dsh-vscode-mode 0.29.2 → 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 (80) hide show
  1. package/README.md +120 -11
  2. package/lib/client.js +178 -51
  3. package/lib/client.js.map +1 -1
  4. package/lib/index.js +4860 -1576
  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/compatSummary.ts +15 -0
  22. package/src/client/editorFlush.ts +55 -0
  23. package/src/client/featurePrefs.ts +63 -0
  24. package/src/client/htmlPlan/HtmlPlanPanel.ts +261 -0
  25. package/src/client/htmlPlan/planActions.ts +347 -0
  26. package/src/client/htmlPlan/planPage.ts +333 -0
  27. package/src/client/htmlPreview.ts +218 -0
  28. package/src/client/index.ts +43 -0
  29. package/src/client/monaco/loader.ts +71 -9
  30. package/src/client/monaco/templateLanguages.ts +300 -0
  31. package/src/client/officialSidebar.ts +16 -4
  32. package/src/client/openPathRouter.ts +7 -0
  33. package/src/client/planState.ts +8 -2
  34. package/src/client/refCopy.ts +70 -0
  35. package/src/client/refIntake.ts +215 -0
  36. package/src/client/sidebar/menuItems.ts +11 -0
  37. package/src/client/sidebar/panels/FileExplorer.ts +11 -0
  38. package/src/client/sidebar/panels/SearchPanel.ts +214 -4
  39. package/src/client/sidebar/panels/SvnPanel.ts +17 -0
  40. package/src/client/sidebar/types.ts +2 -0
  41. package/src/client/styles/editor.css +112 -0
  42. package/src/client/svnActions.ts +7 -0
  43. package/src/client/svnCommit.ts +109 -0
  44. package/src/client/svnNotice.ts +1 -1
  45. package/src/client/svnStatus.ts +5 -2
  46. package/src/client/ui/DiffLauncher.ts +3 -1
  47. package/src/client/ui/EditorView.ts +221 -14
  48. package/src/client/ui/McpSettings.ts +108 -1
  49. package/src/client/ui/SvnAiPlanDialog.ts +24 -4
  50. package/src/client/ui/SvnCommitDialog.ts +458 -0
  51. package/src/client/ui/commandCatalog.ts +11 -0
  52. package/src/client/ui/svnCommitModel.ts +204 -0
  53. package/src/client/univer/UniverCacheSettings.ts +75 -0
  54. package/src/client/univer/UniverHost.ts +177 -0
  55. package/src/client/univer/api.ts +30 -0
  56. package/src/client/univer/routing.ts +32 -0
  57. package/src/client/univer/store.ts +111 -0
  58. package/src/fileOpenSettings.ts +118 -6
  59. package/src/htmlPlanCommand.ts +176 -0
  60. package/src/index.ts +4 -0
  61. package/src/paths.ts +5 -0
  62. package/src/refPointer.ts +193 -0
  63. package/src/rpc.ts +51 -0
  64. package/src/search/replacePlan.ts +144 -0
  65. package/src/search/replaceRun.ts +289 -0
  66. package/src/shared/keybindings.ts +11 -0
  67. package/src/shared/refSyntax.ts +106 -0
  68. package/src/shared/rpc.ts +28 -4
  69. package/src/shared/snippets.ts +17 -0
  70. package/src/shared/svn.ts +191 -10
  71. package/src/shared/svnActions.ts +16 -0
  72. package/src/shared/univer.ts +90 -0
  73. package/src/svn.ts +205 -47
  74. package/src/svnCommit.ts +348 -0
  75. package/src/svnCore.ts +254 -0
  76. package/src/svnToolJson.ts +73 -0
  77. package/src/svnTools.ts +566 -0
  78. package/src/univerBridge.ts +83 -0
  79. package/src/univerCache.ts +205 -0
  80. package/src/univerRpc.ts +144 -0
