Getting Started with the Codex SDK: TypeScript Calls, Streaming Events, and Thread Resumption

Use @openai/codex-sdk to run a read-only task, handle streaming events, and resume threads. Covers Node.js requirements, the Git working directory, authentication, and troubleshooting failures.

5 分钟阅读
Getting Started with the Codex SDK: TypeScript Calls, Streaming Events, and Thread Resumption

The Codex SDK lets a Node.js program start, continue, and resume local Codex threads. For your first integration, complete one read-only task, then add event logging and thread resumption. Don't start by letting the program edit code or publish results automatically. This article focuses on the TypeScript interface of @openai/codex-sdk, and the information was checked on October 12, 2026.

How the SDK Differs from a Regular Model API

The TypeScript SDK wraps the Codex CLI and exchanges JSONL events over standard input and output. What it runs is a coding agent with project context and tool capabilities, not a plain chat request sent to a model. The official SDK page lists CI automation as a suitable use case. If you need to build a full client with authentication, approvals, and session management, evaluate the Codex app server separately.

Prepare Node.js, the Project Directory, and Authentication

The official docs require Node.js 18 or later. Try it first in a temporary Git project, prepare a README.md, and confirm that Codex authentication works for the user running the process. The SDK inherits the Node.js process environment by default. If your service process and your terminal use different accounts or environments, their login and configuration may differ.

text
node --version
npm init -y
npm install @openai/codex-sdk
git init

If the directory is already a Git repository, don't initialize it again. Record the output of npm ls @openai/codex-sdk and keep the lockfile, so later troubleshooting can refer to the installed version.

Run Your First Read-Only Thread

Save the following lines in order as example.mjs, then run node example.mjs in the project directory. The example is written from the official interface and has not been verified with a real model call. The read-only requirement is written into the task, and you should also constrain tools with the permission limits of the runtime environment.

text
import { Codex } from "@openai/codex-sdk";
const codex = new Codex();
const thread = codex.startThread({ workingDirectory: process.cwd() });
try {
  const turn = await thread.run("只读取 README.md,使用中文说明启动方法;不修改文件,不执行安装命令。");
  console.log(turn.finalResponse);
  console.log('thread ID:', thread.id);
} catch (error) {
  console.error(error instanceof Error ? error.message : String(error));
  process.exitCode = 1;
}

For acceptance, check whether the final answer cites the actual README, and confirm that git status --short shows no unexpected changes. Getting an answer only means the turn returned a result. It doesn't mean the content is correct, and it doesn't prove that all tool permissions are as expected.

Receive Intermediate Events with runStreamed

run() buffers events until the turn ends. To show intermediate status, switch to runStreamed() and iterate over events. Save the complete example below as stream.mjs and run node stream.mjs. Don't append it to the previous file, which would cause duplicate variable declarations.

text
import { Codex } from "@openai/codex-sdk";
const codex = new Codex();
const thread = codex.startThread({ workingDirectory: process.cwd() });
let completed = false;
try {
  const { events } = await thread.runStreamed("只读取 README.md,概述启动方法;不修改文件,不执行命令。");
  for await (const event of events) {
    if (event.type === "thread.started") console.log("thread ID:", event.thread_id);
    if (event.type === "item.completed" && event.item.type === "agent_message") {
      console.log(event.item.text);
    }
    if (event.type === "turn.completed") {
      completed = true;
      console.log("usage:", event.usage);
    }
    if (event.type === "turn.failed") throw new Error(event.error.message);
    if (event.type === "error") throw new Error(event.message);
  }
  if (!completed) throw new Error("本轮没有收到 turn.completed");
} catch (error) {
  console.error(error instanceof Error ? error.message : String(error));
  process.exitCode = 1;
}

On success, you should get the thread ID, the agent's text, and the usage that comes with turn.completed. Treat failure events, exceptions, and a missing completion event all as failures. Empty text shouldn't be counted as a completed task. Printing the answer here is only for an example project with no sensitive data. In production, redact logs and limit how long they are retained.

