@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,568 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
|
|
4
|
+
//
|
|
5
|
+
// restart-watchdog — C 方案「外部看护」:不改 DSH 启动方式,只旁路观察宿主。
|
|
6
|
+
//
|
|
7
|
+
// 它每 poll-ms 读一次 <dataDir>/fang.pid(守卫插件在母体启动时写、优雅卸载时删):
|
|
8
|
+
// 宿主活着 → 继续观察(execute 模式下同时续写 supervisor.present 心跳)
|
|
9
|
+
// 宿主死了 → 只读校验 <stateDir>/approved/<id>.json:
|
|
10
|
+
// 没有 armed/未过期/pid 匹配/无回执的清单 → 不干预,退出
|
|
11
|
+
// 有清单 + --execute → 用 `--` 之后的命令重启宿主
|
|
12
|
+
// 有清单 + dry-run(默认) → 只报告 would-relaunch
|
|
13
|
+
// 重启成功后写 executed/<id>.json 回执(execution.executed=true),这是唯一的执行证明。
|
|
14
|
+
//
|
|
15
|
+
// 用法:
|
|
16
|
+
// node tools/restart-watchdog.mjs --data-root <dir> -- <重启命令 argv...>
|
|
17
|
+
// node tools/restart-watchdog.mjs --execute --data-root <dir> -- <重启命令 argv...>
|
|
18
|
+
//
|
|
19
|
+
// 安全边界:
|
|
20
|
+
// * 默认 dry-run;只有 --execute 才会写 supervisor.present(守卫据此判断「有人在拉起我」)
|
|
21
|
+
// 并真正 spawn 重启命令。
|
|
22
|
+
// * 没有清单/清单未 armed/过期/pid 不匹配/已有回执 => 不干预,绝不重启。
|
|
23
|
+
// * 与 DSH Desktop 的启动方式无关:命令由用户提供,watchdog 不猜。
|
|
24
|
+
import fs from 'node:fs'
|
|
25
|
+
import path from 'node:path'
|
|
26
|
+
import { spawn } from 'node:child_process'
|
|
27
|
+
import { fileURLToPath } from 'node:url'
|
|
28
|
+
|
|
29
|
+
import {
|
|
30
|
+
appendJsonl,
|
|
31
|
+
ensureDir,
|
|
32
|
+
resolveFangLayout,
|
|
33
|
+
sleep,
|
|
34
|
+
writeJsonAtomic,
|
|
35
|
+
} from '../src/kernel/index.mjs'
|
|
36
|
+
import {
|
|
37
|
+
buildExecutionReceipt,
|
|
38
|
+
receiptFile,
|
|
39
|
+
} from '../src/lib/restart-contract.mjs'
|
|
40
|
+
import { readForkSupervisionSettings } from '../src/lib/fork-supervision-settings.mjs'
|
|
41
|
+
import { detectDesktopProfileDir, runBootGuard } from '../src/lib/desktop-launch.mjs'
|
|
42
|
+
import { GATED_RESTART_EXIT, verifyApprovalForPid, writeRestartReceipt } from './restart-supervisor.mjs'
|
|
43
|
+
import { runMainGate, formatGateFailure } from '../src/lib/main-gate.mjs'
|
|
44
|
+
|
|
45
|
+
export const WATCHDOG_ID = 'fang-restart-watchdog'
|
|
46
|
+
export const MARKER_FILENAME = 'supervisor.present'
|
|
47
|
+
export const DEFAULTS = Object.freeze({
|
|
48
|
+
execute: false,
|
|
49
|
+
pollMs: 2000,
|
|
50
|
+
maxRelaunches: 3,
|
|
51
|
+
startupTimeoutMs: 60000,
|
|
52
|
+
dataRoot: '',
|
|
53
|
+
stateDir: '',
|
|
54
|
+
pidFile: '',
|
|
55
|
+
log: '',
|
|
56
|
+
supervisorId: WATCHDOG_ID,
|
|
57
|
+
// null = 只在 --execute 时自动拉起分身;true/false 可显式覆盖
|
|
58
|
+
autostartForks: null,
|
|
59
|
+
motherUrl: '',
|
|
60
|
+
token: '',
|
|
61
|
+
autostartTimeoutMs: 15000,
|
|
62
|
+
profileDir: '',
|
|
63
|
+
bootGuard: true,
|
|
64
|
+
safeModeOnFailure: true,
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
export const USAGE = `usage: node tools/restart-watchdog.mjs [options] -- <relaunch command argv...>
|
|
68
|
+
|
|
69
|
+
外部看护(C):不改 DSH 启动方式;只在宿主以退出码 75 死亡且存在 armed 授权清单时重启它。
|
|
70
|
+
|
|
71
|
+
options:
|
|
72
|
+
--data-root <dir> Fang 数据根目录(默认 resolveFangLayout())
|
|
73
|
+
--pid-file <file> 宿主 pid 文件(默认 <dataDir>/fang.pid)
|
|
74
|
+
--state-dir <dir> 守卫状态目录(默认 <dataDir>/restart)
|
|
75
|
+
--execute 真正重启(默认 dry-run:只报告 would-relaunch)
|
|
76
|
+
--poll-ms <n> 轮询间隔(默认 ${DEFAULTS.pollMs}ms)
|
|
77
|
+
--max-relaunches <n> 最多重启次数(默认 ${DEFAULTS.maxRelaunches})
|
|
78
|
+
--startup-timeout-ms <n> 重启后等新 pid 出现的上限(默认 ${DEFAULTS.startupTimeoutMs}ms)
|
|
79
|
+
--autostart-forks 启动时自动拉起已登记但没在跑的分身(默认:--execute 时开启)
|
|
80
|
+
--no-autostart-forks 关闭分身自动启动
|
|
81
|
+
--mother-url <url> 母体 HTTP 地址(默认读 <dataDir>/endpoint.json)
|
|
82
|
+
--token <token> 母体鉴权 token(默认 env DSH_FANG_AUTH_TOKEN 或 <dataDir>/fang-auth.json)
|
|
83
|
+
--supervisor-id <id> 写进执行回执的执行者标识(默认 ${DEFAULTS.supervisorId})
|
|
84
|
+
--profile-dir <dir> DSH profile(用于重启前 boot-guard;默认自动探测)
|
|
85
|
+
--no-boot-guard 重启前不跑 boot-guard
|
|
86
|
+
--no-safe-mode boot-guard 失败只拒绝重启,不自动禁用 fang 行
|
|
87
|
+
--log <file> 看护日志(默认 <stateDir>/watchdog.jsonl)
|
|
88
|
+
-h, --help 显示本帮助
|
|
89
|
+
|
|
90
|
+
examples:
|
|
91
|
+
node tools/restart-watchdog.mjs --data-root E:\\fang-data -- "E:\\DS\\DeepSeek Harness.exe"
|
|
92
|
+
node tools/restart-watchdog.mjs --execute --data-root E:\\fang-data -- "E:\\DS\\DeepSeek Harness.exe"
|
|
93
|
+
`
|
|
94
|
+
|
|
95
|
+
const CLAMP = (n, lo, hi) => Math.min(hi, Math.max(lo, n))
|
|
96
|
+
|
|
97
|
+
function parsePositiveInt(raw, name, { min = 0, max = 1_000_000 } = {}) {
|
|
98
|
+
const n = Number(raw)
|
|
99
|
+
if (!Number.isFinite(n) || !Number.isInteger(n) || n < min || n > max) {
|
|
100
|
+
throw new Error(`${name} must be an integer in [${min}, ${max}]`)
|
|
101
|
+
}
|
|
102
|
+
return n
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function parseWatchdogArgs(argv = []) {
|
|
106
|
+
const options = { ...DEFAULTS }
|
|
107
|
+
let relaunch = []
|
|
108
|
+
for (let i = 0; i < argv.length; i++) {
|
|
109
|
+
const a = String(argv[i])
|
|
110
|
+
if (a === '--') { relaunch = argv.slice(i + 1).map(String); break }
|
|
111
|
+
if (a === '--help' || a === '-h') return { help: true, options, relaunch: [] }
|
|
112
|
+
const next = () => {
|
|
113
|
+
if (i + 1 >= argv.length) throw new Error(`missing value for ${a}`)
|
|
114
|
+
return String(argv[++i])
|
|
115
|
+
}
|
|
116
|
+
if (a === '--data-root') { options.dataRoot = next(); continue }
|
|
117
|
+
if (a.startsWith('--data-root=')) { options.dataRoot = a.slice('--data-root='.length); continue }
|
|
118
|
+
if (a === '--pid-file') { options.pidFile = next(); continue }
|
|
119
|
+
if (a.startsWith('--pid-file=')) { options.pidFile = a.slice('--pid-file='.length); continue }
|
|
120
|
+
if (a === '--state-dir') { options.stateDir = next(); continue }
|
|
121
|
+
if (a.startsWith('--state-dir=')) { options.stateDir = a.slice('--state-dir='.length); continue }
|
|
122
|
+
if (a === '--log') { options.log = next(); continue }
|
|
123
|
+
if (a.startsWith('--log=')) { options.log = a.slice('--log='.length); continue }
|
|
124
|
+
if (a === '--supervisor-id') { options.supervisorId = next(); continue }
|
|
125
|
+
if (a.startsWith('--supervisor-id=')) { options.supervisorId = a.slice('--supervisor-id='.length); continue }
|
|
126
|
+
if (a === '--execute') { options.execute = true; continue }
|
|
127
|
+
if (a === '--dry-run') { options.execute = false; continue }
|
|
128
|
+
if (a === '--poll-ms') { options.pollMs = parsePositiveInt(next(), '--poll-ms', { min: 10, max: 3_600_000 }); continue }
|
|
129
|
+
if (a.startsWith('--poll-ms=')) { options.pollMs = parsePositiveInt(a.slice('--poll-ms='.length), '--poll-ms', { min: 10, max: 3_600_000 }); continue }
|
|
130
|
+
if (a === '--max-relaunches') { options.maxRelaunches = parsePositiveInt(next(), '--max-relaunches', { min: 0, max: 20 }); continue }
|
|
131
|
+
if (a.startsWith('--max-relaunches=')) { options.maxRelaunches = parsePositiveInt(a.slice('--max-relaunches='.length), '--max-relaunches', { min: 0, max: 20 }); continue }
|
|
132
|
+
if (a === '--startup-timeout-ms') { options.startupTimeoutMs = parsePositiveInt(next(), '--startup-timeout-ms', { min: 100, max: 600000 }); continue }
|
|
133
|
+
if (a.startsWith('--startup-timeout-ms=')) { options.startupTimeoutMs = parsePositiveInt(a.slice('--startup-timeout-ms='.length), '--startup-timeout-ms', { min: 100, max: 600000 }); continue }
|
|
134
|
+
if (a === '--autostart-timeout-ms') { options.autostartTimeoutMs = parsePositiveInt(next(), '--autostart-timeout-ms', { min: 100, max: 600000 }); continue }
|
|
135
|
+
if (a.startsWith('--autostart-timeout-ms=')) { options.autostartTimeoutMs = parsePositiveInt(a.slice('--autostart-timeout-ms='.length), '--autostart-timeout-ms', { min: 100, max: 600000 }); continue }
|
|
136
|
+
if (a === '--autostart-forks') { options.autostartForks = true; continue }
|
|
137
|
+
if (a === '--no-autostart-forks') { options.autostartForks = false; continue }
|
|
138
|
+
if (a === '--profile-dir') { options.profileDir = next(); continue }
|
|
139
|
+
if (a.startsWith('--profile-dir=')) { options.profileDir = a.slice('--profile-dir='.length); continue }
|
|
140
|
+
if (a === '--no-boot-guard') { options.bootGuard = false; continue }
|
|
141
|
+
if (a === '--no-safe-mode') { options.safeModeOnFailure = false; continue }
|
|
142
|
+
if (a === '--mother-url') { options.motherUrl = next(); continue }
|
|
143
|
+
if (a.startsWith('--mother-url=')) { options.motherUrl = a.slice('--mother-url='.length); continue }
|
|
144
|
+
if (a === '--token') { options.token = next(); continue }
|
|
145
|
+
if (a.startsWith('--token=')) { options.token = a.slice('--token='.length); continue }
|
|
146
|
+
throw new Error(`unknown option: ${a} (put the relaunch command after --)`)
|
|
147
|
+
}
|
|
148
|
+
if (!relaunch.length) throw new Error('missing relaunch command: use -- <command> [args...]')
|
|
149
|
+
if (!options.supervisorId || options.supervisorId.length > 128) throw new Error('--supervisor-id must be 1..128 chars')
|
|
150
|
+
return { options, relaunch }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function stateDirForWatchdog(options = {}) {
|
|
154
|
+
if (options.stateDir) return String(options.stateDir)
|
|
155
|
+
const layout = resolveFangLayout({ dataRoot: options.dataRoot ?? '' })
|
|
156
|
+
return path.join(layout.dataDir, 'restart')
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function pidFileFor(options = {}) {
|
|
160
|
+
if (options.pidFile) return String(options.pidFile)
|
|
161
|
+
if (options.stateDir) return path.join(path.dirname(String(options.stateDir)), 'fang.pid')
|
|
162
|
+
const layout = resolveFangLayout({ dataRoot: options.dataRoot ?? '' })
|
|
163
|
+
return layout.pidFile
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function markerFileFor(stateDir) {
|
|
167
|
+
return path.join(String(stateDir), MARKER_FILENAME)
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function writeSupervisorMarker(stateDir, { pid = process.pid, execute = false, supervisor = WATCHDOG_ID } = {}) {
|
|
171
|
+
ensureDir(stateDir)
|
|
172
|
+
const file = markerFileFor(stateDir)
|
|
173
|
+
writeJsonAtomic(file, { version: 1, supervisor, pid, execute: execute === true, at: Date.now() })
|
|
174
|
+
return file
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function clearSupervisorMarker(stateDir, { pid = process.pid } = {}) {
|
|
178
|
+
const file = markerFileFor(stateDir)
|
|
179
|
+
try {
|
|
180
|
+
const raw = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
181
|
+
if (Number(raw?.pid) === Number(pid)) fs.unlinkSync(file)
|
|
182
|
+
} catch { /* already gone */ }
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** 读宿主 pid 文件;兼容 {pid} JSON 与纯数字文本。读不到返回 null。 */
|
|
186
|
+
export function readHostPid(pidFile) {
|
|
187
|
+
try {
|
|
188
|
+
const raw = fs.readFileSync(pidFile, 'utf8').replace(/^\uFEFF/, '').trim()
|
|
189
|
+
if (!raw) return null
|
|
190
|
+
if (/^\d+$/.test(raw)) return Number(raw)
|
|
191
|
+
const parsed = JSON.parse(raw)
|
|
192
|
+
const pid = Number(parsed?.pid)
|
|
193
|
+
return Number.isInteger(pid) && pid > 0 ? pid : null
|
|
194
|
+
} catch {
|
|
195
|
+
return null
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export function isPidAlive(pid) {
|
|
200
|
+
if (!Number.isInteger(pid) || pid <= 0) return false
|
|
201
|
+
try { process.kill(pid, 0); return true } catch (error) { return error?.code === 'EPERM' }
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export function dataDirForWatchdog(options = {}) {
|
|
205
|
+
if (options.stateDir) return path.dirname(String(options.stateDir))
|
|
206
|
+
const layout = resolveFangLayout({ dataRoot: options.dataRoot ?? '' })
|
|
207
|
+
return layout.dataDir
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** 母体 HTTP 地址:显式 --mother-url 优先,否则读 orchestrator 写的 <dataDir>/endpoint.json。 */
|
|
211
|
+
export function readMotherEndpoint(options = {}) {
|
|
212
|
+
if (options.motherUrl) return String(options.motherUrl).replace(/\/+$/, '')
|
|
213
|
+
try {
|
|
214
|
+
const doc = JSON.parse(fs.readFileSync(path.join(dataDirForWatchdog(options), 'endpoint.json'), 'utf8'))
|
|
215
|
+
return String(doc?.url ?? '').replace(/\/+$/, '')
|
|
216
|
+
} catch {
|
|
217
|
+
return ''
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** 母体鉴权 token:显式 --token > env DSH_FANG_AUTH_TOKEN > <dataDir>/fang-auth.json。 */
|
|
222
|
+
export function readMotherToken(options = {}) {
|
|
223
|
+
if (options.token) return String(options.token)
|
|
224
|
+
const env = String(process.env.DSH_FANG_AUTH_TOKEN ?? '').trim()
|
|
225
|
+
if (env) return env
|
|
226
|
+
try {
|
|
227
|
+
const doc = JSON.parse(fs.readFileSync(path.join(dataDirForWatchdog(options), 'fang-auth.json'), 'utf8'))
|
|
228
|
+
return String(doc?.token ?? '')
|
|
229
|
+
} catch {
|
|
230
|
+
return ''
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** UI 持久化开关 vs CLI 显式覆盖:给出本次 watchdog 是否请求 autostart。 */
|
|
235
|
+
export function resolveAutostartPreference(options = {}) {
|
|
236
|
+
const settings = readForkSupervisionSettings(dataDirForWatchdog(options))
|
|
237
|
+
const explicit = options.autostartForks === true || options.autostartForks === false
|
|
238
|
+
const want = explicit
|
|
239
|
+
? options.autostartForks === true
|
|
240
|
+
: (options.execute === true && settings.autostartForks !== false)
|
|
241
|
+
return { want, source: explicit ? 'cli' : 'settings', settings }
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
export async function requestAutostartForks(options = {}) {
|
|
246
|
+
const base = readMotherEndpoint(options)
|
|
247
|
+
if (!base) return { ok: false, error: 'mother-url-unavailable' }
|
|
248
|
+
const token = readMotherToken(options)
|
|
249
|
+
if (!token) return { ok: false, error: 'auth-token-unavailable' }
|
|
250
|
+
const controller = new AbortController()
|
|
251
|
+
const timer = setTimeout(() => controller.abort(), Math.max(1000, Number(options.autostartTimeoutMs) || 15000))
|
|
252
|
+
try {
|
|
253
|
+
const res = await fetch(`${base}/fang/api/forks/autostart`, {
|
|
254
|
+
method: 'POST',
|
|
255
|
+
headers: { 'content-type': 'application/json', 'x-fang-auth': token, accept: 'application/json' },
|
|
256
|
+
body: '{}',
|
|
257
|
+
signal: controller.signal,
|
|
258
|
+
})
|
|
259
|
+
const text = await res.text()
|
|
260
|
+
let body = null
|
|
261
|
+
try { body = text ? JSON.parse(text) : null } catch { body = null }
|
|
262
|
+
if (!res.ok || body?.ok === false) {
|
|
263
|
+
return { ok: false, status: res.status, error: body?.error ?? 'autostart-http-error', body }
|
|
264
|
+
}
|
|
265
|
+
return {
|
|
266
|
+
ok: true,
|
|
267
|
+
status: res.status,
|
|
268
|
+
started: Array.isArray(body?.started) ? body.started.length : 0,
|
|
269
|
+
failed: Array.isArray(body?.failed) ? body.failed.length : 0,
|
|
270
|
+
skipped: Array.isArray(body?.skipped) ? body.skipped.length : 0,
|
|
271
|
+
body,
|
|
272
|
+
}
|
|
273
|
+
} catch (error) {
|
|
274
|
+
return {
|
|
275
|
+
ok: false,
|
|
276
|
+
error: error?.name === 'AbortError' ? 'autostart-timeout' : 'autostart-failed',
|
|
277
|
+
detail: String(error?.message ?? error),
|
|
278
|
+
}
|
|
279
|
+
} finally {
|
|
280
|
+
clearTimeout(timer)
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** spawn 一个重启命令;detached + 不捕获 stdio,避免看护进程退出时带走宿主。 */
|
|
285
|
+
export function spawnRelaunch(argv, { spawnImpl = spawn } = {}) {
|
|
286
|
+
try {
|
|
287
|
+
const child = spawnImpl(argv[0], argv.slice(1), {
|
|
288
|
+
detached: true,
|
|
289
|
+
stdio: 'ignore',
|
|
290
|
+
env: process.env,
|
|
291
|
+
})
|
|
292
|
+
child.on?.('error', () => { /* 错误由调用方通过 pid 确认兜底 */ })
|
|
293
|
+
child.unref?.()
|
|
294
|
+
return { ok: true, pid: Number.isInteger(child.pid) ? child.pid : null }
|
|
295
|
+
} catch (error) {
|
|
296
|
+
return { ok: false, pid: null, error: String(error?.message ?? error) }
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* 看护主循环(可注入 verify/sleep/spawn,测试用)。
|
|
302
|
+
* @returns {Promise<{relaunches:number, stopped:string, deadPid:number|null, manifestId:string|null, receipts:Array, reason?:string}>}
|
|
303
|
+
*/
|
|
304
|
+
export async function watch({
|
|
305
|
+
relaunch,
|
|
306
|
+
options = {},
|
|
307
|
+
verify = verifyApprovalForPid,
|
|
308
|
+
sleepFn = sleep,
|
|
309
|
+
spawnImpl = spawn,
|
|
310
|
+
signal = null,
|
|
311
|
+
logSink = null,
|
|
312
|
+
guard = null,
|
|
313
|
+
} = {}) {
|
|
314
|
+
if (!Array.isArray(relaunch) || !relaunch.length) throw new Error('watch() requires a relaunch command argv')
|
|
315
|
+
const opts = { ...DEFAULTS, ...options }
|
|
316
|
+
const stateDir = stateDirForWatchdog(opts)
|
|
317
|
+
const pidFile = pidFileFor(opts)
|
|
318
|
+
const logFile = opts.log ? String(opts.log) : path.join(stateDir, 'watchdog.jsonl')
|
|
319
|
+
const log = (event, data = {}) => {
|
|
320
|
+
try {
|
|
321
|
+
ensureDir(path.dirname(logFile))
|
|
322
|
+
appendJsonl(logFile, { at: new Date().toISOString(), watchdogPid: process.pid, event, ...data })
|
|
323
|
+
} catch { /* ignore */ }
|
|
324
|
+
try { logSink?.(event, data) } catch { /* ignore */ }
|
|
325
|
+
}
|
|
326
|
+
const result = {
|
|
327
|
+
execute: opts.execute === true,
|
|
328
|
+
relaunches: 0,
|
|
329
|
+
stopped: null,
|
|
330
|
+
deadPid: null,
|
|
331
|
+
manifestId: null,
|
|
332
|
+
receipts: [],
|
|
333
|
+
autostart: null,
|
|
334
|
+
}
|
|
335
|
+
// UI 持久化开关是默认值:CLI --autostart-forks/--no-autostart-forks 显式覆盖。
|
|
336
|
+
const autostartPreference = resolveAutostartPreference(opts)
|
|
337
|
+
const wantAutostart = autostartPreference.want
|
|
338
|
+
result.supervision = {
|
|
339
|
+
autostartForks: autostartPreference.settings.autostartForks,
|
|
340
|
+
source: autostartPreference.source,
|
|
341
|
+
settingsFile: autostartPreference.settings.file,
|
|
342
|
+
}
|
|
343
|
+
let autostartDone = false
|
|
344
|
+
let autostartAttempts = 0
|
|
345
|
+
let markerWritten = false
|
|
346
|
+
const refreshMarker = () => {
|
|
347
|
+
if (!opts.execute) return
|
|
348
|
+
try {
|
|
349
|
+
writeSupervisorMarker(stateDir, { execute: true, supervisor: opts.supervisorId })
|
|
350
|
+
markerWritten = true
|
|
351
|
+
} catch (error) {
|
|
352
|
+
log('marker-write-failed', { error: String(error?.message ?? error) })
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
const stop = (reason) => {
|
|
356
|
+
result.stopped = reason
|
|
357
|
+
if (markerWritten) clearSupervisorMarker(stateDir)
|
|
358
|
+
log('watchdog-stop', { reason, relaunches: result.relaunches })
|
|
359
|
+
return result
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
log('watchdog-start', {
|
|
363
|
+
pidFile, stateDir, dryRun: !opts.execute, pollMs: opts.pollMs,
|
|
364
|
+
maxRelaunches: opts.maxRelaunches, relaunch,
|
|
365
|
+
})
|
|
366
|
+
refreshMarker()
|
|
367
|
+
|
|
368
|
+
try {
|
|
369
|
+
for (;;) {
|
|
370
|
+
if (signal?.aborted) return stop('aborted')
|
|
371
|
+
refreshMarker()
|
|
372
|
+
|
|
373
|
+
const pid = readHostPid(pidFile)
|
|
374
|
+
if (!Number.isInteger(pid) || pid <= 0) {
|
|
375
|
+
log('pid-missing', { pidFile })
|
|
376
|
+
await sleepFn(Math.max(20, opts.pollMs))
|
|
377
|
+
continue
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
if (isPidAlive(pid)) {
|
|
381
|
+
result.deadPid = null
|
|
382
|
+
// 宿主活着:按需把已登记但没在跑的分身拉起来(只做一次;失败重试 3 次后放弃)。
|
|
383
|
+
if (wantAutostart && !autostartDone) {
|
|
384
|
+
if (!opts.execute) {
|
|
385
|
+
log('would-autostart-forks', { pid })
|
|
386
|
+
result.autostart = { requested: false, reason: 'dry-run' }
|
|
387
|
+
autostartDone = true
|
|
388
|
+
} else {
|
|
389
|
+
const out = await requestAutostartForks(opts)
|
|
390
|
+
autostartAttempts++
|
|
391
|
+
if (out.ok) {
|
|
392
|
+
autostartDone = true
|
|
393
|
+
result.autostart = {
|
|
394
|
+
requested: true, ok: true, started: out.started ?? 0,
|
|
395
|
+
failed: out.failed ?? 0, skipped: out.skipped ?? 0,
|
|
396
|
+
}
|
|
397
|
+
log('autostart-forks', result.autostart)
|
|
398
|
+
} else if (autostartAttempts >= 3) {
|
|
399
|
+
autostartDone = true
|
|
400
|
+
result.autostart = { requested: true, ok: false, error: out.error }
|
|
401
|
+
log('autostart-forks-failed', result.autostart)
|
|
402
|
+
} else {
|
|
403
|
+
log('autostart-forks-deferred', { error: out.error, attempt: autostartAttempts })
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
await sleepFn(Math.max(20, opts.pollMs))
|
|
408
|
+
continue
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// 宿主已死:只认 armed/未过期/pid 匹配/无回执的清单
|
|
412
|
+
result.deadPid = pid
|
|
413
|
+
log('host-dead', { pid })
|
|
414
|
+
const verdict = verify({ stateDir, pid, now: Date.now() })
|
|
415
|
+
if (!verdict?.ok) {
|
|
416
|
+
log('no-approved-restart', { pid, reason: verdict?.reason ?? 'not-authorized' })
|
|
417
|
+
result.reason = verdict?.reason ?? 'not-authorized'
|
|
418
|
+
return stop('no-approved-restart')
|
|
419
|
+
}
|
|
420
|
+
const manifest = verdict.manifest
|
|
421
|
+
result.manifestId = manifest.id
|
|
422
|
+
|
|
423
|
+
if (!opts.execute) {
|
|
424
|
+
log('would-relaunch', { pid, manifestId: manifest.id })
|
|
425
|
+
return stop('dry-run')
|
|
426
|
+
}
|
|
427
|
+
if (result.relaunches >= opts.maxRelaunches) return stop('max-relaunches')
|
|
428
|
+
|
|
429
|
+
// 重启前自检:坏 profile/候选行/上次启动期崩溃 → 安全模式或拒绝重启。
|
|
430
|
+
if (typeof guard === 'function') {
|
|
431
|
+
let gate = null
|
|
432
|
+
try { gate = await guard() } catch (error) { gate = { ok: false, error: String(error?.message ?? error) } }
|
|
433
|
+
result.guard = gate
|
|
434
|
+
if (gate?.safeModeApplied) log('boot-guard-safe-mode', { reason: gate.reason ?? 'unknown', added: gate.applied?.added ?? 0 })
|
|
435
|
+
else if (gate?.skipped) log('boot-guard-skipped', { reason: gate.skipped })
|
|
436
|
+
else if (gate?.ok) log('boot-guard-pass', { checked: gate.checked ?? 0 })
|
|
437
|
+
if (!gate?.ok) {
|
|
438
|
+
result.reason = String(gate?.error ?? 'boot-guard-blocked')
|
|
439
|
+
log('boot-guard-blocked', { error: result.reason })
|
|
440
|
+
return stop('boot-guard-blocked')
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
const launched = spawnRelaunch(relaunch, { spawnImpl })
|
|
445
|
+
if (!launched.ok) {
|
|
446
|
+
result.reason = launched.error
|
|
447
|
+
log('relaunch-spawn-failed', { error: launched.error })
|
|
448
|
+
return stop('relaunch-spawn-failed')
|
|
449
|
+
}
|
|
450
|
+
result.relaunches++
|
|
451
|
+
|
|
452
|
+
// 等新宿主写 pid 文件(最多 startupTimeoutMs);确认后回执记录新 host pid。
|
|
453
|
+
const deadline = Date.now() + Math.max(100, opts.startupTimeoutMs)
|
|
454
|
+
let newPid = null
|
|
455
|
+
while (Date.now() < deadline) {
|
|
456
|
+
if (signal?.aborted) return stop('aborted')
|
|
457
|
+
const seen = readHostPid(pidFile)
|
|
458
|
+
if (Number.isInteger(seen) && seen > 0 && seen !== pid && isPidAlive(seen)) { newPid = seen; break }
|
|
459
|
+
await sleepFn(Math.min(120, Math.max(20, opts.pollMs)))
|
|
460
|
+
}
|
|
461
|
+
const replacedAt = Date.now()
|
|
462
|
+
let receipt
|
|
463
|
+
try {
|
|
464
|
+
const written = writeRestartReceipt({
|
|
465
|
+
stateDir,
|
|
466
|
+
manifest,
|
|
467
|
+
supervisorId: opts.supervisorId,
|
|
468
|
+
executedAt: replacedAt,
|
|
469
|
+
exitCode: GATED_RESTART_EXIT,
|
|
470
|
+
previousPid: pid,
|
|
471
|
+
replacementPid: newPid ?? null,
|
|
472
|
+
})
|
|
473
|
+
receipt = { id: manifest.id, file: written.file, digest: written.receipt.digest }
|
|
474
|
+
result.receipts.push(receipt)
|
|
475
|
+
log('relaunched', { manifestId: manifest.id, previousPid: pid, replacementPid: newPid, spawnedPid: launched.pid, receipt: written.file })
|
|
476
|
+
} catch (error) {
|
|
477
|
+
result.reason = String(error?.message ?? error)
|
|
478
|
+
log('receipt-write-failed', { error: result.reason })
|
|
479
|
+
return stop('receipt-write-failed')
|
|
480
|
+
}
|
|
481
|
+
if (!newPid) {
|
|
482
|
+
// 无法确认新宿主 pid:已写回执(执行确实发生),但不继续看护未知进程。
|
|
483
|
+
log('replacement-unconfirmed', { spawnedPid: launched.pid })
|
|
484
|
+
result.reason = 'replacement-unconfirmed'
|
|
485
|
+
return stop('replacement-unconfirmed')
|
|
486
|
+
}
|
|
487
|
+
// 继续观察新宿主;下一轮会从新 pid 开始。
|
|
488
|
+
await sleepFn(Math.max(20, opts.pollMs))
|
|
489
|
+
}
|
|
490
|
+
} finally {
|
|
491
|
+
if (markerWritten) clearSupervisorMarker(stateDir)
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
export async function main(argv = process.argv.slice(2)) {
|
|
496
|
+
let parsed
|
|
497
|
+
try {
|
|
498
|
+
parsed = parseWatchdogArgs(argv)
|
|
499
|
+
} catch (error) {
|
|
500
|
+
console.error(`[restart-watchdog] ${error?.message ?? error}`)
|
|
501
|
+
console.error(USAGE)
|
|
502
|
+
return 2
|
|
503
|
+
}
|
|
504
|
+
if (parsed.help) { console.log(USAGE); return 0 }
|
|
505
|
+
// 自动 profile 探测:DSH_PROFILE_DIR / DSH_HOME/profiles/<profile>;探测不到则跳过(不阻塞)。
|
|
506
|
+
let guard = null
|
|
507
|
+
if (parsed.options.bootGuard) {
|
|
508
|
+
const dataDir = dataDirForWatchdog(parsed.options)
|
|
509
|
+
const profileDir = String(parsed.options.profileDir ?? '').trim()
|
|
510
|
+
|| detectDesktopProfileDir({ env: process.env, args: parsed.relaunch })
|
|
511
|
+
if (profileDir) {
|
|
512
|
+
guard = async () => {
|
|
513
|
+
const boot = runBootGuard(profileDir, {
|
|
514
|
+
dataRoot: dataDir,
|
|
515
|
+
safeModeOnFailure: parsed.options.execute === true && parsed.options.safeModeOnFailure !== false,
|
|
516
|
+
})
|
|
517
|
+
if (!boot.ok) return boot
|
|
518
|
+
// v3.3.0 主城门禁(部署):profile/审计链/崩溃循环/备份/磁盘;execute 时自动做备份。
|
|
519
|
+
const profileName = path.basename(path.resolve(profileDir))
|
|
520
|
+
const homeDir = path.dirname(path.dirname(path.resolve(profileDir)))
|
|
521
|
+
const gate = runMainGate({
|
|
522
|
+
target: 'deploy',
|
|
523
|
+
homeDir,
|
|
524
|
+
profile: profileName,
|
|
525
|
+
profileDir: path.resolve(profileDir),
|
|
526
|
+
dataDir,
|
|
527
|
+
repair: parsed.options.execute === true,
|
|
528
|
+
requireBackup: parsed.options.execute === true,
|
|
529
|
+
supervisorPresent: parsed.options.execute === true,
|
|
530
|
+
})
|
|
531
|
+
if (!gate.ok) {
|
|
532
|
+
return { ok: false, error: 'main-city-gate-blocked', reason: formatGateFailure(gate), gate, profileDir }
|
|
533
|
+
}
|
|
534
|
+
return { ok: true, boot, gate, profileDir }
|
|
535
|
+
}
|
|
536
|
+
console.log(`[restart-watchdog] boot-guard + main-city deploy gate: ${profileDir}`)
|
|
537
|
+
} else {
|
|
538
|
+
console.log('[restart-watchdog] boot-guard skipped: profile not detected (pass --profile-dir)')
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
const result = await watch({ relaunch: parsed.relaunch, options: parsed.options, guard })
|
|
542
|
+
if (result.stopped === 'dry-run') {
|
|
543
|
+
console.log(`[restart-watchdog] dry-run: host ${result.deadPid} dead with approval ${result.manifestId}; not relaunching (pass --execute to allow)`)
|
|
544
|
+
} else if (result.stopped === 'no-approved-restart') {
|
|
545
|
+
console.log(`[restart-watchdog] host ${result.deadPid} dead without an approved restart (${result.reason}); not intervening`)
|
|
546
|
+
} else if (result.stopped === 'boot-guard-blocked') {
|
|
547
|
+
console.error(`[restart-watchdog] boot-guard blocked relaunch: ${result.reason ?? ''}`)
|
|
548
|
+
} else if (result.stopped === 'relaunch-spawn-failed' || result.stopped === 'receipt-write-failed') {
|
|
549
|
+
console.error(`[restart-watchdog] stopped: ${result.stopped}: ${result.reason ?? ''}`)
|
|
550
|
+
} else {
|
|
551
|
+
console.log(`[restart-watchdog] stopped=${result.stopped} relaunches=${result.relaunches}`)
|
|
552
|
+
}
|
|
553
|
+
return ['relaunch-spawn-failed', 'receipt-write-failed', 'boot-guard-blocked'].includes(result.stopped) ? 1 : 0
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
const isMain = (() => {
|
|
557
|
+
try {
|
|
558
|
+
return Boolean(process.argv[1]) && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url))
|
|
559
|
+
} catch {
|
|
560
|
+
return false
|
|
561
|
+
}
|
|
562
|
+
})()
|
|
563
|
+
if (isMain) {
|
|
564
|
+
main().then((code) => { process.exitCode = code }).catch((error) => {
|
|
565
|
+
console.error(`[restart-watchdog] ${error?.message ?? error}`)
|
|
566
|
+
process.exitCode = 1
|
|
567
|
+
})
|
|
568
|
+
}
|
package/vault/client.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Independent Vault client half: inject 导出/导入 into every fork tab bar.
|
|
3
|
+
// It uses the main panel's authenticated bridge; no token handling here.
|
|
4
|
+
window.__ModuleLoader__.load({
|
|
5
|
+
id: '@twinsearth/dsh-fang-vault',
|
|
6
|
+
factory() {
|
|
7
|
+
const BUTTONS = [
|
|
8
|
+
{ key: 'vault-export', label: '导出', title: '导出该分身为 Vault 文件夹(可选工作区快照)', action: 'exportTask' },
|
|
9
|
+
{ key: 'vault-import', label: '导入', title: '从 Vault 文件夹导入为新分身,并重新移植依赖', action: 'importTask' },
|
|
10
|
+
]
|
|
11
|
+
function buttonFor(card, spec) {
|
|
12
|
+
const button = document.createElement('button')
|
|
13
|
+
button.type = 'button'
|
|
14
|
+
button.dataset.vault = spec.key
|
|
15
|
+
button.className = 'btn btn--sm btn--ghost'
|
|
16
|
+
button.textContent = spec.label
|
|
17
|
+
button.title = spec.title
|
|
18
|
+
button.style.marginInlineStart = '4px'
|
|
19
|
+
button.addEventListener('click', (event) => {
|
|
20
|
+
event.preventDefault()
|
|
21
|
+
event.stopPropagation()
|
|
22
|
+
const bridge = window.__fangVaultBridge
|
|
23
|
+
if (!bridge || typeof bridge[spec.action] !== 'function') {
|
|
24
|
+
window.alert?.('瓮城 Vault 桥接不可用:请刷新母体页面')
|
|
25
|
+
return
|
|
26
|
+
}
|
|
27
|
+
if (spec.action === 'exportTask') void bridge.exportTask({ taskId: card.dataset.task })
|
|
28
|
+
else void bridge.importTask()
|
|
29
|
+
})
|
|
30
|
+
return button
|
|
31
|
+
}
|
|
32
|
+
function inject() {
|
|
33
|
+
for (const card of document.querySelectorAll('[data-task]')) {
|
|
34
|
+
const actions = card.querySelector('.fork-actions')
|
|
35
|
+
if (!actions) continue
|
|
36
|
+
// 母体自带按钮已存在时不再重复注入;独立子插件只做兼容补位。
|
|
37
|
+
if (actions.querySelector('[data-btn-id="C-08"]')) continue
|
|
38
|
+
for (const spec of BUTTONS) {
|
|
39
|
+
if (actions.querySelector(`[data-vault="${spec.key}"]`)) continue
|
|
40
|
+
actions.appendChild(buttonFor(card, spec))
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const observer = new MutationObserver(() => inject())
|
|
45
|
+
observer.observe(document.documentElement, { childList: true, subtree: true })
|
|
46
|
+
inject()
|
|
47
|
+
return { inject }
|
|
48
|
+
},
|
|
49
|
+
})
|