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.
@@ -6,16 +6,28 @@
6
6
  * - 处理器调用官方 /plan 命令并带上本插件的技能指令,官方 plan 处理器会
7
7
  * 进入计划模式并用 agent.steer 把这段指令作为用户消息送出;
8
8
  * - 因此这里不自行构造 UserMessage、不碰 plan 模式内部状态,官方不可用时直接报错(fail closed)。
9
+ *
10
+ * 附件:命令声明 input.attachments,官方执行器把 composer 的图片/文件入库后再交给本处理器。
11
+ * 处理器把字节复制到 plans/<slug>/assets/(agent 与打包脚本都读得到的工作区内路径),
12
+ * 并把路径写进指令;失败只降级为说明文字,绝不阻断进入计划模式。
9
13
  * @author ddj 2026年11月21号
10
14
  */
15
+ import { mkdir, rmdir, unlink, writeFile } from 'node:fs/promises'
16
+ import { dirname, join } from 'node:path'
11
17
  import { log } from './log.js'
12
- import type { Ctx } from './store.js'
18
+ import { cwdOfSession, type Ctx } from './store.js'
19
+ import {
20
+ attachmentLines,
21
+ slugFromTask,
22
+ stageAttachments,
23
+ type AttachmentStage,
24
+ } from './htmlPlanAttachments.js'
13
25
 
14
26
  /** 命令名(官方语法:小写字母开头,允许数字/_/-)。 */
15
27
  export const HTML_PLAN_COMMAND = 'html-plan'
16
28
 
17
29
  /** 命令描述(出现在 / 菜单与命令目录)。 */
18
- export const HTML_PLAN_DESCRIPTION = '用 HTML 计划页进入计划模式:/html-plan <任务>'
30
+ export const HTML_PLAN_DESCRIPTION = '用 HTML 计划页进入计划模式:/html-plan <任务>(可附图片或文件)'
19
31
 
20
32
  /** 计划指令模板版本(改文案时便于测试断言)。 */
21
33
  export const HTML_PLAN_INSTRUCTION_HEAD = '请使用技能 dsh-vscodemode-html-plan 规划下面的任务,并按 DSH 计划模式提交:'
@@ -34,7 +46,9 @@ export const HTML_PLAN_DELEGATE_INSTRUCTION = '写页方式:本次已获用户
34
46
 
35
47
  /** 明确不委派的指令段(--no-delegate)。 */
36
48
  export const HTML_PLAN_SINGLE_AGENT_INSTRUCTION = '写页方式:本次不要委派子 agent,由你自己写计划页并用 plan.mjs 打包。'
