# @axiom-lattice/core 中文文档

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

版本：12\.1\.1
npm 元数据更新时间：2026-11-03T03:44:25.644Z
中文译文更新时间：2026-11-07T16:43:15.767Z
软件包许可：ISC

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

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

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

- 包体积（解压后）：15 MB，21 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=20\.10\.0
- 运行依赖：32 个
- 首次发布：2025-09-01T09:25:00.109Z
- 最新版本发布：2026-11-03T03:44:25.438Z
- 近 30 天下载量：4678（2026-10-08 至 2026-11-06，npm 官方下载统计）
- 已发布版本数：203（近 12 个月 175 个）

## 中文简介

基于代理应用程序的核心库

## 安装

```sh
npm install @axiom-lattice/core
```

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

## README

# @ axiom-lattice/ core (韩语)

核心代理框架为模型,工具,代理,内存,存储等提供线条管理器.

## 存储配置

### `configureStores`

取代手册的统一存储注册 `new → initialize → remove → register` 锅炉板. 处理 `StoreLatticeManager`, (中文(简体) ), `ScheduleLatticeManager`,以及 `MemoryLatticeManager` 通过一个电话.

```typescript
import { configureStores } from "@axiom-lattice/core";
import { createPgStoreConfig } from "@axiom-lattice/pg-stores";
import { PostgresSaver } from "@langchain/langgraph-checkpoint-postgres";

// One connection string creates all PG store instances
const stores = createPgStoreConfig(process.env.DATABASE_URL);

// One call registers all stores across three managers
await configureStores({
  ...stores,
  checkpoint: PostgresSaver.fromConnString(process.env.DATABASE_URL),
}, { autoDisposeStores: true });
```

### 支持的存储密钥

| 密钥 | 通过 |
| --- | --- |
| `thread`, (中文(简体) ), `assistant`, (中文(简体) ), `workspace`, (中文(简体) ), `project`, (中文(简体) ), `database`, (中文(简体) ), `metrics`, (中文(简体) ), `mcp`, (中文(简体) ), `user`, (中文(简体) ), `tenant`, (中文(简体) ), `userTenantLink`, (中文(简体) ), `threadMessageQueue`, (中文(简体) ), `workflowTracking`, (中文(简体) ), `eval`, (中文(简体) ), `channelInstallation`, (中文(简体) ), `channelBinding`, (中文(简体) ), `skill` | `StoreLatticeManager` |
| `schedule` | `ScheduleLatticeManager` (自动配置为 POSTGRES) |
| `checkpoint` | `MemoryLatticeManager` (接受任何检查点保护) |

### 行为

每个商店条目:

1.  电话 `store.initialize()` 如果该方法存在( 如果需要参数则跳过)
2.  删除任何已存在的 `"default"` 登记
3.  注册新仓库 `"default"`
4.  音轨 `store.dispose` 用于清理

### 选项

```typescript
interface ConfigureStoresOptions {
  autoDisposeStores?: boolean;     // Register SIGINT/SIGTERM handlers for cleanup
  customStores?: Record<string, object>;  // Register custom store types
}
```

回返a `dispose` 用于手动清理的函数,无论是否 `autoDisposeStores`。 。 。 .

### 自定义仓库

注册紧随其后的自定义存储执行 `initialize()` 编号 : `dispose()` 样式 :

```ts
interface MyCustomStore {
  getData(): Promise<string>;
}

class PostgreSQLMyCustomStore implements MyCustomStore {
  async initialize() { /* run migrations */ }
  async dispose() { /* close pool */ }
  async getData() { return "from pg"; }
}
```

```ts
await configureStores({
  thread: new PostgreSQLThreadStore(opts),
}, {
  customStores: {
    myCustom: new PostgreSQLMyCustomStore({ poolConfig }),
  },
});

// Consume via StoreLatticeManager
const { store } = getStoreLattice("default", "myCustom");
const customStore = store as MyCustomStore;
```

### 消费者模式

需要存储的组件直接从 `StoreLatticeManager` 没有 `setConfigStore` 要求:

```typescript
// SqlDatabaseManager reads database configs lazily from the store lattice
const db = await sqlDatabaseManager.getDatabase(tenantId, "main-db");

// MetricsServerManager loads configs on first access
const client = await metricsServerManager.getClient(tenantId, "prometheus");
const servers = await metricsServerManager.getServerKeys(tenantId);
```

* * *

## 其他 Lattice 管理员

### 模型拉蒂斯

```typescript
import { registerModelLattice } from "@axiom-lattice/core";

registerModelLattice("default", {
  model: "gpt-4o",
  provider: "openai",
  streaming: true,
  apiKeyEnvName: "OPENAI_API_KEY",
});
```

### 春克缓冲

