@twinsearth/dsh-fang 3.3.2 → 3.7.7
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.
- package/README.md +5 -5
- package/client.js +674 -60
- package/cordis.patch.yml +26 -20
- package/docs/APPROVAL-DRILL.md +42 -0
- package/docs/AUTO-WATCHDOG.md +46 -0
- package/docs/DECISION-LOSSLESS.md +36 -0
- package/docs/ESSENCE-AUTO-SYNC.md +32 -0
- package/docs/INBOX-SCROLL.md +33 -0
- package/docs/PACKAGE-RENAME-v3.3.3.md +40 -0
- package/docs/RESTART-CONFIRMATION.md +29 -0
- package/docs/TEST-STABILITY-v3.4.0.md +30 -0
- package/package.json +11 -7
- package/src/compose.mjs +4 -1
- package/src/contract/VENDOR.json +6 -5
- package/src/contract/constants.js +16 -1
- package/src/contract/relay.js +12 -6
- package/src/kernel/types.mjs +3 -1
- package/src/lib/accelerated-fork.mjs +813 -0
- package/src/lib/accelerated-install.mjs +295 -0
- package/src/lib/accelerated-web.mjs +103 -0
- package/src/lib/approval-drill.mjs +111 -0
- package/src/lib/boot-guard.mjs +6 -2
- package/src/lib/chat-import-delegation.mjs +47 -0
- package/src/lib/compat.mjs +5 -1
- package/src/lib/contract-delegation.mjs +161 -0
- package/src/lib/default-essence.mjs +7 -4
- package/src/lib/essence.mjs +113 -7
- package/src/lib/fork-config-lock.mjs +2 -2
- package/src/lib/fork-core-settings.mjs +95 -0
- package/src/lib/fork-export.mjs +85 -0
- package/src/lib/global-redline.mjs +164 -0
- package/src/lib/http-auth.mjs +36 -0
- package/src/lib/install-snapshot.mjs +77 -0
- package/src/lib/lsp-delegation.mjs +70 -0
- package/src/lib/lsp-provider.mjs +250 -0
- package/src/lib/main-gate.mjs +33 -28
- package/src/lib/mirror.mjs +115 -4
- package/src/lib/node-compat.mjs +24 -0
- package/src/lib/pro-delegation.mjs +185 -0
- package/src/lib/runtime-capture.mjs +11 -3
- package/src/lib/watch-guard.mjs +51 -0
- package/src/plugins/approver.mjs +5 -2
- package/src/plugins/auditor.mjs +125 -18
- package/src/plugins/decision-center.mjs +77 -34
- package/src/plugins/forker.mjs +258 -33
- package/src/plugins/orchestrator.mjs +1508 -65
- package/src/plugins/restart-guard.mjs +79 -2
- package/src/plugins/session-catalog.mjs +127 -40
- package/tools/approval-drill.mjs +21 -0
- package/tools/fangctl.mjs +21 -4
- package/tools/gate/main-city.mjs +1 -1
- package/tools/restart-supervisor.mjs +425 -0
- package/tools/restart-watchdog.mjs +568 -0
- package/vault/client.js +49 -0
- package/vault/cordis.patch.yml +3 -0
- package/vault/lib/vault.mjs +219 -0
- package/vault/package.json +29 -0
|
@@ -0,0 +1,813 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
|
|
3
|
+
//
|
|
4
|
+
// Accelerated fork profile (P0): a *minimal* profile for a fork that runs on the
|
|
5
|
+
// accelerated core (@twinsearth/dsh). The mother/desktop profile is never
|
|
6
|
+
// cloned: its bundles are @deepseek-ai/* and its third-party plugins target the
|
|
7
|
+
// stock core, so they cannot be reused here.
|
|
8
|
+
//
|
|
9
|
+
// Composition is intentionally tiny and asserted by tests:
|
|
10
|
+
// @twinsearth/dsh-base → @twinsearth/dsh-web-app → @twinsearth/fang-dsh-plugin
|
|
11
|
+
// plus per-entry junctions for the fang bundle and its two child plugins, and a
|
|
12
|
+
// scope-rewritten model overlay for the fork's own DSH_HOME.
|
|
13
|
+
import fs from 'node:fs'
|
|
14
|
+
import path from 'node:path'
|
|
15
|
+
import zlib from 'node:zlib'
|
|
16
|
+
import { pathToFileURL } from 'node:url'
|
|
17
|
+
|
|
18
|
+
export const ACCEL_BUNDLES = Object.freeze(['@twinsearth/dsh-base', '@twinsearth/dsh-web-app'])
|
|
19
|
+
export const FANG_BUNDLE = '@twinsearth/fang-dsh-plugin'
|
|
20
|
+
/** npm-installed fang bundle name (aliases @twinsearth/fang-dsh-plugin in production profiles). */
|
|
21
|
+
export const FANG_NPM_BUNDLE = '@twinsearth/dsh-fang'
|
|
22
|
+
/** Published npm package name of this repo's bundle (post-build name; not renamed by build). */
|
|
23
|
+
export const FANG_PUBLISHED_BUNDLE = '@twinsearth/fang-dsh-plugin'
|
|
24
|
+
function isFangBundle(bundle) {
|
|
25
|
+
return bundle === FANG_BUNDLE || bundle === FANG_NPM_BUNDLE || bundle === FANG_PUBLISHED_BUNDLE
|
|
26
|
+
}
|
|
27
|
+
export const ACCEL_BUNDLES_WITH_FANG = Object.freeze([...ACCEL_BUNDLES, FANG_BUNDLE])
|
|
28
|
+
export const FANG_CHILD_PACKAGES = Object.freeze([
|
|
29
|
+
'@twinsearth/dsh-fang-web-entry',
|
|
30
|
+
'@twinsearth/dsh-fang-queue-journal',
|
|
31
|
+
])
|
|
32
|
+
export const OVERLAY_MARKER = '# dsh-Fang accelerated-fork model overlay (generated; do not edit by hand)'
|
|
33
|
+
export const OVERLAY_FILE = 'cordis.patch.yml'
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* 2026-11-22:fork profile 里 fang bundle 的**实际包名**以 fangRoot/package.json 为准。
|
|
37
|
+
* 发布构建会把源码里的 `@twinsearth/fang-dsh-plugin` 常量改名成发布名,而 junction 路径若写死
|
|
38
|
+
* `@twinsearth/fang-dsh-plugin` 就会与包名/bundle 行不一致 → 派生时报 fork-bundle-unavailable。
|
|
39
|
+
* 这里统一用包名(开发链 @twinsearth/fang-dsh-plugin / npm 安装 @twinsearth/fang-dsh-plugin)。
|
|
40
|
+
*/
|
|
41
|
+
export function fangBundleNameOf(fangRoot = '') {
|
|
42
|
+
try {
|
|
43
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(String(fangRoot ?? '').trim(), 'package.json'), 'utf8'))
|
|
44
|
+
const name = typeof pkg?.name === 'string' ? pkg.name.trim() : ''
|
|
45
|
+
if (/^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/i.test(name)) return name
|
|
46
|
+
} catch { /* fall back to dev alias */ }
|
|
47
|
+
return FANG_BUNDLE
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** @returns {{name:string, private:true, dsh:{profile:{bundles:string[]}}, dependencies:Record<string,string>}} */
|
|
51
|
+
export function buildAcceleratedForkProfile({ profileName = 'fang-accelerated', fangRoot = '' } = {}) {
|
|
52
|
+
const deps = {}
|
|
53
|
+
const fangBundle = fangRoot ? fangBundleNameOf(fangRoot) : FANG_BUNDLE
|
|
54
|
+
if (fangRoot) deps[fangBundle] = `link:${String(fangRoot).replace(/\\/g, '/')}`
|
|
55
|
+
return {
|
|
56
|
+
name: `dsh-profile-${String(profileName).replace(/[^a-z0-9._-]/gi, '-').toLowerCase()}`,
|
|
57
|
+
private: true,
|
|
58
|
+
dsh: { profile: { bundles: [...ACCEL_BUNDLES, fangBundle] } },
|
|
59
|
+
dependencies: deps,
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Rewrite the stock package scope to the accelerated core's scope. */
|
|
64
|
+
export function rewriteScope(text) {
|
|
65
|
+
return String(text ?? '').replace(/@deepseek-ai\/dsh-/g, '@twinsearth/dsh-')
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Build the home-level model overlay for the accelerated fork.
|
|
70
|
+
* The mother's home patch defines providers with @deepseek-ai/* names; the
|
|
71
|
+
* accelerated core resolves @twinsearth/* names, so the same rows would be
|
|
72
|
+
* skipped ("name mismatch"). Rewriting the scope makes the config apply.
|
|
73
|
+
* @returns {{ok:boolean, text?:string, error?:string, source?:string}}
|
|
74
|
+
*/
|
|
75
|
+
export function buildModelOverlay({ motherHome = '', readImpl = fs.readFileSync } = {}) {
|
|
76
|
+
const source = path.join(String(motherHome ?? '').trim(), OVERLAY_FILE)
|
|
77
|
+
let text = ''
|
|
78
|
+
try {
|
|
79
|
+
text = String(readImpl(source, 'utf8'))
|
|
80
|
+
} catch {
|
|
81
|
+
return { ok: false, error: 'mother-home-patch-missing', source }
|
|
82
|
+
}
|
|
83
|
+
const rewritten = rewriteScope(text)
|
|
84
|
+
if (!rewritten.trim()) return { ok: false, error: 'mother-home-patch-empty', source }
|
|
85
|
+
return { ok: true, text: `${OVERLAY_MARKER}\n${rewritten.replace(/^\uFEFF/, '')}`, source }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// ── D2 hybrid: alias/shim layer for third-party plugin compatibility ──────────
|
|
89
|
+
// Stock-core plugins import `@deepseek-ai/dsh-*`; the accelerated core ships
|
|
90
|
+
// `@twinsearth/dsh-*` with the same module layout. We therefore materialise the
|
|
91
|
+
// source profile's plugin surface in the accelerated fork and add alias stubs so
|
|
92
|
+
// Node's resolver hands those plugins the accelerated implementation.
|
|
93
|
+
export const DEEPSEEK_SCOPE = '@deepseek-ai/'
|
|
94
|
+
export const ACCEL_SCOPE = '@twinsearth/'
|
|
95
|
+
export const ALIAS_STUB_VERSION = '0.0.0-fang-alias'
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Disposition of known `@deepseek-ai/*` specs that have no accelerated equivalent.
|
|
99
|
+
* Established by source attribution (2026-11-17): these are client-half/devDependency
|
|
100
|
+
* declarations, desktop-app string references, or metadata-only peer declarations —
|
|
101
|
+
* NOT host-side runtime imports. See docs/ACCEL-FORK-COMPAT.md §3.5.
|
|
102
|
+
*/
|
|
103
|
+
export const ALIAS_DISPOSITIONS = Object.freeze({
|
|
104
|
+
'@deepseek-ai/dsh-client-runtime': 'client-half',
|
|
105
|
+
'@deepseek-ai/dsh-client-store': 'client-half',
|
|
106
|
+
'@deepseek-ai/dsh-client-ui-primitives': 'client-half',
|
|
107
|
+
'@deepseek-ai/dsh-desktop': 'desktop-only',
|
|
108
|
+
'@deepseek-ai/dsh-desktop-runtime': 'desktop-only',
|
|
109
|
+
'@deepseek-ai/dsh-invariants': 'dev-metadata',
|
|
110
|
+
'@deepseek-ai/dsh-code-runtime': 'optional-metadata',
|
|
111
|
+
'@deepseek-ai/dsh-tool-lsp': 'string-reference',
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
/** Category for a spec without an accelerated equivalent. */
|
|
115
|
+
export function classifyAliasSpec(spec) {
|
|
116
|
+
return ALIAS_DISPOSITIONS[String(spec ?? '')] ?? 'unknown'
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function readJsonFile(file) {
|
|
120
|
+
try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return null }
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Does the accelerated module tree ship `@twinsearth/<name>`? */
|
|
124
|
+
export function accelHasPackage(accelNodeModules, name) {
|
|
125
|
+
const root = String(accelNodeModules ?? '').trim()
|
|
126
|
+
if (!root) return false
|
|
127
|
+
return fs.existsSync(path.join(root, ...String(name).split('/'), 'package.json'))
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Translate a stock bundle list to accelerated bundles.
|
|
132
|
+
* Official packages without an accelerated equivalent are reported, never silently dropped.
|
|
133
|
+
* @returns {{bundles:string[], mapped:object[], unsupported:object[]}}
|
|
134
|
+
*/
|
|
135
|
+
export function translateBundles(bundles, { accelNodeModules = '' } = {}) {
|
|
136
|
+
const result = { bundles: [], mapped: [], unsupported: [] }
|
|
137
|
+
const seen = new Set()
|
|
138
|
+
for (const raw of Array.isArray(bundles) ? bundles : []) {
|
|
139
|
+
const bundle = String(raw ?? '').trim()
|
|
140
|
+
if (!bundle || seen.has(bundle)) continue
|
|
141
|
+
if (isFangBundle(bundle)) continue // handled by the fang junctions
|
|
142
|
+
if (bundle.startsWith(DEEPSEEK_SCOPE)) {
|
|
143
|
+
const accel = `${ACCEL_SCOPE}${bundle.slice(DEEPSEEK_SCOPE.length)}`
|
|
144
|
+
if (accelHasPackage(accelNodeModules, accel)) {
|
|
145
|
+
seen.add(bundle)
|
|
146
|
+
result.bundles.push(accel)
|
|
147
|
+
result.mapped.push({ from: bundle, to: accel })
|
|
148
|
+
} else {
|
|
149
|
+
result.unsupported.push({ bundle, reason: 'no-accelerated-equivalent' })
|
|
150
|
+
}
|
|
151
|
+
continue
|
|
152
|
+
}
|
|
153
|
+
seen.add(bundle)
|
|
154
|
+
result.bundles.push(bundle)
|
|
155
|
+
}
|
|
156
|
+
return result
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Recursively collect `@deepseek-ai/dsh-*` import specifiers used by a plugin tree. */
|
|
160
|
+
export function scanDeepseekSpecs(dir, out = new Set()) {
|
|
161
|
+
let entries
|
|
162
|
+
try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { return out }
|
|
163
|
+
for (const entry of entries) {
|
|
164
|
+
if (entry.name === 'node_modules') continue
|
|
165
|
+
const full = path.join(dir, entry.name)
|
|
166
|
+
if (entry.isDirectory()) { scanDeepseekSpecs(full, out); continue }
|
|
167
|
+
if (!/\.(?:mjs|cjs|js|json)$/i.test(entry.name)) continue
|
|
168
|
+
let text = ''
|
|
169
|
+
try { text = fs.readFileSync(full, 'utf8') } catch { continue }
|
|
170
|
+
for (const match of text.matchAll(/@deepseek-ai\/dsh-[a-z0-9-]+(?:\/[a-z0-9\-/]+)?/g)) out.add(match[0])
|
|
171
|
+
}
|
|
172
|
+
return out
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function accelExportFile(accelNodeModules, spec) {
|
|
176
|
+
const parts = String(spec).split('/')
|
|
177
|
+
const name = parts[1]
|
|
178
|
+
const sub = parts.slice(2).join('/')
|
|
179
|
+
const pkg = readJsonFile(path.join(accelNodeModules, '@twinsearth', name, 'package.json'))
|
|
180
|
+
if (!pkg) return null
|
|
181
|
+
const key = sub ? `./${sub}` : '.'
|
|
182
|
+
const value = pkg.exports?.[key]
|
|
183
|
+
const target = typeof value === 'string' ? value : (value?.default ?? value?.import ?? value?.require)
|
|
184
|
+
if (!target) return null
|
|
185
|
+
const file = path.join(accelNodeModules, '@twinsearth', name, target)
|
|
186
|
+
return fs.existsSync(file) ? file : null
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Write `@deepseek-ai/*` alias stub packages that re-export the accelerated modules.
|
|
191
|
+
* @returns {{resolved:object[], unsupported:object[], stubCount:number}}
|
|
192
|
+
*/
|
|
193
|
+
export function writeAliasStubs({ profileNodeModules = '', accelNodeModules = '', specs = [] } = {}) {
|
|
194
|
+
const resolved = []
|
|
195
|
+
const unsupported = []
|
|
196
|
+
const byPackage = new Map()
|
|
197
|
+
for (const spec of [...new Set(specs)].sort()) {
|
|
198
|
+
const parts = String(spec).split('/')
|
|
199
|
+
if (parts.length < 2 || !parts[1]) continue
|
|
200
|
+
const name = parts[1]
|
|
201
|
+
const sub = parts.slice(2).join('/')
|
|
202
|
+
const accelFile = accelExportFile(accelNodeModules, spec)
|
|
203
|
+
if (!accelFile) {
|
|
204
|
+
unsupported.push({ spec, reason: accelHasPackage(accelNodeModules, name) ? 'no-export-mapping' : 'no-accelerated-equivalent', category: classifyAliasSpec(spec) })
|
|
205
|
+
continue
|
|
206
|
+
}
|
|
207
|
+
if (!byPackage.has(name)) byPackage.set(name, [])
|
|
208
|
+
byPackage.get(name).push({ spec, sub, accelFile })
|
|
209
|
+
}
|
|
210
|
+
let stubCount = 0
|
|
211
|
+
for (const [name, entries] of byPackage) {
|
|
212
|
+
const stubDir = path.join(profileNodeModules, '@deepseek-ai', name)
|
|
213
|
+
fs.mkdirSync(stubDir, { recursive: true })
|
|
214
|
+
const exportsMap = {}
|
|
215
|
+
for (const entry of entries) {
|
|
216
|
+
const rel = entry.sub ? `${entry.sub.replace(/[\\/]/g, '_')}.js` : 'index.js'
|
|
217
|
+
const file = path.join(stubDir, rel)
|
|
218
|
+
const target = pathToFileURL(entry.accelFile).href
|
|
219
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
220
|
+
writeFileAtomic(file,
|
|
221
|
+
`// fang alias stub: ${entry.spec} -> ${ACCEL_SCOPE}${name}${entry.sub ? `/${entry.sub}` : ''}\n` +
|
|
222
|
+
`export * from ${JSON.stringify(target)}\n` +
|
|
223
|
+
`import * as NS from ${JSON.stringify(target)}\n` +
|
|
224
|
+
`export default NS\n`)
|
|
225
|
+
exportsMap[entry.sub ? `./${entry.sub}` : '.'] = `./${rel}`
|
|
226
|
+
stubCount += 1
|
|
227
|
+
resolved.push({ spec: entry.spec, accel: `${ACCEL_SCOPE}${name}${entry.sub ? `/${entry.sub}` : ''}` })
|
|
228
|
+
}
|
|
229
|
+
writeFileAtomic(path.join(stubDir, 'package.json'), `${JSON.stringify({
|
|
230
|
+
name: `${DEEPSEEK_SCOPE}${name}`,
|
|
231
|
+
version: ALIAS_STUB_VERSION,
|
|
232
|
+
private: true,
|
|
233
|
+
type: 'module',
|
|
234
|
+
exports: exportsMap,
|
|
235
|
+
}, null, 2)}\n`)
|
|
236
|
+
}
|
|
237
|
+
return { resolved, unsupported, stubCount }
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Remove `@deepseek-ai/*` alias stubs written by writeAliasStubs().
|
|
242
|
+
*
|
|
243
|
+
* Why: a fork can switch core (`syncForkCoreMode`). An accelerated fork owns alias stubs
|
|
244
|
+
* that shadow the installation's real `@deepseek-ai/*` packages; switching it back to the
|
|
245
|
+
* stock CLI must delete those stubs, otherwise the stock host imports the accelerated
|
|
246
|
+
* modules (and any subpath the stub never mapped, e.g. `dsh-tool-subagent/model-selection-settings`,
|
|
247
|
+
* fails with ERR_PACKAGE_PATH_NOT_EXPORTED → startup-abort → "spawn-failed/exited" on restore).
|
|
248
|
+
*
|
|
249
|
+
* Only packages whose package.json carries ALIAS_STUB_VERSION are removed; real packages
|
|
250
|
+
* (including a user's own @deepseek-ai deps) are never touched.
|
|
251
|
+
* @returns {{ok:boolean, removed:string[]}}
|
|
252
|
+
*/
|
|
253
|
+
export function pruneAliasStubs(profileDir) {
|
|
254
|
+
const removed = []
|
|
255
|
+
const profile = String(profileDir ?? '').trim()
|
|
256
|
+
if (!profile) return { ok: false, removed }
|
|
257
|
+
const scopeDir = path.join(profile, 'node_modules', '@deepseek-ai')
|
|
258
|
+
let entries = []
|
|
259
|
+
try { entries = fs.readdirSync(scopeDir, { withFileTypes: true }) } catch { return { ok: true, removed } }
|
|
260
|
+
for (const entry of entries) {
|
|
261
|
+
if (!entry || typeof entry.isDirectory !== 'function' || !entry.isDirectory()) continue
|
|
262
|
+
const pkgDir = path.join(scopeDir, entry.name)
|
|
263
|
+
const pkg = readJsonFile(path.join(pkgDir, 'package.json'))
|
|
264
|
+
if (pkg?.version !== ALIAS_STUB_VERSION) continue
|
|
265
|
+
try {
|
|
266
|
+
fs.rmSync(pkgDir, { recursive: true, force: true })
|
|
267
|
+
removed.push(entry.name)
|
|
268
|
+
} catch { /* best-effort: a locked stub must not abort the start */ }
|
|
269
|
+
}
|
|
270
|
+
if (removed.length > 0) {
|
|
271
|
+
try {
|
|
272
|
+
if (fs.readdirSync(scopeDir).length === 0) fs.rmdirSync(scopeDir)
|
|
273
|
+
} catch { /* ignore */ }
|
|
274
|
+
}
|
|
275
|
+
return { ok: true, removed }
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* 2026-11-22: the accelerated core 3.5.0 session-format migration only accepts
|
|
280
|
+
* `subagent/catalog` facts with version 0/1/2. A stock-DSH session imported into an
|
|
281
|
+
* accelerated fork can carry version 3, which makes the fork's session reader fail with
|
|
282
|
+
* `SessionFormatError: subagent/catalog requires a supported versioned catalog fact`.
|
|
283
|
+
*
|
|
284
|
+
* Downgrade version 3+ catalog events to the equivalent version 1/2 fact, frame-preserving:
|
|
285
|
+
* only frames containing such events are re-compressed; every other frame keeps its exact bytes.
|
|
286
|
+
* @returns {{ok:boolean, changedEvents:number, changedFrames:number, backup?:string, error?:string}}
|
|
287
|
+
*/
|
|
288
|
+
export function downgradeSubagentCatalogLog(logFile, { backup = true, knownEventTypes = null } = {}) {
|
|
289
|
+
const file = String(logFile ?? '').trim()
|
|
290
|
+
if (!file) return { ok: false, changedEvents: 0, changedFrames: 0, error: 'no-log-file' }
|
|
291
|
+
const known = knownEventTypes instanceof Set
|
|
292
|
+
? knownEventTypes
|
|
293
|
+
: new Set(Array.isArray(knownEventTypes) ? knownEventTypes : [])
|
|
294
|
+
let buf
|
|
295
|
+
try { buf = fs.readFileSync(file) } catch (error) { return { ok: false, changedEvents: 0, changedFrames: 0, error: String(error?.message ?? error) } }
|
|
296
|
+
const MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd])
|
|
297
|
+
const offsets = []
|
|
298
|
+
for (let i = 0; (i = buf.indexOf(MAGIC, i)) !== -1; i += 4) offsets.push(i)
|
|
299
|
+
if (offsets.length === 0 || offsets[0] !== 0) return { ok: false, changedEvents: 0, changedFrames: 0, error: 'not-frame-log' }
|
|
300
|
+
const frames = []
|
|
301
|
+
let changedFrames = 0
|
|
302
|
+
let changedEvents = 0
|
|
303
|
+
let markedIgnorable = 0
|
|
304
|
+
let strippedFields = 0
|
|
305
|
+
for (let k = 0; k < offsets.length; k++) {
|
|
306
|
+
const raw = buf.subarray(offsets[k], k + 1 < offsets.length ? offsets[k + 1] : buf.length)
|
|
307
|
+
const text = zlib.zstdDecompressSync(raw).toString('utf8')
|
|
308
|
+
const lines = text.split('\n')
|
|
309
|
+
let changed = false
|
|
310
|
+
for (let i = 0; i < lines.length; i++) {
|
|
311
|
+
const line = lines[i]
|
|
312
|
+
if (!line.trim()) continue
|
|
313
|
+
let event
|
|
314
|
+
try { event = JSON.parse(line) } catch { continue }
|
|
315
|
+
if (event?.type === 'subagent/catalog' && event.data && typeof event.data === 'object') {
|
|
316
|
+
const version = Number(event.data.version)
|
|
317
|
+
if (version > 2) {
|
|
318
|
+
const mode = event.data.mode === 'external' ? 'external' : (event.data.mode === 'one-shot' ? 'one-shot' : 'continuable')
|
|
319
|
+
event.data.version = mode === 'external' ? 2 : 1
|
|
320
|
+
event.data.mode = mode
|
|
321
|
+
if (mode === 'continuable' && typeof event.data.label !== 'string') event.data.label = ''
|
|
322
|
+
changed = true
|
|
323
|
+
changedEvents += 1
|
|
324
|
+
}
|
|
325
|
+
// v1/v2 schema is strict: `name` was introduced with v3 and is an unrecognized key
|
|
326
|
+
// for the accelerated core's projection (2026-11-22: unrecognized_keys "name").
|
|
327
|
+
if (event.data.name !== undefined) {
|
|
328
|
+
delete event.data.name
|
|
329
|
+
changed = true
|
|
330
|
+
strippedFields += 1
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
// The accelerated core refuses event types it does not know unless the writer marks
|
|
334
|
+
// them ignorable. Stock DSH adds new event types (e.g. team/mode) first; a fork must
|
|
335
|
+
// still be able to read the copied history, so mark only unknown-to-accelerated events.
|
|
336
|
+
const fallbackIgnorable = new Set(['team/mode', 'team/task', 'team/status', 'deliverables/presented'])
|
|
337
|
+
if (fallbackIgnorable.has(event.type) && (known.size === 0 || !known.has(event.type)) && event.ignorable !== true) {
|
|
338
|
+
event.ignorable = true
|
|
339
|
+
changed = true
|
|
340
|
+
markedIgnorable += 1
|
|
341
|
+
}
|
|
342
|
+
if (changed) lines[i] = JSON.stringify(event)
|
|
343
|
+
}
|
|
344
|
+
if (!changed) { frames.push(raw); continue }
|
|
345
|
+
frames.push(zlib.zstdCompressSync(Buffer.from(lines.join('\n'), 'utf8')))
|
|
346
|
+
changedFrames += 1
|
|
347
|
+
}
|
|
348
|
+
if (changedEvents === 0 && markedIgnorable === 0 && strippedFields === 0) return { ok: true, changedEvents: 0, changedFrames: 0, markedIgnorable: 0, strippedFields: 0 }
|
|
349
|
+
const backupFile = backup ? `${file}.bak-catalogv3-${Date.now()}` : ''
|
|
350
|
+
if (backup) fs.copyFileSync(file, backupFile)
|
|
351
|
+
const tmp = `${file}.tmp-catalogv3-${process.pid}`
|
|
352
|
+
fs.writeFileSync(tmp, Buffer.concat(frames))
|
|
353
|
+
// Verify: still decodable and header frame unchanged; abandon on any mismatch.
|
|
354
|
+
try {
|
|
355
|
+
const verify = fs.readFileSync(tmp)
|
|
356
|
+
const voffs = []
|
|
357
|
+
for (let i = 0; (i = verify.indexOf(MAGIC, i)) !== -1; i += 4) voffs.push(i)
|
|
358
|
+
const header = zlib.zstdDecompressSync(verify.subarray(voffs[0], voffs[1] ?? verify.length)).toString('utf8')
|
|
359
|
+
const originalHeader = zlib.zstdDecompressSync(buf.subarray(offsets[0], offsets[1] ?? buf.length)).toString('utf8')
|
|
360
|
+
if (header !== originalHeader) throw new Error('header-frame-changed')
|
|
361
|
+
for (let k = 0; k < voffs.length; k++) {
|
|
362
|
+
zlib.zstdDecompressSync(verify.subarray(voffs[k], k + 1 < voffs.length ? voffs[k + 1] : verify.length))
|
|
363
|
+
}
|
|
364
|
+
} catch (error) {
|
|
365
|
+
try { fs.rmSync(tmp, { force: true }) } catch { /* ignore */ }
|
|
366
|
+
return { ok: false, changedEvents: 0, changedFrames: 0, error: String(error?.message ?? error) }
|
|
367
|
+
}
|
|
368
|
+
fs.renameSync(tmp, file)
|
|
369
|
+
return { ok: true, changedEvents, changedFrames, markedIgnorable, strippedFields, ...(backupFile ? { backup: backupFile } : {}) }
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Resolve the accelerated core's supported event vocabulary from its installed
|
|
374
|
+
* `@twinsearth/dsh-session` package (dynamic import, cached by Node).
|
|
375
|
+
* @returns {Promise<Set<string>|null>}
|
|
376
|
+
*/
|
|
377
|
+
export async function loadAcceleratedKnownEventTypes(accelNodeModules) {
|
|
378
|
+
const root = String(accelNodeModules ?? '').trim()
|
|
379
|
+
if (!root) return null
|
|
380
|
+
const file = path.join(root, '@twinsearth', 'dsh-session', 'lib', 'index.js')
|
|
381
|
+
if (!fs.existsSync(file)) return null
|
|
382
|
+
try {
|
|
383
|
+
const mod = await import(pathToFileURL(file).href)
|
|
384
|
+
const value = mod?.KNOWN_SESSION_EVENT_TYPES
|
|
385
|
+
if (value instanceof Set) return value
|
|
386
|
+
if (Array.isArray(value)) return new Set(value)
|
|
387
|
+
} catch { /* accelerated core unavailable: caller falls back to catalog-only compat */ }
|
|
388
|
+
return null
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* Walk a fork's own `$DSH_HOME/sessions` and downgrade legacy catalog facts so an
|
|
393
|
+
* accelerated core can read sessions imported from a stock mother.
|
|
394
|
+
*/
|
|
395
|
+
export function sanitizeAcceleratedForkSessions(homeDir, options = {}) {
|
|
396
|
+
const root = path.join(String(homeDir ?? '').trim(), 'sessions')
|
|
397
|
+
const result = { ok: true, files: [], changedEvents: 0, changedFrames: 0 }
|
|
398
|
+
let workspaces = []
|
|
399
|
+
try { workspaces = fs.readdirSync(root, { withFileTypes: true }) } catch { return result }
|
|
400
|
+
for (const workspace of workspaces) {
|
|
401
|
+
if (!workspace.isDirectory()) continue
|
|
402
|
+
let sessions = []
|
|
403
|
+
try { sessions = fs.readdirSync(path.join(root, workspace.name), { withFileTypes: true }) } catch { continue }
|
|
404
|
+
for (const session of sessions) {
|
|
405
|
+
if (!session.isDirectory()) continue
|
|
406
|
+
const logFile = path.join(root, workspace.name, session.name, 'session.v4.jsonl.zstd')
|
|
407
|
+
if (!fs.existsSync(logFile)) continue
|
|
408
|
+
const downgraded = downgradeSubagentCatalogLog(logFile, options)
|
|
409
|
+
if (downgraded.changedEvents > 0 || downgraded.markedIgnorable > 0 || downgraded.strippedFields > 0) {
|
|
410
|
+
result.files.push({ sessionId: session.name, workspace: workspace.name, ...downgraded })
|
|
411
|
+
result.changedEvents += downgraded.changedEvents
|
|
412
|
+
result.changedFrames += downgraded.changedFrames
|
|
413
|
+
} else if (downgraded.ok === false) {
|
|
414
|
+
result.ok = false
|
|
415
|
+
result.files.push({ sessionId: session.name, workspace: workspace.name, ok: false, error: downgraded.error })
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
return result
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Client halves resolved by the accelerated web shell as *static* modules (the shell's
|
|
424
|
+
* `staticModules` table), not as `@twinsearth` packages. Kept explicit: the accelerated
|
|
425
|
+
* client bundles require these exact names, so a third-party bundle rewritten to them works
|
|
426
|
+
* without an extra client row.
|
|
427
|
+
*/
|
|
428
|
+
export const STATIC_CLIENT_MODULES = Object.freeze([
|
|
429
|
+
'@twinsearth/dsh-client-ui-primitives',
|
|
430
|
+
'@twinsearth/dsh-client-store',
|
|
431
|
+
'@twinsearth/dsh-client-ui-slots',
|
|
432
|
+
'@twinsearth/dsh-client-ui-dockkit',
|
|
433
|
+
])
|
|
434
|
+
|
|
435
|
+
/** Every browser-module id the accelerated fork can satisfy for a client half. */
|
|
436
|
+
export function availableClientModules(accelNodeModules) {
|
|
437
|
+
const available = new Set(STATIC_CLIENT_MODULES)
|
|
438
|
+
try {
|
|
439
|
+
const scopeDir = path.join(accelNodeModules, ACCEL_SCOPE.slice(0, -1))
|
|
440
|
+
for (const entry of fs.readdirSync(scopeDir)) {
|
|
441
|
+
const dir = path.join(scopeDir, entry)
|
|
442
|
+
let pkg = null
|
|
443
|
+
try { pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')) } catch { pkg = null }
|
|
444
|
+
const hasClient = (pkg?.dsh?.client && typeof pkg.dsh.client === 'object')
|
|
445
|
+
|| Boolean(pkg?.exports?.['./client'])
|
|
446
|
+
|| fs.existsSync(path.join(dir, 'lib', 'client.js'))
|
|
447
|
+
if (hasClient) available.add(`${ACCEL_SCOPE}${entry}`)
|
|
448
|
+
}
|
|
449
|
+
} catch { /* best effort: static table still applies */ }
|
|
450
|
+
return available
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* Rewrite `@deepseek-ai/*` browser-module specifiers to the accelerated scope for client
|
|
455
|
+
* halves. Only specs with an accelerated counterpart are rewritten; the rest are reported
|
|
456
|
+
* verbatim so the UI can list unsupported client halves explicitly (never silent).
|
|
457
|
+
*/
|
|
458
|
+
export function rewriteClientSpecifiers(text, available = new Set()) {
|
|
459
|
+
const mapped = []
|
|
460
|
+
const unsupported = []
|
|
461
|
+
const output = String(text ?? '').replace(/@deepseek-ai\/([a-z0-9][a-z0-9-]*)/giu, (spec, name) => {
|
|
462
|
+
const target = `${ACCEL_SCOPE}${name}`
|
|
463
|
+
if (available.has(target)) {
|
|
464
|
+
mapped.push({ from: `@deepseek-ai/${name}`, to: target })
|
|
465
|
+
return target
|
|
466
|
+
}
|
|
467
|
+
unsupported.push(spec)
|
|
468
|
+
return spec
|
|
469
|
+
})
|
|
470
|
+
return { text: output, mapped, unsupported: [...new Set(unsupported)] }
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
function clientEntryFiles(pluginDir, pkgJson) {
|
|
474
|
+
const files = new Set()
|
|
475
|
+
const clientExport = pkgJson?.exports?.['./client']
|
|
476
|
+
const pick = typeof clientExport === 'string'
|
|
477
|
+
? clientExport
|
|
478
|
+
: (clientExport && typeof clientExport === 'object' ? clientExport.default ?? clientExport.import ?? '' : '')
|
|
479
|
+
if (typeof pick === 'string' && pick) files.add(path.resolve(pluginDir, pick))
|
|
480
|
+
const fallback = path.join(pluginDir, 'lib', 'client.js')
|
|
481
|
+
if (fs.existsSync(fallback)) files.add(fallback)
|
|
482
|
+
return [...files].filter((file) => {
|
|
483
|
+
try { return fs.statSync(file).isFile() } catch { return false }
|
|
484
|
+
})
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/**
|
|
488
|
+
* Rewrite a copied third-party plugin's browser side: `dsh.client.inject` / `external`
|
|
489
|
+
* declarations and its `./client` bundle specifiers. Package files are copied first, so this
|
|
490
|
+
* only touches the fork's private copy.
|
|
491
|
+
*/
|
|
492
|
+
export function rewriteClientHalfPackage({ pluginDir = '', available = new Set() } = {}) {
|
|
493
|
+
const pkgFile = path.join(pluginDir, 'package.json')
|
|
494
|
+
let pkg = null
|
|
495
|
+
try { pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf8')) } catch { return null }
|
|
496
|
+
const mapped = []
|
|
497
|
+
const unsupported = []
|
|
498
|
+
const declaration = pkg?.dsh?.client
|
|
499
|
+
let declarationChanged = false
|
|
500
|
+
if (declaration && typeof declaration === 'object') {
|
|
501
|
+
for (const field of ['inject', 'external']) {
|
|
502
|
+
if (!Array.isArray(declaration[field])) continue
|
|
503
|
+
const rewritten = declaration[field].map((spec) => {
|
|
504
|
+
const result = rewriteClientSpecifiers(spec, available)
|
|
505
|
+
mapped.push(...result.mapped)
|
|
506
|
+
unsupported.push(...result.unsupported)
|
|
507
|
+
if (result.text !== spec) declarationChanged = true
|
|
508
|
+
return result.text
|
|
509
|
+
})
|
|
510
|
+
declaration[field] = [...new Set(rewritten)]
|
|
511
|
+
}
|
|
512
|
+
if (declarationChanged) fs.writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`)
|
|
513
|
+
}
|
|
514
|
+
const clientFiles = clientEntryFiles(pluginDir, pkg)
|
|
515
|
+
for (const file of clientFiles) {
|
|
516
|
+
let text = ''
|
|
517
|
+
try { text = fs.readFileSync(file, 'utf8') } catch { continue }
|
|
518
|
+
const result = rewriteClientSpecifiers(text, available)
|
|
519
|
+
mapped.push(...result.mapped)
|
|
520
|
+
unsupported.push(...result.unsupported)
|
|
521
|
+
if (result.text !== text) fs.writeFileSync(file, result.text)
|
|
522
|
+
}
|
|
523
|
+
const dedupe = (items) => [...new Map(items.map((item) => [JSON.stringify(item), item])).values()]
|
|
524
|
+
return {
|
|
525
|
+
package: typeof pkg?.name === 'string' ? pkg.name : path.basename(pluginDir),
|
|
526
|
+
mapped: dedupe(mapped),
|
|
527
|
+
unsupported: [...new Set(unsupported)],
|
|
528
|
+
clientFiles: clientFiles.map((file) => path.relative(pluginDir, file).replace(/\\/g, '/')),
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
/**
|
|
533
|
+
* Profile rows disabled in the source (desktop-shell supplied equivalents) that the
|
|
534
|
+
* accelerated *web* composition still needs. Enabling them is a deliberate, named
|
|
535
|
+
* override — never a blanket "enable every disabled client row".
|
|
536
|
+
*/
|
|
537
|
+
export const CLIENT_ROW_ENABLE_OVERRIDES = Object.freeze([
|
|
538
|
+
{ id: 'ui-theme', reason: 'desktop shell supplies theme; accelerated web composition provides it as the theme client half' },
|
|
539
|
+
])
|
|
540
|
+
|
|
541
|
+
/** Re-enable the named client rows in a profile patch (JSON/JSON-array text). */
|
|
542
|
+
export function applyClientRowOverrides(patchText) {
|
|
543
|
+
const original = String(patchText ?? '')
|
|
544
|
+
const applied = []
|
|
545
|
+
let parsed = null
|
|
546
|
+
try { parsed = JSON.parse(original) } catch { parsed = null }
|
|
547
|
+
if (parsed !== null) {
|
|
548
|
+
const targetIds = new Set(CLIENT_ROW_ENABLE_OVERRIDES.map((override) => override.id))
|
|
549
|
+
const walk = (node) => {
|
|
550
|
+
if (Array.isArray(node)) { for (const item of node) walk(item); return }
|
|
551
|
+
if (!node || typeof node !== 'object') return
|
|
552
|
+
if (targetIds.has(node.id) && node.disabled === true) {
|
|
553
|
+
node.disabled = false
|
|
554
|
+
applied.push({ id: node.id, reason: CLIENT_ROW_ENABLE_OVERRIDES.find((override) => override.id === node.id)?.reason ?? '' })
|
|
555
|
+
}
|
|
556
|
+
for (const value of Object.values(node)) walk(value)
|
|
557
|
+
}
|
|
558
|
+
walk(parsed)
|
|
559
|
+
if (applied.length) return { text: JSON.stringify(parsed, null, 2), applied }
|
|
560
|
+
return { text: original, applied }
|
|
561
|
+
}
|
|
562
|
+
let text = original
|
|
563
|
+
for (const override of CLIENT_ROW_ENABLE_OVERRIDES) {
|
|
564
|
+
const escaped = override.id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
565
|
+
const blockPattern = new RegExp(`(\\{[^{}]*"id"\\s*:\\s*"${escaped}"\\s*,?[^{}]*?\\})`, 'g')
|
|
566
|
+
text = text.replace(blockPattern, (block) => {
|
|
567
|
+
if (!/"disabled"\s*:\s*true/.test(block)) return block
|
|
568
|
+
applied.push({ id: override.id, reason: override.reason })
|
|
569
|
+
return block.replace(/"disabled"\s*:\s*true/, '"disabled": false')
|
|
570
|
+
})
|
|
571
|
+
}
|
|
572
|
+
return { text, applied }
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/** 路线 B(增强):fork-local LSP 所需的加速核 client/host 包。 */
|
|
576
|
+
export const FORK_LSP_PACKAGES = Object.freeze([
|
|
577
|
+
'@twinsearth/dsh-lsp',
|
|
578
|
+
'@twinsearth/dsh-lsp-stdio',
|
|
579
|
+
'@twinsearth/dsh-tool-lsp',
|
|
580
|
+
])
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
* Detect whether the accelerated core can host a fork-local LSP stack (route B).
|
|
584
|
+
* Detection only — provisioning stays opt-in; absent packages mean the fork keeps
|
|
585
|
+
* delegating to the mother (route A) or reporting contract-unavailable.
|
|
586
|
+
*/
|
|
587
|
+
export function detectForkLspSupport(accelNodeModules) {
|
|
588
|
+
const packages = FORK_LSP_PACKAGES.map((name) => ({ name, installed: accelHasPackage(accelNodeModules, name) }))
|
|
589
|
+
const missing = packages.filter((item) => item.installed !== true).map((item) => item.name)
|
|
590
|
+
return { available: missing.length === 0, packages, missing }
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
function copyPackageDir(source, target) {
|
|
594
|
+
fs.mkdirSync(target, { recursive: true })
|
|
595
|
+
for (const entry of fs.readdirSync(source, { withFileTypes: true })) {
|
|
596
|
+
if (entry.name === 'node_modules') continue
|
|
597
|
+
const src = path.join(source, entry.name)
|
|
598
|
+
const dst = path.join(target, entry.name)
|
|
599
|
+
if (entry.isDirectory()) copyPackageDir(src, dst)
|
|
600
|
+
else fs.copyFileSync(src, dst)
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* Build the accelerated profile package + patch for a source (essence/mother) profile,
|
|
606
|
+
* copying third-party plugin packages into the fork profile and linking the rest of
|
|
607
|
+
* the source module tree by junction. Returns metadata for the sync report.
|
|
608
|
+
*/
|
|
609
|
+
export function buildSyncedAcceleratedProfile({ sourceProfileDir = '', accelNodeModules = '', fangRoot = '', profileName = 'fang-accelerated' } = {}) {
|
|
610
|
+
const source = path.resolve(String(sourceProfileDir ?? '').trim() || '.')
|
|
611
|
+
const sourcePkg = readJsonFile(path.join(source, 'package.json'))
|
|
612
|
+
if (!sourcePkg || !sourcePkg.dsh?.profile) return { ok: false, error: 'source-profile-invalid', source }
|
|
613
|
+
const accel = String(accelNodeModules ?? '').trim()
|
|
614
|
+
if (!accel) return { ok: false, error: 'accel-node-modules-missing' }
|
|
615
|
+
const translated = translateBundles(sourcePkg.dsh.profile.bundles, { accelNodeModules: accel })
|
|
616
|
+
const deps = {}
|
|
617
|
+
for (const [name, version] of Object.entries(sourcePkg.dependencies ?? {})) {
|
|
618
|
+
if (name.startsWith(DEEPSEEK_SCOPE)) continue
|
|
619
|
+
if (isFangBundle(name)) continue
|
|
620
|
+
deps[name] = version
|
|
621
|
+
}
|
|
622
|
+
if (fangRoot) deps[fangBundleNameOf(fangRoot)] = `link:${path.resolve(fangRoot).replace(/\\/g, '/')}`
|
|
623
|
+
const fangBundle = fangRoot ? fangBundleNameOf(fangRoot) : FANG_BUNDLE
|
|
624
|
+
const pkg = {
|
|
625
|
+
name: `dsh-profile-${String(profileName).replace(/[^a-z0-9._-]/gi, '-').toLowerCase()}`,
|
|
626
|
+
private: true,
|
|
627
|
+
dsh: { profile: { bundles: [...translated.bundles, ...(fangRoot ? [fangBundle] : [])] } },
|
|
628
|
+
dependencies: deps,
|
|
629
|
+
}
|
|
630
|
+
const sourcePatchFile = path.join(source, OVERLAY_FILE)
|
|
631
|
+
let patchText = ''
|
|
632
|
+
try { patchText = String(fs.readFileSync(sourcePatchFile, 'utf8')) } catch { patchText = '' }
|
|
633
|
+
patchText = rewriteScope(patchText).replace(/^\uFEFF/, '')
|
|
634
|
+
const rowOverrides = applyClientRowOverrides(patchText)
|
|
635
|
+
patchText = rowOverrides.text
|
|
636
|
+
if (patchText.trim().startsWith('{')) patchText = `[${patchText}]`
|
|
637
|
+
if (!patchText.trim()) patchText = '[]\n'
|
|
638
|
+
return {
|
|
639
|
+
ok: true,
|
|
640
|
+
package: pkg,
|
|
641
|
+
patchText,
|
|
642
|
+
source,
|
|
643
|
+
bundles: { translated: translated.bundles, mapped: translated.mapped, unsupported: translated.unsupported },
|
|
644
|
+
pluginPackages: translated.bundles.filter((bundle) => !bundle.startsWith(ACCEL_SCOPE) && !isFangBundle(bundle)),
|
|
645
|
+
deps,
|
|
646
|
+
rowOverrides: rowOverrides.applied,
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
function writeFileAtomic(file, content) {
|
|
651
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
652
|
+
const tmp = `${file}.tmp-${process.pid}`
|
|
653
|
+
fs.writeFileSync(tmp, content, 'utf8')
|
|
654
|
+
fs.renameSync(tmp, file)
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
function makeEntryJunction(target, linkPath) {
|
|
658
|
+
if (!fs.existsSync(target)) return { ok: false, reason: 'target-missing', target }
|
|
659
|
+
try {
|
|
660
|
+
const stat = fs.lstatSync(linkPath, { throwIfNoEntry: false })
|
|
661
|
+
if (stat) return { ok: true, reused: true }
|
|
662
|
+
} catch { /* fall through */ }
|
|
663
|
+
try {
|
|
664
|
+
fs.symlinkSync(target, linkPath, 'junction')
|
|
665
|
+
return { ok: true, created: true }
|
|
666
|
+
} catch (error) {
|
|
667
|
+
return { ok: false, reason: 'junction-failed', detail: String(error?.message ?? error) }
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/**
|
|
672
|
+
* Materialise the accelerated fork profile and its home overlay.
|
|
673
|
+
* @returns {{ok:boolean, profileDir?:string, bundles?:string[], junctions?:object[], warning?:string[],
|
|
674
|
+
* overlay?:{ok:boolean, file?:string, error?:string}, error?:string}}
|
|
675
|
+
*/
|
|
676
|
+
export function writeAcceleratedForkProfile(options = {}) {
|
|
677
|
+
const {
|
|
678
|
+
profileDir = '',
|
|
679
|
+
fangRoot = '',
|
|
680
|
+
homeDir = '',
|
|
681
|
+
motherHome = '',
|
|
682
|
+
profileName = path.basename(String(profileDir || '')),
|
|
683
|
+
} = options
|
|
684
|
+
if (!String(profileDir ?? '').trim()) return { ok: false, error: 'no-profile-dir' }
|
|
685
|
+
if (!String(fangRoot ?? '').trim()) return { ok: false, error: 'no-fang-root' }
|
|
686
|
+
const fangDir = path.resolve(fangRoot)
|
|
687
|
+
if (!fs.existsSync(path.join(fangDir, 'package.json'))) return { ok: false, error: 'fang-package-missing', fangRoot: fangDir }
|
|
688
|
+
|
|
689
|
+
fs.mkdirSync(profileDir, { recursive: true })
|
|
690
|
+
const sourceProfileDir = String(options.sourceProfileDir ?? '').trim()
|
|
691
|
+
const accelNodeModules = String(options.accelNodeModules ?? '').trim()
|
|
692
|
+
let synced = null
|
|
693
|
+
if (sourceProfileDir && accelNodeModules) {
|
|
694
|
+
const built = buildSyncedAcceleratedProfile({ sourceProfileDir, accelNodeModules, fangRoot: fangDir, profileName })
|
|
695
|
+
if (built.ok !== true) return { ok: false, error: built.error ?? 'synced-profile-failed', sourceProfileDir }
|
|
696
|
+
synced = built
|
|
697
|
+
writeFileAtomic(path.join(profileDir, 'package.json'), `${JSON.stringify(built.package, null, 2)}\n`)
|
|
698
|
+
writeFileAtomic(path.join(profileDir, OVERLAY_FILE), built.patchText)
|
|
699
|
+
} else {
|
|
700
|
+
const pkg = buildAcceleratedForkProfile({ profileName, fangRoot: fangDir })
|
|
701
|
+
writeFileAtomic(path.join(profileDir, 'package.json'), `${JSON.stringify(pkg, null, 2)}\n`)
|
|
702
|
+
// Empty patch layer; applyForkConfigLock() appends the production locks afterwards.
|
|
703
|
+
writeFileAtomic(path.join(profileDir, OVERLAY_FILE), '[]\n')
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
const moduleDir = path.join(profileDir, 'node_modules')
|
|
707
|
+
fs.mkdirSync(path.join(moduleDir, '@local'), { recursive: true })
|
|
708
|
+
fs.mkdirSync(path.join(moduleDir, '@twinsearth'), { recursive: true })
|
|
709
|
+
let alias = null
|
|
710
|
+
let copiedPlugins = []
|
|
711
|
+
const clientAliases = []
|
|
712
|
+
if (synced) {
|
|
713
|
+
const clientAvailable = availableClientModules(accelNodeModules)
|
|
714
|
+
const sourceModules = path.join(synced.source, 'node_modules')
|
|
715
|
+
for (const bundle of synced.pluginPackages) {
|
|
716
|
+
const from = path.join(sourceModules, ...bundle.split('/'))
|
|
717
|
+
if (!fs.existsSync(from)) continue
|
|
718
|
+
const targetDir = path.join(moduleDir, ...bundle.split('/'))
|
|
719
|
+
copyPackageDir(from, targetDir)
|
|
720
|
+
copiedPlugins.push(bundle)
|
|
721
|
+
const rewritten = rewriteClientHalfPackage({ pluginDir: targetDir, available: clientAvailable })
|
|
722
|
+
if (rewritten) clientAliases.push(rewritten)
|
|
723
|
+
}
|
|
724
|
+
// Link the rest of the source module tree by entry junctions (never the whole tree:
|
|
725
|
+
// each plugin must keep resolving through the fork profile, where alias stubs live).
|
|
726
|
+
if (fs.existsSync(sourceModules)) {
|
|
727
|
+
const linkEntry = (rel) => {
|
|
728
|
+
if (rel === '@deepseek-ai' || copiedPlugins.includes(rel)) return
|
|
729
|
+
const dst = path.join(moduleDir, rel)
|
|
730
|
+
if (fs.existsSync(dst)) return
|
|
731
|
+
try { makeEntryJunction(path.join(sourceModules, rel), dst) } catch { /* best effort */ }
|
|
732
|
+
}
|
|
733
|
+
for (const entry of fs.readdirSync(sourceModules, { withFileTypes: true })) {
|
|
734
|
+
if (entry.name === '@deepseek-ai') continue
|
|
735
|
+
if (entry.name.startsWith('@')) {
|
|
736
|
+
try {
|
|
737
|
+
for (const scoped of fs.readdirSync(path.join(sourceModules, entry.name))) linkEntry(path.join(entry.name, scoped))
|
|
738
|
+
} catch { /* ignore */ }
|
|
739
|
+
} else linkEntry(entry.name)
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
const specs = new Set()
|
|
743
|
+
for (const plugin of synced.pluginPackages) {
|
|
744
|
+
const pluginDir = path.join(moduleDir, ...plugin.split('/'))
|
|
745
|
+
if (fs.existsSync(pluginDir)) scanDeepseekSpecs(pluginDir, specs)
|
|
746
|
+
}
|
|
747
|
+
alias = writeAliasStubs({ profileNodeModules: moduleDir, accelNodeModules, specs: [...specs] })
|
|
748
|
+
}
|
|
749
|
+
const junctions = []
|
|
750
|
+
// 2026-11-22: 用 package.json 的真实包名建 junction(发布包名与开发别名不同;
|
|
751
|
+
// 只写死 @twinsearth/fang-dsh-plugin 会让发布版在 orchestrator 的 bundle 探测里找不到 → fork-bundle-unavailable)。
|
|
752
|
+
const fangBundle = fangBundleNameOf(fangDir)
|
|
753
|
+
const fangTarget = path.join(moduleDir, ...fangBundle.split('/'))
|
|
754
|
+
fs.mkdirSync(path.dirname(fangTarget), { recursive: true })
|
|
755
|
+
junctions.push({ package: fangBundle, ...makeEntryJunction(fangDir, fangTarget) })
|
|
756
|
+
if (fangBundle !== FANG_BUNDLE) {
|
|
757
|
+
// 兼容旧检查/旧 profile:保留 @twinsearth/fang-dsh-plugin 开发别名 junction。
|
|
758
|
+
junctions.push({ package: FANG_BUNDLE, ...makeEntryJunction(fangDir, path.join(moduleDir, '@local', 'dsh-fang')) })
|
|
759
|
+
}
|
|
760
|
+
for (const child of FANG_CHILD_PACKAGES) {
|
|
761
|
+
const [scope, name] = child.split('/')
|
|
762
|
+
junctions.push({
|
|
763
|
+
package: child,
|
|
764
|
+
...makeEntryJunction(path.join(fangDir, 'node_modules', scope, name), path.join(moduleDir, scope, name)),
|
|
765
|
+
})
|
|
766
|
+
}
|
|
767
|
+
const warning = junctions.filter((entry) => entry.ok !== true).map((entry) => `junction-failed:${entry.package}${entry.reason ? `:${entry.reason}` : ''}`)
|
|
768
|
+
|
|
769
|
+
let overlay = { ok: false, error: 'overlay-skipped' }
|
|
770
|
+
if (String(homeDir ?? '').trim() && String(motherHome ?? '').trim()) {
|
|
771
|
+
const built = buildModelOverlay({ motherHome })
|
|
772
|
+
if (built.ok) {
|
|
773
|
+
const target = path.join(homeDir, OVERLAY_FILE)
|
|
774
|
+
let existing = ''
|
|
775
|
+
try { existing = String(fs.readFileSync(target, 'utf8')) } catch { existing = '' }
|
|
776
|
+
if (existing && !existing.includes(OVERLAY_MARKER)) {
|
|
777
|
+
overlay = { ok: false, error: 'home-patch-exists-unmanaged', file: target }
|
|
778
|
+
} else {
|
|
779
|
+
writeFileAtomic(target, built.text)
|
|
780
|
+
overlay = { ok: true, file: target, source: built.source }
|
|
781
|
+
}
|
|
782
|
+
} else {
|
|
783
|
+
overlay = { ok: false, error: built.error }
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
const bundles = synced ? [...synced.bundles.translated, fangBundleNameOf(fangDir)] : [...ACCEL_BUNDLES, fangBundleNameOf(fangDir)]
|
|
787
|
+
return {
|
|
788
|
+
ok: true,
|
|
789
|
+
profileDir,
|
|
790
|
+
bundles,
|
|
791
|
+
junctions,
|
|
792
|
+
warning,
|
|
793
|
+
overlay,
|
|
794
|
+
forkLsp: accelNodeModules ? detectForkLspSupport(accelNodeModules) : null,
|
|
795
|
+
sync: synced ? {
|
|
796
|
+
source: synced.source,
|
|
797
|
+
mapped: synced.bundles.mapped,
|
|
798
|
+
unsupportedBundles: synced.bundles.unsupported,
|
|
799
|
+
copiedPlugins,
|
|
800
|
+
alias,
|
|
801
|
+
clientAliases,
|
|
802
|
+
rowOverrides: synced.rowOverrides ?? [],
|
|
803
|
+
unsupportedClientHalves: clientAliases
|
|
804
|
+
.filter((item) => item.unsupported.length > 0)
|
|
805
|
+
.map((item) => ({ package: item.package, unsupported: item.unsupported })),
|
|
806
|
+
} : null,
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
/** Normalise a configured core mode; anything unknown is stock (safe default). */
|
|
811
|
+
export function normalizeCoreMode(value) {
|
|
812
|
+
return String(value ?? '').trim() === 'accelerated' ? 'accelerated' : 'stock'
|
|
813
|
+
}
|