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
package/src/tui/theme.ts CHANGED
@@ -1,432 +1,432 @@
1
- /**
2
- * QwenProxy TUI - Visual Theme, ANSI TrueColor Palette & Box Drawing
3
- * Adheres to Monospace Design TUI Standard v0.2.5 (Catppuccin Mocha / TokyoNight palette)
4
- */
5
-
6
- export const ANSI = {
7
- reset: "\x1b[0m",
8
- bold: "\x1b[1m",
9
- dim: "\x1b[2m",
10
- italic: "\x1b[3m",
11
- underline: "\x1b[4m",
12
- inverse: "\x1b[7m",
13
- clearLine: "\x1b[2K",
14
- cursorHome: "\x1b[H",
15
- hideCursor: "\x1b[?25l",
16
- showCursor: "\x1b[?25h",
17
- enterAltScreen: "\x1b[?1049h",
18
- exitAltScreen: "\x1b[?1049l",
19
- enableMouse: "\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h",
20
- disableMouse: "\x1b[?1006l\x1b[?1005l\x1b[?1004l\x1b[?1003l\x1b[?1002l\x1b[?1000l\x1b[?1015l",
21
- };
22
-
23
- export const theme = {
24
- // Official Qwen Logo & Web Dark Theme (Electric Violet #7B61FF / #615CED)
25
- cyan: (s: string) => `\x1b[38;2;123;97;255m${s}\x1b[39m`, // #7b61ff (Qwen Logo Electric Violet / Primary Highlight)
26
- blue: (s: string) => `\x1b[38;2;97;92;237m${s}\x1b[39m`, // #615ced (Qwen Deep Violet / Brand Theme)
27
- lavender: (s: string) => `\x1b[38;2;178;162;255m${s}\x1b[39m`, // #b2a2ff (Qwen Lilac / Iris Glow)
28
- green: (s: string) => `\x1b[38;2;8;229;166m${s}\x1b[39m`, // #08e5a6 (Qwen Success Mint)
29
- yellow: (s: string) => `\x1b[38;2;242;178;45m${s}\x1b[39m`, // #f2b22d (Qwen Caution Gold)
30
- peach: (s: string) => `\x1b[38;2;247;142;75m${s}\x1b[39m`, // #f78e4b (Qwen Warning Orange)
31
-
32
- red: (s: string) => `\x1b[38;2;252;109;109m${s}\x1b[39m`, // #fc6d6d (Qwen Danger Red)
33
- white: (s: string) => `\x1b[38;2;247;248;252m${s}\x1b[39m`, // #f7f8fc (Qwen Character Primary Text)
34
- gray: (s: string) => `\x1b[38;2;220;221;229m${s}\x1b[39m`, // #dcdde5 (Qwen Character Secondary Text)
35
- muted: (s: string) => `\x1b[38;2;121;123;137m${s}\x1b[39m`, // #797b89 (Qwen Character Quaternary Text)
36
- dark: (s: string) => `\x1b[38;2;53;53;61m${s}\x1b[39m`, // #35353d (Qwen Line Primary Border)
37
- borderActive: (s: string) => `\x1b[38;2;123;97;255m${s}\x1b[39m`, // #7b61ff (Qwen Logo Electric Violet Border)
38
- borderInactive: (s: string) => `\x1b[38;2;53;53;61m${s}\x1b[39m`, // #35353d (Qwen Line Primary Border)
39
- bgSelected: (s: string) => `\x1b[48;2;45;35;85m\x1b[38;2;247;248;252m${s}\x1b[49m\x1b[39m`, // #2d2355 Deep Violet + #f7f8fc White
40
- bgHover: (s: string) => `\x1b[48;2;58;46;110m\x1b[38;2;247;248;252m${s}\x1b[49m\x1b[39m`, // #3a2e6e Violet Hover + #f7f8fc White
41
- bold: (s: string) => `\x1b[1m${s}\x1b[22m`,
42
- italic: (s: string) => `\x1b[3m${s}\x1b[23m`,
43
- dim: (s: string) => `\x1b[2m${s}\x1b[22m`,
44
- underline: (s: string) => `\x1b[4m${s}\x1b[24m`,
45
- inverse: (s: string) => `\x1b[7m${s}\x1b[27m`,
46
- };
47
-
48
- import { execSync, spawnSync } from "node:child_process";
49
-
50
- /**
51
- * Safely writes text to the system clipboard on Windows/macOS/Linux.
52
- * Also emits OSC 52 to copy inside terminal emulators supporting it.
53
- */
54
- export function setClipboardText(text: string): boolean {
55
- try {
56
- // 1. Emit OSC 52 sequence for terminal emulators supporting it natively (only when interactive TTY)
57
- try {
58
- if (process.stdout.isTTY && !process.env.NODE_TEST_CONTEXT) {
59
- const b64 = Buffer.from(text, "utf-8").toString("base64");
60
- process.stdout.write(`\x1b]52;c;${b64}\x07`);
61
- }
62
- } catch {}
63
-
64
- // 2. OS-level clipboard utility
65
- if (process.platform === "win32") {
66
- const p = spawnSync("clip.exe", {
67
- input: text,
68
- encoding: "utf-8",
69
- windowsHide: true,
70
- });
71
- return p.status === 0;
72
- } else if (process.platform === "darwin") {
73
- const p = spawnSync("pbcopy", { input: text, encoding: "utf-8" });
74
- return p.status === 0;
75
- } else {
76
- let p = spawnSync("wl-copy", { input: text, encoding: "utf-8" });
77
- if (p.status !== 0) {
78
- p = spawnSync("xclip", ["-selection", "clipboard"], { input: text, encoding: "utf-8" });
79
- }
80
- return p.status === 0;
81
- }
82
- } catch {
83
- return false;
84
- }
85
- }
86
-
87
- /**
88
- * Safely reads the system clipboard text on Windows/macOS/Linux without throwing.
89
- */
90
- export function getClipboardText(): string {
91
- try {
92
- if (process.platform === "win32") {
93
- return execSync("powershell -NoProfile -Command Get-Clipboard", {
94
- timeout: 1000,
95
- windowsHide: true,
96
- stdio: ["pipe", "pipe", "ignore"],
97
- })
98
- .toString()
99
- .replace(/\r?\n/g, "")
100
- .trim();
101
- }
102
- } catch {}
103
- return "";
104
- }
105
-
106
- export const glyphs = {
107
- bullet: "●",
108
- circle: "○",
109
- pointer: "▸",
110
- arrowRight: "→",
111
- check: "✓",
112
- cross: "✕",
113
- warn: "⚠",
114
- reload: "↻",
115
- zap: "⚡",
116
- plus: "+",
117
- remove: "×",
118
- scissor: "✂",
119
- backspace: "⌫",
120
- broom: "🧹",
121
- enter: "↵",
122
- ellipsis: "…",
123
- blockFull: "█",
124
- blockDark: "▓",
125
- blockMed: "▒",
126
- blockLight: "░",
127
- radioOn: "(●)",
128
- radioOff: "( )",
129
- checkOn: "[x]",
130
- checkOff: "[ ]",
131
- };
132
-
133
- export const boxChars = {
134
- rounded: {
135
- tl: "╭",
136
- tr: "╮",
137
- bl: "╰",
138
- br: "╯",
139
- h: "─",
140
- v: "│",
141
- vl: "├",
142
- vr: "┤",
143
- hu: "┴",
144
- hd: "┬",
145
- cross: "┼",
146
- },
147
- single: {
148
- tl: "┌",
149
- tr: "┐",
150
- bl: "└",
151
- br: "┘",
152
- h: "─",
153
- v: "│",
154
- vl: "├",
155
- vr: "┤",
156
- hu: "┴",
157
- hd: "┬",
158
- cross: "┼",
159
- },
160
- double: {
161
- tl: "╔",
162
- tr: "╗",
163
- bl: "╚",
164
- br: "╝",
165
- h: "═",
166
- v: "║",
167
- vl: "╠",
168
- vr: "╣",
169
- hu: "╩",
170
- hd: "╦",
171
- cross: "╬",
172
- },
173
- };
174
-
175
- const ANSI_REGEX =
176
- /\x1b(?:\[[0-9;?]*[a-zA-Z]|\][^\x1b\x07]*(?:\x1b\\|\x07)|\([a-zA-Z])/g;
177
-
178
- /**
179
- * Strips all ANSI and OSC escape codes (including OSC 8 hyperlinks) for accurate measurement.
180
- */
181
- export function stripAnsi(str: string): string {
182
- return str.replace(ANSI_REGEX, "");
183
- }
184
-
185
- /**
186
- * Computes visual display width of string, accounting for wide characters and emojis.
187
- */
188
- export function stringWidth(str: string): number {
189
- const clean = stripAnsi(str).replace(/\t/g, " ").replace(/\r/g, "");
190
- let width = 0;
191
- for (const char of clean) {
192
- const code = char.codePointAt(0) || 0;
193
- // Zero-width characters (variation selectors, zero-width space/joiner)
194
- if ((code >= 0xfe00 && code <= 0xfe0f) || (code >= 0x200b && code <= 0x200d)) {
195
- continue;
196
- }
197
- // Specific BMP emojis and symbols that occupy 2 visual terminal cells (e.g. ⚠️, ⚡, ✅, ❌, ✨, ☕)
198
- const isBmpEmoji =
199
- code === 0x26a0 || // ⚠️ (WARNING SIGN)
200
- code === 0x2705 || // ✅
201
- code === 0x2728 || // ✨
202
- code === 0x274c || // ❌
203
- code === 0x274e || // ❎
204
- code === 0x2753 || // ❓
205
- code === 0x2757 || // ❗
206
- code === 0x2b50 || // ⭐
207
- code === 0x2b55 || // ⭕
208
- code === 0x26a1 || // ⚡
209
- code === 0x2615 || // ☕
210
- code === 0x231a || // ⌚
211
- code === 0x231b || // ⌛
212
- code === 0x23f0 || // ⏰
213
- code === 0x23f3; // ⏳
214
- // Common emoji and CJK full-width ranges (SMP Emojis 0x1f300 - 0x1faff)
215
- if (
216
- isBmpEmoji ||
217
- (code >= 0x1100 && code <= 0x115f) ||
218
- (code >= 0x2e80 && code <= 0xa4cf && code !== 0x303f) ||
219
- (code >= 0xac00 && code <= 0xd7a3) ||
220
- (code >= 0xf900 && code <= 0xfaff) ||
221
- (code >= 0xfe10 && code <= 0xfe19) ||
222
- (code >= 0xfe30 && code <= 0xfe6f) ||
223
- (code >= 0xff01 && code <= 0xff60) ||
224
- (code >= 0xffe0 && code <= 0xffe6) ||
225
- (code >= 0x1f300 && code <= 0x1faff)
226
- ) {
227
- width += 2;
228
- } else {
229
- width += 1;
230
- }
231
- }
232
- return width;
233
- }
234
-
235
- /**
236
- * Truncates string to specified visual width with optional ellipsis.
237
- */
238
- export function truncate(str: string, maxWidth: number, ellipsis = "…"): string {
239
- if (maxWidth <= 0) return "";
240
- const clean = stripAnsi(str).replace(/\t/g, " ").replace(/\r/g, "");
241
- if (stringWidth(clean) <= maxWidth) return str;
242
-
243
- const ellipsisW = stringWidth(ellipsis);
244
- const targetW = Math.max(0, maxWidth - ellipsisW);
245
-
246
- let currentW = 0;
247
- let cutIndex = 0;
248
- for (const char of clean) {
249
- const charW = stringWidth(char);
250
- if (currentW + charW > targetW) break;
251
- currentW += charW;
252
- cutIndex += char.length;
253
- }
254
-
255
- return clean.slice(0, cutIndex) + ellipsis;
256
- }
257
-
258
- /**
259
- * Pads string to target visual width with alignment.
260
- */
261
- export function pad(
262
- str: string,
263
- width: number,
264
- align: "left" | "right" | "center" = "left",
265
- ): string {
266
- const visualW = stringWidth(str);
267
- if (visualW >= width) return str;
268
-
269
- const diff = width - visualW;
270
- if (align === "right") {
271
- return " ".repeat(diff) + str;
272
- }
273
- if (align === "center") {
274
- const left = Math.floor(diff / 2);
275
- const right = diff - left;
276
- return " ".repeat(left) + str + " ".repeat(right);
277
- }
278
- return str + " ".repeat(diff);
279
- }
280
-
281
- /**
282
- * Word-wraps a content line to fit within maxWidth, preserving leading indentation.
283
- */
284
- export function wrapContentLine(line: string, maxWidth: number): string[] {
285
- if (stringWidth(line) <= maxWidth) return [line];
286
-
287
- const clean = stripAnsi(line);
288
- if (stringWidth(clean) <= maxWidth) return [line];
289
-
290
- // Preserve leading ANSI styling prefix (e.g. colors, dim) and reset on each wrapped line
291
- const ansiMatch = line.match(/^(\x1b\[[0-9;]*m)+/);
292
- const ansiPrefix = ansiMatch ? ansiMatch[0] : "";
293
- const ansiSuffix = ansiPrefix ? "\x1b[0m" : "";
294
-
295
- // Preserve leading indentation from clean text
296
- const indentMatch = clean.match(/^(\s+)/);
297
- const indent = indentMatch ? indentMatch[1] : " ";
298
-
299
- const words = clean.trim().split(/\s+/);
300
- const wrapped: string[] = [];
301
- let current = "";
302
-
303
- for (const word of words) {
304
- const test = current.length > 0 ? `${current} ${word}` : `${indent}${word}`;
305
- if (stringWidth(test) <= maxWidth) {
306
- current = test;
307
- } else {
308
- if (current.length > 0) {
309
- wrapped.push(ansiPrefix ? `${ansiPrefix}${current}${ansiSuffix}` : current);
310
- }
311
- current = `${indent}${word}`;
312
- }
313
- }
314
-
315
- if (current.length > 0) {
316
- wrapped.push(ansiPrefix ? `${ansiPrefix}${current}${ansiSuffix}` : current);
317
- }
318
-
319
- return wrapped.length > 0 ? wrapped : [line];
320
- }
321
-
322
- export interface BoxOptions {
323
- title?: string;
324
- footer?: string;
325
- width: number;
326
- height?: number;
327
- borderStyle?: "rounded" | "single" | "double";
328
- borderColor?: (s: string) => string;
329
- titleColor?: (s: string) => string;
330
- footerColor?: (s: string) => string;
331
- content: string[];
332
- }
333
-
334
- /**
335
- * Draws a beautiful bordered box with optional header, footer, and height constraint.
336
- */
337
- export function drawBox(options: BoxOptions): string[] {
338
- const {
339
- title,
340
- footer,
341
- width,
342
- height,
343
- borderStyle = "rounded",
344
- borderColor = theme.borderInactive,
345
- titleColor = theme.cyan,
346
- footerColor = theme.muted,
347
- content,
348
- } = options;
349
-
350
- const b = boxChars[borderStyle];
351
- const innerW = Math.max(1, width - 2);
352
- const lines: string[] = [];
353
-
354
- // Top border
355
- let topHeader = "";
356
- if (title) {
357
- const hasAnsi = title.includes("\x1b[");
358
- const rawTitle = ` ${title} `;
359
- const cleanTitle = ` ${stripAnsi(title)} `;
360
- const titleW = stringWidth(cleanTitle);
361
- if (titleW < innerW - 2) {
362
- const remainingH = innerW - titleW - 1;
363
- topHeader =
364
- borderColor(b.h) +
365
- (hasAnsi ? rawTitle : titleColor(cleanTitle)) +
366
- borderColor(b.h.repeat(Math.max(0, remainingH)));
367
- } else if (innerW > 6) {
368
- const truncated = ` ${truncate(stripAnsi(title), innerW - 4)} `;
369
- const remainingH = Math.max(0, innerW - stringWidth(truncated) - 1);
370
- topHeader =
371
- borderColor(b.h) +
372
- titleColor(truncated) +
373
- borderColor(b.h.repeat(remainingH));
374
- } else {
375
- topHeader = borderColor(b.h.repeat(innerW));
376
- }
377
- } else {
378
- topHeader = borderColor(b.h.repeat(innerW));
379
- }
380
- lines.push(borderColor(b.tl) + topHeader + borderColor(b.tr));
381
-
382
- // Flatten and auto-wrap content lines so words are never cut off with ellipsis,
383
- // and strictly prevent any embedded \n or \r from leaking into a terminal row!
384
- const expandedContent: string[] = [];
385
- for (const item of content) {
386
- const subItems = String(item ?? "").split(/\r?\n/);
387
- for (const sub of subItems) {
388
- if (stringWidth(sub) <= innerW) {
389
- expandedContent.push(sub);
390
- } else {
391
- expandedContent.push(...wrapContentLine(sub, innerW));
392
- }
393
- }
394
- }
395
- // Content rows
396
- const maxContentRows = height ? Math.max(0, height - 2) : expandedContent.length;
397
- for (let i = 0; i < maxContentRows; i++) {
398
- const rawLine = i < expandedContent.length ? expandedContent[i] : "";
399
- const truncated = truncate(rawLine, innerW);
400
- const padded = pad(truncated, innerW);
401
- lines.push(borderColor(b.v) + padded + borderColor(b.v));
402
- }
403
-
404
- // Bottom border
405
- let bottomFooter = "";
406
- if (footer) {
407
- const hasAnsi = footer.includes("\x1b[");
408
- const rawFooter = ` ${footer} `;
409
- const cleanFooter = ` ${stripAnsi(footer)} `;
410
- const footerW = stringWidth(cleanFooter);
411
- if (footerW < innerW - 2) {
412
- const remainingH = innerW - footerW - 1;
413
- bottomFooter =
414
- borderColor(b.h) +
415
- (hasAnsi ? rawFooter : footerColor(cleanFooter)) +
416
- borderColor(b.h.repeat(Math.max(0, remainingH)));
417
- } else if (innerW > 6) {
418
- const truncated = ` ${truncate(stripAnsi(footer), innerW - 4)} `;
419
- const remainingH = Math.max(0, innerW - stringWidth(truncated) - 1);
420
- bottomFooter =
421
- borderColor(b.h) +
422
- footerColor(truncated) +
423
- borderColor(b.h.repeat(remainingH));
424
- } else {
425
- bottomFooter = borderColor(b.h.repeat(innerW));
426
- }
427
- } else {
428
- bottomFooter = borderColor(b.h.repeat(innerW));
429
- }
430
- lines.push(borderColor(b.bl) + bottomFooter + borderColor(b.br));
431
- return lines;
432
- }
1
+ /**
2
+ * QwenProxy TUI - Visual Theme, ANSI TrueColor Palette & Box Drawing
3
+ * Adheres to Monospace Design TUI Standard v0.2.5 (Catppuccin Mocha / TokyoNight palette)
4
+ */
5
+
6
+ export const ANSI = {
7
+ reset: "\x1b[0m",
8
+ bold: "\x1b[1m",
9
+ dim: "\x1b[2m",
10
+ italic: "\x1b[3m",
11
+ underline: "\x1b[4m",
12
+ inverse: "\x1b[7m",
13
+ clearLine: "\x1b[2K",
14
+ cursorHome: "\x1b[H",
15
+ hideCursor: "\x1b[?25l",
16
+ showCursor: "\x1b[?25h",
17
+ enterAltScreen: "\x1b[?1049h",
18
+ exitAltScreen: "\x1b[?1049l",
19
+ enableMouse: "\x1b[?1000h\x1b[?1002h\x1b[?1006h",
20
+ disableMouse: "\x1b[?1006l\x1b[?1005l\x1b[?1004l\x1b[?1003l\x1b[?1002l\x1b[?1000l\x1b[?1015l",
21
+ };
22
+
23
+ export const theme = {
24
+ // Official Qwen Logo & Web Dark Theme (Electric Violet #7B61FF / #615CED)
25
+ cyan: (s: string) => `\x1b[38;2;123;97;255m${s}\x1b[39m`, // #7b61ff (Qwen Logo Electric Violet / Primary Highlight)
26
+ blue: (s: string) => `\x1b[38;2;97;92;237m${s}\x1b[39m`, // #615ced (Qwen Deep Violet / Brand Theme)
27
+ lavender: (s: string) => `\x1b[38;2;178;162;255m${s}\x1b[39m`, // #b2a2ff (Qwen Lilac / Iris Glow)
28
+ green: (s: string) => `\x1b[38;2;8;229;166m${s}\x1b[39m`, // #08e5a6 (Qwen Success Mint)
29
+ yellow: (s: string) => `\x1b[38;2;242;178;45m${s}\x1b[39m`, // #f2b22d (Qwen Caution Gold)
30
+ peach: (s: string) => `\x1b[38;2;247;142;75m${s}\x1b[39m`, // #f78e4b (Qwen Warning Orange)
31
+
32
+ red: (s: string) => `\x1b[38;2;252;109;109m${s}\x1b[39m`, // #fc6d6d (Qwen Danger Red)
33
+ white: (s: string) => `\x1b[38;2;247;248;252m${s}\x1b[39m`, // #f7f8fc (Qwen Character Primary Text)
34
+ gray: (s: string) => `\x1b[38;2;220;221;229m${s}\x1b[39m`, // #dcdde5 (Qwen Character Secondary Text)
35
+ muted: (s: string) => `\x1b[38;2;121;123;137m${s}\x1b[39m`, // #797b89 (Qwen Character Quaternary Text)
36
+ dark: (s: string) => `\x1b[38;2;53;53;61m${s}\x1b[39m`, // #35353d (Qwen Line Primary Border)
37
+ borderActive: (s: string) => `\x1b[38;2;123;97;255m${s}\x1b[39m`, // #7b61ff (Qwen Logo Electric Violet Border)
38
+ borderInactive: (s: string) => `\x1b[38;2;53;53;61m${s}\x1b[39m`, // #35353d (Qwen Line Primary Border)
39
+ bgSelected: (s: string) => `\x1b[48;2;45;35;85m\x1b[38;2;247;248;252m${s}\x1b[49m\x1b[39m`, // #2d2355 Deep Violet + #f7f8fc White
40
+ bgHover: (s: string) => `\x1b[48;2;58;46;110m\x1b[38;2;247;248;252m${s}\x1b[49m\x1b[39m`, // #3a2e6e Violet Hover + #f7f8fc White
41
+ bold: (s: string) => `\x1b[1m${s}\x1b[22m`,
42
+ italic: (s: string) => `\x1b[3m${s}\x1b[23m`,
43
+ dim: (s: string) => `\x1b[2m${s}\x1b[22m`,
44
+ underline: (s: string) => `\x1b[4m${s}\x1b[24m`,
45
+ inverse: (s: string) => `\x1b[7m${s}\x1b[27m`,
46
+ };
47
+
48
+ import { execSync, spawnSync } from "node:child_process";
49
+
50
+ /**
51
+ * Safely writes text to the system clipboard on Windows/macOS/Linux.
52
+ * Also emits OSC 52 to copy inside terminal emulators supporting it.
53
+ */
54
+ export function setClipboardText(text: string): boolean {
55
+ try {
56
+ // 1. Emit OSC 52 sequence for terminal emulators supporting it natively (only when interactive TTY)
57
+ try {
58
+ if (process.stdout.isTTY && !process.env.NODE_TEST_CONTEXT) {
59
+ const b64 = Buffer.from(text, "utf-8").toString("base64");
60
+ process.stdout.write(`\x1b]52;c;${b64}\x07`);
61
+ }
62
+ } catch {}
63
+
64
+ // 2. OS-level clipboard utility
65
+ if (process.platform === "win32") {
66
+ const p = spawnSync("clip.exe", {
67
+ input: text,
68
+ encoding: "utf-8",
69
+ windowsHide: true,
70
+ });
71
+ return p.status === 0;
72
+ } else if (process.platform === "darwin") {
73
+ const p = spawnSync("pbcopy", { input: text, encoding: "utf-8" });
74
+ return p.status === 0;
75
+ } else {
76
+ let p = spawnSync("wl-copy", { input: text, encoding: "utf-8" });
77
+ if (p.status !== 0) {
78
+ p = spawnSync("xclip", ["-selection", "clipboard"], { input: text, encoding: "utf-8" });
79
+ }
80
+ return p.status === 0;
81
+ }
82
+ } catch {
83
+ return false;
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Safely reads the system clipboard text on Windows/macOS/Linux without throwing.
89
+ */
90
+ export function getClipboardText(): string {
91
+ try {
92
+ if (process.platform === "win32") {
93
+ return execSync("powershell -NoProfile -Command Get-Clipboard", {
94
+ timeout: 1000,
95
+ windowsHide: true,
96
+ stdio: ["pipe", "pipe", "ignore"],
97
+ })
98
+ .toString()
99
+ .replace(/\r?\n/g, "")
100
+ .trim();
101
+ }
102
+ } catch {}
103
+ return "";
104
+ }
105
+
106
+ export const glyphs = {
107
+ bullet: "●",
108
+ circle: "○",
109
+ pointer: "▸",
110
+ arrowRight: "→",
111
+ check: "✓",
112
+ cross: "✕",
113
+ warn: "⚠",
114
+ reload: "↻",
115
+ zap: "⚡",
116
+ plus: "+",
117
+ remove: "×",
118
+ scissor: "✂",
119
+ backspace: "⌫",
120
+ broom: "🧹",
121
+ enter: "↵",
122
+ ellipsis: "…",
123
+ blockFull: "█",
124
+ blockDark: "▓",
125
+ blockMed: "▒",
126
+ blockLight: "░",
127
+ radioOn: "(●)",
128
+ radioOff: "( )",
129
+ checkOn: "[x]",
130
+ checkOff: "[ ]",
131
+ };
132
+
133
+ export const boxChars = {
134
+ rounded: {
135
+ tl: "╭",
136
+ tr: "╮",
137
+ bl: "╰",
138
+ br: "╯",
139
+ h: "─",
140
+ v: "│",
141
+ vl: "├",
142
+ vr: "┤",
143
+ hu: "┴",
144
+ hd: "┬",
145
+ cross: "┼",
146
+ },
147
+ single: {
148
+ tl: "┌",
149
+ tr: "┐",
150
+ bl: "└",
151
+ br: "┘",
152
+ h: "─",
153
+ v: "│",
154
+ vl: "├",
155
+ vr: "┤",
156
+ hu: "┴",
157
+ hd: "┬",
158
+ cross: "┼",
159
+ },
160
+ double: {
161
+ tl: "╔",
162
+ tr: "╗",
163
+ bl: "╚",
164
+ br: "╝",
165
+ h: "═",
166
+ v: "║",
167
+ vl: "╠",
168
+ vr: "╣",
169
+ hu: "╩",
170
+ hd: "╦",
171
+ cross: "╬",
172
+ },
173
+ };
174
+
175
+ const ANSI_REGEX =
176
+ /\x1b(?:\[[0-9;?]*[a-zA-Z]|\][^\x1b\x07]*(?:\x1b\\|\x07)|\([a-zA-Z])/g;
177
+
178
+ /**
179
+ * Strips all ANSI and OSC escape codes (including OSC 8 hyperlinks) for accurate measurement.
180
+ */
181
+ export function stripAnsi(str: string): string {
182
+ return str.replace(ANSI_REGEX, "");
183
+ }
184
+
185
+ /**
186
+ * Computes visual display width of string, accounting for wide characters and emojis.
187
+ */
188
+ export function stringWidth(str: string): number {
189
+ const clean = stripAnsi(str).replace(/\t/g, " ").replace(/\r/g, "");
190
+ let width = 0;
191
+ for (const char of clean) {
192
+ const code = char.codePointAt(0) || 0;
193
+ // Zero-width characters (variation selectors, zero-width space/joiner)
194
+ if ((code >= 0xfe00 && code <= 0xfe0f) || (code >= 0x200b && code <= 0x200d)) {
195
+ continue;
196
+ }
197
+ // Specific BMP emojis and symbols that occupy 2 visual terminal cells (e.g. ⚠️, ⚡, ✅, ❌, ✨, ☕)
198
+ const isBmpEmoji =
199
+ code === 0x26a0 || // ⚠️ (WARNING SIGN)
200
+ code === 0x2705 || // ✅
201
+ code === 0x2728 || // ✨
202
+ code === 0x274c || // ❌
203
+ code === 0x274e || // ❎
204
+ code === 0x2753 || // ❓
205
+ code === 0x2757 || // ❗
206
+ code === 0x2b50 || // ⭐
207
+ code === 0x2b55 || // ⭕
208
+ code === 0x26a1 || // ⚡
209
+ code === 0x2615 || // ☕
210
+ code === 0x231a || // ⌚
211
+ code === 0x231b || // ⌛
212
+ code === 0x23f0 || // ⏰
213
+ code === 0x23f3; // ⏳
214
+ // Common emoji and CJK full-width ranges (SMP Emojis 0x1f300 - 0x1faff)
215
+ if (
216
+ isBmpEmoji ||
217
+ (code >= 0x1100 && code <= 0x115f) ||
218
+ (code >= 0x2e80 && code <= 0xa4cf && code !== 0x303f) ||
219
+ (code >= 0xac00 && code <= 0xd7a3) ||
220
+ (code >= 0xf900 && code <= 0xfaff) ||
221
+ (code >= 0xfe10 && code <= 0xfe19) ||
222
+ (code >= 0xfe30 && code <= 0xfe6f) ||
223
+ (code >= 0xff01 && code <= 0xff60) ||
224
+ (code >= 0xffe0 && code <= 0xffe6) ||
225
+ (code >= 0x1f300 && code <= 0x1faff)
226
+ ) {
227
+ width += 2;
228
+ } else {
229
+ width += 1;
230
+ }
231
+ }
232
+ return width;
233
+ }
234
+
235
+ /**
236
+ * Truncates string to specified visual width with optional ellipsis.
237
+ */
238
+ export function truncate(str: string, maxWidth: number, ellipsis = "…"): string {
239
+ if (maxWidth <= 0) return "";
240
+ const clean = stripAnsi(str).replace(/\t/g, " ").replace(/\r/g, "");
241
+ if (stringWidth(clean) <= maxWidth) return str;
242
+
243
+ const ellipsisW = stringWidth(ellipsis);
244
+ const targetW = Math.max(0, maxWidth - ellipsisW);
245
+
246
+ let currentW = 0;
247
+ let cutIndex = 0;
248
+ for (const char of clean) {
249
+ const charW = stringWidth(char);
250
+ if (currentW + charW > targetW) break;
251
+ currentW += charW;
252
+ cutIndex += char.length;
253
+ }
254
+
255
+ return clean.slice(0, cutIndex) + ellipsis;
256
+ }
257
+
258
+ /**
259
+ * Pads string to target visual width with alignment.
260
+ */
261
+ export function pad(
262
+ str: string,
263
+ width: number,
264
+ align: "left" | "right" | "center" = "left",
265
+ ): string {
266
+ const visualW = stringWidth(str);
267
+ if (visualW >= width) return str;
268
+
269
+ const diff = width - visualW;
270
+ if (align === "right") {
271
+ return " ".repeat(diff) + str;
272
+ }
273
+ if (align === "center") {
274
+ const left = Math.floor(diff / 2);
275
+ const right = diff - left;
276
+ return " ".repeat(left) + str + " ".repeat(right);
277
+ }
278
+ return str + " ".repeat(diff);
279
+ }
280
+
281
+ /**
282
+ * Word-wraps a content line to fit within maxWidth, preserving leading indentation.
283
+ */
284
+ export function wrapContentLine(line: string, maxWidth: number): string[] {
285
+ if (stringWidth(line) <= maxWidth) return [line];
286
+
287
+ const clean = stripAnsi(line);
288
+ if (stringWidth(clean) <= maxWidth) return [line];
289
+
290
+ // Preserve leading ANSI styling prefix (e.g. colors, dim) and reset on each wrapped line
291
+ const ansiMatch = line.match(/^(\x1b\[[0-9;]*m)+/);
292
+ const ansiPrefix = ansiMatch ? ansiMatch[0] : "";
293
+ const ansiSuffix = ansiPrefix ? "\x1b[0m" : "";
294
+
295
+ // Preserve leading indentation from clean text
296
+ const indentMatch = clean.match(/^(\s+)/);
297
+ const indent = indentMatch ? indentMatch[1] : " ";
298
+
299
+ const words = clean.trim().split(/\s+/);
300
+ const wrapped: string[] = [];
301
+ let current = "";
302
+
303
+ for (const word of words) {
304
+ const test = current.length > 0 ? `${current} ${word}` : `${indent}${word}`;
305
+ if (stringWidth(test) <= maxWidth) {
306
+ current = test;
307
+ } else {
308
+ if (current.length > 0) {
309
+ wrapped.push(ansiPrefix ? `${ansiPrefix}${current}${ansiSuffix}` : current);
310
+ }
311
+ current = `${indent}${word}`;
312
+ }
313
+ }
314
+
315
+ if (current.length > 0) {
316
+ wrapped.push(ansiPrefix ? `${ansiPrefix}${current}${ansiSuffix}` : current);
317
+ }
318
+
319
+ return wrapped.length > 0 ? wrapped : [line];
320
+ }
321
+
322
+ export interface BoxOptions {
323
+ title?: string;
324
+ footer?: string;
325
+ width: number;
326
+ height?: number;
327
+ borderStyle?: "rounded" | "single" | "double";
328
+ borderColor?: (s: string) => string;
329
+ titleColor?: (s: string) => string;
330
+ footerColor?: (s: string) => string;
331
+ content: string[];
332
+ }
333
+
334
+ /**
335
+ * Draws a beautiful bordered box with optional header, footer, and height constraint.
336
+ */
337
+ export function drawBox(options: BoxOptions): string[] {
338
+ const {
339
+ title,
340
+ footer,
341
+ width,
342
+ height,
343
+ borderStyle = "rounded",
344
+ borderColor = theme.borderInactive,
345
+ titleColor = theme.cyan,
346
+ footerColor = theme.muted,
347
+ content,
348
+ } = options;
349
+
350
+ const b = boxChars[borderStyle];
351
+ const innerW = Math.max(1, width - 2);
352
+ const lines: string[] = [];
353
+
354
+ // Top border
355
+ let topHeader = "";
356
+ if (title) {
357
+ const hasAnsi = title.includes("\x1b[");
358
+ const rawTitle = ` ${title} `;
359
+ const cleanTitle = ` ${stripAnsi(title)} `;
360
+ const titleW = stringWidth(cleanTitle);
361
+ if (titleW < innerW - 2) {
362
+ const remainingH = innerW - titleW - 1;
363
+ topHeader =
364
+ borderColor(b.h) +
365
+ (hasAnsi ? rawTitle : titleColor(cleanTitle)) +
366
+ borderColor(b.h.repeat(Math.max(0, remainingH)));
367
+ } else if (innerW > 6) {
368
+ const truncated = ` ${truncate(stripAnsi(title), innerW - 4)} `;
369
+ const remainingH = Math.max(0, innerW - stringWidth(truncated) - 1);
370
+ topHeader =
371
+ borderColor(b.h) +
372
+ titleColor(truncated) +
373
+ borderColor(b.h.repeat(remainingH));
374
+ } else {
375
+ topHeader = borderColor(b.h.repeat(innerW));
376
+ }
377
+ } else {
378
+ topHeader = borderColor(b.h.repeat(innerW));
379
+ }
380
+ lines.push(borderColor(b.tl) + topHeader + borderColor(b.tr));
381
+
382
+ // Flatten and auto-wrap content lines so words are never cut off with ellipsis,
383
+ // and strictly prevent any embedded \n or \r from leaking into a terminal row!
384
+ const expandedContent: string[] = [];
385
+ for (const item of content) {
386
+ const subItems = String(item ?? "").split(/\r?\n/);
387
+ for (const sub of subItems) {
388
+ if (stringWidth(sub) <= innerW) {
389
+ expandedContent.push(sub);
390
+ } else {
391
+ expandedContent.push(...wrapContentLine(sub, innerW));
392
+ }
393
+ }
394
+ }
395
+ // Content rows
396
+ const maxContentRows = height ? Math.max(0, height - 2) : expandedContent.length;
397
+ for (let i = 0; i < maxContentRows; i++) {
398
+ const rawLine = i < expandedContent.length ? expandedContent[i] : "";
399
+ const truncated = truncate(rawLine, innerW);
400
+ const padded = pad(truncated, innerW);
401
+ lines.push(borderColor(b.v) + padded + borderColor(b.v));
402
+ }
403
+
404
+ // Bottom border
405
+ let bottomFooter = "";
406
+ if (footer) {
407
+ const hasAnsi = footer.includes("\x1b[");
408
+ const rawFooter = ` ${footer} `;
409
+ const cleanFooter = ` ${stripAnsi(footer)} `;
410
+ const footerW = stringWidth(cleanFooter);
411
+ if (footerW < innerW - 2) {
412
+ const remainingH = innerW - footerW - 1;
413
+ bottomFooter =
414
+ borderColor(b.h) +
415
+ (hasAnsi ? rawFooter : footerColor(cleanFooter)) +
416
+ borderColor(b.h.repeat(Math.max(0, remainingH)));
417
+ } else if (innerW > 6) {
418
+ const truncated = ` ${truncate(stripAnsi(footer), innerW - 4)} `;
419
+ const remainingH = Math.max(0, innerW - stringWidth(truncated) - 1);
420
+ bottomFooter =
421
+ borderColor(b.h) +
422
+ footerColor(truncated) +
423
+ borderColor(b.h.repeat(remainingH));
424
+ } else {
425
+ bottomFooter = borderColor(b.h.repeat(innerW));
426
+ }
427
+ } else {
428
+ bottomFooter = borderColor(b.h.repeat(innerW));
429
+ }
430
+ lines.push(borderColor(b.bl) + bottomFooter + borderColor(b.br));
431
+ return lines;
432
+ }