@aiwayds/dsh-opentui 0.28.2 → 0.29.0

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.
@@ -1,8 +1,10 @@
1
1
  // ../bridge/src/index.ts
2
2
  import { randomUUID } from "node:crypto";
3
- import { readFileSync as readFileSync2, realpathSync } from "node:fs";
4
- import { createRequire } from "node:module";
5
- import { dirname, join as join2 } from "node:path";
3
+ import { readFileSync as readFileSync2, realpathSync as realpathSync2 } from "node:fs";
4
+ import { appendFile, lstat, mkdir, open as open2, readFile, readdir, realpath, rename, rmdir, stat, unlink, writeFile } from "node:fs/promises";
5
+ import { createRequire as createRequire2 } from "node:module";
6
+ import { homedir as homedir2 } from "node:os";
7
+ import { dirname as dirname4, join as join6 } from "node:path";
6
8
 
7
9
  // ../bridge/src/ask-frames.ts
8
10
  var ASK_FRAME_TYPES = {
@@ -1134,17 +1136,1796 @@ class SubagentIndex {
1134
1136
  out.push({ childId, row });
1135
1137
  }
1136
1138
  }
1137
- return out;
1138
- }
1139
- }
1140
- var indexes = new WeakMap;
1141
- function getSubagentIndex(ctx) {
1142
- let index = indexes.get(ctx);
1143
- if (index === undefined) {
1144
- index = new SubagentIndex;
1145
- indexes.set(ctx, index);
1146
- }
1147
- return index;
1139
+ return out;
1140
+ }
1141
+ }
1142
+ var indexes = new WeakMap;
1143
+ function getSubagentIndex(ctx) {
1144
+ let index = indexes.get(ctx);
1145
+ if (index === undefined) {
1146
+ index = new SubagentIndex;
1147
+ indexes.set(ctx, index);
1148
+ }
1149
+ return index;
1150
+ }
1151
+
1152
+ // ../bridge/src/session-prune.ts
1153
+ import { basename, dirname, join as join2, sep } from "node:path";
1154
+ var DEFAULT_RETENTION_DAYS = 90;
1155
+ var MS_PER_DAY = 86400000;
1156
+ function encodeSegment(raw) {
1157
+ if (raw.length === 0)
1158
+ throw new Error("cannot encode an empty path segment");
1159
+ if (raw === ".")
1160
+ return "~002E";
1161
+ if (raw === "..")
1162
+ return "~002E~002E";
1163
+ let out = "";
1164
+ for (let i = 0;i < raw.length; i++) {
1165
+ const code = raw.charCodeAt(i);
1166
+ const ch = String.fromCharCode(code);
1167
+ if (ch !== "~" && /^[A-Za-z0-9._-]$/.test(ch)) {
1168
+ out += ch;
1169
+ } else {
1170
+ out += "~" + code.toString(16).toUpperCase().padStart(4, "0");
1171
+ }
1172
+ }
1173
+ return out;
1174
+ }
1175
+ function hasStatCapability(value) {
1176
+ return value !== null && typeof value === "object" && typeof value.stat === "function";
1177
+ }
1178
+ var DEFAULT_MAX_PAGES = 64;
1179
+ async function listAllSessions(lister, options) {
1180
+ const requested = options?.maxPages;
1181
+ const maxPages = typeof requested === "number" && Number.isInteger(requested) && requested > 0 && requested <= 512 ? requested : DEFAULT_MAX_PAGES;
1182
+ const rows = [];
1183
+ const seenIds = new Set;
1184
+ const usedCursors = new Set;
1185
+ let cursor;
1186
+ let pages = 0;
1187
+ let truncated = false;
1188
+ while (pages < maxPages) {
1189
+ usedCursors.add(cursor ?? "");
1190
+ const page = await lister.list({ _request: cursor !== undefined ? { cursor } : {} });
1191
+ if (page === null || typeof page !== "object" || !Array.isArray(page.items)) {
1192
+ throw new Error("BAD_REPLY: session.list returned an object without an items array");
1193
+ }
1194
+ pages += 1;
1195
+ for (const raw of page.items) {
1196
+ if (raw === null || typeof raw !== "object")
1197
+ continue;
1198
+ const row = raw;
1199
+ if (typeof row.sessionId !== "string" || row.sessionId === "" || seenIds.has(row.sessionId))
1200
+ continue;
1201
+ seenIds.add(row.sessionId);
1202
+ rows.push(row);
1203
+ }
1204
+ const hasMore = page.hasMore === true;
1205
+ const next = typeof page.nextCursor === "string" && page.nextCursor !== "" ? page.nextCursor : undefined;
1206
+ if (!hasMore)
1207
+ break;
1208
+ if (next === undefined) {
1209
+ truncated = true;
1210
+ break;
1211
+ }
1212
+ if (usedCursors.has(next)) {
1213
+ truncated = true;
1214
+ break;
1215
+ }
1216
+ cursor = next;
1217
+ }
1218
+ if (pages >= maxPages && cursor !== undefined)
1219
+ truncated = true;
1220
+ return { rows, pages, truncated };
1221
+ }
1222
+ function isInside(root, target) {
1223
+ const base = root.length > 1 && root.endsWith(sep) ? root.slice(0, -1) : root;
1224
+ return target === base || target.startsWith(base.endsWith(sep) ? base : base + sep);
1225
+ }
1226
+ function locationPath(location) {
1227
+ if (typeof location === "string")
1228
+ return location !== "" ? location : undefined;
1229
+ if (location !== null && typeof location === "object") {
1230
+ return typeof location.path === "string" && location.path !== "" ? location.path : undefined;
1231
+ }
1232
+ return;
1233
+ }
1234
+ function hasRunningDescendant(id, rows) {
1235
+ const children = new Map;
1236
+ for (const row of rows) {
1237
+ if (typeof row.sessionId !== "string" || row.sessionId === "")
1238
+ continue;
1239
+ const parent = typeof row.parentSessionId === "string" ? row.parentSessionId : "";
1240
+ if (parent !== "") {
1241
+ const list = children.get(parent) ?? [];
1242
+ list.push(row.sessionId);
1243
+ children.set(parent, list);
1244
+ }
1245
+ }
1246
+ const queue = [id];
1247
+ const visited = new Set([id]);
1248
+ while (queue.length > 0) {
1249
+ const current = queue.shift();
1250
+ for (const childId of children.get(current) ?? []) {
1251
+ if (visited.has(childId))
1252
+ continue;
1253
+ visited.add(childId);
1254
+ const child = rows.find((r) => r.sessionId === childId);
1255
+ if (child?.running === true)
1256
+ return true;
1257
+ queue.push(childId);
1258
+ }
1259
+ }
1260
+ return rows.some((row) => row.running === true && typeof row.sessionId === "string" && row.sessionId.startsWith(id + "/"));
1261
+ }
1262
+ function skip(id, reason, location, ageDays) {
1263
+ return location !== undefined ? { sessionId: id, decision: "skip", reason, location, ...ageDays !== undefined ? { ageDays } : {} } : { sessionId: id, decision: "skip", reason, ...ageDays !== undefined ? { ageDays } : {} };
1264
+ }
1265
+ async function planSessionPrune(rows, persistence, fs, config) {
1266
+ const rootReal = await fs.realpath(config.sessionsRoot);
1267
+ const now = Number.isFinite(config.now) ? config.now : Date.now();
1268
+ const entries = [];
1269
+ for (const row of rows) {
1270
+ const rawId = row.sessionId;
1271
+ if (typeof rawId !== "string" || rawId === "") {
1272
+ entries.push(skip("", "field-anomaly"));
1273
+ continue;
1274
+ }
1275
+ const id = rawId;
1276
+ if (config.retentionDays === 0) {
1277
+ entries.push(skip(id, "retention-disabled"));
1278
+ continue;
1279
+ }
1280
+ if (id === config.currentSessionId) {
1281
+ entries.push(skip(id, "current"));
1282
+ continue;
1283
+ }
1284
+ if (config.stagedIds?.has(id) === true) {
1285
+ entries.push(skip(id, "staged"));
1286
+ continue;
1287
+ }
1288
+ if (row.agentAvailable === true) {
1289
+ entries.push(skip(id, "agent-available"));
1290
+ continue;
1291
+ }
1292
+ if (typeof row.agentAvailable !== "boolean") {
1293
+ entries.push(skip(id, "field-anomaly"));
1294
+ continue;
1295
+ }
1296
+ if (row.running === true) {
1297
+ entries.push(skip(id, "running"));
1298
+ continue;
1299
+ }
1300
+ if (row.running !== false) {
1301
+ entries.push(skip(id, "field-anomaly"));
1302
+ continue;
1303
+ }
1304
+ if (typeof row.blank !== "boolean") {
1305
+ entries.push(skip(id, "field-anomaly"));
1306
+ continue;
1307
+ }
1308
+ const updatedAt = row.updatedAt;
1309
+ if (updatedAt === undefined || updatedAt === null) {
1310
+ entries.push(skip(id, "missing-time"));
1311
+ continue;
1312
+ }
1313
+ if (typeof updatedAt !== "number" || !Number.isFinite(updatedAt)) {
1314
+ entries.push(skip(id, "field-anomaly"));
1315
+ continue;
1316
+ }
1317
+ if (updatedAt > now) {
1318
+ entries.push(skip(id, "future-time"));
1319
+ continue;
1320
+ }
1321
+ if (hasRunningDescendant(id, rows)) {
1322
+ entries.push(skip(id, "subtree-running"));
1323
+ continue;
1324
+ }
1325
+ let snapshot;
1326
+ try {
1327
+ snapshot = await persistence.stat(id);
1328
+ } catch {
1329
+ snapshot = undefined;
1330
+ }
1331
+ if (snapshot === undefined || snapshot === null) {
1332
+ entries.push(skip(id, "unknown"));
1333
+ continue;
1334
+ }
1335
+ if (snapshot.header?.id !== id) {
1336
+ entries.push(skip(id, "header-mismatch"));
1337
+ continue;
1338
+ }
1339
+ const path = locationPath(snapshot.location);
1340
+ if (path === undefined) {
1341
+ entries.push(skip(id, "no-location"));
1342
+ continue;
1343
+ }
1344
+ const sessionDir = dirname(path);
1345
+ if (basename(sessionDir) !== encodeSegment(id)) {
1346
+ entries.push(skip(id, "basename-mismatch", path));
1347
+ continue;
1348
+ }
1349
+ try {
1350
+ const st = await fs.lstat(sessionDir);
1351
+ if (!st.isDirectory() || st.isSymbolicLink?.() === true) {
1352
+ entries.push(skip(id, "not-directory", path));
1353
+ continue;
1354
+ }
1355
+ } catch {
1356
+ entries.push(skip(id, "not-directory", path));
1357
+ continue;
1358
+ }
1359
+ try {
1360
+ const real = await fs.realpath(sessionDir);
1361
+ if (!isInside(rootReal, real)) {
1362
+ entries.push(skip(id, "escaped-root", path));
1363
+ continue;
1364
+ }
1365
+ } catch {
1366
+ entries.push(skip(id, "escaped-root", path));
1367
+ continue;
1368
+ }
1369
+ const lockPath = join2(sessionDir, "session.lock");
1370
+ try {
1371
+ const lockStat = await fs.stat(lockPath);
1372
+ const mtime = lockStat.mtimeMs;
1373
+ if (typeof mtime === "number" && Number.isFinite(mtime) && now - mtime < config.lockGraceMs) {
1374
+ entries.push(skip(id, "lock-fresh", path));
1375
+ continue;
1376
+ }
1377
+ } catch (err) {
1378
+ const code = err?.code;
1379
+ if (code !== "ENOENT") {
1380
+ entries.push(skip(id, "unknown", path));
1381
+ continue;
1382
+ }
1383
+ }
1384
+ if (typeof fs.lockProbe === "function") {
1385
+ let probe;
1386
+ try {
1387
+ probe = await fs.lockProbe(lockPath);
1388
+ } catch {
1389
+ probe = { status: "unknown", detail: "probe-threw" };
1390
+ }
1391
+ if (probe.status === "lock-held") {
1392
+ entries.push(skip(id, "lock-held", path));
1393
+ continue;
1394
+ }
1395
+ if (probe.status === "unknown") {
1396
+ entries.push(skip(id, "unknown", path));
1397
+ continue;
1398
+ }
1399
+ }
1400
+ const freshGrace = typeof config.freshMtimeGraceMs === "number" && Number.isFinite(config.freshMtimeGraceMs) && config.freshMtimeGraceMs > 0 ? config.freshMtimeGraceMs : 0;
1401
+ if (freshGrace > 0) {
1402
+ try {
1403
+ const artifactStat = await fs.stat(path);
1404
+ const artifactMtime = artifactStat.mtimeMs;
1405
+ if (typeof artifactMtime === "number" && Number.isFinite(artifactMtime) && now - artifactMtime < freshGrace) {
1406
+ entries.push(skip(id, "fresh-mtime", path));
1407
+ continue;
1408
+ }
1409
+ } catch {
1410
+ entries.push(skip(id, "unknown", path));
1411
+ continue;
1412
+ }
1413
+ }
1414
+ const ageDays = (now - updatedAt) / MS_PER_DAY;
1415
+ const threshold = config.retentionDays + (row.blank === true ? config.blankGraceDays : 0);
1416
+ if (ageDays < threshold) {
1417
+ entries.push(skip(id, row.blank === true ? "blank-grace" : "within-retention", path, ageDays));
1418
+ continue;
1419
+ }
1420
+ entries.push({ sessionId: id, decision: "prune", location: path, ageDays });
1421
+ }
1422
+ const byReason = {};
1423
+ let prune = 0;
1424
+ let skipped = 0;
1425
+ for (const entry of entries) {
1426
+ if (entry.decision === "prune") {
1427
+ prune += 1;
1428
+ } else {
1429
+ skipped += 1;
1430
+ const reason = entry.reason ?? "unknown";
1431
+ byReason[reason] = (byReason[reason] ?? 0) + 1;
1432
+ }
1433
+ }
1434
+ return {
1435
+ generatedAt: now,
1436
+ retentionDays: config.retentionDays,
1437
+ entries,
1438
+ counts: { prune, skip: skipped, byReason }
1439
+ };
1440
+ }
1441
+
1442
+ // ../bridge/src/prune-lock-probe.ts
1443
+ import { realpathSync } from "node:fs";
1444
+ import { open, stat as fsStat } from "node:fs/promises";
1445
+ import { createRequire } from "node:module";
1446
+ var defaultIo = {
1447
+ open(path) {
1448
+ return open(path, "r");
1449
+ },
1450
+ stat(path) {
1451
+ return fsStat(path);
1452
+ }
1453
+ };
1454
+ function errorCode(err) {
1455
+ if (err === null || typeof err !== "object")
1456
+ return;
1457
+ const code = err.code;
1458
+ return typeof code === "string" ? code : undefined;
1459
+ }
1460
+ var cachedTryLockExclusive;
1461
+ var resolved = false;
1462
+ function resolveFlockTryLockExclusive(extraRoots = []) {
1463
+ if (extraRoots.length === 0 && resolved)
1464
+ return cachedTryLockExclusive;
1465
+ const roots = [...extraRoots, import.meta.url];
1466
+ if (process.argv[1]) {
1467
+ try {
1468
+ roots.push(realpathSync(process.argv[1]));
1469
+ } catch {}
1470
+ }
1471
+ let found;
1472
+ for (const root of roots) {
1473
+ try {
1474
+ const req = createRequire(root);
1475
+ const mod = req("@deepseek-ai/node-addon-system/flock");
1476
+ const fn = mod.tryLockExclusive;
1477
+ if (typeof fn === "function") {
1478
+ found = fn;
1479
+ break;
1480
+ }
1481
+ } catch {}
1482
+ }
1483
+ if (extraRoots.length === 0) {
1484
+ resolved = true;
1485
+ cachedTryLockExclusive = found;
1486
+ }
1487
+ return found;
1488
+ }
1489
+ function createPruneLockProbe(tryLockExclusive, io = defaultIo) {
1490
+ return async (lockPath) => {
1491
+ let handle;
1492
+ try {
1493
+ try {
1494
+ handle = await io.open(lockPath, "r");
1495
+ } catch (err) {
1496
+ const code = errorCode(err);
1497
+ return code === "ENOENT" || code === "ENOTDIR" ? { status: "no-lock", detail: code } : { status: "unknown", detail: code ?? "open-failed" };
1498
+ }
1499
+ try {
1500
+ await tryLockExclusive(handle.fd);
1501
+ } catch (err) {
1502
+ const code = errorCode(err);
1503
+ if (code === "EAGAIN" || code === "EWOULDBLOCK")
1504
+ return { status: "lock-held", detail: code };
1505
+ if (code === "ENOENT" || code === "ENOTDIR")
1506
+ return { status: "no-lock", detail: code };
1507
+ return { status: "unknown", detail: code ?? "flock-failed" };
1508
+ }
1509
+ try {
1510
+ const opened = await handle.stat();
1511
+ const current = await io.stat(lockPath);
1512
+ if (opened.dev !== current.dev || opened.ino !== current.ino) {
1513
+ return { status: "unknown", detail: "lock-file-replaced" };
1514
+ }
1515
+ } catch (err) {
1516
+ return { status: "unknown", detail: errorCode(err) ?? "stat-failed" };
1517
+ }
1518
+ return { status: "unlocked" };
1519
+ } finally {
1520
+ if (handle !== undefined) {
1521
+ try {
1522
+ await handle.close();
1523
+ } catch {}
1524
+ }
1525
+ }
1526
+ };
1527
+ }
1528
+
1529
+ // ../bridge/src/session-prune-apply.ts
1530
+ import { createHash } from "node:crypto";
1531
+ import { basename as basename2, dirname as dirname2, join as join3, sep as sep2 } from "node:path";
1532
+ class ApplyError extends Error {
1533
+ code;
1534
+ detail;
1535
+ constructor(code, message, detail) {
1536
+ super(message);
1537
+ this.name = "ApplyError";
1538
+ this.code = code;
1539
+ this.detail = detail;
1540
+ }
1541
+ }
1542
+ function fail(code, message, detail) {
1543
+ throw new ApplyError(code, message, detail);
1544
+ }
1545
+ function errorCode2(err) {
1546
+ if (err === null || typeof err !== "object")
1547
+ return;
1548
+ const code = err.code;
1549
+ return typeof code === "string" ? code : undefined;
1550
+ }
1551
+ function isEnoent(err) {
1552
+ return errorCode2(err) === "ENOENT";
1553
+ }
1554
+ function sha256(text) {
1555
+ return createHash("sha256").update(text, "utf8").digest("hex");
1556
+ }
1557
+ function computeConfigFingerprint(policy) {
1558
+ return sha256(JSON.stringify([
1559
+ policy.retentionDays,
1560
+ policy.blankGraceDays,
1561
+ policy.lockGraceMs,
1562
+ policy.freshMtimeGraceMs,
1563
+ policy.sessionsRoot
1564
+ ]));
1565
+ }
1566
+ function computePlanFingerprint(plan) {
1567
+ const canonical = JSON.stringify({
1568
+ retentionDays: plan.retentionDays,
1569
+ entries: plan.entries.map((e) => [
1570
+ e.sessionId,
1571
+ e.decision,
1572
+ e.reason ?? "",
1573
+ e.location ?? ""
1574
+ ]),
1575
+ counts: plan.counts
1576
+ });
1577
+ return sha256(canonical);
1578
+ }
1579
+ function utcStamp(now) {
1580
+ return new Date(now).toISOString().replace(/[:.]/g, "-");
1581
+ }
1582
+ function trashRoot(dshHome) {
1583
+ return join3(dshHome, "trash");
1584
+ }
1585
+ function trashSessionsRoot(dshHome) {
1586
+ return join3(trashRoot(dshHome), "sessions");
1587
+ }
1588
+ function trashJournalRoot(dshHome) {
1589
+ return join3(trashRoot(dshHome), "journal");
1590
+ }
1591
+ function isInside2(root, target) {
1592
+ const base = root.length > 1 && root.endsWith(sep2) ? root.slice(0, -1) : root;
1593
+ return target === base || target.startsWith(base.endsWith(sep2) ? base : base + sep2);
1594
+ }
1595
+ function sameDev(a, b) {
1596
+ return a !== undefined && b !== undefined && String(a) === String(b);
1597
+ }
1598
+ async function pathExists(fs, path) {
1599
+ try {
1600
+ await fs.lstat(path);
1601
+ return true;
1602
+ } catch (err) {
1603
+ if (isEnoent(err))
1604
+ return false;
1605
+ throw err;
1606
+ }
1607
+ }
1608
+ var APPLY_WIRE_MSG = {
1609
+ STALE_PLAN: "apply refused: the plan is stale",
1610
+ BAD_PARAMS: "apply refused: invalid parameters",
1611
+ BAD_PATH: "apply refused: an unsafe path was rejected",
1612
+ EXDEV: "apply refused: cross-device rename",
1613
+ CONFLICT: "apply refused: destination already exists",
1614
+ LOCKED: "apply refused: session.lock is held or unknown",
1615
+ ROLLED_BACK: "apply reversed the rename because session.lock was held at trash",
1616
+ ROLLBACK_FAILED: "apply failed and the reverse rename also failed",
1617
+ JOURNAL_FAILED: "apply reversed the rename after a journal write failed",
1618
+ NO_RECOVERY: "apply refused: no recovery path is available",
1619
+ INTERNAL: "apply failed: internal error"
1620
+ };
1621
+ function applyWireMessage(err) {
1622
+ const code = err instanceof ApplyError ? err.code : "INTERNAL";
1623
+ return APPLY_WIRE_MSG[code];
1624
+ }
1625
+ async function writeAppliedMarker(fs, path, record) {
1626
+ const data = JSON.stringify(record);
1627
+ try {
1628
+ await fs.writeFile(path, data, { flag: "wx", mode: 384 });
1629
+ return;
1630
+ } catch (err) {
1631
+ if (errorCode2(err) !== "EEXIST")
1632
+ throw err;
1633
+ }
1634
+ let existing;
1635
+ try {
1636
+ existing = JSON.parse(await fs.readFile(path));
1637
+ } catch {
1638
+ fail("JOURNAL_FAILED", "existing applied marker is not readable JSON", { id: record.id });
1639
+ }
1640
+ if (existing === null || typeof existing !== "object") {
1641
+ fail("JOURNAL_FAILED", "existing applied marker is not an object", { id: record.id });
1642
+ }
1643
+ const marker = existing;
1644
+ if (marker.id !== record.id || marker.to !== record.to) {
1645
+ fail("JOURNAL_FAILED", "existing applied marker identity mismatch", { id: record.id });
1646
+ }
1647
+ }
1648
+ async function probeLock(probe, lockPath) {
1649
+ if (probe === undefined)
1650
+ return;
1651
+ let result;
1652
+ try {
1653
+ result = await probe(lockPath);
1654
+ } catch {
1655
+ fail("LOCKED", "lock probe threw; refusing to move a session", { lockPath });
1656
+ }
1657
+ if (result.status === "lock-held" || result.status === "unknown") {
1658
+ fail("LOCKED", "session.lock probe is not unlocked", { lockPath, status: result.status, detail: result.detail });
1659
+ }
1660
+ }
1661
+ async function validateRollbackManifest(fs, journalBase, id, sourceDir, trashPath) {
1662
+ let raw;
1663
+ try {
1664
+ raw = JSON.parse(await fs.readFile(`${journalBase}.pre.json`));
1665
+ } catch {
1666
+ fail("BAD_PATH", "rollback refused: no valid pre-rename journal", { id });
1667
+ }
1668
+ if (raw === null || typeof raw !== "object")
1669
+ fail("BAD_PATH", "rollback refused: pre-rename journal is not an object", { id });
1670
+ const proof = raw;
1671
+ if (proof.id !== id || proof.sourceDir !== sourceDir || proof.trashPath !== trashPath) {
1672
+ fail("BAD_PATH", "rollback refused: pre-rename journal identity mismatch", { id });
1673
+ }
1674
+ }
1675
+ async function restoreFromTrash(fs, options) {
1676
+ if (await pathExists(fs, options.sourceDir)) {
1677
+ fail("CONFLICT", "restore refused: source path already exists", { id: options.id });
1678
+ }
1679
+ let st;
1680
+ try {
1681
+ st = await fs.lstat(options.trashPath);
1682
+ } catch (err) {
1683
+ fail("BAD_PATH", "restore refused: trash entry is not readable", { id: options.id, code: errorCode2(err) });
1684
+ }
1685
+ if (options.flippedAfterRename !== true && (!st.isDirectory() || st.isSymbolicLink?.() === true)) {
1686
+ fail("BAD_PATH", "restore refused: trash entry is not a real directory", { id: options.id });
1687
+ }
1688
+ if (options.journalBase !== undefined) {
1689
+ await validateRollbackManifest(fs, options.journalBase, options.id, options.sourceDir, options.trashPath);
1690
+ } else {
1691
+ let snapshot;
1692
+ try {
1693
+ snapshot = await options.persistence.stat(options.id);
1694
+ } catch {
1695
+ snapshot = undefined;
1696
+ }
1697
+ if (snapshot?.header?.id !== options.id) {
1698
+ fail("BAD_PATH", "restore refused: header.id mismatch", { id: options.id });
1699
+ }
1700
+ }
1701
+ if (options.skipLock !== true)
1702
+ await probeLock(options.lockProbe, join3(options.trashPath, "session.lock"));
1703
+ try {
1704
+ await fs.rename(options.trashPath, options.sourceDir);
1705
+ } catch (err) {
1706
+ if (errorCode2(err) === "EXDEV")
1707
+ fail("EXDEV", "restore refused: cross-device rename", { id: options.id });
1708
+ throw err;
1709
+ }
1710
+ }
1711
+ async function rollbackAfterRename(fs, deps, options) {
1712
+ const markerPath = join3(options.trashPath, ".applied.json");
1713
+ if (await pathExists(fs, markerPath)) {
1714
+ try {
1715
+ await fs.rename(markerPath, `${options.journalBase}.discarded.json`);
1716
+ } catch {
1717
+ fail("ROLLBACK_FAILED", APPLY_WIRE_MSG.ROLLBACK_FAILED, {
1718
+ id: options.id,
1719
+ reason: options.reason,
1720
+ cause: "applied-marker-retire-failed"
1721
+ });
1722
+ }
1723
+ }
1724
+ try {
1725
+ await restoreFromTrash(fs, {
1726
+ sourceDir: options.sourceDir,
1727
+ trashPath: options.trashPath,
1728
+ id: options.id,
1729
+ persistence: deps.persistence,
1730
+ journalBase: options.journalBase,
1731
+ lockProbe: deps.lockProbe,
1732
+ skipLock: true
1733
+ });
1734
+ } catch (rollbackErr) {
1735
+ const causeMessage = options.cause instanceof Error ? options.cause.message : String(options.cause);
1736
+ const rollbackMessage = rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr);
1737
+ fail("ROLLBACK_FAILED", APPLY_WIRE_MSG.ROLLBACK_FAILED, {
1738
+ id: options.id,
1739
+ reason: options.reason,
1740
+ cause: causeMessage,
1741
+ rollback: rollbackMessage
1742
+ });
1743
+ }
1744
+ try {
1745
+ await fs.writeFile(`${options.journalBase}.rollback.json`, JSON.stringify({
1746
+ opId: deps.opId,
1747
+ phase: "rolled-back",
1748
+ id: options.id,
1749
+ sourceDir: options.sourceDir,
1750
+ trashPath: options.trashPath,
1751
+ planFingerprint: options.planFingerprint,
1752
+ reason: options.reason
1753
+ }), { flag: "wx", mode: 384 });
1754
+ } catch {}
1755
+ }
1756
+ async function recoverTrashOrphans(fs, dshHome) {
1757
+ const runsRoot = trashSessionsRoot(dshHome);
1758
+ let runs;
1759
+ try {
1760
+ runs = await fs.readdir(runsRoot);
1761
+ } catch (err) {
1762
+ if (isEnoent(err))
1763
+ return [];
1764
+ throw err;
1765
+ }
1766
+ const marked = [];
1767
+ for (const run of runs) {
1768
+ let entries;
1769
+ try {
1770
+ entries = await fs.readdir(join3(runsRoot, run));
1771
+ } catch (err) {
1772
+ if (isEnoent(err))
1773
+ continue;
1774
+ throw err;
1775
+ }
1776
+ for (const entry of entries) {
1777
+ if (entry.startsWith("."))
1778
+ continue;
1779
+ const entryDir = join3(runsRoot, run, entry);
1780
+ try {
1781
+ const st = await fs.lstat(entryDir);
1782
+ if (!st.isDirectory() || st.isSymbolicLink?.() === true)
1783
+ continue;
1784
+ } catch {
1785
+ continue;
1786
+ }
1787
+ if (await pathExists(fs, join3(entryDir, ".applied.json")))
1788
+ continue;
1789
+ const marker = join3(entryDir, ".orphan.json");
1790
+ try {
1791
+ await fs.writeFile(marker, JSON.stringify({ markedAt: Date.now(), reason: "no-applied-manifest", path: entryDir }), { flag: "wx", mode: 384 });
1792
+ marked.push(entryDir);
1793
+ } catch (err) {
1794
+ if (errorCode2(err) !== "EEXIST")
1795
+ throw err;
1796
+ }
1797
+ }
1798
+ }
1799
+ return marked;
1800
+ }
1801
+ async function applyTrashPlan(fs, deps, plan, config) {
1802
+ return deps.withApplyLock(async () => {
1803
+ const trashBase = trashRoot(config.dshHome);
1804
+ const sessionsTrash = trashSessionsRoot(config.dshHome);
1805
+ const journalDir = trashJournalRoot(config.dshHome);
1806
+ await fs.mkdir(trashBase, { recursive: true, mode: 448 });
1807
+ await fs.mkdir(sessionsTrash, { recursive: true, mode: 448 });
1808
+ await fs.mkdir(journalDir, { recursive: true, mode: 448 });
1809
+ const runDir = join3(sessionsTrash, utcStamp(deps.now));
1810
+ await fs.mkdir(runDir, { mode: 448 });
1811
+ const applied = [];
1812
+ const failed = [];
1813
+ let roots;
1814
+ try {
1815
+ const rootReal = await fs.realpath(config.sessionsRoot);
1816
+ const rootStat = await fs.stat(config.sessionsRoot);
1817
+ const trashStat = await fs.stat(runDir);
1818
+ if (!sameDev(rootStat.dev, trashStat.dev)) {
1819
+ fail("EXDEV", "sessions root and trash are on different devices", { sessionsRoot: config.sessionsRoot, runDir });
1820
+ }
1821
+ roots = { rootReal, trashStat };
1822
+ } catch (err) {
1823
+ const code = err instanceof ApplyError ? err.code : "INTERNAL";
1824
+ const message = applyWireMessage(err);
1825
+ const ids = plan.entries.filter((entry) => entry.decision === "prune").map((entry) => entry.sessionId);
1826
+ for (const id of ids.length > 0 ? ids : ["<root>"])
1827
+ failed.push({ id, code, message });
1828
+ return { opId: deps.opId, runDir, applied, failed, markedOrphans: [] };
1829
+ }
1830
+ const { rootReal, trashStat } = roots;
1831
+ const markedOrphans = await recoverTrashOrphans(fs, config.dshHome);
1832
+ for (const entry of plan.entries) {
1833
+ if (entry.decision !== "prune")
1834
+ continue;
1835
+ const id = entry.sessionId;
1836
+ const encoded = encodeSegment(id);
1837
+ const journalBase = join3(journalDir, `${deps.opId}-${encoded}`);
1838
+ try {
1839
+ const snapshot = await deps.persistence.stat(id);
1840
+ if (snapshot?.header?.id !== id)
1841
+ fail("BAD_PATH", "header.id mismatch", { id });
1842
+ const location = snapshot.location;
1843
+ const locationPath = typeof location === "string" ? location : location !== null && typeof location === "object" && typeof location.path === "string" ? location.path : undefined;
1844
+ if (locationPath === undefined || locationPath === "")
1845
+ fail("BAD_PATH", "no host location", { id });
1846
+ const sourceDir = dirname2(locationPath);
1847
+ if (basename2(sourceDir) !== encoded)
1848
+ fail("BAD_PATH", "basename/encodeSegment mismatch", { id, sourceDir });
1849
+ const st = await fs.lstat(sourceDir);
1850
+ if (!st.isDirectory() || st.isSymbolicLink?.() === true)
1851
+ fail("BAD_PATH", "not a real directory", { id, sourceDir });
1852
+ const real = await fs.realpath(sourceDir);
1853
+ if (!isInside2(rootReal, real))
1854
+ fail("BAD_PATH", "source escaped sessions root", { id, sourceDir, real });
1855
+ const sourceStat = await fs.stat(sourceDir);
1856
+ if (!sameDev(sourceStat.dev, trashStat.dev))
1857
+ fail("EXDEV", "cross-device rename refused", { id, sourceDir, runDir });
1858
+ await probeLock(deps.lockProbe, join3(sourceDir, "session.lock"));
1859
+ const trashPath = join3(runDir, encoded);
1860
+ if (await pathExists(fs, trashPath))
1861
+ fail("CONFLICT", "trash destination exists; refusing to overwrite", { id, trashPath });
1862
+ const recheckSt = await fs.lstat(sourceDir);
1863
+ if (!recheckSt.isDirectory() || recheckSt.isSymbolicLink?.() === true) {
1864
+ fail("BAD_PATH", "source flipped to symlink/non-directory before rename", { id, sourceDir });
1865
+ }
1866
+ const recheckReal = await fs.realpath(sourceDir);
1867
+ if (!isInside2(rootReal, recheckReal)) {
1868
+ fail("BAD_PATH", "source escaped sessions root before rename", { id, sourceDir, real: recheckReal });
1869
+ }
1870
+ const recheckStat = await fs.stat(sourceDir);
1871
+ if (!sameDev(recheckStat.dev, trashStat.dev)) {
1872
+ fail("EXDEV", "cross-device rename refused at second check", { id, sourceDir, runDir });
1873
+ }
1874
+ const recheckSnapshot = await deps.persistence.stat(id);
1875
+ if (recheckSnapshot?.header?.id !== id)
1876
+ fail("BAD_PATH", "header.id mismatch before rename", { id });
1877
+ await fs.writeFile(`${journalBase}.pre.json`, JSON.stringify({
1878
+ opId: deps.opId,
1879
+ phase: "pre-rename",
1880
+ id,
1881
+ sourceDir,
1882
+ trashPath,
1883
+ planFingerprint: config.planFingerprint,
1884
+ generatedAt: deps.now
1885
+ }), { flag: "wx", mode: 384 });
1886
+ try {
1887
+ await fs.rename(sourceDir, trashPath);
1888
+ } catch (err) {
1889
+ if (errorCode2(err) === "EXDEV")
1890
+ fail("EXDEV", "rename returned EXDEV; no copy fallback", { id, sourceDir, trashPath });
1891
+ throw err;
1892
+ }
1893
+ let movedSt;
1894
+ try {
1895
+ movedSt = await fs.lstat(trashPath);
1896
+ } catch (err) {
1897
+ fail("BAD_PATH", "moved entry is not readable at trash path", { id, trashPath, code: errorCode2(err) });
1898
+ }
1899
+ if (!movedSt.isDirectory() || movedSt.isSymbolicLink?.() === true) {
1900
+ await restoreFromTrash(fs, {
1901
+ sourceDir,
1902
+ trashPath,
1903
+ id,
1904
+ persistence: deps.persistence,
1905
+ journalBase,
1906
+ lockProbe: deps.lockProbe,
1907
+ skipLock: true,
1908
+ flippedAfterRename: true
1909
+ });
1910
+ await fs.writeFile(`${journalBase}.rollback.json`, JSON.stringify({
1911
+ opId: deps.opId,
1912
+ phase: "rolled-back",
1913
+ id,
1914
+ sourceDir,
1915
+ trashPath,
1916
+ planFingerprint: config.planFingerprint,
1917
+ reason: "flipped-to-symlink-or-non-directory"
1918
+ }), { flag: "wx", mode: 384 });
1919
+ fail("BAD_PATH", "moved entry flipped to symlink/non-directory; reversed rename", { id, trashPath });
1920
+ }
1921
+ let heldAtTrash = false;
1922
+ try {
1923
+ await probeLock(deps.lockProbe, join3(trashPath, "session.lock"));
1924
+ } catch (err) {
1925
+ heldAtTrash = true;
1926
+ if (!(err instanceof ApplyError) || err.code !== "LOCKED")
1927
+ throw err;
1928
+ }
1929
+ if (heldAtTrash) {
1930
+ await restoreFromTrash(fs, {
1931
+ sourceDir,
1932
+ trashPath,
1933
+ id,
1934
+ persistence: deps.persistence,
1935
+ journalBase,
1936
+ lockProbe: deps.lockProbe,
1937
+ skipLock: true
1938
+ });
1939
+ await fs.writeFile(`${journalBase}.rollback.json`, JSON.stringify({
1940
+ opId: deps.opId,
1941
+ phase: "rolled-back",
1942
+ id,
1943
+ sourceDir,
1944
+ trashPath,
1945
+ planFingerprint: config.planFingerprint
1946
+ }), { flag: "wx", mode: 384 });
1947
+ fail("ROLLED_BACK", "lock held/unknown at trash path; reversed rename", { id, trashPath });
1948
+ }
1949
+ const appliedRecord = {
1950
+ opId: deps.opId,
1951
+ phase: "applied",
1952
+ id,
1953
+ from: sourceDir,
1954
+ to: trashPath,
1955
+ planFingerprint: config.planFingerprint,
1956
+ appliedAt: deps.now
1957
+ };
1958
+ try {
1959
+ await fs.writeFile(`${journalBase}.post.json`, JSON.stringify(appliedRecord), { flag: "wx", mode: 384 });
1960
+ await fs.appendFile(join3(runDir, "manifest.jsonl"), JSON.stringify(appliedRecord) + `
1961
+ `);
1962
+ await writeAppliedMarker(fs, join3(trashPath, ".applied.json"), appliedRecord);
1963
+ } catch (journalErr) {
1964
+ await rollbackAfterRename(fs, deps, {
1965
+ sourceDir,
1966
+ trashPath,
1967
+ id,
1968
+ journalBase,
1969
+ planFingerprint: config.planFingerprint,
1970
+ cause: journalErr,
1971
+ reason: "post-rename-journal-write-failed"
1972
+ });
1973
+ fail("JOURNAL_FAILED", APPLY_WIRE_MSG.JOURNAL_FAILED, {
1974
+ id,
1975
+ cause: journalErr instanceof Error ? journalErr.message : String(journalErr)
1976
+ });
1977
+ }
1978
+ applied.push({ id, from: sourceDir, to: trashPath });
1979
+ } catch (err) {
1980
+ const code = err instanceof ApplyError ? err.code : "INTERNAL";
1981
+ const message = applyWireMessage(err);
1982
+ failed.push({ id, code, message });
1983
+ }
1984
+ }
1985
+ return { opId: deps.opId, runDir, applied, failed, markedOrphans };
1986
+ });
1987
+ }
1988
+
1989
+ // ../bridge/src/session-prune-purge.ts
1990
+ import { createHash as createHash2, createHmac, timingSafeEqual } from "node:crypto";
1991
+ import { zstdDecompressSync as nodeZstdDecompressSync } from "node:zlib";
1992
+ import { basename as basename3, isAbsolute, join as join4, relative, sep as sep3 } from "node:path";
1993
+ var MS_PER_DAY2 = 86400000;
1994
+ var DEFAULT_PURGE_RETENTION_DAYS = 7;
1995
+
1996
+ class PurgeError extends Error {
1997
+ code;
1998
+ detail;
1999
+ constructor(code, message, detail) {
2000
+ super(message);
2001
+ this.name = "PurgeError";
2002
+ this.code = code;
2003
+ this.detail = detail;
2004
+ }
2005
+ }
2006
+ function fail2(code, message, detail) {
2007
+ throw new PurgeError(code, message, detail);
2008
+ }
2009
+ function purgeWireMessage(err) {
2010
+ return err instanceof PurgeError ? err.message : "purge entry could not be processed";
2011
+ }
2012
+ function errorCode3(err) {
2013
+ if (err === null || typeof err !== "object")
2014
+ return;
2015
+ const code = err.code;
2016
+ return typeof code === "string" ? code : undefined;
2017
+ }
2018
+ function sha2562(text) {
2019
+ return createHash2("sha256").update(text, "utf8").digest("hex");
2020
+ }
2021
+ function isInside3(root, target) {
2022
+ const base = root.length > 1 && root.endsWith(sep3) ? root.slice(0, -1) : root;
2023
+ return target === base || target.startsWith(base.endsWith(sep3) ? base : base + sep3);
2024
+ }
2025
+ function canonicalTokenPayload(p) {
2026
+ return JSON.stringify([
2027
+ p.v,
2028
+ p.opId,
2029
+ [...p.ids],
2030
+ [...p.paths],
2031
+ p.root,
2032
+ p.retentionDays,
2033
+ p.issuedAt,
2034
+ p.expiresAt,
2035
+ p.nonce
2036
+ ]);
2037
+ }
2038
+ function issuePurgeToken(input, secret, ttlMs) {
2039
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0)
2040
+ fail2("BAD_PARAMS", "tokenTtlMs must be positive");
2041
+ const payload = {
2042
+ ...input,
2043
+ v: 1,
2044
+ expiresAt: input.issuedAt + ttlMs
2045
+ };
2046
+ const body = Buffer.from(canonicalTokenPayload(payload), "utf8").toString("base64url");
2047
+ const sig = createHmac("sha256", secret).update(body).digest("hex");
2048
+ return { token: `${body}.${sig}`, payload };
2049
+ }
2050
+ function verifyPurgeToken(token, secret, now) {
2051
+ if (typeof token !== "string" || token === "")
2052
+ fail2("BAD_TOKEN", "purge requires a server-issued token");
2053
+ const parts = token.split(".");
2054
+ if (parts.length !== 2 || parts[0] === "" || parts[1] === "")
2055
+ fail2("BAD_TOKEN", "malformed purge token");
2056
+ const expected = createHmac("sha256", secret).update(parts[0]).digest();
2057
+ const actual = Buffer.from(parts[1], "hex");
2058
+ if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
2059
+ fail2("BAD_TOKEN", "purge token signature mismatch");
2060
+ }
2061
+ let raw = undefined;
2062
+ try {
2063
+ raw = JSON.parse(Buffer.from(parts[0], "base64url").toString("utf8"));
2064
+ } catch {}
2065
+ if (!Array.isArray(raw) || raw.length !== 9 || raw[0] !== 1)
2066
+ fail2("BAD_TOKEN", "purge token payload shape mismatch");
2067
+ const [v, opId, ids, paths, root, retentionDays, issuedAt, expiresAt, nonce] = raw;
2068
+ if (typeof opId !== "string" || !Array.isArray(ids) || !Array.isArray(paths) || ids.some((id) => typeof id !== "string") || paths.some((p) => typeof p !== "string") || ids.length !== paths.length || typeof root !== "string" || typeof retentionDays !== "number" || typeof issuedAt !== "number" || typeof expiresAt !== "number" || typeof nonce !== "string") {
2069
+ fail2("BAD_TOKEN", "purge token payload fields are invalid");
2070
+ }
2071
+ if (!Number.isFinite(issuedAt) || !Number.isFinite(expiresAt))
2072
+ fail2("BAD_TOKEN", "purge token timestamps are invalid");
2073
+ if (issuedAt > now + 1000)
2074
+ fail2("STALE_TOKEN", "purge token issued in the future");
2075
+ if (now >= expiresAt)
2076
+ fail2("STALE_TOKEN", "purge token expired");
2077
+ return { v: 1, opId, ids, paths, root, retentionDays, issuedAt, expiresAt, nonce };
2078
+ }
2079
+ async function resolvePurgeSecret(fs, dshHome, newSecret) {
2080
+ const path = join4(trashRoot(dshHome), ".purge.secret");
2081
+ try {
2082
+ const value = (await fs.readFile(path)).trim();
2083
+ if (value !== "")
2084
+ return value;
2085
+ fail2("INTERNAL", "purge secret file is empty");
2086
+ } catch (err) {
2087
+ if (err instanceof PurgeError)
2088
+ throw err;
2089
+ if (errorCode3(err) !== "ENOENT")
2090
+ throw err;
2091
+ }
2092
+ await fs.mkdir(trashRoot(dshHome), { recursive: true, mode: 448 });
2093
+ try {
2094
+ await fs.writeFile(path, newSecret(), { flag: "wx", mode: 384 });
2095
+ } catch (err) {
2096
+ if (errorCode3(err) !== "EEXIST")
2097
+ throw err;
2098
+ }
2099
+ const value = (await fs.readFile(path)).trim();
2100
+ if (value === "")
2101
+ fail2("INTERNAL", "purge secret file is empty");
2102
+ return value;
2103
+ }
2104
+ function readLocationPath(location) {
2105
+ if (typeof location === "string")
2106
+ return location || undefined;
2107
+ if (location !== null && typeof location === "object" && typeof location.path === "string")
2108
+ return location.path || undefined;
2109
+ return;
2110
+ }
2111
+ var RUN_NAME_RE = /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z$/;
2112
+ var ARTIFACT_FILENAME = "session.v4.jsonl.zstd";
2113
+ var RUN_MANIFEST_FILENAME = "manifest.jsonl";
2114
+ function zstdDecompress(frame) {
2115
+ const bun = globalThis.Bun;
2116
+ if (bun?.zstdDecompressSync !== undefined)
2117
+ return bun.zstdDecompressSync(frame);
2118
+ return nodeZstdDecompressSync(frame);
2119
+ }
2120
+ async function readTrashArtifactHeaderId(fs, dir) {
2121
+ const artifact = join4(dir, ARTIFACT_FILENAME);
2122
+ let frame;
2123
+ try {
2124
+ frame = await fs.readFileBuffer(artifact);
2125
+ } catch {
2126
+ fail2("BAD_MANIFEST", "trash entry has no readable session artifact");
2127
+ }
2128
+ if (frame.length === 0)
2129
+ fail2("BAD_MANIFEST", "trash session artifact is empty");
2130
+ let text;
2131
+ try {
2132
+ text = zstdDecompress(frame).toString("utf8");
2133
+ } catch {
2134
+ fail2("BAD_MANIFEST", "trash session artifact is not a valid zstd frame");
2135
+ }
2136
+ const firstLine = text.split(`
2137
+ `, 1)[0] ?? "";
2138
+ let header;
2139
+ try {
2140
+ header = JSON.parse(firstLine);
2141
+ } catch {
2142
+ fail2("BAD_MANIFEST", "trash session artifact header is not JSON");
2143
+ }
2144
+ if (header === null || typeof header !== "object") {
2145
+ fail2("BAD_MANIFEST", "trash session artifact header is not an object");
2146
+ }
2147
+ const id = header.id;
2148
+ if (typeof id !== "string" || id === "") {
2149
+ fail2("BAD_MANIFEST", "trash artifact header.id is missing");
2150
+ }
2151
+ return id;
2152
+ }
2153
+ function parseAppliedManifest(text) {
2154
+ let raw;
2155
+ try {
2156
+ raw = JSON.parse(text);
2157
+ } catch {
2158
+ fail2("BAD_MANIFEST", "trash entry .applied.json is not JSON");
2159
+ }
2160
+ if (raw === null || typeof raw !== "object")
2161
+ fail2("BAD_MANIFEST", "trash entry .applied.json is not an object");
2162
+ const m = raw;
2163
+ if (typeof m.id !== "string" || m.id === "")
2164
+ fail2("BAD_MANIFEST", "applied manifest id is missing");
2165
+ if (typeof m.to !== "string" || m.to === "")
2166
+ fail2("BAD_MANIFEST", "applied manifest to is missing");
2167
+ if (typeof m.opId !== "string" || m.opId === "")
2168
+ fail2("BAD_MANIFEST", "applied manifest opId is missing");
2169
+ if (typeof m.appliedAt !== "number" || !Number.isFinite(m.appliedAt)) {
2170
+ fail2("BAD_MANIFEST", "applied manifest appliedAt is invalid");
2171
+ }
2172
+ return {
2173
+ id: m.id,
2174
+ to: m.to,
2175
+ ...typeof m.from === "string" && m.from !== "" ? { from: m.from } : {},
2176
+ opId: m.opId,
2177
+ appliedAt: m.appliedAt
2178
+ };
2179
+ }
2180
+ async function readRunManifestRow(fs, manifestPath, entryPath) {
2181
+ let text;
2182
+ try {
2183
+ text = await fs.readFile(manifestPath);
2184
+ } catch {
2185
+ fail2("BAD_MANIFEST", "trash entry has no in-place marker or same-run manifest");
2186
+ }
2187
+ for (const line of text.split(`
2188
+ `)) {
2189
+ if (line === "")
2190
+ continue;
2191
+ let row;
2192
+ try {
2193
+ row = JSON.parse(line);
2194
+ } catch {
2195
+ continue;
2196
+ }
2197
+ if (row === null || typeof row !== "object")
2198
+ continue;
2199
+ const r = row;
2200
+ if (r.phase !== "applied" || r.to !== entryPath)
2201
+ continue;
2202
+ return parseAppliedManifest(line);
2203
+ }
2204
+ fail2("BAD_MANIFEST", "no same-run manifest row matches this trash entry");
2205
+ }
2206
+ async function readAppliedManifest(fs, dir, runManifest) {
2207
+ let text;
2208
+ try {
2209
+ text = await fs.readFile(join4(dir, ".applied.json"));
2210
+ } catch (err) {
2211
+ if (errorCode3(err) === "ENOENT" && runManifest !== undefined)
2212
+ return readRunManifestRow(fs, runManifest, dir);
2213
+ fail2("BAD_MANIFEST", "trash entry has no readable .applied.json");
2214
+ }
2215
+ return parseAppliedManifest(text);
2216
+ }
2217
+ async function probeLockForPurge(lockProbe, lockPath) {
2218
+ if (lockProbe === undefined)
2219
+ fail2("UNSUPPORTED", "lockProbe capability unavailable; purge refuses to assume unlocked");
2220
+ let result;
2221
+ try {
2222
+ result = await lockProbe(lockPath);
2223
+ } catch {
2224
+ fail2("LOCKED", "lock probe threw; refusing to purge");
2225
+ }
2226
+ if (result.status === "lock-held" || result.status === "unknown") {
2227
+ fail2("LOCKED", "session.lock probe is not unlocked", { status: result.status });
2228
+ }
2229
+ }
2230
+ async function assessTrashEntry(fs, deps, dshHome, run, encoded, liveIds) {
2231
+ if (deps.lockProbe === undefined) {
2232
+ fail2("UNSUPPORTED", "lockProbe capability unavailable; purge refuses to assume unlocked");
2233
+ }
2234
+ if (!RUN_NAME_RE.test(run))
2235
+ fail2("BAD_PATH", "trash run directory name is not a UTC stamp", { run });
2236
+ const entryPath = join4(trashSessionsRoot(dshHome), run, encoded);
2237
+ const st = await fs.lstat(entryPath);
2238
+ if (!st.isDirectory() || st.isSymbolicLink?.() === true) {
2239
+ fail2("BAD_PATH", "trash entry is not a real directory");
2240
+ }
2241
+ const manifest = await readAppliedManifest(fs, entryPath, join4(trashSessionsRoot(dshHome), run, RUN_MANIFEST_FILENAME));
2242
+ if (encodeSegment(manifest.id) !== encoded || basename3(entryPath) !== encoded) {
2243
+ fail2("BAD_MANIFEST", "manifest id does not encode to the entry basename", { id: manifest.id });
2244
+ }
2245
+ const toRel = relative(trashSessionsRoot(dshHome), manifest.to);
2246
+ if (!isAbsolute(manifest.to) || toRel.startsWith("..") || isAbsolute(toRel)) {
2247
+ fail2("BAD_MANIFEST", "applied manifest to escapes the trash sessions root");
2248
+ }
2249
+ const expectedRel = join4(run, encoded);
2250
+ if (toRel !== expectedRel && toRel !== expectedRel.split(sep3).join("/")) {
2251
+ fail2("BAD_MANIFEST", "applied manifest to does not match the scanned entry", { expectedRel });
2252
+ }
2253
+ const trashReal = await fs.realpath(trashSessionsRoot(dshHome));
2254
+ const real = await fs.realpath(entryPath);
2255
+ if (!isInside3(trashReal, real) || relative(trashReal, real) !== expectedRel) {
2256
+ fail2("BAD_PATH", "trash entry realpath escaped the sessions trash root");
2257
+ }
2258
+ const liveState = liveIds.get(manifest.id);
2259
+ if (liveState === "LIVE_AGENT") {
2260
+ fail2("LIVE_AGENT", "purge refused: a live agent still owns this session id", { id: manifest.id });
2261
+ }
2262
+ if (liveState === "CONFLICT") {
2263
+ fail2("CONFLICT", "purge refused: session.id exists outside trash (restore conflict)", { id: manifest.id });
2264
+ }
2265
+ const artifactHeaderId = await readTrashArtifactHeaderId(fs, entryPath);
2266
+ if (artifactHeaderId !== manifest.id) {
2267
+ fail2("BAD_MANIFEST", "trash artifact header.id mismatch", { id: manifest.id, artifactHeaderId });
2268
+ }
2269
+ let liveSnapshot;
2270
+ try {
2271
+ liveSnapshot = await deps.persistence.stat(manifest.id);
2272
+ } catch {
2273
+ liveSnapshot = undefined;
2274
+ }
2275
+ const hintedPath = readLocationPath(liveSnapshot?.location);
2276
+ const originalPath = manifest.from === undefined ? undefined : join4(manifest.from, ARTIFACT_FILENAME);
2277
+ for (const livePath of [hintedPath, originalPath]) {
2278
+ if (livePath === undefined || livePath === entryPath)
2279
+ continue;
2280
+ try {
2281
+ await fs.lstat(livePath);
2282
+ fail2("CONFLICT", "purge refused: live path for this id exists again", { id: manifest.id });
2283
+ } catch (err) {
2284
+ if (err instanceof PurgeError)
2285
+ throw err;
2286
+ if (errorCode3(err) !== "ENOENT")
2287
+ throw err;
2288
+ }
2289
+ }
2290
+ const ageDays = (deps.now - manifest.appliedAt) / MS_PER_DAY2;
2291
+ if (!Number.isFinite(deps.retentionDays) || deps.retentionDays < 0) {
2292
+ fail2("BAD_PARAMS", "host purge retentionDays is invalid");
2293
+ }
2294
+ if (ageDays < deps.retentionDays) {
2295
+ fail2("FRESH", "trash entry has not served the residence window", { id: manifest.id, ageDays, retentionDays: deps.retentionDays });
2296
+ }
2297
+ await probeLockForPurge(deps.lockProbe, join4(entryPath, "session.lock"));
2298
+ return {
2299
+ id: manifest.id,
2300
+ encoded,
2301
+ run,
2302
+ path: real,
2303
+ appliedAt: manifest.appliedAt,
2304
+ ageDays,
2305
+ manifest
2306
+ };
2307
+ }
2308
+ async function readLiveIds(deps) {
2309
+ const listing = await listAllSessions(deps.lister);
2310
+ if (listing.truncated)
2311
+ fail2("BLOCKED", "purge aborted: session.list roster is incomplete", { pages: listing.pages });
2312
+ const ids = new Map;
2313
+ for (const row of listing.rows) {
2314
+ const raw = row.sessionId;
2315
+ if (raw === undefined || raw === null)
2316
+ continue;
2317
+ const id = String(raw);
2318
+ if (row.agentAvailable === true) {
2319
+ ids.set(id, "LIVE_AGENT");
2320
+ } else if (!ids.has(id)) {
2321
+ ids.set(id, "CONFLICT");
2322
+ }
2323
+ }
2324
+ return ids;
2325
+ }
2326
+ async function scanPurgeCandidates(fs, deps, dshHome, liveIds) {
2327
+ const root = trashSessionsRoot(dshHome);
2328
+ let runs;
2329
+ try {
2330
+ runs = await fs.readdir(root);
2331
+ } catch (err) {
2332
+ if (errorCode3(err) === "ENOENT")
2333
+ return { candidates: [], rejected: [] };
2334
+ throw err;
2335
+ }
2336
+ const candidates = [];
2337
+ const rejected = [];
2338
+ for (const run of runs) {
2339
+ let entries;
2340
+ try {
2341
+ entries = await fs.readdir(join4(root, run));
2342
+ } catch (err) {
2343
+ if (errorCode3(err) === "ENOENT")
2344
+ continue;
2345
+ rejected.push({ path: join4(root, run), code: "INTERNAL", message: purgeWireMessage(err) });
2346
+ continue;
2347
+ }
2348
+ for (const encoded of entries) {
2349
+ if (encoded.startsWith(".") || encoded === RUN_MANIFEST_FILENAME)
2350
+ continue;
2351
+ try {
2352
+ candidates.push(await assessTrashEntry(fs, deps, dshHome, run, encoded, liveIds));
2353
+ } catch (err) {
2354
+ rejected.push({
2355
+ path: join4(root, run, encoded),
2356
+ code: err instanceof PurgeError ? err.code : "INTERNAL",
2357
+ message: purgeWireMessage(err)
2358
+ });
2359
+ }
2360
+ }
2361
+ }
2362
+ candidates.sort((a, b) => a.id.localeCompare(b.id));
2363
+ return { candidates, rejected };
2364
+ }
2365
+ async function removeNode(fs, path, rootReal) {
2366
+ const st = await fs.lstat(path);
2367
+ if (st.isSymbolicLink?.() === true) {
2368
+ await fs.unlink(path);
2369
+ return;
2370
+ }
2371
+ if (st.isDirectory()) {
2372
+ const real = await fs.realpath(path);
2373
+ if (!isInside3(rootReal, real))
2374
+ fail2("BAD_PATH", "delete target escaped the trash session directory");
2375
+ for (const child of await fs.readdir(path)) {
2376
+ await removeNode(fs, join4(path, child), rootReal);
2377
+ }
2378
+ await fs.rmdir(path);
2379
+ return;
2380
+ }
2381
+ await fs.unlink(path);
2382
+ }
2383
+ async function removeTrashTree(fs, candidate) {
2384
+ const st = await fs.lstat(candidate.path);
2385
+ if (!st.isDirectory() || st.isSymbolicLink?.() === true) {
2386
+ fail2("BAD_PATH", "delete target flipped to symlink/non-directory");
2387
+ }
2388
+ const real = await fs.realpath(candidate.path);
2389
+ if (real !== candidate.path)
2390
+ fail2("BAD_PATH", "delete target realpath changed");
2391
+ await removeNode(fs, candidate.path, real);
2392
+ }
2393
+ function purgeManifestPath(dshHome, opId) {
2394
+ return join4(trashJournalRoot(dshHome), `purge-${opId}.jsonl`);
2395
+ }
2396
+ function usedTokenPath(dshHome, token) {
2397
+ return join4(trashJournalRoot(dshHome), "purge-tokens", `${sha2562(token)}.used`);
2398
+ }
2399
+ async function claimToken(fs, dshHome, token, payload, now) {
2400
+ await fs.mkdir(join4(trashJournalRoot(dshHome), "purge-tokens"), { recursive: true, mode: 448 });
2401
+ try {
2402
+ await fs.writeFile(usedTokenPath(dshHome, token), JSON.stringify({
2403
+ opId: payload.opId,
2404
+ issuedAt: payload.issuedAt,
2405
+ claimedAt: now,
2406
+ tokenHash: sha2562(token)
2407
+ }), { flag: "wx", mode: 384 });
2408
+ } catch (err) {
2409
+ if (errorCode3(err) === "EEXIST")
2410
+ fail2("REPLAY", "purge token already consumed", { opId: payload.opId });
2411
+ throw err;
2412
+ }
2413
+ }
2414
+ async function appendManifest(fs, dshHome, opId, row) {
2415
+ await fs.appendFile(purgeManifestPath(dshHome, opId), JSON.stringify(row) + `
2416
+ `);
2417
+ }
2418
+ async function purgeRootForToken(fs, dshHome) {
2419
+ const root = trashSessionsRoot(dshHome);
2420
+ try {
2421
+ return await fs.realpath(root);
2422
+ } catch (err) {
2423
+ if (errorCode3(err) === "ENOENT")
2424
+ return root;
2425
+ throw err;
2426
+ }
2427
+ }
2428
+ async function preparePurge(fs, deps, dshHome) {
2429
+ return deps.withApplyLock(async () => {
2430
+ const liveIds = await readLiveIds(deps);
2431
+ const scan = await scanPurgeCandidates(fs, deps, dshHome, liveIds);
2432
+ const root = await purgeRootForToken(fs, dshHome);
2433
+ const issued = issuePurgeToken({
2434
+ opId: deps.opId,
2435
+ ids: scan.candidates.map((c) => c.id),
2436
+ paths: scan.candidates.map((c) => c.path),
2437
+ root,
2438
+ retentionDays: deps.retentionDays,
2439
+ issuedAt: deps.now,
2440
+ nonce: `${deps.opId}:${deps.newSecret()}`
2441
+ }, deps.secret, deps.tokenTtlMs);
2442
+ return {
2443
+ opId: deps.opId,
2444
+ candidates: scan.candidates,
2445
+ rejected: scan.rejected,
2446
+ token: issued.token,
2447
+ tokenPayload: issued.payload
2448
+ };
2449
+ });
2450
+ }
2451
+ async function purgeTrashSessions(fs, deps, dshHome, token) {
2452
+ return deps.withApplyLock(async () => {
2453
+ const payload = verifyPurgeToken(token, deps.secret, deps.now);
2454
+ if (payload.v !== 1)
2455
+ fail2("BAD_TOKEN", "unsupported purge token version");
2456
+ const liveIds = await readLiveIds(deps);
2457
+ const scan = await scanPurgeCandidates(fs, deps, dshHome, liveIds);
2458
+ const root = await purgeRootForToken(fs, dshHome);
2459
+ if (root !== payload.root || payload.retentionDays !== deps.retentionDays) {
2460
+ fail2("STALE_TOKEN", "host trash root or retention policy changed since prepare", {
2461
+ retentionDays: deps.retentionDays
2462
+ });
2463
+ }
2464
+ const byId = new Map(scan.candidates.map((c) => [c.id, c]));
2465
+ const rejectedByPath = new Map(scan.rejected.map((r) => [r.path, r]));
2466
+ await claimToken(fs, dshHome, String(token), payload, deps.now);
2467
+ const purged = [];
2468
+ const failed = [];
2469
+ const manifestPath = purgeManifestPath(dshHome, payload.opId);
2470
+ for (let i = 0;i < payload.ids.length; i++) {
2471
+ const id = payload.ids[i];
2472
+ const tokenPath = payload.paths[i];
2473
+ const candidate = byId.get(id);
2474
+ if (candidate === undefined || candidate.path !== tokenPath) {
2475
+ const rejection = rejectedByPath.get(tokenPath);
2476
+ failed.push({
2477
+ id,
2478
+ path: tokenPath,
2479
+ code: rejection?.code ?? "STALE_TOKEN",
2480
+ message: rejection?.message ?? "candidate disappeared or moved after token verification"
2481
+ });
2482
+ continue;
2483
+ }
2484
+ try {
2485
+ const fresh = await assessTrashEntry(fs, deps, dshHome, candidate.run, candidate.encoded, liveIds);
2486
+ if (fresh.path !== tokenPath)
2487
+ fail2("STALE_TOKEN", "candidate realpath moved after token verification", { id });
2488
+ await appendManifest(fs, dshHome, payload.opId, {
2489
+ phase: "intent",
2490
+ opId: payload.opId,
2491
+ id: fresh.id,
2492
+ path: fresh.path,
2493
+ at: deps.now,
2494
+ tokenHash: sha2562(String(token))
2495
+ });
2496
+ await removeTrashTree(fs, fresh);
2497
+ await appendManifest(fs, dshHome, payload.opId, {
2498
+ phase: "done",
2499
+ opId: payload.opId,
2500
+ id: fresh.id,
2501
+ path: fresh.path,
2502
+ at: deps.now
2503
+ });
2504
+ purged.push({ id: fresh.id, path: fresh.path });
2505
+ } catch (err) {
2506
+ failed.push({
2507
+ id: candidate.id,
2508
+ path: candidate.path,
2509
+ code: err instanceof PurgeError ? err.code : "DELETE_FAILED",
2510
+ message: purgeWireMessage(err)
2511
+ });
2512
+ }
2513
+ }
2514
+ return { opId: payload.opId, purged, failed, manifestPath };
2515
+ });
2516
+ }
2517
+
2518
+ // ../bridge/src/session-prune-restore.ts
2519
+ import { basename as basename4, dirname as dirname3, isAbsolute as isAbsolute2, join as join5, relative as relative2, sep as sep4 } from "node:path";
2520
+ import { zstdDecompressSync as nodeZstdDecompressSync2 } from "node:zlib";
2521
+ var RUN_NAME_RE2 = /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z$/;
2522
+ var ARTIFACT_FILENAME2 = "session.v4.jsonl.zstd";
2523
+ var APPLIED_MARKER = ".applied.json";
2524
+ var RUN_MANIFEST_FILENAME2 = "manifest.jsonl";
2525
+ function runManifestPath(dshHome, run) {
2526
+ return join5(trashSessionsRoot(dshHome), run, RUN_MANIFEST_FILENAME2);
2527
+ }
2528
+ function restoredMarkerPath(dshHome, opId, encoded) {
2529
+ return join5(trashJournalRoot(dshHome), `${opId}-${encoded}.restored.json`);
2530
+ }
2531
+
2532
+ class RestoreError extends Error {
2533
+ code;
2534
+ detail;
2535
+ constructor(code, message, detail) {
2536
+ super(message);
2537
+ this.name = "RestoreError";
2538
+ this.code = code;
2539
+ this.detail = detail;
2540
+ }
2541
+ }
2542
+ function fail3(code, message, detail) {
2543
+ throw new RestoreError(code, message, detail);
2544
+ }
2545
+ function errorCode4(err) {
2546
+ if (err === null || typeof err !== "object")
2547
+ return;
2548
+ const code = err.code;
2549
+ return typeof code === "string" ? code : undefined;
2550
+ }
2551
+ function isEnoent2(err) {
2552
+ return errorCode4(err) === "ENOENT";
2553
+ }
2554
+ function isInside4(root, target) {
2555
+ const base = root.length > 1 && root.endsWith(sep4) ? root.slice(0, -1) : root;
2556
+ return target === base || target.startsWith(base.endsWith(sep4) ? base : base + sep4);
2557
+ }
2558
+ function sameDev2(a, b) {
2559
+ return a !== undefined && b !== undefined && String(a) === String(b);
2560
+ }
2561
+ var FS_MSG = {
2562
+ vanished: "trash entry is no longer available",
2563
+ unreadable: "trash entry could not be read",
2564
+ pathUnreadable: "path could not be resolved",
2565
+ statUnavailable: "path metadata is unavailable",
2566
+ rootUnreadable: "sessions root could not be resolved",
2567
+ destinationUnreadable: "live destination could not be resolved"
2568
+ };
2569
+ async function lstatGuest(fs, path) {
2570
+ try {
2571
+ return await fs.lstat(path);
2572
+ } catch (err) {
2573
+ fail3(isEnoent2(err) ? "NOT_FOUND" : "BAD_PATH", isEnoent2(err) ? FS_MSG.vanished : FS_MSG.unreadable);
2574
+ }
2575
+ }
2576
+ async function realpathGuest(fs, path) {
2577
+ try {
2578
+ return await fs.realpath(path);
2579
+ } catch (err) {
2580
+ fail3(isEnoent2(err) ? "NOT_FOUND" : "BAD_PATH", isEnoent2(err) ? FS_MSG.vanished : FS_MSG.pathUnreadable);
2581
+ }
2582
+ }
2583
+ async function statGuest(fs, path) {
2584
+ try {
2585
+ return await fs.stat(path);
2586
+ } catch (err) {
2587
+ fail3(isEnoent2(err) ? "NOT_FOUND" : "BAD_PATH", isEnoent2(err) ? FS_MSG.vanished : FS_MSG.statUnavailable);
2588
+ }
2589
+ }
2590
+ function zstdDecompress2(frame) {
2591
+ const bun = globalThis.Bun;
2592
+ if (bun?.zstdDecompressSync !== undefined)
2593
+ return bun.zstdDecompressSync(frame);
2594
+ return nodeZstdDecompressSync2(frame);
2595
+ }
2596
+ async function readTrashArtifactHeaderId2(fs, dir) {
2597
+ const artifact = join5(dir, ARTIFACT_FILENAME2);
2598
+ let frame;
2599
+ try {
2600
+ frame = await fs.readFileBuffer(artifact);
2601
+ } catch (err) {
2602
+ fail3("BAD_MANIFEST", "trash entry has no readable session artifact", { code: errorCode4(err) });
2603
+ }
2604
+ if (frame.length === 0)
2605
+ fail3("BAD_MANIFEST", "trash session artifact is empty");
2606
+ let text;
2607
+ try {
2608
+ text = zstdDecompress2(frame).toString("utf8");
2609
+ } catch {
2610
+ fail3("BAD_MANIFEST", "trash session artifact is not a valid zstd frame");
2611
+ }
2612
+ const firstLine = text.split(`
2613
+ `, 1)[0] ?? "";
2614
+ let header;
2615
+ try {
2616
+ header = JSON.parse(firstLine);
2617
+ } catch {
2618
+ fail3("BAD_MANIFEST", "trash session artifact header is not JSON");
2619
+ }
2620
+ if (header === null || typeof header !== "object")
2621
+ fail3("BAD_MANIFEST", "trash session artifact header is not an object");
2622
+ const id = header.id;
2623
+ if (typeof id !== "string" || id === "")
2624
+ fail3("BAD_MANIFEST", "trash artifact header.id is missing");
2625
+ return id;
2626
+ }
2627
+ function parseAppliedManifest2(text) {
2628
+ let raw;
2629
+ try {
2630
+ raw = JSON.parse(text);
2631
+ } catch {
2632
+ fail3("BAD_MANIFEST", "trash entry .applied.json is not JSON");
2633
+ }
2634
+ if (raw === null || typeof raw !== "object")
2635
+ fail3("BAD_MANIFEST", "trash entry .applied.json is not an object");
2636
+ const m = raw;
2637
+ if (typeof m.id !== "string" || m.id === "")
2638
+ fail3("BAD_MANIFEST", "applied manifest id is missing");
2639
+ if (typeof m.to !== "string" || m.to === "")
2640
+ fail3("BAD_MANIFEST", "applied manifest to is missing");
2641
+ if (typeof m.appliedAt !== "number" || !Number.isFinite(m.appliedAt))
2642
+ fail3("BAD_MANIFEST", "applied manifest appliedAt is invalid");
2643
+ return {
2644
+ id: m.id,
2645
+ to: m.to,
2646
+ ...typeof m.from === "string" && m.from !== "" ? { from: m.from } : {},
2647
+ appliedAt: m.appliedAt
2648
+ };
2649
+ }
2650
+ async function readRunManifestRow2(fs, manifestPath, entryPath) {
2651
+ let text;
2652
+ try {
2653
+ text = await fs.readFile(manifestPath);
2654
+ } catch {
2655
+ fail3("BAD_MANIFEST", "trash entry has no in-place marker or same-run manifest");
2656
+ }
2657
+ for (const line of text.split(`
2658
+ `)) {
2659
+ if (line === "")
2660
+ continue;
2661
+ let row;
2662
+ try {
2663
+ row = JSON.parse(line);
2664
+ } catch {
2665
+ continue;
2666
+ }
2667
+ if (row === null || typeof row !== "object")
2668
+ continue;
2669
+ const r = row;
2670
+ if (r.phase !== "applied" || r.to !== entryPath)
2671
+ continue;
2672
+ return parseAppliedManifest2(line);
2673
+ }
2674
+ fail3("BAD_MANIFEST", "no same-run manifest row matches this trash entry");
2675
+ }
2676
+ async function readAppliedManifest2(fs, dir, runManifest) {
2677
+ let text;
2678
+ try {
2679
+ text = await fs.readFile(join5(dir, APPLIED_MARKER));
2680
+ } catch (err) {
2681
+ if (isEnoent2(err) && runManifest !== undefined)
2682
+ return readRunManifestRow2(fs, runManifest, dir);
2683
+ fail3("BAD_MANIFEST", "trash entry has no readable .applied.json", { code: errorCode4(err) });
2684
+ }
2685
+ return parseAppliedManifest2(text);
2686
+ }
2687
+ async function probeLockForRestore(lockProbe, lockPath) {
2688
+ if (lockProbe === undefined)
2689
+ fail3("UNSUPPORTED", "lockProbe capability unavailable; restore refuses to assume unlocked");
2690
+ let result;
2691
+ try {
2692
+ result = await lockProbe(lockPath);
2693
+ } catch {
2694
+ fail3("LOCKED", "lock probe threw; refusing to restore");
2695
+ }
2696
+ if (result.status === "lock-held" || result.status === "unknown") {
2697
+ fail3("LOCKED", "session.lock probe is not unlocked", { status: result.status });
2698
+ }
2699
+ }
2700
+ async function pathExists2(fs, path) {
2701
+ try {
2702
+ await fs.lstat(path);
2703
+ return true;
2704
+ } catch (err) {
2705
+ if (isEnoent2(err))
2706
+ return false;
2707
+ fail3("BAD_PATH", FS_MSG.unreadable);
2708
+ }
2709
+ }
2710
+ async function assessEntry(fs, dshHome, run, encoded) {
2711
+ if (!RUN_NAME_RE2.test(run))
2712
+ fail3("BAD_PATH", "trash run directory name is not a UTC stamp");
2713
+ const entryPath = join5(trashSessionsRoot(dshHome), run, encoded);
2714
+ const st = await lstatGuest(fs, entryPath);
2715
+ if (!st.isDirectory() || st.isSymbolicLink?.() === true)
2716
+ fail3("BAD_PATH", "trash entry is not a real directory");
2717
+ const manifest = await readAppliedManifest2(fs, entryPath, runManifestPath(dshHome, run));
2718
+ if (encodeSegment(manifest.id) !== encoded || basename4(entryPath) !== encoded) {
2719
+ fail3("BAD_MANIFEST", "manifest id does not encode to the entry basename");
2720
+ }
2721
+ const toRel = relative2(trashSessionsRoot(dshHome), manifest.to);
2722
+ const expectedRel = join5(run, encoded);
2723
+ if (!isAbsolute2(manifest.to) || toRel.startsWith("..") || isAbsolute2(toRel)) {
2724
+ fail3("BAD_MANIFEST", "applied manifest to escapes the trash sessions root");
2725
+ }
2726
+ if (toRel !== expectedRel && toRel !== expectedRel.split(sep4).join("/")) {
2727
+ fail3("BAD_MANIFEST", "applied manifest to does not match the scanned entry");
2728
+ }
2729
+ const trashReal = await realpathGuest(fs, trashSessionsRoot(dshHome));
2730
+ const real = await realpathGuest(fs, entryPath);
2731
+ if (!isInside4(trashReal, real) || relative2(trashReal, real) !== expectedRel) {
2732
+ fail3("BAD_PATH", "trash entry realpath escaped the sessions trash root");
2733
+ }
2734
+ const headerId = await readTrashArtifactHeaderId2(fs, entryPath);
2735
+ if (headerId !== manifest.id)
2736
+ fail3("BAD_MANIFEST", "trash artifact header.id mismatch");
2737
+ return { id: manifest.id, run, encoded, path: entryPath, manifest };
2738
+ }
2739
+ async function listRestoreEntries(fs, dshHome) {
2740
+ const root = trashSessionsRoot(dshHome);
2741
+ let runs;
2742
+ try {
2743
+ runs = await fs.readdir(root);
2744
+ } catch (err) {
2745
+ if (isEnoent2(err))
2746
+ return { entries: [], rejected: [] };
2747
+ fail3("BAD_PATH", FS_MSG.rootUnreadable);
2748
+ }
2749
+ const entries = [];
2750
+ const rejected = [];
2751
+ for (const run of runs) {
2752
+ let leaves;
2753
+ try {
2754
+ leaves = await fs.readdir(join5(root, run));
2755
+ } catch (err) {
2756
+ if (isEnoent2(err))
2757
+ continue;
2758
+ rejected.push({ code: "INTERNAL", message: "cannot read a trash run directory" });
2759
+ continue;
2760
+ }
2761
+ for (const encoded of leaves) {
2762
+ if (encoded.startsWith(".") || encoded === RUN_MANIFEST_FILENAME2)
2763
+ continue;
2764
+ try {
2765
+ const scanned = await assessEntry(fs, dshHome, run, encoded);
2766
+ let size;
2767
+ try {
2768
+ const artifactStat = await fs.stat(join5(scanned.path, ARTIFACT_FILENAME2));
2769
+ if (typeof artifactStat.size === "number" && Number.isFinite(artifactStat.size))
2770
+ size = artifactStat.size;
2771
+ } catch {}
2772
+ entries.push({
2773
+ id: scanned.id,
2774
+ movedAt: scanned.manifest.appliedAt,
2775
+ ...size !== undefined ? { size } : {}
2776
+ });
2777
+ } catch (err) {
2778
+ if (err instanceof RestoreError && err.code === "NOT_FOUND")
2779
+ continue;
2780
+ rejected.push({
2781
+ code: err instanceof RestoreError ? err.code : "INTERNAL",
2782
+ message: err instanceof RestoreError ? err.message : "trash entry could not be assessed"
2783
+ });
2784
+ }
2785
+ }
2786
+ }
2787
+ entries.sort((a, b) => b.movedAt - a.movedAt || a.id.localeCompare(b.id));
2788
+ return { entries, rejected };
2789
+ }
2790
+ async function readLiveIds2(lister) {
2791
+ const listing = await listAllSessions(lister);
2792
+ if (listing.truncated)
2793
+ fail3("BLOCKED", "restore aborted: session.list roster is incomplete", { pages: listing.pages });
2794
+ const ids = new Map;
2795
+ for (const row of listing.rows) {
2796
+ const raw = row.sessionId;
2797
+ if (raw === undefined || raw === null)
2798
+ continue;
2799
+ const id = String(raw);
2800
+ if (row.agentAvailable === true)
2801
+ ids.set(id, "LIVE_AGENT");
2802
+ else if (!ids.has(id))
2803
+ ids.set(id, "CONFLICT");
2804
+ }
2805
+ return ids;
2806
+ }
2807
+ async function liveDestination(fs, deps, scanned, rootReal) {
2808
+ let destination;
2809
+ const from = scanned.manifest.from;
2810
+ if (typeof from === "string" && from !== "" && isAbsolute2(from)) {
2811
+ const rel = relative2(deps.sessionsRoot, from);
2812
+ if (rel !== "" && !rel.startsWith("..") && !isAbsolute2(rel))
2813
+ destination = from;
2814
+ }
2815
+ if (destination === undefined) {
2816
+ let snapshot;
2817
+ try {
2818
+ snapshot = await deps.persistence.stat(scanned.id);
2819
+ } catch {
2820
+ snapshot = undefined;
2821
+ }
2822
+ const location = snapshot?.location;
2823
+ const path = typeof location === "string" ? location : location !== null && typeof location === "object" && typeof location.path === "string" ? location.path : undefined;
2824
+ if (path !== undefined && path !== "" && isAbsolute2(path)) {
2825
+ const candidate = dirname3(path);
2826
+ const rel = relative2(deps.sessionsRoot, candidate);
2827
+ if (rel !== "" && !rel.startsWith("..") && !isAbsolute2(rel))
2828
+ destination = candidate;
2829
+ }
2830
+ }
2831
+ if (destination === undefined)
2832
+ fail3("BAD_PATH", "restore refused: no host-derived live destination");
2833
+ const dir = basename4(destination);
2834
+ if (dir !== encodeSegment(scanned.id))
2835
+ fail3("BAD_PATH", "restore refused: live destination basename mismatch");
2836
+ if (await pathExists2(fs, destination))
2837
+ fail3("CONFLICT", "restore refused: live destination already exists");
2838
+ const parent = join5(destination, "..");
2839
+ const parentReal = await realpathGuest(fs, parent);
2840
+ if (!isInside4(rootReal, parentReal))
2841
+ fail3("BAD_PATH", "restore refused: live destination escaped sessions root");
2842
+ return destination;
2843
+ }
2844
+ async function restoreTrashEntry(fs, deps, dshHome, id) {
2845
+ if (typeof id !== "string" || id === "")
2846
+ fail3("BAD_PARAMS", "session.prune.restore requires a non-empty id");
2847
+ return deps.withApplyLock(async () => {
2848
+ const liveIds = await readLiveIds2(deps.lister);
2849
+ const live = liveIds.get(id);
2850
+ if (live === "LIVE_AGENT")
2851
+ fail3("LIVE_AGENT", "restore refused: a live agent still owns this session id");
2852
+ if (live === "CONFLICT")
2853
+ fail3("CONFLICT", "restore refused: session id already exists outside trash");
2854
+ const rootReal = await realpathGuest(fs, deps.sessionsRoot);
2855
+ const root = trashSessionsRoot(dshHome);
2856
+ let runs;
2857
+ try {
2858
+ runs = await fs.readdir(root);
2859
+ } catch (err) {
2860
+ if (isEnoent2(err))
2861
+ fail3("NOT_FOUND", "restore refused: no such trash entry");
2862
+ fail3("BAD_PATH", FS_MSG.rootUnreadable);
2863
+ }
2864
+ const matches = [];
2865
+ for (const run of runs) {
2866
+ let leaves;
2867
+ try {
2868
+ leaves = await fs.readdir(join5(root, run));
2869
+ } catch (err) {
2870
+ if (isEnoent2(err))
2871
+ continue;
2872
+ fail3("BAD_PATH", FS_MSG.rootUnreadable);
2873
+ }
2874
+ for (const encoded of leaves) {
2875
+ if (encoded.startsWith(".") || encoded === RUN_MANIFEST_FILENAME2)
2876
+ continue;
2877
+ try {
2878
+ const scanned = await assessEntry(fs, dshHome, run, encoded);
2879
+ if (scanned.id === id)
2880
+ matches.push(scanned);
2881
+ } catch (err) {
2882
+ if (err instanceof RestoreError)
2883
+ continue;
2884
+ fail3("INTERNAL", "trash entry could not be assessed");
2885
+ }
2886
+ }
2887
+ }
2888
+ if (matches.length === 0)
2889
+ fail3("NOT_FOUND", "restore refused: no such trash entry");
2890
+ if (matches.length > 1)
2891
+ fail3("CONFLICT", "restore refused: duplicate trash entries for this id");
2892
+ const scanned = matches[0];
2893
+ const destination = await liveDestination(fs, deps, scanned, rootReal);
2894
+ const trashStat = await statGuest(fs, scanned.path);
2895
+ const parentStat = await statGuest(fs, join5(destination, ".."));
2896
+ if (!sameDev2(trashStat.dev, parentStat.dev))
2897
+ fail3("EXDEV", "restore refused: cross-device rename");
2898
+ const recheckSt = await lstatGuest(fs, scanned.path);
2899
+ if (!recheckSt.isDirectory() || recheckSt.isSymbolicLink?.() === true) {
2900
+ fail3("BAD_PATH", "restore refused: trash entry flipped to symlink/non-directory");
2901
+ }
2902
+ if (await pathExists2(fs, destination))
2903
+ fail3("CONFLICT", "restore refused: live destination already exists");
2904
+ await probeLockForRestore(deps.lockProbe, join5(scanned.path, "session.lock"));
2905
+ const markerPath = join5(scanned.path, APPLIED_MARKER);
2906
+ if (await pathExists2(fs, markerPath)) {
2907
+ const retiredPath = restoredMarkerPath(dshHome, deps.opId, scanned.encoded);
2908
+ if (await pathExists2(fs, retiredPath)) {
2909
+ fail3("RESTORE_FAILED", "restore refused: retired marker journal already exists");
2910
+ }
2911
+ try {
2912
+ await fs.rename(markerPath, retiredPath);
2913
+ } catch {
2914
+ fail3("RESTORE_FAILED", "restore refused: could not retire the applied marker");
2915
+ }
2916
+ if (await pathExists2(fs, markerPath)) {
2917
+ fail3("RESTORE_FAILED", "restore refused: applied marker still present after retirement");
2918
+ }
2919
+ }
2920
+ try {
2921
+ await fs.rename(scanned.path, destination);
2922
+ } catch (err) {
2923
+ if (errorCode4(err) === "EXDEV")
2924
+ fail3("EXDEV", "restore refused: cross-device rename");
2925
+ fail3("RESTORE_FAILED", "restore rename failed", { code: errorCode4(err) });
2926
+ }
2927
+ return { id, restored: true, opId: deps.opId };
2928
+ });
1148
2929
  }
