@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,284 @@
1
+ /**
2
+ * 按真实发送顺序拼出首请求的 user-role 消息。
3
+ *
4
+ * 顺序不是猜的:日志里一条 `standard` 会话的首请求依次是
5
+ * user → agent-instructions → runtime-context → skill-catalog → time-context。
6
+ * 依据是各自挂在哪里:
7
+ * - `agent-instructions` 在 `agent/pre-step` 里插到 claimed 消息之后;
8
+ * - runtime-context 由 loop 的默认 decision 追加;
9
+ * - skill-catalog 与 skill-invocation 依次 append;
10
+ * - time-context 的 prepend 监听器最后把时间快照放到末尾。
11
+ *
12
+ * 每条消息都带「这是什么、凭什么这样预测、有多确定」,页面据此区分实测与推导。
13
+ * @module dsh-plugin-console/host/preview-messages
14
+ */
15
+
16
+ import { previewRuntimeContext } from './preview-contexts.js'
17
+ import { previewInstructions } from './preview-instructions.js'
18
+ import { hostModuleResolver } from './preview-modules.js'
19
+ import { invokedSkillNames, previewSkillInvocation, previewSkills } from './preview-skills.js'
20
+ import { overlayPreviewMessages } from './recipe-overlay.js'
21
+
22
+ /** 时间快照的 pre-step 所有者;宿主行与模式挂载任一成立就会发这条消息。 */
23
+ const TIME_MODULE = '@deepseek-ai/dsh-time-context'
24
+
25
+ /** 三段会话依赖上下文分别由谁注册,用于溯源。 */
26
+ const CONTEXT_OWNERS = {
27
+ 'working-directory:current': '@deepseek-ai/dsh-working-directory',
28
+ 'sandbox:policy': '@deepseek-ai/dsh-sandbox-policy',
29
+ 'approval:policy': '@deepseek-ai/dsh-user-approval',
30
+ }
31
+
32
+ /**
33
+ * 一条消息。
34
+ * @param {object} init - 字段。
35
+ * @returns {object} 消息。
36
+ */
37
+ function message(init) {
38
+ return {
39
+ index: 0,
40
+ sourceKind: init.sourceKind,
41
+ role: init.role ?? 'user',
42
+ text: init.text,
43
+ // 占位行有文案但没有内容,所以长度可以显式给 0;其余消息按正文算。
44
+ length: init.length ?? init.text.length,
45
+ mechanism: init.mechanism,
46
+ owners: init.owners ?? [],
47
+ confidence: init.confidence,
48
+ basis: init.basis ?? [],
49
+ ...(init.parts === undefined ? {} : { parts: init.parts }),
50
+ ...(init.unavailable === undefined ? {} : { unavailable: init.unavailable }),
51
+ ...(init.incomplete === true ? { incomplete: true } : {}),
52
+ }
53
+ }
54
+
55
+ /**
56
+ * ISO 形状 + 偏移 + IANA 时区名的时间戳,与 DSH 的 time-context 逐字一致。
57
+ * @param {number} now - 预览时刻(epoch ms)。
58
+ * @param {string | undefined} timeZone - 展示时区。
59
+ * @returns {string} 时间戳文本。
60
+ */
61
+ function formatTimestamp(now, timeZone) {
62
+ const formatter = new Intl.DateTimeFormat('en-US', {
63
+ ...(timeZone === undefined ? {} : { timeZone }),
64
+ year: 'numeric',
65
+ month: '2-digit',
66
+ day: '2-digit',
67
+ hour: '2-digit',
68
+ minute: '2-digit',
69
+ second: '2-digit',
70
+ hourCycle: 'h23',
71
+ timeZoneName: 'longOffset',
72
+ })
73
+ const parts = Object.fromEntries(formatter.formatToParts(now).map((part) => [part.type, part.value]))
74
+ const offset = (parts.timeZoneName ?? 'GMT+00:00').replace(/^GMT$/, 'GMT+00:00').slice(3)
75
+ const zone = timeZone ?? formatter.resolvedOptions().timeZone
76
+ return `${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:${parts.second}${offset}[${zone}]`
77
+ }
78
+
79
+ /**
80
+ * 预测 `time-context` 消息。
81
+ *
82
+ * 时间取**预览时刻**而不是发送时刻,页面要标明这一点;首请求没有前序消息,
83
+ * 所以 elapsed 恒为 `unavailable`。时间戳用行配置的时区(缺省为服务端时区),
84
+ * 浏览器时区那一行只反映客户端上报的值——两者在 DSH 里本来就是分开的。
85
+ * @param {object} conditions - 已解析条件。
86
+ * @param {object} devices - 模块判定器(`resolveModules()` 或宿主层判定器)。
87
+ * @param {number} now - 预览时刻。
88
+ * @returns {object} `{ available, text, reason? }`。
89
+ */
90
+ function previewTimeContext(conditions, devices, now) {
91
+ const device = devices.get(TIME_MODULE)
92
+ if (!device.available) return { available: false, reason: device.reason }
93
+ let stamp
94
+ try {
95
+ stamp = formatTimestamp(now, typeof device.config?.timeZone === 'string' ? device.config.timeZone : undefined)
96
+ } catch (error) {
97
+ return { available: false, reason: `时区不可用:${error instanceof Error ? error.message : String(error)}` }
98
+ }
99
+ const browserLine = conditions.clientTimeZoneSource === 'client'
100
+ ? `Browser time zone for this request: ${conditions.clientTimeZone}. Interpret otherwise-unqualified dates and times in this zone.`
101
+ : 'Browser time zone for this request: unavailable. Ask the user to clarify otherwise-unqualified dates and times.'
102
+ return {
103
+ available: true,
104
+ text: [
105
+ `Time sampled while preparing turn 1, step 1: ${stamp}`,
106
+ browserLine,
107
+ 'Elapsed since the preceding model-visible message: unavailable.',
108
+ ].join('\n'),
109
+ }
110
+ }
111
+
112
+ /**
113
+ * 拼出一次首请求的全部 user-role 消息。
114
+ * @param {object} ctx - host 插件上下文。
115
+ * @param {object} options - 条件与装配结果。
116
+ * @param {object} options.assembly - `previewAssembly()` 的结果。
117
+ * @param {object} options.conditions - `resolveConditions()` 的结果。
118
+ * @param {symbol | undefined} options.scopeKey - 预设 scope。
119
+ * @param {object} [options.modules] - `resolveModules()` 的结果;省略时只按宿主行判定。
120
+ * @param {string} [options.draft] - 首条消息草稿;有值时它成为 user 消息正文。
121
+ * @param {object} [options.recipe] - 提示词模板配方;提供时在基线之后叠加覆盖。
122
+ * @param {number} [options.now] - 预览时刻。
123
+ * @returns {Promise<{messages: Array<object>, skipped: Array<object>, warnings: Array<string>, applied: object}>} 消息与诊断。
124
+ */
125
+ export async function previewMessages(ctx, options) {
126
+ const { assembly, conditions, scopeKey } = options
127
+ const now = options.now ?? Date.now()
128
+ const draft = typeof options.draft === 'string' ? options.draft : ''
129
+ // 一次预演只解析一份模块判定:三个采集器必须看到同一份「谁在跑」的答案。
130
+ const modules = options.modules ?? hostModuleResolver(ctx)
131
+ const messages = []
132
+ const skipped = []
133
+
134
+ // 1. 首条用户消息。有草稿就用草稿;没有就留一行占位,并明确「没有内容」。
135
+ if (draft.length > 0) {
136
+ messages.push(message({
137
+ sourceKind: 'user',
138
+ text: draft,
139
+ mechanism: 'user input',
140
+ confidence: 'derived',
141
+ basis: ['draft'],
142
+ parts: [],
143
+ }))
144
+ } else {
145
+ messages.push(message({
146
+ sourceKind: 'user',
147
+ text: '(未输入首条消息)',
148
+ length: 0,
149
+ mechanism: 'user input',
150
+ confidence: 'unknown',
151
+ basis: ['draft'],
152
+ parts: [],
153
+ unavailable: { reason: '草稿未提供:附件、图片与 `/skill` 调用都不会被预测' },
154
+ }))
155
+ }
156
+
157
+ // 2. agent-instructions:行没挂或没有可读文件时整条不出现,不是空消息。
158
+ const instructions = await previewInstructions(ctx, {
159
+ workspacePath: conditions?.workspace?.path,
160
+ modules,
161
+ })
162
+ if (instructions.available && instructions.text.length > 0) {
163
+ messages.push(message({
164
+ sourceKind: 'agent-instructions',
165
+ text: instructions.text,
166
+ mechanism: 'agent/pre-step',
167
+ owners: ['@deepseek-ai/dsh-agent-instructions'],
168
+ confidence: 'derived',
169
+ basis: ['workspace'],
170
+ parts: instructions.files,
171
+ }))
172
+ } else if (instructions.available) {
173
+ skipped.push({ sourceKind: 'agent-instructions', reason: '这个工作区没有指令文件(例如AGENTS.md、CLAUDE.md)' })
174
+ } else {
175
+ skipped.push({ sourceKind: 'agent-instructions', reason: instructions.reason })
176
+ }
177
+
178
+ // 3. runtime-context:实测段与推导段拼成一份快照。
179
+ const runtime = previewRuntimeContext(assembly, conditions, options.recipe?.contexts)
180
+ if (runtime.text.length > 0) {
181
+ messages.push(message({
182
+ sourceKind: 'runtime-context',
183
+ text: runtime.text,
184
+ mechanism: 'agent-loop',
185
+ confidence: runtime.segments.every((item) => item.confidence === 'measured') ? 'measured' : 'derived',
186
+ basis: ['workspace', 'permission'],
187
+ // 文本为空的段不会进入消息正文,也不属于「这条消息包含什么」:
188
+ // 它们由消息视图按 `preview.contexts` 列进「注册了但没有进入这条消息」。
189
+ parts: runtime.segments
190
+ .filter((item) => item.text.length > 0)
191
+ .map((item) => ({
192
+ name: item.name,
193
+ order: item.order,
194
+ text: item.text,
195
+ length: item.text.length,
196
+ confidence: item.confidence,
197
+ owners: CONTEXT_OWNERS[item.name] === undefined ? [] : [CONTEXT_OWNERS[item.name]],
198
+ ...(item.basis === undefined ? {} : { basis: item.basis }),
199
+ ...(item.reason === undefined ? {} : { reason: item.reason }),
200
+ ...(item.overridden === true ? { overridden: true } : {}),
201
+ })),
202
+ }))
203
+ } else {
204
+ skipped.push({ sourceKind: 'runtime-context', reason: '没有生效的运行时上下文' })
205
+ }
206
+
207
+ // 4. skill 目录:工具不可见、快照不完整或目录为空时都不生成消息。
208
+ const skills = await previewSkills(ctx, {
209
+ workspacePath: conditions?.workspace?.path,
210
+ scopeKey,
211
+ tools: assembly?.tools ?? [],
212
+ modules,
213
+ })
214
+ if (skills.available && skills.text.length > 0) {
215
+ messages.push(message({
216
+ sourceKind: 'skill-catalog',
217
+ text: skills.text,
218
+ mechanism: 'agent/pre-step',
219
+ owners: ['@deepseek-ai/dsh-tool-skill'],
220
+ confidence: 'derived',
221
+ basis: ['workspace', 'preset', 'skills-service'],
222
+ parts: skills.entries,
223
+ incomplete: skills.incomplete,
224
+ }))
225
+ } else if (skills.available) {
226
+ skipped.push({ sourceKind: 'skill-catalog', reason: '目录为空' })
227
+ } else {
228
+ skipped.push({ sourceKind: 'skill-catalog', reason: skills.reason })
229
+ }
230
+
231
+ // 5. `/name` 手势带出来的 skill 正文。只有草稿里出现手势时才存在,且每个名字一条消息。
232
+ for (const name of invokedSkillNames(draft)) {
233
+ const invocation = await previewSkillInvocation(ctx, {
234
+ name,
235
+ workspacePath: conditions?.workspace?.path,
236
+ scopeKey,
237
+ modules,
238
+ })
239
+ if (invocation.available && invocation.text.length > 0) {
240
+ messages.push(message({
241
+ sourceKind: 'skill-invocation',
242
+ text: invocation.text,
243
+ mechanism: 'agent/pre-step',
244
+ owners: ['@deepseek-ai/dsh-tool-skill'],
245
+ confidence: 'derived',
246
+ basis: ['draft', 'workspace'],
247
+ parts: [invocation.skill],
248
+ }))
249
+ } else {
250
+ skipped.push({ sourceKind: 'skill-invocation:' + name, reason: invocation.reason })
251
+ }
252
+ }
253
+
254
+ // 6. time-context:宿主行或当前模式挂载了它才会出现。
255
+ const time = previewTimeContext(conditions, modules, now)
256
+ if (time.available) {
257
+ messages.push(message({
258
+ sourceKind: 'time-context',
259
+ text: time.text,
260
+ mechanism: 'agent/pre-step',
261
+ owners: ['@deepseek-ai/dsh-time-context'],
262
+ confidence: 'derived',
263
+ basis: ['client-time-zone'],
264
+ parts: [{ sampledAt: now, timeZone: conditions.clientTimeZone, timeZoneSource: conditions.clientTimeZoneSource }],
265
+ }))
266
+ } else {
267
+ skipped.push({ sourceKind: 'time-context', reason: time.reason })
268
+ }
269
+
270
+ // 模板叠加放在最后:它改的是“所有内置注入完成之后模型会看到的文字”,
271
+ // 与真实请求里 pre-step 监听器的位置一致。
272
+ const overlaid = options.recipe === undefined
273
+ ? { messages, skipped, applied: { messages: [], catalogEntries: [], skipped: [] } }
274
+ : overlayPreviewMessages(messages, skipped, options.recipe, assembly)
275
+ overlaid.messages.forEach((item, index) => {
276
+ item.index = index + 1
277
+ })
278
+ return {
279
+ messages: overlaid.messages,
280
+ skipped: overlaid.skipped,
281
+ warnings: modules.warnings ?? [],
282
+ applied: overlaid.applied,
283
+ }
284
+ }
@@ -0,0 +1,233 @@
1
+ /**
2
+ * 预演用的「这条 pre-step 插件到底会不会运行」判定。
3
+ *
4
+ * **不能只看宿主 Loader 行。** web/desktop profile 会在 bundle patch 里把
5
+ * `agent-instructions` 与 `tool-skill` 的宿主行显式 `disabled: true`,改由 agent
6
+ * preset 在独立的内存 Loader 树里挂载;`time-context` 更是只有 preset 声明、
7
+ * 连宿主行都没有。只查 `ctx.loader.entries()` 会把「模式里正 active 的插件」说成
8
+ * 「插件已禁用」,于是三条注入消息永远不出现——这正是本模块存在的原因。
9
+ *
10
+ * 判定口径是「宿主启用了 **或** 当前模式挂载了」:两者任一成立,这条 pre-step
11
+ * 监听器都会对新会话生效。
12
+ *
13
+ * 配置始终取宿主行:`compositionInventory()` 只暴露 entryId / moduleName /
14
+ * enabled / condition,不暴露 preset 行的 config。取不到时由各采集器退回 DSH
15
+ * 缺省值(见各自的 DEFAULTS),页面据此把「按缺省值推导」和「实测」分开标。
16
+ * @module dsh-plugin-console/host/preview-modules
17
+ */
18
+
19
+ /** 预演真正消费的模块;条件挂载的警告只针对这几个,不淹没其它条件行。 */
20
+ const TRACKED = [
21
+ '@deepseek-ai/dsh-agent-instructions',
22
+ '@deepseek-ai/dsh-tool-skill',
23
+ '@deepseek-ai/dsh-time-context',
24
+ '@deepseek-ai/dsh-skill-filesystem',
25
+ ]
26
+
27
+ /** 模型看得到的短名;警告与 skipped 原因里用它,而不是整条包名。 */
28
+ const LABELS = {
29
+ '@deepseek-ai/dsh-agent-instructions': 'agent-instructions',
30
+ '@deepseek-ai/dsh-tool-skill': 'tool-skill',
31
+ '@deepseek-ai/dsh-time-context': 'time-context',
32
+ '@deepseek-ai/dsh-skill-filesystem': 'skill-filesystem',
33
+ }
34
+
35
+ /**
36
+ * @param {string} moduleName - 包名。
37
+ * @returns {string} 展示名。
38
+ */
39
+ function labelOf(moduleName) {
40
+ return LABELS[moduleName] ?? moduleName
41
+ }
42
+
43
+ /**
44
+ * 一条模块判定结果。
45
+ * @param {object} init - 字段。
46
+ * @returns {object} 判定记录。
47
+ */
48
+ function record(init) {
49
+ return {
50
+ name: init.name,
51
+ available: init.available,
52
+ /** `host` / `preset` / `both`;不可用时为 null。 */
53
+ source: init.source ?? null,
54
+ config: init.config,
55
+ /** 模式里按 `!!js` 条件挂载:会不会生效取决于运行时条件。 */
56
+ conditional: init.conditional === true,
57
+ reason: init.reason,
58
+ }
59
+ }
60
+
61
+ /**
62
+ * 读宿主 Loader 行:模块名 → `{ enabled, config }`。
63
+ *
64
+ * 同名多行(例如 profile 的 `include:` 行与 bundle 行)时,只要有一行启用就算
65
+ * 启用;配置取第一份带配置的,避免后一个空配置盖掉真正的值。
66
+ * @param {object} ctx - host 插件上下文。
67
+ * @returns {Map<string, {enabled: boolean, config: object | undefined}>} 宿主行。
68
+ */
69
+ function hostRows(ctx) {
70
+ const rows = new Map()
71
+ let entries = []
72
+ try {
73
+ entries = ctx.loader?.entries?.() ?? []
74
+ } catch {
75
+ entries = []
76
+ }
77
+ for (const entry of entries) {
78
+ const name = entry?.options?.name
79
+ if (typeof name !== 'string') continue
80
+ let enabled = true
81
+ try {
82
+ enabled = !entry.disabled
83
+ } catch {
84
+ enabled = true
85
+ }
86
+ const known = rows.get(name)
87
+ rows.set(name, {
88
+ enabled: enabled || known?.enabled === true,
89
+ config: known?.config ?? entry.options?.config,
90
+ })
91
+ }
92
+ return rows
93
+ }
94
+
95
+ /**
96
+ * 读当前模式的声明组合:模块名 → `{ enabled, conditional }`。
97
+ *
98
+ * 只有 `compositionInventory()` 是公开且带启用状态的来源;`enabled` 为
99
+ * `'conditional'` 表示这一行带 `!!js` 条件,预演不知道条件结果,按「挂载了但
100
+ * 可能不生效」处理并留警告。
101
+ * @param {object} ctx - host 插件上下文。
102
+ * @param {string | undefined} presetId - 目标模式。
103
+ * @returns {Promise<{rows: Map<string, {enabled: boolean, conditional: boolean}> | null, id: string | undefined, warning: string | undefined}>} 组合与诊断。
104
+ */
105
+ async function presetRows(ctx, presetId) {
106
+ const presets = ctx.get('agentPresetRegistry') ?? ctx.get('agentPresets')
107
+ if (presets === undefined || typeof presets.compositionInventory !== 'function') {
108
+ return { rows: null, id: presetId, warning: '模式注册表不可用:预演只覆盖宿主层' }
109
+ }
110
+ let inventory
111
+ try {
112
+ inventory = await presets.compositionInventory()
113
+ } catch (error) {
114
+ const message = error instanceof Error ? error.message : String(error)
115
+ return { rows: null, id: presetId, warning: `模式组合读取失败:${message}` }
116
+ }
117
+ const mode = inventory.find((row) => row?.id === presetId)
118
+ ?? inventory.find((row) => row?.isDefault === true)
119
+ ?? inventory[0]
120
+ if (mode === undefined) {
121
+ return { rows: null, id: presetId, warning: '没有可用的模式:预演只覆盖宿主层' }
122
+ }
123
+ const rows = new Map()
124
+ for (const row of mode.rows ?? []) {
125
+ const name = row?.moduleName
126
+ if (typeof name !== 'string') continue
127
+ const conditional = row.enabled === 'conditional'
128
+ const enabled = row.enabled !== false
129
+ const known = rows.get(name)
130
+ rows.set(name, {
131
+ enabled: enabled || known?.enabled === true,
132
+ conditional: conditional || known?.conditional === true,
133
+ })
134
+ }
135
+ return { rows, id: mode.id, warning: undefined }
136
+ }
137
+
138
+ /**
139
+ * 只在宿主层判定(供直接调用采集器的场景使用)。
140
+ *
141
+ * 生产路径由 `request-preview.js` 用 `resolveModules()` 一次解析;这个同步版本
142
+ * 只是让「没有模式上下文」的调用保持原来的语义,不静默改变行为。
143
+ * @param {object} ctx - host 插件上下文。
144
+ * @returns {object} 与 `resolveModules()` 同形的判定器。
145
+ */
146
+ export function hostModuleResolver(ctx) {
147
+ const host = hostRows(ctx)
148
+ return {
149
+ presetId: undefined,
150
+ presetKnown: false,
151
+ warnings: [],
152
+ get(name) {
153
+ const row = host.get(name)
154
+ if (row === undefined) {
155
+ return record({ name, available: false, reason: `${labelOf(name)} 未挂载` })
156
+ }
157
+ if (!row.enabled) {
158
+ return record({ name, available: false, config: row.config, reason: `${labelOf(name)} 已禁用` })
159
+ }
160
+ return record({ name, available: true, source: 'host', config: row.config })
161
+ },
162
+ onlyFromPreset() {
163
+ return false
164
+ },
165
+ }
166
+ }
167
+
168
+ /**
169
+ * 解析一次预演里所有模块的可用性:宿主层 + 目标模式。
170
+ * @param {object} ctx - host 插件上下文。
171
+ * @param {string | undefined} presetId - 目标模式;省略时用 roster 的默认模式。
172
+ * @returns {Promise<object>} `{ presetId, presetKnown, warnings, get, onlyFromPreset }`。
173
+ */
174
+ export async function resolveModules(ctx, presetId) {
175
+ const host = hostRows(ctx)
176
+ const preset = await presetRows(ctx, presetId)
177
+
178
+ const get = (name) => {
179
+ const hostRow = host.get(name)
180
+ const presetRow = preset.rows?.get(name)
181
+ const hostEnabled = hostRow?.enabled === true
182
+ const presetEnabled = presetRow?.enabled === true
183
+ if (hostEnabled || presetEnabled) {
184
+ return record({
185
+ name,
186
+ available: true,
187
+ source: hostEnabled && presetEnabled ? 'both' : (presetEnabled ? 'preset' : 'host'),
188
+ config: hostRow?.config,
189
+ // 宿主已经无条件挂载时,模式里的条件行不再是唯一来源。
190
+ conditional: presetRow?.conditional === true && !hostEnabled,
191
+ })
192
+ }
193
+ let reason
194
+ if (preset.rows === null) {
195
+ reason = hostRow === undefined
196
+ ? `${labelOf(name)} 未挂载(宿主层没有这一行)`
197
+ : `${labelOf(name)} 已禁用`
198
+ } else if (presetRow !== undefined) {
199
+ reason = `${labelOf(name)} 在当前模式里被禁用`
200
+ } else if (hostRow !== undefined) {
201
+ reason = `${labelOf(name)} 未挂载:宿主行已禁用,当前模式也没有这一行`
202
+ } else {
203
+ reason = `${labelOf(name)} 未挂载:宿主与当前模式都没有这一行`
204
+ }
205
+ return record({ name, available: false, config: hostRow?.config, reason })
206
+ }
207
+
208
+ // 条件挂载只警告一次:missing 的判定仍按「挂载了」算,页面才不会被误报成缺消息。
209
+ const conditional = TRACKED.filter((name) => get(name).conditional)
210
+ return {
211
+ presetId: preset.id,
212
+ presetKnown: preset.rows !== null,
213
+ warnings: [
214
+ ...(preset.warning === undefined ? [] : [preset.warning]),
215
+ ...(conditional.length === 0
216
+ ? []
217
+ : [`${conditional.map(labelOf).join('、')} 在当前模式里是条件挂载,实际是否生效取决于运行时条件`]),
218
+ ],
219
+ get,
220
+ /**
221
+ * 该模块是否只由模式提供。
222
+ *
223
+ * skill 目录依赖 `skill-filesystem` 注册进模式 scope;宿主层没有它时,
224
+ * 拿不到模式 scope 就读不到任何提供方——这时必须标「不可用」,不能把
225
+ * 空目录说成「这个工作区没有 skill」。
226
+ * @param {string} name - 包名。
227
+ * @returns {boolean} 是否只来自模式。
228
+ */
229
+ onlyFromPreset(name) {
230
+ return preset.rows?.get(name)?.enabled === true && host.get(name)?.enabled !== true
231
+ },
232
+ }
233
+ }