@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.
Files changed (38) hide show
  1. package/client.js +1511 -1
  2. package/cordis.patch.yml +9 -0
  3. package/package.json +7 -3
  4. package/src/compose.mjs +4 -1
  5. package/src/kernel/paths.mjs +9 -1
  6. package/src/kernel/role.mjs +1 -0
  7. package/src/kernel/types.mjs +5 -1
  8. package/src/lib/ai-secret-store.mjs +202 -0
  9. package/src/lib/boot-guard.mjs +182 -0
  10. package/src/lib/business-producers.mjs +109 -0
  11. package/src/lib/compat.mjs +1 -1
  12. package/src/lib/composer-journal.mjs +8 -0
  13. package/src/lib/decision-events.mjs +129 -0
  14. package/src/lib/decision-ingest-client.mjs +41 -0
  15. package/src/lib/decision-outbox.mjs +129 -0
  16. package/src/lib/desktop-launch.mjs +138 -0
  17. package/src/lib/fork-supervision-settings.mjs +58 -0
  18. package/src/lib/mirror-official-source.mjs +93 -0
  19. package/src/lib/mirror.mjs +10 -3
  20. package/src/lib/producer-contract.mjs +162 -0
  21. package/src/lib/restart-contract.mjs +650 -0
  22. package/src/lib/rule-registry.mjs +69 -0
  23. package/src/lib/ssrf-guard.mjs +170 -0
  24. package/src/lib/umbrella.mjs +143 -18
  25. package/src/plugins/adapter.mjs +31 -2
  26. package/src/plugins/approver.mjs +423 -40
  27. package/src/plugins/decision-center.mjs +2255 -0
  28. package/src/plugins/forker.mjs +20 -1
  29. package/src/plugins/healer.mjs +53 -20
  30. package/src/plugins/imports.mjs +48 -0
  31. package/src/plugins/orchestrator.mjs +844 -46
  32. package/src/plugins/restart-guard.mjs +645 -52
  33. package/src/plugins/scorer.mjs +227 -15
  34. package/src/plugins/umbrella.mjs +18 -14
  35. package/tools/boot-guard.mjs +95 -0
  36. package/tools/decision-ingest.mjs +53 -0
  37. package/tools/desktop-launch.mjs +71 -0
  38. package/tools/fangctl.mjs +229 -1
