@cheemsup/dsh-plugin-console 0.0.0-stage → 0.2.0

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 (101) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +95 -3
  3. package/cordis.patch.yml +5 -0
  4. package/icon.svg +203 -0
  5. package/lib/client.activity.js +222 -0
  6. package/lib/client.apply.js +171 -0
  7. package/lib/client.changes.js +206 -0
  8. package/lib/client.cleanup.js +270 -0
  9. package/lib/client.control.js +247 -0
  10. package/lib/client.dialog.js +77 -0
  11. package/lib/client.disable-preview.js +904 -0
  12. package/lib/client.draft.js +280 -0
  13. package/lib/client.editor-messages.js +421 -0
  14. package/lib/client.editor-store.js +266 -0
  15. package/lib/client.editor.js +433 -0
  16. package/lib/client.effects.js +115 -0
  17. package/lib/client.impact-tree.js +487 -0
  18. package/lib/client.influence.js +361 -0
  19. package/lib/client.js +246 -0
  20. package/lib/client.page.js +646 -0
  21. package/lib/client.plugin-filters.js +62 -0
  22. package/lib/client.plugins.js +506 -0
  23. package/lib/client.preview-messages.js +506 -0
  24. package/lib/client.preview-raw.js +132 -0
  25. package/lib/client.preview-store.js +128 -0
  26. package/lib/client.preview-tools.js +194 -0
  27. package/lib/client.preview.js +448 -0
  28. package/lib/client.relation-graph.js +364 -0
  29. package/lib/client.schema.js +327 -0
  30. package/lib/client.search.js +409 -0
  31. package/lib/client.session-detail.js +503 -0
  32. package/lib/client.sessions.js +495 -0
  33. package/lib/client.shared.js +562 -0
  34. package/lib/client.store.js +452 -0
  35. package/lib/client.styles.js +589 -0
  36. package/lib/client.template-card.js +240 -0
  37. package/lib/client.tools.js +366 -0
  38. package/lib/client.workspace-picker.js +204 -0
  39. package/lib/host/activity.js +252 -0
  40. package/lib/host/assembly-preview.js +244 -0
  41. package/lib/host/attribution.js +341 -0
  42. package/lib/host/catalog.js +133 -0
  43. package/lib/host/categorize.js +40 -0
  44. package/lib/host/config-layers.js +589 -0
  45. package/lib/host/constants.js +69 -0
  46. package/lib/host/control.js +159 -0
  47. package/lib/host/disable-preview.js +651 -0
  48. package/lib/host/entries.js +289 -0
  49. package/lib/host/fiber.js +86 -0
  50. package/lib/host/fs.js +99 -0
  51. package/lib/host/health.js +178 -0
  52. package/lib/host/http.js +65 -0
  53. package/lib/host/impact.js +138 -0
  54. package/lib/host/injection-owners.js +60 -0
  55. package/lib/host/layers.js +132 -0
  56. package/lib/host/masks.js +145 -0
  57. package/lib/host/modes.js +96 -0
  58. package/lib/host/names.js +44 -0
  59. package/lib/host/patch-config.js +554 -0
  60. package/lib/host/patch-scan.js +103 -0
  61. package/lib/host/preview-conditions.js +281 -0
  62. package/lib/host/preview-contexts.js +174 -0
  63. package/lib/host/preview-envelope.js +31 -0
  64. package/lib/host/preview-instructions.js +450 -0
  65. package/lib/host/preview-messages.js +284 -0
  66. package/lib/host/preview-modules.js +233 -0
  67. package/lib/host/preview-skills.js +200 -0
  68. package/lib/host/prompt.js +213 -0
  69. package/lib/host/recipe-overlay.js +209 -0
  70. package/lib/host/request-preview.js +114 -0
  71. package/lib/host/routes/activation.js +96 -0
  72. package/lib/host/routes/activity.js +22 -0
  73. package/lib/host/routes/apply.js +93 -0
  74. package/lib/host/routes/cleanup.js +62 -0
  75. package/lib/host/routes/control.js +22 -0
  76. package/lib/host/routes/disable-preview.js +19 -0
  77. package/lib/host/routes/impact.js +19 -0
  78. package/lib/host/routes/operations.js +22 -0
  79. package/lib/host/routes/preview.js +58 -0
  80. package/lib/host/routes/session-influence.js +23 -0
  81. package/lib/host/routes/snapshot.js +21 -0
  82. package/lib/host/routes/template.js +54 -0
  83. package/lib/host/routes/templates.js +28 -0
  84. package/lib/host/scope-impact.js +125 -0
  85. package/lib/host/session-events.js +39 -0
  86. package/lib/host/session-influence.js +467 -0
  87. package/lib/host/sessions.js +293 -0
  88. package/lib/host/snapshot.js +218 -0
  89. package/lib/host/source-scan.js +225 -0
  90. package/lib/host/templates/cleanup.js +219 -0
  91. package/lib/host/templates/inheritance.js +144 -0
  92. package/lib/host/templates/materialize.js +317 -0
  93. package/lib/host/templates/message-overlay.js +184 -0
  94. package/lib/host/templates/repository.js +323 -0
  95. package/lib/host/templates/store.js +131 -0
  96. package/lib/host/tool-set.js +150 -0
  97. package/lib/host/tools.js +129 -0
  98. package/lib/index.js +106 -0
  99. package/locale/en.json +6 -0
  100. package/locale/zh.json +6 -0
  101. package/package.json +124 -6
