@cheemsup/dsh-plugin-console 0.0.0-stage → 0.1.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.
Files changed (90) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +85 -2
  3. package/cordis.patch.yml +5 -0
  4. package/lib/client.activity.js +222 -0
  5. package/lib/client.apply.js +171 -0
  6. package/lib/client.changes.js +206 -0
  7. package/lib/client.cleanup.js +270 -0
  8. package/lib/client.control.js +242 -0
  9. package/lib/client.dialog.js +77 -0
  10. package/lib/client.draft.js +280 -0
  11. package/lib/client.editor-messages.js +421 -0
  12. package/lib/client.editor-store.js +266 -0
  13. package/lib/client.editor.js +433 -0
  14. package/lib/client.effects.js +115 -0
  15. package/lib/client.influence.js +361 -0
  16. package/lib/client.js +216 -0
  17. package/lib/client.page.js +584 -0
  18. package/lib/client.plugin-filters.js +62 -0
  19. package/lib/client.plugins.js +504 -0
  20. package/lib/client.preview-messages.js +495 -0
  21. package/lib/client.preview-raw.js +132 -0
  22. package/lib/client.preview-store.js +128 -0
  23. package/lib/client.preview-tools.js +194 -0
  24. package/lib/client.preview.js +447 -0
  25. package/lib/client.schema.js +327 -0
  26. package/lib/client.search.js +408 -0
  27. package/lib/client.session-detail.js +503 -0
  28. package/lib/client.sessions.js +495 -0
  29. package/lib/client.shared.js +559 -0
  30. package/lib/client.store.js +452 -0
  31. package/lib/client.styles.js +524 -0
  32. package/lib/client.template-card.js +240 -0
  33. package/lib/client.tools.js +366 -0
  34. package/lib/client.workspace-picker.js +204 -0
  35. package/lib/host/activity.js +252 -0
  36. package/lib/host/assembly-preview.js +244 -0
  37. package/lib/host/attribution.js +307 -0
  38. package/lib/host/catalog.js +133 -0
  39. package/lib/host/categorize.js +40 -0
  40. package/lib/host/constants.js +66 -0
  41. package/lib/host/control.js +159 -0
  42. package/lib/host/entries.js +289 -0
  43. package/lib/host/fiber.js +86 -0
  44. package/lib/host/fs.js +99 -0
  45. package/lib/host/health.js +178 -0
  46. package/lib/host/http.js +65 -0
  47. package/lib/host/impact.js +132 -0
  48. package/lib/host/layers.js +132 -0
  49. package/lib/host/masks.js +145 -0
  50. package/lib/host/modes.js +96 -0
  51. package/lib/host/names.js +44 -0
  52. package/lib/host/patch-scan.js +103 -0
  53. package/lib/host/preview-conditions.js +281 -0
  54. package/lib/host/preview-contexts.js +174 -0
  55. package/lib/host/preview-envelope.js +31 -0
  56. package/lib/host/preview-instructions.js +450 -0
  57. package/lib/host/preview-messages.js +284 -0
  58. package/lib/host/preview-modules.js +233 -0
  59. package/lib/host/preview-skills.js +200 -0
  60. package/lib/host/prompt.js +213 -0
  61. package/lib/host/recipe-overlay.js +209 -0
  62. package/lib/host/request-preview.js +114 -0
  63. package/lib/host/routes/activation.js +96 -0
  64. package/lib/host/routes/activity.js +22 -0
  65. package/lib/host/routes/apply.js +93 -0
  66. package/lib/host/routes/cleanup.js +62 -0
  67. package/lib/host/routes/control.js +22 -0
  68. package/lib/host/routes/impact.js +19 -0
  69. package/lib/host/routes/operations.js +22 -0
  70. package/lib/host/routes/preview.js +58 -0
  71. package/lib/host/routes/session-influence.js +23 -0
  72. package/lib/host/routes/snapshot.js +21 -0
  73. package/lib/host/routes/template.js +54 -0
  74. package/lib/host/routes/templates.js +28 -0
  75. package/lib/host/scope-impact.js +125 -0
  76. package/lib/host/session-events.js +39 -0
  77. package/lib/host/session-influence.js +475 -0
  78. package/lib/host/sessions.js +293 -0
  79. package/lib/host/snapshot.js +218 -0
  80. package/lib/host/source-scan.js +225 -0
  81. package/lib/host/templates/cleanup.js +219 -0
  82. package/lib/host/templates/inheritance.js +144 -0
  83. package/lib/host/templates/materialize.js +317 -0
  84. package/lib/host/templates/message-overlay.js +184 -0
  85. package/lib/host/templates/repository.js +323 -0
  86. package/lib/host/templates/store.js +131 -0
  87. package/lib/host/tool-set.js +150 -0
  88. package/lib/host/tools.js +129 -0
  89. package/lib/index.js +103 -0
  90. package/package.json +111 -4
