# @gajae-code/agent-core 中文文档

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

版本：0\.21\.0
npm 元数据更新时间：2026-11-16T05:13:45.969Z
中文译文更新时间：2026-11-16T05:15:41.715Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/%40gajae-code/agent-core
原文对照：https://npmcn.com/package/%40gajae-code/agent-core/?lang=original
项目主页：https://gajae-code.com/
源码仓库：https://github.com/Yeachan-Heo/gajae-code

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

- 包体积（解压后）：1 MB，71 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：3 个
- 首次发布：2026-05-27T18:46:39.308Z
- 最新版本发布：2026-11-16T05:13:45.646Z
- 近 30 天下载量：7490（2026-10-16 至 2026-11-14，npm 官方下载统计）
- 已发布版本数：158（近 12 个月 158 个）

## 中文简介

具有运输抽象、状态管理和附件支持的通用剂

## 安装

```sh
npm install @gajae-code/agent-core
```

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

## README

# @gajae-code/代理核心

具有工具执行和事件流的状态代理 。 建造在 `@gajae-code/ai`。 。 。 .

## 安装

```bash
npm install @gajae-code/agent-core
```

## 快速启动

```typescript
import { Agent } from "@gajae-code/agent-core";
import { getModel } from "@gajae-code/ai";

const agent = new Agent({
    initialState: {
        systemPrompt: ["You are a helpful assistant."],
        model: getModel("anthropic", "anthropic-model-sonnet-4-20250514"),
    },
});

agent.subscribe((event) => {
    if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
        // Stream just the new text chunk
        process.stdout.write(event.assistantMessageEvent.delta);
    }
});

await agent.prompt("Hello!");
```

## 核心概念

### 代理Message vs LLM 信件

代理与 `AgentMessage`,灵活类型,可以包括:

-   标准 LLM 消息 (`user`, (中文(简体) ), `assistant`, (中文(简体) ), `toolResult`(中文(简体) )
-   通过声明合并自定义应用特定消息类型

法学硕士只理解 `user`, (中文(简体) ), `assistant`,以及 `toolResult`编辑 `convertToLlm` 函数通过在每次LLM调用前过滤和转换消息来弥补这一空白.

### 信件流动

```
AgentMessage[] → transformContext() → AgentMessage[] → convertToLlm() → Message[] → LLM
                    (optional)                           (required)
```

1.  **转换语句**: Prune 旧消息, 注入外部上下文
2.  **转换为Llm**: 过滤出仅UI 信件, 将自定义类型转换为 LLM 格式

## 事件流程

代理为 UI 更新发布事件 。 了解事件序列有助于构建响应界面.

### 提示( ) 事件顺序

当你打电话 `prompt("Hello")`数字 :

```
prompt("Hello")
├─ agent_start
├─ turn_start
├─ message_start   { message: userMessage }      // Your prompt
├─ message_end     { message: userMessage }
├─ message_start   { message: assistantMessage } // LLM starts responding
├─ message_update  { message: partial... }       // Streaming chunks
├─ message_update  { message: partial... }
├─ message_end     { message: assistantMessage } // Complete response
├─ turn_end           { message, toolResults: [] }
└─ agent_end       { messages: [...] }
```

当供应商或本地运行失败时, 代理发送 `agent_failed` 在终端之前 `agent_end`数字 :

```ts
{ type: "agent_failed", error, scope? }
// ...then
{ type: "agent_end", messages, stopReason: "error" }
```

`agent_failed` (a) 诊断性,并与同一尝试相关 不把它当作终点边界 或停止等待 `agent_end`编辑 失败事件是添加剂,所以存在 `agent_end` 仍然需要处理.

`agent_failed.error` 总是消毒 `{ code, message }` 由 运行时间在排放前的故障消毒器——绝不是原始提供者出错. 消费者不得依赖提供者的具体细节、请求体或原始的 此有效载荷中的错误对象; 代码是一个稳定的分类器和信件 是一个固定的人类可读描述.

### 用工具调用

如果助手调用工具,循环继续:

```
prompt("Read config.json")
├─ agent_start
├─ turn_start
├─ message_start/end  { userMessage }
├─ message_start      { assistantMessage with toolCall }
├─ message_update...
├─ message_end        { assistantMessage }
├─ tool_execution_start  { toolCallId, toolName, args }
├─ tool_execution_update { partialResult }           // If tool streams
├─ tool_execution_end    { toolCallId, result }
├─ message_start/end  { toolResultMessage }
├─ turn_end           { message, toolResults: [toolResult] }
│
├─ turn_start                                        // Next turn
├─ message_start      { assistantMessage }           // LLM responds to tool result
├─ message_update...
├─ message_end
├─ turn_end
└─ agent_end
```

### 持续( ) 事件顺序

`continue()` 从现有上下文恢复,而不添加新信件。 错误发生后用它进行重试 .

```typescript
// After an error, retry from current state
await agent.continue();
```

上下文中的最后信息必须是 `user` 或者说 `toolResult` (无) `assistant`) (中文(简体) ).

