@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,293 @@
1
+ /**
2
+ * 会话、工作区与派发树。
3
+ *
4
+ * 会话的模式来自持久化 header(冷会话不必打开正文);工作区本身不记录模式,
5
+ * 它只记录成员会话。活会话额外带 runtime——那是本进程里真实挂载的组合。
6
+ * @module dsh-plugin-console/host/sessions
7
+ */
8
+
9
+ import { listDir, readTextFile, statFile } from './fs.js'
10
+ import { readRuntimeComposition } from './modes.js'
11
+
12
+ /**
13
+ * 从会话 header 的派发字段构建父子树。
14
+ *
15
+ * `parentSession` 指向父会话 id。父会话可能不在当前列表里(已被清理、或属于
16
+ * 另一个 profile),这种节点升级为根并标记 `orphan`,不静默丢弃。
17
+ * `depth` 以实际父子链重算,而不是直接采信 `delegationDepth`:父会话消失后
18
+ * 记录值仍是 1,但在这棵树里它就是根。
19
+ * @param {Array<object>} sessions - 会话列表(含 parentSession / origin / delegationDepth)。
20
+ * @returns {{roots: Array<object>, nodes: Array<object>, orphanCount: number, childCount: number}} 树。
21
+ */
22
+ export function buildDispatchTree(sessions) {
23
+ const byId = new Map(sessions.map((session) => [session.id, session]))
24
+ const childrenOf = new Map()
25
+
26
+ for (const session of sessions) {
27
+ const parentId = session.parentSession
28
+ if (typeof parentId !== 'string' || !byId.has(parentId)) continue
29
+ const list = childrenOf.get(parentId) ?? []
30
+ list.push(session.id)
31
+ childrenOf.set(parentId, list)
32
+ }
33
+
34
+ /** 递归构建一个节点及其子树。 */
35
+ const build = (id, depth, seen) => {
36
+ const session = byId.get(id)
37
+ // 防御环:header 写入时不做环检测,读取方必须自己挡
38
+ if (session === undefined || seen.has(id)) return null
39
+ const nextSeen = new Set(seen)
40
+ nextSeen.add(id)
41
+ const children = (childrenOf.get(id) ?? [])
42
+ .map((childId) => build(childId, depth + 1, nextSeen))
43
+ .filter((node) => node !== null)
44
+ return {
45
+ id,
46
+ title: session.title,
47
+ preset: session.preset,
48
+ cwd: session.cwd,
49
+ createdAt: session.createdAt,
50
+ live: session.live === true,
51
+ origin: session.origin,
52
+ recordedDepth: session.delegationDepth,
53
+ depth,
54
+ childCount: children.length,
55
+ orphan: typeof session.parentSession === 'string' && !byId.has(session.parentSession),
56
+ parentId: typeof session.parentSession === 'string' ? session.parentSession : undefined,
57
+ children,
58
+ }
59
+ }
60
+
61
+ const roots = []
62
+ for (const session of sessions) {
63
+ const parentId = session.parentSession
64
+ if (typeof parentId === 'string' && byId.has(parentId)) continue
65
+ const node = build(session.id, 0, new Set())
66
+ if (node !== null) roots.push(node)
67
+ }
68
+
69
+ /** 摊平所有节点,便于前端按 id 查找。 */
70
+ const flatten = (node, out) => {
71
+ out.push(node)
72
+ for (const child of node.children) flatten(child, out)
73
+ return out
74
+ }
75
+ const nodes = []
76
+ for (const root of roots) flatten(root, nodes)
77
+
78
+ return {
79
+ roots,
80
+ nodes,
81
+ orphanCount: nodes.filter((node) => node.orphan).length,
82
+ childCount: nodes.filter((node) => node.parentId !== undefined).length,
83
+ }
84
+ }
85
+
86
+ /**
87
+ * 读取一批会话的标题。
88
+ *
89
+ * 两条路,按可靠性排序:
90
+ * 1. `sessionProjections`:对活会话直接读已折叠的 `title` 投影(无需打开日志);
91
+ * 2. 投影缓存文件:冷会话的投影被 checkpoint 到 `<home>/storages/session_projcache`,
92
+ * 结构是 `{ version, record: { rows: { title: { val } } } }`。
93
+ *
94
+ * 拿不到就返回 undefined,由前端退回会话 id——不编造标题。
95
+ * @param {object} ctx - host 插件上下文。
96
+ * @param {Array<string>} sessionIds - 会话 id 列表。
97
+ * @param {object} profile - profile 信息(提供 home 路径)。
98
+ * @returns {Promise<Map<string, string>>} 会话 id → 标题。
99
+ */
100
+ export async function readSessionTitles(ctx, sessionIds, profile) {
101
+ const titles = new Map()
102
+ if (sessionIds.length === 0) return titles
103
+
104
+ const projections = ctx.get('sessionProjections')
105
+ const sessions = ctx.get('sessions')
106
+ if (projections !== undefined && sessions !== undefined && typeof projections.stateOf === 'function') {
107
+ for (const id of sessionIds) {
108
+ try {
109
+ const session = sessions.get?.(id)
110
+ if (session === undefined) continue
111
+ const title = projections.stateOf(session, 'title')
112
+ if (typeof title === 'string' && title.length > 0) titles.set(id, title)
113
+ } catch {
114
+ // 单个会话读失败不影响其它会话
115
+ }
116
+ }
117
+ }
118
+
119
+ const missing = sessionIds.filter((id) => !titles.has(id))
120
+ if (missing.length === 0) return titles
121
+
122
+ const home = typeof profile?.home === 'string' ? profile.home : undefined
123
+ if (home === undefined) return titles
124
+
125
+ const dir = `${home}/storages/session_projcache/sessions`
126
+ const files = await listDir(dir)
127
+ if (files.length === 0) return titles
128
+ const wanted = new Set(missing)
129
+ for (const file of files) {
130
+ const id = file.replace(/\.json$/, '')
131
+ if (!wanted.has(id)) continue
132
+ const text = await readTextFile(`${dir}/${file}`)
133
+ if (text === null) continue
134
+ try {
135
+ const parsed = JSON.parse(text)
136
+ const value = parsed?.record?.rows?.title?.val
137
+ if (typeof value === 'string' && value.length > 0) titles.set(id, value)
138
+ } catch {
139
+ // 缓存文件损坏时跳过
140
+ }
141
+ }
142
+ return titles
143
+ }
144
+
145
+ /**
146
+ * 读取工作区与会话,并把每个会话归属到它的工作区。
147
+ *
148
+ * 会话的 `agentPreset` 来自持久化 header(冷会话不必打开正文),
149
+ * 工作区只记录成员,本身不携带模式。
150
+ * @param {object} ctx - host 插件上下文。
151
+ * @param {object} profile - profile 信息(提供 home 路径)。
152
+ * @returns {Promise<object>} 工作区列表与压平后的会话列表。
153
+ */
154
+ export async function readSessions(ctx, profile) {
155
+ /** @type {Map<string, object>} */
156
+ const sessionMap = new Map()
157
+ /** 会话日志文件路径:只有它能给出「最近活跃」所需的写入时间。 */
158
+ const logPaths = new Map()
159
+
160
+ const persistence = ctx.get('sessionPersistence')
161
+ if (persistence !== undefined && typeof persistence.list === 'function') {
162
+ try {
163
+ for (const snapshot of await persistence.list()) {
164
+ const header = snapshot?.header
165
+ if (!header || typeof header.id !== 'string') continue
166
+ const logPath = snapshot?.location?.path
167
+ if (typeof logPath === 'string') logPaths.set(header.id, logPath)
168
+ // 派发关系来自 header:origin 标记子 Agent,parentSession 指回父会话。
169
+ sessionMap.set(header.id, {
170
+ id: header.id,
171
+ cwd: typeof header.cwd === 'string' ? header.cwd : undefined,
172
+ preset: typeof header.agentPreset === 'string' ? header.agentPreset : null,
173
+ createdAt: typeof header.createdAt === 'number' ? header.createdAt : undefined,
174
+ sizeBytes: typeof snapshot.sizeBytes === 'number' ? snapshot.sizeBytes : undefined,
175
+ parentSession: typeof header.parentSession === 'string' ? header.parentSession : undefined,
176
+ origin: header.origin === 'subagent' ? 'subagent' : undefined,
177
+ delegationDepth: typeof header.delegationDepth === 'number' ? header.delegationDepth : undefined,
178
+ isSeeded: header.isSeeded === true ? true : undefined,
179
+ })
180
+ }
181
+ } catch {
182
+ // 读取失败时保留 live 会话(下面补),不让整个快照失败
183
+ }
184
+ }
185
+
186
+ // 本轮进程里活着的会话一定存在磁盘上的 header 之外——补上没被 list() 覆盖的。
187
+ const sessions = ctx.get('sessions')
188
+ if (sessions !== undefined && typeof sessions.list === 'function') {
189
+ for (const session of sessions.list()) {
190
+ const known = sessionMap.get(session.id)
191
+ if (known !== undefined) {
192
+ known.live = true
193
+ continue
194
+ }
195
+ let preset
196
+ try {
197
+ preset = ctx.get('agentPresets')?.presetForSession?.(session) ?? undefined
198
+ } catch {
199
+ preset = undefined
200
+ }
201
+ sessionMap.set(session.id, { id: session.id, preset: preset ?? null, live: true })
202
+ }
203
+ }
204
+
205
+ // 运行时常驻:给每个活会话补上它此刻真正加载的插件集合
206
+ const agents = ctx.get('agents')
207
+ if (agents !== undefined && typeof agents.get === 'function') {
208
+ for (const [sessionId, record] of sessionMap) {
209
+ if (record.live !== true) continue
210
+ let agent
211
+ try {
212
+ agent = agents.get(sessionId)
213
+ } catch {
214
+ agent = undefined
215
+ }
216
+ if (agent === undefined) continue
217
+ record.runtime = readRuntimeComposition(ctx, agent) ?? null
218
+ }
219
+ }
220
+
221
+ // 最近活跃时间来自会话日志文件的修改时间;读不到时退回 createdAt。
222
+ // 活会话即使日志暂时没变也不算「从未活跃」,所以两者取较晚的一个。
223
+ const mtimes = new Map()
224
+ await Promise.all([...logPaths].map(async ([id, file]) => {
225
+ const info = await statFile(file)
226
+ if (info !== null) mtimes.set(id, info.mtimeMs)
227
+ }))
228
+ for (const [id, session] of sessionMap) {
229
+ const stamp = Math.max(mtimes.get(id) ?? 0, typeof session.createdAt === 'number' ? session.createdAt : 0)
230
+ session.lastActiveAt = stamp > 0 ? stamp : (session.live === true ? Date.now() : undefined)
231
+ }
232
+
233
+ const workspaces = []
234
+ const claimed = new Set()
235
+ const registry = ctx.get('workspaceRegistry')
236
+ if (registry !== undefined && typeof registry.list === 'function') {
237
+ for (const workspace of registry.list()) {
238
+ const ids = workspace.sessionIds ?? []
239
+ for (const id of ids) claimed.add(id)
240
+ workspaces.push({
241
+ id: workspace.id,
242
+ path: workspace.path,
243
+ title: workspace.title,
244
+ sessions: ids.map((id) => sessionMap.get(id) ?? { id, preset: null }),
245
+ })
246
+ }
247
+ }
248
+
249
+ // 不属于任何工作区的会话仍要能查到模式
250
+ const ungrouped = [...sessionMap.values()].filter((session) => !claimed.has(session.id))
251
+
252
+ // 标题:DSH 侧边栏显示的是它,不是 session id。拿不到就留空,前端退回 id。
253
+ const titles = await readSessionTitles(ctx, [...sessionMap.keys()], profile)
254
+ for (const [id, title] of titles) {
255
+ const session = sessionMap.get(id)
256
+ if (session !== undefined) session.title = title
257
+ }
258
+ // workspaces / ungrouped 里的对象可能就是 sessionMap 里的同一批对象,
259
+ // 但缺省的占位对象({ id, preset: null })需要单独补。
260
+ for (const list of [...workspaces.map((workspace) => workspace.sessions), ungrouped]) {
261
+ for (const session of list) {
262
+ const title = titles.get(session.id)
263
+ if (title !== undefined && session.title === undefined) session.title = title
264
+ }
265
+ }
266
+
267
+ // 工作区的最近活跃 = 成员会话里最晚的一次(含派生子会话)。
268
+ for (const workspace of workspaces) {
269
+ workspace.lastActiveAt = latestActiveAt(workspace.sessions)
270
+ }
271
+
272
+ // 派发树最后构建:节点会带上 title / live 的快照,
273
+ // 因此必须等这些字段都写完了再建。
274
+ const dispatch = buildDispatchTree([...sessionMap.values()])
275
+
276
+ return {
277
+ workspaces,
278
+ ungrouped,
279
+ ungroupedLastActiveAt: latestActiveAt(ungrouped),
280
+ sessions: [...sessionMap.values()],
281
+ dispatch,
282
+ }
283
+ }
284
+
285
+ /** 一组会话里最晚的活跃时间;没有可用时间时 undefined。 */
286
+ function latestActiveAt(sessions) {
287
+ let latest
288
+ for (const session of sessions) {
289
+ if (typeof session?.lastActiveAt !== 'number') continue
290
+ if (latest === undefined || session.lastActiveAt > latest) latest = session.lastActiveAt
291
+ }
292
+ return latest
293
+ }
@@ -0,0 +1,218 @@
1
+ /**
2
+ * 快照编排。
3
+ *
4
+ * 采集分八步,每一步只依赖前面几步的产物:
5
+ * 1. profile 声明的 bundle 顺序 → 层归因优先级;
6
+ * 2. 每个组合包插入/覆盖了哪些行;
7
+ * 3. 用户自己的 profile / home patch;
8
+ * 4. 逐条 Loader 行(含服务供需与统计);
9
+ * 5. 模式(Agent 预设)与会话归属;
10
+ * 6. 工具注入全景(全局 ∪ 各活会话);
11
+ * 7. 提示词注册表与名字级归属;
12
+ * 8. 汇总成一份可直接序列化的 JSON。
13
+ * @module dsh-plugin-console/host/snapshot
14
+ */
15
+
16
+ import {
17
+ annotateSessionDiffs,
18
+ attributeTool,
19
+ backfillMcpTools,
20
+ buildModeOnlyEntries,
21
+ buildOwnerIndex,
22
+ computePresetDifferences,
23
+ computePresetLayer,
24
+ matchOwners,
25
+ scanModeOnlyModules,
26
+ } from './attribution.js'
27
+ import { collectEntries, indexRowsByModule } from './entries.js'
28
+ import { computeHealth } from './health.js'
29
+ import { collectBundles, collectUserLayers } from './layers.js'
30
+ import { readModes } from './modes.js'
31
+ import { readPromptRegistry } from './prompt.js'
32
+ import { attachScopeImpacts } from './scope-impact.js'
33
+ import { readSessions } from './sessions.js'
34
+ import { readScopedSchemas, readVisibleTools } from './tools.js'
35
+
36
+ /**
37
+ * 采集一份完整的插件树快照。
38
+ * @param {object} ctx - host 插件上下文。
39
+ * @param {object} [extras] - 额外要挂进快照的东西(模板绑定等)。
40
+ * @returns {Promise<object>} 可直接序列化为 JSON 的快照。
41
+ */
42
+ export async function readSnapshot(ctx, extras = {}) {
43
+ const profile = ctx.get('profileContext')
44
+ const pluginManager = ctx.get('pluginManager')
45
+ const packages = ctx.get('pluginPackages')
46
+
47
+ // —— 1~3. 层:bundle 顺序、bundle 认领、用户 patch ——
48
+ const { rowOwner, rowOverriders, layerList, enabledBundles } = await collectBundles(profile, pluginManager)
49
+ const { userInserted, userOverrides, userLayers } = await collectUserLayers(profile)
50
+
51
+ // —— 4. 逐条 Loader 行 ——
52
+ const { entries, services, stats } = await collectEntries(
53
+ ctx,
54
+ packages,
55
+ rowOwner,
56
+ rowOverriders,
57
+ userInserted,
58
+ userOverrides,
59
+ )
60
+
61
+ // —— 5. 模式(Agent 预设)与会话归属 ——
62
+ const rowsByModule = indexRowsByModule(entries)
63
+ const modes = await readModes(ctx, rowsByModule)
64
+ const sessionIndex = await readSessions(ctx, profile)
65
+ stats.modes = modes.length
66
+ stats.sessions = sessionIndex.sessions.length
67
+ stats.liveSessions = sessionIndex.sessions.filter((session) => session.live === true).length
68
+
69
+ // —— 6. 工具注入全景 ——
70
+ // 全局视图(无 scope)是该部署在 agent 之外的默认工具集;
71
+ // 某个 agent 的可见集若比它多,差额就是该 agent 的 preset scope 注入的工具。
72
+ const globalTools = readVisibleTools(ctx) ?? []
73
+ const liveAgents = sessionIndex.sessions
74
+ .filter((session) => session.live === true && Array.isArray(session.runtime?.tools))
75
+ .map((session) => ({
76
+ sessionId: session.id,
77
+ preset: session.runtime.preset,
78
+ tools: session.runtime.tools,
79
+ // restrict 之前的已知集;与 tools 的差集才是「被 restrict 过滤」。
80
+ knownNames: session.runtime.knownNames,
81
+ }))
82
+
83
+ // —— 7. 提示词注册表 + 工具/区段的名字级归属 ——
84
+ // 注册表给「有什么」,源码扫描给「谁注册的」;两边按名字连接。
85
+ const promptRegistry = await readPromptRegistry(ctx)
86
+ const index = buildOwnerIndex(entries)
87
+ const { entryByRow, toolOwners, sectionOwners } = index
88
+ // 有些插件只出现在模式声明里,不在全局条目树中(present / schedule / ask_user 都是),
89
+ // 它们同样会注册工具与提示词,但没有任何「行」可供扫描。
90
+ const packageRoot = await scanModeOnlyModules(entries, modes, toolOwners, sectionOwners)
91
+ const modeOnlyEntries = packageRoot === undefined ? [] : buildModeOnlyEntries(entries, modes)
92
+ entries.push(...modeOnlyEntries)
93
+
94
+ // 工具集取「全局 ∪ 各活会话」的并集。
95
+ //
96
+ // 只看全局会漏掉一半:read / write / bash / glob 这些是模式通过 agent scope
97
+ // 注册的,全局视图里根本不存在(实测全局 62 个、每个会话 94 个,差 32 个全是核心工具)。
98
+ // 并集里每个工具标注它在哪些范围可见,这样「全局」与「某会话」都能对上。
99
+ const schemaByName = new Map((promptRegistry?.tools ?? []).map((tool) => [tool.name, tool]))
100
+ for (const agent of liveAgents) {
101
+ const agentCtx = ctx.get('agents')?.get?.(agent.sessionId)?.ctx
102
+ if (agentCtx === undefined) continue
103
+ for (const schema of readScopedSchemas(ctx, agentCtx)) {
104
+ if (!schemaByName.has(schema.name)) schemaByName.set(schema.name, schema)
105
+ }
106
+ }
107
+
108
+ const toolScopes = new Map()
109
+ for (const name of globalTools) {
110
+ const list = toolScopes.get(name) ?? []
111
+ list.push('global')
112
+ toolScopes.set(name, list)
113
+ }
114
+ for (const agent of liveAgents) {
115
+ for (const name of agent.tools ?? []) {
116
+ const list = toolScopes.get(name) ?? []
117
+ if (!list.includes('global')) list.push(agent.sessionId)
118
+ toolScopes.set(name, list)
119
+ }
120
+ }
121
+ const allToolNames = [...toolScopes.keys()]
122
+
123
+ // 一个会话的工具集是怎么来的,需要区分三层:
124
+ //
125
+ // 1. 全局层:不带 scope 注册的工具,所有会话都看得到;
126
+ // 2. 模式层:模式的声明行在 agent scope 上注册的工具。*同模式的会话共享同一份*
127
+ // ——`agentPresets` 的 `retain(id)` 返回同一份 generation,`bind` 只是把会话
128
+ // 的 scope 挂到那份上,所以工具不是每个会话各建一套;
129
+ // 3. 会话层:会话自己的 scope 注册的。实测为空——没有哪个会话注册了模式之外的工具。
130
+ const presetLayer = computePresetLayer(modes, entries, liveAgents, globalTools)
131
+ annotateSessionDiffs(liveAgents, presetLayer, globalTools)
132
+ // scope 影响:活会话用自己的 agent scope;没有活会话的模式临时建 preset scope,
133
+ // 读完立刻释放。它只回答「差集」,不推断覆盖者。
134
+ await attachScopeImpacts(ctx, modes, liveAgents, globalTools)
135
+ const presetDifferences = computePresetDifferences(liveAgents)
136
+
137
+ // MCP 回填必须在归属之前:toolOwners 是一座「名字 → 行」的索引,
138
+ // MCP 后缀反推出来的工具名要能落回 mcp-client 那一行。
139
+ backfillMcpTools(entries, allToolNames)
140
+
141
+ const toolsAttributed = allToolNames.map((name) => {
142
+ const schema = schemaByName.get(name)
143
+ return {
144
+ name,
145
+ ...attributeTool(name, index),
146
+ scopes: toolScopes.get(name) ?? [],
147
+ ...(schema === undefined
148
+ ? {}
149
+ : {
150
+ description: schema.description,
151
+ parameters: schema.parameters,
152
+ deferLoading: schema.deferLoading,
153
+ }),
154
+ }
155
+ })
156
+
157
+ const sectionsAttributed = (promptRegistry?.sections ?? []).map((section) => ({ ...section, ...matchOwners(sectionOwners, section.name, entryByRow) }))
158
+ const contextsAttributed = (promptRegistry?.contexts ?? []).map((context) => ({ ...context, ...matchOwners(sectionOwners, context.name, entryByRow) }))
159
+
160
+ stats.entries = entries.length
161
+ stats.plugins = entries.length
162
+ stats.modeOnly = modeOnlyEntries.length
163
+ stats.tools = allToolNames.length
164
+ stats.toolsGlobal = globalTools.length
165
+ stats.promptSections = sectionsAttributed.length
166
+ stats.toolsAttributed = toolsAttributed.filter((tool) => tool.owners.length > 0).length
167
+ stats.sectionsAttributed = sectionsAttributed.filter((section) => section.owners.length > 0).length
168
+
169
+ // 健康摘要只聚合已采集到的静态事实:失败、缺服务、归属盲区、条件禁用。
170
+ // 它不读 session log,因此可以跟着快照一起刷新,不会把首屏拖慢。
171
+ const { summary: health, attention } = computeHealth({
172
+ entries,
173
+ services,
174
+ tools: { attributed: toolsAttributed },
175
+ prompt: { sections: sectionsAttributed, contexts: contextsAttributed },
176
+ })
177
+
178
+ return {
179
+ generatedAt: new Date().toISOString(),
180
+ profile: {
181
+ name: profile?.name ?? null,
182
+ dir: profile?.dir ?? null,
183
+ home: profile?.home ?? null,
184
+ bundles: enabledBundles,
185
+ },
186
+ layers: layerList,
187
+ userLayers,
188
+ stats,
189
+ health,
190
+ attention,
191
+ entries,
192
+ services,
193
+ modes,
194
+ workspaces: sessionIndex.workspaces,
195
+ ungroupedSessions: sessionIndex.ungrouped,
196
+ dispatch: sessionIndex.dispatch,
197
+ tools: {
198
+ global: globalTools,
199
+ liveAgents,
200
+ attributed: toolsAttributed,
201
+ /** 模式层:每个模式在 agent scope 上挂的工具。 */
202
+ presetLayer: [...presetLayer.entries()].map(([id, layer]) => ({ presetId: id, ...layer })),
203
+ /** 同模式会话之间的实际差异;空数组表示所有同模式会话完全一致。 */
204
+ presetDifferences,
205
+ },
206
+ prompt: {
207
+ sections: sectionsAttributed,
208
+ contexts: contextsAttributed,
209
+ // 名字 → 产出它的模块。会话级上下文与消息注入不在全局注册表里,
210
+ // 但它们的名字仍写在包源码中,这份索引让按会话懒读到的条目也能归属。
211
+ nameOwners: Object.fromEntries(sectionOwners),
212
+ },
213
+ // 模板绑定:哪些会话绑了模板、现在是否启用。会话页的开关读这一份。
214
+ bindings: extras.bindings ?? {},
215
+ // 模板列表本身也带上,会话页要显示「绑的是哪个模板」而不只是 id。
216
+ templates: extras.templates ?? [],
217
+ }
218
+ }