# @ashdev/codex-plugin-sdk 中文文档

规范地址：https://npmcn.com/package/%40ashdev/codex-plugin-sdk/

版本：2\.9\.0
npm 元数据更新时间：2026-10-28T04:09:19.843Z
中文译文更新时间：2026-11-07T04:16:12.902Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/%40ashdev/codex-plugin-sdk
原文对照：https://npmcn.com/package/%40ashdev/codex-plugin-sdk/?lang=original
项目主页：https://github.com/AshDevFr/codex#readme
源码仓库：https://github.com/AshDevFr/codex

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

- 包体积（解压后）：202 kB，62 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=22\.0\.0
- 运行依赖：0 个
- 首次发布：2026-01-31T06:04:32.299Z
- 最新版本发布：2026-10-28T04:09:19.518Z
- 近 30 天下载量：2053（2026-10-07 至 2026-11-05，npm 官方下载统计）
- 已发布版本数：170（近 12 个月 170 个）

## 中文简介

用于构建 Codex 插件的 SDK

## 安装

```sh
npm install @ashdev/codex-plugin-sdk
```

也可以使用：`pnpm add @ashdev/codex-plugin-sdk`、`yarn add @ashdev/codex-plugin-sdk`、`bun add @ashdev/codex-plugin-sdk`

## README

# @ashdev/codex-plugin-sdk (英语)

用于构建 Codex 插件的官方 SDK. 提供类型安全接口,公用设施,并提供一个服务器框架,通过JSON-RPC在stdio上与Codex通信.

## 安装

```bash
npm install @ashdev/codex-plugin-sdk
```

## 快速启动

```typescript
import {
  createMetadataPlugin,
  type MetadataContentType,
  type MetadataProvider,
  type PluginManifest,
} from "@ashdev/codex-plugin-sdk";

// Define your plugin manifest
const manifest = {
  name: "metadata-my-plugin",
  displayName: "My Plugin",
  version: "1.0.0",
  description: "A custom metadata provider",
  author: "Your Name",
  protocolVersion: "1.0",
  capabilities: {
    metadataProvider: ["series"] as MetadataContentType[],
  },
} as const satisfies PluginManifest & {
  capabilities: { metadataProvider: MetadataContentType[] };
};

// Implement the MetadataProvider interface
const provider: MetadataProvider = {
  async search(params) {
    // Search your data source
    return {
      results: [
        {
          externalId: "123",
          title: "Example Series",
          alternateTitles: [],
          relevanceScore: 0.95,
          preview: {
            status: "ongoing",
            genres: ["Action", "Adventure"],
          },
        },
      ],
    };
  },

  async get(params) {
    // Fetch full metadata
    return {
      externalId: params.externalId,
      externalUrl: `https://example.com/series/${params.externalId}`,
      title: "Example Series",
      alternateTitles: [],
      summary: "An exciting series...",
      status: "ongoing",
      year: 2024,
      genres: ["Action", "Adventure"],
      tags: [],
      authors: ["Author Name"],
      artists: [],
      externalLinks: [],
    };
  },

  // Optional: implement match for auto-matching during library scans
  async match(params) {
    const result = await this.search({
      query: params.title,
    });

    return {
      match: result.results[0] ?? null,
      confidence: result.results[0] ? 0.8 : 0,
    };
  },
};

// Start the plugin
createMetadataPlugin({ manifest, provider });
```

## 特征

-   **类型安全**: 有接口合同的完整类型脚本支持
-   **议定书遵守情况**: 类型完全符合 Codex JSON- RPC 协议
-   **简单 API**: 执行 `MetadataProvider` 界面, SDK 处理其余部分
-   **处理错误**: 内建错误类, 映射到 JSON- RPC 错误
-   **日志**: 安全记录到 stderr( stdout 保留用于协议)

## 概念

### 能力

插件在其清单中声明能力。 每个能力都有相应的接口:

| 能力 | 接口 | 说明 |
| --- | --- | --- |
| `metadataProvider` | `MetadataProvider` | 搜索和获取内容元数据 |

这个 `metadataProvider` 能力是您插件支持的一系列内容类型:

```typescript
capabilities: {
  metadataProvider: ["series"] as MetadataContentType[],
}
```

支持的内容类型 : `"series"` (未来: `"book"`(中文(简体) )

### 协议类型

SDK提供了完全符合"代码JSON-RPC"协议的TypeScript类型:

-   `MetadataSearchParams` 编号 : `MetadataSearchResponse` - 搜索参数和结果
-   `MetadataGetParams` 编号 : `PluginSeriesMetadata` - 获取完整的元数据
-   `MetadataMatchParams` 编号 : `MetadataMatchResponse` - 自动匹配内容
-   `SearchResult` - 个人搜索结果 `relevanceScore`

### 相关性分数

搜索结果必须包括 `relevanceScore` 0.0至1.0之间:

-   `1.0` = 完美匹配 (中文(简体) )
-   `0.7-0.9` = 匹配不错
-   `0.5-0.7` = 部分匹配数
-   `< 0.5` = 较弱

## API 参考

### `createMetadataPlugin(options)`

创建并启动元数据提供者插件 .

```typescript
interface MetadataPluginOptions {
  manifest: PluginManifest & { capabilities: { metadataProvider: MetadataContentType[] } };
  provider: MetadataProvider;
  onInitialize?: (params: InitializeParams) => void | Promise<void>;
  logLevel?: "debug" | "info" | "warn" | "error";
}
```

### `MetadataProvider`

元数据提供者插件接口 :

```typescript
interface MetadataProvider {
  search(params: MetadataSearchParams): Promise<MetadataSearchResponse>;
  get(params: MetadataGetParams): Promise<PluginSeriesMetadata>;
  match?(params: MetadataMatchParams): Promise<MetadataMatchResponse>;
}
```

### 处理错误

使用内置错误类进行正确的错误响应 :

```typescript
import { NotFoundError, RateLimitError, AuthError, ApiError } from "@ashdev/codex-plugin-sdk";

