@ssamurias/dsh-fish 1.0.0 → 1.0.1

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/lib/identity.js CHANGED
@@ -27,7 +27,8 @@
27
27
  import { existsSync, readFileSync, statSync } from 'node:fs'
28
28
  import { selfDocPath } 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'
31
32
  import { activeOutingSync, bindOutingSession } from './outing.js'
32
33
  import { attachStreamScrub } from './scrub.js'
33
34
  import { deliverQueued } from './sessionnote.js'
@@ -56,15 +57,34 @@ export const TOOLS_ORDER = 8600
56
57
  * 免得他之后主动聊天时她还带着上一次的「此刻处境」。
57
58
  */
58
59
  export const WAKE_SECTION = 'fish:wake'
59
- export const WAKE_ORDER = 8700
60
+ /**
61
+ * 处境的顺序(2026-11-14,用户 m03077)。
62
+ *
63
+ * 原来是 8700,排在 `fish:beliefs`(9000)前面。可处境是**每醒一次就换一份**的:
64
+ * 时间、距上次多久、最近几条事件都不同。它一变,后面那 3,000 字左右的信念段
65
+ * (她自己说过的话 / 读到的一句话 / 被打脸过 / 对自己的说法 / 我做过的事)
66
+ * 就跟着重算——一次自主醒,白付三成提示词。
67
+ *
68
+ * 挪到 9250:在信念(9000)之后、指纹账本的基准(9400)之前。这样醒一次只有
69
+ * 处境自己那一千多字是新的,信念段还能命中前缀缓存;账本挪来的外来段仍排在最后。
70
+ * 语义上也更顺:她读到最后才是「此刻」。
71
+ */
72
+ export const WAKE_ORDER = 9250
60
73
 
61
74
  /**
62
75
  * 「这一刻会变的那几段」段(0.8.10,用户 m00315)。
63
76
  *
64
- * 她自己的身份文档里,有四段是逐轮、逐天都在变的:她自己说过的话、读到的一句话、
65
- * 被打脸过、对自己的说法。它们原来夹在身份正文中间(靠前),一变,后面整条提示词的
66
- * 前缀缓存就作废——实测她那次唤醒 25,832 字符的提示词里,这四段合计约 1,442 字符,
67
- * 位置却在第 22 行附近。
77
+ * 她自己的身份文档里,有五段是逐轮、逐天、**每用完一次工具**都在变的:她自己说过的话、
78
+ * 读到的一句话、被打脸过、对自己的说法,以及「我做过的事」(履历是从 `use:` 账现算的,
79
+ * 她用一次 bili_look、写一张便条,这一节就多一行)。
80
+ *
81
+ * 它们原来夹在身份正文中间(靠前),一变,后面整条提示词的前缀缓存就作废:
82
+ * - 0.8.10 实测:那次唤醒 25,832 字符的提示词里,那四段合计约 1,442 字符,
83
+ * 位置却在第 22 行附近。
84
+ * - 2026-11-14 复测(用户 m02511 问「要不要再挪」):连续 12 轮的 system prompt 逐节 diff,
85
+ * `## 我做过的事` 在 79→80、82→83、83→84、85→86、86→87、89→90 这几对里都变了
86
+ * (1,485→1,558→1,594→1,584→1,564),每次变都把她后面近 20,000 字符的缓存带掉;
87
+ * `## 现在`/`## 你是谁` 里的天数一天变一次,代价可以忽略,不动。
68
88
  *
69
89
  * 所以 `reorderForHer` 把它们从身份正文里剪出来,单列一段挂到最后(order 9000):
70
90
  * 内容一个字不少,只是排到了所有稳定内容之后。变的永远是尾巴。
@@ -72,14 +92,82 @@ export const WAKE_ORDER = 8700
72
92
  export const BELIEFS_SECTION = 'fish:beliefs'
73
93
  export const BELIEFS_ORDER = 9000
74
94
 
75
- /** 这四段的标题(`## ` 开头,按前缀认;正文里的括号补充说明不影响匹配)。 */
95
+ /** 这几段的标题(`## ` 开头,按前缀认;正文里的括号补充说明不影响匹配)。 */
76
96
  const VOLATILE_HEADINGS = [
77
97
  '## 你自己说过的话',
78
98
  '## 你读到的一句话',
79
99
  '## 你被打脸过',
80
100
  '## 你对自己的说法',
101
+ // 2026-11-14(用户 m02511):履历从 `use:` 账现算,她每用一次工具就多一行/换一行,
102
+ // 却是她身份最靠前的一段——留下来会把她后面整条提示词每轮都带掉。
103
+ '## 我做过的事',
81
104
  ]
82
105
 
