@keyou007/agent-bot 0.1.27-alpha.2 → 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 +22 -0
- package/README.md +78 -13
- package/README.zh.md +78 -13
- 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 +219 -129
- 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 +207 -132
- 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
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { createHash, type Hash } from "node:crypto";
|
|
4
|
+
import { setImmediate as yieldEventLoop } from "node:timers/promises";
|
|
4
5
|
import type { AgentEvent, ToolState } from "../runtime/types.js";
|
|
5
6
|
import { approvalActivityId, continueTurnView, reduceTurnEvent } from "../presentation/TurnStateReducer.js";
|
|
6
7
|
import type { TurnViewState } from "../presentation/turnViewTypes.js";
|
|
7
8
|
import { normalizeTurnActivity } from "../presentation/turnActivity.js";
|
|
9
|
+
import { canApplyTurnEvent } from "../presentation/turnStatus.js";
|
|
10
|
+
import { toolTimestamp } from "../utils/toolTimestamp.js";
|
|
11
|
+
import { TurnToolTextReader } from "./TurnToolText.js";
|
|
8
12
|
|
|
9
13
|
type TextChange = { key: string; field: string; append: boolean; text: string };
|
|
10
14
|
export type PreviewRecord =
|
|
@@ -15,12 +19,14 @@ export type PreviewRecord =
|
|
|
15
19
|
| { kind: "event"; event: AgentEvent; texts: TextChange[] };
|
|
16
20
|
type Stream = { length: number; hash: Hash };
|
|
17
21
|
type Writer = { seeded?: boolean; pending: string[]; bytes: number; dirtyDisk?: boolean; streams: Map<string, Stream>; timings: Map<string, number>; timer?: NodeJS.Timeout; error?: unknown };
|
|
22
|
+
type Reader = { projection: TurnPreviewProjection; offset: number; accessed: number };
|
|
18
23
|
|
|
19
24
|
/** A presentation journal, not an agent/tool replay mechanism. All paths are local to this store. */
|
|
20
25
|
export class TurnPreviewJournal {
|
|
21
26
|
private readonly writers = new Map<string, Writer>();
|
|
22
27
|
private detailExpiry?: NodeJS.Timeout;
|
|
23
|
-
private readonly detailReaders = new Map<string,
|
|
28
|
+
private readonly detailReaders = new Map<string, Reader>();
|
|
29
|
+
private readonly toolText = new TurnToolTextReader();
|
|
24
30
|
constructor(readonly directory: string, private readonly onError: (error: unknown) => void = () => {}) {}
|
|
25
31
|
|
|
26
32
|
file(turnId: string): string {
|
|
@@ -73,10 +79,10 @@ export class TurnPreviewJournal {
|
|
|
73
79
|
texts.push({ key, field, append: incremental, text: suffix });
|
|
74
80
|
};
|
|
75
81
|
if (copy.type === "tool_started" || copy.type === "tool_updated") {
|
|
76
|
-
const startedAt = copy.tool.startedAt ?? writer.timings.get(copy.tool.id) ?? Date.now();
|
|
82
|
+
const startedAt = toolTimestamp(copy.tool.startedAt) ?? writer.timings.get(copy.tool.id) ?? Date.now();
|
|
77
83
|
writer.timings.set(copy.tool.id, startedAt);
|
|
78
84
|
copy.tool = { ...copy.tool, startedAt,
|
|
79
|
-
completedAt: copy.tool.status === "running" ? copy.tool.completedAt : copy.tool.completedAt ?? Date.now() };
|
|
85
|
+
completedAt: copy.tool.status === "running" ? toolTimestamp(copy.tool.completedAt) : toolTimestamp(copy.tool.completedAt) ?? Date.now() };
|
|
80
86
|
for (const field of ["title", "command", "output", "error"] as const) {
|
|
81
87
|
const text = copy.tool[field];
|
|
82
88
|
if (text === undefined) continue;
|
|
@@ -146,18 +152,28 @@ export class TurnPreviewJournal {
|
|
|
146
152
|
for (const writer of this.writers.values()) if (writer.timer) clearTimeout(writer.timer);
|
|
147
153
|
this.writers.clear();
|
|
148
154
|
this.detailReaders.clear();
|
|
155
|
+
this.toolText.clear();
|
|
149
156
|
if (this.detailExpiry) clearTimeout(this.detailExpiry);
|
|
150
157
|
}
|
|
151
158
|
}
|
|
152
159
|
|
|
160
|
+
async toolTextPage(turnId: string, toolId: string, offset: number, limit: number) {
|
|
161
|
+
this.flush(turnId);
|
|
162
|
+
const file = fs.statSync(this.file(turnId), { throwIfNoEntry: false, bigint: true });
|
|
163
|
+
if (!file) return;
|
|
164
|
+
const fileId = `${file.dev}:${file.ino}:${file.birthtimeNs}`;
|
|
165
|
+
return this.toolText.page(JSON.stringify([turnId, toolId]), toolId,
|
|
166
|
+
(start, through) => this.read(turnId, start, 256 * 1024, through), Number(file.size), fileId, offset, limit);
|
|
167
|
+
}
|
|
168
|
+
|
|
153
169
|
/** Bounded byte cursor; a partial final record is ignored until its newline is present. */
|
|
154
|
-
read(turnId: string, offset = 0, maxBytes = 256 * 1024, through = Infinity): { records: PreviewRecord[]; offset: number; end: boolean } {
|
|
170
|
+
read(turnId: string, offset = 0, maxBytes = 256 * 1024, through = Infinity): { records: PreviewRecord[]; starts: number[]; offset: number; end: boolean } {
|
|
155
171
|
const file = this.file(turnId);
|
|
156
|
-
if (!fs.existsSync(file)) return { records: [], offset, end: true };
|
|
172
|
+
if (!fs.existsSync(file)) return { records: [], starts: [], offset, end: true };
|
|
157
173
|
const fd = fs.openSync(file, "r");
|
|
158
174
|
try {
|
|
159
175
|
const size = Math.min(fs.fstatSync(fd).size, through);
|
|
160
|
-
const records: PreviewRecord[] = [];
|
|
176
|
+
const records: PreviewRecord[] = [], starts: number[] = [];
|
|
161
177
|
const start = offset;
|
|
162
178
|
let position = offset;
|
|
163
179
|
let parts: Buffer[] = [];
|
|
@@ -172,44 +188,80 @@ export class TurnPreviewJournal {
|
|
|
172
188
|
parts.push(chunk.subarray(begin, newline));
|
|
173
189
|
const line = Buffer.concat(parts);
|
|
174
190
|
records.push(JSON.parse(line.toString("utf8")) as PreviewRecord);
|
|
191
|
+
starts.push(offset);
|
|
175
192
|
offset += line.length + 1;
|
|
193
|
+
if (offset - start >= maxBytes) return { records, starts, offset, end: offset >= size };
|
|
176
194
|
parts = [];
|
|
177
195
|
begin = newline + 1;
|
|
178
196
|
}
|
|
179
197
|
if (begin < count) parts.push(chunk.subarray(begin, count));
|
|
180
198
|
if (records.length && position - start >= maxBytes) break;
|
|
181
199
|
}
|
|
182
|
-
return { records, offset, end: position >= size };
|
|
200
|
+
return { records, starts, offset, end: position >= size };
|
|
183
201
|
} finally { fs.closeSync(fd); }
|
|
184
202
|
}
|
|
185
203
|
|
|
186
204
|
load(turnId: string, details: boolean | string = true): TurnViewState | undefined {
|
|
187
|
-
this.
|
|
188
|
-
const cacheKey = `${turnId}:${String(details)}`;
|
|
189
|
-
const cached = typeof details === "string" ? this.detailReaders.get(cacheKey) : undefined;
|
|
190
|
-
const projection = cached?.projection ?? new TurnPreviewProjection(details);
|
|
191
|
-
let offset = cached?.offset ?? 0;
|
|
205
|
+
const reader = this.loadReader(turnId, details);
|
|
192
206
|
for (;;) {
|
|
193
|
-
const batch = this.read(turnId, offset);
|
|
194
|
-
for (const record of batch.records) projection.apply(record, ++projection.revision);
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
207
|
+
const batch = this.read(turnId, reader.offset);
|
|
208
|
+
for (const record of batch.records) reader.projection.apply(record, ++reader.projection.revision);
|
|
209
|
+
const done = batch.end || batch.offset === reader.offset;
|
|
210
|
+
reader.offset = batch.offset;
|
|
211
|
+
if (done) return this.finishRead(turnId, details, reader);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async loadAsync(turnId: string, details: boolean | string = false): Promise<TurnViewState | undefined> {
|
|
216
|
+
const reader = this.loadReader(turnId, details);
|
|
217
|
+
let yieldedAt = performance.now();
|
|
218
|
+
for (;;) {
|
|
219
|
+
const batch = this.read(turnId, reader.offset);
|
|
220
|
+
for (const record of batch.records) reader.projection.apply(record, ++reader.projection.revision);
|
|
221
|
+
const done = batch.end || batch.offset === reader.offset;
|
|
222
|
+
reader.offset = batch.offset;
|
|
223
|
+
if (done) return this.finishRead(turnId, details, reader);
|
|
224
|
+
if (performance.now() - yieldedAt >= 8) {
|
|
225
|
+
await yieldEventLoop();
|
|
226
|
+
yieldedAt = performance.now();
|
|
208
227
|
}
|
|
209
|
-
offset = batch.offset;
|
|
210
228
|
}
|
|
211
229
|
}
|
|
212
230
|
|
|
231
|
+
cachedProjection(turnId: string, offset: number): TurnPreviewProjection | undefined {
|
|
232
|
+
const reader = this.detailReaders.get(`${turnId}:false`);
|
|
233
|
+
return reader?.offset === offset ? reader.projection.copy() : undefined;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
private loadReader(turnId: string, details: boolean | string): Reader {
|
|
237
|
+
this.flush(turnId);
|
|
238
|
+
const cacheKey = `${turnId}:${String(details)}`;
|
|
239
|
+
let cached = details !== true ? this.detailReaders.get(cacheKey) : undefined;
|
|
240
|
+
if (cached && (!fs.existsSync(this.file(turnId)) || fs.statSync(this.file(turnId)).size < cached.offset)) {
|
|
241
|
+
this.detailReaders.delete(cacheKey);
|
|
242
|
+
cached = undefined;
|
|
243
|
+
}
|
|
244
|
+
// Async readers and live connections must never mutate another request's checkpoint.
|
|
245
|
+
return cached ? { ...cached, projection: cached.projection.copy() }
|
|
246
|
+
: { projection: new TurnPreviewProjection(details), offset: 0, accessed: Date.now() };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
private finishRead(turnId: string, details: boolean | string, reader: Reader): TurnViewState | undefined {
|
|
250
|
+
if (details !== true) {
|
|
251
|
+
const now = Date.now();
|
|
252
|
+
for (const [key, value] of this.detailReaders) if (now - value.accessed > 60_000) this.detailReaders.delete(key);
|
|
253
|
+
const cacheKey = `${turnId}:${String(details)}`;
|
|
254
|
+
this.detailReaders.delete(cacheKey);
|
|
255
|
+
if (reader.projection.retainedTextBytes() < 16 * 1024 * 1024)
|
|
256
|
+
this.detailReaders.set(cacheKey, { ...reader, accessed: now });
|
|
257
|
+
if (this.detailExpiry) clearTimeout(this.detailExpiry);
|
|
258
|
+
this.detailExpiry = setTimeout(() => this.detailReaders.clear(), 60_000);
|
|
259
|
+
this.detailExpiry.unref();
|
|
260
|
+
while (this.detailReaders.size > 4) this.detailReaders.delete(this.detailReaders.keys().next().value!);
|
|
261
|
+
}
|
|
262
|
+
return reader.projection.state ? { ...reader.projection.state, previewCursor: reader.offset } : undefined;
|
|
263
|
+
}
|
|
264
|
+
|
|
213
265
|
outputAppend(turnId: string, toolId: string, after: number, through: number): string | undefined {
|
|
214
266
|
if (!Number.isSafeInteger(after) || after <= 0 || after > through) return undefined;
|
|
215
267
|
let offset = after;
|
|
@@ -255,8 +307,10 @@ export class TurnPreviewJournal {
|
|
|
255
307
|
if (record.kind === "event") {
|
|
256
308
|
for (const change of record.texts) this.track(writer, change);
|
|
257
309
|
const event = record.event;
|
|
258
|
-
if (
|
|
259
|
-
|
|
310
|
+
if (event.type === "tool_started" || event.type === "tool_updated") {
|
|
311
|
+
const startedAt = toolTimestamp(event.tool.startedAt);
|
|
312
|
+
if (startedAt !== undefined) writer.timings.set(event.tool.id, startedAt);
|
|
313
|
+
}
|
|
260
314
|
}
|
|
261
315
|
if (record.kind === "seed") {
|
|
262
316
|
writer.seeded = true;
|
|
@@ -296,9 +350,18 @@ export class TurnPreviewProjection {
|
|
|
296
350
|
readonly changed = new Set<string>();
|
|
297
351
|
readonly removed = new Set<string>();
|
|
298
352
|
private readonly text = new Map<string, string>();
|
|
353
|
+
private readonly toolPositions = new Map<string, number>();
|
|
299
354
|
constructor(private readonly details: boolean | string = false) {}
|
|
355
|
+
copy(): TurnPreviewProjection {
|
|
356
|
+
const copy = new TurnPreviewProjection(this.details);
|
|
357
|
+
copy.state = this.state && structuredClone(this.state);
|
|
358
|
+
copy.revision = this.revision;
|
|
359
|
+
for (const [key, value] of this.text) copy.text.set(key, value);
|
|
360
|
+
return copy;
|
|
361
|
+
}
|
|
300
362
|
retainedTextBytes(): number {
|
|
301
|
-
let bytes = 0
|
|
363
|
+
let bytes = ((this.state?.prompt?.length ?? 0) + (this.state?.finalResponse?.length ?? 0)
|
|
364
|
+
+ (this.state?.assistantText.length ?? 0)) * 2;
|
|
302
365
|
for (const value of this.text.values()) bytes += value.length * 2;
|
|
303
366
|
return bytes;
|
|
304
367
|
}
|
|
@@ -308,11 +371,20 @@ export class TurnPreviewProjection {
|
|
|
308
371
|
|
|
309
372
|
apply(record: PreviewRecord, revision: number): void {
|
|
310
373
|
if (record.kind === "seed") {
|
|
311
|
-
this.
|
|
374
|
+
this.toolPositions.clear();
|
|
375
|
+
this.state = { ...record.state, fullToolOutputs: { ...record.state.fullToolOutputs },
|
|
376
|
+
activities: record.state.activities.map(normalizeTurnActivity), activitiesTruncated: false };
|
|
312
377
|
for (const change of seedTexts(record.state)) this.text.set(change.key, this.wantsFull(change.key) ? change.text : change.text.slice(0, 6000));
|
|
313
378
|
if (this.details !== true) {
|
|
379
|
+
const summarizeTool = (tool: ToolState): ToolState => this.wantsFull(`tool:${tool.id}:`) ? tool : { ...tool,
|
|
380
|
+
title: tool.title.slice(0, 6000), command: tool.command?.slice(0, 6000),
|
|
381
|
+
output: tool.output?.slice(0, 6000), error: tool.error?.slice(0, 6000) };
|
|
314
382
|
this.state = { ...this.state, fullToolOutputs: {}, fullToolErrors: {}, activities: this.state.activities.map((a) => a.kind === "tool"
|
|
315
|
-
? { ...a, tool:
|
|
383
|
+
? { ...a, tool: summarizeTool(a.tool) } : a),
|
|
384
|
+
activeTool: this.state.activeTool && summarizeTool(this.state.activeTool),
|
|
385
|
+
completedTools: this.state.completedTools.map(summarizeTool), failedTools: this.state.failedTools.map(summarizeTool),
|
|
386
|
+
reasoningItems: this.state.reasoningItems?.map((item) => this.wantsFull(`reasoning:${item.itemId}:`) ? item : { ...item,
|
|
387
|
+
summary: item.summary.map((text) => text.slice(0, 6000)), content: item.content.map((text) => text.slice(0, 6000)) }) };
|
|
316
388
|
}
|
|
317
389
|
if (typeof this.details === "string" && this.details.startsWith("tool:")) {
|
|
318
390
|
const id = this.details.slice(5);
|
|
@@ -343,6 +415,7 @@ export class TurnPreviewProjection {
|
|
|
343
415
|
this.changed.add(record.id);
|
|
344
416
|
return;
|
|
345
417
|
}
|
|
418
|
+
if (record.event.type === "tool_output_delta" && this.applyToolOutput(record, revision)) return;
|
|
346
419
|
let event = { ...record.event } as AgentEvent;
|
|
347
420
|
if (event.type === "tool_started" || event.type === "tool_updated") event.tool = { ...event.tool };
|
|
348
421
|
if (event.type === "reasoning_completed") event = { ...event, summary: [...event.summary], content: [...event.content] };
|
|
@@ -379,7 +452,7 @@ export class TurnPreviewProjection {
|
|
|
379
452
|
else if (event.type === "agent_text_delta" && event.replacesActivityId) this.removed.add(event.replacesActivityId);
|
|
380
453
|
if (event.type === "reasoning_delta" || event.type === "reasoning_completed") this.changed.add(`reasoning:${event.itemId}`);
|
|
381
454
|
const old = this.state;
|
|
382
|
-
this.state = reduceTurnEvent(old, event, true);
|
|
455
|
+
this.state = reduceTurnEvent(old, event, true, true);
|
|
383
456
|
if (["completed", "failed", "cancelled"].includes(old.status) && !event.type.startsWith("turn_")) this.state.status = old.status;
|
|
384
457
|
const reasoningId = event.type === "reasoning_delta" || event.type === "reasoning_completed" ? event.itemId
|
|
385
458
|
: event.type === "progress" ? event.reasoning?.itemId : undefined;
|
|
@@ -394,6 +467,37 @@ export class TurnPreviewProjection {
|
|
|
394
467
|
summary: r.summary.map((t) => this.wantsFull(`reasoning:${r.itemId}:`) ? t : t.slice(0, 6000)), content: r.content.map((t) => this.wantsFull(`reasoning:${r.itemId}:`) ? t : t.slice(0, 6000)) }));
|
|
395
468
|
this.state.activitiesTruncated = false;
|
|
396
469
|
}
|
|
470
|
+
|
|
471
|
+
private applyToolOutput(record: Extract<PreviewRecord, { kind: "event" }>, revision: number): boolean {
|
|
472
|
+
const event = record.event;
|
|
473
|
+
const state = this.state!;
|
|
474
|
+
if (event.type !== "tool_output_delta" || !canApplyTurnEvent(state, event)
|
|
475
|
+
|| state.status !== "tool_running" || state.activeTool?.id !== event.toolId) return false;
|
|
476
|
+
let index = this.toolPositions.get(event.toolId);
|
|
477
|
+
if (index === undefined || state.activities[index]?.id !== event.toolId) {
|
|
478
|
+
index = state.activities.findIndex((a) => a.kind === "tool" && a.id === event.toolId);
|
|
479
|
+
this.toolPositions.set(event.toolId, index);
|
|
480
|
+
}
|
|
481
|
+
const activity = state.activities[index];
|
|
482
|
+
if (activity?.kind !== "tool" || activity.tool.status !== "running") return false;
|
|
483
|
+
const change = record.texts[0];
|
|
484
|
+
if (record.texts.length !== 1 || change?.key !== `tool:${event.toolId}:output`) return false;
|
|
485
|
+
const previous = change.append ? this.text.get(change.key) ?? "" : "";
|
|
486
|
+
const full = this.wantsFull(change.key);
|
|
487
|
+
const output = full ? previous + change.text
|
|
488
|
+
: previous.length >= 6000 ? previous : (previous + change.text).slice(0, 6000);
|
|
489
|
+
this.text.set(change.key, output);
|
|
490
|
+
const tool = { ...activity.tool, output, previewRevision: revision };
|
|
491
|
+
state.activities[index] = { ...activity, tool };
|
|
492
|
+
state.fullToolOutputs ??= {};
|
|
493
|
+
state.fullToolOutputs[event.toolId] = output;
|
|
494
|
+
const summary = previous.length > 6000 ? state.activeTool.output
|
|
495
|
+
: output.length <= 6000 ? output : output.slice(0, 5999) + "…";
|
|
496
|
+
state.activeTool = { ...state.activeTool, output: summary,
|
|
497
|
+
previewRevision: revision };
|
|
498
|
+
this.changed.add(event.toolId);
|
|
499
|
+
return true;
|
|
500
|
+
}
|
|
397
501
|
}
|
|
398
502
|
|
|
399
503
|
function seedTexts(state: TurnViewState): TextChange[] {
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { setImmediate as yieldEventLoop } from "node:timers/promises";
|
|
3
|
+
import type { ToolState } from "../runtime/types.js";
|
|
4
|
+
import type { PreviewRecord } from "./TurnPreviewJournal.js";
|
|
5
|
+
|
|
6
|
+
export const toolTextFields = ["command", "output", "error"] as const;
|
|
7
|
+
type Field = typeof toolTextFields[number];
|
|
8
|
+
type Texts = Record<Field, string>;
|
|
9
|
+
type Checkpoint = { offset: number; chars: number };
|
|
10
|
+
type FieldIndex = { length: number; checkpoints: Checkpoint[]; hash: ReturnType<typeof createHash> };
|
|
11
|
+
type ToolIndex = Record<Field, FieldIndex>;
|
|
12
|
+
type Batch = { records: PreviewRecord[]; starts: number[]; offset: number; end: boolean };
|
|
13
|
+
type ReadBatch = (offset: number, through: number) => Batch;
|
|
14
|
+
const stride = 256 * 1024;
|
|
15
|
+
|
|
16
|
+
function changes(record: PreviewRecord, tool: string): Array<[Field, string, boolean]> {
|
|
17
|
+
if (record.kind === "seed") {
|
|
18
|
+
const activity = record.state.activities.find((item) => item.kind === "tool" && item.id === tool);
|
|
19
|
+
if (activity?.kind !== "tool") return [];
|
|
20
|
+
const { command, output, error } = activity.tool;
|
|
21
|
+
return [["command", command ?? "", false],
|
|
22
|
+
["output", record.state.fullToolOutputs?.[tool] ?? output ?? "", false],
|
|
23
|
+
["error", record.state.fullToolErrors?.[tool] ?? error ?? "", false]];
|
|
24
|
+
}
|
|
25
|
+
if (record.kind !== "event") return [];
|
|
26
|
+
const event = record.event;
|
|
27
|
+
if ((event.type === "tool_started" || event.type === "tool_updated") && event.tool.id === tool) {
|
|
28
|
+
return toolTextFields.flatMap((field) => {
|
|
29
|
+
const change = record.texts.find((item) => item.field === field && item.key === `tool:${tool}:${field}`);
|
|
30
|
+
const text = change?.text ?? event.tool[field];
|
|
31
|
+
return typeof text === "string" ? [[field, text, change?.append ?? false]] : [];
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
if (event.type === "tool_output_delta" && event.toolId === tool) {
|
|
35
|
+
const change = record.texts.find((item) => item.key === `tool:${tool}:output`);
|
|
36
|
+
return [["output", change?.text ?? event.delta, change?.append ?? true]];
|
|
37
|
+
}
|
|
38
|
+
return [];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function scan(read: ReadBatch, offset: number, through: number, visit: (record: PreviewRecord, start: number) => boolean | void) {
|
|
42
|
+
let yieldedAt = performance.now();
|
|
43
|
+
while (offset < through) {
|
|
44
|
+
const batch = read(offset, through);
|
|
45
|
+
for (const [index, record] of batch.records.entries()) {
|
|
46
|
+
if (visit(record, batch.starts[index]!) === false) return batch.offset;
|
|
47
|
+
}
|
|
48
|
+
if (batch.end || batch.offset === offset) return batch.offset;
|
|
49
|
+
offset = batch.offset;
|
|
50
|
+
if (performance.now() - yieldedAt >= 8) { await yieldEventLoop(); yieldedAt = performance.now(); }
|
|
51
|
+
}
|
|
52
|
+
return offset;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function newField(): FieldIndex { return { length: 0, checkpoints: [], hash: createHash("sha256") }; }
|
|
56
|
+
function copyField(field: FieldIndex): FieldIndex {
|
|
57
|
+
return { ...field, hash: field.hash.copy(), checkpoints: [...field.checkpoints] };
|
|
58
|
+
}
|
|
59
|
+
type Entry = { end: number; through: number; index: ToolIndex; found: boolean; fileId: string; toolKind?: string; files?: ToolState["files"] };
|
|
60
|
+
type Page = Texts & { remaining: Field[]; next?: number; revision: string; toolKind?: string; outputIsError?: boolean; files?: ToolState["files"] };
|
|
61
|
+
|
|
62
|
+
/** Indexes recent tool reads by range, without retaining log text or rebuilding the full Turn. */
|
|
63
|
+
export class TurnToolTextReader {
|
|
64
|
+
private readonly cache = new Map<string, Entry>();
|
|
65
|
+
private readonly pending = new Map<string, Promise<Entry>>();
|
|
66
|
+
|
|
67
|
+
async page(key: string, tool: string, read: ReadBatch, through: number, fileId: string, offset: number, limit: number): Promise<Page | { busy: true } | undefined> {
|
|
68
|
+
let entry = this.cache.get(key);
|
|
69
|
+
if (entry?.fileId !== fileId || entry.through > through) entry = undefined;
|
|
70
|
+
if (!entry || entry.through !== through) {
|
|
71
|
+
let loading = this.pending.get(key);
|
|
72
|
+
if (!loading) {
|
|
73
|
+
if (this.pending.size >= 4) return { busy: true } as const;
|
|
74
|
+
loading = this.index(tool, read, through, fileId, entry);
|
|
75
|
+
this.pending.set(key, loading);
|
|
76
|
+
const pending = loading;
|
|
77
|
+
void pending.then((result) => {
|
|
78
|
+
if (this.pending.get(key) !== pending) return;
|
|
79
|
+
this.cache.delete(key); this.cache.set(key, result);
|
|
80
|
+
while (this.cache.size > 8) this.cache.delete(this.cache.keys().next().value!);
|
|
81
|
+
}, () => {}).finally(() => { if (this.pending.get(key) === pending) this.pending.delete(key); });
|
|
82
|
+
}
|
|
83
|
+
entry = await loading;
|
|
84
|
+
if (entry.through < through || entry.fileId !== fileId) {
|
|
85
|
+
if (this.pending.get(key) === loading) this.pending.delete(key);
|
|
86
|
+
return this.page(key, tool, read, through, fileId, offset, limit);
|
|
87
|
+
}
|
|
88
|
+
} else { this.cache.delete(key); this.cache.set(key, entry); }
|
|
89
|
+
if (!entry.found) return;
|
|
90
|
+
const { index, end } = entry;
|
|
91
|
+
const sameError = index.output.length === index.error.length && index.output.hash.copy().digest("hex") === index.error.hash.copy().digest("hex");
|
|
92
|
+
const page: Texts = { command: "", output: "", error: "" };
|
|
93
|
+
const remaining: Field[] = [];
|
|
94
|
+
for (const field of toolTextFields) {
|
|
95
|
+
if (field === "error" && sameError) continue;
|
|
96
|
+
const source = index[field];
|
|
97
|
+
if (offset >= source.length) continue;
|
|
98
|
+
const until = Math.min(offset + limit, source.length);
|
|
99
|
+
let left = 0, right = source.checkpoints.length;
|
|
100
|
+
while (left + 1 < right) {
|
|
101
|
+
const middle = (left + right) >>> 1;
|
|
102
|
+
if (source.checkpoints[middle]!.chars <= offset) left = middle; else right = middle;
|
|
103
|
+
}
|
|
104
|
+
const start = source.checkpoints[left]!;
|
|
105
|
+
const pieces: string[] = [];
|
|
106
|
+
let chars = start.chars;
|
|
107
|
+
await scan(read, start.offset, end, (record) => {
|
|
108
|
+
for (const [name, text] of changes(record, tool)) {
|
|
109
|
+
if (name !== field) continue;
|
|
110
|
+
const next = chars + text.length;
|
|
111
|
+
if (next > offset && chars < until) pieces.push(text.slice(Math.max(0, offset - chars), until - chars));
|
|
112
|
+
chars = next;
|
|
113
|
+
}
|
|
114
|
+
return chars < until;
|
|
115
|
+
});
|
|
116
|
+
if (chars < until) throw new Error("Tool journal changed while reading a page.");
|
|
117
|
+
page[field] = pieces.join("");
|
|
118
|
+
if (until < source.length) remaining.push(field);
|
|
119
|
+
}
|
|
120
|
+
const revision = createHash("sha256").update(JSON.stringify([entry.fileId, sameError,
|
|
121
|
+
...toolTextFields.map((field) => index[field].checkpoints[0]?.offset ?? -1),
|
|
122
|
+
])).digest("base64url");
|
|
123
|
+
return { ...page, remaining, revision, next: remaining.length ? offset + limit : undefined,
|
|
124
|
+
toolKind: entry.toolKind, files: offset === 0 ? entry.files : undefined, outputIsError: sameError && index.output.length > 0 || undefined };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
clear() { this.cache.clear(); this.pending.clear(); }
|
|
128
|
+
|
|
129
|
+
private async index(tool: string, read: ReadBatch, through: number, fileId: string, previous?: Entry): Promise<Entry> {
|
|
130
|
+
const index = previous ? { command: copyField(previous.index.command), output: copyField(previous.index.output), error: copyField(previous.index.error) }
|
|
131
|
+
: { command: newField(), output: newField(), error: newField() };
|
|
132
|
+
let found = previous?.found ?? false, toolKind = previous?.toolKind, files = previous?.files;
|
|
133
|
+
const end = await scan(read, previous?.end ?? 0, through, (record, offset) => {
|
|
134
|
+
const event = record.kind === "event" ? record.event : undefined;
|
|
135
|
+
if ((event?.type === "tool_started" || event?.type === "tool_updated") && event.tool.id === tool) {
|
|
136
|
+
found = true;
|
|
137
|
+
toolKind = event.tool.kind ?? toolKind;
|
|
138
|
+
files = event.tool.files ?? files;
|
|
139
|
+
} else if (record.kind === "seed") {
|
|
140
|
+
const activity = record.state.activities.find((item) => item.kind === "tool" && item.id === tool);
|
|
141
|
+
if (activity?.kind === "tool") { toolKind = activity.tool.kind ?? toolKind; files = activity.tool.files ?? files; }
|
|
142
|
+
}
|
|
143
|
+
for (const [field, text, append] of changes(record, tool)) {
|
|
144
|
+
found = true;
|
|
145
|
+
if (!append) index[field] = newField();
|
|
146
|
+
const current = index[field];
|
|
147
|
+
const last = current.checkpoints.at(-1);
|
|
148
|
+
if (!last || current.length - last.chars >= stride) current.checkpoints.push({ offset, chars: current.length });
|
|
149
|
+
current.length += text.length;
|
|
150
|
+
// Hash UTF-16 code units so a surrogate pair split across two deltas compares correctly.
|
|
151
|
+
current.hash.update(text, "utf16le");
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
return { end, through, index, found, fileId, toolKind, files };
|
|
155
|
+
}
|
|
156
|
+
}
|
package/src/state/migrations.ts
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
export const migrations = [
|
|
2
|
+
`CREATE TABLE IF NOT EXISTS task_metadata (
|
|
3
|
+
local_session_id TEXT NOT NULL, kind TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL,
|
|
4
|
+
PRIMARY KEY (local_session_id, kind, key)
|
|
5
|
+
);`,
|
|
2
6
|
`CREATE TABLE IF NOT EXISTS workspace_requests (
|
|
3
7
|
id TEXT PRIMARY KEY, local_session_id TEXT NOT NULL, fingerprint TEXT NOT NULL,
|
|
4
8
|
status TEXT NOT NULL, posted INTEGER NOT NULL DEFAULT 0, message TEXT, created_at INTEGER NOT NULL
|
|
@@ -143,12 +143,15 @@ export class SafeRestartNotifier {
|
|
|
143
143
|
? []
|
|
144
144
|
: this.store.listAllSessions()
|
|
145
145
|
.filter((session) => this.store.sessionBlocksSafeRestart(session.localSessionId))
|
|
146
|
-
.map((session) =>
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
146
|
+
.map((session) => {
|
|
147
|
+
const isRunning = session.status === "running";
|
|
148
|
+
const attempt = isRunning ? this.store.findIncompleteTurnAttemptForSession(session.localSessionId) : undefined;
|
|
149
|
+
const turnId = attempt ? attempt.turnId ?? attempt.pendingTurnId : session.lastTurnId;
|
|
150
|
+
const summary = isRunning && turnId ? this.store.getTurnPromptSummary(turnId) : undefined;
|
|
151
|
+
const prompt = summary && !["completed", "cancelled", "failed"].includes(summary.status ?? "")
|
|
152
|
+
? summary.prompt ?? attempt?.promptText : attempt?.promptText;
|
|
153
|
+
return { localSessionId: session.localSessionId, isRunning, title: session.title, prompt };
|
|
154
|
+
});
|
|
152
155
|
await Promise.all(targets.map(async ({ contextKey, replyMessageId, reason }) => {
|
|
153
156
|
const card = this.renderer.renderSafeRestartStatus({
|
|
154
157
|
scheduleId: status.scheduleId,
|
|
@@ -253,6 +253,11 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
|
|
|
253
253
|
window.addEventListener('offline', () => { offline = true; suspend(); });
|
|
254
254
|
window.addEventListener('online', () => { offline = false; resume(); });
|
|
255
255
|
window.addEventListener('focus', resume);
|
|
256
|
+
if (workspace && window.parent !== window) window.addEventListener('keydown', event => {
|
|
257
|
+
if (!(event.ctrlKey || event.metaKey) || event.altKey || event.isComposing || event.key?.toLowerCase() !== 'p') return;
|
|
258
|
+
event.preventDefault(); event.stopPropagation();
|
|
259
|
+
if (!event.repeat) window.parent.postMessage({type:'agentbot-workspace-open-file-search',commands:event.shiftKey === true},location.origin);
|
|
260
|
+
}, true);
|
|
256
261
|
window.addEventListener('message', event => {
|
|
257
262
|
if (window.parent === window || event.source !== window.parent || event.origin !== location.origin || event.data?.type !== 'agentbot-workspace-visibility' || typeof event.data.visible !== 'boolean') return;
|
|
258
263
|
if (workspace && event.data.start === true) startRequested = true;
|
|
@@ -1,18 +1,46 @@
|
|
|
1
1
|
import { execFile, type ExecFileOptionsWithStringEncoding } from "node:child_process";
|
|
2
2
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
3
|
-
import { promisify } from "node:util";
|
|
4
3
|
import { z } from "zod";
|
|
5
4
|
import { loadConfig } from "../config/loadConfig.js";
|
|
6
5
|
import { controlEndpoint } from "../cli/controlProtocol.js";
|
|
7
|
-
import {
|
|
6
|
+
import { sanitizeUpdateDiagnostic } from "../cli/SelfUpdateRunner.js";
|
|
7
|
+
import { finalizeSelfUpdatePlan, prepareSelfUpdate, releaseSelfUpdatePlan, requireNpmSelfUpdateInstallation, SelfUpdatePreparationError } from "../cli/SelfUpdater.js";
|
|
8
8
|
import { publishedVersionSchema, stableVersionSchema } from "./PublishedRelease.js";
|
|
9
9
|
|
|
10
10
|
const resultSchema = z.discriminatedUnion("status", [
|
|
11
11
|
z.object({ status: z.literal("current") }),
|
|
12
12
|
z.object({ status: z.literal("prepared"), planPath: z.string().min(1), targetVersion: publishedVersionSchema }),
|
|
13
13
|
]);
|
|
14
|
-
|
|
15
|
-
|
|
14
|
+
type RunPreparation = (file: string, args: string[], options: ExecFileOptionsWithStringEncoding, onProgress?: (message: string) => void) => Promise<{ stdout: string }>;
|
|
15
|
+
const progressPrefix = "AGENT_BOT_UPDATE_PROGRESS ";
|
|
16
|
+
function progressMessage(line: string): string | undefined {
|
|
17
|
+
if (!line.startsWith(progressPrefix)) return undefined;
|
|
18
|
+
try {
|
|
19
|
+
const message: unknown = JSON.parse(line.slice(progressPrefix.length));
|
|
20
|
+
return typeof message === "string" ? message : undefined;
|
|
21
|
+
} catch { return undefined; }
|
|
22
|
+
}
|
|
23
|
+
const runFile: RunPreparation = (file, args, options, onProgress) => new Promise((resolve, reject) => {
|
|
24
|
+
const child = execFile(file, args, options, (error, stdout, stderr) => {
|
|
25
|
+
if (error) {
|
|
26
|
+
const diagnostic = stderr.split(/\r?\n/).filter((line) => progressMessage(line) === undefined).join("\n").trim();
|
|
27
|
+
let preparationFailed = false;
|
|
28
|
+
try { preparationFailed = z.object({ status: z.literal("preparation_failed") }).safeParse(JSON.parse(stdout)).success; } catch {}
|
|
29
|
+
const Failure = preparationFailed ? SelfUpdatePreparationError : Error;
|
|
30
|
+
reject(new Failure(sanitizeUpdateDiagnostic(diagnostic || error.message)));
|
|
31
|
+
} else resolve({ stdout });
|
|
32
|
+
});
|
|
33
|
+
let pending = "";
|
|
34
|
+
child.stderr?.on("data", (chunk: string) => {
|
|
35
|
+
pending += chunk;
|
|
36
|
+
const lines = pending.split(/\r?\n/);
|
|
37
|
+
pending = lines.pop()!;
|
|
38
|
+
for (const line of lines) {
|
|
39
|
+
const message = progressMessage(line);
|
|
40
|
+
if (message !== undefined) onProgress?.(message);
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
});
|
|
16
44
|
interface UpdateProfile { home: string; configPath: string }
|
|
17
45
|
|
|
18
46
|
export async function checkAutomaticUpdateSupport(profile: UpdateProfile, run: RunPreparation = runFile): Promise<void> {
|
|
@@ -23,9 +51,10 @@ export async function prepareAutomaticUpdate(
|
|
|
23
51
|
version: string,
|
|
24
52
|
profile: UpdateProfile,
|
|
25
53
|
run: RunPreparation = runFile,
|
|
54
|
+
onProgress?: (message: string) => Promise<void>,
|
|
26
55
|
): Promise<z.infer<typeof resultSchema>> {
|
|
27
56
|
stableVersionSchema.parse(version);
|
|
28
|
-
const result = resultSchema.parse(await runPreparer(version, profile, run));
|
|
57
|
+
const result = resultSchema.parse(await runPreparer(version, profile, run, undefined, onProgress));
|
|
29
58
|
if (result.status === "prepared" && result.targetVersion !== version) {
|
|
30
59
|
throw new Error("The prepared update does not match the announced version.");
|
|
31
60
|
}
|
|
@@ -36,23 +65,32 @@ export async function prepareSelectedUpdate(
|
|
|
36
65
|
version: string,
|
|
37
66
|
profile: UpdateProfile,
|
|
38
67
|
run: RunPreparation = runFile,
|
|
68
|
+
onProgress?: (message: string) => Promise<void>,
|
|
39
69
|
): Promise<z.infer<typeof resultSchema>> {
|
|
40
70
|
publishedVersionSchema.parse(version);
|
|
41
|
-
const result = resultSchema.parse(await runPreparer("--manual", profile, run, version));
|
|
71
|
+
const result = resultSchema.parse(await runPreparer("--manual", profile, run, version, onProgress));
|
|
42
72
|
if (result.status === "prepared" && result.targetVersion !== version) {
|
|
43
73
|
throw new Error("The prepared update does not match the selected version.");
|
|
44
74
|
}
|
|
45
75
|
return result;
|
|
46
76
|
}
|
|
47
77
|
|
|
48
|
-
async function runPreparer(argument: string, profile: UpdateProfile, run: RunPreparation, version?: string): Promise<unknown> {
|
|
78
|
+
async function runPreparer(argument: string, profile: UpdateProfile, run: RunPreparation, version?: string, onProgress?: (message: string) => Promise<void>): Promise<unknown> {
|
|
49
79
|
const environment: NodeJS.ProcessEnv = { ...process.env, AGENT_BOT_HOME: profile.home, AGENT_BOT_CONFIG: profile.configPath };
|
|
50
80
|
delete environment.AGENT_BOT;
|
|
51
81
|
// npm preparation is synchronous and can take minutes; keep it off the live worker's event loop.
|
|
52
|
-
|
|
82
|
+
let progress = Promise.resolve();
|
|
83
|
+
const receive = (message: string): void => { progress = progress.then(() => onProgress?.(message)); };
|
|
84
|
+
const options: ExecFileOptionsWithStringEncoding = {
|
|
53
85
|
env: environment, windowsHide: true, encoding: "utf8", maxBuffer: 1_000_000,
|
|
54
|
-
}
|
|
55
|
-
|
|
86
|
+
};
|
|
87
|
+
try {
|
|
88
|
+
const args = [fileURLToPath(import.meta.url), argument, ...(version ? [version] : [])];
|
|
89
|
+
const { stdout } = onProgress ? await run(process.execPath, args, options, receive) : await run(process.execPath, args, options);
|
|
90
|
+
return JSON.parse(String(stdout)) as unknown;
|
|
91
|
+
} finally {
|
|
92
|
+
await progress;
|
|
93
|
+
}
|
|
56
94
|
}
|
|
57
95
|
|
|
58
96
|
async function main(): Promise<void> {
|
|
@@ -64,7 +102,9 @@ async function main(): Promise<void> {
|
|
|
64
102
|
const manual = process.argv[2] === "--manual";
|
|
65
103
|
const version = manual ? publishedVersionSchema.parse(process.argv[3]) : stableVersionSchema.parse(process.argv[2]);
|
|
66
104
|
const config = loadConfig();
|
|
67
|
-
const prepared = await prepareSelfUpdate({ version
|
|
105
|
+
const prepared = await prepareSelfUpdate({ version, onProgress: (message) => {
|
|
106
|
+
process.stderr.write(progressPrefix + JSON.stringify(message) + "\n");
|
|
107
|
+
} });
|
|
68
108
|
if (prepared.status === "prepared") {
|
|
69
109
|
try {
|
|
70
110
|
finalizeSelfUpdatePlan(prepared.planPath, {
|
|
@@ -84,6 +124,7 @@ async function main(): Promise<void> {
|
|
|
84
124
|
|
|
85
125
|
if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
|
|
86
126
|
void main().catch((error: unknown) => {
|
|
127
|
+
if (error instanceof SelfUpdatePreparationError) process.stdout.write(JSON.stringify({ status: "preparation_failed" }));
|
|
87
128
|
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
88
129
|
process.exitCode = 1;
|
|
89
130
|
});
|
|
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
|
|
|
2
2
|
import type { Logger } from "pino";
|
|
3
3
|
import { truncateText } from "../utils/markdown.js";
|
|
4
4
|
import { compareSemver } from "../cli/SelfUpdater.js";
|
|
5
|
+
import { sanitizeUpdateDiagnostic } from "../cli/SelfUpdateRunner.js";
|
|
5
6
|
import { CardRenderer, type TaskListCardAction } from "../feishu/CardRenderer.js";
|
|
6
7
|
import type { CardAction, MessageReplyTarget } from "../feishu/types.js";
|
|
7
8
|
import type { OutboundRouter } from "../presentation/OutboundRouter.js";
|
|
@@ -17,7 +18,7 @@ interface ManualUpdateOptions {
|
|
|
17
18
|
readReleases(): Promise<PublishedRelease[]>;
|
|
18
19
|
checkSupport(): Promise<void>;
|
|
19
20
|
hasPendingUpdate(): boolean;
|
|
20
|
-
applyUpdate(version: string, contextKey: string, replyTarget?: MessageReplyTarget): Promise<void>;
|
|
21
|
+
applyUpdate(version: string, contextKey: string, replyTarget?: MessageReplyTarget, progress?: { messageId: string; update(message: string): Promise<void> }): Promise<void>;
|
|
21
22
|
now?(): number;
|
|
22
23
|
}
|
|
23
24
|
|
|
@@ -95,10 +96,14 @@ export class ManualUpdateController {
|
|
|
95
96
|
try {
|
|
96
97
|
this.options.store.retainCardActionBindings(action.messageId!, []);
|
|
97
98
|
await this.options.outbound.sendText(action.contextKey, `正在下载并校验 Agent Bot ${version},请稍后;完成后将安排安全更新。`);
|
|
98
|
-
await this.
|
|
99
|
+
await this.showResult(action, version, "正在准备更新……");
|
|
100
|
+
await this.options.applyUpdate(version, action.contextKey, replyTarget, {
|
|
101
|
+
messageId: action.messageId!, update: (message) => this.showResult(action, version, message),
|
|
102
|
+
});
|
|
99
103
|
await this.showResult(action, version, "更新已就绪,等待任务与结果投递完成后自动安装并重启。");
|
|
100
104
|
} catch (error) {
|
|
101
|
-
|
|
105
|
+
const reason = truncateText(sanitizeUpdateDiagnostic(error instanceof Error ? error.message : String(error)), 3000);
|
|
106
|
+
await this.showResult(action, version, "更新未完成,当前服务继续运行。请重新发送 /update 后重试。\n失败原因:" + reason);
|
|
102
107
|
throw error;
|
|
103
108
|
} finally {
|
|
104
109
|
this.selecting = false;
|