chatccc 0.2.196 → 0.2.198

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 (53) hide show
  1. package/agent-prompts/cursor_specific.md +13 -13
  2. package/bin/cccagent.mjs +17 -17
  3. package/config.sample.json +27 -27
  4. package/package.json +2 -1
  5. package/src/__tests__/agent-reload-config-rpc.test.ts +99 -0
  6. package/src/__tests__/builtin-chat-session.test.ts +277 -181
  7. package/src/__tests__/builtin-cli-json.test.ts +39 -39
  8. package/src/__tests__/builtin-config.test.ts +33 -33
  9. package/src/__tests__/builtin-context.test.ts +163 -163
  10. package/src/__tests__/builtin-file-tools.test.ts +224 -196
  11. package/src/__tests__/builtin-session-select.test.ts +116 -116
  12. package/src/__tests__/builtin-sigint.test.ts +56 -56
  13. package/src/__tests__/cards.test.ts +109 -109
  14. package/src/__tests__/ccc-adapter.test.ts +114 -113
  15. package/src/__tests__/chatgpt-subscription-rpc.test.ts +89 -89
  16. package/src/__tests__/chatgpt-subscription.test.ts +135 -135
  17. package/src/__tests__/chrome-devtools-guard.test.ts +165 -165
  18. package/src/__tests__/claude-raw-stream-log.test.ts +87 -0
  19. package/src/__tests__/codex-raw-stream-log.test.ts +163 -0
  20. package/src/__tests__/config-reload.test.ts +10 -10
  21. package/src/__tests__/config-sample.test.ts +18 -18
  22. package/src/__tests__/cursor-adapter.test.ts +167 -113
  23. package/src/__tests__/feishu-avatar.test.ts +40 -40
  24. package/src/__tests__/jsonl-stream.test.ts +79 -0
  25. package/src/__tests__/orchestrator.test.ts +181 -154
  26. package/src/__tests__/raw-stream-log.test.ts +106 -106
  27. package/src/__tests__/session.test.ts +40 -40
  28. package/src/__tests__/sim-platform.test.ts +12 -12
  29. package/src/__tests__/web-ui.test.ts +209 -209
  30. package/src/adapters/ccc-adapter.ts +121 -119
  31. package/src/adapters/claude-adapter.ts +603 -566
  32. package/src/adapters/codex-adapter.ts +65 -52
  33. package/src/adapters/cursor-adapter.ts +269 -276
  34. package/src/adapters/jsonl-stream.ts +157 -0
  35. package/src/adapters/raw-stream-log.ts +124 -124
  36. package/src/agent-reload-config-rpc.ts +34 -0
  37. package/src/builtin/cli.ts +473 -461
  38. package/src/builtin/context.ts +323 -323
  39. package/src/builtin/file-tools.ts +1072 -915
  40. package/src/builtin/index.ts +404 -353
  41. package/src/builtin/session-select.ts +48 -48
  42. package/src/builtin/sigint.ts +50 -50
  43. package/src/cards.ts +195 -195
  44. package/src/chatgpt-subscription-rpc.ts +27 -27
  45. package/src/chatgpt-subscription.ts +299 -299
  46. package/src/chrome-devtools-guard.ts +318 -318
  47. package/src/config.ts +125 -125
  48. package/src/feishu-api.ts +49 -49
  49. package/src/index.ts +8 -13
  50. package/src/orchestrator.ts +166 -145
  51. package/src/runtime-reload.ts +34 -0
  52. package/src/session.ts +141 -141
  53. package/src/web-ui.ts +205 -205
