@ssamurias/dsh-fish 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/AGENTS.md +6 -3
  2. package/CHANGELOG.md +572 -368
  3. package/README.md +148 -14
  4. package/RELEASE-NOTES-1.0.0.md +62 -3
  5. package/RELEASE-NOTES-1.0.1.md +363 -0
  6. package/RELEASE-NOTES-1.0.2.md +114 -0
  7. package/THIRD-PARTY-NOTICES.md +13 -3
  8. package/docs/troubleshooting.md +119 -0
  9. package/docs//346/217/222/344/273/266/347/272/246/345/256/232.md +167 -0
  10. package/docs//347/264/240/346/235/220/345/245/221/347/272/246.md +96 -0
  11. package/lib/ask.js +3 -3
  12. package/lib/at.js +4 -2
  13. package/lib/autobackup.js +414 -0
  14. package/lib/backup.js +75 -5
  15. package/lib/bili.js +132 -21
  16. package/lib/browse.js +33 -16
  17. package/lib/capture.js +27 -1
  18. package/lib/client.js +1329 -349
  19. package/lib/cloudbackup.js +352 -0
  20. package/lib/cloudcrypto.js +161 -0
  21. package/lib/clouddrive.js +693 -0
  22. package/lib/cloudsmtp.js +331 -0
  23. package/lib/cloudtargets.js +228 -0
  24. package/lib/comment.js +23 -5
  25. package/lib/contract.js +7 -2
  26. package/lib/deliver.js +4 -1
  27. package/lib/doing.js +316 -0
  28. package/lib/events.js +22 -4
  29. package/lib/firstwake.js +74 -0
  30. package/lib/freewake.js +5 -0
  31. package/lib/generator.js +35 -4
  32. package/lib/handoff.js +166 -0
  33. package/lib/hear.js +102 -7
  34. package/lib/home.js +169 -204
  35. package/lib/identity.js +498 -28
  36. package/lib/index.js +14 -2
  37. package/lib/look.js +37 -3
  38. package/lib/material.js +12 -1
  39. package/lib/note.js +100 -9
  40. package/lib/observe.js +365 -36
  41. package/lib/persona.js +61 -41
  42. package/lib/proactive.js +12 -5
  43. package/lib/recall.js +159 -10
  44. package/lib/report.js +14 -7
  45. package/lib/say.js +10 -2
  46. package/lib/scheduler.js +238 -26
  47. package/lib/schema.js +8 -1
  48. package/lib/scrub.js +105 -4
  49. package/lib/selfcheck.js +13 -1
  50. package/lib/selfdoc.js +170 -12
  51. package/lib/selfpronoun.js +112 -0
  52. package/lib/selfrules.js +50 -0
  53. package/lib/sessionnote.js +7 -3
  54. package/lib/settings.js +163 -13
  55. package/lib/status.js +16 -8
  56. package/lib/sub.js +42 -5
  57. package/lib/turnexport.js +123 -0
  58. package/lib/turns.js +102 -10
  59. package/lib/video.js +1 -1
  60. package/lib/voices.js +24 -1
  61. package/media/principle-drive.svg +131 -0
  62. package/media/principle-loop.svg +3 -3
  63. package/media/principle-memory.svg +1 -1
  64. package/package.json +2 -1
package/lib/identity.js CHANGED
@@ -24,22 +24,121 @@
24
24
  * - 只挂在她那个 agent 上(判据 herDir == 会话 cwd),不影响用户自己的会话。
25
25
  */
26
26
 
27
- import { existsSync, readFileSync, statSync } from 'node:fs'
28
- import { selfDocPath } from './selfdoc.js'
27
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
28
+ import { selfDocPath, catalogOf } from './selfdoc.js'
29
29
  import { fillOwner, pronounFor } from './pronoun.js'
30
- import { cwdOf, foldedRecallNote, isHerHome, toolSurfaceFor } from './restrict.js'
30
+ import { cwdOf, foldedRecallNote, isHerHome, toolSurfaceFor, visibleToolsOf } from './restrict.js'
31
+ import { paths } from './store.js'
32
+ import { notesPath } from './note.js'
33
+ import { appointPath } from './appoint.js'
31
34
  import { activeOutingSync, bindOutingSession } from './outing.js'
32
35
  import { attachStreamScrub } from './scrub.js'
33
36
  import { deliverQueued } from './sessionnote.js'
37
+ import { handoffArmed, handoffTextSync } from './handoff.js'
34
38
 
35
39
  /** 段名与顺序:放在宿主自己的段之后、`complete` 段之前(order 越大越靠后)。 */
36
40
  export const IDENTITY_SECTION = 'fish:identity'
37
41
  export const IDENTITY_ORDER = 8500
38
42
 
43
+ /**
44
+ * 「上次停在这」交接页(2026-11-15,用户 m01722)。
45
+ *
46
+ * 为什么要单独一段:换窗口带走的那几轮原话,原来写进身份文档(`carry`),
47
+ * 到 3 天/8 轮才消失——她每轮都在念「上次我们说到这」,像放着一份旧稿。
48
+ * 用户明确说过「只能换房的时候出现一次,不能一直出现」。
49
+ *
50
+ * 现在:轮换或认领新窗口时生成,存在 home.json 的 `carry` 里;他换窗口后
51
+ * 第一次开口,这一段才挂上;那一轮结完就撤(turns.js 的 settle)。
52
+ * order 8450 落在身份段(8500)之前——先让他看见她,再说上次停在哪。
53
+ */
54
+ export const HANDOFF_SECTION = 'fish:handoff'
55
+ export const HANDOFF_ORDER = 8450
56
+
39
57
  /** 「手边有什么」段(2026-10-29,用户 m01276):收不窄的工具靠提示词说清。 */
