chatccc 0.2.231 → 0.2.232

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 (127) hide show
  1. package/.agents/skills/create-chatccc-feishu-app/SKILL.md +85 -85
  2. package/.claude/skills/create-chatccc-feishu-app/SKILL.md +85 -85
  3. package/.cursor/skills/create-chatccc-feishu-app/SKILL.md +85 -85
  4. package/README.md +90 -90
  5. package/agent-prompts/claude_specific.md +45 -45
  6. package/agent-prompts/codex_specific.md +2 -2
  7. package/agent-prompts/cursor_specific.md +13 -13
  8. package/bin/cccagent.mjs +17 -17
  9. package/im-skills/feishu-skill/receive-send-file.md +63 -63
  10. package/im-skills/feishu-skill/receive-send-image.md +24 -24
  11. package/im-skills/feishu-skill/skill.md +3 -3
  12. package/im-skills/wechat-file-skill/receive-send-file.md +38 -38
  13. package/im-skills/wechat-file-skill/send-file.mjs +83 -83
  14. package/im-skills/wechat-file-skill/skill.md +10 -10
  15. package/im-skills/wechat-image-skill/skill.md +10 -10
  16. package/im-skills/wechat-video-skill/receive-send-video.md +38 -38
  17. package/im-skills/wechat-video-skill/send-video.mjs +79 -79
  18. package/im-skills/wechat-video-skill/skill.md +10 -10
  19. package/package.json +1 -1
  20. package/scripts/postinstall-sharp-check.mjs +58 -58
  21. package/src/__tests__/agent-activity.test.ts +86 -86
  22. package/src/__tests__/agent-delegate-task-rpc.test.ts +165 -165
  23. package/src/__tests__/agent-reload-config-rpc.test.ts +99 -99
  24. package/src/__tests__/builtin-chat-session.test.ts +449 -393
  25. package/src/__tests__/builtin-cli-json.test.ts +39 -39
  26. package/src/__tests__/builtin-config.test.ts +26 -26
  27. package/src/__tests__/builtin-context.test.ts +319 -202
  28. package/src/__tests__/builtin-file-tools.test.ts +240 -240
  29. package/src/__tests__/builtin-permissions.test.ts +211 -211
  30. package/src/__tests__/builtin-session-search.test.ts +228 -0
  31. package/src/__tests__/builtin-session-select.test.ts +116 -116
  32. package/src/__tests__/builtin-sigint.test.ts +56 -56
  33. package/src/__tests__/builtin-skills.test.ts +284 -284
  34. package/src/__tests__/builtin-web-tools.test.ts +220 -220
  35. package/src/__tests__/card-action-routing.test.ts +18 -18
  36. package/src/__tests__/cardkit.test.ts +60 -60
  37. package/src/__tests__/ccc-adapter.test.ts +170 -170
  38. package/src/__tests__/chatgpt-subscription-rpc.test.ts +89 -89
  39. package/src/__tests__/chatgpt-subscription.test.ts +135 -135
  40. package/src/__tests__/chrome-devtools-guard.test.ts +165 -165
  41. package/src/__tests__/claude-adapter.test.ts +614 -614
  42. package/src/__tests__/claude-raw-stream-log.test.ts +87 -87
  43. package/src/__tests__/codex-adapter.test.ts +58 -58
  44. package/src/__tests__/codex-raw-stream-log.test.ts +170 -170
  45. package/src/__tests__/codex-reset-actions.test.ts +146 -146
  46. package/src/__tests__/cursor-adapter.test.ts +268 -268
  47. package/src/__tests__/feishu-api.test.ts +60 -60
  48. package/src/__tests__/feishu-avatar.test.ts +164 -164
  49. package/src/__tests__/feishu-message-ingress.test.ts +138 -138
  50. package/src/__tests__/feishu-platform.test.ts +22 -22
  51. package/src/__tests__/format-message.test.ts +47 -47
  52. package/src/__tests__/jsonl-stream.test.ts +79 -79
  53. package/src/__tests__/package-files.test.ts +24 -24
  54. package/src/__tests__/privacy.test.ts +198 -198
  55. package/src/__tests__/progress-reducer.test.ts +121 -121
  56. package/src/__tests__/raw-stream-log.test.ts +106 -106
  57. package/src/__tests__/response-stall.test.ts +49 -49
  58. package/src/__tests__/restart.test.ts +132 -132
  59. package/src/__tests__/session.test.ts +199 -199
  60. package/src/__tests__/shared-prefix.test.ts +36 -36
  61. package/src/__tests__/sim-platform.test.ts +16 -16
  62. package/src/__tests__/startup-lifecycle.test.ts +231 -231
  63. package/src/__tests__/stop-session.test.ts +34 -34
  64. package/src/__tests__/stream-state.test.ts +42 -42
  65. package/src/__tests__/terminal-error.test.ts +54 -54
  66. package/src/__tests__/terminal-renderer.test.ts +247 -247
  67. package/src/__tests__/update-command-guard.test.ts +144 -144
  68. package/src/__tests__/web-ui.test.ts +326 -326
  69. package/src/adapters/adapter-interface.ts +33 -33
  70. package/src/adapters/ccc-adapter.ts +141 -141
  71. package/src/adapters/claude-adapter.ts +620 -620
  72. package/src/adapters/claude-session-meta-store.ts +120 -120
  73. package/src/adapters/codex-adapter.ts +426 -426
  74. package/src/adapters/cursor-adapter.ts +681 -681
  75. package/src/adapters/jsonl-stream.ts +157 -157
  76. package/src/adapters/raw-stream-log.ts +124 -124
  77. package/src/adapters/resource-monitor.ts +140 -140
  78. package/src/agent-activity.ts +175 -175
  79. package/src/agent-delegate-task-rpc.ts +153 -153
  80. package/src/agent-delegate-task.ts +91 -91
  81. package/src/agent-reload-config-rpc.ts +34 -34
  82. package/src/agent-stop-stuck.ts +129 -129
  83. package/src/builtin/cli.ts +6 -0
  84. package/src/builtin/config.ts +84 -84
  85. package/src/builtin/context.ts +465 -391
  86. package/src/builtin/file-log.ts +38 -38
  87. package/src/builtin/file-tools.ts +34 -0
  88. package/src/builtin/index.ts +24 -23
  89. package/src/builtin/proc-tree-kill.ts +61 -61
  90. package/src/builtin/progress/cards-helpers.ts +76 -76
  91. package/src/builtin/progress/reducer.ts +113 -113
  92. package/src/builtin/progress/terminal-renderer.ts +294 -294
  93. package/src/builtin/progress/view.ts +77 -77
  94. package/src/builtin/raw-stream-log.ts +124 -124
  95. package/src/builtin/session-search.ts +363 -0
  96. package/src/builtin/session-select.ts +48 -48
  97. package/src/builtin/sigint.ts +50 -50
  98. package/src/builtin/skills.ts +205 -205
  99. package/src/builtin/web-tools.ts +313 -313
  100. package/src/card-action-routing.ts +14 -14
  101. package/src/chatgpt-subscription-rpc.ts +27 -27
  102. package/src/chatgpt-subscription.ts +299 -299
  103. package/src/chrome-devtools-guard.ts +318 -318
  104. package/src/codex-reset-actions.ts +184 -184
  105. package/src/feishu-api.ts +193 -193
  106. package/src/feishu-message-ingress.ts +195 -195
  107. package/src/feishu-platform.ts +20 -20
  108. package/src/format-message.ts +293 -293
  109. package/src/litellm-proxy.ts +374 -374
  110. package/src/orchestrator.ts +2494 -2494
  111. package/src/platform-adapter.ts +6 -6
  112. package/src/privacy.ts +118 -118
  113. package/src/progress/reducer.ts +113 -113
  114. package/src/progress/terminal-renderer.ts +294 -294
  115. package/src/progress/view.ts +77 -77
  116. package/src/response-stall.ts +28 -28
  117. package/src/runtime-reload.ts +34 -34
  118. package/src/session-chat-binding.ts +82 -82
  119. package/src/session-name.ts +8 -8
  120. package/src/session.ts +201 -201
  121. package/src/shared-prefix.ts +29 -29
  122. package/src/sim-platform.ts +20 -20
  123. package/src/startup-lifecycle.ts +250 -250
  124. package/src/stream-state.ts +21 -21
  125. package/src/terminal-error.ts +129 -129
  126. package/src/turn-cards.ts +117 -117
  127. package/src/update-command-guard.ts +165 -165
@@ -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
+ });