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.
- package/LICENSE +14 -0
- package/README.md +907 -0
- package/bin/qwenproxy.js +141 -0
- package/package.json +78 -0
- package/src/api/error-classifier.ts +159 -0
- package/src/api/error-helpers.ts +118 -0
- package/src/api/models.ts +261 -0
- package/src/api/server.ts +859 -0
- package/src/cache/memory-cache.ts +385 -0
- package/src/clean-cache.ts +204 -0
- package/src/core/account-concurrency.ts +671 -0
- package/src/core/account-manager.ts +297 -0
- package/src/core/account-priority.ts +163 -0
- package/src/core/accounts.ts +186 -0
- package/src/core/config.ts +383 -0
- package/src/core/crypto-utils.ts +79 -0
- package/src/core/database.ts +276 -0
- package/src/core/errors.ts +118 -0
- package/src/core/logger.ts +269 -0
- package/src/core/memory-usage.ts +84 -0
- package/src/core/metrics.ts +291 -0
- package/src/core/model-alias.ts +77 -0
- package/src/core/model-registry.ts +544 -0
- package/src/core/mutex.ts +119 -0
- package/src/core/paths.ts +199 -0
- package/src/core/prompt-limits.ts +214 -0
- package/src/core/reasoning-effort.ts +102 -0
- package/src/core/stream-registry.ts +96 -0
- package/src/core/waf-isolation.ts +117 -0
- package/src/core/watchdog.ts +195 -0
- package/src/delete-chats.ts +23 -0
- package/src/index.ts +64 -0
- package/src/login.ts +147 -0
- package/src/reset-cooldowns.ts +11 -0
- package/src/routes/anthropic/index.ts +355 -0
- package/src/routes/anthropic/translate.ts +522 -0
- package/src/routes/anthropic/types.ts +154 -0
- package/src/routes/anthropic/validation.ts +144 -0
- package/src/routes/chat/account.ts +1817 -0
- package/src/routes/chat/context.ts +241 -0
- package/src/routes/chat/errors.ts +85 -0
- package/src/routes/chat/helpers.ts +268 -0
- package/src/routes/chat/index.ts +618 -0
- package/src/routes/chat/media.ts +285 -0
- package/src/routes/chat/retry-policy.ts +754 -0
- package/src/routes/chat/stop.ts +98 -0
- package/src/routes/chat/streaming.ts +2710 -0
- package/src/routes/chat/validation.ts +526 -0
- package/src/routes/chat.ts +2 -0
- package/src/routes/completions.ts +290 -0
- package/src/routes/images.ts +139 -0
- package/src/routes/responses/adapter.ts +503 -0
- package/src/routes/responses/index.ts +405 -0
- package/src/routes/responses/state.ts +230 -0
- package/src/routes/responses/streaming.ts +528 -0
- package/src/routes/responses/types.ts +285 -0
- package/src/routes/responses/validation.ts +202 -0
- package/src/routes/upload.ts +731 -0
- package/src/routes/videos.ts +214 -0
- package/src/services/auth-playwright.ts +173 -0
- package/src/services/captcha-coordinator.ts +161 -0
- package/src/services/captcha-solver.ts +553 -0
- package/src/services/chat-cleanup.ts +80 -0
- package/src/services/context-meter.ts +317 -0
- package/src/services/fingerprint.ts +242 -0
- package/src/services/human-behavior.ts +173 -0
- package/src/services/media-generation.ts +1748 -0
- package/src/services/playwright.ts +2800 -0
- package/src/services/qwen-chat-pool.ts +345 -0
- package/src/services/qwen-errors.ts +133 -0
- package/src/services/qwen-headers.ts +79 -0
- package/src/services/qwen-thread-state.ts +393 -0
- package/src/services/qwen-url.ts +19 -0
- package/src/services/qwen.ts +3126 -0
- package/src/services/session-keeper.ts +88 -0
- package/src/services/token-estimation-metrics.ts +118 -0
- package/src/sync/claude-code.ts +75 -0
- package/src/sync/codex.ts +123 -0
- package/src/sync/index.ts +362 -0
- package/src/sync/omp.ts +105 -0
- package/src/sync/opencode.ts +214 -0
- package/src/sync/types.ts +53 -0
- package/src/sync/utils.ts +27 -0
- package/src/sync-clients.ts +189 -0
- package/src/tools/instructions.ts +137 -0
- package/src/tools/manifest.ts +81 -0
- package/src/tools/parser.ts +2989 -0
- package/src/tools/toolcall-tags.ts +142 -0
- package/src/tools/types.ts +53 -0
- package/src/tui/app.ts +264 -0
- package/src/tui/index.ts +61 -0
- package/src/tui/markdown.ts +258 -0
- package/src/tui/proxy-client.ts +326 -0
- package/src/tui/screen.ts +278 -0
- package/src/tui/server-manager.ts +270 -0
- package/src/tui/theme.ts +432 -0
- package/src/tui/types.ts +33 -0
- package/src/tui/views/accounts-view.ts +656 -0
- package/src/tui/views/chat-view.ts +823 -0
- package/src/tui/views/logs-view.ts +413 -0
- package/src/tui/views/status-view.ts +204 -0
- package/src/tui/views/storage-view.ts +291 -0
- package/src/tui/views/sync-view.ts +409 -0
- package/src/types/ali-oss.d.ts +32 -0
- package/src/utils/context-truncation.ts +84 -0
- package/src/utils/json.ts +380 -0
- package/src/utils/session-id.ts +37 -0
- package/src/utils/tool-call-guard.ts +85 -0
- package/src/utils/types.ts +109 -0
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* QwenProxy TUI - Screen Buffer, Resize Listener & Raw Keyboard Engine
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import readline from "node:readline";
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import { ANSI, theme, pad } from "./theme.ts";
|
|
8
|
+
import { ServerManager } from "./server-manager.ts";
|
|
9
|
+
export interface MouseInfo {
|
|
10
|
+
type: "click" | "scroll-up" | "scroll-down" | "hover";
|
|
11
|
+
button?: "left" | "right";
|
|
12
|
+
col: number;
|
|
13
|
+
row: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface KeyEvent {
|
|
17
|
+
name: string;
|
|
18
|
+
ctrl: boolean;
|
|
19
|
+
shift: boolean;
|
|
20
|
+
meta: boolean;
|
|
21
|
+
raw?: string;
|
|
22
|
+
char?: string;
|
|
23
|
+
mouse?: MouseInfo;
|
|
24
|
+
}
|
|
25
|
+
export type KeyHandler = (key: KeyEvent) => void;
|
|
26
|
+
export type ResizeHandler = (cols: number, rows: number) => void;
|
|
27
|
+
export class Screen {
|
|
28
|
+
private active = false;
|
|
29
|
+
private keyListeners: Set<KeyHandler> = new Set();
|
|
30
|
+
private resizeListeners: Set<ResizeHandler> = new Set();
|
|
31
|
+
private keypressHandler: ((ch: string | undefined, key: any) => void) | null = null;
|
|
32
|
+
private resizeHandler: (() => void) | null = null;
|
|
33
|
+
private exitHandler: (() => void) | null = null;
|
|
34
|
+
private prevRenderedRows: string[] = [];
|
|
35
|
+
private originalStdinEmit: typeof process.stdin.emit | null = null;
|
|
36
|
+
|
|
37
|
+
constructor() {
|
|
38
|
+
this.exitHandler = () => this.stop();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
public start(): boolean {
|
|
42
|
+
if (this.active) return true;
|
|
43
|
+
if (!process.stdout.isTTY || !process.stdin.isTTY) {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
this.active = true;
|
|
48
|
+
this.prevRenderedRows = [];
|
|
49
|
+
// Switch to alternate screen buffer, clear screen, hide cursor, and enable mouse tracking
|
|
50
|
+
ServerManager.getInstance().withTuiRendering(() => {
|
|
51
|
+
process.stdout.write(
|
|
52
|
+
ANSI.enterAltScreen + "\x1b[2J" + ANSI.cursorHome + ANSI.hideCursor + ANSI.enableMouse,
|
|
53
|
+
);
|
|
54
|
+
});
|
|
55
|
+
// Setup raw keyboard input
|
|
56
|
+
if (process.stdin.setRawMode) {
|
|
57
|
+
process.stdin.setRawMode(true);
|
|
58
|
+
}
|
|
59
|
+
process.stdin.resume();
|
|
60
|
+
readline.emitKeypressEvents(process.stdin);
|
|
61
|
+
|
|
62
|
+
// Intercept stdin 'data' to capture SGR mouse wheel sequences before readline
|
|
63
|
+
this.originalStdinEmit = process.stdin.emit.bind(process.stdin);
|
|
64
|
+
const self = this;
|
|
65
|
+
process.stdin.emit = function (event: string, ...args: any[]) {
|
|
66
|
+
if (event === "data" && args[0] && self.active) {
|
|
67
|
+
const str = typeof args[0] === "string" ? args[0] : args[0].toString();
|
|
68
|
+
const mouseRegex = /\x1b\[<(\d+);(\d+);(\d+)([mM])/g;
|
|
69
|
+
let match: RegExpExecArray | null;
|
|
70
|
+
let handled = false;
|
|
71
|
+
while ((match = mouseRegex.exec(str)) !== null) {
|
|
72
|
+
handled = true;
|
|
73
|
+
const btn = parseInt(match[1], 10);
|
|
74
|
+
const col = parseInt(match[2], 10);
|
|
75
|
+
const row = parseInt(match[3], 10);
|
|
76
|
+
const isRelease = match[4] === "m";
|
|
77
|
+
|
|
78
|
+
if (btn === 64) {
|
|
79
|
+
self.dispatchKey({
|
|
80
|
+
name: "wheelup",
|
|
81
|
+
ctrl: false,
|
|
82
|
+
shift: false,
|
|
83
|
+
meta: false,
|
|
84
|
+
mouse: { type: "scroll-up", col, row },
|
|
85
|
+
});
|
|
86
|
+
} else if (btn === 65) {
|
|
87
|
+
self.dispatchKey({
|
|
88
|
+
name: "wheeldown",
|
|
89
|
+
ctrl: false,
|
|
90
|
+
shift: false,
|
|
91
|
+
meta: false,
|
|
92
|
+
mouse: { type: "scroll-down", col, row },
|
|
93
|
+
});
|
|
94
|
+
} else if (btn === 0 && !isRelease) {
|
|
95
|
+
self.dispatchKey({
|
|
96
|
+
name: "click",
|
|
97
|
+
ctrl: false,
|
|
98
|
+
shift: false,
|
|
99
|
+
meta: false,
|
|
100
|
+
mouse: { type: "click", button: "left", col, row },
|
|
101
|
+
});
|
|
102
|
+
} else if (btn === 35) {
|
|
103
|
+
self.dispatchKey({
|
|
104
|
+
name: "hover",
|
|
105
|
+
ctrl: false,
|
|
106
|
+
shift: false,
|
|
107
|
+
meta: false,
|
|
108
|
+
mouse: { type: "hover", col, row },
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (handled) {
|
|
113
|
+
return true;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return self.originalStdinEmit!.apply(process.stdin, [event, ...args] as any);
|
|
117
|
+
} as any;
|
|
118
|
+
|
|
119
|
+
this.keypressHandler = (_ch: string | undefined, key: any) => {
|
|
120
|
+
if (!this.active || !key) return;
|
|
121
|
+
|
|
122
|
+
let name = key.name || "";
|
|
123
|
+
let shift = Boolean(key.shift);
|
|
124
|
+
if (key.sequence === "\x1b[Z") {
|
|
125
|
+
name = "tab";
|
|
126
|
+
shift = true;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Suppress control characters from event.char
|
|
130
|
+
const isControlChar =
|
|
131
|
+
_ch && (_ch === "\t" || _ch === "\r" || _ch === "\n" || _ch < " ");
|
|
132
|
+
const char = isControlChar ? undefined : _ch;
|
|
133
|
+
|
|
134
|
+
const event: KeyEvent = {
|
|
135
|
+
name,
|
|
136
|
+
ctrl: Boolean(key.ctrl),
|
|
137
|
+
shift,
|
|
138
|
+
meta: Boolean(key.meta),
|
|
139
|
+
raw: key.sequence,
|
|
140
|
+
char,
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
// Direct Ctrl+C fallback to exit cleanly
|
|
144
|
+
this.dispatchKey(event);
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
this.resizeHandler = () => {
|
|
148
|
+
if (!this.active) return;
|
|
149
|
+
const { cols, rows } = this.getSize();
|
|
150
|
+
for (const listener of this.resizeListeners) {
|
|
151
|
+
listener(cols, rows);
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
process.stdin.on("keypress", this.keypressHandler);
|
|
156
|
+
process.stdout.on("resize", this.resizeHandler);
|
|
157
|
+
process.on("SIGINT", this.exitHandler!);
|
|
158
|
+
process.on("SIGTERM", this.exitHandler!);
|
|
159
|
+
process.on("SIGBREAK", this.exitHandler!);
|
|
160
|
+
process.on("exit", this.exitHandler!);
|
|
161
|
+
return true;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
private dispatchKey(event: KeyEvent): void {
|
|
165
|
+
if (!this.active) return;
|
|
166
|
+
for (const listener of this.keyListeners) {
|
|
167
|
+
listener(event);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
public stop(): void {
|
|
172
|
+
if (!this.active) return;
|
|
173
|
+
this.active = false;
|
|
174
|
+
|
|
175
|
+
if (this.keypressHandler) {
|
|
176
|
+
process.stdin.removeListener("keypress", this.keypressHandler);
|
|
177
|
+
this.keypressHandler = null;
|
|
178
|
+
}
|
|
179
|
+
if (this.resizeHandler) {
|
|
180
|
+
process.stdout.removeListener("resize", this.resizeHandler);
|
|
181
|
+
this.resizeHandler = null;
|
|
182
|
+
}
|
|
183
|
+
if (this.exitHandler) {
|
|
184
|
+
process.removeListener("SIGINT", this.exitHandler);
|
|
185
|
+
process.removeListener("SIGTERM", this.exitHandler);
|
|
186
|
+
process.removeListener("SIGBREAK", this.exitHandler);
|
|
187
|
+
process.removeListener("exit", this.exitHandler);
|
|
188
|
+
this.exitHandler = null;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
if (process.stdin.setRawMode) {
|
|
192
|
+
process.stdin.setRawMode(false);
|
|
193
|
+
}
|
|
194
|
+
process.stdin.pause();
|
|
195
|
+
if (this.originalStdinEmit) {
|
|
196
|
+
process.stdin.emit = this.originalStdinEmit;
|
|
197
|
+
this.originalStdinEmit = null;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// Restore original screen buffer, cursor, and disable all mouse tracking modes synchronously
|
|
201
|
+
const restoreSeq = ANSI.disableMouse + ANSI.exitAltScreen + ANSI.showCursor + ANSI.reset;
|
|
202
|
+
try {
|
|
203
|
+
fs.writeSync(1, restoreSeq);
|
|
204
|
+
} catch {
|
|
205
|
+
try {
|
|
206
|
+
ServerManager.getInstance().withTuiRendering(() => {
|
|
207
|
+
process.stdout.write(restoreSeq);
|
|
208
|
+
});
|
|
209
|
+
} catch {}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
public onKey(handler: KeyHandler): () => void {
|
|
214
|
+
this.keyListeners.add(handler);
|
|
215
|
+
return () => this.keyListeners.delete(handler);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
public onResize(handler: ResizeHandler): () => void {
|
|
219
|
+
this.prevRenderedRows = [];
|
|
220
|
+
this.resizeListeners.add(handler);
|
|
221
|
+
return () => this.resizeListeners.delete(handler);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
public getSize(): { cols: number; rows: number } {
|
|
225
|
+
return {
|
|
226
|
+
cols: process.stdout.columns || 100,
|
|
227
|
+
rows: process.stdout.rows || 30,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Renders the frame atomically with zero flicker.
|
|
233
|
+
*/
|
|
234
|
+
public render(lines: string[]): void {
|
|
235
|
+
if (!this.active) return;
|
|
236
|
+
const { cols, rows } = this.getSize();
|
|
237
|
+
|
|
238
|
+
if (cols < 70 || rows < 18) {
|
|
239
|
+
// Terminal size warning
|
|
240
|
+
const warnLines = [
|
|
241
|
+
"",
|
|
242
|
+
theme.yellow(" ⚠️ Terminal muito pequeno para a interface QwenProxy."),
|
|
243
|
+
theme.muted(` Tamanho atual: ${cols}x${rows} | Mínimo recomendado: 80x24`),
|
|
244
|
+
theme.cyan(" Por favor, expanda a janela do seu terminal."),
|
|
245
|
+
"",
|
|
246
|
+
theme.muted(" Pressione Ctrl+C duas vezes para sair."),
|
|
247
|
+
];
|
|
248
|
+
process.stdout.write(ANSI.cursorHome + warnLines.join("\n") + "\n");
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
const currentRows: string[] = [];
|
|
252
|
+
for (let r = 0; r < rows; r++) {
|
|
253
|
+
const rawLine = r < lines.length ? lines[r] : "";
|
|
254
|
+
currentRows.push(pad(rawLine, cols));
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
let diffBuffer = "";
|
|
258
|
+
let changed = 0;
|
|
259
|
+
const isFirstRender = this.prevRenderedRows.length !== rows;
|
|
260
|
+
|
|
261
|
+
for (let r = 0; r < rows; r++) {
|
|
262
|
+
if (isFirstRender || this.prevRenderedRows[r] !== currentRows[r]) {
|
|
263
|
+
diffBuffer += `\x1b[${r + 1};1H${currentRows[r]}`;
|
|
264
|
+
changed++;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
if (changed === 0) {
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
this.prevRenderedRows = currentRows;
|
|
273
|
+
|
|
274
|
+
ServerManager.getInstance().withTuiRendering(() => {
|
|
275
|
+
process.stdout.write(ANSI.hideCursor + diffBuffer + ANSI.cursorHome);
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
}
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* QwenProxy TUI - In-Process Server Manager ("Tudo Junto Uma Coisa Só")
|
|
3
|
+
* Starts and manages the Hono + Playwright proxy server directly within the TUI process.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { config } from "../core/config.ts";
|
|
7
|
+
import { startServer, stopServer } from "../api/server.ts";
|
|
8
|
+
import { stripAnsi } from "./theme.ts";
|
|
9
|
+
export type ServerLifecycleState = "offline" | "warming" | "online" | "error";
|
|
10
|
+
|
|
11
|
+
export interface ServerLogEntry {
|
|
12
|
+
time: string;
|
|
13
|
+
level: "INFO" | "WARN" | "ERROR";
|
|
14
|
+
message: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export class ServerManager {
|
|
18
|
+
private static instance: ServerManager | null = null;
|
|
19
|
+
|
|
20
|
+
private state: ServerLifecycleState = "offline";
|
|
21
|
+
private lastError: string | null = null;
|
|
22
|
+
private logEntries: ServerLogEntry[] = [];
|
|
23
|
+
private logBuffer: string[] = [];
|
|
24
|
+
private originalLog = console.log;
|
|
25
|
+
private originalInfo = console.info;
|
|
26
|
+
private originalDebug = console.debug;
|
|
27
|
+
private originalWarn = console.warn;
|
|
28
|
+
private originalError = console.error;
|
|
29
|
+
private originalStdoutWrite = process.stdout.write.bind(process.stdout);
|
|
30
|
+
private originalStderrWrite = process.stderr.write.bind(process.stderr);
|
|
31
|
+
private intercepted = false;
|
|
32
|
+
private isTuiRendering = false;
|
|
33
|
+
private startPromise: Promise<void> | null = null;
|
|
34
|
+
|
|
35
|
+
public static getInstance(): ServerManager {
|
|
36
|
+
if (!ServerManager.instance) {
|
|
37
|
+
ServerManager.instance = new ServerManager();
|
|
38
|
+
}
|
|
39
|
+
return ServerManager.instance;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
public getState(): ServerLifecycleState {
|
|
43
|
+
return this.state;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
public withTuiRendering<T>(fn: () => T): T {
|
|
47
|
+
this.isTuiRendering = true;
|
|
48
|
+
try {
|
|
49
|
+
return fn();
|
|
50
|
+
} finally {
|
|
51
|
+
this.isTuiRendering = false;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
public getRawStdoutWrite(): (chunk: string | Uint8Array) => boolean {
|
|
56
|
+
return this.originalStdoutWrite;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
public getLastError(): string | null {
|
|
60
|
+
return this.lastError;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
public getRecentLogs(max = 12): string[] {
|
|
64
|
+
return this.logBuffer.slice(-max);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
public getLogEntries(filter: "all" | "warn" | "error" = "all"): ServerLogEntry[] {
|
|
68
|
+
if (filter === "error") {
|
|
69
|
+
return this.logEntries.filter((e) => e.level === "ERROR");
|
|
70
|
+
}
|
|
71
|
+
if (filter === "warn") {
|
|
72
|
+
return this.logEntries.filter((e) => e.level === "WARN" || e.level === "ERROR");
|
|
73
|
+
}
|
|
74
|
+
return this.logEntries;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
public clearLogs(): void {
|
|
78
|
+
this.logEntries = [];
|
|
79
|
+
this.logBuffer = [];
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
private appendLog(level: "INFO" | "WARN" | "ERROR", text: string): void {
|
|
83
|
+
if (!text) return;
|
|
84
|
+
const clean = stripAnsi(text).trim();
|
|
85
|
+
if (!clean || clean.length === 0) return;
|
|
86
|
+
|
|
87
|
+
const time = new Date().toLocaleTimeString("pt-BR", {
|
|
88
|
+
hour: "2-digit",
|
|
89
|
+
minute: "2-digit",
|
|
90
|
+
second: "2-digit",
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
const lines = clean.split(/\r?\n/);
|
|
94
|
+
for (const raw of lines) {
|
|
95
|
+
let line = raw.trim();
|
|
96
|
+
if (!line) continue;
|
|
97
|
+
|
|
98
|
+
// Filter out raw ASCII box frames (like +-----+ or empty row | |)
|
|
99
|
+
if (/^[+\-=#]{5,}$/.test(line)) continue;
|
|
100
|
+
if (/^\|\s*\|$/.test(line)) continue;
|
|
101
|
+
|
|
102
|
+
// If line is an ASCII box row like "| Endpoint http://... |", extract the text
|
|
103
|
+
if (line.startsWith("|") && line.endsWith("|")) {
|
|
104
|
+
line = line.slice(1, -1).trim();
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (!line) continue;
|
|
108
|
+
|
|
109
|
+
// Prevent identical consecutive duplicate logs in the same second
|
|
110
|
+
const last = this.logEntries[this.logEntries.length - 1];
|
|
111
|
+
if (last && last.time === time && last.level === level && last.message === line) {
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
this.logEntries.push({ time, level, message: line });
|
|
116
|
+
if (this.logEntries.length > 500) {
|
|
117
|
+
this.logEntries.shift();
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const levelTag = level === "ERROR" ? "[ERR]" : level === "WARN" ? "[WARN]" : "";
|
|
121
|
+
const formatted = `[${time}] ${levelTag ? levelTag + " " : ""}${line}`;
|
|
122
|
+
this.logBuffer.push(formatted);
|
|
123
|
+
if (this.logBuffer.length > 500) {
|
|
124
|
+
this.logBuffer.shift();
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
public interceptLogs(): void {
|
|
130
|
+
if (this.intercepted) return;
|
|
131
|
+
this.intercepted = true;
|
|
132
|
+
|
|
133
|
+
console.log = (...args: any[]) => {
|
|
134
|
+
this.appendLog(
|
|
135
|
+
"INFO",
|
|
136
|
+
args.map((a) => (typeof a === "string" ? a : JSON.stringify(a))).join(" "),
|
|
137
|
+
);
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
console.info = (...args: any[]) => {
|
|
141
|
+
this.appendLog(
|
|
142
|
+
"INFO",
|
|
143
|
+
args.map((a) => (typeof a === "string" ? a : JSON.stringify(a))).join(" "),
|
|
144
|
+
);
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
console.debug = (...args: any[]) => {
|
|
148
|
+
this.appendLog(
|
|
149
|
+
"INFO",
|
|
150
|
+
args.map((a) => (typeof a === "string" ? a : JSON.stringify(a))).join(" "),
|
|
151
|
+
);
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
console.warn = (...args: any[]) => {
|
|
155
|
+
this.appendLog(
|
|
156
|
+
"WARN",
|
|
157
|
+
args.map((a) => (typeof a === "string" ? a : JSON.stringify(a))).join(" "),
|
|
158
|
+
);
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
console.error = (...args: any[]) => {
|
|
162
|
+
this.appendLog(
|
|
163
|
+
"ERROR",
|
|
164
|
+
args.map((a) => (typeof a === "string" ? a : JSON.stringify(a))).join(" "),
|
|
165
|
+
);
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
// Sandbox direct process.stdout.write calls (Playwright, Hono, etc.)
|
|
169
|
+
process.stdout.write = ((chunk: any, encoding?: any, cb?: any) => {
|
|
170
|
+
if (this.isTuiRendering) {
|
|
171
|
+
return this.originalStdoutWrite(chunk, encoding, cb);
|
|
172
|
+
}
|
|
173
|
+
const str = typeof chunk === "string" ? chunk : chunk?.toString(encoding);
|
|
174
|
+
// Terminal escape sequences (OSC 52 clipboard, cursor codes) bypass log capture
|
|
175
|
+
if (typeof str === "string" && (str.startsWith("\x1b]") || str.startsWith("\x1b[") || str.startsWith("\x1b"))) {
|
|
176
|
+
return this.originalStdoutWrite(chunk, encoding, cb);
|
|
177
|
+
}
|
|
178
|
+
this.appendLog("INFO", str);
|
|
179
|
+
if (typeof cb === "function") cb();
|
|
180
|
+
return true;
|
|
181
|
+
}) as any;
|
|
182
|
+
|
|
183
|
+
// Sandbox direct process.stderr.write calls
|
|
184
|
+
process.stderr.write = ((chunk: any, encoding?: any, cb?: any) => {
|
|
185
|
+
const str = typeof chunk === "string" ? chunk : chunk?.toString(encoding);
|
|
186
|
+
this.appendLog("ERROR", str);
|
|
187
|
+
if (typeof cb === "function") cb();
|
|
188
|
+
return true;
|
|
189
|
+
}) as any;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
public restoreLogs(): void {
|
|
193
|
+
if (!this.intercepted) return;
|
|
194
|
+
console.log = this.originalLog;
|
|
195
|
+
console.info = this.originalInfo;
|
|
196
|
+
console.debug = this.originalDebug;
|
|
197
|
+
console.warn = this.originalWarn;
|
|
198
|
+
console.error = this.originalError;
|
|
199
|
+
process.stdout.write = this.originalStdoutWrite;
|
|
200
|
+
process.stderr.write = this.originalStderrWrite;
|
|
201
|
+
this.intercepted = false;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Checks if proxy is already running on port 7936, or boots it up in-process.
|
|
206
|
+
*/
|
|
207
|
+
public async ensureStarted(): Promise<void> {
|
|
208
|
+
if (this.state === "online") return;
|
|
209
|
+
if (this.startPromise) return this.startPromise;
|
|
210
|
+
|
|
211
|
+
const port = config.server?.port || 7936;
|
|
212
|
+
const host = config.server?.host || "127.0.0.1";
|
|
213
|
+
const cleanHost = host === "0.0.0.0" ? "127.0.0.1" : host;
|
|
214
|
+
|
|
215
|
+
// 1. Probe if already online
|
|
216
|
+
try {
|
|
217
|
+
const controller = new AbortController();
|
|
218
|
+
const timeout = setTimeout(() => controller.abort(), 600);
|
|
219
|
+
const resp = await fetch(`http://${cleanHost}:${port}/health`, {
|
|
220
|
+
signal: controller.signal,
|
|
221
|
+
});
|
|
222
|
+
clearTimeout(timeout);
|
|
223
|
+
if (resp.ok) {
|
|
224
|
+
this.state = "online";
|
|
225
|
+
this.appendLog(
|
|
226
|
+
"INFO",
|
|
227
|
+
`QwenProxy já está em execução na porta ${port}. Conectado com sucesso!`,
|
|
228
|
+
);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
} catch {}
|
|
232
|
+
|
|
233
|
+
// 2. Start in-process
|
|
234
|
+
this.state = "warming";
|
|
235
|
+
this.appendLog(
|
|
236
|
+
"INFO",
|
|
237
|
+
`Iniciando servidor QwenProxy na porta ${port} e aquecendo Playwright...`,
|
|
238
|
+
);
|
|
239
|
+
|
|
240
|
+
this.interceptLogs();
|
|
241
|
+
|
|
242
|
+
this.startPromise = (async () => {
|
|
243
|
+
try {
|
|
244
|
+
await startServer({ installSignalHandlers: false });
|
|
245
|
+
this.state = "online";
|
|
246
|
+
this.appendLog(
|
|
247
|
+
"INFO",
|
|
248
|
+
`✓ Servidor QwenProxy pronto e online em http://${cleanHost}:${port}/v1`,
|
|
249
|
+
);
|
|
250
|
+
} catch (err: any) {
|
|
251
|
+
this.state = "error";
|
|
252
|
+
this.lastError = err?.message || String(err);
|
|
253
|
+
this.appendLog(
|
|
254
|
+
"ERROR",
|
|
255
|
+
`✗ Falha ao iniciar servidor: ${this.lastError}`,
|
|
256
|
+
);
|
|
257
|
+
} finally {
|
|
258
|
+
this.startPromise = null;
|
|
259
|
+
}
|
|
260
|
+
})();
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
public async stop(): Promise<void> {
|
|
264
|
+
this.restoreLogs();
|
|
265
|
+
try {
|
|
266
|
+
await stopServer();
|
|
267
|
+
this.state = "offline";
|
|
268
|
+
} catch {}
|
|
269
|
+
}
|
|
270
|
+
}
|