dsh-agent-enhancer 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/README.en.md +22 -10
  2. package/README.md +22 -10
  3. package/lib/client/context/open-tab.d.ts +5 -0
  4. package/lib/client/context/open-tab.d.ts.map +1 -1
  5. package/lib/client/dsh/conversation.d.ts.map +1 -1
  6. package/lib/client/dsh/icons.d.ts +2 -0
  7. package/lib/client/dsh/icons.d.ts.map +1 -1
  8. package/lib/client/dsh/overlay.d.ts.map +1 -1
  9. package/lib/client/dsh/settings.d.ts.map +1 -1
  10. package/lib/client/index.d.ts.map +1 -1
  11. package/lib/client/locales.d.ts +113 -19
  12. package/lib/client/locales.d.ts.map +1 -1
  13. package/lib/client/prompt/coordinator.d.ts +2 -0
  14. package/lib/client/prompt/coordinator.d.ts.map +1 -1
  15. package/lib/client/prompt/history.d.ts.map +1 -1
  16. package/lib/client/prompt/ledger-store.d.ts +8 -0
  17. package/lib/client/prompt/ledger-store.d.ts.map +1 -0
  18. package/lib/client/prompt/ledger.d.ts +15 -0
  19. package/lib/client/prompt/ledger.d.ts.map +1 -0
  20. package/lib/client/rollback/actions.d.ts +1 -0
  21. package/lib/client/rollback/actions.d.ts.map +1 -1
  22. package/lib/client/rollback/controller.d.ts +25 -2
  23. package/lib/client/rollback/controller.d.ts.map +1 -1
  24. package/lib/client/rollback/cut-cache.d.ts +13 -0
  25. package/lib/client/rollback/cut-cache.d.ts.map +1 -0
  26. package/lib/client/rollback/failure.d.ts +7 -0
  27. package/lib/client/rollback/failure.d.ts.map +1 -0
  28. package/lib/client/rollback/format.d.ts +23 -0
  29. package/lib/client/rollback/format.d.ts.map +1 -0
  30. package/lib/client/rollback/input-actions-cache.d.ts +6 -0
  31. package/lib/client/rollback/input-actions-cache.d.ts.map +1 -0
  32. package/lib/client/rollback/modal-host.d.ts +13 -0
  33. package/lib/client/rollback/modal-host.d.ts.map +1 -1
  34. package/lib/client/rollback/preview.d.ts +3 -2
  35. package/lib/client/rollback/preview.d.ts.map +1 -1
  36. package/lib/client/rollback/prompt-entries.d.ts +9 -0
  37. package/lib/client/rollback/prompt-entries.d.ts.map +1 -0
  38. package/lib/client/rollback/remote.d.ts +3 -1
  39. package/lib/client/rollback/remote.d.ts.map +1 -1
  40. package/lib/client/rollback/scope.d.ts +3 -1
  41. package/lib/client/rollback/scope.d.ts.map +1 -1
  42. package/lib/client/rollback/session-stats-dock.d.ts +10 -0
  43. package/lib/client/rollback/session-stats-dock.d.ts.map +1 -0
  44. package/lib/client/rollback/session-stats-filter.d.ts +19 -0
  45. package/lib/client/rollback/session-stats-filter.d.ts.map +1 -0
  46. package/lib/client/rollback/session-stats-meter.d.ts +20 -0
  47. package/lib/client/rollback/session-stats-meter.d.ts.map +1 -0
  48. package/lib/client/rollback/timeline-format.d.ts +23 -0
  49. package/lib/client/rollback/timeline-format.d.ts.map +1 -0
  50. package/lib/client/rollback/timeline-kind.d.ts +13 -0
  51. package/lib/client/rollback/timeline-kind.d.ts.map +1 -0
  52. package/lib/client/rollback/timeline-panel.d.ts +23 -0
  53. package/lib/client/rollback/timeline-panel.d.ts.map +1 -0
  54. package/lib/client/rollback/timeline-tab.d.ts +40 -0
  55. package/lib/client/rollback/timeline-tab.d.ts.map +1 -0
  56. package/lib/client/rollback/transcript-filter.d.ts +17 -2
  57. package/lib/client/rollback/transcript-filter.d.ts.map +1 -1
  58. package/lib/client/rollback/transcript.d.ts +55 -9
  59. package/lib/client/rollback/transcript.d.ts.map +1 -1
  60. package/lib/client/rollback/turn-outline-filter.d.ts.map +1 -1
  61. package/lib/client/rollback/types.d.ts +17 -1
  62. package/lib/client/rollback/types.d.ts.map +1 -1
  63. package/lib/client/rollback/user-node.d.ts +1 -0
  64. package/lib/client/rollback/user-node.d.ts.map +1 -1
  65. package/lib/client.js +1959 -261
  66. package/lib/client.js.map +1 -1
  67. package/lib/config.d.ts +3 -1
  68. package/lib/config.d.ts.map +1 -1
  69. package/lib/host/auto-route/classifier.d.ts.map +1 -1
  70. package/lib/host/auto-route/session-hook.d.ts.map +1 -1
  71. package/lib/host/auto-route/session-selection.d.ts.map +1 -1
  72. package/lib/host/checkpoint/activity.d.ts +43 -0
  73. package/lib/host/checkpoint/activity.d.ts.map +1 -0
  74. package/lib/host/checkpoint/availability.d.ts +8 -1
  75. package/lib/host/checkpoint/availability.d.ts.map +1 -1
  76. package/lib/host/checkpoint/capture.d.ts +12 -4
  77. package/lib/host/checkpoint/capture.d.ts.map +1 -1
  78. package/lib/host/checkpoint/chain-files.d.ts +35 -0
  79. package/lib/host/checkpoint/chain-files.d.ts.map +1 -0
  80. package/lib/host/checkpoint/cut-filter.d.ts +9 -0
  81. package/lib/host/checkpoint/cut-filter.d.ts.map +1 -0
  82. package/lib/host/checkpoint/cut-live.d.ts +13 -0
  83. package/lib/host/checkpoint/cut-live.d.ts.map +1 -0
  84. package/lib/host/checkpoint/cut-store.d.ts +30 -0
  85. package/lib/host/checkpoint/cut-store.d.ts.map +1 -0
  86. package/lib/host/checkpoint/dsh.d.ts.map +1 -1
  87. package/lib/host/checkpoint/files.d.ts +3 -0
  88. package/lib/host/checkpoint/files.d.ts.map +1 -1
  89. package/lib/host/checkpoint/live.d.ts +9 -0
  90. package/lib/host/checkpoint/live.d.ts.map +1 -1
  91. package/lib/host/checkpoint/service.d.ts +125 -4
  92. package/lib/host/checkpoint/service.d.ts.map +1 -1
  93. package/lib/host/checkpoint/store.d.ts +13 -0
  94. package/lib/host/checkpoint/store.d.ts.map +1 -1
  95. package/lib/host/checkpoint/workspace-snapshot.d.ts +30 -0
  96. package/lib/host/checkpoint/workspace-snapshot.d.ts.map +1 -0
  97. package/lib/host/index.d.ts +3 -1
  98. package/lib/host/index.d.ts.map +1 -1
  99. package/lib/host/model.d.ts.map +1 -1
  100. package/lib/host/rpc.d.ts +7 -0
  101. package/lib/host/rpc.d.ts.map +1 -1
  102. package/lib/host/usage/source.d.ts.map +1 -1
  103. package/lib/identity.d.ts +1 -1
  104. package/lib/identity.d.ts.map +1 -1
  105. package/lib/index.js +1677 -774
  106. package/lib/index.js.map +4 -4
  107. package/package.json +61 -60
