chatccc 0.2.300 → 0.2.302

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 (55) 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 +8 -3
  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 +26 -26
  9. package/bin/chatccc.mjs +15 -15
  10. package/config.sample.json +7 -6
  11. package/deepccc-agent/README.md +21 -4
  12. package/deepccc-agent/os-prompts/darwin.md +8 -8
  13. package/deepccc-agent/os-prompts/linux.md +8 -8
  14. package/deepccc-agent/os-prompts/win32.md +11 -11
  15. package/deepccc-agent/package.json +68 -68
  16. package/dist/deepccc-agent/src/attachments.js +7 -5
  17. package/dist/deepccc-agent/src/cli.js +52 -7
  18. package/dist/deepccc-agent/src/completion-session.js +100 -0
  19. package/dist/deepccc-agent/src/config.js +4 -0
  20. package/dist/deepccc-agent/src/context.js +4 -1
  21. package/dist/deepccc-agent/src/decision-session.js +314 -0
  22. package/dist/deepccc-agent/src/file-tools.js +5 -0
  23. package/dist/deepccc-agent/src/index.js +41 -4
  24. package/dist/deepccc-agent/src/json-mode-fetch.js +12 -0
  25. package/dist/deepccc-agent/src/json-response.js +33 -0
  26. package/dist/deepccc-agent/src/multimodal.js +291 -0
  27. package/dist/deepccc-agent/src/progress/reducer.js +2 -0
  28. package/dist/deepccc-agent/src/web-page.js +411 -411
  29. package/dist/deepccc-agent/src/web-runtime.js +3 -0
  30. package/dist/deepccc-agent/src/web-server.js +2 -0
  31. package/dist/src/adapters/ccc-adapter.js +4 -0
  32. package/dist/src/agent-team/web/agent-team-page.js +250 -250
  33. package/dist/src/config.js +2 -0
  34. package/dist/src/engines/engine-specs.js +71 -71
  35. package/dist/src/feishu-api.js +11 -11
  36. package/dist/src/format-message.js +38 -19
  37. package/dist/src/litellm-proxy.js +15 -15
  38. package/dist/src/progress/reducer.js +2 -0
  39. package/dist/src/session.js +1 -0
  40. package/dist/src/web-ui.js +80 -66
  41. package/im-skills/feishu-skill/receive-send-file.md +65 -65
  42. package/im-skills/feishu-skill/receive-send-image.md +26 -26
  43. package/im-skills/feishu-skill/send-file.mjs +6 -6
  44. package/im-skills/feishu-skill/send-image.mjs +6 -6
  45. package/im-skills/feishu-skill/skill.md +28 -28
  46. package/im-skills/wechat-file-skill/receive-send-file.md +38 -38
  47. package/im-skills/wechat-file-skill/send-file.mjs +83 -83
  48. package/im-skills/wechat-file-skill/skill.md +10 -10
  49. package/im-skills/wechat-image-skill/skill.md +10 -10
  50. package/im-skills/wechat-video-skill/receive-send-video.md +38 -38
  51. package/im-skills/wechat-video-skill/send-video.mjs +79 -79
  52. package/im-skills/wechat-video-skill/skill.md +10 -10
  53. package/package.json +77 -77
  54. package/scripts/postinstall-sharp-check.mjs +58 -58
  55. package/scripts/self-update-helper.mjs +301 -301