@@ -0,0 +1,144 @@
1
+ /**
2
+ * dsh-vscode-mode host — 全局替换的纯逻辑:模式编译、空匹配拒绝、逐行替换与计数。
3
+ *
4
+ * 为什么按「行」而不是整段正则:
5
+ * 1. 编辑器里的搜索是行感知的(`^`/`$` 在行首行尾生效、`.` 不跨行),替换必须同语义;
6
+ * 2. CRLF 文件按行拆分后能原样拼回,不会把 `\r\n` 洗成 `\n`;
7
+ * 3. 命中跨行结构的需求可以用正则里的 `\n` 表达,但只能是用户显式写出。
8
+ *
9
+ * 纯函数,不碰 fs / ctx,便于单测与事后复查破坏性行为。
10
+ * @author ddj 2026年11月15号
11
+ */
12
+
13
+ /** 替换请求(与 RPC 入参同形)。 */
14
+ export interface ReplaceQuery {
15
+ query: string
16
+ replacement: string
17
+ regex?: boolean
18
+ matchCase?: boolean
19
+ wholeWord?: boolean
20
+ }
21
+
22
+ /** 编译后的替换模式。 */
23
+ export interface CompiledReplace {
24
+ pattern: RegExp
25
+ regex: boolean
26
+ replacement: string
27
+ }
28
+
29
+ /** 正则源码长度上限:防止把超长串当正则编译(ReDoS 面与内存面都收窄)。 */
30
+ export const MAX_PATTERN_LENGTH = 4000
31
+
32
+ /**
33
+ * 转义正则元字符(字面量模式用)。
34
+ * @author ddj 2026年11月15号
35
+ * @param text 原始文本
36
+ * @returns 可安全嵌入正则的文本
37
+ */
38
+ export function escapeRegExp(text: string): string {
39
+ return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
40
+ }
41
+
42
+ /**
43
+ * 判断模式能否匹配空字符串(`a*`、`(?:)`、`x?` 等)。
44
+ *
45
+ * 这类模式在替换时会在每个字符间隙插入替换文本,破坏文件;发现即拒绝。
46
+ * @author ddj 2026年11月15号
47
+ * @param pattern 已编译模式(可带任意 flags)
48
+ * @returns 是否可能匹配空串
49
+ */
50
+ export function hasEmptyMatch(pattern: RegExp): boolean {
51
+ const flags = pattern.flags.includes('g') ? pattern.flags : pattern.flags + 'g'
52
+ const probe = new RegExp(pattern.source, flags)
53
+ for (const sample of ['', 'a', 'ab', ' ', '\n']) {
54
+ probe.lastIndex = 0
55
+ const match = probe.exec(sample)
56
+ if (match !== null && match[0] === '') return true
57
+ }
58
+ return false
59
+ }
60
+
61
+ /**
62
+ * 编译替换模式(字面量模式转义;正则模式支持分组 `$1`)。
63
+ * @author ddj 2026年11月15号
64
+ * @param input 替换请求
65
+ * @returns 编译结果
66
+ * @throws 查询为空 / 正则无效 / 可匹配空串
67
+ */
68
+ export function compileReplace(input: ReplaceQuery): CompiledReplace {
69
+ const query = String(input.query ?? '')
70
+ if (query === '') throw new Error('请先输入要查找的内容')
71
+ if (query.length > MAX_PATTERN_LENGTH) throw new Error('查找内容过长(超过 ' + MAX_PATTERN_LENGTH + ' 字符)')
72
+ const regex = input.regex === true
73
+ const body = regex ? query : escapeRegExp(query)
74
+ const wrapped = input.wholeWord === true ? '\\b(?:' + body + ')\\b' : (regex ? '(?:' + body + ')' : body)
75
+ let pattern: RegExp
76
+ try {
77
+ pattern = new RegExp(wrapped, input.matchCase === true ? 'g' : 'gi')
78
+ } catch (error) {
79
+ throw new Error('正则表达式无效:' + (error instanceof Error ? error.message : String(error)))
80
+ }
81
+ if (hasEmptyMatch(pattern)) throw new Error('该查询可以匹配空字符串(例如 a*),替换会破坏文件,已拒绝')
82
+ return { pattern, regex, replacement: String(input.replacement ?? '') }
83
+ }
84
+
85
+ /**
86
+ * 统计一行内的命中数(用独立副本,避免污染调用方 lastIndex)。
87
+ * @author ddj 2026年11月15号
88
+ * @param line 单行文本
89
+ * @param pattern 已编译模式
90
+ * @returns 命中次数
91
+ */
92
+ export function countInLine(line: string, pattern: RegExp): number {
93
+ if (line === '') return 0
94
+ const flags = pattern.flags.includes('g') ? pattern.flags : pattern.flags + 'g'
95
+ const probe = new RegExp(pattern.source, flags)
96
+ let total = 0
97
+ for (const matched of line.matchAll(probe)) {
98
+ if (matched[0] !== '') total += 1
99
+ }
100
+ return total
101
+ }
102
+
103
+ /**
104
+ * 逐行替换(保留行尾与 BOM;只改写确实变化的行)。
105
+ * @author ddj 2026年11月15号
106
+ * @param text 文件全文
107
+ * @param compiled 编译后的模式
108
+ * @returns 新文本与替换次数
109
+ */
110
+ export function replaceInText(text: string, compiled: CompiledReplace): { text: string; count: number } {
111
+ if (text === '') return { text, count: 0 }
112
+ const bom = text.startsWith('\uFEFF') ? '\uFEFF' : ''
113
+ const body = bom ? text.slice(1) : text
114
+ // 保留分隔符的拆分:奇数下标是行尾,偶数下标是行内容
115
+ const parts = body.split(/(\r\n|\r|\n)/)
116
+ const replacement = compiled.replacement
117
+ let count = 0
118
+ for (let index = 0; index < parts.length; index += 2) {
119
+ const line = parts[index]
120
+ const hits = countInLine(line, compiled.pattern)
121
+ if (hits === 0) continue
122
+ // 字面量模式用函数替换,保证用户输入的 `$` 不被解释成分组引用
123
+ parts[index] = compiled.regex ? line.replace(compiled.pattern, replacement) : line.replace(compiled.pattern, () => replacement)
124
+ count += hits
125
+ }
126
+ if (count === 0) return { text, count: 0 }
127
+ return { text: bom + parts.join(''), count }
128
+ }
129
+
130
+ /**
131
+ * 统计全文命中数(dryRun 预览用;与 replaceInText 同语义)。
132
+ * @author ddj 2026年11月15号
133
+ * @param text 文件全文
134
+ * @param compiled 编译后的模式
135
+ * @returns 命中次数
136
+ */
137
+ export function countInText(text: string, compiled: CompiledReplace): number {
138
+ if (text === '') return 0
139
+ const body = text.startsWith('\uFEFF') ? text.slice(1) : text
140
+ const parts = body.split(/(\r\n|\r|\n)/)
141
+ let total = 0
142
+ for (let index = 0; index < parts.length; index += 2) total += countInLine(parts[index], compiled.pattern)
143
+ return total
144
+ }
@@ -0,0 +1,289 @@
1
+ /**
2
+ * dsh-vscode-mode host — 全局替换执行层(候选枚举 + 逐文件守卫写入)。
3
+ *
4
+ * 安全边界:
5
+ * 1. 候选文件由 ripgrep `--files-with-matches` 枚举(复用搜索面板同一套排除/包含 glob),
6
+ * 不自己遍历目录树;显式 `paths` 只用于「单文件替换」。
7
+ * 2. 每个文件都按 `stat.version` 做 `replaceIfVersion` 守卫写入:写盘瞬间文件被外部改过
8
+ * 就记为该文件冲突并继续,不覆盖别人的改动。
9
+ * 3. 单文件 > 8MB、含 NUL 的二进制、非普通文件一律跳过并计入 skipped。
10
+ * 4. `dryRun` 只统计不写盘(确认弹窗用),语义与真实执行完全同源(同一套 replaceInText)。
11
+ *
12
+ * @author ddj 2026年11月15号
13
+ */
14
+ import { relative } from 'node:path'
15
+ import type { Ctx, Session } from '../store.js'
16
+ import { policyOf, resolveTarget } from '../store.js'
17
+ import { invalidateIndex } from '../treeIndex.js'
18
+ import { EXCLUDES, FILE_EXCLUDES, readStderr, rgExitFailure, ripgrepPath, searchRoot } from './ripgrep.js'
19
+ import { compileReplace, countInText, replaceInText } from './replacePlan.js'
20
+ import type { ReplaceQuery } from './replacePlan.js'
21
+
22
+ /** 单次替换最多处理的文件数(超出截断并提示)。 */
23
+ export const MAX_REPLACE_FILES = 200
24
+ /** 单文件大小上限(与 host 读文本上限一致)。 */
25
+ export const MAX_REPLACE_FILE_BYTES = 8 * 1024 * 1024
26
+ /** ripgrep 输出上限(候选路径列表,200 条接口上限远小于此)。 */
27
+ const STDOUT_CAP = 2 << 20
28
+ const STDERR_CAP = 64 << 10
29
+ const GRACE_MS = 20_000
30
+
31
+ /** 替换请求(RPC 入参)。 */
32
+ export interface ReplaceRequest extends ReplaceQuery {
33
+ include?: string[]
34
+ exclude?: string[]
35
+ paths?: string[]
36
+ dryRun?: boolean
37
+ }
38
+
39
+ /** 单个文件的替换结果。 */
40
+ export interface ReplaceFileChange {
41
+ path: string
42
+ replaced: number
43
+ }
44
+
45
+ /** 替换汇总。 */
46
+ export interface ReplaceOutcome {
47
+ files: ReplaceFileChange[]
48
+ totalFiles: number
49
+ totalReplaced: number
50
+ truncated: boolean
51
+ dryRun: boolean
52
+ skipped: number
53
+ failed: Array<{ path: string; reason: string }>
54
+ warning?: string
55
+ }
56
+
57
+ /** 执行输入。 */
58
+ export interface ReplaceRunInput {
59
+ ctx: Ctx
60
+ session: Session
61
+ /** 会话工作区目录(invalidateIndex 的索引键)。 */
62
+ cwd: string
63
+ request: ReplaceRequest
64
+ signal?: AbortSignal
65
+ }
66
+
67
+ interface SpawnHandle {
68
+ done: Promise<{ exitCode: number | null; code?: number | null }>
69
+ collected?: {
70
+ stdout?: { readFrom(offset: number): { text: string; lossy?: boolean } }
71
+ stderr?: { readFrom(offset: number): { text: string } }
72
+ }
73
+ }
74
+
75
+ interface SpawnService {
76
+ spawn(spec: {
77
+ argv: readonly string[]
78
+ cwd: string
79
+ stdio: { stdin: 'ignore'; stdout: { maxBytes: number }; stderr: { maxBytes: number } }
80
+ graceMs: number
81
+ signal?: AbortSignal
82
+ }): SpawnHandle
83
+ }
84
+
85
+ /**
86
+ * 构造「列出含命中文件」的 rg argv(与内容搜索同一套过滤口径)。
87
+ * @author ddj 2026年11月15号
88
+ * @param binary rg 路径
89
+ * @param root 搜索根目录
90
+ * @param request 替换请求
91
+ * @returns argv 数组
92
+ */
93
+ export function matchedFilesArgv(binary: string, root: string, request: ReplaceRequest): string[] {
94
+ const argv = [binary, '--no-config', '--files-with-matches', '--hidden', '--no-ignore']
95
+ argv.push(request.matchCase === true ? '--case-sensitive' : '--ignore-case')
96
+ if (request.wholeWord === true) argv.push('--word-regexp')
97
+ if (request.regex !== true) argv.push('--fixed-strings')
98
+ for (const excluded of EXCLUDES) argv.push('--glob', '!**/' + excluded + '/**')
99
+ for (const excluded of FILE_EXCLUDES) argv.push('--glob', '!' + excluded)
100
+ for (const pattern of request.include ?? []) {
101
+ const glob = String(pattern).trim()
102
+ if (glob) argv.push('--glob', glob)
103
+ }
104
+ for (const pattern of request.exclude ?? []) {
105
+ const glob = String(pattern).trim()
106
+ if (glob) argv.push('--glob', '!' + glob)
107
+ }
108
+ argv.push('--', request.query, root)
109
+ return argv
110
+ }
111
+
112
+ /**
113
+ * 把 rg 输出的执行世界路径还原成工作区相对路径(统一 `/` 分隔)。
114
+ * @author ddj 2026年11月15号
115
+ * @param root 搜索根(执行世界路径)
116
+ * @param candidate rg 输出的一行路径
117
+ * @returns 相对路径;无法还原时返回空串
118
+ */
119
+ export function relativeCandidate(root: string, candidate: string): string {
120
+ const text = String(candidate ?? '').trim()
121
+ if (!text) return ''
122
+ const rel = relative(root, text).split('\\').join('/')
123
+ if (rel === '' || rel.startsWith('../')) return ''
124
+ return rel
125
+ }
126
+
127
+ /**
128
+ * 需求:显式 paths 时直接用;否则用 rg 枚举含命中文件(有界)。
129
+ * @author ddj 2026年11月15号
130
+ * @param input 执行输入
131
+ * @returns 相对路径列表与截断标记
132
+ */
133
+ async function listCandidates(input: ReplaceRunInput): Promise<{ files: string[]; truncated: boolean; warning?: string }> {
134
+ const explicit = (input.request.paths ?? []).map((path) => String(path ?? '').trim()).filter(Boolean)
135
+ if (explicit.length > 0) {
136
+ const unique = [...new Set(explicit)]
137
+ return { files: unique.slice(0, MAX_REPLACE_FILES), truncated: unique.length > MAX_REPLACE_FILES }
138
+ }
139
+
140
+ const sub = input.ctx.get('subprocess') as SpawnService | undefined
141
+ const binary = ripgrepPath()
142
+ if (!sub || !binary) throw new Error('替换需要 ripgrep,但当前环境不可用')
143
+ const root = await searchRoot(input.ctx, input.session)
144
+ const handle = sub.spawn({
145
+ argv: matchedFilesArgv(binary, root, input.request),
146
+ cwd: root,
147
+ stdio: { stdin: 'ignore', stdout: { maxBytes: STDOUT_CAP }, stderr: { maxBytes: STDERR_CAP } },
148
+ graceMs: GRACE_MS,
149
+ signal: input.signal,
150
+ })
151
+ let outcome: { exitCode: number | null; code?: number | null }
152
+ try {
153
+ outcome = await handle.done
154
+ } catch (error) {
155
+ throw new Error('ripgrep 启动失败:' + String(error))
156
+ }
157
+ const code = outcome.exitCode ?? outcome.code
158
+ let warning: string | undefined
159
+ if (code !== 0 && code !== 1) {
160
+ const failure = rgExitFailure(code, readStderr(handle).text)
161
+ if (failure.kind !== 'partial') throw new Error(failure.message)
162
+ warning = failure.message
163
+ }
164
+ const reader = handle.collected?.stdout
165
+ if (!reader) throw new Error('ripgrep stdout 不可用')
166
+ const output = reader.readFrom(0)
167
+ const rels = output.text.split(/\r?\n/).map((line) => relativeCandidate(root, line)).filter(Boolean)
168
+ const unique = [...new Set(rels)]
169
+ return { files: unique.slice(0, MAX_REPLACE_FILES), truncated: Boolean(output.lossy) || unique.length > MAX_REPLACE_FILES, warning }
170
+ }
171
+
172
+ /**
173
+ * 单文件替换(读 → 校验 → 版本守卫写入)。
174
+ * @author ddj 2026年11月15号
175
+ * @param input 执行输入
176
+ * @param relativePath 工作区相对路径
177
+ * @param compiled 编译后的模式
178
+ * @returns 该文件结果;跳过与失败通过 outcome 字段表达
179
+ */
180
+ async function replaceOneFile(
181
+ input: ReplaceRunInput,
182
+ relativePath: string,
183
+ compiled: ReturnType<typeof compileReplace>,
184
+ ): Promise<{ replaced: number; skipped: boolean; reason?: string }> {
185
+ const fs = input.ctx.get('fs')
186
+ if (!fs) throw new Error('缺少 fs')
187
+ const target = await resolveTarget(input.ctx, input.session, relativePath)
188
+ const info = await fs.stat(target)
189
+ if (!info || info.type !== 'file') return { replaced: 0, skipped: true, reason: '不是普通文件' }
190
+ if (Number(info.size ?? 0) > MAX_REPLACE_FILE_BYTES) return { replaced: 0, skipped: true, reason: '文件过大(>8MB)' }
191
+
192
+ const text = await fs.readText(target)
193
+ if (typeof text !== 'string' || text.includes('\u0000')) return { replaced: 0, skipped: true, reason: '二进制文件' }
194
+ const count = countInText(text, compiled)
195
+ if (count === 0) return { replaced: 0, skipped: false }
196
+ if (input.request.dryRun === true) return { replaced: count, skipped: false }
197
+
198
+ const { text: next, count: replaced } = replaceInText(text, compiled)
199
+ if (replaced === 0) return { replaced: 0, skipped: false }
200
+ // BOM 可能已被读文本通道剥掉(UTF-8 BOM 在解码时常见地消失):按原始字节判断并在写回时补回,
201
+ // 否则替换会悄悄把带 BOM 的文件变成无 BOM(对依赖 BOM 构建/解析的工具是破坏性改动)。
202
+ const raw = await readRawPrefix(fs, target)
203
+ const hasBom = isBom(raw) || next.startsWith('\uFEFF')
204
+ const payload = hasBom && !next.startsWith('\uFEFF') ? '\uFEFF' + next : next
205
+ const intent = info.version ? { kind: 'replaceIfVersion', version: info.version } : undefined
206
+ await fs.writeText(target, payload, intent, undefined, policyOf(input.ctx, input.session))
207
+ // 目录树缓存失效是 best effort:索引不可用时不能把已经成功的写盘报成失败
208
+ try { invalidateIndex(input.ctx, input.cwd, relativePath) } catch (error) { /* 索引失效失败不影响替换结果 */ }
209
+ return { replaced, skipped: false }
210
+ }
211
+
212
+ /**
213
+ * 执行替换(dryRun 只统计)。
214
+ * @author ddj 2026年11月15号
215
+ * @param input 执行输入
216
+ * @returns 汇总结果
217
+ */
218
+ export async function runReplace(input: ReplaceRunInput): Promise<ReplaceOutcome> {
219
+ const compiled = compileReplace(input.request)
220
+ const candidates = await listCandidates(input)
221
+ const outcome: ReplaceOutcome = {
222
+ files: [],
223
+ totalFiles: 0,
224
+ totalReplaced: 0,
225
+ truncated: candidates.truncated,
226
+ dryRun: input.request.dryRun === true,
227
+ skipped: 0,
228
+ failed: [],
229
+ ...(candidates.warning ? { warning: candidates.warning } : {}),
230
+ }
231
+ for (const relativePath of candidates.files) {
232
+ if (input.signal?.aborted === true) {
233
+ outcome.warning = '替换已取消'
234
+ break
235
+ }
236
+ try {
237
+ const result = await replaceOneFile(input, relativePath, compiled)
238
+ if (result.skipped) { outcome.skipped += 1; continue }
239
+ if (result.replaced === 0) continue
240
+ outcome.files.push({ path: relativePath, replaced: result.replaced })
241
+ outcome.totalFiles += 1
242
+ outcome.totalReplaced += result.replaced
243
+ } catch (error) {
244
+ outcome.failed.push({ path: relativePath, reason: describeFailure(error) })
245
+ }
246
+ }
247
+ return outcome
248
+ }
249
+
250
+ /**
251
+ * 读原始字节前缀(用于 BOM 判断;读取失败时返回 null,不阻塞替换)。
252
+ * @author ddj 2026年11月15号
253
+ * @param fs 文件服务
254
+ * @param target 解析后的目标
255
+ * @returns 原始字节或 null
256
+ */
257
+ async function readRawPrefix(fs: any, target: unknown): Promise<unknown> {
258
+ if (typeof fs?.readBytes !== 'function') return null
259
+ try {
260
+ return await fs.readBytes(target, undefined, MAX_REPLACE_FILE_BYTES)
261
+ } catch (error) {
262
+ return null
263
+ }
264
+ }
265
+
266
+ /**
267
+ * 判断字节序列是否以 UTF-8 BOM 开头。
268
+ * @author ddj 2026年11月15号
269
+ * @param bytes 文件原始字节
270
+ * @returns 是否带 BOM
271
+ */
272
+ export function isBom(bytes: unknown): boolean {
273
+ const view = bytes as { length?: number; [index: number]: number } | null
274
+ if (!view || typeof view.length !== 'number' || view.length < 3) return false
275
+ return view[0] === 0xef && view[1] === 0xbb && view[2] === 0xbf
276
+ }
277
+
278
+ /**
279
+ * 失败原因归一(版本冲突给可读提示,其余保留原始消息)。
280
+ * @author ddj 2026年11月15号
281
+ * @param error 捕获的异常
282
+ * @returns 可读原因
283
+ */
284
+ export function describeFailure(error: unknown): string {
285
+ const source = error as { code?: unknown; message?: unknown } | null
286
+ const message = typeof source?.message === 'string' ? source.message : String(error)
287
+ if (source?.code === 'FS_STALE_VERSION' || message.includes('changed since it was read')) return '文件在替换期间被修改,已跳过'
288
+ return message.length > 300 ? message.slice(0, 300) + '…' : message
289
+ }
@@ -22,6 +22,9 @@ export const KEYBINDING_DEFAULTS: Record<string, string> = {
22
22
  // Markdown 预览切换:VS Code 同款 (Ctrl+K V 为分栏,此处取单键 Ctrl+Shift+V)。
23
23
  // 仅当活动文件是 .md 时才吞键,其余情况放行给浏览器/输入框(保留「粘贴为纯文本」语义)。
24
24
  'edrv.toggleMarkdownPreview': 'Ctrl+Shift+V',
25
+ // HTML 网页预览:交给官方 HTML 渲染器,Ctrl+Alt+V 与 Markdown 预览分工。
26
+ // 仅当活动文件是 .html/.htm 且官方渲染器可用时才吞键,其余情况放行。
27
+ 'edrv.previewHtml': 'Ctrl+Alt+V',
25
28
  'edrv.navigateBack': 'Alt+ArrowLeft|Ctrl+Alt+-',
26
29
  'edrv.navigateForward': 'Alt+ArrowRight|Ctrl+Shift+-',
27
30
  // 页签循环:主候选避开浏览器保留键(Ctrl+Tab / Ctrl+PgUp/PgDn 会被浏览器截获)
@@ -250,6 +253,14 @@ export const SHORTCUT_PROFILES: Record<string, ShortcutProfiles> = {
250
253
  'web:macos': bind('KeyV', ['primary', 'shift']),
251
254
  'web:windows': bind('KeyV', ['primary', 'shift']),
252
255
  },
256
+ // HTML 预览用 primary+alt+KeyV:避开 Markdown 的 primary+shift+V;
257
+ // linux 的 primary+KeyV 属官方保留键,两个 linux profile 都不声明(用户可自设)。
258
+ 'edrv.previewHtml': {
259
+ 'desktop:macos': bind('KeyV', ['primary', 'alt']),
260
+ 'desktop:windows': bind('KeyV', ['primary', 'alt']),
261
+ 'web:macos': bind('KeyV', ['primary', 'alt']),
262
+ 'web:windows': bind('KeyV', ['primary', 'alt']),
263
+ },
253
264
  // 导航历史:主候选 Alt+Arrow 在 linux/web 为保留或白名单外;web 取第二候选(Ctrl+Alt+- / Ctrl+Shift+-)
254
265
  'edrv.navigateBack': {
255
266
  'desktop:macos': bind('ArrowLeft', ['alt']),
@@ -0,0 +1,106 @@
1
+ /**
2
+ * dsh-vscode-mode — 会话引用语法(`@相对路径 Lx-Ly`)的解析与格式化。
3
+ *
4
+ * 双面共享(client 复制/粘贴/拖拽拦截 + host 无关),故放在 shared 且不引入 node/react。
5
+ *
6
+ * 语义(与 VS Code「复制行引用/添加选区到对话」对齐):
7
+ * - 路径统一 `/` 分隔、相对工作区;
8
+ * - 行区间后缀 `L12`(单行)或 `L12-L20`(多行),只有存在真实行范围时才带;
9
+ * - 复制拦截规则:跨行选区一律算引用;单行只有**整行选中**才算(否则普通复制)。
10
+ *
11
+ * @author ddj 2026年11月15号
12
+ */
13
+
14
+ /** 引用行范围(1-based,闭区间)。 */
15
+ export interface RefRange {
16
+ startLine: number
17
+ endLine: number
18
+ }
19
+
20
+ /** 解析结果。 */
21
+ export interface ParsedRef {
22
+ path: string
23
+ range?: RefRange
24
+ }
25
+
26
+ /** 引用文本正则:`@path` 或 `@path L3-L5`;路径可加引号以容纳空格。 */
27
+ const REF_PATTERN = /^\s*@?(?:"([^"]+)"|(\S+?))(?:\s+L(\d+)(?:-L?(\d+))?)?\s*$/
28
+
29
+ /**
30
+ * 路径归一:反斜杠转 `/`、去掉前导 `./` 与 `@`。
31
+ * @author ddj 2026年11月15号
32
+ * @param path 原始路径
33
+ * @returns 归一后的相对路径
34
+ */
35
+ export function normalizeRefPath(path: string): string {
36
+ let text = String(path ?? '').trim().split('\\').join('/')
37
+ if (text.startsWith('@')) text = text.slice(1)
38
+ while (text.startsWith('./')) text = text.slice(2)
39
+ return text
40
+ }
41
+
42
+ /**
43
+ * 格式化引用文本。
44
+ * @author ddj 2026年11月15号
45
+ * @param path 工作区相对路径
46
+ * @param range 行范围(可空)
47
+ * @returns `@path` / `@path L3` / `@path L3-L5`
48
+ */
49
+ export function formatRef(path: string, range?: RefRange | null): string {
50
+ const relative = normalizeRefPath(path)
51
+ if (!relative) return ''
52
+ if (!range || !Number.isFinite(range.startLine)) return '@' + relative
53
+ const start = Math.max(1, Math.trunc(range.startLine))
54
+ const end = Math.max(start, Math.trunc(range.endLine ?? start))
55
+ return start === end ? '@' + relative + ' L' + start : '@' + relative + ' L' + start + '-L' + end
56
+ }
57
+
58
+ /**
59
+ * 解析剪贴板/拖拽里的引用文本(整段必须是一条引用,否则返回 null)。
60
+ * @author ddj 2026年11月15号
61
+ * @param text 原始文本
62
+ * @returns 解析结果;不是引用语法时返回 null
63
+ */
64
+ export function parseRef(text: string): ParsedRef | null {
65
+ const raw = String(text ?? '').trim()
66
+ if (!raw || raw.length > 4096) return null
67
+ const matched = REF_PATTERN.exec(raw)
68
+ if (!matched) return null
69
+ const path = normalizeRefPath(matched[1] ?? matched[2] ?? '')
70
+ if (!path) return null
71
+ const start = matched[3] === undefined ? undefined : Number(matched[3])
72
+ const end = matched[4] === undefined ? start : Number(matched[4])
73
+ if (start === undefined || !Number.isFinite(start) || start < 1) return { path }
74
+ return { path, range: { startLine: start, endLine: Math.max(start, end ?? start) } }
75
+ }
76
+
77
+ /**
78
+ * 选区是否应转成「行引用」:跨行一律是;单行只有整行选中才是。
79
+ * @author ddj 2026年11月15号
80
+ * @param input 选区信息(行列均 1-based;endColumn 为选区右边界后一位)
81
+ * @returns 行范围;不满足条件返回 null
82
+ */
83
+ export function selectionRange(input: {
84
+ startLine: number
85
+ endLine: number
86
+ startColumn: number
87
+ endColumn: number
88
+ lineLength: number
89
+ }): RefRange | null {
90
+ const startLine = Math.max(1, Math.trunc(Number(input.startLine) || 0))
91
+ const endLine = Math.max(startLine, Math.trunc(Number(input.endLine) || startLine))
92
+ const lineLength = Math.max(0, Math.trunc(Number(input.lineLength) || 0))
93
+ if (endLine > startLine) return { startLine, endLine }
94
+ const wholeLine = Math.trunc(Number(input.startColumn)) === 1 && Math.trunc(Number(input.endColumn)) === lineLength + 1
95
+ return wholeLine && lineLength > 0 ? { startLine, endLine: startLine } : null
96
+ }
97
+
98
+ /**
99
+ * 取路径末段文件名(引用解析/同名匹配用)。
100
+ * @author ddj 2026年11月15号
101
+ * @param path 路径文本
102
+ * @returns 文件名
103
+ */
104
+ export function refBasename(path: string): string {
105
+ return normalizeRefPath(path).split('/').filter(Boolean).pop() ?? ''
106
+ }
package/src/shared/rpc.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  * Purity rule: no node/react imports (same as types.ts).
7
7
  * 作者 ddj 2026-08-20
8
8
  */
9
+ import type { UniverCapability, UniverImport, UniverImportResult, UniverCachedOpen, UniverCacheList, UniverCleanItem } from './univer.js'
9
10
  import type {
10
11
  ArchiveBatch,
11
12
  ArchiveEntry,
@@ -21,7 +22,7 @@ import type { SnippetEntry, SnippetInfo, SnippetProject, SnippetRefInput, Snippe
21
22
  import type { QuickMenuDoc } from './quickMenu.js'
22
23
  import type { LspCompletionItem, LspCompletionList, LspEnvInstallState, LspExtInfo, LspExtUpdate, LspHover, LspLocation, LspMarketItem, LspPosition, LspSemanticTokens, LspServerStatus, LspSignatureHelp, LspSymbol } from './lsp.js'
23
24
  import type { AiConfigPatch, AiConfigView, AiDirectoryView, AiInlineRequest, AiInlineResult } from './ai.js'
24
- import type { SvnAction, SvnAiPlan, SvnChangeEntry, SvnConflictArtifact, SvnDiffRevResult, SvnIgnoreItem, SvnLogEntry, SvnRemoteOutdatedEntry, SvnStatusPayload, SvnSumEntry, SvnUpdatePoll, SvnUpdateResult, SvnUpdateState } from './svn.js'
25
+ import type { SvnAction, SvnAiPlan, SvnChangeEntry, SvnCommitPlan, SvnCommitResult, SvnConflictArtifact, SvnDiffRevResult, SvnIgnoreItem, SvnLogEntry, SvnRemoteOutdatedEntry, SvnStatusPayload, SvnSumEntry, SvnUpdatePoll, SvnUpdateResult, SvnUpdateState } from './svn.js'
25
26
  import type { DapAction, DapAdapterInfo, DapBreakpointAck, DapBreakpointInput, DapConfigSnippet, DapConfigSource, DapDebugConfig, DapFrameView, DapPhase, DapPollResult, DapProcessInfo, DapScopeView, DapVariableView } from './dap.js'
26
27
  import { DAP_ACTIONS } from './dap.js'
27
28
  import { transportUrl } from './remoteChannel.js'
@@ -375,6 +376,11 @@ export interface UiStatePatchInput {
375
376
 
376
377
  /** 每个方法的请求参数(sessionId 为公共可选字段)。 */
377
378
  export interface RpcRequestMap {
379
+ 'edrv.univer.capabilities': { sessionId: string }
380
+ 'edrv.univer.importCopy': UniverImport
381
+ 'edrv.univer.openCached': { sessionId: string; source: string; operationId: string; refresh?: boolean }
382
+ 'edrv.univer.cacheList': { sessionId: string }
383
+ 'edrv.univer.cacheClean': { sessionId: string; entries: Array<{ id: string; revision: string }> }
378
384
  'edrv.review.list': ReviewRequest & { cursor?: number; history?: boolean; path?: string; all?: boolean }
379
385
  'edrv.review.detail': ReviewRequest & { id: string }
380
386
  'edrv.review.decide': DecideReview
@@ -410,6 +416,8 @@ export interface RpcRequestMap {
410
416
  'edrv.dlog.reveal': { sessionId?: string }
411
417
  'edrv.searchFiles': { sessionId?: string; query: string }
412
418
  'edrv.searchContent': { sessionId?: string; query: string; matchCase?: boolean; wholeWord?: boolean; regex?: boolean; maxResults?: number; include?: string[]; exclude?: string[]; force?: boolean }
419
+ 'edrv.replaceContent': { sessionId?: string; query: string; replacement: string; matchCase?: boolean; wholeWord?: boolean; regex?: boolean; include?: string[]; exclude?: string[]; paths?: string[]; dryRun?: boolean }
420
+ 'edrv.resolveRef': { sessionId?: string; ref: string; activePath?: string }
413
421
  'edrv.listDir': { sessionId?: string; path: string; force?: boolean }
414
422
  'edrv.revealInExplorer': { sessionId?: string; path: string }
415
423
  'edrv.fsCreateFile': { sessionId?: string; path: string }
@@ -531,14 +539,20 @@ export interface RpcRequestMap {
531
539
  'svn.conflictArtifacts': { sessionId?: string; path: string }
532
540
  'svn.diffLocalPair': { sessionId?: string; left: string; right: string }
533
541
  'svn.fileSizes': { sessionId?: string; paths: string[] }
534
- /** AI 智能整理:只读分析全部变更,产出分组/还原/忽略三段方案(不写工作副本)。 */
535
- 'svn.aiPlan': { sessionId?: string }
542
+ /** AI 智能整理:只读分析变更(paths 限定范围,缺省 = 全部),产出分组/还原/忽略/拆分提交方案。 */
543
+ 'svn.aiPlan': { sessionId?: string; paths?: string[] }
536
544
  /** AI 智能整理执行段:按目录合并写入 svn:ignore 属性(propget 合并,不整体覆盖)。 */
537
545
  'svn.ignore': { sessionId?: string; items: SvnIgnoreItem[] }
538
546
  /** 混合通道投递口:会话 agent 深度分析后把方案 POST 回面板收件箱(免鉴权本地 RPC)。 */
539
547
  'svn.aiPlanSubmit': { sessionId?: string; plan: unknown }
540
548
  /** 混合通道取件口:面板轮询取收件箱方案(since = 注入时刻,早于它的旧投递不算新件)。 */
541
549
  'svn.aiPlanPending': { sessionId?: string; since?: number }
550
+ /** 提交计划:变更清单 + 既有 changelist + 最近提交信息(只读)。 */
551
+ 'svn.commitPlan': { sessionId?: string }
552
+ /** 原生提交:仅提交给定路径;host 先 status 重查再按开关自动 add/delete。 */
553
+ 'svn.commit': { sessionId?: string; paths: string[]; message: string; changelist?: string; keepLocks?: boolean; autoAdd?: boolean; autoDelete?: boolean }
554
+ /** AI 生成提交信息:只分析给定路径(提交范围),产出 subject/body(不提交)。 */
555
+ 'svn.aiCommitMsg': { sessionId?: string; paths: string[]; style?: 'plain' | 'conventional' }
542
556
  'edrv.dap.configs': { workspacePath: string }
543
557
  'edrv.dap.snippets': {}
544
558
  'edrv.dap.processes': { processName?: string }
@@ -561,6 +575,11 @@ export type RpcMethod = keyof RpcRequestMap
561
575
 
562
576
  /** 每个方法成功(ok:true)时的附加载荷。 */
563
577
  export interface RpcOkMap {
578
+ 'edrv.univer.capabilities': { capability: UniverCapability }
579
+ 'edrv.univer.importCopy': { imported: UniverImportResult }
580
+ 'edrv.univer.openCached': { cached: UniverCachedOpen }
581
+ 'edrv.univer.cacheList': { cache: UniverCacheList }
582
+ 'edrv.univer.cacheClean': { results: UniverCleanItem[] }
564
583
  'edrv.review.list': { page: ReviewPage }
565
584
  'edrv.review.detail': { detail: ReviewDetail }
566
585
  'edrv.review.decide': { revision: number }
@@ -596,6 +615,8 @@ export interface RpcOkMap {
596
615
  'edrv.dlog.reveal': { opened: boolean }
597
616
  'edrv.searchFiles': { files: string[]; truncated: boolean }
598
617
  'edrv.searchContent': { matches: SearchContentMatch[]; truncated: boolean; warning?: string }
618
+ 'edrv.replaceContent': { files: Array<{ path: string; replaced: number }>; totalFiles: number; totalReplaced: number; truncated: boolean; dryRun: boolean; skipped: number; failed: Array<{ path: string; reason: string }>; warning?: string }
619
+ 'edrv.resolveRef': { path: string; ambiguous?: string[] }
599
620
  'edrv.listDir': { root: string; path: string; entries: TreeEntry[] }
600
621
  'edrv.revealInExplorer': { revealed: string }
601
622
  'edrv.fsCreateFile': { path: string }
@@ -717,11 +738,14 @@ export interface RpcOkMap {
717
738
  'svn.conflictArtifacts': { artifacts: SvnConflictArtifact[] }
718
739
  'svn.diffLocalPair': SvnDiffRevResult
719
740
  'svn.fileSizes': { sizes: Array<{ path: string; size: number | null }> }
720
- 'svn.aiPlan': { plan: SvnAiPlan; entriesCount: number; diffIncluded: boolean; dropped: number; model?: string }
741
+ 'svn.aiPlan': { plan: SvnAiPlan; entriesCount: number; analyzedCount: number; diffIncluded: boolean; dropped: number; model?: string }
721
742
  'svn.ignore': { count: number; summary: string; output: string }
722
743
  /** accepted = 归一后三段总路径数(0 = ok:false 拒收);dropped = 幻觉/落选丢弃数。 */
723
744
  'svn.aiPlanSubmit': { accepted: number; dropped: number }
724
745
  'svn.aiPlanPending': { plan: SvnAiPlan | null; dropped: number; at: number }
746
+ 'svn.commitPlan': SvnCommitPlan
747
+ 'svn.commit': SvnCommitResult
748
+ 'svn.aiCommitMsg': { subject: string; body: string; message: string; model: string; stats: { files: number; diffBytes: number; diffIncluded: boolean } }
725
749
  'edrv.dap.configs': { configs: DapDebugConfig[]; adapters: DapAdapterInfo[]; source: DapConfigSource }
726
750
  'edrv.dap.snippets': { snippets: DapConfigSnippet[] }
727
751
  'edrv.dap.processes': { items: DapProcessInfo[] }