@twinsearth/dsh-fang 3.3.1 → 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 +709 -61
- 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/OVERLAY-MASTER-SWITCH.md +35 -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 +34 -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
|
@@ -22,12 +22,18 @@ import {
|
|
|
22
22
|
import { parseWorkspaceIndex, scanSessionDirs, readBoundedEvents, extractSessionTitle, encodeWorkspaceKey } from '../lib/session-format.mjs'
|
|
23
23
|
import { ensureEssenceRuntimePnpmConfig, readNodeLinker } from '../lib/pnpm-store.mjs'
|
|
24
24
|
import { captureRuntimeProfileIntoEssence } from '../lib/runtime-capture.mjs'
|
|
25
|
+
import { installWatchGuard } from '../lib/watch-guard.mjs'
|
|
26
|
+
import { ensureInstallSnapshot } from '../lib/install-snapshot.mjs'
|
|
27
|
+
import { exportVault, importVault, readVault } from '../../vault/lib/vault.mjs'
|
|
28
|
+
import { installGlobalRedline } from '../lib/global-redline.mjs'
|
|
29
|
+
import { normalizeFetchDescriptor } from '../lib/node-compat.mjs'
|
|
30
|
+
import { cleanupApprovalDrill, runApprovalDrill } from '../lib/approval-drill.mjs'
|
|
25
31
|
import { negotiateProtocol } from '../lib/adapter-protocol.mjs'
|
|
26
32
|
import { describeMotherLink, probeLink, readSharedProfileSummary } from '../lib/mother-link.mjs'
|
|
27
33
|
import { MirrorManager } from '../lib/mirror.mjs'
|
|
28
34
|
import { buildMirrorStatusResponse } from '../lib/mirror-etag.mjs'
|
|
29
35
|
import { PreferencesStore } from '../lib/preferences.mjs'
|
|
30
|
-
import { EssenceManager, OFFICIAL_ESSENCE_ID, VIP_QUOTAS } from '../lib/essence.mjs'
|
|
36
|
+
import { EssenceManager, OFFICIAL_ESSENCE_ID, OFFICIAL_EXPERIMENTAL_BUNDLES, NODE_COMPAT_BUNDLE, VIP_QUOTAS, parsePatchEntries } from '../lib/essence.mjs'
|
|
31
37
|
import { applyForkConfigLock, setProfileConfigReadonly } from '../lib/fork-config-lock.mjs'
|
|
32
38
|
import { ensureForkEmptySession, enforceForkSessionCap, summarizeForkSessions, FORK_SESSION_MAX, FORK_SESSION_MIN } from '../lib/fork-sessions.mjs'
|
|
33
39
|
import { DEFAULT_ESSENCE_NAME, planDefaultEssence } from '../lib/default-essence.mjs'
|
|
@@ -41,11 +47,27 @@ import { buildUpgradeStatus } from '../lib/upgrade-status.mjs'
|
|
|
41
47
|
import { openDecisionEventStream } from '../lib/decision-events.mjs'
|
|
42
48
|
import { authErrorBody, checkRequestAuth, loadAuthToken } from '../lib/http-auth.mjs'
|
|
43
49
|
import { buildEssenceActions, buildTaskActions } from '../lib/ui-actions.mjs'
|
|
50
|
+
// P0: the former "accelerated Web sidecar" (a second mother Web) was retired — the
|
|
51
|
+
// accelerator serves fork Web UIs only. See /fang/api/fork-core.
|
|
52
|
+
import { readForkCoreSettings, resolveForkCoreState, writeForkCoreSettings } from '../lib/fork-core-settings.mjs'
|
|
53
|
+
import {
|
|
54
|
+
capabilityCatalog, checkDelegation, createDelegationGate, DELEGATE_ERROR, delegationAuditRecord,
|
|
55
|
+
DEFAULT_READ_ALLOW, exceedPayloadLimit, normalizeDelegationConfig, runDelegated,
|
|
56
|
+
} from '../lib/contract-delegation.mjs'
|
|
57
|
+
import {
|
|
58
|
+
PRO_CAPABILITIES, PRO_STAGE, checkProGate, createProApprovalStore, normalizeProConfig,
|
|
59
|
+
proAuditRecord, proParamsDigest, providerMissingResult, runProCapability,
|
|
60
|
+
} from '../lib/pro-delegation.mjs'
|
|
61
|
+
import { validateToolInvoke } from '../lib/lsp-delegation.mjs'
|
|
62
|
+
import { LSP_PROVIDER_TEST, advertisedActionsFromSeam, checkWorkspaceRoot, collectForkWorkspaceRoots, describeLspProvider, lspAuditRecord, queryMotherLsp, resolveLspAllowedRoots } from '../lib/lsp-provider.mjs'
|
|
63
|
+
import { buildChatImportDryRun, validateChatImport } from '../lib/chat-import-delegation.mjs'
|
|
64
|
+
import { detectForkLspSupport, normalizeCoreMode, pruneAliasStubs, sanitizeAcceleratedForkSessions } from '../lib/accelerated-fork.mjs'
|
|
65
|
+
import { accelNodeModulesRoot, resolveAcceleratedCore } from '../lib/accelerated-install.mjs'
|
|
44
66
|
import { BranchStore } from '../lib/branch-store.mjs'
|
|
45
67
|
import { ComposerJournal } from '../lib/composer-journal.mjs'
|
|
46
68
|
import { fileURLToPath } from 'node:url'
|
|
47
69
|
import {
|
|
48
|
-
createContractServer, startFileContractServer,
|
|
70
|
+
createContractServer, startFileContractServer, createResponse,
|
|
49
71
|
createRelayStore, relayHandlers, // v3.1.35:contract 1.1 回流接口
|
|
50
72
|
METHODS as CONTRACT_METHODS, CONTRACT_VERSION,
|
|
51
73
|
} from '../contract/index.js'
|
|
@@ -92,7 +114,51 @@ export function atomicReplaceDir(sourceDir, targetDir) {
|
|
|
92
114
|
}
|
|
93
115
|
|
|
94
116
|
|
|
95
|
-
const FORK_BUNDLE_NAMES = Object.freeze(['@twinsearth/dsh-
|
|
117
|
+
const FORK_BUNDLE_NAMES = Object.freeze(['@twinsearth/fang-dsh-plugin', '@twinsearth/dsh-fang', '@twinsearth/fang-dsh-plugin'])
|
|
118
|
+
// build.mjs rewrites @twinsearth/fang-dsh-plugin to the published package name.
|
|
119
|
+
const CURRENT_FANG_BUNDLE = '@twinsearth/fang-dsh-plugin'
|
|
120
|
+
|
|
121
|
+
function profileBundles(profileDir) {
|
|
122
|
+
try {
|
|
123
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(String(profileDir ?? ''), 'package.json'), 'utf8'))
|
|
124
|
+
const bundles = Array.isArray(pkg?.dsh?.profile?.bundles) ? pkg.dsh.profile.bundles.map(String) : []
|
|
125
|
+
const deps = pkg?.dependencies && typeof pkg.dependencies === 'object' ? Object.keys(pkg.dependencies) : []
|
|
126
|
+
return { bundles, deps, pkg }
|
|
127
|
+
} catch {
|
|
128
|
+
return { bundles: [], deps: [], pkg: null }
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* v3.3.7: an essence captured by an older release can still declare the legacy
|
|
134
|
+
* `@twinsearth/dsh-fang` bundle while the current fork has no such package.
|
|
135
|
+
* Such an essence is not a valid fork template; deriving from it creates a
|
|
136
|
+
* process whose Adapter never mounts (404). Treat it as stale and fall back to
|
|
137
|
+
* the clean template instead of silently producing a zombie fork.
|
|
138
|
+
*/
|
|
139
|
+
export function profileUsesCurrentFangBundle(profileDir) {
|
|
140
|
+
const { bundles, deps, pkg } = profileBundles(profileDir)
|
|
141
|
+
if (!pkg) return true // unknown template: don't reject (caller has its own checks)
|
|
142
|
+
const declared = new Set([...bundles, ...deps])
|
|
143
|
+
const current = declared.has(CURRENT_FANG_BUNDLE) || declared.has('@twinsearth/fang-dsh-plugin')
|
|
144
|
+
if (!current) {
|
|
145
|
+
// Only a positively-declared legacy bundle is stale. Templates that don't
|
|
146
|
+
// declare fang at all (unit-test fixtures, custom hosts) are left to the
|
|
147
|
+
// existing forkBundlePath probe.
|
|
148
|
+
return !(declared.has('@twinsearth/dsh-fang') || declared.has('@twinsearth/fang-dsh-plugin-legacy'))
|
|
149
|
+
}
|
|
150
|
+
// v3.3.8: same package name but an older exact version is stale too. This is
|
|
151
|
+
// the normal upgrade case (3.3.7 essence after installing 3.3.8).
|
|
152
|
+
const dependencies = pkg?.dependencies && typeof pkg.dependencies === 'object' ? pkg.dependencies : {}
|
|
153
|
+
const declaredVersion = String(
|
|
154
|
+
dependencies['@twinsearth/fang-dsh-plugin'] ||
|
|
155
|
+
dependencies['@twinsearth/fang-dsh-plugin'] ||
|
|
156
|
+
dependencies['@twinsearth/dsh-fang'] ||
|
|
157
|
+
'',
|
|
158
|
+
).replace(/^[~^]/, '')
|
|
159
|
+
if (/^\d+\.\d+\.\d+/.test(declaredVersion) && declaredVersion !== FANG_VERSION) return false
|
|
160
|
+
return true
|
|
161
|
+
}
|
|
96
162
|
|
|
97
163
|
/** 分身 profile 可解析的 fang bundle 路径(npm 安装名/开发 link 名都接受)。 */
|
|
98
164
|
function forkBundlePath(profileDir) {
|
|
@@ -106,6 +172,15 @@ function forkBundlePath(profileDir) {
|
|
|
106
172
|
export const name = 'fang-orchestrator'
|
|
107
173
|
export const inject = []
|
|
108
174
|
|
|
175
|
+
/**
|
|
176
|
+
* v3.3.5: a fork participates in the mother's approval aggregation only while it
|
|
177
|
+
* is actually alive. Failed/stopped/reaped forks are offline state, not approval
|
|
178
|
+
* failures; they must not turn the inbox `degraded`.
|
|
179
|
+
*/
|
|
180
|
+
export function isLiveForkForApprovals(_task, status) {
|
|
181
|
+
return status === TASK_STATUS.READY || status === TASK_STATUS.RUNNING
|
|
182
|
+
}
|
|
183
|
+
|
|
109
184
|
export const Config = z.object({
|
|
110
185
|
role: z.union([z.const('mother'), z.const('fork')]).default('mother')
|
|
111
186
|
.description('配置层角色;环境 DSH_FANG_ROLE 优先(forker 派生的分身自动为 fork)'),
|
|
@@ -125,6 +200,13 @@ export const Config = z.object({
|
|
|
125
200
|
.description('新用户自动生成“默认元宝”(仅当没有任何用户元主、且默认插件已有安装时;失败不影响启动)'),
|
|
126
201
|
cliPath: z.string().default('')
|
|
127
202
|
.description('dsh 启动器路径;留空自动探测(PATH 上的 dsh / 安装目录 dsh.cmd)'),
|
|
203
|
+
accelerated: z.object({
|
|
204
|
+
cliPath: z.string().default('').description('加速版 DSH CLI 入口(@twinsearth/dsh 的 bin;留空 = FANG_ACCEL_CLI)'),
|
|
205
|
+
profile: z.string().default('fang-accelerated').description('加速版 sidecar 的 profile 名'),
|
|
206
|
+
port: z.number().min(1).max(65535).default(18080).description('加速版 sidecar 的固定端口'),
|
|
207
|
+
home: z.string().default('').description('加速版 sidecar 的 DSH_HOME;留空 = 当前 DSH_HOME'),
|
|
208
|
+
enabled: z.boolean().default(false).description('允许母体面板启动加速版 sidecar'),
|
|
209
|
+
}).default({}),
|
|
128
210
|
dataRoot: z.string().default('')
|
|
129
211
|
.description('数据根目录;留空 = $DSH_HOME/fang/<profileTag>'),
|
|
130
212
|
forksRoot: z.string().default('')
|
|
@@ -163,6 +245,29 @@ export const Config = z.object({
|
|
|
163
245
|
token: z.string().default('').description('契约 HTTP Bearer token(留空 = HTTP 契约端点禁用;不写日志/状态)'),
|
|
164
246
|
fileDir: z.string().default('').description('可选:文件 outbox 兜底目录(同机 fallback;留空 = 关闭)'),
|
|
165
247
|
pathPrefix: z.string().default('/fang/api/contract').description('契约路由前缀'),
|
|
248
|
+
// B 契约委托:加速分身 → 母体 的无头能力委托(默认只读白名单)
|
|
249
|
+
delegate: z.object({
|
|
250
|
+
enabled: z.boolean().default(true).description('是否允许委托调用(默认开启;仍受 allow 白名单约束)'),
|
|
251
|
+
allow: z.array(z.string()).default([...DEFAULT_READ_ALLOW]).description('允许委托的能力方法名;默认只读白名单'),
|
|
252
|
+
maxPayloadBytes: z.number().min(1024).max(16 * 1024 * 1024).default(64 * 1024),
|
|
253
|
+
readTimeoutMs: z.number().min(100).max(120000).default(5000),
|
|
254
|
+
writeTimeoutMs: z.number().min(100).max(600000).default(30000),
|
|
255
|
+
maxConcurrent: z.number().min(1).max(64).default(4).description('委托并发上限;超过立即 contract-rate-limited(fail-closed,不排队)'),
|
|
256
|
+
pro: z.object({
|
|
257
|
+
enabled: z.boolean().default(false).description('B-8 专业版总开关:默认 false,未开启时 fang.code.run 一律拒绝'),
|
|
258
|
+
allow: z.array(z.string()).default([]).description('逐项手动授权激活列表(每项独立显式 allow)'),
|
|
259
|
+
approvalTtlMs: z.number().min(1000).max(3600000).default(120000),
|
|
260
|
+
maxConcurrent: z.number().min(1).max(8).default(1),
|
|
261
|
+
timeoutMs: z.number().min(100).max(600000).default(30000),
|
|
262
|
+
maxOutputBytes: z.number().min(1024).max(1048576).default(65536),
|
|
263
|
+
}).default({}),
|
|
264
|
+
lsp: z.object({
|
|
265
|
+
allowedRoots: z.array(z.string()).default([]).description('LSP 委托允许的 workspaceRoot 前缀(空 = 拒绝,fail-closed;realpath 包含校验)'),
|
|
266
|
+
includeForkWorktrees: z.boolean().default(true).description('自动登记所有 fork 任务的工作区根(母体根 + fork 工作区根,显式登记)'),
|
|
267
|
+
maxLocations: z.number().min(1).max(1000).default(200).description('locations 结果上限(超出裁剪并标记 truncated)'),
|
|
268
|
+
maxResultChars: z.number().min(256).max(200000).default(20000).description('hover 等文本结果上限(超出裁剪并标记 truncated)'),
|
|
269
|
+
}).default({}),
|
|
270
|
+
}).default({}),
|
|
166
271
|
}).default({}),
|
|
167
272
|
})
|
|
168
273
|
|
|
@@ -270,12 +375,93 @@ export function normalizeSeed(seed) {
|
|
|
270
375
|
}
|
|
271
376
|
|
|
272
377
|
export function apply(ctx, config) {
|
|
378
|
+
// 必须在 roleGate 之前:fork 角色也要执行(experimental-inspector 在 fork/元主都可能加载)。
|
|
379
|
+
try { normalizeFetchDescriptor(globalThis) } catch { /* best effort */ }
|
|
380
|
+
// EB-03 全局红线:所有 fork 进程只能写自己的 DSH_HOME;母体/客户端/其他分身写入即 EPERM。
|
|
381
|
+
if (String(process.env.DSH_FANG_ROLE ?? '').toLowerCase() === 'fork') {
|
|
382
|
+
try {
|
|
383
|
+
installGlobalRedline({
|
|
384
|
+
ownHome: process.env.DSH_HOME,
|
|
385
|
+
motherData: process.env.DSH_FANG_MOTHER,
|
|
386
|
+
logger: ctx.logger,
|
|
387
|
+
})
|
|
388
|
+
} catch { /* guard must never prevent fork boot; failures are audited by caller */ }
|
|
389
|
+
}
|
|
273
390
|
const cfg = { ...Config({}), ...(config ?? {}) }
|
|
274
391
|
const gate = roleGate('orchestrator', { cfgRole: cfg.role, logger: ctx.logger })
|
|
275
392
|
if (!gate.active) return
|
|
393
|
+
// 2026-11-22:宿主 watcher EPERM 不应杀死整个 DSH host。在加载业务插件前安装
|
|
394
|
+
// fs.watch error 降级层(止损;上游仍应修复 watcher error 处理)。
|
|
395
|
+
try {
|
|
396
|
+
if (process.env.DSH_FANG_WATCH_GUARD === '1') {
|
|
397
|
+
const watchGuard = installWatchGuard({ logger: ctx.logger })
|
|
398
|
+
if (watchGuard.ok === true && watchGuard.already !== true) ctx.logger?.info?.('[fang] fs.watch error guard installed')
|
|
399
|
+
}
|
|
400
|
+
} catch { /* guard 失败不阻塞插件加载 */ }
|
|
276
401
|
const role = gate.role
|
|
277
402
|
|
|
278
403
|
const layout = resolveFangLayout({ dataRoot: cfg.dataRoot, forksRoot: cfg.forksRoot, fangHome: cfg.fangHome })
|
|
404
|
+
// P1:分身核心开关(只影响新派生/重启的分身;母体与元主不读它)。
|
|
405
|
+
const forkCoreSettings = () => readForkCoreSettings(layout.dataDir)
|
|
406
|
+
/** 当前开关期望的分身核心。 */
|
|
407
|
+
const desiredForkCoreMode = () => normalizeCoreMode(forkCoreSettings().mode)
|
|
408
|
+
/**
|
|
409
|
+
* 开关不是热更新:重新打开(restore/autostart)分身时才应用。
|
|
410
|
+
* 分身是生产盘——每次打开本来就会从模板重放 profile 配置,因此换核等价于重放一次:
|
|
411
|
+
* official ←→ accelerated 需要重新 provision(profile 形状不同),会话目录不动。
|
|
412
|
+
* @returns {{ok:boolean, switched:boolean, coreMode:string, error?:string, detail?:string}}
|
|
413
|
+
*/
|
|
414
|
+
const syncForkCoreMode = async (task, options = {}) => {
|
|
415
|
+
const force = options?.force === true
|
|
416
|
+
const desired = desiredForkCoreMode()
|
|
417
|
+
const current = normalizeCoreMode(task?.coreMode)
|
|
418
|
+
// 2026-11-22:重新打开/换核前先捕获元主 Web 的最新插件设置,保证分身与元主同步。
|
|
419
|
+
if (task?.essenceId) {
|
|
420
|
+
captureEssenceRuntimeIfPresent(task.essenceId)
|
|
421
|
+
if (task.essenceId === OFFICIAL_ESSENCE_ID) await repairOfficialEssenceNow()
|
|
422
|
+
}
|
|
423
|
+
if (!task || (desired === current && !force)) return { ok: true, switched: false, coreMode: current || desired }
|
|
424
|
+
const f = forker()
|
|
425
|
+
if (!f || typeof f.provision !== 'function') return { ok: false, switched: false, coreMode: current, error: 'forker-unavailable' }
|
|
426
|
+
let provisioned
|
|
427
|
+
if (desired === 'accelerated') {
|
|
428
|
+
// 原身派生的分身:重新打开换加速核时同步原身插件面(与 createTask 一致)。
|
|
429
|
+
let sourceProfileDir = ''
|
|
430
|
+
if (task.sourceEssence?.id) {
|
|
431
|
+
try { sourceProfileDir = essenceManager.mergedProfileDir(task.sourceEssence.id) } catch { sourceProfileDir = '' }
|
|
432
|
+
}
|
|
433
|
+
provisioned = await f.provision({
|
|
434
|
+
forkId: task.taskId,
|
|
435
|
+
taskTitle: task.title,
|
|
436
|
+
homeDir: task.homeDir,
|
|
437
|
+
profile: task.profile,
|
|
438
|
+
coreMode: 'accelerated',
|
|
439
|
+
...(sourceProfileDir ? { sourceProfileDir } : {}),
|
|
440
|
+
})
|
|
441
|
+
} else {
|
|
442
|
+
provisioned = await f.provision({
|
|
443
|
+
forkId: task.taskId,
|
|
444
|
+
taskTitle: task.title,
|
|
445
|
+
homeDir: task.homeDir,
|
|
446
|
+
profile: task.profile,
|
|
447
|
+
profileTemplate: templateDir(),
|
|
448
|
+
cleanTemplate: true,
|
|
449
|
+
coreMode: 'stock',
|
|
450
|
+
nodeModulesSource: path.join(templateDir(), 'node_modules'),
|
|
451
|
+
})
|
|
452
|
+
}
|
|
453
|
+
if (!provisioned || provisioned.ok === false) {
|
|
454
|
+
return { ok: false, switched: false, coreMode: current, error: desired === 'accelerated' ? 'accelerated-provision-failed' : 'stock-provision-failed', detail: provisioned?.error }
|
|
455
|
+
}
|
|
456
|
+
task.prevCoreMode = current
|
|
457
|
+
task.coreMode = desired
|
|
458
|
+
if (provisioned?.accelerated?.sync) task.acceleratedSync = provisioned.accelerated.sync
|
|
459
|
+
task.updatedAt = nowMs()
|
|
460
|
+
persist()
|
|
461
|
+
try { audit('fang/fork-core-switched', { taskId: task.taskId, from: current, to: desired }) } catch { /* audit optional */ }
|
|
462
|
+
try { bus.emit('fang/fork-core-switched', { taskId: task.taskId, from: current, to: desired }) } catch { /* bus optional */ }
|
|
463
|
+
return { ok: true, switched: true, coreMode: desired }
|
|
464
|
+
}
|
|
279
465
|
const branchStore = new BranchStore(layout.dataDir)
|
|
280
466
|
const composerJournal = new ComposerJournal(layout.dataDir)
|
|
281
467
|
// v3.0.5/B1:安装级 token(0600 文件 / env / 显式配置);关闭仅限测试
|
|
@@ -299,6 +485,10 @@ export function apply(ctx, config) {
|
|
|
299
485
|
}
|
|
300
486
|
|
|
301
487
|
const safeGet = (key) => { try { return ctx.get(key) } catch { return undefined } }
|
|
488
|
+
// v3.3.3: queue journal is an optional sub-plugin. Its host half provides
|
|
489
|
+
// SERVICE.queueJournal; without it the journal/queue routes must fail closed
|
|
490
|
+
// and the client half is never registered (row disabled -> no UI).
|
|
491
|
+
const queueJournalEnabled = () => Boolean(safeGet(SERVICE.queueJournal))
|
|
302
492
|
/**
|
|
303
493
|
* 宿主内部生产者 → 决策中心(best-effort,绝不改变原流程结果)。
|
|
304
494
|
* 用于 MirrorUpgrade / EssenceManager 这类仓内对象;外部系统(PM/PJM/Worker/
|
|
@@ -328,9 +518,66 @@ export function apply(ctx, config) {
|
|
|
328
518
|
} catch { return null }
|
|
329
519
|
}
|
|
330
520
|
const businessProducers = createBusinessProducers({ submit: (spec) => raiseDecisionTicket(spec) })
|
|
521
|
+
// R15:审计失败不再完全静默——累计失败数 + 限频告警,并暴露在 /fang/api/status.audit。
|
|
522
|
+
// 失败语义保持不变(audit() 不抛:审计不可用不能把普通业务路径打挂);安全关键路径用 auditStrict()。
|
|
523
|
+
let auditFailures = 0
|
|
524
|
+
let lastAuditError = null
|
|
525
|
+
let lastAuditWarnAt = 0
|
|
526
|
+
const recordAuditFailure = (kind, error) => {
|
|
527
|
+
auditFailures += 1
|
|
528
|
+
lastAuditError = String(error?.message ?? error ?? 'audit-append-failed').slice(0, 300)
|
|
529
|
+
const now = Date.now()
|
|
530
|
+
if (now - lastAuditWarnAt >= 60_000) {
|
|
531
|
+
lastAuditWarnAt = now
|
|
532
|
+
try { ctx.logger?.warn?.(`[fang] 审计写入失败(kind=${String(kind)}):${lastAuditError}`) } catch { /* logger optional */ }
|
|
533
|
+
}
|
|
534
|
+
}
|
|
331
535
|
const audit = (kind, data) => {
|
|
332
|
-
try {
|
|
536
|
+
try {
|
|
537
|
+
const auditor = safeGet(SERVICE.auditor)
|
|
538
|
+
if (auditor && typeof auditor.append === 'function') {
|
|
539
|
+
const record = auditor.append(kind, data)
|
|
540
|
+
if (record === null || record === undefined) throw new Error('audit-append-failed')
|
|
541
|
+
}
|
|
542
|
+
} catch (error) {
|
|
543
|
+
recordAuditFailure(kind, error)
|
|
544
|
+
}
|
|
545
|
+
try { bus.emit('fang/audit', { kind, data }) } catch { /* ignore */ }
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* 安全关键路径的审计:必须确实写入链,否则抛错让调用方 fail-closed
|
|
549
|
+
* (R15:静默丢失比拒绝更危险;审计服务缺失时仍允许“跳过”,与旧部署兼容)。
|
|
550
|
+
*/
|
|
551
|
+
const auditStrict = (kind, data) => {
|
|
552
|
+
const auditor = safeGet(SERVICE.auditor)
|
|
553
|
+
if (!auditor) return { ok: true, skipped: true }
|
|
554
|
+
let record = null
|
|
555
|
+
try {
|
|
556
|
+
if (typeof auditor.appendStrict === 'function') record = auditor.appendStrict(kind, data)
|
|
557
|
+
else {
|
|
558
|
+
record = typeof auditor.append === 'function' ? auditor.append(kind, data) : null
|
|
559
|
+
if (record === null || record === undefined) throw new Error('audit-append-failed')
|
|
560
|
+
}
|
|
561
|
+
} catch (error) {
|
|
562
|
+
recordAuditFailure(kind, error)
|
|
563
|
+
throw error instanceof Error ? error : new Error(String(error))
|
|
564
|
+
}
|
|
333
565
|
try { bus.emit('fang/audit', { kind, data }) } catch { /* ignore */ }
|
|
566
|
+
return { ok: true, record }
|
|
567
|
+
}
|
|
568
|
+
/** 审计健康快照(只读):auditor 自述 + 本进程观察到的失败。 */
|
|
569
|
+
const auditHealth = () => {
|
|
570
|
+
let auditorStatus = null
|
|
571
|
+
try {
|
|
572
|
+
const auditor = safeGet(SERVICE.auditor)
|
|
573
|
+
if (auditor && typeof auditor.status === 'function') auditorStatus = auditor.status()
|
|
574
|
+
} catch { auditorStatus = null }
|
|
575
|
+
return {
|
|
576
|
+
...(auditorStatus ?? {}),
|
|
577
|
+
processFailures: auditFailures,
|
|
578
|
+
processLastError: lastAuditError,
|
|
579
|
+
ok: auditFailures === 0 && (auditorStatus === null || auditorStatus.ok !== false),
|
|
580
|
+
}
|
|
334
581
|
}
|
|
335
582
|
const persist = () => {
|
|
336
583
|
try {
|
|
@@ -342,10 +589,30 @@ export function apply(ctx, config) {
|
|
|
342
589
|
}
|
|
343
590
|
const forker = () => safeGet(SERVICE.forker)
|
|
344
591
|
const cliPath = () => (cfg.cliPath ? cfg.cliPath : resolveCliPath('', process.env))
|
|
592
|
+
const forkTempEnv = (taskId) => {
|
|
593
|
+
const tmp = path.join(layout.forkHomesDir, String(taskId), 'tmp')
|
|
594
|
+
try { ensureDir(tmp) } catch { /* best effort */ }
|
|
595
|
+
return { TEMP: tmp, TMP: tmp }
|
|
596
|
+
}
|
|
597
|
+
// P2:每个版本一份不可变安装快照;stock 分身使用自己的快照 CLI,母体安装升级/替换
|
|
598
|
+
// 不会改变运行中分身解析到的 app.asar/runtime。快照创建失败时显式回退共享安装。
|
|
599
|
+
let installSnapshotMemo = null
|
|
600
|
+
const forkCliPath = () => {
|
|
601
|
+
// P2-A 安装快照默认关闭:首次创建需对约 1.1GB/7,884 文件的安装树做 hardlink,
|
|
602
|
+
// 在部分卷/目录结构上会退化为复制并超过 fork spawn 的 60s 预算,导致“启动失败”。
|
|
603
|
+
// 验证通过后可显式 DSH_FANG_INSTALL_SNAPSHOT=1 启用(启动前预热快照)。
|
|
604
|
+
if (process.env.DSH_FANG_INSTALL_SNAPSHOT !== '1') return cliPath()
|
|
605
|
+
if (installSnapshotMemo) return installSnapshotMemo.cliPath
|
|
606
|
+
const result = ensureInstallSnapshot({ cliPath: cliPath(), version: FANG_VERSION })
|
|
607
|
+
installSnapshotMemo = result
|
|
608
|
+
if (result.ok !== true) audit('fork-install-snapshot-failed', { error: result.error ?? 'unknown' })
|
|
609
|
+
else audit('fork-install-snapshot-ready', { root: result.root, created: result.created })
|
|
610
|
+
return result.ok === true ? result.cliPath : cliPath()
|
|
611
|
+
}
|
|
345
612
|
// The booted profile's own directory is authoritative (launcher sets DSH_PROFILE_DIR);
|
|
346
613
|
// resolving "$DSH_HOME/profiles/<tag>" from argv can point at a template that never existed.
|
|
347
614
|
// 分身模板必须来自一个**真的装了本 bundle** 的 profile;否则分身的 node_modules junction
|
|
348
|
-
// 指到一个没有 @twinsearth/dsh-
|
|
615
|
+
// 指到一个没有 @twinsearth/fang-dsh-plugin 的 profile,fork 里所有 /fang 路由都会 404(实测事故)。
|
|
349
616
|
const templateDir = () => {
|
|
350
617
|
const candidates = [cfg.profileTemplate, process.env.DSH_PROFILE_DIR, resolveProfileDir(motherProfile), resolveProfileDir(layout.profileTag)]
|
|
351
618
|
const usable = candidates.filter((dir) => typeof dir === "string" && dir.trim()
|
|
@@ -383,6 +650,8 @@ export function apply(ctx, config) {
|
|
|
383
650
|
template: f.template ?? '',
|
|
384
651
|
essenceId: f.essenceId ?? null,
|
|
385
652
|
sourceEssence: f.sourceEssence ?? null,
|
|
653
|
+
syncSourceId: f.syncSourceId ?? f.essenceId ?? OFFICIAL_ESSENCE_ID,
|
|
654
|
+
configSourceFingerprint: f.configSourceFingerprint ?? null,
|
|
386
655
|
}
|
|
387
656
|
}
|
|
388
657
|
|
|
@@ -497,6 +766,9 @@ export function apply(ctx, config) {
|
|
|
497
766
|
return {
|
|
498
767
|
taskId: t.taskId,
|
|
499
768
|
forkId: t.taskId,
|
|
769
|
+
coreMode: t.coreMode === 'accelerated' ? 'accelerated' : 'stock',
|
|
770
|
+
// D2:加速分身的插件面同步报告(映射成功/不支持清单/被复制插件),无则不出现。
|
|
771
|
+
acceleratedSync: t.acceleratedSync ?? null,
|
|
500
772
|
title: t.title,
|
|
501
773
|
taskTitle: t.title,
|
|
502
774
|
status,
|
|
@@ -525,9 +797,9 @@ export function apply(ctx, config) {
|
|
|
525
797
|
return { activeBranchId: t.activeBranchId ?? null, sessionId: null, count: 0 }
|
|
526
798
|
}
|
|
527
799
|
})(),
|
|
528
|
-
pid: live?.pid ?? t.pid ?? null,
|
|
529
|
-
port: t.port ?? null,
|
|
530
|
-
url: stripUrlToken(t.url),
|
|
800
|
+
pid: running ? (live?.pid ?? t.pid ?? null) : null,
|
|
801
|
+
port: running ? (t.port ?? null) : null,
|
|
802
|
+
url: running ? stripUrlToken(t.url) : null,
|
|
531
803
|
homeDir: t.homeDir,
|
|
532
804
|
profile: t.profile,
|
|
533
805
|
createdAt: t.createdAt,
|
|
@@ -687,6 +959,56 @@ export function apply(ctx, config) {
|
|
|
687
959
|
try { return String(readJson(defaultEssenceFile, {})?.essenceId ?? '') } catch { return '' }
|
|
688
960
|
}
|
|
689
961
|
const writeDefaultEssenceId = (essenceId) => writeJsonAtomic(defaultEssenceFile, { essenceId: String(essenceId), at: nowMs() })
|
|
962
|
+
// v3.3.8: after an upgrade the default essence still pins the previous fang
|
|
963
|
+
// version. Auto-capture the current mother profile as a fresh essence and make
|
|
964
|
+
// it default, so future forks never start from an old snapshot.
|
|
965
|
+
let autoRefreshPromise = null
|
|
966
|
+
let lastAutoRefresh = null
|
|
967
|
+
const refreshStaleDefaultEssenceIfNeeded = () => {
|
|
968
|
+
if (autoRefreshPromise) return autoRefreshPromise
|
|
969
|
+
autoRefreshPromise = (async () => {
|
|
970
|
+
// 2026-11-22:官方「开发者推荐(官方)」存在时它就是默认底座,不再自动捕获
|
|
971
|
+
// “默认元宝 · 自动同步”快照(旧逻辑每次宿主重启都会新增一个,永不收敛)。
|
|
972
|
+
const official = essenceManager.getMeta(OFFICIAL_ESSENCE_ID)
|
|
973
|
+
if (official?.id && official.archived !== true) {
|
|
974
|
+
return (lastAutoRefresh = { ok: true, skipped: 'official-essence-default' })
|
|
975
|
+
}
|
|
976
|
+
// Two defaults exist: default-essence.json (quick derive) and the mirror
|
|
977
|
+
// default used by the essence list/UI. Accept either; capture({setDefault})
|
|
978
|
+
// writes only the mirror default, so reading the file alone would skip.
|
|
979
|
+
const mirrorDefault = typeof essenceManager.getDefault === 'function' ? essenceManager.getDefault() : null
|
|
980
|
+
const essenceId = readDefaultEssenceId() || String(mirrorDefault?.essenceId ?? '')
|
|
981
|
+
if (!essenceId) return (lastAutoRefresh = { ok: true, skipped: 'no-default-essence' })
|
|
982
|
+
const meta = essenceManager.getMeta(essenceId)
|
|
983
|
+
if (!meta?.id) return (lastAutoRefresh = { ok: false, skipped: 'default-essence-missing', essenceId })
|
|
984
|
+
const mergedDir = essenceManager.mergedProfileDir(essenceId)
|
|
985
|
+
if (profileUsesCurrentFangBundle(mergedDir)) {
|
|
986
|
+
return (lastAutoRefresh = { ok: true, skipped: 'already-current', essenceId })
|
|
987
|
+
}
|
|
988
|
+
try {
|
|
989
|
+
const captured = essenceManager.captureFromProfile(templateDir(), {
|
|
990
|
+
name: `${DEFAULT_ESSENCE_NAME} · 自动同步 ${FANG_VERSION}`,
|
|
991
|
+
tier: meta.tier ?? 'free',
|
|
992
|
+
includeDependencies: true,
|
|
993
|
+
includeSettings: true,
|
|
994
|
+
})
|
|
995
|
+
essenceManager.setDefault(captured.meta.id)
|
|
996
|
+
writeDefaultEssenceId(captured.meta.id)
|
|
997
|
+
audit('essence-auto-refreshed', {
|
|
998
|
+
from: essenceId, to: captured.meta.id, fromVersion: String(meta?.fangVersion ?? 'unknown'), version: FANG_VERSION,
|
|
999
|
+
})
|
|
1000
|
+
return (lastAutoRefresh = {
|
|
1001
|
+
ok: true, from: essenceId, to: captured.meta.id, version: FANG_VERSION,
|
|
1002
|
+
name: captured.meta.name,
|
|
1003
|
+
})
|
|
1004
|
+
} catch (error) {
|
|
1005
|
+
const detail = String(error?.message ?? error)
|
|
1006
|
+
audit('essence-auto-refresh-failed', { from: essenceId, error: detail })
|
|
1007
|
+
return (lastAutoRefresh = { ok: false, from: essenceId, error: detail })
|
|
1008
|
+
}
|
|
1009
|
+
})().finally(() => { autoRefreshPromise = null })
|
|
1010
|
+
return autoRefreshPromise
|
|
1011
|
+
}
|
|
690
1012
|
const listInstalledPlugins = async () => {
|
|
691
1013
|
try {
|
|
692
1014
|
const pm = safeGet('pluginManager')
|
|
@@ -771,6 +1093,7 @@ export function apply(ctx, config) {
|
|
|
771
1093
|
if (presetId && essenceManager.getMeta(presetId)?.id) essenceIdInput = presetId
|
|
772
1094
|
}
|
|
773
1095
|
let sourceEssence = null
|
|
1096
|
+
let templateFallback = null
|
|
774
1097
|
if (essenceIdInput) {
|
|
775
1098
|
const essenceId = essenceIdInput
|
|
776
1099
|
const meta = essenceManager.getMeta(essenceId)
|
|
@@ -778,9 +1101,21 @@ export function apply(ctx, config) {
|
|
|
778
1101
|
return { ok: false, error: isTombstoned(essenceId) ? 'essence-deleted' : 'unknown-essence' }
|
|
779
1102
|
}
|
|
780
1103
|
if (meta.archived === true) return { ok: false, error: 'essence-archived' }
|
|
1104
|
+
captureEssenceRuntimeIfPresent(essenceId)
|
|
1105
|
+
if (essenceId === OFFICIAL_ESSENCE_ID) await repairOfficialEssenceNow()
|
|
781
1106
|
await essenceManager.ensureFresh(essenceId)
|
|
782
1107
|
const fresh = essenceManager.getMeta(essenceId)
|
|
783
|
-
|
|
1108
|
+
const mergedDir = essenceManager.mergedProfileDir(essenceId)
|
|
1109
|
+
// v3.3.7: an old essence can still declare the legacy bundle while the
|
|
1110
|
+
// current profile has no such package. Deriving from it produces a
|
|
1111
|
+
// process whose Adapter never mounts (404), so fall back to the clean
|
|
1112
|
+
// template built from the current mother instead of a zombie fork.
|
|
1113
|
+
if (!profileUsesCurrentFangBundle(mergedDir)) {
|
|
1114
|
+
templateFallback = { from: essenceId, name: String(meta.name ?? ''), reason: 'stale-legacy-bundle' }
|
|
1115
|
+
audit('fork-template-stale', { essenceId, name: String(meta.name ?? ''), fallback: 'clean-template' })
|
|
1116
|
+
} else {
|
|
1117
|
+
sourceEssence = { id: essenceId, name: meta.name, fingerprint: fresh?.lastMergedFingerprint ?? null }
|
|
1118
|
+
}
|
|
784
1119
|
}
|
|
785
1120
|
const profileTemplate = sourceEssence
|
|
786
1121
|
? essenceManager.mergedProfileDir(sourceEssence.id)
|
|
@@ -794,13 +1129,27 @@ export function apply(ctx, config) {
|
|
|
794
1129
|
createdAt: nowMs(),
|
|
795
1130
|
collaborators: Array.isArray(input.collaborators) ? input.collaborators : [],
|
|
796
1131
|
template,
|
|
1132
|
+
templateFallback,
|
|
797
1133
|
essenceId: sourceEssence?.id ?? null,
|
|
798
1134
|
sourceEssence,
|
|
1135
|
+
// 2026-11-22:所有分身(含模板/空白)都以官方推荐为默认同步源;每次打开都会
|
|
1136
|
+
// 对比源 fingerprint,源变化则重启并重新 provision,而不是等用户手动修复。
|
|
1137
|
+
syncSourceId: sourceEssence?.id ?? OFFICIAL_ESSENCE_ID,
|
|
1138
|
+
configSourceFingerprint: null,
|
|
799
1139
|
adapter: { ok: false, error: 'handshaking' },
|
|
800
1140
|
})
|
|
801
1141
|
tasks.set(taskId, task)
|
|
802
1142
|
persist()
|
|
803
1143
|
|
|
1144
|
+
// P1:核心选择只作用于分身。显式 input.coreMode 优先,否则读面板开关。
|
|
1145
|
+
const coreSettings = forkCoreSettings()
|
|
1146
|
+
const coreMode = normalizeCoreMode(input.coreMode ?? coreSettings.mode)
|
|
1147
|
+
// 会话策略:加速核默认只新会话;`copy` 允许把旧会话复制进分身(新副本,绝不原地挂载)。
|
|
1148
|
+
const allowSessionImport = coreMode !== 'accelerated' || coreSettings.sessionMode === 'copy'
|
|
1149
|
+
task.coreMode = coreMode
|
|
1150
|
+
task.sessionMode = coreSettings.sessionMode
|
|
1151
|
+
task.configSourceFingerprint = essenceManager.getMeta(sourceEssence?.id ?? OFFICIAL_ESSENCE_ID)?.lastMergedFingerprint ?? null
|
|
1152
|
+
|
|
804
1153
|
try {
|
|
805
1154
|
const provisioned = await f.provision({
|
|
806
1155
|
forkId: taskId,
|
|
@@ -808,9 +1157,11 @@ export function apply(ctx, config) {
|
|
|
808
1157
|
homeDir,
|
|
809
1158
|
profile,
|
|
810
1159
|
profileTemplate,
|
|
811
|
-
|
|
1160
|
+
coreMode,
|
|
1161
|
+
// 加速档 + 原身派生:同步原身插件面(第三方包复制 + @deepseek-ai/* 别名桩包)。
|
|
1162
|
+
...(coreMode === 'accelerated' && sourceEssence ? { sourceProfileDir: profileTemplate } : {}),
|
|
812
1163
|
// node_modules:优先元主自己的模块树;默认元宝/新建原身可能尚未物化 node_modules,
|
|
813
|
-
// 此时回退母体模块树,保证分身仍能解析 @twinsearth/dsh-
|
|
1164
|
+
// 此时回退母体模块树,保证分身仍能解析 @twinsearth/fang-dsh-plugin(否则是僵尸分身)。
|
|
814
1165
|
...(sourceEssence ? {
|
|
815
1166
|
cleanTemplate: false,
|
|
816
1167
|
nodeModulesSource: (() => {
|
|
@@ -825,12 +1176,20 @@ export function apply(ctx, config) {
|
|
|
825
1176
|
persist()
|
|
826
1177
|
return { ok: false, error: 'provision-failed', detail: provisioned.error }
|
|
827
1178
|
}
|
|
828
|
-
|
|
1179
|
+
const experimentalSurface = applyOfficialExperimentalSurface(path.join(homeDir, 'profiles', profile), { coreMode })
|
|
1180
|
+
if (experimentalSurface.ok === false) audit('fork-experimental-surface-failed', { taskId, error: experimentalSurface.error })
|
|
1181
|
+
// D2:记录加速分身的插件面同步结果(哪些映射成功、哪些不支持、哪些插件被复制)。
|
|
1182
|
+
if (provisioned?.accelerated?.sync) {
|
|
1183
|
+
task.acceleratedSync = provisioned.accelerated.sync
|
|
1184
|
+
persist()
|
|
1185
|
+
}
|
|
1186
|
+
audit(AUDIT.FORK_CREATED, { taskId, forkId: taskId, title, homeDir, profile, templateFallback })
|
|
829
1187
|
|
|
830
1188
|
// 防御:分身的 profile 必须能解析本 bundle;否则派生出来的是一个"没有 /fang 路由"的
|
|
831
1189
|
// 僵尸分身(adapter 握手会得到 http-404)。发现即回收并如实报错。
|
|
832
|
-
// npm 安装名是 @twinsearth/dsh-fang
|
|
1190
|
+
// npm 安装名是 @twinsearth/fang-dsh-plugin;旧包名 @twinsearth/dsh-fang 与开发 link @twinsearth/fang-dsh-plugin 继续兼容。
|
|
833
1191
|
const forkProfileDir = path.join(homeDir, 'profiles', profile)
|
|
1192
|
+
if (process.env.DSH_FANG_E2E_DEBUG === '1') { try { copyTree(forkProfileDir, path.join(layout.dataDir, 'debug-fork-profile')) } catch { /* debug best effort */ } }
|
|
834
1193
|
const forkBundle = forkBundlePath(forkProfileDir)
|
|
835
1194
|
if (!forkBundle) {
|
|
836
1195
|
task.status = TASK_STATUS.FAILED
|
|
@@ -866,13 +1225,19 @@ export function apply(ctx, config) {
|
|
|
866
1225
|
}
|
|
867
1226
|
}
|
|
868
1227
|
|
|
869
|
-
if (
|
|
1228
|
+
if (!allowSessionImport) {
|
|
1229
|
+
task.importedSession = { ok: false, reason: 'accelerated-new-session' }
|
|
1230
|
+
audit(AUDIT.FORK_CREATED + '-import-skipped', { taskId, reason: 'accelerated-new-session', coreMode })
|
|
1231
|
+
persist()
|
|
1232
|
+
} else if (input.importSession && typeof input.importSession === 'object') {
|
|
870
1233
|
const importSpec = input.importSession
|
|
1234
|
+
// 加速分身(sessionMode:'copy'):旧会话只以**复制副本**进入分身 home,绝不原地读原会话。
|
|
1235
|
+
const copyMode = coreMode === 'accelerated'
|
|
871
1236
|
// 新入口:只给 sessionId(元主栏“派生”按钮)→ 由会话目录整目录复制进分身。
|
|
872
1237
|
if (importSpec.sessionId && !importSpec.sourceFile) {
|
|
873
1238
|
try {
|
|
874
1239
|
const imported = importSessionsInto(homeDir, [importSpec.sessionId])
|
|
875
|
-
task.importedSession = imported[0] ? { ok: true, ...imported[0] } : { ok: false, reason: 'not-imported' }
|
|
1240
|
+
task.importedSession = imported[0] ? { ok: true, ...imported[0], copied: true, source: 'copy' } : { ok: false, reason: 'not-imported' }
|
|
876
1241
|
audit(AUDIT.FORK_CREATED + '-import', { taskId, ...task.importedSession })
|
|
877
1242
|
} catch (e) {
|
|
878
1243
|
task.importedSession = { ok: false, reason: 'import-failed', error: String(e?.message ?? e) }
|
|
@@ -893,6 +1258,16 @@ export function apply(ctx, config) {
|
|
|
893
1258
|
|
|
894
1259
|
// v3.1.35:分身会话下限 1 —— 没有导入会话时补一个空会话,
|
|
895
1260
|
// 让分身 Web 打开就有可用的会话(用户规格:默认不能为 0)。
|
|
1261
|
+
if (coreMode === 'accelerated') {
|
|
1262
|
+
// 2026-11-22: accelerated core 3.5.0 cannot read catalog v3 facts; sessions copied
|
|
1263
|
+
// from a stock mother must be downgraded before the fork reads them.
|
|
1264
|
+
try {
|
|
1265
|
+
const sanitized = sanitizeAcceleratedForkSessions(homeDir)
|
|
1266
|
+
if (sanitized.changedEvents > 0) audit(AUDIT.FORK_CREATED + '-catalog-downgraded', { taskId, ...sanitized })
|
|
1267
|
+
} catch (error) {
|
|
1268
|
+
audit(AUDIT.FORK_CREATED + '-catalog-sanitize-failed', { taskId, error: String(error?.message ?? error) })
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
896
1271
|
try {
|
|
897
1272
|
const floors = await ensureForkSessionFloor({ homeDir, task, cwd: input.cwd })
|
|
898
1273
|
task.sessionFloor = floors
|
|
@@ -908,15 +1283,32 @@ export function apply(ctx, config) {
|
|
|
908
1283
|
forkId: taskId,
|
|
909
1284
|
homeDir,
|
|
910
1285
|
profile,
|
|
911
|
-
|
|
912
|
-
|
|
1286
|
+
// 加速档只解析加速核入口;stock 母体 CLI 绝不能传入(v3.5.2 起会误判/失败)。
|
|
1287
|
+
...(coreMode === 'accelerated' ? {} : { cliPath: forkCliPath() }),
|
|
1288
|
+
coreMode,
|
|
1289
|
+
env: { DSH_FANG_ROLE: 'fork', DSH_FANG_TASK_ID: taskId, DSH_FANG_MOTHER: layout.dataDir, ...forkTempEnv(taskId) },
|
|
913
1290
|
})
|
|
914
1291
|
if (!started || started.ok === false) {
|
|
915
1292
|
task.status = TASK_STATUS.FAILED
|
|
1293
|
+
task.lastError = started?.error ?? 'spawn-failed'
|
|
916
1294
|
persist()
|
|
917
|
-
audit(AUDIT.FORK_CRASHED, { taskId, error: started?.error ?? 'spawn-failed' })
|
|
1295
|
+
audit(AUDIT.FORK_CRASHED, { taskId, error: started?.error ?? 'spawn-failed', coreMode })
|
|
918
1296
|
bus.emit('fang/task-failed', { taskId, error: started?.error ?? 'spawn-failed' })
|
|
919
|
-
return {
|
|
1297
|
+
return {
|
|
1298
|
+
ok: false,
|
|
1299
|
+
error: started?.error === 'accelerated-cli-missing' ? 'accelerated-cli-missing' : 'spawn-failed',
|
|
1300
|
+
detail: started?.error ?? 'unknown',
|
|
1301
|
+
...(Array.isArray(started?.searched) ? { searched: started.searched } : {}),
|
|
1302
|
+
// 失败可见性:spawn 失败时把子进程退出码/信号/输出尾部带回任务接口,避免只剩 "exited"。
|
|
1303
|
+
...(started && started.error !== 'accelerated-cli-missing'
|
|
1304
|
+
? {
|
|
1305
|
+
exit: started.exit ?? null,
|
|
1306
|
+
signal: started.signal ?? null,
|
|
1307
|
+
kind: started.kind ?? null,
|
|
1308
|
+
log: Array.isArray(started.log) ? started.log : [],
|
|
1309
|
+
}
|
|
1310
|
+
: {}),
|
|
1311
|
+
}
|
|
920
1312
|
}
|
|
921
1313
|
task.status = TASK_STATUS.RUNNING
|
|
922
1314
|
task.pid = started.pid ?? null
|
|
@@ -1015,6 +1407,61 @@ export function apply(ctx, config) {
|
|
|
1015
1407
|
}
|
|
1016
1408
|
},
|
|
1017
1409
|
|
|
1410
|
+
/** 2026-11-22:一键导出分身完整 home(不含可再生的 node_modules/tmp)。 */
|
|
1411
|
+
async exportTask(taskId, destDir, options = {}) {
|
|
1412
|
+
const task = tasks.get(String(taskId ?? '').trim())
|
|
1413
|
+
if (!task) return { ok: false, error: 'unknown-task' }
|
|
1414
|
+
if (!destDir || !path.isAbsolute(String(destDir))) return { ok: false, error: 'dest-dir-required' }
|
|
1415
|
+
let workspacePath = ''
|
|
1416
|
+
try {
|
|
1417
|
+
const ws = readJson(path.join(task.homeDir, 'storages', 'workspace.json'), {})
|
|
1418
|
+
workspacePath = Object.values(ws?.tables?.workspaces ?? {}).map((item) => String(item?.path ?? '')).find(Boolean) ?? ''
|
|
1419
|
+
} catch { /* optional */ }
|
|
1420
|
+
const out = exportVault({ homeDir: task.homeDir, destDir: String(destDir), task: { ...task, workspacePath }, options })
|
|
1421
|
+
if (out.ok) audit('fork-exported', { taskId: task.taskId, dir: out.dir, files: out.files, bytes: out.bytes })
|
|
1422
|
+
return out
|
|
1423
|
+
},
|
|
1424
|
+
|
|
1425
|
+
/** 2026-11-22:一键导入分身导出包,复制 home/profile 后重新拉起并握手。 */
|
|
1426
|
+
async importTask(sourceDir, title) {
|
|
1427
|
+
const parsed = readVault(sourceDir)
|
|
1428
|
+
if (!parsed.ok) return parsed
|
|
1429
|
+
const id = newId('task')
|
|
1430
|
+
const profile = `fang-${id.slice(-12)}`
|
|
1431
|
+
const homeDir = path.join(layout.forkHomesDir, id)
|
|
1432
|
+
if (exists(homeDir)) return { ok: false, error: 'task-exists', taskId: id }
|
|
1433
|
+
ensureDir(path.dirname(homeDir))
|
|
1434
|
+
const imported = importVault({ sourceDir, homeDir, profile })
|
|
1435
|
+
if (imported.ok !== true) return imported
|
|
1436
|
+
const targetProfileDir = path.join(homeDir, 'profiles', profile)
|
|
1437
|
+
// 导出包不含 node_modules:从母体/官方 merged 重新移植依赖树,再拉起。
|
|
1438
|
+
const importedModules = path.join(targetProfileDir, 'node_modules')
|
|
1439
|
+
if (!exists(importedModules)) {
|
|
1440
|
+
const motherModules = path.join(linkProfileDir() || essenceManager.mergedProfileDir(OFFICIAL_ESSENCE_ID), 'node_modules')
|
|
1441
|
+
if (exists(motherModules)) {
|
|
1442
|
+
try { fs.symlinkSync(motherModules, importedModules, 'junction') } catch { /* mirror repair will retry */ }
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
try { syncProfileModulesFromMother(targetProfileDir, linkProfileDir() || essenceManager.mergedProfileDir(OFFICIAL_ESSENCE_ID)) } catch { /* best effort */ }
|
|
1446
|
+
const task = normalizeTask({
|
|
1447
|
+
taskId: id,
|
|
1448
|
+
title: String(title ?? '').trim() || String(parsed.manifest?.title ?? '').trim() || `导入的分身 ${id.slice(-6)}`,
|
|
1449
|
+
profile,
|
|
1450
|
+
homeDir,
|
|
1451
|
+
status: TASK_STATUS.FAILED,
|
|
1452
|
+
coreMode: parsed.manifest?.coreMode === 'accelerated' ? 'accelerated' : 'stock',
|
|
1453
|
+
essenceId: null,
|
|
1454
|
+
syncSourceId: OFFICIAL_ESSENCE_ID,
|
|
1455
|
+
configSourceFingerprint: essenceManager.getMeta(OFFICIAL_ESSENCE_ID)?.lastMergedFingerprint ?? null,
|
|
1456
|
+
importedSnapshot: true,
|
|
1457
|
+
})
|
|
1458
|
+
tasks.set(id, task)
|
|
1459
|
+
persist()
|
|
1460
|
+
audit('fork-imported', { taskId: id, sourceDir: parsed.dir, files: parsed.manifest?.files ?? 0, profile })
|
|
1461
|
+
const restored = await service.restoreTask(id, { preserveProfile: true })
|
|
1462
|
+
return { ok: restored.ok === true, taskId: id, title: task.title, restored, dir: parsed.dir }
|
|
1463
|
+
},
|
|
1464
|
+
|
|
1018
1465
|
listForks() {
|
|
1019
1466
|
return service.listTasks()
|
|
1020
1467
|
},
|
|
@@ -1461,12 +1908,13 @@ export function apply(ctx, config) {
|
|
|
1461
1908
|
const id = String(taskId ?? '')
|
|
1462
1909
|
const task = tasks.get(id)
|
|
1463
1910
|
if (!task) return { ok: false, error: 'unknown-task' }
|
|
1464
|
-
|
|
1465
|
-
|
|
1911
|
+
const sourceId = String(task.essenceId || task.syncSourceId || OFFICIAL_ESSENCE_ID)
|
|
1912
|
+
if (!task.essenceId && !task.syncSourceId) return { ok: false, error: 'no-source-essence' }
|
|
1913
|
+
const meta = essenceManager.getMeta(sourceId)
|
|
1466
1914
|
if (!meta || typeof meta.id !== 'string') return { ok: false, error: 'source-essence-missing' }
|
|
1467
1915
|
if (meta.archived === true) return { ok: false, error: 'source-essence-archived' }
|
|
1468
|
-
await essenceManager.ensureFresh(
|
|
1469
|
-
const source = essenceManager.mergedProfileDir(
|
|
1916
|
+
await essenceManager.ensureFresh(sourceId)
|
|
1917
|
+
const source = essenceManager.mergedProfileDir(sourceId)
|
|
1470
1918
|
const target = path.join(task.homeDir, 'profiles', task.profile)
|
|
1471
1919
|
if (!exists(target)) return { ok: false, error: 'fork-profile-missing' }
|
|
1472
1920
|
setProfileConfigReadonly(target, false)
|
|
@@ -1488,9 +1936,11 @@ export function apply(ctx, config) {
|
|
|
1488
1936
|
const configLock = applyForkConfigLock(target)
|
|
1489
1937
|
const profileReadonly = setProfileConfigReadonly(target, true)
|
|
1490
1938
|
task.configSyncedAt = nowMs()
|
|
1491
|
-
task.configSyncedFrom =
|
|
1939
|
+
task.configSyncedFrom = sourceId
|
|
1940
|
+
task.syncSourceId = sourceId
|
|
1941
|
+
task.configSourceFingerprint = essenceManager.getMeta(sourceId)?.lastMergedFingerprint ?? null
|
|
1492
1942
|
persist()
|
|
1493
|
-
audit('fork-config-reset', { taskId: id, essenceId:
|
|
1943
|
+
audit('fork-config-reset', { taskId: id, essenceId: sourceId, files: picked, configLock, profileReadonly })
|
|
1494
1944
|
return { ok: true, taskId: id, essenceId: task.essenceId, files: picked, configLock, profileReadonly }
|
|
1495
1945
|
},
|
|
1496
1946
|
|
|
@@ -1508,11 +1958,28 @@ export function apply(ctx, config) {
|
|
|
1508
1958
|
return { ...applyForkSessionGuard(task), taskId: id }
|
|
1509
1959
|
},
|
|
1510
1960
|
|
|
1511
|
-
async restoreTask(taskId) {
|
|
1961
|
+
async restoreTask(taskId, options = {}) {
|
|
1962
|
+
const preserveProfile = options?.preserveProfile === true
|
|
1512
1963
|
const id = String(taskId ?? '')
|
|
1513
1964
|
const task = tasks.get(id)
|
|
1514
1965
|
if (!task) return { ok: false, error: 'unknown-task' }
|
|
1515
|
-
|
|
1966
|
+
const f = forker()
|
|
1967
|
+
if (!f || typeof f.spawn !== 'function') return { ok: false, error: 'forker-unavailable', taskId: id }
|
|
1968
|
+
// 2026-11-22:任务可能停在 ready/running,但子进程已经死了(宿主重启、手动 kill、
|
|
1969
|
+
// 端口丢失)。客户端「启动」仍会调用 restore;旧逻辑返回 not-archived,导致
|
|
1970
|
+
// 真机界面一直显示“启动失败”。这里允许恢复 stale 的 ready/running。
|
|
1971
|
+
if (task.status !== TASK_STATUS.ARCHIVED && task.status !== TASK_STATUS.FAILED) {
|
|
1972
|
+
const live = f.status?.(id) ?? null
|
|
1973
|
+
if (live?.running === true && task.adapter?.ok === true) {
|
|
1974
|
+
return { ok: true, alreadyRunning: true, taskId: id, url: task.url, port: task.port, adapter: task.adapter }
|
|
1975
|
+
}
|
|
1976
|
+
try { f.stop?.(id) } catch { /* stale process already gone */ }
|
|
1977
|
+
task.status = TASK_STATUS.FAILED
|
|
1978
|
+
task.pid = null
|
|
1979
|
+
task.port = null
|
|
1980
|
+
task.url = null
|
|
1981
|
+
persist()
|
|
1982
|
+
}
|
|
1516
1983
|
if (!task.homeDir || !exists(task.homeDir)) {
|
|
1517
1984
|
return { ok: false, error: 'archive-home-missing', taskId: id, homeDir: task.homeDir ?? '' }
|
|
1518
1985
|
}
|
|
@@ -1524,28 +1991,64 @@ export function apply(ctx, config) {
|
|
|
1524
1991
|
if (!forkBundle) {
|
|
1525
1992
|
return { ok: false, error: 'fork-bundle-unavailable', taskId: id, detail: forkProfileDir }
|
|
1526
1993
|
}
|
|
1527
|
-
const f = forker()
|
|
1528
|
-
if (!f || typeof f.spawn !== 'function') return { ok: false, error: 'forker-unavailable', taskId: id }
|
|
1529
1994
|
// 从原身派生的分身:还原前先把配置重置回来源原身(分身只生产,不保留配置改动)。
|
|
1995
|
+
// 先捕获元主 Web 的最新插件改动,避免 reset 用旧快照覆盖。所有分身(含模板)
|
|
1996
|
+
// 默认同步源为官方推荐。
|
|
1997
|
+
const syncSourceId = String(task.essenceId || task.syncSourceId || OFFICIAL_ESSENCE_ID)
|
|
1530
1998
|
let configReset = null
|
|
1531
|
-
if (
|
|
1999
|
+
if (!preserveProfile) {
|
|
2000
|
+
captureEssenceRuntimeIfPresent(syncSourceId)
|
|
2001
|
+
if (syncSourceId === OFFICIAL_ESSENCE_ID) await repairOfficialEssenceNow()
|
|
1532
2002
|
try { configReset = await service.resetForkConfig(id) } catch (error) {
|
|
1533
2003
|
configReset = { ok: false, error: String(error?.message ?? error) }
|
|
1534
2004
|
}
|
|
2005
|
+
} else {
|
|
2006
|
+
configReset = { ok: true, skipped: 'preserve-imported-profile' }
|
|
2007
|
+
}
|
|
2008
|
+
// EB-01 防线:restore 绝不再搬移用户会话。超额只保留 violation 警告;
|
|
2009
|
+
// 只有用户显式 enforce/归档动作才允许移动(见 docs/ERROR-BOOK.md EB-01)。
|
|
2010
|
+
const sessionGuard = { ok: true, skipped: 'restore-never-moves-sessions', violation: Boolean(task.sessions?.violation) }
|
|
2011
|
+
// 开关不是热更新:重新打开分身时按当前开关换核(重新 provision profile;会话目录不动)。
|
|
2012
|
+
// resetForkConfig 刚把 profile 重置回 stock 形状;即使 coreMode 未变也必须强制 reprovision,
|
|
2013
|
+
// 否则加速分身会以 stock 配置 + accelerated CLI 启动而永远不 ready(2026-11-22 实测 timeout)。
|
|
2014
|
+
const coreSync = preserveProfile
|
|
2015
|
+
? { ok: true, switched: false, coreMode: task.coreMode === 'accelerated' ? 'accelerated' : 'stock' }
|
|
2016
|
+
: await syncForkCoreMode(task, { force: true })
|
|
2017
|
+
if (coreSync.ok !== true) { task.status = TASK_STATUS.FAILED
|
|
2018
|
+
persist()
|
|
2019
|
+
audit(AUDIT.TASK_RESTORED, { taskId: id, ok: false, error: coreSync.error })
|
|
2020
|
+
return { ok: false, error: coreSync.error, detail: coreSync.detail ?? null, taskId: id }
|
|
1535
2021
|
}
|
|
1536
|
-
//
|
|
1537
|
-
|
|
1538
|
-
|
|
2022
|
+
// 老/空白分身重新打开时补齐官方实验性插件表面;先整体对齐来源元主的完整插件面。
|
|
2023
|
+
// 完整来源插件面对齐:默认开启;e2e 已证 125/125(node-compat 复制关闭后)。
|
|
2024
|
+
const sourceSurface = preserveProfile
|
|
2025
|
+
? { ok: true, skipped: 'preserve-imported-profile' }
|
|
2026
|
+
: process.env.DSH_FANG_SOURCE_SURFACE === '0'
|
|
2027
|
+
? { ok: true, skipped: 'disabled' }
|
|
2028
|
+
: applySourcePluginSurface(task, forkProfileDir)
|
|
2029
|
+
if (process.env.DSH_FANG_E2E_DEBUG === '1') { try { copyTree(forkProfileDir, path.join(layout.dataDir, 'debug-restore-profile')) } catch { /* debug */ } }
|
|
2030
|
+
if (sourceSurface.ok === false) audit('fork-source-surface-failed', { taskId: id, error: sourceSurface.error })
|
|
2031
|
+
const experimentalSurface = preserveProfile
|
|
2032
|
+
? { ok: true, skipped: 'preserve-imported-profile' }
|
|
2033
|
+
: applyOfficialExperimentalSurface(forkProfileDir, { coreMode: coreSync.coreMode })
|
|
2034
|
+
if (experimentalSurface.ok === false) audit('fork-experimental-surface-failed', { taskId: id, error: experimentalSurface.error })
|
|
1539
2035
|
const started = await f.spawn({
|
|
1540
2036
|
forkId: id,
|
|
1541
2037
|
homeDir: task.homeDir,
|
|
1542
2038
|
profile: task.profile,
|
|
1543
|
-
cliPath:
|
|
1544
|
-
|
|
2039
|
+
...(coreSync.coreMode === 'accelerated' ? {} : { cliPath: forkCliPath() }),
|
|
2040
|
+
coreMode: coreSync.coreMode,
|
|
2041
|
+
env: { DSH_FANG_ROLE: 'fork', DSH_FANG_TASK_ID: id, DSH_FANG_MOTHER: layout.dataDir, ...forkTempEnv(id) },
|
|
1545
2042
|
})
|
|
1546
2043
|
if (!started || started.ok === false) {
|
|
1547
2044
|
audit(AUDIT.TASK_RESTORED, { taskId: id, ok: false, error: started?.error ?? 'spawn-failed' })
|
|
1548
|
-
return {
|
|
2045
|
+
return {
|
|
2046
|
+
ok: false,
|
|
2047
|
+
error: started?.error === 'accelerated-cli-missing' ? 'accelerated-cli-missing' : 'spawn-failed',
|
|
2048
|
+
detail: started?.error ?? 'unknown',
|
|
2049
|
+
taskId: id,
|
|
2050
|
+
...(Array.isArray(started?.searched) ? { searched: started.searched } : {}),
|
|
2051
|
+
}
|
|
1549
2052
|
}
|
|
1550
2053
|
task.status = TASK_STATUS.RUNNING
|
|
1551
2054
|
task.archivedAt = null
|
|
@@ -1565,6 +2068,107 @@ export function apply(ctx, config) {
|
|
|
1565
2068
|
return { ok: true, restored: true, taskId: id, title: task.title, url: task.url, port: task.port, adapter, configReset, sessionGuard }
|
|
1566
2069
|
},
|
|
1567
2070
|
|
|
2071
|
+
/**
|
|
2072
|
+
* 2026-11-22:每次打开分身都主动同步来源元主的插件状态。
|
|
2073
|
+
* 读取运行中元主的 settings/patch/bundles/modules → 更新元宝 fingerprint;
|
|
2074
|
+
* fingerprint 变化时停止旧分身并按新 merged profile 重新 provision + spawn。
|
|
2075
|
+
*/
|
|
2076
|
+
async syncTaskOnOpen(taskId) {
|
|
2077
|
+
const id = String(taskId ?? '')
|
|
2078
|
+
const task = tasks.get(id)
|
|
2079
|
+
if (!task) return { ok: false, error: 'unknown-task' }
|
|
2080
|
+
const sourceId = String(task.essenceId || task.syncSourceId || OFFICIAL_ESSENCE_ID)
|
|
2081
|
+
captureEssenceRuntimeIfPresent(sourceId)
|
|
2082
|
+
if (sourceId === OFFICIAL_ESSENCE_ID) await repairOfficialEssenceNow()
|
|
2083
|
+
await essenceManager.ensureFresh(sourceId)
|
|
2084
|
+
const fingerprint = essenceManager.getMeta(sourceId)?.lastMergedFingerprint ?? null
|
|
2085
|
+
const changed = Boolean(fingerprint && task.configSourceFingerprint !== fingerprint)
|
|
2086
|
+
const live = forker()?.status?.(id) ?? null
|
|
2087
|
+
if (changed) {
|
|
2088
|
+
if (live?.running === true) {
|
|
2089
|
+
try { forker().stop?.(id) } catch { /* best effort */ }
|
|
2090
|
+
}
|
|
2091
|
+
task.status = TASK_STATUS.FAILED
|
|
2092
|
+
task.pid = null
|
|
2093
|
+
task.port = null
|
|
2094
|
+
task.url = null
|
|
2095
|
+
persist()
|
|
2096
|
+
const restored = await service.restoreTask(id)
|
|
2097
|
+
return { ...restored, synced: true, restarted: true, sourceFingerprint: fingerprint }
|
|
2098
|
+
}
|
|
2099
|
+
if (task.status === TASK_STATUS.FAILED) {
|
|
2100
|
+
const restored = await service.restoreTask(id)
|
|
2101
|
+
return { ...restored, synced: true, restarted: true, sourceFingerprint: fingerprint }
|
|
2102
|
+
}
|
|
2103
|
+
const out = forker()?.openUrl?.(id) ?? null
|
|
2104
|
+
if (!out || out.ok !== true) return { ok: false, error: out?.error ?? 'not-running' }
|
|
2105
|
+
return { ...out, synced: true, restarted: false, sourceFingerprint: fingerprint }
|
|
2106
|
+
},
|
|
2107
|
+
|
|
2108
|
+
/**
|
|
2109
|
+
* 一键修复(2026-11-22):把「起不来」的常见原因逐项处理后再拉起,不删除 home/会话。
|
|
2110
|
+
* 步骤:停残留进程 → 清加速别名桩 → 按来源原身重置 profile → 归位任务状态 → restore 重新 spawn
|
|
2111
|
+
* (spawn 内部还会修复 node_modules mirror 并再次清理别名桩)。
|
|
2112
|
+
* 每一步结果都返回给 UI,失败时给出具体 step。
|
|
2113
|
+
*/
|
|
2114
|
+
async repairTask(taskId) {
|
|
2115
|
+
const id = String(taskId ?? '')
|
|
2116
|
+
const task = tasks.get(id)
|
|
2117
|
+
if (!task) return { ok: false, error: 'unknown-task' }
|
|
2118
|
+
if (!task.homeDir || !exists(task.homeDir)) return { ok: false, error: 'archive-home-missing', taskId: id }
|
|
2119
|
+
if (!task.profile) return { ok: false, error: 'fork-profile-missing', taskId: id }
|
|
2120
|
+
const f = forker()
|
|
2121
|
+
if (!f || typeof f.spawn !== 'function') return { ok: false, error: 'forker-unavailable' }
|
|
2122
|
+
const steps = []
|
|
2123
|
+
// 1) 停掉可能残留的半死进程(pid 在、adapter 失联)——不清 home。
|
|
2124
|
+
let live = null
|
|
2125
|
+
try { live = f.status?.(id) ?? null } catch { live = null }
|
|
2126
|
+
if (live?.running === true || live?.pid) {
|
|
2127
|
+
try {
|
|
2128
|
+
f.stop?.(id)
|
|
2129
|
+
steps.push({ step: 'stop-stale', ok: true })
|
|
2130
|
+
} catch (error) {
|
|
2131
|
+
steps.push({ step: 'stop-stale', ok: false, error: String(error?.message ?? error) })
|
|
2132
|
+
}
|
|
2133
|
+
} else {
|
|
2134
|
+
steps.push({ step: 'stop-stale', ok: true, skipped: true })
|
|
2135
|
+
}
|
|
2136
|
+
// 2) 清 stock 下残留的加速别名桩(核心切换后它们会遮挡官方包,启动即崩)。
|
|
2137
|
+
const profileDir = path.join(task.homeDir, 'profiles', task.profile)
|
|
2138
|
+
const pruned = pruneAliasStubs(profileDir)
|
|
2139
|
+
steps.push({ step: 'prune-alias-stubs', ok: pruned.ok !== false, removed: pruned.removed.length })
|
|
2140
|
+
// 3) 有来源原身时,按源配置重置 profile(与 restore 的配置归位一致;无源则跳过)。
|
|
2141
|
+
if (task.essenceId) {
|
|
2142
|
+
let configReset = null
|
|
2143
|
+
try { configReset = await service.resetForkConfig(id) } catch (error) {
|
|
2144
|
+
configReset = { ok: false, error: String(error?.message ?? error) }
|
|
2145
|
+
}
|
|
2146
|
+
steps.push({ step: 'reset-profile-config', ok: configReset?.ok === true, error: configReset?.error ?? null })
|
|
2147
|
+
} else {
|
|
2148
|
+
steps.push({ step: 'reset-profile-config', ok: true, skipped: true })
|
|
2149
|
+
}
|
|
2150
|
+
// 4) 归位任务状态:restoreTask 只接受 archived/failed;运行中的先置 failed。
|
|
2151
|
+
if (task.status === TASK_STATUS.RUNNING || task.status === TASK_STATUS.READY || task.status === TASK_STATUS.PROVISIONING) {
|
|
2152
|
+
task.status = TASK_STATUS.FAILED
|
|
2153
|
+
}
|
|
2154
|
+
persist()
|
|
2155
|
+
// 5) 重新拉起(新端口、新 token;spawn 会做 mirror 修复 + 再次 prune)。
|
|
2156
|
+
const restored = await service.restoreTask(id)
|
|
2157
|
+
steps.push({ step: 'spawn', ok: restored?.ok === true, error: restored?.error ?? null, detail: restored?.detail ?? null })
|
|
2158
|
+
const ok = restored?.ok === true
|
|
2159
|
+
audit('task-repaired', { taskId: id, ok, steps })
|
|
2160
|
+
if (!ok) {
|
|
2161
|
+
return {
|
|
2162
|
+
ok: false,
|
|
2163
|
+
taskId: id,
|
|
2164
|
+
error: restored?.error ?? 'repair-failed',
|
|
2165
|
+
detail: restored?.detail ?? null,
|
|
2166
|
+
steps,
|
|
2167
|
+
}
|
|
2168
|
+
}
|
|
2169
|
+
return { ok: true, taskId: id, steps, url: restored.url, port: restored.port, adapter: restored.adapter }
|
|
2170
|
+
},
|
|
2171
|
+
|
|
1568
2172
|
/**
|
|
1569
2173
|
* watchdog 启动时的恢复入口:把「已登记但进程没在跑」的非归档任务重新 spawn。
|
|
1570
2174
|
* 不创建新任务、不动归档任务;失败的任务不重试(避免崩溃循环),只如实报告。
|
|
@@ -1609,12 +2213,19 @@ export function apply(ctx, config) {
|
|
|
1609
2213
|
persist()
|
|
1610
2214
|
let started
|
|
1611
2215
|
try {
|
|
2216
|
+
const coreSync = await syncForkCoreMode(task)
|
|
2217
|
+
if (coreSync.ok !== true) {
|
|
2218
|
+
report.failed.push({ taskId: id, error: coreSync.error })
|
|
2219
|
+
audit(AUDIT.FORK_CRASHED, { taskId: id, error: coreSync.error, reason: 'autostart-core-switch' })
|
|
2220
|
+
continue
|
|
2221
|
+
}
|
|
1612
2222
|
started = await f.spawn({
|
|
1613
2223
|
forkId: id,
|
|
1614
2224
|
homeDir: task.homeDir,
|
|
1615
2225
|
profile: task.profile,
|
|
1616
|
-
cliPath:
|
|
1617
|
-
|
|
2226
|
+
...(coreSync.coreMode === 'accelerated' ? {} : { cliPath: forkCliPath() }),
|
|
2227
|
+
coreMode: coreSync.coreMode,
|
|
2228
|
+
env: { DSH_FANG_ROLE: 'fork', DSH_FANG_TASK_ID: id, DSH_FANG_MOTHER: layout.dataDir, ...forkTempEnv(id) },
|
|
1618
2229
|
})
|
|
1619
2230
|
} catch (error) {
|
|
1620
2231
|
started = { ok: false, error: String(error?.message ?? error) }
|
|
@@ -1723,10 +2334,22 @@ export function apply(ctx, config) {
|
|
|
1723
2334
|
sessionsRoot: layout.sessionsRoot || '',
|
|
1724
2335
|
},
|
|
1725
2336
|
mother: { profile: motherProfile, cliPath: cliPath(), template: templateDir() },
|
|
2337
|
+
essenceAutoRefresh: lastAutoRefresh,
|
|
1726
2338
|
tasks: { total: list.length, ready, running, max: cfg.maxForks, list },
|
|
1727
2339
|
// v1 兼容视图:Client 徽标与旧调用方仍读 forks.*
|
|
1728
2340
|
forks: { total: list.length, running: ready + running, max: cfg.maxForks, list },
|
|
1729
|
-
audit:
|
|
2341
|
+
audit: (() => {
|
|
2342
|
+
const health = auditHealth()
|
|
2343
|
+
return {
|
|
2344
|
+
checkedAt: bootState.at,
|
|
2345
|
+
ok: bootState.ok === true && health.ok !== false,
|
|
2346
|
+
findings: bootState.findings,
|
|
2347
|
+
// R15 健康面:链完整性/追加失败次数/最后失败时间;UI 与运维据此发现“静默丢失”。
|
|
2348
|
+
health,
|
|
2349
|
+
failures: health.processFailures,
|
|
2350
|
+
lastError: health.processLastError,
|
|
2351
|
+
}
|
|
2352
|
+
})(),
|
|
1730
2353
|
commercial: { ...commercialHooks },
|
|
1731
2354
|
services: {
|
|
1732
2355
|
forker: !!safeGet(SERVICE.forker),
|
|
@@ -1741,14 +2364,32 @@ export function apply(ctx, config) {
|
|
|
1741
2364
|
adapter: !!safeGet(SERVICE.adapter),
|
|
1742
2365
|
commercial: !!safeGet(SERVICE.commercial),
|
|
1743
2366
|
sessionCatalog: !!safeGet(SERVICE.sessionCatalog),
|
|
2367
|
+
decisionCenter: !!safeGet(SERVICE.decisionCenter),
|
|
2368
|
+
queueJournal: queueJournalEnabled(),
|
|
1744
2369
|
},
|
|
1745
2370
|
// 重启守卫摘要(只读):Client Header 用它显示 mode/红灯策略;无守卫时 available:false。
|
|
1746
2371
|
restart: restartSummary(restartView()),
|
|
1747
2372
|
}
|
|
1748
2373
|
},
|
|
1749
2374
|
|
|
2375
|
+
/** v3.3.8:手动/启动后检测默认元主是否落后,旧则自动 capture 并 setDefault。 */
|
|
2376
|
+
refreshDefaultEssence: () => refreshStaleDefaultEssenceIfNeeded(),
|
|
2377
|
+
|
|
1750
2378
|
/** 母体重启的唯一入口:转交 restart-guard,自身永不直接退出进程。 */
|
|
1751
|
-
async requestMotherRestart(reason = 'manual') {
|
|
2379
|
+
async requestMotherRestart(reason = 'manual', options = {}) {
|
|
2380
|
+
// v3.3.6: human restart requires two explicit confirmations:
|
|
2381
|
+
// 1) forkChecked — user has checked the impact in a fork;
|
|
2382
|
+
// 2) finalConfirm — the second red confirmation click.
|
|
2383
|
+
// API callers that omit them are refused before touching the guard.
|
|
2384
|
+
const confirmation = options?.confirmation && typeof options.confirmation === 'object' ? options.confirmation : null
|
|
2385
|
+
if (!confirmation || confirmation.forkChecked !== true || confirmation.finalConfirm !== true) {
|
|
2386
|
+
return {
|
|
2387
|
+
ok: false,
|
|
2388
|
+
error: 'restart-confirmation-required',
|
|
2389
|
+
required: { forkChecked: true, finalConfirm: true },
|
|
2390
|
+
detail: '请先在分身确认影响,再进行第二次确认;缺失确认时不会创建重启请求。',
|
|
2391
|
+
}
|
|
2392
|
+
}
|
|
1752
2393
|
const guard = safeGet(SERVICE.restart)
|
|
1753
2394
|
if (!guard || typeof guard.request !== 'function') {
|
|
1754
2395
|
return { ok: false, error: 'restart-guard-unavailable' }
|
|
@@ -1758,6 +2399,12 @@ export function apply(ctx, config) {
|
|
|
1758
2399
|
risk: 'red',
|
|
1759
2400
|
scope: 'mother',
|
|
1760
2401
|
origin: 'fang:orchestrator',
|
|
2402
|
+
confirmation: {
|
|
2403
|
+
forkChecked: true,
|
|
2404
|
+
finalConfirm: true,
|
|
2405
|
+
at: Number(confirmation.at) || Date.now(),
|
|
2406
|
+
forkId: confirmation.forkId ? String(confirmation.forkId).slice(0, 200) : null,
|
|
2407
|
+
},
|
|
1761
2408
|
})
|
|
1762
2409
|
// auto-allow is a successful policy decision, not a denial.
|
|
1763
2410
|
const allowed = decision?.outcome === 'approved' || decision?.outcome === 'auto-allow'
|
|
@@ -1766,6 +2413,12 @@ export function apply(ctx, config) {
|
|
|
1766
2413
|
}
|
|
1767
2414
|
|
|
1768
2415
|
ctx.effect(() => ctx.provide(SERVICE.orchestrator, service))
|
|
2416
|
+
// v3.3.8:启动后异步自愈默认元主;不阻塞 boot,不 unref 也不会阻止退出。
|
|
2417
|
+
{
|
|
2418
|
+
const timer = setTimeout(() => { void refreshStaleDefaultEssenceIfNeeded() }, 1500)
|
|
2419
|
+
timer.unref?.()
|
|
2420
|
+
ctx.effect(() => () => clearTimeout(timer))
|
|
2421
|
+
}
|
|
1769
2422
|
|
|
1770
2423
|
// v3.1.15:fang-master 契约服务(dsh-Master 通过 local/http/file/legacy 四层传输调用)。
|
|
1771
2424
|
const contractCfg = {
|
|
@@ -1798,7 +2451,60 @@ export function apply(ctx, config) {
|
|
|
1798
2451
|
peerLabel: 'dsh-fang-bundle',
|
|
1799
2452
|
role: gate.role,
|
|
1800
2453
|
instanceId: `fang-${gate.role}-${process.pid}`,
|
|
2454
|
+
// M5 回流批次约定(房主合同口径:maxBatch=32、maxPayloadBytes=512000)。
|
|
2455
|
+
// vendored contract 1.2.0 库默认 maxBatch=128;运行时在此按 M5 约定收敛,不改 vendor 实现。
|
|
2456
|
+
limits: { maxBatch: 32, maxPayloadBytes: 512000 },
|
|
1801
2457
|
})
|
|
2458
|
+
const delegationCfg = normalizeDelegationConfig(cfg.contract?.delegate ?? {})
|
|
2459
|
+
const delegationGate = createDelegationGate({ maxConcurrent: delegationCfg.maxConcurrent })
|
|
2460
|
+
const proCfg = normalizeProConfig(cfg.contract?.delegate?.pro ?? {})
|
|
2461
|
+
const proGate = createDelegationGate({ maxConcurrent: proCfg.maxConcurrent })
|
|
2462
|
+
const proApprovals = createProApprovalStore()
|
|
2463
|
+
|
|
2464
|
+
// B-6 路线 A:母体 LSP 能力缝(ctx.lsp)。未安装官方 LSP 栈时显式不可用,不假装成功。
|
|
2465
|
+
const lspService = (() => { try { return typeof ctx.get === 'function' ? ctx.get('lsp') : null } catch { return null } })()
|
|
2466
|
+
const lspCfg = {
|
|
2467
|
+
allowedRoots: Array.isArray(cfg.contract?.delegate?.lsp?.allowedRoots) ? cfg.contract.delegate.lsp.allowedRoots.map((root) => String(root)) : [],
|
|
2468
|
+
includeForkWorktrees: cfg.contract?.delegate?.lsp?.includeForkWorktrees !== false,
|
|
2469
|
+
maxLocations: Number.isInteger(cfg.contract?.delegate?.lsp?.maxLocations) ? cfg.contract.delegate.lsp.maxLocations : 200,
|
|
2470
|
+
maxResultChars: Number.isInteger(cfg.contract?.delegate?.lsp?.maxResultChars) ? cfg.contract.delegate.lsp.maxResultChars : 20000,
|
|
2471
|
+
}
|
|
2472
|
+
/** 显式登记:母体配置根 + 所有 fork 任务工作区根(任务 registry 即登记来源)。 */
|
|
2473
|
+
const resolveLspRootsForTask = () => {
|
|
2474
|
+
let forkRoots = []
|
|
2475
|
+
try {
|
|
2476
|
+
const registryFile = exists(layout.tasksFile) ? layout.tasksFile : layout.forksFile
|
|
2477
|
+
const homes = loadRegistry(registryFile).map((task) => task?.homeDir).filter(Boolean)
|
|
2478
|
+
forkRoots = collectForkWorkspaceRoots(homes)
|
|
2479
|
+
} catch { /* registry unavailable → configured roots only */ }
|
|
2480
|
+
return resolveLspAllowedRoots({ configuredRoots: lspCfg.allowedRoots, forkRoots, includeForkWorktrees: lspCfg.includeForkWorktrees })
|
|
2481
|
+
}
|
|
2482
|
+
const lspHooksEnabled = process.env.FANG_CONTRACT_TEST_HOOKS === '1'
|
|
2483
|
+
/**
|
|
2484
|
+
* 路线 B(fork-local)就绪信息:只读探测加速核是否含同版本 LSP trio。
|
|
2485
|
+
* 语义:fork-local 的 LSP 跑在分身自己的 workspace/worktree,不经过契约委托;
|
|
2486
|
+
* 这里只用于能力目录显式区分 provider: 'mother' | 'fork-local',不改变执行路径。
|
|
2487
|
+
*/
|
|
2488
|
+
const forkLspInfo = (() => {
|
|
2489
|
+
try {
|
|
2490
|
+
const accelHome = String(layout?.fangHome ?? '').trim()
|
|
2491
|
+
|| (layout?.dataDir ? path.resolve(layout.dataDir, '..') : '')
|
|
2492
|
+
const resolved = resolveAcceleratedCore({ cliPath: cfg.acceleratedCliPath ?? '', env: process.env, fangHome: accelHome })
|
|
2493
|
+
if (resolved?.ok !== true || !resolved.cliPath) return { available: false, error: 'accelerated-cli-missing' }
|
|
2494
|
+
const info = detectForkLspSupport(accelNodeModulesRoot(resolved.cliPath))
|
|
2495
|
+
return { ...info, cliPath: resolved.cliPath }
|
|
2496
|
+
} catch (error) {
|
|
2497
|
+
return { available: false, error: String(error?.message ?? error) }
|
|
2498
|
+
}
|
|
2499
|
+
})()
|
|
2500
|
+
const lspProviderInfo = describeLspProvider({
|
|
2501
|
+
lspService,
|
|
2502
|
+
hooksEnabled: lspHooksEnabled,
|
|
2503
|
+
forkLocal: Boolean(forkLspInfo?.available),
|
|
2504
|
+
forkLspInfo,
|
|
2505
|
+
supportedActions: advertisedActionsFromSeam(lspService),
|
|
2506
|
+
})
|
|
2507
|
+
const delegateUnavailable = (message, code = DELEGATE_ERROR.UNAVAILABLE) => { const error = new Error(message); error.code = code; throw error }
|
|
1802
2508
|
const contractServer = createContractServer({
|
|
1803
2509
|
role: gate.role,
|
|
1804
2510
|
instanceId: `fang-${gate.role}-${process.pid}`,
|
|
@@ -1808,7 +2514,14 @@ export function apply(ctx, config) {
|
|
|
1808
2514
|
[CONTRACT_METHODS.FORK_SPAWN]: async (params) => {
|
|
1809
2515
|
const forker = contractService('forker', 'spawn')
|
|
1810
2516
|
const input = params && typeof params === 'object' ? params : {}
|
|
1811
|
-
|
|
2517
|
+
const coreMode = normalizeCoreMode(input.coreMode ?? forkCoreSettings().mode)
|
|
2518
|
+
const { cliPath: requestedCliPath, ...rest } = input
|
|
2519
|
+
return await forker.spawn({
|
|
2520
|
+
...rest,
|
|
2521
|
+
...(coreMode === 'accelerated' ? {} : { cliPath: String(requestedCliPath ?? '') }),
|
|
2522
|
+
coreMode,
|
|
2523
|
+
env: contractEnv(input.env),
|
|
2524
|
+
})
|
|
1812
2525
|
},
|
|
1813
2526
|
[CONTRACT_METHODS.FORK_STOP]: async (params) => {
|
|
1814
2527
|
const forker = contractService('forker', 'stop', false)
|
|
@@ -1825,9 +2538,189 @@ export function apply(ctx, config) {
|
|
|
1825
2538
|
[CONTRACT_METHODS.SESSION_LIST]: async (params) => {
|
|
1826
2539
|
const catalog = contractService('sessionCatalog', 'list', false)
|
|
1827
2540
|
if (catalog) return await catalog.list(params ?? {})
|
|
1828
|
-
|
|
2541
|
+
return delegateUnavailable('fang session catalog is unavailable', 'fang-service-unavailable')
|
|
1829
2542
|
},
|
|
1830
2543
|
[CONTRACT_METHODS.ORCHESTRATOR_STATUS]: async () => service.status(),
|
|
2544
|
+
// ── B 委托:只读能力(白名单在 invoke 路由统一校验;这里只做能力实现)──
|
|
2545
|
+
[CONTRACT_METHODS.CAPABILITY_LIST]: async () => ({
|
|
2546
|
+
enabled: true,
|
|
2547
|
+
contractVersion: CONTRACT_VERSION,
|
|
2548
|
+
capabilities: capabilityCatalog(delegationCfg.allow).map((item) => (
|
|
2549
|
+
item.method === 'fang.tool.invoke'
|
|
2550
|
+
? { ...item, actions: [...lspProviderInfo.actions], provider: lspProviderInfo }
|
|
2551
|
+
: item
|
|
2552
|
+
)),
|
|
2553
|
+
lspProvider: lspProviderInfo,
|
|
2554
|
+
allow: delegationCfg.allow,
|
|
2555
|
+
limits: { maxPayloadBytes: delegationCfg.maxPayloadBytes, readTimeoutMs: delegationCfg.readTimeoutMs, writeTimeoutMs: delegationCfg.writeTimeoutMs },
|
|
2556
|
+
}),
|
|
2557
|
+
'fang.session.events': async (params) => {
|
|
2558
|
+
const catalog = contractService('sessionCatalog', 'readHead', false)
|
|
2559
|
+
if (!catalog) return delegateUnavailable('fang session catalog is unavailable', 'fang-service-unavailable')
|
|
2560
|
+
const sessionId = String(params?.sessionId ?? '').trim()
|
|
2561
|
+
if (!sessionId) {
|
|
2562
|
+
const error = new Error('sessionId is required')
|
|
2563
|
+
error.code = DELEGATE_ERROR.INVALID
|
|
2564
|
+
throw error
|
|
2565
|
+
}
|
|
2566
|
+
const limit = Math.min(200, Math.max(1, Number(params?.limit) || 50))
|
|
2567
|
+
const maxChars = Math.min(256 * 1024, Math.max(0, Number(params?.maxChars) || 64 * 1024))
|
|
2568
|
+
const head = await catalog.readHead(sessionId, { maxLines: limit, maxChars })
|
|
2569
|
+
if (!head || head.ok === false) return head ?? delegateUnavailable('session read failed', 'fang-service-unavailable')
|
|
2570
|
+
return {
|
|
2571
|
+
sessionId: head.sessionId ?? sessionId,
|
|
2572
|
+
events: (Array.isArray(head.lines) ? head.lines : []).slice(0, limit).map((line, index) => ({ index, line })),
|
|
2573
|
+
redactions: head.redactions ?? 0,
|
|
2574
|
+
bytesRead: head.bytesRead ?? 0,
|
|
2575
|
+
degraded: Array.isArray(head.degraded) ? head.degraded : [],
|
|
2576
|
+
}
|
|
2577
|
+
},
|
|
2578
|
+
// B-6:LSP 工具委托。官方能力缝只读(definition/references/implementation/hover);
|
|
2579
|
+
// 路线 A 优先用母体 ctx.lsp;路线 B(fork-local)作为增强,同一契约按 provider 区分。
|
|
2580
|
+
'fang.tool.invoke': async (params) => {
|
|
2581
|
+
const validated = validateToolInvoke(params)
|
|
2582
|
+
if (validated.ok !== true) {
|
|
2583
|
+
const error = new Error(validated.message)
|
|
2584
|
+
error.code = validated.error ?? DELEGATE_ERROR.INVALID
|
|
2585
|
+
throw error
|
|
2586
|
+
}
|
|
2587
|
+
if (validated.kind === 'write') {
|
|
2588
|
+
const error = new Error('lsp write actions require fang approval; no side effect performed')
|
|
2589
|
+
error.code = DELEGATE_ERROR.APPROVAL_REQUIRED
|
|
2590
|
+
error.detail = { tool: 'lsp', action: validated.action, approval: 'required' }
|
|
2591
|
+
throw error
|
|
2592
|
+
}
|
|
2593
|
+
if (validated.kind === 'test-only') {
|
|
2594
|
+
// diagnostics 仅 e2e 测试缝可用:不进入能力目录、真实 provider 下不可用。
|
|
2595
|
+
if (!lspService && lspHooksEnabled) {
|
|
2596
|
+
return {
|
|
2597
|
+
tool: 'lsp',
|
|
2598
|
+
action: validated.action,
|
|
2599
|
+
file: validated.file,
|
|
2600
|
+
line: validated.line,
|
|
2601
|
+
character: validated.character,
|
|
2602
|
+
ok: true,
|
|
2603
|
+
provider: LSP_PROVIDER_TEST,
|
|
2604
|
+
testSeam: true,
|
|
2605
|
+
nonProduction: true,
|
|
2606
|
+
diagnostics: [{ file: validated.file, line: validated.line, character: validated.character, severity: 'info', message: 'stub diagnostics (test hook only, non-production)' }],
|
|
2607
|
+
}
|
|
2608
|
+
}
|
|
2609
|
+
const error = new Error(`lsp action '${validated.action}' is test-seam only and not provided by the official LSP seam`)
|
|
2610
|
+
error.code = DELEGATE_ERROR.UNSUPPORTED
|
|
2611
|
+
error.detail = { tool: 'lsp', action: validated.action, reason: 'test-seam-only' }
|
|
2612
|
+
throw error
|
|
2613
|
+
}
|
|
2614
|
+
if (lspService) {
|
|
2615
|
+
// 母体委托最小正确路径(E7):直接走官方能力缝 ctx.get('lsp').query({operation,filePath,position,workspaceRoot});
|
|
2616
|
+
// 不需要 Agent Session(E10 只约束模型工具 dsh-tool-lsp),也不经过 tools 服务。
|
|
2617
|
+
const startedAt = Date.now()
|
|
2618
|
+
const auditLsp = (outcome, error, workspaceRoot = null) => {
|
|
2619
|
+
try { audit('contract-delegate', lspAuditRecord({ action: validated.action, provider: 'mother', workspaceRoot, outcome, error, latencyMs: Date.now() - startedAt })) } catch { /* audit optional */ }
|
|
2620
|
+
}
|
|
2621
|
+
if (!lspProviderInfo.actions.includes(validated.action)) {
|
|
2622
|
+
const error = new Error(`lsp provider does not provide action '${validated.action}' (advertised: ${lspProviderInfo.actions.join(',') || 'none'})`)
|
|
2623
|
+
error.code = DELEGATE_ERROR.UNSUPPORTED
|
|
2624
|
+
error.detail = { tool: 'lsp', action: validated.action, provider: 'mother', reason: 'provider-capability-missing', advertised: lspProviderInfo.actions }
|
|
2625
|
+
auditLsp('rejected', DELEGATE_ERROR.UNSUPPORTED)
|
|
2626
|
+
throw error
|
|
2627
|
+
}
|
|
2628
|
+
const allowedRoots = resolveLspRootsForTask()
|
|
2629
|
+
const rootCheck = checkWorkspaceRoot({ workspaceRoot: params?.workspaceRoot, file: validated.file, allowedRoots })
|
|
2630
|
+
if (rootCheck.ok !== true) {
|
|
2631
|
+
const error = new Error(rootCheck.message)
|
|
2632
|
+
error.code = rootCheck.code
|
|
2633
|
+
error.detail = { tool: 'lsp', action: validated.action, provider: 'mother', reason: rootCheck.reason ?? 'workspace-root-denied', allowedRoots: allowedRoots.length }
|
|
2634
|
+
auditLsp('denied', rootCheck.code, String(params?.workspaceRoot ?? ''))
|
|
2635
|
+
throw error
|
|
2636
|
+
}
|
|
2637
|
+
const query = await queryMotherLsp({ lspService, invoke: validated, workspaceRoot: rootCheck.workspaceRoot, limits: { maxLocations: lspCfg.maxLocations, maxResultChars: lspCfg.maxResultChars } })
|
|
2638
|
+
if (query.ok !== true) {
|
|
2639
|
+
const error = new Error(query.message)
|
|
2640
|
+
error.code = query.code
|
|
2641
|
+
error.detail = { tool: 'lsp', action: validated.action, provider: 'mother', ...(query.detail ?? {}) }
|
|
2642
|
+
auditLsp('error', query.code, rootCheck.workspaceRoot)
|
|
2643
|
+
throw error
|
|
2644
|
+
}
|
|
2645
|
+
auditLsp('ok', null, rootCheck.workspaceRoot)
|
|
2646
|
+
return {
|
|
2647
|
+
tool: 'lsp',
|
|
2648
|
+
file: validated.file,
|
|
2649
|
+
line: validated.line,
|
|
2650
|
+
character: validated.character,
|
|
2651
|
+
workspaceRoot: rootCheck.workspaceRoot,
|
|
2652
|
+
...query.result,
|
|
2653
|
+
}
|
|
2654
|
+
}
|
|
2655
|
+
if (lspHooksEnabled) {
|
|
2656
|
+
return {
|
|
2657
|
+
tool: 'lsp',
|
|
2658
|
+
action: validated.action,
|
|
2659
|
+
operation: validated.operation,
|
|
2660
|
+
file: validated.file,
|
|
2661
|
+
line: validated.line,
|
|
2662
|
+
character: validated.character,
|
|
2663
|
+
ok: true,
|
|
2664
|
+
provider: LSP_PROVIDER_TEST,
|
|
2665
|
+
kind: 'locations',
|
|
2666
|
+
locations: [],
|
|
2667
|
+
}
|
|
2668
|
+
}
|
|
2669
|
+
return delegateUnavailable('lsp tool provider is unavailable on mother (install dsh-lsp + dsh-lsp-stdio, or enable the fork-local provider)')
|
|
2670
|
+
},
|
|
2671
|
+
// B-7:chat.import。dryRun(默认)确定性预览;真实导入必须审批——委托层拒绝执行、零副作用。
|
|
2672
|
+
'fang.chat.import': async (params) => {
|
|
2673
|
+
const validated = validateChatImport(params)
|
|
2674
|
+
if (validated.ok !== true) {
|
|
2675
|
+
const error = new Error(validated.message)
|
|
2676
|
+
error.code = validated.error ?? DELEGATE_ERROR.INVALID
|
|
2677
|
+
throw error
|
|
2678
|
+
}
|
|
2679
|
+
const catalog = contractService('sessionCatalog', 'getSession', false)
|
|
2680
|
+
let found = false
|
|
2681
|
+
let reason = null
|
|
2682
|
+
if (catalog && typeof catalog.getSession === 'function') {
|
|
2683
|
+
const result = catalog.getSession(validated.sessionId)
|
|
2684
|
+
found = result?.ok === true
|
|
2685
|
+
reason = found ? null : (result?.code ?? result?.error ?? 'session-not-found')
|
|
2686
|
+
} else {
|
|
2687
|
+
reason = 'session-catalog-unavailable'
|
|
2688
|
+
}
|
|
2689
|
+
const preview = buildChatImportDryRun({ source: validated.source, sessionId: validated.sessionId, found, reason })
|
|
2690
|
+
if (validated.dryRun === true) return preview
|
|
2691
|
+
const error = new Error('chat import requires fang approval; no side effect performed')
|
|
2692
|
+
error.code = DELEGATE_ERROR.APPROVAL_REQUIRED
|
|
2693
|
+
error.detail = { source: validated.source, sessionId: validated.sessionId, approval: 'required', dryRun: preview }
|
|
2694
|
+
throw error
|
|
2695
|
+
},
|
|
2696
|
+
// e2e 专用测试缝(仅 FANG_CONTRACT_TEST_HOOKS=1 时注册;生产不出现;且必须 delegate=true)
|
|
2697
|
+
...(process.env.FANG_CONTRACT_TEST_HOOKS === '1' ? {
|
|
2698
|
+
'fang.test.sleep': async (params, envelope) => {
|
|
2699
|
+
if (envelope?.meta?.delegate !== true) {
|
|
2700
|
+
const error = new Error('test hook requires delegated invocation')
|
|
2701
|
+
error.code = DELEGATE_ERROR.UNSUPPORTED
|
|
2702
|
+
throw error
|
|
2703
|
+
}
|
|
2704
|
+
const ms = Math.min(10000, Math.max(0, Number(params?.ms) || 100))
|
|
2705
|
+
await sleep(ms)
|
|
2706
|
+
return { sleptMs: ms }
|
|
2707
|
+
},
|
|
2708
|
+
} : {}),
|
|
2709
|
+
[CONTRACT_METHODS.DECISION_LIST]: async (params) => {
|
|
2710
|
+
const center = contractService('decisionCenter', 'snapshot', false)
|
|
2711
|
+
if (!center || typeof center.snapshot !== 'function') return delegateUnavailable('fang decision center is unavailable')
|
|
2712
|
+
const snapshot = center.snapshot()
|
|
2713
|
+
const items = Array.isArray(snapshot?.tickets) ? snapshot.tickets : (Array.isArray(snapshot?.items) ? snapshot.items : [])
|
|
2714
|
+
const limit = Math.min(50, Math.max(1, Number(params?.limit) || 20))
|
|
2715
|
+
return { items: items.slice(0, limit).map((t) => ({ id: t.id, level: t.level, status: t.status, title: t.title, priority: t.priority ?? null, risk: t.risk ?? null, at: t.createdAt ?? t.at ?? null })), total: items.length }
|
|
2716
|
+
},
|
|
2717
|
+
[CONTRACT_METHODS.APPROVALS_LIST]: async (params) => {
|
|
2718
|
+
const approver = contractService('approver', 'pending', false)
|
|
2719
|
+
if (!approver) return delegateUnavailable('fang approver is unavailable')
|
|
2720
|
+
const pending = typeof approver.pending === 'function' ? approver.pending() : []
|
|
2721
|
+
const limit = Math.min(50, Math.max(1, Number(params?.limit) || 20))
|
|
2722
|
+
return { items: (Array.isArray(pending) ? pending : []).slice(0, limit).map((a) => ({ id: a.id, kind: a.kind, risk: a.risk, state: a.state, title: a.title, at: a.createdAt ?? a.at ?? null })) }
|
|
2723
|
+
},
|
|
1831
2724
|
},
|
|
1832
2725
|
})
|
|
1833
2726
|
try { ctx.effect(() => ctx.provide(SERVICE.contract, contractServer)) } catch { /* fake ctx */ }
|
|
@@ -1961,6 +2854,173 @@ export function apply(ctx, config) {
|
|
|
1961
2854
|
const runtimeForkId = (essenceId) => 'rt-' + String(essenceId).replace(/^essence-/, '').replace(/[^A-Za-z0-9-]/g, '-')
|
|
1962
2855
|
// v3.0.9 三区口径:运行态 home 统一在 runtimeRoot(FANG_HOME 下是 sessions/<essenceId>/home)。
|
|
1963
2856
|
const runtimeHomeFor = (essenceId) => path.join(layout.runtimeRoot, String(essenceId), 'home')
|
|
2857
|
+
/**
|
|
2858
|
+
* 2026-11-22:官方推荐是默认底座,任何打开/派生都必须先把它修到当前母体版本,
|
|
2859
|
+
* 否则 profileUsesCurrentFangBundle 判 stale,分身会静默回退到 clean template,
|
|
2860
|
+
* 实验性插件就全丢(真机截图复现)。
|
|
2861
|
+
*/
|
|
2862
|
+
const repairOfficialEssenceNow = async () => {
|
|
2863
|
+
let repaired = null
|
|
2864
|
+
try {
|
|
2865
|
+
repaired = essenceManager.repairOfficialEssence({
|
|
2866
|
+
installed: (await listInstalledPlugins()) ?? [],
|
|
2867
|
+
motherProfileDir: templateDir(),
|
|
2868
|
+
})
|
|
2869
|
+
} catch (error) {
|
|
2870
|
+
repaired = { ok: false, error: String(error?.message ?? error) }
|
|
2871
|
+
}
|
|
2872
|
+
let modulesSync = { copied: [], missing: [] }
|
|
2873
|
+
try { modulesSync = syncProfileModulesFromMother(essenceManager.mergedProfileDir(OFFICIAL_ESSENCE_ID), templateDir()) } catch { /* best effort */ }
|
|
2874
|
+
if (repaired?.ok !== true) audit('official-essence-repair-failed', { repaired })
|
|
2875
|
+
return { repaired, modulesSync }
|
|
2876
|
+
}
|
|
2877
|
+
const applyOfficialExperimentalSurface = (profileDir, options = {}) => {
|
|
2878
|
+
if (process.env.DSH_FANG_EXPERIMENTAL_SURFACE === '0') return { ok: true, skipped: 'disabled' }
|
|
2879
|
+
if (options.coreMode === 'accelerated') return { ok: true, skipped: 'accelerated-core' }
|
|
2880
|
+
const dir = String(profileDir ?? '')
|
|
2881
|
+
const pkgFile = path.join(dir, 'package.json')
|
|
2882
|
+
const patchFile = path.join(dir, 'cordis.patch.yml')
|
|
2883
|
+
if (!exists(pkgFile)) return { ok: false, error: 'profile-package-missing' }
|
|
2884
|
+
const officialMerged = essenceManager.mergedProfileDir(OFFICIAL_ESSENCE_ID)
|
|
2885
|
+
const officialPkg = readJson(path.join(officialMerged, 'package.json'), null)
|
|
2886
|
+
if (!officialPkg) return { ok: false, error: 'official-profile-missing' }
|
|
2887
|
+
const officialPatch = parsePatchEntries(
|
|
2888
|
+
exists(path.join(officialMerged, 'cordis.patch.yml')) ? fs.readFileSync(path.join(officialMerged, 'cordis.patch.yml'), 'utf8') : '',
|
|
2889
|
+
).entries
|
|
2890
|
+
const experimentalNames = new Set([
|
|
2891
|
+
...OFFICIAL_EXPERIMENTAL_BUNDLES,
|
|
2892
|
+
...(Array.isArray(officialPkg?.dsh?.profile?.bundles) ? officialPkg.dsh.profile.bundles : []),
|
|
2893
|
+
...officialPatch.map((entry) => String(entry?.name ?? '')),
|
|
2894
|
+
].filter((name) => /^@deepseek-ai\/(dsh-experimental-|dsh-personalized|dsh-cua-|dsh-deepseek-chat-import)/.test(name)))
|
|
2895
|
+
if (experimentalNames.size === 0) return { ok: true, skipped: 'official-has-no-experimental' }
|
|
2896
|
+
const pkg = readJson(pkgFile, null)
|
|
2897
|
+
if (!pkg) return { ok: false, error: 'profile-package-invalid' }
|
|
2898
|
+
pkg.dsh = pkg.dsh && typeof pkg.dsh === 'object' ? pkg.dsh : {}
|
|
2899
|
+
pkg.dsh.profile = pkg.dsh.profile && typeof pkg.dsh.profile === 'object' ? pkg.dsh.profile : {}
|
|
2900
|
+
const bundles = Array.isArray(pkg.dsh.profile.bundles) ? [...pkg.dsh.profile.bundles] : []
|
|
2901
|
+
let bundlesAdded = 0
|
|
2902
|
+
for (const name of experimentalNames) {
|
|
2903
|
+
if (bundles.includes(name)) continue
|
|
2904
|
+
bundles.push(name)
|
|
2905
|
+
bundlesAdded += 1
|
|
2906
|
+
}
|
|
2907
|
+
pkg.dependencies = pkg.dependencies && typeof pkg.dependencies === 'object' ? pkg.dependencies : {}
|
|
2908
|
+
pkg.dependencies[NODE_COMPAT_BUNDLE] = '^0.1.0'
|
|
2909
|
+
if (!bundles.includes(NODE_COMPAT_BUNDLE)) bundles.unshift(NODE_COMPAT_BUNDLE)
|
|
2910
|
+
pkg.dsh.profile.bundles = bundles
|
|
2911
|
+
writeJsonAtomic(pkgFile, pkg)
|
|
2912
|
+
const parsed = parsePatchEntries(exists(patchFile) ? fs.readFileSync(patchFile, 'utf8') : '')
|
|
2913
|
+
const entries = parsed.entries.filter((entry) => !experimentalNames.has(String(entry?.name ?? '')))
|
|
2914
|
+
let rowsAdded = 0
|
|
2915
|
+
for (const name of experimentalNames) {
|
|
2916
|
+
const officialEntry = officialPatch.find((entry) => entry?.name === name)
|
|
2917
|
+
entries.push({ id: officialEntry?.id ?? `fork-exp-${sha256(name).slice(0, 8)}`, name, disabled: false })
|
|
2918
|
+
rowsAdded += 1
|
|
2919
|
+
}
|
|
2920
|
+
fs.writeFileSync(patchFile, `${JSON.stringify(entries, null, 2)}\n`, 'utf8')
|
|
2921
|
+
return { ok: true, bundles: [...experimentalNames], bundlesAdded, rowsAdded }
|
|
2922
|
+
}
|
|
2923
|
+
/**
|
|
2924
|
+
* v3.7.4:把来源元主的完整插件面(bundles + dependencies + patch rows)覆盖到 fork profile。
|
|
2925
|
+
* 修复 BUG-4:只补实验性 bundle 会留下“已同步”假阳性;reset 后必须整体对齐来源。
|
|
2926
|
+
* fork 私有配置锁行(tool-plugin-manager / ui-settings-plugin-inventory)保留。
|
|
2927
|
+
*/
|
|
2928
|
+
const applySourcePluginSurface = (task, profileDir) => {
|
|
2929
|
+
try {
|
|
2930
|
+
if (task?.coreMode === 'accelerated') return { ok: true, skipped: 'accelerated-core' }
|
|
2931
|
+
const sourceId = String(task?.essenceId || task?.syncSourceId || OFFICIAL_ESSENCE_ID)
|
|
2932
|
+
const sourceDir = essenceManager.mergedProfileDir(sourceId)
|
|
2933
|
+
const sourcePkg = readJson(path.join(sourceDir, 'package.json'), null)
|
|
2934
|
+
if (!sourcePkg) return { ok: false, error: 'source-profile-missing', sourceId }
|
|
2935
|
+
const sourcePatch = parsePatchEntries(
|
|
2936
|
+
exists(path.join(sourceDir, 'cordis.patch.yml')) ? fs.readFileSync(path.join(sourceDir, 'cordis.patch.yml'), 'utf8') : '',
|
|
2937
|
+
).entries
|
|
2938
|
+
const pkgFile = path.join(String(profileDir), 'package.json')
|
|
2939
|
+
const patchFile = path.join(String(profileDir), 'cordis.patch.yml')
|
|
2940
|
+
const forkPkg = readJson(pkgFile, null)
|
|
2941
|
+
if (!forkPkg) return { ok: false, error: 'fork-profile-missing' }
|
|
2942
|
+
forkPkg.dsh = forkPkg.dsh && typeof forkPkg.dsh === 'object' ? forkPkg.dsh : {}
|
|
2943
|
+
forkPkg.dsh.profile = forkPkg.dsh.profile && typeof forkPkg.dsh.profile === 'object' ? forkPkg.dsh.profile : {}
|
|
2944
|
+
const sourceBundles = Array.isArray(sourcePkg?.dsh?.profile?.bundles) ? sourcePkg.dsh.profile.bundles : []
|
|
2945
|
+
const forkBundlesBefore = Array.isArray(forkPkg?.dsh?.profile?.bundles) ? forkPkg.dsh.profile.bundles : []
|
|
2946
|
+
const forkFangBundle = FORK_BUNDLE_NAMES.find((candidate) => exists(path.join(String(profileDir), 'node_modules', ...candidate.split('/'))))
|
|
2947
|
+
|| forkBundlesBefore.find((candidate) => /(^|\/)dsh-fang$/.test(String(candidate)))
|
|
2948
|
+
|| '@twinsearth/fang-dsh-plugin'
|
|
2949
|
+
const bundles = sourceBundles
|
|
2950
|
+
.filter((name) => name !== NODE_COMPAT_BUNDLE)
|
|
2951
|
+
.map((name) => /(^|\/)(dsh-fang|fang-dsh-plugin)$/.test(String(name)) ? forkFangBundle : name)
|
|
2952
|
+
bundles.unshift(NODE_COMPAT_BUNDLE)
|
|
2953
|
+
forkPkg.dsh.profile.bundles = [...new Set(bundles)]
|
|
2954
|
+
forkPkg.dependencies = {
|
|
2955
|
+
...(forkPkg.dependencies && typeof forkPkg.dependencies === 'object' ? forkPkg.dependencies : {}),
|
|
2956
|
+
...(sourcePkg.dependencies && typeof sourcePkg.dependencies === 'object' ? sourcePkg.dependencies : {}),
|
|
2957
|
+
[NODE_COMPAT_BUNDLE]: '^0.1.0',
|
|
2958
|
+
}
|
|
2959
|
+
writeJsonAtomic(pkgFile, forkPkg)
|
|
2960
|
+
const forkPatch = parsePatchEntries(exists(patchFile) ? fs.readFileSync(patchFile, 'utf8') : '').entries
|
|
2961
|
+
const lockIds = new Set(['tool-plugin-manager', 'ui-settings-plugin-inventory'])
|
|
2962
|
+
const locks = forkPatch.filter((entry) => lockIds.has(String(entry?.id ?? '')))
|
|
2963
|
+
const merged = [...sourcePatch]
|
|
2964
|
+
for (const row of locks) if (!merged.some((entry) => entry?.id === row.id)) merged.push(row)
|
|
2965
|
+
fs.writeFileSync(patchFile, `${JSON.stringify(merged, null, 2)}\n`, 'utf8')
|
|
2966
|
+
return { ok: true, sourceId, bundles: forkPkg.dsh.profile.bundles.length, rows: merged.length }
|
|
2967
|
+
} catch (error) {
|
|
2968
|
+
return { ok: false, error: String(error?.message ?? error) }
|
|
2969
|
+
}
|
|
2970
|
+
}
|
|
2971
|
+
const syncProfileModulesFromMother = (profileDir, motherProfileDir) => {
|
|
2972
|
+
const copied = []
|
|
2973
|
+
const missing = []
|
|
2974
|
+
const pkg = readJson(path.join(String(profileDir ?? ''), 'package.json'), {}) ?? {}
|
|
2975
|
+
const names = new Set([
|
|
2976
|
+
...(Array.isArray(pkg?.dsh?.profile?.bundles) ? pkg.dsh.profile.bundles : []),
|
|
2977
|
+
...Object.keys(pkg?.dependencies ?? {}),
|
|
2978
|
+
...Object.keys(pkg?.optionalDependencies ?? {}),
|
|
2979
|
+
])
|
|
2980
|
+
const motherModules = path.join(String(motherProfileDir ?? ''), 'node_modules')
|
|
2981
|
+
for (const name of names) {
|
|
2982
|
+
if (typeof name !== 'string' || !name || name.startsWith('@local/')) continue
|
|
2983
|
+
const target = path.join(String(profileDir), 'node_modules', ...name.split('/'))
|
|
2984
|
+
const source = path.join(motherModules, ...name.split('/'))
|
|
2985
|
+
if (!exists(source)) { if (!exists(target)) missing.push(name); continue }
|
|
2986
|
+
// 同名包已存在时不能只看“有没有”:旧 official/fork 可能停留在旧 fang/子包版本,
|
|
2987
|
+
// 必须按 package.json version 比较后替换,否则 stale bundle 永远修不好。
|
|
2988
|
+
let sameVersion = false
|
|
2989
|
+
if (exists(target)) {
|
|
2990
|
+
const targetPkg = readJson(path.join(target, 'package.json'), {}) ?? {}
|
|
2991
|
+
const sourcePkg = readJson(path.join(source, 'package.json'), {}) ?? {}
|
|
2992
|
+
sameVersion = Boolean(sourcePkg.version) && sourcePkg.version === targetPkg.version
|
|
2993
|
+
if (sameVersion) continue
|
|
2994
|
+
}
|
|
2995
|
+
try {
|
|
2996
|
+
if (exists(target)) removeTree(target)
|
|
2997
|
+
ensureDir(path.dirname(target))
|
|
2998
|
+
copyTree(source, target)
|
|
2999
|
+
copied.push(name)
|
|
3000
|
+
} catch { missing.push(name) }
|
|
3001
|
+
}
|
|
3002
|
+
return { copied, missing }
|
|
3003
|
+
}
|
|
3004
|
+
/**
|
|
3005
|
+
* 2026-11-22:元主 Web 里改的插件设置必须先捕获回元宝,分身下一次打开才会拿到。
|
|
3006
|
+
* 以前只在元主运行时停止/再次启动时捕获;运行中直接开分身会读到旧 merged 快照。
|
|
3007
|
+
*/
|
|
3008
|
+
const captureEssenceRuntimeIfPresent = (essenceId) => {
|
|
3009
|
+
const id = String(essenceId ?? '').trim()
|
|
3010
|
+
if (!id) return null
|
|
3011
|
+
const runtimeProfileDir = path.join(runtimeHomeFor(id), 'profiles', 'essence-runtime')
|
|
3012
|
+
if (!exists(runtimeProfileDir)) return null
|
|
3013
|
+
try {
|
|
3014
|
+
const out = captureRuntimeProfileIntoEssence({
|
|
3015
|
+
essenceManager, essenceId: id, runtimeProfileDir, logger: ctx.logger,
|
|
3016
|
+
})
|
|
3017
|
+
if (out?.captured) audit('essence-runtime-captured-on-open', { essenceId: id, packageChanged: out.packageChanged === true, patchChanged: out.patchChanged ?? 0 })
|
|
3018
|
+
return out
|
|
3019
|
+
} catch (error) {
|
|
3020
|
+
audit('essence-runtime-capture-on-open-failed', { essenceId: id, error: String(error?.message ?? error) })
|
|
3021
|
+
return { ok: false, captured: false, error: String(error?.message ?? error) }
|
|
3022
|
+
}
|
|
3023
|
+
}
|
|
1964
3024
|
// 路径守卫:任何拼接出来的目标必须落在给定根内(拒绝 .. / 绝对路径逃逸)。
|
|
1965
3025
|
const assertInside = (root, target, label) => {
|
|
1966
3026
|
const resolvedRoot = path.resolve(String(root))
|
|
@@ -2153,7 +3213,44 @@ export function apply(ctx, config) {
|
|
|
2153
3213
|
ensureDefaultEssence: async ({ apply = false, force = false, mode = 'copy-local' } = {}) => {
|
|
2154
3214
|
const existingId = readDefaultEssenceId()
|
|
2155
3215
|
const existing = existingId ? essenceManager.getMeta(existingId) : null
|
|
2156
|
-
|
|
3216
|
+
const isAutoDefault = (meta) => Boolean(meta) && meta.official !== true
|
|
3217
|
+
&& String(meta.name ?? '').startsWith(DEFAULT_ESSENCE_NAME)
|
|
3218
|
+
// 2026-11-22:官方推荐是唯一保底默认元宝;即使它已经是 default,也要每次启动重算
|
|
3219
|
+
// (否则旧 official overlay 会停在旧 fang 版本,分身派生时被判 stale 回退到 clean template,
|
|
3220
|
+
// 实验性插件就全部丢失)。
|
|
3221
|
+
const repairOfficialDefault = async () => {
|
|
3222
|
+
if (apply !== true) {
|
|
3223
|
+
return { ok: true, dryRun: true, official: true, existed: true, created: false, essenceId: OFFICIAL_ESSENCE_ID, mode }
|
|
3224
|
+
}
|
|
3225
|
+
let repaired = null
|
|
3226
|
+
try {
|
|
3227
|
+
repaired = essenceManager.repairOfficialEssence({
|
|
3228
|
+
installed: (await listInstalledPlugins()) ?? [],
|
|
3229
|
+
motherProfileDir: templateDir(),
|
|
3230
|
+
})
|
|
3231
|
+
} catch (error) {
|
|
3232
|
+
repaired = { ok: false, error: String(error?.message ?? error) }
|
|
3233
|
+
}
|
|
3234
|
+
let modulesSync = { copied: [], missing: [] }
|
|
3235
|
+
try { modulesSync = syncProfileModulesFromMother(essenceManager.mergedProfileDir(OFFICIAL_ESSENCE_ID), templateDir()) } catch { /* best effort */ }
|
|
3236
|
+
essenceManager.setDefault(OFFICIAL_ESSENCE_ID)
|
|
3237
|
+
writeDefaultEssenceId(OFFICIAL_ESSENCE_ID)
|
|
3238
|
+
const archivedDuplicates = []
|
|
3239
|
+
for (const meta of essenceManager.list()) {
|
|
3240
|
+
if (!isAutoDefault(meta) || meta.archived === true) continue
|
|
3241
|
+
try { essenceManager.archive(meta.id, true); archivedDuplicates.push(meta.id) } catch { /* best effort */ }
|
|
3242
|
+
}
|
|
3243
|
+
audit('default-essence-official', { essenceId: OFFICIAL_ESSENCE_ID, archivedDuplicates, repaired, modulesSync })
|
|
3244
|
+
return { ok: true, existed: true, created: false, official: true, essenceId: OFFICIAL_ESSENCE_ID, mode, archivedDuplicates, repaired, modulesSync }
|
|
3245
|
+
}
|
|
3246
|
+
if (existing?.official === true) return repairOfficialDefault()
|
|
3247
|
+
// 用户自己选的默认元宝(非官方、非自动快照)保持不动。
|
|
3248
|
+
if (existing?.id && !isAutoDefault(existing)) {
|
|
3249
|
+
return { ok: true, existed: true, created: false, official: false, essenceId: existingId, mode }
|
|
3250
|
+
}
|
|
3251
|
+
// 2026-11-22:保底一个「开发者推荐(官方)」,不再无限新增“默认元宝”快照。
|
|
3252
|
+
const official = essenceManager.getMeta(OFFICIAL_ESSENCE_ID)
|
|
3253
|
+
if (official?.id && official.archived !== true) return repairOfficialDefault()
|
|
2157
3254
|
const entries = await listInstalledPlugins()
|
|
2158
3255
|
const plan = planDefaultEssence(entries ?? [])
|
|
2159
3256
|
const userEssences = essenceManager.list().filter((meta) => meta.official !== true)
|
|
@@ -2325,6 +3422,7 @@ export function apply(ctx, config) {
|
|
|
2325
3422
|
} catch (error) {
|
|
2326
3423
|
capture = { ok: false, captured: false, error: 'capture-threw', detail: String(error?.message ?? error) }
|
|
2327
3424
|
}
|
|
3425
|
+
if (id === OFFICIAL_ESSENCE_ID) await repairOfficialEssenceNow()
|
|
2328
3426
|
await essenceManager.ensureFresh(id)
|
|
2329
3427
|
const merged = essenceManager.mergedProfileDir(id)
|
|
2330
3428
|
if (!exists(merged)) throw new Error('merged-profile-missing')
|
|
@@ -2341,6 +3439,10 @@ export function apply(ctx, config) {
|
|
|
2341
3439
|
throw new Error(`essence-node-modules-copy-failed: ${String(error?.message ?? error)}`)
|
|
2342
3440
|
}
|
|
2343
3441
|
}
|
|
3442
|
+
// 旧元主的模块树是旧快照:只补它 package.json 声明但 node_modules 缺失的包
|
|
3443
|
+
// (2026-11-22:@twinsearth/dsh-2xray 缺失导致元主 Web 报 cannot resolve bundle)。
|
|
3444
|
+
const modulesSync = syncProfileModulesFromMother(merged, templateDir())
|
|
3445
|
+
if (modulesSync.copied.length > 0) audit('essence-modules-synced', { essenceId: id, copied: modulesSync.copied })
|
|
2344
3446
|
// 复制来的模块树记录了母体 store;元主/运行态的 pnpm 必须显式用同一个 store,
|
|
2345
3447
|
// 否则项目在 D: 盘、模块来自 C: store 时会报 ERR_PNPM_UNEXPECTED_STORE。
|
|
2346
3448
|
// v3.1.8:pnpm 11 只从 pnpm-workspace.yaml 读取非鉴权设置(.npmrc 只剩鉴权/网络键),
|
|
@@ -2377,6 +3479,8 @@ export function apply(ctx, config) {
|
|
|
2377
3479
|
// 否则官方/用户元主打开后看不到本机插件列表(v3.0.10 实测)。
|
|
2378
3480
|
cleanTemplate: false,
|
|
2379
3481
|
nodeModulesSource: essenceModules,
|
|
3482
|
+
// P0 硬约束:加速核只服务分身 Web;元主运行态始终原厂 core。
|
|
3483
|
+
coreMode: 'stock',
|
|
2380
3484
|
})
|
|
2381
3485
|
if (!provisioned.ok) throw new Error(String(provisioned.error ?? 'runtime-provision-failed'))
|
|
2382
3486
|
// 历史版本把生产盘锁写进了 essence-runtime;配置实例必须能管理插件,升级后清掉。
|
|
@@ -2390,6 +3494,9 @@ export function apply(ctx, config) {
|
|
|
2390
3494
|
} catch (error) {
|
|
2391
3495
|
throw new Error(`runtime-node-modules-mirror-failed: ${String(error?.message ?? error)}`)
|
|
2392
3496
|
}
|
|
3497
|
+
// 补运行态 profile 里仍缺的包(mirror 只处理已登记条目)。
|
|
3498
|
+
const runtimeModulesSync = syncProfileModulesFromMother(runtimeProfileDir, templateDir())
|
|
3499
|
+
if (runtimeModulesSync.copied.length > 0) audit('essence-runtime-modules-synced', { essenceId: id, copied: runtimeModulesSync.copied })
|
|
2393
3500
|
// v3.1.8:让运行态内的 pnpm 真正可用(元宝「插件」页更新/卸载插件走 DSH plugin manager)。
|
|
2394
3501
|
// 失败不阻塞实例启动(实例仍可跑会话),但要把原因带回给调用方/面板。
|
|
2395
3502
|
let pnpmConfig = null
|
|
@@ -2411,9 +3518,11 @@ export function apply(ctx, config) {
|
|
|
2411
3518
|
homeDir,
|
|
2412
3519
|
profile: 'essence-runtime',
|
|
2413
3520
|
cliPath: cliPath(),
|
|
3521
|
+
// P0 硬约束:即使 forker 默认切到 accelerated,元主运行态也只跑原厂 core。
|
|
3522
|
+
coreMode: 'stock',
|
|
2414
3523
|
// v3.1.16:原身运行态同样需要母体 dataDir,房主 Router 才能零配置推导
|
|
2415
3524
|
// 契约 file 桥(contract-outbox);普通分身在 846/1461/1534 行已有同名注入。
|
|
2416
|
-
env: { DSH_FANG_ROLE: 'fork', DSH_FANG_TASK_ID: forkId, DSH_FANG_ESSENCE: '1', DSH_FANG_MOTHER: layout.dataDir },
|
|
3525
|
+
env: { DSH_FANG_ROLE: 'fork', DSH_FANG_TASK_ID: forkId, DSH_FANG_ESSENCE: '1', DSH_FANG_MOTHER: layout.dataDir, ...forkTempEnv(forkId) },
|
|
2417
3526
|
})
|
|
2418
3527
|
if (!started.ok) {
|
|
2419
3528
|
// v3.1.33:把真实 errno 与启动规格带进错误信息,避免只剩一个笼统的 spawn-error。
|
|
@@ -2786,6 +3895,12 @@ export function apply(ctx, config) {
|
|
|
2786
3895
|
res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
2787
3896
|
res.end(JSON.stringify(obj))
|
|
2788
3897
|
}
|
|
3898
|
+
// v3.3.3: queue journal route gate (json is in this scope).
|
|
3899
|
+
const queueJournalGate = (res) => {
|
|
3900
|
+
if (queueJournalEnabled()) return false
|
|
3901
|
+
json(res, 503, { ok: false, error: 'queue-journal-disabled', detail: 'enable the fang-queue-journal sub-plugin to use composer journal/queue recovery' })
|
|
3902
|
+
return true
|
|
3903
|
+
}
|
|
2789
3904
|
const readBody = (req) => new Promise((resolve) => {
|
|
2790
3905
|
let raw = ''
|
|
2791
3906
|
req.on('data', (c) => { raw += c; if (raw.length > 1_000_000) req.destroy() })
|
|
@@ -2804,6 +3919,7 @@ export function apply(ctx, config) {
|
|
|
2804
3919
|
const decision = checkRequestAuth(req, {
|
|
2805
3920
|
token: authToken,
|
|
2806
3921
|
publicRoute: authToken.length === 0 || routeOptions?.public === true,
|
|
3922
|
+
bootstrap: routeOptions?.bootstrap === true,
|
|
2807
3923
|
})
|
|
2808
3924
|
if (!decision.ok) return json(res, decision.status, authErrorBody(decision))
|
|
2809
3925
|
if (req.method !== method) {
|
|
@@ -2827,6 +3943,7 @@ export function apply(ctx, config) {
|
|
|
2827
3943
|
const decision = checkRequestAuth(req, {
|
|
2828
3944
|
token: authToken,
|
|
2829
3945
|
publicRoute: authToken.length === 0 || routeOptions?.public === true,
|
|
3946
|
+
bootstrap: routeOptions?.bootstrap === true,
|
|
2830
3947
|
})
|
|
2831
3948
|
if (!decision.ok) return json(res, decision.status, authErrorBody(decision))
|
|
2832
3949
|
const allow = Object.keys(handlers)
|
|
@@ -2869,10 +3986,15 @@ export function apply(ctx, config) {
|
|
|
2869
3986
|
}
|
|
2870
3987
|
}
|
|
2871
3988
|
|
|
2872
|
-
// 浏览器面板 bootstrap:同源读取 token(Host/Origin
|
|
2873
|
-
|
|
2874
|
-
|
|
2875
|
-
|
|
3989
|
+
// 浏览器面板 bootstrap:同源读取 token(Host/Origin 已校验;v3.5.5 起 bootstrap 收紧:
|
|
3990
|
+
// 仅回环 peer + 同源 Origin(host:port 完全一致)+ Sec-Fetch-Site same-origin/none)。
|
|
3991
|
+
route('GET', `${prefix}/api/auth-token`, (req, res) => {
|
|
3992
|
+
try {
|
|
3993
|
+
res.setHeader?.('cache-control', 'no-store')
|
|
3994
|
+
res.setHeader?.('vary', 'Origin')
|
|
3995
|
+
} catch { /* fake res */ }
|
|
3996
|
+
return json(res, 200, { ok: true, token: authToken })
|
|
3997
|
+
}, { public: true, bootstrap: true })
|
|
2876
3998
|
|
|
2877
3999
|
// 母体不可删除:即使有人直接打接口也返回 403,而不是“没有这个路由”。
|
|
2878
4000
|
// 仅 POST(allow-list 只允许 GET/POST;DELETE 语义由该 403 表达)。
|
|
@@ -2920,20 +4042,198 @@ export function apply(ctx, config) {
|
|
|
2920
4042
|
if (!contractAuthorized(req)) return json(res, 401, { ok: false, code: 'contract-unauthorized' })
|
|
2921
4043
|
const body = await readBody(req)
|
|
2922
4044
|
if (!body || typeof body !== 'object') return json(res, 400, { ok: false, code: 'invalid-envelope' })
|
|
4045
|
+
// B 委托:调用方以 meta.delegate=true 声明「委托调用」,白名单默认拒绝;
|
|
4046
|
+
// 未声明 delegate 的旧调用方保持既有语义(fork.spawn/decision.* 等不回归)。
|
|
4047
|
+
const delegated = body?.meta?.delegate === true
|
|
4048
|
+
const source = String(body?.meta?.source ?? body?.meta?.instanceId ?? '').slice(0, 120)
|
|
4049
|
+
if (delegated) {
|
|
4050
|
+
// B-8 激活链(专业版,默认关闭):① 开关 → ② 逐项 allow → ③ 每次调用审批票 →
|
|
4051
|
+
// ④ 审计 + 资源限额。缺一环即显式拒绝(错误码 + detail.stage/reason),不静默降级。
|
|
4052
|
+
if (PRO_CAPABILITIES.includes(String(body?.method ?? ''))) {
|
|
4053
|
+
const proGateResult = checkProGate({ method: body?.method, config: proCfg, ticketId: body?.params?.approvalTicket, source, params: body?.params })
|
|
4054
|
+
if (proGateResult.ok !== true) {
|
|
4055
|
+
try { audit('contract-delegate', proAuditRecord({ method: body?.method, source, outcome: 'rejected', stage: proGateResult.stage, error: proGateResult.code, ticketId: body?.params?.approvalTicket, limits: proCfg })) } catch { /* audit optional */ }
|
|
4056
|
+
return json(res, 200, createResponse({ id: body?.id, error: { code: proGateResult.code, message: proGateResult.message, detail: { stage: proGateResult.stage, digest: proGateResult.digest ?? null } } }))
|
|
4057
|
+
}
|
|
4058
|
+
if (exceedPayloadLimit(body?.params, delegationCfg.maxPayloadBytes)) {
|
|
4059
|
+
try { audit('contract-delegate', proAuditRecord({ method: body?.method, source, outcome: 'rejected', stage: PRO_STAGE.LIMIT_EXCEEDED, error: DELEGATE_ERROR.INVALID, ticketId: body?.params?.approvalTicket, limits: proCfg })) } catch { /* audit optional */ }
|
|
4060
|
+
return json(res, 200, createResponse({ id: body?.id, error: { code: DELEGATE_ERROR.INVALID, message: 'delegated payload exceeds maxPayloadBytes', detail: { stage: PRO_STAGE.LIMIT_EXCEEDED } } }))
|
|
4061
|
+
}
|
|
4062
|
+
const consumed = proApprovals.consume({ id: body?.params?.approvalTicket, capability: body?.method, source, digest: proGateResult.digest })
|
|
4063
|
+
if (consumed.ok !== true) {
|
|
4064
|
+
try { audit('contract-delegate', proAuditRecord({ method: body?.method, source, outcome: 'rejected', stage: consumed.stage ?? PRO_STAGE.APPROVAL_INVALID, error: DELEGATE_ERROR.APPROVAL_REQUIRED, ticketId: body?.params?.approvalTicket, limits: proCfg })) } catch { /* audit optional */ }
|
|
4065
|
+
return json(res, 200, createResponse({ id: body?.id, error: { code: DELEGATE_ERROR.APPROVAL_REQUIRED, message: `approval ticket rejected: ${consumed.reason ?? 'invalid'}`, detail: { stage: PRO_STAGE.APPROVAL_INVALID, reason: consumed.reason ?? 'invalid' } } }))
|
|
4066
|
+
}
|
|
4067
|
+
const proRun = await runProCapability({
|
|
4068
|
+
execute: () => providerMissingResult(body?.method),
|
|
4069
|
+
timeoutMs: proCfg.timeoutMs,
|
|
4070
|
+
maxOutputBytes: proCfg.maxOutputBytes,
|
|
4071
|
+
gate: proGate,
|
|
4072
|
+
})
|
|
4073
|
+
const proOutcome = proRun.code === DELEGATE_ERROR.RATE_LIMITED ? 'rate-limited' : (proRun.ok === true ? 'ok' : 'error')
|
|
4074
|
+
try { audit('contract-delegate', proAuditRecord({ method: body?.method, source, outcome: proOutcome, stage: proRun.stage, error: proRun.ok === true ? null : proRun.code, ticketId: body?.params?.approvalTicket, latencyMs: proRun.latencyMs, limits: proCfg })) } catch { /* audit optional */ }
|
|
4075
|
+
return json(res, 200, createResponse({ id: body?.id, error: { code: proRun.code, message: proRun.message, detail: { stage: proRun.stage, activation: 'verified', limits: { timeoutMs: proCfg.timeoutMs, maxConcurrent: proCfg.maxConcurrent, maxOutputBytes: proCfg.maxOutputBytes } } } }))
|
|
4076
|
+
}
|
|
4077
|
+
const decision = checkDelegation({ method: body?.method, allow: delegationCfg.allow, config: delegationCfg })
|
|
4078
|
+
if (decision.ok !== true) {
|
|
4079
|
+
try { audit('contract-delegate', delegationAuditRecord({ method: body?.method, source, outcome: 'rejected', error: decision.error, latencyMs: 0 })) } catch { /* audit optional */ }
|
|
4080
|
+
return json(res, 200, createResponse({ id: body?.id, error: { code: decision.error, message: decision.message ?? decision.error } }))
|
|
4081
|
+
}
|
|
4082
|
+
if (exceedPayloadLimit(body?.params, delegationCfg.maxPayloadBytes)) {
|
|
4083
|
+
try { audit('contract-delegate', delegationAuditRecord({ method: body?.method, source, outcome: 'rejected', error: DELEGATE_ERROR.INVALID, latencyMs: 0 })) } catch { /* audit optional */ }
|
|
4084
|
+
return json(res, 200, createResponse({ id: body?.id, error: { code: DELEGATE_ERROR.INVALID, message: 'delegated payload exceeds maxPayloadBytes' } }))
|
|
4085
|
+
}
|
|
4086
|
+
const slot = delegationGate.tryAcquire()
|
|
4087
|
+
if (slot.ok !== true) {
|
|
4088
|
+
try { audit('contract-delegate', delegationAuditRecord({ method: body?.method, source, outcome: 'rate-limited', error: DELEGATE_ERROR.RATE_LIMITED, latencyMs: 0 })) } catch { /* audit optional */ }
|
|
4089
|
+
return json(res, 200, createResponse({ id: body?.id, error: { code: DELEGATE_ERROR.RATE_LIMITED, message: `delegation concurrency limit reached (max ${delegationCfg.maxConcurrent})` } }))
|
|
4090
|
+
}
|
|
4091
|
+
try {
|
|
4092
|
+
// LSP 委托需要拉起/索引语言服务器,用 writeTimeoutMs 预算;其余只读能力用 readTimeoutMs。
|
|
4093
|
+
const budgetMs = String(body?.method ?? '') === 'fang.tool.invoke' ? delegationCfg.writeTimeoutMs : delegationCfg.readTimeoutMs
|
|
4094
|
+
const run = await runDelegated(() => contractServer.invoke(body), { timeoutMs: budgetMs })
|
|
4095
|
+
const errorCode = run.ok ? null : (run.error ?? DELEGATE_ERROR.UNAVAILABLE)
|
|
4096
|
+
try { audit('contract-delegate', delegationAuditRecord({ method: body?.method, source, outcome: run.ok ? 'ok' : 'error', error: errorCode, latencyMs: run.latencyMs })) } catch { /* audit optional */ }
|
|
4097
|
+
if (run.ok !== true) {
|
|
4098
|
+
return json(res, 200, createResponse({ id: body?.id, error: { code: errorCode, message: run.message ?? errorCode } }))
|
|
4099
|
+
}
|
|
4100
|
+
// 委托模式统一错误码:服务不可用 → contract-unavailable(不泄露内部 code)。
|
|
4101
|
+
if (run.value?.ok === false && run.value?.error?.code === 'fang-service-unavailable') {
|
|
4102
|
+
return json(res, 200, createResponse({ id: body?.id, error: { code: DELEGATE_ERROR.UNAVAILABLE, message: 'capability service unavailable on mother' } }))
|
|
4103
|
+
}
|
|
4104
|
+
return json(res, 200, run.value)
|
|
4105
|
+
} finally {
|
|
4106
|
+
delegationGate.release()
|
|
4107
|
+
}
|
|
4108
|
+
}
|
|
2923
4109
|
const out = await contractServer.invoke(body)
|
|
2924
4110
|
return json(res, 200, out)
|
|
2925
4111
|
})
|
|
2926
|
-
|
|
2927
|
-
|
|
2928
|
-
|
|
2929
|
-
|
|
4112
|
+
// B-8 专业版审批票签发(每次调用一张,一次性 + TTL;签发需要母体操作者 token)。
|
|
4113
|
+
route('POST', `${contractPath}/pro/approval`, async (req, res) => {
|
|
4114
|
+
if (!contractCfg.token) return json(res, 503, { ok: false, code: 'contract-token-required' })
|
|
4115
|
+
if (!contractAuthorized(req)) return json(res, 401, { ok: false, code: 'contract-unauthorized' })
|
|
4116
|
+
const body = await readBody(req)
|
|
4117
|
+
if (!body || typeof body !== 'object') return json(res, 400, { ok: false, code: 'invalid-envelope' })
|
|
4118
|
+
const capability = String(body.capability ?? '').trim()
|
|
4119
|
+
if (!PRO_CAPABILITIES.includes(capability)) return json(res, 200, { ok: false, code: DELEGATE_ERROR.UNSUPPORTED, stage: 'not-pro', message: `not a pro capability: ${capability || '(empty)'}` })
|
|
4120
|
+
if (proCfg.enabled !== true) return json(res, 200, { ok: false, code: DELEGATE_ERROR.UNSUPPORTED, stage: PRO_STAGE.DISABLED, message: 'pro capability disabled (default off): enable contract.delegate.pro.enabled first' })
|
|
4121
|
+
if (!proCfg.allow.includes(capability)) return json(res, 200, { ok: false, code: DELEGATE_ERROR.UNSUPPORTED, stage: PRO_STAGE.NOT_ALLOWED, message: `pro capability not activated: add '${capability}' to contract.delegate.pro.allow` })
|
|
4122
|
+
// v3.5.5(R23 安全):审批票必须绑定“这一次调用的精确参数”。调用方必须显式提供 params
|
|
4123
|
+
// (可为 null);未绑定参数的票在 consume 侧会被 params-unbound 拒绝,这里提前给出可读错误。
|
|
4124
|
+
if (!Object.prototype.hasOwnProperty.call(body, 'params')) {
|
|
4125
|
+
return json(res, 400, {
|
|
4126
|
+
ok: false,
|
|
4127
|
+
code: 'approval-params-required',
|
|
4128
|
+
stage: 'approval-params-required',
|
|
4129
|
+
message: 'approval ticket must bind the exact delegated params: send "params" (may be null) representing the payload to be approved',
|
|
4130
|
+
})
|
|
4131
|
+
}
|
|
4132
|
+
const digest = proParamsDigest(body.params)
|
|
4133
|
+
const issued = proApprovals.issue({ capability, source: String(body.source ?? '').slice(0, 120), digest, ttlMs: proCfg.approvalTtlMs })
|
|
4134
|
+
if (issued.ok !== true) return json(res, 200, { ok: false, code: DELEGATE_ERROR.INVALID, stage: 'invalid-request', message: String(issued.reason ?? 'cannot issue approval') })
|
|
4135
|
+
// 审计是审批链的硬一环:账本写不进去就不签发(避免“批了但无证据”)。
|
|
2930
4136
|
try {
|
|
2931
|
-
|
|
2932
|
-
|
|
2933
|
-
|
|
2934
|
-
|
|
2935
|
-
|
|
4137
|
+
auditStrict('contract-delegate', proAuditRecord({ method: capability, source: body.source, outcome: 'approval-issued', stage: 'approval-issued', ticketId: issued.ticket.id, limits: proCfg }))
|
|
4138
|
+
} catch (error) {
|
|
4139
|
+
return json(res, 503, {
|
|
4140
|
+
ok: false,
|
|
4141
|
+
code: 'audit-unavailable',
|
|
4142
|
+
stage: 'audit-unavailable',
|
|
4143
|
+
message: `refusing to issue approval without an auditable ledger: ${String(error?.message ?? error).slice(0, 200)}`,
|
|
4144
|
+
})
|
|
4145
|
+
}
|
|
4146
|
+
return json(res, 200, { ok: true, approval: { id: issued.ticket.id, capability: issued.ticket.capability, source: issued.ticket.source, expiresAt: issued.ticket.expiresAt, paramsDigest: issued.ticket.digest } })
|
|
4147
|
+
})
|
|
4148
|
+
route('GET', `${contractPath}/pro/status`, (req, res) => {
|
|
4149
|
+
if (!contractCfg.token) return json(res, 503, { ok: false, code: 'contract-token-required' })
|
|
4150
|
+
if (!contractAuthorized(req)) return json(res, 401, { ok: false, code: 'contract-unauthorized' })
|
|
4151
|
+
return json(res, 200, {
|
|
4152
|
+
ok: true,
|
|
4153
|
+
enabled: proCfg.enabled,
|
|
4154
|
+
allow: [...proCfg.allow],
|
|
4155
|
+
pendingTickets: proApprovals.pendingCount(),
|
|
4156
|
+
limits: { approvalTtlMs: proCfg.approvalTtlMs, maxConcurrent: proCfg.maxConcurrent, timeoutMs: proCfg.timeoutMs, maxOutputBytes: proCfg.maxOutputBytes },
|
|
4157
|
+
})
|
|
4158
|
+
})
|
|
4159
|
+
|
|
4160
|
+
route('GET', `${contractPath}/health`, (req, res) => {
|
|
4161
|
+
// M5 回流端点:无 Bearer 的只读健康信息({ ok, role, version, peer, accepted } 为房主约定字段)。
|
|
4162
|
+
let relayStatus = null
|
|
4163
|
+
try { relayStatus = relayStore.status() } catch { relayStatus = null }
|
|
4164
|
+
return json(res, 200, {
|
|
4165
|
+
ok: true,
|
|
4166
|
+
role: gate.role,
|
|
4167
|
+
version: CONTRACT_VERSION,
|
|
4168
|
+
contractVersion: CONTRACT_VERSION,
|
|
4169
|
+
peer: relayStatus?.peer ?? null,
|
|
4170
|
+
accepted: Number(relayStatus?.accepted ?? 0),
|
|
4171
|
+
methods: contractServer.hello().methods,
|
|
4172
|
+
// v3.1.35:回流计数(排障用;只读状态,不暴露可写 store)
|
|
4173
|
+
relay: relayStatus ? {
|
|
4174
|
+
peer: relayStatus.peer ?? null, cursor: relayStatus.cursor ?? 0, accepted: relayStatus.accepted ?? 0,
|
|
4175
|
+
duplicates: relayStatus.duplicates ?? 0, rejected: relayStatus.rejected ?? 0, batches: relayStatus.batches ?? 0, lastAt: relayStatus.lastAt ?? null,
|
|
4176
|
+
} : null,
|
|
4177
|
+
})
|
|
4178
|
+
})
|
|
4179
|
+
}
|
|
4180
|
+
// 分身核心开关(P1):加速引擎只服务分身 Web;母体/元主始终原厂。
|
|
4181
|
+
// 持久化在 <dataDir>/fork-core.json,只影响新派生/重启的分身。
|
|
4182
|
+
const forkCoreView = () => {
|
|
4183
|
+
const f = safeGet(SERVICE.forker)
|
|
4184
|
+
const base = typeof f?.coreStatus === 'function'
|
|
4185
|
+
? f.coreStatus()
|
|
4186
|
+
: { installable: true, accelerated: { installed: false, version: null, error: 'forker-unavailable' }, forks: {} }
|
|
4187
|
+
const settings = forkCoreSettings()
|
|
4188
|
+
const installed = base?.accelerated?.installed === true
|
|
4189
|
+
const state = resolveForkCoreState(settings, { installed })
|
|
4190
|
+
return {
|
|
4191
|
+
ok: true,
|
|
4192
|
+
mode: state.mode,
|
|
4193
|
+
sessionMode: state.sessionMode,
|
|
4194
|
+
effectiveMode: state.effectiveMode,
|
|
4195
|
+
blocked: state.blocked,
|
|
4196
|
+
accelerated: base?.accelerated ?? { installed: false, version: null },
|
|
4197
|
+
forks: base?.forks ?? {},
|
|
4198
|
+
essence: 'stock',
|
|
4199
|
+
updatedAt: settings.updatedAt,
|
|
4200
|
+
updatedBy: settings.updatedBy,
|
|
4201
|
+
}
|
|
2936
4202
|
}
|
|
4203
|
+
// 同一路径不能 register 两次(webServer 以 path 为键,第二次会抛错并让后续路由静默丢失)。
|
|
4204
|
+
routeMethods(`${prefix}/api/fork-core`, {
|
|
4205
|
+
GET: (req, res) => json(res, 200, forkCoreView()),
|
|
4206
|
+
POST: async (req, res) => {
|
|
4207
|
+
const body = await readBody(req)
|
|
4208
|
+
if (body?.mode !== undefined && !['stock', 'accelerated'].includes(String(body.mode))) {
|
|
4209
|
+
return json(res, 400, { ok: false, error: 'invalid-fork-core-mode' })
|
|
4210
|
+
}
|
|
4211
|
+
if (body?.sessionMode !== undefined && !['new', 'copy', 'inherit'].includes(String(body.sessionMode))) {
|
|
4212
|
+
return json(res, 400, { ok: false, error: 'invalid-fork-session-mode' })
|
|
4213
|
+
}
|
|
4214
|
+
// 服务端同样 fail-closed:未安装加速核时拒绝切到加速档,且绝不写设置(不改档、不静默降级)。
|
|
4215
|
+
if (String(body?.mode ?? '') === 'accelerated') {
|
|
4216
|
+
const view = forkCoreView()
|
|
4217
|
+
if (view.accelerated?.installed !== true) {
|
|
4218
|
+
return json(res, 409, {
|
|
4219
|
+
ok: false,
|
|
4220
|
+
error: 'accelerated-cli-missing',
|
|
4221
|
+
unchanged: true,
|
|
4222
|
+
detail: '加速核未安装:设置未修改',
|
|
4223
|
+
accelerated: view.accelerated,
|
|
4224
|
+
searched: view.accelerated?.searched ?? [],
|
|
4225
|
+
})
|
|
4226
|
+
}
|
|
4227
|
+
}
|
|
4228
|
+
const written = writeForkCoreSettings(layout.dataDir, {
|
|
4229
|
+
...(body?.mode !== undefined ? { mode: String(body.mode) } : {}),
|
|
4230
|
+
...(body?.sessionMode !== undefined ? { sessionMode: String(body.sessionMode) } : {}),
|
|
4231
|
+
}, { by: String(body?.by ?? 'panel').slice(0, 120) })
|
|
4232
|
+
if (written.ok !== true) return json(res, 500, { ok: false, error: written.error ?? 'write-failed' })
|
|
4233
|
+
try { audit('fork-core-settings', { mode: written.settings.mode, sessionMode: written.settings.sessionMode }) } catch { /* audit optional */ }
|
|
4234
|
+
return json(res, 200, { ...forkCoreView(), changed: true })
|
|
4235
|
+
},
|
|
4236
|
+
})
|
|
2937
4237
|
// 重启守卫 / supervisor 契约(只读)。不触发重启;写操作仍只走审批 + 外部 supervisor。
|
|
2938
4238
|
route('GET', `${prefix}/api/restart`, (req, res) => {
|
|
2939
4239
|
const view = restartView()
|
|
@@ -2944,6 +4244,43 @@ export function apply(ctx, config) {
|
|
|
2944
4244
|
if (!guard || typeof guard.selfCheck !== 'function') return json(res, 503, { ok: false, error: 'restart-guard-unavailable' })
|
|
2945
4245
|
return json(res, 200, guard.selfCheck())
|
|
2946
4246
|
})
|
|
4247
|
+
// v3.3.6: red restart UI data. Read-only impact + execution state; no restart.
|
|
4248
|
+
route('GET', `${prefix}/api/restart/impact`, (req, res) => {
|
|
4249
|
+
const guard = safeGet(SERVICE.restart)
|
|
4250
|
+
if (!guard || typeof guard.impact !== 'function') return json(res, 503, { ok: false, error: 'restart-guard-unavailable' })
|
|
4251
|
+
try {
|
|
4252
|
+
const view = restartView()
|
|
4253
|
+
return json(res, 200, {
|
|
4254
|
+
ok: true,
|
|
4255
|
+
impact: guard.impact(),
|
|
4256
|
+
executionArmed: view.executionArmed === true,
|
|
4257
|
+
supervisorPresent: view.supervisorPresent === true,
|
|
4258
|
+
mode: view.mode ?? null,
|
|
4259
|
+
allowProcessRestart: view.allowProcessRestart === true,
|
|
4260
|
+
note: view.executionArmed === true
|
|
4261
|
+
? '已武装:二次确认后守卫会把执行权交给 supervisor 并退出 75。'
|
|
4262
|
+
: '未武装:二次确认只会记录红色审批,不会自动退出/重启宿主。',
|
|
4263
|
+
})
|
|
4264
|
+
} catch (error) {
|
|
4265
|
+
return json(res, 500, { ok: false, error: 'restart-impact-failed', detail: String(error?.message ?? error) })
|
|
4266
|
+
}
|
|
4267
|
+
})
|
|
4268
|
+
// v3.3.6: two-step human restart. Confirmation is enforced here and again
|
|
4269
|
+
// by service.requestMotherRestart; missing fields are rejected with 428.
|
|
4270
|
+
route('POST', `${prefix}/api/restart/request`, async (req, res) => {
|
|
4271
|
+
const body = await readBody(req)
|
|
4272
|
+
const confirmation = body?.confirmation && typeof body.confirmation === 'object' ? body.confirmation : null
|
|
4273
|
+
if (!confirmation || confirmation.forkChecked !== true || confirmation.finalConfirm !== true) {
|
|
4274
|
+
return json(res, 428, {
|
|
4275
|
+
ok: false,
|
|
4276
|
+
error: 'restart-confirmation-required',
|
|
4277
|
+
required: { forkChecked: true, finalConfirm: true },
|
|
4278
|
+
detail: '请先在分身确认影响,再进行第二次确认;缺失确认时不会创建重启请求。',
|
|
4279
|
+
})
|
|
4280
|
+
}
|
|
4281
|
+
const out = await service.requestMotherRestart(String(body?.reason ?? 'manual'), { confirmation })
|
|
4282
|
+
return json(res, out.ok === false ? 409 : 200, out)
|
|
4283
|
+
})
|
|
2947
4284
|
route('GET', `${prefix}/api/upgrade/status`, (req, res) => {
|
|
2948
4285
|
let mirror = null
|
|
2949
4286
|
let essences = []
|
|
@@ -3161,8 +4498,15 @@ export function apply(ctx, config) {
|
|
|
3161
4498
|
failed.push({ taskId: null, error: String(error?.message ?? error) })
|
|
3162
4499
|
}
|
|
3163
4500
|
|
|
3164
|
-
|
|
3165
|
-
|
|
4501
|
+
// v3.3.5: only live forks are aggregated. A dead/stopped fork is an
|
|
4502
|
+
// expected offline state, not an approval failure; keep it in `skipped`
|
|
4503
|
+
// so the panel can show it without marking the whole inbox degraded.
|
|
4504
|
+
const forkTasks = [...tasks.values()].filter((task) => task?.url)
|
|
4505
|
+
const liveForkTasks = forkTasks.filter((task) => isLiveForkForApprovals(task, taskView(task).status))
|
|
4506
|
+
const skipped = forkTasks
|
|
4507
|
+
.filter((task) => !liveForkTasks.includes(task))
|
|
4508
|
+
.map((task) => ({ taskId: task.taskId, status: taskView(task).status, reason: 'fork-offline' }))
|
|
4509
|
+
const forkResults = await Promise.all(liveForkTasks
|
|
3166
4510
|
.map(async (task) => {
|
|
3167
4511
|
if (task.adapter && task.adapter.ok === false) {
|
|
3168
4512
|
return { task, ok: false, error: task.adapter.error ?? 'adapter-unavailable' }
|
|
@@ -3200,7 +4544,31 @@ export function apply(ctx, config) {
|
|
|
3200
4544
|
}
|
|
3201
4545
|
}
|
|
3202
4546
|
items.sort((a, b) => (Number(a.deadlineAt) || Number.MAX_SAFE_INTEGER) - (Number(b.deadlineAt) || Number.MAX_SAFE_INTEGER))
|
|
3203
|
-
return json(res, 200, { ok: true, degraded: failed.length > 0, items, failed })
|
|
4547
|
+
return json(res, 200, { ok: true, degraded: failed.length > 0, items, failed, skipped })
|
|
4548
|
+
})
|
|
4549
|
+
|
|
4550
|
+
// v3.3.5: isolated approval drill. Runs the real approver request → decide →
|
|
4551
|
+
// snapshot → rollback path in a temp dataRoot; never touches production data.
|
|
4552
|
+
// This gives a live host a way to prove the approval chain executes.
|
|
4553
|
+
route('POST', `${prefix}/api/approvals/drill`, async (req, res) => {
|
|
4554
|
+
try {
|
|
4555
|
+
const out = await runApprovalDrill()
|
|
4556
|
+
const cleanup = cleanupApprovalDrill(out)
|
|
4557
|
+
return json(res, out.ok && cleanup ? 200 : 500, {
|
|
4558
|
+
ok: out.ok && cleanup,
|
|
4559
|
+
drill: {
|
|
4560
|
+
request: out.request ?? null,
|
|
4561
|
+
pendingBefore: out.pendingBefore ?? null,
|
|
4562
|
+
pendingAfter: out.pendingAfter ?? null,
|
|
4563
|
+
snapshot: out.snapshot ? { ok: out.snapshot.ok !== false, tag: out.snapshot.tag ?? null } : null,
|
|
4564
|
+
rollback: out.rollback ? { ok: out.rollback.ok === true, restored: out.restored === true } : null,
|
|
4565
|
+
cleanup,
|
|
4566
|
+
},
|
|
4567
|
+
error: out.error ?? null,
|
|
4568
|
+
})
|
|
4569
|
+
} catch (error) {
|
|
4570
|
+
return json(res, 500, { ok: false, error: 'approval-drill-failed', detail: String(error?.message ?? error) })
|
|
4571
|
+
}
|
|
3204
4572
|
})
|
|
3205
4573
|
|
|
3206
4574
|
// Decide one approval by source. The response is the real adapter/approver result;
|
|
@@ -3254,6 +4622,17 @@ export function apply(ctx, config) {
|
|
|
3254
4622
|
return json(res, 400, { ok: false, error: 'bad-source', allowed: ['mother', 'fork'] })
|
|
3255
4623
|
})
|
|
3256
4624
|
|
|
4625
|
+
route('POST', `${prefix}/api/deploy`, async (_req, res) => json(res, 409, {
|
|
4626
|
+
ok: false,
|
|
4627
|
+
error: 'host-running',
|
|
4628
|
+
detail: '宿主存活时禁止部署/热替换母体 profile;请先退出 DSH Desktop,使用 tools/release/deploy-profile.mjs。',
|
|
4629
|
+
}))
|
|
4630
|
+
route('GET', `${prefix}/api/deploy/guard`, async (_req, res) => json(res, 409, {
|
|
4631
|
+
ok: false,
|
|
4632
|
+
error: 'host-running',
|
|
4633
|
+
detail: '当前进程就是 DSH host;任何部署请求都必须由外部工具在 host 停止后执行。',
|
|
4634
|
+
pid: process.pid,
|
|
4635
|
+
}))
|
|
3257
4636
|
route('POST', `${prefix}/api/tasks/create`, async (req, res) => {
|
|
3258
4637
|
const body = await readBody(req)
|
|
3259
4638
|
try {
|
|
@@ -3268,12 +4647,26 @@ export function apply(ctx, config) {
|
|
|
3268
4647
|
const out = await service.getTaskStatus(query.get('taskId') ?? '')
|
|
3269
4648
|
return json(res, out.ok === false ? 404 : 200, out)
|
|
3270
4649
|
})
|
|
3271
|
-
// v3.
|
|
3272
|
-
route('GET', `${prefix}/api/tasks/open-url`, (req, res) => {
|
|
4650
|
+
// v3.7.4:GET 只读(不产生 stop/spawn 副作用),POST 才执行 sync-on-open。
|
|
4651
|
+
route('GET', `${prefix}/api/tasks/open-url`, async (req, res) => {
|
|
3273
4652
|
const query = new URL(String(req.url ?? '/'), 'http://x').searchParams
|
|
3274
4653
|
const taskId = String(query.get('taskId') ?? '').trim()
|
|
3275
|
-
|
|
3276
|
-
if (!
|
|
4654
|
+
if (!taskId) return json(res, 400, { ok: false, error: 'taskId-required' })
|
|
4655
|
+
if (!tasks.has(taskId)) return json(res, 404, { ok: false, error: 'unknown-task', taskId })
|
|
4656
|
+
const out = forker()?.openUrl?.(taskId) ?? null
|
|
4657
|
+
if (!out || out.ok !== true) return json(res, 404, { ok: false, error: out?.error ?? 'not-running', taskId })
|
|
4658
|
+
return json(res, 200, out)
|
|
4659
|
+
})
|
|
4660
|
+
route('POST', `${prefix}/api/tasks/open`, async (req, res) => {
|
|
4661
|
+
const body = await readBody(req)
|
|
4662
|
+
const taskId = String(body?.taskId ?? '').trim()
|
|
4663
|
+
if (!taskId) return json(res, 400, { ok: false, error: 'taskId-required' })
|
|
4664
|
+
if (!tasks.has(taskId)) return json(res, 404, { ok: false, error: 'unknown-task', taskId })
|
|
4665
|
+
const out = await service.syncTaskOnOpen(taskId)
|
|
4666
|
+
if (!out || out.ok !== true) {
|
|
4667
|
+
const status = out?.error === 'unknown-task' ? 404 : out?.error === 'not-running' ? 404 : 409
|
|
4668
|
+
return json(res, status, { ok: false, error: out?.error ?? 'not-running', ...out })
|
|
4669
|
+
}
|
|
3277
4670
|
return json(res, 200, out)
|
|
3278
4671
|
})
|
|
3279
4672
|
route('POST', `${prefix}/api/tasks/archive`, async (req, res) => {
|
|
@@ -3286,6 +4679,40 @@ export function apply(ctx, config) {
|
|
|
3286
4679
|
const out = await service.restoreTask(String(body?.taskId ?? ''))
|
|
3287
4680
|
return json(res, out.ok ? 200 : 409, out)
|
|
3288
4681
|
})
|
|
4682
|
+
// 2026-11-22:一键修复(停残留 → 清别名桩 → 重置配置 → 重新拉起;不删 home/会话)
|
|
4683
|
+
route('POST', `${prefix}/api/vault/export`, async (req, res) => {
|
|
4684
|
+
const body = await readBody(req)
|
|
4685
|
+
const taskId = String(body?.taskId ?? '').trim()
|
|
4686
|
+
if (!taskId) return json(res, 400, { ok: false, error: 'taskId-required' })
|
|
4687
|
+
if (!tasks.has(taskId)) return json(res, 404, { ok: false, error: 'unknown-task', taskId })
|
|
4688
|
+
const destDir = String(body?.destDir ?? '').trim()
|
|
4689
|
+
if (!destDir) return json(res, 400, { ok: false, error: 'dest-dir-required' })
|
|
4690
|
+
try {
|
|
4691
|
+
const out = await service.exportTask(taskId, destDir, body?.options ?? {})
|
|
4692
|
+
return json(res, out.ok ? 200 : 500, out)
|
|
4693
|
+
} catch (error) {
|
|
4694
|
+
return json(res, 500, { ok: false, error: 'export-failed', detail: String(error?.message ?? error) })
|
|
4695
|
+
}
|
|
4696
|
+
})
|
|
4697
|
+
route('POST', `${prefix}/api/vault/import`, async (req, res) => {
|
|
4698
|
+
const body = await readBody(req)
|
|
4699
|
+
const sourceDir = String(body?.sourceDir ?? '').trim()
|
|
4700
|
+
if (!sourceDir) return json(res, 400, { ok: false, error: 'source-dir-required' })
|
|
4701
|
+
try {
|
|
4702
|
+
const out = await service.importTask(sourceDir, body?.title)
|
|
4703
|
+
return json(res, out.ok ? 200 : 409, out)
|
|
4704
|
+
} catch (error) {
|
|
4705
|
+
return json(res, 409, { ok: false, error: 'import-failed', detail: String(error?.message ?? error) })
|
|
4706
|
+
}
|
|
4707
|
+
})
|
|
4708
|
+
route('POST', `${prefix}/api/tasks/repair`, async (req, res) => {
|
|
4709
|
+
const body = await readBody(req)
|
|
4710
|
+
const taskId = String(body?.taskId ?? '').trim()
|
|
4711
|
+
if (!taskId) return json(res, 400, { ok: false, error: 'taskId-required' })
|
|
4712
|
+
if (!tasks.has(taskId)) return json(res, 404, { ok: false, error: 'unknown-task', taskId })
|
|
4713
|
+
const out = await service.repairTask(taskId)
|
|
4714
|
+
return json(res, out.ok ? 200 : 409, out)
|
|
4715
|
+
})
|
|
3289
4716
|
// v3.0.9:强制单会话(运行中拒绝;停止/归档态把多余会话隔离到 quarantine-sessions/)
|
|
3290
4717
|
route('POST', `${prefix}/api/tasks/sessions/enforce`, async (req, res) => {
|
|
3291
4718
|
const body = await readBody(req)
|
|
@@ -3374,7 +4801,10 @@ export function apply(ctx, config) {
|
|
|
3374
4801
|
return json(res, 200, out)
|
|
3375
4802
|
})
|
|
3376
4803
|
// v2.11.0 母体镜像管理
|
|
3377
|
-
route('GET', `${prefix}/api/mirror/status`, (req, res) => {
|
|
4804
|
+
route('GET', `${prefix}/api/mirror/status`, async (req, res) => {
|
|
4805
|
+
// R13 修复:官方源版本是 async,先刷新缓存(RL 60s),getStatus 只读缓存,
|
|
4806
|
+
// 避免 "[object Promise]" 与未处理 rejection。
|
|
4807
|
+
try { await mirrorManager.refreshOfficialLatest?.({ maxAgeMs: 60_000 }) } catch { /* 官方源不可用不阻塞镜像状态 */ }
|
|
3378
4808
|
const payload = mirrorService.status()
|
|
3379
4809
|
const ifNoneMatch = req && req.headers ? req.headers['if-none-match'] : undefined
|
|
3380
4810
|
const out = buildMirrorStatusResponse(payload, ifNoneMatch)
|
|
@@ -3451,6 +4881,15 @@ export function apply(ctx, config) {
|
|
|
3451
4881
|
return json(res, 400, { ok: false, error: String(error?.message ?? error) })
|
|
3452
4882
|
}
|
|
3453
4883
|
})
|
|
4884
|
+
// v3.3.8:手动触发默认元主版本自愈(启动时也会异步触发)。
|
|
4885
|
+
route('POST', `${prefix}/api/essence/auto-refresh`, async (req, res) => {
|
|
4886
|
+
try {
|
|
4887
|
+
const result = await service.refreshDefaultEssence()
|
|
4888
|
+
return json(res, result?.ok === false ? 500 : 200, { ok: result?.ok !== false, result })
|
|
4889
|
+
} catch (error) {
|
|
4890
|
+
return json(res, 500, { ok: false, error: 'essence-auto-refresh-failed', detail: String(error?.message ?? error) })
|
|
4891
|
+
}
|
|
4892
|
+
})
|
|
3454
4893
|
// v3.0.9 母体 → 元主:从当前母体 profile 的可写层生成一个可配置元主。
|
|
3455
4894
|
route('POST', `${prefix}/api/essence/capture`, async (req, res) => {
|
|
3456
4895
|
const body = await readBody(req)
|
|
@@ -3683,6 +5122,7 @@ export function apply(ctx, config) {
|
|
|
3683
5122
|
// so a restart/crash can offer recovery. Nothing is auto-sent.
|
|
3684
5123
|
routeMethods(`${prefix}/api/composer/journal`, {
|
|
3685
5124
|
GET: (req, res) => {
|
|
5125
|
+
if (queueJournalGate(res)) return
|
|
3686
5126
|
const query = new URL(String(req.url ?? '/'), 'http://x').searchParams
|
|
3687
5127
|
const key = query.get('key') || ''
|
|
3688
5128
|
// list=1 is the recovery list: every saved session draft/queue, newest first.
|
|
@@ -3693,6 +5133,7 @@ export function apply(ctx, config) {
|
|
|
3693
5133
|
return json(res, 200, { ok: true, entry: composerJournal.get(key) })
|
|
3694
5134
|
},
|
|
3695
5135
|
POST: async (req, res) => {
|
|
5136
|
+
if (queueJournalGate(res)) return
|
|
3696
5137
|
const body = await readBody(req)
|
|
3697
5138
|
const key = String(body?.key ?? '')
|
|
3698
5139
|
if (!key) return json(res, 400, { ok: false, error: 'journal-key-required' })
|
|
@@ -3707,6 +5148,7 @@ export function apply(ctx, config) {
|
|
|
3707
5148
|
// v3.1.21:append-only 历史快照(主 journal 被覆盖时的兜底恢复源)。
|
|
3708
5149
|
routeMethods(`${prefix}/api/composer/journal/history`, {
|
|
3709
5150
|
GET: (req, res) => {
|
|
5151
|
+
if (queueJournalGate(res)) return
|
|
3710
5152
|
const query = new URL(String(req.url ?? '/'), 'http://x').searchParams
|
|
3711
5153
|
const limit = Math.max(1, Math.min(200, Number(query.get('limit') || 20)))
|
|
3712
5154
|
const sessionKey = String(query.get('sessionKey') || '')
|
|
@@ -3717,6 +5159,7 @@ export function apply(ctx, config) {
|
|
|
3717
5159
|
// Restore saved queue rows into the official Session inbox WITHOUT waking the
|
|
3718
5160
|
// agent. The queue journal is a recovery surface; it must not send messages.
|
|
3719
5161
|
route('POST', `${prefix}/api/composer/queue`, async (req, res) => {
|
|
5162
|
+
if (queueJournalGate(res)) return
|
|
3720
5163
|
const body = await readBody(req)
|
|
3721
5164
|
const sessionId = String(body?.sessionId ?? '').trim()
|
|
3722
5165
|
const items = Array.isArray(body?.items) ? body.items : []
|