106
+ /**
107
+ * 别人的记忆插件塞进她提示词里的那几段(2026-11-14,用户 m02622)。
108
+ *
109
+ * 她有自己的记法:`events.jsonl` + `her_recall`,加上身份文档里那几段。
110
+ * evolve 和 auto-memory 是给「帮他干活」的 agent 用的:它们往系统提示词里塞
111
+ * 工作区记忆索引(`evolve:memory-index`)和「记忆系统固定纪律」(`dsh:auto-memory-pre-rules`),
112
+ * 还会把一段 `<memory_system>` 挂成 systemPrompt.context——渲染出来是历史尾巴上
113
+ * 一条 user 消息(`dsh:auto-memory-pre`)。在她房间里,那两套规矩和她自己的记法打架:
114
+ * 她会去调自己根本拿不到的工具(memory_log / evolve_write),也会把「按工作区记忆」
115
+ * 当成本能,而不是「记住他说过的话」。
116
+ *
117
+ * 开关是 config 的 `prompt.quietForeignMemory`(默认关):
118
+ * - 只在她自己的房间(`isHerHome`)生效,绝不碰他本人在别的会话里的自动记忆;
119
+ * - 默认关是为了不替别人改环境——谁想让自家鱼少读点别人的规矩,自己打开。
120
+ */
121
+ export const QUIET_FOREIGN_KEY = 'prompt.quietForeignMemory'
122
+ const FOREIGN_MEMORY_SECTIONS = new Set(['evolve:memory-index', 'dsh:auto-memory-pre-rules'])
123
+ const FOREIGN_MEMORY_CONTEXTS = new Set(['dsh:auto-memory-pre'])
124
+
125
+ /** config 的 mtime 缓存:组装是每轮每步都跑的,不能每回读盘。 */
126
+ let prefCache = { file: '', mtime: -1, value: { quietForeignMemory: false, orderVolatileSections: true } }
127
+
128
+ /**
129
+ * 这个工作区的提示词偏好(`config.prompt`)。
130
+ *
131
+ * 读不出来(没装、还没写、JSON 坏了)一律按默认:少读别人的记忆规矩**关**、
132
+ * 会变动的段挪到末尾**开**。前者宁可不摘,后者只换位置、不改字,坏了也不至于让她读不到东西。
133
+ *
134
+ * @param {string} root
135
+ * @returns {{quietForeignMemory: boolean, orderVolatileSections: boolean}}
136
+ */
137
+ export function promptPrefs(root) {
138
+ const dflt = { quietForeignMemory: false, orderVolatileSections: true }
139
+ if (!root) return dflt
140
+ try {
141
+ const file = paths(root).config
142
+ const st = statSync(file)
143
+ if (prefCache.file === file && prefCache.mtime === st.mtimeMs) return prefCache.value
144
+ const raw = readFileSync(file, 'utf8')
145
+ const cfg = raw ? JSON.parse(raw) : {}
146
+ const p = cfg?.prompt ?? {}
147
+ const value = {
148
+ quietForeignMemory: p.quietForeignMemory === true,
149
+ // 默认开:只看「这段内容这两轮是不是不一样」,不改、不删任何字。
150
+ orderVolatileSections: p.orderVolatileSections !== false,
151
+ }
152
+ prefCache = { file, mtime: st.mtimeMs, value }
153
+ return value
154
+ } catch {
155
+ return dflt
156
+ }
157
+ }
158
+
159
+ /**
160
+ * 这个工作区打开了「少读别人的记忆规矩」吗。
161
+ *
162
+ * 读不出来(没装、还没写、JSON 坏了)一律当关:宁可多读一段,也不要替他关掉什么。
163
+ *
164
+ * @param {string} root
165
+ * @returns {boolean}
166
+ */
167
+ export function quietForeignMemory(root) {
168
+ return promptPrefs(root).quietForeignMemory
169
+ }
170
+
83
171
  /**
84
172
  * 宿主那两个段的名字(0.8.5,issue #14 后续 + 用户 m01579 拍板 B 案)。
85
173
  *
@@ -134,23 +222,25 @@ export const TOOL_DOC_MIN_NAMES = 3
134
222
  /** 一段至少这么长,才值得拿工具表去对(短段省不下几个字,还容易误伤)。 */
135
223
  export const TOOL_DOC_MIN_CHARS = 400
136
224
 
137
- let lastTrim = { dropped: [], saved: 0 }
225
+ let lastTrim = { dropped: [], saved: 0, skipped: '' }
226
+
227
+ /** 上一次「别人的记忆插件」摘了几段(排查用,不参与判断)。 */
228
+ let lastQuiet = 0
138
229
 
139
230
  /** 上一次摘段的结果(给自检/tools 用,不参与判断)。 */
140
231
  export function lastTrimReport() {
141
- return { dropped: lastTrim.dropped.slice(), saved: lastTrim.saved }
232
+ return { dropped: lastTrim.dropped.slice(), saved: lastTrim.saved, skipped: lastTrim.skipped ?? '' }
142
233
  }
143
234
 
144
235
  // 同一种摘法只记一次日志:她每一轮都会走这条链,逐轮刷屏没有意义。
145
236
  let loggedTrimKey = ''
146
237
 