@@ -1,16 +1,17 @@
1
- import { describe, it, expect } from "vitest";
2
- import { EventEmitter } from "node:events";
3
- import { readFileSync } from "node:fs";
4
- import { join, dirname } from "node:path";
5
- import { PassThrough } from "node:stream";
6
- import type { ChildProcess } from "node:child_process";
7
- import { fileURLToPath } from "node:url";
8
- import {
9
- normalizeCursorMessage,
10
- createCursorAdapter,
11
- formatCursorAgentEmptyOutputMessage,
12
- } from "../adapters/cursor-adapter.ts";
13
- import type { UnifiedStreamMessage } from "../adapters/adapter-interface.ts";
1
+ import { afterEach, describe, it, expect, vi } from "vitest";
2
+ import { EventEmitter } from "node:events";
3
+ import { readFileSync } from "node:fs";
4
+ import { join, dirname } from "node:path";
5
+ import { PassThrough } from "node:stream";
6
+ import type { ChildProcess } from "node:child_process";
7
+ import { fileURLToPath } from "node:url";
8
+ import {
9
+ normalizeCursorMessage,
10
+ createCursorAdapter,
11
+ formatCursorAgentEmptyOutputMessage,
12
+ } from "../adapters/cursor-adapter.ts";
13
+ import { BadJsonIdleTimeoutError } from "../adapters/jsonl-stream.ts";
14
+ import type { UnifiedStreamMessage } from "../adapters/adapter-interface.ts";
14
15
  import type {
15
16
  CursorSessionMeta,
16
17
  CursorSessionMetaStore,
@@ -44,43 +45,70 @@ function createInMemoryMetaStore(
44
45
  };
45
46
  }
46
47
 
47
- const __dirname = dirname(fileURLToPath(import.meta.url));
48
-
49
- type CursorSpawnForTest = NonNullable<
50
- NonNullable<Parameters<typeof createCursorAdapter>[0]>["spawn"]
51
- >;
52
-
53
- function readFixture(name: string): unknown[] {
54
- const raw = readFileSync(join(__dirname, "fixtures", name), "utf-8");
55
- return raw.split(/\r?\n/).filter(Boolean).map((line) => JSON.parse(line));
56
- }
57
-
58
- function createMockCursorProcess(args: {
59
- stdout?: string;
60
- stderr?: string;
61
- exitCode?: number;
62
- }): ChildProcess {
63
- const child = new EventEmitter() as ChildProcess;
64
- const stdout = new PassThrough();
65
- const stderr = new PassThrough();
66
- const stdin = new PassThrough();
67
- Object.assign(child, {
68
- stdout,
69
- stderr,
70
- stdin,
71
- pid: undefined,
72
- });
73
-
74
- setImmediate(() => {
75
- if (args.stdout) stdout.write(args.stdout);
76
- if (args.stderr) stderr.write(args.stderr);
77
- stdout.end();
78
- stderr.end();
79
- child.emit("close", args.exitCode ?? 0, null);
80
- });
81
-
82
- return child;
83
- }
48
+ const __dirname = dirname(fileURLToPath(import.meta.url));
49
+
50
+ type CursorSpawnForTest = NonNullable<
51
+ NonNullable<Parameters<typeof createCursorAdapter>[0]>["spawn"]
52
+ >;
53
+
54
+ function readFixture(name: string): unknown[] {
55
+ const raw = readFileSync(join(__dirname, "fixtures", name), "utf-8");
56
+ return raw.split(/\r?\n/).filter(Boolean).map((line) => JSON.parse(line));
57
+ }
58
+
59
+ function createMockCursorProcess(args: {
60
+ stdout?: string;
61
+ stderr?: string;
62
+ exitCode?: number;
63
+ }): ChildProcess {
64
+ const child = new EventEmitter() as ChildProcess;
65
+ const stdout = new PassThrough();
66
+ const stderr = new PassThrough();
67
+ const stdin = new PassThrough();
68
+ Object.assign(child, {
69
+ stdout,
70
+ stderr,
71
+ stdin,
72
+ pid: undefined,
73
+ });
74
+
75
+ setImmediate(() => {
76
+ if (args.stdout) stdout.write(args.stdout);
77
+ if (args.stderr) stderr.write(args.stderr);
78
+ stdout.end();
79
+ stderr.end();
80
+ child.emit("close", args.exitCode ?? 0, null);
81
+ });
82
+
83
+ return child;
84
+ }
85
+
86
+ function createHangingMockCursorProcess(args: {
87
+ stdout?: string;
88
+ stderr?: string;
89
+ }): ChildProcess {
90
+ const child = new EventEmitter() as ChildProcess;
91
+ const stdout = new PassThrough();
92
+ const stderr = new PassThrough();
93
+ const stdin = new PassThrough();
94
+ Object.assign(child, {
95
+ stdout,
96
+ stderr,
97
+ stdin,
98
+ pid: undefined,
99
+ });
100
+
101
+ setTimeout(() => {
102
+ if (args.stdout) stdout.write(args.stdout);
103
+ if (args.stderr) stderr.write(args.stderr);
104
+ }, 0);
105
+
106
+ return child;
107
+ }
108
+
109
+ afterEach(() => {
110
+ vi.useRealTimers();
111
+ });
84
112
 