37
- /** 官方命令运行时最小结构面(宿主服务,鸭子类型)。 */interface CommandsLike {
49
+
50
+ /** 官方命令运行时最小结构面(宿主服务,鸭子类型)。 */
51
+ interface CommandsLike {
38
52
  register?: (definition: unknown) => unknown
39
53
  execute?: (agent: unknown, line: string, attachments: readonly unknown[], signal: AbortSignal) => Promise<{ result?: { kind?: string; text?: string } } | undefined>
40
54
  }
@@ -43,12 +57,55 @@ export const HTML_PLAN_SINGLE_AGENT_INSTRUCTION = '写页方式:本次不要
43
57
  interface CommandCtxLike {
44
58
  commands?: CommandsLike
45
59
  effect?: (run: () => unknown, label?: string) => unknown
60
+ get?: (name: string) => unknown
61
+ }
62
+
63
+ /** 官方命令调用(只声明本命令用到的字段)。 */
64
+ export interface HtmlPlanInvocation {
65
+ /** 接收命令的 agent。 */
66
+ agent?: unknown
67
+ /** 命令名之后的原始输入。 */
68
+ rawInput?: unknown
69
+ /** 取消信号。 */
70
+ signal?: AbortSignal
71
+ /** 已入库的图片/文件块(未声明 attachments 时为空)。 */
72
+ attachments?: readonly unknown[]
73
+ }
74
+
75
+ /** 附件准备结果(默认实现是落盘;测试可注入假的)。 */
76
+ export interface AttachmentPrep {
77
+ /** 固定 slug;没附件时 null(沿用 agent 自选)。 */
78
+ slug: string | null
79
+ /** 落盘成功的附件数量。 */
80
+ count: number
81
+ /** 追加到指令里的附件段。 */
82
+ lines: string[]
83
+ /** /plan 失败时回滚本次写入的附件。 */
84
+ rollback: () => Promise<void>
85
+ }
86
+
87
+ /** 指令模板附加信息(固定 slug 与附件段)。 */
88
+ export interface HtmlPlanInstructionExtras {
89
+ /** 固定 slug(有附件时由命令决定)。 */
90
+ slug?: string | null
91
+ /** 附件说明行。 */
92
+ attachmentLines?: readonly string[]
46
93
  }
47
94
 
48
- /** 安装选项(测试可替换指令模板)。 */
95
+ /** 附件存储服务最小结构面。 */
96
+ interface AttachmentStoreLike {
97
+ readImage?: (ref: unknown, signal?: AbortSignal) => Promise<{ data?: unknown }>
98
+ readFileStream?: (ref: unknown, signal?: AbortSignal) => AsyncIterable<Uint8Array>
99
+ }
100
+
101
+ /** 安装选项(测试可替换指令模板与附件准备)。 */
49
102
  export interface HtmlPlanCommandOptions {
50
- /** 自定义指令模板(入参为任务文本与委派开关)。 */
51
- instructionOf?: (task: string, delegate?: boolean | null) => string
103
+ /** 自定义指令模板(入参为任务文本、委派开关与附加信息)。 */
104
+ instructionOf?: (task: string, delegate?: boolean | null, extras?: HtmlPlanInstructionExtras) => string
105
+ /** 附件准备(默认落盘到 plans/<slug>/assets/);测试可替换。 */
106
+ prepareAttachments?: (invocation: HtmlPlanInvocation, task: string) => Promise<AttachmentPrep>
107
+ /** 宿主上下文:取 attachments 服务与会话工作区。 */
108
+ hostCtx?: unknown
52
109
  }
53
110
 
54
111
  /** 命令输入解析结果。 */
@@ -77,32 +134,194 @@ export function parseHtmlPlanInput(rawInput: unknown): HtmlPlanInput {
77
134
  }
78
135
  return { delegate, task: rest.trim() }
79
136
  }
137
+
80
138
  /**
81
139
  * 构造交给 agent 的计划指令:点名技能、产出路径、打包、标记行与审批方式。
140
+ * 有附件时用命令固定下来的 slug,并把附件段插在步骤之后。
82
141
  * @author ddj 2026年11月21号
83
142
  * @param task 用户任务文本
143
+ * @param delegate 委派开关(null = 未指定)
144
+ * @param extras 固定 slug 与附件说明
84
145
  * @returns 完整用户消息正文
85
146
  */
