dsh-vscode-mode 0.34.0 → 0.35.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.
@@ -0,0 +1,362 @@
1
+ /**
2
+ * dsh-vscode-mode host — /html-plan 的附件落盘纯逻辑。
3
+ *
4
+ * 职责:从已入库的图片/文件引用生成安全的文件名、派生固定 slug、按顺序写进
5
+ * plans/<slug>/assets/,并产出交给 agent 的附件说明。所有外部能力(读字节、写文件)
6
+ * 走入参注入,本模块不直接碰 ctx 与文件系统,便于 node 单测。
7
+ * @author ddj 2026年11月24号
8
+ */
9
+
10
+ //region 结构面
11
+
12
+ /** 落盘成功的一个附件。 */
13
+ export interface StagedAttachment {
14
+ /** assets/ 下的文件名。 */
15
+ name: string
16
+ /** 工作区相对路径:plans/<slug>/assets/<name>。 */
17
+ relativePath: string
18
+ /** 字节数。 */
19
+ bytes: number
20
+ /** 来源类型。 */
21
+ kind: 'image' | 'file'
22
+ }
23
+
24
+ /** 被跳过的附件及原因。 */
25
+ export interface SkippedAttachment {
26
+ /** 展示用文件名。 */
27
+ name: string
28
+ /** 跳过原因(可直接读)。 */
29
+ reason: string
30
+ }
31
+
32
+ /** 一次附件落盘的结果。 */
33
+ export interface AttachmentStage {
34
+ /** 固定 slug。 */
35
+ slug: string
36
+ /** assets 目录(工作区相对路径)。 */
37
+ dir: string
38
+ /** 已写入的附件。 */
39
+ files: StagedAttachment[]
40
+ /** 未写入的附件。 */
41
+ skipped: SkippedAttachment[]
42
+ }
43
+
44
+ /** 落盘依赖(真实实现由命令层提供)。 */
45
+ export interface AttachmentStageDeps {
46
+ /** 命令收到的 ImageBlock / FileBlock 列表,按提交顺序。 */
47
+ blocks: readonly unknown[]
48
+ /** 固定 slug。 */
49
+ slug: string
50
+ /** 取消信号。 */
51
+ signal?: AbortSignal
52
+ /** 读图片字节(参数是 attachment 引用)。 */
53
+ readImage: (ref: unknown, signal?: AbortSignal) => Promise<Uint8Array>
54
+ /** 读文件字节(参数是 attachment 引用)。 */
55
+ readFile: (ref: unknown, signal?: AbortSignal) => Promise<Uint8Array>
56
+ /** 写一个附件(参数是工作区相对路径)。 */
57
+ write: (relativePath: string, bytes: Uint8Array) => Promise<void>
58
+ /** 单文件上限,默认 25 MB。 */
59
+ maxBytes?: number
60
+ /** 附件数量上限,默认 12 个。 */
61
+ maxCount?: number
62
+ }
63
+
64
+ /** 一个内容块的引用视图。 */
65
+ interface AttachmentRefView {
66
+ /** 原始 attachment 引用对象(交给读字节函数)。 */
67
+ raw: unknown
68
+ /** 存储 id(用于去重)。 */
69
+ id: string
70
+ /** 原始显示名。 */
71
+ name: string
72
+ /** 媒体类型。 */
73
+ mediaType: string
74
+ /** 块类型。 */
75
+ kind: 'image' | 'file'
76
+ }
77
+
78
+ //endregion
79
+
80
+ //region 常量
81
+
82
+ /** assets 目录名。 */
83
+ export const ATTACHMENTS_DIR = 'assets'
84
+ /** 单文件落盘上限:超过就不复制(避免把工作区写满)。 */
85
+ export const MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024
86
+ /** 单次命令最多接收的附件数。 */
87
+ export const MAX_ATTACHMENTS = 12
88
+ /** 文件名长度上限(保留扩展名)。 */
89
+ export const MAX_FILE_NAME = 80
90
+
91
+ /** 媒体类型 → 扩展名(文件名缺失时兜底)。 */
92
+ const MIME_EXT: Record<string, string> = {
93
+ 'image/png': '.png',
94
+ 'image/jpeg': '.jpg',
95
+ 'image/webp': '.webp',
96
+ 'image/gif': '.gif',
97
+ 'application/pdf': '.pdf',
98
+ 'text/plain': '.txt',
99
+ 'text/markdown': '.md',
100
+ 'text/csv': '.csv',
101
+ 'application/json': '.json',
102
+ 'application/zip': '.zip',
103
+ }
104
+
105
+ /** 派生 slug 时跳过的常见虚词(只影响可读性,不改变语义)。 */
106
+ const STOP_WORDS = new Set(['a', 'an', 'the', 'and', 'or', 'to', 'of', 'in', 'on', 'for', 'with', 'add', 'new'])
107
+
108
+ /** Windows 保留文件名。 */
109
+ const RESERVED_NAME = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i
110
+
111
+ //endregion
112
+
113
+ //region 工具
114
+
115
+ /**
116
+ * 取异常的展示文案。
117
+ * @author ddj 2026年11月24号
118
+ * @param error 捕获值
119
+ * @returns 可读文案
120
+ */
121
+ function messageOf(error: unknown): string {
122
+ if (error instanceof Error) return error.message
123
+ return String(error ?? '未知错误')
124
+ }
125
+
126
+ /**
127
+ * 按媒体类型取扩展名。
128
+ * @author ddj 2026年11月24号
129
+ * @param mediaType 媒体类型
130
+ * @returns 形如 `.png` 的扩展名;未知类型返回空串
131
+ */
132
+ export function extensionOf(mediaType: string): string {
133
+ const value = String(mediaType ?? '').toLowerCase()
134
+ const known = MIME_EXT[value]
135
+ if (known) return known
136
+ const match = /^[a-z]+\/([a-z0-9.+-]+)$/.exec(value)
137
+ if (!match) return ''
138
+ const suffix = match[1].replace(/[^a-z0-9]/g, '').slice(0, 5)
139
+ return suffix ? '.' + suffix : ''
140
+ }
141
+
142
+ /**
143
+ * 把过长的文件名裁到上限,优先保住扩展名。
144
+ * @author ddj 2026年11月24号
145
+ * @param name 已清洗过的文件名
146
+ * @param limit 长度上限
147
+ * @returns 裁好的文件名
148
+ */
149
+ function trimName(name: string, limit: number): string {
150
+ if (name.length <= limit) return name
151
+ const dot = name.lastIndexOf('.')
152
+ const suffix = dot > 0 && name.length - dot <= 9 ? name.slice(dot) : ''
153
+ const base = suffix ? name.slice(0, dot) : name
154
+ return base.slice(0, Math.max(1, limit - suffix.length)) + suffix
155
+ }
156
+
157
+ /**
158
+ * 清洗附件文件名:去目录、去控制字符与 Windows 非法字符、补扩展名、避开保留名。
159
+ * @author ddj 2026年11月24号
160
+ * @param raw 原始显示名(可能为空或带路径)
161
+ * @param index 提交顺序(兜底命名用)
162
+ * @param kind 来源类型
163
+ * @param mediaType 媒体类型(缺扩展名时补)
164
+ * @returns 可安全写进 assets/ 的文件名
165
+ */
166
+ export function safeFileName(raw: unknown, index: number, kind: 'image' | 'file', mediaType = ''): string {
167
+ const text = String(raw ?? '').replace(/\\/g, '/')
168
+ const leaf = text.slice(text.lastIndexOf('/') + 1)
169
+ const cleaned = leaf
170
+ .replace(/[\u0000-\u001f\u007f<>:"|?*]/g, '')
171
+ .replace(/^[.\s]+|[.\s]+$/g, '')
172
+ .slice(0, MAX_FILE_NAME)
173
+
174
+ let name = cleaned
175
+ if (!name) name = (kind === 'image' ? 'image-' : 'file-') + String(index + 1) + (extensionOf(mediaType) || (kind === 'image' ? '.png' : '.bin'))
176
+ else if (!/\.[a-z0-9]{1,8}$/i.test(name)) {
177
+ const suffix = extensionOf(mediaType)
178
+ if (suffix) name += suffix
179
+ }
180
+
181
+ name = trimName(name, MAX_FILE_NAME)
182
+ if (RESERVED_NAME.test(name)) name = '_' + name
183
+ return name
184
+ }
185
+
186
+ /**
187
+ * 让同名附件错开(大小写不敏感,贴合 Windows 语义)。
188
+ * @author ddj 2026年11月24号
189
+ * @param name 候选文件名
190
+ * @param used 已占用的文件名(小写)
191
+ * @returns 唯一的文件名,并登记进 used
192
+ */
193
+ export function uniqueFileName(name: string, used: Set<string>): string {
194
+ if (!used.has(name.toLowerCase())) {
195
+ used.add(name.toLowerCase())
196
+ return name
197
+ }
198
+
199
+ const dot = name.lastIndexOf('.')
200
+ const base = dot > 0 ? name.slice(0, dot) : name
201
+ const suffix = dot > 0 ? name.slice(dot) : ''
202
+ for (let serial = 2; serial < 100; serial += 1) {
203
+ const candidate = base + '-' + String(serial) + suffix
204
+ if (used.has(candidate.toLowerCase())) continue
205
+ used.add(candidate.toLowerCase())
206
+ return candidate
207
+ }
208
+
209
+ const fallback = base + '-' + String(Date.now()) + suffix
210
+ used.add(fallback.toLowerCase())
211
+ return fallback
212
+ }
213
+
214
+ /**
215
+ * 生成本地时间戳 `YYYYMMDD-HHmm`(slug 兜底用)。
216
+ * @author ddj 2026年11月24号
217
+ * @param at 时间点
218
+ * @returns 13 位时间戳片段
219
+ */
220
+ function stampOf(at: Date): string {
221
+ const pad = (value: number): string => String(value).padStart(2, '0')
222
+ return String(at.getFullYear()) + pad(at.getMonth() + 1) + pad(at.getDate()) + '-' + pad(at.getHours()) + pad(at.getMinutes())
223
+ }
224
+
225
+ /**
226
+ * 从任务文本派生固定 slug:取前几个 ASCII 词;词太少或没有可用词时用时间戳。
227
+ * 中文任务里零散出现的单个短 ASCII 词(如 html)不足以当目录名,走时间戳兜底。
228
+ * @author ddj 2026年11月24号
229
+ * @param task 任务文本(可能全是中文)
230
+ * @param at 时间点(兜底时间戳)
231
+ * @returns kebab-case slug(只含小写字母、数字与连字符)
232
+ */
233
+ export function slugFromTask(task: unknown, at: Date = new Date()): string {
234
+ const words = String(task ?? '').toLowerCase().match(/[a-z0-9]+/g) ?? []
235
+ const meaningful = words.filter((word) => !STOP_WORDS.has(word)).slice(0, 4)
236
+ const usable = meaningful.length >= 2 || (meaningful.length === 1 && meaningful[0].length >= 6)
237
+ const slug = usable ? meaningful.join('-').slice(0, 40).replace(/-+/g, '-').replace(/^-|-$/g, '') : ''
238
+ return slug || 'attach-' + stampOf(at)
239
+ }
240
+
241
+ /**
242
+ * 字节数的人类可读写法。
243
+ * @author ddj 2026年11月24号
244
+ * @param bytes 字节数
245
+ * @returns 如 `812 KB`;非法值返回空串
246
+ */
247
+ export function formatBytes(bytes: unknown): string {
248
+ const value = Number(bytes)
249
+ if (!Number.isFinite(value) || value <= 0) return ''
250
+ if (value >= 1024 * 1024) return (value / 1024 / 1024).toFixed(1) + ' MB'
251
+ if (value >= 1024) return String(Math.round(value / 1024)) + ' KB'
252
+ return String(value) + ' B'
253
+ }
254
+
255
+ /**
256
+ * 从一个内容块里取出引用视图。
257
+ * @author ddj 2026年11月24号
258
+ * @param block 命令收到的内容块
259
+ * @returns 引用视图;不是图片/文件块时 null
260
+ */
261
+ function refOf(block: unknown): AttachmentRefView | null {
262
+ if (block === null || typeof block !== 'object') return null
263
+ const row = block as { type?: unknown; attachment?: unknown }
264
+ const kind = row.type === 'image' ? 'image' : row.type === 'file' ? 'file' : ''
265
+ if (!kind || row.attachment === null || typeof row.attachment !== 'object') return null
266
+ const ref = row.attachment as { attachmentId?: unknown; name?: unknown; mediaType?: unknown }
267
+ return {
268
+ raw: row.attachment,
269
+ id: typeof ref.attachmentId === 'string' ? ref.attachmentId : '',
270
+ name: typeof ref.name === 'string' ? ref.name : '',
271
+ mediaType: typeof ref.mediaType === 'string' ? ref.mediaType : '',
272
+ kind,
273
+ }
274
+ }
275
+
276
+ //endregion
277
+
278
+ //region 落盘与指令
279
+
280
+ /**
281
+ * 把附件按提交顺序写进 plans/<slug>/assets/。
282
+ *
283
+ * 单个附件失败只记进 skipped,不影响其余附件;取消信号在每轮开始时检查。
284
+ * @author ddj 2026年11月24号
285
+ * @param deps 内容块、slug 与读写能力
286
+ * @returns 已写入与被跳过的附件清单
287
+ */
288
+ export async function stageAttachments(deps: AttachmentStageDeps): Promise<AttachmentStage> {
289
+ const slug = String(deps.slug ?? '')
290
+ const dir = 'plans/' + slug + '/' + ATTACHMENTS_DIR
291
+ const maxBytes = deps.maxBytes ?? MAX_ATTACHMENT_BYTES
292
+ const maxCount = deps.maxCount ?? MAX_ATTACHMENTS
293
+ const files: StagedAttachment[] = []
294
+ const skipped: SkippedAttachment[] = []
295
+ const used = new Set<string>()
296
+ const seen = new Set<string>()
297
+
298
+ for (const [index, block] of deps.blocks.entries()) {
299
+ if (deps.signal?.aborted) break
300
+ const ref = refOf(block)
301
+ if (!ref) {
302
+ skipped.push({ name: 'attachment-' + String(index + 1), reason: '不是可用的图片或文件引用' })
303
+ continue
304
+ }
305
+ if (ref.id && seen.has(ref.id)) continue
306
+ if (ref.id) seen.add(ref.id)
307
+
308
+ const name = uniqueFileName(safeFileName(ref.name, index, ref.kind, ref.mediaType), used)
309
+ if (files.length >= maxCount) {
310
+ skipped.push({ name, reason: '超过 ' + String(maxCount) + ' 个附件上限' })
311
+ continue
312
+ }
313
+
314
+ try {
315
+ const bytes = ref.kind === 'image'
316
+ ? await deps.readImage(ref.raw, deps.signal)
317
+ : await deps.readFile(ref.raw, deps.signal)
318
+ if (bytes.byteLength > maxBytes) {
319
+ skipped.push({ name, reason: '超过 ' + formatBytes(maxBytes) })
320
+ continue
321
+ }
322
+ const relativePath = dir + '/' + name
323
+ await deps.write(relativePath, bytes)
324
+ files.push({ name, relativePath, bytes: bytes.byteLength, kind: ref.kind })
325
+ } catch (error) {
326
+ skipped.push({ name, reason: messageOf(error) })
327
+ }
328
+ }
329
+
330
+ return { slug, dir, files, skipped }
331
+ }
332
+
333
+ /**
334
+ * 生成交给 agent 的附件说明段(路径、类型、大小、页面写法)。
335
+ * @author ddj 2026年11月24号
336
+ * @param stage 落盘结果
337
+ * @returns 逐行文本;没有附件时返回空数组
338
+ */
339
+ export function attachmentLines(stage: AttachmentStage): string[] {
340
+ const lines: string[] = []
341
+
342
+ if (stage.files.length) {
343
+ lines.push('附件已保存(页面里必须引用,不要复制到别处):')
344
+ for (const file of stage.files) {
345
+ const size = formatBytes(file.bytes)
346
+ const kindText = file.kind === 'image' ? '图片' : '文件'
347
+ lines.push('- ' + file.relativePath + '(' + kindText + (size ? ',' + size : '') + ')')
348
+ }
349
+ lines.push('页面里用 <doc-attach label="随附材料"><doc-file src="assets/<文件名>">显示名</doc-file></doc-attach> 引用;')
350
+ lines.push('图片先用 read_image 看清内容;文档或日志用 read 读原文。')
351
+ lines.push('打包成功后 plans/' + stage.slug + '/assets/ 会被删除;要再打包一次就先给 plan.mjs 加 --keep-assets。')
352
+ }
353
+
354
+ if (stage.skipped.length) {
355
+ lines.push('以下附件没能落盘,本次不要引用:')
356
+ for (const item of stage.skipped) lines.push('- ' + item.name + ':' + item.reason)
357
+ }
358
+
359
+ return lines
360
+ }
361
+
362
+ //endregion