@ashdev/codex-plugin-sdk

中文文档
2.9.0发布于 2026/10/28MITTypeScriptES Module零依赖构建来源已验证近 30 天下载 2053

SDK for building Codex plugins

原始使用文档
文档目录17 节
  1. Installation
  2. Quick Start
  3. Features
  4. Concepts
  5. Capabilities
  6. Protocol Types
  7. Relevance Score
  8. API Reference
  9. createMetadataPlugin(options)
  10. MetadataProvider
  11. Error Handling
  12. Logging
  13. Credentials
  14. Protocol
  15. Building Your Plugin
  16. Example Plugins
  17. License

@ashdev/codex-plugin-sdk

Official SDK for building Codex plugins. Provides type-safe interfaces, utilities, and a server framework for communicating with Codex via JSON-RPC over stdio.

Installation

npm install @ashdev/codex-plugin-sdk

Quick Start

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 });

Features

  • Type-safe: Full TypeScript support with interface contracts
  • Protocol compliance: Types match the Codex JSON-RPC protocol exactly
  • Simple API: Implement the MetadataProvider interface, SDK handles the rest
  • Error handling: Built-in error classes that map to JSON-RPC errors
  • Logging: Safe logging to stderr (stdout is reserved for protocol)

Concepts

Capabilities

Plugins declare capabilities in their manifest. Each capability has a corresponding interface:

CapabilityInterfaceDescription
metadataProviderMetadataProviderSearch and fetch metadata for content

The metadataProvider capability is an array of content types your plugin supports:

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

Supported content types: "series" (future: "book")

Protocol Types

The SDK provides TypeScript types that exactly match the Codex JSON-RPC protocol:

  • MetadataSearchParams / MetadataSearchResponse - Search parameters and results
  • MetadataGetParams / PluginSeriesMetadata - Get full metadata
  • MetadataMatchParams / MetadataMatchResponse - Auto-match content
  • SearchResult - Individual search result with relevanceScore

Relevance Score

Search results must include a relevanceScore between 0.0 and 1.0:

  • 1.0 = Perfect match
  • 0.7-0.9 = Good match
  • 0.5-0.7 = Partial match
  • < 0.5 = Weak match

API Reference

createMetadataPlugin(options)

Creates and starts a metadata provider plugin.

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

MetadataProvider

Interface for metadata provider plugins:

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

Error Handling

Use built-in error classes for proper error responses:

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;
}

Logging

Plugins should log to stderr (stdout is reserved for JSON-RPC):

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);

Credentials

Plugins can receive credentials (API keys, tokens) via the onInitialize callback:

let apiKey: string | undefined;

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

Credentials are configured by admins in Codex and delivered securely to the plugin.

Protocol

Plugins communicate with Codex via JSON-RPC 2.0 over stdio:

  • stdin: Receives JSON-RPC requests (one per line)
  • stdout: Sends JSON-RPC responses (one per line)
  • stderr: Logging output (visible in Codex logs)

Building Your Plugin

  1. Create a new npm package
  2. Install the SDK: npm install @ashdev/codex-plugin-sdk
  3. Implement your provider
  4. Bundle with esbuild (include shebang for npx support):
{
  "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"
  }
}

Key fields for npx support:

  • bin: Points to the entry file, tells npx what to execute
  • --banner:js='#!/usr/bin/env node': Adds shebang so the file is directly executable
  • files: Only publish dist and README to npm

Example Plugins

License

MIT

版本与发布记录

@ashdev/codex-plugin-sdk 共发布 170 个版本,首次发布于 2026/01/31;过去 12 个月发布了 170 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.9.0latest2026/10/2810 天前
2.8.12026/10/2711 天前
2.8.02026/10/2612 天前
2.7.02026/10/1820 天前
2.6.32026/10/031 个月前
2.6.22026/09/291 个月前

关于 @ashdev/codex-plugin-sdk 的常见问题

@ashdev/codex-plugin-sdk 是什么?

SDK for building Codex plugins

如何安装 @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 和提交记录判断。