@@ -0,0 +1,225 @@
1
+ /**
2
+ * 从包的源码里静态提取它注册的工具名与提示词段名。
3
+ *
4
+ * 为什么必须静态扫:`tools.register(definition)` 只把 `definition` 存进注册表,
5
+ * `systemPrompt.section({name})` 也只把对象存进 `NamedEntries`——两者都不保留
6
+ * 「谁注册的」。唯一可靠的归属信息是 `fiber.getEffects()` 的 label,而它只有
7
+ * `tools.register()` 这种不带名字的通用文案。
8
+ *
9
+ * 因此这里读包自己的 lib 目录,按 `defineTool({ name })`、
10
+ * `systemPrompt.section/context({ name })` 的写法提取名字。这是**源码级**事实,
11
+ * 不是运行时推断:名字确实写在代码里,只是运行时的注册表把它丢掉了。
12
+ *
13
+ * 扫描实现有两条务实约束:
14
+ * - 不假设只有 `lib/index.js`。第三方插件可能拆成多个 chunk,所以递归扫
15
+ * `lib/**\/*.{js,mjs,cjs}`;文件数与总字节都有上限,避免大包拖住快照。
16
+ * - 用平衡花括号截取对象字面量,而不是固定字符窗口;`name` 可能写在几十行
17
+ * 之后,固定窗口会截断,也可能把下一个调用的 name 收进来。
18
+ *
19
+ * 结果按「包目录 + 文件 stat」缓存:快照每次都会重扫,但包没变就不重新读盘。
20
+ * @module dsh-plugin-console/host/source-scan
21
+ */
22
+
23
+ import { listDirDetailed, readTextFile, statFile } from './fs.js'
24
+
25
+ /** 空结果;包目录缺失或读不到源码时返回它。 */
26
+ const EMPTY = { tools: [], sections: [], contexts: [], variables: [] }
27
+
28
+ /** 单个包最多扫多少个 JS 文件 / 多少字节。 */
29
+ const MAX_FILES = 200
30
+ const MAX_BYTES = 4 * 1024 * 1024
31
+
32
+ /** 递归深度上限:lib 下的目录通常只有一两层。 */
33
+ const MAX_DEPTH = 4
34
+
35
+ /** packageDir → { stamp, result }。 */
36
+ const CACHE = new Map()
37
+ const CACHE_LIMIT = 128
38
+
39
+ /**
40
+ * 递归列出 lib 下的 JS 文件;失败/超限时返回已收集的部分。
41
+ * @param {string} dir - 目录。
42
+ * @param {number} depth - 当前深度。
43
+ * @param {string[]} out - 收集数组。
44
+ * @returns {Promise<string[]>} 文件路径。
45
+ */
46
+ async function jsFiles(dir, depth = 0, out = []) {
47
+ if (depth > MAX_DEPTH || out.length >= MAX_FILES) return out
48
+ const entries = await listDirDetailed(dir)
49
+ for (const entry of entries) {
50
+ if (out.length >= MAX_FILES) break
51
+ const full = `${dir}/${entry.name}`
52
+ if (entry.isFile && /\.(?:mjs|cjs|js)$/.test(entry.name)) {
53
+ out.push(full)
54
+ continue
55
+ }
56
+ // 只递归真实子目录;跳过 node_modules 与隐藏目录,避免把依赖当成本包源码。
57
+ if (entry.isDirectory && !entry.name.startsWith('.') && entry.name !== 'node_modules') {
58
+ await jsFiles(full, depth + 1, out)
59
+ }
60
+ }
61
+ return out
62
+ }
63
+
64
+ /** 文件列表的轻量指纹:路径 + mtime + size。 */
65
+ async function stampOf(files) {
66
+ const parts = []
67
+ for (const file of files) {
68
+ const stat = await statFile(file)
69
+ parts.push(`${file}:${stat?.mtimeMs ?? 0}:${stat?.size ?? 0}`)
70
+ }
71
+ return parts.join('|')
72
+ }
73
+
74
+ /** 引号/斜杠/花括号的字符码:避免在源码里写裸引号,静态体检会把它们当成字符串边界。 */
75
+ const QUOTE_DOUBLE = 34
76
+ const QUOTE_SINGLE = 39
77
+ const QUOTE_TEMPLATE = 96
78
+ const BACKSLASH = 92
79
+ const SLASH = 47
80
+ const STAR = 42
81
+ const NEWLINE = 10
82
+ const OPEN_BRACE = 123
83
+ const CLOSE_BRACE = 125
84
+
85
+ /** 用字符码拼引号类,避免本文件自身出现会被静态体检误判的裸引号。 */
86
+ const QUOTE_CLASS = '["' + String.fromCharCode(QUOTE_SINGLE, QUOTE_TEMPLATE) + ']'
87
+ const NAME_PATTERN = new RegExp('\\bname\\s*:\\s*(' + QUOTE_CLASS + ')([^"' + String.fromCharCode(QUOTE_SINGLE, QUOTE_TEMPLATE) + ']*)\\1')
88
+ const CONSTANT_PATTERN = new RegExp(
89
+ '\\bconst\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*(' + QUOTE_CLASS + ')([^"' + String.fromCharCode(QUOTE_SINGLE, QUOTE_TEMPLATE) + ']*)\\2',
90
+ 'g',
91
+ )
92
+
93
+ /**
94
+ * 从 `{` 开始截取完整的对象字面量;字符串/注释里的括号不参与配对。
95
+ * 找不到配对的 `}` 时退回一个有限窗口,至少保留可读内容。
96
+ * @param {string} text - 源码。
97
+ * @param {number} start - `{` 的下标。
98
+ * @returns {string} 对象字面量文本。
99
+ */
100
+ function objectSpan(text, start) {
101
+ let depth = 0
102
+ let quote = 0
103
+ let lineComment = false
104
+ let blockComment = false
105
+ for (let index = start; index < text.length; index++) {
106
+ const code = text.charCodeAt(index)
107
+ const next = text.charCodeAt(index + 1)
108
+ if (lineComment) {
109
+ if (code === NEWLINE) lineComment = false
110
+ continue
111
+ }
112
+ if (blockComment) {
113
+ if (code === STAR && next === SLASH) {
114
+ blockComment = false
115
+ index++
116
+ }
117
+ continue
118
+ }
119
+ if (quote !== 0) {
120
+ if (code === BACKSLASH) {
121
+ index++
122
+ continue
123
+ }
124
+ if (code === quote) quote = 0
125
+ continue
126
+ }
127
+ if (code === SLASH && next === SLASH) {
128
+ lineComment = true
129
+ index++
130
+ continue
131
+ }
132
+ if (code === SLASH && next === STAR) {
133
+ blockComment = true
134
+ index++
135
+ continue
136
+ }
137
+ if (code === QUOTE_DOUBLE || code === QUOTE_SINGLE || code === QUOTE_TEMPLATE) {
138
+ quote = code
139
+ continue
140
+ }
141
+ if (code === OPEN_BRACE) depth++
142
+ else if (code === CLOSE_BRACE) {
143
+ depth--
144
+ if (depth === 0) return text.slice(start, index + 1)
145
+ }
146
+ }
147
+ return text.slice(start, Math.min(text.length, start + 2000))
148
+ }
149
+
150
+ /**
151
+ * 从一个对象字面量里取 `name`:字面量、常量引用,或大写占位名。
152
+ * @param {string} span - 对象字面量。
153
+ * @param {Map<string, string>} constants - 源码里的字符串常量。
154
+ * @returns {string | undefined} 名字或 undefined。
155
+ */
156
+ function nameIn(span, constants) {
157
+ const literal = span.match(NAME_PATTERN)
158
+ if (literal) return literal[2]
159
+ const identifier = span.match(/\bname\s*:\s*([A-Za-z_$][\w$]*)/)
160
+ if (identifier) {
161
+ const resolved = constants.get(identifier[1])
162
+ if (resolved !== undefined) return resolved
163
+ // 查不到值的常量保留成占位,便于界面显示「这里有个名字但解析不出来」。
164
+ if (/^[A-Z][A-Z0-9_]{2,}$/.test(identifier[1])) return '⟨' + identifier[1] + '⟩'
165
+ }
166
+ return undefined
167
+ }
168
+
169
+ /**
170
+ * 收集某一类调用里的 name。
171
+ * @param {string} text - 合并后的源码。
172
+ * @param {RegExp} pattern - 匹配到 `{` 的调用模式。
173
+ * @param {Map<string, string>} constants - 字符串常量表。
174
+ * @returns {string[]} 名字列表。
175
+ */
176
+ function collect(text, pattern, constants) {
177
+ const names = new Set()
178
+ for (const match of text.matchAll(pattern)) {
179
+ const open = text.indexOf('{', match.index)
180
+ if (open < 0 || open > match.index + 160) continue
181
+ const name = nameIn(objectSpan(text, open), constants)
182
+ if (name !== undefined) names.add(name)
183
+ }
184
+ return [...names]
185
+ }
186
+
187
+ /**
188
+ * @param {string} packageDir - 包的根目录。
189
+ * @returns {Promise<{tools: string[], sections: string[], contexts: string[], variables: string[]}>} 静态提取结果。
190
+ */
191
+ export async function scanPackageRegistrations(packageDir) {
192
+ if (typeof packageDir !== 'string') return EMPTY
193
+ const files = await jsFiles(`${packageDir}/lib`)
194
+ if (files.length === 0) return EMPTY
195
+
196
+ const stamp = await stampOf(files)
197
+ const cached = CACHE.get(packageDir)
198
+ if (cached !== undefined && cached.stamp === stamp) return cached.result
199
+
200
+ let text = ''
201
+ let bytes = 0
202
+ for (const file of files) {
203
+ if (bytes >= MAX_BYTES) break
204
+ const part = await readTextFile(file)
205
+ if (part === null) continue
206
+ bytes += part.length
207
+ text += '\n' + part
208
+ }
209
+
210
+ const constants = new Map()
211
+ for (const match of text.matchAll(CONSTANT_PATTERN)) {
212
+ constants.set(match[1], match[3])
213
+ }
214
+
215
+ const result = {
216
+ tools: collect(text, /defineTool\s*\(\s*\{/g, constants),
217
+ sections: collect(text, /systemPrompt\.section\s*\(\s*\{/g, constants),
218
+ contexts: collect(text, /systemPrompt\.context\s*\(\s*\{/g, constants),
219
+ variables: collect(text, /systemPrompt\.variable\s*\(\s*\{/g, constants),
220
+ }
221
+
222
+ CACHE.set(packageDir, { stamp, result })
223
+ if (CACHE.size > CACHE_LIMIT) CACHE.delete(CACHE.keys().next().value)
224
+ return result
225
+ }
@@ -0,0 +1,219 @@
1
+ /**
2
+ * 模板数据的清理。
3
+ *
4
+ * 两种范围:
5
+ * - workspace:只清该工作区(含它派生的子 Agent)的 manifest 与 activation,
6
+ * 模板定义和历史保留;
7
+ * - all:清空四张表并删除存储文件,下一次写入自动重建空单元。
8
+ *
9
+ * 运行中的会话不受影响:这里不碰 `appliedHandles`,已经注册到 agent scope 上的
10
+ * 提示词段与工具限制会保留到会话结束(或 DSH 重启)。这是刻意的——清理的是
11
+ * 持久记录,不是正在运行的那一步。
12
+ * @module dsh-plugin-console/host/templates/cleanup
13
+ */
14
+
15
+ import { rm } from 'node:fs/promises'
16
+ import { join } from 'node:path'
17
+ import { resetTemplateStore, templateTable } from './store.js'
18
+
19
+ /** 存储文件名;与 storage-json 的 single 布局一致。 */
20
+ const UNIT_FILE = 'plugin_console_templates.json'
21
+
22
+ /**
23
+ * 收集当前宿主认识的所有会话 header。
24
+ *
25
+ * 两路来源:持久化列表(含冷会话)与进程内会话(可能还没进持久化列表)。
26
+ * 都拿不到就只靠工作区自己记录的 sessionIds,派生会话会漏——所以两路都试。
27
+ * @param {object} ctx - host 插件上下文。
28
+ * @returns {Promise<Array<object>>} 去重后的 header 列表。
29
+ */
30
+ async function knownHeaders(ctx) {
31
+ const headers = []
32
+ const seen = new Set()
33
+ const add = (header) => {
34
+ if (header === null || typeof header !== 'object') return
35
+ if (typeof header.id !== 'string' || seen.has(header.id)) return
36
+ seen.add(header.id)
37
+ headers.push(header)
38
+ }
39
+
40
+ try {
41
+ const persistence = ctx.get('sessionPersistence')
42
+ if (typeof persistence?.list === 'function') {
43
+ for (const snapshot of await persistence.list()) add(snapshot?.header)
44
+ }
45
+ } catch {
46
+ // 读不到持久化列表时继续用进程内会话
47
+ }
48
+ try {
49
+ const sessions = ctx.get('sessions')
50
+ if (typeof sessions?.list === 'function') {
51
+ for (const session of sessions.list()) add(session?.header)
52
+ }
53
+ } catch {
54
+ // 同上
55
+ }
56
+ return headers
57
+ }
58
+
59
+ /**
60
+ * 把一个工作区展开成「它自己的会话 + 所有派生会话」。
61
+ *
62
+ * 子 Agent 不写进 workspaceRegistry 的 sessionIds,所以只看工作区记录会漏掉
63
+ * 继承出来的绑定。这里按 header.parentSession 反复扩展,直到没有新节点。
64
+ * @param {object} ctx - host 插件上下文。
65
+ * @param {string} workspaceId - 工作区 id。
66
+ * @returns {Promise<Set<string> | undefined>} 会话 id 集合;工作区不存在时 undefined。
67
+ */
68
+ async function workspaceSessionIds(ctx, workspaceId) {
69
+ let workspaces
70
+ try {
71
+ workspaces = ctx.get('workspaceRegistry')?.list?.() ?? []
72
+ } catch {
73
+ workspaces = []
74
+ }
75
+ const workspace = workspaces.find((candidate) => candidate?.id === workspaceId)
76
+ if (workspace === undefined) return undefined
77
+
78
+ const ids = new Set((workspace.sessionIds ?? []).filter((id) => typeof id === 'string'))
79
+ const headers = await knownHeaders(ctx)
80
+ let grew = true
81
+ while (grew) {
82
+ grew = false
83
+ for (const header of headers) {
84
+ if (ids.has(header.id)) continue
85
+ if (typeof header.parentSession === 'string' && ids.has(header.parentSession)) {
86
+ ids.add(header.id)
87
+ grew = true
88
+ }
89
+ }
90
+ }
91
+ return ids
92
+ }
93
+
94
+ /**
95
+ * 清理一个工作区里的模板绑定。
96
+ * @param {object} ctx - host 插件上下文。
97
+ * @param {object} state - 模板存储状态(调用方已 ensure)。
98
+ * @param {string} workspaceId - 工作区 id。
99
+ * @returns {Promise<object | undefined>} 计数;工作区不存在时 undefined。
100
+ */
101
+ export async function clearWorkspaceTemplateData(ctx, state, workspaceId) {
102
+ const ids = await workspaceSessionIds(ctx, workspaceId)
103
+ if (ids === undefined) return undefined
104
+
105
+ const manifests = templateTable(state, 'manifests')
106
+ const activations = templateTable(state, 'activations')
107
+ const masks = templateTable(state, 'masks')
108
+ const touched = new Set()
109
+ let removedManifests = 0
110
+ let removedActivations = 0
111
+ let removedMasks = 0
112
+
113
+ for (const [sessionId] of [...manifests.entries()]) {
114
+ if (!ids.has(sessionId)) continue
115
+ await manifests.delete(sessionId)
116
+ touched.add(sessionId)
117
+ removedManifests++
118
+ }
119
+ for (const [sessionId] of [...activations.entries()]) {
120
+ if (!ids.has(sessionId)) continue
121
+ await activations.delete(sessionId)
122
+ touched.add(sessionId)
123
+ removedActivations++
124
+ }
125
+ for (const [key, record] of [...masks.entries()]) {
126
+ if (typeof record?.sessionId !== 'string' || !ids.has(record.sessionId)) continue
127
+ await masks.delete(key)
128
+ touched.add(record.sessionId)
129
+ removedMasks++
130
+ }
131
+
132
+ return {
133
+ sessionCount: ids.size,
134
+ touchedSessions: touched.size,
135
+ removedManifests,
136
+ removedActivations,
137
+ removedMasks,
138
+ keptTemplates: [...templateTable(state, 'templates').entries()].length,
139
+ }
140
+ }
141
+
142
+ /**
143
+ * 清理单个会话的模板绑定。
144
+ *
145
+ * 只动这一条会话:不展开子 Agent,也不碰同一工作区的其他会话。运行中的会话
146
+ * 同样不受影响——清的是持久记录,已注册到 agent scope 的内容保留到会话结束。
147
+ * @param {object} state - 模板存储状态(调用方已 ensure)。
148
+ * @param {string} sessionId - 目标会话 id。
149
+ * @returns {Promise<object>} 各表删除计数。
150
+ */
151
+ export async function clearSessionTemplateData(state, sessionId) {
152
+ const manifests = templateTable(state, 'manifests')
153
+ const activations = templateTable(state, 'activations')
154
+ const masks = templateTable(state, 'masks')
155
+ const removedManifests = manifests.get(sessionId) !== undefined ? 1 : 0
156
+ const removedActivations = activations.get(sessionId) !== undefined ? 1 : 0
157
+ await manifests.delete(sessionId)
158
+ await activations.delete(sessionId)
159
+
160
+ let removedMasks = 0
161
+ for (const [key, record] of [...masks.entries()]) {
162
+ if (typeof record?.sessionId !== 'string' || record.sessionId !== sessionId) continue
163
+ await masks.delete(key)
164
+ removedMasks++
165
+ }
166
+
167
+ return {
168
+ sessionId,
169
+ removedManifests,
170
+ removedActivations,
171
+ removedMasks,
172
+ keptTemplates: [...templateTable(state, 'templates').entries()].length,
173
+ }
174
+ }
175
+
176
+ /**
177
+ * 清空全部模板数据并删除存储文件。
178
+ *
179
+ * 先统计、再关闭域(排空在途写入),最后删文件。关闭后把 state 退回「从未打开」,
180
+ * 下一次访问会重新打开一个空单元;如果文件删除失败,错误会带回去,界面能看见。
181
+ * @param {object} ctx - host 插件上下文。
182
+ * @param {object} state - 模板存储状态(调用方已 ensure)。
183
+ * @returns {Promise<object>} 计数与文件删除结果。
184
+ */
185
+ export async function clearAllTemplateData(ctx, state) {
186
+ // 打开失败(坏记录、版本不匹配)时也要能清理:没有可读的表就按 0 计,
187
+ // 直接关域、删文件,让下一次访问从空单元开始。这是坏数据的恢复出口。
188
+ const hasStore = state.domain !== undefined || state.memory !== undefined
189
+ const countOf = (name) => hasStore ? [...templateTable(state, name).entries()].length : 0
190
+ const counts = {
191
+ removedTemplates: countOf('templates'),
192
+ removedRevisions: countOf('revisions'),
193
+ removedManifests: countOf('manifests'),
194
+ removedActivations: countOf('activations'),
195
+ removedMasks: countOf('masks'),
196
+ removedOperations: countOf('operations'),
197
+ }
198
+
199
+ if (state.domain !== undefined) await state.domain.close()
200
+ resetTemplateStore(state)
201
+
202
+ const home = ctx.get('profileContext')?.home
203
+ if (typeof home !== 'string' || home.length === 0) {
204
+ return { ...counts, fileDeleted: false, fileError: 'profileContext.home 不可用,未能删除存储文件' }
205
+ }
206
+
207
+ const path = join(home, 'storages', UNIT_FILE)
208
+ try {
209
+ await rm(path, { force: true })
210
+ return { ...counts, fileDeleted: true, filePath: path }
211
+ } catch (error) {
212
+ return {
213
+ ...counts,
214
+ fileDeleted: false,
215
+ filePath: path,
216
+ fileError: error instanceof Error ? error.message : String(error),
217
+ }
218
+ }
219
+ }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * 子 Agent 的模板继承。
3
+ *
4
+ * DSH 创建子 Agent 时只复制模式组合(provider / model / preset)与工具注册,
5
+ * 不会复制父会话在运行时注册的提示词段——模板物化出来的段是运行时注册,
6
+ * 因此子会话默认看不到它。
7
+ *
8
+ * 这里监听 `agent/created`,在子 Agent 的首个 turn 之前补做物化:
9
+ * - 会话自己有 manifest(resume / startup / clear)→ 按它重放;
10
+ * - 自己没有,但 header.parentSession 指向的父会话有 manifest → 复制一份
11
+ * 父会话的 recipe(保持快照语义),写成自己的 manifest 再物化。
12
+ *
13
+ * 监听器不能抛错:`agent/created` 是串行生命周期,一个监听器 reject 会让
14
+ * 整个 agent 创建失败。所有失败只记日志。
15
+ * @module dsh-plugin-console/host/templates/inheritance
16
+ */
17
+
18
+ import { applyRecipeToSession } from './materialize.js'
19
+ import { getManifest, putManifest } from './repository.js'
20
+ import { ensureTemplateStore, templateTable } from './store.js'
21
+
22
+ /**
23
+ * 会话当前是否启用。
24
+ *
25
+ * 没有 activation 记录 = 启用,所以「关」必须是显式写下的 `enabled: false`。
26
+ * @param {object} state - 模板存储状态。
27
+ * @param {string} sessionId - 会话 id。
28
+ * @returns {boolean} 是否启用。
29
+ */
30
+ function isEnabled(state, sessionId) {
31
+ const record = templateTable(state, 'activations').get(sessionId)
32
+ return record === undefined ? true : record.enabled === true
33
+ }
34
+
35
+ /**
36
+ * 取一个会话自己的模式。
37
+ *
38
+ * header 是持久化真源(冷会话只看 header);`agentPresets` 只做兜底,
39
+ * 缺失时返回 undefined,让预览退回默认模式。
40
+ * @param {object} ctx - host 插件上下文。
41
+ * @param {object} session - 会话对象。
42
+ * @returns {string | undefined} 模式 id。
43
+ */
44
+ function presetOf(ctx, session) {
45
+ const header = session?.header
46
+ if (typeof header?.agentPreset === 'string') return header.agentPreset
47
+ try {
48
+ return ctx.get('agentPresets')?.presetForSession?.(session) ?? undefined
49
+ } catch {
50
+ return undefined
51
+ }
52
+ }
53
+
54
+ /**
55
+ * 为一个刚创建的 agent 决定是否套模板,并在需要时物化。
56
+ *
57
+ * 规则:
58
+ * 1. 自己有 manifest → 按自己的重放(resume / clear 走这条);
59
+ * 2. 自己没有、header.parentSession 有 manifest → 继承父会话的 recipe;
60
+ * 3. 任一方显式关闭(activation.enabled === false)→ 不套。
61
+ *
62
+ * 子会话继承时会写一份自己的 manifest,并带 `inheritedFrom`。这样:
63
+ * - 会话页能显示它确实绑了模板,也能单独关掉;
64
+ * - 父模板之后改版不影响已经创建的子会话(manifest 仍是快照);
65
+ * - resume 时按这份 manifest 重新物化,不必再找父会话。
66
+ * @param {object} ctx - host 插件上下文。
67
+ * @param {object} state - 模板存储状态。
68
+ * @param {object} agent - 刚创建的 agent。
69
+ * @returns {Promise<object>} 处理结果(`applied` / `inherited` / `reason`)。
70
+ */
71
+ export async function inheritTemplateForAgent(ctx, state, agent) {
72
+ const sessionId = typeof agent?.id === 'string' ? agent.id : agent?.session?.id
73
+ const header = agent?.session?.header
74
+ if (typeof sessionId !== 'string' || header === undefined || header === null) {
75
+ return { applied: false, reason: 'no-session' }
76
+ }
77
+
78
+ await ensureTemplateStore(ctx, state)
79
+
80
+ const own = getManifest(state, sessionId)
81
+ if (own !== undefined) {
82
+ if (!isEnabled(state, sessionId)) return { applied: false, reason: 'activation-disabled' }
83
+ const result = await applyRecipeToSession(ctx, sessionId, own.recipe, presetOf(ctx, agent.session))
84
+ return { applied: result.applied === true, inherited: false, result }
85
+ }
86
+
87
+ const parentId = typeof header.parentSession === 'string' ? header.parentSession : undefined
88
+ if (parentId === undefined) return { applied: false, reason: 'no-parent' }
89
+ // 子会话自己显式关过:不继承。这是「子自己被关过时以子为准」的落点。
90
+ if (!isEnabled(state, sessionId)) return { applied: false, reason: 'activation-disabled' }
91
+
92
+ const parent = getManifest(state, parentId)
93
+ if (parent === undefined) return { applied: false, reason: 'parent-unbound' }
94
+ // 父会话关掉了模板,子树也不该继承它。
95
+ if (!isEnabled(state, parentId)) return { applied: false, reason: 'parent-disabled' }
96
+ if (typeof parent.source?.templateId !== 'string' || parent.recipe === null || typeof parent.recipe !== 'object') {
97
+ return { applied: false, reason: 'parent-manifest-incomplete' }
98
+ }
99
+
100
+ const manifest = {
101
+ schemaVersion: 1,
102
+ sessionId,
103
+ source: {
104
+ templateId: parent.source.templateId,
105
+ revision: parent.source.revision,
106
+ // 名字也随快照复制:父模板之后改名或删除,子会话仍显示应用时的名字。
107
+ ...(typeof parent.source.templateName === 'string' ? { templateName: parent.source.templateName } : {}),
108
+ },
109
+ recipe: parent.recipe,
110
+ createdAt: Date.now(),
111
+ inheritedFrom: parentId,
112
+ }
113
+ // 先落 manifest:即使这一次物化失败,会话页也能看出它「登记为继承」,
114
+ // resume 时还会按它再试一次。
115
+ await putManifest(state, sessionId, manifest)
116
+
117
+ const result = await applyRecipeToSession(ctx, sessionId, manifest.recipe, presetOf(ctx, agent.session))
118
+ if (result.applied === true) {
119
+ manifest.applied = result.applied0
120
+ manifest.errors = result.errors
121
+ await putManifest(state, sessionId, manifest)
122
+ }
123
+ return { applied: result.applied === true, inherited: true, result, manifest }
124
+ }
125
+
126
+ /**
127
+ * 安装模板继承监听。
128
+ *
129
+ * 不需要 connection——`agent/created` 来自 agent 注册表,插件加载时就能挂上。
130
+ * @param {object} ctx - host 插件上下文。
131
+ * @param {object} state - 模板存储状态。
132
+ * @returns {void}
133
+ */
134
+ export function installTemplateInheritance(ctx, state) {
135
+ ctx.on('agent/created', async ({ agent }) => {
136
+ try {
137
+ await inheritTemplateForAgent(ctx, state, agent)
138
+ } catch (error) {
139
+ ctx.logger?.warn?.(
140
+ 'plugin-console: 模板继承失败:' + (error instanceof Error ? error.message : String(error)),
141
+ )
142
+ }
143
+ })
144
+ }