@furongjun1999/dsh-memory 0.9.10 → 0.9.12

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/src/hooks.ts CHANGED
@@ -92,6 +92,14 @@ export interface MemoryHooksOptions {
92
92
  autoRecall: boolean
93
93
  /** 自动召回条数(默认 4)。 */
94
94
  autoRecallLimit: number
95
+ /** 身份锚点独立注入块(issue #635,默认 false = 保持既有行为)。
96
+ *
97
+ * 背景:永久层(self/anchor)被 RECALL_SKIP_LAYERS 跳过,用户写完「我是谁」永远
98
+ * 不会被自动注入,只能去改 stg.py(升级即被整包抹掉)。
99
+ * 开启后:额外取若干条 self/anchor 节点,单独渲染成「【身份锚点】」块,
100
+ * **独立预算**(不占 recent 块),条数与字数都小(存在性提示,不承载知识)。
101
+ */
102
+ autoRecallIdentity?: boolean
95
103
  /** 自动记忆脱敏:写入前过滤敏感信息(密钥/密码/令牌/身份证/手机号,默认 true)。 */
96
104
  desensitize: boolean
97
105
  /** 落盘审计文件路径(issue #56,诊断面:哪些消息被设计滤除、source.kind 分布、
@@ -409,7 +417,7 @@ const RECALL_SKIP_LAYERS = new Set(['anchor', 'self'])
409
417
  * 9 条全部保留。(注意:整块仍远小于一条知识节点 500~800 tok,故本块定位是
410
418
  * 「存在性索引/提醒」,不承载知识本身——要知识请显式 mdcg_recall 并给足预算。) */
411
419
  // issue #563:导出仅为可测(注入面脱敏顺序的回归用例需要直接喂 payload)。
412
- export function formatTimelineDecayed(payload: unknown): string {
420
+ export function formatTimelineDecayed(payload: unknown, opts?: { includeIdentity?: boolean }): string {
413
421
  const items = (payload && typeof payload === 'object'
414
422
  && Array.isArray((payload as { items?: unknown }).items))
415
423
  ? (payload as { items: Array<Record<string, unknown>> }).items
@@ -418,6 +426,9 @@ export function formatTimelineDecayed(payload: unknown): string {
418
426
  let rank = 0
419
427
  for (const it of items) {
420
428
  const layer = String(it['layer'] ?? '')
429
+ // issue #635:includeIdentity=true 时,永久层**在本块仍不渲染**(它们走独立块),
430
+ // 这里只放宽"跳过"以便调用方取到它们——真正的分流在 renderIdentityAnchors。
431
+ if (RECALL_SKIP_LAYERS.has(layer) && !opts?.includeIdentity) continue
421
432
  if (RECALL_SKIP_LAYERS.has(layer)) continue
422
433
  const preview = String(it['preview'] ?? '').replace(/\s+/g, ' ').trim()
423
434
  if (!preview) continue
@@ -439,6 +450,30 @@ export function formatTimelineDecayed(payload: unknown): string {
439
450
  return out.join('\n').slice(0, RECALL_MAX_CHARS)
440
451
  }
441
452
 
453
+ /** 身份锚点块(issue #635):只取永久层(self/anchor),独立预算。 */
454
+ export const IDENTITY_MAX_ITEMS = 3
455
+ export const IDENTITY_MAX_CHARS = 640
456
+ export const IDENTITY_ITEM_CHARS = 160
457
+
458
+ export function renderIdentityAnchors(payload: unknown): string {
459
+ const items = (payload && typeof payload === 'object'
460
+ && Array.isArray((payload as { items?: unknown }).items))
461
+ ? (payload as { items: Array<Record<string, unknown>> }).items
462
+ : []
463
+ const out: string[] = []
464
+ for (const it of items) {
465
+ const layer = String(it['layer'] ?? '')
466
+ if (!RECALL_SKIP_LAYERS.has(layer)) continue
467
+ const preview = String(it['preview'] ?? '').replace(/\s+/g, ' ').trim()
468
+ if (!preview) continue
469
+ const safe = redactKeepPlaceholders(preview)
470
+ out.push(' - [' + layer + '] ' + (safe.length > IDENTITY_ITEM_CHARS ? safe.slice(0, IDENTITY_ITEM_CHARS) + '…' : safe))
471
+ if (out.length >= IDENTITY_MAX_ITEMS) break
472
+ if (out.join('\n').length >= IDENTITY_MAX_CHARS) break
473
+ }
474
+ return out.join('\n').slice(0, IDENTITY_MAX_CHARS)
475
+ }
476
+
442
477
  // ---------------------------------------------------------------- 会话窗口渲染
443
478
  // 「短期会话窗口」(contextWindow)的取数/渲染常量。与上方 RECALL_* 同款纪律:
444
479
  // 常量写死在此处(而非 config schema——未知键会被 schema 剥离)。
@@ -770,8 +805,13 @@ export function installMemoryHooks(ctx: Context, mdcg: MdcgClient | null, opts:
770
805
  if (sticky) {
771
806
  assembly.contexts.push({ name: 'lingshu:turn-reminder', text: sticky })
772
807
  }
773
- const text = formatTimelineDecayed(
774
- await graph.timeline(recallLimit, sid ? { session: sid } : {}))
808
+ // issue #635:身份锚点独立块(默认关)。开启时多取几条,按层分流:
809
+ // 非永久层 → 既有「最近记忆」块;self/anchor → 独立「身份锚点」块(独立预算)。
810
+ const identityOn = opts.autoRecallIdentity === true
811
+ const timelinePayload = await graph.timeline(
812
+ identityOn ? recallLimit + IDENTITY_MAX_ITEMS : recallLimit,
813
+ sid ? { session: sid } : {})
814
+ const text = formatTimelineDecayed(timelinePayload)
775
815
  if (text) {
776
816
  // 注入边界转义(issue #16):宿主 system-prompt 对 context 文本做严格
777
817
  // `{{variable}}` 插值,裸 `{{` 会 throw → 该轮请求整体失败。记忆原文
@@ -804,6 +844,23 @@ export function installMemoryHooks(ctx: Context, mdcg: MdcgClient | null, opts:
804
844
  })
805
845
  }
806
846
  }
847
+ if (identityOn) {
848
+ try {
849
+ const idText = renderIdentityAnchors(timelinePayload)
850
+ if (idText) {
851
+ assembly.contexts.push({
852
+ name: 'lingshu:identity-anchor',
853
+ text: escapePromptBraces(renderUntrustedMemoryBlock(
854
+ '【灵枢身份锚点】(self/anchor 层,独立预算)\n' + idText)),
855
+ })
856
+ }
857
+ } catch (err) {
858
+ // issue #128 同款纪律:fail-soft 但不静默——空 catch 会被
859
+ // test/session-declaration-report ③ 判红,也会让「身份块从未注入成功」
860
+ // 与「确实没有身份节点」不可分辨。失败不越过会话流边界(不抛)。
861
+ ctx.logger.warn(`dsh-memory: 身份锚点注入失败(已跳过该块): ${redactForLog(err)}`)
862
+ }
863
+ }
807
864
  // ── 独立第二块:「【本会话近期对话】」(contextWindow 注入面)──
808
865
  // 与上方 timeline 块**块名/取数/开关各自独立**(既有块一字未动)。
809
866
  // 稳定性口径与既有块同等:**每步都 push**(内容随新轮增长属预期——
package/src/index.ts CHANGED
@@ -95,6 +95,9 @@ export const inject = ['tools']
95
95
  export interface Config {
96
96
  /** 内部标识(provider/日志用;**不再用于工具名前缀**,工具名与 MCP 服务同名)。 */
97
97
  serverName: string
98
+ /** issue #634:是否同时注册 lingshu_* 兼容别名(缺省 true)。
99
+ * 0.9.9 起工具名去前缀,旧会话/旧脚本硬编码旧名会 unknown tool。 */
100
+ toolAliases: boolean
98
101
  /** Python 可执行文件(或 md_cg-mcp console script)。
99
102
  * 缺省 = 平台感知(issue #19):Windows `python` / Linux·macOS `python3`,
100
103
  * 可用 env `MDCG_PYTHON` 覆盖;显式配置本项优先级最高。 */
@@ -149,6 +152,9 @@ export interface Config {
149
152
 
150
153
  export const Config: z<Config> = z.object({
151
154
  serverName: z.string().default('lingshu'),
155
+ /** issue #634:0.9.9 起工具名去前缀(lingshu_cg -> cg)。
156
+ * 缺省 true = 同时注册 lingshu_* 兼容别名;设 false 则只注册裸名。 */
157
+ toolAliases: z.boolean().default(true),
152
158
  // issue #19:默认值按平台解析(Windows: python / 其它: python3;env MDCG_PYTHON 可覆盖)。
153
159
  // 写死 'python' 时 Linux/macOS 首装即 spawn ENOENT(PEP 394 只有 python3),
154
160
  // 且表现为「装好了但记忆永远为空」——最难定位的失效形态。
@@ -168,6 +174,8 @@ export const Config: z<Config> = z.object({
168
174
  importance: z.number().default(0.6),
169
175
  autoRecall: z.boolean().default(true),
170
176
  autoRecallLimit: z.number().default(4),
177
+ /** issue #635:self/anchor 层单列「身份锚点」块(默认 false = 维持既有行为)。 */
178
+ autoRecallIdentity: z.boolean().default(false),
171
179
  desensitize: z.boolean().default(true),
172
180
  /** **短期会话窗口**(滑动窗口,2026-10-06)——「短期保留近 N 条对话记录」
173
181
  * 的机制实现(长期记忆仍走灵枢的显式调用)。
@@ -191,7 +199,7 @@ export const Config: z<Config> = z.object({
191
199
  })
192
200
  .default({ enabled: true, turns: 10 }),
193
201
  })
194
- .default({ userMessage: true, assistantMessage: false, toolResult: false, importance: 0.6, autoRecall: true, autoRecallLimit: 4, desensitize: true, contextWindow: { enabled: true, turns: 10 } }),
202
+ .default({ userMessage: true, assistantMessage: false, toolResult: false, importance: 0.6, autoRecall: true, autoRecallLimit: 4, autoRecallIdentity: false, desensitize: true, contextWindow: { enabled: true, turns: 10 } }),
195
203
  toolCallTimeoutMs: z.number().default(60_000),
196
204
  maxRetryDelayMs: z.number().default(30_000),
197
205
  failOnStartupError: z.boolean().default(false),
@@ -430,6 +438,9 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
430
438
  // `cg` / `stg` / `mdcg_*`。此前按 `${config.serverName}_` 拼成 `cg`,造成「同一个
431
439
  // MCP 服务、不同端看到不同工具名」的初次识别错误。serverName 仍用于内部 provider/日志标识。
432
440
  toolPrefix: '',
441
+ // issue #634:默认补注册 lingshu_* 兼容别名(旧会话/旧脚本硬编码旧名时不至于 unknown tool)。
442
+ // 需要「只要裸名」的部署可设 tools.legacyAliases=false。
443
+ legacyAliases: config.toolAliases !== false,
433
444
  })
434
445
  disposers.push(dispose)
435
446
  toolsRegistered = true
package/src/tools.ts CHANGED
@@ -186,10 +186,26 @@ export function extractText(content: Array<{ type: string; text?: string; [key:
186
186
  * import 本包」在模块求值前就失败。惰性导入后:不在 DSH 宿主内时包仍可加载,
187
187
  * 只有真正注册工具才报错,且错误消息点名缺哪个包。
188
188
  */
189
+ /** 工具对外名(issue #634):正式名 + 可选兼容别名。
190
+ *
191
+ * 0.9.9 起去掉了 `${serverName}_` 前缀(lingshu_cg -> cg),升级瞬间
192
+ * 已存在会话里的旧名调用全部变成 unknown tool。这里给出「一个工具要注册哪些名字」的
193
+ * 纯函数,注册面与测试共用,避免两处各写一份判据。
194
+ */
195
+ export function toolPublicNames(
196
+ toolName: string,
197
+ prefix: string,
198
+ legacyAliases = true,
199
+ ): string[] {
200
+ const primary = `${prefix}${toolName}`
201
+ if (prefix || !legacyAliases || toolName.startsWith("lingshu_")) return [primary]
202
+ return [primary, `lingshu_${toolName}`]
203
+ }
204
+
189
205
  export async function registerLingshuTools(
190
206
  ctx: Context,
191
207
  bridge: LingshuBridge,
192
- opts: { selection: ToolSelection; toolPrefix: string },
208
+ opts: { selection: ToolSelection; toolPrefix: string; legacyAliases?: boolean },
193
209
  ): Promise<() => void> {
194
210
  let defineTool: typeof import('@deepseek-ai/dsh-tools').defineTool
195
211
  try {
@@ -205,12 +221,21 @@ export async function registerLingshuTools(
205
221
  const disposers: Array<() => void> = []
206
222
  const registered: string[] = []
207
223
  try {
224
+ // issue #634(2026-10-22):0.9.9 起工具名去掉 serverName 前缀(lingshu_cg -> cg),
225
+ // 升级瞬间已存在的会话里旧名调用全变 unknown tool,宿主与插件都没有提示。
226
+ // 这里加兼容别名:裸名照常注册,同时补注册 lingshu_<name>(legacyAliases=false 可关)。
227
+ // 别名与正式名指向同一个 execute,语义不变;描述标注 deprecated 供模型与人识别。
208
228
  for (const tool of tools) {
209
229
  if (!wanted.has(tool.name)) continue
210
- const publicName = `${opts.toolPrefix}${tool.name}`
211
- const definition = defineTool({
212
- name: publicName,
213
- description: tool.description || `灵枢 ${tool.name}`,
230
+ const names = toolPublicNames(tool.name, opts.toolPrefix, opts.legacyAliases !== false)
231
+ const publicName = names[0] as string
232
+ const aliasName = names[1] ?? ""
233
+ const makeDefinition = (registeredName: string, deprecated: boolean) => defineTool({
234
+ name: registeredName,
235
+ description: deprecated
236
+ ? '【已弃用别名】旧版工具名(升级兼容用),请改用 ' + publicName + '。原始描述:'
237
+ + (tool.description || '灵枢 ' + tool.name)
238
+ : (tool.description || '灵枢 ' + tool.name),
214
239
  parameters: schemaToParameters(tool.inputSchema),
215
240
  output: {
216
241
  schema: { type: 'json' } as never,
@@ -253,8 +278,14 @@ export async function registerLingshuTools(
253
278
  return { content: result.content } as never
254
279
  },
255
280
  })
256
- disposers.push(ctx.tools.register(definition))
281
+ disposers.push(ctx.tools.register(makeDefinition(publicName, false)))
257
282
  registered.push(publicName)
283
+ if (aliasName) {
284
+ // 兼容别名:指向同一个 execute(makeDefinition 复用了同一份定义体),
285
+ // 标记 deprecated;下一轮 minor 再评估是否移除。
286
+ disposers.push(ctx.tools.register(makeDefinition(aliasName, true)))
287
+ registered.push(aliasName)
288
+ }
258
289
  }
259
290
  } catch (err) {
260
291
  for (const dispose of disposers) dispose()