@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,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
|
+
}
|
package/src/lib/mirror.mjs
CHANGED
|
@@ -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
|
-
|
|
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)
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
|
|
3
|
+
//
|
|
4
|
+
// producer-contract — 业务生产者 → 决策中心的统一调用契约(v1)。
|
|
5
|
+
//
|
|
6
|
+
// 这五个系统本体不在本仓:本模块只定义「它们该怎么调用」,并提供:
|
|
7
|
+
// * normalizeProducerPayload(input) 字段校验 + 默认值 + 稳定 dedupeKey
|
|
8
|
+
// * createProducerSubmitter({submit}) 统一提交封装(返回统一 envelope)
|
|
9
|
+
// * producerCatalog() 机器可读契约目录(UI/外部系统可发现)
|
|
10
|
+
import { nowMs } from '../kernel/index.mjs'
|
|
11
|
+
|
|
12
|
+
export const PRODUCER_CONTRACT_VERSION = 1
|
|
13
|
+
export const PRODUCER_LEVELS = Object.freeze(['red', 'yellow', 'blue', 'green'])
|
|
14
|
+
export const PRODUCER_NAMES = Object.freeze(['HarnessMM', 'PluginUpdater', 'SuperAgent', 'PJM', 'Worker'])
|
|
15
|
+
|
|
16
|
+
export const PRODUCER_CONTRACTS = Object.freeze({
|
|
17
|
+
HarnessMM: Object.freeze({
|
|
18
|
+
kinds: ['harnessmm-suggestion'],
|
|
19
|
+
defaultLevel: 'blue',
|
|
20
|
+
sourceRole: 'worker',
|
|
21
|
+
required: ['title'],
|
|
22
|
+
defaultActions: [
|
|
23
|
+
{ id: 'accept', label: '采纳', type: 'default' },
|
|
24
|
+
{ id: 'ignore', label: '忽略', type: 'default' },
|
|
25
|
+
],
|
|
26
|
+
}),
|
|
27
|
+
PluginUpdater: Object.freeze({
|
|
28
|
+
kinds: ['plugin-updater-backup'],
|
|
29
|
+
defaultLevel: 'green',
|
|
30
|
+
sourceRole: 'worker',
|
|
31
|
+
required: ['title'],
|
|
32
|
+
defaultActions: [],
|
|
33
|
+
}),
|
|
34
|
+
SuperAgent: Object.freeze({
|
|
35
|
+
kinds: ['superagent-completion'],
|
|
36
|
+
defaultLevel: 'green',
|
|
37
|
+
sourceRole: 'worker',
|
|
38
|
+
required: ['title'],
|
|
39
|
+
defaultActions: [],
|
|
40
|
+
}),
|
|
41
|
+
PJM: Object.freeze({
|
|
42
|
+
kinds: ['pjm-timeout', 'pjm-fatal'],
|
|
43
|
+
defaultLevel: 'yellow',
|
|
44
|
+
sourceRole: 'pjm',
|
|
45
|
+
required: ['title'],
|
|
46
|
+
defaultActions: [
|
|
47
|
+
{ id: 'retry', label: '重试', type: 'primary' },
|
|
48
|
+
{ id: 'abandon', label: '放弃', type: 'default' },
|
|
49
|
+
],
|
|
50
|
+
}),
|
|
51
|
+
Worker: Object.freeze({
|
|
52
|
+
kinds: ['worker-deviation'],
|
|
53
|
+
defaultLevel: 'yellow',
|
|
54
|
+
sourceRole: 'worker',
|
|
55
|
+
required: ['title'],
|
|
56
|
+
defaultActions: [
|
|
57
|
+
{ id: 'review', label: '查看', type: 'primary' },
|
|
58
|
+
{ id: 'ignore', label: '忽略', type: 'default' },
|
|
59
|
+
],
|
|
60
|
+
}),
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
const fail = (code, extra = {}) => ({ ok: false, code, ...extra })
|
|
64
|
+
|
|
65
|
+
/** 稳定默认 dedupeKey:调用方显式传优先,否则用常见业务 id 派生。 */
|
|
66
|
+
function deriveDedupeKey(producer, kind, raw) {
|
|
67
|
+
if (raw.dedupeKey !== undefined && raw.dedupeKey !== null && String(raw.dedupeKey).trim()) return String(raw.dedupeKey).trim().slice(0, 200)
|
|
68
|
+
const ref = raw.id ?? raw.backupId ?? raw.suggestionId ?? raw.taskId ?? raw.projectId ?? raw.workerId
|
|
69
|
+
if (ref === undefined || ref === null || String(ref).trim() === '') return undefined
|
|
70
|
+
return `${producer}:${kind}:${String(ref).trim()}`.slice(0, 200)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* 校验并补全统一 payload。成功返回 { ok:true, payload };失败返回 { ok:false, code, errors }。
|
|
75
|
+
* 不写盘、不提交。
|
|
76
|
+
*/
|
|
77
|
+
export function normalizeProducerPayload(input = {}) {
|
|
78
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) return fail('invalid-payload')
|
|
79
|
+
const producer = String(input.producer ?? '').trim()
|
|
80
|
+
const contract = PRODUCER_CONTRACTS[producer]
|
|
81
|
+
if (!contract) return fail('unknown-producer', { allowedProducers: [...PRODUCER_NAMES] })
|
|
82
|
+
const kind = String(input.kind ?? contract.kinds[0]).trim()
|
|
83
|
+
if (!contract.kinds.includes(kind)) {
|
|
84
|
+
return fail('unknown-kind', { producer, allowedKinds: [...contract.kinds] })
|
|
85
|
+
}
|
|
86
|
+
const level = input.level === undefined || input.level === null ? contract.defaultLevel : String(input.level).trim().toLowerCase()
|
|
87
|
+
if (!PRODUCER_LEVELS.includes(level)) return fail('bad-level', { allowedLevels: [...PRODUCER_LEVELS] })
|
|
88
|
+
const title = String(input.title ?? '').trim()
|
|
89
|
+
if (!title) return fail('title-required')
|
|
90
|
+
const actions = Array.isArray(input.actions) ? input.actions.slice(0, 12)
|
|
91
|
+
: (Array.isArray(contract.defaultActions) && contract.defaultActions.length > 0 ? contract.defaultActions.map((item) => ({ ...item })) : undefined)
|
|
92
|
+
const options = Array.isArray(input.options) ? input.options.slice(0, 12) : undefined
|
|
93
|
+
if (level !== 'green' && !(actions?.length) && !(options?.length)) {
|
|
94
|
+
return fail('options-or-actions-required', { level })
|
|
95
|
+
}
|
|
96
|
+
const timeoutMinutes = Number.isFinite(Number(input.timeoutMinutes))
|
|
97
|
+
? Math.max(0, Number(input.timeoutMinutes))
|
|
98
|
+
: kind === 'pjm-timeout' ? 5 : undefined
|
|
99
|
+
const payload = {
|
|
100
|
+
producer,
|
|
101
|
+
kind,
|
|
102
|
+
level,
|
|
103
|
+
title: title.slice(0, 500),
|
|
104
|
+
context: String(input.context ?? input.description ?? `${producer}/${kind}`).slice(0, 12000),
|
|
105
|
+
...(actions ? { actions } : {}),
|
|
106
|
+
...(options ? { options } : {}),
|
|
107
|
+
...(timeoutMinutes === undefined ? {} : { timeoutMinutes }),
|
|
108
|
+
...(deriveDedupeKey(producer, kind, input) ? { dedupeKey: deriveDedupeKey(producer, kind, input) } : {}),
|
|
109
|
+
sourceRole: String(input.sourceRole ?? contract.sourceRole),
|
|
110
|
+
...(input.sessionId ? { sessionId: String(input.sessionId).slice(0, 200) } : {}),
|
|
111
|
+
...(input.metadata && typeof input.metadata === 'object' ? { metadata: input.metadata } : {}),
|
|
112
|
+
producerContractVersion: PRODUCER_CONTRACT_VERSION,
|
|
113
|
+
at: nowMs(),
|
|
114
|
+
}
|
|
115
|
+
return { ok: true, payload }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** 统一提交封装:返回固定 envelope,外部系统不需要理解 decision-center 内部形状。 */
|
|
119
|
+
export function createProducerSubmitter({ submit } = {}) {
|
|
120
|
+
if (typeof submit !== 'function') throw new TypeError('createProducerSubmitter: submit required')
|
|
121
|
+
return async function submitProducerEvent(input = {}) {
|
|
122
|
+
const normalized = normalizeProducerPayload(input)
|
|
123
|
+
if (!normalized.ok) {
|
|
124
|
+
return { ok: false, code: normalized.code, errors: normalized.errors ?? null, ...normalized }
|
|
125
|
+
}
|
|
126
|
+
let out = null
|
|
127
|
+
try {
|
|
128
|
+
out = await submit(normalized.payload)
|
|
129
|
+
} catch (error) {
|
|
130
|
+
return { ok: false, code: 'submit-failed', error: String(error?.message ?? error).slice(0, 500) }
|
|
131
|
+
}
|
|
132
|
+
return {
|
|
133
|
+
ok: out?.ok !== false,
|
|
134
|
+
producer: normalized.payload.producer,
|
|
135
|
+
kind: normalized.payload.kind,
|
|
136
|
+
level: normalized.payload.level,
|
|
137
|
+
ticketId: out?.ticket?.id ?? null,
|
|
138
|
+
deduped: out?.deduped === true,
|
|
139
|
+
queued: out?.queued === true,
|
|
140
|
+
outboxId: out?.outboxId ?? null,
|
|
141
|
+
reason: out?.reason ?? null,
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function producerCatalog() {
|
|
147
|
+
return {
|
|
148
|
+
ok: true,
|
|
149
|
+
version: PRODUCER_CONTRACT_VERSION,
|
|
150
|
+
producers: PRODUCER_NAMES.map((producer) => {
|
|
151
|
+
const contract = PRODUCER_CONTRACTS[producer]
|
|
152
|
+
return {
|
|
153
|
+
producer,
|
|
154
|
+
kinds: [...contract.kinds],
|
|
155
|
+
defaultLevel: contract.defaultLevel,
|
|
156
|
+
sourceRole: contract.sourceRole,
|
|
157
|
+
required: [...contract.required],
|
|
158
|
+
payload: ['producer', 'kind', 'level?', 'title', 'context', 'actions|options', 'timeoutMinutes?', 'dedupeKey?', 'sourceRole?', 'sessionId?'],
|
|
159
|
+
}
|
|
160
|
+
}),
|
|
161
|
+
}
|
|
162
|
+
}
|