@dabuliu_wsy/dsh-im 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 +197 -3
- package/cordis.patch.yml +4 -0
- package/dist/core/agent-state.d.ts +38 -0
- package/dist/core/agent-state.js +59 -0
- package/dist/core/arbiter-bridge.d.ts +25 -0
- package/dist/core/arbiter-bridge.js +20 -0
- package/dist/core/arbiter.d.ts +29 -0
- package/dist/core/arbiter.js +59 -0
- package/dist/core/avatar-brands.d.ts +23 -0
- package/dist/core/avatar-brands.js +75 -0
- package/dist/core/avatar-presets.d.ts +21 -0
- package/dist/core/avatar-presets.js +38 -0
- package/dist/core/avatar.d.ts +1 -0
- package/dist/core/avatar.js +18 -0
- package/dist/core/blocked.d.ts +12 -0
- package/dist/core/blocked.js +23 -0
- package/dist/core/budget-plan.d.ts +41 -0
- package/dist/core/budget-plan.js +69 -0
- package/dist/core/calibration-samples.d.ts +77 -0
- package/dist/core/calibration-samples.js +168 -0
- package/dist/core/calibrator.d.ts +57 -0
- package/dist/core/calibrator.js +125 -0
- package/dist/core/chapter-tree.d.ts +128 -0
- package/dist/core/chapter-tree.js +400 -0
- package/dist/core/consensus.d.ts +135 -0
- package/dist/core/consensus.js +394 -0
- package/dist/core/context-budget.d.ts +153 -0
- package/dist/core/context-budget.js +183 -0
- package/dist/core/curator.d.ts +28 -0
- package/dist/core/curator.js +190 -0
- package/dist/core/dual-window.d.ts +86 -0
- package/dist/core/dual-window.js +175 -0
- package/dist/core/events.d.ts +110 -0
- package/dist/core/events.js +117 -0
- package/dist/core/facts.d.ts +114 -0
- package/dist/core/facts.js +400 -0
- package/dist/core/fence.d.ts +34 -0
- package/dist/core/fence.js +129 -0
- package/dist/core/floor.d.ts +18 -0
- package/dist/core/floor.js +80 -0
- package/dist/core/ids.d.ts +11 -0
- package/dist/core/ids.js +29 -0
- package/dist/core/im.d.ts +167 -0
- package/dist/core/im.js +1307 -0
- package/dist/core/index.d.ts +33 -0
- package/dist/core/index.js +33 -0
- package/dist/core/log.d.ts +21 -0
- package/dist/core/log.js +63 -0
- package/dist/core/memory-claims.d.ts +67 -0
- package/dist/core/memory-claims.js +164 -0
- package/dist/core/memory-context.d.ts +121 -0
- package/dist/core/memory-context.js +303 -0
- package/dist/core/memory-visibility.d.ts +58 -0
- package/dist/core/memory-visibility.js +36 -0
- package/dist/core/memory.d.ts +12 -0
- package/dist/core/memory.js +73 -0
- package/dist/core/metrics.d.ts +49 -0
- package/dist/core/metrics.js +89 -0
- package/dist/core/multi-hop.d.ts +116 -0
- package/dist/core/multi-hop.js +278 -0
- package/dist/core/persist.d.ts +21 -0
- package/dist/core/persist.js +94 -0
- package/dist/core/proactive.d.ts +54 -0
- package/dist/core/proactive.js +108 -0
- package/dist/core/prompt.d.ts +82 -0
- package/dist/core/prompt.js +164 -0
- package/dist/core/receipt.d.ts +107 -0
- package/dist/core/receipt.js +86 -0
- package/dist/core/retrieval.d.ts +69 -0
- package/dist/core/retrieval.js +260 -0
- package/dist/core/role-state.d.ts +16 -0
- package/dist/core/role-state.js +65 -0
- package/dist/core/runtime.d.ts +137 -0
- package/dist/core/runtime.js +574 -0
- package/dist/core/summary.d.ts +19 -0
- package/dist/core/summary.js +96 -0
- package/dist/core/text.d.ts +10 -0
- package/dist/core/text.js +45 -0
- package/dist/core/time.d.ts +22 -0
- package/dist/core/time.js +84 -0
- package/dist/core/tool-schema.d.ts +12 -0
- package/dist/core/tool-schema.js +92 -0
- package/dist/core/tools.d.ts +137 -0
- package/dist/core/tools.js +348 -0
- package/dist/core/types.d.ts +400 -0
- package/dist/core/types.js +1 -0
- package/dist/core/window.d.ts +6 -0
- package/dist/core/window.js +7 -0
- package/dist/core/workspace-node.d.ts +28 -0
- package/dist/core/workspace-node.js +232 -0
- package/dist/core/workspace.d.ts +9 -0
- package/dist/core/workspace.js +45 -0
- package/dist/host/agent-session.d.ts +279 -0
- package/dist/host/agent-session.js +935 -0
- package/dist/host/attachment-gc.d.ts +37 -0
- package/dist/host/attachment-gc.js +97 -0
- package/dist/host/calibration-samples-store.d.ts +5 -0
- package/dist/host/calibration-samples-store.js +67 -0
- package/dist/host/capabilities.d.ts +45 -0
- package/dist/host/capabilities.js +67 -0
- package/dist/host/derived-store.d.ts +36 -0
- package/dist/host/derived-store.js +199 -0
- package/dist/host/dsh-llm.d.ts +143 -0
- package/dist/host/dsh-llm.js +395 -0
- package/dist/host/event-store.d.ts +47 -0
- package/dist/host/event-store.js +154 -0
- package/dist/host/fs-atomic.d.ts +1 -0
- package/dist/host/fs-atomic.js +26 -0
- package/dist/host/im-api.d.ts +352 -0
- package/dist/host/im-api.js +1137 -0
- package/dist/host/index.d.ts +103 -0
- package/dist/host/index.js +453 -0
- package/dist/host/memory-index.d.ts +65 -0
- package/dist/host/memory-index.js +181 -0
- package/dist/host/metrics-store.d.ts +7 -0
- package/dist/host/metrics-store.js +104 -0
- package/dist/host/models.d.ts +39 -0
- package/dist/host/models.js +67 -0
- package/dist/host/persona-tools.d.ts +57 -0
- package/dist/host/persona-tools.js +226 -0
- package/dist/host/preflight.d.ts +31 -0
- package/dist/host/preflight.js +29 -0
- package/dist/host/receipt-store.d.ts +26 -0
- package/dist/host/receipt-store.js +68 -0
- package/dist/host/run-check.d.ts +51 -0
- package/dist/host/run-check.js +190 -0
- package/dist/host/state-roots.d.ts +50 -0
- package/dist/host/state-roots.js +163 -0
- package/dist/host/tool-cache.d.ts +25 -0
- package/dist/host/tool-cache.js +90 -0
- package/dist/host/tool-call-budget.d.ts +29 -0
- package/dist/host/tool-call-budget.js +38 -0
- package/dsh-plugin.json +25 -0
- package/lib/client.inner.cjs +3346 -0
- package/lib/client.js +3354 -0
- package/package.json +86 -6
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import { type DshAttachmentStore } from './im-api.ts';
|
|
3
|
+
import type { LlmService } from './dsh-llm.ts';
|
|
4
|
+
import { type HostToolsProbe, type NativeAgentsApi } from './agent-session.ts';
|
|
5
|
+
import { type ToolGroupDecl } from '../core/tools.ts';
|
|
6
|
+
export declare const name = "dsh-im";
|
|
7
|
+
export declare const inject: string[];
|
|
8
|
+
type DshCtx = {
|
|
9
|
+
inject?: (deps: string[], fn: (sub: DshCtx) => void) => void;
|
|
10
|
+
effect?: (fn: () => (() => void) | void, label?: string) => void;
|
|
11
|
+
get?: (name: string) => unknown;
|
|
12
|
+
workspaceRegistry?: {
|
|
13
|
+
list?: () => {
|
|
14
|
+
id?: string;
|
|
15
|
+
path?: string;
|
|
16
|
+
title?: string;
|
|
17
|
+
}[];
|
|
18
|
+
get?: (id: string) => {
|
|
19
|
+
path?: string;
|
|
20
|
+
title?: string;
|
|
21
|
+
} | undefined;
|
|
22
|
+
create?: (path: string, title?: string) => Promise<{
|
|
23
|
+
id?: string;
|
|
24
|
+
path?: string;
|
|
25
|
+
title?: string;
|
|
26
|
+
} | undefined> | {
|
|
27
|
+
id?: string;
|
|
28
|
+
path?: string;
|
|
29
|
+
title?: string;
|
|
30
|
+
} | undefined;
|
|
31
|
+
archiveSession?: (sessionId: string, options?: {
|
|
32
|
+
stopActivity?: boolean;
|
|
33
|
+
}) => Promise<unknown>;
|
|
34
|
+
};
|
|
35
|
+
agents?: NativeAgentsApi;
|
|
36
|
+
webServer?: {
|
|
37
|
+
register: (row: {
|
|
38
|
+
kind: string;
|
|
39
|
+
path: string;
|
|
40
|
+
handler: (req: IncomingMessage, res: ServerResponse) => Promise<void> | void;
|
|
41
|
+
}) => () => void;
|
|
42
|
+
};
|
|
43
|
+
webRuntime?: {
|
|
44
|
+
trustedHosts?: string[];
|
|
45
|
+
};
|
|
46
|
+
logger?: {
|
|
47
|
+
info?: (m: string) => void;
|
|
48
|
+
warn?: (m: string) => void;
|
|
49
|
+
};
|
|
50
|
+
llm?: LlmService;
|
|
51
|
+
/** DSH 附件存储(宿主可能没挂载;没挂载时图片只存本地、模型看不到内容)。 */
|
|
52
|
+
attachments?: DshAttachmentStore;
|
|
53
|
+
/** 宿主 tools 服务(能力探测用;agent 作用域才可执行,这里只读方法形状)。 */
|
|
54
|
+
tools?: HostToolsProbe;
|
|
55
|
+
/** 可选的「用过的数据根」记忆文件路径(默认 ~/.dsh-im/known-roots.json)。 */
|
|
56
|
+
rootsFile?: string;
|
|
57
|
+
};
|
|
58
|
+
/** DSH 原生工作区列表(给“关联工作区”下拉用;新工作区在 DSH 里添加后刷新面板即可)。 */
|
|
59
|
+
export declare function workspaceOptions(ctx: DshCtx): {
|
|
60
|
+
title: string;
|
|
61
|
+
path: string;
|
|
62
|
+
}[];
|
|
63
|
+
/**
|
|
64
|
+
* 通过 DSH 注册表创建工作区。
|
|
65
|
+
* 必须保留 `this`(DSH 的 create 内部会用到 this.enqueueOperation 等),
|
|
66
|
+
* 所以不能把 create 拆出来单独调用——否则报 `Cannot read properties of undefined (reading 'enqueueOperation')`。
|
|
67
|
+
*/
|
|
68
|
+
export declare function createWorkspaceViaRegistry(registry: {
|
|
69
|
+
create?: (path: string, title?: string) => Promise<{
|
|
70
|
+
id?: string;
|
|
71
|
+
path?: string;
|
|
72
|
+
title?: string;
|
|
73
|
+
} | undefined> | {
|
|
74
|
+
id?: string;
|
|
75
|
+
path?: string;
|
|
76
|
+
title?: string;
|
|
77
|
+
} | undefined;
|
|
78
|
+
} | undefined, path: string, title?: string): Promise<{
|
|
79
|
+
id?: string;
|
|
80
|
+
path?: string;
|
|
81
|
+
title?: string;
|
|
82
|
+
} | undefined> | {
|
|
83
|
+
id?: string;
|
|
84
|
+
path?: string;
|
|
85
|
+
title?: string;
|
|
86
|
+
} | undefined;
|
|
87
|
+
/** 文件夹浏览器:只列目录(不读文件内容),用于“添加工作区…”选文件夹。 */
|
|
88
|
+
export declare function browseFolders(rawPath?: string): Promise<{
|
|
89
|
+
path: string;
|
|
90
|
+
parent: string;
|
|
91
|
+
entries: {
|
|
92
|
+
name: string;
|
|
93
|
+
path: string;
|
|
94
|
+
}[];
|
|
95
|
+
}>;
|
|
96
|
+
/** dsh-im 插件配置。目前只有工具来源组声明(追加/覆盖出厂声明)。 */
|
|
97
|
+
export interface DshImConfig {
|
|
98
|
+
toolGroups?: ToolGroupDecl[];
|
|
99
|
+
}
|
|
100
|
+
/** 配置声明只做形状校验:非法项直接报错,不静默吞掉。 */
|
|
101
|
+
export declare function resolveConfiguredToolGroups(config?: DshImConfig): ToolGroupDecl[];
|
|
102
|
+
export declare function apply(ctx: DshCtx, config?: DshImConfig): void;
|
|
103
|
+
export {};
|
|
@@ -0,0 +1,453 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { readdir } from 'node:fs/promises';
|
|
3
|
+
import { dirname, isAbsolute, join, parse } from 'node:path';
|
|
4
|
+
import { createImApi } from './im-api.js';
|
|
5
|
+
import { createNativeRuntime, nativeTtlMs, } from './agent-session.js';
|
|
6
|
+
import { BUILTIN_TOOL_GROUPS, schemaToolNames, toolGroupCatalog } from '../core/tools.js';
|
|
7
|
+
import { setLogSink } from '../core/log.js';
|
|
8
|
+
export const name = 'dsh-im';
|
|
9
|
+
export const inject = ['llm', 'agents', 'workspaceRegistry', 'attachments'];
|
|
10
|
+
const MAX_BODY = 2 * 1024 * 1024;
|
|
11
|
+
const MAX_UPLOAD_BODY = 25 * 1024 * 1024;
|
|
12
|
+
function readBody(req) {
|
|
13
|
+
return new Promise((resolve, reject) => {
|
|
14
|
+
const chunks = [];
|
|
15
|
+
let size = 0;
|
|
16
|
+
req.on('data', (c) => {
|
|
17
|
+
const chunk = Buffer.isBuffer(c) ? c : Buffer.from(c);
|
|
18
|
+
size += chunk.length;
|
|
19
|
+
if (size > MAX_BODY) {
|
|
20
|
+
reject(Object.assign(new Error('request body too large'), { status: 413 }));
|
|
21
|
+
req.destroy();
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
chunks.push(chunk);
|
|
25
|
+
});
|
|
26
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
27
|
+
req.on('error', reject);
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
/** 附件上传专用:原始字节,上限 25MB。 */
|
|
31
|
+
function readRawBody(req, limit = MAX_UPLOAD_BODY) {
|
|
32
|
+
return new Promise((resolve, reject) => {
|
|
33
|
+
const chunks = [];
|
|
34
|
+
let size = 0;
|
|
35
|
+
req.on('data', (c) => {
|
|
36
|
+
const chunk = Buffer.isBuffer(c) ? c : Buffer.from(c);
|
|
37
|
+
size += chunk.length;
|
|
38
|
+
if (size > limit) {
|
|
39
|
+
reject(Object.assign(new Error('附件太大'), { status: 413 }));
|
|
40
|
+
req.destroy();
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
chunks.push(chunk);
|
|
44
|
+
});
|
|
45
|
+
req.on('end', () => resolve(Buffer.concat(chunks)));
|
|
46
|
+
req.on('error', reject);
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
function send(res, status, body) {
|
|
50
|
+
const json = typeof body === 'string' ? body : JSON.stringify(body);
|
|
51
|
+
res.statusCode = status;
|
|
52
|
+
res.setHeader('content-type', 'application/json; charset=utf-8');
|
|
53
|
+
res.end(json);
|
|
54
|
+
}
|
|
55
|
+
function workspacePath(ctx) {
|
|
56
|
+
try {
|
|
57
|
+
const list = ctx.workspaceRegistry?.list?.() ?? [];
|
|
58
|
+
const first = list.find((w) => w.path)?.path;
|
|
59
|
+
if (first)
|
|
60
|
+
return first;
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
// 没有工作区时落到进程 cwd。
|
|
64
|
+
}
|
|
65
|
+
return process.cwd();
|
|
66
|
+
}
|
|
67
|
+
/** 宿主可能没挂载附件服务:先按 Cordis 服务取,再退回字段;都没有就返回 undefined。 */
|
|
68
|
+
function dshAttachmentStore(ctx) {
|
|
69
|
+
try {
|
|
70
|
+
const fromService = typeof ctx.get === 'function' ? ctx.get('attachments') : undefined;
|
|
71
|
+
if (fromService)
|
|
72
|
+
return fromService;
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
// 没有该服务时 get 可能抛错,忽略。
|
|
76
|
+
}
|
|
77
|
+
return ctx.attachments;
|
|
78
|
+
}
|
|
79
|
+
/** DSH 原生工作区列表(给“关联工作区”下拉用;新工作区在 DSH 里添加后刷新面板即可)。 */
|
|
80
|
+
export function workspaceOptions(ctx) {
|
|
81
|
+
try {
|
|
82
|
+
const list = ctx.workspaceRegistry?.list?.() ?? [];
|
|
83
|
+
return list
|
|
84
|
+
.filter((item) => Boolean(item.path))
|
|
85
|
+
.map((item) => ({ title: item.title?.trim() || item.path, path: item.path }));
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return [];
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* 通过 DSH 注册表创建工作区。
|
|
93
|
+
* 必须保留 `this`(DSH 的 create 内部会用到 this.enqueueOperation 等),
|
|
94
|
+
* 所以不能把 create 拆出来单独调用——否则报 `Cannot read properties of undefined (reading 'enqueueOperation')`。
|
|
95
|
+
*/
|
|
96
|
+
export function createWorkspaceViaRegistry(registry, path, title) {
|
|
97
|
+
if (!registry?.create)
|
|
98
|
+
throw Object.assign(new Error('当前 DSH 不支持从插件创建工作区'), { status: 400 });
|
|
99
|
+
return registry.create.call(registry, path, title);
|
|
100
|
+
}
|
|
101
|
+
/** 文件夹浏览器:只列目录(不读文件内容),用于“添加工作区…”选文件夹。 */
|
|
102
|
+
export async function browseFolders(rawPath) {
|
|
103
|
+
const target = (rawPath ?? '').trim();
|
|
104
|
+
if (!target) {
|
|
105
|
+
if (process.platform !== 'win32') {
|
|
106
|
+
const entries = await listDirs('/');
|
|
107
|
+
return { path: '/', parent: '', entries };
|
|
108
|
+
}
|
|
109
|
+
const entries = [];
|
|
110
|
+
for (const letter of 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') {
|
|
111
|
+
const root = `${letter}:\\`;
|
|
112
|
+
if (existsSync(root))
|
|
113
|
+
entries.push({ name: root, path: root });
|
|
114
|
+
}
|
|
115
|
+
return { path: '', parent: '', entries };
|
|
116
|
+
}
|
|
117
|
+
if (!isAbsolute(target))
|
|
118
|
+
throw Object.assign(new Error('必须是绝对路径'), { status: 400 });
|
|
119
|
+
const entries = await listDirs(target);
|
|
120
|
+
const root = parse(target).root;
|
|
121
|
+
const parent = target === root ? '' : dirname(target);
|
|
122
|
+
return { path: target, parent, entries };
|
|
123
|
+
}
|
|
124
|
+
async function listDirs(path) {
|
|
125
|
+
const rows = await readdir(path, { withFileTypes: true });
|
|
126
|
+
return rows
|
|
127
|
+
.filter((row) => row.isDirectory())
|
|
128
|
+
.map((row) => ({ name: row.name, path: join(path, row.name) }))
|
|
129
|
+
.sort((a, b) => a.name.localeCompare(b.name, 'zh-CN'));
|
|
130
|
+
}
|
|
131
|
+
function mountImRoutes(wctx, host, native, tooling) {
|
|
132
|
+
const api = createImApi({
|
|
133
|
+
projectRoot: () => workspacePath(host),
|
|
134
|
+
llm: () => host.llm,
|
|
135
|
+
attachments: () => dshAttachmentStore(host),
|
|
136
|
+
native: () => native.bridge,
|
|
137
|
+
workspaces: () => workspaceOptions(host),
|
|
138
|
+
hostTools: tooling.probe,
|
|
139
|
+
toolGroups: tooling.catalog,
|
|
140
|
+
rootsFile: () => host.rootsFile,
|
|
141
|
+
});
|
|
142
|
+
// 预热「用过的数据根」白名单:挂载后首个请求就能认回 DSH 注册表外的历史数据根。
|
|
143
|
+
void api.loadKnownRoots();
|
|
144
|
+
const logger = host.logger ?? wctx.logger;
|
|
145
|
+
// 插件自己的日志统一走 core/log.ts:宿主有 logger 时跟着宿主走,不再直接打 console。
|
|
146
|
+
if (logger) {
|
|
147
|
+
setLogSink({
|
|
148
|
+
info: (message) => logger.info?.(message),
|
|
149
|
+
warn: (message, detail) => logger.warn?.(detail === undefined ? message : `${message} ${typeof detail === 'string' ? detail : String(detail)}`),
|
|
150
|
+
debug: (message) => logger.info?.(message),
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
const handler = async (req, res) => {
|
|
154
|
+
// 防跨站:只接受同源页面发起的请求。
|
|
155
|
+
const origin = req.headers.origin;
|
|
156
|
+
if (origin) {
|
|
157
|
+
try {
|
|
158
|
+
if (new URL(origin).host !== req.headers.host) {
|
|
159
|
+
send(res, 403, { error: 'forbidden origin' });
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
send(res, 403, { error: 'forbidden origin' });
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const url = new URL(req.url ?? '/', 'http://localhost');
|
|
169
|
+
const path = url.pathname.replace(/\/$/, '') || '/';
|
|
170
|
+
try {
|
|
171
|
+
if (path.endsWith('/state') && req.method === 'GET') {
|
|
172
|
+
// 状态跟随“当前面板/活动工作区”:客户端带 ?projectRoot= 时读写那个工作区的 .dsh-im。
|
|
173
|
+
const state = await api.getState(url.searchParams.get('projectRoot') ?? undefined);
|
|
174
|
+
if (!state) {
|
|
175
|
+
send(res, 404, { error: 'empty' });
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
send(res, 200, state);
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
if (path.endsWith('/state') && req.method === 'PUT') {
|
|
182
|
+
send(res, 200, await api.putState(await readBody(req), url.searchParams.get('projectRoot') ?? undefined));
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
if (path.endsWith('/models') && req.method === 'GET') {
|
|
186
|
+
send(res, 200, await api.models());
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
// 数据根体检(只读):面板据此在加载失败时列出「哪个根里还有数据」。
|
|
190
|
+
if (path.endsWith('/roots') && req.method === 'GET') {
|
|
191
|
+
send(res, 200, await api.stateRoots());
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
if (path.endsWith('/preflight') && req.method === 'POST') {
|
|
195
|
+
send(res, 200, await api.preflight(JSON.parse(await readBody(req))));
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
// 注意:/native-complete 要排在 /complete 之前(endsWith 会命中)。
|
|
199
|
+
if (path.endsWith('/llm-probe') && req.method === 'POST') {
|
|
200
|
+
send(res, 200, await api.llmProbe(JSON.parse(await readBody(req))));
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
if (path.endsWith('/native-complete') && req.method === 'POST') {
|
|
204
|
+
send(res, 200, await api.nativeComplete(JSON.parse(await readBody(req))));
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
if (path.endsWith('/native-status') && req.method === 'GET') {
|
|
208
|
+
send(res, 200, api.nativeStatus());
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
if (path.endsWith('/tool-groups') && req.method === 'GET') {
|
|
212
|
+
send(res, 200, api.toolGroups());
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
if (path.endsWith('/native-debug') && req.method === 'GET') {
|
|
216
|
+
send(res, 200, api.nativeDebug());
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
// Phase 0:宿主能力探测(tokenizer / usage / embeddings),只读。
|
|
220
|
+
if (path.endsWith('/capabilities') && req.method === 'GET') {
|
|
221
|
+
send(res, 200, api.capabilities());
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
// Phase 1b:chars/token 校准(面板启动读取,用于 token 预算换算)。
|
|
225
|
+
if (path.endsWith('/calibration') && req.method === 'GET') {
|
|
226
|
+
send(res, 200, await api.tokenCalibration(url.searchParams.get('projectRoot') ?? undefined));
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
// Phase 0:记忆索引预览(默认不落盘),用于验证派生索引与弱状态。
|
|
230
|
+
if (path.endsWith('/memory-index') && req.method === 'GET') {
|
|
231
|
+
send(res, 200, await api.memoryIndex({
|
|
232
|
+
threadId: url.searchParams.get('threadId') ?? undefined,
|
|
233
|
+
projectRoot: url.searchParams.get('projectRoot') ?? undefined,
|
|
234
|
+
persist: url.searchParams.get('persist') === '1',
|
|
235
|
+
}));
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
if (path.endsWith('/complete') && req.method === 'POST') {
|
|
239
|
+
const body = JSON.parse(await readBody(req));
|
|
240
|
+
send(res, 200, await api.complete(body));
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (path.endsWith('/file') && req.method === 'POST') {
|
|
244
|
+
send(res, 200, await api.writeFile(JSON.parse(await readBody(req))));
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
if (path.endsWith('/workspaces') && req.method === 'GET') {
|
|
248
|
+
send(res, 200, workspaceOptions(host));
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
if (path.endsWith('/workspaces') && req.method === 'POST') {
|
|
252
|
+
const body = JSON.parse(await readBody(req));
|
|
253
|
+
const target = (body.path ?? '').trim();
|
|
254
|
+
if (!target || !isAbsolute(target)) {
|
|
255
|
+
throw Object.assign(new Error('path 必须是绝对路径'), { status: 400 });
|
|
256
|
+
}
|
|
257
|
+
if (!host.workspaceRegistry?.create) {
|
|
258
|
+
throw Object.assign(new Error('当前 DSH 不支持从插件创建工作区'), { status: 400 });
|
|
259
|
+
}
|
|
260
|
+
const created = await createWorkspaceViaRegistry(host.workspaceRegistry, target, body.title?.trim() || undefined);
|
|
261
|
+
send(res, 200, { workspaces: workspaceOptions(host), path: created?.path ?? target });
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
if (path.endsWith('/upload') && req.method === 'POST') {
|
|
265
|
+
const bytes = await readRawBody(req);
|
|
266
|
+
send(res, 200, await api.uploadAttachment({
|
|
267
|
+
threadId: url.searchParams.get('threadId') ?? undefined,
|
|
268
|
+
projectRoot: url.searchParams.get('projectRoot') ?? undefined,
|
|
269
|
+
name: url.searchParams.get('name') ?? undefined,
|
|
270
|
+
mediaType: url.searchParams.get('mediaType') ?? undefined,
|
|
271
|
+
data: bytes,
|
|
272
|
+
}));
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
if (path.endsWith('/attachment-gc') && req.method === 'POST') {
|
|
276
|
+
const body = JSON.parse(await readBody(req));
|
|
277
|
+
send(res, 200, await api.attachmentGc(body));
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
if (path.endsWith('/attachment') && req.method === 'GET') {
|
|
281
|
+
const file = await api.attachmentFile({
|
|
282
|
+
threadId: url.searchParams.get('threadId') ?? undefined,
|
|
283
|
+
file: url.searchParams.get('file') ?? undefined,
|
|
284
|
+
projectRoot: url.searchParams.get('projectRoot') ?? undefined,
|
|
285
|
+
});
|
|
286
|
+
res.writeHead(200, {
|
|
287
|
+
'content-type': file.mediaType,
|
|
288
|
+
'content-length': String(file.bytes.byteLength),
|
|
289
|
+
'cache-control': 'private, max-age=31536000, immutable',
|
|
290
|
+
});
|
|
291
|
+
res.end(file.bytes);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
if (path.endsWith('/fs') && req.method === 'GET') {
|
|
295
|
+
send(res, 200, await browseFolders(url.searchParams.get('path') ?? undefined));
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
if (path.endsWith('/workspace') && req.method === 'GET') {
|
|
299
|
+
send(res, 200, await api.workspace(url.searchParams.get('projectRoot') ?? undefined));
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
send(res, 404, { error: 'not found' });
|
|
303
|
+
}
|
|
304
|
+
catch (err) {
|
|
305
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
306
|
+
const status = err.status ?? 500;
|
|
307
|
+
send(res, status, { error: message });
|
|
308
|
+
}
|
|
309
|
+
};
|
|
310
|
+
const dispose = wctx.webServer?.register({
|
|
311
|
+
kind: 'prefix',
|
|
312
|
+
path: '/api/im',
|
|
313
|
+
handler,
|
|
314
|
+
});
|
|
315
|
+
logger?.info?.('[dsh-im] /api/im mounted; models and calls go through ctx.llm');
|
|
316
|
+
return () => dispose?.();
|
|
317
|
+
}
|
|
318
|
+
/** 配置声明只做形状校验:非法项直接报错,不静默吞掉。 */
|
|
319
|
+
export function resolveConfiguredToolGroups(config) {
|
|
320
|
+
const raw = config?.toolGroups;
|
|
321
|
+
if (raw === undefined)
|
|
322
|
+
return [];
|
|
323
|
+
if (!Array.isArray(raw))
|
|
324
|
+
throw new Error('dsh-im config.toolGroups 必须是数组');
|
|
325
|
+
return raw.map((item, index) => {
|
|
326
|
+
const at = `dsh-im config.toolGroups[${index}]`;
|
|
327
|
+
if (!item || typeof item !== 'object')
|
|
328
|
+
throw new Error(`${at} 必须是对象`);
|
|
329
|
+
const id = item.id;
|
|
330
|
+
const label = item.label;
|
|
331
|
+
if (typeof id !== 'string' || !id.trim())
|
|
332
|
+
throw new Error(`${at}.id 必须是非空字符串`);
|
|
333
|
+
if (typeof label !== 'string' || !label.trim())
|
|
334
|
+
throw new Error(`${at}.label 必须是非空字符串`);
|
|
335
|
+
if (BUILTIN_TOOL_GROUPS.some((builtin) => builtin.id === id)) {
|
|
336
|
+
throw new Error(`${at}.id "${id}" 与出厂来源组重名`);
|
|
337
|
+
}
|
|
338
|
+
const match = item.match;
|
|
339
|
+
if (match !== undefined) {
|
|
340
|
+
if (!match || typeof match !== 'object')
|
|
341
|
+
throw new Error(`${at}.match 必须是对象`);
|
|
342
|
+
for (const key of ['names', 'prefixes', 'mcpServers']) {
|
|
343
|
+
const value = match[key];
|
|
344
|
+
if (value === undefined)
|
|
345
|
+
continue;
|
|
346
|
+
if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string' || !entry)) {
|
|
347
|
+
throw new Error(`${at}.match.${key} 必须是非空字符串数组`);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
return { id: id.trim(), label: label.trim(), ...(match ? { match: { ...match } } : {}) };
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
/** 宿主 tools 服务探测(只读形状)。 */
|
|
355
|
+
function hostToolsProbe(ctx) {
|
|
356
|
+
try {
|
|
357
|
+
const tools = typeof ctx.get === 'function' ? ctx.get('tools') : ctx.tools;
|
|
358
|
+
return tools;
|
|
359
|
+
}
|
|
360
|
+
catch {
|
|
361
|
+
return undefined;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
/** 宿主全局(host-plane)工具名;来源组发现与会话重建判定共用。 */
|
|
365
|
+
function hostPlaneToolNames(probe) {
|
|
366
|
+
try {
|
|
367
|
+
const tools = probe();
|
|
368
|
+
if (!tools || typeof tools.schemas !== 'function')
|
|
369
|
+
return [];
|
|
370
|
+
return schemaToolNames(tools.schemas());
|
|
371
|
+
}
|
|
372
|
+
catch {
|
|
373
|
+
return [];
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
export function apply(ctx, config) {
|
|
377
|
+
ctx.effect?.(() => {
|
|
378
|
+
let disposeWeb;
|
|
379
|
+
const configuredGroups = resolveConfiguredToolGroups(config);
|
|
380
|
+
const declaredGroups = [...BUILTIN_TOOL_GROUPS, ...configuredGroups];
|
|
381
|
+
const host = {
|
|
382
|
+
get llm() {
|
|
383
|
+
return ctx.llm ?? (typeof ctx.get === 'function' ? ctx.get('llm') : undefined);
|
|
384
|
+
},
|
|
385
|
+
get workspaceRegistry() {
|
|
386
|
+
return ctx.workspaceRegistry;
|
|
387
|
+
},
|
|
388
|
+
get agents() {
|
|
389
|
+
// 可选依赖:优先 ctx.get(Cordis 允许未 inject 的服务这样取),再退回属性。
|
|
390
|
+
try {
|
|
391
|
+
const fromGet = typeof ctx.get === 'function' ? ctx.get('agents') : undefined;
|
|
392
|
+
if (fromGet)
|
|
393
|
+
return fromGet;
|
|
394
|
+
}
|
|
395
|
+
catch {
|
|
396
|
+
// 没有该服务。
|
|
397
|
+
}
|
|
398
|
+
return ctx.agents;
|
|
399
|
+
},
|
|
400
|
+
get tools() {
|
|
401
|
+
return hostToolsProbe(ctx);
|
|
402
|
+
},
|
|
403
|
+
logger: ctx.logger,
|
|
404
|
+
};
|
|
405
|
+
try {
|
|
406
|
+
const got = typeof ctx.get === 'function' ? ctx.get('attachments') : ctx.attachments;
|
|
407
|
+
const saveImagesType = got == null ? 'undefined' : typeof got.saveImages;
|
|
408
|
+
ctx.logger?.warn?.(`[dsh-im] attachments typeof=${got == null ? 'undefined' : typeof got} typeofSaveImages=${saveImagesType}`);
|
|
409
|
+
}
|
|
410
|
+
catch (error) {
|
|
411
|
+
ctx.logger?.warn?.(`[dsh-im] attachments get failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
412
|
+
}
|
|
413
|
+
const native = createNativeRuntime({
|
|
414
|
+
// 默认挂上。DSH_IM_NATIVE_SESSION=0 才整段关掉,给排查用。开不开由面板开关决定。
|
|
415
|
+
enabled: process.env.DSH_IM_NATIVE_SESSION !== '0',
|
|
416
|
+
ttlMs: nativeTtlMs(),
|
|
417
|
+
agents: () => host.agents,
|
|
418
|
+
workspace: () => host.workspaceRegistry,
|
|
419
|
+
logger: ctx.logger,
|
|
420
|
+
hostTools: () => hostToolsProbe(ctx),
|
|
421
|
+
toolGroups: configuredGroups,
|
|
422
|
+
});
|
|
423
|
+
const tooling = {
|
|
424
|
+
probe: () => hostToolsProbe(ctx),
|
|
425
|
+
catalog: () => toolGroupCatalog(hostPlaneToolNames(() => hostToolsProbe(ctx)), declaredGroups),
|
|
426
|
+
};
|
|
427
|
+
if (typeof ctx.inject === 'function') {
|
|
428
|
+
try {
|
|
429
|
+
ctx.inject(['workspaceRegistry'], (reg) => {
|
|
430
|
+
Object.defineProperty(host, 'workspaceRegistry', {
|
|
431
|
+
configurable: true,
|
|
432
|
+
get: () => reg.workspaceRegistry ?? ctx.workspaceRegistry,
|
|
433
|
+
});
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
catch {
|
|
437
|
+
// 没有工作区注册表时用进程 cwd。
|
|
438
|
+
}
|
|
439
|
+
try {
|
|
440
|
+
ctx.inject(['webServer', 'webRuntime'], (wctx) => {
|
|
441
|
+
disposeWeb = mountImRoutes(wctx, host, native, tooling);
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
catch (error) {
|
|
445
|
+
ctx.logger?.warn?.(`[dsh-im] web UI not mounted: ${error instanceof Error ? error.message : String(error)}`);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
return () => {
|
|
449
|
+
disposeWeb?.();
|
|
450
|
+
void native.disposeAll();
|
|
451
|
+
};
|
|
452
|
+
}, 'dsh-im web');
|
|
453
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { type MemoryClaimState } from '../core/memory-claims.ts';
|
|
2
|
+
import type { ConsensusState } from '../core/consensus.ts';
|
|
3
|
+
import { type ChatEvent } from '../core/events.ts';
|
|
4
|
+
export declare const MEMORY_INDEX_SCHEMA = 1;
|
|
5
|
+
/** 单群索引条目上限:超过就拒绝构建(不静默截断,避免"可寻址"变成"部分可寻址")。 */
|
|
6
|
+
export declare const INDEX_MAX_ENTRIES = 50000;
|
|
7
|
+
/** 增量条目超过已有条目的这个比例时改为全量重建。 */
|
|
8
|
+
export declare const INDEX_REBUILD_DELTA_RATIO = 0.5;
|
|
9
|
+
/** 兼容旧引用:指令性语句正则现在定义在 core(客户端也要用)。 */
|
|
10
|
+
export declare const INDEX_IMPERATIVE: RegExp;
|
|
11
|
+
export interface MemoryIndexEntry {
|
|
12
|
+
seq: number;
|
|
13
|
+
at: number;
|
|
14
|
+
actorName: string;
|
|
15
|
+
actorId?: string;
|
|
16
|
+
/** 话题段号 = 该段首条用户消息的 seq(0 = 尚无用户消息)。 */
|
|
17
|
+
topicId: number;
|
|
18
|
+
claim: MemoryClaimState;
|
|
19
|
+
successorSeq?: number;
|
|
20
|
+
/** 正文指纹(正文不复制;展开时回 events.jsonl 取)。 */
|
|
21
|
+
textHash: string;
|
|
22
|
+
textLen: number;
|
|
23
|
+
untrusted: boolean;
|
|
24
|
+
imperative: boolean;
|
|
25
|
+
}
|
|
26
|
+
export interface MemoryIndexCursor {
|
|
27
|
+
lastSeq: number;
|
|
28
|
+
lastTopicId: number;
|
|
29
|
+
sourceSize: number;
|
|
30
|
+
builtAt: number;
|
|
31
|
+
rebuilds: number;
|
|
32
|
+
dirtySeqs: number[];
|
|
33
|
+
}
|
|
34
|
+
export interface MemoryIndex {
|
|
35
|
+
schema: number;
|
|
36
|
+
threadId: string;
|
|
37
|
+
entries: MemoryIndexEntry[];
|
|
38
|
+
cursor: MemoryIndexCursor;
|
|
39
|
+
stats: {
|
|
40
|
+
messages: number;
|
|
41
|
+
topics: number;
|
|
42
|
+
active: number;
|
|
43
|
+
superseded: number;
|
|
44
|
+
raw: number;
|
|
45
|
+
untrusted: number;
|
|
46
|
+
imperative: number;
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
export declare function memoryIndexPath(root: string, threadId: string): string;
|
|
50
|
+
export declare function loadMemoryIndex(root: string, threadId: string): Promise<MemoryIndex | null>;
|
|
51
|
+
export interface BuildIndexOptions {
|
|
52
|
+
force?: boolean;
|
|
53
|
+
consensus?: ConsensusState;
|
|
54
|
+
now?: number;
|
|
55
|
+
/** 是否落盘(默认 true;诊断预览传 false)。 */
|
|
56
|
+
persist?: boolean;
|
|
57
|
+
}
|
|
58
|
+
export interface BuildIndexResult {
|
|
59
|
+
index: MemoryIndex;
|
|
60
|
+
rebuilt: boolean;
|
|
61
|
+
reason: string;
|
|
62
|
+
}
|
|
63
|
+
export declare function buildMemoryIndex(root: string, threadId: string, options?: BuildIndexOptions): Promise<BuildIndexResult>;
|
|
64
|
+
/** 按 seq 取回原文(expand 路径)。正文只从 events.jsonl 取,索引不复制正文。 */
|
|
65
|
+
export declare function resolveMemoryMessages(root: string, threadId: string, seqs: readonly number[]): Promise<Map<number, ChatEvent>>;
|