86
- export function buildHtmlPlanInstruction(task: string, delegate: boolean | null = null): string {
147
+ export function buildHtmlPlanInstruction(
148
+ task: string,
149
+ delegate: boolean | null = null,
150
+ extras: HtmlPlanInstructionExtras = {},
151
+ ): string {
87
152
  const objective = String(task ?? '').trim()
153
+ const slug = typeof extras.slug === 'string' && /^[a-z0-9][a-z0-9-]*$/i.test(extras.slug) ? extras.slug : ''
154
+ const pagePath = slug ? 'plans/' + slug + '/plan.html' : 'plans/<slug>/plan.html'
155
+ const packedPath = slug ? 'plans/' + slug + '/plan.packed.html' : 'plans/<slug>/plan.packed.html'
156
+ const command = slug
157
+ ? 'node <技能目录>/runtime/plan.mjs ' + slug + ' --root <工作区>'
158
+ : 'node <技能目录>/runtime/plan.mjs <slug> --root <工作区>'
159
+ const check = slug ? 'plan.mjs ' + slug + ' --check' : 'plan.mjs <slug> --check'
88
160
  const steps = [
89
- '1. 先读相关代码与文件,按技能规则写 plans/<slug>/plan.html(slug 用 kebab-case)。',
90
- '2. 用一条命令打包:node <技能目录>/runtime/plan.mjs <slug> --root <工作区>,它会复制运行时、pack、清理;再跑 plan.mjs <slug> --check 确认 plan.packed.html 在位。',
161
+ '1. 先读相关代码与文件,按技能规则写 ' + pagePath + (slug ? '(slug 已固定,不要另起目录)。' : '(slug 用 kebab-case)。'),
162
+ '2. 用一条命令打包:' + command + ',它会复制运行时、pack、清理;再跑 ' + check + ' 确认 plan.packed.html 在位。',
91
163
  '3. 计划模式允许写 plans/ 下的计划文件:不要因为「在计划模式」跳过写页面,更不要让我退出计划模式来生成。',
92
- '4. 页面确认生成后,才调用 exit_plan_mode:正文第一行必须是「# 计划:<标题>」,并单独一行「HTML 计划页:plans/<slug>/plan.packed.html」;没生成成功就别写这一行,改交 Markdown 计划并说明原因。',
164
+ '4. 页面确认生成后,才调用 exit_plan_mode:正文第一行必须是「# 计划:<标题>」,并单独一行「HTML 计划页:' + packedPath + '」;没生成成功就别写这一行,改交 Markdown 计划并说明原因。',
93
165
  '5. 计划正文同时给出 3~6 行摘要与待决策清单;不要绕过计划模式直接开工。',
94
166
  ]
167
+ const attachment = (extras.attachmentLines ?? []).filter((line) => typeof line === 'string' && line.trim() !== '')
95
168
  const extra = delegate === null ? '' : (delegate ? HTML_PLAN_DELEGATE_INSTRUCTION : HTML_PLAN_SINGLE_AGENT_INSTRUCTION)
96
- const lines = [HTML_PLAN_INSTRUCTION_HEAD, ...steps, ...(extra ? [`${steps.length + 1}. ${extra}`] : []), '', '任务:' + objective]
169
+ const lines = [
170
+ HTML_PLAN_INSTRUCTION_HEAD,
171
+ ...steps,
172
+ ...(attachment.length ? ['', ...attachment] : []),
173
+ ...(extra ? [String(steps.length + 1) + '. ' + extra] : []),
174
+ '',
175
+ '任务:' + objective,
176
+ ]
97
177
  return lines.join('\n')
98
178
  }
99
179
 
100
- /** 取异常的展示文案。 */
180
+ /**
181
+ * 取异常的展示文案。
182
+ * @author ddj 2026年11月21号
183
+ * @param error 捕获值
184
+ * @returns 可读文案
185
+ */
101
186
  function messageOf(error: unknown): string {
102
187
  if (error instanceof Error) return error.message
103
188
  return String(error ?? '未知错误')
104
189
  }
105
190
 
191
+ /**
192
+ * 把流式字节拼成一个 Uint8Array(附件可能是任意长度,不假设单块)。
193
+ * @author ddj 2026年11月24号
194
+ * @param source 按顺序产出的字节块
195
+ * @returns 拼接后的字节
196
+ */
197
+ async function readChunks(source: AsyncIterable<Uint8Array>): Promise<Uint8Array> {
198
+ const parts: Uint8Array[] = []
199
+ let total = 0
200
+ for await (const part of source) {
201
+ parts.push(part)
202
+ total += part.byteLength
203
+ }
204
+
205
+ const merged = new Uint8Array(total)
206
+ let offset = 0
207
+ for (const part of parts) {
208
+ merged.set(part, offset)
209
+ offset += part.byteLength
210
+ }
211
+ return merged
212
+ }
213
+
214
+ /**
215
+ * 归一化附件存储返回的字节。
216
+ * @author ddj 2026年11月24号
217
+ * @param value 服务返回值
218
+ * @returns 字节视图
219
+ * @throws 无法识别时抛错(由上层记入 skipped)
220
+ */
221
+ function toBytes(value: unknown): Uint8Array {
222
+ if (value instanceof Uint8Array) return value
223
+ if (value instanceof ArrayBuffer) return new Uint8Array(value)
224
+ if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength)
225
+ throw new Error('附件存储返回了无法识别的字节')
226
+ }
227
+
228
+ /**
229
+ * 回滚本次写入的附件:逐个删除文件,再尝试移除空目录。
230
+ * @author ddj 2026年11月24号
231
+ * @param workspace 工作区绝对路径
232
+ * @param stage 落盘结果
233
+ * @returns 完成后的 Promise(单步失败只忽略)
234
+ */
235
+ async function rollbackStage(workspace: string, stage: AttachmentStage): Promise<void> {
236
+ for (const file of stage.files) {
237
+ try {
238
+ await unlink(join(workspace, file.relativePath))
239
+ } catch {
240
+ /* 文件可能已被删除 */
241
+ }
242
+ }
243
+ try {
244
+ await rmdir(join(workspace, stage.dir))
245
+ } catch {
246
+ /* 目录非空或已不存在 */
247
+ }
248
+ }
249
+
250
+ /**
251
+ * 默认附件准备:把 composer 的图片/文件复制到 plans/<slug>/assets/。
252
+ *
253
+ * 任何失败(服务缺失、读字节失败、写盘失败)都降级成说明行,不阻断进入计划模式;
254
+ * 只有 /plan 调用失败时才会回滚本次写入。
255
+ * @author ddj 2026年11月24号
256
+ * @param hostCtx 宿主上下文
257
+ * @param invocation 官方命令调用
258
+ * @param task 任务文本(派生 slug)
259
+ * @returns 附件准备结果
260
+ */
261
+ export async function stagePlanFiles(
262
+ hostCtx: unknown,
263
+ invocation: HtmlPlanInvocation,
264
+ task: string,
265
+ ): Promise<AttachmentPrep> {
266
+ const empty: AttachmentPrep = { slug: null, count: 0, lines: [], rollback: async () => {} }
267
+ const blocks = Array.isArray(invocation?.attachments) ? invocation.attachments.filter(Boolean) : []
268
+ if (!blocks.length) return empty
269
+
270
+ const ctx = hostCtx as { get?: (name: string) => unknown } | undefined
271
+ const session = (invocation?.agent as { session?: unknown } | undefined)?.session
272
+ const workspace = typeof ctx?.get === 'function' ? cwdOfSession(ctx, session) : null
273
+ const store = typeof ctx?.get === 'function' ? ctx.get('attachments') as AttachmentStoreLike | undefined : undefined
274
+ const readImage = store?.readImage
275
+ const readFileStream = store?.readFileStream
276
+ if (!workspace || typeof readImage !== 'function' || typeof readFileStream !== 'function') {
277
+ return {
278
+ slug: null,
279
+ count: 0,
280
+ lines: ['附件读取失败:当前会话没有可用工作区或附件存储;本次按无附件规划。'],
281
+ rollback: async () => {},
282
+ }
283
+ }
284
+
285
+ const slug = slugFromTask(task)
286
+ try {
287
+ const stage = await stageAttachments({
288
+ blocks,
289
+ slug,
290
+ signal: invocation.signal,
291
+ readImage: async (ref, signal) => toBytes((await readImage(ref, signal)).data),
292
+ readFile: async (ref, signal) => readChunks(readFileStream(ref, signal)),
293
+ write: async (relativePath, bytes) => {
294
+ const absolute = join(workspace, relativePath)
295
+ await mkdir(dirname(absolute), { recursive: true })
296
+ await writeFile(absolute, bytes)
297
+ },
298
+ })
299
+ return {
300
+ slug,
301
+ count: stage.files.length,
302
+ lines: attachmentLines(stage),
303
+ rollback: () => rollbackStage(workspace, stage),
304
+ }
305
+ } catch (error) {
306
+ return { slug: null, count: 0, lines: ['附件读取失败:' + messageOf(error) + ';本次按无附件规划。'], rollback: async () => {} }
307
+ }
308
+ }
309
+
310
+ /**
311
+ * 回滚但不覆盖原始错误。
312
+ * @author ddj 2026年11月24号
313
+ * @param prep 附件准备结果(可能为空)
314
+ * @returns 完成后的 Promise
315
+ */
316
+ async function rollbackOf(prep: AttachmentPrep | null): Promise<void> {
317
+ if (!prep) return
318
+ try {
319
+ await prep.rollback()
320
+ } catch {
321
+ /* 收尾失败不影响错误上报 */
322
+ }
323
+ }
324
+
106
325
  /**
107
326
  * 构造 /html-plan 命令定义(导出便于单测直接调用 handler)。
108
327
  * @author ddj 2026年11月21号
@@ -112,26 +331,46 @@ function messageOf(error: unknown): string {
112
331
  */
