@aiwayds/dsh-opentui 0.28.2 → 0.29.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 = {
@@ -1147,145 +1149,1924 @@ function getSubagentIndex(ctx) {
1147
1149
  return index;
1148
1150
  }
1149
1151
 
1150
- // ../bridge/src/settings-adapter.ts
1151
- var NS_FIELDS = ["ns", "revision", "schema", "value", "base", "user", "applies", "secrets"];
1152
- function isObject(v) {
1153
- return v !== null && typeof v === "object" && !Array.isArray(v);
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;
1154
1174
  }
1155
- function projectNamespace(raw) {
1156
- if (!isObject(raw))
1157
- return {};
1158
- const out = {};
1159
- for (const key of NS_FIELDS) {
1160
- if (key === "secrets") {
1161
- const secrets = raw.secrets;
1162
- if (Array.isArray(secrets)) {
1163
- out.secrets = secrets.filter(isObject).map((s) => ({ path: s.path, set: s.set }));
1164
- }
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 === "")
1165
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);
1166
1258
  }
1167
- if (key in raw)
1168
- out[key] = raw[key];
1169
1259
  }
1170
- return out;
1260
+ return rows.some((row) => row.running === true && typeof row.sessionId === "string" && row.sessionId.startsWith(id + "/"));
1171
1261
  }
1172
- function extractNamespaces(result) {
1173
- if (Array.isArray(result))
1174
- return result;
1175
- if (isObject(result) && Array.isArray(result.namespaces))
1176
- return result.namespaces;
1177
- return [];
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 } : {} };
1178
1264
  }
1179
- function adaptSettingsForms(settings) {
1180
- if (!isObject(settings))
1181
- return;
1182
- const host = settings;
1183
- return {
1184
- describe: async () => {
1185
- if (typeof host.describe !== "function") {
1186
- throw new Error("HOST_UNAVAILABLE: settings.describe is not available on the inproc host");
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;
1187
1354
  }
1188
- const result = await host.describe({ redactSecrets: true });
1189
- return {
1190
- writable: typeof host.writable === "boolean" ? host.writable : false,
1191
- hasDocument: true,
1192
- namespaces: extractNamespaces(result).map(projectNamespace)
1193
- };
1194
- },
1195
- mutate: async (ns, ops, expectedRevision) => {
1196
- if (typeof host.mutate !== "function") {
1197
- throw new Error("HOST_UNAVAILABLE: settings.mutate is not available on the inproc host");
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;
1198
1398
  }
1199
- return host.mutate(ns, ops, expectedRevision);
1200
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 }
1201
1439
  };
1202
1440
  }
