dsh-agent-enhancer 0.3.0 → 0.3.1
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/README.en.md +22 -10
- package/README.md +22 -10
- package/lib/client/context/open-tab.d.ts +5 -0
- package/lib/client/context/open-tab.d.ts.map +1 -1
- package/lib/client/dsh/conversation.d.ts.map +1 -1
- package/lib/client/dsh/icons.d.ts +2 -0
- package/lib/client/dsh/icons.d.ts.map +1 -1
- package/lib/client/dsh/overlay.d.ts.map +1 -1
- package/lib/client/index.d.ts.map +1 -1
- package/lib/client/locales.d.ts +93 -9
- package/lib/client/locales.d.ts.map +1 -1
- package/lib/client/prompt/coordinator.d.ts +2 -0
- package/lib/client/prompt/coordinator.d.ts.map +1 -1
- package/lib/client/prompt/history.d.ts.map +1 -1
- package/lib/client/prompt/ledger-store.d.ts +8 -0
- package/lib/client/prompt/ledger-store.d.ts.map +1 -0
- package/lib/client/prompt/ledger.d.ts +15 -0
- package/lib/client/prompt/ledger.d.ts.map +1 -0
- package/lib/client/rollback/actions.d.ts +1 -0
- package/lib/client/rollback/actions.d.ts.map +1 -1
- package/lib/client/rollback/controller.d.ts +24 -2
- package/lib/client/rollback/controller.d.ts.map +1 -1
- package/lib/client/rollback/failure.d.ts +7 -0
- package/lib/client/rollback/failure.d.ts.map +1 -0
- package/lib/client/rollback/format.d.ts +23 -0
- package/lib/client/rollback/format.d.ts.map +1 -0
- package/lib/client/rollback/input-actions-cache.d.ts +6 -0
- package/lib/client/rollback/input-actions-cache.d.ts.map +1 -0
- package/lib/client/rollback/modal-host.d.ts +13 -0
- package/lib/client/rollback/modal-host.d.ts.map +1 -1
- package/lib/client/rollback/preview.d.ts +3 -2
- package/lib/client/rollback/preview.d.ts.map +1 -1
- package/lib/client/rollback/prompt-entries.d.ts +9 -0
- package/lib/client/rollback/prompt-entries.d.ts.map +1 -0
- package/lib/client/rollback/remote.d.ts +2 -1
- package/lib/client/rollback/remote.d.ts.map +1 -1
- package/lib/client/rollback/session-stats-dock.d.ts +10 -0
- package/lib/client/rollback/session-stats-dock.d.ts.map +1 -0
- package/lib/client/rollback/session-stats-filter.d.ts +18 -0
- package/lib/client/rollback/session-stats-filter.d.ts.map +1 -0
- package/lib/client/rollback/session-stats-meter.d.ts +18 -0
- package/lib/client/rollback/session-stats-meter.d.ts.map +1 -0
- package/lib/client/rollback/timeline-format.d.ts +23 -0
- package/lib/client/rollback/timeline-format.d.ts.map +1 -0
- package/lib/client/rollback/timeline-kind.d.ts +13 -0
- package/lib/client/rollback/timeline-kind.d.ts.map +1 -0
- package/lib/client/rollback/timeline-panel.d.ts +25 -0
- package/lib/client/rollback/timeline-panel.d.ts.map +1 -0
- package/lib/client/rollback/timeline-tab.d.ts +39 -0
- package/lib/client/rollback/timeline-tab.d.ts.map +1 -0
- package/lib/client/rollback/transcript-filter.d.ts +5 -0
- package/lib/client/rollback/transcript-filter.d.ts.map +1 -1
- package/lib/client/rollback/transcript.d.ts +45 -5
- package/lib/client/rollback/transcript.d.ts.map +1 -1
- package/lib/client/rollback/turn-outline-filter.d.ts.map +1 -1
- package/lib/client/rollback/types.d.ts +14 -1
- package/lib/client/rollback/types.d.ts.map +1 -1
- package/lib/client/rollback/user-node.d.ts +1 -0
- package/lib/client/rollback/user-node.d.ts.map +1 -1
- package/lib/client.js +1807 -236
- package/lib/client.js.map +1 -1
- package/lib/host/auto-route/session-hook.d.ts.map +1 -1
- package/lib/host/auto-route/session-selection.d.ts.map +1 -1
- package/lib/host/checkpoint/activity.d.ts +43 -0
- package/lib/host/checkpoint/activity.d.ts.map +1 -0
- package/lib/host/checkpoint/availability.d.ts +8 -1
- package/lib/host/checkpoint/availability.d.ts.map +1 -1
- package/lib/host/checkpoint/capture.d.ts +12 -4
- package/lib/host/checkpoint/capture.d.ts.map +1 -1
- package/lib/host/checkpoint/dsh.d.ts.map +1 -1
- package/lib/host/checkpoint/files.d.ts +3 -0
- package/lib/host/checkpoint/files.d.ts.map +1 -1
- package/lib/host/checkpoint/live.d.ts +8 -0
- package/lib/host/checkpoint/live.d.ts.map +1 -1
- package/lib/host/checkpoint/service.d.ts +82 -0
- package/lib/host/checkpoint/service.d.ts.map +1 -1
- package/lib/host/checkpoint/store.d.ts +7 -0
- package/lib/host/checkpoint/store.d.ts.map +1 -1
- package/lib/host/checkpoint/workspace-snapshot.d.ts +30 -0
- package/lib/host/checkpoint/workspace-snapshot.d.ts.map +1 -0
- package/lib/host/index.d.ts +2 -1
- package/lib/host/index.d.ts.map +1 -1
- package/lib/host/rpc.d.ts +3 -0
- package/lib/host/rpc.d.ts.map +1 -1
- package/lib/host/usage/source.d.ts.map +1 -1
- package/lib/identity.d.ts +1 -1
- package/lib/identity.d.ts.map +1 -1
- package/lib/index.js +1094 -138
- package/lib/index.js.map +4 -4
- package/package.json +61 -60
package/lib/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// src/host/index.ts
|
|
2
2
|
import { existsSync, mkdirSync, readdirSync, renameSync, rmdirSync } from "node:fs";
|
|
3
3
|
import { homedir as homedir2 } from "node:os";
|
|
4
|
-
import { join as
|
|
4
|
+
import { join as join8 } from "node:path";
|
|
5
5
|
import z4 from "@deepseek-ai/schemastery";
|
|
6
6
|
import { RemoteError, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
|
|
7
7
|
|
|
@@ -160,7 +160,7 @@ var AuxiliaryError = class extends Error {
|
|
|
160
160
|
// src/identity.ts
|
|
161
161
|
var PACKAGE_NAME = "dsh-agent-enhancer";
|
|
162
162
|
var PLUGIN_ID = "agent-enhancer";
|
|
163
|
-
var PACKAGE_VERSION = "0.
|
|
163
|
+
var PACKAGE_VERSION = "0.3.1";
|
|
164
164
|
var LEGACY_PACKAGE_NAME = "dsh-composer-enhancer";
|
|
165
165
|
var ROLLBACK_PREFIX = `${PACKAGE_NAME}:rollback:`;
|
|
166
166
|
var UNDO_PREFIX = `${PACKAGE_NAME}:undo:`;
|
|
@@ -177,6 +177,19 @@ function indexOfRollbackPrefix(id) {
|
|
|
177
177
|
if (current >= 0) return current;
|
|
178
178
|
return id.indexOf(LEGACY_ROLLBACK_PREFIX);
|
|
179
179
|
}
|
|
180
|
+
function turnFromRollbackId(id) {
|
|
181
|
+
for (const prefix of [ROLLBACK_PREFIX, LEGACY_ROLLBACK_PREFIX]) {
|
|
182
|
+
if (!id.startsWith(prefix)) continue;
|
|
183
|
+
const match = new RegExp(`^${escapeRegExp(prefix)}(\\d+):`).exec(id);
|
|
184
|
+
if (match !== null) return Number(match[1]);
|
|
185
|
+
}
|
|
186
|
+
const embedded = indexOfRollbackPrefix(id);
|
|
187
|
+
if (embedded > 0) return turnFromRollbackId(id.slice(embedded));
|
|
188
|
+
return void 0;
|
|
189
|
+
}
|
|
190
|
+
function escapeRegExp(value) {
|
|
191
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
192
|
+
}
|
|
180
193
|
|
|
181
194
|
// src/host/catalog.ts
|
|
182
195
|
async function buildAuxiliaryModelCatalog(ctx) {
|
|
@@ -233,7 +246,10 @@ async function buildAuxiliaryModelCatalog(ctx) {
|
|
|
233
246
|
// src/host/checkpoint/dsh.ts
|
|
234
247
|
function syncIdleLastTurnFromProjection(ctx, agent) {
|
|
235
248
|
if (agent.status !== "idle") return;
|
|
236
|
-
const
|
|
249
|
+
const agents = ctx.agents;
|
|
250
|
+
const fromAgents = agents.turnBoundaryOf?.(agent.session);
|
|
251
|
+
const fromProjection = ctx.sessionProjections.stateOf(agent.session, "turnBoundary");
|
|
252
|
+
const lastTurn = fromAgents?.lastTurn ?? fromProjection?.lastTurn;
|
|
237
253
|
if (typeof lastTurn !== "number") return;
|
|
238
254
|
const live = agent;
|
|
239
255
|
if (live.phase?.kind !== "idle" || live.phase.lastTurn === lastTurn) return;
|
|
@@ -287,7 +303,142 @@ var DshCheckpointSessions = class {
|
|
|
287
303
|
};
|
|
288
304
|
|
|
289
305
|
// src/host/checkpoint/live.ts
|
|
290
|
-
import { isAbsolute as isAbsolute2, relative, sep as sep2 } from "node:path";
|
|
306
|
+
import { isAbsolute as isAbsolute2, join as join3, relative, sep as sep2 } from "node:path";
|
|
307
|
+
|
|
308
|
+
// src/host/checkpoint/activity.ts
|
|
309
|
+
function surfaceMessageId(event) {
|
|
310
|
+
switch (event.type) {
|
|
311
|
+
case "user/message":
|
|
312
|
+
return event.data.id;
|
|
313
|
+
case "system/message":
|
|
314
|
+
case "developer/message":
|
|
315
|
+
case "assistant/message":
|
|
316
|
+
case "tool/result":
|
|
317
|
+
return event.data.message.id;
|
|
318
|
+
default:
|
|
319
|
+
return null;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
function isUndoCopyEvent(event) {
|
|
323
|
+
const id = surfaceMessageId(event);
|
|
324
|
+
return id !== null && isUndoId(id);
|
|
325
|
+
}
|
|
326
|
+
function isRollbackScaffoldEvent(event) {
|
|
327
|
+
if (event.type !== "user/message") return false;
|
|
328
|
+
if (isRollbackId(event.data.id)) return true;
|
|
329
|
+
return event.data.source.kind === "checkpoint-rollback";
|
|
330
|
+
}
|
|
331
|
+
function undoShellRanges(events) {
|
|
332
|
+
const ranges = [];
|
|
333
|
+
let turn;
|
|
334
|
+
let startSeq = 0;
|
|
335
|
+
let sawUndo = false;
|
|
336
|
+
let sawReal = false;
|
|
337
|
+
let lastSeq = 0;
|
|
338
|
+
const flush = () => {
|
|
339
|
+
if (turn !== void 0 && sawUndo && !sawReal) {
|
|
340
|
+
ranges.push({ turn, startSeq, endSeq: lastSeq });
|
|
341
|
+
}
|
|
342
|
+
sawUndo = false;
|
|
343
|
+
sawReal = false;
|
|
344
|
+
};
|
|
345
|
+
for (const event of events) {
|
|
346
|
+
lastSeq = Number(event.seq);
|
|
347
|
+
if (event.type === "turn/start") {
|
|
348
|
+
flush();
|
|
349
|
+
turn = event.data.turn;
|
|
350
|
+
startSeq = lastSeq;
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
if (event.type === "turn/end" && turn !== void 0 && event.data.turn === turn) {
|
|
354
|
+
flush();
|
|
355
|
+
turn = void 0;
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
if (turn === void 0 || isRollbackScaffoldEvent(event)) continue;
|
|
359
|
+
if (isUndoCopyEvent(event)) {
|
|
360
|
+
sawUndo = true;
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
if (event.type === "user/message" || event.type === "assistant/message" || event.type === "tool/result" || event.type === "system/message" || event.type === "developer/message") {
|
|
364
|
+
sawReal = true;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
flush();
|
|
368
|
+
return ranges;
|
|
369
|
+
}
|
|
370
|
+
function inUndoShellRange(seq, ranges) {
|
|
371
|
+
return ranges.some((range) => seq >= range.startSeq && seq <= range.endSeq);
|
|
372
|
+
}
|
|
373
|
+
function isUndoShellCheckpoint(atSeq, ranges) {
|
|
374
|
+
const turnStartSeq = atSeq + 1;
|
|
375
|
+
return ranges.some((range) => turnStartSeq >= range.startSeq && turnStartSeq <= range.endSeq);
|
|
376
|
+
}
|
|
377
|
+
function turnOfEvent(event) {
|
|
378
|
+
if (event.type === "turn/start" || event.type === "turn/end" || event.type === "step/start" || event.type === "step/end") {
|
|
379
|
+
return event.data.turn;
|
|
380
|
+
}
|
|
381
|
+
const turn = event.data.turn;
|
|
382
|
+
return typeof turn === "number" ? turn : void 0;
|
|
383
|
+
}
|
|
384
|
+
function liveActivityStats(events, options) {
|
|
385
|
+
const ranges = undoShellRanges(events);
|
|
386
|
+
const everShadowed = /* @__PURE__ */ new Set();
|
|
387
|
+
for (const event of events) {
|
|
388
|
+
if (!isRollbackScaffoldEvent(event)) continue;
|
|
389
|
+
for (const seq of event.sourceEventSeqs ?? []) everShadowed.add(Number(seq));
|
|
390
|
+
}
|
|
391
|
+
const closed = /* @__PURE__ */ new Set();
|
|
392
|
+
const turns = /* @__PURE__ */ new Set();
|
|
393
|
+
for (const event of events) {
|
|
394
|
+
if (event.type !== "step/end") continue;
|
|
395
|
+
const seq = Number(event.seq);
|
|
396
|
+
if (everShadowed.has(seq)) continue;
|
|
397
|
+
if (inUndoShellRange(seq, ranges)) continue;
|
|
398
|
+
const beforeTip = options.continueAfterSeq === void 0 || seq <= options.continueAfterSeq;
|
|
399
|
+
const turn = event.data.turn;
|
|
400
|
+
if (options.hideTurnsFrom !== void 0 && turn >= options.hideTurnsFrom && beforeTip) {
|
|
401
|
+
continue;
|
|
402
|
+
}
|
|
403
|
+
const key = `${turn}:${event.data.step}`;
|
|
404
|
+
if (closed.has(key)) continue;
|
|
405
|
+
closed.add(key);
|
|
406
|
+
turns.add(turn);
|
|
407
|
+
}
|
|
408
|
+
if (closed.size === 0) {
|
|
409
|
+
let steps = 0;
|
|
410
|
+
for (const event of events) {
|
|
411
|
+
const seq = Number(event.seq);
|
|
412
|
+
if (inUndoShellRange(seq, ranges)) continue;
|
|
413
|
+
if (isRollbackScaffoldEvent(event)) continue;
|
|
414
|
+
const beforeTip = options.continueAfterSeq === void 0 || seq <= options.continueAfterSeq;
|
|
415
|
+
const ownedTurn = turnOfEvent(event);
|
|
416
|
+
if (options.hideTurnsFrom !== void 0 && ownedTurn !== void 0 && ownedTurn >= options.hideTurnsFrom && beforeTip && !isUndoCopyEvent(event)) {
|
|
417
|
+
continue;
|
|
418
|
+
}
|
|
419
|
+
if (event.type === "turn/start") {
|
|
420
|
+
turns.add(event.data.turn);
|
|
421
|
+
continue;
|
|
422
|
+
}
|
|
423
|
+
if (event.type === "assistant/message") {
|
|
424
|
+
steps += 1;
|
|
425
|
+
if (ownedTurn !== void 0) turns.add(ownedTurn);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
return {
|
|
429
|
+
turns: turns.size,
|
|
430
|
+
steps,
|
|
431
|
+
checkpoints: options.checkpointCount,
|
|
432
|
+
liveCheckpoints: options.liveCheckpointCount
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
return {
|
|
436
|
+
turns: turns.size,
|
|
437
|
+
steps: closed.size,
|
|
438
|
+
checkpoints: options.checkpointCount,
|
|
439
|
+
liveCheckpoints: options.liveCheckpointCount
|
|
440
|
+
};
|
|
441
|
+
}
|
|
291
442
|
|
|
292
443
|
// src/host/checkpoint/capture.ts
|
|
293
444
|
import { randomUUID } from "node:crypto";
|
|
@@ -296,19 +447,50 @@ import { randomUUID } from "node:crypto";
|
|
|
296
447
|
var CHECKPOINT_SCHEMA_VERSION = 1;
|
|
297
448
|
|
|
298
449
|
// src/host/checkpoint/capture.ts
|
|
450
|
+
function textBlocksOf(content) {
|
|
451
|
+
return content.flatMap((block) => block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("");
|
|
452
|
+
}
|
|
299
453
|
function directText(prompt) {
|
|
300
454
|
if (prompt.source.kind !== "user" || prompt.content.length === 0) return null;
|
|
301
|
-
|
|
302
|
-
return
|
|
455
|
+
const text3 = textBlocksOf(prompt.content);
|
|
456
|
+
return text3.trim() === "" ? null : text3;
|
|
457
|
+
}
|
|
458
|
+
function recoverTurnPrompt(events, turn) {
|
|
459
|
+
const turnStart = events.find(
|
|
460
|
+
(event) => event.type === "turn/start" && event.data.turn === turn
|
|
461
|
+
);
|
|
462
|
+
const turnEnd = events.find(
|
|
463
|
+
(event) => event.type === "turn/end" && event.data.turn === turn
|
|
464
|
+
);
|
|
465
|
+
if (turnStart === void 0 || turnEnd === void 0) return "";
|
|
466
|
+
for (const event of events) {
|
|
467
|
+
if (event.type !== "user/message") continue;
|
|
468
|
+
if (event.seq <= turnStart.seq || event.seq >= turnEnd.seq) continue;
|
|
469
|
+
if (event.data.source.kind !== "user") continue;
|
|
470
|
+
const text3 = textBlocksOf(event.data.content);
|
|
471
|
+
if (text3.trim() !== "") return text3;
|
|
472
|
+
}
|
|
473
|
+
return "";
|
|
303
474
|
}
|
|
304
475
|
function checkpointAtSeq(turnStartSeq) {
|
|
305
476
|
return Math.max(0, turnStartSeq - 1);
|
|
306
477
|
}
|
|
307
|
-
function resolveRollbackCut(events, turn,
|
|
308
|
-
const
|
|
478
|
+
function resolveRollbackCut(events, turn, atSeq) {
|
|
479
|
+
const starts = events.filter(
|
|
309
480
|
(event) => event.type === "turn/start" && event.data.turn === turn
|
|
310
481
|
);
|
|
311
|
-
if (
|
|
482
|
+
if (starts.length === 0) return null;
|
|
483
|
+
let turnStart = starts[0];
|
|
484
|
+
if (typeof atSeq === "number") {
|
|
485
|
+
const want = atSeq + 1;
|
|
486
|
+
const exact = starts.find((event) => Number(event.seq) === want);
|
|
487
|
+
if (exact !== void 0) {
|
|
488
|
+
turnStart = exact;
|
|
489
|
+
} else {
|
|
490
|
+
const after = [...starts].reverse().find((event) => Number(event.seq) >= want);
|
|
491
|
+
if (after !== void 0) turnStart = after;
|
|
492
|
+
}
|
|
493
|
+
}
|
|
312
494
|
return { cutSeq: Number(turnStart.seq) - 1 };
|
|
313
495
|
}
|
|
314
496
|
async function captureCheckpoint(options) {
|
|
@@ -322,8 +504,8 @@ async function captureCheckpoint(options) {
|
|
|
322
504
|
let files;
|
|
323
505
|
try {
|
|
324
506
|
files = await options.captureFiles();
|
|
325
|
-
} catch {
|
|
326
|
-
files = [];
|
|
507
|
+
} catch (error) {
|
|
508
|
+
files = Array.isArray(error.files) ? error.files : [];
|
|
327
509
|
gaps.push({ type: "workspace", reason: "capture-failed" });
|
|
328
510
|
}
|
|
329
511
|
options.onStage?.("workspace-captured");
|
|
@@ -356,7 +538,7 @@ function synthesizeCheckpoint(options) {
|
|
|
356
538
|
if (turnStart === void 0 || turnEnd === void 0 || turnStart.seq < 0) return null;
|
|
357
539
|
if (options.events.some((event, index) => Number(event.seq) !== index)) return null;
|
|
358
540
|
const user = options.events.find(
|
|
359
|
-
(event) => event.type === "user/message" && event.seq > turnStart.seq && event.seq < turnEnd.seq
|
|
541
|
+
(event) => event.type === "user/message" && event.data.source.kind === "user" && event.seq > turnStart.seq && event.seq < turnEnd.seq
|
|
360
542
|
);
|
|
361
543
|
const prompt = user === void 0 ? null : directText(user.data);
|
|
362
544
|
const gaps = prompt === null ? [{ type: "prompt", reason: "non-text-content" }] : [];
|
|
@@ -385,6 +567,11 @@ import { TextDecoder } from "node:util";
|
|
|
385
567
|
var MAX_FILE_BYTES = 2 * 1024 * 1024;
|
|
386
568
|
var ABSENT_FILE_HASH = "";
|
|
387
569
|
var excludedSegments = /* @__PURE__ */ new Set([".git", "node_modules", ".dsh", "dist", "build", "out", "coverage", ".next"]);
|
|
570
|
+
function isExcludedSegment(segment) {
|
|
571
|
+
if (!segment || segment === "." || segment === "..") return true;
|
|
572
|
+
const canonical = segment.replace(/[. ]+$/g, "").toLowerCase();
|
|
573
|
+
return !canonical || excludedSegments.has(canonical) || canonical === ".env" || canonical.startsWith(".env.");
|
|
574
|
+
}
|
|
388
575
|
var decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
389
576
|
var transactionQueues = /* @__PURE__ */ new Map();
|
|
390
577
|
async function serialize(key, operation) {
|
|
@@ -441,11 +628,7 @@ function pathKey(path) {
|
|
|
441
628
|
}
|
|
442
629
|
function unsafePath(path) {
|
|
443
630
|
if (!path || path.includes("\0") || isAbsolute(path) || win32.isAbsolute(path) || /^[a-z]:/i.test(path)) return true;
|
|
444
|
-
return segments(path).some((segment) =>
|
|
445
|
-
if (!segment || segment === "." || segment === "..") return true;
|
|
446
|
-
const canonical = canonicalSegment(segment);
|
|
447
|
-
return !canonical || excludedSegments.has(canonical) || canonical === ".env" || canonical.startsWith(".env.");
|
|
448
|
-
});
|
|
631
|
+
return segments(path).some((segment) => isExcludedSegment(segment));
|
|
449
632
|
}
|
|
450
633
|
function absolutePath(workspaceRoot, path) {
|
|
451
634
|
return resolve(workspaceRoot, ...segments(path));
|
|
@@ -803,7 +986,123 @@ var CheckpointFiles = class {
|
|
|
803
986
|
}
|
|
804
987
|
};
|
|
805
988
|
|
|
989
|
+
// src/host/checkpoint/workspace-snapshot.ts
|
|
990
|
+
import { readdir } from "node:fs/promises";
|
|
991
|
+
import { join as join2 } from "node:path";
|
|
992
|
+
var MAX_WORKSPACE_SCAN_FILES = 2e3;
|
|
993
|
+
var MAX_SHELL_CHANGED_FILES = 200;
|
|
994
|
+
async function scanWorkspace(workspaceRoot, options = {}) {
|
|
995
|
+
const maxFiles = options.maxFiles ?? MAX_WORKSPACE_SCAN_FILES;
|
|
996
|
+
const files = /* @__PURE__ */ new Map();
|
|
997
|
+
let truncated = false;
|
|
998
|
+
const visit = async (absoluteDir, relativeDir) => {
|
|
999
|
+
if (truncated) return;
|
|
1000
|
+
let entries;
|
|
1001
|
+
try {
|
|
1002
|
+
entries = await readdir(absoluteDir, { withFileTypes: true });
|
|
1003
|
+
} catch {
|
|
1004
|
+
truncated = true;
|
|
1005
|
+
return;
|
|
1006
|
+
}
|
|
1007
|
+
for (const entry of entries) {
|
|
1008
|
+
if (truncated) return;
|
|
1009
|
+
if (isExcludedSegment(entry.name)) continue;
|
|
1010
|
+
const relativePath = relativeDir === "" ? entry.name : `${relativeDir}/${entry.name}`;
|
|
1011
|
+
const absolutePath2 = join2(absoluteDir, entry.name);
|
|
1012
|
+
if (entry.isSymbolicLink()) continue;
|
|
1013
|
+
if (entry.isDirectory()) {
|
|
1014
|
+
await visit(absolutePath2, relativePath.split("\\").join("/"));
|
|
1015
|
+
continue;
|
|
1016
|
+
}
|
|
1017
|
+
if (!entry.isFile()) continue;
|
|
1018
|
+
const path = relativePath.split("\\").join("/");
|
|
1019
|
+
if (unsafePath(path)) continue;
|
|
1020
|
+
if (files.size >= maxFiles) {
|
|
1021
|
+
truncated = true;
|
|
1022
|
+
return;
|
|
1023
|
+
}
|
|
1024
|
+
try {
|
|
1025
|
+
const snapshot = await readSnapshot(workspaceRoot, path);
|
|
1026
|
+
if (snapshot.exists) files.set(path, snapshot);
|
|
1027
|
+
} catch {
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
};
|
|
1031
|
+
await visit(workspaceRoot, "");
|
|
1032
|
+
return { files, truncated };
|
|
1033
|
+
}
|
|
1034
|
+
function diffSnapshots(before, after, options = {}) {
|
|
1035
|
+
const maxChanges = options.maxChanges ?? MAX_SHELL_CHANGED_FILES;
|
|
1036
|
+
const files = [];
|
|
1037
|
+
let truncated = false;
|
|
1038
|
+
const push = (checkpoint) => {
|
|
1039
|
+
if (files.length >= maxChanges) {
|
|
1040
|
+
truncated = true;
|
|
1041
|
+
return;
|
|
1042
|
+
}
|
|
1043
|
+
files.push(checkpoint);
|
|
1044
|
+
};
|
|
1045
|
+
for (const [path, afterSnap] of after) {
|
|
1046
|
+
if (truncated) break;
|
|
1047
|
+
const beforeSnap = before.get(path) ?? { path, exists: false, text: null };
|
|
1048
|
+
const beforeHash = snapshotHash(beforeSnap);
|
|
1049
|
+
const afterHash = snapshotHash(afterSnap);
|
|
1050
|
+
if (beforeHash === afterHash) continue;
|
|
1051
|
+
push({
|
|
1052
|
+
path,
|
|
1053
|
+
change: !beforeSnap.exists ? "create" : "modify",
|
|
1054
|
+
beforeText: beforeSnap.exists ? beforeSnap.text : null,
|
|
1055
|
+
beforeHash,
|
|
1056
|
+
afterText: afterSnap.exists ? afterSnap.text : null,
|
|
1057
|
+
afterHash
|
|
1058
|
+
});
|
|
1059
|
+
}
|
|
1060
|
+
for (const [path, beforeSnap] of before) {
|
|
1061
|
+
if (truncated) break;
|
|
1062
|
+
if (after.has(path)) continue;
|
|
1063
|
+
const afterSnap = { path, exists: false, text: null };
|
|
1064
|
+
const beforeHash = snapshotHash(beforeSnap);
|
|
1065
|
+
const afterHash = snapshotHash(afterSnap);
|
|
1066
|
+
if (beforeHash === afterHash) continue;
|
|
1067
|
+
push({
|
|
1068
|
+
path,
|
|
1069
|
+
change: "delete",
|
|
1070
|
+
beforeText: beforeSnap.exists ? beforeSnap.text : null,
|
|
1071
|
+
beforeHash,
|
|
1072
|
+
afterText: null,
|
|
1073
|
+
afterHash
|
|
1074
|
+
});
|
|
1075
|
+
}
|
|
1076
|
+
return { files, truncated };
|
|
1077
|
+
}
|
|
1078
|
+
|
|
806
1079
|
// src/host/checkpoint/live.ts
|
|
1080
|
+
function isFileMutationTool(name2) {
|
|
1081
|
+
return /^(?:write_file|edit_file|write|edit|str_replace(?:_editor)?|apply_patch)$/i.test(name2);
|
|
1082
|
+
}
|
|
1083
|
+
function isShellTool(name2) {
|
|
1084
|
+
return /^(?:shell|bash|terminal|run_code|pwsh)/i.test(name2);
|
|
1085
|
+
}
|
|
1086
|
+
function filePathFromToolArgs(args) {
|
|
1087
|
+
if (args === null || typeof args !== "object") return null;
|
|
1088
|
+
const record2 = args;
|
|
1089
|
+
for (const key of ["path", "file_path", "filePath", "target"]) {
|
|
1090
|
+
const value = record2[key];
|
|
1091
|
+
if (typeof value === "string" && value.trim() !== "") return value;
|
|
1092
|
+
}
|
|
1093
|
+
return null;
|
|
1094
|
+
}
|
|
1095
|
+
function agentFromActor(actor, actors) {
|
|
1096
|
+
if (actor === void 0) return void 0;
|
|
1097
|
+
const mapped = actors.get(actor);
|
|
1098
|
+
if (mapped !== void 0) return mapped;
|
|
1099
|
+
if (!("agent" in actor)) return void 0;
|
|
1100
|
+
const agent = actor.agent;
|
|
1101
|
+
return agent;
|
|
1102
|
+
}
|
|
1103
|
+
function isScaffoldUserPrompt(event) {
|
|
1104
|
+
return isUndoId(event.data.id) || isRollbackId(event.data.id) || isRollbackScaffoldEvent(event);
|
|
1105
|
+
}
|
|
807
1106
|
var DshCheckpointCapture = class {
|
|
808
1107
|
constructor(ctx, options) {
|
|
809
1108
|
this.ctx = ctx;
|
|
@@ -819,7 +1118,8 @@ var DshCheckpointCapture = class {
|
|
|
819
1118
|
turnStart: null,
|
|
820
1119
|
files: /* @__PURE__ */ new Map(),
|
|
821
1120
|
capturing: /* @__PURE__ */ new Set(),
|
|
822
|
-
incomplete: false
|
|
1121
|
+
incomplete: false,
|
|
1122
|
+
suppressCheckpoint: false
|
|
823
1123
|
});
|
|
824
1124
|
}
|
|
825
1125
|
return next();
|
|
@@ -836,13 +1136,21 @@ var DshCheckpointCapture = class {
|
|
|
836
1136
|
turnStart: null,
|
|
837
1137
|
files: /* @__PURE__ */ new Map(),
|
|
838
1138
|
capturing: /* @__PURE__ */ new Set(),
|
|
839
|
-
incomplete: false
|
|
1139
|
+
incomplete: false,
|
|
1140
|
+
suppressCheckpoint: false
|
|
840
1141
|
};
|
|
841
1142
|
current.turnStart = event;
|
|
842
1143
|
this.turns.set(session.id, current);
|
|
843
1144
|
} else if (event.type === "user/message") {
|
|
844
1145
|
const current = this.turns.get(session.id);
|
|
845
|
-
if (current
|
|
1146
|
+
if (current === void 0) return;
|
|
1147
|
+
if (isScaffoldUserPrompt(event)) {
|
|
1148
|
+
current.suppressCheckpoint = true;
|
|
1149
|
+
return;
|
|
1150
|
+
}
|
|
1151
|
+
if (event.data.source.kind === "user" && (current.prompt === null || current.prompt.source.kind !== "user")) {
|
|
1152
|
+
current.prompt = event.data;
|
|
1153
|
+
}
|
|
846
1154
|
} else if (event.type === "turn/end") {
|
|
847
1155
|
const current = this.turns.get(session.id);
|
|
848
1156
|
if (current?.turnStart?.data.turn === event.data.turn) {
|
|
@@ -851,25 +1159,34 @@ var DshCheckpointCapture = class {
|
|
|
851
1159
|
}
|
|
852
1160
|
}
|
|
853
1161
|
}),
|
|
1162
|
+
// global: Desktop dispatches tools/execute with an agent carrier; without
|
|
1163
|
+
// this flag the host plugin's listener is filtered out and never runs.
|
|
854
1164
|
ctx.on("tools/execute", async (exec, next) => {
|
|
855
1165
|
if (exec.agent === void 0) return next();
|
|
856
1166
|
const current = this.turns.get(exec.agent.id);
|
|
857
|
-
if (current !== void 0 && /^(?:shell|bash|terminal|run_code)/.test(exec.name)) current.incomplete = true;
|
|
858
1167
|
this.actors.set(exec, exec.agent);
|
|
859
1168
|
try {
|
|
1169
|
+
if (current !== void 0 && isFileMutationTool(exec.name)) {
|
|
1170
|
+
await this.captureToolPath(exec.agent, exec.arguments);
|
|
1171
|
+
}
|
|
1172
|
+
if (current !== void 0 && isShellTool(exec.name)) {
|
|
1173
|
+
return await this.captureShellWorkspace(current, next);
|
|
1174
|
+
}
|
|
860
1175
|
return await next();
|
|
861
1176
|
} finally {
|
|
862
1177
|
this.actors.delete(exec);
|
|
863
1178
|
}
|
|
864
|
-
}),
|
|
1179
|
+
}, { global: true }),
|
|
1180
|
+
// Prepend: policy is a single-slot owner that does not call next(). Capture
|
|
1181
|
+
// must wrap it so create/edit before-images still land in the checkpoint.
|
|
865
1182
|
ctx.on("fs/write-intent", async (target, actor, next) => {
|
|
866
1183
|
await this.captureIntent(target, actor);
|
|
867
1184
|
return next();
|
|
868
|
-
}),
|
|
1185
|
+
}, { prepend: true, global: true }),
|
|
869
1186
|
ctx.on("fs/edit-intent", async (target, actor, next) => {
|
|
870
1187
|
await this.captureIntent(target, actor);
|
|
871
1188
|
return next();
|
|
872
|
-
})
|
|
1189
|
+
}, { prepend: true, global: true })
|
|
873
1190
|
);
|
|
874
1191
|
}
|
|
875
1192
|
ctx;
|
|
@@ -892,7 +1209,7 @@ var DshCheckpointCapture = class {
|
|
|
892
1209
|
}
|
|
893
1210
|
finish(turn, turnEnd) {
|
|
894
1211
|
const turnStart = turn.turnStart;
|
|
895
|
-
if (turnStart === null) return;
|
|
1212
|
+
if (turnStart === null || turn.suppressCheckpoint) return;
|
|
896
1213
|
const operation = captureCheckpoint({
|
|
897
1214
|
store: {
|
|
898
1215
|
save: async (checkpoint) => {
|
|
@@ -918,12 +1235,76 @@ var DshCheckpointCapture = class {
|
|
|
918
1235
|
this.pending.delete(operation);
|
|
919
1236
|
});
|
|
920
1237
|
}
|
|
1238
|
+
/**
|
|
1239
|
+
* Cline-style workspace before/after scan around shell tools so creates like
|
|
1240
|
+
* `Set-Content` land in turn.files. Incomplete only when the scan truncates
|
|
1241
|
+
* or fails — not merely because a shell tool ran.
|
|
1242
|
+
*/
|
|
1243
|
+
async captureShellWorkspace(turn, run) {
|
|
1244
|
+
const workspaceRoot = turn.agent.session.header.cwd;
|
|
1245
|
+
if (workspaceRoot === void 0) {
|
|
1246
|
+
turn.incomplete = true;
|
|
1247
|
+
return run();
|
|
1248
|
+
}
|
|
1249
|
+
let before;
|
|
1250
|
+
try {
|
|
1251
|
+
before = await scanWorkspace(workspaceRoot);
|
|
1252
|
+
} catch {
|
|
1253
|
+
turn.incomplete = true;
|
|
1254
|
+
return run();
|
|
1255
|
+
}
|
|
1256
|
+
if (before.truncated) turn.incomplete = true;
|
|
1257
|
+
try {
|
|
1258
|
+
return await run();
|
|
1259
|
+
} finally {
|
|
1260
|
+
try {
|
|
1261
|
+
const after = await scanWorkspace(workspaceRoot);
|
|
1262
|
+
if (after.truncated) turn.incomplete = true;
|
|
1263
|
+
const diff = diffSnapshots(before.files, after.files);
|
|
1264
|
+
if (diff.truncated) turn.incomplete = true;
|
|
1265
|
+
for (const file of diff.files) {
|
|
1266
|
+
if (turn.files.has(file.path) || turn.capturing.has(file.path)) continue;
|
|
1267
|
+
turn.files.set(file.path, {
|
|
1268
|
+
path: file.path,
|
|
1269
|
+
before: file.beforeText === null ? { path: file.path, exists: false, text: null } : { path: file.path, exists: true, text: file.beforeText }
|
|
1270
|
+
});
|
|
1271
|
+
}
|
|
1272
|
+
} catch {
|
|
1273
|
+
turn.incomplete = true;
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
async captureToolPath(agent, args) {
|
|
1278
|
+
const path = filePathFromToolArgs(args);
|
|
1279
|
+
if (path === null) return;
|
|
1280
|
+
const workspaceRoot = agent.session.header.cwd;
|
|
1281
|
+
if (workspaceRoot === void 0) {
|
|
1282
|
+
const turn = this.turns.get(agent.id);
|
|
1283
|
+
if (turn !== void 0) turn.incomplete = true;
|
|
1284
|
+
return;
|
|
1285
|
+
}
|
|
1286
|
+
try {
|
|
1287
|
+
const absolutePath2 = isAbsolute2(path) ? path : join3(workspaceRoot, path);
|
|
1288
|
+
await this.captureAbsolutePath(agent, absolutePath2);
|
|
1289
|
+
} catch {
|
|
1290
|
+
const turn = this.turns.get(agent.id);
|
|
1291
|
+
if (turn !== void 0) turn.incomplete = true;
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
921
1294
|
async captureIntent(target, actor) {
|
|
922
|
-
const agent = actor
|
|
1295
|
+
const agent = agentFromActor(actor, this.actors);
|
|
923
1296
|
if (agent === void 0) {
|
|
924
|
-
for (const turn2 of this.turns.values()) turn2.incomplete = true;
|
|
925
1297
|
return;
|
|
926
1298
|
}
|
|
1299
|
+
try {
|
|
1300
|
+
const absolutePath2 = this.ctx.fs.processPath(target);
|
|
1301
|
+
await this.captureAbsolutePath(agent, absolutePath2);
|
|
1302
|
+
} catch {
|
|
1303
|
+
const turn = this.turns.get(agent.id);
|
|
1304
|
+
if (turn !== void 0) turn.incomplete = true;
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
async captureAbsolutePath(agent, absolutePath2) {
|
|
927
1308
|
const turn = this.turns.get(agent.id);
|
|
928
1309
|
if (turn === void 0) return;
|
|
929
1310
|
const workspaceRoot = agent.session.header.cwd;
|
|
@@ -932,7 +1313,6 @@ var DshCheckpointCapture = class {
|
|
|
932
1313
|
return;
|
|
933
1314
|
}
|
|
934
1315
|
try {
|
|
935
|
-
const absolutePath2 = this.ctx.fs.processPath(target);
|
|
936
1316
|
const relativePath = relative(workspaceRoot, absolutePath2);
|
|
937
1317
|
if (relativePath === "" || relativePath.startsWith(`..${sep2}`) || relativePath === ".." || isAbsolute2(relativePath)) {
|
|
938
1318
|
turn.incomplete = true;
|
|
@@ -971,7 +1351,9 @@ var DshCheckpointCapture = class {
|
|
|
971
1351
|
afterHash
|
|
972
1352
|
});
|
|
973
1353
|
}
|
|
974
|
-
if (turn.incomplete)
|
|
1354
|
+
if (turn.incomplete) {
|
|
1355
|
+
throw Object.assign(new Error("Workspace capture is incomplete"), { files });
|
|
1356
|
+
}
|
|
975
1357
|
return files;
|
|
976
1358
|
}
|
|
977
1359
|
};
|
|
@@ -1029,26 +1411,62 @@ var CONVERSATION_SOFT = /* @__PURE__ */ new Set([
|
|
|
1029
1411
|
"compacted-surface",
|
|
1030
1412
|
// Conversation restore does not need a workspace cwd.
|
|
1031
1413
|
"permission-denied",
|
|
1032
|
-
// Turn 1 is restorable; keep this soft for older previews that still emit it.
|
|
1033
|
-
"first-turn"
|
|
1034
1414
|
// Non-contiguous logs are unusual but still restorable when a surface was built.
|
|
1035
1415
|
// Only emit unknown-surface when surface is missing — that case stays hard.
|
|
1416
|
+
// Re-confirming the active tip is a soft no-op (draft prefill / optional files).
|
|
1417
|
+
"already-restored",
|
|
1418
|
+
// Covered cuts need undo-first — UI replaces confirms with Undo, not a fatal gap list.
|
|
1419
|
+
"covered-by-earlier-restore"
|
|
1036
1420
|
]);
|
|
1037
1421
|
var EMPTY_FILES_SOFT = /* @__PURE__ */ new Set([
|
|
1038
1422
|
"incomplete-checkpoint",
|
|
1039
1423
|
"workspace-capture-failed",
|
|
1040
1424
|
"prompt-non-text-content",
|
|
1041
|
-
"compacted-surface"
|
|
1425
|
+
"compacted-surface",
|
|
1426
|
+
"already-restored",
|
|
1427
|
+
"covered-by-earlier-restore"
|
|
1428
|
+
]);
|
|
1429
|
+
var TRACKED_FILES_SOFT = /* @__PURE__ */ new Set([
|
|
1430
|
+
"incomplete-checkpoint",
|
|
1431
|
+
"workspace-capture-failed",
|
|
1432
|
+
"prompt-non-text-content",
|
|
1433
|
+
"already-restored",
|
|
1434
|
+
"covered-by-earlier-restore"
|
|
1042
1435
|
]);
|
|
1043
1436
|
function blockingUnavailable(unavailable, scope, options = {}) {
|
|
1044
|
-
const trackedFiles = options.trackedFiles;
|
|
1045
|
-
const soft = scope === "conversation"
|
|
1046
|
-
if (soft === null) return unavailable;
|
|
1437
|
+
const trackedFiles = options.trackedFiles ?? 0;
|
|
1438
|
+
const soft = scope === "conversation" ? CONVERSATION_SOFT : trackedFiles === 0 ? EMPTY_FILES_SOFT : TRACKED_FILES_SOFT;
|
|
1047
1439
|
return unavailable.filter((reason) => !soft.has(reason));
|
|
1048
1440
|
}
|
|
1049
1441
|
|
|
1050
1442
|
// src/host/checkpoint/service.ts
|
|
1051
1443
|
var surfaceEventTypes = /* @__PURE__ */ new Set(["system/message", "developer/message", "user/message", "assistant/message", "tool/result"]);
|
|
1444
|
+
var PROMPT_PREVIEW_MAX = 96;
|
|
1445
|
+
function checkpointPromptPreview(prompt, max = PROMPT_PREVIEW_MAX) {
|
|
1446
|
+
const normalized = prompt.replace(/\s+/g, " ").trim();
|
|
1447
|
+
if (normalized.length <= max) return normalized;
|
|
1448
|
+
return `${normalized.slice(0, Math.max(0, max - 1)).trimEnd()}\u2026`;
|
|
1449
|
+
}
|
|
1450
|
+
function toCheckpointTurnSummary(checkpoint, options = {}) {
|
|
1451
|
+
const rolledBack = options.rolledBack ?? false;
|
|
1452
|
+
const tip = options.tip ?? false;
|
|
1453
|
+
const recovered = options.recoveredPrompt?.trim() ?? "";
|
|
1454
|
+
const prompt = checkpoint.prompt.trim() !== "" ? checkpoint.prompt : recovered;
|
|
1455
|
+
const gaps = prompt.trim() === "" ? checkpoint.gaps : checkpoint.gaps.filter((gap) => !(gap.type === "prompt" && gap.reason === "non-text-content"));
|
|
1456
|
+
return {
|
|
1457
|
+
turn: checkpoint.turn,
|
|
1458
|
+
coverage: gaps.length === 0 ? "complete" : "partial",
|
|
1459
|
+
fileCount: checkpoint.files.length,
|
|
1460
|
+
createdAt: checkpoint.createdAt,
|
|
1461
|
+
atSeq: checkpoint.atSeq,
|
|
1462
|
+
prompt,
|
|
1463
|
+
promptPreview: checkpointPromptPreview(prompt),
|
|
1464
|
+
files: checkpoint.files.map((file) => ({ path: file.path, change: file.change })),
|
|
1465
|
+
gaps,
|
|
1466
|
+
rolledBack,
|
|
1467
|
+
tip
|
|
1468
|
+
};
|
|
1469
|
+
}
|
|
1052
1470
|
var CheckpointRollbackError = class extends Error {
|
|
1053
1471
|
constructor(code, unavailable = [], conflicts = []) {
|
|
1054
1472
|
super(code);
|
|
@@ -1093,7 +1511,42 @@ function isRollbackMarker(event, turn) {
|
|
|
1093
1511
|
const embedded = event.data.id.slice(original);
|
|
1094
1512
|
return prefixes.some((prefix) => embedded.startsWith(prefix));
|
|
1095
1513
|
}
|
|
1096
|
-
function
|
|
1514
|
+
function surfaceOpOf(event) {
|
|
1515
|
+
const op = event.surfaceOp;
|
|
1516
|
+
if (op === "append") return "append";
|
|
1517
|
+
if (typeof op !== "object" || op === null) return void 0;
|
|
1518
|
+
const record2 = op;
|
|
1519
|
+
if (record2.op !== "replace") return void 0;
|
|
1520
|
+
if (typeof record2.startSeq !== "number" || typeof record2.endSeq !== "number") return void 0;
|
|
1521
|
+
return { op: "replace", startSeq: record2.startSeq, endSeq: record2.endSeq };
|
|
1522
|
+
}
|
|
1523
|
+
function markerStillActive(marker, events) {
|
|
1524
|
+
return !events.some((event) => {
|
|
1525
|
+
if (event.seq <= marker.seq) return false;
|
|
1526
|
+
const op = surfaceOpOf(event);
|
|
1527
|
+
return op !== void 0 && op !== "append" && op.startSeq <= marker.seq && op.endSeq >= marker.seq;
|
|
1528
|
+
});
|
|
1529
|
+
}
|
|
1530
|
+
function activeRollbackWindow(events, surfaceNodes) {
|
|
1531
|
+
const onSurface = surfaceNodes === void 0 ? void 0 : new Set(surfaceNodes.map((node) => Number(node)));
|
|
1532
|
+
let tipTurn;
|
|
1533
|
+
let continueAfterSeq;
|
|
1534
|
+
for (const event of events) {
|
|
1535
|
+
if (!isRollbackMarker(event) || !markerStillActive(event, events)) continue;
|
|
1536
|
+
if (onSurface !== void 0 && !onSurface.has(Number(event.seq))) continue;
|
|
1537
|
+
const turn = turnFromRollbackId(event.data.id);
|
|
1538
|
+
if (turn === void 0) continue;
|
|
1539
|
+
tipTurn = tipTurn === void 0 ? turn : Math.min(tipTurn, turn);
|
|
1540
|
+
continueAfterSeq = continueAfterSeq === void 0 ? Number(event.seq) : Math.max(continueAfterSeq, Number(event.seq));
|
|
1541
|
+
}
|
|
1542
|
+
if (tipTurn === void 0 || continueAfterSeq === void 0) return void 0;
|
|
1543
|
+
return { tipTurn, hideTurnsFrom: tipTurn, continueAfterSeq };
|
|
1544
|
+
}
|
|
1545
|
+
function isRolledBackCheckpoint(turn, atSeq, window) {
|
|
1546
|
+
if (window === void 0 || turn < window.hideTurnsFrom) return false;
|
|
1547
|
+
return atSeq < window.continueAfterSeq;
|
|
1548
|
+
}
|
|
1549
|
+
function surfaceMessageId2(event) {
|
|
1097
1550
|
switch (event.type) {
|
|
1098
1551
|
case "user/message":
|
|
1099
1552
|
return event.data.id;
|
|
@@ -1107,16 +1560,16 @@ function surfaceMessageId(event) {
|
|
|
1107
1560
|
}
|
|
1108
1561
|
}
|
|
1109
1562
|
function isUndoCopy(event) {
|
|
1110
|
-
const id =
|
|
1563
|
+
const id = surfaceMessageId2(event);
|
|
1111
1564
|
return id !== null && isUndoId(id);
|
|
1112
1565
|
}
|
|
1113
1566
|
function isUndoCopyAt(event, expected) {
|
|
1114
|
-
const id =
|
|
1567
|
+
const id = surfaceMessageId2(event);
|
|
1115
1568
|
return id === expected || (id?.startsWith(`${expected}:`) ?? false);
|
|
1116
1569
|
}
|
|
1117
1570
|
function logicalSeq(event) {
|
|
1118
1571
|
if (isUndoCopy(event)) {
|
|
1119
|
-
const match =
|
|
1572
|
+
const match = surfaceMessageId2(event)?.match(/:(\d+)(?::dsh-(?:agent|composer)-enhancer:rollback:.*)?$/);
|
|
1120
1573
|
if (match !== null && match !== void 0) return SessionSeq(Number(match[1]));
|
|
1121
1574
|
}
|
|
1122
1575
|
return event.seq;
|
|
@@ -1130,6 +1583,12 @@ function isProtectedSystemMessage(event) {
|
|
|
1130
1583
|
function rollbackSurfaceNodes(events, candidates) {
|
|
1131
1584
|
return candidates.filter((node) => !isProtectedSystemMessage(events[node]));
|
|
1132
1585
|
}
|
|
1586
|
+
function isAlreadyRestoredRollback(events, nodes, turn, surfaceNodes) {
|
|
1587
|
+
if (nodes.length === 0) return false;
|
|
1588
|
+
if (!nodes.every((node) => isRollbackMarker(events[node]))) return false;
|
|
1589
|
+
const window = activeRollbackWindow(events, surfaceNodes);
|
|
1590
|
+
return window !== void 0 && turn === window.tipTurn;
|
|
1591
|
+
}
|
|
1133
1592
|
function abortError() {
|
|
1134
1593
|
return new DOMException("Checkpoint rollback was cancelled", "AbortError");
|
|
1135
1594
|
}
|
|
@@ -1155,22 +1614,58 @@ function scopeOf(request) {
|
|
|
1155
1614
|
function directionOf(operation) {
|
|
1156
1615
|
return operation === "rollback" ? "rollback" : "undo";
|
|
1157
1616
|
}
|
|
1617
|
+
function turnOwningSeq(events, seq) {
|
|
1618
|
+
let current;
|
|
1619
|
+
for (const event of events) {
|
|
1620
|
+
if (Number(event.seq) > seq) break;
|
|
1621
|
+
if (event.type === "turn/start") current = event.data.turn;
|
|
1622
|
+
}
|
|
1623
|
+
return current;
|
|
1624
|
+
}
|
|
1625
|
+
function logicalTurnOwning(events, event) {
|
|
1626
|
+
return turnOwningSeq(events, Number(logicalSeq(event)));
|
|
1627
|
+
}
|
|
1158
1628
|
function sourceEvents(events, marker) {
|
|
1159
|
-
if (marker.surfaceOp === "append") {
|
|
1160
|
-
if (marker.sourceEventSeqs?.length !== 1) return null;
|
|
1629
|
+
if (marker.surfaceOp === "append" && marker.sourceEventSeqs?.length === 1) {
|
|
1161
1630
|
const original = events[marker.sourceEventSeqs[0]];
|
|
1162
|
-
|
|
1631
|
+
if (isRollbackMarker(original)) return sourceEvents(events, original);
|
|
1163
1632
|
}
|
|
1164
1633
|
if (marker.sourceEventSeqs === void 0 || marker.sourceEventSeqs.length === 0) return null;
|
|
1165
1634
|
const sources = [];
|
|
1166
1635
|
for (const seq of marker.sourceEventSeqs) {
|
|
1167
1636
|
const event = events[seq];
|
|
1168
|
-
if (event === void 0
|
|
1637
|
+
if (event === void 0) return null;
|
|
1638
|
+
if (isRollbackMarker(event)) {
|
|
1639
|
+
const nested = sourceEvents(events, event);
|
|
1640
|
+
if (nested === null) return null;
|
|
1641
|
+
sources.push(...nested);
|
|
1642
|
+
continue;
|
|
1643
|
+
}
|
|
1644
|
+
if (!surfaceEventTypes.has(event.type)) return null;
|
|
1169
1645
|
sources.push(event);
|
|
1170
1646
|
}
|
|
1171
1647
|
if (sources[0]?.type !== "user/message") return null;
|
|
1172
1648
|
return sources;
|
|
1173
1649
|
}
|
|
1650
|
+
function peelUndoSources(events, sources, tipTurn) {
|
|
1651
|
+
const reappear = sources.filter((event) => logicalTurnOwning(events, event) === tipTurn);
|
|
1652
|
+
const stillWithdraw = sources.filter((event) => {
|
|
1653
|
+
const owned = logicalTurnOwning(events, event);
|
|
1654
|
+
return owned !== void 0 && owned !== tipTurn;
|
|
1655
|
+
});
|
|
1656
|
+
if (reappear.length === 0 || stillWithdraw.length === 0) {
|
|
1657
|
+
return { undoSources: sources, nextTip: void 0 };
|
|
1658
|
+
}
|
|
1659
|
+
const nextTipTurn = stillWithdraw.reduce((min, event) => {
|
|
1660
|
+
const owned = logicalTurnOwning(events, event);
|
|
1661
|
+
return owned === void 0 ? min : Math.min(min, owned);
|
|
1662
|
+
}, Number.POSITIVE_INFINITY);
|
|
1663
|
+
if (!Number.isFinite(nextTipTurn)) return { undoSources: sources, nextTip: void 0 };
|
|
1664
|
+
return {
|
|
1665
|
+
undoSources: reappear,
|
|
1666
|
+
nextTip: { turn: nextTipTurn, sources: stillWithdraw }
|
|
1667
|
+
};
|
|
1668
|
+
}
|
|
1174
1669
|
function nextTurnNumber(events) {
|
|
1175
1670
|
let max = 0;
|
|
1176
1671
|
for (const event of events) {
|
|
@@ -1186,8 +1681,56 @@ function undoTurnAfterMarker(events, markerSeq) {
|
|
|
1186
1681
|
}
|
|
1187
1682
|
throw new Error("Partial undo is missing its turn/start");
|
|
1188
1683
|
}
|
|
1189
|
-
function
|
|
1190
|
-
|
|
1684
|
+
function tipRollbackMarker(events, nodes, turn) {
|
|
1685
|
+
let tip;
|
|
1686
|
+
for (const node of nodes) {
|
|
1687
|
+
const event = events[node];
|
|
1688
|
+
if (!isRollbackMarker(event, turn) || !markerStillActive(event, events)) continue;
|
|
1689
|
+
tip = event;
|
|
1690
|
+
}
|
|
1691
|
+
return tip;
|
|
1692
|
+
}
|
|
1693
|
+
function resolveUndoTipMarker(events, nodes) {
|
|
1694
|
+
const onSurface = tipRollbackMarker(events, nodes);
|
|
1695
|
+
if (onSurface !== void 0) return onSurface;
|
|
1696
|
+
let tip;
|
|
1697
|
+
for (const event of events) {
|
|
1698
|
+
if (!isRollbackMarker(event) || !markerStillActive(event, events)) continue;
|
|
1699
|
+
tip = event;
|
|
1700
|
+
}
|
|
1701
|
+
if (tip !== void 0 && nodes.some((node) => Number(node) === Number(tip.seq))) return tip;
|
|
1702
|
+
let surfaceTip;
|
|
1703
|
+
for (const node of nodes) {
|
|
1704
|
+
const event = events[node];
|
|
1705
|
+
if (isRollbackMarker(event)) surfaceTip = event;
|
|
1706
|
+
}
|
|
1707
|
+
return surfaceTip;
|
|
1708
|
+
}
|
|
1709
|
+
function undoReplaceEndSeq(events, nodes, markerSeq) {
|
|
1710
|
+
const markerIndex = nodes.findIndex((node) => Number(node) === Number(markerSeq));
|
|
1711
|
+
if (markerIndex < 0) return markerSeq;
|
|
1712
|
+
let end = markerSeq;
|
|
1713
|
+
for (let index = markerIndex + 1; index < nodes.length; index += 1) {
|
|
1714
|
+
const event = events[nodes[index]];
|
|
1715
|
+
if (ignoreOnUndoKeepPrefix(event)) continue;
|
|
1716
|
+
end = SessionSeq(nodes[index]);
|
|
1717
|
+
}
|
|
1718
|
+
return end;
|
|
1719
|
+
}
|
|
1720
|
+
function undoShadowedSourceSeqs(nodes, markerSeq, replaceEndSeq, sourceSeq) {
|
|
1721
|
+
const seqs = [];
|
|
1722
|
+
let inRange = false;
|
|
1723
|
+
for (const node of nodes) {
|
|
1724
|
+
if (Number(node) === Number(markerSeq)) inRange = true;
|
|
1725
|
+
if (!inRange) continue;
|
|
1726
|
+
seqs.push(SessionSeq(node));
|
|
1727
|
+
if (Number(node) === Number(replaceEndSeq)) break;
|
|
1728
|
+
}
|
|
1729
|
+
if (!seqs.some((seq) => Number(seq) === Number(sourceSeq))) seqs.push(sourceSeq);
|
|
1730
|
+
return seqs;
|
|
1731
|
+
}
|
|
1732
|
+
function ignoreOnUndoKeepPrefix(event) {
|
|
1733
|
+
return isProtectedSystemMessage(event) || event?.type === "developer/message";
|
|
1191
1734
|
}
|
|
1192
1735
|
function toolCallsOf(event) {
|
|
1193
1736
|
const calls = [];
|
|
@@ -1280,19 +1823,33 @@ function countPartialUndoCopies(events, first, journalId, tip) {
|
|
|
1280
1823
|
}
|
|
1281
1824
|
return completed;
|
|
1282
1825
|
}
|
|
1283
|
-
function appendUndoCopy(session, source, journalId, index,
|
|
1826
|
+
function appendUndoCopy(session, source, journalId, index, tipMarkerSeq, mode, replaceStartSeq, replaceEndSeq, turn, step, openCalls) {
|
|
1284
1827
|
const copyId = MessageId(`${undoCopyId(journalId, index)}:${source.seq}`);
|
|
1285
1828
|
const id = isRollbackMarker(source) ? MessageId(`${copyId}:${source.data.id}`) : copyId;
|
|
1286
1829
|
if (source.type === "user/message") {
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1830
|
+
if (mode === "append" || index > 0) {
|
|
1831
|
+
return session.append("user/message", { ...source.data, id }, {
|
|
1832
|
+
surfaceOp: "append",
|
|
1833
|
+
sourceEventSeqs: [source.seq]
|
|
1834
|
+
});
|
|
1835
|
+
}
|
|
1836
|
+
const shadowed = undoShadowedSourceSeqs(
|
|
1837
|
+
session.surface.nodes,
|
|
1838
|
+
replaceStartSeq,
|
|
1839
|
+
replaceEndSeq,
|
|
1840
|
+
source.seq
|
|
1841
|
+
);
|
|
1842
|
+
if (!shadowed.some((seq) => Number(seq) === Number(tipMarkerSeq))) {
|
|
1843
|
+
shadowed.unshift(tipMarkerSeq);
|
|
1844
|
+
}
|
|
1845
|
+
return session.append("user/message", { ...source.data, id }, {
|
|
1846
|
+
surfaceOp: { op: "replace", startSeq: replaceStartSeq, endSeq: replaceEndSeq },
|
|
1847
|
+
sourceEventSeqs: shadowed
|
|
1293
1848
|
});
|
|
1294
1849
|
}
|
|
1295
|
-
if (index === 0
|
|
1850
|
+
if (index === 0 && mode === "replace") {
|
|
1851
|
+
throw new Error("The first restored surface event must be a user message");
|
|
1852
|
+
}
|
|
1296
1853
|
switch (source.type) {
|
|
1297
1854
|
case "assistant/message": {
|
|
1298
1855
|
const event = session.append("assistant/message", {
|
|
@@ -1344,6 +1901,9 @@ var CheckpointRollbackService = class {
|
|
|
1344
1901
|
execute(request, signal) {
|
|
1345
1902
|
return this.track(this.runExecute(request, signal));
|
|
1346
1903
|
}
|
|
1904
|
+
summaries(request, signal) {
|
|
1905
|
+
return this.track(this.runSummaries(request, signal));
|
|
1906
|
+
}
|
|
1347
1907
|
recover() {
|
|
1348
1908
|
if (this.recovery !== void 0) return this.recovery;
|
|
1349
1909
|
const operation = this.track(this.runRecovery());
|
|
@@ -1401,6 +1961,62 @@ var CheckpointRollbackService = class {
|
|
|
1401
1961
|
linked.cleanup();
|
|
1402
1962
|
}
|
|
1403
1963
|
}
|
|
1964
|
+
async runSummaries(request, callerSignal) {
|
|
1965
|
+
const linked = this.linkedSignal([callerSignal]);
|
|
1966
|
+
try {
|
|
1967
|
+
linked.signal.throwIfAborted();
|
|
1968
|
+
if (this.options.isEnabled?.() === false) {
|
|
1969
|
+
return {
|
|
1970
|
+
sessionId: request.sessionId,
|
|
1971
|
+
activity: { turns: 0, steps: 0, checkpoints: 0, liveCheckpoints: 0 },
|
|
1972
|
+
turns: []
|
|
1973
|
+
};
|
|
1974
|
+
}
|
|
1975
|
+
await this.options.awaitCaptures?.();
|
|
1976
|
+
linked.signal.throwIfAborted();
|
|
1977
|
+
const checkpoints = await this.options.store.list(request.sessionId);
|
|
1978
|
+
const adapter = this.options.resolveSession(request.sessionId);
|
|
1979
|
+
const events = adapter?.readEvents() ?? [];
|
|
1980
|
+
const surfaceNodes = adapter?.session.surface.nodes;
|
|
1981
|
+
const window = events.length === 0 ? void 0 : activeRollbackWindow(events, surfaceNodes);
|
|
1982
|
+
const shells = undoShellRanges(events);
|
|
1983
|
+
const kept = events.length === 0 ? checkpoints : checkpoints.filter((checkpoint) => !isUndoShellCheckpoint(checkpoint.atSeq, shells));
|
|
1984
|
+
if (kept.length !== checkpoints.length) {
|
|
1985
|
+
await this.options.store.replace(request.sessionId, kept);
|
|
1986
|
+
}
|
|
1987
|
+
void this.options.store.purgeSettledJournals().catch(() => void 0);
|
|
1988
|
+
const byTurn = /* @__PURE__ */ new Map();
|
|
1989
|
+
for (const checkpoint of kept) {
|
|
1990
|
+
const recoveredPrompt = checkpoint.prompt.trim() === "" ? recoverTurnPrompt(events, checkpoint.turn) : "";
|
|
1991
|
+
const rolledBack = isRolledBackCheckpoint(checkpoint.turn, checkpoint.atSeq, window);
|
|
1992
|
+
byTurn.set(
|
|
1993
|
+
checkpoint.turn,
|
|
1994
|
+
toCheckpointTurnSummary(checkpoint, {
|
|
1995
|
+
rolledBack,
|
|
1996
|
+
tip: window !== void 0 && checkpoint.turn === window.tipTurn,
|
|
1997
|
+
recoveredPrompt
|
|
1998
|
+
})
|
|
1999
|
+
);
|
|
2000
|
+
}
|
|
2001
|
+
const turns = [...byTurn.values()].sort((left, right) => left.atSeq - right.atSeq || left.turn - right.turn || left.createdAt - right.createdAt);
|
|
2002
|
+
const liveCheckpoints = turns.filter((turn) => !turn.rolledBack).length;
|
|
2003
|
+
const activity = liveActivityStats(events, {
|
|
2004
|
+
hideTurnsFrom: window?.hideTurnsFrom,
|
|
2005
|
+
continueAfterSeq: window?.continueAfterSeq,
|
|
2006
|
+
checkpointCount: turns.length,
|
|
2007
|
+
liveCheckpointCount: liveCheckpoints
|
|
2008
|
+
});
|
|
2009
|
+
return {
|
|
2010
|
+
sessionId: request.sessionId,
|
|
2011
|
+
activity,
|
|
2012
|
+
turns
|
|
2013
|
+
};
|
|
2014
|
+
} catch (error) {
|
|
2015
|
+
throw this.sanitize(error, linked.signal);
|
|
2016
|
+
} finally {
|
|
2017
|
+
linked.cleanup();
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
1404
2020
|
async runExecute(request, callerSignal) {
|
|
1405
2021
|
const linked = this.linkedSignal([callerSignal]);
|
|
1406
2022
|
try {
|
|
@@ -1430,6 +2046,15 @@ var CheckpointRollbackService = class {
|
|
|
1430
2046
|
const journalId = (this.options.createId ?? randomUUID3)();
|
|
1431
2047
|
const files = this.files(adapter, checkpoint, journalId);
|
|
1432
2048
|
const filesToRestore = scope === "conversation" ? [] : checkpoint.files;
|
|
2049
|
+
const surface = current.surface;
|
|
2050
|
+
if (operation === "rollback" && surface.operation === "rollback" && surface.alreadyRestored && filesToRestore.length === 0) {
|
|
2051
|
+
const draftPrompt2 = checkpoint.prompt.trim() !== "" ? checkpoint.prompt : recoverTurnPrompt(adapter.readEvents(), request.turn);
|
|
2052
|
+
return {
|
|
2053
|
+
sessionId: request.sessionId,
|
|
2054
|
+
turn: request.turn,
|
|
2055
|
+
draft: draftPrompt2
|
|
2056
|
+
};
|
|
2057
|
+
}
|
|
1433
2058
|
await files.runTransaction(filesToRestore, async () => {
|
|
1434
2059
|
if (maintenance.signal.aborted) return { appended: false, synchronized: false };
|
|
1435
2060
|
const latest = this.options.resolveSession(request.sessionId);
|
|
@@ -1438,7 +2063,7 @@ var CheckpointRollbackService = class {
|
|
|
1438
2063
|
}
|
|
1439
2064
|
const restored = await this.appendAndSynchronize(
|
|
1440
2065
|
adapter,
|
|
1441
|
-
|
|
2066
|
+
surface,
|
|
1442
2067
|
journalId,
|
|
1443
2068
|
scope,
|
|
1444
2069
|
maintenance.signal
|
|
@@ -1446,10 +2071,11 @@ var CheckpointRollbackService = class {
|
|
|
1446
2071
|
const appended = restored.appended && this.appendOccurred(adapter, journalId);
|
|
1447
2072
|
return { appended, synchronized: appended && restored.synchronized };
|
|
1448
2073
|
}, directionOf(operation));
|
|
2074
|
+
const draftPrompt = checkpoint.prompt.trim() !== "" ? checkpoint.prompt : recoverTurnPrompt(adapter.readEvents(), request.turn);
|
|
1449
2075
|
return {
|
|
1450
2076
|
sessionId: request.sessionId,
|
|
1451
2077
|
turn: request.turn,
|
|
1452
|
-
draft: operation === "rollback" ?
|
|
2078
|
+
draft: operation === "rollback" ? draftPrompt : ""
|
|
1453
2079
|
};
|
|
1454
2080
|
} catch (error) {
|
|
1455
2081
|
throw this.sanitize(error, maintenance.signal);
|
|
@@ -1473,7 +2099,23 @@ var CheckpointRollbackService = class {
|
|
|
1473
2099
|
async appendAndSynchronize(adapter, surface, journalId, scope, signal) {
|
|
1474
2100
|
try {
|
|
1475
2101
|
if (surface.operation === "rollback") this.appendRollback(adapter, surface, journalId, scope);
|
|
1476
|
-
else
|
|
2102
|
+
else {
|
|
2103
|
+
this.appendUndo(
|
|
2104
|
+
adapter.session,
|
|
2105
|
+
surface.marker,
|
|
2106
|
+
surface.sources,
|
|
2107
|
+
journalId,
|
|
2108
|
+
surface.mode,
|
|
2109
|
+
surface.replaceStartSeq,
|
|
2110
|
+
surface.replaceEndSeq
|
|
2111
|
+
);
|
|
2112
|
+
if (surface.nextTip !== void 0 && surface.nextTip.sources.length > 0) {
|
|
2113
|
+
this.appendRollbackNotice(adapter, surface.nextTip.turn, journalId, scopeOfMarker(surface.marker), {
|
|
2114
|
+
surfaceOp: "append",
|
|
2115
|
+
sourceEventSeqs: surface.nextTip.sources.map((event) => SessionSeq(event.seq))
|
|
2116
|
+
});
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
1477
2119
|
} catch {
|
|
1478
2120
|
return { appended: this.appendOccurred(adapter, journalId), synchronized: false };
|
|
1479
2121
|
}
|
|
@@ -1485,7 +2127,56 @@ var CheckpointRollbackService = class {
|
|
|
1485
2127
|
}
|
|
1486
2128
|
}
|
|
1487
2129
|
appendRollback(adapter, surface, journalId, scope) {
|
|
1488
|
-
const
|
|
2130
|
+
const forward = surface.forwardFromTip;
|
|
2131
|
+
if (forward !== void 0) {
|
|
2132
|
+
if (forward.stillWithdraw.length === 0) {
|
|
2133
|
+
this.appendUndo(
|
|
2134
|
+
adapter.session,
|
|
2135
|
+
forward.marker,
|
|
2136
|
+
forward.reappear,
|
|
2137
|
+
journalId,
|
|
2138
|
+
"replace",
|
|
2139
|
+
SessionSeq(forward.marker.seq),
|
|
2140
|
+
SessionSeq(forward.marker.seq)
|
|
2141
|
+
);
|
|
2142
|
+
return;
|
|
2143
|
+
}
|
|
2144
|
+
if (forward.reappear.length === 0) {
|
|
2145
|
+
this.appendRollbackNotice(adapter, surface.turn, journalId, scope, {
|
|
2146
|
+
surfaceOp: {
|
|
2147
|
+
op: "replace",
|
|
2148
|
+
startSeq: SessionSeq(forward.marker.seq),
|
|
2149
|
+
endSeq: SessionSeq(forward.marker.seq)
|
|
2150
|
+
},
|
|
2151
|
+
sourceEventSeqs: forward.stillWithdraw.map((event) => SessionSeq(event.seq))
|
|
2152
|
+
});
|
|
2153
|
+
return;
|
|
2154
|
+
}
|
|
2155
|
+
this.appendUndo(
|
|
2156
|
+
adapter.session,
|
|
2157
|
+
forward.marker,
|
|
2158
|
+
forward.reappear,
|
|
2159
|
+
journalId,
|
|
2160
|
+
"replace",
|
|
2161
|
+
SessionSeq(forward.marker.seq),
|
|
2162
|
+
SessionSeq(forward.marker.seq)
|
|
2163
|
+
);
|
|
2164
|
+
this.appendRollbackNotice(adapter, surface.turn, journalId, scope, {
|
|
2165
|
+
surfaceOp: "append",
|
|
2166
|
+
sourceEventSeqs: forward.stillWithdraw.map((event) => SessionSeq(event.seq))
|
|
2167
|
+
});
|
|
2168
|
+
return;
|
|
2169
|
+
}
|
|
2170
|
+
this.appendRollbackNotice(adapter, surface.turn, journalId, scope, {
|
|
2171
|
+
surfaceOp: {
|
|
2172
|
+
op: "replace",
|
|
2173
|
+
startSeq: surface.nodes[0],
|
|
2174
|
+
endSeq: surface.nodes[surface.nodes.length - 1]
|
|
2175
|
+
},
|
|
2176
|
+
sourceEventSeqs: [...surface.nodes]
|
|
2177
|
+
});
|
|
2178
|
+
}
|
|
2179
|
+
appendRollbackNotice(adapter, checkpointTurn, journalId, scope, append) {
|
|
1489
2180
|
const conversationOnly = scope === "conversation";
|
|
1490
2181
|
const summary = conversationOnly ? `Conversation rolled back before turn ${checkpointTurn}` : `Conversation and tracked files rolled back before turn ${checkpointTurn}`;
|
|
1491
2182
|
const detail = conversationOnly ? `The user rolled back the conversation to before turn ${checkpointTurn}. Later events remain in the append-only log but are no longer active model context. Tracked files were not restored.` : `The user rolled back the conversation and tracked files to before turn ${checkpointTurn}. Later events remain in the append-only log but are no longer active model context. Re-read tracked files before relying on their contents.`;
|
|
@@ -1495,15 +2186,11 @@ var CheckpointRollbackService = class {
|
|
|
1495
2186
|
content: [{ type: "text", text: detail }],
|
|
1496
2187
|
source: { kind: "checkpoint-rollback", form: "notice", summary }
|
|
1497
2188
|
}, {
|
|
1498
|
-
surfaceOp:
|
|
1499
|
-
|
|
1500
|
-
startSeq: surface.nodes[0],
|
|
1501
|
-
endSeq: surface.nodes[surface.nodes.length - 1]
|
|
1502
|
-
},
|
|
1503
|
-
sourceEventSeqs: [...surface.nodes]
|
|
2189
|
+
surfaceOp: append.surfaceOp,
|
|
2190
|
+
sourceEventSeqs: [...append.sourceEventSeqs]
|
|
1504
2191
|
});
|
|
1505
2192
|
}
|
|
1506
|
-
appendUndo(session, marker, sources, journalId, start = 0, openCalls = /* @__PURE__ */ new Map()) {
|
|
2193
|
+
appendUndo(session, marker, sources, journalId, mode, replaceStartSeq, replaceEndSeq, start = 0, openCalls = /* @__PURE__ */ new Map()) {
|
|
1507
2194
|
const events = session.snapshotEvents();
|
|
1508
2195
|
const turn = start === 0 ? nextTurnNumber(events) : undoTurnAfterMarker(events, marker.seq);
|
|
1509
2196
|
const step = 1;
|
|
@@ -1512,7 +2199,19 @@ var CheckpointRollbackService = class {
|
|
|
1512
2199
|
session.append("step/start", { turn, step });
|
|
1513
2200
|
}
|
|
1514
2201
|
for (let index = start; index < sources.length; index += 1) {
|
|
1515
|
-
appendUndoCopy(
|
|
2202
|
+
appendUndoCopy(
|
|
2203
|
+
session,
|
|
2204
|
+
sources[index],
|
|
2205
|
+
journalId,
|
|
2206
|
+
index,
|
|
2207
|
+
marker.seq,
|
|
2208
|
+
mode,
|
|
2209
|
+
replaceStartSeq,
|
|
2210
|
+
replaceEndSeq,
|
|
2211
|
+
turn,
|
|
2212
|
+
step,
|
|
2213
|
+
openCalls
|
|
2214
|
+
);
|
|
1516
2215
|
}
|
|
1517
2216
|
settleOpenUndoToolCalls(session, journalId, turn, step, openCalls);
|
|
1518
2217
|
session.append("step/end", { turn, step });
|
|
@@ -1562,13 +2261,18 @@ var CheckpointRollbackService = class {
|
|
|
1562
2261
|
const events = adapter.readEvents();
|
|
1563
2262
|
const first = events.find((event) => isUndoCopyAt(event, undoCopyId(journalId, 0)));
|
|
1564
2263
|
if (first === void 0) return;
|
|
1565
|
-
if (first.type !== "user/message"
|
|
2264
|
+
if (first.type !== "user/message") {
|
|
1566
2265
|
throw new CheckpointRollbackError("ROLLBACK_RECOVERY_FAILED");
|
|
1567
2266
|
}
|
|
1568
|
-
const
|
|
2267
|
+
const appendOnly = first.surfaceOp === "append";
|
|
2268
|
+
const hinted = first.sourceEventSeqs?.map((seq) => events[seq]).find((event) => isRollbackMarker(event));
|
|
2269
|
+
const marker = !appendOnly && first.surfaceOp !== void 0 && first.surfaceOp !== "append" && isRollbackMarker(events[first.surfaceOp.startSeq]) ? events[first.surfaceOp.startSeq] : hinted;
|
|
1569
2270
|
if (!isRollbackMarker(marker)) throw new CheckpointRollbackError("ROLLBACK_RECOVERY_FAILED");
|
|
1570
2271
|
const sources = sourceEvents(events, marker);
|
|
1571
2272
|
if (sources === null) throw new CheckpointRollbackError("ROLLBACK_RECOVERY_FAILED");
|
|
2273
|
+
const tipTurn = turnFromRollbackId(marker.data.id);
|
|
2274
|
+
if (tipTurn === void 0) throw new CheckpointRollbackError("ROLLBACK_RECOVERY_FAILED");
|
|
2275
|
+
const peeled = peelUndoSources(events, sources, tipTurn);
|
|
1572
2276
|
const tip = Number(adapter.session.seq) - 1;
|
|
1573
2277
|
const completed = countPartialUndoCopies(events, first, journalId, tip);
|
|
1574
2278
|
const openCalls = /* @__PURE__ */ new Map();
|
|
@@ -1583,14 +2287,37 @@ var CheckpointRollbackService = class {
|
|
|
1583
2287
|
step,
|
|
1584
2288
|
openCalls
|
|
1585
2289
|
);
|
|
1586
|
-
|
|
2290
|
+
const replaceStart = appendOnly || first.surfaceOp === "append" || first.surfaceOp === void 0 ? marker.seq : SessionSeq(first.surfaceOp.startSeq);
|
|
2291
|
+
const replaceEnd = appendOnly || first.surfaceOp === "append" || first.surfaceOp === void 0 ? marker.seq : SessionSeq(first.surfaceOp.endSeq);
|
|
2292
|
+
this.appendUndo(
|
|
2293
|
+
adapter.session,
|
|
2294
|
+
marker,
|
|
2295
|
+
peeled.undoSources,
|
|
2296
|
+
journalId,
|
|
2297
|
+
appendOnly ? "append" : "replace",
|
|
2298
|
+
replaceStart,
|
|
2299
|
+
replaceEnd,
|
|
2300
|
+
completed,
|
|
2301
|
+
openCalls
|
|
2302
|
+
);
|
|
2303
|
+
if (peeled.nextTip !== void 0 && peeled.nextTip.sources.length > 0) {
|
|
2304
|
+
const live = activeRollbackWindow(adapter.readEvents(), adapter.session.surface.nodes);
|
|
2305
|
+
if (live?.tipTurn !== peeled.nextTip.turn) {
|
|
2306
|
+
this.appendRollbackNotice(adapter, peeled.nextTip.turn, journalId, scopeOfMarker(marker), {
|
|
2307
|
+
surfaceOp: "append",
|
|
2308
|
+
sourceEventSeqs: peeled.nextTip.sources.map((event) => SessionSeq(event.seq))
|
|
2309
|
+
});
|
|
2310
|
+
}
|
|
2311
|
+
}
|
|
1587
2312
|
}
|
|
1588
2313
|
async evaluate(request, options = {}) {
|
|
1589
2314
|
const operation = operationOf(request);
|
|
1590
2315
|
await this.options.awaitCaptures?.();
|
|
1591
|
-
const checkpoints = await this.options.store.list(request.sessionId);
|
|
1592
|
-
let stored = checkpoints.find((checkpoint) => checkpoint.turn === request.turn) ?? null;
|
|
1593
2316
|
const adapter = this.options.resolveSession(request.sessionId) ?? null;
|
|
2317
|
+
const events = adapter?.readEvents() ?? [];
|
|
2318
|
+
const shells = undoShellRanges(events);
|
|
2319
|
+
const checkpoints = await this.options.store.list(request.sessionId);
|
|
2320
|
+
let stored = checkpoints.find((checkpoint) => checkpoint.turn === request.turn && !isUndoShellCheckpoint(checkpoint.atSeq, shells)) ?? null;
|
|
1594
2321
|
if (stored === null && adapter !== null && operation === "rollback") {
|
|
1595
2322
|
stored = synthesizeCheckpoint({
|
|
1596
2323
|
sessionId: request.sessionId,
|
|
@@ -1628,46 +2355,157 @@ var CheckpointRollbackService = class {
|
|
|
1628
2355
|
let messages = [];
|
|
1629
2356
|
let surface = null;
|
|
1630
2357
|
if (stored !== null && adapter !== null && stored.atSeq >= 0) {
|
|
1631
|
-
const
|
|
1632
|
-
const cut = resolveRollbackCut(
|
|
2358
|
+
const events2 = adapter.readEvents();
|
|
2359
|
+
const cut = resolveRollbackCut(events2, stored.turn, stored.atSeq);
|
|
1633
2360
|
if (cut === null) {
|
|
1634
2361
|
unavailable.push("unknown-surface");
|
|
1635
2362
|
} else if (operation === "rollback") {
|
|
1636
|
-
if (
|
|
2363
|
+
if (events2.some((event) => Number(event.seq) > cut.cutSeq && typeof event.surfaceOp === "object" && !isOwnReplacement(event))) {
|
|
1637
2364
|
unavailable.push("compacted-surface");
|
|
1638
2365
|
}
|
|
1639
|
-
const
|
|
1640
|
-
const
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
2366
|
+
const surfaceNodes = adapter.session.surface.nodes;
|
|
2367
|
+
const tipWindow2 = activeRollbackWindow(events2, surfaceNodes);
|
|
2368
|
+
if (tipWindow2 !== void 0 && stored.turn > tipWindow2.tipTurn) {
|
|
2369
|
+
const marker = resolveUndoTipMarker(events2, surfaceNodes);
|
|
2370
|
+
const sources = marker === void 0 ? null : sourceEvents(events2, marker);
|
|
2371
|
+
if (marker === void 0 || sources === null) {
|
|
2372
|
+
unavailable.push("unknown-surface");
|
|
2373
|
+
} else {
|
|
2374
|
+
const reappear = sources.filter((event) => Number(event.seq) <= cut.cutSeq);
|
|
2375
|
+
const stillWithdraw = sources.filter((event) => Number(event.seq) > cut.cutSeq);
|
|
2376
|
+
messages = reappear.map((event) => ({
|
|
2377
|
+
seq: event.seq,
|
|
2378
|
+
type: event.type,
|
|
2379
|
+
text: textOf(event)
|
|
2380
|
+
}));
|
|
2381
|
+
surface = {
|
|
2382
|
+
operation,
|
|
2383
|
+
turn: stored.turn,
|
|
2384
|
+
nodes: [SessionSeq(marker.seq)],
|
|
2385
|
+
alreadyRestored: false,
|
|
2386
|
+
forwardFromTip: { marker, reappear, stillWithdraw }
|
|
2387
|
+
};
|
|
2388
|
+
}
|
|
1645
2389
|
} else {
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
2390
|
+
const fromSurface = adapter.session.surface.nodes.filter((node) => events2[node] !== void 0 && Number(logicalSeq(events2[node])) > cut.cutSeq);
|
|
2391
|
+
const fromLog = events2.filter((event) => Number(event.seq) > cut.cutSeq && surfaceEventTypes.has(event.type)).map((event) => SessionSeq(event.seq));
|
|
2392
|
+
const candidates = fromSurface.length > 0 && fromSurface.every((node) => surfaceEventTypes.has(events2[node].type)) ? fromSurface.map((node) => SessionSeq(node)) : fromLog;
|
|
2393
|
+
const nodes = rollbackSurfaceNodes(events2, candidates);
|
|
2394
|
+
if (nodes.length === 0) {
|
|
2395
|
+
unavailable.push("already-restored");
|
|
2396
|
+
surface = { operation, turn: stored.turn, nodes, alreadyRestored: true };
|
|
2397
|
+
messages = [];
|
|
2398
|
+
} else {
|
|
2399
|
+
const alreadyRestored = isAlreadyRestoredRollback(events2, nodes, stored.turn, surfaceNodes);
|
|
2400
|
+
if (alreadyRestored) unavailable.push("already-restored");
|
|
2401
|
+
surface = { operation, turn: stored.turn, nodes, alreadyRestored };
|
|
2402
|
+
messages = alreadyRestored ? [] : nodes.map((node) => ({
|
|
2403
|
+
seq: node,
|
|
2404
|
+
type: events2[node].type,
|
|
2405
|
+
text: textOf(events2[node])
|
|
2406
|
+
}));
|
|
2407
|
+
}
|
|
1652
2408
|
}
|
|
1653
2409
|
} else {
|
|
1654
2410
|
const currentNodes = adapter.session.surface.nodes;
|
|
1655
|
-
const
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
2411
|
+
const tipWindow2 = activeRollbackWindow(events2, currentNodes);
|
|
2412
|
+
let marker = resolveUndoTipMarker(events2, currentNodes);
|
|
2413
|
+
if (marker === void 0 && tipWindow2 !== void 0) {
|
|
2414
|
+
for (let index = events2.length - 1; index >= 0; index -= 1) {
|
|
2415
|
+
const event = events2[index];
|
|
2416
|
+
if (!isRollbackMarker(event) || !markerStillActive(event, events2)) continue;
|
|
2417
|
+
const turn = turnFromRollbackId(event.data.id);
|
|
2418
|
+
if (turn === tipWindow2.tipTurn) {
|
|
2419
|
+
marker = event;
|
|
2420
|
+
break;
|
|
2421
|
+
}
|
|
2422
|
+
}
|
|
2423
|
+
}
|
|
2424
|
+
const tipTurn = marker === void 0 ? void 0 : turnFromRollbackId(marker.data.id);
|
|
2425
|
+
if (marker === void 0 || tipTurn === void 0) {
|
|
1663
2426
|
unavailable.push("session-changed");
|
|
1664
2427
|
} else {
|
|
1665
|
-
|
|
1666
|
-
if (
|
|
1667
|
-
|
|
2428
|
+
let undoStored = tipTurn === stored.turn ? stored : checkpoints.find((item) => item.turn === tipTurn && !isUndoShellCheckpoint(item.atSeq, shells)) ?? null;
|
|
2429
|
+
if (undoStored === null) {
|
|
2430
|
+
undoStored = synthesizeCheckpoint({
|
|
2431
|
+
sessionId: request.sessionId,
|
|
2432
|
+
session: {
|
|
2433
|
+
format: adapter.session.header.version,
|
|
2434
|
+
preset: adapter.session.header.agentPreset ?? null
|
|
2435
|
+
},
|
|
2436
|
+
pluginVersion: this.options.pluginVersion,
|
|
2437
|
+
turn: tipTurn,
|
|
2438
|
+
events: events2,
|
|
2439
|
+
createId: this.options.createId,
|
|
2440
|
+
now: this.options.now
|
|
2441
|
+
});
|
|
2442
|
+
}
|
|
2443
|
+
if (undoStored === null) {
|
|
2444
|
+
unavailable.push("checkpoint-not-found");
|
|
1668
2445
|
} else {
|
|
1669
|
-
|
|
1670
|
-
|
|
2446
|
+
if (tipTurn !== stored.turn) {
|
|
2447
|
+
const drop = /* @__PURE__ */ new Set([
|
|
2448
|
+
"checkpoint-not-found",
|
|
2449
|
+
"incomplete-checkpoint",
|
|
2450
|
+
"prompt-non-text-content",
|
|
2451
|
+
"workspace-capture-failed",
|
|
2452
|
+
"incompatible-session"
|
|
2453
|
+
]);
|
|
2454
|
+
for (let index = unavailable.length - 1; index >= 0; index -= 1) {
|
|
2455
|
+
if (drop.has(unavailable[index])) unavailable.splice(index, 1);
|
|
2456
|
+
}
|
|
2457
|
+
if (undoStored.coverage !== "complete" || undoStored.gaps.length > 0) {
|
|
2458
|
+
unavailable.push("incomplete-checkpoint");
|
|
2459
|
+
for (const gap of undoStored.gaps) {
|
|
2460
|
+
unavailable.push(gap.type === "prompt" ? "prompt-non-text-content" : "workspace-capture-failed");
|
|
2461
|
+
}
|
|
2462
|
+
}
|
|
2463
|
+
if (undoStored.session.format !== adapter.session.header.version) {
|
|
2464
|
+
unavailable.push("incompatible-session");
|
|
2465
|
+
}
|
|
2466
|
+
}
|
|
2467
|
+
stored = undoStored;
|
|
2468
|
+
const sources = sourceEvents(events2, marker);
|
|
2469
|
+
if (sources === null || sources.length === 0) {
|
|
2470
|
+
unavailable.push("unknown-surface");
|
|
2471
|
+
} else {
|
|
2472
|
+
const markerOnSurface = currentNodes.some((node) => Number(node) === Number(marker.seq));
|
|
2473
|
+
let mode = "replace";
|
|
2474
|
+
let replaceStartSeq = marker.seq;
|
|
2475
|
+
let replaceEndSeq = undoReplaceEndSeq(events2, currentNodes, marker.seq);
|
|
2476
|
+
if (!markerOnSurface) {
|
|
2477
|
+
const tipCut = resolveRollbackCut(events2, tipTurn, undoStored.atSeq);
|
|
2478
|
+
const afterCut = tipCut === null ? [] : currentNodes.filter((node) => {
|
|
2479
|
+
const event = events2[node];
|
|
2480
|
+
if (ignoreOnUndoKeepPrefix(event)) return false;
|
|
2481
|
+
return Number(logicalSeq(event)) > tipCut.cutSeq;
|
|
2482
|
+
});
|
|
2483
|
+
if (afterCut.length === 0) {
|
|
2484
|
+
mode = "append";
|
|
2485
|
+
const last = currentNodes[currentNodes.length - 1];
|
|
2486
|
+
replaceStartSeq = last === void 0 ? marker.seq : SessionSeq(last);
|
|
2487
|
+
replaceEndSeq = replaceStartSeq;
|
|
2488
|
+
} else {
|
|
2489
|
+
replaceStartSeq = SessionSeq(afterCut[0]);
|
|
2490
|
+
replaceEndSeq = SessionSeq(afterCut[afterCut.length - 1]);
|
|
2491
|
+
}
|
|
2492
|
+
}
|
|
2493
|
+
const peeled = peelUndoSources(events2, sources, tipTurn);
|
|
2494
|
+
surface = {
|
|
2495
|
+
operation,
|
|
2496
|
+
marker,
|
|
2497
|
+
sources: peeled.undoSources,
|
|
2498
|
+
mode,
|
|
2499
|
+
replaceStartSeq,
|
|
2500
|
+
replaceEndSeq,
|
|
2501
|
+
...peeled.nextTip !== void 0 ? { nextTip: peeled.nextTip } : {}
|
|
2502
|
+
};
|
|
2503
|
+
messages = peeled.undoSources.map((event) => ({
|
|
2504
|
+
seq: event.seq,
|
|
2505
|
+
type: event.type,
|
|
2506
|
+
text: textOf(event)
|
|
2507
|
+
}));
|
|
2508
|
+
}
|
|
1671
2509
|
}
|
|
1672
2510
|
}
|
|
1673
2511
|
}
|
|
@@ -1682,15 +2520,18 @@ var CheckpointRollbackService = class {
|
|
|
1682
2520
|
}
|
|
1683
2521
|
}
|
|
1684
2522
|
const markerScope = surface?.operation === "undo" ? scopeOfMarker(surface.marker) : void 0;
|
|
2523
|
+
const tipWindow = adapter !== null ? activeRollbackWindow(adapter.readEvents(), adapter.session.surface.nodes) : void 0;
|
|
2524
|
+
const previewTurn = surface?.operation === "undo" ? turnFromRollbackId(surface.marker.data.id) ?? request.turn : request.turn;
|
|
1685
2525
|
return {
|
|
1686
2526
|
checkpoint: stored,
|
|
1687
2527
|
adapter,
|
|
1688
2528
|
surface,
|
|
1689
2529
|
preview: {
|
|
1690
2530
|
sessionId: request.sessionId,
|
|
1691
|
-
turn:
|
|
2531
|
+
turn: previewTurn,
|
|
1692
2532
|
...operation === "undo" ? { operation } : {},
|
|
1693
2533
|
...markerScope === void 0 ? {} : { scope: markerScope },
|
|
2534
|
+
...tipWindow === void 0 ? {} : { tipTurn: tipWindow.tipTurn },
|
|
1694
2535
|
messages,
|
|
1695
2536
|
files: stored?.files.map((file) => ({ path: file.path, change: file.change })) ?? [],
|
|
1696
2537
|
conflicts,
|
|
@@ -1752,8 +2593,8 @@ var CheckpointRollbackService = class {
|
|
|
1752
2593
|
|
|
1753
2594
|
// src/host/checkpoint/store.ts
|
|
1754
2595
|
import { createHash as createHash2, randomUUID as randomUUID4 } from "node:crypto";
|
|
1755
|
-
import { chmod as chmod2, mkdir as mkdir2, readdir, readFile as readFile2, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
|
|
1756
|
-
import { basename as basename2, join as
|
|
2596
|
+
import { chmod as chmod2, mkdir as mkdir2, readdir as readdir2, readFile as readFile2, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
|
|
2597
|
+
import { basename as basename2, join as join4 } from "node:path";
|
|
1757
2598
|
import { z } from "zod";
|
|
1758
2599
|
var MAX_CHECKPOINTS = 20;
|
|
1759
2600
|
var checkpointQueues = /* @__PURE__ */ new Map();
|
|
@@ -1854,7 +2695,7 @@ async function removeIfPresent2(path) {
|
|
|
1854
2695
|
}
|
|
1855
2696
|
}
|
|
1856
2697
|
async function writeAtomic2(path, value) {
|
|
1857
|
-
const temporary =
|
|
2698
|
+
const temporary = join4(join4(path, ".."), `.${basename2(path)}.${randomUUID4()}.tmp`);
|
|
1858
2699
|
try {
|
|
1859
2700
|
await writeFile2(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
|
|
1860
2701
|
await rename2(temporary, path);
|
|
@@ -1866,9 +2707,9 @@ async function writeAtomic2(path, value) {
|
|
|
1866
2707
|
var CheckpointStore = class {
|
|
1867
2708
|
constructor(root) {
|
|
1868
2709
|
this.root = root;
|
|
1869
|
-
this.checkpointDirectory =
|
|
1870
|
-
this.journalDirectory =
|
|
1871
|
-
this.rootKey =
|
|
2710
|
+
this.checkpointDirectory = join4(root, "checkpoints");
|
|
2711
|
+
this.journalDirectory = join4(root, "journals");
|
|
2712
|
+
this.rootKey = join4(root, ".");
|
|
1872
2713
|
}
|
|
1873
2714
|
root;
|
|
1874
2715
|
checkpointDirectory;
|
|
@@ -1905,6 +2746,59 @@ var CheckpointStore = class {
|
|
|
1905
2746
|
if (!parsed.success) throw new CheckpointStoreError("INVALID_STORE");
|
|
1906
2747
|
return parsed.data.checkpoints;
|
|
1907
2748
|
}
|
|
2749
|
+
/**
|
|
2750
|
+
* Replace the full per-session checkpoint list (used to drop undo-shell junk).
|
|
2751
|
+
* Empty list removes the session file.
|
|
2752
|
+
*/
|
|
2753
|
+
async replace(sessionId, checkpoints) {
|
|
2754
|
+
await serialize2(checkpointQueues, this.checkpointKey(sessionId), async () => {
|
|
2755
|
+
await this.ensureDirectories();
|
|
2756
|
+
const path = this.checkpointPath(sessionId);
|
|
2757
|
+
if (checkpoints.length === 0) {
|
|
2758
|
+
await removeIfPresent2(path);
|
|
2759
|
+
return;
|
|
2760
|
+
}
|
|
2761
|
+
const next = [];
|
|
2762
|
+
for (const checkpoint of checkpoints) {
|
|
2763
|
+
assertCheckpointSchema(checkpoint);
|
|
2764
|
+
const parsed = checkpointSchema.safeParse(checkpoint);
|
|
2765
|
+
if (!parsed.success) throw new CheckpointStoreError("INVALID_CHECKPOINT");
|
|
2766
|
+
if (parsed.data.sessionId !== sessionId) throw new CheckpointStoreError("INVALID_CHECKPOINT");
|
|
2767
|
+
next.push(parsed.data);
|
|
2768
|
+
}
|
|
2769
|
+
next.sort((left, right) => left.createdAt - right.createdAt || left.turn - right.turn || left.id.localeCompare(right.id));
|
|
2770
|
+
await writeAtomic2(path, {
|
|
2771
|
+
schemaVersion: CHECKPOINT_SCHEMA_VERSION,
|
|
2772
|
+
checkpoints: next.slice(-MAX_CHECKPOINTS)
|
|
2773
|
+
});
|
|
2774
|
+
});
|
|
2775
|
+
}
|
|
2776
|
+
/** Drop settled journal files left behind after compensate / complete races. */
|
|
2777
|
+
async purgeSettledJournals() {
|
|
2778
|
+
return serialize2(journalQueues, this.rootKey, async () => {
|
|
2779
|
+
await this.ensureDirectories();
|
|
2780
|
+
let names;
|
|
2781
|
+
try {
|
|
2782
|
+
names = await readdir2(this.journalDirectory);
|
|
2783
|
+
} catch (error) {
|
|
2784
|
+
if (isMissing2(error)) return 0;
|
|
2785
|
+
throw error;
|
|
2786
|
+
}
|
|
2787
|
+
let removed = 0;
|
|
2788
|
+
for (const name2 of names) {
|
|
2789
|
+
if (!name2.endsWith(".json")) continue;
|
|
2790
|
+
const path = join4(this.journalDirectory, name2);
|
|
2791
|
+
const stored = await this.readJson(path);
|
|
2792
|
+
assertCheckpointSchema(stored);
|
|
2793
|
+
const parsed = journalSchema.safeParse(stored);
|
|
2794
|
+
if (!parsed.success) continue;
|
|
2795
|
+
if (parsed.data.status === "prepared" || parsed.data.status === "files-restored") continue;
|
|
2796
|
+
await removeIfPresent2(path);
|
|
2797
|
+
removed += 1;
|
|
2798
|
+
}
|
|
2799
|
+
return removed;
|
|
2800
|
+
});
|
|
2801
|
+
}
|
|
1908
2802
|
async recoverInterruptedWrites(sessionId) {
|
|
1909
2803
|
await serialize2(checkpointQueues, this.checkpointKey(sessionId), async () => {
|
|
1910
2804
|
await this.ensureDirectories();
|
|
@@ -1918,13 +2812,13 @@ var CheckpointStore = class {
|
|
|
1918
2812
|
if (!parsed.success) throw new CheckpointStoreError("INVALID_JOURNAL");
|
|
1919
2813
|
await serialize2(journalQueues, this.rootKey, async () => {
|
|
1920
2814
|
await this.ensureDirectories();
|
|
1921
|
-
await writeAtomic2(
|
|
2815
|
+
await writeAtomic2(join4(this.journalDirectory, `${digest2(journal.id)}.json`), parsed.data);
|
|
1922
2816
|
});
|
|
1923
2817
|
}
|
|
1924
2818
|
async completeJournal(id) {
|
|
1925
2819
|
await serialize2(journalQueues, this.rootKey, async () => {
|
|
1926
2820
|
await this.ensureDirectories();
|
|
1927
|
-
await removeIfPresent2(
|
|
2821
|
+
await removeIfPresent2(join4(this.journalDirectory, `${digest2(id)}.json`));
|
|
1928
2822
|
});
|
|
1929
2823
|
}
|
|
1930
2824
|
async listPendingJournals() {
|
|
@@ -1940,7 +2834,7 @@ var CheckpointStore = class {
|
|
|
1940
2834
|
async readPendingJournals() {
|
|
1941
2835
|
let names;
|
|
1942
2836
|
try {
|
|
1943
|
-
names = await
|
|
2837
|
+
names = await readdir2(this.journalDirectory);
|
|
1944
2838
|
} catch (error) {
|
|
1945
2839
|
if (isMissing2(error)) return [];
|
|
1946
2840
|
throw error;
|
|
@@ -1948,7 +2842,7 @@ var CheckpointStore = class {
|
|
|
1948
2842
|
const journals = [];
|
|
1949
2843
|
for (const name2 of names.sort()) {
|
|
1950
2844
|
if (!name2.endsWith(".json")) continue;
|
|
1951
|
-
const stored = await this.readJson(
|
|
2845
|
+
const stored = await this.readJson(join4(this.journalDirectory, name2));
|
|
1952
2846
|
assertCheckpointSchema(stored);
|
|
1953
2847
|
const parsed = journalSchema.safeParse(stored);
|
|
1954
2848
|
if (!parsed.success) throw new CheckpointStoreError("INVALID_STORE");
|
|
@@ -1960,7 +2854,7 @@ var CheckpointStore = class {
|
|
|
1960
2854
|
return `${this.rootKey}\0${sessionId}`;
|
|
1961
2855
|
}
|
|
1962
2856
|
checkpointPath(sessionId) {
|
|
1963
|
-
return
|
|
2857
|
+
return join4(this.checkpointDirectory, `${digest2(sessionId)}.json`);
|
|
1964
2858
|
}
|
|
1965
2859
|
async ensureDirectories() {
|
|
1966
2860
|
await mkdir2(this.root, { recursive: true, mode: 448 });
|
|
@@ -1968,8 +2862,8 @@ var CheckpointStore = class {
|
|
|
1968
2862
|
await mkdir2(this.journalDirectory, { recursive: true, mode: 448 });
|
|
1969
2863
|
}
|
|
1970
2864
|
async cleanTemporaryFiles(directory, prefix = "") {
|
|
1971
|
-
for (const name2 of await
|
|
1972
|
-
if (name2.startsWith(prefix) && name2.endsWith(".tmp")) await unlink2(
|
|
2865
|
+
for (const name2 of await readdir2(directory)) {
|
|
2866
|
+
if (name2.startsWith(prefix) && name2.endsWith(".tmp")) await unlink2(join4(directory, name2));
|
|
1973
2867
|
}
|
|
1974
2868
|
}
|
|
1975
2869
|
async readJson(path) {
|
|
@@ -2004,18 +2898,16 @@ function classifyUsageSource(options) {
|
|
|
2004
2898
|
stamps.set(options, tagged);
|
|
2005
2899
|
return tagged;
|
|
2006
2900
|
}
|
|
2007
|
-
|
|
2901
|
+
const purpose = options.purpose;
|
|
2902
|
+
switch (purpose) {
|
|
2008
2903
|
case "compaction":
|
|
2009
2904
|
return "compaction";
|
|
2010
2905
|
case "session-title":
|
|
2011
2906
|
return "sessionTitle";
|
|
2012
2907
|
case void 0:
|
|
2013
2908
|
break;
|
|
2014
|
-
default:
|
|
2015
|
-
const _exhaustive = options.purpose;
|
|
2016
|
-
void _exhaustive;
|
|
2909
|
+
default:
|
|
2017
2910
|
return "other";
|
|
2018
|
-
}
|
|
2019
2911
|
}
|
|
2020
2912
|
if (isAgentLoopRequest(options)) return "session";
|
|
2021
2913
|
if (options.system === void 0 && options.sessionId !== void 0) return "session";
|
|
@@ -2752,6 +3644,7 @@ function inspectContextCategory(session, category, tokenMeter) {
|
|
|
2752
3644
|
import { LlmAdapter, LlmError } from "@deepseek-ai/dsh-llm";
|
|
2753
3645
|
import { ReasoningEffortId } from "@deepseek-ai/dsh-llm/brand";
|
|
2754
3646
|
var AUTO_CATALOG_NAME = "Auto";
|
|
3647
|
+
var AUTO_CONTEXT_WINDOW = 524288;
|
|
2755
3648
|
var AutoCatalogAdapter = class extends LlmAdapter {
|
|
2756
3649
|
providerInfo(provider) {
|
|
2757
3650
|
return { id: provider, name: AUTO_CATALOG_NAME };
|
|
@@ -2769,7 +3662,8 @@ var AutoCatalogAdapter = class extends LlmAdapter {
|
|
|
2769
3662
|
provider,
|
|
2770
3663
|
id: model,
|
|
2771
3664
|
name: AUTO_CATALOG_NAME,
|
|
2772
|
-
inputModalities: ["text"]
|
|
3665
|
+
inputModalities: ["text"],
|
|
3666
|
+
context: { contextWindow: AUTO_CONTEXT_WINDOW }
|
|
2773
3667
|
});
|
|
2774
3668
|
}
|
|
2775
3669
|
stream(_options) {
|
|
@@ -4111,7 +5005,7 @@ function mergeUsageCalls(stored, history) {
|
|
|
4111
5005
|
// src/host/usage/ledger.ts
|
|
4112
5006
|
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
4113
5007
|
import { chmod as chmod3, mkdir as mkdir3, readFile as readFile3, rename as rename3, unlink as unlink3, writeFile as writeFile3 } from "node:fs/promises";
|
|
4114
|
-
import { basename as basename3, join as
|
|
5008
|
+
import { basename as basename3, join as join5 } from "node:path";
|
|
4115
5009
|
import { z as z2 } from "zod";
|
|
4116
5010
|
var callSchema = z2.object({
|
|
4117
5011
|
at: z2.number().int().nonnegative(),
|
|
@@ -4141,7 +5035,7 @@ async function removeIfPresent3(path) {
|
|
|
4141
5035
|
}
|
|
4142
5036
|
}
|
|
4143
5037
|
async function writeAtomic3(path, value) {
|
|
4144
|
-
const temporary =
|
|
5038
|
+
const temporary = join5(join5(path, ".."), `.${basename3(path)}.${randomUUID5()}.tmp`);
|
|
4145
5039
|
try {
|
|
4146
5040
|
await writeFile3(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
|
|
4147
5041
|
await rename3(temporary, path);
|
|
@@ -4155,7 +5049,7 @@ var UsageLedger = class {
|
|
|
4155
5049
|
}) {
|
|
4156
5050
|
this.root = root;
|
|
4157
5051
|
this.warn = warn;
|
|
4158
|
-
this.file =
|
|
5052
|
+
this.file = join5(root, "ledger.json");
|
|
4159
5053
|
}
|
|
4160
5054
|
root;
|
|
4161
5055
|
warn;
|
|
@@ -4647,17 +5541,19 @@ var checkpointUnavailableSchema = z3.enum([
|
|
|
4647
5541
|
"session-running",
|
|
4648
5542
|
"permission-denied",
|
|
4649
5543
|
"rollback-disabled",
|
|
4650
|
-
"first-turn",
|
|
4651
5544
|
"incompatible-session",
|
|
4652
5545
|
"compacted-surface",
|
|
4653
5546
|
"subagent-session",
|
|
4654
|
-
"unknown-surface"
|
|
5547
|
+
"unknown-surface",
|
|
5548
|
+
"already-restored",
|
|
5549
|
+
"covered-by-earlier-restore"
|
|
4655
5550
|
]);
|
|
4656
5551
|
var checkpointPreviewSchema = z3.strictObject({
|
|
4657
5552
|
sessionId: sessionIdSchema2,
|
|
4658
5553
|
turn: z3.number().int().positive(),
|
|
4659
5554
|
operation: z3.enum(["rollback", "undo"]).optional(),
|
|
4660
5555
|
scope: checkpointScopeSchema.optional(),
|
|
5556
|
+
tipTurn: z3.number().int().positive().optional(),
|
|
4661
5557
|
messages: z3.array(checkpointMessageSchema),
|
|
4662
5558
|
files: z3.array(checkpointFileSchema),
|
|
4663
5559
|
conflicts: z3.array(checkpointConflictSchema),
|
|
@@ -4668,9 +5564,48 @@ var checkpointResultSchema = z3.strictObject({
|
|
|
4668
5564
|
turn: z3.number().int().positive(),
|
|
4669
5565
|
draft: z3.string()
|
|
4670
5566
|
});
|
|
5567
|
+
var checkpointSummariesRequestSchema = z3.strictObject({
|
|
5568
|
+
sessionId: sessionIdSchema2
|
|
5569
|
+
});
|
|
5570
|
+
var checkpointGapSchema = z3.discriminatedUnion("type", [
|
|
5571
|
+
z3.object({ type: z3.literal("prompt"), reason: z3.literal("non-text-content") }).strict(),
|
|
5572
|
+
z3.object({ type: z3.literal("workspace"), reason: z3.literal("capture-failed") }).strict()
|
|
5573
|
+
]);
|
|
5574
|
+
var checkpointTurnSummarySchema = z3.strictObject({
|
|
5575
|
+
turn: z3.number().int().positive(),
|
|
5576
|
+
coverage: z3.enum(["complete", "partial"]),
|
|
5577
|
+
fileCount: z3.number().int().nonnegative(),
|
|
5578
|
+
createdAt: z3.number().int().nonnegative(),
|
|
5579
|
+
atSeq: z3.number().int().nonnegative(),
|
|
5580
|
+
prompt: z3.string(),
|
|
5581
|
+
promptPreview: z3.string(),
|
|
5582
|
+
files: z3.array(checkpointFileSchema),
|
|
5583
|
+
gaps: z3.array(checkpointGapSchema),
|
|
5584
|
+
rolledBack: z3.boolean(),
|
|
5585
|
+
tip: z3.boolean()
|
|
5586
|
+
});
|
|
5587
|
+
var liveActivityStatsSchema = z3.strictObject({
|
|
5588
|
+
turns: z3.number().int().nonnegative(),
|
|
5589
|
+
steps: z3.number().int().nonnegative(),
|
|
5590
|
+
checkpoints: z3.number().int().nonnegative(),
|
|
5591
|
+
liveCheckpoints: z3.number().int().nonnegative()
|
|
5592
|
+
});
|
|
5593
|
+
var checkpointSummariesResultSchema = z3.strictObject({
|
|
5594
|
+
sessionId: sessionIdSchema2,
|
|
5595
|
+
activity: liveActivityStatsSchema,
|
|
5596
|
+
turns: z3.array(checkpointTurnSummarySchema)
|
|
5597
|
+
});
|
|
4671
5598
|
var checkpointRequestCodec = codec("dsh-agent-enhancer#CheckpointRollbackRequest", checkpointRollbackRequestSchema);
|
|
4672
5599
|
var checkpointPreviewCodec = codec("dsh-agent-enhancer#CheckpointRollbackPreview", checkpointPreviewSchema);
|
|
4673
5600
|
var checkpointResultCodec = codec("dsh-agent-enhancer#CheckpointRollbackResult", checkpointResultSchema);
|
|
5601
|
+
var checkpointSummariesRequestCodec = codec(
|
|
5602
|
+
"dsh-agent-enhancer#CheckpointSummariesRequest",
|
|
5603
|
+
checkpointSummariesRequestSchema
|
|
5604
|
+
);
|
|
5605
|
+
var checkpointSummariesResultCodec = codec(
|
|
5606
|
+
"dsh-agent-enhancer#CheckpointSummariesResult",
|
|
5607
|
+
checkpointSummariesResultSchema
|
|
5608
|
+
);
|
|
4674
5609
|
var checkpointRemoteInfo = createTypertRemoteInfo({
|
|
4675
5610
|
package: "dsh-agent-enhancer",
|
|
4676
5611
|
methods: {
|
|
@@ -4689,13 +5624,26 @@ var checkpointRemoteInfo = createTypertRemoteInfo({
|
|
|
4689
5624
|
parameters: [{ name: "request", source: "json", codec: checkpointRequestCodec, strictCodec: checkpointRequestCodec }],
|
|
4690
5625
|
cancellation: { parameter: "signal" },
|
|
4691
5626
|
result: checkpointResultCodec
|
|
5627
|
+
},
|
|
5628
|
+
"checkpointRollback/summaries": {
|
|
5629
|
+
service: "checkpointRollback",
|
|
5630
|
+
implementation: "summaries",
|
|
5631
|
+
invocation: { kind: "direct" },
|
|
5632
|
+
parameters: [{
|
|
5633
|
+
name: "request",
|
|
5634
|
+
source: "json",
|
|
5635
|
+
codec: checkpointSummariesRequestCodec,
|
|
5636
|
+
strictCodec: checkpointSummariesRequestCodec
|
|
5637
|
+
}],
|
|
5638
|
+
cancellation: { parameter: "signal" },
|
|
5639
|
+
result: checkpointSummariesResultCodec
|
|
4692
5640
|
}
|
|
4693
5641
|
}
|
|
4694
5642
|
}, z3);
|
|
4695
5643
|
|
|
4696
5644
|
// src/host/update/check.ts
|
|
4697
5645
|
import { homedir } from "node:os";
|
|
4698
|
-
import { join as
|
|
5646
|
+
import { join as join7 } from "node:path";
|
|
4699
5647
|
|
|
4700
5648
|
// src/host/update/cli.ts
|
|
4701
5649
|
import { spawn as nodeSpawn } from "node:child_process";
|
|
@@ -4766,9 +5714,9 @@ async function runPluginAdd(latest, spawnFn = defaultSpawn) {
|
|
|
4766
5714
|
|
|
4767
5715
|
// src/host/update/install-kind.ts
|
|
4768
5716
|
import { lstatSync } from "node:fs";
|
|
4769
|
-
import { join as
|
|
5717
|
+
import { join as join6 } from "node:path";
|
|
4770
5718
|
function detectInstallKind(profileDir) {
|
|
4771
|
-
const pkgPath =
|
|
5719
|
+
const pkgPath = join6(profileDir, "node_modules", PACKAGE_NAME);
|
|
4772
5720
|
try {
|
|
4773
5721
|
const stat = lstatSync(pkgPath);
|
|
4774
5722
|
if (stat.isSymbolicLink()) return "link";
|
|
@@ -4899,8 +5847,8 @@ function isNewerVersion(latest, current) {
|
|
|
4899
5847
|
|
|
4900
5848
|
// src/host/update/check.ts
|
|
4901
5849
|
function resolveDesktopProfileDir(env = process.env, home = homedir()) {
|
|
4902
|
-
const dshHome = env.DSH_HOME ??
|
|
4903
|
-
return
|
|
5850
|
+
const dshHome = env.DSH_HOME ?? join7(home, ".dsh");
|
|
5851
|
+
return join7(dshHome, "profiles", "desktop");
|
|
4904
5852
|
}
|
|
4905
5853
|
async function checkPluginUpdate(deps) {
|
|
4906
5854
|
const latest = await deps.fetchLatest();
|
|
@@ -5128,14 +6076,14 @@ var AgentEnhancerService = class extends TypertRemoteService {
|
|
|
5128
6076
|
}
|
|
5129
6077
|
};
|
|
5130
6078
|
function resolveCheckpointRoot(dshHome) {
|
|
5131
|
-
const base =
|
|
5132
|
-
const nextPkg =
|
|
5133
|
-
const next =
|
|
5134
|
-
const prev =
|
|
6079
|
+
const base = join8(dshHome, "profiles", "desktop", "plugin-data");
|
|
6080
|
+
const nextPkg = join8(base, PACKAGE_NAME);
|
|
6081
|
+
const next = join8(nextPkg, "checkpoint");
|
|
6082
|
+
const prev = join8(base, LEGACY_PACKAGE_NAME, "checkpoint");
|
|
5135
6083
|
if (!existsSync(next) && existsSync(prev)) {
|
|
5136
6084
|
mkdirSync(nextPkg, { recursive: true });
|
|
5137
6085
|
renameSync(prev, next);
|
|
5138
|
-
const prevPkg =
|
|
6086
|
+
const prevPkg = join8(base, LEGACY_PACKAGE_NAME);
|
|
5139
6087
|
try {
|
|
5140
6088
|
if (existsSync(prevPkg) && readdirSync(prevPkg).length === 0) rmdirSync(prevPkg);
|
|
5141
6089
|
} catch {
|
|
@@ -5201,8 +6149,8 @@ function apply(ctx, config) {
|
|
|
5201
6149
|
const settings = () => readSettings(config);
|
|
5202
6150
|
const models = new AuxiliaryModels(ctx, settings);
|
|
5203
6151
|
installAutoSessionRoute(ctx, { settings });
|
|
5204
|
-
const storageRoot = resolveCheckpointRoot(process.env.DSH_HOME ??
|
|
5205
|
-
const usage = new UsageLedger(
|
|
6152
|
+
const storageRoot = resolveCheckpointRoot(process.env.DSH_HOME ?? join8(homedir2(), ".dsh"));
|
|
6153
|
+
const usage = new UsageLedger(join8(storageRoot, "..", "usage"), (message) => {
|
|
5206
6154
|
ctx.logger.warn(message);
|
|
5207
6155
|
});
|
|
5208
6156
|
const balancesFacade = (() => {
|
|
@@ -5268,10 +6216,10 @@ function apply(ctx, config) {
|
|
|
5268
6216
|
ctx.logger.warn("Checkpoint rollback recovery is still pending");
|
|
5269
6217
|
});
|
|
5270
6218
|
ctx.effect(() => {
|
|
5271
|
-
const unsubscribe = ctx.on("internal/update", (
|
|
5272
|
-
rollbackEnabled =
|
|
6219
|
+
const unsubscribe = ctx.on("internal/update", (resolvedConfig, next) => {
|
|
6220
|
+
rollbackEnabled = resolvedConfig.rollbackEnabled.get();
|
|
5273
6221
|
captures.setEnabled(rollbackEnabled);
|
|
5274
|
-
next();
|
|
6222
|
+
return next();
|
|
5275
6223
|
});
|
|
5276
6224
|
captures.setEnabled(rollbackEnabled);
|
|
5277
6225
|
return async () => {
|
|
@@ -5310,6 +6258,14 @@ var CheckpointRollbackRemoteService = class extends TypertRemoteService {
|
|
|
5310
6258
|
throw this.remoteError(error, signal);
|
|
5311
6259
|
}
|
|
5312
6260
|
}
|
|
6261
|
+
async summaries(request, signal) {
|
|
6262
|
+
this.assertOwner();
|
|
6263
|
+
try {
|
|
6264
|
+
return await this.rollback.summaries(request, signal);
|
|
6265
|
+
} catch (error) {
|
|
6266
|
+
throw this.remoteError(error, signal);
|
|
6267
|
+
}
|
|
6268
|
+
}
|
|
5313
6269
|
assertOwner() {
|
|
5314
6270
|
if (this.ctx.invocation?.peer.principal.kind !== "owner") {
|
|
5315
6271
|
throw new RemoteError("agent-enhancer/forbidden", "Only the desktop owner may use checkpoint rollback", {});
|