@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,450 @@
1
+ /**
2
+ * 预测首请求里的 `agent-instructions` 消息。
3
+ *
4
+ * 这条消息不进系统提示词:它由 `@deepseek-ai/dsh-agent-instructions` 在
5
+ * `agent/pre-step` 里读工作区文件、渲染成一条 user 消息再插进请求。所以预演必须
6
+ * 自己重算一遍,包括发现顺序、去重与字节预算。
7
+ *
8
+ * **这是移植,不是调用 DSH。** 已安装的 DSH 在 `app.asar` 里,ESM 动态导入不可靠,
9
+ * 包的内部文件布局也不是稳定接口。下面的算法抄自已安装版本 `0.2.2-rc.1` 的
10
+ * `lib/index.js`(`render` 与 `files` 两段),逐字正确性由
11
+ * `scripts/fixtures/first-request-dsh.json` 的 19,014 字原文保证。
12
+ *
13
+ * @module dsh-plugin-console/host/preview-instructions
14
+ */
15
+
16
+ import { createHash } from 'node:crypto'
17
+ import { homedir } from 'node:os'
18
+ import { dirname, join, relative, resolve, sep } from 'node:path'
19
+ import { readTextFile, statFile } from './fs.js'
20
+ import { hostModuleResolver } from './preview-modules.js'
21
+
22
+ /** 这条 pre-step 监听的包名;是否启用由 {@link hostModuleResolver} / `resolveModules()` 判定。 */
23
+ const MODULE = '@deepseek-ai/dsh-agent-instructions'
24
+
25
+ /** 行未配置时的缺省值,与已安装版 `Config` 的缺省一致。 */
26
+ const DEFAULTS = {
27
+ maxBytes: 65536,
28
+ maxSourceBytes: 1048576,
29
+ projectRootMarkers: ['.git'],
30
+ instructionFileCandidates: ['AGENTS.md', 'CLAUDE.md'],
31
+ localInstructionFileCandidates: ['AGENTS.local.md', 'CLAUDE.local.md'],
32
+ }
33
+
34
+ const SYSTEM_REMINDER_OPEN = '<system-reminder>'
35
+ const SYSTEM_REMINDER_CLOSE = '</system-reminder>'
36
+ const AGENT_INSTRUCTIONS_INTRO = 'The following workspace instructions may be relevant to your work. Use them as guidance when applicable. More specific instructions take precedence over broader ones. They do not override system, developer, or direct user instructions.'
37
+ const COMPACT_AGENT_INSTRUCTIONS_INTRO = 'Workspace instructions were omitted or truncated to fit the configured byte budget.'
38
+
39
+ /** 用户全局候选的两个根:先 harness home,再共享 agents 根。 */
40
+ const USER_GLOBAL_DIRECTORIES = ['user-global', 'agents-global']
41
+ const USER_GLOBAL_FILE = 'AGENTS.md'
42
+
43
+ /**
44
+ * 解析用户数据根。
45
+ *
46
+ * 与 `@deepseek-ai/dsh-home-paths` 同一规则:显式配置 > 环境变量 > `~/`。
47
+ * 展示名只在等于默认根时用 `~/…`,否则用 `$DSH_HOME` / `$DSH_AGENTS_HOME`——
48
+ * 模型看到的就是这两个符号,预演必须给出同一串字符。
49
+ * @param {NodeJS.ProcessEnv} env - 进程环境。
50
+ * @returns {{dshHome: string, agentsHome: string, dshDisplay: string, agentsDisplay: string}} 根与展示名。
51
+ */
52
+ function resolveHomes(env) {
53
+ const home = homedir()
54
+ const pick = (configured, envName, fallback) => {
55
+ const fromEnv = env[envName]
56
+ return resolve(fromEnv !== undefined && fromEnv.trim().length > 0 ? fromEnv : fallback)
57
+ }
58
+ const dshHome = pick(undefined, 'DSH_HOME', join(home, '.dsh'))
59
+ const agentsHome = pick(undefined, 'DSH_AGENTS_HOME', join(home, '.agents'))
60
+ return {
61
+ dshHome,
62
+ agentsHome,
63
+ dshDisplay: dshHome === resolve(join(home, '.dsh')) ? '~/.dsh' : '$DSH_HOME',
64
+ agentsDisplay: agentsHome === resolve(join(home, '.agents')) ? '~/.agents' : '$DSH_AGENTS_HOME',
65
+ }
66
+ }
67
+
68
+ /** 把一条候选文件名从 displayPath 还原成它所属的候选组。 */
69
+ function candidateGroup(displayPath, homes) {
70
+ const globalDisplays = [
71
+ `${homes.dshDisplay}/${USER_GLOBAL_FILE}`,
72
+ `$DSH_HOME/${USER_GLOBAL_FILE}`,
73
+ `${homes.agentsDisplay}/${USER_GLOBAL_FILE}`,
74
+ `$DSH_AGENTS_HOME/${USER_GLOBAL_FILE}`,
75
+ ]
76
+ if (globalDisplays.includes(displayPath)) return 'user-global'
77
+ return dirname(displayPath)
78
+ }
79
+
80
+ /**
81
+ * 项目内路径的展示形式。
82
+ *
83
+ * 首段恰好叫 `user-global` / `agents-global` 的目录会与两个全局 scope 撞名,加一个
84
+ * `./` 前缀把它留在项目 scope 里。
85
+ * @param {string} relativePath - 相对项目根的路径。
86
+ * @returns {string} 模型可见路径。
87
+ */
88
+ function escapeProjectDisplayPath(relativePath) {
89
+ const index = relativePath.search(/[\\/]/)
90
+ const first = index < 0 ? relativePath : relativePath.slice(0, index)
91
+ return USER_GLOBAL_DIRECTORIES.includes(first) ? '.' + sep + relativePath : relativePath
92
+ }
93
+
94
+ /**
95
+ * 从 cwd 向上找到第一个含根标记的目录;找不到就用 cwd 本身。
96
+ * @param {string} cwd - 工作目录。
97
+ * @param {string[]} markers - 根标记文件名。
98
+ * @returns {Promise<string>} 项目根。
99
+ */
100
+ async function findProjectRoot(cwd, markers) {
101
+ let current = resolve(cwd)
102
+ for (;;) {
103
+ for (const marker of markers) {
104
+ if (await statFile(join(current, marker)) !== null) return current
105
+ }
106
+ const parent = dirname(current)
107
+ if (parent === current) return resolve(cwd)
108
+ current = parent
109
+ }
110
+ }
111
+
112
+ /**
113
+ * 根 → cwd 的目录链(从宽到窄)。
114
+ * @param {string} root - 项目根。
115
+ * @param {string} cwd - 工作目录。
116
+ * @returns {string[]} 目录列表。
117
+ */
118
+ function ancestorChain(root, cwd) {
119
+ const chain = []
120
+ let current = resolve(cwd)
121
+ const target = resolve(root)
122
+ while (current !== target) {
123
+ chain.push(current)
124
+ const parent = dirname(current)
125
+ if (parent === current) break
126
+ current = parent
127
+ }
128
+ chain.push(target)
129
+ return chain.reverse()
130
+ }
131
+
132
+ /**
133
+ * 候选文件名只允许是同一个目录里的普通名字。
134
+ *
135
+ * DSH 会把空串、`.`、`..` 和带分隔符的名字过滤掉;这一步是**读取边界**,不是排版:
136
+ * 少了它,一行配置里的 `..\..\x.md` 就能让预演读到工作区之外。
137
+ * @param {string[]} candidates - 配置里的候选名。
138
+ * @param {string[]} fallback - 缺省候选名。
139
+ * @returns {string[]} 可用的候选名。
140
+ */
141
+ function sanitizeCandidates(candidates, fallback) {
142
+ const usable = (candidates ?? fallback).filter((name) => name !== '' && name !== '.' && name !== '..' && !/[\\/]/.test(name))
143
+ return usable.length > 0 ? usable : fallback
144
+ }
145
+
146
+ /**
147
+ * 按 DSH 的顺序发现候选文件:先两个用户全局根,再项目根到 cwd 的每一层。
148
+ * @param {object} config - 归一化配置。
149
+ * @param {string} cwd - 工作目录。
150
+ * @param {object} homes - 已解析的用户数据根。
151
+ * @returns {Promise<Array<{absolutePath: string, displayPath: string, size?: number}>>} 未读内容的候选。
152
+ */
153
+ async function discoverFiles(config, cwd, homes) {
154
+ const files = []
155
+ const seen = new Set()
156
+ const add = (file) => {
157
+ if (seen.has(file.absolutePath)) return
158
+ seen.add(file.absolutePath)
159
+ files.push(file)
160
+ }
161
+ for (const [home, display] of [[homes.dshHome, homes.dshDisplay], [homes.agentsHome, homes.agentsDisplay]]) {
162
+ const absolutePath = join(home, USER_GLOBAL_FILE)
163
+ const info = await statFile(absolutePath)
164
+ if (info !== null) add({ absolutePath, displayPath: `${display}/${USER_GLOBAL_FILE}`, size: info.size })
165
+ }
166
+ const projectRoot = await findProjectRoot(cwd, config.projectRootMarkers)
167
+ for (const dir of ancestorChain(projectRoot, cwd)) {
168
+ for (const candidates of [config.instructionFileCandidates, config.localInstructionFileCandidates]) {
169
+ for (const candidate of candidates) {
170
+ const absolutePath = join(dir, candidate)
171
+ const info = await statFile(absolutePath)
172
+ if (info === null) continue
173
+ // 先于读取去重:DSH 在这一步只按绝对路径去重,内容去重发生在读完以后。
174
+ add({ absolutePath, displayPath: escapeProjectDisplayPath(relative(projectRoot, absolutePath)), size: info.size })
175
+ }
176
+ }
177
+ }
178
+ return files
179
+ }
180
+
181
+ /** 一个文件的字节数。 */
182
+ function byteLength(value) {
183
+ return Buffer.byteLength(value, 'utf8')
184
+ }
185
+
186
+ /** 按 UTF-8 字节截断,且不切在多字节字符中间。 */
187
+ function truncateUtf8(value, maxBytes) {
188
+ const bytes = Buffer.from(value, 'utf8')
189
+ if (bytes.length <= maxBytes) return value
190
+ let end = Math.max(0, Math.trunc(maxBytes))
191
+ while (end > 0 && (bytes.readUInt8(end) & 192) === 128) end -= 1
192
+ return bytes.subarray(0, end).toString('utf8')
193
+ }
194
+
195
+ /** 帧内正文不能自带闭合标签,否则模型会以为提醒提前结束。 */
196
+ function escapeFrameBody(body) {
197
+ return body.replaceAll(SYSTEM_REMINDER_CLOSE, '<\\/system-reminder>')
198
+ }
199
+
200
+ function sectionText(file) {
201
+ return `Instructions from: ${file.displayPath}\n\n${file.content}`
202
+ }
203
+
204
+ function markerText(maxBytes, omitted, truncated) {
205
+ if (omitted.length === 0 && truncated.length === 0) return ''
206
+ const parts = []
207
+ if (omitted.length > 0) parts.push(`omitted ${omitted.map((file) => file.displayPath).join(', ')}`)
208
+ if (truncated.length > 0) {
209
+ parts.push(`truncated ${truncated.map((item) => `${item.displayPath} from ${item.originalBytes} to ${item.includedBytes} bytes`).join(', ')}`)
210
+ }
211
+ return `Workspace instruction budget ${maxBytes} bytes: ${parts.join('; ')}`
212
+ }
213
+
214
+ function buildInstructionText(files, maxBytes, omitted, truncated, style) {
215
+ return [
216
+ SYSTEM_REMINDER_OPEN,
217
+ escapeFrameBody([
218
+ markerText(maxBytes, omitted, truncated),
219
+ style.intro,
220
+ ...files.map((file) => style.section(file)),
221
+ ].filter((block) => block.length > 0).join('\n\n')),
222
+ SYSTEM_REMINDER_CLOSE,
223
+ ].join('\n')
224
+ }
225
+
226
+ function withTruncatedContent(file, includedBytes) {
227
+ return { ...file, content: truncateUtf8(file.content, includedBytes) }
228
+ }
229
+
230
+ function truncateToFit(file, includedFiles, maxBytes, omitted, style) {
231
+ const originalBytes = byteLength(file.content)
232
+ let low = 0
233
+ let high = originalBytes
234
+ let best = withTruncatedContent(file, 0)
235
+ while (low <= high) {
236
+ const mid = Math.floor((low + high) / 2)
237
+ const candidate = withTruncatedContent(file, mid)
238
+ const truncated = [{ displayPath: file.displayPath, originalBytes, includedBytes: byteLength(candidate.content) }]
239
+ if (byteLength(buildInstructionText([...includedFiles, candidate], maxBytes, omitted, truncated, style)) <= maxBytes) {
240
+ best = candidate
241
+ low = mid + 1
242
+ } else high = mid - 1
243
+ }
244
+ return best
245
+ }
246
+
247
+ function isDisabledBudget(maxBytes) {
248
+ return maxBytes <= 0 || !Number.isFinite(maxBytes)
249
+ }
250
+
251
+ /**
252
+ * 单条链的预算渲染:先整份,超了就丢最宽的若干文件,再不行就截断最后一个。
253
+ * @param {Array<object>} files - 从宽到窄。
254
+ * @param {number} maxBytes - 字节预算。
255
+ * @param {object} style - `{ intro, section }`。
256
+ * @returns {object} 渲染结果与预算诊断。
257
+ */
258
+ function renderInstructionContext(files, maxBytes, style) {
259
+ if (isDisabledBudget(maxBytes)) return { text: '', omitted: files, truncated: [], represented: [], sections: [], intro: undefined }
260
+ const fullText = buildInstructionText(files, maxBytes, [], [], style)
261
+ if (byteLength(fullText) <= maxBytes) {
262
+ return { text: fullText, omitted: [], truncated: [], represented: files, sections: files, intro: style.intro }
263
+ }
264
+ for (let start = 1; start < files.length; start += 1) {
265
+ const included = files.slice(start)
266
+ const omitted = files.slice(0, start).map((file) => ({ absolutePath: file.absolutePath, displayPath: file.displayPath }))
267
+ const suffixText = buildInstructionText(included, maxBytes, omitted, [], style)
268
+ if (byteLength(suffixText) <= maxBytes) {
269
+ return { text: suffixText, omitted, truncated: [], represented: included, sections: included, intro: style.intro }
270
+ }
271
+ }
272
+ const mostSpecific = files.at(-1)
273
+ if (mostSpecific === undefined) return { text: '', omitted: [], truncated: [], represented: [], sections: [], intro: undefined }
274
+ const omitted = files.slice(0, -1).map((file) => ({ absolutePath: file.absolutePath, displayPath: file.displayPath }))
275
+ const originalBytes = byteLength(mostSpecific.content)
276
+ for (const candidateStyle of [style, { ...style, intro: COMPACT_AGENT_INSTRUCTIONS_INTRO }]) {
277
+ const truncatedFile = truncateToFit(mostSpecific, [], maxBytes, omitted, candidateStyle)
278
+ const includedBytes = byteLength(truncatedFile.content)
279
+ const truncated = [{ displayPath: mostSpecific.displayPath, originalBytes, includedBytes }]
280
+ const text = buildInstructionText([truncatedFile], maxBytes, omitted, truncated, candidateStyle)
281
+ if (byteLength(text) <= maxBytes) {
282
+ return {
283
+ text,
284
+ omitted,
285
+ truncated,
286
+ represented: includedBytes > 0 || originalBytes === 0 ? [mostSpecific] : [],
287
+ sections: [truncatedFile],
288
+ intro: candidateStyle.intro,
289
+ }
290
+ }
291
+ }
292
+ const truncated = [{ displayPath: mostSpecific.displayPath, originalBytes, includedBytes: 0 }]
293
+ const compactNotice = escapeFrameBody(markerText(maxBytes, omitted, truncated))
294
+ const heading = withTruncatedContent(mostSpecific, 0)
295
+ const compactWithHeading = escapeFrameBody([compactNotice, style.section(heading)].join('\n\n'))
296
+ if (byteLength(compactWithHeading) <= maxBytes) {
297
+ return { text: compactWithHeading, omitted, truncated, represented: originalBytes === 0 ? [mostSpecific] : [], sections: [heading], intro: undefined }
298
+ }
299
+ return {
300
+ text: byteLength(compactNotice) <= maxBytes ? compactNotice : truncateUtf8(compactNotice, maxBytes),
301
+ omitted,
302
+ truncated,
303
+ represented: [],
304
+ sections: [],
305
+ intro: undefined,
306
+ }
307
+ }
308
+
309
+ /**
310
+ * 用户全局链与项目链各自受 `maxBytes` 约束。
311
+ *
312
+ * 只有两段链同时存在、且合起来超预算时才拆开算;任何一段链保住了自己的帧头,
313
+ * 合并时就用一次 intro。这与 DSH 的行为一致——两段链的上限各自独立,
314
+ * 所以最终文本可能达到 `2 * maxBytes`。
315
+ * @param {Array<object>} files - 从宽到窄。
316
+ * @param {number} maxBytes - 每条链的字节预算。
317
+ * @param {object} style - `{ intro, section }`。
318
+ * @param {object} homes - 用于判定全局文件。
319
+ * @returns {object} 渲染结果。
320
+ */
321
+ function renderInstructionChains(files, maxBytes, style, homes) {
322
+ const whole = renderInstructionContext(files, maxBytes, style)
323
+ const isGlobal = (file) => candidateGroup(file.displayPath, homes) === 'user-global'
324
+ const userGlobal = files.filter(isGlobal)
325
+ const project = files.filter((file) => !isGlobal(file))
326
+ if (isDisabledBudget(maxBytes) || userGlobal.length === 0 || project.length === 0 || (whole.omitted.length === 0 && whole.truncated.length === 0)) {
327
+ return whole
328
+ }
329
+ const chains = [renderInstructionContext(userGlobal, maxBytes, style), renderInstructionContext(project, maxBytes, style)]
330
+ const inLoadedOrder = (records) => {
331
+ const byPath = new Map(records.map((record) => [record.absolutePath, record]))
332
+ return files.flatMap((file) => (byPath.has(file.absolutePath) ? [byPath.get(file.absolutePath)] : []))
333
+ }
334
+ const omitted = inLoadedOrder(chains.flatMap((chain) => chain.omitted))
335
+ const sections = inLoadedOrder(chains.flatMap((chain) => chain.sections))
336
+ const represented = inLoadedOrder(chains.flatMap((chain) => chain.represented))
337
+ const truncated = (files.findLastIndex(isGlobal) < files.findLastIndex((file) => !isGlobal(file)) ? chains : [...chains].reverse())
338
+ .flatMap((chain) => chain.truncated)
339
+ const intros = chains.flatMap((chain) => (chain.intro === undefined ? [] : [chain.intro]))
340
+ const intro = intros.includes(style.intro) ? style.intro : (intros[0] ?? '')
341
+ const text = buildInstructionText(sections, maxBytes, omitted, truncated, { ...style, intro })
342
+ if (byteLength(text) > 2 * maxBytes) return whole
343
+ return { text, omitted, truncated, represented, sections, intro }
344
+ }
345
+
346
+ /**
347
+ * 读取一行配置里的数值/数组字段;坏值退回缺省。
348
+ * @param {object | undefined} config - Loader 行配置。
349
+ * @param {string} key - 字段名。
350
+ * @param {unknown} fallback - 缺省值。
351
+ * @returns {unknown} 生效值。
352
+ */
353
+ function configValue(config, key, fallback) {
354
+ const value = config?.[key]
355
+ if (Array.isArray(fallback)) return Array.isArray(value) ? value.filter((item) => typeof item === 'string') : fallback
356
+ if (typeof fallback === 'number') return typeof value === 'number' && Number.isFinite(value) ? value : fallback
357
+ return value ?? fallback
358
+ }
359
+
360
+ /**
361
+ * 预测一条首请求里的 `agent-instructions` 消息。
362
+ * @param {object} ctx - host 插件上下文。
363
+ * @param {object} options - 条件。
364
+ * @param {string} options.workspacePath - 工作区路径。
365
+ * @param {object} [options.modules] - `resolveModules()` 的结果;省略时只按宿主行判定。
366
+ * @param {NodeJS.ProcessEnv} [options.env] - 进程环境(测试用)。
367
+ * @returns {Promise<object>} `{ available, text, files, omitted, truncated, confidence, reason? }`。
368
+ */
369
+ export async function previewInstructions(ctx, options) {
370
+ const device = (options.modules ?? hostModuleResolver(ctx)).get(MODULE)
371
+ if (!device.available) {
372
+ return { available: false, reason: device.reason, text: '', files: [], omitted: [], truncated: [] }
373
+ }
374
+ if (typeof options.workspacePath !== 'string' || options.workspacePath.length === 0) {
375
+ return { available: false, reason: '未选择工作区', text: '', files: [], omitted: [], truncated: [] }
376
+ }
377
+
378
+ const row = { config: device.config }
379
+ const config = {
380
+ maxBytes: configValue(row.config, 'maxBytes', DEFAULTS.maxBytes),
381
+ maxSourceBytes: configValue(row.config, 'maxSourceBytes', DEFAULTS.maxSourceBytes),
382
+ projectRootMarkers: configValue(row.config, 'projectRootMarkers', DEFAULTS.projectRootMarkers),
383
+ instructionFileCandidates: sanitizeCandidates(configValue(row.config, 'instructionFileCandidates', DEFAULTS.instructionFileCandidates), DEFAULTS.instructionFileCandidates),
384
+ localInstructionFileCandidates: sanitizeCandidates(configValue(row.config, 'localInstructionFileCandidates', DEFAULTS.localInstructionFileCandidates), DEFAULTS.localInstructionFileCandidates),
385
+ }
386
+ if (config.maxBytes <= 0 || config.maxSourceBytes <= 0) {
387
+ return { available: false, reason: '指令字节预算被禁用', text: '', files: [], omitted: [], truncated: [] }
388
+ }
389
+
390
+ const homes = resolveHomes(options.env ?? process.env)
391
+ const discovered = await discoverFiles(config, options.workspacePath, homes)
392
+ const loaded = []
393
+ const skipped = []
394
+ for (const file of discovered) {
395
+ // 先按 stat 的大小拒绝:超限文件不该被整份读进内存再丢掉。
396
+ if (typeof file.size === 'number' && file.size > config.maxSourceBytes) {
397
+ skipped.push({ displayPath: file.displayPath, reason: `超过 maxSourceBytes(${config.maxSourceBytes} 字节)` })
398
+ continue
399
+ }
400
+ const content = await readTextFile(file.absolutePath)
401
+ if (content === null) {
402
+ // 读不到的文件跳过,但留下记录:预演不该把「读失败」静默成「没有这个文件」。
403
+ skipped.push({ displayPath: file.displayPath, reason: '读取失败' })
404
+ continue
405
+ }
406
+ if (byteLength(content) > config.maxSourceBytes) {
407
+ skipped.push({ displayPath: file.displayPath, reason: `超过 maxSourceBytes(${config.maxSourceBytes} 字节)` })
408
+ continue
409
+ }
410
+ loaded.push({ ...file, content })
411
+ }
412
+
413
+ // 同一候选组内,trim 后内容相同的文件只渲染第一份(用户全局两个根共用一组)。
414
+ const keptDigests = new Map()
415
+ const kept = []
416
+ for (const file of loaded) {
417
+ const group = candidateGroup(file.displayPath, homes)
418
+ const digests = keptDigests.get(group) ?? new Set()
419
+ keptDigests.set(group, digests)
420
+ const digest = createHash('sha1').update(file.content.trim()).digest('hex')
421
+ if (digests.has(digest)) continue
422
+ digests.add(digest)
423
+ kept.push(file)
424
+ }
425
+ if (kept.length === 0) {
426
+ return { available: true, text: '', files: [], omitted: [], truncated: [], skipped, confidence: 'derived' }
427
+ }
428
+
429
+ const style = { intro: AGENT_INSTRUCTIONS_INTRO, section: sectionText }
430
+ const rendered = renderInstructionChains(kept, config.maxBytes, style, homes)
431
+ const represented = new Set(rendered.represented.map((file) => file.absolutePath))
432
+ const omittedPaths = new Set(rendered.omitted.map((file) => file.absolutePath))
433
+ const truncatedPaths = new Set(rendered.truncated.map((item) => item.displayPath))
434
+ return {
435
+ available: true,
436
+ text: rendered.text,
437
+ confidence: 'derived',
438
+ files: kept.map((file) => ({
439
+ displayPath: file.displayPath,
440
+ bytes: byteLength(file.content),
441
+ included: represented.has(file.absolutePath),
442
+ omitted: omittedPaths.has(file.absolutePath),
443
+ truncated: truncatedPaths.has(file.displayPath),
444
+ })),
445
+ omitted: rendered.omitted.map((file) => ({ displayPath: file.displayPath })),
446
+ truncated: rendered.truncated,
447
+ skipped,
448
+ maxBytes: config.maxBytes,
449
+ }
450
+ }