```typescript
import { InMemoryChunkBuffer, registerChunkBuffer } from "@axiom-lattice/core";

const buffer = new InMemoryChunkBuffer({ ttl: 30 * 60 * 1000 });
registerChunkBuffer("default", buffer);
```

## 目录结构

-   `src/store_lattice/` — 存储网纹管理器+配置层纹
-   `src/model_lattice/` - LLM 提供者抽象
-   `src/tool_lattice/` 工具实施(SQL、度量衡等)
-   `src/agent_lattice/` 代理人定义和构建者
-   `src/memory_lattice/` - 背景/记忆管理
-   `src/schedule_lattice/` - 计划任务管理
-   `src/sandbox_lattice/` - 代码执行沙盒供应商

* * *

## 自定义中件注册

应用程序可以在不修改核心源代码的情况下写出自己的中间软件并在运行时注册. 然后可以通过存储在数据库中的代理配置启用已注册的中间软件.

### 快开始

```typescript
import { createMiddleware, CustomMiddlewareRegistry } from "@axiom-lattice/core";

CustomMiddlewareRegistry.register("my-logger", (config) =>
  createMiddleware({
    name: "MyLogger",
    wrapModelCall: async (request, handler) => {
      console.log(`[${config.logLevel}] Model call`);
      return handler(request);
    },
  })
);
```

### 数据库配置格式

在你的经纪人那里 `graphDefinition.middleware` 数组,添加一个 `"custom"` 类型条目 :

```json
{
  "id": "mw-001",
  "type": "custom",
  "name": "Audit Logger",
  "description": "Logs model calls for audit",
  "enabled": true,
  "config": {
    "key": "my-logger",
    "logLevel": "debug"
  }
}
```

这个 `config.key` 必须匹配传递到的密钥 `register()`。所有其它配置字段都转发到您的工厂功能.

### 完整的例子——权限检查中间软件

```typescript
import { createMiddleware, CustomMiddlewareRegistry } from "@axiom-lattice/core";

CustomMiddlewareRegistry.register("permission-check", (config) =>
  createMiddleware({
    name: "PermissionCheck",
    wrapToolCall: async (request, handler) => {
      const toolName = request.toolCall?.name;
      if (toolName && !config.allowedTools.includes(toolName)) {
        return { content: `Tool "${toolName}" is not permitted.` };
      }
      return handler(request);
    },
  })
);
```

数据库配置 :

```json
{
  "id": "perm-001",
  "type": "custom",
  "name": "Tool Permissions",
  "description": "Restrict tool access",
  "enabled": true,
  "config": {
    "key": "permission-check",
    "allowedTools": ["read_file", "write_file"]
  }
}
```

### API 参考

| 方法 | 签署 | 说明 |
| --- | --- | --- |
| `register` | `(key: string, factory: (config: Record<string, any>) => AgentMiddleware | Promise<AgentMiddleware>) => void` | 按密钥注册工厂 |
| `unregister` | `(key: string) => boolean` | 删除注册 |
| `get` | `(key: string) => AgentMiddlewareFactory | undefined` | 找一个工厂 |
| `has` | `(key: string) => boolean` | 检查密钥是否注册 |
| `list` | `() => string[]` | 获取所有已注册的密钥 |

### 重要

-   注册工厂 **在此之前** 建筑代理(通常在应用程序启动时)
-   复制密钥覆盖先前的注册
-   未注册的密钥在构建时带有控制台警告被跳过
-   工厂职能收到原始 `config` 对象(减去 `key`)——自己验证

* * *

## 外部频道集成

核心提供外部信道适配器(Lark,Slack,Email等)所依赖的存储基础设施和绑定系统. 实际的 HTTP 路径和消息发送在 `packages/gateway`,但所有持久性和发送者分辨率都在这里处理.

### 核心内容

| 构成部分 | 地点 | 目的 |
| --- | --- | --- |
| `InMemoryChannelInstallationStore` | `store_lattice/` | 记忆 `ChannelInstallationStore` 执行 |
| `InMemoryBindingStore` | `store_lattice/` | 记忆 `BindingRegistry` 执行 |
| `BindingRegistryHolder` | `bindings_lattice/` | 活动方全球接入器 `BindingRegistry` |
| `manage_binding` 工具 | `tool_lattice/manage_binding/` | 关于发送方对代理方绑定的 CRUD 代理工具 |

### 结构概览

```
External Platform (Lark, Slack, Email)
  → Gateway HTTP route (packages/gateway)
  → ChannelAdapter.receive(rawPayload) → InboundMessage
  → MessageRouter.dispatch() (packages/gateway)
    → BindingRegistry.resolve() ←── core
    → Thread creation / reuse ←── core
    → Agent.addMessage() ←── core
  → ChannelAdapter.sendReply() (packages/gateway)
```

特工留下来 **频道不可知** ——它们只看到标准线程/消息执行.

