@twinsearth/dsh-fang 3.7.6 → 3.8.0

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 CHANGED
@@ -1,4 +1,4 @@
1
- [![CI](https://github.com/TwinsEarth/dsh-fang/actions/workflows/ci.yml/badge.svg)](https://github.com/TwinsEarth/dsh-fang/actions/workflows/ci.yml)
1
+ [![CI](https://github.com/TwinsEarth/fang-dsh-plugin/actions/workflows/ci.yml/badge.svg)](https://github.com/TwinsEarth/fang-dsh-plugin/actions/workflows/ci.yml)
2
2
  [![DSH](https://img.shields.io/badge/DSH-0.2.2--rc.1-4D6BFE?logo=deepseek&logoColor=white)](https://github.com/deepseek-ai/deepseek-harness)
3
3
  [![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-blue.svg)](LICENSE-CORE)
4
4
  [![SDK: MIT](https://img.shields.io/badge/SDK-MIT-green.svg)](LICENSE-SDK)
@@ -71,7 +71,7 @@
71
71
  ## 快速开始
72
72
 
73
73
  ```powershell
74
- git clone https://github.com/TwinsEarth/dsh-fang.git && cd dsh-fang
74
+ git clone https://github.com/TwinsEarth/fang-dsh-plugin.git && cd dsh-fang
75
75
 
76
76
  # 1. 离线自检(不修改任何东西)
77
77
  node tools/fangctl.mjs doctor
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 {
@@ -2829,13 +2833,82 @@ html[data-fang-overlays="hidden"] .fang-console .toast{display:none!important}
2829
2833
  void loadEssenceDetail()
2830
2834
  }
2831
2835
 
2836
+ /**
2837
+ * Electron webview does not implement the native prompt(); using it makes
2838
+ * 导出/导入 look completely dead. Use an in-app dialog instead.
2839
+ */
2840
+ function vaultDialog({ title, label, defaultValue = '', withWorkspace = false }) {
2841
+ return new Promise((resolve) => {
2842
+ const overlay = document.createElement('div')
2843
+ overlay.style.cssText = 'position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,.45);display:flex;align-items:center;justify-content:center;padding:20px'
2844
+ const box = document.createElement('div')
2845
+ box.style.cssText = 'width:min(560px,100%);background:var(--f-surface,#fff);color:var(--f-text,#111);border:1px solid var(--f-line,#d0d7de);border-radius:12px;padding:18px;box-shadow:0 18px 60px rgba(0,0,0,.25);font:14px/1.5 system-ui,sans-serif'
2846
+ const heading = document.createElement('div')
2847
+ heading.textContent = title
2848
+ heading.style.cssText = 'font-weight:700;font-size:16px;margin-bottom:12px'
2849
+ const hint = document.createElement('div')
2850
+ hint.textContent = label
2851
+ hint.style.cssText = 'font-size:12.5px;opacity:.8;margin-bottom:8px'
2852
+ const input = document.createElement('input')
2853
+ input.type = 'text'
2854
+ input.value = defaultValue
2855
+ input.placeholder = 'D:\\backup\\fang'
2856
+ input.style.cssText = 'width:100%;box-sizing:border-box;padding:9px 10px;border:1px solid var(--f-line,#d0d7de);border-radius:8px;background:transparent;color:inherit;font:inherit'
2857
+ const workspaceLine = document.createElement('label')
2858
+ workspaceLine.style.cssText = 'display:flex;gap:8px;align-items:flex-start;margin-top:12px;font-size:12.5px'
2859
+ const workspace = document.createElement('input')
2860
+ workspace.type = 'checkbox'
2861
+ workspace.checked = false
2862
+ const workspaceText = document.createElement('span')
2863
+ workspaceText.textContent = '同时打包工作区项目文件(默认不勾选;项目很大时会明显变慢)'
2864
+ workspaceLine.append(workspace, workspaceText)
2865
+ const actions = document.createElement('div')
2866
+ actions.style.cssText = 'display:flex;justify-content:flex-end;gap:8px;margin-top:16px'
2867
+ const cancel = document.createElement('button')
2868
+ cancel.type = 'button'
2869
+ cancel.textContent = '取消'
2870
+ cancel.style.cssText = 'padding:7px 14px;border:1px solid var(--f-line,#d0d7de);border-radius:7px;background:transparent;color:inherit;cursor:pointer'
2871
+ const ok = document.createElement('button')
2872
+ ok.type = 'button'
2873
+ ok.textContent = '确定'
2874
+ ok.style.cssText = 'padding:7px 14px;border:0;border-radius:7px;background:#2563eb;color:#fff;cursor:pointer'
2875
+ actions.append(cancel, ok)
2876
+ box.append(heading, hint, input)
2877
+ if (withWorkspace) box.append(workspaceLine)
2878
+ box.append(actions)
2879
+ overlay.append(box)
2880
+ const close = (value) => {
2881
+ overlay.remove()
2882
+ document.removeEventListener('keydown', onKey)
2883
+ resolve(value)
2884
+ }
2885
+ const onKey = (event) => {
2886
+ if (event.key === 'Escape') close(null)
2887
+ if (event.key === 'Enter' && document.activeElement === input) close({ value: input.value.trim(), workspace: workspace.checked })
2888
+ }
2889
+ cancel.addEventListener('click', () => close(null))
2890
+ ok.addEventListener('click', () => close({ value: input.value.trim(), workspace: workspace.checked }))
2891
+ overlay.addEventListener('click', (event) => { if (event.target === overlay) close(null) })
2892
+ document.addEventListener('keydown', onKey)
2893
+ document.body.appendChild(overlay)
2894
+ input.focus()
2895
+ input.select()
2896
+ })
2897
+ }
2898
+
2832
2899
  async function exportTask(task) {
2833
2900
  const taskId = String(task?.taskId ?? '')
2834
2901
  if (!taskId) return
2835
2902
  const fallback = localStorage.getItem('fang.exportDir') || ''
2836
- const destDir = window.prompt('导出到文件夹(绝对路径;不存在会自动创建)', fallback)
2837
- if (!destDir) return
2838
- const workspace = window.confirm('是否同时打包工作区项目文件?\n\n默认「取消」= 只导出会话/附件/配置/日志。\n项目很大时会明显变慢。')
2903
+ const answer = await vaultDialog({
2904
+ title: '导出分身',
2905
+ label: '导出到文件夹(绝对路径;不存在会自动创建)',
2906
+ defaultValue: fallback,
2907
+ withWorkspace: true,
2908
+ })
2909
+ if (!answer?.value) return
2910
+ const destDir = answer.value
2911
+ const workspace = answer.workspace === true
2839
2912
  localStorage.setItem('fang.exportDir', destDir)
2840
2913
  const result = await api('/fang/api/vault/export', { method: 'POST', body: JSON.stringify({ taskId, destDir, options: { workspace, workspaceSnapshot: workspace } }) })
2841
2914
  if (result.status === 200 && result.body?.ok) {
@@ -2846,8 +2919,13 @@ html[data-fang-overlays="hidden"] .fang-console .toast{display:none!important}
2846
2919
  }
2847
2920
 
2848
2921
  async function importTask() {
2849
- const sourceDir = window.prompt('选择分身导出包文件夹(包含 manifest.json 的那一层)', localStorage.getItem('fang.importDir') || '')
2850
- if (!sourceDir) return
2922
+ const answer = await vaultDialog({
2923
+ title: '导入分身',
2924
+ label: '选择导出包文件夹(包含 manifest.json 的那一层)',
2925
+ defaultValue: localStorage.getItem('fang.importDir') || '',
2926
+ })
2927
+ if (!answer?.value) return
2928
+ const sourceDir = answer.value
2851
2929
  localStorage.setItem('fang.importDir', sourceDir)
2852
2930
  const result = await api('/fang/api/vault/import', { method: 'POST', body: JSON.stringify({ sourceDir }) })
2853
2931
  if (result.status === 200 && result.body?.ok) {
@@ -2867,9 +2945,29 @@ html[data-fang-overlays="hidden"] .fang-console .toast{display:none!important}
2867
2945
  // v3.7.4:打开是显式用户动作,用 POST 触发同步;GET 只读,避免副作用。
2868
2946
  const result = await api('/fang/api/tasks/open', { method: 'POST', body: JSON.stringify({ taskId }) })
2869
2947
  if (result.status === 200 && result.body?.url) {
2870
- try { window.open(result.body.url, '_blank', 'noopener'); return } catch { /* 弹层被拦 */ }
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 { /* 弹层被拦 */ }
2871
2956
  }
2872
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
+ }
2873
2971
  if (code === 'not-running') {
2874
2972
  notify('warn', '分身已停止,正在启动…')
2875
2973
  // 2026-11-22:服务端 restoreTask 直接接受 failed/archived 任务;不再“先归档再还原”。
@@ -3546,6 +3644,20 @@ html[data-fang-overlays="hidden"] .fang-console .toast{display:none!important}
3546
3644
  h('span', { class: 'fh-sub' }, '母体 × 分身 · 三区控制台'))),
3547
3645
  renderStats(S),
3548
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
+ : null,
3549
3661
  restart?.available && restart.redLineAutoAllowed
3550
3662
  ? chip('warn', '红灯自动放行', {
3551
3663
  title: 'strictRedLine=false:auto 授权模式下红灯可被策略自动放行。这只到决策层;execution.executed 恒为 false,真正重启仍由外部 supervisor 的 armed 清单决定。',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twinsearth/dsh-fang",
3
- "version": "3.7.6",
3
+ "version": "3.8.0",
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,17 +58,17 @@
58
58
  },
59
59
  "dependencies": {
60
60
  "@twinsearth/dsh-fang-node-compat": "^0.1.0",
61
- "@twinsearth/fang-dsh-plugin": "3.7.6"
62
- },
63
- "publishConfig": {
64
- "access": "public"
61
+ "@twinsearth/fang-dsh-plugin": "3.8.0"
65
62
  },
66
63
  "repository": {
67
64
  "type": "git",
68
- "url": "git+https://github.com/TwinsEarth/dsh-fang.git"
65
+ "url": "git+https://github.com/TwinsEarth/fang-dsh-plugin.git"
69
66
  },
70
- "homepage": "https://github.com/TwinsEarth/dsh-fang#readme",
67
+ "homepage": "https://github.com/TwinsEarth/fang-dsh-plugin#readme",
71
68
  "bugs": {
72
- "url": "https://github.com/TwinsEarth/dsh-fang/issues"
69
+ "url": "https://github.com/TwinsEarth/fang-dsh-plugin/issues"
70
+ },
71
+ "publishConfig": {
72
+ "access": "public"
73
73
  }
74
74
  }
@@ -131,7 +131,7 @@ export const AUDIT = {
131
131
  RUNTIME_ERROR: 'runtime-error',
132
132
  }
133
133
 
134
- export const FANG_VERSION = '3.7.6'
134
+ export const FANG_VERSION = '3.8.0'
135
135
 
136
136
  /**
137
137
  * @typedef {object} ForkInfo
@@ -0,0 +1,195 @@
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 } 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 function findBrowserPath(configured = '') {
21
+ const explicit = String(configured || '').trim()
22
+ if (explicit && fs.existsSync(explicit)) return explicit
23
+ for (const candidate of [...EDGE_CANDIDATES, ...CHROME_CANDIDATES]) if (fs.existsSync(candidate)) return candidate
24
+ return ''
25
+ }
26
+
27
+ export function isPidAlive(pid) {
28
+ const value = Number(pid)
29
+ if (!Number.isInteger(value) || value <= 0) return false
30
+ try { process.kill(value, 0); return true } catch { return false }
31
+ }
32
+
33
+ export async function freePort(start = 19300, end = 19400) {
34
+ for (let port = start; port <= end; port += 1) {
35
+ const ok = await new Promise((resolve) => {
36
+ const server = net.createServer()
37
+ server.once('error', () => resolve(false))
38
+ server.once('listening', () => server.close(() => resolve(true)))
39
+ server.listen(port, '127.0.0.1')
40
+ })
41
+ if (ok) return port
42
+ }
43
+ return 0
44
+ }
45
+
46
+ function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)) }
47
+
48
+ /** Launch an isolated app window and wait for its CDP endpoint. */
49
+ export async function launchManagedBrowser({ exe, url, profileDir, logDir, port, extraArgs = [] }) {
50
+ if (!exe || !fs.existsSync(exe)) return { ok: false, error: 'browser-unavailable' }
51
+ fs.mkdirSync(profileDir, { recursive: true })
52
+ fs.mkdirSync(logDir, { recursive: true })
53
+ const logFile = path.join(logDir, `browser-${Date.now()}.log`)
54
+ const crashDir = path.join(logDir, 'crash-dumps')
55
+ fs.mkdirSync(crashDir, { recursive: true })
56
+ const args = [
57
+ `--app=${url}`,
58
+ `--user-data-dir=${profileDir}`,
59
+ `--remote-debugging-port=${port}`,
60
+ '--remote-debugging-address=127.0.0.1',
61
+ '--no-first-run',
62
+ '--no-default-browser-check',
63
+ '--disable-sync',
64
+ '--disable-background-networking',
65
+ '--disable-features=msEdgeSyncConfirmation,msEdgeIdentity',
66
+ '--renderer-process-limit=1',
67
+ '--enable-logging',
68
+ `--log-file=${logFile}`,
69
+ '--enable-crash-reporter',
70
+ `--crash-dumps-dir=${crashDir}`,
71
+ '--js-flags=--max-old-space-size=2048',
72
+ ...extraArgs,
73
+ ]
74
+ let child
75
+ try {
76
+ child = spawn(exe, args, { detached: false, stdio: 'ignore', windowsHide: false })
77
+ } catch (error) {
78
+ return { ok: false, error: 'browser-spawn-failed', detail: String(error?.message ?? error) }
79
+ }
80
+ child.on('error', () => {})
81
+ child.unref?.()
82
+ const pid = Number(child.pid)
83
+ let ready = false
84
+ for (let i = 0; i < 40; i += 1) {
85
+ await sleep(250)
86
+ if (!isPidAlive(pid)) break
87
+ try {
88
+ const response = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1000) })
89
+ if (response.ok) { ready = true; break }
90
+ } catch { /* not ready */ }
91
+ }
92
+ if (!ready) {
93
+ try { await closeManagedBrowser({ pid, port }) } catch { /* ignore */ }
94
+ return { ok: false, error: 'browser-cdp-timeout', pid }
95
+ }
96
+ return { ok: true, pid, port, profileDir, logFile, crashDir, exe }
97
+ }
98
+
99
+ export async function closeManagedBrowser({ pid, port, timeoutMs = 3000 }) {
100
+ const value = Number(pid)
101
+ if (Number.isInteger(value) && value > 0) {
102
+ // Best-effort graceful close first; CDP Browser.close may be unavailable.
103
+ if (port) {
104
+ try {
105
+ await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(800) })
106
+ } catch { /* already gone */ }
107
+ }
108
+ if (process.platform === 'win32') {
109
+ try {
110
+ await new Promise((resolve) => {
111
+ const child = spawn('taskkill.exe', ['/PID', String(value), '/T', '/F'], { stdio: 'ignore', windowsHide: true })
112
+ child.once('exit', resolve)
113
+ child.once('error', resolve)
114
+ })
115
+ } catch { /* ignore */ }
116
+ } else {
117
+ try { process.kill(-value, 'SIGKILL') } catch { try { process.kill(value, 'SIGKILL') } catch { /* ignore */ } }
118
+ }
119
+ for (let i = 0; i < Math.ceil(timeoutMs / 100); i += 1) {
120
+ if (!isPidAlive(value)) break
121
+ await sleep(100)
122
+ }
123
+ }
124
+ return { ok: !isPidAlive(value) }
125
+ }
126
+
127
+ async function cdpTargets(port) {
128
+ try {
129
+ const response = await fetch(`http://127.0.0.1:${port}/json`, { signal: AbortSignal.timeout(1500) })
130
+ if (!response.ok) return []
131
+ const list = await response.json()
132
+ return Array.isArray(list) ? list.filter((item) => item.type === 'page' && item.webSocketDebuggerUrl) : []
133
+ } catch { return [] }
134
+ }
135
+
136
+ function cdpEvaluate(wsUrl, expression, timeoutMs = 2500) {
137
+ return new Promise((resolve) => {
138
+ let ws
139
+ let timer
140
+ try {
141
+ ws = new WebSocket(wsUrl)
142
+ } catch {
143
+ resolve(null)
144
+ return
145
+ }
146
+ const done = (value) => {
147
+ try { clearTimeout(timer) } catch { /* ignore */ }
148
+ try { ws?.close() } catch { /* ignore */ }
149
+ resolve(value)
150
+ }
151
+ timer = setTimeout(() => done(null), timeoutMs)
152
+ ws.addEventListener('open', () => {
153
+ try {
154
+ ws.send(JSON.stringify({ id: 1, method: 'Runtime.evaluate', params: { expression, returnByValue: true, awaitPromise: false } }))
155
+ } catch { done(null) }
156
+ })
157
+ ws.addEventListener('message', (event) => {
158
+ try {
159
+ const message = JSON.parse(String(event.data))
160
+ if (message.id !== 1) return
161
+ done(message.result?.result?.value ?? null)
162
+ } catch { done(null) }
163
+ })
164
+ ws.addEventListener('error', () => done(null))
165
+ ws.addEventListener('close', () => done(null))
166
+ })
167
+ }
168
+
169
+ /** Read DOM/heap/visibility from the managed page. */
170
+ /** Best-effort page flush before force-close; server-side session persistence is authoritative. */
171
+ export async function flushManagedBrowser(port) {
172
+ const targets = await cdpTargets(port)
173
+ if (!targets.length) return { ok: false, error: 'no-page' }
174
+ const target = targets[0]
175
+ await cdpEvaluate(target.webSocketDebuggerUrl, `(() => {
176
+ try { window.dispatchEvent(new Event('pagehide')); window.dispatchEvent(new Event('beforeunload')); } catch (e) {}
177
+ return true;
178
+ })()`, 1200)
179
+ return { ok: true }
180
+ }
181
+
182
+ export async function sampleManagedBrowser(port) {
183
+ const targets = await cdpTargets(port)
184
+ if (!targets.length) return { ok: false, error: 'browser-cdp-no-page' }
185
+ const target = targets.find((item) => item.url?.startsWith('http://127.0.0.1:')) ?? targets[0]
186
+ const value = await cdpEvaluate(target.webSocketDebuggerUrl, `(() => {
187
+ const perf = performance;
188
+ const heap = perf && perf.memory ? perf.memory.usedJSHeapSize : 0;
189
+ const nodes = document.getElementsByTagName('*').length;
190
+ const text = document.body && document.body.innerText ? document.body.innerText.length : 0;
191
+ return { visibility: document.visibilityState, heapBytes: heap, nodes, textLength: text, url: location.href };
192
+ })()`)
193
+ if (!value || typeof value !== 'object') return { ok: false, error: 'browser-cdp-evaluate-failed' }
194
+ return { ok: true, ...value }
195
+ }
@@ -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, 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'
@@ -190,6 +193,44 @@ export const Config = z.object({
190
193
  .description('官方源 Bearer token(可选;不会写进日志/状态)'),
191
194
  maxForks: z.number().min(1).max(64).default(8)
192
195
  .description('同时存活的任务/分身上限'),
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(30000)
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
+ browserDomNodeLimit: z.number().min(1000).max(10000000).default(200000)
225
+ .description('托管浏览器 DOM 节点上限,超过即关闭'),
226
+ autoCloseIdleMinutes: z.number().min(0).max(1440).default(10)
227
+ .description('浏览器页面隐藏超过该分钟数自动关闭(0=不关)'),
228
+ quarantineOnGuard: z.boolean().default(true)
229
+ .description('内存护栏触发后隔离任务,禁止自动重连'),
230
+ safeModeAfterCrash: z.boolean().default(true)
231
+ .description('上次宿主非正常退出时启动 Safe Mode,禁止自动恢复分身'),
232
+ autoRestoreForks: z.boolean().default(false)
233
+ .description('宿主启动时自动恢复上次运行的分身(默认关闭)'),
193
234
  motherProfile: z.string().default('')
194
235
  .description('母体 profile 名;留空 = 当前 profile(分身模板来源)'),
195
236
  profileTemplate: z.string().default('')
@@ -484,6 +525,85 @@ export function apply(ctx, config) {
484
525
  }
485
526
  }
486
527
 
528
+ // v3.8.0: host crash latch. A previous host that did not write cleanShutdown
529
+ // means the last run died; enter Safe Mode unless explicitly disabled.
530
+ const safeModeFile = path.join(layout.dataDir, 'safe-mode.json')
531
+ const hostStateFile = path.join(layout.dataDir, 'host-state.json')
532
+ const readJsonFile = (file) => { try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return null } }
533
+ const previousHost = readJsonFile(hostStateFile)
534
+ const previousSafeMode = readJsonFile(safeModeFile)
535
+ const unclean = Boolean(previousHost && previousHost.clean !== true && Number(previousHost.pid) !== process.pid)
536
+ let safeMode = Boolean(previousSafeMode?.safeMode)
537
+ let safeModeReason = String(previousSafeMode?.reason ?? '')
538
+ if (unclean && cfg.safeModeAfterCrash === true && !safeMode) {
539
+ safeMode = true
540
+ safeModeReason = 'unclean-shutdown'
541
+ }
542
+ // A fresh host process is an explicit recovery boundary: clear per-task
543
+ // quarantine latches, but keep tokens revoked so the old page cannot reconnect.
544
+ let quarantineReset = 0
545
+ if (previousHost?.pid !== process.pid) {
546
+ for (const task of tasks.values()) {
547
+ if (!task.quarantined) continue
548
+ task.quarantineCleared = { at: nowMs(), reason: 'host-restart' }
549
+ task.quarantined = null
550
+ task.token = ''
551
+ task.url = ''
552
+ task.status = TASK_STATUS.FAILED
553
+ task.pid = null
554
+ task.port = null
555
+ quarantineReset += 1
556
+ }
557
+ if (quarantineReset) {
558
+ try { saveRegistry(layout.tasksFile, [...tasks.values()].map(task => ({ ...task, token: '', url: stripUrlToken(task.url) }))) } catch { /* best effort */ }
559
+ }
560
+ }
561
+ const persistSafeMode = () => {
562
+ try { fs.writeFileSync(safeModeFile, JSON.stringify({ safeMode, reason: safeModeReason, at: new Date().toISOString() }, null, 2)) } catch { /* best effort */ }
563
+ }
564
+ persistSafeMode()
565
+ try { fs.writeFileSync(hostStateFile, JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString(), clean: false }, null, 2)) } catch { /* best effort */ }
566
+ try {
567
+ ctx.effect(() => () => {
568
+ try { fs.writeFileSync(hostStateFile, JSON.stringify({ pid: process.pid, exitedAt: new Date().toISOString(), clean: true }, null, 2)) } catch { /* best effort */ }
569
+ try {
570
+ const prior = JSON.parse(fs.readFileSync(watchdogFile, 'utf8'))
571
+ fs.writeFileSync(watchdogFile, JSON.stringify({ ...prior, hostPid: process.pid, clean: true, at: new Date().toISOString() }, null, 2))
572
+ } catch { /* best effort */ }
573
+ })
574
+ } catch { /* fake ctx */ }
575
+
576
+ // v3.8.0 independent watchdog: a detached Node/Electron process cleans up
577
+ // managed browsers/fork trees if this host is force-killed. It never reads
578
+ // user data and acts only on PIDs written here.
579
+ const watchdogFile = path.join(layout.dataDir, `watchdog-${process.pid}.json`)
580
+ const writeWatchdog = () => {
581
+ const targets = []
582
+ for (const task of tasks.values()) {
583
+ if (task.browser?.pid) targets.push({ pid: Number(task.browser.pid), kind: 'browser', taskId: task.taskId })
584
+ if (task.pid && (task.status === TASK_STATUS.READY || task.status === TASK_STATUS.RUNNING)) targets.push({ pid: Number(task.pid), kind: 'fork', taskId: task.taskId })
585
+ }
586
+ try { fs.writeFileSync(watchdogFile, JSON.stringify({ hostPid: process.pid, clean: false, at: new Date().toISOString(), targets }, null, 2)) } catch { /* best effort */ }
587
+ }
588
+ writeWatchdog()
589
+ const testLike = Boolean(process.env.NODE_TEST_CONTEXT) || process.env.DSH_FANG_E2E === '1' || /(?:test|e2e)/i.test(String(process.argv[1] ?? ''))
590
+ const sidecarAlready = globalThis.__fangWatchdogSidecar === true
591
+ if (process.platform === 'win32' && process.env.DSH_FANG_DISABLE_SIDECAR !== '1' && !testLike && !sidecarAlready) {
592
+ globalThis.__fangWatchdogSidecar = true
593
+ try {
594
+ const sidecar = fileURLToPath(new URL('../lib/watchdog-sidecar.mjs', import.meta.url))
595
+ const child = spawn(process.execPath, [sidecar, watchdogFile], {
596
+ detached: true,
597
+ stdio: 'ignore',
598
+ windowsHide: true,
599
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
600
+ })
601
+ child.on('error', () => {})
602
+ child.unref()
603
+ } catch { /* sidecar is best effort; host watchdog remains */ }
604
+ }
605
+
606
+
487
607
  const safeGet = (key) => { try { return ctx.get(key) } catch { return undefined } }
488
608
  // v3.3.3: queue journal is an optional sub-plugin. Its host half provides
489
609
  // SERVICE.queueJournal; without it the journal/queue routes must fail closed
@@ -588,6 +708,267 @@ export function apply(ctx, config) {
588
708
  } catch { /* best effort */ }
589
709
  }
590
710
  const forker = () => safeGet(SERVICE.forker)
711
+
712
+ /** 2026-11-24: commit-memory guard before any new renderer/spawn. */
713
+ let pagefileWarned = false
714
+ const memoryGate = async (action) => {
715
+ if (cfg.memoryGuard !== true) return { ok: true, skipped: 'disabled' }
716
+ const memory = await readSystemMemory()
717
+ if (memory.ok === true && memory.hasPageFile === false && !pagefileWarned) {
718
+ pagefileWarned = true
719
+ audit('pagefile-missing', { action, commitLimitMB: memory.commitLimitMB, commitFreeMB: memory.commitFreeMB })
720
+ }
721
+ const decision = evaluateMemoryGuard(memory, { minFreeMB: cfg.memoryMinFreeMB })
722
+ if (decision.ok !== true) audit('fork-memory-low', { action, commitFreeMB: decision.commitFreeMB, minFreeMB: decision.minFreeMB })
723
+ return decision
724
+ }
725
+
726
+ /** Single-active-fork policy: stop other running forks before starting/opening one. */
727
+ const pauseOtherForks = async (currentId, reason = 'single-active-fork') => {
728
+ if (cfg.singleActiveFork !== true) return { ok: true, paused: [] }
729
+ const f = forker()
730
+ const paused = []
731
+ for (const [id, task] of tasks) {
732
+ if (id === currentId) continue
733
+ if (task.status !== TASK_STATUS.READY && task.status !== TASK_STATUS.RUNNING) continue
734
+ const live = f?.status?.(id)
735
+ if (!live?.running) continue
736
+ await closeTaskBrowser(task, reason)
737
+ try { f.stop?.(id) } catch { /* already gone */ }
738
+ task.status = TASK_STATUS.FAILED
739
+ task.pid = null
740
+ task.port = null
741
+ task.url = null
742
+ task.adapter = { ok: false, error: 'auto-paused-memory' }
743
+ task.memoryPaused = { reason, at: nowMs() }
744
+ paused.push(id)
745
+ audit('fork-auto-paused', { taskId: id, reason, by: currentId })
746
+ }
747
+ if (paused.length) persist()
748
+ return { ok: true, paused }
749
+ }
750
+
751
+ const memorySamples = new Map()
752
+
753
+ const closeTaskBrowser = async (task, reason = 'guard') => {
754
+ if (!task?.browser?.pid) return { ok: true, skipped: 'no-browser' }
755
+ const browser = task.browser
756
+ try { await flushManagedBrowser(browser.port) } catch { /* best effort */ }
757
+ const result = await closeManagedBrowser({ pid: browser.pid, port: browser.port })
758
+ task.browser = null
759
+ task.browserClosed = { at: nowMs(), reason, pid: browser.pid, ok: result.ok }
760
+ writeWatchdog()
761
+ try {
762
+ 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 }) + '\n')
763
+ } catch { /* diagnostics only */ }
764
+ audit('fork-browser-closed', { taskId: task.taskId, reason, pid: browser.pid, ok: result.ok })
765
+ persist()
766
+ return result
767
+ }
768
+
769
+ const quarantineTask = async (task, reason, { closeBrowser = true, stopFork = true } = {}) => {
770
+ if (!task) return { ok: false, error: 'unknown-task' }
771
+ if (closeBrowser) await closeTaskBrowser(task, reason)
772
+ if (stopFork) {
773
+ try { forker()?.stop?.(task.taskId) } catch { /* best effort */ }
774
+ }
775
+ task.status = TASK_STATUS.FAILED
776
+ task.pid = null
777
+ task.port = null
778
+ task.url = null
779
+ task.token = ''
780
+ task.adapter = { ok: false, error: 'fork-quarantined' }
781
+ task.quarantined = { reason, at: nowMs(), tokenRevoked: true }
782
+ audit('fork-quarantined', { taskId: task.taskId, reason })
783
+ persist()
784
+ return { ok: true, quarantined: true, taskId: task.taskId, reason }
785
+ }
786
+
787
+ const launchTaskBrowser = async (task, url) => {
788
+ if (cfg.managedBrowser !== true) return { ok: true, managed: false, url }
789
+ if (!task || !url) return { ok: false, error: 'browser-url-required' }
790
+ if (task.browser?.pid && isPidAlive(task.browser.pid)) {
791
+ return { ok: true, managed: true, pid: task.browser.pid, port: task.browser.port, reused: true }
792
+ }
793
+ const liveBrowsers = [...tasks.values()].filter((item) => item.browser?.pid && isPidAlive(item.browser.pid))
794
+ const max = Math.max(1, Number(cfg.maxOpenForkBrowsers) || 1)
795
+ let liveCount = liveBrowsers.length
796
+ for (const other of liveBrowsers) {
797
+ if (other.taskId === task.taskId) continue
798
+ if (liveCount < max) break
799
+ await closeTaskBrowser(other, 'max-open-fork-browsers')
800
+ liveCount -= 1
801
+ }
802
+ const exe = findBrowserPath(cfg.browserPath)
803
+ if (!exe) return { ok: false, error: 'browser-unavailable' }
804
+ const port = await freePort()
805
+ if (!port) return { ok: false, error: 'browser-port-unavailable' }
806
+ const profileDir = path.join(task.homeDir, 'browser-profile')
807
+ const logDir = path.join(task.homeDir, 'browser-logs')
808
+ const launched = await launchManagedBrowser({ exe, url, profileDir, logDir, port })
809
+ if (launched.ok !== true) {
810
+ audit('fork-browser-launch-failed', { taskId: task.taskId, error: launched.error, pid: launched.pid ?? null })
811
+ return launched
812
+ }
813
+ task.browser = {
814
+ pid: launched.pid, port: launched.port, profileDir, logFile: launched.logFile,
815
+ crashDir: launched.crashDir, exe, startedAt: nowMs(), hiddenSince: null, last: null,
816
+ }
817
+ writeWatchdog()
818
+ persist()
819
+ audit('fork-browser-opened', { taskId: task.taskId, pid: launched.pid, port: launched.port })
820
+ return { ok: true, managed: true, pid: launched.pid, port: launched.port }
821
+ }
822
+
823
+ let hostPanic = false
824
+ const hostEmergency = async (reason, { safe = false } = {}) => {
825
+ if (hostPanic) return { ok: true, skipped: 'in-progress' }
826
+ hostPanic = true
827
+ try {
828
+ // Order is deliberate: browser (largest commit) first, then fork backends.
829
+ for (const task of tasks.values()) {
830
+ if (task.browser?.pid) await closeTaskBrowser(task, `host-panic:${reason}`)
831
+ }
832
+ for (const task of tasks.values()) {
833
+ if (task.status === TASK_STATUS.READY || task.status === TASK_STATUS.RUNNING) {
834
+ await quarantineTask(task, `host-panic:${reason}`, { closeBrowser: false })
835
+ }
836
+ }
837
+ if (safe) {
838
+ safeMode = true
839
+ safeModeReason = `host-emergency:${reason}`
840
+ persistSafeMode()
841
+ }
842
+ audit('host-emergency-guard', { reason, safe, tasks: tasks.size })
843
+ return { ok: true, reason, safe }
844
+ } finally {
845
+ hostPanic = false
846
+ }
847
+ }
848
+
849
+ const recordForkMemory = async (task, rootPid, table) => {
850
+ const tree = sumProcessTree(selectProcessTree(table.rows, rootPid))
851
+ if (!tree.count) return null
852
+ const list = memorySamples.get(task.taskId) ?? []
853
+ list.push({ at: nowMs(), ...tree })
854
+ if (list.length > 40) list.splice(0, list.length - 40)
855
+ memorySamples.set(task.taskId, list)
856
+ try {
857
+ fs.appendFileSync(path.join(layout.dataDir, 'memory-samples.jsonl'), JSON.stringify({ taskId: task.taskId, at: nowMs(), ...tree }) + '\n')
858
+ } catch { /* diagnostics only */ }
859
+ const low = Math.min(...list.map((sample) => Number(sample.commitMB) || 0))
860
+ const current = Number(tree.commitMB) || 0
861
+ const overKill = current >= Number(cfg.memoryKillCommitMB)
862
+ const overGrowth = current - low >= Number(cfg.memoryGrowCommitMB)
863
+ if (overKill && overGrowth) {
864
+ try { forker()?.stop?.(task.taskId) } catch { /* best effort */ }
865
+ try { await killProcessTree(rootPid) } catch { /* PID may already be gone */ }
866
+ task.status = TASK_STATUS.FAILED
867
+ task.pid = null
868
+ task.port = null
869
+ task.url = null
870
+ task.adapter = { ok: false, error: 'memory-watchdog-killed' }
871
+ task.memoryKill = { at: nowMs(), commitMB: current, lowMB: low, pids: tree.pids }
872
+ audit('fork-memory-killed', { taskId: task.taskId, commitMB: current, lowMB: low, pids: tree.pids })
873
+ persist()
874
+ return { ...tree, killed: true }
875
+ }
876
+ return tree
877
+ }
878
+
879
+ const browserWatchdogTick = async (table) => {
880
+ if (cfg.managedBrowser !== true || process.platform !== 'win32') return
881
+ for (const task of tasks.values()) {
882
+ const browser = task.browser
883
+ if (!browser?.pid) continue
884
+ if (!isPidAlive(browser.pid)) {
885
+ task.browser = null
886
+ task.browserClosed = { at: nowMs(), reason: 'browser-process-exited', pid: browser.pid }
887
+ audit('fork-browser-exited', { taskId: task.taskId, pid: browser.pid })
888
+ persist()
889
+ continue
890
+ }
891
+ const tree = sumProcessTree(selectProcessTree(table.rows, browser.pid))
892
+ const sample = await sampleManagedBrowser(browser.port)
893
+ const nodes = Number(sample?.nodes) || 0
894
+ const heapMB = Math.round((Number(sample?.heapBytes) || 0) / 1048576)
895
+ browser.last = { at: nowMs(), ...tree, nodes, heapMB, visibility: sample?.visibility ?? 'unknown' }
896
+ try {
897
+ fs.appendFileSync(path.join(layout.dataDir, 'browser-samples.jsonl'), JSON.stringify({ taskId: task.taskId, ...browser.last }) + '\n')
898
+ } catch { /* diagnostics only */ }
899
+ const overMemory = Number(tree.commitMB) >= Number(cfg.browserMemoryLimitMB)
900
+ const overDom = nodes >= Number(cfg.browserDomNodeLimit)
901
+ if (overMemory || overDom) {
902
+ audit('fork-browser-memory-guard', { taskId: task.taskId, commitMB: tree.commitMB, nodes, heapMB, overMemory, overDom })
903
+ await quarantineTask(task, overMemory ? 'browser-memory-limit' : 'browser-dom-limit')
904
+ continue
905
+ }
906
+ if (cfg.autoCloseIdleMinutes > 0) {
907
+ if (sample?.ok === true && sample.visibility === 'hidden') {
908
+ if (!browser.hiddenSince) browser.hiddenSince = nowMs()
909
+ const idleMs = nowMs() - Number(browser.hiddenSince)
910
+ if (idleMs >= Number(cfg.autoCloseIdleMinutes) * 60_000) {
911
+ await closeTaskBrowser(task, 'idle-hidden')
912
+ continue
913
+ }
914
+ } else if (sample?.ok === true) {
915
+ browser.hiddenSince = null
916
+ }
917
+ }
918
+ }
919
+ }
920
+
921
+ const memoryWatchdogTick = async () => {
922
+ if (cfg.memoryWatchdog !== true || process.platform !== 'win32') return
923
+ const running = [...tasks.values()].filter((task) => task.status === TASK_STATUS.READY || task.status === TASK_STATUS.RUNNING)
924
+ const hasBrowser = [...tasks.values()].some((task) => task.browser?.pid)
925
+ if (!running.length && !hasBrowser) return
926
+ const table = await readProcessTable()
927
+ if (!table.ok) return
928
+ for (const task of running) {
929
+ const rootPid = Number(forker()?.status?.(task.taskId)?.pid ?? task.pid)
930
+ if (rootPid > 0) await recordForkMemory(task, rootPid, table)
931
+ }
932
+ await browserWatchdogTick(table)
933
+ writeWatchdog()
934
+ }
935
+
936
+ let lastHostWarnAt = 0
937
+ const hostWatchdogTick = async () => {
938
+ if (process.platform !== 'win32' || hostPanic) return
939
+ const memory = await readSystemMemory()
940
+ if (!memory.ok) return
941
+ const free = Number(memory.commitFreeMB) || 0
942
+ if (free < Number(cfg.hostWarnFreeMB) && nowMs() - lastHostWarnAt > 60_000) {
943
+ lastHostWarnAt = nowMs()
944
+ audit('host-memory-warning', { commitFreeMB: free, warnMB: cfg.hostWarnFreeMB })
945
+ }
946
+ if (free < Number(cfg.hostCriticalFreeMB)) {
947
+ await hostEmergency('commit-free-critical', { safe: true })
948
+ }
949
+ }
950
+
951
+
952
+ const cleanupOrphanForks = async () => {
953
+ if (process.platform !== 'win32') return { ok: true, killed: [] }
954
+ const table = await readProcessTable()
955
+ if (!table.ok) return { ok: false, killed: [], error: table.error }
956
+ const killed = []
957
+ for (const task of tasks.values()) {
958
+ if (task.status !== TASK_STATUS.ARCHIVED && task.status !== TASK_STATUS.FAILED) continue
959
+ const rootPid = Number(task.pid)
960
+ if (!(rootPid > 0)) continue
961
+ const tree = selectProcessTree(table.rows, rootPid)
962
+ if (!tree.length) continue
963
+ const marker = String(task.taskId)
964
+ const looksLikeFork = tree.some((row) => row.commandLine.includes(marker) || (task.profile && row.commandLine.includes(String(task.profile))))
965
+ if (!looksLikeFork) continue
966
+ const result = await killProcessTree(rootPid)
967
+ if (result.ok) { killed.push(task.taskId); audit('fork-orphan-killed', { taskId: task.taskId, pid: rootPid }) }
968
+ }
969
+ return { ok: true, killed }
970
+ }
971
+
591
972
  const cliPath = () => (cfg.cliPath ? cfg.cliPath : resolveCliPath('', process.env))
