@twinsearth/ai-prison-dsh-plugin 1.6.1 → 1.7.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/CHANGELOG.md +64 -0
- package/README.md +56 -10
- package/client.js +51 -4
- package/cordis.patch.yml +15 -7
- package/docs/preview.svg +64 -28
- package/lib/api.js +60 -3
- package/lib/boot-watch.js +4 -2
- package/lib/harness.js +9 -0
- package/lib/remediation.js +3 -2
- package/lib/rss-scan.js +29 -20
- package/lib/tamper-monitor.js +18 -7
- package/lib/tools.js +2 -0
- package/lib/watchdog-api.js +86 -0
- package/lib/watchdog-budget.js +116 -0
- package/lib/watchdog-core.js +95 -0
- package/lib/watchdog-crash.js +117 -0
- package/lib/watchdog-enforcement.js +211 -0
- package/lib/watchdog-persistence.js +124 -0
- package/lib/watchdog-policy.js +50 -6
- package/lib/watchdog-runtime.js +127 -867
- package/lib/watchdog-sampler.js +85 -0
- package/lib/watchdog-snapshot.js +95 -0
- package/lib/watchdog-state.js +5 -3
- package/locale/en.json +2 -23
- package/locale/zh.json +2 -23
- package/package.json +3 -2
- package/watchdog.js +11 -5
package/lib/rss-scan.js
CHANGED
|
@@ -8,11 +8,38 @@ import { RSS_QUERY_SCRIPT, parseProcessList } from './rss.js'
|
|
|
8
8
|
* falls back to a direct spawn. Failures are recorded on the watchdog state and
|
|
9
9
|
* reported once per run instead of silently producing an empty Top5.
|
|
10
10
|
*/
|
|
11
|
+
/**
|
|
12
|
+
* Run the process-list query through the Host subprocess service (collected
|
|
13
|
+
* stdout + abort signal + grace). Exported separately so the provider contract
|
|
14
|
+
* can be tested on every platform, not only where the periodic scanner runs.
|
|
15
|
+
*/
|
|
16
|
+
export async function scanViaService(serviceInstance, { profileDir = process.cwd(), timeoutMs = 20_000 } = {}) {
|
|
17
|
+
const controller = new AbortController()
|
|
18
|
+
const abortTimer = setTimeout(() => controller.abort(), timeoutMs)
|
|
19
|
+
if (typeof abortTimer.unref === 'function') abortTimer.unref()
|
|
20
|
+
try {
|
|
21
|
+
const handle = serviceInstance.spawn({
|
|
22
|
+
argv: ['powershell.exe', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', RSS_QUERY_SCRIPT],
|
|
23
|
+
cwd: profileDir,
|
|
24
|
+
stdio: { stdin: 'ignore', stdout: { maxBytes: 4 * 1024 * 1024 }, stderr: { maxBytes: 64 * 1024 } },
|
|
25
|
+
graceMs: 5000,
|
|
26
|
+
signal: controller.signal,
|
|
27
|
+
})
|
|
28
|
+
await handle.done
|
|
29
|
+
const stdout = handle.collected.stdout ? handle.collected.stdout.readFrom(0).text : ''
|
|
30
|
+
const stderr = handle.collected.stderr ? handle.collected.stderr.readFrom(0).text : ''
|
|
31
|
+
if (!stdout) throw new Error('subprocess service returned no stdout' + (stderr ? ': ' + stderr.slice(0, 300) : ''))
|
|
32
|
+
return { stdout }
|
|
33
|
+
} finally {
|
|
34
|
+
clearTimeout(abortTimer)
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
11
38
|
const INTERVAL_MS = 60_000
|
|
12
39
|
|
|
13
40
|
export function startRssScannerV2({ ctx, refs, profileDir, watchdogState, appendIncident, exemptTargets, spawn = defaultSpawn }) {
|
|
14
41
|
if (process.platform !== 'win32') return undefined
|
|
15
|
-
if (watchdogState.config
|
|
42
|
+
if (!watchdogState.config || watchdogState.config.rssScan !== true) return undefined
|
|
16
43
|
if (refs.rssStarted) return undefined
|
|
17
44
|
refs.rssStarted = true
|
|
18
45
|
let scanning = false
|
|
@@ -47,25 +74,7 @@ export function startRssScannerV2({ ctx, refs, profileDir, watchdogState, append
|
|
|
47
74
|
}
|
|
48
75
|
|
|
49
76
|
async function viaService(serviceInstance) {
|
|
50
|
-
|
|
51
|
-
const abortTimer = setTimeout(() => controller.abort(), 20_000)
|
|
52
|
-
if (typeof abortTimer.unref === 'function') abortTimer.unref()
|
|
53
|
-
try {
|
|
54
|
-
const handle = serviceInstance.spawn({
|
|
55
|
-
argv: ['powershell.exe', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', RSS_QUERY_SCRIPT],
|
|
56
|
-
cwd: profileDir,
|
|
57
|
-
stdio: { stdin: 'ignore', stdout: { maxBytes: 4 * 1024 * 1024 }, stderr: { maxBytes: 64 * 1024 } },
|
|
58
|
-
graceMs: 5000,
|
|
59
|
-
signal: controller.signal,
|
|
60
|
-
})
|
|
61
|
-
await handle.done
|
|
62
|
-
const stdout = handle.collected.stdout ? handle.collected.stdout.readFrom(0).text : ''
|
|
63
|
-
const stderr = handle.collected.stderr ? handle.collected.stderr.readFrom(0).text : ''
|
|
64
|
-
if (!stdout) throw new Error('subprocess service returned no stdout' + (stderr ? ': ' + stderr.slice(0, 300) : ''))
|
|
65
|
-
return { stdout }
|
|
66
|
-
} finally {
|
|
67
|
-
clearTimeout(abortTimer)
|
|
68
|
-
}
|
|
77
|
+
return scanViaService(serviceInstance, { profileDir })
|
|
69
78
|
}
|
|
70
79
|
|
|
71
80
|
async function scan() {
|
package/lib/tamper-monitor.js
CHANGED
|
@@ -4,14 +4,24 @@ import crypto from 'node:crypto'
|
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Hash watch for the profile files a plugin must never change behind the plugin
|
|
7
|
-
* manager's back.
|
|
8
|
-
*
|
|
9
|
-
*
|
|
7
|
+
* manager's back.
|
|
8
|
+
*
|
|
9
|
+
* A drift outside a plugin-manager operation window is suspicious. The default
|
|
10
|
+
* policy is **observe**: the changed bytes are backed up as evidence and an
|
|
11
|
+
* incident fires, but the file is never rewritten. `alert` additionally treats
|
|
12
|
+
* the drift as a signal for the caller's enforcement path; `restore` is opt-in
|
|
13
|
+
* and is the only policy that writes the baseline bytes back to the profile.
|
|
10
14
|
*/
|
|
11
15
|
export const CRITICAL_FILES = ['package.json', 'cordis.patch.yml', 'cordis.yml', 'pnpm-workspace.yaml', 'pnpm-lock.yaml']
|
|
12
16
|
export const OPERATION_GRACE_MS = 4000
|
|
13
17
|
export const STARTUP_GRACE_MS = 15000
|
|
14
18
|
export const DEFAULT_INTERVAL_MS = 30000
|
|
19
|
+
export const TAMPER_POLICIES = Object.freeze(['observe', 'alert', 'restore'])
|
|
20
|
+
|
|
21
|
+
/** Unknown or missing policies must fail safe to observe (never rewrite files). */
|
|
22
|
+
export function normalizeTamperPolicy(value) {
|
|
23
|
+
return value === 'restore' || value === 'alert' ? value : 'observe'
|
|
24
|
+
}
|
|
15
25
|
|
|
16
26
|
export function sha256(buffer) {
|
|
17
27
|
return crypto.createHash('sha256').update(buffer).digest('hex')
|
|
@@ -106,7 +116,7 @@ export function restoreBaseline(profileDir, baselineContents, diffs) {
|
|
|
106
116
|
export function createTamperMonitor({
|
|
107
117
|
profileDir,
|
|
108
118
|
dataDir,
|
|
109
|
-
policy = '
|
|
119
|
+
policy = 'observe',
|
|
110
120
|
graceMs = STARTUP_GRACE_MS,
|
|
111
121
|
intervalMs = DEFAULT_INTERVAL_MS,
|
|
112
122
|
shouldIgnore,
|
|
@@ -114,13 +124,14 @@ export function createTamperMonitor({
|
|
|
114
124
|
onTamper,
|
|
115
125
|
log,
|
|
116
126
|
} = {}) {
|
|
127
|
+
const effectivePolicy = normalizeTamperPolicy(policy)
|
|
117
128
|
const base = snapshotCriticalFiles(profileDir)
|
|
118
129
|
let baseline = base
|
|
119
130
|
let baselineAt = Date.now()
|
|
120
131
|
let timer = null
|
|
121
132
|
const status = {
|
|
122
133
|
enabled: true,
|
|
123
|
-
policy,
|
|
134
|
+
policy: effectivePolicy,
|
|
124
135
|
files: base.files.map((entry) => entry.file),
|
|
125
136
|
baselineAt: new Date(baselineAt).toISOString(),
|
|
126
137
|
lastCheckAt: null,
|
|
@@ -156,7 +167,7 @@ export function createTamperMonitor({
|
|
|
156
167
|
return { ok: true, diffs: [], restored: [], skipped: status.skipped }
|
|
157
168
|
}
|
|
158
169
|
const backup = backupTampered(dataDir, profileDir, suspicious)
|
|
159
|
-
const restored =
|
|
170
|
+
const restored = effectivePolicy === 'restore' ? restoreBaseline(profileDir, baseline.contents, suspicious) : []
|
|
160
171
|
status.lastDiff = suspicious
|
|
161
172
|
status.restored = restored
|
|
162
173
|
status.incidents += 1
|
|
@@ -164,7 +175,7 @@ export function createTamperMonitor({
|
|
|
164
175
|
baseline = snapshotCriticalFiles(profileDir)
|
|
165
176
|
baselineAt = Date.now()
|
|
166
177
|
if (backup.length > 0 && typeof log === 'function') log(`tamper monitor: 备份到 ${backup.length} 个文件`)
|
|
167
|
-
if (typeof onTamper === 'function') onTamper({ diffs: suspicious, restored, policy, backup })
|
|
178
|
+
if (typeof onTamper === 'function') onTamper({ diffs: suspicious, restored, policy: effectivePolicy, backup })
|
|
168
179
|
return { ok: true, diffs, restored, backup }
|
|
169
180
|
}
|
|
170
181
|
|
package/lib/tools.js
CHANGED
|
@@ -216,6 +216,8 @@ export async function installTools({ ctx, config = {}, logger } = {}) {
|
|
|
216
216
|
tamper: snapshot.tamper,
|
|
217
217
|
boot: snapshot.boot,
|
|
218
218
|
heap6g: snapshot.heap6g,
|
|
219
|
+
heap6gRequest: snapshot.heap6gRequest,
|
|
220
|
+
pendingBoot: snapshot.pendingBoot,
|
|
219
221
|
rss: snapshot.rss,
|
|
220
222
|
rssAt: snapshot.rssAt,
|
|
221
223
|
rssError: snapshot.rssError,
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { PAUSE_GRACE_MS } from './watchdog-core.js'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* HTTP surface of the watchdog: the read-only status snapshot and the explicit
|
|
7
|
+
* panel actions (probe, release, close, confirm-pause, 6 GB heap request).
|
|
8
|
+
*
|
|
9
|
+
* Registered through `ctx.inject(['connection'])`; every action is driven by the
|
|
10
|
+
* panel and the response is JSON with `cache-control: no-store`.
|
|
11
|
+
*/
|
|
12
|
+
export function registerWatchdogApi({ ctx, watchdogState, getSnapshot, actions, logger }) {
|
|
13
|
+
try {
|
|
14
|
+
if (typeof ctx.inject !== 'function') return false
|
|
15
|
+
ctx.inject(['connection'], (child) => {
|
|
16
|
+
try {
|
|
17
|
+
child.effect(
|
|
18
|
+
() =>
|
|
19
|
+
child.connection.fetch.register({
|
|
20
|
+
path: '/api/ai-prison/watchdog/status',
|
|
21
|
+
methods: ['GET'],
|
|
22
|
+
requestBody: 'buffered',
|
|
23
|
+
fetch: async () => Response.json(getSnapshot(), { headers: { 'cache-control': 'no-store' } }),
|
|
24
|
+
}),
|
|
25
|
+
'ai-prison-watchdog: status api',
|
|
26
|
+
)
|
|
27
|
+
child.effect(
|
|
28
|
+
() =>
|
|
29
|
+
child.connection.fetch.register({
|
|
30
|
+
path: '/api/ai-prison/watchdog/action',
|
|
31
|
+
methods: ['POST'],
|
|
32
|
+
requestBody: 'buffered',
|
|
33
|
+
fetch: async (request) => {
|
|
34
|
+
let body = {}
|
|
35
|
+
try {
|
|
36
|
+
body = await request.json()
|
|
37
|
+
} catch {
|
|
38
|
+
body = {}
|
|
39
|
+
}
|
|
40
|
+
const action = typeof body.action === 'string' ? body.action : ''
|
|
41
|
+
const target = typeof body.target === 'string' ? body.target : ''
|
|
42
|
+
if (action === 'heap6g') {
|
|
43
|
+
const enabled = body.enabled === true
|
|
44
|
+
// The request lives inside the watchdog state directory; an
|
|
45
|
+
// external launcher is still required to act on it, and none
|
|
46
|
+
// ships with the plugin. Never write outside the profile.
|
|
47
|
+
const flagPath = path.join(watchdogState.dataDir || '', 'heap6g-request.json')
|
|
48
|
+
try {
|
|
49
|
+
if (enabled) fs.writeFileSync(flagPath, JSON.stringify({ enabled: true, at: new Date().toISOString(), consumer: 'external-launcher-required' }, null, 2) + '\n')
|
|
50
|
+
else fs.rmSync(flagPath, { force: true })
|
|
51
|
+
watchdogState.heap6g = enabled
|
|
52
|
+
actions.appendIncident({ kind: 'heap6g', detail: enabled ? '已记录 6GB 堆请求(需外部启动器消费;当前未安装)' : '已取消 6GB 堆请求' })
|
|
53
|
+
} catch (error) {
|
|
54
|
+
return Response.json({ ok: false, error: String((error && error.message) || error) }, { status: 500 })
|
|
55
|
+
}
|
|
56
|
+
return Response.json({ ok: true, enabled, consumer: 'external-launcher-required', requestFile: flagPath })
|
|
57
|
+
}
|
|
58
|
+
if (action === 'probe') {
|
|
59
|
+
const progress = await actions.scheduleProbe({ force: true })
|
|
60
|
+
return Response.json({ ok: true, progress })
|
|
61
|
+
}
|
|
62
|
+
if (action === 'confirm-pause') {
|
|
63
|
+
watchdogState.graceUntil = Date.now() + PAUSE_GRACE_MS
|
|
64
|
+
actions.appendIncident({ kind: 'pause-confirmed', detail: '用户二次确认继续插件操作(宽限 10 分钟)' })
|
|
65
|
+
return Response.json({ ok: true })
|
|
66
|
+
}
|
|
67
|
+
if (action === 'release') return Response.json(actions.releaseTarget(target))
|
|
68
|
+
if (action === 'close') {
|
|
69
|
+
const ok = await actions.disableTarget(target, 'manual-close')
|
|
70
|
+
return Response.json({ ok })
|
|
71
|
+
}
|
|
72
|
+
return Response.json({ ok: false, error: 'unknown action' }, { status: 400 })
|
|
73
|
+
},
|
|
74
|
+
}),
|
|
75
|
+
'ai-prison-watchdog: action api',
|
|
76
|
+
)
|
|
77
|
+
} catch (error) {
|
|
78
|
+
if (logger && typeof logger.warn === 'function') logger.warn('[ai-prison-watchdog] status api: ' + String((error && error.message) || error))
|
|
79
|
+
}
|
|
80
|
+
})
|
|
81
|
+
return true
|
|
82
|
+
} catch (error) {
|
|
83
|
+
if (logger && typeof logger.warn === 'function') logger.warn('[ai-prison-watchdog] connection inject: ' + String((error && error.message) || error))
|
|
84
|
+
return false
|
|
85
|
+
}
|
|
86
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { probeBudget } from './budget-probe.js'
|
|
2
|
+
import { remediationFor } from './remediation.js'
|
|
3
|
+
import { prunePluginState } from './watchdog-policy.js'
|
|
4
|
+
import { readJournalRecords } from './watchdog-core.js'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Per-plugin startup budget probes.
|
|
8
|
+
*
|
|
9
|
+
* A candidate is a non-exempt enabled bundle whose measured version is missing,
|
|
10
|
+
* stale, errored or older than the retry window. Probes run in a child process
|
|
11
|
+
* (`budget-probe.js` -> `budget-child.mjs`), one at a time, and only while the
|
|
12
|
+
* waterline is OK. A probe above the singleBlock threshold quarantines the
|
|
13
|
+
* plugin and writes a pending-boot plan.
|
|
14
|
+
*/
|
|
15
|
+
export function createBudget({ watchdogState, refs, profileDir, journalDir, exemptions, appendIncident, persist, enforcement, config }) {
|
|
16
|
+
const probeFn = typeof config.probe === 'function' ? config.probe : probeBudget
|
|
17
|
+
const probeMax = Number(config.probeMax) > 0 ? Number(config.probeMax) : 5
|
|
18
|
+
const probeRetryMs = Number(config.probeRetryMs) > 0 ? Number(config.probeRetryMs) : 10 * 60 * 1000
|
|
19
|
+
const probeMaxAgeMs = 7 * 24 * 3600 * 1000
|
|
20
|
+
|
|
21
|
+
function budgetState(name, version) {
|
|
22
|
+
const entry = watchdogState.budgets[name]
|
|
23
|
+
if (!entry) return 'missing'
|
|
24
|
+
if (entry.error) {
|
|
25
|
+
const age = Date.now() - Date.parse(entry.measuredAt || 0)
|
|
26
|
+
return age > probeRetryMs && (Number(entry.attempts) || 0) < 5 ? 'retry' : 'error'
|
|
27
|
+
}
|
|
28
|
+
if (entry.moduleLoadMB === undefined) return 'stale'
|
|
29
|
+
if (!entry.version || (version && entry.version !== version)) return 'stale'
|
|
30
|
+
if (Date.now() - Date.parse(entry.measuredAt || 0) > probeMaxAgeMs) return 'stale'
|
|
31
|
+
return 'ok'
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function probeOne(name, version) {
|
|
35
|
+
const previous = watchdogState.budgets[name] || {}
|
|
36
|
+
watchdogState.probeProgress = { ...(watchdogState.probeProgress || { done: 0, total: 0 }), current: name }
|
|
37
|
+
const result = await probeFn({ profileDir, packageName: name })
|
|
38
|
+
if (!result || !result.ok) {
|
|
39
|
+
watchdogState.budgets[name] = {
|
|
40
|
+
error: String((result && result.error) || 'probe-failed').slice(0, 300),
|
|
41
|
+
measuredAt: new Date().toISOString(),
|
|
42
|
+
version: version || previous.version || null,
|
|
43
|
+
attempts: (Number(previous.attempts) || 0) + 1,
|
|
44
|
+
source: 'module-load-probe',
|
|
45
|
+
}
|
|
46
|
+
persist(true)
|
|
47
|
+
return { ok: false }
|
|
48
|
+
}
|
|
49
|
+
watchdogState.budgets[name] = {
|
|
50
|
+
moduleLoadMB: result.moduleLoadMB,
|
|
51
|
+
rssMB: result.rssMB,
|
|
52
|
+
ms: result.ms,
|
|
53
|
+
measuredAt: new Date().toISOString(),
|
|
54
|
+
version: version || null,
|
|
55
|
+
attempts: (Number(previous.attempts) || 0) + 1,
|
|
56
|
+
source: 'module-load-probe',
|
|
57
|
+
}
|
|
58
|
+
const thresholds = watchdogState.thresholds
|
|
59
|
+
const mb = result.moduleLoadMB
|
|
60
|
+
if (thresholds && mb >= Math.round(thresholds.singleBlock / (1024 * 1024))) {
|
|
61
|
+
appendIncident({ kind: 'plugin-budget', target: name, level: 'block', detail: '启动实测 ' + mb + ' MB > 500 MB,禁止该插件' })
|
|
62
|
+
if (watchdogState.enforce) {
|
|
63
|
+
watchdogState.quarantine.set(name, { reason: 'budget', level: 'L1', at: new Date().toISOString(), release: 'manual', evidence: mb + ' MB > 500 MB', remediation: remediationFor('budget') })
|
|
64
|
+
void enforcement.disableTarget(name, 'budget-over-500MB')
|
|
65
|
+
enforcement.writePendingBoot({ level: 'L1', reason: 'budget', disable: [name], keep: [] })
|
|
66
|
+
}
|
|
67
|
+
} else if (thresholds && mb >= Math.round(thresholds.singleWarn / (1024 * 1024))) {
|
|
68
|
+
appendIncident({ kind: 'plugin-budget', target: name, level: 'warn', detail: '启动实测 ' + mb + ' MB > 300 MB,仅提醒' })
|
|
69
|
+
}
|
|
70
|
+
persist(true)
|
|
71
|
+
return { ok: true }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function scheduleProbe({ force = false } = {}) {
|
|
75
|
+
if (watchdogState.probeRunning) return watchdogState.probeProgress
|
|
76
|
+
const manager = refs.manager
|
|
77
|
+
if (!manager || typeof manager.listBundles !== 'function') return null
|
|
78
|
+
let rows
|
|
79
|
+
try {
|
|
80
|
+
rows = await manager.listBundles()
|
|
81
|
+
} catch {
|
|
82
|
+
return null
|
|
83
|
+
}
|
|
84
|
+
prunePluginState(watchdogState, rows)
|
|
85
|
+
const recent = new Set()
|
|
86
|
+
const cutoff = Date.now() - 30 * 60 * 1000
|
|
87
|
+
for (const record of readJournalRecords(journalDir)) {
|
|
88
|
+
const operation = record && record.operation
|
|
89
|
+
if (!operation || !operation.target) continue
|
|
90
|
+
if (operation.stage !== 'install' && operation.stage !== 'enable') continue
|
|
91
|
+
if (Date.parse(operation.time || 0) < cutoff) continue
|
|
92
|
+
recent.add(operation.target)
|
|
93
|
+
}
|
|
94
|
+
const candidates = rows
|
|
95
|
+
.filter((row) => row.enabled && !exemptions.has(row.name))
|
|
96
|
+
.map((row) => ({ name: row.name, version: row.version ? String(row.version) : '', state: budgetState(row.name, row.version ? String(row.version) : '') }))
|
|
97
|
+
.filter((candidate) => candidate.state !== 'ok')
|
|
98
|
+
.sort((a, b) => (recent.has(b.name) ? 1 : 0) - (recent.has(a.name) ? 1 : 0))
|
|
99
|
+
.slice(0, force ? Math.max(probeMax, Number(config.probeMaxForce) > 0 ? Number(config.probeMaxForce) : 15) : probeMax)
|
|
100
|
+
watchdogState.probeProgress = { done: 0, total: candidates.length, current: null, finishedAt: null }
|
|
101
|
+
if (candidates.length === 0) return watchdogState.probeProgress
|
|
102
|
+
watchdogState.probeRunning = true
|
|
103
|
+
for (const candidate of candidates) {
|
|
104
|
+
if (watchdogState.waterline !== 'ok') break
|
|
105
|
+
const outcome = await probeOne(candidate.name, candidate.version)
|
|
106
|
+
watchdogState.probeProgress = { ...watchdogState.probeProgress, done: watchdogState.probeProgress.done + 1, current: candidate.name, lastOk: Boolean(outcome && outcome.ok) }
|
|
107
|
+
if (candidates.length > 1) await new Promise((resolve) => setTimeout(resolve, Number(config.probeGapMs) >= 0 ? Number(config.probeGapMs) : 1500))
|
|
108
|
+
}
|
|
109
|
+
watchdogState.probeProgress = { ...watchdogState.probeProgress, current: null, finishedAt: new Date().toISOString() }
|
|
110
|
+
watchdogState.probeRunning = false
|
|
111
|
+
persist(true)
|
|
112
|
+
return watchdogState.probeProgress
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return { scheduleProbe }
|
|
116
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import os from 'node:os'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Shared constants, path resolution and low-level readers for the watchdog.
|
|
7
|
+
* Keeping them in one place lets the runtime, crash reader and budget probe
|
|
8
|
+
* agree on where DSH keeps its profile, logs and operation journal.
|
|
9
|
+
*/
|
|
10
|
+
export const SAMPLE_MS = 5_000
|
|
11
|
+
export const FLUSH_MS = 30_000
|
|
12
|
+
export const CRASH_HEAD_BYTES = 256 * 1024
|
|
13
|
+
export const BASELINE_DELAY_MS = 60_000
|
|
14
|
+
export const PAUSE_GRACE_MS = 10 * 60_000
|
|
15
|
+
export const CRASH_WINDOW_MS = 10 * 60_000
|
|
16
|
+
export const MAX_JOURNAL_RECORDS = 4000
|
|
17
|
+
|
|
18
|
+
/** Bundles the watchdog must never quarantine or disable. */
|
|
19
|
+
export const EXEMPT_TARGETS = new Set([
|
|
20
|
+
'dsh-base',
|
|
21
|
+
'dsh-web-app',
|
|
22
|
+
'@deepseek-ai/dsh-base',
|
|
23
|
+
'@deepseek-ai/dsh-web-app',
|
|
24
|
+
'@twinsearth/ai-prison-dsh-plugin',
|
|
25
|
+
])
|
|
26
|
+
|
|
27
|
+
export function resolveProfileDir() {
|
|
28
|
+
const fromEnv = typeof process.env.DSH_PROFILE_DIR === 'string' && process.env.DSH_PROFILE_DIR.trim()
|
|
29
|
+
if (fromEnv) return fromEnv
|
|
30
|
+
const name = typeof process.env.DSH_PROFILE === 'string' && process.env.DSH_PROFILE.trim() ? process.env.DSH_PROFILE.trim() : 'desktop'
|
|
31
|
+
return path.join(os.homedir(), '.dsh', 'profiles', name)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function resolveLogsDir() {
|
|
35
|
+
const roaming = process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming')
|
|
36
|
+
return path.join(roaming, '@deepseek-ai', 'dsh-desktop', 'logs')
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function resolveJournalDir() {
|
|
40
|
+
const roaming = process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming')
|
|
41
|
+
return path.join(roaming, '@deepseek-ai', 'dsh-desktop', 'plugin-operations')
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Read the first bytes of a file without loading the whole crash log. */
|
|
45
|
+
export function readHead(file, bytes) {
|
|
46
|
+
let fd
|
|
47
|
+
try {
|
|
48
|
+
fd = fs.openSync(file, 'r')
|
|
49
|
+
const buffer = Buffer.alloc(bytes)
|
|
50
|
+
const read = fs.readSync(fd, buffer, 0, bytes, 0)
|
|
51
|
+
return buffer.subarray(0, read).toString('utf8')
|
|
52
|
+
} catch {
|
|
53
|
+
return ''
|
|
54
|
+
} finally {
|
|
55
|
+
if (fd !== undefined) {
|
|
56
|
+
try {
|
|
57
|
+
fs.closeSync(fd)
|
|
58
|
+
} catch {
|
|
59
|
+
// ignore
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Last records of the plugin-manager operation journal (both files). */
|
|
66
|
+
export function readJournalRecords(journalDir) {
|
|
67
|
+
const records = []
|
|
68
|
+
for (const name of ['operations.jsonl', 'operations.previous.jsonl']) {
|
|
69
|
+
const file = path.join(journalDir, name)
|
|
70
|
+
let text = ''
|
|
71
|
+
try {
|
|
72
|
+
text = fs.readFileSync(file, 'utf8')
|
|
73
|
+
} catch {
|
|
74
|
+
continue
|
|
75
|
+
}
|
|
76
|
+
for (const line of text.split('\n').slice(-MAX_JOURNAL_RECORDS)) {
|
|
77
|
+
const trimmed = line.trim()
|
|
78
|
+
if (!trimmed) continue
|
|
79
|
+
try {
|
|
80
|
+
records.push(JSON.parse(trimmed))
|
|
81
|
+
} catch {
|
|
82
|
+
// ignore partial line
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return records
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Info/warn facade that tolerates a missing or partial cordis logger. */
|
|
90
|
+
export function createLogger(logger = {}) {
|
|
91
|
+
return {
|
|
92
|
+
info: (...args) => (typeof logger.info === 'function' ? logger.info(...args) : undefined),
|
|
93
|
+
warn: (...args) => (typeof logger.warn === 'function' ? logger.warn(...args) : undefined),
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { attributeCrash, diffBaseline, escalationLevel, parseCrashLog } from './watchdog-policy.js'
|
|
4
|
+
import { remediationFor } from './remediation.js'
|
|
5
|
+
import { CRASH_HEAD_BYTES, CRASH_WINDOW_MS, readHead, readJournalRecords } from './watchdog-core.js'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Crash-log ingestion and graded crash plans.
|
|
9
|
+
*
|
|
10
|
+
* Every new `crash-*-host.log` is parsed, attributed to the last changed plugin
|
|
11
|
+
* of that host run and turned into an L1-L3 plan. In enforce mode the plan is
|
|
12
|
+
* executed through the enforcement module (close/quarantine + pending-boot).
|
|
13
|
+
*/
|
|
14
|
+
export function createCrash({ watchdogState, logsDir, journalDir, refs, exemptions, appendIncident, persist, enforcement }) {
|
|
15
|
+
async function enforceCrashPlan(plan) {
|
|
16
|
+
if (!plan || !plan.target || watchdogState.crashFallback !== 'enforce') return
|
|
17
|
+
try {
|
|
18
|
+
watchdogState.quarantine.set(plan.target, { reason: 'crash', level: plan.level, at: new Date().toISOString(), release: 'manual', evidence: plan.reason, remediation: remediationFor('crash') })
|
|
19
|
+
const disabled = [plan.target].filter((target) => !exemptions.has(target))
|
|
20
|
+
await enforcement.disableTarget(plan.target, 'crash-' + plan.level)
|
|
21
|
+
let targets = [plan.target]
|
|
22
|
+
if (plan.level === 'L2' || plan.level === 'L3') {
|
|
23
|
+
const manager = refs.manager
|
|
24
|
+
const rows = manager && typeof manager.listBundles === 'function' ? await manager.listBundles() : []
|
|
25
|
+
const baselineNames = watchdogState.baseline ? watchdogState.baseline.bundles.map((row) => row.name) : []
|
|
26
|
+
targets = plan.level === 'L3'
|
|
27
|
+
? rows.filter((row) => row.enabled && !exemptions.has(row.name) && !baselineNames.includes(row.name)).map((row) => row.name)
|
|
28
|
+
: diffBaseline(rows, watchdogState.baseline).changed.map((row) => row.name).concat(plan.target)
|
|
29
|
+
disabled.push(...(await enforcement.disableMany(targets, 'crash-' + plan.level)))
|
|
30
|
+
}
|
|
31
|
+
enforcement.writePendingBoot({
|
|
32
|
+
level: plan.level,
|
|
33
|
+
reason: 'crash',
|
|
34
|
+
attribution: plan.target,
|
|
35
|
+
disable: [...new Set(targets)],
|
|
36
|
+
keep: watchdogState.baseline ? watchdogState.baseline.bundles.map((row) => row.name) : [],
|
|
37
|
+
})
|
|
38
|
+
appendIncident({ kind: 'crash-enforced', level: plan.level, target: plan.target, detail: '已按 ' + plan.level + ' 隔离 ' + disabled.length + ' 个目标(pending-boot.json 供外部包装器下次启动前使用)' })
|
|
39
|
+
persist(true)
|
|
40
|
+
} catch (error) {
|
|
41
|
+
watchdogState.degraded = 'crash enforce: ' + String((error && error.message) || error)
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function readCrashLogs() {
|
|
46
|
+
let entries
|
|
47
|
+
try {
|
|
48
|
+
entries = fs.readdirSync(logsDir, { withFileTypes: true })
|
|
49
|
+
} catch {
|
|
50
|
+
return
|
|
51
|
+
}
|
|
52
|
+
let newest = watchdogState.lastCrashScan
|
|
53
|
+
const crashes = []
|
|
54
|
+
for (const entry of entries) {
|
|
55
|
+
if (!entry.isFile() || !/^crash-.*-host\.log$/.test(entry.name)) continue
|
|
56
|
+
const file = path.join(logsDir, entry.name)
|
|
57
|
+
let stat
|
|
58
|
+
try {
|
|
59
|
+
stat = fs.statSync(file)
|
|
60
|
+
} catch {
|
|
61
|
+
continue
|
|
62
|
+
}
|
|
63
|
+
if (stat.mtimeMs <= watchdogState.lastCrashScan) continue
|
|
64
|
+
const text = readHead(file, CRASH_HEAD_BYTES)
|
|
65
|
+
const parsed = parseCrashLog(text)
|
|
66
|
+
if (!parsed.valid) continue
|
|
67
|
+
crashes.push({ file: entry.name, mtimeMs: stat.mtimeMs, parsed })
|
|
68
|
+
if (stat.mtimeMs > newest) newest = stat.mtimeMs
|
|
69
|
+
}
|
|
70
|
+
if (crashes.length === 0) return
|
|
71
|
+
const records = readJournalRecords(journalDir)
|
|
72
|
+
for (const crash of crashes) {
|
|
73
|
+
watchdogState.escalation.crashes.push(Date.now())
|
|
74
|
+
const recent = watchdogState.escalation.crashes.filter((at) => Date.now() - at <= CRASH_WINDOW_MS)
|
|
75
|
+
watchdogState.escalation.crashes = recent
|
|
76
|
+
const level = escalationLevel(recent.length)
|
|
77
|
+
watchdogState.escalation.level = level
|
|
78
|
+
const attribution = attributeCrash(records, crash.parsed)
|
|
79
|
+
watchdogState.hostRunId = crash.parsed.hostRunId || null
|
|
80
|
+
const plan = {
|
|
81
|
+
at: new Date().toISOString(),
|
|
82
|
+
level,
|
|
83
|
+
remediation: remediationFor('crash'),
|
|
84
|
+
crash: { file: crash.file, time: crash.parsed.time, phase: crash.parsed.phase, oom: crash.parsed.oom, hostExitCode: crash.parsed.hostExitCode },
|
|
85
|
+
hostRunId: crash.parsed.hostRunId,
|
|
86
|
+
target: attribution.picked ? attribution.picked.target : null,
|
|
87
|
+
inFlight: attribution.picked ? Boolean(attribution.picked.inFlight) : false,
|
|
88
|
+
evidence: attribution.candidates,
|
|
89
|
+
reason: attribution.reason,
|
|
90
|
+
applied: false,
|
|
91
|
+
}
|
|
92
|
+
watchdogState.plans.push(plan)
|
|
93
|
+
if (watchdogState.plans.length > 20) watchdogState.plans = watchdogState.plans.slice(-20)
|
|
94
|
+
appendIncident({
|
|
95
|
+
kind: 'crash',
|
|
96
|
+
file: crash.file,
|
|
97
|
+
time: crash.parsed.time,
|
|
98
|
+
phase: crash.parsed.phase,
|
|
99
|
+
hostExitCode: crash.parsed.hostExitCode,
|
|
100
|
+
oom: crash.parsed.oom,
|
|
101
|
+
level,
|
|
102
|
+
target: plan.target,
|
|
103
|
+
inFlight: plan.inFlight,
|
|
104
|
+
detail: plan.target
|
|
105
|
+
? `崩溃归因:${plan.target}${plan.inFlight ? '(崩溃时操作仍在途)' : ''};${watchdogState.enforce ? 'enforce' : 'dry-run'}`
|
|
106
|
+
: '崩溃归因失败:本 run 无安装/启用记录,不自动关闭',
|
|
107
|
+
})
|
|
108
|
+
if (watchdogState.enforce && watchdogState.crashFallback === 'enforce') void enforceCrashPlan(plan)
|
|
109
|
+
}
|
|
110
|
+
if (newest > watchdogState.lastCrashScan) {
|
|
111
|
+
watchdogState.lastCrashScan = newest
|
|
112
|
+
persist(true)
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return { readCrashLogs }
|
|
117
|
+
}
|