@keyou007/agent-bot 0.1.27-alpha.3 → 0.1.27-alpha.5
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 +32 -0
- package/README.md +102 -18
- package/README.zh.md +102 -18
- 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 +2676 -243
- package/assets/workspace.css +553 -44
- package/assets/workspace.js +3429 -327
- 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 +51 -22
- 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 +106 -14
- 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 +141 -122
- 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 +53 -276
- 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 +43 -0
- package/dist/local-files/WorkspaceImages.js.map +1 -0
- package/dist/local-files/WorkspacePage.js +24 -6
- package/dist/local-files/WorkspacePage.js.map +1 -1
- package/dist/local-files/WorkspaceSessions.js +1153 -104
- package/dist/local-files/WorkspaceSessions.js.map +1 -1
- package/dist/local-files/WorkspaceTimeline.js +129 -0
- package/dist/local-files/WorkspaceTimeline.js.map +1 -0
- package/dist/presentation/OutboundRouter.js +15 -6
- package/dist/presentation/OutboundRouter.js.map +1 -1
- package/dist/presentation/TurnStateReducer.js +31 -22
- package/dist/presentation/TurnStateReducer.js.map +1 -1
- package/dist/proxy/ProxySessionController.js +335 -113
- 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 +53 -12
- package/dist/scheduling/ScheduledTaskStore.js.map +1 -1
- package/dist/scheduling/types.js +19 -4
- package/dist/scheduling/types.js.map +1 -1
- package/dist/state/StateStore.js +213 -23
- package/dist/state/StateStore.js.map +1 -1
- package/dist/state/TurnPreviewJournal.js +157 -39
- 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 +22 -0
- package/dist/utils/promptAttachments.js.map +1 -0
- package/dist/utils/promptQuotes.js +47 -0
- package/dist/utils/promptQuotes.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 +49 -16
- 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 +107 -15
- package/src/local-files/LiveMarkup.ts +103 -0
- package/src/local-files/LocalFileViewerServer.ts +128 -125
- 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 +58 -261
- package/src/local-files/WorkspaceFileEvents.ts +186 -0
- package/src/local-files/WorkspaceFiles.ts +72 -5
- package/src/local-files/WorkspaceImages.ts +35 -0
- package/src/local-files/WorkspacePage.ts +24 -6
- package/src/local-files/WorkspaceSessions.ts +1057 -111
- package/src/local-files/WorkspaceTimeline.ts +135 -0
- package/src/presentation/OutboundRouter.ts +18 -4
- package/src/presentation/TurnStateReducer.ts +30 -19
- package/src/presentation/turnViewTypes.ts +3 -1
- package/src/proxy/ProxySessionController.ts +336 -96
- 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 +56 -9
- package/src/scheduling/types.ts +27 -4
- package/src/state/StateStore.ts +227 -24
- package/src/state/TurnPreviewJournal.ts +155 -38
- 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 +27 -0
- package/src/utils/promptQuotes.ts +48 -0
- package/src/utils/toolTimestamp.ts +5 -0
|
@@ -1,26 +1,32 @@
|
|
|
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 =
|
|
11
15
|
| { kind: "seed"; state: TurnViewState }
|
|
12
16
|
| { kind: "state"; patch: Partial<TurnViewState> }
|
|
13
|
-
| { kind: "user"; id: string; text: string; images?: string[] }
|
|
17
|
+
| { kind: "user"; id: string; text: string; images?: string[]; startedAt?: number }
|
|
14
18
|
| { kind: "handoff"; turnId: string; startedAt: number }
|
|
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 {
|
|
@@ -48,8 +54,8 @@ export class TurnPreviewJournal {
|
|
|
48
54
|
this.append(state.previewTurnId ?? state.turnId, { kind: "state", patch });
|
|
49
55
|
}
|
|
50
56
|
|
|
51
|
-
user(turnId: string, id: string, text: string, images?: string[]): void {
|
|
52
|
-
this.append(turnId, { kind: "user", id, text, images });
|
|
57
|
+
user(turnId: string, id: string, text: string, images?: string[], startedAt?: number): void {
|
|
58
|
+
this.append(turnId, { kind: "user", id, text, images, startedAt });
|
|
53
59
|
}
|
|
54
60
|
|
|
55
61
|
handoff(journalId: string, turnId: string, startedAt: number): void {
|
|
@@ -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,42 +188,88 @@ 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
|
-
|
|
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, throughTurnId?: string): Promise<TurnViewState | undefined> {
|
|
216
|
+
const reader = this.loadReader(turnId, details, throughTurnId);
|
|
217
|
+
let yieldedAt = performance.now();
|
|
218
|
+
for (;;) {
|
|
219
|
+
const batch = this.read(turnId, reader.offset);
|
|
220
|
+
for (const [index, record] of batch.records.entries()) {
|
|
221
|
+
if (throughTurnId && record.kind === "handoff" && reader.projection.state?.turnId === throughTurnId) {
|
|
222
|
+
reader.offset = batch.starts[index]!;
|
|
223
|
+
return this.finishRead(turnId, details, reader, throughTurnId);
|
|
206
224
|
}
|
|
207
|
-
|
|
225
|
+
reader.projection.apply(record, ++reader.projection.revision);
|
|
208
226
|
}
|
|
209
|
-
|
|
227
|
+
const done = batch.end || batch.offset === reader.offset;
|
|
228
|
+
reader.offset = batch.offset;
|
|
229
|
+
if (done) return this.finishRead(turnId, details, reader, throughTurnId);
|
|
230
|
+
if (performance.now() - yieldedAt >= 8) {
|
|
231
|
+
await yieldEventLoop();
|
|
232
|
+
yieldedAt = performance.now();
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
cachedProjection(turnId: string, offset: number): TurnPreviewProjection | undefined {
|
|
238
|
+
const reader = this.detailReaders.get(`${turnId}:false`);
|
|
239
|
+
return reader?.offset === offset ? reader.projection.copy() : undefined;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
private readerKey(turnId: string, details: boolean | string, throughTurnId?: string): string {
|
|
243
|
+
return throughTurnId ? JSON.stringify([turnId, details, throughTurnId]) : `${turnId}:${String(details)}`;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
private loadReader(turnId: string, details: boolean | string, throughTurnId?: string): Reader {
|
|
247
|
+
this.flush(turnId);
|
|
248
|
+
const cacheKey = this.readerKey(turnId, details, throughTurnId);
|
|
249
|
+
let cached = details !== true ? this.detailReaders.get(cacheKey) : undefined;
|
|
250
|
+
if (cached && (!fs.existsSync(this.file(turnId)) || fs.statSync(this.file(turnId)).size < cached.offset)) {
|
|
251
|
+
this.detailReaders.delete(cacheKey);
|
|
252
|
+
cached = undefined;
|
|
210
253
|
}
|
|
254
|
+
// Async readers and live connections must never mutate another request's checkpoint.
|
|
255
|
+
return cached ? { ...cached, projection: cached.projection.copy() }
|
|
256
|
+
: { projection: new TurnPreviewProjection(details), offset: 0, accessed: Date.now() };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
private finishRead(turnId: string, details: boolean | string, reader: Reader, throughTurnId?: string): TurnViewState | undefined {
|
|
260
|
+
if (details !== true) {
|
|
261
|
+
const now = Date.now();
|
|
262
|
+
for (const [key, value] of this.detailReaders) if (now - value.accessed > 60_000) this.detailReaders.delete(key);
|
|
263
|
+
const cacheKey = this.readerKey(turnId, details, throughTurnId);
|
|
264
|
+
this.detailReaders.delete(cacheKey);
|
|
265
|
+
if (reader.projection.retainedTextBytes() < 16 * 1024 * 1024)
|
|
266
|
+
this.detailReaders.set(cacheKey, { ...reader, accessed: now });
|
|
267
|
+
if (this.detailExpiry) clearTimeout(this.detailExpiry);
|
|
268
|
+
this.detailExpiry = setTimeout(() => this.detailReaders.clear(), 60_000);
|
|
269
|
+
this.detailExpiry.unref();
|
|
270
|
+
while (this.detailReaders.size > 4) this.detailReaders.delete(this.detailReaders.keys().next().value!);
|
|
271
|
+
}
|
|
272
|
+
return reader.projection.state ? { ...reader.projection.state, previewCursor: reader.offset } : undefined;
|
|
211
273
|
}
|
|
212
274
|
|
|
213
275
|
outputAppend(turnId: string, toolId: string, after: number, through: number): string | undefined {
|
|
@@ -255,8 +317,10 @@ export class TurnPreviewJournal {
|
|
|
255
317
|
if (record.kind === "event") {
|
|
256
318
|
for (const change of record.texts) this.track(writer, change);
|
|
257
319
|
const event = record.event;
|
|
258
|
-
if (
|
|
259
|
-
|
|
320
|
+
if (event.type === "tool_started" || event.type === "tool_updated") {
|
|
321
|
+
const startedAt = toolTimestamp(event.tool.startedAt);
|
|
322
|
+
if (startedAt !== undefined) writer.timings.set(event.tool.id, startedAt);
|
|
323
|
+
}
|
|
260
324
|
}
|
|
261
325
|
if (record.kind === "seed") {
|
|
262
326
|
writer.seeded = true;
|
|
@@ -296,9 +360,18 @@ export class TurnPreviewProjection {
|
|
|
296
360
|
readonly changed = new Set<string>();
|
|
297
361
|
readonly removed = new Set<string>();
|
|
298
362
|
private readonly text = new Map<string, string>();
|
|
363
|
+
private readonly toolPositions = new Map<string, number>();
|
|
299
364
|
constructor(private readonly details: boolean | string = false) {}
|
|
365
|
+
copy(): TurnPreviewProjection {
|
|
366
|
+
const copy = new TurnPreviewProjection(this.details);
|
|
367
|
+
copy.state = this.state && structuredClone(this.state);
|
|
368
|
+
copy.revision = this.revision;
|
|
369
|
+
for (const [key, value] of this.text) copy.text.set(key, value);
|
|
370
|
+
return copy;
|
|
371
|
+
}
|
|
300
372
|
retainedTextBytes(): number {
|
|
301
|
-
let bytes = 0
|
|
373
|
+
let bytes = ((this.state?.prompt?.length ?? 0) + (this.state?.finalResponse?.length ?? 0)
|
|
374
|
+
+ (this.state?.assistantText.length ?? 0)) * 2;
|
|
302
375
|
for (const value of this.text.values()) bytes += value.length * 2;
|
|
303
376
|
return bytes;
|
|
304
377
|
}
|
|
@@ -308,11 +381,20 @@ export class TurnPreviewProjection {
|
|
|
308
381
|
|
|
309
382
|
apply(record: PreviewRecord, revision: number): void {
|
|
310
383
|
if (record.kind === "seed") {
|
|
311
|
-
this.
|
|
384
|
+
this.toolPositions.clear();
|
|
385
|
+
this.state = { ...record.state, fullToolOutputs: { ...record.state.fullToolOutputs },
|
|
386
|
+
activities: record.state.activities.map(normalizeTurnActivity), activitiesTruncated: record.state.activitiesTruncated ?? false };
|
|
312
387
|
for (const change of seedTexts(record.state)) this.text.set(change.key, this.wantsFull(change.key) ? change.text : change.text.slice(0, 6000));
|
|
313
388
|
if (this.details !== true) {
|
|
389
|
+
const summarizeTool = (tool: ToolState): ToolState => this.wantsFull(`tool:${tool.id}:`) ? tool : { ...tool,
|
|
390
|
+
title: tool.title.slice(0, 6000), command: tool.command?.slice(0, 6000),
|
|
391
|
+
output: tool.output?.slice(0, 6000), error: tool.error?.slice(0, 6000) };
|
|
314
392
|
this.state = { ...this.state, fullToolOutputs: {}, fullToolErrors: {}, activities: this.state.activities.map((a) => a.kind === "tool"
|
|
315
|
-
? { ...a, tool:
|
|
393
|
+
? { ...a, tool: summarizeTool(a.tool) } : a),
|
|
394
|
+
activeTool: this.state.activeTool && summarizeTool(this.state.activeTool),
|
|
395
|
+
completedTools: this.state.completedTools.map(summarizeTool), failedTools: this.state.failedTools.map(summarizeTool),
|
|
396
|
+
reasoningItems: this.state.reasoningItems?.map((item) => this.wantsFull(`reasoning:${item.itemId}:`) ? item : { ...item,
|
|
397
|
+
summary: item.summary.map((text) => text.slice(0, 6000)), content: item.content.map((text) => text.slice(0, 6000)) }) };
|
|
316
398
|
}
|
|
317
399
|
if (typeof this.details === "string" && this.details.startsWith("tool:")) {
|
|
318
400
|
const id = this.details.slice(5);
|
|
@@ -336,13 +418,17 @@ export class TurnPreviewProjection {
|
|
|
336
418
|
return;
|
|
337
419
|
}
|
|
338
420
|
if (record.kind === "user") {
|
|
339
|
-
const user = { kind: "user" as const, id: record.id, text: record.text, localImagePaths: record.images };
|
|
340
421
|
const index = this.state.activities.findIndex((a) => a.id === record.id);
|
|
422
|
+
const previous = this.state.activities[index];
|
|
423
|
+
const startedAt = (previous?.kind === "user" ? previous.startedAt : undefined) ?? record.startedAt;
|
|
424
|
+
const user = { kind: "user" as const, id: record.id, text: record.text, localImagePaths: record.images,
|
|
425
|
+
...(startedAt === undefined ? {} : { startedAt }) };
|
|
341
426
|
this.state.activities = [...this.state.activities];
|
|
342
427
|
if (index < 0) this.state.activities.push(user); else this.state.activities[index] = user;
|
|
343
428
|
this.changed.add(record.id);
|
|
344
429
|
return;
|
|
345
430
|
}
|
|
431
|
+
if (record.event.type === "tool_output_delta" && this.applyToolOutput(record, revision)) return;
|
|
346
432
|
let event = { ...record.event } as AgentEvent;
|
|
347
433
|
if (event.type === "tool_started" || event.type === "tool_updated") event.tool = { ...event.tool };
|
|
348
434
|
if (event.type === "reasoning_completed") event = { ...event, summary: [...event.summary], content: [...event.content] };
|
|
@@ -379,7 +465,7 @@ export class TurnPreviewProjection {
|
|
|
379
465
|
else if (event.type === "agent_text_delta" && event.replacesActivityId) this.removed.add(event.replacesActivityId);
|
|
380
466
|
if (event.type === "reasoning_delta" || event.type === "reasoning_completed") this.changed.add(`reasoning:${event.itemId}`);
|
|
381
467
|
const old = this.state;
|
|
382
|
-
this.state = reduceTurnEvent(old, event, true);
|
|
468
|
+
this.state = reduceTurnEvent(old, event, true, true);
|
|
383
469
|
if (["completed", "failed", "cancelled"].includes(old.status) && !event.type.startsWith("turn_")) this.state.status = old.status;
|
|
384
470
|
const reasoningId = event.type === "reasoning_delta" || event.type === "reasoning_completed" ? event.itemId
|
|
385
471
|
: event.type === "progress" ? event.reasoning?.itemId : undefined;
|
|
@@ -392,7 +478,38 @@ export class TurnPreviewProjection {
|
|
|
392
478
|
if (old.approval && !this.state.approval) this.changed.add(approvalActivityId(event.turnId, old.approval.id));
|
|
393
479
|
if (this.details !== true && this.state.reasoningItems) this.state.reasoningItems = this.state.reasoningItems.map((r) => ({ ...r,
|
|
394
480
|
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
|
-
this.state.activitiesTruncated = false;
|
|
481
|
+
this.state.activitiesTruncated = old.activitiesTruncated ?? false;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
private applyToolOutput(record: Extract<PreviewRecord, { kind: "event" }>, revision: number): boolean {
|
|
485
|
+
const event = record.event;
|
|
486
|
+
const state = this.state!;
|
|
487
|
+
if (event.type !== "tool_output_delta" || !canApplyTurnEvent(state, event)
|
|
488
|
+
|| state.status !== "tool_running" || state.activeTool?.id !== event.toolId) return false;
|
|
489
|
+
let index = this.toolPositions.get(event.toolId);
|
|
490
|
+
if (index === undefined || state.activities[index]?.id !== event.toolId) {
|
|
491
|
+
index = state.activities.findIndex((a) => a.kind === "tool" && a.id === event.toolId);
|
|
492
|
+
this.toolPositions.set(event.toolId, index);
|
|
493
|
+
}
|
|
494
|
+
const activity = state.activities[index];
|
|
495
|
+
if (activity?.kind !== "tool" || activity.tool.status !== "running") return false;
|
|
496
|
+
const change = record.texts[0];
|
|
497
|
+
if (record.texts.length !== 1 || change?.key !== `tool:${event.toolId}:output`) return false;
|
|
498
|
+
const previous = change.append ? this.text.get(change.key) ?? "" : "";
|
|
499
|
+
const full = this.wantsFull(change.key);
|
|
500
|
+
const output = full ? previous + change.text
|
|
501
|
+
: previous.length >= 6000 ? previous : (previous + change.text).slice(0, 6000);
|
|
502
|
+
this.text.set(change.key, output);
|
|
503
|
+
const tool = { ...activity.tool, output, previewRevision: revision };
|
|
504
|
+
state.activities[index] = { ...activity, tool };
|
|
505
|
+
state.fullToolOutputs ??= {};
|
|
506
|
+
state.fullToolOutputs[event.toolId] = output;
|
|
507
|
+
const summary = previous.length > 6000 ? state.activeTool.output
|
|
508
|
+
: output.length <= 6000 ? output : output.slice(0, 5999) + "…";
|
|
509
|
+
state.activeTool = { ...state.activeTool, output: summary,
|
|
510
|
+
previewRevision: revision };
|
|
511
|
+
this.changed.add(event.toolId);
|
|
512
|
+
return true;
|
|
396
513
|
}
|
|
397
514
|
}
|
|
398
515
|
|
|
@@ -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
|
});
|