dsh-vscode-mode 0.30.0 → 0.31.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 (53) hide show
  1. package/README.md +54 -10
  2. package/lib/client.js +143 -52
  3. package/lib/client.js.map +1 -1
  4. package/lib/index.js +3549 -1465
  5. package/lib/index.js.map +1 -1
  6. package/package.json +1 -1
  7. package/skills/dsh-vscodemode-html-plan/LICENSE +202 -0
  8. package/skills/dsh-vscodemode-html-plan/SKILL.md +147 -0
  9. package/skills/dsh-vscodemode-html-plan/examples/scheduled-send.html +298 -0
  10. package/skills/dsh-vscodemode-html-plan/references/blocks.md +227 -0
  11. package/skills/dsh-vscodemode-html-plan/references/subagent-brief.md +17 -0
  12. package/skills/dsh-vscodemode-html-plan/references/upstream-SKILL.md +174 -0
  13. package/skills/dsh-vscodemode-html-plan/runtime/htmlplan.css +564 -0
  14. package/skills/dsh-vscodemode-html-plan/runtime/htmlplan.js +1299 -0
  15. package/skills/dsh-vscodemode-html-plan/runtime/pack.mjs +300 -0
  16. package/src/ai/llmTask.ts +178 -0
  17. package/src/ai/llmTypes.ts +6 -0
  18. package/src/ai/svnCommitMsg.ts +107 -0
  19. package/src/ai/svnTriage.ts +34 -85
  20. package/src/client/aiCommit.ts +57 -0
  21. package/src/client/htmlPlan/HtmlPlanPanel.ts +261 -0
  22. package/src/client/htmlPlan/planActions.ts +347 -0
  23. package/src/client/htmlPlan/planPage.ts +333 -0
  24. package/src/client/htmlPreview.ts +218 -0
  25. package/src/client/index.ts +8 -0
  26. package/src/client/officialSidebar.ts +11 -3
  27. package/src/client/planState.ts +8 -2
  28. package/src/client/sidebar/menuItems.ts +1 -0
  29. package/src/client/sidebar/panels/SvnPanel.ts +17 -0
  30. package/src/client/sidebar/types.ts +2 -0
  31. package/src/client/styles/editor.css +77 -0
  32. package/src/client/svnActions.ts +7 -0
  33. package/src/client/svnCommit.ts +109 -0
  34. package/src/client/svnNotice.ts +1 -1
  35. package/src/client/svnStatus.ts +5 -2
  36. package/src/client/ui/EditorView.ts +85 -7
  37. package/src/client/ui/McpSettings.ts +59 -0
  38. package/src/client/ui/SvnAiPlanDialog.ts +24 -4
  39. package/src/client/ui/SvnCommitDialog.ts +458 -0
  40. package/src/client/ui/commandCatalog.ts +11 -0
  41. package/src/client/ui/svnCommitModel.ts +204 -0
  42. package/src/fileOpenSettings.ts +113 -5
  43. package/src/htmlPlanCommand.ts +176 -0
  44. package/src/index.ts +4 -0
  45. package/src/shared/keybindings.ts +11 -0
  46. package/src/shared/rpc.ts +13 -4
  47. package/src/shared/svn.ts +191 -10
  48. package/src/shared/svnActions.ts +16 -0
  49. package/src/svn.ts +205 -47
  50. package/src/svnCommit.ts +348 -0
  51. package/src/svnCore.ts +254 -0
  52. package/src/svnToolJson.ts +73 -0
  53. package/src/svnTools.ts +566 -0
