@dabuliu_wsy/dsh-im 0.2.0 → 0.3.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/README.md +15 -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.js +59 -3
- 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
|
@@ -135,6 +135,14 @@ export interface NativeBridge {
|
|
|
135
135
|
toolStats?: NativeToolStats;
|
|
136
136
|
}>;
|
|
137
137
|
debug?(): NativeDebugInfo;
|
|
138
|
+
/**
|
|
139
|
+
* 删除会话 / 删除角色 / 清空聊天记录后,释放匹配的原生会话。
|
|
140
|
+
* 不释放的话,被删掉的历史还留在宿主的 agent 会话内存里,模型仍可能"记得"。
|
|
141
|
+
*/
|
|
142
|
+
forget?(filter: {
|
|
143
|
+
personaId?: string;
|
|
144
|
+
threadId?: string;
|
|
145
|
+
}): Promise<number>;
|
|
138
146
|
}
|
|
139
147
|
export interface NativeAgentSessionsOptions {
|
|
140
148
|
agents: () => NativeAgentsApi | undefined;
|
|
@@ -234,6 +242,15 @@ export declare class NativeAgentSessions {
|
|
|
234
242
|
private refreshFacts;
|
|
235
243
|
/** 释放空闲超时的原生会话(惰性清扫,避免定时器常驻)。 */
|
|
236
244
|
sweep(): void;
|
|
245
|
+
/**
|
|
246
|
+
* 按「角色 × 群」释放匹配的原生会话(sessionKey = `personaId:threadId`)。
|
|
247
|
+
* 删除会话 / 删除角色 / 清空聊天记录后调用:被删的历史不能继续留在宿主内存里。
|
|
248
|
+
* 返回释放条数;没匹配到就是 0(不假装做了事)。
|
|
249
|
+
*/
|
|
250
|
+
forget(filter: {
|
|
251
|
+
personaId?: string;
|
|
252
|
+
threadId?: string;
|
|
253
|
+
}): Promise<number>;
|
|
237
254
|
complete(input: NativeBridgeInput): Promise<{
|
|
238
255
|
text: string;
|
|
239
256
|
trace?: TurnStepTrace[];
|
|
@@ -367,6 +367,34 @@ export class NativeAgentSessions {
|
|
|
367
367
|
});
|
|
368
368
|
}
|
|
369
369
|
}
|
|
370
|
+
/**
|
|
371
|
+
* 按「角色 × 群」释放匹配的原生会话(sessionKey = `personaId:threadId`)。
|
|
372
|
+
* 删除会话 / 删除角色 / 清空聊天记录后调用:被删的历史不能继续留在宿主内存里。
|
|
373
|
+
* 返回释放条数;没匹配到就是 0(不假装做了事)。
|
|
374
|
+
*/
|
|
375
|
+
async forget(filter) {
|
|
376
|
+
const personaId = filter.personaId?.trim();
|
|
377
|
+
const threadId = filter.threadId?.trim();
|
|
378
|
+
if (!personaId && !threadId)
|
|
379
|
+
return 0;
|
|
380
|
+
const matches = [];
|
|
381
|
+
for (const [key, entry] of this.sessions) {
|
|
382
|
+
const sep = key.indexOf(':');
|
|
383
|
+
const keyPersona = sep >= 0 ? key.slice(0, sep) : key;
|
|
384
|
+
const keyThread = sep >= 0 ? key.slice(sep + 1) : '';
|
|
385
|
+
if (personaId && keyPersona !== personaId)
|
|
386
|
+
continue;
|
|
387
|
+
if (threadId && keyThread !== threadId)
|
|
388
|
+
continue;
|
|
389
|
+
matches.push({ key, entry });
|
|
390
|
+
}
|
|
391
|
+
for (const item of matches) {
|
|
392
|
+
this.sessions.delete(item.key);
|
|
393
|
+
await this.hideFromSidebar(item.entry.sessionId);
|
|
394
|
+
await item.entry.handle.dispose().catch(() => undefined);
|
|
395
|
+
}
|
|
396
|
+
return matches.length;
|
|
397
|
+
}
|
|
370
398
|
async complete(input) {
|
|
371
399
|
const turnStartedAt = this.now();
|
|
372
400
|
const agents = this.options.agents();
|
|
@@ -929,6 +957,7 @@ export function createNativeRuntime(options) {
|
|
|
929
957
|
status: () => sessions.status(),
|
|
930
958
|
complete: (input) => sessions.complete(input),
|
|
931
959
|
debug: () => sessions.debug(),
|
|
960
|
+
forget: (filter) => sessions.forget(filter),
|
|
932
961
|
},
|
|
933
962
|
disposeAll: () => sessions.disposeAll(),
|
|
934
963
|
};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export interface GroupFileEntry {
|
|
2
|
+
name: string;
|
|
3
|
+
/** 相对群工作区的路径('/'-分隔)。 */
|
|
4
|
+
path: string;
|
|
5
|
+
kind: 'file' | 'dir';
|
|
6
|
+
bytes?: number;
|
|
7
|
+
modifiedAt?: number;
|
|
8
|
+
mediaType?: string;
|
|
9
|
+
}
|
|
10
|
+
export interface GroupFileListing {
|
|
11
|
+
path: string;
|
|
12
|
+
parent: string;
|
|
13
|
+
entries: GroupFileEntry[];
|
|
14
|
+
/** 群目录不存在时 exists=false(面板显示空态,不报错)。 */
|
|
15
|
+
exists: boolean;
|
|
16
|
+
/** 目录条目超过上限时截断的提示。 */
|
|
17
|
+
truncated?: boolean;
|
|
18
|
+
}
|
|
19
|
+
/** 列目录(dirs 在前、同类按名称排)。 */
|
|
20
|
+
export declare function listGroupFiles(root: string, threadId: string, rawPath?: string): Promise<GroupFileListing>;
|
|
21
|
+
/** 读一个群文件(只读、围栏同上)。 */
|
|
22
|
+
export declare function readGroupFile(root: string, threadId: string, rawPath: string): Promise<{
|
|
23
|
+
bytes: Buffer;
|
|
24
|
+
mediaType: string;
|
|
25
|
+
name: string;
|
|
26
|
+
}>;
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 群工作区文件浏览(面板右栏「文件」Tab / 会话文件弹窗)。
|
|
3
|
+
*
|
|
4
|
+
* 群工作区 = `<数据根>/.dsh-im/groups/<threadId>/`(群数据与群产物同目录,
|
|
5
|
+
* 不另建"产物区")。角色 `write_file`、`先汇总`、用户附件、`run_check` 日志都落在里面。
|
|
6
|
+
*
|
|
7
|
+
* 这里只做**只读**:
|
|
8
|
+
* - 路径围栏:只允许 threadId 目录内的相对路径,拒绝绝对路径 / `..` / 隐藏文件(`.cache` 等);
|
|
9
|
+
* - 内部账本(events/facts/metrics/receipts/sync/lease/index/watch)不是"群文件",不展示、也不允许读;
|
|
10
|
+
* - 单文件读取上限 50MB(面板预览另有文本截断),列表最多 500 条(超出直接截断并在 where 里说明)。
|
|
11
|
+
*/
|
|
12
|
+
import { readdir, readFile, stat } from 'node:fs/promises';
|
|
13
|
+
import { resolve, sep } from 'node:path';
|
|
14
|
+
import { assertSafeThreadId } from '../core/workspace.js';
|
|
15
|
+
import { groupDir } from './event-store.js';
|
|
16
|
+
import { mediaTypeFor } from './media-type.js';
|
|
17
|
+
/** 群目录里的内部账本文件(仅顶层):面板不展示,读接口也拒绝。 */
|
|
18
|
+
const INTERNAL_FILES = new Set([
|
|
19
|
+
'events.jsonl',
|
|
20
|
+
'facts.json',
|
|
21
|
+
'metrics.jsonl',
|
|
22
|
+
'receipts.jsonl',
|
|
23
|
+
'sync.json',
|
|
24
|
+
'lease.json',
|
|
25
|
+
'index.json',
|
|
26
|
+
'watch.json',
|
|
27
|
+
]);
|
|
28
|
+
const MAX_ENTRIES = 500;
|
|
29
|
+
const MAX_READ_BYTES = 50 * 1024 * 1024;
|
|
30
|
+
function badRequest(message) {
|
|
31
|
+
return Object.assign(new Error(message), { status: 400 });
|
|
32
|
+
}
|
|
33
|
+
/** 归一化并校验相对路径:返回以 '/' 分段的数组;空 = 群目录根。 */
|
|
34
|
+
function safeSegments(input) {
|
|
35
|
+
const raw = (input ?? '').replaceAll('\\', '/').trim();
|
|
36
|
+
if (!raw || raw === '.')
|
|
37
|
+
return [];
|
|
38
|
+
if (raw.startsWith('/') || /^[A-Za-z]:/.test(raw))
|
|
39
|
+
throw badRequest('path 必须是群工作区内的相对路径');
|
|
40
|
+
const segments = raw.split('/').filter((part) => part && part !== '.');
|
|
41
|
+
if (segments.length === 0)
|
|
42
|
+
return [];
|
|
43
|
+
for (const part of segments) {
|
|
44
|
+
if (part === '..')
|
|
45
|
+
throw badRequest('path 不能包含 ..');
|
|
46
|
+
if (part.startsWith('.'))
|
|
47
|
+
throw badRequest('不能访问隐藏文件/目录');
|
|
48
|
+
}
|
|
49
|
+
if (segments.length === 1 && INTERNAL_FILES.has(segments[0])) {
|
|
50
|
+
throw badRequest('这是插件内部账本文件,不作为群文件展示');
|
|
51
|
+
}
|
|
52
|
+
return segments;
|
|
53
|
+
}
|
|
54
|
+
function resolveInside(base, segments) {
|
|
55
|
+
const dir = resolve(base, ...segments);
|
|
56
|
+
const root = resolve(base);
|
|
57
|
+
if (dir !== root && !dir.startsWith(`${root}${sep}`))
|
|
58
|
+
throw badRequest('path 越出群工作区');
|
|
59
|
+
return dir;
|
|
60
|
+
}
|
|
61
|
+
/** 列目录(dirs 在前、同类按名称排)。 */
|
|
62
|
+
export async function listGroupFiles(root, threadId, rawPath = '') {
|
|
63
|
+
assertSafeThreadId(threadId);
|
|
64
|
+
const segments = safeSegments(rawPath);
|
|
65
|
+
const base = groupDir(root, threadId);
|
|
66
|
+
const dir = resolveInside(base, segments);
|
|
67
|
+
const rel = segments.join('/');
|
|
68
|
+
const parent = segments.length <= 1 ? '' : segments.slice(0, -1).join('/');
|
|
69
|
+
let dirents;
|
|
70
|
+
try {
|
|
71
|
+
dirents = await readdir(dir, { withFileTypes: true });
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
if (error.code === 'ENOENT') {
|
|
75
|
+
return { path: rel, parent, entries: [], exists: false };
|
|
76
|
+
}
|
|
77
|
+
throw error;
|
|
78
|
+
}
|
|
79
|
+
const entries = [];
|
|
80
|
+
for (const dirent of dirents) {
|
|
81
|
+
if (dirent.name.startsWith('.'))
|
|
82
|
+
continue;
|
|
83
|
+
if (segments.length === 0 && INTERNAL_FILES.has(dirent.name))
|
|
84
|
+
continue;
|
|
85
|
+
const childPath = segments.length ? `${rel}/${dirent.name}` : dirent.name;
|
|
86
|
+
let info;
|
|
87
|
+
try {
|
|
88
|
+
info = await stat(resolve(dir, dirent.name));
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
// 读目录时文件刚好被删/无权限:跳过这一条,不炸整个列表。
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
if (dirent.isDirectory()) {
|
|
95
|
+
entries.push({ name: dirent.name, path: childPath, kind: 'dir', modifiedAt: info.mtimeMs });
|
|
96
|
+
}
|
|
97
|
+
else if (dirent.isFile()) {
|
|
98
|
+
entries.push({
|
|
99
|
+
name: dirent.name,
|
|
100
|
+
path: childPath,
|
|
101
|
+
kind: 'file',
|
|
102
|
+
bytes: info.size,
|
|
103
|
+
modifiedAt: info.mtimeMs,
|
|
104
|
+
mediaType: mediaTypeFor(dirent.name),
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
if (entries.length >= MAX_ENTRIES)
|
|
108
|
+
return { path: rel, parent, entries, exists: true, truncated: true };
|
|
109
|
+
}
|
|
110
|
+
entries.sort((left, right) => {
|
|
111
|
+
if (left.kind !== right.kind)
|
|
112
|
+
return left.kind === 'dir' ? -1 : 1;
|
|
113
|
+
return left.name.localeCompare(right.name, 'zh-Hans-CN', { numeric: true });
|
|
114
|
+
});
|
|
115
|
+
return { path: rel, parent, entries, exists: true };
|
|
116
|
+
}
|
|
117
|
+
/** 读一个群文件(只读、围栏同上)。 */
|
|
118
|
+
export async function readGroupFile(root, threadId, rawPath) {
|
|
119
|
+
assertSafeThreadId(threadId);
|
|
120
|
+
const segments = safeSegments(rawPath);
|
|
121
|
+
if (segments.length === 0)
|
|
122
|
+
throw badRequest('path 必填(要读的文件路径)');
|
|
123
|
+
const base = groupDir(root, threadId);
|
|
124
|
+
const file = resolveInside(base, segments);
|
|
125
|
+
let info;
|
|
126
|
+
try {
|
|
127
|
+
info = await stat(file);
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
if (error.code === 'ENOENT') {
|
|
131
|
+
throw Object.assign(new Error('文件不存在(可能已被删除或改名)'), { status: 404 });
|
|
132
|
+
}
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
if (!info.isFile())
|
|
136
|
+
throw badRequest('path 不是文件');
|
|
137
|
+
if (info.size > MAX_READ_BYTES) {
|
|
138
|
+
throw Object.assign(new Error(`文件太大(${Math.round(info.size / 1024 / 1024)}MB,上限 ${MAX_READ_BYTES / 1024 / 1024}MB)`), { status: 413 });
|
|
139
|
+
}
|
|
140
|
+
const name = segments[segments.length - 1];
|
|
141
|
+
return { bytes: await readFile(file), mediaType: mediaTypeFor(name), name };
|
|
142
|
+
}
|
package/dist/host/im-api.d.ts
CHANGED
|
@@ -5,6 +5,8 @@ import { type NativeBridge } from './agent-session.ts';
|
|
|
5
5
|
import { type HostCapabilityReport } from './capabilities.ts';
|
|
6
6
|
import type { MemoryContextReceipt } from '../core/memory-context.ts';
|
|
7
7
|
import { type BudgetChangedEvent, type ContextBudgetReceipt } from '../core/context-budget.ts';
|
|
8
|
+
import { type GroupFileListing } from './group-files.ts';
|
|
9
|
+
import type { TrashEntryMeta, TrashPayload } from '../core/trash.ts';
|
|
8
10
|
/** DSH 附件存储(ctx.attachments)的最小接口面:我们只用「存文件/存图片」两种。 */
|
|
9
11
|
export interface DshAttachmentStore {
|
|
10
12
|
saveFile?: (input: {
|
|
@@ -66,6 +68,60 @@ export declare function createImApi(deps: ImApiDeps): {
|
|
|
66
68
|
warnings?: undefined;
|
|
67
69
|
path: string;
|
|
68
70
|
}>;
|
|
71
|
+
trashList(projectRoot?: string): Promise<{
|
|
72
|
+
entries: TrashEntryMeta[];
|
|
73
|
+
}>;
|
|
74
|
+
trashAdd(body: {
|
|
75
|
+
projectRoot?: string;
|
|
76
|
+
kind?: string;
|
|
77
|
+
label?: string;
|
|
78
|
+
detail?: string;
|
|
79
|
+
threadIds?: unknown;
|
|
80
|
+
payload?: unknown;
|
|
81
|
+
replaceOnRestore?: boolean;
|
|
82
|
+
}): Promise<{
|
|
83
|
+
entry: TrashEntryMeta;
|
|
84
|
+
}>;
|
|
85
|
+
trashRestore(body: {
|
|
86
|
+
projectRoot?: string;
|
|
87
|
+
id?: unknown;
|
|
88
|
+
}): Promise<{
|
|
89
|
+
meta: TrashEntryMeta;
|
|
90
|
+
payload: TrashPayload;
|
|
91
|
+
}>;
|
|
92
|
+
trashPurge(body: {
|
|
93
|
+
projectRoot?: string;
|
|
94
|
+
id?: unknown;
|
|
95
|
+
}): Promise<{
|
|
96
|
+
purged: number;
|
|
97
|
+
failed: string[];
|
|
98
|
+
}>;
|
|
99
|
+
/** 删除会话/角色、清空记录后释放对应原生会话(被删历史不能继续留在宿主内存)。 */
|
|
100
|
+
nativeForget(body: {
|
|
101
|
+
personaId?: unknown;
|
|
102
|
+
threadId?: unknown;
|
|
103
|
+
}): Promise<{
|
|
104
|
+
disposed: number;
|
|
105
|
+
}>;
|
|
106
|
+
/**
|
|
107
|
+
* 群工作区文件浏览(只读):路径围栏在 `<根>/.dsh-im/groups/<threadId>/` 内,
|
|
108
|
+
* 内部账本(events/facts/metrics/receipts/...)不展示也不允许读。
|
|
109
|
+
*/
|
|
110
|
+
groupFiles(body: {
|
|
111
|
+
threadId?: unknown;
|
|
112
|
+
projectRoot?: string;
|
|
113
|
+
path?: unknown;
|
|
114
|
+
}): Promise<GroupFileListing>;
|
|
115
|
+
/** 读一个群文件(原始字节;面板用 <img>/fetch 展示或下载)。 */
|
|
116
|
+
groupFile(body: {
|
|
117
|
+
threadId?: unknown;
|
|
118
|
+
projectRoot?: string;
|
|
119
|
+
path?: unknown;
|
|
120
|
+
}): Promise<{
|
|
121
|
+
bytes: Buffer;
|
|
122
|
+
mediaType: string;
|
|
123
|
+
name: string;
|
|
124
|
+
}>;
|
|
69
125
|
/**
|
|
70
126
|
* 数据根发现(只读):当前根 + DSH 注册工作区 + 以前用过的根,各自有没有数据。
|
|
71
127
|
* 面板加载失败时用它列出「哪个根里还有数据」,而不是静默显示空。
|
package/dist/host/im-api.js
CHANGED
|
@@ -23,13 +23,12 @@ import { buildSample } from '../core/calibration-samples.js';
|
|
|
23
23
|
import { buildCalibrationReport } from '../core/calibrator.js';
|
|
24
24
|
import { planBudget } from '../core/budget-plan.js';
|
|
25
25
|
import { buildMemoryIndex } from './memory-index.js';
|
|
26
|
+
import { addTrashEntry, listTrash, purgeTrash, restoreTrashEntry } from './trash-store.js';
|
|
27
|
+
import { listGroupFiles, readGroupFile } from './group-files.js';
|
|
28
|
+
import { mediaTypeFor, isTextLike } from './media-type.js';
|
|
26
29
|
const MAX_IMAGE_BYTES = 8 * 1024 * 1024;
|
|
27
30
|
const MAX_FILE_BYTES = 20 * 1024 * 1024;
|
|
28
31
|
const MAX_INLINE_TEXT = 20_000;
|
|
29
|
-
const TEXT_EXTENSIONS = new Set([
|
|
30
|
-
'ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'json', 'md', 'txt', 'css', 'scss',
|
|
31
|
-
'yml', 'yaml', 'toml', 'py', 'go', 'rs', 'java', 'sh', 'ps1', 'csv', 'log', 'xml', 'html',
|
|
32
|
-
]);
|
|
33
32
|
function safeAttachmentName(name) {
|
|
34
33
|
const base = name.replace(/[^\w.\-\u4e00-\u9fa5]/g, '_').replace(/^\.+/, '');
|
|
35
34
|
if (!base)
|
|
@@ -55,32 +54,6 @@ function inlineTextPreview(data) {
|
|
|
55
54
|
const cleaned = truncated ? text.replace(/\uFFFD+$/, '') : text;
|
|
56
55
|
return Array.from(cleaned).slice(0, MAX_INLINE_TEXT).join('');
|
|
57
56
|
}
|
|
58
|
-
function mediaTypeFor(name, declared) {
|
|
59
|
-
if (declared?.trim())
|
|
60
|
-
return declared.trim();
|
|
61
|
-
const ext = name.split('.').pop()?.toLowerCase() ?? '';
|
|
62
|
-
if (['png'].includes(ext))
|
|
63
|
-
return 'image/png';
|
|
64
|
-
if (['jpg', 'jpeg'].includes(ext))
|
|
65
|
-
return 'image/jpeg';
|
|
66
|
-
if (ext === 'webp')
|
|
67
|
-
return 'image/webp';
|
|
68
|
-
if (ext === 'gif')
|
|
69
|
-
return 'image/gif';
|
|
70
|
-
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))
|
|
71
|
-
return 'text/plain';
|
|
72
|
-
if (ext === 'json')
|
|
73
|
-
return 'application/json';
|
|
74
|
-
return 'application/octet-stream';
|
|
75
|
-
}
|
|
76
|
-
function isTextLike(name, mediaType) {
|
|
77
|
-
if (mediaType.startsWith('text/'))
|
|
78
|
-
return true;
|
|
79
|
-
if (['application/json', 'application/xml'].includes(mediaType))
|
|
80
|
-
return true;
|
|
81
|
-
const ext = name.split('.').pop()?.toLowerCase() ?? '';
|
|
82
|
-
return TEXT_EXTENSIONS.has(ext);
|
|
83
|
-
}
|
|
84
57
|
/** 内容嗅探:声明/扩展名说是图片、实际不是时降级为文件(不当安全边界,只做校正常识)。 */
|
|
85
58
|
function sniffMediaType(data) {
|
|
86
59
|
const bytes = (offset, length) => String.fromCharCode(...data.subarray(offset, offset + length));
|
|
@@ -336,6 +309,84 @@ export function createImApi(deps) {
|
|
|
336
309
|
// 派生数据(事件/facts/摘要/指标)落盘失败时如实回报,不再让客户端以为「存好了」。
|
|
337
310
|
return saved.warnings.length ? { path: saved.path, warnings: saved.warnings } : { path: saved.path };
|
|
338
311
|
},
|
|
312
|
+
// ── 回收站(软删除):会话/群数据目录搬进 .dsh-im/trash,客户端只管清单与状态 ──
|
|
313
|
+
async trashList(projectRoot) {
|
|
314
|
+
await loadKnownRoots();
|
|
315
|
+
const root = rootOf(projectRoot, true);
|
|
316
|
+
return { entries: await listTrash(root) };
|
|
317
|
+
},
|
|
318
|
+
async trashAdd(body) {
|
|
319
|
+
await loadKnownRoots();
|
|
320
|
+
const root = rootOf(body.projectRoot, true);
|
|
321
|
+
const threadIds = Array.isArray(body.threadIds)
|
|
322
|
+
? body.threadIds.filter((id) => typeof id === 'string')
|
|
323
|
+
: [];
|
|
324
|
+
const entry = await addTrashEntry(root, {
|
|
325
|
+
kind: body.kind,
|
|
326
|
+
...(typeof body.label === 'string' ? { label: body.label } : {}),
|
|
327
|
+
...(typeof body.detail === 'string' ? { detail: body.detail } : {}),
|
|
328
|
+
threadIds,
|
|
329
|
+
...(body.payload && typeof body.payload === 'object' ? { payload: body.payload } : {}),
|
|
330
|
+
replaceOnRestore: body.replaceOnRestore === true,
|
|
331
|
+
});
|
|
332
|
+
return { entry };
|
|
333
|
+
},
|
|
334
|
+
async trashRestore(body) {
|
|
335
|
+
await loadKnownRoots();
|
|
336
|
+
const root = rootOf(body.projectRoot, true);
|
|
337
|
+
const id = typeof body.id === 'string' ? body.id.trim() : '';
|
|
338
|
+
if (!id)
|
|
339
|
+
throw Object.assign(new Error('id 必填'), { status: 400 });
|
|
340
|
+
return restoreTrashEntry(root, id);
|
|
341
|
+
},
|
|
342
|
+
async trashPurge(body) {
|
|
343
|
+
await loadKnownRoots();
|
|
344
|
+
const root = rootOf(body.projectRoot, true);
|
|
345
|
+
const id = typeof body.id === 'string' ? body.id.trim() : '';
|
|
346
|
+
return purgeTrash(root, id || undefined);
|
|
347
|
+
},
|
|
348
|
+
/** 删除会话/角色、清空记录后释放对应原生会话(被删历史不能继续留在宿主内存)。 */
|
|
349
|
+
async nativeForget(body) {
|
|
350
|
+
const personaId = typeof body.personaId === 'string' ? body.personaId.trim() : '';
|
|
351
|
+
const threadId = typeof body.threadId === 'string' ? body.threadId.trim() : '';
|
|
352
|
+
if (!personaId && !threadId) {
|
|
353
|
+
throw Object.assign(new Error('personaId 或 threadId 必填(不接受"全部清空")'), { status: 400 });
|
|
354
|
+
}
|
|
355
|
+
const bridge = deps.native?.();
|
|
356
|
+
if (!bridge?.forget)
|
|
357
|
+
return { disposed: 0 };
|
|
358
|
+
const disposed = await bridge.forget({
|
|
359
|
+
...(personaId ? { personaId } : {}),
|
|
360
|
+
...(threadId ? { threadId } : {}),
|
|
361
|
+
});
|
|
362
|
+
return { disposed };
|
|
363
|
+
},
|
|
364
|
+
/**
|
|
365
|
+
* 群工作区文件浏览(只读):路径围栏在 `<根>/.dsh-im/groups/<threadId>/` 内,
|
|
366
|
+
* 内部账本(events/facts/metrics/receipts/...)不展示也不允许读。
|
|
367
|
+
*/
|
|
368
|
+
async groupFiles(body) {
|
|
369
|
+
await loadKnownRoots();
|
|
370
|
+
const root = rootOf(body.projectRoot, true);
|
|
371
|
+
const threadId = typeof body.threadId === 'string' ? body.threadId.trim() : '';
|
|
372
|
+
if (!threadId)
|
|
373
|
+
throw Object.assign(new Error('threadId 必填'), { status: 400 });
|
|
374
|
+
assertSafeThreadId(threadId);
|
|
375
|
+
return listGroupFiles(root, threadId, typeof body.path === 'string' ? body.path : '');
|
|
376
|
+
},
|
|
377
|
+
/** 读一个群文件(原始字节;面板用 <img>/fetch 展示或下载)。 */
|
|
378
|
+
async groupFile(body) {
|
|
379
|
+
await loadKnownRoots();
|
|
380
|
+
const root = rootOf(body.projectRoot, true);
|
|
381
|
+
const threadId = typeof body.threadId === 'string' ? body.threadId.trim() : '';
|
|
382
|
+
if (!threadId)
|
|
383
|
+
throw Object.assign(new Error('threadId 必填'), { status: 400 });
|
|
384
|
+
assertSafeThreadId(threadId);
|
|
385
|
+
const rel = typeof body.path === 'string' ? body.path : '';
|
|
386
|
+
if (!rel.trim())
|
|
387
|
+
throw Object.assign(new Error('path 必填'), { status: 400 });
|
|
388
|
+
return readGroupFile(root, threadId, rel);
|
|
389
|
+
},
|
|
339
390
|
/**
|
|
340
391
|
* 数据根发现(只读):当前根 + DSH 注册工作区 + 以前用过的根,各自有没有数据。
|
|
341
392
|
* 面板加载失败时用它列出「哪个根里还有数据」,而不是静默显示空。
|
package/dist/host/index.js
CHANGED
|
@@ -9,15 +9,20 @@ export const name = 'dsh-im';
|
|
|
9
9
|
export const inject = ['llm', 'agents', 'workspaceRegistry', 'attachments'];
|
|
10
10
|
const MAX_BODY = 2 * 1024 * 1024;
|
|
11
11
|
const MAX_UPLOAD_BODY = 25 * 1024 * 1024;
|
|
12
|
-
|
|
12
|
+
/**
|
|
13
|
+
* 回收站写入要带一份完整会话快照(消息 + 附件元数据),比普通 state 上限放宽。
|
|
14
|
+
* 仍是同源本地请求;上限存在的意义是挡住异常大包,不是权限边界。
|
|
15
|
+
*/
|
|
16
|
+
const MAX_TRASH_BODY = 8 * 1024 * 1024;
|
|
17
|
+
function readBodyLimited(req, limit, tooLarge) {
|
|
13
18
|
return new Promise((resolve, reject) => {
|
|
14
19
|
const chunks = [];
|
|
15
20
|
let size = 0;
|
|
16
21
|
req.on('data', (c) => {
|
|
17
22
|
const chunk = Buffer.isBuffer(c) ? c : Buffer.from(c);
|
|
18
23
|
size += chunk.length;
|
|
19
|
-
if (size >
|
|
20
|
-
reject(Object.assign(new Error(
|
|
24
|
+
if (size > limit) {
|
|
25
|
+
reject(Object.assign(new Error(tooLarge), { status: 413 }));
|
|
21
26
|
req.destroy();
|
|
22
27
|
return;
|
|
23
28
|
}
|
|
@@ -27,6 +32,12 @@ function readBody(req) {
|
|
|
27
32
|
req.on('error', reject);
|
|
28
33
|
});
|
|
29
34
|
}
|
|
35
|
+
function readBody(req) {
|
|
36
|
+
return readBodyLimited(req, MAX_BODY, 'request body too large');
|
|
37
|
+
}
|
|
38
|
+
function readTrashBody(req) {
|
|
39
|
+
return readBodyLimited(req, MAX_TRASH_BODY, '回收站快照太大');
|
|
40
|
+
}
|
|
30
41
|
/** 附件上传专用:原始字节,上限 25MB。 */
|
|
31
42
|
function readRawBody(req, limit = MAX_UPLOAD_BODY) {
|
|
32
43
|
return new Promise((resolve, reject) => {
|
|
@@ -186,6 +197,51 @@ function mountImRoutes(wctx, host, native, tooling) {
|
|
|
186
197
|
send(res, 200, await api.models());
|
|
187
198
|
return;
|
|
188
199
|
}
|
|
200
|
+
// ── 回收站(软删除) ────────────────────────────────────────────────
|
|
201
|
+
if (path.endsWith('/trash') && req.method === 'GET') {
|
|
202
|
+
send(res, 200, await api.trashList(url.searchParams.get('projectRoot') ?? undefined));
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
if (path.endsWith('/trash/add') && req.method === 'POST') {
|
|
206
|
+
send(res, 200, await api.trashAdd(JSON.parse(await readTrashBody(req))));
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
if (path.endsWith('/trash/restore') && req.method === 'POST') {
|
|
210
|
+
send(res, 200, await api.trashRestore(JSON.parse(await readBody(req))));
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
if (path.endsWith('/trash/purge') && req.method === 'POST') {
|
|
214
|
+
send(res, 200, await api.trashPurge(JSON.parse(await readBody(req))));
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
// 删除/清空后释放对应的原生会话(被删历史不能继续留在宿主内存里)。
|
|
218
|
+
if (path.endsWith('/native-forget') && req.method === 'POST') {
|
|
219
|
+
send(res, 200, await api.nativeForget(JSON.parse(await readBody(req))));
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
// 群工作区文件(只读):列表 + 原始文件字节(面板「文件」Tab 用)。
|
|
223
|
+
if (path.endsWith('/group-files') && req.method === 'GET') {
|
|
224
|
+
send(res, 200, await api.groupFiles({
|
|
225
|
+
threadId: url.searchParams.get('threadId') ?? undefined,
|
|
226
|
+
projectRoot: url.searchParams.get('projectRoot') ?? undefined,
|
|
227
|
+
path: url.searchParams.get('path') ?? undefined,
|
|
228
|
+
}));
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
if (path.endsWith('/group-file') && req.method === 'GET') {
|
|
232
|
+
const file = await api.groupFile({
|
|
233
|
+
threadId: url.searchParams.get('threadId') ?? undefined,
|
|
234
|
+
projectRoot: url.searchParams.get('projectRoot') ?? undefined,
|
|
235
|
+
path: url.searchParams.get('path') ?? undefined,
|
|
236
|
+
});
|
|
237
|
+
res.writeHead(200, {
|
|
238
|
+
'content-type': file.mediaType,
|
|
239
|
+
'content-length': String(file.bytes.byteLength),
|
|
240
|
+
'cache-control': 'no-store',
|
|
241
|
+
});
|
|
242
|
+
res.end(file.bytes);
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
189
245
|
// 数据根体检(只读):面板据此在加载失败时列出「哪个根里还有数据」。
|
|
190
246
|
if (path.endsWith('/roots') && req.method === 'GET') {
|
|
191
247
|
send(res, 200, await api.stateRoots());
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 文件 → mediaType 的判定(纯函数,只在 host 侧使用)。
|
|
3
|
+
*
|
|
4
|
+
* 上传附件、群文件浏览、附件下载三处必须用同一套判定:以前这段写在 `im-api.ts` 里,
|
|
5
|
+
* 群文件接口也要用,抽出来避免两套扩展名表漂移。
|
|
6
|
+
*/
|
|
7
|
+
export declare const TEXT_EXTENSIONS: Set<string>;
|
|
8
|
+
export declare function mediaTypeFor(name: string, declared?: string): string;
|
|
9
|
+
/** 是否按文本处理(预览/内联)。mediaType 优先,扩展名兜底。 */
|
|
10
|
+
export declare function isTextLike(name: string, mediaType: string): boolean;
|
|
@@ -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
|
+
}>;
|