import { tool } from "@opencode-ai/plugin"; import { MemoryStore } from "../../src/memory/store.js"; import { ToolSessionContextStore } from "../../src/session/toolContextStore.js"; const memoryStore = new MemoryStore(); const toolContextStore = new ToolSessionContextStore(); const initializePromise = Promise.all([ memoryStore.initialize(), toolContextStore.initialize(), ]); export default tool({ description: "将长期有效的用户偏好或项目事实写入持久 memory。禁止写入 token、password、secret、system prompt 或一次性上下文。scope 仅允许 'user' 或 'workspace'。", args: { reason: tool.schema .string() .describe("Why this memory should be persisted for future requests."), scope: tool.schema .string() .describe( "Required exact keyword. Use only 'user' for user-level durable preferences/constraints, or 'workspace' for project/environment durable facts. Do not use 'project', Chinese labels, or any alias.", ), content: tool.schema .string() .describe( "The durable fact or preference to remember, written as one concise sentence.", ), }, async execute(args, context) { await initializePromise; const sessionContext = await toolContextStore.read(context.sessionID); if (!sessionContext) { throw new Error(`session context not found for ${context.sessionID}`); } const scope = args.scope === "user" ? "user" : args.scope === "workspace" ? "workspace" : null; if (!scope) { return JSON.stringify({ ok: true, kind: "memory", decision: "rejected", detail: `unsupported scope: ${args.scope}; use exact keyword 'user' or 'workspace'`, }); } const scopeKey = scope === "user" ? sessionContext.actorKey : sessionContext.projectKey; const result = await memoryStore.upsert(scope, scopeKey, { content: args.content, sessionId: context.sessionID, source: "tool", traceId: sessionContext.traceId, }); if (!result.entry) { return JSON.stringify({ ok: true, kind: "memory", decision: "rejected", detail: "content rejected by persistence policy", }); } return JSON.stringify({ ok: true, kind: "memory", decision: result.changed ? "accepted" : "deduped", detail: result.changed ? "memory stored" : "memory already existed", target: scope, }); }, });