@keyou007/agent-bot 0.1.27-alpha.3 → 0.1.27-alpha.4

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 (156) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +77 -12
  3. package/README.zh.md +77 -12
  4. package/assets/agent-bot.ico +0 -0
  5. package/assets/roboto-mono-OFL.txt +93 -0
  6. package/assets/roboto-mono-latin.woff2 +0 -0
  7. package/assets/workspace-drafts.js +88 -0
  8. package/assets/workspace-sessions.js +1935 -232
  9. package/assets/workspace.css +360 -35
  10. package/assets/workspace.js +2115 -249
  11. package/dist/cli/SelfUpdateObserver.js +124 -0
  12. package/dist/cli/SelfUpdateObserver.js.map +1 -0
  13. package/dist/cli/SelfUpdateRunner.js +267 -70
  14. package/dist/cli/SelfUpdateRunner.js.map +1 -1
  15. package/dist/cli/SelfUpdater.js +54 -15
  16. package/dist/cli/SelfUpdater.js.map +1 -1
  17. package/dist/cli/controlProtocol.js.map +1 -1
  18. package/dist/cli/help.js +6 -0
  19. package/dist/cli/help.js.map +1 -1
  20. package/dist/cli.js +85 -6
  21. package/dist/cli.js.map +1 -1
  22. package/dist/codex/CodexEventMapper.js +29 -5
  23. package/dist/codex/CodexEventMapper.js.map +1 -1
  24. package/dist/codex/CodexRuntime.js +3 -0
  25. package/dist/codex/CodexRuntime.js.map +1 -1
  26. package/dist/feishu/CardRenderer.js +45 -13
  27. package/dist/feishu/CardRenderer.js.map +1 -1
  28. package/dist/feishu/ConsoleFeishuClient.js +4 -0
  29. package/dist/feishu/ConsoleFeishuClient.js.map +1 -1
  30. package/dist/feishu/FeishuMarkdown.js +2 -14
  31. package/dist/feishu/FeishuMarkdown.js.map +1 -1
  32. package/dist/feishu/FeishuMessageClient.js +9 -0
  33. package/dist/feishu/FeishuMessageClient.js.map +1 -1
  34. package/dist/feishu/FeishuTurnPresenter.js +26 -14
  35. package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
  36. package/dist/index.js +47 -12
  37. package/dist/index.js.map +1 -1
  38. package/dist/local-files/DiagramPreview.js +11 -6
  39. package/dist/local-files/DiagramPreview.js.map +1 -1
  40. package/dist/local-files/GitDiffPreview.js +40 -10
  41. package/dist/local-files/GitDiffPreview.js.map +1 -1
  42. package/dist/local-files/LiveMarkup.js +104 -0
  43. package/dist/local-files/LiveMarkup.js.map +1 -0
  44. package/dist/local-files/LocalFileViewerServer.js +133 -117
  45. package/dist/local-files/LocalFileViewerServer.js.map +1 -1
  46. package/dist/local-files/MarkdownExport.js +54 -0
  47. package/dist/local-files/MarkdownExport.js.map +1 -0
  48. package/dist/local-files/PreviewCodeFont.js +11 -0
  49. package/dist/local-files/PreviewCodeFont.js.map +1 -0
  50. package/dist/local-files/PreviewSyntaxHighlight.js +73 -0
  51. package/dist/local-files/PreviewSyntaxHighlight.js.map +1 -1
  52. package/dist/local-files/ToolCommandDisplay.js +111 -0
  53. package/dist/local-files/ToolCommandDisplay.js.map +1 -0
  54. package/dist/local-files/TurnPreviewPage.js +23 -269
  55. package/dist/local-files/TurnPreviewPage.js.map +1 -1
  56. package/dist/local-files/WorkspaceFileEvents.js +206 -0
  57. package/dist/local-files/WorkspaceFileEvents.js.map +1 -0
  58. package/dist/local-files/WorkspaceFiles.js +79 -3
  59. package/dist/local-files/WorkspaceFiles.js.map +1 -1
  60. package/dist/local-files/WorkspaceImages.js +15 -0
  61. package/dist/local-files/WorkspaceImages.js.map +1 -0
  62. package/dist/local-files/WorkspacePage.js +20 -5
  63. package/dist/local-files/WorkspacePage.js.map +1 -1
  64. package/dist/local-files/WorkspaceSessions.js +881 -79
  65. package/dist/local-files/WorkspaceSessions.js.map +1 -1
  66. package/dist/local-files/WorkspaceTimeline.js +105 -0
  67. package/dist/local-files/WorkspaceTimeline.js.map +1 -0
  68. package/dist/presentation/OutboundRouter.js +13 -6
  69. package/dist/presentation/OutboundRouter.js.map +1 -1
  70. package/dist/presentation/TurnStateReducer.js +28 -21
  71. package/dist/presentation/TurnStateReducer.js.map +1 -1
  72. package/dist/proxy/ProxySessionController.js +229 -92
  73. package/dist/proxy/ProxySessionController.js.map +1 -1
  74. package/dist/proxy/TaskMetadata.js +86 -0
  75. package/dist/proxy/TaskMetadata.js.map +1 -0
  76. package/dist/scheduling/ScheduleCards.js +10 -4
  77. package/dist/scheduling/ScheduleCards.js.map +1 -1
  78. package/dist/scheduling/ScheduleCommand.js +4 -0
  79. package/dist/scheduling/ScheduleCommand.js.map +1 -1
  80. package/dist/scheduling/ScheduledTaskStore.js +51 -12
  81. package/dist/scheduling/ScheduledTaskStore.js.map +1 -1
  82. package/dist/scheduling/types.js +18 -4
  83. package/dist/scheduling/types.js.map +1 -1
  84. package/dist/state/StateStore.js +145 -19
  85. package/dist/state/StateStore.js.map +1 -1
  86. package/dist/state/TurnPreviewJournal.js +143 -36
  87. package/dist/state/TurnPreviewJournal.js.map +1 -1
  88. package/dist/state/TurnToolText.js +172 -0
  89. package/dist/state/TurnToolText.js.map +1 -0
  90. package/dist/state/migrations.js +4 -0
  91. package/dist/state/migrations.js.map +1 -1
  92. package/dist/supervision/SafeRestartNotifier.js +9 -6
  93. package/dist/supervision/SafeRestartNotifier.js.map +1 -1
  94. package/dist/terminal/TerminalPage.js +5 -0
  95. package/dist/terminal/TerminalPage.js.map +1 -1
  96. package/dist/updates/AutomaticUpdatePreparer.js +63 -12
  97. package/dist/updates/AutomaticUpdatePreparer.js.map +1 -1
  98. package/dist/updates/ManualUpdateController.js +7 -2
  99. package/dist/updates/ManualUpdateController.js.map +1 -1
  100. package/dist/utils/promptAttachments.js +20 -0
  101. package/dist/utils/promptAttachments.js.map +1 -0
  102. package/dist/utils/toolTimestamp.js +6 -0
  103. package/dist/utils/toolTimestamp.js.map +1 -0
  104. package/npm-shrinkwrap.json +2 -2
  105. package/package.json +1 -1
  106. package/skills/agent-bot/SKILL.md +23 -2
  107. package/src/cli/SelfUpdateObserver.ts +111 -0
  108. package/src/cli/SelfUpdateRunner.ts +271 -85
  109. package/src/cli/SelfUpdater.ts +53 -16
  110. package/src/cli/controlProtocol.ts +1 -0
  111. package/src/cli/help.ts +6 -0
  112. package/src/cli.ts +71 -5
  113. package/src/codex/CodexEventMapper.ts +25 -5
  114. package/src/codex/CodexRuntime.ts +4 -0
  115. package/src/feishu/CardRenderer.ts +48 -13
  116. package/src/feishu/ConsoleFeishuClient.ts +6 -1
  117. package/src/feishu/FeishuMarkdown.ts +2 -14
  118. package/src/feishu/FeishuMessageClient.ts +10 -0
  119. package/src/feishu/FeishuTurnPresenter.ts +22 -8
  120. package/src/feishu/types.ts +1 -0
  121. package/src/index.ts +47 -12
  122. package/src/local-files/DiagramPreview.ts +11 -6
  123. package/src/local-files/GitDiffPreview.ts +38 -10
  124. package/src/local-files/LiveMarkup.ts +103 -0
  125. package/src/local-files/LocalFileViewerServer.ts +120 -120
  126. package/src/local-files/MarkdownExport.ts +54 -0
  127. package/src/local-files/PreviewCodeFont.ts +12 -0
  128. package/src/local-files/PreviewSyntaxHighlight.ts +75 -0
  129. package/src/local-files/ToolCommandDisplay.ts +104 -0
  130. package/src/local-files/TurnPreviewPage.ts +23 -254
  131. package/src/local-files/WorkspaceFileEvents.ts +186 -0
  132. package/src/local-files/WorkspaceFiles.ts +72 -5
  133. package/src/local-files/WorkspaceImages.ts +10 -0
  134. package/src/local-files/WorkspacePage.ts +20 -5
  135. package/src/local-files/WorkspaceSessions.ts +811 -82
  136. package/src/local-files/WorkspaceTimeline.ts +109 -0
  137. package/src/presentation/OutboundRouter.ts +15 -4
  138. package/src/presentation/TurnStateReducer.ts +27 -18
  139. package/src/presentation/turnViewTypes.ts +2 -0
  140. package/src/proxy/ProxySessionController.ts +226 -77
  141. package/src/proxy/TaskMetadata.ts +81 -0
  142. package/src/runtime/types.ts +2 -1
  143. package/src/scheduling/ScheduleCards.ts +10 -4
  144. package/src/scheduling/ScheduleCommand.ts +4 -0
  145. package/src/scheduling/ScheduledTaskStore.ts +54 -9
  146. package/src/scheduling/types.ts +24 -4
  147. package/src/state/StateStore.ts +157 -20
  148. package/src/state/TurnPreviewJournal.ts +138 -34
  149. package/src/state/TurnToolText.ts +156 -0
  150. package/src/state/migrations.ts +4 -0
  151. package/src/supervision/SafeRestartNotifier.ts +9 -6
  152. package/src/terminal/TerminalPage.ts +5 -0
  153. package/src/updates/AutomaticUpdatePreparer.ts +52 -11
  154. package/src/updates/ManualUpdateController.ts +8 -3
  155. package/src/utils/promptAttachments.ts +24 -0
  156. package/src/utils/toolTimestamp.ts +5 -0
