@twinsearth/dsh-fang 3.1.0 → 3.1.3
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/client.js +1511 -1
- package/cordis.patch.yml +9 -0
- package/package.json +7 -3
- package/src/compose.mjs +4 -1
- package/src/kernel/paths.mjs +9 -1
- package/src/kernel/role.mjs +1 -0
- package/src/kernel/types.mjs +5 -1
- package/src/lib/ai-secret-store.mjs +202 -0
- package/src/lib/boot-guard.mjs +182 -0
- package/src/lib/business-producers.mjs +109 -0
- package/src/lib/compat.mjs +1 -1
- package/src/lib/composer-journal.mjs +8 -0
- package/src/lib/decision-events.mjs +129 -0
- package/src/lib/decision-ingest-client.mjs +41 -0
- package/src/lib/decision-outbox.mjs +129 -0
- package/src/lib/desktop-launch.mjs +138 -0
- package/src/lib/fork-supervision-settings.mjs +58 -0
- package/src/lib/mirror-official-source.mjs +93 -0
- package/src/lib/mirror.mjs +10 -3
- package/src/lib/producer-contract.mjs +162 -0
- package/src/lib/restart-contract.mjs +650 -0
- package/src/lib/rule-registry.mjs +69 -0
- package/src/lib/ssrf-guard.mjs +170 -0
- package/src/lib/umbrella.mjs +143 -18
- package/src/plugins/adapter.mjs +31 -2
- package/src/plugins/approver.mjs +423 -40
- package/src/plugins/decision-center.mjs +2255 -0
- package/src/plugins/forker.mjs +20 -1
- package/src/plugins/healer.mjs +53 -20
- package/src/plugins/imports.mjs +48 -0
- package/src/plugins/orchestrator.mjs +844 -46
- package/src/plugins/restart-guard.mjs +645 -52
- package/src/plugins/scorer.mjs +227 -15
- package/src/plugins/umbrella.mjs +18 -14
- package/tools/boot-guard.mjs +95 -0
- package/tools/decision-ingest.mjs +53 -0
- package/tools/desktop-launch.mjs +71 -0
- package/tools/fangctl.mjs +229 -1
|
@@ -14,7 +14,7 @@ import path from 'node:path'
|
|
|
14
14
|
import {
|
|
15
15
|
z, roleGate, resolveFangLayout, resolveProfileDir, resolveSessionsLayout,
|
|
16
16
|
SERVICE, AUDIT, TASK_STATUS, FORK_STATUS, FANG_VERSION, ADAPTER_OP,
|
|
17
|
-
exists, ensureDir, readJson, writeJsonAtomic, writeFileAtomic, sha256, removeTree, copyTree,
|
|
17
|
+
exists, ensureDir, readJson, writeJsonAtomic, writeFileAtomic, sha256, removeTree, copyTree, digestTree, makeJunction,
|
|
18
18
|
newId, iso, nowMs, bus, sleep, parseWebUrl, probeWebUrl,
|
|
19
19
|
invokeCommercial, commercialConfigSchemaDefaults,
|
|
20
20
|
} from '../kernel/index.mjs'
|
|
@@ -28,8 +28,12 @@ import { EssenceManager, OFFICIAL_ESSENCE_ID, VIP_QUOTAS } from '../lib/essence.
|
|
|
28
28
|
import { applyForkConfigLock, setProfileConfigReadonly } from '../lib/fork-config-lock.mjs'
|
|
29
29
|
import { DEFAULT_ESSENCE_NAME, planDefaultEssence } from '../lib/default-essence.mjs'
|
|
30
30
|
import { MirrorUpgradeCoordinator } from '../lib/upgrade-coordinator.mjs'
|
|
31
|
+
import { createBusinessProducers } from '../lib/business-producers.mjs'
|
|
32
|
+
import { createManifestOfficialSource } from '../lib/mirror-official-source.mjs'
|
|
33
|
+
import { readForkSupervisionSettings, writeForkSupervisionSettings } from '../lib/fork-supervision-settings.mjs'
|
|
31
34
|
import { DEFAULT_EXPECTED_ROUTE_COUNT, readCompatStatus, runCompatGate, writeCompatStatus } from '../lib/compat.mjs'
|
|
32
35
|
import { buildUpgradeStatus } from '../lib/upgrade-status.mjs'
|
|
36
|
+
import { openDecisionEventStream } from '../lib/decision-events.mjs'
|
|
33
37
|
import { authErrorBody, checkRequestAuth, loadAuthToken } from '../lib/http-auth.mjs'
|
|
34
38
|
import { buildEssenceActions, buildTaskActions } from '../lib/ui-actions.mjs'
|
|
35
39
|
import { BranchStore } from '../lib/branch-store.mjs'
|
|
@@ -37,12 +41,68 @@ import { ComposerJournal } from '../lib/composer-journal.mjs'
|
|
|
37
41
|
import { fileURLToPath } from 'node:url'
|
|
38
42
|
import zlib from 'node:zlib'
|
|
39
43
|
|
|
44
|
+
/**
|
|
45
|
+
* Commit a promoted directory by copy → digest → directory swap.
|
|
46
|
+
* The old target is only removed after the new tree has been verified and renamed in.
|
|
47
|
+
*/
|
|
48
|
+
export function atomicReplaceDir(sourceDir, targetDir) {
|
|
49
|
+
const suffix = newId('promote')
|
|
50
|
+
const tmp = `${targetDir}.tmp-${suffix}`
|
|
51
|
+
const old = `${targetDir}.old-${suffix}`
|
|
52
|
+
const digestOf = (dir) => {
|
|
53
|
+
const tree = digestTree(dir)
|
|
54
|
+
const keys = Object.keys(tree).sort()
|
|
55
|
+
return sha256(keys.map((key) => `${key}\u0000${tree[key]}`).join('\n'))
|
|
56
|
+
}
|
|
57
|
+
try {
|
|
58
|
+
removeTree(tmp)
|
|
59
|
+
removeTree(old)
|
|
60
|
+
copyTree(sourceDir, tmp)
|
|
61
|
+
const digest = digestOf(tmp)
|
|
62
|
+
if (digest !== digestOf(sourceDir)) throw new Error('promote-digest-mismatch')
|
|
63
|
+
const hadOld = exists(targetDir)
|
|
64
|
+
if (hadOld) fs.renameSync(targetDir, old)
|
|
65
|
+
try {
|
|
66
|
+
fs.renameSync(tmp, targetDir)
|
|
67
|
+
} catch (error) {
|
|
68
|
+
if (hadOld && !exists(targetDir)) {
|
|
69
|
+
try { fs.renameSync(old, targetDir) } catch { /* best effort restore */ }
|
|
70
|
+
}
|
|
71
|
+
throw error
|
|
72
|
+
}
|
|
73
|
+
if (hadOld) removeTree(old)
|
|
74
|
+
return { digest }
|
|
75
|
+
} catch (error) {
|
|
76
|
+
removeTree(tmp)
|
|
77
|
+
if (exists(old) && !exists(targetDir)) {
|
|
78
|
+
try { fs.renameSync(old, targetDir) } catch { /* best effort restore */ }
|
|
79
|
+
}
|
|
80
|
+
throw error
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
const FORK_BUNDLE_NAMES = Object.freeze(['@twinsearth/dsh-fang', '@twinsearth/dsh-fang'])
|
|
86
|
+
|
|
87
|
+
/** 分身 profile 可解析的 fang bundle 路径(npm 安装名/开发 link 名都接受)。 */
|
|
88
|
+
function forkBundlePath(profileDir) {
|
|
89
|
+
for (const name of FORK_BUNDLE_NAMES) {
|
|
90
|
+
const candidate = path.join(String(profileDir ?? ''), 'node_modules', ...name.split('/'))
|
|
91
|
+
if (exists(candidate)) return candidate
|
|
92
|
+
}
|
|
93
|
+
return null
|
|
94
|
+
}
|
|
95
|
+
|
|
40
96
|
export const name = 'fang-orchestrator'
|
|
41
97
|
export const inject = []
|
|
42
98
|
|
|
43
99
|
export const Config = z.object({
|
|
44
100
|
role: z.union([z.const('mother'), z.const('fork')]).default('mother')
|
|
45
101
|
.description('配置层角色;环境 DSH_FANG_ROLE 优先(forker 派生的分身自动为 fork)'),
|
|
102
|
+
officialSourceUrl: z.string().default('')
|
|
103
|
+
.description('官方源 manifest 基础 URL(https;留空 = 无官方源,升级显式 official-source-unavailable)'),
|
|
104
|
+
officialSourceToken: z.string().default('')
|
|
105
|
+
.description('官方源 Bearer token(可选;不会写进日志/状态)'),
|
|
46
106
|
maxForks: z.number().min(1).max(64).default(8)
|
|
47
107
|
.description('同时存活的任务/分身上限'),
|
|
48
108
|
motherProfile: z.string().default('')
|
|
@@ -109,14 +169,28 @@ export function stripUrlToken(url) {
|
|
|
109
169
|
}
|
|
110
170
|
|
|
111
171
|
/** Find a runnable dsh launcher. `.cmd` wrappers are spawned through a shell by the forker. */
|
|
112
|
-
export function resolveCliPath(explicit = '', env = process.env) {
|
|
172
|
+
export function resolveCliPath(explicit = '', env = process.env, execPath = process.execPath) {
|
|
113
173
|
const candidates = []
|
|
114
174
|
if (explicit) candidates.push(explicit)
|
|
115
175
|
if (env.DSH_CLI) candidates.push(env.DSH_CLI)
|
|
176
|
+
if (env.DSH_INSTALL_DIR) candidates.push(path.join(env.DSH_INSTALL_DIR, 'resources', 'runtime', 'cli', 'bin', 'dsh.cmd'))
|
|
116
177
|
for (const dir of String(env.PATH ?? env.Path ?? '').split(path.delimiter)) {
|
|
117
178
|
if (!dir) continue
|
|
118
179
|
candidates.push(path.join(dir, 'dsh.cmd'), path.join(dir, 'dsh.exe'), path.join(dir, 'dsh'))
|
|
119
180
|
}
|
|
181
|
+
// 新版桌面安装目录不一定叫 E:\DS;从当前宿主可执行文件反推安装根目录:
|
|
182
|
+
// <install>\DeepSeek Harness.exe -> <install>\resources\runtime\cli\bin\dsh.cmd
|
|
183
|
+
// 同时向上探测 4 层,兼容 node.exe 等位于 runtime/ 下的启动器。
|
|
184
|
+
try {
|
|
185
|
+
let dir = path.dirname(String(execPath ?? ''))
|
|
186
|
+
for (let i = 0; i < 5 && dir; i += 1) {
|
|
187
|
+
candidates.push(path.join(dir, 'resources', 'runtime', 'cli', 'bin', 'dsh.cmd'))
|
|
188
|
+
candidates.push(path.join(dir, 'runtime', 'cli', 'bin', 'dsh.cmd'))
|
|
189
|
+
const parent = path.dirname(dir)
|
|
190
|
+
if (parent === dir) break
|
|
191
|
+
dir = parent
|
|
192
|
+
}
|
|
193
|
+
} catch { /* keep legacy candidates */ }
|
|
120
194
|
candidates.push(
|
|
121
195
|
'E:\\DS\\resources\\runtime\\cli\\bin\\dsh.cmd',
|
|
122
196
|
'C:\\Program Files\\DeepSeek Harness\\resources\\runtime\\cli\\bin\\dsh.cmd',
|
|
@@ -183,6 +257,35 @@ export function apply(ctx, config) {
|
|
|
183
257
|
}
|
|
184
258
|
|
|
185
259
|
const safeGet = (key) => { try { return ctx.get(key) } catch { return undefined } }
|
|
260
|
+
/**
|
|
261
|
+
* 宿主内部生产者 → 决策中心(best-effort,绝不改变原流程结果)。
|
|
262
|
+
* 用于 MirrorUpgrade / EssenceManager 这类仓内对象;外部系统(PM/PJM/Worker/
|
|
263
|
+
* HarnessMM/PluginUpdater/SuperAgent)走 POST /fang/api/decisions/ingest 桥。
|
|
264
|
+
*/
|
|
265
|
+
const raiseDecisionTicket = (spec = {}) => { try {
|
|
266
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
267
|
+
if (!center || typeof center.submit !== 'function') return null
|
|
268
|
+
const submitted = center.submit({
|
|
269
|
+
level: spec.level ?? 'yellow',
|
|
270
|
+
title: spec.title,
|
|
271
|
+
context: spec.context,
|
|
272
|
+
options: spec.options,
|
|
273
|
+
actions: spec.actions,
|
|
274
|
+
timeoutMinutes: spec.timeoutMinutes ?? 1440,
|
|
275
|
+
dedupeKey: spec.dedupeKey,
|
|
276
|
+
source: {
|
|
277
|
+
sessionId: String(spec.sessionId ?? 'orchestrator'),
|
|
278
|
+
agentRole: spec.agentRole ?? 'system',
|
|
279
|
+
roleSource: 'host:orchestrator',
|
|
280
|
+
roleTrusted: true,
|
|
281
|
+
taskName: String(spec.sourceName ?? spec.producer ?? 'orchestrator'),
|
|
282
|
+
},
|
|
283
|
+
metadata: spec.metadata,
|
|
284
|
+
})
|
|
285
|
+
return submitted?.ok ? submitted.ticket : null
|
|
286
|
+
} catch { return null }
|
|
287
|
+
}
|
|
288
|
+
const businessProducers = createBusinessProducers({ submit: (spec) => raiseDecisionTicket(spec) })
|
|
186
289
|
const audit = (kind, data) => {
|
|
187
290
|
try { safeGet(SERVICE.auditor)?.append(kind, data) } catch { /* auditor optional */ }
|
|
188
291
|
try { bus.emit('fang/audit', { kind, data }) } catch { /* ignore */ }
|
|
@@ -531,6 +634,47 @@ export function apply(ctx, config) {
|
|
|
531
634
|
} catch { return null }
|
|
532
635
|
}
|
|
533
636
|
|
|
637
|
+
/**
|
|
638
|
+
* 只读:重启守卫 + supervisor 契约状态。
|
|
639
|
+
* status() 只带摘要(Client Header 用),/fang/api/restart 带完整视图。
|
|
640
|
+
* 任何字段缺失都按「不可用/未知」返回,绝不伪造已武装或已执行。
|
|
641
|
+
*/
|
|
642
|
+
const restartView = () => {
|
|
643
|
+
const guard = safeGet(SERVICE.restart)
|
|
644
|
+
if (!guard) return { available: false }
|
|
645
|
+
try {
|
|
646
|
+
const state = typeof guard.state === 'function' ? guard.state() : null
|
|
647
|
+
const policy = typeof guard.policy === 'function' ? guard.policy() : null
|
|
648
|
+
const contract = typeof guard.executionContract === 'function' ? guard.executionContract() : null
|
|
649
|
+
const approvals = typeof guard.approvals === 'function' ? guard.approvals({ limit: 20 }) : null
|
|
650
|
+
return { available: true, state, policy, contract, approvals, decisionOnly: true, executed: false }
|
|
651
|
+
} catch (error) {
|
|
652
|
+
return { available: true, error: 'restart-guard-status-failed', detail: String(error?.message ?? error) }
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
const restartSummary = (view) => {
|
|
657
|
+
if (!view?.available) return { available: false }
|
|
658
|
+
if (view.error) return { available: true, error: view.error }
|
|
659
|
+
const s = view.state ?? {}
|
|
660
|
+
const p = view.policy ?? {}
|
|
661
|
+
return {
|
|
662
|
+
available: true,
|
|
663
|
+
state: s.state ?? null,
|
|
664
|
+
pending: s.pending ?? null,
|
|
665
|
+
mode: p.mode ?? s.mode ?? null,
|
|
666
|
+
authMode: p.authMode ?? s.authMode ?? null,
|
|
667
|
+
strictRedLine: p.strictRedLine ?? null,
|
|
668
|
+
redLineAutoAllowed: p.redLineAutoAllowed === true || s.redLineAutoAllowed === true,
|
|
669
|
+
allowProcessRestart: p.allowProcessRestart === true || s.allowProcessRestart === true,
|
|
670
|
+
tempEffectiveManual: p.tempEffectiveManual === true || s.tempEffectiveManual === true,
|
|
671
|
+
decisionOnly: true,
|
|
672
|
+
contractVersion: s.contractVersion ?? null,
|
|
673
|
+
manifestTtlMs: p.manifestTtlMs ?? s.manifestTtlMs ?? null,
|
|
674
|
+
approvals: view.approvals?.counts ?? null,
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
|
|
534
678
|
const service = {
|
|
535
679
|
role,
|
|
536
680
|
version: FANG_VERSION,
|
|
@@ -600,9 +744,17 @@ export function apply(ctx, config) {
|
|
|
600
744
|
homeDir,
|
|
601
745
|
profile,
|
|
602
746
|
profileTemplate,
|
|
603
|
-
// 从原身派生:配置必须真的来自原身 merged(不能被 clean template
|
|
604
|
-
// node_modules
|
|
605
|
-
|
|
747
|
+
// 从原身派生:配置必须真的来自原身 merged(不能被 clean template 覆盖)。
|
|
748
|
+
// node_modules:优先元主自己的模块树;默认元宝/新建原身可能尚未物化 node_modules,
|
|
749
|
+
// 此时回退母体模块树,保证分身仍能解析 @twinsearth/dsh-fang(否则是僵尸分身)。
|
|
750
|
+
...(sourceEssence ? {
|
|
751
|
+
cleanTemplate: false,
|
|
752
|
+
nodeModulesSource: (() => {
|
|
753
|
+
const essenceModules = path.join(profileTemplate, 'node_modules')
|
|
754
|
+
if (exists(essenceModules)) return essenceModules
|
|
755
|
+
return path.join(templateDir(), 'node_modules')
|
|
756
|
+
})(),
|
|
757
|
+
} : {}),
|
|
606
758
|
})
|
|
607
759
|
if (provisioned && provisioned.ok === false) {
|
|
608
760
|
task.status = TASK_STATUS.FAILED
|
|
@@ -613,9 +765,10 @@ export function apply(ctx, config) {
|
|
|
613
765
|
|
|
614
766
|
// 防御:分身的 profile 必须能解析本 bundle;否则派生出来的是一个"没有 /fang 路由"的
|
|
615
767
|
// 僵尸分身(adapter 握手会得到 http-404)。发现即回收并如实报错。
|
|
768
|
+
// npm 安装名是 @twinsearth/dsh-fang;开发 link 才是 @twinsearth/dsh-fang。两者都算可用。
|
|
616
769
|
const forkProfileDir = path.join(homeDir, 'profiles', profile)
|
|
617
|
-
const forkBundle =
|
|
618
|
-
if (!
|
|
770
|
+
const forkBundle = forkBundlePath(forkProfileDir)
|
|
771
|
+
if (!forkBundle) {
|
|
619
772
|
task.status = TASK_STATUS.FAILED
|
|
620
773
|
tasks.delete(taskId)
|
|
621
774
|
persist()
|
|
@@ -789,6 +942,44 @@ export function apply(ctx, config) {
|
|
|
789
942
|
return service.listTasks()
|
|
790
943
|
},
|
|
791
944
|
|
|
945
|
+
/** 分身看护开关:持久化设置 + forker 运行时 supervise 状态。 */
|
|
946
|
+
forkSupervision() {
|
|
947
|
+
const persisted = readForkSupervisionSettings(layout.dataDir)
|
|
948
|
+
const f = forker()
|
|
949
|
+
const live = f && typeof f.getSupervision === 'function' ? f.getSupervision() : null
|
|
950
|
+
return {
|
|
951
|
+
ok: true,
|
|
952
|
+
persisted: {
|
|
953
|
+
autostartForks: persisted.autostartForks,
|
|
954
|
+
supervise: persisted.supervise,
|
|
955
|
+
updatedAt: persisted.updatedAt,
|
|
956
|
+
exists: persisted.exists,
|
|
957
|
+
},
|
|
958
|
+
effective: {
|
|
959
|
+
autostartForks: persisted.autostartForks,
|
|
960
|
+
supervise: live ? live.enabled : persisted.supervise,
|
|
961
|
+
},
|
|
962
|
+
forker: live,
|
|
963
|
+
}
|
|
964
|
+
},
|
|
965
|
+
|
|
966
|
+
/** 更新看护开关;supervise 会立即应用到 forker,无需重启宿主。 */
|
|
967
|
+
setForkSupervision(input = {}) {
|
|
968
|
+
const patch = {}
|
|
969
|
+
if (typeof input?.autostartForks === 'boolean') patch.autostartForks = input.autostartForks
|
|
970
|
+
if (typeof input?.supervise === 'boolean') patch.supervise = input.supervise
|
|
971
|
+
if (!Object.keys(patch).length) return { ok: false, error: 'no-settings' }
|
|
972
|
+
const written = writeForkSupervisionSettings(layout.dataDir, patch)
|
|
973
|
+
if (!written.ok) return written
|
|
974
|
+
let applied = null
|
|
975
|
+
if (patch.supervise !== undefined) {
|
|
976
|
+
const f = forker()
|
|
977
|
+
if (f && typeof f.setSupervise === 'function') applied = f.setSupervise(patch.supervise)
|
|
978
|
+
}
|
|
979
|
+
try { audit(AUDIT.FORK_SUPERVISION, { ...patch, applied: applied?.enabled ?? null }) } catch { /* audit optional */ }
|
|
980
|
+
return { ...service.forkSupervision(), applied }
|
|
981
|
+
},
|
|
982
|
+
|
|
792
983
|
async getTaskStatus(taskId) {
|
|
793
984
|
const task = tasks.get(String(taskId ?? ''))
|
|
794
985
|
if (!task) return { ok: false, error: 'unknown-task' }
|
|
@@ -861,22 +1052,25 @@ export function apply(ctx, config) {
|
|
|
861
1052
|
// Materialize the fetched source into a mother-side work dir, then re-score with
|
|
862
1053
|
// the MOTHER threshold policy (母体更严格,且这是真正写进生产的判定).
|
|
863
1054
|
const workDir = path.join(layout.dataDir, 'work', `${id}-${plugin}`)
|
|
1055
|
+
const discardWorkDir = () => { try { removeTree(workDir) } catch { /* best effort */ } }
|
|
864
1056
|
try {
|
|
865
1057
|
removeTree(workDir)
|
|
866
1058
|
ensureDir(workDir)
|
|
867
1059
|
for (const [rel, content] of Object.entries(files)) {
|
|
868
1060
|
const target = resolveInside(workDir, rel)
|
|
869
|
-
if (!target) return { ok: false, error: 'unsafe-plugin-path', detail: rel }
|
|
1061
|
+
if (!target) { discardWorkDir(); return { ok: false, error: 'unsafe-plugin-path', detail: rel } }
|
|
870
1062
|
writeFileAtomic(target, String(content))
|
|
871
1063
|
}
|
|
872
1064
|
} catch (e) {
|
|
1065
|
+
discardWorkDir()
|
|
873
1066
|
return { ok: false, error: 'materialize-failed', detail: String(e?.message ?? e) }
|
|
874
1067
|
}
|
|
875
1068
|
|
|
876
1069
|
const scorer = safeGet(SERVICE.scorer)
|
|
877
|
-
const motherAssessment = scorer?.scoreDir ? scorer.scoreDir(workDir, null, { environment: 'mother' }) : null
|
|
878
|
-
if (!motherAssessment) return { ok: false, error: 'scorer-unavailable' }
|
|
1070
|
+
const motherAssessment = scorer?.scoreDir ? scorer.scoreDir(workDir, null, { environment: 'mother', deep: true }) : null
|
|
1071
|
+
if (!motherAssessment) { discardWorkDir(); return { ok: false, error: 'scorer-unavailable' } }
|
|
879
1072
|
if (motherAssessment.grade === 'D' || motherAssessment.grade === 'E') {
|
|
1073
|
+
discardWorkDir()
|
|
880
1074
|
return { ok: false, error: 'grade-too-low', grade: motherAssessment.grade, score: motherAssessment.S }
|
|
881
1075
|
}
|
|
882
1076
|
|
|
@@ -889,11 +1083,12 @@ export function apply(ctx, config) {
|
|
|
889
1083
|
})
|
|
890
1084
|
: null
|
|
891
1085
|
if (route && route.route !== 'sandbox') {
|
|
1086
|
+
discardWorkDir()
|
|
892
1087
|
return { ok: false, error: 'route-refused', route: route.route, reason: route.reason }
|
|
893
1088
|
}
|
|
894
1089
|
|
|
895
1090
|
const approver = safeGet(SERVICE.approver)
|
|
896
|
-
if (!approver) return { ok: false, error: 'approver-unavailable' }
|
|
1091
|
+
if (!approver) { discardWorkDir(); return { ok: false, error: 'approver-unavailable' } }
|
|
897
1092
|
|
|
898
1093
|
// 团队权限钩子(无 provider 时放行并记录 basis)。
|
|
899
1094
|
let teamBasis = { commercial: false }
|
|
@@ -903,7 +1098,7 @@ export function apply(ctx, config) {
|
|
|
903
1098
|
method: 'check', args: [{ action: 'promote', group: plugin }],
|
|
904
1099
|
})
|
|
905
1100
|
teamBasis = { commercial: true, ...(check.ok ? check.value : { allowed: true, error: check.error }) }
|
|
906
|
-
if (teamBasis.allowed === false) return { ok: false, error: 'team-denied', basis: teamBasis }
|
|
1101
|
+
if (teamBasis.allowed === false) { discardWorkDir(); return { ok: false, error: 'team-denied', basis: teamBasis } }
|
|
907
1102
|
}
|
|
908
1103
|
|
|
909
1104
|
const decision = typeof approver.requestPromotion === 'function'
|
|
@@ -922,23 +1117,28 @@ export function apply(ctx, config) {
|
|
|
922
1117
|
})
|
|
923
1118
|
const outcome = decision?.outcome ?? 'timeout'
|
|
924
1119
|
audit(AUDIT.APPROVAL_DECIDED, { kind: 'promotion', taskId: id, pluginId: plugin, outcome })
|
|
925
|
-
if (outcome !== 'approved') return { ok: false, error: 'denied', outcome }
|
|
1120
|
+
if (outcome !== 'approved') { discardWorkDir(); return { ok: false, error: 'denied', outcome } }
|
|
926
1121
|
|
|
927
1122
|
const target = path.join(layout.dataDir, 'promoted', plugin)
|
|
928
1123
|
try {
|
|
929
1124
|
if (exists(target)) {
|
|
930
|
-
approver.snapshot?.({ tag: plugin, dir: target })
|
|
931
|
-
|
|
1125
|
+
const snap = await approver.snapshot?.({ tag: plugin, dir: target })
|
|
1126
|
+
if (!snap || snap.ok === false) {
|
|
1127
|
+
discardWorkDir()
|
|
1128
|
+
return { ok: false, error: 'snapshot-failed', detail: String(snap?.error ?? snap?.reason ?? 'snapshot unavailable') }
|
|
1129
|
+
}
|
|
932
1130
|
}
|
|
933
|
-
|
|
1131
|
+
const commit = atomicReplaceDir(workDir, target)
|
|
1132
|
+
discardWorkDir()
|
|
1133
|
+
audit(AUDIT.PROMOTE_COMMITTED, {
|
|
1134
|
+
taskId: id, pluginId: plugin, target, digest: commit.digest,
|
|
1135
|
+
forkGrade: forkAssessment?.grade ?? null, motherGrade: motherAssessment.grade,
|
|
1136
|
+
})
|
|
934
1137
|
} catch (e) {
|
|
1138
|
+
discardWorkDir()
|
|
935
1139
|
audit(AUDIT.PROMOTE_FAILED, { taskId: id, pluginId: plugin, error: String(e?.message ?? e) })
|
|
936
1140
|
return { ok: false, error: 'promote-failed', detail: String(e?.message ?? e) }
|
|
937
1141
|
}
|
|
938
|
-
audit(AUDIT.PROMOTE_COMMITTED, {
|
|
939
|
-
taskId: id, pluginId: plugin, target,
|
|
940
|
-
forkGrade: forkAssessment?.grade ?? null, motherGrade: motherAssessment.grade,
|
|
941
|
-
})
|
|
942
1142
|
|
|
943
1143
|
// 商用钩子:云备份(不阻塞、失败只记录)。
|
|
944
1144
|
let backup = { ok: false, error: 'not-configured' }
|
|
@@ -992,14 +1192,16 @@ export function apply(ctx, config) {
|
|
|
992
1192
|
const target = path.join(layout.dataDir, 'promoted', String(pluginId))
|
|
993
1193
|
try {
|
|
994
1194
|
if (exists(target)) {
|
|
995
|
-
approver.snapshot?.({ tag: String(pluginId), dir: target })
|
|
996
|
-
|
|
1195
|
+
const snap = await approver.snapshot?.({ tag: String(pluginId), dir: target })
|
|
1196
|
+
if (!snap || snap.ok === false) {
|
|
1197
|
+
return { ok: false, error: 'snapshot-failed', detail: String(snap?.error ?? snap?.reason ?? 'snapshot unavailable') }
|
|
1198
|
+
}
|
|
997
1199
|
}
|
|
998
|
-
|
|
1200
|
+
const commit = atomicReplaceDir(src, target)
|
|
1201
|
+
audit(AUDIT.PROMOTE_COMMITTED, { forkId, pluginId, target, digest: commit.digest })
|
|
999
1202
|
} catch (e) {
|
|
1000
1203
|
return { ok: false, error: 'promote-failed', detail: String(e?.message ?? e) }
|
|
1001
1204
|
}
|
|
1002
|
-
audit(AUDIT.PROMOTE_COMMITTED, { forkId, pluginId, target })
|
|
1003
1205
|
return { ok: true, outcome: 'approved', target, pluginId, assessment }
|
|
1004
1206
|
},
|
|
1005
1207
|
|
|
@@ -1224,8 +1426,8 @@ export function apply(ctx, config) {
|
|
|
1224
1426
|
return { ok: false, error: 'path-escape', taskId: id, detail: String(error?.message ?? error) }
|
|
1225
1427
|
}
|
|
1226
1428
|
const forkProfileDir = path.join(task.homeDir, 'profiles', task.profile)
|
|
1227
|
-
const forkBundle =
|
|
1228
|
-
if (!
|
|
1429
|
+
const forkBundle = forkBundlePath(forkProfileDir)
|
|
1430
|
+
if (!forkBundle) {
|
|
1229
1431
|
return { ok: false, error: 'fork-bundle-unavailable', taskId: id, detail: forkProfileDir }
|
|
1230
1432
|
}
|
|
1231
1433
|
const f = forker()
|
|
@@ -1269,6 +1471,90 @@ export function apply(ctx, config) {
|
|
|
1269
1471
|
return { ok: true, restored: true, taskId: id, title: task.title, url: task.url, port: task.port, adapter, configReset, sessionGuard }
|
|
1270
1472
|
},
|
|
1271
1473
|
|
|
1474
|
+
/**
|
|
1475
|
+
* watchdog 启动时的恢复入口:把「已登记但进程没在跑」的非归档任务重新 spawn。
|
|
1476
|
+
* 不创建新任务、不动归档任务;失败的任务不重试(避免崩溃循环),只如实报告。
|
|
1477
|
+
* @param {{taskIds?: string[]}} [input]
|
|
1478
|
+
*/
|
|
1479
|
+
async autostartForks(input = {}) {
|
|
1480
|
+
const f = forker()
|
|
1481
|
+
if (!f || typeof f.spawn !== 'function') {
|
|
1482
|
+
return { ok: false, error: 'forker-unavailable', started: [], failed: [], skipped: [] }
|
|
1483
|
+
}
|
|
1484
|
+
const wanted = Array.isArray(input?.taskIds) && input.taskIds.length
|
|
1485
|
+
? new Set(input.taskIds.map(String))
|
|
1486
|
+
: null
|
|
1487
|
+
const report = { ok: true, started: [], failed: [], skipped: [] }
|
|
1488
|
+
for (const task of tasks.values()) {
|
|
1489
|
+
const id = task.taskId
|
|
1490
|
+
if (wanted && !wanted.has(id)) continue
|
|
1491
|
+
if (task.status === TASK_STATUS.ARCHIVED) {
|
|
1492
|
+
report.skipped.push({ taskId: id, reason: 'archived' })
|
|
1493
|
+
continue
|
|
1494
|
+
}
|
|
1495
|
+
let live = null
|
|
1496
|
+
try { live = f.status?.(id) ?? null } catch { live = null }
|
|
1497
|
+
if (live?.running === true || live?.state === 'running') {
|
|
1498
|
+
report.skipped.push({ taskId: id, reason: 'already-running' })
|
|
1499
|
+
continue
|
|
1500
|
+
}
|
|
1501
|
+
if (!task.homeDir || !exists(task.homeDir) || !task.profile) {
|
|
1502
|
+
report.failed.push({ taskId: id, error: 'home-missing' })
|
|
1503
|
+
continue
|
|
1504
|
+
}
|
|
1505
|
+
try { assertInside(layout.forkHomesDir, task.homeDir, 'fork-home') } catch {
|
|
1506
|
+
report.failed.push({ taskId: id, error: 'path-escape' })
|
|
1507
|
+
continue
|
|
1508
|
+
}
|
|
1509
|
+
const forkBundle = forkBundlePath(path.join(task.homeDir, 'profiles', task.profile))
|
|
1510
|
+
if (!forkBundle) {
|
|
1511
|
+
report.failed.push({ taskId: id, error: 'fork-bundle-unavailable' })
|
|
1512
|
+
continue
|
|
1513
|
+
}
|
|
1514
|
+
task.status = TASK_STATUS.PROVISIONING
|
|
1515
|
+
persist()
|
|
1516
|
+
let started
|
|
1517
|
+
try {
|
|
1518
|
+
started = await f.spawn({
|
|
1519
|
+
forkId: id,
|
|
1520
|
+
homeDir: task.homeDir,
|
|
1521
|
+
profile: task.profile,
|
|
1522
|
+
cliPath: cliPath(),
|
|
1523
|
+
env: { DSH_FANG_ROLE: 'fork', DSH_FANG_TASK_ID: id, DSH_FANG_MOTHER: layout.dataDir },
|
|
1524
|
+
})
|
|
1525
|
+
} catch (error) {
|
|
1526
|
+
started = { ok: false, error: String(error?.message ?? error) }
|
|
1527
|
+
}
|
|
1528
|
+
if (!started || started.ok === false) {
|
|
1529
|
+
task.status = TASK_STATUS.FAILED
|
|
1530
|
+
persist()
|
|
1531
|
+
audit(AUDIT.FORK_CRASHED, { taskId: id, error: started?.error ?? 'spawn-failed', reason: 'autostart' })
|
|
1532
|
+
report.failed.push({ taskId: id, error: started?.error ?? 'spawn-failed' })
|
|
1533
|
+
continue
|
|
1534
|
+
}
|
|
1535
|
+
task.status = TASK_STATUS.RUNNING
|
|
1536
|
+
task.pid = started.pid ?? null
|
|
1537
|
+
task.port = started.port ?? null
|
|
1538
|
+
task.url = started.url ?? null
|
|
1539
|
+
task.token = started.token ?? extractTokenSafe(task.url)
|
|
1540
|
+
task.adapter = { ok: false, error: 'handshaking' }
|
|
1541
|
+
persist()
|
|
1542
|
+
audit(AUDIT.FORK_STARTED, { taskId: id, pid: task.pid, port: task.port, profile: task.profile, reason: 'autostart' })
|
|
1543
|
+
bus.emit('fang/fork-started', { taskId: id, forkId: id, pid: task.pid, port: task.port })
|
|
1544
|
+
report.started.push({ taskId: id, pid: task.pid, port: task.port })
|
|
1545
|
+
// 握手放到后台:watchdog 的启动请求不应该被 N 个分身的启动时间串行阻塞。
|
|
1546
|
+
void handshake(task).then((adapter) => {
|
|
1547
|
+
if (!adapter?.ok) return
|
|
1548
|
+
const current = tasks.get(id)
|
|
1549
|
+
if (!current || current.pid !== task.pid) return
|
|
1550
|
+
current.status = TASK_STATUS.READY
|
|
1551
|
+
current.adapter = adapter
|
|
1552
|
+
persist()
|
|
1553
|
+
}).catch(() => {})
|
|
1554
|
+
}
|
|
1555
|
+
return report
|
|
1556
|
+
},
|
|
1557
|
+
|
|
1272
1558
|
/** 永久删除存档:reap(杀进程 + 删 home + 删记录);forker 记录已丢时按 home 兜底清理。 */
|
|
1273
1559
|
async deleteArchivedTask(taskId) {
|
|
1274
1560
|
const id = String(taskId ?? '')
|
|
@@ -1362,6 +1648,8 @@ export function apply(ctx, config) {
|
|
|
1362
1648
|
commercial: !!safeGet(SERVICE.commercial),
|
|
1363
1649
|
sessionCatalog: !!safeGet(SERVICE.sessionCatalog),
|
|
1364
1650
|
},
|
|
1651
|
+
// 重启守卫摘要(只读):Client Header 用它显示 mode/红灯策略;无守卫时 available:false。
|
|
1652
|
+
restart: restartSummary(restartView()),
|
|
1365
1653
|
}
|
|
1366
1654
|
},
|
|
1367
1655
|
|
|
@@ -1377,11 +1665,21 @@ export function apply(ctx, config) {
|
|
|
1377
1665
|
scope: 'mother',
|
|
1378
1666
|
origin: 'fang:orchestrator',
|
|
1379
1667
|
})
|
|
1380
|
-
|
|
1668
|
+
// auto-allow is a successful policy decision, not a denial.
|
|
1669
|
+
const allowed = decision?.outcome === 'approved' || decision?.outcome === 'auto-allow'
|
|
1670
|
+
return { ok: allowed, ...decision }
|
|
1381
1671
|
},
|
|
1382
1672
|
}
|
|
1383
1673
|
|
|
1384
1674
|
ctx.effect(() => ctx.provide(SERVICE.orchestrator, service))
|
|
1675
|
+
// 启动时把持久化的 supervise 开关应用到已经挂载的 forker(插件顺序可能晚于本插件)。
|
|
1676
|
+
ctx.inject([SERVICE.forker], (child) => {
|
|
1677
|
+
try {
|
|
1678
|
+
const f = child?.get?.(SERVICE.forker) ?? child?.[SERVICE.forker] ?? child?.forker ?? null
|
|
1679
|
+
const stored = readForkSupervisionSettings(layout.dataDir)
|
|
1680
|
+
if (f && typeof f.setSupervise === 'function' && stored.supervise === true) f.setSupervise(true)
|
|
1681
|
+
} catch { /* forker optional */ }
|
|
1682
|
+
})
|
|
1385
1683
|
|
|
1386
1684
|
// ── v2.9.0 母体连接:只描述 + 只读探测,不持有连接状态 ──────────────────
|
|
1387
1685
|
const linkProfileDir = () => {
|
|
@@ -1414,7 +1712,14 @@ export function apply(ctx, config) {
|
|
|
1414
1712
|
// v3.0.3:客户端升级后的兼容性门禁(模块导入 + 路由契约;失败保持子插件关闭)
|
|
1415
1713
|
const compatRoot = fileURLToPath(new URL('../../', import.meta.url))
|
|
1416
1714
|
let compatWebServer = null
|
|
1715
|
+
const rawConfig = config && typeof config === 'object' ? config : {}
|
|
1417
1716
|
const runCompatCheck = async () => {
|
|
1717
|
+
if (typeof rawConfig.compatGate === 'function') {
|
|
1718
|
+
// 测试/嵌入注入点:不改变生产默认(bundle 配置无法携带函数)。
|
|
1719
|
+
const injected = await rawConfig.compatGate()
|
|
1720
|
+
writeCompatStatus(layout.dataDir, injected)
|
|
1721
|
+
return injected
|
|
1722
|
+
}
|
|
1418
1723
|
const status = await runCompatGate({
|
|
1419
1724
|
rootDir: compatRoot,
|
|
1420
1725
|
expectedRouteCount: DEFAULT_EXPECTED_ROUTE_COUNT,
|
|
@@ -1426,8 +1731,24 @@ export function apply(ctx, config) {
|
|
|
1426
1731
|
return status
|
|
1427
1732
|
}
|
|
1428
1733
|
let upgradeCoordinator = null
|
|
1734
|
+
// 官方源:rawConfig.officialSource 优先(测试/嵌入可注入对象);否则按 URL 构建 manifest adapter。
|
|
1735
|
+
let officialSource = rawConfig.officialSource ?? null
|
|
1736
|
+
if (officialSource === null && String(cfg.officialSourceUrl ?? '').trim()) {
|
|
1737
|
+
try {
|
|
1738
|
+
officialSource = createManifestOfficialSource({
|
|
1739
|
+
baseUrl: cfg.officialSourceUrl,
|
|
1740
|
+
token: cfg.officialSourceToken,
|
|
1741
|
+
headers: {},
|
|
1742
|
+
})
|
|
1743
|
+
} catch (error) {
|
|
1744
|
+
try { ctx.logger?.warn?.(`[mirror] official source disabled: ${String(error?.message ?? error)}`) } catch { /* ignore */ }
|
|
1745
|
+
officialSource = null
|
|
1746
|
+
}
|
|
1747
|
+
}
|
|
1429
1748
|
const mirrorManager = new MirrorManager({
|
|
1430
1749
|
mirrorRoot,
|
|
1750
|
+
// 测试/嵌入注入点:官方源与 compat gate 都可替换;生产 bundle 可配置 manifest URL。
|
|
1751
|
+
officialSource,
|
|
1431
1752
|
logger: ctx.logger ?? {},
|
|
1432
1753
|
usageProvider: () => ({
|
|
1433
1754
|
activeEssenceCount: 0,
|
|
@@ -1437,7 +1758,20 @@ export function apply(ctx, config) {
|
|
|
1437
1758
|
}),
|
|
1438
1759
|
compatGate: () => runCompatCheck(),
|
|
1439
1760
|
onCompatResult: (compat) => { writeCompatStatus(layout.dataDir, compat) },
|
|
1440
|
-
postUpgradeHook: () => {
|
|
1761
|
+
postUpgradeHook: () => {
|
|
1762
|
+
if (upgradeCoordinator === null) return
|
|
1763
|
+
// 升级成功 → 元主重算;失败必须让人看见(决策中心 ticket),不吞掉。
|
|
1764
|
+
Promise.resolve(upgradeCoordinator.onUpgradeSuccess()).catch((error) => {
|
|
1765
|
+
raiseDecisionTicket({
|
|
1766
|
+
level: 'yellow',
|
|
1767
|
+
title: '升级后元主重算失败',
|
|
1768
|
+
context: `镜像升级成功,但元主重算失败:${String(error?.message ?? error)}`,
|
|
1769
|
+
options: [{ value: 'retry', label: '重试重算' }, { value: 'ignore', label: '忽略' }],
|
|
1770
|
+
dedupeKey: 'mirror-upgrade:recompute-failed',
|
|
1771
|
+
sourceName: 'MirrorUpgrade',
|
|
1772
|
+
})
|
|
1773
|
+
})
|
|
1774
|
+
},
|
|
1441
1775
|
})
|
|
1442
1776
|
mirrorManager.ensureLayout()
|
|
1443
1777
|
const preferencesStore = new PreferencesStore({ mirrorRoot, logger: ctx.logger ?? {} })
|
|
@@ -1783,9 +2117,10 @@ export function apply(ctx, config) {
|
|
|
1783
2117
|
importEssence: (input = {}) => essenceManager.importBundle(input?.bundle ?? input, {
|
|
1784
2118
|
name: input?.name, tier: input?.tier, parentId: input?.parentId ?? null,
|
|
1785
2119
|
}),
|
|
1786
|
-
// v3.0
|
|
1787
|
-
// 隔离边界:DSH_HOME =
|
|
1788
|
-
//
|
|
2120
|
+
// v3.1.0 元主运行态:用元主 merged/profile 起一个**隔离 home** 的配置态实例。
|
|
2121
|
+
// 隔离边界:DSH_HOME = sessions/<essenceId>/home(自己的 sessions/storages),
|
|
2122
|
+
// node_modules 也属于元主自己(D: 盘),不再 junction 到母体 C: 盘模块树;
|
|
2123
|
+
// 分身才复用元主/母体的 node_modules junction。
|
|
1789
2124
|
startEssenceRuntime: async (essenceId, input = {}) => {
|
|
1790
2125
|
const id = String(essenceId ?? '').trim()
|
|
1791
2126
|
const meta = essenceManager.getMeta(id)
|
|
@@ -1801,15 +2136,46 @@ export function apply(ctx, config) {
|
|
|
1801
2136
|
if (!exists(merged)) throw new Error('merged-profile-missing')
|
|
1802
2137
|
assertInside(layout.essenceRoot, merged, 'essence-merged')
|
|
1803
2138
|
const motherModules = path.join(templateDir(), 'node_modules')
|
|
1804
|
-
const
|
|
1805
|
-
|
|
1806
|
-
|
|
2139
|
+
const essenceModules = path.join(merged, 'node_modules')
|
|
2140
|
+
// 元主自己的 node_modules:必须是 D: 盘真实目录,不能是到母体 C: 盘的 junction。
|
|
2141
|
+
// 旧布局/新建元主可能缺失;首次打开时从母体复制一份,之后各自独立升级。
|
|
2142
|
+
if (!exists(essenceModules)) {
|
|
2143
|
+
try {
|
|
2144
|
+
if (exists(motherModules)) copyTree(motherModules, essenceModules)
|
|
2145
|
+
else ensureDir(essenceModules)
|
|
2146
|
+
} catch (error) {
|
|
2147
|
+
throw new Error(`essence-node-modules-copy-failed: ${String(error?.message ?? error)}`)
|
|
2148
|
+
}
|
|
1807
2149
|
}
|
|
2150
|
+
// 复制来的模块树记录了母体 store;元主/运行态的 pnpm 必须显式用同一个 store,
|
|
2151
|
+
// 否则项目在 D: 盘、模块来自 C: store 时会报 ERR_PNPM_UNEXPECTED_STORE。
|
|
2152
|
+
const writeModuleStoreConfig = (profileDir) => {
|
|
2153
|
+
try {
|
|
2154
|
+
const modulesYaml = fs.readFileSync(path.join(essenceModules, '.modules.yaml'), 'utf8')
|
|
2155
|
+
const store = /^storeDir:\s*(.+)$/m.exec(modulesYaml)?.[1]?.trim()
|
|
2156
|
+
if (!store) return
|
|
2157
|
+
ensureDir(profileDir)
|
|
2158
|
+
const file = path.join(profileDir, '.npmrc')
|
|
2159
|
+
if (exists(file) && fs.readFileSync(file, 'utf8').includes('store-dir=')) return
|
|
2160
|
+
fs.writeFileSync(file, `store-dir=${store}\npackage-import-method=copy\n`, 'utf8')
|
|
2161
|
+
} catch { /* missing modules metadata is non-fatal */ }
|
|
2162
|
+
}
|
|
2163
|
+
writeModuleStoreConfig(merged)
|
|
1808
2164
|
const forkId = runtimeForkId(id)
|
|
1809
2165
|
// v3.0.9 三区:运行态 home 在 runtimeRoot 下(FANG_HOME 时是 sessions/<essenceId>/home),
|
|
1810
2166
|
// 原身文件夹只保留配置,项目/会话/任务文件不落原身目录。
|
|
1811
2167
|
const homeDir = runtimeHomeFor(id)
|
|
1812
2168
|
assertInside(layout.runtimeRoot, homeDir, 'runtime-home')
|
|
2169
|
+
// 运行态 profile 的 node_modules 必须重新指向该元主自己的模块树。
|
|
2170
|
+
// makeJunction 对已存在的链接不会替换,所以先安全移除旧 junction(不进入目标)。
|
|
2171
|
+
const runtimeProfileDir = path.join(homeDir, 'profiles', 'essence-runtime')
|
|
2172
|
+
const runtimeModules = path.join(runtimeProfileDir, 'node_modules')
|
|
2173
|
+
// 迁移/旧版本可能留下“指向不存在 merged/profile/node_modules”的 junction;
|
|
2174
|
+
// fs.existsSync 对 broken junction 返回 false,必须用 lstat 才能发现并清掉。
|
|
2175
|
+
try {
|
|
2176
|
+
const stat = fs.lstatSync(runtimeModules)
|
|
2177
|
+
if (stat.isSymbolicLink() || !exists(runtimeModules)) removeTree(runtimeModules)
|
|
2178
|
+
} catch { /* 不存在 */ }
|
|
1813
2179
|
const legacyHomes = [
|
|
1814
2180
|
path.join(layout.dataDir, 'runtime', forkId, 'home'),
|
|
1815
2181
|
path.join(essenceManager.essenceRoot(id), 'runtime', 'home'),
|
|
@@ -1826,9 +2192,21 @@ export function apply(ctx, config) {
|
|
|
1826
2192
|
// 元主运行态必须继承元主的插件/设置;clean template 只用于空白分身,
|
|
1827
2193
|
// 否则官方/用户元主打开后看不到本机插件列表(v3.0.10 实测)。
|
|
1828
2194
|
cleanTemplate: false,
|
|
1829
|
-
nodeModulesSource:
|
|
2195
|
+
nodeModulesSource: essenceModules,
|
|
1830
2196
|
})
|
|
1831
2197
|
if (!provisioned.ok) throw new Error(String(provisioned.error ?? 'runtime-provision-failed'))
|
|
2198
|
+
// provision 若看到旧 junction 可能不替换;这里以 essenceModules 为准做最后自愈。
|
|
2199
|
+
if (!exists(runtimeModules)) {
|
|
2200
|
+
try {
|
|
2201
|
+
const stat = fs.lstatSync(runtimeModules)
|
|
2202
|
+
if (stat.isSymbolicLink()) removeTree(runtimeModules)
|
|
2203
|
+
} catch { /* ignore */ }
|
|
2204
|
+
if (!exists(essenceModules)) throw new Error('runtime-node-modules-source-missing')
|
|
2205
|
+
try { makeJunction(essenceModules, runtimeModules) } catch (error) {
|
|
2206
|
+
throw new Error(`runtime-node-modules-junction-failed: ${String(error?.message ?? error)}`)
|
|
2207
|
+
}
|
|
2208
|
+
}
|
|
2209
|
+
writeModuleStoreConfig(runtimeProfileDir)
|
|
1832
2210
|
// 先导入选中的进行中会话,再拉起实例(实例启动时就能看到它们)。
|
|
1833
2211
|
const importedSessions = importSessionsInto(homeDir, input?.sessionIds)
|
|
1834
2212
|
// 注意:forker.spawn 需要显式 homeDir/profile(它不从 provision 记录里猜)。
|
|
@@ -1984,6 +2362,17 @@ export function apply(ctx, config) {
|
|
|
1984
2362
|
const essenceId = String(input?.essenceId ?? '').trim()
|
|
1985
2363
|
if (!essenceId) {
|
|
1986
2364
|
const out = await essenceManager.recomputeAll({ concurrency: Number(input?.concurrency) || 2 })
|
|
2365
|
+
// recomputeAll 返回的是 id 数组(recomputed/skipped/conflicted/failed),不是计数。
|
|
2366
|
+
const conflictedCount = Array.isArray(out?.conflicted) ? out.conflicted.length : (Number(out?.conflicted) || 0)
|
|
2367
|
+
const failedCount = Array.isArray(out?.failed) ? out.failed.length : (Number(out?.failed) || 0)
|
|
2368
|
+
// EssenceManager:批量重算出现冲突/失败时,必须变成人类可见的 ticket。
|
|
2369
|
+
if (conflictedCount > 0 || failedCount > 0) {
|
|
2370
|
+
const conflicts = Array.from({ length: conflictedCount }, () => ({ kind: 'recompute-conflict', severity: 'warning' }))
|
|
2371
|
+
await businessProducers.essenceConflict({
|
|
2372
|
+
essenceId: 'all', conflicts,
|
|
2373
|
+
severity: failedCount > 0 ? 'fatal' : 'warning',
|
|
2374
|
+
})
|
|
2375
|
+
}
|
|
1987
2376
|
return { ok: true, mode: 'all', ...out }
|
|
1988
2377
|
}
|
|
1989
2378
|
const meta = essenceManager.getMeta(essenceId)
|
|
@@ -2006,12 +2395,68 @@ export function apply(ctx, config) {
|
|
|
2006
2395
|
recomputeStatus: () => upgradeCoordinator.getRecomputeStatus(),
|
|
2007
2396
|
compatStatus: () => readCompatStatus(layout.dataDir),
|
|
2008
2397
|
runCompatCheck,
|
|
2009
|
-
upgrade: (input = {}) =>
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2398
|
+
upgrade: async (input = {}) => {
|
|
2399
|
+
const emitStage = (stage) => {
|
|
2400
|
+
try { bus.emit('fang/mirror-upgrade-stage', { stage, at: Date.now() }) } catch { /* ignore */ }
|
|
2401
|
+
try { audit('mirror-upgrade-stage', { stage }) } catch { /* ignore */ }
|
|
2402
|
+
}
|
|
2403
|
+
try {
|
|
2404
|
+
const out = await mirrorManager.upgrade({
|
|
2405
|
+
autoBackup: input?.autoBackup !== false,
|
|
2406
|
+
autoRollback: input?.autoRollback !== false,
|
|
2407
|
+
onProgress: emitStage,
|
|
2408
|
+
})
|
|
2409
|
+
if (out?.ok === false) {
|
|
2410
|
+
await businessProducers.mirrorUpgradeFailed({
|
|
2411
|
+
from: out.from, to: out.to,
|
|
2412
|
+
reason: String(out?.error ?? out?.reason ?? 'unknown'),
|
|
2413
|
+
})
|
|
2414
|
+
} else if (out?.reason === 'compat-gate-failed') {
|
|
2415
|
+
const findings = Array.isArray(out?.compat?.findings) ? out.compat.findings.length : 0
|
|
2416
|
+
raiseDecisionTicket({
|
|
2417
|
+
level: 'yellow',
|
|
2418
|
+
title: '镜像升级后兼容门禁未通过',
|
|
2419
|
+
context: `镜像已切到 ${String(out?.to ?? '新版本')},但 compat 门禁未通过(findings=${findings}),子插件保持关闭。`,
|
|
2420
|
+
options: [{ value: 'retry', label: '重试升级' }, { value: 'ignore', label: '暂不处理' }],
|
|
2421
|
+
dedupeKey: 'mirror-upgrade:compat-gate-failed',
|
|
2422
|
+
sourceName: 'MirrorUpgrade',
|
|
2423
|
+
})
|
|
2424
|
+
} else if (out?.ok === true && out?.to && out.from !== out.to && !out.reason) {
|
|
2425
|
+
// 升级成功:新镜像要重启宿主才完全生效 → 红色 restart ticket(动作 confirm_restart)。
|
|
2426
|
+
await businessProducers.mirrorUpgradeRestartRequired({ from: out.from, to: out.to })
|
|
2427
|
+
}
|
|
2428
|
+
return out
|
|
2429
|
+
} catch (error) {
|
|
2430
|
+
await businessProducers.mirrorUpgradeFailed({
|
|
2431
|
+
from: 'unknown', reason: String(error?.message ?? error), level: 'red',
|
|
2432
|
+
})
|
|
2433
|
+
throw error
|
|
2434
|
+
}
|
|
2435
|
+
},
|
|
2013
2436
|
}
|
|
2014
2437
|
ctx.effect(() => ctx.provide(SERVICE.mirror, mirrorService))
|
|
2438
|
+
|
|
2439
|
+
// 特殊动作执行钩子:confirm_restart 不再只落库,交给 restart-guard 的 request
|
|
2440
|
+
// (它自己的审批/三重门禁/外部 supervisor 仍然生效;决策中心只负责触发)。
|
|
2441
|
+
try {
|
|
2442
|
+
const decisionCenterService = safeGet(SERVICE.decisionCenter)
|
|
2443
|
+
if (decisionCenterService && typeof decisionCenterService.registerActionHandler === 'function') {
|
|
2444
|
+
const unregisterAction = decisionCenterService.registerActionHandler('confirm_restart', async ({ ticket, payload } = {}) => {
|
|
2445
|
+
const restart = safeGet(SERVICE.restart)
|
|
2446
|
+
if (!restart || typeof restart.request !== 'function') return { ok: false, reason: 'restart-unavailable' }
|
|
2447
|
+
const input = payload && typeof payload === 'object' ? payload : {}
|
|
2448
|
+
return restart.request({
|
|
2449
|
+
reason: input.reason ?? `decision:${ticket?.id ?? 'unknown'}`,
|
|
2450
|
+
risk: input.risk ?? 'yellow',
|
|
2451
|
+
scope: input.scope ?? 'mother',
|
|
2452
|
+
origin: 'decision-center',
|
|
2453
|
+
digests: Array.isArray(input.digests) ? input.digests : undefined,
|
|
2454
|
+
forcedApproval: input.forcedApproval === true,
|
|
2455
|
+
})
|
|
2456
|
+
})
|
|
2457
|
+
ctx.effect(() => () => { try { unregisterAction?.() } catch { /* ignore */ } })
|
|
2458
|
+
}
|
|
2459
|
+
} catch { /* decision center optional */ }
|
|
2015
2460
|
// 启动后自检一次;兼容状态默认 subPluginsEnabled=false,直到门禁通过
|
|
2016
2461
|
const compatBootTimer = setTimeout(() => { void runCompatCheck() }, 1500)
|
|
2017
2462
|
compatBootTimer.unref?.()
|
|
@@ -2232,6 +2677,16 @@ export function apply(ctx, config) {
|
|
|
2232
2677
|
})
|
|
2233
2678
|
|
|
2234
2679
|
route('GET', `${prefix}/api/status`, (req, res) => json(res, 200, service.status()))
|
|
2680
|
+
// 重启守卫 / supervisor 契约(只读)。不触发重启;写操作仍只走审批 + 外部 supervisor。
|
|
2681
|
+
route('GET', `${prefix}/api/restart`, (req, res) => {
|
|
2682
|
+
const view = restartView()
|
|
2683
|
+
return json(res, 200, { ok: view.available === true && !view.error, ...view })
|
|
2684
|
+
})
|
|
2685
|
+
route('GET', `${prefix}/api/restart/selfcheck`, (req, res) => {
|
|
2686
|
+
const guard = safeGet(SERVICE.restart)
|
|
2687
|
+
if (!guard || typeof guard.selfCheck !== 'function') return json(res, 503, { ok: false, error: 'restart-guard-unavailable' })
|
|
2688
|
+
return json(res, 200, guard.selfCheck())
|
|
2689
|
+
})
|
|
2235
2690
|
route('GET', `${prefix}/api/upgrade/status`, (req, res) => {
|
|
2236
2691
|
let mirror = null
|
|
2237
2692
|
let essences = []
|
|
@@ -2244,6 +2699,300 @@ export function apply(ctx, config) {
|
|
|
2244
2699
|
return json(res, 200, buildUpgradeStatus({ version: FANG_VERSION, mirror, essences, compat, tasks: { failed: failedTasks } }))
|
|
2245
2700
|
})
|
|
2246
2701
|
route('GET', `${prefix}/api/tasks`, (req, res) => json(res, 200, { ok: true, tasks: service.listTasks() }))
|
|
2702
|
+
|
|
2703
|
+
// Decision center (瓮城·决策中心): one inbox for human attention. The plugin
|
|
2704
|
+
// owns tickets; this route is only the authenticated read/write surface.
|
|
2705
|
+
route('GET', `${prefix}/api/decisions`, (req, res) => {
|
|
2706
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2707
|
+
if (!center || typeof center.list !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2708
|
+
const query = new URL(String(req.url ?? '/'), 'http://x').searchParams
|
|
2709
|
+
const out = center.list({
|
|
2710
|
+
includeArchived: query.get('includeArchived') === '1' || query.get('includeArchived') === 'true',
|
|
2711
|
+
since: Number(query.get('since')) || 0,
|
|
2712
|
+
})
|
|
2713
|
+
return json(res, 200, { ok: true, ...out })
|
|
2714
|
+
})
|
|
2715
|
+
route('GET', `${prefix}/api/decisions/quota`, (req, res) => {
|
|
2716
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2717
|
+
if (!center || typeof center.quotaStatus !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2718
|
+
return json(res, 200, center.quotaStatus())
|
|
2719
|
+
})
|
|
2720
|
+
route('GET', `${prefix}/api/decisions/item`, (req, res) => {
|
|
2721
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2722
|
+
if (!center || typeof center.get !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2723
|
+
const query = new URL(String(req.url ?? '/'), 'http://x').searchParams
|
|
2724
|
+
const ticket = center.get(String(query.get('id') ?? ''))
|
|
2725
|
+
return ticket ? json(res, 200, { ok: true, ticket }) : json(res, 404, { ok: false, error: 'not-found' })
|
|
2726
|
+
})
|
|
2727
|
+
route('GET', `${prefix}/api/decisions/forks`, (req, res) => {
|
|
2728
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2729
|
+
if (!center || typeof center.forkAggregation !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2730
|
+
return json(res, 200, center.forkAggregation())
|
|
2731
|
+
})
|
|
2732
|
+
route('GET', `${prefix}/api/decisions/producers`, (req, res) => {
|
|
2733
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2734
|
+
if (!center || typeof center.producerCatalog !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2735
|
+
return json(res, 200, center.producerCatalog())
|
|
2736
|
+
})
|
|
2737
|
+
// 外部生产者桥(PM/PJM/Worker/HarnessMM/PluginUpdater/SuperAgent):
|
|
2738
|
+
// 只做带鉴权的 ingest;ticket 来源标记 external:<producer>,roleTrusted=false。
|
|
2739
|
+
route('POST', `${prefix}/api/decisions/ingest`, async (req, res) => {
|
|
2740
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2741
|
+
if (!center || typeof center.ingest !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2742
|
+
const body = await readBody(req)
|
|
2743
|
+
const out = center.ingest(body && typeof body === 'object' ? body : {})
|
|
2744
|
+
const status = out.ok ? 200
|
|
2745
|
+
: out.reason === 'title-required' || out.reason === 'options-required' || out.reason === 'gray-is-terminal' ? 400
|
|
2746
|
+
: 409
|
|
2747
|
+
return json(res, status, out)
|
|
2748
|
+
})
|
|
2749
|
+
// 决策中心实时推送:SSE。bus 事件 → 一条已鉴权流;无 SSE 时客户端仍可轮询。
|
|
2750
|
+
const decisionStreams = new Set()
|
|
2751
|
+
route('GET', `${prefix}/api/decisions/events`, (req, res) => {
|
|
2752
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2753
|
+
if (!center || typeof center.list !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2754
|
+
if (decisionStreams.size >= 20) return json(res, 429, { ok: false, error: 'too-many-event-streams' })
|
|
2755
|
+
const stream = openDecisionEventStream({ req, res, bus, center })
|
|
2756
|
+
decisionStreams.add(stream)
|
|
2757
|
+
const cleanup = () => {
|
|
2758
|
+
if (!decisionStreams.delete(stream)) return
|
|
2759
|
+
try { stream.close() } catch { /* ignore */ }
|
|
2760
|
+
}
|
|
2761
|
+
try { req.on?.('close', cleanup) } catch { /* ignore */ }
|
|
2762
|
+
try { res.on?.('close', cleanup) } catch { /* ignore */ }
|
|
2763
|
+
return undefined
|
|
2764
|
+
})
|
|
2765
|
+
try { child.effect?.(() => () => { for (const stream of decisionStreams) { try { stream.close() } catch { /* ignore */ } } decisionStreams.clear() }) } catch { /* fake webServer in tests */ }
|
|
2766
|
+
route('POST', `${prefix}/api/decisions/resolve`, async (req, res) => {
|
|
2767
|
+
const body = await readBody(req)
|
|
2768
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2769
|
+
if (!center || typeof center.resolve !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2770
|
+
if (Array.isArray(body?.ids)) {
|
|
2771
|
+
if (typeof center.resolveMany !== 'function') return json(res, 503, { ok: false, error: 'decision-center-batch-unavailable' })
|
|
2772
|
+
const out = center.resolveMany(body.ids, { option: body?.option, by: body?.by ?? 'fang-api', note: body?.note })
|
|
2773
|
+
return json(res, 200, out)
|
|
2774
|
+
}
|
|
2775
|
+
const out = (body?.actionId !== undefined && typeof center.resolveAction === 'function')
|
|
2776
|
+
? center.resolveAction(body?.id, body.actionId, body?.payload, { by: body?.by ?? 'fang-api', note: body?.note })
|
|
2777
|
+
: center.resolve(body?.id, body?.option, { by: body?.by ?? 'fang-api', note: body?.note })
|
|
2778
|
+
const status = out.ok ? 200
|
|
2779
|
+
: out.reason === 'not-found' ? 404
|
|
2780
|
+
: out.reason === 'option-required' || out.reason === 'unknown-option' ? 400
|
|
2781
|
+
: 409
|
|
2782
|
+
return json(res, status, out)
|
|
2783
|
+
})
|
|
2784
|
+
route('POST', `${prefix}/api/decisions/abandon`, async (req, res) => {
|
|
2785
|
+
const body = await readBody(req)
|
|
2786
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2787
|
+
if (!center || typeof center.abandon !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2788
|
+
if (Array.isArray(body?.ids)) {
|
|
2789
|
+
if (typeof center.abandonMany !== 'function') return json(res, 503, { ok: false, error: 'decision-center-batch-unavailable' })
|
|
2790
|
+
const out = center.abandonMany(body.ids, { by: body?.by ?? 'fang-api', note: body?.note })
|
|
2791
|
+
return json(res, 200, out)
|
|
2792
|
+
}
|
|
2793
|
+
const out = center.abandon(body?.id, { by: body?.by ?? 'fang-api', note: body?.note })
|
|
2794
|
+
return json(res, out.ok ? 200 : (out.reason === 'not-found' ? 404 : 409), out)
|
|
2795
|
+
})
|
|
2796
|
+
|
|
2797
|
+
route('GET', `${prefix}/api/decisions/ai`, (req, res) => {
|
|
2798
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2799
|
+
if (!center || typeof center.aiStatus !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2800
|
+
return json(res, 200, { ok: true, ...center.aiStatus() })
|
|
2801
|
+
})
|
|
2802
|
+
route('POST', `${prefix}/api/decisions/ai/test`, async (req, res) => {
|
|
2803
|
+
const body = await readBody(req)
|
|
2804
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2805
|
+
if (!center || typeof center.testAi !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2806
|
+
const out = await center.testAi(body ?? {})
|
|
2807
|
+
return json(res, out.ok ? 200 : (out.status === 429 ? 429 : 400), out)
|
|
2808
|
+
})
|
|
2809
|
+
route('POST', `${prefix}/api/decisions/ai/config`, async (req, res) => {
|
|
2810
|
+
const body = await readBody(req)
|
|
2811
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2812
|
+
if (!center || typeof center.configureAi !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2813
|
+
const out = center.configureAi(body ?? {})
|
|
2814
|
+
return json(res, out.ok ? 200 : 400, out)
|
|
2815
|
+
})
|
|
2816
|
+
route('POST', `${prefix}/api/decisions/ai/advise/stream`, async (req, res) => {
|
|
2817
|
+
const body = await readBody(req)
|
|
2818
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2819
|
+
if (!center || typeof center.advise !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2820
|
+
res.writeHead(200, {
|
|
2821
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
2822
|
+
'cache-control': 'no-store',
|
|
2823
|
+
'x-accel-buffering': 'no',
|
|
2824
|
+
connection: 'keep-alive',
|
|
2825
|
+
})
|
|
2826
|
+
try { res.flushHeaders?.() } catch { /* fake res */ }
|
|
2827
|
+
let closed = false
|
|
2828
|
+
let wrote = 0
|
|
2829
|
+
const send = (event, data) => {
|
|
2830
|
+
if (closed) return false
|
|
2831
|
+
try { res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); wrote += 1; return true } catch { return false }
|
|
2832
|
+
}
|
|
2833
|
+
try {
|
|
2834
|
+
send('start', { id: String(body?.id ?? '') })
|
|
2835
|
+
const out = typeof center.adviseStream === 'function'
|
|
2836
|
+
? await center.adviseStream(body?.id, (delta, text) => { send('delta', { delta, text }) })
|
|
2837
|
+
: await center.advise(body?.id)
|
|
2838
|
+
send(out.ok ? 'done' : 'error', out.ok ? { advice: out.advice, ticket: out.ticket } : out)
|
|
2839
|
+
} catch (error) {
|
|
2840
|
+
send('error', { ok: false, error: String(error?.message ?? error) })
|
|
2841
|
+
} finally {
|
|
2842
|
+
closed = true
|
|
2843
|
+
try { res.end() } catch { /* ignore */ }
|
|
2844
|
+
}
|
|
2845
|
+
})
|
|
2846
|
+
route('POST', `${prefix}/api/decisions/ai/advise`, async (req, res) => {
|
|
2847
|
+
const body = await readBody(req)
|
|
2848
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2849
|
+
if (!center || typeof center.advise !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2850
|
+
const out = await center.advise(body?.id)
|
|
2851
|
+
const limited = out?.reason === 'ai-rate-limited' || out?.reason === 'ai-circuit-open' || out?.reason === 'ai-daily-quota-exceeded'
|
|
2852
|
+
if (limited && Number.isFinite(out?.retryAfterMs) && out.retryAfterMs > 0) {
|
|
2853
|
+
try { res.setHeader?.('retry-after', String(Math.ceil(out.retryAfterMs / 1000))) } catch { /* fake res */ }
|
|
2854
|
+
}
|
|
2855
|
+
return json(res, out.ok ? 200 : (out.reason === 'not-found' ? 404 : limited ? 429 : 409), out)
|
|
2856
|
+
})
|
|
2857
|
+
|
|
2858
|
+
// Mother-side approval aggregation: local approver + every live fork adapter.
|
|
2859
|
+
// A failed adapter is reported as degraded, never as an empty approval list.
|
|
2860
|
+
route('GET', `${prefix}/api/approvals`, async (req, res) => {
|
|
2861
|
+
const items = []
|
|
2862
|
+
const failed = []
|
|
2863
|
+
const approver = safeGet(SERVICE.approver)
|
|
2864
|
+
try {
|
|
2865
|
+
if (approver && typeof approver.pending === 'function') {
|
|
2866
|
+
for (const item of approver.pending() ?? []) {
|
|
2867
|
+
items.push({
|
|
2868
|
+
source: 'mother',
|
|
2869
|
+
taskId: null,
|
|
2870
|
+
approvalId: String(item?.id ?? ''),
|
|
2871
|
+
title: String(item?.title ?? ''),
|
|
2872
|
+
risk: String(item?.risk ?? 'unknown'),
|
|
2873
|
+
kind: String(item?.kind ?? 'unknown'),
|
|
2874
|
+
state: item?.state ?? 'pending',
|
|
2875
|
+
createdAt: item?.createdAt ?? null,
|
|
2876
|
+
deadlineAt: item?.deadlineAt ?? null,
|
|
2877
|
+
adapterOk: true,
|
|
2878
|
+
})
|
|
2879
|
+
}
|
|
2880
|
+
if (typeof approver.orphaned === 'function') {
|
|
2881
|
+
for (const item of approver.orphaned() ?? []) {
|
|
2882
|
+
items.push({
|
|
2883
|
+
source: 'mother',
|
|
2884
|
+
taskId: null,
|
|
2885
|
+
approvalId: String(item?.id ?? ''),
|
|
2886
|
+
title: String(item?.title ?? ''),
|
|
2887
|
+
risk: String(item?.risk ?? 'unknown'),
|
|
2888
|
+
kind: String(item?.kind ?? 'unknown'),
|
|
2889
|
+
state: 'orphaned',
|
|
2890
|
+
createdAt: item?.createdAt ?? null,
|
|
2891
|
+
deadlineAt: item?.deadlineAt ?? null,
|
|
2892
|
+
adapterOk: true,
|
|
2893
|
+
})
|
|
2894
|
+
}
|
|
2895
|
+
}
|
|
2896
|
+
} else {
|
|
2897
|
+
failed.push({ taskId: null, error: 'approver-unavailable' })
|
|
2898
|
+
}
|
|
2899
|
+
} catch (error) {
|
|
2900
|
+
failed.push({ taskId: null, error: String(error?.message ?? error) })
|
|
2901
|
+
}
|
|
2902
|
+
|
|
2903
|
+
const forkResults = await Promise.all([...tasks.values()]
|
|
2904
|
+
.filter((task) => task?.url)
|
|
2905
|
+
.map(async (task) => {
|
|
2906
|
+
if (task.adapter && task.adapter.ok === false) {
|
|
2907
|
+
return { task, ok: false, error: task.adapter.error ?? 'adapter-unavailable' }
|
|
2908
|
+
}
|
|
2909
|
+
const client = await remoteFor(task)
|
|
2910
|
+
if (!client) return { task, ok: false, error: 'remote-unavailable' }
|
|
2911
|
+
const result = await client.command(ADAPTER_OP.APPROVALS, {})
|
|
2912
|
+
const data = result?.data?.result ?? result?.data ?? {}
|
|
2913
|
+
if (!result?.ok || data?.ok === false) {
|
|
2914
|
+
return { task, ok: false, error: data?.error ?? result?.error ?? 'adapter-failed' }
|
|
2915
|
+
}
|
|
2916
|
+
const list = Array.isArray(data?.items) ? data.items
|
|
2917
|
+
: Array.isArray(data?.result?.items) ? data.result.items
|
|
2918
|
+
: []
|
|
2919
|
+
return { task, ok: true, items: list }
|
|
2920
|
+
}))
|
|
2921
|
+
for (const result of forkResults) {
|
|
2922
|
+
if (!result.ok) {
|
|
2923
|
+
failed.push({ taskId: result.task.taskId, error: result.error })
|
|
2924
|
+
continue
|
|
2925
|
+
}
|
|
2926
|
+
for (const item of result.items) {
|
|
2927
|
+
items.push({
|
|
2928
|
+
source: 'fork',
|
|
2929
|
+
taskId: result.task.taskId,
|
|
2930
|
+
approvalId: String(item?.id ?? item?.approvalId ?? ''),
|
|
2931
|
+
title: String(item?.title ?? ''),
|
|
2932
|
+
risk: String(item?.risk ?? 'unknown'),
|
|
2933
|
+
kind: String(item?.kind ?? 'unknown'),
|
|
2934
|
+
state: item?.state ?? 'pending',
|
|
2935
|
+
createdAt: item?.createdAt ?? null,
|
|
2936
|
+
deadlineAt: item?.deadlineAt ?? null,
|
|
2937
|
+
adapterOk: true,
|
|
2938
|
+
})
|
|
2939
|
+
}
|
|
2940
|
+
}
|
|
2941
|
+
items.sort((a, b) => (Number(a.deadlineAt) || Number.MAX_SAFE_INTEGER) - (Number(b.deadlineAt) || Number.MAX_SAFE_INTEGER))
|
|
2942
|
+
return json(res, 200, { ok: true, degraded: failed.length > 0, items, failed })
|
|
2943
|
+
})
|
|
2944
|
+
|
|
2945
|
+
// Decide one approval by source. The response is the real adapter/approver result;
|
|
2946
|
+
// stale or unknown approvals return 409 instead of pretending success.
|
|
2947
|
+
route('POST', `${prefix}/api/approvals/decide`, async (req, res) => {
|
|
2948
|
+
const body = await readBody(req)
|
|
2949
|
+
const source = String(body?.source ?? '')
|
|
2950
|
+
const taskId = body?.taskId === undefined || body?.taskId === null ? null : String(body.taskId)
|
|
2951
|
+
const approvalId = String(body?.approvalId ?? '').trim()
|
|
2952
|
+
const raw = body?.outcome ?? body?.decision
|
|
2953
|
+
const outcome = raw === 'approve' ? 'approved' : raw === 'deny' ? 'denied' : String(raw ?? '')
|
|
2954
|
+
const by = String(body?.by ?? 'fang-api')
|
|
2955
|
+
const note = body?.note === undefined || body?.note === null ? null : String(body.note)
|
|
2956
|
+
if (!approvalId) return json(res, 400, { ok: false, error: 'approval-id-required' })
|
|
2957
|
+
if (outcome !== 'approved' && outcome !== 'denied') return json(res, 400, { ok: false, error: 'bad-outcome', allowed: ['approved', 'denied'] })
|
|
2958
|
+
|
|
2959
|
+
if (source === 'mother') {
|
|
2960
|
+
const approver = safeGet(SERVICE.approver)
|
|
2961
|
+
if (!approver || typeof approver.decide !== 'function') {
|
|
2962
|
+
return json(res, 503, { ok: false, source, error: 'approver-unavailable' })
|
|
2963
|
+
}
|
|
2964
|
+
try {
|
|
2965
|
+
const result = approver.decide(approvalId, outcome, { by, note })
|
|
2966
|
+
if (!result || result.ok === false) {
|
|
2967
|
+
const stale = result?.reason === 'not-found' || result?.reason === 'not-pending'
|
|
2968
|
+
return json(res, stale ? 409 : 400, { ok: false, source, approvalId, error: result?.reason ?? 'decide-failed' })
|
|
2969
|
+
}
|
|
2970
|
+
audit(AUDIT.APPROVAL_DECIDED, { source, taskId: null, approvalId, outcome, by, note })
|
|
2971
|
+
return json(res, 200, { ok: true, source, taskId: null, approvalId, outcome, by, result })
|
|
2972
|
+
} catch (error) {
|
|
2973
|
+
return json(res, 500, { ok: false, source, approvalId, error: String(error?.message ?? error) })
|
|
2974
|
+
}
|
|
2975
|
+
}
|
|
2976
|
+
|
|
2977
|
+
if (source === 'fork') {
|
|
2978
|
+
if (!taskId) return json(res, 400, { ok: false, source, error: 'task-id-required' })
|
|
2979
|
+
const task = tasks.get(taskId)
|
|
2980
|
+
if (!task) return json(res, 404, { ok: false, source, taskId, error: 'unknown-task' })
|
|
2981
|
+
const client = await remoteFor(task)
|
|
2982
|
+
if (!client) return json(res, 503, { ok: false, source, taskId, error: 'remote-unavailable' })
|
|
2983
|
+
const result = await client.command(ADAPTER_OP.APPROVAL_DECIDE, { id: approvalId, outcome, by, note })
|
|
2984
|
+
const data = result?.data?.result ?? result?.data ?? {}
|
|
2985
|
+
if (!result?.ok || data?.ok === false) {
|
|
2986
|
+
const stale = data?.code === 'not-found' || data?.code === 'conflict'
|
|
2987
|
+
return json(res, stale ? 409 : 502, { ok: false, source, taskId, approvalId, error: data?.error ?? result?.error ?? 'adapter-failed' })
|
|
2988
|
+
}
|
|
2989
|
+
audit(AUDIT.APPROVAL_DECIDED, { source, taskId, approvalId, outcome, by, note })
|
|
2990
|
+
return json(res, 200, { ok: true, source, taskId, approvalId, outcome, by, result: data })
|
|
2991
|
+
}
|
|
2992
|
+
|
|
2993
|
+
return json(res, 400, { ok: false, error: 'bad-source', allowed: ['mother', 'fork'] })
|
|
2994
|
+
})
|
|
2995
|
+
|
|
2247
2996
|
route('POST', `${prefix}/api/tasks/create`, async (req, res) => {
|
|
2248
2997
|
const body = await readBody(req)
|
|
2249
2998
|
try {
|
|
@@ -2314,6 +3063,21 @@ export function apply(ctx, config) {
|
|
|
2314
3063
|
})
|
|
2315
3064
|
// v1 兼容路由
|
|
2316
3065
|
route('GET', `${prefix}/api/forks`, (req, res) => json(res, 200, { ok: true, forks: service.listForks() }))
|
|
3066
|
+
routeMethods(`${prefix}/api/forks/supervision`, {
|
|
3067
|
+
GET: (req, res) => json(res, 200, service.forkSupervision()),
|
|
3068
|
+
POST: async (req, res) => {
|
|
3069
|
+
const body = await readBody(req)
|
|
3070
|
+
const out = service.setForkSupervision(body ?? {})
|
|
3071
|
+
return json(res, out.ok ? 200 : 400, out)
|
|
3072
|
+
},
|
|
3073
|
+
})
|
|
3074
|
+
// watchdog 启动时的分身自动恢复;只拉起已登记但没在跑的非归档任务。
|
|
3075
|
+
route('POST', `${prefix}/api/forks/autostart`, async (req, res) => {
|
|
3076
|
+
const body = await readBody(req)
|
|
3077
|
+
const taskIds = Array.isArray(body?.taskIds) ? body.taskIds : null
|
|
3078
|
+
const out = await service.autostartForks({ taskIds })
|
|
3079
|
+
return json(res, out.ok ? 200 : 503, out)
|
|
3080
|
+
})
|
|
2317
3081
|
route('POST', `${prefix}/api/forks/create`, async (req, res) => {
|
|
2318
3082
|
const body = await readBody(req)
|
|
2319
3083
|
const out = await service.fork({ taskTitle: body?.taskTitle ?? body?.title })
|
|
@@ -2506,12 +3270,6 @@ export function apply(ctx, config) {
|
|
|
2506
3270
|
return json(res, 400, { ok: false, error: String(error?.message ?? error) })
|
|
2507
3271
|
}
|
|
2508
3272
|
})
|
|
2509
|
-
route('POST', `${prefix}/api/essence/default`, async (req, res) => {
|
|
2510
|
-
const body = await readBody(req)
|
|
2511
|
-
try { return json(res, 200, { ok: true, default: mirrorService.setDefaultEssence(String(body?.essenceId ?? '')) }) } catch (error) {
|
|
2512
|
-
return json(res, 400, { ok: false, error: String(error?.message ?? error) })
|
|
2513
|
-
}
|
|
2514
|
-
})
|
|
2515
3273
|
route('GET', `${prefix}/api/essence/download`, (req, res) => {
|
|
2516
3274
|
const query = new URL(String(req.url ?? '/'), 'http://x').searchParams
|
|
2517
3275
|
try {
|
|
@@ -2658,7 +3416,12 @@ export function apply(ctx, config) {
|
|
|
2658
3416
|
// so a restart/crash can offer recovery. Nothing is auto-sent.
|
|
2659
3417
|
routeMethods(`${prefix}/api/composer/journal`, {
|
|
2660
3418
|
GET: (req, res) => {
|
|
2661
|
-
const
|
|
3419
|
+
const query = new URL(String(req.url ?? '/'), 'http://x').searchParams
|
|
3420
|
+
const key = query.get('key') || ''
|
|
3421
|
+
// list=1 is the recovery list: every saved session draft/queue, newest first.
|
|
3422
|
+
if (!key && query.get('list') === '1') {
|
|
3423
|
+
return json(res, 200, { ok: true, entries: composerJournal.list() })
|
|
3424
|
+
}
|
|
2662
3425
|
if (!key) return json(res, 400, { ok: false, error: 'journal-key-required' })
|
|
2663
3426
|
return json(res, 200, { ok: true, entry: composerJournal.get(key) })
|
|
2664
3427
|
},
|
|
@@ -2674,6 +3437,37 @@ export function apply(ctx, config) {
|
|
|
2674
3437
|
},
|
|
2675
3438
|
})
|
|
2676
3439
|
|
|
3440
|
+
// Restore saved queue rows into the official Session inbox WITHOUT waking the
|
|
3441
|
+
// agent. The queue journal is a recovery surface; it must not send messages.
|
|
3442
|
+
route('POST', `${prefix}/api/composer/queue`, async (req, res) => {
|
|
3443
|
+
const body = await readBody(req)
|
|
3444
|
+
const sessionId = String(body?.sessionId ?? '').trim()
|
|
3445
|
+
const items = Array.isArray(body?.items) ? body.items : []
|
|
3446
|
+
if (!sessionId) return json(res, 400, { ok: false, error: 'session-id-required' })
|
|
3447
|
+
if (items.length === 0) return json(res, 200, { ok: true, queued: 0, failed: 0 })
|
|
3448
|
+
const agents = safeGet('agents')
|
|
3449
|
+
const agent = agents?.get?.(sessionId)
|
|
3450
|
+
if (!agent || typeof agent.send !== 'function') {
|
|
3451
|
+
return json(res, 409, { ok: false, error: 'session-not-live' })
|
|
3452
|
+
}
|
|
3453
|
+
let queued = 0
|
|
3454
|
+
let failed = 0
|
|
3455
|
+
for (const item of items.slice(0, 100)) {
|
|
3456
|
+
const text = String(item?.text ?? '').trim().slice(0, 4000)
|
|
3457
|
+
if (!text) { failed += 1; continue }
|
|
3458
|
+
try {
|
|
3459
|
+
agent.send({
|
|
3460
|
+
id: newId('msg'),
|
|
3461
|
+
role: 'user',
|
|
3462
|
+
content: [{ type: 'text', text }],
|
|
3463
|
+
source: { kind: 'user' },
|
|
3464
|
+
}, 'next-turn', false)
|
|
3465
|
+
queued += 1
|
|
3466
|
+
} catch { failed += 1 }
|
|
3467
|
+
}
|
|
3468
|
+
return json(res, 200, { ok: true, queued, failed })
|
|
3469
|
+
})
|
|
3470
|
+
|
|
2677
3471
|
// v3.0.8 contract: an unknown /fang/api/* path must be a JSON 404 under the
|
|
2678
3472
|
// same Host/Origin/token gate — not an unauthenticated empty 404 from the host.
|
|
2679
3473
|
// Exact routes above win because the webServer matches exact before prefix.
|
|
@@ -2686,6 +3480,10 @@ export function apply(ctx, config) {
|
|
|
2686
3480
|
route('POST', `${prefix}/api/essence/default`, async (req, res) => {
|
|
2687
3481
|
const body = await readBody(req)
|
|
2688
3482
|
try {
|
|
3483
|
+
// 同一路径两用:显式 essenceId = 设为默认;否则走默认元宝 ensure(apply/force/mode)。
|
|
3484
|
+
if (body?.essenceId) {
|
|
3485
|
+
return json(res, 200, { ok: true, default: mirrorService.setDefaultEssence(String(body.essenceId)) })
|
|
3486
|
+
}
|
|
2689
3487
|
const out = await mirrorService.ensureDefaultEssence({ apply: body?.apply === true, force: body?.force === true, mode: body?.mode === 'preset' ? 'preset' : 'copy-local' })
|
|
2690
3488
|
return json(res, out.ok === false ? 409 : 200, out)
|
|
2691
3489
|
} catch (error) {
|