Skip to content

SDK 与 IDE 集成 — 概念

SDK 架构

Codex 提供两个 SDK——TypeScript 和 Python——采用了截然不同的集成架构:

两种 SDK 的架构对比:

维度TypeScript SDKPython SDK
通信方式子进程(codex execJSON-RPC 直连
进程模型启动独立进程启动/连接 App Server
异步支持Promise/async-await同步 + 异步双 API
输出格式JSON Lines 解析结构化事件流
配置方式CodexOptionsCodexConfig

IDE 集成方式

SDK 为 IDE 插件(如 VS Code、JetBrains)提供了集成接口:

IDE 集成的关键设计决策:

  1. TypeScript SDK 适用于基于 Node.js 的 IDE(VS Code),通过 codex exec --experimental-json 子进程模式运行,每个请求启动新的执行周期
  2. Python SDK 适用于 Python 环境,直接使用 App Server Protocol 的 JSON-RPC 协议通信,支持持久连接
  3. 两者都通过 App Server Protocol 与核心通信,确保功能一致性

API 设计

TypeScript SDK API

typescript
class Codex {
    constructor(options?: CodexOptions)

    // 启动新线程
    startThread(options?: ThreadOptions): Thread

    // 恢复已有线程
    resumeThread(id: string, options?: ThreadOptions): Thread
}

Python SDK API

Python SDK 提供同步和异步两套完整 API:

python
# 同步 API
class Codex:
    def start_thread(self, **kwargs) -> Thread: ...
    def resume_thread(self, id: str) -> Thread: ...

class Thread:
    def turn(self, input: Input) -> TurnHandle: ...
    def close(self): ...

class TurnHandle:
    def result(self) -> TurnResult: ...
    def events(self) -> Iterator[ThreadEvent]: ...

# 异步 API
class AsyncCodex:
    async def start_thread(self, **kwargs) -> AsyncThread: ...

class AsyncThread:
    async def turn(self, input: Input) -> AsyncTurnHandle: ...

class AsyncTurnHandle:
    async def result(self) -> TurnResult: ...
    async def events(self) -> AsyncIterator[ThreadEvent]: ...

Python SDK 的输入类型系统:

类型说明
Input统一输入类型
InputItem单个输入条目
RunInput运行输入
TextInput文本消息
ImageInput远程图片 URL
LocalImageInput本地图片文件
SkillInput技能调用
MentionInput提及(@引用)

类型系统

Python SDK 的配置和错误类型:

python
# 配置
class CodexConfig:
    model: str | None
    approval_mode: ApprovalMode  # suggest / auto-edit / full-auto
    sandbox: Sandbox             # off / platform / docker

# 错误层级
CodexError                    # 基础错误
├── TransportClosedError      # 传输关闭
├── JsonRpcError              # JSON-RPC 协议错误
│   ├── ParseError            # 解析错误
│   ├── InvalidRequestError   # 无效请求
│   ├── MethodNotFoundError   # 方法未找到
│   ├── InvalidParamsError    # 参数无效
│   └── InternalRpcError      # 服务器内部错误
├── CodexRpcError             # Codex 特定 RPC 错误
│   ├── ServerBusyError       # 服务器繁忙
│   └── RetryLimitExceededError  # 重试超限

错误处理工具:

python
def retry_on_overload(fn, *, max_retries=3):
    """自动重试可恢复的错误(ServerBusyError 等)"""

def is_retryable_error(error: CodexError) -> bool:
    """判断错误是否可重试"""

相关概念