@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.
- package/CHANGELOG.md +18 -0
- package/README.md +77 -12
- package/README.zh.md +77 -12
- package/assets/agent-bot.ico +0 -0
- package/assets/roboto-mono-OFL.txt +93 -0
- package/assets/roboto-mono-latin.woff2 +0 -0
- package/assets/workspace-drafts.js +88 -0
- package/assets/workspace-sessions.js +1935 -232
- package/assets/workspace.css +360 -35
- package/assets/workspace.js +2115 -249
- package/dist/cli/SelfUpdateObserver.js +124 -0
- package/dist/cli/SelfUpdateObserver.js.map +1 -0
- package/dist/cli/SelfUpdateRunner.js +267 -70
- package/dist/cli/SelfUpdateRunner.js.map +1 -1
- package/dist/cli/SelfUpdater.js +54 -15
- package/dist/cli/SelfUpdater.js.map +1 -1
- package/dist/cli/controlProtocol.js.map +1 -1
- package/dist/cli/help.js +6 -0
- package/dist/cli/help.js.map +1 -1
- package/dist/cli.js +85 -6
- package/dist/cli.js.map +1 -1
- package/dist/codex/CodexEventMapper.js +29 -5
- package/dist/codex/CodexEventMapper.js.map +1 -1
- package/dist/codex/CodexRuntime.js +3 -0
- package/dist/codex/CodexRuntime.js.map +1 -1
- package/dist/feishu/CardRenderer.js +45 -13
- package/dist/feishu/CardRenderer.js.map +1 -1
- package/dist/feishu/ConsoleFeishuClient.js +4 -0
- package/dist/feishu/ConsoleFeishuClient.js.map +1 -1
- package/dist/feishu/FeishuMarkdown.js +2 -14
- package/dist/feishu/FeishuMarkdown.js.map +1 -1
- package/dist/feishu/FeishuMessageClient.js +9 -0
- package/dist/feishu/FeishuMessageClient.js.map +1 -1
- package/dist/feishu/FeishuTurnPresenter.js +26 -14
- package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
- package/dist/index.js +47 -12
- package/dist/index.js.map +1 -1
- package/dist/local-files/DiagramPreview.js +11 -6
- package/dist/local-files/DiagramPreview.js.map +1 -1
- package/dist/local-files/GitDiffPreview.js +40 -10
- package/dist/local-files/GitDiffPreview.js.map +1 -1
- package/dist/local-files/LiveMarkup.js +104 -0
- package/dist/local-files/LiveMarkup.js.map +1 -0
- package/dist/local-files/LocalFileViewerServer.js +133 -117
- package/dist/local-files/LocalFileViewerServer.js.map +1 -1
- package/dist/local-files/MarkdownExport.js +54 -0
- package/dist/local-files/MarkdownExport.js.map +1 -0
- package/dist/local-files/PreviewCodeFont.js +11 -0
- package/dist/local-files/PreviewCodeFont.js.map +1 -0
- package/dist/local-files/PreviewSyntaxHighlight.js +73 -0
- package/dist/local-files/PreviewSyntaxHighlight.js.map +1 -1
- package/dist/local-files/ToolCommandDisplay.js +111 -0
- package/dist/local-files/ToolCommandDisplay.js.map +1 -0
- package/dist/local-files/TurnPreviewPage.js +23 -269
- package/dist/local-files/TurnPreviewPage.js.map +1 -1
- package/dist/local-files/WorkspaceFileEvents.js +206 -0
- package/dist/local-files/WorkspaceFileEvents.js.map +1 -0
- package/dist/local-files/WorkspaceFiles.js +79 -3
- package/dist/local-files/WorkspaceFiles.js.map +1 -1
- package/dist/local-files/WorkspaceImages.js +15 -0
- package/dist/local-files/WorkspaceImages.js.map +1 -0
- package/dist/local-files/WorkspacePage.js +20 -5
- package/dist/local-files/WorkspacePage.js.map +1 -1
- package/dist/local-files/WorkspaceSessions.js +881 -79
- package/dist/local-files/WorkspaceSessions.js.map +1 -1
- package/dist/local-files/WorkspaceTimeline.js +105 -0
- package/dist/local-files/WorkspaceTimeline.js.map +1 -0
- package/dist/presentation/OutboundRouter.js +13 -6
- package/dist/presentation/OutboundRouter.js.map +1 -1
- package/dist/presentation/TurnStateReducer.js +28 -21
- package/dist/presentation/TurnStateReducer.js.map +1 -1
- package/dist/proxy/ProxySessionController.js +229 -92
- package/dist/proxy/ProxySessionController.js.map +1 -1
- package/dist/proxy/TaskMetadata.js +86 -0
- package/dist/proxy/TaskMetadata.js.map +1 -0
- package/dist/scheduling/ScheduleCards.js +10 -4
- package/dist/scheduling/ScheduleCards.js.map +1 -1
- package/dist/scheduling/ScheduleCommand.js +4 -0
- package/dist/scheduling/ScheduleCommand.js.map +1 -1
- package/dist/scheduling/ScheduledTaskStore.js +51 -12
- package/dist/scheduling/ScheduledTaskStore.js.map +1 -1
- package/dist/scheduling/types.js +18 -4
- package/dist/scheduling/types.js.map +1 -1
- package/dist/state/StateStore.js +145 -19
- package/dist/state/StateStore.js.map +1 -1
- package/dist/state/TurnPreviewJournal.js +143 -36
- package/dist/state/TurnPreviewJournal.js.map +1 -1
- package/dist/state/TurnToolText.js +172 -0
- package/dist/state/TurnToolText.js.map +1 -0
- package/dist/state/migrations.js +4 -0
- package/dist/state/migrations.js.map +1 -1
- package/dist/supervision/SafeRestartNotifier.js +9 -6
- package/dist/supervision/SafeRestartNotifier.js.map +1 -1
- package/dist/terminal/TerminalPage.js +5 -0
- package/dist/terminal/TerminalPage.js.map +1 -1
- package/dist/updates/AutomaticUpdatePreparer.js +63 -12
- package/dist/updates/AutomaticUpdatePreparer.js.map +1 -1
- package/dist/updates/ManualUpdateController.js +7 -2
- package/dist/updates/ManualUpdateController.js.map +1 -1
- package/dist/utils/promptAttachments.js +20 -0
- package/dist/utils/promptAttachments.js.map +1 -0
- package/dist/utils/toolTimestamp.js +6 -0
- package/dist/utils/toolTimestamp.js.map +1 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/skills/agent-bot/SKILL.md +23 -2
- package/src/cli/SelfUpdateObserver.ts +111 -0
- package/src/cli/SelfUpdateRunner.ts +271 -85
- package/src/cli/SelfUpdater.ts +53 -16
- package/src/cli/controlProtocol.ts +1 -0
- package/src/cli/help.ts +6 -0
- package/src/cli.ts +71 -5
- package/src/codex/CodexEventMapper.ts +25 -5
- package/src/codex/CodexRuntime.ts +4 -0
- package/src/feishu/CardRenderer.ts +48 -13
- package/src/feishu/ConsoleFeishuClient.ts +6 -1
- package/src/feishu/FeishuMarkdown.ts +2 -14
- package/src/feishu/FeishuMessageClient.ts +10 -0
- package/src/feishu/FeishuTurnPresenter.ts +22 -8
- package/src/feishu/types.ts +1 -0
- package/src/index.ts +47 -12
- package/src/local-files/DiagramPreview.ts +11 -6
- package/src/local-files/GitDiffPreview.ts +38 -10
- package/src/local-files/LiveMarkup.ts +103 -0
- package/src/local-files/LocalFileViewerServer.ts +120 -120
- package/src/local-files/MarkdownExport.ts +54 -0
- package/src/local-files/PreviewCodeFont.ts +12 -0
- package/src/local-files/PreviewSyntaxHighlight.ts +75 -0
- package/src/local-files/ToolCommandDisplay.ts +104 -0
- package/src/local-files/TurnPreviewPage.ts +23 -254
- package/src/local-files/WorkspaceFileEvents.ts +186 -0
- package/src/local-files/WorkspaceFiles.ts +72 -5
- package/src/local-files/WorkspaceImages.ts +10 -0
- package/src/local-files/WorkspacePage.ts +20 -5
- package/src/local-files/WorkspaceSessions.ts +811 -82
- package/src/local-files/WorkspaceTimeline.ts +109 -0
- package/src/presentation/OutboundRouter.ts +15 -4
- package/src/presentation/TurnStateReducer.ts +27 -18
- package/src/presentation/turnViewTypes.ts +2 -0
- package/src/proxy/ProxySessionController.ts +226 -77
- package/src/proxy/TaskMetadata.ts +81 -0
- package/src/runtime/types.ts +2 -1
- package/src/scheduling/ScheduleCards.ts +10 -4
- package/src/scheduling/ScheduleCommand.ts +4 -0
- package/src/scheduling/ScheduledTaskStore.ts +54 -9
- package/src/scheduling/types.ts +24 -4
- package/src/state/StateStore.ts +157 -20
- package/src/state/TurnPreviewJournal.ts +138 -34
- package/src/state/TurnToolText.ts +156 -0
- package/src/state/migrations.ts +4 -0
- package/src/supervision/SafeRestartNotifier.ts +9 -6
- package/src/terminal/TerminalPage.ts +5 -0
- package/src/updates/AutomaticUpdatePreparer.ts +52 -11
- package/src/updates/ManualUpdateController.ts +8 -3
- package/src/utils/promptAttachments.ts +24 -0
- package/src/utils/toolTimestamp.ts +5 -0
|
@@ -4,9 +4,27 @@ import net from "node:net";
|
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
6
|
export const SELF_UPDATE_PLAN_VERSION = 1;
|
|
7
|
+
export const SELF_UPDATE_RECOVERY_ATTEMPTS_ENV = "AGENT_BOT_UPDATE_RECOVERY_ATTEMPTS";
|
|
8
|
+
class ProcessExitTimeoutError extends Error {
|
|
9
|
+
pids;
|
|
10
|
+
constructor(pids) {
|
|
11
|
+
super(`Timed out waiting for Agent Bot processes to exit: ${pids.join(", ")}.`);
|
|
12
|
+
this.pids = pids;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
7
15
|
export async function applySelfUpdatePlan(plan, waitPids = [], dependencies = defaultDependencies) {
|
|
16
|
+
waitPids = [...new Set([...waitPids, ...(plan.preparationPid ? [plan.preparationPid] : [])])];
|
|
17
|
+
const result = await runSelfUpdatePlan(plan, waitPids, dependencies);
|
|
18
|
+
const message = result.status === "updated" ? `更新完成,当前版本 ${result.activeVersion}。`
|
|
19
|
+
: result.status === "rolled-back" ? `更新失败,已恢复 ${result.activeVersion}。`
|
|
20
|
+
: result.serviceReady ? "更新失败,旧服务仍在线,未能完成重启。" : "更新失败,服务未能自动恢复。";
|
|
21
|
+
await reportUpdateProgress(plan, dependencies, message, result);
|
|
22
|
+
return result;
|
|
23
|
+
}
|
|
24
|
+
async function runSelfUpdatePlan(plan, waitPids, dependencies) {
|
|
8
25
|
validatePlan(plan);
|
|
9
26
|
assertUpdateLock(plan);
|
|
27
|
+
process.env[SELF_UPDATE_RECOVERY_ATTEMPTS_ENV] = JSON.stringify(plan.recoveryAttemptIds ?? []);
|
|
10
28
|
markUpdateRunning(plan);
|
|
11
29
|
fs.mkdirSync(path.dirname(plan.logPath), { recursive: true });
|
|
12
30
|
const log = (event, data = {}) => {
|
|
@@ -23,13 +41,28 @@ export async function applySelfUpdatePlan(plan, waitPids = [], dependencies = de
|
|
|
23
41
|
waitPids,
|
|
24
42
|
});
|
|
25
43
|
try {
|
|
26
|
-
await
|
|
44
|
+
await Promise.all([
|
|
45
|
+
(async () => {
|
|
46
|
+
try {
|
|
47
|
+
await dependencies.waitForProcesses(waitPids, 10_000);
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
const remainingPids = error instanceof ProcessExitTimeoutError ? error.pids : waitPids;
|
|
51
|
+
log("old_process_exit_timeout", { waitPids: remainingPids, error: errorMessage(error) });
|
|
52
|
+
await dependencies.forceTerminateProcesses(remainingPids);
|
|
53
|
+
await dependencies.waitForProcesses(remainingPids, 5_000);
|
|
54
|
+
log("old_processes_force_terminated", { waitPids: remainingPids });
|
|
55
|
+
}
|
|
56
|
+
})(),
|
|
57
|
+
reportUpdateProgress(plan, dependencies, "正在等待旧进程退出;超过 10 秒将强制终止本次更新涉及的旧进程……"),
|
|
58
|
+
]);
|
|
27
59
|
}
|
|
28
60
|
catch (error) {
|
|
29
|
-
return recoverBeforeInstallation(plan, errorMessage(error), dependencies, log);
|
|
61
|
+
return await recoverBeforeInstallation(plan, errorMessage(error), dependencies, log);
|
|
30
62
|
}
|
|
31
63
|
let databaseBackup;
|
|
32
64
|
try {
|
|
65
|
+
await reportUpdateProgress(plan, dependencies, "正在备份任务数据库……");
|
|
33
66
|
databaseBackup = createDatabaseBackup(plan);
|
|
34
67
|
log("database_backup_created", {
|
|
35
68
|
directory: databaseBackup.directory,
|
|
@@ -37,15 +70,19 @@ export async function applySelfUpdatePlan(plan, waitPids = [], dependencies = de
|
|
|
37
70
|
});
|
|
38
71
|
}
|
|
39
72
|
catch (error) {
|
|
40
|
-
return recoverBeforeInstallation(plan, `Could not back up Agent Bot state: ${errorMessage(error)}`, dependencies, log);
|
|
73
|
+
return await recoverBeforeInstallation(plan, `Could not back up Agent Bot state: ${errorMessage(error)}`, dependencies, log);
|
|
41
74
|
}
|
|
42
75
|
let startedSupervisorPid;
|
|
43
76
|
try {
|
|
77
|
+
await reportUpdateProgress(plan, dependencies, `正在安装 Agent Bot ${plan.toVersion}……`);
|
|
44
78
|
installTarball(plan.candidateTarball, plan.workingDirectory, dependencies, log);
|
|
79
|
+
await reportUpdateProgress(plan, dependencies, "正在校验已安装版本……");
|
|
45
80
|
dependencies.validatePackage(plan.packageRoot, plan.packageName, plan.toVersion);
|
|
81
|
+
await reportUpdateProgress(plan, dependencies, "正在初始化更新后的配置……");
|
|
46
82
|
initializeUpdatedProfile(plan, dependencies, log);
|
|
47
83
|
if (plan.restartService) {
|
|
48
|
-
|
|
84
|
+
await reportUpdateProgress(plan, dependencies, "正在启动服务并等待就绪……");
|
|
85
|
+
startedSupervisorPid = await dependencies.startSupervisor(plan.packageRoot, plan.workingDirectory);
|
|
49
86
|
if (!(await dependencies.waitForServer(plan.controlEndpoint, 60_000))) {
|
|
50
87
|
throw new Error("The updated Agent Bot service did not become ready within 60 seconds.");
|
|
51
88
|
}
|
|
@@ -67,15 +104,22 @@ export async function applySelfUpdatePlan(plan, waitPids = [], dependencies = de
|
|
|
67
104
|
const message = errorMessage(error);
|
|
68
105
|
log("update_failed", { error: message });
|
|
69
106
|
if (plan.restartService) {
|
|
70
|
-
|
|
71
|
-
.stopServer(plan.controlEndpoint, startedSupervisorPid)
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
107
|
+
try {
|
|
108
|
+
await dependencies.stopServer(plan.controlEndpoint, startedSupervisorPid);
|
|
109
|
+
}
|
|
110
|
+
catch (stopError) {
|
|
111
|
+
const result = {
|
|
112
|
+
status: "failed", fromVersion: plan.fromVersion, toVersion: plan.toVersion,
|
|
113
|
+
error: message, rollbackError: `Could not stop the updated service: ${errorMessage(stopError)}`,
|
|
114
|
+
completedAt: dependencies.now().toISOString(),
|
|
115
|
+
};
|
|
116
|
+
writeResult(plan.resultPath, result);
|
|
117
|
+
log("updated_service_stop_failed", { ...result });
|
|
118
|
+
return result;
|
|
119
|
+
}
|
|
77
120
|
}
|
|
78
|
-
|
|
121
|
+
await reportUpdateProgress(plan, dependencies, `安装或启动失败,正在回滚……\n失败原因:${message}`);
|
|
122
|
+
return await rollback(plan, message, databaseBackup, dependencies, log);
|
|
79
123
|
}
|
|
80
124
|
}
|
|
81
125
|
finally {
|
|
@@ -84,15 +128,25 @@ export async function applySelfUpdatePlan(plan, waitPids = [], dependencies = de
|
|
|
84
128
|
}
|
|
85
129
|
async function recoverBeforeInstallation(plan, waitError, dependencies, log) {
|
|
86
130
|
log("update_aborted_before_install", { error: waitError });
|
|
131
|
+
let recoveryError;
|
|
87
132
|
if (plan.restartService) {
|
|
88
|
-
|
|
89
|
-
|
|
133
|
+
try {
|
|
134
|
+
if (await dependencies.waitForServer(plan.controlEndpoint, 2_000)) {
|
|
135
|
+
const result = {
|
|
136
|
+
status: "failed", fromVersion: plan.fromVersion, toVersion: plan.toVersion,
|
|
137
|
+
activeVersion: plan.fromVersion, serviceReady: true, error: waitError,
|
|
138
|
+
completedAt: dependencies.now().toISOString(),
|
|
139
|
+
};
|
|
140
|
+
writeResult(plan.resultPath, result);
|
|
141
|
+
log("old_service_restart_failed", { ...result });
|
|
142
|
+
return result;
|
|
143
|
+
}
|
|
90
144
|
process.env.AGENT_BOT_RESTART_REASON = `Agent Bot update aborted; running backup ${plan.fromVersion}`;
|
|
91
145
|
dependencies.validatePackage(plan.backupPackageRoot, plan.packageName, plan.fromVersion);
|
|
92
|
-
dependencies.startSupervisor(plan.backupPackageRoot, plan.workingDirectory);
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
146
|
+
await dependencies.startSupervisor(plan.backupPackageRoot, plan.workingDirectory);
|
|
147
|
+
if (!(await dependencies.waitForServer(plan.controlEndpoint, 60_000))) {
|
|
148
|
+
throw new Error("The backup Agent Bot service did not become ready within 60 seconds.");
|
|
149
|
+
}
|
|
96
150
|
const result = {
|
|
97
151
|
status: "rolled-back",
|
|
98
152
|
fromVersion: plan.fromVersion,
|
|
@@ -107,12 +161,16 @@ async function recoverBeforeInstallation(plan, waitError, dependencies, log) {
|
|
|
107
161
|
log("preinstall_recovery_completed", { ...result });
|
|
108
162
|
return result;
|
|
109
163
|
}
|
|
164
|
+
catch (error) {
|
|
165
|
+
recoveryError = errorMessage(error);
|
|
166
|
+
}
|
|
110
167
|
}
|
|
111
168
|
const result = {
|
|
112
169
|
status: "failed",
|
|
113
170
|
fromVersion: plan.fromVersion,
|
|
114
171
|
toVersion: plan.toVersion,
|
|
115
172
|
error: waitError,
|
|
173
|
+
...(recoveryError ? { rollbackError: recoveryError } : {}),
|
|
116
174
|
completedAt: dependencies.now().toISOString(),
|
|
117
175
|
};
|
|
118
176
|
writeResult(plan.resultPath, result);
|
|
@@ -121,13 +179,14 @@ async function recoverBeforeInstallation(plan, waitError, dependencies, log) {
|
|
|
121
179
|
}
|
|
122
180
|
async function rollback(plan, updateError, databaseBackup, dependencies, log) {
|
|
123
181
|
let rollbackError;
|
|
182
|
+
let rollbackSupervisorPid;
|
|
124
183
|
try {
|
|
125
184
|
installTarball(plan.backupTarball, plan.workingDirectory, dependencies, log);
|
|
126
185
|
dependencies.validatePackage(plan.packageRoot, plan.packageName, plan.fromVersion);
|
|
127
186
|
restoreDatabase(databaseBackup);
|
|
128
187
|
if (plan.restartService) {
|
|
129
188
|
process.env.AGENT_BOT_RESTART_REASON = `Agent Bot update failed; restored ${plan.fromVersion}`;
|
|
130
|
-
dependencies.startSupervisor(plan.packageRoot, plan.workingDirectory);
|
|
189
|
+
rollbackSupervisorPid = await dependencies.startSupervisor(plan.packageRoot, plan.workingDirectory);
|
|
131
190
|
if (!(await dependencies.waitForServer(plan.controlEndpoint, 60_000))) {
|
|
132
191
|
throw new Error("The restored Agent Bot service did not become ready within 60 seconds.");
|
|
133
192
|
}
|
|
@@ -149,13 +208,28 @@ async function rollback(plan, updateError, databaseBackup, dependencies, log) {
|
|
|
149
208
|
catch (error) {
|
|
150
209
|
rollbackError = errorMessage(error);
|
|
151
210
|
log("npm_rollback_failed", { error: rollbackError });
|
|
211
|
+
if (plan.restartService) {
|
|
212
|
+
try {
|
|
213
|
+
await dependencies.stopServer(plan.controlEndpoint, rollbackSupervisorPid);
|
|
214
|
+
}
|
|
215
|
+
catch (stopError) {
|
|
216
|
+
const result = {
|
|
217
|
+
status: "failed", fromVersion: plan.fromVersion, toVersion: plan.toVersion,
|
|
218
|
+
error: updateError, rollbackError: `${rollbackError}; could not stop the restored service: ${errorMessage(stopError)}`,
|
|
219
|
+
completedAt: dependencies.now().toISOString(),
|
|
220
|
+
};
|
|
221
|
+
writeResult(plan.resultPath, result);
|
|
222
|
+
log("rollback_service_stop_failed", { ...result });
|
|
223
|
+
return result;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
152
226
|
}
|
|
153
227
|
if (plan.restartService) {
|
|
154
228
|
try {
|
|
155
229
|
dependencies.validatePackage(plan.backupPackageRoot, plan.packageName, plan.fromVersion);
|
|
156
230
|
restoreDatabase(databaseBackup);
|
|
157
231
|
process.env.AGENT_BOT_RESTART_REASON = `Agent Bot update failed; running backup ${plan.fromVersion}`;
|
|
158
|
-
dependencies.startSupervisor(plan.backupPackageRoot, plan.workingDirectory);
|
|
232
|
+
await dependencies.startSupervisor(plan.backupPackageRoot, plan.workingDirectory);
|
|
159
233
|
if (!(await dependencies.waitForServer(plan.controlEndpoint, 60_000))) {
|
|
160
234
|
throw new Error("The backup Agent Bot service did not become ready within 60 seconds.");
|
|
161
235
|
}
|
|
@@ -195,7 +269,7 @@ function installTarball(tarball, cwd, dependencies, log) {
|
|
|
195
269
|
log("npm_install_finished", {
|
|
196
270
|
tarball,
|
|
197
271
|
status: result.status,
|
|
198
|
-
stderr: result.stderr.trim().slice(-4_000),
|
|
272
|
+
stderr: sanitizeUpdateDiagnostic(result.stderr.trim()).slice(-4_000),
|
|
199
273
|
});
|
|
200
274
|
if (result.error)
|
|
201
275
|
throw result.error;
|
|
@@ -209,7 +283,7 @@ function initializeUpdatedProfile(plan, dependencies, log) {
|
|
|
209
283
|
const result = dependencies.initializeProfile(plan.packageRoot, plan.workingDirectory);
|
|
210
284
|
log("profile_initialization_finished", {
|
|
211
285
|
status: result.status,
|
|
212
|
-
stderr: result.stderr.trim().slice(-4_000),
|
|
286
|
+
stderr: sanitizeUpdateDiagnostic(result.stderr.trim()).slice(-4_000),
|
|
213
287
|
});
|
|
214
288
|
if (result.error)
|
|
215
289
|
throw result.error;
|
|
@@ -232,11 +306,11 @@ export function validateInstalledPackage(packageRoot, packageName, version) {
|
|
|
232
306
|
}
|
|
233
307
|
const versionResult = runNode([cliEntry, "--version"], packageRoot);
|
|
234
308
|
if (versionResult.status !== 0 || versionResult.stdout.trim() !== version) {
|
|
235
|
-
throw new Error(`Updated CLI validation failed: ${versionResult.stderr.trim() || versionResult.stdout.trim()}.`);
|
|
309
|
+
throw new Error(`Updated CLI validation failed: ${versionResult.error?.message || versionResult.stderr.trim() || versionResult.stdout.trim() || `process exited with ${versionResult.status}`}.`);
|
|
236
310
|
}
|
|
237
311
|
const helpResult = runNode([cliEntry, "--help"], packageRoot);
|
|
238
312
|
if (helpResult.status !== 0 || !helpResult.stdout.includes("agentbot")) {
|
|
239
|
-
throw new Error(`Updated CLI help validation failed: ${helpResult.stderr.trim() || helpResult.stdout.trim()}.`);
|
|
313
|
+
throw new Error(`Updated CLI help validation failed: ${helpResult.error?.message || helpResult.stderr.trim() || helpResult.stdout.trim() || `process exited with ${helpResult.status}`}.`);
|
|
240
314
|
}
|
|
241
315
|
}
|
|
242
316
|
function startSupervisor(packageRoot, cwd) {
|
|
@@ -245,10 +319,12 @@ function startSupervisor(packageRoot, cwd) {
|
|
|
245
319
|
detached: true,
|
|
246
320
|
windowsHide: true,
|
|
247
321
|
stdio: "ignore",
|
|
248
|
-
env:
|
|
322
|
+
env: runtimeEnvironment(),
|
|
323
|
+
});
|
|
324
|
+
return new Promise((resolve, reject) => {
|
|
325
|
+
child.once("error", reject);
|
|
326
|
+
child.once("spawn", () => { child.unref(); resolve(child.pid); });
|
|
249
327
|
});
|
|
250
|
-
child.unref();
|
|
251
|
-
return child.pid;
|
|
252
328
|
}
|
|
253
329
|
function initializeProfile(packageRoot, cwd) {
|
|
254
330
|
return runNode([
|
|
@@ -271,25 +347,19 @@ async function waitForServer(endpoint, timeoutMs) {
|
|
|
271
347
|
return false;
|
|
272
348
|
}
|
|
273
349
|
async function stopServer(endpoint, supervisorPid) {
|
|
350
|
+
const health = await sendControlRequest(endpoint, { action: "health" }, 1_000).catch(() => undefined);
|
|
351
|
+
const data = isRecord(health?.data) ? health.data : undefined;
|
|
352
|
+
const oldPids = [supervisorPid, data?.supervisorPid, data?.pid,
|
|
353
|
+
...(Array.isArray(data?.agents) ? data.agents.flatMap((agent) => isRecord(agent) ? [agent.pid] : []) : []),
|
|
354
|
+
].filter((pid) => typeof pid === "number" && Number.isInteger(pid) && pid > 0 && pid !== process.pid);
|
|
274
355
|
await sendControlRequest(endpoint, { action: "server_stop" }, 2_000).catch(() => undefined);
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
if (!(await endpointReachable(endpoint)))
|
|
278
|
-
break;
|
|
279
|
-
await delay(250);
|
|
280
|
-
}
|
|
281
|
-
if (supervisorPid) {
|
|
282
|
-
try {
|
|
283
|
-
process.kill(supervisorPid, "SIGTERM");
|
|
284
|
-
}
|
|
285
|
-
catch {
|
|
286
|
-
// The Supervisor may already have exited.
|
|
287
|
-
}
|
|
356
|
+
try {
|
|
357
|
+
await waitForProcesses(oldPids, 10_000);
|
|
288
358
|
}
|
|
289
|
-
|
|
290
|
-
const
|
|
291
|
-
|
|
292
|
-
|
|
359
|
+
catch (error) {
|
|
360
|
+
const remainingPids = error instanceof ProcessExitTimeoutError ? error.pids : oldPids;
|
|
361
|
+
await forceTerminateUpdateProcesses(remainingPids);
|
|
362
|
+
await waitForProcesses(remainingPids, 5_000);
|
|
293
363
|
}
|
|
294
364
|
}
|
|
295
365
|
async function waitForProcesses(pids, timeoutMs) {
|
|
@@ -304,7 +374,7 @@ async function waitForProcesses(pids, timeoutMs) {
|
|
|
304
374
|
await delay(250);
|
|
305
375
|
}
|
|
306
376
|
if (remaining.size > 0) {
|
|
307
|
-
throw new
|
|
377
|
+
throw new ProcessExitTimeoutError([...remaining]);
|
|
308
378
|
}
|
|
309
379
|
}
|
|
310
380
|
function processExists(pid) {
|
|
@@ -316,6 +386,39 @@ function processExists(pid) {
|
|
|
316
386
|
return isRecord(error) && error.code === "EPERM";
|
|
317
387
|
}
|
|
318
388
|
}
|
|
389
|
+
export async function forceTerminateUpdateProcesses(pids) {
|
|
390
|
+
for (const pid of new Set(pids)) {
|
|
391
|
+
if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid || !processExists(pid))
|
|
392
|
+
continue;
|
|
393
|
+
if (process.platform === "win32") {
|
|
394
|
+
// The process tree also contains this updater, so terminate only the recorded PIDs.
|
|
395
|
+
const result = commandResult(spawnSync("taskkill.exe", ["/F", "/PID", String(pid)], {
|
|
396
|
+
windowsHide: true, shell: false, encoding: "utf8", env: runtimeEnvironment(),
|
|
397
|
+
}));
|
|
398
|
+
if ((result.error || result.status !== 0) && processExists(pid)) {
|
|
399
|
+
throw new Error(`Could not terminate Agent Bot process ${pid}: ${errorMessage(result.error ?? (result.stderr.trim() || result.stdout.trim() || `taskkill exited with ${result.status}`))}`);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
else {
|
|
403
|
+
try {
|
|
404
|
+
process.kill(pid, "SIGKILL");
|
|
405
|
+
}
|
|
406
|
+
catch (error) {
|
|
407
|
+
if (processExists(pid))
|
|
408
|
+
throw error;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
export function readSelfUpdateRecoveryAttemptIds(value) {
|
|
414
|
+
try {
|
|
415
|
+
const parsed = JSON.parse(value ?? "[]");
|
|
416
|
+
return Array.isArray(parsed) ? [...new Set(parsed.filter((id) => typeof id === "string" && id.trim().length > 0))] : [];
|
|
417
|
+
}
|
|
418
|
+
catch {
|
|
419
|
+
return [];
|
|
420
|
+
}
|
|
421
|
+
}
|
|
319
422
|
function sendControlRequest(endpoint, request, timeoutMs) {
|
|
320
423
|
return new Promise((resolve, reject) => {
|
|
321
424
|
const socket = net.createConnection(endpoint);
|
|
@@ -348,37 +451,38 @@ function sendControlRequest(endpoint, request, timeoutMs) {
|
|
|
348
451
|
socket.once("end", () => finish(() => reject(new Error("Control endpoint returned no response."))));
|
|
349
452
|
});
|
|
350
453
|
}
|
|
351
|
-
function endpointReachable(endpoint) {
|
|
352
|
-
return sendControlRequest(endpoint, { action: "health" }, 500).then(() => true, () => false);
|
|
353
|
-
}
|
|
354
454
|
export function runNpmCommand(args, cwd) {
|
|
355
455
|
const npmCli = resolveNpmCli();
|
|
356
456
|
if (npmCli)
|
|
357
457
|
return runNode([npmCli, ...args], cwd);
|
|
358
|
-
|
|
458
|
+
if (process.platform === "win32") {
|
|
459
|
+
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." };
|
|
460
|
+
}
|
|
461
|
+
const result = spawnSync("npm", args, {
|
|
359
462
|
cwd,
|
|
360
|
-
env:
|
|
463
|
+
env: runtimeEnvironment(),
|
|
361
464
|
windowsHide: true,
|
|
362
465
|
encoding: "utf8",
|
|
363
466
|
maxBuffer: 32 * 1024 * 1024,
|
|
364
|
-
shell: process.platform === "win32",
|
|
365
467
|
});
|
|
366
468
|
return commandResult(result);
|
|
367
469
|
}
|
|
368
|
-
function resolveNpmCli() {
|
|
470
|
+
export function resolveNpmCli(environment = process.env, executable = process.execPath) {
|
|
471
|
+
const searchPath = Object.entries(environment).find(([key]) => key.toLowerCase() === "path")?.[1];
|
|
369
472
|
const candidates = [
|
|
370
|
-
|
|
371
|
-
path.join(path.dirname(
|
|
372
|
-
|
|
373
|
-
? path.join(
|
|
473
|
+
environment.npm_execpath,
|
|
474
|
+
path.join(path.dirname(executable), "node_modules", "npm", "bin", "npm-cli.js"),
|
|
475
|
+
environment.APPDATA
|
|
476
|
+
? path.join(environment.APPDATA, "npm", "node_modules", "npm", "bin", "npm-cli.js")
|
|
374
477
|
: undefined,
|
|
478
|
+
...(searchPath?.split(path.delimiter) ?? []).map((directory) => path.join(directory.replace(/^"|"$/g, ""), "node_modules", "npm", "bin", "npm-cli.js")),
|
|
375
479
|
];
|
|
376
|
-
return candidates.find((candidate) => Boolean(candidate && fs.existsSync(candidate)));
|
|
480
|
+
return candidates.find((candidate) => Boolean(candidate && path.basename(candidate) === "npm-cli.js" && fs.existsSync(candidate)));
|
|
377
481
|
}
|
|
378
482
|
function runNode(args, cwd) {
|
|
379
483
|
return commandResult(spawnSync(process.execPath, args, {
|
|
380
484
|
cwd,
|
|
381
|
-
env:
|
|
485
|
+
env: runtimeEnvironment(),
|
|
382
486
|
windowsHide: true,
|
|
383
487
|
encoding: "utf8",
|
|
384
488
|
maxBuffer: 32 * 1024 * 1024,
|
|
@@ -386,14 +490,14 @@ function runNode(args, cwd) {
|
|
|
386
490
|
}
|
|
387
491
|
function commandResult(result) {
|
|
388
492
|
return {
|
|
389
|
-
status: result.status ??
|
|
493
|
+
status: result.status ?? 1,
|
|
390
494
|
stdout: typeof result.stdout === "string"
|
|
391
495
|
? result.stdout
|
|
392
496
|
: (result.stdout?.toString("utf8") ?? ""),
|
|
393
497
|
stderr: typeof result.stderr === "string"
|
|
394
498
|
? result.stderr
|
|
395
499
|
: (result.stderr?.toString("utf8") ?? ""),
|
|
396
|
-
...(result.error ? { error: result.error } : {}),
|
|
500
|
+
...(result.error ? { error: result.error } : result.signal ? { error: new Error(`Command terminated by ${result.signal}.`) } : {}),
|
|
397
501
|
};
|
|
398
502
|
}
|
|
399
503
|
function validatePlan(plan) {
|
|
@@ -471,20 +575,84 @@ function releaseUpdateLock(plan) {
|
|
|
471
575
|
}
|
|
472
576
|
}
|
|
473
577
|
function markUpdateRunning(plan) {
|
|
474
|
-
|
|
475
|
-
token: plan.lockToken,
|
|
476
|
-
phase: "running",
|
|
578
|
+
writeSelfUpdateJson(plan.pendingMarkerPath, {
|
|
579
|
+
token: plan.lockToken, phase: "running",
|
|
477
580
|
planPath: path.join(path.dirname(plan.resultPath), "plan.json"),
|
|
478
|
-
runnerPid: process.pid,
|
|
479
|
-
|
|
480
|
-
}, null, 2)}\n`);
|
|
581
|
+
runnerPid: process.pid, startedAt: new Date().toISOString(),
|
|
582
|
+
});
|
|
481
583
|
}
|
|
482
584
|
function writeResult(resultPath, result) {
|
|
483
|
-
|
|
585
|
+
writeSelfUpdateJson(resultPath, result);
|
|
586
|
+
}
|
|
587
|
+
export function writeSelfUpdateJson(resultPath, value) {
|
|
588
|
+
const temporaryPath = `${resultPath}.tmp`;
|
|
589
|
+
fs.writeFileSync(temporaryPath, `${JSON.stringify(value, null, 2)}\n`);
|
|
590
|
+
fs.renameSync(temporaryPath, resultPath);
|
|
591
|
+
}
|
|
592
|
+
async function reportUpdateProgress(plan, dependencies, message, result) {
|
|
593
|
+
fs.mkdirSync(path.dirname(plan.logPath), { recursive: true });
|
|
594
|
+
message = sanitizeUpdateDiagnostic(message);
|
|
595
|
+
fs.appendFileSync(plan.logPath, JSON.stringify({ timestamp: dependencies.now().toISOString(), event: "update_progress", message }) + "\n");
|
|
596
|
+
try {
|
|
597
|
+
const attempts = result ? 3 : 1;
|
|
598
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
599
|
+
try {
|
|
600
|
+
await dependencies.notifyProgress?.(plan, message, result);
|
|
601
|
+
break;
|
|
602
|
+
}
|
|
603
|
+
catch (error) {
|
|
604
|
+
if (attempt + 1 === attempts)
|
|
605
|
+
throw error;
|
|
606
|
+
await delay(500);
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
catch (error) {
|
|
611
|
+
fs.appendFileSync(plan.logPath, JSON.stringify({ event: "update_notification_failed", error: errorMessage(error) }) + "\n");
|
|
612
|
+
}
|
|
484
613
|
}
|
|
485
614
|
function readPlan(planPath) {
|
|
486
615
|
return JSON.parse(fs.readFileSync(planPath, "utf8"));
|
|
487
616
|
}
|
|
617
|
+
let notificationToken;
|
|
618
|
+
export async function notifySelfUpdateProgress(plan, message, result) {
|
|
619
|
+
if (!plan.notificationMessageId)
|
|
620
|
+
return;
|
|
621
|
+
const appId = process.env.AGENT_BOT_UPDATE_APP_ID;
|
|
622
|
+
const appSecret = process.env.AGENT_BOT_UPDATE_APP_SECRET;
|
|
623
|
+
if (!appId || !appSecret)
|
|
624
|
+
throw new Error("Update card credentials are unavailable.");
|
|
625
|
+
if (!notificationToken || notificationToken.expiresAt <= Date.now()) {
|
|
626
|
+
const response = await fetch("https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal", {
|
|
627
|
+
method: "POST", headers: { "Content-Type": "application/json" },
|
|
628
|
+
body: JSON.stringify({ app_id: appId, app_secret: appSecret }), signal: AbortSignal.timeout(5_000),
|
|
629
|
+
});
|
|
630
|
+
const data = await response.json();
|
|
631
|
+
if (!response.ok || data.code !== 0 || !data.tenant_access_token)
|
|
632
|
+
throw new Error(`Update card authentication failed (HTTP ${response.status}, code ${data.code}).`);
|
|
633
|
+
notificationToken = { value: data.tenant_access_token, expiresAt: Date.now() + ((data.expire ?? 7200) - 60) * 1000 };
|
|
634
|
+
}
|
|
635
|
+
const diagnostic = sanitizeUpdateDiagnostic([result?.error, result?.rollbackError].filter(Boolean).join("\n")).slice(-3000);
|
|
636
|
+
const content = [sanitizeUpdateDiagnostic(message).slice(-3000), diagnostic ? `失败原因:${diagnostic}` : ""].filter(Boolean).join("\n");
|
|
637
|
+
const literal = content.split(/\r?\n/).map((line) => `\`${line.replaceAll("`", "'")}\``).join("\n");
|
|
638
|
+
const card = {
|
|
639
|
+
schema: "2.0", config: { update_multi: true, width_mode: "fill" },
|
|
640
|
+
header: { title: { tag: "plain_text", content: "Agent Bot 更新" }, template: result ? result.status === "updated" ? "green" : "red" : "blue" },
|
|
641
|
+
body: { elements: [
|
|
642
|
+
{ tag: "markdown", content: `**${plan.fromVersion} → ${plan.toVersion}**` },
|
|
643
|
+
{ tag: "markdown", content: literal },
|
|
644
|
+
] },
|
|
645
|
+
};
|
|
646
|
+
const response = await fetch(`https://open.feishu.cn/open-apis/im/v1/messages/${encodeURIComponent(plan.notificationMessageId)}`, {
|
|
647
|
+
method: "PATCH", headers: { Authorization: `Bearer ${notificationToken.value}`, "Content-Type": "application/json" },
|
|
648
|
+
body: JSON.stringify({ content: JSON.stringify(card) }), signal: AbortSignal.timeout(5_000),
|
|
649
|
+
});
|
|
650
|
+
const data = await response.json();
|
|
651
|
+
if (!response.ok || data.code !== 0) {
|
|
652
|
+
notificationToken = undefined;
|
|
653
|
+
throw new Error(`Update card refresh failed (HTTP ${response.status}, code ${data.code}).`);
|
|
654
|
+
}
|
|
655
|
+
}
|
|
488
656
|
function writeFatalResult(plan, error) {
|
|
489
657
|
if (!plan)
|
|
490
658
|
return;
|
|
@@ -518,7 +686,22 @@ function isRecord(value) {
|
|
|
518
686
|
return Boolean(value) && typeof value === "object";
|
|
519
687
|
}
|
|
520
688
|
function errorMessage(error) {
|
|
521
|
-
return error instanceof Error ? error.message : String(error);
|
|
689
|
+
return sanitizeUpdateDiagnostic(error instanceof Error ? error.message : String(error));
|
|
690
|
+
}
|
|
691
|
+
function runtimeEnvironment() {
|
|
692
|
+
const environment = { ...process.env };
|
|
693
|
+
delete environment.AGENT_BOT_UPDATE_APP_ID;
|
|
694
|
+
delete environment.AGENT_BOT_UPDATE_APP_SECRET;
|
|
695
|
+
return environment;
|
|
696
|
+
}
|
|
697
|
+
export function sanitizeUpdateDiagnostic(text) {
|
|
698
|
+
let result = text.replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gi, "$1[redacted]@")
|
|
699
|
+
.replace(/((?:_authToken|token|secret|password|api[_-]?key)\s*[=:]\s*)[^\s&,;]+/gi, "$1[redacted]");
|
|
700
|
+
for (const [key, value] of Object.entries(process.env)) {
|
|
701
|
+
if (/token|secret|password|api.?key/i.test(key) && value && value.length >= 4)
|
|
702
|
+
result = result.split(value).join("[redacted]");
|
|
703
|
+
}
|
|
704
|
+
return result;
|
|
522
705
|
}
|
|
523
706
|
function delay(ms) {
|
|
524
707
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
@@ -531,7 +714,9 @@ const defaultDependencies = {
|
|
|
531
714
|
waitForServer,
|
|
532
715
|
stopServer,
|
|
533
716
|
waitForProcesses,
|
|
717
|
+
forceTerminateProcesses: forceTerminateUpdateProcesses,
|
|
534
718
|
now: () => new Date(),
|
|
719
|
+
notifyProgress: notifySelfUpdateProgress,
|
|
535
720
|
};
|
|
536
721
|
const invokedDirectly = process.argv[1] &&
|
|
537
722
|
path.resolve(process.argv[1]) ===
|
|
@@ -543,11 +728,23 @@ if (invokedDirectly) {
|
|
|
543
728
|
if (!planPath)
|
|
544
729
|
throw new Error("Missing Agent Bot update plan path.");
|
|
545
730
|
plan = readPlan(planPath);
|
|
731
|
+
validatePlan(plan);
|
|
732
|
+
assertUpdateLock(plan);
|
|
733
|
+
if (process.send) {
|
|
734
|
+
await new Promise((resolve, reject) => process.send({ status: "ready" }, (error) => error ? reject(error) : resolve()));
|
|
735
|
+
if (process.connected)
|
|
736
|
+
process.disconnect();
|
|
737
|
+
}
|
|
546
738
|
const result = await applySelfUpdatePlan(plan, parseWaitPids(process.argv.slice(3)));
|
|
547
|
-
if (result.status
|
|
739
|
+
if (result.status !== "updated")
|
|
548
740
|
process.exitCode = 1;
|
|
549
|
-
})().catch((error) => {
|
|
741
|
+
})().catch(async (error) => {
|
|
550
742
|
writeFatalResult(plan, error);
|
|
743
|
+
if (plan)
|
|
744
|
+
await reportUpdateProgress(plan, defaultDependencies, `更新失败:${errorMessage(error)}`, {
|
|
745
|
+
status: "failed", fromVersion: plan.fromVersion, toVersion: plan.toVersion, error: errorMessage(error), completedAt: new Date().toISOString(),
|
|
746
|
+
}).catch(() => undefined);
|
|
747
|
+
process.stderr.write(errorMessage(error) + "\n");
|
|
551
748
|
process.exitCode = 1;
|
|
552
749
|
});
|
|
553
750
|
}
|