dsh-macro-memory 0.0.0-stage → 0.4.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.
Files changed (132) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +506 -2
  3. package/cordis.patch.yml +6 -0
  4. package/lib/client.js +3623 -0
  5. package/lib/index.js +502 -0
  6. package/lib/macro/brand.js +82 -0
  7. package/lib/macro/bridge.js +158 -0
  8. package/lib/macro/chain.js +206 -0
  9. package/lib/macro/contract.js +471 -0
  10. package/lib/macro/cost.js +164 -0
  11. package/lib/macro/defs/admin.js +442 -0
  12. package/lib/macro/defs/dream.js +24 -0
  13. package/lib/macro/defs/link.js +257 -0
  14. package/lib/macro/defs/project.js +25 -0
  15. package/lib/macro/defs/read.js +160 -0
  16. package/lib/macro/defs/remember.js +411 -0
  17. package/lib/macro/defs/search.js +871 -0
  18. package/lib/macro/defs/update.js +161 -0
  19. package/lib/macro/dreamledger.js +1398 -0
  20. package/lib/macro/facade.js +135 -0
  21. package/lib/macro/fusion.js +182 -0
  22. package/lib/macro/linkflow.js +391 -0
  23. package/lib/macro/links.js +448 -0
  24. package/lib/macro/neighbor.js +209 -0
  25. package/lib/macro/panel.js +96 -0
  26. package/lib/macro/prompt.js +139 -0
  27. package/lib/macro/provenance.js +148 -0
  28. package/lib/macro/render.js +35 -0
  29. package/lib/macro/revisions.js +253 -0
  30. package/lib/macro/shared.js +113 -0
  31. package/lib/macro/store.js +103 -0
  32. package/lib/macro/supersede.js +197 -0
  33. package/lib/macro/tokencost.js +90 -0
  34. package/lib/macro/tools.js +67 -0
  35. package/package.json +54 -4
  36. package/vendor/VENDOR.json +23 -0
  37. package/vendor/dsh-memory-nebula/CONTRIBUTING.md +48 -0
  38. package/vendor/dsh-memory-nebula/LICENSE +21 -0
  39. package/vendor/dsh-memory-nebula/README.en.md +203 -0
  40. package/vendor/dsh-memory-nebula/README.md +253 -0
  41. package/vendor/dsh-memory-nebula/SECURITY.md +43 -0
  42. package/vendor/dsh-memory-nebula/SUPPORT.md +33 -0
  43. package/vendor/dsh-memory-nebula/cordis.patch.yml +4 -0
  44. package/vendor/dsh-memory-nebula/lib/client.js +105 -0
  45. package/vendor/dsh-memory-nebula/lib/host/adapters/index.js +279 -0
  46. package/vendor/dsh-memory-nebula/lib/host/adapters/ingest.js +230 -0
  47. package/vendor/dsh-memory-nebula/lib/host/adapters/meow.js +320 -0
  48. package/vendor/dsh-memory-nebula/lib/host/adapters/notes.js +305 -0
  49. package/vendor/dsh-memory-nebula/lib/host/adapters/sqlite.js +287 -0
  50. package/vendor/dsh-memory-nebula/lib/host/adapters/util.js +231 -0
  51. package/vendor/dsh-memory-nebula/lib/host/bridge.js +351 -0
  52. package/vendor/dsh-memory-nebula/lib/host/compress.js +97 -0
  53. package/vendor/dsh-memory-nebula/lib/host/demo.js +357 -0
  54. package/vendor/dsh-memory-nebula/lib/host/diagnostics.js +125 -0
  55. package/vendor/dsh-memory-nebula/lib/host/doctor.js +270 -0
  56. package/vendor/dsh-memory-nebula/lib/host/entities.js +230 -0
  57. package/vendor/dsh-memory-nebula/lib/host/graph.js +1762 -0
  58. package/vendor/dsh-memory-nebula/lib/host/graphcache.js +290 -0
  59. package/vendor/dsh-memory-nebula/lib/host/http.js +993 -0
  60. package/vendor/dsh-memory-nebula/lib/host/injectcfg.js +95 -0
  61. package/vendor/dsh-memory-nebula/lib/host/ledger.js +175 -0
  62. package/vendor/dsh-memory-nebula/lib/host/live.js +204 -0
  63. package/vendor/dsh-memory-nebula/lib/host/nebula.js +2105 -0
  64. package/vendor/dsh-memory-nebula/lib/host/page.js +75 -0
  65. package/vendor/dsh-memory-nebula/lib/host/path.js +83 -0
  66. package/vendor/dsh-memory-nebula/lib/host/recall.js +524 -0
  67. package/vendor/dsh-memory-nebula/lib/host/share.js +633 -0
  68. package/vendor/dsh-memory-nebula/lib/host/sources.js +266 -0
  69. package/vendor/dsh-memory-nebula/lib/host/store.js +333 -0
  70. package/vendor/dsh-memory-nebula/lib/host/text.js +410 -0
  71. package/vendor/dsh-memory-nebula/lib/host/transcripts.js +396 -0
  72. package/vendor/dsh-memory-nebula/lib/index.js +782 -0
  73. package/vendor/dsh-memory-nebula/lib/standalone.mjs +315 -0
  74. package/vendor/dsh-memory-nebula/lib/web/api.js +426 -0
  75. package/vendor/dsh-memory-nebula/lib/web/app.js +4172 -0
  76. package/vendor/dsh-memory-nebula/lib/web/i18n.js +580 -0
  77. package/vendor/dsh-memory-nebula/lib/web/index.html +174 -0
  78. package/vendor/dsh-memory-nebula/lib/web/nav.js +132 -0
  79. package/vendor/dsh-memory-nebula/lib/web/render.js +1890 -0
  80. package/vendor/dsh-memory-nebula/lib/web/space3d.js +1883 -0
  81. package/vendor/dsh-memory-nebula/lib/web/style.css +1402 -0
  82. package/vendor/dsh-memory-nebula/locale/en.json +7 -0
  83. package/vendor/dsh-memory-nebula/locale/zh.json +7 -0
  84. package/vendor/dsh-memory-nebula/market/assets/icon-180.png +0 -0
  85. package/vendor/dsh-memory-nebula/market/assets/icon.svg +40 -0
  86. package/vendor/dsh-memory-nebula/market/index.json +101 -0
  87. package/vendor/dsh-memory-nebula/package.json +87 -0
  88. package/vendor/dsh-memory-nebula/sidecar.ps1 +119 -0
  89. package/vendor/meow-memory/LICENSE +21 -0
  90. package/vendor/meow-memory/README.en.md +192 -0
  91. package/vendor/meow-memory/README.md +174 -0
  92. package/vendor/meow-memory/README.pt-br.md +180 -0
  93. package/vendor/meow-memory/cordis.patch.yml +7 -0
  94. package/vendor/meow-memory/lib/client.js +3344 -0
  95. package/vendor/meow-memory/lib/client.js.map +7 -0
  96. package/vendor/meow-memory/lib/index.js +9802 -0
  97. package/vendor/meow-memory/lib/index.js.map +7 -0
  98. package/vendor/meow-memory/lib/prompts/README.md +65 -0
  99. package/vendor/meow-memory/lib/prompts/en/dream-atomic.md +36 -0
  100. package/vendor/meow-memory/lib/prompts/en/dream-header.md +9 -0
  101. package/vendor/meow-memory/lib/prompts/en/dream-project-summary.md +12 -0
  102. package/vendor/meow-memory/lib/prompts/en/dream-topic.md +27 -0
  103. package/vendor/meow-memory/lib/prompts/en/external-memory-notice.md +8 -0
  104. package/vendor/meow-memory/lib/prompts/en/first-create-notice.md +8 -0
  105. package/vendor/meow-memory/lib/prompts/en/labels.md +98 -0
  106. package/vendor/meow-memory/lib/prompts/en/reflect.md +31 -0
  107. package/vendor/meow-memory/lib/prompts/en/system-guide.md +121 -0
  108. package/vendor/meow-memory/lib/prompts/en/tools.md +83 -0
  109. package/vendor/meow-memory/lib/prompts/en/welcome-guide.md +12 -0
  110. package/vendor/meow-memory/lib/prompts/pt-br/dream-atomic.md +36 -0
  111. package/vendor/meow-memory/lib/prompts/pt-br/dream-header.md +9 -0
  112. package/vendor/meow-memory/lib/prompts/pt-br/dream-project-summary.md +12 -0
  113. package/vendor/meow-memory/lib/prompts/pt-br/dream-topic.md +27 -0
  114. package/vendor/meow-memory/lib/prompts/pt-br/external-memory-notice.md +8 -0
  115. package/vendor/meow-memory/lib/prompts/pt-br/first-create-notice.md +8 -0
  116. package/vendor/meow-memory/lib/prompts/pt-br/labels.md +98 -0
  117. package/vendor/meow-memory/lib/prompts/pt-br/reflect.md +31 -0
  118. package/vendor/meow-memory/lib/prompts/pt-br/system-guide.md +121 -0
  119. package/vendor/meow-memory/lib/prompts/pt-br/tools.md +83 -0
  120. package/vendor/meow-memory/lib/prompts/pt-br/welcome-guide.md +12 -0
  121. package/vendor/meow-memory/lib/prompts/zh/dream-atomic.md +36 -0
  122. package/vendor/meow-memory/lib/prompts/zh/dream-header.md +9 -0
  123. package/vendor/meow-memory/lib/prompts/zh/dream-project-summary.md +19 -0
  124. package/vendor/meow-memory/lib/prompts/zh/dream-topic.md +27 -0
  125. package/vendor/meow-memory/lib/prompts/zh/external-memory-notice.md +8 -0
  126. package/vendor/meow-memory/lib/prompts/zh/first-create-notice.md +8 -0
  127. package/vendor/meow-memory/lib/prompts/zh/labels.md +98 -0
  128. package/vendor/meow-memory/lib/prompts/zh/reflect.md +30 -0
  129. package/vendor/meow-memory/lib/prompts/zh/system-guide.md +119 -0
  130. package/vendor/meow-memory/lib/prompts/zh/tools.md +83 -0
  131. package/vendor/meow-memory/lib/prompts/zh/welcome-guide.md +12 -0
  132. package/vendor/meow-memory/package.json +64 -0
