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,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Central tool-call marker module.
|
|
3
|
+
*
|
|
4
|
+
* The Qwen upstream filters/corrupts the conventional `<tool_call>` token in
|
|
5
|
+
* the SSE stream. We deliberately use a private tag (`<qpx_call>`) that does
|
|
6
|
+
* NOT contain the `tool_call` substring, so the provider passes it through
|
|
7
|
+
* untouched. Every place that *emits* (prompt instructions, history replay) or
|
|
8
|
+
* *parses* (response parser) tool calls reads from this module — the two sides
|
|
9
|
+
* can never drift apart.
|
|
10
|
+
*
|
|
11
|
+
* Override with QWEN_TOOL_OPEN / QWEN_TOOL_CLOSE env vars if needed (e.g. to
|
|
12
|
+
* dodge a future provider filter that learns this tag).
|
|
13
|
+
*
|
|
14
|
+
* The parser still accepts the legacy `<tool_call>` token from model output
|
|
15
|
+
* for backward compatibility (in-flight sessions, models fine-tuned on it).
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
const DEFAULT_OPEN = "<qpx_call>";
|
|
19
|
+
const DEFAULT_CLOSE = "</qpx_call>";
|
|
20
|
+
|
|
21
|
+
export const TOOL_CALL_OPEN: string =
|
|
22
|
+
(process.env.QWEN_TOOL_OPEN || DEFAULT_OPEN).trim() || DEFAULT_OPEN;
|
|
23
|
+
export const TOOL_CALL_CLOSE: string =
|
|
24
|
+
(process.env.QWEN_TOOL_CLOSE || DEFAULT_CLOSE).trim() || DEFAULT_CLOSE;
|
|
25
|
+
|
|
26
|
+
function tagName(tag: string): string {
|
|
27
|
+
return tag
|
|
28
|
+
.replace(/^<\/?/, "")
|
|
29
|
+
.replace(/>$/, "")
|
|
30
|
+
.trim();
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** All accepted open tag names (custom + legacy). */
|
|
34
|
+
export function getOpenNames(): string[] {
|
|
35
|
+
return Array.from(new Set([tagName(TOOL_CALL_OPEN), "tool_call", "tool_calls"]));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** All accepted close tag names (custom + legacy). */
|
|
39
|
+
export function getCloseNames(): string[] {
|
|
40
|
+
return Array.from(new Set([tagName(TOOL_CALL_CLOSE), "tool_call", "tool_calls", "tool"]));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Wrap a JSON payload in the canonical open/close tags. */
|
|
44
|
+
export function wrapToolCallPayload(json: string): string {
|
|
45
|
+
return `${TOOL_CALL_OPEN}\n${json}\n${TOOL_CALL_CLOSE}`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function matchesAt(buffer: string, i: number, value: string): boolean {
|
|
49
|
+
if (i + value.length > buffer.length) return false;
|
|
50
|
+
for (let j = 0; j < value.length; j++) {
|
|
51
|
+
const c = buffer.charCodeAt(i + j);
|
|
52
|
+
const t = value.charCodeAt(j);
|
|
53
|
+
if (c !== t && (c | 0x20) !== (t | 0x20)) return false;
|
|
54
|
+
}
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Find the first open tag in `buffer` (any accepted name, case-insensitive).
|
|
60
|
+
* Returns position/length/tag string or null.
|
|
61
|
+
*/
|
|
62
|
+
export function findToolOpen(
|
|
63
|
+
buffer: string,
|
|
64
|
+
): { index: number; length: number; tag: string } | null {
|
|
65
|
+
let best: { index: number; length: number; tag: string } | null = null;
|
|
66
|
+
for (const name of getOpenNames()) {
|
|
67
|
+
const re = new RegExp(`<${name}\\b[^>]*>`, "i");
|
|
68
|
+
const m = buffer.match(re);
|
|
69
|
+
if (m && m.index !== undefined) {
|
|
70
|
+
if (!best || m.index < best.index) {
|
|
71
|
+
best = { index: m.index, length: m[0].length, tag: m[0] };
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return best;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* At buffer position `i`, is there a whitespace-tolerant close tag?
|
|
80
|
+
* Accepts `</qpx_call>`, `</tool_call >` (space before `>`), `</tool>`, etc.
|
|
81
|
+
* Returns the total length consumed, or null.
|
|
82
|
+
*/
|
|
83
|
+
export function matchToolCloseAt(buffer: string, i: number): number | null {
|
|
84
|
+
for (const name of getCloseNames()) {
|
|
85
|
+
const prefix = `</${name}`;
|
|
86
|
+
if (!matchesAt(buffer, i, prefix)) continue;
|
|
87
|
+
let j = i + prefix.length;
|
|
88
|
+
// Allow optional whitespace before closing `>`
|
|
89
|
+
while (j < buffer.length && /\s/.test(buffer[j])) j++;
|
|
90
|
+
if (buffer[j] === ">") return j + 1 - i;
|
|
91
|
+
}
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Bare name of an open tag actually seen in the stream (e.g. 'qpx_call'). */
|
|
96
|
+
export function openTagName(openTag: string): string {
|
|
97
|
+
const m = openTag.match(/^<\/?([a-zA-Z_][\w-]*)/);
|
|
98
|
+
return m ? m[1] : tagName(TOOL_CALL_OPEN);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Matching close tag string for an open tag actually seen in the stream. */
|
|
102
|
+
export function closeTagFor(openTag: string): string {
|
|
103
|
+
return `</${openTagName(openTag)}>`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* True when `text` contains the start of any accepted open tag.
|
|
108
|
+
* Used in stream-handler to detect tool-call signals in a chunk.
|
|
109
|
+
*/
|
|
110
|
+
export function textContainsToolCallStart(text: string): boolean {
|
|
111
|
+
const lower = text.toLowerCase();
|
|
112
|
+
for (const name of getOpenNames()) {
|
|
113
|
+
if (lower.includes(`<${name.toLowerCase()}`)) return true;
|
|
114
|
+
}
|
|
115
|
+
return false;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Strip leading stray close tags (`</qpx_call>`, `</tool_call>`, `</tool>`)
|
|
120
|
+
* that the provider sometimes injects before real content.
|
|
121
|
+
*/
|
|
122
|
+
export function stripLeadingStrayCloses(s: string): string {
|
|
123
|
+
const re = /^\s*<\/(?:qpx_call|tool_call|tool_calls|tool)\s*>/i;
|
|
124
|
+
let m: RegExpExecArray | null;
|
|
125
|
+
while ((m = re.exec(s))) s = s.substring(m[0].length);
|
|
126
|
+
return s;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Strip trailing stray close tags that leak after the real payload.
|
|
131
|
+
*/
|
|
132
|
+
export function stripTrailingStrayCloses(s: string): string {
|
|
133
|
+
const re = /<\/(?:qpx_call|tool_call|tool_calls|tool)\s*>\s*$/i;
|
|
134
|
+
let m: RegExpExecArray | null;
|
|
135
|
+
while ((m = re.exec(s))) s = s.substring(0, s.length - m[0].length);
|
|
136
|
+
return s;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Strip both leading and trailing stray close tags. */
|
|
140
|
+
export function sanitizeStrayCloses(s: string): string {
|
|
141
|
+
return stripTrailingStrayCloses(stripLeadingStrayCloses(s));
|
|
142
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JSON Schema definition following the OpenAI function calling spec.
|
|
3
|
+
*/
|
|
4
|
+
export interface JsonSchema {
|
|
5
|
+
type: string;
|
|
6
|
+
properties?: Record<string, JsonSchema>;
|
|
7
|
+
items?: JsonSchema;
|
|
8
|
+
required?: string[];
|
|
9
|
+
enum?: unknown[];
|
|
10
|
+
const?: unknown;
|
|
11
|
+
default?: unknown;
|
|
12
|
+
description?: string;
|
|
13
|
+
additionalProperties?: boolean | JsonSchema;
|
|
14
|
+
anyOf?: JsonSchema[];
|
|
15
|
+
oneOf?: JsonSchema[];
|
|
16
|
+
allOf?: JsonSchema[];
|
|
17
|
+
not?: JsonSchema;
|
|
18
|
+
if?: JsonSchema;
|
|
19
|
+
then?: JsonSchema;
|
|
20
|
+
else?: JsonSchema;
|
|
21
|
+
minimum?: number;
|
|
22
|
+
maximum?: number;
|
|
23
|
+
minLength?: number;
|
|
24
|
+
maxLength?: number;
|
|
25
|
+
pattern?: string;
|
|
26
|
+
format?: string;
|
|
27
|
+
minItems?: number;
|
|
28
|
+
maxItems?: number;
|
|
29
|
+
uniqueItems?: boolean;
|
|
30
|
+
nullable?: boolean;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* OpenAI-compatible function tool definition.
|
|
35
|
+
*/
|
|
36
|
+
export interface FunctionToolDefinition {
|
|
37
|
+
type: "function";
|
|
38
|
+
function: {
|
|
39
|
+
name: string;
|
|
40
|
+
description?: string;
|
|
41
|
+
parameters?: JsonSchema;
|
|
42
|
+
strict?: boolean;
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* A parsed tool call from the LLM response.
|
|
48
|
+
*/
|
|
49
|
+
export interface ParsedToolCall {
|
|
50
|
+
id: string;
|
|
51
|
+
name: string;
|
|
52
|
+
arguments: Record<string, unknown>;
|
|
53
|
+
}
|
package/src/tui/app.ts
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* QwenProxy TUI - Main Application Controller & Navigation Coordinator
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { Screen, type KeyEvent } from "./screen.ts";
|
|
6
|
+
import type { TuiView, ProxyStatusSnapshot } from "./types.ts";
|
|
7
|
+
import { theme, glyphs, drawBox, stringWidth } from "./theme.ts";
|
|
8
|
+
import { fetchProxyStatus } from "./proxy-client.ts";
|
|
9
|
+
import { ServerManager } from "./server-manager.ts";
|
|
10
|
+
|
|
11
|
+
import { StatusView } from "./views/status-view.ts";
|
|
12
|
+
import { ChatView } from "./views/chat-view.ts";
|
|
13
|
+
import { SyncView } from "./views/sync-view.ts";
|
|
14
|
+
import { StorageView } from "./views/storage-view.ts";
|
|
15
|
+
import { AccountsView } from "./views/accounts-view.ts";
|
|
16
|
+
import { LogsView } from "./views/logs-view.ts";
|
|
17
|
+
export class TuiApp {
|
|
18
|
+
private screen: Screen;
|
|
19
|
+
private views: TuiView[] = [];
|
|
20
|
+
private activeViewIndex = 0;
|
|
21
|
+
private hoveredTabIndex: number | null = null;
|
|
22
|
+
private isRunning = false;
|
|
23
|
+
private lastCtrlCTime = 0;
|
|
24
|
+
private pollInterval: NodeJS.Timeout | null = null;
|
|
25
|
+
private statusSnapshot: ProxyStatusSnapshot | null = null;
|
|
26
|
+
private renderScheduled = false;
|
|
27
|
+
constructor(initialTab = 1) {
|
|
28
|
+
this.screen = new Screen();
|
|
29
|
+
|
|
30
|
+
this.views = [
|
|
31
|
+
new StatusView(),
|
|
32
|
+
new ChatView(() => this.requestRender()),
|
|
33
|
+
new SyncView(),
|
|
34
|
+
new StorageView(),
|
|
35
|
+
new AccountsView(),
|
|
36
|
+
new LogsView(),
|
|
37
|
+
];
|
|
38
|
+
const tabIdx = Math.max(0, Math.min(this.views.length - 1, initialTab - 1));
|
|
39
|
+
this.activeViewIndex = tabIdx;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
private getTabAtCol(col: number): number | null {
|
|
43
|
+
let curCol = 3;
|
|
44
|
+
for (let i = 0; i < this.views.length; i++) {
|
|
45
|
+
const tabLabel = ` [${this.views[i].tabNumber}] ${this.views[i].title} `;
|
|
46
|
+
const width = stringWidth(tabLabel);
|
|
47
|
+
if (col >= curCol && col <= curCol + width) {
|
|
48
|
+
return i;
|
|
49
|
+
}
|
|
50
|
+
curCol += width + 2;
|
|
51
|
+
}
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
public async start(): Promise<void> {
|
|
56
|
+
if (this.isRunning) return;
|
|
57
|
+
// Activate stdio sandbox immediately so zero logs can leak to terminal screen
|
|
58
|
+
ServerManager.getInstance().interceptLogs();
|
|
59
|
+
const ok = this.screen.start();
|
|
60
|
+
if (!ok) {
|
|
61
|
+
console.error(
|
|
62
|
+
"[QwenProxy TUI] A interface interativa requer um terminal TTY interativo.",
|
|
63
|
+
);
|
|
64
|
+
process.exit(1);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
this.isRunning = true;
|
|
68
|
+
|
|
69
|
+
// Listen for key events
|
|
70
|
+
// Listen for key and mouse events with microtask coalescing
|
|
71
|
+
this.screen.onKey(async (key) => {
|
|
72
|
+
await this.handleKey(key);
|
|
73
|
+
this.requestRender();
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
// Listen for terminal resize
|
|
77
|
+
this.screen.onResize(() => {
|
|
78
|
+
this.render();
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
// Start server in-process together with TUI ("tudo junto uma coisa só")
|
|
82
|
+
void ServerManager.getInstance().ensureStarted();
|
|
83
|
+
|
|
84
|
+
// Initial status fetch
|
|
85
|
+
try {
|
|
86
|
+
this.statusSnapshot = await fetchProxyStatus();
|
|
87
|
+
} catch {}
|
|
88
|
+
|
|
89
|
+
// Background polling every 1s for live status updates and model catalog synchronization
|
|
90
|
+
this.pollInterval = setInterval(async () => {
|
|
91
|
+
if (!this.isRunning) return;
|
|
92
|
+
try {
|
|
93
|
+
this.statusSnapshot = await fetchProxyStatus();
|
|
94
|
+
// If the active view has a model refresher, keep it synchronized
|
|
95
|
+
const activeView = this.views[this.activeViewIndex];
|
|
96
|
+
if ("refreshModels" in activeView && typeof (activeView as any).refreshModels === "function") {
|
|
97
|
+
void (activeView as any).refreshModels();
|
|
98
|
+
}
|
|
99
|
+
this.requestRender();
|
|
100
|
+
} catch {}
|
|
101
|
+
}, 1000);
|
|
102
|
+
// Initial render
|
|
103
|
+
this.render();
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
public requestRender(): void {
|
|
107
|
+
if (this.renderScheduled || !this.isRunning) return;
|
|
108
|
+
this.renderScheduled = true;
|
|
109
|
+
queueMicrotask(() => {
|
|
110
|
+
this.renderScheduled = false;
|
|
111
|
+
this.render();
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
public async stop(): Promise<void> {
|
|
116
|
+
if (!this.isRunning) return;
|
|
117
|
+
this.isRunning = false;
|
|
118
|
+
clearInterval(this.pollInterval!);
|
|
119
|
+
this.screen.stop();
|
|
120
|
+
await ServerManager.getInstance().stop();
|
|
121
|
+
ServerManager.getInstance().restoreLogs();
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
private async handleKey(key: KeyEvent): Promise<void> {
|
|
125
|
+
const activeView = this.views[this.activeViewIndex];
|
|
126
|
+
|
|
127
|
+
// 1. Global mouse hover & click on Header Tabs (row 2)
|
|
128
|
+
if (key.mouse && key.mouse.row === 2) {
|
|
129
|
+
const tabIdx = this.getTabAtCol(key.mouse.col);
|
|
130
|
+
if (key.name === "hover") {
|
|
131
|
+
if (this.hoveredTabIndex !== tabIdx) {
|
|
132
|
+
this.hoveredTabIndex = tabIdx;
|
|
133
|
+
this.requestRender();
|
|
134
|
+
}
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
if (key.name === "click") {
|
|
138
|
+
if (tabIdx !== null && tabIdx !== this.activeViewIndex && this.views[tabIdx]) {
|
|
139
|
+
if (activeView.onDeactivate) activeView.onDeactivate();
|
|
140
|
+
this.activeViewIndex = tabIdx;
|
|
141
|
+
this.hoveredTabIndex = null;
|
|
142
|
+
const nextView = this.views[this.activeViewIndex];
|
|
143
|
+
if (nextView.onActivate) nextView.onActivate();
|
|
144
|
+
this.requestRender();
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
} else if (this.hoveredTabIndex !== null && key.mouse) {
|
|
149
|
+
this.hoveredTabIndex = null;
|
|
150
|
+
this.requestRender();
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// 2. Double Ctrl+C to exit cleanly (within 1.5 seconds)
|
|
154
|
+
if (key.ctrl && key.name === "c") {
|
|
155
|
+
const now = Date.now();
|
|
156
|
+
if (now - this.lastCtrlCTime < 1500) {
|
|
157
|
+
await this.stop();
|
|
158
|
+
process.exit(0);
|
|
159
|
+
}
|
|
160
|
+
this.lastCtrlCTime = now;
|
|
161
|
+
|
|
162
|
+
// First Ctrl+C: execute normal action in active view (cancel stream, clear input, etc.)
|
|
163
|
+
const handled = await activeView.handleKey(key);
|
|
164
|
+
if (handled) {
|
|
165
|
+
this.requestRender();
|
|
166
|
+
}
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
// Modal check: if a modal dialog is open (in Accounts or Chat), don't cycle tabs with Tab
|
|
170
|
+
const isModalOpen =
|
|
171
|
+
(typeof (activeView as any).isCapturingText === "function" &&
|
|
172
|
+
(activeView as any).isCapturingText()) ||
|
|
173
|
+
(typeof (activeView as any).isModalOpen === "function" &&
|
|
174
|
+
(activeView as any).isModalOpen());
|
|
175
|
+
|
|
176
|
+
// Tab for cycling tabs across views (including from Chat view when no modal is open!)
|
|
177
|
+
if (key.name === "tab" && !isModalOpen) {
|
|
178
|
+
const newIdx = (this.activeViewIndex + 1) % this.views.length;
|
|
179
|
+
if (activeView.onDeactivate) activeView.onDeactivate();
|
|
180
|
+
this.activeViewIndex = newIdx;
|
|
181
|
+
this.hoveredTabIndex = null;
|
|
182
|
+
const nextView = this.views[this.activeViewIndex];
|
|
183
|
+
if (nextView.onActivate) nextView.onActivate();
|
|
184
|
+
this.requestRender();
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
// Direct tab switching with numbers 1..6 only when NOT typing text in an input
|
|
188
|
+
const isTypingText =
|
|
189
|
+
activeView.id === "chat" ||
|
|
190
|
+
(typeof (activeView as any).isCapturingText === "function" &&
|
|
191
|
+
(activeView as any).isCapturingText());
|
|
192
|
+
|
|
193
|
+
if (!isTypingText) {
|
|
194
|
+
if (!key.ctrl && !key.meta && ["1", "2", "3", "4", "5", "6"].includes(key.name)) {
|
|
195
|
+
const newIdx = parseInt(key.name, 10) - 1;
|
|
196
|
+
if (newIdx !== this.activeViewIndex && this.views[newIdx]) {
|
|
197
|
+
if (activeView.onDeactivate) activeView.onDeactivate();
|
|
198
|
+
this.activeViewIndex = newIdx;
|
|
199
|
+
this.hoveredTabIndex = null;
|
|
200
|
+
const nextView = this.views[this.activeViewIndex];
|
|
201
|
+
if (nextView.onActivate) nextView.onActivate();
|
|
202
|
+
this.requestRender();
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
// Pass event to active view and render immediately if handled
|
|
208
|
+
const handled = await activeView.handleKey(key);
|
|
209
|
+
if (handled) {
|
|
210
|
+
this.requestRender();
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
private render(): void {
|
|
214
|
+
if (!this.isRunning) return;
|
|
215
|
+
const { cols, rows } = this.screen.getSize();
|
|
216
|
+
const frame: string[] = [];
|
|
217
|
+
|
|
218
|
+
// 1. Header Deck (Tabs & Title)
|
|
219
|
+
const serverState = ServerManager.getInstance().getState();
|
|
220
|
+
let statusChip: string;
|
|
221
|
+
if (this.statusSnapshot?.online || serverState === "online") {
|
|
222
|
+
statusChip = theme.green(`[ ${glyphs.bullet} Online ]`);
|
|
223
|
+
} else if (serverState === "warming") {
|
|
224
|
+
statusChip = theme.yellow("[ ◐ Iniciando... ]");
|
|
225
|
+
} else if (serverState === "error") {
|
|
226
|
+
statusChip = theme.red("[ ✕ Erro ]");
|
|
227
|
+
} else {
|
|
228
|
+
statusChip = theme.muted(`[ ○ Offline ]`);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const tabsBar = this.views
|
|
232
|
+
.map((v, idx) => {
|
|
233
|
+
const isSelected = idx === this.activeViewIndex;
|
|
234
|
+
const isHovered = idx === this.hoveredTabIndex;
|
|
235
|
+
const tabLabel = `[${v.tabNumber}] ${v.title}`;
|
|
236
|
+
if (isSelected) {
|
|
237
|
+
return theme.bgSelected(` ${tabLabel} `);
|
|
238
|
+
}
|
|
239
|
+
if (isHovered) {
|
|
240
|
+
return theme.bgHover(` ${tabLabel} `);
|
|
241
|
+
}
|
|
242
|
+
return theme.dim(` ${tabLabel} `);
|
|
243
|
+
})
|
|
244
|
+
.join(" ");
|
|
245
|
+
|
|
246
|
+
const headerContent = [` ${tabsBar}`];
|
|
247
|
+
const headerBox = drawBox({
|
|
248
|
+
title: `QwenProxy v1.0.0 ${statusChip}`,
|
|
249
|
+
width: cols,
|
|
250
|
+
height: 3,
|
|
251
|
+
borderColor: theme.borderActive,
|
|
252
|
+
titleColor: theme.cyan,
|
|
253
|
+
content: headerContent,
|
|
254
|
+
});
|
|
255
|
+
frame.push(...headerBox);
|
|
256
|
+
|
|
257
|
+
// 2. Active View Content (occupies all remaining rows below the header deck)
|
|
258
|
+
const activeView = this.views[this.activeViewIndex];
|
|
259
|
+
const availableContentRows = Math.max(8, rows - 3);
|
|
260
|
+
const viewLines = activeView.render(cols, availableContentRows, this.statusSnapshot);
|
|
261
|
+
frame.push(...viewLines);
|
|
262
|
+
this.screen.render(frame);
|
|
263
|
+
}
|
|
264
|
+
}
|
package/src/tui/index.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* QwenProxy TUI - Interactive Terminal Control Interface Entrypoint
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { TuiApp } from "./app.ts";
|
|
7
|
+
|
|
8
|
+
function parseInitialTab(): number {
|
|
9
|
+
const args = process.argv.slice(2);
|
|
10
|
+
const tabArgIdx = args.findIndex((a) => a === "--tab" || a === "-t");
|
|
11
|
+
if (tabArgIdx !== -1 && args[tabArgIdx + 1]) {
|
|
12
|
+
const parsed = parseInt(args[tabArgIdx + 1], 10);
|
|
13
|
+
if (!isNaN(parsed) && parsed >= 1 && parsed <= 6) {
|
|
14
|
+
return parsed;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Positional numeric argument (e.g. `npm run tui 2`)
|
|
19
|
+
const firstNumeric = args.find((a) => /^[1-6]$/.test(a));
|
|
20
|
+
if (firstNumeric) {
|
|
21
|
+
return parseInt(firstNumeric, 10);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
return 1;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function main() {
|
|
28
|
+
if (!process.stdout.isTTY || !process.stdin.isTTY) {
|
|
29
|
+
console.log(
|
|
30
|
+
"\x1b[33m[QwenProxy TUI]\x1b[0m A interface interativa TUI requer uma sessão de terminal interativo.",
|
|
31
|
+
);
|
|
32
|
+
console.log("Execute diretamente no seu terminal: npm run tui");
|
|
33
|
+
process.exit(0);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const initialTab = parseInitialTab();
|
|
37
|
+
const app = new TuiApp(initialTab);
|
|
38
|
+
|
|
39
|
+
process.on("uncaughtException", async (err) => {
|
|
40
|
+
try {
|
|
41
|
+
await app.stop();
|
|
42
|
+
} catch {}
|
|
43
|
+
console.error("[QwenProxy TUI] Erro inesperado:", err);
|
|
44
|
+
process.exit(1);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
process.on("unhandledRejection", async (err) => {
|
|
48
|
+
try {
|
|
49
|
+
await app.stop();
|
|
50
|
+
} catch {}
|
|
51
|
+
console.error("[QwenProxy TUI] Promessa rejeitada:", err);
|
|
52
|
+
process.exit(1);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
await app.start();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
main().catch((err) => {
|
|
59
|
+
console.error("[QwenProxy TUI] Falha ao inicializar:", err);
|
|
60
|
+
process.exit(1);
|
|
61
|
+
});
|