40
58
  export const TOOLS_SECTION = 'fish:tools'
41
59
  export const TOOLS_ORDER = 8600
42
60
 
61
+ /**
62
+ * 「本子上记着什么」目录段(2026-11-14,用户 m00533 的 ③;同日第二轮收窄)。
63
+ *
64
+ * 为什么要有:她的记忆分三层——事件流、便条/约定、日记。前两者**故意不进事件流**
65
+ * (会污染 derive 的计数),于是换会话重建认知时她连「本子上还记着东西」都不知道,
66
+ * 翻不到就当没有。这一段只说**有哪些东西可翻**,不报条数、不报内容。
67
+ *
68
+ * 为什么一个数字都不报:note.js / appoint.js 从第一天起的硬约束是「不吃状态——
69
+ * 不许变成『你还有 3 条未完成』」。原来这一版写成「便条 N 张(还没收尾 M 张)」,
70
+ * 正好是那条禁令的形态,且每轮都在;数字全部去掉,只留入口。
71
+ *
72
+ * 为什么单开一段、且排到最后(用户点名的要求):内容会变(记了张新便条就变),
73
+ * 而 system prompt 的缓存命中是按**前缀**算的。挂在最末,变化只让这一段自己失效,
74
+ * 前面几千字的身份段、工具段照旧命中缓存。
75
+ */
76
+ export const CATALOG_SECTION = 'fish:catalog'
77
+ export const CATALOG_ORDER = 9500
78
+
79
+ /** 目录段正文的缓存:按三处目录/文件的 mtime+size 失效,避免每轮都读盘。 */
80
+ const CATALOG_CACHE = new Map()
81
+
82
+ /** 同步读一份 JSON 数组;读不到/形状不对就是空数组(目录少一行,不崩)。 */
83
+ function readArraySync(file) {
84
+ try {
85
+ const raw = JSON.parse(readFileSync(file, 'utf8'))
86
+ return Array.isArray(raw) ? raw : []
87
+ } catch {
88
+ return []
89
+ }
90
+ }
91
+
92
+ /** 同步数日记篇数;目录不在就当 0。 */
93
+ function diaryCountSync(dir) {
94
+ try {
95
+ return readdirSync(dir).filter((f) => /^\d{4}-\d{2}-\d{2}\.md$/.test(f)).length
96
+ } catch {
97
+ return 0
98
+ }
99
+ }
100
+
101
+ /**
102
+ * 目录段的正文。`text()` 是同步求值、不能 await(同 identityOfTurn 那条理由),
103
+ * 所以这里直接同步读三处;host 每轮组装提示词都会调,用 mtime+size 兜一层。
104
+ */
105
+ export function catalogText(root) {
106
+ const files = [notesPath(root), appointPath(root)]
107
+ const diaryDir = paths(root).diaryDir
108
+ const stamp = [
109
+ ...files.map((f) => {
110
+ try {
111
+ const s = statSync(f)
112
+ return `${s.mtimeMs}:${s.size}`
113
+ } catch {
114
+ return '-'
115
+ }
116
+ }),
117
+ (() => {
118
+ try {
119
+ const s = statSync(diaryDir)
120
+ return `${s.mtimeMs}:${s.size}`
121
+ } catch {
122
+ return '-'
123
+ }
124
+ })(),
125
+ ].join('|')
126
+ const hit = CATALOG_CACHE.get(root)
127
+ if (hit && hit.stamp === stamp) return hit.text
128
+ const text = fillOwner(
129
+ catalogOf({
130
+ notes: readArraySync(files[0]),
131
+ appointments: readArraySync(files[1]),
132
+ diaryCount: diaryCountSync(diaryDir),
133
+ }),
134
+ pronounFor(root),
135
+ )
136
+ // 只有几条会话的 root,条目不会涨;还是兜个上限,出门那条用完就丢。
137
+ if (CATALOG_CACHE.size > 8) CATALOG_CACHE.clear()
138
+ CATALOG_CACHE.set(root, { stamp, text })
139
+ return text
140
+ }
141
+
43
142
  /**
44
143
  * 「这一次的处境」段(2026-10-25 晚)。
45
144
  *
@@ -56,15 +155,34 @@ export const TOOLS_ORDER = 8600
56
155
  * 免得他之后主动聊天时她还带着上一次的「此刻处境」。
57
156
  */
58
157
  export const WAKE_SECTION = 'fish:wake'
59
- export const WAKE_ORDER = 8700
158
+ /**
159
+ * 处境的顺序(2026-11-14,用户 m03077)。
160
+ *
161
+ * 原来是 8700,排在 `fish:beliefs`(9000)前面。可处境是**每醒一次就换一份**的:
162
+ * 时间、距上次多久、最近几条事件都不同。它一变,后面那 3,000 字左右的信念段
163
+ * (她自己说过的话 / 读到的一句话 / 被打脸过 / 对自己的说法 / 我做过的事)
164
+ * 就跟着重算——一次自主醒,白付三成提示词。
165
+ *
166
+ * 挪到 9250:在信念(9000)之后、指纹账本的基准(9400)之前。这样醒一次只有
167
+ * 处境自己那一千多字是新的,信念段还能命中前缀缓存;账本挪来的外来段仍排在最后。
168
+ * 语义上也更顺:她读到最后才是「此刻」。
169
+ */
170
+ export const WAKE_ORDER = 9250
60
171
 