1149
2930
 
1150
2931
  // ../bridge/src/settings-adapter.ts
@@ -1327,75 +3108,103 @@ var ledger_default = {
1327
3108
  },
1328
3109
  wired_protocol: {
1329
3110
  mark: "bridge-protocol (ADR-0010)",
1330
- count: 10,
3111
+ count: 14,
1331
3112
  methods: [
1332
3113
  {
1333
3114
  method: "bridge.ping",
1334
3115
  kind: "meta",
1335
- source_line: 2247,
3116
+ source_line: 5682,
1336
3117
  capir_id: null,
1337
3118
  note: "protocol version negotiation (no host call)"
1338
3119
  },
1339
3120
  {
1340
3121
  method: "bridge.hello",
1341
3122
  kind: "meta",
1342
- source_line: 2256,
3123
+ source_line: 5691,
1343
3124
  capir_id: null,
1344
3125
  note: "protocol version negotiation (no host call)"
1345
3126
  },
3127
+ {
3128
+ method: "session.prune.plan",
3129
+ kind: "business",
3130
+ source_line: 5725,
3131
+ capir_id: null,
3132
+ note: "retention P1 read-only dry run: session.list drain + sessionPersistence.stat locations + read-only path gates; no CapIR id, no host write, no deletion"
3133
+ },
3134
+ {
3135
+ method: "session.prune.apply",
3136
+ kind: "business",
3137
+ source_line: 5731,
3138
+ capir_id: null,
3139
+ note: "retention P2 host-recomputed trash apply: fingerprint/max-age/config checks + host-side apply lock + rename-to-trash with rollback/journal; client entries/policy rejected; no CapIR id"
3140
+ },
3141
+ {
3142
+ method: "session.prune.purge",
3143
+ kind: "business",
3144
+ source_line: 5737,
3145
+ capir_id: null,
3146
+ note: "retention P3 trash-only deletion: server-issued single-use HMAC token + host re-validation of trash realpath/header/manifest/residence + full gate re-probe (live agent, live path, flock) + recursive delete with per-entry failure and crash manifest; client path/policy rejected; no CapIR id"
3147
+ },
3148
+ {
3149
+ method: "session.prune.restore",
3150
+ kind: "business",
3151
+ source_line: 5743,
3152
+ capir_id: null,
3153
+ note: "retention B4/C7 trash restore by entry id: read-only list of {id,movedAt,size?} (no path) + host re-validation of trash realpath/manifest/artifact header.id/live roster/live destination containment + refuse-if-exists + read-only flock probe + reverse rename; client path/policy rejected; no CapIR id"
3154
+ },
1346
3155
  {
1347
3156
  method: "subagents.interrupt",
1348
3157
  kind: "business",
1349
- source_line: 2300,
3158
+ source_line: 5810,
1350
3159
  capir_id: null,
1351
3160
  note: "L1 0.23.1 added; subagent authorization gate (binding ownership) + index reconcile + per-child cancel"
1352
3161
  },
1353
3162
  {
1354
3163
  method: "subagents.stopChildren",
1355
3164
  kind: "business",
1356
- source_line: 2304,
3165
+ source_line: 5814,
1357
3166
  capir_id: null,
1358
3167
  note: "L1 0.23.1 added; subagent authorization gate (binding ownership) + index reconcile + per-child cancel"
1359
3168
  },
1360
3169
  {
1361
3170
  method: "session.open",
1362
3171
  kind: "business",
1363
- source_line: 2308,
3172
+ source_line: 5818,
1364
3173
  capir_id: null,
1365
3174
  note: "binding orchestration (agents.create/resume + push relay/grants); multi-step, stateful"
1366
3175
  },
1367
3176
  {
1368
3177
  method: "session.send",
1369
3178
  kind: "business",
1370
- source_line: 2312,
3179
+ source_line: 5822,
1371
3180
  capir_id: null,
1372
3181
  note: "single in-flight turn state machine + streaming turn"
1373
3182
  },
1374
3183
  {
1375
3184
  method: "session.close",
1376
3185
  kind: "business",
1377
- source_line: 2316,
3186
+ source_line: 5826,
1378
3187
  capir_id: null,
1379
3188
  note: "binding dispose"
1380
3189
  },
1381
3190
  {
1382
3191
  method: "turn.abort",
1383
3192
  kind: "business",
1384
- source_line: 2320,
3193
+ source_line: 5830,
1385
3194
  capir_id: null,
1386
3195
  note: "turn state machine + terminalTurnIds FIFO idempotency + fire-and-forget agent.cancel"
1387
3196
  },
1388
3197
  {
1389
3198
  method: "ask.response",
1390
3199
  kind: "business",
1391
- source_line: 2324,
3200
+ source_line: 5834,
1392
3201
  capir_id: null,
1393
3202
  note: "bridge-internal AskRegistry settlement (no host call)"
1394
3203
  },
1395
3204
  {
1396
3205
  method: "journal.replay",
1397
3206
  kind: "business",
1398
- source_line: 2328,
3207
+ source_line: 5838,
1399
3208
  capir_id: null,
1400
3209
  note: "I-class persistence read (persistence.open(id,'read')); no same-name CapIR id"
1401
3210
  }
@@ -7816,14 +9625,14 @@ var BRIDGE_CAPABILITIES = ["subagents.interrupt", "subagents.stopChildren"];
7816
9625
  var TERMINAL_TURN_ID_LIMIT = 64;
7817
9626
  function findPackageVersion(entryFile, wantedName) {
7818
9627
  try {
7819
- let dir = dirname(realpathSync(entryFile));
7820
- for (let i = 0;i < 12 && dir !== dirname(dir); i++) {
9628
+ let dir = dirname4(realpathSync2(entryFile));
9629
+ for (let i = 0;i < 12 && dir !== dirname4(dir); i++) {
7821
9630
  try {
7822
- const pkg = JSON.parse(readFileSync2(join2(dir, "package.json"), "utf8"));
9631
+ const pkg = JSON.parse(readFileSync2(join6(dir, "package.json"), "utf8"));
7823
9632
  if (pkg?.name === wantedName && typeof pkg.version === "string")
7824
9633
  return pkg.version;
7825
9634
  } catch {}
7826
- dir = dirname(dir);
9635
+ dir = dirname4(dir);
7827
9636
  }
7828
9637
  } catch {}
7829
9638
  return;
@@ -7844,7 +9653,7 @@ function readHostVersion() {
7844
9653
  return v;
7845
9654
  }
7846
9655
  try {
7847
- const req = createRequire(import.meta.url);
9656
+ const req = createRequire2(import.meta.url);
7848
9657
  const path = req.resolve("@deepseek-ai/dsh/package.json");
7849
9658
  const pkg = JSON.parse(readFileSync2(path, "utf8"));
7850
9659
  if (typeof pkg.version === "string")
@@ -7867,6 +9676,118 @@ function resolvePersistence(ctx) {
7867
9676
  const svc = fromGet ?? ctx.sessionPersistence;
7868
9677
  return svc !== undefined && typeof svc.open === "function" ? svc : undefined;
7869
9678
  }
9679
+ function resolvePrunePersistence(ctx) {
9680
+ const base = resolvePersistence(ctx);
9681
+ return base !== undefined && hasStatCapability(base) ? base : undefined;
9682
+ }
9683
+ function resolvePruneSessionsRoot(ctx, config) {
9684
+ const fromConfig = config !== null && typeof config === "object" ? config : {};
9685
+ if (typeof fromConfig.sessionsRoot === "string" && fromConfig.sessionsRoot !== "")
9686
+ return fromConfig.sessionsRoot;
9687
+ if (typeof fromConfig.dshHome === "string" && fromConfig.dshHome !== "")
9688
+ return join6(fromConfig.dshHome, "sessions");
9689
+ try {
9690
+ const hostConfig = typeof ctx.get === "function" ? ctx.get("config") : undefined;
9691
+ if (hostConfig !== null && typeof hostConfig === "object") {
9692
+ const hc = hostConfig;
9693
+ if (typeof hc.sessionsRoot === "string" && hc.sessionsRoot !== "")
9694
+ return hc.sessionsRoot;
9695
+ if (typeof hc.dshHome === "string" && hc.dshHome !== "")
9696
+ return join6(hc.dshHome, "sessions");
9697
+ }
9698
+ } catch {}
9699
+ return join6(process.env.DSH_HOME || join6(homedir2(), ".dsh"), "sessions");
9700
+ }
9701
+ function resolvePruneDshHome(ctx, config) {
9702
+ const fromConfig = config !== null && typeof config === "object" ? config : {};
9703
+ if (typeof fromConfig.dshHome === "string" && fromConfig.dshHome !== "")
9704
+ return fromConfig.dshHome;
9705
+ try {
9706
+ const hostConfig = typeof ctx.get === "function" ? ctx.get("config") : undefined;
9707
+ if (hostConfig !== null && typeof hostConfig === "object") {
9708
+ const hc = hostConfig;
9709
+ if (typeof hc.dshHome === "string" && hc.dshHome !== "")
9710
+ return hc.dshHome;
9711
+ }
9712
+ } catch {}
9713
+ return process.env.DSH_HOME || join6(homedir2(), ".dsh");
9714
+ }
9715
+ function resolveHostProfileConfig(ctx) {
9716
+ try {
9717
+ const profile = typeof ctx.get === "function" ? ctx.get("profileContext") : undefined;
9718
+ const dir = profile !== null && typeof profile === "object" ? profile.dir : undefined;
9719
+ if (typeof dir !== "string" || dir === "")
9720
+ return;
9721
+ const parsed = JSON.parse(readFileSync2(join6(dir, "config.json"), "utf8"));
9722
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : undefined;
9723
+ } catch {
9724
+ return;
9725
+ }
9726
+ }
9727
+ function resolveHostPrunePolicy(ctx, config, sessionsRoot) {
9728
+ const fromConfig = config !== null && typeof config === "object" ? config : {};
9729
+ const hostConfig = (() => {
9730
+ try {
9731
+ const value = typeof ctx.get === "function" ? ctx.get("config") : undefined;
9732
+ return value !== null && typeof value === "object" ? value : {};
9733
+ } catch {
9734
+ return {};
9735
+ }
9736
+ })();
9737
+ const profileConfig = resolveHostProfileConfig(ctx);
9738
+ const numberFrom = (key, fallback, min, max) => {
9739
+ for (const source of [profileConfig, hostConfig, fromConfig]) {
9740
+ if (source === undefined)
9741
+ continue;
9742
+ const value = source[key];
9743
+ if (typeof value === "number" && Number.isFinite(value) && value >= min && value <= max)
9744
+ return value;
9745
+ }
9746
+ return fallback;
9747
+ };
9748
+ const retentionDays = numberFrom("retentionDays", DEFAULT_RETENTION_DAYS, 0, 3650);
9749
+ const blankGraceDays = numberFrom("blankGraceDays", 30, 0, 3650);
9750
+ const lockGraceMs = numberFrom("lockGraceMs", 300000, 0, 86400000);
9751
+ const freshMtimeGraceMs = numberFrom("freshMtimeGraceMs", lockGraceMs, 0, 86400000);
9752
+ return { retentionDays, blankGraceDays, lockGraceMs, freshMtimeGraceMs, sessionsRoot };
9753
+ }
9754
+ function resolveHostPurgePolicy(ctx, config) {
9755
+ const fromConfig = config !== null && typeof config === "object" ? config : {};
9756
+ const hostConfig = (() => {
9757
+ try {
9758
+ const value = typeof ctx.get === "function" ? ctx.get("config") : undefined;
9759
+ return value !== null && typeof value === "object" ? value : {};
9760
+ } catch {
9761
+ return {};
9762
+ }
9763
+ })();
9764
+ const numberFrom = (key, fallback, min, max) => {
9765
+ for (const source of [fromConfig, hostConfig]) {
9766
+ const value = source[key];
9767
+ if (typeof value === "number" && Number.isFinite(value) && value >= min && value <= max)
9768
+ return value;
9769
+ }
9770
+ return fallback;
9771
+ };
9772
+ return {
9773
+ retentionDays: numberFrom("purgeRetentionDays", DEFAULT_PURGE_RETENTION_DAYS, 0, 3650),
9774
+ tokenTtlMs: numberFrom("purgeTokenTtlMs", 120000, 1, 86400000)
9775
+ };
9776
+ }
9777
+ async function withHostApplyLock(dshHome, tryLockExclusive, fn) {
9778
+ const root = trashRoot(dshHome);
9779
+ await mkdir(root, { recursive: true, mode: 448 });
9780
+ const path = join6(root, ".apply.lock");
9781
+ const handle = await open2(path, "w", 384);
9782
+ try {
9783
+ await tryLockExclusive(handle.fd);
9784
+ return await fn();
9785
+ } finally {
9786
+ try {
9787
+ await handle.close();
9788
+ } catch {}
9789
+ }
9790
+ }
7870
9791
  var cachedAppendPluginRecord;
7871
9792
  var appendPluginRecordResolved = false;
7872
9793
  function resolveAppendPluginRecord() {
@@ -7876,12 +9797,12 @@ function resolveAppendPluginRecord() {
7876
9797
  const roots = [import.meta.url];
7877
9798
  if (process.argv[1]) {
7878
9799
  try {
7879
- roots.push(realpathSync(process.argv[1]));
9800
+ roots.push(realpathSync2(process.argv[1]));
7880
9801
  } catch {}
7881
9802
  }
7882
9803
  for (const root of roots) {
7883
9804
  try {
7884
- const req = createRequire(root);
9805
+ const req = createRequire2(root);
7885
9806
  const mod = req("@deepseek-ai/dsh-session");
7886
9807
  if (typeof mod.appendPluginRecord === "function") {
7887
9808
  cachedAppendPluginRecord = mod.appendPluginRecord;
@@ -8084,10 +10005,23 @@ function resolveAskDeadlineMs(raw, maxAskWaitMs = DEFAULT_MAX_ASK_WAIT_MS, warn
8084
10005
  }
8085
10006
  return raw;
8086
10007
  }
10008
+ function resolveMaxAskWaitMs(raw, cap = DEFAULT_MAX_ASK_WAIT_MS, warn = () => {}) {
10009
+ if (raw === undefined || raw === null)
10010
+ return cap;
10011
+ if (typeof raw !== "number" || !Number.isInteger(raw) || raw <= 0 || raw > cap) {
10012
+ warn("[dsh-opentui-bridge] invalid maxAskWaitMs %s ignored (using hard cap %d)", String(raw), cap);
10013
+ return cap;
10014
+ }
10015
+ return raw;
10016
+ }
8087
10017
  var agentProgressResidues = new WeakMap;
8088
10018
  function probeAgentProgressResidue(ctx) {
8089
10019
  return agentProgressResidues.get(ctx)?.();
8090
10020
  }
10021
+ var agentTranscriptResidues = new WeakMap;
10022
+ function probeAgentTranscriptResidue(ctx) {
10023
+ return agentTranscriptResidues.get(ctx)?.();
10024
+ }
8091
10025
  function apply(ctx, config) {
8092
10026
  const logger = ctx.logger;
8093
10027
  if (process.env[STDIO_SWITCH] !== "1") {
@@ -8506,6 +10440,7 @@ function apply(ctx, config) {
8506
10440
  childProgress: childProgress.size,
8507
10441
  progressSentFp: progressSentFp.size
8508
10442
  }));
10443
+ agentTranscriptResidues.set(ctx, () => ({ childTranscripts: childTranscripts.size }));
8509
10444
  function flushProgress(childId) {
8510
10445
  const snap = progressPending.get(childId);
8511
10446
  if (snap === undefined)
@@ -8549,6 +10484,80 @@ function apply(ctx, config) {
8549
10484
  progressPending.clear();
8550
10485
  progressSentFp.clear();
8551
10486
  childProgress.clear();
10487
+ clearTranscriptState();
10488
+ }
10489
+ const childTranscripts = new Map;
10490
+ const MAX_PENDING_TOOL_CALLS = 64;
10491
+ const childTranscriptRunIds = new Map;
10492
+ function transcriptTurnId() {
10493
+ return inFlightTurnId ?? "";
10494
+ }
10495
+ function childTranscriptRunId(childId) {
10496
+ const fromSpawn = childTranscriptRunIds.get(childId);
10497
+ if (fromSpawn !== undefined && fromSpawn !== "")
10498
+ return fromSpawn;
10499
+ const indexed = getSubagentIndex(ctx).get(childId);
10500
+ return indexed !== undefined && indexed.startedAt > 0 ? `child@${indexed.startedAt}` : "";
10501
+ }
10502
+ function childTranscriptState(childId) {
10503
+ let st = childTranscripts.get(childId);
10504
+ const turnId = transcriptTurnId();
10505
+ if (st === undefined || st.turnId !== turnId) {
10506
+ st = { turnId, seq: 0, pending: [], toolCalls: new Map };
10507
+ childTranscripts.set(childId, st);
10508
+ }
10509
+ return st;
10510
+ }
10511
+ function flushTranscript(childId) {
10512
+ const st = childTranscripts.get(childId);
10513
+ if (st === undefined || st.pending.length === 0 || binding === undefined)
10514
+ return;
10515
+ const rows = st.pending.splice(0);
10516
+ emitEvent("agent.transcript", {
10517
+ turnId: st.turnId,
10518
+ sessionId: binding.sessionId,
10519
+ childId,
10520
+ runId: childTranscriptRunId(childId),
10521
+ seq: st.seq,
10522
+ rows
10523
+ });
10524
+ st.seq += 1;
10525
+ }
10526
+ function flushTranscriptNow(childId) {
10527
+ flushTranscript(childId);
10528
+ const st = childTranscripts.get(childId);
10529
+ if (st !== undefined)
10530
+ st.toolCalls.clear();
10531
+ }
10532
+ function flushAllTranscript() {
10533
+ for (const childId of [...childTranscripts.keys()])
10534
+ flushTranscriptNow(childId);
10535
+ }
10536
+ function clearTranscriptState() {
10537
+ childTranscripts.clear();
10538
+ childTranscriptRunIds.clear();
10539
+ }
10540
+ function clearChildTranscript(childId) {
10541
+ childTranscripts.delete(childId);
10542
+ }
10543
+ function noteChildTranscriptRow(childId, row) {
10544
+ if (binding === undefined || childId === "" || childId === binding.sessionId)
10545
+ return;
10546
+ const indexed = getSubagentIndex(ctx).get(childId);
10547
+ if (indexed === undefined || indexed.parentSessionId !== binding.sessionId || indexed.status === "settled")
10548
+ return;
10549
+ const st = childTranscriptState(childId);
10550
+ st.pending.push(row);
10551
+ flushTranscript(childId);
10552
+ }
10553
+ function assistantMessageText(data) {
10554
+ const message = data.message !== null && typeof data.message === "object" ? data.message : undefined;
10555
+ const content = message?.content ?? data.content ?? message?.text ?? data.text;
10556
+ if (typeof content === "string")
10557
+ return content;
10558
+ if (Array.isArray(content))
10559
+ return contentText(content);
10560
+ return "";
8552
10561
  }
8553
10562
  function noteChildProgress(childId, roundsDelta, textDelta, lastLineOverride) {
8554
10563
  if (binding === undefined || childId === "" || childId === binding.sessionId)
@@ -8674,10 +10683,13 @@ function apply(ctx, config) {
8674
10683
  logger.warn("[dsh-opentui-bridge] ask journal append failed (decision unchanged): %s", err);
8675
10684
  }
8676
10685
  }
8677
- const askDeadlineMsRaw = config !== null && typeof config === "object" ? config.askDeadlineMs : undefined;
8678
- const askDeadlineMs = resolveAskDeadlineMs(askDeadlineMsRaw, DEFAULT_MAX_ASK_WAIT_MS, (fmt, ...params) => logger.warn(fmt, ...params));
10686
+ const configObject = config !== null && typeof config === "object" ? config : undefined;
10687
+ const maxAskWaitMs = resolveMaxAskWaitMs(configObject?.maxAskWaitMs, DEFAULT_MAX_ASK_WAIT_MS, (fmt, ...params) => logger.warn(fmt, ...params));
10688
+ const askDeadlineMsRaw = configObject?.askDeadlineMs;
10689
+ const askDeadlineMs = resolveAskDeadlineMs(askDeadlineMsRaw, maxAskWaitMs, (fmt, ...params) => logger.warn(fmt, ...params));
8679
10690
  const ask = new AskRegistry({
8680
10691
  askDeadlineMs,
10692
+ maxAskWaitMs,
8681
10693
  logger,
8682
10694
  journal: writeAskJournal,
8683
10695
  sink: (frame) => {
@@ -8930,6 +10942,7 @@ function apply(ctx, config) {
8930
10942
  if (!childId)
8931
10943
  return;
8932
10944
  getSubagentIndex(ctx).noteCatalog(childId, sessionId, typeof data.childCreatedAt === "number" ? data.childCreatedAt : undefined);
10945
+ childTranscriptRunIds.set(childId, `catalog:${childId}@${typeof data.childCreatedAt === "number" ? data.childCreatedAt : ""}`);
8933
10946
  syncChildApprovalPolicy(childId, sessionId);
8934
10947
  const turnId = state !== undefined && !state.ended ? state.turnId : inFlightTurnId ?? "";
8935
10948
  const label = typeof data.label === "string" && data.label !== "" ? data.label : typeof data.name === "string" ? data.name : "";
@@ -8955,6 +10968,7 @@ function apply(ctx, config) {
8955
10968
  const childId = idString(data.childId);
8956
10969
  if (!childId)
8957
10970
  return;
10971
+ childTranscriptRunIds.set(childId, idString(data.runId));
8958
10972
  emitEvent("agent.spawn", {
8959
10973
  turnId,
8960
10974
  sessionId: boundId,
@@ -8965,6 +10979,7 @@ function apply(ctx, config) {
8965
10979
  });
8966
10980
  } else {
8967
10981
  flushAllProgress();
10982
+ flushAllTranscript();
8968
10983
  emitEvent("agent.settle", {
8969
10984
  turnId,
8970
10985
  sessionId: boundId,
@@ -8977,6 +10992,44 @@ function apply(ctx, config) {
8977
10992
  }
8978
10993
  if (type === "assistant/message" && binding !== undefined && sessionId !== binding.sessionId) {
8979
10994
  noteChildProgress(sessionId, 1, "", assistantMessageLastLine(data));
10995
+ const text = assistantMessageText(data);
10996
+ if (text !== "")
10997
+ noteChildTranscriptRow(sessionId, { kind: "assistant", text });
10998
+ }
10999
+ if (binding !== undefined && sessionId !== binding.sessionId) {
11000
+ if (type === "tool/call") {
11001
+ const callId = idString(data.callId);
11002
+ if (callId !== "undefined" && callId !== "") {
11003
+ const indexed = getSubagentIndex(ctx).get(sessionId);
11004
+ if (indexed !== undefined && indexed.parentSessionId === binding.sessionId && indexed.status !== "settled") {
11005
+ const st = childTranscriptState(sessionId);
11006
+ const name = typeof data.name === "string" ? data.name : "";
11007
+ if (!st.toolCalls.has(callId) && st.toolCalls.size >= MAX_PENDING_TOOL_CALLS) {
11008
+ const oldest = st.toolCalls.keys().next().value;
11009
+ if (oldest !== undefined)
11010
+ st.toolCalls.delete(oldest);
11011
+ }
11012
+ st.toolCalls.set(callId, name);
11013
+ }
11014
+ }
11015
+ } else if (type === "tool/result") {
11016
+ const message = data.message !== null && typeof data.message === "object" ? data.message : undefined;
11017
+ const callId = idString(message?.toolCallId);
11018
+ if (callId !== "undefined" && callId !== "") {
11019
+ const indexed = getSubagentIndex(ctx).get(sessionId);
11020
+ if (indexed !== undefined && indexed.parentSessionId === binding.sessionId && indexed.status !== "settled") {
11021
+ const state = childTranscripts.get(sessionId);
11022
+ const name = state?.toolCalls.get(callId) ?? "";
11023
+ state?.toolCalls.delete(callId);
11024
+ if (name !== "")
11025
+ noteChildTranscriptRow(sessionId, {
11026
+ kind: "tool",
11027
+ text: name,
11028
+ ...contentText(message?.content) !== "" ? { output: contentText(message?.content) } : {}
11029
+ });
11030
+ }
11031
+ }
11032
+ }
8980
11033
  }
8981
11034
  if (type === "turn/end") {
8982
11035
  const index = getSubagentIndex(ctx);
@@ -8985,8 +11038,10 @@ function apply(ctx, config) {
8985
11038
  const boundId = binding?.sessionId;
8986
11039
  const shouldSettle = row.status === "running" && boundId !== undefined && row.parentSessionId === boundId;
8987
11040
  flushProgressNow(sessionId);
11041
+ flushTranscriptNow(sessionId);
8988
11042
  index.noteSettled(sessionId, typeof data.seq === "number" ? data.seq : undefined);
8989
11043
  clearChildProgress(sessionId);
11044
+ clearChildTranscript(sessionId);
8990
11045
  if (shouldSettle) {
8991
11046
  const turnId = state !== undefined && !state.ended ? state.turnId : inFlightTurnId ?? "";
8992
11047
  emitEvent("agent.settle", {
@@ -9659,6 +11714,460 @@ function apply(ctx, config) {
9659
11714
  replyError(req.id, mapped.code, mapped.message, mapped.detail);
9660
11715
  }
9661
11716
  }
11717
+ async function handlePlanSessionPrune(req) {
11718
+ const persistence = resolvePrunePersistence(ctx);
11719
+ if (persistence === undefined) {
11720
+ replyError(req.id, "UNSUPPORTED", "sessionPersistence.stat unavailable: session.prune.plan requires stat capability", {
11721
+ capability: "session.prune.plan",
11722
+ service: "sessionPersistence"
11723
+ });
11724
+ return;
11725
+ }
11726
+ const controller = resolveSessionController(ctx);
11727
+ if (controller === undefined) {
11728
+ replyError(req.id, "UNSUPPORTED", "sessionController service unavailable: session.prune.plan requires session.list", {
11729
+ capability: "session.prune.plan",
11730
+ service: "sessionController"
11731
+ });
11732
+ return;
11733
+ }
11734
+ const tryLockExclusive = resolveFlockTryLockExclusive();
11735
+ if (tryLockExclusive === undefined) {
11736
+ replyError(req.id, "UNSUPPORTED", "flock capability unavailable: session.prune.plan requires tryLockExclusive", {
11737
+ capability: "session.prune.plan",
11738
+ service: "node-addon-system/flock",
11739
+ detail: "tryLockExclusive"
11740
+ });
11741
+ return;
11742
+ }
11743
+ const lockProbe = createPruneLockProbe(tryLockExclusive);
11744
+ const params = req.params ?? {};
11745
+ for (const key of ["sessionsRoot", "retentionDays", "blankGraceDays", "lockGraceMs", "freshMtimeGraceMs"]) {
11746
+ if (params[key] !== undefined) {
11747
+ replyError(req.id, "BAD_PARAMS", `session.prune.plan ${key} is host-derived; clients may not set it`);
11748
+ return;
11749
+ }
11750
+ }
11751
+ const stagedIds = new Set;
11752
+ if (params.stagedIds !== undefined) {
11753
+ if (!Array.isArray(params.stagedIds) || params.stagedIds.some((s) => typeof s !== "string")) {
11754
+ replyError(req.id, "BAD_PARAMS", "session.prune.plan stagedIds must be a string array");
11755
+ return;
11756
+ }
11757
+ for (const id of params.stagedIds)
11758
+ stagedIds.add(id);
11759
+ }
11760
+ const sessionsRoot = resolvePruneSessionsRoot(ctx, config);
11761
+ const policy = resolveHostPrunePolicy(ctx, config, sessionsRoot);
11762
+ const planConfigFingerprint = computeConfigFingerprint(policy);
11763
+ const lister = {
11764
+ list: (request) => controller.list(request)
11765
+ };
11766
+ const nodePruneFs = { lstat, realpath, stat, lockProbe };
11767
+ try {
11768
+ const listing = await listAllSessions(lister);
11769
+ if (listing.truncated) {
11770
+ replyError(req.id, "BLOCKED", "session.prune.plan aborted: session.list roster is incomplete (truncated pagination)", {
11771
+ capability: "session.prune.plan",
11772
+ reason: "incomplete-roster",
11773
+ pages: listing.pages
11774
+ });
11775
+ return;
11776
+ }
11777
+ const plan = await planSessionPrune(listing.rows, persistence, nodePruneFs, {
11778
+ retentionDays: policy.retentionDays,
11779
+ now: Date.now(),
11780
+ sessionsRoot,
11781
+ currentSessionId: binding?.sessionId,
11782
+ stagedIds,
11783
+ blankGraceDays: policy.blankGraceDays,
11784
+ lockGraceMs: policy.lockGraceMs,
11785
+ freshMtimeGraceMs: policy.freshMtimeGraceMs
11786
+ });
11787
+ replyOk(req.id, {
11788
+ ...plan,
11789
+ fingerprint: computePlanFingerprint(plan),
11790
+ configFingerprint: planConfigFingerprint
11791
+ });
11792
+ } catch (err) {
11793
+ const message = err instanceof Error ? err.message : String(err);
11794
+ logger.error("[dsh-opentui-bridge] session.prune.plan failed: %s", message);
11795
+ const mapped = mapHostError(err);
11796
+ replyError(req.id, mapped.code, mapped.message, mapped.detail);
11797
+ }
11798
+ }
11799
+ async function handleApplySessionPrune(req) {
11800
+ const params = req.params;
11801
+ if (params === null || typeof params !== "object" || Array.isArray(params)) {
11802
+ replyError(req.id, "BAD_PARAMS", "session.prune.apply params must be an object");
11803
+ return;
11804
+ }
11805
+ const p = params;
11806
+ for (const key of [
11807
+ "entries",
11808
+ "retentionDays",
11809
+ "blankGraceDays",
11810
+ "lockGraceMs",
11811
+ "freshMtimeGraceMs",
11812
+ "sessionsRoot",
11813
+ "dshHome"
11814
+ ]) {
11815
+ if (p[key] !== undefined) {
11816
+ replyError(req.id, "BAD_PARAMS", `session.prune.apply ${key} is host-owned; clients may not set it`);
11817
+ return;
11818
+ }
11819
+ }
11820
+ const stagedIds = new Set;
11821
+ if (p.stagedIds !== undefined) {
11822
+ if (!Array.isArray(p.stagedIds) || p.stagedIds.some((s) => typeof s !== "string")) {
11823
+ replyError(req.id, "BAD_PARAMS", "session.prune.apply stagedIds must be a string array");
11824
+ return;
11825
+ }
11826
+ for (const id of p.stagedIds)
11827
+ stagedIds.add(id);
11828
+ }
11829
+ const fingerprint = p.fingerprint;
11830
+ const configFingerprint = p.configFingerprint;
11831
+ const generatedAt = p.generatedAt;
11832
+ if (typeof fingerprint !== "string" || fingerprint === "") {
11833
+ replyError(req.id, "BAD_PARAMS", "session.prune.apply requires fingerprint from session.prune.plan");
11834
+ return;
11835
+ }
11836
+ if (typeof configFingerprint !== "string" || configFingerprint === "") {
11837
+ replyError(req.id, "BAD_PARAMS", "session.prune.apply requires configFingerprint from session.prune.plan");
11838
+ return;
11839
+ }
11840
+ if (typeof generatedAt !== "number" || !Number.isFinite(generatedAt)) {
11841
+ replyError(req.id, "BAD_PARAMS", "session.prune.apply requires numeric generatedAt from session.prune.plan");
11842
+ return;
11843
+ }
11844
+ const persistence = resolvePrunePersistence(ctx);
11845
+ if (persistence === undefined) {
11846
+ replyError(req.id, "UNSUPPORTED", "sessionPersistence.stat unavailable: session.prune.apply requires stat capability", {
11847
+ capability: "session.prune.apply",
11848
+ service: "sessionPersistence"
11849
+ });
11850
+ return;
11851
+ }
11852
+ const controller = resolveSessionController(ctx);
11853
+ if (controller === undefined) {
11854
+ replyError(req.id, "UNSUPPORTED", "sessionController service unavailable: session.prune.apply requires session.list", {
11855
+ capability: "session.prune.apply",
11856
+ service: "sessionController"
11857
+ });
11858
+ return;
11859
+ }
11860
+ const tryLockExclusive = resolveFlockTryLockExclusive();
11861
+ if (tryLockExclusive === undefined) {
11862
+ replyError(req.id, "UNSUPPORTED", "flock capability unavailable: session.prune.apply requires tryLockExclusive", {
11863
+ capability: "session.prune.apply",
11864
+ service: "node-addon-system/flock",
11865
+ detail: "tryLockExclusive"
11866
+ });
11867
+ return;
11868
+ }
11869
+ const sessionsRoot = resolvePruneSessionsRoot(ctx, config);
11870
+ const dshHome = resolvePruneDshHome(ctx, config);
11871
+ const policy = resolveHostPrunePolicy(ctx, config, sessionsRoot);
11872
+ const maxPlanAgeMs = (() => {
11873
+ const fromConfig = config !== null && typeof config === "object" ? config : {};
11874
+ let hostValue;
11875
+ try {
11876
+ const hostConfig = typeof ctx.get === "function" ? ctx.get("config") : undefined;
11877
+ if (hostConfig !== null && typeof hostConfig === "object")
11878
+ hostValue = hostConfig.maxPlanAgeMs;
11879
+ } catch {}
11880
+ const value = fromConfig.maxPlanAgeMs ?? hostValue;
11881
+ return typeof value === "number" && Number.isFinite(value) && value > 0 && value <= 86400000 ? value : 60000;
11882
+ })();
11883
+ const lockProbe = createPruneLockProbe(tryLockExclusive);
11884
+ const nodePruneFs = { lstat, realpath, stat, lockProbe };
11885
+ const nodeApplyFs = {
11886
+ lstat,
11887
+ realpath,
11888
+ stat,
11889
+ rename,
11890
+ mkdir: (path, options) => options?.recursive ? mkdir(path, { recursive: true, mode: options.mode }) : mkdir(path, { mode: options?.mode }),
11891
+ writeFile: (path, data, options) => writeFile(path, data, options),
11892
+ appendFile,
11893
+ readdir,
11894
+ readFile: (path) => readFile(path, "utf8")
11895
+ };
11896
+ const now = Date.now();
11897
+ const deps = {
11898
+ persistence,
11899
+ lockProbe,
11900
+ now,
11901
+ opId: `${utcStamp(now)}-${randomUUID().slice(0, 8)}`,
11902
+ withApplyLock: (fn) => withHostApplyLock(dshHome, tryLockExclusive, fn)
11903
+ };
11904
+ if (computeConfigFingerprint(policy) !== configFingerprint) {
11905
+ replyError(req.id, "STALE_PLAN", "session.prune.apply config fingerprint mismatch", {
11906
+ capability: "session.prune.apply",
11907
+ reason: "config-fingerprint"
11908
+ });
11909
+ return;
11910
+ }
11911
+ if (generatedAt > now + 1000 || now - generatedAt > maxPlanAgeMs) {
11912
+ replyError(req.id, "STALE_PLAN", "session.prune.apply plan is outside the max-age window", {
11913
+ capability: "session.prune.apply",
11914
+ reason: "max-age",
11915
+ maxPlanAgeMs
11916
+ });
11917
+ return;
11918
+ }
11919
+ try {
11920
+ const listing = await listAllSessions({ list: (request) => controller.list(request) });
11921
+ if (listing.truncated) {
11922
+ replyError(req.id, "BLOCKED", "session.prune.apply aborted: session.list roster is incomplete", {
11923
+ capability: "session.prune.apply",
11924
+ reason: "incomplete-roster",
11925
+ pages: listing.pages
11926
+ });
11927
+ return;
11928
+ }
11929
+ const freshPlan = await planSessionPrune(listing.rows, persistence, nodePruneFs, {
11930
+ retentionDays: policy.retentionDays,
11931
+ now,
11932
+ sessionsRoot,
11933
+ currentSessionId: binding?.sessionId,
11934
+ stagedIds,
11935
+ blankGraceDays: policy.blankGraceDays,
11936
+ lockGraceMs: policy.lockGraceMs,
11937
+ freshMtimeGraceMs: policy.freshMtimeGraceMs
11938
+ });
11939
+ const freshFingerprint = computePlanFingerprint(freshPlan);
11940
+ if (freshFingerprint !== fingerprint) {
11941
+ replyError(req.id, "STALE_PLAN", "session.prune.apply plan fingerprint mismatch", {
11942
+ capability: "session.prune.apply",
11943
+ reason: "plan-fingerprint"
11944
+ });
11945
+ return;
11946
+ }
11947
+ const result = await applyTrashPlan(nodeApplyFs, deps, freshPlan, {
11948
+ dshHome,
11949
+ sessionsRoot,
11950
+ planFingerprint: freshFingerprint
11951
+ });
11952
+ replyOk(req.id, { ...result });
11953
+ } catch (err) {
11954
+ const message = err instanceof Error ? err.message : String(err);
11955
+ logger.error("[dsh-opentui-bridge] session.prune.apply failed: %s", message);
11956
+ if (err instanceof ApplyError) {
11957
+ replyError(req.id, err.code, message, err.detail);
11958
+ return;
11959
+ }
11960
+ replyError(req.id, "INTERNAL", "session.prune.apply failed");
11961
+ }
11962
+ }
11963
+ async function handlePurgeSessionPrune(req) {
11964
+ const params = req.params;
11965
+ if (params === null || typeof params !== "object" || Array.isArray(params)) {
11966
+ replyError(req.id, "BAD_PARAMS", "session.prune.purge params must be an object");
11967
+ return;
11968
+ }
11969
+ const p = params;
11970
+ for (const key of [
11971
+ "entries",
11972
+ "retentionDays",
11973
+ "purgeRetentionDays",
11974
+ "tokenTtlMs",
11975
+ "sessionsRoot",
11976
+ "dshHome",
11977
+ "trashRoot",
11978
+ "path",
11979
+ "paths",
11980
+ "secret",
11981
+ "algorithm"
11982
+ ]) {
11983
+ if (p[key] !== undefined) {
11984
+ replyError(req.id, "BAD_PARAMS", `session.prune.purge ${key} is host-owned; clients may not set it`);
11985
+ return;
11986
+ }
11987
+ }
11988
+ if (p.phase !== "prepare" && p.phase !== "commit") {
11989
+ replyError(req.id, "BAD_PARAMS", "session.prune.purge phase must be 'prepare' or 'commit'");
11990
+ return;
11991
+ }
11992
+ if (p.phase === "commit" && (typeof p.token !== "string" || p.token === "")) {
11993
+ replyError(req.id, "BAD_PARAMS", "session.prune.purge commit requires the prepare token");
11994
+ return;
11995
+ }
11996
+ const persistence = resolvePrunePersistence(ctx);
11997
+ if (persistence === undefined) {
11998
+ replyError(req.id, "UNSUPPORTED", "sessionPersistence.stat unavailable: session.prune.purge requires stat capability", {
11999
+ capability: "session.prune.purge",
12000
+ service: "sessionPersistence"
12001
+ });
12002
+ return;
12003
+ }
12004
+ const controller = resolveSessionController(ctx);
12005
+ if (controller === undefined) {
12006
+ replyError(req.id, "UNSUPPORTED", "sessionController service unavailable: session.prune.purge requires session.list", {
12007
+ capability: "session.prune.purge",
12008
+ service: "sessionController"
12009
+ });
12010
+ return;
12011
+ }
12012
+ const tryLockExclusive = resolveFlockTryLockExclusive();
12013
+ if (tryLockExclusive === undefined) {
12014
+ replyError(req.id, "UNSUPPORTED", "flock capability unavailable: session.prune.purge requires tryLockExclusive", {
12015
+ capability: "session.prune.purge",
12016
+ service: "node-addon-system/flock",
12017
+ detail: "tryLockExclusive"
12018
+ });
12019
+ return;
12020
+ }
12021
+ try {
12022
+ const dshHome = resolvePruneDshHome(ctx, config);
12023
+ const hostPolicy = resolveHostPurgePolicy(ctx, config);
12024
+ const lockProbe = createPruneLockProbe(tryLockExclusive);
12025
+ const nodePurgeFs = {
12026
+ lstat,
12027
+ realpath,
12028
+ stat,
12029
+ readdir,
12030
+ readFile: (path) => readFile(path, "utf8"),
12031
+ readFileBuffer: (path) => readFile(path),
12032
+ writeFile: (path, data, options) => writeFile(path, data, options),
12033
+ appendFile,
12034
+ unlink,
12035
+ rmdir,
12036
+ mkdir: (path, options) => options?.recursive ? mkdir(path, { recursive: true, mode: options.mode }) : mkdir(path, { mode: options?.mode })
12037
+ };
12038
+ const now = Date.now();
12039
+ const deps = {
12040
+ persistence,
12041
+ lister: { list: (request) => controller.list(request) },
12042
+ lockProbe,
12043
+ now,
12044
+ opId: `${utcStamp(now)}-${randomUUID().slice(0, 8)}`,
12045
+ secret: await resolvePurgeSecret(nodePurgeFs, dshHome, () => randomUUID() + randomUUID()),
12046
+ retentionDays: hostPolicy.retentionDays,
12047
+ tokenTtlMs: hostPolicy.tokenTtlMs,
12048
+ newSecret: () => randomUUID() + randomUUID(),
12049
+ withApplyLock: (fn) => withHostApplyLock(dshHome, tryLockExclusive, fn)
12050
+ };
12051
+ if (p.phase === "prepare") {
12052
+ const result = await preparePurge(nodePurgeFs, deps, dshHome);
12053
+ replyOk(req.id, {
12054
+ opId: result.opId,
12055
+ candidates: result.candidates,
12056
+ rejected: result.rejected,
12057
+ token: result.token
12058
+ });
12059
+ return;
12060
+ }
12061
+ const result = await purgeTrashSessions(nodePurgeFs, deps, dshHome, p.token);
12062
+ replyOk(req.id, { ...result });
12063
+ } catch (err) {
12064
+ const message = err instanceof Error ? err.message : String(err);
12065
+ logger.error("[dsh-opentui-bridge] session.prune.purge failed: %s", message);
12066
+ if (err instanceof PurgeError) {
12067
+ replyError(req.id, err.code, message, err.detail);
12068
+ return;
12069
+ }
12070
+ const mapped = mapHostError(err);
12071
+ replyError(req.id, mapped.code, mapped.message, mapped.detail);
12072
+ }
12073
+ }
12074
+ async function handleRestoreSessionPrune(req) {
12075
+ const params = req.params;
12076
+ if (params === null || typeof params !== "object" || Array.isArray(params)) {
12077
+ replyError(req.id, "BAD_PARAMS", "session.prune.restore params must be an object");
12078
+ return;
12079
+ }
12080
+ const p = params;
12081
+ for (const key of [
12082
+ "entries",
12083
+ "path",
12084
+ "paths",
12085
+ "sessionsRoot",
12086
+ "dshHome",
12087
+ "trashRoot",
12088
+ "manifest",
12089
+ "root",
12090
+ "retentionDays"
12091
+ ]) {
12092
+ if (p[key] !== undefined) {
12093
+ replyError(req.id, "BAD_PARAMS", `session.prune.restore ${key} is host-owned; clients may not set it`);
12094
+ return;
12095
+ }
12096
+ }
12097
+ const phase = p.phase ?? "list";
12098
+ if (phase !== "list" && phase !== "restore") {
12099
+ replyError(req.id, "BAD_PARAMS", "session.prune.restore phase must be 'list' or 'restore'");
12100
+ return;
12101
+ }
12102
+ if (phase === "restore" && (typeof p.id !== "string" || p.id === "")) {
12103
+ replyError(req.id, "BAD_PARAMS", "session.prune.restore requires a non-empty id");
12104
+ return;
12105
+ }
12106
+ const persistence = resolvePrunePersistence(ctx);
12107
+ if (persistence === undefined) {
12108
+ replyError(req.id, "UNSUPPORTED", "sessionPersistence.stat unavailable: session.prune.restore requires stat capability", {
12109
+ capability: "session.prune.restore",
12110
+ service: "sessionPersistence"
12111
+ });
12112
+ return;
12113
+ }
12114
+ const controller = resolveSessionController(ctx);
12115
+ if (controller === undefined) {
12116
+ replyError(req.id, "UNSUPPORTED", "sessionController service unavailable: session.prune.restore requires session.list", {
12117
+ capability: "session.prune.restore",
12118
+ service: "sessionController"
12119
+ });
12120
+ return;
12121
+ }
12122
+ const tryLockExclusive = resolveFlockTryLockExclusive();
12123
+ if (tryLockExclusive === undefined) {
12124
+ replyError(req.id, "UNSUPPORTED", "flock capability unavailable: session.prune.restore requires tryLockExclusive", {
12125
+ capability: "session.prune.restore",
12126
+ service: "node-addon-system/flock",
12127
+ detail: "tryLockExclusive"
12128
+ });
12129
+ return;
12130
+ }
12131
+ try {
12132
+ const dshHome = resolvePruneDshHome(ctx, config);
12133
+ const sessionsRoot = resolvePruneSessionsRoot(ctx, config);
12134
+ const lockProbe = createPruneLockProbe(tryLockExclusive);
12135
+ const nodeRestoreFs = {
12136
+ lstat,
12137
+ realpath,
12138
+ stat,
12139
+ readdir,
12140
+ readFile: (path) => readFile(path, "utf8"),
12141
+ readFileBuffer: (path) => readFile(path),
12142
+ rename
12143
+ };
12144
+ const now = Date.now();
12145
+ const deps = {
12146
+ persistence,
12147
+ lister: { list: (request) => controller.list(request) },
12148
+ lockProbe,
12149
+ now,
12150
+ opId: `${utcStamp(now)}-${randomUUID().slice(0, 8)}`,
12151
+ sessionsRoot,
12152
+ withApplyLock: (fn) => withHostApplyLock(dshHome, tryLockExclusive, fn)
12153
+ };
12154
+ if (phase === "list") {
12155
+ const result = await listRestoreEntries(nodeRestoreFs, dshHome);
12156
+ replyOk(req.id, { entries: result.entries, rejected: result.rejected });
12157
+ return;
12158
+ }
12159
+ const result = await restoreTrashEntry(nodeRestoreFs, deps, dshHome, p.id);
12160
+ replyOk(req.id, { ...result });
12161
+ } catch (err) {
12162
+ const message = err instanceof Error ? err.message : String(err);
12163
+ logger.error("[dsh-opentui-bridge] session.prune.restore failed: %s", message);
12164
+ if (err instanceof RestoreError) {
12165
+ replyError(req.id, err.code, message, err.detail);
12166
+ return;
12167
+ }
12168
+ replyError(req.id, "INTERNAL", "session.prune.restore failed");
12169
+ }
12170
+ }
9662
12171
  async function reconcileSubagentIndex() {
9663
12172
  const controller = resolveSessionController(ctx);
9664
12173
  if (controller === undefined) {
@@ -9858,6 +12367,22 @@ function apply(ctx, config) {
9858
12367
  await handleListSessions(req);
9859
12368
  return;
9860
12369
  }
12370
+ if (req.method === "session.prune.plan") {
12371
+ await handlePlanSessionPrune(req);
12372
+ return;
12373
+ }
12374
+ if (req.method === "session.prune.apply") {
12375
+ await handleApplySessionPrune(req);
12376
+ return;
12377
+ }
12378
+ if (req.method === "session.prune.purge") {
12379
+ await handlePurgeSessionPrune(req);
12380
+ return;
12381
+ }
12382
+ if (req.method === "session.prune.restore") {
12383
+ await handleRestoreSessionPrune(req);
12384
+ return;
12385
+ }
9861
12386
  const sessionQueryMethodId = CAP_SESSION_QUERY_WIRE_METHODS[req.method];
9862
12387
  if (sessionQueryMethodId !== undefined) {
9863
12388
  try {
@@ -10171,11 +12696,13 @@ export {
10171
12696
  isAskErrorCode,
10172
12697
  name,
10173
12698
  probeAgentProgressResidue,
12699
+ probeAgentTranscriptResidue,
10174
12700
  probeOwnedAbortRelease,
10175
12701
  projectAccountScalarResult,
10176
12702
  projectAccountViewForFrame,
10177
12703
  redactIdentifier,
10178
12704
  resolveAskDeadlineMs,
12705
+ resolveMaxAskWaitMs,
10179
12706
  sanitizeFrameForWire,
10180
12707
  summarizeAnswers,
10181
12708
  turnIdOf,