dsh-seal-scripts 0.0.0-stage → 0.4.7
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.en.md +318 -0
- package/README.md +342 -2
- package/cordis.patch.yml +6 -0
- package/index.js +12 -0
- package/lib/client.js +1465 -0
- package/lib/core/assembly.js +321 -0
- package/lib/core/catalog-snapshot.js +78 -0
- package/lib/core/diary.js +100 -0
- package/lib/core/health.js +72 -0
- package/lib/core/index.js +491 -0
- package/lib/core/inject.js +146 -0
- package/lib/core/lang.js +251 -0
- package/lib/core/locale.js +56 -0
- package/lib/core/memory-file.js +214 -0
- package/lib/core/migrate.js +97 -0
- package/lib/core/path-guard.js +43 -0
- package/lib/core/project-key.js +52 -0
- package/lib/core/render.js +228 -0
- package/lib/core/schema-runner.js +281 -0
- package/lib/core/schema-tools.js +794 -0
- package/lib/core/schema.js +493 -0
- package/lib/core/search.js +254 -0
- package/lib/core/settings.js +158 -0
- package/lib/core/store.js +408 -0
- package/lib/core/tool-transfer.js +249 -0
- package/lib/core/tool.js +602 -0
- package/lib/core/zip.js +226 -0
- package/lib/core/zstd-js.js +705 -0
- package/lib/core/zstd.js +103 -0
- package/lib/host/api.js +9 -0
- package/lib/host/capabilities.js +155 -0
- package/lib/host/compact-delete.js +76 -0
- package/lib/host/delete.js +136 -0
- package/lib/host/host-contract.js +73 -0
- package/lib/host/http-util.js +82 -0
- package/lib/host/lifecycle.js +66 -0
- package/lib/host/register.js +63 -0
- package/lib/host/routes/memories.js +102 -0
- package/lib/host/routes/options.js +46 -0
- package/lib/host/routes/sessions.js +194 -0
- package/lib/host/routes/tools.js +103 -0
- package/lib/host/summary.js +71 -0
- package/package.json +60 -4
package/lib/core/tool.js
ADDED
|
@@ -0,0 +1,602 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 两个工具:session_mem_read(一个线索进去,搜完一条条读出来)与 session_mem_write(读那一份的原文 / 写关键词 / 写日记)。
|
|
3
|
+
*
|
|
4
|
+
* session_mem_read need 必填。顺序:本工作区自己 -> 子级 -> (许可后)平级与上级;
|
|
5
|
+
* 一次只返回一条命中的回顾,读不对就再调一次、把它加进 skip。
|
|
6
|
+
* 只有「本工作区自己」那条被读出去时才算一次命中(0->1、1->2 并锁定)。
|
|
7
|
+
* session_mem_write 用 file,或者用 date(+nth) 定位(「30 号第一份」= date 那天、nth 1,按压缩时刻排);
|
|
8
|
+
* 只定位不写 = 读这一份的「原文」区,只给对话、工具调用(▸/◂ 及其输出)整块剔除;
|
|
9
|
+
* 写的时候 keywords 与 diary 可以一次给齐;多份用 writes 一次写完(全部合格才落盘)。
|
|
10
|
+
*
|
|
11
|
+
* 只动目标区,其余字节不动;改完重新解析校验,坏了就回滚。
|
|
12
|
+
* 文件路径必须落在本工作区的回顾目录里,不许越界。
|
|
13
|
+
*
|
|
14
|
+
* 不依赖 @deepseek-ai/dsh-tools:ctx.tools.register() 只要一个 { name, description,
|
|
15
|
+
* parameters, output:{schema, render}, execute } 的对象,参数和输出都用标准 JSON Schema。
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import fsp from 'node:fs/promises'
|
|
19
|
+
import path from 'node:path'
|
|
20
|
+
import { memoryDir, readAssembly, writeFileAtomic, renameWithRetry } from './store.js'
|
|
21
|
+
import { assertInside, assertMarkdown } from './path-guard.js'
|
|
22
|
+
import { parseMemory, setField, setSection } from './memory-file.js'
|
|
23
|
+
import { readField, isBlankDiary, isBlankKeywords } from './lang.js'
|
|
24
|
+
import { listCandidates } from './search.js'
|
|
25
|
+
import { dialogueOnly } from './render.js'
|
|
26
|
+
|
|
27
|
+
/** 工具名:得是合法 JS 标识符(PTC 模式会把工具折成 SDK 声明)。 */
|
|
28
|
+
/** 搜索入口:读的面更大。名字得是合法 JS 标识符(PTC 模式会把工具折成 SDK 声明)。 */
|
|
29
|
+
export const READ_TOOL_NAME = 'session_mem_read'
|
|
30
|
+
|
|
31
|
+
/** 写入口:只读要写的那一份的原文,以及写关键词 / 日记。 */
|
|
32
|
+
export const WRITE_TOOL_NAME = 'session_mem_write'
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 把模型给的路径归一到本工作区回顾目录内的文件。越界直接抛错,不静默兜底。
|
|
36
|
+
* @param {string} dshHome
|
|
37
|
+
* @param {string} cwd
|
|
38
|
+
* @param {string} file
|
|
39
|
+
* @returns {string} 绝对路径
|
|
40
|
+
*/
|
|
41
|
+
export function resolveMemoryFile(dshHome, cwd, file) {
|
|
42
|
+
const dir = memoryDir(dshHome, cwd)
|
|
43
|
+
const abs = assertInside(dir, file, { label: '本工作区的回顾目录' })
|
|
44
|
+
return assertMarkdown(abs, file)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 窄读:返回这一份的「原文」区,只留对话。
|
|
49
|
+
*
|
|
50
|
+
* 0.2.7 起工具调用整块剔除(▸ 发起、◂ 结果、以及结果的多行正文):
|
|
51
|
+
* 写日记要的是有人说了什么,不是工具跑了什么;原文里的工具部分只给人看。
|
|
52
|
+
*
|
|
53
|
+
* 只给 file 的这条路径(写日记前先看原文)不动深度 —— 深度只跟 read 工具的搜中走,
|
|
54
|
+
* 并且由插件侧记账(见 lib/core/index.js 的 countHit)。
|
|
55
|
+
* @returns {Promise<{file:string, path:string, text:string}>}
|
|
56
|
+
*/
|
|
57
|
+
export async function readMemorySection({ dshHome, cwd, file }) {
|
|
58
|
+
const abs = resolveMemoryFile(dshHome, cwd, file)
|
|
59
|
+
const text = await fsp.readFile(abs, 'utf8')
|
|
60
|
+
const parsed = parseMemory(text)
|
|
61
|
+
if (!parsed.id) throw new Error('这份文件没有回顾分区标记,不是回顾文件:' + file)
|
|
62
|
+
return { file: path.basename(abs), path: abs, text: dialogueOnly(parsed.sections.body) }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* 估 token:UTF-8 字节数 / 4,向上取整。
|
|
67
|
+
* 只用来比长短(日记不能比摘要长),不做精度承诺。
|
|
68
|
+
*/
|
|
69
|
+
export function estimateTokens(text) {
|
|
70
|
+
const s = String(text === undefined || text === null ? '' : text)
|
|
71
|
+
return Math.ceil(Buffer.byteLength(s, 'utf8') / 4)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* 日记比摘要长时的报错,写法对齐「回顾过大」那套诊断:标题 + 现状 + 处理。
|
|
76
|
+
*/
|
|
77
|
+
function diaryTooLongMessage(file, diaryTokens, sumTokens) {
|
|
78
|
+
return [
|
|
79
|
+
'【日记没有写进去】日记比摘要还长,已拒绝。',
|
|
80
|
+
'文件:' + file,
|
|
81
|
+
'现状:日记约 ' + diaryTokens + ' token,摘要约 ' + sumTokens + ' token;日记不得超过摘要。',
|
|
82
|
+
'处理:把日记压到摘要以内再写——只留下次能接上的要点,细节本来就留在原文里。'
|
|
83
|
+
].join('\n')
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 关键词不比日记短时的报错,格式对齐日记那条诊断:标题 + 现状 + 处理。
|
|
88
|
+
*/
|
|
89
|
+
function keywordsTooLongMessage(file, keyTokens, diaryTokens) {
|
|
90
|
+
return [
|
|
91
|
+
'【关键词没有写进去】关键词的 token 不少于日记,已拒绝。',
|
|
92
|
+
'文件:' + file,
|
|
93
|
+
'现状:关键词约 ' + keyTokens + ' token,日记约 ' + diaryTokens + ' token;关键词必须少于日记。',
|
|
94
|
+
'处理:从原文另做一遍摘要,用更少的 token 讲同一件事——它要当检索用的索引,不是第二份日记。'
|
|
95
|
+
].join('\n')
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* 在内存里把一份回顾改好:只算新文本,不落盘。
|
|
100
|
+
*
|
|
101
|
+
* 两道闸门都在这里卡(日记不得超过摘要、关键词必须比日记短),任何一道不过就抛错——
|
|
102
|
+
* 于是批量写时只要一份不合格,整批都不写。keywords 与 diary 可以只给一个,也可以一起给。
|
|
103
|
+
* @param {string} before 读到手的旧文本
|
|
104
|
+
* @param {{file:string, keywords?:string[], diary?:string}} item
|
|
105
|
+
* @returns {{next:string, changed:string[], diary:string, keywords:string}}
|
|
106
|
+
*/
|
|
107
|
+
export function applyWrite(before, { file, keywords, diary }) {
|
|
108
|
+
const hasKeywords = Array.isArray(keywords)
|
|
109
|
+
const hasDiary = typeof diary === 'string'
|
|
110
|
+
if (!hasKeywords && !hasDiary) throw new Error('keywords 与 diary 至少给一个')
|
|
111
|
+
|
|
112
|
+
const parsed = parseMemory(before)
|
|
113
|
+
const oldDiary = String(parsed.sections.diary ?? '').trim()
|
|
114
|
+
const oldKeys = String(readField(parsed.meta, 'keywords')).trim()
|
|
115
|
+
|
|
116
|
+
let keyLine = null
|
|
117
|
+
if (hasKeywords) {
|
|
118
|
+
const words = keywords.map((w) => String(w).trim()).filter(Boolean)
|
|
119
|
+
if (words.length === 0) throw new Error('keywords 不能是空数组')
|
|
120
|
+
keyLine = words.join(' · ')
|
|
121
|
+
}
|
|
122
|
+
const nextDiary = hasDiary ? String(diary).trim() : oldDiary
|
|
123
|
+
const nextKeys = keyLine === null ? oldKeys : keyLine.trim()
|
|
124
|
+
|
|
125
|
+
if (!isBlankDiary(nextDiary)) {
|
|
126
|
+
// 闸门一:写完的日记不能比摘要长:摘要才是压缩之后该有的体量。
|
|
127
|
+
// 摘要为空(没总结出来)时不做限制,否则这份回顾会连日记也写不进去。
|
|
128
|
+
const sumTokens = estimateTokens(parsed.sections.sum)
|
|
129
|
+
const diaryTokens = estimateTokens(nextDiary)
|
|
130
|
+
if (sumTokens > 0 && diaryTokens > sumTokens) {
|
|
131
|
+
throw new Error(diaryTooLongMessage(file, diaryTokens, sumTokens))
|
|
132
|
+
}
|
|
133
|
+
// 闸门二:关键词必须比日记短(关键词还空着时放行——它还没写,不算「太长」)。
|
|
134
|
+
if (!isBlankKeywords(nextKeys)) {
|
|
135
|
+
const keyTokens = estimateTokens(nextKeys)
|
|
136
|
+
if (keyTokens >= diaryTokens) {
|
|
137
|
+
throw new Error(keywordsTooLongMessage(file, keyTokens, diaryTokens))
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
let next = before
|
|
143
|
+
const changed = []
|
|
144
|
+
if (hasKeywords) {
|
|
145
|
+
const updated = setField(next, 'keywords', keyLine)
|
|
146
|
+
if (updated === null) throw new Error('这份文件没有「关键词」字段')
|
|
147
|
+
next = updated
|
|
148
|
+
changed.push('关键词')
|
|
149
|
+
}
|
|
150
|
+
if (hasDiary) {
|
|
151
|
+
const updated = setSection(next, 'diary', diary)
|
|
152
|
+
if (updated === null) throw new Error('这份文件没有日记分区')
|
|
153
|
+
next = updated
|
|
154
|
+
changed.push('日记')
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const check = parseMemory(next)
|
|
158
|
+
const ok = check.id && ['sum', 'body', 'diary'].every((k) => typeof check.sections[k] === 'string')
|
|
159
|
+
if (!ok) throw new Error('写入后校验失败:' + file)
|
|
160
|
+
return { next, changed, diary: check.sections.diary, keywords: readField(check.meta, 'keywords') }
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* 批量写落盘用的 IO 面。默认全是真实现(store.js 的原子写 + Windows 重试)。
|
|
165
|
+
*
|
|
166
|
+
* 为什么留这个替换点:批量写中途失败是必须能测的路径,可 Windows 上造不出
|
|
167
|
+
* 「读得出、写不进」的文件状态(只读属性连 rm -f 都拦不住),只能在这一层注入。
|
|
168
|
+
* 生产路径永远走默认值,测试只在失败路径上换。
|
|
169
|
+
*/
|
|
170
|
+
const fileIO = {
|
|
171
|
+
writeTmp: (file, content) => fsp.writeFile(file, content, 'utf8'),
|
|
172
|
+
rename: (tmp, target) => renameWithRetry(tmp, target),
|
|
173
|
+
writeAtomic: (file, content) => writeFileAtomic(file, content)
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* 一次写多份(0.2.7):先在内存里把每一份都算好(含两道闸门),全部合格才落盘;
|
|
178
|
+
* 落盘中途出错就把已经写过的**逆序**还原并读回来核对,不留下半新半旧,
|
|
179
|
+
* 还原不了的会点名是哪几份。临时文件一律在 finally 里清掉。
|
|
180
|
+
* @param {{dshHome:string, cwd:string, items:Array<{file:string, keywords?:string[], diary?:string}>, io?:object}} p
|
|
181
|
+
* io 只给测试注入失败用,正常调用不用传。
|
|
182
|
+
* @returns {Promise<{items:Array<{file:string, path:string, changed:string, diary:string, keywords:string}>}>}
|
|
183
|
+
*/
|
|
184
|
+
export async function writeMemories({ dshHome, cwd, items, io = fileIO }) {
|
|
185
|
+
if (!Array.isArray(items) || items.length === 0) throw new Error('一次至少写一份')
|
|
186
|
+
const staged = []
|
|
187
|
+
const seen = new Set()
|
|
188
|
+
for (const item of items) {
|
|
189
|
+
const abs = resolveMemoryFile(dshHome, cwd, item.file)
|
|
190
|
+
if (seen.has(abs)) throw new Error('同一份写了两次:' + path.basename(abs))
|
|
191
|
+
seen.add(abs)
|
|
192
|
+
const before = await fsp.readFile(abs, 'utf8')
|
|
193
|
+
const parsed = parseMemory(before)
|
|
194
|
+
if (!parsed.id) throw new Error('这份文件没有回顾分区标记,不是回顾文件:' + item.file)
|
|
195
|
+
const applied = applyWrite(before, { file: path.basename(abs), keywords: item.keywords, diary: item.diary })
|
|
196
|
+
staged.push({ abs, before, ...applied })
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const written = []
|
|
200
|
+
const temps = []
|
|
201
|
+
try {
|
|
202
|
+
for (const s of staged) {
|
|
203
|
+
const tmp = path.join(path.dirname(s.abs),
|
|
204
|
+
path.basename(s.abs) + '.tmp-' + process.pid + '-' + Math.random().toString(36).slice(2, 8))
|
|
205
|
+
temps.push(tmp)
|
|
206
|
+
await io.writeTmp(tmp, s.next)
|
|
207
|
+
await io.rename(tmp, s.abs)
|
|
208
|
+
written.push(s)
|
|
209
|
+
}
|
|
210
|
+
} catch (err) {
|
|
211
|
+
// 逆序还原(后写的先还原),还原完读回来比对:
|
|
212
|
+
// 以前是「尽力而为」,从不检查自己成没成,文件停在半新半旧也没人知道。
|
|
213
|
+
const rollback = []
|
|
214
|
+
for (const s of written.slice().reverse()) {
|
|
215
|
+
try {
|
|
216
|
+
await io.writeAtomic(s.abs, s.before)
|
|
217
|
+
const back = await fsp.readFile(s.abs, 'utf8')
|
|
218
|
+
if (back !== s.before) rollback.push(path.basename(s.abs) + '(回滚后内容不一致)')
|
|
219
|
+
} catch (e) {
|
|
220
|
+
rollback.push(path.basename(s.abs) + '(回滚失败:' + (e?.message ?? e) + ')')
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
// 失败必须说清「哪些没回滚回去」——用户得知道哪一份停在半新半旧。
|
|
224
|
+
const detail = rollback.length > 0
|
|
225
|
+
? '\n以下是没能回滚的,请手工核对:\n · ' + rollback.join('\n · ')
|
|
226
|
+
: '\n所有已写入的文件都已还原。'
|
|
227
|
+
throw new Error((err?.message ?? String(err)) + detail)
|
|
228
|
+
} finally {
|
|
229
|
+
for (const tmp of temps) await fsp.rm(tmp, { force: true }).catch(() => {})
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
return {
|
|
233
|
+
items: staged.map((s) => ({
|
|
234
|
+
file: path.basename(s.abs), path: s.abs,
|
|
235
|
+
changed: s.changed.join(' + '), diary: s.diary, keywords: s.keywords
|
|
236
|
+
}))
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* 写一份(批量写的最小形态)。只改目标区,改完校验。
|
|
242
|
+
* @returns {Promise<{file:string, path:string, changed:string, diary:string, keywords:string}>}
|
|
243
|
+
*/
|
|
244
|
+
export async function writeMemory({ dshHome, cwd, file, keywords, diary }) {
|
|
245
|
+
const { items } = await writeMemories({ dshHome, cwd, items: [{ file, keywords, diary }] })
|
|
246
|
+
return items[0]
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** 本地日期:2026-10-30。和注入行里的日期、用户嘴里的「30 号」是同一个。 */
|
|
250
|
+
export function localDayOf(compactedAt) {
|
|
251
|
+
const d = new Date(compactedAt)
|
|
252
|
+
if (Number.isNaN(d.getTime())) return ''
|
|
253
|
+
const p = (n) => String(n).padStart(2, '0')
|
|
254
|
+
return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate())
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* 按「哪一天的第几份」直接定位到文件,不用搜、不用抄文件名。
|
|
259
|
+
* 同一天按压缩时刻从早到晚数,nth 从 1 起。
|
|
260
|
+
* @returns {Promise<string>} 文件名
|
|
261
|
+
*/
|
|
262
|
+
export async function resolveMemoryByDay({ dshHome, cwd, date, nth }) {
|
|
263
|
+
const day = String(date ?? '').trim()
|
|
264
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) throw new Error('date 要写成 YYYY-MM-DD(本地日期):' + day)
|
|
265
|
+
const { entries } = await listMemories(dshHome, cwd)
|
|
266
|
+
const same = entries
|
|
267
|
+
.filter((e) => e && typeof e.compactedAt === 'string' && localDayOf(e.compactedAt) === day)
|
|
268
|
+
.sort((a, b) => String(a.compactedAt).localeCompare(String(b.compactedAt)))
|
|
269
|
+
if (same.length === 0) {
|
|
270
|
+
const days = [...new Set(entries.map((e) => localDayOf(e.compactedAt)).filter(Boolean))].sort()
|
|
271
|
+
throw new Error('这一天没有回顾:' + day + (days.length > 0 ? '(有回顾的日期:' + days.join('、') + ')' : '(这个工作区还没有任何回顾)'))
|
|
272
|
+
}
|
|
273
|
+
if (nth > same.length) {
|
|
274
|
+
throw new Error('这一天只有 ' + same.length + ' 份:' + day + ' 没有第 ' + nth + ' 份')
|
|
275
|
+
}
|
|
276
|
+
return same[nth - 1].file
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** 列出本工作区的回顾(给工具和设置页用)。 */
|
|
280
|
+
export async function listMemories(dshHome, cwd) {
|
|
281
|
+
const dir = memoryDir(dshHome, cwd)
|
|
282
|
+
const data = await readAssembly(dir, cwd)
|
|
283
|
+
return { dir, entries: data.entries }
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** 读工具的入参校验:一个线索(need),可选跳过清单与跨区许可。 */
|
|
287
|
+
function validateReadArgs(args) {
|
|
288
|
+
if (args === null || typeof args !== 'object' || Array.isArray(args)) throw new Error('参数必须是对象')
|
|
289
|
+
if (typeof args.need !== 'string' || args.need.trim() === '') {
|
|
290
|
+
throw new Error('need 不能为空:用一句话说清你在找什么')
|
|
291
|
+
}
|
|
292
|
+
if (args.skip !== undefined && (!Array.isArray(args.skip) || args.skip.some((s) => typeof s !== 'string'))) {
|
|
293
|
+
throw new Error('skip 必须是字符串数组(已经读过的回顾文件名)')
|
|
294
|
+
}
|
|
295
|
+
if (args.allowOuter !== undefined && typeof args.allowOuter !== 'boolean') {
|
|
296
|
+
throw new Error('allowOuter 必须是布尔值(用户允许才能搜索其他工作区)')
|
|
297
|
+
}
|
|
298
|
+
if (args.query !== undefined || args.file !== undefined) {
|
|
299
|
+
throw new Error('这个工具只收 need(可选 skip / allowOuter):要看某一份的原文用 ' + WRITE_TOOL_NAME)
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** 定位校验:file 或者(date + 可选 nth)二选一。单份与批量里的一项共用。 */
|
|
304
|
+
function validatePosition(args, where = '') {
|
|
305
|
+
const hasFile = typeof args.file === 'string' && args.file.trim() !== ''
|
|
306
|
+
const hasDate = args.date !== undefined
|
|
307
|
+
if (hasFile && hasDate) throw new Error(where + 'file 与 date 只能给一个:给了 file 就不用再给 date / nth')
|
|
308
|
+
if (!hasFile && !hasDate) throw new Error(where + '要么给 file,要么给 date(默认那天的第 1 份)来定位哪一份回顾')
|
|
309
|
+
if (hasDate && !/^\d{4}-\d{2}-\d{2}$/.test(String(args.date).trim())) {
|
|
310
|
+
throw new Error(where + 'date 要写成 YYYY-MM-DD(本地日期):' + String(args.date))
|
|
311
|
+
}
|
|
312
|
+
if (args.date === undefined && args.nth !== undefined) {
|
|
313
|
+
throw new Error(where + 'nth 要配 date 一起用:date 是哪天,nth 是那天第几份(从 1 起)')
|
|
314
|
+
}
|
|
315
|
+
if (args.nth !== undefined && (!Number.isInteger(args.nth) || args.nth < 1)) {
|
|
316
|
+
throw new Error(where + 'nth 必须是 1 起的整数(那天的第几份,按压缩时刻从早到晚)')
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** 批量里的一项:定位 + 至少要写 keywords 或 diary。 */
|
|
321
|
+
function validateWriteItem(item, idx) {
|
|
322
|
+
const where = 'writes[' + idx + ']:'
|
|
323
|
+
if (item === null || typeof item !== 'object' || Array.isArray(item)) throw new Error(where + '必须是对象')
|
|
324
|
+
validatePosition(item, where)
|
|
325
|
+
if (item.keywords !== undefined && !Array.isArray(item.keywords)) throw new Error(where + 'keywords 必须是字符串数组')
|
|
326
|
+
if (item.diary !== undefined && typeof item.diary !== 'string') throw new Error(where + 'diary 必须是字符串')
|
|
327
|
+
if (item.keywords === undefined && item.diary === undefined) throw new Error(where + '至少要给 keywords 或 diary 一项')
|
|
328
|
+
if (item.query !== undefined) throw new Error('搜索请用 ' + READ_TOOL_NAME)
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* 写工具的入参校验:
|
|
333
|
+
* - 单份:file 或 date+nth 定位;不给 keywords/diary 就是读原文;两项可以一起给。
|
|
334
|
+
* - 批量:writes 数组,每一项自带定位与要写的内容;不能再混顶层定位。
|
|
335
|
+
*/
|
|
336
|
+
function validateWriteArgs(args) {
|
|
337
|
+
if (args === null || typeof args !== 'object' || Array.isArray(args)) throw new Error('参数必须是对象')
|
|
338
|
+
if (args.writes !== undefined) {
|
|
339
|
+
if (!Array.isArray(args.writes)) throw new Error('writes 必须是数组(一份一项)')
|
|
340
|
+
if (args.writes.length === 0) throw new Error('writes 不能是空数组')
|
|
341
|
+
for (const key of ['file', 'date', 'nth', 'keywords', 'diary']) {
|
|
342
|
+
if (args[key] !== undefined) throw new Error('给了 writes 就别再给顶层 ' + key + ':每一项都放进 writes 里')
|
|
343
|
+
}
|
|
344
|
+
args.writes.forEach((item, i) => validateWriteItem(item, i))
|
|
345
|
+
return
|
|
346
|
+
}
|
|
347
|
+
validatePosition(args)
|
|
348
|
+
if (args.query !== undefined) throw new Error('搜索请用 ' + READ_TOOL_NAME)
|
|
349
|
+
if (args.keywords !== undefined && !Array.isArray(args.keywords)) throw new Error('keywords 必须是字符串数组')
|
|
350
|
+
if (args.diary !== undefined && typeof args.diary !== 'string') throw new Error('diary 必须是字符串')
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/** 命中在哪一轮、在哪一层工作区,说人话。 */
|
|
354
|
+
const LEVEL_LABEL = { keywords: '关键词', sum: '摘要', body: '原文' }
|
|
355
|
+
const WHERE_LABEL = { self: '本工作区', child: '子工作区', sibling: '平级工作区', outer: '上级/外圈' }
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* 读工具定义(直接给 ctx.tools.register 用)。一次只交给模型一条命中的回顾。
|
|
359
|
+
* @param {{dshHome:string, onHit?:Function}} options
|
|
360
|
+
* @returns {object}
|
|
361
|
+
*/
|
|
362
|
+
export function buildReadToolDefinition({ dshHome, onHit }) {
|
|
363
|
+
return {
|
|
364
|
+
name: READ_TOOL_NAME,
|
|
365
|
+
description: [
|
|
366
|
+
'Use when the load shows only a file name, or the user says you misremembered: give one clue, not the whole question.',
|
|
367
|
+
'Returns one memory per call; child workspaces are searched too. Pass skip for the next, stop once one fits.',
|
|
368
|
+
'Only this workspace\'s memories count toward depth; siblings and parents need allowOuter.',
|
|
369
|
+
'If nothing fits, say you did not recall it.'
|
|
370
|
+
].join(' '),
|
|
371
|
+
parameters: {
|
|
372
|
+
type: 'object',
|
|
373
|
+
additionalProperties: false,
|
|
374
|
+
required: ['need'],
|
|
375
|
+
properties: {
|
|
376
|
+
need: { type: 'string', description: 'Clue in your own words (what the user said).' },
|
|
377
|
+
skip: { type: 'array', items: { type: 'string' }, description: 'Files already read.' },
|
|
378
|
+
allowOuter: { type: 'boolean', description: 'Also search sibling/parent workspaces (needs user permission).' }
|
|
379
|
+
}
|
|
380
|
+
},
|
|
381
|
+
output: {
|
|
382
|
+
schema: {
|
|
383
|
+
type: 'object',
|
|
384
|
+
additionalProperties: false,
|
|
385
|
+
required: ['mode'],
|
|
386
|
+
properties: {
|
|
387
|
+
mode: { type: 'string', enum: ['read', 'exhausted'] },
|
|
388
|
+
file: { type: 'string' },
|
|
389
|
+
workspace: { type: 'string' },
|
|
390
|
+
level: { type: 'string' },
|
|
391
|
+
remaining: { type: 'number' },
|
|
392
|
+
text: { type: 'string' }
|
|
393
|
+
}
|
|
394
|
+
},
|
|
395
|
+
render: (_args, value) => [{ type: 'text', text: value.text ?? '' }]
|
|
396
|
+
},
|
|
397
|
+
async execute(args, exec) {
|
|
398
|
+
validateReadArgs(args)
|
|
399
|
+
const cwd = exec?.agent?.session?.header?.cwd
|
|
400
|
+
if (typeof cwd !== 'string' || cwd === '') throw new Error(READ_TOOL_NAME + ' 需要知道当前工作区')
|
|
401
|
+
const allowOuter = args.allowOuter === true
|
|
402
|
+
const skip = new Set((args.skip ?? []).map((s) => String(s)))
|
|
403
|
+
const picked = await listCandidates({ dshHome, cwd, need: args.need, allowOuter })
|
|
404
|
+
const rest = picked.candidates.filter((c) => !skip.has(c.file) &&
|
|
405
|
+
!skip.has(c.workspace + '|' + c.file) && !skip.has(c.workspace + '\\' + c.file))
|
|
406
|
+
if (rest.length === 0) {
|
|
407
|
+
return exhausted({ need: args.need.trim(), allowOuter, blocked: picked.blocked, read: picked.candidates.length })
|
|
408
|
+
}
|
|
409
|
+
const one = rest[0]
|
|
410
|
+
// 深度只认「本工作区自己」那一份被读出去(子级/平级/上级只读、不计)
|
|
411
|
+
if (one.local === true && typeof onHit === 'function') {
|
|
412
|
+
await onHit({ local: true, workspace: cwd, hitCount: 1, hits: [{ file: one.file }] })
|
|
413
|
+
}
|
|
414
|
+
const text = [
|
|
415
|
+
'读到 ' + one.file + '(' + (WHERE_LABEL[one.scope] || one.scope) + ')· 命中「' + (LEVEL_LABEL[one.level] || one.level) + '」',
|
|
416
|
+
'还有 ' + (rest.length - 1) + ' 条没读;这条不对,就把它放进 skip 再调一次。',
|
|
417
|
+
'',
|
|
418
|
+
one.content
|
|
419
|
+
].join('\n')
|
|
420
|
+
return {
|
|
421
|
+
mode: 'read', file: one.file, workspace: one.workspace,
|
|
422
|
+
level: one.level, remaining: rest.length - 1, text
|
|
423
|
+
}
|
|
424
|
+
},
|
|
425
|
+
presentCall: (args) => ({
|
|
426
|
+
card: 'generic',
|
|
427
|
+
title: 'Recall memory',
|
|
428
|
+
kind: 'other',
|
|
429
|
+
rawInput: args && args.need
|
|
430
|
+
})
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/** 读完了:没找到就明说,并给出下一步(换说法 / 问许可)。 */
|
|
435
|
+
function exhausted({ need, allowOuter, blocked, read }) {
|
|
436
|
+
const lines = []
|
|
437
|
+
if (read === 0) lines.push('这个范围里没有一条回顾提到「' + need + '」。')
|
|
438
|
+
else lines.push('这个范围里的 ' + read + ' 条都读过了,没有更符合的。')
|
|
439
|
+
if (!allowOuter && blocked > 0) {
|
|
440
|
+
lines.push('外圈还有 ' + blocked + ' 份回顾没看,但要用户点头才能搜。')
|
|
441
|
+
lines.push('先告诉用户你没想起来或没记清,请他换个说法;他还坚持的话,再问他能不能搜其他工作区。')
|
|
442
|
+
} else {
|
|
443
|
+
lines.push('先告诉用户你没想起来或没记清,请他换个说法再试。')
|
|
444
|
+
}
|
|
445
|
+
return { mode: 'exhausted', file: '', workspace: '', level: '', remaining: 0, text: lines.join('\n') }
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* 写工具定义:只给 file 就是读这一份的原文,给 keywords / diary 就是写。
|
|
450
|
+
* @param {{dshHome:string}} options
|
|
451
|
+
* @returns {object}
|
|
452
|
+
*/
|
|
453
|
+
export function buildWriteToolDefinition({ dshHome }) {
|
|
454
|
+
return {
|
|
455
|
+
name: WRITE_TOOL_NAME,
|
|
456
|
+
description: [
|
|
457
|
+
'Read or write one memory\'s annotation.',
|
|
458
|
+
'- Locator only (file, or date + nth): returns that memory\'s original text, dialogue only, tool calls stripped.',
|
|
459
|
+
'- Write one: file + keywords and/or diary. Write many: writes[], one call finishes every file, all-or-nothing.',
|
|
460
|
+
'- "The first one on the 30th" is date + nth 1; nth counts by compaction time.',
|
|
461
|
+
'Never changes depth — that belongs to ' + READ_TOOL_NAME + '.'
|
|
462
|
+
].join(' '),
|
|
463
|
+
parameters: {
|
|
464
|
+
type: 'object',
|
|
465
|
+
additionalProperties: false,
|
|
466
|
+
properties: {
|
|
467
|
+
file: { type: 'string', description: 'Memory file name (in this workspace).' },
|
|
468
|
+
date: { type: 'string', description: 'Local date YYYY-MM-DD; use instead of file to locate by day.' },
|
|
469
|
+
nth: { type: 'integer', description: 'Which memory of that date: 1 = earliest compaction. Defaults to 1.' },
|
|
470
|
+
keywords: { type: 'array', items: { type: 'string' }, description: 'Keywords, summarized from the original (not edited down from the diary); must use fewer tokens than the diary. No count limit.' },
|
|
471
|
+
diary: { type: 'string', description: 'Writes the diary section; a diary longer than the summary is rejected.' },
|
|
472
|
+
writes: {
|
|
473
|
+
type: 'array',
|
|
474
|
+
description: 'Batch write: one entry per memory, addressed by file or date+nth, each carrying keywords and/or diary. Prefer this to finish every file in one call.',
|
|
475
|
+
items: {
|
|
476
|
+
type: 'object',
|
|
477
|
+
additionalProperties: false,
|
|
478
|
+
properties: {
|
|
479
|
+
file: { type: 'string', description: 'Memory file name (in this workspace).' },
|
|
480
|
+
date: { type: 'string', description: 'Local date YYYY-MM-DD; use instead of file.' },
|
|
481
|
+
nth: { type: 'integer', description: 'Which memory of that date (defaults to 1).' },
|
|
482
|
+
keywords: { type: 'array', items: { type: 'string' }, description: 'Keywords for this memory.' },
|
|
483
|
+
diary: { type: 'string', description: 'Diary for this memory.' }
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
},
|
|
489
|
+
output: {
|
|
490
|
+
schema: {
|
|
491
|
+
type: 'object',
|
|
492
|
+
additionalProperties: false,
|
|
493
|
+
required: ['mode'],
|
|
494
|
+
properties: {
|
|
495
|
+
file: { type: 'string' },
|
|
496
|
+
path: { type: 'string' },
|
|
497
|
+
mode: { type: 'string', enum: ['read', 'write'] },
|
|
498
|
+
text: { type: 'string' },
|
|
499
|
+
changed: { type: 'string' },
|
|
500
|
+
diary: { type: 'string' },
|
|
501
|
+
keywords: { type: 'string' },
|
|
502
|
+
items: {
|
|
503
|
+
type: 'array',
|
|
504
|
+
items: {
|
|
505
|
+
type: 'object',
|
|
506
|
+
additionalProperties: false,
|
|
507
|
+
properties: {
|
|
508
|
+
file: { type: 'string' },
|
|
509
|
+
path: { type: 'string' },
|
|
510
|
+
changed: { type: 'string' },
|
|
511
|
+
diary: { type: 'string' },
|
|
512
|
+
keywords: { type: 'string' }
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
},
|
|
518
|
+
render: (_args, value) => {
|
|
519
|
+
if (value.mode === 'read') {
|
|
520
|
+
return [{
|
|
521
|
+
type: 'text',
|
|
522
|
+
text: '原文(只含对话,不含工具调用)· ' + value.file + '(' + (value.path ?? '') + ')\n\n' + (value.text ?? '')
|
|
523
|
+
}]
|
|
524
|
+
}
|
|
525
|
+
if (Array.isArray(value.items) && value.items.length > 0) {
|
|
526
|
+
return [{
|
|
527
|
+
type: 'text',
|
|
528
|
+
text: '已更新 ' + value.items.length + ' 份:\n' + value.items
|
|
529
|
+
.map((it) => '· ' + it.file + ':' + it.changed +
|
|
530
|
+
(typeof it.diary === 'string' && it.diary !== '' ? '\n 日记现在是:\n ' + it.diary : '') +
|
|
531
|
+
(typeof it.keywords === 'string' && it.keywords !== '' ? '\n 关键词现在是:' + it.keywords : ''))
|
|
532
|
+
.join('\n')
|
|
533
|
+
}]
|
|
534
|
+
}
|
|
535
|
+
return [{
|
|
536
|
+
type: 'text',
|
|
537
|
+
text: '已更新 ' + value.file + '(' + (value.path ?? '') + '):' + value.changed +
|
|
538
|
+
(typeof value.diary === 'string' && value.diary !== '' ? '\n\n日记现在是:\n' + value.diary : '') +
|
|
539
|
+
(typeof value.keywords === 'string' && value.keywords !== '' ? '\n关键词现在是:' + value.keywords : '')
|
|
540
|
+
}]
|
|
541
|
+
}
|
|
542
|
+
},
|
|
543
|
+
async execute(args, exec) {
|
|
544
|
+
validateWriteArgs(args)
|
|
545
|
+
const cwd = exec?.agent?.session?.header?.cwd
|
|
546
|
+
if (typeof cwd !== 'string' || cwd === '') throw new Error(WRITE_TOOL_NAME + ' 需要知道当前工作区')
|
|
547
|
+
|
|
548
|
+
// 批量:每一项先定位(date 翻成文件名),再一起交给 writeMemories——全部合格才落盘。
|
|
549
|
+
if (Array.isArray(args.writes)) {
|
|
550
|
+
const items = []
|
|
551
|
+
for (const it of args.writes) {
|
|
552
|
+
const file = typeof it.file === 'string' && it.file.trim() !== ''
|
|
553
|
+
? it.file
|
|
554
|
+
: await resolveMemoryByDay({
|
|
555
|
+
dshHome, cwd,
|
|
556
|
+
date: it.date,
|
|
557
|
+
nth: it.nth === undefined ? 1 : it.nth
|
|
558
|
+
})
|
|
559
|
+
items.push({ file, keywords: it.keywords, diary: it.diary })
|
|
560
|
+
}
|
|
561
|
+
const res = await writeMemories({ dshHome, cwd, items })
|
|
562
|
+
// 把刚写进去的内容回显给模型:它就不用再读一遍文件来确认。
|
|
563
|
+
return {
|
|
564
|
+
mode: 'write',
|
|
565
|
+
items: res.items.map((one) => ({
|
|
566
|
+
file: one.file, path: one.path, changed: one.changed,
|
|
567
|
+
diary: one.changed.includes('日记') ? one.diary : '',
|
|
568
|
+
keywords: one.changed.includes('关键词') ? one.keywords : ''
|
|
569
|
+
}))
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
// 单份:给文件名就直接用;给日期(+第几份)就先翻成文件名,模型不用抄、也不用搜。
|
|
574
|
+
const file = typeof args.file === 'string' && args.file.trim() !== ''
|
|
575
|
+
? args.file
|
|
576
|
+
: await resolveMemoryByDay({
|
|
577
|
+
dshHome, cwd,
|
|
578
|
+
date: args.date,
|
|
579
|
+
nth: args.nth === undefined ? 1 : args.nth
|
|
580
|
+
})
|
|
581
|
+
const wantsWrite = Array.isArray(args.keywords) || typeof args.diary === 'string'
|
|
582
|
+
if (wantsWrite) {
|
|
583
|
+
const res = await writeMemory({ dshHome, cwd, file, keywords: args.keywords, diary: args.diary })
|
|
584
|
+
return {
|
|
585
|
+
file: res.file, path: res.path, mode: 'write', changed: res.changed,
|
|
586
|
+
diary: res.changed.includes('日记') ? res.diary : '',
|
|
587
|
+
keywords: res.changed.includes('关键词') ? res.keywords : ''
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
const res = await readMemorySection({ dshHome, cwd, file })
|
|
591
|
+
return { file: res.file, path: res.path, mode: 'read', text: res.text }
|
|
592
|
+
},
|
|
593
|
+
presentCall: (args) => ({
|
|
594
|
+
card: 'generic',
|
|
595
|
+
title: args && (Array.isArray(args.writes) || args.keywords || args.diary) ? 'Annotate memory' : 'Read memory',
|
|
596
|
+
kind: 'other',
|
|
597
|
+
rawInput: args && (Array.isArray(args.writes)
|
|
598
|
+
? 'writes: ' + args.writes.length
|
|
599
|
+
: (args.file || (args.date ? args.date + ' #' + (args.nth === undefined ? 1 : args.nth) : undefined)))
|
|
600
|
+
})
|
|
601
|
+
}
|
|
602
|
+
}
|