61
172
  /**
62
173
  * 「这一刻会变的那几段」段(0.8.10,用户 m00315)。
63
174
  *
64
- * 她自己的身份文档里,有四段是逐轮、逐天都在变的:她自己说过的话、读到的一句话、
65
- * 被打脸过、对自己的说法。它们原来夹在身份正文中间(靠前),一变,后面整条提示词的
66
- * 前缀缓存就作废——实测她那次唤醒 25,832 字符的提示词里,这四段合计约 1,442 字符,
67
- * 位置却在第 22 行附近。
175
+ * 她自己的身份文档里,有五段是逐轮、逐天、**每用完一次工具**都在变的:她自己说过的话、
176
+ * 读到的一句话、被打脸过、对自己的说法,以及「我做过的事」(履历是从 `use:` 账现算的,
177
+ * 她用一次 bili_look、写一张便条,这一节就多一行)。
178
+ *
179
+ * 它们原来夹在身份正文中间(靠前),一变,后面整条提示词的前缀缓存就作废:
180
+ * - 0.8.10 实测:那次唤醒 25,832 字符的提示词里,那四段合计约 1,442 字符,
181
+ * 位置却在第 22 行附近。
182
+ * - 2026-11-14 复测(用户 m02511 问「要不要再挪」):连续 12 轮的 system prompt 逐节 diff,
183
+ * `## 我做过的事` 在 79→80、82→83、83→84、85→86、86→87、89→90 这几对里都变了
184
+ * (1,485→1,558→1,594→1,584→1,564),每次变都把她后面近 20,000 字符的缓存带掉;
185
+ * `## 现在`/`## 你是谁` 里的天数一天变一次,代价可以忽略,不动。
68
186
  *
69
187
  * 所以 `reorderForHer` 把它们从身份正文里剪出来,单列一段挂到最后(order 9000):
70
188
  * 内容一个字不少,只是排到了所有稳定内容之后。变的永远是尾巴。
@@ -72,14 +190,82 @@ export const WAKE_ORDER = 8700
72
190
  export const BELIEFS_SECTION = 'fish:beliefs'
73
191
  export const BELIEFS_ORDER = 9000
74
192
 
75
- /** 这四段的标题(`## ` 开头,按前缀认;正文里的括号补充说明不影响匹配)。 */
193
+ /** 这几段的标题(`## ` 开头,按前缀认;正文里的括号补充说明不影响匹配)。 */
76
194
  const VOLATILE_HEADINGS = [
77
195
  '## 你自己说过的话',
78
196
  '## 你读到的一句话',
79
197
  '## 你被打脸过',
80
198
  '## 你对自己的说法',
199
+ // 2026-11-14(用户 m02511):履历从 `use:` 账现算,她每用一次工具就多一行/换一行,
200
+ // 却是她身份最靠前的一段——留下来会把她后面整条提示词每轮都带掉。
201
+ '## 我做过的事',
81
202
  ]
82
203
 
204
+ /**
205
+ * 别人的记忆插件塞进她提示词里的那几段(2026-11-14,用户 m02622)。
206
+ *
207
+ * 她有自己的记法:`events.jsonl` + `her_recall`,加上身份文档里那几段。
208
+ * evolve 和 auto-memory 是给「帮他干活」的 agent 用的:它们往系统提示词里塞
209
+ * 工作区记忆索引(`evolve:memory-index`)和「记忆系统固定纪律」(`dsh:auto-memory-pre-rules`),
210
+ * 还会把一段 `<memory_system>` 挂成 systemPrompt.context——渲染出来是历史尾巴上
211
+ * 一条 user 消息(`dsh:auto-memory-pre`)。在她房间里,那两套规矩和她自己的记法打架:
212
+ * 她会去调自己根本拿不到的工具(memory_log / evolve_write),也会把「按工作区记忆」
213
+ * 当成本能,而不是「记住他说过的话」。
214
+ *
215
+ * 开关是 config 的 `prompt.quietForeignMemory`(默认关):
216
+ * - 只在她自己的房间(`isHerHome`)生效,绝不碰他本人在别的会话里的自动记忆;
217
+ * - 默认关是为了不替别人改环境——谁想让自家鱼少读点别人的规矩,自己打开。
218
+ */
219
+ export const QUIET_FOREIGN_KEY = 'prompt.quietForeignMemory'
220
+ const FOREIGN_MEMORY_SECTIONS = new Set(['evolve:memory-index', 'dsh:auto-memory-pre-rules'])
221
+ const FOREIGN_MEMORY_CONTEXTS = new Set(['dsh:auto-memory-pre'])
222
+
223
+ /** config 的 mtime 缓存:组装是每轮每步都跑的,不能每回读盘。 */
224
+ let prefCache = { file: '', mtime: -1, value: { quietForeignMemory: false, orderVolatileSections: true } }
225
+
226
+ /**
227
+ * 这个工作区的提示词偏好(`config.prompt`)。
228
+ *
229
+ * 读不出来(没装、还没写、JSON 坏了)一律按默认:少读别人的记忆规矩**关**、
230
+ * 会变动的段挪到末尾**开**。前者宁可不摘,后者只换位置、不改字,坏了也不至于让她读不到东西。
231
+ *
232
+ * @param {string} root
233
+ * @returns {{quietForeignMemory: boolean, orderVolatileSections: boolean}}
234
+ */
235
+ export function promptPrefs(root) {
236
+ const dflt = { quietForeignMemory: false, orderVolatileSections: true }
237
+ if (!root) return dflt
238
+ try {
239
+ const file = paths(root).config
240
+ const st = statSync(file)
241
+ if (prefCache.file === file && prefCache.mtime === st.mtimeMs) return prefCache.value
242
+ const raw = readFileSync(file, 'utf8')
243
+ const cfg = raw ? JSON.parse(raw) : {}
244
+ const p = cfg?.prompt ?? {}
245
+ const value = {
246
+ quietForeignMemory: p.quietForeignMemory === true,
247
+ // 默认开:只看「这段内容这两轮是不是不一样」,不改、不删任何字。
248
+ orderVolatileSections: p.orderVolatileSections !== false,
249
+ }
250
+ prefCache = { file, mtime: st.mtimeMs, value }
251
+ return value
252
+ } catch {
253
+ return dflt
254
+ }
255
+ }
256
+
257
+ /**
258
+ * 这个工作区打开了「少读别人的记忆规矩」吗。
259
+ *
260
+ * 读不出来(没装、还没写、JSON 坏了)一律当关:宁可多读一段,也不要替他关掉什么。
261
+ *
262
+ * @param {string} root
263
+ * @returns {boolean}
264
+ */
265
+ export function quietForeignMemory(root) {
266
+ return promptPrefs(root).quietForeignMemory
267
+ }
268
+
83
269
  /**
84
270
  * 宿主那两个段的名字(0.8.5,issue #14 后续 + 用户 m01579 拍板 B 案)。
85
271
  *
@@ -134,23 +320,25 @@ export const TOOL_DOC_MIN_NAMES = 3
134
320
  /** 一段至少这么长,才值得拿工具表去对(短段省不下几个字,还容易误伤)。 */