1203
- // ../../ledger/ledger.json
1204
- var ledger_default = {
1205
- attribution: "Derived from deepseek-ai/deepseek-harness (MIT, Copyright (c) 2026 DeepSeek)",
1206
- schema: "dsh-opentui.ledger/1",
1207
- generated_by: "scripts/gen-ledger.mjs",
1208
- inputs: [
1209
- "capir/capir.json",
1210
- "ledger/provenance.json"
1211
- ],
1212
- dimensions: {
1213
- full: {
1214
- artifacts: 43,
1215
- methods: 257,
1216
- by_kind: {
1217
- unary: 226,
1218
- stream: 31
1219
- },
1220
- by_class: {
1221
- W: 257
1222
- },
1223
- endpoints_session_controller: 27,
1224
- endpoints_global_map_sum: 257
1225
- },
1226
- expected: {
1227
- profile: "opentui-inproc",
1228
- count: 75,
1229
- contribution_packages: [
1230
- "@deepseek-ai/dsh-agent-team",
1231
- "@deepseek-ai/dsh-api-remote-access",
1232
- "@deepseek-ai/dsh-command-feedback",
1233
- "@deepseek-ai/dsh-commands",
1234
- "@deepseek-ai/dsh-deepseek-account",
1235
- "@deepseek-ai/dsh-goal",
1236
- "@deepseek-ai\u002fdsh-llm",
1237
- "@deepseek-ai/dsh-permission-presets",
1238
- "@deepseek-ai/dsh-plugin-manager",
1239
- "@deepseek-ai/dsh-subagent",
1240
- "@deepseek-ai/dsh-user-questions",
1241
- "@deepseek-ai/dsh-web",
1242
- "@deepseek-ai/dsh-api-session-controller"
1243
- ],
1244
- exclusions: [
1245
- {
1246
- id: "@deepseek-ai/dsh-permission-presets#permissionPresets/set",
1247
- mapping_kind: "method-level environment correction (host rc.4 vs CapIR rc.5)"
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" };
1248
1514
  }
1249
- ],
1250
- method_ids: [
1251
- "@deepseek-ai/dsh-agent-team#agentTeams/setEnabled",
1252
- "@deepseek-ai/dsh-api-remote-access#remoteAccess/follow",
1253
- "@deepseek-ai/dsh-api-session-controller#fileReferences/list",
1254
- "@deepseek-ai/dsh-api-session-controller#session/attachment",
1255
- "@deepseek-ai/dsh-api-session-controller#session/canOpenWorkspacePath",
1256
- "@deepseek-ai/dsh-api-session-controller#session/cancel",
1257
- "@deepseek-ai/dsh-api-session-controller#session/control",
1258
- "@deepseek-ai/dsh-api-session-controller#session/create",
1259
- "@deepseek-ai/dsh-api-session-controller#session/events",
1260
- "@deepseek-ai/dsh-api-session-controller#session/follow",
1261
- "@deepseek-ai/dsh-api-session-controller#session/fork",
1262
- "@deepseek-ai/dsh-api-session-controller#session/initializeDefaultModel",
1263
- "@deepseek-ai/dsh-api-session-controller#session/list",
1264
- "@deepseek-ai/dsh-api-session-controller#session/modelCatalog",
1265
- "@deepseek-ai/dsh-api-session-controller#session/observeEvent",
1266
- "@deepseek-ai/dsh-api-session-controller#session/observeProjections",
1267
- "@deepseek-ai/dsh-api-session-controller#session/observeState",
1268
- "@deepseek-ai/dsh-api-session-controller#session/openWorkspacePath",
1269
- "@deepseek-ai/dsh-api-session-controller#session/page",
1270
- "@deepseek-ai/dsh-api-session-controller#session/projections",
1271
- "@deepseek-ai/dsh-api-session-controller#session/prompt",
1272
- "@deepseek-ai/dsh-api-session-controller#session/rename",
1273
- "@deepseek-ai/dsh-api-session-controller#session/search",
1274
- "@deepseek-ai/dsh-api-session-controller#session/selectModel",
1275
- "@deepseek-ai/dsh-api-session-controller#session/state",
1276
- "@deepseek-ai/dsh-api-session-controller#session/updateQueue",
1277
- "@deepseek-ai/dsh-api-session-controller#session/wait",
1278
- "@deepseek-ai/dsh-api-session-controller#session/workspacePathApplications",
1279
- "@deepseek-ai/dsh-api-session-controller#skills/list",
1280
- "@deepseek-ai/dsh-command-feedback#sessionFeedback/record",
1281
- "@deepseek-ai/dsh-commands#commands/execute",
1282
- "@deepseek-ai/dsh-commands#commands/list",
1283
- "@deepseek-ai/dsh-deepseek-account#account/cancelSignIn",
1284
- "@deepseek-ai/dsh-deepseek-account#account/getBalance",
1285
- "@deepseek-ai/dsh-deepseek-account#account/getNotificationContent",
1286
- "@deepseek-ai/dsh-deepseek-account#account/getNotifications",
1287
- "@deepseek-ai/dsh-deepseek-account#account/getProfile",
1288
- "@deepseek-ai/dsh-deepseek-account#account/getState",
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
+ });
2929
+ }
2930
+
2931
+ // ../bridge/src/settings-adapter.ts
2932
+ var NS_FIELDS = ["ns", "revision", "schema", "value", "base", "user", "applies", "secrets"];
2933
+ function isObject(v) {
2934
+ return v !== null && typeof v === "object" && !Array.isArray(v);
2935
+ }
2936
+ function projectNamespace(raw) {
2937
+ if (!isObject(raw))
2938
+ return {};
2939
+ const out = {};
2940
+ for (const key of NS_FIELDS) {
2941
+ if (key === "secrets") {
2942
+ const secrets = raw.secrets;
2943
+ if (Array.isArray(secrets)) {
2944
+ out.secrets = secrets.filter(isObject).map((s) => ({ path: s.path, set: s.set }));
2945
+ }
2946
+ continue;
2947
+ }
2948
+ if (key in raw)
2949
+ out[key] = raw[key];
2950
+ }
2951
+ return out;
2952
+ }
2953
+ function extractNamespaces(result) {
2954
+ if (Array.isArray(result))
2955
+ return result;
2956
+ if (isObject(result) && Array.isArray(result.namespaces))
2957
+ return result.namespaces;
2958
+ return [];
2959
+ }
2960
+ function adaptSettingsForms(settings) {
2961
+ if (!isObject(settings))
2962
+ return;
2963
+ const host = settings;
2964
+ return {
2965
+ describe: async () => {
2966
+ if (typeof host.describe !== "function") {
2967
+ throw new Error("HOST_UNAVAILABLE: settings.describe is not available on the inproc host");
2968
+ }
2969
+ const result = await host.describe({ redactSecrets: true });
2970
+ return {
2971
+ writable: typeof host.writable === "boolean" ? host.writable : false,
2972
+ hasDocument: true,
2973
+ namespaces: extractNamespaces(result).map(projectNamespace)
2974
+ };
2975
+ },
2976
+ mutate: async (ns, ops, expectedRevision) => {
2977
+ if (typeof host.mutate !== "function") {
2978
+ throw new Error("HOST_UNAVAILABLE: settings.mutate is not available on the inproc host");
2979
+ }
2980
+ return host.mutate(ns, ops, expectedRevision);
2981
+ }
2982
+ };
2983
+ }
2984
+ // ../../ledger/ledger.json
2985
+ var ledger_default = {
2986
+ attribution: "Derived from deepseek-ai/deepseek-harness (MIT, Copyright (c) 2026 DeepSeek)",
2987
+ schema: "dsh-opentui.ledger/1",
2988
+ generated_by: "scripts/gen-ledger.mjs",
2989
+ inputs: [
2990
+ "capir/capir.json",
2991
+ "ledger/provenance.json"
2992
+ ],
2993
+ dimensions: {
2994
+ full: {
2995
+ artifacts: 43,
2996
+ methods: 257,
2997
+ by_kind: {
2998
+ unary: 226,
2999
+ stream: 31
3000
+ },
3001
+ by_class: {
3002
+ W: 257
3003
+ },
3004
+ endpoints_session_controller: 27,
3005
+ endpoints_global_map_sum: 257
3006
+ },
3007
+ expected: {
3008
+ profile: "opentui-inproc",
3009
+ count: 75,
3010
+ contribution_packages: [
3011
+ "@deepseek-ai/dsh-agent-team",
3012
+ "@deepseek-ai/dsh-api-remote-access",
3013
+ "@deepseek-ai/dsh-command-feedback",
3014
+ "@deepseek-ai/dsh-commands",
3015
+ "@deepseek-ai/dsh-deepseek-account",
3016
+ "@deepseek-ai/dsh-goal",
3017
+ "@deepseek-ai\u002fdsh-llm",
3018
+ "@deepseek-ai/dsh-permission-presets",
3019
+ "@deepseek-ai/dsh-plugin-manager",
3020
+ "@deepseek-ai/dsh-subagent",
3021
+ "@deepseek-ai/dsh-user-questions",
3022
+ "@deepseek-ai/dsh-web",
3023
+ "@deepseek-ai/dsh-api-session-controller"
3024
+ ],
3025
+ exclusions: [
3026
+ {
3027
+ id: "@deepseek-ai/dsh-permission-presets#permissionPresets/set",
3028
+ mapping_kind: "method-level environment correction (host rc.4 vs CapIR rc.5)"
3029
+ }
3030
+ ],
3031
+ method_ids: [
3032
+ "@deepseek-ai/dsh-agent-team#agentTeams/setEnabled",
3033
+ "@deepseek-ai/dsh-api-remote-access#remoteAccess/follow",
3034
+ "@deepseek-ai/dsh-api-session-controller#fileReferences/list",
3035
+ "@deepseek-ai/dsh-api-session-controller#session/attachment",
3036
+ "@deepseek-ai/dsh-api-session-controller#session/canOpenWorkspacePath",
3037
+ "@deepseek-ai/dsh-api-session-controller#session/cancel",
3038
+ "@deepseek-ai/dsh-api-session-controller#session/control",
3039
+ "@deepseek-ai/dsh-api-session-controller#session/create",
3040
+ "@deepseek-ai/dsh-api-session-controller#session/events",
3041
+ "@deepseek-ai/dsh-api-session-controller#session/follow",
3042
+ "@deepseek-ai/dsh-api-session-controller#session/fork",
3043
+ "@deepseek-ai/dsh-api-session-controller#session/initializeDefaultModel",
3044
+ "@deepseek-ai/dsh-api-session-controller#session/list",
3045
+ "@deepseek-ai/dsh-api-session-controller#session/modelCatalog",
3046
+ "@deepseek-ai/dsh-api-session-controller#session/observeEvent",
3047
+ "@deepseek-ai/dsh-api-session-controller#session/observeProjections",
3048
+ "@deepseek-ai/dsh-api-session-controller#session/observeState",
3049
+ "@deepseek-ai/dsh-api-session-controller#session/openWorkspacePath",
3050
+ "@deepseek-ai/dsh-api-session-controller#session/page",
3051
+ "@deepseek-ai/dsh-api-session-controller#session/projections",
3052
+ "@deepseek-ai/dsh-api-session-controller#session/prompt",
3053
+ "@deepseek-ai/dsh-api-session-controller#session/rename",
3054
+ "@deepseek-ai/dsh-api-session-controller#session/search",
3055
+ "@deepseek-ai/dsh-api-session-controller#session/selectModel",
3056
+ "@deepseek-ai/dsh-api-session-controller#session/state",
3057
+ "@deepseek-ai/dsh-api-session-controller#session/updateQueue",
3058
+ "@deepseek-ai/dsh-api-session-controller#session/wait",
3059
+ "@deepseek-ai/dsh-api-session-controller#session/workspacePathApplications",
3060
+ "@deepseek-ai/dsh-api-session-controller#skills/list",
3061
+ "@deepseek-ai/dsh-command-feedback#sessionFeedback/record",
3062
+ "@deepseek-ai/dsh-commands#commands/execute",
3063
+ "@deepseek-ai/dsh-commands#commands/list",
3064
+ "@deepseek-ai/dsh-deepseek-account#account/cancelSignIn",
3065
+ "@deepseek-ai/dsh-deepseek-account#account/getBalance",
3066
+ "@deepseek-ai/dsh-deepseek-account#account/getNotificationContent",
3067
+ "@deepseek-ai/dsh-deepseek-account#account/getNotifications",
3068
+ "@deepseek-ai/dsh-deepseek-account#account/getProfile",
3069
+ "@deepseek-ai/dsh-deepseek-account#account/getState",
1289
3070
  "@deepseek-ai/dsh-deepseek-account#account/hasRunningAccountTasks",
1290
3071
  "@deepseek-ai/dsh-deepseek-account#account/reportNotificationEvent",
1291
3072
  "@deepseek-ai/dsh-deepseek-account#account/signOut",
@@ -1327,75 +3108,110 @@ var ledger_default = {
1327
3108
  },
1328
3109
  wired_protocol: {
1329
3110
  mark: "bridge-protocol (ADR-0010)",
1330
- count: 10,
3111
+ count: 15,
1331
3112
  methods: [
1332
3113
  {
1333
3114
  method: "bridge.ping",
1334
3115
  kind: "meta",
1335
- source_line: 2247,
3116
+ source_line: 5747,
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: 5756,
3124
+ capir_id: null,
3125
+ note: "protocol version negotiation (no host call)"
3126
+ },
3127
+ {
3128
+ method: "session.prune.plan",
3129
+ kind: "business",
3130
+ source_line: 5790,
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: 5796,
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: 5802,
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: 5808,
1343
3152
  capir_id: null,
1344
- note: "protocol version negotiation (no host call)"
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"
1345
3154
  },
1346
3155
  {
1347
3156
  method: "subagents.interrupt",
1348
3157
  kind: "business",
1349
- source_line: 2300,
3158
+ source_line: 5875,
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: 5879,
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: 5883,
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: 5887,
1371
3180
  capir_id: null,
1372
3181
  note: "single in-flight turn state machine + streaming turn"
1373
3182
  },
3183
+ {
3184
+ method: "session.steer",
3185
+ kind: "business",
3186
+ source_line: 5891,
3187
+ capir_id: null,
3188
+ note: "029 A: bridge-owned steer into the running turn; accepts only a live non-aborting turn with agent.status==='running', calls agent.steer(createBridgeUserMessage(text)) directly, no turn id / inFlightTurnId / turn.start, no followup downgrade; typed STEER_IDLE / STEER_ENDED / STEER_ABORTING rejections never reach the host"
3189
+ },
1374
3190
  {
1375
3191
  method: "session.close",
1376
3192
  kind: "business",
1377
- source_line: 2316,
3193
+ source_line: 5895,
1378
3194
  capir_id: null,
1379
3195
  note: "binding dispose"
1380
3196
  },
1381
3197
  {
1382
3198
  method: "turn.abort",
1383
3199
  kind: "business",
1384
- source_line: 2320,
3200
+ source_line: 5899,
1385
3201
  capir_id: null,
1386
3202
  note: "turn state machine + terminalTurnIds FIFO idempotency + fire-and-forget agent.cancel"
1387
3203
  },
1388
3204
  {
1389
3205
  method: "ask.response",
1390
3206
  kind: "business",
1391
- source_line: 2324,
3207
+ source_line: 5903,
1392
3208
  capir_id: null,
1393
3209
  note: "bridge-internal AskRegistry settlement (no host call)"
1394
3210
  },
1395
3211
  {
1396
3212
  method: "journal.replay",
1397
3213
  kind: "business",
1398
- source_line: 2328,
3214
+ source_line: 5907,
1399
3215
  capir_id: null,
1400
3216
  note: "I-class persistence read (persistence.open(id,'read')); no same-name CapIR id"
1401
3217
  }
@@ -7812,18 +9628,18 @@ function getAskRegistry(ctx) {
7812
9628
  var PROTOCOL_VERSION = 1;
7813
9629
  var STDIO_SWITCH = "DSH_OPENTUI_BRIDGE_STDIO";
7814
9630
  var CAP_SMOKE_SWITCH = "DSH_OPENTUI_CAP_SMOKE";
7815
- var BRIDGE_CAPABILITIES = ["subagents.interrupt", "subagents.stopChildren"];
9631
+ var BRIDGE_CAPABILITIES = ["subagents.interrupt", "subagents.stopChildren", "session.steer"];
7816
9632
  var TERMINAL_TURN_ID_LIMIT = 64;
7817
9633
  function findPackageVersion(entryFile, wantedName) {
7818
9634
  try {
7819
- let dir = dirname(realpathSync(entryFile));
7820
- for (let i = 0;i < 12 && dir !== dirname(dir); i++) {
9635
+ let dir = dirname4(realpathSync2(entryFile));
9636
+ for (let i = 0;i < 12 && dir !== dirname4(dir); i++) {
7821
9637
  try {
7822
- const pkg = JSON.parse(readFileSync2(join2(dir, "package.json"), "utf8"));
9638
+ const pkg = JSON.parse(readFileSync2(join6(dir, "package.json"), "utf8"));
7823
9639
  if (pkg?.name === wantedName && typeof pkg.version === "string")
7824
9640
  return pkg.version;
7825
9641
  } catch {}
7826
- dir = dirname(dir);
9642
+ dir = dirname4(dir);
7827
9643
  }
7828
9644
  } catch {}
7829
9645
  return;
@@ -7844,7 +9660,7 @@ function readHostVersion() {
7844
9660
  return v;
7845
9661
  }
7846
9662
  try {
7847
- const req = createRequire(import.meta.url);
9663
+ const req = createRequire2(import.meta.url);
7848
9664
  const path = req.resolve("@deepseek-ai/dsh/package.json");
7849
9665
  const pkg = JSON.parse(readFileSync2(path, "utf8"));
7850
9666
  if (typeof pkg.version === "string")
@@ -7867,6 +9683,118 @@ function resolvePersistence(ctx) {
7867
9683
  const svc = fromGet ?? ctx.sessionPersistence;
7868
9684
  return svc !== undefined && typeof svc.open === "function" ? svc : undefined;
7869
9685
  }
9686
+ function resolvePrunePersistence(ctx) {
9687
+ const base = resolvePersistence(ctx);
9688
+ return base !== undefined && hasStatCapability(base) ? base : undefined;
9689
+ }
9690
+ function resolvePruneSessionsRoot(ctx, config) {
9691
+ const fromConfig = config !== null && typeof config === "object" ? config : {};
9692
+ if (typeof fromConfig.sessionsRoot === "string" && fromConfig.sessionsRoot !== "")
9693
+ return fromConfig.sessionsRoot;
9694
+ if (typeof fromConfig.dshHome === "string" && fromConfig.dshHome !== "")
9695
+ return join6(fromConfig.dshHome, "sessions");
9696
+ try {
9697
+ const hostConfig = typeof ctx.get === "function" ? ctx.get("config") : undefined;
9698
+ if (hostConfig !== null && typeof hostConfig === "object") {
9699
+ const hc = hostConfig;
9700
+ if (typeof hc.sessionsRoot === "string" && hc.sessionsRoot !== "")
9701
+ return hc.sessionsRoot;
9702
+ if (typeof hc.dshHome === "string" && hc.dshHome !== "")
9703
+ return join6(hc.dshHome, "sessions");
9704
+ }
9705
+ } catch {}
9706
+ return join6(process.env.DSH_HOME || join6(homedir2(), ".dsh"), "sessions");
9707
+ }
9708
+ function resolvePruneDshHome(ctx, config) {
9709
+ const fromConfig = config !== null && typeof config === "object" ? config : {};
9710
+ if (typeof fromConfig.dshHome === "string" && fromConfig.dshHome !== "")
9711
+ return fromConfig.dshHome;
9712
+ try {
9713
+ const hostConfig = typeof ctx.get === "function" ? ctx.get("config") : undefined;
9714
+ if (hostConfig !== null && typeof hostConfig === "object") {
9715
+ const hc = hostConfig;
9716
+ if (typeof hc.dshHome === "string" && hc.dshHome !== "")
9717
+ return hc.dshHome;
9718
+ }
9719
+ } catch {}
9720
+ return process.env.DSH_HOME || join6(homedir2(), ".dsh");
9721
+ }
9722
+ function resolveHostProfileConfig(ctx) {
9723
+ try {
9724
+ const profile = typeof ctx.get === "function" ? ctx.get("profileContext") : undefined;
9725
+ const dir = profile !== null && typeof profile === "object" ? profile.dir : undefined;
9726
+ if (typeof dir !== "string" || dir === "")
9727
+ return;
9728
+ const parsed = JSON.parse(readFileSync2(join6(dir, "config.json"), "utf8"));
9729
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : undefined;
9730
+ } catch {
9731
+ return;
9732
+ }
9733
+ }
9734
+ function resolveHostPrunePolicy(ctx, config, sessionsRoot) {
9735
+ const fromConfig = config !== null && typeof config === "object" ? config : {};
9736
+ const hostConfig = (() => {
9737
+ try {
9738
+ const value = typeof ctx.get === "function" ? ctx.get("config") : undefined;
9739
+ return value !== null && typeof value === "object" ? value : {};
9740
+ } catch {
9741
+ return {};
9742
+ }
9743
+ })();
9744
+ const profileConfig = resolveHostProfileConfig(ctx);
9745
+ const numberFrom = (key, fallback, min, max) => {
9746
+ for (const source of [profileConfig, hostConfig, fromConfig]) {
9747
+ if (source === undefined)
9748
+ continue;
9749
+ const value = source[key];
9750
+ if (typeof value === "number" && Number.isFinite(value) && value >= min && value <= max)
9751
+ return value;
9752
+ }
9753
+ return fallback;
9754
+ };
9755
+ const retentionDays = numberFrom("retentionDays", DEFAULT_RETENTION_DAYS, 0, 3650);
9756
+ const blankGraceDays = numberFrom("blankGraceDays", 30, 0, 3650);
9757
+ const lockGraceMs = numberFrom("lockGraceMs", 300000, 0, 86400000);
9758
+ const freshMtimeGraceMs = numberFrom("freshMtimeGraceMs", lockGraceMs, 0, 86400000);
9759
+ return { retentionDays, blankGraceDays, lockGraceMs, freshMtimeGraceMs, sessionsRoot };
9760
+ }
9761
+ function resolveHostPurgePolicy(ctx, config) {
9762
+ const fromConfig = config !== null && typeof config === "object" ? config : {};
9763
+ const hostConfig = (() => {
9764
+ try {
9765
+ const value = typeof ctx.get === "function" ? ctx.get("config") : undefined;
9766
+ return value !== null && typeof value === "object" ? value : {};
9767
+ } catch {
9768
+ return {};
9769
+ }
9770
+ })();
9771
+ const numberFrom = (key, fallback, min, max) => {
9772
+ for (const source of [fromConfig, hostConfig]) {
9773
+ const value = source[key];
9774
+ if (typeof value === "number" && Number.isFinite(value) && value >= min && value <= max)
9775
+ return value;
9776
+ }
9777
+ return fallback;
9778
+ };
9779
+ return {
9780
+ retentionDays: numberFrom("purgeRetentionDays", DEFAULT_PURGE_RETENTION_DAYS, 0, 3650),
9781
+ tokenTtlMs: numberFrom("purgeTokenTtlMs", 120000, 1, 86400000)
9782
+ };
9783
+ }
9784
+ async function withHostApplyLock(dshHome, tryLockExclusive, fn) {
9785
+ const root = trashRoot(dshHome);
9786
+ await mkdir(root, { recursive: true, mode: 448 });
9787
+ const path = join6(root, ".apply.lock");
9788
+ const handle = await open2(path, "w", 384);
9789
+ try {
9790
+ await tryLockExclusive(handle.fd);
9791
+ return await fn();
9792
+ } finally {
9793
+ try {
9794
+ await handle.close();
9795
+ } catch {}
9796
+ }
9797
+ }
7870
9798
  var cachedAppendPluginRecord;
7871
9799
  var appendPluginRecordResolved = false;
7872
9800
  function resolveAppendPluginRecord() {
@@ -7876,12 +9804,12 @@ function resolveAppendPluginRecord() {
7876
9804
  const roots = [import.meta.url];
7877
9805
  if (process.argv[1]) {
7878
9806
  try {
7879
- roots.push(realpathSync(process.argv[1]));
9807
+ roots.push(realpathSync2(process.argv[1]));
7880
9808
  } catch {}
7881
9809
  }
7882
9810
  for (const root of roots) {
7883
9811
  try {
7884
- const req = createRequire(root);
9812
+ const req = createRequire2(root);
7885
9813
  const mod = req("@deepseek-ai/dsh-session");
7886
9814
  if (typeof mod.appendPluginRecord === "function") {
7887
9815
  cachedAppendPluginRecord = mod.appendPluginRecord;
@@ -8084,10 +10012,23 @@ function resolveAskDeadlineMs(raw, maxAskWaitMs = DEFAULT_MAX_ASK_WAIT_MS, warn
8084
10012
  }
8085
10013
  return raw;
8086
10014
  }
10015
+ function resolveMaxAskWaitMs(raw, cap = DEFAULT_MAX_ASK_WAIT_MS, warn = () => {}) {
10016
+ if (raw === undefined || raw === null)
10017
+ return cap;
10018
+ if (typeof raw !== "number" || !Number.isInteger(raw) || raw <= 0 || raw > cap) {
10019
+ warn("[dsh-opentui-bridge] invalid maxAskWaitMs %s ignored (using hard cap %d)", String(raw), cap);
10020
+ return cap;
10021
+ }
10022
+ return raw;
10023
+ }
8087
10024
  var agentProgressResidues = new WeakMap;
8088
10025
  function probeAgentProgressResidue(ctx) {
8089
10026
  return agentProgressResidues.get(ctx)?.();
8090
10027
  }
10028
+ var agentTranscriptResidues = new WeakMap;
10029
+ function probeAgentTranscriptResidue(ctx) {
10030
+ return agentTranscriptResidues.get(ctx)?.();
10031
+ }
8091
10032
  function apply(ctx, config) {
8092
10033
  const logger = ctx.logger;
8093
10034
  if (process.env[STDIO_SWITCH] !== "1") {
@@ -8153,7 +10094,7 @@ function apply(ctx, config) {
8153
10094
  catalog: "@deepseek-ai/dsh-api-session-controller#session/modelCatalog",
8154
10095
  select: "@deepseek-ai/dsh-api-session-controller#session/selectModel",
8155
10096
  initDefault: "@deepseek-ai/dsh-api-session-controller#session/initializeDefaultModel",
8156
- unwired: "@deepseek-ai/dsh-api-session-controller#session/create"
10097
+ unwired: "@deepseek-ai/dsh-api-session-controller#session/control"
8157
10098
  };
8158
10099
  const invoke = createCapInvoke(ctx);
8159
10100
  const probe = async (id, params) => {
@@ -8506,6 +10447,7 @@ function apply(ctx, config) {
8506
10447
  childProgress: childProgress.size,
8507
10448
  progressSentFp: progressSentFp.size
8508
10449
  }));
10450
+ agentTranscriptResidues.set(ctx, () => ({ childTranscripts: childTranscripts.size }));
8509
10451
  function flushProgress(childId) {
8510
10452
  const snap = progressPending.get(childId);
8511
10453
  if (snap === undefined)
@@ -8549,6 +10491,80 @@ function apply(ctx, config) {
8549
10491
  progressPending.clear();
8550
10492
  progressSentFp.clear();
8551
10493
  childProgress.clear();
10494
+ clearTranscriptState();
10495
+ }
10496
+ const childTranscripts = new Map;
10497
+ const MAX_PENDING_TOOL_CALLS = 64;
10498
+ const childTranscriptRunIds = new Map;
10499
+ function transcriptTurnId() {
10500
+ return inFlightTurnId ?? "";
10501
+ }
10502
+ function childTranscriptRunId(childId) {
10503
+ const fromSpawn = childTranscriptRunIds.get(childId);
10504
+ if (fromSpawn !== undefined && fromSpawn !== "")
10505
+ return fromSpawn;
10506
+ const indexed = getSubagentIndex(ctx).get(childId);
10507
+ return indexed !== undefined && indexed.startedAt > 0 ? `child@${indexed.startedAt}` : "";
10508
+ }
10509
+ function childTranscriptState(childId) {
10510
+ let st = childTranscripts.get(childId);
10511
+ const turnId = transcriptTurnId();
10512
+ if (st === undefined || st.turnId !== turnId) {
10513
+ st = { turnId, seq: 0, pending: [], toolCalls: new Map };
10514
+ childTranscripts.set(childId, st);
10515
+ }
10516
+ return st;
10517
+ }
10518
+ function flushTranscript(childId) {
10519
+ const st = childTranscripts.get(childId);
10520
+ if (st === undefined || st.pending.length === 0 || binding === undefined)
10521
+ return;
10522
+ const rows = st.pending.splice(0);
10523
+ emitEvent("agent.transcript", {
10524
+ turnId: st.turnId,
10525
+ sessionId: binding.sessionId,
10526
+ childId,
10527
+ runId: childTranscriptRunId(childId),
10528
+ seq: st.seq,
10529
+ rows
10530
+ });
10531
+ st.seq += 1;
10532
+ }
10533
+ function flushTranscriptNow(childId) {
10534
+ flushTranscript(childId);
10535
+ const st = childTranscripts.get(childId);
10536
+ if (st !== undefined)
10537
+ st.toolCalls.clear();
10538
+ }
10539
+ function flushAllTranscript() {
10540
+ for (const childId of [...childTranscripts.keys()])
10541
+ flushTranscriptNow(childId);
10542
+ }
10543
+ function clearTranscriptState() {
10544
+ childTranscripts.clear();
10545
+ childTranscriptRunIds.clear();
10546
+ }
10547
+ function clearChildTranscript(childId) {
10548
+ childTranscripts.delete(childId);
10549
+ }
10550
+ function noteChildTranscriptRow(childId, row) {
10551
+ if (binding === undefined || childId === "" || childId === binding.sessionId)
10552
+ return;
10553
+ const indexed = getSubagentIndex(ctx).get(childId);
10554
+ if (indexed === undefined || indexed.parentSessionId !== binding.sessionId || indexed.status === "settled")
10555
+ return;
10556
+ const st = childTranscriptState(childId);
10557
+ st.pending.push(row);
10558
+ flushTranscript(childId);
10559
+ }
10560
+ function assistantMessageText(data) {
10561
+ const message = data.message !== null && typeof data.message === "object" ? data.message : undefined;
10562
+ const content = message?.content ?? data.content ?? message?.text ?? data.text;
10563
+ if (typeof content === "string")
10564
+ return content;
10565
+ if (Array.isArray(content))
10566
+ return contentText(content);
10567
+ return "";
8552
10568
  }
8553
10569
  function noteChildProgress(childId, roundsDelta, textDelta, lastLineOverride) {
8554
10570
  if (binding === undefined || childId === "" || childId === binding.sessionId)
@@ -8674,10 +10690,13 @@ function apply(ctx, config) {
8674
10690
  logger.warn("[dsh-opentui-bridge] ask journal append failed (decision unchanged): %s", err);
8675
10691
  }
8676
10692
  }
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));
10693
+ const configObject = config !== null && typeof config === "object" ? config : undefined;
10694
+ const maxAskWaitMs = resolveMaxAskWaitMs(configObject?.maxAskWaitMs, DEFAULT_MAX_ASK_WAIT_MS, (fmt, ...params) => logger.warn(fmt, ...params));
10695
+ const askDeadlineMsRaw = configObject?.askDeadlineMs;
10696
+ const askDeadlineMs = resolveAskDeadlineMs(askDeadlineMsRaw, maxAskWaitMs, (fmt, ...params) => logger.warn(fmt, ...params));
8679
10697
  const ask = new AskRegistry({
8680
10698
  askDeadlineMs,
10699
+ maxAskWaitMs,
8681
10700
  logger,
8682
10701
  journal: writeAskJournal,
8683
10702
  sink: (frame) => {
@@ -8930,6 +10949,7 @@ function apply(ctx, config) {
8930
10949
  if (!childId)
8931
10950
  return;
8932
10951
  getSubagentIndex(ctx).noteCatalog(childId, sessionId, typeof data.childCreatedAt === "number" ? data.childCreatedAt : undefined);
10952
+ childTranscriptRunIds.set(childId, `catalog:${childId}@${typeof data.childCreatedAt === "number" ? data.childCreatedAt : ""}`);
8933
10953
  syncChildApprovalPolicy(childId, sessionId);
8934
10954
  const turnId = state !== undefined && !state.ended ? state.turnId : inFlightTurnId ?? "";
8935
10955
  const label = typeof data.label === "string" && data.label !== "" ? data.label : typeof data.name === "string" ? data.name : "";
@@ -8955,6 +10975,7 @@ function apply(ctx, config) {
8955
10975
  const childId = idString(data.childId);
8956
10976
  if (!childId)
8957
10977
  return;
10978
+ childTranscriptRunIds.set(childId, idString(data.runId));
8958
10979
  emitEvent("agent.spawn", {
8959
10980
  turnId,
8960
10981
  sessionId: boundId,
@@ -8965,6 +10986,7 @@ function apply(ctx, config) {
8965
10986
  });
8966
10987
  } else {
8967
10988
  flushAllProgress();
10989
+ flushAllTranscript();
8968
10990
  emitEvent("agent.settle", {
8969
10991
  turnId,
8970
10992
  sessionId: boundId,
@@ -8977,6 +10999,44 @@ function apply(ctx, config) {
8977
10999
  }
8978
11000
  if (type === "assistant/message" && binding !== undefined && sessionId !== binding.sessionId) {
8979
11001
  noteChildProgress(sessionId, 1, "", assistantMessageLastLine(data));
11002
+ const text = assistantMessageText(data);
11003
+ if (text !== "")
11004
+ noteChildTranscriptRow(sessionId, { kind: "assistant", text });
11005
+ }
11006
+ if (binding !== undefined && sessionId !== binding.sessionId) {
11007
+ if (type === "tool/call") {
11008
+ const callId = idString(data.callId);
11009
+ if (callId !== "undefined" && callId !== "") {
11010
+ const indexed = getSubagentIndex(ctx).get(sessionId);
11011
+ if (indexed !== undefined && indexed.parentSessionId === binding.sessionId && indexed.status !== "settled") {
11012
+ const st = childTranscriptState(sessionId);
11013
+ const name = typeof data.name === "string" ? data.name : "";
11014
+ if (!st.toolCalls.has(callId) && st.toolCalls.size >= MAX_PENDING_TOOL_CALLS) {
11015
+ const oldest = st.toolCalls.keys().next().value;
11016
+ if (oldest !== undefined)
11017
+ st.toolCalls.delete(oldest);
11018
+ }
11019
+ st.toolCalls.set(callId, name);
11020
+ }
11021
+ }
11022
+ } else if (type === "tool/result") {
11023
+ const message = data.message !== null && typeof data.message === "object" ? data.message : undefined;
11024
+ const callId = idString(message?.toolCallId);
11025
+ if (callId !== "undefined" && callId !== "") {
11026
+ const indexed = getSubagentIndex(ctx).get(sessionId);
11027
+ if (indexed !== undefined && indexed.parentSessionId === binding.sessionId && indexed.status !== "settled") {
11028
+ const state = childTranscripts.get(sessionId);
11029
+ const name = state?.toolCalls.get(callId) ?? "";
11030
+ state?.toolCalls.delete(callId);
11031
+ if (name !== "")
11032
+ noteChildTranscriptRow(sessionId, {
11033
+ kind: "tool",
11034
+ text: name,
11035
+ ...contentText(message?.content) !== "" ? { output: contentText(message?.content) } : {}
11036
+ });
11037
+ }
11038
+ }
11039
+ }
8980
11040
  }
8981
11041
  if (type === "turn/end") {
8982
11042
  const index = getSubagentIndex(ctx);
@@ -8985,8 +11045,10 @@ function apply(ctx, config) {
8985
11045
  const boundId = binding?.sessionId;
8986
11046
  const shouldSettle = row.status === "running" && boundId !== undefined && row.parentSessionId === boundId;
8987
11047
  flushProgressNow(sessionId);
11048
+ flushTranscriptNow(sessionId);
8988
11049
  index.noteSettled(sessionId, typeof data.seq === "number" ? data.seq : undefined);
8989
11050
  clearChildProgress(sessionId);
11051
+ clearChildTranscript(sessionId);
8990
11052
  if (shouldSettle) {
8991
11053
  const turnId = state !== undefined && !state.ended ? state.turnId : inFlightTurnId ?? "";
8992
11054
  emitEvent("agent.settle", {
@@ -9553,6 +11615,47 @@ function apply(ctx, config) {
9553
11615
  replyError(req.id, "INTERNAL", err instanceof Error ? err.message : String(err));
9554
11616
  }
9555
11617
  }
11618
+ async function handleSteer(req) {
11619
+ if (binding === undefined) {
11620
+ replyError(req.id, "SESSION_NOT_OPEN", "no open session; call session.open first");
11621
+ return;
11622
+ }
11623
+ const text = req.params.text;
11624
+ if (typeof text !== "string" || text.trim() === "") {
11625
+ replyError(req.id, "BAD_PARAMS", "session.steer requires a non-empty text string");
11626
+ return;
11627
+ }
11628
+ const state = activeTurn;
11629
+ const turnId = inFlightTurnId;
11630
+ const lastTerminalTurnId = [...terminalTurnIds].at(-1);
11631
+ if (turnId === undefined || state === undefined || state.ended || turnId !== state.turnId) {
11632
+ const ended = state !== undefined && state.ended || terminalTurnIds.size > 0;
11633
+ replyError(req.id, ended ? "STEER_ENDED" : "STEER_IDLE", ended ? "the turn has already ended; no running turn to steer" : "no turn in flight; steer requires a running turn", { turnId: turnId ?? lastTerminalTurnId ?? null });
11634
+ return;
11635
+ }
11636
+ if (state.abortRequested) {
11637
+ replyError(req.id, "STEER_ABORTING", "the in-flight turn is aborting; steer refused", { turnId });
11638
+ return;
11639
+ }
11640
+ const agent = binding.handle.agent;
11641
+ if (agent.status !== "running") {
11642
+ replyError(req.id, "STEER_IDLE", "agent is not running; steer refused", { turnId });
11643
+ return;
11644
+ }
11645
+ if (typeof agent.steer !== "function") {
11646
+ replyError(req.id, "UNSUPPORTED", "open agent has no steer() seam", { capability: "session.steer" });
11647
+ return;
11648
+ }
11649
+ const message = createBridgeUserMessage(text);
11650
+ try {
11651
+ agent.steer(message);
11652
+ logger.info("[dsh-opentui-bridge] session.steer ok turnId=%s messageId=%s", turnId, message.id);
11653
+ replyOk(req.id, { accepted: true, turnId, messageId: message.id });
11654
+ } catch (err) {
11655
+ logger.error("[dsh-opentui-bridge] session.steer failed: %s", err);
11656
+ replyError(req.id, "INTERNAL", err instanceof Error ? err.message : String(err));
11657
+ }
11658
+ }
9556
11659
  async function handleClose(req) {
9557
11660
  if (binding === undefined) {
9558
11661
  replyError(req.id, "SESSION_NOT_OPEN", "no open session");
@@ -9659,6 +11762,460 @@ function apply(ctx, config) {
9659
11762
  replyError(req.id, mapped.code, mapped.message, mapped.detail);
9660
11763
  }
9661
11764
  }
11765
+ async function handlePlanSessionPrune(req) {
11766
+ const persistence = resolvePrunePersistence(ctx);
11767
+ if (persistence === undefined) {
11768
+ replyError(req.id, "UNSUPPORTED", "sessionPersistence.stat unavailable: session.prune.plan requires stat capability", {
11769
+ capability: "session.prune.plan",
11770
+ service: "sessionPersistence"
11771
+ });
11772
+ return;
11773
+ }
11774
+ const controller = resolveSessionController(ctx);
11775
+ if (controller === undefined) {
11776
+ replyError(req.id, "UNSUPPORTED", "sessionController service unavailable: session.prune.plan requires session.list", {
11777
+ capability: "session.prune.plan",
11778
+ service: "sessionController"
11779
+ });
11780
+ return;
11781
+ }
11782
+ const tryLockExclusive = resolveFlockTryLockExclusive();
11783
+ if (tryLockExclusive === undefined) {
11784
+ replyError(req.id, "UNSUPPORTED", "flock capability unavailable: session.prune.plan requires tryLockExclusive", {
11785
+ capability: "session.prune.plan",
11786
+ service: "node-addon-system/flock",
11787
+ detail: "tryLockExclusive"
11788
+ });
11789
+ return;
11790
+ }
11791
+ const lockProbe = createPruneLockProbe(tryLockExclusive);
11792
+ const params = req.params ?? {};
11793
+ for (const key of ["sessionsRoot", "retentionDays", "blankGraceDays", "lockGraceMs", "freshMtimeGraceMs"]) {
11794
+ if (params[key] !== undefined) {
11795
+ replyError(req.id, "BAD_PARAMS", `session.prune.plan ${key} is host-derived; clients may not set it`);
11796
+ return;
11797
+ }
11798
+ }
11799
+ const stagedIds = new Set;
11800
+ if (params.stagedIds !== undefined) {
11801
+ if (!Array.isArray(params.stagedIds) || params.stagedIds.some((s) => typeof s !== "string")) {
11802
+ replyError(req.id, "BAD_PARAMS", "session.prune.plan stagedIds must be a string array");
11803
+ return;
11804
+ }
11805
+ for (const id of params.stagedIds)
11806
+ stagedIds.add(id);
11807
+ }
11808
+ const sessionsRoot = resolvePruneSessionsRoot(ctx, config);
11809
+ const policy = resolveHostPrunePolicy(ctx, config, sessionsRoot);
11810
+ const planConfigFingerprint = computeConfigFingerprint(policy);
11811
+ const lister = {
11812
+ list: (request) => controller.list(request)
11813
+ };
11814
+ const nodePruneFs = { lstat, realpath, stat, lockProbe };
11815
+ try {
11816
+ const listing = await listAllSessions(lister);
11817
+ if (listing.truncated) {
11818
+ replyError(req.id, "BLOCKED", "session.prune.plan aborted: session.list roster is incomplete (truncated pagination)", {
11819
+ capability: "session.prune.plan",
11820
+ reason: "incomplete-roster",
11821
+ pages: listing.pages
11822
+ });
11823
+ return;
11824
+ }
11825
+ const plan = await planSessionPrune(listing.rows, persistence, nodePruneFs, {
11826
+ retentionDays: policy.retentionDays,
11827
+ now: Date.now(),
11828
+ sessionsRoot,
11829
+ currentSessionId: binding?.sessionId,
11830
+ stagedIds,
11831
+ blankGraceDays: policy.blankGraceDays,
11832
+ lockGraceMs: policy.lockGraceMs,
11833
+ freshMtimeGraceMs: policy.freshMtimeGraceMs
11834
+ });
11835
+ replyOk(req.id, {
11836
+ ...plan,
11837
+ fingerprint: computePlanFingerprint(plan),
11838
+ configFingerprint: planConfigFingerprint
11839
+ });
11840
+ } catch (err) {
11841
+ const message = err instanceof Error ? err.message : String(err);
11842
+ logger.error("[dsh-opentui-bridge] session.prune.plan failed: %s", message);
11843
+ const mapped = mapHostError(err);
11844
+ replyError(req.id, mapped.code, mapped.message, mapped.detail);
11845
+ }
11846
+ }
11847
+ async function handleApplySessionPrune(req) {
11848
+ const params = req.params;
11849
+ if (params === null || typeof params !== "object" || Array.isArray(params)) {
11850
+ replyError(req.id, "BAD_PARAMS", "session.prune.apply params must be an object");
11851
+ return;
11852
+ }
11853
+ const p = params;
11854
+ for (const key of [
11855
+ "entries",
11856
+ "retentionDays",
11857
+ "blankGraceDays",
11858
+ "lockGraceMs",
11859
+ "freshMtimeGraceMs",
11860
+ "sessionsRoot",
11861
+ "dshHome"
11862
+ ]) {
11863
+ if (p[key] !== undefined) {
11864
+ replyError(req.id, "BAD_PARAMS", `session.prune.apply ${key} is host-owned; clients may not set it`);
11865
+ return;
11866
+ }
11867
+ }
11868
+ const stagedIds = new Set;
11869
+ if (p.stagedIds !== undefined) {
11870
+ if (!Array.isArray(p.stagedIds) || p.stagedIds.some((s) => typeof s !== "string")) {
11871
+ replyError(req.id, "BAD_PARAMS", "session.prune.apply stagedIds must be a string array");
11872
+ return;
11873
+ }
11874
+ for (const id of p.stagedIds)
11875
+ stagedIds.add(id);
11876
+ }
11877
+ const fingerprint = p.fingerprint;
11878
+ const configFingerprint = p.configFingerprint;
11879
+ const generatedAt = p.generatedAt;
11880
+ if (typeof fingerprint !== "string" || fingerprint === "") {
11881
+ replyError(req.id, "BAD_PARAMS", "session.prune.apply requires fingerprint from session.prune.plan");
11882
+ return;
11883
+ }
11884
+ if (typeof configFingerprint !== "string" || configFingerprint === "") {
11885
+ replyError(req.id, "BAD_PARAMS", "session.prune.apply requires configFingerprint from session.prune.plan");
11886
+ return;
11887
+ }
11888
+ if (typeof generatedAt !== "number" || !Number.isFinite(generatedAt)) {
11889
+ replyError(req.id, "BAD_PARAMS", "session.prune.apply requires numeric generatedAt from session.prune.plan");
11890
+ return;
11891
+ }
11892
+ const persistence = resolvePrunePersistence(ctx);
11893
+ if (persistence === undefined) {
11894
+ replyError(req.id, "UNSUPPORTED", "sessionPersistence.stat unavailable: session.prune.apply requires stat capability", {
11895
+ capability: "session.prune.apply",
11896
+ service: "sessionPersistence"
11897
+ });
11898
+ return;
11899
+ }
11900
+ const controller = resolveSessionController(ctx);
11901
+ if (controller === undefined) {
11902
+ replyError(req.id, "UNSUPPORTED", "sessionController service unavailable: session.prune.apply requires session.list", {
11903
+ capability: "session.prune.apply",
11904
+ service: "sessionController"
11905
+ });
11906
+ return;
11907
+ }
11908
+ const tryLockExclusive = resolveFlockTryLockExclusive();
11909
+ if (tryLockExclusive === undefined) {
11910
+ replyError(req.id, "UNSUPPORTED", "flock capability unavailable: session.prune.apply requires tryLockExclusive", {
11911
+ capability: "session.prune.apply",
11912
+ service: "node-addon-system/flock",
11913
+ detail: "tryLockExclusive"
11914
+ });
11915
+ return;
11916
+ }
11917
+ const sessionsRoot = resolvePruneSessionsRoot(ctx, config);
11918
+ const dshHome = resolvePruneDshHome(ctx, config);
11919
+ const policy = resolveHostPrunePolicy(ctx, config, sessionsRoot);
11920
+ const maxPlanAgeMs = (() => {
11921
+ const fromConfig = config !== null && typeof config === "object" ? config : {};
11922
+ let hostValue;
11923
+ try {
11924
+ const hostConfig = typeof ctx.get === "function" ? ctx.get("config") : undefined;
11925
+ if (hostConfig !== null && typeof hostConfig === "object")
11926
+ hostValue = hostConfig.maxPlanAgeMs;
11927
+ } catch {}
11928
+ const value = fromConfig.maxPlanAgeMs ?? hostValue;
11929
+ return typeof value === "number" && Number.isFinite(value) && value > 0 && value <= 86400000 ? value : 60000;
11930
+ })();
11931
+ const lockProbe = createPruneLockProbe(tryLockExclusive);
11932
+ const nodePruneFs = { lstat, realpath, stat, lockProbe };
11933
+ const nodeApplyFs = {
11934
+ lstat,
11935
+ realpath,
11936
+ stat,
11937
+ rename,
11938
+ mkdir: (path, options) => options?.recursive ? mkdir(path, { recursive: true, mode: options.mode }) : mkdir(path, { mode: options?.mode }),
11939
+ writeFile: (path, data, options) => writeFile(path, data, options),
11940
+ appendFile,
11941
+ readdir,
11942
+ readFile: (path) => readFile(path, "utf8")
11943
+ };
11944
+ const now = Date.now();
11945
+ const deps = {
11946
+ persistence,
11947
+ lockProbe,
11948
+ now,
11949
+ opId: `${utcStamp(now)}-${randomUUID().slice(0, 8)}`,
11950
+ withApplyLock: (fn) => withHostApplyLock(dshHome, tryLockExclusive, fn)
11951
+ };
11952
+ if (computeConfigFingerprint(policy) !== configFingerprint) {
11953
+ replyError(req.id, "STALE_PLAN", "session.prune.apply config fingerprint mismatch", {
11954
+ capability: "session.prune.apply",
11955
+ reason: "config-fingerprint"
11956
+ });
11957
+ return;
11958
+ }
11959
+ if (generatedAt > now + 1000 || now - generatedAt > maxPlanAgeMs) {
11960
+ replyError(req.id, "STALE_PLAN", "session.prune.apply plan is outside the max-age window", {
11961
+ capability: "session.prune.apply",
11962
+ reason: "max-age",
11963
+ maxPlanAgeMs
11964
+ });
11965
+ return;
11966
+ }
11967
+ try {
11968
+ const listing = await listAllSessions({ list: (request) => controller.list(request) });
11969
+ if (listing.truncated) {
11970
+ replyError(req.id, "BLOCKED", "session.prune.apply aborted: session.list roster is incomplete", {
11971
+ capability: "session.prune.apply",
11972
+ reason: "incomplete-roster",
11973
+ pages: listing.pages
11974
+ });
11975
+ return;
11976
+ }
11977
+ const freshPlan = await planSessionPrune(listing.rows, persistence, nodePruneFs, {
11978
+ retentionDays: policy.retentionDays,
11979
+ now,
11980
+ sessionsRoot,
11981
+ currentSessionId: binding?.sessionId,
11982
+ stagedIds,
11983
+ blankGraceDays: policy.blankGraceDays,
11984
+ lockGraceMs: policy.lockGraceMs,
11985
+ freshMtimeGraceMs: policy.freshMtimeGraceMs
11986
+ });
11987
+ const freshFingerprint = computePlanFingerprint(freshPlan);
11988
+ if (freshFingerprint !== fingerprint) {
11989
+ replyError(req.id, "STALE_PLAN", "session.prune.apply plan fingerprint mismatch", {
11990
+ capability: "session.prune.apply",
11991
+ reason: "plan-fingerprint"
11992
+ });
11993
+ return;
11994
+ }
11995
+ const result = await applyTrashPlan(nodeApplyFs, deps, freshPlan, {
11996
+ dshHome,
11997
+ sessionsRoot,
11998
+ planFingerprint: freshFingerprint
11999
+ });
12000
+ replyOk(req.id, { ...result });
12001
+ } catch (err) {
12002
+ const message = err instanceof Error ? err.message : String(err);
12003
+ logger.error("[dsh-opentui-bridge] session.prune.apply failed: %s", message);
12004
+ if (err instanceof ApplyError) {
12005
+ replyError(req.id, err.code, message, err.detail);
12006
+ return;
12007
+ }
12008
+ replyError(req.id, "INTERNAL", "session.prune.apply failed");
12009
+ }
12010
+ }
12011
+ async function handlePurgeSessionPrune(req) {
12012
+ const params = req.params;
12013
+ if (params === null || typeof params !== "object" || Array.isArray(params)) {
12014
+ replyError(req.id, "BAD_PARAMS", "session.prune.purge params must be an object");
12015
+ return;
12016
+ }
12017
+ const p = params;
12018
+ for (const key of [
12019
+ "entries",
12020
+ "retentionDays",
12021
+ "purgeRetentionDays",
12022
+ "tokenTtlMs",
12023
+ "sessionsRoot",
12024
+ "dshHome",
12025
+ "trashRoot",
12026
+ "path",
12027
+ "paths",
12028
+ "secret",
12029
+ "algorithm"
12030
+ ]) {
12031
+ if (p[key] !== undefined) {
12032
+ replyError(req.id, "BAD_PARAMS", `session.prune.purge ${key} is host-owned; clients may not set it`);
12033
+ return;
12034
+ }
12035
+ }
12036
+ if (p.phase !== "prepare" && p.phase !== "commit") {
12037
+ replyError(req.id, "BAD_PARAMS", "session.prune.purge phase must be 'prepare' or 'commit'");
12038
+ return;
12039
+ }
12040
+ if (p.phase === "commit" && (typeof p.token !== "string" || p.token === "")) {
12041
+ replyError(req.id, "BAD_PARAMS", "session.prune.purge commit requires the prepare token");
12042
+ return;
12043
+ }
12044
+ const persistence = resolvePrunePersistence(ctx);
12045
+ if (persistence === undefined) {
12046
+ replyError(req.id, "UNSUPPORTED", "sessionPersistence.stat unavailable: session.prune.purge requires stat capability", {
12047
+ capability: "session.prune.purge",
12048
+ service: "sessionPersistence"
12049
+ });
12050
+ return;
12051
+ }
12052
+ const controller = resolveSessionController(ctx);
12053
+ if (controller === undefined) {
12054
+ replyError(req.id, "UNSUPPORTED", "sessionController service unavailable: session.prune.purge requires session.list", {
12055
+ capability: "session.prune.purge",
12056
+ service: "sessionController"
12057
+ });
12058
+ return;
12059
+ }
12060
+ const tryLockExclusive = resolveFlockTryLockExclusive();
12061
+ if (tryLockExclusive === undefined) {
12062
+ replyError(req.id, "UNSUPPORTED", "flock capability unavailable: session.prune.purge requires tryLockExclusive", {
12063
+ capability: "session.prune.purge",
12064
+ service: "node-addon-system/flock",
12065
+ detail: "tryLockExclusive"
12066
+ });
12067
+ return;
12068
+ }
12069
+ try {
12070
+ const dshHome = resolvePruneDshHome(ctx, config);
12071
+ const hostPolicy = resolveHostPurgePolicy(ctx, config);
12072
+ const lockProbe = createPruneLockProbe(tryLockExclusive);
12073
+ const nodePurgeFs = {
12074
+ lstat,
12075
+ realpath,
12076
+ stat,
12077
+ readdir,
12078
+ readFile: (path) => readFile(path, "utf8"),
12079
+ readFileBuffer: (path) => readFile(path),
12080
+ writeFile: (path, data, options) => writeFile(path, data, options),
12081
+ appendFile,
12082
+ unlink,
12083
+ rmdir,
12084
+ mkdir: (path, options) => options?.recursive ? mkdir(path, { recursive: true, mode: options.mode }) : mkdir(path, { mode: options?.mode })
12085
+ };
12086
+ const now = Date.now();
12087
+ const deps = {
12088
+ persistence,
12089
+ lister: { list: (request) => controller.list(request) },
12090
+ lockProbe,
12091
+ now,
12092
+ opId: `${utcStamp(now)}-${randomUUID().slice(0, 8)}`,
12093
+ secret: await resolvePurgeSecret(nodePurgeFs, dshHome, () => randomUUID() + randomUUID()),
12094
+ retentionDays: hostPolicy.retentionDays,
12095
+ tokenTtlMs: hostPolicy.tokenTtlMs,
12096
+ newSecret: () => randomUUID() + randomUUID(),
12097
+ withApplyLock: (fn) => withHostApplyLock(dshHome, tryLockExclusive, fn)
12098
+ };
12099
+ if (p.phase === "prepare") {
12100
+ const result = await preparePurge(nodePurgeFs, deps, dshHome);
12101
+ replyOk(req.id, {
12102
+ opId: result.opId,
12103
+ candidates: result.candidates,
12104
+ rejected: result.rejected,
12105
+ token: result.token
12106
+ });
12107
+ return;
12108
+ }
12109
+ const result = await purgeTrashSessions(nodePurgeFs, deps, dshHome, p.token);
12110
+ replyOk(req.id, { ...result });
12111
+ } catch (err) {
12112
+ const message = err instanceof Error ? err.message : String(err);
12113
+ logger.error("[dsh-opentui-bridge] session.prune.purge failed: %s", message);
12114
+ if (err instanceof PurgeError) {
12115
+ replyError(req.id, err.code, message, err.detail);
12116
+ return;
12117
+ }
12118
+ const mapped = mapHostError(err);
12119
+ replyError(req.id, mapped.code, mapped.message, mapped.detail);
12120
+ }
12121
+ }
12122
+ async function handleRestoreSessionPrune(req) {
12123
+ const params = req.params;
12124
+ if (params === null || typeof params !== "object" || Array.isArray(params)) {
12125
+ replyError(req.id, "BAD_PARAMS", "session.prune.restore params must be an object");
12126
+ return;
12127
+ }
12128
+ const p = params;
12129
+ for (const key of [
12130
+ "entries",
12131
+ "path",
12132
+ "paths",
12133
+ "sessionsRoot",
12134
+ "dshHome",
12135
+ "trashRoot",
12136
+ "manifest",
12137
+ "root",
12138
+ "retentionDays"
12139
+ ]) {
12140
+ if (p[key] !== undefined) {
12141
+ replyError(req.id, "BAD_PARAMS", `session.prune.restore ${key} is host-owned; clients may not set it`);
12142
+ return;
12143
+ }
12144
+ }
12145
+ const phase = p.phase ?? "list";
12146
+ if (phase !== "list" && phase !== "restore") {
12147
+ replyError(req.id, "BAD_PARAMS", "session.prune.restore phase must be 'list' or 'restore'");
12148
+ return;
12149
+ }
12150
+ if (phase === "restore" && (typeof p.id !== "string" || p.id === "")) {
12151
+ replyError(req.id, "BAD_PARAMS", "session.prune.restore requires a non-empty id");
12152
+ return;
12153
+ }
12154
+ const persistence = resolvePrunePersistence(ctx);
12155
+ if (persistence === undefined) {
12156
+ replyError(req.id, "UNSUPPORTED", "sessionPersistence.stat unavailable: session.prune.restore requires stat capability", {
12157
+ capability: "session.prune.restore",
12158
+ service: "sessionPersistence"
12159
+ });
12160
+ return;
12161
+ }
12162
+ const controller = resolveSessionController(ctx);
12163
+ if (controller === undefined) {
12164
+ replyError(req.id, "UNSUPPORTED", "sessionController service unavailable: session.prune.restore requires session.list", {
12165
+ capability: "session.prune.restore",
12166
+ service: "sessionController"
12167
+ });
12168
+ return;
12169
+ }
12170
+ const tryLockExclusive = resolveFlockTryLockExclusive();
12171
+ if (tryLockExclusive === undefined) {
12172
+ replyError(req.id, "UNSUPPORTED", "flock capability unavailable: session.prune.restore requires tryLockExclusive", {
12173
+ capability: "session.prune.restore",
12174
+ service: "node-addon-system/flock",
12175
+ detail: "tryLockExclusive"
12176
+ });
12177
+ return;
12178
+ }
12179
+ try {
12180
+ const dshHome = resolvePruneDshHome(ctx, config);
12181
+ const sessionsRoot = resolvePruneSessionsRoot(ctx, config);
12182
+ const lockProbe = createPruneLockProbe(tryLockExclusive);
12183
+ const nodeRestoreFs = {
12184
+ lstat,
12185
+ realpath,
12186
+ stat,
12187
+ readdir,
12188
+ readFile: (path) => readFile(path, "utf8"),
12189
+ readFileBuffer: (path) => readFile(path),
12190
+ rename
12191
+ };
12192
+ const now = Date.now();
12193
+ const deps = {
12194
+ persistence,
12195
+ lister: { list: (request) => controller.list(request) },
12196
+ lockProbe,
12197
+ now,
12198
+ opId: `${utcStamp(now)}-${randomUUID().slice(0, 8)}`,
12199
+ sessionsRoot,
12200
+ withApplyLock: (fn) => withHostApplyLock(dshHome, tryLockExclusive, fn)
12201
+ };
12202
+ if (phase === "list") {
12203
+ const result = await listRestoreEntries(nodeRestoreFs, dshHome);
12204
+ replyOk(req.id, { entries: result.entries, rejected: result.rejected });
12205
+ return;
12206
+ }
12207
+ const result = await restoreTrashEntry(nodeRestoreFs, deps, dshHome, p.id);
12208
+ replyOk(req.id, { ...result });
12209
+ } catch (err) {
12210
+ const message = err instanceof Error ? err.message : String(err);
12211
+ logger.error("[dsh-opentui-bridge] session.prune.restore failed: %s", message);
12212
+ if (err instanceof RestoreError) {
12213
+ replyError(req.id, err.code, message, err.detail);
12214
+ return;
12215
+ }
12216
+ replyError(req.id, "INTERNAL", "session.prune.restore failed");
12217
+ }
12218
+ }
9662
12219
  async function reconcileSubagentIndex() {
9663
12220
  const controller = resolveSessionController(ctx);
9664
12221
  if (controller === undefined) {
@@ -9858,6 +12415,22 @@ function apply(ctx, config) {
9858
12415
  await handleListSessions(req);
9859
12416
  return;
9860
12417
  }
12418
+ if (req.method === "session.prune.plan") {
12419
+ await handlePlanSessionPrune(req);
12420
+ return;
12421
+ }
12422
+ if (req.method === "session.prune.apply") {
12423
+ await handleApplySessionPrune(req);
12424
+ return;
12425
+ }
12426
+ if (req.method === "session.prune.purge") {
12427
+ await handlePurgeSessionPrune(req);
12428
+ return;
12429
+ }
12430
+ if (req.method === "session.prune.restore") {
12431
+ await handleRestoreSessionPrune(req);
12432
+ return;
12433
+ }
9861
12434
  const sessionQueryMethodId = CAP_SESSION_QUERY_WIRE_METHODS[req.method];
9862
12435
  if (sessionQueryMethodId !== undefined) {
9863
12436
  try {
@@ -9918,6 +12491,10 @@ function apply(ctx, config) {
9918
12491
  await handleSend(req);
9919
12492
  return;
9920
12493
  }
12494
+ if (req.method === "session.steer") {
12495
+ await handleSteer(req);
12496
+ return;
12497
+ }
9921
12498
  if (req.method === "session.close") {
9922
12499
  await handleClose(req);
9923
12500
  return;
@@ -10171,11 +12748,13 @@ export {
10171
12748
  isAskErrorCode,
10172
12749
  name,
10173
12750
  probeAgentProgressResidue,
12751
+ probeAgentTranscriptResidue,
10174
12752
  probeOwnedAbortRelease,
10175
12753
  projectAccountScalarResult,
10176
12754
  projectAccountViewForFrame,
10177
12755
  redactIdentifier,
10178
12756
  resolveAskDeadlineMs,
12757
+ resolveMaxAskWaitMs,
10179
12758
  sanitizeFrameForWire,
10180
12759
  summarizeAnswers,
10181
12760
  turnIdOf,