@restregular/dsh-memory 0.34.1 → 0.35.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.
@@ -46,6 +46,20 @@ import {
46
46
  import { ScopeArchiveStore, } from './scope-archive.js'
47
47
  import { SessionGrantsStore, } from './grants.js'
48
48
  import { ApprovalAuditStore, } from './approval-audit.js'
49
+ import {
50
+ DEFAULT_HOOK_SETTINGS,
51
+ HOOK_PHASES,
52
+ HookStore,
53
+ describeOutcomes,
54
+ hashHookCode,
55
+ hookNeedsApproval,
56
+ runHooks,
57
+
58
+
59
+
60
+
61
+
62
+ } from './hooks.js'
49
63
  import {
50
64
  authorize as authorizeAccess,
51
65
 
@@ -200,6 +214,11 @@ function isInside(parent , child ) {
200
214
 
201
215
   
202
216
 
217
+
218
+                        
219
+                               
220
+
221
+
203
222
 
204
223
 
205
224
 
@@ -621,7 +640,7 @@ export function resolveConfig(config = {}) {
621
640
 
622
641
 
623
642
                                    
624
-
643
+
625
644
                       
626
645
 
627
646
 
@@ -829,6 +848,10 @@ export class LocalMemoryService {
829
848
  archive
830
849
  /** 权限申请 / 授权生命周期审计(approvals.jsonl,不含正文)。 */
831
850
  approvalAudit
851
+ /** 记忆钩子(0.35.0):规则记忆附带的可执行校验/解析脚本,独立于记忆存储。 */
852
+ hooks
853
+ /** 钩子运行设置(随 settings.json 的 hooks 小节落盘)。 */
854
+ hookCfg
832
855
  /** 可见域变更通知:下一次 pre-step 注入给 Agent 后删除(按会话)。 */
833
856
  visibilityNotices = new Map ()
834
857
  /** 权限变更通知(0.25.0):授予 / 撤销;下一次 pre-step 注入给 Agent 后删除。 */
@@ -864,7 +887,7 @@ export class LocalMemoryService {
864
887
 
865
888
  constructor(config = {}) {
866
889
  this.cfg = resolveConfig(config)
867
- this.inject = this.loadInjectSettings((config ).inject)
890
+ this.inject = this.loadInjectSettings((config ).inject, (config ).hooks)
868
891
  this.names = new ScopeNames(join(this.cfg.storeDir, 'scopes.json'))
869
892
  this.meta = new ScopeMetaStore({ root: this.cfg.storeDir })
870
893
  this.visibility = new SessionVisibilityStore({ root: this.cfg.storeDir })
@@ -873,6 +896,14 @@ export class LocalMemoryService {
873
896
  this.blocks = new MemoryBlocksStore({ root: this.cfg.storeDir })
874
897
  this.archive = new ScopeArchiveStore({ root: this.cfg.storeDir })
875
898
  this.approvalAudit = new ApprovalAuditStore({ root: this.cfg.storeDir })
899
+ this.hooks = new HookStore({
900
+ root: this.cfg.storeDir,
901
+ onWarn: (m) => console.warn(`[dsh-memory-local] ${m}`),
902
+ })
903
+ // 注意:loadInjectSettings() 已经把 settings.json 里的 hooks 小节覆盖进
904
+ // hookCfg 了(带磁盘覆盖)。这里绝不能再用 config 重新赋值 —— 那会把磁盘
905
+ // 上的覆盖冲掉,表现为"面板改了设置,重启后又变回来"。config 只在
906
+ // loadInjectSettings 里作为底座使用。
876
907
  this.rerankBudget = new DailyBudget(this.cfg.llm.dailyBudgetTokens)
877
908
  this.store = new MemoryStore(this.cfg.storeDir, { onWarn: (m) => console.warn(`[dsh-memory-local] ${m}`) })
878
909
  // Identity BEFORE the eager load (issue #1): ScopeStore skips its sidecar
@@ -912,6 +943,176 @@ export class LocalMemoryService {
912
943
  return normalizeInjectSettings(this.inject, this.inject)
913
944
  }
914
945
 
946
+ // ---------------------------------------------------------------- 记忆钩子(0.35.0)
947
+
948
+ /** 当前钩子设置(配置 + settings.json 覆盖后的快照)。 */
949
+ hookSettings() {
950
+ return { ...this.hookCfg }
951
+ }
952
+
953
+ /** 面板 / 配置改钩子设置。落盘进 settings.json 的 hooks 小节。 */
954
+ updateHookSettings(patch ) {
955
+ this.hookCfg = resolveHookSettings({ ...this.hookCfg, ...(typeof patch === 'object' && patch !== null ? patch : {}) })
956
+ try {
957
+ mkdirSync(this.cfg.storeDir, { recursive: true })
958
+ const current = existsSync(this.settingsPath)
959
+ ? JSON.parse(readFileSync(this.settingsPath, 'utf8'))
960
+ : {}
961
+ current.hooks = this.hookCfg
962
+ writeFileSync(this.settingsPath, `${JSON.stringify(current, null, 2)}\n`, 'utf8')
963
+ } catch (error) {
964
+ console.warn(`[dsh-memory-local] 无法写入钩子设置 ${this.settingsPath}: ${error instanceof Error ? error.message : String(error)}`)
965
+ }
966
+ return this.hookSettings()
967
+ }
968
+
969
+ /** 全部钩子(含代码;只有 memory_hooks 与面板读它)。 */
970
+ listHooks() {
971
+ return this.hooks.list()
972
+ }
973
+
974
+ getHook(id ) {
975
+ return this.hooks.get(id)
976
+ }
977
+
978
+ /** 新建 / 更新钩子。代码改过则旧的审批作废(审批按代码指纹记账)。 */
979
+ saveHook(input ) {
980
+ return this.hooks.save(input, this.hookSettings())
981
+ }
982
+
983
+ deleteHook(id ) {
984
+ return this.hooks.delete(id)
985
+ }
986
+
987
+ /** 记一次用户审批(把当前代码的指纹记为已批准)。 */
988
+ approveHook(id ) {
989
+ const hook = this.hooks.get(id)
990
+ if (hook === undefined) return false
991
+ return this.hooks.approve(id, hashHookCode(hook.code))
992
+ }
993
+
994
+ /** 这条钩子是否还需要用户批准(代码变过也算需要)。 */
995
+ hookPendingApproval(id ) {
996
+ const hook = this.hooks.get(id)
997
+ return hook === undefined ? false : hookNeedsApproval(hook, this.hookSettings())
998
+ }
999
+
1000
+ /**
1001
+ * 带代码的规则首次保存:**向用户审批一次**。
1002
+ *
1003
+ * 审批按代码指纹记账(`approvedHash`),所以:
1004
+ * - 同一段代码只问一次;
1005
+ * - 代码改一个字符就要重新批准(否则改两笔就能继续用旧授权)。
1006
+ *
1007
+ * `requireApproval=false`(用户显式关掉)时直接记批准,不弹窗。
1008
+ * 没有审批通道(老宿主 / 测试)时**保守拒绝**:代码会在这个进程里执行,
1009
+ * 拿不到用户点头就不该让它跑起来。
1010
+ */
1011
+ async requestHookApproval(
1012
+ agent ,
1013
+ id ,
1014
+ options = {},
1015
+ ) {
1016
+ const hook = this.hooks.get(id)
1017
+ if (hook === undefined) return 'unavailable'
1018
+ const settings = this.hookSettings()
1019
+ if (!hookNeedsApproval(hook, settings)) return 'not-needed'
1020
+ if (!settings.requireApproval) {
1021
+ this.hooks.approve(id, hashHookCode(hook.code))
1022
+ return 'approved'
1023
+ }
1024
+ // 没有会话就没有审批浮层可挂:requestOutOfScope 会挂一个 5 分钟的等待,
1025
+ // 在测试 / 老宿主里白白耗掉 5 分钟。这里直接判不可用 —— 代码保持未批准、
1026
+ // 永远不会执行,既安全又不会卡住调用方。
1027
+ if (this.rawSessionIdOf(agent) === undefined) return 'unavailable'
1028
+ const preview = hook.code.length > 3000 ? `${hook.code.slice(0, 3000)}…` : hook.code
1029
+ const answer = await this.requestOutOfScope(agent, {
1030
+ tool: 'memory_hooks',
1031
+ action: 'write',
1032
+ query: hook.name,
1033
+ mode: 'hook',
1034
+ ...(options.description !== undefined ? { description: options.description } : {}),
1035
+ items: [{
1036
+ id: hook.id,
1037
+ scope: hook.scopes.length > 0 ? hook.scopes.join(',') : '*',
1038
+ kind: 'code',
1039
+ content: `${hook.phase}|${hook.name}\n${preview}`,
1040
+ tags: ['hook', hook.phase],
1041
+ importance: 1,
1042
+ updatedAt: Date.now(),
1043
+ reason: 'hook',
1044
+ } ],
1045
+ ...(options.signal !== undefined ? { signal: options.signal } : {}),
1046
+ })
1047
+ if (answer.outcome === 'allowed-once') {
1048
+ this.hooks.approve(id, hashHookCode(hook.code))
1049
+ return 'approved'
1050
+ }
1051
+ return answer.outcome === 'timeout' ? 'timeout' : answer.outcome === 'unavailable' ? 'unavailable' : 'rejected'
1052
+ }
1053
+
1054
+ /** 真正跑一批钩子(工具 / 注入共用)。 */
1055
+ runHooks(phase , input ) {
1056
+ return runHooks(this.hooks, phase, input, this.hookSettings())
1057
+ }
1058
+
1059
+ /**
1060
+ * 注入前解析:把一批记录按 before-inject 钩子处理一遍。
1061
+ *
1062
+ * 返回**新数组**(不改调用方持有的记录对象),并带回每个被改写/丢弃的 id,
1063
+ * 让注入审计能对上账。脚本崩溃等于没跑过,记录原样保留。
1064
+ */
1065
+ parseForInject(records , sessionId )
1066
+
1067
+
1068
+
1069
+ {
1070
+ const settings = this.hookSettings()
1071
+ if (!settings.enabled || records.length === 0) return { records: [...records], changed: [], warnings: [] }
1072
+ const out = []
1073
+ const changed = []
1074
+ const warnings = []
1075
+ for (const record of records) {
1076
+ let current = record
1077
+ let dropped = false
1078
+ // 同一批钩子里后面的脚本看到前面改写后的正文 —— 与保存路径的顺序一致。
1079
+ for (const hook of this.hooks.forRun('before-inject', { scope: record.scope, kind: record.kind }, settings)) {
1080
+ const outcomes = this.runHooks('before-inject', {
1081
+ memory: {
1082
+ id: current.id,
1083
+ scope: current.scope,
1084
+ kind: current.kind,
1085
+ content: current.content,
1086
+ tags: Array.isArray(current.tags) ? current.tags.map(String) : [],
1087
+ importance: current.importance,
1088
+ ...(current.triggers !== undefined ? { triggers: current.triggers } : {}),
1089
+ createdAt: current.createdAt,
1090
+ updatedAt: current.updatedAt,
1091
+ },
1092
+ tool: 'inject',
1093
+ ...(sessionId !== undefined ? { sessionId } : {}),
1094
+ })
1095
+ const outcome = outcomes.find((item) => item.hook.id === hook.id)
1096
+ if (outcome === undefined) continue
1097
+ if (outcome.error !== undefined) {
1098
+ warnings.push(`钩子「${hook.name}」在注入前解析时失败(已忽略):${outcome.error}`)
1099
+ continue
1100
+ }
1101
+ if (outcome.drop === true) {
1102
+ dropped = true
1103
+ changed.push({ id: record.id, hook: hook.name, option: 'dropped' })
1104
+ break
1105
+ }
1106
+ if (typeof outcome.content === 'string' && outcome.content.trim() !== '' && outcome.content !== current.content) {
1107
+ current = { ...current, content: outcome.content }
1108
+ changed.push({ id: record.id, hook: hook.name, option: 'rewritten' })
1109
+ }
1110
+ }
1111
+ if (!dropped) out.push(current)
1112
+ }
1113
+ return { records: out, changed, warnings }
1114
+ }
1115
+
915
1116
  /** 注入半边注册审计收集器。重复注册时后一个覆盖前一个(激活重载)。 */
916
1117
  attachInjectAudit(sink
917
1118
 
@@ -987,8 +1188,12 @@ export class LocalMemoryService {
987
1188
  }
988
1189
 
989
1190
  /** 配置先给底,磁盘上的 settings.json 覆盖它;坏文件忽略而不是启动失败。 */
990
- loadInjectSettings(fromConfig ) {
1191
+ loadInjectSettings(fromConfig , hooksFromConfig ) {
991
1192
  const base = normalizeInjectSettings(fromConfig)
1193
+ // 无条件先给一份底座(配置里的 hooks),随后 settings.json 的 hooks 小节覆盖它。
1194
+ // 不这样做的话:没有 settings.json 时 hookCfg 就是 undefined,而有 settings.json
1195
+ // 时又只在文件分支里赋值 —— 两条路径不一致,且构造函数里那次赋值会把磁盘覆盖冲掉。
1196
+ this.hookCfg = resolveHookSettings(hooksFromConfig)
992
1197
  try {
993
1198
  if (existsSync(this.settingsPath)) {
994
1199
  const parsed = JSON.parse(readFileSync(this.settingsPath, 'utf8'))
@@ -998,6 +1203,9 @@ export class LocalMemoryService {
998
1203
  const oldDigestDefault = digest !== undefined && digest !== null
999
1204
  && typeof digest === 'object' && digest.hintBudget === undefined
1000
1205
  && Number(digest.tokenBudget) === 400
1206
+ // 钩子设置也走这里:配置是底,settings.json 里的 hooks 小节覆盖它。
1207
+ const hookOverride = (parsed )?.hooks
1208
+ if (hookOverride !== undefined) this.hookCfg = resolveHookSettings({ ...this.hookCfg, ...(typeof hookOverride === 'object' && hookOverride !== null ? hookOverride : {}) })
1001
1209
  const merged = mergeInjectSettings(base, parsed)
1002
1210
  if (oldDigestDefault) merged.digest.tokenBudget = base.digest.tokenBudget
1003
1211
  return merged
@@ -3117,6 +3325,42 @@ export class LocalMemoryService {
3117
3325
  this.meta.put(scope, { description, createdBy: metaBefore?.createdBy ?? createdBy, status: 'ready' })
3118
3326
  }
3119
3327
 
3328
+ // 0.35.0:保存前校验钩子。**在真正写盘之前**跑,脚本可以否决这次保存。
3329
+ // 崩溃/超时的钩子不会阻断(见 hooks.ts 文件头第 3 条);只有脚本明确返回
3330
+ // ok:false 才是"规则说不合规"。
3331
+ const hookSettings = this.hookSettings()
3332
+ const draft = {
3333
+ scope,
3334
+ kind: String(input.kind ?? 'note'),
3335
+ content,
3336
+ tags: Array.isArray(input.tags) ? input.tags.map(String) : [],
3337
+ importance: typeof input.importance === 'number' ? input.importance : 0.8,
3338
+ }
3339
+ if (hookSettings.enabled) {
3340
+ const outcomes = this.runHooks('before-save', {
3341
+ memory: {
3342
+ ...draft,
3343
+ ...(input.supersedes !== undefined ? { supersedes: input.supersedes } : {}),
3344
+ ...(input.expiredAt !== undefined ? { expiresAt: input.expiredAt } : {}),
3345
+ },
3346
+ ...(typeof (input ).hookTool === 'string'
3347
+ ? { tool: (input ).hookTool }
3348
+ : {}),
3349
+ ...(saveAgent !== undefined && this.rawSessionIdOf(saveAgent) !== undefined
3350
+ ? { sessionId: this.rawSessionIdOf(saveAgent) }
3351
+ : {}),
3352
+ })
3353
+ const veto = outcomes.find((outcome) => outcome.error === undefined && !outcome.ok)
3354
+ if (veto !== undefined) {
3355
+ const why = veto.message !== undefined && veto.message !== '' ? veto.message : '内容不符合规则记忆的要求'
3356
+ throw memoryError(
3357
+ 'HOOK_REJECTED',
3358
+ `记忆未保存:钩子「${veto.hook.name}」判定不符合要求 —— ${why}\n`
3359
+ + '按提示改好 content 后重新调用 memory_save(这不是权限问题,不需要审批)。',
3360
+ )
3361
+ }
3362
+ }
3363
+
3120
3364
  let record
3121
3365
  try {
3122
3366
  const saved = this.store.save(
@@ -3142,6 +3386,28 @@ export class LocalMemoryService {
3142
3386
  }
3143
3387
  void this.embedRecord(record).catch(() => {})
3144
3388
  this.store.scheduleFlush()
3389
+ // 0.35.0:保存后观察钩子。**不阻断、不改写** —— 记录已经落盘,这里只让脚本
3390
+ // 记录/附注;脚本崩溃只写日志,连告警都不回给模型(避免污染工具结果)。
3391
+ if (hookSettings.enabled) {
3392
+ try {
3393
+ this.runHooks('after-save', {
3394
+ memory: {
3395
+ id: record.id,
3396
+ scope: record.scope,
3397
+ kind: record.kind,
3398
+ content: record.content,
3399
+ tags: Array.isArray(record.tags) ? record.tags.map(String) : [],
3400
+ importance: record.importance,
3401
+ ...(record.triggers !== undefined ? { triggers: record.triggers } : {}),
3402
+ createdAt: record.createdAt,
3403
+ updatedAt: record.updatedAt,
3404
+ ...(record.expiredAt !== undefined ? { expiresAt: record.expiredAt } : {}),
3405
+ ...(record.supersedes !== undefined ? { supersedes: record.supersedes } : {}),
3406
+ ...(record.initial === true ? { initial: true } : {}),
3407
+ },
3408
+ })
3409
+ } catch { /* 观察者的失败绝不能影响已完成的保存 */ }
3410
+ }
3145
3411
  return record
3146
3412
  }
3147
3413
 
@@ -4288,6 +4554,29 @@ function memoryError(code , message ) {
4288
4554
  return err
4289
4555
  }
4290
4556
 
4557
+ /**
4558
+ * 钩子设置归一化(配置 → HookSettings)。
4559
+ *
4560
+ * 默认**开启**:这是"规则能落地成代码"的核心能力,装上就该能用。关掉它需要用户
4561
+ * 显式把 config.hooks.enabled 或面板设置改成 false。
4562
+ */
4563
+ export function resolveHookSettings(raw ) {
4564
+ const base = { ...DEFAULT_HOOK_SETTINGS }
4565
+ if (typeof raw === 'boolean') return { ...base, enabled: raw }
4566
+ if (raw === null || raw === undefined || typeof raw !== 'object') return base
4567
+ const value = raw
4568
+ if (typeof value.enabled === 'boolean') base.enabled = value.enabled
4569
+ if (typeof value.requireApproval === 'boolean') base.requireApproval = value.requireApproval
4570
+ if (typeof value.maxCodeChars === 'number' && Number.isFinite(value.maxCodeChars)) {
4571
+ base.maxCodeChars = Math.max(500, Math.min(200_000, Math.round(value.maxCodeChars)))
4572
+ }
4573
+ if (typeof value.timeoutMs === 'number' && Number.isFinite(value.timeoutMs)) {
4574
+ // 上限 5s:钩子是同步阻塞在写路径 / 注入路径上的,不能让它拖住整轮对话。
4575
+ base.timeoutMs = Math.max(20, Math.min(5_000, Math.round(value.timeoutMs)))
4576
+ }
4577
+ return base
4578
+ }
4579
+
4291
4580
  /** 作用域用途统一成一行(与工具的 description 同款收敛口径)。 */
4292
4581
  function normalizeScopeDescription(raw ) {
4293
4582
  return typeof raw === 'string' ? raw.replace(/\s+/g, ' ').trim() : ''
package/lib/skills.js ADDED
@@ -0,0 +1,157 @@
1
+ /**
2
+ * 随包技能:`skills/<name>/SKILL.md` → 注册表候选。
3
+ *
4
+ * 为什么随包发而不是写进用户目录:记忆钩子的脚本 API(入口函数名、沙箱能力、
5
+ * 返回约定)是**这个插件的**约定,必须和代码同版本、同一次安装。写进
6
+ * `~/.agents/skills` 就成了"另一份需要单独维护的副本",改代码忘了改文档。
7
+ *
8
+ * 注册成 provider 而不是 runtime skill:技能带 `references/examples.md`
9
+ * 这类资源文件,只有 `resourceBase` 能让模型解析相对路径(见 skill-authoring
10
+ * 的 plugin-bundled 说明)。
11
+ */
12
+ import { existsSync, readFileSync, readdirSync } from 'node:fs'
13
+ import { join } from 'node:path'
14
+ import { fileURLToPath } from 'node:url'
15
+
16
+ /** 随包技能目录(产物里是 `<pkg>/skills/`,源码树里是 `source/memory-plugin/skills/`)。 */
17
+ const SKILLS_ROOT = fileURLToPath(new URL('../skills/', import.meta.url))
18
+
19
+ /** 与 `@deepseek-ai/dsh-skill` 的 BUNDLED_SKILL_RANK 对齐:项目 / 用户技能可以覆盖它。 */
20
+ const BUNDLED_SKILL_RANK = 600
21
+
22
+ /** provider 名必须是本包名的一部分,且不能是保留字 `runtime`。 */
23
+ const PROVIDER = 'dsh-memory'
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+ /** 取 frontmatter 里某个单行字段(只处理 `key: value` / `key: "value"`)。 */
38
+ function frontmatterField(text , key ) {
39
+ if (!text.startsWith('---')) return undefined
40
+ const end = text.indexOf('\n---', 3)
41
+ if (end < 0) return undefined
42
+ const block = text.slice(3, end)
43
+ for (const line of block.split(/\r?\n/)) {
44
+ const match = /^([A-Za-z][\w-]*):\s*(.*)$/.exec(line)
45
+ if (match === null || match[1] !== key) continue
46
+ let value = match[2] .trim()
47
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
48
+ value = value.slice(1, -1)
49
+ }
50
+ return value.trim() === '' ? undefined : value
51
+ }
52
+ return undefined
53
+ }
54
+
55
+ /** frontmatter 之后的部分。 */
56
+ function skillBody(text ) {
57
+ if (!text.startsWith('---')) return text.trim()
58
+ const end = text.indexOf('\n---', 3)
59
+ if (end < 0) return text.trim()
60
+ const after = text.indexOf('\n', end + 1)
61
+ return (after < 0 ? '' : text.slice(after + 1)).trim()
62
+ }
63
+
64
+ /**
65
+ * 读一个技能目录成候选。**这里就把错误抛出来**:注册表要求候选合法,否则整批
66
+ * 观察失败;宁可启动时看见一行明确日志,也不要"技能悄悄不存在"。
67
+ */
68
+ function candidateFor(name ) {
69
+ const directory = join(SKILLS_ROOT, name)
70
+ const path = join(directory, 'SKILL.md')
71
+ const text = readFileSync(path, 'utf8')
72
+ const description = frontmatterField(text, 'description')
73
+ if (description === undefined) {
74
+ throw new Error(`随包技能 "${name}" 的 SKILL.md 缺少 description:${path}`)
75
+ }
76
+ return {
77
+ name,
78
+ description,
79
+ invocation: { modelInvocable: true, userInvocable: true },
80
+ provider: PROVIDER,
81
+ source: 'bundled',
82
+ rank: BUNDLED_SKILL_RANK,
83
+ resourceBase: { kind: 'directory', path: directory },
84
+ locator: path,
85
+ path,
86
+ }
87
+ }
88
+
89
+ /** 磁盘上实际存在的技能名(目录里有 SKILL.md 的)。 */
90
+ function skillNames() {
91
+ try {
92
+ if (!existsSync(SKILLS_ROOT)) return []
93
+ return readdirSync(SKILLS_ROOT, { withFileTypes: true })
94
+ .filter((entry) => entry.isDirectory() && existsSync(join(SKILLS_ROOT, entry.name, 'SKILL.md')))
95
+ .map((entry) => entry.name)
96
+ .sort()
97
+ } catch {
98
+ return []
99
+ }
100
+ }
101
+
102
+ /**
103
+ * 注册随包技能。失败只记一行日志:技能资产出问题不该把记忆插件(含工具与面板)
104
+ * 一起带下水 —— 与仓库"任何半边抛错只写一行日志"的铁律一致。
105
+ */
106
+ export function mountBundledSkills(ctx
107
+
108
+
109
+
110
+
111
+ ) {
112
+ // 0.35.1 修复:调用方现在通过 ctx.inject(['skills'], scope => ...) 在服务**就绪后**
113
+ // 才进来,所以这里拿到的 ctx 就是已注入的 scope,skills 一定在。
114
+ // 保留 ctx.get 兜底是为了兼容仍在 apply 里直接调用它的老路径(测试 / 独立加载)。
115
+ let skills
116
+ try {
117
+ skills = (ctx.skills ?? ctx.get?.('skills'))
118
+ } catch {
119
+ skills = undefined
120
+ }
121
+ if (skills === undefined || typeof skills.registerProvider !== 'function') {
122
+ ctx.logger?.warn?.('dsh-memory: skills 服务尚未就绪,随包技能未注册(记忆功能不受影响)')
123
+ return
124
+ }
125
+
126
+ const names = skillNames()
127
+ if (names.length === 0) {
128
+ ctx.logger?.warn?.(`dsh-memory: 没找到随包技能目录 ${SKILLS_ROOT}`)
129
+ return
130
+ }
131
+
132
+ const build = () => {
133
+ const candidates = names.map(candidateFor)
134
+ const byName = new Map(candidates.map((candidate) => [candidate.name, candidate]))
135
+ return {
136
+ name: PROVIDER,
137
+ list: () => Promise.resolve(candidates),
138
+ // 正文每次现读:改 SKILL.md 下一次加载就生效(注册表只缓存目录)。
139
+ get: (winner ) => {
140
+ const known = byName.get(winner?.name)
141
+ if (known === undefined) throw new Error(`随包技能 "${String(winner?.name)}" 不存在`)
142
+ const { rank: _rank, locator: _locator, ...summary } = known
143
+ return Promise.resolve({ ...summary, content: skillBody(readFileSync(known.path, 'utf8')) })
144
+ },
145
+ }
146
+ }
147
+
148
+ try {
149
+ if (typeof ctx.effect === 'function') ctx.effect(() => skills .registerProvider (build), 'dsh-memory: bundled skills')
150
+ else skills.registerProvider(build)
151
+ } catch (error) {
152
+ ctx.logger?.warn?.(`dsh-memory: 随包技能未能注册:${error instanceof Error ? error.message : String(error)}`)
153
+ }
154
+ }
155
+
156
+
157
+ //# sourceURL=source/memory-plugin/src/skills.ts
@@ -20,7 +20,7 @@ import {
20
20
 
21
21
 
22
22
  } from './index.js'
23
- import { renderBlockResult, renderGetResult, renderListResult, renderScopesResult, renderSearchResult } from './render.js'
23
+ import { renderBlockResult, renderGetResult, renderHooksResult, renderListResult, renderScopesResult, renderSearchResult } from './render.js'
24
24
  import { resolveCurrentScopes, scopeDisplayName, sessionShortId, } from '../provider/scope.js'
25
25
 
26
26
  export const name = 'dsh-tool-memory'
@@ -171,6 +171,11 @@ export function apply(ctx , config = {}) {
171
171
  const agent = (exec )?.agent
172
172
  return renderBlockResult(value, (scope) => renderScope(scope, agent))
173
173
  })
174
+
175
+ register(tools.memory_hooks, (value, _args, exec) => {
176
+ const agent = (exec )?.agent
177
+ return renderHooksResult(value, (scope) => renderScope(scope, agent))
178
+ })
174
179
  }
175
180
 
176
181