@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,242 @@
1
+ window.__ModuleLoader__.load({
2
+ id: '@cheemsup/dsh-plugin-console',
3
+ chunk: 'client.control.js',
4
+ factory: (require) => {
5
+ const React = require('react')
6
+ const { createElement: h, useCallback, useEffect, useState } = React
7
+
8
+ return function create(deps) {
9
+ const { fetchJson, formatSessionId, textButton, IMPACT_ROUTE, CONTROL_ROUTE, OPERATIONS_ROUTE } = deps
10
+
11
+ /** 控制接口:影响预览、执行、审计。 */
12
+ function useControlStore() {
13
+ const [operations, setOperations] = useState([])
14
+ const [operationsError, setOperationsError] = useState(null)
15
+
16
+ const loadOperations = useCallback(async () => {
17
+ try {
18
+ const data = await fetchJson(OPERATIONS_ROUTE)
19
+ setOperations(Array.isArray(data.operations) ? data.operations : [])
20
+ setOperationsError(null)
21
+ } catch (cause) {
22
+ setOperationsError(cause instanceof Error ? cause.message : String(cause))
23
+ }
24
+ }, [fetchJson])
25
+
26
+ const preview = useCallback(async (rowId) => {
27
+ const encoded = typeof encodeURIComponent === 'function' ? encodeURIComponent(rowId) : rowId
28
+ return fetchJson(IMPACT_ROUTE + '?id=' + encoded)
29
+ }, [fetchJson])
30
+
31
+ const execute = useCallback(async (payload) => fetchJson(CONTROL_ROUTE, {
32
+ method: 'POST',
33
+ body: JSON.stringify(payload),
34
+ }), [fetchJson])
35
+
36
+ return { operations, operationsError, loadOperations, preview, execute }
37
+ }
38
+
39
+ /** 影响预览里的一行。 */
40
+ function line(label, value) {
41
+ return h(React.Fragment, { key: label }, h('dt', null, label), h('dd', null, value))
42
+ }
43
+
44
+ /**
45
+ * 插件详情里的控制段。
46
+ * @param {object} entry - 目标插件。
47
+ * @param {object} options - `{ control, sessions, reload }`。
48
+ * @returns {object} React 节点。
49
+ */
50
+ function renderControlSection(entry, options) {
51
+ return h(ControlPanel, { entry, ...options })
52
+ }
53
+
54
+ function ControlPanel({ entry, control, sessions, reload }) {
55
+ const sessionList = Array.isArray(sessions) ? sessions : []
56
+ const [sessionId, setSessionId] = useState(sessionList[0]?.id ?? '')
57
+ const [pending, setPending] = useState(null)
58
+ const [busy, setBusy] = useState(false)
59
+ const [notice, setNotice] = useState(null)
60
+
61
+ useEffect(() => { void control.loadOperations() }, [control.loadOperations])
62
+
63
+ const start = async (action) => {
64
+ setBusy(true)
65
+ setNotice(null)
66
+ try {
67
+ const impact = await control.preview(entry.rowId)
68
+ if (impact.found !== true) {
69
+ setNotice({ tone: 'error', text: impact.reason ?? '影响预览不可用' })
70
+ return
71
+ }
72
+ setPending({ action, impact })
73
+ } catch (cause) {
74
+ setNotice({ tone: 'error', text: '影响预览失败:' + (cause instanceof Error ? cause.message : String(cause)) })
75
+ } finally {
76
+ setBusy(false)
77
+ }
78
+ }
79
+
80
+ const confirm = async () => {
81
+ if (pending === null) return
82
+ setBusy(true)
83
+ try {
84
+ const result = await control.execute({
85
+ action: pending.action,
86
+ rowId: entry.rowId,
87
+ ...(pending.action === 'mask' || pending.action === 'unmask' ? { sessionId } : {}),
88
+ confirmed: true,
89
+ })
90
+ if (result.ok === true) {
91
+ setNotice({
92
+ tone: 'ok',
93
+ text: result.restartRequired === true
94
+ ? '已写入 profile;当前没有可用的 HMR,重启后生效。'
95
+ : result.result?.live === false
96
+ ? '已记录;会话未激活,resume 时生效。'
97
+ : '已执行;快照与活动会重新读取。',
98
+ })
99
+ setPending(null)
100
+ if (typeof reload === 'function') void reload()
101
+ void control.loadOperations()
102
+ } else {
103
+ setNotice({ tone: 'error', text: result.reason ?? '控制失败' })
104
+ }
105
+ } catch (cause) {
106
+ setNotice({ tone: 'error', text: '控制失败:' + (cause instanceof Error ? cause.message : String(cause)) })
107
+ } finally {
108
+ setBusy(false)
109
+ }
110
+ }
111
+
112
+ const impact = pending?.impact
113
+ const blocked = pending?.action === 'mask' && (impact?.tools?.shared?.length ?? 0) > 0
114
+ const isSelf = entry.rowId === 'plugin-console' || entry.moduleName === '@cheemsup/dsh-plugin-console'
115
+ const canGlobal = !isSelf && entry.modeOnly !== true
116
+ const hasTools = (entry.registrations?.tools ?? []).length > 0
117
+
118
+ return h(
119
+ 'div',
120
+ { className: 'ptSection' },
121
+ h('p', { className: 'ptSectionTitle' }, '控制'),
122
+ h(
123
+ 'div',
124
+ { className: 'ptCardRow' },
125
+ h(
126
+ 'button',
127
+ {
128
+ type: 'button',
129
+ className: 'ptBtn',
130
+ 'data-tone': entry.enabled ? 'danger' : 'primary',
131
+ disabled: busy || !canGlobal,
132
+ title: isSelf
133
+ ? '不能在这里关闭插件控制台自身'
134
+ : entry.modeOnly === true
135
+ ? '只由模式挂载,不能通过 profile 启停'
136
+ : '影响所有会话;执行前会显示影响预览',
137
+ onClick: () => void start(entry.enabled ? 'disable' : 'enable'),
138
+ },
139
+ entry.enabled ? '禁用(全局)' : '启用(全局)',
140
+ ),
141
+ h(
142
+ 'label',
143
+ { className: 'ptField' },
144
+ h('span', { className: 'ptFieldLabel' }, '会话'),
145
+ h(
146
+ 'select',
147
+ {
148
+ className: 'ptSelect',
149
+ value: sessionId,
150
+ disabled: busy || sessionList.length === 0,
151
+ onChange: (event) => setSessionId(event.target.value),
152
+ },
153
+ sessionList.length === 0
154
+ ? h('option', { value: '' }, '没有可读会话')
155
+ : sessionList.map((session) => h(
156
+ 'option',
157
+ { key: session.id, value: session.id },
158
+ formatSessionId(session.id) + (session.live ? ' · 运行中' : ' · 冷会话'),
159
+ )),
160
+ ),
161
+ ),
162
+ textButton('屏蔽到会话', () => void start('mask'), {
163
+ disabled: busy || sessionId === '' || !hasTools,
164
+ title: hasTools ? '只隐藏这个插件的工具贡献;不卸载插件,不影响其他会话' : '这个插件没有工具型贡献,暂不支持会话掩码',
165
+ }),
166
+ textButton('解除该会话屏蔽', () => void start('unmask'), {
167
+ disabled: busy || sessionId === '',
168
+ title: '移除这个会话上针对当前插件的掩码',
169
+ }),
170
+ ),
171
+ h('p', { className: 'ptHint', style: { margin: 0 } },
172
+ '全局启停委托 plugin-manager;会话掩码只隐藏工具贡献,不卸载插件、不停服务、不移除事件监听。当前版本掩码不处理提示词段。'),
173
+
174
+ pending === null
175
+ ? null
176
+ : h(
177
+ 'div',
178
+ { className: 'ptCard', style: { margin: '6px 0 0' } },
179
+ h('p', { className: 'ptCardTitle' }, '影响预览'),
180
+ h(
181
+ 'dl',
182
+ { className: 'ptFacts' },
183
+ line('目标', entry.title || entry.packageName || entry.moduleName),
184
+ line('范围', pending.action === 'mask' || pending.action === 'unmask' ? '会话 ' + formatSessionId(sessionId) : '全局(所有会话)'),
185
+ line('失去工具', (impact.tools?.lost ?? []).join('、') || '无'),
186
+ line('共享工具', (impact.tools?.shared ?? []).join('、') || '无'),
187
+ line('失去提示词段', (impact.sections?.lost ?? []).join('、') || '无'),
188
+ line('唯一提供', (impact.services?.soleProviders ?? []).join('、') || '无'),
189
+ line('受影响消费者', (impact.services?.affectedConsumers ?? []).join('、') || '无'),
190
+ line('模式', (impact.modes ?? []).map((mode) => mode.name).join('、') || '无'),
191
+ line('活会话 / 冷会话', `${(impact.liveSessions ?? []).length} / ${impact.coldSessionCount ?? 0}`),
192
+ line('生效', impact.hmr === true ? 'HMR 可用,可能立即生效' : '未检测到 HMR;可能需要重启'),
193
+ ),
194
+ blocked
195
+ ? h('p', { className: 'ptError', style: { margin: 0 } }, '这些工具与其他插件重名,按名字 deny 会连带隐藏对方的同名工具;请先改用按工具名选择,或不要做会话掩码。')
196
+ : null,
197
+ h(
198
+ 'div',
199
+ { className: 'ptCardActions' },
200
+ textButton('取消', () => setPending(null), { disabled: busy }),
201
+ h(
202
+ 'button',
203
+ {
204
+ type: 'button',
205
+ className: 'ptBtn',
206
+ 'data-tone': 'danger',
207
+ disabled: busy || blocked,
208
+ onClick: () => void confirm(),
209
+ },
210
+ busy ? '执行中…' : '确认执行',
211
+ ),
212
+ ),
213
+ ),
214
+
215
+ notice === null
216
+ ? null
217
+ : h('p', { className: notice.tone === 'error' ? 'ptError' : 'ptSub', style: { margin: 0 } }, notice.text),
218
+
219
+ control.operations.length > 0
220
+ ? h(
221
+ 'details',
222
+ { className: 'ptFold ptFoldable', style: { marginTop: '4px' } },
223
+ h('summary', null, h('span', null, '最近控制'), h('span', { className: 'ptFoldMeta' }, control.operations.length + ' 条')),
224
+ h(
225
+ 'ul',
226
+ { className: 'ptDepList', style: { padding: '8px 12px' } },
227
+ control.operations.slice(0, 8).map((operation) => h(
228
+ 'li',
229
+ { key: operation.id },
230
+ h('span', { className: 'ptDepKey' }, operation.action),
231
+ h('span', { className: 'ptDepValue' }, `${operation.target} · ${operation.result} · ${new Date(operation.time).toLocaleString()}`),
232
+ )),
233
+ ),
234
+ )
235
+ : null,
236
+ )
237
+ }
238
+
239
+ return { useControlStore, renderControlSection }
240
+ }
241
+ },
242
+ })
@@ -0,0 +1,77 @@
1
+ /**
2
+ * 通用二次操作弹窗:标题、说明、可选输入控件与确认/取消。
3
+ *
4
+ * 用 fixed 覆盖层而不是面板内的卡片:二次操作要打断当前动作,留在文流里
5
+ * 容易被当成又一段说明滚过去。Esc、点遮罩与「取消」都算取消;没有输入控件时
6
+ * 默认焦点落在「取消」上——危险动作不该一按回车就执行。
7
+ *
8
+ * 本文件是一个包内 chunk:入口用 `require.async('./client.dialog.js')` 取它。
9
+ */
10
+
11
+ window.__ModuleLoader__.load({
12
+ id: '@cheemsup/dsh-plugin-console',
13
+ chunk: 'client.dialog.js',
14
+ factory: (require) => {
15
+ const React = require('react')
16
+ const { createElement: h } = React
17
+
18
+ /**
19
+ * 渲染一个弹窗。
20
+ * @param {object} options - 弹窗内容。
21
+ * @param {string} options.id - 标题节点 id,供 `aria-labelledby` 引用。
22
+ * @param {string} options.title - 弹窗标题。
23
+ * @param {string} options.detail - 影响说明。
24
+ * @param {object} [options.body] - 输入控件;没有时默认焦点落在「取消」。
25
+ * @param {string} options.confirmLabel - 确认按钮文字。
26
+ * @param {boolean} [options.danger] - 确认按钮是否是危险动作。
27
+ * @param {boolean} [options.confirmDisabled] - 是否禁用确认。
28
+ * @param {Function} options.onConfirm - 确认回调。
29
+ * @param {Function} options.onCancel - 取消回调。
30
+ * @returns {object} React 节点。
31
+ */
32
+ function renderDialog(options) {
33
+ const { id, title, detail, body, confirmLabel, danger, confirmDisabled, onConfirm, onCancel } = options
34
+ return h(
35
+ 'div',
36
+ {
37
+ className: 'ptModalOverlay',
38
+ onClick: onCancel,
39
+ onKeyDown: (event) => {
40
+ if (event.key === 'Escape') onCancel()
41
+ },
42
+ },
43
+ h(
44
+ 'div',
45
+ {
46
+ className: 'ptModal',
47
+ role: 'dialog',
48
+ 'aria-modal': 'true',
49
+ 'aria-labelledby': id,
50
+ onClick: (event) => event.stopPropagation(),
51
+ },
52
+ h('p', { className: 'ptModalTitle', id }, title),
53
+ h('p', { className: 'ptHint', style: { margin: 0 } }, detail),
54
+ body ?? null,
55
+ h(
56
+ 'div',
57
+ { className: 'ptModalActions' },
58
+ h('button', { type: 'button', className: 'ptBtn', autoFocus: body === undefined, onClick: onCancel }, '取消'),
59
+ h(
60
+ 'button',
61
+ {
62
+ type: 'button',
63
+ className: 'ptBtn',
64
+ 'data-tone': danger === true ? 'danger' : undefined,
65
+ disabled: confirmDisabled === true,
66
+ onClick: onConfirm,
67
+ },
68
+ confirmLabel,
69
+ ),
70
+ ),
71
+ ),
72
+ )
73
+ }
74
+
75
+ return { renderDialog }
76
+ },
77
+ })
@@ -0,0 +1,280 @@
1
+ /**
2
+ * 提示词模板草稿的纯函数:草稿指纹、基线 → 草稿、草稿 → 配方。
3
+ *
4
+ * 这里不碰 React、不碰 DOM,也不依赖其它 chunk。拆出来的理由很简单:
5
+ * 编辑器文件的其余部分都在描述「长什么样、点了会怎样」,只有这几个函数
6
+ * 描述「数据怎么变」,它们值得被单独看懂、单独验证。
7
+ *
8
+ * 草稿覆盖四类内容:system 段 / runtime-context 逐段 / pre-step 消息 / 工具。
9
+ * `recipeFromDraft` 只写与基线不同的项,保持配方是「差异」而不是整份复制。
10
+ *
11
+ * 本文件是一个包内 chunk:入口用 `require.async('./client.draft.js')` 取它。
12
+ */
13
+
14
+ window.__ModuleLoader__.load({
15
+ id: '@cheemsup/dsh-plugin-console',
16
+ chunk: 'client.draft.js',
17
+ factory: () => {
18
+ /** 找到一条预览消息。 */
19
+ function messageOf(baseline, kind) {
20
+ return (baseline?.messages ?? []).find((message) => message.sourceKind === kind)
21
+ }
22
+
23
+ /** 一段的基线文本(插值后的全文优先)。 */
24
+ function baselineText(section) {
25
+ return typeof section.rendered === 'string' ? section.rendered : (section.text ?? '')
26
+ }
27
+
28
+ /**
29
+ * 基线里的 runtime-context 逐段文本。
30
+ *
31
+ * `baseline.contexts` 是注册表全量(可能文本为空),`runtime-context.parts`
32
+ * 是模型实际收到的那几段(推导段只在这里)。两者合并后,parts 优先。
33
+ * @param {object} baseline - 该条件的预演结果。
34
+ * @returns {Object<string, string>} name → 基线文本。
35
+ */
36
+ function baselineContexts(baseline) {
37
+ const contexts = {}
38
+ for (const context of baseline?.contexts ?? []) {
39
+ if (typeof context?.name !== 'string') continue
40
+ contexts[context.name] = typeof context.text === 'string' ? context.text : ''
41
+ }
42
+ const runtime = messageOf(baseline, 'runtime-context')
43
+ for (const part of runtime?.parts ?? []) {
44
+ if (typeof part?.name !== 'string') continue
45
+ contexts[part.name] = typeof part.text === 'string' ? part.text : ''
46
+ }
47
+ return contexts
48
+ }
49
+
50
+ /** 基线里的 instructions / time 正文;没有消息时为空串。 */
51
+ function baselineMessageText(baseline, kind) {
52
+ return messageOf(baseline, kind)?.text ?? ''
53
+ }
54
+
55
+ /** 基线里的 skill 目录条目:name → { listed, description }。 */
56
+ function baselineCatalog(baseline) {
57
+ const entries = {}
58
+ for (const part of messageOf(baseline, 'skill-catalog')?.parts ?? []) {
59
+ if (typeof part?.name !== 'string') continue
60
+ entries[part.name] = {
61
+ listed: true,
62
+ description: typeof part.description === 'string' ? part.description : '',
63
+ }
64
+ }
65
+ return entries
66
+ }
67
+
68
+ /**
69
+ * 草稿指纹:只由「用户能改的东西」组成,用来判断有没有未保存改动。
70
+ *
71
+ * 换基线条件会把草稿整份重置,所以只要是「和上次载入/保存时不一样」,
72
+ * 换条件就会丢东西,必须问一句。
73
+ * @param {object} draft - 草稿。
74
+ * @returns {string} 可比较的指纹。
75
+ */
76
+ function signatureOf(draft) {
77
+ const catalog = draft.catalog ?? { hidden: false, entries: {} }
78
+ return JSON.stringify([
79
+ draft.append,
80
+ Object.entries(draft.sections ?? {}).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),
81
+ [...(draft.disabled ?? [])].sort(),
82
+ Object.entries(draft.contexts ?? {}).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),
83
+ [draft.instructions?.text ?? '', draft.instructions?.hidden === true],
84
+ [draft.time?.text ?? '', draft.time?.mode ?? (draft.time?.hidden === true ? 'hide' : 'keep')],
85
+ draft.runtimeHidden === true,
86
+ [catalog.hidden === true, Object.entries(catalog.entries ?? {}).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))],
87
+ ])
88
+ }
89
+
90
+ /**
91
+ * 用一份基线把草稿整份填好,再把提示词模板的覆盖叠上去。
92
+ *
93
+ * 填的是 `rendered`(插值后的文本)而不是 `text`(原文):用户要改的是
94
+ * 模型真正会收到的那段字,`{{model}}` 之类的占位符在这里已经是实际值。
95
+ * 物化时同名覆盖是 `interpolate: false` 直接使用的,所以两边口径一致。
96
+ * @param {object} baseline - 该条件的预演结果。
97
+ * @param {object} [recipe] - 要叠加的提示词模板配方。
98
+ * @returns {object} 草稿状态。
99
+ */
100
+ function draftFromBaseline(baseline, recipe) {
101
+ const sections = {}
102
+ for (const section of baseline?.sections ?? []) {
103
+ sections[section.name] = baselineText(section)
104
+ }
105
+ // 覆盖只落在「新基线里也存在的段」上。新基线没有的段直接忽略——
106
+ // 凭空造一段不存在的东西,模型不会收到,用户也看不到。
107
+ for (const [name, text] of Object.entries(recipe?.prompt?.sectionOverrides ?? {})) {
108
+ if (typeof text === 'string' && sections[name] !== undefined) sections[name] = text
109
+ }
110
+
111
+ const contexts = baselineContexts(baseline)
112
+ for (const [name, text] of Object.entries(recipe?.contexts ?? {})) {
113
+ if (typeof text === 'string' && contexts[name] !== undefined) contexts[name] = text
114
+ }
115
+
116
+ const messages = recipe?.messages ?? {}
117
+ const instructionsSpec = messages['agent-instructions'] ?? {}
118
+ const timeSpec = messages['time-context'] ?? {}
119
+ const catalogSpec = messages['skill-catalog'] ?? {}
120
+ const catalogEntries = baselineCatalog(baseline)
121
+ const hiddenEntries = new Set(Array.isArray(catalogSpec.hiddenEntries) ? catalogSpec.hiddenEntries : [])
122
+ for (const [name, entry] of Object.entries(catalogEntries)) {
123
+ if (hiddenEntries.has(name)) entry.listed = false
124
+ }
125
+ for (const [name, description] of Object.entries(catalogSpec.descriptions ?? {})) {
126
+ if (catalogEntries[name] !== undefined && typeof description === 'string') {
127
+ catalogEntries[name].description = description
128
+ }
129
+ }
130
+
131
+ // 时间快照三态:hide = 不注入;keep = 不做修改(DSH 每轮重新注入);
132
+ // rewrite = 静态改写。没有覆盖时默认「不做修改」,即保持 DSH 的动态注入。
133
+ const timeMode = timeSpec.hidden === true || timeSpec.text === ''
134
+ ? 'hide'
135
+ : typeof timeSpec.text === 'string'
136
+ ? 'rewrite'
137
+ : 'keep'
138
+
139
+ return {
140
+ append: typeof recipe?.prompt?.appendText === 'string' ? recipe.prompt.appendText : '',
141
+ sections,
142
+ disabled: new Set(Array.isArray(recipe?.tools?.disabled) ? recipe.tools.disabled : []),
143
+ contexts,
144
+ instructions: {
145
+ text: typeof instructionsSpec.text === 'string'
146
+ ? instructionsSpec.text
147
+ : baselineMessageText(baseline, 'agent-instructions'),
148
+ hidden: instructionsSpec.hidden === true || instructionsSpec.text === '',
149
+ },
150
+ time: {
151
+ text: typeof timeSpec.text === 'string'
152
+ ? timeSpec.text
153
+ : baselineMessageText(baseline, 'time-context'),
154
+ mode: timeMode,
155
+ // 保留 hidden 供草稿指纹与旧断言使用;mode 才是界面的选择。
156
+ hidden: timeMode === 'hide',
157
+ },
158
+ runtimeHidden: messages['runtime-context']?.hidden === true,
159
+ catalog: {
160
+ hidden: catalogSpec.hidden === true,
161
+ entries: catalogEntries,
162
+ },
163
+ }
164
+ }
165
+
166
+ /**
167
+ * 从当前草稿算出要写进 recipe 的内容。
168
+ *
169
+ * 只保留**与基线不同**的项:草稿里是全文,recipe 里只放差异。
170
+ * 这样 recipe 保持在几百字节到几 KB 量级,也不会把 25 段原文整份复制进存储。
171
+ *
172
+ * 独占型提示词(`completeSection`)下没有「追加段落」这回事——独占段会把
173
+ * 其余段全部丢弃,所以追加内容只能并进那一段。这里在算 recipe 时就折进去,
174
+ * 存下来的是那一段的完整新文本。
175
+ * @param {object} draft - 草稿与基线。
176
+ * @returns {object} 提示词模板配方。
177
+ */
178
+ function recipeFromDraft(draft) {
179
+ const { editPreview } = draft
180
+ // 草稿统一使用 `draftFromBaseline` 的形状:append / sections / disabled。
181
+ const draftAppend = draft.append ?? ''
182
+ const draftSections = draft.sections ?? {}
183
+ const draftDisabled = draft.disabled ?? new Set()
184
+ const overrides = {}
185
+ const completeName = editPreview?.completeSection ?? null
186
+ for (const section of editPreview?.sections ?? []) {
187
+ const baseline = baselineText(section)
188
+ const current = draftSections?.[section.name]
189
+ if (typeof current === 'string' && current !== baseline) overrides[section.name] = current
190
+ }
191
+ // 独占段:把追加段落并进去
192
+ if (completeName !== null && (draftAppend ?? '').trim().length > 0) {
193
+ const current = overrides[completeName]
194
+ ?? (editPreview?.sections ?? []).find((section) => section.name === completeName)?.rendered
195
+ ?? ''
196
+ overrides[completeName] = current.length > 0 ? current + '\n\n' + draftAppend : draftAppend
197
+ }
198
+
199
+ // runtime-context:只写与基线不同的段。
200
+ const baselineContextsMap = baselineContexts(editPreview)
201
+ const contexts = {}
202
+ for (const [name, text] of Object.entries(draft.contexts ?? {})) {
203
+ if (typeof text !== 'string' || baselineContextsMap[name] === undefined) continue
204
+ if (text !== baselineContextsMap[name]) contexts[name] = text
205
+ }
206
+
207
+ // pre-step 消息:逐类只写差异。
208
+ const messages = {}
209
+ const baselineInstructions = baselineMessageText(editPreview, 'agent-instructions')
210
+ if (draft.instructions?.hidden === true) {
211
+ if (baselineInstructions.length > 0) messages['agent-instructions'] = { hidden: true }
212
+ } else if (typeof draft.instructions?.text === 'string' && draft.instructions.text !== baselineInstructions) {
213
+ messages['agent-instructions'] = { text: draft.instructions.text }
214
+ }
215
+
216
+ const baselineTime = baselineMessageText(editPreview, 'time-context')
217
+ const timeMode = draft.time?.mode ?? (draft.time?.hidden === true ? 'hide' : 'keep')
218
+ if (timeMode === 'hide') {
219
+ if (baselineTime.length > 0) messages['time-context'] = { hidden: true }
220
+ } else if (timeMode === 'rewrite') {
221
+ messages['time-context'] = {
222
+ text: typeof draft.time?.text === 'string' ? draft.time.text : baselineTime,
223
+ }
224
+ }
225
+ // keep:不写字段。配方缺省就是「不做修改」,DSH 每轮重新注入。
226
+
227
+ if (draft.runtimeHidden === true) messages['runtime-context'] = { hidden: true }
228
+
229
+ const baselineCatalogMap = baselineCatalog(editPreview)
230
+ const catalogSpec = draft.catalog ?? { hidden: false, entries: {} }
231
+ if (catalogSpec.hidden === true && Object.keys(baselineCatalogMap).length > 0) {
232
+ messages['skill-catalog'] = { hidden: true }
233
+ } else {
234
+ const hiddenEntries = []
235
+ const descriptions = {}
236
+ for (const [name, entry] of Object.entries(catalogSpec.entries ?? {})) {
237
+ const baseline = baselineCatalogMap[name]
238
+ if (baseline === undefined) continue
239
+ if (entry.listed === false && baseline.listed === true) hiddenEntries.push(name)
240
+ if (entry.description !== baseline.description) descriptions[name] = entry.description
241
+ }
242
+ if (hiddenEntries.length > 0 || Object.keys(descriptions).length > 0) {
243
+ messages['skill-catalog'] = {
244
+ ...(hiddenEntries.length > 0 ? { hiddenEntries } : {}),
245
+ ...(Object.keys(descriptions).length > 0 ? { descriptions } : {}),
246
+ }
247
+ }
248
+ }
249
+
250
+ return {
251
+ prompt: {
252
+ ...((draftAppend ?? '').trim().length > 0 && completeName === null ? { appendText: draftAppend } : {}),
253
+ ...(Object.keys(overrides).length > 0 ? { sectionOverrides: overrides } : {}),
254
+ },
255
+ ...(Object.keys(contexts).length > 0 ? { contexts } : {}),
256
+ ...(Object.keys(messages).length > 0 ? { messages } : {}),
257
+ tools: { disabled: [...(draftDisabled ?? [])] },
258
+ }
259
+ }
260
+
261
+ /**
262
+ * 一份 recipe 的可见规模。
263
+ *
264
+ * 保存/应用后把它写进通知,用户不必打开存储文件就能确认
265
+ * 「段落 / 追加 / 工具 / 上下文 / 消息」是否真的被记下来了。
266
+ * @param {object} recipe - 提示词模板配方。
267
+ * @returns {string} 一行摘要。
268
+ */
269
+ function recipeSummary(recipe) {
270
+ const sections = Object.keys(recipe?.prompt?.sectionOverrides ?? {}).length
271
+ const append = typeof recipe?.prompt?.appendText === 'string' && recipe.prompt.appendText.length > 0 ? 1 : 0
272
+ const tools = Array.isArray(recipe?.tools?.disabled) ? recipe.tools.disabled.length : 0
273
+ const contexts = Object.keys(recipe?.contexts ?? {}).length
274
+ const messages = Object.keys(recipe?.messages ?? {}).length
275
+ return `段落 ${sections} · 追加 ${append} · 工具 ${tools} · 上下文 ${contexts} · 消息 ${messages}`
276
+ }
277
+
278
+ return { signatureOf, draftFromBaseline, recipeFromDraft, recipeSummary, baselineText }
279
+ },
280
+ })