package/lib/index.js CHANGED
@@ -1,8 +1,8 @@
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 join6 } from "node:path";
5
- import z4 from "@deepseek-ai/schemastery";
4
+ import { join as join9 } from "node:path";
5
+ import z5 from "@deepseek-ai/schemastery";
6
6
  import { RemoteError, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
7
7
 
8
8
  // src/host/auto-route/sentinel.ts
@@ -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.2.0";
163
+ var PACKAGE_VERSION = "0.3.2";
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 lastTurn = ctx.sessionProjections.stateOf(agent.session, "turnBoundary")?.lastTurn;
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;
@@ -251,21 +267,25 @@ var DshCheckpointSessions = class {
251
267
  adapters = /* @__PURE__ */ new Map();
252
268
  resolveSession = (sessionId) => {
253
269
  const agent = this.ctx.agents.get(sessionId);
254
- if (agent === void 0 || this.ctx.get("sessions").get(sessionId) !== agent.session) {
270
+ const stored = this.ctx.get("sessions").get(sessionId);
271
+ if (agent === void 0 || stored === void 0 || stored.id !== agent.session.id) {
255
272
  this.adapters.delete(sessionId);
256
273
  return void 0;
257
274
  }
258
275
  const cached = this.adapters.get(sessionId);
259
276
  if (cached?.agent === agent) return cached.adapter;
260
- const workspaceRoot = agent.session.header.cwd ?? "";
261
277
  const adapter = {
262
- session: agent.session,
263
- workspaceRoot,
278
+ get session() {
279
+ return agent.session;
280
+ },
281
+ get workspaceRoot() {
282
+ return agent.session.header.cwd ?? "";
283
+ },
264
284
  get status() {
265
285
  return agent.status;
266
286
  },
267
287
  get canRestore() {
268
- return workspaceRoot !== "";
288
+ return (agent.session.header.cwd ?? "") !== "";
269
289
  },
270
290
  readEvents: () => agent.session.snapshotEvents(),
271
291
  runMaintenance: async (task) => {
@@ -275,10 +295,11 @@ var DshCheckpointSessions = class {
275
295
  },
276
296
  synchronize: async (signal) => {
277
297
  signal.throwIfAborted();
278
- this.ctx.sessionProjections.snapshot(agent.session);
279
- await this.ctx.get("sessions").flush(agent.session);
298
+ const session = agent.session;
299
+ this.ctx.sessionProjections.snapshot(session);
300
+ await this.ctx.get("sessions").flush(session);
280
301
  signal.throwIfAborted();
281
- this.ctx.sessionProjections.snapshot(agent.session);
302
+ this.ctx.sessionProjections.snapshot(session);
282
303
  }
283
304
  };
284
305
  this.adapters.set(sessionId, { agent, adapter });
@@ -287,7 +308,142 @@ var DshCheckpointSessions = class {
287
308
  };
288
309
 
289
310
  // src/host/checkpoint/live.ts
290
- import { isAbsolute as isAbsolute2, relative, sep as sep2 } from "node:path";
311
+ import { isAbsolute as isAbsolute2, join as join3, relative, sep as sep2 } from "node:path";
312
+
313
+ // src/host/checkpoint/activity.ts
314
+ function surfaceMessageId(event) {
315
+ switch (event.type) {
316
+ case "user/message":
317
+ return event.data.id;
318
+ case "system/message":
319
+ case "developer/message":
320
+ case "assistant/message":
321
+ case "tool/result":
322
+ return event.data.message.id;
323
+ default:
324
+ return null;
325
+ }
326
+ }
327
+ function isUndoCopyEvent(event) {
328
+ const id = surfaceMessageId(event);
329
+ return id !== null && isUndoId(id);
330
+ }
331
+ function isRollbackScaffoldEvent(event) {
332
+ if (event.type !== "user/message") return false;
333
+ if (isRollbackId(event.data.id)) return true;
334
+ return event.data.source.kind === "checkpoint-rollback";
335
+ }
336
+ function undoShellRanges(events) {
337
+ const ranges = [];
338
+ let turn;
339
+ let startSeq = 0;
340
+ let sawUndo = false;
341
+ let sawReal = false;
342
+ let lastSeq = 0;
343
+ const flush = () => {
344
+ if (turn !== void 0 && sawUndo && !sawReal) {
345
+ ranges.push({ turn, startSeq, endSeq: lastSeq });
346
+ }
347
+ sawUndo = false;
348
+ sawReal = false;
349
+ };
350
+ for (const event of events) {
351
+ lastSeq = Number(event.seq);
352
+ if (event.type === "turn/start") {
353
+ flush();
354
+ turn = event.data.turn;
355
+ startSeq = lastSeq;
356
+ continue;
357
+ }
358
+ if (event.type === "turn/end" && turn !== void 0 && event.data.turn === turn) {
359
+ flush();
360
+ turn = void 0;
361
+ continue;
362
+ }
363
+ if (turn === void 0 || isRollbackScaffoldEvent(event)) continue;
364
+ if (isUndoCopyEvent(event)) {
365
+ sawUndo = true;
366
+ continue;
367
+ }
368
+ if (event.type === "user/message" || event.type === "assistant/message" || event.type === "tool/result" || event.type === "system/message" || event.type === "developer/message") {
369
+ sawReal = true;
370
+ }
371
+ }
372
+ flush();
373
+ return ranges;
374
+ }
375
+ function inUndoShellRange(seq, ranges) {
376
+ return ranges.some((range) => seq >= range.startSeq && seq <= range.endSeq);
377
+ }
378
+ function isUndoShellCheckpoint(atSeq, ranges) {
379
+ const turnStartSeq = atSeq + 1;
380
+ return ranges.some((range) => turnStartSeq >= range.startSeq && turnStartSeq <= range.endSeq);
381
+ }
382
+ function turnOfEvent(event) {
383
+ if (event.type === "turn/start" || event.type === "turn/end" || event.type === "step/start" || event.type === "step/end") {
384
+ return event.data.turn;
385
+ }
386
+ const turn = event.data.turn;
387
+ return typeof turn === "number" ? turn : void 0;
388
+ }
389
+ function liveActivityStats(events, options) {
390
+ const ranges = undoShellRanges(events);
391
+ const everShadowed = /* @__PURE__ */ new Set();
392
+ for (const event of events) {
393
+ if (!isRollbackScaffoldEvent(event)) continue;
394
+ for (const seq of event.sourceEventSeqs ?? []) everShadowed.add(Number(seq));
395
+ }
396
+ const closed = /* @__PURE__ */ new Set();
397
+ const turns = /* @__PURE__ */ new Set();
398
+ for (const event of events) {
399
+ if (event.type !== "step/end") continue;
400
+ const seq = Number(event.seq);
401
+ if (everShadowed.has(seq)) continue;
402
+ if (inUndoShellRange(seq, ranges)) continue;
403
+ const beforeTip = options.continueAfterSeq === void 0 || seq <= options.continueAfterSeq;
404
+ const turn = event.data.turn;
405
+ if (options.hideTurnsFrom !== void 0 && turn >= options.hideTurnsFrom && beforeTip) {
406
+ continue;
407
+ }
408
+ const key = `${turn}:${event.data.step}`;
409
+ if (closed.has(key)) continue;
410
+ closed.add(key);
411
+ turns.add(turn);
412
+ }
413
+ if (closed.size === 0) {
414
+ let steps = 0;
415
+ for (const event of events) {
416
+ const seq = Number(event.seq);
417
+ if (inUndoShellRange(seq, ranges)) continue;
418
+ if (isRollbackScaffoldEvent(event)) continue;
419
+ const beforeTip = options.continueAfterSeq === void 0 || seq <= options.continueAfterSeq;
420
+ const ownedTurn = turnOfEvent(event);
421
+ if (options.hideTurnsFrom !== void 0 && ownedTurn !== void 0 && ownedTurn >= options.hideTurnsFrom && beforeTip && !isUndoCopyEvent(event)) {
422
+ continue;
423
+ }
424
+ if (event.type === "turn/start") {
425
+ turns.add(event.data.turn);
426
+ continue;
427
+ }
428
+ if (event.type === "assistant/message") {
429
+ steps += 1;
430
+ if (ownedTurn !== void 0) turns.add(ownedTurn);
431
+ }
432
+ }
433
+ return {
434
+ turns: turns.size,
435
+ steps,
436
+ checkpoints: options.checkpointCount,
437
+ liveCheckpoints: options.liveCheckpointCount
438
+ };
439
+ }
440
+ return {
441
+ turns: turns.size,
442
+ steps: closed.size,
443
+ checkpoints: options.checkpointCount,
444
+ liveCheckpoints: options.liveCheckpointCount
445
+ };
446
+ }
291
447
 
292
448
  // src/host/checkpoint/capture.ts
293
449
  import { randomUUID } from "node:crypto";
@@ -296,19 +452,50 @@ import { randomUUID } from "node:crypto";
296
452
  var CHECKPOINT_SCHEMA_VERSION = 1;
297
453
 
298
454
  // src/host/checkpoint/capture.ts
455
+ function textBlocksOf(content) {
456
+ return content.flatMap((block) => block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("");
457
+ }
299
458
  function directText(prompt) {
300
459
  if (prompt.source.kind !== "user" || prompt.content.length === 0) return null;
301
- if (prompt.content.some((block) => block.type !== "text")) return null;
302
- return prompt.content.map((block) => block.type === "text" ? block.text : "").join("");
460
+ const text3 = textBlocksOf(prompt.content);
461
+ return text3.trim() === "" ? null : text3;
462
+ }
463
+ function recoverTurnPrompt(events, turn) {
464
+ const turnStart = events.find(
465
+ (event) => event.type === "turn/start" && event.data.turn === turn
466
+ );
467
+ const turnEnd = events.find(
468
+ (event) => event.type === "turn/end" && event.data.turn === turn
469
+ );
470
+ if (turnStart === void 0 || turnEnd === void 0) return "";
471
+ for (const event of events) {
472
+ if (event.type !== "user/message") continue;
473
+ if (event.seq <= turnStart.seq || event.seq >= turnEnd.seq) continue;
474
+ if (event.data.source.kind !== "user") continue;
475
+ const text3 = textBlocksOf(event.data.content);
476
+ if (text3.trim() !== "") return text3;
477
+ }
478
+ return "";
303
479
  }
304
480
  function checkpointAtSeq(turnStartSeq) {
305
481
  return Math.max(0, turnStartSeq - 1);
306
482
  }
307
- function resolveRollbackCut(events, turn, _atSeq) {
308
- const turnStart = events.find(
483
+ function resolveRollbackCut(events, turn, atSeq) {
484
+ const starts = events.filter(
309
485
  (event) => event.type === "turn/start" && event.data.turn === turn
310
486
  );
311
- if (turnStart === void 0) return null;
487
+ if (starts.length === 0) return null;
488
+ let turnStart = starts[0];
489
+ if (typeof atSeq === "number") {
490
+ const want = atSeq + 1;
491
+ const exact = starts.find((event) => Number(event.seq) === want);
492
+ if (exact !== void 0) {
493
+ turnStart = exact;
494
+ } else {
495
+ const after = [...starts].reverse().find((event) => Number(event.seq) >= want);
496
+ if (after !== void 0) turnStart = after;
497
+ }
498
+ }
312
499
  return { cutSeq: Number(turnStart.seq) - 1 };
313
500
  }
314
501
  async function captureCheckpoint(options) {
@@ -322,8 +509,8 @@ async function captureCheckpoint(options) {
322
509
  let files;
323
510
  try {
324
511
  files = await options.captureFiles();
325
- } catch {
326
- files = [];
512
+ } catch (error) {
513
+ files = Array.isArray(error.files) ? error.files : [];
327
514
  gaps.push({ type: "workspace", reason: "capture-failed" });
328
515
  }
329
516
  options.onStage?.("workspace-captured");
@@ -356,7 +543,7 @@ function synthesizeCheckpoint(options) {
356
543
  if (turnStart === void 0 || turnEnd === void 0 || turnStart.seq < 0) return null;
357
544
  if (options.events.some((event, index) => Number(event.seq) !== index)) return null;
358
545
  const user = options.events.find(
359
- (event) => event.type === "user/message" && event.seq > turnStart.seq && event.seq < turnEnd.seq
546
+ (event) => event.type === "user/message" && event.data.source.kind === "user" && event.seq > turnStart.seq && event.seq < turnEnd.seq
360
547
  );
361
548
  const prompt = user === void 0 ? null : directText(user.data);
362
549
  const gaps = prompt === null ? [{ type: "prompt", reason: "non-text-content" }] : [];
@@ -385,6 +572,11 @@ import { TextDecoder } from "node:util";
385
572
  var MAX_FILE_BYTES = 2 * 1024 * 1024;
386
573
  var ABSENT_FILE_HASH = "";
387
574
  var excludedSegments = /* @__PURE__ */ new Set([".git", "node_modules", ".dsh", "dist", "build", "out", "coverage", ".next"]);
575
+ function isExcludedSegment(segment) {
576
+ if (!segment || segment === "." || segment === "..") return true;
577
+ const canonical = segment.replace(/[. ]+$/g, "").toLowerCase();
578
+ return !canonical || excludedSegments.has(canonical) || canonical === ".env" || canonical.startsWith(".env.");
579
+ }
388
580
  var decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
389
581
  var transactionQueues = /* @__PURE__ */ new Map();
390
582
  async function serialize(key, operation) {
@@ -441,11 +633,7 @@ function pathKey(path) {
441
633
  }
442
634
  function unsafePath(path) {
443
635
  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
- });
636
+ return segments(path).some((segment) => isExcludedSegment(segment));
449
637
  }
450
638
  function absolutePath(workspaceRoot, path) {
451
639
  return resolve(workspaceRoot, ...segments(path));
@@ -626,7 +814,6 @@ var CheckpointFiles = class {
626
814
  await journal.compensate();
627
815
  throw new CheckpointFileError("FILE_RESTORE_FAILED");
628
816
  }
629
- if (!result.synchronized) throw new CheckpointFileError("FILE_RESTORE_FAILED");
630
817
  try {
631
818
  await journal.complete("completed");
632
819
  return journal;
@@ -803,23 +990,141 @@ var CheckpointFiles = class {
803
990
  }
804
991
  };
805
992
 
993
+ // src/host/checkpoint/workspace-snapshot.ts
994
+ import { readdir } from "node:fs/promises";
995
+ import { join as join2 } from "node:path";
996
+ var MAX_WORKSPACE_SCAN_FILES = 2e3;
997
+ var MAX_SHELL_CHANGED_FILES = 200;
998
+ async function scanWorkspace(workspaceRoot, options = {}) {
999
+ const maxFiles = options.maxFiles ?? MAX_WORKSPACE_SCAN_FILES;
1000
+ const files = /* @__PURE__ */ new Map();
1001
+ let truncated = false;
1002
+ const visit = async (absoluteDir, relativeDir) => {
1003
+ if (truncated) return;
1004
+ let entries;
1005
+ try {
1006
+ entries = await readdir(absoluteDir, { withFileTypes: true });
1007
+ } catch {
1008
+ truncated = true;
1009
+ return;
1010
+ }
1011
+ for (const entry of entries) {
1012
+ if (truncated) return;
1013
+ if (isExcludedSegment(entry.name)) continue;
1014
+ const relativePath = relativeDir === "" ? entry.name : `${relativeDir}/${entry.name}`;
1015
+ const absolutePath2 = join2(absoluteDir, entry.name);
1016
+ if (entry.isSymbolicLink()) continue;
1017
+ if (entry.isDirectory()) {
1018
+ await visit(absolutePath2, relativePath.split("\\").join("/"));
1019
+ continue;
1020
+ }
1021
+ if (!entry.isFile()) continue;
1022
+ const path = relativePath.split("\\").join("/");
1023
+ if (unsafePath(path)) continue;
1024
+ if (files.size >= maxFiles) {
1025
+ truncated = true;
1026
+ return;
1027
+ }
1028
+ try {
1029
+ const snapshot = await readSnapshot(workspaceRoot, path);
1030
+ if (snapshot.exists) files.set(path, snapshot);
1031
+ } catch {
1032
+ }
1033
+ }
1034
+ };
1035
+ await visit(workspaceRoot, "");
1036
+ return { files, truncated };
1037
+ }
1038
+ function diffSnapshots(before, after, options = {}) {
1039
+ const maxChanges = options.maxChanges ?? MAX_SHELL_CHANGED_FILES;
1040
+ const files = [];
1041
+ let truncated = false;
1042
+ const push = (checkpoint) => {
1043
+ if (files.length >= maxChanges) {
1044
+ truncated = true;
1045
+ return;
1046
+ }
1047
+ files.push(checkpoint);
1048
+ };
1049
+ for (const [path, afterSnap] of after) {
1050
+ if (truncated) break;
1051
+ const beforeSnap = before.get(path) ?? { path, exists: false, text: null };
1052
+ const beforeHash = snapshotHash(beforeSnap);
1053
+ const afterHash = snapshotHash(afterSnap);
1054
+ if (beforeHash === afterHash) continue;
1055
+ push({
1056
+ path,
1057
+ change: !beforeSnap.exists ? "create" : "modify",
1058
+ beforeText: beforeSnap.exists ? beforeSnap.text : null,
1059
+ beforeHash,
1060
+ afterText: afterSnap.exists ? afterSnap.text : null,
1061
+ afterHash
1062
+ });
1063
+ }
1064
+ for (const [path, beforeSnap] of before) {
1065
+ if (truncated) break;
1066
+ if (after.has(path)) continue;
1067
+ const afterSnap = { path, exists: false, text: null };
1068
+ const beforeHash = snapshotHash(beforeSnap);
1069
+ const afterHash = snapshotHash(afterSnap);
1070
+ if (beforeHash === afterHash) continue;
1071
+ push({
1072
+ path,
1073
+ change: "delete",
1074
+ beforeText: beforeSnap.exists ? beforeSnap.text : null,
1075
+ beforeHash,
1076
+ afterText: null,
1077
+ afterHash
1078
+ });
1079
+ }
1080
+ return { files, truncated };
1081
+ }
1082
+
806
1083
  // src/host/checkpoint/live.ts
1084
+ function isFileMutationTool(name2) {
1085
+ return /^(?:write_file|edit_file|write|edit|str_replace(?:_editor)?|apply_patch)$/i.test(name2);
1086
+ }
1087
+ function isShellTool(name2) {
1088
+ return /^(?:shell|bash|terminal|run_code|pwsh)/i.test(name2);
1089
+ }
1090
+ function filePathFromToolArgs(args) {
1091
+ if (args === null || typeof args !== "object") return null;
1092
+ const record2 = args;
1093
+ for (const key of ["path", "file_path", "filePath", "target"]) {
1094
+ const value = record2[key];
1095
+ if (typeof value === "string" && value.trim() !== "") return value;
1096
+ }
1097
+ return null;
1098
+ }
1099
+ function agentFromActor(actor, actors) {
1100
+ if (actor === void 0) return void 0;
1101
+ const mapped = actors.get(actor);
1102
+ if (mapped !== void 0) return mapped;
1103
+ if (!("agent" in actor)) return void 0;
1104
+ const agent = actor.agent;
1105
+ return agent;
1106
+ }
1107
+ function isScaffoldUserPrompt(event) {
1108
+ return isUndoId(event.data.id) || isRollbackId(event.data.id) || isRollbackScaffoldEvent(event);
1109
+ }
807
1110
  var DshCheckpointCapture = class {
808
1111
  constructor(ctx, options) {
809
1112
  this.ctx = ctx;
810
1113
  this.options = options;
811
1114
  this.disposers.push(
812
1115
  ctx.on("agent/pre-step", async (payload, next) => {
813
- const current = this.turns.get(payload.agent.id);
1116
+ const sessionId = payload.agent.session.id;
1117
+ const current = this.turns.get(sessionId);
814
1118
  const startsTurn = current === void 0 || current.turnStart !== null && current.turnStart.data.turn !== payload.turn;
815
1119
  if (!this.closed && startsTurn && payload.agent.session.header.origin !== "subagent") {
816
- this.turns.set(payload.agent.id, {
1120
+ this.turns.set(sessionId, {
817
1121
  agent: payload.agent,
818
1122
  prompt: payload.messages.find((message) => message.source.kind === "user") ?? null,
819
1123
  turnStart: null,
820
1124
  files: /* @__PURE__ */ new Map(),
821
1125
  capturing: /* @__PURE__ */ new Set(),
822
- incomplete: false
1126
+ incomplete: false,
1127
+ suppressCheckpoint: false
823
1128
  });
824
1129
  }
825
1130
  return next();
@@ -836,13 +1141,21 @@ var DshCheckpointCapture = class {
836
1141
  turnStart: null,
837
1142
  files: /* @__PURE__ */ new Map(),
838
1143
  capturing: /* @__PURE__ */ new Set(),
839
- incomplete: false
1144
+ incomplete: false,
1145
+ suppressCheckpoint: false
840
1146
  };
841
1147
  current.turnStart = event;
842
1148
  this.turns.set(session.id, current);
843
1149
  } else if (event.type === "user/message") {
844
1150
  const current = this.turns.get(session.id);
845
- if (current !== void 0) current.prompt = event.data;
1151
+ if (current === void 0) return;
1152
+ if (isScaffoldUserPrompt(event)) {
1153
+ current.suppressCheckpoint = true;
1154
+ return;
1155
+ }
1156
+ if (event.data.source.kind === "user" && (current.prompt === null || current.prompt.source.kind !== "user")) {
1157
+ current.prompt = event.data;
1158
+ }
846
1159
  } else if (event.type === "turn/end") {
847
1160
  const current = this.turns.get(session.id);
848
1161
  if (current?.turnStart?.data.turn === event.data.turn) {
@@ -851,25 +1164,34 @@ var DshCheckpointCapture = class {
851
1164
  }
852
1165
  }
853
1166
  }),
1167
+ // global: Desktop dispatches tools/execute with an agent carrier; without
1168
+ // this flag the host plugin's listener is filtered out and never runs.
854
1169
  ctx.on("tools/execute", async (exec, next) => {
855
1170
  if (exec.agent === void 0) return next();
856
- const current = this.turns.get(exec.agent.id);
857
- if (current !== void 0 && /^(?:shell|bash|terminal|run_code)/.test(exec.name)) current.incomplete = true;
1171
+ const current = this.turns.get(exec.agent.session.id);
858
1172
  this.actors.set(exec, exec.agent);
859
1173
  try {
1174
+ if (current !== void 0 && isFileMutationTool(exec.name)) {
1175
+ await this.captureToolPath(exec.agent, exec.arguments);
1176
+ }
1177
+ if (current !== void 0 && isShellTool(exec.name)) {
1178
+ return await this.captureShellWorkspace(current, next);
1179
+ }
860
1180
  return await next();
861
1181
  } finally {
862
1182
  this.actors.delete(exec);
863
1183
  }
864
- }),
1184
+ }, { global: true }),
1185
+ // Prepend: policy is a single-slot owner that does not call next(). Capture
1186
+ // must wrap it so create/edit before-images still land in the checkpoint.
865
1187
  ctx.on("fs/write-intent", async (target, actor, next) => {
866
1188
  await this.captureIntent(target, actor);
867
1189
  return next();
868
- }),
1190
+ }, { prepend: true, global: true }),
869
1191
  ctx.on("fs/edit-intent", async (target, actor, next) => {
870
1192
  await this.captureIntent(target, actor);
871
1193
  return next();
872
- })
1194
+ }, { prepend: true, global: true })
873
1195
  );
874
1196
  }
875
1197
  ctx;
@@ -892,14 +1214,14 @@ var DshCheckpointCapture = class {
892
1214
  }
893
1215
  finish(turn, turnEnd) {
894
1216
  const turnStart = turn.turnStart;
895
- if (turnStart === null) return;
1217
+ if (turnStart === null || turn.suppressCheckpoint) return;
896
1218
  const operation = captureCheckpoint({
897
1219
  store: {
898
1220
  save: async (checkpoint) => {
899
1221
  if (!this.closed) await this.options.store.save(checkpoint);
900
1222
  }
901
1223
  },
902
- sessionId: turn.agent.id,
1224
+ sessionId: turn.agent.session.id,
903
1225
  session: {
904
1226
  format: turn.agent.session.header.version,
905
1227
  preset: turn.agent.session.header.agentPreset ?? null
@@ -918,13 +1240,80 @@ var DshCheckpointCapture = class {
918
1240
  this.pending.delete(operation);
919
1241
  });
920
1242
  }
1243
+ /**
1244
+ * Cline-style workspace before/after scan around shell tools so creates like
1245
+ * `Set-Content` land in turn.files. Incomplete only when the scan truncates
1246
+ * or fails — not merely because a shell tool ran.
1247
+ */
1248
+ async captureShellWorkspace(turn, run) {
1249
+ const workspaceRoot = turn.agent.session.header.cwd;
1250
+ if (workspaceRoot === void 0) {
1251
+ turn.incomplete = true;
1252
+ return run();
1253
+ }
1254
+ let before;
1255
+ try {
1256
+ before = await scanWorkspace(workspaceRoot);
1257
+ } catch {
1258
+ turn.incomplete = true;
1259
+ return run();
1260
+ }
1261
+ if (before.truncated) turn.incomplete = true;
1262
+ try {
1263
+ return await run();
1264
+ } finally {
1265
+ try {
1266
+ const after = await scanWorkspace(workspaceRoot);
1267
+ if (after.truncated) turn.incomplete = true;
1268
+ const diff = diffSnapshots(before.files, after.files);
1269
+ if (diff.truncated) turn.incomplete = true;
1270
+ for (const file of diff.files) {
1271
+ if (turn.files.has(file.path) || turn.capturing.has(file.path)) continue;
1272
+ turn.files.set(file.path, {
1273
+ path: file.path,
1274
+ before: file.beforeText === null ? { path: file.path, exists: false, text: null } : { path: file.path, exists: true, text: file.beforeText }
1275
+ });
1276
+ }
1277
+ } catch {
1278
+ turn.incomplete = true;
1279
+ }
1280
+ }
1281
+ }
1282
+ turnOf(agent) {
1283
+ return this.turns.get(agent.session.id);
1284
+ }
1285
+ async captureToolPath(agent, args) {
1286
+ const path = filePathFromToolArgs(args);
1287
+ if (path === null) return;
1288
+ const workspaceRoot = agent.session.header.cwd;
1289
+ if (workspaceRoot === void 0) {
1290
+ const turn = this.turnOf(agent);
1291
+ if (turn !== void 0) turn.incomplete = true;
1292
+ return;
1293
+ }
1294
+ try {
1295
+ const absolutePath2 = isAbsolute2(path) ? path : join3(workspaceRoot, path);
1296
+ await this.captureAbsolutePath(agent, absolutePath2);
1297
+ } catch {
1298
+ const turn = this.turnOf(agent);
1299
+ if (turn !== void 0) turn.incomplete = true;
1300
+ }
1301
+ }
921
1302
  async captureIntent(target, actor) {
922
- const agent = actor === void 0 ? void 0 : this.actors.get(actor);
1303
+ const agent = agentFromActor(actor, this.actors);
923
1304
  if (agent === void 0) {
924
- for (const turn2 of this.turns.values()) turn2.incomplete = true;
925
1305
  return;
926
1306
  }
927
- const turn = this.turns.get(agent.id);
1307
+ try {
1308
+ const absolutePath2 = this.ctx.fs.processPath(target);
1309
+ await this.captureAbsolutePath(agent, absolutePath2);
1310
+ } catch {
1311
+ const turn = this.turnOf(agent);
1312
+ if (turn !== void 0) turn.incomplete = true;
1313
+ }
1314
+ }
1315
+ async captureAbsolutePath(agent, absolutePath2) {
1316
+ const turn = this.turnOf(agent);
928
1317
  if (turn === void 0) return;
929
1318
  const workspaceRoot = agent.session.header.cwd;
930
1319
  if (workspaceRoot === void 0) {
@@ -932,7 +1321,6 @@ var DshCheckpointCapture = class {
932
1321
  return;
933
1322
  }
934
1323
  try {
935
- const absolutePath2 = this.ctx.fs.processPath(target);
936
1324
  const relativePath = relative(workspaceRoot, absolutePath2);
937
1325
  if (relativePath === "" || relativePath.startsWith(`..${sep2}`) || relativePath === ".." || isAbsolute2(relativePath)) {
938
1326
  turn.incomplete = true;
@@ -971,7 +1359,9 @@ var DshCheckpointCapture = class {
971
1359
  afterHash
972
1360
  });
973
1361
  }
974
- if (turn.incomplete) throw new Error("Workspace capture is incomplete");
1362
+ if (turn.incomplete) {
1363
+ throw Object.assign(new Error("Workspace capture is incomplete"), { files });
1364
+ }
975
1365
  return files;
976
1366
  }
977
1367
  };
@@ -1015,7 +1405,7 @@ var DshCheckpointCaptureSwitch = class {
1015
1405
  };
1016
1406
 
1017
1407
  // src/host/checkpoint/service.ts
1018
- import { randomUUID as randomUUID3 } from "node:crypto";
1408
+ import { randomUUID as randomUUID4 } from "node:crypto";
1019
1409
  import { MessageId } from "@deepseek-ai/dsh-llm";
1020
1410
  import { SessionSeq } from "@deepseek-ai/dsh-session";
1021
1411
 
@@ -1029,26 +1419,316 @@ var CONVERSATION_SOFT = /* @__PURE__ */ new Set([
1029
1419
  "compacted-surface",
1030
1420
  // Conversation restore does not need a workspace cwd.
1031
1421
  "permission-denied",
1032
- // Turn 1 is restorable; keep this soft for older previews that still emit it.
1033
- "first-turn"
1034
1422
  // Non-contiguous logs are unusual but still restorable when a surface was built.
1035
1423
  // Only emit unknown-surface when surface is missing — that case stays hard.
1424
+ // Re-confirming the active tip is a soft no-op (draft prefill / optional files).
1425
+ "already-restored",
1426
+ // Covered cuts need undo-first — UI replaces confirms with Undo, not a fatal gap list.
1427
+ "covered-by-earlier-restore"
1036
1428
  ]);
1037
1429
  var EMPTY_FILES_SOFT = /* @__PURE__ */ new Set([
1038
1430
  "incomplete-checkpoint",
1039
1431
  "workspace-capture-failed",
1040
1432
  "prompt-non-text-content",
1041
- "compacted-surface"
1433
+ "compacted-surface",
1434
+ "already-restored",
1435
+ "covered-by-earlier-restore"
1436
+ ]);
1437
+ var TRACKED_FILES_SOFT = /* @__PURE__ */ new Set([
1438
+ "incomplete-checkpoint",
1439
+ "workspace-capture-failed",
1440
+ "prompt-non-text-content",
1441
+ "already-restored",
1442
+ "covered-by-earlier-restore"
1042
1443
  ]);
1043
1444
  function blockingUnavailable(unavailable, scope, options = {}) {
1044
- const trackedFiles = options.trackedFiles;
1045
- const soft = scope === "conversation" || trackedFiles === 0 ? scope === "conversation" ? CONVERSATION_SOFT : EMPTY_FILES_SOFT : null;
1046
- if (soft === null) return unavailable;
1445
+ const trackedFiles = options.trackedFiles ?? 0;
1446
+ const soft = scope === "conversation" ? CONVERSATION_SOFT : trackedFiles === 0 ? EMPTY_FILES_SOFT : TRACKED_FILES_SOFT;
1047
1447
  return unavailable.filter((reason) => !soft.has(reason));
1048
1448
  }
1049
1449
 
1450
+ // src/host/checkpoint/chain-files.ts
1451
+ function netFileChange(earliest, latest) {
1452
+ if (earliest.beforeText === null && latest.afterText === null) return null;
1453
+ if (earliest.beforeText === null) return "create";
1454
+ if (latest.afterText === null) return "delete";
1455
+ return "modify";
1456
+ }
1457
+ function chainTrackedFiles(checkpoints, fromTurnOrRange, untilTurnExclusive) {
1458
+ const range = typeof fromTurnOrRange === "number" ? { fromTurn: fromTurnOrRange, untilTurnExclusive } : fromTurnOrRange;
1459
+ if (!Number.isFinite(range.fromTurn) && range.fromAtSeq === void 0) return [];
1460
+ const inRange = checkpoints.filter((checkpoint) => {
1461
+ if (range.fromAtSeq !== void 0) {
1462
+ if (checkpoint.atSeq < range.fromAtSeq) return false;
1463
+ if (range.untilAtSeqExclusive !== void 0 && checkpoint.atSeq >= range.untilAtSeqExclusive) {
1464
+ return false;
1465
+ }
1466
+ return true;
1467
+ }
1468
+ return checkpoint.turn >= range.fromTurn && (range.untilTurnExclusive === void 0 || checkpoint.turn < range.untilTurnExclusive);
1469
+ }).slice().sort((left, right) => left.atSeq - right.atSeq || left.turn - right.turn);
1470
+ const byPath = /* @__PURE__ */ new Map();
1471
+ for (const checkpoint of inRange) {
1472
+ for (const file of checkpoint.files) {
1473
+ const previous = byPath.get(file.path);
1474
+ if (previous === void 0) {
1475
+ byPath.set(file.path, { earliest: file, latest: file });
1476
+ continue;
1477
+ }
1478
+ byPath.set(file.path, { earliest: previous.earliest, latest: file });
1479
+ }
1480
+ }
1481
+ const chained = [];
1482
+ for (const { earliest, latest } of byPath.values()) {
1483
+ const change = netFileChange(earliest, latest);
1484
+ if (change === null) continue;
1485
+ chained.push({
1486
+ path: earliest.path,
1487
+ change,
1488
+ beforeText: earliest.beforeText,
1489
+ beforeHash: earliest.beforeHash,
1490
+ afterText: latest.afterText,
1491
+ afterHash: latest.afterHash
1492
+ });
1493
+ }
1494
+ return chained;
1495
+ }
1496
+
1497
+ // src/host/checkpoint/cut-store.ts
1498
+ import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
1499
+ import { chmod as chmod2, mkdir as mkdir2, readFile as readFile2, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
1500
+ import { basename as basename2, join as join4 } from "node:path";
1501
+ import { z } from "zod";
1502
+ var SCHEMA_VERSION = 1;
1503
+ var queues = /* @__PURE__ */ new Map();
1504
+ async function serialize2(key, operation) {
1505
+ const previous = queues.get(key) ?? Promise.resolve();
1506
+ const result = previous.then(operation);
1507
+ const tail = result.then(() => void 0, () => void 0);
1508
+ queues.set(key, tail);
1509
+ try {
1510
+ return await result;
1511
+ } finally {
1512
+ if (queues.get(key) === tail) queues.delete(key);
1513
+ }
1514
+ }
1515
+ var sessionIdSchema = z.string().min(1).transform((value) => value);
1516
+ var cutSchema = z.lazy(() => z.object({
1517
+ hideTurnsFrom: z.number().int().positive(),
1518
+ cutSeq: z.number().int().nonnegative(),
1519
+ restoredAtSeq: z.number().int().nonnegative(),
1520
+ draftPrompt: z.string(),
1521
+ scope: z.enum(["conversation", "conversation-and-files"]),
1522
+ journalId: z.string().min(1).optional(),
1523
+ previous: cutSchema.nullable()
1524
+ }).strict());
1525
+ var fileSchema = z.object({
1526
+ schemaVersion: z.literal(SCHEMA_VERSION),
1527
+ sessionId: sessionIdSchema,
1528
+ cut: cutSchema.nullable()
1529
+ }).strict();
1530
+ function digest2(value) {
1531
+ return createHash2("sha256").update(value).digest("hex");
1532
+ }
1533
+ function isMissing2(error) {
1534
+ return typeof error === "object" && error !== null && error.code === "ENOENT";
1535
+ }
1536
+ async function removeIfPresent2(path) {
1537
+ try {
1538
+ await unlink2(path);
1539
+ } catch (error) {
1540
+ if (!isMissing2(error)) throw error;
1541
+ }
1542
+ }
1543
+ async function writeAtomic2(path, value) {
1544
+ const temporary = join4(join4(path, ".."), `.${basename2(path)}.${randomUUID3()}.tmp`);
1545
+ try {
1546
+ await writeFile2(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
1547
+ await rename2(temporary, path);
1548
+ await chmod2(path, 384);
1549
+ } finally {
1550
+ await removeIfPresent2(temporary);
1551
+ }
1552
+ }
1553
+ function isWithdrawnByCut(cut, seq) {
1554
+ return seq > cut.cutSeq && seq <= cut.restoredAtSeq;
1555
+ }
1556
+ var SessionCutStore = class {
1557
+ constructor(root) {
1558
+ this.root = root;
1559
+ this.directory = join4(root, "sessions");
1560
+ this.rootKey = join4(root, ".");
1561
+ }
1562
+ root;
1563
+ directory;
1564
+ rootKey;
1565
+ async get(sessionId) {
1566
+ await mkdir2(this.directory, { recursive: true, mode: 448 });
1567
+ const path = this.pathOf(sessionId);
1568
+ let stored;
1569
+ try {
1570
+ stored = JSON.parse(await readFile2(path, "utf8"));
1571
+ } catch (error) {
1572
+ if (isMissing2(error)) return null;
1573
+ throw error;
1574
+ }
1575
+ const parsed = fileSchema.safeParse(stored);
1576
+ if (!parsed.success) return null;
1577
+ return parsed.data.cut;
1578
+ }
1579
+ async set(sessionId, cut) {
1580
+ return serialize2(`${this.rootKey}\0${sessionId}`, async () => {
1581
+ await mkdir2(this.directory, { recursive: true, mode: 448 });
1582
+ const path = this.pathOf(sessionId);
1583
+ if (cut === null) {
1584
+ await removeIfPresent2(path);
1585
+ return null;
1586
+ }
1587
+ await writeAtomic2(path, {
1588
+ schemaVersion: SCHEMA_VERSION,
1589
+ sessionId,
1590
+ cut
1591
+ });
1592
+ return cut;
1593
+ });
1594
+ }
1595
+ pathOf(sessionId) {
1596
+ return join4(this.directory, `${digest2(sessionId)}.json`);
1597
+ }
1598
+ };
1599
+
1600
+ // src/host/checkpoint/cut-filter.ts
1601
+ function deriveMessagesWithCut(session, cut) {
1602
+ if (cut === null || cut === void 0) {
1603
+ }
1604
+ const events = session.snapshotEvents();
1605
+ const bySeq = new Map(events.map((event) => [Number(event.seq), event]));
1606
+ const messages = [];
1607
+ for (const seq of session.surface.nodes) {
1608
+ const value = Number(seq);
1609
+ const event = bySeq.get(value);
1610
+ if (event === void 0) continue;
1611
+ const keepSystem = event.type === "system/message";
1612
+ if (cut !== null && cut !== void 0 && isWithdrawnByCut(cut, value) && !keepSystem) continue;
1613
+ const message = session.deriveEventMessage(event);
1614
+ if (message !== null) messages.push(message);
1615
+ }
1616
+ return messages;
1617
+ }
1618
+
1619
+ // src/host/checkpoint/cut-live.ts
1620
+ function installSessionCutFilter(ctx, options) {
1621
+ const patched = /* @__PURE__ */ new WeakSet();
1622
+ const patchSession = (session) => {
1623
+ if (patched.has(session)) return;
1624
+ patched.add(session);
1625
+ const native = session.deriveMessages.bind(session);
1626
+ session.deriveMessages = () => {
1627
+ const cut = options.cache.get(session.id);
1628
+ if (cut === void 0 || cut === null) return native();
1629
+ return deriveMessagesWithCut(session, cut);
1630
+ };
1631
+ };
1632
+ const warm = async (sessionId) => {
1633
+ if (options.cache.has(sessionId)) return;
1634
+ const cut = await options.store.get(sessionId);
1635
+ options.cache.set(sessionId, cut);
1636
+ };
1637
+ const disposers = [];
1638
+ disposers.push(ctx.on("agent/pre-step", async (payload, next) => {
1639
+ const agent = payload.agent;
1640
+ patchSession(agent.session);
1641
+ await warm(agent.session.id);
1642
+ return next();
1643
+ }));
1644
+ const agents = ctx.agents;
1645
+ if (agents !== void 0 && typeof agents.get === "function") {
1646
+ const inner = agents.get.bind(agents);
1647
+ agents.get = ((id) => {
1648
+ const agent = inner(id);
1649
+ if (agent?.session !== void 0) {
1650
+ patchSession(agent.session);
1651
+ void warm(agent.session.id);
1652
+ }
1653
+ return agent;
1654
+ });
1655
+ disposers.push(() => {
1656
+ if (agents.get !== inner) agents.get = inner;
1657
+ });
1658
+ }
1659
+ return () => {
1660
+ while (disposers.length > 0) disposers.pop()?.();
1661
+ };
1662
+ }
1663
+ function syncCutCache(cache, sessionId, cut) {
1664
+ cache.set(sessionId, cut);
1665
+ }
1666
+
1050
1667
  // src/host/checkpoint/service.ts
1051
1668
  var surfaceEventTypes = /* @__PURE__ */ new Set(["system/message", "developer/message", "user/message", "assistant/message", "tool/result"]);
1669
+ var PROMPT_PREVIEW_MAX = 96;
1670
+ function checkpointPromptPreview(prompt, max = PROMPT_PREVIEW_MAX) {
1671
+ const normalized = prompt.replace(/\s+/g, " ").trim();
1672
+ if (normalized.length <= max) return normalized;
1673
+ return `${normalized.slice(0, Math.max(0, max - 1)).trimEnd()}\u2026`;
1674
+ }
1675
+ function toCheckpointTurnSummary(checkpoint, options = {}) {
1676
+ const rolledBack = options.rolledBack ?? false;
1677
+ const tip = options.tip ?? false;
1678
+ const recovered = options.recoveredPrompt?.trim() ?? "";
1679
+ const prompt = checkpoint.prompt.trim() !== "" ? checkpoint.prompt : recovered;
1680
+ const gaps = prompt.trim() === "" ? checkpoint.gaps : checkpoint.gaps.filter((gap) => !(gap.type === "prompt" && gap.reason === "non-text-content"));
1681
+ return {
1682
+ turn: checkpoint.turn,
1683
+ coverage: gaps.length === 0 ? "complete" : "partial",
1684
+ fileCount: checkpoint.files.length,
1685
+ createdAt: checkpoint.createdAt,
1686
+ atSeq: checkpoint.atSeq,
1687
+ prompt,
1688
+ promptPreview: checkpointPromptPreview(prompt),
1689
+ files: checkpoint.files.map((file) => ({ path: file.path, change: file.change })),
1690
+ gaps,
1691
+ rolledBack,
1692
+ tip
1693
+ };
1694
+ }
1695
+ function summaryFromClosedTurn(events, turn, options = {}) {
1696
+ const turnStart = events.find(
1697
+ (event) => event.type === "turn/start" && event.data.turn === turn
1698
+ );
1699
+ if (turnStart === void 0) return null;
1700
+ const prompt = recoverTurnPrompt(events, turn);
1701
+ return {
1702
+ turn,
1703
+ coverage: "complete",
1704
+ fileCount: 0,
1705
+ createdAt: options.now ?? Date.now(),
1706
+ atSeq: checkpointAtSeq(Number(turnStart.seq)),
1707
+ prompt,
1708
+ promptPreview: checkpointPromptPreview(prompt),
1709
+ files: [],
1710
+ gaps: [],
1711
+ rolledBack: options.rolledBack ?? false,
1712
+ tip: options.tip ?? false
1713
+ };
1714
+ }
1715
+ function cutViewOf(cut) {
1716
+ return {
1717
+ hideTurnsFrom: cut.hideTurnsFrom,
1718
+ cutSeq: cut.cutSeq,
1719
+ restoredAtSeq: cut.restoredAtSeq,
1720
+ draftPrompt: cut.draftPrompt,
1721
+ scope: cut.scope
1722
+ };
1723
+ }
1724
+ function windowFromCut(cut) {
1725
+ if (cut === null || cut === void 0) return void 0;
1726
+ return {
1727
+ tipTurn: cut.hideTurnsFrom,
1728
+ hideTurnsFrom: cut.hideTurnsFrom,
1729
+ continueAfterSeq: cut.restoredAtSeq
1730
+ };
1731
+ }
1052
1732
  var CheckpointRollbackError = class extends Error {
1053
1733
  constructor(code, unavailable = [], conflicts = []) {
1054
1734
  super(code);
@@ -1061,28 +1741,9 @@ var CheckpointRollbackError = class extends Error {
1061
1741
  unavailable;
1062
1742
  conflicts;
1063
1743
  };
1064
- function rollbackMarkerId(turn, journalId, scope) {
1065
- const tag = scope === "conversation" ? "c:" : "";
1066
- return MessageId(`${ROLLBACK_PREFIX}${turn}:${tag}${journalId}`);
1067
- }
1068
1744
  function undoCopyId(journalId, index) {
1069
1745
  return MessageId(`${UNDO_PREFIX}${journalId}:${index}`);
1070
1746
  }
1071
- function rollbackIdOf(id) {
1072
- const start = indexOfRollbackPrefix(id);
1073
- return start >= 0 ? id.slice(start) : id;
1074
- }
1075
- function scopeOfMarkerId(id) {
1076
- const rolled = rollbackIdOf(id);
1077
- for (const prefix of [ROLLBACK_PREFIX, LEGACY_ROLLBACK_PREFIX]) {
1078
- const pattern = new RegExp(`^${prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\d+:c:`);
1079
- if (pattern.test(rolled)) return "conversation";
1080
- }
1081
- return "conversation-and-files";
1082
- }
1083
- function scopeOfMarker(event) {
1084
- return scopeOfMarkerId(event.data.id);
1085
- }
1086
1747
  function isRollbackMarker(event, turn) {
1087
1748
  if (event?.type !== "user/message" || event.data.source.kind !== "checkpoint-rollback" || event.data.source.form !== "notice" || event.data.content.length === 0) return false;
1088
1749
  const prefixes = turn === void 0 ? [ROLLBACK_PREFIX, LEGACY_ROLLBACK_PREFIX] : [`${ROLLBACK_PREFIX}${turn}:`, `${LEGACY_ROLLBACK_PREFIX}${turn}:`];
@@ -1093,7 +1754,42 @@ function isRollbackMarker(event, turn) {
1093
1754
  const embedded = event.data.id.slice(original);
1094
1755
  return prefixes.some((prefix) => embedded.startsWith(prefix));
1095
1756
  }
1096
- function surfaceMessageId(event) {
1757
+ function surfaceOpOf(event) {
1758
+ const op = event.surfaceOp;
1759
+ if (op === "append") return "append";
1760
+ if (typeof op !== "object" || op === null) return void 0;
1761
+ const record2 = op;
1762
+ if (record2.op !== "replace") return void 0;
1763
+ if (typeof record2.startSeq !== "number" || typeof record2.endSeq !== "number") return void 0;
1764
+ return { op: "replace", startSeq: record2.startSeq, endSeq: record2.endSeq };
1765
+ }
1766
+ function markerStillActive(marker, events) {
1767
+ return !events.some((event) => {
1768
+ if (event.seq <= marker.seq) return false;
1769
+ const op = surfaceOpOf(event);
1770
+ return op !== void 0 && op !== "append" && op.startSeq <= marker.seq && op.endSeq >= marker.seq;
1771
+ });
1772
+ }
1773
+ function activeRollbackWindow(events, surfaceNodes) {
1774
+ const onSurface = surfaceNodes === void 0 ? void 0 : new Set(surfaceNodes.map((node) => Number(node)));
1775
+ let tipTurn;
1776
+ let continueAfterSeq;
1777
+ for (const event of events) {
1778
+ if (!isRollbackMarker(event) || !markerStillActive(event, events)) continue;
1779
+ if (onSurface !== void 0 && !onSurface.has(Number(event.seq))) continue;
1780
+ const turn = turnFromRollbackId(event.data.id);
1781
+ if (turn === void 0) continue;
1782
+ tipTurn = tipTurn === void 0 ? turn : Math.min(tipTurn, turn);
1783
+ continueAfterSeq = continueAfterSeq === void 0 ? Number(event.seq) : Math.max(continueAfterSeq, Number(event.seq));
1784
+ }
1785
+ if (tipTurn === void 0 || continueAfterSeq === void 0) return void 0;
1786
+ return { tipTurn, hideTurnsFrom: tipTurn, continueAfterSeq };
1787
+ }
1788
+ function isRolledBackCheckpoint(turn, atSeq, window) {
1789
+ if (window === void 0 || turn < window.hideTurnsFrom) return false;
1790
+ return atSeq < window.continueAfterSeq;
1791
+ }
1792
+ function surfaceMessageId2(event) {
1097
1793
  switch (event.type) {
1098
1794
  case "user/message":
1099
1795
  return event.data.id;
@@ -1107,29 +1803,19 @@ function surfaceMessageId(event) {
1107
1803
  }
1108
1804
  }
1109
1805
  function isUndoCopy(event) {
1110
- const id = surfaceMessageId(event);
1806
+ const id = surfaceMessageId2(event);
1111
1807
  return id !== null && isUndoId(id);
1112
1808
  }
1113
1809
  function isUndoCopyAt(event, expected) {
1114
- const id = surfaceMessageId(event);
1810
+ const id = surfaceMessageId2(event);
1115
1811
  return id === expected || (id?.startsWith(`${expected}:`) ?? false);
1116
1812
  }
1117
- function logicalSeq(event) {
1118
- if (isUndoCopy(event)) {
1119
- const match = surfaceMessageId(event)?.match(/:(\d+)(?::dsh-(?:agent|composer)-enhancer:rollback:.*)?$/);
1120
- if (match !== null && match !== void 0) return SessionSeq(Number(match[1]));
1121
- }
1122
- return event.seq;
1123
- }
1124
1813
  function isOwnReplacement(event) {
1125
1814
  return isRollbackMarker(event) || isUndoCopy(event);
1126
1815
  }
1127
1816
  function isProtectedSystemMessage(event) {
1128
1817
  return event?.type === "system/message";
1129
1818
  }
1130
- function rollbackSurfaceNodes(events, candidates) {
1131
- return candidates.filter((node) => !isProtectedSystemMessage(events[node]));
1132
- }
1133
1819
  function abortError() {
1134
1820
  return new DOMException("Checkpoint rollback was cancelled", "AbortError");
1135
1821
  }
@@ -1139,196 +1825,22 @@ function textOf(event) {
1139
1825
  return event.data.content.flatMap((block) => block.type === "text" ? [block.text] : []).join("");
1140
1826
  case "system/message":
1141
1827
  case "developer/message":
1142
- case "assistant/message":
1143
- case "tool/result":
1144
- return event.data.message.content.flatMap((block) => block.type === "text" ? [block.text] : []).join("");
1145
- default:
1146
- return "";
1147
- }
1148
- }
1149
- function operationOf(request) {
1150
- return request.operation ?? "rollback";
1151
- }
1152
- function scopeOf(request) {
1153
- return request.scope ?? "conversation-and-files";
1154
- }
1155
- function directionOf(operation) {
1156
- return operation === "rollback" ? "rollback" : "undo";
1157
- }
1158
- function sourceEvents(events, marker) {
1159
- if (marker.surfaceOp === "append") {
1160
- if (marker.sourceEventSeqs?.length !== 1) return null;
1161
- const original = events[marker.sourceEventSeqs[0]];
1162
- return isRollbackMarker(original) ? sourceEvents(events, original) : null;
1163
- }
1164
- if (marker.sourceEventSeqs === void 0 || marker.sourceEventSeqs.length === 0) return null;
1165
- const sources = [];
1166
- for (const seq of marker.sourceEventSeqs) {
1167
- const event = events[seq];
1168
- if (event === void 0 || !surfaceEventTypes.has(event.type)) return null;
1169
- sources.push(event);
1170
- }
1171
- if (sources[0]?.type !== "user/message") return null;
1172
- return sources;
1173
- }
1174
- function nextTurnNumber(events) {
1175
- let max = 0;
1176
- for (const event of events) {
1177
- if (event.type === "turn/start") max = Math.max(max, event.data.turn);
1178
- }
1179
- return max + 1;
1180
- }
1181
- function undoTurnAfterMarker(events, markerSeq) {
1182
- for (const event of events) {
1183
- if (Number(event.seq) > Number(markerSeq) && event.type === "turn/start") {
1184
- return event.data.turn;
1185
- }
1186
- }
1187
- throw new Error("Partial undo is missing its turn/start");
1188
- }
1189
- function isUndoTurnChrome(event) {
1190
- return event.type === "turn/start" || event.type === "turn/end" || event.type === "step/start" || event.type === "step/end";
1191
- }
1192
- function toolCallsOf(event) {
1193
- const calls = [];
1194
- for (const block of event.data.message.content) {
1195
- if (block.type !== "tool-call") continue;
1196
- calls.push({ callId: block.id, name: block.name, arguments: block.arguments });
1197
- }
1198
- return calls;
1199
- }
1200
- function appendUndoToolCalls(session, calls, turn, step, openCalls) {
1201
- for (const call of calls) {
1202
- session.append("tool/call", {
1203
- turn,
1204
- step,
1205
- callId: call.callId,
1206
- name: call.name,
1207
- arguments: call.arguments
1208
- });
1209
- openCalls.set(String(call.callId), call);
1210
- }
1211
- }
1212
- function settleOpenUndoToolCalls(session, journalId, turn, step, openCalls) {
1213
- for (const call of openCalls.values()) {
1214
- session.append("tool/result", {
1215
- turn,
1216
- step,
1217
- message: {
1218
- id: MessageId(`${UNDO_PREFIX}${journalId}:orphan:${call.callId}`),
1219
- role: "tool",
1220
- source: { kind: "tool", callId: call.callId },
1221
- toolCallId: call.callId,
1222
- isError: true,
1223
- content: [{
1224
- type: "text",
1225
- text: "The tool call was restored without a recorded result."
1226
- }]
1227
- },
1228
- error: {
1229
- name: "UndoOrphanToolCall",
1230
- code: "UNDO_ORPHAN_TOOL_CALL",
1231
- reason: "Restored assistant tool call had no matching tool/result in the rollback surface."
1232
- }
1233
- }, { surfaceOp: "append" });
1234
- }
1235
- openCalls.clear();
1236
- }
1237
- function ensureCopiedAssistantToolCalls(session, events, journalId, completed, turn, step, openCalls) {
1238
- const first = events.find((event) => isUndoCopyAt(event, undoCopyId(journalId, 0)));
1239
- if (first === void 0) return;
1240
- const undoStart = Number(first.seq);
1241
- const started = /* @__PURE__ */ new Set();
1242
- const settled = /* @__PURE__ */ new Set();
1243
- for (const event of events) {
1244
- if (Number(event.seq) < undoStart) continue;
1245
- if (event.type === "tool/call") started.add(String(event.data.callId));
1246
- if (event.type === "tool/result") settled.add(String(event.data.message.toolCallId));
1247
- }
1248
- for (let index = 0; index < completed; index += 1) {
1249
- const event = events.find((candidate) => isUndoCopyAt(candidate, undoCopyId(journalId, index)));
1250
- if (event?.type !== "assistant/message") continue;
1251
- const calls = toolCallsOf(event);
1252
- appendUndoToolCalls(
1253
- session,
1254
- calls.filter((call) => !started.has(String(call.callId))),
1255
- turn,
1256
- step,
1257
- openCalls
1258
- );
1259
- for (const call of calls) {
1260
- if (!settled.has(String(call.callId))) openCalls.set(String(call.callId), call);
1261
- }
1262
- }
1263
- }
1264
- function countPartialUndoCopies(events, first, journalId, tip) {
1265
- let completed = 0;
1266
- let cursor = Number(first.seq);
1267
- while (cursor <= tip) {
1268
- const event = events[SessionSeq(cursor)];
1269
- if (event === void 0) throw new CheckpointRollbackError("ROLLBACK_RECOVERY_FAILED");
1270
- if (isUndoCopyAt(event, undoCopyId(journalId, completed))) {
1271
- completed += 1;
1272
- cursor += 1;
1273
- continue;
1274
- }
1275
- if (event.type === "tool/call" && completed > 0) {
1276
- cursor += 1;
1277
- continue;
1278
- }
1279
- throw new CheckpointRollbackError("ROLLBACK_RECOVERY_FAILED");
1280
- }
1281
- return completed;
1282
- }
1283
- function appendUndoCopy(session, source, journalId, index, markerSeq, turn, step, openCalls) {
1284
- const copyId = MessageId(`${undoCopyId(journalId, index)}:${source.seq}`);
1285
- const id = isRollbackMarker(source) ? MessageId(`${copyId}:${source.data.id}`) : copyId;
1286
- if (source.type === "user/message") {
1287
- return session.append("user/message", { ...source.data, id }, index === 0 ? {
1288
- surfaceOp: { op: "replace", startSeq: markerSeq, endSeq: markerSeq },
1289
- sourceEventSeqs: [markerSeq, source.seq]
1290
- } : {
1291
- surfaceOp: "append",
1292
- sourceEventSeqs: [source.seq]
1293
- });
1294
- }
1295
- if (index === 0) throw new Error("The first restored surface event must be a user message");
1296
- switch (source.type) {
1297
- case "assistant/message": {
1298
- const event = session.append("assistant/message", {
1299
- ...source.data,
1300
- turn,
1301
- step,
1302
- message: { ...source.data.message, id }
1303
- }, { surfaceOp: "append" });
1304
- appendUndoToolCalls(session, toolCallsOf(source), turn, step, openCalls);
1305
- return event;
1306
- }
1307
- case "system/message":
1308
- return session.append("system/message", {
1309
- ...source.data,
1310
- turn,
1311
- step,
1312
- message: { ...source.data.message, id }
1313
- }, { surfaceOp: "append", sourceEventSeqs: [source.seq] });
1314
- case "developer/message":
1315
- return session.append("developer/message", {
1316
- ...source.data,
1317
- turn,
1318
- step,
1319
- message: { ...source.data.message, id }
1320
- }, { surfaceOp: "append", sourceEventSeqs: [source.seq] });
1321
- case "tool/result": {
1322
- openCalls.delete(String(source.data.message.toolCallId));
1323
- return session.append("tool/result", {
1324
- ...source.data,
1325
- turn,
1326
- step,
1327
- message: { ...source.data.message, id }
1328
- }, { surfaceOp: "append", sourceEventSeqs: [source.seq] });
1329
- }
1828
+ case "assistant/message":
1829
+ case "tool/result":
1830
+ return event.data.message.content.flatMap((block) => block.type === "text" ? [block.text] : []).join("");
1831
+ default:
1832
+ return "";
1330
1833
  }
1331
1834
  }
1835
+ function operationOf(request) {
1836
+ return request.operation ?? "rollback";
1837
+ }
1838
+ function scopeOf(request) {
1839
+ return request.scope ?? "conversation-and-files";
1840
+ }
1841
+ function directionOf(operation) {
1842
+ return operation === "rollback" ? "rollback" : "undo";
1843
+ }
1332
1844
  var CheckpointRollbackService = class {
1333
1845
  constructor(options) {
1334
1846
  this.options = options;
@@ -1344,6 +1856,12 @@ var CheckpointRollbackService = class {
1344
1856
  execute(request, signal) {
1345
1857
  return this.track(this.runExecute(request, signal));
1346
1858
  }
1859
+ summaries(request, signal) {
1860
+ return this.track(this.runSummaries(request, signal));
1861
+ }
1862
+ getCut(request, signal) {
1863
+ return this.track(this.runGetCut(request, signal));
1864
+ }
1347
1865
  recover() {
1348
1866
  if (this.recovery !== void 0) return this.recovery;
1349
1867
  const operation = this.track(this.runRecovery());
@@ -1391,7 +1909,11 @@ var CheckpointRollbackService = class {
1391
1909
  try {
1392
1910
  linked.signal.throwIfAborted();
1393
1911
  if ((await this.options.store.listPendingJournals()).length > 0) {
1394
- throw new CheckpointRollbackError("ROLLBACK_RECOVERY_FAILED");
1912
+ try {
1913
+ await this.recover();
1914
+ } catch {
1915
+ throw new CheckpointRollbackError("ROLLBACK_RECOVERY_FAILED");
1916
+ }
1395
1917
  }
1396
1918
  linked.signal.throwIfAborted();
1397
1919
  return (await this.evaluate(request)).preview;
@@ -1401,6 +1923,152 @@ var CheckpointRollbackService = class {
1401
1923
  linked.cleanup();
1402
1924
  }
1403
1925
  }
1926
+ async runSummaries(request, callerSignal) {
1927
+ const linked = this.linkedSignal([callerSignal]);
1928
+ try {
1929
+ linked.signal.throwIfAborted();
1930
+ if (this.options.isEnabled?.() === false) {
1931
+ return {
1932
+ sessionId: request.sessionId,
1933
+ activity: { turns: 0, steps: 0, checkpoints: 0, liveCheckpoints: 0 },
1934
+ turns: []
1935
+ };
1936
+ }
1937
+ await this.options.awaitCaptures?.();
1938
+ linked.signal.throwIfAborted();
1939
+ const checkpoints = await this.options.store.list(request.sessionId);
1940
+ const liveCut = await this.readCut(request.sessionId);
1941
+ const adapter = this.options.resolveSession(request.sessionId);
1942
+ const events = adapter?.readEvents() ?? [];
1943
+ const surfaceNodes = adapter?.session.surface.nodes;
1944
+ const tipWindow = events.length === 0 ? void 0 : activeRollbackWindow(events, surfaceNodes);
1945
+ const window = windowFromCut(liveCut) ?? tipWindow;
1946
+ const shells = undoShellRanges(events);
1947
+ const kept = events.length === 0 ? checkpoints : checkpoints.filter((checkpoint) => checkpoint.files.length > 0 || !isUndoShellCheckpoint(checkpoint.atSeq, shells));
1948
+ if (kept.length !== checkpoints.length) {
1949
+ await this.options.store.replace(request.sessionId, kept);
1950
+ }
1951
+ void this.options.store.purgeSettledJournals().catch(() => void 0);
1952
+ const tipAtSeq = liveCut?.cutSeq;
1953
+ const byAtSeq = /* @__PURE__ */ new Map();
1954
+ for (const checkpoint of kept) {
1955
+ const recoveredPrompt = checkpoint.prompt.trim() === "" ? recoverTurnPrompt(events, checkpoint.turn) : "";
1956
+ const rolledBack = isRolledBackCheckpoint(checkpoint.turn, checkpoint.atSeq, window);
1957
+ const tip = tipAtSeq !== void 0 ? checkpoint.atSeq === tipAtSeq : window !== void 0 && checkpoint.turn === window.tipTurn;
1958
+ const summary = toCheckpointTurnSummary(checkpoint, {
1959
+ rolledBack,
1960
+ tip,
1961
+ recoveredPrompt
1962
+ });
1963
+ const previous = byAtSeq.get(checkpoint.atSeq);
1964
+ if (previous !== void 0 && previous.fileCount > 0 && summary.fileCount === 0) continue;
1965
+ byAtSeq.set(checkpoint.atSeq, summary);
1966
+ }
1967
+ const live = adapter;
1968
+ if (live != null && events.length > 0) {
1969
+ const closedStarts = [];
1970
+ for (let index = 0; index < events.length; index += 1) {
1971
+ const event = events[index];
1972
+ if (event.type !== "turn/start") continue;
1973
+ const turn = event.data.turn;
1974
+ const ended = events.slice(index + 1).some((item) => item.type === "turn/end" && item.data.turn === turn && Number(item.seq) > Number(event.seq));
1975
+ if (ended) closedStarts.push(event);
1976
+ }
1977
+ const backfilled = [];
1978
+ for (const event of closedStarts) {
1979
+ const atSeq = checkpointAtSeq(Number(event.seq));
1980
+ if (byAtSeq.has(atSeq)) continue;
1981
+ const soft = synthesizeCheckpoint({
1982
+ sessionId: request.sessionId,
1983
+ session: {
1984
+ format: live.session.header.version,
1985
+ preset: live.session.header.agentPreset ?? null
1986
+ },
1987
+ pluginVersion: this.options.pluginVersion,
1988
+ turn: event.data.turn,
1989
+ events,
1990
+ createId: this.options.createId,
1991
+ now: this.options.now
1992
+ });
1993
+ if (soft !== null) {
1994
+ if (isUndoShellCheckpoint(soft.atSeq, shells) && soft.atSeq === atSeq) continue;
1995
+ const pinned = soft.atSeq === atSeq ? soft : { ...soft, atSeq };
1996
+ if (isUndoShellCheckpoint(pinned.atSeq, shells)) continue;
1997
+ backfilled.push(pinned);
1998
+ byAtSeq.set(
1999
+ atSeq,
2000
+ toCheckpointTurnSummary(pinned, {
2001
+ rolledBack: isRolledBackCheckpoint(pinned.turn, pinned.atSeq, window),
2002
+ tip: tipAtSeq !== void 0 ? pinned.atSeq === tipAtSeq : window !== void 0 && pinned.turn === window.tipTurn
2003
+ })
2004
+ );
2005
+ continue;
2006
+ }
2007
+ const row = summaryFromClosedTurn(events, event.data.turn, {
2008
+ rolledBack: isRolledBackCheckpoint(event.data.turn, atSeq, window),
2009
+ tip: tipAtSeq !== void 0 ? atSeq === tipAtSeq : window !== void 0 && event.data.turn === window.tipTurn,
2010
+ now: this.options.now?.()
2011
+ });
2012
+ if (row !== null && !isUndoShellCheckpoint(atSeq, shells)) {
2013
+ byAtSeq.set(atSeq, { ...row, atSeq });
2014
+ }
2015
+ }
2016
+ for (const soft of backfilled) {
2017
+ try {
2018
+ await this.options.store.save(soft);
2019
+ } catch {
2020
+ }
2021
+ }
2022
+ }
2023
+ const turns = [...byAtSeq.values()].sort((left, right) => left.atSeq - right.atSeq || left.turn - right.turn || left.createdAt - right.createdAt);
2024
+ const liveCheckpoints = turns.filter((turn) => !turn.rolledBack).length;
2025
+ const activity = liveActivityStats(events, {
2026
+ hideTurnsFrom: window?.hideTurnsFrom,
2027
+ continueAfterSeq: window?.continueAfterSeq,
2028
+ checkpointCount: turns.length,
2029
+ liveCheckpointCount: liveCheckpoints
2030
+ });
2031
+ return {
2032
+ sessionId: request.sessionId,
2033
+ activity,
2034
+ turns
2035
+ };
2036
+ } catch (error) {
2037
+ throw this.sanitize(error, linked.signal);
2038
+ } finally {
2039
+ linked.cleanup();
2040
+ }
2041
+ }
2042
+ async runGetCut(request, callerSignal) {
2043
+ const linked = this.linkedSignal([callerSignal]);
2044
+ try {
2045
+ linked.signal.throwIfAborted();
2046
+ const cut = await this.readCut(request.sessionId);
2047
+ return {
2048
+ sessionId: request.sessionId,
2049
+ cut: cut === null ? null : cutViewOf(cut)
2050
+ };
2051
+ } catch (error) {
2052
+ throw this.sanitize(error, linked.signal);
2053
+ } finally {
2054
+ linked.cleanup();
2055
+ }
2056
+ }
2057
+ async readCut(sessionId) {
2058
+ const cached = this.options.cutCache?.get(sessionId);
2059
+ if (cached !== void 0) return cached;
2060
+ if (this.options.cutStore === void 0) return null;
2061
+ const cut = await this.options.cutStore.get(sessionId);
2062
+ if (this.options.cutCache !== void 0) syncCutCache(this.options.cutCache, sessionId, cut);
2063
+ return cut;
2064
+ }
2065
+ async writeCut(sessionId, cut) {
2066
+ if (this.options.cutStore === void 0) {
2067
+ throw new CheckpointRollbackError("ROLLBACK_FAILED");
2068
+ }
2069
+ await this.options.cutStore.set(sessionId, cut);
2070
+ if (this.options.cutCache !== void 0) syncCutCache(this.options.cutCache, sessionId, cut);
2071
+ }
1404
2072
  async runExecute(request, callerSignal) {
1405
2073
  const linked = this.linkedSignal([callerSignal]);
1406
2074
  try {
@@ -1419,37 +2087,72 @@ var CheckpointRollbackService = class {
1419
2087
  const current = await this.evaluate(request, { withinMaintenance: true });
1420
2088
  const scope = this.effectiveScope(request, current);
1421
2089
  this.assertExecutable(current, scope);
1422
- if (current.adapter?.session !== adapter.session || current.surface === null) {
2090
+ if (current.adapter?.session.id !== adapter.session.id || current.surface === null) {
1423
2091
  throw new CheckpointRollbackError("ROLLBACK_UNAVAILABLE", ["session-changed"]);
1424
2092
  }
1425
2093
  const checkpoint = current.checkpoint;
1426
2094
  const operation = operationOf(request);
1427
2095
  const session = adapter.session;
1428
- const expectedSeq = session.seq;
1429
- const expectedNodes = [...session.surface.nodes];
1430
- const journalId = (this.options.createId ?? randomUUID3)();
2096
+ const expectedSeq = Number(session.seq);
2097
+ const journalId = (this.options.createId ?? randomUUID4)();
1431
2098
  const files = this.files(adapter, checkpoint, journalId);
1432
- const filesToRestore = scope === "conversation" ? [] : checkpoint.files;
1433
- await files.runTransaction(filesToRestore, async () => {
1434
- if (maintenance.signal.aborted) return { appended: false, synchronized: false };
1435
- const latest = this.options.resolveSession(request.sessionId);
1436
- if (latest?.session !== session || !this.canCommit(adapter, scope) || session.seq !== expectedSeq || session.surface.nodes.length !== expectedNodes.length || session.surface.nodes.some((node, index) => node !== expectedNodes[index])) {
1437
- return { appended: false, synchronized: false };
2099
+ const surface = current.surface;
2100
+ const filesToRestore = scope === "conversation" ? [] : this.trackedFilesForRestore(
2101
+ await this.options.store.list(request.sessionId),
2102
+ adapter,
2103
+ surface,
2104
+ await this.readCut(request.sessionId)
2105
+ );
2106
+ const draftPrompt = checkpoint.prompt.trim() !== "" ? checkpoint.prompt : recoverTurnPrompt(adapter.readEvents(), request.turn);
2107
+ if (operation === "rollback" && surface.operation === "rollback" && surface.alreadyRestored && filesToRestore.length === 0) {
2108
+ return {
2109
+ sessionId: request.sessionId,
2110
+ turn: request.turn,
2111
+ draft: draftPrompt
2112
+ };
2113
+ }
2114
+ if (maintenance.signal.aborted) {
2115
+ throw this.sanitize(abortError(), maintenance.signal);
2116
+ }
2117
+ if (adapter.session.id !== session.id || Number(adapter.session.seq) !== expectedSeq || !this.canCommit(adapter, scope)) {
2118
+ throw new CheckpointRollbackError("ROLLBACK_FAILED");
2119
+ }
2120
+ try {
2121
+ if (surface.operation === "rollback") {
2122
+ const previous = await this.readCut(request.sessionId);
2123
+ const next = {
2124
+ hideTurnsFrom: surface.turn,
2125
+ cutSeq: surface.cutSeq,
2126
+ restoredAtSeq: expectedSeq,
2127
+ draftPrompt,
2128
+ scope,
2129
+ ...filesToRestore.length > 0 ? { journalId } : {},
2130
+ previous
2131
+ };
2132
+ await this.writeCut(request.sessionId, next);
2133
+ } else {
2134
+ await this.writeCut(request.sessionId, surface.restoreCut);
1438
2135
  }
1439
- const restored = await this.appendAndSynchronize(
1440
- adapter,
1441
- current.surface,
1442
- journalId,
1443
- scope,
1444
- maintenance.signal
1445
- );
1446
- const appended = restored.appended && this.appendOccurred(adapter, journalId);
1447
- return { appended, synchronized: appended && restored.synchronized };
1448
- }, directionOf(operation));
2136
+ } catch (error) {
2137
+ if (error instanceof CheckpointRollbackError) throw error;
2138
+ throw new CheckpointRollbackError("ROLLBACK_FAILED");
2139
+ }
2140
+ const latest = this.options.resolveSession(request.sessionId);
2141
+ const syncTarget = latest !== void 0 && latest.session.id === session.id ? latest : adapter;
2142
+ try {
2143
+ await syncTarget.synchronize(maintenance.signal);
2144
+ } catch {
2145
+ }
2146
+ if (filesToRestore.length > 0) {
2147
+ await files.runTransaction(filesToRestore, async () => {
2148
+ if (maintenance.signal.aborted) return { appended: false, synchronized: false };
2149
+ return { appended: true, synchronized: true };
2150
+ }, directionOf(operation));
2151
+ }
1449
2152
  return {
1450
2153
  sessionId: request.sessionId,
1451
- turn: request.turn,
1452
- draft: operation === "rollback" ? checkpoint.prompt : ""
2154
+ turn: surface.operation === "undo" ? surface.tipTurn : request.turn,
2155
+ draft: operation === "rollback" ? draftPrompt : ""
1453
2156
  };
1454
2157
  } catch (error) {
1455
2158
  throw this.sanitize(error, maintenance.signal);
@@ -1470,54 +2173,6 @@ var CheckpointRollbackService = class {
1470
2173
  linked.cleanup();
1471
2174
  }
1472
2175
  }
1473
- async appendAndSynchronize(adapter, surface, journalId, scope, signal) {
1474
- try {
1475
- if (surface.operation === "rollback") this.appendRollback(adapter, surface, journalId, scope);
1476
- else this.appendUndo(adapter.session, surface.marker, surface.sources, journalId);
1477
- } catch {
1478
- return { appended: this.appendOccurred(adapter, journalId), synchronized: false };
1479
- }
1480
- try {
1481
- await adapter.synchronize(signal);
1482
- return { appended: true, synchronized: true };
1483
- } catch {
1484
- return { appended: true, synchronized: false };
1485
- }
1486
- }
1487
- appendRollback(adapter, surface, journalId, scope) {
1488
- const checkpointTurn = surface.turn;
1489
- const conversationOnly = scope === "conversation";
1490
- const summary = conversationOnly ? `Conversation rolled back before turn ${checkpointTurn}` : `Conversation and tracked files rolled back before turn ${checkpointTurn}`;
1491
- 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.`;
1492
- adapter.session.append("user/message", {
1493
- id: rollbackMarkerId(checkpointTurn, journalId, scope),
1494
- role: "user",
1495
- content: [{ type: "text", text: detail }],
1496
- source: { kind: "checkpoint-rollback", form: "notice", summary }
1497
- }, {
1498
- surfaceOp: {
1499
- op: "replace",
1500
- startSeq: surface.nodes[0],
1501
- endSeq: surface.nodes[surface.nodes.length - 1]
1502
- },
1503
- sourceEventSeqs: [...surface.nodes]
1504
- });
1505
- }
1506
- appendUndo(session, marker, sources, journalId, start = 0, openCalls = /* @__PURE__ */ new Map()) {
1507
- const events = session.snapshotEvents();
1508
- const turn = start === 0 ? nextTurnNumber(events) : undoTurnAfterMarker(events, marker.seq);
1509
- const step = 1;
1510
- if (start === 0) {
1511
- session.append("turn/start", { turn });
1512
- session.append("step/start", { turn, step });
1513
- }
1514
- for (let index = start; index < sources.length; index += 1) {
1515
- appendUndoCopy(session, sources[index], journalId, index, marker.seq, turn, step, openCalls);
1516
- }
1517
- settleOpenUndoToolCalls(session, journalId, turn, step, openCalls);
1518
- session.append("step/end", { turn, step });
1519
- session.append("turn/end", { turn, reason: { kind: "completed" } });
1520
- }
1521
2176
  async runRecovery() {
1522
2177
  try {
1523
2178
  this.lifetime.signal.throwIfAborted();
@@ -1543,10 +2198,8 @@ var CheckpointRollbackService = class {
1543
2198
  now: this.options.now
1544
2199
  });
1545
2200
  await files.recoverFiles(async (journal) => {
1546
- if (!this.appendOccurred(adapter, journal.id)) return false;
1547
- await this.resumeUndo(adapter, journal.id);
1548
- await adapter.synchronize(linked.signal);
1549
- return true;
2201
+ const cut = await this.readCut(sessionId);
2202
+ return cut?.journalId === journal.id;
1550
2203
  });
1551
2204
  } finally {
1552
2205
  linked.cleanup();
@@ -1558,39 +2211,15 @@ var CheckpointRollbackService = class {
1558
2211
  throw new CheckpointRollbackError("ROLLBACK_RECOVERY_FAILED");
1559
2212
  }
1560
2213
  }
1561
- async resumeUndo(adapter, journalId) {
1562
- const events = adapter.readEvents();
1563
- const first = events.find((event) => isUndoCopyAt(event, undoCopyId(journalId, 0)));
1564
- if (first === void 0) return;
1565
- if (first.type !== "user/message" || first.surfaceOp === "append" || first.surfaceOp.startSeq !== first.surfaceOp.endSeq) {
1566
- throw new CheckpointRollbackError("ROLLBACK_RECOVERY_FAILED");
1567
- }
1568
- const marker = events[first.surfaceOp.startSeq];
1569
- if (!isRollbackMarker(marker)) throw new CheckpointRollbackError("ROLLBACK_RECOVERY_FAILED");
1570
- const sources = sourceEvents(events, marker);
1571
- if (sources === null) throw new CheckpointRollbackError("ROLLBACK_RECOVERY_FAILED");
1572
- const tip = Number(adapter.session.seq) - 1;
1573
- const completed = countPartialUndoCopies(events, first, journalId, tip);
1574
- const openCalls = /* @__PURE__ */ new Map();
1575
- const turn = undoTurnAfterMarker(events, marker.seq);
1576
- const step = 1;
1577
- ensureCopiedAssistantToolCalls(
1578
- adapter.session,
1579
- events,
1580
- journalId,
1581
- completed,
1582
- turn,
1583
- step,
1584
- openCalls
1585
- );
1586
- this.appendUndo(adapter.session, marker, sources, journalId, completed, openCalls);
1587
- }
1588
2214
  async evaluate(request, options = {}) {
1589
2215
  const operation = operationOf(request);
1590
2216
  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
2217
  const adapter = this.options.resolveSession(request.sessionId) ?? null;
2218
+ const events = adapter?.readEvents() ?? [];
2219
+ const shells = undoShellRanges(events);
2220
+ const checkpoints = await this.options.store.list(request.sessionId);
2221
+ const candidates = checkpoints.filter((checkpoint) => checkpoint.turn === request.turn && (checkpoint.files.length > 0 || !isUndoShellCheckpoint(checkpoint.atSeq, shells)));
2222
+ let stored = (request.atSeq === void 0 ? void 0 : candidates.find((checkpoint) => checkpoint.atSeq === request.atSeq)) ?? candidates.find((checkpoint) => checkpoint.files.length > 0) ?? candidates[0] ?? null;
1594
2223
  if (stored === null && adapter !== null && operation === "rollback") {
1595
2224
  stored = synthesizeCheckpoint({
1596
2225
  sessionId: request.sessionId,
@@ -1627,77 +2256,159 @@ var CheckpointRollbackService = class {
1627
2256
  }
1628
2257
  let messages = [];
1629
2258
  let surface = null;
2259
+ const liveCut = await this.readCut(request.sessionId);
1630
2260
  if (stored !== null && adapter !== null && stored.atSeq >= 0) {
1631
- const events = adapter.readEvents();
1632
- const cut = resolveRollbackCut(events, stored.turn, stored.atSeq);
2261
+ const events2 = adapter.readEvents();
2262
+ const cut = resolveRollbackCut(events2, stored.turn, stored.atSeq);
1633
2263
  if (cut === null) {
1634
2264
  unavailable.push("unknown-surface");
1635
2265
  } else if (operation === "rollback") {
1636
- if (events.some((event) => Number(event.seq) > cut.cutSeq && typeof event.surfaceOp === "object" && !isOwnReplacement(event))) {
2266
+ if (events2.some((event) => Number(event.seq) > cut.cutSeq && typeof event.surfaceOp === "object" && !isOwnReplacement(event))) {
1637
2267
  unavailable.push("compacted-surface");
1638
2268
  }
1639
- const fromSurface = adapter.session.surface.nodes.filter((node) => Number(logicalSeq(events[node])) > cut.cutSeq);
1640
- const fromLog = events.filter((event) => Number(event.seq) > cut.cutSeq && surfaceEventTypes.has(event.type)).map((event) => SessionSeq(event.seq));
1641
- const candidates = fromSurface.length > 0 && fromSurface.every((node) => events[node] !== void 0 && surfaceEventTypes.has(events[node].type)) ? fromSurface.map((node) => SessionSeq(node)) : fromLog;
1642
- const nodes = rollbackSurfaceNodes(events, candidates);
1643
- if (nodes.length === 0) {
1644
- unavailable.push("unknown-surface");
2269
+ const withdrawn = events2.filter((event) => Number(event.seq) > cut.cutSeq && surfaceEventTypes.has(event.type) && !isProtectedSystemMessage(event));
2270
+ const alreadyRestored = liveCut !== null && liveCut.hideTurnsFrom === stored.turn && liveCut.cutSeq === cut.cutSeq && liveCut.restoredAtSeq === Number(adapter.session.seq);
2271
+ if (withdrawn.length === 0 || alreadyRestored) {
2272
+ unavailable.push("already-restored");
2273
+ surface = {
2274
+ operation,
2275
+ turn: stored.turn,
2276
+ cutSeq: cut.cutSeq,
2277
+ alreadyRestored: true
2278
+ };
2279
+ messages = [];
1645
2280
  } else {
1646
- surface = { operation, turn: stored.turn, nodes };
1647
- messages = nodes.map((node) => ({
1648
- seq: node,
1649
- type: events[node].type,
1650
- text: textOf(events[node])
2281
+ surface = {
2282
+ operation,
2283
+ turn: stored.turn,
2284
+ cutSeq: cut.cutSeq,
2285
+ alreadyRestored: false
2286
+ };
2287
+ messages = withdrawn.map((event) => ({
2288
+ seq: Number(event.seq),
2289
+ type: event.type,
2290
+ text: textOf(event)
1651
2291
  }));
1652
2292
  }
2293
+ } else if (liveCut === null) {
2294
+ unavailable.push("session-changed");
1653
2295
  } else {
1654
- const currentNodes = adapter.session.surface.nodes;
1655
- const markerSeq = currentNodes[currentNodes.length - 1];
1656
- const marker = markerSeq === void 0 ? void 0 : events[markerSeq];
1657
- const origin = marker?.surfaceOp === "append" && marker.sourceEventSeqs?.length === 1 ? events[marker.sourceEventSeqs[0]] : marker;
1658
- if (!isRollbackMarker(marker, stored.turn) || !isRollbackMarker(origin, stored.turn) || currentNodes.slice(0, -1).some((node) => {
1659
- const event = events[node];
1660
- if (isProtectedSystemMessage(event)) return false;
1661
- return Number(logicalSeq(event)) > cut.cutSeq;
1662
- }) || events.slice(Number(origin.seq) + 1).some((event) => !isRollbackMarker(event) && !isUndoCopy(event) && !isUndoTurnChrome(event))) {
1663
- unavailable.push("session-changed");
2296
+ const tipTurn = liveCut.hideTurnsFrom;
2297
+ let undoStored = tipTurn === stored.turn ? stored : checkpoints.find((item) => item.turn === tipTurn && !isUndoShellCheckpoint(item.atSeq, shells)) ?? null;
2298
+ if (undoStored === null) {
2299
+ undoStored = synthesizeCheckpoint({
2300
+ sessionId: request.sessionId,
2301
+ session: {
2302
+ format: adapter.session.header.version,
2303
+ preset: adapter.session.header.agentPreset ?? null
2304
+ },
2305
+ pluginVersion: this.options.pluginVersion,
2306
+ turn: tipTurn,
2307
+ events: events2,
2308
+ createId: this.options.createId,
2309
+ now: this.options.now
2310
+ });
2311
+ }
2312
+ if (undoStored === null) {
2313
+ unavailable.push("checkpoint-not-found");
1664
2314
  } else {
1665
- const sources = sourceEvents(events, marker);
1666
- if (sources === null || sources.some((event) => Number(event.seq) <= cut.cutSeq)) {
1667
- unavailable.push("unknown-surface");
1668
- } else {
1669
- surface = { operation, marker, sources };
1670
- messages = sources.map((event) => ({ seq: event.seq, type: event.type, text: textOf(event) }));
2315
+ if (tipTurn !== stored.turn) {
2316
+ const drop = /* @__PURE__ */ new Set([
2317
+ "checkpoint-not-found",
2318
+ "incomplete-checkpoint",
2319
+ "prompt-non-text-content",
2320
+ "workspace-capture-failed",
2321
+ "incompatible-session"
2322
+ ]);
2323
+ for (let index = unavailable.length - 1; index >= 0; index -= 1) {
2324
+ if (drop.has(unavailable[index])) unavailable.splice(index, 1);
2325
+ }
2326
+ if (undoStored.coverage !== "complete" || undoStored.gaps.length > 0) {
2327
+ unavailable.push("incomplete-checkpoint");
2328
+ for (const gap of undoStored.gaps) {
2329
+ unavailable.push(gap.type === "prompt" ? "prompt-non-text-content" : "workspace-capture-failed");
2330
+ }
2331
+ }
2332
+ if (undoStored.session.format !== adapter.session.header.version) {
2333
+ unavailable.push("incompatible-session");
2334
+ }
1671
2335
  }
2336
+ stored = undoStored;
2337
+ surface = {
2338
+ operation,
2339
+ tipTurn,
2340
+ live: liveCut,
2341
+ restoreCut: liveCut.previous
2342
+ };
2343
+ messages = events2.filter((event) => Number(event.seq) > liveCut.cutSeq && Number(event.seq) <= liveCut.restoredAtSeq && surfaceEventTypes.has(event.type) && !isProtectedSystemMessage(event)).map((event) => ({
2344
+ seq: Number(event.seq),
2345
+ type: event.type,
2346
+ text: textOf(event)
2347
+ }));
1672
2348
  }
1673
2349
  }
1674
2350
  }
2351
+ const trackedFiles = stored === null || adapter === null || surface === null ? [] : this.trackedFilesForRestore(checkpoints, adapter, surface, liveCut);
1675
2352
  let conflicts = [];
1676
2353
  if (stored !== null && adapter !== null) {
1677
2354
  try {
1678
- conflicts = await this.files(adapter, stored, "preview").verifyCurrent(stored.files, directionOf(operation));
2355
+ conflicts = await this.files(adapter, stored, "preview").verifyCurrent(trackedFiles, directionOf(operation));
1679
2356
  } catch (error) {
1680
2357
  if (error instanceof CheckpointFileError) conflicts = error.conflicts;
1681
2358
  else throw error;
1682
2359
  }
1683
2360
  }
1684
- const markerScope = surface?.operation === "undo" ? scopeOfMarker(surface.marker) : void 0;
2361
+ const cutWindow = windowFromCut(liveCut);
2362
+ const tipWindow = adapter !== null ? cutWindow ?? activeRollbackWindow(adapter.readEvents(), adapter.session.surface.nodes) : void 0;
2363
+ const previewTurn = surface?.operation === "undo" ? surface.tipTurn : request.turn;
2364
+ const undoScope = surface?.operation === "undo" ? surface.live.scope : void 0;
1685
2365
  return {
1686
2366
  checkpoint: stored,
1687
2367
  adapter,
1688
2368
  surface,
1689
2369
  preview: {
1690
2370
  sessionId: request.sessionId,
1691
- turn: request.turn,
2371
+ turn: previewTurn,
2372
+ ...stored === null ? {} : { atSeq: stored.atSeq },
1692
2373
  ...operation === "undo" ? { operation } : {},
1693
- ...markerScope === void 0 ? {} : { scope: markerScope },
2374
+ ...undoScope === void 0 ? {} : { scope: undoScope },
2375
+ ...tipWindow === void 0 ? {} : { tipTurn: tipWindow.tipTurn },
1694
2376
  messages,
1695
- files: stored?.files.map((file) => ({ path: file.path, change: file.change })) ?? [],
2377
+ files: trackedFiles.map((file) => ({ path: file.path, change: file.change })),
1696
2378
  conflicts,
1697
2379
  unavailable: [...new Set(unavailable)]
1698
2380
  }
1699
2381
  };
1700
2382
  }
2383
+ /**
2384
+ * Tracked text files for this restore/undo.
2385
+ * Rollback with no live cut: target turn → tip.
2386
+ * Rollback while a later cut is live: only the gap down to that tip (already restored).
2387
+ * Undo: reverse only the segment this tip added (down to previous tip, or open-ended).
2388
+ */
2389
+ trackedFilesForRestore(checkpoints, adapter, surface, liveCut) {
2390
+ const shells = undoShellRanges(adapter.readEvents());
2391
+ const real = checkpoints.filter((checkpoint) => checkpoint.files.length > 0 || !isUndoShellCheckpoint(checkpoint.atSeq, shells));
2392
+ if (surface.operation === "undo") {
2393
+ const previous = liveCut?.previous ?? null;
2394
+ return chainTrackedFiles(real, {
2395
+ fromTurn: surface.tipTurn,
2396
+ fromAtSeq: surface.live.cutSeq,
2397
+ ...previous !== null && previous.hideTurnsFrom > surface.tipTurn ? {
2398
+ untilTurnExclusive: previous.hideTurnsFrom,
2399
+ untilAtSeqExclusive: previous.cutSeq
2400
+ } : {}
2401
+ });
2402
+ }
2403
+ return chainTrackedFiles(real, {
2404
+ fromTurn: surface.turn,
2405
+ fromAtSeq: surface.cutSeq,
2406
+ ...liveCut !== null && liveCut.hideTurnsFrom > surface.turn ? {
2407
+ untilTurnExclusive: liveCut.hideTurnsFrom,
2408
+ untilAtSeqExclusive: liveCut.cutSeq
2409
+ } : {}
2410
+ });
2411
+ }
1701
2412
  effectiveScope(request, evaluation) {
1702
2413
  if (operationOf(request) === "undo") {
1703
2414
  return evaluation.preview.scope ?? "conversation-and-files";
@@ -1751,71 +2462,90 @@ var CheckpointRollbackService = class {
1751
2462
  };
1752
2463
 
1753
2464
  // src/host/checkpoint/store.ts
1754
- 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 join2 } from "node:path";
1757
- import { z } from "zod";
2465
+ import { createHash as createHash3, randomUUID as randomUUID5 } from "node:crypto";
2466
+ import { chmod as chmod3, mkdir as mkdir3, readdir as readdir2, readFile as readFile3, rename as rename3, unlink as unlink3, writeFile as writeFile3 } from "node:fs/promises";
2467
+ import { basename as basename3, join as join5 } from "node:path";
2468
+ import { z as z2 } from "zod";
1758
2469
  var MAX_CHECKPOINTS = 20;
1759
2470
  var checkpointQueues = /* @__PURE__ */ new Map();
1760
2471
  var journalQueues = /* @__PURE__ */ new Map();
1761
- async function serialize2(queues, key, operation) {
1762
- const previous = queues.get(key) ?? Promise.resolve();
2472
+ function byStoreOrder(left, right) {
2473
+ return left.createdAt - right.createdAt || left.atSeq - right.atSeq || left.turn - right.turn || left.id.localeCompare(right.id);
2474
+ }
2475
+ function retainCheckpoints(checkpoints, max = MAX_CHECKPOINTS) {
2476
+ if (checkpoints.length <= max) return [...checkpoints].sort(byStoreOrder);
2477
+ const rich = checkpoints.filter((checkpoint) => checkpoint.files.length > 0);
2478
+ const empty = checkpoints.filter((checkpoint) => checkpoint.files.length === 0);
2479
+ const emptyOldestFirst = [...empty].sort(byStoreOrder);
2480
+ const dropEmpty = Math.max(0, checkpoints.length - max);
2481
+ const keptEmpty = emptyOldestFirst.slice(dropEmpty);
2482
+ let kept = [...rich, ...keptEmpty];
2483
+ if (kept.length > max) {
2484
+ kept = [...kept].sort(byStoreOrder).slice(kept.length - max);
2485
+ }
2486
+ return kept.sort(byStoreOrder);
2487
+ }
2488
+ async function serialize3(queues2, key, operation) {
2489
+ const previous = queues2.get(key) ?? Promise.resolve();
1763
2490
  const result = previous.then(operation);
1764
2491
  const tail = result.then(() => void 0, () => void 0);
1765
- queues.set(key, tail);
2492
+ queues2.set(key, tail);
1766
2493
  try {
1767
2494
  return await result;
1768
2495
  } finally {
1769
- if (queues.get(key) === tail) queues.delete(key);
2496
+ if (queues2.get(key) === tail) queues2.delete(key);
1770
2497
  }
1771
2498
  }
1772
- var sessionIdSchema = z.string().min(1).transform((value) => value);
1773
- var gapSchema = z.discriminatedUnion("type", [
1774
- z.object({ type: z.literal("prompt"), reason: z.literal("non-text-content") }).strict(),
1775
- z.object({ type: z.literal("workspace"), reason: z.literal("capture-failed") }).strict()
2499
+ var sessionIdSchema2 = z2.string().min(1).transform((value) => value);
2500
+ var gapSchema = z2.discriminatedUnion("type", [
2501
+ z2.object({ type: z2.literal("prompt"), reason: z2.literal("non-text-content") }).strict(),
2502
+ z2.object({ type: z2.literal("workspace"), reason: z2.literal("capture-failed") }).strict()
1776
2503
  ]);
1777
- var fileSchema = z.object({
1778
- path: z.string().min(1),
1779
- change: z.enum(["create", "modify", "delete"]),
1780
- beforeText: z.string().nullable(),
1781
- beforeHash: z.string(),
1782
- afterText: z.string().nullable(),
1783
- afterHash: z.string()
2504
+ var fileSchema2 = z2.object({
2505
+ path: z2.string().min(1),
2506
+ change: z2.enum(["create", "modify", "delete"]),
2507
+ beforeText: z2.string().nullable(),
2508
+ beforeHash: z2.string(),
2509
+ afterText: z2.string().nullable(),
2510
+ afterHash: z2.string()
1784
2511
  }).strict().superRefine((file, context) => {
1785
2512
  const validBefore = file.change === "create" ? file.beforeText === null : file.beforeText !== null;
1786
2513
  if (!validBefore) context.addIssue({ code: "custom", path: ["beforeText"], message: "Invalid before-image" });
1787
2514
  const validAfter = file.change === "delete" ? file.afterText === null : file.afterText !== null;
1788
2515
  if (!validAfter) context.addIssue({ code: "custom", path: ["afterText"], message: "Invalid after-image" });
1789
2516
  });
1790
- var checkpointSchema = z.object({
1791
- schemaVersion: z.literal(CHECKPOINT_SCHEMA_VERSION),
1792
- pluginVersion: z.string().min(1),
1793
- id: z.string().min(1),
1794
- sessionId: sessionIdSchema,
1795
- session: z.object({ format: z.number().int().positive(), preset: z.string().nullable() }).strict(),
1796
- turn: z.number().int().positive(),
1797
- atSeq: z.number().int().nonnegative(),
1798
- prompt: z.string(),
1799
- createdAt: z.number().int().nonnegative(),
1800
- stage: z.literal("committed"),
1801
- coverage: z.enum(["complete", "partial"]),
1802
- gaps: z.array(gapSchema),
1803
- files: z.array(fileSchema)
2517
+ var checkpointSchema = z2.object({
2518
+ schemaVersion: z2.literal(CHECKPOINT_SCHEMA_VERSION),
2519
+ pluginVersion: z2.string().min(1),
2520
+ id: z2.string().min(1),
2521
+ sessionId: sessionIdSchema2,
2522
+ session: z2.object({ format: z2.number().int().positive(), preset: z2.string().nullable() }).strict(),
2523
+ turn: z2.number().int().positive(),
2524
+ atSeq: z2.number().int().nonnegative(),
2525
+ prompt: z2.string(),
2526
+ createdAt: z2.number().int().nonnegative(),
2527
+ stage: z2.literal("committed"),
2528
+ coverage: z2.enum(["complete", "partial"]),
2529
+ gaps: z2.array(gapSchema),
2530
+ files: z2.array(fileSchema2),
2531
+ /** Legacy shadow-git fields (ignored; stripped on save). */
2532
+ shadowBeforeCommit: z2.string().min(7).optional(),
2533
+ shadowAfterCommit: z2.string().min(7).optional()
1804
2534
  }).strict().superRefine((checkpoint, context) => {
1805
2535
  const valid = checkpoint.coverage === "complete" ? checkpoint.gaps.length === 0 : checkpoint.gaps.length > 0;
1806
2536
  if (!valid) context.addIssue({ code: "custom", path: ["gaps"], message: "Coverage does not match gaps" });
1807
2537
  });
1808
- var storeSchema = z.object({
1809
- schemaVersion: z.literal(CHECKPOINT_SCHEMA_VERSION),
1810
- checkpoints: z.array(checkpointSchema).max(MAX_CHECKPOINTS)
2538
+ var storeSchema = z2.object({
2539
+ schemaVersion: z2.literal(CHECKPOINT_SCHEMA_VERSION),
2540
+ checkpoints: z2.array(checkpointSchema).max(MAX_CHECKPOINTS)
1811
2541
  }).strict();
1812
- var journalSchema = z.object({
1813
- schemaVersion: z.literal(CHECKPOINT_SCHEMA_VERSION),
1814
- id: z.string().min(1),
1815
- sessionId: sessionIdSchema,
1816
- checkpointId: z.string().min(1),
1817
- status: z.enum(["prepared", "files-restored", "completed", "compensated"]),
1818
- createdAt: z.number().int().nonnegative()
2542
+ var journalSchema = z2.object({
2543
+ schemaVersion: z2.literal(CHECKPOINT_SCHEMA_VERSION),
2544
+ id: z2.string().min(1),
2545
+ sessionId: sessionIdSchema2,
2546
+ checkpointId: z2.string().min(1),
2547
+ status: z2.enum(["prepared", "files-restored", "completed", "compensated"]),
2548
+ createdAt: z2.number().int().nonnegative()
1819
2549
  }).strict();
1820
2550
  var CheckpointStoreError = class extends Error {
1821
2551
  constructor(code) {
@@ -1828,11 +2558,11 @@ var CheckpointStoreError = class extends Error {
1828
2558
  function isRecord2(value) {
1829
2559
  return typeof value === "object" && value !== null;
1830
2560
  }
1831
- function isMissing2(error) {
2561
+ function isMissing3(error) {
1832
2562
  return isRecord2(error) && error.code === "ENOENT";
1833
2563
  }
1834
- function digest2(value) {
1835
- return createHash2("sha256").update(value).digest("hex");
2564
+ function digest3(value) {
2565
+ return createHash3("sha256").update(value).digest("hex");
1836
2566
  }
1837
2567
  function assertCheckpointSchema(value) {
1838
2568
  if (isRecord2(value) && value.schemaVersion !== CHECKPOINT_SCHEMA_VERSION) {
@@ -1846,29 +2576,29 @@ function assertStoredSchema(value) {
1846
2576
  for (const checkpoint of value.checkpoints) assertCheckpointSchema(checkpoint);
1847
2577
  }
1848
2578
  }
1849
- async function removeIfPresent2(path) {
2579
+ async function removeIfPresent3(path) {
1850
2580
  try {
1851
- await unlink2(path);
2581
+ await unlink3(path);
1852
2582
  } catch (error) {
1853
- if (!isMissing2(error)) throw error;
2583
+ if (!isMissing3(error)) throw error;
1854
2584
  }
1855
2585
  }
1856
- async function writeAtomic2(path, value) {
1857
- const temporary = join2(join2(path, ".."), `.${basename2(path)}.${randomUUID4()}.tmp`);
2586
+ async function writeAtomic3(path, value) {
2587
+ const temporary = join5(join5(path, ".."), `.${basename3(path)}.${randomUUID5()}.tmp`);
1858
2588
  try {
1859
- await writeFile2(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
1860
- await rename2(temporary, path);
1861
- await chmod2(path, 384);
2589
+ await writeFile3(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
2590
+ await rename3(temporary, path);
2591
+ await chmod3(path, 384);
1862
2592
  } finally {
1863
- await removeIfPresent2(temporary);
2593
+ await removeIfPresent3(temporary);
1864
2594
  }
1865
2595
  }
1866
2596
  var CheckpointStore = class {
1867
2597
  constructor(root) {
1868
2598
  this.root = root;
1869
- this.checkpointDirectory = join2(root, "checkpoints");
1870
- this.journalDirectory = join2(root, "journals");
1871
- this.rootKey = join2(root, ".");
2599
+ this.checkpointDirectory = join5(root, "checkpoints");
2600
+ this.journalDirectory = join5(root, "journals");
2601
+ this.rootKey = join5(root, ".");
1872
2602
  }
1873
2603
  root;
1874
2604
  checkpointDirectory;
@@ -1878,16 +2608,15 @@ var CheckpointStore = class {
1878
2608
  assertCheckpointSchema(checkpoint);
1879
2609
  const parsed = checkpointSchema.safeParse(checkpoint);
1880
2610
  if (!parsed.success) throw new CheckpointStoreError("INVALID_CHECKPOINT");
1881
- await serialize2(checkpointQueues, this.checkpointKey(checkpoint.sessionId), async () => {
2611
+ await serialize3(checkpointQueues, this.checkpointKey(checkpoint.sessionId), async () => {
1882
2612
  const checkpoints = await this.list(checkpoint.sessionId);
1883
2613
  const existing = checkpoints.findIndex((value) => value.id === checkpoint.id);
1884
2614
  if (existing >= 0) checkpoints.splice(existing, 1, parsed.data);
1885
2615
  else checkpoints.push(parsed.data);
1886
- checkpoints.sort((left, right) => left.createdAt - right.createdAt || left.turn - right.turn || left.id.localeCompare(right.id));
1887
2616
  await this.ensureDirectories();
1888
- await writeAtomic2(this.checkpointPath(checkpoint.sessionId), {
2617
+ await writeAtomic3(this.checkpointPath(checkpoint.sessionId), {
1889
2618
  schemaVersion: CHECKPOINT_SCHEMA_VERSION,
1890
- checkpoints: checkpoints.slice(-MAX_CHECKPOINTS)
2619
+ checkpoints: retainCheckpoints(checkpoints, MAX_CHECKPOINTS)
1891
2620
  });
1892
2621
  });
1893
2622
  }
@@ -1897,7 +2626,7 @@ var CheckpointStore = class {
1897
2626
  try {
1898
2627
  stored = await this.readJson(this.checkpointPath(sessionId));
1899
2628
  } catch (error) {
1900
- if (isMissing2(error)) return [];
2629
+ if (isMissing3(error)) return [];
1901
2630
  throw error;
1902
2631
  }
1903
2632
  assertStoredSchema(stored);
@@ -1905,10 +2634,62 @@ var CheckpointStore = class {
1905
2634
  if (!parsed.success) throw new CheckpointStoreError("INVALID_STORE");
1906
2635
  return parsed.data.checkpoints;
1907
2636
  }
2637
+ /**
2638
+ * Replace the full per-session checkpoint list (used to drop undo-shell junk).
2639
+ * Empty list removes the session file.
2640
+ */
2641
+ async replace(sessionId, checkpoints) {
2642
+ await serialize3(checkpointQueues, this.checkpointKey(sessionId), async () => {
2643
+ await this.ensureDirectories();
2644
+ const path = this.checkpointPath(sessionId);
2645
+ if (checkpoints.length === 0) {
2646
+ await removeIfPresent3(path);
2647
+ return;
2648
+ }
2649
+ const next = [];
2650
+ for (const checkpoint of checkpoints) {
2651
+ assertCheckpointSchema(checkpoint);
2652
+ const parsed = checkpointSchema.safeParse(checkpoint);
2653
+ if (!parsed.success) throw new CheckpointStoreError("INVALID_CHECKPOINT");
2654
+ if (parsed.data.sessionId !== sessionId) throw new CheckpointStoreError("INVALID_CHECKPOINT");
2655
+ next.push(parsed.data);
2656
+ }
2657
+ await writeAtomic3(path, {
2658
+ schemaVersion: CHECKPOINT_SCHEMA_VERSION,
2659
+ checkpoints: retainCheckpoints(next, MAX_CHECKPOINTS)
2660
+ });
2661
+ });
2662
+ }
2663
+ /** Drop settled journal files left behind after compensate / complete races. */
2664
+ async purgeSettledJournals() {
2665
+ return serialize3(journalQueues, this.rootKey, async () => {
2666
+ await this.ensureDirectories();
2667
+ let names;
2668
+ try {
2669
+ names = await readdir2(this.journalDirectory);
2670
+ } catch (error) {
2671
+ if (isMissing3(error)) return 0;
2672
+ throw error;
2673
+ }
2674
+ let removed = 0;
2675
+ for (const name2 of names) {
2676
+ if (!name2.endsWith(".json")) continue;
2677
+ const path = join5(this.journalDirectory, name2);
2678
+ const stored = await this.readJson(path);
2679
+ assertCheckpointSchema(stored);
2680
+ const parsed = journalSchema.safeParse(stored);
2681
+ if (!parsed.success) continue;
2682
+ if (parsed.data.status === "prepared" || parsed.data.status === "files-restored") continue;
2683
+ await removeIfPresent3(path);
2684
+ removed += 1;
2685
+ }
2686
+ return removed;
2687
+ });
2688
+ }
1908
2689
  async recoverInterruptedWrites(sessionId) {
1909
- await serialize2(checkpointQueues, this.checkpointKey(sessionId), async () => {
2690
+ await serialize3(checkpointQueues, this.checkpointKey(sessionId), async () => {
1910
2691
  await this.ensureDirectories();
1911
- const prefix = `.${basename2(this.checkpointPath(sessionId))}.`;
2692
+ const prefix = `.${basename3(this.checkpointPath(sessionId))}.`;
1912
2693
  await this.cleanTemporaryFiles(this.checkpointDirectory, prefix);
1913
2694
  });
1914
2695
  }
@@ -1916,22 +2697,22 @@ var CheckpointStore = class {
1916
2697
  assertCheckpointSchema(journal);
1917
2698
  const parsed = journalSchema.safeParse(journal);
1918
2699
  if (!parsed.success) throw new CheckpointStoreError("INVALID_JOURNAL");
1919
- await serialize2(journalQueues, this.rootKey, async () => {
2700
+ await serialize3(journalQueues, this.rootKey, async () => {
1920
2701
  await this.ensureDirectories();
1921
- await writeAtomic2(join2(this.journalDirectory, `${digest2(journal.id)}.json`), parsed.data);
2702
+ await writeAtomic3(join5(this.journalDirectory, `${digest3(journal.id)}.json`), parsed.data);
1922
2703
  });
1923
2704
  }
1924
2705
  async completeJournal(id) {
1925
- await serialize2(journalQueues, this.rootKey, async () => {
2706
+ await serialize3(journalQueues, this.rootKey, async () => {
1926
2707
  await this.ensureDirectories();
1927
- await removeIfPresent2(join2(this.journalDirectory, `${digest2(id)}.json`));
2708
+ await removeIfPresent3(join5(this.journalDirectory, `${digest3(id)}.json`));
1928
2709
  });
1929
2710
  }
1930
2711
  async listPendingJournals() {
1931
2712
  return this.readPendingJournals();
1932
2713
  }
1933
2714
  async recoverJournal() {
1934
- return serialize2(journalQueues, this.rootKey, async () => {
2715
+ return serialize3(journalQueues, this.rootKey, async () => {
1935
2716
  await this.ensureDirectories();
1936
2717
  await this.cleanTemporaryFiles(this.journalDirectory);
1937
2718
  return this.readPendingJournals();
@@ -1940,15 +2721,15 @@ var CheckpointStore = class {
1940
2721
  async readPendingJournals() {
1941
2722
  let names;
1942
2723
  try {
1943
- names = await readdir(this.journalDirectory);
2724
+ names = await readdir2(this.journalDirectory);
1944
2725
  } catch (error) {
1945
- if (isMissing2(error)) return [];
2726
+ if (isMissing3(error)) return [];
1946
2727
  throw error;
1947
2728
  }
1948
2729
  const journals = [];
1949
2730
  for (const name2 of names.sort()) {
1950
2731
  if (!name2.endsWith(".json")) continue;
1951
- const stored = await this.readJson(join2(this.journalDirectory, name2));
2732
+ const stored = await this.readJson(join5(this.journalDirectory, name2));
1952
2733
  assertCheckpointSchema(stored);
1953
2734
  const parsed = journalSchema.safeParse(stored);
1954
2735
  if (!parsed.success) throw new CheckpointStoreError("INVALID_STORE");
@@ -1960,20 +2741,20 @@ var CheckpointStore = class {
1960
2741
  return `${this.rootKey}\0${sessionId}`;
1961
2742
  }
1962
2743
  checkpointPath(sessionId) {
1963
- return join2(this.checkpointDirectory, `${digest2(sessionId)}.json`);
2744
+ return join5(this.checkpointDirectory, `${digest3(sessionId)}.json`);
1964
2745
  }
1965
2746
  async ensureDirectories() {
1966
- await mkdir2(this.root, { recursive: true, mode: 448 });
1967
- await mkdir2(this.checkpointDirectory, { recursive: true, mode: 448 });
1968
- await mkdir2(this.journalDirectory, { recursive: true, mode: 448 });
2747
+ await mkdir3(this.root, { recursive: true, mode: 448 });
2748
+ await mkdir3(this.checkpointDirectory, { recursive: true, mode: 448 });
2749
+ await mkdir3(this.journalDirectory, { recursive: true, mode: 448 });
1969
2750
  }
1970
2751
  async cleanTemporaryFiles(directory, prefix = "") {
1971
- for (const name2 of await readdir(directory)) {
1972
- if (name2.startsWith(prefix) && name2.endsWith(".tmp")) await unlink2(join2(directory, name2));
2752
+ for (const name2 of await readdir2(directory)) {
2753
+ if (name2.startsWith(prefix) && name2.endsWith(".tmp")) await unlink3(join5(directory, name2));
1973
2754
  }
1974
2755
  }
1975
2756
  async readJson(path) {
1976
- const text3 = await readFile2(path, "utf8");
2757
+ const text3 = await readFile3(path, "utf8");
1977
2758
  try {
1978
2759
  return JSON.parse(text3);
1979
2760
  } catch {
@@ -2004,18 +2785,16 @@ function classifyUsageSource(options) {
2004
2785
  stamps.set(options, tagged);
2005
2786
  return tagged;
2006
2787
  }
2007
- switch (options.purpose) {
2788
+ const purpose = options.purpose;
2789
+ switch (purpose) {
2008
2790
  case "compaction":
2009
2791
  return "compaction";
2010
2792
  case "session-title":
2011
2793
  return "sessionTitle";
2012
2794
  case void 0:
2013
2795
  break;
2014
- default: {
2015
- const _exhaustive = options.purpose;
2016
- void _exhaustive;
2796
+ default:
2017
2797
  return "other";
2018
- }
2019
2798
  }
2020
2799
  if (isAgentLoopRequest(options)) return "session";
2021
2800
  if (options.system === void 0 && options.sessionId !== void 0) return "session";
@@ -2071,11 +2850,8 @@ function createClassifier(llm, route) {
2071
2850
  }
2072
2851
  return async (text3, signal) => withUsageSource("autoClassifier", async () => {
2073
2852
  const timeout = new AbortController();
2074
- const timer = setTimeout(() => {
2075
- timeout.abort();
2076
- }, CLASSIFIER_TIMEOUT_MS);
2077
- const unlink4 = signal === void 0 ? void 0 : linkAbortSignal(signal, timeout);
2078
- try {
2853
+ const unlink5 = signal === void 0 ? void 0 : linkAbortSignal(signal, timeout);
2854
+ const run = (async () => {
2079
2855
  timeout.signal.throwIfAborted();
2080
2856
  const call = await llm.prepareCall(
2081
2857
  { provider: route.provider, model: route.model, maxTokens: CLASSIFIER_MAX_TOKENS },
@@ -2104,9 +2880,21 @@ function createClassifier(llm, route) {
2104
2880
  throw new Error("Classifier finished without stop");
2105
2881
  }
2106
2882
  throw new Error(`Invalid classifier output: ${raw}`);
2883
+ })();
2884
+ let timer;
2885
+ try {
2886
+ return await Promise.race([
2887
+ run,
2888
+ new Promise((_resolve, reject) => {
2889
+ timer = setTimeout(() => {
2890
+ timeout.abort();
2891
+ reject(new Error("Classifier timed out"));
2892
+ }, CLASSIFIER_TIMEOUT_MS);
2893
+ })
2894
+ ]);
2107
2895
  } finally {
2108
- clearTimeout(timer);
2109
- unlink4?.();
2896
+ if (timer !== void 0) clearTimeout(timer);
2897
+ unlink5?.();
2110
2898
  }
2111
2899
  });
2112
2900
  }
@@ -2752,6 +3540,7 @@ function inspectContextCategory(session, category, tokenMeter) {
2752
3540
  import { LlmAdapter, LlmError } from "@deepseek-ai/dsh-llm";
2753
3541
  import { ReasoningEffortId } from "@deepseek-ai/dsh-llm/brand";
2754
3542
  var AUTO_CATALOG_NAME = "Auto";
3543
+ var AUTO_CONTEXT_WINDOW = 524288;
2755
3544
  var AutoCatalogAdapter = class extends LlmAdapter {
2756
3545
  providerInfo(provider) {
2757
3546
  return { id: provider, name: AUTO_CATALOG_NAME };
@@ -2769,7 +3558,8 @@ var AutoCatalogAdapter = class extends LlmAdapter {
2769
3558
  provider,
2770
3559
  id: model,
2771
3560
  name: AUTO_CATALOG_NAME,
2772
- inputModalities: ["text"]
3561
+ inputModalities: ["text"],
3562
+ context: { contextWindow: AUTO_CONTEXT_WINDOW }
2773
3563
  });
2774
3564
  }
2775
3565
  stream(_options) {
@@ -4109,45 +4899,45 @@ function mergeUsageCalls(stored, history) {
4109
4899
  }
4110
4900
 
4111
4901
  // src/host/usage/ledger.ts
4112
- import { randomUUID as randomUUID5 } from "node:crypto";
4113
- 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 join3 } from "node:path";
4115
- import { z as z2 } from "zod";
4116
- var callSchema = z2.object({
4117
- at: z2.number().int().nonnegative(),
4118
- source: z2.enum(USAGE_SOURCES),
4119
- provider: z2.string().min(1),
4120
- model: z2.string().min(1),
4902
+ import { randomUUID as randomUUID6 } from "node:crypto";
4903
+ import { chmod as chmod4, mkdir as mkdir4, readFile as readFile4, rename as rename4, unlink as unlink4, writeFile as writeFile4 } from "node:fs/promises";
4904
+ import { basename as basename4, join as join6 } from "node:path";
4905
+ import { z as z3 } from "zod";
4906
+ var callSchema = z3.object({
4907
+ at: z3.number().int().nonnegative(),
4908
+ source: z3.enum(USAGE_SOURCES),
4909
+ provider: z3.string().min(1),
4910
+ model: z3.string().min(1),
4121
4911
  // Older ledgers omit effort; treat as unknown.
4122
- reasoningEffort: z2.string().optional().default(""),
4123
- inputTokens: z2.number().int().nonnegative(),
4124
- outputTokens: z2.number().int().nonnegative(),
4125
- cacheReadTokens: z2.number().int().nonnegative(),
4126
- cacheWriteTokens: z2.number().int().nonnegative(),
4127
- reasoningTokens: z2.number().int().nonnegative()
4912
+ reasoningEffort: z3.string().optional().default(""),
4913
+ inputTokens: z3.number().int().nonnegative(),
4914
+ outputTokens: z3.number().int().nonnegative(),
4915
+ cacheReadTokens: z3.number().int().nonnegative(),
4916
+ cacheWriteTokens: z3.number().int().nonnegative(),
4917
+ reasoningTokens: z3.number().int().nonnegative()
4128
4918
  }).strict();
4129
- var fileSchema2 = z2.object({
4130
- schemaVersion: z2.literal(1),
4131
- calls: z2.array(z2.unknown())
4919
+ var fileSchema3 = z3.object({
4920
+ schemaVersion: z3.literal(1),
4921
+ calls: z3.array(z3.unknown())
4132
4922
  }).strict();
4133
- function isMissing3(error) {
4923
+ function isMissing4(error) {
4134
4924
  return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
4135
4925
  }
4136
- async function removeIfPresent3(path) {
4926
+ async function removeIfPresent4(path) {
4137
4927
  try {
4138
- await unlink3(path);
4928
+ await unlink4(path);
4139
4929
  } catch (error) {
4140
- if (!isMissing3(error)) throw error;
4930
+ if (!isMissing4(error)) throw error;
4141
4931
  }
4142
4932
  }
4143
- async function writeAtomic3(path, value) {
4144
- const temporary = join3(join3(path, ".."), `.${basename3(path)}.${randomUUID5()}.tmp`);
4933
+ async function writeAtomic4(path, value) {
4934
+ const temporary = join6(join6(path, ".."), `.${basename4(path)}.${randomUUID6()}.tmp`);
4145
4935
  try {
4146
- await writeFile3(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
4147
- await rename3(temporary, path);
4148
- await chmod3(path, 384);
4936
+ await writeFile4(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
4937
+ await rename4(temporary, path);
4938
+ await chmod4(path, 384);
4149
4939
  } finally {
4150
- await removeIfPresent3(temporary);
4940
+ await removeIfPresent4(temporary);
4151
4941
  }
4152
4942
  }
4153
4943
  var UsageLedger = class {
@@ -4155,7 +4945,7 @@ var UsageLedger = class {
4155
4945
  }) {
4156
4946
  this.root = root;
4157
4947
  this.warn = warn;
4158
- this.file = join3(root, "ledger.json");
4948
+ this.file = join6(root, "ledger.json");
4159
4949
  }
4160
4950
  root;
4161
4951
  warn;
@@ -4196,9 +4986,9 @@ var UsageLedger = class {
4196
4986
  async read() {
4197
4987
  let text3;
4198
4988
  try {
4199
- text3 = await readFile3(this.file, "utf8");
4989
+ text3 = await readFile4(this.file, "utf8");
4200
4990
  } catch (error) {
4201
- if (isMissing3(error)) return [];
4991
+ if (isMissing4(error)) return [];
4202
4992
  throw error;
4203
4993
  }
4204
4994
  let parsed;
@@ -4207,7 +4997,7 @@ var UsageLedger = class {
4207
4997
  } catch {
4208
4998
  return [];
4209
4999
  }
4210
- const file = fileSchema2.safeParse(parsed);
5000
+ const file = fileSchema3.safeParse(parsed);
4211
5001
  if (!file.success) return [];
4212
5002
  const calls = [];
4213
5003
  for (const item of file.data.calls) {
@@ -4222,8 +5012,8 @@ var UsageLedger = class {
4222
5012
  await this.persist();
4223
5013
  }
4224
5014
  async persist() {
4225
- await mkdir3(this.root, { recursive: true, mode: 448 });
4226
- await writeAtomic3(this.file, { schemaVersion: 1, calls: this.calls });
5015
+ await mkdir4(this.root, { recursive: true, mode: 448 });
5016
+ await writeAtomic4(this.file, { schemaVersion: 1, calls: this.calls });
4227
5017
  }
4228
5018
  };
4229
5019
 
@@ -4265,53 +5055,53 @@ function installUsageObserver(ctx, recorder) {
4265
5055
 
4266
5056
  // src/host/rpc.ts
4267
5057
  import { createTypertRemoteInfo } from "@deepseek-ai/dsh-typert-protocol/remote-info";
4268
- import { z as z3 } from "zod";
5058
+ import { z as z4 } from "zod";
4269
5059
 
4270
5060
  // src/host/update/types.ts
4271
5061
  var APPLY_UPDATE_CODES = ["restart", "link", "manual", "none", "failed"];
4272
5062
 
4273
5063
  // src/host/rpc.ts
4274
- var sessionIdSchema2 = z3.string().min(1).transform((value) => value);
4275
- var recentExchangeSchema = z3.strictObject({
4276
- turn: z3.number().int().nonnegative(),
4277
- prompt: z3.string(),
4278
- response: z3.string()
5064
+ var sessionIdSchema3 = z4.string().min(1).transform((value) => value);
5065
+ var recentExchangeSchema = z4.strictObject({
5066
+ turn: z4.number().int().nonnegative(),
5067
+ prompt: z4.string(),
5068
+ response: z4.string()
4279
5069
  });
4280
- var optimizeReferenceSchema = z3.strictObject({
4281
- offset: z3.number().int().nonnegative(),
4282
- length: z3.number().int().positive(),
4283
- text: z3.string().min(1)
5070
+ var optimizeReferenceSchema = z4.strictObject({
5071
+ offset: z4.number().int().nonnegative(),
5072
+ length: z4.number().int().positive(),
5073
+ text: z4.string().min(1)
4284
5074
  });
4285
- var uiLocaleSchema = z3.enum(["zh", "en"]).optional();
4286
- var optimizeRequestSchema = z3.strictObject({
4287
- operation: z3.literal("optimize"),
4288
- requestId: z3.string(),
4289
- sessionId: sessionIdSchema2,
4290
- source: z3.string(),
4291
- references: z3.array(optimizeReferenceSchema),
4292
- context: z3.array(recentExchangeSchema),
5075
+ var uiLocaleSchema = z4.enum(["zh", "en"]).optional();
5076
+ var optimizeRequestSchema = z4.strictObject({
5077
+ operation: z4.literal("optimize"),
5078
+ requestId: z4.string(),
5079
+ sessionId: sessionIdSchema3,
5080
+ source: z4.string(),
5081
+ references: z4.array(optimizeReferenceSchema),
5082
+ context: z4.array(recentExchangeSchema),
4293
5083
  uiLocale: uiLocaleSchema
4294
5084
  });
4295
- var predictRequestSchema = z3.strictObject({
4296
- operation: z3.literal("predict"),
4297
- requestId: z3.string(),
4298
- sessionId: sessionIdSchema2,
4299
- context: z3.array(recentExchangeSchema),
5085
+ var predictRequestSchema = z4.strictObject({
5086
+ operation: z4.literal("predict"),
5087
+ requestId: z4.string(),
5088
+ sessionId: sessionIdSchema3,
5089
+ context: z4.array(recentExchangeSchema),
4300
5090
  uiLocale: uiLocaleSchema
4301
5091
  });
4302
- var auxiliaryRequestSchema = z3.discriminatedUnion("operation", [
5092
+ var auxiliaryRequestSchema = z4.discriminatedUnion("operation", [
4303
5093
  optimizeRequestSchema,
4304
5094
  predictRequestSchema
4305
5095
  ]);
4306
- var rpcPayloadSchema = z3.strictObject({
4307
- method: z3.literal("generate"),
5096
+ var rpcPayloadSchema = z4.strictObject({
5097
+ method: z4.literal("generate"),
4308
5098
  data: auxiliaryRequestSchema
4309
5099
  });
4310
- var auxiliaryResultSchema = z3.strictObject({
4311
- requestId: z3.string(),
4312
- text: z3.string(),
4313
- route: z3.strictObject({ provider: z3.string(), model: z3.string() }),
4314
- segments: z3.array(z3.string()).optional()
5100
+ var auxiliaryResultSchema = z4.strictObject({
5101
+ requestId: z4.string(),
5102
+ text: z4.string(),
5103
+ route: z4.strictObject({ provider: z4.string(), model: z4.string() }),
5104
+ segments: z4.array(z4.string()).optional()
4315
5105
  });
4316
5106
  function codec(typeSymbol, schema) {
4317
5107
  return { mode: "strict", typeSymbol, create: () => schema };
@@ -4319,50 +5109,50 @@ function codec(typeSymbol, schema) {
4319
5109
  var payloadCodec = codec("dsh-agent-enhancer#RpcPayload", rpcPayloadSchema);
4320
5110
  var resultCodec = codec(
4321
5111
  "dsh-agent-enhancer#AuxiliaryResult|null",
4322
- z3.union([auxiliaryResultSchema, z3.null()])
5112
+ z4.union([auxiliaryResultSchema, z4.null()])
4323
5113
  );
4324
- var modelReasoningEffortSchema = z3.object({
4325
- id: z3.string(),
4326
- name: z3.string(),
4327
- description: z3.string().optional()
5114
+ var modelReasoningEffortSchema = z4.object({
5115
+ id: z4.string(),
5116
+ name: z4.string(),
5117
+ description: z4.string().optional()
4328
5118
  });
4329
- var modelReasoningSchema = z3.object({
4330
- efforts: z3.array(modelReasoningEffortSchema),
4331
- defaultEffort: z3.string().optional()
5119
+ var modelReasoningSchema = z4.object({
5120
+ efforts: z4.array(modelReasoningEffortSchema),
5121
+ defaultEffort: z4.string().optional()
4332
5122
  });
4333
- var modelCatalogModelSchema = z3.object({
4334
- id: z3.string(),
4335
- name: z3.string(),
4336
- description: z3.string().optional(),
5123
+ var modelCatalogModelSchema = z4.object({
5124
+ id: z4.string(),
5125
+ name: z4.string(),
5126
+ description: z4.string().optional(),
4337
5127
  reasoning: modelReasoningSchema.optional()
4338
5128
  });
4339
- var modelProviderGroupSchema = z3.object({
4340
- id: z3.string(),
4341
- name: z3.string(),
4342
- models: z3.array(modelCatalogModelSchema)
5129
+ var modelProviderGroupSchema = z4.object({
5130
+ id: z4.string(),
5131
+ name: z4.string(),
5132
+ models: z4.array(modelCatalogModelSchema)
4343
5133
  });
4344
- var modelCatalogFailureSchema = z3.object({
4345
- id: z3.string(),
4346
- name: z3.string(),
4347
- message: z3.string()
5134
+ var modelCatalogFailureSchema = z4.object({
5135
+ id: z4.string(),
5136
+ name: z4.string(),
5137
+ message: z4.string()
4348
5138
  });
4349
- var modelCatalogSchema = z3.object({
4350
- default: z3.object({
4351
- provider: z3.string(),
4352
- model: z3.string(),
4353
- reasoningEffort: z3.string().optional()
5139
+ var modelCatalogSchema = z4.object({
5140
+ default: z4.object({
5141
+ provider: z4.string(),
5142
+ model: z4.string(),
5143
+ reasoningEffort: z4.string().optional()
4354
5144
  }),
4355
- routableProviders: z3.array(z3.string()),
4356
- groups: z3.array(modelProviderGroupSchema),
4357
- failures: z3.array(modelCatalogFailureSchema)
5145
+ routableProviders: z4.array(z4.string()),
5146
+ groups: z4.array(modelProviderGroupSchema),
5147
+ failures: z4.array(modelCatalogFailureSchema)
4358
5148
  });
4359
5149
  var catalogCodec = codec("dsh-agent-enhancer#ModelCatalog", modelCatalogSchema);
4360
- var contextInspectCategorySchema = z3.enum(["system", "tools", "messages"]);
4361
- var contextInspectRequestSchema = z3.strictObject({
4362
- sessionId: sessionIdSchema2,
5150
+ var contextInspectCategorySchema = z4.enum(["system", "tools", "messages"]);
5151
+ var contextInspectRequestSchema = z4.strictObject({
5152
+ sessionId: sessionIdSchema3,
4363
5153
  category: contextInspectCategorySchema
4364
5154
  });
4365
- var contextInspectKindSchema = z3.enum([
5155
+ var contextInspectKindSchema = z4.enum([
4366
5156
  "system",
4367
5157
  "tools",
4368
5158
  "user",
@@ -4371,144 +5161,144 @@ var contextInspectKindSchema = z3.enum([
4371
5161
  "tool",
4372
5162
  "developer"
4373
5163
  ]);
4374
- var contextInspectItemSchema = z3.strictObject({
4375
- id: z3.string(),
4376
- title: z3.string(),
4377
- detail: z3.string(),
4378
- body: z3.string(),
4379
- tokens: z3.number().int().nonnegative(),
5164
+ var contextInspectItemSchema = z4.strictObject({
5165
+ id: z4.string(),
5166
+ title: z4.string(),
5167
+ detail: z4.string(),
5168
+ body: z4.string(),
5169
+ tokens: z4.number().int().nonnegative(),
4380
5170
  kind: contextInspectKindSchema,
4381
- replaced: z3.boolean()
5171
+ replaced: z4.boolean()
4382
5172
  });
4383
- var contextInspectPressureSchema = z3.strictObject({
4384
- projectedTokens: z3.number().int().nonnegative().optional(),
4385
- contextWindow: z3.number().int().positive().optional()
5173
+ var contextInspectPressureSchema = z4.strictObject({
5174
+ projectedTokens: z4.number().int().nonnegative().optional(),
5175
+ contextWindow: z4.number().int().positive().optional()
4386
5176
  });
4387
- var contextInspectEventKindSchema = z3.enum(["compact", "prune", "replace"]);
4388
- var contextInspectEventMarkSchema = z3.strictObject({
4389
- id: z3.string(),
5177
+ var contextInspectEventKindSchema = z4.enum(["compact", "prune", "replace"]);
5178
+ var contextInspectEventMarkSchema = z4.strictObject({
5179
+ id: z4.string(),
4390
5180
  kind: contextInspectEventKindSchema,
4391
- seq: z3.number().int().nonnegative(),
4392
- shadowed: z3.number().int().nonnegative(),
4393
- title: z3.string()
5181
+ seq: z4.number().int().nonnegative(),
5182
+ shadowed: z4.number().int().nonnegative(),
5183
+ title: z4.string()
4394
5184
  });
4395
- var contextInspectResultSchema = z3.strictObject({
4396
- sessionId: sessionIdSchema2,
5185
+ var contextInspectResultSchema = z4.strictObject({
5186
+ sessionId: sessionIdSchema3,
4397
5187
  category: contextInspectCategorySchema,
4398
- totalTokens: z3.number().int().nonnegative(),
4399
- approximate: z3.literal(true),
4400
- items: z3.array(contextInspectItemSchema),
5188
+ totalTokens: z4.number().int().nonnegative(),
5189
+ approximate: z4.literal(true),
5190
+ items: z4.array(contextInspectItemSchema),
4401
5191
  pressure: contextInspectPressureSchema,
4402
- events: z3.array(contextInspectEventMarkSchema)
5192
+ events: z4.array(contextInspectEventMarkSchema)
4403
5193
  });
4404
5194
  var contextInspectRequestCodec = codec("dsh-agent-enhancer#ContextInspectRequest", contextInspectRequestSchema);
4405
5195
  var contextInspectResultCodec = codec("dsh-agent-enhancer#ContextInspectResult", contextInspectResultSchema);
4406
- var contextCompactRequestSchema = z3.strictObject({
4407
- sessionId: sessionIdSchema2
5196
+ var contextCompactRequestSchema = z4.strictObject({
5197
+ sessionId: sessionIdSchema3
4408
5198
  });
4409
- var contextCompactResultSchema = z3.strictObject({
4410
- sessionId: sessionIdSchema2,
4411
- status: z3.enum(["compacted", "noop"]),
4412
- shadowedCount: z3.number().int().nonnegative(),
4413
- shadowedTokens: z3.number().int().nonnegative()
5199
+ var contextCompactResultSchema = z4.strictObject({
5200
+ sessionId: sessionIdSchema3,
5201
+ status: z4.enum(["compacted", "noop"]),
5202
+ shadowedCount: z4.number().int().nonnegative(),
5203
+ shadowedTokens: z4.number().int().nonnegative()
4414
5204
  });
4415
5205
  var contextCompactRequestCodec = codec("dsh-agent-enhancer#ContextCompactRequest", contextCompactRequestSchema);
4416
5206
  var contextCompactResultCodec = codec("dsh-agent-enhancer#ContextCompactResult", contextCompactResultSchema);
4417
- var updateCheckResultSchema = z3.strictObject({
4418
- current: z3.string(),
4419
- latest: z3.string().nullable(),
4420
- updateAvailable: z3.boolean(),
4421
- installKind: z3.enum(["npm", "link", "unknown"]),
4422
- canAutoApply: z3.boolean(),
4423
- command: z3.string()
5207
+ var updateCheckResultSchema = z4.strictObject({
5208
+ current: z4.string(),
5209
+ latest: z4.string().nullable(),
5210
+ updateAvailable: z4.boolean(),
5211
+ installKind: z4.enum(["npm", "link", "unknown"]),
5212
+ canAutoApply: z4.boolean(),
5213
+ command: z4.string()
4424
5214
  });
4425
- var applyUpdateResultSchema = z3.strictObject({
4426
- ok: z3.boolean(),
4427
- message: z3.enum(APPLY_UPDATE_CODES),
4428
- command: z3.string().optional()
5215
+ var applyUpdateResultSchema = z4.strictObject({
5216
+ ok: z4.boolean(),
5217
+ message: z4.enum(APPLY_UPDATE_CODES),
5218
+ command: z4.string().optional()
4429
5219
  });
4430
5220
  var updateCheckResultCodec = codec("dsh-agent-enhancer#UpdateCheckResult", updateCheckResultSchema);
4431
5221
  var applyUpdateResultCodec = codec("dsh-agent-enhancer#ApplyUpdateResult", applyUpdateResultSchema);
4432
5222
  var usageTokenFields = {
4433
- inputTokens: z3.number().int().nonnegative(),
4434
- outputTokens: z3.number().int().nonnegative(),
4435
- cacheReadTokens: z3.number().int().nonnegative(),
4436
- cacheWriteTokens: z3.number().int().nonnegative(),
4437
- reasoningTokens: z3.number().int().nonnegative()
5223
+ inputTokens: z4.number().int().nonnegative(),
5224
+ outputTokens: z4.number().int().nonnegative(),
5225
+ cacheReadTokens: z4.number().int().nonnegative(),
5226
+ cacheWriteTokens: z4.number().int().nonnegative(),
5227
+ reasoningTokens: z4.number().int().nonnegative()
4438
5228
  };
4439
- var usageRangeSchema = z3.enum(USAGE_RANGES);
4440
- var usageCallSchema = z3.object({
4441
- at: z3.number().int().nonnegative(),
4442
- source: z3.enum(USAGE_SOURCES),
4443
- provider: z3.string(),
4444
- model: z3.string(),
4445
- reasoningEffort: z3.string(),
5229
+ var usageRangeSchema = z4.enum(USAGE_RANGES);
5230
+ var usageCallSchema = z4.object({
5231
+ at: z4.number().int().nonnegative(),
5232
+ source: z4.enum(USAGE_SOURCES),
5233
+ provider: z4.string(),
5234
+ model: z4.string(),
5235
+ reasoningEffort: z4.string(),
4446
5236
  ...usageTokenFields
4447
5237
  }).strict();
4448
- var usageModelLineSchema = z3.object({
4449
- provider: z3.string(),
4450
- model: z3.string(),
4451
- reasoningEffort: z3.string(),
4452
- calls: z3.number().int().nonnegative(),
5238
+ var usageModelLineSchema = z4.object({
5239
+ provider: z4.string(),
5240
+ model: z4.string(),
5241
+ reasoningEffort: z4.string(),
5242
+ calls: z4.number().int().nonnegative(),
4453
5243
  ...usageTokenFields
4454
5244
  }).strict();
4455
- var usageSourceLineSchema = z3.object({
4456
- source: z3.enum(USAGE_SOURCES),
4457
- calls: z3.number().int().nonnegative(),
4458
- models: z3.array(usageModelLineSchema),
5245
+ var usageSourceLineSchema = z4.object({
5246
+ source: z4.enum(USAGE_SOURCES),
5247
+ calls: z4.number().int().nonnegative(),
5248
+ models: z4.array(usageModelLineSchema),
4459
5249
  ...usageTokenFields
4460
5250
  }).strict();
4461
- var usageHeatCellSchema = z3.object({
4462
- key: z3.string(),
4463
- label: z3.string(),
4464
- at: z3.number().int().nonnegative(),
4465
- tokens: z3.number().int().nonnegative(),
4466
- calls: z3.number().int().nonnegative()
5251
+ var usageHeatCellSchema = z4.object({
5252
+ key: z4.string(),
5253
+ label: z4.string(),
5254
+ at: z4.number().int().nonnegative(),
5255
+ tokens: z4.number().int().nonnegative(),
5256
+ calls: z4.number().int().nonnegative()
4467
5257
  }).strict();
4468
- var usageHeatmapSchema = z3.object({
4469
- grain: z3.enum(["hour", "day"]),
4470
- cells: z3.array(usageHeatCellSchema)
5258
+ var usageHeatmapSchema = z4.object({
5259
+ grain: z4.enum(["hour", "day"]),
5260
+ cells: z4.array(usageHeatCellSchema)
4471
5261
  }).strict();
4472
- var usageMoneySchema = z3.object({
4473
- currency: z3.literal("CNY"),
4474
- estimatedCost: z3.number().nonnegative(),
4475
- pricedCalls: z3.number().int().nonnegative(),
4476
- unpricedCalls: z3.number().int().nonnegative()
5262
+ var usageMoneySchema = z4.object({
5263
+ currency: z4.literal("CNY"),
5264
+ estimatedCost: z4.number().nonnegative(),
5265
+ pricedCalls: z4.number().int().nonnegative(),
5266
+ unpricedCalls: z4.number().int().nonnegative()
4477
5267
  }).strict();
4478
- var usageBalanceSchema = z3.object({
4479
- available: z3.boolean(),
4480
- currency: z3.string(),
4481
- total: z3.string(),
4482
- granted: z3.string(),
4483
- toppedUp: z3.string(),
4484
- checkedAt: z3.number().int().nonnegative(),
4485
- stale: z3.boolean().optional()
5268
+ var usageBalanceSchema = z4.object({
5269
+ available: z4.boolean(),
5270
+ currency: z4.string(),
5271
+ total: z4.string(),
5272
+ granted: z4.string(),
5273
+ toppedUp: z4.string(),
5274
+ checkedAt: z4.number().int().nonnegative(),
5275
+ stale: z4.boolean().optional()
4486
5276
  }).strict();
4487
- var usageBalanceStatusSchema = z3.enum(["ready", "no-key", "unavailable"]);
4488
- var usageSummarySchema = z3.object({
5277
+ var usageBalanceStatusSchema = z4.enum(["ready", "no-key", "unavailable"]);
5278
+ var usageSummarySchema = z4.object({
4489
5279
  range: usageRangeSchema,
4490
- calls: z3.number().int().nonnegative(),
4491
- sources: z3.array(usageSourceLineSchema),
5280
+ calls: z4.number().int().nonnegative(),
5281
+ sources: z4.array(usageSourceLineSchema),
4492
5282
  heatmap: usageHeatmapSchema,
4493
5283
  money: usageMoneySchema,
4494
5284
  balanceStatus: usageBalanceStatusSchema,
4495
5285
  balance: usageBalanceSchema.optional(),
4496
- recent: z3.array(usageCallSchema),
5286
+ recent: z4.array(usageCallSchema),
4497
5287
  ...usageTokenFields
4498
5288
  }).strict();
4499
- var providerBalanceStatusSchema = z3.enum(["ready", "no-key", "signed-out", "unavailable"]);
4500
- var providerBalanceSnapshotSchema = z3.object({
4501
- source: z3.enum(["account", "api-key"]),
5289
+ var providerBalanceStatusSchema = z4.enum(["ready", "no-key", "signed-out", "unavailable"]);
5290
+ var providerBalanceSnapshotSchema = z4.object({
5291
+ source: z4.enum(["account", "api-key"]),
4502
5292
  status: providerBalanceStatusSchema,
4503
5293
  balance: usageBalanceSchema.optional()
4504
5294
  }).strict();
4505
- var providerBalancesSchema = z3.object({
5295
+ var providerBalancesSchema = z4.object({
4506
5296
  account: providerBalanceSnapshotSchema,
4507
5297
  apiKey: providerBalanceSnapshotSchema
4508
5298
  }).strict();
4509
- var providerBalancesRequestSchema = z3.object({
4510
- force: z3.boolean().optional(),
4511
- locale: z3.string().optional()
5299
+ var providerBalancesRequestSchema = z4.object({
5300
+ force: z4.boolean().optional(),
5301
+ locale: z4.string().optional()
4512
5302
  }).strict();
4513
5303
  var usageRangeCodec = codec("dsh-agent-enhancer#UsageRange", usageRangeSchema);
4514
5304
  var usageSummaryCodec = codec("dsh-agent-enhancer#UsageSummary", usageSummarySchema);
@@ -4606,26 +5396,28 @@ var remoteInfo = createTypertRemoteInfo({
4606
5396
  result: providerBalancesCodec
4607
5397
  }
4608
5398
  }
4609
- }, z3);
4610
- var checkpointScopeSchema = z3.enum(["conversation", "conversation-and-files"]);
4611
- var checkpointRollbackRequestSchema = z3.strictObject({
4612
- sessionId: sessionIdSchema2,
4613
- turn: z3.number().int().positive(),
4614
- operation: z3.enum(["rollback", "undo"]).optional(),
4615
- scope: checkpointScopeSchema.optional()
5399
+ }, z4);
5400
+ var checkpointScopeSchema = z4.enum(["conversation", "conversation-and-files"]);
5401
+ var checkpointRollbackRequestSchema = z4.strictObject({
5402
+ sessionId: sessionIdSchema3,
5403
+ turn: z4.number().int().positive(),
5404
+ operation: z4.enum(["rollback", "undo"]).optional(),
5405
+ scope: checkpointScopeSchema.optional(),
5406
+ // Timeline cards pin the tip by atSeq (turn numbers reuse after undo).
5407
+ atSeq: z4.number().int().nonnegative().optional()
4616
5408
  });
4617
- var checkpointMessageSchema = z3.strictObject({
4618
- seq: z3.number().int().nonnegative(),
4619
- type: z3.string(),
4620
- text: z3.string()
5409
+ var checkpointMessageSchema = z4.strictObject({
5410
+ seq: z4.number().int().nonnegative(),
5411
+ type: z4.string(),
5412
+ text: z4.string()
4621
5413
  });
4622
- var checkpointFileSchema = z3.strictObject({
4623
- path: z3.string(),
4624
- change: z3.enum(["create", "modify", "delete"])
5414
+ var checkpointFileSchema = z4.strictObject({
5415
+ path: z4.string(),
5416
+ change: z4.enum(["create", "modify", "delete"])
4625
5417
  });
4626
- var checkpointConflictSchema = z3.strictObject({
4627
- path: z3.string(),
4628
- reason: z3.enum([
5418
+ var checkpointConflictSchema = z4.strictObject({
5419
+ path: z4.string(),
5420
+ reason: z4.enum([
4629
5421
  "unsafe-path",
4630
5422
  "symlink",
4631
5423
  "not-regular-file",
@@ -4635,10 +5427,10 @@ var checkpointConflictSchema = z3.strictObject({
4635
5427
  "invalid-after-image",
4636
5428
  "hash-mismatch"
4637
5429
  ]),
4638
- expectedHash: z3.string().optional(),
4639
- actualHash: z3.string().nullable().optional()
5430
+ expectedHash: z4.string().optional(),
5431
+ actualHash: z4.string().nullable().optional()
4640
5432
  });
4641
- var checkpointUnavailableSchema = z3.enum([
5433
+ var checkpointUnavailableSchema = z4.enum([
4642
5434
  "checkpoint-not-found",
4643
5435
  "incomplete-checkpoint",
4644
5436
  "prompt-non-text-content",
@@ -4647,30 +5439,94 @@ var checkpointUnavailableSchema = z3.enum([
4647
5439
  "session-running",
4648
5440
  "permission-denied",
4649
5441
  "rollback-disabled",
4650
- "first-turn",
4651
5442
  "incompatible-session",
4652
5443
  "compacted-surface",
4653
5444
  "subagent-session",
4654
- "unknown-surface"
5445
+ "unknown-surface",
5446
+ "already-restored",
5447
+ "covered-by-earlier-restore"
4655
5448
  ]);
4656
- var checkpointPreviewSchema = z3.strictObject({
4657
- sessionId: sessionIdSchema2,
4658
- turn: z3.number().int().positive(),
4659
- operation: z3.enum(["rollback", "undo"]).optional(),
5449
+ var checkpointPreviewSchema = z4.strictObject({
5450
+ sessionId: sessionIdSchema3,
5451
+ turn: z4.number().int().positive(),
5452
+ operation: z4.enum(["rollback", "undo"]).optional(),
4660
5453
  scope: checkpointScopeSchema.optional(),
4661
- messages: z3.array(checkpointMessageSchema),
4662
- files: z3.array(checkpointFileSchema),
4663
- conflicts: z3.array(checkpointConflictSchema),
4664
- unavailable: z3.array(checkpointUnavailableSchema)
5454
+ tipTurn: z4.number().int().positive().optional(),
5455
+ atSeq: z4.number().int().nonnegative().optional(),
5456
+ messages: z4.array(checkpointMessageSchema),
5457
+ files: z4.array(checkpointFileSchema),
5458
+ conflicts: z4.array(checkpointConflictSchema),
5459
+ unavailable: z4.array(checkpointUnavailableSchema)
4665
5460
  });
4666
- var checkpointResultSchema = z3.strictObject({
4667
- sessionId: sessionIdSchema2,
4668
- turn: z3.number().int().positive(),
4669
- draft: z3.string()
5461
+ var checkpointResultSchema = z4.strictObject({
5462
+ sessionId: sessionIdSchema3,
5463
+ turn: z4.number().int().positive(),
5464
+ draft: z4.string()
5465
+ });
5466
+ var checkpointSummariesRequestSchema = z4.strictObject({
5467
+ sessionId: sessionIdSchema3
5468
+ });
5469
+ var checkpointGapSchema = z4.discriminatedUnion("type", [
5470
+ z4.object({ type: z4.literal("prompt"), reason: z4.literal("non-text-content") }).strict(),
5471
+ z4.object({ type: z4.literal("workspace"), reason: z4.literal("capture-failed") }).strict()
5472
+ ]);
5473
+ var checkpointTurnSummarySchema = z4.strictObject({
5474
+ turn: z4.number().int().positive(),
5475
+ coverage: z4.enum(["complete", "partial"]),
5476
+ fileCount: z4.number().int().nonnegative(),
5477
+ createdAt: z4.number().int().nonnegative(),
5478
+ atSeq: z4.number().int().nonnegative(),
5479
+ prompt: z4.string(),
5480
+ promptPreview: z4.string(),
5481
+ files: z4.array(checkpointFileSchema),
5482
+ gaps: z4.array(checkpointGapSchema),
5483
+ rolledBack: z4.boolean(),
5484
+ tip: z4.boolean()
5485
+ });
5486
+ var liveActivityStatsSchema = z4.strictObject({
5487
+ turns: z4.number().int().nonnegative(),
5488
+ steps: z4.number().int().nonnegative(),
5489
+ checkpoints: z4.number().int().nonnegative(),
5490
+ liveCheckpoints: z4.number().int().nonnegative()
5491
+ });
5492
+ var checkpointSummariesResultSchema = z4.strictObject({
5493
+ sessionId: sessionIdSchema3,
5494
+ activity: liveActivityStatsSchema,
5495
+ turns: z4.array(checkpointTurnSummarySchema)
5496
+ });
5497
+ var checkpointCutRequestSchema = z4.strictObject({
5498
+ sessionId: sessionIdSchema3
5499
+ });
5500
+ var checkpointCutViewSchema = z4.strictObject({
5501
+ hideTurnsFrom: z4.number().int().positive(),
5502
+ cutSeq: z4.number().int().nonnegative(),
5503
+ restoredAtSeq: z4.number().int().nonnegative(),
5504
+ draftPrompt: z4.string(),
5505
+ scope: checkpointScopeSchema
5506
+ });
5507
+ var checkpointCutResultSchema = z4.strictObject({
5508
+ sessionId: sessionIdSchema3,
5509
+ cut: checkpointCutViewSchema.nullable()
4670
5510
  });
4671
5511
  var checkpointRequestCodec = codec("dsh-agent-enhancer#CheckpointRollbackRequest", checkpointRollbackRequestSchema);
4672
5512
  var checkpointPreviewCodec = codec("dsh-agent-enhancer#CheckpointRollbackPreview", checkpointPreviewSchema);
4673
5513
  var checkpointResultCodec = codec("dsh-agent-enhancer#CheckpointRollbackResult", checkpointResultSchema);
5514
+ var checkpointSummariesRequestCodec = codec(
5515
+ "dsh-agent-enhancer#CheckpointSummariesRequest",
5516
+ checkpointSummariesRequestSchema
5517
+ );
5518
+ var checkpointSummariesResultCodec = codec(
5519
+ "dsh-agent-enhancer#CheckpointSummariesResult",
5520
+ checkpointSummariesResultSchema
5521
+ );
5522
+ var checkpointCutRequestCodec = codec(
5523
+ "dsh-agent-enhancer#CheckpointCutRequest",
5524
+ checkpointCutRequestSchema
5525
+ );
5526
+ var checkpointCutResultCodec = codec(
5527
+ "dsh-agent-enhancer#CheckpointCutResult",
5528
+ checkpointCutResultSchema
5529
+ );
4674
5530
  var checkpointRemoteInfo = createTypertRemoteInfo({
4675
5531
  package: "dsh-agent-enhancer",
4676
5532
  methods: {
@@ -4689,13 +5545,39 @@ var checkpointRemoteInfo = createTypertRemoteInfo({
4689
5545
  parameters: [{ name: "request", source: "json", codec: checkpointRequestCodec, strictCodec: checkpointRequestCodec }],
4690
5546
  cancellation: { parameter: "signal" },
4691
5547
  result: checkpointResultCodec
5548
+ },
5549
+ "checkpointRollback/summaries": {
5550
+ service: "checkpointRollback",
5551
+ implementation: "summaries",
5552
+ invocation: { kind: "direct" },
5553
+ parameters: [{
5554
+ name: "request",
5555
+ source: "json",
5556
+ codec: checkpointSummariesRequestCodec,
5557
+ strictCodec: checkpointSummariesRequestCodec
5558
+ }],
5559
+ cancellation: { parameter: "signal" },
5560
+ result: checkpointSummariesResultCodec
5561
+ },
5562
+ "checkpointRollback/getCut": {
5563
+ service: "checkpointRollback",
5564
+ implementation: "getCut",
5565
+ invocation: { kind: "direct" },
5566
+ parameters: [{
5567
+ name: "request",
5568
+ source: "json",
5569
+ codec: checkpointCutRequestCodec,
5570
+ strictCodec: checkpointCutRequestCodec
5571
+ }],
5572
+ cancellation: { parameter: "signal" },
5573
+ result: checkpointCutResultCodec
4692
5574
  }
4693
5575
  }
4694
- }, z3);
5576
+ }, z4);
4695
5577
 
4696
5578
  // src/host/update/check.ts
4697
5579
  import { homedir } from "node:os";
4698
- import { join as join5 } from "node:path";
5580
+ import { join as join8 } from "node:path";
4699
5581
 
4700
5582
  // src/host/update/cli.ts
4701
5583
  import { spawn as nodeSpawn } from "node:child_process";
@@ -4766,9 +5648,9 @@ async function runPluginAdd(latest, spawnFn = defaultSpawn) {
4766
5648
 
4767
5649
  // src/host/update/install-kind.ts
4768
5650
  import { lstatSync } from "node:fs";
4769
- import { join as join4 } from "node:path";
5651
+ import { join as join7 } from "node:path";
4770
5652
  function detectInstallKind(profileDir) {
4771
- const pkgPath = join4(profileDir, "node_modules", PACKAGE_NAME);
5653
+ const pkgPath = join7(profileDir, "node_modules", PACKAGE_NAME);
4772
5654
  try {
4773
5655
  const stat = lstatSync(pkgPath);
4774
5656
  if (stat.isSymbolicLink()) return "link";
@@ -4899,8 +5781,8 @@ function isNewerVersion(latest, current) {
4899
5781
 
4900
5782
  // src/host/update/check.ts
4901
5783
  function resolveDesktopProfileDir(env = process.env, home = homedir()) {
4902
- const dshHome = env.DSH_HOME ?? join5(home, ".dsh");
4903
- return join5(dshHome, "profiles", "desktop");
5784
+ const dshHome = env.DSH_HOME ?? join8(home, ".dsh");
5785
+ return join8(dshHome, "profiles", "desktop");
4904
5786
  }
4905
5787
  async function checkPluginUpdate(deps) {
4906
5788
  const latest = await deps.fetchLatest();
@@ -4972,35 +5854,35 @@ var inject = [
4972
5854
  // Official `/compact` runs through the command registry (not ctx.compaction).
4973
5855
  "commands"
4974
5856
  ];
4975
- var Config = z4.object({
4976
- historyEnabled: z4.boolean().default(true).volatile(),
4977
- optimizeEnabled: z4.boolean().default(true).volatile(),
4978
- predictEnabled: z4.boolean().default(true).volatile(),
4979
- rollbackEnabled: z4.boolean().default(true).volatile(),
4980
- contextInspectEnabled: z4.boolean().default(true).volatile(),
5857
+ var Config = z5.object({
5858
+ historyEnabled: z5.boolean().default(true).volatile(),
5859
+ optimizeEnabled: z5.boolean().default(true).volatile(),
5860
+ predictEnabled: z5.boolean().default(true).volatile(),
5861
+ rollbackEnabled: z5.boolean().default(true).volatile(),
5862
+ contextInspectEnabled: z5.boolean().default(true).volatile(),
4981
5863
  // Empty provider/model = follow the current Desktop session model.
4982
- optimizeProvider: z4.string().default("").volatile(),
4983
- optimizeModel: z4.string().default("").volatile(),
4984
- optimizeReasoningEffort: z4.string().default("").volatile(),
4985
- predictProvider: z4.string().default("").volatile(),
4986
- predictModel: z4.string().default("").volatile(),
4987
- predictReasoningEffort: z4.string().default("").volatile(),
4988
- compactProvider: z4.string().default("").volatile(),
4989
- compactModel: z4.string().default("").volatile(),
4990
- compactReasoningEffort: z4.string().default("").volatile(),
4991
- autoClassifierEnabled: z4.boolean().default(false).volatile(),
4992
- autoInstantProvider: z4.string().default("").volatile(),
4993
- autoInstantModel: z4.string().default("").volatile(),
4994
- autoInstantReasoningEffort: z4.string().default("").volatile(),
4995
- autoThinkingProvider: z4.string().default("").volatile(),
4996
- autoThinkingModel: z4.string().default("").volatile(),
4997
- autoThinkingReasoningEffort: z4.string().default("").volatile(),
4998
- autoProProvider: z4.string().default("").volatile(),
4999
- autoProModel: z4.string().default("").volatile(),
5000
- autoProReasoningEffort: z4.string().default("").volatile(),
5001
- autoClassifierProvider: z4.string().default("").volatile(),
5002
- autoClassifierModel: z4.string().default("").volatile(),
5003
- autoClassifierReasoningEffort: z4.string().default("").volatile()
5864
+ optimizeProvider: z5.string().default("").volatile(),
5865
+ optimizeModel: z5.string().default("").volatile(),
5866
+ optimizeReasoningEffort: z5.string().default("").volatile(),
5867
+ predictProvider: z5.string().default("").volatile(),
5868
+ predictModel: z5.string().default("").volatile(),
5869
+ predictReasoningEffort: z5.string().default("").volatile(),
5870
+ compactProvider: z5.string().default("").volatile(),
5871
+ compactModel: z5.string().default("").volatile(),
5872
+ compactReasoningEffort: z5.string().default("").volatile(),
5873
+ autoClassifierEnabled: z5.boolean().default(false).volatile(),
5874
+ autoInstantProvider: z5.string().default("").volatile(),
5875
+ autoInstantModel: z5.string().default("").volatile(),
5876
+ autoInstantReasoningEffort: z5.string().default("").volatile(),
5877
+ autoThinkingProvider: z5.string().default("").volatile(),
5878
+ autoThinkingModel: z5.string().default("").volatile(),
5879
+ autoThinkingReasoningEffort: z5.string().default("").volatile(),
5880
+ autoProProvider: z5.string().default("").volatile(),
5881
+ autoProModel: z5.string().default("").volatile(),
5882
+ autoProReasoningEffort: z5.string().default("").volatile(),
5883
+ autoClassifierProvider: z5.string().default("").volatile(),
5884
+ autoClassifierModel: z5.string().default("").volatile(),
5885
+ autoClassifierReasoningEffort: z5.string().default("").volatile()
5004
5886
  });
5005
5887
  var hostContribution = {
5006
5888
  package: PACKAGE_NAME,
@@ -5128,14 +6010,14 @@ var AgentEnhancerService = class extends TypertRemoteService {
5128
6010
  }
5129
6011
  };
5130
6012
  function resolveCheckpointRoot(dshHome) {
5131
- const base = join6(dshHome, "profiles", "desktop", "plugin-data");
5132
- const nextPkg = join6(base, PACKAGE_NAME);
5133
- const next = join6(nextPkg, "checkpoint");
5134
- const prev = join6(base, LEGACY_PACKAGE_NAME, "checkpoint");
6013
+ const base = join9(dshHome, "profiles", "desktop", "plugin-data");
6014
+ const nextPkg = join9(base, PACKAGE_NAME);
6015
+ const next = join9(nextPkg, "checkpoint");
6016
+ const prev = join9(base, LEGACY_PACKAGE_NAME, "checkpoint");
5135
6017
  if (!existsSync(next) && existsSync(prev)) {
5136
6018
  mkdirSync(nextPkg, { recursive: true });
5137
6019
  renameSync(prev, next);
5138
- const prevPkg = join6(base, LEGACY_PACKAGE_NAME);
6020
+ const prevPkg = join9(base, LEGACY_PACKAGE_NAME);
5139
6021
  try {
5140
6022
  if (existsSync(prevPkg) && readdirSync(prevPkg).length === 0) rmdirSync(prevPkg);
5141
6023
  } catch {
@@ -5201,8 +6083,8 @@ function apply(ctx, config) {
5201
6083
  const settings = () => readSettings(config);
5202
6084
  const models = new AuxiliaryModels(ctx, settings);
5203
6085
  installAutoSessionRoute(ctx, { settings });
5204
- const storageRoot = resolveCheckpointRoot(process.env.DSH_HOME ?? join6(homedir2(), ".dsh"));
5205
- const usage = new UsageLedger(join6(storageRoot, "..", "usage"), (message) => {
6086
+ const storageRoot = resolveCheckpointRoot(process.env.DSH_HOME ?? join9(homedir2(), ".dsh"));
6087
+ const usage = new UsageLedger(join9(storageRoot, "..", "usage"), (message) => {
5206
6088
  ctx.logger.warn(message);
5207
6089
  });
5208
6090
  const balancesFacade = (() => {
@@ -5252,6 +6134,8 @@ function apply(ctx, config) {
5252
6134
  );
5253
6135
  ctx.effect(() => ctx.typert.register(hostContribution));
5254
6136
  const store = new CheckpointStore(storageRoot);
6137
+ const cutStore = new SessionCutStore(join9(storageRoot, "cuts"));
6138
+ const cutCache = /* @__PURE__ */ new Map();
5255
6139
  const sessions = new DshCheckpointSessions(ctx);
5256
6140
  let rollbackEnabled = config.rollbackEnabled.get();
5257
6141
  const captures = new DshCheckpointCaptureSwitch(ctx, { store, pluginVersion: PACKAGE_VERSION });
@@ -5261,17 +6145,20 @@ function apply(ctx, config) {
5261
6145
  pluginVersion: PACKAGE_VERSION,
5262
6146
  resolveSession: sessions.resolveSession,
5263
6147
  isEnabled: () => rollbackEnabled,
5264
- awaitCaptures: () => captures.awaitPending()
6148
+ awaitCaptures: () => captures.awaitPending(),
6149
+ cutStore,
6150
+ cutCache
5265
6151
  });
5266
6152
  applyCheckpointRollback(ctx, rollback);
5267
6153
  void rollback.recover().catch(() => {
5268
6154
  ctx.logger.warn("Checkpoint rollback recovery is still pending");
5269
6155
  });
6156
+ ctx.effect(() => installSessionCutFilter(ctx, { store: cutStore, cache: cutCache }));
5270
6157
  ctx.effect(() => {
5271
- const unsubscribe = ctx.on("internal/update", (updated, _noSave, next) => {
5272
- rollbackEnabled = updated.rollbackEnabled.get();
6158
+ const unsubscribe = ctx.on("internal/update", (resolvedConfig, next) => {
6159
+ rollbackEnabled = resolvedConfig.rollbackEnabled.get();
5273
6160
  captures.setEnabled(rollbackEnabled);
5274
- next();
6161
+ return next();
5275
6162
  });
5276
6163
  captures.setEnabled(rollbackEnabled);
5277
6164
  return async () => {
@@ -5310,6 +6197,22 @@ var CheckpointRollbackRemoteService = class extends TypertRemoteService {
5310
6197
  throw this.remoteError(error, signal);
5311
6198
  }
5312
6199
  }
6200
+ async summaries(request, signal) {
6201
+ this.assertOwner();
6202
+ try {
6203
+ return await this.rollback.summaries(request, signal);
6204
+ } catch (error) {
6205
+ throw this.remoteError(error, signal);
6206
+ }
6207
+ }
6208
+ async getCut(request, signal) {
6209
+ this.assertOwner();
6210
+ try {
6211
+ return await this.rollback.getCut(request, signal);
6212
+ } catch (error) {
6213
+ throw this.remoteError(error, signal);
6214
+ }
6215
+ }
5313
6216
  assertOwner() {
5314
6217
  if (this.ctx.invocation?.peer.principal.kind !== "owner") {
5315
6218
  throw new RemoteError("agent-enhancer/forbidden", "Only the desktop owner may use checkpoint rollback", {});