@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.
package/lib/plan.js ADDED
@@ -0,0 +1,185 @@
1
+ // @ts-check
2
+ // plan 是纯函数:输入一份事实快照,输出可展示、可比对的影响面对象。
3
+ // 执行阶段会用同一个函数重算 digest,不一致就中止 —— 预演与执行永不漂移(ADR 0004 §1)。
4
+ import { createHash } from "node:crypto";
5
+
6
+ /**
7
+ * @typedef {object} ActivityGroup
8
+ * @property {string} kind 活动类型(turn / subagent / job / schedule / other)。
9
+ * @property {number} count 条目数。
10
+ * @property {string[]} labels 人类可读标签(标题或 id)。
11
+ */
12
+
13
+ /**
14
+ * @typedef {object} PlanBlocker
15
+ * @property {string} code 稳定的机器可读原因码。
16
+ * @property {string} message 给用户看的原因。
17
+ */
18
+
19
+ /**
20
+ * @typedef {object} PlanInput
21
+ * @property {string} sessionId
22
+ * @property {string | null} [title]
23
+ * @property {string | null} [cwd]
24
+ * @property {number | null} [sizeBytes]
25
+ * @property {boolean} [live]
26
+ * @property {ActivityGroup[]} [activity]
27
+ * @property {{ id: string, title: string | null }[]} [children]
28
+ * @property {{ path: string, tier: "locate" | "scan" } | null} [location]
29
+ * @property {string | null} [trashPath]
30
+ * @property {{ id: string, label: string, tier: string }[]} [removes]
31
+ * @property {PlanBlocker[]} [blockers]
32
+ */
33
+
34
+ /**
35
+ * @typedef {object} Plan
36
+ * @property {number} version
37
+ * @property {string} sessionId
38
+ * @property {string | null} title
39
+ * @property {string | null} cwd
40
+ * @property {number | null} sizeBytes
41
+ * @property {boolean} live
42
+ * @property {ActivityGroup[]} activity
43
+ * @property {{ id: string, title: string | null }[]} children
44
+ * @property {{ path: string, tier: "locate" | "scan" } | null} location
45
+ * @property {string | null} trashPath
46
+ * @property {{ id: string, label: string, tier: string }[]} removes
47
+ * @property {PlanBlocker[]} blockers
48
+ * @property {string} digest
49
+ */
50
+
51
+ /**
52
+ * 确定性序列化:键排序、丢弃 undefined,保证同一份事实永远得到同一摘要。
53
+ * @param {unknown} value
54
+ * @returns {string}
55
+ */
56
+ export function stableStringify(value) {
57
+ if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
58
+ if (Array.isArray(value)) return "[" + value.map(stableStringify).join(",") + "]";
59
+ const record = /** @type {Record<string, unknown>} */ (value);
60
+ const keys = Object.keys(record).sort();
61
+ return (
62
+ "{" +
63
+ keys
64
+ .filter((k) => record[k] !== undefined)
65
+ .map((k) => JSON.stringify(k) + ":" + stableStringify(record[k]))
66
+ .join(",") +
67
+ "}"
68
+ );
69
+ }
70
+
71
+ /** @param {string} text @returns {string} */
72
+ function sha256(text) {
73
+ return createHash("sha256").update(text, "utf8").digest("hex");
74
+ }
75
+
76
+ /**
77
+ * 摘要只覆盖「影响删除后果」的字段:目标、定位、体积、活体、活动、子会话、引用清单、阻断原因。
78
+ * 标题与时间戳不参与,避免因为改名导致用户需要重新确认。
79
+ * @param {Omit<Plan, "digest" | "version">} plan
80
+ * @returns {string}
81
+ */
82
+ export function digestOf(plan) {
83
+ const canonical = {
84
+ sessionId: plan.sessionId,
85
+ cwd: plan.cwd,
86
+ sizeBytes: plan.sizeBytes,
87
+ live: plan.live,
88
+ location: plan.location?.path ?? null,
89
+ trashPath: plan.trashPath,
90
+ activity: plan.activity.map((g) => ({ kind: g.kind, count: g.count })),
91
+ children: plan.children.map((c) => c.id).sort(),
92
+ removes: plan.removes.map((r) => r.id).sort(),
93
+ blockers: plan.blockers.map((b) => b.code).sort(),
94
+ };
95
+ return sha256(stableStringify(canonical)).slice(0, 32);
96
+ }
97
+
98
+ /**
99
+ * 生成 Plan。纯函数:不读盘、不调宿主服务。
100
+ * @param {PlanInput} input
101
+ * @returns {Plan}
102
+ */
103
+ export function buildPlan(input) {
104
+ const activity = [...(input.activity ?? [])].sort((a, b) => a.kind.localeCompare(b.kind));
105
+ const children = [...(input.children ?? [])].sort((a, b) => a.id.localeCompare(b.id));
106
+ const removes = [...(input.removes ?? [])].sort((a, b) => a.id.localeCompare(b.id));
107
+ /** @type {PlanBlocker[]} */
108
+ const blockers = [];
109
+ if (!input.location) {
110
+ blockers.push({
111
+ code: "session-delete/location-unknown",
112
+ message: "找不到这个会话在磁盘上的位置(可能是新版本换了目录布局)。",
113
+ });
114
+ }
115
+ for (const blocker of input.blockers ?? []) {
116
+ if (!blockers.some((b) => b.code === blocker.code)) blockers.push(blocker);
117
+ }
118
+
119
+ /** @type {Omit<Plan, "digest">} */
120
+ const base = {
121
+ version: 1,
122
+ sessionId: input.sessionId,
123
+ title: input.title ?? null,
124
+ cwd: input.cwd ?? null,
125
+ sizeBytes: typeof input.sizeBytes === "number" ? input.sizeBytes : null,
126
+ live: Boolean(input.live),
127
+ activity,
128
+ children,
129
+ location: input.location ?? null,
130
+ trashPath: input.trashPath ?? null,
131
+ removes,
132
+ blockers,
133
+ };
134
+ return { ...base, digest: digestOf(base) };
135
+ }
136
+
137
+ /**
138
+ * 执行前重新计算摘要,用于拦截「确认框打开期间事实发生变化」。
139
+ * @param {Plan} plan
140
+ * @returns {boolean} 摘要是否仍然一致。
141
+ */
142
+ export function planStillValid(plan) {
143
+ return digestOf(plan) === plan.digest;
144
+ }
145
+
146
+ /**
147
+ * 是否允许执行删除(没有阻断原因)。
148
+ * @param {Plan} plan
149
+ * @returns {boolean}
150
+ */
151
+ export function planExecutable(plan) {
152
+ return plan.blockers.length === 0;
153
+ }
154
+
155
+ /**
156
+ * 影响面的一句话摘要(确认框与审计共用)。
157
+ * @param {Plan} plan
158
+ * @returns {string}
159
+ */
160
+ export function summarizePlan(plan) {
161
+ const parts = [];
162
+ parts.push(plan.sizeBytes === null ? "体积未知" : `${formatBytes(plan.sizeBytes)}`);
163
+ if (plan.live) parts.push("会话正在本机打开");
164
+ if (plan.children.length > 0) parts.push(`${plan.children.length} 个子代理会话`);
165
+ if (plan.activity.length > 0)
166
+ parts.push(plan.activity.map((a) => `${a.count} 个${a.kind}`).join("、"));
167
+ return parts.join(" · ");
168
+ }
169
+
170
+ /**
171
+ * @param {number} bytes
172
+ * @returns {string}
173
+ */
174
+ export function formatBytes(bytes) {
175
+ if (!Number.isFinite(bytes) || bytes < 0) return "0 B";
176
+ if (bytes < 1024) return `${Math.round(bytes)} B`;
177
+ const units = ["KB", "MB", "GB", "TB"];
178
+ let value = bytes / 1024;
179
+ let unit = 0;
180
+ while (value >= 1024 && unit < units.length - 1) {
181
+ value /= 1024;
182
+ unit += 1;
183
+ }
184
+ return `${value >= 10 ? value.toFixed(0) : value.toFixed(1)} ${units[unit]}`;
185
+ }
package/lib/refs.js ADDED
@@ -0,0 +1,192 @@
1
+ // @ts-check
2
+ // 7 处引用的适配器表。每一处都实现同一组动作:snapshot / remove / restore / inspect。
3
+ // tier 决定它在 plan 里被标成「可自动处理」还是「未知,仅报告」。
4
+ import { join } from "node:path";
5
+ import { trashRoot } from "./paths.js";
6
+
7
+ /**
8
+ * @typedef {"api" | "internal" | "unknown"} RefTier
9
+ *
10
+ * @typedef {object} RefSnapshot
11
+ * @property {string[]} [workspaceIds]
12
+ * @property {boolean | null} [pinned]
13
+ *
14
+ * @typedef {object} RefAdapter
15
+ * @property {string} id
16
+ * @property {string} label
17
+ * @property {RefTier} tier
18
+ * @property {(sessionId: string) => Promise<RefSnapshot>} [snapshot]
19
+ * @property {(sessionId: string, snapshot: RefSnapshot) => Promise<void>} [remove]
20
+ * @property {(sessionId: string, snapshot: RefSnapshot) => Promise<void>} [restore]
21
+ * @property {(sessionId: string) => Promise<{ id: string, label: string, status: "ok" | "failed" | "skipped", detail: string }>} [inspect]
22
+ */
23
+
24
+ /**
25
+ * 构建引用适配器列表。缺失的服务会以 tier="unknown" 的形式出现在清单里,
26
+ * 让用户知道「这一处我们处理不了」,而不是假装删干净了。
27
+ *
28
+ * @param {import("./capability.js").Capabilities} caps
29
+ * @param {any} logger
30
+ * @returns {RefAdapter[]}
31
+ */
32
+ export function buildRefs(caps, logger) {
33
+ const { workspace, storageDomain, sessions, agents } = caps.services;
34
+ const check = caps.checks;
35
+
36
+ /** @type {RefAdapter[]} */
37
+ const refs = [];
38
+
39
+ refs.push({
40
+ id: "workspace-archive",
41
+ label: "归档标记",
42
+ tier: check["workspace.unarchive"] ? "api" : "unknown",
43
+ remove: async (sessionId) => {
44
+ if (typeof workspace?.unarchiveSession !== "function")
45
+ throw new Error("unarchiveSession unavailable");
46
+ await workspace.unarchiveSession(sessionId);
47
+ },
48
+ });
49
+
50
+ refs.push({
51
+ id: "workspace-pin",
52
+ label: "置顶标记",
53
+ tier: check["workspace.unpin"] ? "api" : "unknown",
54
+ remove: async (sessionId) => {
55
+ if (typeof workspace?.unpinSession !== "function")
56
+ throw new Error("unpinSession unavailable");
57
+ await workspace.unpinSession(sessionId);
58
+ },
59
+ restore: async (sessionId, snapshot) => {
60
+ if (!snapshot?.pinned) return;
61
+ if (typeof workspace?.pinSession === "function") await workspace.pinSession(sessionId);
62
+ },
63
+ });
64
+
65
+ refs.push({
66
+ id: "workspace-slot",
67
+ label: "工作区记账",
68
+ tier: check["workspace.list"] ? "api" : "unknown",
69
+ snapshot: async (sessionId) => {
70
+ /** @type {string[]} */
71
+ const workspaceIds = [];
72
+ if (typeof workspace?.list !== "function") return { workspaceIds };
73
+ for (const item of workspace.list() ?? []) {
74
+ const ids = Array.isArray(item?.sessionIds) ? item.sessionIds : [];
75
+ if (ids.includes(sessionId)) workspaceIds.push(String(item.id));
76
+ }
77
+ return { workspaceIds };
78
+ },
79
+ remove: async (sessionId) => {
80
+ for (const item of workspace?.list?.() ?? []) {
81
+ const ids = Array.isArray(item?.sessionIds) ? item.sessionIds : [];
82
+ if (!ids.includes(sessionId)) continue;
83
+ if (typeof item.detachSession === "function") await item.detachSession(sessionId);
84
+ else logger.warn(`session-delete: workspace ${item.id} has no detachSession`);
85
+ }
86
+ },
87
+ restore: async (sessionId, snapshot) => {
88
+ for (const workspaceId of snapshot?.workspaceIds ?? []) {
89
+ const item = (workspace?.list?.() ?? []).find(
90
+ (/** @type {any} */ w) => String(w.id) === workspaceId,
91
+ );
92
+ if (item && typeof item.attachSession === "function") await item.attachSession(sessionId);
93
+ }
94
+ },
95
+ inspect: async (sessionId) => {
96
+ if (typeof workspace?.list !== "function") {
97
+ return {
98
+ id: "workspace-slot",
99
+ label: "工作区记账",
100
+ status: "skipped",
101
+ detail: "宿主没有 workspaceRegistry.list",
102
+ };
103
+ }
104
+ const remaining = (workspace.list() ?? []).filter(
105
+ (/** @type {any} */ item) =>
106
+ Array.isArray(item?.sessionIds) && item.sessionIds.includes(sessionId),
107
+ );
108
+ return remaining.length === 0
109
+ ? { id: "workspace-slot", label: "工作区记账", status: "ok", detail: "已从所有工作区摘除" }
110
+ : {
111
+ id: "workspace-slot",
112
+ label: "工作区记账",
113
+ status: "failed",
114
+ detail: `仍留在 ${remaining.length} 个工作区`,
115
+ };
116
+ },
117
+ });
118
+
119
+ refs.push({
120
+ id: "projection-cache",
121
+ label: "投影缓存",
122
+ tier: check["storage.domain"] ? "internal" : "unknown",
123
+ remove: async (sessionId) => {
124
+ const domain = storageDomain?.get?.("session_projcache");
125
+ if (!domain) throw new Error("session_projcache domain unavailable");
126
+ const table = domain.table?.("sessions");
127
+ if (!table || typeof table.delete !== "function")
128
+ throw new Error("projection table unavailable");
129
+ await table.delete(sessionId);
130
+ },
131
+ });
132
+
133
+ refs.push({
134
+ id: "host-memory",
135
+ label: "宿主内存条目",
136
+ tier: check["sessions.detach"] ? "internal" : "unknown",
137
+ remove: async (sessionId) => {
138
+ const detach = (/** @type {any} */ service) => {
139
+ const entry = service?.store?.get?.(sessionId);
140
+ if (!entry) return;
141
+ if (typeof service.detachEntered !== "function")
142
+ throw new Error("detachEntered unavailable");
143
+ service.detachEntered(entry);
144
+ };
145
+ detach(agents);
146
+ detach(sessions);
147
+ },
148
+ inspect: async (sessionId) => {
149
+ const stillLive = typeof sessions?.get === "function" ? sessions.get(sessionId) : undefined;
150
+ return stillLive === undefined
151
+ ? { id: "host-memory", label: "宿主内存条目", status: "ok", detail: "已不在宿主内存中" }
152
+ : {
153
+ id: "host-memory",
154
+ label: "宿主内存条目",
155
+ status: "failed",
156
+ detail: "宿主仍持有该会话",
157
+ };
158
+ },
159
+ });
160
+
161
+ refs.push({
162
+ id: "spill-directory",
163
+ label: "spill 溢出目录",
164
+ tier: "unknown",
165
+ inspect: async () => ({
166
+ id: "spill-directory",
167
+ label: "spill 溢出目录",
168
+ status: "skipped",
169
+ detail: "布局未验证,未做处理(如需清理请手工确认)",
170
+ }),
171
+ });
172
+
173
+ return refs;
174
+ }
175
+
176
+ /**
177
+ * 回收站自身的一致性检查(meta 与实际数据是否对得上)。
178
+ * @param {string} dataRoot
179
+ * @param {{ entryId: string, bytes: number }[]} entries
180
+ * @returns {{ id: string, label: string, status: "ok" | "failed" | "skipped", detail: string }[]}
181
+ */
182
+ export function describeTrashRoot(dataRoot, entries) {
183
+ void entries;
184
+ return [
185
+ {
186
+ id: "trash-root",
187
+ label: "回收站目录",
188
+ status: "ok",
189
+ detail: join(trashRoot(dataRoot)),
190
+ },
191
+ ];
192
+ }
package/lib/service.js ADDED
@@ -0,0 +1,166 @@
1
+ // @ts-check
2
+ // Typert Remote 包装层:把 operations 的方法暴露给浏览器,一条 /api 通道。
3
+ // declareRemote 的写法参考 Jaylor-Wang/dsh-tool-session-delete(MIT),见根目录 NOTICE。
4
+ import { Remote, RemoteError, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
5
+ import { createOperations } from "./operations.js";
6
+ import { resolveDataRoot } from "./paths.js";
7
+
8
+ /**
9
+ * 在 decorator 语法不可用(V8 装饰器关闭)的运行时里登记一个 Remote 方法。
10
+ * @param {any} Proto 承载方法的类
11
+ * @param {string} method 方法名,同时也是线缆上的 export 名
12
+ * @returns {void}
13
+ */
14
+ function declareRemote(Proto, method) {
15
+ /** @type {Function[]} */
16
+ const initializers = [];
17
+ Remote(method)(void 0, {
18
+ name: method,
19
+ static: false,
20
+ private: false,
21
+ addInitializer(/** @type {Function} */ initializer) {
22
+ initializers.push(initializer);
23
+ },
24
+ });
25
+ if (initializers.length !== 1) {
26
+ throw new Error("session-delete: cannot declare Remote method " + method);
27
+ }
28
+ initializers[0].call(Object.create(Proto.prototype));
29
+ }
30
+
31
+ /**
32
+ * @param {unknown} error
33
+ * @returns {never}
34
+ */
35
+ function rethrow(error) {
36
+ if (error instanceof RemoteError) throw error;
37
+ const code = /** @type {any} */ (error)?.code;
38
+ const message = error instanceof Error ? error.message : String(error);
39
+ throw new RemoteError(typeof code === "string" ? code : "session-delete/failed", message, {
40
+ details: /** @type {any} */ (error)?.details ?? null,
41
+ });
42
+ }
43
+
44
+ export class SessionDeleteService extends TypertRemoteService {
45
+ /**
46
+ * @param {any} ctx host 上下文
47
+ * @param {{ dataRoot?: unknown }} [config]
48
+ */
49
+ constructor(ctx, config) {
50
+ super(ctx, "sessionDelete");
51
+ this.config = config ?? {};
52
+ /** @type {any} */
53
+ this._ops = null;
54
+ }
55
+
56
+ /**
57
+ * 惰性创建操作层:能力探测必须发生在宿主服务挂载之后,不能在构造函数里固化。
58
+ * @returns {any}
59
+ */
60
+ get ops() {
61
+ if (this._ops === null) {
62
+ this._ops = createOperations({
63
+ ctx: this.ctx,
64
+ dataRoot: resolveDataRoot(this.config),
65
+ logger: this.ctx.logger ?? console,
66
+ });
67
+ }
68
+ return this._ops;
69
+ }
70
+
71
+ /** 能力快照、数据根、待恢复的操作数。 */
72
+ async health() {
73
+ return this.ops.health();
74
+ }
75
+
76
+ /**
77
+ * 只读:返回完整影响面(plan/dry-run 的数据源)。
78
+ * @param {{ sessionId: string }} request
79
+ */
80
+ async plan(request) {
81
+ try {
82
+ return await this.ops.plan(request?.sessionId);
83
+ } catch (error) {
84
+ rethrow(error);
85
+ }
86
+ }
87
+
88
+ /**
89
+ * 把会话移入回收站。
90
+ * @param {{ sessionId: string, digest?: string, title?: string | null }} request
91
+ */
92
+ async trash(request) {
93
+ try {
94
+ return await this.ops.trash(request?.sessionId, {
95
+ digest: request?.digest,
96
+ title: request?.title,
97
+ operator: "ui",
98
+ });
99
+ } catch (error) {
100
+ rethrow(error);
101
+ }
102
+ }
103
+
104
+ async list() {
105
+ try {
106
+ return await this.ops.list();
107
+ } catch (error) {
108
+ rethrow(error);
109
+ }
110
+ }
111
+
112
+ /**
113
+ * 从回收站恢复。
114
+ * @param {{ entryId: string }} request
115
+ */
116
+ async restore(request) {
117
+ try {
118
+ return await this.ops.restore(request?.entryId, { operator: "ui" });
119
+ } catch (error) {
120
+ rethrow(error);
121
+ }
122
+ }
123
+
124
+ /**
125
+ * 彻底删除一个回收站条目。
126
+ * @param {{ entryId: string }} request
127
+ */
128
+ async purge(request) {
129
+ try {
130
+ return await this.ops.purge(request?.entryId, { operator: "ui" });
131
+ } catch (error) {
132
+ rethrow(error);
133
+ }
134
+ }
135
+
136
+ /**
137
+ * @param {{ limit?: number }} [request]
138
+ */
139
+ async audit(request) {
140
+ try {
141
+ return await this.ops.auditLog(request?.limit ?? 100);
142
+ } catch (error) {
143
+ rethrow(error);
144
+ }
145
+ }
146
+
147
+ /**
148
+ * @param {{ sessionId: string }} request
149
+ */
150
+ async reconcile(request) {
151
+ try {
152
+ return { checks: await this.ops.reconcile(request?.sessionId) };
153
+ } catch (error) {
154
+ rethrow(error);
155
+ }
156
+ }
157
+ }
158
+
159
+ declareRemote(SessionDeleteService, "health");
160
+ declareRemote(SessionDeleteService, "plan");
161
+ declareRemote(SessionDeleteService, "trash");
162
+ declareRemote(SessionDeleteService, "list");
163
+ declareRemote(SessionDeleteService, "restore");
164
+ declareRemote(SessionDeleteService, "purge");
165
+ declareRemote(SessionDeleteService, "audit");
166
+ declareRemote(SessionDeleteService, "reconcile");