@twinsearth/dsh-fang 3.7.7 → 3.8.1
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 +50 -2
- package/package.json +2 -2
- package/src/kernel/types.mjs +1 -1
- package/src/lib/browser-guard.mjs +238 -0
- package/src/lib/memory-guard.mjs +161 -0
- package/src/lib/watchdog-sidecar.mjs +42 -0
- package/src/plugins/orchestrator.mjs +562 -8
package/client.js
CHANGED
|
@@ -1623,6 +1623,7 @@ html[data-fang-overlays="hidden"] .fang-console .toast{display:none!important}
|
|
|
1623
1623
|
role: { value: 'unknown', error: '', at: 0 },
|
|
1624
1624
|
status: { state: 'loading', data: null, error: '', diagnostic: null, at: 0 },
|
|
1625
1625
|
tasks: { state: 'loading', items: [], error: '', diagnostic: null, at: 0 },
|
|
1626
|
+
safeMode: { state: 'loading', data: null, error: '', at: 0 },
|
|
1626
1627
|
sessions: { state: 'loading', items: [], total: 0, degraded: [], error: '', diagnostic: null, at: 0 },
|
|
1627
1628
|
forkSessions: new Map(),
|
|
1628
1629
|
query: '',
|
|
@@ -1820,7 +1821,7 @@ html[data-fang-overlays="hidden"] .fang-console .toast{display:none!important}
|
|
|
1820
1821
|
const seq = ++refreshSeq
|
|
1821
1822
|
if (options.manual) { S.refreshing = true; schedule() }
|
|
1822
1823
|
try {
|
|
1823
|
-
const [statusRes, tasksRes, sessionsRes, essenceRes, approvalsRes, supervisionRes, forkCoreRes] = await Promise.all([
|
|
1824
|
+
const [statusRes, tasksRes, sessionsRes, essenceRes, approvalsRes, supervisionRes, forkCoreRes, safeModeRes] = await Promise.all([
|
|
1824
1825
|
api('/fang/api/status').catch((error) => ({ status: 0, body: null, diagnostic: { message: String(error?.message ?? error) } })),
|
|
1825
1826
|
api('/fang/api/tasks').catch((error) => ({ status: 0, body: null, diagnostic: { message: String(error?.message ?? error) } })),
|
|
1826
1827
|
api(`/fang/api/sessions?limit=${S.sessionWindow === 'all' ? 1000 : S.sessionWindow}`).catch((error) => ({ status: 0, body: null, diagnostic: { message: String(error?.message ?? error) } })),
|
|
@@ -1828,6 +1829,7 @@ html[data-fang-overlays="hidden"] .fang-console .toast{display:none!important}
|
|
|
1828
1829
|
api('/fang/api/approvals').catch((error) => ({ status: 0, body: null, diagnostic: { message: String(error?.message ?? error) } })),
|
|
1829
1830
|
api('/fang/api/forks/supervision').catch((error) => ({ status: 0, body: null, diagnostic: { message: String(error?.message ?? error) } })),
|
|
1830
1831
|
api('/fang/api/fork-core').catch((error) => ({ status: 0, body: null, diagnostic: { message: String(error?.message ?? error) } })),
|
|
1832
|
+
api('/fang/api/safe-mode').catch((error) => ({ status: 0, body: null, diagnostic: { message: String(error?.message ?? error) } })),
|
|
1831
1833
|
])
|
|
1832
1834
|
if (!alive || seq !== refreshSeq) return
|
|
1833
1835
|
if (supervisionRes.status === 200 && supervisionRes.body?.ok) {
|
|
@@ -1878,6 +1880,8 @@ html[data-fang-overlays="hidden"] .fang-console .toast{display:none!important}
|
|
|
1878
1880
|
S.tasks = { ...S.tasks, state: 'error', error: code, diagnostic: tasksRes.diagnostic || null }
|
|
1879
1881
|
}
|
|
1880
1882
|
|
|
1883
|
+
if (safeModeRes.status === 200 && safeModeRes.body) S.safeMode = { state: 'ready', data: safeModeRes.body, error: '', at: Date.now() }
|
|
1884
|
+
else S.safeMode = { state: 'error', data: null, error: safeModeRes.body?.error || (safeModeRes.status ? 'http-' + safeModeRes.status : 'network'), at: Date.now() }
|
|
1881
1885
|
if (forkCoreRes.status === 200 && forkCoreRes.body && forkCoreRes.body.ok !== false) {
|
|
1882
1886
|
S.forkCore = { state: 'ready', data: forkCoreRes.body, error: '', at: Date.now() }
|
|
1883
1887
|
} else {
|
|
@@ -2941,9 +2945,29 @@ html[data-fang-overlays="hidden"] .fang-console .toast{display:none!important}
|
|
|
2941
2945
|
// v3.7.4:打开是显式用户动作,用 POST 触发同步;GET 只读,避免副作用。
|
|
2942
2946
|
const result = await api('/fang/api/tasks/open', { method: 'POST', body: JSON.stringify({ taskId }) })
|
|
2943
2947
|
if (result.status === 200 && result.body?.url) {
|
|
2944
|
-
|
|
2948
|
+
const paused = Array.isArray(result.body?.paused) ? result.body.paused : []
|
|
2949
|
+
if (paused.length) notify('warn', `为释放内存,已暂停其他 ${paused.length} 个运行中的分身`, '母体只保留当前任务;其他分身可用“还原”重新启动。')
|
|
2950
|
+
if (result.body?.managed === true) {
|
|
2951
|
+
notify('ok', '已在受控浏览器中打开分身', `PID ${result.body.pid ?? '?'};内存/空闲/崩溃由瓮城看门狗接管。`)
|
|
2952
|
+
void refresh()
|
|
2953
|
+
return
|
|
2954
|
+
}
|
|
2955
|
+
try { window.open(result.body.url, '_blank', 'noopener'); void refresh(); return } catch { /* 弹层被拦 */ }
|
|
2945
2956
|
}
|
|
2946
2957
|
const code = result.body?.error || (result.status ? 'http-' + result.status : 'network')
|
|
2958
|
+
if (code === 'safe-mode') {
|
|
2959
|
+
notify('bad', '宿主处于 Safe Mode,已拒绝自动打开', result.body?.detail || '请先解除 Safe Mode 或重启宿主。')
|
|
2960
|
+
return
|
|
2961
|
+
}
|
|
2962
|
+
if (code === 'fork-quarantined') {
|
|
2963
|
+
notify('bad', '该分身已隔离,通信已断开', '只有重启该分身 Web 或重启 DSH 母体才能恢复。')
|
|
2964
|
+
return
|
|
2965
|
+
}
|
|
2966
|
+
if (code === 'memory-low') {
|
|
2967
|
+
const free = Number(result.body?.commitFreeMB)
|
|
2968
|
+
notify('bad', '系统提交内存不足,已拒绝打开分身', `CommitFree ${Number.isFinite(free) ? free : '?'} MB,低于阈值。请先启用页面文件或关闭其他分身/应用。`)
|
|
2969
|
+
return
|
|
2970
|
+
}
|
|
2947
2971
|
if (code === 'not-running') {
|
|
2948
2972
|
notify('warn', '分身已停止,正在启动…')
|
|
2949
2973
|
// 2026-11-22:服务端 restoreTask 直接接受 failed/archived 任务;不再“先归档再还原”。
|
|
@@ -3620,6 +3644,28 @@ html[data-fang-overlays="hidden"] .fang-console .toast{display:none!important}
|
|
|
3620
3644
|
h('span', { class: 'fh-sub' }, '母体 × 分身 · 三区控制台'))),
|
|
3621
3645
|
renderStats(S),
|
|
3622
3646
|
h('div', { class: 'fh-actions' },
|
|
3647
|
+
S.safeMode?.data?.safeMode
|
|
3648
|
+
? chip('warn', 'Safe Mode', { title: `宿主上次非正常退出或触发内存熔断:${S.safeMode.data.reason || 'guard'};已禁止自动恢复分身。`, state: 'safe-mode' })
|
|
3649
|
+
: null,
|
|
3650
|
+
S.safeMode?.data?.safeMode
|
|
3651
|
+
? button('解除 Safe Mode', {
|
|
3652
|
+
variant: 'danger-quiet', size: 'sm',
|
|
3653
|
+
title: '仅解除“禁止自动恢复”闩锁;不会自动启动任何分身。请确认内存和 pagefile 已修好。',
|
|
3654
|
+
onClick: async () => {
|
|
3655
|
+
const out = await api('/fang/api/safe-mode/reset', { method: 'POST', body: '{}' })
|
|
3656
|
+
if (out.status === 200) { notify('warn', 'Safe Mode 已解除', '不会自动恢复分身;请手动打开需要的任务。'); void refresh() }
|
|
3657
|
+
else notify('bad', '解除 Safe Mode 失败', out.body?.error || '')
|
|
3658
|
+
}, fk: 'safe-mode-reset',
|
|
3659
|
+
})
|
|
3660
|
+
: button('释放全部内存', {
|
|
3661
|
+
variant: 'danger-quiet', size: 'sm',
|
|
3662
|
+
title: '全局 Panic:关闭所有托管浏览器 → 停所有分身 → 清 PID/token → 全部隔离 → Safe Mode',
|
|
3663
|
+
onClick: async () => {
|
|
3664
|
+
const out = await api('/fang/api/panic', { method: 'POST', body: '{}' })
|
|
3665
|
+
if (out.status === 200) { notify('warn', '已触发全局 Panic', '浏览器与分身已关闭;当前处于 Safe Mode。'); void refresh() }
|
|
3666
|
+
else notify('bad', 'Panic 失败', out.body?.error || '')
|
|
3667
|
+
}, fk: 'host-panic',
|
|
3668
|
+
}),
|
|
3623
3669
|
restart?.available && restart.redLineAutoAllowed
|
|
3624
3670
|
? chip('warn', '红灯自动放行', {
|
|
3625
3671
|
title: 'strictRedLine=false:auto 授权模式下红灯可被策略自动放行。这只到决策层;execution.executed 恒为 false,真正重启仍由外部 supervisor 的 armed 清单决定。',
|
|
@@ -4525,6 +4571,8 @@ html[data-fang-overlays="hidden"] .fang-console .toast{display:none!important}
|
|
|
4525
4571
|
chip(health.tone, health.label, { state: health.phase, danger: health.tone === 'bad' && health.anomaly }),
|
|
4526
4572
|
archived ? null : chip(health.adapterTone, health.adapterLabel, { health: health.adapter }),
|
|
4527
4573
|
task.importedSession ? chip('info', '已导入会话', { title: '派生时导入了母体会话历史/摘要' }) : null,
|
|
4574
|
+
task.quarantined ? chip('bad', '已隔离', { title: `通信已断开(${task.quarantined.reason || 'guard'});只有重启该分身或 DSH 母体才能恢复` }) : null,
|
|
4575
|
+
task.memoryGuard ? chip('warn', '内存保护关闭', { title: `关闭原因:${task.memoryGuard.reason || 'guard'};PID ${task.memoryGuard.pid ?? '—'};会话 home 保留,可重新打开` }) : null,
|
|
4528
4576
|
task.sessions?.violation ? chip('warn', `会话 ${task.sessions.count}/${task.sessions.max} 超限`, { title: '分身会话超过上限;打开/修复不会再自动搬移,需手动归档或 enforce' }) : null,
|
|
4529
4577
|
task.essenceDeleted ? chip('warn', '原身已删除(仅运行/归档)', { title: '来源原身已删除:不能再从该原身派生,但本分身可继续运行/归档/还原/删除' }) : null)),
|
|
4530
4578
|
h('div', { class: 'fork-actions' },
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@twinsearth/dsh-fang",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.8.1",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "dsh-Fang (瓮城) — mother/fork plugin development environment for DeepSeek Harness: one readonly mother, a disposable child dsh-Web per task.",
|
|
@@ -58,7 +58,7 @@
|
|
|
58
58
|
},
|
|
59
59
|
"dependencies": {
|
|
60
60
|
"@twinsearth/dsh-fang-node-compat": "^0.1.0",
|
|
61
|
-
"@twinsearth/fang-dsh-plugin": "3.
|
|
61
|
+
"@twinsearth/fang-dsh-plugin": "3.8.1"
|
|
62
62
|
},
|
|
63
63
|
"repository": {
|
|
64
64
|
"type": "git",
|
package/src/kernel/types.mjs
CHANGED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Managed Chromium browser for fork Web pages.
|
|
3
|
+
// Why: the default browser is outside Fang's process tree, so it cannot be
|
|
4
|
+
// measured, force-closed, or crash-dumped. This module launches a dedicated
|
|
5
|
+
// profile and exposes CDP metrics for the memory guard.
|
|
6
|
+
import { spawn, execFile } from 'node:child_process'
|
|
7
|
+
import fs from 'node:fs'
|
|
8
|
+
import net from 'node:net'
|
|
9
|
+
import path from 'node:path'
|
|
10
|
+
|
|
11
|
+
const EDGE_CANDIDATES = [
|
|
12
|
+
'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe',
|
|
13
|
+
'C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe',
|
|
14
|
+
]
|
|
15
|
+
const CHROME_CANDIDATES = [
|
|
16
|
+
'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
|
|
17
|
+
'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
export async function lowerProcessPriority(pid) {
|
|
21
|
+
const value = Number(pid)
|
|
22
|
+
if (process.platform !== 'win32' || !Number.isInteger(value) || value <= 0) return { ok: false, error: 'unsupported' }
|
|
23
|
+
return new Promise((resolve) => {
|
|
24
|
+
try {
|
|
25
|
+
execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', `(Get-Process -Id ${value} -ErrorAction Stop).PriorityClass = 'BelowNormal'`], { windowsHide: true, timeout: 5000 }, (error) => {
|
|
26
|
+
resolve(error ? { ok: false, error: String(error.message ?? error) } : { ok: true })
|
|
27
|
+
})
|
|
28
|
+
} catch (error) { resolve({ ok: false, error: String(error?.message ?? error) }) }
|
|
29
|
+
})
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function findBrowserPath(configured = '') {
|
|
33
|
+
const explicit = String(configured || '').trim()
|
|
34
|
+
if (explicit && fs.existsSync(explicit)) return explicit
|
|
35
|
+
for (const candidate of [...EDGE_CANDIDATES, ...CHROME_CANDIDATES]) if (fs.existsSync(candidate)) return candidate
|
|
36
|
+
return ''
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function isPidAlive(pid) {
|
|
40
|
+
const value = Number(pid)
|
|
41
|
+
if (!Number.isInteger(value) || value <= 0) return false
|
|
42
|
+
try { process.kill(value, 0); return true } catch { return false }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function freePort(start = 19300, end = 19400) {
|
|
46
|
+
for (let port = start; port <= end; port += 1) {
|
|
47
|
+
const ok = await new Promise((resolve) => {
|
|
48
|
+
const server = net.createServer()
|
|
49
|
+
server.once('error', () => resolve(false))
|
|
50
|
+
server.once('listening', () => server.close(() => resolve(true)))
|
|
51
|
+
server.listen(port, '127.0.0.1')
|
|
52
|
+
})
|
|
53
|
+
if (ok) return port
|
|
54
|
+
}
|
|
55
|
+
return 0
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)) }
|
|
59
|
+
|
|
60
|
+
/** Launch an isolated app window and wait for its CDP endpoint. */
|
|
61
|
+
export async function launchManagedBrowser({ exe, url, profileDir, logDir, port, extraArgs = [] }) {
|
|
62
|
+
if (!exe || !fs.existsSync(exe)) return { ok: false, error: 'browser-unavailable' }
|
|
63
|
+
fs.mkdirSync(profileDir, { recursive: true })
|
|
64
|
+
fs.mkdirSync(logDir, { recursive: true })
|
|
65
|
+
const logFile = path.join(logDir, `browser-${Date.now()}.log`)
|
|
66
|
+
const crashDir = path.join(logDir, 'crash-dumps')
|
|
67
|
+
fs.mkdirSync(crashDir, { recursive: true })
|
|
68
|
+
const args = [
|
|
69
|
+
`--app=${url}`,
|
|
70
|
+
`--user-data-dir=${profileDir}`,
|
|
71
|
+
`--remote-debugging-port=${port}`,
|
|
72
|
+
'--remote-debugging-address=127.0.0.1',
|
|
73
|
+
'--no-first-run',
|
|
74
|
+
'--no-default-browser-check',
|
|
75
|
+
'--disable-sync',
|
|
76
|
+
'--disable-background-networking',
|
|
77
|
+
'--disable-features=msEdgeSyncConfirmation,msEdgeIdentity',
|
|
78
|
+
'--renderer-process-limit=1',
|
|
79
|
+
'--enable-logging',
|
|
80
|
+
`--log-file=${logFile}`,
|
|
81
|
+
'--enable-crash-reporter',
|
|
82
|
+
`--crash-dumps-dir=${crashDir}`,
|
|
83
|
+
'--js-flags=--max-old-space-size=2048',
|
|
84
|
+
...extraArgs,
|
|
85
|
+
]
|
|
86
|
+
let child
|
|
87
|
+
try {
|
|
88
|
+
child = spawn(exe, args, { detached: false, stdio: 'ignore', windowsHide: false })
|
|
89
|
+
} catch (error) {
|
|
90
|
+
return { ok: false, error: 'browser-spawn-failed', detail: String(error?.message ?? error) }
|
|
91
|
+
}
|
|
92
|
+
child.on('error', () => {})
|
|
93
|
+
child.unref?.()
|
|
94
|
+
const pid = Number(child.pid)
|
|
95
|
+
let ready = false
|
|
96
|
+
for (let i = 0; i < 40; i += 1) {
|
|
97
|
+
await sleep(250)
|
|
98
|
+
if (!isPidAlive(pid)) break
|
|
99
|
+
try {
|
|
100
|
+
const response = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1000) })
|
|
101
|
+
if (response.ok) { ready = true; break }
|
|
102
|
+
} catch { /* not ready */ }
|
|
103
|
+
}
|
|
104
|
+
if (!ready) {
|
|
105
|
+
try { await closeManagedBrowser({ pid, port }) } catch { /* ignore */ }
|
|
106
|
+
return { ok: false, error: 'browser-cdp-timeout', pid }
|
|
107
|
+
}
|
|
108
|
+
try { await lowerProcessPriority(pid) } catch { /* best effort */ }
|
|
109
|
+
return { ok: true, pid, port, profileDir, logFile, crashDir, exe }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export async function closeManagedBrowser({ pid, port, graceMs = 3000, timeoutMs = 3000 }) {
|
|
113
|
+
const value = Number(pid)
|
|
114
|
+
if (Number.isInteger(value) && value > 0) {
|
|
115
|
+
// 1) Ask the browser to close itself, giving the page a chance to flush.
|
|
116
|
+
let graceful = false
|
|
117
|
+
if (port) {
|
|
118
|
+
try { graceful = await browserCloseCdp(port) } catch { graceful = false }
|
|
119
|
+
for (let i = 0; i < Math.ceil(Math.max(0, graceMs) / 100); i += 1) {
|
|
120
|
+
if (!isPidAlive(value)) return { ok: true, graceful: true }
|
|
121
|
+
await sleep(100)
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
// 2) Force the whole tree only after the grace window.
|
|
125
|
+
if (process.platform === 'win32') {
|
|
126
|
+
try {
|
|
127
|
+
await new Promise((resolve) => {
|
|
128
|
+
const child = spawn('taskkill.exe', ['/PID', String(value), '/T', '/F'], { stdio: 'ignore', windowsHide: true })
|
|
129
|
+
child.once('exit', resolve)
|
|
130
|
+
child.once('error', resolve)
|
|
131
|
+
})
|
|
132
|
+
} catch { /* ignore */ }
|
|
133
|
+
} else {
|
|
134
|
+
try { process.kill(-value, 'SIGKILL') } catch { try { process.kill(value, 'SIGKILL') } catch { /* ignore */ } }
|
|
135
|
+
}
|
|
136
|
+
for (let i = 0; i < Math.ceil(timeoutMs / 100); i += 1) {
|
|
137
|
+
if (!isPidAlive(value)) break
|
|
138
|
+
await sleep(100)
|
|
139
|
+
}
|
|
140
|
+
return { ok: !isPidAlive(value), graceful: false }
|
|
141
|
+
}
|
|
142
|
+
return { ok: true, graceful: true }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async function cdpTargets(port) {
|
|
146
|
+
try {
|
|
147
|
+
const response = await fetch(`http://127.0.0.1:${port}/json`, { signal: AbortSignal.timeout(1500) })
|
|
148
|
+
if (!response.ok) return []
|
|
149
|
+
const list = await response.json()
|
|
150
|
+
return Array.isArray(list) ? list.filter((item) => item.type === 'page' && item.webSocketDebuggerUrl) : []
|
|
151
|
+
} catch { return [] }
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function cdpEvaluate(wsUrl, expression, timeoutMs = 2500) {
|
|
155
|
+
return cdpCommand(wsUrl, 'Runtime.evaluate', { expression, returnByValue: true, awaitPromise: false }, timeoutMs).then((result) => result?.result?.value ?? null)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function cdpCommand(wsUrl, method, params = {}, timeoutMs = 2500) {
|
|
159
|
+
return new Promise((resolve) => {
|
|
160
|
+
let ws
|
|
161
|
+
let timer
|
|
162
|
+
try {
|
|
163
|
+
ws = new WebSocket(wsUrl)
|
|
164
|
+
} catch {
|
|
165
|
+
resolve(null)
|
|
166
|
+
return
|
|
167
|
+
}
|
|
168
|
+
const done = (value) => {
|
|
169
|
+
try { clearTimeout(timer) } catch { /* ignore */ }
|
|
170
|
+
try { ws?.close() } catch { /* ignore */ }
|
|
171
|
+
resolve(value)
|
|
172
|
+
}
|
|
173
|
+
timer = setTimeout(() => done(null), timeoutMs)
|
|
174
|
+
ws.addEventListener('open', () => {
|
|
175
|
+
try { ws.send(JSON.stringify({ id: 1, method, params })) } catch { done(null) }
|
|
176
|
+
})
|
|
177
|
+
ws.addEventListener('message', (event) => {
|
|
178
|
+
try {
|
|
179
|
+
const message = JSON.parse(String(event.data))
|
|
180
|
+
if (message.id !== 1) return
|
|
181
|
+
done(message.result ?? null)
|
|
182
|
+
} catch { done(null) }
|
|
183
|
+
})
|
|
184
|
+
ws.addEventListener('error', () => done(null))
|
|
185
|
+
ws.addEventListener('close', () => done(null))
|
|
186
|
+
})
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async function browserCloseCdp(port) {
|
|
190
|
+
try {
|
|
191
|
+
const response = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1000) })
|
|
192
|
+
if (!response.ok) return false
|
|
193
|
+
const info = await response.json()
|
|
194
|
+
if (!info.webSocketDebuggerUrl) return false
|
|
195
|
+
await cdpCommand(info.webSocketDebuggerUrl, 'Browser.close', {}, 1500)
|
|
196
|
+
return true
|
|
197
|
+
} catch { return false }
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
/** Read DOM/heap/visibility from the managed page. */
|
|
202
|
+
/** Best-effort page flush before force-close; server-side session persistence is authoritative. */
|
|
203
|
+
export async function flushManagedBrowser(port) {
|
|
204
|
+
const targets = await cdpTargets(port)
|
|
205
|
+
if (!targets.length) return { ok: false, error: 'no-page' }
|
|
206
|
+
const target = targets[0]
|
|
207
|
+
await cdpEvaluate(target.webSocketDebuggerUrl, `(() => {
|
|
208
|
+
try { window.dispatchEvent(new Event('pagehide')); window.dispatchEvent(new Event('beforeunload')); } catch (e) {}
|
|
209
|
+
return true;
|
|
210
|
+
})()`, 1200)
|
|
211
|
+
return { ok: true }
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export async function sampleManagedBrowser(port) {
|
|
215
|
+
const targets = await cdpTargets(port)
|
|
216
|
+
if (!targets.length) return { ok: false, error: 'browser-cdp-no-page' }
|
|
217
|
+
const target = targets.find((item) => item.url?.startsWith('http://127.0.0.1:')) ?? targets[0]
|
|
218
|
+
const value = await cdpEvaluate(target.webSocketDebuggerUrl, `(() => {
|
|
219
|
+
return { visibility: document.visibilityState, url: location.href };
|
|
220
|
+
})()`)
|
|
221
|
+
if (!value || typeof value !== 'object') return { ok: false, error: 'browser-cdp-evaluate-failed' }
|
|
222
|
+
const perf = await cdpCommand(target.webSocketDebuggerUrl, 'Performance.getMetrics', {}, 2000)
|
|
223
|
+
const dom = await cdpCommand(target.webSocketDebuggerUrl, 'Memory.getDOMCounters', {}, 2000)
|
|
224
|
+
const heap = await cdpCommand(target.webSocketDebuggerUrl, 'Runtime.getHeapUsage', {}, 2000)
|
|
225
|
+
const metrics = Array.isArray(perf?.metrics)
|
|
226
|
+
? Object.fromEntries(perf.metrics.map((item) => [item.name, item.value]))
|
|
227
|
+
: {}
|
|
228
|
+
return {
|
|
229
|
+
ok: true,
|
|
230
|
+
visibility: value.visibility,
|
|
231
|
+
url: value.url,
|
|
232
|
+
heapBytes: Number(metrics.JSHeapUsedSize || heap?.usedSize || dom?.jsHeapUsedSize || 0),
|
|
233
|
+
nodes: Number(perf?.nodes ?? metrics.Nodes ?? dom?.nodes ?? 0),
|
|
234
|
+
documents: Number(metrics.Documents ?? dom?.documents ?? 0),
|
|
235
|
+
listeners: Number(dom?.jsEventListeners ?? 0),
|
|
236
|
+
layoutCount: Number(metrics.LayoutCount ?? 0),
|
|
237
|
+
}
|
|
238
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Windows commit-memory guard + process-tree sampling for dsh-Fang.
|
|
3
|
+
// No native addon: PowerShell/CIM is queried at most once per cache window.
|
|
4
|
+
import { execFile } from 'node:child_process'
|
|
5
|
+
import { promisify } from 'node:util'
|
|
6
|
+
import os from 'node:os'
|
|
7
|
+
|
|
8
|
+
const execFileAsync = promisify(execFile)
|
|
9
|
+
const DEFAULT_CACHE_MS = 5000
|
|
10
|
+
let cache = { at: 0, value: null, pending: null }
|
|
11
|
+
|
|
12
|
+
function parsePowerShellJson(text) {
|
|
13
|
+
const trimmed = String(text ?? '').trim()
|
|
14
|
+
if (!trimmed) return null
|
|
15
|
+
try { return JSON.parse(trimmed) } catch { /* fall through */ }
|
|
16
|
+
const start = trimmed.indexOf('{')
|
|
17
|
+
const end = trimmed.lastIndexOf('}')
|
|
18
|
+
if (start >= 0 && end > start) {
|
|
19
|
+
try { return JSON.parse(trimmed.slice(start, end + 1)) } catch { /* ignore */ }
|
|
20
|
+
}
|
|
21
|
+
return null
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Read Windows commit limit/free. Values are MB. Non-Windows returns a disabled shape. */
|
|
25
|
+
export async function readSystemMemory({ force = false, cacheMs = DEFAULT_CACHE_MS } = {}) {
|
|
26
|
+
if (process.platform !== 'win32') {
|
|
27
|
+
return { ok: true, supported: false, source: 'non-windows', commitLimitMB: null, commitFreeMB: null, physicalFreeMB: Math.round(os.freemem() / 1048576) }
|
|
28
|
+
}
|
|
29
|
+
const now = Date.now()
|
|
30
|
+
if (!force && cache.value && now - cache.at < cacheMs) return cache.value
|
|
31
|
+
if (!force && cache.pending) return cache.pending
|
|
32
|
+
const script = [
|
|
33
|
+
'$o = Get-CimInstance Win32_OperatingSystem',
|
|
34
|
+
'$p = [pscustomobject]@{',
|
|
35
|
+
' CommitLimitMB = [math]::Round($o.TotalVirtualMemorySize / 1024)',
|
|
36
|
+
' CommitFreeMB = [math]::Round($o.FreeVirtualMemory / 1024)',
|
|
37
|
+
' PhysicalTotalMB = [math]::Round($o.TotalVisibleMemorySize / 1024)',
|
|
38
|
+
' PhysicalFreeMB = [math]::Round($o.FreePhysicalMemory / 1024)',
|
|
39
|
+
' PageFileMB = [math]::Round((Get-CimInstance Win32_PageFileUsage -ErrorAction SilentlyContinue | Measure-Object AllocatedBaseSize -Sum).Sum)',
|
|
40
|
+
'}',
|
|
41
|
+
'$p | ConvertTo-Json -Compress',
|
|
42
|
+
].join('\n')
|
|
43
|
+
const run = (async () => {
|
|
44
|
+
try {
|
|
45
|
+
const { stdout } = await execFileAsync('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', script], {
|
|
46
|
+
timeout: 10000, windowsHide: true, maxBuffer: 65536,
|
|
47
|
+
})
|
|
48
|
+
const data = parsePowerShellJson(stdout)
|
|
49
|
+
if (!data) return { ok: false, supported: true, source: 'powershell', error: 'memory-parse-failed' }
|
|
50
|
+
const value = {
|
|
51
|
+
ok: true,
|
|
52
|
+
supported: true,
|
|
53
|
+
source: 'powershell',
|
|
54
|
+
commitLimitMB: Number(data.CommitLimitMB) || 0,
|
|
55
|
+
commitFreeMB: Number(data.CommitFreeMB) || 0,
|
|
56
|
+
physicalTotalMB: Number(data.PhysicalTotalMB) || 0,
|
|
57
|
+
physicalFreeMB: Number(data.PhysicalFreeMB) || 0,
|
|
58
|
+
pageFileMB: Number(data.PageFileMB) || 0,
|
|
59
|
+
hasPageFile: Number(data.PageFileMB) > 0,
|
|
60
|
+
at: now,
|
|
61
|
+
}
|
|
62
|
+
cache = { at: now, value, pending: null }
|
|
63
|
+
return value
|
|
64
|
+
} catch (error) {
|
|
65
|
+
const value = { ok: false, supported: true, source: 'powershell', error: String(error?.message ?? error) }
|
|
66
|
+
cache = { at: now, value, pending: null }
|
|
67
|
+
return value
|
|
68
|
+
}
|
|
69
|
+
})()
|
|
70
|
+
cache.pending = run
|
|
71
|
+
return run
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Pure guard decision, kept separate for tests. */
|
|
75
|
+
export function evaluateMemoryGuard(memory, { minFreeMB = 4096 } = {}) {
|
|
76
|
+
if (!memory?.ok) return { ok: true, skipped: 'memory-unavailable', memory }
|
|
77
|
+
if (memory.supported === false) return { ok: true, skipped: 'unsupported-platform', memory }
|
|
78
|
+
const free = Number(memory.commitFreeMB) || 0
|
|
79
|
+
const min = Math.max(0, Number(minFreeMB) || 0)
|
|
80
|
+
if (free < min) return { ok: false, error: 'memory-low', commitFreeMB: free, minFreeMB: min, memory }
|
|
81
|
+
return { ok: true, commitFreeMB: free, minFreeMB: min, memory }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Snapshot all Windows processes into rows; caller filters by PID tree. */
|
|
85
|
+
export async function readProcessTable() {
|
|
86
|
+
if (process.platform !== 'win32') return { ok: true, supported: false, rows: [] }
|
|
87
|
+
const script = [
|
|
88
|
+
'Get-CimInstance Win32_Process |',
|
|
89
|
+
' Select-Object ProcessId,ParentProcessId,Name,WorkingSetSize,PageFileUsage,CommandLine |',
|
|
90
|
+
' ConvertTo-Json -Compress',
|
|
91
|
+
].join('\n')
|
|
92
|
+
try {
|
|
93
|
+
const { stdout } = await execFileAsync('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', script], {
|
|
94
|
+
timeout: 12000, windowsHide: true, maxBuffer: 8 * 1024 * 1024,
|
|
95
|
+
})
|
|
96
|
+
let rows = parsePowerShellJson(stdout)
|
|
97
|
+
if (rows === null) return { ok: false, supported: true, error: 'process-table-parse-failed', rows: [] }
|
|
98
|
+
if (!Array.isArray(rows)) rows = [rows]
|
|
99
|
+
return { ok: true, supported: true, rows: rows.map((row) => ({
|
|
100
|
+
pid: Number(row.ProcessId),
|
|
101
|
+
ppid: Number(row.ParentProcessId),
|
|
102
|
+
name: String(row.Name ?? ''),
|
|
103
|
+
workingSetMB: Math.round((Number(row.WorkingSetSize) || 0) / 1048576),
|
|
104
|
+
commitMB: Math.round((Number(row.PageFileUsage) || 0) / 1048576),
|
|
105
|
+
commandLine: String(row.CommandLine ?? ''),
|
|
106
|
+
})) }
|
|
107
|
+
} catch (error) {
|
|
108
|
+
return { ok: false, supported: true, error: String(error?.message ?? error), rows: [] }
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Select a root PID and all descendants from a process table. */
|
|
113
|
+
export function selectProcessTree(rows, rootPid) {
|
|
114
|
+
const root = Number(rootPid)
|
|
115
|
+
if (!Number.isInteger(root) || root <= 0) return []
|
|
116
|
+
const byParent = new Map()
|
|
117
|
+
for (const row of Array.isArray(rows) ? rows : []) {
|
|
118
|
+
if (!byParent.has(row.ppid)) byParent.set(row.ppid, [])
|
|
119
|
+
byParent.get(row.ppid).push(row)
|
|
120
|
+
}
|
|
121
|
+
const out = []
|
|
122
|
+
const stack = [root]
|
|
123
|
+
const seen = new Set()
|
|
124
|
+
while (stack.length) {
|
|
125
|
+
const pid = stack.pop()
|
|
126
|
+
if (seen.has(pid)) continue
|
|
127
|
+
seen.add(pid)
|
|
128
|
+
const row = rows.find((item) => item.pid === pid)
|
|
129
|
+
if (row) out.push(row)
|
|
130
|
+
for (const child of byParent.get(pid) ?? []) stack.push(child.pid)
|
|
131
|
+
}
|
|
132
|
+
return out
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function sumProcessTree(tree) {
|
|
136
|
+
return {
|
|
137
|
+
pids: tree.map((row) => row.pid),
|
|
138
|
+
count: tree.length,
|
|
139
|
+
workingSetMB: tree.reduce((n, row) => n + row.workingSetMB, 0),
|
|
140
|
+
commitMB: tree.reduce((n, row) => n + row.commitMB, 0),
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Kill one process tree. Only intended for PIDs recorded by the task registry. */
|
|
145
|
+
export async function killProcessTree(rootPid) {
|
|
146
|
+
const pid = Number(rootPid)
|
|
147
|
+
if (!Number.isInteger(pid) || pid <= 0) return { ok: false, error: 'invalid-pid' }
|
|
148
|
+
if (process.platform !== 'win32') {
|
|
149
|
+
try { process.kill(pid, 'SIGKILL'); return { ok: true } } catch (error) { return { ok: false, error: String(error?.message ?? error) } }
|
|
150
|
+
}
|
|
151
|
+
try {
|
|
152
|
+
await execFileAsync('taskkill.exe', ['/PID', String(pid), '/T', '/F'], { timeout: 10000, windowsHide: true, maxBuffer: 65536 })
|
|
153
|
+
return { ok: true }
|
|
154
|
+
} catch (error) {
|
|
155
|
+
return { ok: false, error: String(error?.message ?? error) }
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function memoryGuardDefaults() {
|
|
160
|
+
return { enabled: true, minFreeMB: 4096, watchdogEnabled: true, watchIntervalMs: 30000, killCommitMB: 2048, growCommitMB: 768, singleActiveFork: true }
|
|
161
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Independent watchdog. Runs outside the DSH host so it can still clean up
|
|
3
|
+
// managed browsers / fork trees if the host dies or is force-killed.
|
|
4
|
+
// It only acts on PIDs written by the host into watchdog.json.
|
|
5
|
+
import fs from 'node:fs'
|
|
6
|
+
import { spawnSync } from 'node:child_process'
|
|
7
|
+
|
|
8
|
+
const file = String(process.argv[2] ?? '')
|
|
9
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
10
|
+
|
|
11
|
+
function alive(pid) {
|
|
12
|
+
const value = Number(pid)
|
|
13
|
+
if (!Number.isInteger(value) || value <= 0) return false
|
|
14
|
+
try { process.kill(value, 0); return true } catch { return false }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function killTree(pid) {
|
|
18
|
+
const value = Number(pid)
|
|
19
|
+
if (!Number.isInteger(value) || value <= 0) return
|
|
20
|
+
try {
|
|
21
|
+
spawnSync('taskkill.exe', ['/PID', String(value), '/T', '/F'], { windowsHide: true, stdio: 'ignore', timeout: 10000 })
|
|
22
|
+
} catch { /* best effort */ }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function main() {
|
|
26
|
+
if (!file) process.exit(0)
|
|
27
|
+
for (;;) {
|
|
28
|
+
let data = null
|
|
29
|
+
try { data = JSON.parse(fs.readFileSync(file, 'utf8')) } catch { /* host may be writing */ }
|
|
30
|
+
if (!data) { await sleep(2000); continue }
|
|
31
|
+
const hostPid = Number(data.hostPid)
|
|
32
|
+
const targets = Array.isArray(data.targets) ? data.targets : []
|
|
33
|
+
if (data.stop === true || data.clean === true || !alive(hostPid)) {
|
|
34
|
+
for (const target of targets) killTree(target.pid)
|
|
35
|
+
try { fs.writeFileSync(file, JSON.stringify({ ...data, stoppedAt: new Date().toISOString(), stop: true }, null, 2)) } catch { /* ignore */ }
|
|
36
|
+
process.exit(0)
|
|
37
|
+
}
|
|
38
|
+
await sleep(2000)
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
main().catch(() => process.exit(0))
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
import fs from 'node:fs'
|
|
12
12
|
import path from 'node:path'
|
|
13
13
|
import crypto from 'node:crypto'
|
|
14
|
+
import { spawn } from 'node:child_process'
|
|
14
15
|
|
|
15
16
|
import {
|
|
16
17
|
z, roleGate, resolveFangLayout, resolveProfileDir, resolveSessionsLayout,
|
|
@@ -26,6 +27,8 @@ import { installWatchGuard } from '../lib/watch-guard.mjs'
|
|
|
26
27
|
import { ensureInstallSnapshot } from '../lib/install-snapshot.mjs'
|
|
27
28
|
import { exportVault, importVault, readVault } from '../../vault/lib/vault.mjs'
|
|
28
29
|
import { installGlobalRedline } from '../lib/global-redline.mjs'
|
|
30
|
+
import { evaluateMemoryGuard, killProcessTree, memoryGuardDefaults, readProcessTable, readSystemMemory, selectProcessTree, sumProcessTree } from '../lib/memory-guard.mjs'
|
|
31
|
+
import { closeManagedBrowser, findBrowserPath, flushManagedBrowser, freePort, isPidAlive, launchManagedBrowser, lowerProcessPriority, sampleManagedBrowser } from '../lib/browser-guard.mjs'
|
|
29
32
|
import { normalizeFetchDescriptor } from '../lib/node-compat.mjs'
|
|
30
33
|
import { cleanupApprovalDrill, runApprovalDrill } from '../lib/approval-drill.mjs'
|
|
31
34
|
import { negotiateProtocol } from '../lib/adapter-protocol.mjs'
|
|
@@ -189,7 +192,57 @@ export const Config = z.object({
|
|
|
189
192
|
officialSourceToken: z.string().default('')
|
|
190
193
|
.description('官方源 Bearer token(可选;不会写进日志/状态)'),
|
|
191
194
|
maxForks: z.number().min(1).max(64).default(8)
|
|
192
|
-
.description('
|
|
195
|
+
.description('同时存活的任务/分身上限;运行并发由 singleActiveFork 硬限制为 1'),
|
|
196
|
+
memoryGuard: z.boolean().default(true)
|
|
197
|
+
.description('创建/打开/还原分身前检查 Windows CommitFree 余量'),
|
|
198
|
+
memoryMinFreeMB: z.number().min(0).max(1048576).default(6144)
|
|
199
|
+
.description('CommitFree 低于该值(MB)时拒绝启动新分身'),
|
|
200
|
+
hostWarnFreeMB: z.number().min(0).max(1048576).default(8192)
|
|
201
|
+
.description('宿主内存警告阈值(MB,仅提示)'),
|
|
202
|
+
hostCriticalFreeMB: z.number().min(0).max(1048576).default(4096)
|
|
203
|
+
.description('宿主紧急阈值(MB):先杀托管浏览器,再停所有分身'),
|
|
204
|
+
hostEmergencyFreeMB: z.number().min(0).max(1048576).default(2048)
|
|
205
|
+
.description('宿主最低保留(MB);低于此值进入 Safe Mode 并隔离'),
|
|
206
|
+
memoryWatchdog: z.boolean().default(true)
|
|
207
|
+
.description('定时采样每个分身的 PID 树/Commit,异常增长时只杀该分身'),
|
|
208
|
+
memoryWatchIntervalMs: z.number().min(5000).max(600000).default(15000)
|
|
209
|
+
.description('内存看门狗采样间隔(毫秒)'),
|
|
210
|
+
memoryKillCommitMB: z.number().min(128).max(1048576).default(2048)
|
|
211
|
+
.description('单个分身 PID 树 commit 超过该值(MB)时进入杀进程候选'),
|
|
212
|
+
memoryGrowCommitMB: z.number().min(64).max(1048576).default(768)
|
|
213
|
+
.description('相对该分身低点增长超过该值(MB)才杀,避免误杀启动峰值'),
|
|
214
|
+
singleActiveFork: z.boolean().default(true)
|
|
215
|
+
.description('启动新分身时暂停其他运行中的分身,避免同时打开多个 Electron renderer'),
|
|
216
|
+
managedBrowser: z.boolean().default(true)
|
|
217
|
+
.description('由 Fang 启动独立 Chromium 窗口并纳入 PID/CDP 监控'),
|
|
218
|
+
browserPath: z.string().default('')
|
|
219
|
+
.description('托管浏览器 exe;留空自动找 Edge/Chrome'),
|
|
220
|
+
maxOpenForkBrowsers: z.number().min(1).max(16).default(1)
|
|
221
|
+
.description('同时存活的托管浏览器窗口上限'),
|
|
222
|
+
browserMemoryLimitMB: z.number().min(256).max(1048576).default(2048)
|
|
223
|
+
.description('单个托管浏览器 PID 树 Commit 上限(MB),超过即关闭'),
|
|
224
|
+
browserHeapLimitMB: z.number().min(128).max(1048576).default(1536)
|
|
225
|
+
.description('托管浏览器 JS heap 上限(MB),超过即关闭'),
|
|
226
|
+
gracefulBrowserCloseMs: z.number().min(0).max(30000).default(3000)
|
|
227
|
+
.description('CDP Browser.close 后等待优雅退出的时间;超时才 taskkill'),
|
|
228
|
+
idleCloseOnlyWhenIdle: z.boolean().default(true)
|
|
229
|
+
.description('只关闭确认空闲的 fork 页面;无法确认活跃状态时不自动关'),
|
|
230
|
+
orphanSweepMinutes: z.number().min(0).max(1440).default(5)
|
|
231
|
+
.description('孤儿 fork 进程清理间隔(分钟;0=仅启动时)'),
|
|
232
|
+
forkFlushPath: z.string().default('')
|
|
233
|
+
.description('关闭浏览器前调用的 fork 落盘路径(如 /api/session/flush;留空=显式 unsupported)'),
|
|
234
|
+
forkCommitShareLimit: z.number().min(0.05).max(1).default(0.4)
|
|
235
|
+
.description('fork+browser PID 树 commit 总和占系统 CommitLimit 的上限'),
|
|
236
|
+
browserDomNodeLimit: z.number().min(1000).max(10000000).default(200000)
|
|
237
|
+
.description('托管浏览器 DOM 节点上限,超过即关闭'),
|
|
238
|
+
autoCloseIdleMinutes: z.number().min(0).max(1440).default(10)
|
|
239
|
+
.description('浏览器页面隐藏超过该分钟数自动关闭(0=不关)'),
|
|
240
|
+
quarantineOnGuard: z.boolean().default(true)
|
|
241
|
+
.description('内存护栏触发后隔离任务,禁止自动重连'),
|
|
242
|
+
safeModeAfterCrash: z.boolean().default(true)
|
|
243
|
+
.description('上次宿主非正常退出时启动 Safe Mode,禁止自动恢复分身'),
|
|
244
|
+
autoRestoreForks: z.boolean().default(false)
|
|
245
|
+
.description('宿主启动时自动恢复上次运行的分身(默认关闭)'),
|
|
193
246
|
motherProfile: z.string().default('')
|
|
194
247
|
.description('母体 profile 名;留空 = 当前 profile(分身模板来源)'),
|
|
195
248
|
profileTemplate: z.string().default('')
|
|
@@ -484,6 +537,108 @@ export function apply(ctx, config) {
|
|
|
484
537
|
}
|
|
485
538
|
}
|
|
486
539
|
|
|
540
|
+
// v3.8.0: host crash latch. A previous host that did not write cleanShutdown
|
|
541
|
+
// means the last run died; enter Safe Mode unless explicitly disabled.
|
|
542
|
+
const safeModeFile = path.join(layout.dataDir, 'safe-mode.json')
|
|
543
|
+
const hostStateFile = path.join(layout.dataDir, 'host-state.json')
|
|
544
|
+
const hostCrashFile = path.join(layout.dataDir, 'host-crashes.json')
|
|
545
|
+
const readJsonFile = (file) => { try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return null } }
|
|
546
|
+
const previousHost = readJsonFile(hostStateFile)
|
|
547
|
+
const previousSafeMode = readJsonFile(safeModeFile)
|
|
548
|
+
const unclean = Boolean(previousHost && previousHost.clean !== true && Number(previousHost.pid) !== process.pid)
|
|
549
|
+
let safeMode = Boolean(previousSafeMode?.safeMode)
|
|
550
|
+
let safeModeReason = String(previousSafeMode?.reason ?? '')
|
|
551
|
+
if (unclean) {
|
|
552
|
+
const now = nowMs()
|
|
553
|
+
const prior = readJsonFile(hostCrashFile)?.crashes
|
|
554
|
+
const recent = (Array.isArray(prior) ? prior : []).filter((item) => now - Number(item.at) <= 10 * 60_000)
|
|
555
|
+
recent.push({ at: now, previousPid: previousHost?.pid ?? null, reason: 'unclean-shutdown' })
|
|
556
|
+
try { fs.writeFileSync(hostCrashFile, JSON.stringify({ crashes: recent }, null, 2)) } catch { /* best effort */ }
|
|
557
|
+
// Red line: one crash is context; two crashes within 10 minutes means a loop.
|
|
558
|
+
if (cfg.safeModeAfterCrash === true && !safeMode && recent.length >= 2) {
|
|
559
|
+
safeMode = true
|
|
560
|
+
safeModeReason = 'crash-loop-10m'
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
// A fresh host process is an explicit recovery boundary: clear per-task
|
|
564
|
+
// quarantine latches, but keep tokens revoked so the old page cannot reconnect.
|
|
565
|
+
let quarantineReset = 0
|
|
566
|
+
if (previousHost?.pid !== process.pid) {
|
|
567
|
+
for (const task of tasks.values()) {
|
|
568
|
+
if (!task.quarantined) continue
|
|
569
|
+
task.quarantineCleared = { at: nowMs(), reason: 'host-restart' }
|
|
570
|
+
task.quarantined = null
|
|
571
|
+
task.token = ''
|
|
572
|
+
task.url = ''
|
|
573
|
+
task.status = TASK_STATUS.FAILED
|
|
574
|
+
task.pid = null
|
|
575
|
+
task.port = null
|
|
576
|
+
quarantineReset += 1
|
|
577
|
+
}
|
|
578
|
+
if (quarantineReset) {
|
|
579
|
+
try { saveRegistry(layout.tasksFile, [...tasks.values()].map(task => ({ ...task, token: '', url: stripUrlToken(task.url) }))) } catch { /* best effort */ }
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
const persistSafeMode = () => {
|
|
583
|
+
try { fs.writeFileSync(safeModeFile, JSON.stringify({ safeMode, reason: safeModeReason, at: new Date().toISOString() }, null, 2)) } catch { /* best effort */ }
|
|
584
|
+
}
|
|
585
|
+
persistSafeMode()
|
|
586
|
+
try { fs.writeFileSync(hostStateFile, JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString(), clean: false }, null, 2)) } catch { /* best effort */ }
|
|
587
|
+
try {
|
|
588
|
+
ctx.effect(() => () => {
|
|
589
|
+
try { fs.writeFileSync(hostStateFile, JSON.stringify({ pid: process.pid, exitedAt: new Date().toISOString(), clean: true }, null, 2)) } catch { /* best effort */ }
|
|
590
|
+
try {
|
|
591
|
+
const prior = JSON.parse(fs.readFileSync(watchdogFile, 'utf8'))
|
|
592
|
+
fs.writeFileSync(watchdogFile, JSON.stringify({ ...prior, hostPid: process.pid, clean: true, at: new Date().toISOString() }, null, 2))
|
|
593
|
+
} catch { /* best effort */ }
|
|
594
|
+
})
|
|
595
|
+
} catch { /* fake ctx */ }
|
|
596
|
+
|
|
597
|
+
// v3.8.0 independent watchdog: a detached Node/Electron process cleans up
|
|
598
|
+
// managed browsers/fork trees if this host is force-killed. It never reads
|
|
599
|
+
// user data and acts only on PIDs written here.
|
|
600
|
+
const watchdogFile = path.join(layout.dataDir, `watchdog-${process.pid}.json`)
|
|
601
|
+
const writeWatchdog = () => {
|
|
602
|
+
const targets = []
|
|
603
|
+
for (const task of tasks.values()) {
|
|
604
|
+
if (task.browser?.pid) targets.push({ pid: Number(task.browser.pid), kind: 'browser', taskId: task.taskId })
|
|
605
|
+
if (task.pid && (task.status === TASK_STATUS.READY || task.status === TASK_STATUS.RUNNING)) targets.push({ pid: Number(task.pid), kind: 'fork', taskId: task.taskId })
|
|
606
|
+
}
|
|
607
|
+
try { fs.writeFileSync(watchdogFile, JSON.stringify({ hostPid: process.pid, clean: false, at: new Date().toISOString(), targets }, null, 2)) } catch { /* best effort */ }
|
|
608
|
+
}
|
|
609
|
+
writeWatchdog()
|
|
610
|
+
const testLike = Boolean(process.env.NODE_TEST_CONTEXT) || process.env.DSH_FANG_E2E === '1' || /(?:test|e2e)/i.test(String(process.argv[1] ?? ''))
|
|
611
|
+
const sidecarAlready = globalThis.__fangWatchdogSidecar === true
|
|
612
|
+
if (process.platform === 'win32' && process.env.DSH_FANG_DISABLE_SIDECAR !== '1' && !testLike && !sidecarAlready) {
|
|
613
|
+
globalThis.__fangWatchdogSidecar = true
|
|
614
|
+
try {
|
|
615
|
+
// IMPORTANT: never spawn process.execPath here. In a packaged DSH host that
|
|
616
|
+
// is DeepSeek Harness.exe, and ELECTRON_RUN_AS_NODE may be fused off; it
|
|
617
|
+
// would boot a second host, corrupt the profile, and trigger the exact
|
|
618
|
+
// "Failed to load plugins" / handler-threw failure seen in v3.8.0.
|
|
619
|
+
const nodeCandidates = [
|
|
620
|
+
process.env.DSH_FANG_NODE_EXE,
|
|
621
|
+
path.join(path.dirname(process.execPath), 'resources', 'runtime', 'primary-runtime', 'dependencies', 'node', 'bin', 'node.exe'),
|
|
622
|
+
'D:\\DSH\\resources\\runtime\\primary-runtime\\dependencies\\node\\bin\\node.exe',
|
|
623
|
+
].filter(Boolean)
|
|
624
|
+
const nodeExe = nodeCandidates.find((candidate) => exists(candidate))
|
|
625
|
+
if (!nodeExe) {
|
|
626
|
+
audit('watchdog-sidecar-unavailable', { reason: 'bundled-node-not-found' })
|
|
627
|
+
} else {
|
|
628
|
+
const sidecar = fileURLToPath(new URL('../lib/watchdog-sidecar.mjs', import.meta.url))
|
|
629
|
+
const child = spawn(nodeExe, [sidecar, watchdogFile], {
|
|
630
|
+
detached: true,
|
|
631
|
+
stdio: 'ignore',
|
|
632
|
+
windowsHide: true,
|
|
633
|
+
env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
|
|
634
|
+
})
|
|
635
|
+
child.on('error', () => {})
|
|
636
|
+
child.unref()
|
|
637
|
+
}
|
|
638
|
+
} catch { /* sidecar is best effort; host watchdog remains */ }
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
|
|
487
642
|
const safeGet = (key) => { try { return ctx.get(key) } catch { return undefined } }
|
|
488
643
|
// v3.3.3: queue journal is an optional sub-plugin. Its host half provides
|
|
489
644
|
// SERVICE.queueJournal; without it the journal/queue routes must fail closed
|
|
@@ -588,6 +743,320 @@ export function apply(ctx, config) {
|
|
|
588
743
|
} catch { /* best effort */ }
|
|
589
744
|
}
|
|
590
745
|
const forker = () => safeGet(SERVICE.forker)
|
|
746
|
+
|
|
747
|
+
/** 2026-11-24: commit-memory guard before any new renderer/spawn. */
|
|
748
|
+
let pagefileWarned = false
|
|
749
|
+
const memoryGate = async (action) => {
|
|
750
|
+
if (cfg.memoryGuard !== true) return { ok: true, skipped: 'disabled' }
|
|
751
|
+
const memory = await readSystemMemory()
|
|
752
|
+
if (memory.ok === true && memory.hasPageFile === false && !pagefileWarned) {
|
|
753
|
+
pagefileWarned = true
|
|
754
|
+
audit('pagefile-missing', { action, commitLimitMB: memory.commitLimitMB, commitFreeMB: memory.commitFreeMB })
|
|
755
|
+
}
|
|
756
|
+
const decision = evaluateMemoryGuard(memory, { minFreeMB: cfg.memoryMinFreeMB })
|
|
757
|
+
if (decision.ok !== true) audit('fork-memory-low', { action, commitFreeMB: decision.commitFreeMB, minFreeMB: decision.minFreeMB })
|
|
758
|
+
return decision
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
/** Single-active-fork policy: stop other running forks before starting/opening one. */
|
|
762
|
+
const pauseOtherForks = async (currentId, reason = 'single-active-fork') => {
|
|
763
|
+
if (cfg.singleActiveFork !== true) return { ok: true, paused: [] }
|
|
764
|
+
const f = forker()
|
|
765
|
+
const paused = []
|
|
766
|
+
for (const [id, task] of tasks) {
|
|
767
|
+
if (id === currentId) continue
|
|
768
|
+
if (task.status !== TASK_STATUS.READY && task.status !== TASK_STATUS.RUNNING) continue
|
|
769
|
+
const live = f?.status?.(id)
|
|
770
|
+
if (!live?.running) continue
|
|
771
|
+
await closeTaskBrowser(task, reason)
|
|
772
|
+
try { f.stop?.(id) } catch { /* already gone */ }
|
|
773
|
+
task.status = TASK_STATUS.FAILED
|
|
774
|
+
task.pid = null
|
|
775
|
+
task.port = null
|
|
776
|
+
task.url = null
|
|
777
|
+
task.adapter = { ok: false, error: 'auto-paused-memory' }
|
|
778
|
+
task.memoryPaused = { reason, at: nowMs() }
|
|
779
|
+
paused.push(id)
|
|
780
|
+
audit('fork-auto-paused', { taskId: id, reason, by: currentId })
|
|
781
|
+
}
|
|
782
|
+
if (paused.length) persist()
|
|
783
|
+
return { ok: true, paused }
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
const memorySamples = new Map()
|
|
787
|
+
|
|
788
|
+
const flushForkSession = async (task) => {
|
|
789
|
+
const flushPath = String(cfg.forkFlushPath || '').trim()
|
|
790
|
+
if (!flushPath) return { ok: false, error: 'unsupported' }
|
|
791
|
+
const opened = forker()?.openUrl?.(task.taskId)
|
|
792
|
+
if (!opened?.url) return { ok: false, error: 'fork-url-unavailable' }
|
|
793
|
+
try {
|
|
794
|
+
const endpoint = new URL(flushPath, opened.url)
|
|
795
|
+
const response = await fetch(endpoint, { method: 'POST', signal: AbortSignal.timeout(3000) })
|
|
796
|
+
return { ok: response.ok, status: response.status, path: flushPath }
|
|
797
|
+
} catch (error) {
|
|
798
|
+
return { ok: false, error: String(error?.message ?? error), path: flushPath }
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
const closeTaskBrowser = async (task, reason = 'guard') => {
|
|
803
|
+
if (!task?.browser?.pid) return { ok: true, skipped: 'no-browser' }
|
|
804
|
+
const browser = task.browser
|
|
805
|
+
const forkFlush = await flushForkSession(task)
|
|
806
|
+
try { await flushManagedBrowser(browser.port) } catch { /* best effort */ }
|
|
807
|
+
const result = await closeManagedBrowser({ pid: browser.pid, port: browser.port, graceMs: cfg.gracefulBrowserCloseMs })
|
|
808
|
+
task.browser = null
|
|
809
|
+
task.browserClosed = { at: nowMs(), reason, pid: browser.pid, ok: result.ok, graceful: result.graceful === true }
|
|
810
|
+
task.memoryGuard = {
|
|
811
|
+
reason,
|
|
812
|
+
at: nowMs(),
|
|
813
|
+
pid: browser.pid,
|
|
814
|
+
metrics: browser.last ?? null,
|
|
815
|
+
graceful: result.graceful === true,
|
|
816
|
+
forkFlush,
|
|
817
|
+
saved: result.graceful === true,
|
|
818
|
+
}
|
|
819
|
+
writeWatchdog()
|
|
820
|
+
try {
|
|
821
|
+
fs.appendFileSync(path.join(layout.dataDir, 'browser-events.jsonl'), JSON.stringify({ taskId: task.taskId, at: nowMs(), event: 'closed', reason, pid: browser.pid, ok: result.ok, graceful: result.graceful === true, forkFlush, metrics: browser.last ?? null }) + '\n')
|
|
822
|
+
} catch { /* diagnostics only */ }
|
|
823
|
+
audit('fork-browser-closed', { taskId: task.taskId, reason, pid: browser.pid, ok: result.ok, graceful: result.graceful === true, forkFlush })
|
|
824
|
+
persist()
|
|
825
|
+
return result
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
const quarantineTask = async (task, reason, { closeBrowser = true, stopFork = true } = {}) => {
|
|
829
|
+
if (!task) return { ok: false, error: 'unknown-task' }
|
|
830
|
+
if (closeBrowser) await closeTaskBrowser(task, reason)
|
|
831
|
+
if (stopFork) {
|
|
832
|
+
try { forker()?.stop?.(task.taskId) } catch { /* best effort */ }
|
|
833
|
+
}
|
|
834
|
+
task.status = TASK_STATUS.FAILED
|
|
835
|
+
task.pid = null
|
|
836
|
+
task.port = null
|
|
837
|
+
task.url = null
|
|
838
|
+
task.token = ''
|
|
839
|
+
task.adapter = { ok: false, error: 'fork-quarantined' }
|
|
840
|
+
task.quarantined = { reason, at: nowMs(), tokenRevoked: true }
|
|
841
|
+
audit('fork-quarantined', { taskId: task.taskId, reason })
|
|
842
|
+
persist()
|
|
843
|
+
return { ok: true, quarantined: true, taskId: task.taskId, reason }
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
const launchTaskBrowser = async (task, url) => {
|
|
847
|
+
if (cfg.managedBrowser !== true) return { ok: true, managed: false, url }
|
|
848
|
+
if (!task || !url) return { ok: false, error: 'browser-url-required' }
|
|
849
|
+
if (task.browser?.pid && isPidAlive(task.browser.pid)) {
|
|
850
|
+
return { ok: true, managed: true, pid: task.browser.pid, port: task.browser.port, reused: true }
|
|
851
|
+
}
|
|
852
|
+
const liveBrowsers = [...tasks.values()].filter((item) => item.browser?.pid && isPidAlive(item.browser.pid))
|
|
853
|
+
const max = Math.max(1, Number(cfg.maxOpenForkBrowsers) || 1)
|
|
854
|
+
let liveCount = liveBrowsers.length
|
|
855
|
+
for (const other of liveBrowsers) {
|
|
856
|
+
if (other.taskId === task.taskId) continue
|
|
857
|
+
if (liveCount < max) break
|
|
858
|
+
await closeTaskBrowser(other, 'max-open-fork-browsers')
|
|
859
|
+
liveCount -= 1
|
|
860
|
+
}
|
|
861
|
+
const exe = findBrowserPath(cfg.browserPath)
|
|
862
|
+
if (!exe) return { ok: false, error: 'browser-unavailable' }
|
|
863
|
+
const port = await freePort()
|
|
864
|
+
if (!port) return { ok: false, error: 'browser-port-unavailable' }
|
|
865
|
+
const profileDir = path.join(task.homeDir, 'browser-profile')
|
|
866
|
+
const logDir = path.join(task.homeDir, 'browser-logs')
|
|
867
|
+
const launched = await launchManagedBrowser({ exe, url, profileDir, logDir, port })
|
|
868
|
+
if (launched.ok !== true) {
|
|
869
|
+
audit('fork-browser-launch-failed', { taskId: task.taskId, error: launched.error, pid: launched.pid ?? null })
|
|
870
|
+
return launched
|
|
871
|
+
}
|
|
872
|
+
task.browser = {
|
|
873
|
+
pid: launched.pid, port: launched.port, profileDir, logFile: launched.logFile,
|
|
874
|
+
crashDir: launched.crashDir, exe, startedAt: nowMs(), hiddenSince: null, last: null,
|
|
875
|
+
}
|
|
876
|
+
writeWatchdog()
|
|
877
|
+
persist()
|
|
878
|
+
audit('fork-browser-opened', { taskId: task.taskId, pid: launched.pid, port: launched.port })
|
|
879
|
+
return { ok: true, managed: true, pid: launched.pid, port: launched.port }
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
let hostPanic = false
|
|
883
|
+
const hostEmergency = async (reason, { safe = false } = {}) => {
|
|
884
|
+
if (hostPanic) return { ok: true, skipped: 'in-progress' }
|
|
885
|
+
hostPanic = true
|
|
886
|
+
try {
|
|
887
|
+
// Order is deliberate: browser (largest commit) first, then fork backends.
|
|
888
|
+
for (const task of tasks.values()) {
|
|
889
|
+
if (task.browser?.pid) await closeTaskBrowser(task, `host-panic:${reason}`)
|
|
890
|
+
}
|
|
891
|
+
for (const task of tasks.values()) {
|
|
892
|
+
if (task.status === TASK_STATUS.READY || task.status === TASK_STATUS.RUNNING) {
|
|
893
|
+
await quarantineTask(task, `host-panic:${reason}`, { closeBrowser: false })
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
if (safe) {
|
|
897
|
+
safeMode = true
|
|
898
|
+
safeModeReason = `host-emergency:${reason}`
|
|
899
|
+
persistSafeMode()
|
|
900
|
+
}
|
|
901
|
+
const self = process.memoryUsage()
|
|
902
|
+
audit('host-emergency-guard', { reason, safe, tasks: tasks.size, selfRssMB: Math.round(self.rss / 1048576), selfPrivateMB: Math.round((self.heapUsed + self.external) / 1048576) })
|
|
903
|
+
return { ok: true, reason, safe }
|
|
904
|
+
} finally {
|
|
905
|
+
hostPanic = false
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
const recordForkMemory = async (task, rootPid, table) => {
|
|
910
|
+
const tree = sumProcessTree(selectProcessTree(table.rows, rootPid))
|
|
911
|
+
if (!tree.count) return null
|
|
912
|
+
const list = memorySamples.get(task.taskId) ?? []
|
|
913
|
+
list.push({ at: nowMs(), ...tree })
|
|
914
|
+
if (list.length > 40) list.splice(0, list.length - 40)
|
|
915
|
+
memorySamples.set(task.taskId, list)
|
|
916
|
+
try {
|
|
917
|
+
fs.appendFileSync(path.join(layout.dataDir, 'memory-samples.jsonl'), JSON.stringify({ taskId: task.taskId, at: nowMs(), ...tree }) + '\n')
|
|
918
|
+
} catch { /* diagnostics only */ }
|
|
919
|
+
const low = Math.min(...list.map((sample) => Number(sample.commitMB) || 0))
|
|
920
|
+
const current = Number(tree.commitMB) || 0
|
|
921
|
+
const overKill = current >= Number(cfg.memoryKillCommitMB)
|
|
922
|
+
const overGrowth = current - low >= Number(cfg.memoryGrowCommitMB)
|
|
923
|
+
if (overKill && overGrowth) {
|
|
924
|
+
try { forker()?.stop?.(task.taskId) } catch { /* best effort */ }
|
|
925
|
+
try { await killProcessTree(rootPid) } catch { /* PID may already be gone */ }
|
|
926
|
+
task.status = TASK_STATUS.FAILED
|
|
927
|
+
task.pid = null
|
|
928
|
+
task.port = null
|
|
929
|
+
task.url = null
|
|
930
|
+
task.adapter = { ok: false, error: 'memory-watchdog-killed' }
|
|
931
|
+
task.memoryKill = { at: nowMs(), commitMB: current, lowMB: low, pids: tree.pids }
|
|
932
|
+
audit('fork-memory-killed', { taskId: task.taskId, commitMB: current, lowMB: low, pids: tree.pids })
|
|
933
|
+
persist()
|
|
934
|
+
return { ...tree, killed: true }
|
|
935
|
+
}
|
|
936
|
+
return tree
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
const taskIdleForClose = (task) => {
|
|
940
|
+
const live = forker()?.status?.(task.taskId)
|
|
941
|
+
if (!live?.running) return true
|
|
942
|
+
if (task.adapter?.busy === true) return false
|
|
943
|
+
// Conservative: without an explicit idle signal, never auto-close a live fork page.
|
|
944
|
+
return task.adapter?.idle === true
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
const browserWatchdogTick = async (table) => {
|
|
948
|
+
if (cfg.managedBrowser !== true || process.platform !== 'win32') return
|
|
949
|
+
for (const task of tasks.values()) {
|
|
950
|
+
const browser = task.browser
|
|
951
|
+
if (!browser?.pid) continue
|
|
952
|
+
if (!isPidAlive(browser.pid)) {
|
|
953
|
+
task.browser = null
|
|
954
|
+
task.browserClosed = { at: nowMs(), reason: 'browser-process-exited', pid: browser.pid }
|
|
955
|
+
audit('fork-browser-exited', { taskId: task.taskId, pid: browser.pid })
|
|
956
|
+
persist()
|
|
957
|
+
continue
|
|
958
|
+
}
|
|
959
|
+
const tree = sumProcessTree(selectProcessTree(table.rows, browser.pid))
|
|
960
|
+
const sample = await sampleManagedBrowser(browser.port)
|
|
961
|
+
const nodes = Number(sample?.nodes) || 0
|
|
962
|
+
const heapMB = Math.round((Number(sample?.heapBytes) || 0) / 1048576)
|
|
963
|
+
browser.last = { at: nowMs(), ...tree, nodes, heapMB, visibility: sample?.visibility ?? 'unknown', documents: Number(sample?.documents) || 0, listeners: Number(sample?.listeners) || 0 }
|
|
964
|
+
try {
|
|
965
|
+
fs.appendFileSync(path.join(layout.dataDir, 'browser-samples.jsonl'), JSON.stringify({ taskId: task.taskId, ...browser.last }) + '\n')
|
|
966
|
+
} catch { /* diagnostics only */ }
|
|
967
|
+
const overMemory = Number(tree.commitMB) >= Number(cfg.browserMemoryLimitMB)
|
|
968
|
+
const overHeap = heapMB >= Number(cfg.browserHeapLimitMB)
|
|
969
|
+
const overDom = nodes >= Number(cfg.browserDomNodeLimit)
|
|
970
|
+
if (overMemory || overHeap || overDom) {
|
|
971
|
+
const reason = overMemory ? 'browser-memory-limit' : overHeap ? 'browser-heap-limit' : 'browser-dom-limit'
|
|
972
|
+
audit('fork-browser-memory-guard', { taskId: task.taskId, commitMB: tree.commitMB, nodes, heapMB, overMemory, overHeap, overDom })
|
|
973
|
+
await quarantineTask(task, reason)
|
|
974
|
+
continue
|
|
975
|
+
}
|
|
976
|
+
if (cfg.autoCloseIdleMinutes > 0) {
|
|
977
|
+
if (sample?.ok === true && sample.visibility === 'hidden') {
|
|
978
|
+
if (!browser.hiddenSince) browser.hiddenSince = nowMs()
|
|
979
|
+
const idleMs = nowMs() - Number(browser.hiddenSince)
|
|
980
|
+
if (idleMs >= Number(cfg.autoCloseIdleMinutes) * 60_000 && (!cfg.idleCloseOnlyWhenIdle || taskIdleForClose(task))) {
|
|
981
|
+
await closeTaskBrowser(task, 'idle-hidden')
|
|
982
|
+
continue
|
|
983
|
+
}
|
|
984
|
+
} else if (sample?.ok === true) {
|
|
985
|
+
browser.hiddenSince = null
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
const memoryWatchdogTick = async () => {
|
|
992
|
+
if (cfg.memoryWatchdog !== true || process.platform !== 'win32') return
|
|
993
|
+
const running = [...tasks.values()].filter((task) => task.status === TASK_STATUS.READY || task.status === TASK_STATUS.RUNNING)
|
|
994
|
+
const hasBrowser = [...tasks.values()].some((task) => task.browser?.pid)
|
|
995
|
+
if (!running.length && !hasBrowser) return
|
|
996
|
+
const table = await readProcessTable()
|
|
997
|
+
if (!table.ok) return
|
|
998
|
+
for (const task of running) {
|
|
999
|
+
const rootPid = Number(forker()?.status?.(task.taskId)?.pid ?? task.pid)
|
|
1000
|
+
if (rootPid > 0) await recordForkMemory(task, rootPid, table)
|
|
1001
|
+
}
|
|
1002
|
+
await browserWatchdogTick(table)
|
|
1003
|
+
// Red line: aggregate fork+browser commit must stay below the configured share.
|
|
1004
|
+
const memory = await readSystemMemory()
|
|
1005
|
+
if (memory.ok && Number(memory.commitLimitMB) > 0) {
|
|
1006
|
+
let total = 0
|
|
1007
|
+
for (const task of tasks.values()) {
|
|
1008
|
+
if (task.status === TASK_STATUS.READY || task.status === TASK_STATUS.RUNNING) {
|
|
1009
|
+
total += sumProcessTree(selectProcessTree(table.rows, Number(forker()?.status?.(task.taskId)?.pid ?? task.pid))).commitMB
|
|
1010
|
+
}
|
|
1011
|
+
if (task.browser?.pid) total += sumProcessTree(selectProcessTree(table.rows, Number(task.browser.pid))).commitMB
|
|
1012
|
+
}
|
|
1013
|
+
const limit = Number(memory.commitLimitMB) * Number(cfg.forkCommitShareLimit)
|
|
1014
|
+
if (total > limit) {
|
|
1015
|
+
audit('fork-commit-share-exceeded', { totalMB: total, limitMB: Math.round(limit), share: cfg.forkCommitShareLimit })
|
|
1016
|
+
await hostEmergency('fork-commit-share', { safe: true })
|
|
1017
|
+
return
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
writeWatchdog()
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
let lastHostWarnAt = 0
|
|
1024
|
+
const hostWatchdogTick = async () => {
|
|
1025
|
+
if (process.platform !== 'win32' || hostPanic) return
|
|
1026
|
+
const memory = await readSystemMemory()
|
|
1027
|
+
if (!memory.ok) return
|
|
1028
|
+
const free = Number(memory.commitFreeMB) || 0
|
|
1029
|
+
if (free < Number(cfg.hostWarnFreeMB) && nowMs() - lastHostWarnAt > 60_000) {
|
|
1030
|
+
lastHostWarnAt = nowMs()
|
|
1031
|
+
const self = process.memoryUsage()
|
|
1032
|
+
audit('host-memory-warning', { commitFreeMB: free, warnMB: cfg.hostWarnFreeMB, selfRssMB: Math.round(self.rss / 1048576), selfPrivateMB: Math.round((self.heapUsed + self.external) / 1048576) })
|
|
1033
|
+
}
|
|
1034
|
+
if (free < Number(cfg.hostCriticalFreeMB)) {
|
|
1035
|
+
await hostEmergency('commit-free-critical', { safe: true })
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
|
|
1040
|
+
const cleanupOrphanForks = async () => {
|
|
1041
|
+
if (process.platform !== 'win32') return { ok: true, killed: [] }
|
|
1042
|
+
const table = await readProcessTable()
|
|
1043
|
+
if (!table.ok) return { ok: false, killed: [], error: table.error }
|
|
1044
|
+
const killed = []
|
|
1045
|
+
for (const task of tasks.values()) {
|
|
1046
|
+
if (task.status !== TASK_STATUS.ARCHIVED && task.status !== TASK_STATUS.FAILED) continue
|
|
1047
|
+
const rootPid = Number(task.pid)
|
|
1048
|
+
if (!(rootPid > 0)) continue
|
|
1049
|
+
const tree = selectProcessTree(table.rows, rootPid)
|
|
1050
|
+
if (!tree.length) continue
|
|
1051
|
+
const marker = String(task.taskId)
|
|
1052
|
+
const looksLikeFork = tree.some((row) => row.commandLine.includes(marker) || (task.profile && row.commandLine.includes(String(task.profile))))
|
|
1053
|
+
if (!looksLikeFork) continue
|
|
1054
|
+
const result = await killProcessTree(rootPid)
|
|
1055
|
+
if (result.ok) { killed.push(task.taskId); audit('fork-orphan-killed', { taskId: task.taskId, pid: rootPid }) }
|
|
1056
|
+
}
|
|
1057
|
+
return { ok: true, killed }
|
|
1058
|
+
}
|
|
1059
|
+
|
|
591
1060
|
const cliPath = () => (cfg.cliPath ? cfg.cliPath : resolveCliPath('', process.env))
|
|
592
1061
|
const forkTempEnv = (taskId) => {
|
|
593
1062
|
const tmp = path.join(layout.forkHomesDir, String(taskId), 'tmp')
|
|
@@ -1068,6 +1537,7 @@ export function apply(ctx, config) {
|
|
|
1068
1537
|
|
|
1069
1538
|
/** v2 主入口:派生一个任务(= 一个分身)。 */
|
|
1070
1539
|
async createTask(input = {}) {
|
|
1540
|
+
if (safeMode) return { ok: false, error: 'safe-mode', detail: safeModeReason || 'host-safe-mode' }
|
|
1071
1541
|
const title = String(input.title ?? input.taskTitle ?? '').trim() || `任务 ${tasks.size + 1}`
|
|
1072
1542
|
const running = [...tasks.values()].filter(t => {
|
|
1073
1543
|
const s = taskView(t).status
|
|
@@ -1084,6 +1554,9 @@ export function apply(ctx, config) {
|
|
|
1084
1554
|
const taskId = newId('task')
|
|
1085
1555
|
const profile = `fang-${taskId.replace(/^task_/, '').slice(0, 12)}`
|
|
1086
1556
|
const homeDir = path.join(layout.forkHomesDir, taskId)
|
|
1557
|
+
const memory = await memoryGate('create-fork')
|
|
1558
|
+
if (memory.ok !== true) return { ok: false, taskId, ...memory }
|
|
1559
|
+
const paused = await pauseOtherForks(taskId, 'create-fork')
|
|
1087
1560
|
const template = String(input.template ?? '').trim()
|
|
1088
1561
|
// v3.0.9:从原身派生时,模板来源是该原身的 merged/profile(分身只生产,不回写原身)。
|
|
1089
1562
|
// v3.0.9:未指定来源时,若存在“默认元宝”,快速派生直接以它为模板(新用户小白路径)。
|
|
@@ -1316,6 +1789,8 @@ export function apply(ctx, config) {
|
|
|
1316
1789
|
task.url = started.url ?? null
|
|
1317
1790
|
task.token = started.token ?? extractTokenSafe(task.url)
|
|
1318
1791
|
persist()
|
|
1792
|
+
writeWatchdog()
|
|
1793
|
+
void lowerProcessPriority(task.pid)
|
|
1319
1794
|
audit(AUDIT.FORK_STARTED, { taskId, pid: task.pid, port: task.port, profile })
|
|
1320
1795
|
bus.emit('fang/task-created', { taskId, forkId: taskId, title, url: task.url, port: task.port })
|
|
1321
1796
|
|
|
@@ -1868,6 +2343,7 @@ export function apply(ctx, config) {
|
|
|
1868
2343
|
}
|
|
1869
2344
|
const deadline = nowMs() + cfg.archiveStopTimeoutMs
|
|
1870
2345
|
let alive = true
|
|
2346
|
+
await closeTaskBrowser(task, 'archive')
|
|
1871
2347
|
while (nowMs() < deadline) {
|
|
1872
2348
|
alive = typeof f.alive === 'function' ? !!f.alive(id) : !!(f.status?.(id)?.running)
|
|
1873
2349
|
if (!alive) break
|
|
@@ -1963,8 +2439,12 @@ export function apply(ctx, config) {
|
|
|
1963
2439
|
const id = String(taskId ?? '')
|
|
1964
2440
|
const task = tasks.get(id)
|
|
1965
2441
|
if (!task) return { ok: false, error: 'unknown-task' }
|
|
2442
|
+
if (safeMode) return { ok: false, taskId: id, error: 'safe-mode', detail: safeModeReason || 'host-safe-mode' }
|
|
1966
2443
|
const f = forker()
|
|
1967
2444
|
if (!f || typeof f.spawn !== 'function') return { ok: false, error: 'forker-unavailable', taskId: id }
|
|
2445
|
+
const memory = await memoryGate('restore-fork')
|
|
2446
|
+
if (memory.ok !== true) return { ok: false, taskId: id, ...memory }
|
|
2447
|
+
const paused = await pauseOtherForks(id, 'restore-fork')
|
|
1968
2448
|
// 2026-11-22:任务可能停在 ready/running,但子进程已经死了(宿主重启、手动 kill、
|
|
1969
2449
|
// 端口丢失)。客户端「启动」仍会调用 restore;旧逻辑返回 not-archived,导致
|
|
1970
2450
|
// 真机界面一直显示“启动失败”。这里允许恢复 stale 的 ready/running。
|
|
@@ -2059,13 +2539,19 @@ export function apply(ctx, config) {
|
|
|
2059
2539
|
task.token = started.token ?? extractTokenSafe(task.url)
|
|
2060
2540
|
task.adapter = { ok: false, error: 'handshaking' }
|
|
2061
2541
|
persist()
|
|
2542
|
+
writeWatchdog()
|
|
2543
|
+
void lowerProcessPriority(task.pid)
|
|
2062
2544
|
audit(AUDIT.FORK_STARTED, { taskId: id, pid: task.pid, port: task.port, profile: task.profile, restored: true })
|
|
2063
2545
|
const adapter = await handshake(task)
|
|
2064
2546
|
task.status = adapter.ok ? TASK_STATUS.READY : TASK_STATUS.RUNNING
|
|
2065
2547
|
persist()
|
|
2066
2548
|
audit(AUDIT.TASK_RESTORED, { taskId: id, ok: true, adapter })
|
|
2067
2549
|
bus.emit('fang/task-restored', { taskId: id, url: task.url, port: task.port })
|
|
2068
|
-
|
|
2550
|
+
if (task.quarantined) {
|
|
2551
|
+
task.quarantined = null
|
|
2552
|
+
audit('fork-quarantine-cleared', { taskId: id, by: 'restore' })
|
|
2553
|
+
}
|
|
2554
|
+
return { ok: true, restored: true, taskId: id, title: task.title, url: task.url, port: task.port, adapter, configReset, sessionGuard, paused }
|
|
2069
2555
|
},
|
|
2070
2556
|
|
|
2071
2557
|
/**
|
|
@@ -2077,6 +2563,11 @@ export function apply(ctx, config) {
|
|
|
2077
2563
|
const id = String(taskId ?? '')
|
|
2078
2564
|
const task = tasks.get(id)
|
|
2079
2565
|
if (!task) return { ok: false, error: 'unknown-task' }
|
|
2566
|
+
if (safeMode) return { ok: false, taskId: id, error: 'safe-mode', detail: safeModeReason || 'host-safe-mode' }
|
|
2567
|
+
if (task.quarantined) return { ok: false, taskId: id, error: 'fork-quarantined', detail: task.quarantined.reason ?? 'guard' }
|
|
2568
|
+
const memory = await memoryGate('open-fork')
|
|
2569
|
+
if (memory.ok !== true) return { ok: false, taskId: id, ...memory }
|
|
2570
|
+
const paused = await pauseOtherForks(id, 'open-fork')
|
|
2080
2571
|
const sourceId = String(task.essenceId || task.syncSourceId || OFFICIAL_ESSENCE_ID)
|
|
2081
2572
|
captureEssenceRuntimeIfPresent(sourceId)
|
|
2082
2573
|
if (sourceId === OFFICIAL_ESSENCE_ID) await repairOfficialEssenceNow()
|
|
@@ -2094,15 +2585,15 @@ export function apply(ctx, config) {
|
|
|
2094
2585
|
task.url = null
|
|
2095
2586
|
persist()
|
|
2096
2587
|
const restored = await service.restoreTask(id)
|
|
2097
|
-
return { ...restored, synced: true, restarted: true, sourceFingerprint: fingerprint }
|
|
2588
|
+
return { ...restored, synced: true, restarted: true, sourceFingerprint: fingerprint, paused }
|
|
2098
2589
|
}
|
|
2099
2590
|
if (task.status === TASK_STATUS.FAILED) {
|
|
2100
2591
|
const restored = await service.restoreTask(id)
|
|
2101
|
-
return { ...restored, synced: true, restarted: true, sourceFingerprint: fingerprint }
|
|
2592
|
+
return { ...restored, synced: true, restarted: true, sourceFingerprint: fingerprint, paused }
|
|
2102
2593
|
}
|
|
2103
2594
|
const out = forker()?.openUrl?.(id) ?? null
|
|
2104
2595
|
if (!out || out.ok !== true) return { ok: false, error: out?.error ?? 'not-running' }
|
|
2105
|
-
return { ...out, synced: true, restarted: false, sourceFingerprint: fingerprint }
|
|
2596
|
+
return { ...out, synced: true, restarted: false, sourceFingerprint: fingerprint, paused }
|
|
2106
2597
|
},
|
|
2107
2598
|
|
|
2108
2599
|
/**
|
|
@@ -2413,6 +2904,25 @@ export function apply(ctx, config) {
|
|
|
2413
2904
|
}
|
|
2414
2905
|
|
|
2415
2906
|
ctx.effect(() => ctx.provide(SERVICE.orchestrator, service))
|
|
2907
|
+
// 2026-11-24: sample fork PID trees/commit; kill only the offending fork.
|
|
2908
|
+
if (cfg.memoryWatchdog === true && process.platform === 'win32') {
|
|
2909
|
+
const timer = setInterval(() => { void memoryWatchdogTick() }, cfg.memoryWatchIntervalMs)
|
|
2910
|
+
timer.unref?.()
|
|
2911
|
+
try { ctx.effect(() => () => clearInterval(timer)) } catch { /* fake ctx */ }
|
|
2912
|
+
}
|
|
2913
|
+
// v3.8.0: host self-preservation. This must run even when no fork is running.
|
|
2914
|
+
if (process.platform === 'win32') {
|
|
2915
|
+
const timer = setInterval(() => { void hostWatchdogTick() }, 5000)
|
|
2916
|
+
timer.unref?.()
|
|
2917
|
+
try { ctx.effect(() => () => clearInterval(timer)) } catch { /* fake ctx */ }
|
|
2918
|
+
}
|
|
2919
|
+
// Startup: reclaim archived/failed fork processes whose recorded PID still lives.
|
|
2920
|
+
void cleanupOrphanForks()
|
|
2921
|
+
if (cfg.orphanSweepMinutes > 0) {
|
|
2922
|
+
const timer = setInterval(() => { void cleanupOrphanForks() }, Number(cfg.orphanSweepMinutes) * 60_000)
|
|
2923
|
+
timer.unref?.()
|
|
2924
|
+
try { ctx.effect(() => () => clearInterval(timer)) } catch { /* fake ctx */ }
|
|
2925
|
+
}
|
|
2416
2926
|
// v3.3.8:启动后异步自愈默认元主;不阻塞 boot,不 unref 也不会阻止退出。
|
|
2417
2927
|
{
|
|
2418
2928
|
const timer = setTimeout(() => { void refreshStaleDefaultEssenceIfNeeded() }, 1500)
|
|
@@ -3512,6 +4022,9 @@ export function apply(ctx, config) {
|
|
|
3512
4022
|
}
|
|
3513
4023
|
// 先导入选中的进行中会话,再拉起实例(实例启动时就能看到它们)。
|
|
3514
4024
|
const importedSessions = importSessionsInto(homeDir, input?.sessionIds)
|
|
4025
|
+
const memory = await memoryGate('start-essence-runtime')
|
|
4026
|
+
if (memory.ok !== true) return { ok: false, error: memory.error, taskId: forkId, ...memory }
|
|
4027
|
+
const paused = await pauseOtherForks(forkId, 'start-essence-runtime')
|
|
3515
4028
|
// 注意:forker.spawn 需要显式 homeDir/profile(它不从 provision 记录里猜)。
|
|
3516
4029
|
const started = await f.spawn({
|
|
3517
4030
|
forkId,
|
|
@@ -3545,6 +4058,27 @@ export function apply(ctx, config) {
|
|
|
3545
4058
|
capture,
|
|
3546
4059
|
}
|
|
3547
4060
|
},
|
|
4061
|
+
|
|
4062
|
+
openManagedBrowser: async (taskId, url) => {
|
|
4063
|
+
const task = tasks.get(String(taskId ?? ''))
|
|
4064
|
+
if (!task) return { ok: false, error: 'unknown-task' }
|
|
4065
|
+
if (task.quarantined) return { ok: false, error: 'fork-quarantined', detail: task.quarantined.reason ?? 'guard' }
|
|
4066
|
+
return launchTaskBrowser(task, String(url ?? task.url ?? ''))
|
|
4067
|
+
},
|
|
4068
|
+
closeManagedBrowser: async (taskId, reason = 'user') => {
|
|
4069
|
+
const task = tasks.get(String(taskId ?? ''))
|
|
4070
|
+
if (!task) return { ok: false, error: 'unknown-task' }
|
|
4071
|
+
return closeTaskBrowser(task, reason)
|
|
4072
|
+
},
|
|
4073
|
+
safeModeStatus: () => ({ ok: true, safeMode, reason: safeModeReason }),
|
|
4074
|
+
panic: async () => hostEmergency('manual-panic', { safe: true }),
|
|
4075
|
+
resetSafeMode: () => {
|
|
4076
|
+
safeMode = false
|
|
4077
|
+
safeModeReason = ''
|
|
4078
|
+
persistSafeMode()
|
|
4079
|
+
audit('host-safe-mode-reset', {})
|
|
4080
|
+
return { ok: true, safeMode: false }
|
|
4081
|
+
},
|
|
3548
4082
|
stopEssenceRuntime: async (essenceId) => {
|
|
3549
4083
|
const id = String(essenceId ?? '').trim()
|
|
3550
4084
|
const f = forker()
|
|
@@ -4653,6 +5187,9 @@ export function apply(ctx, config) {
|
|
|
4653
5187
|
const taskId = String(query.get('taskId') ?? '').trim()
|
|
4654
5188
|
if (!taskId) return json(res, 400, { ok: false, error: 'taskId-required' })
|
|
4655
5189
|
if (!tasks.has(taskId)) return json(res, 404, { ok: false, error: 'unknown-task', taskId })
|
|
5190
|
+
if (safeMode) return json(res, 423, { ok: false, error: 'safe-mode', detail: safeModeReason })
|
|
5191
|
+
const guardTask = tasks.get(taskId)
|
|
5192
|
+
if (guardTask?.quarantined) return json(res, 423, { ok: false, error: 'fork-quarantined', detail: guardTask.quarantined.reason ?? 'guard' })
|
|
4656
5193
|
const out = forker()?.openUrl?.(taskId) ?? null
|
|
4657
5194
|
if (!out || out.ok !== true) return json(res, 404, { ok: false, error: out?.error ?? 'not-running', taskId })
|
|
4658
5195
|
return json(res, 200, out)
|
|
@@ -4664,10 +5201,26 @@ export function apply(ctx, config) {
|
|
|
4664
5201
|
if (!tasks.has(taskId)) return json(res, 404, { ok: false, error: 'unknown-task', taskId })
|
|
4665
5202
|
const out = await service.syncTaskOnOpen(taskId)
|
|
4666
5203
|
if (!out || out.ok !== true) {
|
|
4667
|
-
const status = out?.error === 'unknown-task' ? 404 : out?.error === 'not-running' ? 404 : 409
|
|
5204
|
+
const status = out?.error === 'unknown-task' ? 404 : out?.error === 'not-running' ? 404 : out?.error === 'safe-mode' || out?.error === 'fork-quarantined' ? 423 : 409
|
|
4668
5205
|
return json(res, status, { ok: false, error: out?.error ?? 'not-running', ...out })
|
|
4669
5206
|
}
|
|
4670
|
-
|
|
5207
|
+
let managed = { ok: true, managed: false }
|
|
5208
|
+
if (out.url) {
|
|
5209
|
+
try {
|
|
5210
|
+
const browser = await service.openManagedBrowser(taskId, out.url)
|
|
5211
|
+
if (browser?.ok === true) managed = browser
|
|
5212
|
+
else managed = { ok: true, managed: false, browserError: browser?.error ?? 'browser-unavailable' }
|
|
5213
|
+
} catch (error) {
|
|
5214
|
+
managed = { ok: true, managed: false, browserError: String(error?.message ?? error) }
|
|
5215
|
+
audit('fork-browser-open-handler-failed', { taskId, error: String(error?.message ?? error) })
|
|
5216
|
+
}
|
|
5217
|
+
}
|
|
5218
|
+
return json(res, 200, { ...out, ...managed })
|
|
5219
|
+
})
|
|
5220
|
+
route('GET', `${prefix}/api/safe-mode`, async (req, res) => json(res, 200, service.safeModeStatus()))
|
|
5221
|
+
route('POST', `${prefix}/api/safe-mode/reset`, async (req, res) => {
|
|
5222
|
+
await readBody(req)
|
|
5223
|
+
return json(res, 200, service.resetSafeMode())
|
|
4671
5224
|
})
|
|
4672
5225
|
route('POST', `${prefix}/api/tasks/archive`, async (req, res) => {
|
|
4673
5226
|
const body = await readBody(req)
|
|
@@ -4677,7 +5230,8 @@ export function apply(ctx, config) {
|
|
|
4677
5230
|
route('POST', `${prefix}/api/tasks/restore`, async (req, res) => {
|
|
4678
5231
|
const body = await readBody(req)
|
|
4679
5232
|
const out = await service.restoreTask(String(body?.taskId ?? ''))
|
|
4680
|
-
|
|
5233
|
+
const status = out.ok ? 200 : out?.error === 'safe-mode' ? 423 : out?.error === 'fork-quarantined' ? 423 : 409
|
|
5234
|
+
return json(res, status, out)
|
|
4681
5235
|
})
|
|
4682
5236
|
// 2026-11-22:一键修复(停残留 → 清别名桩 → 重置配置 → 重新拉起;不删 home/会话)
|
|
4683
5237
|
route('POST', `${prefix}/api/vault/export`, async (req, res) => {
|