macro-memory 0.0.0-stage → 0.9.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/LICENSE +21 -0
- package/README.md +384 -2
- package/bin/macro-memory.mjs +732 -0
- package/docs/CHANGELOG.md +250 -0
- package/docs/MAC.md +156 -0
- package/docs/images/_architecture.svg +70 -0
- package/docs/images/_memory-flow.svg +75 -0
- package/docs/images/_token-budget.svg +40 -0
- package/docs/images/architecture.png +0 -0
- package/docs/images/hero.png +0 -0
- package/docs/images/memory-flow.png +0 -0
- package/docs/images/src/graph.html +78 -0
- package/docs/images/src/hero.html +88 -0
- package/docs/images/src/panel.html +63 -0
- package/docs/images/src/pipeline.html +97 -0
- package/docs/images/token-budget.png +0 -0
- package/lib/client.js +3811 -0
- package/lib/core/agents-file.js +95 -0
- package/lib/core/client.js +313 -0
- package/lib/core/compat/dsh-llm.js +78 -0
- package/lib/core/config.js +117 -0
- package/lib/core/engine.js +456 -0
- package/lib/core/fence.js +109 -0
- package/lib/core/index.js +102 -0
- package/lib/core/migrate.js +70 -0
- package/lib/core/mini-host.js +324 -0
- package/lib/core/owner.js +347 -0
- package/lib/core/paths.js +95 -0
- package/lib/core/serve.js +378 -0
- package/lib/core/trust.js +173 -0
- package/lib/index.js +567 -0
- package/lib/macro/brand.js +82 -0
- package/lib/macro/bridge.js +158 -0
- package/lib/macro/chain.js +206 -0
- package/lib/macro/contract.js +471 -0
- package/lib/macro/cost.js +164 -0
- package/lib/macro/defs/admin.js +528 -0
- package/lib/macro/defs/dream.js +24 -0
- package/lib/macro/defs/link.js +408 -0
- package/lib/macro/defs/project.js +237 -0
- package/lib/macro/defs/read.js +160 -0
- package/lib/macro/defs/remember.js +411 -0
- package/lib/macro/defs/search.js +899 -0
- package/lib/macro/defs/update.js +161 -0
- package/lib/macro/dreamledger.js +1398 -0
- package/lib/macro/facade.js +135 -0
- package/lib/macro/fusion.js +188 -0
- package/lib/macro/injectledger.js +843 -0
- package/lib/macro/linkflow.js +391 -0
- package/lib/macro/links.js +448 -0
- package/lib/macro/neighbor.js +1083 -0
- package/lib/macro/panel.js +96 -0
- package/lib/macro/platform.js +134 -0
- package/lib/macro/prompt.js +139 -0
- package/lib/macro/provenance.js +148 -0
- package/lib/macro/render.js +35 -0
- package/lib/macro/revisions.js +253 -0
- package/lib/macro/shared.js +113 -0
- package/lib/macro/shortid.js +114 -0
- package/lib/macro/snapshot.js +700 -0
- package/lib/macro/spend.js +312 -0
- package/lib/macro/store.js +238 -0
- package/lib/macro/supersede.js +197 -0
- package/lib/macro/tokencost.js +90 -0
- package/lib/macro/tools.js +67 -0
- package/lib/mcp/server.js +196 -0
- package/lib/mcp/stdio.js +151 -0
- package/lib/ui/page.js +300 -0
- package/lib/ui/server.js +226 -0
- package/package.json +56 -4
- package/vendor/VENDOR.json +39 -0
- package/vendor/cosmokit/LICENSE +21 -0
- package/vendor/cosmokit/README.md +30 -0
- package/vendor/cosmokit/lib/index.js +418 -0
- package/vendor/cosmokit/lib/types/array.d.ts +15 -0
- package/vendor/cosmokit/lib/types/array.d.ts.map +1 -0
- package/vendor/cosmokit/lib/types/index.d.ts +13 -0
- package/vendor/cosmokit/lib/types/index.d.ts.map +1 -0
- package/vendor/cosmokit/lib/types/misc.d.ts +41 -0
- package/vendor/cosmokit/lib/types/misc.d.ts.map +1 -0
- package/vendor/cosmokit/lib/types/string.d.ts +89 -0
- package/vendor/cosmokit/lib/types/string.d.ts.map +1 -0
- package/vendor/cosmokit/lib/types/time.d.ts +19 -0
- package/vendor/cosmokit/lib/types/time.d.ts.map +1 -0
- package/vendor/cosmokit/lib/types/types.d.ts +42 -0
- package/vendor/cosmokit/lib/types/types.d.ts.map +1 -0
- package/vendor/cosmokit/lib/types/volatile.d.ts +40 -0
- package/vendor/cosmokit/lib/types/volatile.d.ts.map +1 -0
- package/vendor/cosmokit/package.json +32 -0
- package/vendor/cosmokit/src/array.ts +42 -0
- package/vendor/cosmokit/src/index.ts +12 -0
- package/vendor/cosmokit/src/misc.ts +78 -0
- package/vendor/cosmokit/src/string.ts +113 -0
- package/vendor/cosmokit/src/time.ts +92 -0
- package/vendor/cosmokit/src/types.ts +168 -0
- package/vendor/cosmokit/src/volatile.ts +86 -0
- package/vendor/dsh-memory-nebula/CONTRIBUTING.md +48 -0
- package/vendor/dsh-memory-nebula/LICENSE +21 -0
- package/vendor/dsh-memory-nebula/README.en.md +203 -0
- package/vendor/dsh-memory-nebula/README.md +253 -0
- package/vendor/dsh-memory-nebula/SECURITY.md +43 -0
- package/vendor/dsh-memory-nebula/SUPPORT.md +33 -0
- package/vendor/dsh-memory-nebula/cordis.patch.yml +4 -0
- package/vendor/dsh-memory-nebula/lib/client.js +105 -0
- package/vendor/dsh-memory-nebula/lib/host/adapters/index.js +279 -0
- package/vendor/dsh-memory-nebula/lib/host/adapters/ingest.js +230 -0
- package/vendor/dsh-memory-nebula/lib/host/adapters/meow.js +320 -0
- package/vendor/dsh-memory-nebula/lib/host/adapters/notes.js +305 -0
- package/vendor/dsh-memory-nebula/lib/host/adapters/sqlite.js +287 -0
- package/vendor/dsh-memory-nebula/lib/host/adapters/util.js +231 -0
- package/vendor/dsh-memory-nebula/lib/host/bridge.js +351 -0
- package/vendor/dsh-memory-nebula/lib/host/compress.js +97 -0
- package/vendor/dsh-memory-nebula/lib/host/demo.js +357 -0
- package/vendor/dsh-memory-nebula/lib/host/diagnostics.js +125 -0
- package/vendor/dsh-memory-nebula/lib/host/doctor.js +270 -0
- package/vendor/dsh-memory-nebula/lib/host/entities.js +230 -0
- package/vendor/dsh-memory-nebula/lib/host/graph.js +1762 -0
- package/vendor/dsh-memory-nebula/lib/host/graphcache.js +290 -0
- package/vendor/dsh-memory-nebula/lib/host/http.js +993 -0
- package/vendor/dsh-memory-nebula/lib/host/injectcfg.js +95 -0
- package/vendor/dsh-memory-nebula/lib/host/ledger.js +175 -0
- package/vendor/dsh-memory-nebula/lib/host/live.js +204 -0
- package/vendor/dsh-memory-nebula/lib/host/nebula.js +2105 -0
- package/vendor/dsh-memory-nebula/lib/host/page.js +75 -0
- package/vendor/dsh-memory-nebula/lib/host/path.js +83 -0
- package/vendor/dsh-memory-nebula/lib/host/recall.js +526 -0
- package/vendor/dsh-memory-nebula/lib/host/share.js +633 -0
- package/vendor/dsh-memory-nebula/lib/host/sources.js +266 -0
- package/vendor/dsh-memory-nebula/lib/host/store.js +333 -0
- package/vendor/dsh-memory-nebula/lib/host/text.js +410 -0
- package/vendor/dsh-memory-nebula/lib/host/transcripts.js +396 -0
- package/vendor/dsh-memory-nebula/lib/index.js +782 -0
- package/vendor/dsh-memory-nebula/lib/standalone.mjs +315 -0
- package/vendor/dsh-memory-nebula/lib/web/api.js +426 -0
- package/vendor/dsh-memory-nebula/lib/web/app.js +4172 -0
- package/vendor/dsh-memory-nebula/lib/web/i18n.js +580 -0
- package/vendor/dsh-memory-nebula/lib/web/index.html +174 -0
- package/vendor/dsh-memory-nebula/lib/web/nav.js +132 -0
- package/vendor/dsh-memory-nebula/lib/web/render.js +1890 -0
- package/vendor/dsh-memory-nebula/lib/web/space3d.js +1883 -0
- package/vendor/dsh-memory-nebula/lib/web/style.css +1402 -0
- package/vendor/dsh-memory-nebula/locale/en.json +7 -0
- package/vendor/dsh-memory-nebula/locale/zh.json +7 -0
- package/vendor/dsh-memory-nebula/market/assets/icon-180.png +0 -0
- package/vendor/dsh-memory-nebula/market/assets/icon.svg +40 -0
- package/vendor/dsh-memory-nebula/market/index.json +101 -0
- package/vendor/dsh-memory-nebula/package.json +87 -0
- package/vendor/dsh-memory-nebula/sidecar.ps1 +119 -0
- package/vendor/meow-memory/LICENSE +21 -0
- package/vendor/meow-memory/README.en.md +192 -0
- package/vendor/meow-memory/README.md +174 -0
- package/vendor/meow-memory/README.pt-br.md +180 -0
- package/vendor/meow-memory/cordis.patch.yml +7 -0
- package/vendor/meow-memory/lib/client.js +3354 -0
- package/vendor/meow-memory/lib/client.js.map +7 -0
- package/vendor/meow-memory/lib/index.js +13500 -0
- package/vendor/meow-memory/lib/index.js.map +7 -0
- package/vendor/meow-memory/lib/prompts/README.md +65 -0
- package/vendor/meow-memory/lib/prompts/en/dream-atomic.md +36 -0
- package/vendor/meow-memory/lib/prompts/en/dream-header.md +9 -0
- package/vendor/meow-memory/lib/prompts/en/dream-project-summary.md +12 -0
- package/vendor/meow-memory/lib/prompts/en/dream-topic.md +27 -0
- package/vendor/meow-memory/lib/prompts/en/external-memory-notice.md +8 -0
- package/vendor/meow-memory/lib/prompts/en/first-create-notice.md +8 -0
- package/vendor/meow-memory/lib/prompts/en/labels.md +104 -0
- package/vendor/meow-memory/lib/prompts/en/reflect.md +31 -0
- package/vendor/meow-memory/lib/prompts/en/system-guide.md +121 -0
- package/vendor/meow-memory/lib/prompts/en/tools.md +83 -0
- package/vendor/meow-memory/lib/prompts/en/welcome-guide.md +12 -0
- package/vendor/meow-memory/lib/prompts/pt-br/dream-atomic.md +36 -0
- package/vendor/meow-memory/lib/prompts/pt-br/dream-header.md +9 -0
- package/vendor/meow-memory/lib/prompts/pt-br/dream-project-summary.md +12 -0
- package/vendor/meow-memory/lib/prompts/pt-br/dream-topic.md +27 -0
- package/vendor/meow-memory/lib/prompts/pt-br/external-memory-notice.md +8 -0
- package/vendor/meow-memory/lib/prompts/pt-br/first-create-notice.md +8 -0
- package/vendor/meow-memory/lib/prompts/pt-br/labels.md +104 -0
- package/vendor/meow-memory/lib/prompts/pt-br/reflect.md +31 -0
- package/vendor/meow-memory/lib/prompts/pt-br/system-guide.md +121 -0
- package/vendor/meow-memory/lib/prompts/pt-br/tools.md +83 -0
- package/vendor/meow-memory/lib/prompts/pt-br/welcome-guide.md +12 -0
- package/vendor/meow-memory/lib/prompts/zh/dream-atomic.md +36 -0
- package/vendor/meow-memory/lib/prompts/zh/dream-header.md +9 -0
- package/vendor/meow-memory/lib/prompts/zh/dream-project-summary.md +19 -0
- package/vendor/meow-memory/lib/prompts/zh/dream-topic.md +27 -0
- package/vendor/meow-memory/lib/prompts/zh/external-memory-notice.md +8 -0
- package/vendor/meow-memory/lib/prompts/zh/first-create-notice.md +8 -0
- package/vendor/meow-memory/lib/prompts/zh/labels.md +104 -0
- package/vendor/meow-memory/lib/prompts/zh/reflect.md +30 -0
- package/vendor/meow-memory/lib/prompts/zh/system-guide.md +119 -0
- package/vendor/meow-memory/lib/prompts/zh/tools.md +83 -0
- package/vendor/meow-memory/lib/prompts/zh/welcome-guide.md +12 -0
- package/vendor/meow-memory/package.json +64 -0
- package/vendor/schemastery/LICENSE +21 -0
- package/vendor/schemastery/README.md +393 -0
- package/vendor/schemastery/lib/index.cjs +635 -0
- package/vendor/schemastery/lib/index.mjs +637 -0
- package/vendor/schemastery/lib/types/index.d.ts +211 -0
- package/vendor/schemastery/lib/types/index.d.ts.map +1 -0
- package/vendor/schemastery/package.json +39 -0
- package/vendor/schemastery/src/index.ts +962 -0
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 单写者服务 `serve`(PLAN 第 6 节 / P1-1 / U7 / U9)。
|
|
3
|
+
*
|
|
4
|
+
* 三件事只有它能做:唯一的写连接、唯一跑 dream 的、唯一打快照的。
|
|
5
|
+
* 其余进程要么直连(没服务时),要么把活交给它(有服务时)——两个写者同时开
|
|
6
|
+
* 一个库,是这类插件唯一真会丢数据的坏,别的都能修。
|
|
7
|
+
*
|
|
8
|
+
* 传输:默认 TCP `127.0.0.1:0`(随机端口),非 Windows 额外挂一条 UDS
|
|
9
|
+
* (`<dataDir>/serve.sock`);端点信息写进 `<dataDir>/serve.json`,客户端按它探测。
|
|
10
|
+
* 鉴权:一次性随机 token 写进 `serve.json`(0600),请求头 `Bearer`。
|
|
11
|
+
*
|
|
12
|
+
* 崩溃语义(U9):
|
|
13
|
+
* agent 死 → 只是连接断了,服务与库都不受影响
|
|
14
|
+
* 服务死 → 客户端探不通 → 写落 `pending.jsonl` → 回执写明「没写进库」
|
|
15
|
+
* 服务回来 → 客户端下次调用先补交(按 requestId 去重,重发不会写两遍)
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import crypto from 'node:crypto'
|
|
19
|
+
import fs from 'node:fs'
|
|
20
|
+
import http from 'node:http'
|
|
21
|
+
import os from 'node:os'
|
|
22
|
+
import path from 'node:path'
|
|
23
|
+
|
|
24
|
+
import { DEDUP_WINDOW, PENDING_FILE, pendingCount, readServeInfo, removeServeInfo, writeServeInfo, serveFilePath } from './client.js'
|
|
25
|
+
import { createMacroEngine, resolveDataDir, CORE_NAME } from './engine.js'
|
|
26
|
+
// 平台判断只有 platform.js 一个入口(probe-platform P8 会盯着这条):这里不许自己去问宿主平台
|
|
27
|
+
import { isWindows, platformName } from '../macro/platform.js'
|
|
28
|
+
|
|
29
|
+
const VERSION = (() => {
|
|
30
|
+
try {
|
|
31
|
+
const pkg = JSON.parse(fs.readFileSync(new URL('../../package.json', import.meta.url), 'utf8'))
|
|
32
|
+
return typeof pkg.version === 'string' ? pkg.version : '0.0.0'
|
|
33
|
+
} catch {
|
|
34
|
+
return '0.0.0'
|
|
35
|
+
}
|
|
36
|
+
})()
|
|
37
|
+
|
|
38
|
+
function jsonRes(res, status, obj) {
|
|
39
|
+
const body = `${JSON.stringify(obj)}\n`
|
|
40
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'content-length': Buffer.byteLength(body) })
|
|
41
|
+
res.end(body)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function readJson(req) {
|
|
45
|
+
return new Promise((resolve, reject) => {
|
|
46
|
+
const chunks = []
|
|
47
|
+
let size = 0
|
|
48
|
+
req.on('data', (c) => {
|
|
49
|
+
size += c.length
|
|
50
|
+
if (size > 8 * 1024 * 1024) {
|
|
51
|
+
reject(new Error('请求体超过 8 MB'))
|
|
52
|
+
req.destroy()
|
|
53
|
+
return
|
|
54
|
+
}
|
|
55
|
+
chunks.push(c)
|
|
56
|
+
})
|
|
57
|
+
req.on('end', () => {
|
|
58
|
+
const text = Buffer.concat(chunks).toString('utf8')
|
|
59
|
+
if (text.trim().length === 0) return resolve({})
|
|
60
|
+
try {
|
|
61
|
+
resolve(JSON.parse(text))
|
|
62
|
+
} catch (err) {
|
|
63
|
+
reject(new Error(`请求体不是 JSON:${err.message}`))
|
|
64
|
+
}
|
|
65
|
+
})
|
|
66
|
+
req.on('error', reject)
|
|
67
|
+
})
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* 起一个服务。
|
|
72
|
+
* @param {object} opts 同 `createMacroEngine`,外加 `port` / `host` / `defaultCwd` / `quiet`
|
|
73
|
+
* @returns {Promise<{url:string, token:string, pid:number, info:object, stats:Function, close:Function, server:object}>}
|
|
74
|
+
*/
|
|
75
|
+
export async function startServe(opts = {}) {
|
|
76
|
+
const dataDir = resolveDataDir({ dir: opts.dataDir })
|
|
77
|
+
const token = crypto.randomBytes(24).toString('hex')
|
|
78
|
+
const startedAt = Date.now()
|
|
79
|
+
const engine = await createMacroEngine({ ...opts, dataDir, serve: 'off' })
|
|
80
|
+
const defaultCwd = path.resolve(opts.defaultCwd ?? opts.cwd ?? process.cwd())
|
|
81
|
+
|
|
82
|
+
// FIFO 队列:一条一个短事务。用 promise 链串行化,前一条失败不影响后一条。
|
|
83
|
+
let tail = Promise.resolve()
|
|
84
|
+
let queued = 0
|
|
85
|
+
let maxQueue = 0
|
|
86
|
+
function enqueue(job) {
|
|
87
|
+
queued += 1
|
|
88
|
+
if (queued > maxQueue) maxQueue = queued
|
|
89
|
+
const run = tail.then(job, job)
|
|
90
|
+
tail = run.then(
|
|
91
|
+
() => {},
|
|
92
|
+
() => {},
|
|
93
|
+
)
|
|
94
|
+
return run.finally(() => {
|
|
95
|
+
queued -= 1
|
|
96
|
+
})
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const counts = { calls: 0, writes: 0, dedup: 0, failed: 0, attaches: 0 }
|
|
100
|
+
const memo = new Map() // requestId -> 回执(去重窗口)
|
|
101
|
+
const agents = new Map() // agent 名 -> {first, last, n}
|
|
102
|
+
const listeners = new Set() // SSE
|
|
103
|
+
|
|
104
|
+
function remember(id, payload) {
|
|
105
|
+
memo.set(id, payload)
|
|
106
|
+
if (memo.size > DEDUP_WINDOW) {
|
|
107
|
+
const first = memo.keys().next().value
|
|
108
|
+
if (first !== undefined) memo.delete(first)
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function noteAgent(agent) {
|
|
113
|
+
const key = typeof agent === 'string' && agent.length > 0 ? agent : 'anonymous'
|
|
114
|
+
const row = agents.get(key) ?? { first: Date.now(), last: 0, n: 0 }
|
|
115
|
+
row.last = Date.now()
|
|
116
|
+
row.n += 1
|
|
117
|
+
agents.set(key, row)
|
|
118
|
+
return key
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function broadcast(event, data) {
|
|
122
|
+
const frame = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`
|
|
123
|
+
for (const res of listeners) {
|
|
124
|
+
try {
|
|
125
|
+
res.write(frame)
|
|
126
|
+
} catch {
|
|
127
|
+
listeners.delete(res)
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function stats() {
|
|
133
|
+
return {
|
|
134
|
+
name: CORE_NAME,
|
|
135
|
+
version: VERSION,
|
|
136
|
+
pid: process.pid,
|
|
137
|
+
url,
|
|
138
|
+
dataDir,
|
|
139
|
+
defaultCwd,
|
|
140
|
+
startedAt,
|
|
141
|
+
uptimeMs: Date.now() - startedAt,
|
|
142
|
+
...counts,
|
|
143
|
+
queue: queued,
|
|
144
|
+
maxQueue,
|
|
145
|
+
dedupWindow: memo.size,
|
|
146
|
+
pending: pendingCount(dataDir),
|
|
147
|
+
agents: [...agents.entries()].map(([agent, row]) => ({ agent, n: row.n, first: row.first, last: row.last })),
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** `/call` 与 `/write` 共用:写走队列,读也走队列(保证「读到刚写完的」)。 */
|
|
152
|
+
async function handleCall(body) {
|
|
153
|
+
const tool = typeof body.tool === 'string' && body.tool.length > 0 ? body.tool : 'memory_remember'
|
|
154
|
+
const args = body.args && typeof body.args === 'object' ? body.args : {}
|
|
155
|
+
const cwd = typeof body.cwd === 'string' && body.cwd.length > 0 ? path.resolve(body.cwd) : defaultCwd
|
|
156
|
+
const agent = noteAgent(body.agent)
|
|
157
|
+
const requestId = typeof body.requestId === 'string' ? body.requestId : ''
|
|
158
|
+
if (requestId.length > 0) {
|
|
159
|
+
const hit = memo.get(requestId)
|
|
160
|
+
if (hit) {
|
|
161
|
+
counts.dedup += 1
|
|
162
|
+
return { ...hit, deduped: true }
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
const payload = await enqueue(async () => {
|
|
166
|
+
counts.calls += 1
|
|
167
|
+
try {
|
|
168
|
+
const result = await engine.call(tool, args, {
|
|
169
|
+
cwd,
|
|
170
|
+
agentId: agent,
|
|
171
|
+
sessionId: body.session,
|
|
172
|
+
noServe: true,
|
|
173
|
+
})
|
|
174
|
+
if (String(tool).startsWith('memory_') && (tool === 'memory_remember' || tool === 'memory_update' || tool === 'memory_link')) {
|
|
175
|
+
counts.writes += 1
|
|
176
|
+
}
|
|
177
|
+
return {
|
|
178
|
+
ok: true,
|
|
179
|
+
tool,
|
|
180
|
+
text: result.text ?? '',
|
|
181
|
+
value: result.value ?? null,
|
|
182
|
+
refused: result.refused === true,
|
|
183
|
+
}
|
|
184
|
+
} catch (err) {
|
|
185
|
+
counts.failed += 1
|
|
186
|
+
return { ok: false, tool, text: `服务里执行失败:${err?.message ?? err}`, value: null, error: String(err?.message ?? err) }
|
|
187
|
+
}
|
|
188
|
+
})
|
|
189
|
+
if (requestId.length > 0) remember(requestId, payload)
|
|
190
|
+
broadcast('call', { tool, agent, at: Date.now(), ok: payload.ok })
|
|
191
|
+
return payload
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const server = http.createServer(async (req, res) => {
|
|
195
|
+
const urlPath = (req.url ?? '/').split('?')[0]
|
|
196
|
+
const query = new URLSearchParams((req.url ?? '').split('?')[1] ?? '')
|
|
197
|
+
const given = String(req.headers.authorization ?? '').replace(/^Bearer\s+/i, '')
|
|
198
|
+
if (given !== token) return jsonRes(res, 401, { ok: false, error: 'token 不对(看 serve.json 里的 token)' })
|
|
199
|
+
|
|
200
|
+
try {
|
|
201
|
+
if (req.method === 'GET' && urlPath === '/stats') return jsonRes(res, 200, stats())
|
|
202
|
+
|
|
203
|
+
if (req.method === 'GET' && urlPath === '/events') {
|
|
204
|
+
res.writeHead(200, {
|
|
205
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
206
|
+
'cache-control': 'no-cache',
|
|
207
|
+
connection: 'keep-alive',
|
|
208
|
+
})
|
|
209
|
+
res.write(`event: hello\ndata: ${JSON.stringify({ pid: process.pid, at: Date.now() })}\n\n`)
|
|
210
|
+
listeners.add(res)
|
|
211
|
+
const beat = setInterval(() => {
|
|
212
|
+
try {
|
|
213
|
+
res.write(`: ping ${Date.now()}\n\n`)
|
|
214
|
+
} catch {
|
|
215
|
+
clearInterval(beat)
|
|
216
|
+
listeners.delete(res)
|
|
217
|
+
}
|
|
218
|
+
}, 15000)
|
|
219
|
+
req.on('close', () => {
|
|
220
|
+
clearInterval(beat)
|
|
221
|
+
listeners.delete(res)
|
|
222
|
+
})
|
|
223
|
+
return undefined
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
if (req.method === 'POST' && (urlPath === '/call' || urlPath === '/write')) {
|
|
227
|
+
const body = await readJson(req)
|
|
228
|
+
const out = await handleCall(body)
|
|
229
|
+
return jsonRes(res, 200, out)
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (req.method === 'GET' && urlPath === '/search') {
|
|
233
|
+
const out = await handleCall({
|
|
234
|
+
tool: 'memory_search',
|
|
235
|
+
args: { query: query.get('q') ?? '', ...(query.get('k') ? { k: Number(query.get('k')) } : {}), ...(query.get('mode') ? { mode: query.get('mode') } : {}) },
|
|
236
|
+
cwd: query.get('cwd') ?? undefined,
|
|
237
|
+
agent: query.get('agent') ?? 'http',
|
|
238
|
+
})
|
|
239
|
+
return jsonRes(res, 200, out)
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
if (req.method === 'GET' && urlPath === '/read') {
|
|
243
|
+
const out = await handleCall({ tool: 'memory_read', args: { id: query.get('id') ?? '' }, cwd: query.get('cwd') ?? undefined, agent: query.get('agent') ?? 'http' })
|
|
244
|
+
return jsonRes(res, 200, out)
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// 管理界面(PLAN §10 / P2-1)要的两块数据:分布账与 L0 注入预览。
|
|
248
|
+
// 都**不直连库**:UI 走这两个端点,serve 才是库的主人;只读,不建库不建表。
|
|
249
|
+
if (req.method === 'GET' && urlPath === '/census') {
|
|
250
|
+
const cwdArg = query.get('cwd') ?? opts.cwd ?? process.cwd()
|
|
251
|
+
try {
|
|
252
|
+
return jsonRes(res, 200, { ok: true, ...engine.census(cwdArg) })
|
|
253
|
+
} catch (err) {
|
|
254
|
+
return jsonRes(res, 500, { ok: false, error: String(err?.message ?? err) })
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
if (req.method === 'GET' && urlPath === '/inject') {
|
|
259
|
+
const raw = query.get('maxChars')
|
|
260
|
+
const maxChars = raw !== null && Number.isFinite(Number(raw)) && Number(raw) > 0 ? Number(raw) : undefined
|
|
261
|
+
const text = engine.injection({ ...(maxChars === undefined ? {} : { maxChars }) })
|
|
262
|
+
return jsonRes(res, 200, { ok: true, text, chars: String(text ?? '').length })
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
if (req.method === 'POST' && urlPath === '/attach') {
|
|
266
|
+
const body = await readJson(req)
|
|
267
|
+
counts.attaches += 1
|
|
268
|
+
const agent = noteAgent(body.agent)
|
|
269
|
+
return jsonRes(res, 200, { ok: true, mode: 'shared', agent, pid: process.pid, url, startedAt, defaultCwd })
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
if (req.method === 'POST' && urlPath === '/detach') {
|
|
273
|
+
const body = await readJson(req)
|
|
274
|
+
const agent = typeof body.agent === 'string' ? body.agent : ''
|
|
275
|
+
if (body.shutdown === true) {
|
|
276
|
+
jsonRes(res, 200, { ok: true, shutdown: true })
|
|
277
|
+
setImmediate(() => {
|
|
278
|
+
void close('detach-shutdown')
|
|
279
|
+
})
|
|
280
|
+
return undefined
|
|
281
|
+
}
|
|
282
|
+
return jsonRes(res, 200, { ok: true, mode: 'shared', detached: agent })
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
if (req.method === 'GET' && urlPath === '/health') return jsonRes(res, 200, { ok: true })
|
|
286
|
+
|
|
287
|
+
return jsonRes(res, 404, { ok: false, error: `没有这个端点 ${req.method} ${urlPath}` })
|
|
288
|
+
} catch (err) {
|
|
289
|
+
counts.failed += 1
|
|
290
|
+
return jsonRes(res, 500, { ok: false, error: String(err?.message ?? err) })
|
|
291
|
+
}
|
|
292
|
+
})
|
|
293
|
+
|
|
294
|
+
let socketPath = ''
|
|
295
|
+
await new Promise((resolve, reject) => {
|
|
296
|
+
server.once('error', reject)
|
|
297
|
+
const port = Number.isInteger(opts.port) ? opts.port : 0
|
|
298
|
+
const host = typeof opts.host === 'string' && opts.host.length > 0 ? opts.host : '127.0.0.1'
|
|
299
|
+
server.listen(port, host, () => resolve())
|
|
300
|
+
})
|
|
301
|
+
const addr = server.address()
|
|
302
|
+
const url = `http://${typeof opts.host === 'string' && opts.host.length > 0 ? opts.host : '127.0.0.1'}:${addr && typeof addr === 'object' ? addr.port : 0}`
|
|
303
|
+
|
|
304
|
+
if (!isWindows()) {
|
|
305
|
+
// UDS 是 Unix 上的首选(不用端口、不用防火墙),TCP 那条留着当后备。
|
|
306
|
+
try {
|
|
307
|
+
const uds = http.createServer(server.listeners('request')[0])
|
|
308
|
+
socketPath = path.join(dataDir, 'serve.sock')
|
|
309
|
+
fs.rmSync(socketPath, { force: true })
|
|
310
|
+
await new Promise((resolve, reject) => {
|
|
311
|
+
uds.once('error', reject)
|
|
312
|
+
uds.listen(socketPath, () => resolve())
|
|
313
|
+
})
|
|
314
|
+
server.uds = uds
|
|
315
|
+
} catch {
|
|
316
|
+
socketPath = ''
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
const info = {
|
|
321
|
+
name: CORE_NAME,
|
|
322
|
+
version: VERSION,
|
|
323
|
+
pid: process.pid,
|
|
324
|
+
url,
|
|
325
|
+
...(socketPath ? { socketPath } : {}),
|
|
326
|
+
token,
|
|
327
|
+
dataDir,
|
|
328
|
+
defaultCwd,
|
|
329
|
+
startedAt,
|
|
330
|
+
platform: platformName(),
|
|
331
|
+
host: os.hostname(),
|
|
332
|
+
file: serveFilePath(dataDir),
|
|
333
|
+
}
|
|
334
|
+
// publish=false:只在本进程里当服务用,**不写发现文件**——管理界面(`macro-memory ui`)
|
|
335
|
+
// 借不到现成服务时会临时起一个,它没有资格把别人的 `serve.json` 换成自己的。
|
|
336
|
+
const publish = opts.publish !== false
|
|
337
|
+
writeServeInfo(dataDir, info, { publish })
|
|
338
|
+
|
|
339
|
+
let closed = false
|
|
340
|
+
async function close(reason = 'manual') {
|
|
341
|
+
if (closed) return { reason, already: true }
|
|
342
|
+
closed = true
|
|
343
|
+
for (const res of listeners) {
|
|
344
|
+
try {
|
|
345
|
+
res.end()
|
|
346
|
+
} catch {
|
|
347
|
+
// 已经断了
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
listeners.clear()
|
|
351
|
+
await new Promise((resolve) => server.close(() => resolve()))
|
|
352
|
+
if (server.uds) await new Promise((resolve) => server.uds.close(() => resolve()))
|
|
353
|
+
if (socketPath) fs.rmSync(socketPath, { force: true })
|
|
354
|
+
await tail.catch(() => {})
|
|
355
|
+
const removed = removeServeInfo(dataDir, token)
|
|
356
|
+
try {
|
|
357
|
+
await engine.close()
|
|
358
|
+
} catch {
|
|
359
|
+
// 关引擎失败不影响「服务已停」这个事实
|
|
360
|
+
}
|
|
361
|
+
return { reason, removed, stats: stats() }
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
return { url, token, pid: process.pid, info, stats, close, server, dataDir, engine }
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** 便捷读口:从 `serve.json` 里拿 token 后打一条 `/stats`。 */
|
|
368
|
+
export async function serveStats(dataDir) {
|
|
369
|
+
const info = readServeInfo(dataDir)
|
|
370
|
+
if (!info) return { mode: 'standalone', reason: 'no-serve-json', pending: pendingCount(dataDir), file: serveFilePath(dataDir), pendingFile: path.join(dataDir, PENDING_FILE) }
|
|
371
|
+
const { request, discover } = await import('./client.js')
|
|
372
|
+
const found = await discover(dataDir)
|
|
373
|
+
if (found.mode !== 'shared') {
|
|
374
|
+
return { mode: 'stale', reason: found.reason, info: { pid: info.pid, url: info.url, startedAt: info.startedAt }, pending: pendingCount(dataDir), file: serveFilePath(dataDir) }
|
|
375
|
+
}
|
|
376
|
+
const res = await request(info, 'GET', '/stats', undefined, { timeout: 2000 })
|
|
377
|
+
return { mode: 'shared', stats: res.json, pending: pendingCount(dataDir), file: serveFilePath(dataDir) }
|
|
378
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* core/trust —— workspace 记忆库的信任门。
|
|
3
|
+
*
|
|
4
|
+
* 为什么 core 自己要管这件事:meow 有一个 #64 的防护——**工作区里自带的外部记忆库**
|
|
5
|
+
* (`.dsh-meow` 不是本机创建的)默认关掉读写,免得 clone 一个别人的仓库就被塞一嘴
|
|
6
|
+
* 别人写的「记忆」。DSH 里的解法是让主人手打 `/meow-trust`;可 MCP / CLI 场景没有
|
|
7
|
+
* 斜杠命令,只剩一堵墙。所以 core 把同一套 marker 搬到可编程的一侧:
|
|
8
|
+
*
|
|
9
|
+
* <activeHomeDir>/trusted-workspaces/<sha256(规范化路径)>.json
|
|
10
|
+
* { path, trustedAt, trustedSource }
|
|
11
|
+
*
|
|
12
|
+
* 与 meow 完全同一格式、同一哈希(小写 + 正斜杠 + 去尾斜杠),所以:
|
|
13
|
+
* - core 信任过的目录,DSH 那边立刻也认(不需要两边各点一次);
|
|
14
|
+
* - 反之亦然。
|
|
15
|
+
*
|
|
16
|
+
* 默认策略 `auto`:只在「这个库目录不存在,或者存在但里面只有本插件的产物」时自动
|
|
17
|
+
* 信任——这正是 meow 自己 `created-empty` 的口径。目录里有别的东西(说明库是别人带来
|
|
18
|
+
* 的),一律不猜,回一句「跑 macro-memory trust」让人自己决定。
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import crypto from 'node:crypto'
|
|
22
|
+
import fs from 'node:fs'
|
|
23
|
+
import path from 'node:path'
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* meow 创建库时允许出现的文件:这些不算「外部内容」。
|
|
27
|
+
*
|
|
28
|
+
* `sessions` / `archived-sessions` 这两项是 0.9.0 补的,踩出来的:meow 会把每个会话的
|
|
29
|
+
* 状态快照写进 `<workspace>/<库目录>/sessions/`,于是一个**本机建、本机用**的库在第二个
|
|
30
|
+
* 进程眼里就成了「目录里有不是本插件产生的文件」。多 agent 场景下这件事一天能撞十次:
|
|
31
|
+
* DSH 里用的库,轮到 MCP / CLI / 管理界面接手时全被判成「别处带来的库」。
|
|
32
|
+
* 凡是本插件自己会写的名字都要在这里,否则护栏会把自己人拦在门外。
|
|
33
|
+
*/
|
|
34
|
+
export const CREATION_IGNORE = new Set([
|
|
35
|
+
'memory.db',
|
|
36
|
+
'memory.db-wal',
|
|
37
|
+
'memory.db-shm',
|
|
38
|
+
'memory.db.tmp',
|
|
39
|
+
'memory.db.bak',
|
|
40
|
+
'dream-debug.log',
|
|
41
|
+
'dream-debug.log.old',
|
|
42
|
+
'sessions',
|
|
43
|
+
'archived-sessions',
|
|
44
|
+
'nebula.db',
|
|
45
|
+
'nebula.db-wal',
|
|
46
|
+
'nebula.db-shm',
|
|
47
|
+
'nebula.db.tmp',
|
|
48
|
+
])
|
|
49
|
+
|
|
50
|
+
/** 带后缀的变体(`memory.db.20260101.bak`、`nebula.db.tmp` 这类)按前缀认。 */
|
|
51
|
+
export const CREATION_PREFIX = ['memory.db.', 'nebula.db.', 'dream-debug.log.']
|
|
52
|
+
|
|
53
|
+
/** 这个目录项是不是本插件自己的产物?护栏只该拦「不是我们的」。 */
|
|
54
|
+
export function isCreationArtifact(name) {
|
|
55
|
+
const n = String(name ?? '')
|
|
56
|
+
if (CREATION_IGNORE.has(n)) return true
|
|
57
|
+
return CREATION_PREFIX.some((p) => n.startsWith(p))
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** 与 meow 的 normalizeWorkspacePath 一致:Windows 大小写不敏感,统一小写 + 正斜杠。 */
|
|
61
|
+
export function normalizeWorkspacePath(p) {
|
|
62
|
+
return String(p).replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function markersDirOf(homeDir) {
|
|
66
|
+
return path.join(homeDir, 'trusted-workspaces')
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function markerPathOf(workspace, homeDir) {
|
|
70
|
+
const hash = crypto.createHash('sha256').update(normalizeWorkspacePath(workspace)).digest('hex')
|
|
71
|
+
return path.join(markersDirOf(homeDir), `${hash}.json`)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** 读 marker(读不出来就当没有,绝不抛)。 */
|
|
75
|
+
export function readTrustMarker(workspace, homeDir) {
|
|
76
|
+
try {
|
|
77
|
+
const parsed = JSON.parse(fs.readFileSync(markerPathOf(workspace, homeDir), 'utf8'))
|
|
78
|
+
if (parsed === null || typeof parsed !== 'object' || typeof parsed.path !== 'string') return null
|
|
79
|
+
return parsed
|
|
80
|
+
} catch {
|
|
81
|
+
return null
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function isTrusted(workspace, homeDir) {
|
|
86
|
+
if (!homeDir) return true // 没配 home 时 meow 自己也不启信任门(markersDir=null)
|
|
87
|
+
const marker = readTrustMarker(workspace, homeDir)
|
|
88
|
+
return marker !== null && typeof marker.trustedAt === 'number'
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function trustWorkspace(workspace, { homeDir, source = 'macro-memory-trust' } = {}) {
|
|
92
|
+
if (!homeDir) return false
|
|
93
|
+
const dir = markersDirOf(homeDir)
|
|
94
|
+
fs.mkdirSync(dir, { recursive: true })
|
|
95
|
+
const file = markerPathOf(workspace, homeDir)
|
|
96
|
+
const existing = readTrustMarker(workspace, homeDir)
|
|
97
|
+
if (existing !== null && typeof existing.trustedAt === 'number') return true
|
|
98
|
+
const body = { ...(existing ?? {}), path: workspace, trustedAt: Date.now(), trustedSource: source }
|
|
99
|
+
const tmp = `${file}.tmp`
|
|
100
|
+
fs.writeFileSync(tmp, JSON.stringify(body, null, 1), 'utf8')
|
|
101
|
+
fs.renameSync(tmp, file)
|
|
102
|
+
return true
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function untrustWorkspace(workspace, homeDir) {
|
|
106
|
+
try {
|
|
107
|
+
fs.rmSync(markerPathOf(workspace, homeDir), { force: true })
|
|
108
|
+
return true
|
|
109
|
+
} catch {
|
|
110
|
+
return false
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** 列出所有被信任的工作区(按信任时间倒序)。 */
|
|
115
|
+
export function listTrusted(homeDir) {
|
|
116
|
+
const dir = markersDirOf(homeDir)
|
|
117
|
+
let files = []
|
|
118
|
+
try {
|
|
119
|
+
files = fs.readdirSync(dir).filter((f) => f.endsWith('.json'))
|
|
120
|
+
} catch {
|
|
121
|
+
return []
|
|
122
|
+
}
|
|
123
|
+
const rows = []
|
|
124
|
+
for (const f of files) {
|
|
125
|
+
try {
|
|
126
|
+
const parsed = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8'))
|
|
127
|
+
if (typeof parsed?.path === 'string') {
|
|
128
|
+
rows.push({ path: parsed.path, trustedAt: Number(parsed.trustedAt ?? 0), source: parsed.trustedSource ?? '' })
|
|
129
|
+
}
|
|
130
|
+
} catch {
|
|
131
|
+
/* 坏文件跳过,不让一条烂账拖死列表 */
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return rows.sort((a, b) => b.trustedAt - a.trustedAt)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* 决定这个工作区能不能写,必要时按策略自动信任。
|
|
139
|
+
*
|
|
140
|
+
* @param {object} opts
|
|
141
|
+
* @param {string} opts.workspace 工作区绝对路径(工具 exec 里的 cwd)
|
|
142
|
+
* @param {string} opts.homeDir meow 的 activeHomeDir(markers 落点)
|
|
143
|
+
* @param {string} [opts.projectDir='.dsh-meow'] 工作区内的库目录名
|
|
144
|
+
* @param {'auto'|'always'|'never'} [opts.policy='auto']
|
|
145
|
+
* @returns {{trusted:boolean, created:boolean, reason:string, dir:string, leftovers?:string[]}}
|
|
146
|
+
*/
|
|
147
|
+
export function ensureTrust({ workspace, homeDir, projectDir = '.dsh-meow', policy = 'auto' }) {
|
|
148
|
+
const dir = path.join(workspace, projectDir)
|
|
149
|
+
if (isTrusted(workspace, homeDir)) {
|
|
150
|
+
return { trusted: true, created: false, reason: 'marker', dir, workspace }
|
|
151
|
+
}
|
|
152
|
+
if (policy === 'never') {
|
|
153
|
+
return { trusted: false, created: false, reason: 'policy-never', dir, workspace }
|
|
154
|
+
}
|
|
155
|
+
if (policy === 'always') {
|
|
156
|
+
trustWorkspace(workspace, { homeDir, source: 'macro-memory:always' })
|
|
157
|
+
return { trusted: true, created: false, reason: 'policy-always', dir, workspace }
|
|
158
|
+
}
|
|
159
|
+
// auto:库目录不存在,或存在但只有本插件的产物 → 视为「本机新建」
|
|
160
|
+
let leftovers = null
|
|
161
|
+
if (fs.existsSync(dir)) {
|
|
162
|
+
try {
|
|
163
|
+
leftovers = fs.readdirSync(dir).filter((n) => !isCreationArtifact(n))
|
|
164
|
+
} catch (err) {
|
|
165
|
+
return { trusted: false, created: false, reason: `unreadable:${err.message}`, dir, workspace }
|
|
166
|
+
}
|
|
167
|
+
if (leftovers.length > 0) {
|
|
168
|
+
return { trusted: false, created: false, reason: 'external', dir, workspace, leftovers }
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
trustWorkspace(workspace, { homeDir, source: 'macro-memory:created-empty' })
|
|
172
|
+
return { trusted: true, created: true, reason: 'created-empty', dir, workspace }
|
|
173
|
+
}
|