@@ -0,0 +1,129 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
+ //
4
+ // decision-events — 决策中心 bus 事件 → 一条 HTTP SSE 流。
5
+ //
6
+ // 只负责「把事件写进一个已鉴权的响应」:路由层负责 auth/Host/Origin,本模块不碰 token。
7
+ // 事件:ready(初始 rev/计数)、ticket(created/updated)、ping(心跳)。
8
+ // 客户端断开/出错即退订,绝不把 bus listener 泄漏到下一个请求。
9
+ export const DECISION_EVENT_TOPICS = Object.freeze([
10
+ 'fang/decision-created',
11
+ 'fang/decision-updated',
12
+ ])
13
+
14
+ /**
15
+ * @param {object} input
16
+ * @param {any} input.req
17
+ * @param {any} input.res 已通过路由鉴权的 Node 响应
18
+ * @param {{on:Function,off?:Function}} input.bus kernel bus
19
+ * @param {{list?:Function}} [input.center] 决策中心服务(只读 list 用于 ready)
20
+ * @param {number} [input.heartbeatMs]
21
+ * @param {Function} [input.now]
22
+ * @returns {{close:Function, send:Function, headers:object, closed:boolean}}
23
+ */
24
+ export function openDecisionEventStream({
25
+ req,
26
+ res,
27
+ bus,
28
+ center = null,
29
+ heartbeatMs = 15000,
30
+ now = () => Date.now(),
31
+ } = {}) {
32
+ if (!req || !res || !bus || typeof bus.on !== 'function') {
33
+ throw new Error('openDecisionEventStream: req/res/bus required')
34
+ }
35
+ const headers = {
36
+ 'content-type': 'text/event-stream; charset=utf-8',
37
+ 'cache-control': 'no-store, no-cache, must-revalidate',
38
+ connection: 'keep-alive',
39
+ 'x-accel-buffering': 'no',
40
+ }
41
+ res.writeHead(200, headers)
42
+ try { res.flushHeaders?.() } catch { /* fake/undici responses may not support it */ }
43
+
44
+ let closed = false
45
+ const cleanups = []
46
+ const send = (event, data) => {
47
+ if (closed) return false
48
+ try {
49
+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)
50
+ return true
51
+ } catch {
52
+ close()
53
+ return false
54
+ }
55
+ }
56
+ const close = () => {
57
+ if (closed) return
58
+ closed = true
59
+ for (const off of cleanups.reverse()) {
60
+ try { if (typeof off === 'function') off() } catch { /* ignore */ }
61
+ }
62
+ cleanups.length = 0
63
+ try { res.end() } catch { /* ignore */ }
64
+ }
65
+
66
+ // ready:客户端据此判断「这确实是新流的首帧」,而不是把旧缓存当实时。
67
+ let initial = null
68
+ try { initial = typeof center?.list === 'function' ? center.list({ includeArchived: false }) : null } catch { initial = null }
69
+ send('ready', {
70
+ at: now(),
71
+ rev: Number(initial?.rev) || 0,
72
+ counts: initial?.counts ?? null,
73
+ })
74
+
75
+ for (const topic of DECISION_EVENT_TOPICS) {
76
+ const handler = (ticket) => {
77
+ send('ticket', {
78
+ at: now(),
79
+ type: topic.endsWith('-created') ? 'created' : 'updated',
80
+ // 紧凑提示字段(客户端也可只按 rev 拉增量),ticket 一并带上避免多一跳。
81
+ rev: Number(ticket?.rev) || 0,
82
+ ids: ticket?.id ? [String(ticket.id)] : [],
83
+ ticket,
84
+ })
85
+ }
86
+ const off = bus.on(topic, handler)
87
+ cleanups.push(() => { try { if (typeof off === 'function') off(); else bus.off?.(topic, handler) } catch { /* ignore */ } })
88
+ }
89
+
90
+ const heartbeat = setInterval(() => {
91
+ if (!send('ping', { at: now() })) return
92
+ }, Math.max(10, Number(heartbeatMs) || 15000))
93
+ heartbeat.unref?.()
94
+ cleanups.push(() => clearInterval(heartbeat))
95
+
96
+ for (const [target, event] of [[req, 'close'], [req, 'aborted'], [res, 'close'], [res, 'error']]) {
97
+ if (target && typeof target.on === 'function') {
98
+ const fn = () => close()
99
+ try { target.on(event, fn) } catch { /* ignore */ }
100
+ cleanups.push(() => { try { target.removeListener?.(event, fn) } catch { /* ignore */ } })
101
+ }
102
+ }
103
+
104
+ return { close, send, headers, get closed() { return closed } }
105
+ }
106
+
107
+ /** 紧凑的 SSE 帧解析(客户端/测试共用;不依赖 EventSource)。 */
108
+ export function parseSseFrames(buffer = '') {
109
+ const frames = []
110
+ let rest = String(buffer)
111
+ for (;;) {
112
+ const index = rest.indexOf('\n\n')
113
+ if (index < 0) break
114
+ const raw = rest.slice(0, index)
115
+ rest = rest.slice(index + 2)
116
+ let event = 'message'
117
+ const dataLines = []
118
+ for (const line of raw.split('\n')) {
119
+ if (line.startsWith('event:')) event = line.slice(6).trim()
120
+ else if (line.startsWith('data:')) dataLines.push(line.slice(5).trimStart())
121
+ }
122
+ let data = null
123
+ if (dataLines.length) {
124
+ try { data = JSON.parse(dataLines.join('\n')) } catch { data = null }
125
+ }
126
+ frames.push({ event, data })
127
+ }
128
+ return { frames, rest }
129
+ }
@@ -0,0 +1,41 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
+ //
4
+ // decision-ingest-client — 给独立进程(PJM/Worker/HarnessMM/PluginUpdater/SuperAgent)
5
+ // 用的 fork 侧 ingest 客户端:
6
+ // * 从母体 dataDir 发现 endpoint + token(DSH_FANG_MOTHER 或显式路径)
7
+ // * 直连 POST /fang/api/decisions/ingest
8
+ // * 失败时落本地 outbox,可 flush 重放(耐久,不丢 ticket)
9
+ // 注意:客户端存在 ≠ 业务已接;外部进程仍需在事件处调用 .submit()。
10
+ import process from 'node:process'
11
+
12
+ import { createDecisionOutbox, resolveMotherTarget } from './decision-outbox.mjs'
13
+
14
+ export function createForkIngestClient({
15
+ dataDir,
16
+ motherDataDir = process.env.DSH_FANG_MOTHER,
17
+ fetchImpl,
18
+ logger,
19
+ } = {}) {
20
+ const dir = String(dataDir ?? '').trim()
21
+ if (!dir) throw new TypeError('createForkIngestClient: dataDir required (outbox directory)')
22
+ const outbox = createDecisionOutbox({ dataDir: dir, fetchImpl, logger })
23
+ const target = () => resolveMotherTarget(motherDataDir)
24
+ return {
25
+ target,
26
+ motherDataDir: String(motherDataDir ?? ''),
27
+ /** 直连母体;失败自动落 outbox,返回 {ok, queued, ticket, outboxId?}。 */
28
+ submit(payload) {
29
+ return outbox.submit(payload, { motherDataDir })
30
+ },
31
+ flush() {
32
+ return outbox.flush({ motherDataDir })
33
+ },
34
+ pending() {
35
+ return outbox.pending()
36
+ },
37
+ list() {
38
+ return outbox.list()
39
+ },
40
+ }
41
+ }
@@ -0,0 +1,129 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
+ //
4
+ // decision-outbox — fork 侧的「向母体提交 decision」耐久 outbox(P4 地基)。
5
+ //
6
+ // 方向:fork → mother 走 HTTP ingest,不走 adapter(adapter 是 mother → fork 控制通道)。
7
+ // 母体地址/token 从 DSH_FANG_MOTHER 指向的母体 dataDir 读取:
8
+ // <motherDataDir>/endpoint.json { url }
9
+ // <motherDataDir>/fang-auth.json { token }(0600)
10
+ //
11
+ // 现状:库本身可用,但还没有接进 fork 的 Agent tool / umbrella ASK;未接 = 不算接线。
12
+ import fs from 'node:fs'
13
+ import path from 'node:path'
14
+ import { randomUUID } from 'node:crypto'
15
+
16
+ import { ensureDir, readJson, writeJsonAtomic } from '../kernel/index.mjs'
17
+
18
+ export const OUTBOX_DIRNAME = 'decision-outbox'
19
+
20
+ export function resolveMotherTarget(motherDataDir) {
21
+ const dir = String(motherDataDir ?? '').trim()
22
+ if (!dir) return { ok: false, reason: 'mother-data-dir-required' }
23
+ const endpoint = readJson(path.join(dir, 'endpoint.json'), null)
24
+ const auth = readJson(path.join(dir, 'fang-auth.json'), null)
25
+ const url = String(endpoint?.url ?? '').replace(/\/+$/, '')
26
+ const token = String(auth?.token ?? '')
27
+ if (!url || !token) return { ok: false, reason: 'mother-endpoint-unavailable', url, hasToken: Boolean(token) }
28
+ return { ok: true, url, token }
29
+ }
30
+
31
+ /**
32
+ * @param {{dataDir:string, fetchImpl?:Function, logger?:object, now?:()=>number}} options
33
+ */
34
+ export function createDecisionOutbox(options = {}) {
35
+ const dataDir = String(options.dataDir ?? '')
36
+ if (!dataDir) throw new Error('createDecisionOutbox: dataDir required')
37
+ const dir = path.join(dataDir, OUTBOX_DIRNAME)
38
+ const fetchImpl = typeof options.fetchImpl === 'function' ? options.fetchImpl : globalThis.fetch
39
+ const now = typeof options.now === 'function' ? options.now : () => Date.now()
40
+ const log = (level, message) => { try { options.logger?.[level]?.(`[decision-outbox] ${message}`) } catch { /* ignore */ } }
41
+ const fileOf = (id) => path.join(dir, `${id}.json`)
42
+ const listIds = () => {
43
+ try { return fs.readdirSync(dir).filter((name) => name.endsWith('.json')).map((name) => name.slice(0, -5)).sort() } catch { return [] }
44
+ }
45
+
46
+ function enqueue(payload) {
47
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw new TypeError('enqueue: payload object required')
48
+ ensureDir(dir)
49
+ const id = `out-${now()}-${randomUUID()}`
50
+ const record = { id, payload, createdAt: now(), attempts: 0, nextAt: 0 }
51
+ writeJsonAtomic(fileOf(id), record)
52
+ return record
53
+ }
54
+
55
+ async function post(target, payload) {
56
+ const response = await fetchImpl(`${target.url}/fang/api/decisions/ingest`, {
57
+ method: 'POST',
58
+ headers: { 'content-type': 'application/json', 'x-fang-auth': target.token },
59
+ body: JSON.stringify(payload),
60
+ })
61
+ const text = await response.text().catch(() => '')
62
+ let body = null
63
+ try { body = JSON.parse(text) } catch { body = null }
64
+ return { ok: response.ok, status: response.status, body }
65
+ }
66
+
67
+ /** 先直连母体;失败(含母体不可达)就落 outbox,返回 queued:true。 */
68
+ async function submit(payload, { motherDataDir } = {}) {
69
+ const target = resolveMotherTarget(motherDataDir)
70
+ if (!target.ok) {
71
+ const record = enqueue(payload)
72
+ return { ok: true, queued: true, outboxId: record.id, ticket: null, reason: target.reason }
73
+ }
74
+ try {
75
+ const result = await post(target, payload)
76
+ if (result.ok) return { ok: true, queued: false, status: result.status, ticket: result.body?.ticket ?? null }
77
+ const record = enqueue(payload)
78
+ record.lastStatus = result.status
79
+ writeJsonAtomic(fileOf(record.id), record)
80
+ return { ok: true, queued: true, outboxId: record.id, ticket: null, reason: `http-${result.status}` }
81
+ } catch (error) {
82
+ const record = enqueue(payload)
83
+ log('warn', `submit queued: ${String(error?.message ?? error)}`)
84
+ return { ok: true, queued: true, outboxId: record.id, ticket: null, reason: 'network-error' }
85
+ }
86
+ }
87
+
88
+ /** 重放 outbox;成功即删文件,失败保留并写退避 nextAt。 */
89
+ async function flush({ motherDataDir, limit = 50 } = {}) {
90
+ const target = resolveMotherTarget(motherDataDir)
91
+ const ids = listIds()
92
+ if (!target.ok) return { ok: false, reason: target.reason, sent: 0, failed: 0, remaining: ids.length }
93
+ let sent = 0
94
+ let failed = 0
95
+ for (const id of ids.slice(0, Math.max(0, limit))) {
96
+ const record = readJson(fileOf(id), null)
97
+ if (!record?.payload) { try { fs.unlinkSync(fileOf(id)) } catch { /* ignore */ } continue }
98
+ try {
99
+ const result = await post(target, record.payload)
100
+ if (result.ok) {
101
+ try { fs.unlinkSync(fileOf(id)) } catch { /* ignore */ }
102
+ sent += 1
103
+ } else {
104
+ record.attempts = (Number(record.attempts) || 0) + 1
105
+ record.nextAt = now() + Math.min(60_000, 2 ** record.attempts * 1000)
106
+ record.lastStatus = result.status
107
+ writeJsonAtomic(fileOf(id), record)
108
+ failed += 1
109
+ }
110
+ } catch (error) {
111
+ record.attempts = (Number(record.attempts) || 0) + 1
112
+ record.nextAt = now() + Math.min(60_000, 2 ** record.attempts * 1000)
113
+ record.lastError = String(error?.message ?? error).slice(0, 300)
114
+ writeJsonAtomic(fileOf(id), record)
115
+ failed += 1
116
+ }
117
+ }
118
+ return { ok: true, sent, failed, remaining: listIds().length }
119
+ }
120
+
121
+ return {
122
+ dir,
123
+ enqueue,
124
+ submit,
125
+ flush,
126
+ pending: () => listIds().length,
127
+ list: () => listIds().map((id) => readJson(fileOf(id), null)).filter(Boolean),
128
+ }
129
+ }
@@ -0,0 +1,138 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
+ //
4
+ // desktop-launch — 把 DSH Desktop 启动挂到 restart-supervisor 下的「真实入口」适配器。
5
+ //
6
+ // 它不修改 DSH Desktop 安装目录,也不自动启动;只负责构造:
7
+ // node tools/restart-supervisor.mjs [--execute] --data-root <dir> -- <desktop-exe> <args...>
8
+ // 由 supervisor 决定:退出码 75 + 已武装清单 + pid 匹配才重启;默认 dry-run。
9
+ import fs from 'node:fs'
10
+ import path from 'node:path'
11
+ import { fileURLToPath } from 'node:url'
12
+
13
+ import {
14
+ applyDisabledRows,
15
+ checkBundleRows,
16
+ findFangPackageDir,
17
+ readBundleRows,
18
+ readPackageName,
19
+ } from './boot-guard.mjs'
20
+
21
+ const isExecutableFile = (file) => {
22
+ try { return fs.statSync(file).isFile() } catch { return false }
23
+ }
24
+
25
+ /** 从 env/DSH 参数推断本机 desktop profile(用于无 --profile-dir 时自动自检)。 */
26
+ export function detectDesktopProfileDir({ env = process.env, args = [] } = {}) {
27
+ const hasPackage = (dir) => {
28
+ try { return isExecutableFile(path.join(String(dir), 'package.json')) } catch { return false }
29
+ }
30
+ const explicit = String(env?.DSH_PROFILE_DIR ?? '').trim()
31
+ if (explicit && hasPackage(explicit)) return path.resolve(explicit)
32
+ let profile = String(env?.DSH_PROFILE ?? '').trim()
33
+ if (!profile) {
34
+ const index = Array.isArray(args) ? args.findIndex((value) => value === '--profile' || value === '-p') : -1
35
+ if (index >= 0 && args[index + 1]) profile = String(args[index + 1])
36
+ else {
37
+ const inline = Array.isArray(args) ? args.find((value) => value.startsWith('--profile=')) : null
38
+ if (inline) profile = inline.slice('--profile='.length)
39
+ }
40
+ }
41
+ if (!profile) profile = 'desktop'
42
+ const home = String(env?.DSH_HOME ?? '').trim() || path.join(String(env?.USERPROFILE ?? env?.HOME ?? '').trim() || '.', '.dsh')
43
+ if (!home) return ''
44
+ const candidate = path.join(path.resolve(home), 'profiles', profile)
45
+ return hasPackage(candidate) ? candidate : ''
46
+ }
47
+
48
+ const pidAlive = (pid) => {
49
+ const value = Number(pid)
50
+ if (!Number.isInteger(value) || value <= 0) return false
51
+ try { process.kill(value, 0); return true } catch (error) { return error?.code === 'EPERM' }
52
+ }
53
+
54
+ /** 读取 restart-guard 写的 boot-state;上一进程 booting/crashed 且 pid 已死 = 启动期崩溃。 */
55
+ export function readUncleanBoot(dataRoot) {
56
+ const root = String(dataRoot ?? '').trim()
57
+ if (!root) return null
58
+ try {
59
+ const file = path.join(path.resolve(root), 'restart', 'boot-state.json')
60
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'))
61
+ if (!raw || (raw.state !== 'booting' && raw.state !== 'crashed')) return null
62
+ if (Number(raw.pid) === process.pid) return null
63
+ if (pidAlive(raw.pid)) return null
64
+ return { state: String(raw.state), pid: Number(raw.pid) || null, at: Number(raw.at) || 0, error: raw.error ?? null }
65
+ } catch { return null }
66
+ }
67
+
68
+ /**
69
+ * 启动前跑 boot-guard:失败时可按“安全模式”禁用全部 fang 行。
70
+ * 默认不写 profile;调用方显式 safeModeOnFailure=true 才会改(会先备份)。
71
+ * dataRoot 给出时,若上次 boot-state 为 booting/crashed(启动期崩溃),同样走安全模式熔断。
72
+ */
73
+ export function runBootGuard(profileDir, { dataRoot = '', safeModeOnFailure = false, timeoutMs = 8000 } = {}) {
74
+ const dir = String(profileDir ?? '').trim()
75
+ if (!dir) return { ok: true, skipped: 'no-profile-dir' }
76
+ const resolved = path.resolve(dir)
77
+ if (!isExecutableFile(path.join(resolved, 'package.json'))) return { ok: false, error: 'profile-package-missing', profileDir: resolved }
78
+ const pkgDir = findFangPackageDir(resolved)
79
+ if (!pkgDir) return { ok: true, skipped: 'fang-package-not-found', profileDir: resolved }
80
+ const parsed = readBundleRows(pkgDir)
81
+ if (!parsed.ok) return { ok: false, error: 'bundle-patch-invalid', detail: parsed.error, profileDir: resolved }
82
+ const uncleanBoot = readUncleanBoot(dataRoot)
83
+ const disableAllForSafeMode = (reason, findings) => {
84
+ const applied = applyDisabledRows(resolved, parsed.rows.map((row) => row.id))
85
+ if (!applied.ok) return { ok: false, error: 'safe-mode-apply-failed', detail: applied.error, findings, profileDir: resolved, reason }
86
+ return { ok: true, safeModeApplied: true, reason, applied, findings, checked: findings.length, profileDir: resolved, packageDir: pkgDir }
87
+ }
88
+ if (uncleanBoot) {
89
+ if (!safeModeOnFailure) return { ok: false, error: 'unclean-boot', uncleanBoot, profileDir: resolved, packageDir: pkgDir }
90
+ return disableAllForSafeMode('unclean-boot', [{ code: 'unclean-boot', level: 'block', detail: JSON.stringify(uncleanBoot) }])
91
+ }
92
+ const checked = checkBundleRows(parsed.rows, { profileDir: resolved, ownPackage: readPackageName(pkgDir), timeoutMs })
93
+ if (checked.ok) return { ok: true, checked: checked.checked, findings: checked.findings, profileDir: resolved, packageDir: pkgDir }
94
+ const blocked = checked.findings.filter((finding) => finding.level === 'block')
95
+ if (!safeModeOnFailure) {
96
+ return { ok: false, error: 'boot-guard-blocked', findings: checked.findings, blocked, profileDir: resolved, packageDir: pkgDir }
97
+ }
98
+ return disableAllForSafeMode('boot-guard-blocked', checked.findings)
99
+ }
100
+
101
+ /**
102
+ * @param {{exe?:string, dataRoot?:string, profileDir?:string, args?:string[], execute?:boolean, nodePath?:string, supervisorPath?:string}} input
103
+ * @returns {{ok:true, argv:string[], dryRun:boolean, exe:string, dataRoot:string, profileDir:string} | {ok:false, error:string}}
104
+ */
105
+ export function resolveDesktopLaunch(input = {}) {
106
+ const exe = String(input.exe ?? '').trim()
107
+ if (!exe) return { ok: false, error: 'desktop-exe-required' }
108
+ const resolvedExe = path.resolve(exe)
109
+ if (!isExecutableFile(resolvedExe)) return { ok: false, error: 'desktop-exe-missing' }
110
+ const dataRoot = String(input.dataRoot ?? '').trim()
111
+ if (!dataRoot) return { ok: false, error: 'data-root-required' }
112
+ const resolvedRoot = path.resolve(dataRoot)
113
+ const profileDir = String(input.profileDir ?? '').trim()
114
+ if (profileDir) {
115
+ const resolvedProfile = path.resolve(profileDir)
116
+ if (!isExecutableFile(path.join(resolvedProfile, 'package.json'))) return { ok: false, error: 'profile-dir-missing' }
117
+ }
118
+ const supervisorPath = input.supervisorPath
119
+ ? path.resolve(String(input.supervisorPath))
120
+ : path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'tools', 'restart-supervisor.mjs')
121
+ if (!isExecutableFile(supervisorPath)) return { ok: false, error: 'supervisor-missing' }
122
+ const nodePath = String(input.nodePath ?? process.execPath)
123
+ const execute = input.execute === true
124
+ const desktopArgs = Array.isArray(input.args) ? input.args.map(String) : []
125
+ const argv = [
126
+ nodePath, supervisorPath,
127
+ ...(execute ? ['--execute'] : []),
128
+ '--data-root', resolvedRoot,
129
+ '--', resolvedExe, ...desktopArgs,
130
+ ]
131
+ return { ok: true, argv, dryRun: !execute, exe: resolvedExe, dataRoot: resolvedRoot, profileDir: profileDir ? path.resolve(profileDir) : '' }
132
+ }
133
+
134
+ /** 只用于展示,不做 shell 拼接执行。 */
135
+ export function describeDesktopLaunch(plan) {
136
+ if (!plan?.ok) return `desktop-launch: ${plan?.error ?? 'invalid'}`
137
+ return `${plan.dryRun ? '[dry-run] ' : '[execute] '}${plan.argv.map((part) => (/\s/.test(part) ? JSON.stringify(part) : part)).join(' ')}`
138
+ }
@@ -0,0 +1,58 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
+ //
4
+ // fork-supervision-settings — 分身看护的持久化开关(UI 与 watchdog 共用)。
5
+ // <dataDir>/fork-supervision.json
6
+ // { version:1, autostartForks:boolean, supervise:boolean, updatedAt:number }
7
+ //
8
+ // autostartForks:watchdog 启动时是否请求 /api/forks/autostart
9
+ // supervise :forker 是否在分身崩溃后按退避重启(运行时可切换)
10
+ import fs from 'node:fs'
11
+ import path from 'node:path'
12
+
13
+ const DEFAULTS = Object.freeze({ autostartForks: true, supervise: false })
14
+ const FILE_NAME = 'fork-supervision.json'
15
+
16
+ export function supervisionSettingsFile(dataDir) {
17
+ return path.join(String(dataDir ?? ''), FILE_NAME)
18
+ }
19
+
20
+ function normalize(raw) {
21
+ return {
22
+ version: 1,
23
+ autostartForks: typeof raw?.autostartForks === 'boolean' ? raw.autostartForks : DEFAULTS.autostartForks,
24
+ supervise: typeof raw?.supervise === 'boolean' ? raw.supervise : DEFAULTS.supervise,
25
+ updatedAt: Number.isFinite(Number(raw?.updatedAt)) ? Number(raw.updatedAt) : 0,
26
+ }
27
+ }
28
+
29
+ export function readForkSupervisionSettings(dataDir) {
30
+ const file = supervisionSettingsFile(dataDir)
31
+ try {
32
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'))
33
+ return { ...normalize(raw), file, exists: true }
34
+ } catch {
35
+ return { ...normalize(null), file, exists: false }
36
+ }
37
+ }
38
+
39
+ export function writeForkSupervisionSettings(dataDir, patch = {}) {
40
+ const dir = String(dataDir ?? '')
41
+ if (!dir) return { ok: false, error: 'data-dir-required' }
42
+ const current = readForkSupervisionSettings(dir)
43
+ const next = normalize({
44
+ autostartForks: typeof patch.autostartForks === 'boolean' ? patch.autostartForks : current.autostartForks,
45
+ supervise: typeof patch.supervise === 'boolean' ? patch.supervise : current.supervise,
46
+ updatedAt: Date.now(),
47
+ })
48
+ try {
49
+ fs.mkdirSync(dir, { recursive: true })
50
+ const file = supervisionSettingsFile(dir)
51
+ const tmp = `${file}.tmp-${process.pid}`
52
+ fs.writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`, 'utf8')
53
+ fs.renameSync(tmp, file)
54
+ return { ok: true, ...next, file }
55
+ } catch (error) {
56
+ return { ok: false, error: 'write-failed', detail: String(error?.message ?? error) }
57
+ }
58
+ }
@@ -0,0 +1,93 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
+ //
4
+ // mirror-official-source — 最小可用的「官方源 adapter」(manifest 协议 v1)。
5
+ //
6
+ // 协议:
7
+ // GET <baseUrl>/manifest.json
8
+ // {
9
+ // "version": "3.2.0",
10
+ // "files": {
11
+ // "package.json": "{\"name\":\"dsh-profile\"}",
12
+ // "cordis.patch.yml": "insert: []\n"
13
+ // }
14
+ // }
15
+ // download(version, staging):校验 version 后把 files 写到 staging(防路径逃逸)。
16
+ //
17
+ // 远程必须 HTTPS(loopback 允许 http)。MirrorManager 现在会 await
18
+ // getLatestVersion()/download(),因此 adapter 可以是 async。
19
+
20
+ function isLoopbackHost(hostname) {
21
+ return /^(localhost|127\.0\.0\.1|\[::1\]|::1)$/i.test(String(hostname))
22
+ }
23
+
24
+ export function validateOfficialSourceUrl(baseUrl) {
25
+ let endpoint = null
26
+ try { endpoint = new URL(String(baseUrl ?? '').trim()) } catch { return { ok: false, reason: 'base-url-required' } }
27
+ if (!/^https?:$/.test(endpoint.protocol)) return { ok: false, reason: 'base-url-required' }
28
+ if (endpoint.username || endpoint.password) return { ok: false, reason: 'base-url-userinfo-forbidden' }
29
+ if (!isLoopbackHost(endpoint.hostname) && endpoint.protocol !== 'https:') return { ok: false, reason: 'https-required-for-remote-endpoint' }
30
+ return { ok: true, url: endpoint.toString().replace(/\/+$/, '') }
31
+ }
32
+
33
+ /** 只允许 staging 内的相对路径;拒绝绝对路径、`..`、NUL。 */
34
+ export function safeRelativePath(relative) {
35
+ const raw = String(relative ?? '')
36
+ if (!raw || raw.includes('\0')) return null
37
+ if (/^[A-Za-z]:/.test(raw) || raw.startsWith('\\\\') || raw.startsWith('//')) return null
38
+ const parts = raw.replace(/\\/g, '/').split('/')
39
+ if (parts.some((part) => part === '..')) return null
40
+ if (parts.some((part) => part === '')) return null
41
+ return parts.join('/')
42
+ }
43
+
44
+ export function createManifestOfficialSource({ baseUrl, fetchImpl = globalThis.fetch, headers = {}, token = '' } = {}) {
45
+ const checked = validateOfficialSourceUrl(baseUrl)
46
+ if (!checked.ok) throw new Error(`official source: ${checked.reason}`)
47
+ if (typeof fetchImpl !== 'function') throw new TypeError('official source: fetchImpl required')
48
+ const manifestUrl = `${checked.url}/manifest.json`
49
+
50
+ async function fetchManifest() {
51
+ const auth = token ? { authorization: `Bearer ${token}` } : {}
52
+ const response = await fetchImpl(manifestUrl, { headers: { accept: 'application/json', ...auth, ...headers }, redirect: 'error' })
53
+ if (!response.ok) throw new Error(`official source manifest: http-${response.status}`)
54
+ const text = await response.text()
55
+ let manifest = null
56
+ try { manifest = JSON.parse(text) } catch { throw new Error('official source manifest: bad-json') }
57
+ const version = String(manifest?.version ?? '').trim()
58
+ if (!version) throw new Error('official source manifest: version-required')
59
+ const files = manifest?.files && typeof manifest.files === 'object' && !Array.isArray(manifest.files) ? manifest.files : null
60
+ if (!files) throw new Error('official source manifest: files-required')
61
+ return { version, files }
62
+ }
63
+
64
+ return {
65
+ baseUrl: checked.url,
66
+ async getLatestVersion() {
67
+ return (await fetchManifest()).version
68
+ },
69
+ async download(version, stagingDir) {
70
+ const manifest = await fetchManifest()
71
+ if (manifest.version !== String(version)) {
72
+ throw new Error(`official source version mismatch: manifest=${manifest.version} requested=${version}`)
73
+ }
74
+ const root = String(stagingDir ?? '')
75
+ if (!root) throw new Error('official source download: staging required')
76
+ const fs = await import('node:fs')
77
+ const path = await import('node:path')
78
+ fs.mkdirSync(root, { recursive: true })
79
+ const rootResolved = path.resolve(root)
80
+ for (const [relative, content] of Object.entries(manifest.files)) {
81
+ const safe = safeRelativePath(relative)
82
+ if (!safe) throw new Error(`official source download: unsafe path ${relative}`)
83
+ const target = path.resolve(rootResolved, safe)
84
+ if (target !== rootResolved && !target.startsWith(rootResolved + path.sep)) {
85
+ throw new Error(`official source download: path escape ${relative}`)
86
+ }
87
+ fs.mkdirSync(path.dirname(target), { recursive: true })
88
+ fs.writeFileSync(target, String(content ?? ''), 'utf8')
89
+ }
90
+ return { version: manifest.version, files: Object.keys(manifest.files).length }
91
+ },
92
+ }
93
+ }
@@ -330,9 +330,16 @@ export class MirrorManager {
330
330
  this.ensureLayoutWithoutRecursion()
331
331
  const current = this.readMeta().version
332
332
  if (this.officialSource === null) return { ok: false, current, latest: null, available: false, reason: 'official-source-unavailable' }
333
+ const settle = (latest) => ({ ok: true, current, latest: String(latest ?? null), available: latest !== null && latest !== current })
333
334
  try {
334
335
  const latest = this.officialSource.getLatestVersion()
335
- return { ok: true, current, latest: String(latest ?? null), available: latest !== null && latest !== current }
336
+ if (latest && typeof latest.then === 'function') {
337
+ return latest.then(settle).catch((error) => ({
338
+ ok: false, current, latest: null, available: false,
339
+ reason: String(error instanceof Error ? error.message : error),
340
+ }))
341
+ }
342
+ return settle(latest)
336
343
  } catch (error) {
337
344
  return { ok: false, current, latest: null, available: false, reason: String(error instanceof Error ? error.message : error) }
338
345
  }
@@ -356,7 +363,7 @@ export class MirrorManager {
356
363
  }
357
364
  stage(UPGRADE_STAGE.CHECKING)
358
365
  let latest
359
- try { latest = String(this.officialSource.getLatestVersion() ?? '') } catch (error) {
366
+ try { latest = String((await Promise.resolve(this.officialSource.getLatestVersion())) ?? '') } catch (error) {
360
367
  return { ok: false, from, to: from, backupId: null, rolledBack: false, reason: `fetch-latest-failed: ${error instanceof Error ? error.message : error}` }
361
368
  }
362
369
  if (latest.length === 0) return { ok: false, from, to: from, backupId: null, rolledBack: false, reason: 'latest-version-unknown' }
@@ -371,7 +378,7 @@ export class MirrorManager {
371
378
  const staging = path.join(this.mirrorRoot, `.staging-${this.now()}-${sha256(`${latest}:${Math.random()}`).slice(0, 6)}`)
372
379
  try {
373
380
  stage(UPGRADE_STAGE.DOWNLOADING)
374
- this.officialSource.download(latest, staging)
381
+ await Promise.resolve(this.officialSource.download(latest, staging))
375
382
  stage(UPGRADE_STAGE.SWAPPING)
376
383
  this.swapActive(staging)
377
384
  stage(UPGRADE_STAGE.FINALIZING)