qwenproxy-cli 1.0.0 → 1.0.1

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 (108) hide show
  1. package/LICENSE +14 -14
  2. package/README.md +906 -906
  3. package/bin/qwenproxy.js +5 -1
  4. package/package.json +78 -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 +2800 -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 +264 -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/utils/context-truncation.ts +84 -84
  105. package/src/utils/json.ts +380 -380
  106. package/src/utils/session-id.ts +37 -37
  107. package/src/utils/tool-call-guard.ts +84 -84
  108. package/src/utils/types.ts +109 -109
@@ -1,291 +1,291 @@
1
- import { EventEmitter } from "events";
2
- import { config } from "./config.js";
3
- import { getHeapUsageSnapshot, getRssUsageSnapshot } from "./memory-usage.js";
4
-
5
- interface MetricPoint {
6
- value: number;
7
- timestamp: number;
8
- labels?: Record<string, string>;
9
- }
10
-
11
- type MetricType = "counter" | "gauge" | "histogram" | "summary";
12
-
13
- interface MetricDefinition {
14
- name: string;
15
- type: MetricType;
16
- help: string;
17
- values: Map<string, MetricPoint>;
18
- histogramBuckets?: number[];
19
- }
20
-
21
- export class Metrics extends EventEmitter {
22
- private metrics: Map<string, MetricDefinition> = new Map();
23
- private collectionInterval: NodeJS.Timeout | null = null;
24
-
25
- constructor() {
26
- super();
27
- this.registerDefaults();
28
- }
29
-
30
- private registerDefaults(): void {
31
- const defaults: Array<[string, MetricType, string]> = [
32
- // Core request metrics
33
- ["requests.total", "counter", "Total requests processed"],
34
- ["requests.errors", "counter", "Total request errors"],
35
- ["latency.request", "histogram", "Request latency (ms)"],
36
-
37
- // Stream metrics
38
- ["streams.active", "gauge", "Active SSE streams"],
39
- ["streams.errors", "counter", "Stream errors"],
40
-
41
- // CAPTCHA / anti-bot metrics
42
- ["captcha.challenges.detected", "counter", "Detected CAPTCHA challenges"],
43
- ["captcha.solves.succeeded", "counter", "Successful CAPTCHA solves"],
44
- ["captcha.solves.failed", "counter", "Failed CAPTCHA solves"],
45
- ["captcha.solve.duration", "histogram", "CAPTCHA solve duration (ms)"],
46
-
47
- // Memory metrics
48
- ["memory.heap.used", "gauge", "Heap memory used (bytes)"],
49
- ["memory.heap.total", "gauge", "Heap memory total (bytes)"],
50
- [
51
- "memory.heap.limit",
52
- "gauge",
53
- "V8 heap_size_limit used for RAM pressure (bytes)",
54
- ],
55
- [
56
- "memory.heap.usage_percent",
57
- "gauge",
58
- "Heap used percent vs heap_size_limit",
59
- ],
60
- ["memory.rss", "gauge", "Resident set size (bytes)"],
61
- [
62
- "memory.rss.usage_percent",
63
- "gauge",
64
- "RSS as percent of total system memory (RAM pressure signal)",
65
- ],
66
-
67
- // Cache metrics
68
- ["cache.set", "counter", "Cache set operations"],
69
- ["cache.hit", "counter", "Cache hits"],
70
- ["cache.miss", "counter", "Cache misses"],
71
- ["cache.deleted", "counter", "Cache deletions"],
72
- ["cache.flushed", "counter", "Cache flushes"],
73
- ["cache.value.size", "histogram", "Cache value size (bytes)"],
74
- ["cache.get.latency", "histogram", "Cache get latency (ms)"],
75
- ["cache.hit.ratio", "gauge", "Cache hit ratio (hits / (hits + misses))"],
76
- [
77
- "cache.compression.ratio",
78
- "histogram",
79
- "Compression ratio (original / compressed)",
80
- ],
81
- [
82
- "cache.compression.bytes.saved",
83
- "counter",
84
- "Total bytes saved by compression",
85
- ],
86
- [
87
- "cache.topic.invalidation",
88
- "counter",
89
- "Cache entries invalidated by topic change",
90
- ],
91
- [
92
- "cache.memory.usage.bytes",
93
- "gauge",
94
- "Estimated cache memory usage (bytes)",
95
- ],
96
- ["cache.entries.count", "gauge", "Current number of cache entries"],
97
- [
98
- "topic.change.detected",
99
- "counter",
100
- "Detected conversation topic changes",
101
- ],
102
-
103
- // Watchdog metrics
104
- [
105
- "watchdog.ram.status",
106
- "gauge",
107
- "Watchdog RAM status (0=ok, 1=warning, 2=critical)",
108
- ],
109
- [
110
- "watchdog.overall",
111
- "gauge",
112
- "Watchdog overall status (0=healthy, 1=degraded, 2=unhealthy)",
113
- ],
114
- ["watchdog.recovery.triggered", "counter", "Recovery attempts triggered"],
115
- ["watchdog.recovery.success", "counter", "Successful recoveries"],
116
- ["watchdog.recovery.failed", "counter", "Failed recoveries"],
117
- ];
118
-
119
- for (const [name, type, help] of defaults) {
120
- this.metrics.set(name, {
121
- name,
122
- type,
123
- help,
124
- values: new Map(),
125
- histogramBuckets:
126
- type === "histogram"
127
- ? [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000]
128
- : undefined,
129
- });
130
- }
131
- }
132
-
133
- increment(
134
- name: string,
135
- value: number = 1,
136
- labels?: Record<string, string>,
137
- ): void {
138
- const metric = this.metrics.get(name);
139
- if (!metric || metric.type !== "counter") return;
140
-
141
- const key = labels ? JSON.stringify(labels) : "default";
142
- // Mutate in place to avoid reallocating a MetricPoint on every increment.
143
- const point = metric.values.get(key);
144
- if (point) {
145
- point.value += value;
146
- point.timestamp = Date.now();
147
- } else {
148
- metric.values.set(key, { value, timestamp: Date.now(), labels });
149
- }
150
- }
151
-
152
- gauge(name: string, value: number, labels?: Record<string, string>): void {
153
- const metric = this.metrics.get(name);
154
- if (!metric || metric.type !== "gauge") return;
155
-
156
- const key = labels ? JSON.stringify(labels) : "default";
157
- const point = metric.values.get(key);
158
- if (point) {
159
- point.value = value;
160
- point.timestamp = Date.now();
161
- } else {
162
- metric.values.set(key, { value, timestamp: Date.now(), labels });
163
- }
164
- }
165
-
166
- histogram(
167
- name: string,
168
- value: number,
169
- labels?: Record<string, string>,
170
- ): void {
171
- const metric = this.metrics.get(name);
172
- if (!metric || metric.type !== "histogram") return;
173
-
174
- const key = labels ? JSON.stringify(labels) : "default";
175
- const existing = metric.values.get(key);
176
- // Reuse the stored aggregate object instead of re-wrapping it each call.
177
- let data: { count: number; sum: number; buckets: Map<number, number> };
178
- if (existing && typeof existing.value === "object" && existing.value !== null) {
179
- data = existing.value as { count: number; sum: number; buckets: Map<number, number> };
180
- } else {
181
- data = { count: 0, sum: 0, buckets: new Map<number, number>() };
182
- }
183
-
184
- data.count++;
185
- data.sum += value;
186
- const buckets = metric.histogramBuckets;
187
- if (buckets) {
188
- for (let i = 0; i < buckets.length; i++) {
189
- const bucket = buckets[i];
190
- if (value <= bucket) {
191
- data.buckets.set(bucket, (data.buckets.get(bucket) || 0) + 1);
192
- } else if (!data.buckets.has(bucket)) {
193
- // Keep every bucket present for stable output, but skip redundant writes.
194
- data.buckets.set(bucket, 0);
195
- }
196
- }
197
- }
198
-
199
- if (existing) {
200
- existing.value = data as any;
201
- existing.timestamp = Date.now();
202
- } else {
203
- metric.values.set(key, { value: data as any, timestamp: Date.now(), labels });
204
- }
205
- }
206
-
207
- startCollection(): void {
208
- if (this.collectionInterval) return;
209
-
210
- this.collectionInterval = setInterval(() => {
211
- this.collectSystemMetrics();
212
- }, config.metrics.interval);
213
- }
214
-
215
- private collectSystemMetrics(): void {
216
- const heap = getHeapUsageSnapshot();
217
- const rss = getRssUsageSnapshot();
218
- this.gauge("memory.heap.used", heap.heapUsed);
219
- this.gauge("memory.heap.total", heap.heapTotal);
220
- this.gauge("memory.heap.limit", heap.heapSizeLimit);
221
- this.gauge("memory.heap.usage_percent", heap.usagePercent);
222
- this.gauge("memory.rss", heap.rss);
223
- this.gauge("memory.rss.usage_percent", rss.usagePercent);
224
- }
225
-
226
- get(name: string, labels?: Record<string, string>): MetricPoint | null {
227
- const metric = this.metrics.get(name);
228
- if (!metric) return null;
229
- const key = labels ? JSON.stringify(labels) : "default";
230
- return metric.values.get(key) || null;
231
- }
232
-
233
- formatPrometheus(): string {
234
- let output = "";
235
- for (const metric of this.metrics.values()) {
236
- output += `# HELP ${metric.name} ${metric.help}\n`;
237
- output += `# TYPE ${metric.name} ${metric.type}\n`;
238
-
239
- for (const point of metric.values.values()) {
240
- const labelPairs = point.labels
241
- ? Object.entries(point.labels).map(([k, v]) => `${k}="${v}"`)
242
- : [];
243
- const labelsStr = labelPairs.length ? `{${labelPairs.join(",")}}` : "";
244
-
245
- if (
246
- metric.type === "histogram" &&
247
- typeof point.value === "object" &&
248
- point.value !== null
249
- ) {
250
- // Histogram points store a {count, sum, buckets} aggregate; emitting
251
- // it raw produced "[object Object]" (invalid Prometheus exposition).
252
- const data = point.value as {
253
- count: number;
254
- sum: number;
255
- buckets: Map<number, number>;
256
- };
257
- const bucketPrefix = labelPairs.length
258
- ? `${labelPairs.join(",")},`
259
- : "";
260
- const sortedBuckets = [...data.buckets.keys()].sort((a, b) => a - b);
261
- for (const bucket of sortedBuckets) {
262
- output += `${metric.name}_bucket{${bucketPrefix}le="${bucket}"} ${data.buckets.get(bucket)} ${point.timestamp}\n`;
263
- }
264
- output += `${metric.name}_bucket{${bucketPrefix}le="+Inf"} ${data.count} ${point.timestamp}\n`;
265
- output += `${metric.name}_sum${labelsStr} ${data.sum} ${point.timestamp}\n`;
266
- output += `${metric.name}_count${labelsStr} ${data.count} ${point.timestamp}\n`;
267
- continue;
268
- }
269
-
270
- output += `${metric.name}${labelsStr} ${point.value} ${point.timestamp}\n`;
271
- }
272
- }
273
- return output;
274
- }
275
-
276
- reset(): void {
277
- for (const metric of this.metrics.values()) {
278
- metric.values.clear();
279
- }
280
- this.emit("reset", {});
281
- }
282
-
283
- stopCollection(): void {
284
- if (this.collectionInterval) {
285
- clearInterval(this.collectionInterval);
286
- this.collectionInterval = null;
287
- }
288
- }
289
- }
290
-
291
- export const metrics = new Metrics();
1
+ import { EventEmitter } from "events";
2
+ import { config } from "./config.js";
3
+ import { getHeapUsageSnapshot, getRssUsageSnapshot } from "./memory-usage.js";
4
+
5
+ interface MetricPoint {
6
+ value: number;
7
+ timestamp: number;
8
+ labels?: Record<string, string>;
9
+ }
10
+
11
+ type MetricType = "counter" | "gauge" | "histogram" | "summary";
12
+
13
+ interface MetricDefinition {
14
+ name: string;
15
+ type: MetricType;
16
+ help: string;
17
+ values: Map<string, MetricPoint>;
18
+ histogramBuckets?: number[];
19
+ }
20
+
21
+ export class Metrics extends EventEmitter {
22
+ private metrics: Map<string, MetricDefinition> = new Map();
23
+ private collectionInterval: NodeJS.Timeout | null = null;
24
+
25
+ constructor() {
26
+ super();
27
+ this.registerDefaults();
28
+ }
29
+
30
+ private registerDefaults(): void {
31
+ const defaults: Array<[string, MetricType, string]> = [
32
+ // Core request metrics
33
+ ["requests.total", "counter", "Total requests processed"],
34
+ ["requests.errors", "counter", "Total request errors"],
35
+ ["latency.request", "histogram", "Request latency (ms)"],
36
+
37
+ // Stream metrics
38
+ ["streams.active", "gauge", "Active SSE streams"],
39
+ ["streams.errors", "counter", "Stream errors"],
40
+
41
+ // CAPTCHA / anti-bot metrics
42
+ ["captcha.challenges.detected", "counter", "Detected CAPTCHA challenges"],
43
+ ["captcha.solves.succeeded", "counter", "Successful CAPTCHA solves"],
44
+ ["captcha.solves.failed", "counter", "Failed CAPTCHA solves"],
45
+ ["captcha.solve.duration", "histogram", "CAPTCHA solve duration (ms)"],
46
+
47
+ // Memory metrics
48
+ ["memory.heap.used", "gauge", "Heap memory used (bytes)"],
49
+ ["memory.heap.total", "gauge", "Heap memory total (bytes)"],
50
+ [
51
+ "memory.heap.limit",
52
+ "gauge",
53
+ "V8 heap_size_limit used for RAM pressure (bytes)",
54
+ ],
55
+ [
56
+ "memory.heap.usage_percent",
57
+ "gauge",
58
+ "Heap used percent vs heap_size_limit",
59
+ ],
60
+ ["memory.rss", "gauge", "Resident set size (bytes)"],
61
+ [
62
+ "memory.rss.usage_percent",
63
+ "gauge",
64
+ "RSS as percent of total system memory (RAM pressure signal)",
65
+ ],
66
+
67
+ // Cache metrics
68
+ ["cache.set", "counter", "Cache set operations"],
69
+ ["cache.hit", "counter", "Cache hits"],
70
+ ["cache.miss", "counter", "Cache misses"],
71
+ ["cache.deleted", "counter", "Cache deletions"],
72
+ ["cache.flushed", "counter", "Cache flushes"],
73
+ ["cache.value.size", "histogram", "Cache value size (bytes)"],
74
+ ["cache.get.latency", "histogram", "Cache get latency (ms)"],
75
+ ["cache.hit.ratio", "gauge", "Cache hit ratio (hits / (hits + misses))"],
76
+ [
77
+ "cache.compression.ratio",
78
+ "histogram",
79
+ "Compression ratio (original / compressed)",
80
+ ],
81
+ [
82
+ "cache.compression.bytes.saved",
83
+ "counter",
84
+ "Total bytes saved by compression",
85
+ ],
86
+ [
87
+ "cache.topic.invalidation",
88
+ "counter",
89
+ "Cache entries invalidated by topic change",
90
+ ],
91
+ [
92
+ "cache.memory.usage.bytes",
93
+ "gauge",
94
+ "Estimated cache memory usage (bytes)",
95
+ ],
96
+ ["cache.entries.count", "gauge", "Current number of cache entries"],
97
+ [
98
+ "topic.change.detected",
99
+ "counter",
100
+ "Detected conversation topic changes",
101
+ ],
102
+
103
+ // Watchdog metrics
104
+ [
105
+ "watchdog.ram.status",
106
+ "gauge",
107
+ "Watchdog RAM status (0=ok, 1=warning, 2=critical)",
108
+ ],
109
+ [
110
+ "watchdog.overall",
111
+ "gauge",
112
+ "Watchdog overall status (0=healthy, 1=degraded, 2=unhealthy)",
113
+ ],
114
+ ["watchdog.recovery.triggered", "counter", "Recovery attempts triggered"],
115
+ ["watchdog.recovery.success", "counter", "Successful recoveries"],
116
+ ["watchdog.recovery.failed", "counter", "Failed recoveries"],
117
+ ];
118
+
119
+ for (const [name, type, help] of defaults) {
120
+ this.metrics.set(name, {
121
+ name,
122
+ type,
123
+ help,
124
+ values: new Map(),
125
+ histogramBuckets:
126
+ type === "histogram"
127
+ ? [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000]
128
+ : undefined,
129
+ });
130
+ }
131
+ }
132
+
133
+ increment(
134
+ name: string,
135
+ value: number = 1,
136
+ labels?: Record<string, string>,
137
+ ): void {
138
+ const metric = this.metrics.get(name);
139
+ if (!metric || metric.type !== "counter") return;
140
+
141
+ const key = labels ? JSON.stringify(labels) : "default";
142
+ // Mutate in place to avoid reallocating a MetricPoint on every increment.
143
+ const point = metric.values.get(key);
144
+ if (point) {
145
+ point.value += value;
146
+ point.timestamp = Date.now();
147
+ } else {
148
+ metric.values.set(key, { value, timestamp: Date.now(), labels });
149
+ }
150
+ }
151
+
152
+ gauge(name: string, value: number, labels?: Record<string, string>): void {
153
+ const metric = this.metrics.get(name);
154
+ if (!metric || metric.type !== "gauge") return;
155
+
156
+ const key = labels ? JSON.stringify(labels) : "default";
157
+ const point = metric.values.get(key);
158
+ if (point) {
159
+ point.value = value;
160
+ point.timestamp = Date.now();
161
+ } else {
162
+ metric.values.set(key, { value, timestamp: Date.now(), labels });
163
+ }
164
+ }
165
+
166
+ histogram(
167
+ name: string,
168
+ value: number,
169
+ labels?: Record<string, string>,
170
+ ): void {
171
+ const metric = this.metrics.get(name);
172
+ if (!metric || metric.type !== "histogram") return;
173
+
174
+ const key = labels ? JSON.stringify(labels) : "default";
175
+ const existing = metric.values.get(key);
176
+ // Reuse the stored aggregate object instead of re-wrapping it each call.
177
+ let data: { count: number; sum: number; buckets: Map<number, number> };
178
+ if (existing && typeof existing.value === "object" && existing.value !== null) {
179
+ data = existing.value as { count: number; sum: number; buckets: Map<number, number> };
180
+ } else {
181
+ data = { count: 0, sum: 0, buckets: new Map<number, number>() };
182
+ }
183
+
184
+ data.count++;
185
+ data.sum += value;
186
+ const buckets = metric.histogramBuckets;
187
+ if (buckets) {
188
+ for (let i = 0; i < buckets.length; i++) {
189
+ const bucket = buckets[i];
190
+ if (value <= bucket) {
191
+ data.buckets.set(bucket, (data.buckets.get(bucket) || 0) + 1);
192
+ } else if (!data.buckets.has(bucket)) {
193
+ // Keep every bucket present for stable output, but skip redundant writes.
194
+ data.buckets.set(bucket, 0);
195
+ }
196
+ }
197
+ }
198
+
199
+ if (existing) {
200
+ existing.value = data as any;
201
+ existing.timestamp = Date.now();
202
+ } else {
203
+ metric.values.set(key, { value: data as any, timestamp: Date.now(), labels });
204
+ }
205
+ }
206
+
207
+ startCollection(): void {
208
+ if (this.collectionInterval) return;
209
+
210
+ this.collectionInterval = setInterval(() => {
211
+ this.collectSystemMetrics();
212
+ }, config.metrics.interval);
213
+ }
214
+
215
+ private collectSystemMetrics(): void {
216
+ const heap = getHeapUsageSnapshot();
217
+ const rss = getRssUsageSnapshot();
218
+ this.gauge("memory.heap.used", heap.heapUsed);
219
+ this.gauge("memory.heap.total", heap.heapTotal);
220
+ this.gauge("memory.heap.limit", heap.heapSizeLimit);
221
+ this.gauge("memory.heap.usage_percent", heap.usagePercent);
222
+ this.gauge("memory.rss", heap.rss);
223
+ this.gauge("memory.rss.usage_percent", rss.usagePercent);
224
+ }
225
+
226
+ get(name: string, labels?: Record<string, string>): MetricPoint | null {
227
+ const metric = this.metrics.get(name);
228
+ if (!metric) return null;
229
+ const key = labels ? JSON.stringify(labels) : "default";
230
+ return metric.values.get(key) || null;
231
+ }
232
+
233
+ formatPrometheus(): string {
234
+ let output = "";
235
+ for (const metric of this.metrics.values()) {
236
+ output += `# HELP ${metric.name} ${metric.help}\n`;
237
+ output += `# TYPE ${metric.name} ${metric.type}\n`;
238
+
239
+ for (const point of metric.values.values()) {
240
+ const labelPairs = point.labels
241
+ ? Object.entries(point.labels).map(([k, v]) => `${k}="${v}"`)
242
+ : [];
243
+ const labelsStr = labelPairs.length ? `{${labelPairs.join(",")}}` : "";
244
+
245
+ if (
246
+ metric.type === "histogram" &&
247
+ typeof point.value === "object" &&
248
+ point.value !== null
249
+ ) {
250
+ // Histogram points store a {count, sum, buckets} aggregate; emitting
251
+ // it raw produced "[object Object]" (invalid Prometheus exposition).
252
+ const data = point.value as {
253
+ count: number;
254
+ sum: number;
255
+ buckets: Map<number, number>;
256
+ };
257
+ const bucketPrefix = labelPairs.length
258
+ ? `${labelPairs.join(",")},`
259
+ : "";
260
+ const sortedBuckets = [...data.buckets.keys()].sort((a, b) => a - b);
261
+ for (const bucket of sortedBuckets) {
262
+ output += `${metric.name}_bucket{${bucketPrefix}le="${bucket}"} ${data.buckets.get(bucket)} ${point.timestamp}\n`;
263
+ }
264
+ output += `${metric.name}_bucket{${bucketPrefix}le="+Inf"} ${data.count} ${point.timestamp}\n`;
265
+ output += `${metric.name}_sum${labelsStr} ${data.sum} ${point.timestamp}\n`;
266
+ output += `${metric.name}_count${labelsStr} ${data.count} ${point.timestamp}\n`;
267
+ continue;
268
+ }
269
+
270
+ output += `${metric.name}${labelsStr} ${point.value} ${point.timestamp}\n`;
271
+ }
272
+ }
273
+ return output;
274
+ }
275
+
276
+ reset(): void {
277
+ for (const metric of this.metrics.values()) {
278
+ metric.values.clear();
279
+ }
280
+ this.emit("reset", {});
281
+ }
282
+
283
+ stopCollection(): void {
284
+ if (this.collectionInterval) {
285
+ clearInterval(this.collectionInterval);
286
+ this.collectionInterval = null;
287
+ }
288
+ }
289
+ }
290
+
291
+ export const metrics = new Metrics();