# @cicctencent/agent-core 中文文档

规范地址：https://npmcn.com/package/%40cicctencent/agent-core/

版本：1\.0\.86
npm 元数据更新时间：2026-11-06T01:36:45.469Z
中文译文更新时间：2026-11-09T15:58:06.912Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40cicctencent/agent-core
原文对照：https://npmcn.com/package/%40cicctencent/agent-core/?lang=original

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：4.7 MB，1012 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=22\.17\.0
- 运行依赖：2 个
- 首次发布：2026-06-15T12:50:29.679Z
- 最新版本发布：2026-11-06T01:36:45.254Z
- 近 30 天下载量：2416（2026-10-10 至 2026-11-08，npm 官方下载统计）
- 已发布版本数：195（近 12 个月 195 个）

## 中文简介

AI代理的核心引擎——LLM管弦乐,工具执行,MCP,技能路由,安全,和内存管道.

## 安装

```sh
npm install @cicctencent/agent-core
```

也可以使用：`pnpm add @cicctencent/agent-core`、`yarn add @cicctencent/agent-core`、`bun add @cicctencent/agent-core`

## README

# @cicctencent/agent-core

> **内部库，仅供项目内部使用，不对外发布。**

AI Agent 核心引擎，提供 ReAct 循环编排、多 LLM 供应商抽象、工具注册与执行、MCP 协议集成、Skill 路由、安全守卫、渐进式记忆管道、A2A 协议互操作（流式事件透传），以及工具风险评估、审批管理、运行注册表、引擎复用池、JSON 存储、可观测性日志、多模态输入、对话历史持久化、Token 用量追踪与成本管控、声明式 Agent 定义（YAML front matter）、Anthropic Prompt 缓存优化、SSE 断流中断检测、非破坏性上下文投影（Context Collapse）、工作空间笔记中间件、知识库 RAG（KnowledgeBase + EmbeddingProvider）、向量检索（VectorIndex）、邮件发送接口（EmailProvider）、日历事件类型（CalendarEvent/CalendarStore）、批处理（BatchProvider，OpenAI Batch API）、文件上传与管理（FileProvider，OpenAI Files API）等应用级能力。

## 文档

