dsh-macro-memory 0.0.0-stage → 0.3.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 +457 -2
- package/cordis.patch.yml +6 -0
- package/lib/client.js +3623 -0
- package/lib/index.js +469 -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 +439 -0
- package/lib/macro/defs/dream.js +24 -0
- package/lib/macro/defs/link.js +257 -0
- package/lib/macro/defs/project.js +25 -0
- package/lib/macro/defs/read.js +145 -0
- package/lib/macro/defs/remember.js +213 -0
- package/lib/macro/defs/search.js +661 -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 +182 -0
- package/lib/macro/linkflow.js +391 -0
- package/lib/macro/links.js +448 -0
- package/lib/macro/neighbor.js +209 -0
- package/lib/macro/panel.js +96 -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/store.js +103 -0
- package/lib/macro/tokencost.js +90 -0
- package/lib/macro/tools.js +67 -0
- package/package.json +54 -4
- package/vendor/VENDOR.json +23 -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 +317 -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/graph.js +1663 -0
- package/vendor/dsh-memory-nebula/lib/host/graphcache.js +282 -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 +451 -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 +759 -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 +4159 -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 +3344 -0
- package/vendor/meow-memory/lib/client.js.map +7 -0
- package/vendor/meow-memory/lib/index.js +9567 -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 +98 -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 +98 -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 +98 -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
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 待补连线队列:$DSH_HOME/macro-memory/pending-links.jsonl
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要它:星图是「可重建索引」,新写入的条目要等一轮建图(引擎 12s 巡检)才变成节点。
|
|
5
|
+
* 写记忆时顺手连线的请求如果因为「节点还没入图」或「星图模块这次没接上」而失败,
|
|
6
|
+
* 直接丢掉等于用户白写;把请求落盘排队,之后每次读操作顺手补连,系统就能自愈——
|
|
7
|
+
* 不需要模型记得回来补,也不用等用户在 12 秒后重新说一遍。
|
|
8
|
+
*
|
|
9
|
+
* 三条铁律:
|
|
10
|
+
* 1. 队列坏了不影响记忆主功能(所有 IO 吞异常);
|
|
11
|
+
* 2. 任何一条连线最多重试到 TTL 到期,不制造无限增长的垃圾;
|
|
12
|
+
* 3. 只排队「用户明确要求过」的连线,绝不自己发明关系。
|
|
13
|
+
*/
|
|
14
|
+
import { mkdirSync, renameSync, writeFileSync } from 'node:fs'
|
|
15
|
+
import { macroHome, pendingPath, readJsonl, readJsonlDetail } from './store.js'
|
|
16
|
+
import { LINKED_MARK, MISSING_PAIR_MARK, SELF_PAIR_MARK, NOT_READY_MARK } from './contract.js'
|
|
17
|
+
|
|
18
|
+
export { pendingPath }
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* 待补队列的「理由」只有一份(0.2.33)。
|
|
22
|
+
*
|
|
23
|
+
* 面板按理由分组之后,一个状况两种写法就会多出一个组:同样是「连线失败」,
|
|
24
|
+
* 写记忆那条路以前记 `连线失败待重试`,`memory_link` 那条路记 `memory_link 失败待重试`——
|
|
25
|
+
* 用户看到「2 条连线失败 + 1 条 memory_link 失败」,会以为这是两件不同的事。
|
|
26
|
+
* 所以字面量只许在这里出现一次,其余地方一律用常量。
|
|
27
|
+
*/
|
|
28
|
+
export const PENDING_REASONS = {
|
|
29
|
+
/** 星图模块没接上(子插件未装配 / 被配置关闭) */
|
|
30
|
+
notReady: '星图未装配',
|
|
31
|
+
/** 记忆刚写完,星图那轮建图还没跑到它 */
|
|
32
|
+
notBuilt: '节点待入图',
|
|
33
|
+
/** 星图这次太慢,我们按期限掐断了 */
|
|
34
|
+
slow: '星图太慢待重试',
|
|
35
|
+
/** 连线本身失败(不是「太慢」也不是「没入图」) */
|
|
36
|
+
failed: '连线失败待重试',
|
|
37
|
+
/** 一次写太多 / 一批的总账用完,排到下一轮 */
|
|
38
|
+
deferred: '本次没轮到待补',
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 面板里理由的固定顺序:越靠前越「正常」,越靠后越「要人管」。 */
|
|
42
|
+
export const REASON_ORDER = [
|
|
43
|
+
PENDING_REASONS.deferred,
|
|
44
|
+
PENDING_REASONS.notBuilt,
|
|
45
|
+
PENDING_REASONS.slow,
|
|
46
|
+
PENDING_REASONS.failed,
|
|
47
|
+
PENDING_REASONS.notReady,
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
/** 理由归组:认识的按 `REASON_ORDER`,不认识的照原样单列(旧队列里可能留着老写法)。 */
|
|
51
|
+
export function reasonCounts(list) {
|
|
52
|
+
const seen = new Map()
|
|
53
|
+
for (const e of list) {
|
|
54
|
+
const key = typeof e.reason === 'string' && e.reason.length > 0 ? e.reason : ''
|
|
55
|
+
seen.set(key, (seen.get(key) ?? 0) + 1)
|
|
56
|
+
}
|
|
57
|
+
const known = REASON_ORDER.filter((r) => seen.has(r)).map((r) => ({ reason: r, count: seen.get(r) }))
|
|
58
|
+
const rest = [...seen.entries()]
|
|
59
|
+
.filter(([r]) => r !== '' && !REASON_ORDER.includes(r))
|
|
60
|
+
.map(([reason, count]) => ({ reason, count }))
|
|
61
|
+
const blank = seen.has('') ? [{ reason: '', count: seen.get('') }] : []
|
|
62
|
+
return [...known, ...rest, ...blank]
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** 队列上限:超出就丢最老的,防止坏掉的星图把磁盘撑满。 */
|
|
66
|
+
export const PENDING_MAX = 500
|
|
67
|
+
/** 一条待补连线的存活时间:过了就认为用户已经不在乎了。 */
|
|
68
|
+
export const PENDING_TTL_MS = 7 * 24 * 60 * 60 * 1000
|
|
69
|
+
/**
|
|
70
|
+
* 「星图说找不到这两条记忆」的宽限期(0.2.30)。
|
|
71
|
+
*
|
|
72
|
+
* 星图的这句 404 有两种含义,光看字分不出来:
|
|
73
|
+
* 1. 节点还没建进图——记忆刚写完,引擎 12s 巡检还没跑到它(`vendor/dsh-memory-nebula/lib/host/nebula.js:79`);
|
|
74
|
+
* 2. 记忆真的没了——被删、被合并、id 写错。
|
|
75
|
+
* 前者等一轮就好,后者重试一万次也一样。既然字面分不出来,就用**年龄**分:
|
|
76
|
+
* 排队不足 `MISSING_GRACE_MS` 的一律先留着(建图一轮 12s;200k 条库实测建一次 24.5 秒,
|
|
77
|
+
* 给 10 分钟是「再大的库也建完了」的量级),超过才摘。
|
|
78
|
+
*
|
|
79
|
+
* 旧行为(0.2.29 及之前)是把这句一律当永久失败摘掉:用户刚写完一条记忆、顺手连了邻居,
|
|
80
|
+
* 紧接着读一次记忆触发补连 → 星图还没建到节点 → 说「找不到」→ 队列清零。**用户的连线白写**,
|
|
81
|
+
* 而且没有任何报错。
|
|
82
|
+
*/
|
|
83
|
+
export const MISSING_GRACE_MS = 10 * 60 * 1000
|
|
84
|
+
|
|
85
|
+
function valid(entry) {
|
|
86
|
+
return (
|
|
87
|
+
entry &&
|
|
88
|
+
typeof entry === 'object' &&
|
|
89
|
+
typeof entry.a === 'string' &&
|
|
90
|
+
entry.a.length > 0 &&
|
|
91
|
+
typeof entry.b === 'string' &&
|
|
92
|
+
entry.b.length > 0
|
|
93
|
+
)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** 读全队列(坏行直接跳过;顺手清掉过期条目)。 */
|
|
97
|
+
export function readPending(now = Date.now()) {
|
|
98
|
+
const out = []
|
|
99
|
+
for (const entry of readJsonl(pendingPath())) {
|
|
100
|
+
if (!valid(entry)) continue
|
|
101
|
+
const ts = Number(entry.ts) || 0
|
|
102
|
+
if (ts > 0 && now - ts > PENDING_TTL_MS) continue
|
|
103
|
+
out.push({
|
|
104
|
+
a: entry.a,
|
|
105
|
+
b: entry.b,
|
|
106
|
+
note: typeof entry.note === 'string' ? entry.note : '',
|
|
107
|
+
ts: ts || now,
|
|
108
|
+
reason: typeof entry.reason === 'string' ? entry.reason : '',
|
|
109
|
+
})
|
|
110
|
+
}
|
|
111
|
+
return out
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// 0.2.55:队列写不进去原来也是无声的(约定:不打断记忆主功能)。后果比账本更糟——
|
|
115
|
+
// 这条连线被排队了、返回 true,其实一个字都没落盘,下次读记忆也不会补;
|
|
116
|
+
// 而面板照旧报「0 条,都连上了,没有欠账」。这里留一份最小的失败账,只够面板说实话
|
|
117
|
+
// (写成功就清零:旧账不该冒充现在的状态)。
|
|
118
|
+
const writeFail = { failures: 0, error: '' }
|
|
119
|
+
|
|
120
|
+
/** 整体重写队列(先写临时文件再改名,避免半截文件)。 */
|
|
121
|
+
function writePending(list) {
|
|
122
|
+
try {
|
|
123
|
+
mkdirSync(macroHome(), { recursive: true })
|
|
124
|
+
const file = pendingPath()
|
|
125
|
+
const tmp = `${file}.tmp`
|
|
126
|
+
const text = list.map((e) => JSON.stringify(e)).join('\n')
|
|
127
|
+
writeFileSync(tmp, text.length > 0 ? `${text}\n` : '', 'utf8')
|
|
128
|
+
renameSync(tmp, file)
|
|
129
|
+
writeFail.failures = 0
|
|
130
|
+
writeFail.error = ''
|
|
131
|
+
return true
|
|
132
|
+
} catch (err) {
|
|
133
|
+
writeFail.failures += 1
|
|
134
|
+
writeFail.error = String(err?.message ?? err)
|
|
135
|
+
return false
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** 排一条(同 a→b 已存在就不重复排,只刷新时间与理由)。 */
|
|
140
|
+
export function queuePending(a, b, note = '', reason = '') {
|
|
141
|
+
const anchor = String(a ?? '').trim()
|
|
142
|
+
const target = String(b ?? '').trim()
|
|
143
|
+
if (anchor.length === 0 || target.length === 0 || anchor === target) return false
|
|
144
|
+
const now = Date.now()
|
|
145
|
+
const list = readPending(now).filter((e) => !(e.a === anchor && e.b === target))
|
|
146
|
+
list.push({ a: anchor, b: target, note, ts: now, reason })
|
|
147
|
+
while (list.length > PENDING_MAX) list.shift()
|
|
148
|
+
return writePending(list)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** 连线成功后把这条从队列里摘掉(手工补连也算)。 */
|
|
152
|
+
export function dropPending(a, b) {
|
|
153
|
+
const anchor = String(a ?? '').trim()
|
|
154
|
+
const target = String(b ?? '').trim()
|
|
155
|
+
const list = readPending()
|
|
156
|
+
const kept = list.filter((e) => !(e.a === anchor && e.b === target))
|
|
157
|
+
if (kept.length === list.length) return false
|
|
158
|
+
return writePending(kept)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function pendingCount() {
|
|
162
|
+
return readPending().length
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* 预算哨兵:不是失败,只是「这一轮没来得及」,条目原样留在队列里下轮再补。
|
|
167
|
+
* 用一个独立 Symbol 而不是 `null`/`{timedOut:true}`,是为了让「超时」和「归不出 id」
|
|
168
|
+
* 在代码上根本不可能被混淆——前者要留,后者要摘。
|
|
169
|
+
*/
|
|
170
|
+
const TIMED_OUT = Symbol('macro-memory:budget-timeout')
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* 给一次 await 套上剩余预算。
|
|
174
|
+
*
|
|
175
|
+
* 为什么不能只靠 `tryCall` 的 timeoutMs:那个数只管「等子插件把工具注册出来」,
|
|
176
|
+
* 工具一旦已注册,`execute` 本身慢多久都照等(nebula_link 在建图争锁时能到几十秒)。
|
|
177
|
+
* 而读路径最怕这个——一次 `memory_search` 被补连带住,用户感觉是「记忆坏了」。
|
|
178
|
+
* 最小预算 `MIN_STEP_MS`:剩几毫秒时不再发请求,直接收工,省得白发一次。
|
|
179
|
+
*/
|
|
180
|
+
export const MIN_STEP_MS = 120
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* 前台一次写连线的上限(0.2.31)。
|
|
184
|
+
*
|
|
185
|
+
* 0.2.28 的预算只管后台补连(`flushLinks` 1.2s / `flushNow` 1.5s);前台
|
|
186
|
+
* `memory_link` / 写记忆时顺手连线是**用户在等**的那条路,却一直裸等 `execute`:
|
|
187
|
+
* 星图在建图争锁时能跑几十秒,工具调用就跟着挂几十秒,宿主那边看起来像卡死。
|
|
188
|
+
* 20 秒是「建图 24.5s 那条实测」与「人还能忍」之间的折中:超过它就先记账排队。
|
|
189
|
+
* 排队安全的前提是星图 `addLink` 用 `INSERT … ON CONFLICT(id) DO UPDATE`,重复连同一条边幂等。
|
|
190
|
+
*/
|
|
191
|
+
export const LINK_CALL_MS = 20 * 1000
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* 一次写入最多当场连几条(0.2.32)。
|
|
195
|
+
*
|
|
196
|
+
* 超过的部分**不许悄悄丢掉**:以前 `applyLinks` 里写的是 `items.slice(0, 12)`,
|
|
197
|
+
* 模型给了 15 条 links,后 3 条既没连、也没排队、文案里一个字都没提——
|
|
198
|
+
* 用户的意图就这么消失了,而且看起来一切正常。现在超出的部分一律进队列(读记忆时自动补),
|
|
199
|
+
* 文案里要说清「另有 N 条排着」。
|
|
200
|
+
*/
|
|
201
|
+
export const LINKS_PER_WRITE = 12
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* 一批前台连线的总时长上限(0.2.32)。
|
|
205
|
+
*
|
|
206
|
+
* `LINK_CALL_MS` 只管**单条**。12 条各挂 20 秒,一次写记忆能卡 4 分钟——
|
|
207
|
+
* 用户在等的那条路还是能挂死,只是挂了四次。所以一批也要有总账:到点就把剩下的排队走人。
|
|
208
|
+
*/
|
|
209
|
+
export const LINK_BATCH_MS = 30 * 1000
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* 掐断的那次调用是不是「预算到点」,而不是真的拿到了结果。
|
|
213
|
+
* 哨兵不外泄(Symbol 留在本模块),调用方只能通过这个谓词问,避免各写一份 `===`。
|
|
214
|
+
*/
|
|
215
|
+
export function isTimedOut(x) {
|
|
216
|
+
return x === TIMED_OUT
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* 把毫秒说成人话:「20 秒」而不是「20000 毫秒」,「200 毫秒」而不是「0 秒」。
|
|
221
|
+
* 超时文案里这个数必须真,否则用户按它去判断「要不要再等等」时会看错。
|
|
222
|
+
*/
|
|
223
|
+
export function describeMs(ms) {
|
|
224
|
+
const n = Math.max(0, Math.round(Number(ms) || 0))
|
|
225
|
+
if (n >= 1000) {
|
|
226
|
+
const sec = n / 1000
|
|
227
|
+
return `${Number.isInteger(sec) ? sec : Math.round(sec)} 秒`
|
|
228
|
+
}
|
|
229
|
+
return `${n} 毫秒`
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export function withBudget(promise, ms) {
|
|
233
|
+
if (!(ms >= MIN_STEP_MS)) return Promise.resolve(TIMED_OUT)
|
|
234
|
+
let timer
|
|
235
|
+
const guard = new Promise((resolve) => {
|
|
236
|
+
timer = setTimeout(() => resolve(TIMED_OUT), ms)
|
|
237
|
+
// 不让这个计时器把进程(或一次读)多留一秒
|
|
238
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
239
|
+
})
|
|
240
|
+
const work = Promise.resolve(promise).catch(() => ({ entry: undefined, text: '' }))
|
|
241
|
+
return Promise.race([work, guard]).finally(() => clearTimeout(timer))
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* 补连一轮。判据由调用方给(`tryCall` 与 `isLinked`),这里只管顺序与预算:
|
|
246
|
+
* - 星图整体不可用时立刻停手,别把队列当靶子打(每次调用只探一次);
|
|
247
|
+
* - 单条失败只是留在队列里,不影响别的条目;
|
|
248
|
+
* - `budgetMs` 是**真的**:每一次 await(含短 id 归一那两次 memory_read)都按剩余预算掐断,
|
|
249
|
+
* 掐断即停手、条目留着。宁可不补,也不能把一次读操作拖成几十秒。
|
|
250
|
+
*
|
|
251
|
+
* [macro-fusion 0.2.54] `resolve` 现在可以回一个带 kind 的结构(`resolveIdDetail`),
|
|
252
|
+
* 也能回老的 `完整 id / null`。三种「归不出来」必须分开处理:
|
|
253
|
+
* - `ambiguous`(短 id 撞车,记忆明明在,只是前缀不够)→ **留着**,摘掉等于永远不补;
|
|
254
|
+
* - `unavailable`(memory_read 没接上,连有没有都不知道)→ **留着**;
|
|
255
|
+
* - `missing`(这个工作区真没有 / 已被合并)→ 才摘。
|
|
256
|
+
* 原来一律 `resolve(...) === null` 就摘,并报「清掉 N 条永远连不上的(记忆已合并/删除)」——
|
|
257
|
+
* 一次 meow 超时就能把用户辛苦写的连线整批清掉,而且理由说的是另一回事。
|
|
258
|
+
*/
|
|
259
|
+
export async function flushPending({ tryCall, isLinked, resolve, budgetMs = 1200, limit = 8, exec } = {}) {
|
|
260
|
+
const started = Date.now()
|
|
261
|
+
const remaining = () => budgetMs - (Date.now() - started)
|
|
262
|
+
const norm = (x) => (x && typeof x === 'object' && typeof x.kind === 'string' ? x : { kind: x === null ? 'missing' : 'ok', id: x })
|
|
263
|
+
const list = readPending()
|
|
264
|
+
if (list.length === 0)
|
|
265
|
+
return { tried: 0, linked: 0, dropped: 0, ambiguous: 0, unavailable: 0, left: 0, stopped: 'empty', budgetMs, limit }
|
|
266
|
+
|
|
267
|
+
const done = []
|
|
268
|
+
let linked = 0
|
|
269
|
+
let dropped = 0
|
|
270
|
+
let ambiguous = 0
|
|
271
|
+
let unavailable = 0
|
|
272
|
+
let tried = 0
|
|
273
|
+
let stopped = ''
|
|
274
|
+
for (const entry of list.slice(0, limit)) {
|
|
275
|
+
if (remaining() < MIN_STEP_MS) {
|
|
276
|
+
stopped = 'budget'
|
|
277
|
+
break
|
|
278
|
+
}
|
|
279
|
+
tried += 1
|
|
280
|
+
let a = entry.a
|
|
281
|
+
let b = entry.b
|
|
282
|
+
if (typeof resolve === 'function') {
|
|
283
|
+
const rawA = await withBudget(resolve(entry.a, exec), remaining())
|
|
284
|
+
const rawB = rawA === TIMED_OUT ? TIMED_OUT : await withBudget(resolve(entry.b, exec), remaining())
|
|
285
|
+
if (rawA === TIMED_OUT || rawB === TIMED_OUT) {
|
|
286
|
+
stopped = 'budget'
|
|
287
|
+
tried -= 1
|
|
288
|
+
break
|
|
289
|
+
}
|
|
290
|
+
const da = norm(rawA)
|
|
291
|
+
const db = norm(rawB)
|
|
292
|
+
if (da.kind === 'ambiguous' || db.kind === 'ambiguous') {
|
|
293
|
+
// 记忆在,只是 id 给短了:留着等下一次(或用户把 id 补全),绝不摘
|
|
294
|
+
ambiguous += 1
|
|
295
|
+
continue
|
|
296
|
+
}
|
|
297
|
+
if (da.kind === 'unavailable' || db.kind === 'unavailable') {
|
|
298
|
+
// 这次没查成 ≠ 这条不存在:留着,下一轮再试
|
|
299
|
+
unavailable += 1
|
|
300
|
+
continue
|
|
301
|
+
}
|
|
302
|
+
if (da.kind !== 'ok' || db.kind !== 'ok') {
|
|
303
|
+
dropped += 1
|
|
304
|
+
done.push(entry)
|
|
305
|
+
continue
|
|
306
|
+
}
|
|
307
|
+
a = da.id
|
|
308
|
+
b = db.id
|
|
309
|
+
}
|
|
310
|
+
const r = await withBudget(tryCall('nebula_link', { action: 'link', a, b, note: entry.note }, exec, '星图连线'), remaining())
|
|
311
|
+
if (r === TIMED_OUT) {
|
|
312
|
+
stopped = 'budget'
|
|
313
|
+
// 这条根本没动过手,别算进 tried(0.2.28 的语义:tried = 真的动过几条)
|
|
314
|
+
tried -= 1
|
|
315
|
+
break
|
|
316
|
+
}
|
|
317
|
+
// 判据顺序不能反(0.2.30):成功 → 真永久 → 「找不到」(要按年龄分)→ 桥没接上。
|
|
318
|
+
// 旧顺序把「找不到」并进「永久失败」,把「刚写完、节点还没建进图」也摘掉了。
|
|
319
|
+
if (isLinked(r.text)) {
|
|
320
|
+
linked += 1
|
|
321
|
+
done.push(entry)
|
|
322
|
+
continue
|
|
323
|
+
}
|
|
324
|
+
if (isSelfPairText(r.text)) {
|
|
325
|
+
// 自己连自己:换多少时间都一样,当场摘
|
|
326
|
+
dropped += 1
|
|
327
|
+
done.push(entry)
|
|
328
|
+
continue
|
|
329
|
+
}
|
|
330
|
+
if (saysMissingNodes(r.text)) {
|
|
331
|
+
// 可能是「还没建进图」,也可能是「真的没了」——只按年龄区分
|
|
332
|
+
if (Date.now() - entry.ts >= MISSING_GRACE_MS) {
|
|
333
|
+
dropped += 1
|
|
334
|
+
done.push(entry)
|
|
335
|
+
}
|
|
336
|
+
continue
|
|
337
|
+
}
|
|
338
|
+
if (r.entry === undefined) {
|
|
339
|
+
// 工具本身上下线了(桥没拿到)/ 调用炸了:这一轮别再打它
|
|
340
|
+
stopped = 'unavailable'
|
|
341
|
+
break
|
|
342
|
+
}
|
|
343
|
+
// 其余(节点还没入图、引擎说稍后再试)留着,等下一轮。
|
|
344
|
+
}
|
|
345
|
+
if (done.length > 0) {
|
|
346
|
+
const drop = new Set(done.map((e) => `${e.a}\u0000${e.b}`))
|
|
347
|
+
writePending(readPending().filter((e) => !drop.has(`${e.a}\u0000${e.b}`)))
|
|
348
|
+
}
|
|
349
|
+
// tried = 真的动过几条(被预算掐断的那条不算动过);旧写法报 min(len,limit) 会把「没来得及试」也算成试过
|
|
350
|
+
// budgetMs / limit 一起交出去(0.2.36):面板要能说出「这一轮最多补多久、几条」,
|
|
351
|
+
// 否则被掐断时用户只看到「还剩 N 条」,不知道这个 N 是被 1.5 秒掐的,还是被 20 条掐的。
|
|
352
|
+
return { tried, linked, dropped, ambiguous, unavailable, left: readPending().length, stopped, budgetMs, limit }
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** 面板用:队列概况(不触发补连,纯读)。 */
|
|
356
|
+
export function pendingReport(limit = 20) {
|
|
357
|
+
const detail = readJsonlDetail(pendingPath())
|
|
358
|
+
const list = readPending()
|
|
359
|
+
if (list.length === 0) {
|
|
360
|
+
const p = pendingPath()
|
|
361
|
+
// 0.2.55:「0 条」有四种来路,一种都不是「星图那边都连上了」
|
|
362
|
+
if (writeFail.failures > 0) {
|
|
363
|
+
return (
|
|
364
|
+
`待补连线:一条都没存下来——最近 ${writeFail.failures} 次写队列都失败了(${writeFail.error})。\n` +
|
|
365
|
+
`这不是「没有欠账」:该排队的连线确实发生过,只是没落到盘上,读记忆时也补不了。队列:${p}`
|
|
366
|
+
)
|
|
367
|
+
}
|
|
368
|
+
if (detail.unreadable) {
|
|
369
|
+
return `待补连线:队列在,但这次读不出来(${detail.error})——不是「都连上了、没有欠账」。队列:${p}`
|
|
370
|
+
}
|
|
371
|
+
if (detail.badLines > 0) {
|
|
372
|
+
return `待补连线:队列里有 ${detail.lines} 行,但一行都解析不出来(${detail.badLines} 行坏行)——不是没有欠账,是这份队列坏了。队列:${p}`
|
|
373
|
+
}
|
|
374
|
+
if (detail.entries.length > 0) {
|
|
375
|
+
// 解析出来了却一条都用不上:要么过期了,要么缺 a/b。两种可能都摆出来,不替人挑。
|
|
376
|
+
return `待补连线:队列里有 ${detail.entries.length} 条记录,但这次一条都用不上(要么过期了,要么缺 a/b)。队列:${p}`
|
|
377
|
+
}
|
|
378
|
+
return '待补连线:0 条(星图那边都连上了,没有欠账)。'
|
|
379
|
+
}
|
|
380
|
+
// 0.2.61:limit=0 照办 0,但要说清队列里其实有多少条(不然正文看着像「没有欠账」)
|
|
381
|
+
const cap = Number(limit)
|
|
382
|
+
if (Number.isFinite(cap) && cap <= 0) {
|
|
383
|
+
return `按你给的 limit=${cap} 这次一条都不列(队列里其实有 ${list.length} 条,不是没有欠账)。队列:${pendingPath()}`
|
|
384
|
+
}
|
|
385
|
+
const lines = list.slice(0, cap).map((e, i) => {
|
|
386
|
+
// 本地时间(sv-SE 恰好是 "YYYY-MM-DD HH:mm"),别让面板显示成 UTC 让人误判「过期」
|
|
387
|
+
const when = new Date(e.ts).toLocaleString('sv-SE', { hour12: false }).slice(0, 16)
|
|
388
|
+
const why = e.reason ? `(${e.reason})` : ''
|
|
389
|
+
return `${i + 1}. ${e.a} ↔ ${e.b} ${when}${why}`
|
|
390
|
+
})
|
|
391
|
+
const more = list.length > cap ? `\n… 还有 ${list.length - cap} 条` : ''
|
|
392
|
+
// 先给一句「按理由」的账(0.2.33):一串逐条明细看不出「是星图慢,还是我们没轮到」,
|
|
393
|
+
// 也看不出「这 6 条其实是一件事」。不认识的旧理由照原样列出,不吞。
|
|
394
|
+
const groups = reasonCounts(list)
|
|
395
|
+
.map((g) => `${g.reason === '' ? '未记理由' : g.reason} ${g.count}`)
|
|
396
|
+
.join(' · ')
|
|
397
|
+
return `待补连线:${list.length} 条(读记忆时会自动补,过期 ${Math.round(PENDING_TTL_MS / 86400000)} 天丢弃)\n按理由:${groups}\n${lines.join('\n')}${more}`
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* 星图**连线成功**的文案(原文见 `vendor/dsh-memory-nebula/lib/index.js` 的 `已固化连线`)。
|
|
402
|
+
*
|
|
403
|
+
* 它和下面几个一样是「跨插件的文字契约」:那边是另一个仓库、另一套版本节奏,
|
|
404
|
+
* 我们只能认字。所以字面量统一放在 `contract.js` 里各写一遍,
|
|
405
|
+
* 再由 verify 拿它们去对 vendor 源码——对面哪天改词,断言先红。
|
|
406
|
+
*/
|
|
407
|
+
export { LINKED_MARK, MISSING_PAIR_MARK, SELF_PAIR_MARK, NOT_READY_MARK } from './contract.js'
|
|
408
|
+
|
|
409
|
+
/** 是否真的连上了(nebula_link 的成功文案)。 */
|
|
410
|
+
export function isLinkedText(text) {
|
|
411
|
+
return typeof text === 'string' && text.includes(LINKED_MARK)
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* 重试也不会变的失败:星图说「不能和自己配对」
|
|
416
|
+
* (原文见 `vendor/dsh-memory-nebula/lib/host/nebula.js:90` 的 `new Error(...)`)。
|
|
417
|
+
*
|
|
418
|
+
* 注意「找不到这两条记忆」**不在**这里(0.2.30):那句话有两种含义——节点还没建进图(等一轮就好)
|
|
419
|
+
* 与记忆真的没了(重试无用)。混进来的后果是刚写完的连线被当场摘掉,见 `MISSING_GRACE_MS`。
|
|
420
|
+
*/
|
|
421
|
+
export function isSelfPairText(text) {
|
|
422
|
+
return String(text ?? '').includes(SELF_PAIR_MARK)
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* 星图说「找不到这两条记忆」(`vendor/dsh-memory-nebula/lib/host/nebula.js:79`)。
|
|
427
|
+
*
|
|
428
|
+
* 这句**不代表永久失败**:记忆刚写完时节点还没建进图,星图同样这么回。
|
|
429
|
+
* 调用方必须自己决定「留还是摘」,判据是年龄(`MISSING_GRACE_MS`)或结构(再 inspect 一次)。
|
|
430
|
+
*/
|
|
431
|
+
export function saysMissingNodes(text) {
|
|
432
|
+
return String(text ?? '').includes(MISSING_PAIR_MARK)
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* 星图**没接上**(没装配 / 被配置关掉 / 引擎还没起),而不是「星图说这一步不行」。
|
|
437
|
+
*
|
|
438
|
+
* 判据是 bridge 在工具未注册时抛的那句(`lib/macro/bridge.js` 的 `call()`)。分出来的用途:
|
|
439
|
+
* 这两种失败的**措辞**不一样——没接上属于环境问题,说「星图这次没接上」就够了;说不行属于内容问题,
|
|
440
|
+
* 得把星图的原话转告。混在一起写的后果是成功路径上漏出内部错误(0.2.12 修的就是这个)。
|
|
441
|
+
* 那句文案本身在 `contract.js` 起名(`NOT_READY_MARK`),bridge 抛、这里认,两边同一个字。
|
|
442
|
+
*/
|
|
443
|
+
|
|
444
|
+
/** 这条失败文案是不是「星图没接上」。 */
|
|
445
|
+
export function isNotReady(text) {
|
|
446
|
+
return String(text ?? '').includes(NOT_READY_MARK)
|
|
447
|
+
}
|
|
448
|
+
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
// [macro-fusion 0.2.145] 每轮星图邻域注入。
|
|
2
|
+
//
|
|
3
|
+
// 为什么要有这一层:0.2.18 起「每轮自动注入」被整段删掉,改成全靠模型自己调 memory_search。
|
|
4
|
+
// 省了 token,也把记忆系统降级成「模型想起来才查」——主人 2026-11-21 的话:「邻域注入我认为
|
|
5
|
+
// 还是有必要的」。旋钮可以省,功能不能省:这一层把「这一轮的话在星图里连着谁」自动带进来。
|
|
6
|
+
//
|
|
7
|
+
// 三条硬约束(每条都对应一次踩坑或一条既定原则):
|
|
8
|
+
// 1. **变化的内容不许进 system prompt 前缀**(0.2.18 的教训 / prompt 缓存)。
|
|
9
|
+
// 所以走 `agent/pre-step` 把一段**追加到最后一条用户消息后面**,前缀一个字节都不动。
|
|
10
|
+
// 2. **每轮都要跑的路径必须便宜**:只查星图、不查全库、不调模型;有上限(条数 + 字符),
|
|
11
|
+
// 没有邻居就一个字都不注入。宁可这一轮空着,也不许为了「显得有记忆」硬凑。
|
|
12
|
+
// 3. **注入的东西必须自己说明来路**:模型会把注入当成用户说的话。标题里写明「自动带来的、
|
|
13
|
+
// 不是用户说的」,并给出读全文的办法,否则它会把摘要当成原文引用。
|
|
14
|
+
import { graphNodesOf, uidOf } from './fusion.js'
|
|
15
|
+
|
|
16
|
+
/** 一次最多带几条邻居。 */
|
|
17
|
+
export const NEIGHBOR_DEFAULT_MAX = 4
|
|
18
|
+
/** 整块最多多少字符(含标题与收尾)。 */
|
|
19
|
+
export const NEIGHBOR_DEFAULT_CHARS = 420
|
|
20
|
+
/** 用户这一轮的话短于这么多字符就不猜(「好」「继续」「嗯」不构成检索意图)。 */
|
|
21
|
+
export const NEIGHBOR_MIN_QUERY = 6
|
|
22
|
+
/** 一个会话最多记多少条「已经带过」,防止长会话把集合撑大。 */
|
|
23
|
+
export const NEIGHBOR_SEEN_MAX = 200
|
|
24
|
+
/** 星图那一侧的工具名(走 bridge,不直接碰 vendor)。 */
|
|
25
|
+
export const NEIGHBOR_TOOL = 'nebula_recall'
|
|
26
|
+
/** 注入消息的来源标记:宿主按它折叠成一行「上下文」,也让它与用户消息区分开。 */
|
|
27
|
+
export const NEIGHBOR_SOURCE_KIND = 'macro-memory:neighbor'
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 取这一轮「用户自己说的话」:最后一条 `source.kind === 'user'` 的文本块。
|
|
31
|
+
* 注入消息、工具结果、别的插件的通知都不算——否则会拿自己上一轮的注入去检索。
|
|
32
|
+
* @param {readonly {source?: {kind?: string}, content?: readonly {type: string, text?: string}[]}[]} messages
|
|
33
|
+
* @returns {string} 去掉首尾空白的文本;没有就空串。
|
|
34
|
+
*/
|
|
35
|
+
export function neighborQueryOf(messages) {
|
|
36
|
+
const list = Array.isArray(messages) ? messages : []
|
|
37
|
+
for (let i = list.length - 1; i >= 0; i -= 1) {
|
|
38
|
+
const m = list[i]
|
|
39
|
+
if (m === null || typeof m !== 'object') continue
|
|
40
|
+
if (m.source?.kind !== 'user') continue
|
|
41
|
+
const blocks = Array.isArray(m.content) ? m.content : []
|
|
42
|
+
const text = blocks
|
|
43
|
+
.filter((b) => b !== null && typeof b === 'object' && b.type === 'text' && typeof b.text === 'string')
|
|
44
|
+
.map((b) => b.text)
|
|
45
|
+
.join(' ')
|
|
46
|
+
.trim()
|
|
47
|
+
return text
|
|
48
|
+
}
|
|
49
|
+
return ''
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** 标签里不许出现换行:一行一条,读者才能一眼数清带了几条。 */
|
|
53
|
+
function oneLine(text, max = 60) {
|
|
54
|
+
const flat = String(text ?? '').replace(/\s+/g, ' ').trim()
|
|
55
|
+
return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 把星图回执渲染成注入块。纯函数:探针直接喂文本就能验文案与上限。
|
|
60
|
+
*
|
|
61
|
+
* 形如:
|
|
62
|
+
* 【星图邻域 · 自动带来的】这一轮的话在星图里连着下面几条(不是用户说的原文):
|
|
63
|
+
* - [fact] [0mwq3aa9] 0.2.144 的交付态…(强度 0.82)
|
|
64
|
+
* 要全文用 memory_read(id)。
|
|
65
|
+
*
|
|
66
|
+
* @param {string} recallText 星图工具(nebula_recall)的回执原文。
|
|
67
|
+
* @param {{max?: number, chars?: number, skip?: Iterable<string>}} [opts]
|
|
68
|
+
* `skip` 是这个会话已经带过的 id(裸 id 或带工作区前缀都认)。
|
|
69
|
+
* @returns {{text: string, ids: string[]} | null} 一条都没有时返回 null。
|
|
70
|
+
*/
|
|
71
|
+
export function neighborBlockOf(recallText, opts = {}) {
|
|
72
|
+
const max = Number.isFinite(opts.max) ? Math.max(0, Math.trunc(opts.max)) : NEIGHBOR_DEFAULT_MAX
|
|
73
|
+
const chars = Number.isFinite(opts.chars) ? Math.max(80, Math.trunc(opts.chars)) : NEIGHBOR_DEFAULT_CHARS
|
|
74
|
+
if (max === 0) return null
|
|
75
|
+
const skip = new Set()
|
|
76
|
+
for (const one of opts.skip ?? []) skip.add(String(one))
|
|
77
|
+
const nodes = graphNodesOf(recallText)
|
|
78
|
+
if (nodes.length === 0) return null
|
|
79
|
+
const head = '【星图邻域 · 自动带来的】这一轮的话在星图里连着下面几条(不是用户说的原文):'
|
|
80
|
+
const lines = [head]
|
|
81
|
+
const ids = []
|
|
82
|
+
for (const node of nodes) {
|
|
83
|
+
if (ids.length >= max) break
|
|
84
|
+
const bare = uidOf(node.id)
|
|
85
|
+
if (skip.has(bare) || skip.has(node.id)) continue
|
|
86
|
+
const label = oneLine(node.label, 48)
|
|
87
|
+
const why = oneLine(node.why, 40)
|
|
88
|
+
const score = Number.isFinite(node.score) && node.score > 0 ? `(强度 ${node.score.toFixed(2)})` : ''
|
|
89
|
+
const line = `- [${node.level}] [${bare.slice(0, 8)}] ${label}${score}${why === '' ? '' : ` · ${why}`}`
|
|
90
|
+
if (lines.join('\n').length + line.length + 1 > chars) break
|
|
91
|
+
lines.push(line)
|
|
92
|
+
ids.push(bare)
|
|
93
|
+
}
|
|
94
|
+
if (ids.length === 0) return null
|
|
95
|
+
const tail = `要全文用 memory_read("${ids[0].slice(0, 8)}"),别把上面的摘要当原文引用。`
|
|
96
|
+
if (lines.join('\n').length + tail.length + 1 > chars) return { text: lines.join('\n'), ids }
|
|
97
|
+
lines.push(tail)
|
|
98
|
+
return { text: lines.join('\n'), ids }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* 每轮邻域注入器。
|
|
103
|
+
*
|
|
104
|
+
* @param {object} o
|
|
105
|
+
* @param {any} o.ctx 插件上下文(只用 `ctx.on`)。
|
|
106
|
+
* @param {{tryCall: Function}} o.bridge 融合层的桥:`tryCall(name, args, exec, label)`。
|
|
107
|
+
* @param {{neighborInject?: boolean, neighborMax?: number, neighborChars?: number}} o.config 融合层配置。
|
|
108
|
+
* @param {(msg: string) => void} [o.logger] debug 日志。
|
|
109
|
+
* @param {() => Promise<{createUserMessage: Function}>} [o.loadLlm] 取宿主的消息工厂(探针可注入假货)。
|
|
110
|
+
*/
|
|
111
|
+
export function createNeighborInjector({ ctx, bridge, config = {}, logger, loadLlm }) {
|
|
112
|
+
const seen = new Map()
|
|
113
|
+
const state = { injected: 0, skipped: 0, calls: 0, failed: 0 }
|
|
114
|
+
const enabled = config.neighborInject !== false
|
|
115
|
+
const max = Number.isFinite(config.neighborMax) ? config.neighborMax : NEIGHBOR_DEFAULT_MAX
|
|
116
|
+
const chars = Number.isFinite(config.neighborChars) ? config.neighborChars : NEIGHBOR_DEFAULT_CHARS
|
|
117
|
+
let llm = null
|
|
118
|
+
let llmTried = false
|
|
119
|
+
|
|
120
|
+
const load = async () => {
|
|
121
|
+
if (llm !== null) return llm
|
|
122
|
+
if (llmTried) return null
|
|
123
|
+
llmTried = true
|
|
124
|
+
try {
|
|
125
|
+
const mod = typeof loadLlm === 'function' ? await loadLlm() : await import('@deepseek-ai/dsh-llm')
|
|
126
|
+
if (typeof mod?.createUserMessage === 'function') llm = mod.createUserMessage
|
|
127
|
+
} catch (err) {
|
|
128
|
+
logger?.(`[macro-memory] 邻域注入取不到消息工厂,本轮不注入:${err instanceof Error ? err.message : String(err)}`)
|
|
129
|
+
}
|
|
130
|
+
return llm
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const seenOf = (sid) => {
|
|
134
|
+
let set = seen.get(sid)
|
|
135
|
+
if (set === undefined) {
|
|
136
|
+
set = new Set()
|
|
137
|
+
seen.set(sid, set)
|
|
138
|
+
}
|
|
139
|
+
return set
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* 决策函数:吃 pre-step 的 payload 与已定下的 decision,返回新的 decision。
|
|
144
|
+
* 任何一步不满足就原样返回——注入失败绝不挡住这一轮。
|
|
145
|
+
*/
|
|
146
|
+
const decide = async (payload, decision) => {
|
|
147
|
+
if (!enabled) return decision
|
|
148
|
+
if (decision === undefined || decision === null || decision.kind !== 'enter') return decision
|
|
149
|
+
const messages = Array.isArray(decision.messages) ? decision.messages : []
|
|
150
|
+
if (messages.length === 0) return decision
|
|
151
|
+
const agent = payload?.agent
|
|
152
|
+
if (agent?.session?.header?.origin === 'subagent') return decision
|
|
153
|
+
const query = neighborQueryOf(messages)
|
|
154
|
+
if (query.length < NEIGHBOR_MIN_QUERY) return decision
|
|
155
|
+
const sid = String(agent?.session?.id ?? payload?.sessionId ?? 'unknown')
|
|
156
|
+
const already = seenOf(sid)
|
|
157
|
+
state.calls += 1
|
|
158
|
+
let recallText = ''
|
|
159
|
+
try {
|
|
160
|
+
const r = await bridge.tryCall(NEIGHBOR_TOOL, { query: query.slice(0, 300), limit: max + 2, hops: 1 }, undefined, '星图邻域')
|
|
161
|
+
recallText = typeof r?.text === 'string' ? r.text : ''
|
|
162
|
+
} catch (err) {
|
|
163
|
+
state.failed += 1
|
|
164
|
+
logger?.(`[macro-memory] 邻域注入这一轮没查成:${err instanceof Error ? err.message : String(err)}`)
|
|
165
|
+
return decision
|
|
166
|
+
}
|
|
167
|
+
const block = neighborBlockOf(recallText, { max, chars, skip: already })
|
|
168
|
+
if (block === null) {
|
|
169
|
+
state.skipped += 1
|
|
170
|
+
return decision
|
|
171
|
+
}
|
|
172
|
+
const make = await load()
|
|
173
|
+
if (make === null) {
|
|
174
|
+
state.failed += 1
|
|
175
|
+
return decision
|
|
176
|
+
}
|
|
177
|
+
for (const id of block.ids) {
|
|
178
|
+
already.add(id)
|
|
179
|
+
if (already.size > NEIGHBOR_SEEN_MAX) {
|
|
180
|
+
const first = already.values().next()
|
|
181
|
+
if (!first.done) already.delete(first.value)
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
state.injected += 1
|
|
185
|
+
const msg = make({
|
|
186
|
+
content: [{ type: 'text', text: block.text }],
|
|
187
|
+
source: { kind: NEIGHBOR_SOURCE_KIND, form: 'notice', summary: `星图邻域 ${block.ids.length} 条` },
|
|
188
|
+
})
|
|
189
|
+
// 追加在**后面**:前缀不动,缓存不碎;模型看到的顺序是「用户说 → 附带邻域」。
|
|
190
|
+
return { ...decision, messages: [...messages, msg] }
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const dispose = ctx.on('agent/pre-step', async (payload, next) => {
|
|
194
|
+
const decision = await next()
|
|
195
|
+
try {
|
|
196
|
+
return await decide(payload, decision)
|
|
197
|
+
} catch (err) {
|
|
198
|
+
state.failed += 1
|
|
199
|
+
logger?.(`[macro-memory] 邻域注入出错(不影响这一轮):${err instanceof Error ? err.message : String(err)}`)
|
|
200
|
+
return decision
|
|
201
|
+
}
|
|
202
|
+
})
|
|
203
|
+
|
|
204
|
+
return {
|
|
205
|
+
decide,
|
|
206
|
+
stats: () => ({ ...state, sessions: seen.size }),
|
|
207
|
+
dispose: typeof dispose === 'function' ? dispose : () => {},
|
|
208
|
+
}
|
|
209
|
+
}
|