chatccc 0.2.187 → 0.2.189

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 (71) hide show
  1. package/agent-prompts/claude_specific.md +45 -45
  2. package/agent-prompts/codex_specific.md +2 -2
  3. package/agent-prompts/cursor_specific.md +13 -13
  4. package/config.sample.json +5 -0
  5. package/im-skills/feishu-skill/receive-send-file.md +63 -63
  6. package/im-skills/feishu-skill/receive-send-image.md +24 -24
  7. package/im-skills/feishu-skill/skill.md +3 -3
  8. package/im-skills/wechat-file-skill/receive-send-file.md +38 -38
  9. package/im-skills/wechat-file-skill/send-file.mjs +83 -83
  10. package/im-skills/wechat-file-skill/skill.md +10 -10
  11. package/im-skills/wechat-image-skill/skill.md +10 -10
  12. package/im-skills/wechat-video-skill/receive-send-video.md +38 -38
  13. package/im-skills/wechat-video-skill/send-video.mjs +79 -79
  14. package/im-skills/wechat-video-skill/skill.md +10 -10
  15. package/package.json +1 -1
  16. package/scripts/postinstall-sharp-check.mjs +58 -58
  17. package/src/__tests__/agent-delegate-task-rpc.test.ts +165 -165
  18. package/src/__tests__/builtin-config.test.ts +33 -0
  19. package/src/__tests__/card-plain-text.test.ts +5 -5
  20. package/src/__tests__/cardkit.test.ts +60 -60
  21. package/src/__tests__/cards.test.ts +77 -77
  22. package/src/__tests__/chatgpt-subscription-rpc.test.ts +89 -89
  23. package/src/__tests__/chatgpt-subscription.test.ts +135 -135
  24. package/src/__tests__/chrome-devtools-guard.test.ts +165 -125
  25. package/src/__tests__/claude-adapter.test.ts +592 -592
  26. package/src/__tests__/codex-reset-actions.test.ts +146 -146
  27. package/src/__tests__/config-reload.test.ts +1 -0
  28. package/src/__tests__/config-sample.test.ts +11 -0
  29. package/src/__tests__/feishu-api.test.ts +60 -60
  30. package/src/__tests__/feishu-avatar.test.ts +180 -115
  31. package/src/__tests__/feishu-platform.test.ts +22 -22
  32. package/src/__tests__/format-message.test.ts +47 -47
  33. package/src/__tests__/orchestrator.test.ts +150 -2
  34. package/src/__tests__/privacy.test.ts +198 -198
  35. package/src/__tests__/raw-stream-log.test.ts +106 -106
  36. package/src/__tests__/session.test.ts +10 -0
  37. package/src/__tests__/shared-prefix.test.ts +36 -36
  38. package/src/__tests__/stream-state.test.ts +42 -42
  39. package/src/__tests__/web-ui.test.ts +209 -130
  40. package/src/adapters/claude-adapter.ts +566 -566
  41. package/src/adapters/claude-session-meta-store.ts +120 -120
  42. package/src/adapters/codex-adapter.ts +10 -6
  43. package/src/adapters/cursor-adapter.ts +46 -46
  44. package/src/adapters/raw-stream-log.ts +124 -124
  45. package/src/adapters/resource-monitor.ts +140 -140
  46. package/src/agent-delegate-task-rpc.ts +153 -153
  47. package/src/agent-delegate-task.ts +81 -81
  48. package/src/agent-stop-stuck.ts +129 -129
  49. package/src/builtin/cli.ts +189 -197
  50. package/src/builtin/index.ts +168 -167
  51. package/src/cards.ts +130 -89
  52. package/src/chatgpt-subscription-rpc.ts +27 -27
  53. package/src/chatgpt-subscription.ts +299 -299
  54. package/src/chrome-devtools-guard.ts +318 -242
  55. package/src/codex-reset-actions.ts +184 -184
  56. package/src/config.ts +38 -0
  57. package/src/feishu-api.ts +219 -190
  58. package/src/feishu-platform.ts +20 -20
  59. package/src/format-message.ts +293 -293
  60. package/src/index.ts +2 -2
  61. package/src/litellm-proxy.ts +374 -374
  62. package/src/orchestrator.ts +201 -9
  63. package/src/platform-adapter.ts +9 -1
  64. package/src/privacy.ts +118 -118
  65. package/src/session-chat-binding.ts +6 -6
  66. package/src/session-name.ts +8 -8
  67. package/src/session.ts +44 -16
  68. package/src/shared-prefix.ts +29 -29
  69. package/src/sim-platform.ts +20 -20
  70. package/src/turn-cards.ts +117 -117
  71. package/src/web-ui.ts +142 -24