592
973
  const forkTempEnv = (taskId) => {
593
974
  const tmp = path.join(layout.forkHomesDir, String(taskId), 'tmp')
@@ -1068,6 +1449,7 @@ export function apply(ctx, config) {
1068
1449
 
1069
1450
  /** v2 主入口:派生一个任务(= 一个分身)。 */
1070
1451
  async createTask(input = {}) {
1452
+ if (safeMode) return { ok: false, error: 'safe-mode', detail: safeModeReason || 'host-safe-mode' }
1071
1453
  const title = String(input.title ?? input.taskTitle ?? '').trim() || `任务 ${tasks.size + 1}`
1072
1454
  const running = [...tasks.values()].filter(t => {
1073
1455
  const s = taskView(t).status
@@ -1084,6 +1466,9 @@ export function apply(ctx, config) {
1084
1466
  const taskId = newId('task')
1085
1467
  const profile = `fang-${taskId.replace(/^task_/, '').slice(0, 12)}`
1086
1468
  const homeDir = path.join(layout.forkHomesDir, taskId)
1469
+ const memory = await memoryGate('create-fork')
1470
+ if (memory.ok !== true) return { ok: false, taskId, ...memory }
1471
+ const paused = await pauseOtherForks(taskId, 'create-fork')
1087
1472
  const template = String(input.template ?? '').trim()
1088
1473
  // v3.0.9:从原身派生时,模板来源是该原身的 merged/profile(分身只生产,不回写原身)。
1089
1474
  // v3.0.9:未指定来源时,若存在“默认元宝”,快速派生直接以它为模板(新用户小白路径)。
@@ -1868,6 +2253,7 @@ export function apply(ctx, config) {
1868
2253
  }
1869
2254
  const deadline = nowMs() + cfg.archiveStopTimeoutMs
1870
2255
  let alive = true
2256
+ await closeTaskBrowser(task, 'archive')
1871
2257
  while (nowMs() < deadline) {
1872
2258
  alive = typeof f.alive === 'function' ? !!f.alive(id) : !!(f.status?.(id)?.running)
1873
2259
  if (!alive) break
@@ -1963,8 +2349,12 @@ export function apply(ctx, config) {
1963
2349
  const id = String(taskId ?? '')
1964
2350
  const task = tasks.get(id)
1965
2351
  if (!task) return { ok: false, error: 'unknown-task' }
2352
+ if (safeMode) return { ok: false, taskId: id, error: 'safe-mode', detail: safeModeReason || 'host-safe-mode' }
1966
2353
  const f = forker()
1967
2354
  if (!f || typeof f.spawn !== 'function') return { ok: false, error: 'forker-unavailable', taskId: id }
2355
+ const memory = await memoryGate('restore-fork')
2356
+ if (memory.ok !== true) return { ok: false, taskId: id, ...memory }
2357
+ const paused = await pauseOtherForks(id, 'restore-fork')
1968
2358
  // 2026-11-22:任务可能停在 ready/running,但子进程已经死了(宿主重启、手动 kill、
1969
2359
  // 端口丢失)。客户端「启动」仍会调用 restore;旧逻辑返回 not-archived,导致
1970
2360
  // 真机界面一直显示“启动失败”。这里允许恢复 stale 的 ready/running。
@@ -2065,7 +2455,11 @@ export function apply(ctx, config) {
2065
2455
  persist()
2066
2456
  audit(AUDIT.TASK_RESTORED, { taskId: id, ok: true, adapter })
2067
2457
  bus.emit('fang/task-restored', { taskId: id, url: task.url, port: task.port })
2068
- return { ok: true, restored: true, taskId: id, title: task.title, url: task.url, port: task.port, adapter, configReset, sessionGuard }
2458
+ if (task.quarantined) {
2459
+ task.quarantined = null
2460
+ audit('fork-quarantine-cleared', { taskId: id, by: 'restore' })
2461
+ }
2462
+ return { ok: true, restored: true, taskId: id, title: task.title, url: task.url, port: task.port, adapter, configReset, sessionGuard, paused }
2069
2463
  },
2070
2464
 
2071
2465
  /**
@@ -2077,6 +2471,11 @@ export function apply(ctx, config) {
2077
2471
  const id = String(taskId ?? '')
2078
2472
  const task = tasks.get(id)
2079
2473
  if (!task) return { ok: false, error: 'unknown-task' }
2474
+ if (safeMode) return { ok: false, taskId: id, error: 'safe-mode', detail: safeModeReason || 'host-safe-mode' }
2475
+ if (task.quarantined) return { ok: false, taskId: id, error: 'fork-quarantined', detail: task.quarantined.reason ?? 'guard' }
2476
+ const memory = await memoryGate('open-fork')
2477
+ if (memory.ok !== true) return { ok: false, taskId: id, ...memory }
2478
+ const paused = await pauseOtherForks(id, 'open-fork')
2080
2479
  const sourceId = String(task.essenceId || task.syncSourceId || OFFICIAL_ESSENCE_ID)
2081
2480
  captureEssenceRuntimeIfPresent(sourceId)
2082
2481
  if (sourceId === OFFICIAL_ESSENCE_ID) await repairOfficialEssenceNow()
@@ -2094,15 +2493,15 @@ export function apply(ctx, config) {
2094
2493
  task.url = null
2095
2494
  persist()
2096
2495
  const restored = await service.restoreTask(id)
2097
- return { ...restored, synced: true, restarted: true, sourceFingerprint: fingerprint }
2496
+ return { ...restored, synced: true, restarted: true, sourceFingerprint: fingerprint, paused }
2098
2497
  }
2099
2498
  if (task.status === TASK_STATUS.FAILED) {
2100
2499
  const restored = await service.restoreTask(id)
2101
- return { ...restored, synced: true, restarted: true, sourceFingerprint: fingerprint }
2500
+ return { ...restored, synced: true, restarted: true, sourceFingerprint: fingerprint, paused }
2102
2501
  }
2103
2502
  const out = forker()?.openUrl?.(id) ?? null
2104
2503
  if (!out || out.ok !== true) return { ok: false, error: out?.error ?? 'not-running' }
2105
- return { ...out, synced: true, restarted: false, sourceFingerprint: fingerprint }
2504
+ return { ...out, synced: true, restarted: false, sourceFingerprint: fingerprint, paused }
2106
2505
  },
2107
2506
 
2108
2507
  /**
@@ -2413,6 +2812,20 @@ export function apply(ctx, config) {
2413
2812
  }
2414
2813
 
2415
2814
  ctx.effect(() => ctx.provide(SERVICE.orchestrator, service))
2815
+ // 2026-11-24: sample fork PID trees/commit; kill only the offending fork.
2816
+ if (cfg.memoryWatchdog === true && process.platform === 'win32') {
2817
+ const timer = setInterval(() => { void memoryWatchdogTick() }, cfg.memoryWatchIntervalMs)
2818
+ timer.unref?.()
2819
+ try { ctx.effect(() => () => clearInterval(timer)) } catch { /* fake ctx */ }
2820
+ }
2821
+ // v3.8.0: host self-preservation. This must run even when no fork is running.
2822
+ if (process.platform === 'win32') {
2823
+ const timer = setInterval(() => { void hostWatchdogTick() }, 5000)
2824
+ timer.unref?.()
2825
+ try { ctx.effect(() => () => clearInterval(timer)) } catch { /* fake ctx */ }
2826
+ }
2827
+ // Startup: reclaim archived/failed fork processes whose recorded PID still lives.
2828
+ void cleanupOrphanForks()
2416
2829
  // v3.3.8:启动后异步自愈默认元主;不阻塞 boot,不 unref 也不会阻止退出。
2417
2830
  {
2418
2831
  const timer = setTimeout(() => { void refreshStaleDefaultEssenceIfNeeded() }, 1500)
@@ -3512,6 +3925,9 @@ export function apply(ctx, config) {
3512
3925
  }
3513
3926
  // 先导入选中的进行中会话,再拉起实例(实例启动时就能看到它们)。
3514
3927
  const importedSessions = importSessionsInto(homeDir, input?.sessionIds)
3928
+ const memory = await memoryGate('start-essence-runtime')
3929
+ if (memory.ok !== true) return { ok: false, error: memory.error, taskId: forkId, ...memory }
3930
+ const paused = await pauseOtherForks(forkId, 'start-essence-runtime')
3515
3931
  // 注意:forker.spawn 需要显式 homeDir/profile(它不从 provision 记录里猜)。
3516
3932
  const started = await f.spawn({
3517
3933
  forkId,
@@ -3545,6 +3961,26 @@ export function apply(ctx, config) {
3545
3961
  capture,
3546
3962
  }
3547
3963
  },
3964
+
3965
+ openManagedBrowser: async (taskId, url) => {
3966
+ const task = tasks.get(String(taskId ?? ''))
3967
+ if (!task) return { ok: false, error: 'unknown-task' }
3968
+ if (task.quarantined) return { ok: false, error: 'fork-quarantined', detail: task.quarantined.reason ?? 'guard' }
3969
+ return launchTaskBrowser(task, String(url ?? task.url ?? ''))
3970
+ },
3971
+ closeManagedBrowser: async (taskId, reason = 'user') => {
3972
+ const task = tasks.get(String(taskId ?? ''))
3973
+ if (!task) return { ok: false, error: 'unknown-task' }
3974
+ return closeTaskBrowser(task, reason)
3975
+ },
3976
+ safeModeStatus: () => ({ ok: true, safeMode, reason: safeModeReason }),
3977
+ resetSafeMode: () => {
3978
+ safeMode = false
3979
+ safeModeReason = ''
3980
+ persistSafeMode()
3981
+ audit('host-safe-mode-reset', {})
3982
+ return { ok: true, safeMode: false }
3983
+ },
3548
3984
  stopEssenceRuntime: async (essenceId) => {
3549
3985
  const id = String(essenceId ?? '').trim()
3550
3986
  const f = forker()
@@ -4653,6 +5089,9 @@ export function apply(ctx, config) {
4653
5089
  const taskId = String(query.get('taskId') ?? '').trim()
4654
5090
  if (!taskId) return json(res, 400, { ok: false, error: 'taskId-required' })
4655
5091
  if (!tasks.has(taskId)) return json(res, 404, { ok: false, error: 'unknown-task', taskId })
5092
+ if (safeMode) return json(res, 423, { ok: false, error: 'safe-mode', detail: safeModeReason })
5093
+ const guardTask = tasks.get(taskId)
5094
+ if (guardTask?.quarantined) return json(res, 423, { ok: false, error: 'fork-quarantined', detail: guardTask.quarantined.reason ?? 'guard' })
4656
5095
  const out = forker()?.openUrl?.(taskId) ?? null
4657
5096
  if (!out || out.ok !== true) return json(res, 404, { ok: false, error: out?.error ?? 'not-running', taskId })
4658
5097
  return json(res, 200, out)
@@ -4664,10 +5103,21 @@ export function apply(ctx, config) {
4664
5103
  if (!tasks.has(taskId)) return json(res, 404, { ok: false, error: 'unknown-task', taskId })
4665
5104
  const out = await service.syncTaskOnOpen(taskId)
4666
5105
  if (!out || out.ok !== true) {
4667
- const status = out?.error === 'unknown-task' ? 404 : out?.error === 'not-running' ? 404 : 409
5106
+ const status = out?.error === 'unknown-task' ? 404 : out?.error === 'not-running' ? 404 : out?.error === 'safe-mode' || out?.error === 'fork-quarantined' ? 423 : 409
4668
5107
  return json(res, status, { ok: false, error: out?.error ?? 'not-running', ...out })
4669
5108
  }
4670
- return json(res, 200, out)
5109
+ let managed = { ok: true, managed: false }
5110
+ if (out.url) {
5111
+ const browser = await service.openManagedBrowser(taskId, out.url)
5112
+ if (browser?.ok === true) managed = browser
5113
+ else managed = { ok: true, managed: false, browserError: browser?.error ?? 'browser-unavailable' }
5114
+ }
5115
+ return json(res, 200, { ...out, ...managed })
5116
+ })
5117
+ route('GET', `${prefix}/api/safe-mode`, async (req, res) => json(res, 200, service.safeModeStatus()))
5118
+ route('POST', `${prefix}/api/safe-mode/reset`, async (req, res) => {
5119
+ await readBody(req)
5120
+ return json(res, 200, service.resetSafeMode())
4671
5121
  })
4672
5122
  route('POST', `${prefix}/api/tasks/archive`, async (req, res) => {
4673
5123
  const body = await readBody(req)
@@ -4677,7 +5127,8 @@ export function apply(ctx, config) {
4677
5127
  route('POST', `${prefix}/api/tasks/restore`, async (req, res) => {
4678
5128
  const body = await readBody(req)
4679
5129
  const out = await service.restoreTask(String(body?.taskId ?? ''))
4680
- return json(res, out.ok ? 200 : 409, out)
5130
+ const status = out.ok ? 200 : out?.error === 'safe-mode' ? 423 : out?.error === 'fork-quarantined' ? 423 : 409
5131
+ return json(res, status, out)
4681
5132
  })
4682
5133
  // 2026-11-22:一键修复(停残留 → 清别名桩 → 重置配置 → 重新拉起;不删 home/会话)
4683
5134
  route('POST', `${prefix}/api/vault/export`, async (req, res) => {