@kangyishuai/dsh-session-delete 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,534 @@
1
+ // @ts-check
2
+ // 操作编排层:不依赖 typert,可在单元测试里用假 ctx 跑(真实宿主交互全部经 capability.js 探测)。
3
+ import { createRequire } from "node:module";
4
+ import { setTimeout as delayMs } from "node:timers/promises";
5
+ import { createAudit } from "./audit.js";
6
+ import { describeCapabilities, probeCapabilities } from "./capability.js";
7
+ import { beginOperation, finishOperation, listPending } from "./journal.js";
8
+ import { directorySize, locateSession } from "./locate.js";
9
+ import { auditPath, requireSessionId, sessionsRoot, trashRoot } from "./paths.js";
10
+ import { buildPlan, planExecutable, summarizePlan } from "./plan.js";
11
+ import { buildRefs } from "./refs.js";
12
+ import { listEntries, moveIntoTrash, purgeEntry, readEntry, restoreEntry } from "./trash.js";
13
+
14
+ const nodeRequire = createRequire(import.meta.url);
15
+ const pkg = nodeRequire("../package.json");
16
+
17
+ /** 等宿主把 flush / 取消落盘写完再动文件。 */
18
+ const SETTLE_MS = 200;
19
+ /** 移走之后复查原路径的时间点;活句柄迟到写入会在这个窗口里重建目录。 */
20
+ const REVIVE_CHECK_MS = 1500;
21
+
22
+ /** @param {unknown} error @returns {string} */
23
+ function messageOf(error) {
24
+ return error instanceof Error ? error.message : String(error);
25
+ }
26
+
27
+ /**
28
+ * @param {string} code
29
+ * @param {string} message
30
+ * @param {Record<string, unknown>} [details]
31
+ */
32
+ function failure(code, message, details) {
33
+ return Object.assign(new Error(message), { code, details });
34
+ }
35
+
36
+ /**
37
+ * 把 host 的活动条目归一成 { kind, count, labels, ids }。
38
+ * @param {unknown[]} raw
39
+ * @returns {{ kind: string, count: number, labels: string[], ids: string[] }[]}
40
+ */
41
+ export function normalizeActivity(raw) {
42
+ /** @type {Map<string, { kind: string, count: number, labels: string[], ids: string[] }>} */
43
+ const groups = new Map();
44
+ for (const entry of Array.isArray(raw) ? raw : []) {
45
+ const kind = String(/** @type {any} */ (entry)?.kind ?? "other");
46
+ const items = Array.isArray(/** @type {any} */ (entry)?.items)
47
+ ? /** @type {any} */ (entry).items
48
+ : [];
49
+ const group = groups.get(kind) ?? { kind, count: 0, labels: [], ids: [] };
50
+ for (const item of items) {
51
+ group.count += 1;
52
+ const label =
53
+ typeof item?.label === "string" && item.label.length > 0
54
+ ? item.label
55
+ : String(item?.id ?? "");
56
+ if (label) group.labels.push(label);
57
+ if (typeof item?.id === "string") group.ids.push(item.id);
58
+ }
59
+ groups.set(kind, group);
60
+ }
61
+ return [...groups.values()].filter((group) => group.count > 0);
62
+ }
63
+
64
+ /**
65
+ * @param {{ ctx: any, dataRoot: string, logger: any }} options
66
+ */
67
+ export function createOperations({ ctx, dataRoot, logger }) {
68
+ const caps = probeCapabilities(ctx);
69
+ const audit = createAudit(dataRoot);
70
+ const refs = buildRefs(caps, logger);
71
+ /** 当前进程里正在操作中的会话,防止双击/并发把同一个会话删两遍。 */
72
+ const inFlight = new Set();
73
+
74
+ /**
75
+ * 收集一份完整事实并生成 Plan。
76
+ * @param {unknown} sessionIdRaw
77
+ */
78
+ async function makePlan(sessionIdRaw) {
79
+ const sessionId = requireSessionId(sessionIdRaw);
80
+ /** @type {string[]} */
81
+ const notes = [];
82
+
83
+ let stored;
84
+ try {
85
+ stored = await caps.services.persistence?.stat?.(sessionId);
86
+ } catch (error) {
87
+ notes.push("stat failed: " + messageOf(error));
88
+ }
89
+ const liveEntry = caps.services.sessions?.get?.(sessionId);
90
+ if (!stored && !liveEntry) {
91
+ throw failure("session/not-found", "no session named " + sessionId, { sessionId });
92
+ }
93
+ const header = stored?.header ?? liveEntry?.header ?? null;
94
+
95
+ /** @type {unknown[]} */
96
+ let rawActivity = [];
97
+ if (typeof ctx.waterfall === "function") {
98
+ try {
99
+ rawActivity = await ctx.waterfall("workspace/session-activity", { sessionId }, () => []);
100
+ } catch (error) {
101
+ notes.push("activity unavailable: " + messageOf(error));
102
+ }
103
+ }
104
+ const activity = normalizeActivity(rawActivity);
105
+ const subagents = activity.find((group) => group.kind === "subagent");
106
+ const children = (subagents?.ids ?? []).map((id, index) => ({
107
+ id,
108
+ title: subagents?.labels[index] ?? null,
109
+ }));
110
+
111
+ const located = await locateSession({
112
+ dataRoot,
113
+ sessionId,
114
+ header,
115
+ persistence: caps.services.persistence,
116
+ });
117
+ const location = located.location;
118
+ const ambiguous = located.ambiguous;
119
+
120
+ let sizeBytes = typeof stored?.sizeBytes === "number" ? stored.sizeBytes : null;
121
+ if (sizeBytes === null && location) {
122
+ sizeBytes = await directorySize(location.path).catch(() => null);
123
+ }
124
+
125
+ /** @type {{ code: string, message: string }[]} */
126
+ const blockers = [];
127
+ if (caps.tier === "unknown") {
128
+ blockers.push({
129
+ code: "session-delete/unsupported-host",
130
+ message: "当前 DSH 版本缺少本插件依赖的核心接口,删除功能已禁用(只读模式)。",
131
+ });
132
+ }
133
+ if (!location) {
134
+ blockers.push(
135
+ ambiguous.length > 1
136
+ ? {
137
+ code: "session-delete/ambiguous-location",
138
+ message: "同一会话在 " + ambiguous.length + " 个项目目录下都有副本,已拒绝操作。",
139
+ }
140
+ : {
141
+ code: "session-delete/location-unknown",
142
+ message: "找不到这个会话在磁盘上的位置(可能宿主换了目录布局)。",
143
+ },
144
+ );
145
+ }
146
+ if (liveEntry && !caps.checks["event.session-stop"]) {
147
+ blockers.push({
148
+ code: "session-delete/live-unsupported",
149
+ message: "会话正在运行,但当前宿主不支持安全停止,已拒绝删除。",
150
+ });
151
+ }
152
+
153
+ const plan = buildPlan({
154
+ sessionId,
155
+ title: typeof header?.title === "string" ? header.title : null,
156
+ cwd: typeof header?.cwd === "string" ? header.cwd : null,
157
+ sizeBytes,
158
+ live: Boolean(liveEntry),
159
+ activity: activity.map(({ kind, count, labels }) => ({ kind, count, labels })),
160
+ children,
161
+ location,
162
+ trashPath: null,
163
+ removes: refs.map((ref) => ({ id: ref.id, label: ref.label, tier: ref.tier })),
164
+ blockers,
165
+ });
166
+ return { plan, stored, header, location, refs, notes };
167
+ }
168
+
169
+ /**
170
+ * 移走之后复查一次原路径;目录若被迟到写入重建,就再移一次并记审计。
171
+ * @param {string} sessionId
172
+ * @param {string} originalPath
173
+ */
174
+ function scheduleReviveCheck(sessionId, originalPath) {
175
+ const timer = setTimeout(async () => {
176
+ try {
177
+ const { stat } = await import("node:fs/promises");
178
+ const exists = await stat(originalPath)
179
+ .then(() => true)
180
+ .catch(() => false);
181
+ if (!exists) return;
182
+ await audit.append({
183
+ action: "trash",
184
+ result: "ok",
185
+ sessionId,
186
+ operator: "system",
187
+ detail: "会话目录在移走后被重建,已记录(复活守卫)",
188
+ });
189
+ logger.warn("session-delete: session " + sessionId + " was recreated after deletion");
190
+ } catch (error) {
191
+ logger.warn("session-delete: revive check failed: " + messageOf(error));
192
+ }
193
+ }, REVIVE_CHECK_MS);
194
+ /** @type {any} */ (timer).unref?.();
195
+ }
196
+
197
+ /**
198
+ * @param {string} sessionIdRaw
199
+ * @param {{ digest?: string, title?: string | null, operator?: string }} request
200
+ */
201
+ async function trash(sessionIdRaw, request = {}) {
202
+ const loaded = await makePlan(sessionIdRaw);
203
+ const { plan, location, header } = loaded;
204
+ if (request.digest && request.digest !== plan.digest) {
205
+ throw failure(
206
+ "session-delete/stale-plan",
207
+ "会话状态在确认期间发生了变化,请重新查看影响面。",
208
+ {
209
+ expected: plan.digest,
210
+ actual: request.digest,
211
+ },
212
+ );
213
+ }
214
+ if (!planExecutable(plan)) {
215
+ await audit.append({
216
+ action: "trash",
217
+ result: "refused",
218
+ sessionId: plan.sessionId,
219
+ operator: request.operator ?? "ui",
220
+ detail: plan.blockers.map((b) => b.code).join(","),
221
+ });
222
+ throw failure("session-delete/blocked", plan.blockers[0].message, {
223
+ blockers: plan.blockers,
224
+ plan,
225
+ });
226
+ }
227
+ if (!location) throw failure("session-delete/location-unknown", "没有可移动的会话目录");
228
+ if (inFlight.has(plan.sessionId)) {
229
+ throw failure("session-delete/busy", "这个会话正在被另一个删除操作处理。");
230
+ }
231
+ inFlight.add(plan.sessionId);
232
+
233
+ const record = await beginOperation({
234
+ dataRoot,
235
+ action: "trash",
236
+ extra: { sessionId: plan.sessionId, digest: plan.digest, operator: request.operator ?? "ui" },
237
+ });
238
+
239
+ let moved = false;
240
+ let entryId = "";
241
+ try {
242
+ // 1. 先归档:归档集合就是 provider 的 agent/pre-step 闸门。
243
+ if (caps.checks["workspace.archive"]) {
244
+ await caps.services.workspace.archiveSession(plan.sessionId, { stopActivity: true });
245
+ }
246
+ // 2. 官方停止通道(跑着的轮次、子代理、后台任务、提醒)。
247
+ if (caps.checks["event.session-stop"]) {
248
+ await ctx.parallel("workspace/session-stop", { sessionId: plan.sessionId });
249
+ }
250
+ // 3. 落盘并等写入稳定。
251
+ const live = caps.services.sessions?.get?.(plan.sessionId);
252
+ if (live && caps.checks["sessions.flush"]) await caps.services.sessions.flush(live);
253
+ await delayMs(SETTLE_MS);
254
+
255
+ // 4. 记录引用状态,供恢复时还原。
256
+ /** @type {Record<string, any>} */
257
+ const snapshots = {};
258
+ for (const ref of refs) {
259
+ if (typeof ref.snapshot !== "function") continue;
260
+ try {
261
+ snapshots[ref.id] = await ref.snapshot(plan.sessionId);
262
+ } catch (error) {
263
+ logger.warn("session-delete: snapshot " + ref.id + " failed: " + messageOf(error));
264
+ }
265
+ }
266
+
267
+ // 5. 移入回收站(原子 rename)。
268
+ const movedResult = await moveIntoTrash({
269
+ dataRoot,
270
+ sessionId: plan.sessionId,
271
+ sourceDir: location.path,
272
+ meta: {
273
+ title:
274
+ plan.title ??
275
+ (typeof request.title === "string" && request.title.length > 0 ? request.title : null),
276
+ cwd: typeof header?.cwd === "string" ? header.cwd : null,
277
+ bytes: plan.sizeBytes ?? 0,
278
+ live: plan.live,
279
+ children: plan.children,
280
+ workspaceIds: snapshots["workspace-slot"]?.workspaceIds ?? [],
281
+ pinned: null,
282
+ },
283
+ });
284
+ moved = true;
285
+ entryId = movedResult.entryId;
286
+
287
+ // 6. 摘掉所有还指向它的引用。
288
+ /** @type {{ id: string, label: string, status: string, detail?: string }[]} */
289
+ const removed = [];
290
+ for (const ref of refs) {
291
+ if (typeof ref.remove !== "function" || ref.tier === "unknown") {
292
+ removed.push({
293
+ id: ref.id,
294
+ label: ref.label,
295
+ status: "skipped",
296
+ detail: "当前宿主不提供该接口",
297
+ });
298
+ continue;
299
+ }
300
+ try {
301
+ await ref.remove(plan.sessionId, snapshots[ref.id] ?? {});
302
+ removed.push({ id: ref.id, label: ref.label, status: "ok" });
303
+ } catch (error) {
304
+ removed.push({
305
+ id: ref.id,
306
+ label: ref.label,
307
+ status: "failed",
308
+ detail: messageOf(error),
309
+ });
310
+ }
311
+ }
312
+
313
+ // 7. 复活复查 + 对账回执。
314
+ scheduleReviveCheck(plan.sessionId, location.path);
315
+ const checks = await reconcile(plan.sessionId, { skipDirCheck: true });
316
+ await finishOperation({ dataRoot, id: record.id, state: "done" });
317
+ await audit.append({
318
+ action: "trash",
319
+ result: "ok",
320
+ sessionId: plan.sessionId,
321
+ entryId,
322
+ operator: request.operator ?? "ui",
323
+ detail: summarizePlan(plan),
324
+ });
325
+ return {
326
+ ok: true,
327
+ entryId,
328
+ sessionId: plan.sessionId,
329
+ digest: plan.digest,
330
+ title: plan.title ?? (typeof request.title === "string" ? request.title : null),
331
+ sizeBytes: plan.sizeBytes,
332
+ removed,
333
+ checks,
334
+ };
335
+ } catch (error) {
336
+ if (!moved) {
337
+ try {
338
+ await caps.services.workspace?.unarchiveSession?.(plan.sessionId);
339
+ } catch {
340
+ // 尽力而为。
341
+ }
342
+ }
343
+ await finishOperation({ dataRoot, id: record.id, state: "failed", detail: messageOf(error) });
344
+ await audit.append({
345
+ action: "trash",
346
+ result: "failed",
347
+ sessionId: plan.sessionId,
348
+ operator: request.operator ?? "ui",
349
+ detail: messageOf(error),
350
+ });
351
+ throw failure("session-delete/failed", "删除失败:" + messageOf(error), {
352
+ partial: moved,
353
+ entryId: moved ? entryId : null,
354
+ });
355
+ } finally {
356
+ inFlight.delete(plan.sessionId);
357
+ }
358
+ }
359
+
360
+ /** @param {number} [limit] */
361
+ async function auditLog(limit = 100) {
362
+ return { path: auditPath(dataRoot), entries: await audit.read(limit) };
363
+ }
364
+
365
+ async function list() {
366
+ const listed = await listEntries(dataRoot);
367
+ const pending = await listPending(dataRoot);
368
+ return {
369
+ trashRoot: trashRoot(dataRoot),
370
+ entries: listed.entries,
371
+ unknown: listed.unknown,
372
+ pending: pending.map((record) => ({
373
+ id: record.id,
374
+ action: record.action,
375
+ sessionId: record.sessionId,
376
+ })),
377
+ };
378
+ }
379
+
380
+ /**
381
+ * @param {string} entryId
382
+ * @param {{ operator?: string }} [request]
383
+ */
384
+ async function restore(entryId, request = {}) {
385
+ const meta = await readEntry(dataRoot, entryId);
386
+ const record = await beginOperation({
387
+ dataRoot,
388
+ action: "restore",
389
+ extra: { sessionId: meta.sessionId, entryId },
390
+ });
391
+ try {
392
+ const restored = await restoreEntry({ dataRoot, entryId });
393
+ try {
394
+ await caps.services.workspace?.unarchiveSession?.(meta.sessionId);
395
+ } catch {
396
+ // 恢复失败不阻断:文件已经回去了。
397
+ }
398
+ for (const ref of refs) {
399
+ if (typeof ref.restore !== "function") continue;
400
+ try {
401
+ await ref.restore(meta.sessionId, {
402
+ workspaceIds: meta.workspaceIds,
403
+ pinned: meta.pinned,
404
+ });
405
+ } catch (error) {
406
+ logger.warn("session-delete: restore " + ref.id + " failed: " + messageOf(error));
407
+ }
408
+ }
409
+ await finishOperation({ dataRoot, id: record.id, state: "done" });
410
+ await audit.append({
411
+ action: "restore",
412
+ result: "ok",
413
+ sessionId: meta.sessionId,
414
+ entryId,
415
+ operator: request.operator ?? "ui",
416
+ });
417
+ return { ok: true, sessionId: meta.sessionId, restoredTo: restored.restoredTo };
418
+ } catch (error) {
419
+ await finishOperation({ dataRoot, id: record.id, state: "failed", detail: messageOf(error) });
420
+ await audit.append({
421
+ action: "restore",
422
+ result: "failed",
423
+ sessionId: meta.sessionId,
424
+ entryId,
425
+ operator: request.operator ?? "ui",
426
+ detail: messageOf(error),
427
+ });
428
+ throw failure("session-delete/restore-failed", "恢复失败:" + messageOf(error));
429
+ }
430
+ }
431
+
432
+ /**
433
+ * @param {string} entryId
434
+ * @param {{ operator?: string }} [request]
435
+ */
436
+ async function purge(entryId, request = {}) {
437
+ const meta = await readEntry(dataRoot, entryId);
438
+ const record = await beginOperation({
439
+ dataRoot,
440
+ action: "purge",
441
+ extra: { entryId, sessionId: meta.sessionId },
442
+ });
443
+ try {
444
+ const result = await purgeEntry({ dataRoot, entryId });
445
+ await finishOperation({ dataRoot, id: record.id, state: "done" });
446
+ await audit.append({
447
+ action: "purge",
448
+ result: "ok",
449
+ entryId,
450
+ operator: request.operator ?? "ui",
451
+ detail: "释放约 " + result.bytes + " 字节",
452
+ });
453
+ return { ok: true, bytes: result.bytes, sessionId: meta.sessionId };
454
+ } catch (error) {
455
+ await finishOperation({ dataRoot, id: record.id, state: "failed", detail: messageOf(error) });
456
+ await audit.append({
457
+ action: "purge",
458
+ result: "failed",
459
+ entryId,
460
+ operator: request.operator ?? "ui",
461
+ detail: messageOf(error),
462
+ });
463
+ throw failure("session-delete/purge-failed", "彻底删除失败:" + messageOf(error));
464
+ }
465
+ }
466
+
467
+ /**
468
+ * 删除后对账:目录是否消失、每处引用是否还在。
469
+ * @param {string} sessionIdRaw
470
+ * @param {{ skipDirCheck?: boolean }} [options]
471
+ */
472
+ async function reconcile(sessionIdRaw, options = {}) {
473
+ const sessionId = requireSessionId(sessionIdRaw);
474
+ /** @type {{ id: string, label: string, status: "ok" | "failed" | "skipped", detail: string }[]} */
475
+ const checks = [];
476
+
477
+ if (options.skipDirCheck) {
478
+ checks.push({ id: "session-dir", label: "会话目录", status: "ok", detail: "已移入回收站" });
479
+ } else {
480
+ const located = await locateSession({
481
+ dataRoot,
482
+ sessionId,
483
+ header: undefined,
484
+ persistence: caps.services.persistence,
485
+ });
486
+ checks.push(
487
+ located.location
488
+ ? {
489
+ id: "session-dir",
490
+ label: "会话目录",
491
+ status: "failed",
492
+ detail: "目录仍存在:" + located.location.path,
493
+ }
494
+ : { id: "session-dir", label: "会话目录", status: "ok", detail: "会话目录已不存在" },
495
+ );
496
+ }
497
+
498
+ for (const ref of refs) {
499
+ if (typeof ref.inspect !== "function") continue;
500
+ try {
501
+ checks.push(await ref.inspect(sessionId));
502
+ } catch (error) {
503
+ checks.push({ id: ref.id, label: ref.label, status: "skipped", detail: messageOf(error) });
504
+ }
505
+ }
506
+ return checks;
507
+ }
508
+
509
+ async function health() {
510
+ const pending = await listPending(dataRoot);
511
+ return {
512
+ plugin: pkg.name,
513
+ version: pkg.version,
514
+ dataRoot,
515
+ sessionsRoot: sessionsRoot(dataRoot),
516
+ trashRoot: trashRoot(dataRoot),
517
+ capabilities: describeCapabilities(caps),
518
+ pending: pending.length,
519
+ readOnly: caps.tier === "unknown",
520
+ };
521
+ }
522
+
523
+ return {
524
+ caps,
525
+ health,
526
+ plan: /** @param {unknown} sessionId */ async (sessionId) => (await makePlan(sessionId)).plan,
527
+ trash,
528
+ list,
529
+ restore,
530
+ purge,
531
+ reconcile,
532
+ auditLog,
533
+ };
534
+ }
package/lib/paths.js ADDED
@@ -0,0 +1,148 @@
1
+ // @ts-check
2
+ // 路径解析与安全校验。所有函数都接受显式 dataRoot,方便在 mkdtemp 里测试。
3
+ // 目录布局与命名编码来自 DSH 0.2.1-rc.5 的 JSONL 后端,见 docs/runtime/0.2.1-rc.5.md §6.2。
4
+ import { homedir } from "node:os";
5
+ import { join, resolve, sep } from "node:path";
6
+
7
+ /**
8
+ * 会话 id 的传输安全形态。首字符必须是字母或数字,从而排除 "."、".." 与绝对路径。
9
+ * 与宿主自身生成的 id(`session-<uuid>` / 裸 uuid)一致。
10
+ */
11
+ const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9_$.-]{0,127}$/u;
12
+
13
+ /**
14
+ * 解析数据根。优先级:配置 dataRoot → 环境变量 DSH_HOME → ~/.dsh。
15
+ * 永远返回绝对路径;不创建目录(创建由调用方负责)。
16
+ *
17
+ * @param {{ dataRoot?: unknown } | undefined} [config] 插件配置。
18
+ * @param {NodeJS.ProcessEnv} [env] 环境变量(测试可注入)。
19
+ * @param {string} [home] 用户主目录(测试可注入)。
20
+ * @returns {string} 绝对路径。
21
+ */
22
+ export function resolveDataRoot(config, env = process.env, home = homedir()) {
23
+ const configured = typeof config?.dataRoot === "string" ? config.dataRoot.trim() : "";
24
+ if (configured) return resolve(configured);
25
+ const fromEnv = typeof env?.DSH_HOME === "string" ? env.DSH_HOME.trim() : "";
26
+ if (fromEnv) return resolve(fromEnv);
27
+ return resolve(join(home, ".dsh"));
28
+ }
29
+
30
+ /** @param {string} dataRoot @returns {string} */
31
+ export function sessionsRoot(dataRoot) {
32
+ return join(dataRoot, "sessions");
33
+ }
34
+
35
+ /** @param {string} dataRoot @returns {string} */
36
+ export function trashRoot(dataRoot) {
37
+ return join(dataRoot, "session-trash");
38
+ }
39
+
40
+ /** @param {string} dataRoot @returns {string} */
41
+ export function journalDir(dataRoot) {
42
+ return join(trashRoot(dataRoot), "journal");
43
+ }
44
+
45
+ /** @param {string} dataRoot @returns {string} */
46
+ export function auditPath(dataRoot) {
47
+ return join(trashRoot(dataRoot), "audit.log");
48
+ }
49
+
50
+ /**
51
+ * 会话 id 是否安全可用作单段路径。
52
+ * @param {unknown} id
53
+ * @returns {boolean}
54
+ */
55
+ export function isSafeSessionId(id) {
56
+ return typeof id === "string" && SAFE_ID.test(id);
57
+ }
58
+
59
+ /**
60
+ * 校验并返回会话 id;不合法直接抛出,避免路径穿越。
61
+ * @param {unknown} id
62
+ * @returns {string}
63
+ */
64
+ export function requireSessionId(id) {
65
+ if (!isSafeSessionId(id)) {
66
+ throw Object.assign(new Error("session id must be a transport-safe identifier"), {
67
+ code: "session-delete/invalid-id",
68
+ });
69
+ }
70
+ return /** @type {string} */ (id);
71
+ }
72
+
73
+ /**
74
+ * 把任意字符串编码成单段安全文件名(宿主 JSONL 后端同款规则):
75
+ * 仅 A-Za-z0-9._- 保持原样,其余按 UTF-16 码元写成 ~XXXX(大写十六进制)。
76
+ * 该规则来自宿主行为(见 docs/runtime §6.2),用于在拿不到 locate() 时定位目录。
77
+ *
78
+ * @param {string} raw
79
+ * @returns {string}
80
+ */
81
+ export function encodeSegment(raw) {
82
+ if (raw.length === 0) throw new Error("cannot encode an empty path segment");
83
+ if (raw === ".") return "~002E";
84
+ if (raw === "..") return "~002E~002E";
85
+ let out = "";
86
+ for (let i = 0; i < raw.length; i += 1) {
87
+ const code = raw.charCodeAt(i);
88
+ const ch = String.fromCharCode(code);
89
+ if (ch !== "~" && /^[A-Za-z0-9._-]$/.test(ch)) out += ch;
90
+ else out += "~" + code.toString(16).toUpperCase().padStart(4, "0");
91
+ }
92
+ return out;
93
+ }
94
+
95
+ /**
96
+ * 项目目录键:把 cwd 的分隔符压成 "-",其余不安全码元转义,并加 -- 包裹。
97
+ * @param {string} cwd
98
+ * @returns {string}
99
+ */
100
+ export function projectKey(cwd) {
101
+ if (typeof cwd !== "string" || cwd.length === 0) {
102
+ throw new Error("cannot encode an empty project path");
103
+ }
104
+ let readable = "";
105
+ let separatorRun = false;
106
+ for (let i = 0; i < cwd.length; i += 1) {
107
+ const code = cwd.charCodeAt(i);
108
+ const ch = String.fromCharCode(code);
109
+ if (ch === "/" || ch === "\\" || ch === ":") {
110
+ if (!separatorRun) readable += "-";
111
+ separatorRun = true;
112
+ } else if (ch !== "~" && /^[A-Za-z0-9._-]$/.test(ch)) {
113
+ readable += ch;
114
+ separatorRun = false;
115
+ } else {
116
+ readable += "~" + code.toString(16).toUpperCase().padStart(4, "0");
117
+ separatorRun = false;
118
+ }
119
+ }
120
+ return `--${(readable.replace(/^-+/, "") || "root").slice(0, 251)}--`;
121
+ }
122
+
123
+ /**
124
+ * 子路径必须严格位于 parent 之下(防目录穿越与符号链接逃逸由调用方 realpath 后校验)。
125
+ * @param {string} parent
126
+ * @param {string} child
127
+ * @returns {boolean}
128
+ */
129
+ export function isInside(parent, child) {
130
+ const base = resolve(parent);
131
+ const target = resolve(child);
132
+ return target === base || target.startsWith(base.endsWith(sep) ? base : base + sep);
133
+ }
134
+
135
+ /**
136
+ * 断言路径位于数据根内。
137
+ * @param {string} dataRoot
138
+ * @param {string} target
139
+ * @returns {string} target
140
+ */
141
+ export function requireInside(dataRoot, target) {
142
+ if (!isInside(dataRoot, target)) {
143
+ throw Object.assign(new Error("refusing to touch a path outside the DSH data root"), {
144
+ code: "session-delete/unsafe-path",
145
+ });
146
+ }
147
+ return target;
148
+ }