Continue a Thread and Resume After a Restart

Within the same process, calling run() on the same thread again continues that thread. For example, first ask how to start the app, then ask it to explain only the test command. For an unrelated project or task, create a new thread so old context doesn't affect the answer.

text
const next = await thread.run("根据刚才读取的资料,只解释测试命令,不执行。");
console.log(next.finalResponse);

After a process restart, call resumeThread() with the saved thread ID. Threads are stored in ~/.codex/sessions. Resuming also depends on the same running account and the corresponding session files, so saving an ID alone won't move a thread to another server.

text
const savedId = process.env.CODEX_THREAD_ID;
if (!savedId) throw new Error("请设置 CODEX_THREAD_ID");
const resumed = codex.resumeThread(savedId);
const resumedTurn = await resumed.run("继续说明测试步骤,只读,不执行命令。");
console.log(resumedTurn.finalResponse);

A thread ID is the entry point to a past session, not an idempotency key for a business task. Store business_task_id, thread_id, the SDK version, and the success or failure status of the latest turn separately. Resuming a thread only continues the context. It doesn't prove whether the last write finished. Before retrying a write operation, check the existing artifacts.

How to Locate Common Failures

Authentication failure: confirm the account that launched Node.js, its environment variables, and the Codex login method, and troubleshoot from the full error. Don't treat a third-party key as an official credential. Wrong working directory: confirm that workingDirectory exists and points to the target Git repository. skipGitRepoCheck only skips the repository check. It doesn't fix the directory or its permissions. No final result: distinguish between turn.failed, exceptions, process exit, and timeouts. Don't record a task without turn.completed as successful.

If your service sets a wait timeout, also make clear whether it actually terminates the underlying task. Before resubmitting a task that writes files, check the workspace and existing artifacts to prevent duplicate execution. This article doesn't treat a network reconnect as a safe retry.

From Starter Examples to Maintainable Automation

First verify one read-only task, one streaming run, and one thread resumption. After that, add business task IDs, log redaction, and duplicate-execution checks for write operations. Model provider configuration is a separate integration layer, and you can continue with the API key configuration guide on this site. The SDK itself doesn't require a third-party platform.

If the SDK starts but model authentication fails, first check the provider configuration that the running process actually reads. If you need server-side integration with AICodeWith, you can reuse its Codex-specific configuration and check call records by time. This doesn't change the SDK's thread API, and it doesn't mean every model is compatible with Codex.

AICodeWith's Codex-Specific Integration Method

Related Resources

Official Codex SDK Documentation

Official TypeScript SDK README

Codex API Key Configuration Guide

相关文章

How to Use Agent Autoloop: Let Claude Code / Codex Pick Up Work in the Background and Ask You Only When Needed (Install, rules.json, Hands-on)

How to Use Agent Autoloop: Let Claude Code / Codex Pick Up Work in the Background and Ask You Only When Needed (Install, rules.json, Hands-on)

Agent Autoloop turns Claude Code, Codex, and similar CLI agents into a background loop—events or cron dispatch work, the agent exits after each round, and you get a card only when a decision is yours. This guide follows the official README and SECURITY docs, walks through install plus our measured try → answer → status loop, a morning-brief rules.json example, aicodewith API Key setup, and unattended-security boundaries.

How to Use Cursor Live Apps: Build, Provision a Database, Pass Security Checks, and Share a Link with Cloud Agent

How to Use Cursor Live Apps: Build, Provision a Database, Pass Security Checks, and Share a Link with Cloud Agent

According to @cursor_ai and Cursor's official docs, Cursor Live Apps let a Cloud Agent build a web app (dashboard, portal, or microsite) from a description, with hosting, Postgres, auth, and Secrets included. You preview first, pick a URL, and only get a shareable live link after deterministic and agentic security checks pass. This guide walks through the official steps and records what we saw when we opened the official demo URL. It is for readers who want Cursor Apps deployment, a Cloud Agent share link, or a one-click publish path.