// In your provider:
async get(params) {
  const data = await fetchFromApi(params.externalId);

  if (!data) {
    throw new NotFoundError(`Series ${params.externalId} not found`);
  }

  return data;
}
```

### 日志

插件应登录为 stderr( stdout 保留给 JSON- RPC) :

```typescript
import { createLogger } from "@ashdev/codex-plugin-sdk";

const logger = createLogger({ name: "my-plugin", level: "debug" });
logger.info("Plugin started");
logger.debug("Processing request", { query: "..." });
logger.error("Failed to fetch", error);
```

## 全权证书

插件可以通过 `onInitialize` 回调 :

```typescript
let apiKey: string | undefined;

createMetadataPlugin({
  manifest,
  provider,
  onInitialize(params) {
    apiKey = params.credentials?.api_key;
  },
});
```

身份证明由 Codex 中的管理员配置,并安全地发送给插件.

## 议定书

插件通过 JSON-RPC 2. 0 与 Codex 通信 :

-   **静态**:接收JSON-RPC请求(每行1个)
-   **静态**:发送JSON-RPC的回复(每行1个)
-   **标准**: 日志输出( 在 Codex 日志中可见)

## 构建您的插件

1.  创建新 npm 软件包
2.  安装 SDK : `npm install @ashdev/codex-plugin-sdk`
3.  执行您的提供者
4.  装入建置( 包括 shebang 用于 npx 支持) :

```json
{
  "name": "@your-org/plugin-metadata-example",
  "version": "1.0.0",
  "main": "dist/index.js",
  "bin": "dist/index.js",
  "type": "module",
  "files": ["dist", "README.md"],
  "engines": {
    "node": ">=22.0.0"
  },
  "scripts": {
    "build": "esbuild src/index.ts --bundle --platform=node --target=node22 --format=esm --outfile=dist/index.js --sourcemap --banner:js='#!/usr/bin/env node'",
    "prepublishOnly": "npm run lint && npm run build"
  }
}
```

**Npx 支持的关键字段 :**

-   `bin`: 指向条目文件, 告诉 npx 执行什么
-   `--banner:js='#!/usr/bin/env node'`: 添加 shebang 以直接执行文件
-   `files`: 只发布 dist 和 README 到 npm

## 示例插件

-   [`@ashdev/codex-plugin-metadata-echo`](https://github.com/AshDevFr/codex/tree/main/plugins/metadata-echo) - 测试回放查询的元数据插件
-   [`@ashdev/codex-plugin-metadata-mangabaka`](https://github.com/AshDevFr/codex/tree/main/plugins/metadata-mangabaka) - 曼加巴卡元数据供应商

## 许可证

麻省理工学院

## 常见问题

### @ashdev/codex-plugin-sdk 是什么？

用于构建 Codex 插件的 SDK

### 如何安装 @ashdev/codex-plugin-sdk？

在项目目录运行 npm install @ashdev/codex-plugin-sdk，或使用 pnpm add / yarn add / bun add。

### @ashdev/codex-plugin-sdk 支持 TypeScript 吗？

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

### @ashdev/codex-plugin-sdk 支持 ESM 还是 CommonJS？

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

### @ashdev/codex-plugin-sdk 需要什么版本的 Node\.js？

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

### @ashdev/codex-plugin-sdk 可以商用吗？

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

### @ashdev/codex-plugin-sdk 的下载量有多少？

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

### @ashdev/codex-plugin-sdk 还在维护吗？

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

