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,205 @@
1
+ /** Owned workspace Office cache; never swept automatically. @author ddj 2026年11月13号 */
2
+ import { createHash, randomUUID } from 'node:crypto'
3
+ import { lstat, mkdir, open, readFile, readdir, realpath, rename, rmdir, unlink } from 'node:fs/promises'
4
+ import { join, relative, resolve, sep } from 'node:path'
5
+ import { univerCacheRoot } from './paths.js'
6
+ import { importCopy, insideRoot } from './univerBridge.js'
7
+ import type { UniverService } from './univerBridge.js'
8
+ import { canImportOffice } from './shared/univer.js'
9
+ import type { UniverCachedOpen, UniverCacheEntry, UniverCleanItem, UniverImportResult } from './shared/univer.js'
10
+
11
+ interface CacheRecord {
12
+ owner: 'dsh-vscode-mode/univer-v1'
13
+ source: string
14
+ fingerprint: string
15
+ sourceBytes: number
16
+ sourceMtime: number
17
+ createdAt: number
18
+ accessedAt: number
19
+ imported: UniverImportResult
20
+ }
21
+ interface StoredEntry { view: UniverCacheEntry; record: CacheRecord }
22
+ const queues = new Map<string, Promise<unknown>>()
23
+ const OWNER = 'dsh-vscode-mode/univer-v1'
24
+
25
+ /** @private @author ddj 2026年11月13号 @param content Exact bytes. @returns Stable full hash. */
26
+ function digest(content: string | Buffer): string {
27
+ return createHash('sha256').update(content).digest('hex')
28
+ }
29
+
30
+ /** @public @author ddj 2026年11月13号 @param workspace Real workspace. @param create Explicit mutation. @returns Checked cache root without following symlinks. @throws Unsafe existing ancestor. */
31
+ export async function cacheRoot(workspace: string, create = false): Promise<string> {
32
+ const root = await realpath(workspace)
33
+ const target = univerCacheRoot(root)
34
+ let current = root
35
+ for (const part of relative(root, target).split(sep)) {
36
+ current = join(current, part)
37
+ try {
38
+ const info = await lstat(current)
39
+ if (info.isSymbolicLink() || !info.isDirectory() || !insideRoot(root, await realpath(current))) throw new Error('缓存路径包含链接或非目录')
40
+ } catch (error) {
41
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
42
+ if (!create) return target
43
+ try { await mkdir(current) } catch (cause) { if ((cause as NodeJS.ErrnoException).code !== 'EEXIST') throw cause }
44
+ const info = await lstat(current)
45
+ if (info.isSymbolicLink() || !info.isDirectory() || !insideRoot(root, await realpath(current))) throw new Error('缓存目录身份变化')
46
+ }
47
+ }
48
+ return target
49
+ }
50
+
51
+ /** @private @author ddj 2026年11月13号 @param root Cache root. @param id Host-owned relative entry id. @returns Checked generation directory. @throws Malformed or linked entry. */
52
+ async function entryDir(root: string, id: string): Promise<string> {
53
+ if (!/^[a-f0-9]{64}\/[a-f0-9-]{36}$/.test(id)) throw new Error('无效缓存标识')
54
+ let directory = root
55
+ for (const part of id.split('/')) {
56
+ directory = join(directory, part)
57
+ const info = await lstat(directory)
58
+ if (info.isSymbolicLink() || !info.isDirectory()) throw new Error('缓存条目包含链接')
59
+ }
60
+ return directory
61
+ }
62
+
63
+ /** @private @author ddj 2026年11月13号 @param root Checked root. @param id Generation id. @returns Valid owned metadata and disk identity. */
64
+ async function readEntry(root: string, id: string): Promise<StoredEntry> {
65
+ const directory = await entryDir(root, id)
66
+ const metadata = join(directory, 'entry.json')
67
+ const info = await lstat(metadata)
68
+ if (info.isSymbolicLink() || !info.isFile() || info.size > 32768) throw new Error('缓存清单不安全')
69
+ const text = await readFile(metadata, 'utf8')
70
+ const record = JSON.parse(text) as CacheRecord
71
+ if (record.owner !== OWNER || typeof record.source !== 'string' || !/^[a-f0-9]{64}$/.test(record.fingerprint) || !Number.isFinite(record.createdAt) || !record.imported || typeof record.imported.success !== 'boolean') throw new Error('缓存所有权记录无效')
72
+ const names = await readdir(directory)
73
+ let bytes = 0
74
+ const identities: string[] = []
75
+ for (const name of names.sort()) {
76
+ const child = await lstat(join(directory, name))
77
+ if (child.isSymbolicLink() || !child.isFile()) throw new Error('缓存条目含未知目录或链接')
78
+ bytes += child.size
79
+ identities.push(name + ':' + child.size + ':' + child.mtimeMs)
80
+ }
81
+ return { record, view: { id, revision: digest(text + identities.join('|')), source: record.source, file: join(directory, 'document.univer'), bytes, createdAt: record.createdAt, complete: record.imported.success } }
82
+ }
83
+
84
+ /** @public @author ddj 2026年11月13号 @param workspace Session workspace. @returns Bounded owned cache listing; does not create directories. */
85
+ export async function listCache(workspace: string): Promise<{ root: string; entries: UniverCacheEntry[]; truncated: boolean }> {
86
+ const root = await cacheRoot(workspace)
87
+ let sources: string[]
88
+ try { sources = await readdir(root) } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { root, entries: [], truncated: false }; throw error }
89
+ const entries: UniverCacheEntry[] = []
90
+ let observed = 0
91
+ for (const source of sources) {
92
+ if (!/^[a-f0-9]{64}$/.test(source)) continue
93
+ const sourceInfo = await lstat(join(root, source))
94
+ if (sourceInfo.isSymbolicLink() || !sourceInfo.isDirectory()) continue
95
+ for (const generation of await readdir(join(root, source))) {
96
+ if (++observed > 500) return { root, entries, truncated: true }
97
+ try { entries.push((await readEntry(root, source + '/' + generation)).view) } catch { /* Unsafe/unowned entries are never offered for deletion. */ }
98
+ }
99
+ }
100
+ return { root, entries: entries.sort((a, b) => b.createdAt - a.createdAt), truncated: false }
101
+ }
102
+
103
+ /** @public @author ddj 2026年11月13号 @param workspace Workspace identity. @param action Serialized cache operation. @returns Exclusive process-local result. */
104
+ export async function withCacheLock<T>(workspace: string, action: () => Promise<T>): Promise<T> {
105
+ const key = await realpath(workspace)
106
+ const previous = queues.get(key) ?? Promise.resolve()
107
+ const next = previous.catch(() => undefined).then(action)
108
+ queues.set(key, next)
109
+ try { return await next } finally { if (queues.get(key) === next) queues.delete(key) }
110
+ }
111
+
112
+ /** @private @author ddj 2026年11月13号 @param directory Owned generation. @param record Metadata. Atomically persists stage without rewriting document. */
113
+ async function saveRecord(directory: string, record: CacheRecord): Promise<void> {
114
+ const temporary = join(directory, 'entry-' + randomUUID() + '.tmp')
115
+ const handle = await open(temporary, 'wx')
116
+ try { await handle.writeFile(JSON.stringify(record)); await handle.sync() } finally { await handle.close() }
117
+ await rename(temporary, join(directory, 'entry.json'))
118
+ }
119
+
120
+ /** @private @author ddj 2026年11月13号 @param workspace Canonical workspace. @param source Source relative path. @returns Source identity and content hash. */
121
+ async function sourceState(workspace: string, source: string) {
122
+ if (!canImportOffice(source)) throw new Error('不支持的 Office 源文件')
123
+ const path = await realpath(resolve(workspace, source))
124
+ if (!insideRoot(workspace, path) || !(await lstat(path)).isFile()) throw new Error('源文件超出工作区或不是文件')
125
+ if ((await lstat(path)).size > 32 * 1024 * 1024) throw new Error('Office 源文件超过32MiB缓存导入上限')
126
+ const normalized = relative(workspace, path).split(sep).join('/')
127
+ const identity = process.platform === 'win32' ? normalized.toLowerCase() : normalized
128
+ const info = await lstat(path)
129
+ return { path, source: normalized, key: digest(identity), fingerprint: digest(await readFile(path)), bytes: info.size, mtime: info.mtimeMs }
130
+ }
131
+
132
+ /** @public @author ddj 2026年11月13号 @param workspace Checked workspace. @param source Office source. @param service Optional adapter. @param refresh Explicit source refresh. @returns Existing edits preserved or new owned generation. */
133
+ export async function openCache(workspace: string, source: string, service: UniverService, refresh = false): Promise<UniverCachedOpen> {
134
+ return withCacheLock(workspace, async () => {
135
+ const canonical = await realpath(workspace)
136
+ await sourceState(canonical, source)
137
+ const root = await cacheRoot(canonical, true)
138
+ const lock = await open(join(root, '.mutation.lock'), 'wx').catch(() => { throw new Error('缓存正由其他进程操作;未重复创建,请稍后重试') })
139
+ try { return await prepareCache(canonical, root, source, service, refresh) }
140
+ finally { await lock.close(); await unlink(join(root, '.mutation.lock')) }
141
+ })
142
+ }
143
+
144
+ /** @private @author ddj 2026年11月13号 @param workspace Canonical workspace. @param root Cache root. @param source Office source. @param service Upstream adapter. @param refresh Explicit refresh. @returns Checked cached operation. */
145
+ async function prepareCache(workspace: string, root: string, source: string, service: UniverService, refresh: boolean): Promise<UniverCachedOpen> {
146
+ const original = await sourceState(workspace, source)
147
+ const listing = await listCache(workspace)
148
+ if (listing.truncated) throw new Error('缓存条目超过查询上限,请先清理后再打开')
149
+ const previous = listing.entries.find((entry) => entry.id.startsWith(original.key + '/'))
150
+ if (previous && !refresh) {
151
+ const stored = await readEntry(root, previous.id)
152
+ const file = await lstat(previous.file).catch(() => null)
153
+ if (!file?.isFile() || file.isSymbolicLink()) throw new Error('缓存容器缺失或身份异常;请在设置中检查缓存')
154
+ if (!previous.complete) throw new Error('上次缓存准备未完成;请检查草稿,不自动重复导入')
155
+ stored.record.accessedAt = Date.now()
156
+ await saveRecord(join(root, previous.id), stored.record)
157
+ return { imported: { ...stored.record.imported, file: previous.file }, sourceChanged: stored.record.fingerprint !== original.fingerprint, reused: true }
158
+ }
159
+ const sourceDirectory = join(root, original.key)
160
+ try { await mkdir(sourceDirectory) } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error }
161
+ if ((await lstat(sourceDirectory)).isSymbolicLink()) throw new Error('缓存源目录包含链接')
162
+ const directory = join(sourceDirectory, randomUUID())
163
+ await mkdir(directory)
164
+ const file = join(directory, 'document.univer')
165
+ const record: CacheRecord = { owner: OWNER, source: original.source, fingerprint: original.fingerprint, sourceBytes: original.bytes, sourceMtime: original.mtime, createdAt: Date.now(), accessedAt: Date.now(), imported: { success: false, stage: 'create', file } }
166
+ await saveRecord(directory, record)
167
+ record.imported = await importCopy(service, { workspace, source: original.path, file })
168
+ const current = await sourceState(workspace, source)
169
+ const changed = current.fingerprint !== original.fingerprint
170
+ if (changed) record.imported = { ...record.imported, success: false, error: '导入期间源文件发生变化,请检查缓存结果,未自动重试' }
171
+ await saveRecord(directory, record)
172
+ return { imported: record.imported, sourceChanged: changed, reused: false }
173
+ }
174
+
175
+ /** @public @author ddj 2026年11月13号 @param workspace Authorized root. @param selected Host-issued identities. @param busy Gateway may hold handles. @returns Per-entry safe cleanup outcome. */
176
+ export async function cleanCache(workspace: string, selected: Array<{ id: string; revision: string }>, busy: boolean): Promise<UniverCleanItem[]> {
177
+ return withCacheLock(workspace, async () => {
178
+ const root = await cacheRoot(workspace)
179
+ if (busy) return selected.map(({ id }) => ({ id, status: 'skipped', reason: 'Univer 服务运行中,可能持有缓存;未停止服务或删除文件' }))
180
+ let lock
181
+ try { lock = await open(join(root, '.mutation.lock'), 'wx') } catch { return selected.map(({ id }) => ({ id, status: 'skipped', reason: '缓存不存在或正在由其他进程操作' })) }
182
+ try {
183
+ const results: UniverCleanItem[] = []
184
+ for (const selection of selected.slice(0, 500)) results.push(await cleanEntry(root, selection))
185
+ return results
186
+ } finally { await lock.close(); await unlink(join(root, '.mutation.lock')) }
187
+ })
188
+ }
189
+
190
+ /** @private @author ddj 2026年11月13号 @param root Checked cache root. @param selection Selected revision. @returns Outcome without deleting unknown files. */
191
+ async function cleanEntry(root: string, selection: { id: string; revision: string }): Promise<UniverCleanItem> {
192
+ const { id } = selection
193
+ try {
194
+ const stored = await readEntry(root, id)
195
+ if (stored.view.revision !== selection.revision) return { id, status: 'skipped', reason: '缓存已变化,请刷新后重选' }
196
+ const directory = await entryDir(root, id)
197
+ const names = await readdir(directory)
198
+ if (names.some((name) => !['entry.json', 'document.univer', 'document.univer-wal', 'document.univer-shm', 'document.univer-journal'].includes(name))) return { id, status: 'skipped', reason: '存在未知文件,未清理' }
199
+ for (const name of names.filter((name) => name !== 'entry.json')) await unlink(join(directory, name))
200
+ await unlink(join(directory, 'entry.json'))
201
+ await rmdir(directory)
202
+ await rmdir(join(root, id.split('/')[0])).catch(() => undefined)
203
+ return { id, status: 'deleted' }
204
+ } catch (error) { return { id, status: 'failed', reason: String(error) } }
205
+ }
@@ -0,0 +1,144 @@
1
+ /** Session-authorized optional Univer handlers. @author ddj 2026年11月12号 */
2
+ import { realpath } from 'node:fs/promises'
3
+ import { resolve } from 'node:path'
4
+ import { cleanCache, listCache, openCache } from './univerCache.js'
5
+ import { univerCacheRoot } from './paths.js'
6
+ import type { Ctx } from './store.js'
7
+ import { cwdOfSession, policyOf } from './store.js'
8
+ import { sessionOf } from './registry.js'
9
+ import { importCopy, importPaths, insideRoot, univerService } from './univerBridge.js'
10
+ import type { UniverService } from './univerBridge.js'
11
+ import type { RpcHandlerMap } from './shared/rpc.js'
12
+ import type { UniverCapability, UniverImport, UniverImportResult } from './shared/univer.js'
13
+
14
+ interface SessionAccess {
15
+ workspace: string
16
+ writable: boolean
17
+ policyRoot?: string
18
+ service: UniverService | null
19
+ }
20
+ interface ImportEntry {
21
+ request: string
22
+ promise: Promise<UniverImportResult>
23
+ }
24
+ const imports = new Map<string, ImportEntry>()
25
+ const targets = new Map<string, Promise<UniverImportResult>>()
26
+ const cachedOps = new Map<string, { request: string; result: ReturnType<typeof openCache> }>()
27
+
28
+ /** @private @author ddj 2026年11月13号 @param access Authorized scope. @param args Explicit cache request. @returns Idempotent generation creation, including source refresh. */
29
+ async function cachedOnce(access: SessionAccess, args: { sessionId: string; source: string; operationId: string; refresh?: boolean }) {
30
+ if (!access.service || !args.operationId || args.operationId.length > 100) throw new Error('缺少有效缓存操作标识或服务')
31
+ const key = JSON.stringify([args.sessionId, args.operationId])
32
+ const request = JSON.stringify([access.workspace, args.source, args.refresh === true])
33
+ const previous = cachedOps.get(key)
34
+ if (previous) {
35
+ if (previous.request !== request) throw new Error('缓存操作标识已用于其他请求')
36
+ return previous.result
37
+ }
38
+ if (cachedOps.size >= 512) throw new Error('缓存操作记录已达上限,请重新打开会话后检查已有缓存')
39
+ const result = openCache(access.workspace, args.source, access.service, args.refresh)
40
+ cachedOps.set(key, { request, result })
41
+ return result
42
+ }
43
+
44
+ /** @private @author ddj 2026年11月12号 @param ctx Host context. @param sessionId Live session. @returns Verified session and optional service. @throws Missing session/workspace. */
45
+ function accessOf(ctx: Ctx, sessionId: string): SessionAccess {
46
+ const session = sessionOf(ctx, sessionId)
47
+ if (!session) throw new Error('会话不存在,联动要求本端活跃会话')
48
+ const workspace = cwdOfSession(ctx, session)
49
+ if (!workspace) throw new Error('当前会话没有工作区')
50
+ const policy = policyOf(ctx, session)
51
+ const writable = policy?.mode === 'workspace-write' || policy?.mode === 'danger-full-access'
52
+ // Viewer state is authorized against header.cwd in upstream 0.4.0.
53
+ if (session.header?.cwd !== workspace) throw new Error('当前目录已变化,Univer 0.4.0 仅支持会话初始工作区')
54
+ return { workspace, writable, policyRoot: policy?.workspaceRoot, service: univerService(ctx.get('univer')) }
55
+ }
56
+
57
+ /** @private @author ddj 2026年11月12号 @param access Checked session. @returns Non-mutating capability state. */
58
+ async function capabilityOf(access: SessionAccess): Promise<UniverCapability> {
59
+ if (!access.service) return { available: false, writable: false, reason: 'Univer Office 未启用或接口不兼容' }
60
+ const gateway = await access.service.gatewayStatus()
61
+ return { available: true, writable: access.writable, gateway: gateway.phase, reason: access.writable ? undefined : '当前会话为只读或策略不可用,未加载 Viewer' }
62
+ }
63
+
64
+ /** @private @author ddj 2026年11月12号 @param access Session access. @param args Import request. @returns Identifiable import result. @throws Permission and path refusal before mutation. */
65
+ async function runImport(access: SessionAccess, args: UniverImport): Promise<UniverImportResult> {
66
+ if (!access.writable || !access.service) throw new Error('当前会话没有 Univer 写入能力')
67
+ const paths = await importPaths(access.workspace, args.source, args.target)
68
+ if (!access.policyRoot) throw new Error('无法确定会话写入边界')
69
+ const policyRoot = await realpath(access.policyRoot)
70
+ if (!insideRoot(policyRoot, paths.file) || !insideRoot(policyRoot, paths.source)) throw new Error('源或目标超出会话沙箱边界')
71
+ return importCopy(access.service, paths)
72
+ }
73
+
74
+ /** @private @author ddj 2026年11月12号 @param access Freshly checked session. @param args Request with operation identity. @returns Same outcome for duplicate requests, including partial failure. */
75
+ async function onceImport(access: SessionAccess, args: UniverImport): Promise<UniverImportResult> {
76
+ if (!args.operationId || args.operationId.length > 100) throw new Error('缺少有效操作标识')
77
+ const key = JSON.stringify([args.sessionId, args.operationId])
78
+ const request = JSON.stringify([access.workspace, args.source, args.target])
79
+ const previous = imports.get(key)
80
+ if (previous) {
81
+ if (previous.request !== request) throw new Error('操作标识已用于其他导入')
82
+ return previous.promise
83
+ }
84
+ // Cap process-local outcomes; never evict and accidentally replay a completed mutation.
85
+ if (imports.size >= 512) throw new Error('本进程导入操作记录已达上限,请打开已有副本')
86
+ const targetKey = JSON.stringify([access.workspace, args.target])
87
+ if (targets.has(targetKey)) throw new Error('该目标正在导入,请等待已有操作结束')
88
+ const promise = runImport(access, args)
89
+ imports.set(key, { request, promise })
90
+ targets.set(targetKey, promise)
91
+ try { return await promise } finally { targets.delete(targetKey) }
92
+ }
93
+
94
+ /** @private @author ddj 2026年11月13号 @param access Live session policy. @throws Read-only or cache root outside sandbox. */
95
+ async function cacheWrite(access: SessionAccess): Promise<void> {
96
+ if (!access.writable || !access.policyRoot) throw new Error('当前会话没有缓存写入/清理权限')
97
+ const workspace = await realpath(access.workspace)
98
+ const policyRoot = await realpath(access.policyRoot)
99
+ if (!insideRoot(policyRoot, univerCacheRoot(workspace))) throw new Error('缓存目录超出沙箱写入边界')
100
+ }
101
+
102
+ /** @public @author ddj 2026年11月12号 @param ctx Host context. @returns Optional capability and controlled import handlers. */
103
+ export function univerHandlers(ctx: Ctx): Partial<RpcHandlerMap> {
104
+ return {
105
+ 'edrv.univer.cacheList': async (args) => {
106
+ try {
107
+ const access = accessOf(ctx, args.sessionId)
108
+ return { ok: true, cache: { ...await listCache(access.workspace), workspace: access.workspace, writable: access.writable } }
109
+ } catch (error) { return { ok: false, error: String(error) } }
110
+ },
111
+ 'edrv.univer.cacheClean': async (args) => {
112
+ try {
113
+ const access = accessOf(ctx, args.sessionId)
114
+ await cacheWrite(access)
115
+ const gateway = await access.service?.gatewayStatus()
116
+ // No per-file release API: unknown or running Gateway state is not safe to unlink.
117
+ const busy = !!access.service && gateway?.phase !== 'stopped'
118
+ return { ok: true, results: await cleanCache(access.workspace, args.entries, busy) }
119
+ } catch (error) { return { ok: false, error: String(error) } }
120
+ },
121
+ 'edrv.univer.openCached': async (args) => {
122
+ try {
123
+ const access = accessOf(ctx, args.sessionId)
124
+ await cacheWrite(access)
125
+ if (!access.service) throw new Error('Univer Office 未启用')
126
+ const source = await realpath(resolve(access.workspace, args.source))
127
+ const policyRoot = await realpath(access.policyRoot!)
128
+ if (!insideRoot(policyRoot, source)) throw new Error('源文件超出会话沙箱边界')
129
+ return { ok: true, cached: await cachedOnce(access, args) }
130
+ } catch (error) { return { ok: false, error: String(error) } }
131
+ },
132
+ 'edrv.univer.capabilities': async (args) => {
133
+ try { return { ok: true, capability: await capabilityOf(accessOf(ctx, args.sessionId)) } }
134
+ catch (error) { return { ok: false, error: String(error) } }
135
+ },
136
+ 'edrv.univer.importCopy': async (args) => {
137
+ try {
138
+ const access = accessOf(ctx, args.sessionId)
139
+ if (!access.writable || !access.service) return { ok: false, error: '当前没有 Univer 写入能力' }
140
+ return { ok: true, imported: await onceImport(access, args) }
141
+ } catch (error) { return { ok: false, error: String(error) } }
142
+ },
143
+ }
144
+ }