113
332
  export function htmlPlanCommandDefinition(commands: CommandsLike, options: HtmlPlanCommandOptions = {}): unknown {
114
333
  const instructionOf = typeof options.instructionOf === 'function' ? options.instructionOf : buildHtmlPlanInstruction
334
+ const prepareAttachments = typeof options.prepareAttachments === 'function'
335
+ ? options.prepareAttachments
336
+ : (invocation: HtmlPlanInvocation, task: string) => stagePlanFiles(options.hostCtx, invocation, task)
115
337
  return {
116
338
  name: HTML_PLAN_COMMAND,
117
339
  description: HTML_PLAN_DESCRIPTION,
118
- input: { hint: '<任务描述>' },
340
+ input: { hint: '<任务描述>(可附图片或文件)', attachments: true },
119
341
  /** @private @author ddj 2026年11月21号 @param invocation 官方命令调用。 @returns 成功/错误结算。 */
120
- handler: async (invocation: { agent?: unknown; rawInput?: unknown; signal?: AbortSignal }) => {
342
+ handler: async (invocation: HtmlPlanInvocation) => {
121
343
  const parsed = parseHtmlPlanInput(invocation?.rawInput)
122
344
  const task = parsed.task
123
345
  if (typeof commands.execute !== 'function') return { kind: 'error', text: '无法进入计划模式:官方 /plan 命令不可用' }
124
346
  const signal = invocation?.signal instanceof AbortSignal ? invocation.signal : new AbortController().signal
347
+
348
+ let prep: AttachmentPrep | null = null
349
+ try {
350
+ prep = await prepareAttachments(invocation, task)
351
+ } catch (error) {
352
+ prep = { slug: null, count: 0, lines: ['附件读取失败:' + messageOf(error)], rollback: async () => {} }
353
+ }
354
+
125
355
  try {
126
356
  const delegateNote = parsed.delegate === null ? '' : '\n' + (parsed.delegate ? HTML_PLAN_DELEGATE_INSTRUCTION : HTML_PLAN_SINGLE_AGENT_INSTRUCTION)
127
- const message = task ? instructionOf(task, parsed.delegate) : HTML_PLAN_BARE_INSTRUCTION + delegateNote
357
+ const extras: HtmlPlanInstructionExtras = { slug: prep?.slug ?? null, attachmentLines: prep?.lines ?? [] }
358
+ const message = task
359
+ ? instructionOf(task, parsed.delegate, extras)
360
+ : HTML_PLAN_BARE_INSTRUCTION + delegateNote + (prep?.lines.length ? '\n\n' + prep.lines.join('\n') : '')
128
361
  const execution = await commands.execute(invocation?.agent, '/plan ' + message, [], signal)
129
- if (!execution) return { kind: 'error', text: '无法进入计划模式:官方 /plan 命令不可用' }
362
+ if (!execution) {
363
+ await rollbackOf(prep)
364
+ return { kind: 'error', text: '无法进入计划模式:官方 /plan 命令不可用' }
365
+ }
130
366
  if (execution.result?.kind !== 'success') {
367
+ await rollbackOf(prep)
131
368
  return { kind: 'error', text: '无法进入计划模式:' + String(execution.result?.text ?? '未知原因') }
132
369
  }
133
- return { kind: 'success', text: task ? 'HTML 计划模式已开启:正在生成 HTML 计划页…' : 'HTML 计划模式已开启:请描述要规划的任务' }
370
+ const saved = prep && prep.count > 0 && prep.slug ? '(' + String(prep.count) + ' 个附件在 plans/' + prep.slug + '/assets/)' : ''
371
+ return { kind: 'success', text: (task ? 'HTML 计划模式已开启:正在生成 HTML 计划页…' : 'HTML 计划模式已开启:请描述要规划的任务') + saved }
134
372
  } catch (error) {
373
+ await rollbackOf(prep)
135
374
  return { kind: 'error', text: '无法进入计划模式:' + messageOf(error) }
136
375
  }
137
376
  },
@@ -159,7 +398,7 @@ export function installHtmlPlanCommand(ctx: Ctx, options: HtmlPlanCommandOptions
159
398
  log.warn('/html-plan 未注册:commands 服务不支持 register')
160
399
  return
161
400
  }
162
- const mount = (): unknown => commands.register!(htmlPlanCommandDefinition(commands, options))
401
+ const mount = (): unknown => commands.register!(htmlPlanCommandDefinition(commands, { ...options, hostCtx: sctx }))
163
402
  try {
164
403
  if (typeof commandCtx.effect === 'function') commandCtx.effect(mount, 'vscode-mode: html-plan command')
165
404
  else mount()