chatccc 0.2.159 → 0.2.161
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -1
- package/src/__tests__/cards.test.ts +17 -14
- package/src/__tests__/session.test.ts +128 -128
- package/src/cards.ts +11 -9
- package/src/litellm-proxy.ts +374 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "chatccc",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.161",
|
|
4
4
|
"description": "Feishu bot bridge for Claude Code",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -36,6 +36,7 @@
|
|
|
36
36
|
"demo:claude-hi": "tsx demo/claude_say_hi.ts",
|
|
37
37
|
"demo:codex-hi": "tsx demo/codex_say_hi.ts",
|
|
38
38
|
"demo:ilink-echo": "tsx demo/ilink_echo_probe.ts",
|
|
39
|
+
"claude-proxy": "tsx src/litellm-proxy.ts",
|
|
39
40
|
"test": "vitest run",
|
|
40
41
|
"test:watch": "vitest",
|
|
41
42
|
"postinstall": "node scripts/postinstall-sharp-check.mjs"
|
|
@@ -32,27 +32,30 @@ describe("truncateContent", () => {
|
|
|
32
32
|
expect(resultLines[20]).toBe("line 25");
|
|
33
33
|
});
|
|
34
34
|
|
|
35
|
-
it("truncates chars when exceeding maxChars", () => {
|
|
36
|
-
const long = "x".repeat(9000);
|
|
37
|
-
const result = truncateContent(long, 100, 500);
|
|
38
|
-
expect(result.length).toBeLessThanOrEqual(503); // "..." + 500 chars
|
|
39
|
-
expect(result.startsWith("...")).toBe(true);
|
|
40
|
-
});
|
|
41
|
-
|
|
42
35
|
it("returns empty string for empty input", () => {
|
|
43
36
|
expect(truncateContent("")).toBe("");
|
|
44
37
|
});
|
|
45
38
|
|
|
46
|
-
it("respects custom maxLines
|
|
39
|
+
it("respects custom maxLines", () => {
|
|
47
40
|
const lines = Array.from({ length: 10 }, (_, i) => `line ${i + 1}`);
|
|
48
41
|
const text = lines.join("\n");
|
|
49
|
-
const result = truncateContent(text, 5
|
|
42
|
+
const result = truncateContent(text, 5);
|
|
50
43
|
const resultLines = result.split("\n");
|
|
51
44
|
expect(resultLines[0]).toBe("line 1");
|
|
52
45
|
expect(resultLines[1]).toBe("...");
|
|
53
46
|
expect(resultLines[resultLines.length - 1]).toBe("line 10");
|
|
54
47
|
expect(resultLines.length).toBe(6); // 1 first + "..." + 4 last
|
|
55
48
|
});
|
|
49
|
+
|
|
50
|
+
it("skips leading empty lines, preserves first non-empty line", () => {
|
|
51
|
+
const lines = Array.from({ length: 25 }, (_, i) => `line ${i + 1}`);
|
|
52
|
+
const text = "\n\n\n" + lines.join("\n");
|
|
53
|
+
const result = truncateContent(text);
|
|
54
|
+
const resultLines = result.split("\n");
|
|
55
|
+
expect(resultLines[0]).toBe("line 1");
|
|
56
|
+
expect(resultLines[1]).toBe("...");
|
|
57
|
+
expect(resultLines.length).toBe(21); // 1 first + "..." + 19 last
|
|
58
|
+
});
|
|
56
59
|
});
|
|
57
60
|
|
|
58
61
|
// ---------------------------------------------------------------------------
|
|
@@ -106,11 +109,11 @@ describe("buildProgressCard", () => {
|
|
|
106
109
|
const card = buildProgressCard("hello");
|
|
107
110
|
const parsed = JSON.parse(card);
|
|
108
111
|
const buttons = parsed.body.elements.filter((e: any) => e.tag === "button");
|
|
109
|
-
expect(buttons).toHaveLength(2);
|
|
110
|
-
expect(buttons[0].text.content).toBe("查看状态(/state)");
|
|
111
|
-
expect(buttons[0].value).toEqual({ action: "state" });
|
|
112
|
-
expect(buttons[0].element_id).toBe("action_state");
|
|
113
|
-
expect(buttons[1].text.content).toBe("停止生成(/stop)");
|
|
112
|
+
expect(buttons).toHaveLength(2);
|
|
113
|
+
expect(buttons[0].text.content).toBe("查看状态(/state)");
|
|
114
|
+
expect(buttons[0].value).toEqual({ action: "state" });
|
|
115
|
+
expect(buttons[0].element_id).toBe("action_state");
|
|
116
|
+
expect(buttons[1].text.content).toBe("停止生成(/stop)");
|
|
114
117
|
});
|
|
115
118
|
|
|
116
119
|
it("hides stop button when showStop is false", () => {
|
|
@@ -9,9 +9,9 @@ const mockStreamStates = new Map<string, {
|
|
|
9
9
|
finalReply: string;
|
|
10
10
|
status?: "running" | "done" | "stopped" | "error";
|
|
11
11
|
turnCount?: number;
|
|
12
|
-
finalReplySentTurn?: number;
|
|
13
|
-
finalReplySentAt?: number;
|
|
14
|
-
}>();
|
|
12
|
+
finalReplySentTurn?: number;
|
|
13
|
+
finalReplySentAt?: number;
|
|
14
|
+
}>();
|
|
15
15
|
vi.mock("../stream-state.ts", () => ({
|
|
16
16
|
readStreamState: async (sid: string) => {
|
|
17
17
|
const state = mockStreamStates.get(sid);
|
|
@@ -20,9 +20,9 @@ vi.mock("../stream-state.ts", () => ({
|
|
|
20
20
|
sessionId: sid,
|
|
21
21
|
accumulatedContent: state.accumulatedContent,
|
|
22
22
|
finalReply: state.finalReply,
|
|
23
|
-
finalReplySentTurn: state.finalReplySentTurn,
|
|
24
|
-
finalReplySentAt: state.finalReplySentAt,
|
|
25
|
-
status: state.status ?? "running",
|
|
23
|
+
finalReplySentTurn: state.finalReplySentTurn,
|
|
24
|
+
finalReplySentAt: state.finalReplySentAt,
|
|
25
|
+
status: state.status ?? "running",
|
|
26
26
|
chunkCount: 0,
|
|
27
27
|
turnCount: state.turnCount ?? 0,
|
|
28
28
|
contextTokens: 0,
|
|
@@ -37,18 +37,18 @@ vi.mock("../stream-state.ts", () => ({
|
|
|
37
37
|
finalReply: string;
|
|
38
38
|
status?: "running" | "done" | "stopped" | "error";
|
|
39
39
|
turnCount?: number;
|
|
40
|
-
finalReplySentTurn?: number;
|
|
41
|
-
finalReplySentAt?: number;
|
|
42
|
-
}) => {
|
|
40
|
+
finalReplySentTurn?: number;
|
|
41
|
+
finalReplySentAt?: number;
|
|
42
|
+
}) => {
|
|
43
43
|
mockStreamStates.set(state.sessionId, {
|
|
44
44
|
accumulatedContent: state.accumulatedContent,
|
|
45
45
|
finalReply: state.finalReply,
|
|
46
46
|
status: state.status,
|
|
47
47
|
turnCount: state.turnCount,
|
|
48
|
-
finalReplySentTurn: state.finalReplySentTurn,
|
|
49
|
-
finalReplySentAt: state.finalReplySentAt,
|
|
50
|
-
});
|
|
51
|
-
},
|
|
48
|
+
finalReplySentTurn: state.finalReplySentTurn,
|
|
49
|
+
finalReplySentAt: state.finalReplySentAt,
|
|
50
|
+
});
|
|
51
|
+
},
|
|
52
52
|
createEmptyStreamState: (sid: string, cwd: string, tool: string, turnCount: number) => ({
|
|
53
53
|
sessionId: sid, status: "running" as const, accumulatedContent: "", finalReply: "", chunkCount: 0, turnCount, contextTokens: 0, updatedAt: Date.now(), cwd, tool,
|
|
54
54
|
}),
|
|
@@ -396,48 +396,48 @@ describe("runAgentSession process monitor", () => {
|
|
|
396
396
|
expect.stringContaining("进程异常结束"),
|
|
397
397
|
);
|
|
398
398
|
});
|
|
399
|
-
it("re-injects IM skill capabilities for each resumed Claude prompt", async () => {
|
|
400
|
-
const platform = mockPlatform("feishu");
|
|
401
|
-
setSessionPlatform(platform);
|
|
402
|
-
bindChatToSession("sid-resume", "chat-resume");
|
|
403
|
-
recordLastActiveChat("sid-resume", "chat-resume");
|
|
404
|
-
|
|
405
|
-
const sentTexts: string[] = [];
|
|
406
|
-
const adapter: ToolAdapter = {
|
|
407
|
-
displayName: "Claude Code",
|
|
408
|
-
sessionDescPrefix: "Claude Code Session:",
|
|
409
|
-
createSession: async () => ({ sessionId: "sid-resume" }),
|
|
410
|
-
getSessionInfo: async (sid) => ({ sessionId: sid, cwd: "F:\\repo" }),
|
|
411
|
-
closeSession: async () => {},
|
|
412
|
-
prompt: async function* (_sid: string, text: string) {
|
|
413
|
-
sentTexts.push(text);
|
|
414
|
-
yield { type: "assistant", blocks: [{ type: "text", text: "done" }] };
|
|
415
|
-
},
|
|
416
|
-
};
|
|
417
|
-
_setAdapterForToolForTest("claude", adapter);
|
|
418
|
-
|
|
419
|
-
await runAgentSession("sid-resume", "first prompt", platform, "chat-resume", Date.now(), "claude");
|
|
420
|
-
await runAgentSession("sid-resume", "second prompt", platform, "chat-resume", Date.now(), "claude");
|
|
421
|
-
|
|
422
|
-
expect(sentTexts).toHaveLength(2);
|
|
423
|
-
for (const text of sentTexts) {
|
|
424
|
-
expect(text).toContain("[ChatCCC IM skill: feishu-skill]");
|
|
425
|
-
expect(text).toContain("[/ChatCCC IM skill: feishu-skill]");
|
|
426
|
-
expect(text).toContain('"session_id":"sid-resume"');
|
|
427
|
-
expect(text).toContain("http://127.0.0.1:");
|
|
428
|
-
expect(text).toContain("/api/agent/send-image");
|
|
429
|
-
expect(text).toContain("[User message]");
|
|
430
|
-
expect(text).toContain("[/User message]");
|
|
431
|
-
}
|
|
432
|
-
expect(sentTexts[0]).toContain("first prompt");
|
|
433
|
-
expect(sentTexts[1]).toContain("second prompt");
|
|
434
|
-
});
|
|
435
|
-
});
|
|
436
|
-
|
|
437
|
-
describe("unified display loop WeChat delta", () => {
|
|
438
|
-
beforeEach(() => {
|
|
439
|
-
vi.useFakeTimers();
|
|
440
|
-
resetState();
|
|
399
|
+
it("re-injects IM skill capabilities for each resumed Claude prompt", async () => {
|
|
400
|
+
const platform = mockPlatform("feishu");
|
|
401
|
+
setSessionPlatform(platform);
|
|
402
|
+
bindChatToSession("sid-resume", "chat-resume");
|
|
403
|
+
recordLastActiveChat("sid-resume", "chat-resume");
|
|
404
|
+
|
|
405
|
+
const sentTexts: string[] = [];
|
|
406
|
+
const adapter: ToolAdapter = {
|
|
407
|
+
displayName: "Claude Code",
|
|
408
|
+
sessionDescPrefix: "Claude Code Session:",
|
|
409
|
+
createSession: async () => ({ sessionId: "sid-resume" }),
|
|
410
|
+
getSessionInfo: async (sid) => ({ sessionId: sid, cwd: "F:\\repo" }),
|
|
411
|
+
closeSession: async () => {},
|
|
412
|
+
prompt: async function* (_sid: string, text: string) {
|
|
413
|
+
sentTexts.push(text);
|
|
414
|
+
yield { type: "assistant", blocks: [{ type: "text", text: "done" }] };
|
|
415
|
+
},
|
|
416
|
+
};
|
|
417
|
+
_setAdapterForToolForTest("claude", adapter);
|
|
418
|
+
|
|
419
|
+
await runAgentSession("sid-resume", "first prompt", platform, "chat-resume", Date.now(), "claude");
|
|
420
|
+
await runAgentSession("sid-resume", "second prompt", platform, "chat-resume", Date.now(), "claude");
|
|
421
|
+
|
|
422
|
+
expect(sentTexts).toHaveLength(2);
|
|
423
|
+
for (const text of sentTexts) {
|
|
424
|
+
expect(text).toContain("[ChatCCC IM skill: feishu-skill]");
|
|
425
|
+
expect(text).toContain("[/ChatCCC IM skill: feishu-skill]");
|
|
426
|
+
expect(text).toContain('"session_id":"sid-resume"');
|
|
427
|
+
expect(text).toContain("http://127.0.0.1:");
|
|
428
|
+
expect(text).toContain("/api/agent/send-image");
|
|
429
|
+
expect(text).toContain("[User message]");
|
|
430
|
+
expect(text).toContain("[/User message]");
|
|
431
|
+
}
|
|
432
|
+
expect(sentTexts[0]).toContain("first prompt");
|
|
433
|
+
expect(sentTexts[1]).toContain("second prompt");
|
|
434
|
+
});
|
|
435
|
+
});
|
|
436
|
+
|
|
437
|
+
describe("unified display loop WeChat delta", () => {
|
|
438
|
+
beforeEach(() => {
|
|
439
|
+
vi.useFakeTimers();
|
|
440
|
+
resetState();
|
|
441
441
|
resetBindingState();
|
|
442
442
|
mockStreamStates.clear();
|
|
443
443
|
});
|
|
@@ -500,79 +500,79 @@ describe("unified display loop WeChat delta", () => {
|
|
|
500
500
|
2,
|
|
501
501
|
"chat-wechat",
|
|
502
502
|
"tool output",
|
|
503
|
-
);
|
|
504
|
-
});
|
|
505
|
-
});
|
|
506
|
-
|
|
507
|
-
describe("unified display loop terminal card update", () => {
|
|
508
|
-
beforeEach(() => {
|
|
509
|
-
vi.useFakeTimers();
|
|
510
|
-
resetState();
|
|
511
|
-
resetBindingState();
|
|
512
|
-
mockStreamStates.clear();
|
|
513
|
-
});
|
|
514
|
-
|
|
515
|
-
afterEach(() => {
|
|
516
|
-
stopUnifiedDisplayLoop();
|
|
517
|
-
resetBindingState();
|
|
518
|
-
vi.useRealTimers();
|
|
519
|
-
});
|
|
520
|
-
|
|
521
|
-
it("does not repeat the same terminal CardKit sequence while the prompt is still active", async () => {
|
|
522
|
-
const platform = mockPlatform("feishu");
|
|
523
|
-
platform.cardUpdate = vi.fn(async () => {
|
|
524
|
-
throw new Error("CardKit update: [300317] ErrMsg: sequence number compare failed; ");
|
|
525
|
-
});
|
|
526
|
-
setSessionPlatform(platform);
|
|
527
|
-
|
|
528
|
-
bindChatToSession("sid-terminal", "chat-terminal");
|
|
529
|
-
recordLastActiveChat("sid-terminal", "chat-terminal");
|
|
530
|
-
sessionInfoMap.set("chat-terminal", {
|
|
531
|
-
sessionId: "sid-terminal",
|
|
532
|
-
turnCount: 1,
|
|
533
|
-
lastContextTokens: 0,
|
|
534
|
-
startTime: 0,
|
|
535
|
-
tool: "claude",
|
|
536
|
-
});
|
|
537
|
-
activePrompts.set("sid-terminal", {
|
|
538
|
-
controller: new AbortController(),
|
|
539
|
-
stopped: false,
|
|
540
|
-
startTime: Date.now(),
|
|
541
|
-
});
|
|
542
|
-
displayCards.set("chat-terminal", {
|
|
543
|
-
cardId: "card-terminal",
|
|
544
|
-
sequence: 109,
|
|
545
|
-
cardBusy: false,
|
|
546
|
-
cardCreatedAt: Date.now(),
|
|
547
|
-
lastSentContent: "",
|
|
548
|
-
streamErrorNotified: false,
|
|
549
|
-
sessionId: "sid-terminal",
|
|
550
|
-
turnCount: 1,
|
|
551
|
-
dotCount: 0,
|
|
552
|
-
});
|
|
553
|
-
mockStreamStates.set("sid-terminal", {
|
|
554
|
-
accumulatedContent: "partial tool output",
|
|
555
|
-
finalReply: "",
|
|
556
|
-
status: "stopped",
|
|
557
|
-
turnCount: 1,
|
|
558
|
-
});
|
|
559
|
-
|
|
560
|
-
startUnifiedDisplayLoop();
|
|
561
|
-
await vi.advanceTimersByTimeAsync(3000);
|
|
562
|
-
await vi.advanceTimersByTimeAsync(3000);
|
|
563
|
-
|
|
564
|
-
expect(platform.cardUpdate).toHaveBeenCalledTimes(1);
|
|
565
|
-
expect(platform.cardUpdate).toHaveBeenCalledWith(
|
|
566
|
-
"card-terminal",
|
|
567
|
-
expect.any(String),
|
|
568
|
-
110,
|
|
569
|
-
);
|
|
570
|
-
expect(displayCards.get("chat-terminal")?.sequence).toBe(110);
|
|
571
|
-
});
|
|
572
|
-
});
|
|
573
|
-
|
|
574
|
-
describe("rebuildBindingsFromRegistry", () => {
|
|
575
|
-
let registryFile = "";
|
|
503
|
+
);
|
|
504
|
+
});
|
|
505
|
+
});
|
|
506
|
+
|
|
507
|
+
describe("unified display loop terminal card update", () => {
|
|
508
|
+
beforeEach(() => {
|
|
509
|
+
vi.useFakeTimers();
|
|
510
|
+
resetState();
|
|
511
|
+
resetBindingState();
|
|
512
|
+
mockStreamStates.clear();
|
|
513
|
+
});
|
|
514
|
+
|
|
515
|
+
afterEach(() => {
|
|
516
|
+
stopUnifiedDisplayLoop();
|
|
517
|
+
resetBindingState();
|
|
518
|
+
vi.useRealTimers();
|
|
519
|
+
});
|
|
520
|
+
|
|
521
|
+
it("does not repeat the same terminal CardKit sequence while the prompt is still active", async () => {
|
|
522
|
+
const platform = mockPlatform("feishu");
|
|
523
|
+
platform.cardUpdate = vi.fn(async () => {
|
|
524
|
+
throw new Error("CardKit update: [300317] ErrMsg: sequence number compare failed; ");
|
|
525
|
+
});
|
|
526
|
+
setSessionPlatform(platform);
|
|
527
|
+
|
|
528
|
+
bindChatToSession("sid-terminal", "chat-terminal");
|
|
529
|
+
recordLastActiveChat("sid-terminal", "chat-terminal");
|
|
530
|
+
sessionInfoMap.set("chat-terminal", {
|
|
531
|
+
sessionId: "sid-terminal",
|
|
532
|
+
turnCount: 1,
|
|
533
|
+
lastContextTokens: 0,
|
|
534
|
+
startTime: 0,
|
|
535
|
+
tool: "claude",
|
|
536
|
+
});
|
|
537
|
+
activePrompts.set("sid-terminal", {
|
|
538
|
+
controller: new AbortController(),
|
|
539
|
+
stopped: false,
|
|
540
|
+
startTime: Date.now(),
|
|
541
|
+
});
|
|
542
|
+
displayCards.set("chat-terminal", {
|
|
543
|
+
cardId: "card-terminal",
|
|
544
|
+
sequence: 109,
|
|
545
|
+
cardBusy: false,
|
|
546
|
+
cardCreatedAt: Date.now(),
|
|
547
|
+
lastSentContent: "",
|
|
548
|
+
streamErrorNotified: false,
|
|
549
|
+
sessionId: "sid-terminal",
|
|
550
|
+
turnCount: 1,
|
|
551
|
+
dotCount: 0,
|
|
552
|
+
});
|
|
553
|
+
mockStreamStates.set("sid-terminal", {
|
|
554
|
+
accumulatedContent: "partial tool output",
|
|
555
|
+
finalReply: "",
|
|
556
|
+
status: "stopped",
|
|
557
|
+
turnCount: 1,
|
|
558
|
+
});
|
|
559
|
+
|
|
560
|
+
startUnifiedDisplayLoop();
|
|
561
|
+
await vi.advanceTimersByTimeAsync(3000);
|
|
562
|
+
await vi.advanceTimersByTimeAsync(3000);
|
|
563
|
+
|
|
564
|
+
expect(platform.cardUpdate).toHaveBeenCalledTimes(1);
|
|
565
|
+
expect(platform.cardUpdate).toHaveBeenCalledWith(
|
|
566
|
+
"card-terminal",
|
|
567
|
+
expect.any(String),
|
|
568
|
+
110,
|
|
569
|
+
);
|
|
570
|
+
expect(displayCards.get("chat-terminal")?.sequence).toBe(110);
|
|
571
|
+
});
|
|
572
|
+
});
|
|
573
|
+
|
|
574
|
+
describe("rebuildBindingsFromRegistry", () => {
|
|
575
|
+
let registryFile = "";
|
|
576
576
|
|
|
577
577
|
beforeEach(async () => {
|
|
578
578
|
chatSessionMap.clear();
|
package/src/cards.ts
CHANGED
|
@@ -32,19 +32,21 @@ export function isCodeBlockOpen(text: string): boolean {
|
|
|
32
32
|
|
|
33
33
|
export function truncateContent(text: string, maxLines = 20, maxChars = 8000): string {
|
|
34
34
|
const lines = text.split("\n");
|
|
35
|
+
// 跳过开头空行
|
|
36
|
+
let startIdx = 0;
|
|
37
|
+
while (startIdx < lines.length && lines[startIdx].trim() === "") {
|
|
38
|
+
startIdx++;
|
|
39
|
+
}
|
|
40
|
+
const effectiveLines = lines.slice(startIdx);
|
|
35
41
|
let displayText: string;
|
|
36
|
-
if (
|
|
37
|
-
const firstLine =
|
|
38
|
-
const lastLines =
|
|
42
|
+
if (effectiveLines.length > maxLines) {
|
|
43
|
+
const firstLine = effectiveLines[0];
|
|
44
|
+
const lastLines = effectiveLines.slice(-(maxLines - 1)).join("\n");
|
|
39
45
|
displayText = firstLine + "\n...\n" + lastLines;
|
|
40
46
|
} else {
|
|
41
47
|
displayText = text;
|
|
42
48
|
}
|
|
43
49
|
|
|
44
|
-
if (displayText.length > maxChars) {
|
|
45
|
-
displayText = "..." + displayText.slice(-maxChars);
|
|
46
|
-
}
|
|
47
|
-
|
|
48
50
|
// 截断后如果代码块未闭合,补上闭合标记,避免后续追加内容时误入代码块
|
|
49
51
|
if (isCodeBlockOpen(displayText)) {
|
|
50
52
|
displayText += "\n```";
|
|
@@ -91,8 +93,8 @@ export function buildProgressCard(
|
|
|
91
93
|
tag: "button",
|
|
92
94
|
text: { tag: "plain_text", content: "查看状态(/state)" },
|
|
93
95
|
type: "default",
|
|
94
|
-
value: { action: "state" },
|
|
95
|
-
element_id: "action_state",
|
|
96
|
+
value: { action: "state" },
|
|
97
|
+
element_id: "action_state",
|
|
96
98
|
});
|
|
97
99
|
elements.push({
|
|
98
100
|
tag: "button",
|
|
@@ -0,0 +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
|
+
});
|