dsh-safetymonitor-plug 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +81 -2
- package/client.js +176 -0
- package/cordis.patch.yml +3 -0
- package/docs/DETAIL.md +35 -0
- package/icon.svg +13 -0
- package/index.js +303 -0
- package/locale/en.json +13 -0
- package/locale/zh.json +13 -0
- package/monitor.mjs +505 -0
- package/package.json +63 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 user-yechen
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,82 @@
|
|
|
1
|
-
#
|
|
1
|
+
# dsh-safetymonitor-plug
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
DSH 上下文完整性监控插件。0.3.0 起按 **agent/session 分账**,并加入**同一回合用户消息去重、会话预算、空白时间片、单轮入口限流、历史告警日志**;仍然是**只读监控**:检查时间戳、来源、重复、工具断链、角色边界和提示注入特征,发现异常时在面板与本轮提示词中告警。
|
|
4
|
+
|
|
5
|
+
## 安装
|
|
6
|
+
|
|
7
|
+
插件已上传 GitHub:
|
|
8
|
+
|
|
9
|
+
```powershell
|
|
10
|
+
git clone https://github.com/user-yechen/dsh-safetymonitor-plug.git
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
然后在 **Plugins > Add plugin** 中选择该目录。安装后重启 DSH,输入框下方会出现 `安全监控` 胶囊。
|
|
14
|
+
|
|
15
|
+
本地目录安装会链接当前 checkout;修改 Host 代码后建议重启 DSH,确保加载新的模块代际。
|
|
16
|
+
|
|
17
|
+
## 0.3.0 更新
|
|
18
|
+
|
|
19
|
+
- 同一回合的同一用户消息只记录一次(按 `turn + message id` 去重),修复工具循环导致的重复事件误报;
|
|
20
|
+
- `issues.log` 追加式历史告警,`reset` 后仍可追溯;
|
|
21
|
+
- 面板与 `/safetymonitor` 返回最近 50 条历史告警;
|
|
22
|
+
- `reset` 后 15 秒内不把工具结果判为孤立结果,避免重建边界的假阳性;
|
|
23
|
+
- 14 个离线测试。
|
|
24
|
+
|
|
25
|
+
## 0.2.0 更新
|
|
26
|
+
|
|
27
|
+
- 按 `agent/created` 建立 per-session 监控;状态文件改为 `{ sessions, activeSessionId }`;
|
|
28
|
+
- 会话预算:默认 `maxTurns=200`,达到 80% 警告、100% 严重;
|
|
29
|
+
- 单轮入口限流:默认 `maxIngressPerTurn=30`;
|
|
30
|
+
- 空白时间片:回合推进但本回合没有消息/工具事件时告警;
|
|
31
|
+
- `reset` 原地重置,避免旧事件监听器指向已替换的状态对象。
|
|
32
|
+
|
|
33
|
+
## 结构
|
|
34
|
+
|
|
35
|
+
```text
|
|
36
|
+
index.js Host:事件监听、状态落盘、/safetymonitor 路由
|
|
37
|
+
monitor.mjs 纯检测核心:时间/来源/重复/注入/健康报告
|
|
38
|
+
client.js Client:状态胶囊 + 问题面板 + 来源表 + 敏感度
|
|
39
|
+
docs/DETAIL.md 插件详情页
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## 检查项
|
|
43
|
+
|
|
44
|
+
| 代码 | 含义 | 默认级别 |
|
|
45
|
+
|---|---|---|
|
|
46
|
+
| `time/out-of-order` | 新事件早于上一条 | warn |
|
|
47
|
+
| `time/future` | 事件时间晚于本地时钟 | warn |
|
|
48
|
+
| `time/gap` | 事件间隔偏大 | info |
|
|
49
|
+
| `source/unknown` | 事件没有来源 | warn |
|
|
50
|
+
| `source/conflict` | 工具结果自称来自其他来源 | warn |
|
|
51
|
+
| `flow/duplicate` | 窗口内重复事件 | warn |
|
|
52
|
+
| `flow/orphan-result` | 工具结果没有对应调用 | info |
|
|
53
|
+
| `content/injection` | 疑似提示注入 | critical |
|
|
54
|
+
| `content/authority-spoof` | 普通消息伪装系统/管理员 | warn |
|
|
55
|
+
| `content/role-confusion` | 角色边界异常 | warn |
|
|
56
|
+
| `content/invisible` | 零宽/方向控制字符 | warn |
|
|
57
|
+
| `context/repeat` | 连续用户消息完全相同 | warn |
|
|
58
|
+
| `context/oversize` | 单条文本超过 20k 字符 | info |
|
|
59
|
+
| `flow/blank-slice` | 回合推进但本回合无消息/工具事件 | warn |
|
|
60
|
+
| `budget/turns` | 会话轮数达到 80%/100% 预算 | warn / critical |
|
|
61
|
+
| `budget/ingress` | 单轮入口事件超过上限 | warn |
|
|
62
|
+
|
|
63
|
+
## 设计原则
|
|
64
|
+
|
|
65
|
+
- **证据优先**:日志、时间戳、来源、事件 ID,而不是模型自述;
|
|
66
|
+
- **只读**:不删除上下文、不拦截工具;
|
|
67
|
+
- **可解释**:每条告警有代码、来源、证据和时间;
|
|
68
|
+
- **防回环**:告警只进入提示词一次,不写回用户消息;
|
|
69
|
+
- **可降级**:监控异常不影响主流程。
|
|
70
|
+
|
|
71
|
+
## 已知限制
|
|
72
|
+
|
|
73
|
+
- 按 `agent/created` 注册;插件加载前已经存在的 agent 可能走 `default` 兜底,需要新会话验证 per-session。
|
|
74
|
+
- 只使用 Host 事件和本地状态文件,不读取完整 session log。
|
|
75
|
+
- 关键词规则会误判。
|
|
76
|
+
- 没有自动 quarantine / 工具拦截 / 哈希链审计。
|
|
77
|
+
- 默认 `sensitivity` 只影响展示,不改变阈值。
|
|
78
|
+
- `budget/turns` 是告警,不是强制熔断;不会自动停止工作。
|
|
79
|
+
|
|
80
|
+
## License
|
|
81
|
+
|
|
82
|
+
MIT
|
package/client.js
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
window.__ModuleLoader__.load({
|
|
2
|
+
id: 'dsh-safetymonitor-plug',
|
|
3
|
+
factory(require) {
|
|
4
|
+
const React = require('react')
|
|
5
|
+
const h = React.createElement
|
|
6
|
+
|
|
7
|
+
const STATUS_LABEL = { ok: '正常', warn: '注意', critical: '警告' }
|
|
8
|
+
const STATUS_COLOR = { ok: '#2f9e63', warn: '#c58a16', critical: '#d64545' }
|
|
9
|
+
const SEVERITY_LABEL = { info: '信息', warn: '注意', critical: '严重' }
|
|
10
|
+
|
|
11
|
+
function Monitor() {
|
|
12
|
+
const [state, setState] = React.useState(null)
|
|
13
|
+
const [history, setHistory] = React.useState([])
|
|
14
|
+
const [open, setOpen] = React.useState(false)
|
|
15
|
+
const [busy, setBusy] = React.useState(false)
|
|
16
|
+
|
|
17
|
+
const load = async () => {
|
|
18
|
+
try {
|
|
19
|
+
const res = await fetch('/safetymonitor')
|
|
20
|
+
const body = await res.json()
|
|
21
|
+
if (body && body.state) setState(body.state)
|
|
22
|
+
if (body && Array.isArray(body.history)) setHistory(body.history)
|
|
23
|
+
} catch {
|
|
24
|
+
/* 忽略 */
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
React.useEffect(() => {
|
|
29
|
+
load()
|
|
30
|
+
const timer = setInterval(load, 5000)
|
|
31
|
+
return () => clearInterval(timer)
|
|
32
|
+
}, [])
|
|
33
|
+
|
|
34
|
+
const send = async (action, payload = {}) => {
|
|
35
|
+
if (busy) return
|
|
36
|
+
setBusy(true)
|
|
37
|
+
try {
|
|
38
|
+
const res = await fetch('/safetymonitor', {
|
|
39
|
+
method: 'POST',
|
|
40
|
+
headers: { 'Content-Type': 'application/json' },
|
|
41
|
+
body: JSON.stringify({ action, ...payload }),
|
|
42
|
+
})
|
|
43
|
+
const body = await res.json()
|
|
44
|
+
if (body && body.state) setState(body.state)
|
|
45
|
+
if (body && Array.isArray(body.history)) setHistory(body.history)
|
|
46
|
+
} catch {
|
|
47
|
+
/* 忽略 */
|
|
48
|
+
} finally {
|
|
49
|
+
setBusy(false)
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const status = state?.status || 'ok'
|
|
54
|
+
const color = STATUS_COLOR[status] || STATUS_COLOR.ok
|
|
55
|
+
const issues = state?.issues || []
|
|
56
|
+
const sources = state?.sources || []
|
|
57
|
+
|
|
58
|
+
const shell = { margin: '4px 0 2px', fontSize: 12, color: 'var(--dsw-alias-text-2, #555)' }
|
|
59
|
+
const capsule = {
|
|
60
|
+
display: 'inline-flex', alignItems: 'center', gap: 8,
|
|
61
|
+
padding: '3px 10px', borderRadius: 999,
|
|
62
|
+
border: `1px solid ${color}`,
|
|
63
|
+
background: 'var(--dsw-alias-bg-2, transparent)',
|
|
64
|
+
cursor: 'pointer', userSelect: 'none',
|
|
65
|
+
}
|
|
66
|
+
const card = {
|
|
67
|
+
marginTop: 6, padding: '10px 12px', borderRadius: 10,
|
|
68
|
+
border: '1px solid var(--dsw-alias-border, rgba(127,127,127,.28))',
|
|
69
|
+
background: 'var(--dsw-alias-bg-2, transparent)',
|
|
70
|
+
}
|
|
71
|
+
const row = { display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }
|
|
72
|
+
const btn = {
|
|
73
|
+
padding: '2px 8px', borderRadius: 6,
|
|
74
|
+
border: '1px solid var(--dsw-alias-border, rgba(127,127,127,.28))',
|
|
75
|
+
background: 'transparent', color: 'inherit', cursor: 'pointer', fontSize: 11,
|
|
76
|
+
}
|
|
77
|
+
const select = {
|
|
78
|
+
padding: '2px 4px', borderRadius: 4,
|
|
79
|
+
border: '1px solid var(--dsw-alias-border, rgba(127,127,127,.28))',
|
|
80
|
+
background: 'transparent', color: 'inherit', fontSize: 11,
|
|
81
|
+
}
|
|
82
|
+
const issueColor = { critical: '#d64545', warn: '#c58a16', info: '#6b7a8f' }
|
|
83
|
+
|
|
84
|
+
return h('div', { style: shell }, [
|
|
85
|
+
h('div', {
|
|
86
|
+
key: 'cap', style: capsule,
|
|
87
|
+
onClick: () => setOpen((v) => !v),
|
|
88
|
+
title: '点击展开上下文完整性监控',
|
|
89
|
+
}, [
|
|
90
|
+
h('span', { key: 'dot', style: { width: 7, height: 7, borderRadius: 999, background: color } }),
|
|
91
|
+
h('span', { key: 'label' }, `安全监控 · ${STATUS_LABEL[status] || status}`),
|
|
92
|
+
state ? h('span', { key: 'count', style: { opacity: 0.6 } }, `${issues.length} 项`) : null,
|
|
93
|
+
]),
|
|
94
|
+
open && state
|
|
95
|
+
? h('div', { key: 'card', style: card }, [
|
|
96
|
+
h('div', { key: 'head', style: { ...row, justifyContent: 'space-between' } }, [
|
|
97
|
+
h('strong', { key: 'title' }, '上下文完整性监控'),
|
|
98
|
+
h('div', { key: 'acts', style: { display: 'flex', gap: 6 } }, [
|
|
99
|
+
h('button', { key: 'ack', type: 'button', style: btn, disabled: busy || !issues.length, onClick: () => send('ackAll') }, '全部确认'),
|
|
100
|
+
h('button', { key: 'reset', type: 'button', style: btn, disabled: busy, onClick: () => send('reset') }, '重置'),
|
|
101
|
+
]),
|
|
102
|
+
]),
|
|
103
|
+
h('div', { key: 'meta', style: { opacity: 0.65, marginBottom: 6 } },
|
|
104
|
+
`会话 ${String(state.sessionId || 'default').slice(0, 8)} · 事件 ${state.counts?.events || 0} · 严重 ${state.counts?.critical || 0} · 注意 ${state.counts?.warn || 0} · 回合 ${state.lastTurn || 0}/${state.config?.maxTurns || '—'}`),
|
|
105
|
+
h('div', { key: 'cfg', style: { ...row, marginBottom: 8 } }, [
|
|
106
|
+
h('span', { key: 'l', style: { opacity: 0.7 } }, '敏感度'),
|
|
107
|
+
h('select', {
|
|
108
|
+
key: 's', style: select, value: state.config?.sensitivity || 'normal',
|
|
109
|
+
onChange: (event) => send('config', { config: { sensitivity: event.target.value } }),
|
|
110
|
+
}, [
|
|
111
|
+
h('option', { key: 'low', value: 'low' }, '低'),
|
|
112
|
+
h('option', { key: 'normal', value: 'normal' }, '正常'),
|
|
113
|
+
h('option', { key: 'high', value: 'high' }, '高'),
|
|
114
|
+
]),
|
|
115
|
+
h('span', { key: 'gap', style: { opacity: 0.7, marginLeft: 8 } },
|
|
116
|
+
`最大间隔 ${Math.round((state.config?.maxGapMs || 0) / 60000)} 分钟`),
|
|
117
|
+
h('span', { key: 'turn', style: { opacity: 0.7, marginLeft: 8 } }, '最大轮数'),
|
|
118
|
+
h('input', {
|
|
119
|
+
key: 'maxTurns', type: 'number', defaultValue: state.config?.maxTurns || 200,
|
|
120
|
+
min: 10, max: 5000,
|
|
121
|
+
style: { width: 54, padding: '2px 4px', borderRadius: 4, border: '1px solid var(--dsw-alias-border, rgba(127,127,127,.28))', background: 'transparent', color: 'inherit', fontSize: 11 },
|
|
122
|
+
onBlur: (event) => send('config', { config: { maxTurns: Number(event.target.value) } }),
|
|
123
|
+
onKeyDown: (event) => { if (event.key === 'Enter') event.currentTarget.blur() },
|
|
124
|
+
}),
|
|
125
|
+
]),
|
|
126
|
+
issues.length
|
|
127
|
+
? h('div', { key: 'issues' }, issues.slice().reverse().map((issue) => h('div', {
|
|
128
|
+
key: issue.id,
|
|
129
|
+
style: { padding: '5px 0', borderTop: '1px solid var(--dsw-alias-border, rgba(127,127,127,.16))' },
|
|
130
|
+
}, [
|
|
131
|
+
h('div', { key: 't', style: { color: issueColor[issue.severity] || 'inherit', fontWeight: 600 } },
|
|
132
|
+
`[${SEVERITY_LABEL[issue.severity] || issue.severity}] ${issue.title}${issue.count > 1 ? ` ×${issue.count}` : ''}`),
|
|
133
|
+
h('div', { key: 'd', style: { opacity: 0.75, marginTop: 1 } }, issue.detail || ''),
|
|
134
|
+
h('div', { key: 'm', style: { opacity: 0.55, marginTop: 1 } },
|
|
135
|
+
`来源 ${issue.source} · ${new Date(issue.lastAt || issue.at).toLocaleString()}`),
|
|
136
|
+
h('button', { key: 'a', type: 'button', style: { ...btn, marginTop: 3 }, disabled: busy, onClick: () => send('ack', { id: issue.id }) }, '确认'),
|
|
137
|
+
])))
|
|
138
|
+
: h('div', { key: 'ok', style: { opacity: 0.7, padding: '6px 0' } }, '未发现异常。'),
|
|
139
|
+
h('div', { key: 'srcTitle', style: { marginTop: 8, opacity: 0.6 } }, '数据流接入口'),
|
|
140
|
+
h('div', { key: 'src', style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '2px 12px', marginTop: 3 } },
|
|
141
|
+
sources.filter((item) => item.events > 0 || item.key === 'unknown').map((item) => h('div', {
|
|
142
|
+
key: item.key,
|
|
143
|
+
style: { display: 'flex', justifyContent: 'space-between', opacity: item.trust === 'untrusted' ? 0.95 : 0.72 },
|
|
144
|
+
title: `信任级别:${item.trust}`,
|
|
145
|
+
}, [
|
|
146
|
+
h('span', { key: 'n' }, item.label),
|
|
147
|
+
h('span', { key: 'v' }, `${item.events}${item.trust === 'untrusted' ? ' · 不可信' : ''}`),
|
|
148
|
+
]))),
|
|
149
|
+
h('details', { key: 'history', style: { marginTop: 8 } }, [
|
|
150
|
+
h('summary', { key: 'hs', style: { cursor: 'pointer', opacity: 0.65 } }, `历史告警 ${history.length}`),
|
|
151
|
+
history.length
|
|
152
|
+
? h('div', { key: 'hl', style: { marginTop: 4 } }, history.slice(-10).reverse().map((item) => h('div', {
|
|
153
|
+
key: `${item.sessionId}:${item.id}:${item.at}`,
|
|
154
|
+
style: { padding: '3px 0', opacity: 0.7, fontSize: 11 },
|
|
155
|
+
}, `${new Date(item.at).toLocaleString()} · ${item.severity} · ${item.title} · ${String(item.sessionId || '').slice(0, 8)}`)))
|
|
156
|
+
: h('div', { key: 'he', style: { opacity: 0.5, fontSize: 11, marginTop: 3 } }, '暂无历史'),
|
|
157
|
+
]),
|
|
158
|
+
h('div', { key: 'note', style: { marginTop: 8, opacity: 0.55, fontSize: 11 } },
|
|
159
|
+
'只读监控:不删除上下文、不拦截工具。严重告警会同时进入本轮提示词。'),
|
|
160
|
+
])
|
|
161
|
+
: null,
|
|
162
|
+
])
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
return {
|
|
166
|
+
inject: ['slots'],
|
|
167
|
+
apply(ctx) {
|
|
168
|
+
ctx.slots.inject('conversation.composer.dock', () => ctx.slots.register({
|
|
169
|
+
name: 'conversation.composer.dock',
|
|
170
|
+
id: 'dsh-safetymonitor-plug',
|
|
171
|
+
order: 6,
|
|
172
|
+
}, Monitor))
|
|
173
|
+
},
|
|
174
|
+
}
|
|
175
|
+
},
|
|
176
|
+
})
|
package/cordis.patch.yml
ADDED
package/docs/DETAIL.md
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# 安全监控
|
|
2
|
+
|
|
3
|
+
`dsh-safetymonitor-plug` 是一个 **Host 侧只读监控插件**:按 agent/session 检查时间戳、来源、重复事件、工具断链、空白时间片、会话预算和提示注入特征。发现异常时,在输入框下方的面板和本轮提示词中给出警示。
|
|
4
|
+
|
|
5
|
+
它不删除上下文、不拦截工具、不修改其他插件的数据。
|
|
6
|
+
|
|
7
|
+
## 能检查什么
|
|
8
|
+
|
|
9
|
+
- 时间戳乱序、未来时间、事件间隔异常;
|
|
10
|
+
- 来源缺失、未知来源、工具结果来源冲突;
|
|
11
|
+
- 同一 message/context 事件在窗口内重复;同一回合同一用户消息只记一次;
|
|
12
|
+
- 重置后 15 秒内不把工具结果判为孤立结果;
|
|
13
|
+
- 工具结果没有对应调用;
|
|
14
|
+
- 回合推进但本回合没有消息/工具事件(空白时间片);
|
|
15
|
+
- 会话轮数达到 80%/100% 预算;
|
|
16
|
+
- 单轮入口事件超过上限;
|
|
17
|
+
- 提示注入、权威伪装、角色混淆、不可见字符;
|
|
18
|
+
- 数据流接入口的事件计数与信任级别。
|
|
19
|
+
|
|
20
|
+
## 怎么用
|
|
21
|
+
|
|
22
|
+
1. 安装后在输入框下方出现 `安全监控` 胶囊;
|
|
23
|
+
2. 点击展开:查看异常、来源、会话轮数和预算;
|
|
24
|
+
3. 可以调整敏感度、最大间隔、最大轮数;
|
|
25
|
+
4. `确认` 清除单条;`全部确认` 清除全部;`重置` 清空当前会话状态;历史告警仍保留在 `issues.log`;
|
|
26
|
+
5. 严重异常会同时进入本轮提示词。
|
|
27
|
+
|
|
28
|
+
## 边界
|
|
29
|
+
|
|
30
|
+
- 只检测**可见证据**,不读取模型隐藏状态;
|
|
31
|
+
- 不保证 100% 识别提示注入;
|
|
32
|
+
- 不自动删除上下文,不自动拦截工具;
|
|
33
|
+
- 预算告警不是强制熔断;
|
|
34
|
+
- 按 `agent/created` 注册;插件加载前已存在的 agent 可能走 `default` 兜底;
|
|
35
|
+
- 不读取完整 session log,只使用 Host 事件与本地状态文件。
|
package/icon.svg
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="Safety monitor">
|
|
2
|
+
<defs>
|
|
3
|
+
<linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
|
|
4
|
+
<stop offset="0" stop-color="#2f6f9f"/>
|
|
5
|
+
<stop offset="1" stop-color="#1d3f5c"/>
|
|
6
|
+
</linearGradient>
|
|
7
|
+
</defs>
|
|
8
|
+
<path d="M32 4 54 12v18c0 14-9.5 24.5-22 30C19.5 54.5 10 44 10 30V12z" fill="url(#g)"/>
|
|
9
|
+
<path d="M32 8.5 49.5 15v15c0 11.5-7.6 20.2-17.5 25C22.1 50.2 14.5 41.5 14.5 30V15z" fill="none" stroke="#d7e9f7" stroke-width="2"/>
|
|
10
|
+
<ellipse cx="32" cy="30" rx="11" ry="7" fill="#d7e9f7"/>
|
|
11
|
+
<circle cx="32" cy="30" r="3.5" fill="#1d3f5c"/>
|
|
12
|
+
<path d="M20 44c4 5 8.5 8 12 9.5" fill="none" stroke="#8fc4e8" stroke-width="2" stroke-linecap="round"/>
|
|
13
|
+
</svg>
|
package/index.js
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-safetymonitor-plug — Host 半身 0.2.0。
|
|
3
|
+
*
|
|
4
|
+
* 只读监控:时间戳、来源、重复、断链、角色边界、提示注入特征。
|
|
5
|
+
* 0.2.0 起按 agent/session 分账;加入会话预算、空白时间片、入口限流。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
9
|
+
import { homedir } from 'node:os'
|
|
10
|
+
import { join } from 'node:path'
|
|
11
|
+
|
|
12
|
+
import {
|
|
13
|
+
ackAll,
|
|
14
|
+
ackIssue,
|
|
15
|
+
createMonitor,
|
|
16
|
+
healthOf,
|
|
17
|
+
inspectMessages,
|
|
18
|
+
inspectToolResult,
|
|
19
|
+
migrateMonitor,
|
|
20
|
+
recordToolCall,
|
|
21
|
+
recordTurn,
|
|
22
|
+
renderWarning,
|
|
23
|
+
resetMonitor,
|
|
24
|
+
updateConfig,
|
|
25
|
+
} from './monitor.mjs'
|
|
26
|
+
|
|
27
|
+
export const name = 'dsh-safetymonitor-plug'
|
|
28
|
+
export const inject = ['systemPrompt', 'webServer']
|
|
29
|
+
|
|
30
|
+
const STATE_DIR = join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'safety-monitor')
|
|
31
|
+
const STATE_FILE = join(STATE_DIR, 'state.json')
|
|
32
|
+
const ISSUES_LOG = join(STATE_DIR, 'issues.log')
|
|
33
|
+
const MAX_SESSIONS = 20
|
|
34
|
+
const MAX_HISTORY = 200
|
|
35
|
+
|
|
36
|
+
let store = loadStore()
|
|
37
|
+
const monitorDisposers = new Map()
|
|
38
|
+
|
|
39
|
+
function loadStore() {
|
|
40
|
+
try {
|
|
41
|
+
const raw = JSON.parse(readFileSync(STATE_FILE, 'utf8'))
|
|
42
|
+
if (raw && raw.sessions && typeof raw.sessions === 'object') {
|
|
43
|
+
const sessions = {}
|
|
44
|
+
for (const [id, value] of Object.entries(raw.sessions).slice(0, MAX_SESSIONS)) {
|
|
45
|
+
sessions[id] = migrateMonitor(value, Date.now())
|
|
46
|
+
sessions[id].sessionId = id
|
|
47
|
+
}
|
|
48
|
+
const activeSessionId = sessions[raw.activeSessionId] ? raw.activeSessionId : Object.keys(sessions)[0] || 'default'
|
|
49
|
+
return {
|
|
50
|
+
v: 2,
|
|
51
|
+
sessions,
|
|
52
|
+
activeSessionId,
|
|
53
|
+
history: Array.isArray(raw.history) ? raw.history.slice(-MAX_HISTORY) : [],
|
|
54
|
+
historyKeys: Array.isArray(raw.historyKeys) ? raw.historyKeys.slice(-MAX_HISTORY) : [],
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
// 0.1.0 的单实例状态迁移成一个 default session。
|
|
58
|
+
const migrated = migrateMonitor(raw, Date.now())
|
|
59
|
+
return { v: 2, sessions: { default: migrated }, activeSessionId: 'default', history: [], historyKeys: [] }
|
|
60
|
+
} catch {
|
|
61
|
+
return { v: 2, sessions: { default: createMonitor(Date.now(), 'default') }, activeSessionId: 'default', history: [], historyKeys: [] }
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function archiveIssues() {
|
|
66
|
+
if (!Array.isArray(store.history)) store.history = []
|
|
67
|
+
if (!Array.isArray(store.historyKeys)) store.historyKeys = []
|
|
68
|
+
for (const [sessionId, mon] of Object.entries(store.sessions)) {
|
|
69
|
+
for (const issue of mon.issues || []) {
|
|
70
|
+
const key = `${sessionId}:${issue.id}:${issue.at}`
|
|
71
|
+
if (store.historyKeys.includes(key)) continue
|
|
72
|
+
store.historyKeys.push(key)
|
|
73
|
+
const entry = {
|
|
74
|
+
sessionId,
|
|
75
|
+
id: issue.id,
|
|
76
|
+
code: issue.code,
|
|
77
|
+
severity: issue.severity,
|
|
78
|
+
title: issue.title,
|
|
79
|
+
detail: issue.detail,
|
|
80
|
+
source: issue.source,
|
|
81
|
+
evidence: issue.evidence,
|
|
82
|
+
at: issue.at,
|
|
83
|
+
}
|
|
84
|
+
store.history.push(entry)
|
|
85
|
+
try {
|
|
86
|
+
mkdirSync(STATE_DIR, { recursive: true })
|
|
87
|
+
writeFileSync(ISSUES_LOG, `${JSON.stringify(entry)}\n`, { encoding: 'utf8', flag: 'a' })
|
|
88
|
+
} catch {
|
|
89
|
+
/* 追加日志失败不阻塞 */
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (store.history.length > MAX_HISTORY) store.history.splice(0, store.history.length - MAX_HISTORY)
|
|
94
|
+
if (store.historyKeys.length > MAX_HISTORY * 2) store.historyKeys.splice(0, store.historyKeys.length - MAX_HISTORY * 2)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function saveStore() {
|
|
98
|
+
try {
|
|
99
|
+
archiveIssues()
|
|
100
|
+
mkdirSync(STATE_DIR, { recursive: true })
|
|
101
|
+
const ids = Object.keys(store.sessions)
|
|
102
|
+
if (ids.length > MAX_SESSIONS) {
|
|
103
|
+
for (const id of ids.slice(0, ids.length - MAX_SESSIONS)) delete store.sessions[id]
|
|
104
|
+
}
|
|
105
|
+
writeFileSync(STATE_FILE, JSON.stringify(store), 'utf8')
|
|
106
|
+
} catch {
|
|
107
|
+
/* 落盘失败不阻塞会话 */
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function monitorFor(agent) {
|
|
112
|
+
const id = String(agent?.session?.id || agent?.id || 'default')
|
|
113
|
+
if (!store.sessions[id]) store.sessions[id] = createMonitor(Date.now(), id)
|
|
114
|
+
store.sessions[id].sessionId = id
|
|
115
|
+
store.activeSessionId = id
|
|
116
|
+
return store.sessions[id]
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function currentMonitor() {
|
|
120
|
+
if (!store.sessions[store.activeSessionId]) {
|
|
121
|
+
store.activeSessionId = Object.keys(store.sessions)[0] || 'default'
|
|
122
|
+
store.sessions[store.activeSessionId] = createMonitor(Date.now(), store.activeSessionId)
|
|
123
|
+
}
|
|
124
|
+
return store.sessions[store.activeSessionId]
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function reply(res, status, body) {
|
|
128
|
+
try {
|
|
129
|
+
const payload = body && typeof body === 'object' ? { ...body } : body
|
|
130
|
+
if (payload && payload.state) payload.history = (store.history || []).slice(-50)
|
|
131
|
+
res.writeHead(status, {
|
|
132
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
133
|
+
'Cache-Control': 'no-store',
|
|
134
|
+
})
|
|
135
|
+
res.end(JSON.stringify(payload))
|
|
136
|
+
} catch {
|
|
137
|
+
/* 连接可能已关闭 */
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async function readBody(req) {
|
|
142
|
+
let raw = ''
|
|
143
|
+
for await (const chunk of req) raw += chunk
|
|
144
|
+
return raw ? JSON.parse(raw) : {}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function selectedMonitor(req) {
|
|
148
|
+
try {
|
|
149
|
+
const url = new URL(req.url || '/safetymonitor', 'http://127.0.0.1')
|
|
150
|
+
const id = url.searchParams.get('session')
|
|
151
|
+
if (id && store.sessions[id]) return store.sessions[id]
|
|
152
|
+
} catch {
|
|
153
|
+
/* 用 active */
|
|
154
|
+
}
|
|
155
|
+
return currentMonitor()
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function registerAgent(agent, pluginCtx) {
|
|
159
|
+
if (!agent || typeof agent.ctx?.on !== 'function') return
|
|
160
|
+
const id = String(agent.session?.id || agent.id || 'default')
|
|
161
|
+
const mon = monitorFor(agent)
|
|
162
|
+
store.activeSessionId = id
|
|
163
|
+
saveStore()
|
|
164
|
+
|
|
165
|
+
const install = () => {
|
|
166
|
+
const offs = [
|
|
167
|
+
agent.ctx.on('agent/pre-step', (decision, next) => {
|
|
168
|
+
try {
|
|
169
|
+
inspectMessages(mon, decision?.messages || [], Date.now())
|
|
170
|
+
saveStore()
|
|
171
|
+
} catch {
|
|
172
|
+
/* 监控失败不影响主流程 */
|
|
173
|
+
}
|
|
174
|
+
return typeof next === 'function' ? next() : undefined
|
|
175
|
+
}),
|
|
176
|
+
agent.ctx.on('tools/pre-execute', (exec, next) => {
|
|
177
|
+
try {
|
|
178
|
+
recordToolCall(mon, exec, Date.now())
|
|
179
|
+
saveStore()
|
|
180
|
+
} catch {
|
|
181
|
+
/* 监控失败不影响工具 */
|
|
182
|
+
}
|
|
183
|
+
return typeof next === 'function' ? next() : undefined
|
|
184
|
+
}),
|
|
185
|
+
agent.ctx.on('tools/result', (exec, result) => {
|
|
186
|
+
try {
|
|
187
|
+
inspectToolResult(mon, exec, result, Date.now())
|
|
188
|
+
saveStore()
|
|
189
|
+
} catch {
|
|
190
|
+
/* 监控失败不影响工具 */
|
|
191
|
+
}
|
|
192
|
+
}),
|
|
193
|
+
agent.ctx.on('turn/end', () => {
|
|
194
|
+
try {
|
|
195
|
+
recordTurn(mon, Date.now())
|
|
196
|
+
saveStore()
|
|
197
|
+
} catch {
|
|
198
|
+
/* 监控失败不影响回合 */
|
|
199
|
+
}
|
|
200
|
+
}),
|
|
201
|
+
]
|
|
202
|
+
return () => {
|
|
203
|
+
for (const off of offs) {
|
|
204
|
+
try { off() } catch { /* ignore */ }
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const dispose = agent.ctx.effect(install, `safety: agent ${id}`)
|
|
210
|
+
monitorDisposers.set(agent, dispose)
|
|
211
|
+
pluginCtx.effect(() => () => {
|
|
212
|
+
try { dispose() } catch { /* ignore */ }
|
|
213
|
+
monitorDisposers.delete(agent)
|
|
214
|
+
}, `safety: dispose ${id}`)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export function apply(ctx) {
|
|
218
|
+
try {
|
|
219
|
+
ctx.systemPrompt.context({
|
|
220
|
+
name: 'safety:monitor',
|
|
221
|
+
order: 180,
|
|
222
|
+
text: (context) => {
|
|
223
|
+
try {
|
|
224
|
+
return renderWarning(monitorFor(context?.agent))
|
|
225
|
+
} catch {
|
|
226
|
+
return ''
|
|
227
|
+
}
|
|
228
|
+
},
|
|
229
|
+
})
|
|
230
|
+
|
|
231
|
+
if (typeof ctx.on === 'function') {
|
|
232
|
+
ctx.effect(() => ctx.on('agent/created', (agent) => {
|
|
233
|
+
try {
|
|
234
|
+
registerAgent(agent, ctx)
|
|
235
|
+
} catch {
|
|
236
|
+
/* 单个 agent 注册失败不阻塞插件 */
|
|
237
|
+
}
|
|
238
|
+
}), 'safety: agent registry')
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
ctx.effect(() => {
|
|
242
|
+
const dispose = ctx.webServer.register({
|
|
243
|
+
kind: 'exact',
|
|
244
|
+
path: '/safetymonitor',
|
|
245
|
+
handler: async (req, res) => {
|
|
246
|
+
try {
|
|
247
|
+
const mon = selectedMonitor(req)
|
|
248
|
+
if (req.method === 'POST') {
|
|
249
|
+
const payload = await readBody(req)
|
|
250
|
+
const action = String(payload.action || '')
|
|
251
|
+
if (action === 'ack') {
|
|
252
|
+
const ok = ackIssue(mon, String(payload.id || ''))
|
|
253
|
+
saveStore()
|
|
254
|
+
return reply(res, ok ? 200 : 404, { ok, state: healthOf(mon) })
|
|
255
|
+
}
|
|
256
|
+
if (action === 'ackAll') {
|
|
257
|
+
ackAll(mon)
|
|
258
|
+
saveStore()
|
|
259
|
+
return reply(res, 200, { ok: true, state: healthOf(mon) })
|
|
260
|
+
}
|
|
261
|
+
if (action === 'config') {
|
|
262
|
+
updateConfig(mon, payload.config || {})
|
|
263
|
+
saveStore()
|
|
264
|
+
return reply(res, 200, { ok: true, state: healthOf(mon) })
|
|
265
|
+
}
|
|
266
|
+
if (action === 'reset') {
|
|
267
|
+
archiveIssues()
|
|
268
|
+
const id = mon.sessionId || 'default'
|
|
269
|
+
const fresh = resetMonitor(Date.now(), id)
|
|
270
|
+
fresh.sessionId = id
|
|
271
|
+
for (const key of Object.keys(mon)) delete mon[key]
|
|
272
|
+
Object.assign(mon, fresh)
|
|
273
|
+
store.sessions[id] = mon
|
|
274
|
+
saveStore()
|
|
275
|
+
return reply(res, 200, { ok: true, state: healthOf(mon) })
|
|
276
|
+
}
|
|
277
|
+
return reply(res, 400, { ok: false, error: 'unknown action' })
|
|
278
|
+
}
|
|
279
|
+
return reply(res, 200, {
|
|
280
|
+
ok: true,
|
|
281
|
+
state: healthOf(mon),
|
|
282
|
+
history: (store.history || []).slice(-50),
|
|
283
|
+
sessions: Object.keys(store.sessions).map((id) => ({
|
|
284
|
+
id,
|
|
285
|
+
active: id === store.activeSessionId,
|
|
286
|
+
status: healthOf(store.sessions[id]).status,
|
|
287
|
+
lastTurn: store.sessions[id].lastTurn,
|
|
288
|
+
})),
|
|
289
|
+
})
|
|
290
|
+
} catch (error) {
|
|
291
|
+
return reply(res, 200, {
|
|
292
|
+
ok: false,
|
|
293
|
+
error: String(error && error.message ? error.message : error),
|
|
294
|
+
})
|
|
295
|
+
}
|
|
296
|
+
},
|
|
297
|
+
})
|
|
298
|
+
return () => dispose()
|
|
299
|
+
}, 'safety: route')
|
|
300
|
+
} catch (error) {
|
|
301
|
+
ctx.logger?.warn?.(`safety: 初始化失败 ${String(error && error.message ? error.message : error)}`)
|
|
302
|
+
}
|
|
303
|
+
}
|
package/locale/en.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "Safety monitor",
|
|
4
|
+
"description": "Checks timestamps, provenance, duplicate events, broken links and prompt-injection signals; warns in the panel and conversation when context integrity looks abnormal. Read-only: it does not delete context or block tools.",
|
|
5
|
+
"detail": "docs/DETAIL.md"
|
|
6
|
+
},
|
|
7
|
+
"dock": {
|
|
8
|
+
"title": "Safety monitor",
|
|
9
|
+
"normal": "Normal",
|
|
10
|
+
"warn": "Attention",
|
|
11
|
+
"critical": "Warning"
|
|
12
|
+
}
|
|
13
|
+
}
|
package/locale/zh.json
ADDED
package/monitor.mjs
ADDED
|
@@ -0,0 +1,505 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-safetymonitor-plug — 纯检测核心。
|
|
3
|
+
*
|
|
4
|
+
* 这里不读取模型隐藏状态,也不做“我觉得自己中毒了”的判断。
|
|
5
|
+
* 它只检查可见证据:时间戳、来源、重复、断链、角色边界、
|
|
6
|
+
* 提示注入特征、压缩/恢复后的异常。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export const MONITOR_VERSION = 1
|
|
10
|
+
|
|
11
|
+
export const SOURCE_DEFS = {
|
|
12
|
+
system: { label: '系统', trust: 'high' },
|
|
13
|
+
user: { label: '用户', trust: 'medium' },
|
|
14
|
+
assistant: { label: '助手', trust: 'medium' },
|
|
15
|
+
tool: { label: '工具', trust: 'medium' },
|
|
16
|
+
web: { label: '网页', trust: 'low' },
|
|
17
|
+
file: { label: '文件', trust: 'low' },
|
|
18
|
+
memory: { label: '记忆', trust: 'low' },
|
|
19
|
+
subagent: { label: '子代理', trust: 'medium' },
|
|
20
|
+
plugin: { label: '插件', trust: 'medium' },
|
|
21
|
+
unknown: { label: '未知来源', trust: 'untrusted' },
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const DEFAULT_CONFIG = {
|
|
25
|
+
sensitivity: 'normal', // low | normal | high
|
|
26
|
+
maxGapMs: 5 * 60 * 1000,
|
|
27
|
+
futureSkewMs: 60 * 1000,
|
|
28
|
+
duplicateWindowMs: 10 * 60 * 1000,
|
|
29
|
+
maxEvents: 200,
|
|
30
|
+
maxIssues: 80,
|
|
31
|
+
maxTurns: 200,
|
|
32
|
+
maxIngressPerTurn: 30,
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const SEVERITY_RANK = { info: 1, warn: 2, critical: 3 }
|
|
36
|
+
|
|
37
|
+
const INJECTION = /(ignore\s+(all\s+)?(previous|prior)\s+instructions|忽略(之前|以上|前面|所有)的?(指令|要求)|你现在是|system\s*prompt|开发者模式|developer\s*mode|DAN\b)/i
|
|
38
|
+
const AUTHORITY = /^\s*(system|developer|系统|管理员|admin)\s*[::]/i
|
|
39
|
+
const ROLE_CONFUSION = /(我是|you\s+are)\s*(system|developer|系统|管理员)/i
|
|
40
|
+
const INVISIBLE = /[\u200B-\u200F\u202A-\u202E\u2060-\u206F]/
|
|
41
|
+
|
|
42
|
+
function nowOf(value, fallback) {
|
|
43
|
+
if (typeof value === 'number' && Number.isFinite(value)) return value
|
|
44
|
+
if (value instanceof Date && Number.isFinite(value.getTime())) return value.getTime()
|
|
45
|
+
if (typeof value === 'string') {
|
|
46
|
+
const parsed = Date.parse(value)
|
|
47
|
+
if (Number.isFinite(parsed)) return parsed
|
|
48
|
+
}
|
|
49
|
+
return fallback
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function round(value) {
|
|
53
|
+
return Math.round(Number(value) || 0)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function hashText(text) {
|
|
57
|
+
let hash = 2166136261
|
|
58
|
+
const value = String(text || '')
|
|
59
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
60
|
+
hash ^= value.charCodeAt(i)
|
|
61
|
+
hash = Math.imul(hash, 16777619)
|
|
62
|
+
}
|
|
63
|
+
return (hash >>> 0).toString(16).padStart(8, '0')
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function classifySource(raw) {
|
|
67
|
+
const value = String(raw || '').toLowerCase()
|
|
68
|
+
if (SOURCE_DEFS[value]) return value
|
|
69
|
+
if (value === 'human') return 'user'
|
|
70
|
+
if (value === 'bot' || value === 'model') return 'assistant'
|
|
71
|
+
if (value === 'function' || value === 'toolresult') return 'tool'
|
|
72
|
+
return 'unknown'
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function trustOf(source) {
|
|
76
|
+
return SOURCE_DEFS[classifySource(source)]?.trust || 'untrusted'
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function sourceLabel(source) {
|
|
80
|
+
return SOURCE_DEFS[classifySource(source)]?.label || '未知来源'
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function normalizeConfig(raw = {}) {
|
|
84
|
+
const next = { ...DEFAULT_CONFIG, ...(raw || {}) }
|
|
85
|
+
if (!['low', 'normal', 'high'].includes(next.sensitivity)) next.sensitivity = 'normal'
|
|
86
|
+
next.maxGapMs = Math.max(1000, Math.min(24 * 3600e3, Number(next.maxGapMs) || DEFAULT_CONFIG.maxGapMs))
|
|
87
|
+
next.futureSkewMs = Math.max(0, Math.min(3600e3, Number(next.futureSkewMs) || DEFAULT_CONFIG.futureSkewMs))
|
|
88
|
+
next.duplicateWindowMs = Math.max(1000, Math.min(24 * 3600e3, Number(next.duplicateWindowMs) || DEFAULT_CONFIG.duplicateWindowMs))
|
|
89
|
+
next.maxEvents = Math.max(20, Math.min(1000, Math.floor(Number(next.maxEvents) || DEFAULT_CONFIG.maxEvents)))
|
|
90
|
+
next.maxIssues = Math.max(10, Math.min(300, Math.floor(Number(next.maxIssues) || DEFAULT_CONFIG.maxIssues)))
|
|
91
|
+
next.maxTurns = Math.max(10, Math.min(5000, Math.floor(Number(next.maxTurns) || DEFAULT_CONFIG.maxTurns)))
|
|
92
|
+
next.maxIngressPerTurn = Math.max(1, Math.min(200, Math.floor(Number(next.maxIngressPerTurn) || DEFAULT_CONFIG.maxIngressPerTurn)))
|
|
93
|
+
return next
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function createMonitor(now = Date.now(), sessionId = 'default') {
|
|
97
|
+
const sources = {}
|
|
98
|
+
for (const [key, def] of Object.entries(SOURCE_DEFS)) {
|
|
99
|
+
sources[key] = { ...def, events: 0, lastAt: 0 }
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
v: MONITOR_VERSION,
|
|
103
|
+
sessionId,
|
|
104
|
+
startedAt: now,
|
|
105
|
+
config: { ...DEFAULT_CONFIG },
|
|
106
|
+
events: [],
|
|
107
|
+
issues: [],
|
|
108
|
+
sources,
|
|
109
|
+
toolCalls: {},
|
|
110
|
+
lastAt: 0,
|
|
111
|
+
lastTurn: 0,
|
|
112
|
+
turnHadActivity: false,
|
|
113
|
+
eventsThisTurn: 0,
|
|
114
|
+
lastUserText: '',
|
|
115
|
+
lastUserMessageId: '',
|
|
116
|
+
lastUserTurn: -1,
|
|
117
|
+
resetAt: 0,
|
|
118
|
+
nextEventId: 1,
|
|
119
|
+
nextIssueId: 1,
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function migrateMonitor(raw, now = Date.now()) {
|
|
124
|
+
const base = createMonitor(now)
|
|
125
|
+
if (!raw || typeof raw !== 'object') return base
|
|
126
|
+
const next = {
|
|
127
|
+
...base,
|
|
128
|
+
...raw,
|
|
129
|
+
v: MONITOR_VERSION,
|
|
130
|
+
sessionId: String(raw.sessionId || 'default'),
|
|
131
|
+
config: normalizeConfig(raw.config),
|
|
132
|
+
events: Array.isArray(raw.events) ? raw.events.slice(-200) : [],
|
|
133
|
+
issues: Array.isArray(raw.issues) ? raw.issues.slice(-300) : [],
|
|
134
|
+
sources: { ...base.sources },
|
|
135
|
+
toolCalls: raw.toolCalls && typeof raw.toolCalls === 'object' ? raw.toolCalls : {},
|
|
136
|
+
startedAt: nowOf(raw.startedAt, now),
|
|
137
|
+
lastAt: nowOf(raw.lastAt, 0),
|
|
138
|
+
lastTurn: Math.max(0, Math.floor(Number(raw.lastTurn) || 0)),
|
|
139
|
+
turnHadActivity: Boolean(raw.turnHadActivity),
|
|
140
|
+
eventsThisTurn: Math.max(0, Math.floor(Number(raw.eventsThisTurn) || 0)),
|
|
141
|
+
lastUserText: String(raw.lastUserText || ''),
|
|
142
|
+
lastUserMessageId: String(raw.lastUserMessageId || ''),
|
|
143
|
+
lastUserTurn: Number.isFinite(Number(raw.lastUserTurn)) ? Number(raw.lastUserTurn) : -1,
|
|
144
|
+
resetAt: nowOf(raw.resetAt, 0),
|
|
145
|
+
nextEventId: Math.max(1, Math.floor(Number(raw.nextEventId) || 1)),
|
|
146
|
+
nextIssueId: Math.max(1, Math.floor(Number(raw.nextIssueId) || 1)),
|
|
147
|
+
}
|
|
148
|
+
for (const [key, def] of Object.entries(SOURCE_DEFS)) {
|
|
149
|
+
next.sources[key] = {
|
|
150
|
+
...def,
|
|
151
|
+
...(raw.sources?.[key] || {}),
|
|
152
|
+
events: Math.max(0, Math.floor(Number(raw.sources?.[key]?.events) || 0)),
|
|
153
|
+
lastAt: nowOf(raw.sources?.[key]?.lastAt, 0),
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return next
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function bumpSource(state, source, at) {
|
|
160
|
+
const key = classifySource(source)
|
|
161
|
+
if (!state.sources[key]) state.sources[key] = { ...SOURCE_DEFS.unknown, events: 0, lastAt: 0 }
|
|
162
|
+
state.sources[key].events += 1
|
|
163
|
+
state.sources[key].lastAt = Math.max(state.sources[key].lastAt, at)
|
|
164
|
+
return key
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export function raiseIssue(state, input) {
|
|
168
|
+
const code = String(input.code || 'unknown')
|
|
169
|
+
const source = classifySource(input.source)
|
|
170
|
+
const at = nowOf(input.at, Date.now())
|
|
171
|
+
const severity = ['info', 'warn', 'critical'].includes(input.severity) ? input.severity : 'warn'
|
|
172
|
+
const existing = state.issues.find((item) => item.code === code && item.source === source && !item.ackedAt)
|
|
173
|
+
if (existing) {
|
|
174
|
+
existing.count += 1
|
|
175
|
+
existing.lastAt = at
|
|
176
|
+
existing.detail = String(input.detail || existing.detail || '')
|
|
177
|
+
existing.severity = SEVERITY_RANK[severity] > SEVERITY_RANK[existing.severity] ? severity : existing.severity
|
|
178
|
+
return existing
|
|
179
|
+
}
|
|
180
|
+
const issue = {
|
|
181
|
+
id: `issue_${state.nextIssueId++}`,
|
|
182
|
+
code,
|
|
183
|
+
severity,
|
|
184
|
+
title: String(input.title || code),
|
|
185
|
+
detail: String(input.detail || ''),
|
|
186
|
+
source,
|
|
187
|
+
evidence: String(input.evidence || '').slice(0, 500),
|
|
188
|
+
at,
|
|
189
|
+
lastAt: at,
|
|
190
|
+
count: 1,
|
|
191
|
+
ackedAt: 0,
|
|
192
|
+
}
|
|
193
|
+
state.issues.push(issue)
|
|
194
|
+
if (state.issues.length > state.config.maxIssues) state.issues.splice(0, state.issues.length - state.config.maxIssues)
|
|
195
|
+
return issue
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export function recordEvent(state, input = {}, now = Date.now()) {
|
|
199
|
+
const at = nowOf(input.at, now)
|
|
200
|
+
const source = classifySource(input.source || input.role || 'unknown')
|
|
201
|
+
const type = String(input.type || 'event')
|
|
202
|
+
const summary = String(input.summary || input.text || '').slice(0, 240)
|
|
203
|
+
const hash = hashText(`${type}\0${source}\0${summary}`)
|
|
204
|
+
|
|
205
|
+
if (!input.source && !input.role) {
|
|
206
|
+
raiseIssue(state, {
|
|
207
|
+
code: 'source/unknown', severity: 'warn', source: 'unknown', at,
|
|
208
|
+
title: '来源缺失', detail: '事件没有声明来源;按不可信数据处理。', evidence: type,
|
|
209
|
+
})
|
|
210
|
+
}
|
|
211
|
+
if (state.lastAt > 0 && at < state.lastAt - 1000) {
|
|
212
|
+
raiseIssue(state, {
|
|
213
|
+
code: 'time/out-of-order', severity: 'warn', source, at,
|
|
214
|
+
title: '时间戳乱序', detail: '新事件早于上一条事件的时间戳。', evidence: `${new Date(at).toISOString()} < ${new Date(state.lastAt).toISOString()}`,
|
|
215
|
+
})
|
|
216
|
+
}
|
|
217
|
+
if (at > now + state.config.futureSkewMs) {
|
|
218
|
+
raiseIssue(state, {
|
|
219
|
+
code: 'time/future', severity: 'warn', source, at,
|
|
220
|
+
title: '未来时间戳', detail: '事件时间明显晚于本地时钟。', evidence: new Date(at).toISOString(),
|
|
221
|
+
})
|
|
222
|
+
}
|
|
223
|
+
if (state.lastAt > 0 && at - state.lastAt > state.config.maxGapMs) {
|
|
224
|
+
raiseIssue(state, {
|
|
225
|
+
code: 'time/gap', severity: 'info', source, at,
|
|
226
|
+
title: '事件间隔偏大', detail: '两次事件之间出现较长空档,可能是恢复、压缩或丢事件。', evidence: `${Math.round((at - state.lastAt) / 1000)}s`,
|
|
227
|
+
})
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// 工具调用/回合结束重复出现是正常节奏,不应当成上下文污染。
|
|
231
|
+
const duplicateEligible = ['message', 'session/event', 'context'].includes(type)
|
|
232
|
+
const duplicate = duplicateEligible
|
|
233
|
+
? state.events.find((item) => item.hash === hash && Math.abs(item.at - at) <= state.config.duplicateWindowMs)
|
|
234
|
+
: null
|
|
235
|
+
if (duplicate) {
|
|
236
|
+
raiseIssue(state, {
|
|
237
|
+
code: 'flow/duplicate', severity: 'warn', source, at,
|
|
238
|
+
title: '重复事件', detail: '相同来源、类型和摘要的事件在窗口内重复出现。', evidence: duplicate.id,
|
|
239
|
+
})
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const event = {
|
|
243
|
+
id: `evt_${state.nextEventId++}`,
|
|
244
|
+
at,
|
|
245
|
+
type,
|
|
246
|
+
source,
|
|
247
|
+
hash,
|
|
248
|
+
summary,
|
|
249
|
+
}
|
|
250
|
+
state.events.push(event)
|
|
251
|
+
if (state.events.length > state.config.maxEvents) state.events.splice(0, state.events.length - state.config.maxEvents)
|
|
252
|
+
state.lastAt = Math.max(state.lastAt, at)
|
|
253
|
+
bumpSource(state, source, at)
|
|
254
|
+
if (type !== 'turn/end') {
|
|
255
|
+
state.turnHadActivity = true
|
|
256
|
+
state.eventsThisTurn += 1
|
|
257
|
+
if (state.eventsThisTurn > state.config.maxIngressPerTurn) {
|
|
258
|
+
raiseIssue(state, {
|
|
259
|
+
code: 'budget/ingress', severity: 'warn', source, at,
|
|
260
|
+
title: '单轮入口过多', detail: '本回合进入上下文的事件超过上限,可能发生接口灌入或回环。',
|
|
261
|
+
evidence: `${state.eventsThisTurn}/${state.config.maxIngressPerTurn}`,
|
|
262
|
+
})
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
return event
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function raiseTextIssue(state, input) {
|
|
269
|
+
return raiseIssue(state, input)
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
export function inspectText(state, text, source = 'user', at = Date.now()) {
|
|
273
|
+
const value = String(text || '')
|
|
274
|
+
if (!value.trim()) return null
|
|
275
|
+
const key = classifySource(source)
|
|
276
|
+
recordEvent(state, { type: 'message', source: key, at, summary: value.slice(0, 180) }, at)
|
|
277
|
+
|
|
278
|
+
if (INJECTION.test(value)) {
|
|
279
|
+
raiseTextIssue(state, {
|
|
280
|
+
code: 'content/injection', severity: 'critical', source: key, at,
|
|
281
|
+
title: '疑似提示注入', detail: '文本包含“忽略之前指令/系统提示/角色覆盖”等特征。',
|
|
282
|
+
evidence: value.match(INJECTION)?.[0] || value.slice(0, 80),
|
|
283
|
+
})
|
|
284
|
+
}
|
|
285
|
+
if (AUTHORITY.test(value)) {
|
|
286
|
+
raiseTextIssue(state, {
|
|
287
|
+
code: 'content/authority-spoof', severity: 'warn', source: key, at,
|
|
288
|
+
title: '疑似权威伪装', detail: '普通消息以系统/管理员身份开头。',
|
|
289
|
+
evidence: value.slice(0, 80),
|
|
290
|
+
})
|
|
291
|
+
}
|
|
292
|
+
if (ROLE_CONFUSION.test(value)) {
|
|
293
|
+
raiseTextIssue(state, {
|
|
294
|
+
code: 'content/role-confusion', severity: 'warn', source: key, at,
|
|
295
|
+
title: '角色边界异常', detail: '文本声称自己是系统/开发者,可能试图覆盖角色。',
|
|
296
|
+
evidence: value.match(ROLE_CONFUSION)?.[0] || value.slice(0, 80),
|
|
297
|
+
})
|
|
298
|
+
}
|
|
299
|
+
if (INVISIBLE.test(value)) {
|
|
300
|
+
raiseTextIssue(state, {
|
|
301
|
+
code: 'content/invisible', severity: 'warn', source: key, at,
|
|
302
|
+
title: '不可见字符', detail: '文本包含零宽或方向控制字符,可能用于隐藏内容。',
|
|
303
|
+
evidence: '包含 U+200B–U+206F 区段字符',
|
|
304
|
+
})
|
|
305
|
+
}
|
|
306
|
+
if (value.length > 20000) {
|
|
307
|
+
raiseTextIssue(state, {
|
|
308
|
+
code: 'context/oversize', severity: 'info', source: key, at,
|
|
309
|
+
title: '单条文本过长', detail: '单条消息超过 20k 字符,可能挤占上下文。',
|
|
310
|
+
evidence: `${value.length} chars`,
|
|
311
|
+
})
|
|
312
|
+
}
|
|
313
|
+
if (key === 'user' && state.lastUserText && value === state.lastUserText && value.length > 20) {
|
|
314
|
+
raiseTextIssue(state, {
|
|
315
|
+
code: 'context/repeat', severity: 'warn', source: key, at,
|
|
316
|
+
title: '用户消息重复', detail: '连续两条用户消息完全相同,可能是回环或重复注入。',
|
|
317
|
+
evidence: value.slice(0, 100),
|
|
318
|
+
})
|
|
319
|
+
}
|
|
320
|
+
if (key === 'user') state.lastUserText = value
|
|
321
|
+
return state
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function textOf(message) {
|
|
325
|
+
const content = message?.content
|
|
326
|
+
if (typeof content === 'string') return content
|
|
327
|
+
if (Array.isArray(content)) {
|
|
328
|
+
return content.map((part) => (typeof part === 'string' ? part : part?.text || part?.content || '')).join(' ')
|
|
329
|
+
}
|
|
330
|
+
return String(message?.text || '')
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
export function inspectMessages(state, messages, now = Date.now()) {
|
|
334
|
+
const users = (Array.isArray(messages) ? messages : []).filter((message) => !message?.role || message.role === 'user')
|
|
335
|
+
const last = users[users.length - 1]
|
|
336
|
+
if (!last) return null
|
|
337
|
+
const text = textOf(last)
|
|
338
|
+
const messageId = String(last.id || last.messageId || last.meta?.id || hashText(text))
|
|
339
|
+
// 同一回合里,pre-step 会因工具循环多次触发;同一条用户消息只记一次。
|
|
340
|
+
if (state.lastUserTurn === state.turn && state.lastUserMessageId === messageId) return null
|
|
341
|
+
state.lastUserTurn = state.turn
|
|
342
|
+
state.lastUserMessageId = messageId
|
|
343
|
+
return inspectText(state, text, 'user', now)
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
export function recordToolCall(state, exec, now = Date.now()) {
|
|
347
|
+
const name = exec?.tool?.name || exec?.name || exec?.toolName || 'tool'
|
|
348
|
+
const id = String(exec?.id || exec?.callId || exec?.call_id || name)
|
|
349
|
+
state.toolCalls[id] = { name, at: now }
|
|
350
|
+
const keys = Object.keys(state.toolCalls)
|
|
351
|
+
if (keys.length > 100) {
|
|
352
|
+
for (const key of keys.slice(0, keys.length - 100)) delete state.toolCalls[key]
|
|
353
|
+
}
|
|
354
|
+
recordEvent(state, { type: 'tool.call', source: 'tool', at: now, summary: name }, now)
|
|
355
|
+
return id
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
export function inspectToolResult(state, exec, result, now = Date.now()) {
|
|
359
|
+
const name = exec?.tool?.name || exec?.name || exec?.toolName || 'tool'
|
|
360
|
+
const id = String(exec?.id || exec?.callId || exec?.call_id || name)
|
|
361
|
+
const known = state.toolCalls[id]
|
|
362
|
+
if (!known && !(state.resetAt > 0 && now - state.resetAt < 15000)) {
|
|
363
|
+
raiseIssue(state, {
|
|
364
|
+
code: 'flow/orphan-result', severity: 'info', source: 'tool', at: now,
|
|
365
|
+
title: '工具结果没有对应调用', detail: '收到工具结果,但未观察到同一 id 的调用;可能是重放或跨会话混流。',
|
|
366
|
+
evidence: String(id),
|
|
367
|
+
})
|
|
368
|
+
}
|
|
369
|
+
const declared = result?.source || result?.origin
|
|
370
|
+
if (declared && classifySource(declared) !== 'tool') {
|
|
371
|
+
raiseIssue(state, {
|
|
372
|
+
code: 'source/conflict', severity: 'warn', source: 'tool', at: now,
|
|
373
|
+
title: '工具结果来源冲突', detail: '工具结果自称来自其他来源,可能发生通道混流。',
|
|
374
|
+
evidence: `${declared} -> tool`,
|
|
375
|
+
})
|
|
376
|
+
}
|
|
377
|
+
recordEvent(state, { type: 'tool.result', source: 'tool', at: now, summary: name }, now)
|
|
378
|
+
return state
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
export function recordTurn(state, now = Date.now()) {
|
|
382
|
+
if (state.lastTurn > 0 && !state.turnHadActivity) {
|
|
383
|
+
raiseIssue(state, {
|
|
384
|
+
code: 'flow/blank-slice', severity: 'warn', source: 'system', at: now,
|
|
385
|
+
title: '空白时间片', detail: '回合推进了,但本回合没有记录到消息或工具事件;可能是日志断档、恢复或压缩后丢事件。',
|
|
386
|
+
evidence: `turn ${state.lastTurn} -> ${state.lastTurn + 1}`,
|
|
387
|
+
})
|
|
388
|
+
}
|
|
389
|
+
state.lastTurn += 1
|
|
390
|
+
state.turnHadActivity = false
|
|
391
|
+
state.eventsThisTurn = 0
|
|
392
|
+
const warnAt = Math.ceil(state.config.maxTurns * 0.8)
|
|
393
|
+
if (state.lastTurn >= state.config.maxTurns) {
|
|
394
|
+
raiseIssue(state, {
|
|
395
|
+
code: 'budget/turns', severity: 'critical', source: 'system', at: now,
|
|
396
|
+
title: '会话轮数达到上限', detail: '会话轮数已超过预算,继续运行会显著增加上下文过载与污染风险。建议结束当前会话并新开一个。',
|
|
397
|
+
evidence: `${state.lastTurn}/${state.config.maxTurns}`,
|
|
398
|
+
})
|
|
399
|
+
} else if (state.lastTurn >= warnAt) {
|
|
400
|
+
raiseIssue(state, {
|
|
401
|
+
code: 'budget/turns', severity: 'warn', source: 'system', at: now,
|
|
402
|
+
title: '会话轮数接近上限', detail: '会话轮数已接近预算,建议准备收束或新开会话。',
|
|
403
|
+
evidence: `${state.lastTurn}/${state.config.maxTurns}`,
|
|
404
|
+
})
|
|
405
|
+
}
|
|
406
|
+
recordEvent(state, { type: 'turn/end', source: 'system', at: now, summary: `turn ${state.lastTurn}` }, now)
|
|
407
|
+
return state.lastTurn
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
export function recordSessionEvent(state, event, now = Date.now()) {
|
|
411
|
+
if (!event || typeof event !== 'object') return state
|
|
412
|
+
const source = event.source || event.role || event.actor || 'unknown'
|
|
413
|
+
const type = event.type || event.kind || 'session/event'
|
|
414
|
+
return recordEvent(state, {
|
|
415
|
+
type: String(type),
|
|
416
|
+
source,
|
|
417
|
+
at: event.at || event.time || event.timestamp || now,
|
|
418
|
+
summary: event.summary || event.text || '',
|
|
419
|
+
}, now)
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
export function activeIssues(state) {
|
|
423
|
+
return state.issues.filter((issue) => !issue.ackedAt)
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
export function healthOf(state) {
|
|
427
|
+
const active = activeIssues(state)
|
|
428
|
+
const status = active.some((issue) => issue.severity === 'critical')
|
|
429
|
+
? 'critical'
|
|
430
|
+
: active.some((issue) => issue.severity === 'warn')
|
|
431
|
+
? 'warn'
|
|
432
|
+
: 'ok'
|
|
433
|
+
return {
|
|
434
|
+
status,
|
|
435
|
+
sessionId: state.sessionId || 'default',
|
|
436
|
+
startedAt: state.startedAt,
|
|
437
|
+
lastAt: state.lastAt,
|
|
438
|
+
lastTurn: state.lastTurn,
|
|
439
|
+
turnHadActivity: Boolean(state.turnHadActivity),
|
|
440
|
+
eventsThisTurn: state.eventsThisTurn,
|
|
441
|
+
config: state.config,
|
|
442
|
+
issues: active.slice(-80),
|
|
443
|
+
sources: Object.entries(state.sources).map(([key, value]) => ({
|
|
444
|
+
key,
|
|
445
|
+
label: value.label,
|
|
446
|
+
trust: value.trust,
|
|
447
|
+
events: value.events,
|
|
448
|
+
lastAt: value.lastAt,
|
|
449
|
+
})),
|
|
450
|
+
events: state.events.slice(-80),
|
|
451
|
+
counts: {
|
|
452
|
+
events: state.events.length,
|
|
453
|
+
issues: active.length,
|
|
454
|
+
critical: active.filter((issue) => issue.severity === 'critical').length,
|
|
455
|
+
warn: active.filter((issue) => issue.severity === 'warn').length,
|
|
456
|
+
info: active.filter((issue) => issue.severity === 'info').length,
|
|
457
|
+
},
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
export function renderWarning(state) {
|
|
462
|
+
const issues = activeIssues(state).filter((issue) => issue.severity !== 'info')
|
|
463
|
+
if (issues.length === 0) return ''
|
|
464
|
+
const highest = issues.some((issue) => issue.severity === 'critical') ? 'critical' : 'warn'
|
|
465
|
+
const lines = issues.slice(-3).map((issue) => `- [${issue.severity}] ${issue.title}:${issue.detail}`)
|
|
466
|
+
return [
|
|
467
|
+
`【安全监控】检测到 ${issues.length} 项上下文异常(最高:${highest})。`,
|
|
468
|
+
...lines,
|
|
469
|
+
'只作为警示,不要自行删除上下文;向用户说明,并等待确认。',
|
|
470
|
+
].join('\n')
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
export function ackIssue(state, id) {
|
|
474
|
+
const issue = state.issues.find((item) => item.id === id)
|
|
475
|
+
if (!issue) return false
|
|
476
|
+
issue.ackedAt = Date.now()
|
|
477
|
+
return true
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
export function ackAll(state) {
|
|
481
|
+
const now = Date.now()
|
|
482
|
+
for (const issue of state.issues) {
|
|
483
|
+
if (!issue.ackedAt) issue.ackedAt = now
|
|
484
|
+
}
|
|
485
|
+
return state
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
export function updateConfig(state, patch = {}) {
|
|
489
|
+
state.config = normalizeConfig({ ...state.config, ...(patch || {}) })
|
|
490
|
+
return state.config
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
export function resetMonitor(now = Date.now(), sessionId = 'default') {
|
|
494
|
+
const next = createMonitor(now, sessionId)
|
|
495
|
+
next.resetAt = now
|
|
496
|
+
return next
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
export function formatAt(value) {
|
|
500
|
+
const at = nowOf(value, 0)
|
|
501
|
+
if (!at) return '—'
|
|
502
|
+
return new Date(at).toISOString().replace('T', ' ').slice(0, 19)
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
export { round }
|
package/package.json
CHANGED
|
@@ -1,6 +1,65 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-safetymonitor-plug",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"private": false,
|
|
6
|
+
"description": "DSH 上下文完整性监控插件:按会话检查时间戳、来源、重复、断链、空白时间片、会话预算与提示注入特征;只读告警,不删除上下文、不拦截工具。",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./index.js",
|
|
9
|
+
"./client": "./client.js",
|
|
10
|
+
"./monitor": "./monitor.mjs",
|
|
11
|
+
"./locale/*.json": "./locale/*.json",
|
|
12
|
+
"./icon": "./icon.svg",
|
|
13
|
+
"./package.json": "./package.json"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"index.js",
|
|
17
|
+
"monitor.mjs",
|
|
18
|
+
"client.js",
|
|
19
|
+
"cordis.patch.yml",
|
|
20
|
+
"locale/*.json",
|
|
21
|
+
"docs",
|
|
22
|
+
"icon.svg",
|
|
23
|
+
"README.md",
|
|
24
|
+
"LICENSE"
|
|
25
|
+
],
|
|
26
|
+
"scripts": {
|
|
27
|
+
"test": "node --test"
|
|
28
|
+
},
|
|
29
|
+
"dsh": {
|
|
30
|
+
"bundle": {
|
|
31
|
+
"patch": "./cordis.patch.yml"
|
|
32
|
+
},
|
|
33
|
+
"client": {
|
|
34
|
+
"platform": "web",
|
|
35
|
+
"immediately": true,
|
|
36
|
+
"inject": [
|
|
37
|
+
"@deepseek-ai/dsh-client-ui-conversation"
|
|
38
|
+
]
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
"engines": {
|
|
42
|
+
"node": ">=20"
|
|
43
|
+
},
|
|
44
|
+
"publishConfig": {
|
|
45
|
+
"access": "public"
|
|
46
|
+
},
|
|
47
|
+
"repository": {
|
|
48
|
+
"type": "git",
|
|
49
|
+
"url": "git+https://github.com/user-yechen/dsh-safetymonitor-plug.git"
|
|
50
|
+
},
|
|
51
|
+
"homepage": "https://github.com/user-yechen/dsh-safetymonitor-plug",
|
|
52
|
+
"bugs": {
|
|
53
|
+
"url": "https://github.com/user-yechen/dsh-safetymonitor-plug/issues"
|
|
54
|
+
},
|
|
55
|
+
"keywords": [
|
|
56
|
+
"dsh",
|
|
57
|
+
"dsh-plugin",
|
|
58
|
+
"deepseek-harness",
|
|
59
|
+
"safety",
|
|
60
|
+
"context-integrity",
|
|
61
|
+
"monitoring"
|
|
62
|
+
],
|
|
63
|
+
"author": "user-yechen",
|
|
64
|
+
"license": "MIT"
|
|
65
|
+
}
|