@twinsearth/dsh-fang 3.3.2 → 3.7.7
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/README.md +5 -5
- package/client.js +674 -60
- package/cordis.patch.yml +26 -20
- package/docs/APPROVAL-DRILL.md +42 -0
- package/docs/AUTO-WATCHDOG.md +46 -0
- package/docs/DECISION-LOSSLESS.md +36 -0
- package/docs/ESSENCE-AUTO-SYNC.md +32 -0
- package/docs/INBOX-SCROLL.md +33 -0
- package/docs/PACKAGE-RENAME-v3.3.3.md +40 -0
- package/docs/RESTART-CONFIRMATION.md +29 -0
- package/docs/TEST-STABILITY-v3.4.0.md +30 -0
- package/package.json +11 -7
- package/src/compose.mjs +4 -1
- package/src/contract/VENDOR.json +6 -5
- package/src/contract/constants.js +16 -1
- package/src/contract/relay.js +12 -6
- package/src/kernel/types.mjs +3 -1
- package/src/lib/accelerated-fork.mjs +813 -0
- package/src/lib/accelerated-install.mjs +295 -0
- package/src/lib/accelerated-web.mjs +103 -0
- package/src/lib/approval-drill.mjs +111 -0
- package/src/lib/boot-guard.mjs +6 -2
- package/src/lib/chat-import-delegation.mjs +47 -0
- package/src/lib/compat.mjs +5 -1
- package/src/lib/contract-delegation.mjs +161 -0
- package/src/lib/default-essence.mjs +7 -4
- package/src/lib/essence.mjs +113 -7
- package/src/lib/fork-config-lock.mjs +2 -2
- package/src/lib/fork-core-settings.mjs +95 -0
- package/src/lib/fork-export.mjs +85 -0
- package/src/lib/global-redline.mjs +164 -0
- package/src/lib/http-auth.mjs +36 -0
- package/src/lib/install-snapshot.mjs +77 -0
- package/src/lib/lsp-delegation.mjs +70 -0
- package/src/lib/lsp-provider.mjs +250 -0
- package/src/lib/main-gate.mjs +33 -28
- package/src/lib/mirror.mjs +115 -4
- package/src/lib/node-compat.mjs +24 -0
- package/src/lib/pro-delegation.mjs +185 -0
- package/src/lib/runtime-capture.mjs +11 -3
- package/src/lib/watch-guard.mjs +51 -0
- package/src/plugins/approver.mjs +5 -2
- package/src/plugins/auditor.mjs +125 -18
- package/src/plugins/decision-center.mjs +77 -34
- package/src/plugins/forker.mjs +258 -33
- package/src/plugins/orchestrator.mjs +1508 -65
- package/src/plugins/restart-guard.mjs +79 -2
- package/src/plugins/session-catalog.mjs +127 -40
- package/tools/approval-drill.mjs +21 -0
- package/tools/fangctl.mjs +21 -4
- package/tools/gate/main-city.mjs +1 -1
- package/tools/restart-supervisor.mjs +425 -0
- package/tools/restart-watchdog.mjs +568 -0
- package/vault/client.js +49 -0
- package/vault/cordis.patch.yml +3 -0
- package/vault/lib/vault.mjs +219 -0
- package/vault/package.json +29 -0
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
|
|
3
|
+
//
|
|
4
|
+
// Accelerated core installation (P0): installs @twinsearth/dsh into
|
|
5
|
+
// <FANG_HOME>/accel/cli and remembers where the CLI entry lives.
|
|
6
|
+
//
|
|
7
|
+
// Design rules (see docs/ACCELERATED-FORK.md):
|
|
8
|
+
// * The accelerated core only ever runs FORKS; mother/essence stay stock.
|
|
9
|
+
// * Only a JavaScript entry (`lib/bin.js`) is accepted: spawning a `.cmd`
|
|
10
|
+
// shim from Node on Windows fails with EINVAL/EPERM.
|
|
11
|
+
// * Missing install is a hard, explicit failure — never a silent stock
|
|
12
|
+
// fallback.
|
|
13
|
+
import fs from 'node:fs'
|
|
14
|
+
import path from 'node:path'
|
|
15
|
+
import { spawn } from 'node:child_process'
|
|
16
|
+
|
|
17
|
+
export const ACCEL_PACKAGE = '@twinsearth/dsh'
|
|
18
|
+
export const DEFAULT_ACCEL_VERSION = '3.5.0'
|
|
19
|
+
/** Hard budget for the install directory: above this the operator must confirm explicitly. */
|
|
20
|
+
export const ACCEL_INSTALL_LIMIT_BYTES = 1024 * 1024 * 1024
|
|
21
|
+
export const ACCEL_ENTRY_REL = path.join('node_modules', '@twinsearth', 'dsh', 'lib', 'bin.js')
|
|
22
|
+
const SCRIPT_RE = /\.(?:mjs|cjs|js)$/i
|
|
23
|
+
|
|
24
|
+
/** Install root layout under <FANG_HOME>/accel. */
|
|
25
|
+
export function acceleratedLayout(fangHome) {
|
|
26
|
+
const root = path.join(String(fangHome ?? '').trim(), 'accel')
|
|
27
|
+
const cliDir = path.join(root, 'cli')
|
|
28
|
+
return {
|
|
29
|
+
root,
|
|
30
|
+
cliDir,
|
|
31
|
+
stateFile: path.join(root, 'state.json'),
|
|
32
|
+
cliPath: path.join(cliDir, ACCEL_ENTRY_REL),
|
|
33
|
+
packageFile: path.join(cliDir, 'node_modules', ACCEL_PACKAGE, 'package.json'),
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Read the persisted install state (null when never installed). */
|
|
38
|
+
export function readAcceleratedState(fangHome) {
|
|
39
|
+
const { stateFile } = acceleratedLayout(fangHome)
|
|
40
|
+
try {
|
|
41
|
+
const raw = JSON.parse(fs.readFileSync(stateFile, 'utf8'))
|
|
42
|
+
if (!raw || typeof raw !== 'object') return null
|
|
43
|
+
return raw
|
|
44
|
+
} catch {
|
|
45
|
+
return null
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Persist the install state atomically. */
|
|
50
|
+
export function writeAcceleratedState(fangHome, state) {
|
|
51
|
+
const { root, stateFile } = acceleratedLayout(fangHome)
|
|
52
|
+
fs.mkdirSync(root, { recursive: true })
|
|
53
|
+
const tmp = `${stateFile}.tmp-${process.pid}`
|
|
54
|
+
fs.writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`)
|
|
55
|
+
fs.renameSync(tmp, stateFile)
|
|
56
|
+
return state
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Keep only JavaScript entries: `.cmd`/`.ps1` shims cannot be spawned safely. */
|
|
60
|
+
export function isScriptEntry(cliPath) {
|
|
61
|
+
return SCRIPT_RE.test(String(cliPath ?? ''))
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Validate one candidate CLI path.
|
|
66
|
+
* @returns {{ok:true, cliPath:string} | {ok:false, reason:string}}
|
|
67
|
+
*/
|
|
68
|
+
export function checkCliCandidate(cliPath) {
|
|
69
|
+
const value = String(cliPath ?? '').trim()
|
|
70
|
+
if (!value) return { ok: false, reason: 'empty' }
|
|
71
|
+
if (!isScriptEntry(value)) return { ok: false, reason: 'not-a-js-entry' }
|
|
72
|
+
try {
|
|
73
|
+
if (!fs.statSync(value).isFile()) return { ok: false, reason: 'not-a-file' }
|
|
74
|
+
} catch {
|
|
75
|
+
return { ok: false, reason: 'missing' }
|
|
76
|
+
}
|
|
77
|
+
return { ok: true, cliPath: path.resolve(value) }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Resolve the accelerated CLI entry with an explicit, auditable chain.
|
|
82
|
+
* Sources, in order: config cliPath → FANG_ACCEL_CLI → install state →
|
|
83
|
+
* <FANG_HOME>/accel/cli standard location. The global npm root is not probed
|
|
84
|
+
* because a project must not accidentally pick a machine-wide install.
|
|
85
|
+
* @returns {{ok:true, cliPath:string, source:string} | {ok:false, error:'accelerated-cli-missing', searched:Array<{source:string, value:string, reason:string}>}}
|
|
86
|
+
*/
|
|
87
|
+
export function resolveAcceleratedCore(options = {}) {
|
|
88
|
+
const { cliPath = '', env = process.env, fangHome = '' } = options
|
|
89
|
+
const layout = acceleratedLayout(fangHome)
|
|
90
|
+
const state = readAcceleratedState(fangHome)
|
|
91
|
+
const searched = []
|
|
92
|
+
const candidates = [
|
|
93
|
+
{ source: 'config', value: String(cliPath ?? '').trim() },
|
|
94
|
+
{ source: 'env:FANG_ACCEL_CLI', value: String(env?.FANG_ACCEL_CLI ?? '').trim() },
|
|
95
|
+
{ source: 'state', value: String(state?.cliPath ?? '').trim() },
|
|
96
|
+
{ source: 'layout', value: layout.cliPath },
|
|
97
|
+
]
|
|
98
|
+
for (const candidate of candidates) {
|
|
99
|
+
if (!candidate.value) { searched.push({ ...candidate, reason: 'empty' }); continue }
|
|
100
|
+
const checked = checkCliCandidate(candidate.value)
|
|
101
|
+
if (checked.ok) return { ok: true, cliPath: checked.cliPath, source: candidate.source }
|
|
102
|
+
searched.push({ ...candidate, reason: checked.reason })
|
|
103
|
+
}
|
|
104
|
+
return { ok: false, error: 'accelerated-cli-missing', searched }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Read installed version (null when absent). */
|
|
108
|
+
export function installedAcceleratedVersion(fangHome) {
|
|
109
|
+
const { packageFile } = acceleratedLayout(fangHome)
|
|
110
|
+
try {
|
|
111
|
+
const pkg = JSON.parse(fs.readFileSync(packageFile, 'utf8'))
|
|
112
|
+
return typeof pkg?.version === 'string' ? pkg.version : null
|
|
113
|
+
} catch {
|
|
114
|
+
return null
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Read-only view for the panel route. */
|
|
119
|
+
export function acceleratedCoreInfo(options = {}) {
|
|
120
|
+
const { env = process.env, cliPath = '', fangHome = '' } = options
|
|
121
|
+
const resolved = resolveAcceleratedCore({ cliPath, env, fangHome })
|
|
122
|
+
const state = readAcceleratedState(fangHome)
|
|
123
|
+
const sizeBytes = acceleratedInstallSize(fangHome)
|
|
124
|
+
return {
|
|
125
|
+
installed: resolved.ok === true,
|
|
126
|
+
version: installedAcceleratedVersion(fangHome) ?? state?.version ?? null,
|
|
127
|
+
cliPath: resolved.ok ? resolved.cliPath : null,
|
|
128
|
+
source: resolved.ok ? resolved.source : null,
|
|
129
|
+
error: resolved.ok ? null : resolved.error,
|
|
130
|
+
searched: resolved.ok ? [] : resolved.searched,
|
|
131
|
+
installedAt: state?.installedAt ?? null,
|
|
132
|
+
sizeBytes,
|
|
133
|
+
limitBytes: ACCEL_INSTALL_LIMIT_BYTES,
|
|
134
|
+
requiresConfirmation: sizeBytes > ACCEL_INSTALL_LIMIT_BYTES,
|
|
135
|
+
layout: acceleratedLayout(fangHome),
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Recursive size of a directory in bytes (0 when absent). */
|
|
140
|
+
export function dirSizeBytes(dir) {
|
|
141
|
+
let total = 0
|
|
142
|
+
const walk = (current) => {
|
|
143
|
+
let entries
|
|
144
|
+
try { entries = fs.readdirSync(current, { withFileTypes: true }) } catch { return }
|
|
145
|
+
for (const entry of entries) {
|
|
146
|
+
const full = path.join(current, entry.name)
|
|
147
|
+
if (entry.isDirectory()) {
|
|
148
|
+
walk(full)
|
|
149
|
+
} else {
|
|
150
|
+
try { total += fs.statSync(full).size } catch { /* vanished */ }
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
walk(String(dir ?? ''))
|
|
155
|
+
return total
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Measured install size for the current <FANG_HOME>/accel/cli (0 when absent). */
|
|
159
|
+
export function acceleratedInstallSize(fangHome) {
|
|
160
|
+
return dirSizeBytes(acceleratedLayout(fangHome).cliDir)
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Node_modules root of the accelerated CLI: `<cli>/node_modules` (contains `@twinsearth/*`).
|
|
165
|
+
* The CLI entry is `<cli>/node_modules/@twinsearth/dsh/lib/bin.js`, so walk up 3 dirs.
|
|
166
|
+
*/
|
|
167
|
+
export function accelNodeModulesRoot(cliPath) {
|
|
168
|
+
const entry = String(cliPath ?? '').trim()
|
|
169
|
+
if (!entry) return ''
|
|
170
|
+
const resolved = path.resolve(entry)
|
|
171
|
+
const dirname = path.dirname(resolved)
|
|
172
|
+
if (!/\bnode_modules[\\/]@twinsearth[\\/]/.test(dirname)) {
|
|
173
|
+
// tolerate arbitrary entry shapes: fall back to walking up until a node_modules dir exists
|
|
174
|
+
let current = dirname
|
|
175
|
+
for (let depth = 0; depth < 6; depth += 1) {
|
|
176
|
+
if (path.basename(current) === 'node_modules') return current
|
|
177
|
+
current = path.dirname(current)
|
|
178
|
+
}
|
|
179
|
+
return ''
|
|
180
|
+
}
|
|
181
|
+
return path.resolve(dirname, '..', '..', '..')
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Enforce the 1 GiB budget. Above it the caller must obtain an explicit second
|
|
186
|
+
* confirmation (`confirmOversize`) or answer the interactive prompt.
|
|
187
|
+
* @returns {Promise<{ok:boolean, sizeBytes:number, limitBytes:number, requiresConfirmation?:boolean,
|
|
188
|
+
* error?:string}>}
|
|
189
|
+
*/
|
|
190
|
+
export async function ensureInstallBudget(options = {}) {
|
|
191
|
+
const { sizeBytes = 0, confirmOversize = false, promptImpl = null } = options
|
|
192
|
+
const limitBytes = ACCEL_INSTALL_LIMIT_BYTES
|
|
193
|
+
if (sizeBytes <= limitBytes) return { ok: true, sizeBytes, limitBytes }
|
|
194
|
+
if (confirmOversize === true) return { ok: true, sizeBytes, limitBytes, confirmed: true }
|
|
195
|
+
if (typeof promptImpl === 'function') {
|
|
196
|
+
let accepted = false
|
|
197
|
+
try { accepted = (await promptImpl({ sizeBytes, limitBytes })) === true } catch { accepted = false }
|
|
198
|
+
if (accepted) return { ok: true, sizeBytes, limitBytes, confirmed: true }
|
|
199
|
+
}
|
|
200
|
+
return { ok: false, error: 'accelerated-install-too-large', sizeBytes, limitBytes, requiresConfirmation: true }
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Build the npm install invocation (pure, unit-testable). */
|
|
204
|
+
export function buildInstallCommand({ cliDir, version = DEFAULT_ACCEL_VERSION, npmBin = 'npm' } = {}) {
|
|
205
|
+
const spec = `${ACCEL_PACKAGE}@${String(version ?? '').trim() || DEFAULT_ACCEL_VERSION}`
|
|
206
|
+
return {
|
|
207
|
+
command: npmBin,
|
|
208
|
+
args: ['install', '--prefix', path.resolve(cliDir), '--no-audit', '--no-fund', '--loglevel=error', spec],
|
|
209
|
+
spec,
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function runOnce(spec, { spawnImpl = spawn, timeoutMs = 600000, cwd } = {}) {
|
|
214
|
+
return new Promise((resolve) => {
|
|
215
|
+
let child
|
|
216
|
+
try {
|
|
217
|
+
child = spawnImpl(spec.command, spec.args, {
|
|
218
|
+
cwd,
|
|
219
|
+
windowsHide: true,
|
|
220
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
221
|
+
// .cmd shims on Windows need a shell; the command name is operator-provided.
|
|
222
|
+
shell: process.platform === 'win32',
|
|
223
|
+
})
|
|
224
|
+
} catch (error) {
|
|
225
|
+
resolve({ ok: false, error: 'spawn-failed', detail: String(error?.message ?? error) })
|
|
226
|
+
return
|
|
227
|
+
}
|
|
228
|
+
let output = ''
|
|
229
|
+
const timer = setTimeout(() => {
|
|
230
|
+
try { child.kill() } catch { /* already gone */ }
|
|
231
|
+
resolve({ ok: false, error: 'install-timeout', output: output.slice(-2000) })
|
|
232
|
+
}, Math.max(1000, Number(timeoutMs) || 600000))
|
|
233
|
+
child.stdout?.on('data', (chunk) => { output += String(chunk) })
|
|
234
|
+
child.stderr?.on('data', (chunk) => { output += String(chunk) })
|
|
235
|
+
child.once('error', (error) => {
|
|
236
|
+
clearTimeout(timer)
|
|
237
|
+
resolve({ ok: false, error: 'spawn-error', detail: String(error?.message ?? error), output: output.slice(-2000) })
|
|
238
|
+
})
|
|
239
|
+
child.once('exit', (code) => {
|
|
240
|
+
clearTimeout(timer)
|
|
241
|
+
resolve({ ok: code === 0, error: code === 0 ? null : 'install-failed', code, output: output.slice(-4000) })
|
|
242
|
+
})
|
|
243
|
+
})
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Install (or reuse) the accelerated core under <FANG_HOME>/accel/cli.
|
|
248
|
+
* Reuses an existing install whose version matches, unless force.
|
|
249
|
+
* @returns {Promise<{ok:boolean, version?:string, cliPath?:string, reused?:boolean, error?:string, output?:string}>}
|
|
250
|
+
*/
|
|
251
|
+
export async function installAcceleratedCore(options = {}) {
|
|
252
|
+
const {
|
|
253
|
+
fangHome = '', version = DEFAULT_ACCEL_VERSION, force = false,
|
|
254
|
+
spawnImpl = spawn, npmBin = process.env.FANG_NPM_BIN || 'npm',
|
|
255
|
+
confirmOversize = false, promptImpl = null,
|
|
256
|
+
} = options
|
|
257
|
+
const layout = acceleratedLayout(fangHome)
|
|
258
|
+
if (!String(fangHome ?? '').trim()) return { ok: false, error: 'fang-home-missing' }
|
|
259
|
+
const currentVersion = installedAcceleratedVersion(fangHome)
|
|
260
|
+
if (!force && currentVersion) {
|
|
261
|
+
const checked = checkCliCandidate(layout.cliPath)
|
|
262
|
+
if (checked.ok && (!version || currentVersion === version)) {
|
|
263
|
+
const budget = await ensureInstallBudget({ sizeBytes: acceleratedInstallSize(fangHome), confirmOversize, promptImpl })
|
|
264
|
+
if (budget.ok !== true) return budget
|
|
265
|
+
const state = writeAcceleratedState(fangHome, {
|
|
266
|
+
version: currentVersion,
|
|
267
|
+
cliPath: checked.cliPath,
|
|
268
|
+
installedAt: readAcceleratedState(fangHome)?.installedAt ?? new Date().toISOString(),
|
|
269
|
+
checkedAt: new Date().toISOString(),
|
|
270
|
+
})
|
|
271
|
+
return { ok: true, version: currentVersion, cliPath: checked.cliPath, reused: true, state, sizeBytes: budget.sizeBytes, limitBytes: budget.limitBytes }
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
fs.mkdirSync(layout.cliDir, { recursive: true })
|
|
275
|
+
const spec = buildInstallCommand({ cliDir: layout.cliDir, version, npmBin })
|
|
276
|
+
const run = await runOnce(spec, { spawnImpl })
|
|
277
|
+
if (!run.ok) return { ok: false, error: run.error ?? 'install-failed', output: run.output, detail: run.detail }
|
|
278
|
+
const installed = installedAcceleratedVersion(fangHome)
|
|
279
|
+
const checked = checkCliCandidate(layout.cliPath)
|
|
280
|
+
if (!installed || !checked.ok) {
|
|
281
|
+
return { ok: false, error: 'install-verify-failed', output: run.output, version: installed, cliPath: checked.ok ? checked.cliPath : null }
|
|
282
|
+
}
|
|
283
|
+
// 体积门禁:>1 GiB 必须二次确认;未确认时不写 state(视为未安装),文件保留待人工处理。
|
|
284
|
+
const budget = await ensureInstallBudget({ sizeBytes: acceleratedInstallSize(fangHome), confirmOversize, promptImpl })
|
|
285
|
+
if (budget.ok !== true) return { ...budget, output: run.output, attemptedVersion: installed }
|
|
286
|
+
const state = writeAcceleratedState(fangHome, {
|
|
287
|
+
version: installed,
|
|
288
|
+
cliPath: checked.cliPath,
|
|
289
|
+
installedAt: new Date().toISOString(),
|
|
290
|
+
spec: spec.spec,
|
|
291
|
+
sizeBytes: budget.sizeBytes,
|
|
292
|
+
limitBytes: budget.limitBytes,
|
|
293
|
+
})
|
|
294
|
+
return { ok: true, version: installed, cliPath: checked.cliPath, reused: false, state, output: run.output, sizeBytes: budget.sizeBytes, limitBytes: budget.limitBytes }
|
|
295
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Accelerated Web sidecar: keeps the original DSH process untouched and starts
|
|
3
|
+
// a second @twinsearth/dsh Web process with its own profile and port.
|
|
4
|
+
import { spawn } from 'node:child_process'
|
|
5
|
+
import path from 'node:path'
|
|
6
|
+
import { ensureDir, readJson, writeJsonAtomic } from '../kernel/index.mjs'
|
|
7
|
+
|
|
8
|
+
export const ACCELERATED_STATE_FILE = 'accelerated-web.json'
|
|
9
|
+
export const DEFAULT_ACCELERATED_PORT = 18080
|
|
10
|
+
export const URL_PATTERN = /dsh web: (https?:\/\/\S+)/
|
|
11
|
+
|
|
12
|
+
/** Resolve the accelerated CLI: explicit config, env, or the installed package bin. */
|
|
13
|
+
export function resolveAcceleratedCli({ cliPath = '', env = process.env } = {}) {
|
|
14
|
+
const explicit = String(cliPath ?? '').trim()
|
|
15
|
+
if (explicit) return explicit
|
|
16
|
+
const fromEnv = String(env.FANG_ACCEL_CLI ?? '').trim()
|
|
17
|
+
if (fromEnv) return fromEnv
|
|
18
|
+
return ''
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Build the argv for one accelerated Web process. */
|
|
22
|
+
export function buildAcceleratedArgs({ profile = 'fang-accelerated', port = DEFAULT_ACCELERATED_PORT, resetProfile = false } = {}) {
|
|
23
|
+
const args = []
|
|
24
|
+
if (resetProfile) args.push('--from-default-profile', 'web')
|
|
25
|
+
args.push('--profile', profile, '--port', String(port), '--no-open')
|
|
26
|
+
return args
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Read the persisted sidecar state. */
|
|
30
|
+
export function readAcceleratedState(dataDir) {
|
|
31
|
+
return readJson(path.join(dataDir, ACCELERATED_STATE_FILE), null)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Start the accelerated process; returns its PID and URL after the URL line. */
|
|
35
|
+
export async function startAcceleratedWeb({ dataDir, cliPath, profile = 'fang-accelerated', port = DEFAULT_ACCELERATED_PORT, home = process.env.DSH_HOME, timeoutMs = 60000, spawnImpl = spawn, fetchImpl = fetch } = {}) {
|
|
36
|
+
const previous = readAcceleratedState(dataDir)
|
|
37
|
+
if (previous?.pid && await isAlive(previous.pid, fetchImpl, previous.port)) return { ok: true, already: true, ...previous }
|
|
38
|
+
const cli = resolveAcceleratedCli({ cliPath })
|
|
39
|
+
if (!cli) return { ok: false, error: 'accelerated-cli-missing' }
|
|
40
|
+
ensureDir(dataDir)
|
|
41
|
+
const profileDir = path.join(home ?? '', 'profiles', profile)
|
|
42
|
+
const resetProfile = !profileDir || !readJson(path.join(profileDir, 'package.json'), null)
|
|
43
|
+
const args = buildAcceleratedArgs({ profile, port, resetProfile })
|
|
44
|
+
const isScript = /\.(?:mjs|cjs|js)$/i.test(cli)
|
|
45
|
+
const child = spawnImpl(isScript ? process.execPath : cli, isScript ? [cli, ...args] : args, {
|
|
46
|
+
env: { ...process.env, ...(home ? { DSH_HOME: home } : {}) },
|
|
47
|
+
windowsHide: true,
|
|
48
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
49
|
+
})
|
|
50
|
+
let output = ''
|
|
51
|
+
const url = await new Promise((resolve, reject) => {
|
|
52
|
+
const timer = setTimeout(() => reject(new Error('accelerated-web-start-timeout')), timeoutMs)
|
|
53
|
+
const onData = (chunk) => {
|
|
54
|
+
output += String(chunk)
|
|
55
|
+
const match = URL_PATTERN.exec(output)
|
|
56
|
+
if (match) { clearTimeout(timer); resolve(match[1]) }
|
|
57
|
+
}
|
|
58
|
+
child.stdout?.on('data', onData)
|
|
59
|
+
child.stderr?.on('data', onData)
|
|
60
|
+
child.once('error', (error) => { clearTimeout(timer); reject(error) })
|
|
61
|
+
child.once('exit', (code) => { if (!URL_PATTERN.test(output)) { clearTimeout(timer); reject(new Error(`accelerated-web-exited-${code}`)) } })
|
|
62
|
+
}).catch((error) => {
|
|
63
|
+
try { child.kill() } catch { /* already gone */ }
|
|
64
|
+
return { error }
|
|
65
|
+
})
|
|
66
|
+
if (typeof url !== 'string') return { ok: false, error: url.error?.message ?? 'accelerated-web-start-failed', output: output.slice(-2000) }
|
|
67
|
+
const state = { version: 1, pid: child.pid, url, port, profile, cliPath: cli, startedAt: new Date().toISOString() }
|
|
68
|
+
writeJsonAtomic(path.join(dataDir, ACCELERATED_STATE_FILE), state)
|
|
69
|
+
child.once('exit', () => {
|
|
70
|
+
const current = readAcceleratedState(dataDir)
|
|
71
|
+
if (current?.pid === child.pid) writeJsonAtomic(path.join(dataDir, ACCELERATED_STATE_FILE), { ...current, running: false, stoppedAt: new Date().toISOString() })
|
|
72
|
+
})
|
|
73
|
+
return { ok: true, ...state }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Stop the sidecar process tree. */
|
|
77
|
+
export async function stopAcceleratedWeb({ dataDir, execFileImpl } = {}) {
|
|
78
|
+
const state = readAcceleratedState(dataDir)
|
|
79
|
+
if (!state?.pid) return { ok: true, stopped: false }
|
|
80
|
+
const execFile = execFileImpl ?? (await import('node:child_process')).execFile
|
|
81
|
+
await new Promise((resolve) => {
|
|
82
|
+
execFile('taskkill', ['/PID', String(state.pid), '/T', '/F'], { windowsHide: true }, () => resolve(undefined))
|
|
83
|
+
})
|
|
84
|
+
writeJsonAtomic(path.join(dataDir, ACCELERATED_STATE_FILE), { ...state, running: false, stoppedAt: new Date().toISOString() })
|
|
85
|
+
return { ok: true, stopped: true, pid: state.pid }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Current sidecar view for the panel. */
|
|
89
|
+
export async function acceleratedWebStatus({ dataDir, fetchImpl = fetch } = {}) {
|
|
90
|
+
const state = readAcceleratedState(dataDir)
|
|
91
|
+
if (!state?.pid) return { ok: true, running: false, state: null }
|
|
92
|
+
const running = await isAlive(state.pid, fetchImpl, state.port)
|
|
93
|
+
return { ok: true, running, state: { ...state, running } }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function isAlive(pid, fetchImpl, port = DEFAULT_ACCELERATED_PORT) {
|
|
97
|
+
try {
|
|
98
|
+
const response = await fetchImpl(`http://127.0.0.1:${port}/`, { signal: AbortSignal.timeout(1500) })
|
|
99
|
+
return response.ok || response.status < 500
|
|
100
|
+
} catch {
|
|
101
|
+
return false
|
|
102
|
+
}
|
|
103
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
|
|
3
|
+
//
|
|
4
|
+
// approval-drill — 在隔离的临时 dataRoot 里真实执行一次“提升审批”闭环:
|
|
5
|
+
// requestPromotion(red) → pending → decide(approved) → snapshot → 改动文件 → rollback
|
|
6
|
+
// 不触碰生产 dataDir、不加载真实插件、不写 profile;用于证明审批/快照/回滚链路可执行。
|
|
7
|
+
import fs from 'node:fs'
|
|
8
|
+
import os from 'node:os'
|
|
9
|
+
import path from 'node:path'
|
|
10
|
+
|
|
11
|
+
import { apply as applyApprover } from '../plugins/approver.mjs'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @returns {{
|
|
15
|
+
* ok:boolean, request:{id:string,kind:string,risk:string,outcome:string},
|
|
16
|
+
* pendingBefore:number, pendingAfter:number, snapshot:object, rollback:object,
|
|
17
|
+
* restored:boolean, target:string, dataRoot:string, cleanup:boolean
|
|
18
|
+
* }}
|
|
19
|
+
*/
|
|
20
|
+
export async function runApprovalDrill() {
|
|
21
|
+
const dataRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'fang-approval-drill-'))
|
|
22
|
+
const target = path.join(dataRoot, 'target')
|
|
23
|
+
fs.mkdirSync(target, { recursive: true })
|
|
24
|
+
fs.writeFileSync(path.join(target, 'plugin.mjs'), 'export const version = 1\n', 'utf8')
|
|
25
|
+
|
|
26
|
+
const services = new Map()
|
|
27
|
+
const disposers = []
|
|
28
|
+
const ctx = {
|
|
29
|
+
effect(fn) {
|
|
30
|
+
const dispose = fn()
|
|
31
|
+
if (typeof dispose === 'function') disposers.push(dispose)
|
|
32
|
+
return () => { try { dispose?.() } catch { /* ignore */ } }
|
|
33
|
+
},
|
|
34
|
+
provide(key, value) { services.set(key, value); return () => services.delete(key) },
|
|
35
|
+
get(key) { return services.get(key) },
|
|
36
|
+
logger: { info() {}, warn() {}, debug() {}, error() {} },
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
let approver = null
|
|
40
|
+
let requestPromise = null
|
|
41
|
+
try {
|
|
42
|
+
applyApprover(ctx, {
|
|
43
|
+
dataRoot,
|
|
44
|
+
defaultTtlMs: 10000,
|
|
45
|
+
authMode: 'manual',
|
|
46
|
+
strictRedLine: true,
|
|
47
|
+
snapshotGenerations: 3,
|
|
48
|
+
})
|
|
49
|
+
approver = services.get('fangApprover')
|
|
50
|
+
if (!approver || typeof approver.requestPromotion !== 'function') {
|
|
51
|
+
return { ok: false, error: 'approver-service-missing', dataRoot, cleanup: false }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
requestPromise = approver.requestPromotion({
|
|
55
|
+
pluginId: 'approval-drill',
|
|
56
|
+
taskId: 'approval-drill',
|
|
57
|
+
detail: '隔离审批 drill:验证 request→decide→snapshot→rollback',
|
|
58
|
+
ttlMs: 10000,
|
|
59
|
+
})
|
|
60
|
+
// request() 同步入队;让出一次事件循环以确保 pending 可见。
|
|
61
|
+
await new Promise((resolve) => setImmediate(resolve))
|
|
62
|
+
const pendingBefore = approver.pending()
|
|
63
|
+
if (pendingBefore.length !== 1) {
|
|
64
|
+
return { ok: false, error: 'request-not-pending', pendingBefore: pendingBefore.length, dataRoot, cleanup: false }
|
|
65
|
+
}
|
|
66
|
+
const id = String(pendingBefore[0].id)
|
|
67
|
+
const decided = approver.decide(id, 'approved', { by: 'approval-drill', note: 'isolated drill' })
|
|
68
|
+
const outcome = await requestPromise
|
|
69
|
+
const pendingAfter = approver.pending().length
|
|
70
|
+
requestPromise = null
|
|
71
|
+
|
|
72
|
+
const snapshot = await approver.snapshot({ tag: 'approval-drill', dir: target })
|
|
73
|
+
fs.writeFileSync(path.join(target, 'plugin.mjs'), 'export const version = 2\n', 'utf8')
|
|
74
|
+
const rollback = await approver.rollback({ tag: 'approval-drill', dir: target })
|
|
75
|
+
const restored = fs.readFileSync(path.join(target, 'plugin.mjs'), 'utf8') === 'export const version = 1\n'
|
|
76
|
+
|
|
77
|
+
return {
|
|
78
|
+
ok: outcome?.outcome === 'approved' && decided?.ok === true && snapshot?.ok !== false && rollback?.ok === true && restored && pendingAfter === 0,
|
|
79
|
+
request: { id, kind: 'promotion', risk: 'red', outcome: String(outcome?.outcome ?? '') },
|
|
80
|
+
decided,
|
|
81
|
+
pendingBefore: pendingBefore.length,
|
|
82
|
+
pendingAfter,
|
|
83
|
+
snapshot,
|
|
84
|
+
rollback,
|
|
85
|
+
restored,
|
|
86
|
+
target,
|
|
87
|
+
dataRoot,
|
|
88
|
+
cleanup: false,
|
|
89
|
+
}
|
|
90
|
+
} finally {
|
|
91
|
+
// 未决请求不能被遗留在计时器里:显式拒绝/超时结算。
|
|
92
|
+
if (requestPromise) {
|
|
93
|
+
const pending = approver?.pending?.() ?? []
|
|
94
|
+
for (const item of pending) {
|
|
95
|
+
try { approver.decide(item.id, 'denied', { by: 'approval-drill-cleanup' }) } catch { /* ignore */ }
|
|
96
|
+
}
|
|
97
|
+
await requestPromise.catch(() => {})
|
|
98
|
+
}
|
|
99
|
+
for (const dispose of disposers.reverse()) { try { dispose() } catch { /* ignore */ } }
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** 删除 drill 的临时目录;返回是否已不存在。 */
|
|
104
|
+
export function cleanupApprovalDrill(result) {
|
|
105
|
+
const dir = String(result?.dataRoot ?? '')
|
|
106
|
+
if (!dir) return true
|
|
107
|
+
try { fs.rmSync(dir, { recursive: true, force: true }) } catch { /* ignore */ }
|
|
108
|
+
return !fs.existsSync(dir)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export const _internals = { runApprovalDrill, cleanupApprovalDrill }
|
package/src/lib/boot-guard.mjs
CHANGED
|
@@ -14,7 +14,7 @@ import { createRequire } from 'node:module'
|
|
|
14
14
|
|
|
15
15
|
import { parseYamlSubset } from './rule-registry.mjs'
|
|
16
16
|
|
|
17
|
-
export const FANG_PACKAGE_NAMES = Object.freeze(['@twinsearth/dsh-
|
|
17
|
+
export const FANG_PACKAGE_NAMES = Object.freeze(['@twinsearth/fang-dsh-plugin', '@twinsearth/dsh-fang', '@twinsearth/fang-dsh-plugin'])
|
|
18
18
|
export const SMOKE_TIMEOUT_MS = 8000
|
|
19
19
|
|
|
20
20
|
/** 找到 profile 里已安装的 fang 包目录(发布名优先,其次本地 link 名)。 */
|
|
@@ -35,7 +35,9 @@ export function readBundleRows(pkgDir) {
|
|
|
35
35
|
const value = parsed?.value
|
|
36
36
|
const insert = Array.isArray(value) ? value.flatMap((item) => Array.isArray(item?.insert) ? item.insert : []) : (Array.isArray(value?.insert) ? value.insert : [])
|
|
37
37
|
const rows = insert.filter((row) => row && typeof row === 'object' && row.id).map((row) => ({
|
|
38
|
-
id: String(row.id),
|
|
38
|
+
id: String(row.id),
|
|
39
|
+
name: row.name === undefined ? null : String(row.name),
|
|
40
|
+
disabled: row.disabled === true,
|
|
39
41
|
}))
|
|
40
42
|
return { ok: parsed.errors.length === 0, error: parsed.errors.length ? `patch-parse:${parsed.errors[0]}` : null, rows, parseErrors: parsed.errors }
|
|
41
43
|
}
|
|
@@ -109,6 +111,8 @@ export function checkBundleRows(rows, { profileDir, ownPackage = '', timeoutMs =
|
|
|
109
111
|
continue
|
|
110
112
|
}
|
|
111
113
|
seen.add(row.id)
|
|
114
|
+
// v3.3.3:disabled 行不会加载;不因可选子插件未安装/未启用而阻塞启动。
|
|
115
|
+
if (row.disabled === true) continue
|
|
112
116
|
if (!row.name) {
|
|
113
117
|
findings.push({ code: 'row-name-missing', level: 'warn', id: row.id })
|
|
114
118
|
continue
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
|
|
3
|
+
//
|
|
4
|
+
// B-7:chat.import 委托。
|
|
5
|
+
// dryRun(默认 true)返回确定性预览:同输入两次调用结果必须逐字节一致;
|
|
6
|
+
// 真正导入(dryRun=false)必须走瓮城审批——委托层返回 contract-approval-required 且不产生副作用。
|
|
7
|
+
import crypto from 'node:crypto'
|
|
8
|
+
|
|
9
|
+
export const CHAT_IMPORT_SOURCES = Object.freeze(['deepseek'])
|
|
10
|
+
|
|
11
|
+
/** Pure: validate delegated chat.import params. */
|
|
12
|
+
export function validateChatImport(params) {
|
|
13
|
+
const input = params && typeof params === 'object' ? params : {}
|
|
14
|
+
const source = String(input.source ?? '').trim().toLowerCase()
|
|
15
|
+
if (!CHAT_IMPORT_SOURCES.includes(source)) {
|
|
16
|
+
return { ok: false, error: 'contract-invalid-request', message: `unsupported import source: ${source || '(empty)'}` }
|
|
17
|
+
}
|
|
18
|
+
const sessionId = String(input.sessionId ?? '').trim()
|
|
19
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{2,120}$/.test(sessionId)) {
|
|
20
|
+
return { ok: false, error: 'contract-invalid-request', message: 'invalid sessionId' }
|
|
21
|
+
}
|
|
22
|
+
return {
|
|
23
|
+
ok: true,
|
|
24
|
+
source,
|
|
25
|
+
sessionId,
|
|
26
|
+
dryRun: input.dryRun !== false,
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Pure, deterministic dry-run preview for a chat import.
|
|
32
|
+
* `found` is whether the mother session catalog can see the session; the digest
|
|
33
|
+
* lets the caller verify two dry runs agree without moving payload bytes.
|
|
34
|
+
*/
|
|
35
|
+
export function buildChatImportDryRun({ source = '', sessionId = '', found = false, reason = null } = {}) {
|
|
36
|
+
const digest = crypto.createHash('sha256').update(`${source}\u0000${sessionId}`).digest('hex').slice(0, 16)
|
|
37
|
+
return {
|
|
38
|
+
source,
|
|
39
|
+
sessionId,
|
|
40
|
+
dryRun: true,
|
|
41
|
+
found: found === true,
|
|
42
|
+
wouldImport: found === true,
|
|
43
|
+
approvalRequired: true,
|
|
44
|
+
digest,
|
|
45
|
+
skipped: found === true ? [] : [reason ?? 'session-not-found'],
|
|
46
|
+
}
|
|
47
|
+
}
|
package/src/lib/compat.mjs
CHANGED
|
@@ -34,8 +34,12 @@ export const REQUIRED_ROUTE_PATHS = Object.freeze([
|
|
|
34
34
|
'/fang/api/tasks/branches',
|
|
35
35
|
'/fang/api/reflow/policy',
|
|
36
36
|
'/fang/api/composer/journal',
|
|
37
|
+
'/fang/api/fork-core',
|
|
37
38
|
])
|
|
38
|
-
|
|
39
|
+
// v3.5.0 (P0): the accelerated Web sidecar retired 3 routes (/accelerated/status|start|stop)
|
|
40
|
+
// and added /fang/api/fork-core → 88 - 3 + 1 = 86.
|
|
41
|
+
// 2026-11-22: added /fang/api/tasks/repair (one-click repair) → 87.
|
|
42
|
+
export const DEFAULT_EXPECTED_ROUTE_COUNT = 89
|
|
39
43
|
|
|
40
44
|
/**
|
|
41
45
|
* 列出需要做导入检查的插件模块文件(排序稳定)。
|