dsh-mop 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +41 -2
- package/client.js +1859 -0
- package/cordis.patch.yml +3 -0
- package/icon.svg +5 -0
- package/index.js +40 -0
- package/lib/artifacts.mjs +47 -0
- package/lib/clean.mjs +316 -0
- package/lib/errors.mjs +6 -0
- package/lib/guard.mjs +20 -0
- package/lib/home.mjs +12 -0
- package/lib/routes.mjs +151 -0
- package/lib/session-shell.mjs +45 -0
- package/lib/store.mjs +386 -0
- package/locale/de.json +6 -0
- package/locale/en.json +6 -0
- package/locale/es.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/pt.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +43 -4
package/cordis.patch.yml
ADDED
package/icon.svg
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none" stroke="#4d8fd6" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
|
|
2
|
+
<path d="M13.5 2.5H2.5C1.94772 2.5 1.5 2.94772 1.5 3.5V4.5C1.5 5.05228 1.94772 5.5 2.5 5.5H13.5C14.0523 5.5 14.5 5.05228 14.5 4.5V3.5C14.5 2.94772 14.0523 2.5 13.5 2.5Z"/>
|
|
3
|
+
<path d="M2.5 5.5V13.5C2.5 13.7652 2.60536 14.0196 2.79289 14.2071C2.98043 14.3946 3.23478 14.5 3.5 14.5H12.5C12.7652 14.5 13.0196 14.3946 13.2071 14.2071C13.3946 14.0196 13.5 13.7652 13.5 13.5V5.5"/>
|
|
4
|
+
<path d="M6.5 9.5H9.5"/>
|
|
5
|
+
</svg>
|
package/index.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-mop 宿主半边:清理遗留会话数据,经 connection.fetch 路由暴露给浏览器。
|
|
3
|
+
*
|
|
4
|
+
* 行级配置(protectWorkspaces)通过官方 Loader 的 Config 校验与编辑面
|
|
5
|
+
* (设置 → 插件 → dsh-mop 行 → 配置)读写。
|
|
6
|
+
* @module dsh-mop
|
|
7
|
+
*/
|
|
8
|
+
import z from '@deepseek-ai/schemastery';
|
|
9
|
+
import { registerRoutes } from './lib/routes.mjs';
|
|
10
|
+
import { isPurgingSession, isExternalUnarchive } from './lib/clean.mjs';
|
|
11
|
+
import { cleanError } from './lib/errors.mjs';
|
|
12
|
+
|
|
13
|
+
export const inject = ['connection', 'sessionQuery', 'sessionPersistence', 'workspaceRegistry'];
|
|
14
|
+
|
|
15
|
+
/** 行配置 schema:受保护的工作区根路径列表(绝对路径)。 */
|
|
16
|
+
export const Config = z.object({
|
|
17
|
+
protectWorkspaces: z.array(z.string()).default([]),
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
export function apply(ctx, rawConfig = {}) {
|
|
21
|
+
// Config 是唯一解析点:Loader 校验过的输入直接通过;未经校验的
|
|
22
|
+
// 畸形输入退回默认值,不让插件加载失败。
|
|
23
|
+
let config;
|
|
24
|
+
try { config = Config(rawConfig); } catch { config = Config({}); }
|
|
25
|
+
// Coordinate same-host activation and unarchive with the deletion window.
|
|
26
|
+
// session/created 的同步 throw 是官方支持的否决路径(dsh-session 注释:
|
|
27
|
+
// "Synchronous throws intentionally propagate and veto publication");
|
|
28
|
+
// workspace/session-unarchiving 的 parallel 分发会把 rejection 聚合后
|
|
29
|
+
// 抛给调用方,同样阻断外部取消归档。
|
|
30
|
+
if (typeof ctx.on === 'function') ctx.effect(() => {
|
|
31
|
+
const stopUnarchive = ctx.on('workspace/session-unarchiving', ({ sessionId }) => {
|
|
32
|
+
if (isExternalUnarchive(sessionId)) throw cleanError('purge_busy');
|
|
33
|
+
});
|
|
34
|
+
const stopCreate = ctx.on('session/created', (session) => {
|
|
35
|
+
if (isPurgingSession(session.id)) throw cleanError('purge_busy');
|
|
36
|
+
});
|
|
37
|
+
return () => { stopUnarchive(); stopCreate(); };
|
|
38
|
+
}, 'dsh-mop: purge coordination');
|
|
39
|
+
registerRoutes(ctx, config);
|
|
40
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { lstat, readdir, realpath, rmdir, unlink } from 'node:fs/promises';
|
|
2
|
+
import { basename, dirname, join, resolve } from 'node:path';
|
|
3
|
+
import { reject } from './errors.mjs';
|
|
4
|
+
|
|
5
|
+
export const isSystemMetadata = (name) => ['.DS_Store', 'Thumbs.db', 'desktop.ini'].includes(name);
|
|
6
|
+
|
|
7
|
+
export async function removeEmptyProject(project, root) {
|
|
8
|
+
project = resolve(project);
|
|
9
|
+
root = resolve(root);
|
|
10
|
+
if (dirname(project) !== root) reject('unsafe_path');
|
|
11
|
+
const [rootInfo, projectInfo] = await Promise.all([lstat(root), lstat(project)]);
|
|
12
|
+
if (!rootInfo.isDirectory() || rootInfo.isSymbolicLink() || !projectInfo.isDirectory() || projectInfo.isSymbolicLink()) reject('unsafe_path');
|
|
13
|
+
if (dirname(await realpath(project)) !== await realpath(root)) reject('unsafe_path');
|
|
14
|
+
const names = await readdir(project);
|
|
15
|
+
if (names.some((name) => !isSystemMetadata(name))) reject('session_changed');
|
|
16
|
+
const entries = [];
|
|
17
|
+
for (const name of names) {
|
|
18
|
+
const path = join(project, name);
|
|
19
|
+
const info = await lstat(path, { bigint: true });
|
|
20
|
+
if (!info.isFile() || info.isSymbolicLink()) reject('unsafe_path');
|
|
21
|
+
entries.push({ path, info });
|
|
22
|
+
}
|
|
23
|
+
for (const { path, info } of entries) {
|
|
24
|
+
const current = await lstat(path, { bigint: true });
|
|
25
|
+
if (!current.isFile() || current.isSymbolicLink() || current.dev !== info.dev || current.ino !== info.ino
|
|
26
|
+
|| current.size !== info.size || current.mtimeNs !== info.mtimeNs) reject('session_changed');
|
|
27
|
+
}
|
|
28
|
+
for (const { path } of entries) await unlink(path);
|
|
29
|
+
await rmdir(project);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Permit platform canonicalization of ancestors while rejecting links at the
|
|
33
|
+
// managed root and both levels beneath it.
|
|
34
|
+
export async function assertCanonicalSessionPath(root, dir) {
|
|
35
|
+
root = resolve(root);
|
|
36
|
+
dir = resolve(dir);
|
|
37
|
+
const project = dirname(dir);
|
|
38
|
+
for (const path of [root, project, dir]) {
|
|
39
|
+
const info = await lstat(path);
|
|
40
|
+
if (!info.isDirectory() || info.isSymbolicLink()) reject('unsafe_path');
|
|
41
|
+
}
|
|
42
|
+
const [realRoot, realProject, realDir] = await Promise.all([root, project, dir].map((path) => realpath(path)));
|
|
43
|
+
if (realProject !== await realpath(join(root, basename(project)))
|
|
44
|
+
|| dirname(realProject) !== realRoot
|
|
45
|
+
|| realDir !== await realpath(join(project, basename(dir)))
|
|
46
|
+
|| dirname(realDir) !== realProject) reject('unsafe_path');
|
|
47
|
+
}
|
package/lib/clean.mjs
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
/** dsh-mop · 永久删除:日志目录、投影缓存、工作区注册一并清除,不留自有数据。
|
|
2
|
+
* 仍在本实例中挂载的会话(agents/sessions 注册表)会以 session_resident 拒绝:
|
|
3
|
+
* DSH 未提供跨组件释放常驻 Agent 的公开 API,官方标准下不做内部拆卸,
|
|
4
|
+
* 用户重启 DSH 后即可清理。 */
|
|
5
|
+
import { lstat, readdir, unlink } from 'node:fs/promises';
|
|
6
|
+
import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
7
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
8
|
+
import { assertSessionDirSafe } from './guard.mjs';
|
|
9
|
+
import { removeSessionShell } from './session-shell.mjs';
|
|
10
|
+
import { cleanError, reject } from './errors.mjs';
|
|
11
|
+
import { buildOverview, isEventOnlyLog, sessionsRoot, projcacheDir, workspaceTable } from './store.mjs';
|
|
12
|
+
import { assertCanonicalSessionPath, isSystemMetadata, removeEmptyProject } from './artifacts.mjs';
|
|
13
|
+
|
|
14
|
+
/** Server-derived keys identify the only paths and registry entries eligible for selection. */
|
|
15
|
+
export function listResidue(overview) {
|
|
16
|
+
return [
|
|
17
|
+
...(overview.residue.orphanTasks ?? []).map((item) => ({
|
|
18
|
+
key: `task:${item.id}`, kind: 'orphan-task', id: item.id, label: item.title,
|
|
19
|
+
targetSessionId: item.targetSessionId, updatedAt: item.updatedAt, status: item.status,
|
|
20
|
+
workspacePath: item.workspacePath, workspaceTitle: item.workspaceTitle, workspaceCreatedAt: item.workspaceCreatedAt,
|
|
21
|
+
sizeBytes: null, mtimeMs: item.mtimeMs,
|
|
22
|
+
})),
|
|
23
|
+
...overview.residue.orphanCaches.map((item) => ({
|
|
24
|
+
key: `cache:${item.id}`, kind: 'orphan-cache', id: item.id, label: item.title || item.id,
|
|
25
|
+
workspacePath: item.workspacePath, workspaceTitle: item.workspaceTitle, workspaceCreatedAt: item.workspaceCreatedAt,
|
|
26
|
+
sizeBytes: item.sizeBytes, mtimeMs: item.mtimeMs,
|
|
27
|
+
})),
|
|
28
|
+
...overview.residue.ghostRegistrations.map((item) => ({
|
|
29
|
+
key: `ghost:${item.workspaceId}:${item.id}`, kind: 'ghost-registry', id: item.id, workspaceId: item.workspaceId, label: item.id,
|
|
30
|
+
workspacePath: item.workspacePath, workspaceTitle: item.workspaceTitle, workspaceCreatedAt: item.workspaceCreatedAt,
|
|
31
|
+
sizeBytes: null, mtimeMs: null,
|
|
32
|
+
})),
|
|
33
|
+
...overview.residue.shellDirs.map((item) => ({
|
|
34
|
+
key: `shell:${item.sessionDir}`, kind: 'shell-dir', id: item.sessionId, label: item.sessionId,
|
|
35
|
+
workspacePath: item.workspacePath, workspaceTitle: item.workspaceTitle, workspaceCreatedAt: item.workspaceCreatedAt,
|
|
36
|
+
sizeBytes: item.sizeBytes, mtimeMs: item.mtimeMs, shellType: item.shellType,
|
|
37
|
+
})),
|
|
38
|
+
...overview.residue.emptyProjectDirs.map((item) => ({
|
|
39
|
+
key: `dir:${item.path}`, kind: 'empty-project', id: item.path,
|
|
40
|
+
label: basename(item.path) || item.path,
|
|
41
|
+
sizeBytes: item.sizeBytes, mtimeMs: item.mtimeMs,
|
|
42
|
+
})),
|
|
43
|
+
];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const LOG = /^session(?:\.v\d+)?\.jsonl(?:\.zstd)?$/;
|
|
47
|
+
const purging = new Set();
|
|
48
|
+
const unarchiveOwner = new AsyncLocalStorage();
|
|
49
|
+
export function isPurgingSession(id) { return purging.has(id); }
|
|
50
|
+
export function isExternalUnarchive(id) { return purging.has(id) && unarchiveOwner.getStore() !== id; }
|
|
51
|
+
|
|
52
|
+
/** A session still mounted in this DSH instance; releasing it needs a restart. */
|
|
53
|
+
const isResidentSession = (ctx, id) => !!(ctx.get('sessions')?.get(id) || ctx.get('agents')?.get(id));
|
|
54
|
+
|
|
55
|
+
const isTaskTarget = (task, id) => (task.target?.kind === 'session' || task.target?.kind === 'new_once') && task.target.sessionId === id;
|
|
56
|
+
|
|
57
|
+
async function checkCurrent(ctx, id) {
|
|
58
|
+
if (!(ctx.workspaceRegistry.archivedSessionIds ?? []).includes(id)) reject('session_not_archived');
|
|
59
|
+
const agent = ctx.get('agents')?.get(id);
|
|
60
|
+
if (agent && agent.status !== 'idle') reject('session_resident');
|
|
61
|
+
let activity;
|
|
62
|
+
try { activity = await ctx.waterfall('workspace/session-activity', { sessionId: id }, () => Promise.resolve([])); }
|
|
63
|
+
catch { reject('reference_check_failed'); }
|
|
64
|
+
if (!Array.isArray(activity)) reject('reference_check_failed');
|
|
65
|
+
if (activity.length) reject('session_resident');
|
|
66
|
+
const schedule = ctx.get('schedule');
|
|
67
|
+
if (schedule) {
|
|
68
|
+
let tasks;
|
|
69
|
+
try { tasks = await schedule.catalog(); } catch { reject('reference_check_failed'); }
|
|
70
|
+
if (!Array.isArray(tasks)) reject('reference_check_failed');
|
|
71
|
+
if (tasks.some((task) => !['paused', 'ended'].includes(task.status) && isTaskTarget(task, id))) reject('schedule_reference');
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function workspaceTargets(ctx, id) {
|
|
76
|
+
const workspaces = await ctx.workspaceRegistry.list();
|
|
77
|
+
const table = workspaceTable(ctx);
|
|
78
|
+
if (!table) reject('workspace_unavailable');
|
|
79
|
+
const targets = [];
|
|
80
|
+
for (const workspace of workspaces) {
|
|
81
|
+
const record = table.get(workspace.id);
|
|
82
|
+
if (!record || !Array.isArray(record.sessionIds)) reject('workspace_unavailable');
|
|
83
|
+
if (!record.sessionIds.includes(id)) continue;
|
|
84
|
+
// detachSession prunes every hidden candidate, not only the chosen ID.
|
|
85
|
+
const visible = new Set(workspace.sessionIds ?? []);
|
|
86
|
+
const hidden = record.sessionIds.filter((other) => other !== id && !visible.has(other));
|
|
87
|
+
if (hidden.length) throw Object.assign(cleanError('workspace_filtered'), { blockedIds: hidden });
|
|
88
|
+
if (typeof workspace.detachSession !== 'function') reject('workspace_unavailable');
|
|
89
|
+
targets.push(workspace);
|
|
90
|
+
}
|
|
91
|
+
return targets;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function logFiles(snapshot, id) {
|
|
95
|
+
if (snapshot?.location?.kind !== 'jsonl' || typeof snapshot.location.path !== 'string') reject('unsupported_storage');
|
|
96
|
+
if (snapshot.formatStatus !== 'current') reject('historical_format');
|
|
97
|
+
const selected = resolve(snapshot.location.path);
|
|
98
|
+
const dir = dirname(selected);
|
|
99
|
+
assertSessionDirSafe(dir, id);
|
|
100
|
+
await assertCanonicalSessionPath(sessionsRoot(), dir);
|
|
101
|
+
const names = await readdir(dir);
|
|
102
|
+
const files = [];
|
|
103
|
+
for (const name of names) {
|
|
104
|
+
if (name === 'session.lock' || isSystemMetadata(name)) {
|
|
105
|
+
const lock = await lstat(resolve(dir, name));
|
|
106
|
+
if (!lock.isFile() || lock.isSymbolicLink()) reject('unsafe_path');
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
if (!LOG.test(name)) reject('unknown_artifact');
|
|
110
|
+
const path = resolve(dir, name);
|
|
111
|
+
const stat = await lstat(path);
|
|
112
|
+
if (!stat.isFile() || stat.isSymbolicLink()) reject('unsafe_path');
|
|
113
|
+
files.push(path);
|
|
114
|
+
}
|
|
115
|
+
if (!files.includes(selected)) reject('unsafe_path');
|
|
116
|
+
return files.sort((a, b) => (a === selected ? 1 : 0) - (b === selected ? 1 : 0));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Delete verified JSONL generations of non-resident archived sessions. */
|
|
120
|
+
export async function purgeSessions(ctx, overview, sessionIds) {
|
|
121
|
+
const byId = new Map(overview.sessions.map((session) => [session.id, session]));
|
|
122
|
+
const deleted = [], failed = [];
|
|
123
|
+
for (const id of new Set(sessionIds)) {
|
|
124
|
+
const session = byId.get(id);
|
|
125
|
+
let claimed = false;
|
|
126
|
+
try {
|
|
127
|
+
if (!session) reject('session_not_found');
|
|
128
|
+
if (!session.archived) reject('session_not_archived');
|
|
129
|
+
if (session.protected) reject('protected_workspace');
|
|
130
|
+
if (session.purgeBlock === 'reference_check_failed') reject(session.purgeBlock);
|
|
131
|
+
if (purging.has(id)) reject('purge_busy');
|
|
132
|
+
purging.add(id);
|
|
133
|
+
claimed = true;
|
|
134
|
+
await checkCurrent(ctx, id);
|
|
135
|
+
const snapshot = await ctx.sessionPersistence.stat(id);
|
|
136
|
+
let files = [];
|
|
137
|
+
const remaining = snapshot ? [] : (await buildOverview(ctx, { protectWorkspaces: [] })).residue.shellDirs
|
|
138
|
+
.filter((item) => item.sessionId === id);
|
|
139
|
+
const shells = snapshot?.location?.path ? [{ sessionDir: dirname(snapshot.location.path), shellType: 'lock' }] : remaining;
|
|
140
|
+
if (snapshot) {
|
|
141
|
+
files = await logFiles(snapshot, id);
|
|
142
|
+
if (snapshot.header?.origin === 'subagent' && snapshot.header.parentSession) {
|
|
143
|
+
const parent = await ctx.sessionPersistence.stat(snapshot.header.parentSession);
|
|
144
|
+
if (parent?.formatStatus === 'migration-required') reject('historical_parent');
|
|
145
|
+
}
|
|
146
|
+
} else if (session.sessionDir) {
|
|
147
|
+
reject('session_changed');
|
|
148
|
+
} else {
|
|
149
|
+
// An interrupted purge leaves only the lock file. A directory with
|
|
150
|
+
// other unrecognized artifacts is not proof that the log is gone.
|
|
151
|
+
for (const shell of shells) {
|
|
152
|
+
assertSessionDirSafe(shell.sessionDir, id);
|
|
153
|
+
if (!['empty', 'lock', 'log'].includes(shell.shellType)) reject('unknown_artifact');
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
let targets = await workspaceTargets(ctx, id);
|
|
157
|
+
const cache = ctx.get('storageDomain')?.get('session_projcache')?.table('sessions');
|
|
158
|
+
if (!cache || typeof cache.delete !== 'function') reject('cache_unavailable');
|
|
159
|
+
await checkCurrent(ctx, id);
|
|
160
|
+
if (isResidentSession(ctx, id)) reject('session_resident');
|
|
161
|
+
if (snapshot) {
|
|
162
|
+
const current = await ctx.sessionPersistence.stat(id);
|
|
163
|
+
if (!current || current.revision !== snapshot.revision || current.location?.path !== snapshot.location.path) reject('session_changed');
|
|
164
|
+
files = await logFiles(current, id);
|
|
165
|
+
}
|
|
166
|
+
const cleanAssociated = async () => {
|
|
167
|
+
await cache.delete(id);
|
|
168
|
+
for (const workspace of targets) await workspace.detachSession(id);
|
|
169
|
+
};
|
|
170
|
+
if (snapshot || shells.length === 0) {
|
|
171
|
+
for (const file of files) await unlink(file);
|
|
172
|
+
await cleanAssociated();
|
|
173
|
+
}
|
|
174
|
+
for (const [index, shell] of shells.entries()) {
|
|
175
|
+
await removeSessionShell(shell.sessionDir, id, {
|
|
176
|
+
mode: shell.shellType === 'log' ? 'event-only' : 'metadata',
|
|
177
|
+
recheck: async () => {
|
|
178
|
+
await checkCurrent(ctx, id);
|
|
179
|
+
if (await ctx.sessionPersistence.stat(id)) reject('session_changed');
|
|
180
|
+
if (shell.shellType === 'log' && !await isEventOnlyLog(ctx, id, shell.sessionDir)) reject('session_changed');
|
|
181
|
+
targets = await workspaceTargets(ctx, id);
|
|
182
|
+
},
|
|
183
|
+
cleanup: !snapshot && index === 0 ? cleanAssociated : undefined,
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
// Once the log and registrations are gone, the registry's own
|
|
187
|
+
// unarchive hook may run to retire the otherwise orphaned archive ID.
|
|
188
|
+
await unarchiveOwner.run(id, () => ctx.workspaceRegistry.unarchiveSession(id));
|
|
189
|
+
deleted.push(id);
|
|
190
|
+
} catch (error) {
|
|
191
|
+
failed.push({ id, title: session?.title, code: error?.cleanCode || 'purge_failed',
|
|
192
|
+
...(error?.blockedIds ? { blockedCount: error.blockedIds.length } : {}),
|
|
193
|
+
...(!error?.cleanCode ? { message: String(error?.message ?? error) } : {}) });
|
|
194
|
+
} finally {
|
|
195
|
+
if (claimed) purging.delete(id);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return { deleted, failed };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Revalidate selected entries against a fresh overview before any changes. */
|
|
202
|
+
export async function cleanResidue(ctx, overview, selectedKeys, confirmedTasks = {}) {
|
|
203
|
+
const done = [];
|
|
204
|
+
const failed = [];
|
|
205
|
+
const cacheRoot = resolve(projcacheDir());
|
|
206
|
+
const candidates = new Map(listResidue(overview).map((item) => [item.key, item]));
|
|
207
|
+
const selection = new Set(selectedKeys);
|
|
208
|
+
const completedRegistrations = new Set();
|
|
209
|
+
for (const key of selection) {
|
|
210
|
+
const item = candidates.get(key);
|
|
211
|
+
try {
|
|
212
|
+
if (!item) reject('residue_changed');
|
|
213
|
+
if (item.kind === 'ghost-registry') {
|
|
214
|
+
if (!completedRegistrations.has(key)) {
|
|
215
|
+
const workspace = (await ctx.workspaceRegistry.list()).find((entry) => entry.id === item.workspaceId);
|
|
216
|
+
const record = workspaceTable(ctx)?.get(item.workspaceId);
|
|
217
|
+
if (!workspace || typeof workspace.detachSession !== 'function' || !Array.isArray(record?.sessionIds)) reject('workspace_unavailable');
|
|
218
|
+
if (!record.sessionIds.includes(item.id)) reject('residue_changed');
|
|
219
|
+
const visible = new Set(workspace.sessionIds ?? []);
|
|
220
|
+
const hidden = record.sessionIds.filter((id) => !visible.has(id));
|
|
221
|
+
const affected = new Set([item.id, ...hidden]);
|
|
222
|
+
const blockedIds = [...affected].filter((id) => {
|
|
223
|
+
const affectedKey = `ghost:${item.workspaceId}:${id}`;
|
|
224
|
+
return !selection.has(affectedKey) || !candidates.has(affectedKey);
|
|
225
|
+
});
|
|
226
|
+
if (blockedIds.length) throw Object.assign(cleanError('workspace_filtered'), { blockedIds });
|
|
227
|
+
for (const id of affected) {
|
|
228
|
+
if (isResidentSession(ctx, id)
|
|
229
|
+
|| (ctx.workspaceRegistry.archivedSessionIds ?? []).includes(id)
|
|
230
|
+
|| await ctx.sessionPersistence.stat(id)) reject('session_changed');
|
|
231
|
+
}
|
|
232
|
+
await workspace.detachSession(item.id);
|
|
233
|
+
const remaining = table.get(item.workspaceId)?.sessionIds;
|
|
234
|
+
if (!Array.isArray(remaining) || [...affected].some((id) => remaining.includes(id))) reject('residue_changed');
|
|
235
|
+
for (const id of affected) completedRegistrations.add(`ghost:${item.workspaceId}:${id}`);
|
|
236
|
+
}
|
|
237
|
+
} else if (item.kind === 'orphan-task') {
|
|
238
|
+
const confirmed = Object.hasOwn(confirmedTasks, item.id) ? confirmedTasks[item.id] : undefined;
|
|
239
|
+
if (!confirmed || confirmed.targetSessionId !== item.targetSessionId || confirmed.updatedAt !== item.updatedAt) reject('schedule_changed');
|
|
240
|
+
const schedule = ctx.get('schedule');
|
|
241
|
+
if (typeof schedule?.view !== 'function' || typeof schedule?.edit !== 'function') reject('reference_check_failed');
|
|
242
|
+
const task = await schedule.view({ id: item.id });
|
|
243
|
+
if (!task || task.code === 'schedule_not_found') reject('residue_changed');
|
|
244
|
+
if (task.target?.kind !== 'session' || task.target.sessionId !== item.targetSessionId
|
|
245
|
+
|| (task.updatedAt ?? null) !== item.updatedAt) reject('schedule_changed');
|
|
246
|
+
const listed = await ctx.sessionQuery.listSessions();
|
|
247
|
+
if (!Array.isArray(listed)) reject('reference_check_failed');
|
|
248
|
+
if (listed.some((entry) => (entry?.header?.id ?? entry?.id) === item.targetSessionId)
|
|
249
|
+
|| isResidentSession(ctx, item.targetSessionId)
|
|
250
|
+
|| (ctx.workspaceRegistry.archivedSessionIds ?? []).includes(item.targetSessionId)
|
|
251
|
+
|| await ctx.sessionPersistence.stat(item.targetSessionId)) reject('session_changed');
|
|
252
|
+
let result;
|
|
253
|
+
try { result = await schedule.edit({ id: item.id, action: 'delete', expectedUpdatedAt: item.updatedAt }); }
|
|
254
|
+
catch (error) { reject('schedule_delete_failed', error); }
|
|
255
|
+
if (result?.code === 'schedule_conflict') reject('schedule_changed');
|
|
256
|
+
if (!result?.deleted) reject('residue_changed');
|
|
257
|
+
} else if (item.kind === 'orphan-cache') {
|
|
258
|
+
const target = overview.cacheFiles.get(item.id);
|
|
259
|
+
const rel = target && relative(cacheRoot, resolve(target));
|
|
260
|
+
if (!rel || isAbsolute(rel) || rel === '..' || rel.startsWith(`..${sep}`)) reject('unsafe_path');
|
|
261
|
+
// The official cache owns an in-memory table as well as the file. A
|
|
262
|
+
// direct unlink leaves those two views inconsistent until restart.
|
|
263
|
+
const table = ctx.get('storageDomain')?.get('session_projcache')?.table('sessions');
|
|
264
|
+
if (!table || typeof table.delete !== 'function') reject('cache_unavailable');
|
|
265
|
+
if (!await table.delete(item.id)) reject('residue_changed');
|
|
266
|
+
} else if (item.kind === 'shell-dir' && ['empty', 'lock', 'log', 'unknown'].includes(item.shellType)) {
|
|
267
|
+
const target = key.slice('shell:'.length);
|
|
268
|
+
if (purging.has(item.id)) reject('purge_busy');
|
|
269
|
+
purging.add(item.id);
|
|
270
|
+
try {
|
|
271
|
+
if ((ctx.workspaceRegistry.archivedSessionIds ?? []).includes(item.id)) await checkCurrent(ctx, item.id);
|
|
272
|
+
// A shell whose session is still mounted in this instance is not
|
|
273
|
+
// removable without a DSH restart (no public release API).
|
|
274
|
+
if (isResidentSession(ctx, item.id)) reject('session_resident');
|
|
275
|
+
// Disposing an older, partially deleted session may flush events and
|
|
276
|
+
// recreate an event-only log before its writer closes.
|
|
277
|
+
const eventOnly = await isEventOnlyLog(ctx, item.id, target).catch(() => false);
|
|
278
|
+
const mode = eventOnly ? 'event-only' : item.shellType === 'unknown' ? 'unknown' : 'metadata';
|
|
279
|
+
let targets = await workspaceTargets(ctx, item.id);
|
|
280
|
+
const cache = ctx.get('storageDomain')?.get('session_projcache')?.table('sessions');
|
|
281
|
+
if (!cache || typeof cache.delete !== 'function') reject('cache_unavailable');
|
|
282
|
+
await removeSessionShell(target, item.id, {
|
|
283
|
+
mode,
|
|
284
|
+
recheck: async () => {
|
|
285
|
+
if (isResidentSession(ctx, item.id)
|
|
286
|
+
|| await ctx.sessionPersistence.stat(item.id)) reject('session_changed');
|
|
287
|
+
if (mode === 'event-only' && !await isEventOnlyLog(ctx, item.id, target)) reject('session_changed');
|
|
288
|
+
// A shell and its cache/registrations are one cleanup, whether
|
|
289
|
+
// it originated from an interrupted purge or outside the plugin.
|
|
290
|
+
if ((ctx.workspaceRegistry.archivedSessionIds ?? []).includes(item.id)) {
|
|
291
|
+
await checkCurrent(ctx, item.id);
|
|
292
|
+
}
|
|
293
|
+
targets = await workspaceTargets(ctx, item.id);
|
|
294
|
+
},
|
|
295
|
+
cleanup: async () => {
|
|
296
|
+
await cache.delete(item.id);
|
|
297
|
+
for (const workspace of targets) await workspace.detachSession(item.id);
|
|
298
|
+
},
|
|
299
|
+
});
|
|
300
|
+
if ((ctx.workspaceRegistry.archivedSessionIds ?? []).includes(item.id)) {
|
|
301
|
+
await unarchiveOwner.run(item.id, () => ctx.workspaceRegistry.unarchiveSession(item.id));
|
|
302
|
+
}
|
|
303
|
+
} finally { purging.delete(item.id); }
|
|
304
|
+
} else if (item.kind === 'empty-project') {
|
|
305
|
+
await removeEmptyProject(item.id, sessionsRoot());
|
|
306
|
+
} else reject('residue_unavailable');
|
|
307
|
+
done.push({ key, kind: item.kind, id: item.id });
|
|
308
|
+
} catch (error) {
|
|
309
|
+
failed.push({ key, kind: item?.kind, id: item?.id, code: error?.cleanCode || 'residue_failed',
|
|
310
|
+
...(error?.blockedIds ? { blockedCount: error.blockedIds.length } : {}),
|
|
311
|
+
...(!error?.cleanCode ? { message: String(error?.message ?? error) } : {}),
|
|
312
|
+
...(error?.cleanCode === 'schedule_delete_failed' && error.cause ? { detail: String(error.cause?.message ?? error.cause) } : {}) });
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
return { done, failed };
|
|
316
|
+
}
|
package/lib/errors.mjs
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Stable error identity; presentation and translation belong to the client. */
|
|
2
|
+
export function cleanError(code, cause) {
|
|
3
|
+
return Object.assign(new Error(`dsh-mop:${code}`, cause === undefined ? undefined : { cause }), { cleanCode: code });
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export function reject(code, cause) { throw cleanError(code, cause); }
|
package/lib/guard.mjs
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** dsh-mop · 路径防御。 */
|
|
2
|
+
|
|
3
|
+
import { basename, resolve, sep } from 'node:path';
|
|
4
|
+
import { dshHome } from './home.mjs';
|
|
5
|
+
import { reject } from './errors.mjs';
|
|
6
|
+
|
|
7
|
+
const SESSION_DIR_RE = /^session-[0-9a-zA-Z-]+$/;
|
|
8
|
+
|
|
9
|
+
/** rm 会话目录前的断言:位于 sessions 根内、目录名 === 会话 id。 */
|
|
10
|
+
export function assertSessionDirSafe(sessionDir, sessionId) {
|
|
11
|
+
const root = resolve(dshHome('sessions'));
|
|
12
|
+
const target = resolve(sessionDir);
|
|
13
|
+
if (target === root || !target.startsWith(root + sep)) {
|
|
14
|
+
reject('unsafe_path');
|
|
15
|
+
}
|
|
16
|
+
const base = basename(target);
|
|
17
|
+
if (base !== sessionId || !SESSION_DIR_RE.test(base)) {
|
|
18
|
+
reject('unsafe_path');
|
|
19
|
+
}
|
|
20
|
+
}
|
package/lib/home.mjs
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-mop · 路径
|
|
3
|
+
* 优先级与官方 dsh-home-paths 一致:$DSH_HOME → ~/.dsh。
|
|
4
|
+
*/
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
|
|
8
|
+
export function dshHome(...segments) {
|
|
9
|
+
const env = process.env.DSH_HOME;
|
|
10
|
+
const base = env && env.trim() ? env.trim() : join(homedir(), '.dsh');
|
|
11
|
+
return join(base, ...segments);
|
|
12
|
+
}
|
package/lib/routes.mjs
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-mop · connection.fetch 路由
|
|
3
|
+
*
|
|
4
|
+
* 认证与 peer 准入由载体层负责(仅 owner peer 可达精确路由)。
|
|
5
|
+
* overview / archive / purge / unarchive / residue 路由。
|
|
6
|
+
*/
|
|
7
|
+
import { buildOverview } from './store.mjs';
|
|
8
|
+
import { purgeSessions, cleanResidue, listResidue } from './clean.mjs';
|
|
9
|
+
|
|
10
|
+
const PREFIX = '/api/dsh-mop';
|
|
11
|
+
|
|
12
|
+
function json(data, status = 200) {
|
|
13
|
+
return new Response(JSON.stringify(data), {
|
|
14
|
+
status,
|
|
15
|
+
headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function readJsonBody(request) {
|
|
20
|
+
const text = await request.text();
|
|
21
|
+
if (!text.trim()) return {};
|
|
22
|
+
const data = JSON.parse(text);
|
|
23
|
+
if (typeof data !== 'object' || data === null || Array.isArray(data)) {
|
|
24
|
+
throw new Error('request body must be a JSON object');
|
|
25
|
+
}
|
|
26
|
+
return data;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function sessionIdsOf(body) {
|
|
30
|
+
return Array.isArray(body.sessionIds)
|
|
31
|
+
? body.sessionIds.filter((id) => typeof id === 'string' && id)
|
|
32
|
+
: [];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 注册全部路由(每条路由的注销由 ctx.effect 承载)。 */
|
|
36
|
+
export function registerRoutes(ctx, config) {
|
|
37
|
+
/** Route failures answer a stable code; the raw error goes to the Host log. */
|
|
38
|
+
const fail = (path, error) => {
|
|
39
|
+
ctx.logger.warn(`dsh-mop: route ${path} failed`, error);
|
|
40
|
+
return json({ error: `dsh-mop:${error?.cleanCode ?? 'internal'}` }, 500);
|
|
41
|
+
};
|
|
42
|
+
const get = (path, handler) => ctx.effect(() => ctx.connection.fetch.register({
|
|
43
|
+
path: `${PREFIX}.${path}`, methods: ['GET', 'HEAD'], requestBody: 'buffered',
|
|
44
|
+
fetch: async (request) => {
|
|
45
|
+
if (request.method === 'HEAD') return new Response(null, { status: 200 });
|
|
46
|
+
try { return await handler(request); }
|
|
47
|
+
catch (error) { return fail(path, error); }
|
|
48
|
+
},
|
|
49
|
+
}), `dsh-mop: ${PREFIX}.${path}`);
|
|
50
|
+
const post = (path, handler) => ctx.effect(() => ctx.connection.fetch.register({
|
|
51
|
+
path: `${PREFIX}.${path}`, methods: ['POST'], requestBody: 'buffered',
|
|
52
|
+
fetch: async (request) => {
|
|
53
|
+
let body;
|
|
54
|
+
try { body = await readJsonBody(request); }
|
|
55
|
+
catch { return json({ error: 'dsh-mop:bad_request' }, 400); }
|
|
56
|
+
try { return await handler(body); }
|
|
57
|
+
catch (error) { return fail(path, error); }
|
|
58
|
+
},
|
|
59
|
+
}), `dsh-mop: ${PREFIX}.${path}`);
|
|
60
|
+
|
|
61
|
+
get('overview', async () => {
|
|
62
|
+
const overview = await buildOverview(ctx, config);
|
|
63
|
+
const pick = (s) => ({
|
|
64
|
+
id: s.id, title: s.title,
|
|
65
|
+
live: s.live, blank: s.blank, updatedAt: s.updatedAt,
|
|
66
|
+
archived: s.archived, protected: s.protected, purgeBlock: s.purgeBlock, scheduleTasks: s.scheduleTasks,
|
|
67
|
+
cwd: s.cwd, workspacePath: s.workspacePath, workspaceTitle: s.workspaceTitle, workspaceCreatedAt: s.workspaceCreatedAt,
|
|
68
|
+
sizeBytes: s.sizeBytes, mtimeMs: s.mtimeMs,
|
|
69
|
+
});
|
|
70
|
+
return json({
|
|
71
|
+
apiVersion: 3,
|
|
72
|
+
sessions: overview.sessions.filter((s) => !s.archived).map(pick),
|
|
73
|
+
recycled: overview.sessions.filter((s) => s.archived).map(pick),
|
|
74
|
+
home: overview.home,
|
|
75
|
+
residue: { items: listResidue(overview) },
|
|
76
|
+
});
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
post('archive', async (body) => {
|
|
80
|
+
const ids = sessionIdsOf(body);
|
|
81
|
+
const stopActivity = body.stopActivity === true;
|
|
82
|
+
if (ids.length === 0) return json({ error: 'sessionIds[] is required' }, 400);
|
|
83
|
+
const overview = await buildOverview(ctx, config);
|
|
84
|
+
const byId = new Map(overview.sessions.map((session) => [session.id, session]));
|
|
85
|
+
const done = [];
|
|
86
|
+
const failed = [];
|
|
87
|
+
for (const id of new Set(ids)) {
|
|
88
|
+
const session = byId.get(id);
|
|
89
|
+
if (!session || session.archived || session.protected) {
|
|
90
|
+
failed.push({ id, code: !session ? 'session_not_found' : session.protected ? 'protected_workspace' : 'already_archived' });
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
try {
|
|
94
|
+
await ctx.workspaceRegistry.archiveSession(id, stopActivity ? { stopActivity: true } : {});
|
|
95
|
+
done.push(id);
|
|
96
|
+
} catch (error) {
|
|
97
|
+
if (error?.name === 'WorkspaceActiveSessionError' && Array.isArray(error.activity)) {
|
|
98
|
+
failed.push({ id, title: session.title, code: 'session_active', activity: error.activity });
|
|
99
|
+
} else {
|
|
100
|
+
failed.push({ id, ...(error?.cleanCode ? { code: error.cleanCode } : { message: String(error?.message ?? error) }) });
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return json({ done, failed });
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
post('purge', async (body) => {
|
|
108
|
+
const ids = sessionIdsOf(body);
|
|
109
|
+
if (ids.length === 0) return json({ error: 'sessionIds[] is required' }, 400);
|
|
110
|
+
const overview = await buildOverview(ctx, config);
|
|
111
|
+
return json(await purgeSessions(ctx, overview, ids));
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
post('unarchive', async (body) => {
|
|
115
|
+
const ids = sessionIdsOf(body);
|
|
116
|
+
if (ids.length === 0) return json({ error: 'sessionIds[] is required' }, 400);
|
|
117
|
+
const done = [];
|
|
118
|
+
const failed = [];
|
|
119
|
+
for (const id of ids) {
|
|
120
|
+
try {
|
|
121
|
+
await ctx.workspaceRegistry.unarchiveSession(id);
|
|
122
|
+
done.push(id);
|
|
123
|
+
} catch (error) {
|
|
124
|
+
failed.push({ id, ...(error?.cleanCode ? { code: error.cleanCode } : { message: String(error?.message ?? error) }) });
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return json({ done, failed });
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
post('task', async ({ sessionId, id }) => {
|
|
131
|
+
if (typeof sessionId !== 'string' || typeof id !== 'string' || !id) return json({ error: 'sessionId and id are required' }, 400);
|
|
132
|
+
const overview = await buildOverview(ctx, config);
|
|
133
|
+
const session = overview.sessions.find((item) => item.id === sessionId);
|
|
134
|
+
const orphan = (overview.residue.orphanTasks ?? []).some((task) => task.id === id && task.targetSessionId === sessionId);
|
|
135
|
+
if (!session?.scheduleTasks.some((task) => task.id === id) && !orphan) return json({ error: 'dsh-mop:task_not_found' }, 404);
|
|
136
|
+
const schedule = ctx.get('schedule');
|
|
137
|
+
if (!schedule || typeof schedule.view !== 'function') return json({ error: 'dsh-mop:task_unavailable' }, 503);
|
|
138
|
+
const task = await schedule.view({ id });
|
|
139
|
+
if (!task || task.code === 'schedule_not_found') return json({ error: 'dsh-mop:task_not_found' }, 404);
|
|
140
|
+
return json({ task });
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
post('residue', async (body) => {
|
|
144
|
+
const keys = Array.isArray(body.keys) ? body.keys.filter((key) => typeof key === 'string' && key) : [];
|
|
145
|
+
if (keys.length === 0) return json({ error: 'keys[] is required' }, 400);
|
|
146
|
+
const overview = await buildOverview(ctx, config);
|
|
147
|
+
const confirmedTasks = body.confirmedTasks && typeof body.confirmedTasks === 'object' && !Array.isArray(body.confirmedTasks)
|
|
148
|
+
? body.confirmedTasks : {};
|
|
149
|
+
return json(await cleanResidue(ctx, overview, keys, confirmedTasks));
|
|
150
|
+
});
|
|
151
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { lstat, readdir, rmdir, unlink } from 'node:fs/promises';
|
|
2
|
+
import { dirname, join, resolve } from 'node:path';
|
|
3
|
+
import { dshHome } from './home.mjs';
|
|
4
|
+
import { assertSessionDirSafe } from './guard.mjs';
|
|
5
|
+
import { assertCanonicalSessionPath, isSystemMetadata, removeEmptyProject } from './artifacts.mjs';
|
|
6
|
+
import { reject } from './errors.mjs';
|
|
7
|
+
|
|
8
|
+
/** Validate and remove a session directory and its recognized files. */
|
|
9
|
+
export async function removeSessionShell(sessionDir, id, { recheck, mode = 'metadata', cleanup = async () => {} }) {
|
|
10
|
+
const target = resolve(sessionDir);
|
|
11
|
+
assertSessionDirSafe(target, id);
|
|
12
|
+
await assertCanonicalSessionPath(dshHome('sessions'), target);
|
|
13
|
+
const names = await readdir(target);
|
|
14
|
+
const allowed = (name) => name === 'session.lock' || isSystemMetadata(name)
|
|
15
|
+
|| (mode === 'event-only' && ['session.v4.jsonl', 'session.v4.jsonl.zstd'].includes(name))
|
|
16
|
+
|| (mode === 'unknown' && !/^session(?:\.v\d+)?\.jsonl(?:\.zstd)?$/.test(name));
|
|
17
|
+
if (names.some((name) => !allowed(name))) reject('unknown_artifact');
|
|
18
|
+
const files = [...names.filter((name) => name !== 'session.lock'), ...names.filter((name) => name === 'session.lock')];
|
|
19
|
+
const identities = new Map();
|
|
20
|
+
for (const name of files) {
|
|
21
|
+
const file = await lstat(join(target, name), { bigint: true });
|
|
22
|
+
if (!file.isFile() || file.isSymbolicLink()) reject('unsafe_path');
|
|
23
|
+
identities.set(name, file);
|
|
24
|
+
}
|
|
25
|
+
await recheck();
|
|
26
|
+
const expected = new Set(names);
|
|
27
|
+
const verify = async () => {
|
|
28
|
+
await assertCanonicalSessionPath(dshHome('sessions'), target);
|
|
29
|
+
const entries = await readdir(target);
|
|
30
|
+
if (entries.length !== expected.size || entries.some((name) => !expected.has(name))) reject('session_changed');
|
|
31
|
+
for (const [name, previous] of identities) {
|
|
32
|
+
const file = await lstat(join(target, name), { bigint: true });
|
|
33
|
+
if (!file.isFile() || file.isSymbolicLink() || file.dev !== previous.dev || file.ino !== previous.ino
|
|
34
|
+
|| file.size !== previous.size || file.mtimeNs !== previous.mtimeNs) reject('session_changed');
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
await verify();
|
|
38
|
+
await cleanup();
|
|
39
|
+
await verify();
|
|
40
|
+
for (const name of files) await unlink(join(target, name));
|
|
41
|
+
await rmdir(target);
|
|
42
|
+
try { await removeEmptyProject(dirname(target), dshHome('sessions')); } catch (error) {
|
|
43
|
+
if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error?.code) && error?.cleanCode !== 'session_changed') throw error;
|
|
44
|
+
}
|
|
45
|
+
}
|