refactor(memory): extract the memory bundle behind MemoryRemoteFactory
This commit is contained in:
parent
0412095635
commit
e1035358ab
|
|
@ -0,0 +1,47 @@
|
|||
/**
|
||||
* Cloud-sync bundle — the remote side of the memory feature.
|
||||
*
|
||||
* This module owns the concrete transport: one cloud client per connection,
|
||||
* with the package settings sidecar as the fallback for any field the
|
||||
* connection left empty. The memory bundle consumes the `MemoryRemote`
|
||||
* contract and never sees this file — the composition root injects the
|
||||
* factory, so swapping the transport never touches the tools or the
|
||||
* Mnemon provider.
|
||||
*/
|
||||
import { CloudClient } from "./api.js";
|
||||
import { SettingsStore } from "./store.js";
|
||||
/** Build a factory over live settings closures (the composition root's path). */
|
||||
export function createCloudMemoryRemoteFactory(deps) {
|
||||
let shared;
|
||||
return {
|
||||
current: () => {
|
||||
shared ??= new CloudClient({
|
||||
baseUrl: () => deps.settings().baseUrl,
|
||||
token: () => deps.memoryToken(),
|
||||
timeoutMs: () => deps.settings().requestTimeoutMs,
|
||||
});
|
||||
return shared;
|
||||
},
|
||||
forConnection: (connection) => new CloudClient({
|
||||
baseUrl: () => connection.endpoint ?? deps.settings().baseUrl,
|
||||
token: () => connection.token ?? deps.memoryToken(),
|
||||
timeoutMs: () => connection.timeoutMs ?? deps.settings().requestTimeoutMs,
|
||||
}),
|
||||
};
|
||||
}
|
||||
/**
|
||||
* The standalone Mnemon-provider path: the same factory, backed lazily by
|
||||
* the settings sidecar so a provider constructed before any configuration
|
||||
* still resolves against live settings at call time.
|
||||
*/
|
||||
export function createSidecarMemoryRemoteFactory() {
|
||||
let store;
|
||||
const ensure = () => {
|
||||
store ??= new SettingsStore({});
|
||||
return store;
|
||||
};
|
||||
return createCloudMemoryRemoteFactory({
|
||||
settings: () => ensure().settings(),
|
||||
memoryToken: () => ensure().memoryToken(),
|
||||
});
|
||||
}
|
||||
11
lib/index.js
11
lib/index.js
|
|
@ -20,7 +20,9 @@ import { SkillGroupManager, detectSources } from "./skill-groups.js";
|
|||
import { ClaudePluginMarketplaceProvider, MarketService } from "./market.js";
|
||||
import { SkillUpdater } from "./skill-update.js";
|
||||
import { ClientRegistry } from "./clients.js";
|
||||
import { createMemoryTools, createSkillTools } from "./tools.js";
|
||||
import { createCloudMemoryRemoteFactory } from "./cloudsync.js";
|
||||
import { createMemoryTools } from "./memory/tools.js";
|
||||
import { createSkillTools } from "./tools.js";
|
||||
/** Package name; also the client bundle id. */
|
||||
export const name = 'dsh-brain';
|
||||
/** Services required before `apply` runs. */
|
||||
|
|
@ -42,6 +44,12 @@ export function apply(ctx, config) {
|
|||
token: () => store.memoryToken(),
|
||||
timeoutMs: () => settings().requestTimeoutMs,
|
||||
});
|
||||
// The memory bundle sees the cloud through this factory only: the concrete
|
||||
// client stays a cloud-sync concern, injected here at the composition root.
|
||||
const memoryRemoteFactory = createCloudMemoryRemoteFactory({
|
||||
settings: () => settings(),
|
||||
memoryToken: () => store.memoryToken(),
|
||||
});
|
||||
const reporter = new Reporter({
|
||||
client,
|
||||
settings: () => ({ enabled: settings().enabled, clientId: settings().clientId }),
|
||||
|
|
@ -125,6 +133,7 @@ export function apply(ctx, config) {
|
|||
if (tools === undefined)
|
||||
return;
|
||||
const toolDeps = {
|
||||
remote: () => memoryRemoteFactory.current(),
|
||||
client: () => client,
|
||||
memoryToken: () => store.memoryToken(),
|
||||
settings: () => ({ enabled: settings().enabled, defaultK: settings().defaultK }),
|
||||
|
|
|
|||
|
|
@ -0,0 +1 @@
|
|||
export {};
|
||||
|
|
@ -0,0 +1,259 @@
|
|||
/**
|
||||
* Agent-facing memory tools — the memory bundle's tool face.
|
||||
*
|
||||
* Bundle rule: the remote is injected via MemoryRemoteFactory; this module
|
||||
* imports neither the concrete cloud client nor the settings sidecar.
|
||||
*
|
||||
* 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`. A missing token is a normal, explainable failure — never a
|
||||
* crash in the host.
|
||||
*/
|
||||
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,
|
||||
};
|
||||
}
|
||||
/** 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 页面开启后再试。');
|
||||
}
|
||||
const token = deps.memoryToken();
|
||||
if (token === '') {
|
||||
throw new Error('未配置记忆令牌。请在 /dsh-brain 页面填入 mem_… 或 cmt_… 记忆令牌(需要 memory:read / memory:write 权限)。');
|
||||
}
|
||||
return token;
|
||||
}
|
||||
/** Search stored memories by keyword. */
|
||||
function searchTool(deps) {
|
||||
return {
|
||||
name: 'memory_search',
|
||||
description: '在云端长期记忆库中按关键词检索历史记忆片段。返回命中的记忆 id、内容摘要、标签与所属项目;' +
|
||||
'需要更多正文时用 memory_read 按 id 取全文。纯关键词匹配,不会做语义相似度检索。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: { type: 'string', description: '检索关键词或短语(必填)。' },
|
||||
k: { type: 'integer', description: '最多返回条数,默认取配置值(1..1000)。' },
|
||||
project_id: { type: 'string', description: '可选:只在这些项目 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) {
|
||||
requireMemoryToken(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 = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined;
|
||||
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: '按 id 读取一条云端记忆的完整内容(正文、标签、项目、修订号与时间戳)。id 可先用 memory_search 或 memory_list 获得。',
|
||||
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) {
|
||||
requireMemoryToken(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: '向云端长期记忆库写入一条新记忆。content 上限 7000 字节,适合存结论、决策、待办与可复用事实;' +
|
||||
'不要写入密钥、令牌或完整源码。写入用 operation_id 保证幂等,重复调用不会产生重复条目。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
content: { type: 'string', description: '要长期保存的正文(≤7000 字节)。' },
|
||||
tags: { type: 'array', items: { type: 'string' }, description: '可选标签,最多 30 个,每个不超过 100 字符。' },
|
||||
project_id: { type: 'string', description: '可选:归属项目 id(≤128 字符)。' },
|
||||
sector: { type: 'string', enum: [...SECTORS], description: '可选:记忆分类(semantic/episodic/procedural/emotional/reflective)。' },
|
||||
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) {
|
||||
requireMemoryToken(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 = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined;
|
||||
const sector = typeof args.sector === 'string' && SECTORS.includes(args.sector) ? args.sector : undefined;
|
||||
const candidate = typeof args.operation_id === 'string' ? args.operation_id.trim() : '';
|
||||
const operationId = /^[0-9a-f-]{36}$/i.test(candidate) ? candidate : randomUUID();
|
||||
const result = await deps.remote().add({ content, tags, project, sector, operationId });
|
||||
if (!result.ok) {
|
||||
if (result.error.status === 409 && result.error.code === 'storage_not_configured') {
|
||||
throw new Error('云端主存储尚未配置(WebDAV),服务端拒绝写入。请先在云端设置里完成存储配置。');
|
||||
}
|
||||
throw new Error(`写入失败:${describeError(result.error)}`);
|
||||
}
|
||||
return {
|
||||
id: result.data.id,
|
||||
revision: result.data.revision,
|
||||
remote_saved: result.data.remote_saved,
|
||||
state: result.data.state,
|
||||
operation_id: result.data.operation_id ?? operationId,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
/** List recent memories. */
|
||||
function listTool(deps) {
|
||||
return {
|
||||
name: 'memory_list',
|
||||
description: '按时间倒序列出云端记忆(可分页,可按项目过滤)。适合浏览最近保存了什么,再决定是否 memory_read 取全文。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
limit: { type: 'integer', description: '返回条数,默认 20,上限 100。' },
|
||||
offset: { type: 'integer', description: '跳过条数,默认 0。' },
|
||||
project_id: { type: 'string', description: '可选:只看某个项目。' },
|
||||
},
|
||||
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) {
|
||||
requireMemoryToken(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 = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined;
|
||||
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: '列出云端账号下的记忆项目(project_id 与名称),用于给 memory_add 选择归属项目。',
|
||||
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() {
|
||||
requireMemoryToken(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)];
|
||||
}
|
||||
|
|
@ -10,16 +10,15 @@
|
|||
* Connection resolution, per call:
|
||||
* 1. the Mnemon connection for the space (service fields configured on
|
||||
* the Mnemon page, plus the space's own `projectId`),
|
||||
* 2. this package's own settings sidecar (`$DSH_HOME/dsh-brain.json`)
|
||||
* for any of endpoint/token the Mnemon side left empty — so a user
|
||||
* who already configured dsh-brain configures nothing twice.
|
||||
* 2. the injected `MemoryRemoteFactory` (cloud-sync bundle), which fills
|
||||
* any endpoint/token the Mnemon side left empty from this package's
|
||||
* settings sidecar — so a user who already configured dsh-brain
|
||||
* configures nothing twice.
|
||||
*
|
||||
* A Memory Space maps to one LongMemory project; the empty project is the
|
||||
* account-wide default scope.
|
||||
*/
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { CloudClient } from "../api.js";
|
||||
import { SettingsStore } from "../store.js";
|
||||
import { descriptor } from "./descriptor.js";
|
||||
/** Epoch (ms, or seconds on older payloads) → ISO string, when plausible. */
|
||||
function toIso(value) {
|
||||
|
|
@ -55,23 +54,19 @@ export function insightFromHit(hit) {
|
|||
export class LongMemoryProvider {
|
||||
authority;
|
||||
options;
|
||||
remoteFactory;
|
||||
id = descriptor.id;
|
||||
/** LongMemory scores are its own scale; the host may only order by them. */
|
||||
scoreSemantics = { kind: 'provider-native' };
|
||||
store;
|
||||
constructor(authority, options = {}) {
|
||||
constructor(authority, options, remoteFactory) {
|
||||
this.authority = authority;
|
||||
this.options = options;
|
||||
}
|
||||
/** This package's settings sidecar, read lazily so edits apply live. */
|
||||
settings() {
|
||||
this.store ??= new SettingsStore({});
|
||||
return this.store;
|
||||
this.remoteFactory = remoteFactory;
|
||||
}
|
||||
/**
|
||||
* Merge the space's Mnemon connection over the package settings.
|
||||
* The authority is the source of merged service+space values; the space
|
||||
* record itself is the fallback for older hosts.
|
||||
* Merge the space's Mnemon connection fields (authority first, the space
|
||||
* record as fallback for older hosts). Fields left empty stay empty on
|
||||
* purpose: the injected factory owns the package-settings fallback.
|
||||
*/
|
||||
resolve(body, direct) {
|
||||
let connection = { ...(direct ?? {}) };
|
||||
|
|
@ -89,25 +84,22 @@ export class LongMemoryProvider {
|
|||
connection = { ...own, ...connection };
|
||||
}
|
||||
}
|
||||
const settings = this.settings().settings();
|
||||
const endpointRaw = typeof connection.endpoint === 'string' && connection.endpoint !== ''
|
||||
? connection.endpoint
|
||||
: settings.baseUrl;
|
||||
const token = typeof connection.token === 'string' && connection.token !== ''
|
||||
? connection.token
|
||||
: this.settings().memoryToken();
|
||||
const project = typeof connection.projectId === 'string' && connection.projectId !== ''
|
||||
? connection.projectId
|
||||
const endpoint = typeof connection.endpoint === 'string' && connection.endpoint !== ''
|
||||
? connection.endpoint.replace(/\/+$/, '')
|
||||
: undefined;
|
||||
return { endpoint: endpointRaw.replace(/\/+$/, ''), header: token, ...(project === undefined ? {} : { project }) };
|
||||
const token = typeof connection.token === 'string' && connection.token !== '' ? connection.token : undefined;
|
||||
const projectId = typeof connection.projectId === 'string' && connection.projectId !== '' ? connection.projectId : undefined;
|
||||
const timeoutMs = this.options.requestTimeoutMs;
|
||||
return {
|
||||
...(endpoint === undefined ? {} : { endpoint }),
|
||||
...(token === undefined ? {} : { token }),
|
||||
...(projectId === undefined ? {} : { projectId }),
|
||||
...(timeoutMs === undefined ? {} : { timeoutMs }),
|
||||
};
|
||||
}
|
||||
/** A client bound to one resolved connection (clients here are cheap). */
|
||||
client(resolved) {
|
||||
return new CloudClient({
|
||||
baseUrl: () => resolved.endpoint,
|
||||
token: () => resolved.header,
|
||||
timeoutMs: () => this.options.requestTimeoutMs ?? this.settings().settings().requestTimeoutMs,
|
||||
});
|
||||
/** A remote bound to one resolved connection; the factory owns fallbacks. */
|
||||
client(connection) {
|
||||
return this.remoteFactory.forConnection(connection);
|
||||
}
|
||||
/** Enumerate the account's projects as Memory Spaces, plus the default scope. */
|
||||
async discover(connection, signal) {
|
||||
|
|
@ -139,9 +131,8 @@ export class LongMemoryProvider {
|
|||
async status(body, signal) {
|
||||
signal?.throwIfAborted();
|
||||
const resolved = this.resolve(body);
|
||||
if (resolved.header === '') {
|
||||
return { healthy: false, error: 'LongMemory memory token is not configured' };
|
||||
}
|
||||
// No local token short-circuit: the factory owns the sidecar fallback, so
|
||||
// only the live call can tell whether a token is configured anywhere.
|
||||
const result = await this.client(resolved).storageStatus();
|
||||
return result.ok
|
||||
? { healthy: true }
|
||||
|
|
@ -152,7 +143,7 @@ export class LongMemoryProvider {
|
|||
signal?.throwIfAborted();
|
||||
const resolved = this.resolve(body);
|
||||
const limit = Math.min(Math.max(request.limit ?? 10, 1), 100);
|
||||
const result = await this.client(resolved).search(request.query, limit, resolved.project);
|
||||
const result = await this.client(resolved).search(request.query, limit, resolved.projectId);
|
||||
if (!result.ok) {
|
||||
throw new Error(`LongMemory search failed: ${result.error.message}`);
|
||||
}
|
||||
|
|
@ -171,7 +162,7 @@ export class LongMemoryProvider {
|
|||
}
|
||||
const resolved = this.resolve(body);
|
||||
const limit = Math.min(Math.max(request.limit ?? 100, 1), 200);
|
||||
const result = await this.client(resolved).list({ limit, project: resolved.project });
|
||||
const result = await this.client(resolved).list({ limit, project: resolved.projectId });
|
||||
if (!result.ok) {
|
||||
throw new Error(`LongMemory list failed: ${result.error.message}`);
|
||||
}
|
||||
|
|
@ -186,7 +177,7 @@ export class LongMemoryProvider {
|
|||
const result = await this.client(resolved).add({
|
||||
content: request.content,
|
||||
...(request.tags === undefined ? {} : { tags: request.tags }),
|
||||
...(resolved.project === undefined ? {} : { project: resolved.project }),
|
||||
...(resolved.projectId === undefined ? {} : { project: resolved.projectId }),
|
||||
...(request.category === undefined ? {} : { sector: request.category }),
|
||||
operationId: `mnemon-${randomUUID()}`,
|
||||
});
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@
|
|||
import { MEMORY_SPACE_PROVIDER_API_VERSION, defineMemorySpaceProvider, defineMemorySpaceProviderDefinition, } from 'dsh-mnemon-source-memory-spaces/provider-sdk';
|
||||
import { descriptor } from "./descriptor.js";
|
||||
import { LongMemoryProvider } from "./driver.js";
|
||||
import { createSidecarMemoryRemoteFactory } from "../cloudsync.js";
|
||||
export { LongMemoryProvider, descriptor };
|
||||
/** Keep in sync with the package version (asserted by the verify script). */
|
||||
const PROVIDER_VERSION = '0.9.8';
|
||||
|
|
@ -36,7 +37,7 @@ export const definition = defineMemorySpaceProviderDefinition({
|
|||
secrets: descriptor.fields.filter((field) => field.input === 'secret').map((field) => field.key),
|
||||
scoreSemantics: 'provider-native',
|
||||
},
|
||||
create: (context) => new LongMemoryProvider(context.memorySpaces ?? context.memoryBodies, { requestTimeoutMs: context.config.timeoutMs }),
|
||||
create: (context) => new LongMemoryProvider(context.memorySpaces ?? context.memoryBodies, { requestTimeoutMs: context.config.timeoutMs }, createSidecarMemoryRemoteFactory()),
|
||||
});
|
||||
export default defineMemorySpaceProvider({
|
||||
id: descriptor.id,
|
||||
|
|
|
|||
256
lib/tools.js
256
lib/tools.js
|
|
@ -1,259 +1,5 @@
|
|||
/**
|
||||
* Agent-facing memory tools.
|
||||
*
|
||||
* 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`. A missing token is a normal, explainable failure — never a
|
||||
* crash in the host.
|
||||
*/
|
||||
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,
|
||||
};
|
||||
}
|
||||
/** Render any tool value as one JSON text block. */
|
||||
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. */
|
||||
function requireMemoryToken(deps) {
|
||||
if (!deps.settings().enabled) {
|
||||
throw new Error('云端记忆插件当前已禁用(enabled=false)。请在 /dsh-brain 页面开启后再试。');
|
||||
}
|
||||
const token = deps.memoryToken();
|
||||
if (token === '') {
|
||||
throw new Error('未配置记忆令牌。请在 /dsh-brain 页面填入 mem_… 或 cmt_… 记忆令牌(需要 memory:read / memory:write 权限)。');
|
||||
}
|
||||
return token;
|
||||
}
|
||||
/** Search stored memories by keyword. */
|
||||
function searchTool(deps) {
|
||||
return {
|
||||
name: 'memory_search',
|
||||
description: '在云端长期记忆库中按关键词检索历史记忆片段。返回命中的记忆 id、内容摘要、标签与所属项目;' +
|
||||
'需要更多正文时用 memory_read 按 id 取全文。纯关键词匹配,不会做语义相似度检索。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: { type: 'string', description: '检索关键词或短语(必填)。' },
|
||||
k: { type: 'integer', description: '最多返回条数,默认取配置值(1..1000)。' },
|
||||
project_id: { type: 'string', description: '可选:只在这些项目 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) {
|
||||
requireMemoryToken(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 = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined;
|
||||
const result = await deps.client().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: '按 id 读取一条云端记忆的完整内容(正文、标签、项目、修订号与时间戳)。id 可先用 memory_search 或 memory_list 获得。',
|
||||
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) {
|
||||
requireMemoryToken(deps);
|
||||
const id = typeof args.id === 'string' ? args.id.trim() : '';
|
||||
if (id === '')
|
||||
throw new Error('id 不能为空。');
|
||||
const result = await deps.client().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: '向云端长期记忆库写入一条新记忆。content 上限 7000 字节,适合存结论、决策、待办与可复用事实;' +
|
||||
'不要写入密钥、令牌或完整源码。写入用 operation_id 保证幂等,重复调用不会产生重复条目。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
content: { type: 'string', description: '要长期保存的正文(≤7000 字节)。' },
|
||||
tags: { type: 'array', items: { type: 'string' }, description: '可选标签,最多 30 个,每个不超过 100 字符。' },
|
||||
project_id: { type: 'string', description: '可选:归属项目 id(≤128 字符)。' },
|
||||
sector: { type: 'string', enum: [...SECTORS], description: '可选:记忆分类(semantic/episodic/procedural/emotional/reflective)。' },
|
||||
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) {
|
||||
requireMemoryToken(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 = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined;
|
||||
const sector = typeof args.sector === 'string' && SECTORS.includes(args.sector) ? args.sector : undefined;
|
||||
const candidate = typeof args.operation_id === 'string' ? args.operation_id.trim() : '';
|
||||
const operationId = /^[0-9a-f-]{36}$/i.test(candidate) ? candidate : randomUUID();
|
||||
const result = await deps.client().add({ content, tags, project, sector, operationId });
|
||||
if (!result.ok) {
|
||||
if (result.error.status === 409 && result.error.code === 'storage_not_configured') {
|
||||
throw new Error('云端主存储尚未配置(WebDAV),服务端拒绝写入。请先在云端设置里完成存储配置。');
|
||||
}
|
||||
throw new Error(`写入失败:${describeError(result.error)}`);
|
||||
}
|
||||
return {
|
||||
id: result.data.id,
|
||||
revision: result.data.revision,
|
||||
remote_saved: result.data.remote_saved,
|
||||
state: result.data.state,
|
||||
operation_id: result.data.operation_id ?? operationId,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
/** List recent memories. */
|
||||
function listTool(deps) {
|
||||
return {
|
||||
name: 'memory_list',
|
||||
description: '按时间倒序列出云端记忆(可分页,可按项目过滤)。适合浏览最近保存了什么,再决定是否 memory_read 取全文。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
limit: { type: 'integer', description: '返回条数,默认 20,上限 100。' },
|
||||
offset: { type: 'integer', description: '跳过条数,默认 0。' },
|
||||
project_id: { type: 'string', description: '可选:只看某个项目。' },
|
||||
},
|
||||
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) {
|
||||
requireMemoryToken(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 = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined;
|
||||
const result = await deps.client().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: '列出云端账号下的记忆项目(project_id 与名称),用于给 memory_add 选择归属项目。',
|
||||
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() {
|
||||
requireMemoryToken(deps);
|
||||
const result = await deps.client().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)];
|
||||
}
|
||||
import { renderJson, requireMemoryToken } from "./memory/tools.js";
|
||||
/** List the cloud skill center inventory (skills sync keeps local copies current). */
|
||||
function skillListTool(deps) {
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,57 @@
|
|||
/**
|
||||
* Cloud-sync bundle — the remote side of the memory feature.
|
||||
*
|
||||
* This module owns the concrete transport: one cloud client per connection,
|
||||
* with the package settings sidecar as the fallback for any field the
|
||||
* connection left empty. The memory bundle consumes the `MemoryRemote`
|
||||
* contract and never sees this file — the composition root injects the
|
||||
* factory, so swapping the transport never touches the tools or the
|
||||
* Mnemon provider.
|
||||
*/
|
||||
import { CloudClient } from './api.ts'
|
||||
import type { MemoryConnection, MemoryRemote, MemoryRemoteFactory } from './memory/remote.ts'
|
||||
import { SettingsStore } from './store.ts'
|
||||
|
||||
/** What the factory needs from the live settings. */
|
||||
export interface CloudMemoryRemoteDeps {
|
||||
settings: () => { baseUrl: string; requestTimeoutMs: number }
|
||||
memoryToken: () => string
|
||||
}
|
||||
|
||||
/** Build a factory over live settings closures (the composition root's path). */
|
||||
export function createCloudMemoryRemoteFactory(deps: CloudMemoryRemoteDeps): MemoryRemoteFactory {
|
||||
let shared: CloudClient | undefined
|
||||
return {
|
||||
current: () => {
|
||||
shared ??= new CloudClient({
|
||||
baseUrl: () => deps.settings().baseUrl,
|
||||
token: () => deps.memoryToken(),
|
||||
timeoutMs: () => deps.settings().requestTimeoutMs,
|
||||
})
|
||||
return shared
|
||||
},
|
||||
forConnection: (connection: MemoryConnection): MemoryRemote =>
|
||||
new CloudClient({
|
||||
baseUrl: () => connection.endpoint ?? deps.settings().baseUrl,
|
||||
token: () => connection.token ?? deps.memoryToken(),
|
||||
timeoutMs: () => connection.timeoutMs ?? deps.settings().requestTimeoutMs,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The standalone Mnemon-provider path: the same factory, backed lazily by
|
||||
* the settings sidecar so a provider constructed before any configuration
|
||||
* still resolves against live settings at call time.
|
||||
*/
|
||||
export function createSidecarMemoryRemoteFactory(): MemoryRemoteFactory {
|
||||
let store: SettingsStore | undefined
|
||||
const ensure = () => {
|
||||
store ??= new SettingsStore({})
|
||||
return store
|
||||
}
|
||||
return createCloudMemoryRemoteFactory({
|
||||
settings: () => ensure().settings(),
|
||||
memoryToken: () => ensure().memoryToken(),
|
||||
})
|
||||
}
|
||||
12
src/index.ts
12
src/index.ts
|
|
@ -21,7 +21,9 @@ import { SkillGroupManager, detectSources } from './skill-groups.ts'
|
|||
import { ClaudePluginMarketplaceProvider, MarketService } from './market.ts'
|
||||
import { SkillUpdater } from './skill-update.ts'
|
||||
import { ClientRegistry } from './clients.ts'
|
||||
import { createMemoryTools, createSkillTools } from './tools.ts'
|
||||
import { createCloudMemoryRemoteFactory } from './cloudsync.ts'
|
||||
import { createMemoryTools } from './memory/tools.ts'
|
||||
import { createSkillTools } from './tools.ts'
|
||||
|
||||
/** Package name; also the client bundle id. */
|
||||
export const name = 'dsh-brain'
|
||||
|
|
@ -51,6 +53,13 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
|
|||
timeoutMs: () => settings().requestTimeoutMs,
|
||||
})
|
||||
|
||||
// The memory bundle sees the cloud through this factory only: the concrete
|
||||
// client stays a cloud-sync concern, injected here at the composition root.
|
||||
const memoryRemoteFactory = createCloudMemoryRemoteFactory({
|
||||
settings: () => settings(),
|
||||
memoryToken: () => store.memoryToken(),
|
||||
})
|
||||
|
||||
const reporter = new Reporter({
|
||||
client,
|
||||
settings: () => ({ enabled: settings().enabled, clientId: settings().clientId }),
|
||||
|
|
@ -145,6 +154,7 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
|
|||
const tools = (toolsCtx as CloudMemoryContext).tools
|
||||
if (tools === undefined) return
|
||||
const toolDeps = {
|
||||
remote: () => memoryRemoteFactory.current(),
|
||||
client: () => client,
|
||||
memoryToken: () => store.memoryToken(),
|
||||
settings: () => ({ enabled: settings().enabled, defaultK: settings().defaultK }),
|
||||
|
|
|
|||
|
|
@ -0,0 +1,47 @@
|
|||
/**
|
||||
* Memory bundle — remote contracts.
|
||||
*
|
||||
* The memory tools and the Mnemon provider talk to the LongMemory service
|
||||
* through this narrow face only. The cloud-sync side implements it with
|
||||
* its concrete client (src/cloudsync.ts); the composition root injects one
|
||||
* factory, so the memory bundle never imports that client or the settings
|
||||
* sidecar.
|
||||
*/
|
||||
import type {
|
||||
AddResponse,
|
||||
CloudResult,
|
||||
ListResponse,
|
||||
MemoryHit,
|
||||
ProjectsResponse,
|
||||
SearchResponse,
|
||||
} from '../api.ts'
|
||||
|
||||
/** One live connection: everything a remote call needs. */
|
||||
export interface MemoryConnection {
|
||||
/** LongMemory base URL; empty falls back to the package settings. */
|
||||
endpoint?: string
|
||||
/** Scoped memory token; empty falls back to the package settings. */
|
||||
token?: string
|
||||
/** LongMemory project scope, or the account-wide default. */
|
||||
projectId?: string
|
||||
/** Per-request timeout override. */
|
||||
timeoutMs?: number
|
||||
}
|
||||
|
||||
/** The remote surface the memory bundle consumes (a client subset). */
|
||||
export interface MemoryRemote {
|
||||
search(query: string, k: number, project?: string): Promise<CloudResult<SearchResponse>>
|
||||
read(id: string): Promise<CloudResult<MemoryHit>>
|
||||
add(input: { content: string; tags?: string[]; project?: string; sector?: string; operationId: string }): Promise<CloudResult<AddResponse>>
|
||||
list(options?: { limit?: number; offset?: number; project?: string }): Promise<CloudResult<ListResponse>>
|
||||
projects(): Promise<CloudResult<ProjectsResponse>>
|
||||
storageStatus(): Promise<CloudResult<Record<string, unknown>>>
|
||||
}
|
||||
|
||||
/** How the composition root hands remotes to the memory bundle. */
|
||||
export interface MemoryRemoteFactory {
|
||||
/** The remote bound to the package's own settings. */
|
||||
current(): MemoryRemote
|
||||
/** A remote for one Mnemon-style connection, falling back to settings. */
|
||||
forConnection(connection: MemoryConnection): MemoryRemote
|
||||
}
|
||||
|
|
@ -0,0 +1,283 @@
|
|||
/**
|
||||
* Agent-facing memory tools — the memory bundle's tool face.
|
||||
*
|
||||
* Bundle rule: the remote is injected via MemoryRemoteFactory; this module
|
||||
* imports neither the concrete cloud client nor the settings sidecar.
|
||||
*
|
||||
* 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`. A missing token is a normal, explainable failure — never a
|
||||
* crash in the host.
|
||||
*/
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import type { MemoryHit } from '../api.ts'
|
||||
import { describeError } from '../api.ts'
|
||||
import type { ToolDefinitionLike } from '../context-types.ts'
|
||||
import type { MemoryRemote } from './remote.ts'
|
||||
|
||||
/** Everything the tools need from the plugin core. */
|
||||
export interface MemoryToolDeps {
|
||||
/** The memory remote, injected by the composition root. */
|
||||
remote: () => MemoryRemote
|
||||
/** Memory token, or empty when unconfigured. */
|
||||
memoryToken: () => string
|
||||
/** Effective settings. */
|
||||
settings: () => { enabled: boolean; defaultK: number }
|
||||
}
|
||||
|
||||
/** Text block shape the harness renders. */
|
||||
interface TextBlock {
|
||||
type: 'text'
|
||||
text: string
|
||||
}
|
||||
|
||||
/** Sectors the service accepts for `metadata.primary_sector`. */
|
||||
export const SECTORS = ['semantic', 'episodic', 'procedural', 'emotional', 'reflective'] as const
|
||||
|
||||
/** Trim a memory body down to a display-sized snippet. */
|
||||
function snippet(text: string | undefined, limit = 600): string {
|
||||
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: MemoryHit): Record<string, unknown> {
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
/** Render any tool value as one JSON text block. */
|
||||
export function renderJson(_args: unknown, value: unknown): TextBlock[] {
|
||||
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: { memoryToken: () => string; settings: () => { enabled: boolean } }): string {
|
||||
if (!deps.settings().enabled) {
|
||||
throw new Error('云端记忆插件当前已禁用(enabled=false)。请在 /dsh-brain 页面开启后再试。')
|
||||
}
|
||||
const token = deps.memoryToken()
|
||||
if (token === '') {
|
||||
throw new Error('未配置记忆令牌。请在 /dsh-brain 页面填入 mem_… 或 cmt_… 记忆令牌(需要 memory:read / memory:write 权限)。')
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
/** Search stored memories by keyword. */
|
||||
function searchTool(deps: MemoryToolDeps): ToolDefinitionLike {
|
||||
return {
|
||||
name: 'memory_search',
|
||||
description:
|
||||
'在云端长期记忆库中按关键词检索历史记忆片段。返回命中的记忆 id、内容摘要、标签与所属项目;' +
|
||||
'需要更多正文时用 memory_read 按 id 取全文。纯关键词匹配,不会做语义相似度检索。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: { type: 'string', description: '检索关键词或短语(必填)。' },
|
||||
k: { type: 'integer', description: '最多返回条数,默认取配置值(1..1000)。' },
|
||||
project_id: { type: 'string', description: '可选:只在这些项目 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: Record<string, unknown>): Promise<unknown> {
|
||||
requireMemoryToken(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 = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined
|
||||
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: MemoryToolDeps): ToolDefinitionLike {
|
||||
return {
|
||||
name: 'memory_read',
|
||||
description: '按 id 读取一条云端记忆的完整内容(正文、标签、项目、修订号与时间戳)。id 可先用 memory_search 或 memory_list 获得。',
|
||||
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: Record<string, unknown>): Promise<unknown> {
|
||||
requireMemoryToken(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: MemoryToolDeps): ToolDefinitionLike {
|
||||
return {
|
||||
name: 'memory_add',
|
||||
description:
|
||||
'向云端长期记忆库写入一条新记忆。content 上限 7000 字节,适合存结论、决策、待办与可复用事实;' +
|
||||
'不要写入密钥、令牌或完整源码。写入用 operation_id 保证幂等,重复调用不会产生重复条目。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
content: { type: 'string', description: '要长期保存的正文(≤7000 字节)。' },
|
||||
tags: { type: 'array', items: { type: 'string' }, description: '可选标签,最多 30 个,每个不超过 100 字符。' },
|
||||
project_id: { type: 'string', description: '可选:归属项目 id(≤128 字符)。' },
|
||||
sector: { type: 'string', enum: [...SECTORS], description: '可选:记忆分类(semantic/episodic/procedural/emotional/reflective)。' },
|
||||
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: Record<string, unknown>): Promise<unknown> {
|
||||
requireMemoryToken(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): tag is string => typeof tag === 'string' && tag !== '').slice(0, 30)
|
||||
const project = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined
|
||||
const sector = typeof args.sector === 'string' && (SECTORS as readonly string[]).includes(args.sector) ? args.sector : undefined
|
||||
const candidate = typeof args.operation_id === 'string' ? args.operation_id.trim() : ''
|
||||
const operationId = /^[0-9a-f-]{36}$/i.test(candidate) ? candidate : randomUUID()
|
||||
const result = await deps.remote().add({ content, tags, project, sector, operationId })
|
||||
if (!result.ok) {
|
||||
if (result.error.status === 409 && result.error.code === 'storage_not_configured') {
|
||||
throw new Error('云端主存储尚未配置(WebDAV),服务端拒绝写入。请先在云端设置里完成存储配置。')
|
||||
}
|
||||
throw new Error(`写入失败:${describeError(result.error)}`)
|
||||
}
|
||||
return {
|
||||
id: result.data.id,
|
||||
revision: result.data.revision,
|
||||
remote_saved: result.data.remote_saved,
|
||||
state: result.data.state,
|
||||
operation_id: result.data.operation_id ?? operationId,
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** List recent memories. */
|
||||
function listTool(deps: MemoryToolDeps): ToolDefinitionLike {
|
||||
return {
|
||||
name: 'memory_list',
|
||||
description: '按时间倒序列出云端记忆(可分页,可按项目过滤)。适合浏览最近保存了什么,再决定是否 memory_read 取全文。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
limit: { type: 'integer', description: '返回条数,默认 20,上限 100。' },
|
||||
offset: { type: 'integer', description: '跳过条数,默认 0。' },
|
||||
project_id: { type: 'string', description: '可选:只看某个项目。' },
|
||||
},
|
||||
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: Record<string, unknown>): Promise<unknown> {
|
||||
requireMemoryToken(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 = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined
|
||||
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: MemoryToolDeps): ToolDefinitionLike {
|
||||
return {
|
||||
name: 'memory_projects',
|
||||
description: '列出云端账号下的记忆项目(project_id 与名称),用于给 memory_add 选择归属项目。',
|
||||
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(): Promise<unknown> {
|
||||
requireMemoryToken(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: MemoryToolDeps): ToolDefinitionLike[] {
|
||||
return [searchTool(deps), readTool(deps), addTool(deps), listTool(deps), projectsTool(deps)]
|
||||
}
|
||||
|
||||
|
|
@ -10,9 +10,10 @@
|
|||
* Connection resolution, per call:
|
||||
* 1. the Mnemon connection for the space (service fields configured on
|
||||
* the Mnemon page, plus the space's own `projectId`),
|
||||
* 2. this package's own settings sidecar (`$DSH_HOME/dsh-brain.json`)
|
||||
* for any of endpoint/token the Mnemon side left empty — so a user
|
||||
* who already configured dsh-brain configures nothing twice.
|
||||
* 2. the injected `MemoryRemoteFactory` (cloud-sync bundle), which fills
|
||||
* any endpoint/token the Mnemon side left empty from this package's
|
||||
* settings sidecar — so a user who already configured dsh-brain
|
||||
* configures nothing twice.
|
||||
*
|
||||
* A Memory Space maps to one LongMemory project; the empty project is the
|
||||
* account-wide default scope.
|
||||
|
|
@ -33,8 +34,8 @@ import type {
|
|||
RememberRequest,
|
||||
SearchRequest,
|
||||
} from 'dsh-mnemon-source-memory-spaces/provider-sdk'
|
||||
import { CloudClient, type MemoryHit } from '../api.ts'
|
||||
import { SettingsStore } from '../store.ts'
|
||||
import type { MemoryHit } from '../api.ts'
|
||||
import type { MemoryConnection, MemoryRemote, MemoryRemoteFactory } from '../memory/remote.ts'
|
||||
import { descriptor } from './descriptor.ts'
|
||||
|
||||
/** Options handed over by the provider factory. */
|
||||
|
|
@ -43,13 +44,6 @@ export interface LongMemoryProviderOptions {
|
|||
requestTimeoutMs?: number
|
||||
}
|
||||
|
||||
/** One fully-resolved connection: everything a call needs. */
|
||||
interface ResolvedConnection {
|
||||
endpoint: string
|
||||
header: string
|
||||
project?: string
|
||||
}
|
||||
|
||||
/** Epoch (ms, or seconds on older payloads) → ISO string, when plausible. */
|
||||
function toIso(value: unknown): string | undefined {
|
||||
if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return undefined
|
||||
|
|
@ -82,25 +76,18 @@ export class LongMemoryProvider implements MemoryProviderAdapter {
|
|||
/** LongMemory scores are its own scale; the host may only order by them. */
|
||||
readonly scoreSemantics = { kind: 'provider-native' } as const
|
||||
|
||||
private store: SettingsStore | undefined
|
||||
|
||||
constructor(
|
||||
private readonly authority: MemorySpaceAuthority | undefined,
|
||||
private readonly options: LongMemoryProviderOptions = {},
|
||||
private readonly options: LongMemoryProviderOptions,
|
||||
private readonly remoteFactory: MemoryRemoteFactory,
|
||||
) {}
|
||||
|
||||
/** This package's settings sidecar, read lazily so edits apply live. */
|
||||
private settings(): SettingsStore {
|
||||
this.store ??= new SettingsStore({})
|
||||
return this.store
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge the space's Mnemon connection over the package settings.
|
||||
* The authority is the source of merged service+space values; the space
|
||||
* record itself is the fallback for older hosts.
|
||||
* Merge the space's Mnemon connection fields (authority first, the space
|
||||
* record as fallback for older hosts). Fields left empty stay empty on
|
||||
* purpose: the injected factory owns the package-settings fallback.
|
||||
*/
|
||||
private resolve(body?: MemorySpace, direct?: MemoryProviderConnection): ResolvedConnection {
|
||||
private resolve(body?: MemorySpace, direct?: MemoryProviderConnection): MemoryConnection {
|
||||
let connection: MemoryProviderConnection = { ...(direct ?? {}) }
|
||||
if (body !== undefined) {
|
||||
if (this.authority !== undefined) {
|
||||
|
|
@ -115,26 +102,23 @@ export class LongMemoryProvider implements MemoryProviderAdapter {
|
|||
connection = { ...(own as MemoryProviderConnection), ...connection }
|
||||
}
|
||||
}
|
||||
const settings = this.settings().settings()
|
||||
const endpointRaw = typeof connection.endpoint === 'string' && connection.endpoint !== ''
|
||||
? connection.endpoint
|
||||
: settings.baseUrl
|
||||
const token = typeof connection.token === 'string' && connection.token !== ''
|
||||
? connection.token
|
||||
: this.settings().memoryToken()
|
||||
const project = typeof connection.projectId === 'string' && connection.projectId !== ''
|
||||
? connection.projectId
|
||||
const endpoint = typeof connection.endpoint === 'string' && connection.endpoint !== ''
|
||||
? connection.endpoint.replace(/\/+$/, '')
|
||||
: undefined
|
||||
return { endpoint: endpointRaw.replace(/\/+$/, ''), header: token, ...(project === undefined ? {} : { project }) }
|
||||
const token = typeof connection.token === 'string' && connection.token !== '' ? connection.token : undefined
|
||||
const projectId = typeof connection.projectId === 'string' && connection.projectId !== '' ? connection.projectId : undefined
|
||||
const timeoutMs = this.options.requestTimeoutMs
|
||||
return {
|
||||
...(endpoint === undefined ? {} : { endpoint }),
|
||||
...(token === undefined ? {} : { token }),
|
||||
...(projectId === undefined ? {} : { projectId }),
|
||||
...(timeoutMs === undefined ? {} : { timeoutMs }),
|
||||
}
|
||||
}
|
||||
|
||||
/** A client bound to one resolved connection (clients here are cheap). */
|
||||
private client(resolved: ResolvedConnection): CloudClient {
|
||||
return new CloudClient({
|
||||
baseUrl: () => resolved.endpoint,
|
||||
token: () => resolved.header,
|
||||
timeoutMs: () => this.options.requestTimeoutMs ?? this.settings().settings().requestTimeoutMs,
|
||||
})
|
||||
/** A remote bound to one resolved connection; the factory owns fallbacks. */
|
||||
private client(connection: MemoryConnection): MemoryRemote {
|
||||
return this.remoteFactory.forConnection(connection)
|
||||
}
|
||||
|
||||
/** Enumerate the account's projects as Memory Spaces, plus the default scope. */
|
||||
|
|
@ -167,9 +151,8 @@ export class LongMemoryProvider implements MemoryProviderAdapter {
|
|||
async status(body: MemorySpace, signal?: AbortSignal): Promise<ProviderSpaceStatus> {
|
||||
signal?.throwIfAborted()
|
||||
const resolved = this.resolve(body)
|
||||
if (resolved.header === '') {
|
||||
return { healthy: false, error: 'LongMemory memory token is not configured' }
|
||||
}
|
||||
// No local token short-circuit: the factory owns the sidecar fallback, so
|
||||
// only the live call can tell whether a token is configured anywhere.
|
||||
const result = await this.client(resolved).storageStatus()
|
||||
return result.ok
|
||||
? { healthy: true }
|
||||
|
|
@ -181,7 +164,7 @@ export class LongMemoryProvider implements MemoryProviderAdapter {
|
|||
signal?.throwIfAborted()
|
||||
const resolved = this.resolve(body)
|
||||
const limit = Math.min(Math.max(request.limit ?? 10, 1), 100)
|
||||
const result = await this.client(resolved).search(request.query, limit, resolved.project)
|
||||
const result = await this.client(resolved).search(request.query, limit, resolved.projectId)
|
||||
if (!result.ok) {
|
||||
throw new Error(`LongMemory search failed: ${result.error.message}`)
|
||||
}
|
||||
|
|
@ -201,7 +184,7 @@ export class LongMemoryProvider implements MemoryProviderAdapter {
|
|||
}
|
||||
const resolved = this.resolve(body)
|
||||
const limit = Math.min(Math.max(request.limit ?? 100, 1), 200)
|
||||
const result = await this.client(resolved).list({ limit, project: resolved.project })
|
||||
const result = await this.client(resolved).list({ limit, project: resolved.projectId })
|
||||
if (!result.ok) {
|
||||
throw new Error(`LongMemory list failed: ${result.error.message}`)
|
||||
}
|
||||
|
|
@ -217,7 +200,7 @@ export class LongMemoryProvider implements MemoryProviderAdapter {
|
|||
const result = await this.client(resolved).add({
|
||||
content: request.content,
|
||||
...(request.tags === undefined ? {} : { tags: request.tags }),
|
||||
...(resolved.project === undefined ? {} : { project: resolved.project }),
|
||||
...(resolved.projectId === undefined ? {} : { project: resolved.projectId }),
|
||||
...(request.category === undefined ? {} : { sector: request.category }),
|
||||
operationId: `mnemon-${randomUUID()}`,
|
||||
})
|
||||
|
|
@ -252,4 +235,4 @@ export class LongMemoryProvider implements MemoryProviderAdapter {
|
|||
void body
|
||||
return { nodes: [], edges: [], generatedAt: new Date().toISOString() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -19,6 +19,7 @@ import {
|
|||
} from 'dsh-mnemon-source-memory-spaces/provider-sdk'
|
||||
import { descriptor } from './descriptor.ts'
|
||||
import { LongMemoryProvider } from './driver.ts'
|
||||
import { createSidecarMemoryRemoteFactory } from '../cloudsync.ts'
|
||||
|
||||
export { LongMemoryProvider, descriptor }
|
||||
|
||||
|
|
@ -46,6 +47,7 @@ export const definition = defineMemorySpaceProviderDefinition({
|
|||
create: (context) => new LongMemoryProvider(
|
||||
context.memorySpaces ?? context.memoryBodies,
|
||||
{ requestTimeoutMs: context.config.timeoutMs },
|
||||
createSidecarMemoryRemoteFactory(),
|
||||
),
|
||||
})
|
||||
|
||||
|
|
|
|||
275
src/tools.ts
275
src/tools.ts
|
|
@ -1,5 +1,5 @@
|
|||
/**
|
||||
* Agent-facing memory tools.
|
||||
* Agent-facing skill tools — the skill bundle's tool face.
|
||||
*
|
||||
* These definitions are hand-written `ToolDefinition` objects rather than
|
||||
* `defineTool(...)` calls: `defineTool` only compiles an authoring DSL into the
|
||||
|
|
@ -10,275 +10,28 @@
|
|||
* Failure contract: `execute` throws and the registry turns that into
|
||||
* `isError: true`. A missing token is a normal, explainable failure — never a
|
||||
* crash in the host.
|
||||
*
|
||||
* The cloud skill center rides the memory token (phase-1 credential
|
||||
* semantics), so the token guard and the JSON renderer come from the memory
|
||||
* bundle; swapping that dependency is a later, deliberate step.
|
||||
*/
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import type { CloudClient, MemoryHit } from './api.ts'
|
||||
import type { CloudClient } from './api.ts'
|
||||
import { describeError } from './api.ts'
|
||||
import type { ToolDefinitionLike } from './context-types.ts'
|
||||
import { renderJson, requireMemoryToken } from './memory/tools.ts'
|
||||
|
||||
/** Everything the tools need from the plugin core. */
|
||||
export interface MemoryToolDeps {
|
||||
/** The configured client (rebuilt lazily; settings may change at runtime). */
|
||||
/** Everything the skill tools need from the plugin core. */
|
||||
export interface SkillToolDeps {
|
||||
/** The cloud client (the skill center rides the memory token). */
|
||||
client: () => CloudClient
|
||||
/** Memory token, or empty when unconfigured. */
|
||||
memoryToken: () => string
|
||||
/** Effective settings. */
|
||||
settings: () => { enabled: boolean; defaultK: number }
|
||||
}
|
||||
|
||||
/** Text block shape the harness renders. */
|
||||
interface TextBlock {
|
||||
type: 'text'
|
||||
text: string
|
||||
}
|
||||
|
||||
/** Sectors the service accepts for `metadata.primary_sector`. */
|
||||
export const SECTORS = ['semantic', 'episodic', 'procedural', 'emotional', 'reflective'] as const
|
||||
|
||||
/** Trim a memory body down to a display-sized snippet. */
|
||||
function snippet(text: string | undefined, limit = 600): string {
|
||||
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: MemoryHit): Record<string, unknown> {
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
/** Render any tool value as one JSON text block. */
|
||||
function renderJson(_args: unknown, value: unknown): TextBlock[] {
|
||||
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. */
|
||||
function requireMemoryToken(deps: MemoryToolDeps): string {
|
||||
if (!deps.settings().enabled) {
|
||||
throw new Error('云端记忆插件当前已禁用(enabled=false)。请在 /dsh-brain 页面开启后再试。')
|
||||
}
|
||||
const token = deps.memoryToken()
|
||||
if (token === '') {
|
||||
throw new Error('未配置记忆令牌。请在 /dsh-brain 页面填入 mem_… 或 cmt_… 记忆令牌(需要 memory:read / memory:write 权限)。')
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
/** Search stored memories by keyword. */
|
||||
function searchTool(deps: MemoryToolDeps): ToolDefinitionLike {
|
||||
return {
|
||||
name: 'memory_search',
|
||||
description:
|
||||
'在云端长期记忆库中按关键词检索历史记忆片段。返回命中的记忆 id、内容摘要、标签与所属项目;' +
|
||||
'需要更多正文时用 memory_read 按 id 取全文。纯关键词匹配,不会做语义相似度检索。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: { type: 'string', description: '检索关键词或短语(必填)。' },
|
||||
k: { type: 'integer', description: '最多返回条数,默认取配置值(1..1000)。' },
|
||||
project_id: { type: 'string', description: '可选:只在这些项目 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: Record<string, unknown>): Promise<unknown> {
|
||||
requireMemoryToken(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 = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined
|
||||
const result = await deps.client().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: MemoryToolDeps): ToolDefinitionLike {
|
||||
return {
|
||||
name: 'memory_read',
|
||||
description: '按 id 读取一条云端记忆的完整内容(正文、标签、项目、修订号与时间戳)。id 可先用 memory_search 或 memory_list 获得。',
|
||||
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: Record<string, unknown>): Promise<unknown> {
|
||||
requireMemoryToken(deps)
|
||||
const id = typeof args.id === 'string' ? args.id.trim() : ''
|
||||
if (id === '') throw new Error('id 不能为空。')
|
||||
const result = await deps.client().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: MemoryToolDeps): ToolDefinitionLike {
|
||||
return {
|
||||
name: 'memory_add',
|
||||
description:
|
||||
'向云端长期记忆库写入一条新记忆。content 上限 7000 字节,适合存结论、决策、待办与可复用事实;' +
|
||||
'不要写入密钥、令牌或完整源码。写入用 operation_id 保证幂等,重复调用不会产生重复条目。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
content: { type: 'string', description: '要长期保存的正文(≤7000 字节)。' },
|
||||
tags: { type: 'array', items: { type: 'string' }, description: '可选标签,最多 30 个,每个不超过 100 字符。' },
|
||||
project_id: { type: 'string', description: '可选:归属项目 id(≤128 字符)。' },
|
||||
sector: { type: 'string', enum: [...SECTORS], description: '可选:记忆分类(semantic/episodic/procedural/emotional/reflective)。' },
|
||||
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: Record<string, unknown>): Promise<unknown> {
|
||||
requireMemoryToken(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): tag is string => typeof tag === 'string' && tag !== '').slice(0, 30)
|
||||
const project = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined
|
||||
const sector = typeof args.sector === 'string' && (SECTORS as readonly string[]).includes(args.sector) ? args.sector : undefined
|
||||
const candidate = typeof args.operation_id === 'string' ? args.operation_id.trim() : ''
|
||||
const operationId = /^[0-9a-f-]{36}$/i.test(candidate) ? candidate : randomUUID()
|
||||
const result = await deps.client().add({ content, tags, project, sector, operationId })
|
||||
if (!result.ok) {
|
||||
if (result.error.status === 409 && result.error.code === 'storage_not_configured') {
|
||||
throw new Error('云端主存储尚未配置(WebDAV),服务端拒绝写入。请先在云端设置里完成存储配置。')
|
||||
}
|
||||
throw new Error(`写入失败:${describeError(result.error)}`)
|
||||
}
|
||||
return {
|
||||
id: result.data.id,
|
||||
revision: result.data.revision,
|
||||
remote_saved: result.data.remote_saved,
|
||||
state: result.data.state,
|
||||
operation_id: result.data.operation_id ?? operationId,
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** List recent memories. */
|
||||
function listTool(deps: MemoryToolDeps): ToolDefinitionLike {
|
||||
return {
|
||||
name: 'memory_list',
|
||||
description: '按时间倒序列出云端记忆(可分页,可按项目过滤)。适合浏览最近保存了什么,再决定是否 memory_read 取全文。',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
limit: { type: 'integer', description: '返回条数,默认 20,上限 100。' },
|
||||
offset: { type: 'integer', description: '跳过条数,默认 0。' },
|
||||
project_id: { type: 'string', description: '可选:只看某个项目。' },
|
||||
},
|
||||
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: Record<string, unknown>): Promise<unknown> {
|
||||
requireMemoryToken(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 = typeof args.project_id === 'string' && args.project_id !== '' ? args.project_id : undefined
|
||||
const result = await deps.client().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: MemoryToolDeps): ToolDefinitionLike {
|
||||
return {
|
||||
name: 'memory_projects',
|
||||
description: '列出云端账号下的记忆项目(project_id 与名称),用于给 memory_add 选择归属项目。',
|
||||
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(): Promise<unknown> {
|
||||
requireMemoryToken(deps)
|
||||
const result = await deps.client().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: MemoryToolDeps): ToolDefinitionLike[] {
|
||||
return [searchTool(deps), readTool(deps), addTool(deps), listTool(deps), projectsTool(deps)]
|
||||
settings: () => { enabled: boolean }
|
||||
}
|
||||
|
||||
/** List the cloud skill center inventory (skills sync keeps local copies current). */
|
||||
function skillListTool(deps: MemoryToolDeps): ToolDefinitionLike {
|
||||
function skillListTool(deps: SkillToolDeps): ToolDefinitionLike {
|
||||
return {
|
||||
name: 'skill_list',
|
||||
description: '列出云端技能中心的全部技能(名称、说明、版本)。技能会自动同步到本机技能目录,由 DSH 直接加载;此工具只用于查看云端有哪些技能。',
|
||||
|
|
@ -304,6 +57,6 @@ function skillListTool(deps: MemoryToolDeps): ToolDefinitionLike {
|
|||
}
|
||||
|
||||
/** Build the skill-facing tools for one plugin instance. */
|
||||
export function createSkillTools(deps: MemoryToolDeps): ToolDefinitionLike[] {
|
||||
export function createSkillTools(deps: SkillToolDeps): ToolDefinitionLike[] {
|
||||
return [skillListTool(deps)]
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue