dsh-brain/lib/memory/departments-tools.js

165 lines
9.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { renderJson } from "./tools.js";
function snippet(text, limit = 600) {
return text.length <= limit ? text : text.slice(0, limit) + '…';
}
function inDepartmentWorkspace(deps, exec, job) {
return deps.memory().withWorkspace(deps.workspace(exec), job);
}
function requireEnabled(deps) {
const settings = deps.settings();
if (settings.memoryEnabled === false || settings.localMemoryEnabled === false) {
throw new Error('部门功能当前已禁用。请在 /dsh-brain 页面开启本地记忆和记忆功能后再试。');
}
}
function list(value) {
if (!Array.isArray(value))
return undefined;
return value.filter((item) => typeof item === 'string').slice(0, 50);
}
function text(value) { return typeof value === 'string' ? value : undefined; }
function revision(value) { return typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : undefined; }
export function createDepartmentTools(deps) {
const department_create = {
name: 'department_create',
description: '创建一个部门工作身份。部门拥有私有记忆空间;同名同 scope 幂等返回已有部门,不覆盖。',
parameters: {
type: 'object',
properties: {
name: { type: 'string', description: '部门名称(必填)' },
role: { type: 'string', description: '部门角色说明(可选,最多 12000 字符)' },
scope: { type: 'string', enum: ['global', 'project'], description: '部门空间范围,默认 project' },
skills: { type: 'array', items: { type: 'string' }, description: '关联技能名列表' },
allowedTools: { type: 'array', items: { type: 'string' }, description: '允许使用的工具名列表' },
readGlobal: { type: 'boolean', description: '是否允许读取全局记忆,默认 true' },
readProject: { type: 'boolean', description: '是否允许读取项目记忆,默认 true' },
},
required: ['name'],
additionalProperties: false,
},
output: { schema: { type: 'object' }, render: renderJson },
async execute(args, exec) {
requireEnabled(deps);
return inDepartmentWorkspace(deps, exec, async () => {
const name = text(args.name)?.trim() ?? '';
if (name === '')
throw new Error('部门名称不能为空。');
const input = { name, ...(text(args.role) === undefined ? {} : { role: text(args.role) }), ...(args.scope === 'global' || args.scope === 'project' ? { scope: args.scope } : {}), ...(list(args.skills) === undefined ? {} : { skills: list(args.skills) }), ...(list(args.allowedTools) === undefined ? {} : { allowedTools: list(args.allowedTools) }), ...(typeof args.readGlobal === 'boolean' ? { readGlobal: args.readGlobal } : {}), ...(typeof args.readProject === 'boolean' ? { readProject: args.readProject } : {}) };
const result = await deps.departments().create(input);
return { id: result.department.id, name: result.department.name, scope: result.department.scope, created: result.created };
});
},
};
const department_list = {
name: 'department_list',
description: '列出部门及其精简状态;role 全文不返回,按需使用部门详情接口。',
parameters: { type: 'object', properties: { scope: { type: 'string', enum: ['global', 'project'] } }, additionalProperties: false },
output: { schema: { type: 'object' }, render: renderJson },
async execute(args, exec) {
requireEnabled(deps);
return inDepartmentWorkspace(deps, exec, async () => {
const scope = args.scope === 'global' || args.scope === 'project' ? args.scope : undefined;
const rows = await deps.departments().list(scope);
return { departments: rows.map((department) => ({ id: department.id, name: department.name, scope: department.scope, active: department.active, ...(department.currentTask === undefined ? {} : { currentTask: department.currentTask }), revision: department.revision })) };
});
},
};
const department_remember = {
name: 'department_remember',
description: '向一个部门的私有记忆空间写入记忆。秘密、令牌和密钥不得写入。',
parameters: {
type: 'object',
properties: { departmentId: { type: 'string' }, content: { type: 'string' }, category: { type: 'string' }, tags: { type: 'array', items: { type: 'string' } } },
required: ['departmentId', 'content'],
additionalProperties: false,
},
output: { schema: { type: 'object' }, render: renderJson },
async execute(args, exec) {
requireEnabled(deps);
return inDepartmentWorkspace(deps, exec, async () => {
const id = text(args.departmentId)?.trim() ?? '';
const content = text(args.content)?.trim() ?? '';
if (id === '')
throw new Error('departmentId 不能为空。');
if (content === '')
throw new Error('content 不能为空。');
const result = await deps.departments().remember(id, { content, ...(text(args.category) === undefined ? {} : { category: text(args.category) }), ...(list(args.tags) === undefined ? {} : { tags: list(args.tags) }) });
return { id: result.record.id, duplicate: result.duplicate };
});
},
};
const department_recall = {
name: 'department_recall',
description: '从部门私有空间召回相关记忆,最多 5 条;返回内容为去敏后的短片段。',
parameters: {
type: 'object',
properties: { departmentId: { type: 'string' }, query: { type: 'string' }, k: { type: 'integer', minimum: 1, maximum: 5 } },
required: ['departmentId', 'query'],
additionalProperties: false,
},
output: { schema: { type: 'object' }, render: renderJson },
async execute(args, exec) {
requireEnabled(deps);
const ws = deps.workspace(exec);
return deps.memory().withWorkspace(ws, async () => {
const id = text(args.departmentId)?.trim() ?? '';
const query = text(args.query)?.trim() ?? '';
if (id === '')
throw new Error('departmentId 不能为空。');
if (query === '')
throw new Error('query 不能为空。');
const requested = revision(args.k) ?? 5;
const k = Math.max(1, Math.min(5, requested));
const hits = await deps.departments().recall(id, query, k, ws);
return { hits: hits.map((hit) => ({ id: hit.record.id, origin: hit.origin, content: snippet(hit.record.content) })) };
});
},
};
const department_checkpoint = {
name: 'department_checkpoint',
description: '更新部门当前任务或交接说明,并返回新 revision。',
parameters: {
type: 'object',
properties: { departmentId: { type: 'string' }, currentTask: { type: 'string' }, handoff: { type: 'string' }, expectedRevision: { type: 'integer' } },
required: ['departmentId'],
additionalProperties: false,
},
output: { schema: { type: 'object' }, render: renderJson },
async execute(args, exec) {
requireEnabled(deps);
return inDepartmentWorkspace(deps, exec, async () => {
const id = text(args.departmentId)?.trim() ?? '';
if (id === '')
throw new Error('departmentId 不能为空。');
const department = await deps.departments().checkpoint(id, { ...(text(args.currentTask) === undefined ? {} : { currentTask: text(args.currentTask) }), ...(text(args.handoff) === undefined ? {} : { handoff: text(args.handoff) }) }, revision(args.expectedRevision));
return { revision: department.revision, updatedAt: department.updatedAt };
});
},
};
const department_resume = {
name: 'department_resume',
description: '获取部门可复用会话引用;传入 hostSessionId 时显式绑定宿主会话。',
parameters: {
type: 'object',
properties: { departmentId: { type: 'string' }, host: { type: 'string' }, hostSessionId: { type: 'string' } },
required: ['departmentId'],
additionalProperties: false,
},
output: { schema: { type: 'object' }, render: renderJson },
async execute(args, exec) {
requireEnabled(deps);
return inDepartmentWorkspace(deps, exec, async () => {
const id = text(args.departmentId)?.trim() ?? '';
if (id === '')
throw new Error('departmentId 不能为空。');
const host = text(args.host)?.trim() || 'dsh';
const hostSessionId = text(args.hostSessionId)?.trim();
const sessionRef = hostSessionId !== undefined && hostSessionId !== ''
? await deps.departments().attachSession(id, host, hostSessionId)
: await deps.departments().resumeSession(id, host);
return { sessionRef };
});
},
};
return [department_create, department_list, department_remember, department_recall, department_checkpoint, department_resume];
}