### 自定义频道开发设置

#### 1\. 注册频道存储

```typescript
import { configureStores } from "@axiom-lattice/core";
import { PostgreSQLChannelInstallationStore, PostgreSQLBindingStore } from "@axiom-lattice/pg-stores";

await configureStores({
  channelInstallation: new PostgreSQLChannelInstallationStore({ pool }),
  channelBinding: new PostgreSQLBindingStore({ pool }),
  // ... other stores
});
```

#### 2\. 设定全球具有约束力的登记程序

```typescript
import { setBindingRegistry } from "@axiom-lattice/core";

const bindingStore = getStoreLattice("default", "channelBinding").store;
setBindingRegistry(bindingStore);
```

#### 3\. 执行通道Adapter(网关)

```typescript
import type { ChannelAdapter, InboundMessage, OutboundMessage, ReplyTarget } from "@axiom-lattice/protocols";
import { z } from "zod";

const slackConfigSchema = z.object({
  botToken: z.string(),
  signingSecret: z.string(),
});

export const slackAdapter: ChannelAdapter = {
  channel: "slack",
  configSchema: slackConfigSchema,

  async receive(rawPayload, installation): Promise<InboundMessage | null> {
    // 1. Parse Slack-specific event
    // 2. Return normalized InboundMessage or null to ignore
    return {
      channel: "slack",
      channelInstallationId: installation.id,
      tenantId: installation.tenantId,
      sender: { id: userId, displayName: userName },
      content: { text: messageText },
      replyTarget: {
        adapterChannel: "slack",
        channelInstallationId: installation.id,
        rawTarget: { channelId, threadTs },
      },
    };
  },

  async sendReply(replyTarget, message, installation): Promise<void> {
    // Use Slack API to send reply
    // replyTarget.rawTarget contains channel-specific context
  },
};
```

#### 4\. 登记路线和适配器(网关)

```typescript
// packages/gateway/src/channels/registry.ts
adapterRegistry.register(slackAdapter);

// packages/gateway/src/channels/routes.ts
app.post("/api/channels/slack/installations/:id/events", async (req, reply) => {
  const installation = await installationStore.getInstallationById(req.params.id);
  const message = await slackAdapter.receive(req.body, installation);
  if (message) await messageRouter.dispatch(message);
});
```

### 具有约束力的分辨率流量

何时 `MessageRouter.dispatch()` 收到一个 `InboundMessage`数字 :

1.  电话 `BindingRegistry.resolve({ channel, senderId, channelInstallationId, tenantId })`
2.  若为 **未找到绑定**数字 :
    -   若为 `installation.rejectWhenNoBinding` 抛出 `BindingNotFoundError`
    -   若为 `installation.fallbackAgentId` • 创建临时倒置约束
3.  若为 **绑定已禁用** ・拒绝
4.  **线索分辨率** (基于 `binding.threadMode`:
    -   `"fixed"` • 重复使用 `binding.threadId`
    -   `"per_conversation"` 总是创造出新的线程
5.  通过 `agent.addMessage()`

### 代理方约束管理

特工可以通过 `manage_binding` 工具:

```typescript
// Agent can call this tool to:
// - list_installations: List available channel installations
// - create: Bind a sender to an agent (channel, senderId, agentId)
// - update: Change agent or threadMode for a binding
// - delete: Remove a binding
// - list: List all bindings with optional filters
```

### 关键类型( 出自 @ axiom- lattice/ protocols)

```typescript
interface ChannelAdapter<TConfig = unknown> {
  readonly channel: string;
  readonly configSchema: z.ZodSchema<TConfig>;
  receive(rawPayload: unknown, installation: ChannelInstallation): Promise<InboundMessage | null>;
  sendReply(replyTarget: ReplyTarget, message: OutboundMessage, installation: ChannelInstallation): Promise<void>;
}

interface Binding {
  id: string;
  channel: string;
  channelInstallationId: string;
  tenantId: string;
  senderId: string;
  agentId: string;
  threadMode: "fixed" | "per_conversation";
  enabled: boolean;
}
```

### 参考执行情况

见 `packages/gateway/src/channels/lark/` 用于完整的生产通道适配器,包括:

-   Webhook 校验和解密
-   事件分析和正常化
-   线程映射( T)`user` 编号 : `group` 编号 : `hybrid` 模式)
-   通过官方SDK提供答复

## 常见问题

### @axiom-lattice/core 是什么？

基于代理应用程序的核心库

### 如何安装 @axiom-lattice/core？

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

### @axiom-lattice/core 支持 TypeScript 吗？

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

### @axiom-lattice/core 支持 ESM 还是 CommonJS？

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

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

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

### @axiom-lattice/core 可以商用吗？

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

### @axiom-lattice/core 的下载量有多少？

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

### @axiom-lattice/core 还在维护吗？

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