-   [完整 API 文档](https://npmcn.com/package/%40cicctencent/agent-core/docs/API.md) — 所有模块的接口说明和使用示例
-   [v0.2 升级指南](https://npmcn.com/package/%40cicctencent/agent-core/docs/UPGRADE_v0.2.md) — 新增 12 个下沉模块的集成指南
-   [Runtime 下沉与迁移指南](https://npmcn.com/package/%40cicctencent/agent-core/docs/RUNTIME_AND_MIGRATION.md) — Runtime Builder、RunController、默认沙箱、A2A Server Helper 与使用方迁移边界

## 快速开始

```bash
pnpm add @cicctencent/agent-core
```

```typescript
import { AgentEngine, createLLMProvider, ToolRegistry, ContextManager } from '@cicctencent/agent-core';

const llm = createLLMProvider({ provider: 'openai', model: 'gpt-4o', apiKey: process.env.OPENAI_API_KEY! });
const toolRegistry = new ToolRegistry();
const engine = new AgentEngine({ llmProvider: llm, toolRegistry, contextManager: new ContextManager(), maxIterations: 10 });

for await (const event of engine.run({ sessionId: 'session-001', message: 'Hello' })) {
  if (event.type === 'message') process.stdout.write(event.content);
  if (event.type === 'done') console.log('\nDone:', event.content);
}
```

## A2A 协议集成

支持将远程 A2A Agent 包装为 `SubAgentRunner`，与本地 Specialist 并列注册到 `delegate_task`：

```typescript
import { A2AClient, createA2ARemoteRunner, createDelegateTool } from '@cicctencent/agent-core';

const client = new A2AClient();
const card = await client.discoverAgent('https://remote-agent.example.com');

const remoteRunner = createA2ARemoteRunner({
  agentUrl: card.url,
  name: `[Remote] ${card.name}`,
  description: card.description,
  streaming: card.capabilities.streaming,
  client,
  skillId: 'specialist_123',  // 可选，供服务端路由到对应的 specialist
});

const delegateTool = createDelegateTool([localSpecialist, remoteRunner]);
if (delegateTool) registry.register(delegateTool);
```

**核心特性**：

-   **事件透传**：Core 不对 A2A SSE 事件做过滤，服务端发的所有事件均透传给调用方
-   **流式自动降级**：远程不支持流式时自动回退到同步模式
-   **取消支持**：流式传输支持 `AbortSignal` 外部取消
-   **心跳重置超时**：逐次读取超时，心跳可重置计时器，适合长时间任务

详见 [A2A 协议文档](https://npmcn.com/package/%40cicctencent/agent-core/docs/API.md#a2a--agent-to-agent-%E5%8D%8F%E8%AE%AE)。

## 多模态输入

`Message.content` 支持 `string | ContentPart[] | null`，可传图片/文件给 Vision 模型：

```typescript
import type { ContentPart } from '@cicctencent/agent-core';

const content: ContentPart[] = [
  { type: 'text', text: '这张图片里是什么？' },
  { type: 'image', source: 'data:image/png;base64,iVBOR...', mimeType: 'image/png' },
];

for await (const event of engine.run({ sessionId: 's1', message: content })) {
  if (event.type === 'message') process.stdout.write(event.content);
}
```

-   `TextPart` — 文本片段
-   `ImagePart` — 图片（base64 data URI 或 URL），OpenAI/Anthropic Provider 自动适配
-   `FilePart` — 文件内容（文本注入上下文）
-   `extractTextFromContent()` — 从多模态内容提取纯文本

## 对话历史持久化

通过 `HistoryPersistence` 接口实现 JSONL append-only 持久化，服务重启后自动恢复：

```typescript
import { JsonlHistoryPersistence } from '@cicctencent/agent-core';

const persistence = new JsonlHistoryPersistence({ dir: 'history' });
const engine = new AgentEngine({
  // ...
  historyPersistence: persistence,
});

// 重启后恢复
await engine.loadHistory('session-001');

// 历史操作（自动同步持久化）
engine.truncateHistory('session-001', 10);  // 截断到第 10 条
engine.forkHistory('session-001', 'session-002', 5);  // 从第 5 条分叉
```

## Token 用量追踪与成本管控

```typescript
import { InMemoryUsageTracker } from '@cicctencent/agent-core';

const tracker = new InMemoryUsageTracker();
const engine = new AgentEngine({
  // ...
  usageTracker: tracker,
  tokenBudget: { maxTokens: 500_000, onExceed: 'warn' },
});

// 查询统计
const stats = tracker.stats({ startTime: Date.now() - 86400000 });
console.log(`总 Token: ${stats.totalTokens}, 成本: $${stats.totalCost}`);

// 预算检查
const budget = tracker.checkBudget('session-001', { maxTokens: 100_000 });
if (budget.exceeded) console.warn('预算超限！');
```

-   内置 20+ 常见模型定价表（`TokenPricing`）
-   `calculateCost(provider, model, usage)` 自动计算成本
-   按 Provider/Model 分组统计
-   预算控制：超限时 `warn`（日志告警）或 `abort`（中止执行）

## 构建

```bash
pnpm typecheck   # 类型检查
pnpm build       # 生成 .d.ts
```

## 运行时要求

Node.js >= 22

## 常见问题

### @cicctencent/agent-core 是什么？

AI代理的核心引擎——LLM管弦乐,工具执行,MCP,技能路由,安全,和内存管道\.

### 如何安装 @cicctencent/agent-core？

在项目目录运行 npm install @cicctencent/agent-core，或使用 pnpm add / yarn add / bun add。

### @cicctencent/agent-core 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @cicctencent/agent-core 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @cicctencent/agent-core 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=22\.17\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @cicctencent/agent-core 可以商用吗？

@cicctencent/agent-core 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @cicctencent/agent-core 的下载量有多少？

根据 npm 官方下载统计，@cicctencent/agent-core 在 2026/10/10 – 2026/11/08 这 30 天内被下载 2,416 次，日均约 81 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @cicctencent/agent-core 还在维护吗？

最新版本 1\.0\.86 发布于 2026/11/06（3 天前）；至今共发布 195 个版本，其中过去 12 个月发布了 195 个；首次发布于 2026/06/15。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

