sage-mem 2.24.1 → 2.26.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 +69 -1
- package/README.md +69 -1
- package/lib/assembly/index.js +3 -0
- package/lib/assembly/mirror-mount.js +195 -0
- package/lib/client.js +599 -0
- package/lib/index.js +48 -3
- package/lib/intake/merge.js +193 -0
- package/lib/intake/policy.js +238 -0
- package/lib/intake/store.js +247 -0
- package/lib/memory/config.js +7 -15
- package/lib/mirror/export.js +224 -0
- package/lib/mirror/mcp.js +443 -0
- package/lib/mirror/policy.js +311 -0
- package/lib/settings.js +34 -6
- package/lib/shared/int-spec.js +28 -0
- package/lib/typert/schemas.js +105 -0
- package/lib/typert.host.js +51 -1
- package/package.json +1 -1
|
@@ -0,0 +1,443 @@
|
|
|
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 { validateSubmission } from '../intake/policy.js'
|
|
23
|
+
import { currentVersion } from '../update.js'
|
|
24
|
+
|
|
25
|
+
/** 认识且愿意应答的协议版本(按新到旧)。客户端报别的 → 回落最新一个。 */
|
|
26
|
+
const PROTOCOL_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05']
|
|
27
|
+
const PROTOCOL_FALLBACK = PROTOCOL_VERSIONS[0]
|
|
28
|
+
|
|
29
|
+
/** 请求体上限。三个工具的参数加起来不该接近这个数;超了就是走错门了。 */
|
|
30
|
+
const MAX_BODY_BYTES = 1024 * 1024
|
|
31
|
+
|
|
32
|
+
/** 片段长度上限(字符)。 */
|
|
33
|
+
const SNIPPET_MAX = 280
|
|
34
|
+
|
|
35
|
+
/** 工具数量与名字只在这里定义一次(`tools/list` 与分派共用)。 */
|
|
36
|
+
const TOOL_DEFS = Object.freeze([
|
|
37
|
+
{
|
|
38
|
+
name: 'memory_search',
|
|
39
|
+
description: '在**记忆副本**里按关键词检索(词面匹配,中文按双字切词)。返回条目名与片段;读全文请用 memory_read。只读,不返回文件路径。',
|
|
40
|
+
inputSchema: {
|
|
41
|
+
type: 'object',
|
|
42
|
+
properties: {
|
|
43
|
+
query: { type: 'string', description: '要检索的词或问句' },
|
|
44
|
+
limit: { type: 'integer', minimum: 1, maximum: 20, description: '最多返回几条,默认 5' },
|
|
45
|
+
},
|
|
46
|
+
required: ['query'],
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
name: 'memory_read',
|
|
51
|
+
description: '读一条记忆副本的全文。name 取 memory_search / memory_list 返回的名字(形如 project_xxx.md)。只读。',
|
|
52
|
+
inputSchema: {
|
|
53
|
+
type: 'object',
|
|
54
|
+
properties: { name: { type: 'string', description: '条目文件名,如 project_sage-mem.md' } },
|
|
55
|
+
required: ['name'],
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
name: 'memory_list',
|
|
60
|
+
description: '列出副本里全部可读条目(名字 + 一句话 + 类型 + 标签)。只读。',
|
|
61
|
+
inputSchema: { type: 'object', properties: {} },
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
// 2.26.0:写侧的唯一入口 —— 它不写记忆库,只把提交放进归并队列。
|
|
65
|
+
name: 'memory_submit',
|
|
66
|
+
description: '向用户提交一条记忆(进入归并队列,由用户逐条批准后才可能进主库;不会直接写入记忆库)。kind=new 提交一条完整的新记忆(只接受 type=project/reference);kind=patch 提交对现有条目的修改建议(永不自动写入)。格式见 initialize 的 instructions。',
|
|
67
|
+
inputSchema: {
|
|
68
|
+
type: 'object',
|
|
69
|
+
properties: {
|
|
70
|
+
kind: { type: 'string', enum: ['new', 'patch'], description: 'new = 新记忆;patch = 对现有条目的修改建议' },
|
|
71
|
+
source: { type: 'string', description: '你的名字,小写字母 / 数字 / 连字符,如 claude-code' },
|
|
72
|
+
name: { type: 'string', description: 'new:文件名(不带 .md,必须以 project_ 或 reference_ 开头);patch:目标条目的名字' },
|
|
73
|
+
description: { type: 'string', description: 'new 必填:一句话说明这条记忆是什么' },
|
|
74
|
+
type: { type: 'string', enum: ['project', 'reference'], description: 'new 必填:只接受 project / reference' },
|
|
75
|
+
tags: { type: 'array', items: { type: 'string' }, description: 'new 可选:最多 8 个标签' },
|
|
76
|
+
body: { type: 'string', description: 'new 必填:正文 markdown(不要自带 frontmatter)' },
|
|
77
|
+
changes: { type: 'string', description: 'patch 必填:要改的地方(引用原文片段)' },
|
|
78
|
+
suggested: { type: 'string', description: 'patch 必填:建议改成什么' },
|
|
79
|
+
reason: { type: 'string', description: 'patch 可选:为什么' },
|
|
80
|
+
},
|
|
81
|
+
required: ['kind', 'source', 'name'],
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
])
|
|
85
|
+
|
|
86
|
+
const INSTRUCTIONS = [
|
|
87
|
+
'这是一个记忆库端点:默认只能**读**(读的是主记忆库按白名单导出的副本)。',
|
|
88
|
+
'可用工具:memory_list(有哪些)/ memory_search(按关键词找)/ memory_read(读全文)/ memory_submit(提交一条记忆或修改建议)。',
|
|
89
|
+
'引用某条记忆时请带上它的 name(如 project_xxx.md),不要假设文件路径 —— 这里不提供路径。',
|
|
90
|
+
'',
|
|
91
|
+
'## memory_submit 的格式',
|
|
92
|
+
'- 提交**不会**直接写入用户的记忆库:它进入归并队列,由用户逐条批准。',
|
|
93
|
+
'- kind=new:必填 source / name / description / type / body;type 只能是 project 或 reference,且 name 要以对应的 project_ / reference_ 开头。正文不要自带 frontmatter。',
|
|
94
|
+
'- kind=patch:必填 source / name / changes / suggested;name 是**现有条目**的名字(不带 .md)。patch 永远不会自动写入,用户只会看到一份建议。',
|
|
95
|
+
'- 体积上限:正文 32 KB,整条 64 KB。格式不对会被当场拒绝(isError 里写明原因)。',
|
|
96
|
+
'- source 是你的**声明**(如 claude-code),不是凭证。',
|
|
97
|
+
].join('\n')
|
|
98
|
+
|
|
99
|
+
/** 正文 → 片段:去掉 frontmatter、压平空白、截断。 */
|
|
100
|
+
function snippetOf(content) {
|
|
101
|
+
const body = stripFrontmatterBlock(String(content ?? '')).replace(/\s+/g, ' ').trim()
|
|
102
|
+
return body.length > SNIPPET_MAX ? `${body.slice(0, SNIPPET_MAX)}…` : body
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** 参数不合法时的统一出口(MCP 的「工具执行失败」用 isError,不用 JSON-RPC 错误码)。 */
|
|
106
|
+
function toolError(text) {
|
|
107
|
+
return { content: [{ type: 'text', text }], isError: true }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function textResult(value) {
|
|
111
|
+
return { content: [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }] }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* 建一个 MCP 端点(**不自动启动**,由挂载层决定何时 start)。
|
|
116
|
+
*
|
|
117
|
+
* @param {object} opts
|
|
118
|
+
* @param {object} opts.ctx — 宿主上下文(只为 `warnLog`)
|
|
119
|
+
* @param {object} opts.exporter — `createMirrorExporter()` 的产物(只读面)
|
|
120
|
+
*/
|
|
121
|
+
export function createMirrorMcpServer({ ctx, exporter, intake }) {
|
|
122
|
+
let server = null
|
|
123
|
+
let listening = false
|
|
124
|
+
let boundPort = 0
|
|
125
|
+
let startedAt = 0
|
|
126
|
+
/** 端点自报的版本:**运行时**读 package.json(与 update.js 同一条理由:内联常量会与 bump 脱节)。 */
|
|
127
|
+
let serverVersion = ''
|
|
128
|
+
/** 起不来 / 中途失败的原因(空串 = 没问题)。 */
|
|
129
|
+
let failure = ''
|
|
130
|
+
|
|
131
|
+
const url = () => (listening ? `http://127.0.0.1:${boundPort}/mcp` : '')
|
|
132
|
+
|
|
133
|
+
/** 端点发现文件:只有在真的在听时才写(外部 agent 据此判断「现在能不能用」)。 */
|
|
134
|
+
async function writeDiscovery() {
|
|
135
|
+
const payload = {
|
|
136
|
+
name: 'sage-mem-mirror',
|
|
137
|
+
protocolVersion: PROTOCOL_FALLBACK,
|
|
138
|
+
url: url(),
|
|
139
|
+
transport: 'http',
|
|
140
|
+
tools: TOOL_DEFS.map((t) => t.name),
|
|
141
|
+
// 对**记忆库**只读;提交只进归并队列,不写主库(2.26.0)。
|
|
142
|
+
readOnly: true,
|
|
143
|
+
acceptsSubmissions: true,
|
|
144
|
+
generatedAt: new Date().toISOString(),
|
|
145
|
+
}
|
|
146
|
+
try {
|
|
147
|
+
await writeFileAtomic(exporter.mcpFile, `${JSON.stringify(payload, null, 2)}\n`)
|
|
148
|
+
} catch (err) {
|
|
149
|
+
// 发现文件写不出来不影响端点本身可用(面板里仍有地址)。
|
|
150
|
+
warnLog(ctx, `外部访问:写不了端点发现文件(${err?.code ?? err?.message ?? err})`)
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function dropDiscovery() {
|
|
155
|
+
await unlink(exporter.mcpFile).catch(() => {})
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// ── 三个工具 ───────────────────────────────────────────────────────
|
|
159
|
+
|
|
160
|
+
async function toolSearch(args) {
|
|
161
|
+
const query = typeof args?.query === 'string' ? args.query.trim() : ''
|
|
162
|
+
if (query === '') return toolError('memory_search 需要非空的 query')
|
|
163
|
+
const rawLimit = Number(args?.limit)
|
|
164
|
+
const limit = Number.isFinite(rawLimit) ? Math.max(1, Math.min(20, Math.round(rawLimit))) : 5
|
|
165
|
+
const corpus = await exporter.listMirrorEntries()
|
|
166
|
+
if (corpus.length === 0) return textResult({ query, corpus: 0, hits: [] })
|
|
167
|
+
const docs = corpus.map((e) => {
|
|
168
|
+
const tokens = tokenize(`${e.title} ${e.description} ${e.content}`)
|
|
169
|
+
return { entry: e, tokens, tf: termFreq(tokens), dl: tokens.length }
|
|
170
|
+
})
|
|
171
|
+
const stats = buildStats(docs.map((d) => ({ tokens: d.tokens })))
|
|
172
|
+
const terms = queryTermsOf(query)
|
|
173
|
+
const scored = []
|
|
174
|
+
for (const d of docs) {
|
|
175
|
+
const score = scoreDoc(terms, d.tf, d.dl, stats)
|
|
176
|
+
if (score > 0) scored.push({ score, entry: d.entry })
|
|
177
|
+
}
|
|
178
|
+
scored.sort((a, b) => b.score - a.score)
|
|
179
|
+
return textResult({
|
|
180
|
+
query,
|
|
181
|
+
corpus: corpus.length,
|
|
182
|
+
hits: scored.slice(0, limit).map(({ entry }) => ({
|
|
183
|
+
name: entry.name,
|
|
184
|
+
title: entry.title,
|
|
185
|
+
description: entry.description,
|
|
186
|
+
type: entry.type,
|
|
187
|
+
tags: entry.tags,
|
|
188
|
+
snippet: snippetOf(entry.content),
|
|
189
|
+
})),
|
|
190
|
+
})
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async function toolRead(args) {
|
|
194
|
+
const name = typeof args?.name === 'string' ? args.name.trim() : ''
|
|
195
|
+
if (!isMirrorReadableName(name)) return toolError('memory_read 的 name 必须是副本里的单段 .md 名字(如 project_xxx.md)')
|
|
196
|
+
const content = await exporter.readMirrorEntry(name)
|
|
197
|
+
if (content === null) return toolError(`副本里没有这条记忆:${name}(用 memory_list 看看现在有哪些)`)
|
|
198
|
+
return textResult(content)
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async function toolList() {
|
|
202
|
+
const corpus = await exporter.listMirrorEntries()
|
|
203
|
+
return textResult({
|
|
204
|
+
corpus: corpus.length,
|
|
205
|
+
entries: corpus.map((e) => ({ name: e.name, title: e.title, description: e.description, type: e.type, tags: e.tags })),
|
|
206
|
+
})
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* 提交一条记忆(2.26.0)。**全端点唯一的写入口**,而且它只写 intake/ —— 主库要人批准。
|
|
211
|
+
*
|
|
212
|
+
* 两道闸:开关(用户是否允许接收)+ 校验(格式不对当场拒,连 pending 都进不去)。
|
|
213
|
+
*/
|
|
214
|
+
async function toolSubmit(args) {
|
|
215
|
+
if (!intake || !intake.store) return toolError('这个端点没有开启接收提交')
|
|
216
|
+
if (!intake.acceptSubmissions()) {
|
|
217
|
+
return toolError('用户没有打开「接收外来提交」(external.acceptSubmissions=0)。请把这条内容直接告诉用户,或请他们开启后再提交。')
|
|
218
|
+
}
|
|
219
|
+
const check = validateSubmission(args)
|
|
220
|
+
if (!check.ok) return toolError(`提交被拒:${check.error}`)
|
|
221
|
+
const saved = await intake.store.save(check.submission)
|
|
222
|
+
if (!saved.ok) return toolError(`提交没落盘:${saved.error}`)
|
|
223
|
+
return textResult({ ok: true, id: saved.id, status: 'pending', note: '已进入归并队列,等待用户批准;不会直接写入记忆库' })
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** 工具名 → 实现。读的三个 + 一个只写 intake 的提交口。 */
|
|
227
|
+
const TOOLS = Object.freeze({ memory_search: toolSearch, memory_read: toolRead, memory_list: toolList, memory_submit: toolSubmit })
|
|
228
|
+
|
|
229
|
+
// ── JSON-RPC 分派 ──────────────────────────────────────────────────
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* 处理一条 JSON-RPC 消息。
|
|
233
|
+
* @returns {Promise<{status:number, body:object|null}>} `body === null` 表示「通知,不回包」
|
|
234
|
+
*/
|
|
235
|
+
async function dispatch(message) {
|
|
236
|
+
if (!message || typeof message !== 'object' || Array.isArray(message)) {
|
|
237
|
+
return { status: 400, body: { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid Request' } } }
|
|
238
|
+
}
|
|
239
|
+
const id = message.id
|
|
240
|
+
const isNotification = id === undefined || id === null
|
|
241
|
+
const method = typeof message.method === 'string' ? message.method : ''
|
|
242
|
+
const fail = (code, msg) => ({ status: 200, body: { jsonrpc: '2.0', id: id ?? null, error: { code, message: msg } } })
|
|
243
|
+
if (method === '') return isNotification ? { status: 202, body: null } : fail(-32600, 'Invalid Request')
|
|
244
|
+
|
|
245
|
+
if (method === 'initialize') {
|
|
246
|
+
const asked = message.params?.protocolVersion
|
|
247
|
+
const protocolVersion = PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_FALLBACK
|
|
248
|
+
return {
|
|
249
|
+
status: 200,
|
|
250
|
+
body: {
|
|
251
|
+
jsonrpc: '2.0',
|
|
252
|
+
id: id ?? null,
|
|
253
|
+
result: {
|
|
254
|
+
protocolVersion,
|
|
255
|
+
capabilities: { tools: { listChanged: false } },
|
|
256
|
+
serverInfo: { name: 'sage-mem-mirror', version: serverVersion || 'unknown' },
|
|
257
|
+
instructions: INSTRUCTIONS,
|
|
258
|
+
},
|
|
259
|
+
},
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
// 通知:客户端说「我初始化好了」。无回包。
|
|
263
|
+
if (method.startsWith('notifications/')) return { status: 202, body: null }
|
|
264
|
+
if (method === 'ping') return { status: 200, body: { jsonrpc: '2.0', id: id ?? null, result: {} } }
|
|
265
|
+
if (method === 'tools/list') {
|
|
266
|
+
return { status: 200, body: { jsonrpc: '2.0', id: id ?? null, result: { tools: TOOL_DEFS.map((t) => ({ ...t })) } } }
|
|
267
|
+
}
|
|
268
|
+
if (method === 'tools/call') {
|
|
269
|
+
const name = message.params?.name
|
|
270
|
+
const impl = TOOLS[name]
|
|
271
|
+
if (!impl) return fail(-32602, `Unknown tool: ${String(name)}`)
|
|
272
|
+
try {
|
|
273
|
+
const result = await impl(message.params?.arguments ?? {})
|
|
274
|
+
return { status: 200, body: { jsonrpc: '2.0', id: id ?? null, result } }
|
|
275
|
+
} catch (err) {
|
|
276
|
+
warnLog(ctx, `外部访问:工具 ${name} 出错(${err?.message ?? err})`)
|
|
277
|
+
return { status: 200, body: { jsonrpc: '2.0', id: id ?? null, result: toolError(`工具执行失败:${err?.message ?? err}`) } }
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return fail(-32601, `Method not found: ${method}`)
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** 读请求体(带上限)。超限先回 413、再把剩下的请求排干(不缓存)。 */
|
|
284
|
+
function readBody(req, res) {
|
|
285
|
+
return new Promise((resolve) => {
|
|
286
|
+
const chunks = []
|
|
287
|
+
let size = 0
|
|
288
|
+
/** 已经回过 413:后面只排干,不再缓存。 */
|
|
289
|
+
let overflow = false
|
|
290
|
+
req.on('data', (chunk) => {
|
|
291
|
+
size += chunk.length
|
|
292
|
+
if (overflow) {
|
|
293
|
+
// 极端情况(有人往回环口灌包):超过 8 倍上限就直接断,不留一条无限长的排干。
|
|
294
|
+
if (size > MAX_BODY_BYTES * 8) req.destroy()
|
|
295
|
+
return
|
|
296
|
+
}
|
|
297
|
+
if (size > MAX_BODY_BYTES) {
|
|
298
|
+
overflow = true
|
|
299
|
+
chunks.length = 0
|
|
300
|
+
res.writeHead(413, { 'content-type': 'application/json' })
|
|
301
|
+
res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Request body too large' } }))
|
|
302
|
+
return
|
|
303
|
+
}
|
|
304
|
+
chunks.push(chunk)
|
|
305
|
+
})
|
|
306
|
+
req.on('end', () => {
|
|
307
|
+
if (overflow) { resolve(null); return }
|
|
308
|
+
resolve(Buffer.concat(chunks).toString('utf8'))
|
|
309
|
+
})
|
|
310
|
+
req.on('error', () => resolve(null))
|
|
311
|
+
})
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
async function onRequest(req, res) {
|
|
315
|
+
// GET:给人和探针看的一份状态(不含任何记忆正文)。
|
|
316
|
+
if (req.method === 'GET') {
|
|
317
|
+
res.writeHead(200, { 'content-type': 'application/json' })
|
|
318
|
+
res.end(JSON.stringify({ name: 'sage-mem-mirror', readOnly: true, waitingFor: 'POST JSON-RPC 2.0', ...status() }))
|
|
319
|
+
return
|
|
320
|
+
}
|
|
321
|
+
if (req.method !== 'POST') {
|
|
322
|
+
res.writeHead(405, { 'content-type': 'application/json', allow: 'POST, GET' })
|
|
323
|
+
res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Method Not Allowed' } }))
|
|
324
|
+
return
|
|
325
|
+
}
|
|
326
|
+
const raw = await readBody(req, res)
|
|
327
|
+
if (raw === null) return
|
|
328
|
+
let parsed
|
|
329
|
+
try {
|
|
330
|
+
parsed = JSON.parse(raw)
|
|
331
|
+
} catch {
|
|
332
|
+
res.writeHead(200, { 'content-type': 'application/json' })
|
|
333
|
+
res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }))
|
|
334
|
+
return
|
|
335
|
+
}
|
|
336
|
+
// 允许一次发一批(JSON-RPC batch):MCP 客户端偶尔这么干。
|
|
337
|
+
if (Array.isArray(parsed)) {
|
|
338
|
+
const out = []
|
|
339
|
+
for (const one of parsed) {
|
|
340
|
+
const r = await dispatch(one)
|
|
341
|
+
if (r.body !== null) out.push(r.body)
|
|
342
|
+
}
|
|
343
|
+
if (out.length === 0) {
|
|
344
|
+
res.writeHead(202)
|
|
345
|
+
res.end()
|
|
346
|
+
return
|
|
347
|
+
}
|
|
348
|
+
res.writeHead(200, { 'content-type': 'application/json' })
|
|
349
|
+
res.end(JSON.stringify(out))
|
|
350
|
+
return
|
|
351
|
+
}
|
|
352
|
+
const result = await dispatch(parsed)
|
|
353
|
+
if (result.body === null) {
|
|
354
|
+
res.writeHead(result.status)
|
|
355
|
+
res.end()
|
|
356
|
+
return
|
|
357
|
+
}
|
|
358
|
+
res.writeHead(result.status, { 'content-type': 'application/json' })
|
|
359
|
+
res.end(JSON.stringify(result.body))
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* 开始监听。**不抛**:端口被占用等失败一律通过返回值 + `status()` 表达。
|
|
364
|
+
* @param {number} port — 从设置来的端口(1024–65535)
|
|
365
|
+
*/
|
|
366
|
+
async function start(port) {
|
|
367
|
+
if (listening) return status()
|
|
368
|
+
failure = ''
|
|
369
|
+
serverVersion = await currentVersion()
|
|
370
|
+
await new Promise((resolve) => {
|
|
371
|
+
let settled = false
|
|
372
|
+
const done = () => {
|
|
373
|
+
if (settled) return
|
|
374
|
+
settled = true
|
|
375
|
+
resolve()
|
|
376
|
+
}
|
|
377
|
+
try {
|
|
378
|
+
server = createServer((req, res) => {
|
|
379
|
+
onRequest(req, res).catch((err) => {
|
|
380
|
+
warnLog(ctx, `外部访问:处理请求失败(${err?.message ?? err})`)
|
|
381
|
+
try {
|
|
382
|
+
res.writeHead(500, { 'content-type': 'application/json' })
|
|
383
|
+
res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32603, message: 'Internal error' } }))
|
|
384
|
+
} catch { /* 已经回过了 */ }
|
|
385
|
+
})
|
|
386
|
+
})
|
|
387
|
+
} catch (err) {
|
|
388
|
+
failure = `建不了 HTTP 服务(${err?.code ?? err?.message ?? err})`
|
|
389
|
+
done()
|
|
390
|
+
return
|
|
391
|
+
}
|
|
392
|
+
server.on('error', (err) => {
|
|
393
|
+
failure = err?.code === 'EADDRINUSE'
|
|
394
|
+
? `端口 ${port} 已被占用(换一个 external.port,或关掉占用的进程)`
|
|
395
|
+
: `监听失败(${err?.code ?? err?.message ?? err})`
|
|
396
|
+
listening = false
|
|
397
|
+
warnLog(ctx, `外部访问端点起不来:${failure}`)
|
|
398
|
+
done()
|
|
399
|
+
})
|
|
400
|
+
server.on('listening', () => {
|
|
401
|
+
listening = true
|
|
402
|
+
boundPort = server.address()?.port ?? port
|
|
403
|
+
startedAt = Date.now()
|
|
404
|
+
done()
|
|
405
|
+
})
|
|
406
|
+
server.listen({ host: '127.0.0.1', port })
|
|
407
|
+
})
|
|
408
|
+
if (listening) await writeDiscovery()
|
|
409
|
+
return status()
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** 关掉监听并删掉发现文件(幂等)。 */
|
|
413
|
+
async function stop() {
|
|
414
|
+
const current = server
|
|
415
|
+
server = null
|
|
416
|
+
listening = false
|
|
417
|
+
if (current) {
|
|
418
|
+
await new Promise((resolve) => {
|
|
419
|
+
try {
|
|
420
|
+
current.close(() => resolve())
|
|
421
|
+
} catch {
|
|
422
|
+
resolve()
|
|
423
|
+
}
|
|
424
|
+
})
|
|
425
|
+
}
|
|
426
|
+
await dropDiscovery()
|
|
427
|
+
startedAt = 0
|
|
428
|
+
return status()
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/** 面板读的状态(不含任何正文)。 */
|
|
432
|
+
function status() {
|
|
433
|
+
return {
|
|
434
|
+
listening,
|
|
435
|
+
port: listening ? boundPort : 0,
|
|
436
|
+
url: url(),
|
|
437
|
+
since: startedAt,
|
|
438
|
+
error: failure,
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
return { start, stop, status }
|
|
443
|
+
}
|