@@ -0,0 +1,993 @@
1
+ /**
2
+ * 记忆星图的 HTTP 接口 + 静态页面。[macro-fusion 0.2.11]
3
+ *
4
+ * 全部挂在同一个源上(DSH 的 webServer),所以 iframe 里可以直接 fetch,
5
+ * 不用处理跨域、也不用另起端口。
6
+ */
7
+ import { readFileSync, statSync, readdirSync } from 'node:fs'
8
+ import { createHash, timingSafeEqual } from 'node:crypto'
9
+ import { join, dirname } from 'node:path'
10
+ import { fileURLToPath } from 'node:url'
11
+ import { buildShareHtml, parseShareHide, parseShareHops, parseShareLimit, parseShareScope } from './share.js'
12
+ import { buildDiagnostics, formatDiagnostics } from './diagnostics.js'
13
+ import { compressBuffer, isCompressibleType, mergeVary, pickEncoding, MIN_COMPRESS_BYTES } from './compress.js'
14
+
15
+ const HERE = dirname(fileURLToPath(import.meta.url))
16
+ const WEB_DIR = join(HERE, '..', 'web')
17
+ const PKG = (() => {
18
+ try {
19
+ return JSON.parse(readFileSync(join(HERE, '..', '..', 'package.json'), 'utf8'))
20
+ } catch {
21
+ return {}
22
+ }
23
+ })()
24
+
25
+ /** 插件版本(/ping 里给页面与 smoke 看版本漂移)。 */
26
+ const VERSION = String(PKG.version || '0.0.0')
27
+ /** 这一次进程是什么时候把模块读进来的 —— 排查「跑的是旧代码」比 mtime 更直接。 */
28
+ const STARTED_AT = Date.now()
29
+
30
+ /**
31
+ * 代码指纹:lib 下所有宿主模块(不含 web)的 mtime 最大值。
32
+ *
33
+ * 以前只硬编码了 8 个文件,于是改 bridge.js / ledger.js / path.js 时指纹不变,
34
+ * 页面会误判「宿主和独立引擎一样新」,继续用缺接口的旧进程。现在递归扫全量。
35
+ */
36
+ const BUILD = (() => {
37
+ let max = 0
38
+ const walk = (dir) => {
39
+ let entries
40
+ try {
41
+ entries = readdirSync(dir, { withFileTypes: true })
42
+ } catch {
43
+ return
44
+ }
45
+ for (const ent of entries) {
46
+ const p = join(dir, ent.name)
47
+ if (ent.isDirectory()) {
48
+ if (ent.name !== 'web' && ent.name !== 'node_modules' && ent.name !== 'ingest') walk(p)
49
+ continue
50
+ }
51
+ if (!/\.m?js$/.test(ent.name)) continue
52
+ try {
53
+ max = Math.max(max, statSync(p).mtimeMs)
54
+ } catch {}
55
+ }
56
+ }
57
+ walk(join(HERE, '..'))
58
+ return Math.round(max)
59
+ })()
60
+
61
+ /** 这个版本提供的接口清单:旧宿主缺哪些,页面一眼能说清。 */
62
+ export const CAPABILITIES = Object.freeze([
63
+ 'ping', 'graph', 'node', 'recall', 'path', 'overview', 'mutes', 'link', 'unlink',
64
+ 'mute', 'unmute', 'bridge', 'sources', 'ingest', 'ledger', 'export', 'refresh',
65
+ // 0.5.0:内存里的示例星系(?demo=1)与可带走的单文件快照(/share)
66
+ // 1.11.32:建图期间的进度(只报阶段,不阻塞)。
67
+ 'progress',
68
+ // 1.11.46:体检单独一条(20 万条要 12.9 秒,不该压在「打开面板」那一趟上)。
69
+ 'hygiene',
70
+ 'demo', 'share',
71
+ // 1.0.0:给支持用的一键诊断(只报告版本/环境/图规模,不读正文、不带路径)
72
+ 'diagnostics',
73
+ ])
74
+
75
+ const PREFIX = '/api/memory-nebula'
76
+
77
+ /**
78
+ * ETag 里只能出现可见 ASCII(RFC 7232 的 opaque-tag,Node 还会更严格:
79
+ * 非 ASCII 直接抛 ERR_INVALID_CHAR)。签名里可能有中文(来源标题、工作区目录名),
80
+ * 所以非 ASCII 一律哈希成十六进制——语义仍是「同一个签名 → 同一个标签」。
81
+ */
82
+ function etagSafe(text) {
83
+ const raw = String(text || '0').replace(/["\\]/g, '')
84
+ if (/^[\x20-\x7e]*$/.test(raw) && raw.length > 0) return raw
85
+ return createHash('sha1').update(String(text || '0')).digest('hex').slice(0, 20)
86
+ }
87
+
88
+ /**
89
+ * 本机来源判定。写接口只接受「没有 Origin 的本机客户端(curl / 脚本)」或
90
+ * 「loopback 页面」。一个公网网页即使能向 127.0.0.1 发 POST,也会被挡在这里,
91
+ * 否则随便一个页面就能 mute 掉你的关联、往星图里灌垃圾。
92
+ */
93
+ export function isLoopbackOrigin(origin) {
94
+ if (!origin) return true
95
+ try {
96
+ const u = new URL(String(origin))
97
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') return false
98
+ return u.hostname === '127.0.0.1' || u.hostname === 'localhost' || u.hostname === '::1' || u.hostname === '[::1]'
99
+ } catch {
100
+ return false
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Host 只接受回环名。挡 DNS rebinding:恶意域名解析到 127.0.0.1 后,
106
+ * 浏览器发出的 GET 不带 Origin,但 Host 仍是 evil.example,这里能拦住。
107
+ */
108
+ export function isLoopbackHost(host) {
109
+ const raw = String(host || '').trim().toLowerCase()
110
+ if (!raw) return false
111
+ let name = raw
112
+ if (raw.startsWith('[')) {
113
+ const end = raw.indexOf(']')
114
+ if (end < 0) return false
115
+ name = raw.slice(0, end + 1)
116
+ } else {
117
+ const colon = raw.indexOf(':')
118
+ if (colon >= 0) name = raw.slice(0, colon)
119
+ }
120
+ return name === '127.0.0.1' || name === 'localhost' || name === '::1' || name === '[::1]'
121
+ }
122
+
123
+
124
+ function allowWrite(req) {
125
+ if (!isLoopbackOrigin(req.headers.origin)) return false
126
+ if (String(req.headers['sec-fetch-site'] || '').toLowerCase() === 'cross-site') return false
127
+ return true
128
+ }
129
+
130
+ /** 可选的本机口令:常量时间比较,不把 token 写进日志。 */
131
+ function sameSecret(a, b) {
132
+ const left = Buffer.from(String(a || ''))
133
+ const right = Buffer.from(String(b || ''))
134
+ return left.length === right.length && left.length > 0 && timingSafeEqual(left, right)
135
+ }
136
+
137
+ function cookieToken(req) {
138
+ const cookie = String(req.headers.cookie || '')
139
+ for (const part of cookie.split(';')) {
140
+ const at = part.indexOf('=')
141
+ if (at < 0) continue
142
+ if (part.slice(0, at).trim() !== 'nb_token') continue
143
+ try {
144
+ return decodeURIComponent(part.slice(at + 1).trim())
145
+ } catch {
146
+ return ''
147
+ }
148
+ }
149
+ return ''
150
+ }
151
+
152
+ function hasToken(req, url, token) {
153
+ const auth = String(req.headers.authorization || '')
154
+ if (auth.startsWith('Bearer ') && sameSecret(auth.slice(7).trim(), token)) return true
155
+ if (sameSecret(cookieToken(req), token)) return true
156
+ return sameSecret(url.searchParams.get('token') || '', token)
157
+ }
158
+
159
+
160
+ /** 跨端口调用(宿主页面 ↔ 独立引擎)需要 CORS;只对本机页面开放。 */
161
+ export function corsHeaders(req) {
162
+ const origin = req.headers.origin
163
+ if (!origin || !isLoopbackOrigin(origin)) return {}
164
+ return { 'access-control-allow-origin': origin, vary: 'Origin' }
165
+ }
166
+
167
+ const MIME = {
168
+ '.html': 'text/html; charset=utf-8',
169
+ '.js': 'text/javascript; charset=utf-8',
170
+ '.css': 'text/css; charset=utf-8',
171
+ '.svg': 'image/svg+xml',
172
+ '.json': 'application/json; charset=utf-8',
173
+ }
174
+
175
+ /** 只允许这几个文件,避免路径穿越。 */
176
+ const STATIC = new Set(['index.html', 'style.css', 'app.js', 'api.js', 'render.js', 'space3d.js', 'i18n.js', 'nav.js'])
177
+
178
+ const esc = (s) =>
179
+ String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c])
180
+
181
+ /** 口令门的登录页:不加载任何脚本,只提交一个表单。 */
182
+ function sendUnlockPage(res, message = '', status = 401) {
183
+ const body = Buffer.from(`<!doctype html>
184
+ <html lang="zh-CN"><head><meta charset="utf-8" />
185
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
186
+ <title>宏记忆 · 星图 · 需要口令</title>
187
+ <style>
188
+ :root{color-scheme:dark}*{box-sizing:border-box}
189
+ body{margin:0;min-height:100vh;display:grid;place-items:center;background:#070b12;color:#dbe7f3;
190
+ font:15px/1.6 "Segoe UI",system-ui,sans-serif}
191
+ .card{width:min(92vw,380px);padding:28px 26px;border:1px solid #213040;border-radius:16px;
192
+ background:linear-gradient(160deg,#0b1420,#08101a);box-shadow:0 20px 60px #0008}
193
+ h1{margin:0 0 6px;font-size:18px;letter-spacing:.02em}
194
+ p{margin:0 0 18px;color:#8fa6bd;font-size:13px}
195
+ input{width:100%;padding:11px 12px;border:1px solid #2b3d50;border-radius:10px;background:#07101a;
196
+ color:#e8f2fb;font:inherit;outline:none}
197
+ input:focus{border-color:#3fa7a0;box-shadow:0 0 0 3px #3fa7a033}
198
+ button{width:100%;margin-top:12px;padding:11px 12px;border:0;border-radius:10px;background:#3fa7a0;
199
+ color:#04110f;font:600 14px/1 inherit;cursor:pointer}
200
+ button:hover{background:#4dbdb5}
201
+ .err{margin:0 0 12px;color:#ff9a9a;font-size:12.5px}
202
+ .foot{margin-top:16px;color:#647b92;font-size:11.5px}
203
+ </style></head>
204
+ <body><main class="card">
205
+ <h1>需要本机口令</h1>
206
+ <p>这个独立引擎用 <code>--token</code> 启动。输入启动时设置的口令,浏览器会记住它。</p>
207
+ ${message ? `<p class="err">${esc(message)}</p>` : ''}
208
+ <form method="post" action="${PREFIX}/unlock">
209
+ <input name="token" type="password" autocomplete="current-password" autofocus required
210
+ aria-label="本机口令" placeholder="本机口令" />
211
+ <button type="submit">打开星图</button>
212
+ </form>
213
+ <p class="foot">口令只保存在本机 HttpOnly cookie 里;也可以继续用终端打印的带 token 地址。</p>
214
+ </main></body></html>`, 'utf8')
215
+ res.writeHead(status, {
216
+ 'content-type': 'text/html; charset=utf-8',
217
+ 'content-length': String(body.length),
218
+ 'cache-control': 'no-store',
219
+ 'x-content-type-options': 'nosniff',
220
+ 'referrer-policy': 'no-referrer',
221
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'",
222
+ })
223
+ res.end(body)
224
+ }
225
+
226
+ /** 读 urlencoded 表单(口令页只收这一种)。 */
227
+ function readForm(req, limit = 8 * 1024) {
228
+ return new Promise((resolve) => {
229
+ let size = 0
230
+ let settled = false
231
+ const chunks = []
232
+ const finish = (value) => {
233
+ if (settled) return
234
+ settled = true
235
+ resolve(value)
236
+ }
237
+ req.on('data', (chunk) => {
238
+ size += chunk.length
239
+ if (size > limit) {
240
+ // 同 readBody:停读而不是拆连接,400 页才有机会显示出来。
241
+ req.pause?.()
242
+ finish(null)
243
+ return
244
+ }
245
+ chunks.push(chunk)
246
+ })
247
+ req.on('end', () => {
248
+ try {
249
+ finish(new URLSearchParams(Buffer.concat(chunks).toString('utf8')))
250
+ } catch {
251
+ finish(null)
252
+ }
253
+ })
254
+ req.on('error', () => finish(null))
255
+ })
256
+ }
257
+
258
+ /**
259
+ * 统一出口:协商压缩、带 content-length、HEAD 不出 body。
260
+ *
261
+ * 为什么这里要接 req:压缩取决于 Accept-Encoding,HEAD 取决于方法,
262
+ * 而这两个信息只有请求里有。之前 sendJson 只有 res,所以 1.7.0 的大响应
263
+ * 一直是整包未压缩下发(真实库 2000+ 条时 /graph 约 1MB)。
264
+ */
265
+ async function sendBody(req, res, status, body, headers = {}) {
266
+ // 头值里有非 ASCII(中文标题、签名)→ Node 会抛 ERR_INVALID_CHAR,
267
+ // 那时头已经写出去一半,响应就再也发不完了。宁可不发这个头。
268
+ for (const key of Object.keys(headers)) {
269
+ const value = headers[key]
270
+ if (value === undefined || value === null) {
271
+ delete headers[key]
272
+ continue
273
+ }
274
+ if (!/^[\x20-\x7e]*$/.test(String(value))) delete headers[key]
275
+ }
276
+ const buffer = Buffer.isBuffer(body) ? body : Buffer.from(String(body), 'utf8')
277
+ const type = headers['content-type']
278
+ const encoding = status === 304 ? null : pickEncoding(req.headers['accept-encoding'])
279
+ const compressible =
280
+ Boolean(encoding) && buffer.length >= MIN_COMPRESS_BYTES && isCompressibleType(type) && !headers['content-encoding']
281
+ let payload = buffer
282
+ const extra = {}
283
+ if (compressible) {
284
+ payload = await compressBuffer(buffer, encoding)
285
+ extra['content-encoding'] = encoding
286
+ }
287
+ // CORS 在 standalone 里用 res.setHeader('vary','Origin') 先挂了一层;writeHead 里同名的
288
+ // vary 会把它盖掉,所以这里要连同「已经挂在 res 上的」一起合并,不能只看 headers 参数。
289
+ const priorVary = typeof res.getHeader === 'function' ? res.getHeader('vary') : ''
290
+ let vary = String(priorVary || '').trim()
291
+ if (headers.vary) vary = mergeVary(vary, headers.vary)
292
+ if (encoding) vary = mergeVary(vary, 'accept-encoding')
293
+ if (vary) extra.vary = vary
294
+ // 半截请求:响应发完再断,别让 413 还没写出去就把 socket 拆了。
295
+ if (headers.connection === 'close' && typeof res.once === 'function') {
296
+ res.once('finish', () => {
297
+ try {
298
+ req.destroy?.()
299
+ } catch {
300
+ /* 已经断了就算了 */
301
+ }
302
+ })
303
+ }
304
+ res.writeHead(status, {
305
+ ...headers,
306
+ ...extra,
307
+ 'content-length': String(payload.length),
308
+ })
309
+ if ((req.method || 'GET').toUpperCase() === 'HEAD' || status === 204) return res.end()
310
+ return res.end(payload)
311
+ }
312
+
313
+ async function sendJson(req, res, status, payload, headers = {}) {
314
+ let body
315
+ try {
316
+ body = Buffer.from(JSON.stringify(payload), 'utf8')
317
+ } catch (err) {
318
+ body = Buffer.from(JSON.stringify({ error: '序列化失败:' + (err?.message || err) }), 'utf8')
319
+ status = 500
320
+ }
321
+ return sendBody(req, res, status, body, {
322
+ 'content-type': 'application/json; charset=utf-8',
323
+ 'cache-control': 'no-store',
324
+ 'x-content-type-options': 'nosniff',
325
+ 'referrer-policy': 'no-referrer',
326
+ ...headers,
327
+ })
328
+ }
329
+
330
+ /** 页面自身只加载同源脚本、只连本机接口;导出图走 data:/blob:。 */
331
+ const CSP = [
332
+ "default-src 'self'",
333
+ "script-src 'self' 'unsafe-inline' http://127.0.0.1:*",
334
+ "style-src 'self' 'unsafe-inline'",
335
+ "img-src 'self' data: blob:",
336
+ "connect-src 'self' http://127.0.0.1:*",
337
+ "font-src 'self' data:",
338
+ "frame-ancestors 'self'",
339
+ "base-uri 'none'",
340
+ "form-action 'none'",
341
+ ].join('; ')
342
+
343
+ /**
344
+ * 静态资源缓存。1.8.0 起:
345
+ * - 带 ETag(mtime+size),刷新走 304,不再每次重下 300KB 前端;
346
+ * - 按 Accept-Encoding 压缩,压缩结果按 name:mtime:encoding 缓存,重启才失效;
347
+ * - 支持 HEAD(探活与 CDN 预检会用到)。
348
+ * 缓存键带 mtime,所以改了文件立刻生效,不会拿到旧字节。
349
+ */
350
+ const STATIC_CACHE = new Map()
351
+
352
+ async function sendFile(req, res, name) {
353
+ const file = join(WEB_DIR, name)
354
+ const ext = name.slice(name.lastIndexOf('.'))
355
+ const type = MIME[ext] || 'application/octet-stream'
356
+ let stat
357
+ let raw
358
+ try {
359
+ stat = statSync(file)
360
+ raw = readFileSync(file)
361
+ } catch {
362
+ return sendBody(req, res, 404, 'not found: ' + name, {
363
+ 'content-type': 'text/plain; charset=utf-8',
364
+ 'cache-control': 'no-store',
365
+ 'x-content-type-options': 'nosniff',
366
+ })
367
+ }
368
+ const etag = '"' + Math.round(stat.mtimeMs).toString(36) + '-' + stat.size.toString(36) + '"'
369
+ const headers = {
370
+ 'content-type': type,
371
+ 'cache-control': 'no-cache',
372
+ etag,
373
+ 'x-content-type-options': 'nosniff',
374
+ 'referrer-policy': 'no-referrer',
375
+ }
376
+ if (ext === '.html') {
377
+ headers['content-security-policy'] = CSP
378
+ headers['x-frame-options'] = 'SAMEORIGIN'
379
+ }
380
+ const inm = String(req.headers['if-none-match'] || '')
381
+ if (inm && inm.split(',').some((tag) => tag.trim() === etag || tag.trim() === 'W/' + etag)) {
382
+ return sendBody(req, res, 304, '', { ...headers, vary: 'accept-encoding' })
383
+ }
384
+ const encoding = pickEncoding(req.headers['accept-encoding'])
385
+ if (encoding && raw.length >= MIN_COMPRESS_BYTES && isCompressibleType(type)) {
386
+ const key = name + ':' + Math.round(stat.mtimeMs) + ':' + encoding
387
+ let zipped = STATIC_CACHE.get(key)
388
+ if (!zipped) {
389
+ zipped = await compressBuffer(raw, encoding)
390
+ // 文件不多,直接清掉同名旧版本即可,别让 Map 无限长
391
+ for (const k of STATIC_CACHE.keys()) if (k.startsWith(name + ':')) STATIC_CACHE.delete(k)
392
+ STATIC_CACHE.set(key, zipped)
393
+ }
394
+ headers['content-encoding'] = encoding
395
+ headers.vary = 'accept-encoding'
396
+ return sendBody(req, res, 200, zipped, headers)
397
+ }
398
+ return sendBody(req, res, 200, raw, headers)
399
+ }
400
+
401
+ /**
402
+ * 读 JSON 请求体。返回 `{ok:true,value}` / `{ok:false,error}`,
403
+ * 让路由能把「太大」和「不是 JSON」分别回 413 / 400,而不是一律当成空对象。
404
+ */
405
+ function readBody(req, limit = 256 * 1024) {
406
+ return new Promise((resolve) => {
407
+ let size = 0
408
+ let settled = false
409
+ const chunks = []
410
+ const finish = (result) => {
411
+ if (settled) return
412
+ settled = true
413
+ resolve(result)
414
+ }
415
+ req.on('data', (chunk) => {
416
+ size += chunk.length
417
+ if (size > limit) {
418
+ // 只停读、不断连接:先让 413 写得出去。以前这里直接 req.destroy(),
419
+ // 客户端看到的是 ECONNRESET / fetch failed,而不是「请求体太大」。
420
+ req.pause?.()
421
+ finish({ ok: false, error: 'too_large' })
422
+ return
423
+ }
424
+ chunks.push(chunk)
425
+ })
426
+ req.on('end', () => {
427
+ try {
428
+ const text = Buffer.concat(chunks).toString('utf8')
429
+ finish({ ok: true, value: text ? JSON.parse(text) : {} })
430
+ } catch {
431
+ finish({ ok: false, error: 'bad_json' })
432
+ }
433
+ })
434
+ req.on('error', () => finish({ ok: false, error: 'bad_body' }))
435
+ })
436
+ }
437
+
438
+ const BODY_ERROR = {
439
+ too_large: '请求体超过 256 KB',
440
+ bad_json: '请求体不是合法 JSON',
441
+ bad_body: '请求体读取失败',
442
+ }
443
+
444
+ /** 读 JSON 体;失败时已经把响应写回去了,返回 null。 */
445
+ async function jsonBody(req, res) {
446
+ const r = await readBody(req)
447
+ if (!r.ok) {
448
+ const tooLarge = r.error === 'too_large'
449
+ await sendJson(
450
+ req,
451
+ res,
452
+ tooLarge ? 413 : 400,
453
+ { error: BODY_ERROR[r.error] || '请求体无效' },
454
+ // 请求体还没读完就回错误,告诉客户端这条连接到此为止;
455
+ // sendBody 会在响应 finish 之后再断开,不会把 413 自己吞掉。
456
+ tooLarge ? { connection: 'close' } : {},
457
+ )
458
+ return null
459
+ }
460
+ return r.value && typeof r.value === 'object' ? r.value : {}
461
+ }
462
+
463
+ /**
464
+ * 示例星系:一个只存在于内存里的 Nebula,内容来自 lib/host/demo.js。
465
+ * 惰性创建、整进程共用一份——第一次请求时构建一次(几十毫秒),之后一直是热的。
466
+ * 它不读盘、不写盘、不监听文件变化,所以随便谁点「看示例」都不会碰到真实记忆库。
467
+ */
468
+ let demoPromise = null
469
+ function demoInstance() {
470
+ if (!demoPromise) {
471
+ demoPromise = import('./nebula.js')
472
+ .then(async ({ Nebula }) => {
473
+ const demo = new Nebula({ demo: true, log: () => {} })
474
+ await demo.refresh()
475
+ return demo
476
+ })
477
+ .catch((err) => {
478
+ demoPromise = null // 构建失败别把坏结果缓存一辈子,下次请求重试
479
+ throw err
480
+ })
481
+ }
482
+ return demoPromise
483
+ }
484
+
485
+ /**
486
+ * 解析 /graph 的分页参数。
487
+ *
488
+ * 约定:limit=0 / 不带参数 = 交给服务端决定(大图默认第一页 20000)。
489
+ * 只要是数字就一定得是干净的正整数——「abc」「1.5」「-3」都报 400,
490
+ * 免得前端拼错参数时静默拿到整库(5 万条时那是 44MB)。
491
+ * @param {URLSearchParams} sp
492
+ * @returns {{limit:number, offset:number, error?:string}}
493
+ */
494
+ function readPageArgs(sp) {
495
+ const bad = (error) => ({ limit: 0, offset: 0, error })
496
+ let limit = 0
497
+ let offset = 0
498
+ const rawLimit = sp.get('limit')
499
+ if (rawLimit != null && rawLimit !== '') {
500
+ if (!/^\d+$/.test(rawLimit)) return bad('limit 需要 0–50000 的整数')
501
+ limit = Number(rawLimit)
502
+ if (limit > 50000) return bad('limit 不能超过 50000,请分页加载')
503
+ }
504
+ const rawOffset = sp.get('offset')
505
+ if (rawOffset != null && rawOffset !== '') {
506
+ if (!/^\d+$/.test(rawOffset)) return bad('offset 需要非负整数')
507
+ offset = Number(rawOffset)
508
+ }
509
+ return { limit, offset }
510
+ }
511
+
512
+ /**
513
+ * 读一个整数参数:不传就给默认值,写错就报错。
514
+ * 以前这里是 `Number(raw) || fallback`,于是「abc」静默变成默认值,连 0 也被吞掉
515
+ * (recall?hops=0 本该「只给命中、不扩散」,却悄悄按 2 跑了)。拼错要能看见。
516
+ * @param {URLSearchParams} sp
517
+ * @param {string} name
518
+ * @param {{min:number, max:number, fallback:number}} spec
519
+ * @returns {{value?:number, error?:string}}
520
+ */
521
+ export function readIntArg(sp, name, spec) {
522
+ const raw = sp.get(name)
523
+ if (raw == null || raw === '') return { value: spec.fallback }
524
+ const text = String(raw).trim()
525
+ const bad = { error: `${name} 需要 ${spec.min}–${spec.max} 的整数,收到的是「${text}」` }
526
+ if (!/^\d+$/.test(text)) return bad
527
+ const value = Number(text)
528
+ if (!Number.isFinite(value) || value < spec.min || value > spec.max) return bad
529
+ return { value }
530
+ }
531
+
532
+ /**
533
+ * 读一个数字参数(允许小数,比如 min_weight=0.45):规则同上,写错就报错、0 照样有效。
534
+ * @param {URLSearchParams} sp
535
+ * @param {string} name
536
+ * @param {{min:number, max:number, fallback:number}} spec
537
+ * @returns {{value?:number, error?:string}}
538
+ */
539
+ export function readNumArg(sp, name, spec) {
540
+ const raw = sp.get(name)
541
+ if (raw == null || raw === '') return { value: spec.fallback }
542
+ const text = String(raw).trim()
543
+ const bad = { error: `${name} 需要 ${spec.min}–${spec.max} 之间的数,收到的是「${text}」` }
544
+ if (!/^\d+(\.\d+)?$/.test(text)) return bad
545
+ const value = Number(text)
546
+ if (!Number.isFinite(value) || value < spec.min || value > spec.max) return bad
547
+ return { value }
548
+ }
549
+
550
+ /**
551
+ * 注册所有路由。
552
+ * @param {{register:(def:any)=>any}} webServer ctx.webServer
553
+ * @param {import('./nebula.js').Nebula} nebula
554
+ * @param {(line:string)=>void} [log]
555
+ * @param {{mode?:'host'|'standalone', connection?:{requestRejection:(req:any)=>number|undefined}}} [info]
556
+ */
557
+ export function registerRoutes(webServer, nebula, log = () => {}, info = {}) {
558
+ const mode = info.mode === 'standalone' ? 'standalone' : 'host'
559
+ const connection = info.connection && typeof info.connection.requestRejection === 'function' ? info.connection : null
560
+ const token = typeof info.token === 'string' ? info.token : ''
561
+ const handler = async (req, res) => {
562
+ const url = new URL(req.url || '/', 'http://localhost')
563
+ const route = url.pathname.slice(PREFIX.length) || '/'
564
+ // HEAD 按 GET 处理:同一套路由、同样的头与 content-length,只是不出 body。
565
+ // 探活脚本、CDN 预检、`curl -I` 都走这条路,之前 HEAD /app 会掉进 404。
566
+ const method = (req.method || 'GET').toUpperCase() === 'HEAD' ? 'GET' : (req.method || 'GET').toUpperCase()
567
+ try {
568
+ // DNS rebinding:GET 不带 Origin,但 Host 会带着攻击者的域名。
569
+ if (!isLoopbackHost(req.headers.host)) {
570
+ return sendJson(req, res, 403, { error: '只接受来自本机的请求:请通过 127.0.0.1 或 localhost 打开' })
571
+ }
572
+ // 口令登录:表单只能从本机页面提交;正确时种 cookie,再 302 回页面。
573
+ // 有些浏览器对 401 页上的表单会发 `Origin: null`,所以这里不套用写接口的
574
+ // Origin 规则——口令本身就是凭据,猜不中就没有副作用。
575
+ if (token && method === 'POST' && route === '/unlock') {
576
+ const form = await readForm(req)
577
+ if (!form) return sendUnlockPage(res, '表单读取失败,再试一次', 400)
578
+ if (!sameSecret(form.get('token') || '', token)) {
579
+ return sendUnlockPage(res, '口令不对,再试一次')
580
+ }
581
+ res.setHeader(
582
+ 'set-cookie',
583
+ `nb_token=${encodeURIComponent(token)}; Path=${PREFIX}; HttpOnly; SameSite=Strict`,
584
+ )
585
+ res.writeHead(302, { location: PREFIX + '/app', 'cache-control': 'no-store' })
586
+ return res.end()
587
+ }
588
+ // 可选的本机口令:standalone 可以用 --token 打开;宿主模式默认不启用。
589
+ if (token) {
590
+ const fromQuery = sameSecret(url.searchParams.get('token') || '', token)
591
+ if (fromQuery) {
592
+ res.setHeader(
593
+ 'set-cookie',
594
+ `nb_token=${encodeURIComponent(token)}; Path=${PREFIX}; HttpOnly; SameSite=Strict`,
595
+ )
596
+ }
597
+ if (!fromQuery && !hasToken(req, url, token)) {
598
+ // 浏览器直接打开页面时给一个输口令的入口;接口仍然回 JSON 401。
599
+ if (method === 'GET' && (route === '/' || route === '/app' || route === '/index.html')) {
600
+ return sendUnlockPage(res)
601
+ }
602
+ return sendJson(req, res, 401, {
603
+ error: '需要本机口令:用启动时打印的带 token 的地址打开一次,或发送 Authorization: Bearer <token>',
604
+ })
605
+ }
606
+ }
607
+ // 宿主内再走一遍 DSH 的 Host/Origin + 已认证 Peer 围栏;独立引擎没有这个服务。
608
+ if (connection) {
609
+ const rejection = connection.requestRejection(req)
610
+ if (rejection) {
611
+ return sendJson(req, res, rejection, {
612
+ error:
613
+ rejection === 401
614
+ ? '这个视图需要从 DSH 里打开:当前请求没有通过宿主认证'
615
+ : '宿主拒绝了这次请求:Host / Origin 不在可信范围',
616
+ })
617
+ }
618
+ }
619
+ // 写接口只接受本机页面 / 本机脚本:挡掉「任意网页向 127.0.0.1 发 POST」的 CSRF。
620
+ if (method !== 'GET' && method !== 'HEAD' && !allowWrite(req)) {
621
+ return sendJson(req, res, 403, { error: '跨站写入被拒绝:写接口只接受本机页面或本机脚本' })
622
+ }
623
+ // ---------- 静态页面 ----------
624
+ if (method === 'GET' && (route === '/' || route === '/app' || route === '/index.html')) {
625
+ return sendFile(req, res, 'index.html')
626
+ }
627
+ if (method === 'GET' && route.startsWith('/') && STATIC.has(route.slice(1))) {
628
+ return sendFile(req, res, route.slice(1))
629
+ }
630
+
631
+ // ---------- 数据 ----------
632
+ // ?demo=1 切到内置示例星系:只读、不写盘、不碰真实记忆库。
633
+ const demoReq = url.searchParams.get('demo') === '1'
634
+ if (demoReq && method !== 'GET' && method !== 'HEAD') {
635
+ return sendJson(req, res, 403, { error: '示例模式是只读的:不会被改动,也不会写进你的记忆库' })
636
+ }
637
+ const src = demoReq ? await demoInstance() : nebula
638
+
639
+ if (method === 'GET' && route === '/diagnostics') {
640
+ if (!src.graph || src.graph.nodes.length === 0) await src.refresh()
641
+ const report = buildDiagnostics({
642
+ version: VERSION,
643
+ build: BUILD,
644
+ startedAt: STARTED_AT,
645
+ mode,
646
+ demo: demoReq || Boolean(src.demo),
647
+ nebula: src,
648
+ capabilities: CAPABILITIES,
649
+ runtime: {
650
+ node: process.version,
651
+ platform: process.platform,
652
+ arch: process.arch,
653
+ pid: process.pid,
654
+ uptimeSec: process.uptime(),
655
+ rssMb: process.memoryUsage().rss / 1024 / 1024,
656
+ },
657
+ })
658
+ const wantsJson = url.searchParams.get('format') === 'json'
659
+ const lang = url.searchParams.get('lang') === 'en' ? 'en' : 'zh'
660
+ const body = Buffer.from(
661
+ wantsJson ? JSON.stringify(report) : formatDiagnostics(report, { lang }),
662
+ 'utf8',
663
+ )
664
+ return sendBody(req, res, 200, body, {
665
+ 'content-type': wantsJson ? 'application/json; charset=utf-8' : 'text/plain; charset=utf-8',
666
+ 'cache-control': 'no-store',
667
+ 'x-content-type-options': 'nosniff',
668
+ 'referrer-policy': 'no-referrer',
669
+ })
670
+ }
671
+
672
+ if (method === 'GET' && route === '/progress') {
673
+ // 建图期间也要能问,所以这条路由**不等待**建图:
674
+ // 冷启动那几秒 /ping 和 /graph 都卡着,界面靠这里说清走到哪一步。
675
+ return sendJson(req, res, 200, {
676
+ ok: true,
677
+ building: Boolean(src.building),
678
+ progress: src.buildProgress || null,
679
+ nodes: src.graph ? src.graph.nodes.length : 0,
680
+ stale: Boolean(src.staleGraph),
681
+ scale: src.scale || null,
682
+ at: Date.now(),
683
+ })
684
+ }
685
+
686
+ if (method === 'GET' && route === '/ping') {
687
+ if (!src.graph || src.graph.nodes.length === 0) await src.refresh()
688
+ return sendJson(req, res, 200, {
689
+ ok: true,
690
+ version: VERSION,
691
+ build: BUILD,
692
+ startedAt: STARTED_AT,
693
+ mode,
694
+ capabilities: CAPABILITIES,
695
+ sig: src.signature || '',
696
+ builtAt: src.graph?.builtAt || 0,
697
+ stats: src.graph?.stats || {},
698
+ buildMs: src.lastBuildMs || 0,
699
+ cacheAgeMs: src.cacheAgeMs || 0,
700
+ scale: src.scale || null,
701
+ error: src.lastError || '',
702
+ demo: demoReq || Boolean(src.demo),
703
+ })
704
+ }
705
+
706
+ if (method === 'GET' && route === '/graph') {
707
+ // 1.9.0 分页:limit/offset 必须是明确的整数,拼错要报错而不是静默全量。
708
+ const pageArgs = readPageArgs(url.searchParams)
709
+ if (pageArgs.error) return sendJson(req, res, 400, { error: pageArgs.error })
710
+ const { limit, offset } = pageArgs
711
+ // 客户端带 sig 回来 = 「我接着上一页继续加载」;图在这期间重建过就必须从头来,
712
+ // 否则按排名切片会串页(第 2 页拿到的是新图里排名相同的另一批节点)。
713
+ const wantSig = String(url.searchParams.get('sig') || '')
714
+ // 1.11.24:refresh=1 的语义是「看看有没有新东西」,不是「不管怎样都重建」。
715
+ // 以前这里同样传 force:true,于是每打开一次页面(reload(false) 走这条路)
716
+ // 都要白跑一遍全量建图。真要强制重建用 ?force=1。
717
+ const wantRefresh = url.searchParams.get('refresh') === '1'
718
+ const forceRebuild = url.searchParams.get('force') === '1'
719
+ // 1.11.30:手上已经有一张图时,refresh=1 不再等建完——
720
+ // 五万条库上那要五秒多,先给旧图(带着 refreshing 标记),新图建好页面自己来换。
721
+ // 只有「还没图」和「显式 force」两条路继续等:前者没东西可给,后者是主人点了重建。
722
+ if (forceRebuild || !src.graph || src.graph.nodes.length === 0) {
723
+ await src.refresh({ force: forceRebuild })
724
+ } else if (wantRefresh || src.staleGraph) {
725
+ // staleGraph:手上这张是重启时从过期缓存恢复的旧图,页面已经把它画出来了,
726
+ // 现在就该在后台把新的建起来 —— 不能等轮询或其他请求来才发现。
727
+ src.refreshInBackground({})
728
+ }
729
+ if (wantSig && src.signature && wantSig !== src.signature) {
730
+ return sendJson(req, res, 409, {
731
+ error: '图已更新,请从第一页重新加载',
732
+ sig: src.signature,
733
+ })
734
+ }
735
+ const graph = src.publicGraph({ limit, offset })
736
+ // sig 变了图才变;配合 If-None-Match 能让轮询与多标签页省掉整包重传。
737
+ // 1.8.0 起响应可能被压缩,同一个 sig 会有「未压缩 / br / gzip」几种表示,
738
+ // 所以改成弱 ETag:语义仍是「内容没变」,具体变体由 Vary 区分。
739
+ // 1.9.0 把分页参数也编进 ETag:整图和某一页不是同一个表示,不能互相 304。
740
+ const pageTag = limit || offset ? '-p' + offset + '-' + limit : ''
741
+ const etag = 'W/"' + etagSafe(src.signature) + '-' + BUILD + pageTag + '"'
742
+ const inm = String(req.headers['if-none-match'] || '')
743
+ if (inm && inm.split(',').some((tag) => tag.trim() === etag)) {
744
+ return sendBody(req, res, 304, '', { etag, 'cache-control': 'no-cache', vary: 'accept-encoding' })
745
+ }
746
+ return sendJson(req, res, 200, { ...graph, version: VERSION, build: BUILD, sig: src.signature || '', refreshing: Boolean(src.building), stale: Boolean(src.staleGraph), demo: demoReq || Boolean(src.demo) }, { etag, 'cache-control': 'no-cache' })
747
+ }
748
+
749
+ if (method === 'GET' && route === '/node') {
750
+ const id = url.searchParams.get('id') || ''
751
+ const detail = src.detail(id)
752
+ if (!detail) return sendJson(req, res, 404, { error: '没有这条记忆:' + id })
753
+ const node = { ...detail }
754
+ delete node.neighbors
755
+ return sendJson(req, res, 200, {
756
+ node,
757
+ neighbors: (detail.neighbors || []).map((n) => ({ ...n, w: n.weight })),
758
+ degree: (detail.neighbors || []).length,
759
+ cluster: detail.cluster,
760
+ })
761
+ }
762
+
763
+ if (method === 'GET' && route === '/recall') {
764
+ const q = url.searchParams.get('q') || ''
765
+ const seed = url.searchParams.get('seed') || ''
766
+ const ids = url.searchParams.get('ids') || ''
767
+ // 1.11.63:参数拼错就 400。以前 `Number(raw) || 默认` 会把「abc」当默认值,
768
+ // 连 hops=0(只要命中、不扩散)也被吞成 2——调用方看不出自己写错了。
769
+ const limitArg = readIntArg(url.searchParams, 'limit', { min: 1, max: 50, fallback: 12 })
770
+ if (limitArg.error) return sendJson(req, res, 400, { error: limitArg.error })
771
+ const hopsArg = readIntArg(url.searchParams, 'hops', { min: 0, max: 3, fallback: 2 })
772
+ if (hopsArg.error) return sendJson(req, res, 400, { error: hopsArg.error })
773
+ const limit = limitArg.value
774
+ const hops = hopsArg.value
775
+ const seedIds = [seed, ids].filter(Boolean).join(',').split(',').filter(Boolean)
776
+ if (!q && seedIds.length === 0) return sendJson(req, res, 200, { query: '', hits: [], seeds: [] })
777
+ // 第一次查 5 万条的库时,词频表要 1.3 秒;异步版按 6ms 一片灌,不按住事件循环。
778
+ const result = await src.recallAsync(q, { limit, hops, seedIds })
779
+ return sendJson(req, res, 200, result)
780
+ }
781
+
782
+ if (method === 'GET' && route === '/path') {
783
+ const a = url.searchParams.get('a') || ''
784
+ const b = url.searchParams.get('b') || ''
785
+ // 1.11.64:接口文档一直写的是 maxHops,代码却只认 hops——照文档调的调用方
786
+ // 被静默当成 6 跳(连写错都不会报错)。两个名字都收,优先文档里那个。
787
+ const rawMaxHops = url.searchParams.get('maxHops')
788
+ const hopName = rawMaxHops != null && rawMaxHops !== '' ? 'maxHops' : 'hops'
789
+ const hopsArg = readIntArg(url.searchParams, hopName, { min: 1, max: 8, fallback: 6 })
790
+ if (hopsArg.error) return sendJson(req, res, 400, { error: hopsArg.error })
791
+ const hops = hopsArg.value
792
+ if (!a || !b) return sendJson(req, res, 400, { error: '需要 a / b' })
793
+ return sendJson(req, res, 200, await src.path(a, b, { maxHops: hops }))
794
+ }
795
+
796
+ if (method === 'GET' && route === '/overview') {
797
+ // 1.11.46:默认不再等体检(20 万条要 12.9 秒,面板一开就像卡死)。
798
+ // 有缓存就直接带上;没算过就标 hygienePending,让界面自己去 /hygiene 取。
799
+ // 还要「算完再给」的调用方(脚本、工具)加 ?hygiene=1。
800
+ const wantHygiene = url.searchParams.get('hygiene') === '1'
801
+ return sendJson(req, res, 200, wantHygiene ? await src.overviewAsync() : src.overview({ hygiene: 'cached' }))
802
+ }
803
+
804
+ if (method === 'GET' && route === '/hygiene') {
805
+ // 体检单独一条路由:它会分片算很久,但只占这一条请求,别拖住整个面板。
806
+ // 同一份图上的并发调用共用一次计算(hygieneAsync 内部单飞),算完就进缓存。
807
+ const value = await src.hygieneAsync()
808
+ return sendJson(req, res, 200, { ok: true, hygiene: value, cards: src.cards(), at: Date.now() })
809
+ }
810
+
811
+ if (method === 'GET' && route === '/mutes') {
812
+ return sendJson(req, res, 200, { mutes: src.mutes() })
813
+ }
814
+
815
+ if (method === 'POST' && route === '/link') {
816
+ const body = await jsonBody(req, res)
817
+ if (!body) return
818
+ if (!body.a || !body.b) return sendJson(req, res, 400, { error: '需要 a / b' })
819
+ // 策展一条关联就地生效(冻结 now 下与全量重建逐边相同:正好 +1 条),不再重建整张图
820
+ const out = src.link(body.a, body.b, body.note || '')
821
+ return sendJson(req, res, 200, { ok: true, ...out })
822
+ }
823
+
824
+ if (method === 'POST' && route === '/unlink') {
825
+ const body = await jsonBody(req, res)
826
+ if (!body) return
827
+ if (!body.a || !body.b) return sendJson(req, res, 400, { error: '需要 a / b' })
828
+ const ok = src.unlink(body.a, body.b)
829
+ return sendJson(req, res, 200, { ok })
830
+ }
831
+
832
+ if (method === 'POST' && route === '/mute') {
833
+ const body = await jsonBody(req, res)
834
+ if (!body) return
835
+ if (!body.a || !body.b) return sendJson(req, res, 400, { error: '需要 a / b' })
836
+ // 屏蔽就地删掉这一条(剪枝腾出的空位不补;下次重建时自然补位)
837
+ const out = src.mute(body.a, body.b, body.note || '')
838
+ return sendJson(req, res, 200, { ok: true, ...out })
839
+ }
840
+
841
+ if (method === 'POST' && route === '/unmute') {
842
+ const body = await jsonBody(req, res)
843
+ if (!body) return
844
+ if (!body.a || !body.b) return sendJson(req, res, 400, { error: '需要 a / b' })
845
+ const ok = src.unmute(body.a, body.b)
846
+ // 撤销屏蔽:当初删掉的那条边能原样放回就地放回(毫秒级);放不回去才重算一遍。
847
+ if (ok && src.takeRebuildFlag()) await src.refresh({ force: true })
848
+ return sendJson(req, res, 200, { ok })
849
+ }
850
+
851
+ // ---------- 跨插件协同:补充包 / 来源体检 / 外部推送 ----------
852
+ if (method === 'GET' && route === '/bridge') {
853
+ const ids = (url.searchParams.get('ids') || '')
854
+ .split(',')
855
+ .map((x) => x.trim())
856
+ .filter(Boolean)
857
+ const query = (url.searchParams.get('query') || '').trim()
858
+ if (ids.length === 0 && !query) return sendJson(req, res, 400, { error: '需要 ids 或 query' })
859
+ // 预算四个参数同样不许静默回落:写错就 400,0 也照用(min_weight=0 是「不过滤」)。
860
+ const limitArg = readIntArg(url.searchParams, 'limit', { min: 1, max: 20, fallback: 6 })
861
+ if (limitArg.error) return sendJson(req, res, 400, { error: limitArg.error })
862
+ const charsArg = readIntArg(url.searchParams, 'chars', { min: 1, max: 4000, fallback: 1600 })
863
+ if (charsArg.error) return sendJson(req, res, 400, { error: charsArg.error })
864
+ const minWArg = readNumArg(url.searchParams, 'min_weight', { min: 0, max: 1, fallback: 0.45 })
865
+ if (minWArg.error) return sendJson(req, res, 400, { error: minWArg.error })
866
+ const hopsArg = readIntArg(url.searchParams, 'hops', { min: 0, max: 3, fallback: 1 })
867
+ if (hopsArg.error) return sendJson(req, res, 400, { error: hopsArg.error })
868
+ const out = src.bridge({
869
+ ids,
870
+ query,
871
+ sessionId: url.searchParams.get('session') || '',
872
+ ws: url.searchParams.get('ws') || '',
873
+ mark: url.searchParams.get('mark') === '1',
874
+ budget: {
875
+ maxItems: limitArg.value,
876
+ maxChars: charsArg.value,
877
+ minWeight: minWArg.value,
878
+ hops: hopsArg.value,
879
+ },
880
+ })
881
+ return sendJson(req, res, 200, out)
882
+ }
883
+
884
+ if (method === 'GET' && route === '/sources') {
885
+ return sendJson(req, res, 200, await src.sourcesReport())
886
+ }
887
+
888
+ if (method === 'POST' && route === '/ingest') {
889
+ const body = await jsonBody(req, res)
890
+ if (!body) return
891
+ const provider = String(body.provider || '').trim()
892
+ const items = Array.isArray(body.items) ? body.items : []
893
+ if (!provider) return sendJson(req, res, 400, { error: '需要 provider' })
894
+ if (items.length === 0) return sendJson(req, res, 400, { error: '需要 items' })
895
+ if (items.length > 5000) return sendJson(req, res, 413, { error: '单次最多 5000 条' })
896
+ const out = await src.ingest(provider, items)
897
+ // 1.11.68:条目全是坏的、一条也没写成时,以前照样回 200 {ok:true, written:0}。
898
+ if (out.error) {
899
+ return sendJson(req, res, 400, {
900
+ error: out.error,
901
+ written: 0,
902
+ skipped: out.skipped || 0,
903
+ reasons: out.reasons || {},
904
+ })
905
+ }
906
+ return sendJson(req, res, 200, { ok: true, ...out })
907
+ }
908
+
909
+ if (method === 'GET' && route === '/ledger') {
910
+ const session = url.searchParams.get('session') || ''
911
+ return sendJson(req, res, 200, src.ledger
912
+ ? src.ledger(session)
913
+ : { stats: null })
914
+ }
915
+
916
+ if (method === 'GET' && route === '/export') {
917
+ const format = (url.searchParams.get('format') || 'md').toLowerCase()
918
+ // 不要 toLowerCase 整个 scope:工作区/项目名可能是大小写敏感的中英文混合。
919
+ const scope = (url.searchParams.get('scope') || 'all').trim()
920
+ // 1.11.63:`Number(raw) || 2` 会把 hops=0 也吞成 2;与 /share 用同一套解析(那边拼错一直报 400)。
921
+ const hopsArg = readIntArg(url.searchParams, 'hops', { min: 0, max: 5, fallback: 2 })
922
+ if (hopsArg.error) return sendJson(req, res, 400, { error: hopsArg.error })
923
+ const report = src.exportReport({ format, scope, hops: hopsArg.value })
924
+ if (report && report.error) return sendJson(req, res, 400, report)
925
+ return sendJson(req, res, 200, report)
926
+ }
927
+
928
+ if (method === 'GET' && route === '/share') {
929
+ // 单文件快照:一张图 + 记忆全文,内联成一个 HTML,用户主动下载到本地。
930
+ // 不经过任何远端服务;下载完就是一份可以双击打开的只读星图。
931
+ // ?scope=ws:<工作区> | project:<项目> | focus:<节点 id>&hops=N 只把这一片写进文件,
932
+ // 范围外的记忆不会出现在快照的数据里——隐私不能靠前端隐藏。
933
+ const scope = parseShareScope(url.searchParams.get('scope'))
934
+ const hops = parseShareHops(url.searchParams.get('hops'))
935
+ // hide 可以重复传,也可以逗号分隔;白名单校验在 parseShareHide 里,拼错直接 400。
936
+ const hide = parseShareHide(url.searchParams.getAll('hide'))
937
+ // 分片上限:5 万条整库快照约 40MB,默认只写前 2 万条(按重要度),并在页面上写明已裁剪
938
+ const limit = parseShareLimit(url.searchParams.get('limit'))
939
+ const { html, scope: used } = await buildShareHtml(
940
+ src,
941
+ { version: VERSION, build: BUILD },
942
+ { scope, hops, hide, limit },
943
+ )
944
+ // 用本地时间,和快照页面上「生成于 …」显示的一致(toISOString 是 UTC,会差 8 小时)
945
+ const now = new Date()
946
+ const pad = (n) => String(n).padStart(2, '0')
947
+ const stamp = [now.getFullYear(), pad(now.getMonth() + 1), pad(now.getDate()), pad(now.getHours()), pad(now.getMinutes())].join('-')
948
+ const suffix = used && used.kind !== 'all' ? '-' + used.kind : ''
949
+ return sendBody(req, res, 200, Buffer.from(html, 'utf8'), {
950
+ 'content-type': 'text/html; charset=utf-8',
951
+ 'content-disposition': 'attachment; filename="memory-nebula-snapshot' + suffix + '-' + stamp + '.html"',
952
+ 'cache-control': 'no-store',
953
+ 'x-content-type-options': 'nosniff',
954
+ 'referrer-policy': 'no-referrer',
955
+ })
956
+ }
957
+
958
+ if (method === 'POST' && route === '/refresh') {
959
+ // 1.11.24:默认先比指纹,没变就直接把现有图还回去。
960
+ // 以前这里一律 force:true,用户按一次「重建星图」就要白付 5 秒 CPU,
961
+ // 而磁盘上一个字节都没动。真要强制重建就带 ?force=1。
962
+ const force = url.searchParams.get('force') === '1'
963
+ const rebuilt = await src.refresh({ force })
964
+ const last = src.lastRefresh || {}
965
+ const graph = src.publicGraph()
966
+ return sendJson(req, res, 200, {
967
+ ...graph,
968
+ version: VERSION,
969
+ build: BUILD,
970
+ sig: src.signature || '',
971
+ rebuilt,
972
+ // 三态照实说:重建 / 没变 / 等别人建完。界面不该把后两种混成一句话。
973
+ unchanged: Boolean(last.rebuilt) === false && last.why === 'unchanged',
974
+ why: last.why || '',
975
+ refreshMs: Number(last.ms) || 0,
976
+ })
977
+ }
978
+
979
+ return sendJson(req, res, 404, { error: '未知接口 ' + route })
980
+ } catch (err) {
981
+ // 引擎抛的错误带 status(比如「找不到这两条记忆」= 404)就照用,
982
+ // 其余才是真·服务器错误。以前一律 500,前端只能显示「加载失败」。
983
+ const status = Number(err?.status) || 500
984
+ if (status >= 500) log(`接口 ${route} 出错:${err?.stack || err}`)
985
+ return sendJson(req, res, status, { error: String(err?.message || err) })
986
+ }
987
+ }
988
+
989
+ webServer.register({ kind: 'prefix', path: PREFIX, handler })
990
+ return PREFIX
991
+ }
992
+
993
+ export { PREFIX, BUILD, VERSION, STARTED_AT }