@dabuliu_wsy/dsh-im 0.2.0 → 0.3.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.
- package/README.md +18 -8
- package/dist/core/im.d.ts +46 -0
- package/dist/core/im.js +333 -0
- package/dist/core/index.d.ts +1 -0
- package/dist/core/index.js +1 -0
- package/dist/core/trash.d.ts +110 -0
- package/dist/core/trash.js +56 -0
- package/dist/host/agent-session.d.ts +17 -0
- package/dist/host/agent-session.js +29 -0
- package/dist/host/group-files.d.ts +26 -0
- package/dist/host/group-files.js +142 -0
- package/dist/host/im-api.d.ts +56 -0
- package/dist/host/im-api.js +81 -30
- package/dist/host/index.d.ts +5 -0
- package/dist/host/index.js +82 -10
- package/dist/host/media-type.d.ts +10 -0
- package/dist/host/media-type.js +39 -0
- package/dist/host/trash-store.d.ts +32 -0
- package/dist/host/trash-store.js +316 -0
- package/dsh-plugin.json +1 -1
- package/lib/client.inner.cjs +3905 -3318
- package/lib/client.js +3905 -3318
- package/package.json +2 -2
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 文件 → mediaType 的判定(纯函数,只在 host 侧使用)。
|
|
3
|
+
*
|
|
4
|
+
* 上传附件、群文件浏览、附件下载三处必须用同一套判定:以前这段写在 `im-api.ts` 里,
|
|
5
|
+
* 群文件接口也要用,抽出来避免两套扩展名表漂移。
|
|
6
|
+
*/
|
|
7
|
+
export const TEXT_EXTENSIONS = new Set([
|
|
8
|
+
'ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'json', 'md', 'txt', 'css', 'scss',
|
|
9
|
+
'yml', 'yaml', 'toml', 'py', 'go', 'rs', 'java', 'sh', 'ps1', 'csv', 'log', 'xml', 'html',
|
|
10
|
+
]);
|
|
11
|
+
export function mediaTypeFor(name, declared) {
|
|
12
|
+
if (declared?.trim())
|
|
13
|
+
return declared.trim();
|
|
14
|
+
const ext = name.split('.').pop()?.toLowerCase() ?? '';
|
|
15
|
+
if (ext === 'png')
|
|
16
|
+
return 'image/png';
|
|
17
|
+
if (ext === 'jpg' || ext === 'jpeg')
|
|
18
|
+
return 'image/jpeg';
|
|
19
|
+
if (ext === 'webp')
|
|
20
|
+
return 'image/webp';
|
|
21
|
+
if (ext === 'gif')
|
|
22
|
+
return 'image/gif';
|
|
23
|
+
if (ext === 'svg')
|
|
24
|
+
return 'image/svg+xml';
|
|
25
|
+
if (['md', 'txt', 'log', 'ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'css', 'scss', 'yml', 'yaml', 'toml', 'py', 'go', 'rs', 'java', 'sh', 'ps1', 'csv', 'xml', 'html'].includes(ext))
|
|
26
|
+
return 'text/plain';
|
|
27
|
+
if (ext === 'json')
|
|
28
|
+
return 'application/json';
|
|
29
|
+
return 'application/octet-stream';
|
|
30
|
+
}
|
|
31
|
+
/** 是否按文本处理(预览/内联)。mediaType 优先,扩展名兜底。 */
|
|
32
|
+
export function isTextLike(name, mediaType) {
|
|
33
|
+
if (mediaType.startsWith('text/'))
|
|
34
|
+
return true;
|
|
35
|
+
if (mediaType === 'application/json' || mediaType === 'application/xml')
|
|
36
|
+
return true;
|
|
37
|
+
const ext = name.split('.').pop()?.toLowerCase() ?? '';
|
|
38
|
+
return TEXT_EXTENSIONS.has(ext);
|
|
39
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type TrashEntryMeta, type TrashKind, type TrashPayload } from '../core/trash.ts';
|
|
2
|
+
export interface TrashAddInput {
|
|
3
|
+
kind: TrashKind;
|
|
4
|
+
label?: string;
|
|
5
|
+
detail?: string;
|
|
6
|
+
threadIds?: string[];
|
|
7
|
+
payload?: TrashPayload;
|
|
8
|
+
replaceOnRestore?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export declare function trashRoot(root: string): string;
|
|
11
|
+
export declare function assertSafeTrashId(id: string): void;
|
|
12
|
+
export declare function entryDir(root: string, id: string): string;
|
|
13
|
+
/** 列出回收站(deletedAt 倒序)。坏条目跳过并写 warn 日志——不静默,也不整页崩。 */
|
|
14
|
+
export declare function listTrash(root: string): Promise<TrashEntryMeta[]>;
|
|
15
|
+
/** 把会话数据目录移进回收站并写 manifest;任何一步失败都回滚,不留半份数据。 */
|
|
16
|
+
export declare function addTrashEntry(root: string, input: TrashAddInput): Promise<TrashEntryMeta>;
|
|
17
|
+
/**
|
|
18
|
+
* 恢复一条回收站记录:数据目录搬回原位置 + 删掉回收站条目 + 返回快照。
|
|
19
|
+
* 搬目录失败会回滚已搬的部分。
|
|
20
|
+
*/
|
|
21
|
+
export declare function restoreTrashEntry(root: string, id: string): Promise<{
|
|
22
|
+
meta: TrashEntryMeta;
|
|
23
|
+
payload: TrashPayload;
|
|
24
|
+
}>;
|
|
25
|
+
/**
|
|
26
|
+
* 彻底删除:给 id 删一条;不传 id 清空回收站。
|
|
27
|
+
* 单条删除失败会记进 failed(不吞),清空时只处理回收站目录下的合法条目。
|
|
28
|
+
*/
|
|
29
|
+
export declare function purgeTrash(root: string, id?: string): Promise<{
|
|
30
|
+
purged: number;
|
|
31
|
+
failed: string[];
|
|
32
|
+
}>;
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 回收站存储(host 侧):`<数据根>/.dsh-im/trash/`。
|
|
3
|
+
*
|
|
4
|
+
* 布局(一个回收站条目一个目录,**manifest 就是唯一真源**,不再维护 index.json):
|
|
5
|
+
* ```
|
|
6
|
+
* .dsh-im/trash/<trashId>/
|
|
7
|
+
* manifest.json { version, meta, payload, replaceOnRestore }
|
|
8
|
+
* data/<threadId>/... 被删/被清空会话的数据目录(events/facts/attachments/产物)
|
|
9
|
+
* ```
|
|
10
|
+
* 为什么不用 index:条目数很少(一个用户手动删除的量级),扫目录读 manifest 足够快,
|
|
11
|
+
* 少一个会跟目录不同步的索引文件;manifest 写入仍是原子写,读到半截 JSON 的概率可忽略,
|
|
12
|
+
* 万一真的坏了就 **跳过并记日志**(不把整页回收站弄崩,但也不静默当它不存在)。
|
|
13
|
+
*
|
|
14
|
+
* 恢复是「先搬目录、再删条目」;搬一半失败会把已搬的移回去(不留下半恢复状态)。
|
|
15
|
+
* 清空聊天记录用 `replaceOnRestore=true`:清空后 saveState 会重建一个空目录,恢复时要覆盖它。
|
|
16
|
+
*/
|
|
17
|
+
import { randomUUID } from 'node:crypto';
|
|
18
|
+
import { mkdir, readdir, readFile, rename, rm, stat } from 'node:fs/promises';
|
|
19
|
+
import { join } from 'node:path';
|
|
20
|
+
import { assertSafeThreadId } from '../core/workspace.js';
|
|
21
|
+
import { TRASH_KINDS } from '../core/trash.js';
|
|
22
|
+
import { logWarn } from '../core/log.js';
|
|
23
|
+
import { groupDir } from './event-store.js';
|
|
24
|
+
import { writeFileAtomic } from './fs-atomic.js';
|
|
25
|
+
const TRASH_ID_PATTERN = /^tr_[0-9a-z]{6,40}$/;
|
|
26
|
+
const MAX_LABEL = 120;
|
|
27
|
+
const MAX_DETAIL = 240;
|
|
28
|
+
function error400(message) {
|
|
29
|
+
return Object.assign(new Error(message), { status: 400 });
|
|
30
|
+
}
|
|
31
|
+
function error404(message) {
|
|
32
|
+
return Object.assign(new Error(message), { status: 404 });
|
|
33
|
+
}
|
|
34
|
+
function error409(message) {
|
|
35
|
+
return Object.assign(new Error(message), { status: 409 });
|
|
36
|
+
}
|
|
37
|
+
/** 同一个数据根的回收站操作串行:并发删除/恢复不会互相搬同一个目录。 */
|
|
38
|
+
const chains = new Map();
|
|
39
|
+
function queueKey(root) {
|
|
40
|
+
const normalized = root.replaceAll('\\', '/').replace(/\/+$/, '');
|
|
41
|
+
return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
|
|
42
|
+
}
|
|
43
|
+
function serialized(root, run) {
|
|
44
|
+
const key = queueKey(root);
|
|
45
|
+
const previous = chains.get(key) ?? Promise.resolve();
|
|
46
|
+
const next = previous.then(run, run);
|
|
47
|
+
chains.set(key, next.then(() => undefined, () => undefined));
|
|
48
|
+
return next;
|
|
49
|
+
}
|
|
50
|
+
export function trashRoot(root) {
|
|
51
|
+
return join(root, '.dsh-im', 'trash');
|
|
52
|
+
}
|
|
53
|
+
export function assertSafeTrashId(id) {
|
|
54
|
+
if (!TRASH_ID_PATTERN.test(id))
|
|
55
|
+
throw error400('denied: invalid trash id');
|
|
56
|
+
}
|
|
57
|
+
export function entryDir(root, id) {
|
|
58
|
+
assertSafeTrashId(id);
|
|
59
|
+
return join(trashRoot(root), id);
|
|
60
|
+
}
|
|
61
|
+
function manifestPath(root, id) {
|
|
62
|
+
return join(entryDir(root, id), 'manifest.json');
|
|
63
|
+
}
|
|
64
|
+
async function exists(path) {
|
|
65
|
+
try {
|
|
66
|
+
await stat(path);
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
if (error.code === 'ENOENT')
|
|
71
|
+
return false;
|
|
72
|
+
throw error;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
async function sumDirSize(dir) {
|
|
76
|
+
let total = 0;
|
|
77
|
+
let entries;
|
|
78
|
+
try {
|
|
79
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
if (error.code === 'ENOENT')
|
|
83
|
+
return 0;
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
for (const entry of entries) {
|
|
87
|
+
const full = join(dir, entry.name);
|
|
88
|
+
if (entry.isDirectory()) {
|
|
89
|
+
total += await sumDirSize(full);
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
total += (await stat(full)).size;
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
// 单个文件 stat 失败不影响整体报告(bytes 是展示用,不是安全边界)。
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return total;
|
|
100
|
+
}
|
|
101
|
+
function clip(text, limit) {
|
|
102
|
+
const value = (text ?? '').trim();
|
|
103
|
+
return value.length > limit ? `${value.slice(0, limit)}…` : value;
|
|
104
|
+
}
|
|
105
|
+
function isRecord(value) {
|
|
106
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
107
|
+
}
|
|
108
|
+
async function readManifest(root, id) {
|
|
109
|
+
let raw;
|
|
110
|
+
try {
|
|
111
|
+
raw = await readFile(manifestPath(root, id), 'utf8');
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
if (error.code === 'ENOENT')
|
|
115
|
+
throw error404('回收站里没有这条记录(可能已被彻底删除或已恢复)');
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
118
|
+
let parsed;
|
|
119
|
+
try {
|
|
120
|
+
parsed = JSON.parse(raw);
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
throw Object.assign(new Error('回收站记录损坏(manifest.json 不是合法 JSON)'), { status: 500 });
|
|
124
|
+
}
|
|
125
|
+
if (!isRecord(parsed) || !isRecord(parsed.meta) || typeof parsed.meta.id !== 'string') {
|
|
126
|
+
throw Object.assign(new Error('回收站记录损坏(缺少 meta 字段)'), { status: 500 });
|
|
127
|
+
}
|
|
128
|
+
const meta = parsed.meta;
|
|
129
|
+
return {
|
|
130
|
+
version: 1,
|
|
131
|
+
meta,
|
|
132
|
+
payload: isRecord(parsed.payload) ? parsed.payload : {},
|
|
133
|
+
replaceOnRestore: parsed.replaceOnRestore === true,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
function validateInput(input) {
|
|
137
|
+
const kind = input.kind;
|
|
138
|
+
if (!TRASH_KINDS.includes(kind))
|
|
139
|
+
throw error400(`未知的回收站类型:${String(kind)}`);
|
|
140
|
+
const threadIds = [...new Set(input.threadIds ?? [])];
|
|
141
|
+
for (const threadId of threadIds)
|
|
142
|
+
assertSafeThreadId(threadId);
|
|
143
|
+
const payload = isRecord(input.payload) ? input.payload : {};
|
|
144
|
+
if (kind === 'persona') {
|
|
145
|
+
if (!isRecord(payload.persona) || typeof payload.persona.id !== 'string') {
|
|
146
|
+
throw error400('删除角色的回收站记录必须带 persona 快照');
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
else if (!isRecord(payload.thread) || typeof payload.thread.id !== 'string') {
|
|
150
|
+
throw error400('删除会话/清空记录的回收站记录必须带 thread 快照');
|
|
151
|
+
}
|
|
152
|
+
const fallbackLabel = kind === 'persona'
|
|
153
|
+
? String(payload.persona.name ?? '角色')
|
|
154
|
+
: String(payload.thread.title ?? '会话');
|
|
155
|
+
return {
|
|
156
|
+
kind,
|
|
157
|
+
threadIds,
|
|
158
|
+
payload,
|
|
159
|
+
label: clip(input.label ?? fallbackLabel, MAX_LABEL) || fallbackLabel,
|
|
160
|
+
detail: clip(input.detail, MAX_DETAIL),
|
|
161
|
+
replaceOnRestore: input.replaceOnRestore === true,
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
/** 列出回收站(deletedAt 倒序)。坏条目跳过并写 warn 日志——不静默,也不整页崩。 */
|
|
165
|
+
export async function listTrash(root) {
|
|
166
|
+
let names;
|
|
167
|
+
try {
|
|
168
|
+
names = (await readdir(trashRoot(root), { withFileTypes: true }))
|
|
169
|
+
.filter((entry) => entry.isDirectory() && TRASH_ID_PATTERN.test(entry.name))
|
|
170
|
+
.map((entry) => entry.name);
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
if (error.code === 'ENOENT')
|
|
174
|
+
return [];
|
|
175
|
+
throw error;
|
|
176
|
+
}
|
|
177
|
+
const entries = [];
|
|
178
|
+
for (const id of names) {
|
|
179
|
+
try {
|
|
180
|
+
const manifest = await readManifest(root, id);
|
|
181
|
+
entries.push(manifest.meta);
|
|
182
|
+
}
|
|
183
|
+
catch (error) {
|
|
184
|
+
logWarn('[dsh-im] 回收站条目读取失败,已跳过', { id, reason: error instanceof Error ? error.message : String(error) });
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return entries.sort((left, right) => right.deletedAt - left.deletedAt);
|
|
188
|
+
}
|
|
189
|
+
/** 把会话数据目录移进回收站并写 manifest;任何一步失败都回滚,不留半份数据。 */
|
|
190
|
+
export function addTrashEntry(root, input) {
|
|
191
|
+
return serialized(root, async () => {
|
|
192
|
+
const { kind, threadIds, payload, label, detail, replaceOnRestore } = validateInput(input);
|
|
193
|
+
const id = `tr_${randomUUID().replaceAll('-', '').slice(0, 12)}`;
|
|
194
|
+
const dir = entryDir(root, id);
|
|
195
|
+
const dataDir = join(dir, 'data');
|
|
196
|
+
await mkdir(dataDir, { recursive: true });
|
|
197
|
+
const moved = [];
|
|
198
|
+
try {
|
|
199
|
+
for (const threadId of threadIds) {
|
|
200
|
+
const from = groupDir(root, threadId);
|
|
201
|
+
if (!(await exists(from)))
|
|
202
|
+
continue;
|
|
203
|
+
const to = join(dataDir, threadId);
|
|
204
|
+
await rename(from, to);
|
|
205
|
+
moved.push({ from, to });
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
catch (error) {
|
|
209
|
+
// 回滚已经搬走的目录,再把空条目删掉。
|
|
210
|
+
for (const item of moved.reverse()) {
|
|
211
|
+
await rename(item.to, item.from).catch(() => undefined);
|
|
212
|
+
}
|
|
213
|
+
await rm(dir, { recursive: true, force: true }).catch(() => undefined);
|
|
214
|
+
throw Object.assign(new Error(`移入回收站失败:${error instanceof Error ? error.message : String(error)}`), { status: 500 });
|
|
215
|
+
}
|
|
216
|
+
const meta = {
|
|
217
|
+
id,
|
|
218
|
+
kind,
|
|
219
|
+
label,
|
|
220
|
+
detail,
|
|
221
|
+
deletedAt: Date.now(),
|
|
222
|
+
threadIds,
|
|
223
|
+
bytes: await sumDirSize(dataDir),
|
|
224
|
+
restorable: true,
|
|
225
|
+
};
|
|
226
|
+
const manifest = { version: 1, meta, payload, replaceOnRestore };
|
|
227
|
+
try {
|
|
228
|
+
await writeFileAtomic(manifestPath(root, id), JSON.stringify(manifest, null, 2));
|
|
229
|
+
}
|
|
230
|
+
catch (error) {
|
|
231
|
+
for (const item of moved.reverse()) {
|
|
232
|
+
await rename(item.to, item.from).catch(() => undefined);
|
|
233
|
+
}
|
|
234
|
+
await rm(dir, { recursive: true, force: true }).catch(() => undefined);
|
|
235
|
+
throw error;
|
|
236
|
+
}
|
|
237
|
+
return meta;
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* 恢复一条回收站记录:数据目录搬回原位置 + 删掉回收站条目 + 返回快照。
|
|
242
|
+
* 搬目录失败会回滚已搬的部分。
|
|
243
|
+
*/
|
|
244
|
+
export function restoreTrashEntry(root, id) {
|
|
245
|
+
return serialized(root, async () => {
|
|
246
|
+
assertSafeTrashId(id);
|
|
247
|
+
const manifest = await readManifest(root, id);
|
|
248
|
+
const dataDir = join(entryDir(root, id), 'data');
|
|
249
|
+
const moved = [];
|
|
250
|
+
try {
|
|
251
|
+
for (const threadId of manifest.meta.threadIds) {
|
|
252
|
+
const from = join(dataDir, threadId);
|
|
253
|
+
if (!(await exists(from)))
|
|
254
|
+
continue;
|
|
255
|
+
const to = groupDir(root, threadId);
|
|
256
|
+
if (await exists(to)) {
|
|
257
|
+
if (!manifest.replaceOnRestore) {
|
|
258
|
+
throw error409(`会话数据目录已经存在,不能直接恢复:${threadId}(可先删除这个会话再恢复)`);
|
|
259
|
+
}
|
|
260
|
+
await rm(to, { recursive: true, force: true });
|
|
261
|
+
}
|
|
262
|
+
await rename(from, to);
|
|
263
|
+
moved.push({ from, to });
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
catch (error) {
|
|
267
|
+
for (const item of moved.reverse()) {
|
|
268
|
+
await rename(item.to, item.from).catch(() => undefined);
|
|
269
|
+
}
|
|
270
|
+
throw error;
|
|
271
|
+
}
|
|
272
|
+
await rm(entryDir(root, id), { recursive: true, force: true }).catch((error) => {
|
|
273
|
+
logWarn('[dsh-im] 恢复后清理回收站条目失败(数据已恢复)', {
|
|
274
|
+
id,
|
|
275
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
276
|
+
});
|
|
277
|
+
});
|
|
278
|
+
return { meta: manifest.meta, payload: manifest.payload };
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* 彻底删除:给 id 删一条;不传 id 清空回收站。
|
|
283
|
+
* 单条删除失败会记进 failed(不吞),清空时只处理回收站目录下的合法条目。
|
|
284
|
+
*/
|
|
285
|
+
export function purgeTrash(root, id) {
|
|
286
|
+
return serialized(root, async () => {
|
|
287
|
+
if (id) {
|
|
288
|
+
assertSafeTrashId(id);
|
|
289
|
+
await rm(entryDir(root, id), { recursive: true, force: true });
|
|
290
|
+
return { purged: 1, failed: [] };
|
|
291
|
+
}
|
|
292
|
+
let names;
|
|
293
|
+
try {
|
|
294
|
+
names = (await readdir(trashRoot(root), { withFileTypes: true }))
|
|
295
|
+
.filter((entry) => entry.isDirectory() && TRASH_ID_PATTERN.test(entry.name))
|
|
296
|
+
.map((entry) => entry.name);
|
|
297
|
+
}
|
|
298
|
+
catch (error) {
|
|
299
|
+
if (error.code === 'ENOENT')
|
|
300
|
+
return { purged: 0, failed: [] };
|
|
301
|
+
throw error;
|
|
302
|
+
}
|
|
303
|
+
let purged = 0;
|
|
304
|
+
const failed = [];
|
|
305
|
+
for (const name of names) {
|
|
306
|
+
try {
|
|
307
|
+
await rm(join(trashRoot(root), name), { recursive: true, force: true });
|
|
308
|
+
purged += 1;
|
|
309
|
+
}
|
|
310
|
+
catch {
|
|
311
|
+
failed.push(name);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return { purged, failed };
|
|
315
|
+
});
|
|
316
|
+
}
|