@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
|
@@ -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
|
+
}
|
|
@@ -11,12 +11,24 @@ export const FORK_LOCKED_ENTRY_IDS = Object.freeze([
|
|
|
11
11
|
'tool-plugin-manager',
|
|
12
12
|
])
|
|
13
13
|
|
|
14
|
+
/** DSH first-run notice needs a durable ui-settings-general config form in every fork profile. */
|
|
15
|
+
const WELCOME_NOTICE_ENTRY = Object.freeze({
|
|
16
|
+
id: 'ui-settings-general',
|
|
17
|
+
name: '@deepseek-ai/dsh-client-ui-settings-general',
|
|
18
|
+
config: Object.freeze({ welcomeNoticeVersion: '2026-09-28.1' }),
|
|
19
|
+
})
|
|
20
|
+
|
|
14
21
|
// cordis.yml 不加只读:DSH 启动时会打开它做规范化写入,只读会导致 EPERM 启动失败。
|
|
15
22
|
export const PROFILE_CONFIG_FILES = Object.freeze(['package.json', 'cordis.patch.yml'])
|
|
16
23
|
|
|
17
24
|
/** 把分身 profile 的配置文件设为只读(防止误写;不防有意绕过)。 */
|
|
18
25
|
export function setProfileConfigReadonly(profileDir, readonly = true) {
|
|
19
26
|
if (String(process.env.DSH_FANG_FORK_PROFILE_RO ?? '1') === '0') return { ok: true, skipped: true, changed: [] }
|
|
27
|
+
// essence-runtime 是元主的配置态实例:DSH 设置/内置插件开关需要原子写 package.json。
|
|
28
|
+
// 只对真正的分身(生产盘)保持只读;否则点「启用」会 EPERM rename package.json.tmp。
|
|
29
|
+
if (readonly && path.basename(String(profileDir)) === 'essence-runtime') {
|
|
30
|
+
return { ok: true, skipped: true, runtime: true, changed: [] }
|
|
31
|
+
}
|
|
20
32
|
const changed = []
|
|
21
33
|
for (const name of PROFILE_CONFIG_FILES) {
|
|
22
34
|
const file = path.join(String(profileDir), name)
|
|
@@ -28,11 +40,54 @@ export function setProfileConfigReadonly(profileDir, readonly = true) {
|
|
|
28
40
|
return { ok: true, changed }
|
|
29
41
|
}
|
|
30
42
|
|
|
43
|
+
/**
|
|
44
|
+
* Essence-derived profiles serialize their patch as a JSON object `{ insert: [...] }`.
|
|
45
|
+
* Appending YAML lines after that object produces invalid YAML (the v3.0.10 spawn-failed
|
|
46
|
+
* bug). Return the semantic entry array when the file is JSON, so the lock can be merged
|
|
47
|
+
* structurally instead.
|
|
48
|
+
* @param {string} text
|
|
49
|
+
* @returns {Array<Record<string, unknown>> | null}
|
|
50
|
+
*/
|
|
51
|
+
function jsonPatchEntries(text) {
|
|
52
|
+
const trimmed = String(text ?? '').trim()
|
|
53
|
+
if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) return null
|
|
54
|
+
let value
|
|
55
|
+
try { value = JSON.parse(trimmed) } catch { return null }
|
|
56
|
+
if (Array.isArray(value)) return value.length === 0 ? null : value
|
|
57
|
+
if (value !== null && typeof value === 'object' && Array.isArray(value.insert)) return [value]
|
|
58
|
+
return null
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Add the lock rows and the onboarding row without duplicating ids. */
|
|
62
|
+
function withLockRows(entries, ids) {
|
|
63
|
+
const out = entries.slice()
|
|
64
|
+
let added = 0
|
|
65
|
+
for (const id of ids) {
|
|
66
|
+
if (!out.some((entry) => entry !== null && typeof entry === 'object' && entry.id === id)) {
|
|
67
|
+
out.push({ id, disabled: true })
|
|
68
|
+
added += 1
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (!out.some((entry) => entry !== null && typeof entry === 'object' && entry.id === WELCOME_NOTICE_ENTRY.id)) {
|
|
72
|
+
out.push({ ...WELCOME_NOTICE_ENTRY, config: { ...WELCOME_NOTICE_ENTRY.config } })
|
|
73
|
+
}
|
|
74
|
+
return { entries: out, added }
|
|
75
|
+
}
|
|
76
|
+
|
|
31
77
|
export function applyForkConfigLock(profileDir, options = {}) {
|
|
32
78
|
if (String(process.env.DSH_FANG_FORK_CONFIG_LOCK ?? '1') === '0') return { ok: true, skipped: true }
|
|
33
79
|
const file = path.join(String(profileDir), 'cordis.patch.yml')
|
|
34
80
|
let text = ''
|
|
35
81
|
try { text = fs.readFileSync(file, 'utf8') } catch { text = '' }
|
|
82
|
+
const ids = options.ids ?? FORK_LOCKED_ENTRY_IDS
|
|
83
|
+
// JSON object/array patches are semantic entry lists; merge them structurally. Appending
|
|
84
|
+
// YAML text after `{ insert: [...] }` would make the whole file unparsable.
|
|
85
|
+
const jsonEntries = jsonPatchEntries(text)
|
|
86
|
+
if (jsonEntries !== null) {
|
|
87
|
+
const merged = withLockRows(jsonEntries, ids)
|
|
88
|
+
fs.writeFileSync(file, `${JSON.stringify(merged.entries, null, 2)}\n`, 'utf8')
|
|
89
|
+
return { ok: true, entries: merged.added }
|
|
90
|
+
}
|
|
36
91
|
// 模板里的 `[]`(空 YAML 数组)必须去掉,否则追加 `- id:` 会变成非法 YAML。
|
|
37
92
|
const kept = text
|
|
38
93
|
.replace(/^\uFEFF/, '')
|
|
@@ -40,15 +95,23 @@ export function applyForkConfigLock(profileDir, options = {}) {
|
|
|
40
95
|
.filter((line) => !/^\s*\[\s*\]\s*(#.*)?$/.test(line))
|
|
41
96
|
text = kept.join('\n')
|
|
42
97
|
const lines = []
|
|
43
|
-
for (const id of
|
|
98
|
+
for (const id of ids) {
|
|
44
99
|
const present = new RegExp(`(^|\\n)\\s*-\\s*id:\\s*${id}\\s*$`, 'm').test(text)
|
|
45
100
|
if (present) continue
|
|
46
101
|
lines.push(`- id: ${id}`, ' disabled: true')
|
|
47
102
|
}
|
|
103
|
+
if (!new RegExp(`(^|\\n)\\s*-\\s*id:\\s*${WELCOME_NOTICE_ENTRY.id}\\s*$`, 'm').test(text)) {
|
|
104
|
+
lines.push(
|
|
105
|
+
`- id: ${WELCOME_NOTICE_ENTRY.id}`,
|
|
106
|
+
` name: "${WELCOME_NOTICE_ENTRY.name}"`,
|
|
107
|
+
' config:',
|
|
108
|
+
` welcomeNoticeVersion: ${WELCOME_NOTICE_ENTRY.config.welcomeNoticeVersion}`,
|
|
109
|
+
)
|
|
110
|
+
}
|
|
48
111
|
if (lines.length === 0) return { ok: true, entries: 0 }
|
|
49
112
|
const prefix = text.trim().length === 0 ? '' : (text.endsWith('\n') ? text : text + '\n')
|
|
50
113
|
const comment = text.includes('# fang: fork is production-only')
|
|
51
114
|
? '' : '# fang: fork is production-only (plugin install / settings disabled)\n'
|
|
52
115
|
fs.writeFileSync(file, `${prefix}${comment}${lines.join('\n')}\n`, 'utf8')
|
|
53
|
-
return { ok: true, entries:
|
|
116
|
+
return { ok: true, entries: ids.length }
|
|
54
117
|
}
|
|
@@ -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
|
+
}
|