@@ -0,0 +1,348 @@
1
+ /**
2
+ * dsh-vscode-mode host — 原生提交(P4)+ 提交计划与最近提交信息(22-agent-tools-and-commit)。
3
+ *
4
+ * 为什么自建提交而不是继续跳 TortoiseProc:提交是提交前整理(changelist/勾选/自动 add·delete)
5
+ * 的终点,只有在本插件内执行才能保证「勾选了什么就提交什么」;Tortoise 对话框拿不到我们的勾选态。
6
+ *
7
+ * 关键纪律(对齐 svn-workflow 与远程项目的既有经验):
8
+ * - **先 status 重查**:客户端清单可能已过期,只提交仍处于变更态的路径,其余进 skipped;
9
+ * - **不分块**:提交分块会拆成多个 revision,超上限一律拒绝而不是半提交;
10
+ * - **中文日志**:UTF-8 临时文件 + §--encoding utf-8 -F§,避开 Windows GBK 控制台;
11
+ * - **不擅自解决冲突**:冲突路径单列并提示先更新,绝不顺带 resolve。
12
+ * @author ddj 2026年11月15号
13
+ */
14
+ import { mkdir, readFile, unlink, writeFile } from 'node:fs/promises'
15
+ import { tmpdir } from 'node:os'
16
+ import { join } from 'node:path'
17
+ import type { SvnChangeEntry, SvnCommitEntry, SvnCommitPlan, SvnCommitResult } from './shared/svn.js'
18
+ import { BATCH_PATHS_CAP, COMMIT_MSG_MAX, COMMIT_PATHS_CAP, SVN_READONLY_CODE } from './shared/svn.js'
19
+ import { commitResultOf } from './svnText.js'
20
+ import { classifySvnError } from './svnCore.js'
21
+ import { hashOf, userCacheDir } from './paths.js'
22
+
23
+ /** 提交子进程基础超时(大工作副本/慢网络留足预算;设置倍数再放大)。 */
24
+ export const COMMIT_GRACE_MS = 300_000
25
+ /** 自动 add/delete 子进程基础超时。 */
26
+ export const PREPARE_GRACE_MS = 120_000
27
+ /** 最近提交信息保留条数。 */
28
+ export const RECENT_MAX = 20
29
+ /** 最近提交信息单条上限(字符)。 */
30
+ export const RECENT_ITEM_MAX = 2000
31
+
32
+ /** 提交作用域(会话工作区 + 工作副本根)。 */
33
+ export interface SvnCommitScope {
34
+ /** 会话工作区目录。 */
35
+ cwd: string
36
+ /** 工作副本根(绝对路径)。 */
37
+ root: string
38
+ }
39
+
40
+ /** 提交模块依赖(由 svn.ts 注入,避免与 createSvnRpc 互相 import)。 */
41
+ export interface SvnCommitDeps {
42
+ /** svn 执行器(只读门禁在 svnCore,此处不再判)。 */
43
+ run: (cwd: string, argv: string[], graceMs: number, stdoutCap?: number, allowFallback?: boolean) => Promise<{ code: number | null; stdout: string; stderr: string }>
44
+ /** 会话 → 作用域(含「不受管理/无 CLI」错误文案)。 */
45
+ scopeOf: (sessionId?: string) => Promise<SvnCommitScope | { err: string }>
46
+ /** 变更清单读取(force = 强制重查)。 */
47
+ changesOf: (root: string, force?: boolean) => Promise<{ entries: SvnChangeEntry[]; truncated: boolean }>
48
+ /** 作废变更/状态缓存(提交与自动整理后必做)。 */
49
+ invalidate: (root: string) => void
50
+ /** 工作区相对路径 → svn 目标(越界返回 null)。 */
51
+ targetOf: (cwd: string, root: string, rel: string) => string | null
52
+ /** 只读是否开启(提交入口兜底;正常路径已被执行器拦截)。 */
53
+ readOnly: () => boolean
54
+ /** 提交前自动整理默认开关(请求未显式给出时生效;缺省按开启)。 */
55
+ defaults?: () => { autoAdd: boolean; autoDelete: boolean }
56
+ }
57
+
58
+ /** 提交请求(与 RPC 契约同形)。 */
59
+ export interface SvnCommitRequest {
60
+ sessionId?: string
61
+ paths: string[]
62
+ message: string
63
+ changelist?: string
64
+ keepLocks?: boolean
65
+ autoAdd?: boolean
66
+ autoDelete?: boolean
67
+ }
68
+
69
+ /** 提交计划结果。 */
70
+ export type SvnCommitPlanOutcome = { ok: true; plan: SvnCommitPlan } | { ok: false; error: string }
71
+
72
+ /** 提交结果(ok:false 带可读错误与可选拒绝码)。 */
73
+ export type SvnCommitOutcome =
74
+ | ({ ok: true } & SvnCommitResult)
75
+ | { ok: false; error: string; code?: string }
76
+
77
+ /** 提交动作字母 → 中文说明。 */
78
+ const ACTION_LABEL: Record<SvnCommitEntry['action'], string> = {
79
+ M: '已修改',
80
+ A: '已新增',
81
+ D: '已删除',
82
+ R: '已替换',
83
+ }
84
+
85
+ /** 提交输出里单文件动作行(英文 / 常见中文输出)。 */
86
+ const ENTRY_PATTERNS: Array<{ action: SvnCommitEntry['action']; re: RegExp }> = [
87
+ { action: 'M', re: /^(?:Sending|正在发送)\s+(.+)$/ },
88
+ { action: 'A', re: /^(?:Adding|正在添加)\s+(.+)$/ },
89
+ { action: 'D', re: /^(?:Deleting|正在删除)\s+(.+)$/ },
90
+ { action: 'R', re: /^(?:Replacing|正在替换)\s+(.+)$/ },
91
+ ]
92
+
93
+ /**
94
+ * 解析提交输出里的逐文件动作。
95
+ * @author ddj 2026年11月15号
96
+ * @param output 合并后的提交输出
97
+ * @returns 逐文件动作(保持输出顺序;无法识别的行忽略)
98
+ */
99
+ export function commitEntriesOf(output: string): SvnCommitEntry[] {
100
+ const entries: SvnCommitEntry[] = []
101
+ for (const raw of String(output ?? '').split(/\r?\n/)) {
102
+ const line = raw.trim()
103
+ if (!line) continue
104
+ for (const pattern of ENTRY_PATTERNS) {
105
+ const matched = pattern.re.exec(line)
106
+ if (!matched) continue
107
+ const path = matched[1].trim()
108
+ if (!path) continue
109
+ entries.push({ path, action: pattern.action, label: ACTION_LABEL[pattern.action] })
110
+ break
111
+ }
112
+ }
113
+ return entries
114
+ }
115
+
116
+ /**
117
+ * 提交信息校验(首行 → subject,其余 → body;总长受限)。
118
+ * @author ddj 2026年11月15号
119
+ * @param message 完整提交信息
120
+ * @returns 错误文案;合法为 null
121
+ */
122
+ export function messageErrorOf(message: string): string | null {
123
+ const text = String(message ?? '')
124
+ if (!text.trim()) return '提交信息不能为空'
125
+ if (text.length > COMMIT_MSG_MAX) return '提交信息最长 ' + COMMIT_MSG_MAX + ' 字符'
126
+ if (text.includes('\u0000')) return '提交信息包含非法字符'
127
+ return null
128
+ }
129
+
130
+ /**
131
+ * 最近提交信息文件路径(按工作副本根哈希隔离,与 sidecar 口径一致)。
132
+ * @author ddj 2026年11月15号
133
+ * @param root 工作副本根
134
+ * @returns 文件绝对路径
135
+ */
136
+ export function recentFileOf(root: string): string {
137
+ return join(userCacheDir(), 'svn-commit-msg', hashOf(root) + '.json')
138
+ }
139
+
140
+ /**
141
+ * 读取最近提交信息(缺失/损坏一律空表,不抛错)。
142
+ * @author ddj 2026年11月15号
143
+ * @param root 工作副本根
144
+ * @returns 提交信息列表(新→旧)
145
+ */
146
+ export async function readRecent(root: string): Promise<string[]> {
147
+ try {
148
+ const raw = await readFile(recentFileOf(root), 'utf8')
149
+ const parsed = JSON.parse(raw) as { messages?: unknown }
150
+ const list = Array.isArray(parsed?.messages) ? parsed.messages : []
151
+ return list.filter((item): item is string => typeof item === 'string' && item.trim().length > 0).slice(0, RECENT_MAX)
152
+ } catch {
153
+ return []
154
+ }
155
+ }
156
+
157
+ /**
158
+ * 追加最近提交信息(去重上浮、截断到上限;写盘失败不影响提交结果)。
159
+ * @author ddj 2026年11月15号
160
+ * @param root 工作副本根
161
+ * @param message 本次提交信息
162
+ */
163
+ export async function pushRecent(root: string, message: string): Promise<void> {
164
+ const trim = String(message ?? '').trim().slice(0, RECENT_ITEM_MAX)
165
+ if (!trim) return
166
+ try {
167
+ const previous = await readRecent(root)
168
+ const next = [trim, ...previous.filter((item) => item !== trim)].slice(0, RECENT_MAX)
169
+ const file = recentFileOf(root)
170
+ await mkdir(join(userCacheDir(), 'svn-commit-msg'), { recursive: true })
171
+ await writeFile(file, JSON.stringify({ messages: next }), 'utf8')
172
+ } catch {
173
+ /* 最近信息是便利功能,失败不影响提交 */
174
+ }
175
+ }
176
+
177
+ /**
178
+ * 创建提交能力(计划 + 执行)。
179
+ * @author ddj 2026年11月15号
180
+ * @param deps 依赖
181
+ * @returns 计划与提交方法
182
+ */
183
+ export function createSvnCommit(deps: SvnCommitDeps) {
184
+ /**
185
+ * 提交计划:变更清单 + 既有 changelist + 最近信息。
186
+ * @author ddj 2026年11月15号
187
+ * @param sessionId 会话 id
188
+ * @returns 计划或错误
189
+ */
190
+ async function planOf(sessionId?: string): Promise<SvnCommitPlanOutcome> {
191
+ const scope = await deps.scopeOf(sessionId)
192
+ if ('err' in scope) return { ok: false, error: scope.err }
193
+ try {
194
+ const changes = await deps.changesOf(scope.root, false)
195
+ const names = new Set<string>()
196
+ for (const entry of changes.entries) if (entry.changelist) names.add(entry.changelist)
197
+ return {
198
+ ok: true,
199
+ plan: {
200
+ entries: changes.entries,
201
+ changelists: [...names].sort((a, b) => a.localeCompare(b)),
202
+ recent: await readRecent(scope.root),
203
+ truncated: changes.truncated,
204
+ },
205
+ }
206
+ } catch (error) {
207
+ return { ok: false, error: '读取提交计划失败:' + String(error instanceof Error ? error.message : error) }
208
+ }
209
+ }
210
+
211
+ /**
212
+ * 提交已选路径:status 重查 → 自动整理 → commit → 解析 → 作废缓存。
213
+ * @author ddj 2026年11月15号
214
+ * @param request 提交请求
215
+ * @returns 提交结果
216
+ */
217
+ async function commitOf(request: SvnCommitRequest): Promise<SvnCommitOutcome> {
218
+ if (deps.readOnly()) return { ok: false, code: SVN_READONLY_CODE, error: '只读模式已开启:提交被拒绝(可在设置里关闭 svnReadOnly)' }
219
+ const messageError = messageErrorOf(request.message)
220
+ if (messageError) return { ok: false, error: messageError }
221
+ const requested = Array.isArray(request.paths) ? [...new Set(request.paths.map((item) => String(item ?? '').trim()).filter(Boolean))] : []
222
+ if (!requested.length) return { ok: false, error: '未选择任何文件' }
223
+ if (requested.length > COMMIT_PATHS_CAP) return { ok: false, error: '一次最多提交 ' + COMMIT_PATHS_CAP + ' 个路径(提交不分块,避免拆成多个版本)' }
224
+
225
+ const scope = await deps.scopeOf(request.sessionId)
226
+ if ('err' in scope) return { ok: false, error: scope.err }
227
+ // 闭包内 TS 不保留联合类型收窄,先落成局部常量
228
+ const scopeCwd = scope.cwd
229
+ const scopeRoot = scope.root
230
+
231
+ let changes: { entries: SvnChangeEntry[]; truncated: boolean }
232
+ try {
233
+ changes = await deps.changesOf(scope.root, true)
234
+ } catch (error) {
235
+ return { ok: false, error: '提交前状态重查失败:' + String(error instanceof Error ? error.message : error) }
236
+ }
237
+
238
+ const byPath = new Map<string, SvnChangeEntry>()
239
+ for (const entry of changes.entries) byPath.set(entry.path, entry)
240
+
241
+ const skipped: string[] = []
242
+ const conflicts: string[] = []
243
+ const addable: string[] = []
244
+ const deletable: string[] = []
245
+ const targets: string[] = []
246
+ const fallback = deps.defaults?.() ?? { autoAdd: true, autoDelete: true }
247
+ const autoAdd = request.autoAdd ?? fallback.autoAdd
248
+ const autoDelete = request.autoDelete ?? fallback.autoDelete
249
+
250
+ for (const path of requested) {
251
+ const entry = byPath.get(path)
252
+ if (!entry || (entry.status === 'normal' || entry.status === 'external')) { skipped.push(path); continue }
253
+ if (entry.status === 'ignored') { skipped.push(path); continue }
254
+ if (request.changelist && entry.changelist !== request.changelist) { skipped.push(path); continue }
255
+ if (entry.status === 'conflicted') { conflicts.push(path); continue }
256
+ if (entry.status === 'unversioned') {
257
+ if (!autoAdd) { skipped.push(path); continue }
258
+ addable.push(path)
259
+ continue
260
+ }
261
+ if (entry.status === 'missing') {
262
+ if (!autoDelete) { skipped.push(path); continue }
263
+ deletable.push(path)
264
+ continue
265
+ }
266
+ targets.push(path)
267
+ }
268
+
269
+ if (conflicts.length && !targets.length && !addable.length && !deletable.length) {
270
+ return { ok: false, error: '所选文件全部处于冲突状态:请先更新并解决冲突后再提交(' + conflicts.slice(0, 5).join('、') + ')' }
271
+ }
272
+ if (!targets.length && !addable.length && !deletable.length) {
273
+ return { ok: false, error: '所选文件均无待提交变更(可能已提交或已被还原)' }
274
+ }
275
+
276
+ /** @author ddj 2026年11月15号 @param verb 子命令 @param paths 相对路径 @returns 失败文案或 null */
277
+ async function prepare(verb: 'add' | 'delete', paths: readonly string[]): Promise<string | null> {
278
+ for (let start = 0; start < paths.length; start += BATCH_PATHS_CAP) {
279
+ const chunk = paths.slice(start, start + BATCH_PATHS_CAP)
280
+ const resolved = chunk.map((rel) => deps.targetOf(scopeCwd, scopeRoot, rel))
281
+ if (resolved.some((item) => item === null)) return '目标不在 SVN 工作副本内'
282
+ const outcome = await deps.run(scopeRoot, [verb, '--', ...resolved.map((item) => item as string)], PREPARE_GRACE_MS)
283
+ if (outcome.code !== 0) {
284
+ const info = classifySvnError([outcome.stderr, outcome.stdout].filter(Boolean).join('\n'))
285
+ return '自动 ' + verb + ' 失败:' + info.message
286
+ }
287
+ }
288
+ return null
289
+ }
290
+
291
+ const prepareError = await prepare('add', addable) ?? await prepare('delete', deletable)
292
+ if (prepareError) {
293
+ deps.invalidate(scope.root)
294
+ return { ok: false, error: prepareError }
295
+ }
296
+
297
+ const commitPaths = [...targets, ...addable, ...deletable]
298
+ const resolved = commitPaths.map((rel) => deps.targetOf(scope.cwd, scope.root, rel))
299
+ if (resolved.some((item) => item === null)) return { ok: false, error: '目标不在 SVN 工作副本内' }
300
+
301
+ const argv = ['commit', '--encoding', 'utf-8', '-F', '']
302
+ if (request.keepLocks) argv.push('--no-unlock')
303
+ if (request.changelist) argv.push('--changelist', request.changelist)
304
+ const messageFile = join(tmpdir(), 'dsh-vscode-commit-' + process.pid + '-' + Date.now() + '.txt')
305
+ let outcome: { code: number | null; stdout: string; stderr: string }
306
+ try {
307
+ await writeFile(messageFile, request.message.replace(/\r\n/g, '\n'), 'utf8')
308
+ argv[argv.indexOf('')] = messageFile
309
+ outcome = await deps.run(scope.root, [...argv, '--', ...resolved.map((item) => item as string)], COMMIT_GRACE_MS)
310
+ } catch (error) {
311
+ deps.invalidate(scope.root)
312
+ return { ok: false, error: '提交失败:' + String(error instanceof Error ? error.message : error) }
313
+ } finally {
314
+ try { await unlink(messageFile) } catch { /* 临时文件由系统清理,删除失败不影响结果 */ }
315
+ }
316
+
317
+ deps.invalidate(scope.root)
318
+ const parsed = commitResultOf(outcome.stdout, outcome.stderr, outcome.code, '提交')
319
+ const entries = commitEntriesOf(parsed.output)
320
+
321
+ if (outcome.code !== 0) {
322
+ let freshConflicts: string[] = []
323
+ try {
324
+ const fresh = await deps.changesOf(scope.root, true)
325
+ freshConflicts = fresh.entries.filter((entry) => entry.status === 'conflicted').map((entry) => entry.path)
326
+ } catch { /* 冲突补测失败就按原冲突清单 */ }
327
+ const info = classifySvnError(parsed.output)
328
+ const conflictPaths = [...new Set([...conflicts, ...freshConflicts])]
329
+ return {
330
+ ok: false,
331
+ error: '提交失败:' + (info.kind === 'conflict' ? info.message : parsed.output ? info.message : '未知错误') + (conflictPaths.length ? '(冲突:' + conflictPaths.slice(0, 5).join('、') + ')' : ''),
332
+ }
333
+ }
334
+
335
+ await pushRecent(scope.root, request.message)
336
+ const result: SvnCommitResult = {
337
+ summary: parsed.summary,
338
+ conflicts,
339
+ entries,
340
+ skipped,
341
+ output: parsed.output,
342
+ }
343
+ if (parsed.revision !== undefined) result.revision = parsed.revision
344
+ return { ok: true, ...result }
345
+ }
346
+
347
+ return { planOf, commitOf }
348
+ }
package/src/svnCore.ts ADDED
@@ -0,0 +1,254 @@
1
+ /**
2
+ * dsh-vscode-mode host — SVN 统一执行核心(22-agent-tools-and-commit)。
3
+ *
4
+ * 为什么单独成模块:原生提交、agent 工具与既有面板 RPC 必须共用**同一条**执行路径,
5
+ * 否则「只读门禁 / 超时倍数 / 操作数防注入 / 错误分类」会出现多份实现并各自漂移。
6
+ * 本模块只放执行与校验基元(无状态、依赖可注入、可单测);会话与工作副本作用域仍在 §src/svn.ts§。
7
+ *
8
+ * 与既有 §runSvn§ 的等价性(不改行为):argv 不经 shell、自动加 §--non-interactive§、
9
+ * stdin ignore、stdio 管道收集(spawn 级失败回退 inherit,输出降级为空)、graceMs 超时。
10
+ * 新增能力:只读门禁(写类子命令统一拒绝)、超时倍数、操作数 §-§ 前缀拒绝、连接错误分类。
11
+ * @author ddj 2026年11月15号
12
+ */
13
+ import type { Ctx } from './store.js'
14
+ import { SVN_CLI_DEFAULT, SVN_READONLY_CODE, SVN_READONLY_ERROR } from './shared/svn.js'
15
+
16
+ /** svn 子进程输出(与 svn.ts 的 SvnRunOutcome 同形)。 */
17
+ export interface SvnRunOutcome {
18
+ /** 退出码(null = 进程异常终止)。 */
19
+ code: number | null
20
+ /** 标准输出。 */
21
+ stdout: string
22
+ /** 标准错误。 */
23
+ stderr: string
24
+ }
25
+
26
+ /**
27
+ * 写类子命令字面量(命中即受只读门禁约束)。
28
+ * §export§ 计写(会落盘);§update§/§cleanup§ 计写(改工作副本);§changelist§ 计写(改工作副本元数据)。
29
+ */
30
+ export const SVN_WRITE_COMMANDS: ReadonlySet<string> = new Set([
31
+ 'add', 'delete', 'remove', 'rm', 'revert', 'commit', 'ci', 'update', 'up',
32
+ 'switch', 'sw', 'merge', 'propset', 'propdel', 'propedit', 'mkdir', 'copy', 'cp',
33
+ 'move', 'mv', 'import', 'export', 'cleanup', 'resolve', 'lock', 'unlock',
34
+ 'relocate', 'upgrade', 'changelist', 'patch',
35
+ ])
36
+
37
+ /** 只读模式拒绝错误:带稳定 code,工具层据此返回结构化失败。 */
38
+ export class SvnReadOnlyError extends Error {
39
+ /** 稳定拒绝码(§SVN_READONLY§)。 */
40
+ readonly code = SVN_READONLY_CODE
41
+
42
+ /** @author ddj 2026年11月15号 */
43
+ constructor() {
44
+ super(SVN_READONLY_CODE + ': ' + SVN_READONLY_ERROR)
45
+ this.name = 'SvnReadOnlyError'
46
+ }
47
+ }
48
+
49
+ /**
50
+ * 异常 → 结构化失败(只读拒绝带 code;其余 code 为空)。
51
+ * @author ddj 2026年11月15号
52
+ * @param error 捕获到的异常
53
+ * @returns code(可能为空)与可读文案
54
+ */
55
+ export function svnErrorOf(error: unknown): { code?: string; error: string } {
56
+ if (error instanceof SvnReadOnlyError) return { code: error.code, error: SVN_READONLY_ERROR }
57
+ const message = error instanceof Error ? error.message : String(error)
58
+ return { error: message }
59
+ }
60
+
61
+ /**
62
+ * 取 argv 里的子命令(跳过前置选项),小写。
63
+ * @author ddj 2026年11月15号
64
+ * @param argv 参数列表(不含可执行文件名)
65
+ * @returns 子命令字面量(空 argv 返回 '')
66
+ */
67
+ export function svnCommandOf(argv: readonly string[]): string {
68
+ for (const item of argv) {
69
+ if (typeof item === 'string' && item && item !== '--non-interactive') return item.toLowerCase()
70
+ }
71
+ return ''
72
+ }
73
+
74
+ /**
75
+ * argv 是否写类子命令。
76
+ * @author ddj 2026年11月15号
77
+ * @param argv 参数列表
78
+ * @returns 是否写
79
+ */
80
+ export function svnCommandIsWrite(argv: readonly string[]): boolean {
81
+ return SVN_WRITE_COMMANDS.has(svnCommandOf(argv))
82
+ }
83
+
84
+ /**
85
+ * 位置参数校验:拒 §-§ 开头(防 §--config-dir=§ 之类把 svn 变成外部程序执行)。
86
+ * @author ddj 2026年11月15号
87
+ * @param value 待校验值(属性名 / changelist 名 / URL / 分支路径等)
88
+ * @returns 错误文案;合法为 null
89
+ */
90
+ export function svnOperandErrorOf(value: unknown): string | null {
91
+ if (typeof value !== 'string') return '参数必须是字符串'
92
+ const trimmed = value.trim()
93
+ if (!trimmed) return '参数不能为空'
94
+ if (trimmed.startsWith('-')) return '参数不能以 - 开头(防被 svn 当成选项)'
95
+ return null
96
+ }
97
+
98
+ /**
99
+ * 超时倍数收敛(设置越界一律夹到 0.2–20,非数值按 1)。
100
+ * @author ddj 2026年11月15号
101
+ * @param scale 设置值
102
+ * @returns 可用倍数
103
+ */
104
+ export function svnScaleOf(scale: unknown): number {
105
+ const value = typeof scale === 'number' ? scale : Number(scale)
106
+ if (!Number.isFinite(value) || value <= 0) return 1
107
+ return Math.min(20, Math.max(0.2, value))
108
+ }
109
+
110
+ /**
111
+ * 按倍数放大命令超时。
112
+ * @author ddj 2026年11月15号
113
+ * @param baseMs 基础超时(毫秒)
114
+ * @param scale 设置倍数
115
+ * @returns 实际超时(毫秒)
116
+ */
117
+ export function svnGraceOf(baseMs: number, scale: unknown): number {
118
+ return Math.max(1_000, Math.round(baseMs * svnScaleOf(scale)))
119
+ }
120
+
121
+ /** 连接/权限类错误分类(用于把 svn 原始 stderr 变成可读文案)。 */
122
+ export type SvnErrorKind = 'offline' | 'no-repository' | 'auth' | 'conflict' | 'not-wc' | 'other'
123
+
124
+ /**
125
+ * svn 输出 → 错误分类与可读文案(不推断原因,只按已知错误码/短语映射)。
126
+ * @author ddj 2026年11月15号
127
+ * @param text 合并后的 stdout/stderr
128
+ * @returns 分类与文案
129
+ */
130
+ export function classifySvnError(text: string): { kind: SvnErrorKind; message: string } {
131
+ const raw = String(text ?? '').trim()
132
+ if (!raw) return { kind: 'other', message: 'svn 命令失败(无输出)' }
133
+ if (/E170013/.test(raw)) return { kind: 'offline', message: '服务器不可达(E170013):请检查网络、代理或版本库地址' }
134
+ if (/E210005/.test(raw)) return { kind: 'no-repository', message: '该 URL 已没有版本库(E210005):可能被改名、删除或停用' }
135
+ if (/E170001|E215004|authorization failed|认证失败/i.test(raw)) return { kind: 'auth', message: '认证失败:请检查凭据或缓存密码' }
136
+ if (/E155015|E155004|remains in conflict|冲突/.test(raw)) return { kind: 'conflict', message: '存在冲突或工作副本被锁:请先更新/解决冲突' }
137
+ if (/E155007|not a working copy|不是工作副本/i.test(raw)) return { kind: 'not-wc', message: '目标不是 SVN 工作副本(E155007)' }
138
+ return { kind: 'other', message: raw }
139
+ }
140
+
141
+ /** 执行器设置读取面(setupOpenSettings 提供;字段可缺省以兼容旧设置)。 */
142
+ export interface SvnRunnerSettings {
143
+ /** SVN 路径 / 只读 / 超时倍数。 */
144
+ svn: () => { svnPath: string; readOnly?: boolean; commandTimeoutScale?: number }
145
+ }
146
+
147
+ /** 执行器依赖(spawn 与 fs 解析可注入,便于单测)。 */
148
+ export interface SvnRunnerDeps {
149
+ /** host 上下文(取 fs 服务做路径规范化)。 */
150
+ ctx: Ctx
151
+ /** 设置读取面。 */
152
+ settings: SvnRunnerSettings
153
+ /** subprocess 服务取值(缺失返回 null)。 */
154
+ spawn: () => unknown
155
+ }
156
+
157
+ /** 执行器实例。 */
158
+ export interface SvnRunner {
159
+ /**
160
+ * 执行 svn(语义与既有 runSvn 一致)。
161
+ * @param cwd 运行目录(绝对路径)
162
+ * @param argv 参数(不含可执行文件名;自动加 --non-interactive)
163
+ * @param graceMs 基础超时(会乘设置倍数)
164
+ * @param stdoutCap stdout 收集上限
165
+ * @param allowFallback 管道失败时是否回退 inherit
166
+ * @returns 退出码与输出
167
+ */
168
+ run: (cwd: string, argv: string[], graceMs: number, stdoutCap?: number, allowFallback?: boolean) => Promise<SvnRunOutcome>
169
+ /** 只读是否开启。 */
170
+ readOnly: () => boolean
171
+ /** 当前超时倍数。 */
172
+ scale: () => number
173
+ }
174
+
175
+ /** 默认 stdout 收集上限(1MB,对齐既有 runSvn)。 */
176
+ const DEFAULT_STDOUT_CAP = 1 << 20
177
+
178
+ /**
179
+ * 创建 SVN 执行器(无状态除设置外)。
180
+ * @author ddj 2026年11月15号
181
+ * @param deps 依赖
182
+ * @returns 执行器
183
+ */
184
+ export function createSvnRunner(deps: SvnRunnerDeps): SvnRunner {
185
+ /** @author ddj 2026年11月15号 @returns 设置快照 */
186
+ function configuration() {
187
+ return deps.settings.svn()
188
+ }
189
+
190
+ /** @author ddj 2026年11月15号 @param argv 参数 @returns 是否只读拒绝 */
191
+ function blocked(argv: readonly string[]): boolean {
192
+ return svnCommandIsWrite(argv) && configuration().readOnly === true
193
+ }
194
+
195
+ /** @author ddj 2026年11月15号 @param cwd 运行目录 @returns 规范化后的绝对目录 */
196
+ async function resolveCwd(cwd: string): Promise<string> {
197
+ const fs = deps.ctx.get('fs') as
198
+ | { resolve?: (p: string, o: object) => Promise<unknown>; processPath?: (t: unknown) => string }
199
+ | null
200
+ | undefined
201
+ if (!fs?.resolve || !fs?.processPath) return cwd
202
+ return fs.processPath(await fs.resolve(cwd, {}))
203
+ }
204
+
205
+ /** @author ddj 2026年11月15号 @param cwd 运行目录 @param argv 参数 @param graceMs 超时 @param stdoutCap 上限 @param allowFallback 回退 @returns 结果 */
206
+ async function run(
207
+ cwd: string,
208
+ argv: string[],
209
+ graceMs: number,
210
+ stdoutCap = DEFAULT_STDOUT_CAP,
211
+ allowFallback = true,
212
+ ): Promise<SvnRunOutcome> {
213
+ if (blocked(argv)) throw new SvnReadOnlyError()
214
+ const spawn = deps.spawn() as
215
+ | ((options: unknown) => {
216
+ collected?: { stdout?: { readFrom: (at: number) => { text: string } }; stderr?: { readFrom: (at: number) => { text: string } } }
217
+ done: Promise<{ exitCode?: number | null; code?: number | null }>
218
+ })
219
+ | null
220
+ | undefined
221
+ if (!spawn) throw new Error('缺少 subprocess 服务')
222
+
223
+ const configured = configuration()
224
+ const exe = configured.svnPath.trim() || SVN_CLI_DEFAULT
225
+ const realCwd = await resolveCwd(cwd)
226
+ const timeout = svnGraceOf(graceMs, configured.commandTimeoutScale)
227
+ /** @author ddj 2026年11月15号 @param mode 收集模式 @returns 进程句柄 */
228
+ const attempt = (mode: 'pipe' | 'inherit') => spawn({
229
+ argv: [exe, '--non-interactive', ...argv],
230
+ cwd: realCwd,
231
+ stdio: mode === 'pipe'
232
+ ? { stdout: { maxBytes: stdoutCap }, stderr: { maxBytes: DEFAULT_STDOUT_CAP }, stdin: 'ignore' }
233
+ : { stdout: 'inherit', stderr: 'inherit', stdin: 'ignore' },
234
+ graceMs: timeout,
235
+ })
236
+ try {
237
+ const handle = attempt('pipe')
238
+ const outcome = await handle.done
239
+ return {
240
+ code: outcome?.exitCode ?? outcome?.code ?? null,
241
+ stdout: handle.collected?.stdout?.readFrom(0).text ?? '',
242
+ stderr: handle.collected?.stderr?.readFrom(0).text ?? '',
243
+ }
244
+ } catch (error) {
245
+ if (!allowFallback) throw error
246
+ // 受管环境管道 spawn EPERM:回退 inherit(只拿退出码,输出为空)
247
+ const handle = attempt('inherit')
248
+ const outcome = await handle.done
249
+ return { code: outcome?.exitCode ?? outcome?.code ?? null, stdout: '', stderr: '' }
250
+ }
251
+ }
252
+
253
+ return { run, readOnly: () => configuration().readOnly === true, scale: () => svnScaleOf(configuration().commandTimeoutScale) }
254
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * dsh-vscode-mode host — agent 工具输出归一(无损 JSON)。
3
+ *
4
+ * 为什么必须归一:DSH 0.2.x 的 dsh-tools 会用 snapshotJsonValue 快照每个工具结果,
5
+ * 只要出现 §undefined§ / NaN / 稀疏数组 / 非普通对象,**整次调用**就以
6
+ * "value is not lossless JSON" 失败——而 svn 的结构化载荷本来就有大量可选字段
7
+ * (未版本化条目没有 revision、不带 -v 的 log 没有 paths…),因此统一出口归一一次。
8
+ * @author ddj 2026年11月15号
9
+ */
10
+
11
+ /** 单字段字符串上限(超长截断并留标记)。 */
12
+ export const TOOL_FIELD_MAX = 8 * 1024
13
+
14
+ /** 单次工具输出总字节上限(防超大载荷拖慢会话)。 */
15
+ export const TOOL_TOTAL_MAX = 200 * 1024
16
+
17
+ /**
18
+ * 深度归一为无损 JSON 值:丢 undefined/函数/Symbol,NaN/Infinity → null,
19
+ * 数组空洞 → null,类实例 → 普通对象,循环引用 → null,字符串超长截断。
20
+ * @author ddj 2026年11月15号
21
+ * @param value 任意值
22
+ * @returns 可安全 JSON 序列化的值
23
+ */
24
+ /** 「丢弃该属性」哨兵(与 null 区分:undefined/函数如实省略,循环引用才补 null)。 */
25
+ const DROP = Symbol('drop')
26
+
27
+ export function toLosslessJson(value: unknown): unknown {
28
+ const seen = new WeakSet<object>()
29
+
30
+ /** @author ddj 2026年11月15号 @param input 任意值 @returns 归一值 */
31
+ function walk(input: unknown): unknown {
32
+ if (input === null) return null
33
+ const type = typeof input
34
+ if (type === 'string') return (input as string).length > TOOL_FIELD_MAX ? (input as string).slice(0, TOOL_FIELD_MAX) : input
35
+ if (type === 'number') return Number.isFinite(input as number) ? input : null
36
+ if (type === 'boolean') return input
37
+ if (type === 'undefined' || type === 'function' || type === 'symbol' || type === 'bigint') return DROP
38
+ if (type !== 'object') return null
39
+
40
+ const object = input as object
41
+ if (seen.has(object)) return null
42
+ seen.add(object)
43
+ if (Array.isArray(object)) {
44
+ const out: unknown[] = []
45
+ for (let i = 0; i < object.length; i++) {
46
+ const next = i in object ? walk(object[i]) : null
47
+ out.push(next === DROP ? null : next)
48
+ }
49
+ return out
50
+ }
51
+ const out: Record<string, unknown> = {}
52
+ for (const [key, item] of Object.entries(object as Record<string, unknown>)) {
53
+ const next = walk(item)
54
+ if (next === DROP) continue
55
+ out[key] = next
56
+ }
57
+ return out
58
+ }
59
+
60
+ return walk(value)
61
+ }
62
+
63
+ /**
64
+ * 工具结果 → 提供给模型的文本(无损 JSON + 总量截断)。
65
+ * @author ddj 2026年11月15号
66
+ * @param value 工具结果(任意形状)
67
+ * @returns JSON 文本(超总上限时附截断标记)
68
+ */
69
+ export function toolJsonText(value: unknown): string {
70
+ const json = JSON.stringify(toLosslessJson(value)) ?? 'null'
71
+ if (json.length <= TOOL_TOTAL_MAX) return json
72
+ return JSON.stringify({ ok: false, truncated: true, error: '工具输出超限(' + json.length + ' 字符),请缩小范围重试' })
73
+ }