@twinsearth/ai-prison-dsh-plugin 1.1.4 → 1.2.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 +48 -0
- package/README.md +13 -0
- package/client.js +185 -0
- package/cordis.patch.yml +19 -10
- package/lib/tools.js +50 -0
- package/lib/watchdog-policy.js +92 -0
- package/lib/watchdog-runtime.js +360 -0
- package/lib/watchdog-state.js +45 -0
- package/package.json +4 -2
- package/watchdog.js +20 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,54 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `@twinsearth/ai-prison-dsh-plugin` are recorded here.
|
|
4
4
|
|
|
5
|
+
## [1.2.1] — 2026-11-18
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
|
|
9
|
+
- **Watchdog row crashed before its sampler started**: `readCrashLogs()` ran during
|
|
10
|
+
setup and called `persist()` while `let lastFlush` was still in its temporal dead
|
|
11
|
+
zone, so the row threw a `ReferenceError` after recording crash history but before
|
|
12
|
+
registering the sampler, the operation listener and the status route. The value is now
|
|
13
|
+
declared before the first scan, `readCrashLogs` is wrapped defensively, and the
|
|
14
|
+
runtime exposes a `dispose()` used by tests.
|
|
15
|
+
- Watchdog state directory and crash-log directory are now injectable
|
|
16
|
+
(`config.dataDir` / `config.logsDir`) so runtime tests stay hermetic.
|
|
17
|
+
|
|
18
|
+
### Tests
|
|
19
|
+
|
|
20
|
+
- New `test/watchdog-runtime.test.mjs`: heap sampling, crash-fixture parsing and
|
|
21
|
+
persistence, plugin-operation counting/estimation, failed-operation and removal
|
|
22
|
+
handling, all against temporary directories.
|
|
23
|
+
|
|
24
|
+
## [1.2.0] — 2026-11-18
|
|
25
|
+
|
|
26
|
+
### Added — P0 memory watchdog (observe mode)
|
|
27
|
+
|
|
28
|
+
- **New loader row `ai-prison-watchdog`** (`watchdog.js` + `lib/watchdog-*.js`):
|
|
29
|
+
samples the host heap every 5 s (`process.memoryUsage` + `v8.getHeapStatistics`),
|
|
30
|
+
derives the design thresholds from the actual heap limit (300/500 MB per plugin,
|
|
31
|
+
3.0/3.9/5.0 GB total, 4/5 GB operation gates), classifies the waterline
|
|
32
|
+
(`ok` → `warn` → `pause` → `block`) and records threshold crossings, per-plugin
|
|
33
|
+
operation counts (install/remove = 1, enable = 1, disable = 0.5) and estimated
|
|
34
|
+
heap deltas per plugin.
|
|
35
|
+
- **Crash-history scan**: on activation it reads new
|
|
36
|
+
`crash-*-host.log` files from the desktop log directory, parses
|
|
37
|
+
phase/OOM/exit-code and appends them to the incident journal.
|
|
38
|
+
- **Read-only API** `GET /api/ai-prison/watchdog/status` and a new
|
|
39
|
+
`ai_prison_watchdog_status` tool.
|
|
40
|
+
- **Panel**: two new cards — **Memory watchdog** (heap bar, used/limit, RSS,
|
|
41
|
+
warn/pause/block thresholds) and **Plugin prison** (top-5 plugins by estimated
|
|
42
|
+
heap, hot-operation counts, recent incidents). Both label themselves
|
|
43
|
+
"observe mode: records only, never closes plugins".
|
|
44
|
+
- State is persisted under `<profile>/.ai-prison-watchdog/`
|
|
45
|
+
(`state.json`, `incidents.jsonl`).
|
|
46
|
+
|
|
47
|
+
### Explicitly not in this release
|
|
48
|
+
|
|
49
|
+
- No automatic closing, disabling or quarantine: enforcement (P1–P3 of
|
|
50
|
+
`AI-PRISON-WATCHDOG-DESIGN.md`) is not implemented and requires explicit
|
|
51
|
+
confirmation.
|
|
52
|
+
|
|
5
53
|
## [1.1.4] — 2026-11-18
|
|
6
54
|
|
|
7
55
|
### Fixed
|
package/README.md
CHANGED
|
@@ -43,6 +43,19 @@ deleted and the action runs, because the CLI replays an existing ledger and
|
|
|
43
43
|
refuses to re-seed credentials that earlier runs already revoked (`demo` twice,
|
|
44
44
|
or a second `drill`, would otherwise fail).
|
|
45
45
|
|
|
46
|
+
## Memory watchdog (P0, observe only)
|
|
47
|
+
|
|
48
|
+
A second loader row (`ai-prison-watchdog`) samples the host heap every 5 seconds,
|
|
49
|
+
derives the design thresholds from the real heap limit (300/500 MB per plugin,
|
|
50
|
+
3.0/3.9/5.0 GB total, 4/5 GB operation gates), accounts plugin operations
|
|
51
|
+
(install/remove = 1, enable = 1, disable = 0.5), estimates each plugin's heap
|
|
52
|
+
delta around those operations and reads new `crash-*-host.log` files at startup.
|
|
53
|
+
It exposes `GET /api/ai-prison/watchdog/status` and the read-only
|
|
54
|
+
`ai_prison_watchdog_status` tool; the panel adds **Memory watchdog** and
|
|
55
|
+
**Plugin prison** cards. **Observe mode never enables or disables a plugin** —
|
|
56
|
+
enforcement (P1–P3) is not implemented and needs explicit confirmation.
|
|
57
|
+
State lives in `<profile>/.ai-prison-watchdog/`.
|
|
58
|
+
|
|
46
59
|
## Ledger directory
|
|
47
60
|
|
|
48
61
|
Default for tools: `<session working directory>/.ai-prison`, so the audit trail
|
package/client.js
CHANGED
|
@@ -11,6 +11,7 @@ window.__ModuleLoader__.load({
|
|
|
11
11
|
const NS = 'ai-prison'
|
|
12
12
|
const STATUS_URL = 'api/ai-prison/status'
|
|
13
13
|
const RUN_URL = 'api/ai-prison/run'
|
|
14
|
+
const WATCHDOG_URL = 'api/ai-prison/watchdog/status'
|
|
14
15
|
|
|
15
16
|
const DICTS = {
|
|
16
17
|
en: {
|
|
@@ -49,6 +50,25 @@ window.__ModuleLoader__.load({
|
|
|
49
50
|
'ledger.lastAction': 'Last action',
|
|
50
51
|
'meta.updated': 'Updated {time}',
|
|
51
52
|
'meta.readonly': 'Read-only view: the panel never writes by itself; only the buttons above do.',
|
|
53
|
+
'watchdog.title': 'Memory watchdog',
|
|
54
|
+
'watchdog.mode': 'Observe mode: records only, never closes plugins',
|
|
55
|
+
'watchdog.disabled': 'Watchdog row not enabled; heap observation is unavailable.',
|
|
56
|
+
'watchdog.heap': 'Heap used',
|
|
57
|
+
'watchdog.limit': 'Heap limit',
|
|
58
|
+
'watchdog.rss': 'RSS',
|
|
59
|
+
'watchdog.waterline': 'Waterline',
|
|
60
|
+
'watchdog.thresholds': 'Warn / pause / block',
|
|
61
|
+
'waterline.ok': 'OK',
|
|
62
|
+
'waterline.warn': 'Warning',
|
|
63
|
+
'waterline.pause': 'Paused',
|
|
64
|
+
'waterline.block': 'Blocked',
|
|
65
|
+
'prison.title': 'Plugin prison',
|
|
66
|
+
'prison.top': 'Top {n} plugins by estimated heap',
|
|
67
|
+
'prison.ops': 'Hot ops',
|
|
68
|
+
'prison.estimate': 'Est.',
|
|
69
|
+
'prison.incidents': 'Recent incidents',
|
|
70
|
+
'prison.empty': 'No quarantined plugins: observe mode never closes one.',
|
|
71
|
+
'prison.noestimates': 'No plugin operations observed yet.',
|
|
52
72
|
'error.title': 'Cannot read the status',
|
|
53
73
|
'error.hint': 'Check that the bundle is enabled and the aiprison CLI resolves for this platform.',
|
|
54
74
|
},
|
|
@@ -88,6 +108,25 @@ window.__ModuleLoader__.load({
|
|
|
88
108
|
'ledger.lastAction': '最近操作',
|
|
89
109
|
'meta.updated': '更新于 {time}',
|
|
90
110
|
'meta.readonly': '只读视图:面板不会自行写入账本,只有上方按钮会写入。',
|
|
111
|
+
'watchdog.title': '内存看护',
|
|
112
|
+
'watchdog.mode': '观察模式:只记录,不关闭插件',
|
|
113
|
+
'watchdog.disabled': 'watchdog 行未启用,暂时无法观察内存。',
|
|
114
|
+
'watchdog.heap': '已用堆',
|
|
115
|
+
'watchdog.limit': '堆上限',
|
|
116
|
+
'watchdog.rss': 'RSS',
|
|
117
|
+
'watchdog.waterline': '水位',
|
|
118
|
+
'watchdog.thresholds': '提醒 / 暂停 / 禁止',
|
|
119
|
+
'waterline.ok': '正常',
|
|
120
|
+
'waterline.warn': '警告',
|
|
121
|
+
'waterline.pause': '暂停',
|
|
122
|
+
'waterline.block': '禁止',
|
|
123
|
+
'prison.title': '插件监狱',
|
|
124
|
+
'prison.top': '按估算内存排序的前 {n} 个插件',
|
|
125
|
+
'prison.ops': '热操作',
|
|
126
|
+
'prison.estimate': '估算',
|
|
127
|
+
'prison.incidents': '最近事件',
|
|
128
|
+
'prison.empty': '没有被隔离的插件:观察模式不会关闭任何插件。',
|
|
129
|
+
'prison.noestimates': '还没有观察到插件操作。',
|
|
91
130
|
'error.title': '无法读取状态',
|
|
92
131
|
'error.hint': '请确认插件已启用,且本平台能解析到 aiprison CLI。',
|
|
93
132
|
},
|
|
@@ -234,6 +273,130 @@ window.__ModuleLoader__.load({
|
|
|
234
273
|
})
|
|
235
274
|
}
|
|
236
275
|
|
|
276
|
+
/** Read-only watchdog snapshot; a missing row (or 404) simply hides the cards. */
|
|
277
|
+
function fetchWatchdog() {
|
|
278
|
+
return fetch(new URL(WATCHDOG_URL, document.baseURI), {
|
|
279
|
+
credentials: 'same-origin',
|
|
280
|
+
headers: { accept: 'application/json' },
|
|
281
|
+
}).then((response) => {
|
|
282
|
+
if (!response.ok) return null
|
|
283
|
+
return response.json().then((payload) => (payload && payload.ok ? payload : null))
|
|
284
|
+
})
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function waterlineText(level) {
|
|
288
|
+
if (level === 'block') return t('waterline.block')
|
|
289
|
+
if (level === 'pause') return t('waterline.pause')
|
|
290
|
+
if (level === 'warn') return t('waterline.warn')
|
|
291
|
+
return t('waterline.ok')
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function MemoryCard({ watchdog }) {
|
|
295
|
+
if (!watchdog) {
|
|
296
|
+
return h(
|
|
297
|
+
'section',
|
|
298
|
+
{ style: C.card },
|
|
299
|
+
h('div', { style: C.cardHead }, t('watchdog.title')),
|
|
300
|
+
h('p', { style: { ...C.muted, fontSize: 12, margin: 0 } }, t('watchdog.disabled')),
|
|
301
|
+
)
|
|
302
|
+
}
|
|
303
|
+
const heap = watchdog.heap || {}
|
|
304
|
+
const thresholds = watchdog.thresholds || {}
|
|
305
|
+
const ratio = heap.heapLimit > 0 ? Math.min(1, heap.heapUsed / heap.heapLimit) : 0
|
|
306
|
+
const tone = watchdog.waterline === 'ok' ? C.ok.color : watchdog.waterline === 'warn' ? '#b45309' : C.error.color
|
|
307
|
+
return h(
|
|
308
|
+
'section',
|
|
309
|
+
{ style: C.card },
|
|
310
|
+
h(
|
|
311
|
+
'div',
|
|
312
|
+
{ style: C.cardHead },
|
|
313
|
+
t('watchdog.title'),
|
|
314
|
+
h('span', { style: { ...C.chip, marginLeft: 8 } }, t('watchdog.mode')),
|
|
315
|
+
h(Pill, { tone: watchdog.waterline === 'ok' ? 'ok' : 'error', text: `${t('watchdog.waterline')}: ${waterlineText(watchdog.waterline)}` }),
|
|
316
|
+
),
|
|
317
|
+
h(
|
|
318
|
+
'div',
|
|
319
|
+
{ style: { height: 10, borderRadius: 999, background: 'var(--dsw-alias-border-l1, rgba(0,0,0,.08))', overflow: 'hidden', margin: '4px 0 10px' } },
|
|
320
|
+
h('div', { style: { width: `${Math.round(ratio * 1000) / 10}%`, height: '100%', background: tone } }),
|
|
321
|
+
),
|
|
322
|
+
h(
|
|
323
|
+
'div',
|
|
324
|
+
{ style: C.grid },
|
|
325
|
+
h('div', { style: C.key }, t('watchdog.heap')),
|
|
326
|
+
h('div', { style: C.mono }, `${Math.round(heap.heapUsed / 1048576)} MB / ${Math.round(heap.heapLimit / 1048576)} MB(${Math.round(ratio * 100)}%)`),
|
|
327
|
+
h('div', { style: C.key }, t('watchdog.rss')),
|
|
328
|
+
h('div', { style: C.mono }, `${Math.round((heap.rss || 0) / 1048576)} MB`),
|
|
329
|
+
h('div', { style: C.key }, t('watchdog.thresholds')),
|
|
330
|
+
h(
|
|
331
|
+
'div',
|
|
332
|
+
{ style: C.mono },
|
|
333
|
+
`${Math.round(thresholds.totalWarn / 1048576)} / ${Math.round(thresholds.totalPause / 1048576)} / ${Math.round(thresholds.totalBlock / 1048576)} MB`,
|
|
334
|
+
),
|
|
335
|
+
),
|
|
336
|
+
)
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function PrisonCard({ watchdog }) {
|
|
340
|
+
if (!watchdog) {
|
|
341
|
+
return h(
|
|
342
|
+
'section',
|
|
343
|
+
{ style: C.card },
|
|
344
|
+
h('div', { style: C.cardHead }, t('prison.title')),
|
|
345
|
+
h('p', { style: { ...C.muted, fontSize: 12, margin: 0 } }, t('watchdog.disabled')),
|
|
346
|
+
)
|
|
347
|
+
}
|
|
348
|
+
const operations = Array.isArray(watchdog.operations) ? watchdog.operations.slice(0, 5) : []
|
|
349
|
+
const incidents = Array.isArray(watchdog.incidents) ? watchdog.incidents.slice(-5).reverse() : []
|
|
350
|
+
return h(
|
|
351
|
+
'section',
|
|
352
|
+
{ style: C.card },
|
|
353
|
+
h('div', { style: C.cardHead }, t('prison.title'), h('span', { style: { ...C.chip, marginLeft: 8 } }, t('watchdog.mode'))),
|
|
354
|
+
operations.length === 0
|
|
355
|
+
? h('p', { style: { ...C.muted, fontSize: 12, margin: '0 0 6px' } }, t('prison.noestimates'))
|
|
356
|
+
: h(
|
|
357
|
+
'table',
|
|
358
|
+
{ style: C.table },
|
|
359
|
+
h(
|
|
360
|
+
'thead',
|
|
361
|
+
null,
|
|
362
|
+
h('tr', null, h('th', { style: C.th }, t('prison.top', { n: operations.length })), h('th', { style: C.th }, t('prison.estimate')), h('th', { style: C.th }, t('prison.ops'))),
|
|
363
|
+
),
|
|
364
|
+
h(
|
|
365
|
+
'tbody',
|
|
366
|
+
null,
|
|
367
|
+
operations.map((row) =>
|
|
368
|
+
h(
|
|
369
|
+
'tr',
|
|
370
|
+
{ key: row.target },
|
|
371
|
+
h('td', { style: { ...C.td, ...C.mono, wordBreak: 'break-all' } }, row.target),
|
|
372
|
+
h('td', { style: C.td }, `${row.estimateMB} MB`),
|
|
373
|
+
h('td', { style: C.td }, String(row.count)),
|
|
374
|
+
),
|
|
375
|
+
),
|
|
376
|
+
),
|
|
377
|
+
),
|
|
378
|
+
h('p', { style: { ...C.muted, fontSize: 12, margin: '10px 0 4px' } }, t('prison.empty')),
|
|
379
|
+
incidents.length > 0
|
|
380
|
+
? h(
|
|
381
|
+
'div',
|
|
382
|
+
null,
|
|
383
|
+
h('div', { style: { ...C.key, marginBottom: 4 } }, t('prison.incidents')),
|
|
384
|
+
h(
|
|
385
|
+
'div',
|
|
386
|
+
{ style: { display: 'flex', flexDirection: 'column', gap: 4 } },
|
|
387
|
+
incidents.map((incident, index) =>
|
|
388
|
+
h(
|
|
389
|
+
'div',
|
|
390
|
+
{ key: `${incident.at || index}-${index}`, style: { ...C.mono, fontSize: 11.5, wordBreak: 'break-word' } },
|
|
391
|
+
`${incident.at || ''} · ${incident.kind || 'event'}${incident.detail ? ` · ${incident.detail}` : ''}${incident.target ? ` · ${incident.target}` : ''}`,
|
|
392
|
+
),
|
|
393
|
+
),
|
|
394
|
+
),
|
|
395
|
+
)
|
|
396
|
+
: null,
|
|
397
|
+
)
|
|
398
|
+
}
|
|
399
|
+
|
|
237
400
|
function MatrixCard({ levels }) {
|
|
238
401
|
if (!Array.isArray(levels) || levels.length === 0) {
|
|
239
402
|
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')))
|
|
@@ -349,6 +512,7 @@ window.__ModuleLoader__.load({
|
|
|
349
512
|
const [updated, setUpdated] = React.useState(null)
|
|
350
513
|
const [busy, setBusy] = React.useState(null)
|
|
351
514
|
const [lastResult, setLastResult] = React.useState(null)
|
|
515
|
+
const [watchdog, setWatchdog] = React.useState(null)
|
|
352
516
|
|
|
353
517
|
const load = React.useCallback(() => {
|
|
354
518
|
setLoading(true)
|
|
@@ -371,6 +535,25 @@ window.__ModuleLoader__.load({
|
|
|
371
535
|
return () => clearInterval(timer)
|
|
372
536
|
}, [load])
|
|
373
537
|
|
|
538
|
+
React.useEffect(() => {
|
|
539
|
+
let cancelled = false
|
|
540
|
+
const tick = () => {
|
|
541
|
+
fetchWatchdog()
|
|
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
|
+
}
|
|
555
|
+
}, [])
|
|
556
|
+
|
|
374
557
|
const runAction = React.useCallback(
|
|
375
558
|
(action) => {
|
|
376
559
|
setBusy(action)
|
|
@@ -421,6 +604,8 @@ window.__ModuleLoader__.load({
|
|
|
421
604
|
onAction: runAction,
|
|
422
605
|
lastResult,
|
|
423
606
|
}),
|
|
607
|
+
h(MemoryCard, { watchdog }),
|
|
608
|
+
h(PrisonCard, { watchdog }),
|
|
424
609
|
h(
|
|
425
610
|
'p',
|
|
426
611
|
{ style: { ...C.muted, fontSize: 12, margin: '2px 0 0', display: 'flex', gap: 12, flexWrap: 'wrap' } },
|
package/cordis.patch.yml
CHANGED
|
@@ -1,21 +1,30 @@
|
|
|
1
1
|
# ai-prison-dsh-plugin: the AI Prison governance bundle.
|
|
2
2
|
#
|
|
3
|
-
#
|
|
4
|
-
#
|
|
5
|
-
#
|
|
3
|
+
# Two rows:
|
|
4
|
+
# ai-prison Host tools + read-only status API + the sidebar panel
|
|
5
|
+
# (L0-L5 matrix, audit chain, plugin prison and memory cards).
|
|
6
|
+
# ai-prison-watchdog P0 watchdog in OBSERVE mode: samples the host heap,
|
|
7
|
+
# accounts plugin operations, reads recent host crash logs and
|
|
8
|
+
# serves /api/ai-prison/watchdog/status. It never enables or
|
|
9
|
+
# disables a plugin; enforcement arrives in later phases.
|
|
6
10
|
#
|
|
7
11
|
# Optional config (a profile-level patch replaces this block wholesale, so
|
|
8
12
|
# restate every field you want to keep):
|
|
9
13
|
#
|
|
10
14
|
# config:
|
|
11
|
-
# #
|
|
12
|
-
# #
|
|
13
|
-
#
|
|
14
|
-
#
|
|
15
|
-
#
|
|
16
|
-
#
|
|
17
|
-
#
|
|
15
|
+
# cliPath: '' # absolute path to an aiprison binary
|
|
16
|
+
# dataDir: '' # durable ledger directory (default <session cwd>/.ai-prison)
|
|
17
|
+
# timeoutMs: 120000 # per-call CLI timeout
|
|
18
|
+
#
|
|
19
|
+
# The watchdog accepts:
|
|
20
|
+
#
|
|
21
|
+
# config:
|
|
22
|
+
# sampleMs: 5000 # heap sampling interval
|
|
23
|
+
# observe: true # P0 is observe-only; enforcement is not implemented yet
|
|
18
24
|
- insert:
|
|
19
25
|
- id: ai-prison
|
|
20
26
|
name: '@twinsearth/ai-prison-dsh-plugin'
|
|
21
27
|
config: {}
|
|
28
|
+
- id: ai-prison-watchdog
|
|
29
|
+
name: '@twinsearth/ai-prison-dsh-plugin/watchdog'
|
|
30
|
+
config: {}
|
package/lib/tools.js
CHANGED
|
@@ -2,6 +2,8 @@ import path from 'node:path'
|
|
|
2
2
|
import { resolveCli, resolveDataDir, runCli } from './cli.js'
|
|
3
3
|
import { loadDefineTool } from './harness.js'
|
|
4
4
|
import { buildStatus, statusSummary } from './status.js'
|
|
5
|
+
import { watchdogSnapshot } from './watchdog-runtime.js'
|
|
6
|
+
import { formatBytes } from './watchdog-policy.js'
|
|
5
7
|
|
|
6
8
|
const MAX_TEXT = 4_000
|
|
7
9
|
const TAIL_LINES = 60
|
|
@@ -159,6 +161,54 @@ export async function installTools({ ctx, config = {}, logger } = {}) {
|
|
|
159
161
|
},
|
|
160
162
|
})
|
|
161
163
|
|
|
164
|
+
register({
|
|
165
|
+
name: 'ai_prison_watchdog_status',
|
|
166
|
+
description:
|
|
167
|
+
'Read the AI Prison watchdog snapshot (P0 observe mode): host heap usage and limit, derived thresholds, the waterline verdict, per-plugin heap estimates, hot plugin-operation counts and recent incidents (including host crash logs observed at startup). Observe mode never enables or disables a plugin.',
|
|
168
|
+
parameters: {},
|
|
169
|
+
output: stringOutput,
|
|
170
|
+
async execute() {
|
|
171
|
+
const snapshot = watchdogSnapshot()
|
|
172
|
+
if (!snapshot.ok) {
|
|
173
|
+
return toolResult({
|
|
174
|
+
ok: false,
|
|
175
|
+
mode: 'disabled',
|
|
176
|
+
hint: 'watchdog 行未启用:在插件配置里启用 ai-prison-watchdog 后重启即可开始观察。',
|
|
177
|
+
})
|
|
178
|
+
}
|
|
179
|
+
const heap = snapshot.heap || {}
|
|
180
|
+
return toolResult({
|
|
181
|
+
ok: true,
|
|
182
|
+
mode: snapshot.mode,
|
|
183
|
+
dataDir: snapshot.dataDir,
|
|
184
|
+
degraded: snapshot.degraded,
|
|
185
|
+
waterline: snapshot.waterline,
|
|
186
|
+
heap: {
|
|
187
|
+
used: formatBytes(heap.heapUsed),
|
|
188
|
+
total: formatBytes(heap.heapTotal),
|
|
189
|
+
limit: formatBytes(heap.heapLimit),
|
|
190
|
+
rss: formatBytes(heap.rss),
|
|
191
|
+
heapUsedBytes: heap.heapUsed,
|
|
192
|
+
heapLimitBytes: heap.heapLimit,
|
|
193
|
+
},
|
|
194
|
+
thresholds: snapshot.thresholds
|
|
195
|
+
? {
|
|
196
|
+
totalWarn: formatBytes(snapshot.thresholds.totalWarn),
|
|
197
|
+
totalPause: formatBytes(snapshot.thresholds.totalPause),
|
|
198
|
+
totalBlock: formatBytes(snapshot.thresholds.totalBlock),
|
|
199
|
+
singleWarn: formatBytes(snapshot.thresholds.singleWarn),
|
|
200
|
+
singleBlock: formatBytes(snapshot.thresholds.singleBlock),
|
|
201
|
+
opWarn: formatBytes(snapshot.thresholds.opWarn),
|
|
202
|
+
opBlock: formatBytes(snapshot.thresholds.opBlock),
|
|
203
|
+
}
|
|
204
|
+
: null,
|
|
205
|
+
operations: snapshot.operations,
|
|
206
|
+
incidents: snapshot.incidents,
|
|
207
|
+
note: 'observe 模式:仅观察与记录,不自动关闭任何插件。',
|
|
208
|
+
})
|
|
209
|
+
},
|
|
210
|
+
})
|
|
211
|
+
|
|
162
212
|
register({
|
|
163
213
|
name: 'ai_prison_demo',
|
|
164
214
|
description:
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure policy math for the AI Prison watchdog (P0 observe mode).
|
|
3
|
+
* No I/O here: every function takes plain numbers/strings so the panel, the
|
|
4
|
+
* tools and the tests share one definition of the thresholds.
|
|
5
|
+
*/
|
|
6
|
+
export const MB = 1024 * 1024
|
|
7
|
+
export const GB = 1024 * MB
|
|
8
|
+
|
|
9
|
+
/** Thresholds derived from the host heap limit (absolute values clamped to the cap). */
|
|
10
|
+
export function thresholdsFor(heapLimitBytes) {
|
|
11
|
+
const limit = Number(heapLimitBytes) > 0 ? Number(heapLimitBytes) : 4 * GB
|
|
12
|
+
const clamp = (absolute, ratio) => Math.min(absolute, ratio * limit)
|
|
13
|
+
return {
|
|
14
|
+
heapLimit: limit,
|
|
15
|
+
singleWarn: clamp(300 * MB, 0.075),
|
|
16
|
+
singleBlock: clamp(500 * MB, 0.125),
|
|
17
|
+
totalWarn: clamp(3 * GB, 0.73),
|
|
18
|
+
totalPause: clamp(3.9 * GB, 0.88),
|
|
19
|
+
totalBlock: clamp(5 * GB, 0.93),
|
|
20
|
+
opWarn: clamp(4 * GB, 2 / 3),
|
|
21
|
+
opBlock: clamp(5 * GB, 5 / 6),
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Waterline for the whole host: ok | warn | pause | block. */
|
|
26
|
+
export function classifyWaterline(heapUsed, thresholds) {
|
|
27
|
+
if (!thresholds || !(heapUsed >= 0)) return 'ok'
|
|
28
|
+
if (heapUsed >= thresholds.totalBlock) return 'block'
|
|
29
|
+
if (heapUsed >= thresholds.totalPause) return 'pause'
|
|
30
|
+
if (heapUsed >= thresholds.totalWarn) return 'warn'
|
|
31
|
+
return 'ok'
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** How much one plugin operation counts toward the per-target hot-operation limit. */
|
|
35
|
+
export function operationWeight(operation) {
|
|
36
|
+
if (!operation || typeof operation !== 'object') return 0
|
|
37
|
+
const { stage, enabled } = operation
|
|
38
|
+
if (stage === 'install' || stage === 'remove') return 1
|
|
39
|
+
if (stage === 'enable') return enabled === false ? 0.5 : 1
|
|
40
|
+
return 0
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Exponentially weighted estimate of a plugin's heap cost. */
|
|
44
|
+
export function mergeEstimate(previous, next, alpha = 0.5) {
|
|
45
|
+
const value = Number(next)
|
|
46
|
+
if (!Number.isFinite(value) || value < 0) return Number(previous) || 0
|
|
47
|
+
const before = Number(previous)
|
|
48
|
+
if (!Number.isFinite(before) || before <= 0) return value
|
|
49
|
+
return Math.round(before * (1 - alpha) + value * alpha)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Parse the header block of a DSH desktop host crash log. */
|
|
53
|
+
export function parseCrashLog(text) {
|
|
54
|
+
const source = String(text || '')
|
|
55
|
+
const header = source.slice(0, 4000)
|
|
56
|
+
const time = /^time:\s*(.+)$/m.exec(header)
|
|
57
|
+
const phase = /^phase:\s*(.+)$/m.exec(header)
|
|
58
|
+
const exit = /exited with (\d+)/.exec(source)
|
|
59
|
+
const oom = /heap out of memory|Allocation failed|MarkCompactCollector|Scavenger:/i.test(source)
|
|
60
|
+
const fatal = /FATAL ERROR/.test(source)
|
|
61
|
+
return {
|
|
62
|
+
valid: Boolean(time || exit || fatal),
|
|
63
|
+
time: time ? time[1].trim() : null,
|
|
64
|
+
phase: phase ? phase[1].trim() : null,
|
|
65
|
+
hostExitCode: exit ? Number(exit[1]) : null,
|
|
66
|
+
oom,
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** A compact top-N view of the per-target accounting, biggest estimate first. */
|
|
71
|
+
export function topOperations(operations, limit = 5) {
|
|
72
|
+
const rows = []
|
|
73
|
+
for (const [target, entry] of operations instanceof Map ? operations : Object.entries(operations || {})) {
|
|
74
|
+
rows.push({
|
|
75
|
+
target,
|
|
76
|
+
count: Number(entry.count) || 0,
|
|
77
|
+
estimateMB: Number(entry.estimateMB) || 0,
|
|
78
|
+
lastAt: entry.lastAt || null,
|
|
79
|
+
version: entry.version || null,
|
|
80
|
+
})
|
|
81
|
+
}
|
|
82
|
+
rows.sort((a, b) => b.estimateMB - a.estimateMB || b.count - a.count)
|
|
83
|
+
return rows.slice(0, Math.max(1, limit))
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Named byte formatting used by the panel/tool text. */
|
|
87
|
+
export function formatBytes(bytes) {
|
|
88
|
+
const value = Number(bytes)
|
|
89
|
+
if (!Number.isFinite(value) || value < 0) return '—'
|
|
90
|
+
if (value >= GB) return `${(value / GB).toFixed(2)} GB`
|
|
91
|
+
return `${Math.round(value / MB)} MB`
|
|
92
|
+
}
|
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import os from 'node:os'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import v8 from 'node:v8'
|
|
5
|
+
import { watchdogState, MAX_SAMPLES, MAX_INCIDENTS } from './watchdog-state.js'
|
|
6
|
+
import {
|
|
7
|
+
classifyWaterline,
|
|
8
|
+
formatBytes,
|
|
9
|
+
mergeEstimate,
|
|
10
|
+
operationWeight,
|
|
11
|
+
parseCrashLog,
|
|
12
|
+
thresholdsFor,
|
|
13
|
+
topOperations,
|
|
14
|
+
} from './watchdog-policy.js'
|
|
15
|
+
|
|
16
|
+
const SAMPLE_MS = 5_000
|
|
17
|
+
const FLUSH_MS = 30_000
|
|
18
|
+
const CRASH_HEAD_BYTES = 8 * 1024
|
|
19
|
+
const LEVEL_RANK = { ok: 0, warn: 1, pause: 2, block: 3 }
|
|
20
|
+
|
|
21
|
+
function resolveProfileDir() {
|
|
22
|
+
const fromEnv = typeof process.env.DSH_PROFILE_DIR === 'string' && process.env.DSH_PROFILE_DIR.trim()
|
|
23
|
+
if (fromEnv) return fromEnv
|
|
24
|
+
const name = typeof process.env.DSH_PROFILE === 'string' && process.env.DSH_PROFILE.trim() ? process.env.DSH_PROFILE.trim() : 'desktop'
|
|
25
|
+
return path.join(os.homedir(), '.dsh', 'profiles', name)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function resolveLogsDir() {
|
|
29
|
+
const roaming = process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming')
|
|
30
|
+
return path.join(roaming, '@deepseek-ai', 'dsh-desktop', 'logs')
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function readHead(file, bytes) {
|
|
34
|
+
let fd
|
|
35
|
+
try {
|
|
36
|
+
fd = fs.openSync(file, 'r')
|
|
37
|
+
const buffer = Buffer.alloc(bytes)
|
|
38
|
+
const read = fs.readSync(fd, buffer, 0, bytes, 0)
|
|
39
|
+
return buffer.subarray(0, read).toString('utf8')
|
|
40
|
+
} catch {
|
|
41
|
+
return ''
|
|
42
|
+
} finally {
|
|
43
|
+
if (fd !== undefined) {
|
|
44
|
+
try {
|
|
45
|
+
fs.closeSync(fd)
|
|
46
|
+
} catch {
|
|
47
|
+
// ignore
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Read-only watchdog runtime. It observes; it never enables or disables plugins. */
|
|
54
|
+
export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
55
|
+
const profileDir = resolveProfileDir()
|
|
56
|
+
const dataDir = config.dataDir ? path.resolve(String(config.dataDir)) : path.join(profileDir, '.ai-prison-watchdog')
|
|
57
|
+
const logsDir = config.logsDir ? path.resolve(String(config.logsDir)) : resolveLogsDir()
|
|
58
|
+
const stateFile = path.join(dataDir, 'state.json')
|
|
59
|
+
const incidentsFile = path.join(dataDir, 'incidents.jsonl')
|
|
60
|
+
const log = {
|
|
61
|
+
info: (...args) => (typeof logger.info === 'function' ? logger.info(...args) : undefined),
|
|
62
|
+
warn: (...args) => (typeof logger.warn === 'function' ? logger.warn(...args) : undefined),
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
try {
|
|
66
|
+
fs.mkdirSync(dataDir, { recursive: true })
|
|
67
|
+
} catch (error) {
|
|
68
|
+
watchdogState.degraded = `cannot create ${dataDir}: ${String((error && error.message) || error)}`
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
watchdogState.mode = 'observe'
|
|
72
|
+
watchdogState.startedAt = new Date().toISOString()
|
|
73
|
+
watchdogState.dataDir = dataDir
|
|
74
|
+
watchdogState.config = { sampleMs: SAMPLE_MS, ...config }
|
|
75
|
+
watchdogState.lastCrashScan = 0
|
|
76
|
+
let lastFlush = 0
|
|
77
|
+
const cleanups = []
|
|
78
|
+
const effect = (fn, label) => {
|
|
79
|
+
const disposer = ctx.effect(fn, label)
|
|
80
|
+
if (typeof disposer === 'function') cleanups.push(disposer)
|
|
81
|
+
return disposer
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
restoreState()
|
|
85
|
+
readCrashLogs()
|
|
86
|
+
|
|
87
|
+
function restoreState() {
|
|
88
|
+
try {
|
|
89
|
+
const parsed = JSON.parse(fs.readFileSync(stateFile, 'utf8'))
|
|
90
|
+
watchdogState.lastCrashScan = Number(parsed.lastCrashScan) > 0 ? Number(parsed.lastCrashScan) : 0
|
|
91
|
+
if (Array.isArray(parsed.incidents)) {
|
|
92
|
+
watchdogState.incidents = parsed.incidents.slice(-MAX_INCIDENTS)
|
|
93
|
+
}
|
|
94
|
+
} catch {
|
|
95
|
+
// first run or unreadable state: start clean
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function appendIncident(incident) {
|
|
100
|
+
const record = { at: new Date().toISOString(), mode: watchdogState.mode, ...incident }
|
|
101
|
+
watchdogState.incidents.push(record)
|
|
102
|
+
if (watchdogState.incidents.length > MAX_INCIDENTS) {
|
|
103
|
+
watchdogState.incidents = watchdogState.incidents.slice(-MAX_INCIDENTS)
|
|
104
|
+
}
|
|
105
|
+
try {
|
|
106
|
+
fs.appendFileSync(incidentsFile, `${JSON.stringify(record)}\n`)
|
|
107
|
+
const stat = fs.statSync(incidentsFile)
|
|
108
|
+
if (stat.size > 1024 * 1024) {
|
|
109
|
+
const lines = fs.readFileSync(incidentsFile, 'utf8').trim().split('\n').slice(-500)
|
|
110
|
+
fs.writeFileSync(incidentsFile, `${lines.join('\n')}\n`)
|
|
111
|
+
}
|
|
112
|
+
} catch {
|
|
113
|
+
// auditing is best-effort in observe mode
|
|
114
|
+
}
|
|
115
|
+
return record
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function persist(force = false) {
|
|
119
|
+
const now = Date.now()
|
|
120
|
+
if (!force && now - lastFlush < FLUSH_MS) return
|
|
121
|
+
lastFlush = now
|
|
122
|
+
const payload = {
|
|
123
|
+
startedAt: watchdogState.startedAt,
|
|
124
|
+
lastCrashScan: watchdogState.lastCrashScan,
|
|
125
|
+
incidents: watchdogState.incidents.slice(-50),
|
|
126
|
+
}
|
|
127
|
+
try {
|
|
128
|
+
fs.writeFileSync(stateFile, `${JSON.stringify(payload, null, 2)}\n`)
|
|
129
|
+
} catch {
|
|
130
|
+
// ignore
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function sample() {
|
|
135
|
+
let heap
|
|
136
|
+
try {
|
|
137
|
+
heap = v8.getHeapStatistics()
|
|
138
|
+
} catch {
|
|
139
|
+
heap = { heap_size_limit: 0, used_heap_size: 0, total_heap_size: 0 }
|
|
140
|
+
}
|
|
141
|
+
const usage = process.memoryUsage()
|
|
142
|
+
const heapLimit = Number(heap.heap_size_limit) > 0 ? Number(heap.heap_size_limit) : 4 * 1024 * 1024 * 1024
|
|
143
|
+
watchdogState.thresholds = thresholdsFor(heapLimit)
|
|
144
|
+
const heapUsed = Number(usage.heapUsed) > 0 ? Number(usage.heapUsed) : Number(heap.used_heap_size) || 0
|
|
145
|
+
const waterline = classifyWaterline(heapUsed, watchdogState.thresholds)
|
|
146
|
+
const previous = watchdogState.waterline
|
|
147
|
+
const record = {
|
|
148
|
+
t: new Date().toISOString(),
|
|
149
|
+
heapUsed,
|
|
150
|
+
heapTotal: Number(usage.heapTotal) || Number(heap.total_heap_size) || 0,
|
|
151
|
+
external: Number(usage.external) || 0,
|
|
152
|
+
rss: Number(usage.rss) || 0,
|
|
153
|
+
heapLimit,
|
|
154
|
+
waterline,
|
|
155
|
+
}
|
|
156
|
+
watchdogState.latest = record
|
|
157
|
+
watchdogState.waterline = waterline
|
|
158
|
+
watchdogState.samples.push(record)
|
|
159
|
+
if (watchdogState.samples.length > MAX_SAMPLES) {
|
|
160
|
+
watchdogState.samples = watchdogState.samples.slice(-MAX_SAMPLES)
|
|
161
|
+
}
|
|
162
|
+
if (waterline !== previous && LEVEL_RANK[waterline] > LEVEL_RANK[previous]) {
|
|
163
|
+
const incident = appendIncident({
|
|
164
|
+
kind: 'waterline',
|
|
165
|
+
level: waterline,
|
|
166
|
+
heapUsed,
|
|
167
|
+
heapLimit,
|
|
168
|
+
detail: `heap ${formatBytes(heapUsed)} / limit ${formatBytes(heapLimit)}`,
|
|
169
|
+
})
|
|
170
|
+
log.warn(`[ai-prison-watchdog] waterline ${waterline}: ${incident.detail}(observe 模式,不关闭插件)`)
|
|
171
|
+
persist(true)
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** target -> { heapBefore } for operations currently in flight. */
|
|
176
|
+
const inflight = new Map()
|
|
177
|
+
|
|
178
|
+
function onOperation(operation) {
|
|
179
|
+
try {
|
|
180
|
+
if (!operation || typeof operation !== 'object') return
|
|
181
|
+
const target = typeof operation.target === 'string' && operation.target ? operation.target : null
|
|
182
|
+
if (!target || operation.reason === 'remove') {
|
|
183
|
+
if (operation.phase === 'settled' && target) {
|
|
184
|
+
watchdogState.operations.delete(target)
|
|
185
|
+
}
|
|
186
|
+
return
|
|
187
|
+
}
|
|
188
|
+
const entry = watchdogState.operations.get(target) || {
|
|
189
|
+
count: 0,
|
|
190
|
+
estimateMB: 0,
|
|
191
|
+
lastAt: null,
|
|
192
|
+
version: operation.version || null,
|
|
193
|
+
lastApplication: null,
|
|
194
|
+
}
|
|
195
|
+
if (operation.phase === 'started') {
|
|
196
|
+
inflight.set(operation.id, { target, heapBefore: watchdogState.latest ? watchdogState.latest.heapUsed : 0 })
|
|
197
|
+
entry.lastAt = operation.time || entry.lastAt
|
|
198
|
+
watchdogState.operations.set(target, entry)
|
|
199
|
+
return
|
|
200
|
+
}
|
|
201
|
+
if (operation.phase === 'settled') {
|
|
202
|
+
const weight = operationWeight(operation)
|
|
203
|
+
if (weight > 0 && operation.application !== 'failed') {
|
|
204
|
+
entry.count = Math.round((Number(entry.count) + weight) * 10) / 10
|
|
205
|
+
}
|
|
206
|
+
const before = inflight.get(operation.id)
|
|
207
|
+
inflight.delete(operation.id)
|
|
208
|
+
if (before && watchdogState.latest && before.heapBefore > 0) {
|
|
209
|
+
const deltaMB = Math.max(0, Math.round((watchdogState.latest.heapUsed - before.heapBefore) / (1024 * 1024)))
|
|
210
|
+
entry.estimateMB = mergeEstimate(entry.estimateMB, deltaMB)
|
|
211
|
+
}
|
|
212
|
+
entry.lastAt = operation.time || entry.lastAt
|
|
213
|
+
entry.version = operation.version || entry.version
|
|
214
|
+
entry.lastApplication = operation.application || null
|
|
215
|
+
watchdogState.operations.set(target, entry)
|
|
216
|
+
const thresholds = watchdogState.thresholds
|
|
217
|
+
if (thresholds && entry.estimateMB >= Math.round(thresholds.singleWarn / (1024 * 1024))) {
|
|
218
|
+
appendIncident({
|
|
219
|
+
kind: 'plugin-estimate',
|
|
220
|
+
target,
|
|
221
|
+
estimateMB: entry.estimateMB,
|
|
222
|
+
level: entry.estimateMB >= Math.round(thresholds.singleBlock / (1024 * 1024)) ? 'block' : 'warn',
|
|
223
|
+
detail: `${target} 估算 ${entry.estimateMB} MB(observe 模式,仅提醒)`,
|
|
224
|
+
})
|
|
225
|
+
}
|
|
226
|
+
persist(true)
|
|
227
|
+
}
|
|
228
|
+
} catch (error) {
|
|
229
|
+
watchdogState.degraded = `operation handler: ${String((error && error.message) || error)}`
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function readCrashLogs() {
|
|
234
|
+
let entries
|
|
235
|
+
try {
|
|
236
|
+
entries = fs.readdirSync(logsDir, { withFileTypes: true })
|
|
237
|
+
} catch {
|
|
238
|
+
return
|
|
239
|
+
}
|
|
240
|
+
let newest = watchdogState.lastCrashScan
|
|
241
|
+
for (const entry of entries) {
|
|
242
|
+
if (!entry.isFile() || !/^crash-.*-host\.log$/.test(entry.name)) continue
|
|
243
|
+
const file = path.join(logsDir, entry.name)
|
|
244
|
+
let stat
|
|
245
|
+
try {
|
|
246
|
+
stat = fs.statSync(file)
|
|
247
|
+
} catch {
|
|
248
|
+
continue
|
|
249
|
+
}
|
|
250
|
+
if (stat.mtimeMs <= watchdogState.lastCrashScan) continue
|
|
251
|
+
const parsed = parseCrashLog(readHead(file, CRASH_HEAD_BYTES))
|
|
252
|
+
if (!parsed.valid) continue
|
|
253
|
+
appendIncident({
|
|
254
|
+
kind: 'crash',
|
|
255
|
+
file: entry.name,
|
|
256
|
+
time: parsed.time,
|
|
257
|
+
phase: parsed.phase,
|
|
258
|
+
hostExitCode: parsed.hostExitCode,
|
|
259
|
+
oom: parsed.oom,
|
|
260
|
+
detail: parsed.oom ? 'JavaScript heap out of memory' : `host exited with ${parsed.hostExitCode ?? '?'}`,
|
|
261
|
+
})
|
|
262
|
+
if (stat.mtimeMs > newest) newest = stat.mtimeMs
|
|
263
|
+
}
|
|
264
|
+
if (newest > watchdogState.lastCrashScan) {
|
|
265
|
+
watchdogState.lastCrashScan = newest
|
|
266
|
+
persist(true)
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// Sampler (P0: observe only).
|
|
271
|
+
try {
|
|
272
|
+
if (typeof ctx.effect === 'function') {
|
|
273
|
+
effect(() => {
|
|
274
|
+
sample()
|
|
275
|
+
const interval = Number(config.sampleMs) > 0 ? Number(config.sampleMs) : SAMPLE_MS
|
|
276
|
+
const timer = setInterval(sample, interval)
|
|
277
|
+
return () => clearInterval(timer)
|
|
278
|
+
}, 'ai-prison-watchdog: sampler')
|
|
279
|
+
} else {
|
|
280
|
+
sample()
|
|
281
|
+
setInterval(sample, SAMPLE_MS)
|
|
282
|
+
}
|
|
283
|
+
} catch (error) {
|
|
284
|
+
watchdogState.degraded = `sampler: ${String((error && error.message) || error)}`
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// Plugin-operation accounting.
|
|
288
|
+
try {
|
|
289
|
+
if (typeof ctx.on === 'function') {
|
|
290
|
+
if (typeof ctx.effect === 'function') {
|
|
291
|
+
effect(() => ctx.on('plugin-manager/operation', onOperation), 'ai-prison-watchdog: operations')
|
|
292
|
+
} else {
|
|
293
|
+
ctx.on('plugin-manager/operation', onOperation)
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
} catch (error) {
|
|
297
|
+
watchdogState.degraded = `operations: ${String((error && error.message) || error)}`
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// Read-only HTTP snapshot for the panel.
|
|
301
|
+
try {
|
|
302
|
+
if (typeof ctx.inject === 'function') {
|
|
303
|
+
ctx.inject(['connection'], (child) => {
|
|
304
|
+
try {
|
|
305
|
+
child.effect(
|
|
306
|
+
() =>
|
|
307
|
+
child.connection.fetch.register({
|
|
308
|
+
path: '/api/ai-prison/watchdog/status',
|
|
309
|
+
methods: ['GET'],
|
|
310
|
+
requestBody: 'buffered',
|
|
311
|
+
fetch: async () =>
|
|
312
|
+
Response.json(watchdogSnapshot(), { headers: { 'cache-control': 'no-store' } }),
|
|
313
|
+
}),
|
|
314
|
+
'ai-prison-watchdog: status api',
|
|
315
|
+
)
|
|
316
|
+
} catch (error) {
|
|
317
|
+
watchdogState.degraded = `status api: ${String((error && error.message) || error)}`
|
|
318
|
+
}
|
|
319
|
+
})
|
|
320
|
+
}
|
|
321
|
+
} catch (error) {
|
|
322
|
+
watchdogState.degraded = `connection: ${String((error && error.message) || error)}`
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
log.info(`[ai-prison-watchdog] observe 模式已启动(数据目录 ${dataDir})`)
|
|
326
|
+
return {
|
|
327
|
+
snapshot: watchdogSnapshot,
|
|
328
|
+
sample,
|
|
329
|
+
readCrashLogs,
|
|
330
|
+
dispose() {
|
|
331
|
+
while (cleanups.length > 0) {
|
|
332
|
+
const disposer = cleanups.pop()
|
|
333
|
+
try {
|
|
334
|
+
disposer()
|
|
335
|
+
} catch {
|
|
336
|
+
// ignore dispose races
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
},
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Serialisable snapshot shared by the tool and the panel route. */
|
|
344
|
+
export function watchdogSnapshot() {
|
|
345
|
+
const s = watchdogState
|
|
346
|
+
return {
|
|
347
|
+
ok: Boolean(s.startedAt),
|
|
348
|
+
mode: s.mode,
|
|
349
|
+
startedAt: s.startedAt,
|
|
350
|
+
dataDir: s.dataDir,
|
|
351
|
+
degraded: s.degraded,
|
|
352
|
+
heap: s.latest,
|
|
353
|
+
thresholds: s.thresholds,
|
|
354
|
+
waterline: s.waterline,
|
|
355
|
+
samples: s.samples.slice(-30),
|
|
356
|
+
operations: topOperations(s.operations, 10),
|
|
357
|
+
incidents: s.incidents.slice(-20),
|
|
358
|
+
generatedAt: new Date().toISOString(),
|
|
359
|
+
}
|
|
360
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared in-process state of the AI Prison watchdog. The watchdog loader row
|
|
3
|
+
* writes it; the panel tool and the HTTP route read it. Same package, same Node
|
|
4
|
+
* process, so one module instance is enough (no service plumbing needed).
|
|
5
|
+
*/
|
|
6
|
+
export const watchdogState = {
|
|
7
|
+
mode: 'observe',
|
|
8
|
+
startedAt: null,
|
|
9
|
+
dataDir: null,
|
|
10
|
+
config: {},
|
|
11
|
+
/** Latest metrics sample. */
|
|
12
|
+
latest: null,
|
|
13
|
+
/** Ring of recent metrics samples (oldest first). */
|
|
14
|
+
samples: [],
|
|
15
|
+
thresholds: null,
|
|
16
|
+
waterline: 'ok',
|
|
17
|
+
/** target -> { count, estimateMB, lastAt, version, lastApplication } */
|
|
18
|
+
operations: new Map(),
|
|
19
|
+
/** Recent incidents (newest last), capped. */
|
|
20
|
+
incidents: [],
|
|
21
|
+
/** Last crash-log scan marker (ms). */
|
|
22
|
+
lastCrashScan: 0,
|
|
23
|
+
/** Non-fatal degradation reason, if any. */
|
|
24
|
+
degraded: null,
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export const MAX_SAMPLES = 120
|
|
28
|
+
export const MAX_INCIDENTS = 200
|
|
29
|
+
|
|
30
|
+
export function resetWatchdogState(overrides = {}) {
|
|
31
|
+
watchdogState.mode = 'observe'
|
|
32
|
+
watchdogState.startedAt = null
|
|
33
|
+
watchdogState.dataDir = null
|
|
34
|
+
watchdogState.config = {}
|
|
35
|
+
watchdogState.latest = null
|
|
36
|
+
watchdogState.samples = []
|
|
37
|
+
watchdogState.thresholds = null
|
|
38
|
+
watchdogState.waterline = 'ok'
|
|
39
|
+
watchdogState.operations = new Map()
|
|
40
|
+
watchdogState.incidents = []
|
|
41
|
+
watchdogState.lastCrashScan = 0
|
|
42
|
+
watchdogState.degraded = null
|
|
43
|
+
Object.assign(watchdogState, overrides)
|
|
44
|
+
return watchdogState
|
|
45
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@twinsearth/ai-prison-dsh-plugin",
|
|
3
|
-
"version": "1.1
|
|
3
|
+
"version": "1.2.1",
|
|
4
4
|
"description": "AI Prison for DSH: six governance tools wrapping the aiprison CLI (levels, demo, drill, inspect, verify, repair-tail) plus a panel for the L0–L5 matrix and the audit-chain state. The CLI ships bundled for Windows, macOS and Linux; every capability-removal backend stays simulated.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "index.js",
|
|
@@ -37,11 +37,13 @@
|
|
|
37
37
|
"./client": "./client.js",
|
|
38
38
|
"./package.json": "./package.json",
|
|
39
39
|
"./locale/*.json": "./locale/*.json",
|
|
40
|
-
"./icon": "./icon.svg"
|
|
40
|
+
"./icon": "./icon.svg",
|
|
41
|
+
"./watchdog": "./watchdog.js"
|
|
41
42
|
},
|
|
42
43
|
"files": [
|
|
43
44
|
"index.js",
|
|
44
45
|
"client.js",
|
|
46
|
+
"watchdog.js",
|
|
45
47
|
"lib/*.js",
|
|
46
48
|
"cordis.patch.yml",
|
|
47
49
|
"locale/*.json",
|
package/watchdog.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { createWatchdog } from './lib/watchdog-runtime.js'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* AI Prison watchdog loader row (P0: observe only).
|
|
5
|
+
*
|
|
6
|
+
* It samples the host heap, accounts plugin operations, reads recent host crash
|
|
7
|
+
* logs and serves a read-only snapshot at /api/ai-prison/watchdog/status.
|
|
8
|
+
* It never enables or disables a plugin: enforcement stays in later phases until
|
|
9
|
+
* the design is confirmed.
|
|
10
|
+
*/
|
|
11
|
+
export function apply(ctx, config = {}) {
|
|
12
|
+
const logger = ctx && typeof ctx === 'object' ? ctx.logger : undefined
|
|
13
|
+
try {
|
|
14
|
+
createWatchdog(ctx, config, logger || {})
|
|
15
|
+
} catch (error) {
|
|
16
|
+
const message = String((error && error.stack) || error)
|
|
17
|
+
if (logger && typeof logger.warn === 'function') logger.warn(`[ai-prison-watchdog] 启动失败:${message}`)
|
|
18
|
+
else console.warn('[ai-prison-watchdog] 启动失败', message)
|
|
19
|
+
}
|
|
20
|
+
}
|