@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,281 @@
1
+ /**
2
+ * 预演条件:把「在哪个工作区、用哪套权限、什么模型、什么时区」解析成可展示的值。
3
+ *
4
+ * 为什么这些要单独成文件:首请求里有一半内容不是 `assemble()` 产出的,而是
5
+ * loop 与 pre-step 监听器按会话状态注入的(cwd、sandbox、approval、skill 目录、
6
+ * 时间快照)。那些东西在「只选一个模式」的预演里根本没有输入,页面只能显示
7
+ * 空——把一个条件缺失说成「模型没收到」,结论正好相反。所以条件必须先被显式解析,
8
+ * 解析不出来就标未知并写原因,不留空。
9
+ *
10
+ * 所有采集都降级:任何一段读不到只影响它自己,绝不抛错——除了 `assemble()` 本身。
11
+ * @module dsh-plugin-console/host/preview-conditions
12
+ */
13
+
14
+ import { isAbsolute, resolve } from 'node:path'
15
+ import { isDirectory } from './fs.js'
16
+
17
+ /** 路径比较在 Windows 上大小写不敏感;这是比较口径,不是路径改写。 */
18
+ const WINDOWS = process.platform === 'win32'
19
+
20
+ /** 模型信息查询的上限:适配器可能访问网络,预演不该被它拖住。 */
21
+ const MODEL_INFO_TIMEOUT_MS = 2000
22
+
23
+ /** 客户端时区的合理长度上限;超长说明不是 IANA 时区名。 */
24
+ const MAX_TIME_ZONE_LENGTH = 64
25
+
26
+ /** 列举可用的 permissionPresets 选项时要保留的字段。 */
27
+ function presetOption(option) {
28
+ return {
29
+ value: String(option?.value ?? ''),
30
+ name: typeof option?.name === 'string' ? option.name : String(option?.value ?? ''),
31
+ ...(typeof option?.description === 'string' ? { description: option.description } : {}),
32
+ }
33
+ }
34
+
35
+ /**
36
+ * 归一化路径用于**比较**:统一分隔符、去掉尾部分隔符,Windows 上折成小写。
37
+ * 不改写任何展示路径——注册表里的 `path` 才是权威写法。
38
+ * @param {unknown} value - 待比较的路径。
39
+ * @returns {string} 比较键。
40
+ */
41
+ function pathKey(value) {
42
+ const text = String(value ?? '').replace(/[\\/]+/g, '/').replace(/\/+$/, '')
43
+ return WINDOWS ? text.toLowerCase() : text
44
+ }
45
+
46
+ /**
47
+ * 解析工作区条件。
48
+ *
49
+ * 已注册的工作区优先用注册表记录(id / title 是权威值);未注册但真实存在的绝对路径
50
+ * 按「自定义目录」预演——预演需要看任意目录的 AGENTS.md 与 skill 目录,不能只限注册表。
51
+ * 自定义目录只用于推导:它没有工作区 id,不会被拿去建会话。
52
+ * @param {object} ctx - host 插件上下文。
53
+ * @param {string | undefined} requested - 客户端选择的工作区路径。
54
+ * @param {string[]} warnings - 收集警告。
55
+ * @returns {Promise<object | null>} `{ id, path, title, source }`;无法解析时为 null。
56
+ */
57
+ async function readWorkspace(ctx, requested, warnings) {
58
+ let list = []
59
+ try {
60
+ list = ctx.get('workspaceRegistry')?.list?.() ?? []
61
+ } catch (error) {
62
+ warnings.push(`工作区注册表不可用:${error instanceof Error ? error.message : String(error)}`)
63
+ }
64
+ if (typeof requested !== 'string' || requested.trim().length === 0) {
65
+ warnings.push('未选择工作区:skill 目录、workspace 指令与 cwd / sandbox / approval 文本都无法预测')
66
+ return null
67
+ }
68
+ const requestedText = requested.trim()
69
+ const found = list.find((workspace) => pathKey(workspace?.path) === pathKey(requestedText))
70
+ if (found !== undefined) {
71
+ return {
72
+ id: found.id ?? null,
73
+ path: found.path,
74
+ title: found.title ?? found.path,
75
+ source: 'registered',
76
+ }
77
+ }
78
+ // 注册表里没有:只有真实存在的绝对路径才能当目录读。
79
+ if (!isAbsolute(requestedText)) {
80
+ warnings.push(`工作区路径「${requestedText}」不是绝对路径:无法定位目录`)
81
+ return null
82
+ }
83
+ const resolved = resolve(requestedText)
84
+ if (!(await isDirectory(resolved))) {
85
+ warnings.push(`工作区路径「${resolved}」不存在或不是目录`)
86
+ return null
87
+ }
88
+ warnings.push(`工作区「${resolved}」未注册:按自定义目录预演,仅影响推导,不用于建会话`)
89
+ return { id: null, path: resolved, title: resolved, source: 'custom' }
90
+ }
91
+
92
+ /**
93
+ * 组合默认的 sandbox / approval。
94
+ *
95
+ * 新建会话在 `permissionPresets` 缺席时会直接读到这两个值,所以它们是「没有预设时
96
+ * 真实会生效的东西」,而不是猜测。
97
+ * @param {object} ctx - host 插件上下文。
98
+ * @returns {{ sandbox: string | null, approval: string }} 组合默认值。
99
+ */
100
+ function compositionPermission(ctx) {
101
+ let sandbox = null
102
+ let approval = 'ask'
103
+ try {
104
+ const mode = ctx.get('shell')?.sandboxMode
105
+ if (typeof mode === 'string') sandbox = mode
106
+ } catch {
107
+ // shell 不可用就留空,由调用方标未知
108
+ }
109
+ try {
110
+ const policy = ctx.get('approval')?.config?.policy
111
+ if (typeof policy === 'string') approval = policy
112
+ } catch {
113
+ // approval 不可用就用 DSH 自己的缺省
114
+ }
115
+ return { sandbox, approval }
116
+ }
117
+
118
+ /**
119
+ * 解析权限预设:预设名 → `{ sandbox, approval }` 的映射由 `permissionPresets.resolve()`
120
+ * 给出,不需要去偷读 Loader 行的私有配置。
121
+ * @param {object} ctx - host 插件上下文。
122
+ * @param {string | undefined} requested - 客户端选择的预设名。
123
+ * @param {string[]} warnings - 收集警告。
124
+ * @returns {object} `{ preset, sandbox, approval, source, options }`。
125
+ */
126
+ function readPermission(ctx, requested, warnings) {
127
+ const fallback = compositionPermission(ctx)
128
+ let service
129
+ let catalog = null
130
+ try {
131
+ service = ctx.get('permissionPresets')
132
+ catalog = service?.catalog?.() ?? null
133
+ } catch (error) {
134
+ warnings.push(`权限预设目录不可用:${error instanceof Error ? error.message : String(error)}`)
135
+ }
136
+ if (catalog === null || catalog === undefined) {
137
+ warnings.push('权限预设服务不可用:sandbox 与 approval 退回组合默认值')
138
+ return { preset: null, ...fallback, source: 'composition', options: [] }
139
+ }
140
+
141
+ const options = (catalog.options ?? []).map(presetOption)
142
+ const names = new Set(options.map((option) => option.value))
143
+ const fallbackName = typeof catalog.defaultPreset === 'string' ? catalog.defaultPreset : null
144
+ let preset = fallbackName
145
+ let source = 'default'
146
+ if (typeof requested === 'string' && requested.length > 0) {
147
+ if (names.has(requested)) {
148
+ preset = requested
149
+ source = 'selected'
150
+ } else {
151
+ warnings.push(`未知的权限预设「${requested}」:改用部署默认值「${fallbackName ?? '无'}」`)
152
+ }
153
+ }
154
+
155
+ let spec = null
156
+ try {
157
+ spec = service.resolve(preset)
158
+ } catch {
159
+ // `custom` 不是可切换目标,`resolve()` 对它必然抛错:它本身就等于「不匹配任何预设」,
160
+ // 所以直接退回组合默认值,那正是当前会话真实生效的 sandbox / approval。
161
+ spec = null
162
+ }
163
+ if (spec === null) {
164
+ return { preset, ...fallback, source: 'composition', options }
165
+ }
166
+ return {
167
+ preset,
168
+ sandbox: typeof spec.sandbox === 'string' ? spec.sandbox : fallback.sandbox,
169
+ approval: typeof spec.approval === 'string' ? spec.approval : fallback.approval,
170
+ source,
171
+ options,
172
+ }
173
+ }
174
+
175
+ /**
176
+ * 解析默认模型。没有它,`{{model}}` / `{{provider}}` 只能保留字面量。
177
+ * @param {object} ctx - host 插件上下文。
178
+ * @param {string[]} warnings - 收集警告。
179
+ * @returns {object | null} `{ provider, model, reasoningEffort?, source }`。
180
+ */
181
+ function readModel(ctx, warnings) {
182
+ try {
183
+ const selection = ctx.get('agentDefaultModel')?.currentSelection?.()
184
+ if (typeof selection?.provider === 'string' && typeof selection?.model === 'string') {
185
+ return {
186
+ provider: selection.provider,
187
+ model: selection.model,
188
+ ...(typeof selection.reasoningEffort === 'string' ? { reasoningEffort: selection.reasoningEffort } : {}),
189
+ source: 'default',
190
+ }
191
+ }
192
+ } catch (error) {
193
+ warnings.push(`默认模型不可用:${error instanceof Error ? error.message : String(error)}`)
194
+ return null
195
+ }
196
+ warnings.push('默认模型不可用:provider、model 与上下文窗口都标为未知')
197
+ return null
198
+ }
199
+
200
+ /**
201
+ * 解析上下文窗口。
202
+ *
203
+ * 适配器可能真的去问远端,所以既传 AbortSignal 又自己设一道超时——只依赖 signal 的话,
204
+ * 不理会信号的适配器会让整次预演挂住。
205
+ * @param {object} ctx - host 插件上下文。
206
+ * @param {object | null} model - 已解析的模型。
207
+ * @param {string[]} warnings - 收集警告。
208
+ * @returns {Promise<number | null>} 窗口大小(token)。
209
+ */
210
+ async function readContextWindow(ctx, model, warnings) {
211
+ if (model === null) return null
212
+ const llm = ctx.get('llm')
213
+ if (typeof llm?.resolveModelInfo !== 'function') {
214
+ warnings.push('llm 服务不可用:上下文窗口未知')
215
+ return null
216
+ }
217
+ let timer
218
+ try {
219
+ const expired = new Promise((resolve) => {
220
+ timer = setTimeout(() => resolve(null), MODEL_INFO_TIMEOUT_MS)
221
+ })
222
+ const info = await Promise.race([
223
+ llm.resolveModelInfo(model.provider, model.model, AbortSignal.timeout(MODEL_INFO_TIMEOUT_MS)),
224
+ expired,
225
+ ])
226
+ const window = info?.context?.contextWindow
227
+ return typeof window === 'number' && window > 0 ? window : null
228
+ } catch (error) {
229
+ warnings.push(`模型信息查询失败:上下文窗口未知(${error instanceof Error ? error.message : String(error)})`)
230
+ return null
231
+ } finally {
232
+ clearTimeout(timer)
233
+ }
234
+ }
235
+
236
+ /**
237
+ * 解析客户端时区:模型看到的 time-context 用的就是这个时区。
238
+ * @param {unknown} requested - 客户端上报的 IANA 时区名。
239
+ * @param {string[]} warnings - 收集警告。
240
+ * @returns {{ clientTimeZone: string, clientTimeZoneSource: 'client' | 'server' }} 时区与来源。
241
+ */
242
+ function readTimeZone(requested, warnings) {
243
+ if (typeof requested === 'string' && requested.length > 0 && requested.length <= MAX_TIME_ZONE_LENGTH) {
244
+ return { clientTimeZone: requested, clientTimeZoneSource: 'client' }
245
+ }
246
+ let fallback = 'UTC'
247
+ try {
248
+ fallback = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'
249
+ } catch {
250
+ // 拿不到就用 UTC,不编一个时区出来
251
+ }
252
+ warnings.push('客户端时区缺失:退回服务端时区')
253
+ return { clientTimeZone: fallback, clientTimeZoneSource: 'server' }
254
+ }
255
+
256
+ /**
257
+ * 解析一次首请求预演的全部条件。
258
+ * @param {object} ctx - host 插件上下文。
259
+ * @param {object} options - 客户端上报的条件。
260
+ * @param {string} [options.workspacePath] - 工作区路径:已注册路径,或任意绝对目录。
261
+ * @param {string} [options.permissionPreset] - 权限预设名。
262
+ * @param {string} [options.clientTimeZone] - 客户端 IANA 时区。
263
+ * @returns {Promise<object>} 条件 + 警告。
264
+ */
265
+ export async function resolveConditions(ctx, options = {}) {
266
+ const warnings = []
267
+ const workspace = await readWorkspace(ctx, options.workspacePath, warnings)
268
+ const permission = readPermission(ctx, options.permissionPreset, warnings)
269
+ const model = readModel(ctx, warnings)
270
+ const contextWindow = await readContextWindow(ctx, model, warnings)
271
+ const zone = readTimeZone(options.clientTimeZone, warnings)
272
+ return {
273
+ workspace,
274
+ permission,
275
+ model,
276
+ contextWindow,
277
+ clientTimeZone: zone.clientTimeZone,
278
+ clientTimeZoneSource: zone.clientTimeZoneSource,
279
+ warnings,
280
+ }
281
+ }
@@ -0,0 +1,174 @@
1
+ /**
2
+ * 预测首请求里的 `runtime-context` 快照。
3
+ *
4
+ * 这段快照由 loop 在请求前拼好,来源有两类:
5
+ * - **实测**:`assemble()` 直接给出的 contexts(harness:source、app:web-surface 等);
6
+ * - **推导**:cwd / sandbox / approval 三段依赖会话状态,没有 Agent 时装配里是空的,
7
+ * 但它们恰恰把「权限预设」这个条件变成了模型能看到的文字。
8
+ *
9
+ * 文案抄自已安装版本 `0.2.2-rc.1`(`dsh-working-directory`、`dsh-sandbox-policy`、
10
+ * `dsh-user-approval`)。本地源码 checkout 的文案与已安装版不同,所以以日志为准。
11
+ * @module dsh-plugin-console/host/preview-contexts
12
+ */
13
+
14
+ /** DSH 在快照正文前加的那句前缀。 */
15
+ export const RUNTIME_CONTEXT_PREFIX = 'Current runtime context. This snapshot supersedes earlier runtime-context snapshots.'
16
+
17
+ /** 三段会话依赖上下文的 order,与 `dsh-system-prompt` 的常量表一致。 */
18
+ const ORDER = {
19
+ WORKING_DIRECTORY: 100,
20
+ SANDBOX_POLICY: 110,
21
+ APPROVAL_POLICY: 115,
22
+ }
23
+
24
+ /** 三种 sandbox 模式各自在模型面前的文案。 */
25
+ const SANDBOX_TEXT = {
26
+ 'read-only': 'Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.',
27
+ 'danger-full-access': 'Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.',
28
+ }
29
+
30
+ const NEVER_SENTENCE = 'Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).'
31
+ const ASK_SENTENCE = 'Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.'
32
+
33
+ /**
34
+ * workspace-write 的文案要带上沙箱根目录;没有额外可写目录时不加那一句。
35
+ * @param {string} workspaceRoot - 会话工作区路径。
36
+ * @returns {string} 模型可见文本。
37
+ */
38
+ function workspaceWriteText(workspaceRoot) {
39
+ return `Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: ${JSON.stringify(workspaceRoot)}. Some platform temporary areas may also be writable.`
40
+ }
41
+
42
+ /**
43
+ * 与 system 段同一套插值规则:只替换能解析的变量,解析不了的保留字面量。
44
+ * @param {string} text - 原文。
45
+ * @param {object} variables - 变量表。
46
+ * @returns {string} 渲染结果。
47
+ */
48
+ function interpolateText(text, variables) {
49
+ return text.replace(/\{\{(\w+)\}\}/g, (whole, key) => {
50
+ const value = variables?.[key]
51
+ return typeof value === 'string' ? value : whole
52
+ })
53
+ }
54
+
55
+ /**
56
+ * 一条 runtime-context 分段。
57
+ * @param {object} init - 分段字段。
58
+ * @returns {object} 分段。
59
+ */
60
+ function segment(init) {
61
+ return {
62
+ name: init.name,
63
+ order: init.order,
64
+ text: init.text ?? '',
65
+ confidence: init.confidence,
66
+ ...(init.basis === undefined ? {} : { basis: init.basis }),
67
+ ...(init.reason === undefined ? {} : { reason: init.reason }),
68
+ }
69
+ }
70
+
71
+ /**
72
+ * 预测整个 runtime-context 快照。
73
+ * @param {object} assembly - `previewAssembly()` 的结果。
74
+ * @param {object} conditions - `resolveConditions()` 的结果。
75
+ * @param {object} [overrides] - 模板对 context 的逐段覆盖(name → 最终文本)。
76
+ * @returns {object} `{ text, segments }`。
77
+ */
78
+ export function previewRuntimeContext(assembly, conditions, overrides) {
79
+ const workspacePath = conditions?.workspace?.path
80
+ const measured = new Map((assembly?.contexts ?? []).map((context) => [context.name, context]))
81
+ const segments = []
82
+
83
+ // —— 三段由会话状态决定的部分 ——
84
+ if (typeof workspacePath === 'string' && workspacePath.length > 0) {
85
+ segments.push(segment({
86
+ name: 'working-directory:current',
87
+ order: ORDER.WORKING_DIRECTORY,
88
+ text: `Current working directory: ${JSON.stringify(workspacePath)}.`,
89
+ confidence: 'derived',
90
+ basis: ['workspace'],
91
+ }))
92
+ } else {
93
+ // 没有工作区时不编一个路径,也不把这一项当成空段:模型是收不到的。
94
+ segments.push(segment({
95
+ name: 'working-directory:current',
96
+ order: ORDER.WORKING_DIRECTORY,
97
+ confidence: 'unknown',
98
+ basis: ['workspace'],
99
+ reason: 'workspace is not selected',
100
+ }))
101
+ }
102
+
103
+ const sandbox = conditions?.permission?.sandbox
104
+ if (typeof sandbox === 'string' && typeof workspacePath === 'string') {
105
+ segments.push(segment({
106
+ name: 'sandbox:policy',
107
+ order: ORDER.SANDBOX_POLICY,
108
+ text: sandbox === 'workspace-write' ? workspaceWriteText(workspacePath) : (SANDBOX_TEXT[sandbox] ?? ''),
109
+ confidence: 'derived',
110
+ basis: ['workspace', 'permission'],
111
+ }))
112
+ } else {
113
+ segments.push(segment({
114
+ name: 'sandbox:policy',
115
+ order: ORDER.SANDBOX_POLICY,
116
+ confidence: 'unknown',
117
+ basis: ['permission'],
118
+ reason: 'sandbox mode is unknown',
119
+ }))
120
+ }
121
+
122
+ const approval = conditions?.permission?.approval
123
+ if (approval === 'ask' || approval === 'never') {
124
+ segments.push(segment({
125
+ name: 'approval:policy',
126
+ order: ORDER.APPROVAL_POLICY,
127
+ text: approval === 'never' ? NEVER_SENTENCE : ASK_SENTENCE,
128
+ confidence: 'derived',
129
+ basis: ['permission'],
130
+ }))
131
+ } else {
132
+ segments.push(segment({
133
+ name: 'approval:policy',
134
+ order: ORDER.APPROVAL_POLICY,
135
+ confidence: 'unknown',
136
+ basis: ['permission'],
137
+ reason: 'approval policy is unknown',
138
+ }))
139
+ }
140
+
141
+ // —— 装配直接给出的部分 ——
142
+ const derivedNames = new Set(['working-directory:current', 'sandbox:policy', 'approval:policy'])
143
+ for (const [name, context] of measured) {
144
+ if (derivedNames.has(name)) continue
145
+ const text = context.interpolate === false ? context.text : interpolateText(context.text, assembly?.variables)
146
+ segments.push(segment({
147
+ name,
148
+ order: typeof context.order === 'number' ? context.order : undefined,
149
+ text,
150
+ confidence: 'measured',
151
+ }))
152
+ }
153
+
154
+ // 模板覆盖只落在已经存在的段上:名字对不上就保持原样,不凭空造一个 context。
155
+ if (overrides !== null && typeof overrides === 'object') {
156
+ for (const item of segments) {
157
+ const text = overrides[item.name]
158
+ if (typeof text !== 'string') continue
159
+ item.text = text
160
+ item.overridden = true
161
+ item.confidence = 'derived'
162
+ delete item.reason
163
+ item.basis = [...(item.basis ?? []), 'template']
164
+ }
165
+ }
166
+
167
+ // DSH 按 order 排;读不到 order 的放在最后,保持相对顺序(sort 在 V8 上稳定)。
168
+ segments.sort((left, right) => (left.order ?? Number.MAX_SAFE_INTEGER) - (right.order ?? Number.MAX_SAFE_INTEGER))
169
+ const body = segments.map((item) => item.text).filter((text) => text.length > 0).join('\n\n')
170
+ return {
171
+ text: body.length === 0 ? '' : `${RUNTIME_CONTEXT_PREFIX}\n\n${body}`,
172
+ segments,
173
+ }
174
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * 请求信封:一条请求自身的元信息——发给哪个 provider / model、窗口多大、带多少工具。
3
+ *
4
+ * 与 sections / tools 分开的理由:它们回答「内容是什么」,信封回答「发给谁、装得下吗」。
5
+ * 页面顶部那行元信息就是它。
6
+ * @module dsh-plugin-console/host/preview-envelope
7
+ */
8
+
9
+ /**
10
+ * @param {object} assembly - `previewAssembly()` 的结果。
11
+ * @param {object} conditions - `resolveConditions()` 的结果。
12
+ * @returns {object} `{ provider, model, contextWindow, toolCount, toolSchemaChars, confidence, unknown }`。
13
+ */
14
+ export function previewEnvelope(assembly, conditions) {
15
+ const provider = conditions?.model?.provider ?? null
16
+ const model = conditions?.model?.model ?? null
17
+ const contextWindow = typeof conditions?.contextWindow === 'number' ? conditions.contextWindow : null
18
+ const unknown = []
19
+ if (provider === null || model === null) unknown.push('model')
20
+ if (contextWindow === null) unknown.push('contextWindow')
21
+ return {
22
+ provider,
23
+ model,
24
+ contextWindow,
25
+ toolCount: assembly?.stats?.tools ?? 0,
26
+ toolSchemaChars: assembly?.stats?.toolSchemaChars ?? 0,
27
+ // 工具与段来自实测的装配结果,模型与窗口来自服务推导;只要有一项未知就整体标未知。
28
+ confidence: unknown.includes('model') ? 'unknown' : 'derived',
29
+ unknown,
30
+ }
31
+ }