85
113
  // ---------------------------------------------------------------------------
86
114
  // normalizeCursorMessage — 核心映射逻辑测试(纯函数)
@@ -680,7 +708,7 @@ describe("Cursor stream fixture - 端到端不重复", () => {
680
708
  });
681
709
  });
682
710
 
683
- it("mapToolCallKey: maps known keys to readable names", () => {
711
+ it("mapToolCallKey: maps known keys to readable names", () => {
684
712
  const cases: [string, string][] = [
685
713
  ["globToolCall", "Glob"],
686
714
  ["shellToolCall", "Bash"],
@@ -696,65 +724,91 @@ describe("Cursor stream fixture - 端到端不重复", () => {
696
724
  tool_call: { [raw]: { args: {} } },
697
725
  } as Parameters<typeof normalizeCursorMessage>[0]);
698
726
  expect(r!.blocks[0]).toMatchObject({ type: "tool_use", name: expected });
699
- }
700
- });
701
- });
702
-
703
- describe("Cursor adapter process failures", () => {
704
- it("formats empty stdout auth stderr as a cautious visible message", () => {
705
- const message = formatCursorAgentEmptyOutputMessage({
706
- exitCode: 1,
707
- stdoutLength: 0,
708
- stderr: "Error: Authentication required. Please run 'agent login' first, or set CURSOR_API_KEY environment variable.\n",
709
- });
710
-
711
- expect(message).toContain("检测到认证相关错误");
712
- expect(message).toContain("可能需要重新登录 Cursor Agent");
713
- expect(message).toContain("CURSOR_API_KEY");
714
- expect(message).toContain("agent status");
715
- expect(message).toContain("agent login");
716
- expect(message).not.toContain("登录态已失效");
717
- });
718
-
719
- it("does not format a message when stdout is non-empty", () => {
720
- expect(
721
- formatCursorAgentEmptyOutputMessage({
722
- exitCode: 1,
723
- stdoutLength: 10,
724
- stderr: "Error: Authentication required",
725
- }),
726
- ).toBeNull();
727
- });
728
-
729
- it("prompt surfaces auth-related empty output before failing the stream", async () => {
730
- const store = createInMemoryMetaStore({ sid: { cwd: "F:/repo" } });
731
- const spawnImpl = (() =>
732
- createMockCursorProcess({
733
- exitCode: 1,
734
- stderr: "Error: Authentication required. Please run 'agent login' first, or set CURSOR_API_KEY environment variable.\n",
735
- })) as CursorSpawnForTest;
736
- const adapter = createCursorAdapter({ metaStore: store, spawn: spawnImpl });
737
- const iterator = adapter.prompt(
738
- "sid",
739
- "[User message]\nhello\n[/User message]",
740
- "F:/repo",
741
- )[Symbol.asyncIterator]();
742
-
743
- const first = await iterator.next();
744
- expect(first.done).toBe(false);
745
- expect(first.value.blocks).toHaveLength(1);
746
- expect(first.value.blocks[0]).toMatchObject({ type: "text_final" });
747
- expect(first.value.blocks[0]).toHaveProperty(
748
- "text",
749
- expect.stringContaining("可能需要重新登录 Cursor Agent"),
750
- );
751
- expect(first.value.blocks[0]).toHaveProperty(
752
- "text",
753
- expect.not.stringContaining("登录态已失效"),
754
- );
755
-
756
- await expect(iterator.next()).rejects.toThrow(
757
- /Cursor Agent exited without stream-json output/,
758
- );
759
- });
760
- });
727
+ }
728
+ });
729
+ });
730
+
731
+ describe("Cursor adapter process failures", () => {
732
+ it("formats empty stdout auth stderr as a cautious visible message", () => {
733
+ const message = formatCursorAgentEmptyOutputMessage({
734
+ exitCode: 1,
735
+ stdoutLength: 0,
736
+ stderr: "Error: Authentication required. Please run 'agent login' first, or set CURSOR_API_KEY environment variable.\n",
737
+ });
738
+
739
+ expect(message).toContain("检测到认证相关错误");
740
+ expect(message).toContain("可能需要重新登录 Cursor Agent");
741
+ expect(message).toContain("CURSOR_API_KEY");
742
+ expect(message).toContain("agent status");
743
+ expect(message).toContain("agent login");
744
+ expect(message).not.toContain("登录态已失效");
745
+ });
746
+
747
+ it("does not format a message when stdout is non-empty", () => {
748
+ expect(
749
+ formatCursorAgentEmptyOutputMessage({
750
+ exitCode: 1,
751
+ stdoutLength: 10,
752
+ stderr: "Error: Authentication required",
753
+ }),
754
+ ).toBeNull();
755
+ });
756
+
757
+ it("prompt surfaces auth-related empty output before failing the stream", async () => {
758
+ const store = createInMemoryMetaStore({ sid: { cwd: "F:/repo" } });
759
+ const spawnImpl = (() =>
760
+ createMockCursorProcess({
761
+ exitCode: 1,
762
+ stderr: "Error: Authentication required. Please run 'agent login' first, or set CURSOR_API_KEY environment variable.\n",
763
+ })) as CursorSpawnForTest;
764
+ const adapter = createCursorAdapter({ metaStore: store, spawn: spawnImpl });
765
+ const iterator = adapter.prompt(
766
+ "sid",
767
+ "[User message]\nhello\n[/User message]",
768
+ "F:/repo",
769
+ )[Symbol.asyncIterator]();
770
+
771
+ const first = await iterator.next();
772
+ expect(first.done).toBe(false);
773
+ expect(first.value.blocks).toHaveLength(1);
774
+ expect(first.value.blocks[0]).toMatchObject({ type: "text_final" });
775
+ expect(first.value.blocks[0]).toHaveProperty(
776
+ "text",
777
+ expect.stringContaining("可能需要重新登录 Cursor Agent"),
778
+ );
779
+ expect(first.value.blocks[0]).toHaveProperty(
780
+ "text",
781
+ expect.not.stringContaining("登录态已失效"),
782
+ );
783
+
784
+ await expect(iterator.next()).rejects.toThrow(
785
+ /Cursor Agent exited without stream-json output/,
786
+ );
787
+ });
788
+
789
+ it("prompt fails when Cursor emits bad JSON and then leaves stdout idle", async () => {
790
+ vi.useFakeTimers();
791
+ const store = createInMemoryMetaStore({ sid: { cwd: "F:/repo" } });
792
+ const spawnImpl = (() =>
793
+ createHangingMockCursorProcess({
794
+ stdout: "{\"type\":\"tool_call\",\"subtype\":\"started\"\n",
795
+ })) as CursorSpawnForTest;
796
+ const adapter = createCursorAdapter({ metaStore: store, spawn: spawnImpl });
797
+
798
+ const pending = (async () => {
799
+ for await (const _event of adapter.prompt(
800
+ "sid",
801
+ "[User message]\nhello\n[/User message]",
802
+ "F:/repo",
803
+ )) {
804
+ // No normalized events are expected before the watchdog fires.
805
+ }
806
+ })().catch((error: unknown) => error);
807
+
808
+ await vi.advanceTimersByTimeAsync(0);
809
+ await vi.advanceTimersByTimeAsync(120_000);
810
+
811
+ const error = await pending;
812
+ expect(error).toBeInstanceOf(BadJsonIdleTimeoutError);
813
+ });
814
+ });
@@ -1,4 +1,4 @@
1
- import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
1
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
4
 