### 事件类型

| 活动 | 说明 |
| --- | --- |
| `agent_start` | 代理开始处理 |
| `agent_failed` | 提供者/局部故障诊断;在终端前排放 `agent_end` |
| `agent_end` | 代理完成所有新信件 |
| `turn_start` | 新回合开始( 一个 LLM 调用 + 工具执行) |
| `turn_end` | 以助理消息和工具结果转换完成 |
| `message_start` | 任何消息开始( 用户、 助手、 工具Result) |
| `message_update` | **仅限助理.** 包括 `assistantMessageEvent` 带三角洲 |
| `message_end` | 信件完成 |
| `tool_execution_start` | 工具开始 |
| `tool_execution_update` | 工具流进展 |
| `tool_execution_end` | 工具完成 |

## 代理选项

```typescript
const agent = new Agent({
  // Initial state
  initialState: {
    systemPrompt: string[],
    model: Model,
    thinkingLevel: "off" | "minimal" | "low" | "medium" | "high" | "xhigh",
    tools: AgentTool<any>[],
    messages: AgentMessage[],
  },

  // Convert AgentMessage[] to LLM Message[] (required for custom message types)
  convertToLlm: (messages) => messages.filter(...),

  // Transform context before convertToLlm (for pruning, compaction)
  transformContext: async (messages, signal) => pruneOldMessages(messages),

  // How to handle queued messages: "one-at-a-time" (default) or "all"
  queueMode: "one-at-a-time",

  // Custom stream function (for proxy backends)
  streamFn: streamProxy,

  // Dynamic API key resolution (for expiring OAuth tokens)
  getApiKey: async (provider) => refreshToken(),

  // Tool execution context (late-bound UI/session access)
  getToolContext: () => ({ /* app-defined */ }),
});
```

## 代理国

```typescript
interface AgentState {
    systemPrompt: string[];
    model: Model;
    thinkingLevel: ThinkingLevel;
    tools: AgentTool<any>[];
    messages: AgentMessage[];
    isStreaming: boolean;
    streamMessage: AgentMessage | null; // Current partial during streaming
    pendingToolCalls: Set<string>;
    error?: string;
}
```

通过 `agent.state`在流出时, `streamMessage` 包含部分助理消息.

## 方法

### 提示

```typescript
// Text prompt
await agent.prompt("Hello");

// With images
await agent.prompt("What's in this image?", [{ type: "image", data: base64Data, mimeType: "image/jpeg" }]);

// AgentMessage directly
await agent.prompt({ role: "user", content: "Hello", timestamp: Date.now() });

// Continue from current context (last message must be user or toolResult)
await agent.continue();
```

### 州管理层

```typescript
agent.setSystemPrompt("New prompt");
agent.setModel(getModel("openai", "gpt-4o"));
agent.setThinkingLevel("medium");
agent.setTools([myTool]);
agent.replaceMessages(newMessages);
agent.appendMessage(message);
agent.clearMessages();
agent.reset(); // Clear everything
```

### 控制权