@@ -1,374 +1,374 @@
1
- import http, { createServer, type IncomingHttpHeaders, type IncomingMessage, type ServerResponse } from "node:http";
2
- import https from "node:https";
3
- import { createWriteStream } from "node:fs";
4
- import { mkdir, writeFile, appendFile } from "node:fs/promises";
5
- import { homedir } from "node:os";
6
- import { dirname, join } from "node:path";
7
-
8
- type ProxyConfig = {
9
- host: string;
10
- port: number;
11
- upstream: URL;
12
- logDir: string;
13
- logSecrets: boolean;
14
- };
15
-
16
- type RequestLog = {
17
- id: string;
18
- timestamp: string;
19
- method: string;
20
- path: string;
21
- upstreamUrl: string;
22
- headers: Record<string, string | string[] | undefined>;
23
- bodyBytes: number;
24
- bodyFile: string;
25
- };
26
-
27
- type ResponseLog = {
28
- id: string;
29
- timestamp: string;
30
- status: number;
31
- statusText: string;
32
- headers: Record<string, string>;
33
- bodyBytes: number;
34
- bodyFile: string;
35
- durationMs: number;
36
- };
37
-
38
- type RawUpstreamResponse = {
39
- statusCode: number;
40
- statusMessage: string;
41
- headers: IncomingHttpHeaders;
42
- stream: IncomingMessage;
43
- };
44
-
45
- const HOP_BY_HOP_HEADERS = new Set([
46
- "connection",
47
- "keep-alive",
48
- "proxy-authenticate",
49
- "proxy-authorization",
50
- "te",
51
- "trailer",
52
- "transfer-encoding",
53
- "upgrade",
54
- ]);
55
-
56
- const SENSITIVE_HEADERS = new Set([
57
- "authorization",
58
- "cookie",
59
- "set-cookie",
60
- "x-api-key",
61
- "api-key",
62
- ]);
63
-
64
- let requestSeq = 0;
65
-
66
- function parseArgs(argv: string[]): Partial<ProxyConfig> {
67
- const parsed: Partial<ProxyConfig> = {};
68
- for (let i = 0; i < argv.length; i++) {
69
- const arg = argv[i];
70
- const next = argv[i + 1];
71
- const readValue = () => {
72
- if (!next) throw new Error(`${arg} requires a value`);
73
- i++;
74
- return next;
75
- };
76
-
77
- if (arg === "--host") parsed.host = readValue();
78
- else if (arg === "--port") parsed.port = Number(readValue());
79
- else if (arg === "--upstream") parsed.upstream = new URL(readValue());
80
- else if (arg === "--log-dir") parsed.logDir = readValue();
81
- else if (arg === "--log-secrets") parsed.logSecrets = true;
82
- else if (arg === "--help" || arg === "-h") {
83
- printHelp();
84
- process.exit(0);
85
- } else {
86
- throw new Error(`Unknown argument: ${arg}`);
87
- }
88
- }
89
- return parsed;
90
- }
91
-
92
- function readConfig(): ProxyConfig {
93
- const args = parseArgs(process.argv.slice(2));
94
- const upstreamRaw = args.upstream?.toString() ??
95
- process.env.CHATCCC_LITELLM_PROXY_UPSTREAM ??
96
- "https://litellm.hypergryph.net";
97
-
98
- const portRaw = args.port ?? Number(process.env.CHATCCC_LITELLM_PROXY_PORT ?? "18081");
99
- if (!Number.isInteger(portRaw) || portRaw <= 0 || portRaw > 65535) {
100
- throw new Error(`Invalid port: ${portRaw}`);
101
- }
102
-
103
- return {
104
- host: args.host ?? process.env.CHATCCC_LITELLM_PROXY_HOST ?? "127.0.0.1",
105
- port: portRaw,
106
- upstream: new URL(upstreamRaw),
107
- logDir: args.logDir ?? process.env.CHATCCC_LITELLM_PROXY_LOG_DIR ??
108
- join(homedir(), ".chatccc", "logs", "litellm-proxy"),
109
- logSecrets: args.logSecrets ?? process.env.CHATCCC_LITELLM_PROXY_LOG_SECRETS === "1",
110
- };
111
- }
112
-
113
- function printHelp(): void {
114
- console.log(`Usage: npm run claude-proxy -- [options]
115
-
116
- Options:
117
- --host <host> Listen host, default 127.0.0.1
118
- --port <port> Listen port, default 18081
119
- --upstream <url> Upstream LiteLLM base URL, default https://litellm.hypergryph.net
120
- --log-dir <path> Log directory, default %USERPROFILE%/.chatccc/logs/litellm-proxy
121
- --log-secrets Log sensitive headers instead of redacting them
122
-
123
- Equivalent env vars:
124
- CHATCCC_LITELLM_PROXY_HOST
125
- CHATCCC_LITELLM_PROXY_PORT
126
- CHATCCC_LITELLM_PROXY_UPSTREAM
127
- CHATCCC_LITELLM_PROXY_LOG_DIR
128
- CHATCCC_LITELLM_PROXY_LOG_SECRETS=1
129
- `);
130
- }
131
-
132
- function nextRequestId(): string {
133
- const stamp = new Date().toISOString()
134
- .replace(/[-:]/g, "")
135
- .replace(/\.\d{3}Z$/, "Z");
136
- requestSeq = (requestSeq + 1) % 1_000_000;
137
- return `${stamp}-${String(requestSeq).padStart(6, "0")}`;
138
- }
139
-
140
- function dayDir(baseDir: string): string {
141
- return join(baseDir, new Date().toISOString().slice(0, 10));
142
- }
143
-
144
- function toUpstreamUrl(reqUrl: string | undefined, upstream: URL): URL {
145
- const path = reqUrl && reqUrl.startsWith("/") ? reqUrl : "/";
146
- return new URL(path, upstream);
147
- }
148
-
149
- function isHopByHopHeader(name: string): boolean {
150
- return HOP_BY_HOP_HEADERS.has(name.toLowerCase());
151
- }
152
-
153
- function copyRequestHeaders(headers: IncomingHttpHeaders, bodyLength: number): Record<string, string | string[]> {
154
- const next: Record<string, string | string[]> = {};
155
- for (const [name, value] of Object.entries(headers)) {
156
- const lower = name.toLowerCase();
157
- if (lower === "host" || lower === "content-length" || isHopByHopHeader(lower)) continue;
158
- if (Array.isArray(value)) {
159
- next[name] = value;
160
- } else if (typeof value === "string") {
161
- next[name] = value;
162
- }
163
- }
164
- if (bodyLength > 0) next["content-length"] = String(bodyLength);
165
- return next;
166
- }
167
-
168
- function safeHeaders<T extends Record<string, string | string[] | undefined>>(
169
- headers: T,
170
- logSecrets: boolean,
171
- ): T {
172
- if (logSecrets) return headers;
173
- const redacted = { ...headers };
174
- for (const key of Object.keys(redacted)) {
175
- if (SENSITIVE_HEADERS.has(key.toLowerCase())) {
176
- redacted[key as keyof T] = "[REDACTED]" as T[keyof T];
177
- }
178
- }
179
- return redacted;
180
- }
181
-
182
- function responseHeaders(headers: IncomingHttpHeaders, logSecrets: boolean): Record<string, string> {
183
- const result: Record<string, string> = {};
184
- for (const [key, value] of Object.entries(headers)) {
185
- if (value === undefined) continue;
186
- result[key] = SENSITIVE_HEADERS.has(key.toLowerCase()) && !logSecrets
187
- ? "[REDACTED]"
188
- : Array.isArray(value) ? value.join(", ") : value;
189
- }
190
- return result;
191
- }
192
-
193
- async function readBody(req: IncomingMessage): Promise<Buffer> {
194
- const chunks: Buffer[] = [];
195
- for await (const chunk of req) {
196
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
197
- }
198
- return Buffer.concat(chunks);
199
- }
200
-
201
- async function appendJsonl(filePath: string, value: unknown): Promise<void> {
202
- await mkdir(dirname(filePath), { recursive: true });
203
- await appendFile(filePath, JSON.stringify(value) + "\n", "utf-8");
204
- }
205
-
206
- async function logRequest(
207
- config: ProxyConfig,
208
- id: string,
209
- req: IncomingMessage,
210
- upstreamUrl: URL,
211
- body: Buffer,
212
- bodyFile: string,
213
- ): Promise<void> {
214
- const log: RequestLog = {
215
- id,
216
- timestamp: new Date().toISOString(),
217
- method: req.method ?? "GET",
218
- path: req.url ?? "/",
219
- upstreamUrl: upstreamUrl.toString(),
220
- headers: safeHeaders(req.headers, config.logSecrets),
221
- bodyBytes: body.byteLength,
222
- bodyFile,
223
- };
224
- await writeFile(bodyFile, body);
225
- await appendJsonl(join(dayDir(config.logDir), "events.jsonl"), { event: "request", ...log });
226
- }
227
-
228
- async function logResponse(
229
- config: ProxyConfig,
230
- log: ResponseLog,
231
- ): Promise<void> {
232
- await appendJsonl(join(dayDir(config.logDir), "events.jsonl"), { event: "response", ...log });
233
- }
234
-
235
- function requestUpstream(
236
- upstreamUrl: URL,
237
- req: IncomingMessage,
238
- body: Buffer,
239
- abortSignal: AbortSignal,
240
- ): Promise<RawUpstreamResponse> {
241
- return new Promise((resolve, reject) => {
242
- const transport = upstreamUrl.protocol === "https:" ? https : http;
243
- const upstreamReq = transport.request({
244
- protocol: upstreamUrl.protocol,
245
- hostname: upstreamUrl.hostname,
246
- port: upstreamUrl.port || undefined,
247
- method: req.method,
248
- path: `${upstreamUrl.pathname}${upstreamUrl.search}`,
249
- headers: copyRequestHeaders(req.headers, body.byteLength),
250
- }, (upstreamRes) => {
251
- resolve({
252
- statusCode: upstreamRes.statusCode ?? 502,
253
- statusMessage: upstreamRes.statusMessage ?? "",
254
- headers: upstreamRes.headers,
255
- stream: upstreamRes,
256
- });
257
- });
258
-
259
- upstreamReq.on("error", reject);
260
- abortSignal.addEventListener("abort", () => upstreamReq.destroy(new Error("client aborted")), { once: true });
261
-
262
- if (body.byteLength > 0) upstreamReq.write(body);
263
- upstreamReq.end();
264
- });
265
- }
266
-
267
- function setResponseHeaders(res: ServerResponse, headers: IncomingHttpHeaders): void {
268
- for (const [key, value] of Object.entries(headers)) {
269
- if (!value || isHopByHopHeader(key)) continue;
270
- res.setHeader(key, value);
271
- }
272
- }
273
-
274
- async function writeError(res: ServerResponse, status: number, error: string): Promise<void> {
275
- if (res.headersSent) {
276
- res.end();
277
- return;
278
- }
279
- res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
280
- res.end(JSON.stringify({ error }));
281
- }
282
-
283
- async function handleProxyRequest(config: ProxyConfig, req: IncomingMessage, res: ServerResponse): Promise<void> {
284
- const started = Date.now();
285
- const id = nextRequestId();
286
- const dir = dayDir(config.logDir);
287
- await mkdir(dir, { recursive: true });
288
-
289
- const upstreamUrl = toUpstreamUrl(req.url, config.upstream);
290
- const requestBody = await readBody(req);
291
- const requestBodyFile = join(dir, `${id}.request.body`);
292
- const responseBodyFile = join(dir, `${id}.response.body`);
293
- await logRequest(config, id, req, upstreamUrl, requestBody, requestBodyFile);
294
-
295
- const abortController = new AbortController();
296
- req.on("aborted", () => abortController.abort());
297
-
298
- let upstreamResponse: RawUpstreamResponse;
299
- try {
300
- upstreamResponse = await requestUpstream(upstreamUrl, req, requestBody, abortController.signal);
301
- } catch (err) {
302
- await appendJsonl(join(dir, "events.jsonl"), {
303
- event: "error",
304
- id,
305
- timestamp: new Date().toISOString(),
306
- message: (err as Error).message,
307
- durationMs: Date.now() - started,
308
- });
309
- await writeError(res, 502, `Proxy upstream request failed: ${(err as Error).message}`);
310
- return;
311
- }
312
-
313
- res.statusCode = upstreamResponse.statusCode;
314
- res.statusMessage = upstreamResponse.statusMessage;
315
- setResponseHeaders(res, upstreamResponse.headers);
316
-
317
- let responseBytes = 0;
318
- const out = createWriteStream(responseBodyFile);
319
- try {
320
- for await (const chunk of upstreamResponse.stream) {
321
- const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
322
- responseBytes += buf.byteLength;
323
- out.write(buf);
324
- if (!res.write(buf)) {
325
- await new Promise<void>((resolve) => res.once("drain", resolve));
326
- }
327
- }
328
- } catch (err) {
329
- await appendJsonl(join(dir, "events.jsonl"), {
330
- event: "stream_error",
331
- id,
332
- timestamp: new Date().toISOString(),
333
- message: (err as Error).message,
334
- durationMs: Date.now() - started,
335
- });
336
- } finally {
337
- out.end();
338
- res.end();
339
- }
340
-
341
- await logResponse(config, {
342
- id,
343
- timestamp: new Date().toISOString(),
344
- status: upstreamResponse.statusCode,
345
- statusText: upstreamResponse.statusMessage,
346
- headers: responseHeaders(upstreamResponse.headers, config.logSecrets),
347
- bodyBytes: responseBytes,
348
- bodyFile: responseBodyFile,
349
- durationMs: Date.now() - started,
350
- });
351
- }
352
-
353
- async function main(): Promise<void> {
354
- const config = readConfig();
355
- await mkdir(config.logDir, { recursive: true });
356
-
357
- const server = createServer((req, res) => {
358
- void handleProxyRequest(config, req, res).catch(async (err) => {
359
- console.error(`[litellm-proxy] unhandled request error: ${(err as Error).stack ?? (err as Error).message}`);
360
- await writeError(res, 500, `Proxy internal error: ${(err as Error).message}`);
361
- });
362
- });
363
-
364
- server.listen(config.port, config.host, () => {
365
- console.log(`[litellm-proxy] listening on http://${config.host}:${config.port}`);
366
- console.log(`[litellm-proxy] upstream ${config.upstream.toString()}`);
367
- console.log(`[litellm-proxy] logs ${config.logDir}`);
368
- });
369
- }
370
-
371
- void main().catch((err) => {
372
- console.error(`[litellm-proxy] failed to start: ${(err as Error).message}`);
373
- process.exit(1);
374
- });
1
+ import http, { createServer, type IncomingHttpHeaders, type IncomingMessage, type ServerResponse } from "node:http";
2
+ import https from "node:https";
3
+ import { createWriteStream } from "node:fs";
4
+ import { mkdir, writeFile, appendFile } from "node:fs/promises";
5
+ import { homedir } from "node:os";
6
+ import { dirname, join } from "node:path";
7
+
8
+ type ProxyConfig = {
9
+ host: string;
10
+ port: number;
11
+ upstream: URL;
12
+ logDir: string;
13
+ logSecrets: boolean;
14
+ };
15
+
16
+ type RequestLog = {
17
+ id: string;
18
+ timestamp: string;
19
+ method: string;
20
+ path: string;
21
+ upstreamUrl: string;
22
+ headers: Record<string, string | string[] | undefined>;
23
+ bodyBytes: number;
24
+ bodyFile: string;
25
+ };
26
+
27
+ type ResponseLog = {
28
+ id: string;
29
+ timestamp: string;
30
+ status: number;
31
+ statusText: string;
32
+ headers: Record<string, string>;
33
+ bodyBytes: number;
34
+ bodyFile: string;
35
+ durationMs: number;
36
+ };
37
+
38
+ type RawUpstreamResponse = {
39
+ statusCode: number;
40
+ statusMessage: string;
41
+ headers: IncomingHttpHeaders;
42
+ stream: IncomingMessage;
43
+ };
44
+
45
+ const HOP_BY_HOP_HEADERS = new Set([
46
+ "connection",
47
+ "keep-alive",
48
+ "proxy-authenticate",
49
+ "proxy-authorization",
50
+ "te",
51
+ "trailer",
52
+ "transfer-encoding",
53
+ "upgrade",
54
+ ]);
55
+
56
+ const SENSITIVE_HEADERS = new Set([
57
+ "authorization",
58
+ "cookie",
59
+ "set-cookie",
60
+ "x-api-key",
61
+ "api-key",
62
+ ]);
63
+
64
+ let requestSeq = 0;
65
+
66
+ function parseArgs(argv: string[]): Partial<ProxyConfig> {
67
+ const parsed: Partial<ProxyConfig> = {};
68
+ for (let i = 0; i < argv.length; i++) {
69
+ const arg = argv[i];
70
+ const next = argv[i + 1];
71
+ const readValue = () => {
72
+ if (!next) throw new Error(`${arg} requires a value`);
73
+ i++;
74
+ return next;
75
+ };
76
+
77
+ if (arg === "--host") parsed.host = readValue();
78
+ else if (arg === "--port") parsed.port = Number(readValue());
79
+ else if (arg === "--upstream") parsed.upstream = new URL(readValue());
80
+ else if (arg === "--log-dir") parsed.logDir = readValue();
81
+ else if (arg === "--log-secrets") parsed.logSecrets = true;
82
+ else if (arg === "--help" || arg === "-h") {
83
+ printHelp();
84
+ process.exit(0);
85
+ } else {
86
+ throw new Error(`Unknown argument: ${arg}`);
87
+ }
88
+ }
89
+ return parsed;
90
+ }
91
+
92
+ function readConfig(): ProxyConfig {
93
+ const args = parseArgs(process.argv.slice(2));
94
+ const upstreamRaw = args.upstream?.toString() ??
95
+ process.env.CHATCCC_LITELLM_PROXY_UPSTREAM ??
96
+ "https://litellm.hypergryph.net";
97
+
98
+ const portRaw = args.port ?? Number(process.env.CHATCCC_LITELLM_PROXY_PORT ?? "18081");
99
+ if (!Number.isInteger(portRaw) || portRaw <= 0 || portRaw > 65535) {
100
+ throw new Error(`Invalid port: ${portRaw}`);
101
+ }
102
+
103
+ return {
104
+ host: args.host ?? process.env.CHATCCC_LITELLM_PROXY_HOST ?? "127.0.0.1",
105
+ port: portRaw,
106
+ upstream: new URL(upstreamRaw),
107
+ logDir: args.logDir ?? process.env.CHATCCC_LITELLM_PROXY_LOG_DIR ??
108
+ join(homedir(), ".chatccc", "logs", "litellm-proxy"),
109
+ logSecrets: args.logSecrets ?? process.env.CHATCCC_LITELLM_PROXY_LOG_SECRETS === "1",
110
+ };
111
+ }
112
+
113
+ function printHelp(): void {
114
+ console.log(`Usage: npm run claude-proxy -- [options]
115
+
116
+ Options:
117
+ --host <host> Listen host, default 127.0.0.1
118
+ --port <port> Listen port, default 18081
119
+ --upstream <url> Upstream LiteLLM base URL, default https://litellm.hypergryph.net
120
+ --log-dir <path> Log directory, default %USERPROFILE%/.chatccc/logs/litellm-proxy
121
+ --log-secrets Log sensitive headers instead of redacting them
122
+
123
+ Equivalent env vars:
124
+ CHATCCC_LITELLM_PROXY_HOST
125
+ CHATCCC_LITELLM_PROXY_PORT
126
+ CHATCCC_LITELLM_PROXY_UPSTREAM
127
+ CHATCCC_LITELLM_PROXY_LOG_DIR
128
+ CHATCCC_LITELLM_PROXY_LOG_SECRETS=1
129
+ `);
130
+ }
131
+
132
+ function nextRequestId(): string {
133
+ const stamp = new Date().toISOString()
134
+ .replace(/[-:]/g, "")
135
+ .replace(/\.\d{3}Z$/, "Z");
136
+ requestSeq = (requestSeq + 1) % 1_000_000;
137
+ return `${stamp}-${String(requestSeq).padStart(6, "0")}`;
138
+ }
139
+
140
+ function dayDir(baseDir: string): string {
141
+ return join(baseDir, new Date().toISOString().slice(0, 10));
142
+ }
143
+
144
+ function toUpstreamUrl(reqUrl: string | undefined, upstream: URL): URL {
145
+ const path = reqUrl && reqUrl.startsWith("/") ? reqUrl : "/";
146
+ return new URL(path, upstream);
147
+ }
148
+
149
+ function isHopByHopHeader(name: string): boolean {
150
+ return HOP_BY_HOP_HEADERS.has(name.toLowerCase());
151
+ }
152
+
153
+ function copyRequestHeaders(headers: IncomingHttpHeaders, bodyLength: number): Record<string, string | string[]> {
154
+ const next: Record<string, string | string[]> = {};
155
+ for (const [name, value] of Object.entries(headers)) {
156
+ const lower = name.toLowerCase();
157
+ if (lower === "host" || lower === "content-length" || isHopByHopHeader(lower)) continue;
158
+ if (Array.isArray(value)) {
159
+ next[name] = value;
160
+ } else if (typeof value === "string") {
161
+ next[name] = value;
162
+ }
163
+ }
164
+ if (bodyLength > 0) next["content-length"] = String(bodyLength);
165
+ return next;
166
+ }
167
+
168
+ function safeHeaders<T extends Record<string, string | string[] | undefined>>(
169
+ headers: T,
170
+ logSecrets: boolean,
171
+ ): T {
172
+ if (logSecrets) return headers;
173
+ const redacted = { ...headers };
174
+ for (const key of Object.keys(redacted)) {
175
+ if (SENSITIVE_HEADERS.has(key.toLowerCase())) {
176
+ redacted[key as keyof T] = "[REDACTED]" as T[keyof T];
177
+ }
178
+ }
179
+ return redacted;
180
+ }
181
+
182
+ function responseHeaders(headers: IncomingHttpHeaders, logSecrets: boolean): Record<string, string> {
183
+ const result: Record<string, string> = {};
184
+ for (const [key, value] of Object.entries(headers)) {
185
+ if (value === undefined) continue;
186
+ result[key] = SENSITIVE_HEADERS.has(key.toLowerCase()) && !logSecrets
187
+ ? "[REDACTED]"
188
+ : Array.isArray(value) ? value.join(", ") : value;
189
+ }
190
+ return result;
191
+ }
192
+
193
+ async function readBody(req: IncomingMessage): Promise<Buffer> {
194
+ const chunks: Buffer[] = [];
195
+ for await (const chunk of req) {
196
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
197
+ }
198
+ return Buffer.concat(chunks);
199
+ }
200
+
201
+ async function appendJsonl(filePath: string, value: unknown): Promise<void> {
202
+ await mkdir(dirname(filePath), { recursive: true });
203
+ await appendFile(filePath, JSON.stringify(value) + "\n", "utf-8");
204
+ }
205
+
206
+ async function logRequest(
207
+ config: ProxyConfig,
208
+ id: string,
209
+ req: IncomingMessage,
210
+ upstreamUrl: URL,
211
+ body: Buffer,
212
+ bodyFile: string,
213
+ ): Promise<void> {
214
+ const log: RequestLog = {
215
+ id,
216
+ timestamp: new Date().toISOString(),
217
+ method: req.method ?? "GET",
218
+ path: req.url ?? "/",
219
+ upstreamUrl: upstreamUrl.toString(),
220
+ headers: safeHeaders(req.headers, config.logSecrets),
221
+ bodyBytes: body.byteLength,
222
+ bodyFile,
223
+ };
224
+ await writeFile(bodyFile, body);
225
+ await appendJsonl(join(dayDir(config.logDir), "events.jsonl"), { event: "request", ...log });
226
+ }
227
+
228
+ async function logResponse(
229
+ config: ProxyConfig,
230
+ log: ResponseLog,
231
+ ): Promise<void> {
232
+ await appendJsonl(join(dayDir(config.logDir), "events.jsonl"), { event: "response", ...log });
233
+ }
234
+
235
+ function requestUpstream(
236
+ upstreamUrl: URL,
237
+ req: IncomingMessage,
238
+ body: Buffer,
239
+ abortSignal: AbortSignal,
240
+ ): Promise<RawUpstreamResponse> {
241
+ return new Promise((resolve, reject) => {
242
+ const transport = upstreamUrl.protocol === "https:" ? https : http;
243
+ const upstreamReq = transport.request({
244
+ protocol: upstreamUrl.protocol,
245
+ hostname: upstreamUrl.hostname,
246
+ port: upstreamUrl.port || undefined,
247
+ method: req.method,
248
+ path: `${upstreamUrl.pathname}${upstreamUrl.search}`,
249
+ headers: copyRequestHeaders(req.headers, body.byteLength),
250
+ }, (upstreamRes) => {
251
+ resolve({
252
+ statusCode: upstreamRes.statusCode ?? 502,
253
+ statusMessage: upstreamRes.statusMessage ?? "",
254
+ headers: upstreamRes.headers,
255
+ stream: upstreamRes,
256
+ });
257
+ });
258
+
259
+ upstreamReq.on("error", reject);
260
+ abortSignal.addEventListener("abort", () => upstreamReq.destroy(new Error("client aborted")), { once: true });
261
+
262
+ if (body.byteLength > 0) upstreamReq.write(body);
263
+ upstreamReq.end();
264
+ });
265
+ }
266
+
267
+ function setResponseHeaders(res: ServerResponse, headers: IncomingHttpHeaders): void {
268
+ for (const [key, value] of Object.entries(headers)) {
269
+ if (!value || isHopByHopHeader(key)) continue;
270
+ res.setHeader(key, value);
271
+ }
272
+ }
273
+
274
+ async function writeError(res: ServerResponse, status: number, error: string): Promise<void> {
275
+ if (res.headersSent) {
276
+ res.end();
277
+ return;
278
+ }
279
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
280
+ res.end(JSON.stringify({ error }));
281
+ }
282
+
283
+ async function handleProxyRequest(config: ProxyConfig, req: IncomingMessage, res: ServerResponse): Promise<void> {
284
+ const started = Date.now();
285
+ const id = nextRequestId();
286
+ const dir = dayDir(config.logDir);
287
+ await mkdir(dir, { recursive: true });
288
+
289
+ const upstreamUrl = toUpstreamUrl(req.url, config.upstream);
290
+ const requestBody = await readBody(req);
291
+ const requestBodyFile = join(dir, `${id}.request.body`);
292
+ const responseBodyFile = join(dir, `${id}.response.body`);
293
+ await logRequest(config, id, req, upstreamUrl, requestBody, requestBodyFile);
294
+
295
+ const abortController = new AbortController();
296
+ req.on("aborted", () => abortController.abort());
297
+
298
+ let upstreamResponse: RawUpstreamResponse;
299
+ try {
300
+ upstreamResponse = await requestUpstream(upstreamUrl, req, requestBody, abortController.signal);
301
+ } catch (err) {
302
+ await appendJsonl(join(dir, "events.jsonl"), {
303
+ event: "error",
304
+ id,
305
+ timestamp: new Date().toISOString(),
306
+ message: (err as Error).message,
307
+ durationMs: Date.now() - started,
308
+ });
309
+ await writeError(res, 502, `Proxy upstream request failed: ${(err as Error).message}`);
310
+ return;
311
+ }
312
+
313
+ res.statusCode = upstreamResponse.statusCode;
314
+ res.statusMessage = upstreamResponse.statusMessage;
315
+ setResponseHeaders(res, upstreamResponse.headers);
316
+
317
+ let responseBytes = 0;
318
+ const out = createWriteStream(responseBodyFile);
319
+ try {
320
+ for await (const chunk of upstreamResponse.stream) {
321
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
322
+ responseBytes += buf.byteLength;
323
+ out.write(buf);
324
+ if (!res.write(buf)) {
325
+ await new Promise<void>((resolve) => res.once("drain", resolve));
326
+ }
327
+ }
328
+ } catch (err) {
329
+ await appendJsonl(join(dir, "events.jsonl"), {
330
+ event: "stream_error",
331
+ id,
332
+ timestamp: new Date().toISOString(),
333
+ message: (err as Error).message,
334
+ durationMs: Date.now() - started,
335
+ });
336
+ } finally {
337
+ out.end();
338
+ res.end();
339
+ }
340
+
341
+ await logResponse(config, {
342
+ id,
343
+ timestamp: new Date().toISOString(),
344
+ status: upstreamResponse.statusCode,
345
+ statusText: upstreamResponse.statusMessage,
346
+ headers: responseHeaders(upstreamResponse.headers, config.logSecrets),
347
+ bodyBytes: responseBytes,
348
+ bodyFile: responseBodyFile,
349
+ durationMs: Date.now() - started,
350
+ });
351
+ }
352
+
353
+ async function main(): Promise<void> {
354
+ const config = readConfig();
355
+ await mkdir(config.logDir, { recursive: true });
356
+
357
+ const server = createServer((req, res) => {
358
+ void handleProxyRequest(config, req, res).catch(async (err) => {
359
+ console.error(`[litellm-proxy] unhandled request error: ${(err as Error).stack ?? (err as Error).message}`);
360
+ await writeError(res, 500, `Proxy internal error: ${(err as Error).message}`);
361
+ });
362
+ });
363
+
364
+ server.listen(config.port, config.host, () => {
365
+ console.log(`[litellm-proxy] listening on http://${config.host}:${config.port}`);
366
+ console.log(`[litellm-proxy] upstream ${config.upstream.toString()}`);
367
+ console.log(`[litellm-proxy] logs ${config.logDir}`);
368
+ });
369
+ }
370
+
371
+ void main().catch((err) => {
372
+ console.error(`[litellm-proxy] failed to start: ${(err as Error).message}`);
373
+ process.exit(1);
374
+ });