sentinel-agentos 0.3.4 → 0.3.6

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/README.md CHANGED
@@ -1,1769 +1,1797 @@
1
- # Sentinel AgentOS — AI Agent 操作系统 · AI Agent Operating System
2
-
3
- > **确定性 Guard 层 + 分层记忆 + 自动评估,让任何 Agent 变得可靠、可审计、可改进。**
4
- > *Deterministic Guard Layer + Layered Memory + Automated Evaluation — making any Agent reliable, auditable, and self-improving.*
5
-
6
- [![TypeScript](https://img.shields.io/badge/TypeScript-5.8-blue)](https://www.typescriptlang.org/)
7
- [![Tests](https://img.shields.io/badge/tests-99%2F99-brightgreen)](https://github.com/jishuanjimingtian/sentinel-agentos/actions)
8
- [![License](https://img.shields.io/badge/license-MIT-green)](./LICENSE)
9
-
10
- ---
11
-
12
- ## 🤔 为什么需要 Sentinel AgentOS · Why Sentinel AgentOS
13
-
14
- AI Agent 面临五大核心问题,现有框架都没能真正解决。
15
- *AI Agents face five critical problems that no existing framework truly solves.*
16
-
17
- | 痛点 · Pain | 现状 · Status Quo | Sentinel AgentOS 方案 · Solution |
18
- |------|------|-------------|
19
- | 🔴 **幻觉导致错误操作** · *Hallucinated operations* | Prompt 里说"不要删文件"——这是愿望,不是约束 · *"Please don't delete files" — that's a wish, not a constraint* | Guard 层确定性校验,不依赖 LLM 判断 · *Deterministic Guard checks, zero LLM dependency* |
20
- | 🔴 **越权/危险操作** · *Over-privileged ops* | 无分级控制,要么全禁要么全放 · *All-or-nothing access control* | Risk Gate 四维数学公式,0-100 自动分级 · *4-dimensional risk formula with auto-thresholding* |
21
- | 🔴 **记不住、记不对** · *Poor memory* | 把对话扔进向量库——只有检索没有理解 · *Dump conversation into vector DB — retrieval, not understanding* | 三层记忆,像人脑一样评级、压缩、遗忘 · *3-layer memory: rate, compress, forget like a brain* |
22
- | 🔴 **出事查不到原因** · *No audit trail* | Agent 做了什么、为什么做——全不可追溯 · *What the agent did and why — completely untraceable* | 每次操作前后 diff,JSONL 不可篡改审计 · *Pre/post diff per operation, immutable JSONL audit* |
23
- | 🔴 **不知道 Agent 好不好** · *No quality measurement* | 最多有个 success rate 计数器 · *At best, a success-rate counter* | 三阶段评估 + 隐性反馈 + 质量画像 · *3-phase evaluation + implicit feedback + quality profile* |
24
-
25
- ---
26
-
27
- ## 🏗️ 架构设计 · Architecture
28
-
29
- ```
30
- ┌─────────────────────────────────────────────────────────────────┐
31
- │ Sentinel AgentOS 架构 │
32
- │ │
33
- │ 任意 Agent 框架 · Any Agent Framework │
34
- │ (OpenClaw / LangChain / CrewAI / 自研 · Custom) │
35
- │ │ │
36
- │ ▼ │
37
- │ ┌───────────────────────────────────────────────────────────┐ │
38
- │ │ Sentinel AgentOS 内核 · Kernel │ │
39
- │ │ │ │
40
- │ │ ┌─────────┐ ┌──────────┐ ┌────────────┐ │ │
41
- │ │ │ Guard │ │ Memory │ │ Evaluator │ │ │
42
- │ │ │ 守卫层 │ │ 记忆层 │ │ 评估层 │ │ │
43
- │ │ ├─────────┤ ├──────────┤ ├────────────┤ │ │
44
- │ │ │ Schema │ │ Working │ │ Pre-exec │ │ │
45
- │ │ │ Gate │ │ 工作记忆 │ │ 执行前评估 │ │ │
46
- │ │ │ ↓ │ │ ↓ │ │ ↓ │ │ │
47
- │ │ │ Risk │ │ Episodic │ │ Runtime │ │ │
48
- │ │ │ Gate │ │ 情景记忆 │ │ 执行中评估 │ │ │
49
- │ │ │ ↓ │ │ ↓ │ │ ↓ │ │ │
50
- │ │ │Snapshot │ │ Semantic │ │ Post-exec │ │ │
51
- │ │ │ Gate │ │ 语义记忆 │ │ 执行后评估 │ │ │
52
- │ │ │ ↓ │ └──────────┘ │ ↓ │ │ │
53
- │ │ │ Verify │ │ Feedback │ │ │
54
- │ │ │ Gate │ │ 反馈引擎 │ │ │
55
- │ │ │ ↓ │ │ ↓ │ │ │
56
- │ │ │ Audit │ │ Profiler │ │ │
57
- │ │ │ Log │ │ 质量画像 │ │ │
58
- │ │ └─────────┘ └────────────┘ │ │
59
- │ │ │ │
60
- │ │ ┌─────────────────────────────────────────────────────┐ │ │
61
- │ │ │ Sandbox 沙箱 (direct/sandbox/dry-run) │ │ │
62
- │ │ └─────────────────────────────────────────────────────┘ │ │
63
- │ └───────────────────────────────────────────────────────────┘ │
64
- │ │ │
65
- │ ┌───────────────┴───────────────┐ │
66
- │ ▼ ▼ │
67
- │ 安全执行 · Safe Execution 可靠记忆 · Reliable Memory │
68
- │ 全程审计 · Full Audit 持续改进 · Continuous Improve│
69
- └─────────────────────────────────────────────────────────────────┘
70
- ```
71
-
72
- ### 设计哲学 · Design Philosophy
73
-
74
- | 原则 · Principle | 含义 · Meaning | 反例 · Counter-example |
75
- |------|------|------|
76
- | **确定性优先** · *Determinism first* | 能不用 LLM 就不用,用确定性代码 · *Use deterministic code whenever possible* | 用 LLM 做安全判断 · *Using LLM for security* |
77
- | **可审计优先** · *Auditability first* | 所有操作可追溯、可回滚、可解释 · *Every operation traceable, rollbackable, explainable* | Agent 操作后无日志 · *No log after agent operations* |
78
- | **渐进增强** · *Progressive enhancement* | 框架无关,可增量接入,不要求替换现有架构 · *Framework-agnostic, incremental adoption* | LangChain 的强绑定 · *Hard vendor lock-in* |
79
-
80
- ### 不是 Agent,是 Agent 的操作系统 · *Not an Agent — an OS for Agents*
81
-
82
- | 类比 · Analogy | 对应 · Implementation |
83
- |------|------|
84
- | 应用程序 · Applications | 任意 Agent 框架 · Any Agent Framework |
85
- | 操作系统 · Operating System | Sentinel AgentOS |
86
- | 内核 · Kernel | Schema Gate + Risk Gate(确定性代码,零 LLM) |
87
- | 文件系统 · File System | 分层 Memory Store |
88
- | 日志系统 · Logging | Audit Log(不可篡改,支持回滚 · *immutable, supports rollback*) |
89
- | 性能监控 · Performance Monitor | Evaluator 三阶段评估 · *3-phase evaluation* |
90
-
91
- ---
92
-
93
- ## ✨ 功能介绍 · Features
94
-
95
- ### 🛡️ Guard 守卫层(6 个组件,零 LLM 依赖 · *6 components, zero LLM*)
96
-
97
- #### Schema Gate — 参数格式校验 · Parameter Validation
98
-
99
- | 校验项 · Check | 说明 · Description | 示例 · Example |
100
- |--------|------|------|
101
- | 必填 · required | 字段必须存在 · *Field must exist* | `delete_file` 必须提供 `path` |
102
- | 类型 · types | string/number/boolean/object/array | `path` 必须是 string |
103
- | 允许值 · allowedValues | 枚举约束 · *Enum constraint* | `mode` 只能是 `read`/`write`/`append` |
104
- | 数值范围 · min/max | 数字范围 · *Numeric range* | `max_tokens` 1-100000 |
105
- | 长度范围 · — | 字符串/数组长度 · *String/array length* | `query` 至少 3 字符 |
106
- | 正则 · patterns | 格式校验 · *Pattern match* | `email` 符合邮箱格式 |
107
- | 路径约束 · pathScope | 限制在 workspace 内 · *Workspace boundary* | 禁止写系统目录 · *No system dir writes* |
108
- | 路径黑白名单 · pathAllow/Deny | 允许/禁止的文件模式 · *File pattern allow/block* | 禁止 `.env`, `*.key`, `*.pem` |
109
- | 参数依赖 · dependsOn | 条件必填 · *Conditional required* | `auto_merge=true` → `base_branch` 必填 |
110
- | 参数互斥 · mutuallyExclusive | 互斥参数 · *Mutually exclusive* | `content` 和 `file_path` 不同时存在 |
111
- | 参数大小 · maxSize | 内容字节上限 · *Max content bytes* | `content` ≤ 1MB |
112
- | 敏感标记 · secrets | 日志中脱敏 · *Redact in logs* | |
113
-
114
- #### Risk Gate — 风险分级 · Risk Scoring
115
-
116
- 四维数学公式,零 LLM · *4-dimensional formula:*
117
-
118
- ```
119
- RiskScore = Impact × (1 - Reversibility) × Sensitivity × (1 + ErrorRate)
120
- ```
121
-
122
- | 分数区间 · Score | 动作 · Action |
123
- |----------|------|
124
- | ≤ 0.5 | 🟢 自动放行 · *Auto-approve* |
125
- | ≤ 1.0 | 🔵 执行后通知 · *Notify after execution* |
126
- | ≤ 3.0 | 🟡 暂停等待确认 · *Pause for confirmation* |
127
- | > 8.0 | 🔴 直接拒绝 · *Deny* |
128
-
129
- #### Snapshot Gate — 执行前快照 · Pre-exec Snapshot
130
-
131
- 只记录文件 SHA-256 hash + git 状态,不做全量备份,极快。
132
- *Records only SHA-256 hashes + git state, no full backup — extremely fast.*
133
-
134
- #### Verify Gate — 执行后校验 · Post-exec Verification
135
-
136
- **8 项确定性校验** · *8 deterministic checks:*
137
-
138
- | 校验项 · Check | 说明 · Description |
139
- |--------|------|
140
- | 文件存在 · File existence | `fs.existsSync()` 验证声称创建的文件 |
141
- | 文件变更 · File changed | 对比 Snapshot hash,确认真的改了 |
142
- | Lint | ESLint 验证代码文件 |
143
- | TypeCheck | `tsc --noEmit` TypeScript 验证 |
144
- | 格式合法 · Valid format | JSON.parse 验证声称的 JSON 结果 |
145
- | 返回值非空 · Non-empty result | 不应为空但为空 → WARN |
146
- | npm 发布 · npm publish | `npm view` 真实验证 |
147
- | git push | `git ls-remote` HEAD 对比 |
148
-
149
- #### Audit Log — 不可篡改审计 · Immutable Audit
150
-
151
- 追加写入 JSONL 文件,每次操作前后完整记录(Schema + Risk + Snapshot + Verify + Diff)。支持按 session/tool/status 查询。
152
- *Append-only JSONL with full pre/post state per operation. Query by session/tool/status.*
153
-
154
- #### Rollback 回滚
155
-
156
- 基于 Snapshot + Git 自动回滚。Verify Gate FAIL + 高风险 → 自动触发。
157
- *Git-based auto-rollback. Triggered on Verify FAIL + high risk.*
158
-
159
- #### Sandbox Executor 沙箱执行器
160
-
161
- 三种模式 · *Three modes:* **direct** · **sandbox** · **dry-run**
162
-
163
- - 网络策略 · *Network policy:* none / localhost / whitelist
164
- - 文件系统策略 · *Filesystem policy:* writablePaths / readonlyPaths
165
- - 内置危险命令检测(`rm -rf /`、`sudo`、fork bomb、`curl\|bash` 等)· *Built-in dangerous command detection*
166
-
167
- ---
168
-
169
- ### 🧠 Memory 记忆层(3 层,人脑模型 · *3-layer brain model*)
170
-
171
- ```
172
- Working Memory → Episodic Memory → Semantic Memory
173
- 工作记忆 → 情景记忆 → 语义记忆
174
- ──────────────────────────────────────────────────────
175
- 当前会话 → 跨会话事件线 → 永久知识
176
- Current session → Cross-session → Permanent knowledge
177
- 1 session 存活 → 数周-数月 → 永久
178
- < 50KB → < 500KB → < 100KB
179
- ```
180
-
181
- | · Layer | 用途 · Purpose | 关键能力 · Key Ability |
182
- |----|------|---------|
183
- | **Working** | 当前会话实时上下文 · *Live session context* | 消息/任务/工具缓存/文件/token 预算 · *Messages, tasks, tool cache, open files, token budget* |
184
- | **Episodic** | 跨会话事件时间线 · *Cross-session timeline* | 9 种事件类型、自动重要性评分、渐进压缩(fullsummary→one-liner→forgotten) |
185
- | **Semantic** | 提炼后的永久知识 · *Distilled permanent knowledge* | 用户偏好/事实、项目上下文、学习规则(含置信度)、术语表 |
186
-
187
- #### Session 启动上下文注入 · Startup Context Injection
188
-
189
- session 自动从 Semantic + Episodic 注入最相关上下文:
190
- *Auto-injects relevant context at every new session:*
191
-
192
- ```
193
- [Sentinel AgentOS Memory Context]
194
- 你正在帮助用户"老板"处理项目"coderev"。
195
- You are helping user "Boss" with project "coderev".
196
- 上次会话讨论了 Guard 层设计。
197
- Last session discussed Guard layer design.
198
- 关键提醒 · Key reminders:
199
- - 老板偏好直接、不说废话 · Boss prefers direct, no fluff
200
- - 发布 npm 前必须更新 CHANGELOG.md · Update CHANGELOG before npm publish
201
- ```
202
-
203
- ---
204
-
205
- ### 📊 Evaluator 评估层(三阶段 + 隐性反馈 · *3-phase + Implicit Feedback*)
206
-
207
- #### 三阶段评估 · Three-Phase Evaluation
208
-
209
- ```
210
- Pre-exec 评估 → Runtime 评估 → Post-exec 评估
211
- 执行前评估 执行中评估 执行后评估
212
- ↓ ↓ ↓
213
- 参数质量 重试次数 验证结果
214
- 风险分数 自适应评分 用户接受度
215
- 上下文利用 工具选择准确性 结果利用度
216
- ```
217
-
218
- #### 隐性反馈捕获 · Implicit Feedback(核心差异点 · *Key differentiator*)
219
-
220
- 不靠"👍👎",靠行为推断满意度。*No thumbs up/down — infer satisfaction from behavior.*
221
-
222
- | 用户行为 · User Behavior | 隐性信号 · Signal | 强度 · Strength |
223
- |----------|---------|------|
224
- | 用户删除了 Agent 创建的代码 · *User deleted agent's code* | `user_deleted_code` | -0.8 |
225
- | 用户打断了 Agent · *User interrupted agent* | `user_interrupted` | -0.6 |
226
- | 用户修改了 Agent 输出 · *User modified agent output* | `user_modified_output` | -0.5 |
227
- | 用户重复了相同指令 · *User repeated same command* | `user_repeated_instruction` | -0.3 |
228
- | 用户立即继续对话 · *User immediately continued* | `user_immediate_continue` | +0.3 |
229
- | 用户说"做得好" · *User said "good job"* | `user_explicit_approval` | +0.6 |
230
- | 用户使用了 Agent 的结果 · *User used agent's result* | `user_used_result` | +0.7 |
231
- | 用户分享了 Agent 输出 · *User shared agent output* | `user_shared_output` | +0.8 |
232
-
233
- #### Agent 质量画像 · Quality Profile
234
-
235
- ```
236
- === Sentinel AgentOS Status Report ===
237
-
238
- Quality Score: 85/100 📈
239
- Total Operations: 156 (12 in last 24h)
240
-
241
- --- Breakdown ---
242
- Pre-Exec: 92/100
243
- Runtime: 88/100
244
- Post-Exec: 85/100
245
- Satisfaction: 82/100
246
-
247
- --- Audit ---
248
- Total: 156 | Failures: 2 | High-Risk: 3
249
-
250
- --- ⚠️ Warnings ---
251
- - 2 verify failures in last 24h — review session #3
252
- 24小时内2次校验失败——检查session #3
253
-
254
- --- ✅ Strengths 强项 ---
255
- - Excellent execution reliability · 优秀的执行可靠性
256
- - Strong positive user feedback · 强烈正向用户反馈
257
- ```
258
-
259
- ---
260
-
261
- ## 📦 安装 · Installation
262
-
263
- ```bash
264
- npm install sentinel-agentos
265
- ```
266
-
267
- 即可使用所有功能。
268
-
269
- 如果从源码开发:
270
-
271
- ```bash
272
- git clone git@github.com:jishuanjimingtian/Sentinel AgentOS.git
273
- cd Sentinel AgentOS
274
- npm install
275
- npm test # 99 tests, all passing · 99个测试全部通过
276
- npm run build # 编译到 dist/
277
- ```
278
-
279
- ---
280
-
281
- ## 🚀 使用说明 · Usage
282
-
283
- ### 三种接入方式 · Three Integration Modes
284
-
285
- Sentinel AgentOS 支持三种接入方式,从轻到重按需选择。
286
-
287
- | 方式 | 适用场景 | 代码量 | 说明 |
288
- |------|---------|--------|------|
289
- | **CLI** | 快速测试 / CI/CD | 1 行命令 | 直接命令行检验工具调用 |
290
- | **SDK** | 嵌入 Agent 框架 | 5 行代码 | `import { AgentOS }` 在进程内调用 |
291
- | **HTTP API** | 跨语言 / 远程服务 | HTTP 请求 | 独立 HTTP 服务,任何语言都能调 |
292
-
293
- ---
294
-
295
- ### 方式一:CLI(命令行)
296
-
297
- ```bash
298
- # 安装
299
- npm install -g sentinel-agentos
300
-
301
- # 校验参数
302
- sentinel-agentos validate exec command="rm -rf /"
303
- sentinel-agentos validate write_file path=src/main.ts content="console.log(1)"
304
-
305
- # 风险评分
306
- sentinel-agentos risk exec command="sudo reboot"
307
- sentinel-agentos risk exec command="npm test"
308
-
309
- # 查看审计日志
310
- sentinel-agentos audit --limit 10
311
-
312
- # 查看状态报告
313
- sentinel-agentos status
314
-
315
- # 启动 HTTP 服务
316
- sentinel-agentos server --port 3300 --token ***
317
-
318
- # 查看帮助
319
- sentinel-agentos help
320
- ```
321
-
322
- **支持的命令**:`validate` / `risk` / `audit` / `stats` / `profile` / `status` / `server` / `memory` / `help`
323
-
324
- ---
325
-
326
- ### 方式二:SDK(代码嵌入)
327
-
328
- #### 2.1 基础用法 · Basic
329
-
330
- ```typescript
331
- import { AgentOS } from 'sentinel-agentos';
332
-
333
- const aos = new AgentOS({
334
- workspaceRoot: process.cwd(),
335
- maxWorkingTokens: 50000,
336
- maxEpisodicSizeKb: 500,
337
- });
338
-
339
- // 设置记忆 · Configure memory
340
- aos.memory.semantic.setPreference('language', 'zh-CN');
341
- aos.memory.semantic.addFact('用户在北京,偏好简洁沟通');
342
- aos.memory.semantic.learnRule('提交前运行 npm test', 'session_1');
343
-
344
- // 设置 Schema 规则 · Register schema rules
345
- aos.guard.schema.registerRule({
346
- tool: 'write_file',
347
- required: ['path', 'content'],
348
- types: { path: 'string', content: 'string' },
349
- pathDeny: { path: ['.env', '*.key', '*.pem', '.git/**'] },
350
- maxSize: { content: 1048576 },
351
- secrets: ['content'],
352
- });
353
-
354
- // Pre-exec:校验 + 快照 · Validate + snapshot
355
- const { preExec, snapshot } = aos.executePipeline({
356
- sessionId: 'session_1',
357
- agentId: 'main_agent',
358
- toolName: 'write_file',
359
- parameters: { path: 'src/main.ts', content: 'console.log("hello");' },
360
- affectedFiles: ['src/main.ts'],
361
- });
362
-
363
- console.log(`Risk: ${preExec.riskScore.score} → ${preExec.riskScore.action}`);
364
- // → Risk: 0.19 → auto
365
-
366
- // Post-exec:验证 + 审计 · Verify + audit
367
- const result = aos.completeExecution({
368
- sessionId: 'session_1', agentId: 'main_agent',
369
- toolName: 'write_file',
370
- toolParameters: { path: 'src/main.ts', content: 'console.log("hello");' },
371
- toolResult: 'file written',
372
- snapshot,
373
- startTime: Date.now() - 500, endTime: Date.now(),
374
- retryCount: 0, wasSelfCorrected: false, hadTimeout: false,
375
- userAccepted: true, userProvidedEdit: false, resultWasUsed: true,
376
- });
377
-
378
- console.log(`Post-exec: ${result.postExec.outcomeScore}`);
379
- console.log(`Audit: ${result.auditEntry.id}`);
380
-
381
- // 记录反馈 · Record feedback
382
- aos.recordFeedback('user_immediate_continue', 'session_1');
383
-
384
- // 查看报告 · Status report
385
- console.log(aos.statusReport());
386
- ```
387
-
388
- ### 接入现有 Agent 框架 · Integrate with any Agent framework
389
-
390
- ```typescript
391
- import { AgentOS } from 'sentinel-agentos';
392
-
393
- const aos = new AgentOS({ workspaceRoot: process.cwd() });
394
-
395
- async function safeToolCall(toolName: string, params: Record<string, unknown>) {
396
- const sessionId = getCurrentSessionId();
397
-
398
- // 1. 校验 + 风险 + 快照 · Validate + Risk + Snapshot
399
- const { preExec, snapshot } = aos.executePipeline({
400
- sessionId, agentId: 'my_agent', toolName, parameters: params,
401
- });
402
-
403
- if (preExec.riskScore.action === 'deny') {
404
- throw new Error(`Rejected: risk ${preExec.riskScore.score}`);
405
- }
406
-
407
- if (preExec.riskScore.action === 'confirm') {
408
- const ok = await askUser(`Risk ${preExec.riskScore.score}. Proceed?`);
409
- if (!ok) return;
410
- }
411
-
412
- const t0 = Date.now();
413
- const result = await yourActualCall(toolName, params);
414
-
415
- // 2. 验证 + 审计 · Verify + Audit
416
- return aos.completeExecution({
417
- sessionId, agentId: 'my_agent', toolName,
418
- toolParameters: params, toolResult: result, snapshot,
419
- startTime: t0, endTime: Date.now(),
420
- retryCount: 0, wasSelfCorrected: false, hadTimeout: false,
421
- userAccepted: true, userProvidedEdit: false, resultWasUsed: false,
422
- });
423
- }
424
- ```
425
-
426
- ### 沙箱 · Sandbox
427
-
428
- ```typescript
429
- import { SandboxExecutor } from 'sentinel-agentos';
430
-
431
- const sandbox = new SandboxExecutor({
432
- mode: 'sandbox',
433
- workspaceRoot: process.cwd(),
434
- timeoutMs: 30000,
435
- networkAccess: 'whitelist',
436
- networkWhitelist: ['api.github.com', 'registry.npmjs.org'],
437
- writablePaths: ['src/', 'tests/', 'dist/'],
438
- allowedTools: ['read_file', 'write_file', 'edit', 'exec'],
439
- forbiddenTools: ['rm', 'unlink'],
440
- });
441
-
442
- // Pre-flight · 预检
443
- sandbox.validate('rm', { path: 'src/main.ts' });
444
- // { success: false, sandboxRejectReason: 'Tool "rm" is forbidden' }
445
-
446
- // Execute · 执行
447
- await sandbox.execute('exec', { command: 'npm test', cwd: process.cwd() });
448
- ```
449
-
450
- #### 2.2 中间件(一行接入) · Middleware (one-liner)
451
-
452
- ```typescript
453
- import { wrapAgent } from 'sentinel-agentos';
454
-
455
- // 一行接入——包裹你的 Agent 工具调用
456
- const sentinel = wrapAgent({ workspaceRoot: process.cwd() });
457
-
458
- // 每次工具调用前后调用即可
459
- const { allowed, reason } = sentinel.preCheck('exec', { command: 'rm -rf /' });
460
- // → { allowed: false, reason: 'Risk 9.18 → DENY' }
461
- ```
462
-
463
- #### 2.3 OpenClaw 插件
464
-
465
- 如果你在用 OpenClaw Agent 框架,直接以插件形式集成:
466
-
467
- ```typescript
468
- import { sentinelPlugin } from 'sentinel-agentos';
469
-
470
- // 注册为 OpenClaw 插件,自动 hook 所有工具调用
471
- const plugin = sentinelPlugin({
472
- workspaceRoot: process.cwd(),
473
- preRegisteredRules: true,
474
- });
475
- // → onBeforeTool → 校验 + 风险评分
476
- // onAfterTool 验证 + 审计
477
- ```
478
-
479
- ---
480
-
481
- ### 方式三:HTTP API(远程调用,跨语言通用)
482
-
483
- Sentinel AgentOS 可启动为独立 HTTP 服务,任何语言(Python/Go/Rust/Java...)都能调用。
484
-
485
- #### 3.1 启动服务
486
-
487
- ```bash
488
- # CLI 一行启动
489
- npx sentinel-agentos server --port 3300 --token ***
490
-
491
- # 或代码中启动
492
- import { createServer } from 'sentinel-agentos';
493
- createServer({ port: 3300, apiToken: '***' }).start();
494
- ```
495
-
496
- 启动后健康检查(免 token):
497
- ```bash
498
- curl http://localhost:3300/health
499
- #{"ok":true,"uptime":12.3}
500
- ```
501
-
502
- #### 3.2 鉴权
503
-
504
- `/health` 外所有端点需要 `Authorization: Bearer <token>` header。否则返回 `401`。
505
-
506
- #### 3.3 API 端点参考 · API Reference
507
-
508
- **基础端点:**
509
-
510
- | 端点 | 方法 | 鉴权 | 说明 |
511
- |------|:--:|:--:|------|
512
- | `/health` | GET | | 服务健康检查 |
513
- | `/pipeline/pre` | POST | ✅ | 执行前校验(Schema + Risk + Snapshot) |
514
- | `/pipeline/post` | POST | ✅ | 执行后验证(Verify + Audit + Feedback) |
515
- | `/pipeline/report` | GET | ✅ | 质量状态报告(文本) |
516
- | `/pipeline/profile` | GET | ✅ | 质量画像(JSON) |
517
-
518
- **Guard / Memory / Feedback / Audit 端点:**
519
-
520
- | 端点 | 方法 | 说明 |
521
- |------|:--:|------|
522
- | `/guard/schema` | POST | 注册 Schema 校验规则 |
523
- | `/memory/preference` | POST | 设置用户偏好 `{"key":"language","value":"zh-CN"}` |
524
- | `/memory/fact` | POST | 添加事实 `{"fact":"用户在上海"}` |
525
- | `/memory/context` | GET | 获取当前记忆上下文 |
526
- | `/feedback` | POST | 记录隐性反馈 `{"signal":"user_explicit_approval"}` |
527
- | `/audit` | GET | 查询审计日志(支持 `?limit=&sessionId=&toolName=&status=`) |
528
-
529
- **反馈信号类型:**
530
-
531
- | 信号 | 强度 | 说明 |
532
- |------|------|------|
533
- | `user_explicit_approval` | +0.6 | 用户明确说"做得好" |
534
- | `user_immediate_continue` | +0.3 | 用户立即继续对话 |
535
- | `user_used_result` | +0.7 | 用户使用了 Agent 的结果 |
536
- | `user_shared_output` | +0.8 | 用户分享了 Agent 输出 |
537
- | `user_modified_output` | -0.5 | 用户修改了 Agent 输出 |
538
- | `user_deleted_code` | -0.8 | 用户删除了 Agent 创建的代码 |
539
- | `user_interrupted` | -0.6 | 用户打断了 Agent |
540
- | `user_repeated_instruction` | -0.3 | 用户重复了相同指令 |
541
-
542
- #### 3.4 完整调用示例
543
-
544
- ```bash
545
- # 1. Pre-exec 校验 + 风险评分
546
- curl -s -H "Authorization: Bearer $TOKEN" \
547
- -X POST http://localhost:3300/pipeline/pre \
548
- -H 'Content-Type: application/json' \
549
- -d '{"toolName":"exec","parameters":{"command":"npm test"}}'
550
- # {"preExec":{"schemaCheck":{"pass":true},"riskScore":{"score":0.19,"action":"auto"}},"snapshot":{...}}
551
-
552
- # 2. Post-exec — 验证 + 审计
553
- # (传入 pre 返回的 snapshot)
554
- curl -s -H "Authorization: Bearer $TOKEN" \
555
- -X POST http://localhost:3300/pipeline/post \
556
- -H 'Content-Type: application/json' \
557
- -d '{"toolName":"exec","toolParameters":{"command":"npm test"},"toolResult":"all passed","snapshot":{...},"startTime":1718123456000,"endTime":1718123457000,"retryCount":0,"wasSelfCorrected":false,"hadTimeout":false,"userAccepted":true,"userProvidedEdit":false,"resultWasUsed":true}'
558
-
559
- # 3. 查看报告
560
- curl -s -H "Authorization: Bearer $TOKEN" http://localhost:3300/pipeline/report
561
-
562
- # 4. 查询审计
563
- curl -s -H "Authorization: Bearer $TOKEN" "http://localhost:3300/audit?limit=10&toolName=exec"
564
-
565
- # 5. 记录反馈
566
- curl -s -H "Authorization: Bearer $TOKEN" \
567
- -X POST http://localhost:3300/feedback \
568
- -H 'Content-Type: application/json' \
569
- -d '{"signal":"user_immediate_continue","sessionId":"session_1"}'
570
- ```
571
-
572
- #### 3.5 跨语言(Python 示例)
573
-
574
- ```python
575
- import requests
576
-
577
- BASE = "http://localhost:3300"
578
- HEADERS = {"Authorization": "Bearer ***"}
579
-
580
- # Pre-exec
581
- resp = requests.post(f"{BASE}/pipeline/pre", json={
582
- "toolName": "exec", "parameters": {"command": "npm test"}
583
- }, headers=HEADERS)
584
- data = resp.json()
585
- print(f"Risk: {data['preExec']['riskScore']['score']} → {data['preExec']['riskScore']['action']}")
586
-
587
- # Post-exec (pass snapshot from pre)
588
- snapshot = data["snapshot"]
589
- resp2 = requests.post(f"{BASE}/pipeline/post", json={
590
- "toolName": "exec",
591
- "toolParameters": {"command": "npm test"},
592
- "toolResult": "all passed",
593
- "snapshot": snapshot,
594
- "startTime": 1718123456000, "endTime": 1718123457000,
595
- "retryCount": 0, "wasSelfCorrected": False,
596
- "hadTimeout": False, "userAccepted": True,
597
- "userProvidedEdit": False, "resultWasUsed": True
598
- }, headers=HEADERS)
599
- print(f"Verify: {resp2.json()['postExec']['verifyPassed']}")
600
-
601
- # Report
602
- print(requests.get(f"{BASE}/pipeline/report", headers=HEADERS).text)
603
- ```
604
-
605
- ---
606
-
607
- ---
608
-
609
- ## 🔌 sentinel-guard Skill — OpenClaw 实际对接
610
-
611
- > 这是 Sentinel AgentOS 接入 OpenClaw Agent 框架的**生产级 skill**。
612
- > 提供一个统一入口 `sentinel.execute()`,自动走完 Guard → Execute → Verify + Audit + Memory + Evaluator 三层面。
613
- > 使用前务必阅读 [sentinel-guard SKILL.md](../skills/sentinel-guard/SKILL.md)。
614
-
615
- ### 统一入口 vs 传统两段式
616
-
617
- **传统方式(preCheck + postCheck 两次调用)**:
618
-
619
- ```javascript
620
- const guard = require('./sentinel-guard');
621
- const check = guard.preCheck('exec', { command: '...' }); // 只做拦截
622
- if (!check.passed) return ...;
623
- // 执行...
624
- guard.postCheck('exec', params, result); // 只做审计
625
- ```
626
-
627
- **统一入口(推荐)**:
628
-
629
- ```javascript
630
- const sentinel = require('./sentinel-guard');
631
- const result = await sentinel.execute('exec', { command: 'npm test' }, () => exec('npm test'));
632
-
633
- // result.allowed — Guard 是否放行
634
- // result.result — 执行函数的返回值
635
- // result.auditId — 审计 ID
636
- // result.verify — Verify Gate 状态 (PASS/WARN/FAIL)
637
- // result.profile — 当前质量评分 (0-100)
638
- ```
639
-
640
- ### 执行流程详解
641
-
642
- ```
643
- sentinel.execute(toolName, params, fn)
644
-
645
- ├─ 第1层: 确定性命令/文件拦截 (<1μs,零 LLM)
646
- │ ├─ 危险命令正则匹配 (rm -rf /, mkfs, dd if=, fork bomb...)
647
- │ ├─ 警告命令正则匹配 (git push --force, npm publish, DROP TABLE...)
648
- │ ├─ 敏感文件 glob 匹配 (.env, *.key, *.pem, .git/**...)
649
- │ └─ 保护文件匹配 (package.json, MEMORY.md, AGENTS.md...)
650
-
651
- ├─ 第2层: AgentOS Pipeline
652
- │ ├─ Schema Gate — 参数格式校验 (required/types/pathDeny/maxSize/secrets)
653
- │ ├─ Risk Gate — 四维公式评分 → auto/notify/confirm/deny
654
- │ └─ Snapshot Gate 执行前文件 hash 快照
655
-
656
- ├─ 第3层: 实际执行 fn()
657
- │ └─ 异常捕获,失败也记录审计
658
-
659
- ├─ 第4层: Verify + Audit + Evaluator
660
- ├─ Verify Gate 8 项确定性校验 (文件存在/变更/lint/格式...)
661
- │ ├─ Audit Log — JSONL 不可篡改审计
662
- │ ├─ PreExecEvaluator — 参数质量+上下文利用评分
663
- │ ├─ RuntimeEvaluator — 重试/超时/自纠正评分
664
- │ ├─ PostExecEvaluator — 验证通过/用户接受/结果利用率评分
665
- │ └─ AgentProfiler — 综合评分 0-100 + 趋势 + 亮点/警告
666
-
667
- ├─ 第5层: Memory 同步
668
- ├─ Working Memory 消息+工具结果缓存
669
- │ ├─ Episodic Memory 事件记录
670
- └─ Semantic Memory (自动迁移时写入)
671
-
672
- └─ 返回统一结果
673
- ```
674
-
675
- ### execute() 完整返回值
676
-
677
- | 字段 | 类型 | 说明 |
678
- |------|------|------|
679
- | `allowed` | boolean | 是否通过 Guard 层 |
680
- | `blocked` | boolean | 是否被拦截 |
681
- | `risk` | `'auto' | 'confirm' | 'deny'` | 风险等级 |
682
- | `reason` | string? | 拦截/警告原因(blocked=true 时) |
683
- | `needsConfirmation` | boolean? | 是否需要用户确认 |
684
- | `result` | any | 执行函数的返回值 |
685
- | `error` | string? | 执行异常信息 |
686
- | `auditId` | string | 审计条目 ID(如 `op_5`) |
687
- | `verify` | `'PASS' | 'WARN' | 'FAIL'` | Verify Gate 状态 |
688
- | `profile` | number | 当前 Agent 质量评分 (0-100) |
689
-
690
- **被拦截示例**:
691
-
692
- ```json
693
- {
694
- "allowed": false,
695
- "blocked": true,
696
- "risk": "DENY",
697
- "reason": "🚫 危险命令: rm -rf / — 删除整个系统"
698
- }
699
- ```
700
-
701
- **正常通过示例**:
702
-
703
- ```json
704
- {
705
- "allowed": true,
706
- "blocked": false,
707
- "risk": "auto",
708
- "result": "hello output",
709
- "auditId": "op_5",
710
- "verify": "PASS",
711
- "profile": 85
712
- }
713
- ```
714
-
715
- ### 自动迁移 MEMORY.md → Semantic Memory
716
-
717
- 首次加载 sentinel-guard 时自动执行,仅一次:
718
-
719
- 1. 解析 `MEMORY.md` 的 Markdown 结构(支持 bullet 列表和表格行)
720
- 2. 提取用户事实 (👤 关于老板 / 🆔 关于我) → `semantic.addFact()`
721
- 3. 提取工作方式规则 (🤖 我的工作方式) → `semantic.learnRule()`
722
- 4. 提取项目上下文 (📦 coderev / agentos) → `semantic.setProjectContext()`
723
- 5. 提取环境记录 (💻 环境记录) → `semantic.addFact()`
724
- 6. 提取关键决策 (💡 关键决策记录) → `episodic.record('decision', ...)`
725
- 7. 生成 `.sentinel-migrated` 标记文件防止重复
726
-
727
- 迁移后原有 MEMORY.md 不受影响(只读不写),两套记忆并行:
728
-
729
- | 记忆系统 | 用途 | 格式 |
730
- |---------|------|------|
731
- | `MEMORY.md` | 人类编辑,session 注入上下文 | Markdown |
732
- | AgentOS Semantic Memory | 程序读写,自动学习 | 结构化 JSON (`.agentos/`) |
733
-
734
- ### 规则配置 guard-rules.json
735
-
736
- 所有 Guard 黑白名单可通过 `guard-rules.json` 直接编辑,无需改源码:
737
-
738
- ```json
739
- {
740
- "dangerous": [
741
- ["rm -rf /", "删除整个系统"],
742
- ["sudo rm", "超级用户删除"],
743
- ["mkfs", "格式化磁盘"]
744
- ],
745
- "warning": [
746
- ["git push --force", "强制覆盖远程分支"],
747
- ["npm publish\\b", "发布 npm 公共包"],
748
- ["DROP (TABLE|DATABASE)", "删除数据库"]
749
- ],
750
- "sensitiveFiles": [
751
- ".env", ".env.*", "*.key", "*.pem",
752
- ".git/**", "**/credentials/**"
753
- ],
754
- "protectedFiles": [
755
- "package.json", "MEMORY.md", "AGENTS.md", "SOUL.md"
756
- ],
757
- "schema": [
758
- { "tool": "exec", "required": ["command"] },
759
- {
760
- "tool": "write",
761
- "required": ["path", "content"],
762
- "pathDeny": [".env", "*.key", ".git/**"],
763
- "maxSize": { "content": 1048576 },
764
- "secrets": ["content"]
765
- }
766
- ]
767
- }
768
- ```
769
-
770
- | 配置项 | 类型 | 说明 |
771
- |--------|------|------|
772
- | `dangerous` | `[regex, desc][]` | 匹配到直接拒绝 |
773
- | `warning` | `[regex, desc][]` | 匹配到需用户确认 |
774
- | `sensitiveFiles` | `string[]` | glob 模式,禁止读写 |
775
- | `protectedFiles` | `string[]` | 精确匹配,禁止删除 |
776
- | `schema` | `SchemaRule[]` | AgentOS Schema Gate 规则 |
777
-
778
- ### 完整 API 参考
779
-
780
- ```javascript
781
- const sentinel = require('./sentinel-guard');
782
- ```
783
-
784
- | 方法 | 类型 | 说明 |
785
- |------|------|------|
786
- | `execute(tool, params, fn, opts?)` | async | **统一入口**,走完三层 |
787
- | `preCheck(tool, params)` | sync | [兼容] 仅确定性拦截 |
788
- | `postCheck(tool, params, result)` | sync | [兼容] 仅审计记录 |
789
- | `injectContext()` | sync → string | Session 启动时注入 Memory 上下文 |
790
- | `endSession()` | sync | Session 结束:追加 daily log → 清空 Working → 同步 Episodic |
791
- | `status()` | sync → string | AgentOS 状态报告 |
792
- | `fullStatus()` | sync → object | 完整状态快照 (JSON) |
793
- | `compactReport()` | sync → string | 精简版评估报告 |
794
- | `fullReport()` | sync → string | 完整评估报告 |
795
- | `audit(limit?)` | sync array | 最近 N 条审计记录 |
796
- | `feedback(signal)` | sync | 记录用户反馈信号 |
797
-
798
- ### Session 生命周期
799
-
800
- ```
801
- Session 启动
802
- ├─ require('./sentinel-guard') ← 首次自动迁移 MEMORY.md
803
- ├─ sentinel.injectContext() ← 注入 Semantic+Episodic 上下文
804
-
805
- Session 运行中
806
- ├─ sentinel.execute('exec', ...) ← 每次工具调用
807
- ├─ sentinel.execute('write', ...)
808
- ├─ sentinel.feedback('user_used_result') ← 关键节点记录反馈
809
-
810
- Session 结束
811
- └─ sentinel.endSession() 追加 daily log + 清空 Working
812
- ```
813
-
814
- ### AgentOS sentinel-guard 功能对照
815
-
816
- | 功能 | AgentOS 源码 | sentinel-guard skill | 覆盖率 |
817
- |------|------------|---------------------|:------:|
818
- | Schema Gate (12 项校验) | `schema-gate.ts` | `execute()` 内自动 | 100% |
819
- | Risk Gate (四维公式) | ✅ `risk-gate.ts` | `execute()` 内自动 | 100% |
820
- | 确定性命令拦截 | ❌ (依赖 Sandbox) | ✅ 正则匹配 (<1μs) | **额外增强** |
821
- | Snapshot Gate | ✅ `snapshot-verify.ts` | ✅ `execute()` 内自动 | 100% |
822
- | Verify Gate (8 项校验) | ✅ `snapshot-verify.ts` | ✅ `execute()` 内自动 | 100% |
823
- | Audit Log (JSONL) | ✅ `audit-log.ts` | ✅ 双写 (AgentOS + 自身) | 100% |
824
- | 规则可配置 | ❌ (代码硬编码) | ✅ `guard-rules.json` | **额外增强** |
825
- | Working Memory | ✅ `working.ts` | ✅ 消息+工具缓存 | 100% |
826
- | Episodic Memory | ✅ `episodic.ts` | 事件自动记录 | 100% |
827
- | Semantic Memory | ✅ `semantic.ts` | ✅ 自动迁移+初始值 | 100% |
828
- | MEMORY.md 迁移 | ✅ `memory-bridge.ts` | ✅ 首次加载自动跑 | 100% |
829
- | Session 注入上下文 | ✅ `injectContext()` | ✅ `sentinel.injectContext()` | 100% |
830
- | Session 清理 | ✅ `endSession()` | ✅ 含 daily log | 100% |
831
- | PreExecEvaluator | ✅ `exec-evaluator.ts` | ✅ `execute()` 内自动 | 100% |
832
- | RuntimeEvaluator | ✅ `exec-evaluator.ts` | ✅ `execute()` 内自动 | 100% |
833
- | PostExecEvaluator | ✅ `exec-evaluator.ts` | ✅ `execute()` 内自动 | 100% |
834
- | AgentProfiler | ✅ `profiler.ts` | ✅ `execute()` 返回 profile | 100% |
835
- | ImplicitFeedback | ✅ `feedback.ts` | ✅ `recordFeedback()` | 100% |
836
- | Daily Log 注入 | ✅ `evaluation-bridge.ts` | ✅ `endSession()` 自动 | 100% |
837
- | Compact/Full Report | ✅ `evaluation-bridge.ts` | ✅ `compactReport()`/`fullReport()` | 100% |
838
- | Sandbox 沙箱 | ✅ `sandbox.ts` | ❌ (暂未接入) | 0% |
839
- | HTTP API | `server.ts` | (skill 为进程内调用) | N/A |
840
- | **按设计范围总计** | **20 项** | **20/20** | **100%** |
841
-
842
- ### 快速入门(5 步接入)
843
-
844
- ```javascript
845
- // 1. 加载 skill(自动迁移 MEMORY.md)
846
- const sentinel = require('./sentinel-guard');
847
-
848
- // 2. Session 启动 注入记忆上下文
849
- const context = sentinel.injectContext();
850
-
851
- // 3. 工具调用 统一入口,三层全走
852
- const r = await sentinel.execute('write',
853
- { path: 'src/main.ts', content: 'console.log("hi")' },
854
- () => fs.writeFileSync('src/main.ts', 'console.log("hi")')
855
- );
856
- if (!r.allowed) return { blocked: true, reason: r.reason };
857
-
858
- // 4. 记录反馈
859
- sentinel.feedback('user_used_result');
860
-
861
- // 5. Session 结束 追加 daily log + 清理
862
- sentinel.endSession();
863
- ```
864
-
865
- 完整示例代码见 `sentinel-guard/SKILL.md`,配置文件见 `sentinel-guard/guard-rules.json`。
866
-
867
- ---
868
-
869
- ### API 层 · SDK API
870
-
871
- ```typescript
872
- import { Sentinel AgentOS, Sentinel AgentOSAPI } from 'Sentinel AgentOS';
873
-
874
- const api = new AgentOSAPI(new AgentOS());
875
-
876
- // Guard
877
- api.guardRegisterRule({ tool: 'delete_file', required: ['path'] });
878
-
879
- // Memory
880
- api.memorySetPreference('language', 'zh-CN');
881
- api.memoryLearnRule('Never push directly to main', 'cr_1');
882
-
883
- // Pipeline + Audit
884
- const result = await api.pipelineExecute({...});
885
- const audit = api.auditQuery({ toolName: 'write_file', limit: 10 });
886
-
887
- // Profile
888
- const report = api.getStatusReport();
889
- api.endSession('session_1');
890
- ```
891
-
892
- ---
893
-
894
- ## 📖 使用案例 · Examples
895
-
896
- ### 1. 拦截危险命令 · Blocking dangerous commands
897
-
898
- ```typescript
899
- const { preExec } = aos.executePipeline({
900
- sessionId: 's1', agentId: 'a1',
901
- toolName: 'exec',
902
- parameters: { command: 'rm -rf /home' },
903
- });
904
- // → { score: 9.18, action: 'deny' } 🔴 自动拒绝 · Auto-denied
905
- ```
906
-
907
- ### 2. 检测 Agent 幻觉 · Detecting hallucination
908
-
909
- ```typescript
910
- // Agent 声称"写入了文件",但实际没有 · Agent claims "file written" but didn't
911
- const result = aos.completeExecution({
912
- ...,
913
- toolResult: 'file written successfully', // Agent 幻觉!
914
- snapshot,
915
- ...
916
- });
917
- console.log(result.postExec.verifyPassed); // → false
918
- // Verify Gate 检测到文件不存在 → FAIL
919
- ```
920
-
921
- ### 3. 跨会话记忆 · Cross-session memory
922
-
923
- ```typescript
924
- // Session 1: 学到偏好 · Learned preferences
925
- const aos1 = new AgentOS();
926
- aos1.memory.semantic.setPreference('language', 'zh-CN');
927
- aos1.memory.semantic.learnRule('测试前先编译', 'session_1');
928
- aos1.endSession('session_1');
929
-
930
- // Session 2: 自动注入 · Auto-injected
931
- const aos2 = new AgentOS();
932
- console.log(aos2.injectContext());
933
- // [Sentinel AgentOS Semantic Memory]
934
- // ## Preferences
935
- // - language: "zh-CN"
936
- // ## Learned Rules · 学习到的规则
937
- // - [50%] 测试前先编译
938
- ```
939
-
940
- ### 4. 隐性反馈驱动改进 · Feedback-driven improvement
941
-
942
- ```typescript
943
- // 用户删除了 Agent 创建的代码 · User deleted agent-created code
944
- aos.recordFeedback('user_deleted_code', 's1');
945
-
946
- // 连续3次修改 · Modified 3 times
947
- aos.recordFeedback('user_modified_output', 's1');
948
- aos.recordFeedback('user_modified_output', 's1');
949
- aos.recordFeedback('user_modified_output', 's1');
950
-
951
- const stats = aos.evaluator.feedback.stats();
952
- // { totalSignals: 4, negativeSignals: 4, averageStrength: -0.57 }
953
-
954
- const profile = aos.getProfile();
955
- // → warnings: ["User satisfaction declining — review recent sessions"]
956
- ```
957
-
958
- ### 5. 沙箱保护 · Sandbox protection
959
-
960
- ```typescript
961
- const sandbox = new SandboxExecutor({
962
- mode: 'sandbox',
963
- networkAccess: 'none', // 禁止网络 · No network
964
- writablePaths: ['src/', 'logs/'], // 只能写这里 · Only writable here
965
- forbiddenTools: ['rm', 'git_push'],
966
- });
967
-
968
- await sandbox.execute('exec', { command: 'npm test' }); // ✅ OK
969
- await sandbox.execute('exec', { command: 'curl evil.com' }); // ❌ 网络被黑洞 · Blocked
970
- ```
971
-
972
- ---
973
-
974
- ## 🧪 测试 · Tests
975
-
976
- ```bash
977
- npm test
978
- ```
979
-
980
- ```
981
- PASS tests/guard/schema-gate.test.ts (21 tests)
982
- PASS tests/guard/risk-gate.test.ts (20 tests)
983
- PASS tests/guard/snapshot-verify-audit.test.ts (17 tests)
984
- PASS tests/memory/memory.test.ts (29 tests)
985
- PASS tests/core.test.ts (12 tests)
986
- ────────────────────────────────────────────────
987
- Test Suites: 5 passed, 5 total
988
- Tests: 99 passed, 99 total
989
- ```
990
-
991
- ---
992
-
993
- ## ⚠️ 常见问题 · FAQ
994
-
995
- <details>
996
- <summary><b>Q: Sentinel AgentOS LangChain / CrewAI 什么关系?</b></summary>
997
-
998
- Sentinel AgentOS **不是竞争对手**,是基础设施层。LangChain/CrewAI 是 Agent 框架,Sentinel AgentOS 是给它们提供安全、记忆、评估的操作系统。可以增量接入任何框架。
999
- *Not a competitor — infrastructure. LangChain/CrewAI are agent frameworks; Sentinel AgentOS provides safety + memory + evaluation as an OS layer. Incrementally pluggable into any framework.*
1000
- </details>
1001
-
1002
- <details>
1003
- <summary><b>Q: 为什么 Guard 层不用 LLM? · Why no LLM in Guard?</b></summary>
1004
-
1005
- LLM 做安全判断 = 用问题制造者来解决问题。Schema 校验是纯工程数学——类型检查、范围检查、hash 对比——这些 LLM 反而做不好(会幻觉)。确定性代码 = 0 幻觉。
1006
- *Using LLM for security = solving problems with the problem-maker. Schema validation is pure engineering — type/range/hash checks — things LLMs are bad at. Deterministic code = zero hallucination.*
1007
- </details>
1008
-
1009
- <details>
1010
- <summary><b>Q: Memory 层和 RAG 有什么区别? · How is this different from RAG?</b></summary>
1011
-
1012
- RAG = 把对话扔进向量库做检索。Sentinel AgentOS Memory = 人脑模型:Working(当前会话)、Episodic(自动评分+压缩)、Semantic(提炼后的永久知识)。最重要的是:**Sentinel AgentOS 会自动写入记忆,不需要 Agent 手动管理**。
1013
- *RAG = dump conversation into vector DB. Sentinel AgentOS Memory = brain model. Most importantly: **Sentinel AgentOS auto-writes memory; agents don't need to manage it manually.***
1014
- </details>
1015
-
1016
- <details>
1017
- <summary><b>Q: 会不会很慢? · Is it slow?</b></summary>
1018
-
1019
- 不会。Guard 层所有校验都是 `fs.existsSync()`、hash 对比、数学公式,每个校验 **< 1ms**。Snapshot 只记录 hash 不复制文件。整个流水线开销可忽略。
1020
- *No. All Guard checks are fs.existsSync(), hash comparison, math formulas — each < 1ms. Snapshot records hashes only, no file copy. Pipeline overhead is negligible.*
1021
- </details>
1022
-
1023
- <details>
1024
- <summary><b>Q: 能用在生产环境吗? · Production-ready?</b></summary>
1025
-
1026
- v1.0 已完成 100% 设计文档覆盖率、99 个测试全通过、TypeScript 严格模式。API 稳定,可以集成。但建议先在测试环境跑一段时间。
1027
- *v1.0 has 100% design coverage, 99 passing tests, strict TypeScript. API is stable and integrable. Recommend testing before production.*
1028
- </details>
1029
-
1030
- <details>
1031
- <summary><b>Q: npm 包已经发布了吗? · Is npm package published?</b></summary>
1032
-
1033
- 已发布。`npm install sentinel-agentos` 即可使用。当前版本 v0.1.x。
1034
- *Published. Just `npm install sentinel-agentos`. Current version v0.1.x.*
1035
- </details>
1036
-
1037
- <details>
1038
- <summary><b>Q: 沙箱模式安全吗? · Is sandbox truly secure?</b></summary>
1039
-
1040
- v1.0 沙箱基于环境变量 + 路径校验 + 命令模式检测,不是容器级隔离。v2.0 计划支持 Docker 沙箱。
1041
- *v1.0 sandbox uses env vars + path validation + command pattern detection not container-level isolation. Docker sandbox planned for v2.0.*
1042
- </details>
1043
-
1044
- <details>
1045
- <summary><b>Q: 怎么看 Audit Log? · How to view audit logs?</b></summary>
1046
-
1047
- ```bash
1048
- cat .Sentinel AgentOS/audit.jsonl | jq '.'
1049
- ```
1050
-
1051
- 或通过 API · *or via API:*
1052
-
1053
- ```typescript
1054
- const entries = api.auditQuery({ minScore: 3.0 }); // 高风险操作 · High-risk ops
1055
- ```
1056
- </details>
1057
-
1058
- <details>
1059
- <summary><b>Q: Sentinel AgentOS 需要 API Key 吗? · Does it need an API Key?</b></summary>
1060
-
1061
- 不需要。Sentinel AgentOS Guard / Memory / Evaluator 层都是纯确定性代码,不调用任何外部 AI API。唯一的鉴权是 HTTP API 模式下可选的 `--token` 参数。
1062
- *No. All Guard/Memory/Evaluator layers are pure deterministic code with zero external API calls. The only authentication is the optional `--token` for HTTP API mode.*
1063
- </details>
1064
-
1065
- <details>
1066
- <summary><b>Q: HTTP API Token 怎么设置? · How to set HTTP API token?</b></summary>
1067
-
1068
- 三种方式:
1069
- 1. 命令行参数:`npx sentinel-agentos server --port 3300 --token my-secret`
1070
- 2. 代码中配置:`createServer({ port: 3300, apiToken: 'my-secret' })`
1071
- 3. 环境变量:`AGENTOS_TOKEN=*** npx sentinel-agentos server`
1072
-
1073
- 不设置 Token 则不加鉴权(仅适合本地开发环境)。
1074
- *Three ways: CLI flag, code config, or AGENTOS_TOKEN env var. No token = no auth (local dev only).*
1075
- </details>
1076
-
1077
- <details>
1078
- <summary><b>Q: Token 泄漏了怎么办? · What if token leaks?</b></summary>
1079
-
1080
- 重启服务,换一个新 Token 即可:
1081
- 1. 生成新 Token:`openssl rand -hex 32`
1082
- 2. 重启 sentinel-agentos server 使用新 Token
1083
- 3. 更新所有客户端调用
1084
- Sentinel AgentOS 的 Token 是服务端本地验证的,无需到任何平台撤销。
1085
- *Restart server with a new token. No external platform involved — tokens are validated locally.*
1086
- </details>
1087
-
1088
- ---
1089
-
1090
- ## 🗺️ 路线图 · Roadmap
1091
-
1092
- | 版本 | 内容 | 状态 |
1093
- |------|------|:--:|
1094
- | v0.1 | 项目脚手架 + 类型定义 · *Scaffold + types* | |
1095
- | v0.2 | Guard 层(6 组件)· *Guard layer (6 components)* | ✅ |
1096
- | v0.3 | Memory 层(3 层)· *Memory layer (3 layers)* | ✅ |
1097
- | v0.4 | Evaluator 层(评估 + 反馈 + 画像)· *Evaluator* | ✅ |
1098
- | v1.0 | 沙箱 + API + x- 扩展 + 校验补齐 · *Sandbox + API + x-ext* | ✅ |
1099
- | v1.1 | npm 发布 + 三种接入方式 · *npm publish + 3 modes* | ✅ |
1100
- | v2.0 | Docker 沙箱、Dashboard、SaaS · *Docker sandbox, Dashboard, SaaS* | 📋 |
1101
-
1102
- ---
1103
-
1104
- ## 🔑 Token 与鉴权说明
1105
-
1106
- Sentinel AgentOS 本身**不依赖外部 AI API**,所有 Guard / Memory / Evaluator 都是纯确定性代码。唯一的鉴权需求来自 **HTTP API 模式**下的 `server` 命令。
1107
-
1108
- ### HTTP API Token 鉴权
1109
-
1110
- 启动 HTTP 服务后,除 `/health` 外所有端点都需要 Bearer Token 鉴权。
1111
-
1112
- #### 启动时设置 Token
1113
-
1114
- ```bash
1115
- # 方式一:命令行参数
1116
- npx sentinel-agentos server --port 3300 --token my-secret-token-123
1117
-
1118
- # 方式二:代码中配置
1119
- import { createServer } from 'sentinel-agentos';
1120
- const server = createServer({ port: 3300, apiToken: 'my-secret-token-123' });
1121
- await server.start();
1122
- ```
1123
-
1124
- #### 客户端调用
1125
-
1126
- ```bash
1127
- # 所有 API(/health 除外)都需要 Authorization header
1128
- curl -H "Authorization: Bearer my-secret-token-123" \
1129
- http://localhost:3300/pipeline/profile
1130
-
1131
- # Token 不匹配 → 401 Unauthorized
1132
- curl http://localhost:3300/pipeline/profile
1133
- # → {"error":"Unauthorized: invalid or missing API token"}
1134
- ```
1135
-
1136
- #### Token 未设置时
1137
-
1138
- 如果不传 `--token` `apiToken`,服务**不加鉴权**,所有端点可自由访问。适用于本地开发环境,生产环境**强烈建议设置 Token**。
1139
-
1140
- ```bash
1141
- # 无鉴权模式(仅限本地开发)
1142
- npx sentinel-agentos server --port 3300
1143
- # 所有端点无需 Authorization header
1144
- ```
1145
-
1146
- #### Token 最佳实践
1147
-
1148
- | 环境 | Token 策略 | 示例 |
1149
- |------|----------|------|
1150
- | 本地开发 | 可不用 Token | `npx sentinel-agentos server --port 3300` |
1151
- | 本机测试 | 简短 Token | `--token dev-123` |
1152
- | 生产环境 | 强随机 Token | `--token $(openssl rand -hex 32)` |
1153
- | Docker / CI | 环境变量注入 | `--token $AGENTOS_API_TOKEN` |
1154
- | 跨语言调用 | HTTP header | `Authorization: Bearer <token>` |
1155
-
1156
- ### 环境变量配置
1157
-
1158
- 除 Token 外,Sentinel AgentOS 没有其他必填环境变量。可选的环境变量:
1159
-
1160
- | 环境变量 | 说明 | 默认值 |
1161
- |---------|------|--------|
1162
- | `HOME` / `USERPROFILE` | 持久化存储根目录 | 系统默认 |
1163
- | `AGENTOS_WORKSPACE` | workspace 根目录 | `process.cwd()` |
1164
- | `AGENTOS_TOKEN` | API Token(备选方式) | — |
1165
-
1166
- ---
1167
-
1168
- ## 📋 完整接口使用说明
1169
-
1170
- > 本章汇总 Sentinel AgentOS 所有接口——CLI、SDK、HTTP API、中间件、沙箱——作为完整参考。
1171
-
1172
- ### 命令一览
1173
-
1174
- | 分类 | 接口/命令 | 说明 |
1175
- |------|---------|------|
1176
- | CLI | `validate` | 参数格式校验(Schema Gate) |
1177
- | CLI | `risk` | 风险评分(Risk Gate) |
1178
- | CLI | `audit` | 查询审计日志 |
1179
- | CLI | `stats` | 审计统计(JSON) |
1180
- | CLI | `profile` | Agent 质量画像(JSON) |
1181
- | CLI | `status` | 质量状态报告(人类可读) |
1182
- | CLI | `server` | 启动 HTTP API 服务 |
1183
- | CLI | `memory` | 查看注入上下文 |
1184
- | CLI | `help` | 帮助信息 |
1185
- | SDK | `AgentOS` | 主类,完整流水线 |
1186
- | SDK | `AgentOSAPI` | SDK 协议层(25+ 方法) |
1187
- | SDK | `SchemaGate` / `RiskGate` 等 | 独立组件 |
1188
- | SDK | `wrapAgent` | 一行接入中间件 |
1189
- | SDK | `sentinelPlugin` | OpenClaw 插件 |
1190
- | SDK | `SandboxExecutor` | 沙箱执行器 |
1191
- | HTTP | `POST /pipeline/pre` | 执行前校验 |
1192
- | HTTP | `POST /pipeline/post` | 执行后验证 |
1193
- | HTTP | `GET /pipeline/report` | 状态报告 |
1194
- | HTTP | `GET /pipeline/profile` | 质量画像 |
1195
- | HTTP | `POST /guard/schema` | 注册 Schema 规则 |
1196
- | HTTP | `GET /guard/schema` | 查看 Schema 规则 |
1197
- | HTTP | `POST /memory/preference` | 设置偏好 |
1198
- | HTTP | `POST /memory/fact` | 添加事实 |
1199
- | HTTP | `POST /memory/rule` | 学习规则 |
1200
- | HTTP | `GET /memory/context` | 获取注入上下文 |
1201
- | HTTP | `GET /audit` | 查询审计日志 |
1202
- | HTTP | `POST /feedback` | 记录反馈 |
1203
- | HTTP | `POST /session/end` | 结束 session |
1204
- | HTTP | `GET /health` | 健康检查(免 Token) |
1205
-
1206
- ---
1207
-
1208
- ### CLI 接口
1209
-
1210
- ```
1211
- sentinel-agentos <command> [args...]
1212
- ```
1213
-
1214
- #### `validate` 参数格式校验
1215
-
1216
- ```bash
1217
- # 新语法(推荐)
1218
- sentinel-agentos validate <tool> [key=value...]
1219
-
1220
- # 校验 exec 命令
1221
- sentinel-agentos validate exec command="rm -rf /"
1222
- # {"pass":true,"errors":[]}
1223
-
1224
- # 校验 write_file(会被 pathDeny 拦截)
1225
- sentinel-agentos validate write_file path=.env content=hello
1226
- # {"pass":false,"errors":[{"field":"path","message":"path matches deny pattern"}]}
1227
-
1228
- # 旧语法(--tool + --params JSON)
1229
- sentinel-agentos validate --tool exec --params '{"command":"npm test"}'
1230
- ```
1231
-
1232
- | 参数 | 说明 |
1233
- |------|------|
1234
- | `<tool>` | 工具名称(如 `exec`, `write_file`, `delete_file`) |
1235
- | `key=value` | 参数键值对,支持 `key="带空格的值"`,自动检测类型 |
1236
-
1237
- #### `risk` — 风险评分
1238
-
1239
- ```bash
1240
- sentinel-agentos risk exec command="sudo reboot"
1241
- # → {"score":8.5,"action":"deny","dimensions":{"impact":3,"reversibility":0.2,...}}
1242
-
1243
- sentinel-agentos risk exec command="npm test"
1244
- # → {"score":0.19,"action":"auto",...}
1245
- ```
1246
-
1247
- | 风险等级 | 分数 | 动作 |
1248
- |---------|------|------|
1249
- | 🟢 Auto | 0.5 | 自动放行 |
1250
- | 🔵 Notify | ≤ 1.0 | 执行后通知 |
1251
- | 🟡 Confirm | ≤ 3.0 | 暂停等待确认 |
1252
- | 🔴 Deny | > 8.0 | 直接拒绝 |
1253
-
1254
- #### `audit` 查询审计日志
1255
-
1256
- ```bash
1257
- sentinel-agentos audit --limit 10
1258
- # → [{id, sessionId, toolName, verifyStatus, riskScore, ...}, ...]
1259
-
1260
- sentinel-agentos audit --limit 5
1261
- ```
1262
-
1263
- #### `stats` / `profile` / `status` — 统计与画像
1264
-
1265
- ```bash
1266
- # 审计统计(JSON)
1267
- sentinel-agentos stats
1268
- # {"totalOperations":156,"verifyFailures":2,"highRiskOps":3,...}
1269
-
1270
- # Agent 质量画像(JSON)
1271
- sentinel-agentos profile
1272
- # → {"overallScore":85,"breakdown":{...},"trends":{...},"warnings":[...]}
1273
-
1274
- # 质量状态报告(人类可读)
1275
- sentinel-agentos status
1276
- # → 文本报告
1277
- ```
1278
-
1279
- #### `server` 启动 HTTP API 服务
1280
-
1281
- ```bash
1282
- sentinel-agentos server --port 3300 --token ***
1283
- # → 🛡️ Sentinel AgentOS HTTP server → http://127.0.0.1:3300
1284
-
1285
- # 可选项
1286
- sentinel-agentos server --port 8080 --host 0.0.0.0 --token ***
1287
- ```
1288
-
1289
- | 参数 | 默认值 | 说明 |
1290
- |------|--------|------|
1291
- | `--port <N>` | `3300` | 服务端口 |
1292
- | `--host <IP>` | `127.0.0.1` | 绑定地址 |
1293
- | `--token <str>` | — | API 鉴权 Token(不设则无鉴权) |
1294
-
1295
- #### `memory` — 查看记忆上下文
1296
-
1297
- ```bash
1298
- sentinel-agentos memory
1299
- # → 当前 semantic + episodic 注入的上下文文本
1300
- ```
1301
-
1302
- ---
1303
-
1304
- ### SDK 接口
1305
-
1306
- #### `AgentOS` — 主类
1307
-
1308
- ```typescript
1309
- import { AgentOS } from 'sentinel-agentos';
1310
-
1311
- const aos = new AgentOS({
1312
- workspaceRoot: process.cwd(), // 工作区根目录
1313
- maxWorkingTokens: 50000, // 工作记忆 token 上限
1314
- maxEpisodicSizeKb: 500, // 情景记忆大小上限 (KB)
1315
- guardConfig: { // Guard 配置
1316
- riskGate: {
1317
- autoApprove: 0.5,
1318
- notify: 1.0,
1319
- confirm: 3.0,
1320
- deny: 8.0,
1321
- },
1322
- },
1323
- });
1324
- ```
1325
-
1326
- **构造函数参数 `AgentOSConfig`**:
1327
-
1328
- | 字段 | 类型 | 默认值 | 说明 |
1329
- |------|------|--------|------|
1330
- | `workspaceRoot` | string | `process.cwd()` | 工作区根目录,持久化存储位置 |
1331
- | `maxWorkingTokens` | number | `50000` | 工作记忆最大 token 数 |
1332
- | `maxEpisodicSizeKb` | number | `500` | 情景记忆最大大小 (KB) |
1333
- | `guardConfig.riskGate` | object | 见上 | 风险评分阈值覆盖 |
1334
- | `evaluatorConfig.implicitFeedbackEnabled` | boolean | | 隐性反馈开关 |
1335
-
1336
- **核心方法**:
1337
-
1338
- | 方法 | 返回 | 说明 |
1339
- |------|------|------|
1340
- | `executePipeline({...})` | `{preExec, snapshot, profile}` | 执行前校验流水线(Schema + Risk + Snapshot) |
1341
- | `completeExecution({...})` | `{runtime, postExec, auditEntry, profile}` | 执行后验证流水线(Verify + Audit) |
1342
- | `recordFeedback(signal, sessionId)` | `void` | 记录隐性用户反馈 |
1343
- | `injectContext()` | `string` | 注入记忆上下文(session 启动时调用) |
1344
- | `endSession(sessionId)` | `void` | 结束 session(清空 Working Memory) |
1345
- | `getProfile(sessionId?)` | `AgentProfile` | 获取 Agent 质量画像 |
1346
- | `getAuditStats()` | 审计统计 | 获取审计统计 |
1347
- | `statusReport()` | `string` | 获取人类可读的状态报告 |
1348
-
1349
- **访问子组件**:
1350
-
1351
- ```typescript
1352
- // Guard 层
1353
- aos.guard.schema // SchemaGate — 注册/查询校验规则
1354
- aos.guard.risk // RiskGate — 风险评分引擎
1355
- aos.guard.snapshot // SnapshotGate — 执行前快照
1356
- aos.guard.verify // VerifyGate 执行后验证
1357
- aos.guard.audit // AuditLog — 审计日志
1358
-
1359
- // Memory
1360
- aos.memory.working // WorkingMemory 当前会话工作记忆
1361
- aos.memory.episodic // EpisodicMemory 跨会话事件时间线
1362
- aos.memory.semantic // SemanticMemoryStore永久知识
1363
-
1364
- // Evaluator 层
1365
- aos.evaluator.preExec // PreExecEvaluator — 执行前评估
1366
- aos.evaluator.runtime // RuntimeEvaluator 执行中评估
1367
- aos.evaluator.postExec // PostExecEvaluator — 执行后评估
1368
- aos.evaluator.feedback // ImplicitFeedbackEngine 隐性反馈
1369
- aos.evaluator.profiler // AgentProfiler 质量画像
1370
- ```
1371
-
1372
- #### `AgentOSAPI` SDK 协议层
1373
-
1374
- ```typescript
1375
- import { AgentOS, AgentOSAPI } from 'sentinel-agentos';
1376
-
1377
- const api = new AgentOSAPI(new AgentOS());
1378
-
1379
- // Guard
1380
- api.guardRegisterRule({ tool: 'exec', required: ['command'] });
1381
- api.guardRegisterRules([...]);
1382
- api.guardEvaluateRisk('exec', { command: 'rm -rf /' });
1383
- api.guardSetRiskThresholds({ autoApprove: 0.5, deny: 6.0 });
1384
-
1385
- // Pipeline
1386
- const result = await api.pipelineExecute({
1387
- sessionId: 's1', agentId: 'a1',
1388
- toolName: 'write_file',
1389
- toolParameters: { path: 'src/main.ts', content: 'hello' },
1390
- });
1391
- const complete = api.pipelineComplete({...});
1392
-
1393
- // Memory
1394
- api.memorySetPreference('language', 'zh-CN');
1395
- api.memoryGetPreference('language'); // 'zh-CN'
1396
- api.memoryLearnRule('提交前 npm test', 'session_1');
1397
- api.memoryDefineTerm('PEP', 'Python Enhancement Proposal');
1398
- api.memorySetProjectContext('my-app', { description: '...', techStack: ['React', 'Node'] });
1399
- api.memoryInjectContext(); // → 启动注入文本
1400
- api.memoryAddMessage('user', 'Hello');
1401
- api.memoryRecordEvent('decision', 'Chose approach A', ['architecture'], []);
1402
-
1403
- // Audit
1404
- api.auditQuery({ toolName: 'exec', limit: 10 });
1405
- api.auditQuery({ minScore: 3.0 }); // 高风险操作
1406
- api.auditStats();
1407
-
1408
- // Feedback
1409
- api.recordFeedback('user_explicit_approval', 's1');
1410
- api.getSatisfaction(); // 82 (0-100)
1411
- api.getSatisfaction('s1', 24); // 最近 24 小时
1412
- api.feedbackStats();
1413
-
1414
- // Profile
1415
- api.getProfile();
1416
- api.getProfile('s1');
1417
- api.getStatusReport();
1418
- api.getSessionOverview();
1419
-
1420
- // Session
1421
- api.endSession('s1');
1422
- ```
1423
-
1424
- **AgentOSAPI 完整方法清单(25 个)**:
1425
-
1426
- | 方法 | 说明 |
1427
- |------|------|
1428
- | `guardRegisterRule(rule)` | 注册单条 Schema 规则 |
1429
- | `guardRegisterRules(rules)` | 批量注册 Schema 规则 |
1430
- | `guardHasRule(toolName)` | 检查工具是否有规则 |
1431
- | `guardGetRules()` | 获取所有已注册规则 |
1432
- | `guardEvaluateRisk(tool, params)` | 评估风险评分 |
1433
- | `guardSetRiskThresholds(thresholds)` | 设置风险阈值 |
1434
- | `pipelineExecute(params)` | 执行前校验流水线 |
1435
- | `pipelineComplete(params)` | 执行后验证流水线 |
1436
- | `memoryInjectContext()` | 注入记忆上下文 |
1437
- | `memoryAddMessage(role, content)` | 添加工作记忆消息 |
1438
- | `memorySetTask(task)` | 设置当前任务 |
1439
- | `memoryCacheResult(tool, result)` | 缓存工具结果 |
1440
- | `memoryRecordEvent(type, content, tags, entities)` | 记录情景事件 |
1441
- | `memorySetPreference(key, value)` | 设置用户偏好 |
1442
- | `memoryGetPreference(key)` | 获取用户偏好 |
1443
- | `memoryLearnRule(rule, source)` | 学习规则 |
1444
- | `memoryDefineTerm(term, meaning)` | 定义术语 |
1445
- | `memorySetProjectContext(name, context)` | 设置项目上下文 |
1446
- | `auditQuery(filter)` | 查询审计日志 |
1447
- | `auditStats()` | 审计统计 |
1448
- | `recordFeedback(signal, sessionId)` | 记录反馈 |
1449
- | `getSatisfaction(sessionId?, hours?)` | 获取满意度 |
1450
- | `feedbackStats()` | 反馈统计 |
1451
- | `getProfile(sessionId?)` | 获取质量画像 |
1452
- | `getStatusReport()` | 获取状态报告 |
1453
- | `getSessionOverview()` | 获取 session 概况 |
1454
- | `endSession(sessionId)` | 结束 session |
1455
-
1456
- ---
1457
-
1458
- ### HTTP API 接口
1459
-
1460
- 基础 URL:`http://localhost:3300`(默认)
1461
-
1462
- #### Request/Response 通用格式
1463
-
1464
- - **Content-Type**:`application/json`
1465
- - **鉴权**:除 `/health` 外,`Authorization: Bearer <token>`
1466
- - **成功**:`200 OK`,JSON body
1467
- - **鉴权失败**:`401 Unauthorized`
1468
- - **参数错误**:`400 Bad Request`,`{"error":"..."}`
1469
- - **服务错误**:`500 Internal Server Error`
1470
-
1471
- #### 端点详情
1472
-
1473
- ##### `GET /health` 健康检查(免 Token)
1474
-
1475
- ```bash
1476
- curl http://localhost:3300/health
1477
- # {"ok":true,"uptime":12.3}
1478
- ```
1479
-
1480
- ##### `POST /pipeline/pre` 执行前校验
1481
-
1482
- ```bash
1483
- curl -X POST http://localhost:3300/pipeline/pre \
1484
- -H "Authorization: Bearer ***" \
1485
- -H "Content-Type: application/json" \
1486
- -d '{
1487
- "sessionId": "s1",
1488
- "agentId": "main",
1489
- "toolName": "exec",
1490
- "parameters": {"command": "npm test"},
1491
- "affectedFiles": []
1492
- }'
1493
- ```
1494
-
1495
- | 字段 | 类型 | 必填 | 说明 |
1496
- |------|------|------|------|
1497
- | `toolName` | string | ✅ | 工具名 |
1498
- | `sessionId` | string | ❌ | 默认 `"http_session"` |
1499
- | `agentId` | string | ❌ | 默认 `"http_agent"` |
1500
- | `parameters` | object | ❌ | 工具参数,默认 `{}` |
1501
- | `affectedFiles` | string[] | ❌ | 受影响的文件列表 |
1502
-
1503
- **返回**:
1504
-
1505
- ```json
1506
- {
1507
- "preExec": {
1508
- "schemaCheck": { "pass": true, "errors": [] },
1509
- "riskScore": { "score": 0.19, "action": "auto", "dimensions": {...} },
1510
- "paramQuality": { "score": 85, "observations": [] },
1511
- "contextUtilization": { "score": 70, "patterns": [] }
1512
- },
1513
- "snapshot": { "id": "...", "fileHashes": {...}, "gitHead": "...", "gitDirty": false },
1514
- "profile": { "overallScore": 85, ... }
1515
- }
1516
- ```
1517
-
1518
- ##### `POST /pipeline/post` — 执行后验证
1519
-
1520
- ```bash
1521
- curl -X POST http://localhost:3300/pipeline/post \
1522
- -H "Authorization: Bearer ***" \
1523
- -H "Content-Type: application/json" \
1524
- -d '{
1525
- "toolName": "exec",
1526
- "toolParameters": {"command": "npm test"},
1527
- "toolResult": "all passed",
1528
- "snapshot": {...},
1529
- "startTime": 1718123456000,
1530
- "endTime": 1718123457000,
1531
- "retryCount": 0,
1532
- "wasSelfCorrected": false,
1533
- "hadTimeout": false,
1534
- "userAccepted": true,
1535
- "userProvidedEdit": false,
1536
- "resultWasUsed": true
1537
- }'
1538
- ```
1539
-
1540
- | 字段 | 类型 | 必填 | 说明 |
1541
- |------|------|------|------|
1542
- | `toolName` | string | ✅ | 工具名 |
1543
- | `sessionId` | string | ❌ | session 标识 |
1544
- | `agentId` | string | ❌ | agent 标识 |
1545
- | `toolParameters` | object | ❌ | 执行时的参数 |
1546
- | `toolResult` | any | ❌ | 工具返回结果 |
1547
- | `snapshot` | object | ❌ | 从 `/pipeline/pre` 获取的 snapshot |
1548
- | `startTime` | number | ❌ | 执行开始时间戳 ms |
1549
- | `endTime` | number | ❌ | 执行结束时间戳 ms |
1550
- | `retryCount` | number | ❌ | 重试次数,默认 0 |
1551
- | `wasSelfCorrected` | boolean | ❌ | Agent 是否自我纠正 |
1552
- | `hadTimeout` | boolean | ❌ | 是否超时 |
1553
- | `userAccepted` | boolean | ❌ | 用户是否接受了结果 |
1554
- | `userProvidedEdit` | boolean | ❌ | 用户是否修改了结果 |
1555
- | `resultWasUsed` | boolean | ❌ | 用户是否使用了结果 |
1556
-
1557
- ##### `GET /pipeline/report` / `GET /pipeline/profile`
1558
-
1559
- ```bash
1560
- curl -H "Authorization: Bearer ***" http://localhost:3300/pipeline/report
1561
- # → {"report":"=== AgentOS Status Report ===\n..."}
1562
-
1563
- curl -H "Authorization: Bearer ***" http://localhost:3300/pipeline/profile
1564
- curl -H "Authorization: Bearer ***" "http://localhost:3300/pipeline/profile?sessionId=s1"
1565
- ```
1566
-
1567
- ##### `POST /guard/schema` / `GET /guard/schema`
1568
-
1569
- ```bash
1570
- # 注册规则
1571
- curl -X POST http://localhost:3300/guard/schema \
1572
- -H "Authorization: Bearer ***" \
1573
- -H "Content-Type: application/json" \
1574
- -d '{"tool":"delete_file","required":["path"],"forbidden":[]}'
1575
- # {"ok":true,"tool":"delete_file"}
1576
-
1577
- # 查看规则
1578
- curl -H "Authorization: Bearer ***" "http://localhost:3300/guard/schema?tool=delete_file"
1579
- ```
1580
-
1581
- ##### Memory 端点(4 个)
1582
-
1583
- ```bash
1584
- # 设置偏好
1585
- curl -X POST http://localhost:3300/memory/preference \
1586
- -H "Authorization: Bearer ***" -H "Content-Type: application/json" \
1587
- -d '{"key":"language","value":"zh-CN"}'
1588
-
1589
- # 添加事实
1590
- curl -X POST http://localhost:3300/memory/fact \
1591
- -H "Authorization: Bearer ***" -H "Content-Type: application/json" \
1592
- -d '{"fact":"用户在北京"}'
1593
-
1594
- # 学习规则
1595
- curl -X POST http://localhost:3300/memory/rule \
1596
- -H "Authorization: Bearer ***" -H "Content-Type: application/json" \
1597
- -d '{"rule":"提交前运行 npm test","source":"session_1"}'
1598
-
1599
- # 获取注入上下文
1600
- curl -H "Authorization: Bearer ***" http://localhost:3300/memory/context
1601
- ```
1602
-
1603
- ##### `GET /audit` — 审计查询
1604
-
1605
- ```bash
1606
- curl -H "Authorization: Bearer ***" "http://localhost:3300/audit?limit=10"
1607
- curl -H "Authorization: Bearer ***" "http://localhost:3300/audit?toolName=exec&status=FAIL"
1608
- ```
1609
-
1610
- | 查询参数 | 说明 |
1611
- |---------|------|
1612
- | `limit` | 返回条数(默认 20) |
1613
- | `toolName` | 按工具名过滤 |
1614
- | `status` | 按校验状态过滤:`PASS` / `WARN` / `FAIL` |
1615
-
1616
- ##### `POST /feedback` — 记录隐性反馈
1617
-
1618
- ```bash
1619
- curl -X POST http://localhost:3300/feedback \
1620
- -H "Authorization: Bearer ***" -H "Content-Type: application/json" \
1621
- -d '{"signal":"user_explicit_approval","sessionId":"s1"}'
1622
- ```
1623
-
1624
- **支持的 signal 值**:
1625
-
1626
- | Signal | 强度 | 说明 |
1627
- |--------|------|------|
1628
- | `user_explicit_approval` | +0.6 | 用户明确说"做得好" |
1629
- | `user_immediate_continue` | +0.3 | 用户立即继续对话 |
1630
- | `user_used_result` | +0.7 | 用户使用了 Agent 的结果 |
1631
- | `user_shared_output` | +0.8 | 用户分享了 Agent 输出 |
1632
- | `user_modified_output` | -0.5 | 用户修改了 Agent 输出 |
1633
- | `user_deleted_code` | -0.8 | 用户删除了 Agent 创建的代码 |
1634
- | `user_interrupted` | -0.6 | 用户打断了 Agent |
1635
- | `user_repeated_instruction` | -0.3 | 用户重复了相同指令 |
1636
-
1637
- ##### `POST /session/end` — 结束 Session
1638
-
1639
- ```bash
1640
- curl -X POST http://localhost:3300/session/end \
1641
- -H "Authorization: Bearer ***" -H "Content-Type: application/json" \
1642
- -d '{"sessionId":"s1"}'
1643
- # → {"ok":true}
1644
- ```
1645
-
1646
- ---
1647
-
1648
- ### 中间件 / 插件接口
1649
-
1650
- #### `wrapAgent` — 一行接入中间件
1651
-
1652
- ```typescript
1653
- import { wrapAgent } from 'sentinel-agentos';
1654
-
1655
- const sentinel = wrapAgent({ workspaceRoot: process.cwd() });
1656
-
1657
- // 每个工具调用前后调用
1658
- const { allowed, reason } = sentinel.preCheck('exec', { command: 'rm -rf /' });
1659
- // { allowed: false, reason: 'Risk 9.18 → DENY' }
1660
-
1661
- const { allowed } = sentinel.preCheck('exec', { command: 'npm test' });
1662
- // { allowed: true }
1663
-
1664
- // 执行后验证
1665
- sentinel.postCheck('exec', { command: 'npm test' }, 'all passed');
1666
- ```
1667
-
1668
- **`wrapAgent` 参数**:
1669
-
1670
- | 参数 | 类型 | 默认值 | 说明 |
1671
- |------|------|--------|------|
1672
- | `workspaceRoot` | string | `process.cwd()` | 工作区根目录 |
1673
- | `maxWorkingTokens` | number | `50000` | 工作记忆 token 上限 |
1674
- | `preRegisteredRules` | boolean | `false` | 是否使用内置默认规则 |
1675
-
1676
- #### `sentinelPlugin` OpenClaw 插件
1677
-
1678
- ```typescript
1679
- import { sentinelPlugin } from 'sentinel-agentos';
1680
-
1681
- const plugin = sentinelPlugin({
1682
- workspaceRoot: process.cwd(),
1683
- preRegisteredRules: true,
1684
- });
1685
- // → onBeforeTool → Schema + Risk 校验
1686
- // onAfterTool Verify + Audit 记录
1687
- ```
1688
-
1689
- ---
1690
-
1691
- ### Sandbox 沙箱接口
1692
-
1693
- ```typescript
1694
- import { SandboxExecutor } from 'sentinel-agentos';
1695
-
1696
- const sandbox = new SandboxExecutor({
1697
- mode: 'sandbox', // 'direct' | 'sandbox' | 'dry-run'
1698
- workspaceRoot: process.cwd(),
1699
- timeoutMs: 30000, // 命令超时 30s
1700
- networkAccess: 'whitelist', // 'none' | 'localhost' | 'whitelist'
1701
- networkWhitelist: ['api.github.com', 'registry.npmjs.org'],
1702
- writablePaths: ['src/', 'tests/', 'dist/'],
1703
- readonlyPaths: ['node_modules/', '.git/'],
1704
- allowedTools: ['read_file', 'write_file', 'edit', 'exec'],
1705
- forbiddenTools: ['rm', 'unlink', 'delete_file'],
1706
- });
1707
-
1708
- // 预检
1709
- const check = sandbox.validate('exec', { command: 'curl evil.com' });
1710
- // → { success: false, sandboxRejectReason: 'Network not in whitelist' }
1711
-
1712
- // 执行
1713
- const result = await sandbox.execute('exec', { command: 'npm test' });
1714
- // → { success: true, result: {...} }
1715
- ```
1716
-
1717
- **`SandboxExecutor` 构造参数**:
1718
-
1719
- | 参数 | 类型 | 默认值 | 说明 |
1720
- |------|------|--------|------|
1721
- | `mode` | `'direct' | 'sandbox' | 'dry-run'` | `'sandbox'` | 执行模式 |
1722
- | `workspaceRoot` | string | `process.cwd()` | 工作区根目录 |
1723
- | `timeoutMs` | number | `30000` | 命令超时毫秒 |
1724
- | `networkAccess` | `'none' | 'localhost' | 'whitelist'` | `'localhost'` | 网络策略 |
1725
- | `networkWhitelist` | string[] | `[]` | 网络白名单域名 |
1726
- | `writablePaths` | string[] | `[]` | 可写路径 |
1727
- | `readonlyPaths` | string[] | `[]` | 只读路径 |
1728
- | `allowedTools` | string[] | `[]` | 允许的工具 |
1729
- | `forbiddenTools` | string[] | `[]` | 禁止的工具 |
1730
-
1731
- **执行模式说明**:
1732
-
1733
- | 模式 | 说明 |
1734
- |------|------|
1735
- | `direct` | 直接执行,无限制 |
1736
- | `sandbox` | 沙箱模式,受限的文件系统和网络访问 |
1737
- | `dry-run` | 试运行,不实际执行,只校验权限 |
1738
-
1739
- ---
1740
-
1741
- ## 📂 源码结构 · Source Layout
1742
-
1743
- ```
1744
- src/
1745
- ├── index.ts # 导出入口 · Exports (30+)
1746
- ├── core.ts # Sentinel AgentOS 主循环 · Main loop
1747
- ├── api.ts # SDK 协议层 · API layer (25+ methods)
1748
- ├── types/index.ts # 完整类型定义 · Type definitions
1749
- ├── guard/
1750
- │ ├── schema-gate.ts # Schema 校验 · Validation (12 checks)
1751
- │ ├── risk-gate.ts # 风险评分 · Risk scoring
1752
- │ ├── snapshot-verify.ts # 快照 + 验证 + 回滚 · Snapshot + Verify + Rollback
1753
- │ ├── audit-log.ts # 审计日志 · Audit
1754
- │ └── sandbox.ts # 沙箱执行器 · Sandbox executor
1755
- ├── memory/
1756
- │ ├── working.ts # 工作记忆 · Working
1757
- │ ├── episodic.ts # 情景记忆 · Episodic
1758
- │ └── semantic.ts # 语义记忆 · Semantic
1759
- └── evaluator/
1760
- ├── exec-evaluator.ts # 三阶段评估器 · 3-phase evaluator
1761
- ├── feedback.ts # 隐性反馈引擎 · Implicit feedback
1762
- └── profiler.ts # Agent 质量画像 · Quality profiler
1763
- ```
1764
-
1765
- ---
1766
-
1767
- ## 📄 License
1768
-
1769
- MIT
1
+ # Sentinel AgentOS — AI Agent 操作系统 · AI Agent Operating System
2
+
3
+ > **确定性 Guard 层 + 分层记忆 + 自动评估,让任何 Agent 变得可靠、可审计、可改进。**
4
+ > *Deterministic Guard Layer + Layered Memory + Automated Evaluation — making any Agent reliable, auditable, and self-improving.*
5
+
6
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.8-blue)](https://www.typescriptlang.org/)
7
+ [![Tests](https://img.shields.io/badge/tests-99%2F99-brightgreen)](https://github.com/jishuanjimingtian/sentinel-agentos/actions)
8
+ [![License](https://img.shields.io/badge/license-MIT-green)](./LICENSE)
9
+
10
+ ---
11
+
12
+ ## 🤔 为什么需要 Sentinel AgentOS · Why Sentinel AgentOS
13
+
14
+ AI Agent 面临五大核心问题,现有框架都没能真正解决。
15
+ *AI Agents face five critical problems that no existing framework truly solves.*
16
+
17
+ | 痛点 · Pain | 现状 · Status Quo | Sentinel AgentOS 方案 · Solution |
18
+ |------|------|-------------|
19
+ | 🔴 **幻觉导致错误操作** · *Hallucinated operations* | Prompt 里说"不要删文件"——这是愿望,不是约束 · *"Please don't delete files" — that's a wish, not a constraint* | Guard 层确定性校验,不依赖 LLM 判断 · *Deterministic Guard checks, zero LLM dependency* |
20
+ | 🔴 **越权/危险操作** · *Over-privileged ops* | 无分级控制,要么全禁要么全放 · *All-or-nothing access control* | Risk Gate 四维数学公式,0-100 自动分级 · *4-dimensional risk formula with auto-thresholding* |
21
+ | 🔴 **记不住、记不对** · *Poor memory* | 把对话扔进向量库——只有检索没有理解 · *Dump conversation into vector DB — retrieval, not understanding* | 三层记忆,像人脑一样评级、压缩、遗忘 · *3-layer memory: rate, compress, forget like a brain* |
22
+ | 🔴 **出事查不到原因** · *No audit trail* | Agent 做了什么、为什么做——全不可追溯 · *What the agent did and why — completely untraceable* | 每次操作前后 diff,JSONL 不可篡改审计 · *Pre/post diff per operation, immutable JSONL audit* |
23
+ | 🔴 **不知道 Agent 好不好** · *No quality measurement* | 最多有个 success rate 计数器 · *At best, a success-rate counter* | 三阶段评估 + 隐性反馈 + 质量画像 · *3-phase evaluation + implicit feedback + quality profile* |
24
+
25
+ ---
26
+
27
+ ## 🏗️ 架构设计 · Architecture
28
+
29
+ ```
30
+ ┌─────────────────────────────────────────────────────────────────┐
31
+ │ Sentinel AgentOS 架构 │
32
+ │ │
33
+ │ 任意 Agent 框架 · Any Agent Framework │
34
+ │ (OpenClaw / LangChain / CrewAI / 自研 · Custom) │
35
+ │ │ │
36
+ │ ▼ │
37
+ │ ┌───────────────────────────────────────────────────────────┐ │
38
+ │ │ Sentinel AgentOS 内核 · Kernel │ │
39
+ │ │ │ │
40
+ │ │ ┌─────────┐ ┌──────────┐ ┌────────────┐ │ │
41
+ │ │ │ Guard │ │ Memory │ │ Evaluator │ │ │
42
+ │ │ │ 守卫层 │ │ 记忆层 │ │ 评估层 │ │ │
43
+ │ │ ├─────────┤ ├──────────┤ ├────────────┤ │ │
44
+ │ │ │ Schema │ │ Working │ │ Pre-exec │ │ │
45
+ │ │ │ Gate │ │ 工作记忆 │ │ 执行前评估 │ │ │
46
+ │ │ │ ↓ │ │ ↓ │ │ ↓ │ │ │
47
+ │ │ │ Risk │ │ Episodic │ │ Runtime │ │ │
48
+ │ │ │ Gate │ │ 情景记忆 │ │ 执行中评估 │ │ │
49
+ │ │ │ ↓ │ │ ↓ │ │ ↓ │ │ │
50
+ │ │ │Snapshot │ │ Semantic │ │ Post-exec │ │ │
51
+ │ │ │ Gate │ │ 语义记忆 │ │ 执行后评估 │ │ │
52
+ │ │ │ ↓ │ └──────────┘ │ ↓ │ │ │
53
+ │ │ │ Verify │ │ Feedback │ │ │
54
+ │ │ │ Gate │ │ 反馈引擎 │ │ │
55
+ │ │ │ ↓ │ │ ↓ │ │ │
56
+ │ │ │ Audit │ │ Profiler │ │ │
57
+ │ │ │ Log │ │ 质量画像 │ │ │
58
+ │ │ └─────────┘ └────────────┘ │ │
59
+ │ │ │ │
60
+ │ │ ┌─────────────────────────────────────────────────────┐ │ │
61
+ │ │ │ Sandbox 沙箱 (direct/sandbox/dry-run) │ │ │
62
+ │ │ └─────────────────────────────────────────────────────┘ │ │
63
+ │ └───────────────────────────────────────────────────────────┘ │
64
+ │ │ │
65
+ │ ┌───────────────┴───────────────┐ │
66
+ │ ▼ ▼ │
67
+ │ 安全执行 · Safe Execution 可靠记忆 · Reliable Memory │
68
+ │ 全程审计 · Full Audit 持续改进 · Continuous Improve│
69
+ └─────────────────────────────────────────────────────────────────┘
70
+ ```
71
+
72
+ ### 设计哲学 · Design Philosophy
73
+
74
+ | 原则 · Principle | 含义 · Meaning | 反例 · Counter-example |
75
+ |------|------|------|
76
+ | **确定性优先** · *Determinism first* | 能不用 LLM 就不用,用确定性代码 · *Use deterministic code whenever possible* | 用 LLM 做安全判断 · *Using LLM for security* |
77
+ | **可审计优先** · *Auditability first* | 所有操作可追溯、可回滚、可解释 · *Every operation traceable, rollbackable, explainable* | Agent 操作后无日志 · *No log after agent operations* |
78
+ | **渐进增强** · *Progressive enhancement* | 框架无关,可增量接入,不要求替换现有架构 · *Framework-agnostic, incremental adoption* | LangChain 的强绑定 · *Hard vendor lock-in* |
79
+
80
+ ### 不是 Agent,是 Agent 的操作系统 · *Not an Agent — an OS for Agents*
81
+
82
+ | 类比 · Analogy | 对应 · Implementation |
83
+ |------|------|
84
+ | 应用程序 · Applications | 任意 Agent 框架 · Any Agent Framework |
85
+ | 操作系统 · Operating System | Sentinel AgentOS |
86
+ | 内核 · Kernel | Schema Gate + Risk Gate(确定性代码,零 LLM) |
87
+ | 文件系统 · File System | 分层 Memory Store |
88
+ | 日志系统 · Logging | Audit Log(不可篡改,支持回滚 · *immutable, supports rollback*) |
89
+ | 性能监控 · Performance Monitor | Evaluator 三阶段评估 · *3-phase evaluation* |
90
+
91
+ ---
92
+
93
+ ## ✨ 功能介绍 · Features
94
+
95
+ ### 🛡️ Guard 守卫层(6 个组件,零 LLM 依赖 · *6 components, zero LLM*)
96
+
97
+ #### Schema Gate — 参数格式校验 · Parameter Validation
98
+
99
+ | 校验项 · Check | 说明 · Description | 示例 · Example |
100
+ |--------|------|------|
101
+ | 必填 · required | 字段必须存在 · *Field must exist* | `delete_file` 必须提供 `path` |
102
+ | 类型 · types | string/number/boolean/object/array | `path` 必须是 string |
103
+ | 允许值 · allowedValues | 枚举约束 · *Enum constraint* | `mode` 只能是 `read`/`write`/`append` |
104
+ | 数值范围 · min/max | 数字范围 · *Numeric range* | `max_tokens` 1-100000 |
105
+ | 长度范围 · — | 字符串/数组长度 · *String/array length* | `query` 至少 3 字符 |
106
+ | 正则 · patterns | 格式校验 · *Pattern match* | `email` 符合邮箱格式 |
107
+ | 路径约束 · pathScope | 限制在 workspace 内 · *Workspace boundary* | 禁止写系统目录 · *No system dir writes* |
108
+ | 路径黑白名单 · pathAllow/Deny | 允许/禁止的文件模式 · *File pattern allow/block* | 禁止 `.env`, `*.key`, `*.pem` |
109
+ | 参数依赖 · dependsOn | 条件必填 · *Conditional required* | `auto_merge=true` → `base_branch` 必填 |
110
+ | 参数互斥 · mutuallyExclusive | 互斥参数 · *Mutually exclusive* | `content` 和 `file_path` 不同时存在 |
111
+ | 参数大小 · maxSize | 内容字节上限 · *Max content bytes* | `content` ≤ 1MB |
112
+ | 敏感标记 · secrets | 日志中脱敏 · *Redact in logs* | |
113
+
114
+ #### Risk Gate — 风险分级 · Risk Scoring
115
+
116
+ 四维数学公式 + 12 条危险正则,零 LLM · *4-dimensional formula + regex patterns:*
117
+
118
+ ```
119
+ RiskScore = Impact × (1 - Reversibility) × Sensitivity × (1 + ErrorRate)
120
+ ```
121
+
122
+ | 分数区间 · Score | 动作 · Action |
123
+ |----------|------|
124
+ | ≤ 0.5 | 🟢 自动放行 · *Auto-approve* |
125
+ | ≤ 1.0 | 🔵 执行后通知 · *Notify after execution* |
126
+ | ≤ 3.0 | 🟡 暂停等待确认 · *Pause for confirmation* |
127
+ | > 8.0 | 🔴 直接拒绝 · *Deny* |
128
+
129
+ **安全边界 · Security Limitations**
130
+
131
+ 基于命令字符串的正则匹配能覆盖 ~80% 的直接危险操作(`rm -rf /`、`git push --force main`、`DROP TABLE` 等),但无法检测"看起来正常但实际危险"的操作组合(如 `rm -rf ./node_modules`、`git push --force feature-branch`)。这是基于字符串匹配的本质局限。
132
+
133
+ 兜底措施:
134
+ - **Verify Gate**事后校验文件是否真的被修改/删除
135
+ - **Rollback** — git checkout 自动回滚
136
+ - **Confirm 模式** 风险分 3.0 时暂停等待用户确认
137
+ - **Audit Log** — 完整记录每次操作,事后可追溯
138
+
139
+ #### Snapshot Gate — 执行前快照 · Pre-exec Snapshot
140
+
141
+ 只记录文件 SHA-256 hash + git 状态,不做全量备份,极快。
142
+ *Records only SHA-256 hashes + git state, no full backup — extremely fast.*
143
+
144
+ #### Verify Gate 执行后校验 · Post-exec Verification
145
+
146
+ **核心 2 项(已实现)+ 6 项可扩展** · *2 core checks (implemented) + 6 extensible:*
147
+
148
+ | 校验项 · Check | 说明 · Description | 状态 |
149
+ |--------|------|:--:|
150
+ | 文件存在 · File existence | `fs.existsSync()` 验证声称创建的文件 | ✅ |
151
+ | 文件变更 · File changed | 对比 Snapshot hash,确认真的改了 | |
152
+ | 返回值非空 · Non-empty result | 不应为空但为空 WARN | ✅ |
153
+ | Lint 验证 | ESLint(待接入) | 🔧 |
154
+ | TypeCheck | `tsc --noEmit`(待接入) | 🔧 |
155
+ | 格式校验 | JSON.parse / 结构化验证(待接入) | 🔧 |
156
+ | npm 发布验证 | `npm view` 确认版本存在(待接入) | 🔧 |
157
+ | git push 验证 | `git ls-remote` HEAD 对比(待接入) | 🔧 |
158
+
159
+ > 文件存在 + hash 对比已能检测 Agent 最常见的幻觉(声称写了但没写)。其余校验项保留接口,按需接入。
160
+
161
+ #### Audit Log 不可篡改审计 · Immutable Audit
162
+
163
+ 追加写入 JSONL 文件,每次操作前后完整记录(Schema + Risk + Snapshot + Verify + Diff)。支持按 session/tool/status 查询。
164
+ *Append-only JSONL with full pre/post state per operation. Query by session/tool/status.*
165
+
166
+ #### Rollback — 回滚
167
+
168
+ 基于 Snapshot + Git 自动回滚。Verify Gate FAIL + 高风险 → 自动触发。
169
+ *Git-based auto-rollback. Triggered on Verify FAIL + high risk.*
170
+
171
+ #### Sandbox Executor — 沙箱执行器
172
+
173
+ 三种模式 · *Three modes:* **direct** · **sandbox** · **dry-run**
174
+
175
+ - 网络策略 · *Network policy:* none / localhost / whitelist
176
+ - 文件系统策略 · *Filesystem policy:* writablePaths / readonlyPaths
177
+ - 内置危险命令检测(`rm -rf /`、`sudo`、fork bomb、`curl\|bash` 等)· *Built-in dangerous command detection*
178
+
179
+ ---
180
+
181
+ ### 🧠 Memory 记忆层(3 层,人脑模型 · *3-layer brain model*)
182
+
183
+ ```
184
+ Working Memory → Episodic Memory Semantic Memory
185
+ 工作记忆 → 情景记忆 → 语义记忆
186
+ ──────────────────────────────────────────────────────
187
+ 当前会话 → 跨会话事件线 → 永久知识
188
+ Current session → Cross-session → Permanent knowledge
189
+ 1 session 存活 → 数周-数月 → 永久
190
+ < 50KB → < 500KB → < 100KB
191
+ ```
192
+
193
+ | · Layer | 用途 · Purpose | 关键能力 · Key Ability |
194
+ |----|------|---------|
195
+ | **Working** | 当前会话实时上下文 · *Live session context* | 消息/任务/工具缓存/文件/token 预算 · *Messages, tasks, tool cache, open files, token budget* |
196
+ | **Episodic** | 跨会话事件时间线 · *Cross-session timeline* | 9 种事件类型、自动重要性评分、渐进压缩(full→summary→one-liner→forgotten) |
197
+ | **Semantic** | 提炼后的永久知识 · *Distilled permanent knowledge* | 用户偏好/事实、项目上下文、学习规则(含置信度)、术语表 |
198
+
199
+ #### Session 启动上下文注入 · Startup Context Injection
200
+
201
+ 新 session 自动从 Semantic + Episodic 注入最相关上下文:
202
+ *Auto-injects relevant context at every new session:*
203
+
204
+ ```
205
+ [Sentinel AgentOS Memory Context]
206
+ 你正在帮助用户"老板"处理项目"coderev"。
207
+ You are helping user "Boss" with project "coderev".
208
+ 上次会话讨论了 Guard 层设计。
209
+ Last session discussed Guard layer design.
210
+ 关键提醒 · Key reminders:
211
+ - 老板偏好直接、不说废话 · Boss prefers direct, no fluff
212
+ - 发布 npm 前必须更新 CHANGELOG.md · Update CHANGELOG before npm publish
213
+ ```
214
+
215
+ ---
216
+
217
+ ### 📊 Evaluator 评估层(三阶段 + 隐性反馈 · *3-phase + Implicit Feedback*)
218
+
219
+ #### 三阶段评估 · Three-Phase Evaluation
220
+
221
+ ```
222
+ Pre-exec 评估 → Runtime 评估 → Post-exec 评估
223
+ 执行前评估 执行中评估 执行后评估
224
+ ↓ ↓ ↓
225
+ 参数质量 重试次数 验证结果
226
+ 风险分数 自适应评分 用户接受度
227
+ 上下文利用 工具选择准确性 结果利用度
228
+ ```
229
+
230
+ #### 隐性反馈捕获 · Implicit Feedback(核心差异点 · *Key differentiator*)
231
+
232
+ 不靠"👍👎",靠行为推断满意度。*No thumbs up/down — infer satisfaction from behavior.*
233
+
234
+ | 用户行为 · User Behavior | 隐性信号 · Signal | 强度 · Strength |
235
+ |----------|---------|------|
236
+ | 用户删除了 Agent 创建的代码 · *User deleted agent's code* | `user_deleted_code` | -0.8 |
237
+ | 用户打断了 Agent · *User interrupted agent* | `user_interrupted` | -0.6 |
238
+ | 用户修改了 Agent 输出 · *User modified agent output* | `user_modified_output` | -0.5 |
239
+ | 用户重复了相同指令 · *User repeated same command* | `user_repeated_instruction` | -0.15 |
240
+ | 用户立即继续对话 · *User immediately continued* | `user_immediate_continue` | +0.3 |
241
+ | 用户说"做得好" · *User said "good job"* | `user_explicit_approval` | +0.6 |
242
+ | 用户使用了 Agent 的结果 · *User used agent's result* | `user_used_result` | +0.7 |
243
+ | 用户分享了 Agent 输出 · *User shared agent output* | `user_shared_output` | +0.8 |
244
+
245
+ #### Agent 质量画像 · Quality Profile
246
+
247
+ ```
248
+ === Sentinel AgentOS Status Report ===
249
+
250
+ Quality Score: 85/100 📈
251
+ Total Operations: 156 (12 in last 24h)
252
+
253
+ --- Breakdown ---
254
+ Pre-Exec: 92/100
255
+ Runtime: 88/100
256
+ Post-Exec: 85/100
257
+ Satisfaction: 82/100
258
+
259
+ --- Audit ---
260
+ Total: 156 | Failures: 2 | High-Risk: 3
261
+
262
+ --- ⚠️ Warnings ---
263
+ - 2 verify failures in last 24h — review session #3
264
+ 24小时内2次校验失败——检查session #3
265
+
266
+ --- ✅ Strengths 强项 ---
267
+ - Excellent execution reliability · 优秀的执行可靠性
268
+ - Strong positive user feedback · 强烈正向用户反馈
269
+ ```
270
+
271
+ ---
272
+
273
+ ## 📦 安装 · Installation
274
+
275
+ ### 全量安装(包含 HTTP API + Dashboard)
276
+
277
+ ```bash
278
+ npm install sentinel-agentos
279
+ ```
280
+
281
+ ### 轻量安装(仅 Guard + Memory + Evaluator,零额外依赖)
282
+
283
+ 如果只需要核心能力,直接引用 `sentinel-light.js`:
284
+
285
+ ```javascript
286
+ const { AgentOS } = require('sentinel-agentos/sentinel-light');
287
+ ```
288
+
289
+ > `sentinel-light.js` 不依赖 express/puppeteer/ws/cors,安装体积大幅减小。
290
+ > 未来将拆分为 `sentinel-agentos-core` + `sentinel-agentos-server` 两个独立包。
291
+
292
+ 从源码开发:
293
+
294
+ ```bash
295
+ git clone git@github.com:jishuanjimingtian/sentinel-agentos.git
296
+ cd sentinel-agentos
297
+ npm install
298
+ npm test # 99 tests, all passing · 99个测试全部通过
299
+ npm run build # 编译到 dist/
300
+ ```
301
+
302
+ ---
303
+
304
+ ## 🚀 使用说明 · Usage
305
+
306
+ ### 三种接入方式 · Three Integration Modes
307
+
308
+ Sentinel AgentOS 支持三种接入方式,从轻到重按需选择。
309
+
310
+ | 方式 | 适用场景 | 代码量 | 说明 |
311
+ |------|---------|--------|------|
312
+ | **CLI** | 快速测试 / CI/CD | 1 行命令 | 直接命令行检验工具调用 |
313
+ | **SDK** | 嵌入 Agent 框架 | 5 行代码 | `import { AgentOS }` 在进程内调用 |
314
+ | **HTTP API** | 跨语言 / 远程服务 | HTTP 请求 | 独立 HTTP 服务,任何语言都能调 |
315
+
316
+ ---
317
+
318
+ ### 方式一:CLI(命令行)
319
+
320
+ ```bash
321
+ # 安装
322
+ npm install -g sentinel-agentos
323
+
324
+ # 校验参数
325
+ sentinel-agentos validate exec command="rm -rf /"
326
+ sentinel-agentos validate write_file path=src/main.ts content="console.log(1)"
327
+
328
+ # 风险评分
329
+ sentinel-agentos risk exec command="sudo reboot"
330
+ sentinel-agentos risk exec command="npm test"
331
+
332
+ # 查看审计日志
333
+ sentinel-agentos audit --limit 10
334
+
335
+ # 查看状态报告
336
+ sentinel-agentos status
337
+
338
+ # 启动 HTTP 服务
339
+ sentinel-agentos server --port 3300 --token ***
340
+
341
+ # 查看帮助
342
+ sentinel-agentos help
343
+ ```
344
+
345
+ **支持的命令**:`validate` / `risk` / `audit` / `stats` / `profile` / `status` / `server` / `memory` / `help`
346
+
347
+ ---
348
+
349
+ ### 方式二:SDK(代码嵌入)
350
+
351
+ #### 2.1 基础用法 · Basic
352
+
353
+ ```typescript
354
+ import { AgentOS } from 'sentinel-agentos';
355
+
356
+ const aos = new AgentOS({
357
+ workspaceRoot: process.cwd(),
358
+ maxWorkingTokens: 50000,
359
+ maxEpisodicSizeKb: 500,
360
+ });
361
+
362
+ // 设置记忆 · Configure memory
363
+ aos.memory.semantic.setPreference('language', 'zh-CN');
364
+ aos.memory.semantic.addFact('用户在北京,偏好简洁沟通');
365
+ aos.memory.semantic.learnRule('提交前运行 npm test', 'session_1');
366
+
367
+ // 设置 Schema 规则 · Register schema rules
368
+ aos.guard.schema.registerRule({
369
+ tool: 'write_file',
370
+ required: ['path', 'content'],
371
+ types: { path: 'string', content: 'string' },
372
+ pathDeny: { path: ['.env', '*.key', '*.pem', '.git/**'] },
373
+ maxSize: { content: 1048576 },
374
+ secrets: ['content'],
375
+ });
376
+
377
+ // Pre-exec:校验 + 快照 · Validate + snapshot
378
+ const { preExec, snapshot } = aos.executePipeline({
379
+ sessionId: 'session_1',
380
+ agentId: 'main_agent',
381
+ toolName: 'write_file',
382
+ parameters: { path: 'src/main.ts', content: 'console.log("hello");' },
383
+ affectedFiles: ['src/main.ts'],
384
+ });
385
+
386
+ console.log(`Risk: ${preExec.riskScore.score} → ${preExec.riskScore.action}`);
387
+ // → Risk: 0.19 → auto
388
+
389
+ // Post-exec:验证 + 审计 · Verify + audit
390
+ const result = aos.completeExecution({
391
+ sessionId: 'session_1', agentId: 'main_agent',
392
+ toolName: 'write_file',
393
+ toolParameters: { path: 'src/main.ts', content: 'console.log("hello");' },
394
+ toolResult: 'file written',
395
+ snapshot,
396
+ startTime: Date.now() - 500, endTime: Date.now(),
397
+ retryCount: 0, wasSelfCorrected: false, hadTimeout: false,
398
+ userAccepted: true, userProvidedEdit: false, resultWasUsed: true,
399
+ });
400
+
401
+ console.log(`Post-exec: ${result.postExec.outcomeScore}`);
402
+ console.log(`Audit: ${result.auditEntry.id}`);
403
+
404
+ // 记录反馈 · Record feedback
405
+ aos.recordFeedback('user_immediate_continue', 'session_1');
406
+
407
+ // 查看报告 · Status report
408
+ console.log(aos.statusReport());
409
+ ```
410
+
411
+ ### 接入现有 Agent 框架 · Integrate with any Agent framework
412
+
413
+ ```typescript
414
+ import { AgentOS } from 'sentinel-agentos';
415
+
416
+ const aos = new AgentOS({ workspaceRoot: process.cwd() });
417
+
418
+ async function safeToolCall(toolName: string, params: Record<string, unknown>) {
419
+ const sessionId = getCurrentSessionId();
420
+
421
+ // 1. 校验 + 风险 + 快照 · Validate + Risk + Snapshot
422
+ const { preExec, snapshot } = aos.executePipeline({
423
+ sessionId, agentId: 'my_agent', toolName, parameters: params,
424
+ });
425
+
426
+ if (preExec.riskScore.action === 'deny') {
427
+ throw new Error(`Rejected: risk ${preExec.riskScore.score}`);
428
+ }
429
+
430
+ if (preExec.riskScore.action === 'confirm') {
431
+ const ok = await askUser(`Risk ${preExec.riskScore.score}. Proceed?`);
432
+ if (!ok) return;
433
+ }
434
+
435
+ const t0 = Date.now();
436
+ const result = await yourActualCall(toolName, params);
437
+
438
+ // 2. 验证 + 审计 · Verify + Audit
439
+ return aos.completeExecution({
440
+ sessionId, agentId: 'my_agent', toolName,
441
+ toolParameters: params, toolResult: result, snapshot,
442
+ startTime: t0, endTime: Date.now(),
443
+ retryCount: 0, wasSelfCorrected: false, hadTimeout: false,
444
+ userAccepted: true, userProvidedEdit: false, resultWasUsed: false,
445
+ });
446
+ }
447
+ ```
448
+
449
+ ### 沙箱 · Sandbox
450
+
451
+ ```typescript
452
+ import { SandboxExecutor } from 'sentinel-agentos';
453
+
454
+ const sandbox = new SandboxExecutor({
455
+ mode: 'sandbox',
456
+ workspaceRoot: process.cwd(),
457
+ timeoutMs: 30000,
458
+ networkAccess: 'whitelist',
459
+ networkWhitelist: ['api.github.com', 'registry.npmjs.org'],
460
+ writablePaths: ['src/', 'tests/', 'dist/'],
461
+ allowedTools: ['read_file', 'write_file', 'edit', 'exec'],
462
+ forbiddenTools: ['rm', 'unlink'],
463
+ });
464
+
465
+ // Pre-flight · 预检
466
+ sandbox.validate('rm', { path: 'src/main.ts' });
467
+ // → { success: false, sandboxRejectReason: 'Tool "rm" is forbidden' }
468
+
469
+ // Execute · 执行
470
+ await sandbox.execute('exec', { command: 'npm test', cwd: process.cwd() });
471
+ ```
472
+
473
+ #### 2.2 中间件(一行接入) · Middleware (one-liner)
474
+
475
+ ```typescript
476
+ import { wrapAgent } from 'sentinel-agentos';
477
+
478
+ // 一行接入——包裹你的 Agent 工具调用
479
+ const sentinel = wrapAgent({ workspaceRoot: process.cwd() });
480
+
481
+ // 每次工具调用前后调用即可
482
+ const { allowed, reason } = sentinel.preCheck('exec', { command: 'rm -rf /' });
483
+ // { allowed: false, reason: 'Risk 9.18 → DENY' }
484
+ ```
485
+
486
+ #### 2.3 OpenClaw 插件
487
+
488
+ 如果你在用 OpenClaw Agent 框架,直接以插件形式集成:
489
+
490
+ ```typescript
491
+ import { sentinelPlugin } from 'sentinel-agentos';
492
+
493
+ // 注册为 OpenClaw 插件,自动 hook 所有工具调用
494
+ const plugin = sentinelPlugin({
495
+ workspaceRoot: process.cwd(),
496
+ preRegisteredRules: true,
497
+ });
498
+ // → onBeforeTool → 校验 + 风险评分
499
+ //onAfterTool → 验证 + 审计
500
+ ```
501
+
502
+ ---
503
+
504
+ ### 方式三:HTTP API(远程调用,跨语言通用)
505
+
506
+ Sentinel AgentOS 可启动为独立 HTTP 服务,任何语言(Python/Go/Rust/Java...)都能调用。
507
+
508
+ #### 3.1 启动服务
509
+
510
+ ```bash
511
+ # CLI 一行启动
512
+ npx sentinel-agentos server --port 3300 --token ***
513
+
514
+ # 或代码中启动
515
+ import { createServer } from 'sentinel-agentos';
516
+ createServer({ port: 3300, apiToken: '***' }).start();
517
+ ```
518
+
519
+ 启动后健康检查(免 token):
520
+ ```bash
521
+ curl http://localhost:3300/health
522
+ # {"ok":true,"uptime":12.3}
523
+ ```
524
+
525
+ #### 3.2 鉴权
526
+
527
+ `/health` 外所有端点需要 `Authorization: Bearer <token>` header。否则返回 `401`。
528
+
529
+ #### 3.3 API 端点参考 · API Reference
530
+
531
+ **基础端点:**
532
+
533
+ | 端点 | 方法 | 鉴权 | 说明 |
534
+ |------|:--:|:--:|------|
535
+ | `/health` | GET | | 服务健康检查 |
536
+ | `/pipeline/pre` | POST | | 执行前校验(Schema + Risk + Snapshot) |
537
+ | `/pipeline/post` | POST | | 执行后验证(Verify + Audit + Feedback) |
538
+ | `/pipeline/report` | GET | | 质量状态报告(文本) |
539
+ | `/pipeline/profile` | GET | | 质量画像(JSON) |
540
+
541
+ **Guard / Memory / Feedback / Audit 端点:**
542
+
543
+ | 端点 | 方法 | 说明 |
544
+ |------|:--:|------|
545
+ | `/guard/schema` | POST | 注册 Schema 校验规则 |
546
+ | `/memory/preference` | POST | 设置用户偏好 `{"key":"language","value":"zh-CN"}` |
547
+ | `/memory/fact` | POST | 添加事实 `{"fact":"用户在上海"}` |
548
+ | `/memory/context` | GET | 获取当前记忆上下文 |
549
+ | `/feedback` | POST | 记录隐性反馈 `{"signal":"user_explicit_approval"}` |
550
+ | `/audit` | GET | 查询审计日志(支持 `?limit=&sessionId=&toolName=&status=`) |
551
+
552
+ **反馈信号类型:**
553
+
554
+ | 信号 | 强度 | 说明 |
555
+ |------|------|------|
556
+ | `user_explicit_approval` | +0.6 | 用户明确说"做得好" |
557
+ | `user_immediate_continue` | +0.3 | 用户立即继续对话 |
558
+ | `user_used_result` | +0.7 | 用户使用了 Agent 的结果 |
559
+ | `user_shared_output` | +0.8 | 用户分享了 Agent 输出 |
560
+ | `user_modified_output` | -0.5 | 用户修改了 Agent 输出 |
561
+ | `user_deleted_code` | -0.8 | 用户删除了 Agent 创建的代码 |
562
+ | `user_interrupted` | -0.6 | 用户打断了 Agent |
563
+ | `user_repeated_instruction` | -0.3 | 用户重复了相同指令 |
564
+
565
+ #### 3.4 完整调用示例
566
+
567
+ ```bash
568
+ # 1. Pre-exec 校验 + 风险评分
569
+ curl -s -H "Authorization: Bearer $TOKEN" \
570
+ -X POST http://localhost:3300/pipeline/pre \
571
+ -H 'Content-Type: application/json' \
572
+ -d '{"toolName":"exec","parameters":{"command":"npm test"}}'
573
+ # → {"preExec":{"schemaCheck":{"pass":true},"riskScore":{"score":0.19,"action":"auto"}},"snapshot":{...}}
574
+
575
+ # 2. Post-exec — 验证 + 审计
576
+ # (传入 pre 返回的 snapshot)
577
+ curl -s -H "Authorization: Bearer $TOKEN" \
578
+ -X POST http://localhost:3300/pipeline/post \
579
+ -H 'Content-Type: application/json' \
580
+ -d '{"toolName":"exec","toolParameters":{"command":"npm test"},"toolResult":"all passed","snapshot":{...},"startTime":1718123456000,"endTime":1718123457000,"retryCount":0,"wasSelfCorrected":false,"hadTimeout":false,"userAccepted":true,"userProvidedEdit":false,"resultWasUsed":true}'
581
+
582
+ # 3. 查看报告
583
+ curl -s -H "Authorization: Bearer $TOKEN" http://localhost:3300/pipeline/report
584
+
585
+ # 4. 查询审计
586
+ curl -s -H "Authorization: Bearer $TOKEN" "http://localhost:3300/audit?limit=10&toolName=exec"
587
+
588
+ # 5. 记录反馈
589
+ curl -s -H "Authorization: Bearer $TOKEN" \
590
+ -X POST http://localhost:3300/feedback \
591
+ -H 'Content-Type: application/json' \
592
+ -d '{"signal":"user_immediate_continue","sessionId":"session_1"}'
593
+ ```
594
+
595
+ #### 3.5 跨语言(Python 示例)
596
+
597
+ ```python
598
+ import requests
599
+
600
+ BASE = "http://localhost:3300"
601
+ HEADERS = {"Authorization": "Bearer ***"}
602
+
603
+ # Pre-exec
604
+ resp = requests.post(f"{BASE}/pipeline/pre", json={
605
+ "toolName": "exec", "parameters": {"command": "npm test"}
606
+ }, headers=HEADERS)
607
+ data = resp.json()
608
+ print(f"Risk: {data['preExec']['riskScore']['score']} → {data['preExec']['riskScore']['action']}")
609
+
610
+ # Post-exec (pass snapshot from pre)
611
+ snapshot = data["snapshot"]
612
+ resp2 = requests.post(f"{BASE}/pipeline/post", json={
613
+ "toolName": "exec",
614
+ "toolParameters": {"command": "npm test"},
615
+ "toolResult": "all passed",
616
+ "snapshot": snapshot,
617
+ "startTime": 1718123456000, "endTime": 1718123457000,
618
+ "retryCount": 0, "wasSelfCorrected": False,
619
+ "hadTimeout": False, "userAccepted": True,
620
+ "userProvidedEdit": False, "resultWasUsed": True
621
+ }, headers=HEADERS)
622
+ print(f"Verify: {resp2.json()['postExec']['verifyPassed']}")
623
+
624
+ # Report
625
+ print(requests.get(f"{BASE}/pipeline/report", headers=HEADERS).text)
626
+ ```
627
+
628
+ ---
629
+
630
+ ---
631
+
632
+ ## 🔌 sentinel-guard Skill — OpenClaw 实际对接
633
+
634
+ > 这是 Sentinel AgentOS 接入 OpenClaw Agent 框架的**生产级 skill**。
635
+ > 提供一个统一入口 `sentinel.execute()`,自动走完 Guard → Execute → Verify + Audit + Memory + Evaluator 三层面。
636
+ > 使用前务必阅读 [sentinel-guard SKILL.md](../skills/sentinel-guard/SKILL.md)
637
+
638
+ ### 统一入口 vs 传统两段式
639
+
640
+ **传统方式(preCheck + postCheck 两次调用)**:
641
+
642
+ ```javascript
643
+ const guard = require('./sentinel-guard');
644
+ const check = guard.preCheck('exec', { command: '...' }); // 只做拦截
645
+ if (!check.passed) return ...;
646
+ // 执行...
647
+ guard.postCheck('exec', params, result); // 只做审计
648
+ ```
649
+
650
+ **统一入口(推荐)**:
651
+
652
+ ```javascript
653
+ const sentinel = require('./sentinel-guard');
654
+ const result = await sentinel.execute('exec', { command: 'npm test' }, () => exec('npm test'));
655
+
656
+ // result.allowed — Guard 是否放行
657
+ // result.result — 执行函数的返回值
658
+ // result.auditId — 审计 ID
659
+ // result.verify — Verify Gate 状态 (PASS/WARN/FAIL)
660
+ // result.profile当前质量评分 (0-100)
661
+ ```
662
+
663
+ ### 执行流程详解
664
+
665
+ ```
666
+ sentinel.execute(toolName, params, fn)
667
+
668
+ ├─ 第1层: 确定性命令/文件拦截 (<1μs,零 LLM)
669
+ │ ├─ 危险命令正则匹配 (rm -rf /, mkfs, dd if=, fork bomb...)
670
+ ├─ 警告命令正则匹配 (git push --force, npm publish, DROP TABLE...)
671
+ ├─ 敏感文件 glob 匹配 (.env, *.key, *.pem, .git/**...)
672
+ └─ 保护文件匹配 (package.json, MEMORY.md, AGENTS.md...)
673
+
674
+ ├─ 第2层: AgentOS Pipeline
675
+ │ ├─ Schema Gate — 参数格式校验 (required/types/pathDeny/maxSize/secrets)
676
+ │ ├─ Risk Gate — 四维公式评分 → auto/notify/confirm/deny
677
+ │ └─ Snapshot Gate 执行前文件 hash 快照
678
+
679
+ ├─ 第3层: 实际执行 fn()
680
+ │ └─ 异常捕获,失败也记录审计
681
+
682
+ ├─ 第4层: Verify + Audit + Evaluator
683
+ │ ├─ Verify Gate 确定性校验 (文件存在/变更 + 可扩展)
684
+ │ ├─ Audit Log JSONL 不可篡改审计
685
+ │ ├─ PreExecEvaluator 参数质量+上下文利用评分
686
+ │ ├─ RuntimeEvaluator 重试/超时/自纠正评分
687
+ │ ├─ PostExecEvaluator 验证通过/用户接受/结果利用率评分
688
+ │ └─ AgentProfiler 综合评分 0-100 + 趋势 + 亮点/警告
689
+
690
+ ├─ 第5层: Memory 同步
691
+ │ ├─ Working Memory — 消息+工具结果缓存
692
+ │ ├─ Episodic Memory — 事件记录
693
+ │ └─ Semantic Memory — (自动迁移时写入)
694
+
695
+ └─ 返回统一结果
696
+ ```
697
+
698
+ ### execute() 完整返回值
699
+
700
+ | 字段 | 类型 | 说明 |
701
+ |------|------|------|
702
+ | `allowed` | boolean | 是否通过 Guard 层 |
703
+ | `blocked` | boolean | 是否被拦截 |
704
+ | `risk` | `'auto' | 'confirm' | 'deny'` | 风险等级 |
705
+ | `reason` | string? | 拦截/警告原因(blocked=true 时) |
706
+ | `needsConfirmation` | boolean? | 是否需要用户确认 |
707
+ | `result` | any | 执行函数的返回值 |
708
+ | `error` | string? | 执行异常信息 |
709
+ | `auditId` | string | 审计条目 ID(如 `op_5`) |
710
+ | `verify` | `'PASS' | 'WARN' | 'FAIL'` | Verify Gate 状态 |
711
+ | `profile` | number | 当前 Agent 质量评分 (0-100) |
712
+
713
+ **被拦截示例**:
714
+
715
+ ```json
716
+ {
717
+ "allowed": false,
718
+ "blocked": true,
719
+ "risk": "DENY",
720
+ "reason": "🚫 危险命令: rm -rf / 删除整个系统"
721
+ }
722
+ ```
723
+
724
+ **正常通过示例**:
725
+
726
+ ```json
727
+ {
728
+ "allowed": true,
729
+ "blocked": false,
730
+ "risk": "auto",
731
+ "result": "hello output",
732
+ "auditId": "op_5",
733
+ "verify": "PASS",
734
+ "profile": 85
735
+ }
736
+ ```
737
+
738
+ ### 自动迁移 MEMORY.md → Semantic Memory
739
+
740
+ 首次加载 sentinel-guard 时自动执行,仅一次:
741
+
742
+ 1. 解析 `MEMORY.md` 的 Markdown 结构(支持 bullet 列表和表格行)
743
+ 2. 提取用户事实 (👤 关于老板 / 🆔 关于我) → `semantic.addFact()`
744
+ 3. 提取工作方式规则 (🤖 我的工作方式) → `semantic.learnRule()`
745
+ 4. 提取项目上下文 (📦 coderev / agentos) → `semantic.setProjectContext()`
746
+ 5. 提取环境记录 (💻 环境记录) → `semantic.addFact()`
747
+ 6. 提取关键决策 (💡 关键决策记录) → `episodic.record('decision', ...)`
748
+ 7. 生成 `.sentinel-migrated` 标记文件防止重复
749
+
750
+ 迁移后原有 MEMORY.md 不受影响(只读不写),两套记忆并行:
751
+
752
+ | 记忆系统 | 用途 | 格式 |
753
+ |---------|------|------|
754
+ | `MEMORY.md` | 人类编辑,session 注入上下文 | Markdown |
755
+ | AgentOS Semantic Memory | 程序读写,自动学习 | 结构化 JSON (`.agentos/`) |
756
+
757
+ ### 规则配置 guard-rules.json
758
+
759
+ 所有 Guard 黑白名单可通过 `guard-rules.json` 直接编辑,无需改源码:
760
+
761
+ ```json
762
+ {
763
+ "dangerous": [
764
+ ["rm -rf /", "删除整个系统"],
765
+ ["sudo rm", "超级用户删除"],
766
+ ["mkfs", "格式化磁盘"]
767
+ ],
768
+ "warning": [
769
+ ["git push --force", "强制覆盖远程分支"],
770
+ ["npm publish\\b", "发布 npm 公共包"],
771
+ ["DROP (TABLE|DATABASE)", "删除数据库"]
772
+ ],
773
+ "sensitiveFiles": [
774
+ ".env", ".env.*", "*.key", "*.pem",
775
+ ".git/**", "**/credentials/**"
776
+ ],
777
+ "protectedFiles": [
778
+ "package.json", "MEMORY.md", "AGENTS.md", "SOUL.md"
779
+ ],
780
+ "schema": [
781
+ { "tool": "exec", "required": ["command"] },
782
+ {
783
+ "tool": "write",
784
+ "required": ["path", "content"],
785
+ "pathDeny": [".env", "*.key", ".git/**"],
786
+ "maxSize": { "content": 1048576 },
787
+ "secrets": ["content"]
788
+ }
789
+ ]
790
+ }
791
+ ```
792
+
793
+ | 配置项 | 类型 | 说明 |
794
+ |--------|------|------|
795
+ | `dangerous` | `[regex, desc][]` | 匹配到直接拒绝 |
796
+ | `warning` | `[regex, desc][]` | 匹配到需用户确认 |
797
+ | `sensitiveFiles` | `string[]` | glob 模式,禁止读写 |
798
+ | `protectedFiles` | `string[]` | 精确匹配,禁止删除 |
799
+ | `schema` | `SchemaRule[]` | AgentOS Schema Gate 规则 |
800
+
801
+ ### 完整 API 参考
802
+
803
+ ```javascript
804
+ const sentinel = require('./sentinel-guard');
805
+ ```
806
+
807
+ | 方法 | 类型 | 说明 |
808
+ |------|------|------|
809
+ | `execute(tool, params, fn, opts?)` | async | **统一入口**,走完三层 |
810
+ | `preCheck(tool, params)` | sync | [兼容] 仅确定性拦截 |
811
+ | `postCheck(tool, params, result)` | sync | [兼容] 仅审计记录 |
812
+ | `injectContext()` | sync → string | Session 启动时注入 Memory 上下文 |
813
+ | `endSession()` | sync | Session 结束:追加 daily log → 清空 Working → 同步 Episodic |
814
+ | `status()` | sync → string | AgentOS 状态报告 |
815
+ | `fullStatus()` | sync → object | 完整状态快照 (JSON) |
816
+ | `compactReport()` | sync string | 精简版评估报告 |
817
+ | `fullReport()` | sync → string | 完整评估报告 |
818
+ | `audit(limit?)` | sync array | 最近 N 条审计记录 |
819
+ | `feedback(signal)` | sync | 记录用户反馈信号 |
820
+
821
+ ### Session 生命周期
822
+
823
+ ```
824
+ Session 启动
825
+ ├─ require('./sentinel-guard') ← 首次自动迁移 MEMORY.md
826
+ ├─ sentinel.injectContext() ← 注入 Semantic+Episodic 上下文
827
+
828
+ Session 运行中
829
+ ├─ sentinel.execute('exec', ...) 每次工具调用
830
+ ├─ sentinel.execute('write', ...)
831
+ ├─ sentinel.feedback('user_used_result') 关键节点记录反馈
832
+
833
+ Session 结束
834
+ └─ sentinel.endSession() 追加 daily log + 清空 Working
835
+ ```
836
+
837
+ ### AgentOS sentinel-guard 功能对照
838
+
839
+ | 功能 | AgentOS 源码 | sentinel-guard skill | 覆盖率 |
840
+ |------|------------|---------------------|:------:|
841
+ | Schema Gate (12 项校验) | ✅ `schema-gate.ts` | ✅ `execute()` 内自动 | 100% |
842
+ | Risk Gate (四维公式) | ✅ `risk-gate.ts` | ✅ `execute()` 内自动 | 100% |
843
+ | 确定性命令拦截 | ❌ (依赖 Sandbox) | ✅ 正则匹配 (<1μs) | **额外增强** |
844
+ | Snapshot Gate | ✅ `snapshot-verify.ts` | ✅ `execute()` 内自动 | 100% |
845
+ | Verify Gate (3 项已实现 + 5 可扩展) | ✅ `snapshot-verify.ts` | `execute()` 内自动 | 100% |
846
+ | Audit Log (JSONL) | ✅ `audit-log.ts` | ✅ 双写 (AgentOS + 自身) | 100% |
847
+ | 规则可配置 | ❌ (代码硬编码) | ✅ `guard-rules.json` | **额外增强** |
848
+ | Working Memory | ✅ `working.ts` | 消息+工具缓存 | 100% |
849
+ | Episodic Memory | ✅ `episodic.ts` | ✅ 事件自动记录 | 100% |
850
+ | Semantic Memory | ✅ `semantic.ts` | ✅ 自动迁移+初始值 | 100% |
851
+ | MEMORY.md 迁移 | ✅ `memory-bridge.ts` | ✅ 首次加载自动跑 | 100% |
852
+ | Session 注入上下文 | ✅ `injectContext()` | ✅ `sentinel.injectContext()` | 100% |
853
+ | Session 清理 | ✅ `endSession()` | ✅ 含 daily log | 100% |
854
+ | PreExecEvaluator | ✅ `exec-evaluator.ts` | ✅ `execute()` 内自动 | 100% |
855
+ | RuntimeEvaluator | ✅ `exec-evaluator.ts` | ✅ `execute()` 内自动 | 100% |
856
+ | PostExecEvaluator | ✅ `exec-evaluator.ts` | `execute()` 内自动 | 100% |
857
+ | AgentProfiler | ✅ `profiler.ts` | ✅ `execute()` 返回 profile | 100% |
858
+ | ImplicitFeedback | ✅ `feedback.ts` | ✅ `recordFeedback()` | 100% |
859
+ | Daily Log 注入 | ✅ `evaluation-bridge.ts` | ✅ `endSession()` 自动 | 100% |
860
+ | Compact/Full Report | ✅ `evaluation-bridge.ts` | ✅ `compactReport()`/`fullReport()` | 100% |
861
+ | Sandbox 沙箱 | `sandbox.ts` | (暂未接入) | 0% |
862
+ | HTTP API | ✅ `server.ts` | ❌ (skill 为进程内调用) | N/A |
863
+ | **按设计范围总计** | **20 项** | **20/20** | **100%** |
864
+
865
+ > **接入深度说明**
866
+ > `wrapper.ts` / `sentinelPlugin()` 提供的是框架无关的通用中间件 API(`preCheck` / `postCheck` / `execute`)。
867
+ > 真正的"一行接入"需要 OpenClaw 引擎级别的 hook 注册——这是平台能力,非本包可控。
868
+ > 当前推荐方式是通过 `sentinel-guard` skill 的 `sentinel.execute()` 手动包装每次工具调用,或通过 `global.__sentinel` 自动 hook。
869
+
870
+ ### 快速入门(5 步接入)
871
+
872
+ ```javascript
873
+ // 1. 加载 skill(自动迁移 MEMORY.md)
874
+ const sentinel = require('./sentinel-guard');
875
+
876
+ // 2. Session 启动 — 注入记忆上下文
877
+ const context = sentinel.injectContext();
878
+
879
+ // 3. 工具调用 — 统一入口,三层全走
880
+ const r = await sentinel.execute('write',
881
+ { path: 'src/main.ts', content: 'console.log("hi")' },
882
+ () => fs.writeFileSync('src/main.ts', 'console.log("hi")')
883
+ );
884
+ if (!r.allowed) return { blocked: true, reason: r.reason };
885
+
886
+ // 4. 记录反馈
887
+ sentinel.feedback('user_used_result');
888
+
889
+ // 5. Session 结束 — 追加 daily log + 清理
890
+ sentinel.endSession();
891
+ ```
892
+
893
+ 完整示例代码见 `sentinel-guard/SKILL.md`,配置文件见 `sentinel-guard/guard-rules.json`。
894
+
895
+ ---
896
+
897
+ ### API 层 · SDK API
898
+
899
+ ```typescript
900
+ import { Sentinel AgentOS, Sentinel AgentOSAPI } from 'Sentinel AgentOS';
901
+
902
+ const api = new AgentOSAPI(new AgentOS());
903
+
904
+ // Guard
905
+ api.guardRegisterRule({ tool: 'delete_file', required: ['path'] });
906
+
907
+ // Memory
908
+ api.memorySetPreference('language', 'zh-CN');
909
+ api.memoryLearnRule('Never push directly to main', 'cr_1');
910
+
911
+ // Pipeline + Audit
912
+ const result = await api.pipelineExecute({...});
913
+ const audit = api.auditQuery({ toolName: 'write_file', limit: 10 });
914
+
915
+ // Profile
916
+ const report = api.getStatusReport();
917
+ api.endSession('session_1');
918
+ ```
919
+
920
+ ---
921
+
922
+ ## 📖 使用案例 · Examples
923
+
924
+ ### 1. 拦截危险命令 · Blocking dangerous commands
925
+
926
+ ```typescript
927
+ const { preExec } = aos.executePipeline({
928
+ sessionId: 's1', agentId: 'a1',
929
+ toolName: 'exec',
930
+ parameters: { command: 'rm -rf /home' },
931
+ });
932
+ // → { score: 9.18, action: 'deny' } 🔴 自动拒绝 · Auto-denied
933
+ ```
934
+
935
+ ### 2. 检测 Agent 幻觉 · Detecting hallucination
936
+
937
+ ```typescript
938
+ // Agent 声称"写入了文件",但实际没有 · Agent claims "file written" but didn't
939
+ const result = aos.completeExecution({
940
+ ...,
941
+ toolResult: 'file written successfully', // ← Agent 幻觉!
942
+ snapshot,
943
+ ...
944
+ });
945
+ console.log(result.postExec.verifyPassed); // → false
946
+ // Verify Gate 检测到文件不存在 FAIL
947
+ ```
948
+
949
+ ### 3. 跨会话记忆 · Cross-session memory
950
+
951
+ ```typescript
952
+ // Session 1: 学到偏好 · Learned preferences
953
+ const aos1 = new AgentOS();
954
+ aos1.memory.semantic.setPreference('language', 'zh-CN');
955
+ aos1.memory.semantic.learnRule('测试前先编译', 'session_1');
956
+ aos1.endSession('session_1');
957
+
958
+ // Session 2: 自动注入 · Auto-injected
959
+ const aos2 = new AgentOS();
960
+ console.log(aos2.injectContext());
961
+ // [Sentinel AgentOS Semantic Memory]
962
+ // ## Preferences
963
+ // - language: "zh-CN"
964
+ // ## Learned Rules · 学习到的规则
965
+ // - [50%] 测试前先编译
966
+ ```
967
+
968
+ ### 4. 隐性反馈驱动改进 · Feedback-driven improvement
969
+
970
+ ```typescript
971
+ // 用户删除了 Agent 创建的代码 · User deleted agent-created code
972
+ aos.recordFeedback('user_deleted_code', 's1');
973
+
974
+ // 连续3次修改 · Modified 3 times
975
+ aos.recordFeedback('user_modified_output', 's1');
976
+ aos.recordFeedback('user_modified_output', 's1');
977
+ aos.recordFeedback('user_modified_output', 's1');
978
+
979
+ const stats = aos.evaluator.feedback.stats();
980
+ // → { totalSignals: 4, negativeSignals: 4, averageStrength: -0.57 }
981
+
982
+ const profile = aos.getProfile();
983
+ // warnings: ["User satisfaction declining — review recent sessions"]
984
+ ```
985
+
986
+ ### 5. 沙箱保护 · Sandbox protection
987
+
988
+ ```typescript
989
+ const sandbox = new SandboxExecutor({
990
+ mode: 'sandbox',
991
+ networkAccess: 'none', // 禁止网络 · No network
992
+ writablePaths: ['src/', 'logs/'], // 只能写这里 · Only writable here
993
+ forbiddenTools: ['rm', 'git_push'],
994
+ });
995
+
996
+ await sandbox.execute('exec', { command: 'npm test' }); // ✅ OK
997
+ await sandbox.execute('exec', { command: 'curl evil.com' }); // ❌ 网络被黑洞 · Blocked
998
+ ```
999
+
1000
+ ---
1001
+
1002
+ ## 🧪 测试 · Tests
1003
+
1004
+ ```bash
1005
+ npm test
1006
+ ```
1007
+
1008
+ ```
1009
+ PASS tests/guard/schema-gate.test.ts (21 tests)
1010
+ PASS tests/guard/risk-gate.test.ts (20 tests)
1011
+ PASS tests/guard/snapshot-verify-audit.test.ts (17 tests)
1012
+ PASS tests/memory/memory.test.ts (29 tests)
1013
+ PASS tests/core.test.ts (12 tests)
1014
+ ────────────────────────────────────────────────
1015
+ Test Suites: 5 passed, 5 total
1016
+ Tests: 99 passed, 99 total
1017
+ ```
1018
+
1019
+ ---
1020
+
1021
+ ## ⚠️ 常见问题 · FAQ
1022
+
1023
+ <details>
1024
+ <summary><b>Q: Sentinel AgentOS 和 LangChain / CrewAI 什么关系?</b></summary>
1025
+
1026
+ Sentinel AgentOS **不是竞争对手**,是基础设施层。LangChain/CrewAI Agent 框架,Sentinel AgentOS 是给它们提供安全、记忆、评估的操作系统。可以增量接入任何框架。
1027
+ *Not a competitor — infrastructure. LangChain/CrewAI are agent frameworks; Sentinel AgentOS provides safety + memory + evaluation as an OS layer. Incrementally pluggable into any framework.*
1028
+ </details>
1029
+
1030
+ <details>
1031
+ <summary><b>Q: 为什么 Guard 层不用 LLM? · Why no LLM in Guard?</b></summary>
1032
+
1033
+ LLM 做安全判断 = 用问题制造者来解决问题。Schema 校验是纯工程数学——类型检查、范围检查、hash 对比——这些 LLM 反而做不好(会幻觉)。确定性代码 = 0 幻觉。
1034
+ *Using LLM for security = solving problems with the problem-maker. Schema validation is pure engineering — type/range/hash checks — things LLMs are bad at. Deterministic code = zero hallucination.*
1035
+ </details>
1036
+
1037
+ <details>
1038
+ <summary><b>Q: Memory 层和 RAG 有什么区别? · How is this different from RAG?</b></summary>
1039
+
1040
+ RAG = 把对话扔进向量库做检索。Sentinel AgentOS Memory = 人脑模型:Working(当前会话)、Episodic(自动评分+压缩)、Semantic(提炼后的永久知识)。最重要的是:**Sentinel AgentOS 会自动写入记忆,不需要 Agent 手动管理**。
1041
+ *RAG = dump conversation into vector DB. Sentinel AgentOS Memory = brain model. Most importantly: **Sentinel AgentOS auto-writes memory; agents don't need to manage it manually.***
1042
+ </details>
1043
+
1044
+ <details>
1045
+ <summary><b>Q: 会不会很慢? · Is it slow?</b></summary>
1046
+
1047
+ 不会。Guard 层所有校验都是 `fs.existsSync()`、hash 对比、数学公式,每个校验 **< 1ms**。Snapshot 只记录 hash 不复制文件。整个流水线开销可忽略。
1048
+ *No. All Guard checks are fs.existsSync(), hash comparison, math formulas — each < 1ms. Snapshot records hashes only, no file copy. Pipeline overhead is negligible.*
1049
+ </details>
1050
+
1051
+ <details>
1052
+ <summary><b>Q: 能用在生产环境吗? · Production-ready?</b></summary>
1053
+
1054
+ v1.0 已完成 100% 设计文档覆盖率、99 个测试全通过、TypeScript 严格模式。API 稳定,可以集成。但建议先在测试环境跑一段时间。
1055
+ *v1.0 has 100% design coverage, 99 passing tests, strict TypeScript. API is stable and integrable. Recommend testing before production.*
1056
+ </details>
1057
+
1058
+ <details>
1059
+ <summary><b>Q: npm 包已经发布了吗? · Is npm package published?</b></summary>
1060
+
1061
+ 已发布。`npm install sentinel-agentos` 即可使用。当前版本 v0.1.x。
1062
+ *Published. Just `npm install sentinel-agentos`. Current version v0.1.x.*
1063
+ </details>
1064
+
1065
+ <details>
1066
+ <summary><b>Q: 沙箱模式安全吗? · Is sandbox truly secure?</b></summary>
1067
+
1068
+ v1.0 沙箱基于环境变量 + 路径校验 + 命令模式检测,不是容器级隔离。v2.0 计划支持 Docker 沙箱。
1069
+ *v1.0 sandbox uses env vars + path validation + command pattern detection — not container-level isolation. Docker sandbox planned for v2.0.*
1070
+ </details>
1071
+
1072
+ <details>
1073
+ <summary><b>Q: 怎么看 Audit Log? · How to view audit logs?</b></summary>
1074
+
1075
+ ```bash
1076
+ cat .Sentinel AgentOS/audit.jsonl | jq '.'
1077
+ ```
1078
+
1079
+ 或通过 API · *or via API:*
1080
+
1081
+ ```typescript
1082
+ const entries = api.auditQuery({ minScore: 3.0 }); // 高风险操作 · High-risk ops
1083
+ ```
1084
+ </details>
1085
+
1086
+ <details>
1087
+ <summary><b>Q: Sentinel AgentOS 需要 API Key 吗? · Does it need an API Key?</b></summary>
1088
+
1089
+ 不需要。Sentinel AgentOS 的 Guard / Memory / Evaluator 层都是纯确定性代码,不调用任何外部 AI API。唯一的鉴权是 HTTP API 模式下可选的 `--token` 参数。
1090
+ *No. All Guard/Memory/Evaluator layers are pure deterministic code with zero external API calls. The only authentication is the optional `--token` for HTTP API mode.*
1091
+ </details>
1092
+
1093
+ <details>
1094
+ <summary><b>Q: HTTP API Token 怎么设置? · How to set HTTP API token?</b></summary>
1095
+
1096
+ 三种方式:
1097
+ 1. 命令行参数:`npx sentinel-agentos server --port 3300 --token my-secret`
1098
+ 2. 代码中配置:`createServer({ port: 3300, apiToken: 'my-secret' })`
1099
+ 3. 环境变量:`AGENTOS_TOKEN=*** npx sentinel-agentos server`
1100
+
1101
+ 不设置 Token 则不加鉴权(仅适合本地开发环境)。
1102
+ *Three ways: CLI flag, code config, or AGENTOS_TOKEN env var. No token = no auth (local dev only).*
1103
+ </details>
1104
+
1105
+ <details>
1106
+ <summary><b>Q: Token 泄漏了怎么办? · What if token leaks?</b></summary>
1107
+
1108
+ 重启服务,换一个新 Token 即可:
1109
+ 1. 生成新 Token:`openssl rand -hex 32`
1110
+ 2. 重启 sentinel-agentos server 使用新 Token
1111
+ 3. 更新所有客户端调用
1112
+ Sentinel AgentOS Token 是服务端本地验证的,无需到任何平台撤销。
1113
+ *Restart server with a new token. No external platform involved — tokens are validated locally.*
1114
+ </details>
1115
+
1116
+ ---
1117
+
1118
+ ## 🗺️ 路线图 · Roadmap
1119
+
1120
+ | 版本 | 内容 | 状态 |
1121
+ |------|------|:--:|
1122
+ | v0.1 | 项目脚手架 + 类型定义 · *Scaffold + types* | ✅ |
1123
+ | v0.2 | Guard 层(6 组件)· *Guard layer (6 components)* | ✅ |
1124
+ | v0.3 | Memory 层(3 层)· *Memory layer (3 layers)* | ✅ |
1125
+ | v0.4 | Evaluator 层(评估 + 反馈 + 画像)· *Evaluator* | ✅ |
1126
+ | v1.0 | 沙箱 + API + x- 扩展 + 校验补齐 · *Sandbox + API + x-ext* | ✅ |
1127
+ | v1.1 | npm 发布 + 三种接入方式 · *npm publish + 3 modes* | ✅ |
1128
+ | v2.0 | Docker 沙箱、Dashboard、SaaS · *Docker sandbox, Dashboard, SaaS* | 📋 |
1129
+
1130
+ ---
1131
+
1132
+ ## 🔑 Token 与鉴权说明
1133
+
1134
+ Sentinel AgentOS 本身**不依赖外部 AI API**,所有 Guard / Memory / Evaluator 都是纯确定性代码。唯一的鉴权需求来自 **HTTP API 模式**下的 `server` 命令。
1135
+
1136
+ ### HTTP API Token 鉴权
1137
+
1138
+ 启动 HTTP 服务后,除 `/health` 外所有端点都需要 Bearer Token 鉴权。
1139
+
1140
+ #### 启动时设置 Token
1141
+
1142
+ ```bash
1143
+ # 方式一:命令行参数
1144
+ npx sentinel-agentos server --port 3300 --token my-secret-token-123
1145
+
1146
+ # 方式二:代码中配置
1147
+ import { createServer } from 'sentinel-agentos';
1148
+ const server = createServer({ port: 3300, apiToken: 'my-secret-token-123' });
1149
+ await server.start();
1150
+ ```
1151
+
1152
+ #### 客户端调用
1153
+
1154
+ ```bash
1155
+ # 所有 API(/health 除外)都需要 Authorization header
1156
+ curl -H "Authorization: Bearer my-secret-token-123" \
1157
+ http://localhost:3300/pipeline/profile
1158
+
1159
+ # Token 不匹配 → 401 Unauthorized
1160
+ curl http://localhost:3300/pipeline/profile
1161
+ # → {"error":"Unauthorized: invalid or missing API token"}
1162
+ ```
1163
+
1164
+ #### Token 未设置时
1165
+
1166
+ 如果不传 `--token` 或 `apiToken`,服务**不加鉴权**,所有端点可自由访问。适用于本地开发环境,生产环境**强烈建议设置 Token**。
1167
+
1168
+ ```bash
1169
+ # 无鉴权模式(仅限本地开发)
1170
+ npx sentinel-agentos server --port 3300
1171
+ # 所有端点无需 Authorization header
1172
+ ```
1173
+
1174
+ #### Token 最佳实践
1175
+
1176
+ | 环境 | Token 策略 | 示例 |
1177
+ |------|----------|------|
1178
+ | 本地开发 | 可不用 Token | `npx sentinel-agentos server --port 3300` |
1179
+ | 本机测试 | 简短 Token | `--token dev-123` |
1180
+ | 生产环境 | 强随机 Token | `--token $(openssl rand -hex 32)` |
1181
+ | Docker / CI | 环境变量注入 | `--token $AGENTOS_API_TOKEN` |
1182
+ | 跨语言调用 | HTTP header | `Authorization: Bearer <token>` |
1183
+
1184
+ ### 环境变量配置
1185
+
1186
+ Token 外,Sentinel AgentOS 没有其他必填环境变量。可选的环境变量:
1187
+
1188
+ | 环境变量 | 说明 | 默认值 |
1189
+ |---------|------|--------|
1190
+ | `HOME` / `USERPROFILE` | 持久化存储根目录 | 系统默认 |
1191
+ | `AGENTOS_WORKSPACE` | workspace 根目录 | `process.cwd()` |
1192
+ | `AGENTOS_TOKEN` | API Token(备选方式) | |
1193
+
1194
+ ---
1195
+
1196
+ ## 📋 完整接口使用说明
1197
+
1198
+ > 本章汇总 Sentinel AgentOS 所有接口——CLI、SDK、HTTP API、中间件、沙箱——作为完整参考。
1199
+
1200
+ ### 命令一览
1201
+
1202
+ | 分类 | 接口/命令 | 说明 |
1203
+ |------|---------|------|
1204
+ | CLI | `validate` | 参数格式校验(Schema Gate) |
1205
+ | CLI | `risk` | 风险评分(Risk Gate) |
1206
+ | CLI | `audit` | 查询审计日志 |
1207
+ | CLI | `stats` | 审计统计(JSON) |
1208
+ | CLI | `profile` | Agent 质量画像(JSON) |
1209
+ | CLI | `status` | 质量状态报告(人类可读) |
1210
+ | CLI | `server` | 启动 HTTP API 服务 |
1211
+ | CLI | `memory` | 查看注入上下文 |
1212
+ | CLI | `help` | 帮助信息 |
1213
+ | SDK | `AgentOS` | 主类,完整流水线 |
1214
+ | SDK | `AgentOSAPI` | SDK 协议层(25+ 方法) |
1215
+ | SDK | `SchemaGate` / `RiskGate` 等 | 独立组件 |
1216
+ | SDK | `wrapAgent` | 一行接入中间件 |
1217
+ | SDK | `sentinelPlugin` | OpenClaw 插件 |
1218
+ | SDK | `SandboxExecutor` | 沙箱执行器 |
1219
+ | HTTP | `POST /pipeline/pre` | 执行前校验 |
1220
+ | HTTP | `POST /pipeline/post` | 执行后验证 |
1221
+ | HTTP | `GET /pipeline/report` | 状态报告 |
1222
+ | HTTP | `GET /pipeline/profile` | 质量画像 |
1223
+ | HTTP | `POST /guard/schema` | 注册 Schema 规则 |
1224
+ | HTTP | `GET /guard/schema` | 查看 Schema 规则 |
1225
+ | HTTP | `POST /memory/preference` | 设置偏好 |
1226
+ | HTTP | `POST /memory/fact` | 添加事实 |
1227
+ | HTTP | `POST /memory/rule` | 学习规则 |
1228
+ | HTTP | `GET /memory/context` | 获取注入上下文 |
1229
+ | HTTP | `GET /audit` | 查询审计日志 |
1230
+ | HTTP | `POST /feedback` | 记录反馈 |
1231
+ | HTTP | `POST /session/end` | 结束 session |
1232
+ | HTTP | `GET /health` | 健康检查(免 Token) |
1233
+
1234
+ ---
1235
+
1236
+ ### CLI 接口
1237
+
1238
+ ```
1239
+ sentinel-agentos <command> [args...]
1240
+ ```
1241
+
1242
+ #### `validate` — 参数格式校验
1243
+
1244
+ ```bash
1245
+ # 新语法(推荐)
1246
+ sentinel-agentos validate <tool> [key=value...]
1247
+
1248
+ # 校验 exec 命令
1249
+ sentinel-agentos validate exec command="rm -rf /"
1250
+ # {"pass":true,"errors":[]}
1251
+
1252
+ # 校验 write_file(会被 pathDeny 拦截)
1253
+ sentinel-agentos validate write_file path=.env content=hello
1254
+ # {"pass":false,"errors":[{"field":"path","message":"path matches deny pattern"}]}
1255
+
1256
+ # 旧语法(--tool + --params JSON)
1257
+ sentinel-agentos validate --tool exec --params '{"command":"npm test"}'
1258
+ ```
1259
+
1260
+ | 参数 | 说明 |
1261
+ |------|------|
1262
+ | `<tool>` | 工具名称(如 `exec`, `write_file`, `delete_file`) |
1263
+ | `key=value` | 参数键值对,支持 `key="带空格的值"`,自动检测类型 |
1264
+
1265
+ #### `risk` — 风险评分
1266
+
1267
+ ```bash
1268
+ sentinel-agentos risk exec command="sudo reboot"
1269
+ # → {"score":8.5,"action":"deny","dimensions":{"impact":3,"reversibility":0.2,...}}
1270
+
1271
+ sentinel-agentos risk exec command="npm test"
1272
+ # → {"score":0.19,"action":"auto",...}
1273
+ ```
1274
+
1275
+ | 风险等级 | 分数 | 动作 |
1276
+ |---------|------|------|
1277
+ | 🟢 Auto | ≤ 0.5 | 自动放行 |
1278
+ | 🔵 Notify | ≤ 1.0 | 执行后通知 |
1279
+ | 🟡 Confirm | 3.0 | 暂停等待确认 |
1280
+ | 🔴 Deny | > 8.0 | 直接拒绝 |
1281
+
1282
+ #### `audit` 查询审计日志
1283
+
1284
+ ```bash
1285
+ sentinel-agentos audit --limit 10
1286
+ # [{id, sessionId, toolName, verifyStatus, riskScore, ...}, ...]
1287
+
1288
+ sentinel-agentos audit --limit 5
1289
+ ```
1290
+
1291
+ #### `stats` / `profile` / `status` 统计与画像
1292
+
1293
+ ```bash
1294
+ # 审计统计(JSON)
1295
+ sentinel-agentos stats
1296
+ # → {"totalOperations":156,"verifyFailures":2,"highRiskOps":3,...}
1297
+
1298
+ # Agent 质量画像(JSON)
1299
+ sentinel-agentos profile
1300
+ # → {"overallScore":85,"breakdown":{...},"trends":{...},"warnings":[...]}
1301
+
1302
+ # 质量状态报告(人类可读)
1303
+ sentinel-agentos status
1304
+ # 文本报告
1305
+ ```
1306
+
1307
+ #### `server` — 启动 HTTP API 服务
1308
+
1309
+ ```bash
1310
+ sentinel-agentos server --port 3300 --token ***
1311
+ # 🛡️ Sentinel AgentOS HTTP server → http://127.0.0.1:3300
1312
+
1313
+ # 可选项
1314
+ sentinel-agentos server --port 8080 --host 0.0.0.0 --token ***
1315
+ ```
1316
+
1317
+ | 参数 | 默认值 | 说明 |
1318
+ |------|--------|------|
1319
+ | `--port <N>` | `3300` | 服务端口 |
1320
+ | `--host <IP>` | `127.0.0.1` | 绑定地址 |
1321
+ | `--token <str>` | — | API 鉴权 Token(不设则无鉴权) |
1322
+
1323
+ #### `memory` — 查看记忆上下文
1324
+
1325
+ ```bash
1326
+ sentinel-agentos memory
1327
+ # → 当前 semantic + episodic 注入的上下文文本
1328
+ ```
1329
+
1330
+ ---
1331
+
1332
+ ### SDK 接口
1333
+
1334
+ #### `AgentOS` — 主类
1335
+
1336
+ ```typescript
1337
+ import { AgentOS } from 'sentinel-agentos';
1338
+
1339
+ const aos = new AgentOS({
1340
+ workspaceRoot: process.cwd(), // 工作区根目录
1341
+ maxWorkingTokens: 50000, // 工作记忆 token 上限
1342
+ maxEpisodicSizeKb: 500, // 情景记忆大小上限 (KB)
1343
+ guardConfig: { // Guard 配置
1344
+ riskGate: {
1345
+ autoApprove: 0.5,
1346
+ notify: 1.0,
1347
+ confirm: 3.0,
1348
+ deny: 8.0,
1349
+ },
1350
+ },
1351
+ });
1352
+ ```
1353
+
1354
+ **构造函数参数 `AgentOSConfig`**:
1355
+
1356
+ | 字段 | 类型 | 默认值 | 说明 |
1357
+ |------|------|--------|------|
1358
+ | `workspaceRoot` | string | `process.cwd()` | 工作区根目录,持久化存储位置 |
1359
+ | `maxWorkingTokens` | number | `50000` | 工作记忆最大 token 数 |
1360
+ | `maxEpisodicSizeKb` | number | `500` | 情景记忆最大大小 (KB) |
1361
+ | `guardConfig.riskGate` | object | 见上 | 风险评分阈值覆盖 |
1362
+ | `evaluatorConfig.implicitFeedbackEnabled` | boolean | | 隐性反馈开关 |
1363
+
1364
+ **核心方法**:
1365
+
1366
+ | 方法 | 返回 | 说明 |
1367
+ |------|------|------|
1368
+ | `executePipeline({...})` | `{preExec, snapshot, profile}` | 执行前校验流水线(Schema + Risk + Snapshot) |
1369
+ | `completeExecution({...})` | `{runtime, postExec, auditEntry, profile}` | 执行后验证流水线(Verify + Audit) |
1370
+ | `recordFeedback(signal, sessionId)` | `void` | 记录隐性用户反馈 |
1371
+ | `injectContext()` | `string` | 注入记忆上下文(session 启动时调用) |
1372
+ | `endSession(sessionId)` | `void` | 结束 session(清空 Working Memory) |
1373
+ | `getProfile(sessionId?)` | `AgentProfile` | 获取 Agent 质量画像 |
1374
+ | `getAuditStats()` | 审计统计 | 获取审计统计 |
1375
+ | `statusReport()` | `string` | 获取人类可读的状态报告 |
1376
+
1377
+ **访问子组件**:
1378
+
1379
+ ```typescript
1380
+ // Guard
1381
+ aos.guard.schema // SchemaGate — 注册/查询校验规则
1382
+ aos.guard.risk // RiskGate 风险评分引擎
1383
+ aos.guard.snapshot // SnapshotGate 执行前快照
1384
+ aos.guard.verify // VerifyGate — 执行后验证
1385
+ aos.guard.audit // AuditLog — 审计日志
1386
+
1387
+ // Memory
1388
+ aos.memory.working // WorkingMemory — 当前会话工作记忆
1389
+ aos.memory.episodic // EpisodicMemory 跨会话事件时间线
1390
+ aos.memory.semantic // SemanticMemoryStore — 永久知识
1391
+
1392
+ // Evaluator 层
1393
+ aos.evaluator.preExec // PreExecEvaluator — 执行前评估
1394
+ aos.evaluator.runtime // RuntimeEvaluator — 执行中评估
1395
+ aos.evaluator.postExec // PostExecEvaluator — 执行后评估
1396
+ aos.evaluator.feedback // ImplicitFeedbackEngine 隐性反馈
1397
+ aos.evaluator.profiler // AgentProfiler 质量画像
1398
+ ```
1399
+
1400
+ #### `AgentOSAPI` — SDK 协议层
1401
+
1402
+ ```typescript
1403
+ import { AgentOS, AgentOSAPI } from 'sentinel-agentos';
1404
+
1405
+ const api = new AgentOSAPI(new AgentOS());
1406
+
1407
+ // Guard
1408
+ api.guardRegisterRule({ tool: 'exec', required: ['command'] });
1409
+ api.guardRegisterRules([...]);
1410
+ api.guardEvaluateRisk('exec', { command: 'rm -rf /' });
1411
+ api.guardSetRiskThresholds({ autoApprove: 0.5, deny: 6.0 });
1412
+
1413
+ // Pipeline
1414
+ const result = await api.pipelineExecute({
1415
+ sessionId: 's1', agentId: 'a1',
1416
+ toolName: 'write_file',
1417
+ toolParameters: { path: 'src/main.ts', content: 'hello' },
1418
+ });
1419
+ const complete = api.pipelineComplete({...});
1420
+
1421
+ // Memory
1422
+ api.memorySetPreference('language', 'zh-CN');
1423
+ api.memoryGetPreference('language'); // → 'zh-CN'
1424
+ api.memoryLearnRule('提交前 npm test', 'session_1');
1425
+ api.memoryDefineTerm('PEP', 'Python Enhancement Proposal');
1426
+ api.memorySetProjectContext('my-app', { description: '...', techStack: ['React', 'Node'] });
1427
+ api.memoryInjectContext(); // → 启动注入文本
1428
+ api.memoryAddMessage('user', 'Hello');
1429
+ api.memoryRecordEvent('decision', 'Chose approach A', ['architecture'], []);
1430
+
1431
+ // Audit
1432
+ api.auditQuery({ toolName: 'exec', limit: 10 });
1433
+ api.auditQuery({ minScore: 3.0 }); // 高风险操作
1434
+ api.auditStats();
1435
+
1436
+ // Feedback
1437
+ api.recordFeedback('user_explicit_approval', 's1');
1438
+ api.getSatisfaction(); // 82 (0-100)
1439
+ api.getSatisfaction('s1', 24); // 最近 24 小时
1440
+ api.feedbackStats();
1441
+
1442
+ // Profile
1443
+ api.getProfile();
1444
+ api.getProfile('s1');
1445
+ api.getStatusReport();
1446
+ api.getSessionOverview();
1447
+
1448
+ // Session
1449
+ api.endSession('s1');
1450
+ ```
1451
+
1452
+ **AgentOSAPI 完整方法清单(25 个)**:
1453
+
1454
+ | 方法 | 说明 |
1455
+ |------|------|
1456
+ | `guardRegisterRule(rule)` | 注册单条 Schema 规则 |
1457
+ | `guardRegisterRules(rules)` | 批量注册 Schema 规则 |
1458
+ | `guardHasRule(toolName)` | 检查工具是否有规则 |
1459
+ | `guardGetRules()` | 获取所有已注册规则 |
1460
+ | `guardEvaluateRisk(tool, params)` | 评估风险评分 |
1461
+ | `guardSetRiskThresholds(thresholds)` | 设置风险阈值 |
1462
+ | `pipelineExecute(params)` | 执行前校验流水线 |
1463
+ | `pipelineComplete(params)` | 执行后验证流水线 |
1464
+ | `memoryInjectContext()` | 注入记忆上下文 |
1465
+ | `memoryAddMessage(role, content)` | 添加工作记忆消息 |
1466
+ | `memorySetTask(task)` | 设置当前任务 |
1467
+ | `memoryCacheResult(tool, result)` | 缓存工具结果 |
1468
+ | `memoryRecordEvent(type, content, tags, entities)` | 记录情景事件 |
1469
+ | `memorySetPreference(key, value)` | 设置用户偏好 |
1470
+ | `memoryGetPreference(key)` | 获取用户偏好 |
1471
+ | `memoryLearnRule(rule, source)` | 学习规则 |
1472
+ | `memoryDefineTerm(term, meaning)` | 定义术语 |
1473
+ | `memorySetProjectContext(name, context)` | 设置项目上下文 |
1474
+ | `auditQuery(filter)` | 查询审计日志 |
1475
+ | `auditStats()` | 审计统计 |
1476
+ | `recordFeedback(signal, sessionId)` | 记录反馈 |
1477
+ | `getSatisfaction(sessionId?, hours?)` | 获取满意度 |
1478
+ | `feedbackStats()` | 反馈统计 |
1479
+ | `getProfile(sessionId?)` | 获取质量画像 |
1480
+ | `getStatusReport()` | 获取状态报告 |
1481
+ | `getSessionOverview()` | 获取 session 概况 |
1482
+ | `endSession(sessionId)` | 结束 session |
1483
+
1484
+ ---
1485
+
1486
+ ### HTTP API 接口
1487
+
1488
+ 基础 URL:`http://localhost:3300`(默认)
1489
+
1490
+ #### Request/Response 通用格式
1491
+
1492
+ - **Content-Type**:`application/json`
1493
+ - **鉴权**:除 `/health` 外,`Authorization: Bearer <token>`
1494
+ - **成功**:`200 OK`,JSON body
1495
+ - **鉴权失败**:`401 Unauthorized`
1496
+ - **参数错误**:`400 Bad Request`,`{"error":"..."}`
1497
+ - **服务错误**:`500 Internal Server Error`
1498
+
1499
+ #### 端点详情
1500
+
1501
+ ##### `GET /health` 健康检查(免 Token)
1502
+
1503
+ ```bash
1504
+ curl http://localhost:3300/health
1505
+ # → {"ok":true,"uptime":12.3}
1506
+ ```
1507
+
1508
+ ##### `POST /pipeline/pre` 执行前校验
1509
+
1510
+ ```bash
1511
+ curl -X POST http://localhost:3300/pipeline/pre \
1512
+ -H "Authorization: Bearer ***" \
1513
+ -H "Content-Type: application/json" \
1514
+ -d '{
1515
+ "sessionId": "s1",
1516
+ "agentId": "main",
1517
+ "toolName": "exec",
1518
+ "parameters": {"command": "npm test"},
1519
+ "affectedFiles": []
1520
+ }'
1521
+ ```
1522
+
1523
+ | 字段 | 类型 | 必填 | 说明 |
1524
+ |------|------|------|------|
1525
+ | `toolName` | string | ✅ | 工具名 |
1526
+ | `sessionId` | string | ❌ | 默认 `"http_session"` |
1527
+ | `agentId` | string | ❌ | 默认 `"http_agent"` |
1528
+ | `parameters` | object | ❌ | 工具参数,默认 `{}` |
1529
+ | `affectedFiles` | string[] | ❌ | 受影响的文件列表 |
1530
+
1531
+ **返回**:
1532
+
1533
+ ```json
1534
+ {
1535
+ "preExec": {
1536
+ "schemaCheck": { "pass": true, "errors": [] },
1537
+ "riskScore": { "score": 0.19, "action": "auto", "dimensions": {...} },
1538
+ "paramQuality": { "score": 85, "observations": [] },
1539
+ "contextUtilization": { "score": 70, "patterns": [] }
1540
+ },
1541
+ "snapshot": { "id": "...", "fileHashes": {...}, "gitHead": "...", "gitDirty": false },
1542
+ "profile": { "overallScore": 85, ... }
1543
+ }
1544
+ ```
1545
+
1546
+ ##### `POST /pipeline/post` 执行后验证
1547
+
1548
+ ```bash
1549
+ curl -X POST http://localhost:3300/pipeline/post \
1550
+ -H "Authorization: Bearer ***" \
1551
+ -H "Content-Type: application/json" \
1552
+ -d '{
1553
+ "toolName": "exec",
1554
+ "toolParameters": {"command": "npm test"},
1555
+ "toolResult": "all passed",
1556
+ "snapshot": {...},
1557
+ "startTime": 1718123456000,
1558
+ "endTime": 1718123457000,
1559
+ "retryCount": 0,
1560
+ "wasSelfCorrected": false,
1561
+ "hadTimeout": false,
1562
+ "userAccepted": true,
1563
+ "userProvidedEdit": false,
1564
+ "resultWasUsed": true
1565
+ }'
1566
+ ```
1567
+
1568
+ | 字段 | 类型 | 必填 | 说明 |
1569
+ |------|------|------|------|
1570
+ | `toolName` | string | ✅ | 工具名 |
1571
+ | `sessionId` | string | ❌ | session 标识 |
1572
+ | `agentId` | string | ❌ | agent 标识 |
1573
+ | `toolParameters` | object | ❌ | 执行时的参数 |
1574
+ | `toolResult` | any | ❌ | 工具返回结果 |
1575
+ | `snapshot` | object | ❌ | 从 `/pipeline/pre` 获取的 snapshot |
1576
+ | `startTime` | number | ❌ | 执行开始时间戳 ms |
1577
+ | `endTime` | number | ❌ | 执行结束时间戳 ms |
1578
+ | `retryCount` | number | ❌ | 重试次数,默认 0 |
1579
+ | `wasSelfCorrected` | boolean | ❌ | Agent 是否自我纠正 |
1580
+ | `hadTimeout` | boolean | ❌ | 是否超时 |
1581
+ | `userAccepted` | boolean | ❌ | 用户是否接受了结果 |
1582
+ | `userProvidedEdit` | boolean | ❌ | 用户是否修改了结果 |
1583
+ | `resultWasUsed` | boolean | ❌ | 用户是否使用了结果 |
1584
+
1585
+ ##### `GET /pipeline/report` / `GET /pipeline/profile`
1586
+
1587
+ ```bash
1588
+ curl -H "Authorization: Bearer ***" http://localhost:3300/pipeline/report
1589
+ # → {"report":"=== AgentOS Status Report ===\n..."}
1590
+
1591
+ curl -H "Authorization: Bearer ***" http://localhost:3300/pipeline/profile
1592
+ curl -H "Authorization: Bearer ***" "http://localhost:3300/pipeline/profile?sessionId=s1"
1593
+ ```
1594
+
1595
+ ##### `POST /guard/schema` / `GET /guard/schema`
1596
+
1597
+ ```bash
1598
+ # 注册规则
1599
+ curl -X POST http://localhost:3300/guard/schema \
1600
+ -H "Authorization: Bearer ***" \
1601
+ -H "Content-Type: application/json" \
1602
+ -d '{"tool":"delete_file","required":["path"],"forbidden":[]}'
1603
+ # {"ok":true,"tool":"delete_file"}
1604
+
1605
+ # 查看规则
1606
+ curl -H "Authorization: Bearer ***" "http://localhost:3300/guard/schema?tool=delete_file"
1607
+ ```
1608
+
1609
+ ##### Memory 端点(4 个)
1610
+
1611
+ ```bash
1612
+ # 设置偏好
1613
+ curl -X POST http://localhost:3300/memory/preference \
1614
+ -H "Authorization: Bearer ***" -H "Content-Type: application/json" \
1615
+ -d '{"key":"language","value":"zh-CN"}'
1616
+
1617
+ # 添加事实
1618
+ curl -X POST http://localhost:3300/memory/fact \
1619
+ -H "Authorization: Bearer ***" -H "Content-Type: application/json" \
1620
+ -d '{"fact":"用户在北京"}'
1621
+
1622
+ # 学习规则
1623
+ curl -X POST http://localhost:3300/memory/rule \
1624
+ -H "Authorization: Bearer ***" -H "Content-Type: application/json" \
1625
+ -d '{"rule":"提交前运行 npm test","source":"session_1"}'
1626
+
1627
+ # 获取注入上下文
1628
+ curl -H "Authorization: Bearer ***" http://localhost:3300/memory/context
1629
+ ```
1630
+
1631
+ ##### `GET /audit` 审计查询
1632
+
1633
+ ```bash
1634
+ curl -H "Authorization: Bearer ***" "http://localhost:3300/audit?limit=10"
1635
+ curl -H "Authorization: Bearer ***" "http://localhost:3300/audit?toolName=exec&status=FAIL"
1636
+ ```
1637
+
1638
+ | 查询参数 | 说明 |
1639
+ |---------|------|
1640
+ | `limit` | 返回条数(默认 20) |
1641
+ | `toolName` | 按工具名过滤 |
1642
+ | `status` | 按校验状态过滤:`PASS` / `WARN` / `FAIL` |
1643
+
1644
+ ##### `POST /feedback` — 记录隐性反馈
1645
+
1646
+ ```bash
1647
+ curl -X POST http://localhost:3300/feedback \
1648
+ -H "Authorization: Bearer ***" -H "Content-Type: application/json" \
1649
+ -d '{"signal":"user_explicit_approval","sessionId":"s1"}'
1650
+ ```
1651
+
1652
+ **支持的 signal 值**:
1653
+
1654
+ | Signal | 强度 | 说明 |
1655
+ |--------|------|------|
1656
+ | `user_explicit_approval` | +0.6 | 用户明确说"做得好" |
1657
+ | `user_immediate_continue` | +0.3 | 用户立即继续对话 |
1658
+ | `user_used_result` | +0.7 | 用户使用了 Agent 的结果 |
1659
+ | `user_shared_output` | +0.8 | 用户分享了 Agent 输出 |
1660
+ | `user_modified_output` | -0.5 | 用户修改了 Agent 输出 |
1661
+ | `user_deleted_code` | -0.8 | 用户删除了 Agent 创建的代码 |
1662
+ | `user_interrupted` | -0.6 | 用户打断了 Agent |
1663
+ | `user_repeated_instruction` | -0.3 | 用户重复了相同指令 |
1664
+
1665
+ ##### `POST /session/end` 结束 Session
1666
+
1667
+ ```bash
1668
+ curl -X POST http://localhost:3300/session/end \
1669
+ -H "Authorization: Bearer ***" -H "Content-Type: application/json" \
1670
+ -d '{"sessionId":"s1"}'
1671
+ # → {"ok":true}
1672
+ ```
1673
+
1674
+ ---
1675
+
1676
+ ### 中间件 / 插件接口
1677
+
1678
+ #### `wrapAgent` — 一行接入中间件
1679
+
1680
+ ```typescript
1681
+ import { wrapAgent } from 'sentinel-agentos';
1682
+
1683
+ const sentinel = wrapAgent({ workspaceRoot: process.cwd() });
1684
+
1685
+ // 每个工具调用前后调用
1686
+ const { allowed, reason } = sentinel.preCheck('exec', { command: 'rm -rf /' });
1687
+ // → { allowed: false, reason: 'Risk 9.18 → DENY' }
1688
+
1689
+ const { allowed } = sentinel.preCheck('exec', { command: 'npm test' });
1690
+ // → { allowed: true }
1691
+
1692
+ // 执行后验证
1693
+ sentinel.postCheck('exec', { command: 'npm test' }, 'all passed');
1694
+ ```
1695
+
1696
+ **`wrapAgent` 参数**:
1697
+
1698
+ | 参数 | 类型 | 默认值 | 说明 |
1699
+ |------|------|--------|------|
1700
+ | `workspaceRoot` | string | `process.cwd()` | 工作区根目录 |
1701
+ | `maxWorkingTokens` | number | `50000` | 工作记忆 token 上限 |
1702
+ | `preRegisteredRules` | boolean | `false` | 是否使用内置默认规则 |
1703
+
1704
+ #### `sentinelPlugin` OpenClaw 插件
1705
+
1706
+ ```typescript
1707
+ import { sentinelPlugin } from 'sentinel-agentos';
1708
+
1709
+ const plugin = sentinelPlugin({
1710
+ workspaceRoot: process.cwd(),
1711
+ preRegisteredRules: true,
1712
+ });
1713
+ // onBeforeTool Schema + Risk 校验
1714
+ // → onAfterTool Verify + Audit 记录
1715
+ ```
1716
+
1717
+ ---
1718
+
1719
+ ### Sandbox 沙箱接口
1720
+
1721
+ ```typescript
1722
+ import { SandboxExecutor } from 'sentinel-agentos';
1723
+
1724
+ const sandbox = new SandboxExecutor({
1725
+ mode: 'sandbox', // 'direct' | 'sandbox' | 'dry-run'
1726
+ workspaceRoot: process.cwd(),
1727
+ timeoutMs: 30000, // 命令超时 30s
1728
+ networkAccess: 'whitelist', // 'none' | 'localhost' | 'whitelist'
1729
+ networkWhitelist: ['api.github.com', 'registry.npmjs.org'],
1730
+ writablePaths: ['src/', 'tests/', 'dist/'],
1731
+ readonlyPaths: ['node_modules/', '.git/'],
1732
+ allowedTools: ['read_file', 'write_file', 'edit', 'exec'],
1733
+ forbiddenTools: ['rm', 'unlink', 'delete_file'],
1734
+ });
1735
+
1736
+ // 预检
1737
+ const check = sandbox.validate('exec', { command: 'curl evil.com' });
1738
+ // → { success: false, sandboxRejectReason: 'Network not in whitelist' }
1739
+
1740
+ // 执行
1741
+ const result = await sandbox.execute('exec', { command: 'npm test' });
1742
+ // → { success: true, result: {...} }
1743
+ ```
1744
+
1745
+ **`SandboxExecutor` 构造参数**:
1746
+
1747
+ | 参数 | 类型 | 默认值 | 说明 |
1748
+ |------|------|--------|------|
1749
+ | `mode` | `'direct' | 'sandbox' | 'dry-run'` | `'sandbox'` | 执行模式 |
1750
+ | `workspaceRoot` | string | `process.cwd()` | 工作区根目录 |
1751
+ | `timeoutMs` | number | `30000` | 命令超时毫秒 |
1752
+ | `networkAccess` | `'none' | 'localhost' | 'whitelist'` | `'localhost'` | 网络策略 |
1753
+ | `networkWhitelist` | string[] | `[]` | 网络白名单域名 |
1754
+ | `writablePaths` | string[] | `[]` | 可写路径 |
1755
+ | `readonlyPaths` | string[] | `[]` | 只读路径 |
1756
+ | `allowedTools` | string[] | `[]` | 允许的工具 |
1757
+ | `forbiddenTools` | string[] | `[]` | 禁止的工具 |
1758
+
1759
+ **执行模式说明**:
1760
+
1761
+ | 模式 | 说明 |
1762
+ |------|------|
1763
+ | `direct` | 直接执行,无限制 |
1764
+ | `sandbox` | 沙箱模式,受限的文件系统和网络访问 |
1765
+ | `dry-run` | 试运行,不实际执行,只校验权限 |
1766
+
1767
+ ---
1768
+
1769
+ ## 📂 源码结构 · Source Layout
1770
+
1771
+ ```
1772
+ src/
1773
+ ├── index.ts # 导出入口 · Exports (30+)
1774
+ ├── core.ts # Sentinel AgentOS 主循环 · Main loop
1775
+ ├── api.ts # SDK 协议层 · API layer (25+ methods)
1776
+ ├── types/index.ts # 完整类型定义 · Type definitions
1777
+ ├── guard/
1778
+ │ ├── schema-gate.ts # Schema 校验 · Validation (12 checks)
1779
+ │ ├── risk-gate.ts # 风险评分 · Risk scoring
1780
+ │ ├── snapshot-verify.ts # 快照 + 验证 + 回滚 · Snapshot + Verify + Rollback
1781
+ │ ├── audit-log.ts # 审计日志 · Audit
1782
+ │ └── sandbox.ts # 沙箱执行器 · Sandbox executor
1783
+ ├── memory/
1784
+ │ ├── working.ts # 工作记忆 · Working
1785
+ │ ├── episodic.ts # 情景记忆 · Episodic
1786
+ │ └── semantic.ts # 语义记忆 · Semantic
1787
+ └── evaluator/
1788
+ ├── exec-evaluator.ts # 三阶段评估器 · 3-phase evaluator
1789
+ ├── feedback.ts # 隐性反馈引擎 · Implicit feedback
1790
+ └── profiler.ts # Agent 质量画像 · Quality profiler
1791
+ ```
1792
+
1793
+ ---
1794
+
1795
+ ## 📄 License
1796
+
1797
+ MIT