chatccc 0.2.232 → 0.2.233

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chatccc",
3
- "version": "0.2.232",
3
+ "version": "0.2.233",
4
4
  "description": "Feishu bot bridge for Claude Code",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -1,9 +1,15 @@
1
1
  import { mkdtemp, readFile, rm } from "node:fs/promises";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
+ import { EventEmitter } from "node:events";
4
5
  import { describe, it, expect, vi } from "vitest";
5
6
 
6
- import { buildCrashLoggingHandlers, installCrashLogging, setupFileLogging } from "../shared.ts";
7
+ import {
8
+ buildCrashLoggingHandlers,
9
+ installCrashLogging,
10
+ installEpipeGuard,
11
+ setupFileLogging,
12
+ } from "../shared.ts";
7
13
 
8
14
  describe("buildCrashLoggingHandlers", () => {
9
15
  it("uncaughtException: 写诊断、刷新日志、调用 onFatal", () => {
@@ -212,6 +218,69 @@ describe("installCrashLogging", () => {
212
218
  });
213
219
  });
214
220
 
221
+ describe("installEpipeGuard", () => {
222
+ function fakeStream(): EventEmitter & { on: typeof EventEmitter.prototype.on; off: typeof EventEmitter.prototype.off } {
223
+ return new EventEmitter() as unknown as EventEmitter & {
224
+ on: typeof EventEmitter.prototype.on;
225
+ off: typeof EventEmitter.prototype.off;
226
+ };
227
+ }
228
+
229
+ it("吞掉 EPIPE 写错误并记录非致命 trace,不抛出", () => {
230
+ const stream = fakeStream();
231
+ const tracer = vi.fn();
232
+ const cleanup = installEpipeGuard([stream as never], { tracer });
233
+
234
+ const err = Object.assign(new Error("broken pipe"), { code: "EPIPE" });
235
+ expect(() => stream.emit("error", err)).not.toThrow();
236
+ expect(tracer).toHaveBeenCalledWith(
237
+ "stdio write error (non-fatal)",
238
+ expect.objectContaining({ code: "EPIPE" }),
239
+ );
240
+
241
+ cleanup();
242
+ });
243
+
244
+ it("其它 IO 错误同样非致命(日志失败不能拖垮服务)", () => {
245
+ const stream = fakeStream();
246
+ const tracer = vi.fn();
247
+ const cleanup = installEpipeGuard([stream as never], { tracer });
248
+
249
+ const err = Object.assign(new Error("permission denied"), { code: "EACCES" });
250
+ expect(() => stream.emit("error", err)).not.toThrow();
251
+ expect(tracer).toHaveBeenCalledWith(
252
+ "stdio write error (non-fatal)",
253
+ expect.objectContaining({ code: "EACCES" }),
254
+ );
255
+
256
+ cleanup();
257
+ });
258
+
259
+ it("cleanup 后不再监听,错误可正常传播", () => {
260
+ const stream = fakeStream();
261
+ const tracer = vi.fn();
262
+ const cleanup = installEpipeGuard([stream as never], { tracer });
263
+ cleanup();
264
+
265
+ expect(() => stream.emit("error", new Error("boom"))).toThrow("boom");
266
+ expect(tracer).not.toHaveBeenCalled();
267
+ });
268
+
269
+ it("默认同时守护 stdout 与 stderr", () => {
270
+ const stdoutBefore = process.stdout.listenerCount("error");
271
+ const stderrBefore = process.stderr.listenerCount("error");
272
+ const cleanup = installEpipeGuard(undefined, { tracer: () => {} });
273
+ try {
274
+ expect(process.stdout.listenerCount("error")).toBe(stdoutBefore + 1);
275
+ expect(process.stderr.listenerCount("error")).toBe(stderrBefore + 1);
276
+ } finally {
277
+ cleanup();
278
+ expect(process.stdout.listenerCount("error")).toBe(stdoutBefore);
279
+ expect(process.stderr.listenerCount("error")).toBe(stderrBefore);
280
+ }
281
+ });
282
+ });
283
+
215
284
  describe("setupFileLogging", () => {
216
285
  it("flush 后继续写日志不会触发 write after end,且日志已落盘", async () => {
217
286
  const originalLog = console.log;
@@ -263,4 +332,29 @@ describe("setupFileLogging", () => {
263
332
  await rm(dir, { recursive: true, force: true });
264
333
  }
265
334
  });
335
+
336
+ it("console.warn 也会落盘并包含 WARN 级别标记", async () => {
337
+ const originalLog = console.log;
338
+ const originalError = console.error;
339
+ const originalWarn = console.warn;
340
+ console.log = vi.fn() as never;
341
+ console.error = vi.fn() as never;
342
+ console.warn = vi.fn() as never;
343
+ const dir = await mkdtemp(join(tmpdir(), "chatccc-log-"));
344
+
345
+ try {
346
+ const fileLog = setupFileLogging(dir, "index");
347
+
348
+ expect(() => console.warn("sdk warning")).not.toThrow();
349
+ fileLog.flush();
350
+
351
+ const content = await readFile(fileLog.logPath, "utf8");
352
+ expect(content).toContain("[WARN] sdk warning");
353
+ } finally {
354
+ console.log = originalLog;
355
+ console.error = originalError;
356
+ console.warn = originalWarn;
357
+ await rm(dir, { recursive: true, force: true });
358
+ }
359
+ });
266
360
  });
@@ -1,132 +1,177 @@
1
- import { EventEmitter } from "node:events";
2
- import { join } from "node:path";
3
-
4
- import { describe, expect, it, vi } from "vitest";
5
-
6
- import {
7
- buildRestartSpawnSpec,
8
- decideRestartParentExit,
9
- spawnRestartChild,
10
- RESTART_CHILD_READY_MS,
11
- } from "../orchestrator.ts";
12
- import { INTERNAL_RESTART_ENV_VAR } from "../startup-lifecycle.ts";
13
-
14
- describe("buildRestartSpawnSpec", () => {
15
- it("spawns node directly with the local tsx CLI (never via npx/npm)", () => {
16
- const spec = buildRestartSpawnSpec("F:/proj");
17
- expect(spec.command).toBe(process.execPath);
18
- expect(spec.args[0]).toBe(join("F:/proj", "node_modules", "tsx", "dist", "cli.mjs"));
19
- expect(spec.args[1]).toBe("src/index.ts");
20
- expect([spec.command, ...spec.args].join(" ")).not.toMatch(/npx|npm/i);
21
- });
22
-
23
- it("accepts the default project root", () => {
24
- const spec = buildRestartSpawnSpec();
25
- expect(spec.command).toBe(process.execPath);
26
- expect(spec.args[0]).toContain("tsx");
27
- });
28
- });
29
-
30
- describe("spawnRestartChild", () => {
31
- class FakeChild extends EventEmitter {
32
- pid = 12345;
33
- exitCode: number | null = null;
34
- signalCode: number | string | null = null;
35
- unref = vi.fn();
36
- stderr = new EventEmitter();
37
- }
38
-
39
- it("spawns without a shell, captures stderr, and marks the internal restart env", () => {
40
- const fake = new FakeChild();
41
- const spawnImpl = vi.fn(() => fake as never);
42
- const trace = vi.fn();
43
-
44
- const child = spawnRestartChild({ projectRoot: "F:/proj", spawnImpl, trace });
45
-
46
- expect(child).toBe(fake);
47
- expect(spawnImpl).toHaveBeenCalledWith(
48
- process.execPath,
49
- [join("F:/proj", "node_modules", "tsx", "dist", "cli.mjs"), "src/index.ts"],
50
- expect.objectContaining({
51
- detached: true,
52
- stdio: ["ignore", "ignore", "pipe"],
53
- env: expect.objectContaining({ [INTERNAL_RESTART_ENV_VAR]: "1" }),
54
- // 不使用 shell:避免 npm/npx 的 PATH 注入问题
55
- shell: false,
56
- }),
57
- );
58
- // spawnImpl 收到的 command/args 中不得出现 npx/npm(env 里的 npm_* 变量不算)
59
- const firstCall = spawnImpl.mock.calls[0] as unknown as [string, string[]];
60
- const [cmd, args] = firstCall;
61
- expect([cmd, ...args].join(" ")).not.toMatch(/npx|npm/i);
62
- });
63
-
64
- it("writes captured stderr into the trace on child exit", () => {
65
- const fake = new FakeChild();
66
- const spawnImpl = vi.fn(() => fake as never);
67
- const trace = vi.fn();
68
-
69
- spawnRestartChild({ projectRoot: "F:/proj", spawnImpl, trace });
70
-
71
- fake.stderr.emit("data", Buffer.from("tsx error line 1\n"));
72
- fake.stderr.emit("data", Buffer.from("tsx error line 2\n"));
73
- fake.exitCode = 1;
74
- fake.emit("exit", 1, null);
75
-
76
- const exitCall = trace.mock.calls.find(([name]) => name === "restart: child exit");
77
- expect(exitCall).toBeTruthy();
78
- expect(exitCall![1]).toEqual(expect.objectContaining({
79
- childPid: 12345,
80
- code: 1,
81
- signal: null,
82
- }));
83
- expect(exitCall![1].stderr).toContain("tsx error line 1");
84
- expect(exitCall![1].stderr).toContain("tsx error line 2");
85
- });
86
- });
87
-
88
- describe("decideRestartParentExit", () => {
89
- it("returns false (parent stays alive) when the child dies during the window", async () => {
90
- const child = { exitCode: 1, signalCode: null, pid: 42 } as never;
91
- const trace = vi.fn();
92
-
93
- const shouldExit = await decideRestartParentExit(child, 200, 50, trace);
94
-
95
- expect(shouldExit).toBe(false);
96
- expect(trace).toHaveBeenCalledWith(
97
- "restart: child died during window, keeping parent",
98
- expect.objectContaining({ childPid: 42, exitCode: 1 }),
99
- );
100
- });
101
-
102
- it("returns true (parent exits) when the child stays alive through the window", async () => {
103
- const child = { exitCode: null, signalCode: null, pid: 42 } as never;
104
- const trace = vi.fn();
105
-
106
- const shouldExit = await decideRestartParentExit(child, 150, 30, trace);
107
-
108
- expect(shouldExit).toBe(true);
109
- expect(trace).toHaveBeenCalledWith(
110
- "restart: child alive after window, parent exiting",
111
- expect.objectContaining({ childPid: 42 }),
112
- );
113
- });
114
-
115
- it("surfaces a child that died with a signal", async () => {
116
- const child = { exitCode: null, signalCode: "SIGKILL", pid: 42 } as never;
117
- const trace = vi.fn();
118
-
119
- const shouldExit = await decideRestartParentExit(child, 100, 25, trace);
120
-
121
- expect(shouldExit).toBe(false);
122
- expect(trace).toHaveBeenCalledWith(
123
- "restart: child died during window, keeping parent",
124
- expect.objectContaining({ signalCode: "SIGKILL" }),
125
- );
126
- });
127
-
128
- it("exports a sane default readiness window", () => {
129
- expect(RESTART_CHILD_READY_MS).toBeGreaterThan(0);
130
- expect(RESTART_CHILD_READY_MS).toBeLessThan(60_000);
131
- });
132
- });
1
+ import { EventEmitter } from "node:events";
2
+ import { mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+
6
+ import { describe, expect, it, vi, afterEach } from "vitest";
7
+
8
+ import {
9
+ buildRestartSpawnSpec,
10
+ decideRestartParentExit,
11
+ spawnRestartChild,
12
+ RESTART_CHILD_READY_MS,
13
+ } from "../orchestrator.ts";
14
+ import { INTERNAL_RESTART_ENV_VAR } from "../startup-lifecycle.ts";
15
+
16
+ describe("buildRestartSpawnSpec", () => {
17
+ it("spawns node directly with the local tsx CLI (never via npx/npm)", () => {
18
+ const spec = buildRestartSpawnSpec("F:/proj");
19
+ expect(spec.command).toBe(process.execPath);
20
+ expect(spec.args[0]).toBe(join("F:/proj", "node_modules", "tsx", "dist", "cli.mjs"));
21
+ expect(spec.args[1]).toBe("src/index.ts");
22
+ expect([spec.command, ...spec.args].join(" ")).not.toMatch(/npx|npm/i);
23
+ });
24
+
25
+ it("accepts the default project root", () => {
26
+ const spec = buildRestartSpawnSpec();
27
+ expect(spec.command).toBe(process.execPath);
28
+ expect(spec.args[0]).toContain("tsx");
29
+ });
30
+ });
31
+
32
+ describe("spawnRestartChild", () => {
33
+ class FakeChild extends EventEmitter {
34
+ pid = 12345;
35
+ exitCode: number | null = null;
36
+ signalCode: number | string | null = null;
37
+ unref = vi.fn();
38
+ stderr = new EventEmitter();
39
+ }
40
+
41
+ let tmpDirs: string[] = [];
42
+ afterEach(async () => {
43
+ for (const dir of tmpDirs) await rm(dir, { recursive: true, force: true });
44
+ tmpDirs = [];
45
+ });
46
+
47
+ async function tmpLogDir(): Promise<string> {
48
+ const dir = await mkdtemp(join(tmpdir(), "chatccc-restart-"));
49
+ tmpDirs.push(dir);
50
+ return dir;
51
+ }
52
+
53
+ it("spawns without a shell, redirects stderr to a restart log file, and marks the internal restart env", async () => {
54
+ const logDir = await tmpLogDir();
55
+ const fake = new FakeChild();
56
+ const spawnImpl = vi.fn(() => fake as never);
57
+ const trace = vi.fn();
58
+
59
+ const child = spawnRestartChild({ projectRoot: "F:/proj", spawnImpl, trace, restartLogDir: logDir });
60
+
61
+ expect(child).toBe(fake);
62
+ expect(spawnImpl).toHaveBeenCalledWith(
63
+ process.execPath,
64
+ [join("F:/proj", "node_modules", "tsx", "dist", "cli.mjs"), "src/index.ts"],
65
+ expect.objectContaining({
66
+ detached: true,
67
+ env: expect.objectContaining({ [INTERNAL_RESTART_ENV_VAR]: "1" }),
68
+ // 不使用 shell:避免 npm/npx 的 PATH 注入问题
69
+ shell: false,
70
+ }),
71
+ );
72
+ // spawnImpl 收到的 command/args 中不得出现 npx/npm(env 里的 npm_* 变量不算)
73
+ const firstCall = spawnImpl.mock.calls[0] as unknown as [string, string[]];
74
+ const [cmd, args] = firstCall;
75
+ expect([cmd, ...args].join(" ")).not.toMatch(/npx|npm/i);
76
+
77
+ // stderr 指向磁盘日志文件(fd),而不是 pipe:pipe 读端随父进程退出关闭后,
78
+ // 子进程写 stderr 会 EPIPE 崩溃(飞书 SDK console.warn 崩溃根因)。
79
+ const callArgs = spawnImpl.mock.calls[0] as unknown as Array<unknown>;
80
+ const stdio = (callArgs[2] as { stdio: unknown[] }).stdio;
81
+ expect(stdio[0]).toBe("ignore");
82
+ expect(stdio[1]).toBe("ignore");
83
+ expect(typeof stdio[2]).toBe("number");
84
+ expect(stdio[2] as number).toBeGreaterThan(2);
85
+
86
+ const files = await readdir(logDir);
87
+ expect(files.some((f) => f.startsWith("restart-") && f.endsWith(".log"))).toBe(true);
88
+ });
89
+
90
+ it("records child exit code/signal in trace without pipe capture", async () => {
91
+ const logDir = await tmpLogDir();
92
+ const fake = new FakeChild();
93
+ const spawnImpl = vi.fn(() => fake as never);
94
+ const trace = vi.fn();
95
+
96
+ spawnRestartChild({ projectRoot: "F:/proj", spawnImpl, trace, restartLogDir: logDir });
97
+
98
+ fake.exitCode = 1;
99
+ fake.emit("exit", 1, null);
100
+
101
+ const exitCall = trace.mock.calls.find(([name]) => name === "restart: child exit");
102
+ expect(exitCall).toBeTruthy();
103
+ expect(exitCall![1]).toEqual(expect.objectContaining({
104
+ childPid: 12345,
105
+ code: 1,
106
+ signal: null,
107
+ }));
108
+ // 不再用 pipe 收集 stderr,trace 里不再有 stderr 字段
109
+ expect(exitCall![1]).not.toHaveProperty("stderr");
110
+ });
111
+
112
+ it("falls back to pipe capture when the stderr log file cannot be opened", async () => {
113
+ const dir = await tmpLogDir();
114
+ // 用普通文件顶替目录:mkdir/open 日志文件必然失败
115
+ const blocker = join(dir, "blocker");
116
+ await writeFile(blocker, "x");
117
+ const fake = new FakeChild();
118
+ const spawnImpl = vi.fn(() => fake as never);
119
+ const trace = vi.fn();
120
+
121
+ spawnRestartChild({ projectRoot: "F:/proj", spawnImpl, trace, restartLogDir: blocker });
122
+
123
+ const callArgs = spawnImpl.mock.calls[0] as unknown as Array<unknown>;
124
+ expect((callArgs[2] as { stdio: unknown[] }).stdio[2]).toBe("pipe");
125
+ const failCall = trace.mock.calls.find(
126
+ ([name]) => name === "restart: stderr log open failed, falling back to pipe",
127
+ );
128
+ expect(failCall).toBeTruthy();
129
+ expect(typeof (failCall![1] as { error: unknown }).error).toBe("string");
130
+ });
131
+ });
132
+
133
+ describe("decideRestartParentExit", () => {
134
+ it("returns false (parent stays alive) when the child dies during the window", async () => {
135
+ const child = { exitCode: 1, signalCode: null, pid: 42 } as never;
136
+ const trace = vi.fn();
137
+
138
+ const shouldExit = await decideRestartParentExit(child, 200, 50, trace);
139
+
140
+ expect(shouldExit).toBe(false);
141
+ expect(trace).toHaveBeenCalledWith(
142
+ "restart: child died during window, keeping parent",
143
+ expect.objectContaining({ childPid: 42, exitCode: 1 }),
144
+ );
145
+ });
146
+
147
+ it("returns true (parent exits) when the child stays alive through the window", async () => {
148
+ const child = { exitCode: null, signalCode: null, pid: 42 } as never;
149
+ const trace = vi.fn();
150
+
151
+ const shouldExit = await decideRestartParentExit(child, 150, 30, trace);
152
+
153
+ expect(shouldExit).toBe(true);
154
+ expect(trace).toHaveBeenCalledWith(
155
+ "restart: child alive after window, parent exiting",
156
+ expect.objectContaining({ childPid: 42 }),
157
+ );
158
+ });
159
+
160
+ it("surfaces a child that died with a signal", async () => {
161
+ const child = { exitCode: null, signalCode: "SIGKILL", pid: 42 } as never;
162
+ const trace = vi.fn();
163
+
164
+ const shouldExit = await decideRestartParentExit(child, 100, 25, trace);
165
+
166
+ expect(shouldExit).toBe(false);
167
+ expect(trace).toHaveBeenCalledWith(
168
+ "restart: child died during window, keeping parent",
169
+ expect.objectContaining({ signalCode: "SIGKILL" }),
170
+ );
171
+ });
172
+
173
+ it("exports a sane default readiness window", () => {
174
+ expect(RESTART_CHILD_READY_MS).toBeGreaterThan(0);
175
+ expect(RESTART_CHILD_READY_MS).toBeLessThan(60_000);
176
+ });
177
+ });
package/src/index.ts CHANGED
@@ -27,7 +27,7 @@ import { createServer, type IncomingMessage, type Server, type ServerResponse }
27
27
  import { WSClient, EventDispatcher, Domain } from "@larksuiteoapi/node-sdk";
28
28
  import WebSocket from "ws";
29
29
 
30
- import { appendStartupTrace, attachRelayWebSocket, ensureSingleInstance, freeRelayListenPort, installCrashLogging, waitForPortFree } from "./shared.ts";
30
+ import { appendStartupTrace, attachRelayWebSocket, ensureSingleInstance, freeRelayListenPort, installCrashLogging, installEpipeGuard, waitForPortFree } from "./shared.ts";
31
31
  import { createUiRouter, setExtraApiHandler, setReloadConfigHook, startSetupMode } from "./web-ui.ts";
32
32
  import {
33
33
  buildWebUiUrl,
@@ -804,6 +804,11 @@ async function main(): Promise<void> {
804
804
  onBeforeExit: (code) => serviceLifecycle.handleBeforeExit(code),
805
805
  });
806
806
 
807
+ // stdout/stderr 管道读端消失(如 /restart 旧进程退出后)时,第三方 SDK 写
808
+ // stderr 会 EPIPE;无监听会抛 uncaughtException 杀死整个服务。挂守卫把这类
809
+ // IO 错误降级为一条非致命 trace。
810
+ installEpipeGuard();
811
+
807
812
  // 模拟模式:独立端口 18079,不与 SDK 实例冲突,不走飞书凭证/权限/WSClient
808
813
  if (USE_SIMULATE) {
809
814
  const SIM_PORT = 18079;