```typescript
agent.abort(); // Cancel current operation
await agent.waitForIdle(); // Wait for completion
```

### 活动

```typescript
const unsubscribe = agent.subscribe((event) => {
    console.log(event.type);
});
unsubscribe();
```

## 指导与后续行动

在工具执行(stering)期间或代理商停止(后续)后要注入的队列信息 :

```typescript
agent.setSteeringMode("one-at-a-time");
agent.setToolInterruptPolicy("abort_tools");

// A steer is admitted ONLY into a live, non-aborted run.
const admission = agent.steer({
    role: "user",
    content: "Stop! Do this instead.",
    timestamp: Date.now(),
});
if (!admission.admitted) {
    // admission.reason is "idle" (no run to steer) or "aborting" (the run is
    // winding down). Nothing was queued: the caller owns routing the message,
    // e.g. as a fresh prompt or a follow-up of the next turn.
}

// Queue a follow-up to run after the current turn completes
agent.followUp({
    role: "user",
    content: "After that, summarize the changes.",
    timestamp: Date.now(),
});
```

每次工具默认调用后都会检查引导消息 。 设定 `toolInterruptPolicy` 改为 `"finish_tools"` 来让运行的工具批次在方向盘转动打开前完成;方向盘是 仍然在下一个工具/回合边界上消耗.

结束( 完成、 中止或出错) 的运行从未持续引导它没有消耗: 代理 清除队列并报告信件 `agent_end.disownedSteering`,所以业主决定一次 无论是改变路线还是放弃.

## 自定义信件类型

扩展 `AgentMessage` 通过声明合并:

```typescript
declare module "@gajae-code/agent-core" {
    interface CustomAgentMessages {
        notification: { role: "notification"; text: string; timestamp: number };
    }
}

// Now valid
const msg: AgentMessage = { role: "notification", text: "Info", timestamp: Date.now() };
```

处理自定义类型 `convertToLlm`数字 :

```typescript
const agent = new Agent({
    convertToLlm: (messages) =>
        messages.flatMap((m) => {
            if (m.role === "notification") return []; // Filter out
            return [m];
        }),
});
```

## 工具

使用 `AgentTool` 带有 Zod 参数计划(通过) `z` 从 `@gajae-code/ai`) (中文(简体) ).

```typescript
import { z } from "@gajae-code/ai";

const readFileTool: AgentTool = {
    name: "read_file",
    label: "Read File", // For UI display
    description: "Read a file's contents",
    parameters: z.object({
        path: z.string().describe("File path"),
    }),
    execute: async (toolCallId, params, signal, onUpdate, context) => {
        const content = await fs.readFile(params.path, "utf-8");

        // Optional: stream progress
        onUpdate?.({ content: [{ type: "text", text: "Reading..." }], details: {} });

        return {
            content: [{ type: "text", text: content }],
            details: { path: params.path, size: content.length },
        };
    },
};

agent.setTools([readFileTool]);
```

### 处理错误

**丢出错误** 当工具失败时。 不返回错误消息为内容 .

```typescript
execute: async (toolCallId, params, signal, onUpdate) => {
    if (!fs.existsSync(params.path)) {
        throw new Error(`File not found: ${params.path}`);
    }
    // Return content only on success
    return { content: [{ type: "text", text: "..." }] };
};
```

丢出的错误被代理抓住,并作为工具错误报告到 LLM `isError: true`。 。 。 .

## 代理用户

对于通过后端代理的浏览器应用:

```typescript
import { Agent, streamProxy } from "@gajae-code/agent-core";

const agent = new Agent({
    streamFn: (model, context, options) =>
        streamProxy(model, context, {
            ...options,
            authToken: "...",
            proxyUrl: "https://your-server.com",
        }),
});
```

## 低级 API

对于没有代理类的直接控制:

