@twinsearth/ai-prison-dsh-plugin 1.2.1 → 1.4.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/CHANGELOG.md +70 -0
- package/client.js +65 -17
- package/lib/budget-probe.js +56 -0
- package/lib/tools.js +15 -2
- package/lib/watchdog-policy.js +149 -10
- package/lib/watchdog-runtime.js +491 -98
- package/lib/watchdog-state.js +37 -5
- package/locale/en.json +14 -1
- package/locale/zh.json +14 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,76 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `@twinsearth/ai-prison-dsh-plugin` are recorded here.
|
|
4
4
|
|
|
5
|
+
## [1.4.0] — 2026-11-18
|
|
6
|
+
|
|
7
|
+
### Added — P2 crash enforcement + per-plugin budgets, P3 external guard
|
|
8
|
+
|
|
9
|
+
- **Crash enforcement (requirement 3/4)**: `crashFallback` defaults to `enforce`
|
|
10
|
+
now. A crash attributed to a plugin quarantines it, disables it live, and with
|
|
11
|
+
L2/L3 also closes the bundles that exceed the clean baseline (L2) or everything
|
|
12
|
+
outside the baseline (L3, never below base + web-app). Plans persist in
|
|
13
|
+
`state.json`, a machine-readable `pending-boot.json` is written for the
|
|
14
|
+
external guard, and quarantined targets are re-disabled on the next boot.
|
|
15
|
+
- **Per-plugin startup budget (requirement 1)**: a new isolated probe
|
|
16
|
+
(`lib/budget-probe.js` + `lib/budget-child.mjs`) spawns the bundled Node with
|
|
17
|
+
`--expose-gc`, imports one plugin package from the profile and reports its
|
|
18
|
+
retained module-load delta. Plugins installed or enabled in the last 30 minutes
|
|
19
|
+
are probed automatically after boot (max 5, only at the `ok` waterline);
|
|
20
|
+
results land in `budgets` inside `state.json`. Above 500 MB the plugin is
|
|
21
|
+
quarantined and closed (pending the next boot for a hard block); above 300 MB
|
|
22
|
+
an incident is recorded.
|
|
23
|
+
- **External guard (P3)**: `E:ToFuture oolsaiprison-guard.ps1/.cmd` runs before
|
|
24
|
+
DSH, reads `pending-boot.json`, backs up the profile `package.json`, removes
|
|
25
|
+
the bundles that must stay closed (or keeps only the L3 baseline), and then
|
|
26
|
+
launches DSH. It is the only component that can break an import-phase crash
|
|
27
|
+
loop, where the in-process watchdog never runs.
|
|
28
|
+
|
|
29
|
+
### Fixed
|
|
30
|
+
- Watchdog probes keep the event loop alive no longer (timer `unref`), keeping
|
|
31
|
+
the test suite fast and the host responsive.
|
|
32
|
+
|
|
33
|
+
## [1.3.0] — 2026-11-18
|
|
34
|
+
## [1.3.0] — 2026-11-18
|
|
35
|
+
|
|
36
|
+
### Added — P1 enforcement (requirements 2, 3, 4 dry-run, 5)
|
|
37
|
+
|
|
38
|
+
- **Memory waterline enforcement**: warn 3 GB, pause 3.9 GB (needs a panel
|
|
39
|
+
second confirmation, 10-minute grace), strong warning 4 GB, freeze 5 GB on a
|
|
40
|
+
6 GB host. Thresholds stay cap-relative on a 4 GB host. Hysteresis keeps a
|
|
41
|
+
frozen host frozen until the heap drops below the block line minus 300 MB.
|
|
42
|
+
- **Hot-operation jail (requirement 2)**: `plugin-manager/operation` settled
|
|
43
|
+
records are counted per target (install/remove = 1, enable = 1, disable = 0.5,
|
|
44
|
+
failed/cancelled ignored, base bundles and the watchdog itself exempt). More
|
|
45
|
+
than five in one run auto-disables the target through
|
|
46
|
+
`pluginManager.setBundleEnabled`, quarantines it for the rest of the run and
|
|
47
|
+
audits every step. Quarantine is released by restart or by the panel
|
|
48
|
+
"Release" action; the agent-facing `plugin_manager` tool is denied while a
|
|
49
|
+
target is jailed.
|
|
50
|
+
- **Tool guard**: frozen/paused states deny mutating `plugin_manager` actions
|
|
51
|
+
with a reason (read-only actions stay allowed; the panel keeps release
|
|
52
|
+
actions for the Top5 close buttons).
|
|
53
|
+
- **Crash attribution (requirement 3, dry-run)**: new crash logs are parsed for
|
|
54
|
+
`hostRunId`; the plugin-operation journal is matched by that run id and the
|
|
55
|
+
last changed plugin is picked (in-flight install/enable first, then the latest
|
|
56
|
+
settled install, then the latest settled enable). The result is recorded as an
|
|
57
|
+
L1 plan and an incident; nothing is closed until the user confirms enforcement.
|
|
58
|
+
- **Baseline (requirement 4, dry-run)**: a clean run records its enabled bundle
|
|
59
|
+
set after 60 s without crashes, waterline trouble or quarantine; escalation
|
|
60
|
+
counters L1→L2→L3 persist across restarts.
|
|
61
|
+
- **Panel**: new "Enforcement" card shows the freeze banner, pause confirmation,
|
|
62
|
+
quarantine list with release buttons, the memory Top5 with "close now" buttons
|
|
63
|
+
and the latest dry-run crash plans.
|
|
64
|
+
- **Tool**: `ai_prison_watchdog_status` now reports enforcement state,
|
|
65
|
+
quarantine, Top5, plans and escalation.
|
|
66
|
+
|
|
67
|
+
### Notes
|
|
68
|
+
|
|
69
|
+
- Automatic disable only uses the plugin manager service; no profile file is
|
|
70
|
+
edited and no plugin code is loaded or unloaded by the watchdog.
|
|
71
|
+
- Top5 numbers are startup-budget + operation-delta estimates, labelled as such;
|
|
72
|
+
no heap snapshot is taken near the limit.
|
|
73
|
+
|
|
74
|
+
## [1.2.1] — 2026-11-18
|
|
5
75
|
## [1.2.1] — 2026-11-18
|
|
6
76
|
|
|
7
77
|
### Fixed
|
package/client.js
CHANGED
|
@@ -12,6 +12,7 @@ window.__ModuleLoader__.load({
|
|
|
12
12
|
const STATUS_URL = 'api/ai-prison/status'
|
|
13
13
|
const RUN_URL = 'api/ai-prison/run'
|
|
14
14
|
const WATCHDOG_URL = 'api/ai-prison/watchdog/status'
|
|
15
|
+
const WATCHDOG_ACTION_URL = 'api/ai-prison/watchdog/action'
|
|
15
16
|
|
|
16
17
|
const DICTS = {
|
|
17
18
|
en: {
|
|
@@ -284,6 +285,15 @@ window.__ModuleLoader__.load({
|
|
|
284
285
|
})
|
|
285
286
|
}
|
|
286
287
|
|
|
288
|
+
|
|
289
|
+
function postWatchdogAction(action, target) {
|
|
290
|
+
return fetch(new URL(WATCHDOG_ACTION_URL, document.baseURI), {
|
|
291
|
+
method: 'POST',
|
|
292
|
+
credentials: 'same-origin',
|
|
293
|
+
headers: { 'content-type': 'application/json', accept: 'application/json' },
|
|
294
|
+
body: JSON.stringify({ action, target }),
|
|
295
|
+
}).then((response) => response.json())
|
|
296
|
+
}
|
|
287
297
|
function waterlineText(level) {
|
|
288
298
|
if (level === 'block') return t('waterline.block')
|
|
289
299
|
if (level === 'pause') return t('waterline.pause')
|
|
@@ -397,6 +407,50 @@ window.__ModuleLoader__.load({
|
|
|
397
407
|
)
|
|
398
408
|
}
|
|
399
409
|
|
|
410
|
+
function EnforceCard({ watchdog, refresh }) {
|
|
411
|
+
if (!watchdog || !watchdog.ok) return null
|
|
412
|
+
const act = (name, target, prompt) => {
|
|
413
|
+
if (prompt && !window.confirm(prompt)) return
|
|
414
|
+
postWatchdogAction(name, target).then(() => refresh()).catch(() => refresh())
|
|
415
|
+
}
|
|
416
|
+
const frozen = Boolean(watchdog.frozenAt) || watchdog.waterline === 'frost'
|
|
417
|
+
const paused = Boolean(watchdog.pausedAt) || watchdog.waterline === 'pause'
|
|
418
|
+
const grace = Number.isFinite(watchdog.graceUntil) && Date.now() < watchdog.graceUntil
|
|
419
|
+
const quarantine = Array.isArray(watchdog.quarantine) ? watchdog.quarantine : []
|
|
420
|
+
const topFive = Array.isArray(watchdog.topFive) ? watchdog.topFive : []
|
|
421
|
+
const plans = Array.isArray(watchdog.plans) ? watchdog.plans.slice(-2).reverse() : []
|
|
422
|
+
const button = { cursor: 'pointer', padding: '3px 9px', borderRadius: 6, border: '1px solid var(--dsw-alias-border-l1, rgba(0,0,0,.18))', background: 'transparent', fontSize: 12 }
|
|
423
|
+
return h('section', { style: C.card },
|
|
424
|
+
h('div', { style: C.cardHead }, t('watchdog.enforceTitle'), h('span', { style: { ...C.chip, marginLeft: 8 } }, watchdog.enforce ? t('watchdog.enforceOn') : t('watchdog.observeOnly'))),
|
|
425
|
+
frozen ? h('p', { style: { color: C.error.color, fontSize: 12.5, margin: '0 0 8px' } }, t('watchdog.freezeHint', { level: watchdog.waterline })) : null,
|
|
426
|
+
paused && !grace ? h('div', { style: { margin: '0 0 10px' } }, h('button', { style: { ...button, padding: '6px 12px' }, onClick: () => act('confirm-pause') }, t('watchdog.confirmPause'))) : null,
|
|
427
|
+
h('div', { style: { ...C.key, marginBottom: 4 } }, t('watchdog.quarantine')),
|
|
428
|
+
quarantine.length === 0
|
|
429
|
+
? h('p', { style: { ...C.muted, fontSize: 12, margin: '0 0 10px' } }, t('watchdog.noQuarantine'))
|
|
430
|
+
: h('div', { style: { display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 10 } },
|
|
431
|
+
quarantine.map((entry) => h('div', { key: entry.target, style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' } },
|
|
432
|
+
h('span', { style: { ...C.mono, fontSize: 12, wordBreak: 'break-all' } }, entry.target + ' · ' + entry.reason + ' · ' + entry.level),
|
|
433
|
+
h('button', { style: button, onClick: () => act('release', entry.target, '假释 ' + entry.target + ' ?') }, t('watchdog.release')),
|
|
434
|
+
))),
|
|
435
|
+
topFive.length === 0 ? null : h('div', null,
|
|
436
|
+
h('div', { style: { ...C.key, marginBottom: 4 } }, t('watchdog.topFive', { n: topFive.length })),
|
|
437
|
+
h('table', { style: C.table },
|
|
438
|
+
h('tbody', null, topFive.map((row) => h('tr', { key: row.target },
|
|
439
|
+
h('td', { style: { ...C.td, ...C.mono, fontSize: 11.5, wordBreak: 'break-all' } }, row.target),
|
|
440
|
+
h('td', { style: C.td }, row.estimateMB + ' MB'),
|
|
441
|
+
h('td', { style: C.td }, h('button', { style: button, onClick: () => act('close', row.target, '立即关闭 ' + row.target + ' ?') }, t('watchdog.close'))),
|
|
442
|
+
))),
|
|
443
|
+
),
|
|
444
|
+
),
|
|
445
|
+
plans.length === 0 ? null : h('div', { style: { marginTop: 10 } },
|
|
446
|
+
h('div', { style: { ...C.key, marginBottom: 4 } }, t('watchdog.plans')),
|
|
447
|
+
plans.map((plan) => h('div', { key: plan.at, style: { ...C.mono, fontSize: 11.5, wordBreak: 'break-word' } },
|
|
448
|
+
plan.at + ' · ' + plan.level + ' · ' + (plan.target || 'unattributed') + (plan.inFlight ? ' (in-flight)' : '') + (plan.crash ? ' · ' + (plan.crash.oom ? 'OOM' : 'exit ' + plan.crash.hostExitCode) : ''))),
|
|
449
|
+
),
|
|
450
|
+
watchdog.baseline ? h('p', { style: { ...C.muted, fontSize: 11.5, margin: '10px 0 0' } }, t('watchdog.baseline', { at: watchdog.baseline.at })) : null,
|
|
451
|
+
)
|
|
452
|
+
}
|
|
453
|
+
|
|
400
454
|
function MatrixCard({ levels }) {
|
|
401
455
|
if (!Array.isArray(levels) || levels.length === 0) {
|
|
402
456
|
return h('section', { style: C.card }, h('div', { style: C.cardHead }, t('matrix.title')), h('p', { style: { ...C.muted, margin: 0, fontSize: 12 } }, t('matrix.empty')))
|
|
@@ -535,25 +589,18 @@ window.__ModuleLoader__.load({
|
|
|
535
589
|
return () => clearInterval(timer)
|
|
536
590
|
}, [load])
|
|
537
591
|
|
|
538
|
-
React.
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
.then((payload) => {
|
|
543
|
-
if (!cancelled) setWatchdog(payload)
|
|
544
|
-
})
|
|
545
|
-
.catch(() => {
|
|
546
|
-
if (!cancelled) setWatchdog(null)
|
|
547
|
-
})
|
|
548
|
-
}
|
|
549
|
-
tick()
|
|
550
|
-
const timer = setInterval(tick, 15000)
|
|
551
|
-
return () => {
|
|
552
|
-
cancelled = true
|
|
553
|
-
clearInterval(timer)
|
|
554
|
-
}
|
|
592
|
+
const refreshWatchdog = React.useCallback(() => {
|
|
593
|
+
fetchWatchdog()
|
|
594
|
+
.then((payload) => setWatchdog(payload))
|
|
595
|
+
.catch(() => setWatchdog(null))
|
|
555
596
|
}, [])
|
|
556
597
|
|
|
598
|
+
React.useEffect(() => {
|
|
599
|
+
refreshWatchdog()
|
|
600
|
+
const timer = setInterval(refreshWatchdog, 15000)
|
|
601
|
+
return () => clearInterval(timer)
|
|
602
|
+
}, [refreshWatchdog])
|
|
603
|
+
|
|
557
604
|
const runAction = React.useCallback(
|
|
558
605
|
(action) => {
|
|
559
606
|
setBusy(action)
|
|
@@ -606,6 +653,7 @@ window.__ModuleLoader__.load({
|
|
|
606
653
|
}),
|
|
607
654
|
h(MemoryCard, { watchdog }),
|
|
608
655
|
h(PrisonCard, { watchdog }),
|
|
656
|
+
h(EnforceCard, { watchdog, refresh: refreshWatchdog }),
|
|
609
657
|
h(
|
|
610
658
|
'p',
|
|
611
659
|
{ style: { ...C.muted, fontSize: 12, margin: '2px 0 0', display: 'flex', gap: 12, flexWrap: 'wrap' } },
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
import { fileURLToPath } from 'node:url'
|
|
3
|
+
|
|
4
|
+
const CHILD = fileURLToPath(new URL('./budget-child.mjs', import.meta.url))
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Measure a plugin package's module-load heap cost in an isolated child process.
|
|
8
|
+
* The child runs with --expose-gc, resolves the package from the profile, imports
|
|
9
|
+
* its entry module, forces GC and reports the retained delta. This is the
|
|
10
|
+
* "启动内存" budget that feeds the 300/500 MB per-plugin thresholds.
|
|
11
|
+
*/
|
|
12
|
+
export function probeBudget({ profileDir, packageName, timeoutMs = 25_000 } = {}) {
|
|
13
|
+
return new Promise((resolve) => {
|
|
14
|
+
const nodeExe = process.env.DSH_PROBE_NODE || process.execPath
|
|
15
|
+
const env = { ...process.env }
|
|
16
|
+
if (process.versions.electron) env.ELECTRON_RUN_AS_NODE = '1'
|
|
17
|
+
delete env.NODE_OPTIONS
|
|
18
|
+
const child = spawn(nodeExe, ['--expose-gc', CHILD, profileDir, packageName], {
|
|
19
|
+
env,
|
|
20
|
+
windowsHide: true,
|
|
21
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
22
|
+
})
|
|
23
|
+
let stdout = ''
|
|
24
|
+
let stderr = ''
|
|
25
|
+
let settled = false
|
|
26
|
+
const finish = (value) => {
|
|
27
|
+
if (settled) return
|
|
28
|
+
settled = true
|
|
29
|
+
clearTimeout(timer)
|
|
30
|
+
try {
|
|
31
|
+
child.kill()
|
|
32
|
+
} catch {
|
|
33
|
+
// already gone
|
|
34
|
+
}
|
|
35
|
+
resolve(value)
|
|
36
|
+
}
|
|
37
|
+
const timer = setTimeout(() => finish({ ok: false, error: 'probe-timeout' }), timeoutMs)
|
|
38
|
+
child.stdout.on('data', (chunk) => {
|
|
39
|
+
stdout += String(chunk)
|
|
40
|
+
})
|
|
41
|
+
child.stderr.on('data', (chunk) => {
|
|
42
|
+
stderr = (stderr + String(chunk)).slice(-2000)
|
|
43
|
+
})
|
|
44
|
+
child.on('error', (error) => finish({ ok: false, error: String(error && error.message) }))
|
|
45
|
+
child.on('exit', (code) => {
|
|
46
|
+
const line = stdout.trim().split('\n').filter(Boolean).pop()
|
|
47
|
+
if (!line) return finish({ ok: false, error: `probe-exit-${code}: ${stderr.slice(0, 300)}` })
|
|
48
|
+
try {
|
|
49
|
+
const parsed = JSON.parse(line)
|
|
50
|
+
finish(parsed)
|
|
51
|
+
} catch {
|
|
52
|
+
finish({ ok: false, error: `probe-bad-json: ${line.slice(0, 300)}` })
|
|
53
|
+
}
|
|
54
|
+
})
|
|
55
|
+
})
|
|
56
|
+
}
|
package/lib/tools.js
CHANGED
|
@@ -164,7 +164,7 @@ export async function installTools({ ctx, config = {}, logger } = {}) {
|
|
|
164
164
|
register({
|
|
165
165
|
name: 'ai_prison_watchdog_status',
|
|
166
166
|
description:
|
|
167
|
-
'Read the AI Prison watchdog snapshot (
|
|
167
|
+
'Read the AI Prison watchdog snapshot (P1 enforce mode): heap waterline (warn 3 GB / pause 3.9 GB / freeze 5 GB on a 6 GB host), per-plugin hot-operation counts and heap estimates, the plugin prison with quarantined targets and release state, the memory Top5, dry-run crash escalation plans (L1-L3) and recent incidents. Enforcement auto-closes a plugin after more than five hot operations in one run; the tool itself never changes a plugin.',
|
|
168
168
|
parameters: {},
|
|
169
169
|
output: stringOutput,
|
|
170
170
|
async execute() {
|
|
@@ -202,9 +202,22 @@ export async function installTools({ ctx, config = {}, logger } = {}) {
|
|
|
202
202
|
opBlock: formatBytes(snapshot.thresholds.opBlock),
|
|
203
203
|
}
|
|
204
204
|
: null,
|
|
205
|
+
enforce: snapshot.enforce,
|
|
206
|
+
strongWarn: snapshot.strongWarn,
|
|
207
|
+
pausedAt: snapshot.pausedAt,
|
|
208
|
+
graceUntil: snapshot.graceUntil,
|
|
209
|
+
frozenAt: snapshot.frozenAt,
|
|
210
|
+
topFive: snapshot.topFive,
|
|
211
|
+
quarantine: snapshot.quarantine,
|
|
212
|
+
plans: snapshot.plans,
|
|
213
|
+
escalation: snapshot.escalation,
|
|
214
|
+
baselineAt: snapshot.baseline ? snapshot.baseline.at : null,
|
|
215
|
+
budgets: snapshot.budgets,
|
|
205
216
|
operations: snapshot.operations,
|
|
206
217
|
incidents: snapshot.incidents,
|
|
207
|
-
note:
|
|
218
|
+
note: snapshot.enforce
|
|
219
|
+
? 'enforce 模式:热操作 > 5 次自动关闭;3.9GB 暂停需二次确认,5GB 冻结插件操作。'
|
|
220
|
+
: 'observe 模式:仅观察与记录,不自动关闭任何插件。',
|
|
208
221
|
})
|
|
209
222
|
},
|
|
210
223
|
})
|
package/lib/watchdog-policy.js
CHANGED
|
@@ -1,11 +1,21 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Pure policy math for the AI Prison watchdog (
|
|
3
|
-
*
|
|
4
|
-
*
|
|
2
|
+
* Pure policy math for the AI Prison watchdog (P1).
|
|
3
|
+
*
|
|
4
|
+
* Threshold layout (derived from the real heap limit, absolute values clamped):
|
|
5
|
+
* warn 3.0 GB -> yellow waterline
|
|
6
|
+
* pause 3.9 GB -> additive plugin operations need a second confirmation
|
|
7
|
+
* opWarn 4.0 GB -> red warning once the user continued through pause
|
|
8
|
+
* block 5.0 GB -> freeze every plugin operation except the release whitelist
|
|
9
|
+
* On a 4 GB host the same ratios map down (2.99 / 3.60 / 4.09 / 3.81 GB).
|
|
5
10
|
*/
|
|
6
11
|
export const MB = 1024 * 1024
|
|
7
12
|
export const GB = 1024 * MB
|
|
8
13
|
|
|
14
|
+
export const FREEZE_MARGIN = 0.3 * GB
|
|
15
|
+
export const HOT_OP_LIMIT = 5
|
|
16
|
+
export const ADDITIVE_ACTIONS = new Set(['set_plugin', 'set_bundle', 'install_bundle', 'remove_bundle', 'set_version_exemption'])
|
|
17
|
+
export const READONLY_ACTIONS = new Set(['list_plugins', 'list_bundles', 'list_version_exemptions'])
|
|
18
|
+
|
|
9
19
|
/** Thresholds derived from the host heap limit (absolute values clamped to the cap). */
|
|
10
20
|
export function thresholdsFor(heapLimitBytes) {
|
|
11
21
|
const limit = Number(heapLimitBytes) > 0 ? Number(heapLimitBytes) : 4 * GB
|
|
@@ -22,15 +32,23 @@ export function thresholdsFor(heapLimitBytes) {
|
|
|
22
32
|
}
|
|
23
33
|
}
|
|
24
34
|
|
|
25
|
-
/** Waterline for the whole host
|
|
26
|
-
export function classifyWaterline(heapUsed, thresholds) {
|
|
35
|
+
/** Waterline for the whole host, with the active level to keep hysteresis. */
|
|
36
|
+
export function classifyWaterline(heapUsed, thresholds, previous = 'ok') {
|
|
27
37
|
if (!thresholds || !(heapUsed >= 0)) return 'ok'
|
|
28
|
-
|
|
29
|
-
if (heapUsed >= thresholds.
|
|
30
|
-
if (heapUsed >= thresholds.
|
|
38
|
+
const above = (value, guard) => heapUsed + guard >= value
|
|
39
|
+
if (previous === 'frost' && heapUsed + FREEZE_MARGIN >= thresholds.totalBlock) return 'frost'
|
|
40
|
+
if (heapUsed + FREEZE_MARGIN >= thresholds.totalBlock) return 'frost'
|
|
41
|
+
if (previous === 'pause' && heapUsed + FREEZE_MARGIN >= thresholds.totalPause) return 'pause'
|
|
42
|
+
if (heapUsed + FREEZE_MARGIN >= thresholds.totalPause) return 'pause'
|
|
43
|
+
if (heapUsed + FREEZE_MARGIN >= thresholds.totalWarn) return 'warn'
|
|
31
44
|
return 'ok'
|
|
32
45
|
}
|
|
33
46
|
|
|
47
|
+
/** True when additive plugin operations must be denied at this waterline. */
|
|
48
|
+
export function operationsDenied(level) {
|
|
49
|
+
return level === 'pause' || level === 'frost'
|
|
50
|
+
}
|
|
51
|
+
|
|
34
52
|
/** How much one plugin operation counts toward the per-target hot-operation limit. */
|
|
35
53
|
export function operationWeight(operation) {
|
|
36
54
|
if (!operation || typeof operation !== 'object') return 0
|
|
@@ -49,14 +67,63 @@ export function mergeEstimate(previous, next, alpha = 0.5) {
|
|
|
49
67
|
return Math.round(before * (1 - alpha) + value * alpha)
|
|
50
68
|
}
|
|
51
69
|
|
|
70
|
+
/**
|
|
71
|
+
* Tool guard decision for the agent-facing plugin_manager tool.
|
|
72
|
+
* @returns {{ reason: string, info?: { name: string, code: string } } | undefined}
|
|
73
|
+
*/
|
|
74
|
+
export function decideToolGuard(execution, state) {
|
|
75
|
+
if (!execution || execution.name !== 'plugin_manager') return undefined
|
|
76
|
+
const args = execution.arguments && typeof execution.arguments === 'object' ? execution.arguments : {}
|
|
77
|
+
const action = typeof args.action === 'string' ? args.action : ''
|
|
78
|
+
if (!action) return undefined
|
|
79
|
+
const target = typeof args.target === 'string' ? args.target : null
|
|
80
|
+
const quarantine = target && state.quarantine instanceof Map ? state.quarantine.get(target) : null
|
|
81
|
+
if (quarantine && action !== 'list_plugins' && action !== 'list_bundles') {
|
|
82
|
+
return {
|
|
83
|
+
reason: `插件 ${target} 在 AI 监狱(${quarantine.reason},级别 ${quarantine.level})。需要用户在本机面板点击"假释"后才能操作。`,
|
|
84
|
+
info: { name: 'ai-prison-quarantine', code: 'quarantined' },
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
if (READONLY_ACTIONS.has(action)) return undefined
|
|
88
|
+
if (!ADDITIVE_ACTIONS.has(action)) return undefined
|
|
89
|
+
const level = state.waterline
|
|
90
|
+
if (level === 'frost') {
|
|
91
|
+
return {
|
|
92
|
+
reason: `堆水位 ${level}(≥${formatBytes(state.thresholds ? state.thresholds.totalBlock : 0)})已冻结所有插件操作。请先在面板"内存看护"里关闭 Top5 插件释放内存,或重启 DSH。`,
|
|
93
|
+
info: { name: 'ai-prison-freeze', code: 'memory-frozen' },
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (level === 'pause') {
|
|
97
|
+
const grace = Number.isFinite(state.graceUntil) ? state.graceUntil : 0
|
|
98
|
+
if (!(Date.now() < grace)) {
|
|
99
|
+
return {
|
|
100
|
+
reason: `堆水位 ${level}(≥${formatBytes(state.thresholds ? state.thresholds.totalPause : 0)})已暂停插件操作,需要用户二次确认。请在面板"内存看护"里确认继续,或重启 DSH。`,
|
|
101
|
+
info: { name: 'ai-prison-pause', code: 'memory-paused' },
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return undefined
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** A panel/UI-initiated operation may run only for the release whitelist while frozen. */
|
|
109
|
+
export function allowedDuringFreeze(action) {
|
|
110
|
+
return action === 'list_plugins' || action === 'list_bundles' || action === 'list_version_exemptions'
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Should this crash attribution candidate be quarantined? */
|
|
114
|
+
export function hotOperationTriggered(count) {
|
|
115
|
+
return Number(count) > HOT_OP_LIMIT
|
|
116
|
+
}
|
|
117
|
+
|
|
52
118
|
/** Parse the header block of a DSH desktop host crash log. */
|
|
53
119
|
export function parseCrashLog(text) {
|
|
54
120
|
const source = String(text || '')
|
|
55
|
-
const header = source.slice(0,
|
|
121
|
+
const header = source.slice(0, 6000)
|
|
56
122
|
const time = /^time:\s*(.+)$/m.exec(header)
|
|
57
123
|
const phase = /^phase:\s*(.+)$/m.exec(header)
|
|
58
124
|
const exit = /exited with (\d+)/.exec(source)
|
|
59
125
|
const oom = /heap out of memory|Allocation failed|MarkCompactCollector|Scavenger:/i.test(source)
|
|
126
|
+
const runId = /hostRunId:\s*'([^']+)'/.exec(source)
|
|
60
127
|
const fatal = /FATAL ERROR/.test(source)
|
|
61
128
|
return {
|
|
62
129
|
valid: Boolean(time || exit || fatal),
|
|
@@ -64,10 +131,82 @@ export function parseCrashLog(text) {
|
|
|
64
131
|
phase: phase ? phase[1].trim() : null,
|
|
65
132
|
hostExitCode: exit ? Number(exit[1]) : null,
|
|
66
133
|
oom,
|
|
134
|
+
hostRunId: runId ? runId[1] : null,
|
|
67
135
|
}
|
|
68
136
|
}
|
|
69
137
|
|
|
70
|
-
/**
|
|
138
|
+
/**
|
|
139
|
+
* Attribute a crash to the last changed plugin.
|
|
140
|
+
*
|
|
141
|
+
* Preference order (per requirement 3, "only close the last installed plugin"):
|
|
142
|
+
* 1. an installation/enable that was still in flight when the host died;
|
|
143
|
+
* 2. the latest settled install/update in the same host run;
|
|
144
|
+
* 3. the latest settled enable in the same host run.
|
|
145
|
+
* Disable/remove records are never candidates. A run id mismatch or an empty
|
|
146
|
+
* candidate list means "unknown": the caller records it and does not kill.
|
|
147
|
+
*/
|
|
148
|
+
export function attributeCrash(journalRecords, crash) {
|
|
149
|
+
const runId = crash && crash.hostRunId
|
|
150
|
+
const records = Array.isArray(journalRecords) ? journalRecords : []
|
|
151
|
+
const inRun = records.filter((record) => !runId || record.runId === runId)
|
|
152
|
+
const positive = (operation) =>
|
|
153
|
+
operation
|
|
154
|
+
&& (operation.stage === 'install' || (operation.stage === 'enable' && operation.enabled !== false))
|
|
155
|
+
&& operation.target
|
|
156
|
+
const started = new Map()
|
|
157
|
+
for (const record of inRun) {
|
|
158
|
+
const operation = record.operation
|
|
159
|
+
if (!positive(operation)) continue
|
|
160
|
+
if (operation.phase === 'started') started.set(operation.id, operation)
|
|
161
|
+
if (operation.phase === 'settled') started.delete(operation.id)
|
|
162
|
+
}
|
|
163
|
+
const inFlight = [...started.values()].sort((a, b) => String(b.time).localeCompare(String(a.time)))[0]
|
|
164
|
+
const settled = inRun
|
|
165
|
+
.map((record) => record.operation)
|
|
166
|
+
.filter((operation) => positive(operation) && operation.phase === 'settled')
|
|
167
|
+
.sort((a, b) => String(b.time).localeCompare(String(a.time)))
|
|
168
|
+
const latestInstall = settled.find((operation) => operation.stage === 'install')
|
|
169
|
+
const latestEnable = settled.find((operation) => operation.stage === 'enable')
|
|
170
|
+
const candidates = []
|
|
171
|
+
if (inFlight) candidates.push({ target: inFlight.target, inFlight: true, reason: inFlight.reason, time: inFlight.time, version: inFlight.version || null })
|
|
172
|
+
for (const operation of [latestInstall, latestEnable]) {
|
|
173
|
+
if (operation && !candidates.some((candidate) => candidate.target === operation.target)) {
|
|
174
|
+
candidates.push({ target: operation.target, inFlight: false, reason: operation.reason, time: operation.time, version: operation.version || null })
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return {
|
|
178
|
+
hostRunId: runId || null,
|
|
179
|
+
candidates,
|
|
180
|
+
picked: candidates.length > 0 ? candidates[0] : null,
|
|
181
|
+
reason: candidates.length === 0 ? 'no candidate in this host run (missing or incomplete operation history)' : 'last changed plugin in the crashed host run',
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Difference between current bundle rows and the recorded clean baseline. */
|
|
186
|
+
export function diffBaseline(rows, baseline) {
|
|
187
|
+
const baselineBundles = baseline && Array.isArray(baseline.bundles) ? baseline.bundles : []
|
|
188
|
+
const known = new Map(baselineBundles.map((row) => [row.name, String(row.version || '')]))
|
|
189
|
+
const changed = []
|
|
190
|
+
for (const row of Array.isArray(rows) ? rows : []) {
|
|
191
|
+
const version = String(row.version || '')
|
|
192
|
+
if (!row.enabled) continue
|
|
193
|
+
const before = known.get(row.name)
|
|
194
|
+
if (before === undefined) changed.push({ name: row.name, version, kind: 'added' })
|
|
195
|
+
else if (before !== version) changed.push({ name: row.name, version, before, kind: 'updated' })
|
|
196
|
+
}
|
|
197
|
+
const level = escalationLevel(0)
|
|
198
|
+
return { changed, unknown: !baseline, level }
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Escalation level from recent crash count (dry-run plans in P1). */
|
|
202
|
+
export function escalationLevel(crashCount) {
|
|
203
|
+
if (crashCount >= 3) return 'L3'
|
|
204
|
+
if (crashCount >= 2) return 'L2'
|
|
205
|
+
if (crashCount >= 1) return 'L1'
|
|
206
|
+
return 'L0'
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Top-N view of per-target accounting, biggest estimate first. */
|
|
71
210
|
export function topOperations(operations, limit = 5) {
|
|
72
211
|
const rows = []
|
|
73
212
|
for (const [target, entry] of operations instanceof Map ? operations : Object.entries(operations || {})) {
|