@twinsearth/dsh-fang 3.0.10 → 3.1.2
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 +6 -2
- 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-config-lock.mjs +65 -2
- 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 +33 -2
- package/src/plugins/healer.mjs +53 -20
- package/src/plugins/imports.mjs +48 -0
- package/src/plugins/orchestrator.mjs +818 -42
- 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,
|
|
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,57 @@ 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
|
+
|
|
40
85
|
export const name = 'fang-orchestrator'
|
|
41
86
|
export const inject = []
|
|
42
87
|
|
|
43
88
|
export const Config = z.object({
|
|
44
89
|
role: z.union([z.const('mother'), z.const('fork')]).default('mother')
|
|
45
90
|
.description('配置层角色;环境 DSH_FANG_ROLE 优先(forker 派生的分身自动为 fork)'),
|
|
91
|
+
officialSourceUrl: z.string().default('')
|
|
92
|
+
.description('官方源 manifest 基础 URL(https;留空 = 无官方源,升级显式 official-source-unavailable)'),
|
|
93
|
+
officialSourceToken: z.string().default('')
|
|
94
|
+
.description('官方源 Bearer token(可选;不会写进日志/状态)'),
|
|
46
95
|
maxForks: z.number().min(1).max(64).default(8)
|
|
47
96
|
.description('同时存活的任务/分身上限'),
|
|
48
97
|
motherProfile: z.string().default('')
|
|
@@ -109,14 +158,28 @@ export function stripUrlToken(url) {
|
|
|
109
158
|
}
|
|
110
159
|
|
|
111
160
|
/** Find a runnable dsh launcher. `.cmd` wrappers are spawned through a shell by the forker. */
|
|
112
|
-
export function resolveCliPath(explicit = '', env = process.env) {
|
|
161
|
+
export function resolveCliPath(explicit = '', env = process.env, execPath = process.execPath) {
|
|
113
162
|
const candidates = []
|
|
114
163
|
if (explicit) candidates.push(explicit)
|
|
115
164
|
if (env.DSH_CLI) candidates.push(env.DSH_CLI)
|
|
165
|
+
if (env.DSH_INSTALL_DIR) candidates.push(path.join(env.DSH_INSTALL_DIR, 'resources', 'runtime', 'cli', 'bin', 'dsh.cmd'))
|
|
116
166
|
for (const dir of String(env.PATH ?? env.Path ?? '').split(path.delimiter)) {
|
|
117
167
|
if (!dir) continue
|
|
118
168
|
candidates.push(path.join(dir, 'dsh.cmd'), path.join(dir, 'dsh.exe'), path.join(dir, 'dsh'))
|
|
119
169
|
}
|
|
170
|
+
// 新版桌面安装目录不一定叫 E:\DS;从当前宿主可执行文件反推安装根目录:
|
|
171
|
+
// <install>\DeepSeek Harness.exe -> <install>\resources\runtime\cli\bin\dsh.cmd
|
|
172
|
+
// 同时向上探测 4 层,兼容 node.exe 等位于 runtime/ 下的启动器。
|
|
173
|
+
try {
|
|
174
|
+
let dir = path.dirname(String(execPath ?? ''))
|
|
175
|
+
for (let i = 0; i < 5 && dir; i += 1) {
|
|
176
|
+
candidates.push(path.join(dir, 'resources', 'runtime', 'cli', 'bin', 'dsh.cmd'))
|
|
177
|
+
candidates.push(path.join(dir, 'runtime', 'cli', 'bin', 'dsh.cmd'))
|
|
178
|
+
const parent = path.dirname(dir)
|
|
179
|
+
if (parent === dir) break
|
|
180
|
+
dir = parent
|
|
181
|
+
}
|
|
182
|
+
} catch { /* keep legacy candidates */ }
|
|
120
183
|
candidates.push(
|
|
121
184
|
'E:\\DS\\resources\\runtime\\cli\\bin\\dsh.cmd',
|
|
122
185
|
'C:\\Program Files\\DeepSeek Harness\\resources\\runtime\\cli\\bin\\dsh.cmd',
|
|
@@ -183,6 +246,35 @@ export function apply(ctx, config) {
|
|
|
183
246
|
}
|
|
184
247
|
|
|
185
248
|
const safeGet = (key) => { try { return ctx.get(key) } catch { return undefined } }
|
|
249
|
+
/**
|
|
250
|
+
* 宿主内部生产者 → 决策中心(best-effort,绝不改变原流程结果)。
|
|
251
|
+
* 用于 MirrorUpgrade / EssenceManager 这类仓内对象;外部系统(PM/PJM/Worker/
|
|
252
|
+
* HarnessMM/PluginUpdater/SuperAgent)走 POST /fang/api/decisions/ingest 桥。
|
|
253
|
+
*/
|
|
254
|
+
const raiseDecisionTicket = (spec = {}) => { try {
|
|
255
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
256
|
+
if (!center || typeof center.submit !== 'function') return null
|
|
257
|
+
const submitted = center.submit({
|
|
258
|
+
level: spec.level ?? 'yellow',
|
|
259
|
+
title: spec.title,
|
|
260
|
+
context: spec.context,
|
|
261
|
+
options: spec.options,
|
|
262
|
+
actions: spec.actions,
|
|
263
|
+
timeoutMinutes: spec.timeoutMinutes ?? 1440,
|
|
264
|
+
dedupeKey: spec.dedupeKey,
|
|
265
|
+
source: {
|
|
266
|
+
sessionId: String(spec.sessionId ?? 'orchestrator'),
|
|
267
|
+
agentRole: spec.agentRole ?? 'system',
|
|
268
|
+
roleSource: 'host:orchestrator',
|
|
269
|
+
roleTrusted: true,
|
|
270
|
+
taskName: String(spec.sourceName ?? spec.producer ?? 'orchestrator'),
|
|
271
|
+
},
|
|
272
|
+
metadata: spec.metadata,
|
|
273
|
+
})
|
|
274
|
+
return submitted?.ok ? submitted.ticket : null
|
|
275
|
+
} catch { return null }
|
|
276
|
+
}
|
|
277
|
+
const businessProducers = createBusinessProducers({ submit: (spec) => raiseDecisionTicket(spec) })
|
|
186
278
|
const audit = (kind, data) => {
|
|
187
279
|
try { safeGet(SERVICE.auditor)?.append(kind, data) } catch { /* auditor optional */ }
|
|
188
280
|
try { bus.emit('fang/audit', { kind, data }) } catch { /* ignore */ }
|
|
@@ -531,6 +623,47 @@ export function apply(ctx, config) {
|
|
|
531
623
|
} catch { return null }
|
|
532
624
|
}
|
|
533
625
|
|
|
626
|
+
/**
|
|
627
|
+
* 只读:重启守卫 + supervisor 契约状态。
|
|
628
|
+
* status() 只带摘要(Client Header 用),/fang/api/restart 带完整视图。
|
|
629
|
+
* 任何字段缺失都按「不可用/未知」返回,绝不伪造已武装或已执行。
|
|
630
|
+
*/
|
|
631
|
+
const restartView = () => {
|
|
632
|
+
const guard = safeGet(SERVICE.restart)
|
|
633
|
+
if (!guard) return { available: false }
|
|
634
|
+
try {
|
|
635
|
+
const state = typeof guard.state === 'function' ? guard.state() : null
|
|
636
|
+
const policy = typeof guard.policy === 'function' ? guard.policy() : null
|
|
637
|
+
const contract = typeof guard.executionContract === 'function' ? guard.executionContract() : null
|
|
638
|
+
const approvals = typeof guard.approvals === 'function' ? guard.approvals({ limit: 20 }) : null
|
|
639
|
+
return { available: true, state, policy, contract, approvals, decisionOnly: true, executed: false }
|
|
640
|
+
} catch (error) {
|
|
641
|
+
return { available: true, error: 'restart-guard-status-failed', detail: String(error?.message ?? error) }
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
const restartSummary = (view) => {
|
|
646
|
+
if (!view?.available) return { available: false }
|
|
647
|
+
if (view.error) return { available: true, error: view.error }
|
|
648
|
+
const s = view.state ?? {}
|
|
649
|
+
const p = view.policy ?? {}
|
|
650
|
+
return {
|
|
651
|
+
available: true,
|
|
652
|
+
state: s.state ?? null,
|
|
653
|
+
pending: s.pending ?? null,
|
|
654
|
+
mode: p.mode ?? s.mode ?? null,
|
|
655
|
+
authMode: p.authMode ?? s.authMode ?? null,
|
|
656
|
+
strictRedLine: p.strictRedLine ?? null,
|
|
657
|
+
redLineAutoAllowed: p.redLineAutoAllowed === true || s.redLineAutoAllowed === true,
|
|
658
|
+
allowProcessRestart: p.allowProcessRestart === true || s.allowProcessRestart === true,
|
|
659
|
+
tempEffectiveManual: p.tempEffectiveManual === true || s.tempEffectiveManual === true,
|
|
660
|
+
decisionOnly: true,
|
|
661
|
+
contractVersion: s.contractVersion ?? null,
|
|
662
|
+
manifestTtlMs: p.manifestTtlMs ?? s.manifestTtlMs ?? null,
|
|
663
|
+
approvals: view.approvals?.counts ?? null,
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
|
|
534
667
|
const service = {
|
|
535
668
|
role,
|
|
536
669
|
version: FANG_VERSION,
|
|
@@ -600,9 +733,17 @@ export function apply(ctx, config) {
|
|
|
600
733
|
homeDir,
|
|
601
734
|
profile,
|
|
602
735
|
profileTemplate,
|
|
603
|
-
// 从原身派生:配置必须真的来自原身 merged(不能被 clean template
|
|
604
|
-
// node_modules
|
|
605
|
-
|
|
736
|
+
// 从原身派生:配置必须真的来自原身 merged(不能被 clean template 覆盖)。
|
|
737
|
+
// node_modules:优先元主自己的模块树;默认元宝/新建原身可能尚未物化 node_modules,
|
|
738
|
+
// 此时回退母体模块树,保证分身仍能解析 @twinsearth/dsh-fang(否则是僵尸分身)。
|
|
739
|
+
...(sourceEssence ? {
|
|
740
|
+
cleanTemplate: false,
|
|
741
|
+
nodeModulesSource: (() => {
|
|
742
|
+
const essenceModules = path.join(profileTemplate, 'node_modules')
|
|
743
|
+
if (exists(essenceModules)) return essenceModules
|
|
744
|
+
return path.join(templateDir(), 'node_modules')
|
|
745
|
+
})(),
|
|
746
|
+
} : {}),
|
|
606
747
|
})
|
|
607
748
|
if (provisioned && provisioned.ok === false) {
|
|
608
749
|
task.status = TASK_STATUS.FAILED
|
|
@@ -789,6 +930,44 @@ export function apply(ctx, config) {
|
|
|
789
930
|
return service.listTasks()
|
|
790
931
|
},
|
|
791
932
|
|
|
933
|
+
/** 分身看护开关:持久化设置 + forker 运行时 supervise 状态。 */
|
|
934
|
+
forkSupervision() {
|
|
935
|
+
const persisted = readForkSupervisionSettings(layout.dataDir)
|
|
936
|
+
const f = forker()
|
|
937
|
+
const live = f && typeof f.getSupervision === 'function' ? f.getSupervision() : null
|
|
938
|
+
return {
|
|
939
|
+
ok: true,
|
|
940
|
+
persisted: {
|
|
941
|
+
autostartForks: persisted.autostartForks,
|
|
942
|
+
supervise: persisted.supervise,
|
|
943
|
+
updatedAt: persisted.updatedAt,
|
|
944
|
+
exists: persisted.exists,
|
|
945
|
+
},
|
|
946
|
+
effective: {
|
|
947
|
+
autostartForks: persisted.autostartForks,
|
|
948
|
+
supervise: live ? live.enabled : persisted.supervise,
|
|
949
|
+
},
|
|
950
|
+
forker: live,
|
|
951
|
+
}
|
|
952
|
+
},
|
|
953
|
+
|
|
954
|
+
/** 更新看护开关;supervise 会立即应用到 forker,无需重启宿主。 */
|
|
955
|
+
setForkSupervision(input = {}) {
|
|
956
|
+
const patch = {}
|
|
957
|
+
if (typeof input?.autostartForks === 'boolean') patch.autostartForks = input.autostartForks
|
|
958
|
+
if (typeof input?.supervise === 'boolean') patch.supervise = input.supervise
|
|
959
|
+
if (!Object.keys(patch).length) return { ok: false, error: 'no-settings' }
|
|
960
|
+
const written = writeForkSupervisionSettings(layout.dataDir, patch)
|
|
961
|
+
if (!written.ok) return written
|
|
962
|
+
let applied = null
|
|
963
|
+
if (patch.supervise !== undefined) {
|
|
964
|
+
const f = forker()
|
|
965
|
+
if (f && typeof f.setSupervise === 'function') applied = f.setSupervise(patch.supervise)
|
|
966
|
+
}
|
|
967
|
+
try { audit(AUDIT.FORK_SUPERVISION, { ...patch, applied: applied?.enabled ?? null }) } catch { /* audit optional */ }
|
|
968
|
+
return { ...service.forkSupervision(), applied }
|
|
969
|
+
},
|
|
970
|
+
|
|
792
971
|
async getTaskStatus(taskId) {
|
|
793
972
|
const task = tasks.get(String(taskId ?? ''))
|
|
794
973
|
if (!task) return { ok: false, error: 'unknown-task' }
|
|
@@ -861,22 +1040,25 @@ export function apply(ctx, config) {
|
|
|
861
1040
|
// Materialize the fetched source into a mother-side work dir, then re-score with
|
|
862
1041
|
// the MOTHER threshold policy (母体更严格,且这是真正写进生产的判定).
|
|
863
1042
|
const workDir = path.join(layout.dataDir, 'work', `${id}-${plugin}`)
|
|
1043
|
+
const discardWorkDir = () => { try { removeTree(workDir) } catch { /* best effort */ } }
|
|
864
1044
|
try {
|
|
865
1045
|
removeTree(workDir)
|
|
866
1046
|
ensureDir(workDir)
|
|
867
1047
|
for (const [rel, content] of Object.entries(files)) {
|
|
868
1048
|
const target = resolveInside(workDir, rel)
|
|
869
|
-
if (!target) return { ok: false, error: 'unsafe-plugin-path', detail: rel }
|
|
1049
|
+
if (!target) { discardWorkDir(); return { ok: false, error: 'unsafe-plugin-path', detail: rel } }
|
|
870
1050
|
writeFileAtomic(target, String(content))
|
|
871
1051
|
}
|
|
872
1052
|
} catch (e) {
|
|
1053
|
+
discardWorkDir()
|
|
873
1054
|
return { ok: false, error: 'materialize-failed', detail: String(e?.message ?? e) }
|
|
874
1055
|
}
|
|
875
1056
|
|
|
876
1057
|
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' }
|
|
1058
|
+
const motherAssessment = scorer?.scoreDir ? scorer.scoreDir(workDir, null, { environment: 'mother', deep: true }) : null
|
|
1059
|
+
if (!motherAssessment) { discardWorkDir(); return { ok: false, error: 'scorer-unavailable' } }
|
|
879
1060
|
if (motherAssessment.grade === 'D' || motherAssessment.grade === 'E') {
|
|
1061
|
+
discardWorkDir()
|
|
880
1062
|
return { ok: false, error: 'grade-too-low', grade: motherAssessment.grade, score: motherAssessment.S }
|
|
881
1063
|
}
|
|
882
1064
|
|
|
@@ -889,11 +1071,12 @@ export function apply(ctx, config) {
|
|
|
889
1071
|
})
|
|
890
1072
|
: null
|
|
891
1073
|
if (route && route.route !== 'sandbox') {
|
|
1074
|
+
discardWorkDir()
|
|
892
1075
|
return { ok: false, error: 'route-refused', route: route.route, reason: route.reason }
|
|
893
1076
|
}
|
|
894
1077
|
|
|
895
1078
|
const approver = safeGet(SERVICE.approver)
|
|
896
|
-
if (!approver) return { ok: false, error: 'approver-unavailable' }
|
|
1079
|
+
if (!approver) { discardWorkDir(); return { ok: false, error: 'approver-unavailable' } }
|
|
897
1080
|
|
|
898
1081
|
// 团队权限钩子(无 provider 时放行并记录 basis)。
|
|
899
1082
|
let teamBasis = { commercial: false }
|
|
@@ -903,7 +1086,7 @@ export function apply(ctx, config) {
|
|
|
903
1086
|
method: 'check', args: [{ action: 'promote', group: plugin }],
|
|
904
1087
|
})
|
|
905
1088
|
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 }
|
|
1089
|
+
if (teamBasis.allowed === false) { discardWorkDir(); return { ok: false, error: 'team-denied', basis: teamBasis } }
|
|
907
1090
|
}
|
|
908
1091
|
|
|
909
1092
|
const decision = typeof approver.requestPromotion === 'function'
|
|
@@ -922,23 +1105,28 @@ export function apply(ctx, config) {
|
|
|
922
1105
|
})
|
|
923
1106
|
const outcome = decision?.outcome ?? 'timeout'
|
|
924
1107
|
audit(AUDIT.APPROVAL_DECIDED, { kind: 'promotion', taskId: id, pluginId: plugin, outcome })
|
|
925
|
-
if (outcome !== 'approved') return { ok: false, error: 'denied', outcome }
|
|
1108
|
+
if (outcome !== 'approved') { discardWorkDir(); return { ok: false, error: 'denied', outcome } }
|
|
926
1109
|
|
|
927
1110
|
const target = path.join(layout.dataDir, 'promoted', plugin)
|
|
928
1111
|
try {
|
|
929
1112
|
if (exists(target)) {
|
|
930
|
-
approver.snapshot?.({ tag: plugin, dir: target })
|
|
931
|
-
|
|
1113
|
+
const snap = await approver.snapshot?.({ tag: plugin, dir: target })
|
|
1114
|
+
if (!snap || snap.ok === false) {
|
|
1115
|
+
discardWorkDir()
|
|
1116
|
+
return { ok: false, error: 'snapshot-failed', detail: String(snap?.error ?? snap?.reason ?? 'snapshot unavailable') }
|
|
1117
|
+
}
|
|
932
1118
|
}
|
|
933
|
-
|
|
1119
|
+
const commit = atomicReplaceDir(workDir, target)
|
|
1120
|
+
discardWorkDir()
|
|
1121
|
+
audit(AUDIT.PROMOTE_COMMITTED, {
|
|
1122
|
+
taskId: id, pluginId: plugin, target, digest: commit.digest,
|
|
1123
|
+
forkGrade: forkAssessment?.grade ?? null, motherGrade: motherAssessment.grade,
|
|
1124
|
+
})
|
|
934
1125
|
} catch (e) {
|
|
1126
|
+
discardWorkDir()
|
|
935
1127
|
audit(AUDIT.PROMOTE_FAILED, { taskId: id, pluginId: plugin, error: String(e?.message ?? e) })
|
|
936
1128
|
return { ok: false, error: 'promote-failed', detail: String(e?.message ?? e) }
|
|
937
1129
|
}
|
|
938
|
-
audit(AUDIT.PROMOTE_COMMITTED, {
|
|
939
|
-
taskId: id, pluginId: plugin, target,
|
|
940
|
-
forkGrade: forkAssessment?.grade ?? null, motherGrade: motherAssessment.grade,
|
|
941
|
-
})
|
|
942
1130
|
|
|
943
1131
|
// 商用钩子:云备份(不阻塞、失败只记录)。
|
|
944
1132
|
let backup = { ok: false, error: 'not-configured' }
|
|
@@ -992,14 +1180,16 @@ export function apply(ctx, config) {
|
|
|
992
1180
|
const target = path.join(layout.dataDir, 'promoted', String(pluginId))
|
|
993
1181
|
try {
|
|
994
1182
|
if (exists(target)) {
|
|
995
|
-
approver.snapshot?.({ tag: String(pluginId), dir: target })
|
|
996
|
-
|
|
1183
|
+
const snap = await approver.snapshot?.({ tag: String(pluginId), dir: target })
|
|
1184
|
+
if (!snap || snap.ok === false) {
|
|
1185
|
+
return { ok: false, error: 'snapshot-failed', detail: String(snap?.error ?? snap?.reason ?? 'snapshot unavailable') }
|
|
1186
|
+
}
|
|
997
1187
|
}
|
|
998
|
-
|
|
1188
|
+
const commit = atomicReplaceDir(src, target)
|
|
1189
|
+
audit(AUDIT.PROMOTE_COMMITTED, { forkId, pluginId, target, digest: commit.digest })
|
|
999
1190
|
} catch (e) {
|
|
1000
1191
|
return { ok: false, error: 'promote-failed', detail: String(e?.message ?? e) }
|
|
1001
1192
|
}
|
|
1002
|
-
audit(AUDIT.PROMOTE_COMMITTED, { forkId, pluginId, target })
|
|
1003
1193
|
return { ok: true, outcome: 'approved', target, pluginId, assessment }
|
|
1004
1194
|
},
|
|
1005
1195
|
|
|
@@ -1269,6 +1459,90 @@ export function apply(ctx, config) {
|
|
|
1269
1459
|
return { ok: true, restored: true, taskId: id, title: task.title, url: task.url, port: task.port, adapter, configReset, sessionGuard }
|
|
1270
1460
|
},
|
|
1271
1461
|
|
|
1462
|
+
/**
|
|
1463
|
+
* watchdog 启动时的恢复入口:把「已登记但进程没在跑」的非归档任务重新 spawn。
|
|
1464
|
+
* 不创建新任务、不动归档任务;失败的任务不重试(避免崩溃循环),只如实报告。
|
|
1465
|
+
* @param {{taskIds?: string[]}} [input]
|
|
1466
|
+
*/
|
|
1467
|
+
async autostartForks(input = {}) {
|
|
1468
|
+
const f = forker()
|
|
1469
|
+
if (!f || typeof f.spawn !== 'function') {
|
|
1470
|
+
return { ok: false, error: 'forker-unavailable', started: [], failed: [], skipped: [] }
|
|
1471
|
+
}
|
|
1472
|
+
const wanted = Array.isArray(input?.taskIds) && input.taskIds.length
|
|
1473
|
+
? new Set(input.taskIds.map(String))
|
|
1474
|
+
: null
|
|
1475
|
+
const report = { ok: true, started: [], failed: [], skipped: [] }
|
|
1476
|
+
for (const task of tasks.values()) {
|
|
1477
|
+
const id = task.taskId
|
|
1478
|
+
if (wanted && !wanted.has(id)) continue
|
|
1479
|
+
if (task.status === TASK_STATUS.ARCHIVED) {
|
|
1480
|
+
report.skipped.push({ taskId: id, reason: 'archived' })
|
|
1481
|
+
continue
|
|
1482
|
+
}
|
|
1483
|
+
let live = null
|
|
1484
|
+
try { live = f.status?.(id) ?? null } catch { live = null }
|
|
1485
|
+
if (live?.running === true || live?.state === 'running') {
|
|
1486
|
+
report.skipped.push({ taskId: id, reason: 'already-running' })
|
|
1487
|
+
continue
|
|
1488
|
+
}
|
|
1489
|
+
if (!task.homeDir || !exists(task.homeDir) || !task.profile) {
|
|
1490
|
+
report.failed.push({ taskId: id, error: 'home-missing' })
|
|
1491
|
+
continue
|
|
1492
|
+
}
|
|
1493
|
+
try { assertInside(layout.forkHomesDir, task.homeDir, 'fork-home') } catch {
|
|
1494
|
+
report.failed.push({ taskId: id, error: 'path-escape' })
|
|
1495
|
+
continue
|
|
1496
|
+
}
|
|
1497
|
+
const forkBundle = path.join(task.homeDir, 'profiles', task.profile, 'node_modules', '@local', 'dsh-fang')
|
|
1498
|
+
if (!exists(forkBundle)) {
|
|
1499
|
+
report.failed.push({ taskId: id, error: 'fork-bundle-unavailable' })
|
|
1500
|
+
continue
|
|
1501
|
+
}
|
|
1502
|
+
task.status = TASK_STATUS.PROVISIONING
|
|
1503
|
+
persist()
|
|
1504
|
+
let started
|
|
1505
|
+
try {
|
|
1506
|
+
started = await f.spawn({
|
|
1507
|
+
forkId: id,
|
|
1508
|
+
homeDir: task.homeDir,
|
|
1509
|
+
profile: task.profile,
|
|
1510
|
+
cliPath: cliPath(),
|
|
1511
|
+
env: { DSH_FANG_ROLE: 'fork', DSH_FANG_TASK_ID: id, DSH_FANG_MOTHER: layout.dataDir },
|
|
1512
|
+
})
|
|
1513
|
+
} catch (error) {
|
|
1514
|
+
started = { ok: false, error: String(error?.message ?? error) }
|
|
1515
|
+
}
|
|
1516
|
+
if (!started || started.ok === false) {
|
|
1517
|
+
task.status = TASK_STATUS.FAILED
|
|
1518
|
+
persist()
|
|
1519
|
+
audit(AUDIT.FORK_CRASHED, { taskId: id, error: started?.error ?? 'spawn-failed', reason: 'autostart' })
|
|
1520
|
+
report.failed.push({ taskId: id, error: started?.error ?? 'spawn-failed' })
|
|
1521
|
+
continue
|
|
1522
|
+
}
|
|
1523
|
+
task.status = TASK_STATUS.RUNNING
|
|
1524
|
+
task.pid = started.pid ?? null
|
|
1525
|
+
task.port = started.port ?? null
|
|
1526
|
+
task.url = started.url ?? null
|
|
1527
|
+
task.token = started.token ?? extractTokenSafe(task.url)
|
|
1528
|
+
task.adapter = { ok: false, error: 'handshaking' }
|
|
1529
|
+
persist()
|
|
1530
|
+
audit(AUDIT.FORK_STARTED, { taskId: id, pid: task.pid, port: task.port, profile: task.profile, reason: 'autostart' })
|
|
1531
|
+
bus.emit('fang/fork-started', { taskId: id, forkId: id, pid: task.pid, port: task.port })
|
|
1532
|
+
report.started.push({ taskId: id, pid: task.pid, port: task.port })
|
|
1533
|
+
// 握手放到后台:watchdog 的启动请求不应该被 N 个分身的启动时间串行阻塞。
|
|
1534
|
+
void handshake(task).then((adapter) => {
|
|
1535
|
+
if (!adapter?.ok) return
|
|
1536
|
+
const current = tasks.get(id)
|
|
1537
|
+
if (!current || current.pid !== task.pid) return
|
|
1538
|
+
current.status = TASK_STATUS.READY
|
|
1539
|
+
current.adapter = adapter
|
|
1540
|
+
persist()
|
|
1541
|
+
}).catch(() => {})
|
|
1542
|
+
}
|
|
1543
|
+
return report
|
|
1544
|
+
},
|
|
1545
|
+
|
|
1272
1546
|
/** 永久删除存档:reap(杀进程 + 删 home + 删记录);forker 记录已丢时按 home 兜底清理。 */
|
|
1273
1547
|
async deleteArchivedTask(taskId) {
|
|
1274
1548
|
const id = String(taskId ?? '')
|
|
@@ -1362,6 +1636,8 @@ export function apply(ctx, config) {
|
|
|
1362
1636
|
commercial: !!safeGet(SERVICE.commercial),
|
|
1363
1637
|
sessionCatalog: !!safeGet(SERVICE.sessionCatalog),
|
|
1364
1638
|
},
|
|
1639
|
+
// 重启守卫摘要(只读):Client Header 用它显示 mode/红灯策略;无守卫时 available:false。
|
|
1640
|
+
restart: restartSummary(restartView()),
|
|
1365
1641
|
}
|
|
1366
1642
|
},
|
|
1367
1643
|
|
|
@@ -1377,11 +1653,21 @@ export function apply(ctx, config) {
|
|
|
1377
1653
|
scope: 'mother',
|
|
1378
1654
|
origin: 'fang:orchestrator',
|
|
1379
1655
|
})
|
|
1380
|
-
|
|
1656
|
+
// auto-allow is a successful policy decision, not a denial.
|
|
1657
|
+
const allowed = decision?.outcome === 'approved' || decision?.outcome === 'auto-allow'
|
|
1658
|
+
return { ok: allowed, ...decision }
|
|
1381
1659
|
},
|
|
1382
1660
|
}
|
|
1383
1661
|
|
|
1384
1662
|
ctx.effect(() => ctx.provide(SERVICE.orchestrator, service))
|
|
1663
|
+
// 启动时把持久化的 supervise 开关应用到已经挂载的 forker(插件顺序可能晚于本插件)。
|
|
1664
|
+
ctx.inject([SERVICE.forker], (child) => {
|
|
1665
|
+
try {
|
|
1666
|
+
const f = child?.get?.(SERVICE.forker) ?? child?.[SERVICE.forker] ?? child?.forker ?? null
|
|
1667
|
+
const stored = readForkSupervisionSettings(layout.dataDir)
|
|
1668
|
+
if (f && typeof f.setSupervise === 'function' && stored.supervise === true) f.setSupervise(true)
|
|
1669
|
+
} catch { /* forker optional */ }
|
|
1670
|
+
})
|
|
1385
1671
|
|
|
1386
1672
|
// ── v2.9.0 母体连接:只描述 + 只读探测,不持有连接状态 ──────────────────
|
|
1387
1673
|
const linkProfileDir = () => {
|
|
@@ -1414,7 +1700,14 @@ export function apply(ctx, config) {
|
|
|
1414
1700
|
// v3.0.3:客户端升级后的兼容性门禁(模块导入 + 路由契约;失败保持子插件关闭)
|
|
1415
1701
|
const compatRoot = fileURLToPath(new URL('../../', import.meta.url))
|
|
1416
1702
|
let compatWebServer = null
|
|
1703
|
+
const rawConfig = config && typeof config === 'object' ? config : {}
|
|
1417
1704
|
const runCompatCheck = async () => {
|
|
1705
|
+
if (typeof rawConfig.compatGate === 'function') {
|
|
1706
|
+
// 测试/嵌入注入点:不改变生产默认(bundle 配置无法携带函数)。
|
|
1707
|
+
const injected = await rawConfig.compatGate()
|
|
1708
|
+
writeCompatStatus(layout.dataDir, injected)
|
|
1709
|
+
return injected
|
|
1710
|
+
}
|
|
1418
1711
|
const status = await runCompatGate({
|
|
1419
1712
|
rootDir: compatRoot,
|
|
1420
1713
|
expectedRouteCount: DEFAULT_EXPECTED_ROUTE_COUNT,
|
|
@@ -1426,8 +1719,24 @@ export function apply(ctx, config) {
|
|
|
1426
1719
|
return status
|
|
1427
1720
|
}
|
|
1428
1721
|
let upgradeCoordinator = null
|
|
1722
|
+
// 官方源:rawConfig.officialSource 优先(测试/嵌入可注入对象);否则按 URL 构建 manifest adapter。
|
|
1723
|
+
let officialSource = rawConfig.officialSource ?? null
|
|
1724
|
+
if (officialSource === null && String(cfg.officialSourceUrl ?? '').trim()) {
|
|
1725
|
+
try {
|
|
1726
|
+
officialSource = createManifestOfficialSource({
|
|
1727
|
+
baseUrl: cfg.officialSourceUrl,
|
|
1728
|
+
token: cfg.officialSourceToken,
|
|
1729
|
+
headers: {},
|
|
1730
|
+
})
|
|
1731
|
+
} catch (error) {
|
|
1732
|
+
try { ctx.logger?.warn?.(`[mirror] official source disabled: ${String(error?.message ?? error)}`) } catch { /* ignore */ }
|
|
1733
|
+
officialSource = null
|
|
1734
|
+
}
|
|
1735
|
+
}
|
|
1429
1736
|
const mirrorManager = new MirrorManager({
|
|
1430
1737
|
mirrorRoot,
|
|
1738
|
+
// 测试/嵌入注入点:官方源与 compat gate 都可替换;生产 bundle 可配置 manifest URL。
|
|
1739
|
+
officialSource,
|
|
1431
1740
|
logger: ctx.logger ?? {},
|
|
1432
1741
|
usageProvider: () => ({
|
|
1433
1742
|
activeEssenceCount: 0,
|
|
@@ -1437,7 +1746,20 @@ export function apply(ctx, config) {
|
|
|
1437
1746
|
}),
|
|
1438
1747
|
compatGate: () => runCompatCheck(),
|
|
1439
1748
|
onCompatResult: (compat) => { writeCompatStatus(layout.dataDir, compat) },
|
|
1440
|
-
postUpgradeHook: () => {
|
|
1749
|
+
postUpgradeHook: () => {
|
|
1750
|
+
if (upgradeCoordinator === null) return
|
|
1751
|
+
// 升级成功 → 元主重算;失败必须让人看见(决策中心 ticket),不吞掉。
|
|
1752
|
+
Promise.resolve(upgradeCoordinator.onUpgradeSuccess()).catch((error) => {
|
|
1753
|
+
raiseDecisionTicket({
|
|
1754
|
+
level: 'yellow',
|
|
1755
|
+
title: '升级后元主重算失败',
|
|
1756
|
+
context: `镜像升级成功,但元主重算失败:${String(error?.message ?? error)}`,
|
|
1757
|
+
options: [{ value: 'retry', label: '重试重算' }, { value: 'ignore', label: '忽略' }],
|
|
1758
|
+
dedupeKey: 'mirror-upgrade:recompute-failed',
|
|
1759
|
+
sourceName: 'MirrorUpgrade',
|
|
1760
|
+
})
|
|
1761
|
+
})
|
|
1762
|
+
},
|
|
1441
1763
|
})
|
|
1442
1764
|
mirrorManager.ensureLayout()
|
|
1443
1765
|
const preferencesStore = new PreferencesStore({ mirrorRoot, logger: ctx.logger ?? {} })
|
|
@@ -1783,9 +2105,10 @@ export function apply(ctx, config) {
|
|
|
1783
2105
|
importEssence: (input = {}) => essenceManager.importBundle(input?.bundle ?? input, {
|
|
1784
2106
|
name: input?.name, tier: input?.tier, parentId: input?.parentId ?? null,
|
|
1785
2107
|
}),
|
|
1786
|
-
// v3.0
|
|
1787
|
-
// 隔离边界:DSH_HOME =
|
|
1788
|
-
//
|
|
2108
|
+
// v3.1.0 元主运行态:用元主 merged/profile 起一个**隔离 home** 的配置态实例。
|
|
2109
|
+
// 隔离边界:DSH_HOME = sessions/<essenceId>/home(自己的 sessions/storages),
|
|
2110
|
+
// node_modules 也属于元主自己(D: 盘),不再 junction 到母体 C: 盘模块树;
|
|
2111
|
+
// 分身才复用元主/母体的 node_modules junction。
|
|
1789
2112
|
startEssenceRuntime: async (essenceId, input = {}) => {
|
|
1790
2113
|
const id = String(essenceId ?? '').trim()
|
|
1791
2114
|
const meta = essenceManager.getMeta(id)
|
|
@@ -1801,15 +2124,43 @@ export function apply(ctx, config) {
|
|
|
1801
2124
|
if (!exists(merged)) throw new Error('merged-profile-missing')
|
|
1802
2125
|
assertInside(layout.essenceRoot, merged, 'essence-merged')
|
|
1803
2126
|
const motherModules = path.join(templateDir(), 'node_modules')
|
|
1804
|
-
const
|
|
1805
|
-
|
|
1806
|
-
|
|
2127
|
+
const essenceModules = path.join(merged, 'node_modules')
|
|
2128
|
+
// 元主自己的 node_modules:必须是 D: 盘真实目录,不能是到母体 C: 盘的 junction。
|
|
2129
|
+
// 旧布局/新建元主可能缺失;首次打开时从母体复制一份,之后各自独立升级。
|
|
2130
|
+
if (!exists(essenceModules)) {
|
|
2131
|
+
try {
|
|
2132
|
+
if (exists(motherModules)) copyTree(motherModules, essenceModules)
|
|
2133
|
+
else ensureDir(essenceModules)
|
|
2134
|
+
} catch (error) {
|
|
2135
|
+
throw new Error(`essence-node-modules-copy-failed: ${String(error?.message ?? error)}`)
|
|
2136
|
+
}
|
|
1807
2137
|
}
|
|
2138
|
+
// 复制来的模块树记录了母体 store;元主/运行态的 pnpm 必须显式用同一个 store,
|
|
2139
|
+
// 否则项目在 D: 盘、模块来自 C: store 时会报 ERR_PNPM_UNEXPECTED_STORE。
|
|
2140
|
+
const writeModuleStoreConfig = (profileDir) => {
|
|
2141
|
+
try {
|
|
2142
|
+
const modulesYaml = fs.readFileSync(path.join(essenceModules, '.modules.yaml'), 'utf8')
|
|
2143
|
+
const store = /^storeDir:\s*(.+)$/m.exec(modulesYaml)?.[1]?.trim()
|
|
2144
|
+
if (!store) return
|
|
2145
|
+
ensureDir(profileDir)
|
|
2146
|
+
const file = path.join(profileDir, '.npmrc')
|
|
2147
|
+
if (exists(file) && fs.readFileSync(file, 'utf8').includes('store-dir=')) return
|
|
2148
|
+
fs.writeFileSync(file, `store-dir=${store}\npackage-import-method=copy\n`, 'utf8')
|
|
2149
|
+
} catch { /* missing modules metadata is non-fatal */ }
|
|
2150
|
+
}
|
|
2151
|
+
writeModuleStoreConfig(merged)
|
|
1808
2152
|
const forkId = runtimeForkId(id)
|
|
1809
2153
|
// v3.0.9 三区:运行态 home 在 runtimeRoot 下(FANG_HOME 时是 sessions/<essenceId>/home),
|
|
1810
2154
|
// 原身文件夹只保留配置,项目/会话/任务文件不落原身目录。
|
|
1811
2155
|
const homeDir = runtimeHomeFor(id)
|
|
1812
2156
|
assertInside(layout.runtimeRoot, homeDir, 'runtime-home')
|
|
2157
|
+
// 运行态 profile 的 node_modules 必须重新指向该元主自己的模块树。
|
|
2158
|
+
// makeJunction 对已存在的链接不会替换,所以先安全移除旧 junction(不进入目标)。
|
|
2159
|
+
const runtimeProfileDir = path.join(homeDir, 'profiles', 'essence-runtime')
|
|
2160
|
+
const runtimeModules = path.join(runtimeProfileDir, 'node_modules')
|
|
2161
|
+
if (exists(runtimeModules)) {
|
|
2162
|
+
try { if (fs.lstatSync(runtimeModules).isSymbolicLink()) removeTree(runtimeModules) } catch { /* ignore */ }
|
|
2163
|
+
}
|
|
1813
2164
|
const legacyHomes = [
|
|
1814
2165
|
path.join(layout.dataDir, 'runtime', forkId, 'home'),
|
|
1815
2166
|
path.join(essenceManager.essenceRoot(id), 'runtime', 'home'),
|
|
@@ -1823,8 +2174,13 @@ export function apply(ctx, config) {
|
|
|
1823
2174
|
const provisioned = await f.provision({
|
|
1824
2175
|
forkId, taskTitle: `元主运行时 · ${String(meta.name ?? id)}`,
|
|
1825
2176
|
homeDir, profile: 'essence-runtime', profileTemplate: merged,
|
|
2177
|
+
// 元主运行态必须继承元主的插件/设置;clean template 只用于空白分身,
|
|
2178
|
+
// 否则官方/用户元主打开后看不到本机插件列表(v3.0.10 实测)。
|
|
2179
|
+
cleanTemplate: false,
|
|
2180
|
+
nodeModulesSource: essenceModules,
|
|
1826
2181
|
})
|
|
1827
2182
|
if (!provisioned.ok) throw new Error(String(provisioned.error ?? 'runtime-provision-failed'))
|
|
2183
|
+
writeModuleStoreConfig(runtimeProfileDir)
|
|
1828
2184
|
// 先导入选中的进行中会话,再拉起实例(实例启动时就能看到它们)。
|
|
1829
2185
|
const importedSessions = importSessionsInto(homeDir, input?.sessionIds)
|
|
1830
2186
|
// 注意:forker.spawn 需要显式 homeDir/profile(它不从 provision 记录里猜)。
|
|
@@ -1980,6 +2336,17 @@ export function apply(ctx, config) {
|
|
|
1980
2336
|
const essenceId = String(input?.essenceId ?? '').trim()
|
|
1981
2337
|
if (!essenceId) {
|
|
1982
2338
|
const out = await essenceManager.recomputeAll({ concurrency: Number(input?.concurrency) || 2 })
|
|
2339
|
+
// recomputeAll 返回的是 id 数组(recomputed/skipped/conflicted/failed),不是计数。
|
|
2340
|
+
const conflictedCount = Array.isArray(out?.conflicted) ? out.conflicted.length : (Number(out?.conflicted) || 0)
|
|
2341
|
+
const failedCount = Array.isArray(out?.failed) ? out.failed.length : (Number(out?.failed) || 0)
|
|
2342
|
+
// EssenceManager:批量重算出现冲突/失败时,必须变成人类可见的 ticket。
|
|
2343
|
+
if (conflictedCount > 0 || failedCount > 0) {
|
|
2344
|
+
const conflicts = Array.from({ length: conflictedCount }, () => ({ kind: 'recompute-conflict', severity: 'warning' }))
|
|
2345
|
+
await businessProducers.essenceConflict({
|
|
2346
|
+
essenceId: 'all', conflicts,
|
|
2347
|
+
severity: failedCount > 0 ? 'fatal' : 'warning',
|
|
2348
|
+
})
|
|
2349
|
+
}
|
|
1983
2350
|
return { ok: true, mode: 'all', ...out }
|
|
1984
2351
|
}
|
|
1985
2352
|
const meta = essenceManager.getMeta(essenceId)
|
|
@@ -2002,12 +2369,68 @@ export function apply(ctx, config) {
|
|
|
2002
2369
|
recomputeStatus: () => upgradeCoordinator.getRecomputeStatus(),
|
|
2003
2370
|
compatStatus: () => readCompatStatus(layout.dataDir),
|
|
2004
2371
|
runCompatCheck,
|
|
2005
|
-
upgrade: (input = {}) =>
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2372
|
+
upgrade: async (input = {}) => {
|
|
2373
|
+
const emitStage = (stage) => {
|
|
2374
|
+
try { bus.emit('fang/mirror-upgrade-stage', { stage, at: Date.now() }) } catch { /* ignore */ }
|
|
2375
|
+
try { audit('mirror-upgrade-stage', { stage }) } catch { /* ignore */ }
|
|
2376
|
+
}
|
|
2377
|
+
try {
|
|
2378
|
+
const out = await mirrorManager.upgrade({
|
|
2379
|
+
autoBackup: input?.autoBackup !== false,
|
|
2380
|
+
autoRollback: input?.autoRollback !== false,
|
|
2381
|
+
onProgress: emitStage,
|
|
2382
|
+
})
|
|
2383
|
+
if (out?.ok === false) {
|
|
2384
|
+
await businessProducers.mirrorUpgradeFailed({
|
|
2385
|
+
from: out.from, to: out.to,
|
|
2386
|
+
reason: String(out?.error ?? out?.reason ?? 'unknown'),
|
|
2387
|
+
})
|
|
2388
|
+
} else if (out?.reason === 'compat-gate-failed') {
|
|
2389
|
+
const findings = Array.isArray(out?.compat?.findings) ? out.compat.findings.length : 0
|
|
2390
|
+
raiseDecisionTicket({
|
|
2391
|
+
level: 'yellow',
|
|
2392
|
+
title: '镜像升级后兼容门禁未通过',
|
|
2393
|
+
context: `镜像已切到 ${String(out?.to ?? '新版本')},但 compat 门禁未通过(findings=${findings}),子插件保持关闭。`,
|
|
2394
|
+
options: [{ value: 'retry', label: '重试升级' }, { value: 'ignore', label: '暂不处理' }],
|
|
2395
|
+
dedupeKey: 'mirror-upgrade:compat-gate-failed',
|
|
2396
|
+
sourceName: 'MirrorUpgrade',
|
|
2397
|
+
})
|
|
2398
|
+
} else if (out?.ok === true && out?.to && out.from !== out.to && !out.reason) {
|
|
2399
|
+
// 升级成功:新镜像要重启宿主才完全生效 → 红色 restart ticket(动作 confirm_restart)。
|
|
2400
|
+
await businessProducers.mirrorUpgradeRestartRequired({ from: out.from, to: out.to })
|
|
2401
|
+
}
|
|
2402
|
+
return out
|
|
2403
|
+
} catch (error) {
|
|
2404
|
+
await businessProducers.mirrorUpgradeFailed({
|
|
2405
|
+
from: 'unknown', reason: String(error?.message ?? error), level: 'red',
|
|
2406
|
+
})
|
|
2407
|
+
throw error
|
|
2408
|
+
}
|
|
2409
|
+
},
|
|
2009
2410
|
}
|
|
2010
2411
|
ctx.effect(() => ctx.provide(SERVICE.mirror, mirrorService))
|
|
2412
|
+
|
|
2413
|
+
// 特殊动作执行钩子:confirm_restart 不再只落库,交给 restart-guard 的 request
|
|
2414
|
+
// (它自己的审批/三重门禁/外部 supervisor 仍然生效;决策中心只负责触发)。
|
|
2415
|
+
try {
|
|
2416
|
+
const decisionCenterService = safeGet(SERVICE.decisionCenter)
|
|
2417
|
+
if (decisionCenterService && typeof decisionCenterService.registerActionHandler === 'function') {
|
|
2418
|
+
const unregisterAction = decisionCenterService.registerActionHandler('confirm_restart', async ({ ticket, payload } = {}) => {
|
|
2419
|
+
const restart = safeGet(SERVICE.restart)
|
|
2420
|
+
if (!restart || typeof restart.request !== 'function') return { ok: false, reason: 'restart-unavailable' }
|
|
2421
|
+
const input = payload && typeof payload === 'object' ? payload : {}
|
|
2422
|
+
return restart.request({
|
|
2423
|
+
reason: input.reason ?? `decision:${ticket?.id ?? 'unknown'}`,
|
|
2424
|
+
risk: input.risk ?? 'yellow',
|
|
2425
|
+
scope: input.scope ?? 'mother',
|
|
2426
|
+
origin: 'decision-center',
|
|
2427
|
+
digests: Array.isArray(input.digests) ? input.digests : undefined,
|
|
2428
|
+
forcedApproval: input.forcedApproval === true,
|
|
2429
|
+
})
|
|
2430
|
+
})
|
|
2431
|
+
ctx.effect(() => () => { try { unregisterAction?.() } catch { /* ignore */ } })
|
|
2432
|
+
}
|
|
2433
|
+
} catch { /* decision center optional */ }
|
|
2011
2434
|
// 启动后自检一次;兼容状态默认 subPluginsEnabled=false,直到门禁通过
|
|
2012
2435
|
const compatBootTimer = setTimeout(() => { void runCompatCheck() }, 1500)
|
|
2013
2436
|
compatBootTimer.unref?.()
|
|
@@ -2228,6 +2651,16 @@ export function apply(ctx, config) {
|
|
|
2228
2651
|
})
|
|
2229
2652
|
|
|
2230
2653
|
route('GET', `${prefix}/api/status`, (req, res) => json(res, 200, service.status()))
|
|
2654
|
+
// 重启守卫 / supervisor 契约(只读)。不触发重启;写操作仍只走审批 + 外部 supervisor。
|
|
2655
|
+
route('GET', `${prefix}/api/restart`, (req, res) => {
|
|
2656
|
+
const view = restartView()
|
|
2657
|
+
return json(res, 200, { ok: view.available === true && !view.error, ...view })
|
|
2658
|
+
})
|
|
2659
|
+
route('GET', `${prefix}/api/restart/selfcheck`, (req, res) => {
|
|
2660
|
+
const guard = safeGet(SERVICE.restart)
|
|
2661
|
+
if (!guard || typeof guard.selfCheck !== 'function') return json(res, 503, { ok: false, error: 'restart-guard-unavailable' })
|
|
2662
|
+
return json(res, 200, guard.selfCheck())
|
|
2663
|
+
})
|
|
2231
2664
|
route('GET', `${prefix}/api/upgrade/status`, (req, res) => {
|
|
2232
2665
|
let mirror = null
|
|
2233
2666
|
let essences = []
|
|
@@ -2240,10 +2673,304 @@ export function apply(ctx, config) {
|
|
|
2240
2673
|
return json(res, 200, buildUpgradeStatus({ version: FANG_VERSION, mirror, essences, compat, tasks: { failed: failedTasks } }))
|
|
2241
2674
|
})
|
|
2242
2675
|
route('GET', `${prefix}/api/tasks`, (req, res) => json(res, 200, { ok: true, tasks: service.listTasks() }))
|
|
2676
|
+
|
|
2677
|
+
// Decision center (瓮城·决策中心): one inbox for human attention. The plugin
|
|
2678
|
+
// owns tickets; this route is only the authenticated read/write surface.
|
|
2679
|
+
route('GET', `${prefix}/api/decisions`, (req, res) => {
|
|
2680
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2681
|
+
if (!center || typeof center.list !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2682
|
+
const query = new URL(String(req.url ?? '/'), 'http://x').searchParams
|
|
2683
|
+
const out = center.list({
|
|
2684
|
+
includeArchived: query.get('includeArchived') === '1' || query.get('includeArchived') === 'true',
|
|
2685
|
+
since: Number(query.get('since')) || 0,
|
|
2686
|
+
})
|
|
2687
|
+
return json(res, 200, { ok: true, ...out })
|
|
2688
|
+
})
|
|
2689
|
+
route('GET', `${prefix}/api/decisions/quota`, (req, res) => {
|
|
2690
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2691
|
+
if (!center || typeof center.quotaStatus !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2692
|
+
return json(res, 200, center.quotaStatus())
|
|
2693
|
+
})
|
|
2694
|
+
route('GET', `${prefix}/api/decisions/item`, (req, res) => {
|
|
2695
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2696
|
+
if (!center || typeof center.get !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2697
|
+
const query = new URL(String(req.url ?? '/'), 'http://x').searchParams
|
|
2698
|
+
const ticket = center.get(String(query.get('id') ?? ''))
|
|
2699
|
+
return ticket ? json(res, 200, { ok: true, ticket }) : json(res, 404, { ok: false, error: 'not-found' })
|
|
2700
|
+
})
|
|
2701
|
+
route('GET', `${prefix}/api/decisions/forks`, (req, res) => {
|
|
2702
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2703
|
+
if (!center || typeof center.forkAggregation !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2704
|
+
return json(res, 200, center.forkAggregation())
|
|
2705
|
+
})
|
|
2706
|
+
route('GET', `${prefix}/api/decisions/producers`, (req, res) => {
|
|
2707
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2708
|
+
if (!center || typeof center.producerCatalog !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2709
|
+
return json(res, 200, center.producerCatalog())
|
|
2710
|
+
})
|
|
2711
|
+
// 外部生产者桥(PM/PJM/Worker/HarnessMM/PluginUpdater/SuperAgent):
|
|
2712
|
+
// 只做带鉴权的 ingest;ticket 来源标记 external:<producer>,roleTrusted=false。
|
|
2713
|
+
route('POST', `${prefix}/api/decisions/ingest`, async (req, res) => {
|
|
2714
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2715
|
+
if (!center || typeof center.ingest !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2716
|
+
const body = await readBody(req)
|
|
2717
|
+
const out = center.ingest(body && typeof body === 'object' ? body : {})
|
|
2718
|
+
const status = out.ok ? 200
|
|
2719
|
+
: out.reason === 'title-required' || out.reason === 'options-required' || out.reason === 'gray-is-terminal' ? 400
|
|
2720
|
+
: 409
|
|
2721
|
+
return json(res, status, out)
|
|
2722
|
+
})
|
|
2723
|
+
// 决策中心实时推送:SSE。bus 事件 → 一条已鉴权流;无 SSE 时客户端仍可轮询。
|
|
2724
|
+
const decisionStreams = new Set()
|
|
2725
|
+
route('GET', `${prefix}/api/decisions/events`, (req, res) => {
|
|
2726
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2727
|
+
if (!center || typeof center.list !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2728
|
+
if (decisionStreams.size >= 20) return json(res, 429, { ok: false, error: 'too-many-event-streams' })
|
|
2729
|
+
const stream = openDecisionEventStream({ req, res, bus, center })
|
|
2730
|
+
decisionStreams.add(stream)
|
|
2731
|
+
const cleanup = () => {
|
|
2732
|
+
if (!decisionStreams.delete(stream)) return
|
|
2733
|
+
try { stream.close() } catch { /* ignore */ }
|
|
2734
|
+
}
|
|
2735
|
+
try { req.on?.('close', cleanup) } catch { /* ignore */ }
|
|
2736
|
+
try { res.on?.('close', cleanup) } catch { /* ignore */ }
|
|
2737
|
+
return undefined
|
|
2738
|
+
})
|
|
2739
|
+
try { child.effect?.(() => () => { for (const stream of decisionStreams) { try { stream.close() } catch { /* ignore */ } } decisionStreams.clear() }) } catch { /* fake webServer in tests */ }
|
|
2740
|
+
route('POST', `${prefix}/api/decisions/resolve`, async (req, res) => {
|
|
2741
|
+
const body = await readBody(req)
|
|
2742
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2743
|
+
if (!center || typeof center.resolve !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2744
|
+
if (Array.isArray(body?.ids)) {
|
|
2745
|
+
if (typeof center.resolveMany !== 'function') return json(res, 503, { ok: false, error: 'decision-center-batch-unavailable' })
|
|
2746
|
+
const out = center.resolveMany(body.ids, { option: body?.option, by: body?.by ?? 'fang-api', note: body?.note })
|
|
2747
|
+
return json(res, 200, out)
|
|
2748
|
+
}
|
|
2749
|
+
const out = (body?.actionId !== undefined && typeof center.resolveAction === 'function')
|
|
2750
|
+
? center.resolveAction(body?.id, body.actionId, body?.payload, { by: body?.by ?? 'fang-api', note: body?.note })
|
|
2751
|
+
: center.resolve(body?.id, body?.option, { by: body?.by ?? 'fang-api', note: body?.note })
|
|
2752
|
+
const status = out.ok ? 200
|
|
2753
|
+
: out.reason === 'not-found' ? 404
|
|
2754
|
+
: out.reason === 'option-required' || out.reason === 'unknown-option' ? 400
|
|
2755
|
+
: 409
|
|
2756
|
+
return json(res, status, out)
|
|
2757
|
+
})
|
|
2758
|
+
route('POST', `${prefix}/api/decisions/abandon`, async (req, res) => {
|
|
2759
|
+
const body = await readBody(req)
|
|
2760
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2761
|
+
if (!center || typeof center.abandon !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2762
|
+
if (Array.isArray(body?.ids)) {
|
|
2763
|
+
if (typeof center.abandonMany !== 'function') return json(res, 503, { ok: false, error: 'decision-center-batch-unavailable' })
|
|
2764
|
+
const out = center.abandonMany(body.ids, { by: body?.by ?? 'fang-api', note: body?.note })
|
|
2765
|
+
return json(res, 200, out)
|
|
2766
|
+
}
|
|
2767
|
+
const out = center.abandon(body?.id, { by: body?.by ?? 'fang-api', note: body?.note })
|
|
2768
|
+
return json(res, out.ok ? 200 : (out.reason === 'not-found' ? 404 : 409), out)
|
|
2769
|
+
})
|
|
2770
|
+
|
|
2771
|
+
route('GET', `${prefix}/api/decisions/ai`, (req, res) => {
|
|
2772
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2773
|
+
if (!center || typeof center.aiStatus !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2774
|
+
return json(res, 200, { ok: true, ...center.aiStatus() })
|
|
2775
|
+
})
|
|
2776
|
+
route('POST', `${prefix}/api/decisions/ai/test`, async (req, res) => {
|
|
2777
|
+
const body = await readBody(req)
|
|
2778
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2779
|
+
if (!center || typeof center.testAi !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2780
|
+
const out = await center.testAi(body ?? {})
|
|
2781
|
+
return json(res, out.ok ? 200 : (out.status === 429 ? 429 : 400), out)
|
|
2782
|
+
})
|
|
2783
|
+
route('POST', `${prefix}/api/decisions/ai/config`, async (req, res) => {
|
|
2784
|
+
const body = await readBody(req)
|
|
2785
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2786
|
+
if (!center || typeof center.configureAi !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2787
|
+
const out = center.configureAi(body ?? {})
|
|
2788
|
+
return json(res, out.ok ? 200 : 400, out)
|
|
2789
|
+
})
|
|
2790
|
+
route('POST', `${prefix}/api/decisions/ai/advise/stream`, async (req, res) => {
|
|
2791
|
+
const body = await readBody(req)
|
|
2792
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2793
|
+
if (!center || typeof center.advise !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2794
|
+
res.writeHead(200, {
|
|
2795
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
2796
|
+
'cache-control': 'no-store',
|
|
2797
|
+
'x-accel-buffering': 'no',
|
|
2798
|
+
connection: 'keep-alive',
|
|
2799
|
+
})
|
|
2800
|
+
try { res.flushHeaders?.() } catch { /* fake res */ }
|
|
2801
|
+
let closed = false
|
|
2802
|
+
let wrote = 0
|
|
2803
|
+
const send = (event, data) => {
|
|
2804
|
+
if (closed) return false
|
|
2805
|
+
try { res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); wrote += 1; return true } catch { return false }
|
|
2806
|
+
}
|
|
2807
|
+
try {
|
|
2808
|
+
send('start', { id: String(body?.id ?? '') })
|
|
2809
|
+
const out = typeof center.adviseStream === 'function'
|
|
2810
|
+
? await center.adviseStream(body?.id, (delta, text) => { send('delta', { delta, text }) })
|
|
2811
|
+
: await center.advise(body?.id)
|
|
2812
|
+
send(out.ok ? 'done' : 'error', out.ok ? { advice: out.advice, ticket: out.ticket } : out)
|
|
2813
|
+
} catch (error) {
|
|
2814
|
+
send('error', { ok: false, error: String(error?.message ?? error) })
|
|
2815
|
+
} finally {
|
|
2816
|
+
closed = true
|
|
2817
|
+
try { res.end() } catch { /* ignore */ }
|
|
2818
|
+
}
|
|
2819
|
+
})
|
|
2820
|
+
route('POST', `${prefix}/api/decisions/ai/advise`, async (req, res) => {
|
|
2821
|
+
const body = await readBody(req)
|
|
2822
|
+
const center = safeGet(SERVICE.decisionCenter)
|
|
2823
|
+
if (!center || typeof center.advise !== 'function') return json(res, 503, { ok: false, error: 'decision-center-unavailable' })
|
|
2824
|
+
const out = await center.advise(body?.id)
|
|
2825
|
+
const limited = out?.reason === 'ai-rate-limited' || out?.reason === 'ai-circuit-open' || out?.reason === 'ai-daily-quota-exceeded'
|
|
2826
|
+
if (limited && Number.isFinite(out?.retryAfterMs) && out.retryAfterMs > 0) {
|
|
2827
|
+
try { res.setHeader?.('retry-after', String(Math.ceil(out.retryAfterMs / 1000))) } catch { /* fake res */ }
|
|
2828
|
+
}
|
|
2829
|
+
return json(res, out.ok ? 200 : (out.reason === 'not-found' ? 404 : limited ? 429 : 409), out)
|
|
2830
|
+
})
|
|
2831
|
+
|
|
2832
|
+
// Mother-side approval aggregation: local approver + every live fork adapter.
|
|
2833
|
+
// A failed adapter is reported as degraded, never as an empty approval list.
|
|
2834
|
+
route('GET', `${prefix}/api/approvals`, async (req, res) => {
|
|
2835
|
+
const items = []
|
|
2836
|
+
const failed = []
|
|
2837
|
+
const approver = safeGet(SERVICE.approver)
|
|
2838
|
+
try {
|
|
2839
|
+
if (approver && typeof approver.pending === 'function') {
|
|
2840
|
+
for (const item of approver.pending() ?? []) {
|
|
2841
|
+
items.push({
|
|
2842
|
+
source: 'mother',
|
|
2843
|
+
taskId: null,
|
|
2844
|
+
approvalId: String(item?.id ?? ''),
|
|
2845
|
+
title: String(item?.title ?? ''),
|
|
2846
|
+
risk: String(item?.risk ?? 'unknown'),
|
|
2847
|
+
kind: String(item?.kind ?? 'unknown'),
|
|
2848
|
+
state: item?.state ?? 'pending',
|
|
2849
|
+
createdAt: item?.createdAt ?? null,
|
|
2850
|
+
deadlineAt: item?.deadlineAt ?? null,
|
|
2851
|
+
adapterOk: true,
|
|
2852
|
+
})
|
|
2853
|
+
}
|
|
2854
|
+
if (typeof approver.orphaned === 'function') {
|
|
2855
|
+
for (const item of approver.orphaned() ?? []) {
|
|
2856
|
+
items.push({
|
|
2857
|
+
source: 'mother',
|
|
2858
|
+
taskId: null,
|
|
2859
|
+
approvalId: String(item?.id ?? ''),
|
|
2860
|
+
title: String(item?.title ?? ''),
|
|
2861
|
+
risk: String(item?.risk ?? 'unknown'),
|
|
2862
|
+
kind: String(item?.kind ?? 'unknown'),
|
|
2863
|
+
state: 'orphaned',
|
|
2864
|
+
createdAt: item?.createdAt ?? null,
|
|
2865
|
+
deadlineAt: item?.deadlineAt ?? null,
|
|
2866
|
+
adapterOk: true,
|
|
2867
|
+
})
|
|
2868
|
+
}
|
|
2869
|
+
}
|
|
2870
|
+
} else {
|
|
2871
|
+
failed.push({ taskId: null, error: 'approver-unavailable' })
|
|
2872
|
+
}
|
|
2873
|
+
} catch (error) {
|
|
2874
|
+
failed.push({ taskId: null, error: String(error?.message ?? error) })
|
|
2875
|
+
}
|
|
2876
|
+
|
|
2877
|
+
const forkResults = await Promise.all([...tasks.values()]
|
|
2878
|
+
.filter((task) => task?.url)
|
|
2879
|
+
.map(async (task) => {
|
|
2880
|
+
if (task.adapter && task.adapter.ok === false) {
|
|
2881
|
+
return { task, ok: false, error: task.adapter.error ?? 'adapter-unavailable' }
|
|
2882
|
+
}
|
|
2883
|
+
const client = await remoteFor(task)
|
|
2884
|
+
if (!client) return { task, ok: false, error: 'remote-unavailable' }
|
|
2885
|
+
const result = await client.command(ADAPTER_OP.APPROVALS, {})
|
|
2886
|
+
const data = result?.data?.result ?? result?.data ?? {}
|
|
2887
|
+
if (!result?.ok || data?.ok === false) {
|
|
2888
|
+
return { task, ok: false, error: data?.error ?? result?.error ?? 'adapter-failed' }
|
|
2889
|
+
}
|
|
2890
|
+
const list = Array.isArray(data?.items) ? data.items
|
|
2891
|
+
: Array.isArray(data?.result?.items) ? data.result.items
|
|
2892
|
+
: []
|
|
2893
|
+
return { task, ok: true, items: list }
|
|
2894
|
+
}))
|
|
2895
|
+
for (const result of forkResults) {
|
|
2896
|
+
if (!result.ok) {
|
|
2897
|
+
failed.push({ taskId: result.task.taskId, error: result.error })
|
|
2898
|
+
continue
|
|
2899
|
+
}
|
|
2900
|
+
for (const item of result.items) {
|
|
2901
|
+
items.push({
|
|
2902
|
+
source: 'fork',
|
|
2903
|
+
taskId: result.task.taskId,
|
|
2904
|
+
approvalId: String(item?.id ?? item?.approvalId ?? ''),
|
|
2905
|
+
title: String(item?.title ?? ''),
|
|
2906
|
+
risk: String(item?.risk ?? 'unknown'),
|
|
2907
|
+
kind: String(item?.kind ?? 'unknown'),
|
|
2908
|
+
state: item?.state ?? 'pending',
|
|
2909
|
+
createdAt: item?.createdAt ?? null,
|
|
2910
|
+
deadlineAt: item?.deadlineAt ?? null,
|
|
2911
|
+
adapterOk: true,
|
|
2912
|
+
})
|
|
2913
|
+
}
|
|
2914
|
+
}
|
|
2915
|
+
items.sort((a, b) => (Number(a.deadlineAt) || Number.MAX_SAFE_INTEGER) - (Number(b.deadlineAt) || Number.MAX_SAFE_INTEGER))
|
|
2916
|
+
return json(res, 200, { ok: true, degraded: failed.length > 0, items, failed })
|
|
2917
|
+
})
|
|
2918
|
+
|
|
2919
|
+
// Decide one approval by source. The response is the real adapter/approver result;
|
|
2920
|
+
// stale or unknown approvals return 409 instead of pretending success.
|
|
2921
|
+
route('POST', `${prefix}/api/approvals/decide`, async (req, res) => {
|
|
2922
|
+
const body = await readBody(req)
|
|
2923
|
+
const source = String(body?.source ?? '')
|
|
2924
|
+
const taskId = body?.taskId === undefined || body?.taskId === null ? null : String(body.taskId)
|
|
2925
|
+
const approvalId = String(body?.approvalId ?? '').trim()
|
|
2926
|
+
const raw = body?.outcome ?? body?.decision
|
|
2927
|
+
const outcome = raw === 'approve' ? 'approved' : raw === 'deny' ? 'denied' : String(raw ?? '')
|
|
2928
|
+
const by = String(body?.by ?? 'fang-api')
|
|
2929
|
+
const note = body?.note === undefined || body?.note === null ? null : String(body.note)
|
|
2930
|
+
if (!approvalId) return json(res, 400, { ok: false, error: 'approval-id-required' })
|
|
2931
|
+
if (outcome !== 'approved' && outcome !== 'denied') return json(res, 400, { ok: false, error: 'bad-outcome', allowed: ['approved', 'denied'] })
|
|
2932
|
+
|
|
2933
|
+
if (source === 'mother') {
|
|
2934
|
+
const approver = safeGet(SERVICE.approver)
|
|
2935
|
+
if (!approver || typeof approver.decide !== 'function') {
|
|
2936
|
+
return json(res, 503, { ok: false, source, error: 'approver-unavailable' })
|
|
2937
|
+
}
|
|
2938
|
+
try {
|
|
2939
|
+
const result = approver.decide(approvalId, outcome, { by, note })
|
|
2940
|
+
if (!result || result.ok === false) {
|
|
2941
|
+
const stale = result?.reason === 'not-found' || result?.reason === 'not-pending'
|
|
2942
|
+
return json(res, stale ? 409 : 400, { ok: false, source, approvalId, error: result?.reason ?? 'decide-failed' })
|
|
2943
|
+
}
|
|
2944
|
+
audit(AUDIT.APPROVAL_DECIDED, { source, taskId: null, approvalId, outcome, by, note })
|
|
2945
|
+
return json(res, 200, { ok: true, source, taskId: null, approvalId, outcome, by, result })
|
|
2946
|
+
} catch (error) {
|
|
2947
|
+
return json(res, 500, { ok: false, source, approvalId, error: String(error?.message ?? error) })
|
|
2948
|
+
}
|
|
2949
|
+
}
|
|
2950
|
+
|
|
2951
|
+
if (source === 'fork') {
|
|
2952
|
+
if (!taskId) return json(res, 400, { ok: false, source, error: 'task-id-required' })
|
|
2953
|
+
const task = tasks.get(taskId)
|
|
2954
|
+
if (!task) return json(res, 404, { ok: false, source, taskId, error: 'unknown-task' })
|
|
2955
|
+
const client = await remoteFor(task)
|
|
2956
|
+
if (!client) return json(res, 503, { ok: false, source, taskId, error: 'remote-unavailable' })
|
|
2957
|
+
const result = await client.command(ADAPTER_OP.APPROVAL_DECIDE, { id: approvalId, outcome, by, note })
|
|
2958
|
+
const data = result?.data?.result ?? result?.data ?? {}
|
|
2959
|
+
if (!result?.ok || data?.ok === false) {
|
|
2960
|
+
const stale = data?.code === 'not-found' || data?.code === 'conflict'
|
|
2961
|
+
return json(res, stale ? 409 : 502, { ok: false, source, taskId, approvalId, error: data?.error ?? result?.error ?? 'adapter-failed' })
|
|
2962
|
+
}
|
|
2963
|
+
audit(AUDIT.APPROVAL_DECIDED, { source, taskId, approvalId, outcome, by, note })
|
|
2964
|
+
return json(res, 200, { ok: true, source, taskId, approvalId, outcome, by, result: data })
|
|
2965
|
+
}
|
|
2966
|
+
|
|
2967
|
+
return json(res, 400, { ok: false, error: 'bad-source', allowed: ['mother', 'fork'] })
|
|
2968
|
+
})
|
|
2969
|
+
|
|
2243
2970
|
route('POST', `${prefix}/api/tasks/create`, async (req, res) => {
|
|
2244
2971
|
const body = await readBody(req)
|
|
2245
2972
|
try {
|
|
2246
|
-
const out = await service.createTask({ title: body?.title, template: body?.template, collaborators: body?.collaborators, essenceId: body?.essenceId })
|
|
2973
|
+
const out = await service.createTask({ title: body?.title, template: body?.template, collaborators: body?.collaborators, essenceId: body?.essenceId, importSession: body?.importSession, seed: body?.seed })
|
|
2247
2974
|
return json(res, out.ok ? 200 : 409, out)
|
|
2248
2975
|
} catch (error) {
|
|
2249
2976
|
return json(res, 500, { ok: false, error: String(error?.message ?? error) })
|
|
@@ -2310,6 +3037,21 @@ export function apply(ctx, config) {
|
|
|
2310
3037
|
})
|
|
2311
3038
|
// v1 兼容路由
|
|
2312
3039
|
route('GET', `${prefix}/api/forks`, (req, res) => json(res, 200, { ok: true, forks: service.listForks() }))
|
|
3040
|
+
routeMethods(`${prefix}/api/forks/supervision`, {
|
|
3041
|
+
GET: (req, res) => json(res, 200, service.forkSupervision()),
|
|
3042
|
+
POST: async (req, res) => {
|
|
3043
|
+
const body = await readBody(req)
|
|
3044
|
+
const out = service.setForkSupervision(body ?? {})
|
|
3045
|
+
return json(res, out.ok ? 200 : 400, out)
|
|
3046
|
+
},
|
|
3047
|
+
})
|
|
3048
|
+
// watchdog 启动时的分身自动恢复;只拉起已登记但没在跑的非归档任务。
|
|
3049
|
+
route('POST', `${prefix}/api/forks/autostart`, async (req, res) => {
|
|
3050
|
+
const body = await readBody(req)
|
|
3051
|
+
const taskIds = Array.isArray(body?.taskIds) ? body.taskIds : null
|
|
3052
|
+
const out = await service.autostartForks({ taskIds })
|
|
3053
|
+
return json(res, out.ok ? 200 : 503, out)
|
|
3054
|
+
})
|
|
2313
3055
|
route('POST', `${prefix}/api/forks/create`, async (req, res) => {
|
|
2314
3056
|
const body = await readBody(req)
|
|
2315
3057
|
const out = await service.fork({ taskTitle: body?.taskTitle ?? body?.title })
|
|
@@ -2502,12 +3244,6 @@ export function apply(ctx, config) {
|
|
|
2502
3244
|
return json(res, 400, { ok: false, error: String(error?.message ?? error) })
|
|
2503
3245
|
}
|
|
2504
3246
|
})
|
|
2505
|
-
route('POST', `${prefix}/api/essence/default`, async (req, res) => {
|
|
2506
|
-
const body = await readBody(req)
|
|
2507
|
-
try { return json(res, 200, { ok: true, default: mirrorService.setDefaultEssence(String(body?.essenceId ?? '')) }) } catch (error) {
|
|
2508
|
-
return json(res, 400, { ok: false, error: String(error?.message ?? error) })
|
|
2509
|
-
}
|
|
2510
|
-
})
|
|
2511
3247
|
route('GET', `${prefix}/api/essence/download`, (req, res) => {
|
|
2512
3248
|
const query = new URL(String(req.url ?? '/'), 'http://x').searchParams
|
|
2513
3249
|
try {
|
|
@@ -2654,7 +3390,12 @@ export function apply(ctx, config) {
|
|
|
2654
3390
|
// so a restart/crash can offer recovery. Nothing is auto-sent.
|
|
2655
3391
|
routeMethods(`${prefix}/api/composer/journal`, {
|
|
2656
3392
|
GET: (req, res) => {
|
|
2657
|
-
const
|
|
3393
|
+
const query = new URL(String(req.url ?? '/'), 'http://x').searchParams
|
|
3394
|
+
const key = query.get('key') || ''
|
|
3395
|
+
// list=1 is the recovery list: every saved session draft/queue, newest first.
|
|
3396
|
+
if (!key && query.get('list') === '1') {
|
|
3397
|
+
return json(res, 200, { ok: true, entries: composerJournal.list() })
|
|
3398
|
+
}
|
|
2658
3399
|
if (!key) return json(res, 400, { ok: false, error: 'journal-key-required' })
|
|
2659
3400
|
return json(res, 200, { ok: true, entry: composerJournal.get(key) })
|
|
2660
3401
|
},
|
|
@@ -2670,6 +3411,37 @@ export function apply(ctx, config) {
|
|
|
2670
3411
|
},
|
|
2671
3412
|
})
|
|
2672
3413
|
|
|
3414
|
+
// Restore saved queue rows into the official Session inbox WITHOUT waking the
|
|
3415
|
+
// agent. The queue journal is a recovery surface; it must not send messages.
|
|
3416
|
+
route('POST', `${prefix}/api/composer/queue`, async (req, res) => {
|
|
3417
|
+
const body = await readBody(req)
|
|
3418
|
+
const sessionId = String(body?.sessionId ?? '').trim()
|
|
3419
|
+
const items = Array.isArray(body?.items) ? body.items : []
|
|
3420
|
+
if (!sessionId) return json(res, 400, { ok: false, error: 'session-id-required' })
|
|
3421
|
+
if (items.length === 0) return json(res, 200, { ok: true, queued: 0, failed: 0 })
|
|
3422
|
+
const agents = safeGet('agents')
|
|
3423
|
+
const agent = agents?.get?.(sessionId)
|
|
3424
|
+
if (!agent || typeof agent.send !== 'function') {
|
|
3425
|
+
return json(res, 409, { ok: false, error: 'session-not-live' })
|
|
3426
|
+
}
|
|
3427
|
+
let queued = 0
|
|
3428
|
+
let failed = 0
|
|
3429
|
+
for (const item of items.slice(0, 100)) {
|
|
3430
|
+
const text = String(item?.text ?? '').trim().slice(0, 4000)
|
|
3431
|
+
if (!text) { failed += 1; continue }
|
|
3432
|
+
try {
|
|
3433
|
+
agent.send({
|
|
3434
|
+
id: newId('msg'),
|
|
3435
|
+
role: 'user',
|
|
3436
|
+
content: [{ type: 'text', text }],
|
|
3437
|
+
source: { kind: 'user' },
|
|
3438
|
+
}, 'next-turn', false)
|
|
3439
|
+
queued += 1
|
|
3440
|
+
} catch { failed += 1 }
|
|
3441
|
+
}
|
|
3442
|
+
return json(res, 200, { ok: true, queued, failed })
|
|
3443
|
+
})
|
|
3444
|
+
|
|
2673
3445
|
// v3.0.8 contract: an unknown /fang/api/* path must be a JSON 404 under the
|
|
2674
3446
|
// same Host/Origin/token gate — not an unauthenticated empty 404 from the host.
|
|
2675
3447
|
// Exact routes above win because the webServer matches exact before prefix.
|
|
@@ -2682,6 +3454,10 @@ export function apply(ctx, config) {
|
|
|
2682
3454
|
route('POST', `${prefix}/api/essence/default`, async (req, res) => {
|
|
2683
3455
|
const body = await readBody(req)
|
|
2684
3456
|
try {
|
|
3457
|
+
// 同一路径两用:显式 essenceId = 设为默认;否则走默认元宝 ensure(apply/force/mode)。
|
|
3458
|
+
if (body?.essenceId) {
|
|
3459
|
+
return json(res, 200, { ok: true, default: mirrorService.setDefaultEssence(String(body.essenceId)) })
|
|
3460
|
+
}
|
|
2685
3461
|
const out = await mirrorService.ensureDefaultEssence({ apply: body?.apply === true, force: body?.force === true, mode: body?.mode === 'preset' ? 'preset' : 'copy-local' })
|
|
2686
3462
|
return json(res, out.ok === false ? 409 : 200, out)
|
|
2687
3463
|
} catch (error) {
|