@@ -1,301 +1,301 @@
1
- import { spawn, spawnSync } from "node:child_process";
2
- import {
3
- existsSync,
4
- readFileSync,
5
- renameSync,
6
- rmSync,
7
- writeFileSync,
8
- } from "node:fs";
9
- import { basename, resolve } from "node:path";
10
- import { pathToFileURL } from "node:url";
11
-
12
- const READY_MESSAGE = "chatccc:self-update-helper-ready";
13
- const INTERNAL_RESTART_ENV = "CHATCCC_INTERNAL_RESTART";
14
- const RESTART_PARENT_PID_ENV = "CHATCCC_RESTART_PARENT_PID";
15
- const UPDATE_RESULT_ENV = "CHATCCC_SELF_UPDATE_RESULT";
16
- const UPDATE_ERROR_ENV = "CHATCCC_SELF_UPDATE_ERROR";
17
-
18
- function log(message, details) {
19
- const suffix = details === undefined
20
- ? ""
21
- : ` ${typeof details === "string" ? details : JSON.stringify(details)}`;
22
- console.log(`${new Date().toISOString()} [UPDATE-HELPER] ${message}${suffix}`);
23
- }
24
-
25
- function sleep(ms) {
26
- return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
27
- }
28
-
29
- function pidIsAlive(pid) {
30
- try {
31
- process.kill(pid, 0);
32
- return true;
33
- } catch (error) {
34
- return error?.code === "EPERM";
35
- }
36
- }
37
-
38
- async function waitForParentExit(parentPid, timeoutMs) {
39
- const deadline = Date.now() + timeoutMs;
40
- while (pidIsAlive(parentPid)) {
41
- if (Date.now() >= deadline) return false;
42
- await sleep(100);
43
- }
44
- // npm 的 bin 包装器会在主进程结束后才从 spawnSync 返回;留出短暂时间,
45
- // 让包装器也退出并释放它继承的 Windows 当前目录句柄。
46
- await sleep(300);
47
- return true;
48
- }
49
-
50
- function readInstalledPackage(job) {
51
- const packageJsonPath = resolve(job.packageRoot, "package.json");
52
- const parsed = JSON.parse(readFileSync(packageJsonPath, "utf8"));
53
- if (parsed?.name !== "chatccc" || typeof parsed.version !== "string") {
54
- throw new Error("安装后的 package.json 无效。");
55
- }
56
- if (!existsSync(job.runtimeEntry)) {
57
- throw new Error(`安装后的运行入口不存在:${job.runtimeEntry}`);
58
- }
59
- return parsed;
60
- }
61
-
62
- function runNpmInstall(job, packageSpec) {
63
- const args = [
64
- ...job.npmArgsPrefix,
65
- "install",
66
- "-g",
67
- packageSpec,
68
- "--no-audit",
69
- "--no-fund",
70
- ];
71
- log("npm install begin", {
72
- command: job.npmCommand,
73
- args,
74
- cwd: job.restartCwd,
75
- });
76
- const result = spawnSync(job.npmCommand, args, {
77
- cwd: job.restartCwd,
78
- env: process.env,
79
- encoding: "utf8",
80
- maxBuffer: 8 * 1024 * 1024,
81
- timeout: 180_000,
82
- windowsHide: true,
83
- shell: false,
84
- });
85
- const output = `${result.stdout ?? ""}\n${result.stderr ?? ""}`.trim();
86
- log("npm install end", {
87
- packageSpec,
88
- status: result.status,
89
- signal: result.signal,
90
- error: result.error?.message,
91
- output: output.slice(-4_000),
92
- });
93
- if (result.error) throw result.error;
94
- if (result.status !== 0) {
95
- throw new Error(`npm install ${packageSpec} 失败(退出码 ${result.status ?? "unknown"}):${output.slice(-1_000)}`);
96
- }
97
- }
98
-
99
- async function installWithRetry(job, packageSpec) {
100
- const attempts = Number.isInteger(job.maxInstallAttempts) && job.maxInstallAttempts > 0
101
- ? job.maxInstallAttempts
102
- : 3;
103
- let lastError;
104
- for (let attempt = 1; attempt <= attempts; attempt += 1) {
105
- try {
106
- runNpmInstall(job, packageSpec);
107
- return;
108
- } catch (error) {
109
- lastError = error;
110
- log("npm install attempt failed", {
111
- packageSpec,
112
- attempt,
113
- attempts,
114
- error: error instanceof Error ? error.message : String(error),
115
- });
116
- if (attempt < attempts) await sleep(500 * attempt);
117
- }
118
- }
119
- throw lastError ?? new Error(`npm install ${packageSpec} 失败。`);
120
- }
121
-
122
- function persistResult(job, result) {
123
- const temporary = `${job.resultFile}.${process.pid}.tmp`;
124
- writeFileSync(temporary, JSON.stringify({
125
- schemaVersion: 1,
126
- completedAt: new Date().toISOString(),
127
- ...result,
128
- }, null, 2), "utf8");
129
- renameSync(temporary, job.resultFile);
130
- }
131
-
132
- function markSafeUpdateFailed(job, message) {
133
- if (!job.safeMaintenanceFile || !existsSync(job.safeMaintenanceFile)) return;
134
- try {
135
- const current = JSON.parse(readFileSync(job.safeMaintenanceFile, "utf8"));
136
- if (current?.kind !== "update" || current.phase !== "executing") return;
137
- const failed = {
138
- ...current,
139
- phase: "failed",
140
- updatedAt: new Date().toISOString(),
141
- lastError: message,
142
- };
143
- const temporary = `${job.safeMaintenanceFile}.${process.pid}.tmp`;
144
- writeFileSync(temporary, JSON.stringify(failed, null, 2), "utf8");
145
- renameSync(temporary, job.safeMaintenanceFile);
146
- log("safe update state marked failed");
147
- } catch (error) {
148
- log("failed to persist safe update failure", error instanceof Error ? error.message : String(error));
149
- }
150
- }
151
-
152
- function launchRuntime(job, status, errorMessage) {
153
- const env = {
154
- ...process.env,
155
- [INTERNAL_RESTART_ENV]: "1",
156
- [RESTART_PARENT_PID_ENV]: String(process.pid),
157
- [UPDATE_RESULT_ENV]: status,
158
- };
159
- if (errorMessage) env[UPDATE_ERROR_ENV] = errorMessage.slice(0, 2_000);
160
- const child = spawn(job.runtimeCommand, [job.runtimeEntry], {
161
- cwd: job.restartCwd,
162
- detached: true,
163
- stdio: ["ignore", "ignore", "inherit"],
164
- shell: false,
165
- windowsHide: true,
166
- env,
167
- });
168
- child.unref();
169
- log("runtime launched", {
170
- pid: child.pid,
171
- status,
172
- command: job.runtimeCommand,
173
- entry: job.runtimeEntry,
174
- cwd: job.restartCwd,
175
- });
176
- }
177
-
178
- function validateJob(job) {
179
- if (
180
- job?.schemaVersion !== 1
181
- || !Number.isInteger(job.parentPid)
182
- || job.parentPid <= 0
183
- || typeof job.packageRoot !== "string"
184
- || typeof job.previousVersion !== "string"
185
- || typeof job.restartCwd !== "string"
186
- || typeof job.npmCommand !== "string"
187
- || !Array.isArray(job.npmArgsPrefix)
188
- || !job.npmArgsPrefix.every((arg) => typeof arg === "string")
189
- || typeof job.runtimeCommand !== "string"
190
- || typeof job.runtimeEntry !== "string"
191
- || typeof job.resultFile !== "string"
192
- || (job.safeMaintenanceFile !== undefined && typeof job.safeMaintenanceFile !== "string")
193
- || (job.cleanupPaths !== undefined && (
194
- !Array.isArray(job.cleanupPaths)
195
- || !job.cleanupPaths.every((path) => typeof path === "string")
196
- ))
197
- ) {
198
- throw new Error("自更新任务文件无效。");
199
- }
200
- return job;
201
- }
202
-
203
- async function announceReady(job) {
204
- if (typeof process.send !== "function") return;
205
- await new Promise((resolvePromise) => {
206
- try {
207
- process.send({
208
- type: READY_MESSAGE,
209
- pid: process.pid,
210
- parentPid: job.parentPid,
211
- }, () => resolvePromise());
212
- } catch {
213
- resolvePromise();
214
- }
215
- });
216
- try { process.disconnect?.(); } catch { /* parent may disconnect first */ }
217
- }
218
-
219
- export async function runSelfUpdateJob(job) {
220
- const parentExited = await waitForParentExit(
221
- job.parentPid,
222
- job.parentExitTimeoutMs ?? 30_000,
223
- );
224
- if (!parentExited) {
225
- throw new Error(`旧 ChatCCC 进程 ${job.parentPid} 未在限定时间内退出,已取消更新。`);
226
- }
227
-
228
- try {
229
- await installWithRetry(job, "chatccc@latest");
230
- const installed = readInstalledPackage(job);
231
- persistResult(job, {
232
- status: "success",
233
- previousVersion: job.previousVersion,
234
- installedVersion: installed.version,
235
- rollbackSucceeded: false,
236
- });
237
- launchRuntime(job, "success");
238
- } catch (updateError) {
239
- const message = updateError instanceof Error ? updateError.message : String(updateError);
240
- log("latest installation failed; rollback begin", {
241
- previousVersion: job.previousVersion,
242
- error: message,
243
- });
244
- let rollbackSucceeded = false;
245
- try {
246
- await installWithRetry(job, `chatccc@${job.previousVersion}`);
247
- readInstalledPackage(job);
248
- rollbackSucceeded = true;
249
- } catch (rollbackError) {
250
- log("rollback failed", rollbackError instanceof Error ? rollbackError.message : String(rollbackError));
251
- // npm 可能只在 postinstall 等末尾步骤失败;若入口仍完整,则优先恢复服务。
252
- try {
253
- readInstalledPackage(job);
254
- rollbackSucceeded = true;
255
- log("existing runtime remains usable after rollback failure");
256
- } catch {
257
- // 包目录确实不可用,只能保留结果和日志供人工恢复。
258
- }
259
- }
260
- persistResult(job, {
261
- status: "failed",
262
- previousVersion: job.previousVersion,
263
- rollbackSucceeded,
264
- error: message,
265
- });
266
- markSafeUpdateFailed(job, message);
267
- if (!rollbackSucceeded) {
268
- throw new Error(`更新失败且无法恢复旧版本:${message}`);
269
- }
270
- launchRuntime(job, "failed", message);
271
- }
272
- }
273
-
274
- async function main() {
275
- const jobPath = process.argv[2];
276
- if (!jobPath) throw new Error("缺少自更新任务文件路径。");
277
- const job = validateJob(JSON.parse(readFileSync(jobPath, "utf8")));
278
- log("helper started", {
279
- pid: process.pid,
280
- parentPid: job.parentPid,
281
- packageRoot: job.packageRoot,
282
- helper: basename(process.argv[1]),
283
- });
284
- await announceReady(job);
285
- try {
286
- await runSelfUpdateJob(job);
287
- } finally {
288
- for (const path of job.cleanupPaths ?? []) {
289
- try { rmSync(path, { force: true }); } catch { /* best effort */ }
290
- }
291
- }
292
- }
293
-
294
- const invokedDirectly = process.argv[1]
295
- && import.meta.url === pathToFileURL(resolve(process.argv[1])).href;
296
- if (invokedDirectly) {
297
- main().catch((error) => {
298
- log("fatal", error instanceof Error ? error.stack ?? error.message : String(error));
299
- process.exitCode = 1;
300
- });
301
- }
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import {
3
+ existsSync,
4
+ readFileSync,
5
+ renameSync,
6
+ rmSync,
7
+ writeFileSync,
8
+ } from "node:fs";
9
+ import { basename, resolve } from "node:path";
10
+ import { pathToFileURL } from "node:url";
11
+
12
+ const READY_MESSAGE = "chatccc:self-update-helper-ready";
13
+ const INTERNAL_RESTART_ENV = "CHATCCC_INTERNAL_RESTART";
14
+ const RESTART_PARENT_PID_ENV = "CHATCCC_RESTART_PARENT_PID";
15
+ const UPDATE_RESULT_ENV = "CHATCCC_SELF_UPDATE_RESULT";
16
+ const UPDATE_ERROR_ENV = "CHATCCC_SELF_UPDATE_ERROR";
17
+
18
+ function log(message, details) {
19
+ const suffix = details === undefined
20
+ ? ""
21
+ : ` ${typeof details === "string" ? details : JSON.stringify(details)}`;
22
+ console.log(`${new Date().toISOString()} [UPDATE-HELPER] ${message}${suffix}`);
23
+ }
24
+
25
+ function sleep(ms) {
26
+ return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
27
+ }
28
+
29
+ function pidIsAlive(pid) {
30
+ try {
31
+ process.kill(pid, 0);
32
+ return true;
33
+ } catch (error) {
34
+ return error?.code === "EPERM";
35
+ }
36
+ }
37
+
38
+ async function waitForParentExit(parentPid, timeoutMs) {
39
+ const deadline = Date.now() + timeoutMs;
40
+ while (pidIsAlive(parentPid)) {
41
+ if (Date.now() >= deadline) return false;
42
+ await sleep(100);
43
+ }
44
+ // npm 的 bin 包装器会在主进程结束后才从 spawnSync 返回;留出短暂时间,
45
+ // 让包装器也退出并释放它继承的 Windows 当前目录句柄。
46
+ await sleep(300);
47
+ return true;
48
+ }
49
+
50
+ function readInstalledPackage(job) {
51
+ const packageJsonPath = resolve(job.packageRoot, "package.json");
52
+ const parsed = JSON.parse(readFileSync(packageJsonPath, "utf8"));
53
+ if (parsed?.name !== "chatccc" || typeof parsed.version !== "string") {
54
+ throw new Error("安装后的 package.json 无效。");
55
+ }
56
+ if (!existsSync(job.runtimeEntry)) {
57
+ throw new Error(`安装后的运行入口不存在:${job.runtimeEntry}`);
58
+ }
59
+ return parsed;
60
+ }
61
+
62
+ function runNpmInstall(job, packageSpec) {
63
+ const args = [
64
+ ...job.npmArgsPrefix,
65
+ "install",
66
+ "-g",
67
+ packageSpec,
68
+ "--no-audit",
69
+ "--no-fund",
70
+ ];
71
+ log("npm install begin", {
72
+ command: job.npmCommand,
73
+ args,
74
+ cwd: job.restartCwd,
75
+ });
76
+ const result = spawnSync(job.npmCommand, args, {
77
+ cwd: job.restartCwd,
78
+ env: process.env,
79
+ encoding: "utf8",
80
+ maxBuffer: 8 * 1024 * 1024,
81
+ timeout: 180_000,
82
+ windowsHide: true,
83
+ shell: false,
84
+ });
85
+ const output = `${result.stdout ?? ""}\n${result.stderr ?? ""}`.trim();
86
+ log("npm install end", {
87
+ packageSpec,
88
+ status: result.status,
89
+ signal: result.signal,
90
+ error: result.error?.message,
91
+ output: output.slice(-4_000),
92
+ });
93
+ if (result.error) throw result.error;
94
+ if (result.status !== 0) {
95
+ throw new Error(`npm install ${packageSpec} 失败(退出码 ${result.status ?? "unknown"}):${output.slice(-1_000)}`);
96
+ }
97
+ }
98
+
99
+ async function installWithRetry(job, packageSpec) {
100
+ const attempts = Number.isInteger(job.maxInstallAttempts) && job.maxInstallAttempts > 0
101
+ ? job.maxInstallAttempts
102
+ : 3;
103
+ let lastError;
104
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
105
+ try {
106
+ runNpmInstall(job, packageSpec);
107
+ return;
108
+ } catch (error) {
109
+ lastError = error;
110
+ log("npm install attempt failed", {
111
+ packageSpec,
112
+ attempt,
113
+ attempts,
114
+ error: error instanceof Error ? error.message : String(error),
115
+ });
116
+ if (attempt < attempts) await sleep(500 * attempt);
117
+ }
118
+ }
119
+ throw lastError ?? new Error(`npm install ${packageSpec} 失败。`);
120
+ }
121
+
122
+ function persistResult(job, result) {
123
+ const temporary = `${job.resultFile}.${process.pid}.tmp`;
124
+ writeFileSync(temporary, JSON.stringify({
125
+ schemaVersion: 1,
126
+ completedAt: new Date().toISOString(),
127
+ ...result,
128
+ }, null, 2), "utf8");
129
+ renameSync(temporary, job.resultFile);
130
+ }
131
+
132
+ function markSafeUpdateFailed(job, message) {
133
+ if (!job.safeMaintenanceFile || !existsSync(job.safeMaintenanceFile)) return;
134
+ try {
135
+ const current = JSON.parse(readFileSync(job.safeMaintenanceFile, "utf8"));
136
+ if (current?.kind !== "update" || current.phase !== "executing") return;
137
+ const failed = {
138
+ ...current,
139
+ phase: "failed",
140
+ updatedAt: new Date().toISOString(),
141
+ lastError: message,
142
+ };
143
+ const temporary = `${job.safeMaintenanceFile}.${process.pid}.tmp`;
144
+ writeFileSync(temporary, JSON.stringify(failed, null, 2), "utf8");
145
+ renameSync(temporary, job.safeMaintenanceFile);
146
+ log("safe update state marked failed");
147
+ } catch (error) {
148
+ log("failed to persist safe update failure", error instanceof Error ? error.message : String(error));
149
+ }
150
+ }
151
+
152
+ function launchRuntime(job, status, errorMessage) {
153
+ const env = {
154
+ ...process.env,
155
+ [INTERNAL_RESTART_ENV]: "1",
156
+ [RESTART_PARENT_PID_ENV]: String(process.pid),
157
+ [UPDATE_RESULT_ENV]: status,
158
+ };
159
+ if (errorMessage) env[UPDATE_ERROR_ENV] = errorMessage.slice(0, 2_000);
160
+ const child = spawn(job.runtimeCommand, [job.runtimeEntry], {
161
+ cwd: job.restartCwd,
162
+ detached: true,
163
+ stdio: ["ignore", "ignore", "inherit"],
164
+ shell: false,
165
+ windowsHide: true,
166
+ env,
167
+ });
168
+ child.unref();
169
+ log("runtime launched", {
170
+ pid: child.pid,
171
+ status,
172
+ command: job.runtimeCommand,
173
+ entry: job.runtimeEntry,
174
+ cwd: job.restartCwd,
175
+ });
176
+ }
177
+
178
+ function validateJob(job) {
179
+ if (
180
+ job?.schemaVersion !== 1
181
+ || !Number.isInteger(job.parentPid)
182
+ || job.parentPid <= 0
183
+ || typeof job.packageRoot !== "string"
184
+ || typeof job.previousVersion !== "string"
185
+ || typeof job.restartCwd !== "string"
186
+ || typeof job.npmCommand !== "string"
187
+ || !Array.isArray(job.npmArgsPrefix)
188
+ || !job.npmArgsPrefix.every((arg) => typeof arg === "string")
189
+ || typeof job.runtimeCommand !== "string"
190
+ || typeof job.runtimeEntry !== "string"
191
+ || typeof job.resultFile !== "string"
192
+ || (job.safeMaintenanceFile !== undefined && typeof job.safeMaintenanceFile !== "string")
193
+ || (job.cleanupPaths !== undefined && (
194
+ !Array.isArray(job.cleanupPaths)
195
+ || !job.cleanupPaths.every((path) => typeof path === "string")
196
+ ))
197
+ ) {
198
+ throw new Error("自更新任务文件无效。");
199
+ }
200
+ return job;
201
+ }
202
+
203
+ async function announceReady(job) {
204
+ if (typeof process.send !== "function") return;
205
+ await new Promise((resolvePromise) => {
206
+ try {
207
+ process.send({
208
+ type: READY_MESSAGE,
209
+ pid: process.pid,
210
+ parentPid: job.parentPid,
211
+ }, () => resolvePromise());
212
+ } catch {
213
+ resolvePromise();
214
+ }
215
+ });
216
+ try { process.disconnect?.(); } catch { /* parent may disconnect first */ }
217
+ }
218
+
219
+ export async function runSelfUpdateJob(job) {
220
+ const parentExited = await waitForParentExit(
221
+ job.parentPid,
222
+ job.parentExitTimeoutMs ?? 30_000,
223
+ );
224
+ if (!parentExited) {
225
+ throw new Error(`旧 ChatCCC 进程 ${job.parentPid} 未在限定时间内退出,已取消更新。`);
226
+ }
227
+
228
+ try {
229
+ await installWithRetry(job, "chatccc@latest");
230
+ const installed = readInstalledPackage(job);
231
+ persistResult(job, {
232
+ status: "success",
233
+ previousVersion: job.previousVersion,
234
+ installedVersion: installed.version,
235
+ rollbackSucceeded: false,
236
+ });
237
+ launchRuntime(job, "success");
238
+ } catch (updateError) {
239
+ const message = updateError instanceof Error ? updateError.message : String(updateError);
240
+ log("latest installation failed; rollback begin", {
241
+ previousVersion: job.previousVersion,
242
+ error: message,
243
+ });
244
+ let rollbackSucceeded = false;
245
+ try {
246
+ await installWithRetry(job, `chatccc@${job.previousVersion}`);
247
+ readInstalledPackage(job);
248
+ rollbackSucceeded = true;
249
+ } catch (rollbackError) {
250
+ log("rollback failed", rollbackError instanceof Error ? rollbackError.message : String(rollbackError));
251
+ // npm 可能只在 postinstall 等末尾步骤失败;若入口仍完整,则优先恢复服务。
252
+ try {
253
+ readInstalledPackage(job);
254
+ rollbackSucceeded = true;
255
+ log("existing runtime remains usable after rollback failure");
256
+ } catch {
257
+ // 包目录确实不可用,只能保留结果和日志供人工恢复。
258
+ }
259
+ }
260
+ persistResult(job, {
261
+ status: "failed",
262
+ previousVersion: job.previousVersion,
263
+ rollbackSucceeded,
264
+ error: message,
265
+ });
266
+ markSafeUpdateFailed(job, message);
267
+ if (!rollbackSucceeded) {
268
+ throw new Error(`更新失败且无法恢复旧版本:${message}`);
269
+ }
270
+ launchRuntime(job, "failed", message);
271
+ }
272
+ }
273
+
274
+ async function main() {
275
+ const jobPath = process.argv[2];
276
+ if (!jobPath) throw new Error("缺少自更新任务文件路径。");
277
+ const job = validateJob(JSON.parse(readFileSync(jobPath, "utf8")));
278
+ log("helper started", {
279
+ pid: process.pid,
280
+ parentPid: job.parentPid,
281
+ packageRoot: job.packageRoot,
282
+ helper: basename(process.argv[1]),
283
+ });
284
+ await announceReady(job);
285
+ try {
286
+ await runSelfUpdateJob(job);
287
+ } finally {
288
+ for (const path of job.cleanupPaths ?? []) {
289
+ try { rmSync(path, { force: true }); } catch { /* best effort */ }
290
+ }
291
+ }
292
+ }
293
+
294
+ const invokedDirectly = process.argv[1]
295
+ && import.meta.url === pathToFileURL(resolve(process.argv[1])).href;
296
+ if (invokedDirectly) {
297
+ main().catch((error) => {
298
+ log("fatal", error instanceof Error ? error.stack ?? error.message : String(error));
299
+ process.exitCode = 1;
300
+ });
301
+ }