Skip to content
FunCoding

Search

Search docs, Skills and MCP

TypeScript SDK

在服务端创建与恢复线程,处理流式事件,约束输出并设置工作目录。

This page has not been translated into English yet. The original Chinese version is shown below.

TypeScript SDK 包装 @openai/codex CLI,通过 stdin/stdout 交换 JSONL 事件。它要求 Node.js 18 或更高版本,运行位置是服务端。

创建线程并运行

npm install @openai/codex-sdk
import { Codex } from "@openai/codex-sdk";

const codex = new Codex();
const thread = codex.startThread();
const turn = await thread.run("Diagnose the test failure and propose a fix");
console.log(turn.finalResponse);
console.log(turn.items);

再次调用同一 thread.run() 会继续讨论。进程重启后,有已保存的 thread ID 时可以用 codex.resumeThread(threadId) 重建对象,再运行下一步。

处理流式进展

run() 缓冲事件直到回合结束;需要逐步处理工具调用、文件变化或输出时,用 runStreamed():

const { events } = await thread.runStreamed("Diagnose the test failure and propose a fix");
for await (const event of events) {
  switch (event.type) {
    case "item.completed":
      console.log("item", event.item);
      break;
    case "turn.completed":
      console.log("usage", event.usage);
      break;
  }
}

不要把某个 item 完成当作整个 turn 完成;应按事件类型更新应用状态。

约束最后输出

每回合可通过 outputSchema 传 JSON Schema:

const schema = {
  type: "object",
  properties: {
    summary: { type: "string" },
    status: { type: "string", enum: ["ok", "action_required"] },
  },
  required: ["summary", "status"],
  additionalProperties: false,
} as const;

const result = await thread.run("Summarize repository status", { outputSchema: schema });
console.log(result.finalResponse);

工作目录与环境

默认工作目录是当前进程目录,且要求属于 Git 仓库。startThread({ workingDirectory: "/path/to/project" }) 指定项目;确需在非 Git 目录运行时再传 skipGitRepoCheck: true。

创建 Codex 时的 env 控制传给 CLI 的环境,SDK 仍会补入自身必需变量。config 对象会转为点路径和 TOML 参数;不能用点路径表达的配置可通过 configOverrides 传原始 TOML。原始覆盖高于结构化 config,SDK 自己管理的设置和线程选项随后应用,优先级更高。