sage-mem 2.24.0 → 2.25.0
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.en.md +47 -5
- package/README.md +47 -5
- package/lib/assembly/index.js +3 -0
- package/lib/assembly/mirror-mount.js +184 -0
- package/lib/client.js +363 -0
- package/lib/index.js +29 -3
- package/lib/memory/config.js +7 -15
- package/lib/mirror/export.js +224 -0
- package/lib/mirror/mcp.js +396 -0
- package/lib/mirror/policy.js +300 -0
- package/lib/settings.js +34 -6
- package/lib/shared/int-spec.js +28 -0
- package/lib/typert/schemas.js +58 -0
- package/lib/typert.host.js +13 -1
- package/package.json +1 -1
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mirror 层 —— **唯一**写 `mirror/` 目录的地方(IO 与副作用层)。
|
|
3
|
+
*
|
|
4
|
+
* 三条纪律,改这个文件之前先读:
|
|
5
|
+
* 1. **只写副本,不碰主库**。这里没有任何指向 `memory/` 的写操作,连 rename 都不做。
|
|
6
|
+
* 2. **判据不在本文件**。要不要暴露、索引写成什么样,全在 `policy.js`;本文件只负责
|
|
7
|
+
* 「读主库 → 问 policy → 落盘 / 删盘」,一句自己的判据都不许有。
|
|
8
|
+
* 3. **拿不准就不动手**。主库列不出来(盘掉线 / 无权限 / 目录还没建)时,副本与账
|
|
9
|
+
* **一个字节都不动**并如实上报 —— 把「扫描失败」当成「主库空了」会清空副本,
|
|
10
|
+
* 而那份副本正是别的 agent 此刻在读的东西。
|
|
11
|
+
*
|
|
12
|
+
* 增量判据是**副本自己的内容 sha**,不是账里的记录:账只用来回答「上次导了什么」,
|
|
13
|
+
* 不用来回答「还要不要导」。差别在于副本被外部改坏 / 删掉之后,账看起来一切正常,
|
|
14
|
+
* 而按内容比对会立刻发现并重写。
|
|
15
|
+
*/
|
|
16
|
+
import { mkdir, readdir, readFile, unlink } from 'node:fs/promises'
|
|
17
|
+
import { join } from 'node:path'
|
|
18
|
+
import { parseFrontmatter } from '../memory/frontmatter.js'
|
|
19
|
+
import { revisionOf } from '../memory/write-protocol.js'
|
|
20
|
+
import { scanMemoryDirDetailed } from '../memory/scan.js'
|
|
21
|
+
import { warnLog, writeFileAtomic } from '../memory/util.js'
|
|
22
|
+
import { stampHuman } from '../shared/stamp.js'
|
|
23
|
+
import {
|
|
24
|
+
MIRROR_DIR_NAME,
|
|
25
|
+
MIRROR_INDEX_NAME,
|
|
26
|
+
MIRROR_MCP_NAME,
|
|
27
|
+
MIRROR_STATE_NAME,
|
|
28
|
+
buildMirrorIndex,
|
|
29
|
+
isExposed,
|
|
30
|
+
isMirrorReadableName,
|
|
31
|
+
} from './policy.js'
|
|
32
|
+
|
|
33
|
+
/** 增量账的格式版本。形状(不是加字段)变了才 +1。 */
|
|
34
|
+
const STATE_VERSION = 1
|
|
35
|
+
|
|
36
|
+
const shaOf = (text) => revisionOf(Buffer.from(text, 'utf8'))
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 建一个导出器。
|
|
40
|
+
*
|
|
41
|
+
* @param {object} opts
|
|
42
|
+
* @param {object} opts.ctx — 宿主上下文(只为 `warnLog`)
|
|
43
|
+
* @param {string} opts.memoryDir — 主库目录(**只读**)
|
|
44
|
+
* @param {string} opts.stateRoot — 状态根;副本落 `join(stateRoot, 'mirror')`
|
|
45
|
+
* @param {Function} [opts.scan] — 测试注入用;默认 `scanMemoryDirDetailed`
|
|
46
|
+
*/
|
|
47
|
+
export function createMirrorExporter({ ctx, memoryDir, stateRoot, scan = scanMemoryDirDetailed }) {
|
|
48
|
+
const mirrorDir = join(stateRoot, MIRROR_DIR_NAME)
|
|
49
|
+
const stateFile = join(mirrorDir, MIRROR_STATE_NAME)
|
|
50
|
+
const indexPath = join(mirrorDir, MIRROR_INDEX_NAME)
|
|
51
|
+
|
|
52
|
+
/** 读增量账。坏文件 / 旧版本当空账(只影响「上次导了什么」的叙述,不影响是否要写)。 */
|
|
53
|
+
async function readState() {
|
|
54
|
+
try {
|
|
55
|
+
const parsed = JSON.parse(await readFile(stateFile, 'utf8'))
|
|
56
|
+
if (!parsed || typeof parsed !== 'object' || parsed.version !== STATE_VERSION) return { entries: {} }
|
|
57
|
+
const entries = parsed.entries && typeof parsed.entries === 'object' && !Array.isArray(parsed.entries) ? parsed.entries : {}
|
|
58
|
+
return { entries }
|
|
59
|
+
} catch {
|
|
60
|
+
return { entries: {} }
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 副本目录里现在有哪些**可读条目**(点文件与索引不算)。 */
|
|
65
|
+
async function listMirrorNames() {
|
|
66
|
+
const names = await readdir(mirrorDir).catch(() => [])
|
|
67
|
+
return names.filter((n) => isMirrorReadableName(n))
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* 跑一轮导出。**不抛**:任何失败都进 `errors` 并如实上报(挂载层会写进面板状态)。
|
|
72
|
+
*
|
|
73
|
+
* @param {object} external — `resolveExternal` 的产物
|
|
74
|
+
* @returns {Promise<{ok:boolean, at:number, exposed:number, written:number, unchanged:number,
|
|
75
|
+
* deleted:number, indexed:boolean, skipped:string[], errors:string[]}>}
|
|
76
|
+
*/
|
|
77
|
+
async function run(external) {
|
|
78
|
+
const at = Date.now()
|
|
79
|
+
const report = { ok: true, at, disabled: false, exposed: 0, names: [], written: 0, unchanged: 0, deleted: 0, indexed: false, skipped: [], errors: [] }
|
|
80
|
+
// 开关关着时**什么都不碰**:不清副本、不写账。副本是「可重建的只读快照」,
|
|
81
|
+
// 关掉端点不等于要求删文件;而「关一次清一次」会让下次打开时有一段空窗期。
|
|
82
|
+
if (!external || !external.enabled) {
|
|
83
|
+
report.disabled = true
|
|
84
|
+
return report
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// ── 1. 读主库(只读)─────────────────────────────────────────────
|
|
88
|
+
const scanned = await scan(ctx, '', memoryDir)
|
|
89
|
+
if (scanned.complete === false) {
|
|
90
|
+
report.ok = false
|
|
91
|
+
report.errors.push(`主库目录读不出来,本轮不动副本:${scanned.errors.map((e) => e.code || e.message).join(';') || '未知原因'}`)
|
|
92
|
+
warnLog(ctx, `外部访问导出有问题:${report.errors.join(';')}`)
|
|
93
|
+
return report
|
|
94
|
+
}
|
|
95
|
+
if (scanned.missing === true) {
|
|
96
|
+
report.ok = false
|
|
97
|
+
report.errors.push('主库目录不存在,本轮不动副本(避免把一次盘掉线当成「主库空了」)')
|
|
98
|
+
warnLog(ctx, `外部访问导出有问题:${report.errors.join(';')}`)
|
|
99
|
+
return report
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// ── 2. 问 policy:这一轮该暴露谁 ─────────────────────────────────
|
|
103
|
+
/** name → {content, meta, sha} */
|
|
104
|
+
const desired = new Map()
|
|
105
|
+
for (const file of scanned.files) {
|
|
106
|
+
const meta = parseFrontmatter(file.content)
|
|
107
|
+
if (!isExposed(file.file, meta.tags, external)) continue
|
|
108
|
+
desired.set(file.file, { content: file.content, meta, sha: shaOf(file.content), mtimeMs: file.mtimeMs ?? 0 })
|
|
109
|
+
}
|
|
110
|
+
report.exposed = desired.size
|
|
111
|
+
report.names = [...desired.keys()].sort()
|
|
112
|
+
|
|
113
|
+
// ── 3. 落盘(内容 sha 相同就不写)────────────────────────────────
|
|
114
|
+
try {
|
|
115
|
+
await mkdir(mirrorDir, { recursive: true })
|
|
116
|
+
} catch (err) {
|
|
117
|
+
report.ok = false
|
|
118
|
+
report.errors.push(`建不了副本目录(${err?.code ?? err?.message ?? err})`)
|
|
119
|
+
return report
|
|
120
|
+
}
|
|
121
|
+
const existing = new Set(await listMirrorNames())
|
|
122
|
+
const next = {}
|
|
123
|
+
for (const [name, item] of desired) {
|
|
124
|
+
next[name] = { sha: item.sha, size: Buffer.byteLength(item.content, 'utf8'), mtimeMs: item.mtimeMs }
|
|
125
|
+
const current = existing.has(name) ? await readFile(join(mirrorDir, name), 'utf8').catch(() => null) : null
|
|
126
|
+
if (current !== null && shaOf(current) === item.sha) {
|
|
127
|
+
report.unchanged += 1
|
|
128
|
+
continue
|
|
129
|
+
}
|
|
130
|
+
try {
|
|
131
|
+
await writeFileAtomic(join(mirrorDir, name), item.content)
|
|
132
|
+
report.written += 1
|
|
133
|
+
} catch (err) {
|
|
134
|
+
// 单条写失败不拖垮整轮:报出来、下一轮再来。
|
|
135
|
+
report.ok = false
|
|
136
|
+
report.skipped.push(name)
|
|
137
|
+
report.errors.push(`写副本失败 ${name}:${err?.code ?? err?.message ?? err}`)
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// ── 4. 删掉退出白名单 / 主库已删的副本 ───────────────────────────
|
|
142
|
+
for (const name of existing) {
|
|
143
|
+
if (desired.has(name)) continue
|
|
144
|
+
try {
|
|
145
|
+
await unlink(join(mirrorDir, name))
|
|
146
|
+
report.deleted += 1
|
|
147
|
+
} catch (err) {
|
|
148
|
+
if (err?.code === 'ENOENT') continue
|
|
149
|
+
report.ok = false
|
|
150
|
+
report.errors.push(`删副本失败 ${name}:${err?.code ?? err?.message ?? err}`)
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// ── 5. 副本索引(重新生成;只有真的变了才写)──────────────────────
|
|
155
|
+
const indexText = buildMirrorIndex(
|
|
156
|
+
[...desired].map(([name, item]) => ({ name, title: item.meta.name, description: item.meta.description, tags: item.meta.tags })),
|
|
157
|
+
{ stamp: stampHuman(at) },
|
|
158
|
+
)
|
|
159
|
+
const currentIndex = await readFile(indexPath, 'utf8').catch(() => null)
|
|
160
|
+
if (currentIndex !== indexText) {
|
|
161
|
+
try {
|
|
162
|
+
await writeFileAtomic(indexPath, indexText)
|
|
163
|
+
report.indexed = true
|
|
164
|
+
} catch (err) {
|
|
165
|
+
report.ok = false
|
|
166
|
+
report.errors.push(`写副本索引失败:${err?.code ?? err?.message ?? err}`)
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// ── 6. 记账 ─────────────────────────────────────────────────────
|
|
171
|
+
try {
|
|
172
|
+
await writeFileAtomic(stateFile, `${JSON.stringify({ version: STATE_VERSION, at, entries: next }, null, 2)}\n`)
|
|
173
|
+
} catch (err) {
|
|
174
|
+
report.ok = false
|
|
175
|
+
report.errors.push(`写增量账失败:${err?.code ?? err?.message ?? err}`)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if (report.errors.length > 0) warnLog(ctx, `外部访问导出有问题:${report.errors.join(';')}`)
|
|
179
|
+
return report
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* 副本里的一条正文(MCP `memory_read` 用)。**不存在就返回 null**,不抛 ——
|
|
184
|
+
* 外部调用方要的是一句「没有这条」,不是一个异常栈。
|
|
185
|
+
*/
|
|
186
|
+
async function readMirrorEntry(name) {
|
|
187
|
+
if (!isMirrorReadableName(name)) return null
|
|
188
|
+
try {
|
|
189
|
+
return await readFile(join(mirrorDir, name), 'utf8')
|
|
190
|
+
} catch {
|
|
191
|
+
return null
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* 副本里**此刻真的能读到**的条目(MCP `memory_list` / `memory_search` 的语料)。
|
|
197
|
+
*
|
|
198
|
+
* 读的是副本目录本身,不是增量账:账里可能记着一条刚被删掉的副本,
|
|
199
|
+
* 而工具面必须只说「现在能读到什么」。
|
|
200
|
+
*/
|
|
201
|
+
async function listMirrorEntries() {
|
|
202
|
+
const out = []
|
|
203
|
+
for (const name of await listMirrorNames()) {
|
|
204
|
+
const content = await readFile(join(mirrorDir, name), 'utf8').catch(() => null)
|
|
205
|
+
if (content === null) continue
|
|
206
|
+
const meta = parseFrontmatter(content)
|
|
207
|
+
out.push({
|
|
208
|
+
name,
|
|
209
|
+
title: meta.name || name.replace(/\.md$/i, ''),
|
|
210
|
+
description: meta.description || '',
|
|
211
|
+
type: meta.type || '',
|
|
212
|
+
tags: meta.tags,
|
|
213
|
+
content,
|
|
214
|
+
})
|
|
215
|
+
}
|
|
216
|
+
out.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
|
|
217
|
+
return out
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** 记在副本目录里的端点发现文件路径(MCP 层写它)。 */
|
|
221
|
+
const mcpFile = join(mirrorDir, MIRROR_MCP_NAME)
|
|
222
|
+
|
|
223
|
+
return { mirrorDir, stateFile, indexPath, mcpFile, run, readMirrorEntry, listMirrorEntries, listMirrorNames, readState }
|
|
224
|
+
}
|
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mirror 层 —— 只读 MCP 端点(127.0.0.1,JSON-RPC 2.0 over HTTP)。
|
|
3
|
+
*
|
|
4
|
+
* 这里只做三件事:起一个回环口的 HTTP 服务、把 JSON-RPC 分派到三个只读工具、把「端点开着」
|
|
5
|
+
* 这件事写进副本目录的 `mcp.json`(外部 agent 靠它发现地址)。
|
|
6
|
+
*
|
|
7
|
+
* 四条不许动的边界:
|
|
8
|
+
* 1. **只绑 127.0.0.1** —— 不提供跨机器访问。真要跨机器,走 SSH 端口转发,别在这里开口子。
|
|
9
|
+
* 2. **只读副本** —— 一切正文来自 `exporter`,本文件不 import 主库扫描,也不写主库。
|
|
10
|
+
* 3. **不返回绝对路径** —— 工具面只给 `name`。记忆是「看不见的底座」:能引用,不能顺着路径去改。
|
|
11
|
+
* 4. **没有写工具** —— 连一个都没有;写侧属于 2.26.0 的 `intake/` + 归并器。
|
|
12
|
+
*
|
|
13
|
+
* ⚠️ 无状态:不维持 session,不校验 `Mcp-Session-Id`。客户端每次带完整请求即可 ——
|
|
14
|
+
* 这套端点的消费者是同一台机器上的 IDE agent,多一层会话状态只会多一种「连不上」的原因。
|
|
15
|
+
*/
|
|
16
|
+
import { createServer } from 'node:http'
|
|
17
|
+
import { unlink } from 'node:fs/promises'
|
|
18
|
+
import { buildStats, queryTermsOf, scoreDoc, termFreq, tokenize } from '../memory/bm25.js'
|
|
19
|
+
import { stripFrontmatterBlock } from '../memory/frontmatter.js'
|
|
20
|
+
import { warnLog, writeFileAtomic } from '../memory/util.js'
|
|
21
|
+
import { MIRROR_MCP_NAME, isMirrorReadableName } from './policy.js'
|
|
22
|
+
import { currentVersion } from '../update.js'
|
|
23
|
+
|
|
24
|
+
/** 认识且愿意应答的协议版本(按新到旧)。客户端报别的 → 回落最新一个。 */
|
|
25
|
+
const PROTOCOL_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05']
|
|
26
|
+
const PROTOCOL_FALLBACK = PROTOCOL_VERSIONS[0]
|
|
27
|
+
|
|
28
|
+
/** 请求体上限。三个工具的参数加起来不该接近这个数;超了就是走错门了。 */
|
|
29
|
+
const MAX_BODY_BYTES = 1024 * 1024
|
|
30
|
+
|
|
31
|
+
/** 片段长度上限(字符)。 */
|
|
32
|
+
const SNIPPET_MAX = 280
|
|
33
|
+
|
|
34
|
+
/** 工具数量与名字只在这里定义一次(`tools/list` 与分派共用)。 */
|
|
35
|
+
const TOOL_DEFS = Object.freeze([
|
|
36
|
+
{
|
|
37
|
+
name: 'memory_search',
|
|
38
|
+
description: '在**记忆副本**里按关键词检索(词面匹配,中文按双字切词)。返回条目名与片段;读全文请用 memory_read。只读,不返回文件路径。',
|
|
39
|
+
inputSchema: {
|
|
40
|
+
type: 'object',
|
|
41
|
+
properties: {
|
|
42
|
+
query: { type: 'string', description: '要检索的词或问句' },
|
|
43
|
+
limit: { type: 'integer', minimum: 1, maximum: 20, description: '最多返回几条,默认 5' },
|
|
44
|
+
},
|
|
45
|
+
required: ['query'],
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
name: 'memory_read',
|
|
50
|
+
description: '读一条记忆副本的全文。name 取 memory_search / memory_list 返回的名字(形如 project_xxx.md)。只读。',
|
|
51
|
+
inputSchema: {
|
|
52
|
+
type: 'object',
|
|
53
|
+
properties: { name: { type: 'string', description: '条目文件名,如 project_sage-mem.md' } },
|
|
54
|
+
required: ['name'],
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
name: 'memory_list',
|
|
59
|
+
description: '列出副本里全部可读条目(名字 + 一句话 + 类型 + 标签)。只读。',
|
|
60
|
+
inputSchema: { type: 'object', properties: {} },
|
|
61
|
+
},
|
|
62
|
+
])
|
|
63
|
+
|
|
64
|
+
const INSTRUCTIONS = [
|
|
65
|
+
'这是一个**只读**记忆库端点:读的是主记忆库按白名单导出的副本。',
|
|
66
|
+
'可用工具:memory_list(有哪些)/ memory_search(按关键词找)/ memory_read(读全文)。',
|
|
67
|
+
'引用某条记忆时请带上它的 name(如 project_xxx.md),不要假设文件路径 —— 这里不提供路径。',
|
|
68
|
+
'这里没有写入能力:你想留下东西的话,请直接告诉用户,由 sage-mem 的归并流程处理。',
|
|
69
|
+
].join('\n')
|
|
70
|
+
|
|
71
|
+
/** 正文 → 片段:去掉 frontmatter、压平空白、截断。 */
|
|
72
|
+
function snippetOf(content) {
|
|
73
|
+
const body = stripFrontmatterBlock(String(content ?? '')).replace(/\s+/g, ' ').trim()
|
|
74
|
+
return body.length > SNIPPET_MAX ? `${body.slice(0, SNIPPET_MAX)}…` : body
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** 参数不合法时的统一出口(MCP 的「工具执行失败」用 isError,不用 JSON-RPC 错误码)。 */
|
|
78
|
+
function toolError(text) {
|
|
79
|
+
return { content: [{ type: 'text', text }], isError: true }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function textResult(value) {
|
|
83
|
+
return { content: [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }] }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 建一个 MCP 端点(**不自动启动**,由挂载层决定何时 start)。
|
|
88
|
+
*
|
|
89
|
+
* @param {object} opts
|
|
90
|
+
* @param {object} opts.ctx — 宿主上下文(只为 `warnLog`)
|
|
91
|
+
* @param {object} opts.exporter — `createMirrorExporter()` 的产物(只读面)
|
|
92
|
+
*/
|
|
93
|
+
export function createMirrorMcpServer({ ctx, exporter }) {
|
|
94
|
+
let server = null
|
|
95
|
+
let listening = false
|
|
96
|
+
let boundPort = 0
|
|
97
|
+
let startedAt = 0
|
|
98
|
+
/** 端点自报的版本:**运行时**读 package.json(与 update.js 同一条理由:内联常量会与 bump 脱节)。 */
|
|
99
|
+
let serverVersion = ''
|
|
100
|
+
/** 起不来 / 中途失败的原因(空串 = 没问题)。 */
|
|
101
|
+
let failure = ''
|
|
102
|
+
|
|
103
|
+
const url = () => (listening ? `http://127.0.0.1:${boundPort}/mcp` : '')
|
|
104
|
+
|
|
105
|
+
/** 端点发现文件:只有在真的在听时才写(外部 agent 据此判断「现在能不能用」)。 */
|
|
106
|
+
async function writeDiscovery() {
|
|
107
|
+
const payload = {
|
|
108
|
+
name: 'sage-mem-mirror',
|
|
109
|
+
protocolVersion: PROTOCOL_FALLBACK,
|
|
110
|
+
url: url(),
|
|
111
|
+
transport: 'http',
|
|
112
|
+
tools: TOOL_DEFS.map((t) => t.name),
|
|
113
|
+
readOnly: true,
|
|
114
|
+
generatedAt: new Date().toISOString(),
|
|
115
|
+
}
|
|
116
|
+
try {
|
|
117
|
+
await writeFileAtomic(exporter.mcpFile, `${JSON.stringify(payload, null, 2)}\n`)
|
|
118
|
+
} catch (err) {
|
|
119
|
+
// 发现文件写不出来不影响端点本身可用(面板里仍有地址)。
|
|
120
|
+
warnLog(ctx, `外部访问:写不了端点发现文件(${err?.code ?? err?.message ?? err})`)
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function dropDiscovery() {
|
|
125
|
+
await unlink(exporter.mcpFile).catch(() => {})
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// ── 三个工具 ───────────────────────────────────────────────────────
|
|
129
|
+
|
|
130
|
+
async function toolSearch(args) {
|
|
131
|
+
const query = typeof args?.query === 'string' ? args.query.trim() : ''
|
|
132
|
+
if (query === '') return toolError('memory_search 需要非空的 query')
|
|
133
|
+
const rawLimit = Number(args?.limit)
|
|
134
|
+
const limit = Number.isFinite(rawLimit) ? Math.max(1, Math.min(20, Math.round(rawLimit))) : 5
|
|
135
|
+
const corpus = await exporter.listMirrorEntries()
|
|
136
|
+
if (corpus.length === 0) return textResult({ query, corpus: 0, hits: [] })
|
|
137
|
+
const docs = corpus.map((e) => {
|
|
138
|
+
const tokens = tokenize(`${e.title} ${e.description} ${e.content}`)
|
|
139
|
+
return { entry: e, tokens, tf: termFreq(tokens), dl: tokens.length }
|
|
140
|
+
})
|
|
141
|
+
const stats = buildStats(docs.map((d) => ({ tokens: d.tokens })))
|
|
142
|
+
const terms = queryTermsOf(query)
|
|
143
|
+
const scored = []
|
|
144
|
+
for (const d of docs) {
|
|
145
|
+
const score = scoreDoc(terms, d.tf, d.dl, stats)
|
|
146
|
+
if (score > 0) scored.push({ score, entry: d.entry })
|
|
147
|
+
}
|
|
148
|
+
scored.sort((a, b) => b.score - a.score)
|
|
149
|
+
return textResult({
|
|
150
|
+
query,
|
|
151
|
+
corpus: corpus.length,
|
|
152
|
+
hits: scored.slice(0, limit).map(({ entry }) => ({
|
|
153
|
+
name: entry.name,
|
|
154
|
+
title: entry.title,
|
|
155
|
+
description: entry.description,
|
|
156
|
+
type: entry.type,
|
|
157
|
+
tags: entry.tags,
|
|
158
|
+
snippet: snippetOf(entry.content),
|
|
159
|
+
})),
|
|
160
|
+
})
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async function toolRead(args) {
|
|
164
|
+
const name = typeof args?.name === 'string' ? args.name.trim() : ''
|
|
165
|
+
if (!isMirrorReadableName(name)) return toolError('memory_read 的 name 必须是副本里的单段 .md 名字(如 project_xxx.md)')
|
|
166
|
+
const content = await exporter.readMirrorEntry(name)
|
|
167
|
+
if (content === null) return toolError(`副本里没有这条记忆:${name}(用 memory_list 看看现在有哪些)`)
|
|
168
|
+
return textResult(content)
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async function toolList() {
|
|
172
|
+
const corpus = await exporter.listMirrorEntries()
|
|
173
|
+
return textResult({
|
|
174
|
+
corpus: corpus.length,
|
|
175
|
+
entries: corpus.map((e) => ({ name: e.name, title: e.title, description: e.description, type: e.type, tags: e.tags })),
|
|
176
|
+
})
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** 工具名 → 实现。**没有**写工具,别在这里加。 */
|
|
180
|
+
const TOOLS = Object.freeze({ memory_search: toolSearch, memory_read: toolRead, memory_list: toolList })
|
|
181
|
+
|
|
182
|
+
// ── JSON-RPC 分派 ──────────────────────────────────────────────────
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* 处理一条 JSON-RPC 消息。
|
|
186
|
+
* @returns {Promise<{status:number, body:object|null}>} `body === null` 表示「通知,不回包」
|
|
187
|
+
*/
|
|
188
|
+
async function dispatch(message) {
|
|
189
|
+
if (!message || typeof message !== 'object' || Array.isArray(message)) {
|
|
190
|
+
return { status: 400, body: { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid Request' } } }
|
|
191
|
+
}
|
|
192
|
+
const id = message.id
|
|
193
|
+
const isNotification = id === undefined || id === null
|
|
194
|
+
const method = typeof message.method === 'string' ? message.method : ''
|
|
195
|
+
const fail = (code, msg) => ({ status: 200, body: { jsonrpc: '2.0', id: id ?? null, error: { code, message: msg } } })
|
|
196
|
+
if (method === '') return isNotification ? { status: 202, body: null } : fail(-32600, 'Invalid Request')
|
|
197
|
+
|
|
198
|
+
if (method === 'initialize') {
|
|
199
|
+
const asked = message.params?.protocolVersion
|
|
200
|
+
const protocolVersion = PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_FALLBACK
|
|
201
|
+
return {
|
|
202
|
+
status: 200,
|
|
203
|
+
body: {
|
|
204
|
+
jsonrpc: '2.0',
|
|
205
|
+
id: id ?? null,
|
|
206
|
+
result: {
|
|
207
|
+
protocolVersion,
|
|
208
|
+
capabilities: { tools: { listChanged: false } },
|
|
209
|
+
serverInfo: { name: 'sage-mem-mirror', version: serverVersion || 'unknown' },
|
|
210
|
+
instructions: INSTRUCTIONS,
|
|
211
|
+
},
|
|
212
|
+
},
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
// 通知:客户端说「我初始化好了」。无回包。
|
|
216
|
+
if (method.startsWith('notifications/')) return { status: 202, body: null }
|
|
217
|
+
if (method === 'ping') return { status: 200, body: { jsonrpc: '2.0', id: id ?? null, result: {} } }
|
|
218
|
+
if (method === 'tools/list') {
|
|
219
|
+
return { status: 200, body: { jsonrpc: '2.0', id: id ?? null, result: { tools: TOOL_DEFS.map((t) => ({ ...t })) } } }
|
|
220
|
+
}
|
|
221
|
+
if (method === 'tools/call') {
|
|
222
|
+
const name = message.params?.name
|
|
223
|
+
const impl = TOOLS[name]
|
|
224
|
+
if (!impl) return fail(-32602, `Unknown tool: ${String(name)}`)
|
|
225
|
+
try {
|
|
226
|
+
const result = await impl(message.params?.arguments ?? {})
|
|
227
|
+
return { status: 200, body: { jsonrpc: '2.0', id: id ?? null, result } }
|
|
228
|
+
} catch (err) {
|
|
229
|
+
warnLog(ctx, `外部访问:工具 ${name} 出错(${err?.message ?? err})`)
|
|
230
|
+
return { status: 200, body: { jsonrpc: '2.0', id: id ?? null, result: toolError(`工具执行失败:${err?.message ?? err}`) } }
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return fail(-32601, `Method not found: ${method}`)
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** 读请求体(带上限)。超限先回 413、再把剩下的请求排干(不缓存)。 */
|
|
237
|
+
function readBody(req, res) {
|
|
238
|
+
return new Promise((resolve) => {
|
|
239
|
+
const chunks = []
|
|
240
|
+
let size = 0
|
|
241
|
+
/** 已经回过 413:后面只排干,不再缓存。 */
|
|
242
|
+
let overflow = false
|
|
243
|
+
req.on('data', (chunk) => {
|
|
244
|
+
size += chunk.length
|
|
245
|
+
if (overflow) {
|
|
246
|
+
// 极端情况(有人往回环口灌包):超过 8 倍上限就直接断,不留一条无限长的排干。
|
|
247
|
+
if (size > MAX_BODY_BYTES * 8) req.destroy()
|
|
248
|
+
return
|
|
249
|
+
}
|
|
250
|
+
if (size > MAX_BODY_BYTES) {
|
|
251
|
+
overflow = true
|
|
252
|
+
chunks.length = 0
|
|
253
|
+
res.writeHead(413, { 'content-type': 'application/json' })
|
|
254
|
+
res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Request body too large' } }))
|
|
255
|
+
return
|
|
256
|
+
}
|
|
257
|
+
chunks.push(chunk)
|
|
258
|
+
})
|
|
259
|
+
req.on('end', () => {
|
|
260
|
+
if (overflow) { resolve(null); return }
|
|
261
|
+
resolve(Buffer.concat(chunks).toString('utf8'))
|
|
262
|
+
})
|
|
263
|
+
req.on('error', () => resolve(null))
|
|
264
|
+
})
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
async function onRequest(req, res) {
|
|
268
|
+
// GET:给人和探针看的一份状态(不含任何记忆正文)。
|
|
269
|
+
if (req.method === 'GET') {
|
|
270
|
+
res.writeHead(200, { 'content-type': 'application/json' })
|
|
271
|
+
res.end(JSON.stringify({ name: 'sage-mem-mirror', readOnly: true, waitingFor: 'POST JSON-RPC 2.0', ...status() }))
|
|
272
|
+
return
|
|
273
|
+
}
|
|
274
|
+
if (req.method !== 'POST') {
|
|
275
|
+
res.writeHead(405, { 'content-type': 'application/json', allow: 'POST, GET' })
|
|
276
|
+
res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Method Not Allowed' } }))
|
|
277
|
+
return
|
|
278
|
+
}
|
|
279
|
+
const raw = await readBody(req, res)
|
|
280
|
+
if (raw === null) return
|
|
281
|
+
let parsed
|
|
282
|
+
try {
|
|
283
|
+
parsed = JSON.parse(raw)
|
|
284
|
+
} catch {
|
|
285
|
+
res.writeHead(200, { 'content-type': 'application/json' })
|
|
286
|
+
res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }))
|
|
287
|
+
return
|
|
288
|
+
}
|
|
289
|
+
// 允许一次发一批(JSON-RPC batch):MCP 客户端偶尔这么干。
|
|
290
|
+
if (Array.isArray(parsed)) {
|
|
291
|
+
const out = []
|
|
292
|
+
for (const one of parsed) {
|
|
293
|
+
const r = await dispatch(one)
|
|
294
|
+
if (r.body !== null) out.push(r.body)
|
|
295
|
+
}
|
|
296
|
+
if (out.length === 0) {
|
|
297
|
+
res.writeHead(202)
|
|
298
|
+
res.end()
|
|
299
|
+
return
|
|
300
|
+
}
|
|
301
|
+
res.writeHead(200, { 'content-type': 'application/json' })
|
|
302
|
+
res.end(JSON.stringify(out))
|
|
303
|
+
return
|
|
304
|
+
}
|
|
305
|
+
const result = await dispatch(parsed)
|
|
306
|
+
if (result.body === null) {
|
|
307
|
+
res.writeHead(result.status)
|
|
308
|
+
res.end()
|
|
309
|
+
return
|
|
310
|
+
}
|
|
311
|
+
res.writeHead(result.status, { 'content-type': 'application/json' })
|
|
312
|
+
res.end(JSON.stringify(result.body))
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* 开始监听。**不抛**:端口被占用等失败一律通过返回值 + `status()` 表达。
|
|
317
|
+
* @param {number} port — 从设置来的端口(1024–65535)
|
|
318
|
+
*/
|
|
319
|
+
async function start(port) {
|
|
320
|
+
if (listening) return status()
|
|
321
|
+
failure = ''
|
|
322
|
+
serverVersion = await currentVersion()
|
|
323
|
+
await new Promise((resolve) => {
|
|
324
|
+
let settled = false
|
|
325
|
+
const done = () => {
|
|
326
|
+
if (settled) return
|
|
327
|
+
settled = true
|
|
328
|
+
resolve()
|
|
329
|
+
}
|
|
330
|
+
try {
|
|
331
|
+
server = createServer((req, res) => {
|
|
332
|
+
onRequest(req, res).catch((err) => {
|
|
333
|
+
warnLog(ctx, `外部访问:处理请求失败(${err?.message ?? err})`)
|
|
334
|
+
try {
|
|
335
|
+
res.writeHead(500, { 'content-type': 'application/json' })
|
|
336
|
+
res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32603, message: 'Internal error' } }))
|
|
337
|
+
} catch { /* 已经回过了 */ }
|
|
338
|
+
})
|
|
339
|
+
})
|
|
340
|
+
} catch (err) {
|
|
341
|
+
failure = `建不了 HTTP 服务(${err?.code ?? err?.message ?? err})`
|
|
342
|
+
done()
|
|
343
|
+
return
|
|
344
|
+
}
|
|
345
|
+
server.on('error', (err) => {
|
|
346
|
+
failure = err?.code === 'EADDRINUSE'
|
|
347
|
+
? `端口 ${port} 已被占用(换一个 external.port,或关掉占用的进程)`
|
|
348
|
+
: `监听失败(${err?.code ?? err?.message ?? err})`
|
|
349
|
+
listening = false
|
|
350
|
+
warnLog(ctx, `外部访问端点起不来:${failure}`)
|
|
351
|
+
done()
|
|
352
|
+
})
|
|
353
|
+
server.on('listening', () => {
|
|
354
|
+
listening = true
|
|
355
|
+
boundPort = server.address()?.port ?? port
|
|
356
|
+
startedAt = Date.now()
|
|
357
|
+
done()
|
|
358
|
+
})
|
|
359
|
+
server.listen({ host: '127.0.0.1', port })
|
|
360
|
+
})
|
|
361
|
+
if (listening) await writeDiscovery()
|
|
362
|
+
return status()
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** 关掉监听并删掉发现文件(幂等)。 */
|
|
366
|
+
async function stop() {
|
|
367
|
+
const current = server
|
|
368
|
+
server = null
|
|
369
|
+
listening = false
|
|
370
|
+
if (current) {
|
|
371
|
+
await new Promise((resolve) => {
|
|
372
|
+
try {
|
|
373
|
+
current.close(() => resolve())
|
|
374
|
+
} catch {
|
|
375
|
+
resolve()
|
|
376
|
+
}
|
|
377
|
+
})
|
|
378
|
+
}
|
|
379
|
+
await dropDiscovery()
|
|
380
|
+
startedAt = 0
|
|
381
|
+
return status()
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** 面板读的状态(不含任何正文)。 */
|
|
385
|
+
function status() {
|
|
386
|
+
return {
|
|
387
|
+
listening,
|
|
388
|
+
port: listening ? boundPort : 0,
|
|
389
|
+
url: url(),
|
|
390
|
+
since: startedAt,
|
|
391
|
+
error: failure,
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
return { start, stop, status }
|
|
396
|
+
}
|