@@ -68,7 +68,7 @@ function mockAvatarFetch(uploadedNames: string[], usageResponse: Response): void
68
68
  }));
69
69
  }
70
70
 
71
- function mockAvatarUploadOnlyFetch(uploadedNames: string[]): ReturnType<typeof vi.fn> {
71
+ function mockAvatarUploadOnlyFetch(uploadedNames: string[]): ReturnType<typeof vi.fn> {
72
72
  const fetchMock = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
73
73
  const urlText = String(url);
74
74
  if (urlText === "https://open.feishu.test/im/v1/images") {
@@ -83,44 +83,44 @@ function mockAvatarUploadOnlyFetch(uploadedNames: string[]): ReturnType<typeof v
83
83
  throw new Error(`unexpected fetch: ${urlText}`);
84
84
  });
85
85
  vi.stubGlobal("fetch", fetchMock);
86
- return fetchMock;
87
- }
88
-
89
- describe("Plain avatar fallback", () => {
90
- afterEach(() => {
91
- vi.unstubAllGlobals();
92
- vi.doUnmock("node:os");
93
- vi.doUnmock("../config.ts");
94
- vi.doUnmock("../cursor-usage.ts");
95
- vi.restoreAllMocks();
96
- getCursorUsageSummaryMock.mockReset();
97
- mockConfig.cursor.avatarBatteryMode = "apiPercent";
98
- mockConfig.cursor.onDemandMonthlyBudget = 1000;
99
- });
100
-
101
- it("uses a status-only avatar for unknown tools instead of falling back to Claude", async () => {
102
- const homeDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-home-"));
103
- const userDataDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-data-"));
104
- const uploadedNames: string[] = [];
105
- mockAvatarUploadOnlyFetch(uploadedNames);
106
-
107
- try {
108
- const { setChatAvatar } = await loadFeishuApiWithHome(homeDir, userDataDir);
109
- await setChatAvatar("tenant-token", "chat_1", "ccc", "new");
110
-
111
- expect(uploadedNames).toEqual(["avatar_plain_new.jpg"]);
112
- const cacheRaw = await readFile(join(userDataDir, "state", "avatar-image-keys.json"), "utf-8");
113
- const cache = JSON.parse(cacheRaw) as Record<string, string>;
114
- expect(cache["plain:new"]).toBe("img_test");
115
- expect(cache["claude:new"]).toBeUndefined();
116
- } finally {
117
- await rm(homeDir, { recursive: true, force: true });
118
- await rm(userDataDir, { recursive: true, force: true });
119
- }
120
- });
121
- });
122
-
123
- describe("Codex avatar usage battery", () => {
86
+ return fetchMock;
87
+ }
88
+
89
+ describe("Plain avatar fallback", () => {
90
+ afterEach(() => {
91
+ vi.unstubAllGlobals();
92
+ vi.doUnmock("node:os");
93
+ vi.doUnmock("../config.ts");
94
+ vi.doUnmock("../cursor-usage.ts");
95
+ vi.restoreAllMocks();
96
+ getCursorUsageSummaryMock.mockReset();
97
+ mockConfig.cursor.avatarBatteryMode = "apiPercent";
98
+ mockConfig.cursor.onDemandMonthlyBudget = 1000;
99
+ });
100
+
101
+ it("uses a status-only avatar for unknown tools instead of falling back to Claude", async () => {
102
+ const homeDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-home-"));
103
+ const userDataDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-data-"));
104
+ const uploadedNames: string[] = [];
105
+ mockAvatarUploadOnlyFetch(uploadedNames);
106
+
107
+ try {
108
+ const { setChatAvatar } = await loadFeishuApiWithHome(homeDir, userDataDir);
109
+ await setChatAvatar("tenant-token", "chat_1", "ccc", "new");
110
+
111
+ expect(uploadedNames).toEqual(["avatar_plain_new.jpg"]);
112
+ const cacheRaw = await readFile(join(userDataDir, "state", "avatar-image-keys.json"), "utf-8");
113
+ const cache = JSON.parse(cacheRaw) as Record<string, string>;
114
+ expect(cache["plain:new"]).toBe("img_test");
115
+ expect(cache["claude:new"]).toBeUndefined();
116
+ } finally {
117
+ await rm(homeDir, { recursive: true, force: true });
118
+ await rm(userDataDir, { recursive: true, force: true });
119
+ }
120
+ });
121
+ });
122
+
123
+ describe("Codex avatar usage battery", () => {
124
124
  afterEach(() => {
125
125
  vi.unstubAllGlobals();
126
126
  vi.doUnmock("node:os");
@@ -0,0 +1,79 @@
1
+ import { PassThrough } from "node:stream";
2
+
3
+ import { afterEach, describe, expect, it, vi } from "vitest";
4
+
5
+ import {
6
+ BadJsonIdleTimeoutError,
7
+ readJsonLinesWithBadJsonIdleWatchdog,
8
+ } from "../adapters/jsonl-stream.ts";
9
+
10
+ function createReader(input: PassThrough, idleTimeoutMs = 100): AsyncIterator<unknown> {
11
+ return readJsonLinesWithBadJsonIdleWatchdog({
12
+ input,
13
+ tool: "test-agent",
14
+ tag: "sid-test",
15
+ idleTimeoutMs,
16
+ parse: (line) => JSON.parse(line) as unknown,
17
+ })[Symbol.asyncIterator]();
18
+ }
19
+
20
+ afterEach(() => {
21
+ vi.useRealTimers();
22
+ });
23
+
24
+ describe("readJsonLinesWithBadJsonIdleWatchdog", () => {
25
+ it("throws when a JSON-like bad line remains the last stdout past the idle timeout", async () => {
26
+ vi.useFakeTimers();
27
+ const input = new PassThrough();
28
+ const iterator = createReader(input);
29
+
30
+ const pending = iterator.next().catch((error: unknown) => error);
31
+ input.write("{\"type\":\"tool_call\",\"subtype\":\"started\"\n");
32
+
33
+ await vi.advanceTimersByTimeAsync(100);
34
+
35
+ const error = await pending;
36
+ expect(error).toBeInstanceOf(BadJsonIdleTimeoutError);
37
+ expect(error).toMatchObject({
38
+ code: "BAD_JSON_IDLE_TIMEOUT",
39
+ tool: "test-agent",
40
+ tag: "sid-test",
41
+ });
42
+ });
43
+
44
+ it("does not throw when a valid JSON line arrives after the bad line before timeout", async () => {
45
+ vi.useFakeTimers();
46
+ const input = new PassThrough();
47
+ const iterator = createReader(input);
48
+
49
+ const pending = iterator.next();
50
+ input.write("{\"type\":\"tool_call\"\n");
51
+ await vi.advanceTimersByTimeAsync(50);
52
+ input.write("{\"type\":\"ok\"}\n");
53
+
54
+ await expect(pending).resolves.toEqual({
55
+ done: false,
56
+ value: { type: "ok" },
57
+ });
58
+
59
+ const done = iterator.next();
60
+ input.end();
61
+ await expect(done).resolves.toEqual({ done: true, value: undefined });
62
+ });
63
+
64
+ it("ignores non-JSON banner lines for the bad JSON idle watchdog", async () => {
65
+ vi.useFakeTimers();
66
+ const input = new PassThrough();
67
+ const iterator = createReader(input);
68
+
69
+ const pending = iterator.next();
70
+ input.write("Reading prompt from stdin...\n");
71
+ await vi.advanceTimersByTimeAsync(200);
72
+ input.write("{\"type\":\"ok\"}\n");
73
+
74
+ await expect(pending).resolves.toEqual({
75
+ done: false,
76
+ value: { type: "ok" },
77
+ });
78
+ });
79
+ });