@@ -0,0 +1,323 @@
1
+ /**
2
+ * 模板仓库:对四张表的业务读写。
3
+ *
4
+ * 这一层不碰 HTTP,也不碰 agent——它只回答「模板有哪些、某个模板的最新配方是
5
+ * 什么、哪个会话绑了哪份配方、开关是开还是关」。物化在 `materialize.js`。
6
+ * @module dsh-plugin-console/host/templates/repository
7
+ */
8
+
9
+ import { appliedHandles } from './materialize.js'
10
+ import { ensureTemplateStore, newTemplateId, templateTable } from './store.js'
11
+
12
+ /**
13
+ * 读出「哪些会话绑定了模板、现在是否启用」。
14
+ *
15
+ * 两表合并成一条视图:manifest 提供「绑了哪个模板」,activation 提供「开没开」。
16
+ * 没有 activation 记录就是启用——这正是「默认开」这条语义的落点。
17
+ * @param {object} state - 模板存储状态。
18
+ * @returns {Promise<Map<string, object>>} 会话 id → 绑定信息。
19
+ */
20
+ export async function readTemplateBindings(state) {
21
+ const bindings = new Map()
22
+ const manifests = templateTable(state, 'manifests')
23
+ const heads = templateTable(state, 'templates')
24
+ const activations = templateTable(state, 'activations')
25
+
26
+ for (const [sessionId, manifest] of manifests.entries()) {
27
+ const templateId = manifest?.source?.templateId
28
+ const head = typeof templateId === 'string' ? heads.get(templateId) : undefined
29
+ const activation = activations.get(sessionId)
30
+ // 名字优先取模板头(跟着改名走);模板已删时退回应用时写进 manifest 的快照,
31
+ // 这样删除模板不会让会话那一行只剩一个裸 id。
32
+ const snapshotName = manifest?.source?.templateName
33
+ const templateName = typeof head?.name === 'string'
34
+ ? head.name
35
+ : typeof snapshotName === 'string' && snapshotName.length > 0 ? snapshotName : null
36
+ bindings.set(sessionId, {
37
+ sessionId,
38
+ templateId: typeof templateId === 'string' ? templateId : null,
39
+ templateName,
40
+ enabled: activation === undefined ? true : activation.enabled === true,
41
+ // 「登记为启用」和「此刻真的有注册生效」是两回事:后者还要会话活着、
42
+ // 且上一次物化成功。这一栏直接读进程内句柄表,不靠推断。
43
+ materialized: appliedHandles.has(sessionId),
44
+ // 显式关过才有 updatedAt,从没动过则是 undefined。
45
+ updatedAt: typeof activation?.updatedAt === 'number' ? activation.updatedAt : undefined,
46
+ // 子 Agent 继承父会话时写下 `inheritedFrom`;界面用它区分「自己套的」
47
+ // 和「从父会话继承来的」。
48
+ inheritedFrom: typeof manifest?.inheritedFrom === 'string' ? manifest.inheritedFrom : undefined,
49
+ recipe: manifest?.recipe ?? {},
50
+ })
51
+ }
52
+ return bindings
53
+ }
54
+
55
+ /**
56
+ * 快照要额外带上的模板数据:绑定视图 + 模板列表。
57
+ *
58
+ * 存储不可用时也不能让整个快照失败——会话页拿不到绑定信息只是少一栏开关,
59
+ * 不该连带把插件/工具/提示词三个视图一起拖垮。
60
+ * @param {object} ctx - host 插件上下文。
61
+ * @param {object} state - 模板存储状态。
62
+ * @returns {Promise<object>} `{ bindings, templates }`。
63
+ */
64
+ export async function snapshotExtras(ctx, state) {
65
+ try {
66
+ await ensureTemplateStore(ctx, state)
67
+ const bindings = await readTemplateBindings(state)
68
+ const templates = []
69
+ for (const [, head] of templateTable(state, 'templates').entries()) {
70
+ templates.push({ id: head.id, name: head.name, updatedAt: head.updatedAt })
71
+ }
72
+ templates.sort((left, right) => right.updatedAt - left.updatedAt)
73
+ return { bindings: Object.fromEntries(bindings), templates }
74
+ } catch (error) {
75
+ ctx.logger?.warn?.('plugin-console: 读取模板绑定失败,会话页开关不可用:' + String(error))
76
+ return {}
77
+ }
78
+ }
79
+
80
+ /**
81
+ * 列出所有模板,带历史条数。
82
+ * @param {object} state - 模板存储状态。
83
+ * @returns {object[]} 模板列表(按更新时间倒序)。
84
+ */
85
+ export function listTemplates(state) {
86
+ const items = []
87
+ const revisions = templateTable(state, 'revisions')
88
+ for (const [, head] of templateTable(state, 'templates').entries()) {
89
+ let revisionCount = 0
90
+ for (const [, value] of revisions.entries()) {
91
+ if (value.templateId === head.id) revisionCount++
92
+ }
93
+ items.push({ ...head, revisionCount })
94
+ }
95
+ items.sort((left, right) => right.updatedAt - left.updatedAt)
96
+ return items
97
+ }
98
+
99
+ /**
100
+ * 新建一个模板头。
101
+ * @param {object} state - 模板存储状态。
102
+ * @param {string} name - 显示名;空白时用「未命名模板」。
103
+ * @returns {Promise<object>} 新建的模板头。
104
+ */
105
+ export async function createTemplate(state, name) {
106
+ const now = Date.now()
107
+ const label = typeof name === 'string' && name.trim().length > 0 ? name.trim() : '未命名提示词模板'
108
+ const head = { id: newTemplateId(), name: label, latestRevision: 0, createdAt: now, updatedAt: now }
109
+ await templateTable(state, 'templates').put(head.id, head)
110
+ return head
111
+ }
112
+
113
+ /**
114
+ * 读一个模板头。
115
+ * @param {object} state - 模板存储状态。
116
+ * @param {string} id - 模板 id。
117
+ * @returns {object | undefined} 模板头。
118
+ */
119
+ export function getTemplate(state, id) {
120
+ return templateTable(state, 'templates').get(id)
121
+ }
122
+
123
+ /**
124
+ * 读出一个模板的全部历史,按内部序号升序。
125
+ * @param {object} state - 模板存储状态。
126
+ * @param {string} templateId - 模板 id。
127
+ * @returns {object[]} 历史记录。
128
+ */
129
+ export function revisionsOf(state, templateId) {
130
+ const out = []
131
+ for (const [, value] of templateTable(state, 'revisions').entries()) {
132
+ if (value.templateId === templateId) out.push(value)
133
+ }
134
+ return out.sort((left, right) => left.revision - right.revision)
135
+ }
136
+
137
+ /**
138
+ * 读出一个模板的最新 recipe。
139
+ *
140
+ * `revision` 是内部序号,这里取最大的那条——界面已不再显示版本号,
141
+ * 但存储里保留历史是为了能查改动轨迹。
142
+ * @param {object} state - 模板存储状态。
143
+ * @param {string} templateId - 模板 id。
144
+ * @returns {object | undefined} `{ revision, recipe }`,没有历史时 undefined。
145
+ */
146
+ export function latestRecipe(state, templateId) {
147
+ let latest
148
+ for (const [, value] of templateTable(state, 'revisions').entries()) {
149
+ if (value.templateId !== templateId) continue
150
+ if (latest === undefined || value.revision > latest.revision) latest = value
151
+ }
152
+ if (latest === undefined) return undefined
153
+ return { revision: latest.revision, recipe: latest.recipe }
154
+ }
155
+
156
+ /**
157
+ * 改名:只动 name,不产生新记录。
158
+ * @param {object} state - 模板存储状态。
159
+ * @param {string} id - 模板 id。
160
+ * @param {object} head - 现有模板头。
161
+ * @param {string} name - 新名字(调用方已校验非空)。
162
+ * @returns {Promise<object>} 更新后的模板头。
163
+ */
164
+ export async function renameTemplate(state, id, head, name) {
165
+ const renamed = { ...head, name, updatedAt: Date.now() }
166
+ await templateTable(state, 'templates').put(id, renamed)
167
+ return renamed
168
+ }
169
+
170
+ /**
171
+ * 保存一份配方为新版本。
172
+ *
173
+ * `revision` 只是内部历史序号,不再面向用户——界面上不出现「v12」这种东西。
174
+ * 保留历史是为了查到改动轨迹,但用户看到的就是「这个模板现在是什么」。
175
+ * @param {object} state - 模板存储状态。
176
+ * @param {string} id - 模板 id。
177
+ * @param {object} head - 现有模板头。
178
+ * @param {object} recipe - 配方。
179
+ * @returns {Promise<{template: object, revision: object}>} 新头与新版本。
180
+ */
181
+ export async function saveRecipe(state, id, head, recipe) {
182
+ const revision = head.latestRevision + 1
183
+ const record = {
184
+ templateId: id,
185
+ revision,
186
+ schemaVersion: 3,
187
+ recipe: recipe !== null && typeof recipe === 'object' ? recipe : {},
188
+ createdAt: Date.now(),
189
+ }
190
+ await templateTable(state, 'revisions').put(id + '#' + revision, record)
191
+ const next = { ...head, latestRevision: revision, updatedAt: record.createdAt }
192
+ await templateTable(state, 'templates').put(id, next)
193
+ return { template: next, revision: record }
194
+ }
195
+
196
+ /**
197
+ * 删除一个模板:只删模板自己的头与历史,不动会话侧的 manifest。
198
+ *
199
+ * manifest 是应用模板时复制成的独立快照——按设计,模板只是模板,删除它不该
200
+ * 改变已应用会话的行为。这些会话仍按自己的 recipe 物化、仍能开关、resume 与
201
+ * 被新建的子 Agent 继承;只是名字退回快照,界面标「模板已删除」。
202
+ *
203
+ * 只删头会留下永远读不到的 revision,所以历史一起清掉。
204
+ * @param {object} state - 模板存储状态。
205
+ * @param {string} id - 模板 id。
206
+ * @returns {Promise<{removedRevisions: number, keptManifests: number}>} 删掉的历史条数与保留的会话绑定数。
207
+ */
208
+ export async function deleteTemplate(state, id) {
209
+ const revisions = templateTable(state, 'revisions')
210
+ const manifests = templateTable(state, 'manifests')
211
+
212
+ let removedRevisions = 0
213
+ for (const [key, value] of [...revisions.entries()]) {
214
+ if (value.templateId !== id) continue
215
+ await revisions.delete(key)
216
+ removedRevisions++
217
+ }
218
+ // 只统计、不删除:绑定是会话自有的快照。
219
+ let keptManifests = 0
220
+ for (const [, value] of manifests.entries()) {
221
+ if (value?.source?.templateId === id) keptManifests++
222
+ }
223
+ await templateTable(state, 'templates').delete(id)
224
+ return { removedRevisions, keptManifests }
225
+ }
226
+
227
+ /**
228
+ * 写一条 activation。
229
+ * @param {object} state - 模板存储状态。
230
+ * @param {string} sessionId - 会话 id。
231
+ * @param {boolean} enabled - 目标状态。
232
+ * @returns {Promise<object>} 写入的记录。
233
+ */
234
+ export async function writeActivation(state, sessionId, enabled) {
235
+ const record = { sessionId, enabled, updatedAt: Date.now() }
236
+ await templateTable(state, 'activations').put(sessionId, record)
237
+ return record
238
+ }
239
+
240
+ /**
241
+ * 读一个会话的 manifest。
242
+ * @param {object} state - 模板存储状态。
243
+ * @param {string} sessionId - 会话 id。
244
+ * @returns {object | undefined} manifest。
245
+ */
246
+ export function getManifest(state, sessionId) {
247
+ return templateTable(state, 'manifests').get(sessionId)
248
+ }
249
+
250
+ /**
251
+ * 写一个会话的 manifest。
252
+ * @param {object} state - 模板存储状态。
253
+ * @param {string} sessionId - 会话 id。
254
+ * @param {object} manifest - manifest。
255
+ * @returns {Promise<void>} 写入完成。
256
+ */
257
+ export async function putManifest(state, sessionId, manifest) {
258
+ await templateTable(state, 'manifests').put(sessionId, manifest)
259
+ }
260
+
261
+ /**
262
+ * 读一个会话的全部掩码。
263
+ * @param {object} state - 模板存储状态。
264
+ * @param {string} sessionId - 会话 id。
265
+ * @returns {Array<object>} 掩码记录。
266
+ */
267
+ export function masksForSession(state, sessionId) {
268
+ const out = []
269
+ for (const [, record] of templateTable(state, 'masks').entries()) {
270
+ if (record?.sessionId === sessionId) out.push(record)
271
+ }
272
+ return out
273
+ }
274
+
275
+ /**
276
+ * 写一条掩码;key 用 sessionId + rowId,天然去重。
277
+ * @param {object} state - 模板存储状态。
278
+ * @param {string} sessionId - 会话 id。
279
+ * @param {string} rowId - 目标行 id。
280
+ * @returns {Promise<object>} 写入的记录。
281
+ */
282
+ export async function putMask(state, sessionId, rowId, tools) {
283
+ const record = { sessionId, rowId, tools: Array.isArray(tools) ? tools : [], createdAt: Date.now() }
284
+ await templateTable(state, 'masks').put(sessionId + ':' + rowId, record)
285
+ return record
286
+ }
287
+
288
+ /**
289
+ * 删除一条掩码。
290
+ * @param {object} state - 模板存储状态。
291
+ * @param {string} sessionId - 会话 id。
292
+ * @param {string} rowId - 目标行 id。
293
+ * @returns {Promise<void>} 写入完成。
294
+ */
295
+ export function deleteMask(state, sessionId, rowId) {
296
+ return templateTable(state, 'masks').delete(sessionId + ':' + rowId)
297
+ }
298
+
299
+ /**
300
+ * 追加一条控制审计。
301
+ * @param {object} state - 模板存储状态。
302
+ * @param {object} record - 至少含 action/scope/target/before/after/result。
303
+ * @returns {Promise<object>} 写入的记录。
304
+ */
305
+ export async function appendOperation(state, record) {
306
+ const id = 'op-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 6)
307
+ const value = { id, time: Date.now(), ...record }
308
+ await templateTable(state, 'operations').put(id, value)
309
+ return value
310
+ }
311
+
312
+ /**
313
+ * 读最近的控制审计。
314
+ * @param {object} state - 模板存储状态。
315
+ * @param {number} [limit] - 最多返回多少条。
316
+ * @returns {Array<object>} 按时间倒序的记录。
317
+ */
318
+ export function listOperations(state, limit = 20) {
319
+ return [...templateTable(state, 'operations').entries()]
320
+ .map(([, record]) => record)
321
+ .sort((left, right) => right.time - left.time)
322
+ .slice(0, limit)
323
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * 模板存储的打开与表句柄。
3
+ *
4
+ * 存储域不可用时降级为内存表——绝不写 sidecar 文件,那不是持久化契约。
5
+ * 表句柄把「域的表」和「内存 Map」抹平成同一组方法,上层不必知道当前是哪种。
6
+ * @module dsh-plugin-console/host/templates/store
7
+ */
8
+
9
+ /**
10
+ * 模板域的声明。
11
+ *
12
+ * 域名必须匹配 /^[a-z][a-z0-9_]*$/:storage 拿它当文件名与 SQL 标识符。
13
+ * tables 里的每张表只需一个带 parse 的 schema——storage-domain 在读出时调用它,
14
+ * 失败会抛 invalid-record 并(配置了的话)把坏记录备份移走。
15
+ * @returns {object} 域声明。
16
+ */
17
+ export function templateDomain() {
18
+ /** 一个最小的结构校验器:只检查必填字段类型,够挡住损坏的记录。 */
19
+ const shape = (checks) => ({
20
+ parse(value) {
21
+ if (value === null || typeof value !== 'object') throw new Error('record must be an object')
22
+ for (const [key, test] of Object.entries(checks)) {
23
+ if (!test(value[key])) throw new Error('field "' + key + '" has the wrong type')
24
+ }
25
+ return value
26
+ },
27
+ })
28
+ const isString = (value) => typeof value === 'string'
29
+ const isNumber = (value) => typeof value === 'number' && Number.isFinite(value)
30
+ const isObject = (value) => value !== null && typeof value === 'object'
31
+ const isBoolean = (value) => typeof value === 'boolean'
32
+ const isArray = (value) => Array.isArray(value)
33
+
34
+ return {
35
+ name: 'plugin_console_templates',
36
+ version: 1,
37
+ tables: {
38
+ templates: { valueSchema: shape({ id: isString, name: isString, latestRevision: isNumber, createdAt: isNumber, updatedAt: isNumber }) },
39
+ revisions: { valueSchema: shape({ templateId: isString, revision: isNumber, schemaVersion: isNumber, recipe: isObject, createdAt: isNumber }) },
40
+ manifests: { valueSchema: shape({ schemaVersion: isNumber, sessionId: isString, recipe: isObject, createdAt: isNumber }) },
41
+ // 每会话的启用状态。
42
+ //
43
+ // 与 manifest 分表是刻意的:manifest 记「应该怎么改」,是会话创建时的
44
+ // 不可变快照;activation 记「现在要不要应用」,是频繁变动的开关。
45
+ // 混在一起会让「会话自有、不可变」这条语义失效,也会让每次开关都重写
46
+ // 整份 manifest(含 recipe 全文)。
47
+ //
48
+ // 没有记录 = 启用。所以关闭是显式写一条 enabled: false。
49
+ activations: { valueSchema: shape({ sessionId: isString, enabled: isBoolean, updatedAt: isNumber }) },
50
+ // 会话级贡献掩码:某会话隐藏某个插件的工具贡献。
51
+ // 与 manifest 分开:manifest 是模板快照,掩码是诊断/控制动作,二者可共存。
52
+ masks: { valueSchema: shape({ sessionId: isString, rowId: isString, createdAt: isNumber, tools: isArray }) },
53
+ // 控制审计:谁在什么时候对哪个目标做了什么,结果如何。
54
+ operations: { valueSchema: shape({ id: isString, time: isNumber, action: isString, scope: isString, target: isString, before: isObject, after: isObject, result: isString }) },
55
+ },
56
+ }
57
+ }
58
+
59
+ /** 生成一个模板 id。 */
60
+ export function newTemplateId() {
61
+ return 'tpl-' + Math.random().toString(36).slice(2, 10) + Date.now().toString(36).slice(-4)
62
+ }
63
+
64
+ /**
65
+ * 新建一份存储状态:域、内存降级、以及打开中的 promise 都挂在这里。
66
+ * @returns {object} 状态对象。
67
+ */
68
+ export function createTemplateState() {
69
+ return { domain: undefined, memory: undefined, ready: undefined }
70
+ }
71
+
72
+ /**
73
+ * 打开(或复用)模板存储。
74
+ * @param {object} ctx - host 插件上下文。
75
+ * @param {object} state - 本插件持有的状态(缓存已打开的域)。
76
+ * @returns {Promise<void>} 打开完成。
77
+ */
78
+ export async function ensureTemplateStore(ctx, state) {
79
+ if (state.ready !== undefined) return state.ready
80
+ state.ready = (async () => {
81
+ const facility = ctx.get('storageDomain')
82
+ if (facility === undefined || typeof facility.open !== 'function') {
83
+ state.memory = { templates: new Map(), revisions: new Map(), manifests: new Map(), activations: new Map(), masks: new Map(), operations: new Map() }
84
+ ctx.logger?.warn?.('plugin-console: storageDomain 不可用,模板降级为内存存储(不持久化)')
85
+ return
86
+ }
87
+ state.domain = await facility.open(templateDomain())
88
+ })()
89
+ return state.ready
90
+ }
91
+
92
+ /**
93
+ * 取一张逻辑表。域可用时走域,否则走内存 Map 的同名接口。
94
+ * @param {object} state - 插件状态。
95
+ * @param {string} name - 表名。
96
+ * @returns {object} 表句柄。
97
+ */
98
+ export function templateTable(state, name) {
99
+ if (state.domain !== undefined) return state.domain.table(name)
100
+ const map = state.memory[name]
101
+ return {
102
+ get: (key) => map.get(key),
103
+ put: async (key, value) => { map.set(key, value) },
104
+ delete: async (key) => { map.delete(key) },
105
+ entries: () => map.entries(),
106
+ keys: () => map.keys(),
107
+ }
108
+ }
109
+
110
+ /**
111
+ * 关闭模板存储;重复关闭或从未打开都安全。
112
+ * @param {object} state - 插件状态。
113
+ * @returns {void}
114
+ */
115
+ export function closeTemplateStore(state) {
116
+ if (state.domain !== undefined) void state.domain.close()
117
+ }
118
+
119
+ /**
120
+ * 把存储状态退回「从未打开」。
121
+ *
122
+ * 只在关闭域之后调用:清空重开时文件已被删除,旧的域与已解析的 ready 都必须
123
+ * 丢掉,下一次 `ensureTemplateStore` 才会重新打开并读到空单元。
124
+ * @param {object} state - 插件状态。
125
+ * @returns {void}
126
+ */
127
+ export function resetTemplateStore(state) {
128
+ state.domain = undefined
129
+ state.memory = undefined
130
+ state.ready = undefined
131
+ }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * 工具 schema 的分层归类:实际请求 vs 当前注册表,预演 vs 全局 + preset scope。
3
+ *
4
+ * `request/header` 只给最终工具列表,不记「谁注册的」;公开面也没有逐层 owner。
5
+ * 所以这里拿实际 schema 与当前 global / preset / agent scope 的定义做等值比较,
6
+ * 得出「更像哪一层」的推断,而不是声称历史归属。
7
+ *
8
+ * 边界:
9
+ * - 同名且定义完全相同时,无法区分是全局、预设还是会话层提供的;
10
+ * - 请求之后注册表变了,实际 schema 可能落进 `unknown` 或 `replaced`;
11
+ * - `replaced` 只说明「名字在全局/预设里存在,但实际定义不同」,不确认是谁替换的。
12
+ * @module dsh-plugin-console/host/tool-set
13
+ */
14
+
15
+ /**
16
+ * 把一条工具定义整理成可展示、可比较的 schema。
17
+ * @param {object} tool - 请求头或注册表里的工具定义。
18
+ * @returns {{name: string, description?: string, parameters?: object, deferLoading?: boolean} | undefined} 归一化 schema。
19
+ */
20
+ export function toolSchemaOf(tool) {
21
+ if (tool === null || typeof tool !== 'object' || typeof tool.name !== 'string') return undefined
22
+ return {
23
+ name: tool.name,
24
+ ...(typeof tool.description === 'string' ? { description: tool.description } : {}),
25
+ ...(tool.parameters === undefined ? {} : { parameters: tool.parameters }),
26
+ ...(tool.deferLoading === true ? { deferLoading: true } : {}),
27
+ }
28
+ }
29
+
30
+ /** 键顺序稳定的 JSON,避免同一份 schema 因属性顺序不同被判成不同定义。 */
31
+ function stableStringify(value) {
32
+ if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null'
33
+ if (Array.isArray(value)) return '[' + value.map(stableStringify).join(',') + ']'
34
+ return '{' + Object.keys(value).sort().map((key) => JSON.stringify(key) + ':' + stableStringify(value[key])).join(',') + '}'
35
+ }
36
+
37
+ /** 一份 schema 的比较键;名字单独作为 map 的键,这里只比定义。 */
38
+ function schemaKey(tool) {
39
+ return stableStringify({
40
+ description: tool.description ?? '',
41
+ parameters: tool.parameters ?? null,
42
+ deferLoading: tool.deferLoading === true,
43
+ })
44
+ }
45
+
46
+ /** 把一组工具整理成「名字 → 定义键」,用于跨层比对。 */
47
+ function keyMapOf(tools) {
48
+ const map = new Map()
49
+ for (const tool of Array.isArray(tools) ? tools : []) {
50
+ const normalized = toolSchemaOf(tool)
51
+ if (normalized !== undefined) map.set(normalized.name, schemaKey(normalized))
52
+ }
53
+ return map
54
+ }
55
+
56
+ /**
57
+ * 把实际请求里的工具按「定义来自哪一层」分组。
58
+ *
59
+ * 判定顺序:
60
+ * 1. 与全局层一致 → `global`;
61
+ * 2. 与预设 scope 一致 → `preset`;
62
+ * 3. 名字在当前 agent scope 里可见 → `session`(同名但定义不同也归这里,并进 `replaced`);
63
+ * 4. 名字只在 global/preset 里、定义却不同 → `replaced`(冷会话无法复核 agent scope);
64
+ * 5. 当前注册表里找不到 → `unknown`。
65
+ * @param {{actual: Array<object>, global?: Array<object>, preset?: Array<object>, agentNames?: string[]}} input - 各层定义。
66
+ * @returns {object} 分组结果;`layers` 是名字列表,`layerByName` 是名字 → 层级。
67
+ */
68
+ export function classifyToolSchemas(input = {}) {
69
+ const globalKeys = keyMapOf(input.global)
70
+ const presetKeys = keyMapOf(input.preset)
71
+ const agentNames = new Set(Array.isArray(input.agentNames) ? input.agentNames : [])
72
+ const layers = { global: [], preset: [], session: [], replaced: [], unknown: [] }
73
+ const layerByName = {}
74
+ const replaced = []
75
+
76
+ for (const raw of Array.isArray(input.actual) ? input.actual : []) {
77
+ const tool = toolSchemaOf(raw)
78
+ if (tool === undefined) continue
79
+ const key = schemaKey(tool)
80
+ const inGlobal = globalKeys.has(tool.name)
81
+ const inPreset = presetKeys.has(tool.name)
82
+ let layer
83
+ if (inGlobal && globalKeys.get(tool.name) === key) layer = 'global'
84
+ else if (inPreset && presetKeys.get(tool.name) === key) layer = 'preset'
85
+ else if (agentNames.has(tool.name)) layer = 'session'
86
+ else if (inGlobal || inPreset) layer = 'replaced'
87
+ else layer = 'unknown'
88
+
89
+ if ((inGlobal || inPreset) && layer !== 'global' && layer !== 'preset') replaced.push(tool.name)
90
+ if (!layers[layer].includes(tool.name)) layers[layer].push(tool.name)
91
+ layerByName[tool.name] = layer
92
+ }
93
+
94
+ return {
95
+ basis: 'schema-match-current-registry',
96
+ counts: Object.fromEntries(Object.entries(layers).map(([layer, names]) => [layer, names.length])),
97
+ layers,
98
+ layerByName,
99
+ replaced,
100
+ }
101
+ }
102
+
103
+ /** 把一组工具(名字或 schema)收成名字集合。 */
104
+ function namesOf(tools) {
105
+ const set = new Set()
106
+ for (const entry of Array.isArray(tools) ? tools : []) {
107
+ if (typeof entry === 'string') set.add(entry)
108
+ else if (typeof entry?.name === 'string') set.add(entry.name)
109
+ }
110
+ return set
111
+ }
112
+
113
+ /**
114
+ * 把预演的工具按「这个名字从哪一层来」分组。
115
+ *
116
+ * 预演用 preset scope 装配,所以来源只有全局层与预设层。判定只看**名字是否在
117
+ * 该层的可见集里**,不比较定义:
118
+ * 1. 名字在全局视图里就有 → `global`(所有模式共享,模式可能重新注册过它);
119
+ * 2. 名字只在 preset scope 出现 → `preset`(模式新增的工具);
120
+ * 3. 两边都没有 → `unknown`(装配期间才出现的动态注册)。
121
+ *
122
+ * 为什么不做定义等值比较:装配结果本来就取自 preset scope,先按「全局层有同名、
123
+ * 定义不同」判替换会把模式重新注册过的每个工具都标成「同名替换」;而注册表在
124
+ * 装配后变化、投影方式差异都会制造假差异。名字级分组不会误报,也更容易解释。
125
+ * @param {{tools?: Array<object>, global?: Array<object|string>, preset?: Array<object|string>}} input - 预演工具与两层可见集。
126
+ * @returns {object} 分组结果;`layers` 是名字列表,`layerByName` 是名字 → 层级。
127
+ */
128
+ export function classifyPreviewTools(input = {}) {
129
+ const globalNames = namesOf(input.global)
130
+ const presetNames = namesOf(input.preset)
131
+ const layers = { global: [], preset: [], unknown: [] }
132
+ const layerByName = {}
133
+
134
+ for (const raw of Array.isArray(input.tools) ? input.tools : []) {
135
+ const tool = toolSchemaOf(raw)
136
+ if (tool === undefined) continue
137
+ const layer = globalNames.has(tool.name)
138
+ ? 'global'
139
+ : presetNames.has(tool.name) ? 'preset' : 'unknown'
140
+ if (!layers[layer].includes(tool.name)) layers[layer].push(tool.name)
141
+ layerByName[tool.name] = layer
142
+ }
143
+
144
+ return {
145
+ basis: 'name-membership-scope',
146
+ counts: Object.fromEntries(Object.entries(layers).map(([layer, names]) => [layer, names.length])),
147
+ layers,
148
+ layerByName,
149
+ }
150
+ }