dsh-brain/lib/memory/tools.js

275 lines
13 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.

/**
* Agent-facing memory tools — the memory bundle's tool face.
*
* The entry injects a narrow MemoryRemote adapter.
*
* These definitions are hand-written `ToolDefinition` objects rather than
* `defineTool(...)` calls: `defineTool` only compiles an authoring DSL into the
* same raw JSON Schema, and importing `@deepseek-ai/dsh-tools` at runtime would
* risk a second module instance (and a second class identity) inside a linked
* plugin.
*
* Failure contract: `execute` throws and the registry turns that into
* `isError: true`.
*/
import { randomUUID } from 'node:crypto';
import { describeError } from "../api.js";
/** Sectors the service accepts for `metadata.primary_sector`. */
export const SECTORS = ['semantic', 'episodic', 'procedural', 'emotional', 'reflective'];
/** Trim a memory body down to a display-sized snippet. */
function snippet(text, limit = 600) {
if (typeof text !== 'string')
return '';
if (text.length <= limit)
return text;
return `${text.slice(0, limit)}…`;
}
/** Project one hit into the compact shape returned to the model. */
function toHitView(hit) {
return {
id: hit.id,
content: snippet(hit.content),
tags: hit.tags ?? [],
project_id: hit.project_id ?? null,
sector: hit.primary_sector ?? null,
revision: hit.revision ?? null,
created_at: hit.created_at ?? null,
...(typeof hit.category === 'string' ? { category: hit.category } : {}),
...(typeof hit.target === 'string' ? { target: hit.target } : {}),
};
}
/** Render any tool value as one JSON text block. */
export function renderJson(_args, value) {
const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2);
return [{ type: 'text', text }];
}
/** Assert the memory scope is usable, or throw a message the model can act on. */
export function requireMemoryToken(deps) {
if (!deps.settings().enabled) {
throw new Error('记忆插件当前已禁用(enabled=false)。请在 /dsh-brain 页面开启后再试。');
}
// Local-first mode needs no credential and wins unless cloud mode was
// explicitly selected and configured. If local memory is off, only a
// configured cloud credential may select the cloud adapter.
if (deps.localMemory?.() === true)
return '';
const token = deps.memoryToken();
if (token !== '')
return token;
throw new Error('记忆功能未启用或未配置令牌。请在 /dsh-brain 页面开启本地记忆,或填入 mem_… / cmt_… 记忆令牌。');
}
function requireMemoryEnabled(deps) {
if (!deps.settings().enabled)
throw new Error('记忆工具当前已禁用。请在 /dsh-brain 页面开启后再试。');
}
function projectId(value) {
if (value === undefined)
return undefined;
if (typeof value !== 'string' || value.trim() === '')
throw new Error('project_id 必须是 memory_projects 返回的工作区 ID。');
return value.trim();
}
/** Search stored memories by keyword. */
function searchTool(deps) {
return {
name: 'memory_search',
description: '按关键词检索 Mnemon 记忆。默认检索全局 Runtime,指定 project_id 时检索对应 DSH 工作区的记忆空间。' +
'需要全文时用 memory_read 读取返回的 id。',
parameters: {
type: 'object',
properties: {
query: { type: 'string', description: '检索关键词或短语(必填)。' },
k: { type: 'integer', description: '最多返回条数,默认取配置值(1..1000)。' },
project_id: { type: 'string', description: '可选:memory_projects 返回的 DSH 工作区 ID。省略时检索全局。' },
},
required: ['query'],
additionalProperties: false,
},
output: {
schema: {
type: 'object',
properties: {
query: { type: 'string' },
total: { type: 'number' },
search_mode: { type: 'string' },
matches: { type: 'array', items: { type: 'object' } },
},
required: ['query', 'matches'],
additionalProperties: true,
},
render: renderJson,
},
async execute(args) {
requireMemoryEnabled(deps);
const query = typeof args.query === 'string' ? args.query.trim() : '';
if (query === '')
throw new Error('query 不能为空。');
const requested = typeof args.k === 'number' && Number.isFinite(args.k) ? Math.trunc(args.k) : deps.settings().defaultK;
const k = Math.min(1000, Math.max(1, requested));
const project = projectId(args.project_id);
const result = await deps.remote().search(query, k, project);
if (!result.ok)
throw new Error(`检索失败:${describeError(result.error)}`);
const matches = result.data.matches;
return {
query,
total: result.data.total ?? matches.length,
search_mode: result.data.search_mode ?? 'keyword',
matches: matches.map(toHitView),
};
},
};
}
/** Read one memory by id. */
function readTool(deps) {
return {
name: 'memory_read',
description: '按 memory_search、memory_list 或 memory_add 返回的 id 读取 Mnemon 条目全文及其可用元数据。',
parameters: {
type: 'object',
properties: {
id: { type: 'string', description: '记忆条目 id(必填)。' },
},
required: ['id'],
additionalProperties: false,
},
output: {
schema: { type: 'object', properties: { id: { type: 'string' }, content: { type: 'string' } }, required: ['id'], additionalProperties: true },
render: renderJson,
},
async execute(args) {
requireMemoryEnabled(deps);
const id = typeof args.id === 'string' ? args.id.trim() : '';
if (id === '')
throw new Error('id 不能为空。');
const result = await deps.remote().read(id);
if (!result.ok) {
if (result.error.status === 404)
throw new Error(`没有找到 id=${id} 的记忆(可能已删除)。`);
throw new Error(`读取失败:${describeError(result.error)}`);
}
return result.data;
},
};
}
/** Store one new memory. */
function addTool(deps) {
return {
name: 'memory_add',
description: '追加一条 Mnemon 记忆。默认写入全局 Runtime,指定 project_id 时写入对应 DSH 工作区的记忆空间。正文上限 7000 字节。' +
'不要保存密钥、令牌或完整源码。重试同一次写入请复用 operation_id。',
parameters: {
type: 'object',
properties: {
content: { type: 'string', description: '要长期保存的正文(≤7000 字节)。' },
tags: { type: 'array', items: { type: 'string' }, description: '项目条目可选标签,最多 30 个。全局 Runtime 不支持标签。' },
project_id: { type: 'string', description: '可选:memory_projects 返回的 DSH 工作区 ID。省略时写入全局。' },
sector: { type: 'string', enum: [...SECTORS], description: '项目条目可选分类。全局 Runtime 不支持分类。' },
operation_id: { type: 'string', description: '可选:幂等键(uuid);省略时自动生成。重试同一次写入时请复用同一个值。' },
},
required: ['content'],
additionalProperties: false,
},
output: {
schema: {
type: 'object',
properties: {
id: { type: 'string' },
revision: { type: 'number' },
remote_saved: { type: 'boolean' },
state: { type: 'string' },
operation_id: { type: 'string' },
},
required: ['id'],
additionalProperties: true,
},
render: renderJson,
},
async execute(args) {
requireMemoryEnabled(deps);
const content = typeof args.content === 'string' ? args.content : '';
if (content.trim() === '')
throw new Error('content 不能为空。');
const bytes = Buffer.byteLength(content, 'utf8');
if (bytes > 7000)
throw new Error(`content 过大:${bytes} 字节,上限 7000 字节。`);
const rawTags = Array.isArray(args.tags) ? args.tags : [];
const tags = rawTags.filter((tag) => typeof tag === 'string' && tag !== '').slice(0, 30);
const project = projectId(args.project_id);
const sector = typeof args.sector === 'string' && SECTORS.includes(args.sector) ? args.sector : undefined;
const candidate = typeof args.operation_id === 'string' ? args.operation_id.trim() : '';
if (args.operation_id !== undefined && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(candidate)) {
throw new Error('operation_id 必须是 UUID。');
}
const operationId = candidate.toLowerCase() || randomUUID();
const result = await deps.remote().add({ content, tags, project, sector, operationId });
if (!result.ok) {
throw new Error(`写入失败(operation_id=${operationId}):${describeError(result.error)}`);
}
return {
id: result.data.id,
...(result.data.revision === undefined ? {} : { revision: result.data.revision }),
...(result.data.remote_saved === undefined ? {} : { remote_saved: result.data.remote_saved }),
...(result.data.state === undefined ? {} : { state: result.data.state }),
operation_id: result.data.operation_id ?? operationId,
};
},
};
}
/** List recent memories. */
function listTool(deps) {
return {
name: 'memory_list',
description: '按时间倒序列出 Mnemon 记忆。省略 project_id 时列出全局 Runtime 条目。',
parameters: {
type: 'object',
properties: {
limit: { type: 'integer', description: '返回条数,默认 20,上限 100。' },
offset: { type: 'integer', description: '跳过条数,默认 0。' },
project_id: { type: 'string', description: '可选:memory_projects 返回的 DSH 工作区 ID。' },
},
additionalProperties: false,
},
output: {
schema: { type: 'object', properties: { total: { type: 'number' }, items: { type: 'array', items: { type: 'object' } } }, required: ['items'], additionalProperties: true },
render: renderJson,
},
async execute(args) {
requireMemoryEnabled(deps);
const rawLimit = typeof args.limit === 'number' && Number.isFinite(args.limit) ? Math.trunc(args.limit) : 20;
const limit = Math.min(100, Math.max(1, rawLimit));
const rawOffset = typeof args.offset === 'number' && Number.isFinite(args.offset) ? Math.trunc(args.offset) : 0;
const offset = Math.max(0, rawOffset);
const project = projectId(args.project_id);
const result = await deps.remote().list({ limit, offset, project });
if (!result.ok)
throw new Error(`列表读取失败:${describeError(result.error)}`);
const items = result.data.items;
return { total: result.data.total ?? items.length, items: items.map(toHitView) };
},
};
}
/** List projects known to the account. */
function projectsTool(deps) {
return {
name: 'memory_projects',
description: '列出 DSH 注册的工作区 ID 和名称。将返回的 id 用作其他记忆工具的 project_id。',
parameters: { type: 'object', properties: {}, additionalProperties: false },
output: {
schema: { type: 'object', properties: { projects: { type: 'array', items: { type: 'object' } } }, required: ['projects'], additionalProperties: true },
render: renderJson,
},
async execute(_args) {
requireMemoryEnabled(deps);
const result = await deps.remote().projects();
if (!result.ok)
throw new Error(`项目列表读取失败:${describeError(result.error)}`);
return { projects: result.data.projects };
},
};
}
/** Build every memory tool for one plugin instance. */
export function createMemoryTools(deps) {
return [searchTool(deps), readTool(deps), addTool(deps), listTool(deps), projectsTool(deps)];
}