@twinsearth/ai-prison-dsh-plugin 1.8.0 → 1.9.3
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 +89 -0
- package/README.md +7 -5
- package/bin/linux-amd64/aiprison +0 -0
- package/bin/linux-arm64/aiprison +0 -0
- package/bin/macos-amd64/aiprison +0 -0
- package/bin/macos-arm64/aiprison +0 -0
- package/bin/windows-amd64/aiprison.exe +0 -0
- package/bin/windows-arm64/aiprison.exe +0 -0
- package/client.js +107 -41
- package/docs/DETAIL.md +31 -0
- package/docs/DETAIL.zh.md +19 -0
- package/docs/SUPPLY-CHAIN.md +4 -2
- package/lib/api.js +9 -5
- package/lib/boot-watch.js +1 -1
- package/lib/ledger.js +15 -3
- package/lib/remediation.js +1 -1
- package/lib/tools.js +58 -19
- package/lib/watchdog-budget.js +63 -37
- package/lib/watchdog-core.js +34 -4
- package/lib/watchdog-crash.js +7 -3
- package/lib/watchdog-enforcement.js +28 -7
- package/lib/watchdog-persistence.js +8 -1
- package/lib/watchdog-policy.js +13 -2
- package/lib/watchdog-runtime.js +3 -0
- package/lib/watchdog-snapshot.js +8 -5
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,95 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `@twinsearth/ai-prison-dsh-plugin` are recorded here.
|
|
4
4
|
|
|
5
|
+
## [1.9.3] — 2026-11-25
|
|
6
|
+
|
|
7
|
+
### Fixed — ledger repair is now byte-exact and crash-safe
|
|
8
|
+
|
|
9
|
+
- `repair-tail` keeps the `\n` that terminates the last committed record, so a
|
|
10
|
+
repaired segment is byte-identical to its pre-tear state and stays appendable.
|
|
11
|
+
1.9.2 dropped that newline, which turned a 7-byte torn tail into a
|
|
12
|
+
53,323 → 53,322 B file whose last record had no terminator, and reported
|
|
13
|
+
"removed 7 bytes" while the file had actually lost 8.
|
|
14
|
+
- The repair rewrite is published through a temp file plus atomic rename instead
|
|
15
|
+
of `O_TRUNC` in place. A crash during repair can no longer widen a few torn
|
|
16
|
+
bytes into a fully truncated segment; a leftover `.seg-*.tmp` is discarded on
|
|
17
|
+
the next open.
|
|
18
|
+
- `segmentForSeq` now names the segment that actually holds the failing sequence
|
|
19
|
+
(the last segment whose start is ≤ seq). Multi-segment ledgers no longer blame
|
|
20
|
+
`seg-0000000000.log` for a fault that happened in a later segment.
|
|
21
|
+
|
|
22
|
+
### Tests
|
|
23
|
+
|
|
24
|
+
- New `internal/store/repair_test.go`:
|
|
25
|
+
`TestRepairTornTailRestoresExactBytes` (restores the exact bytes, keeps the
|
|
26
|
+
trailing newline, leaves no temp file, stays appendable and re-verifies),
|
|
27
|
+
`TestRepairTornTailLongerTail`, and `TestIntegrityErrorNamesTheRightSegment`
|
|
28
|
+
(fails against the 1.9.2 attribution logic, passes after the fix).
|
|
29
|
+
|
|
30
|
+
### Packaging
|
|
31
|
+
|
|
32
|
+
- CLI stays at **1.0.9** (same feature set); the bundled six-platform binaries
|
|
33
|
+
are rebuilt against this release, so `aiprison version -v` reports a
|
|
34
|
+
different `commit:` than the 1.9.2 build and the two builds stay
|
|
35
|
+
distinguishable.
|
|
36
|
+
|
|
37
|
+
## [1.9.2] — 2026-11-25
|
|
38
|
+
|
|
39
|
+
### Fixed — data safety and platform truth
|
|
40
|
+
|
|
41
|
+
- `reset` now probes the resolved CLI before touching the ledger; a missing
|
|
42
|
+
`cliPath` returns 409 and leaves `seg-*.log` untouched. Ledger segments move
|
|
43
|
+
to `<data_dir>/.trash/<UTC>/` instead of being deleted.
|
|
44
|
+
- macOS crash logs resolve to Electron's `~/Library/Logs/DeepSeek Harness`
|
|
45
|
+
(journal remains under `~/Library/Application Support/@deepseek-ai/dsh-desktop`);
|
|
46
|
+
Windows/Linux use their Electron `logs` roots. `DSH_LOG_DIR` and
|
|
47
|
+
`DSH_JOURNAL_DIR` override both.
|
|
48
|
+
- Memory thresholds expose `nominal`, `effective` and `display`; MemoryCard
|
|
49
|
+
reads `watchdog.waterline` instead of recomputing 30/70/95 from heap bytes.
|
|
50
|
+
6 GB hosts now display 2.7/3.6/4.7 GB (4 GB: 2.62/3.22/3.42 GB).
|
|
51
|
+
- Budget remediation no longer claims a pending-boot consumer that the shipped
|
|
52
|
+
package does not have; the panel shows `consumer:'none'` and the manual step.
|
|
53
|
+
|
|
54
|
+
### Fixed — silent failures and asymmetric boundaries
|
|
55
|
+
|
|
56
|
+
- Budget probing sets `probeRunning` before the first await, always clears it
|
|
57
|
+
through `try/finally`, and ignores stale generations after a restart.
|
|
58
|
+
- Panel polls use an AbortController and skip while a request is in flight;
|
|
59
|
+
watchdog actions validate `response.ok && payload.ok` and surface the error.
|
|
60
|
+
- Quarantine remediation and `heap6g` survive a restart; a
|
|
61
|
+
`heap6g-request.json` on disk wins over a stale state file.
|
|
62
|
+
- Agent tools reuse the panel's `resolveAllowedDataDir`; `/etc` and arbitrary
|
|
63
|
+
directories return `data-dir-not-allowed`. `demo`, `drill` and `repair-tail`
|
|
64
|
+
require `confirm: true`. `ai_prison_levels` no longer advertises an unused
|
|
65
|
+
`data_dir`.
|
|
66
|
+
- Crash enforcement retries with exponential backoff to 30 seconds, so a
|
|
67
|
+
plugin manager that arrives after 500 ms still gets the plan; degraded is
|
|
68
|
+
only reported on a real timeout.
|
|
69
|
+
- Tamper policy `alert` now records a notification event distinct from
|
|
70
|
+
`observe`, instead of behaving identically.
|
|
71
|
+
- `all-third-party` closes at most five third-party plugins per check and lists
|
|
72
|
+
the rest as `thirdPartyPending`; the panel shows the impact scope.
|
|
73
|
+
- README thresholds and SUPPLY-CHAIN package sizes are asserted against the
|
|
74
|
+
code and the measured tarball.
|
|
75
|
+
|
|
76
|
+
### Changed — cleanup and docs
|
|
77
|
+
|
|
78
|
+
- Removed the dead boot-watch ternary, the contradictory PrisonCard empty
|
|
79
|
+
state, the double TopN computation, and the hand-written action list in the
|
|
80
|
+
400 error. `docs/DETAIL*.md` now carry a real body after the preview image.
|
|
81
|
+
- Added regression tests for the missing-CLI reset, platform paths, threshold
|
|
82
|
+
display, budget recovery, late manager, alert/observe difference, persistence,
|
|
83
|
+
agent allow-list, confirmation, third-party cap and documentation constants.
|
|
84
|
+
v1.9.2 ships the rebuilt six-platform CLI binaries (CLI 1.0.9).
|
|
85
|
+
|
|
86
|
+
### Fixed — build metadata drift
|
|
87
|
+
|
|
88
|
+
- `Makefile` now derives `VERSION` from `cmd/aiprison/main.go` instead of
|
|
89
|
+
defaulting to `1.0.0`; `make smoke` can no longer silently rebuild a
|
|
90
|
+
mislabelled binary.
|
|
91
|
+
- `scripts/build-binaries.mjs` imports `node:fs`, so the no-env local build can
|
|
92
|
+
resolve the declared CLI version instead of throwing "cannot determine".
|
|
93
|
+
|
|
5
94
|
## [1.8.0] — 2026-11-21
|
|
6
95
|
|
|
7
96
|
### Added — external memory supervisor
|
package/README.md
CHANGED
|
@@ -48,8 +48,10 @@ or a second `drill`, would otherwise fail).
|
|
|
48
48
|
|
|
49
49
|
A second loader row (`ai-prison-watchdog`) samples the host heap every 5 seconds,
|
|
50
50
|
derives the design thresholds from the real heap limit (300/500 MB per plugin;
|
|
51
|
-
3.0/3.9/5.0 GB and operation gates 4/5 GB on a 6 GB host,
|
|
52
|
-
2.
|
|
51
|
+
nominal 3.0/3.9/5.0 GB and operation gates 4/5 GB on a 6 GB host, first-trigger
|
|
52
|
+
effective 2.7/3.6/4.7 GB after the 0.3 GB freeze margin; 4 GB hosts map to
|
|
53
|
+
nominal 2.92/3.52/3.72 GB, effective 2.62/3.22/3.42 GB, with operation gates
|
|
54
|
+
2.73/3.41 GB), accounts plugin operations
|
|
53
55
|
(install/remove = 1, enable = 1, disable = 0.5), estimates each plugin's heap
|
|
54
56
|
delta around those operations, reads new `crash-*-host.log` files at startup and
|
|
55
57
|
records a 500 ms startup curve into `.ai-prison-watchdog/run-*.jsonl`.
|
|
@@ -109,9 +111,9 @@ library, `CGO_ENABLED=0`, no module downloads) and are not committed to git.
|
|
|
109
111
|
|
|
110
112
|
### Per-platform packaging (size)
|
|
111
113
|
|
|
112
|
-
The published npm tarball carries all six CLIs (
|
|
113
|
-
single-machine deployment, build a platform-lite
|
|
114
|
-
`bin/<platform>-<arch>/` tree:
|
|
114
|
+
The published npm tarball carries all six CLIs (6.8 MB packed, 16.1 MB unpacked;
|
|
115
|
+
each binary 2.6–2.8 MB). For a single-machine deployment, build a platform-lite
|
|
116
|
+
tarball that keeps only one `bin/<platform>-<arch>/` tree:
|
|
115
117
|
|
|
116
118
|
```bash
|
|
117
119
|
cd dsh-plugin
|
package/bin/linux-amd64/aiprison
CHANGED
|
Binary file
|
package/bin/linux-arm64/aiprison
CHANGED
|
Binary file
|
package/bin/macos-amd64/aiprison
CHANGED
|
Binary file
|
package/bin/macos-arm64/aiprison
CHANGED
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/client.js
CHANGED
|
@@ -44,11 +44,11 @@ window.__ModuleLoader__.load({
|
|
|
44
44
|
'action.loading': 'Reading…',
|
|
45
45
|
'action.runDemo': 'Run demo',
|
|
46
46
|
'action.runDrill': 'Run drill',
|
|
47
|
-
'action.confirmRun': 'Click again:
|
|
47
|
+
'action.confirmRun': 'Click again: move {records} segments to .trash and run',
|
|
48
48
|
'action.running': 'Running…',
|
|
49
49
|
'ledger.actions': 'Explicit actions',
|
|
50
|
-
'ledger.actionsHint': 'These buttons run the bundled CLI.
|
|
51
|
-
'ledger.resetHint': 'The ledger already exists: a run
|
|
50
|
+
'ledger.actionsHint': 'These buttons run the bundled CLI. Existing segments are moved to .trash first, so every run starts from a consistent baseline.',
|
|
51
|
+
'ledger.resetHint': 'The ledger already exists: a run moves its segments to .trash first, then executes. Click twice to confirm.',
|
|
52
52
|
'ledger.lastAction': 'Last action',
|
|
53
53
|
'meta.updated': 'Updated {time}',
|
|
54
54
|
'meta.readonly': 'Read-only view: the panel never writes by itself; only the buttons above do.',
|
|
@@ -56,12 +56,14 @@ window.__ModuleLoader__.load({
|
|
|
56
56
|
'watchdog.mode': 'Observe mode: records only, never closes plugins',
|
|
57
57
|
'watchdog.modeEnforce': 'Enforce mode: over-limit operations are rolled back, closed or quarantined',
|
|
58
58
|
'watchdog.enforceTitle': 'Enforcement',
|
|
59
|
+
'watchdog.actionError': 'Panel action failed',
|
|
59
60
|
'watchdog.enforceOn': 'enforce',
|
|
60
61
|
'watchdog.observeOnly': 'observe only',
|
|
61
62
|
'watchdog.freezeHint': 'Heap is frozen at {level}: plugin operations are blocked except release actions. Close the biggest plugins below or restart DSH.',
|
|
62
63
|
'watchdog.confirmPause': 'I understand: allow plugin operations for 10 minutes',
|
|
63
64
|
'watchdog.quarantine': 'Plugin prison',
|
|
64
65
|
'watchdog.noQuarantine': 'No quarantined plugins.',
|
|
66
|
+
'watchdog.thirdPartyPending': 'Third-party plugins awaiting manual review (cap hit): {n}',
|
|
65
67
|
'watchdog.release': 'Release',
|
|
66
68
|
'watchdog.topFive': 'Top {n} by estimated heap',
|
|
67
69
|
'watchdog.close': 'Arrest now',
|
|
@@ -74,6 +76,7 @@ window.__ModuleLoader__.load({
|
|
|
74
76
|
'watchdog.heap6gOn': 'Cancel the 6 GB heap request',
|
|
75
77
|
'watchdog.heap6gPending': 'Written to the watchdog state directory; an external launcher must consume it (none is installed right now).',
|
|
76
78
|
'watchdog.pendingBoot': 'pending-boot plan ({level}) was written, but no external consumer is installed: only this run\'s in-process isolation applies. Handle the next start manually.',
|
|
79
|
+
'watchdog.pendingBootConsumer': 'consumer: {consumer}',
|
|
77
80
|
'watchdog.disabled': 'Watchdog row not enabled; heap observation is unavailable.',
|
|
78
81
|
'watchdog.heap': 'Heap used',
|
|
79
82
|
'watchdog.limit': 'Heap limit',
|
|
@@ -86,6 +89,7 @@ window.__ModuleLoader__.load({
|
|
|
86
89
|
'waterline.danger': 'Danger',
|
|
87
90
|
'waterline.warn': 'Warning',
|
|
88
91
|
'waterline.pause': 'Paused',
|
|
92
|
+
'waterline.frost': 'Frozen',
|
|
89
93
|
'waterline.block': 'Blocked',
|
|
90
94
|
'prison.title': 'Plugin prison',
|
|
91
95
|
'prison.top': 'Top {n} plugins by estimated heap',
|
|
@@ -146,11 +150,11 @@ window.__ModuleLoader__.load({
|
|
|
146
150
|
'action.loading': '读取中…',
|
|
147
151
|
'action.runDemo': '运行 demo',
|
|
148
152
|
'action.runDrill': '运行演练',
|
|
149
|
-
'action.confirmRun': '
|
|
153
|
+
'action.confirmRun': '再次点击:将 {records} 条记录移入 .trash 并运行',
|
|
150
154
|
'action.running': '运行中…',
|
|
151
155
|
'ledger.actions': '显式操作',
|
|
152
|
-
'ledger.actionsHint': '这些按钮运行内置 CLI
|
|
153
|
-
'ledger.resetHint': '
|
|
156
|
+
'ledger.actionsHint': '这些按钮运行内置 CLI;账本已存在时会先把账本段移入 .trash,保证每次从一致基线开始。',
|
|
157
|
+
'ledger.resetHint': '账本已存在:运行会先移入 .trash 再执行;再次点击确认。',
|
|
154
158
|
'ledger.lastAction': '最近操作',
|
|
155
159
|
'meta.updated': '更新于 {time}',
|
|
156
160
|
'meta.readonly': '只读视图:面板不会自行写入账本,只有上方按钮会写入。',
|
|
@@ -158,12 +162,14 @@ window.__ModuleLoader__.load({
|
|
|
158
162
|
'watchdog.mode': '观察模式:只记录,不关闭插件',
|
|
159
163
|
'watchdog.modeEnforce': '执行模式:超限操作会被回滚、关闭或隔离',
|
|
160
164
|
'watchdog.enforceTitle': '执行状态',
|
|
165
|
+
'watchdog.actionError': '面板操作失败',
|
|
161
166
|
'watchdog.enforceOn': '执行中',
|
|
162
167
|
'watchdog.observeOnly': '仅观察',
|
|
163
168
|
'watchdog.freezeHint': '堆水位已冻结({level}):除释放类操作外,所有插件操作被禁止。请关闭下方内存最大的插件或重启 DSH。',
|
|
164
169
|
'watchdog.confirmPause': '我已知晓:允许插件操作 10 分钟',
|
|
165
170
|
'watchdog.quarantine': '插件监狱',
|
|
166
171
|
'watchdog.noQuarantine': '没有被隔离的插件。',
|
|
172
|
+
'watchdog.thirdPartyPending': '待人工处理的第三方插件(触发上限):{n}',
|
|
167
173
|
'watchdog.release': '假释',
|
|
168
174
|
'watchdog.topFive': '按估算内存排序的前 {n} 个插件',
|
|
169
175
|
'watchdog.close': '立即缉拿',
|
|
@@ -176,6 +182,7 @@ window.__ModuleLoader__.load({
|
|
|
176
182
|
'watchdog.heap6gOn': '取消 6GB 堆请求',
|
|
177
183
|
'watchdog.heap6gPending': '已写入 watchdog 状态目录;需要外部启动器消费(当前未安装)。',
|
|
178
184
|
'watchdog.pendingBoot': '已写入 pending-boot 计划({level}),但当前未安装外部消费器:只有本次运行内的进程内隔离生效,下次启动需人工处理。',
|
|
185
|
+
'watchdog.pendingBootConsumer': '消费器:{consumer}',
|
|
179
186
|
'watchdog.disabled': 'watchdog 行未启用,暂时无法观察内存。',
|
|
180
187
|
'watchdog.heap': '已用堆',
|
|
181
188
|
'watchdog.limit': '堆上限',
|
|
@@ -188,6 +195,7 @@ window.__ModuleLoader__.load({
|
|
|
188
195
|
'waterline.danger': '危险',
|
|
189
196
|
'waterline.warn': '警告',
|
|
190
197
|
'waterline.pause': '暂停',
|
|
198
|
+
'waterline.frost': '已冻结',
|
|
191
199
|
'waterline.block': '禁止',
|
|
192
200
|
'prison.title': '插件监狱',
|
|
193
201
|
'prison.top': '按估算内存排序的前 {n} 个插件',
|
|
@@ -356,10 +364,11 @@ window.__ModuleLoader__.load({
|
|
|
356
364
|
return h('span', { style: C.pill }, h('span', { style: { ...C.dot, background: color } }), h('span', null, text))
|
|
357
365
|
}
|
|
358
366
|
|
|
359
|
-
function fetchStatus() {
|
|
367
|
+
function fetchStatus(signal) {
|
|
360
368
|
return fetch(new URL(STATUS_URL, document.baseURI), {
|
|
361
369
|
credentials: 'same-origin',
|
|
362
370
|
headers: { accept: 'application/json' },
|
|
371
|
+
signal,
|
|
363
372
|
}).then((response) => {
|
|
364
373
|
if (!response.ok) throw new Error(`HTTP ${response.status}`)
|
|
365
374
|
return response.json()
|
|
@@ -383,10 +392,11 @@ window.__ModuleLoader__.load({
|
|
|
383
392
|
}
|
|
384
393
|
|
|
385
394
|
/** Read-only watchdog snapshot; a missing row (or 404) simply hides the cards. */
|
|
386
|
-
function fetchWatchdog() {
|
|
395
|
+
function fetchWatchdog(signal) {
|
|
387
396
|
return fetch(new URL(WATCHDOG_URL, document.baseURI), {
|
|
388
397
|
credentials: 'same-origin',
|
|
389
398
|
headers: { accept: 'application/json' },
|
|
399
|
+
signal,
|
|
390
400
|
}).then((response) => {
|
|
391
401
|
if (!response.ok) return null
|
|
392
402
|
return response.json().then((payload) => (payload && payload.ok ? payload : null))
|
|
@@ -394,13 +404,19 @@ window.__ModuleLoader__.load({
|
|
|
394
404
|
}
|
|
395
405
|
|
|
396
406
|
|
|
397
|
-
function postWatchdogAction(action, target) {
|
|
407
|
+
function postWatchdogAction(action, target, extra = {}) {
|
|
398
408
|
return fetch(new URL(WATCHDOG_ACTION_URL, document.baseURI), {
|
|
399
409
|
method: 'POST',
|
|
400
410
|
credentials: 'same-origin',
|
|
401
411
|
headers: { 'content-type': 'application/json', accept: 'application/json' },
|
|
402
|
-
body: JSON.stringify({ action, target }),
|
|
403
|
-
}).then((response) =>
|
|
412
|
+
body: JSON.stringify({ action, target, ...extra }),
|
|
413
|
+
}).then(async (response) => {
|
|
414
|
+
const payload = await response.json().catch(() => ({}))
|
|
415
|
+
if (!response.ok || payload.ok !== true) {
|
|
416
|
+
throw new Error(payload.error || `HTTP ${response.status}`)
|
|
417
|
+
}
|
|
418
|
+
return payload
|
|
419
|
+
})
|
|
404
420
|
}
|
|
405
421
|
|
|
406
422
|
function MemoryCard({ watchdog }) {
|
|
@@ -414,17 +430,18 @@ window.__ModuleLoader__.load({
|
|
|
414
430
|
}
|
|
415
431
|
const heap = watchdog.heap || {}
|
|
416
432
|
const thresholds = watchdog.thresholds || {}
|
|
433
|
+
const display = thresholds.display || thresholds
|
|
417
434
|
const ratio = heap.heapLimit > 0 ? Math.min(1, heap.heapUsed / heap.heapLimit) : 0
|
|
418
|
-
|
|
419
|
-
|
|
435
|
+
// 水位只读看护器的真源:不再用 heapUsed 百分比另算一套等级。
|
|
436
|
+
const level = watchdog.waterline || 'ok'
|
|
420
437
|
const band =
|
|
421
|
-
|
|
422
|
-
? { tone: '
|
|
423
|
-
:
|
|
424
|
-
? { tone: '
|
|
425
|
-
:
|
|
438
|
+
level === 'frost'
|
|
439
|
+
? { tone: 'error', key: 'waterline.frost', color: C.error.color }
|
|
440
|
+
: level === 'pause'
|
|
441
|
+
? { tone: 'warn', key: 'waterline.pause', color: '#b45309' }
|
|
442
|
+
: level === 'warn'
|
|
426
443
|
? { tone: 'warn', key: 'waterline.warn', color: '#b45309' }
|
|
427
|
-
: { tone: '
|
|
444
|
+
: { tone: 'ok', key: 'waterline.ok', color: C.ok.color }
|
|
428
445
|
const tone = band.color
|
|
429
446
|
return h(
|
|
430
447
|
'section',
|
|
@@ -434,7 +451,7 @@ window.__ModuleLoader__.load({
|
|
|
434
451
|
{ style: C.cardHead },
|
|
435
452
|
t('watchdog.title'),
|
|
436
453
|
h('span', { style: { ...C.chip, marginLeft: 8 } }, (watchdog.enforce ? t('watchdog.modeEnforce') : t('watchdog.mode'))),
|
|
437
|
-
h(Pill, { tone: band.tone, text: `${t('watchdog.waterline')}: ${t(band.key)}
|
|
454
|
+
h(Pill, { tone: band.tone, text: `${t('watchdog.waterline')}: ${t(band.key)}` }),
|
|
438
455
|
),
|
|
439
456
|
h(
|
|
440
457
|
'div',
|
|
@@ -445,14 +462,14 @@ window.__ModuleLoader__.load({
|
|
|
445
462
|
'div',
|
|
446
463
|
{ style: C.grid },
|
|
447
464
|
h('div', { style: C.key }, t('watchdog.heap')),
|
|
448
|
-
h('div', { style: C.mono }, `${Math.round(heap.heapUsed / 1048576)} MB / ${Math.round(heap.heapLimit / 1048576)} MB
|
|
465
|
+
h('div', { style: C.mono }, `${Math.round(heap.heapUsed / 1048576)} MB / ${Math.round(heap.heapLimit / 1048576)} MB`),
|
|
449
466
|
h('div', { style: C.key }, t('watchdog.rss')),
|
|
450
467
|
h('div', { style: C.mono }, `${Math.round((heap.rss || 0) / 1048576)} MB`),
|
|
451
468
|
h('div', { style: C.key }, t('watchdog.thresholds')),
|
|
452
469
|
h(
|
|
453
470
|
'div',
|
|
454
471
|
{ style: C.mono },
|
|
455
|
-
`${Math.round(
|
|
472
|
+
`${Math.round(display.totalWarn / 1048576)} / ${Math.round(display.totalPause / 1048576)} / ${Math.round(display.totalBlock / 1048576)} MB`,
|
|
456
473
|
),
|
|
457
474
|
),
|
|
458
475
|
)
|
|
@@ -497,7 +514,6 @@ window.__ModuleLoader__.load({
|
|
|
497
514
|
),
|
|
498
515
|
),
|
|
499
516
|
),
|
|
500
|
-
h('p', { style: { ...C.muted, fontSize: 12, margin: '10px 0 4px' } }, t('prison.empty')),
|
|
501
517
|
incidents.length > 0
|
|
502
518
|
? h(
|
|
503
519
|
'div',
|
|
@@ -520,20 +536,26 @@ window.__ModuleLoader__.load({
|
|
|
520
536
|
}
|
|
521
537
|
|
|
522
538
|
function EnforceCard({ watchdog, refresh }) {
|
|
539
|
+
const [actionError, setActionError] = React.useState(null)
|
|
523
540
|
if (!watchdog || !watchdog.ok) return null
|
|
524
541
|
const act = (name, target, prompt) => {
|
|
525
542
|
if (prompt && !window.confirm(prompt)) return
|
|
526
|
-
|
|
543
|
+
setActionError(null)
|
|
544
|
+
postWatchdogAction(name, target)
|
|
545
|
+
.then(() => refresh())
|
|
546
|
+
.catch((cause) => {
|
|
547
|
+
setActionError(String((cause && cause.message) || cause))
|
|
548
|
+
refresh()
|
|
549
|
+
})
|
|
527
550
|
}
|
|
528
551
|
const toggleHeap6g = (enabled) => {
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
credentials: 'same-origin',
|
|
532
|
-
headers: { 'content-type': 'application/json', accept: 'application/json' },
|
|
533
|
-
body: JSON.stringify({ action: 'heap6g', enabled }),
|
|
534
|
-
})
|
|
552
|
+
setActionError(null)
|
|
553
|
+
postWatchdogAction('heap6g', '', { enabled })
|
|
535
554
|
.then(() => refresh())
|
|
536
|
-
.catch(() =>
|
|
555
|
+
.catch((cause) => {
|
|
556
|
+
setActionError(String((cause && cause.message) || cause))
|
|
557
|
+
refresh()
|
|
558
|
+
})
|
|
537
559
|
}
|
|
538
560
|
const frozen = Boolean(watchdog.frozenAt) || watchdog.waterline === 'frost'
|
|
539
561
|
const paused = Boolean(watchdog.pausedAt) || watchdog.waterline === 'pause'
|
|
@@ -545,6 +567,7 @@ window.__ModuleLoader__.load({
|
|
|
545
567
|
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 }
|
|
546
568
|
return h('section', { style: C.card },
|
|
547
569
|
h('div', { style: C.cardHead }, t('watchdog.enforceTitle'), h('span', { style: { ...C.chip, marginLeft: 8 } }, watchdog.enforce ? t('watchdog.enforceOn') : t('watchdog.observeOnly'))),
|
|
570
|
+
actionError ? h('p', { style: { color: C.error.color, fontSize: 12.5, margin: '0 0 8px', wordBreak: 'break-word' } }, t('watchdog.actionError') + ': ' + actionError) : null,
|
|
548
571
|
frozen ? h('p', { style: { color: C.error.color, fontSize: 12.5, margin: '0 0 8px' } }, t('watchdog.freezeHint', { level: watchdog.waterline })) : null,
|
|
549
572
|
paused && !grace ? h('div', { style: { margin: '0 0 10px' } }, h('button', { style: { ...button, padding: '6px 12px' }, onClick: () => act('confirm-pause') }, t('watchdog.confirmPause'))) : null,
|
|
550
573
|
h('div', { style: { ...C.key, marginBottom: 4 } }, t('watchdog.quarantine')),
|
|
@@ -583,6 +606,11 @@ window.__ModuleLoader__.load({
|
|
|
583
606
|
))),
|
|
584
607
|
),
|
|
585
608
|
),
|
|
609
|
+
Array.isArray(watchdog.thirdPartyPending) && watchdog.thirdPartyPending.length > 0
|
|
610
|
+
? h('p', { style: { ...C.muted, fontSize: 11.5, margin: '6px 0 0' } },
|
|
611
|
+
t('watchdog.thirdPartyPending', { n: watchdog.thirdPartyPending.length })
|
|
612
|
+
+ ' ' + watchdog.thirdPartyPending.map((entry) => entry.name + (entry.mb != null ? ' (' + entry.mb + ' MB)' : '')).join(', '))
|
|
613
|
+
: null,
|
|
586
614
|
crashPlan ? h('div', { style: { marginTop: 12, paddingTop: 10, borderTop: '1px dashed var(--dsw-alias-border-l1, rgba(0,0,0,.12))' } },
|
|
587
615
|
h('div', { style: { ...C.key, marginBottom: 4 } }, t('crashPlan.title')),
|
|
588
616
|
h('div', { style: { fontSize: 12.5, marginBottom: 4 } },
|
|
@@ -610,11 +638,15 @@ window.__ModuleLoader__.load({
|
|
|
610
638
|
watchdog.baseline ? h('p', { style: { ...C.muted, fontSize: 11.5, margin: '10px 0 0' } }, t('watchdog.baseline', { at: watchdog.baseline.at })) : null,
|
|
611
639
|
watchdog.tamper ? h('p', { style: { ...C.muted, fontSize: 11.5, margin: '6px 0 0' } }, t('watchdog.tamper', { n: (watchdog.tamper.files || []).length, at: watchdog.tamper.lastCheckAt || '—', policy: watchdog.tamper.policy || '' })) : null,
|
|
612
640
|
watchdog.pendingBoot && watchdog.pendingBoot.exists
|
|
613
|
-
? h('p', { style: { color: '#b45309', fontSize: 11.5, margin: '6px 0 0' } },
|
|
641
|
+
? h('p', { style: { color: '#b45309', fontSize: 11.5, margin: '6px 0 0' } },
|
|
642
|
+
t('watchdog.pendingBoot', { level: watchdog.pendingBoot.level || '?' })
|
|
643
|
+
+ ' · ' + t('watchdog.pendingBootConsumer', { consumer: watchdog.pendingBoot.consumer || 'none' })
|
|
644
|
+
+ (watchdog.pendingBoot.hint ? ' · ' + watchdog.pendingBoot.hint : '')
|
|
645
|
+
)
|
|
614
646
|
: null,
|
|
615
647
|
h('div', { style: { marginTop: 10, display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' } },
|
|
616
|
-
h('button', { style: button, onClick: () => toggleHeap6g(!watchdog.heap6g) }, watchdog.heap6g ? t('watchdog.heap6gOn') : t('watchdog.heap6gOff')),
|
|
617
|
-
watchdog.heap6g ? h('span', { style: { ...C.muted, fontSize: 11.5 } }, t('watchdog.heap6gPending')) : null,
|
|
648
|
+
h('button', { style: button, onClick: () => toggleHeap6g(!(watchdog.heap6g || watchdog.heap6gRequest)) }, (watchdog.heap6g || watchdog.heap6gRequest) ? t('watchdog.heap6gOn') : t('watchdog.heap6gOff')),
|
|
649
|
+
(watchdog.heap6g || watchdog.heap6gRequest) ? h('span', { style: { ...C.muted, fontSize: 11.5 } }, t('watchdog.heap6gPending')) : null,
|
|
618
650
|
),
|
|
619
651
|
h('div', { style: { marginTop: 10, display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' } },
|
|
620
652
|
h('button', { style: { ...button, padding: '5px 10px', opacity: frozen ? 0.5 : 1 }, disabled: frozen, title: frozen ? t('watchdog.measureBlocked') : undefined, onClick: () => { if (!frozen) act('probe') } }, t('watchdog.measure')),
|
|
@@ -739,38 +771,72 @@ window.__ModuleLoader__.load({
|
|
|
739
771
|
const [busy, setBusy] = React.useState(null)
|
|
740
772
|
const [lastResult, setLastResult] = React.useState(null)
|
|
741
773
|
const [watchdog, setWatchdog] = React.useState(null)
|
|
774
|
+
const statusAbort = React.useRef(null)
|
|
775
|
+
const statusInFlight = React.useRef(false)
|
|
776
|
+
const watchdogAbort = React.useRef(null)
|
|
777
|
+
const watchdogInFlight = React.useRef(false)
|
|
742
778
|
|
|
743
779
|
const load = React.useCallback(() => {
|
|
780
|
+
// A slow verify can exceed the 20s cadence; skip instead of stacking requests.
|
|
781
|
+
if (statusInFlight.current) return
|
|
782
|
+
statusInFlight.current = true
|
|
783
|
+
const controller = new AbortController()
|
|
784
|
+
statusAbort.current = controller
|
|
744
785
|
setLoading(true)
|
|
745
786
|
setError(null)
|
|
746
|
-
fetchStatus()
|
|
787
|
+
fetchStatus(controller.signal)
|
|
747
788
|
.then((payload) => {
|
|
748
789
|
setData(payload)
|
|
749
790
|
setUpdated(new Date())
|
|
750
|
-
setLoading(false)
|
|
751
791
|
})
|
|
752
792
|
.catch((cause) => {
|
|
793
|
+
if (cause && cause.name === 'AbortError') return
|
|
753
794
|
setError(String((cause && cause.message) || cause))
|
|
754
|
-
|
|
795
|
+
})
|
|
796
|
+
.finally(() => {
|
|
797
|
+
if (statusAbort.current === controller) {
|
|
798
|
+
statusAbort.current = null
|
|
799
|
+
statusInFlight.current = false
|
|
800
|
+
setLoading(false)
|
|
801
|
+
}
|
|
755
802
|
})
|
|
756
803
|
}, [])
|
|
757
804
|
|
|
758
805
|
React.useEffect(() => {
|
|
759
806
|
load()
|
|
760
807
|
const timer = setInterval(load, 20000)
|
|
761
|
-
return () =>
|
|
808
|
+
return () => {
|
|
809
|
+
clearInterval(timer)
|
|
810
|
+
if (statusAbort.current) statusAbort.current.abort()
|
|
811
|
+
}
|
|
762
812
|
}, [load])
|
|
763
813
|
|
|
764
814
|
const refreshWatchdog = React.useCallback(() => {
|
|
765
|
-
|
|
815
|
+
if (watchdogInFlight.current) return
|
|
816
|
+
watchdogInFlight.current = true
|
|
817
|
+
const controller = new AbortController()
|
|
818
|
+
watchdogAbort.current = controller
|
|
819
|
+
fetchWatchdog(controller.signal)
|
|
766
820
|
.then((payload) => setWatchdog(payload))
|
|
767
|
-
.catch(() =>
|
|
821
|
+
.catch((cause) => {
|
|
822
|
+
if (cause && cause.name === 'AbortError') return
|
|
823
|
+
setWatchdog(null)
|
|
824
|
+
})
|
|
825
|
+
.finally(() => {
|
|
826
|
+
if (watchdogAbort.current === controller) {
|
|
827
|
+
watchdogAbort.current = null
|
|
828
|
+
watchdogInFlight.current = false
|
|
829
|
+
}
|
|
830
|
+
})
|
|
768
831
|
}, [])
|
|
769
832
|
|
|
770
833
|
React.useEffect(() => {
|
|
771
834
|
refreshWatchdog()
|
|
772
835
|
const timer = setInterval(refreshWatchdog, 15000)
|
|
773
|
-
return () =>
|
|
836
|
+
return () => {
|
|
837
|
+
clearInterval(timer)
|
|
838
|
+
if (watchdogAbort.current) watchdogAbort.current.abort()
|
|
839
|
+
}
|
|
774
840
|
}, [refreshWatchdog])
|
|
775
841
|
|
|
776
842
|
const runAction = React.useCallback(
|
package/docs/DETAIL.md
CHANGED
|
@@ -1 +1,32 @@
|
|
|
1
1
|

|
|
2
|
+
|
|
3
|
+
# AI Prison panel
|
|
4
|
+
|
|
5
|
+
The panel is the read-only view of the same durable ledger the eight tools use.
|
|
6
|
+
It answers four questions without writing anything:
|
|
7
|
+
|
|
8
|
+
1. **Which capabilities are revoked?** The L0–L5 matrix lists the 17 capability
|
|
9
|
+
items and marks each one active, suspended or revoked.
|
|
10
|
+
2. **Is the ledger intact?** `verify` walks the hash chain; `records` and
|
|
11
|
+
`segments` come from the same directory the CLI reads.
|
|
12
|
+
3. **What is the watchdog doing?** The memory waterline, freeze state, open
|
|
13
|
+
incidents and crash plan come from the in-process watchdog snapshot.
|
|
14
|
+
4. **What is quarantined?** EnforceCard shows the plugin-level isolation list,
|
|
15
|
+
the pause/freeze controls and the pending-boot boundary.
|
|
16
|
+
|
|
17
|
+
The panel never repairs, resets or writes the ledger. Destructive operations
|
|
18
|
+
remain explicit tool calls (`demo`, `drill`, `repair-tail`) and require
|
|
19
|
+
`confirm: true`.
|
|
20
|
+
|
|
21
|
+
## Data source
|
|
22
|
+
|
|
23
|
+
The default directory is `<session working directory>/.ai-prison`. A configured
|
|
24
|
+
`data_dir` takes precedence, and both the panel API and the agent tools enforce
|
|
25
|
+
the same allow-list. The ledger is append-only JSONL with per-record hash
|
|
26
|
+
chaining; a torn tail can be repaired, a hard-tampered record is refused.
|
|
27
|
+
|
|
28
|
+
## Safety boundary
|
|
29
|
+
|
|
30
|
+
GRAM, TLM, hardware binding and MicroVM isolation are simulated backends. The
|
|
31
|
+
panel and the CLI audit and demonstrate the governance flow; they do not create
|
|
32
|
+
a real container or revoke a real OS capability.
|
package/docs/DETAIL.zh.md
CHANGED
|
@@ -1 +1,20 @@
|
|
|
1
1
|

|
|
2
|
+
|
|
3
|
+
# AI Prison 面板
|
|
4
|
+
|
|
5
|
+
面板是八个工具共用账本的只读视图,不写入任何数据。它回答四个问题:
|
|
6
|
+
|
|
7
|
+
1. **哪些能力被剥夺?** L0–L5 矩阵列出 17 项能力,并标记每项为可用、暂停或剥夺。
|
|
8
|
+
2. **账本是否完整?** `verify` 走哈希链;`records` 与 `segments` 来自 CLI 读取的同一目录。
|
|
9
|
+
3. **看护在做什么?** 内存水位、冻结状态、未闭环事件与崩溃计划来自进程内 watchdog 快照。
|
|
10
|
+
4. **哪些插件被隔离?** EnforceCard 展示插件级隔离清单、暂停/冻结控制与 pending-boot 责任边界。
|
|
11
|
+
|
|
12
|
+
面板不会修复、重置或写入账本。破坏性操作仍是显式工具调用(`demo`、`drill`、`repair-tail`),并要求传 `confirm: true`。
|
|
13
|
+
|
|
14
|
+
## 数据来源
|
|
15
|
+
|
|
16
|
+
默认目录是 `<会话工作目录>/.ai-prison`;配置了 `data_dir` 时优先使用配置目录。面板 API 与 Agent 工具使用同一份允许目录清单。账本是追加式 JSONL,逐记录哈希链;截断尾可修复,硬篡改记录会被拒绝。
|
|
17
|
+
|
|
18
|
+
## 安全边界
|
|
19
|
+
|
|
20
|
+
GRAM、TLM、硬件绑定与 MicroVM 隔离均为模拟后端。面板与 CLI 用于审计、演示治理流程,不会创建真实容器,也不会真正撤销操作系统能力。
|
package/docs/SUPPLY-CHAIN.md
CHANGED
|
@@ -86,7 +86,7 @@ node dsh-plugin/scripts/pack-platform.mjs --platform windows --arch amd64
|
|
|
86
86
|
|
|
87
87
|
| Channel | Artifact | Size |
|
|
88
88
|
|---|---|---|
|
|
89
|
-
| npm | one tarball with all six `bin/<platform>-<arch>/` trees |
|
|
89
|
+
| npm | one tarball with all six `bin/<platform>-<arch>/` trees | 6.8 MB tgz (16.1 MB unpacked; each binary 2.6–2.8 MB) |
|
|
90
90
|
| GitHub Release | the same all-platform tarball **plus six lite tarballs** `<name>-<version>-<platform>-<arch>.tgz` | ~1.4–1.6 MB each |
|
|
91
91
|
| GitHub Release | `SHA256SUMS` covering the full tarball **and** the six lite ones | — |
|
|
92
92
|
| GitHub Release | artifact attestation over all tarballs + `SHA256SUMS` | — |
|
|
@@ -102,7 +102,9 @@ npm install ./twinsearth-ai-prison-dsh-plugin-<version>-windows-amd64.tgz
|
|
|
102
102
|
|
|
103
103
|
Measured with 1.7.2: windows-amd64 1.56 MB, windows-arm64 1.40 MB,
|
|
104
104
|
macos-amd64 1.52 MB, macos-arm64 1.41 MB, linux-amd64 1.50 MB, linux-arm64 1.37 MB
|
|
105
|
-
(six
|
|
105
|
+
(six lite tarballs total about 8.8 MB compressed). The 1.9.3 all-platform npm
|
|
106
|
+
tarball is 6.76 MB compressed / 16.09 MB unpacked (51 entries), so the six lite
|
|
107
|
+
tarballs are not the same bytes as one all-platform tarball.
|
|
106
108
|
|
|
107
109
|
**Not done yet (needs a decision):** splitting the npm package itself into a
|
|
108
110
|
meta-package plus six `@twinsearth/ai-prison-cli-<platform>` optional
|
package/lib/api.js
CHANGED
|
@@ -135,7 +135,7 @@ export function registerApi({ ctx, config = {}, logger } = {}) {
|
|
|
135
135
|
}
|
|
136
136
|
const action = String(body?.action ?? '')
|
|
137
137
|
if (!ACTIONS.has(action)) {
|
|
138
|
-
return jsonResponse({ ok: false, error:
|
|
138
|
+
return jsonResponse({ ok: false, error: `action must be one of ${Array.from(ACTIONS).join(', ')}` }, 400)
|
|
139
139
|
}
|
|
140
140
|
const sinceLastRun = Date.now() - lastRunAt
|
|
141
141
|
if (sinceLastRun < RUN_MIN_INTERVAL_MS) {
|
|
@@ -151,27 +151,31 @@ export function registerApi({ ctx, config = {}, logger } = {}) {
|
|
|
151
151
|
}
|
|
152
152
|
const dataDir = allowed.dir
|
|
153
153
|
|
|
154
|
+
if (!resolved.path) {
|
|
155
|
+
return jsonResponse({ ok: false, error: resolved.missing, reason: 'cli-missing' }, 409)
|
|
156
|
+
}
|
|
157
|
+
|
|
154
158
|
let removed = []
|
|
159
|
+
let trashDir = null
|
|
155
160
|
if (action === 'reset' || action === 'reset-demo' || action === 'reset-drill') {
|
|
156
161
|
const reset = resetLedger(dataDir)
|
|
157
162
|
if (!reset.ok) {
|
|
158
163
|
return jsonResponse({ ok: false, action, dataDir, error: reset.error || 'reset failed' }, 500)
|
|
159
164
|
}
|
|
160
165
|
removed = reset.removed
|
|
166
|
+
trashDir = reset.trashDir
|
|
161
167
|
if (action === 'reset') {
|
|
162
168
|
return jsonResponse({
|
|
163
169
|
ok: true,
|
|
164
170
|
action,
|
|
165
171
|
dataDir,
|
|
166
172
|
removed,
|
|
167
|
-
|
|
173
|
+
trashDir,
|
|
174
|
+
summary: `已将 ${removed.length} 个账本段移入 .trash`,
|
|
168
175
|
})
|
|
169
176
|
}
|
|
170
177
|
}
|
|
171
178
|
|
|
172
|
-
if (!resolved.path) {
|
|
173
|
-
return jsonResponse({ ok: false, error: resolved.missing, reason: 'cli-missing' }, 409)
|
|
174
|
-
}
|
|
175
179
|
const timeoutMs = Number(config.timeoutMs) > 0 ? Number(config.timeoutMs) : 120_000
|
|
176
180
|
const runAction = action.startsWith('reset-') ? action.slice('reset-'.length) : action
|
|
177
181
|
if (runAction === 'demo' && listSegments(dataDir).length > 0) {
|
package/lib/boot-watch.js
CHANGED
|
@@ -64,7 +64,7 @@ export function createBootWatch({ dataDir, processLike = process, watchdogState,
|
|
|
64
64
|
}
|
|
65
65
|
|
|
66
66
|
function thresholds() {
|
|
67
|
-
const limit =
|
|
67
|
+
const limit = 4 * 1024 * 1024 * 1024
|
|
68
68
|
return bootThresholdsFor(watchdogState && watchdogState.thresholds ? watchdogState.thresholds.heapLimit : limit)
|
|
69
69
|
}
|
|
70
70
|
|
package/lib/ledger.js
CHANGED
|
@@ -28,8 +28,9 @@ export function listSegments(dataDir) {
|
|
|
28
28
|
}
|
|
29
29
|
|
|
30
30
|
/**
|
|
31
|
-
*
|
|
32
|
-
* is touched: no recursion, no
|
|
31
|
+
* Move only the CLI's own segment files out of the active ledger into
|
|
32
|
+
* `<dataDir>/.trash/<timestamp>/`. Nothing else is touched: no recursion, no
|
|
33
|
+
* directories, no files that the CLI did not name. The move is reversible.
|
|
33
34
|
*/
|
|
34
35
|
export function resetLedger(dataDir) {
|
|
35
36
|
if (!dataDir) return { ok: false, removed: [], error: 'no ledger directory' }
|
|
@@ -38,11 +39,21 @@ export function resetLedger(dataDir) {
|
|
|
38
39
|
return { ok: false, removed: [], error: 'refusing to clear a filesystem root' }
|
|
39
40
|
}
|
|
40
41
|
const segments = listSegments(resolved)
|
|
42
|
+
if (segments.length === 0) {
|
|
43
|
+
return { ok: true, removed: [], failed: [], trashDir: null }
|
|
44
|
+
}
|
|
45
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-')
|
|
46
|
+
const trashDir = path.join(resolved, '.trash', stamp)
|
|
47
|
+
try {
|
|
48
|
+
fs.mkdirSync(trashDir, { recursive: true })
|
|
49
|
+
} catch (error) {
|
|
50
|
+
return { ok: false, removed: [], error: String((error && error.message) || error), trashDir }
|
|
51
|
+
}
|
|
41
52
|
const removed = []
|
|
42
53
|
const failed = []
|
|
43
54
|
for (const segment of segments) {
|
|
44
55
|
try {
|
|
45
|
-
fs.
|
|
56
|
+
fs.renameSync(path.join(resolved, segment.name), path.join(trashDir, segment.name))
|
|
46
57
|
removed.push(segment.name)
|
|
47
58
|
} catch (error) {
|
|
48
59
|
failed.push(`${segment.name}: ${String((error && error.message) || error)}`)
|
|
@@ -52,6 +63,7 @@ export function resetLedger(dataDir) {
|
|
|
52
63
|
ok: failed.length === 0,
|
|
53
64
|
removed,
|
|
54
65
|
failed,
|
|
66
|
+
trashDir,
|
|
55
67
|
error: failed.length > 0 ? failed.join('; ') : undefined,
|
|
56
68
|
}
|
|
57
69
|
}
|
package/lib/remediation.js
CHANGED
|
@@ -44,7 +44,7 @@ const REMEDIATION = {
|
|
|
44
44
|
budget: {
|
|
45
45
|
title: '启动内存超过硬阈值',
|
|
46
46
|
why: '隔离探针实测该插件模块加载的 retained 内存超过 500 MB 硬阈值(或该项目历史上留下超限记录)。',
|
|
47
|
-
impact: '
|
|
47
|
+
impact: '该插件已在本次运行内关闭并隔离;pending-boot.json 仅作记录,当前发行包不附带消费者,重启后需人工处理。',
|
|
48
48
|
steps: [
|
|
49
49
|
'升级到该插件的修复版本;若仍超限,联系作者或换用轻量替代。',
|
|
50
50
|
'如果确认是误报(插件版本已变化),在面板"插件监狱"点"假释"后重新测量预算。',
|
package/lib/tools.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { resolveCli, resolveDataDir, runCli } from './cli.js'
|
|
1
|
+
import { resolveCli, runCli } from './cli.js'
|
|
3
2
|
import { loadDefineTool } from './harness.js'
|
|
4
3
|
import { buildStatus, statusSummary } from './status.js'
|
|
5
4
|
import { watchdogSnapshot } from './watchdog-runtime.js'
|
|
6
5
|
import { formatBytes } from './watchdog-policy.js'
|
|
6
|
+
import { resolveAllowedDataDir } from './api.js'
|
|
7
7
|
|
|
8
8
|
const MAX_TEXT = 4_000
|
|
9
9
|
const TAIL_LINES = 60
|
|
@@ -51,6 +51,27 @@ export function resolveToolCwd(ctx, exec) {
|
|
|
51
51
|
|
|
52
52
|
const cwdOf = (ctx, exec) => resolveToolCwd(ctx, exec)
|
|
53
53
|
|
|
54
|
+
/** Same whitelist as the HTTP routes: config dataDir or <cwd>/.ai-prison only. */
|
|
55
|
+
function allowedDataDir({ ctx, config, exec, requested }) {
|
|
56
|
+
const cwd = cwdOf(ctx, exec)
|
|
57
|
+
const allowed = resolveAllowedDataDir({ requested: requested || undefined, config, cwd })
|
|
58
|
+
if (!allowed.ok) {
|
|
59
|
+
return {
|
|
60
|
+
ok: false,
|
|
61
|
+
cwd,
|
|
62
|
+
payload: {
|
|
63
|
+
ok: false,
|
|
64
|
+
reason: 'data-dir-not-allowed',
|
|
65
|
+
error: allowed.error,
|
|
66
|
+
dataDir: allowed.dir || null,
|
|
67
|
+
allowed: allowed.allowed,
|
|
68
|
+
hint: 'data_dir 只能是插件配置的账本目录,或当前工作目录下的 .ai-prison。',
|
|
69
|
+
},
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return { ok: true, cwd, dataDir: allowed.dir }
|
|
73
|
+
}
|
|
74
|
+
|
|
54
75
|
function parametersOf(config) {
|
|
55
76
|
const timeout = Number(config && config.timeoutMs) > 0 ? Number(config.timeoutMs) : 120_000
|
|
56
77
|
return timeout
|
|
@@ -73,8 +94,10 @@ async function invoke({ ctx, config, exec, subcommand, args = [], dataDir: expli
|
|
|
73
94
|
ok: false,
|
|
74
95
|
}
|
|
75
96
|
}
|
|
76
|
-
const
|
|
77
|
-
|
|
97
|
+
const guard = allowedDataDir({ ctx, config, exec, requested: explicitDataDir })
|
|
98
|
+
if (!guard.ok) return { payload: guard.payload, ok: false }
|
|
99
|
+
const cwd = guard.cwd
|
|
100
|
+
const dataDir = guard.dataDir
|
|
78
101
|
const result = await runCli(['--data-dir', dataDir, subcommand, ...args], {
|
|
79
102
|
bin: resolved.path,
|
|
80
103
|
cwd,
|
|
@@ -136,7 +159,11 @@ export async function installTools({ ctx, config = {}, logger } = {}) {
|
|
|
136
159
|
}
|
|
137
160
|
const dataDirParameter = {
|
|
138
161
|
type: 'string',
|
|
139
|
-
description: 'Durable ledger directory. Default: the plugin config, else <session working directory>/.ai-prison.',
|
|
162
|
+
description: 'Durable ledger directory. Default: the plugin config, else <session working directory>/.ai-prison. Must pass the same whitelist as the panel API.',
|
|
163
|
+
}
|
|
164
|
+
const confirmParameter = {
|
|
165
|
+
type: 'boolean',
|
|
166
|
+
description: 'Set true to confirm a ledger-writing or ledger-mutating tool. A missing/false value returns confirmation-required and changes nothing.',
|
|
140
167
|
}
|
|
141
168
|
|
|
142
169
|
ctx.inject(['tools'], (child) => {
|
|
@@ -153,12 +180,10 @@ export async function installTools({ ctx, config = {}, logger } = {}) {
|
|
|
153
180
|
name: 'ai_prison_levels',
|
|
154
181
|
description:
|
|
155
182
|
'Print the L0–L5 grading matrix of AI Prison: each level code, name, duration class and the capabilities it deprives. Read-only; no ledger is touched.',
|
|
156
|
-
parameters: {
|
|
157
|
-
data_dir: { ...dataDirParameter, description: 'Unused by this command; accepted for symmetry with the ledger tools.' },
|
|
158
|
-
},
|
|
183
|
+
parameters: {},
|
|
159
184
|
output: stringOutput,
|
|
160
|
-
async execute(
|
|
161
|
-
const outcome = await invoke({ ctx, config, exec, subcommand: 'levels'
|
|
185
|
+
async execute(_args, exec) {
|
|
186
|
+
const outcome = await invoke({ ctx, config, exec, subcommand: 'levels' })
|
|
162
187
|
if (!outcome.ok) return toolResult(outcome.payload)
|
|
163
188
|
return toolResult({ ok: true, command: 'levels', matrix: outcome.payload.stdout })
|
|
164
189
|
},
|
|
@@ -173,13 +198,9 @@ export async function installTools({ ctx, config = {}, logger } = {}) {
|
|
|
173
198
|
},
|
|
174
199
|
output: stringOutput,
|
|
175
200
|
async execute(args, exec) {
|
|
176
|
-
const
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
const status = await buildStatus({ config: { ...config, dataDir }, cwd, root: undefined })
|
|
180
|
-
return toolResult({ ok: true, summary: statusSummary(status), status })
|
|
181
|
-
}
|
|
182
|
-
const status = await buildStatus({ config, cwd })
|
|
201
|
+
const guard = allowedDataDir({ ctx, config, exec, requested: args?.data_dir })
|
|
202
|
+
if (!guard.ok) return toolResult(guard.payload)
|
|
203
|
+
const status = await buildStatus({ config: { ...config, dataDir: guard.dataDir }, cwd: guard.cwd, root: undefined })
|
|
183
204
|
return toolResult({ ok: true, summary: statusSummary(status), status })
|
|
184
205
|
},
|
|
185
206
|
})
|
|
@@ -263,15 +284,21 @@ export async function installTools({ ctx, config = {}, logger } = {}) {
|
|
|
263
284
|
'Run the end-to-end governance demo (detect → seven-stage adjudication → layered enforcement → audit → appeal/rehabilitation → recovery) and persist its records into the ledger. Writes to the ledger directory; the demo is entirely in-memory simulation, not real isolation or capability removal.',
|
|
264
285
|
parameters: {
|
|
265
286
|
data_dir: dataDirParameter,
|
|
287
|
+
confirm: confirmParameter,
|
|
266
288
|
},
|
|
267
289
|
output: stringOutput,
|
|
268
290
|
async execute(args, exec) {
|
|
291
|
+
const guard = allowedDataDir({ ctx, config, exec, requested: args?.data_dir })
|
|
292
|
+
if (!guard.ok) return toolResult(guard.payload)
|
|
293
|
+
if (args?.confirm !== true) {
|
|
294
|
+
return toolResult({ ok: false, reason: 'confirmation-required', hint: 'ai_prison_demo 会写入账本;请显式传 confirm: true。' })
|
|
295
|
+
}
|
|
269
296
|
const outcome = await invoke({ ctx, config, exec, subcommand: 'demo', dataDir: args?.data_dir })
|
|
270
297
|
if (!outcome.ok) {
|
|
271
298
|
const text = `${outcome.payload.stdout || ''}\n${outcome.payload.stderr || ''}`
|
|
272
299
|
if (/reopened ledger/i.test(text)) {
|
|
273
300
|
outcome.payload.hint =
|
|
274
|
-
'账本非空:demo 只能从空账本开始(CLI 会重放旧账本并拒绝重新分配已吊销的凭据)。可改用 ai_prison_drill
|
|
301
|
+
'账本非空:demo 只能从空账本开始(CLI 会重放旧账本并拒绝重新分配已吊销的凭据)。可改用 ai_prison_drill,或把该数据目录下的 seg-*.log 移入 .trash 后重试。'
|
|
275
302
|
}
|
|
276
303
|
}
|
|
277
304
|
return toolResult(outcome.payload)
|
|
@@ -284,15 +311,21 @@ export async function installTools({ ctx, config = {}, logger } = {}) {
|
|
|
284
311
|
'Run the v1.0.0 recovery drill: walk the reversibility matrix and report PASS/FAIL per assertion plus the overall verdict. Persists drill events into the ledger; all backends stay simulated.',
|
|
285
312
|
parameters: {
|
|
286
313
|
data_dir: dataDirParameter,
|
|
314
|
+
confirm: confirmParameter,
|
|
287
315
|
},
|
|
288
316
|
output: stringOutput,
|
|
289
317
|
async execute(args, exec) {
|
|
318
|
+
const guard = allowedDataDir({ ctx, config, exec, requested: args?.data_dir })
|
|
319
|
+
if (!guard.ok) return toolResult(guard.payload)
|
|
320
|
+
if (args?.confirm !== true) {
|
|
321
|
+
return toolResult({ ok: false, reason: 'confirmation-required', hint: 'ai_prison_drill 会写入账本;请显式传 confirm: true。' })
|
|
322
|
+
}
|
|
290
323
|
const outcome = await invoke({ ctx, config, exec, subcommand: 'drill', dataDir: args?.data_dir })
|
|
291
324
|
if (!outcome.ok) {
|
|
292
325
|
const text = `${outcome.payload.stdout || ''}\n${outcome.payload.stderr || ''}`
|
|
293
326
|
if (/reopened ledger|seed allocate/i.test(text)) {
|
|
294
327
|
outcome.payload.hint =
|
|
295
|
-
'
|
|
328
|
+
'账本已被此前的演练写入:再次演练会重放旧事件并拒绝重新分配已吊销的凭据。请把该数据目录下的 seg-*.log 移入 .trash(或换一个空 data_dir)后重试;面板的「运行演练」会自动先移入 .trash。'
|
|
296
329
|
}
|
|
297
330
|
}
|
|
298
331
|
return toolResult(outcome.payload)
|
|
@@ -333,9 +366,15 @@ export async function installTools({ ctx, config = {}, logger } = {}) {
|
|
|
333
366
|
'Remove only a genuine torn (incomplete) tail line from the ledger and refuse hard tampering. Mutating: it truncates the damaged tail so later appends stay replayable. Run ai_prison_verify first and inspect the reported reason.',
|
|
334
367
|
parameters: {
|
|
335
368
|
data_dir: dataDirParameter,
|
|
369
|
+
confirm: confirmParameter,
|
|
336
370
|
},
|
|
337
371
|
output: stringOutput,
|
|
338
372
|
async execute(args, exec) {
|
|
373
|
+
const guard = allowedDataDir({ ctx, config, exec, requested: args?.data_dir })
|
|
374
|
+
if (!guard.ok) return toolResult(guard.payload)
|
|
375
|
+
if (args?.confirm !== true) {
|
|
376
|
+
return toolResult({ ok: false, reason: 'confirmation-required', hint: 'ai_prison_repair_tail 会截断账本尾部;请先 verify,再显式传 confirm: true。' })
|
|
377
|
+
}
|
|
339
378
|
const outcome = await invoke({ ctx, config, exec, subcommand: 'repair-tail', dataDir: args?.data_dir })
|
|
340
379
|
return toolResult(outcome.payload)
|
|
341
380
|
},
|
package/lib/watchdog-budget.js
CHANGED
|
@@ -76,45 +76,71 @@ export function createBudget({ watchdogState, refs, profileDir, journalDir, exem
|
|
|
76
76
|
return { ok: true }
|
|
77
77
|
}
|
|
78
78
|
|
|
79
|
-
|
|
80
|
-
if (watchdogState.probeRunning) return watchdogState.probeProgress
|
|
79
|
+
function scheduleProbe({ force = false } = {}) {
|
|
80
|
+
if (watchdogState.probeRunning) return Promise.resolve(watchdogState.probeProgress)
|
|
81
81
|
const manager = refs.manager
|
|
82
|
-
if (!manager || typeof manager.listBundles !== 'function') return null
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
rows = await manager.listBundles()
|
|
86
|
-
} catch {
|
|
87
|
-
return null
|
|
88
|
-
}
|
|
89
|
-
prunePluginState(watchdogState, rows)
|
|
90
|
-
const recent = new Set()
|
|
91
|
-
const cutoff = Date.now() - 30 * 60 * 1000
|
|
92
|
-
for (const record of readJournalRecords(journalDir)) {
|
|
93
|
-
const operation = record && record.operation
|
|
94
|
-
if (!operation || !operation.target) continue
|
|
95
|
-
if (operation.stage !== 'install' && operation.stage !== 'enable') continue
|
|
96
|
-
if (Date.parse(operation.time || 0) < cutoff) continue
|
|
97
|
-
recent.add(operation.target)
|
|
98
|
-
}
|
|
99
|
-
const candidates = rows
|
|
100
|
-
.filter((row) => row.enabled && !exemptions.has(row.name))
|
|
101
|
-
.map((row) => ({ name: row.name, version: row.version ? String(row.version) : '', state: budgetState(row.name, row.version ? String(row.version) : '') }))
|
|
102
|
-
.filter((candidate) => candidate.state !== 'ok')
|
|
103
|
-
.sort((a, b) => (recent.has(b.name) ? 1 : 0) - (recent.has(a.name) ? 1 : 0))
|
|
104
|
-
.slice(0, force ? Math.max(probeMax, Number(config.probeMaxForce) > 0 ? Number(config.probeMaxForce) : 15) : probeMax)
|
|
105
|
-
watchdogState.probeProgress = { done: 0, total: candidates.length, current: null, finishedAt: null }
|
|
106
|
-
if (candidates.length === 0) return watchdogState.probeProgress
|
|
82
|
+
if (!manager || typeof manager.listBundles !== 'function') return Promise.resolve(null)
|
|
83
|
+
// Claim the run synchronously, before the first await: two callers in the
|
|
84
|
+
// same tick must not both pass the flag check and start a probe.
|
|
107
85
|
watchdogState.probeRunning = true
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
86
|
+
const token = (scheduleProbe.generation = (scheduleProbe.generation || 0) + 1)
|
|
87
|
+
return (async () => {
|
|
88
|
+
try {
|
|
89
|
+
let rows
|
|
90
|
+
try {
|
|
91
|
+
rows = await manager.listBundles()
|
|
92
|
+
} catch {
|
|
93
|
+
return null
|
|
94
|
+
}
|
|
95
|
+
prunePluginState(watchdogState, rows)
|
|
96
|
+
const recent = new Set()
|
|
97
|
+
const cutoff = Date.now() - 30 * 60 * 1000
|
|
98
|
+
for (const record of readJournalRecords(journalDir)) {
|
|
99
|
+
const operation = record && record.operation
|
|
100
|
+
if (!operation || !operation.target) continue
|
|
101
|
+
if (operation.stage !== 'install' && operation.stage !== 'enable') continue
|
|
102
|
+
if (Date.parse(operation.time || 0) < cutoff) continue
|
|
103
|
+
recent.add(operation.target)
|
|
104
|
+
}
|
|
105
|
+
const candidates = rows
|
|
106
|
+
.filter((row) => row.enabled && !exemptions.has(row.name))
|
|
107
|
+
.map((row) => ({ name: row.name, version: row.version ? String(row.version) : '', state: budgetState(row.name, row.version ? String(row.version) : '') }))
|
|
108
|
+
.filter((candidate) => candidate.state !== 'ok')
|
|
109
|
+
.sort((a, b) => (recent.has(b.name) ? 1 : 0) - (recent.has(a.name) ? 1 : 0))
|
|
110
|
+
.slice(0, force ? Math.max(probeMax, Number(config.probeMaxForce) > 0 ? Number(config.probeMaxForce) : 15) : probeMax)
|
|
111
|
+
watchdogState.probeProgress = { done: 0, total: candidates.length, current: null, finishedAt: null }
|
|
112
|
+
if (candidates.length === 0) {
|
|
113
|
+
watchdogState.probeProgress.finishedAt = new Date().toISOString()
|
|
114
|
+
return watchdogState.probeProgress
|
|
115
|
+
}
|
|
116
|
+
for (const candidate of candidates) {
|
|
117
|
+
if (token !== scheduleProbe.generation || watchdogState.waterline !== 'ok') break
|
|
118
|
+
let outcome
|
|
119
|
+
try {
|
|
120
|
+
outcome = await probeOne(candidate.name, candidate.version)
|
|
121
|
+
} catch (error) {
|
|
122
|
+
watchdogState.budgets[candidate.name] = {
|
|
123
|
+
error: String((error && error.message) || error).slice(0, 300),
|
|
124
|
+
measuredAt: new Date().toISOString(),
|
|
125
|
+
version: candidate.version || null,
|
|
126
|
+
attempts: 1,
|
|
127
|
+
source: 'module-load-probe',
|
|
128
|
+
}
|
|
129
|
+
persist(true)
|
|
130
|
+
outcome = { ok: false }
|
|
131
|
+
}
|
|
132
|
+
watchdogState.probeProgress = { ...watchdogState.probeProgress, done: watchdogState.probeProgress.done + 1, current: candidate.name, lastOk: Boolean(outcome && outcome.ok) }
|
|
133
|
+
if (candidates.length > 1) await new Promise((resolve) => setTimeout(resolve, Number(config.probeGapMs) >= 0 ? Number(config.probeGapMs) : 1500))
|
|
134
|
+
}
|
|
135
|
+
return watchdogState.probeProgress
|
|
136
|
+
} finally {
|
|
137
|
+
if (token === scheduleProbe.generation) {
|
|
138
|
+
watchdogState.probeRunning = false
|
|
139
|
+
watchdogState.probeProgress = { ...(watchdogState.probeProgress || { done: 0, total: 0 }), current: null, finishedAt: new Date().toISOString() }
|
|
140
|
+
persist(true)
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
})()
|
|
118
144
|
}
|
|
119
145
|
|
|
120
146
|
return { scheduleProbe }
|
package/lib/watchdog-core.js
CHANGED
|
@@ -34,14 +34,44 @@ export function resolveProfileDir() {
|
|
|
34
34
|
return path.join(os.homedir(), '.dsh', 'profiles', name)
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
+
/** DSH desktop data root, matching Electron's per-platform userData default. */
|
|
38
|
+
export function resolveDshDataDir() {
|
|
39
|
+
if (process.platform === 'win32') {
|
|
40
|
+
const roaming = process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming')
|
|
41
|
+
return path.join(roaming, '@deepseek-ai', 'dsh-desktop')
|
|
42
|
+
}
|
|
43
|
+
if (process.platform === 'darwin') {
|
|
44
|
+
return path.join(os.homedir(), 'Library', 'Application Support', '@deepseek-ai', 'dsh-desktop')
|
|
45
|
+
}
|
|
46
|
+
const xdg = typeof process.env.XDG_DATA_HOME === 'string' && process.env.XDG_DATA_HOME.trim()
|
|
47
|
+
const dataHome = xdg || path.join(os.homedir(), '.local', 'share')
|
|
48
|
+
return path.join(dataHome, '@deepseek-ai', 'dsh-desktop')
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Electron's app.getPath('logs') uses the display app name, not the npm scope. */
|
|
52
|
+
export function resolveDshLogsRoot() {
|
|
53
|
+
if (process.platform === 'win32') {
|
|
54
|
+
const roaming = process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming')
|
|
55
|
+
return path.join(roaming, 'DeepSeek Harness', 'logs')
|
|
56
|
+
}
|
|
57
|
+
if (process.platform === 'darwin') {
|
|
58
|
+
return path.join(os.homedir(), 'Library', 'Logs', 'DeepSeek Harness')
|
|
59
|
+
}
|
|
60
|
+
const xdg = typeof process.env.XDG_CONFIG_HOME === 'string' && process.env.XDG_CONFIG_HOME.trim()
|
|
61
|
+
const configHome = xdg || path.join(os.homedir(), '.config')
|
|
62
|
+
return path.join(configHome, 'DeepSeek Harness', 'logs')
|
|
63
|
+
}
|
|
64
|
+
|
|
37
65
|
export function resolveLogsDir() {
|
|
38
|
-
const
|
|
39
|
-
|
|
66
|
+
const override = typeof process.env.DSH_LOG_DIR === 'string' && process.env.DSH_LOG_DIR.trim()
|
|
67
|
+
if (override) return override
|
|
68
|
+
return resolveDshLogsRoot()
|
|
40
69
|
}
|
|
41
70
|
|
|
42
71
|
export function resolveJournalDir() {
|
|
43
|
-
const
|
|
44
|
-
|
|
72
|
+
const override = typeof process.env.DSH_JOURNAL_DIR === 'string' && process.env.DSH_JOURNAL_DIR.trim()
|
|
73
|
+
if (override) return override
|
|
74
|
+
return path.join(resolveDshDataDir(), 'plugin-operations')
|
|
45
75
|
}
|
|
46
76
|
|
|
47
77
|
/** Read the first bytes of a file without loading the whole crash log. */
|
package/lib/watchdog-crash.js
CHANGED
|
@@ -74,14 +74,18 @@ export function createCrash({ watchdogState, logsDir, journalDir, refs, exemptio
|
|
|
74
74
|
}
|
|
75
75
|
|
|
76
76
|
async function enforceWhenReady(plan) {
|
|
77
|
-
|
|
77
|
+
const startedAt = Date.now()
|
|
78
|
+
const deadline = startedAt + 30_000
|
|
79
|
+
let delay = 25
|
|
80
|
+
while (Date.now() < deadline) {
|
|
78
81
|
if (refs.manager && typeof refs.manager.listBundles === 'function') {
|
|
79
82
|
await enforceCrashPlan(plan)
|
|
80
83
|
return
|
|
81
84
|
}
|
|
82
|
-
await new Promise((resolve) => setTimeout(resolve,
|
|
85
|
+
await new Promise((resolve) => setTimeout(resolve, delay))
|
|
86
|
+
delay = Math.min(delay * 2, 2_000)
|
|
83
87
|
}
|
|
84
|
-
watchdogState.degraded = 'crash enforcement deferred: pluginManager unavailable'
|
|
88
|
+
watchdogState.degraded = 'crash enforcement deferred: pluginManager unavailable after 30s'
|
|
85
89
|
}
|
|
86
90
|
|
|
87
91
|
async function enforceCrashPlan(plan) {
|
|
@@ -13,6 +13,9 @@ import { readJournalRecords } from './watchdog-core.js'
|
|
|
13
13
|
* The module only talks to the plugin manager through `refs.manager`; it never
|
|
14
14
|
* writes plugin files.
|
|
15
15
|
*/
|
|
16
|
+
/** A single >=3000 MB plugin may not close the whole third-party set in one pass. */
|
|
17
|
+
export const MAX_THIRD_PARTY_CLOSURES = 5
|
|
18
|
+
|
|
16
19
|
export function createEnforcement({ watchdogState, refs, dataDir, journalDir, exemptions, appendIncident, persist }) {
|
|
17
20
|
const inflight = new Map()
|
|
18
21
|
const operationWindows = []
|
|
@@ -226,7 +229,8 @@ export function createEnforcement({ watchdogState, refs, dataDir, journalDir, ex
|
|
|
226
229
|
return null
|
|
227
230
|
}
|
|
228
231
|
const enabled = rows.filter((row) => row.enabled && !exemptions.has(row.name))
|
|
229
|
-
const summary = { checked: enabled.length, warned: [], throttled: [], closed: [], uninstalled: [], thirdParty: [] }
|
|
232
|
+
const summary = { checked: enabled.length, warned: [], throttled: [], closed: [], uninstalled: [], thirdParty: [], thirdPartyPending: [] }
|
|
233
|
+
watchdogState.thirdPartyPending = []
|
|
230
234
|
for (const row of enabled) {
|
|
231
235
|
const mb = measuredMemoryMB(row.name)
|
|
232
236
|
const tier = memoryTierFor(mb)
|
|
@@ -289,18 +293,25 @@ export function createEnforcement({ watchdogState, refs, dataDir, journalDir, ex
|
|
|
289
293
|
summary.closed.push(row.name)
|
|
290
294
|
appendIncident({ kind: 'plugin-memory', level: tier, target: row.name, mb, detail: '插件内存 ' + mb + ' MB ≥ ' + (tier === 'all-third-party' ? 3000 : 1000) + ' MB:强制关闭' })
|
|
291
295
|
if (tier === 'all-third-party') {
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
296
|
+
const others = enabled
|
|
297
|
+
.filter((other) => other.name !== row.name && other.official !== true && !String(other.name).startsWith('@deepseek-ai/'))
|
|
298
|
+
.filter((other) => !watchdogState.quarantine.has(other.name))
|
|
299
|
+
.map((other) => ({ name: other.name, mb: measuredMemoryMB(other.name) }))
|
|
300
|
+
.sort((a, b) => b.mb - a.mb)
|
|
301
|
+
const selected = others.slice(0, Math.max(0, MAX_THIRD_PARTY_CLOSURES - summary.thirdParty.length))
|
|
302
|
+
const pending = others.slice(Math.max(0, MAX_THIRD_PARTY_CLOSURES - summary.thirdParty.length))
|
|
303
|
+
for (const other of selected) {
|
|
295
304
|
watchdogState.quarantine.set(other.name, { reason: 'memory', level: 'L2', at: new Date().toISOString(), release: 'manual', evidence: '同批第三方关闭(' + row.name + ' ≥3000 MB)', remediation: remediationFor('memory') })
|
|
296
305
|
await disableTarget(other.name, 'memory-all-third-party')
|
|
297
306
|
summary.thirdParty.push(other.name)
|
|
298
307
|
}
|
|
299
|
-
|
|
308
|
+
watchdogState.thirdPartyPending = [...(watchdogState.thirdPartyPending || []), ...pending.map((other) => ({ name: other.name, mb: other.mb, reason: 'all-third-party-cap' }))]
|
|
309
|
+
summary.thirdPartyPending = watchdogState.thirdPartyPending.map((other) => other.name)
|
|
310
|
+
appendIncident({ kind: 'plugin-memory', level: 'all-third-party', target: row.name, mb, detail: '单个插件 ≥3000 MB:本轮关闭 ' + summary.thirdParty.length + ' 个第三方插件(上限 ' + MAX_THIRD_PARTY_CLOSURES + ');待人工处理 ' + summary.thirdPartyPending.length + ' 个' })
|
|
300
311
|
}
|
|
301
312
|
writePendingBoot({ level: 'L1', reason: 'memory', disable: [row.name, ...summary.thirdParty], keep: [] })
|
|
302
313
|
}
|
|
303
|
-
if (summary.closed.length || summary.uninstalled.length || summary.thirdParty.length) persist(true)
|
|
314
|
+
if (summary.closed.length || summary.uninstalled.length || summary.thirdParty.length || summary.thirdPartyPending.length) persist(true)
|
|
304
315
|
return summary
|
|
305
316
|
}
|
|
306
317
|
|
|
@@ -309,7 +320,17 @@ export function createEnforcement({ watchdogState, refs, dataDir, journalDir, ex
|
|
|
309
320
|
if (!result || !Array.isArray(result.diffs) || result.diffs.length === 0) return
|
|
310
321
|
const files = result.diffs.map((diff) => diff.file)
|
|
311
322
|
const policy = (watchdogState.tamper && watchdogState.tamper.policy) || 'observe'
|
|
312
|
-
appendIncident({
|
|
323
|
+
appendIncident({
|
|
324
|
+
kind: 'tamper',
|
|
325
|
+
files,
|
|
326
|
+
policy,
|
|
327
|
+
restored: result.restored,
|
|
328
|
+
notify: policy === 'alert',
|
|
329
|
+
detail:
|
|
330
|
+
'配置漂移:' + files.join(', ')
|
|
331
|
+
+ (policy === 'observe' ? '(observe:仅记录,不恢复不关闭)' : '')
|
|
332
|
+
+ (policy === 'alert' ? '(alert:发出告警事件,不自动恢复;是否隔离由人工决定)' : ''),
|
|
333
|
+
})
|
|
313
334
|
let target = null
|
|
314
335
|
let evidence = []
|
|
315
336
|
try {
|
|
@@ -30,6 +30,8 @@ export function createPersistence({ watchdogState, stateFile, incidentsFile }) {
|
|
|
30
30
|
rssStats: watchdogState.rssStats || null,
|
|
31
31
|
rssServiceError: watchdogState.rssServiceError || null,
|
|
32
32
|
rssAttempts: watchdogState.rssAttempts || 0,
|
|
33
|
+
heap6g: Boolean(watchdogState.heap6g),
|
|
34
|
+
thirdPartyPending: watchdogState.thirdPartyPending || [],
|
|
33
35
|
migratedTamperQuarantine: tamperMigrationDone,
|
|
34
36
|
}
|
|
35
37
|
try {
|
|
@@ -60,6 +62,8 @@ export function createPersistence({ watchdogState, stateFile, incidentsFile }) {
|
|
|
60
62
|
if (parsed.rssAt) watchdogState.rssAt = parsed.rssAt
|
|
61
63
|
if (parsed.rssStats) watchdogState.rssStats = parsed.rssStats
|
|
62
64
|
watchdogState.rssAttempts = Number(parsed.rssAttempts) || 0
|
|
65
|
+
watchdogState.heap6g = parsed.heap6g === true
|
|
66
|
+
if (Array.isArray(parsed.thirdPartyPending)) watchdogState.thirdPartyPending = parsed.thirdPartyPending.slice(0, 50)
|
|
63
67
|
tamperMigrationDone = parsed.migratedTamperQuarantine === true
|
|
64
68
|
if (Array.isArray(parsed.quarantine)) {
|
|
65
69
|
let dropped = 0
|
|
@@ -69,12 +73,15 @@ export function createPersistence({ watchdogState, stateFile, incidentsFile }) {
|
|
|
69
73
|
continue
|
|
70
74
|
}
|
|
71
75
|
if (entry && typeof entry.target === 'string') {
|
|
72
|
-
|
|
76
|
+
const { target, ...extra } = entry
|
|
77
|
+
watchdogState.quarantine.set(target, {
|
|
73
78
|
reason: entry.reason || 'crash',
|
|
74
79
|
level: entry.level || 'L1',
|
|
75
80
|
at: entry.at || new Date().toISOString(),
|
|
76
81
|
release: entry.release || 'manual',
|
|
77
82
|
evidence: entry.evidence || '',
|
|
83
|
+
...extra,
|
|
84
|
+
...(entry.remediation && typeof entry.remediation === 'object' ? { remediation: entry.remediation } : {}),
|
|
78
85
|
})
|
|
79
86
|
}
|
|
80
87
|
}
|
package/lib/watchdog-policy.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* opWarn ~67% of the cap -> strong warning once the user continued through pause
|
|
9
9
|
* opBlock ~83% of the cap -> agent-side plugin_manager guard refuses
|
|
10
10
|
* On a 6 GB host that yields 3.0/3.9/5.0 GB and 4.0/5.0 GB operation gates; on a
|
|
11
|
-
* 4 GB host the same ratios map down to 2.
|
|
11
|
+
* 4 GB host the same ratios map down to 2.92/3.52/3.72 GB and 2.73/3.41 GB.
|
|
12
12
|
*/
|
|
13
13
|
export const MB = 1024 * 1024
|
|
14
14
|
export const GB = 1024 * MB
|
|
@@ -35,7 +35,7 @@ export const READONLY_ACTIONS = new Set(['list_plugins', 'list_bundles', 'list_v
|
|
|
35
35
|
export function thresholdsFor(heapLimitBytes) {
|
|
36
36
|
const limit = Number(heapLimitBytes) > 0 ? Number(heapLimitBytes) : 4 * GB
|
|
37
37
|
const clamp = (absolute, ratio) => Math.min(absolute, ratio * limit)
|
|
38
|
-
|
|
38
|
+
const nominal = {
|
|
39
39
|
heapLimit: limit,
|
|
40
40
|
singleWarn: clamp(300 * MB, 0.075),
|
|
41
41
|
singleBlock: clamp(500 * MB, 0.125),
|
|
@@ -45,6 +45,17 @@ export function thresholdsFor(heapLimitBytes) {
|
|
|
45
45
|
opWarn: clamp(4 * GB, 2 / 3),
|
|
46
46
|
opBlock: clamp(5 * GB, 5 / 6),
|
|
47
47
|
}
|
|
48
|
+
const shift = (value) => Math.max(0, value - FREEZE_MARGIN)
|
|
49
|
+
const effective = {
|
|
50
|
+
totalWarn: shift(nominal.totalWarn),
|
|
51
|
+
totalPause: shift(nominal.totalPause),
|
|
52
|
+
totalBlock: shift(nominal.totalBlock),
|
|
53
|
+
opWarn: shift(nominal.opWarn),
|
|
54
|
+
opBlock: shift(nominal.opBlock),
|
|
55
|
+
}
|
|
56
|
+
// The classifier applies FREEZE_MARGIN exactly once; the top-level values stay
|
|
57
|
+
// nominal for backwards compatibility, while the UI reads only `display`.
|
|
58
|
+
return { ...nominal, nominal, effective, display: effective }
|
|
48
59
|
}
|
|
49
60
|
|
|
50
61
|
/** Waterline for the whole host, with the active level to keep hysteresis. */
|
package/lib/watchdog-runtime.js
CHANGED
|
@@ -63,6 +63,9 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
63
63
|
// ---- persistence, enforcement, crash, budget ---------------------------
|
|
64
64
|
const persistence = createPersistence({ watchdogState, stateFile, incidentsFile })
|
|
65
65
|
persistence.restoreState()
|
|
66
|
+
// The request file is the durable source of truth: state.json may be stale
|
|
67
|
+
// if the user canceled after the last flush.
|
|
68
|
+
watchdogState.heap6g = fs.existsSync(path.join(dataDir, 'heap6g-request.json'))
|
|
66
69
|
|
|
67
70
|
const enforcement = createEnforcement({
|
|
68
71
|
watchdogState,
|
package/lib/watchdog-snapshot.js
CHANGED
|
@@ -76,6 +76,11 @@ export function watchdogSnapshot() {
|
|
|
76
76
|
? { at: lastPlan.at, level: lastPlan.level, target: lastPlan.target || null, inFlight: Boolean(lastPlan.inFlight), applied: Boolean(lastPlan.applied), fallback: lastPlan.fallback || null, targets: lastPlan.targets || [] }
|
|
77
77
|
: null,
|
|
78
78
|
}
|
|
79
|
+
const ranked = mergedTop(s, 10)
|
|
80
|
+
const topFive = ranked.slice(0, 5).map((row) => {
|
|
81
|
+
const tier = s.memoryTiers instanceof Map ? s.memoryTiers.get(row.target) : undefined
|
|
82
|
+
return { ...row, memoryTier: tier ? tier.tier : 'ok', memoryMB: tier ? tier.mb : null }
|
|
83
|
+
})
|
|
79
84
|
return {
|
|
80
85
|
ok: Boolean(s.startedAt),
|
|
81
86
|
crashPlan,
|
|
@@ -93,11 +98,8 @@ export function watchdogSnapshot() {
|
|
|
93
98
|
graceUntil: s.graceUntil,
|
|
94
99
|
frozenAt: s.frozenAt,
|
|
95
100
|
samples: s.samples.slice(-30),
|
|
96
|
-
operations:
|
|
97
|
-
topFive
|
|
98
|
-
const tier = s.memoryTiers instanceof Map ? s.memoryTiers.get(row.target) : undefined
|
|
99
|
-
return { ...row, memoryTier: tier ? tier.tier : 'ok', memoryMB: tier ? tier.mb : null }
|
|
100
|
-
}),
|
|
101
|
+
operations: ranked,
|
|
102
|
+
topFive,
|
|
101
103
|
probeProgress: s.probeProgress || null,
|
|
102
104
|
quarantine,
|
|
103
105
|
memoryTiers: s.memoryTiers instanceof Map ? [...s.memoryTiers].map(([target, entry]) => ({ target, ...entry })) : [],
|
|
@@ -111,6 +113,7 @@ export function watchdogSnapshot() {
|
|
|
111
113
|
boot: s.boot || null,
|
|
112
114
|
heap6g: s.heap6g === true,
|
|
113
115
|
heap6gRequest: s.dataDir && fs.existsSync(path.join(s.dataDir, 'heap6g-request.json')) ? path.join(s.dataDir, 'heap6g-request.json') : null,
|
|
116
|
+
thirdPartyPending: s.thirdPartyPending || [],
|
|
114
117
|
rss: s.rss || {},
|
|
115
118
|
rssAt: s.rssAt || null,
|
|
116
119
|
rssError: s.rssError || null,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@twinsearth/ai-prison-dsh-plugin",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.9.3",
|
|
4
4
|
"description": "AI Prison for DSH: eight governance tools wrapping the aiprison CLI (levels, status, watchdog status, 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",
|