@twinsearth/dsh-fang 3.3.2 → 3.7.6
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 +3 -3
- package/client.js +600 -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 +9 -5
- 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,161 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
|
|
3
|
+
//
|
|
4
|
+
// B 契约委托:加速分身 → 母体 的无头能力委托层(白名单 / 分会话鉴权 / 错误码 / 超时 / 审计)。
|
|
5
|
+
// 仅处理委托调用(envelope.meta.delegate === true);未带该标记的旧调用方保持既有语义。
|
|
6
|
+
// 设计:默认拒绝(fail-closed);未登记能力返回 contract-unsupported;委托层关闭返回 contract-unavailable。
|
|
7
|
+
|
|
8
|
+
import { ERROR_CODES } from '../contract/constants.js'
|
|
9
|
+
|
|
10
|
+
// B 委托错误码统一来自 contract SDK 1.2(append-only 注册表)。
|
|
11
|
+
export const DELEGATE_ERROR = Object.freeze({
|
|
12
|
+
UNAVAILABLE: ERROR_CODES.CONTRACT_UNAVAILABLE,
|
|
13
|
+
UNAUTHORIZED: ERROR_CODES.CONTRACT_UNAUTHORIZED,
|
|
14
|
+
UNSUPPORTED: ERROR_CODES.CONTRACT_UNSUPPORTED,
|
|
15
|
+
TIMEOUT: ERROR_CODES.CONTRACT_TIMEOUT,
|
|
16
|
+
INVALID: ERROR_CODES.CONTRACT_INVALID_REQUEST,
|
|
17
|
+
APPROVAL_REQUIRED: ERROR_CODES.CONTRACT_APPROVAL_REQUIRED,
|
|
18
|
+
RATE_LIMITED: ERROR_CODES.CONTRACT_RATE_LIMITED,
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
export const DELEGATE_KIND = Object.freeze({ READ: 'read', WRITE: 'write' })
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 能力目录(首批只读;写能力需显式加入 allow 且走审批——当前不注册写能力)。
|
|
25
|
+
* @typedef {{method:string, kind:'read'|'write', approval:'none'|'required', since:string, summary:string}} CapabilityDescriptor
|
|
26
|
+
*/
|
|
27
|
+
export const CAPABILITY_CATALOG = Object.freeze([
|
|
28
|
+
{ method: 'fang.capability.list', kind: 'read', approval: 'none', since: '1.2', summary: '列出已放行的委托能力(引导方法,总是可用)' },
|
|
29
|
+
{ method: 'fang.orchestrator.status', kind: 'read', approval: 'none', since: '1.0', summary: '母体 orchestrator 状态' },
|
|
30
|
+
{ method: 'fang.session.list', kind: 'read', approval: 'none', since: '1.0', summary: '母体会话目录(只读)' },
|
|
31
|
+
{ method: 'fang.session.events', kind: 'read', approval: 'none', since: '1.2', summary: '母体会话有界头读(只读;<200 行)' },
|
|
32
|
+
{ method: 'fang.decision.list', kind: 'read', approval: 'none', since: '1.2', summary: '母体决策中心快照(只读)' },
|
|
33
|
+
{ method: 'fang.approvals.list', kind: 'read', approval: 'none', since: '1.2', summary: '母体审批队列(只读)' },
|
|
34
|
+
{ method: 'fang.tool.invoke', kind: 'write', approval: 'required', since: '1.2', summary: '工具委托(官方 LSP 只读:definition/references/implementation/hover;母体 ctx.lsp provider 优先,fork-local 增强;默认不在白名单)' },
|
|
35
|
+
{ method: 'fang.chat.import', kind: 'write', approval: 'required', since: '1.2', summary: '官方会话导入(默认 dryRun;真实导入需审批;默认不在白名单)' },
|
|
36
|
+
])
|
|
37
|
+
|
|
38
|
+
export const DEFAULT_READ_ALLOW = Object.freeze([
|
|
39
|
+
'fang.capability.list',
|
|
40
|
+
'fang.orchestrator.status',
|
|
41
|
+
'fang.session.list',
|
|
42
|
+
'fang.session.events',
|
|
43
|
+
'fang.decision.list',
|
|
44
|
+
'fang.approvals.list',
|
|
45
|
+
])
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 专业版(Pro)专属能力:默认**不开启**,不进能力目录、不在默认白名单,
|
|
49
|
+
* 需要“单独专业版 + 每项手动授权激活(配置级 + 每次调用审批)”后才可由上层注册 handler。
|
|
50
|
+
* 当前仅登记决策,不注册任何 handler;请求即返回 contract-unsupported。
|
|
51
|
+
*/
|
|
52
|
+
export const PRO_ONLY_CAPABILITIES = Object.freeze([
|
|
53
|
+
{ method: 'fang.code.run', kind: 'write', approval: 'required', since: 'pro-1', summary: '代码执行(run_code / code-runtime;专业版,默认关闭,需每项手动授权激活 + 独立安全评审)' },
|
|
54
|
+
])
|
|
55
|
+
|
|
56
|
+
export const DELEGATE_DEFAULTS = Object.freeze({
|
|
57
|
+
enabled: true,
|
|
58
|
+
allow: [...DEFAULT_READ_ALLOW],
|
|
59
|
+
maxPayloadBytes: 64 * 1024,
|
|
60
|
+
readTimeoutMs: 5000,
|
|
61
|
+
writeTimeoutMs: 30000,
|
|
62
|
+
maxConcurrent: 4,
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
/** Pure: normalise the `contract.delegate` config block. */
|
|
66
|
+
export function normalizeDelegationConfig(raw = {}) {
|
|
67
|
+
const input = raw && typeof raw === 'object' ? raw : {}
|
|
68
|
+
const allow = Array.isArray(input.allow)
|
|
69
|
+
? input.allow.map((method) => String(method ?? '').trim()).filter(Boolean)
|
|
70
|
+
: [...DELEGATE_DEFAULTS.allow]
|
|
71
|
+
return {
|
|
72
|
+
enabled: input.enabled === undefined ? DELEGATE_DEFAULTS.enabled : input.enabled !== false,
|
|
73
|
+
allow: [...new Set(allow)],
|
|
74
|
+
maxPayloadBytes: Number.isFinite(Number(input.maxPayloadBytes)) && Number(input.maxPayloadBytes) > 0
|
|
75
|
+
? Math.round(Number(input.maxPayloadBytes)) : DELEGATE_DEFAULTS.maxPayloadBytes,
|
|
76
|
+
readTimeoutMs: Number.isFinite(Number(input.readTimeoutMs)) && Number(input.readTimeoutMs) >= 100
|
|
77
|
+
? Math.round(Number(input.readTimeoutMs)) : DELEGATE_DEFAULTS.readTimeoutMs,
|
|
78
|
+
writeTimeoutMs: Number.isFinite(Number(input.writeTimeoutMs)) && Number(input.writeTimeoutMs) >= 100
|
|
79
|
+
? Math.round(Number(input.writeTimeoutMs)) : DELEGATE_DEFAULTS.writeTimeoutMs,
|
|
80
|
+
maxConcurrent: Number.isFinite(Number(input.maxConcurrent)) && Number(input.maxConcurrent) >= 1
|
|
81
|
+
? Math.min(64, Math.round(Number(input.maxConcurrent))) : DELEGATE_DEFAULTS.maxConcurrent,
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* 并发闸门:超过上限立即拒绝(fail-closed),不排队、不静默降级。
|
|
87
|
+
* @returns {{tryAcquire:()=>({ok:true,active:number}|{ok:false,error:string,active:number}), release:()=>void, snapshot:()=>({active:number,maxConcurrent:number})}}
|
|
88
|
+
*/
|
|
89
|
+
export function createDelegationGate({ maxConcurrent = DELEGATE_DEFAULTS.maxConcurrent } = {}) {
|
|
90
|
+
const limit = Math.max(1, Math.round(Number(maxConcurrent) || DELEGATE_DEFAULTS.maxConcurrent))
|
|
91
|
+
let active = 0
|
|
92
|
+
return {
|
|
93
|
+
tryAcquire() {
|
|
94
|
+
if (active >= limit) return { ok: false, error: DELEGATE_ERROR.RATE_LIMITED, active }
|
|
95
|
+
active += 1
|
|
96
|
+
return { ok: true, active }
|
|
97
|
+
},
|
|
98
|
+
release() { active = Math.max(0, active - 1) },
|
|
99
|
+
snapshot() { return { active, maxConcurrent: limit } },
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Pure: descriptors visible to a caller under the current allowlist. */
|
|
104
|
+
export function capabilityCatalog(allow = DEFAULT_READ_ALLOW) {
|
|
105
|
+
const allowed = new Set(Array.isArray(allow) ? allow.map(String) : [])
|
|
106
|
+
return CAPABILITY_CATALOG.filter((item) => allowed.has(item.method)).map((item) => ({ ...item }))
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Pure: decide whether a delegated call may run.
|
|
111
|
+
* @returns {{ok:true, descriptor?:object} | {ok:false, error:string, message?:string}}
|
|
112
|
+
*/
|
|
113
|
+
export function checkDelegation({ method, allow, config } = {}) {
|
|
114
|
+
const cfg = normalizeDelegationConfig(config)
|
|
115
|
+
if (cfg.enabled !== true) return { ok: false, error: DELEGATE_ERROR.UNAVAILABLE, message: 'contract delegation is disabled' }
|
|
116
|
+
const name = String(method ?? '')
|
|
117
|
+
if (PRO_ONLY_CAPABILITIES.some((item) => item.method === name)) {
|
|
118
|
+
return { ok: false, error: DELEGATE_ERROR.UNSUPPORTED, message: `pro capability requires separate authorization activation (default off): ${name}` }
|
|
119
|
+
}
|
|
120
|
+
if (name === 'fang.capability.list') return { ok: true, descriptor: CAPABILITY_CATALOG[0] }
|
|
121
|
+
if (!cfg.allow.includes(name)) return { ok: false, error: DELEGATE_ERROR.UNSUPPORTED, message: `capability not allowed: ${name}` }
|
|
122
|
+
const descriptor = CAPABILITY_CATALOG.find((item) => item.method === name) ?? null
|
|
123
|
+
// allowlist 是权威白名单;目录仅用于 hello/能力自述(允许无描述的运维/测试缝能力被显式放行)。
|
|
124
|
+
return { ok: true, descriptor }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Pure: reject oversized payloads before touching the handler. */
|
|
128
|
+
export function exceedPayloadLimit(params, maxPayloadBytes = DELEGATE_DEFAULTS.maxPayloadBytes) {
|
|
129
|
+
let size = 0
|
|
130
|
+
try { size = Buffer.byteLength(JSON.stringify(params ?? null), 'utf8') } catch { return true }
|
|
131
|
+
return size > Number(maxPayloadBytes)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Run `fn` with a timeout; never throws. */
|
|
135
|
+
export async function runDelegated(fn, { timeoutMs = DELEGATE_DEFAULTS.readTimeoutMs } = {}) {
|
|
136
|
+
const startedAt = Date.now()
|
|
137
|
+
let timer = null
|
|
138
|
+
try {
|
|
139
|
+
const value = await Promise.race([
|
|
140
|
+
Promise.resolve().then(fn),
|
|
141
|
+
new Promise((_, reject) => {
|
|
142
|
+
timer = setTimeout(() => reject(Object.assign(new Error('contract delegation timed out'), { code: DELEGATE_ERROR.TIMEOUT })), Math.max(1, Number(timeoutMs) || DELEGATE_DEFAULTS.readTimeoutMs))
|
|
143
|
+
}),
|
|
144
|
+
])
|
|
145
|
+
return { ok: true, value, latencyMs: Date.now() - startedAt }
|
|
146
|
+
} catch (error) {
|
|
147
|
+
return {
|
|
148
|
+
ok: false,
|
|
149
|
+
error: String(error?.code ?? 'contract-error'),
|
|
150
|
+
message: String(error?.message ?? error),
|
|
151
|
+
latencyMs: Date.now() - startedAt,
|
|
152
|
+
}
|
|
153
|
+
} finally {
|
|
154
|
+
if (timer) clearTimeout(timer)
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Pure: audit record for one delegated call (capability/source/outcome/latency). */
|
|
159
|
+
export function delegationAuditRecord({ method, source = '', outcome = 'ok', error = null, latencyMs = 0 } = {}) {
|
|
160
|
+
return { capability: String(method ?? ''), source: String(source ?? '').slice(0, 120), outcome: String(outcome), error: error ? String(error).slice(0, 120) : null, latencyMs: Math.max(0, Math.round(Number(latencyMs) || 0)) }
|
|
161
|
+
}
|
|
@@ -10,10 +10,14 @@ export const DEFAULT_ESSENCE_PRESET = Object.freeze({
|
|
|
10
10
|
title: '安装不激活',
|
|
11
11
|
enabled: false,
|
|
12
12
|
specs: Object.freeze([
|
|
13
|
-
'@twinsearth/dsh-2xray',
|
|
14
|
-
'@michengai/dsh-agency-agents',
|
|
15
13
|
'dsh-better-sidebar',
|
|
16
14
|
'dsh-context',
|
|
15
|
+
'dshmarket',
|
|
16
|
+
'@xmanrui/dsh-im',
|
|
17
|
+
'@twinsearth/dsh-2xray',
|
|
18
|
+
'@twinsearth/dsh-master',
|
|
19
|
+
'@michengai/dsh-agency-agents',
|
|
20
|
+
'@twinsearth/dsh-im2a-plugin',
|
|
17
21
|
'@liustack/modlens',
|
|
18
22
|
'@liustack/modsearch',
|
|
19
23
|
]),
|
|
@@ -23,8 +27,7 @@ export const DEFAULT_ESSENCE_PRESET = Object.freeze({
|
|
|
23
27
|
title: '安装并激活',
|
|
24
28
|
enabled: true,
|
|
25
29
|
specs: Object.freeze([
|
|
26
|
-
'
|
|
27
|
-
'@twinsearth/dsh-im2a-plugin',
|
|
30
|
+
'@twinsearth/ai-prison-dsh-plugin',
|
|
28
31
|
'@openviking/dsh-memory-plugin',
|
|
29
32
|
'@twinsearth/w2m-dsh-plugin',
|
|
30
33
|
]),
|
package/src/lib/essence.mjs
CHANGED
|
@@ -36,18 +36,44 @@ export const ESSENCE_VERSION = '1.0.0'
|
|
|
36
36
|
export const OFFICIAL_ESSENCE_ID = 'essence-official-dev'
|
|
37
37
|
export const OFFICIAL_ESSENCE_NAME = '开发者推荐(官方)'
|
|
38
38
|
export const OFFICIAL_ESSENCE_MIN_TIER = 'vip100'
|
|
39
|
+
/**
|
|
40
|
+
* 2026-11-22:DSH 插件页「实验性插件」的完整官方包集合(来自 DSH client 的
|
|
41
|
+
* EXPERIMENTAL_BUNDLES,含不带 experimental 前缀的 personalized/cua/chat-import)。
|
|
42
|
+
* 官方/分身都必须启用这整组,而不是只匹配 `@deepseek-ai/dsh-experimental-*`。
|
|
43
|
+
*/
|
|
44
|
+
export const NODE_COMPAT_BUNDLE = '@twinsearth/dsh-fang-node-compat'
|
|
45
|
+
export const OFFICIAL_EXPERIMENTAL_BUNDLES = Object.freeze([
|
|
46
|
+
'@deepseek-ai/dsh-personalized-recommendations',
|
|
47
|
+
'@deepseek-ai/dsh-cua-bundle',
|
|
48
|
+
'@deepseek-ai/dsh-experimental-voice-input-bundle',
|
|
49
|
+
'@deepseek-ai/dsh-experimental-auto-review',
|
|
50
|
+
'@deepseek-ai/dsh-experimental-inspector-profile',
|
|
51
|
+
'@deepseek-ai/dsh-experimental-forge-bundle',
|
|
52
|
+
'@deepseek-ai/dsh-experimental-tool-worktree',
|
|
53
|
+
'@deepseek-ai/dsh-experimental-cot-translation-bundle',
|
|
54
|
+
'@deepseek-ai/dsh-experimental-session-search',
|
|
55
|
+
'@deepseek-ai/dsh-experimental-session-titles-bundle',
|
|
56
|
+
'@deepseek-ai/dsh-experimental-badge-skill-bundle',
|
|
57
|
+
'@deepseek-ai/dsh-experimental-ralph-bundle',
|
|
58
|
+
'@deepseek-ai/dsh-experimental-plugin-market-bundle',
|
|
59
|
+
'@deepseek-ai/dsh-experimental-liveshare',
|
|
60
|
+
'@deepseek-ai/dsh-deepseek-chat-import',
|
|
61
|
+
])
|
|
39
62
|
/** 官方推荐原身预装的默认插件条目(v3.0.7:自定义清单,安装≠激活)。 */
|
|
40
63
|
export const DEFAULT_OFFICIAL_PATCH_ENTRIES = Object.freeze([
|
|
41
|
-
//
|
|
42
|
-
Object.freeze({ id: 'official-2xray', name: '@twinsearth/dsh-2xray', disabled: true }),
|
|
43
|
-
Object.freeze({ id: 'official-agency-agents', name: '@michengai/dsh-agency-agents', disabled: true }),
|
|
64
|
+
// 安装但不激活(用户 2026-11-22 更新清单)
|
|
44
65
|
Object.freeze({ id: 'official-better-sidebar', name: 'dsh-better-sidebar', disabled: true }),
|
|
45
66
|
Object.freeze({ id: 'official-context', name: 'dsh-context', disabled: true }),
|
|
67
|
+
Object.freeze({ id: 'official-dshmarket', name: 'dshmarket', disabled: true }),
|
|
68
|
+
Object.freeze({ id: 'official-xmanrui-im', name: '@xmanrui/dsh-im', disabled: true }),
|
|
69
|
+
Object.freeze({ id: 'official-2xray', name: '@twinsearth/dsh-2xray', disabled: true }),
|
|
70
|
+
Object.freeze({ id: 'official-master', name: '@twinsearth/dsh-master', disabled: true }),
|
|
71
|
+
Object.freeze({ id: 'official-agency-agents', name: '@michengai/dsh-agency-agents', disabled: true }),
|
|
72
|
+
Object.freeze({ id: 'official-im2a', name: '@twinsearth/dsh-im2a-plugin', disabled: true }),
|
|
46
73
|
Object.freeze({ id: 'official-modlens', name: '@liustack/modlens', disabled: true }),
|
|
47
74
|
Object.freeze({ id: 'official-modsearch', name: '@liustack/modsearch', disabled: true }),
|
|
48
75
|
// 安装并激活
|
|
49
|
-
Object.freeze({ id: 'official-
|
|
50
|
-
Object.freeze({ id: 'official-im2a', name: '@twinsearth/dsh-im2a-plugin', disabled: false }),
|
|
76
|
+
Object.freeze({ id: 'official-ai-prison', name: '@twinsearth/ai-prison-dsh-plugin', disabled: false }),
|
|
51
77
|
Object.freeze({ id: 'official-openviking-memory', name: '@openviking/dsh-memory-plugin', disabled: false }),
|
|
52
78
|
Object.freeze({ id: 'official-w2m', name: '@twinsearth/w2m-dsh-plugin', disabled: false }),
|
|
53
79
|
])
|
|
@@ -209,7 +235,10 @@ export function parsePatchEntries(text) {
|
|
|
209
235
|
* @returns {string}
|
|
210
236
|
*/
|
|
211
237
|
export function serializePatchEntries(entries) {
|
|
212
|
-
|
|
238
|
+
// DSH app-boot requires `<profile>/cordis.patch.yml` to be a top-level YAML array
|
|
239
|
+
// of loader patch entries. The old `{ insert: [...] }` wrapper made every
|
|
240
|
+
// essence/official runtime fail with "must be a top-level YAML array".
|
|
241
|
+
return `${JSON.stringify(entries, null, 2)}\n`
|
|
213
242
|
}
|
|
214
243
|
|
|
215
244
|
// ===========================================================================
|
|
@@ -567,6 +596,83 @@ export class EssenceManager {
|
|
|
567
596
|
})
|
|
568
597
|
}
|
|
569
598
|
|
|
599
|
+
/**
|
|
600
|
+
* 2026-11-22: 修复/刷新「开发者推荐(官方)」:
|
|
601
|
+
* - 依赖与 bundles 跟随当前母体 profile(新的 fang/2xray 等不再缺失);
|
|
602
|
+
* - 推荐插件按固定清单 install/enable;
|
|
603
|
+
* - 所有已安装的实验性插件默认开启(`@deepseek-ai/dsh-experimental-*`)。
|
|
604
|
+
* 官方原身是锁定底座,这里直接改 overlay 后 recompute(不走 update() 的 locked 拒绝)。
|
|
605
|
+
*/
|
|
606
|
+
repairOfficialEssence({ installed = [], motherProfileDir = '' } = {}) {
|
|
607
|
+
const root = this.essenceRoot(OFFICIAL_ESSENCE_ID)
|
|
608
|
+
const meta = this.getMeta(OFFICIAL_ESSENCE_ID)
|
|
609
|
+
if (!meta?.id) return { ok: false, error: 'official-missing' }
|
|
610
|
+
const overlay = this.loadOverlay(root)
|
|
611
|
+
if (motherProfileDir) {
|
|
612
|
+
const motherPkg = readJson(path.join(String(motherProfileDir), 'package.json'), null)
|
|
613
|
+
if (motherPkg) overlay.packageJson = { ...overlay.packageJson, ...this.selectProfilePackage(motherPkg) }
|
|
614
|
+
}
|
|
615
|
+
const mirror = this.loadMirror()
|
|
616
|
+
const recommended = DEFAULT_OFFICIAL_PATCH_ENTRIES.map((entry) => ({ ...entry }))
|
|
617
|
+
// 同名镜像行会与推荐行并存;用镜像 id 的 disabled 影子条目删掉镜像行,
|
|
618
|
+
// 推荐行自己仍保留(否则 dsh-context 这类包会因为行被删掉而回到 bundle 默认开启)。
|
|
619
|
+
const shadows = []
|
|
620
|
+
for (const entry of recommended) {
|
|
621
|
+
const mirrorId = (mirror.patchEntries ?? []).find((candidate) => candidate.name === entry.name)?.id
|
|
622
|
+
if (mirrorId && String(mirrorId) !== entry.id && !mirror.lockedPluginIds?.has?.(String(mirrorId))) {
|
|
623
|
+
shadows.push({ id: String(mirrorId), name: entry.name, disabled: true })
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
const experimentalNames = [...new Set([
|
|
627
|
+
...OFFICIAL_EXPERIMENTAL_BUNDLES,
|
|
628
|
+
...(installed ?? [])
|
|
629
|
+
.map((entry) => String(entry?.name ?? entry?.spec ?? entry?.id ?? ''))
|
|
630
|
+
.filter((name) => /^@deepseek-ai\/dsh-experimental-/.test(name)),
|
|
631
|
+
])]
|
|
632
|
+
const mirrorEntries = mirror.patchEntries ?? []
|
|
633
|
+
const experimental = experimentalNames.map((name) => {
|
|
634
|
+
const mirrorEntry = mirrorEntries.find((candidate) => candidate.name === name)
|
|
635
|
+
return {
|
|
636
|
+
id: mirrorEntry?.id ? String(mirrorEntry.id) : `official-exp-${sha256(name).slice(0, 8)}`,
|
|
637
|
+
name,
|
|
638
|
+
disabled: false,
|
|
639
|
+
}
|
|
640
|
+
})
|
|
641
|
+
// 官方 profile 的 bundles 必须显式包含所有实验性包;仅写 patch 行不够
|
|
642
|
+
// (插件页按 dsh.profile.bundles/EXPERIMENTAL_BUNDLES 判断是否已启用)。
|
|
643
|
+
const expBundles = new Set(OFFICIAL_EXPERIMENTAL_BUNDLES)
|
|
644
|
+
overlay.packageJson.dsh = overlay.packageJson.dsh && typeof overlay.packageJson.dsh === 'object' ? overlay.packageJson.dsh : {}
|
|
645
|
+
overlay.packageJson.dsh.profile = overlay.packageJson.dsh.profile && typeof overlay.packageJson.dsh.profile === 'object' ? overlay.packageJson.dsh.profile : {}
|
|
646
|
+
const bundles = Array.isArray(overlay.packageJson.dsh.profile.bundles) ? [...overlay.packageJson.dsh.profile.bundles] : []
|
|
647
|
+
for (const name of expBundles) if (!bundles.includes(name)) bundles.push(name)
|
|
648
|
+
// 2026-11-22:把 fang 放到 base/web 之后、实验性 bundle 之前。experimental-inspector
|
|
649
|
+
// 会在加载时观察 globalThis.fetch;fang 的 node-compat 必须先运行,否则 Node 26 直接报
|
|
650
|
+
// "fetch is an accessor and cannot be observed safely"。
|
|
651
|
+
overlay.packageJson.dependencies = overlay.packageJson.dependencies && typeof overlay.packageJson.dependencies === 'object' ? overlay.packageJson.dependencies : {}
|
|
652
|
+
overlay.packageJson.dependencies[NODE_COMPAT_BUNDLE] = '^0.1.0'
|
|
653
|
+
if (!bundles.includes(NODE_COMPAT_BUNDLE)) bundles.unshift(NODE_COMPAT_BUNDLE)
|
|
654
|
+
const fangIndex = bundles.indexOf('@twinsearth/fang-dsh-plugin')
|
|
655
|
+
if (fangIndex > 3) {
|
|
656
|
+
bundles.splice(fangIndex, 1)
|
|
657
|
+
bundles.splice(3, 0, '@twinsearth/fang-dsh-plugin')
|
|
658
|
+
}
|
|
659
|
+
overlay.packageJson.dsh.profile.bundles = bundles
|
|
660
|
+
const managedNames = new Set([...recommended, ...experimental].map((entry) => String(entry.name)))
|
|
661
|
+
const preserved = (Array.isArray(overlay.patchEntries) ? overlay.patchEntries : [])
|
|
662
|
+
.filter((entry) => !String(entry?.id ?? '').startsWith('official-'))
|
|
663
|
+
.filter((entry) => !managedNames.has(String(entry?.name ?? '')))
|
|
664
|
+
overlay.patchEntries = [...recommended, ...experimental, ...shadows, ...preserved]
|
|
665
|
+
this.saveOverlay(root, overlay)
|
|
666
|
+
const merge = this.recompute(OFFICIAL_ESSENCE_ID)
|
|
667
|
+
return {
|
|
668
|
+
ok: true,
|
|
669
|
+
essenceId: OFFICIAL_ESSENCE_ID,
|
|
670
|
+
recommended: recommended.length,
|
|
671
|
+
experimental: experimental.length,
|
|
672
|
+
status: merge.status,
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
|
|
570
676
|
/**
|
|
571
677
|
* 从母体 profile 生成元主(v3.0.9):把母体的**可写层**克隆成新元主的覆盖层。
|
|
572
678
|
*
|
|
@@ -852,7 +958,7 @@ export class EssenceManager {
|
|
|
852
958
|
const guide = [
|
|
853
959
|
'# dsh-Fang 元主导入引导',
|
|
854
960
|
'',
|
|
855
|
-
'1. 目标机器安装并启用 dsh-Fang(@twinsearth/dsh-
|
|
961
|
+
'1. 目标机器安装并启用 dsh-Fang(@twinsearth/fang-dsh-plugin)。',
|
|
856
962
|
'2. 打开瓮城面板 → 元主区 → 「导入」→ 选择本 JSON 文件(或 POST /fang/api/essence/import)。',
|
|
857
963
|
'3. 导入会生成新的 essences/<新id> 并自动重算;凭据不随包迁移,需要重新登录。',
|
|
858
964
|
'4. 打开前建议先执行「同步」,把该元主重放到目标机器当前的母体镜像。',
|
|
@@ -73,8 +73,8 @@ function jsonPatchEntries(text) {
|
|
|
73
73
|
if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) return null
|
|
74
74
|
let value
|
|
75
75
|
try { value = JSON.parse(trimmed) } catch { return null }
|
|
76
|
-
if (Array.isArray(value)) return value
|
|
77
|
-
if (value !== null && typeof value === 'object' && Array.isArray(value.insert)) return
|
|
76
|
+
if (Array.isArray(value)) return value
|
|
77
|
+
if (value !== null && typeof value === 'object' && Array.isArray(value.insert)) return value.insert
|
|
78
78
|
return null
|
|
79
79
|
}
|
|
80
80
|
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
|
|
3
|
+
//
|
|
4
|
+
// Fork core settings (P1): the mother panel switch that decides which DSH core a
|
|
5
|
+
// newly provisioned/restarted FORK runs on. Host and essence never read this.
|
|
6
|
+
//
|
|
7
|
+
// File: <dataDir>/fork-core.json
|
|
8
|
+
// { "mode": "stock" | "accelerated",
|
|
9
|
+
// "sessionMode": "new" | "inherit",
|
|
10
|
+
// "updatedAt": ISO, "updatedBy": string }
|
|
11
|
+
import fs from 'node:fs'
|
|
12
|
+
import path from 'node:path'
|
|
13
|
+
import { readJson, writeJsonAtomic } from '../kernel/index.mjs'
|
|
14
|
+
|
|
15
|
+
export const FORK_CORE_FILE = 'fork-core.json'
|
|
16
|
+
export const FORK_CORE_MODES = Object.freeze(['stock', 'accelerated'])
|
|
17
|
+
// Session policy for accelerated forks:
|
|
18
|
+
// new — only new sessions (default, safest)
|
|
19
|
+
// copy — user may import old sessions, but only as COPIES into the fork home
|
|
20
|
+
// (never attach/read the original in place); `inherit` is a legacy alias.
|
|
21
|
+
export const FORK_SESSION_MODES = Object.freeze(['new', 'copy'])
|
|
22
|
+
export const DEFAULT_FORK_CORE = Object.freeze({ mode: 'stock', sessionMode: 'new' })
|
|
23
|
+
|
|
24
|
+
/** Normalise one mode value; unknown input falls back to the safe default. */
|
|
25
|
+
export function normalizeForkCoreMode(value) {
|
|
26
|
+
const text = String(value ?? '').trim()
|
|
27
|
+
return FORK_CORE_MODES.includes(text) ? text : DEFAULT_FORK_CORE.mode
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Normalise the session policy; `new` is the safe default, `inherit` maps to `copy`. */
|
|
31
|
+
export function normalizeForkSessionMode(value) {
|
|
32
|
+
const text = String(value ?? '').trim()
|
|
33
|
+
if (text === 'inherit') return 'copy'
|
|
34
|
+
return FORK_SESSION_MODES.includes(text) ? text : DEFAULT_FORK_CORE.sessionMode
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Pure: coerce a persisted object (or null) into the settings shape. */
|
|
38
|
+
export function normalizeForkCoreSettings(raw) {
|
|
39
|
+
const input = raw && typeof raw === 'object' ? raw : {}
|
|
40
|
+
return {
|
|
41
|
+
mode: normalizeForkCoreMode(input.mode),
|
|
42
|
+
sessionMode: normalizeForkSessionMode(input.sessionMode),
|
|
43
|
+
updatedAt: typeof input.updatedAt === 'string' ? input.updatedAt : null,
|
|
44
|
+
updatedBy: typeof input.updatedBy === 'string' ? input.updatedBy : null,
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Pure: resolve the panel/API view from persisted settings + install state.
|
|
50
|
+
* When high gear is selected without an installed accelerated core this MUST NOT
|
|
51
|
+
* report a silent stock fallback: `effectiveMode` is null and `blocked` explains why.
|
|
52
|
+
* @returns {{mode:string, sessionMode:string, effectiveMode:string|null, blocked:string|null}}
|
|
53
|
+
*/
|
|
54
|
+
export function resolveForkCoreState(settings, { installed = false } = {}) {
|
|
55
|
+
const normalized = normalizeForkCoreSettings(settings)
|
|
56
|
+
const blocked = normalized.mode === 'accelerated' && installed !== true ? 'accelerated-cli-missing' : null
|
|
57
|
+
return {
|
|
58
|
+
mode: normalized.mode,
|
|
59
|
+
sessionMode: normalized.sessionMode,
|
|
60
|
+
effectiveMode: blocked ? null : normalized.mode,
|
|
61
|
+
blocked,
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Read `<dataDir>/fork-core.json`; a missing/corrupt file means stock/new. */export function readForkCoreSettings(dataDir, { readImpl = readJson } = {}) {
|
|
66
|
+
const file = path.join(String(dataDir ?? ''), FORK_CORE_FILE)
|
|
67
|
+
try {
|
|
68
|
+
return normalizeForkCoreSettings(readImpl(file, null))
|
|
69
|
+
} catch {
|
|
70
|
+
return normalizeForkCoreSettings(null)
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Persist the settings atomically (delegated to the kernel writer).
|
|
76
|
+
* @returns {{ok:true, settings:object} | {ok:false, error:string}}
|
|
77
|
+
*/
|
|
78
|
+
export function writeForkCoreSettings(dataDir, patch = {}, { at = new Date().toISOString(), by = '' } = {}) {
|
|
79
|
+
const dir = String(dataDir ?? '').trim()
|
|
80
|
+
if (!dir) return { ok: false, error: 'no-data-dir' }
|
|
81
|
+
const current = readForkCoreSettings(dir)
|
|
82
|
+
const next = normalizeForkCoreSettings({
|
|
83
|
+
mode: patch.mode === undefined ? current.mode : patch.mode,
|
|
84
|
+
sessionMode: patch.sessionMode === undefined ? current.sessionMode : patch.sessionMode,
|
|
85
|
+
updatedAt: at,
|
|
86
|
+
updatedBy: String(by ?? '').slice(0, 120) || current.updatedBy,
|
|
87
|
+
})
|
|
88
|
+
try {
|
|
89
|
+
fs.mkdirSync(dir, { recursive: true })
|
|
90
|
+
writeJsonAtomic(path.join(dir, FORK_CORE_FILE), next)
|
|
91
|
+
return { ok: true, settings: next }
|
|
92
|
+
} catch (error) {
|
|
93
|
+
return { ok: false, error: 'write-failed', detail: String(error?.message ?? error) }
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Fork full-home export/import (folder based, no zip dependency).
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
import { createHash, randomBytes } from 'node:crypto'
|
|
6
|
+
|
|
7
|
+
export const FORK_EXPORT_FORMAT = 'dsh-fang-fork-export/v1'
|
|
8
|
+
const SKIP_ROOT = new Set(['tmp', 'node_modules'])
|
|
9
|
+
const SKIP_ANY = new Set(['node_modules'])
|
|
10
|
+
|
|
11
|
+
function copyFiltered(from, to, relative = '') {
|
|
12
|
+
const stat = fs.lstatSync(from)
|
|
13
|
+
if (stat.isSymbolicLink()) {
|
|
14
|
+
const target = fs.readlinkSync(from)
|
|
15
|
+
try { fs.symlinkSync(target, to, 'junction') } catch { /* best effort */ }
|
|
16
|
+
return { files: 1, bytes: 0 }
|
|
17
|
+
}
|
|
18
|
+
if (stat.isDirectory()) {
|
|
19
|
+
const name = path.basename(from)
|
|
20
|
+
if (SKIP_ANY.has(name)) return { files: 0, bytes: 0 }
|
|
21
|
+
fs.mkdirSync(to, { recursive: true })
|
|
22
|
+
let files = 0
|
|
23
|
+
let bytes = 0
|
|
24
|
+
for (const entry of fs.readdirSync(from)) {
|
|
25
|
+
if (!relative && SKIP_ROOT.has(entry)) continue
|
|
26
|
+
const child = copyFiltered(path.join(from, entry), path.join(to, entry), path.join(relative, entry))
|
|
27
|
+
files += child.files
|
|
28
|
+
bytes += child.bytes
|
|
29
|
+
}
|
|
30
|
+
return { files, bytes }
|
|
31
|
+
}
|
|
32
|
+
fs.mkdirSync(path.dirname(to), { recursive: true })
|
|
33
|
+
fs.copyFileSync(from, to)
|
|
34
|
+
return { files: 1, bytes: stat.size }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function exportForkHome({ homeDir, destDir, task }) {
|
|
38
|
+
const src = path.resolve(String(homeDir ?? ''))
|
|
39
|
+
const dest = path.resolve(String(destDir ?? ''))
|
|
40
|
+
if (!fs.existsSync(path.join(src, 'profiles'))) return { ok: false, error: 'fork-home-invalid', detail: src }
|
|
41
|
+
fs.mkdirSync(dest, { recursive: true })
|
|
42
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-')
|
|
43
|
+
const outDir = path.join(dest, `fang-${String(task?.taskId ?? 'fork')}-${stamp}`)
|
|
44
|
+
fs.mkdirSync(outDir, { recursive: true })
|
|
45
|
+
const copied = copyFiltered(src, path.join(outDir, 'home'))
|
|
46
|
+
const manifest = {
|
|
47
|
+
format: FORK_EXPORT_FORMAT,
|
|
48
|
+
version: 1,
|
|
49
|
+
exportedAt: new Date().toISOString(),
|
|
50
|
+
taskId: task?.taskId ?? '',
|
|
51
|
+
title: task?.title ?? '',
|
|
52
|
+
profile: task?.profile ?? '',
|
|
53
|
+
coreMode: task?.coreMode ?? 'stock',
|
|
54
|
+
sourceEssenceId: task?.syncSourceId ?? task?.essenceId ?? 'essence-official-dev',
|
|
55
|
+
files: copied.files,
|
|
56
|
+
bytes: copied.bytes,
|
|
57
|
+
nonce: randomBytes(8).toString('hex'),
|
|
58
|
+
}
|
|
59
|
+
const json = `${JSON.stringify(manifest, null, 2)}\n`
|
|
60
|
+
fs.writeFileSync(path.join(outDir, 'manifest.json'), json)
|
|
61
|
+
fs.writeFileSync(path.join(outDir, 'manifest.sha256'), `${createHash('sha256').update(json).digest('hex')} manifest.json\n`)
|
|
62
|
+
fs.writeFileSync(path.join(outDir, 'IMPORT-GUIDE.md'), [
|
|
63
|
+
'# 瓮城分身导出包',
|
|
64
|
+
'',
|
|
65
|
+
`- 分身:${manifest.title}(${manifest.taskId})`,
|
|
66
|
+
`- 导出时间:${manifest.exportedAt}`,
|
|
67
|
+
`- 文件数:${manifest.files},字节:${manifest.bytes}`,
|
|
68
|
+
'',
|
|
69
|
+
'在母体面板「分身工作区」点该分身的「导入」,选择本文件夹即可恢复为一个新分身。',
|
|
70
|
+
'导出不包含 `node_modules` 与 `tmp`;导入后由瓮城重新移植依赖并启动。',
|
|
71
|
+
].join('\n'))
|
|
72
|
+
return { ok: true, dir: outDir, files: copied.files, bytes: copied.bytes, manifest }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function readForkExport(sourceDir) {
|
|
76
|
+
const dir = path.resolve(String(sourceDir ?? ''))
|
|
77
|
+
const manifestPath = path.join(dir, 'manifest.json')
|
|
78
|
+
if (!fs.existsSync(manifestPath)) return { ok: false, error: 'manifest-missing', detail: manifestPath }
|
|
79
|
+
let manifest
|
|
80
|
+
try { manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) } catch { return { ok: false, error: 'manifest-invalid' } }
|
|
81
|
+
if (manifest?.format !== FORK_EXPORT_FORMAT) return { ok: false, error: 'format-unsupported', detail: manifest?.format ?? '' }
|
|
82
|
+
const homeDir = path.join(dir, 'home')
|
|
83
|
+
if (!fs.existsSync(path.join(homeDir, 'profiles'))) return { ok: false, error: 'home-missing', detail: homeDir }
|
|
84
|
+
return { ok: true, dir, homeDir, manifest }
|
|
85
|
+
}
|