135
321
  export const TOOL_DOC_MIN_CHARS = 400
136
322
 
137
- let lastTrim = { dropped: [], saved: 0 }
323
+ let lastTrim = { dropped: [], saved: 0, skipped: '' }
324
+
325
+ /** 上一次「别人的记忆插件」摘了几段(排查用,不参与判断)。 */
326
+ let lastQuiet = 0
138
327
 
139
328
  /** 上一次摘段的结果(给自检/tools 用,不参与判断)。 */
140
329
  export function lastTrimReport() {
141
- return { dropped: lastTrim.dropped.slice(), saved: lastTrim.saved }
330
+ return { dropped: lastTrim.dropped.slice(), saved: lastTrim.saved, skipped: lastTrim.skipped ?? '' }
142
331
  }
143
332
 
144
333
  // 同一种摘法只记一次日志:她每一轮都会走这条链,逐轮刷屏没有意义。
145
334
  let loggedTrimKey = ''
146
335
 
147
- function logTrimOnce(dropped, saved, log) {
336
+ function logTrimOnce(dropped, saved, log, message) {
148
337
  if (typeof log !== 'function') return
149
- const key = `${dropped.map((d) => d.name).join(',')}|${saved}`
338
+ const key = message ?? `${dropped.map((d) => d.name).join(',')}|${saved}`
150
339
  if (key === loggedTrimKey) return
151
340
  loggedTrimKey = key
152
- const names = dropped.map((d) => d.name).join('、')
153
- log(`[dsh-fish] 摘掉了 ${dropped.length} 段讲别的工具的提示词(省 ${saved} 字符):${names}`)
341
+ log(message ?? `[dsh-fish] 摘掉了 ${dropped.length} 段讲别的工具的提示词(省 ${saved} 字符):${dropped.map((d) => d.name).join('、')}`)
154
342
  }
155
343
 
156
344
  /** 从一段文字里挑出「像工具名」的词(去重)。 */
@@ -175,32 +363,137 @@ export function toolNamesIn(text) {
175
363
  * @param {object} assembly 宿主组装出来的 PromptAssembly(就地改 sections)
176
364
  * @returns {object} 同一个对象
177
365
  */
178
- export function trimToolDocs(assembly, { log } = {}) {
366
+ // 2026-11-14(随公开包发布前加固):名字认得出、内容也确认是「讲别的插件 / 她没有的
367
+ // 工具」的段。**只认名字是不够的**——宿主升级可能改文案,甚至把同名段挪作他用;所以
368
+ // 每条都带一段内容签名,签名对不上就留着(宁可多留,不能误摘)。
369
+ // `needs` 表示「她真拿到这个工具时,这段讲的是她能做的事」,那就留着。
370
+ const HOST_TOOL_SECTIONS = new Map([
371
+ ['tool:beauticode', { sig: /beautiCode 可以把本机图片/ }],
372
+ ['tool:jobs', { sig: /job_output|background job|后台任务/ }],
373
+ ['tool:pwsh', { sig: /\[exit code: N\]|pwsh -Command/ }],
374
+ ['tool:goal', { sig: /create_goal|update_goal|get_goal/ }],
375
+ ['free-search:engines', { sig: /Current mode: |web_search/ }],
376
+ ['genui:fence', { sig: /dsh-ui/ }],
377
+ ['genui:native', { sig: /dsh-ui/ }],
378
+ ['dsh:auto-memory-pre-rules', { sig: /记忆系统|记忆定位/ }],
379
+ ['dsh:auto-memory-pre', { sig: /记忆系统|记忆定位/ }],
380
+ ['dsh:m6-reference-tail-pre', { sig: /hindsight|知识页/ }],
381
+ ['dsh-harness-dev-context', { sig: /DeepSeek Harness implementation checkout|HMR/ }],
382
+ // 同一段运行时说明在有些宿主版本里叫 `dsh-context`:讲的是 checkout 路径、GUI 地址、
383
+ // HMR 怎么开——全是给开发者看的,和她是谁无关(2026-11-14 复核她的提示词时发现)。
384
+ ['dsh-context', { sig: /implementation checkout|client-plugin HMR receiver|Web GUI whose URL/ }],
385
+ // 宿主那句「You are an AI agent powered by DeepSeek Harness.」是产品元信息,
386
+ // 不是她这个人的一部分(2026-11-14 用户要求)。签名钉死原文,宿主改词就留着。
387
+ ['harness:identity', { sig: /^You are an AI agent powered by DeepSeek Harness\./ }],
388
+ // present 的文件引用规则:她手里真有 `present` 时留(needs)。
389
+ ['ui:deliverable-file-references', { sig: /present|file references/i, needs: 'present' }],
390
+ ])
391
+ // 兜底:不管叫什么名字,只要是「用第二人称告诉模型它是什么」的英文身份句,就属于工具性描述,
392
+ // 不该出现在她的人格提示词里(2026-11-14 用户要求:人格养成要尽量少这种话)。
393
+ // 只认这几种开头,避免误伤工具文档里 "You are given ..." 之类。
394
+ const HOST_IDENTITY_CLAUSE = /^You are (?:an? (?:AI|coding) agent|interacting with the user)\b/im
395
+ // 不管上面那张表怎么写,这几段永远留着:她的身份、她的陈述。
396
+ const NEVER_TRIM = new Set([
397
+ 'fish:identity',
398
+ 'fish:tools',
399
+ 'fish:wake',
400
+ 'fish:beliefs',
401
+ 'persona',
402
+ 'deployment:persona-prefix',
403
+ ])
404
+
405
+ /** 段正文:宿主可能把 text 给成 getter。取不到就当空串(空串匹配不上签名 → 不摘)。 */
406
+ function sectionText(section) {
407
+ try {
408
+ const t = typeof section?.text === 'function' ? section.text() : section?.text
409
+ return typeof t === 'string' ? t : ''
410
+ } catch {
411
+ return ''
412
+ }
413
+ }
414
+
415
+ /** 摘完之后至少还得留下这么多字,否则当成「判据出问题了」。 */
416
+ export const TRIM_FLOOR_CHARS = 2000
417
+ /** 一次摘掉超过这个比例,也当成判据出问题(正常最狠的一台机器也只摘 60% 左右)。 */
418
+ const TRIM_MAX_SHARE = 0.75
419
+ /** 提示词本身小于这个数时不做安全闸(小样本多数是测试/特殊宿主,闸会误伤)。 */
420
+ const TRIM_GUARD_MIN_CHARS = 4000
421
+
422
+ /** 公开包里的紧急开关:`DSH_FISH_PROMPT_TRIM=off` 时只排序、一段不摘。 */
423
+ export function trimDisabled() {
424
+ const v = String(process.env.DSH_FISH_PROMPT_TRIM ?? '').toLowerCase()
425
+ return v === '0' || v === 'off' || v === 'false' || v === 'no'
426
+ }
427
+
428
+ export function trimToolDocs(assembly, { log, tools } = {}) {
179
429
  if (!assembly || !Array.isArray(assembly.sections)) return assembly
430
+ if (trimDisabled()) {
431
+ lastTrim = { dropped: [], saved: 0, skipped: 'off' }
432
+ return assembly
433
+ }
434
+ // 2026-11-14:宿主 0.2.x 组装的 `assembly` 里**没有** tools(它是在瀑布返回之后
435
+ // 才挂上去的,见 dsh-system-prompt 的 assemble),所以只看 `assembly.tools`
436
+ // 这里会永远拿到空集、整条判据变成空转。她的工具表改由调用方从
437
+ // `visibleToolsOf(agent)` 传进来;两处取并集,老宿主仍然按老办法工作。
180
438
  const have = new Set(
181
- (Array.isArray(assembly.tools) ? assembly.tools : [])
439
+ [...(Array.isArray(assembly.tools) ? assembly.tools : []), ...(Array.isArray(tools) ? tools : [])]
182
440
  .map((t) => String(typeof t === 'string' ? t : t?.name ?? ''))
183
441
  .filter(Boolean),
184
442
  )
185
443
  if (have.size === 0) {
186
- lastTrim = { dropped: [], saved: 0 }
444
+ // 判不了就不动——这是最重要的一条自保:宁可多读几千字,也不能凭猜摘掉她需要的东西。
445
+ lastTrim = { dropped: [], saved: 0, skipped: 'no-tools' }
187
446
  return assembly
188
447
  }
448
+ const totalChars = assembly.sections.reduce((n, s) => n + sectionText(s).length, 0)
189
449
  const dropped = []
190
450
  let saved = 0
191
451
  const kept = assembly.sections.filter((s) => {
192
452
  const name = String(s?.name ?? '')
193
453
  if (name.startsWith('fish:')) return true
194
- const text = typeof s?.text === 'string' ? s.text : ''
195
- if (text.length < TOOL_DOC_MIN_CHARS) return true
454
+ if (NEVER_TRIM.has(name)) return true
455
+ const text = sectionText(s)
456
+ // 英文身份句(「You are an AI agent …」「You are interacting with the user …」)是
457
+ // 模型/工具视角的自述,不是她的话(2026-11-14 用户要求)。名字不可靠时靠这一条兜住。
458
+ if (HOST_IDENTITY_CLAUSE.test(text)) {
459
+ dropped.push({ name, chars: text.length })
460
+ saved += text.length
461
+ return false
462
+ }
463
+ // 先看她够不够得着:段里提到的工具只要有一个在她手上,这段就是在讲她能做的事,留着。
196
464
  const mentioned = toolNamesIn(text)
197
- if (mentioned.length < TOOL_DOC_MIN_NAMES) return true
198
465
  if (mentioned.some((n) => have.has(n))) return true
466
+ // 名字认得出的「别的插件的工具说明」:还要内容签名对得上。
467
+ const known = HOST_TOOL_SECTIONS.get(name)
468
+ if (known) {
469
+ if (known.needs && have.has(known.needs)) return true
470
+ if (!known.sig.test(text)) return true
471
+ dropped.push({ name, chars: text.length })
472
+ saved += text.length
473
+ return false
474
+ }
475
+ if (text.length < TOOL_DOC_MIN_CHARS) return true
476
+ if (mentioned.length < TOOL_DOC_MIN_NAMES) return true
199
477
  dropped.push({ name, chars: text.length })
200
478
  saved += text.length
201
479
  return false
202
480
  })
203
- lastTrim = { dropped, saved }
481
+ if (dropped.length > 0 && totalChars >= TRIM_GUARD_MIN_CHARS) {
482
+ const left = totalChars - saved
483
+ if (left < TRIM_FLOOR_CHARS || saved > totalChars * TRIM_MAX_SHARE) {
484
+ // 判据算出来要摘掉大半、或几乎不给她留东西:这不是「她没这些工具」,更像判据坏了。
485
+ // 原样放行,并记一次(同样的形态只记一次)。
486
+ lastTrim = { dropped: [], saved: 0, skipped: 'suspicious' }
487
+ logTrimOnce(
488
+ [],
489
+ 0,
490
+ log,
491
+ `[dsh-fish] 一段都没摘:判据算出来要摘 ${dropped.length} 段、省 ${saved} 字,摘完只剩 ${left} 字,太可疑,按原样放行`,
492
+ )
493
+ return assembly
494
+ }
495
+ }
496
+ lastTrim = { dropped, saved, skipped: '' }
204
497
  if (dropped.length > 0) {
205
498
  assembly.sections = kept
206
499
  logTrimOnce(dropped, saved, log)
@@ -238,9 +531,24 @@ export function splitVolatileIdentity(text) {
238
531
  return { stable: keep.join('\n'), volatile: moved.join('\n') }
239
532
  }
240
533
 
241
- export function reorderForHer(assembly, { log } = {}) {
534
+ export function reorderForHer(assembly, { log, tools, quietForeign = false } = {}) {
242
535
  if (!assembly || !Array.isArray(assembly.sections)) return assembly
243
- trimToolDocs(assembly, { log })
536
+ trimToolDocs(assembly, { log, tools })
537
+ if (quietForeign) {
538
+ // 别人的记忆插件在她房间里留的东西:段按名字摘,context 按名字摘(渲染出来是
539
+ // 历史尾巴上那条 <memory_system>)。`required: true` 的照旧留着——宿主自己标了必需。
540
+ const before = assembly.sections.length
541
+ assembly.sections = assembly.sections.filter((s) => !FOREIGN_MEMORY_SECTIONS.has(String(s?.name ?? '')))
542
+ if (Array.isArray(assembly.contexts)) {
543
+ assembly.contexts = assembly.contexts.filter(
544
+ (c) => c?.required === true || !FOREIGN_MEMORY_CONTEXTS.has(String(c?.name ?? '')),
545
+ )
546
+ }
547
+ const gone = before - assembly.sections.length
548
+ lastQuiet = gone
549
+ } else {
550
+ lastQuiet = 0
551
+ }
244
552
  const kept = assembly.sections.filter((s) => String(s?.name ?? '') !== HOST_PERSONA_SECTION)
245
553
  const mine = kept.find((s) => String(s?.name ?? '') === IDENTITY_SECTION)
246
554
  if (!mine) {
@@ -261,6 +569,100 @@ export function reorderForHer(assembly, { log } = {}) {
261
569
  return assembly
262
570
  }
263
571
 
572
+ /* ------------------------------------------------------------------ *
573
+ * 会变的段:自适应地挪到最后(2026-11-14,用户 m02835)
574
+ *
575
+ * 宿主的提示词是按段平铺 join 出来的,缓存按**字节前缀**命中:前面任何一段改一个字,
576
+ * 后面所有段都要重算。所以「谁在变」比「谁重要」更决定缓存。
577
+ *
578
+ * 她是养成型,自己的身份段已经被 splitVolatileIdentity 按标题剪到尾巴;
579
+ * 但别人装的插件(evolve 的记忆索引、auto-memory 的今日日志、别的注入器)
580
+ * 也可能每轮换内容,而且**不同用户装的插件根本不一样**——写死名字没法公开发出去。
581
+ * 于是这里只看行为:同一段连续几轮内容都在变,就把它挪到 beliefs 之后(末尾),
582
+ * 变了也就只影响它自己后面那点尾巴。
583
+ *
584
+ * 三条安全线:
585
+ * 1. 只换位置、不改字:一段内容一个字都不删;
586
+ * 2. 不碰 `fish:*`(她自己的顺序由 reorderForHer 定)和宿主的两个身份段;
587
+ * 3. 判据要「见过至少 3 次、变了至少 2 次」才动手,避免一次抖动就重排。
588
+ * ------------------------------------------------------------------ */
589
+
590
+ /** 每个会话记一本「各段上一轮长什么样」的账,键是会话 id。 */
591
+ const volatileBook = new Map()
592
+ const VOLATILE_BOOK_MAX = 300
593
+ const VOLATILE_MIN_SEEN = 3
594
+ const VOLATILE_MIN_CHANGES = 2
595
+ const VOLATILE_MAX_MOVED = 5
596
+ const VOLATILE_ORDER_BASE = 9400
597
+ /** 顺序有语义、或者本来就放在最前面的段,不参与搬迁。 */
598
+ const VOLATILE_PINNED = new Set(['harness:identity', 'deployment:persona-prefix'])
599
+
600
+ /** FNV-1a,够用就行;只拿来判「这段和上一轮是不是同一段」。 */
601
+ function fnv1a(text) {
602
+ let h = 0x811c9dc5
603
+ for (let i = 0; i < text.length; i += 1) {
604
+ h ^= text.charCodeAt(i)
605
+ h = Math.imul(h, 0x01000193) >>> 0
606
+ }
607
+ return h.toString(16)
608
+ }
609
+
610
+ function sectionHash(text) {
611
+ const s = String(text ?? '')
612
+ const mid = s.length >> 1
613
+ // 只取一处容易漏掉「中间改了、首尾没改」的情况,所以头尾各算一次。
614
+ return `${s.length}:${fnv1a(s)}:${fnv1a(s.slice(mid) + s.slice(0, mid))}`
615
+ }
616
+
617
+ /**
618
+ * 把「一直在变」的外来段挪到最后。只改位置,不改内容。
619
+ *
620
+ * @param {object} assembly 宿主的组装结果(`{ sections, contexts, variables }`)
621
+ * @param {{key?: string, log?: Function}} [opts] `key` 用来区分会话
622
+ * @returns {number} 这次挪了几段(0 表示没动)
623
+ */
624
+ export function reorderVolatile(assembly, { key = 'default', log = null } = {}) {
625
+ const sections = Array.isArray(assembly?.sections) ? assembly.sections : []
626
+ if (sections.length < 2) return 0
627
+ let book = volatileBook.get(key)
628
+ if (!book) {
629
+ if (volatileBook.size >= VOLATILE_BOOK_MAX) volatileBook.delete(volatileBook.keys().next().value)
630
+ book = new Map()
631
+ volatileBook.set(key, book)
632
+ }
633
+ const hot = []
634
+ for (const s of sections) {
635
+ const name = String(s?.name ?? '')
636
+ if (!name || name.startsWith('fish:') || VOLATILE_PINNED.has(name)) continue
637
+ const text = sectionText(s)
638
+ if (!text) continue
639
+ const h = sectionHash(text)
640
+ const prev = book.get(name) ?? { last: '', changes: 0, seen: 0 }
641
+ const changed = prev.last !== '' && prev.last !== h
642
+ const next = { last: h, changes: changed ? prev.changes + 1 : prev.changes, seen: prev.seen + 1 }
643
+ book.set(name, next)
644
+ if (next.seen >= VOLATILE_MIN_SEEN && next.changes >= VOLATILE_MIN_CHANGES) hot.push({ section: s, chars: text.length })
645
+ }
646
+ if (!hot.length) return 0
647
+ // 先挪最大的:它变了会带掉后面最长的一截缓存。
648
+ hot.sort((a, b) => b.chars - a.chars)
649
+ const moved = hot.slice(0, VOLATILE_MAX_MOVED)
650
+ const rest = sections.filter((s) => !moved.some((m) => m.section === s))
651
+ // 跟着 beliefs(order 9000)后面排,宿主按 order 排也不会被排回去。
652
+ const tail = moved.map((m, i) => ({ ...m.section, order: VOLATILE_ORDER_BASE + i }))
653
+ assembly.sections = [...rest, ...tail]
654
+ if (typeof log === 'function') logVolatileOnce(moved, log)
655
+ return moved.length
656
+ }
657
+
658
+ let loggedVolatile = 0
659
+ function logVolatileOnce(moved, log) {
660
+ if (loggedVolatile) return
661
+ loggedVolatile = 1
662
+ const chars = moved.reduce((n, m) => n + m.chars, 0)
663
+ try { log(`[dsh-fish] 提示词整理:把 ${moved.length} 段每轮都在变的内容挪到最后(共 ${chars} 字,前缀缓存省着用)`) } catch { /* 日志坏了不影响组装 */ }
664
+ }
665
+
264
666
  /**
265
667
  * 把 <code>reorderForHer</code> 挂到这条 agent 的组装链上。
266
668
  *
@@ -270,7 +672,7 @@ export function reorderForHer(assembly, { log } = {}) {
270
672
  * @param {object} agent
271
673
  * @returns {(() => void)|undefined} 卸载函数
272
674
  */
273
- export function attachAssembleFix(agent, { log } = {}) {
675
+ export function attachAssembleFix(agent, { log, root, herDir } = {}) {
274
676
  const ctx = agent?.ctx
275
677
  if (!ctx || typeof ctx.on !== 'function') return undefined
276
678
  try {
@@ -281,7 +683,45 @@ export function attachAssembleFix(agent, { log } = {}) {
281
683
  // 整改失败必须原样放行:这条链断掉等于她一整轮读不到任何系统提示词,
282
684
  // 比「coding agent 排在前面」糟得多。
283
685
  try {
284
- return reorderForHer(assembled, { log })
686
+ // 宿主的组装结果里没有 tools(见 trimToolDocs 的注释),她的工具表从
687
+ // 自己的能力视图现取;取不到就交回 [],trimToolDocs 那边会整条不动。
688
+ let tools = []
689
+ try {
690
+ tools = visibleToolsOf(agent) ?? []
691
+ } catch {
692
+ tools = []
693
+ }
694
+ // 只有她自己的房间才少读别人的记忆规矩;他在别的会话里照旧。
695
+ let quiet = false
696
+ try {
697
+ quiet = quietForeignMemory(root) && isHerHome(agent, herDir)
698
+ } catch {
699
+ quiet = false
700
+ }
701
+ const out = reorderForHer(assembled, { log, tools, quietForeign: quiet })
702
+ // 会变的段挪到最后(默认开):先拿这一轮的段做一次「和上一轮比」,
703
+ // 连续几轮都在变的那几段就排到 beliefs 后面去,前面前缀才能稳定命中缓存。
704
+ let orderVolatile = true
705
+ try {
706
+ orderVolatile = promptPrefs(root).orderVolatileSections
707
+ } catch {
708
+ orderVolatile = true
709
+ }
710
+ if (orderVolatile) {
711
+ try {
712
+ const sid = String(agent?.session?.header?.id ?? agent?.session?.id ?? 'default')
713
+ reorderVolatile(out, { key: wakeKey(sid), log })
714
+ } catch { /* 排不动就保持原样,不影响她读提示词 */ }
715
+ }
716
+ if (quiet && lastQuiet > 0 && typeof log === 'function') {
717
+ logQuietOnce(lastQuiet, log)
718
+ }
719
+ // 排查用:DSH_FISH_PROMPT_TRIM=debug 时每轮记一行「她手上几个工具、摘了几段」。
720
+ if (String(process.env.DSH_FISH_PROMPT_TRIM ?? '').toLowerCase() === 'debug' && typeof log === 'function') {
721
+ const rep = lastTrimReport()
722
+ try { log(`[dsh-fish] 提示词整理:她手上 ${tools.length} 个工具,这次摘 ${rep.dropped.length} 段 / 省 ${rep.saved} 字`) } catch { /* 日志坏了不影响组装 */ }
723
+ }
724
+ return out
285
725
  } catch {
286
726
  return assembled
287
727
  }
@@ -292,6 +732,14 @@ export function attachAssembleFix(agent, { log } = {}) {
292
732
  }
293
733
  }
294
734
 
735
+ /** 「少读别人的记忆规矩」只在第一次真的摘到东西时记一行日志。 */
736
+ let loggedQuiet = false
737
+ function logQuietOnce(gone, log) {
738
+ if (loggedQuiet) return
739
+ loggedQuiet = true
740
+ try { log(`[dsh-fish] 她这个房间不再读别的记忆插件的段(摘了 ${gone} 段)`) } catch { /* 日志坏了不影响组装 */ }
741
+ }
742
+
295
743
  /**
296
744
  * 这一次唤醒的处境正文,**按会话分开存**(2026-11-06,用户 m03265 二次报)。
297
745
  *
@@ -612,6 +1060,14 @@ export function attachIdentity(agent, root, { frozen = '', herDir = '', log } =
612
1060
  // 他 / 她 / TA(1.0.0 起改占位符,见 lib/pronoun.js 文件头)。
613
1061
  text: () => fillOwner(getWakeSection(wakeSid), pronounFor(root)),
614
1062
  }))
1063
+ // 交接页(2026-11-15,用户 m01722):只在他换窗口后第一次开口的那一轮挂上。
1064
+ // `armHandoffFor` 在 turns.js 的 onHuman 里认领;settle 那一轮结完就撤。
1065
+ // 平时 `handoffArmed` 为假,这一段的 text() 是空串,等于不存在。
1066
+ remember(agent, 'section', sp.section({
1067
+ name: HANDOFF_SECTION,
1068
+ order: HANDOFF_ORDER,
1069
+ text: () => (handoffArmed(wakeSid) ? handoffTextSync(root) : ''),
1070
+ }))
615
1071
  // 「手边有什么」单独一段(2026-10-29,用户 m01276)。
616
1072
  // 有些工具我们收不窄——注册在 agent 自己作用域里的(ops_*、Agent Teams)
617
1073
  // 照样会出现在她的工具表里,schema 有名字她就会当成「我能用」。
@@ -627,12 +1083,26 @@ export function attachIdentity(agent, root, { frozen = '', herDir = '', log } =
627
1083
  order: TOOLS_ORDER,
628
1084
  // 2026-11-13:末尾接一段「旧话被压成摘要了去哪儿翻」,只在宿主真给了
629
1085
  // search_context 时才出现(见 restrict.js 的 foldedRecallNote)。
630
- text: () => [toolSurfaceFor(agent, { herDir }), foldedRecallNote(agent)].filter(Boolean).join('\n\n'),
1086
+ //
1087
+ // 2026-11-14(issue #137):这一路是独立挂载的,不经过 persona.assemble() 的
1088
+ // 出口,所以 toolSurfaceText() 里那句「{T}随时能再添几样进来」一直是字面量。
1089
+ // 跟处境段用同一个出口口径填一次(fillOwner 幂等,填两遍也不坏)。
1090
+ text: () => fillOwner(
1091
+ [toolSurfaceFor(agent, { herDir }), foldedRecallNote(agent)].filter(Boolean).join('\n\n'),
1092
+ pronounFor(root),
1093
+ ),
1094
+ }))
1095
+ // 「本子上记着什么」目录段:挂在**最后**(见 CATALOG_ORDER 的注释)。
1096
+ // 平时没什么可报(便条/约定都空)就是空串,等于这一段不存在。
1097
+ remember(agent, 'section', sp.section({
1098
+ name: CATALOG_SECTION,
1099
+ order: CATALOG_ORDER,
1100
+ text: () => catalogText(root),
631
1101
  }))
632
1102
  // 0.8.5(用户 m01579 拍板 B 案):宿主的 `deployment:persona-prefix` 那段
633
1103
  // "You are a coding agent…" 排在她的身份段前面七千多字,她先认下那句空话。
634
1104
  // 挂一个组装钩子摘掉它、把身份段提到紧跟 harness:identity —— 详情见 reorderForHer。
635
- const offAssemble = attachAssembleFix(agent, { log })
1105
+ const offAssemble = attachAssembleFix(agent, { log, root, herDir })
636
1106
  if (offAssemble) remember(agent, 'hook', offAssemble)
637
1107
  // 2026-11-10(外部用户真机):模型偶尔把一次没组起来的工具调用当正文吐出来
638
1108
  // (`<her_note action="list" filter="open"/>`、成串的 `||DSML||` 收尾标记)。