@mox/agent-core

元认知协议引擎 + 分级自主护栏 —— 平台无关的通用 Agent 核心

Metacognition engine + tiered-autonomy guardrails — a runtime-agnostic core for AI agents

0 平台绑定platform deps 47 项测试tests TypeScript MIT 依赖注入DI-based

这是什么What is this

一个把「会思考的 Agent」里真正难复用的那部分抽出来的核心库:元认知协议(think / reflect 闭环)与分级自主护栏(工具分级、单日熔断、影子模式)。它不是 prompt 模板,而是可测试的架构——平台无关、依赖注入、47 项测试覆盖。运维、研发、数据分析、内容生产……任何需要「会思考 + 可控自治」的 Agent 都能用。

The reusable core of a "thinking" AI agent: a metacognition protocol (think / reflect loop) and tiered-autonomy guardrails (tool tiers, daily circuit-breaker, shadow mode). Not a prompt template — a testable architecture: runtime-agnostic, dependency-injected, covered by 47 tests. For any agent that needs to think and act with controlled autonomy.

元认知引擎

Metacognition engine

结构化推理卡(think)+ 执行后自检卡(reflect)+ 闭环门(未反思不许收尾)

Structured think cards + post-action reflect cards + a gate that blocks premature answers

分级护栏

Tiered guardrails

工具分低/中/高三级;低危自动、中危熔断计数、高危永远需人确认

Tools tiered low/mid/high; low runs free, mid consumes a daily budget, high always needs a human

影子模式

Shadow mode

先"只模拟不执行"地跑中危动作,攒够信心再放开——把风险关在门外

Dry-run mid-tier actions first, gain confidence, then open the gate

安装Install

npm install @mox/agent-core
import { normalizeActions, guardExecute, ReflectGate } from '@mox/agent-core';

元认知协议Metacognition protocol

模型每轮可输出 think(外显结构化推理:目标 / 假设 / 查证 / 四视角)、reflect(执行后自检:结论 / 副作用 / 更优解 / 置信度)、call(调工具)或 answer。核心负责把它们规范化并强制闭环。

Each turn the model may emit think (structured reasoning: goal / assumptions / checks / four perspectives), reflect (post-action self-check: verdict / side effects / better way / confidence), call (invoke a tool) or answer. The core normalizes these and enforces the loop.

动作归一化(健壮解析)

Action normalization (robust parsing)

模型常常不守协议,一次吐一个 JSON 数组。若只按单对象解析,后面的 call 会被静默吞掉——这正是"只思考不干活"的根因。normalizeActions 把单对象 / 数组 / 带 markdown 包裹的输出统一归一化成动作数组,逐个执行,一个不丢。

Models often batch actions into a single JSON array. Naive single-object parsing silently drops the trailing call — the classic "thinks but never acts" bug. normalizeActions folds single objects, arrays, and markdown-fenced output into one action array, executed item by item.

import { normalizeActions } from '@mox/agent-core';

normalizeActions({ action: 'think', reasoning: { goal: '…' } });
// → [{ action: 'think', … }]

normalizeActions([
  { action: 'think', reasoning: { goal: '体检' } },
  { action: 'call', tool: 'diagnose', args: {} },
]);
// → [think, call]  两个动作都会被处理

闭环门 ReflectGate

ReflectGate — the closing gate

变更类动作执行后,门被"武装";在模型 reflect 之前不允许收尾。这样把"执行完就自夸"变成结构上不可能。

After a mutating action the gate is armed; the agent may not finalize until it reflects. This makes "act then brag" structurally impossible.

const gate = new ReflectGate();
// 循环里:
if (res.ok && isMutationTier(tier)) gate.afterMutation();
if (isReflect(action)) gate.onReflect();
if (action.action === 'answer' && gate.isPending) {
  // 驳回:要求先反思再答复
  continue;
}

四视角

Four perspectives

每个 think 可从四个视角交叉检查,missingPerspectives 能检出漏掉的视角:

Each think may cross-check four perspectives; missingPerspectives detects which are missing:

视角Perspective关注Focus
决策者Decision-maker影响、是否需立即处理Impact, urgency
用户User数据丢失、功能异常Data loss, broken features
安全Security是否暴露内部结构Internal exposure
成本Cost重试/资源消耗Retries, resource spend

分级自主护栏Tiered-autonomy guardrails

不是简单的"要不要批准",而是按风险分级:低危自动放行、 中危计入单日额度、高危永远交给人。

Not a binary approve/deny — it's risk-tiered: low tier runs free, mid tier consumes a daily budget, high tier always defers to a human.

级别Tier行为Behavior
lowLow可逆的小操作,自动执行且不消耗额度Reversible & small; auto-runs, no budget cost
midMid计入单日熔断额度,超额即停;可切影子模式Counts toward a daily cap; can run in shadow mode
highHigh永远需要人工确认(走你原有的批准门)Always requires human approval (your existing gate)

统一执行入口

One guarded entry point

import { guardExecute, defaultToolTier } from '@mox/agent-core';

const deps = {
  storage,                                   // 任意 KV(注入)
  executor: { async execute(action, args) { /* 你的业务执行 */ } },
  policy: defaultToolTier,
  remediationTier,                            // 修复类动作的等级
  logger: console,
};

const r = await guardExecute(deps, 'disable_channel', { id: 5 });
// r.ok / r.simulated / r.blocked / r.summary / r.data

guardExecute 依次做:查单日熔断 → 判影子模式(仅模拟、不执行)→ 真正执行 → 中危以上计入额度。所有决策都返回结构化结果,可直接推给前端渲染。

guardExecute runs: check daily breaker → honor shadow mode (simulate only) → execute → count budget for mid+. Every decision returns a structured result you can stream to a UI.

运行时抽象Runtime abstraction

核心不依赖任何平台。三个注入接口就够:

The core depends on no platform. Three injected interfaces are all it takes:

接口Interface作用Role
StorageStorage读写 JSON 状态(额度、影子开关)Persist JSON state (budget, shadow flag)
ActionExecutorActionExecutor真正执行一个动作Actually perform an action
ActionLoggerActionLogger审计 / 可观测Audit / observability

Cloudflare D1 适配器

Cloudflare D1 adapter

自带一个 D1 实现,表名/列名在构造时传入(核心不硬编码任何业务 schema):

A D1 implementation ships in the box; table/column names are passed at construction (the core hardcodes no business schema):

import { D1Storage } from '@mox/agent-core';

const storage = new D1Storage(env.DB, { table: 'agent_kv' });
// 期望表结构:CREATE TABLE agent_kv (key TEXT PRIMARY KEY, value TEXT);

Node / Vercel 等环境,实现自己的 Storage 即可复用全部护栏与元认知逻辑。

On Node / Vercel etc., implement your own Storage to reuse all guardrail and metacognition logic.