```typescript
import { agentLoop, agentLoopContinue } from "@gajae-code/agent-core";

const context: AgentContext = {
    systemPrompt: ["You are helpful."],
    messages: [],
    tools: [],
};

const config: AgentLoopConfig = {
    model: getModel("openai", "gpt-4o"),
    convertToLlm: (msgs) => msgs.filter((m) => ["user", "assistant", "toolResult"].includes(m.role)),
};

const userMessage = { role: "user", content: "Hello", timestamp: Date.now() };

for await (const event of agentLoop([userMessage], context, config)) {
    console.log(event.type);
}

// Continue from existing context
for await (const event of agentLoopContinue(context, config)) {
    console.log(event.type);
}
```

## 运行级遥测

每个 `invoke_agent` 与 OTEL 跨度同时产生两个值:

-   **`AgentRunSummary`** —聊天/工具/使用/成本/出错计数器被桶装 按状态,按工具名细分。 纯聚合, 安全到 坚持 坚持 坚持 坚持.
-   **`AgentRunCoverage`** —已排序+已排序 `toolsAvailable` 编号 : `toolsInvoked` 编号 : `toolsUnused` 编号 : `modelsUsed` 编号 : `providersUsed` 数组。 稳定快照 测试.

三个送货渠道(以合用者为准):

### `agent_end` 事件(增加)

```typescript
for await (const event of agentLoop([userMessage], context, {
    ...config,
    telemetry: {},
})) {
    if (event.type === "agent_end" && event.telemetry) {
        console.log("tokens:", event.telemetry.usage.totalTokens);
        console.log("unused tools:", event.coverage?.toolsUnused);
    }
}
```

这个 `messages` 字段不变。 忽视的消费者 `telemetry`编号 : `coverage` 继续工作.

### `onRunEnd` 钩子( 非脂肪)

```typescript
const stream = agentLoop([userMessage], context, {
    ...config,
    telemetry: {
        onRunEnd: (summary, coverage) => {
            await persistRunSummary(summary, coverage);
        },
    },
});
```

从 `onRunEnd` 被捕获和登录 `console.warn`· ; 行为不端的遥测消费者可以 **永远** 运行成功代理 变成失败者.

### `agentLoopDetailed` (类型) `detailed()` 结果)

保存现有流 API 并曝光 以打出值滚动 :

```typescript
const { stream, detailed } = agentLoopDetailed([userMessage], context, {
    ...config,
    telemetry: {}, // required to populate telemetry/coverage
});

for await (const event of stream) {
    // existing event handling
}

const { messages, telemetry, coverage } = await detailed();
```

`stream.result()` 仍决心 `AgentMessage[]` - 没有突破性的变化.

### 多运行汇总

多次驱动循环的呼叫者( 验证通过, 基准控制) 以 `aggregateAgentRunSummaries` 编号 : `aggregateAgentRunCoverage`数字 :

```typescript
import {
    aggregateAgentRunSummaries,
    aggregateAgentRunCoverage,
} from "@gajae-code/agent-core";

const summaries: AgentRunSummary[] = [];
const coverages: AgentRunCoverage[] = [];
for (const target of targets) {
    const { detailed } = agentLoopDetailed(/* ... */);
    const result = await detailed();
    if (result.telemetry) summaries.push(result.telemetry);
    if (result.coverage) coverages.push(result.coverage);
}
const runSummary = aggregateAgentRunSummaries(summaries);
const runCoverage = aggregateAgentRunCoverage(coverages);
```

### 工具状态报告

`execute_tool` 跨度带 `pi.gen_ai.tool.status` ∈ `"ok" | "error" | "skipped" | "blocked" | "timeout" | "aborted"`。 。 。 . `beforeToolCall` 块抛出可区分 `ToolCallBlockedError` 内部; 捕获路径报告 `status: "blocked"` 而不是拼凑 带有通用工具错误。 运行前中断 和尾声的跳跃是 记录为 `"skipped"` 即使他们从来没有开始一个阶段.

## 许可证

麻省理工学院

## 常见问题

### @gajae-code/agent-core 是什么？

具有运输抽象、状态管理和附件支持的通用剂

### 如何安装 @gajae-code/agent-core？

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

### @gajae-code/agent-core 支持 TypeScript 吗？

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

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

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

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

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

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

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

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

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

