dsh-agent-enhancer 0.3.1 → 0.3.3

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 (71) hide show
  1. package/README.en.md +15 -22
  2. package/README.md +15 -22
  3. package/lib/client/dsh/controls.d.ts.map +1 -1
  4. package/lib/client/dsh/persist-settings.d.ts +71 -0
  5. package/lib/client/dsh/persist-settings.d.ts.map +1 -0
  6. package/lib/client/dsh/settings-form.d.ts +19 -1
  7. package/lib/client/dsh/settings-form.d.ts.map +1 -1
  8. package/lib/client/dsh/settings.d.ts +4 -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 +39 -27
  12. package/lib/client/locales.d.ts.map +1 -1
  13. package/lib/client/rollback/controller.d.ts +1 -0
  14. package/lib/client/rollback/controller.d.ts.map +1 -1
  15. package/lib/client/rollback/cut-cache.d.ts +13 -0
  16. package/lib/client/rollback/cut-cache.d.ts.map +1 -0
  17. package/lib/client/rollback/modal-host.d.ts.map +1 -1
  18. package/lib/client/rollback/remote.d.ts +2 -1
  19. package/lib/client/rollback/remote.d.ts.map +1 -1
  20. package/lib/client/rollback/scope.d.ts +3 -1
  21. package/lib/client/rollback/scope.d.ts.map +1 -1
  22. package/lib/client/rollback/session-stats-dock.d.ts +1 -1
  23. package/lib/client/rollback/session-stats-dock.d.ts.map +1 -1
  24. package/lib/client/rollback/session-stats-filter.d.ts +9 -8
  25. package/lib/client/rollback/session-stats-filter.d.ts.map +1 -1
  26. package/lib/client/rollback/session-stats-meter.d.ts +4 -2
  27. package/lib/client/rollback/session-stats-meter.d.ts.map +1 -1
  28. package/lib/client/rollback/timeline-panel.d.ts +2 -4
  29. package/lib/client/rollback/timeline-panel.d.ts.map +1 -1
  30. package/lib/client/rollback/timeline-tab.d.ts +3 -2
  31. package/lib/client/rollback/timeline-tab.d.ts.map +1 -1
  32. package/lib/client/rollback/transcript-filter.d.ts +16 -6
  33. package/lib/client/rollback/transcript-filter.d.ts.map +1 -1
  34. package/lib/client/rollback/transcript.d.ts +15 -9
  35. package/lib/client/rollback/transcript.d.ts.map +1 -1
  36. package/lib/client/rollback/types.d.ts +4 -1
  37. package/lib/client/rollback/types.d.ts.map +1 -1
  38. package/lib/client/rollback/user-node.d.ts.map +1 -1
  39. package/lib/client.js +612 -346
  40. package/lib/client.js.map +1 -1
  41. package/lib/config.d.ts +3 -1
  42. package/lib/config.d.ts.map +1 -1
  43. package/lib/host/auto-route/classifier.d.ts.map +1 -1
  44. package/lib/host/auto-route/session-hook.d.ts.map +1 -1
  45. package/lib/host/auto-route/session-selection.d.ts +5 -1
  46. package/lib/host/auto-route/session-selection.d.ts.map +1 -1
  47. package/lib/host/checkpoint/chain-files.d.ts +35 -0
  48. package/lib/host/checkpoint/chain-files.d.ts.map +1 -0
  49. package/lib/host/checkpoint/cut-filter.d.ts +9 -0
  50. package/lib/host/checkpoint/cut-filter.d.ts.map +1 -0
  51. package/lib/host/checkpoint/cut-live.d.ts +13 -0
  52. package/lib/host/checkpoint/cut-live.d.ts.map +1 -0
  53. package/lib/host/checkpoint/cut-store.d.ts +30 -0
  54. package/lib/host/checkpoint/cut-store.d.ts.map +1 -0
  55. package/lib/host/checkpoint/dsh.d.ts.map +1 -1
  56. package/lib/host/checkpoint/files.d.ts.map +1 -1
  57. package/lib/host/checkpoint/live.d.ts +1 -0
  58. package/lib/host/checkpoint/live.d.ts.map +1 -1
  59. package/lib/host/checkpoint/service.d.ts +44 -5
  60. package/lib/host/checkpoint/service.d.ts.map +1 -1
  61. package/lib/host/checkpoint/store.d.ts +6 -0
  62. package/lib/host/checkpoint/store.d.ts.map +1 -1
  63. package/lib/host/index.d.ts +2 -1
  64. package/lib/host/index.d.ts.map +1 -1
  65. package/lib/host/model.d.ts.map +1 -1
  66. package/lib/host/rpc.d.ts +4 -0
  67. package/lib/host/rpc.d.ts.map +1 -1
  68. package/lib/identity.d.ts +1 -1
  69. package/lib/index.js +1063 -1086
  70. package/lib/index.js.map +4 -4
  71. package/package.json +4 -2
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 join8 } 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.3.1";
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:`;
@@ -247,9 +247,7 @@ async function buildAuxiliaryModelCatalog(ctx) {
247
247
  function syncIdleLastTurnFromProjection(ctx, agent) {
248
248
  if (agent.status !== "idle") return;
249
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;
250
+ const lastTurn = agents.turnBoundaryOf?.(agent.session)?.lastTurn;
253
251
  if (typeof lastTurn !== "number") return;
254
252
  const live = agent;
255
253
  if (live.phase?.kind !== "idle" || live.phase.lastTurn === lastTurn) return;
@@ -267,21 +265,25 @@ var DshCheckpointSessions = class {
267
265
  adapters = /* @__PURE__ */ new Map();
268
266
  resolveSession = (sessionId) => {
269
267
  const agent = this.ctx.agents.get(sessionId);
270
- if (agent === void 0 || this.ctx.get("sessions").get(sessionId) !== agent.session) {
268
+ const stored = this.ctx.get("sessions").get(sessionId);
269
+ if (agent === void 0 || stored === void 0 || stored.id !== agent.session.id) {
271
270
  this.adapters.delete(sessionId);
272
271
  return void 0;
273
272
  }
274
273
  const cached = this.adapters.get(sessionId);
275
274
  if (cached?.agent === agent) return cached.adapter;
276
- const workspaceRoot = agent.session.header.cwd ?? "";
277
275
  const adapter = {
278
- session: agent.session,
279
- workspaceRoot,
276
+ get session() {
277
+ return agent.session;
278
+ },
279
+ get workspaceRoot() {
280
+ return agent.session.header.cwd ?? "";
281
+ },
280
282
  get status() {
281
283
  return agent.status;
282
284
  },
283
285
  get canRestore() {
284
- return workspaceRoot !== "";
286
+ return (agent.session.header.cwd ?? "") !== "";
285
287
  },
286
288
  readEvents: () => agent.session.snapshotEvents(),
287
289
  runMaintenance: async (task) => {
@@ -291,10 +293,11 @@ var DshCheckpointSessions = class {
291
293
  },
292
294
  synchronize: async (signal) => {
293
295
  signal.throwIfAborted();
294
- this.ctx.sessionProjections.snapshot(agent.session);
295
- await this.ctx.get("sessions").flush(agent.session);
296
+ const session = agent.session;
297
+ this.ctx.sessionProjections.snapshot(session);
298
+ await this.ctx.get("sessions").flush(session);
296
299
  signal.throwIfAborted();
297
- this.ctx.sessionProjections.snapshot(agent.session);
300
+ this.ctx.sessionProjections.snapshot(session);
298
301
  }
299
302
  };
300
303
  this.adapters.set(sessionId, { agent, adapter });
@@ -809,7 +812,6 @@ var CheckpointFiles = class {
809
812
  await journal.compensate();
810
813
  throw new CheckpointFileError("FILE_RESTORE_FAILED");
811
814
  }
812
- if (!result.synchronized) throw new CheckpointFileError("FILE_RESTORE_FAILED");
813
815
  try {
814
816
  await journal.complete("completed");
815
817
  return journal;
@@ -1109,10 +1111,11 @@ var DshCheckpointCapture = class {
1109
1111
  this.options = options;
1110
1112
  this.disposers.push(
1111
1113
  ctx.on("agent/pre-step", async (payload, next) => {
1112
- const current = this.turns.get(payload.agent.id);
1114
+ const sessionId = payload.agent.session.id;
1115
+ const current = this.turns.get(sessionId);
1113
1116
  const startsTurn = current === void 0 || current.turnStart !== null && current.turnStart.data.turn !== payload.turn;
1114
1117
  if (!this.closed && startsTurn && payload.agent.session.header.origin !== "subagent") {
1115
- this.turns.set(payload.agent.id, {
1118
+ this.turns.set(sessionId, {
1116
1119
  agent: payload.agent,
1117
1120
  prompt: payload.messages.find((message) => message.source.kind === "user") ?? null,
1118
1121
  turnStart: null,
@@ -1163,7 +1166,7 @@ var DshCheckpointCapture = class {
1163
1166
  // this flag the host plugin's listener is filtered out and never runs.
1164
1167
  ctx.on("tools/execute", async (exec, next) => {
1165
1168
  if (exec.agent === void 0) return next();
1166
- const current = this.turns.get(exec.agent.id);
1169
+ const current = this.turns.get(exec.agent.session.id);
1167
1170
  this.actors.set(exec, exec.agent);
1168
1171
  try {
1169
1172
  if (current !== void 0 && isFileMutationTool(exec.name)) {
@@ -1216,7 +1219,7 @@ var DshCheckpointCapture = class {
1216
1219
  if (!this.closed) await this.options.store.save(checkpoint);
1217
1220
  }
1218
1221
  },
1219
- sessionId: turn.agent.id,
1222
+ sessionId: turn.agent.session.id,
1220
1223
  session: {
1221
1224
  format: turn.agent.session.header.version,
1222
1225
  preset: turn.agent.session.header.agentPreset ?? null
@@ -1274,12 +1277,15 @@ var DshCheckpointCapture = class {
1274
1277
  }
1275
1278
  }
1276
1279
  }
1280
+ turnOf(agent) {
1281
+ return this.turns.get(agent.session.id);
1282
+ }
1277
1283
  async captureToolPath(agent, args) {
1278
1284
  const path = filePathFromToolArgs(args);
1279
1285
  if (path === null) return;
1280
1286
  const workspaceRoot = agent.session.header.cwd;
1281
1287
  if (workspaceRoot === void 0) {
1282
- const turn = this.turns.get(agent.id);
1288
+ const turn = this.turnOf(agent);
1283
1289
  if (turn !== void 0) turn.incomplete = true;
1284
1290
  return;
1285
1291
  }
@@ -1287,7 +1293,7 @@ var DshCheckpointCapture = class {
1287
1293
  const absolutePath2 = isAbsolute2(path) ? path : join3(workspaceRoot, path);
1288
1294
  await this.captureAbsolutePath(agent, absolutePath2);
1289
1295
  } catch {
1290
- const turn = this.turns.get(agent.id);
1296
+ const turn = this.turnOf(agent);
1291
1297
  if (turn !== void 0) turn.incomplete = true;
1292
1298
  }
1293
1299
  }
@@ -1300,12 +1306,12 @@ var DshCheckpointCapture = class {
1300
1306
  const absolutePath2 = this.ctx.fs.processPath(target);
1301
1307
  await this.captureAbsolutePath(agent, absolutePath2);
1302
1308
  } catch {
1303
- const turn = this.turns.get(agent.id);
1309
+ const turn = this.turnOf(agent);
1304
1310
  if (turn !== void 0) turn.incomplete = true;
1305
1311
  }
1306
1312
  }
1307
1313
  async captureAbsolutePath(agent, absolutePath2) {
1308
- const turn = this.turns.get(agent.id);
1314
+ const turn = this.turnOf(agent);
1309
1315
  if (turn === void 0) return;
1310
1316
  const workspaceRoot = agent.session.header.cwd;
1311
1317
  if (workspaceRoot === void 0) {
@@ -1397,7 +1403,7 @@ var DshCheckpointCaptureSwitch = class {
1397
1403
  };
1398
1404
 
1399
1405
  // src/host/checkpoint/service.ts
1400
- import { randomUUID as randomUUID3 } from "node:crypto";
1406
+ import { randomUUID as randomUUID4 } from "node:crypto";
1401
1407
  import { MessageId } from "@deepseek-ai/dsh-llm";
1402
1408
  import { SessionSeq } from "@deepseek-ai/dsh-session";
1403
1409
 
@@ -1439,6 +1445,223 @@ function blockingUnavailable(unavailable, scope, options = {}) {
1439
1445
  return unavailable.filter((reason) => !soft.has(reason));
1440
1446
  }
1441
1447
 
1448
+ // src/host/checkpoint/chain-files.ts
1449
+ function netFileChange(earliest, latest) {
1450
+ if (earliest.beforeText === null && latest.afterText === null) return null;
1451
+ if (earliest.beforeText === null) return "create";
1452
+ if (latest.afterText === null) return "delete";
1453
+ return "modify";
1454
+ }
1455
+ function chainTrackedFiles(checkpoints, fromTurnOrRange, untilTurnExclusive) {
1456
+ const range = typeof fromTurnOrRange === "number" ? { fromTurn: fromTurnOrRange, untilTurnExclusive } : fromTurnOrRange;
1457
+ if (!Number.isFinite(range.fromTurn) && range.fromAtSeq === void 0) return [];
1458
+ const inRange = checkpoints.filter((checkpoint) => {
1459
+ if (range.fromAtSeq !== void 0) {
1460
+ if (checkpoint.atSeq < range.fromAtSeq) return false;
1461
+ if (range.untilAtSeqExclusive !== void 0 && checkpoint.atSeq >= range.untilAtSeqExclusive) {
1462
+ return false;
1463
+ }
1464
+ return true;
1465
+ }
1466
+ return checkpoint.turn >= range.fromTurn && (range.untilTurnExclusive === void 0 || checkpoint.turn < range.untilTurnExclusive);
1467
+ }).slice().sort((left, right) => left.atSeq - right.atSeq || left.turn - right.turn);
1468
+ const byPath = /* @__PURE__ */ new Map();
1469
+ for (const checkpoint of inRange) {
1470
+ for (const file of checkpoint.files) {
1471
+ const previous = byPath.get(file.path);
1472
+ if (previous === void 0) {
1473
+ byPath.set(file.path, { earliest: file, latest: file });
1474
+ continue;
1475
+ }
1476
+ byPath.set(file.path, { earliest: previous.earliest, latest: file });
1477
+ }
1478
+ }
1479
+ const chained = [];
1480
+ for (const { earliest, latest } of byPath.values()) {
1481
+ const change = netFileChange(earliest, latest);
1482
+ if (change === null) continue;
1483
+ chained.push({
1484
+ path: earliest.path,
1485
+ change,
1486
+ beforeText: earliest.beforeText,
1487
+ beforeHash: earliest.beforeHash,
1488
+ afterText: latest.afterText,
1489
+ afterHash: latest.afterHash
1490
+ });
1491
+ }
1492
+ return chained;
1493
+ }
1494
+
1495
+ // src/host/checkpoint/cut-store.ts
1496
+ import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
1497
+ import { chmod as chmod2, mkdir as mkdir2, readFile as readFile2, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
1498
+ import { basename as basename2, join as join4 } from "node:path";
1499
+ import { z } from "zod";
1500
+ var SCHEMA_VERSION = 1;
1501
+ var queues = /* @__PURE__ */ new Map();
1502
+ async function serialize2(key, operation) {
1503
+ const previous = queues.get(key) ?? Promise.resolve();
1504
+ const result = previous.then(operation);
1505
+ const tail = result.then(() => void 0, () => void 0);
1506
+ queues.set(key, tail);
1507
+ try {
1508
+ return await result;
1509
+ } finally {
1510
+ if (queues.get(key) === tail) queues.delete(key);
1511
+ }
1512
+ }
1513
+ var sessionIdSchema = z.string().min(1).transform((value) => value);
1514
+ var cutSchema = z.lazy(() => z.object({
1515
+ hideTurnsFrom: z.number().int().positive(),
1516
+ cutSeq: z.number().int().nonnegative(),
1517
+ restoredAtSeq: z.number().int().nonnegative(),
1518
+ draftPrompt: z.string(),
1519
+ scope: z.enum(["conversation", "conversation-and-files"]),
1520
+ journalId: z.string().min(1).optional(),
1521
+ previous: cutSchema.nullable()
1522
+ }).strict());
1523
+ var fileSchema = z.object({
1524
+ schemaVersion: z.literal(SCHEMA_VERSION),
1525
+ sessionId: sessionIdSchema,
1526
+ cut: cutSchema.nullable()
1527
+ }).strict();
1528
+ function digest2(value) {
1529
+ return createHash2("sha256").update(value).digest("hex");
1530
+ }
1531
+ function isMissing2(error) {
1532
+ return typeof error === "object" && error !== null && error.code === "ENOENT";
1533
+ }
1534
+ async function removeIfPresent2(path) {
1535
+ try {
1536
+ await unlink2(path);
1537
+ } catch (error) {
1538
+ if (!isMissing2(error)) throw error;
1539
+ }
1540
+ }
1541
+ async function writeAtomic2(path, value) {
1542
+ const temporary = join4(join4(path, ".."), `.${basename2(path)}.${randomUUID3()}.tmp`);
1543
+ try {
1544
+ await writeFile2(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
1545
+ await rename2(temporary, path);
1546
+ await chmod2(path, 384);
1547
+ } finally {
1548
+ await removeIfPresent2(temporary);
1549
+ }
1550
+ }
1551
+ function isWithdrawnByCut(cut, seq) {
1552
+ return seq > cut.cutSeq && seq <= cut.restoredAtSeq;
1553
+ }
1554
+ var SessionCutStore = class {
1555
+ constructor(root) {
1556
+ this.root = root;
1557
+ this.directory = join4(root, "sessions");
1558
+ this.rootKey = join4(root, ".");
1559
+ }
1560
+ root;
1561
+ directory;
1562
+ rootKey;
1563
+ async get(sessionId) {
1564
+ await mkdir2(this.directory, { recursive: true, mode: 448 });
1565
+ const path = this.pathOf(sessionId);
1566
+ let stored;
1567
+ try {
1568
+ stored = JSON.parse(await readFile2(path, "utf8"));
1569
+ } catch (error) {
1570
+ if (isMissing2(error)) return null;
1571
+ throw error;
1572
+ }
1573
+ const parsed = fileSchema.safeParse(stored);
1574
+ if (!parsed.success) return null;
1575
+ return parsed.data.cut;
1576
+ }
1577
+ async set(sessionId, cut) {
1578
+ return serialize2(`${this.rootKey}\0${sessionId}`, async () => {
1579
+ await mkdir2(this.directory, { recursive: true, mode: 448 });
1580
+ const path = this.pathOf(sessionId);
1581
+ if (cut === null) {
1582
+ await removeIfPresent2(path);
1583
+ return null;
1584
+ }
1585
+ await writeAtomic2(path, {
1586
+ schemaVersion: SCHEMA_VERSION,
1587
+ sessionId,
1588
+ cut
1589
+ });
1590
+ return cut;
1591
+ });
1592
+ }
1593
+ pathOf(sessionId) {
1594
+ return join4(this.directory, `${digest2(sessionId)}.json`);
1595
+ }
1596
+ };
1597
+
1598
+ // src/host/checkpoint/cut-filter.ts
1599
+ function deriveMessagesWithCut(session, cut) {
1600
+ if (cut === null || cut === void 0) {
1601
+ }
1602
+ const events = session.snapshotEvents();
1603
+ const bySeq = new Map(events.map((event) => [Number(event.seq), event]));
1604
+ const messages = [];
1605
+ for (const seq of session.surface.nodes) {
1606
+ const value = Number(seq);
1607
+ const event = bySeq.get(value);
1608
+ if (event === void 0) continue;
1609
+ const keepSystem = event.type === "system/message";
1610
+ if (cut !== null && cut !== void 0 && isWithdrawnByCut(cut, value) && !keepSystem) continue;
1611
+ const message = session.deriveEventMessage(event);
1612
+ if (message !== null) messages.push(message);
1613
+ }
1614
+ return messages;
1615
+ }
1616
+
1617
+ // src/host/checkpoint/cut-live.ts
1618
+ function installSessionCutFilter(ctx, options) {
1619
+ const patched = /* @__PURE__ */ new WeakSet();
1620
+ const patchSession = (session) => {
1621
+ if (patched.has(session)) return;
1622
+ patched.add(session);
1623
+ const native = session.deriveMessages.bind(session);
1624
+ session.deriveMessages = () => {
1625
+ const cut = options.cache.get(session.id);
1626
+ if (cut === void 0 || cut === null) return native();
1627
+ return deriveMessagesWithCut(session, cut);
1628
+ };
1629
+ };
1630
+ const warm = async (sessionId) => {
1631
+ if (options.cache.has(sessionId)) return;
1632
+ const cut = await options.store.get(sessionId);
1633
+ options.cache.set(sessionId, cut);
1634
+ };
1635
+ const disposers = [];
1636
+ disposers.push(ctx.on("agent/pre-step", async (payload, next) => {
1637
+ const agent = payload.agent;
1638
+ patchSession(agent.session);
1639
+ await warm(agent.session.id);
1640
+ return next();
1641
+ }));
1642
+ const agents = ctx.agents;
1643
+ if (agents !== void 0 && typeof agents.get === "function") {
1644
+ const inner = agents.get.bind(agents);
1645
+ agents.get = ((id) => {
1646
+ const agent = inner(id);
1647
+ if (agent?.session !== void 0) {
1648
+ patchSession(agent.session);
1649
+ void warm(agent.session.id);
1650
+ }
1651
+ return agent;
1652
+ });
1653
+ disposers.push(() => {
1654
+ if (agents.get !== inner) agents.get = inner;
1655
+ });
1656
+ }
1657
+ return () => {
1658
+ while (disposers.length > 0) disposers.pop()?.();
1659
+ };
1660
+ }
1661
+ function syncCutCache(cache, sessionId, cut) {
1662
+ cache.set(sessionId, cut);
1663
+ }
1664
+
1442
1665
  // src/host/checkpoint/service.ts
1443
1666
  var surfaceEventTypes = /* @__PURE__ */ new Set(["system/message", "developer/message", "user/message", "assistant/message", "tool/result"]);
1444
1667
  var PROMPT_PREVIEW_MAX = 96;
@@ -1467,6 +1690,43 @@ function toCheckpointTurnSummary(checkpoint, options = {}) {
1467
1690
  tip
1468
1691
  };
1469
1692
  }
1693
+ function summaryFromClosedTurn(events, turn, options = {}) {
1694
+ const turnStart = events.find(
1695
+ (event) => event.type === "turn/start" && event.data.turn === turn
1696
+ );
1697
+ if (turnStart === void 0) return null;
1698
+ const prompt = recoverTurnPrompt(events, turn);
1699
+ return {
1700
+ turn,
1701
+ coverage: "complete",
1702
+ fileCount: 0,
1703
+ createdAt: options.now ?? Date.now(),
1704
+ atSeq: checkpointAtSeq(Number(turnStart.seq)),
1705
+ prompt,
1706
+ promptPreview: checkpointPromptPreview(prompt),
1707
+ files: [],
1708
+ gaps: [],
1709
+ rolledBack: options.rolledBack ?? false,
1710
+ tip: options.tip ?? false
1711
+ };
1712
+ }
1713
+ function cutViewOf(cut) {
1714
+ return {
1715
+ hideTurnsFrom: cut.hideTurnsFrom,
1716
+ cutSeq: cut.cutSeq,
1717
+ restoredAtSeq: cut.restoredAtSeq,
1718
+ draftPrompt: cut.draftPrompt,
1719
+ scope: cut.scope
1720
+ };
1721
+ }
1722
+ function windowFromCut(cut) {
1723
+ if (cut === null || cut === void 0) return void 0;
1724
+ return {
1725
+ tipTurn: cut.hideTurnsFrom,
1726
+ hideTurnsFrom: cut.hideTurnsFrom,
1727
+ continueAfterSeq: cut.restoredAtSeq
1728
+ };
1729
+ }
1470
1730
  var CheckpointRollbackError = class extends Error {
1471
1731
  constructor(code, unavailable = [], conflicts = []) {
1472
1732
  super(code);
@@ -1479,28 +1739,9 @@ var CheckpointRollbackError = class extends Error {
1479
1739
  unavailable;
1480
1740
  conflicts;
1481
1741
  };
1482
- function rollbackMarkerId(turn, journalId, scope) {
1483
- const tag = scope === "conversation" ? "c:" : "";
1484
- return MessageId(`${ROLLBACK_PREFIX}${turn}:${tag}${journalId}`);
1485
- }
1486
1742
  function undoCopyId(journalId, index) {
1487
1743
  return MessageId(`${UNDO_PREFIX}${journalId}:${index}`);
1488
1744
  }
1489
- function rollbackIdOf(id) {
1490
- const start = indexOfRollbackPrefix(id);
1491
- return start >= 0 ? id.slice(start) : id;
1492
- }
1493
- function scopeOfMarkerId(id) {
1494
- const rolled = rollbackIdOf(id);
1495
- for (const prefix of [ROLLBACK_PREFIX, LEGACY_ROLLBACK_PREFIX]) {
1496
- const pattern = new RegExp(`^${prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\d+:c:`);
1497
- if (pattern.test(rolled)) return "conversation";
1498
- }
1499
- return "conversation-and-files";
1500
- }
1501
- function scopeOfMarker(event) {
1502
- return scopeOfMarkerId(event.data.id);
1503
- }
1504
1745
  function isRollbackMarker(event, turn) {
1505
1746
  if (event?.type !== "user/message" || event.data.source.kind !== "checkpoint-rollback" || event.data.source.form !== "notice" || event.data.content.length === 0) return false;
1506
1747
  const prefixes = turn === void 0 ? [ROLLBACK_PREFIX, LEGACY_ROLLBACK_PREFIX] : [`${ROLLBACK_PREFIX}${turn}:`, `${LEGACY_ROLLBACK_PREFIX}${turn}:`];
@@ -1567,28 +1808,12 @@ function isUndoCopyAt(event, expected) {
1567
1808
  const id = surfaceMessageId2(event);
1568
1809
  return id === expected || (id?.startsWith(`${expected}:`) ?? false);
1569
1810
  }
1570
- function logicalSeq(event) {
1571
- if (isUndoCopy(event)) {
1572
- const match = surfaceMessageId2(event)?.match(/:(\d+)(?::dsh-(?:agent|composer)-enhancer:rollback:.*)?$/);
1573
- if (match !== null && match !== void 0) return SessionSeq(Number(match[1]));
1574
- }
1575
- return event.seq;
1576
- }
1577
1811
  function isOwnReplacement(event) {
1578
1812
  return isRollbackMarker(event) || isUndoCopy(event);
1579
1813
  }
1580
1814
  function isProtectedSystemMessage(event) {
1581
1815
  return event?.type === "system/message";
1582
1816
  }
1583
- function rollbackSurfaceNodes(events, candidates) {
1584
- return candidates.filter((node) => !isProtectedSystemMessage(events[node]));
1585
- }
1586
- function isAlreadyRestoredRollback(events, nodes, turn, surfaceNodes) {
1587
- if (nodes.length === 0) return false;
1588
- if (!nodes.every((node) => isRollbackMarker(events[node]))) return false;
1589
- const window = activeRollbackWindow(events, surfaceNodes);
1590
- return window !== void 0 && turn === window.tipTurn;
1591
- }
1592
1817
  function abortError() {
1593
1818
  return new DOMException("Checkpoint rollback was cancelled", "AbortError");
1594
1819
  }
@@ -1614,278 +1839,6 @@ function scopeOf(request) {
1614
1839
  function directionOf(operation) {
1615
1840
  return operation === "rollback" ? "rollback" : "undo";
1616
1841
  }
1617
- function turnOwningSeq(events, seq) {
1618
- let current;
1619
- for (const event of events) {
1620
- if (Number(event.seq) > seq) break;
1621
- if (event.type === "turn/start") current = event.data.turn;
1622
- }
1623
- return current;
1624
- }
1625
- function logicalTurnOwning(events, event) {
1626
- return turnOwningSeq(events, Number(logicalSeq(event)));
1627
- }
1628
- function sourceEvents(events, marker) {
1629
- if (marker.surfaceOp === "append" && marker.sourceEventSeqs?.length === 1) {
1630
- const original = events[marker.sourceEventSeqs[0]];
1631
- if (isRollbackMarker(original)) return sourceEvents(events, original);
1632
- }
1633
- if (marker.sourceEventSeqs === void 0 || marker.sourceEventSeqs.length === 0) return null;
1634
- const sources = [];
1635
- for (const seq of marker.sourceEventSeqs) {
1636
- const event = events[seq];
1637
- if (event === void 0) return null;
1638
- if (isRollbackMarker(event)) {
1639
- const nested = sourceEvents(events, event);
1640
- if (nested === null) return null;
1641
- sources.push(...nested);
1642
- continue;
1643
- }
1644
- if (!surfaceEventTypes.has(event.type)) return null;
1645
- sources.push(event);
1646
- }
1647
- if (sources[0]?.type !== "user/message") return null;
1648
- return sources;
1649
- }
1650
- function peelUndoSources(events, sources, tipTurn) {
1651
- const reappear = sources.filter((event) => logicalTurnOwning(events, event) === tipTurn);
1652
- const stillWithdraw = sources.filter((event) => {
1653
- const owned = logicalTurnOwning(events, event);
1654
- return owned !== void 0 && owned !== tipTurn;
1655
- });
1656
- if (reappear.length === 0 || stillWithdraw.length === 0) {
1657
- return { undoSources: sources, nextTip: void 0 };
1658
- }
1659
- const nextTipTurn = stillWithdraw.reduce((min, event) => {
1660
- const owned = logicalTurnOwning(events, event);
1661
- return owned === void 0 ? min : Math.min(min, owned);
1662
- }, Number.POSITIVE_INFINITY);
1663
- if (!Number.isFinite(nextTipTurn)) return { undoSources: sources, nextTip: void 0 };
1664
- return {
1665
- undoSources: reappear,
1666
- nextTip: { turn: nextTipTurn, sources: stillWithdraw }
1667
- };
1668
- }
1669
- function nextTurnNumber(events) {
1670
- let max = 0;
1671
- for (const event of events) {
1672
- if (event.type === "turn/start") max = Math.max(max, event.data.turn);
1673
- }
1674
- return max + 1;
1675
- }
1676
- function undoTurnAfterMarker(events, markerSeq) {
1677
- for (const event of events) {
1678
- if (Number(event.seq) > Number(markerSeq) && event.type === "turn/start") {
1679
- return event.data.turn;
1680
- }
1681
- }
1682
- throw new Error("Partial undo is missing its turn/start");
1683
- }
1684
- function tipRollbackMarker(events, nodes, turn) {
1685
- let tip;
1686
- for (const node of nodes) {
1687
- const event = events[node];
1688
- if (!isRollbackMarker(event, turn) || !markerStillActive(event, events)) continue;
1689
- tip = event;
1690
- }
1691
- return tip;
1692
- }
1693
- function resolveUndoTipMarker(events, nodes) {
1694
- const onSurface = tipRollbackMarker(events, nodes);
1695
- if (onSurface !== void 0) return onSurface;
1696
- let tip;
1697
- for (const event of events) {
1698
- if (!isRollbackMarker(event) || !markerStillActive(event, events)) continue;
1699
- tip = event;
1700
- }
1701
- if (tip !== void 0 && nodes.some((node) => Number(node) === Number(tip.seq))) return tip;
1702
- let surfaceTip;
1703
- for (const node of nodes) {
1704
- const event = events[node];
1705
- if (isRollbackMarker(event)) surfaceTip = event;
1706
- }
1707
- return surfaceTip;
1708
- }
1709
- function undoReplaceEndSeq(events, nodes, markerSeq) {
1710
- const markerIndex = nodes.findIndex((node) => Number(node) === Number(markerSeq));
1711
- if (markerIndex < 0) return markerSeq;
1712
- let end = markerSeq;
1713
- for (let index = markerIndex + 1; index < nodes.length; index += 1) {
1714
- const event = events[nodes[index]];
1715
- if (ignoreOnUndoKeepPrefix(event)) continue;
1716
- end = SessionSeq(nodes[index]);
1717
- }
1718
- return end;
1719
- }
1720
- function undoShadowedSourceSeqs(nodes, markerSeq, replaceEndSeq, sourceSeq) {
1721
- const seqs = [];
1722
- let inRange = false;
1723
- for (const node of nodes) {
1724
- if (Number(node) === Number(markerSeq)) inRange = true;
1725
- if (!inRange) continue;
1726
- seqs.push(SessionSeq(node));
1727
- if (Number(node) === Number(replaceEndSeq)) break;
1728
- }
1729
- if (!seqs.some((seq) => Number(seq) === Number(sourceSeq))) seqs.push(sourceSeq);
1730
- return seqs;
1731
- }
1732
- function ignoreOnUndoKeepPrefix(event) {
1733
- return isProtectedSystemMessage(event) || event?.type === "developer/message";
1734
- }
1735
- function toolCallsOf(event) {
1736
- const calls = [];
1737
- for (const block of event.data.message.content) {
1738
- if (block.type !== "tool-call") continue;
1739
- calls.push({ callId: block.id, name: block.name, arguments: block.arguments });
1740
- }
1741
- return calls;
1742
- }
1743
- function appendUndoToolCalls(session, calls, turn, step, openCalls) {
1744
- for (const call of calls) {
1745
- session.append("tool/call", {
1746
- turn,
1747
- step,
1748
- callId: call.callId,
1749
- name: call.name,
1750
- arguments: call.arguments
1751
- });
1752
- openCalls.set(String(call.callId), call);
1753
- }
1754
- }
1755
- function settleOpenUndoToolCalls(session, journalId, turn, step, openCalls) {
1756
- for (const call of openCalls.values()) {
1757
- session.append("tool/result", {
1758
- turn,
1759
- step,
1760
- message: {
1761
- id: MessageId(`${UNDO_PREFIX}${journalId}:orphan:${call.callId}`),
1762
- role: "tool",
1763
- source: { kind: "tool", callId: call.callId },
1764
- toolCallId: call.callId,
1765
- isError: true,
1766
- content: [{
1767
- type: "text",
1768
- text: "The tool call was restored without a recorded result."
1769
- }]
1770
- },
1771
- error: {
1772
- name: "UndoOrphanToolCall",
1773
- code: "UNDO_ORPHAN_TOOL_CALL",
1774
- reason: "Restored assistant tool call had no matching tool/result in the rollback surface."
1775
- }
1776
- }, { surfaceOp: "append" });
1777
- }
1778
- openCalls.clear();
1779
- }
1780
- function ensureCopiedAssistantToolCalls(session, events, journalId, completed, turn, step, openCalls) {
1781
- const first = events.find((event) => isUndoCopyAt(event, undoCopyId(journalId, 0)));
1782
- if (first === void 0) return;
1783
- const undoStart = Number(first.seq);
1784
- const started = /* @__PURE__ */ new Set();
1785
- const settled = /* @__PURE__ */ new Set();
1786
- for (const event of events) {
1787
- if (Number(event.seq) < undoStart) continue;
1788
- if (event.type === "tool/call") started.add(String(event.data.callId));
1789
- if (event.type === "tool/result") settled.add(String(event.data.message.toolCallId));
1790
- }
1791
- for (let index = 0; index < completed; index += 1) {
1792
- const event = events.find((candidate) => isUndoCopyAt(candidate, undoCopyId(journalId, index)));
1793
- if (event?.type !== "assistant/message") continue;
1794
- const calls = toolCallsOf(event);
1795
- appendUndoToolCalls(
1796
- session,
1797
- calls.filter((call) => !started.has(String(call.callId))),
1798
- turn,
1799
- step,
1800
- openCalls
1801
- );
1802
- for (const call of calls) {
1803
- if (!settled.has(String(call.callId))) openCalls.set(String(call.callId), call);
1804
- }
1805
- }
1806
- }
1807
- function countPartialUndoCopies(events, first, journalId, tip) {
1808
- let completed = 0;
1809
- let cursor = Number(first.seq);
1810
- while (cursor <= tip) {
1811
- const event = events[SessionSeq(cursor)];
1812
- if (event === void 0) throw new CheckpointRollbackError("ROLLBACK_RECOVERY_FAILED");
1813
- if (isUndoCopyAt(event, undoCopyId(journalId, completed))) {
1814
- completed += 1;
1815
- cursor += 1;
1816
- continue;
1817
- }
1818
- if (event.type === "tool/call" && completed > 0) {
1819
- cursor += 1;
1820
- continue;
1821
- }
1822
- throw new CheckpointRollbackError("ROLLBACK_RECOVERY_FAILED");
1823
- }
1824
- return completed;
1825
- }
1826
- function appendUndoCopy(session, source, journalId, index, tipMarkerSeq, mode, replaceStartSeq, replaceEndSeq, turn, step, openCalls) {
1827
- const copyId = MessageId(`${undoCopyId(journalId, index)}:${source.seq}`);
1828
- const id = isRollbackMarker(source) ? MessageId(`${copyId}:${source.data.id}`) : copyId;
1829
- if (source.type === "user/message") {
1830
- if (mode === "append" || index > 0) {
1831
- return session.append("user/message", { ...source.data, id }, {
1832
- surfaceOp: "append",
1833
- sourceEventSeqs: [source.seq]
1834
- });
1835
- }
1836
- const shadowed = undoShadowedSourceSeqs(
1837
- session.surface.nodes,
1838
- replaceStartSeq,
1839
- replaceEndSeq,
1840
- source.seq
1841
- );
1842
- if (!shadowed.some((seq) => Number(seq) === Number(tipMarkerSeq))) {
1843
- shadowed.unshift(tipMarkerSeq);
1844
- }
1845
- return session.append("user/message", { ...source.data, id }, {
1846
- surfaceOp: { op: "replace", startSeq: replaceStartSeq, endSeq: replaceEndSeq },
1847
- sourceEventSeqs: shadowed
1848
- });
1849
- }
1850
- if (index === 0 && mode === "replace") {
1851
- throw new Error("The first restored surface event must be a user message");
1852
- }
1853
- switch (source.type) {
1854
- case "assistant/message": {
1855
- const event = session.append("assistant/message", {
1856
- ...source.data,
1857
- turn,
1858
- step,
1859
- message: { ...source.data.message, id }
1860
- }, { surfaceOp: "append" });
1861
- appendUndoToolCalls(session, toolCallsOf(source), turn, step, openCalls);
1862
- return event;
1863
- }
1864
- case "system/message":
1865
- return session.append("system/message", {
1866
- ...source.data,
1867
- turn,
1868
- step,
1869
- message: { ...source.data.message, id }
1870
- }, { surfaceOp: "append", sourceEventSeqs: [source.seq] });
1871
- case "developer/message":
1872
- return session.append("developer/message", {
1873
- ...source.data,
1874
- turn,
1875
- step,
1876
- message: { ...source.data.message, id }
1877
- }, { surfaceOp: "append", sourceEventSeqs: [source.seq] });
1878
- case "tool/result": {
1879
- openCalls.delete(String(source.data.message.toolCallId));
1880
- return session.append("tool/result", {
1881
- ...source.data,
1882
- turn,
1883
- step,
1884
- message: { ...source.data.message, id }
1885
- }, { surfaceOp: "append", sourceEventSeqs: [source.seq] });
1886
- }
1887
- }
1888
- }
1889
1842
  var CheckpointRollbackService = class {
1890
1843
  constructor(options) {
1891
1844
  this.options = options;
@@ -1904,6 +1857,9 @@ var CheckpointRollbackService = class {
1904
1857
  summaries(request, signal) {
1905
1858
  return this.track(this.runSummaries(request, signal));
1906
1859
  }
1860
+ getCut(request, signal) {
1861
+ return this.track(this.runGetCut(request, signal));
1862
+ }
1907
1863
  recover() {
1908
1864
  if (this.recovery !== void 0) return this.recovery;
1909
1865
  const operation = this.track(this.runRecovery());
@@ -1951,7 +1907,11 @@ var CheckpointRollbackService = class {
1951
1907
  try {
1952
1908
  linked.signal.throwIfAborted();
1953
1909
  if ((await this.options.store.listPendingJournals()).length > 0) {
1954
- throw new CheckpointRollbackError("ROLLBACK_RECOVERY_FAILED");
1910
+ try {
1911
+ await this.recover();
1912
+ } catch {
1913
+ throw new CheckpointRollbackError("ROLLBACK_RECOVERY_FAILED");
1914
+ }
1955
1915
  }
1956
1916
  linked.signal.throwIfAborted();
1957
1917
  return (await this.evaluate(request)).preview;
@@ -1975,30 +1935,90 @@ var CheckpointRollbackService = class {
1975
1935
  await this.options.awaitCaptures?.();
1976
1936
  linked.signal.throwIfAborted();
1977
1937
  const checkpoints = await this.options.store.list(request.sessionId);
1938
+ const liveCut = await this.readCut(request.sessionId);
1978
1939
  const adapter = this.options.resolveSession(request.sessionId);
1979
1940
  const events = adapter?.readEvents() ?? [];
1980
1941
  const surfaceNodes = adapter?.session.surface.nodes;
1981
- const window = events.length === 0 ? void 0 : activeRollbackWindow(events, surfaceNodes);
1942
+ const tipWindow = events.length === 0 ? void 0 : activeRollbackWindow(events, surfaceNodes);
1943
+ const window = windowFromCut(liveCut) ?? tipWindow;
1982
1944
  const shells = undoShellRanges(events);
1983
- const kept = events.length === 0 ? checkpoints : checkpoints.filter((checkpoint) => !isUndoShellCheckpoint(checkpoint.atSeq, shells));
1945
+ const kept = events.length === 0 ? checkpoints : checkpoints.filter((checkpoint) => checkpoint.files.length > 0 || !isUndoShellCheckpoint(checkpoint.atSeq, shells));
1984
1946
  if (kept.length !== checkpoints.length) {
1985
1947
  await this.options.store.replace(request.sessionId, kept);
1986
1948
  }
1987
1949
  void this.options.store.purgeSettledJournals().catch(() => void 0);
1988
- const byTurn = /* @__PURE__ */ new Map();
1950
+ const tipAtSeq = liveCut?.cutSeq;
1951
+ const byAtSeq = /* @__PURE__ */ new Map();
1989
1952
  for (const checkpoint of kept) {
1990
1953
  const recoveredPrompt = checkpoint.prompt.trim() === "" ? recoverTurnPrompt(events, checkpoint.turn) : "";
1991
1954
  const rolledBack = isRolledBackCheckpoint(checkpoint.turn, checkpoint.atSeq, window);
1992
- byTurn.set(
1993
- checkpoint.turn,
1994
- toCheckpointTurnSummary(checkpoint, {
1995
- rolledBack,
1996
- tip: window !== void 0 && checkpoint.turn === window.tipTurn,
1997
- recoveredPrompt
1998
- })
1999
- );
1955
+ const tip = tipAtSeq !== void 0 ? checkpoint.atSeq === tipAtSeq : window !== void 0 && checkpoint.turn === window.tipTurn;
1956
+ const summary = toCheckpointTurnSummary(checkpoint, {
1957
+ rolledBack,
1958
+ tip,
1959
+ recoveredPrompt
1960
+ });
1961
+ const previous = byAtSeq.get(checkpoint.atSeq);
1962
+ if (previous !== void 0 && previous.fileCount > 0 && summary.fileCount === 0) continue;
1963
+ byAtSeq.set(checkpoint.atSeq, summary);
1964
+ }
1965
+ const live = adapter;
1966
+ if (live != null && events.length > 0) {
1967
+ const closedStarts = [];
1968
+ for (let index = 0; index < events.length; index += 1) {
1969
+ const event = events[index];
1970
+ if (event.type !== "turn/start") continue;
1971
+ const turn = event.data.turn;
1972
+ const ended = events.slice(index + 1).some((item) => item.type === "turn/end" && item.data.turn === turn && Number(item.seq) > Number(event.seq));
1973
+ if (ended) closedStarts.push(event);
1974
+ }
1975
+ const backfilled = [];
1976
+ for (const event of closedStarts) {
1977
+ const atSeq = checkpointAtSeq(Number(event.seq));
1978
+ if (byAtSeq.has(atSeq)) continue;
1979
+ const soft = synthesizeCheckpoint({
1980
+ sessionId: request.sessionId,
1981
+ session: {
1982
+ format: live.session.header.version,
1983
+ preset: live.session.header.agentPreset ?? null
1984
+ },
1985
+ pluginVersion: this.options.pluginVersion,
1986
+ turn: event.data.turn,
1987
+ events,
1988
+ createId: this.options.createId,
1989
+ now: this.options.now
1990
+ });
1991
+ if (soft !== null) {
1992
+ if (isUndoShellCheckpoint(soft.atSeq, shells) && soft.atSeq === atSeq) continue;
1993
+ const pinned = soft.atSeq === atSeq ? soft : { ...soft, atSeq };
1994
+ if (isUndoShellCheckpoint(pinned.atSeq, shells)) continue;
1995
+ backfilled.push(pinned);
1996
+ byAtSeq.set(
1997
+ atSeq,
1998
+ toCheckpointTurnSummary(pinned, {
1999
+ rolledBack: isRolledBackCheckpoint(pinned.turn, pinned.atSeq, window),
2000
+ tip: tipAtSeq !== void 0 ? pinned.atSeq === tipAtSeq : window !== void 0 && pinned.turn === window.tipTurn
2001
+ })
2002
+ );
2003
+ continue;
2004
+ }
2005
+ const row = summaryFromClosedTurn(events, event.data.turn, {
2006
+ rolledBack: isRolledBackCheckpoint(event.data.turn, atSeq, window),
2007
+ tip: tipAtSeq !== void 0 ? atSeq === tipAtSeq : window !== void 0 && event.data.turn === window.tipTurn,
2008
+ now: this.options.now?.()
2009
+ });
2010
+ if (row !== null && !isUndoShellCheckpoint(atSeq, shells)) {
2011
+ byAtSeq.set(atSeq, { ...row, atSeq });
2012
+ }
2013
+ }
2014
+ for (const soft of backfilled) {
2015
+ try {
2016
+ await this.options.store.save(soft);
2017
+ } catch {
2018
+ }
2019
+ }
2000
2020
  }
2001
- const turns = [...byTurn.values()].sort((left, right) => left.atSeq - right.atSeq || left.turn - right.turn || left.createdAt - right.createdAt);
2021
+ const turns = [...byAtSeq.values()].sort((left, right) => left.atSeq - right.atSeq || left.turn - right.turn || left.createdAt - right.createdAt);
2002
2022
  const liveCheckpoints = turns.filter((turn) => !turn.rolledBack).length;
2003
2023
  const activity = liveActivityStats(events, {
2004
2024
  hideTurnsFrom: window?.hideTurnsFrom,
@@ -2017,6 +2037,36 @@ var CheckpointRollbackService = class {
2017
2037
  linked.cleanup();
2018
2038
  }
2019
2039
  }
2040
+ async runGetCut(request, callerSignal) {
2041
+ const linked = this.linkedSignal([callerSignal]);
2042
+ try {
2043
+ linked.signal.throwIfAborted();
2044
+ const cut = await this.readCut(request.sessionId);
2045
+ return {
2046
+ sessionId: request.sessionId,
2047
+ cut: cut === null ? null : cutViewOf(cut)
2048
+ };
2049
+ } catch (error) {
2050
+ throw this.sanitize(error, linked.signal);
2051
+ } finally {
2052
+ linked.cleanup();
2053
+ }
2054
+ }
2055
+ async readCut(sessionId) {
2056
+ const cached = this.options.cutCache?.get(sessionId);
2057
+ if (cached !== void 0) return cached;
2058
+ if (this.options.cutStore === void 0) return null;
2059
+ const cut = await this.options.cutStore.get(sessionId);
2060
+ if (this.options.cutCache !== void 0) syncCutCache(this.options.cutCache, sessionId, cut);
2061
+ return cut;
2062
+ }
2063
+ async writeCut(sessionId, cut) {
2064
+ if (this.options.cutStore === void 0) {
2065
+ throw new CheckpointRollbackError("ROLLBACK_FAILED");
2066
+ }
2067
+ await this.options.cutStore.set(sessionId, cut);
2068
+ if (this.options.cutCache !== void 0) syncCutCache(this.options.cutCache, sessionId, cut);
2069
+ }
2020
2070
  async runExecute(request, callerSignal) {
2021
2071
  const linked = this.linkedSignal([callerSignal]);
2022
2072
  try {
@@ -2035,46 +2085,71 @@ var CheckpointRollbackService = class {
2035
2085
  const current = await this.evaluate(request, { withinMaintenance: true });
2036
2086
  const scope = this.effectiveScope(request, current);
2037
2087
  this.assertExecutable(current, scope);
2038
- if (current.adapter?.session !== adapter.session || current.surface === null) {
2088
+ if (current.adapter?.session.id !== adapter.session.id || current.surface === null) {
2039
2089
  throw new CheckpointRollbackError("ROLLBACK_UNAVAILABLE", ["session-changed"]);
2040
2090
  }
2041
2091
  const checkpoint = current.checkpoint;
2042
2092
  const operation = operationOf(request);
2043
2093
  const session = adapter.session;
2044
- const expectedSeq = session.seq;
2045
- const expectedNodes = [...session.surface.nodes];
2046
- const journalId = (this.options.createId ?? randomUUID3)();
2094
+ const expectedSeq = Number(session.seq);
2095
+ const journalId = (this.options.createId ?? randomUUID4)();
2047
2096
  const files = this.files(adapter, checkpoint, journalId);
2048
- const filesToRestore = scope === "conversation" ? [] : checkpoint.files;
2049
2097
  const surface = current.surface;
2098
+ const filesToRestore = scope === "conversation" ? [] : this.trackedFilesForRestore(
2099
+ await this.options.store.list(request.sessionId),
2100
+ adapter,
2101
+ surface,
2102
+ await this.readCut(request.sessionId)
2103
+ );
2104
+ const draftPrompt = checkpoint.prompt.trim() !== "" ? checkpoint.prompt : recoverTurnPrompt(adapter.readEvents(), request.turn);
2050
2105
  if (operation === "rollback" && surface.operation === "rollback" && surface.alreadyRestored && filesToRestore.length === 0) {
2051
- const draftPrompt2 = checkpoint.prompt.trim() !== "" ? checkpoint.prompt : recoverTurnPrompt(adapter.readEvents(), request.turn);
2052
2106
  return {
2053
2107
  sessionId: request.sessionId,
2054
2108
  turn: request.turn,
2055
- draft: draftPrompt2
2109
+ draft: draftPrompt
2056
2110
  };
2057
2111
  }
2058
- await files.runTransaction(filesToRestore, async () => {
2059
- if (maintenance.signal.aborted) return { appended: false, synchronized: false };
2060
- const latest = this.options.resolveSession(request.sessionId);
2061
- 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])) {
2062
- return { appended: false, synchronized: false };
2112
+ if (maintenance.signal.aborted) {
2113
+ throw this.sanitize(abortError(), maintenance.signal);
2114
+ }
2115
+ if (adapter.session.id !== session.id || Number(adapter.session.seq) !== expectedSeq || !this.canCommit(adapter, scope)) {
2116
+ throw new CheckpointRollbackError("ROLLBACK_FAILED");
2117
+ }
2118
+ try {
2119
+ if (surface.operation === "rollback") {
2120
+ const previous = await this.readCut(request.sessionId);
2121
+ const next = {
2122
+ hideTurnsFrom: surface.turn,
2123
+ cutSeq: surface.cutSeq,
2124
+ restoredAtSeq: expectedSeq,
2125
+ draftPrompt,
2126
+ scope,
2127
+ ...filesToRestore.length > 0 ? { journalId } : {},
2128
+ previous
2129
+ };
2130
+ await this.writeCut(request.sessionId, next);
2131
+ } else {
2132
+ await this.writeCut(request.sessionId, surface.restoreCut);
2063
2133
  }
2064
- const restored = await this.appendAndSynchronize(
2065
- adapter,
2066
- surface,
2067
- journalId,
2068
- scope,
2069
- maintenance.signal
2070
- );
2071
- const appended = restored.appended && this.appendOccurred(adapter, journalId);
2072
- return { appended, synchronized: appended && restored.synchronized };
2073
- }, directionOf(operation));
2074
- const draftPrompt = checkpoint.prompt.trim() !== "" ? checkpoint.prompt : recoverTurnPrompt(adapter.readEvents(), request.turn);
2134
+ } catch (error) {
2135
+ if (error instanceof CheckpointRollbackError) throw error;
2136
+ throw new CheckpointRollbackError("ROLLBACK_FAILED");
2137
+ }
2138
+ const latest = this.options.resolveSession(request.sessionId);
2139
+ const syncTarget = latest !== void 0 && latest.session.id === session.id ? latest : adapter;
2140
+ try {
2141
+ await syncTarget.synchronize(maintenance.signal);
2142
+ } catch {
2143
+ }
2144
+ if (filesToRestore.length > 0) {
2145
+ await files.runTransaction(filesToRestore, async () => {
2146
+ if (maintenance.signal.aborted) return { appended: false, synchronized: false };
2147
+ return { appended: true, synchronized: true };
2148
+ }, directionOf(operation));
2149
+ }
2075
2150
  return {
2076
2151
  sessionId: request.sessionId,
2077
- turn: request.turn,
2152
+ turn: surface.operation === "undo" ? surface.tipTurn : request.turn,
2078
2153
  draft: operation === "rollback" ? draftPrompt : ""
2079
2154
  };
2080
2155
  } catch (error) {
@@ -2096,127 +2171,6 @@ var CheckpointRollbackService = class {
2096
2171
  linked.cleanup();
2097
2172
  }
2098
2173
  }
2099
- async appendAndSynchronize(adapter, surface, journalId, scope, signal) {
2100
- try {
2101
- if (surface.operation === "rollback") this.appendRollback(adapter, surface, journalId, scope);
2102
- else {
2103
- this.appendUndo(
2104
- adapter.session,
2105
- surface.marker,
2106
- surface.sources,
2107
- journalId,
2108
- surface.mode,
2109
- surface.replaceStartSeq,
2110
- surface.replaceEndSeq
2111
- );
2112
- if (surface.nextTip !== void 0 && surface.nextTip.sources.length > 0) {
2113
- this.appendRollbackNotice(adapter, surface.nextTip.turn, journalId, scopeOfMarker(surface.marker), {
2114
- surfaceOp: "append",
2115
- sourceEventSeqs: surface.nextTip.sources.map((event) => SessionSeq(event.seq))
2116
- });
2117
- }
2118
- }
2119
- } catch {
2120
- return { appended: this.appendOccurred(adapter, journalId), synchronized: false };
2121
- }
2122
- try {
2123
- await adapter.synchronize(signal);
2124
- return { appended: true, synchronized: true };
2125
- } catch {
2126
- return { appended: true, synchronized: false };
2127
- }
2128
- }
2129
- appendRollback(adapter, surface, journalId, scope) {
2130
- const forward = surface.forwardFromTip;
2131
- if (forward !== void 0) {
2132
- if (forward.stillWithdraw.length === 0) {
2133
- this.appendUndo(
2134
- adapter.session,
2135
- forward.marker,
2136
- forward.reappear,
2137
- journalId,
2138
- "replace",
2139
- SessionSeq(forward.marker.seq),
2140
- SessionSeq(forward.marker.seq)
2141
- );
2142
- return;
2143
- }
2144
- if (forward.reappear.length === 0) {
2145
- this.appendRollbackNotice(adapter, surface.turn, journalId, scope, {
2146
- surfaceOp: {
2147
- op: "replace",
2148
- startSeq: SessionSeq(forward.marker.seq),
2149
- endSeq: SessionSeq(forward.marker.seq)
2150
- },
2151
- sourceEventSeqs: forward.stillWithdraw.map((event) => SessionSeq(event.seq))
2152
- });
2153
- return;
2154
- }
2155
- this.appendUndo(
2156
- adapter.session,
2157
- forward.marker,
2158
- forward.reappear,
2159
- journalId,
2160
- "replace",
2161
- SessionSeq(forward.marker.seq),
2162
- SessionSeq(forward.marker.seq)
2163
- );
2164
- this.appendRollbackNotice(adapter, surface.turn, journalId, scope, {
2165
- surfaceOp: "append",
2166
- sourceEventSeqs: forward.stillWithdraw.map((event) => SessionSeq(event.seq))
2167
- });
2168
- return;
2169
- }
2170
- this.appendRollbackNotice(adapter, surface.turn, journalId, scope, {
2171
- surfaceOp: {
2172
- op: "replace",
2173
- startSeq: surface.nodes[0],
2174
- endSeq: surface.nodes[surface.nodes.length - 1]
2175
- },
2176
- sourceEventSeqs: [...surface.nodes]
2177
- });
2178
- }
2179
- appendRollbackNotice(adapter, checkpointTurn, journalId, scope, append) {
2180
- const conversationOnly = scope === "conversation";
2181
- const summary = conversationOnly ? `Conversation rolled back before turn ${checkpointTurn}` : `Conversation and tracked files rolled back before turn ${checkpointTurn}`;
2182
- const detail = conversationOnly ? `The user rolled back the conversation to before turn ${checkpointTurn}. Later events remain in the append-only log but are no longer active model context. Tracked files were not restored.` : `The user rolled back the conversation and tracked files to before turn ${checkpointTurn}. Later events remain in the append-only log but are no longer active model context. Re-read tracked files before relying on their contents.`;
2183
- adapter.session.append("user/message", {
2184
- id: rollbackMarkerId(checkpointTurn, journalId, scope),
2185
- role: "user",
2186
- content: [{ type: "text", text: detail }],
2187
- source: { kind: "checkpoint-rollback", form: "notice", summary }
2188
- }, {
2189
- surfaceOp: append.surfaceOp,
2190
- sourceEventSeqs: [...append.sourceEventSeqs]
2191
- });
2192
- }
2193
- appendUndo(session, marker, sources, journalId, mode, replaceStartSeq, replaceEndSeq, start = 0, openCalls = /* @__PURE__ */ new Map()) {
2194
- const events = session.snapshotEvents();
2195
- const turn = start === 0 ? nextTurnNumber(events) : undoTurnAfterMarker(events, marker.seq);
2196
- const step = 1;
2197
- if (start === 0) {
2198
- session.append("turn/start", { turn });
2199
- session.append("step/start", { turn, step });
2200
- }
2201
- for (let index = start; index < sources.length; index += 1) {
2202
- appendUndoCopy(
2203
- session,
2204
- sources[index],
2205
- journalId,
2206
- index,
2207
- marker.seq,
2208
- mode,
2209
- replaceStartSeq,
2210
- replaceEndSeq,
2211
- turn,
2212
- step,
2213
- openCalls
2214
- );
2215
- }
2216
- settleOpenUndoToolCalls(session, journalId, turn, step, openCalls);
2217
- session.append("step/end", { turn, step });
2218
- session.append("turn/end", { turn, reason: { kind: "completed" } });
2219
- }
2220
2174
  async runRecovery() {
2221
2175
  try {
2222
2176
  this.lifetime.signal.throwIfAborted();
@@ -2242,10 +2196,8 @@ var CheckpointRollbackService = class {
2242
2196
  now: this.options.now
2243
2197
  });
2244
2198
  await files.recoverFiles(async (journal) => {
2245
- if (!this.appendOccurred(adapter, journal.id)) return false;
2246
- await this.resumeUndo(adapter, journal.id);
2247
- await adapter.synchronize(linked.signal);
2248
- return true;
2199
+ const cut = await this.readCut(sessionId);
2200
+ return cut?.journalId === journal.id;
2249
2201
  });
2250
2202
  } finally {
2251
2203
  linked.cleanup();
@@ -2257,59 +2209,6 @@ var CheckpointRollbackService = class {
2257
2209
  throw new CheckpointRollbackError("ROLLBACK_RECOVERY_FAILED");
2258
2210
  }
2259
2211
  }
2260
- async resumeUndo(adapter, journalId) {
2261
- const events = adapter.readEvents();
2262
- const first = events.find((event) => isUndoCopyAt(event, undoCopyId(journalId, 0)));
2263
- if (first === void 0) return;
2264
- if (first.type !== "user/message") {
2265
- throw new CheckpointRollbackError("ROLLBACK_RECOVERY_FAILED");
2266
- }
2267
- const appendOnly = first.surfaceOp === "append";
2268
- const hinted = first.sourceEventSeqs?.map((seq) => events[seq]).find((event) => isRollbackMarker(event));
2269
- const marker = !appendOnly && first.surfaceOp !== void 0 && first.surfaceOp !== "append" && isRollbackMarker(events[first.surfaceOp.startSeq]) ? events[first.surfaceOp.startSeq] : hinted;
2270
- if (!isRollbackMarker(marker)) throw new CheckpointRollbackError("ROLLBACK_RECOVERY_FAILED");
2271
- const sources = sourceEvents(events, marker);
2272
- if (sources === null) throw new CheckpointRollbackError("ROLLBACK_RECOVERY_FAILED");
2273
- const tipTurn = turnFromRollbackId(marker.data.id);
2274
- if (tipTurn === void 0) throw new CheckpointRollbackError("ROLLBACK_RECOVERY_FAILED");
2275
- const peeled = peelUndoSources(events, sources, tipTurn);
2276
- const tip = Number(adapter.session.seq) - 1;
2277
- const completed = countPartialUndoCopies(events, first, journalId, tip);
2278
- const openCalls = /* @__PURE__ */ new Map();
2279
- const turn = undoTurnAfterMarker(events, marker.seq);
2280
- const step = 1;
2281
- ensureCopiedAssistantToolCalls(
2282
- adapter.session,
2283
- events,
2284
- journalId,
2285
- completed,
2286
- turn,
2287
- step,
2288
- openCalls
2289
- );
2290
- const replaceStart = appendOnly || first.surfaceOp === "append" || first.surfaceOp === void 0 ? marker.seq : SessionSeq(first.surfaceOp.startSeq);
2291
- const replaceEnd = appendOnly || first.surfaceOp === "append" || first.surfaceOp === void 0 ? marker.seq : SessionSeq(first.surfaceOp.endSeq);
2292
- this.appendUndo(
2293
- adapter.session,
2294
- marker,
2295
- peeled.undoSources,
2296
- journalId,
2297
- appendOnly ? "append" : "replace",
2298
- replaceStart,
2299
- replaceEnd,
2300
- completed,
2301
- openCalls
2302
- );
2303
- if (peeled.nextTip !== void 0 && peeled.nextTip.sources.length > 0) {
2304
- const live = activeRollbackWindow(adapter.readEvents(), adapter.session.surface.nodes);
2305
- if (live?.tipTurn !== peeled.nextTip.turn) {
2306
- this.appendRollbackNotice(adapter, peeled.nextTip.turn, journalId, scopeOfMarker(marker), {
2307
- surfaceOp: "append",
2308
- sourceEventSeqs: peeled.nextTip.sources.map((event) => SessionSeq(event.seq))
2309
- });
2310
- }
2311
- }
2312
- }
2313
2212
  async evaluate(request, options = {}) {
2314
2213
  const operation = operationOf(request);
2315
2214
  await this.options.awaitCaptures?.();
@@ -2317,7 +2216,8 @@ var CheckpointRollbackService = class {
2317
2216
  const events = adapter?.readEvents() ?? [];
2318
2217
  const shells = undoShellRanges(events);
2319
2218
  const checkpoints = await this.options.store.list(request.sessionId);
2320
- let stored = checkpoints.find((checkpoint) => checkpoint.turn === request.turn && !isUndoShellCheckpoint(checkpoint.atSeq, shells)) ?? null;
2219
+ const candidates = checkpoints.filter((checkpoint) => checkpoint.turn === request.turn && (checkpoint.files.length > 0 || !isUndoShellCheckpoint(checkpoint.atSeq, shells)));
2220
+ 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;
2321
2221
  if (stored === null && adapter !== null && operation === "rollback") {
2322
2222
  stored = synthesizeCheckpoint({
2323
2223
  sessionId: request.sessionId,
@@ -2354,6 +2254,7 @@ var CheckpointRollbackService = class {
2354
2254
  }
2355
2255
  let messages = [];
2356
2256
  let surface = null;
2257
+ const liveCut = await this.readCut(request.sessionId);
2357
2258
  if (stored !== null && adapter !== null && stored.atSeq >= 0) {
2358
2259
  const events2 = adapter.readEvents();
2359
2260
  const cut = resolveRollbackCut(events2, stored.turn, stored.atSeq);
@@ -2363,165 +2264,102 @@ var CheckpointRollbackService = class {
2363
2264
  if (events2.some((event) => Number(event.seq) > cut.cutSeq && typeof event.surfaceOp === "object" && !isOwnReplacement(event))) {
2364
2265
  unavailable.push("compacted-surface");
2365
2266
  }
2366
- const surfaceNodes = adapter.session.surface.nodes;
2367
- const tipWindow2 = activeRollbackWindow(events2, surfaceNodes);
2368
- if (tipWindow2 !== void 0 && stored.turn > tipWindow2.tipTurn) {
2369
- const marker = resolveUndoTipMarker(events2, surfaceNodes);
2370
- const sources = marker === void 0 ? null : sourceEvents(events2, marker);
2371
- if (marker === void 0 || sources === null) {
2372
- unavailable.push("unknown-surface");
2373
- } else {
2374
- const reappear = sources.filter((event) => Number(event.seq) <= cut.cutSeq);
2375
- const stillWithdraw = sources.filter((event) => Number(event.seq) > cut.cutSeq);
2376
- messages = reappear.map((event) => ({
2377
- seq: event.seq,
2378
- type: event.type,
2379
- text: textOf(event)
2380
- }));
2381
- surface = {
2382
- operation,
2383
- turn: stored.turn,
2384
- nodes: [SessionSeq(marker.seq)],
2385
- alreadyRestored: false,
2386
- forwardFromTip: { marker, reappear, stillWithdraw }
2387
- };
2388
- }
2267
+ const withdrawn = events2.filter((event) => Number(event.seq) > cut.cutSeq && surfaceEventTypes.has(event.type) && !isProtectedSystemMessage(event));
2268
+ const alreadyRestored = liveCut !== null && liveCut.hideTurnsFrom === stored.turn && liveCut.cutSeq === cut.cutSeq && liveCut.restoredAtSeq === Number(adapter.session.seq);
2269
+ if (withdrawn.length === 0 || alreadyRestored) {
2270
+ unavailable.push("already-restored");
2271
+ surface = {
2272
+ operation,
2273
+ turn: stored.turn,
2274
+ cutSeq: cut.cutSeq,
2275
+ alreadyRestored: true
2276
+ };
2277
+ messages = [];
2389
2278
  } else {
2390
- const fromSurface = adapter.session.surface.nodes.filter((node) => events2[node] !== void 0 && Number(logicalSeq(events2[node])) > cut.cutSeq);
2391
- const fromLog = events2.filter((event) => Number(event.seq) > cut.cutSeq && surfaceEventTypes.has(event.type)).map((event) => SessionSeq(event.seq));
2392
- const candidates = fromSurface.length > 0 && fromSurface.every((node) => surfaceEventTypes.has(events2[node].type)) ? fromSurface.map((node) => SessionSeq(node)) : fromLog;
2393
- const nodes = rollbackSurfaceNodes(events2, candidates);
2394
- if (nodes.length === 0) {
2395
- unavailable.push("already-restored");
2396
- surface = { operation, turn: stored.turn, nodes, alreadyRestored: true };
2397
- messages = [];
2398
- } else {
2399
- const alreadyRestored = isAlreadyRestoredRollback(events2, nodes, stored.turn, surfaceNodes);
2400
- if (alreadyRestored) unavailable.push("already-restored");
2401
- surface = { operation, turn: stored.turn, nodes, alreadyRestored };
2402
- messages = alreadyRestored ? [] : nodes.map((node) => ({
2403
- seq: node,
2404
- type: events2[node].type,
2405
- text: textOf(events2[node])
2406
- }));
2407
- }
2279
+ surface = {
2280
+ operation,
2281
+ turn: stored.turn,
2282
+ cutSeq: cut.cutSeq,
2283
+ alreadyRestored: false
2284
+ };
2285
+ messages = withdrawn.map((event) => ({
2286
+ seq: Number(event.seq),
2287
+ type: event.type,
2288
+ text: textOf(event)
2289
+ }));
2408
2290
  }
2291
+ } else if (liveCut === null) {
2292
+ unavailable.push("session-changed");
2409
2293
  } else {
2410
- const currentNodes = adapter.session.surface.nodes;
2411
- const tipWindow2 = activeRollbackWindow(events2, currentNodes);
2412
- let marker = resolveUndoTipMarker(events2, currentNodes);
2413
- if (marker === void 0 && tipWindow2 !== void 0) {
2414
- for (let index = events2.length - 1; index >= 0; index -= 1) {
2415
- const event = events2[index];
2416
- if (!isRollbackMarker(event) || !markerStillActive(event, events2)) continue;
2417
- const turn = turnFromRollbackId(event.data.id);
2418
- if (turn === tipWindow2.tipTurn) {
2419
- marker = event;
2420
- break;
2421
- }
2422
- }
2294
+ const tipTurn = liveCut.hideTurnsFrom;
2295
+ let undoStored = tipTurn === stored.turn ? stored : checkpoints.find((item) => item.turn === tipTurn && !isUndoShellCheckpoint(item.atSeq, shells)) ?? null;
2296
+ if (undoStored === null) {
2297
+ undoStored = synthesizeCheckpoint({
2298
+ sessionId: request.sessionId,
2299
+ session: {
2300
+ format: adapter.session.header.version,
2301
+ preset: adapter.session.header.agentPreset ?? null
2302
+ },
2303
+ pluginVersion: this.options.pluginVersion,
2304
+ turn: tipTurn,
2305
+ events: events2,
2306
+ createId: this.options.createId,
2307
+ now: this.options.now
2308
+ });
2423
2309
  }
2424
- const tipTurn = marker === void 0 ? void 0 : turnFromRollbackId(marker.data.id);
2425
- if (marker === void 0 || tipTurn === void 0) {
2426
- unavailable.push("session-changed");
2310
+ if (undoStored === null) {
2311
+ unavailable.push("checkpoint-not-found");
2427
2312
  } else {
2428
- let undoStored = tipTurn === stored.turn ? stored : checkpoints.find((item) => item.turn === tipTurn && !isUndoShellCheckpoint(item.atSeq, shells)) ?? null;
2429
- if (undoStored === null) {
2430
- undoStored = synthesizeCheckpoint({
2431
- sessionId: request.sessionId,
2432
- session: {
2433
- format: adapter.session.header.version,
2434
- preset: adapter.session.header.agentPreset ?? null
2435
- },
2436
- pluginVersion: this.options.pluginVersion,
2437
- turn: tipTurn,
2438
- events: events2,
2439
- createId: this.options.createId,
2440
- now: this.options.now
2441
- });
2442
- }
2443
- if (undoStored === null) {
2444
- unavailable.push("checkpoint-not-found");
2445
- } else {
2446
- if (tipTurn !== stored.turn) {
2447
- const drop = /* @__PURE__ */ new Set([
2448
- "checkpoint-not-found",
2449
- "incomplete-checkpoint",
2450
- "prompt-non-text-content",
2451
- "workspace-capture-failed",
2452
- "incompatible-session"
2453
- ]);
2454
- for (let index = unavailable.length - 1; index >= 0; index -= 1) {
2455
- if (drop.has(unavailable[index])) unavailable.splice(index, 1);
2456
- }
2457
- if (undoStored.coverage !== "complete" || undoStored.gaps.length > 0) {
2458
- unavailable.push("incomplete-checkpoint");
2459
- for (const gap of undoStored.gaps) {
2460
- unavailable.push(gap.type === "prompt" ? "prompt-non-text-content" : "workspace-capture-failed");
2461
- }
2462
- }
2463
- if (undoStored.session.format !== adapter.session.header.version) {
2464
- unavailable.push("incompatible-session");
2465
- }
2313
+ if (tipTurn !== stored.turn) {
2314
+ const drop = /* @__PURE__ */ new Set([
2315
+ "checkpoint-not-found",
2316
+ "incomplete-checkpoint",
2317
+ "prompt-non-text-content",
2318
+ "workspace-capture-failed",
2319
+ "incompatible-session"
2320
+ ]);
2321
+ for (let index = unavailable.length - 1; index >= 0; index -= 1) {
2322
+ if (drop.has(unavailable[index])) unavailable.splice(index, 1);
2466
2323
  }
2467
- stored = undoStored;
2468
- const sources = sourceEvents(events2, marker);
2469
- if (sources === null || sources.length === 0) {
2470
- unavailable.push("unknown-surface");
2471
- } else {
2472
- const markerOnSurface = currentNodes.some((node) => Number(node) === Number(marker.seq));
2473
- let mode = "replace";
2474
- let replaceStartSeq = marker.seq;
2475
- let replaceEndSeq = undoReplaceEndSeq(events2, currentNodes, marker.seq);
2476
- if (!markerOnSurface) {
2477
- const tipCut = resolveRollbackCut(events2, tipTurn, undoStored.atSeq);
2478
- const afterCut = tipCut === null ? [] : currentNodes.filter((node) => {
2479
- const event = events2[node];
2480
- if (ignoreOnUndoKeepPrefix(event)) return false;
2481
- return Number(logicalSeq(event)) > tipCut.cutSeq;
2482
- });
2483
- if (afterCut.length === 0) {
2484
- mode = "append";
2485
- const last = currentNodes[currentNodes.length - 1];
2486
- replaceStartSeq = last === void 0 ? marker.seq : SessionSeq(last);
2487
- replaceEndSeq = replaceStartSeq;
2488
- } else {
2489
- replaceStartSeq = SessionSeq(afterCut[0]);
2490
- replaceEndSeq = SessionSeq(afterCut[afterCut.length - 1]);
2491
- }
2324
+ if (undoStored.coverage !== "complete" || undoStored.gaps.length > 0) {
2325
+ unavailable.push("incomplete-checkpoint");
2326
+ for (const gap of undoStored.gaps) {
2327
+ unavailable.push(gap.type === "prompt" ? "prompt-non-text-content" : "workspace-capture-failed");
2492
2328
  }
2493
- const peeled = peelUndoSources(events2, sources, tipTurn);
2494
- surface = {
2495
- operation,
2496
- marker,
2497
- sources: peeled.undoSources,
2498
- mode,
2499
- replaceStartSeq,
2500
- replaceEndSeq,
2501
- ...peeled.nextTip !== void 0 ? { nextTip: peeled.nextTip } : {}
2502
- };
2503
- messages = peeled.undoSources.map((event) => ({
2504
- seq: event.seq,
2505
- type: event.type,
2506
- text: textOf(event)
2507
- }));
2329
+ }
2330
+ if (undoStored.session.format !== adapter.session.header.version) {
2331
+ unavailable.push("incompatible-session");
2508
2332
  }
2509
2333
  }
2334
+ stored = undoStored;
2335
+ surface = {
2336
+ operation,
2337
+ tipTurn,
2338
+ live: liveCut,
2339
+ restoreCut: liveCut.previous
2340
+ };
2341
+ messages = events2.filter((event) => Number(event.seq) > liveCut.cutSeq && Number(event.seq) <= liveCut.restoredAtSeq && surfaceEventTypes.has(event.type) && !isProtectedSystemMessage(event)).map((event) => ({
2342
+ seq: Number(event.seq),
2343
+ type: event.type,
2344
+ text: textOf(event)
2345
+ }));
2510
2346
  }
2511
2347
  }
2512
2348
  }
2349
+ const trackedFiles = stored === null || adapter === null || surface === null ? [] : this.trackedFilesForRestore(checkpoints, adapter, surface, liveCut);
2513
2350
  let conflicts = [];
2514
2351
  if (stored !== null && adapter !== null) {
2515
2352
  try {
2516
- conflicts = await this.files(adapter, stored, "preview").verifyCurrent(stored.files, directionOf(operation));
2353
+ conflicts = await this.files(adapter, stored, "preview").verifyCurrent(trackedFiles, directionOf(operation));
2517
2354
  } catch (error) {
2518
2355
  if (error instanceof CheckpointFileError) conflicts = error.conflicts;
2519
2356
  else throw error;
2520
2357
  }
2521
2358
  }
2522
- const markerScope = surface?.operation === "undo" ? scopeOfMarker(surface.marker) : void 0;
2523
- const tipWindow = adapter !== null ? activeRollbackWindow(adapter.readEvents(), adapter.session.surface.nodes) : void 0;
2524
- const previewTurn = surface?.operation === "undo" ? turnFromRollbackId(surface.marker.data.id) ?? request.turn : request.turn;
2359
+ const cutWindow = windowFromCut(liveCut);
2360
+ const tipWindow = adapter !== null ? cutWindow ?? activeRollbackWindow(adapter.readEvents(), adapter.session.surface.nodes) : void 0;
2361
+ const previewTurn = surface?.operation === "undo" ? surface.tipTurn : request.turn;
2362
+ const undoScope = surface?.operation === "undo" ? surface.live.scope : void 0;
2525
2363
  return {
2526
2364
  checkpoint: stored,
2527
2365
  adapter,
@@ -2529,16 +2367,46 @@ var CheckpointRollbackService = class {
2529
2367
  preview: {
2530
2368
  sessionId: request.sessionId,
2531
2369
  turn: previewTurn,
2370
+ ...stored === null ? {} : { atSeq: stored.atSeq },
2532
2371
  ...operation === "undo" ? { operation } : {},
2533
- ...markerScope === void 0 ? {} : { scope: markerScope },
2372
+ ...undoScope === void 0 ? {} : { scope: undoScope },
2534
2373
  ...tipWindow === void 0 ? {} : { tipTurn: tipWindow.tipTurn },
2535
2374
  messages,
2536
- files: stored?.files.map((file) => ({ path: file.path, change: file.change })) ?? [],
2375
+ files: trackedFiles.map((file) => ({ path: file.path, change: file.change })),
2537
2376
  conflicts,
2538
2377
  unavailable: [...new Set(unavailable)]
2539
2378
  }
2540
2379
  };
2541
2380
  }
2381
+ /**
2382
+ * Tracked text files for this restore/undo.
2383
+ * Rollback with no live cut: target turn → tip.
2384
+ * Rollback while a later cut is live: only the gap down to that tip (already restored).
2385
+ * Undo: reverse only the segment this tip added (down to previous tip, or open-ended).
2386
+ */
2387
+ trackedFilesForRestore(checkpoints, adapter, surface, liveCut) {
2388
+ const shells = undoShellRanges(adapter.readEvents());
2389
+ const real = checkpoints.filter((checkpoint) => checkpoint.files.length > 0 || !isUndoShellCheckpoint(checkpoint.atSeq, shells));
2390
+ if (surface.operation === "undo") {
2391
+ const previous = liveCut?.previous ?? null;
2392
+ return chainTrackedFiles(real, {
2393
+ fromTurn: surface.tipTurn,
2394
+ fromAtSeq: surface.live.cutSeq,
2395
+ ...previous !== null && previous.hideTurnsFrom > surface.tipTurn ? {
2396
+ untilTurnExclusive: previous.hideTurnsFrom,
2397
+ untilAtSeqExclusive: previous.cutSeq
2398
+ } : {}
2399
+ });
2400
+ }
2401
+ return chainTrackedFiles(real, {
2402
+ fromTurn: surface.turn,
2403
+ fromAtSeq: surface.cutSeq,
2404
+ ...liveCut !== null && liveCut.hideTurnsFrom > surface.turn ? {
2405
+ untilTurnExclusive: liveCut.hideTurnsFrom,
2406
+ untilAtSeqExclusive: liveCut.cutSeq
2407
+ } : {}
2408
+ });
2409
+ }
2542
2410
  effectiveScope(request, evaluation) {
2543
2411
  if (operationOf(request) === "undo") {
2544
2412
  return evaluation.preview.scope ?? "conversation-and-files";
@@ -2592,71 +2460,90 @@ var CheckpointRollbackService = class {
2592
2460
  };
2593
2461
 
2594
2462
  // src/host/checkpoint/store.ts
2595
- import { createHash as createHash2, randomUUID as randomUUID4 } from "node:crypto";
2596
- import { chmod as chmod2, mkdir as mkdir2, readdir as readdir2, readFile as readFile2, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
2597
- import { basename as basename2, join as join4 } from "node:path";
2598
- import { z } from "zod";
2463
+ import { createHash as createHash3, randomUUID as randomUUID5 } from "node:crypto";
2464
+ 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";
2465
+ import { basename as basename3, join as join5 } from "node:path";
2466
+ import { z as z2 } from "zod";
2599
2467
  var MAX_CHECKPOINTS = 20;
2600
2468
  var checkpointQueues = /* @__PURE__ */ new Map();
2601
2469
  var journalQueues = /* @__PURE__ */ new Map();
2602
- async function serialize2(queues, key, operation) {
2603
- const previous = queues.get(key) ?? Promise.resolve();
2470
+ function byStoreOrder(left, right) {
2471
+ return left.createdAt - right.createdAt || left.atSeq - right.atSeq || left.turn - right.turn || left.id.localeCompare(right.id);
2472
+ }
2473
+ function retainCheckpoints(checkpoints, max = MAX_CHECKPOINTS) {
2474
+ if (checkpoints.length <= max) return [...checkpoints].sort(byStoreOrder);
2475
+ const rich = checkpoints.filter((checkpoint) => checkpoint.files.length > 0);
2476
+ const empty = checkpoints.filter((checkpoint) => checkpoint.files.length === 0);
2477
+ const emptyOldestFirst = [...empty].sort(byStoreOrder);
2478
+ const dropEmpty = Math.max(0, checkpoints.length - max);
2479
+ const keptEmpty = emptyOldestFirst.slice(dropEmpty);
2480
+ let kept = [...rich, ...keptEmpty];
2481
+ if (kept.length > max) {
2482
+ kept = [...kept].sort(byStoreOrder).slice(kept.length - max);
2483
+ }
2484
+ return kept.sort(byStoreOrder);
2485
+ }
2486
+ async function serialize3(queues2, key, operation) {
2487
+ const previous = queues2.get(key) ?? Promise.resolve();
2604
2488
  const result = previous.then(operation);
2605
2489
  const tail = result.then(() => void 0, () => void 0);
2606
- queues.set(key, tail);
2490
+ queues2.set(key, tail);
2607
2491
  try {
2608
2492
  return await result;
2609
2493
  } finally {
2610
- if (queues.get(key) === tail) queues.delete(key);
2494
+ if (queues2.get(key) === tail) queues2.delete(key);
2611
2495
  }
2612
2496
  }
2613
- var sessionIdSchema = z.string().min(1).transform((value) => value);
2614
- var gapSchema = z.discriminatedUnion("type", [
2615
- z.object({ type: z.literal("prompt"), reason: z.literal("non-text-content") }).strict(),
2616
- z.object({ type: z.literal("workspace"), reason: z.literal("capture-failed") }).strict()
2497
+ var sessionIdSchema2 = z2.string().min(1).transform((value) => value);
2498
+ var gapSchema = z2.discriminatedUnion("type", [
2499
+ z2.object({ type: z2.literal("prompt"), reason: z2.literal("non-text-content") }).strict(),
2500
+ z2.object({ type: z2.literal("workspace"), reason: z2.literal("capture-failed") }).strict()
2617
2501
  ]);
2618
- var fileSchema = z.object({
2619
- path: z.string().min(1),
2620
- change: z.enum(["create", "modify", "delete"]),
2621
- beforeText: z.string().nullable(),
2622
- beforeHash: z.string(),
2623
- afterText: z.string().nullable(),
2624
- afterHash: z.string()
2502
+ var fileSchema2 = z2.object({
2503
+ path: z2.string().min(1),
2504
+ change: z2.enum(["create", "modify", "delete"]),
2505
+ beforeText: z2.string().nullable(),
2506
+ beforeHash: z2.string(),
2507
+ afterText: z2.string().nullable(),
2508
+ afterHash: z2.string()
2625
2509
  }).strict().superRefine((file, context) => {
2626
2510
  const validBefore = file.change === "create" ? file.beforeText === null : file.beforeText !== null;
2627
2511
  if (!validBefore) context.addIssue({ code: "custom", path: ["beforeText"], message: "Invalid before-image" });
2628
2512
  const validAfter = file.change === "delete" ? file.afterText === null : file.afterText !== null;
2629
2513
  if (!validAfter) context.addIssue({ code: "custom", path: ["afterText"], message: "Invalid after-image" });
2630
2514
  });
2631
- var checkpointSchema = z.object({
2632
- schemaVersion: z.literal(CHECKPOINT_SCHEMA_VERSION),
2633
- pluginVersion: z.string().min(1),
2634
- id: z.string().min(1),
2635
- sessionId: sessionIdSchema,
2636
- session: z.object({ format: z.number().int().positive(), preset: z.string().nullable() }).strict(),
2637
- turn: z.number().int().positive(),
2638
- atSeq: z.number().int().nonnegative(),
2639
- prompt: z.string(),
2640
- createdAt: z.number().int().nonnegative(),
2641
- stage: z.literal("committed"),
2642
- coverage: z.enum(["complete", "partial"]),
2643
- gaps: z.array(gapSchema),
2644
- files: z.array(fileSchema)
2515
+ var checkpointSchema = z2.object({
2516
+ schemaVersion: z2.literal(CHECKPOINT_SCHEMA_VERSION),
2517
+ pluginVersion: z2.string().min(1),
2518
+ id: z2.string().min(1),
2519
+ sessionId: sessionIdSchema2,
2520
+ session: z2.object({ format: z2.number().int().positive(), preset: z2.string().nullable() }).strict(),
2521
+ turn: z2.number().int().positive(),
2522
+ atSeq: z2.number().int().nonnegative(),
2523
+ prompt: z2.string(),
2524
+ createdAt: z2.number().int().nonnegative(),
2525
+ stage: z2.literal("committed"),
2526
+ coverage: z2.enum(["complete", "partial"]),
2527
+ gaps: z2.array(gapSchema),
2528
+ files: z2.array(fileSchema2),
2529
+ /** Legacy shadow-git fields (ignored; stripped on save). */
2530
+ shadowBeforeCommit: z2.string().min(7).optional(),
2531
+ shadowAfterCommit: z2.string().min(7).optional()
2645
2532
  }).strict().superRefine((checkpoint, context) => {
2646
2533
  const valid = checkpoint.coverage === "complete" ? checkpoint.gaps.length === 0 : checkpoint.gaps.length > 0;
2647
2534
  if (!valid) context.addIssue({ code: "custom", path: ["gaps"], message: "Coverage does not match gaps" });
2648
2535
  });
2649
- var storeSchema = z.object({
2650
- schemaVersion: z.literal(CHECKPOINT_SCHEMA_VERSION),
2651
- checkpoints: z.array(checkpointSchema).max(MAX_CHECKPOINTS)
2536
+ var storeSchema = z2.object({
2537
+ schemaVersion: z2.literal(CHECKPOINT_SCHEMA_VERSION),
2538
+ checkpoints: z2.array(checkpointSchema).max(MAX_CHECKPOINTS)
2652
2539
  }).strict();
2653
- var journalSchema = z.object({
2654
- schemaVersion: z.literal(CHECKPOINT_SCHEMA_VERSION),
2655
- id: z.string().min(1),
2656
- sessionId: sessionIdSchema,
2657
- checkpointId: z.string().min(1),
2658
- status: z.enum(["prepared", "files-restored", "completed", "compensated"]),
2659
- createdAt: z.number().int().nonnegative()
2540
+ var journalSchema = z2.object({
2541
+ schemaVersion: z2.literal(CHECKPOINT_SCHEMA_VERSION),
2542
+ id: z2.string().min(1),
2543
+ sessionId: sessionIdSchema2,
2544
+ checkpointId: z2.string().min(1),
2545
+ status: z2.enum(["prepared", "files-restored", "completed", "compensated"]),
2546
+ createdAt: z2.number().int().nonnegative()
2660
2547
  }).strict();
2661
2548
  var CheckpointStoreError = class extends Error {
2662
2549
  constructor(code) {
@@ -2669,11 +2556,11 @@ var CheckpointStoreError = class extends Error {
2669
2556
  function isRecord2(value) {
2670
2557
  return typeof value === "object" && value !== null;
2671
2558
  }
2672
- function isMissing2(error) {
2559
+ function isMissing3(error) {
2673
2560
  return isRecord2(error) && error.code === "ENOENT";
2674
2561
  }
2675
- function digest2(value) {
2676
- return createHash2("sha256").update(value).digest("hex");
2562
+ function digest3(value) {
2563
+ return createHash3("sha256").update(value).digest("hex");
2677
2564
  }
2678
2565
  function assertCheckpointSchema(value) {
2679
2566
  if (isRecord2(value) && value.schemaVersion !== CHECKPOINT_SCHEMA_VERSION) {
@@ -2687,29 +2574,29 @@ function assertStoredSchema(value) {
2687
2574
  for (const checkpoint of value.checkpoints) assertCheckpointSchema(checkpoint);
2688
2575
  }
2689
2576
  }
2690
- async function removeIfPresent2(path) {
2577
+ async function removeIfPresent3(path) {
2691
2578
  try {
2692
- await unlink2(path);
2579
+ await unlink3(path);
2693
2580
  } catch (error) {
2694
- if (!isMissing2(error)) throw error;
2581
+ if (!isMissing3(error)) throw error;
2695
2582
  }
2696
2583
  }
2697
- async function writeAtomic2(path, value) {
2698
- const temporary = join4(join4(path, ".."), `.${basename2(path)}.${randomUUID4()}.tmp`);
2584
+ async function writeAtomic3(path, value) {
2585
+ const temporary = join5(join5(path, ".."), `.${basename3(path)}.${randomUUID5()}.tmp`);
2699
2586
  try {
2700
- await writeFile2(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
2701
- await rename2(temporary, path);
2702
- await chmod2(path, 384);
2587
+ await writeFile3(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
2588
+ await rename3(temporary, path);
2589
+ await chmod3(path, 384);
2703
2590
  } finally {
2704
- await removeIfPresent2(temporary);
2591
+ await removeIfPresent3(temporary);
2705
2592
  }
2706
2593
  }
2707
2594
  var CheckpointStore = class {
2708
2595
  constructor(root) {
2709
2596
  this.root = root;
2710
- this.checkpointDirectory = join4(root, "checkpoints");
2711
- this.journalDirectory = join4(root, "journals");
2712
- this.rootKey = join4(root, ".");
2597
+ this.checkpointDirectory = join5(root, "checkpoints");
2598
+ this.journalDirectory = join5(root, "journals");
2599
+ this.rootKey = join5(root, ".");
2713
2600
  }
2714
2601
  root;
2715
2602
  checkpointDirectory;
@@ -2719,16 +2606,15 @@ var CheckpointStore = class {
2719
2606
  assertCheckpointSchema(checkpoint);
2720
2607
  const parsed = checkpointSchema.safeParse(checkpoint);
2721
2608
  if (!parsed.success) throw new CheckpointStoreError("INVALID_CHECKPOINT");
2722
- await serialize2(checkpointQueues, this.checkpointKey(checkpoint.sessionId), async () => {
2609
+ await serialize3(checkpointQueues, this.checkpointKey(checkpoint.sessionId), async () => {
2723
2610
  const checkpoints = await this.list(checkpoint.sessionId);
2724
2611
  const existing = checkpoints.findIndex((value) => value.id === checkpoint.id);
2725
2612
  if (existing >= 0) checkpoints.splice(existing, 1, parsed.data);
2726
2613
  else checkpoints.push(parsed.data);
2727
- checkpoints.sort((left, right) => left.createdAt - right.createdAt || left.turn - right.turn || left.id.localeCompare(right.id));
2728
2614
  await this.ensureDirectories();
2729
- await writeAtomic2(this.checkpointPath(checkpoint.sessionId), {
2615
+ await writeAtomic3(this.checkpointPath(checkpoint.sessionId), {
2730
2616
  schemaVersion: CHECKPOINT_SCHEMA_VERSION,
2731
- checkpoints: checkpoints.slice(-MAX_CHECKPOINTS)
2617
+ checkpoints: retainCheckpoints(checkpoints, MAX_CHECKPOINTS)
2732
2618
  });
2733
2619
  });
2734
2620
  }
@@ -2738,7 +2624,7 @@ var CheckpointStore = class {
2738
2624
  try {
2739
2625
  stored = await this.readJson(this.checkpointPath(sessionId));
2740
2626
  } catch (error) {
2741
- if (isMissing2(error)) return [];
2627
+ if (isMissing3(error)) return [];
2742
2628
  throw error;
2743
2629
  }
2744
2630
  assertStoredSchema(stored);
@@ -2751,11 +2637,11 @@ var CheckpointStore = class {
2751
2637
  * Empty list removes the session file.
2752
2638
  */
2753
2639
  async replace(sessionId, checkpoints) {
2754
- await serialize2(checkpointQueues, this.checkpointKey(sessionId), async () => {
2640
+ await serialize3(checkpointQueues, this.checkpointKey(sessionId), async () => {
2755
2641
  await this.ensureDirectories();
2756
2642
  const path = this.checkpointPath(sessionId);
2757
2643
  if (checkpoints.length === 0) {
2758
- await removeIfPresent2(path);
2644
+ await removeIfPresent3(path);
2759
2645
  return;
2760
2646
  }
2761
2647
  const next = [];
@@ -2766,43 +2652,42 @@ var CheckpointStore = class {
2766
2652
  if (parsed.data.sessionId !== sessionId) throw new CheckpointStoreError("INVALID_CHECKPOINT");
2767
2653
  next.push(parsed.data);
2768
2654
  }
2769
- next.sort((left, right) => left.createdAt - right.createdAt || left.turn - right.turn || left.id.localeCompare(right.id));
2770
- await writeAtomic2(path, {
2655
+ await writeAtomic3(path, {
2771
2656
  schemaVersion: CHECKPOINT_SCHEMA_VERSION,
2772
- checkpoints: next.slice(-MAX_CHECKPOINTS)
2657
+ checkpoints: retainCheckpoints(next, MAX_CHECKPOINTS)
2773
2658
  });
2774
2659
  });
2775
2660
  }
2776
2661
  /** Drop settled journal files left behind after compensate / complete races. */
2777
2662
  async purgeSettledJournals() {
2778
- return serialize2(journalQueues, this.rootKey, async () => {
2663
+ return serialize3(journalQueues, this.rootKey, async () => {
2779
2664
  await this.ensureDirectories();
2780
2665
  let names;
2781
2666
  try {
2782
2667
  names = await readdir2(this.journalDirectory);
2783
2668
  } catch (error) {
2784
- if (isMissing2(error)) return 0;
2669
+ if (isMissing3(error)) return 0;
2785
2670
  throw error;
2786
2671
  }
2787
2672
  let removed = 0;
2788
2673
  for (const name2 of names) {
2789
2674
  if (!name2.endsWith(".json")) continue;
2790
- const path = join4(this.journalDirectory, name2);
2675
+ const path = join5(this.journalDirectory, name2);
2791
2676
  const stored = await this.readJson(path);
2792
2677
  assertCheckpointSchema(stored);
2793
2678
  const parsed = journalSchema.safeParse(stored);
2794
2679
  if (!parsed.success) continue;
2795
2680
  if (parsed.data.status === "prepared" || parsed.data.status === "files-restored") continue;
2796
- await removeIfPresent2(path);
2681
+ await removeIfPresent3(path);
2797
2682
  removed += 1;
2798
2683
  }
2799
2684
  return removed;
2800
2685
  });
2801
2686
  }
2802
2687
  async recoverInterruptedWrites(sessionId) {
2803
- await serialize2(checkpointQueues, this.checkpointKey(sessionId), async () => {
2688
+ await serialize3(checkpointQueues, this.checkpointKey(sessionId), async () => {
2804
2689
  await this.ensureDirectories();
2805
- const prefix = `.${basename2(this.checkpointPath(sessionId))}.`;
2690
+ const prefix = `.${basename3(this.checkpointPath(sessionId))}.`;
2806
2691
  await this.cleanTemporaryFiles(this.checkpointDirectory, prefix);
2807
2692
  });
2808
2693
  }
@@ -2810,22 +2695,22 @@ var CheckpointStore = class {
2810
2695
  assertCheckpointSchema(journal);
2811
2696
  const parsed = journalSchema.safeParse(journal);
2812
2697
  if (!parsed.success) throw new CheckpointStoreError("INVALID_JOURNAL");
2813
- await serialize2(journalQueues, this.rootKey, async () => {
2698
+ await serialize3(journalQueues, this.rootKey, async () => {
2814
2699
  await this.ensureDirectories();
2815
- await writeAtomic2(join4(this.journalDirectory, `${digest2(journal.id)}.json`), parsed.data);
2700
+ await writeAtomic3(join5(this.journalDirectory, `${digest3(journal.id)}.json`), parsed.data);
2816
2701
  });
2817
2702
  }
2818
2703
  async completeJournal(id) {
2819
- await serialize2(journalQueues, this.rootKey, async () => {
2704
+ await serialize3(journalQueues, this.rootKey, async () => {
2820
2705
  await this.ensureDirectories();
2821
- await removeIfPresent2(join4(this.journalDirectory, `${digest2(id)}.json`));
2706
+ await removeIfPresent3(join5(this.journalDirectory, `${digest3(id)}.json`));
2822
2707
  });
2823
2708
  }
2824
2709
  async listPendingJournals() {
2825
2710
  return this.readPendingJournals();
2826
2711
  }
2827
2712
  async recoverJournal() {
2828
- return serialize2(journalQueues, this.rootKey, async () => {
2713
+ return serialize3(journalQueues, this.rootKey, async () => {
2829
2714
  await this.ensureDirectories();
2830
2715
  await this.cleanTemporaryFiles(this.journalDirectory);
2831
2716
  return this.readPendingJournals();
@@ -2836,13 +2721,13 @@ var CheckpointStore = class {
2836
2721
  try {
2837
2722
  names = await readdir2(this.journalDirectory);
2838
2723
  } catch (error) {
2839
- if (isMissing2(error)) return [];
2724
+ if (isMissing3(error)) return [];
2840
2725
  throw error;
2841
2726
  }
2842
2727
  const journals = [];
2843
2728
  for (const name2 of names.sort()) {
2844
2729
  if (!name2.endsWith(".json")) continue;
2845
- const stored = await this.readJson(join4(this.journalDirectory, name2));
2730
+ const stored = await this.readJson(join5(this.journalDirectory, name2));
2846
2731
  assertCheckpointSchema(stored);
2847
2732
  const parsed = journalSchema.safeParse(stored);
2848
2733
  if (!parsed.success) throw new CheckpointStoreError("INVALID_STORE");
@@ -2854,20 +2739,20 @@ var CheckpointStore = class {
2854
2739
  return `${this.rootKey}\0${sessionId}`;
2855
2740
  }
2856
2741
  checkpointPath(sessionId) {
2857
- return join4(this.checkpointDirectory, `${digest2(sessionId)}.json`);
2742
+ return join5(this.checkpointDirectory, `${digest3(sessionId)}.json`);
2858
2743
  }
2859
2744
  async ensureDirectories() {
2860
- await mkdir2(this.root, { recursive: true, mode: 448 });
2861
- await mkdir2(this.checkpointDirectory, { recursive: true, mode: 448 });
2862
- await mkdir2(this.journalDirectory, { recursive: true, mode: 448 });
2745
+ await mkdir3(this.root, { recursive: true, mode: 448 });
2746
+ await mkdir3(this.checkpointDirectory, { recursive: true, mode: 448 });
2747
+ await mkdir3(this.journalDirectory, { recursive: true, mode: 448 });
2863
2748
  }
2864
2749
  async cleanTemporaryFiles(directory, prefix = "") {
2865
2750
  for (const name2 of await readdir2(directory)) {
2866
- if (name2.startsWith(prefix) && name2.endsWith(".tmp")) await unlink2(join4(directory, name2));
2751
+ if (name2.startsWith(prefix) && name2.endsWith(".tmp")) await unlink3(join5(directory, name2));
2867
2752
  }
2868
2753
  }
2869
2754
  async readJson(path) {
2870
- const text3 = await readFile2(path, "utf8");
2755
+ const text3 = await readFile3(path, "utf8");
2871
2756
  try {
2872
2757
  return JSON.parse(text3);
2873
2758
  } catch {
@@ -2963,11 +2848,8 @@ function createClassifier(llm, route) {
2963
2848
  }
2964
2849
  return async (text3, signal) => withUsageSource("autoClassifier", async () => {
2965
2850
  const timeout = new AbortController();
2966
- const timer = setTimeout(() => {
2967
- timeout.abort();
2968
- }, CLASSIFIER_TIMEOUT_MS);
2969
- const unlink4 = signal === void 0 ? void 0 : linkAbortSignal(signal, timeout);
2970
- try {
2851
+ const unlink5 = signal === void 0 ? void 0 : linkAbortSignal(signal, timeout);
2852
+ const run = (async () => {
2971
2853
  timeout.signal.throwIfAborted();
2972
2854
  const call = await llm.prepareCall(
2973
2855
  { provider: route.provider, model: route.model, maxTokens: CLASSIFIER_MAX_TOKENS },
@@ -2996,9 +2878,21 @@ function createClassifier(llm, route) {
2996
2878
  throw new Error("Classifier finished without stop");
2997
2879
  }
2998
2880
  throw new Error(`Invalid classifier output: ${raw}`);
2881
+ })();
2882
+ let timer;
2883
+ try {
2884
+ return await Promise.race([
2885
+ run,
2886
+ new Promise((_resolve, reject) => {
2887
+ timer = setTimeout(() => {
2888
+ timeout.abort();
2889
+ reject(new Error("Classifier timed out"));
2890
+ }, CLASSIFIER_TIMEOUT_MS);
2891
+ })
2892
+ ]);
2999
2893
  } finally {
3000
- clearTimeout(timer);
3001
- unlink4?.();
2894
+ if (timer !== void 0) clearTimeout(timer);
2895
+ unlink5?.();
3002
2896
  }
3003
2897
  });
3004
2898
  }
@@ -3027,10 +2921,24 @@ function clearSessionResolvedRoute(agent) {
3027
2921
  // src/host/auto-route/session-selection.ts
3028
2922
  function projectedSessionModel(ctx, session) {
3029
2923
  try {
3030
- const projections = ctx.get("sessionProjections");
3031
- const state = projections?.stateOf?.(session, "modelSelection");
3032
- if (state?.pending !== void 0 && state.pending !== null) return state.pending;
3033
- if (state?.lastUsed !== void 0 && state.lastUsed !== null) return state.lastUsed;
2924
+ const agents = ctx.get("agents");
2925
+ const agent = agents?.get?.(session.id);
2926
+ const fromModel = agent?.model?.current?.();
2927
+ if (fromModel !== void 0 && typeof fromModel.provider === "string" && fromModel.provider !== "" && typeof fromModel.model === "string" && fromModel.model !== "") {
2928
+ return {
2929
+ provider: fromModel.provider,
2930
+ model: fromModel.model,
2931
+ ...typeof fromModel.reasoningEffort === "string" ? { reasoningEffort: fromModel.reasoningEffort } : {}
2932
+ };
2933
+ }
2934
+ const options = agent?.options;
2935
+ if (typeof options?.provider === "string" && options.provider !== "" && typeof options.model === "string" && options.model !== "") {
2936
+ return {
2937
+ provider: options.provider,
2938
+ model: options.model,
2939
+ ...typeof options.reasoningEffort === "string" ? { reasoningEffort: options.reasoningEffort } : {}
2940
+ };
2941
+ }
3034
2942
  } catch {
3035
2943
  }
3036
2944
  try {
@@ -3727,6 +3635,13 @@ function concreteRoute(selection) {
3727
3635
  };
3728
3636
  }
3729
3637
  function projectedSelection(ctx, agent) {
3638
+ try {
3639
+ const fromModel = agent?.model?.current?.();
3640
+ if (fromModel !== void 0 && typeof fromModel.provider === "string" && fromModel.provider !== "" && typeof fromModel.model === "string" && fromModel.model !== "") {
3641
+ return fromModel;
3642
+ }
3643
+ } catch {
3644
+ }
3730
3645
  const session = agent?.session;
3731
3646
  if (session === void 0) return void 0;
3732
3647
  try {
@@ -3737,17 +3652,26 @@ function projectedSelection(ctx, agent) {
3737
3652
  }
3738
3653
  function fallbackRoute(ctx, agent) {
3739
3654
  try {
3655
+ const projected = concreteRoute(projectedSelection(ctx, agent));
3656
+ if (projected !== void 0) return projected;
3740
3657
  const options = agent?.options;
3741
3658
  const fromOptions = typeof options?.provider === "string" && typeof options.model === "string" ? concreteRoute({ provider: options.provider, model: options.model }) : void 0;
3742
3659
  if (fromOptions !== void 0) return fromOptions;
3743
- const projected = concreteRoute(projectedSelection(ctx, agent));
3744
- if (projected !== void 0) return projected;
3745
3660
  const defaults = softService(ctx, "agentDefaultModel");
3746
3661
  return concreteRoute(defaults?.currentSelection?.());
3747
3662
  } catch {
3748
3663
  return void 0;
3749
3664
  }
3750
3665
  }
3666
+ function shouldRemapAuto(config, agent) {
3667
+ if (isAutoModel(config)) return true;
3668
+ try {
3669
+ const seat = agent?.model?.current?.();
3670
+ return seat !== void 0 && isAutoModel(seat);
3671
+ } catch {
3672
+ return false;
3673
+ }
3674
+ }
3751
3675
  function routeConfig(config, mapped) {
3752
3676
  const { reasoningEffort: _effort, ...rest } = config;
3753
3677
  void _effort;
@@ -3804,10 +3728,12 @@ function installAutoSessionRoute(ctx, options) {
3804
3728
  const llm = ctx.llm;
3805
3729
  const inner = llm.prepareCall.bind(llm);
3806
3730
  const wrapped = async (config, signal, configure) => {
3807
- const keyProbe = activeAgent(ctx) ?? config;
3808
- const depth = resolving.get(keyProbe) ?? 0;
3809
- if (depth > 0 || !isAutoModel(config)) return inner(config, signal, configure);
3810
3731
  const agent = activeAgent(ctx);
3732
+ const keyProbe = agent ?? config;
3733
+ const depth = resolving.get(keyProbe) ?? 0;
3734
+ if (depth > 0 || !shouldRemapAuto(config, asAgent(agent))) {
3735
+ return inner(config, signal, configure);
3736
+ }
3811
3737
  const key = agent ?? config;
3812
3738
  resolving.set(key, (resolving.get(key) ?? 0) + 1);
3813
3739
  try {
@@ -3829,9 +3755,9 @@ function installAutoSessionRoute(ctx, options) {
3829
3755
  if (agent !== void 0) setSessionResolvedRoute(agent, mapped);
3830
3756
  return await inner(routeConfig(config, mapped), signal, configure);
3831
3757
  } finally {
3832
- const next = (resolving.get(key) ?? 1) - 1;
3833
- if (next <= 0) resolving.delete(key);
3834
- else resolving.set(key, next);
3758
+ const nextDepth = (resolving.get(key) ?? 1) - 1;
3759
+ if (nextDepth <= 0) resolving.delete(key);
3760
+ else resolving.set(key, nextDepth);
3835
3761
  }
3836
3762
  };
3837
3763
  llm.prepareCall = wrapped;
@@ -5003,45 +4929,45 @@ function mergeUsageCalls(stored, history) {
5003
4929
  }
5004
4930
 
5005
4931
  // src/host/usage/ledger.ts
5006
- import { randomUUID as randomUUID5 } from "node:crypto";
5007
- import { chmod as chmod3, mkdir as mkdir3, readFile as readFile3, rename as rename3, unlink as unlink3, writeFile as writeFile3 } from "node:fs/promises";
5008
- import { basename as basename3, join as join5 } from "node:path";
5009
- import { z as z2 } from "zod";
5010
- var callSchema = z2.object({
5011
- at: z2.number().int().nonnegative(),
5012
- source: z2.enum(USAGE_SOURCES),
5013
- provider: z2.string().min(1),
5014
- model: z2.string().min(1),
4932
+ import { randomUUID as randomUUID6 } from "node:crypto";
4933
+ import { chmod as chmod4, mkdir as mkdir4, readFile as readFile4, rename as rename4, unlink as unlink4, writeFile as writeFile4 } from "node:fs/promises";
4934
+ import { basename as basename4, join as join6 } from "node:path";
4935
+ import { z as z3 } from "zod";
4936
+ var callSchema = z3.object({
4937
+ at: z3.number().int().nonnegative(),
4938
+ source: z3.enum(USAGE_SOURCES),
4939
+ provider: z3.string().min(1),
4940
+ model: z3.string().min(1),
5015
4941
  // Older ledgers omit effort; treat as unknown.
5016
- reasoningEffort: z2.string().optional().default(""),
5017
- inputTokens: z2.number().int().nonnegative(),
5018
- outputTokens: z2.number().int().nonnegative(),
5019
- cacheReadTokens: z2.number().int().nonnegative(),
5020
- cacheWriteTokens: z2.number().int().nonnegative(),
5021
- reasoningTokens: z2.number().int().nonnegative()
4942
+ reasoningEffort: z3.string().optional().default(""),
4943
+ inputTokens: z3.number().int().nonnegative(),
4944
+ outputTokens: z3.number().int().nonnegative(),
4945
+ cacheReadTokens: z3.number().int().nonnegative(),
4946
+ cacheWriteTokens: z3.number().int().nonnegative(),
4947
+ reasoningTokens: z3.number().int().nonnegative()
5022
4948
  }).strict();
5023
- var fileSchema2 = z2.object({
5024
- schemaVersion: z2.literal(1),
5025
- calls: z2.array(z2.unknown())
4949
+ var fileSchema3 = z3.object({
4950
+ schemaVersion: z3.literal(1),
4951
+ calls: z3.array(z3.unknown())
5026
4952
  }).strict();
5027
- function isMissing3(error) {
4953
+ function isMissing4(error) {
5028
4954
  return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
5029
4955
  }
5030
- async function removeIfPresent3(path) {
4956
+ async function removeIfPresent4(path) {
5031
4957
  try {
5032
- await unlink3(path);
4958
+ await unlink4(path);
5033
4959
  } catch (error) {
5034
- if (!isMissing3(error)) throw error;
4960
+ if (!isMissing4(error)) throw error;
5035
4961
  }
5036
4962
  }
5037
- async function writeAtomic3(path, value) {
5038
- const temporary = join5(join5(path, ".."), `.${basename3(path)}.${randomUUID5()}.tmp`);
4963
+ async function writeAtomic4(path, value) {
4964
+ const temporary = join6(join6(path, ".."), `.${basename4(path)}.${randomUUID6()}.tmp`);
5039
4965
  try {
5040
- await writeFile3(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
5041
- await rename3(temporary, path);
5042
- await chmod3(path, 384);
4966
+ await writeFile4(temporary, JSON.stringify(value), { encoding: "utf8", mode: 384, flag: "wx" });
4967
+ await rename4(temporary, path);
4968
+ await chmod4(path, 384);
5043
4969
  } finally {
5044
- await removeIfPresent3(temporary);
4970
+ await removeIfPresent4(temporary);
5045
4971
  }
5046
4972
  }
5047
4973
  var UsageLedger = class {
@@ -5049,7 +4975,7 @@ var UsageLedger = class {
5049
4975
  }) {
5050
4976
  this.root = root;
5051
4977
  this.warn = warn;
5052
- this.file = join5(root, "ledger.json");
4978
+ this.file = join6(root, "ledger.json");
5053
4979
  }
5054
4980
  root;
5055
4981
  warn;
@@ -5090,9 +5016,9 @@ var UsageLedger = class {
5090
5016
  async read() {
5091
5017
  let text3;
5092
5018
  try {
5093
- text3 = await readFile3(this.file, "utf8");
5019
+ text3 = await readFile4(this.file, "utf8");
5094
5020
  } catch (error) {
5095
- if (isMissing3(error)) return [];
5021
+ if (isMissing4(error)) return [];
5096
5022
  throw error;
5097
5023
  }
5098
5024
  let parsed;
@@ -5101,7 +5027,7 @@ var UsageLedger = class {
5101
5027
  } catch {
5102
5028
  return [];
5103
5029
  }
5104
- const file = fileSchema2.safeParse(parsed);
5030
+ const file = fileSchema3.safeParse(parsed);
5105
5031
  if (!file.success) return [];
5106
5032
  const calls = [];
5107
5033
  for (const item of file.data.calls) {
@@ -5116,8 +5042,8 @@ var UsageLedger = class {
5116
5042
  await this.persist();
5117
5043
  }
5118
5044
  async persist() {
5119
- await mkdir3(this.root, { recursive: true, mode: 448 });
5120
- await writeAtomic3(this.file, { schemaVersion: 1, calls: this.calls });
5045
+ await mkdir4(this.root, { recursive: true, mode: 448 });
5046
+ await writeAtomic4(this.file, { schemaVersion: 1, calls: this.calls });
5121
5047
  }
5122
5048
  };
5123
5049
 
@@ -5159,53 +5085,53 @@ function installUsageObserver(ctx, recorder) {
5159
5085
 
5160
5086
  // src/host/rpc.ts
5161
5087
  import { createTypertRemoteInfo } from "@deepseek-ai/dsh-typert-protocol/remote-info";
5162
- import { z as z3 } from "zod";
5088
+ import { z as z4 } from "zod";
5163
5089
 
5164
5090
  // src/host/update/types.ts
5165
5091
  var APPLY_UPDATE_CODES = ["restart", "link", "manual", "none", "failed"];
5166
5092
 
5167
5093
  // src/host/rpc.ts
5168
- var sessionIdSchema2 = z3.string().min(1).transform((value) => value);
5169
- var recentExchangeSchema = z3.strictObject({
5170
- turn: z3.number().int().nonnegative(),
5171
- prompt: z3.string(),
5172
- response: z3.string()
5094
+ var sessionIdSchema3 = z4.string().min(1).transform((value) => value);
5095
+ var recentExchangeSchema = z4.strictObject({
5096
+ turn: z4.number().int().nonnegative(),
5097
+ prompt: z4.string(),
5098
+ response: z4.string()
5173
5099
  });
5174
- var optimizeReferenceSchema = z3.strictObject({
5175
- offset: z3.number().int().nonnegative(),
5176
- length: z3.number().int().positive(),
5177
- text: z3.string().min(1)
5100
+ var optimizeReferenceSchema = z4.strictObject({
5101
+ offset: z4.number().int().nonnegative(),
5102
+ length: z4.number().int().positive(),
5103
+ text: z4.string().min(1)
5178
5104
  });
5179
- var uiLocaleSchema = z3.enum(["zh", "en"]).optional();
5180
- var optimizeRequestSchema = z3.strictObject({
5181
- operation: z3.literal("optimize"),
5182
- requestId: z3.string(),
5183
- sessionId: sessionIdSchema2,
5184
- source: z3.string(),
5185
- references: z3.array(optimizeReferenceSchema),
5186
- context: z3.array(recentExchangeSchema),
5105
+ var uiLocaleSchema = z4.enum(["zh", "en"]).optional();
5106
+ var optimizeRequestSchema = z4.strictObject({
5107
+ operation: z4.literal("optimize"),
5108
+ requestId: z4.string(),
5109
+ sessionId: sessionIdSchema3,
5110
+ source: z4.string(),
5111
+ references: z4.array(optimizeReferenceSchema),
5112
+ context: z4.array(recentExchangeSchema),
5187
5113
  uiLocale: uiLocaleSchema
5188
5114
  });
5189
- var predictRequestSchema = z3.strictObject({
5190
- operation: z3.literal("predict"),
5191
- requestId: z3.string(),
5192
- sessionId: sessionIdSchema2,
5193
- context: z3.array(recentExchangeSchema),
5115
+ var predictRequestSchema = z4.strictObject({
5116
+ operation: z4.literal("predict"),
5117
+ requestId: z4.string(),
5118
+ sessionId: sessionIdSchema3,
5119
+ context: z4.array(recentExchangeSchema),
5194
5120
  uiLocale: uiLocaleSchema
5195
5121
  });
5196
- var auxiliaryRequestSchema = z3.discriminatedUnion("operation", [
5122
+ var auxiliaryRequestSchema = z4.discriminatedUnion("operation", [
5197
5123
  optimizeRequestSchema,
5198
5124
  predictRequestSchema
5199
5125
  ]);
5200
- var rpcPayloadSchema = z3.strictObject({
5201
- method: z3.literal("generate"),
5126
+ var rpcPayloadSchema = z4.strictObject({
5127
+ method: z4.literal("generate"),
5202
5128
  data: auxiliaryRequestSchema
5203
5129
  });
5204
- var auxiliaryResultSchema = z3.strictObject({
5205
- requestId: z3.string(),
5206
- text: z3.string(),
5207
- route: z3.strictObject({ provider: z3.string(), model: z3.string() }),
5208
- segments: z3.array(z3.string()).optional()
5130
+ var auxiliaryResultSchema = z4.strictObject({
5131
+ requestId: z4.string(),
5132
+ text: z4.string(),
5133
+ route: z4.strictObject({ provider: z4.string(), model: z4.string() }),
5134
+ segments: z4.array(z4.string()).optional()
5209
5135
  });
5210
5136
  function codec(typeSymbol, schema) {
5211
5137
  return { mode: "strict", typeSymbol, create: () => schema };
@@ -5213,50 +5139,50 @@ function codec(typeSymbol, schema) {
5213
5139
  var payloadCodec = codec("dsh-agent-enhancer#RpcPayload", rpcPayloadSchema);
5214
5140
  var resultCodec = codec(
5215
5141
  "dsh-agent-enhancer#AuxiliaryResult|null",
5216
- z3.union([auxiliaryResultSchema, z3.null()])
5142
+ z4.union([auxiliaryResultSchema, z4.null()])
5217
5143
  );
5218
- var modelReasoningEffortSchema = z3.object({
5219
- id: z3.string(),
5220
- name: z3.string(),
5221
- description: z3.string().optional()
5144
+ var modelReasoningEffortSchema = z4.object({
5145
+ id: z4.string(),
5146
+ name: z4.string(),
5147
+ description: z4.string().optional()
5222
5148
  });
5223
- var modelReasoningSchema = z3.object({
5224
- efforts: z3.array(modelReasoningEffortSchema),
5225
- defaultEffort: z3.string().optional()
5149
+ var modelReasoningSchema = z4.object({
5150
+ efforts: z4.array(modelReasoningEffortSchema),
5151
+ defaultEffort: z4.string().optional()
5226
5152
  });
5227
- var modelCatalogModelSchema = z3.object({
5228
- id: z3.string(),
5229
- name: z3.string(),
5230
- description: z3.string().optional(),
5153
+ var modelCatalogModelSchema = z4.object({
5154
+ id: z4.string(),
5155
+ name: z4.string(),
5156
+ description: z4.string().optional(),
5231
5157
  reasoning: modelReasoningSchema.optional()
5232
5158
  });
5233
- var modelProviderGroupSchema = z3.object({
5234
- id: z3.string(),
5235
- name: z3.string(),
5236
- models: z3.array(modelCatalogModelSchema)
5159
+ var modelProviderGroupSchema = z4.object({
5160
+ id: z4.string(),
5161
+ name: z4.string(),
5162
+ models: z4.array(modelCatalogModelSchema)
5237
5163
  });
5238
- var modelCatalogFailureSchema = z3.object({
5239
- id: z3.string(),
5240
- name: z3.string(),
5241
- message: z3.string()
5164
+ var modelCatalogFailureSchema = z4.object({
5165
+ id: z4.string(),
5166
+ name: z4.string(),
5167
+ message: z4.string()
5242
5168
  });
5243
- var modelCatalogSchema = z3.object({
5244
- default: z3.object({
5245
- provider: z3.string(),
5246
- model: z3.string(),
5247
- reasoningEffort: z3.string().optional()
5169
+ var modelCatalogSchema = z4.object({
5170
+ default: z4.object({
5171
+ provider: z4.string(),
5172
+ model: z4.string(),
5173
+ reasoningEffort: z4.string().optional()
5248
5174
  }),
5249
- routableProviders: z3.array(z3.string()),
5250
- groups: z3.array(modelProviderGroupSchema),
5251
- failures: z3.array(modelCatalogFailureSchema)
5175
+ routableProviders: z4.array(z4.string()),
5176
+ groups: z4.array(modelProviderGroupSchema),
5177
+ failures: z4.array(modelCatalogFailureSchema)
5252
5178
  });
5253
5179
  var catalogCodec = codec("dsh-agent-enhancer#ModelCatalog", modelCatalogSchema);
5254
- var contextInspectCategorySchema = z3.enum(["system", "tools", "messages"]);
5255
- var contextInspectRequestSchema = z3.strictObject({
5256
- sessionId: sessionIdSchema2,
5180
+ var contextInspectCategorySchema = z4.enum(["system", "tools", "messages"]);
5181
+ var contextInspectRequestSchema = z4.strictObject({
5182
+ sessionId: sessionIdSchema3,
5257
5183
  category: contextInspectCategorySchema
5258
5184
  });
5259
- var contextInspectKindSchema = z3.enum([
5185
+ var contextInspectKindSchema = z4.enum([
5260
5186
  "system",
5261
5187
  "tools",
5262
5188
  "user",
@@ -5265,144 +5191,144 @@ var contextInspectKindSchema = z3.enum([
5265
5191
  "tool",
5266
5192
  "developer"
5267
5193
  ]);
5268
- var contextInspectItemSchema = z3.strictObject({
5269
- id: z3.string(),
5270
- title: z3.string(),
5271
- detail: z3.string(),
5272
- body: z3.string(),
5273
- tokens: z3.number().int().nonnegative(),
5194
+ var contextInspectItemSchema = z4.strictObject({
5195
+ id: z4.string(),
5196
+ title: z4.string(),
5197
+ detail: z4.string(),
5198
+ body: z4.string(),
5199
+ tokens: z4.number().int().nonnegative(),
5274
5200
  kind: contextInspectKindSchema,
5275
- replaced: z3.boolean()
5201
+ replaced: z4.boolean()
5276
5202
  });
5277
- var contextInspectPressureSchema = z3.strictObject({
5278
- projectedTokens: z3.number().int().nonnegative().optional(),
5279
- contextWindow: z3.number().int().positive().optional()
5203
+ var contextInspectPressureSchema = z4.strictObject({
5204
+ projectedTokens: z4.number().int().nonnegative().optional(),
5205
+ contextWindow: z4.number().int().positive().optional()
5280
5206
  });
5281
- var contextInspectEventKindSchema = z3.enum(["compact", "prune", "replace"]);
5282
- var contextInspectEventMarkSchema = z3.strictObject({
5283
- id: z3.string(),
5207
+ var contextInspectEventKindSchema = z4.enum(["compact", "prune", "replace"]);
5208
+ var contextInspectEventMarkSchema = z4.strictObject({
5209
+ id: z4.string(),
5284
5210
  kind: contextInspectEventKindSchema,
5285
- seq: z3.number().int().nonnegative(),
5286
- shadowed: z3.number().int().nonnegative(),
5287
- title: z3.string()
5211
+ seq: z4.number().int().nonnegative(),
5212
+ shadowed: z4.number().int().nonnegative(),
5213
+ title: z4.string()
5288
5214
  });
5289
- var contextInspectResultSchema = z3.strictObject({
5290
- sessionId: sessionIdSchema2,
5215
+ var contextInspectResultSchema = z4.strictObject({
5216
+ sessionId: sessionIdSchema3,
5291
5217
  category: contextInspectCategorySchema,
5292
- totalTokens: z3.number().int().nonnegative(),
5293
- approximate: z3.literal(true),
5294
- items: z3.array(contextInspectItemSchema),
5218
+ totalTokens: z4.number().int().nonnegative(),
5219
+ approximate: z4.literal(true),
5220
+ items: z4.array(contextInspectItemSchema),
5295
5221
  pressure: contextInspectPressureSchema,
5296
- events: z3.array(contextInspectEventMarkSchema)
5222
+ events: z4.array(contextInspectEventMarkSchema)
5297
5223
  });
5298
5224
  var contextInspectRequestCodec = codec("dsh-agent-enhancer#ContextInspectRequest", contextInspectRequestSchema);
5299
5225
  var contextInspectResultCodec = codec("dsh-agent-enhancer#ContextInspectResult", contextInspectResultSchema);
5300
- var contextCompactRequestSchema = z3.strictObject({
5301
- sessionId: sessionIdSchema2
5226
+ var contextCompactRequestSchema = z4.strictObject({
5227
+ sessionId: sessionIdSchema3
5302
5228
  });
5303
- var contextCompactResultSchema = z3.strictObject({
5304
- sessionId: sessionIdSchema2,
5305
- status: z3.enum(["compacted", "noop"]),
5306
- shadowedCount: z3.number().int().nonnegative(),
5307
- shadowedTokens: z3.number().int().nonnegative()
5229
+ var contextCompactResultSchema = z4.strictObject({
5230
+ sessionId: sessionIdSchema3,
5231
+ status: z4.enum(["compacted", "noop"]),
5232
+ shadowedCount: z4.number().int().nonnegative(),
5233
+ shadowedTokens: z4.number().int().nonnegative()
5308
5234
  });
5309
5235
  var contextCompactRequestCodec = codec("dsh-agent-enhancer#ContextCompactRequest", contextCompactRequestSchema);
5310
5236
  var contextCompactResultCodec = codec("dsh-agent-enhancer#ContextCompactResult", contextCompactResultSchema);
5311
- var updateCheckResultSchema = z3.strictObject({
5312
- current: z3.string(),
5313
- latest: z3.string().nullable(),
5314
- updateAvailable: z3.boolean(),
5315
- installKind: z3.enum(["npm", "link", "unknown"]),
5316
- canAutoApply: z3.boolean(),
5317
- command: z3.string()
5237
+ var updateCheckResultSchema = z4.strictObject({
5238
+ current: z4.string(),
5239
+ latest: z4.string().nullable(),
5240
+ updateAvailable: z4.boolean(),
5241
+ installKind: z4.enum(["npm", "link", "unknown"]),
5242
+ canAutoApply: z4.boolean(),
5243
+ command: z4.string()
5318
5244
  });
5319
- var applyUpdateResultSchema = z3.strictObject({
5320
- ok: z3.boolean(),
5321
- message: z3.enum(APPLY_UPDATE_CODES),
5322
- command: z3.string().optional()
5245
+ var applyUpdateResultSchema = z4.strictObject({
5246
+ ok: z4.boolean(),
5247
+ message: z4.enum(APPLY_UPDATE_CODES),
5248
+ command: z4.string().optional()
5323
5249
  });
5324
5250
  var updateCheckResultCodec = codec("dsh-agent-enhancer#UpdateCheckResult", updateCheckResultSchema);
5325
5251
  var applyUpdateResultCodec = codec("dsh-agent-enhancer#ApplyUpdateResult", applyUpdateResultSchema);
5326
5252
  var usageTokenFields = {
5327
- inputTokens: z3.number().int().nonnegative(),
5328
- outputTokens: z3.number().int().nonnegative(),
5329
- cacheReadTokens: z3.number().int().nonnegative(),
5330
- cacheWriteTokens: z3.number().int().nonnegative(),
5331
- reasoningTokens: z3.number().int().nonnegative()
5253
+ inputTokens: z4.number().int().nonnegative(),
5254
+ outputTokens: z4.number().int().nonnegative(),
5255
+ cacheReadTokens: z4.number().int().nonnegative(),
5256
+ cacheWriteTokens: z4.number().int().nonnegative(),
5257
+ reasoningTokens: z4.number().int().nonnegative()
5332
5258
  };
5333
- var usageRangeSchema = z3.enum(USAGE_RANGES);
5334
- var usageCallSchema = z3.object({
5335
- at: z3.number().int().nonnegative(),
5336
- source: z3.enum(USAGE_SOURCES),
5337
- provider: z3.string(),
5338
- model: z3.string(),
5339
- reasoningEffort: z3.string(),
5259
+ var usageRangeSchema = z4.enum(USAGE_RANGES);
5260
+ var usageCallSchema = z4.object({
5261
+ at: z4.number().int().nonnegative(),
5262
+ source: z4.enum(USAGE_SOURCES),
5263
+ provider: z4.string(),
5264
+ model: z4.string(),
5265
+ reasoningEffort: z4.string(),
5340
5266
  ...usageTokenFields
5341
5267
  }).strict();
5342
- var usageModelLineSchema = z3.object({
5343
- provider: z3.string(),
5344
- model: z3.string(),
5345
- reasoningEffort: z3.string(),
5346
- calls: z3.number().int().nonnegative(),
5268
+ var usageModelLineSchema = z4.object({
5269
+ provider: z4.string(),
5270
+ model: z4.string(),
5271
+ reasoningEffort: z4.string(),
5272
+ calls: z4.number().int().nonnegative(),
5347
5273
  ...usageTokenFields
5348
5274
  }).strict();
5349
- var usageSourceLineSchema = z3.object({
5350
- source: z3.enum(USAGE_SOURCES),
5351
- calls: z3.number().int().nonnegative(),
5352
- models: z3.array(usageModelLineSchema),
5275
+ var usageSourceLineSchema = z4.object({
5276
+ source: z4.enum(USAGE_SOURCES),
5277
+ calls: z4.number().int().nonnegative(),
5278
+ models: z4.array(usageModelLineSchema),
5353
5279
  ...usageTokenFields
5354
5280
  }).strict();
5355
- var usageHeatCellSchema = z3.object({
5356
- key: z3.string(),
5357
- label: z3.string(),
5358
- at: z3.number().int().nonnegative(),
5359
- tokens: z3.number().int().nonnegative(),
5360
- calls: z3.number().int().nonnegative()
5281
+ var usageHeatCellSchema = z4.object({
5282
+ key: z4.string(),
5283
+ label: z4.string(),
5284
+ at: z4.number().int().nonnegative(),
5285
+ tokens: z4.number().int().nonnegative(),
5286
+ calls: z4.number().int().nonnegative()
5361
5287
  }).strict();
5362
- var usageHeatmapSchema = z3.object({
5363
- grain: z3.enum(["hour", "day"]),
5364
- cells: z3.array(usageHeatCellSchema)
5288
+ var usageHeatmapSchema = z4.object({
5289
+ grain: z4.enum(["hour", "day"]),
5290
+ cells: z4.array(usageHeatCellSchema)
5365
5291
  }).strict();
5366
- var usageMoneySchema = z3.object({
5367
- currency: z3.literal("CNY"),
5368
- estimatedCost: z3.number().nonnegative(),
5369
- pricedCalls: z3.number().int().nonnegative(),
5370
- unpricedCalls: z3.number().int().nonnegative()
5292
+ var usageMoneySchema = z4.object({
5293
+ currency: z4.literal("CNY"),
5294
+ estimatedCost: z4.number().nonnegative(),
5295
+ pricedCalls: z4.number().int().nonnegative(),
5296
+ unpricedCalls: z4.number().int().nonnegative()
5371
5297
  }).strict();
5372
- var usageBalanceSchema = z3.object({
5373
- available: z3.boolean(),
5374
- currency: z3.string(),
5375
- total: z3.string(),
5376
- granted: z3.string(),
5377
- toppedUp: z3.string(),
5378
- checkedAt: z3.number().int().nonnegative(),
5379
- stale: z3.boolean().optional()
5298
+ var usageBalanceSchema = z4.object({
5299
+ available: z4.boolean(),
5300
+ currency: z4.string(),
5301
+ total: z4.string(),
5302
+ granted: z4.string(),
5303
+ toppedUp: z4.string(),
5304
+ checkedAt: z4.number().int().nonnegative(),
5305
+ stale: z4.boolean().optional()
5380
5306
  }).strict();
5381
- var usageBalanceStatusSchema = z3.enum(["ready", "no-key", "unavailable"]);
5382
- var usageSummarySchema = z3.object({
5307
+ var usageBalanceStatusSchema = z4.enum(["ready", "no-key", "unavailable"]);
5308
+ var usageSummarySchema = z4.object({
5383
5309
  range: usageRangeSchema,
5384
- calls: z3.number().int().nonnegative(),
5385
- sources: z3.array(usageSourceLineSchema),
5310
+ calls: z4.number().int().nonnegative(),
5311
+ sources: z4.array(usageSourceLineSchema),
5386
5312
  heatmap: usageHeatmapSchema,
5387
5313
  money: usageMoneySchema,
5388
5314
  balanceStatus: usageBalanceStatusSchema,
5389
5315
  balance: usageBalanceSchema.optional(),
5390
- recent: z3.array(usageCallSchema),
5316
+ recent: z4.array(usageCallSchema),
5391
5317
  ...usageTokenFields
5392
5318
  }).strict();
5393
- var providerBalanceStatusSchema = z3.enum(["ready", "no-key", "signed-out", "unavailable"]);
5394
- var providerBalanceSnapshotSchema = z3.object({
5395
- source: z3.enum(["account", "api-key"]),
5319
+ var providerBalanceStatusSchema = z4.enum(["ready", "no-key", "signed-out", "unavailable"]);
5320
+ var providerBalanceSnapshotSchema = z4.object({
5321
+ source: z4.enum(["account", "api-key"]),
5396
5322
  status: providerBalanceStatusSchema,
5397
5323
  balance: usageBalanceSchema.optional()
5398
5324
  }).strict();
5399
- var providerBalancesSchema = z3.object({
5325
+ var providerBalancesSchema = z4.object({
5400
5326
  account: providerBalanceSnapshotSchema,
5401
5327
  apiKey: providerBalanceSnapshotSchema
5402
5328
  }).strict();
5403
- var providerBalancesRequestSchema = z3.object({
5404
- force: z3.boolean().optional(),
5405
- locale: z3.string().optional()
5329
+ var providerBalancesRequestSchema = z4.object({
5330
+ force: z4.boolean().optional(),
5331
+ locale: z4.string().optional()
5406
5332
  }).strict();
5407
5333
  var usageRangeCodec = codec("dsh-agent-enhancer#UsageRange", usageRangeSchema);
5408
5334
  var usageSummaryCodec = codec("dsh-agent-enhancer#UsageSummary", usageSummarySchema);
@@ -5500,26 +5426,28 @@ var remoteInfo = createTypertRemoteInfo({
5500
5426
  result: providerBalancesCodec
5501
5427
  }
5502
5428
  }
5503
- }, z3);
5504
- var checkpointScopeSchema = z3.enum(["conversation", "conversation-and-files"]);
5505
- var checkpointRollbackRequestSchema = z3.strictObject({
5506
- sessionId: sessionIdSchema2,
5507
- turn: z3.number().int().positive(),
5508
- operation: z3.enum(["rollback", "undo"]).optional(),
5509
- scope: checkpointScopeSchema.optional()
5429
+ }, z4);
5430
+ var checkpointScopeSchema = z4.enum(["conversation", "conversation-and-files"]);
5431
+ var checkpointRollbackRequestSchema = z4.strictObject({
5432
+ sessionId: sessionIdSchema3,
5433
+ turn: z4.number().int().positive(),
5434
+ operation: z4.enum(["rollback", "undo"]).optional(),
5435
+ scope: checkpointScopeSchema.optional(),
5436
+ // Timeline cards pin the tip by atSeq (turn numbers reuse after undo).
5437
+ atSeq: z4.number().int().nonnegative().optional()
5510
5438
  });
5511
- var checkpointMessageSchema = z3.strictObject({
5512
- seq: z3.number().int().nonnegative(),
5513
- type: z3.string(),
5514
- text: z3.string()
5439
+ var checkpointMessageSchema = z4.strictObject({
5440
+ seq: z4.number().int().nonnegative(),
5441
+ type: z4.string(),
5442
+ text: z4.string()
5515
5443
  });
5516
- var checkpointFileSchema = z3.strictObject({
5517
- path: z3.string(),
5518
- change: z3.enum(["create", "modify", "delete"])
5444
+ var checkpointFileSchema = z4.strictObject({
5445
+ path: z4.string(),
5446
+ change: z4.enum(["create", "modify", "delete"])
5519
5447
  });
5520
- var checkpointConflictSchema = z3.strictObject({
5521
- path: z3.string(),
5522
- reason: z3.enum([
5448
+ var checkpointConflictSchema = z4.strictObject({
5449
+ path: z4.string(),
5450
+ reason: z4.enum([
5523
5451
  "unsafe-path",
5524
5452
  "symlink",
5525
5453
  "not-regular-file",
@@ -5529,10 +5457,10 @@ var checkpointConflictSchema = z3.strictObject({
5529
5457
  "invalid-after-image",
5530
5458
  "hash-mismatch"
5531
5459
  ]),
5532
- expectedHash: z3.string().optional(),
5533
- actualHash: z3.string().nullable().optional()
5460
+ expectedHash: z4.string().optional(),
5461
+ actualHash: z4.string().nullable().optional()
5534
5462
  });
5535
- var checkpointUnavailableSchema = z3.enum([
5463
+ var checkpointUnavailableSchema = z4.enum([
5536
5464
  "checkpoint-not-found",
5537
5465
  "incomplete-checkpoint",
5538
5466
  "prompt-non-text-content",
@@ -5548,52 +5476,67 @@ var checkpointUnavailableSchema = z3.enum([
5548
5476
  "already-restored",
5549
5477
  "covered-by-earlier-restore"
5550
5478
  ]);
5551
- var checkpointPreviewSchema = z3.strictObject({
5552
- sessionId: sessionIdSchema2,
5553
- turn: z3.number().int().positive(),
5554
- operation: z3.enum(["rollback", "undo"]).optional(),
5479
+ var checkpointPreviewSchema = z4.strictObject({
5480
+ sessionId: sessionIdSchema3,
5481
+ turn: z4.number().int().positive(),
5482
+ operation: z4.enum(["rollback", "undo"]).optional(),
5555
5483
  scope: checkpointScopeSchema.optional(),
5556
- tipTurn: z3.number().int().positive().optional(),
5557
- messages: z3.array(checkpointMessageSchema),
5558
- files: z3.array(checkpointFileSchema),
5559
- conflicts: z3.array(checkpointConflictSchema),
5560
- unavailable: z3.array(checkpointUnavailableSchema)
5484
+ tipTurn: z4.number().int().positive().optional(),
5485
+ atSeq: z4.number().int().nonnegative().optional(),
5486
+ messages: z4.array(checkpointMessageSchema),
5487
+ files: z4.array(checkpointFileSchema),
5488
+ conflicts: z4.array(checkpointConflictSchema),
5489
+ unavailable: z4.array(checkpointUnavailableSchema)
5561
5490
  });
5562
- var checkpointResultSchema = z3.strictObject({
5563
- sessionId: sessionIdSchema2,
5564
- turn: z3.number().int().positive(),
5565
- draft: z3.string()
5491
+ var checkpointResultSchema = z4.strictObject({
5492
+ sessionId: sessionIdSchema3,
5493
+ turn: z4.number().int().positive(),
5494
+ draft: z4.string()
5566
5495
  });
5567
- var checkpointSummariesRequestSchema = z3.strictObject({
5568
- sessionId: sessionIdSchema2
5496
+ var checkpointSummariesRequestSchema = z4.strictObject({
5497
+ sessionId: sessionIdSchema3
5569
5498
  });
5570
- var checkpointGapSchema = z3.discriminatedUnion("type", [
5571
- z3.object({ type: z3.literal("prompt"), reason: z3.literal("non-text-content") }).strict(),
5572
- z3.object({ type: z3.literal("workspace"), reason: z3.literal("capture-failed") }).strict()
5499
+ var checkpointGapSchema = z4.discriminatedUnion("type", [
5500
+ z4.object({ type: z4.literal("prompt"), reason: z4.literal("non-text-content") }).strict(),
5501
+ z4.object({ type: z4.literal("workspace"), reason: z4.literal("capture-failed") }).strict()
5573
5502
  ]);
5574
- var checkpointTurnSummarySchema = z3.strictObject({
5575
- turn: z3.number().int().positive(),
5576
- coverage: z3.enum(["complete", "partial"]),
5577
- fileCount: z3.number().int().nonnegative(),
5578
- createdAt: z3.number().int().nonnegative(),
5579
- atSeq: z3.number().int().nonnegative(),
5580
- prompt: z3.string(),
5581
- promptPreview: z3.string(),
5582
- files: z3.array(checkpointFileSchema),
5583
- gaps: z3.array(checkpointGapSchema),
5584
- rolledBack: z3.boolean(),
5585
- tip: z3.boolean()
5503
+ var checkpointTurnSummarySchema = z4.strictObject({
5504
+ turn: z4.number().int().positive(),
5505
+ coverage: z4.enum(["complete", "partial"]),
5506
+ fileCount: z4.number().int().nonnegative(),
5507
+ createdAt: z4.number().int().nonnegative(),
5508
+ atSeq: z4.number().int().nonnegative(),
5509
+ prompt: z4.string(),
5510
+ promptPreview: z4.string(),
5511
+ files: z4.array(checkpointFileSchema),
5512
+ gaps: z4.array(checkpointGapSchema),
5513
+ rolledBack: z4.boolean(),
5514
+ tip: z4.boolean()
5586
5515
  });
5587
- var liveActivityStatsSchema = z3.strictObject({
5588
- turns: z3.number().int().nonnegative(),
5589
- steps: z3.number().int().nonnegative(),
5590
- checkpoints: z3.number().int().nonnegative(),
5591
- liveCheckpoints: z3.number().int().nonnegative()
5516
+ var liveActivityStatsSchema = z4.strictObject({
5517
+ turns: z4.number().int().nonnegative(),
5518
+ steps: z4.number().int().nonnegative(),
5519
+ checkpoints: z4.number().int().nonnegative(),
5520
+ liveCheckpoints: z4.number().int().nonnegative()
5592
5521
  });
5593
- var checkpointSummariesResultSchema = z3.strictObject({
5594
- sessionId: sessionIdSchema2,
5522
+ var checkpointSummariesResultSchema = z4.strictObject({
5523
+ sessionId: sessionIdSchema3,
5595
5524
  activity: liveActivityStatsSchema,
5596
- turns: z3.array(checkpointTurnSummarySchema)
5525
+ turns: z4.array(checkpointTurnSummarySchema)
5526
+ });
5527
+ var checkpointCutRequestSchema = z4.strictObject({
5528
+ sessionId: sessionIdSchema3
5529
+ });
5530
+ var checkpointCutViewSchema = z4.strictObject({
5531
+ hideTurnsFrom: z4.number().int().positive(),
5532
+ cutSeq: z4.number().int().nonnegative(),
5533
+ restoredAtSeq: z4.number().int().nonnegative(),
5534
+ draftPrompt: z4.string(),
5535
+ scope: checkpointScopeSchema
5536
+ });
5537
+ var checkpointCutResultSchema = z4.strictObject({
5538
+ sessionId: sessionIdSchema3,
5539
+ cut: checkpointCutViewSchema.nullable()
5597
5540
  });
5598
5541
  var checkpointRequestCodec = codec("dsh-agent-enhancer#CheckpointRollbackRequest", checkpointRollbackRequestSchema);
5599
5542
  var checkpointPreviewCodec = codec("dsh-agent-enhancer#CheckpointRollbackPreview", checkpointPreviewSchema);
@@ -5606,6 +5549,14 @@ var checkpointSummariesResultCodec = codec(
5606
5549
  "dsh-agent-enhancer#CheckpointSummariesResult",
5607
5550
  checkpointSummariesResultSchema
5608
5551
  );
5552
+ var checkpointCutRequestCodec = codec(
5553
+ "dsh-agent-enhancer#CheckpointCutRequest",
5554
+ checkpointCutRequestSchema
5555
+ );
5556
+ var checkpointCutResultCodec = codec(
5557
+ "dsh-agent-enhancer#CheckpointCutResult",
5558
+ checkpointCutResultSchema
5559
+ );
5609
5560
  var checkpointRemoteInfo = createTypertRemoteInfo({
5610
5561
  package: "dsh-agent-enhancer",
5611
5562
  methods: {
@@ -5637,13 +5588,26 @@ var checkpointRemoteInfo = createTypertRemoteInfo({
5637
5588
  }],
5638
5589
  cancellation: { parameter: "signal" },
5639
5590
  result: checkpointSummariesResultCodec
5591
+ },
5592
+ "checkpointRollback/getCut": {
5593
+ service: "checkpointRollback",
5594
+ implementation: "getCut",
5595
+ invocation: { kind: "direct" },
5596
+ parameters: [{
5597
+ name: "request",
5598
+ source: "json",
5599
+ codec: checkpointCutRequestCodec,
5600
+ strictCodec: checkpointCutRequestCodec
5601
+ }],
5602
+ cancellation: { parameter: "signal" },
5603
+ result: checkpointCutResultCodec
5640
5604
  }
5641
5605
  }
5642
- }, z3);
5606
+ }, z4);
5643
5607
 
5644
5608
  // src/host/update/check.ts
5645
5609
  import { homedir } from "node:os";
5646
- import { join as join7 } from "node:path";
5610
+ import { join as join8 } from "node:path";
5647
5611
 
5648
5612
  // src/host/update/cli.ts
5649
5613
  import { spawn as nodeSpawn } from "node:child_process";
@@ -5714,9 +5678,9 @@ async function runPluginAdd(latest, spawnFn = defaultSpawn) {
5714
5678
 
5715
5679
  // src/host/update/install-kind.ts
5716
5680
  import { lstatSync } from "node:fs";
5717
- import { join as join6 } from "node:path";
5681
+ import { join as join7 } from "node:path";
5718
5682
  function detectInstallKind(profileDir) {
5719
- const pkgPath = join6(profileDir, "node_modules", PACKAGE_NAME);
5683
+ const pkgPath = join7(profileDir, "node_modules", PACKAGE_NAME);
5720
5684
  try {
5721
5685
  const stat = lstatSync(pkgPath);
5722
5686
  if (stat.isSymbolicLink()) return "link";
@@ -5847,8 +5811,8 @@ function isNewerVersion(latest, current) {
5847
5811
 
5848
5812
  // src/host/update/check.ts
5849
5813
  function resolveDesktopProfileDir(env = process.env, home = homedir()) {
5850
- const dshHome = env.DSH_HOME ?? join7(home, ".dsh");
5851
- return join7(dshHome, "profiles", "desktop");
5814
+ const dshHome = env.DSH_HOME ?? join8(home, ".dsh");
5815
+ return join8(dshHome, "profiles", "desktop");
5852
5816
  }
5853
5817
  async function checkPluginUpdate(deps) {
5854
5818
  const latest = await deps.fetchLatest();
@@ -5920,35 +5884,35 @@ var inject = [
5920
5884
  // Official `/compact` runs through the command registry (not ctx.compaction).
5921
5885
  "commands"
5922
5886
  ];
5923
- var Config = z4.object({
5924
- historyEnabled: z4.boolean().default(true).volatile(),
5925
- optimizeEnabled: z4.boolean().default(true).volatile(),
5926
- predictEnabled: z4.boolean().default(true).volatile(),
5927
- rollbackEnabled: z4.boolean().default(true).volatile(),
5928
- contextInspectEnabled: z4.boolean().default(true).volatile(),
5887
+ var Config = z5.object({
5888
+ historyEnabled: z5.boolean().default(true).volatile(),
5889
+ optimizeEnabled: z5.boolean().default(true).volatile(),
5890
+ predictEnabled: z5.boolean().default(true).volatile(),
5891
+ rollbackEnabled: z5.boolean().default(true).volatile(),
5892
+ contextInspectEnabled: z5.boolean().default(true).volatile(),
5929
5893
  // Empty provider/model = follow the current Desktop session model.
5930
- optimizeProvider: z4.string().default("").volatile(),
5931
- optimizeModel: z4.string().default("").volatile(),
5932
- optimizeReasoningEffort: z4.string().default("").volatile(),
5933
- predictProvider: z4.string().default("").volatile(),
5934
- predictModel: z4.string().default("").volatile(),
5935
- predictReasoningEffort: z4.string().default("").volatile(),
5936
- compactProvider: z4.string().default("").volatile(),
5937
- compactModel: z4.string().default("").volatile(),
5938
- compactReasoningEffort: z4.string().default("").volatile(),
5939
- autoClassifierEnabled: z4.boolean().default(false).volatile(),
5940
- autoInstantProvider: z4.string().default("").volatile(),
5941
- autoInstantModel: z4.string().default("").volatile(),
5942
- autoInstantReasoningEffort: z4.string().default("").volatile(),
5943
- autoThinkingProvider: z4.string().default("").volatile(),
5944
- autoThinkingModel: z4.string().default("").volatile(),
5945
- autoThinkingReasoningEffort: z4.string().default("").volatile(),
5946
- autoProProvider: z4.string().default("").volatile(),
5947
- autoProModel: z4.string().default("").volatile(),
5948
- autoProReasoningEffort: z4.string().default("").volatile(),
5949
- autoClassifierProvider: z4.string().default("").volatile(),
5950
- autoClassifierModel: z4.string().default("").volatile(),
5951
- autoClassifierReasoningEffort: z4.string().default("").volatile()
5894
+ optimizeProvider: z5.string().default("").volatile(),
5895
+ optimizeModel: z5.string().default("").volatile(),
5896
+ optimizeReasoningEffort: z5.string().default("").volatile(),
5897
+ predictProvider: z5.string().default("").volatile(),
5898
+ predictModel: z5.string().default("").volatile(),
5899
+ predictReasoningEffort: z5.string().default("").volatile(),
5900
+ compactProvider: z5.string().default("").volatile(),
5901
+ compactModel: z5.string().default("").volatile(),
5902
+ compactReasoningEffort: z5.string().default("").volatile(),
5903
+ autoClassifierEnabled: z5.boolean().default(false).volatile(),
5904
+ autoInstantProvider: z5.string().default("").volatile(),
5905
+ autoInstantModel: z5.string().default("").volatile(),
5906
+ autoInstantReasoningEffort: z5.string().default("").volatile(),
5907
+ autoThinkingProvider: z5.string().default("").volatile(),
5908
+ autoThinkingModel: z5.string().default("").volatile(),
5909
+ autoThinkingReasoningEffort: z5.string().default("").volatile(),
5910
+ autoProProvider: z5.string().default("").volatile(),
5911
+ autoProModel: z5.string().default("").volatile(),
5912
+ autoProReasoningEffort: z5.string().default("").volatile(),
5913
+ autoClassifierProvider: z5.string().default("").volatile(),
5914
+ autoClassifierModel: z5.string().default("").volatile(),
5915
+ autoClassifierReasoningEffort: z5.string().default("").volatile()
5952
5916
  });
5953
5917
  var hostContribution = {
5954
5918
  package: PACKAGE_NAME,
@@ -6076,14 +6040,14 @@ var AgentEnhancerService = class extends TypertRemoteService {
6076
6040
  }
6077
6041
  };
6078
6042
  function resolveCheckpointRoot(dshHome) {
6079
- const base = join8(dshHome, "profiles", "desktop", "plugin-data");
6080
- const nextPkg = join8(base, PACKAGE_NAME);
6081
- const next = join8(nextPkg, "checkpoint");
6082
- const prev = join8(base, LEGACY_PACKAGE_NAME, "checkpoint");
6043
+ const base = join9(dshHome, "profiles", "desktop", "plugin-data");
6044
+ const nextPkg = join9(base, PACKAGE_NAME);
6045
+ const next = join9(nextPkg, "checkpoint");
6046
+ const prev = join9(base, LEGACY_PACKAGE_NAME, "checkpoint");
6083
6047
  if (!existsSync(next) && existsSync(prev)) {
6084
6048
  mkdirSync(nextPkg, { recursive: true });
6085
6049
  renameSync(prev, next);
6086
- const prevPkg = join8(base, LEGACY_PACKAGE_NAME);
6050
+ const prevPkg = join9(base, LEGACY_PACKAGE_NAME);
6087
6051
  try {
6088
6052
  if (existsSync(prevPkg) && readdirSync(prevPkg).length === 0) rmdirSync(prevPkg);
6089
6053
  } catch {
@@ -6149,8 +6113,8 @@ function apply(ctx, config) {
6149
6113
  const settings = () => readSettings(config);
6150
6114
  const models = new AuxiliaryModels(ctx, settings);
6151
6115
  installAutoSessionRoute(ctx, { settings });
6152
- const storageRoot = resolveCheckpointRoot(process.env.DSH_HOME ?? join8(homedir2(), ".dsh"));
6153
- const usage = new UsageLedger(join8(storageRoot, "..", "usage"), (message) => {
6116
+ const storageRoot = resolveCheckpointRoot(process.env.DSH_HOME ?? join9(homedir2(), ".dsh"));
6117
+ const usage = new UsageLedger(join9(storageRoot, "..", "usage"), (message) => {
6154
6118
  ctx.logger.warn(message);
6155
6119
  });
6156
6120
  const balancesFacade = (() => {
@@ -6200,6 +6164,8 @@ function apply(ctx, config) {
6200
6164
  );
6201
6165
  ctx.effect(() => ctx.typert.register(hostContribution));
6202
6166
  const store = new CheckpointStore(storageRoot);
6167
+ const cutStore = new SessionCutStore(join9(storageRoot, "cuts"));
6168
+ const cutCache = /* @__PURE__ */ new Map();
6203
6169
  const sessions = new DshCheckpointSessions(ctx);
6204
6170
  let rollbackEnabled = config.rollbackEnabled.get();
6205
6171
  const captures = new DshCheckpointCaptureSwitch(ctx, { store, pluginVersion: PACKAGE_VERSION });
@@ -6209,12 +6175,15 @@ function apply(ctx, config) {
6209
6175
  pluginVersion: PACKAGE_VERSION,
6210
6176
  resolveSession: sessions.resolveSession,
6211
6177
  isEnabled: () => rollbackEnabled,
6212
- awaitCaptures: () => captures.awaitPending()
6178
+ awaitCaptures: () => captures.awaitPending(),
6179
+ cutStore,
6180
+ cutCache
6213
6181
  });
6214
6182
  applyCheckpointRollback(ctx, rollback);
6215
6183
  void rollback.recover().catch(() => {
6216
6184
  ctx.logger.warn("Checkpoint rollback recovery is still pending");
6217
6185
  });
6186
+ ctx.effect(() => installSessionCutFilter(ctx, { store: cutStore, cache: cutCache }));
6218
6187
  ctx.effect(() => {
6219
6188
  const unsubscribe = ctx.on("internal/update", (resolvedConfig, next) => {
6220
6189
  rollbackEnabled = resolvedConfig.rollbackEnabled.get();
@@ -6266,6 +6235,14 @@ var CheckpointRollbackRemoteService = class extends TypertRemoteService {
6266
6235
  throw this.remoteError(error, signal);
6267
6236
  }
6268
6237
  }
6238
+ async getCut(request, signal) {
6239
+ this.assertOwner();
6240
+ try {
6241
+ return await this.rollback.getCut(request, signal);
6242
+ } catch (error) {
6243
+ throw this.remoteError(error, signal);
6244
+ }
6245
+ }
6269
6246
  assertOwner() {
6270
6247
  if (this.ctx.invocation?.peer.principal.kind !== "owner") {
6271
6248
  throw new RemoteError("agent-enhancer/forbidden", "Only the desktop owner may use checkpoint rollback", {});