@tangjs/dsh-memory 0.0.0-stage → 1.0.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/CHANGELOG.md +154 -0
- package/LICENSE +201 -0
- package/README.en.md +268 -0
- package/README.md +268 -2
- package/client/client.js +1607 -0
- package/cordis.patch.yml +7 -0
- package/docs/ACCEPTANCE.md +341 -0
- package/docs/DESIGN.md +87 -0
- package/docs/DETAIL.md +48 -0
- package/docs/SPIKE.md +20 -0
- package/docs/diagrams/memory-flow.html +1227 -0
- package/icon.svg +8 -0
- package/index.js +582 -0
- package/locale/en.json +50 -0
- package/locale/zh.json +50 -0
- package/package.json +77 -4
- package/screenshots/global-space.png +0 -0
- package/screenshots/guide.png +0 -0
- package/screenshots/memory-detail.png +0 -0
- package/screenshots/memory-flow.png +0 -0
- package/screenshots/memory-page.png +0 -0
- package/src/host/api.mjs +234 -0
- package/src/host/autoDream.mjs +946 -0
- package/src/host/config.mjs +131 -0
- package/src/host/digest.mjs +121 -0
- package/src/host/dream.mjs +385 -0
- package/src/host/dreamAgent.mjs +619 -0
- package/src/host/extract.mjs +813 -0
- package/src/host/memoryIndex.mjs +137 -0
- package/src/host/prompt.mjs +65 -0
- package/src/host/recall.mjs +456 -0
- package/src/host/score.mjs +76 -0
- package/src/host/store.mjs +498 -0
- package/src/host/tool.mjs +144 -0
|
@@ -0,0 +1,619 @@
|
|
|
1
|
+
// Dream agent —— 带工具的记忆整理通道。
|
|
2
|
+
//
|
|
3
|
+
// 与 autoDream 的单次 LLM 调用不同,这里把整理交给一个**真正有工具的
|
|
4
|
+
// 子 agent**:它可以读记忆文件、读代码库、跑只读 git 命令,用现实证据
|
|
5
|
+
// 判断哪条笔记已经过时或写错了,然后只返回一份 JSON 计划;改动由本插件
|
|
6
|
+
// 通过 store 落地。
|
|
7
|
+
//
|
|
8
|
+
// 为什么不是子 agent 直接写:
|
|
9
|
+
// - DSH 的子 agent 无法按调用传入工具白名单(toolFilter 只用于历史冷恢复),
|
|
10
|
+
// fork/spawn 的默认组合都会继承父会话的完整工具集;
|
|
11
|
+
// - 因此本模块把"写"这道口子收回插件侧:子 agent 只产出计划,落地前有
|
|
12
|
+
// 白名单、截断保护、删除上限和缩水保护,落地之外再用快照守卫把子 agent
|
|
13
|
+
// 的越权写入回滚掉。
|
|
14
|
+
//
|
|
15
|
+
// 契约(index.js 只负责装配):
|
|
16
|
+
// createDreamAgentRunner({ store, config, log, getSubagents, getParent, now })
|
|
17
|
+
// -> { respond({ session, spaceKey, spaceLabel, memoryDir, notes, maxOps, signal })
|
|
18
|
+
// Promise<{ merges, deletes, conflicts, evidence } | { error }> }
|
|
19
|
+
// buildDreamAgentPrompt({...}) -> string
|
|
20
|
+
// parseDreamAgentReply(raw) -> { merges, deletes, conflicts, evidence } | { error }
|
|
21
|
+
// validateDreamAgentPlan({ plan, prompted, truncated, sizes, maxOps, maxDeletes })
|
|
22
|
+
// -> { merges, deletes, conflicts, rejected }
|
|
23
|
+
// snapshotSpace(dir) -> Map<file, { text, mtimeMs, size }>
|
|
24
|
+
// restoreSpace({ dir, before, log }) -> { restored, removed, warnings }
|
|
25
|
+
//
|
|
26
|
+
// 本模块只用 node: 内置模块,不 import 任何 @deepseek-ai/*。
|
|
27
|
+
|
|
28
|
+
import { readFileSync, readdirSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
|
|
29
|
+
import { join } from 'node:path'
|
|
30
|
+
|
|
31
|
+
export const MEMORY_TYPES = ['user', 'feedback', 'project', 'reference']
|
|
32
|
+
/** 一次整理最多汇报多少个冲突;超出部分只记日志。 */
|
|
33
|
+
export const MAX_CONFLICTS = 5
|
|
34
|
+
/** 被整理改写的笔记正文至少保留原长度的这个比例,否则视为"读都没读完就重写"。 */
|
|
35
|
+
export const MIN_BODY_RATIO = 0.5
|
|
36
|
+
/** 缩水保护只在绝对差超过这个字符数时生效,避免短笔记误伤。 */
|
|
37
|
+
export const MIN_BODY_DELTA = 400
|
|
38
|
+
|
|
39
|
+
const INDEX_NAME = 'MEMORY.md'
|
|
40
|
+
const SAFE_FILE = /^[a-z0-9][a-z0-9._-]*\.md$/
|
|
41
|
+
const MAX_NAME_CHARS = 120
|
|
42
|
+
const MAX_DESCRIPTION_CHARS = 240
|
|
43
|
+
const MAX_REASON_CHARS = 240
|
|
44
|
+
const MAX_EVIDENCE_CHARS = 240
|
|
45
|
+
const DEFAULT_TIMEOUT_MS = 180_000
|
|
46
|
+
|
|
47
|
+
function errorMessage(error) {
|
|
48
|
+
return error instanceof Error ? error.message : String(error)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function collapseLine(text) {
|
|
52
|
+
return String(text ?? '')
|
|
53
|
+
.replace(/\s+/g, ' ')
|
|
54
|
+
.trim()
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function clampText(text, max) {
|
|
58
|
+
const value = collapseLine(text)
|
|
59
|
+
return value.length > max ? value.slice(0, max).trim() : value
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function logAt(log, level, ...args) {
|
|
63
|
+
if (log === null || typeof log !== 'object') return
|
|
64
|
+
const write = log[level]
|
|
65
|
+
if (typeof write !== 'function') return
|
|
66
|
+
try {
|
|
67
|
+
write.call(log, ...args)
|
|
68
|
+
} catch {
|
|
69
|
+
// 日志永远不允许把整理流程带崩。
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ---------------------------------------------------------------------------
|
|
74
|
+
// 提示词
|
|
75
|
+
// ---------------------------------------------------------------------------
|
|
76
|
+
|
|
77
|
+
/** 一行笔记清单:文件、类型、更新时间、长度。正文不放进提示词——子 agent 自己去读。 */
|
|
78
|
+
function manifestLine(note) {
|
|
79
|
+
const file = typeof note?.file === 'string' ? note.file : ''
|
|
80
|
+
if (file === '') return ''
|
|
81
|
+
const type = MEMORY_TYPES.includes(note?.type) ? note.type : 'project'
|
|
82
|
+
const name = clampText(note?.name, MAX_NAME_CHARS) || file
|
|
83
|
+
const description = clampText(note?.description, MAX_DESCRIPTION_CHARS)
|
|
84
|
+
const updated = clampText(note?.updated, 40)
|
|
85
|
+
const chars = Number.isFinite(note?.chars) ? note.chars : null
|
|
86
|
+
const parts = [`- \`${file}\``, `[${type}]`, name]
|
|
87
|
+
if (description !== '') parts.push(`— ${description}`)
|
|
88
|
+
if (updated !== '') parts.push(`(updated ${updated})`)
|
|
89
|
+
if (chars !== null) parts.push(`${chars} chars`)
|
|
90
|
+
return parts.join(' ')
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* 生成 dream agent 的提示词。
|
|
95
|
+
*
|
|
96
|
+
* 与单次调用的 buildDreamOpsPrompt 的关键差别:
|
|
97
|
+
* - 不塞正文,只给清单,要求子 agent 用文件工具去读;
|
|
98
|
+
* - 明确给出记忆目录和代码根目录,要求"用现实核对断言";
|
|
99
|
+
* - 输出里要求 evidence(你核对了什么)和 conflicts(无法判断时不要猜)。
|
|
100
|
+
*
|
|
101
|
+
* prompt 不含易变内容(日期、随机串),同一入参永远得到同一段文本。
|
|
102
|
+
*/
|
|
103
|
+
export function buildDreamAgentPrompt(options = {}) {
|
|
104
|
+
const input = options ?? {}
|
|
105
|
+
const memoryDir = collapseLine(input.memoryDir) || '<memory directory>'
|
|
106
|
+
const codeRoot = collapseLine(input.codeRoot) || '<workspace directory>'
|
|
107
|
+
const spaceLabel = collapseLine(input.spaceLabel) || 'this workspace'
|
|
108
|
+
const maxOps = Number.isFinite(input.maxOps) ? Math.max(1, Math.trunc(input.maxOps)) : 8
|
|
109
|
+
const notes = Array.isArray(input.notes) ? input.notes : []
|
|
110
|
+
const sessionHints = Array.isArray(input.sessionHints) ? input.sessionHints : []
|
|
111
|
+
|
|
112
|
+
const lines = notes.map(manifestLine).filter(line => line !== '')
|
|
113
|
+
const existing = lines.length === 0 ? '(this space has no notes yet)' : lines.join('\n')
|
|
114
|
+
const hints =
|
|
115
|
+
sessionHints.length === 0
|
|
116
|
+
? 'The host recorded no new sessions since the last pass.'
|
|
117
|
+
: `Sessions started since the last pass (${sessionHints.length}):\n${sessionHints
|
|
118
|
+
.slice(0, 50)
|
|
119
|
+
.map(id => `- ${id}`)
|
|
120
|
+
.join('\n')}`
|
|
121
|
+
|
|
122
|
+
return `# Dream: memory consolidation with evidence
|
|
123
|
+
|
|
124
|
+
You are the memory consolidation step for the workspace memory space "${spaceLabel}". You have tools and you are expected to use them: a consolidation that only reshuffles text cannot tell whether a note is still true.
|
|
125
|
+
|
|
126
|
+
Memory directory: \`${memoryDir}\`
|
|
127
|
+
Workspace directory: \`${codeRoot}\`
|
|
128
|
+
|
|
129
|
+
## Hard constraints
|
|
130
|
+
|
|
131
|
+
1. **Do not write.** Do not create, edit, move, or delete any file. No redirection, no \`touch\`, no shell command that changes state. Any file you modify is reverted by the host, and the whole pass may be discarded.
|
|
132
|
+
2. **Ignore the memory tools.** You inherited the parent conversation's guidance about saving memories. It does not apply to this pass: do not call \`memory_note\` / \`memory_forget\` or any save-memory tool, even if the guidance tells you to. Your only output channel is the JSON plan below.
|
|
133
|
+
3. **Read before you rewrite.** Every note you return in "merges" must have been read in full with your file tools. The manifest below lists sizes, not contents.
|
|
134
|
+
4. **This pass consolidates; it does not capture new facts.** Fold what the notes already claim into fewer, more accurate notes. Do not turn this into a log of what recently happened.
|
|
135
|
+
5. Never empty the space. If the only note is stale, rewrite it into the most useful durable summary instead of deleting it.
|
|
136
|
+
|
|
137
|
+
## Existing notes (${lines.length})
|
|
138
|
+
|
|
139
|
+
${existing}
|
|
140
|
+
|
|
141
|
+
## Phase 1 — Orient
|
|
142
|
+
|
|
143
|
+
Read the notes that matter. Build an inventory: what each note claims, when it was last touched, which claims are concrete (file paths, function or flag names, commands, versions) and which are narrative.
|
|
144
|
+
|
|
145
|
+
## Phase 2 — Check claims against reality
|
|
146
|
+
|
|
147
|
+
Concrete claims are checkable; narrative ones are not. Check the concrete ones:
|
|
148
|
+
|
|
149
|
+
- A named file, directory, or path: does it still exist?
|
|
150
|
+
- A named function, flag, environment variable, script, or config key: grep for it.
|
|
151
|
+
- A command or workflow described as "the way to do X": does it still match the repo?
|
|
152
|
+
- \`git log\` in the workspace directory tells you which areas changed recently; a note about an area that changed after its \`updated\` date is a drift candidate.
|
|
153
|
+
|
|
154
|
+
A claim you could not verify is **not** automatically wrong — do not delete a note just because you did not find the string. Only act on claims you disproved.
|
|
155
|
+
|
|
156
|
+
## Phase 3 — Plan the changes
|
|
157
|
+
|
|
158
|
+
- **merges** — rewrite one existing note: its complete new body, not a diff, not a fragment. Fold in duplicates and corrections. Keep the note's existing name unless the topic itself changed.
|
|
159
|
+
- **deletes** — only for notes that are fully obsolete or entirely duplicated by a note you keep. Say why.
|
|
160
|
+
- **conflicts** — when two notes disagree and the evidence does not settle which is right, do **not** pick one. Report the conflict with both files and the single question a human should answer.
|
|
161
|
+
|
|
162
|
+
Convert relative dates ("yesterday", "last week", "上周") to absolute dates when the note itself supplies enough context; never invent one.
|
|
163
|
+
|
|
164
|
+
## Output
|
|
165
|
+
|
|
166
|
+
Return ONLY a JSON object, no prose and no code fence:
|
|
167
|
+
|
|
168
|
+
{"merges":[{"file":"existing-note.md","name":"Human readable topic","description":"One sentence used for recall","type":"user|feedback|project|reference","body":"complete new body","evidence":"what you checked, one line"}],"deletes":[{"file":"obsolete-note.md","reason":"why"}],"conflicts":[{"files":["a.md","b.md"],"summary":"what the notes disagree about","question":"what a human should decide"}]}
|
|
169
|
+
|
|
170
|
+
Rules:
|
|
171
|
+
- Every \`file\` must appear in the manifest above. Never invent a file name.
|
|
172
|
+
- At most ${maxOps} merge(s). Fewer is better.
|
|
173
|
+
- "name", "description" and "type" are optional in a merge; omit them to keep the note's current values.
|
|
174
|
+
- \`evidence\` is required on every merge and \`reason\` on every delete: one short line, no file contents.
|
|
175
|
+
- If the notes are already accurate and tidy, return {"merges":[],"deletes":[],"conflicts":[]}.
|
|
176
|
+
|
|
177
|
+
## Recent sessions
|
|
178
|
+
|
|
179
|
+
${hints}
|
|
180
|
+
|
|
181
|
+
If your tool set includes session-history search tools, use them narrowly — a few targeted queries about the specific claims you are checking, never a full read. If you have no such tools, treat this list as context only: it tells you roughly how much activity happened, not what was said.`;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// ---------------------------------------------------------------------------
|
|
185
|
+
// 回复解析
|
|
186
|
+
// ---------------------------------------------------------------------------
|
|
187
|
+
|
|
188
|
+
/** 模型回复里每一段可能的 JSON(围栏优先,其次是整段文本与首尾花括号之间)。 */
|
|
189
|
+
function jsonCandidates(text) {
|
|
190
|
+
const candidates = []
|
|
191
|
+
for (const match of text.matchAll(/```([\s\S]*?)```/g)) {
|
|
192
|
+
const block = String(match[1] ?? '').trim()
|
|
193
|
+
if (block === '') continue
|
|
194
|
+
candidates.push(block)
|
|
195
|
+
const newline = block.indexOf('\n')
|
|
196
|
+
if (newline > 0) {
|
|
197
|
+
const first = block.slice(0, newline).trim()
|
|
198
|
+
if (/^[A-Za-z][\w+.-]*$/.test(first)) {
|
|
199
|
+
const rest = block.slice(newline + 1).trim()
|
|
200
|
+
if (rest !== '') candidates.push(rest)
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
candidates.push(text)
|
|
205
|
+
const start = text.indexOf('{')
|
|
206
|
+
const end = text.lastIndexOf('}')
|
|
207
|
+
if (start >= 0 && end > start) candidates.push(text.slice(start, end + 1))
|
|
208
|
+
return candidates
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function sanitizeMerge(item) {
|
|
212
|
+
if (item === null || typeof item !== 'object' || Array.isArray(item)) return null
|
|
213
|
+
const file = typeof item.file === 'string' ? item.file.trim() : ''
|
|
214
|
+
if (!SAFE_FILE.test(file)) return null
|
|
215
|
+
if (typeof item.body !== 'string' || item.body.trim() === '') return null
|
|
216
|
+
const merge = { file, body: item.body }
|
|
217
|
+
const name = clampText(item.name, MAX_NAME_CHARS)
|
|
218
|
+
if (name !== '') merge.name = name
|
|
219
|
+
const description = clampText(item.description, MAX_DESCRIPTION_CHARS)
|
|
220
|
+
if (description !== '') merge.description = description
|
|
221
|
+
if (MEMORY_TYPES.includes(item.type)) merge.type = item.type
|
|
222
|
+
const evidence = clampText(item.evidence, MAX_EVIDENCE_CHARS)
|
|
223
|
+
if (evidence !== '') merge.evidence = evidence
|
|
224
|
+
return merge
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** deletes 允许 `"x.md"` 或 `{"file":"x.md","reason":"..."}` 两种写法。 */
|
|
228
|
+
function sanitizeDelete(item) {
|
|
229
|
+
if (typeof item === 'string') {
|
|
230
|
+
const file = item.trim()
|
|
231
|
+
return SAFE_FILE.test(file) ? { file } : null
|
|
232
|
+
}
|
|
233
|
+
if (item === null || typeof item !== 'object' || Array.isArray(item)) return null
|
|
234
|
+
const file = typeof item.file === 'string' ? item.file.trim() : ''
|
|
235
|
+
if (!SAFE_FILE.test(file)) return null
|
|
236
|
+
const reason = clampText(item.reason, MAX_REASON_CHARS)
|
|
237
|
+
return reason === '' ? { file } : { file, reason }
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function sanitizeConflict(item) {
|
|
241
|
+
if (item === null || typeof item !== 'object' || Array.isArray(item)) return null
|
|
242
|
+
const files = Array.isArray(item.files)
|
|
243
|
+
? [...new Set(item.files.filter(file => typeof file === 'string' && SAFE_FILE.test(file.trim())).map(file => file.trim()))]
|
|
244
|
+
: []
|
|
245
|
+
// 冲突的定义就是"两条笔记互相矛盾",少于两个文件不是冲突。
|
|
246
|
+
if (files.length < 2) return null
|
|
247
|
+
const summary = clampText(item.summary, MAX_REASON_CHARS)
|
|
248
|
+
const question = clampText(item.question, MAX_REASON_CHARS)
|
|
249
|
+
if (summary === '' && question === '') return null
|
|
250
|
+
return { files, summary, question }
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function dedupeByFile(items) {
|
|
254
|
+
const seen = new Set()
|
|
255
|
+
const out = []
|
|
256
|
+
for (const item of items) {
|
|
257
|
+
if (seen.has(item.file)) continue
|
|
258
|
+
seen.add(item.file)
|
|
259
|
+
out.push(item)
|
|
260
|
+
}
|
|
261
|
+
return out
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* 解析 dream agent 的回复。容忍 ```json 围栏、前后 prose、行内 JSON;
|
|
266
|
+
* 非对象/非法 JSON 返回 { error },由调用方整段丢弃。
|
|
267
|
+
*/
|
|
268
|
+
export function parseDreamAgentReply(raw) {
|
|
269
|
+
if (Array.isArray(raw)) return { error: 'reply is not an object' }
|
|
270
|
+
if (raw !== null && typeof raw === 'object') return normalizePlanObject(raw)
|
|
271
|
+
|
|
272
|
+
const text = String(raw ?? '').trim()
|
|
273
|
+
if (text === '') return { error: 'empty reply' }
|
|
274
|
+
let sawNonObject = false
|
|
275
|
+
let lastError = null
|
|
276
|
+
for (const candidate of jsonCandidates(text)) {
|
|
277
|
+
let parsed
|
|
278
|
+
try {
|
|
279
|
+
parsed = JSON.parse(candidate)
|
|
280
|
+
} catch (error) {
|
|
281
|
+
lastError = error
|
|
282
|
+
continue
|
|
283
|
+
}
|
|
284
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
285
|
+
sawNonObject = true
|
|
286
|
+
continue
|
|
287
|
+
}
|
|
288
|
+
return normalizePlanObject(parsed)
|
|
289
|
+
}
|
|
290
|
+
if (sawNonObject) return { error: 'reply is not an object' }
|
|
291
|
+
return { error: `invalid JSON${lastError === null ? '' : `: ${errorMessage(lastError)}`}` }
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function normalizePlanObject(parsed) {
|
|
295
|
+
const merges = Array.isArray(parsed.merges)
|
|
296
|
+
? dedupeByFile(parsed.merges.map(sanitizeMerge).filter(item => item !== null))
|
|
297
|
+
: []
|
|
298
|
+
const deletes = Array.isArray(parsed.deletes)
|
|
299
|
+
? dedupeByFile(parsed.deletes.map(sanitizeDelete).filter(item => item !== null))
|
|
300
|
+
: []
|
|
301
|
+
const conflicts = Array.isArray(parsed.conflicts)
|
|
302
|
+
? parsed.conflicts.map(sanitizeConflict).filter(item => item !== null)
|
|
303
|
+
: []
|
|
304
|
+
return { merges, deletes, conflicts }
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// ---------------------------------------------------------------------------
|
|
308
|
+
// 计划校验(落地前的硬约束)
|
|
309
|
+
// ---------------------------------------------------------------------------
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* 把模型计划收敛到可安全落地的操作集。
|
|
313
|
+
*
|
|
314
|
+
* - merges / deletes 只能命中本次清单里出现过的文件(模型没见过的笔记不许动);
|
|
315
|
+
* - 被截断正文的笔记不许重写(模型看不到全文时重写会丢数据);
|
|
316
|
+
* - 单次 merge 数不超过 maxOps;
|
|
317
|
+
* - 缩水保护:新正文不到原长度一半且少了 400 字符以上,拒绝——这通常意味着
|
|
318
|
+
* 模型没读完就重写了;
|
|
319
|
+
* - conflicts 不是操作,只回传,永远不自动解决。
|
|
320
|
+
*/
|
|
321
|
+
export function validateDreamAgentPlan(options = {}) {
|
|
322
|
+
const input = options ?? {}
|
|
323
|
+
const plan = input.plan ?? {}
|
|
324
|
+
const prompted = input.prompted instanceof Set ? input.prompted : new Set()
|
|
325
|
+
const truncated = input.truncated instanceof Set ? input.truncated : new Set()
|
|
326
|
+
const sizes = input.sizes instanceof Map ? input.sizes : new Map()
|
|
327
|
+
const maxOps = Number.isFinite(input.maxOps) ? Math.max(1, Math.trunc(input.maxOps)) : 8
|
|
328
|
+
const maxDeletes = Number.isFinite(input.maxDeletes) ? Math.max(0, Math.trunc(input.maxDeletes)) : 5
|
|
329
|
+
|
|
330
|
+
const rejected = []
|
|
331
|
+
const merges = []
|
|
332
|
+
for (const merge of Array.isArray(plan.merges) ? plan.merges : []) {
|
|
333
|
+
if (!prompted.has(merge.file)) {
|
|
334
|
+
rejected.push({ file: merge.file, reason: 'not in this pass manifest' })
|
|
335
|
+
continue
|
|
336
|
+
}
|
|
337
|
+
if (truncated.has(merge.file)) {
|
|
338
|
+
rejected.push({ file: merge.file, reason: 'body was truncated for this pass' })
|
|
339
|
+
continue
|
|
340
|
+
}
|
|
341
|
+
const current = sizes.get(merge.file)
|
|
342
|
+
if (Number.isFinite(current) && current > 0) {
|
|
343
|
+
const next = merge.body.length
|
|
344
|
+
if (next < current * MIN_BODY_RATIO && current - next > MIN_BODY_DELTA) {
|
|
345
|
+
rejected.push({ file: merge.file, reason: `rewrite drops ${current - next} chars (${current} → ${next})` })
|
|
346
|
+
continue
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
merges.push(merge)
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
const deletes = []
|
|
353
|
+
for (const item of Array.isArray(plan.deletes) ? plan.deletes : []) {
|
|
354
|
+
if (!prompted.has(item.file)) {
|
|
355
|
+
rejected.push({ file: item.file, reason: 'not in this pass manifest' })
|
|
356
|
+
continue
|
|
357
|
+
}
|
|
358
|
+
if (deletes.length >= maxDeletes) {
|
|
359
|
+
rejected.push({ file: item.file, reason: `delete budget of ${maxDeletes} reached` })
|
|
360
|
+
continue
|
|
361
|
+
}
|
|
362
|
+
deletes.push(item.file)
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const conflicts = []
|
|
366
|
+
for (const conflict of Array.isArray(plan.conflicts) ? plan.conflicts : []) {
|
|
367
|
+
const files = conflict.files.filter(file => prompted.has(file))
|
|
368
|
+
if (files.length < 2) continue
|
|
369
|
+
conflicts.push({ files, summary: conflict.summary, question: conflict.question })
|
|
370
|
+
if (conflicts.length >= MAX_CONFLICTS) break
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
return {
|
|
374
|
+
merges: merges.slice(0, maxOps),
|
|
375
|
+
deletes,
|
|
376
|
+
conflicts,
|
|
377
|
+
rejected,
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// ---------------------------------------------------------------------------
|
|
382
|
+
// 快照守卫:把子 agent 的越权写入回滚
|
|
383
|
+
// ---------------------------------------------------------------------------
|
|
384
|
+
|
|
385
|
+
/** 读取记忆目录下所有 Markdown(含生成的 MEMORY.md)的内容与元信息。 */
|
|
386
|
+
export function snapshotSpace(dir) {
|
|
387
|
+
const snapshot = new Map()
|
|
388
|
+
let entries
|
|
389
|
+
try {
|
|
390
|
+
entries = readdirSync(dir, { withFileTypes: true })
|
|
391
|
+
} catch {
|
|
392
|
+
return snapshot
|
|
393
|
+
}
|
|
394
|
+
for (const entry of entries) {
|
|
395
|
+
if (!entry.isFile() || !entry.name.endsWith('.md')) continue
|
|
396
|
+
const path = join(dir, entry.name)
|
|
397
|
+
try {
|
|
398
|
+
const stat = statSync(path)
|
|
399
|
+
snapshot.set(entry.name, {
|
|
400
|
+
text: readFileSync(path, 'utf8'),
|
|
401
|
+
mtimeMs: stat.mtimeMs,
|
|
402
|
+
size: stat.size,
|
|
403
|
+
})
|
|
404
|
+
} catch {
|
|
405
|
+
// 单条读失败不影响其它条目;它只是不会进入快照。
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
return snapshot
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* 对比快照与当前目录:新增的删掉,被改的写回原内容,被删的补回。
|
|
413
|
+
*
|
|
414
|
+
* 子 agent 不该写文件;真写了就说明提示词约束失效,这里做最后一道兜底。
|
|
415
|
+
* 任何一步失败只记录警告,绝不抛错——整理本身不该因为回滚失败而中断。
|
|
416
|
+
*/
|
|
417
|
+
export function restoreSpace({ dir, before, log } = {}) {
|
|
418
|
+
const restored = []
|
|
419
|
+
const removed = []
|
|
420
|
+
const warnings = []
|
|
421
|
+
if (!(before instanceof Map)) return { restored, removed, warnings }
|
|
422
|
+
|
|
423
|
+
const after = snapshotSpace(dir)
|
|
424
|
+
for (const [file, current] of after) {
|
|
425
|
+
const original = before.get(file)
|
|
426
|
+
if (original === undefined) {
|
|
427
|
+
try {
|
|
428
|
+
unlinkSync(join(dir, file))
|
|
429
|
+
removed.push(file)
|
|
430
|
+
} catch (error) {
|
|
431
|
+
warnings.push(`${file}: cannot remove: ${errorMessage(error)}`)
|
|
432
|
+
}
|
|
433
|
+
continue
|
|
434
|
+
}
|
|
435
|
+
if (original.size === current.size && original.mtimeMs === current.mtimeMs) continue
|
|
436
|
+
try {
|
|
437
|
+
writeFileSync(join(dir, file), original.text, 'utf8')
|
|
438
|
+
restored.push(file)
|
|
439
|
+
} catch (error) {
|
|
440
|
+
warnings.push(`${file}: cannot restore: ${errorMessage(error)}`)
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
for (const [file, original] of before) {
|
|
444
|
+
if (after.has(file)) continue
|
|
445
|
+
try {
|
|
446
|
+
writeFileSync(join(dir, file), original.text, 'utf8')
|
|
447
|
+
restored.push(file)
|
|
448
|
+
} catch (error) {
|
|
449
|
+
warnings.push(`${file}: cannot recreate: ${errorMessage(error)}`)
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
if (restored.length > 0 || removed.length > 0) {
|
|
454
|
+
logAt(log, 'warn', 'dsh-memory: dream agent wrote to the memory directory; reverted %d restored / %d removed', restored.length, removed.length)
|
|
455
|
+
}
|
|
456
|
+
for (const warning of warnings) logAt(log, 'warn', 'dsh-memory: dream guard: %s', warning)
|
|
457
|
+
return { restored, removed, warnings }
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// ---------------------------------------------------------------------------
|
|
461
|
+
// 运行器:起子 agent,拿回计划
|
|
462
|
+
// ---------------------------------------------------------------------------
|
|
463
|
+
|
|
464
|
+
function textOfOutput(output) {
|
|
465
|
+
if (!Array.isArray(output)) return ''
|
|
466
|
+
const parts = []
|
|
467
|
+
for (const block of output) {
|
|
468
|
+
if (block === null || typeof block !== 'object') continue
|
|
469
|
+
if (block.type === 'text' && typeof block.text === 'string') parts.push(block.text)
|
|
470
|
+
}
|
|
471
|
+
return parts.join('\n').trim()
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function normalizeAgentConfig(config) {
|
|
475
|
+
const section = config?.dream ?? config ?? {}
|
|
476
|
+
const provider = collapseLine(section.provider)
|
|
477
|
+
return {
|
|
478
|
+
enabled: section.agent !== false,
|
|
479
|
+
provider: provider === '' ? 'spawn' : provider,
|
|
480
|
+
model: collapseLine(section.agentModel ?? section.model),
|
|
481
|
+
timeoutMs:
|
|
482
|
+
Number.isFinite(section.agentTimeoutMs) && section.agentTimeoutMs > 0
|
|
483
|
+
? Math.trunc(section.agentTimeoutMs)
|
|
484
|
+
: DEFAULT_TIMEOUT_MS,
|
|
485
|
+
maxOps: Number.isFinite(section.maxNotes) ? Math.max(1, Math.min(8, Math.trunc(section.maxNotes))) : 8,
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* 造一个 respond:入口签名与单次调用路径一致,返回解析后的计划。
|
|
491
|
+
*
|
|
492
|
+
* 依赖全部由调用方注入,本函数不懂 DSH 的装配细节:
|
|
493
|
+
* getSubagents() -> ctx.subagents 或 undefined
|
|
494
|
+
* getParent(session) -> 活着的主 Agent(子 agent 的 parent)
|
|
495
|
+
* getCodeRoot(session) -> 工作目录
|
|
496
|
+
* getSessionHints() -> 自上次整理以来的 session id 列表
|
|
497
|
+
*/
|
|
498
|
+
export function createDreamAgentRunner(options = {}) {
|
|
499
|
+
const getSubagents = typeof options.getSubagents === 'function' ? options.getSubagents : null
|
|
500
|
+
const getParent = typeof options.getParent === 'function' ? options.getParent : null
|
|
501
|
+
const getCodeRoot = typeof options.getCodeRoot === 'function' ? options.getCodeRoot : null
|
|
502
|
+
const getSessionHints = typeof options.getSessionHints === 'function' ? options.getSessionHints : null
|
|
503
|
+
const log = options.log ?? null
|
|
504
|
+
const settings = normalizeAgentConfig(options.config)
|
|
505
|
+
async function respond(input = {}) {
|
|
506
|
+
if (!settings.enabled) return { error: 'dream agent disabled' }
|
|
507
|
+
if (getSubagents === null || getParent === null) return { error: 'no subagent service' }
|
|
508
|
+
|
|
509
|
+
let subagents
|
|
510
|
+
try {
|
|
511
|
+
subagents = getSubagents()
|
|
512
|
+
} catch (error) {
|
|
513
|
+
return { error: `subagent lookup failed: ${errorMessage(error)}` }
|
|
514
|
+
}
|
|
515
|
+
if (subagents === null || subagents === undefined || typeof subagents.startActivation !== 'function') {
|
|
516
|
+
return { error: 'no subagent service' }
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
let parent
|
|
520
|
+
try {
|
|
521
|
+
parent = getParent(input.session)
|
|
522
|
+
} catch (error) {
|
|
523
|
+
return { error: `parent lookup failed: ${errorMessage(error)}` }
|
|
524
|
+
}
|
|
525
|
+
if (parent === null || parent === undefined) return { error: 'no live parent agent' }
|
|
526
|
+
|
|
527
|
+
let codeRoot = ''
|
|
528
|
+
try {
|
|
529
|
+
codeRoot = getCodeRoot === null ? '' : String(getCodeRoot(input.session) ?? '')
|
|
530
|
+
} catch {
|
|
531
|
+
codeRoot = ''
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
let sessionHints = []
|
|
535
|
+
try {
|
|
536
|
+
sessionHints = getSessionHints === null ? [] : (getSessionHints() ?? [])
|
|
537
|
+
} catch {
|
|
538
|
+
sessionHints = []
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
const notes = Array.isArray(input.notes) ? input.notes : []
|
|
542
|
+
const prompt = buildDreamAgentPrompt({
|
|
543
|
+
memoryDir: input.memoryDir,
|
|
544
|
+
codeRoot,
|
|
545
|
+
spaceLabel: input.spaceLabel,
|
|
546
|
+
notes,
|
|
547
|
+
sessionHints,
|
|
548
|
+
maxOps: settings.maxOps,
|
|
549
|
+
})
|
|
550
|
+
|
|
551
|
+
const before = typeof input.memoryDir === 'string' && input.memoryDir !== '' ? snapshotSpace(input.memoryDir) : null
|
|
552
|
+
|
|
553
|
+
// 统一用一个自建 controller:既响应调用方中止,也响应本模块的墙钟超时。
|
|
554
|
+
const controller = new AbortController()
|
|
555
|
+
const signal = controller.signal
|
|
556
|
+
const timer = setTimeout(() => controller.abort(new Error('dream agent timed out')), settings.timeoutMs)
|
|
557
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
558
|
+
const callerSignal = input.signal instanceof AbortSignal ? input.signal : null
|
|
559
|
+
const onCallerAbort = () => controller.abort(callerSignal?.reason)
|
|
560
|
+
if (callerSignal !== null) {
|
|
561
|
+
if (callerSignal.aborted) controller.abort(callerSignal.reason)
|
|
562
|
+
else callerSignal.addEventListener('abort', onCallerAbort, { once: true })
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
let activation = null
|
|
566
|
+
try {
|
|
567
|
+
activation = await subagents.startActivation({
|
|
568
|
+
provider: settings.provider,
|
|
569
|
+
label: 'dsh-memory dream',
|
|
570
|
+
name: 'dream',
|
|
571
|
+
delivery: 'caller',
|
|
572
|
+
signal,
|
|
573
|
+
prompt: [{ type: 'text', text: prompt }],
|
|
574
|
+
parent,
|
|
575
|
+
...(settings.model === '' ? {} : { agentOptions: { model: settings.model } }),
|
|
576
|
+
})
|
|
577
|
+
const result = await activation.result
|
|
578
|
+
if (result?.stopReason !== 'completed') {
|
|
579
|
+
const detail = typeof result?.diagnostic === 'string' ? `: ${result.diagnostic}` : ''
|
|
580
|
+
return { error: `dream agent ended with ${String(result?.stopReason ?? 'unknown')}${detail}` }
|
|
581
|
+
}
|
|
582
|
+
const text = textOfOutput(result.output)
|
|
583
|
+
if (text === '') return { error: 'dream agent produced no output' }
|
|
584
|
+
const parsed = parseDreamAgentReply(text)
|
|
585
|
+
if (parsed.error !== undefined) return { error: `dream agent reply invalid: ${parsed.error}` }
|
|
586
|
+
logAt(
|
|
587
|
+
log,
|
|
588
|
+
'debug',
|
|
589
|
+
'dsh-memory: dream agent proposed %d merge(s), %d delete(s), %d conflict(s)',
|
|
590
|
+
parsed.merges.length,
|
|
591
|
+
parsed.deletes.length,
|
|
592
|
+
parsed.conflicts.length,
|
|
593
|
+
)
|
|
594
|
+
return parsed
|
|
595
|
+
} catch (error) {
|
|
596
|
+
return { error: `dream agent failed: ${errorMessage(error)}` }
|
|
597
|
+
} finally {
|
|
598
|
+
clearTimeout(timer)
|
|
599
|
+
if (callerSignal !== null) callerSignal.removeEventListener('abort', onCallerAbort)
|
|
600
|
+
// 先等子 agent 真正收尾,再回滚写入:否则它的最后一次写可能落在快照恢复之后。
|
|
601
|
+
if (activation !== null && typeof activation.dispose === 'function') {
|
|
602
|
+
try {
|
|
603
|
+
await activation.dispose()
|
|
604
|
+
} catch (error) {
|
|
605
|
+
logAt(log, 'debug', 'dsh-memory: dream activation dispose failed: %o', error)
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
if (before !== null) {
|
|
609
|
+
try {
|
|
610
|
+
restoreSpace({ dir: input.memoryDir, before, log })
|
|
611
|
+
} catch (error) {
|
|
612
|
+
logAt(log, 'warn', 'dsh-memory: dream guard failed: %o', error)
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
return { respond }
|
|
619
|
+
}
|