whale-memory-core 0.15.0 → 0.18.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -0
- package/bin/whale-memory-mcp.mjs +276 -0
- package/demo.mjs +44 -33
- package/index.d.ts +16 -15
- package/index.js +18 -17
- package/lib/archive.d.ts +22 -22
- package/lib/archive.js +171 -135
- package/lib/as-of.d.ts +5 -5
- package/lib/as-of.js +32 -32
- package/lib/book.d.ts +4 -4
- package/lib/book.js +75 -75
- package/lib/chapter-events.d.ts +39 -39
- package/lib/chapter-events.js +89 -89
- package/lib/detail-recall.d.ts +15 -0
- package/lib/detail-recall.js +174 -0
- package/lib/event-log.d.ts +10 -10
- package/lib/event-log.js +61 -61
- package/lib/evidence-from-experience.d.ts +8 -8
- package/lib/evidence-from-experience.js +62 -62
- package/lib/evidence-policy.js +2 -2
- package/lib/fact-timeline-contract.d.ts +73 -0
- package/lib/fact-timeline-contract.js +226 -0
- package/lib/fact-timeline-query.d.ts +29 -0
- package/lib/fact-timeline-query.js +97 -0
- package/lib/file-lock.js +1 -1
- package/lib/later-events.d.ts +21 -21
- package/lib/later-events.js +80 -80
- package/lib/link-events.d.ts +15 -15
- package/lib/link-events.js +33 -33
- package/lib/query-match.js +55 -0
- package/lib/recall-events.d.ts +24 -24
- package/lib/recall-events.js +97 -97
- package/lib/recap.d.ts +23 -23
- package/lib/recap.js +79 -79
- package/lib/seal-events.d.ts +25 -25
- package/lib/seal-events.js +82 -82
- package/lib/self-experience.d.ts +180 -175
- package/lib/self-experience.js +624 -560
- package/lib/self-memory.js +70 -68
- package/lib/self-prompt.js +8 -4
- package/lib/self-settings.js +2 -2
- package/lib/unfinished-events.d.ts +26 -26
- package/lib/unfinished-events.js +105 -105
- package/lib/unsaid.d.ts +28 -28
- package/lib/unsaid.js +105 -105
- package/lib/waking.d.ts +1 -1
- package/lib/waking.js +99 -92
- package/package.json +127 -113
package/README.md
CHANGED
|
@@ -39,6 +39,20 @@ npm install whale-memory-core
|
|
|
39
39
|
|
|
40
40
|
已发布在 npm:`whale-memory-core`([npmjs.com](https://www.npmjs.com/package/whale-memory-core),最新版本以 npm 为准)。也可以从仓库本地安装:`npm install ./packages/core`。
|
|
41
41
|
|
|
42
|
+
> 包名带 `-core`。npm 上不带 `-core` 的 `whale-memory` 是别人的包,和本项目无关,别装错。
|
|
43
|
+
|
|
44
|
+
从零开始接一个角色,看 [30 分钟教程](https://github.com/firefly1office/whale-memory/blob/main/docs/tutorial.md)。
|
|
45
|
+
|
|
46
|
+
## 当 MCP 服务用
|
|
47
|
+
|
|
48
|
+
包里带一个 MCP 服务(stdio、只在本机、零依赖),接到 Claude Desktop、Claude Code、Cursor 等客户端:
|
|
49
|
+
|
|
50
|
+
```sh
|
|
51
|
+
npx -y -p whale-memory-core whale-memory-mcp --data /path/to/data
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
抽屉默认不开(`--owner true` 才开),`--readonly true` 只给读的工具。工具表与配置写法见仓库里的 [adapters/mcp/README.md](https://github.com/firefly1office/whale-memory/blob/main/adapters/mcp/README.md)。
|
|
55
|
+
|
|
42
56
|
## 运行示例
|
|
43
57
|
|
|
44
58
|
```bash
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// whale-memory 的 MCP 适配器:stdio 传输,只在本机跑,不开端口、不联网。
|
|
3
|
+
//
|
|
4
|
+
// whale-memory-mcp --data <数据根目录> [--owner true] [--readonly true]
|
|
5
|
+
//
|
|
6
|
+
// 数据根目录下面有 plugin-data/(和 CLI 的 --data 一样);不给就用 WHALE_DATA_DIR,再不给用 ./data。
|
|
7
|
+
//
|
|
8
|
+
// 守住的边界和 CLI 一样:
|
|
9
|
+
// - then 不可改:写下的只能追加后记(revise),不能改原文
|
|
10
|
+
// - 没有记录就说没有:召回不到就返回空,不编
|
|
11
|
+
// - 封存不外露:recall / book / recap 都不带封存的;read 点名 id 才给(带封存标记)
|
|
12
|
+
// - 没说出口的抽屉默认不开:只有 --owner true(你自己在本机打开它)才出现,按 local:owner 处理
|
|
13
|
+
// - 不提供导入、导出、删除、改提示词、改设置:这些高风险操作留在 CLI 里由人来做
|
|
14
|
+
//
|
|
15
|
+
// 协议:JSON-RPC 2.0,一行一条消息(MCP stdio 传输)。stdout 只写协议消息,日志写 stderr。
|
|
16
|
+
import fs from 'node:fs'
|
|
17
|
+
import path from 'node:path'
|
|
18
|
+
import readline from 'node:readline'
|
|
19
|
+
import { fileURLToPath } from 'node:url'
|
|
20
|
+
import * as exp from '../lib/self-experience.js'
|
|
21
|
+
import { recallDetail } from '../lib/detail-recall.js'
|
|
22
|
+
import * as waking from '../lib/waking.js'
|
|
23
|
+
import * as chapterEvents from '../lib/chapter-events.js'
|
|
24
|
+
import * as recapLib from '../lib/recap.js'
|
|
25
|
+
import * as book from '../lib/book.js'
|
|
26
|
+
import * as unsaid from '../lib/unsaid.js'
|
|
27
|
+
import { parseAsOf } from '../lib/as-of.js'
|
|
28
|
+
|
|
29
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
|
30
|
+
const VERSION = (() => { try { return JSON.parse(fs.readFileSync(path.join(HERE, '..', 'package.json'), 'utf8')).version } catch { return '0.0.0' } })()
|
|
31
|
+
const PROTOCOLS = ['2025-06-18', '2025-03-26', '2024-11-05']
|
|
32
|
+
const OWNER_KEY = 'local:owner'
|
|
33
|
+
|
|
34
|
+
export function parseArgs(argv) {
|
|
35
|
+
const get = (k) => { const i = argv.indexOf('--' + k); if (i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--')) return argv[i + 1]; const eq = argv.find((a) => a.startsWith('--' + k + '=')); return eq ? eq.slice(k.length + 3) : '' }
|
|
36
|
+
const data = path.resolve(get('data') || process.env.WHALE_DATA_DIR || path.join(process.cwd(), 'data'))
|
|
37
|
+
const lang = (get('lang') || process.env.WHALE_LANG || (/^zh/i.test(String(process.env.LC_ALL || process.env.LANG || Intl.DateTimeFormat().resolvedOptions().locale || '')) ? 'zh' : 'en')) === 'zh' ? 'zh' : 'en'
|
|
38
|
+
return { data, mem: path.join(data, 'plugin-data', 'biomimetic-memory'), owner: get('owner') === 'true', readonly: get('readonly') === 'true', lang }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// ── 工具 ────────────────────────────────────────────────────────────────
|
|
42
|
+
const S = (props, required = []) => ({ type: 'object', properties: props, required, additionalProperties: false })
|
|
43
|
+
const str = (description) => ({ type: 'string', description })
|
|
44
|
+
const num = (description) => ({ type: 'number', description })
|
|
45
|
+
const strs = (description) => ({ type: 'array', items: { type: 'string' }, description })
|
|
46
|
+
const ASOF = str('可选:翻回那天的自己,比如 2026-11-15(只看那天及以前写下的、想过的)')
|
|
47
|
+
const READ = { readOnlyHint: true, destructiveHint: false, openWorldHint: false }
|
|
48
|
+
const WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }
|
|
49
|
+
|
|
50
|
+
const limitOf = (v, d, max = 50) => { const n = v === undefined ? d : Number(v); if (!Number.isInteger(n) || n < 0) throw new Error('limit must be a non-negative integer(limit 要是非负整数)'); return Math.min(n, max) }
|
|
51
|
+
const list = (v) => (Array.isArray(v) ? v.map(String).map((s) => s.trim()).filter(Boolean) : typeof v === 'string' ? v.split(',').map((s) => s.trim()).filter(Boolean) : [])
|
|
52
|
+
const need = (v, name) => { if (typeof v !== 'string' || !v.trim()) throw new Error('Missing ' + name + ' (it cannot be blank)(缺少 ' + name + '(不能是空白))'); return v }
|
|
53
|
+
const feelingNow = (r) => { const l = [...(r.later || [])].reverse().find((x) => Array.isArray(x.feeling) && x.feeling.length); return l ? l.feeling : [] }
|
|
54
|
+
|
|
55
|
+
export function buildTools(cfg) {
|
|
56
|
+
const M = cfg.mem
|
|
57
|
+
const tools = [
|
|
58
|
+
{
|
|
59
|
+
name: 'memory_detail', title: '回想一件事的细节', annotations: READ,
|
|
60
|
+
description: 'Look up a detail in visible experiences. Only supported supplies a value. Related gives excerpts to check, ambiguous gives alternatives, unmatched means this search found nothing.(查经历的细节,只有 supported 提供值。related 给原文待核对,ambiguous 有多条可能,unmatched 表示本次没查到。)',
|
|
61
|
+
inputSchema: S({ query: str('完整问题,保留人物、时间和否定'), asOf: ASOF }, ['query']),
|
|
62
|
+
run: (a) => recallDetail(M, a.query, { asOf: a.asOf || null })
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
name: 'memory_recall', title: '想起', annotations: READ,
|
|
66
|
+
description: 'Recall your own experiences related to this. If nothing is found, an empty list comes back: none means none, do not make anything up. Sealed experiences are never recalled. Empty query = the latest few.(从自己的经历里想起和这件事有关的。召回不到就返回空列表——没有就是没有,不要编。封存了的不会被想起。空 query = 最近几条。)',
|
|
67
|
+
inputSchema: S({ query: str('想找什么,一句话'), limit: num('最多几条,默认 3'), mode: { type: 'string', enum: ['strict', 'loose'], description: 'strict(默认)宁可不召回;loose 放宽一点' }, asOf: ASOF }),
|
|
68
|
+
run: (a) => {
|
|
69
|
+
const mode = a.mode || 'strict'
|
|
70
|
+
if (mode !== 'strict' && mode !== 'loose') throw new Error('mode must be strict or loose(mode 只能是 strict 或 loose)')
|
|
71
|
+
const n = limitOf(a.limit, 3)
|
|
72
|
+
const rows = n === 0 ? [] : exp.recall(M, String(a.query || ''), { limit: n, mode, asOf: a.asOf || null })
|
|
73
|
+
return { ok: true, ...(a.asOf ? { asOf: a.asOf } : {}), items: rows.map((r) => ({ id: r.id, day: r.day, weight: r.weight, text: exp.renderTwoPart(r, { lang: cfg.lang }) })), ...(rows.length ? {} : { note: '没有找到相关的经历。' }) }
|
|
74
|
+
}
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
name: 'memory_read', title: '翻经历', annotations: READ,
|
|
78
|
+
description: 'Browse your own experiences in time order: what was written then, later thoughts, unfinished things and their state. Sealed ones are not listed by default; the one named by id is always returned (with a sealed marker).(按时间翻自己的经历:当时写下的、后来的想法、没弄完的事和它的状态。封存了的默认不列;用 id 点名的那一条照给(带封存标记)。)',
|
|
79
|
+
inputSchema: S({ id: str('可选:只看这一条'), limit: num('看几条,默认 8'), asOf: ASOF }),
|
|
80
|
+
run: (a) => {
|
|
81
|
+
const asOf = a.asOf || null
|
|
82
|
+
const only = String(a.id || '')
|
|
83
|
+
const all = exp.loadAll(M, { asOf })
|
|
84
|
+
const picked = only ? all.filter((r) => r.id === only || r.formerId === only) : all.filter((r) => !r.sealed)
|
|
85
|
+
const n = limitOf(a.limit, 8)
|
|
86
|
+
const rows = n === 0 ? [] : picked.slice(-n)
|
|
87
|
+
const res = {
|
|
88
|
+
ok: true, ...(asOf ? { asOf } : {}),
|
|
89
|
+
items: rows.map((r) => ({
|
|
90
|
+
id: r.id, day: r.day, weight: r.weight, text: r.then.text, thought: r.then.thought,
|
|
91
|
+
feeling: r.then.feeling || [], feelingNow: feelingNow(r),
|
|
92
|
+
unfinished: r.then.unfinished || '', unfinishedState: r.unfinishedState || null,
|
|
93
|
+
later: (r.later || []).map((x) => x.thought), refs: r.then.refs || [],
|
|
94
|
+
...(r.sealed ? { sealed: r.sealed } : {}), ...(only ? { view: exp.renderTwoPart(r, { lang: cfg.lang }) } : {})
|
|
95
|
+
}))
|
|
96
|
+
}
|
|
97
|
+
if (!only) { const hidden = all.filter((r) => r.sealed).length; if (hidden) res.sealedHidden = hidden }
|
|
98
|
+
if (only && !rows.length) res.note = asOf ? '截至 ' + asOf + ' 还没有这条经历。' : '找不到这条经历:' + only
|
|
99
|
+
return res
|
|
100
|
+
}
|
|
101
|
+
},
|
|
102
|
+
{
|
|
103
|
+
name: 'memory_recap', title: '这几天', annotations: READ,
|
|
104
|
+
description: 'The last few days: what was written, where you changed your mind, feelings that changed, things figured out or set aside, things still unfinished. Facts only, for writing your own look-back; no conclusions.(这几天写下的、改过主意的、感觉变了的、想通或放下的、还没弄完的。只列事实,给自己写回想用,不下结论。)',
|
|
105
|
+
inputSchema: S({ days: num('看最近几天,默认 7'), asOf: ASOF }),
|
|
106
|
+
run: (a) => { const rc = recapLib.recap(M, { days: Number(a.days || 7), asOf: a.asOf || null }); return { ok: true, text: recapLib.renderRecap(rc), recap: rc } }
|
|
107
|
+
},
|
|
108
|
+
{
|
|
109
|
+
name: 'memory_chapters', title: '人生章节', annotations: READ,
|
|
110
|
+
description: 'List the stretches of days you have named (chapters) and how many experiences each chapter holds.(列出自己起过名字的那些日子(章节),以及每一章里有几条经历。)',
|
|
111
|
+
inputSchema: S({ asOf: ASOF }),
|
|
112
|
+
run: (a) => {
|
|
113
|
+
const asOf = a.asOf || null
|
|
114
|
+
const rows = exp.loadAll(M, { asOf })
|
|
115
|
+
return { ok: true, chapters: chapterEvents.chapters(M, { until: parseAsOf(asOf) }).map((c) => ({ ...c, experiences: rows.filter((r) => (r.chapters || []).some((x) => x.id === c.id)).length })) }
|
|
116
|
+
}
|
|
117
|
+
},
|
|
118
|
+
{
|
|
119
|
+
name: 'memory_book', title: '我的书', annotations: READ,
|
|
120
|
+
description: 'Arrange your experiences by chapter into a human-readable book (Markdown). Sealed ones are left out.(把自己的经历按章节排成一本人能读的书(Markdown)。封存了的不收。)',
|
|
121
|
+
inputSchema: S({ asOf: ASOF, title: str('可选:书名') }),
|
|
122
|
+
run: (a) => ({ ok: true, markdown: book.renderBook(M, { asOf: a.asOf || null, title: a.title || undefined }) })
|
|
123
|
+
},
|
|
124
|
+
{
|
|
125
|
+
name: 'memory_waking', title: '醒来', annotations: { ...READ, readOnlyHint: false, idempotentHint: false },
|
|
126
|
+
description: 'The passage to read when you first wake up today: what you left for yourself yesterday and what is still unfinished. Shown once per day; peek=true looks without using up the one showing for today.(今天第一次醒来时看的那一段:昨天留给自己的话、还没弄完的事。每天只出一次;peek=true 只看不占用今天的这一次。)',
|
|
127
|
+
inputSchema: S({ peek: { type: 'boolean', description: '只看看,不算今天已经醒来' } }),
|
|
128
|
+
run: (a) => {
|
|
129
|
+
const block = waking.buildWakingBlock(cfg.data, OWNER_KEY, { lang: cfg.lang })
|
|
130
|
+
if (block && a.peek !== true && !cfg.readonly) waking.consumeWaking(cfg.data, OWNER_KEY) // 只读模式只看不占用
|
|
131
|
+
return { ok: true, block: block || '', ...(block ? {} : { note: '今天已经醒来过了,或者没有要提醒的。' }) }
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
]
|
|
135
|
+
if (!cfg.readonly) tools.push(
|
|
136
|
+
{
|
|
137
|
+
name: 'memory_write', title: '记下一段经历', annotations: WRITE,
|
|
138
|
+
description: 'Record what happened in your own time: what you read, thought or did. First person, written to yourself. Once written, the original text never changes; if your view changes, append with memory_revise.(把自己时间里发生的事记下来:读了什么、想了什么、做了什么。第一人称,写给自己。写下以后原文永远不改;想法变了用 memory_revise 追加。)',
|
|
139
|
+
inputSchema: S({
|
|
140
|
+
text: str('做了什么、读了什么、想了什么'), scene: str('当时的场景,可不填'), thought: str('当时的想法,可不填'),
|
|
141
|
+
feeling: strs('当时的感觉词,1–3 个'), unfinished: str('还没弄完的事,可不填'),
|
|
142
|
+
quote: { type: 'object', properties: { text: str('原文'), source: str('出处') }, required: ['text'], additionalProperties: false, description: '当时读到的原文锚,可不填' },
|
|
143
|
+
weight: { type: 'string', enum: ['important', 'normal', 'minor'] }, kind: str('读书 / 发呆 / 写东西 / 想事 / 回想 / 其它'),
|
|
144
|
+
refs: strs('这段是从哪几段经历想到的(id),可不填')
|
|
145
|
+
}, ['text']),
|
|
146
|
+
run: (a) => {
|
|
147
|
+
if (a.weight !== undefined && !['important', 'normal', 'minor'].includes(a.weight)) throw new Error('weight must be important / normal / minor(weight 只能是 important / normal / minor)')
|
|
148
|
+
const row = exp.addExperience(M, {
|
|
149
|
+
text: need(a.text, 'text'), scene: a.scene || '', thought: a.thought || '', feeling: list(a.feeling), unfinished: a.unfinished || '',
|
|
150
|
+
quote: a.quote && a.quote.text ? { text: String(a.quote.text), source: String(a.quote.source || '') } : null,
|
|
151
|
+
weight: a.weight || 'normal', kind: a.kind || '其它', refs: list(a.refs).join(',')
|
|
152
|
+
})
|
|
153
|
+
return { ok: true, id: row.id, day: row.day, ...(row.then.refs ? { refs: row.then.refs } : {}) }
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
{
|
|
157
|
+
name: 'memory_revise', title: '我改主意了', annotations: WRITE,
|
|
158
|
+
description: 'Your view of something recorded earlier has changed: append the thought you have now (and how it feels to recall it now). Not a word of what was written then is changed.(以前记下的看法变了:追加今天的想法(和现在再想起的感觉)。当时写下的一个字都不改。)',
|
|
159
|
+
inputSchema: S({ id: str('那条经历的 id'), thought: str('现在的想法'), reason: str('为什么改,可不填'), feeling: strs('现在再想起的感觉,可不填') }, ['id', 'thought']),
|
|
160
|
+
run: (a) => exp.reviseExperience(M, { id: need(a.id, 'id'), thought: need(a.thought, 'thought'), reason: a.reason || '', feeling: list(a.feeling).join(',') })
|
|
161
|
+
},
|
|
162
|
+
{
|
|
163
|
+
name: 'memory_unfinished', title: '想通了 / 先放下 / 再接着想', annotations: WRITE,
|
|
164
|
+
description: 'For something you wrote down as "not finished yet": done = figured it out, shelved = set it aside for now, reopen = want to think about it again. Once done or shelved, waking no longer reminds you.(之前写下"还没弄完"的那件事:done=想通了,shelved=先放一放,reopen=又想接着想。想通或放下后,醒来时不再提醒。)',
|
|
165
|
+
inputSchema: S({ id: str('那条经历的 id'), state: { type: 'string', enum: ['done', 'shelved', 'reopen'] }, note: str('可选') }, ['id', 'state']),
|
|
166
|
+
run: (a) => exp.setUnfinishedState(M, { id: need(a.id, 'id'), choice: need(a.state, 'state'), note: a.note || '' })
|
|
167
|
+
},
|
|
168
|
+
{
|
|
169
|
+
name: 'memory_seal', title: '封存 / 解封', annotations: WRITE,
|
|
170
|
+
description: 'Stop being reminded of something: sealed=true seals it, so it is not recalled, not mentioned on waking and left out of the book; it still exists, and sealed=false unseals it any time.(不想再被某件事主动提醒:sealed=true 封存,之后不会被想起、醒来不提、书里不收;它还在,sealed=false 随时解封。)',
|
|
171
|
+
inputSchema: S({ id: str('那条经历的 id'), sealed: { type: 'boolean' }, note: str('可选') }, ['id', 'sealed']),
|
|
172
|
+
run: (a) => exp.setSealed(M, { id: need(a.id, 'id'), sealed: a.sealed !== false, note: a.note || '' })
|
|
173
|
+
},
|
|
174
|
+
{
|
|
175
|
+
name: 'memory_link', title: '这两件事有关', annotations: WRITE,
|
|
176
|
+
description: 'You later notice two experiences are related: link them yourself. You must say why; each pair is linked only once.(事后发现两段经历有关,亲手连起来。必须说为什么;同一对只连一次。)',
|
|
177
|
+
inputSchema: S({ from: str('一条经历的 id'), to: str('另一条经历的 id'), reason: str('为什么觉得有关') }, ['from', 'to', 'reason']),
|
|
178
|
+
run: (a) => exp.linkExperiences(M, { from: need(a.from, 'from'), to: need(a.to, 'to'), reason: need(a.reason, 'reason') })
|
|
179
|
+
},
|
|
180
|
+
{
|
|
181
|
+
name: 'memory_chapter', title: '给一段日子起名字', annotations: WRITE,
|
|
182
|
+
description: 'open = start a chapter (give it a name, optionally start/end dates), rename = rename it (old names are kept), close = end the chapter. Experiences fall into chapters by date automatically.(open=开一章(起名字,可给起止日期),rename=改名(旧名保留),close=结束这一章。经历按日期自动落进章节。)',
|
|
183
|
+
inputSchema: S({ action: { type: 'string', enum: ['open', 'rename', 'close'] }, id: str('rename / close 时:章节 id'), name: str('open / rename 时:名字'), from: str('open 时可选:开始日期'), to: str('可选:结束日期'), note: str('可选') }, ['action']),
|
|
184
|
+
run: (a) => {
|
|
185
|
+
let res
|
|
186
|
+
if (a.action === 'open') res = chapterEvents.open(M, { name: need(a.name, 'name'), from: a.from || '', to: a.to || '', note: a.note || '' })
|
|
187
|
+
else if (a.action === 'rename') res = chapterEvents.rename(M, { id: need(a.id, 'id'), name: need(a.name, 'name') })
|
|
188
|
+
else if (a.action === 'close') res = chapterEvents.close(M, { id: need(a.id, 'id'), to: a.to || '' })
|
|
189
|
+
else throw new Error('action must be open / rename / close(action 只能是 open / rename / close)')
|
|
190
|
+
return { ok: true, noop: res.noop, ...(res.row ? { chapter: res.row } : {}) }
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
)
|
|
194
|
+
if (cfg.owner) tools.push({
|
|
195
|
+
name: 'memory_unsaid', title: '没说出口的话', annotations: { ...WRITE, readOnlyHint: false },
|
|
196
|
+
description: 'Put what you typed but did not send (draft), wanted to ask but did not (question), or held back (held) into the drawer. leave = put it in, list = open and look, spoken = you said it later after all, discard = no longer wanted (you will not see it either, but the original text is kept; to really delete it, ask a person to do it). Only you see it, and it is never brought up automatically.(打了没发的(draft)、想问没问的(question)、忍住了的(held)先放进抽屉。leave=放进去,list=打开看,spoken=后来说出口了,discard=不要了(之后自己也看不到,但原文还留着;真想删掉要找人来做)。只有自己会看到,不会被自动提起。)',
|
|
197
|
+
inputSchema: S({ action: { type: 'string', enum: ['leave', 'list', 'spoken', 'discard'] }, kind: { type: 'string', enum: ['draft', 'question', 'held'] }, text: str('leave 时:那句话'), reason: str('leave 时可选:为什么没说'), id: str('spoken / discard 时:那一条的 id'), all: { type: 'boolean', description: 'list 时:连说出口了的也看' } }, ['action']),
|
|
198
|
+
run: (a) => {
|
|
199
|
+
if (cfg.readonly && a.action !== 'list') throw new Error('Read-only mode: only list is allowed(只读模式下只能 list)')
|
|
200
|
+
if (a.action === 'leave') return unsaid.leaveUnsaid(M, { chatKey: OWNER_KEY, kind: a.kind || 'draft', text: a.text || '', reason: a.reason || '' })
|
|
201
|
+
if (a.action === 'list') return unsaid.listUnsaid(M, { chatKey: OWNER_KEY, all: a.all === true })
|
|
202
|
+
if (a.action === 'spoken') return unsaid.markUnsaidSpoken(M, { chatKey: OWNER_KEY, id: a.id || '' })
|
|
203
|
+
if (a.action === 'discard') return unsaid.discardUnsaid(M, { chatKey: OWNER_KEY, id: a.id || '' })
|
|
204
|
+
throw new Error('action must be leave / list / spoken / discard(action 只能是 leave / list / spoken / discard)')
|
|
205
|
+
}
|
|
206
|
+
})
|
|
207
|
+
return tools
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// ── 协议 ────────────────────────────────────────────────────────────────
|
|
211
|
+
const INSTRUCTIONS = [
|
|
212
|
+
'This is the autobiographical memory of an AI character, kept by herself. Three rules:(这是一个 AI 角色自己的自传体记忆。三条规矩:)',
|
|
213
|
+
'1. What was written then is never changed; if a view changes, append with memory_revise.(1. 当时写下的永远不改;想法变了用 memory_revise 追加。)',
|
|
214
|
+
'2. An empty result means this search found nothing; do not make anything up. For a specific detail use memory_detail; distinguish related events from support for an answer.(2. 查空只说明这次没找到,不要编。核对细节时用 memory_detail,按原文能支持的范围回答。)',
|
|
215
|
+
'3. Do not bring up what she has sealed; only she opens the unsaid drawer.(3. 她封存了的事不要主动提起;没说出口的抽屉只有她自己打开。)'
|
|
216
|
+
].join('\n')
|
|
217
|
+
|
|
218
|
+
export function createServer(cfg) {
|
|
219
|
+
const tools = buildTools(cfg)
|
|
220
|
+
const byName = new Map(tools.map((t) => [t.name, t]))
|
|
221
|
+
const ok = (id, result) => ({ jsonrpc: '2.0', id, result })
|
|
222
|
+
const err = (id, code, message) => ({ jsonrpc: '2.0', id, error: { code, message } })
|
|
223
|
+
return function handle(msg) {
|
|
224
|
+
if (!msg || typeof msg !== 'object' || Array.isArray(msg) || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') {
|
|
225
|
+
return err(msg && (typeof msg.id === 'string' || typeof msg.id === 'number') ? msg.id : null, -32600, 'Not a valid JSON-RPC 2.0 request(不是合法的 JSON-RPC 2.0 请求)')
|
|
226
|
+
}
|
|
227
|
+
const isNote = !('id' in msg)
|
|
228
|
+
const { id, method, params = {} } = msg
|
|
229
|
+
if (isNote) return null // notifications/initialized、notifications/cancelled 等:不用回
|
|
230
|
+
if (method === 'initialize') {
|
|
231
|
+
const want = params?.protocolVersion
|
|
232
|
+
return ok(id, {
|
|
233
|
+
protocolVersion: PROTOCOLS.includes(want) ? want : PROTOCOLS[0],
|
|
234
|
+
capabilities: { tools: { listChanged: false } },
|
|
235
|
+
serverInfo: { name: 'whale-memory', title: 'whale-memory(自传体记忆)', version: VERSION },
|
|
236
|
+
instructions: INSTRUCTIONS
|
|
237
|
+
})
|
|
238
|
+
}
|
|
239
|
+
if (method === 'ping') return ok(id, {})
|
|
240
|
+
if (method === 'tools/list') return ok(id, { tools: tools.map(({ run, ...t }) => t) })
|
|
241
|
+
if (method === 'tools/call') {
|
|
242
|
+
const tool = byName.get(params?.name)
|
|
243
|
+
if (!tool) return err(id, -32602, 'No such tool: ' + params?.name + '(没有这个工具:' + params?.name + ')')
|
|
244
|
+
const args = params.arguments && typeof params.arguments === 'object' && !Array.isArray(params.arguments) ? params.arguments : {}
|
|
245
|
+
try {
|
|
246
|
+
const res = tool.run(args)
|
|
247
|
+
return ok(id, { content: [{ type: 'text', text: JSON.stringify(res, null, 1) }], structuredContent: res, isError: res && res.ok === false })
|
|
248
|
+
} catch (e) {
|
|
249
|
+
const message = String(e && e.message ? e.message : e)
|
|
250
|
+
return ok(id, { content: [{ type: 'text', text: JSON.stringify({ ok: false, error: message }) }], structuredContent: { ok: false, error: message }, isError: true })
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return err(id, -32601, 'Unsupported method: ' + method + '(不支持的方法:' + method + ')')
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export function serve(cfg, input = process.stdin, output = process.stdout) {
|
|
258
|
+
const handle = createServer(cfg)
|
|
259
|
+
const rl = readline.createInterface({ input, crlfDelay: Infinity })
|
|
260
|
+
rl.on('line', (line) => {
|
|
261
|
+
if (!line.trim()) return
|
|
262
|
+
let msg
|
|
263
|
+
try { msg = JSON.parse(line) } catch { output.write(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Not valid JSON(不是合法的 JSON)' } }) + '\n'); return }
|
|
264
|
+
let reply
|
|
265
|
+
try { reply = handle(msg) } catch (e) { reply = { jsonrpc: '2.0', id: msg?.id ?? null, error: { code: -32603, message: String(e?.message || e) } } }
|
|
266
|
+
if (reply) output.write(JSON.stringify(reply) + '\n')
|
|
267
|
+
})
|
|
268
|
+
return rl
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const isMain = process.argv[1] && fs.realpathSync(path.resolve(process.argv[1])) === fs.realpathSync(fileURLToPath(import.meta.url))
|
|
272
|
+
if (isMain) {
|
|
273
|
+
const cfg = parseArgs(process.argv.slice(2))
|
|
274
|
+
process.stderr.write('whale-memory-mcp ' + VERSION + ':数据 ' + cfg.data + (cfg.owner ? ',抽屉已打开' : '') + (cfg.readonly ? ',只读' : '') + '\n')
|
|
275
|
+
serve(cfg)
|
|
276
|
+
}
|
package/demo.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
// 可运行示例:不需要任何宿主,node demo.mjs
|
|
2
|
+
// Runnable example, no host needed: node demo.mjs (--lang en | zh; default follows WHALE_LANG, then your system locale)
|
|
2
3
|
import fs from 'node:fs'
|
|
3
4
|
import os from 'node:os'
|
|
4
5
|
import path from 'node:path'
|
|
@@ -6,47 +7,57 @@ import * as exp from './lib/self-experience.js'
|
|
|
6
7
|
import * as prompt from './lib/self-prompt.js'
|
|
7
8
|
import * as waking from './lib/waking.js'
|
|
8
9
|
|
|
10
|
+
const argLang = (process.argv.find((a) => a.startsWith('--lang=')) || '').slice(7) || (process.argv.includes('--lang') ? process.argv[process.argv.indexOf('--lang') + 1] : '')
|
|
11
|
+
const sysLocale = String(process.env.LC_ALL || process.env.LANG || Intl.DateTimeFormat().resolvedOptions().locale || '')
|
|
12
|
+
const lang = (argLang || process.env.WHALE_LANG || (/^zh/i.test(sysLocale) ? 'zh' : 'en')) === 'zh' ? 'zh' : 'en'
|
|
13
|
+
|
|
14
|
+
// 示例内容:中文角色用中文,英文用户看英文(内容是虚构的)
|
|
15
|
+
const S = lang === 'zh' ? {
|
|
16
|
+
dataDir: '数据目录:', wrote: '[写] id=', weight: '| 重要度=', recalled: '[想起]', none: '[想起] 这次什么都没想起来(查询和记录没有足够重叠)',
|
|
17
|
+
revised: '[改主意后]', waking: '[醒来块]', shown: '(今天已经展示过)', overlay: '[overlay] 版本:', current: '当前内容:', history: '历史:', done: '演示完成。数据在',
|
|
18
|
+
entry: { text: '读到烤肉那段,笑了一下', scene: '晚上十一点多,屋里很静,书摊在桌上', feeling: ['轻松', '有点羡慕'], thought: '这种好事只在书里', unfinished: '想知道小鞠和社长后面怎么样了', quote: { text: '那就让妳重新迷上我一百年吧', source: '《败北女角太多了》第1卷第3章' }, state: { mood: '偏愉快' } },
|
|
19
|
+
query: '烤肉', revise: { thought: '现在觉得那个人其实是在护着朋友', reason: '读到后面那段' },
|
|
20
|
+
p1: ['说话能短就短;想不起就说想不起。', '第一次写'], p2: ['说话能短就短;想不起就说想不起。累了会慢,这不是失职。', '补一句']
|
|
21
|
+
} : {
|
|
22
|
+
dataDir: 'Data directory:', wrote: '[write] id=', weight: '| weight=', recalled: '[recall]', none: '[recall] Nothing came back this time (the query and the record do not overlap enough)',
|
|
23
|
+
revised: '[after changing her mind]', waking: '[waking block]', shown: '(already shown today)', overlay: '[overlay] versions:', current: 'Current text:', history: 'History:', done: 'Demo finished. The data is in',
|
|
24
|
+
entry: { text: 'Read the barbecue scene and laughed a little', scene: 'A bit after eleven at night, the room very quiet, the book open on the desk', feeling: ['relaxed', 'a little envious'], thought: 'Good things like that only happen in books', unfinished: 'Want to know what happens to the two of them later', quote: { text: 'Then let me make you fall for me again, for a hundred years', source: 'the novel she was reading, vol. 1 ch. 3' }, state: { mood: 'cheerful' } },
|
|
25
|
+
query: 'barbecue scene', revise: { thought: 'Now I think he was actually protecting his friend', reason: 'read the later chapter' },
|
|
26
|
+
p1: ['Keep it short. If you cannot remember, say so.', 'first version'], p2: ['Keep it short. If you cannot remember, say so. Being slow when tired is not a failure.', 'one more line']
|
|
27
|
+
}
|
|
28
|
+
|
|
9
29
|
const DATA = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'whale-demo-')), 'data')
|
|
10
30
|
const dir = path.join(DATA, 'plugin-data', 'biomimetic-memory')
|
|
11
31
|
fs.mkdirSync(dir, { recursive: true })
|
|
12
32
|
|
|
13
|
-
console.log(
|
|
14
|
-
|
|
15
|
-
// 1) 她写下一条经历(重要的写细)
|
|
16
|
-
const e = exp.addExperience(dir, {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
quote: { text: '那就让妳重新迷上我一百年吧', source: '《败北女角太多了》第1卷第3章' },
|
|
23
|
-
weight: 'important',
|
|
24
|
-
state: { mood: '偏愉快' }
|
|
25
|
-
})
|
|
26
|
-
console.log('\n[写] id=', e.id, '| 重要度=', e.weight)
|
|
27
|
-
|
|
28
|
-
// 2) 第二天她想起(相关话题触发);mark:true 表示这次取回也记一次“想起”
|
|
29
|
-
// 查询要用能命中的短锚点;长问句会被“≥8 字要求 60% 命中”的门槛挡住(这是故意的)
|
|
30
|
-
const hits = exp.recall(dir, '烤肉', { limit: 1, mark: true })
|
|
33
|
+
console.log(S.dataDir, DATA)
|
|
34
|
+
|
|
35
|
+
// 1) 她写下一条经历(重要的写细) / She writes down an experience (important ones in detail)
|
|
36
|
+
const e = exp.addExperience(dir, { ...S.entry, weight: 'important' })
|
|
37
|
+
console.log('\n' + S.wrote, e.id, S.weight, e.weight)
|
|
38
|
+
|
|
39
|
+
// 2) 第二天她想起;mark:true 表示这次取回也记一次"想起" / The next day she recalls it; mark:true records the recall
|
|
40
|
+
// 查询要和记录有足够重叠;对不上就返回空——没有记录就说没有 / An empty result means "no record", never a guess
|
|
41
|
+
const hits = exp.recall(dir, S.query, { limit: 1, mark: true })
|
|
31
42
|
if (!hits.length) {
|
|
32
|
-
console.log('\n
|
|
43
|
+
console.log('\n' + S.none)
|
|
33
44
|
} else {
|
|
34
|
-
console.log('\n
|
|
45
|
+
console.log('\n' + S.recalled + '\n' + exp.renderTwoPart(hits[0], { lang }))
|
|
35
46
|
}
|
|
36
47
|
|
|
37
|
-
// 3) 她改主意:只往 later 追加,不动"当时"
|
|
38
|
-
exp.reviseExperience(dir, { id: e.id,
|
|
39
|
-
console.log('\n
|
|
48
|
+
// 3) 她改主意:只往 later 追加,不动"当时" / She changes her mind: appended to "later", "then" is untouched
|
|
49
|
+
exp.reviseExperience(dir, { id: e.id, ...S.revise })
|
|
50
|
+
console.log('\n' + S.revised + '\n' + exp.renderTwoPart(exp.currentView(dir, e.id), { lang }))
|
|
40
51
|
|
|
41
|
-
// 4) 醒来块(只在一对一私聊给)
|
|
42
|
-
const wake = waking.buildWakingBlock(DATA, 'local:owner')
|
|
43
|
-
console.log('\n
|
|
52
|
+
// 4) 醒来块(只在一对一私聊给) / The waking block (only in one-to-one chats)
|
|
53
|
+
const wake = waking.buildWakingBlock(DATA, 'local:owner', { lang })
|
|
54
|
+
console.log('\n' + S.waking + '\n' + (wake || S.shown))
|
|
44
55
|
|
|
45
|
-
// 5) 她自己的提示词 overlay(版本只追加)
|
|
46
|
-
const v1 = prompt.save(DATA,
|
|
47
|
-
const v2 = prompt.save(DATA,
|
|
48
|
-
console.log('\n
|
|
49
|
-
console.log(
|
|
50
|
-
console.log(
|
|
56
|
+
// 5) 她自己的提示词 overlay(版本只追加) / Her own prompt overlay (versions are append-only)
|
|
57
|
+
const v1 = prompt.save(DATA, ...S.p1)
|
|
58
|
+
const v2 = prompt.save(DATA, ...S.p2)
|
|
59
|
+
console.log('\n' + S.overlay, v1.version, '→', v2.version)
|
|
60
|
+
console.log(S.current, prompt.load(DATA))
|
|
61
|
+
console.log(S.history, prompt.history(DATA, 3).map((h) => h.snapshot).join(', '))
|
|
51
62
|
|
|
52
|
-
console.log('\n
|
|
63
|
+
console.log('\n' + S.done, DATA)
|
package/index.d.ts
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
|
-
export * as selfExperience from './lib/self-experience.js'
|
|
2
|
-
export * as selfMemory from './lib/self-memory.js'
|
|
3
|
-
export
|
|
4
|
-
export * as
|
|
5
|
-
export * as
|
|
6
|
-
export * as
|
|
7
|
-
export * as
|
|
8
|
-
export * as
|
|
9
|
-
export * as
|
|
10
|
-
export * as
|
|
11
|
-
export * as
|
|
12
|
-
export * as
|
|
13
|
-
export * as
|
|
14
|
-
export * as
|
|
15
|
-
export * as
|
|
1
|
+
export * as selfExperience from './lib/self-experience.js'
|
|
2
|
+
export * as selfMemory from './lib/self-memory.js'
|
|
3
|
+
export { recallDetail } from './lib/detail-recall.js'
|
|
4
|
+
export * as waking from './lib/waking.js'
|
|
5
|
+
export * as selfPrompt from './lib/self-prompt.js'
|
|
6
|
+
export * as selfSettings from './lib/self-settings.js'
|
|
7
|
+
export * as evidencePolicy from './lib/evidence-policy.js'
|
|
8
|
+
export * as evidenceFromExperience from './lib/evidence-from-experience.js'
|
|
9
|
+
export * as unfinishedEvents from './lib/unfinished-events.js'
|
|
10
|
+
export * as sealEvents from './lib/seal-events.js'
|
|
11
|
+
export * as recap from './lib/recap.js'
|
|
12
|
+
export * as linkEvents from './lib/link-events.js'
|
|
13
|
+
export * as chapterEvents from './lib/chapter-events.js'
|
|
14
|
+
export * as book from './lib/book.js'
|
|
15
|
+
export * as unsaid from './lib/unsaid.js'
|
|
16
|
+
export * as archive from './lib/archive.js'
|
package/index.js
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
|
-
// whale-memory core:不依赖 QQ Agent 的可复用记忆内核
|
|
2
|
-
// 只放通用模块;宿主相关的工具注册与提示词拼接由使用者自己实现
|
|
3
|
-
export * as selfExperience from './lib/self-experience.js'
|
|
4
|
-
export * as selfMemory from './lib/self-memory.js'
|
|
5
|
-
export
|
|
6
|
-
export * as
|
|
7
|
-
export * as
|
|
8
|
-
export * as
|
|
9
|
-
export * as
|
|
10
|
-
export * as
|
|
11
|
-
export * as
|
|
12
|
-
export * as
|
|
13
|
-
export * as
|
|
14
|
-
export * as
|
|
15
|
-
export * as
|
|
16
|
-
export * as
|
|
17
|
-
export * as
|
|
1
|
+
// whale-memory core:不依赖 QQ Agent 的可复用记忆内核
|
|
2
|
+
// 只放通用模块;宿主相关的工具注册与提示词拼接由使用者自己实现
|
|
3
|
+
export * as selfExperience from './lib/self-experience.js'
|
|
4
|
+
export * as selfMemory from './lib/self-memory.js'
|
|
5
|
+
export { recallDetail } from './lib/detail-recall.js'
|
|
6
|
+
export * as waking from './lib/waking.js'
|
|
7
|
+
export * as selfPrompt from './lib/self-prompt.js'
|
|
8
|
+
export * as selfSettings from './lib/self-settings.js'
|
|
9
|
+
export * as evidencePolicy from './lib/evidence-policy.js'
|
|
10
|
+
export * as evidenceFromExperience from './lib/evidence-from-experience.js'
|
|
11
|
+
export * as unfinishedEvents from './lib/unfinished-events.js'
|
|
12
|
+
export * as sealEvents from './lib/seal-events.js'
|
|
13
|
+
export * as recap from './lib/recap.js'
|
|
14
|
+
export * as linkEvents from './lib/link-events.js'
|
|
15
|
+
export * as chapterEvents from './lib/chapter-events.js'
|
|
16
|
+
export * as book from './lib/book.js'
|
|
17
|
+
export * as unsaid from './lib/unsaid.js'
|
|
18
|
+
export * as archive from './lib/archive.js'
|
package/lib/archive.d.ts
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
export const FORMAT: 'whale-memory-export'
|
|
2
|
-
export function sha256(buf: Uint8Array | string): string
|
|
3
|
-
export function stamp(): string
|
|
4
|
-
export function collectFiles(root: string): Array<{ name: string; abs: string }>
|
|
5
|
-
/** a 是否等于 b 或在 b
|
|
6
|
-
export function inside(a: string, b: string): boolean
|
|
7
|
-
/** 越界路径(正反斜杠、绝对路径、盘符、..)抛错 */
|
|
8
|
-
export function safeJoin(root: string, name: string): string
|
|
9
|
-
|
|
10
|
-
export interface ArchiveManifest {
|
|
11
|
-
format: 'whale-memory-export'
|
|
12
|
-
version: number
|
|
13
|
-
exportedAt: string
|
|
14
|
-
files: Array<{ name: string; bytes: number; sha256: string }>
|
|
15
|
-
counts: Record<string, number>
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export function exportArchive(memDir: string, outDir: string, opts?: { name?: string }): { ok: true; dir: string; files: number; bytes: number; counts: Record<string, number> }
|
|
19
|
-
/** 整包校验;不对就抛错并说清是哪个文件 */
|
|
20
|
-
export function verifyArchive(fromDir: string): ArchiveManifest
|
|
21
|
-
/**
|
|
22
|
-
export function importArchive(fromDir: string, memDir: string, opts?: { force?: boolean }): { ok: true; files: number; restoreTo: string; backup: string; counts: { experiences: number } }
|
|
1
|
+
export const FORMAT: 'whale-memory-export'
|
|
2
|
+
export function sha256(buf: Uint8Array | string): string
|
|
3
|
+
export function stamp(): string
|
|
4
|
+
export function collectFiles(root: string): Array<{ name: string; abs: string }>
|
|
5
|
+
/** a 是否等于 b 或在 b 里面(解析现存父目录的真实路径,含目录链接) */
|
|
6
|
+
export function inside(a: string, b: string): boolean
|
|
7
|
+
/** 越界路径(正反斜杠、绝对路径、盘符、..)抛错 */
|
|
8
|
+
export function safeJoin(root: string, name: string): string
|
|
9
|
+
|
|
10
|
+
export interface ArchiveManifest {
|
|
11
|
+
format: 'whale-memory-export'
|
|
12
|
+
version: number
|
|
13
|
+
exportedAt: string
|
|
14
|
+
files: Array<{ name: string; bytes: number; sha256: string }>
|
|
15
|
+
counts: Record<string, number>
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function exportArchive(memDir: string, outDir: string, opts?: { name?: string }): { ok: true; dir: string; files: number; bytes: number; counts: Record<string, number> }
|
|
19
|
+
/** 整包校验;不对就抛错并说清是哪个文件 */
|
|
20
|
+
export function verifyArchive(fromDir: string): ArchiveManifest
|
|
21
|
+
/** 先校验并暂存完整副本,再替换;force 保留旧目录备份,替换报错时尝试还原。源与目标不得互相包含。 */
|
|
22
|
+
export function importArchive(fromDir: string, memDir: string, opts?: { force?: boolean }): { ok: true; files: number; restoreTo: string; backup: string; counts: { experiences: number } }
|