@@ -5,6 +5,7 @@ import path from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
 
7
7
  export const SELF_UPDATE_PLAN_VERSION = 1;
8
+ export const SELF_UPDATE_RECOVERY_ATTEMPTS_ENV = "AGENT_BOT_UPDATE_RECOVERY_ATTEMPTS";
8
9
 
9
10
  export interface SelfUpdatePlan {
10
11
  schemaVersion: typeof SELF_UPDATE_PLAN_VERSION;
@@ -22,9 +23,12 @@ export interface SelfUpdatePlan {
22
23
  controlEndpoint: string;
23
24
  workingDirectory: string;
24
25
  restartService: boolean;
26
+ preparationPid?: number;
27
+ recoveryAttemptIds?: string[];
25
28
  reason?: string;
26
29
  notificationSessionId?: string;
27
30
  notificationTarget?: { contextKey: string; replyMessageId?: string };
31
+ notificationMessageId?: string;
28
32
  resultPath: string;
29
33
  logPath: string;
30
34
  }
@@ -54,6 +58,12 @@ interface DatabaseBackup {
54
58
  entries: Array<{ sourcePath: string; backupPath: string; existed: boolean }>;
55
59
  }
56
60
 
61
+ class ProcessExitTimeoutError extends Error {
62
+ constructor(readonly pids: number[]) {
63
+ super(`Timed out waiting for Agent Bot processes to exit: ${pids.join(", ")}.`);
64
+ }
65
+ }
66
+
57
67
  export interface SelfUpdateRunnerDependencies {
58
68
  runNpm(args: string[], cwd: string): CommandResult;
59
69
  validatePackage(
@@ -62,20 +72,37 @@ export interface SelfUpdateRunnerDependencies {
62
72
  version: string,
63
73
  ): void;
64
74
  initializeProfile(packageRoot: string, cwd: string): CommandResult;
65
- startSupervisor(packageRoot: string, cwd: string): number | undefined;
75
+ startSupervisor(packageRoot: string, cwd: string): number | undefined | Promise<number>;
66
76
  waitForServer(endpoint: string, timeoutMs: number): Promise<boolean>;
67
77
  stopServer(endpoint: string, supervisorPid?: number): Promise<void>;
68
78
  waitForProcesses(pids: number[], timeoutMs: number): Promise<void>;
79
+ forceTerminateProcesses(pids: number[]): Promise<void>;
69
80
  now(): Date;
81
+ notifyProgress?(plan: SelfUpdatePlan, message: string, result?: SelfUpdateResult): Promise<void>;
70
82
  }
71
83
 
72
84
  export async function applySelfUpdatePlan(
73
85
  plan: SelfUpdatePlan,
74
86
  waitPids: number[] = [],
75
87
  dependencies: SelfUpdateRunnerDependencies = defaultDependencies,
88
+ ): Promise<SelfUpdateResult> {
89
+ waitPids = [...new Set([...waitPids, ...(plan.preparationPid ? [plan.preparationPid] : [])])];
90
+ const result = await runSelfUpdatePlan(plan, waitPids, dependencies);
91
+ const message = result.status === "updated" ? `更新完成,当前版本 ${result.activeVersion}。`
92
+ : result.status === "rolled-back" ? `更新失败,已恢复 ${result.activeVersion}。`
93
+ : result.serviceReady ? "更新失败,旧服务仍在线,未能完成重启。" : "更新失败,服务未能自动恢复。";
94
+ await reportUpdateProgress(plan, dependencies, message, result);
95
+ return result;
96
+ }
97
+
98
+ async function runSelfUpdatePlan(
99
+ plan: SelfUpdatePlan,
100
+ waitPids: number[],
101
+ dependencies: SelfUpdateRunnerDependencies,
76
102
  ): Promise<SelfUpdateResult> {
77
103
  validatePlan(plan);
78
104
  assertUpdateLock(plan);
105
+ process.env[SELF_UPDATE_RECOVERY_ATTEMPTS_ENV] = JSON.stringify(plan.recoveryAttemptIds ?? []);
79
106
  markUpdateRunning(plan);
80
107
  fs.mkdirSync(path.dirname(plan.logPath), { recursive: true });
81
108
  const log = (event: string, data: Record<string, unknown> = {}): void => {
@@ -96,9 +123,22 @@ export async function applySelfUpdatePlan(
96
123
  waitPids,
97
124
  });
98
125
  try {
99
- await dependencies.waitForProcesses(waitPids, 60_000);
126
+ await Promise.all([
127
+ (async () => {
128
+ try {
129
+ await dependencies.waitForProcesses(waitPids, 10_000);
130
+ } catch (error) {
131
+ const remainingPids = error instanceof ProcessExitTimeoutError ? error.pids : waitPids;
132
+ log("old_process_exit_timeout", { waitPids: remainingPids, error: errorMessage(error) });
133
+ await dependencies.forceTerminateProcesses(remainingPids);
134
+ await dependencies.waitForProcesses(remainingPids, 5_000);
135
+ log("old_processes_force_terminated", { waitPids: remainingPids });
136
+ }
137
+ })(),
138
+ reportUpdateProgress(plan, dependencies, "正在等待旧进程退出;超过 10 秒将强制终止本次更新涉及的旧进程……"),
139
+ ]);
100
140
  } catch (error) {
101
- return recoverBeforeInstallation(
141
+ return await recoverBeforeInstallation(
102
142
  plan,
103
143
  errorMessage(error),
104
144
  dependencies,
@@ -108,13 +148,14 @@ export async function applySelfUpdatePlan(
108
148
 
109
149
  let databaseBackup: DatabaseBackup;
110
150
  try {
151
+ await reportUpdateProgress(plan, dependencies, "正在备份任务数据库……");
111
152
  databaseBackup = createDatabaseBackup(plan);
112
153
  log("database_backup_created", {
113
154
  directory: databaseBackup.directory,
114
155
  files: databaseBackup.entries.filter((entry) => entry.existed).length,
115
156
  });
116
157
  } catch (error) {
117
- return recoverBeforeInstallation(
158
+ return await recoverBeforeInstallation(
118
159
  plan,
119
160
  `Could not back up Agent Bot state: ${errorMessage(error)}`,
120
161
  dependencies,
@@ -124,20 +165,24 @@ export async function applySelfUpdatePlan(
124
165
 
125
166
  let startedSupervisorPid: number | undefined;
126
167
  try {
168
+ await reportUpdateProgress(plan, dependencies, `正在安装 Agent Bot ${plan.toVersion}……`);
127
169
  installTarball(
128
170
  plan.candidateTarball,
129
171
  plan.workingDirectory,
130
172
  dependencies,
131
173
  log,
132
174
  );
175
+ await reportUpdateProgress(plan, dependencies, "正在校验已安装版本……");
133
176
  dependencies.validatePackage(
134
177
  plan.packageRoot,
135
178
  plan.packageName,
136
179
  plan.toVersion,
137
180
  );
181
+ await reportUpdateProgress(plan, dependencies, "正在初始化更新后的配置……");
138
182
  initializeUpdatedProfile(plan, dependencies, log);
139
183
  if (plan.restartService) {
140
- startedSupervisorPid = dependencies.startSupervisor(
184
+ await reportUpdateProgress(plan, dependencies, "正在启动服务并等待就绪……");
185
+ startedSupervisorPid = await dependencies.startSupervisor(
141
186
  plan.packageRoot,
142
187
  plan.workingDirectory,
143
188
  );
@@ -163,15 +208,21 @@ export async function applySelfUpdatePlan(
163
208
  const message = errorMessage(error);
164
209
  log("update_failed", { error: message });
165
210
  if (plan.restartService) {
166
- await dependencies
167
- .stopServer(plan.controlEndpoint, startedSupervisorPid)
168
- .catch((stopError: unknown) => {
169
- log("updated_service_stop_failed", {
170
- error: errorMessage(stopError),
171
- });
172
- });
211
+ try {
212
+ await dependencies.stopServer(plan.controlEndpoint, startedSupervisorPid);
213
+ } catch (stopError) {
214
+ const result: SelfUpdateResult = {
215
+ status: "failed", fromVersion: plan.fromVersion, toVersion: plan.toVersion,
216
+ error: message, rollbackError: `Could not stop the updated service: ${errorMessage(stopError)}`,
217
+ completedAt: dependencies.now().toISOString(),
218
+ };
219
+ writeResult(plan.resultPath, result);
220
+ log("updated_service_stop_failed", { ...result });
221
+ return result;
222
+ }
173
223
  }
174
- return rollback(plan, message, databaseBackup, dependencies, log);
224
+ await reportUpdateProgress(plan, dependencies, `安装或启动失败,正在回滚……\n失败原因:${message}`);
225
+ return await rollback(plan, message, databaseBackup, dependencies, log);
175
226
  }
176
227
  } finally {
177
228
  releaseUpdateLock(plan);
@@ -185,22 +236,32 @@ async function recoverBeforeInstallation(
185
236
  log: (event: string, data?: Record<string, unknown>) => void,
186
237
  ): Promise<SelfUpdateResult> {
187
238
  log("update_aborted_before_install", { error: waitError });
239
+ let recoveryError: string | undefined;
188
240
  if (plan.restartService) {
189
- let ready = await dependencies.waitForServer(plan.controlEndpoint, 2_000);
190
- if (!ready) {
241
+ try {
242
+ if (await dependencies.waitForServer(plan.controlEndpoint, 2_000)) {
243
+ const result: SelfUpdateResult = {
244
+ status: "failed", fromVersion: plan.fromVersion, toVersion: plan.toVersion,
245
+ activeVersion: plan.fromVersion, serviceReady: true, error: waitError,
246
+ completedAt: dependencies.now().toISOString(),
247
+ };
248
+ writeResult(plan.resultPath, result);
249
+ log("old_service_restart_failed", { ...result });
250
+ return result;
251
+ }
191
252
  process.env.AGENT_BOT_RESTART_REASON = `Agent Bot update aborted; running backup ${plan.fromVersion}`;
192
253
  dependencies.validatePackage(
193
254
  plan.backupPackageRoot,
194
255
  plan.packageName,
195
256
  plan.fromVersion,
196
257
  );
197
- dependencies.startSupervisor(
258
+ await dependencies.startSupervisor(
198
259
  plan.backupPackageRoot,
199
260
  plan.workingDirectory,
200
261
  );
201
- ready = await dependencies.waitForServer(plan.controlEndpoint, 60_000);
202
- }
203
- if (ready) {
262
+ if (!(await dependencies.waitForServer(plan.controlEndpoint, 60_000))) {
263
+ throw new Error("The backup Agent Bot service did not become ready within 60 seconds.");
264
+ }
204
265
  const result: SelfUpdateResult = {
205
266
  status: "rolled-back",
206
267
  fromVersion: plan.fromVersion,
@@ -214,6 +275,8 @@ async function recoverBeforeInstallation(
214
275
  writeResult(plan.resultPath, result);
215
276
  log("preinstall_recovery_completed", { ...result });
216
277
  return result;
278
+ } catch (error) {
279
+ recoveryError = errorMessage(error);
217
280
  }
218
281
  }
219
282
  const result: SelfUpdateResult = {
@@ -221,6 +284,7 @@ async function recoverBeforeInstallation(
221
284
  fromVersion: plan.fromVersion,
222
285
  toVersion: plan.toVersion,
223
286
  error: waitError,
287
+ ...(recoveryError ? { rollbackError: recoveryError } : {}),
224
288
  completedAt: dependencies.now().toISOString(),
225
289
  };
226
290
  writeResult(plan.resultPath, result);
@@ -236,6 +300,7 @@ async function rollback(
236
300
  log: (event: string, data?: Record<string, unknown>) => void,
237
301
  ): Promise<SelfUpdateResult> {
238
302
  let rollbackError: string | undefined;
303
+ let rollbackSupervisorPid: number | undefined;
239
304
  try {
240
305
  installTarball(
241
306
  plan.backupTarball,
@@ -251,7 +316,7 @@ async function rollback(
251
316
  restoreDatabase(databaseBackup);
252
317
  if (plan.restartService) {
253
318
  process.env.AGENT_BOT_RESTART_REASON = `Agent Bot update failed; restored ${plan.fromVersion}`;
254
- dependencies.startSupervisor(plan.packageRoot, plan.workingDirectory);
319
+ rollbackSupervisorPid = await dependencies.startSupervisor(plan.packageRoot, plan.workingDirectory);
255
320
  if (!(await dependencies.waitForServer(plan.controlEndpoint, 60_000))) {
256
321
  throw new Error(
257
322
  "The restored Agent Bot service did not become ready within 60 seconds.",
@@ -274,6 +339,20 @@ async function rollback(
274
339
  } catch (error) {
275
340
  rollbackError = errorMessage(error);
276
341
  log("npm_rollback_failed", { error: rollbackError });
342
+ if (plan.restartService) {
343
+ try {
344
+ await dependencies.stopServer(plan.controlEndpoint, rollbackSupervisorPid);
345
+ } catch (stopError) {
346
+ const result: SelfUpdateResult = {
347
+ status: "failed", fromVersion: plan.fromVersion, toVersion: plan.toVersion,
348
+ error: updateError, rollbackError: `${rollbackError}; could not stop the restored service: ${errorMessage(stopError)}`,
349
+ completedAt: dependencies.now().toISOString(),
350
+ };
351
+ writeResult(plan.resultPath, result);
352
+ log("rollback_service_stop_failed", { ...result });
353
+ return result;
354
+ }
355
+ }
277
356
  }
278
357
 
279
358
  if (plan.restartService) {
@@ -285,7 +364,7 @@ async function rollback(
285
364
  );
286
365
  restoreDatabase(databaseBackup);
287
366
  process.env.AGENT_BOT_RESTART_REASON = `Agent Bot update failed; running backup ${plan.fromVersion}`;
288
- dependencies.startSupervisor(
367
+ await dependencies.startSupervisor(
289
368
  plan.backupPackageRoot,
290
369
  plan.workingDirectory,
291
370
  );
@@ -339,7 +418,7 @@ function installTarball(
339
418
  log("npm_install_finished", {
340
419
  tarball,
341
420
  status: result.status,
342
- stderr: result.stderr.trim().slice(-4_000),
421
+ stderr: sanitizeUpdateDiagnostic(result.stderr.trim()).slice(-4_000),
343
422
  });
344
423
  if (result.error) throw result.error;
345
424
  if (result.status !== 0) {
@@ -359,7 +438,7 @@ function initializeUpdatedProfile(
359
438
  const result = dependencies.initializeProfile(plan.packageRoot, plan.workingDirectory);
360
439
  log("profile_initialization_finished", {
361
440
  status: result.status,
362
- stderr: result.stderr.trim().slice(-4_000),
441
+ stderr: sanitizeUpdateDiagnostic(result.stderr.trim()).slice(-4_000),
363
442
  });
364
443
  if (result.error) throw result.error;
365
444
  if (result.status !== 0) {
@@ -396,18 +475,18 @@ export function validateInstalledPackage(
396
475
  const versionResult = runNode([cliEntry, "--version"], packageRoot);
397
476
  if (versionResult.status !== 0 || versionResult.stdout.trim() !== version) {
398
477
  throw new Error(
399
- `Updated CLI validation failed: ${versionResult.stderr.trim() || versionResult.stdout.trim()}.`,
478
+ `Updated CLI validation failed: ${versionResult.error?.message || versionResult.stderr.trim() || versionResult.stdout.trim() || `process exited with ${versionResult.status}`}.`,
400
479
  );
401
480
  }
402
481
  const helpResult = runNode([cliEntry, "--help"], packageRoot);
403
482
  if (helpResult.status !== 0 || !helpResult.stdout.includes("agentbot")) {
404
483
  throw new Error(
405
- `Updated CLI help validation failed: ${helpResult.stderr.trim() || helpResult.stdout.trim()}.`,
484
+ `Updated CLI help validation failed: ${helpResult.error?.message || helpResult.stderr.trim() || helpResult.stdout.trim() || `process exited with ${helpResult.status}`}.`,
406
485
  );
407
486
  }
408
487
  }
409
488
 
410
- function startSupervisor(packageRoot: string, cwd: string): number | undefined {
489
+ function startSupervisor(packageRoot: string, cwd: string): Promise<number> {
411
490
  const child = spawn(
412
491
  process.execPath,
413
492
  [path.join(packageRoot, "dist", "supervisor.js")],
@@ -416,11 +495,13 @@ function startSupervisor(packageRoot: string, cwd: string): number | undefined {
416
495
  detached: true,
417
496
  windowsHide: true,
418
497
  stdio: "ignore",
419
- env: process.env,
498
+ env: runtimeEnvironment(),
420
499
  },
421
500
  );
422
- child.unref();
423
- return child.pid;
501
+ return new Promise((resolve, reject) => {
502
+ child.once("error", reject);
503
+ child.once("spawn", () => { child.unref(); resolve(child.pid!); });
504
+ });
424
505
  }
425
506
 
426
507
  function initializeProfile(packageRoot: string, cwd: string): CommandResult {
@@ -458,25 +539,20 @@ async function stopServer(
458
539
  endpoint: string,
459
540
  supervisorPid?: number,
460
541
  ): Promise<void> {
542
+ const health = await sendControlRequest(endpoint, { action: "health" }, 1_000).catch(() => undefined);
543
+ const data = isRecord(health?.data) ? health.data : undefined;
544
+ const oldPids = [supervisorPid, data?.supervisorPid, data?.pid,
545
+ ...(Array.isArray(data?.agents) ? data.agents.flatMap((agent: unknown) => isRecord(agent) ? [agent.pid] : []) : []),
546
+ ].filter((pid): pid is number => typeof pid === "number" && Number.isInteger(pid) && pid > 0 && pid !== process.pid);
461
547
  await sendControlRequest(endpoint, { action: "server_stop" }, 2_000).catch(
462
548
  () => undefined,
463
549
  );
464
- const deadline = Date.now() + 10_000;
465
- while (Date.now() < deadline) {
466
- if (!(await endpointReachable(endpoint))) break;
467
- await delay(250);
468
- }
469
- if (supervisorPid) {
470
- try {
471
- process.kill(supervisorPid, "SIGTERM");
472
- } catch {
473
- // The Supervisor may already have exited.
474
- }
475
- }
476
- if (supervisorPid) {
477
- const processDeadline = Date.now() + 5_000;
478
- while (processExists(supervisorPid) && Date.now() < processDeadline)
479
- await delay(250);
550
+ try {
551
+ await waitForProcesses(oldPids, 10_000);
552
+ } catch (error) {
553
+ const remainingPids = error instanceof ProcessExitTimeoutError ? error.pids : oldPids;
554
+ await forceTerminateUpdateProcesses(remainingPids);
555
+ await waitForProcesses(remainingPids, 5_000);
480
556
  }
481
557
  }
482
558
 
@@ -495,9 +571,7 @@ async function waitForProcesses(
495
571
  if (remaining.size > 0) await delay(250);
496
572
  }
497
573
  if (remaining.size > 0) {
498
- throw new Error(
499
- `Timed out waiting for Agent Bot processes to exit: ${[...remaining].join(", ")}.`,
500
- );
574
+ throw new ProcessExitTimeoutError([...remaining]);
501
575
  }
502
576
  }
503
577
 
@@ -510,6 +584,32 @@ function processExists(pid: number): boolean {
510
584
  }
511
585
  }
512
586
 
587
+ export async function forceTerminateUpdateProcesses(pids: number[]): Promise<void> {
588
+ for (const pid of new Set(pids)) {
589
+ if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid || !processExists(pid)) continue;
590
+ if (process.platform === "win32") {
591
+ // The process tree also contains this updater, so terminate only the recorded PIDs.
592
+ const result = commandResult(spawnSync("taskkill.exe", ["/F", "/PID", String(pid)], {
593
+ windowsHide: true, shell: false, encoding: "utf8", env: runtimeEnvironment(),
594
+ }));
595
+ if ((result.error || result.status !== 0) && processExists(pid)) {
596
+ throw new Error(`Could not terminate Agent Bot process ${pid}: ${errorMessage(result.error ?? (result.stderr.trim() || result.stdout.trim() || `taskkill exited with ${result.status}`))}`);
597
+ }
598
+ } else {
599
+ try { process.kill(pid, "SIGKILL"); } catch (error) {
600
+ if (processExists(pid)) throw error;
601
+ }
602
+ }
603
+ }
604
+ }
605
+
606
+ export function readSelfUpdateRecoveryAttemptIds(value: string | undefined): string[] {
607
+ try {
608
+ const parsed: unknown = JSON.parse(value ?? "[]");
609
+ return Array.isArray(parsed) ? [...new Set(parsed.filter((id): id is string => typeof id === "string" && id.trim().length > 0))] : [];
610
+ } catch { return []; }
611
+ }
612
+
513
613
  function sendControlRequest(
514
614
  endpoint: string,
515
615
  request: Record<string, unknown>,
@@ -556,44 +656,43 @@ function sendControlRequest(
556
656
  });
557
657
  }
558
658
 
559
- function endpointReachable(endpoint: string): Promise<boolean> {
560
- return sendControlRequest(endpoint, { action: "health" }, 500).then(
561
- () => true,
562
- () => false,
563
- );
564
- }
565
-
566
659
  export function runNpmCommand(args: string[], cwd: string): CommandResult {
567
660
  const npmCli = resolveNpmCli();
568
661
  if (npmCli) return runNode([npmCli, ...args], cwd);
662
+ if (process.platform === "win32") {
663
+ return { status: 1, stdout: "", stderr: "Cannot locate npm-cli.js. Check the Node.js/npm installation and PATH; Windows updates require npm's JavaScript entry point." };
664
+ }
569
665
  const result = spawnSync(
570
- process.platform === "win32" ? "npm.cmd" : "npm",
666
+ "npm",
571
667
  args,
572
668
  {
573
669
  cwd,
574
- env: process.env,
670
+ env: runtimeEnvironment(),
575
671
  windowsHide: true,
576
672
  encoding: "utf8",
577
673
  maxBuffer: 32 * 1024 * 1024,
578
- shell: process.platform === "win32",
579
674
  },
580
675
  );
581
676
  return commandResult(result);
582
677
  }
583
678
 
584
- function resolveNpmCli(): string | undefined {
679
+ export function resolveNpmCli(
680
+ environment: NodeJS.ProcessEnv = process.env,
681
+ executable = process.execPath,
682
+ ): string | undefined {
683
+ const searchPath = Object.entries(environment).find(([key]) => key.toLowerCase() === "path")?.[1];
585
684
  const candidates = [
586
- process.env.npm_execpath,
685
+ environment.npm_execpath,
587
686
  path.join(
588
- path.dirname(process.execPath),
687
+ path.dirname(executable),
589
688
  "node_modules",
590
689
  "npm",
591
690
  "bin",
592
691
  "npm-cli.js",
593
692
  ),
594
- process.env.APPDATA
693
+ environment.APPDATA
595
694
  ? path.join(
596
- process.env.APPDATA,
695
+ environment.APPDATA,
597
696
  "npm",
598
697
  "node_modules",
599
698
  "npm",
@@ -601,9 +700,11 @@ function resolveNpmCli(): string | undefined {
601
700
  "npm-cli.js",
602
701
  )
603
702
  : undefined,
703
+ ...(searchPath?.split(path.delimiter) ?? []).map((directory) =>
704
+ path.join(directory.replace(/^"|"$/g, ""), "node_modules", "npm", "bin", "npm-cli.js")),
604
705
  ];
605
706
  return candidates.find((candidate): candidate is string =>
606
- Boolean(candidate && fs.existsSync(candidate)),
707
+ Boolean(candidate && path.basename(candidate) === "npm-cli.js" && fs.existsSync(candidate)),
607
708
  );
608
709
  }
609
710
 
@@ -611,7 +712,7 @@ function runNode(args: string[], cwd: string): CommandResult {
611
712
  return commandResult(
612
713
  spawnSync(process.execPath, args, {
613
714
  cwd,
614
- env: process.env,
715
+ env: runtimeEnvironment(),
615
716
  windowsHide: true,
616
717
  encoding: "utf8",
617
718
  maxBuffer: 32 * 1024 * 1024,
@@ -621,7 +722,7 @@ function runNode(args: string[], cwd: string): CommandResult {
621
722
 
622
723
  function commandResult(result: ReturnType<typeof spawnSync>): CommandResult {
623
724
  return {
624
- status: result.status ?? (result.error ? 1 : 0),
725
+ status: result.status ?? 1,
625
726
  stdout:
626
727
  typeof result.stdout === "string"
627
728
  ? result.stdout
@@ -630,7 +731,7 @@ function commandResult(result: ReturnType<typeof spawnSync>): CommandResult {
630
731
  typeof result.stderr === "string"
631
732
  ? result.stderr
632
733
  : (result.stderr?.toString("utf8") ?? ""),
633
- ...(result.error ? { error: result.error } : {}),
734
+ ...(result.error ? { error: result.error } : result.signal ? { error: new Error(`Command terminated by ${result.signal}.`) } : {}),
634
735
  };
635
736
  }
636
737
 
@@ -721,30 +822,87 @@ function releaseUpdateLock(plan: SelfUpdatePlan): void {
721
822
  }
722
823
 
723
824
  function markUpdateRunning(plan: SelfUpdatePlan): void {
724
- fs.writeFileSync(
725
- plan.pendingMarkerPath,
726
- `${JSON.stringify(
727
- {
728
- token: plan.lockToken,
729
- phase: "running",
730
- planPath: path.join(path.dirname(plan.resultPath), "plan.json"),
731
- runnerPid: process.pid,
732
- startedAt: new Date().toISOString(),
733
- },
734
- null,
735
- 2,
736
- )}\n`,
737
- );
825
+ writeSelfUpdateJson(plan.pendingMarkerPath, {
826
+ token: plan.lockToken, phase: "running",
827
+ planPath: path.join(path.dirname(plan.resultPath), "plan.json"),
828
+ runnerPid: process.pid, startedAt: new Date().toISOString(),
829
+ });
738
830
  }
739
831
 
740
832
  function writeResult(resultPath: string, result: SelfUpdateResult): void {
741
- fs.writeFileSync(resultPath, `${JSON.stringify(result, null, 2)}\n`);
833
+ writeSelfUpdateJson(resultPath, result);
834
+ }
835
+
836
+ export function writeSelfUpdateJson(resultPath: string, value: unknown): void {
837
+ const temporaryPath = `${resultPath}.tmp`;
838
+ fs.writeFileSync(temporaryPath, `${JSON.stringify(value, null, 2)}\n`);
839
+ fs.renameSync(temporaryPath, resultPath);
840
+ }
841
+
842
+ async function reportUpdateProgress(
843
+ plan: SelfUpdatePlan,
844
+ dependencies: SelfUpdateRunnerDependencies,
845
+ message: string,
846
+ result?: SelfUpdateResult,
847
+ ): Promise<void> {
848
+ fs.mkdirSync(path.dirname(plan.logPath), { recursive: true });
849
+ message = sanitizeUpdateDiagnostic(message);
850
+ fs.appendFileSync(plan.logPath, JSON.stringify({ timestamp: dependencies.now().toISOString(), event: "update_progress", message }) + "\n");
851
+ try {
852
+ const attempts = result ? 3 : 1;
853
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
854
+ try { await dependencies.notifyProgress?.(plan, message, result); break; } catch (error) {
855
+ if (attempt + 1 === attempts) throw error;
856
+ await delay(500);
857
+ }
858
+ }
859
+ } catch (error) {
860
+ fs.appendFileSync(plan.logPath, JSON.stringify({ event: "update_notification_failed", error: errorMessage(error) }) + "\n");
861
+ }
742
862
  }
743
863
 
744
864
  function readPlan(planPath: string): SelfUpdatePlan {
745
865
  return JSON.parse(fs.readFileSync(planPath, "utf8")) as SelfUpdatePlan;
746
866
  }
747
867
 
868
+ let notificationToken: { value: string; expiresAt: number } | undefined;
869
+
870
+ export async function notifySelfUpdateProgress(plan: SelfUpdatePlan, message: string, result?: SelfUpdateResult): Promise<void> {
871
+ if (!plan.notificationMessageId) return;
872
+ const appId = process.env.AGENT_BOT_UPDATE_APP_ID;
873
+ const appSecret = process.env.AGENT_BOT_UPDATE_APP_SECRET;
874
+ if (!appId || !appSecret) throw new Error("Update card credentials are unavailable.");
875
+ if (!notificationToken || notificationToken.expiresAt <= Date.now()) {
876
+ const response = await fetch("https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal", {
877
+ method: "POST", headers: { "Content-Type": "application/json" },
878
+ body: JSON.stringify({ app_id: appId, app_secret: appSecret }), signal: AbortSignal.timeout(5_000),
879
+ });
880
+ const data = await response.json() as { code?: number; tenant_access_token?: string; expire?: number };
881
+ if (!response.ok || data.code !== 0 || !data.tenant_access_token) throw new Error(`Update card authentication failed (HTTP ${response.status}, code ${data.code}).`);
882
+ notificationToken = { value: data.tenant_access_token, expiresAt: Date.now() + ((data.expire ?? 7200) - 60) * 1000 };
883
+ }
884
+ const diagnostic = sanitizeUpdateDiagnostic([result?.error, result?.rollbackError].filter(Boolean).join("\n")).slice(-3000);
885
+ const content = [sanitizeUpdateDiagnostic(message).slice(-3000), diagnostic ? `失败原因:${diagnostic}` : ""].filter(Boolean).join("\n");
886
+ const literal = content.split(/\r?\n/).map((line) => `\`${line.replaceAll("`", "'")}\``).join("\n");
887
+ const card = {
888
+ schema: "2.0", config: { update_multi: true, width_mode: "fill" },
889
+ header: { title: { tag: "plain_text", content: "Agent Bot 更新" }, template: result ? result.status === "updated" ? "green" : "red" : "blue" },
890
+ body: { elements: [
891
+ { tag: "markdown", content: `**${plan.fromVersion} → ${plan.toVersion}**` },
892
+ { tag: "markdown", content: literal },
893
+ ] },
894
+ };
895
+ const response = await fetch(`https://open.feishu.cn/open-apis/im/v1/messages/${encodeURIComponent(plan.notificationMessageId)}`, {
896
+ method: "PATCH", headers: { Authorization: `Bearer ${notificationToken.value}`, "Content-Type": "application/json" },
897
+ body: JSON.stringify({ content: JSON.stringify(card) }), signal: AbortSignal.timeout(5_000),
898
+ });
899
+ const data = await response.json() as { code?: number };
900
+ if (!response.ok || data.code !== 0) {
901
+ notificationToken = undefined;
902
+ throw new Error(`Update card refresh failed (HTTP ${response.status}, code ${data.code}).`);
903
+ }
904
+ }
905
+
748
906
  function writeFatalResult(
749
907
  plan: SelfUpdatePlan | undefined,
750
908
  error: unknown,
@@ -780,7 +938,23 @@ function isRecord(value: unknown): value is Record<string, unknown> {
780
938
  }
781
939
 
782
940
  function errorMessage(error: unknown): string {
783
- return error instanceof Error ? error.message : String(error);
941
+ return sanitizeUpdateDiagnostic(error instanceof Error ? error.message : String(error));
942
+ }
943
+
944
+ function runtimeEnvironment(): NodeJS.ProcessEnv {
945
+ const environment = { ...process.env };
946
+ delete environment.AGENT_BOT_UPDATE_APP_ID;
947
+ delete environment.AGENT_BOT_UPDATE_APP_SECRET;
948
+ return environment;
949
+ }
950
+
951
+ export function sanitizeUpdateDiagnostic(text: string): string {
952
+ let result = text.replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gi, "$1[redacted]@")
953
+ .replace(/((?:_authToken|token|secret|password|api[_-]?key)\s*[=:]\s*)[^\s&,;]+/gi, "$1[redacted]");
954
+ for (const [key, value] of Object.entries(process.env)) {
955
+ if (/token|secret|password|api.?key/i.test(key) && value && value.length >= 4) result = result.split(value).join("[redacted]");
956
+ }
957
+ return result;
784
958
  }
785
959
 
786
960
  function delay(ms: number): Promise<void> {
@@ -795,7 +969,9 @@ const defaultDependencies: SelfUpdateRunnerDependencies = {
795
969
  waitForServer,
796
970
  stopServer,
797
971
  waitForProcesses,
972
+ forceTerminateProcesses: forceTerminateUpdateProcesses,
798
973
  now: () => new Date(),
974
+ notifyProgress: notifySelfUpdateProgress,
799
975
  };
800
976
 
801
977
  const invokedDirectly =
@@ -808,13 +984,23 @@ if (invokedDirectly) {
808
984
  void (async () => {
809
985
  if (!planPath) throw new Error("Missing Agent Bot update plan path.");
810
986
  plan = readPlan(planPath);
987
+ validatePlan(plan);
988
+ assertUpdateLock(plan);
989
+ if (process.send) {
990
+ await new Promise<void>((resolve, reject) => process.send!({ status: "ready" }, (error: Error | null) => error ? reject(error) : resolve()));
991
+ if (process.connected) process.disconnect();
992
+ }
811
993
  const result = await applySelfUpdatePlan(
812
994
  plan,
813
995
  parseWaitPids(process.argv.slice(3)),
814
996
  );
815
- if (result.status === "failed") process.exitCode = 1;
816
- })().catch((error: unknown) => {
997
+ if (result.status !== "updated") process.exitCode = 1;
998
+ })().catch(async (error: unknown) => {
817
999
  writeFatalResult(plan, error);
1000
+ if (plan) await reportUpdateProgress(plan, defaultDependencies, `更新失败:${errorMessage(error)}`, {
1001
+ status: "failed", fromVersion: plan.fromVersion, toVersion: plan.toVersion, error: errorMessage(error), completedAt: new Date().toISOString(),
1002
+ }).catch(() => undefined);
1003
+ process.stderr.write(errorMessage(error) + "\n");
818
1004
  process.exitCode = 1;
819
1005
  });
820
1006
  }