147
- function logTrimOnce(dropped, saved, log) {
238
+ function logTrimOnce(dropped, saved, log, message) {
148
239
  if (typeof log !== 'function') return
149
- const key = `${dropped.map((d) => d.name).join(',')}|${saved}`
240
+ const key = message ?? `${dropped.map((d) => d.name).join(',')}|${saved}`
150
241
  if (key === loggedTrimKey) return
151
242
  loggedTrimKey = key
152
- const names = dropped.map((d) => d.name).join('、')
153
- log(`[dsh-fish] 摘掉了 ${dropped.length} 段讲别的工具的提示词(省 ${saved} 字符):${names}`)
243
+ log(message ?? `[dsh-fish] 摘掉了 ${dropped.length} 段讲别的工具的提示词(省 ${saved} 字符):${dropped.map((d) => d.name).join('、')}`)
154
244
  }
155
245
 
156
246
  /** 从一段文字里挑出「像工具名」的词(去重)。 */
@@ -175,32 +265,137 @@ export function toolNamesIn(text) {
175
265
  * @param {object} assembly 宿主组装出来的 PromptAssembly(就地改 sections)
176
266
  * @returns {object} 同一个对象
177
267
  */
178
- export function trimToolDocs(assembly, { log } = {}) {
268
+ // 2026-11-14(随公开包发布前加固):名字认得出、内容也确认是「讲别的插件 / 她没有的
269
+ // 工具」的段。**只认名字是不够的**——宿主升级可能改文案,甚至把同名段挪作他用;所以
270
+ // 每条都带一段内容签名,签名对不上就留着(宁可多留,不能误摘)。
271
+ // `needs` 表示「她真拿到这个工具时,这段讲的是她能做的事」,那就留着。
272
+ const HOST_TOOL_SECTIONS = new Map([
273
+ ['tool:beauticode', { sig: /beautiCode 可以把本机图片/ }],
274
+ ['tool:jobs', { sig: /job_output|background job|后台任务/ }],
275
+ ['tool:pwsh', { sig: /\[exit code: N\]|pwsh -Command/ }],
276
+ ['tool:goal', { sig: /create_goal|update_goal|get_goal/ }],
277
+ ['free-search:engines', { sig: /Current mode: |web_search/ }],
278
+ ['genui:fence', { sig: /dsh-ui/ }],
279
+ ['genui:native', { sig: /dsh-ui/ }],
280
+ ['dsh:auto-memory-pre-rules', { sig: /记忆系统|记忆定位/ }],
281
+ ['dsh:auto-memory-pre', { sig: /记忆系统|记忆定位/ }],
282
+ ['dsh:m6-reference-tail-pre', { sig: /hindsight|知识页/ }],
283
+ ['dsh-harness-dev-context', { sig: /DeepSeek Harness implementation checkout|HMR/ }],
284
+ // 同一段运行时说明在有些宿主版本里叫 `dsh-context`:讲的是 checkout 路径、GUI 地址、
285
+ // HMR 怎么开——全是给开发者看的,和她是谁无关(2026-11-14 复核她的提示词时发现)。
286
+ ['dsh-context', { sig: /implementation checkout|client-plugin HMR receiver|Web GUI whose URL/ }],
287
+ // 宿主那句「You are an AI agent powered by DeepSeek Harness.」是产品元信息,
288
+ // 不是她这个人的一部分(2026-11-14 用户要求)。签名钉死原文,宿主改词就留着。
289
+ ['harness:identity', { sig: /^You are an AI agent powered by DeepSeek Harness\./ }],
290
+ // present 的文件引用规则:她手里真有 `present` 时留(needs)。
291
+ ['ui:deliverable-file-references', { sig: /present|file references/i, needs: 'present' }],
292
+ ])
293
+ // 兜底:不管叫什么名字,只要是「用第二人称告诉模型它是什么」的英文身份句,就属于工具性描述,
294
+ // 不该出现在她的人格提示词里(2026-11-14 用户要求:人格养成要尽量少这种话)。
295
+ // 只认这几种开头,避免误伤工具文档里 "You are given ..." 之类。
296
+ const HOST_IDENTITY_CLAUSE = /^You are (?:an? (?:AI|coding) agent|interacting with the user)\b/im
297
+ // 不管上面那张表怎么写,这几段永远留着:她的身份、她的陈述。
298
+ const NEVER_TRIM = new Set([
299
+ 'fish:identity',
300
+ 'fish:tools',
301
+ 'fish:wake',
302
+ 'fish:beliefs',
303
+ 'persona',
304
+ 'deployment:persona-prefix',
305
+ ])
306
+
307
+ /** 段正文:宿主可能把 text 给成 getter。取不到就当空串(空串匹配不上签名 → 不摘)。 */
308
+ function sectionText(section) {
309
+ try {
310
+ const t = typeof section?.text === 'function' ? section.text() : section?.text
311
+ return typeof t === 'string' ? t : ''
312
+ } catch {
313
+ return ''
314
+ }
315
+ }
316
+
317
+ /** 摘完之后至少还得留下这么多字,否则当成「判据出问题了」。 */
318
+ export const TRIM_FLOOR_CHARS = 2000
319
+ /** 一次摘掉超过这个比例,也当成判据出问题(正常最狠的一台机器也只摘 60% 左右)。 */
320
+ const TRIM_MAX_SHARE = 0.75
321
+ /** 提示词本身小于这个数时不做安全闸(小样本多数是测试/特殊宿主,闸会误伤)。 */
322
+ const TRIM_GUARD_MIN_CHARS = 4000
323
+
324
+ /** 公开包里的紧急开关:`DSH_FISH_PROMPT_TRIM=off` 时只排序、一段不摘。 */
325
+ export function trimDisabled() {
326
+ const v = String(process.env.DSH_FISH_PROMPT_TRIM ?? '').toLowerCase()
327
+ return v === '0' || v === 'off' || v === 'false' || v === 'no'
328
+ }
329
+
330
+ export function trimToolDocs(assembly, { log, tools } = {}) {
179
331
  if (!assembly || !Array.isArray(assembly.sections)) return assembly
332
+ if (trimDisabled()) {
333
+ lastTrim = { dropped: [], saved: 0, skipped: 'off' }
334
+ return assembly
335
+ }
336
+ // 2026-11-14:宿主 0.2.x 组装的 `assembly` 里**没有** tools(它是在瀑布返回之后
337
+ // 才挂上去的,见 dsh-system-prompt 的 assemble),所以只看 `assembly.tools`
338
+ // 这里会永远拿到空集、整条判据变成空转。她的工具表改由调用方从
339
+ // `visibleToolsOf(agent)` 传进来;两处取并集,老宿主仍然按老办法工作。
180
340
  const have = new Set(
181
- (Array.isArray(assembly.tools) ? assembly.tools : [])
341
+ [...(Array.isArray(assembly.tools) ? assembly.tools : []), ...(Array.isArray(tools) ? tools : [])]
182
342
  .map((t) => String(typeof t === 'string' ? t : t?.name ?? ''))
183
343
  .filter(Boolean),
184
344
  )
185
345
  if (have.size === 0) {
186
- lastTrim = { dropped: [], saved: 0 }
346
+ // 判不了就不动——这是最重要的一条自保:宁可多读几千字,也不能凭猜摘掉她需要的东西。
347
+ lastTrim = { dropped: [], saved: 0, skipped: 'no-tools' }
187
348
  return assembly
188
349
  }
350
+ const totalChars = assembly.sections.reduce((n, s) => n + sectionText(s).length, 0)
189
351
  const dropped = []
190
352
  let saved = 0
191
353
  const kept = assembly.sections.filter((s) => {
192
354
  const name = String(s?.name ?? '')
193
355
  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
356
+ if (NEVER_TRIM.has(name)) return true
357
+ const text = sectionText(s)
358
+ // 英文身份句(「You are an AI agent …」「You are interacting with the user …」)是
359
+ // 模型/工具视角的自述,不是她的话(2026-11-14 用户要求)。名字不可靠时靠这一条兜住。
360
+ if (HOST_IDENTITY_CLAUSE.test(text)) {
361
+ dropped.push({ name, chars: text.length })
362
+ saved += text.length
363
+ return false
364
+ }
365
+ // 先看她够不够得着:段里提到的工具只要有一个在她手上,这段就是在讲她能做的事,留着。
196
366
  const mentioned = toolNamesIn(text)
197
- if (mentioned.length < TOOL_DOC_MIN_NAMES) return true
198
367
  if (mentioned.some((n) => have.has(n))) return true
368
+ // 名字认得出的「别的插件的工具说明」:还要内容签名对得上。
369
+ const known = HOST_TOOL_SECTIONS.get(name)
370
+ if (known) {
371
+ if (known.needs && have.has(known.needs)) return true
372
+ if (!known.sig.test(text)) return true
373
+ dropped.push({ name, chars: text.length })
374
+ saved += text.length
375
+ return false
376
+ }
377
+ if (text.length < TOOL_DOC_MIN_CHARS) return true
378
+ if (mentioned.length < TOOL_DOC_MIN_NAMES) return true
199
379
  dropped.push({ name, chars: text.length })
200
380
  saved += text.length
201
381
  return false
202
382
  })
203
- lastTrim = { dropped, saved }
383
+ if (dropped.length > 0 && totalChars >= TRIM_GUARD_MIN_CHARS) {
384
+ const left = totalChars - saved
385
+ if (left < TRIM_FLOOR_CHARS || saved > totalChars * TRIM_MAX_SHARE) {
386
+ // 判据算出来要摘掉大半、或几乎不给她留东西:这不是「她没这些工具」,更像判据坏了。
387
+ // 原样放行,并记一次(同样的形态只记一次)。
388
+ lastTrim = { dropped: [], saved: 0, skipped: 'suspicious' }
389
+ logTrimOnce(
390
+ [],
391
+ 0,
392
+ log,
393
+ `[dsh-fish] 一段都没摘:判据算出来要摘 ${dropped.length} 段、省 ${saved} 字,摘完只剩 ${left} 字,太可疑,按原样放行`,
394
+ )
395
+ return assembly
396
+ }
397
+ }
398
+ lastTrim = { dropped, saved, skipped: '' }
204
399
  if (dropped.length > 0) {
205
400
  assembly.sections = kept
206
401
  logTrimOnce(dropped, saved, log)
@@ -238,9 +433,24 @@ export function splitVolatileIdentity(text) {
238
433
  return { stable: keep.join('\n'), volatile: moved.join('\n') }
239
434
  }
240
435
 
241
- export function reorderForHer(assembly, { log } = {}) {
436
+ export function reorderForHer(assembly, { log, tools, quietForeign = false } = {}) {
242
437
  if (!assembly || !Array.isArray(assembly.sections)) return assembly
243
- trimToolDocs(assembly, { log })
438
+ trimToolDocs(assembly, { log, tools })
439
+ if (quietForeign) {
440
+ // 别人的记忆插件在她房间里留的东西:段按名字摘,context 按名字摘(渲染出来是
441
+ // 历史尾巴上那条 <memory_system>)。`required: true` 的照旧留着——宿主自己标了必需。
442
+ const before = assembly.sections.length
443
+ assembly.sections = assembly.sections.filter((s) => !FOREIGN_MEMORY_SECTIONS.has(String(s?.name ?? '')))
444
+ if (Array.isArray(assembly.contexts)) {
445
+ assembly.contexts = assembly.contexts.filter(
446
+ (c) => c?.required === true || !FOREIGN_MEMORY_CONTEXTS.has(String(c?.name ?? '')),
447
+ )
448
+ }
449
+ const gone = before - assembly.sections.length
450
+ lastQuiet = gone
451
+ } else {
452
+ lastQuiet = 0
453
+ }
244
454
  const kept = assembly.sections.filter((s) => String(s?.name ?? '') !== HOST_PERSONA_SECTION)
245
455
  const mine = kept.find((s) => String(s?.name ?? '') === IDENTITY_SECTION)
246
456
  if (!mine) {
@@ -261,6 +471,100 @@ export function reorderForHer(assembly, { log } = {}) {
261
471
  return assembly
262
472
  }
263
473
 
474
+ /* ------------------------------------------------------------------ *
475
+ * 会变的段:自适应地挪到最后(2026-11-14,用户 m02835)
476
+ *
477
+ * 宿主的提示词是按段平铺 join 出来的,缓存按**字节前缀**命中:前面任何一段改一个字,
478
+ * 后面所有段都要重算。所以「谁在变」比「谁重要」更决定缓存。
479
+ *
480
+ * 她是养成型,自己的身份段已经被 splitVolatileIdentity 按标题剪到尾巴;
481
+ * 但别人装的插件(evolve 的记忆索引、auto-memory 的今日日志、别的注入器)
482
+ * 也可能每轮换内容,而且**不同用户装的插件根本不一样**——写死名字没法公开发出去。
483
+ * 于是这里只看行为:同一段连续几轮内容都在变,就把它挪到 beliefs 之后(末尾),
484
+ * 变了也就只影响它自己后面那点尾巴。
485
+ *
486
+ * 三条安全线:
487
+ * 1. 只换位置、不改字:一段内容一个字都不删;
488
+ * 2. 不碰 `fish:*`(她自己的顺序由 reorderForHer 定)和宿主的两个身份段;
489
+ * 3. 判据要「见过至少 3 次、变了至少 2 次」才动手,避免一次抖动就重排。
490
+ * ------------------------------------------------------------------ */
491
+
492
+ /** 每个会话记一本「各段上一轮长什么样」的账,键是会话 id。 */
493
+ const volatileBook = new Map()
494
+ const VOLATILE_BOOK_MAX = 300
495
+ const VOLATILE_MIN_SEEN = 3
496
+ const VOLATILE_MIN_CHANGES = 2
497
+ const VOLATILE_MAX_MOVED = 5
498
+ const VOLATILE_ORDER_BASE = 9400
499
+ /** 顺序有语义、或者本来就放在最前面的段,不参与搬迁。 */
500
+ const VOLATILE_PINNED = new Set(['harness:identity', 'deployment:persona-prefix'])
501
+
502
+ /** FNV-1a,够用就行;只拿来判「这段和上一轮是不是同一段」。 */
503
+ function fnv1a(text) {
504
+ let h = 0x811c9dc5
505
+ for (let i = 0; i < text.length; i += 1) {
506
+ h ^= text.charCodeAt(i)
507
+ h = Math.imul(h, 0x01000193) >>> 0
508
+ }
509
+ return h.toString(16)
510
+ }
511
+
512
+ function sectionHash(text) {
513
+ const s = String(text ?? '')
514
+ const mid = s.length >> 1
515
+ // 只取一处容易漏掉「中间改了、首尾没改」的情况,所以头尾各算一次。
516
+ return `${s.length}:${fnv1a(s)}:${fnv1a(s.slice(mid) + s.slice(0, mid))}`
517
+ }
518
+
519
+ /**
520
+ * 把「一直在变」的外来段挪到最后。只改位置,不改内容。
521
+ *
522
+ * @param {object} assembly 宿主的组装结果(`{ sections, contexts, variables }`)
523
+ * @param {{key?: string, log?: Function}} [opts] `key` 用来区分会话
524
+ * @returns {number} 这次挪了几段(0 表示没动)
525
+ */
526
+ export function reorderVolatile(assembly, { key = 'default', log = null } = {}) {
527
+ const sections = Array.isArray(assembly?.sections) ? assembly.sections : []
528
+ if (sections.length < 2) return 0
529
+ let book = volatileBook.get(key)
530
+ if (!book) {
531
+ if (volatileBook.size >= VOLATILE_BOOK_MAX) volatileBook.delete(volatileBook.keys().next().value)
532
+ book = new Map()
533
+ volatileBook.set(key, book)
534
+ }
535
+ const hot = []
536
+ for (const s of sections) {
537
+ const name = String(s?.name ?? '')
538
+ if (!name || name.startsWith('fish:') || VOLATILE_PINNED.has(name)) continue
539
+ const text = sectionText(s)
540
+ if (!text) continue
541
+ const h = sectionHash(text)
542
+ const prev = book.get(name) ?? { last: '', changes: 0, seen: 0 }
543
+ const changed = prev.last !== '' && prev.last !== h
544
+ const next = { last: h, changes: changed ? prev.changes + 1 : prev.changes, seen: prev.seen + 1 }
545
+ book.set(name, next)
546
+ if (next.seen >= VOLATILE_MIN_SEEN && next.changes >= VOLATILE_MIN_CHANGES) hot.push({ section: s, chars: text.length })
547
+ }
548
+ if (!hot.length) return 0
549
+ // 先挪最大的:它变了会带掉后面最长的一截缓存。
550
+ hot.sort((a, b) => b.chars - a.chars)
551
+ const moved = hot.slice(0, VOLATILE_MAX_MOVED)
552
+ const rest = sections.filter((s) => !moved.some((m) => m.section === s))
553
+ // 跟着 beliefs(order 9000)后面排,宿主按 order 排也不会被排回去。
554
+ const tail = moved.map((m, i) => ({ ...m.section, order: VOLATILE_ORDER_BASE + i }))
555
+ assembly.sections = [...rest, ...tail]
556
+ if (typeof log === 'function') logVolatileOnce(moved, log)
557
+ return moved.length
558
+ }
559
+
560
+ let loggedVolatile = 0
561
+ function logVolatileOnce(moved, log) {
562
+ if (loggedVolatile) return
563
+ loggedVolatile = 1
564
+ const chars = moved.reduce((n, m) => n + m.chars, 0)
565
+ try { log(`[dsh-fish] 提示词整理:把 ${moved.length} 段每轮都在变的内容挪到最后(共 ${chars} 字,前缀缓存省着用)`) } catch { /* 日志坏了不影响组装 */ }
566
+ }
567
+
264
568
  /**
265
569
  * 把 <code>reorderForHer</code> 挂到这条 agent 的组装链上。
266
570
  *
@@ -270,7 +574,7 @@ export function reorderForHer(assembly, { log } = {}) {
270
574
  * @param {object} agent
271
575
  * @returns {(() => void)|undefined} 卸载函数
272
576
  */
273
- export function attachAssembleFix(agent, { log } = {}) {
577
+ export function attachAssembleFix(agent, { log, root, herDir } = {}) {
274
578
  const ctx = agent?.ctx
275
579
  if (!ctx || typeof ctx.on !== 'function') return undefined
276
580
  try {
@@ -281,7 +585,45 @@ export function attachAssembleFix(agent, { log } = {}) {
281
585
  // 整改失败必须原样放行:这条链断掉等于她一整轮读不到任何系统提示词,
282
586
  // 比「coding agent 排在前面」糟得多。
283
587
  try {
284
- return reorderForHer(assembled, { log })
588
+ // 宿主的组装结果里没有 tools(见 trimToolDocs 的注释),她的工具表从
589
+ // 自己的能力视图现取;取不到就交回 [],trimToolDocs 那边会整条不动。
590
+ let tools = []
591
+ try {
592
+ tools = visibleToolsOf(agent) ?? []
593
+ } catch {
594
+ tools = []
595
+ }
596
+ // 只有她自己的房间才少读别人的记忆规矩;他在别的会话里照旧。
597
+ let quiet = false
598
+ try {
599
+ quiet = quietForeignMemory(root) && isHerHome(agent, herDir)
600
+ } catch {
601
+ quiet = false
602
+ }
603
+ const out = reorderForHer(assembled, { log, tools, quietForeign: quiet })
604
+ // 会变的段挪到最后(默认开):先拿这一轮的段做一次「和上一轮比」,
605
+ // 连续几轮都在变的那几段就排到 beliefs 后面去,前面前缀才能稳定命中缓存。
606
+ let orderVolatile = true
607
+ try {
608
+ orderVolatile = promptPrefs(root).orderVolatileSections
609
+ } catch {
610
+ orderVolatile = true
611
+ }
612
+ if (orderVolatile) {
613
+ try {
614
+ const sid = String(agent?.session?.header?.id ?? agent?.session?.id ?? 'default')
615
+ reorderVolatile(out, { key: wakeKey(sid), log })
616
+ } catch { /* 排不动就保持原样,不影响她读提示词 */ }
617
+ }
618
+ if (quiet && lastQuiet > 0 && typeof log === 'function') {
619
+ logQuietOnce(lastQuiet, log)
620
+ }
621
+ // 排查用:DSH_FISH_PROMPT_TRIM=debug 时每轮记一行「她手上几个工具、摘了几段」。
622
+ if (String(process.env.DSH_FISH_PROMPT_TRIM ?? '').toLowerCase() === 'debug' && typeof log === 'function') {
623
+ const rep = lastTrimReport()
624
+ try { log(`[dsh-fish] 提示词整理:她手上 ${tools.length} 个工具,这次摘 ${rep.dropped.length} 段 / 省 ${rep.saved} 字`) } catch { /* 日志坏了不影响组装 */ }
625
+ }
626
+ return out
285
627
  } catch {
286
628
  return assembled
287
629
  }
@@ -292,6 +634,14 @@ export function attachAssembleFix(agent, { log } = {}) {
292
634
  }
293
635
  }
294
636
 
637
+ /** 「少读别人的记忆规矩」只在第一次真的摘到东西时记一行日志。 */
638
+ let loggedQuiet = false
639
+ function logQuietOnce(gone, log) {
640
+ if (loggedQuiet) return
641
+ loggedQuiet = true
642
+ try { log(`[dsh-fish] 她这个房间不再读别的记忆插件的段(摘了 ${gone} 段)`) } catch { /* 日志坏了不影响组装 */ }
643
+ }
644
+
295
645
  /**
296
646
  * 这一次唤醒的处境正文,**按会话分开存**(2026-11-06,用户 m03265 二次报)。
297
647
  *
@@ -627,12 +977,19 @@ export function attachIdentity(agent, root, { frozen = '', herDir = '', log } =
627
977
  order: TOOLS_ORDER,
628
978
  // 2026-11-13:末尾接一段「旧话被压成摘要了去哪儿翻」,只在宿主真给了
629
979
  // search_context 时才出现(见 restrict.js 的 foldedRecallNote)。
630
- text: () => [toolSurfaceFor(agent, { herDir }), foldedRecallNote(agent)].filter(Boolean).join('\n\n'),
980
+ //
981
+ // 2026-11-14(issue #137):这一路是独立挂载的,不经过 persona.assemble() 的
982
+ // 出口,所以 toolSurfaceText() 里那句「{T}随时能再添几样进来」一直是字面量。
983
+ // 跟处境段用同一个出口口径填一次(fillOwner 幂等,填两遍也不坏)。
984
+ text: () => fillOwner(
985
+ [toolSurfaceFor(agent, { herDir }), foldedRecallNote(agent)].filter(Boolean).join('\n\n'),
986
+ pronounFor(root),
987
+ ),
631
988
  }))
632
989
  // 0.8.5(用户 m01579 拍板 B 案):宿主的 `deployment:persona-prefix` 那段
633
990
  // "You are a coding agent…" 排在她的身份段前面七千多字,她先认下那句空话。
634
991
  // 挂一个组装钩子摘掉它、把身份段提到紧跟 harness:identity —— 详情见 reorderForHer。
635
- const offAssemble = attachAssembleFix(agent, { log })
992
+ const offAssemble = attachAssembleFix(agent, { log, root, herDir })
636
993
  if (offAssemble) remember(agent, 'hook', offAssemble)
637
994
  // 2026-11-10(外部用户真机):模型偶尔把一次没组起来的工具调用当正文吐出来
638
995
  // (`<her_note action="list" filter="open"/>`、成串的 `||DSML||` 收尾标记)。
package/lib/index.js CHANGED
@@ -31,6 +31,7 @@ import { registerPronounAsk } from './pronounask.js'
31
31
  import { answerCard } from './cardanswer.js'
32
32
  import { registerDream } from './dream.js'
33
33
  import { registerProactive } from './proactive.js'
34
+ import { registerDoingHooks } from './doing.js'
34
35
  import { registerObserve } from './observe.js'
35
36
  import { startScheduler } from './scheduler.js'
36
37
  import { registerTurns } from './turns.js'
@@ -57,7 +58,7 @@ export const name = 'dsh-fish'
57
58
  * 版本号,必须和 package.json 的 version 一样(test/boot.test.mjs 盯着)。
58
59
  * 不只是日志:升级自检和设置页的「检查更新」拿它当「正在跑的版本」。
59
60
  */
60
- export const VERSION = '1.0.0'
61
+ export const VERSION = '1.0.1'
61
62
 
62
63
  // ⚠️ 一个数组写全,不要拆成对象
63
64
  // 2026-10-30(m02961):`userQuestions` **不再写进 inject**。写进 inject 的东西缺一个,
@@ -461,6 +462,11 @@ export function apply(ctx, baseConfig = {}) {
461
462
  const obs = registerObserve(ctx, { root, version: VERSION, tenancy, install, compat })
462
463
  if (obs?.dispose) disposers.push(() => obs.dispose())
463
464
 
465
+ // 动手回合的闸与记账(2026-11-14,用户 m01237):只在主动回合里生效,
466
+ // 他自己找她、定时叫醒都不经过;拿不到会话时一律放行。
467
+ const doingOff = registerDoingHooks(ctx, { root, log: (...a) => logger.info(...a) })
468
+ if (doingOff) disposers.push(doingOff)
469
+
464
470
  // 生物钟:把屋子信息一起传下去。她每晚醒来说话要落进**同一个**会话,
465
471
  // 不是每晚新开一个藏起来的会话(用户定案:打开侧栏就该看见她)。
466
472
  //
@@ -511,8 +517,14 @@ export function apply(ctx, baseConfig = {}) {
511
517
  try { scheduler?.dispose?.() } catch { /* ignore */ }
512
518
  try { clearWakeSection() } catch { /* ignore */ }
513
519
  for (const d of disposers) { try { d() } catch { /* ignore */ } }
520
+ // 临走前抢刷一次兜底备份(用户 m00597):谁也不知道哪次启动是最后一次,
521
+ // 关机前这一下是最后的机会。跟 released 一起 race,且自带 2 秒上限——
522
+ // 磁盘卡住时不能把卸载也挂住,依赖这个插件的服务还在等它。
523
+ const flushed = Promise.resolve()
524
+ .then(() => scheduler?.flushBackup?.())
525
+ .catch(() => {})
514
526
  // 磁盘卡住时别把卸载也挂住,依赖这个插件的服务要等它。用不 ref 的定时器,它不该拖住进程
515
- return Promise.race([released, sleep(2000, undefined, { ref: false })])
527
+ return Promise.race([Promise.all([released, flushed]), sleep(2000, undefined, { ref: false })])
516
528
  }
517
529
 
518
530
  // 宿主的 cordis 4 没有 'dispose' 事件,也不管 apply 返回的 { dispose },只认 ctx.effect。
package/lib/look.js CHANGED
@@ -28,6 +28,37 @@ import { guardWrite } from './tenant.js'
28
28
 
29
29
  import { defineTool } from './tool.js'
30
30
 
31
+ /**
32
+ * 「没读出回复」时到底该说什么(2026-11-13,issue #136 B)。
33
+ *
34
+ * 原来这里只有一句写死的话:「你最近没在谁的评论下面被人回过——也可能是我这边
35
+ * 查不到(B 站这会儿回了个 -412)」。可 -412 从没发生过,她照着这句去理解,
36
+ * 得到的是一个不存在的风控;真正的原因(没发过评论 / 没人回 / 网络没通)全被
37
+ * `readMyReplies` 里那句 `continue` 吞掉了。现在按 diag 里的事实分句说。
38
+ */
39
+ export function repliesMissNote(diag = {}, { bvid = '' } = {}) {
40
+ const days = Number(diag.days) || 0
41
+ const failed = Array.isArray(diag.failed) ? diag.failed : []
42
+ const codes = failed.map((f) => Number(f?.code))
43
+ if (diag.off) return 'B 站那边是关着的(设置里关了),现在没法去看。'
44
+ const risk = codes.find((n) => RISK_CODES.has(n))
45
+ if (risk) return `B 站这会儿没让我查(回了 ${risk}),过一会儿再看。`
46
+ if (failed.some((f) => String(f?.code) === 'NOT_LOGIN')) return 'B 站登录过期了,查不了回复。'
47
+ if (failed.some((f) => String(f?.code) === 'NETWORK')) return '网络没通,这次没查成回复。'
48
+ if (!diag.roots) {
49
+ return bvid
50
+ ? `你在 ${bvid} 下面没发过评论,所以没有「谁回你」可看。`
51
+ : `最近 ${days || '几'} 天你没在 B 站发过评论,所以没有「谁回你」可看。`
52
+ }
53
+ if (failed.length) return `有几条(${failed.length} 条)没查成,剩下那些下面没人回你。`
54
+ // 分不清就不能说成「没有人回你」:她自己是这么说的——「别把「没有」和「查不成」合成一句」。
55
+ if (Number(diag.unresolved) > 0) return `有 ${diag.unresolved} 条这次没打开(没拿到视频详情),所以分不清是不是有人回你,过一会儿再看。`
56
+ return '你发过的那几条评论下面还没有人说话。'
57
+ }
58
+
59
+ /** 风控码:只有这些才算「B 站不让我查」。 */
60
+ const RISK_CODES = new Set([-412, -352, -509])
61
+
31
62
  /**
32
63
  * 调一次"看":返回素材文本。永不抛出。
33
64
  * 单独抽出来是为了能在观测台/单测里直接调(不经模型)。
@@ -67,13 +98,15 @@ export async function lookOnce(o = {}) {
67
98
  // 而且那条提醒被她看过一次就被 cseen 掉了,回头再看永远是空的。
68
99
  // 这里给她一个自己去看的动作:不滤 cseen,带上回楼中楼要用的编号。
69
100
  if (what === 'replies') {
70
- const got = await readMyReplies({ root, client, events, bvid: String(o.bvid ?? '').trim() })
71
- const txt = renderMyReplies(got, { bvid: String(o.bvid ?? '').trim() })
101
+ const want = String(o.bvid ?? '').trim()
102
+ const diag = {}
103
+ const got = await readMyReplies({ root, client, events, bvid: want, diag })
104
+ const txt = renderMyReplies(got, { bvid: want })
72
105
  if (!txt) {
73
106
  return {
74
107
  ok: false,
75
108
  text: '',
76
- note: got.length ? '' : '你最近没在谁的评论下面被人回过——也可能是我这边还查不到(B 站这会儿回了个 -412)。',
109
+ note: repliesMissNote(diag, { bvid: want }),
77
110
  picks: [],
78
111
  }
79
112
  }
@@ -315,6 +348,7 @@ export function registerLook(ctx, deps = {}) {
315
348
  '去看一眼 B 站:首页在推什么、搜一个词、看某条视频之后平台又接着推什么,' +
316
349
  '或者直接看指定的那一条(给 BV 号或链接)。' +
317
350
  '也可以看你自己发过的评论下面有没有人回你(what=replies)。' +
351
+ '别人在 B 站 @ 你,不在这个工具里——那时候那条内容会直接递进你的会话。' +
318
352
  '只读,不会留下痕迹。给的是标题、简介、标签、热评、弹幕——没有视频画面。' +
319
353
  '不用它也可以。',
320
354
  // 注意:必须 toJsonSchema 包一层。简写 DSL 直接发出去会被 provider 拒: