codex-sdk-ts 0.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +158 -0
- package/dist/index.d.ts +273 -0
- package/dist/index.js +388 -0
- package/dist/index.js.map +1 -0
- package/package.json +71 -0
package/README.md
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
# codex-sdk-ts
|
|
2
|
+
|
|
3
|
+
Lightweight TypeScript SDK for the OpenAI Codex agent.
|
|
4
|
+
|
|
5
|
+
This is a fork of the official `@openai/codex-sdk` that **does not bundle the Codex binary**. Instead, it uses the system-installed `codex` command from PATH.
|
|
6
|
+
|
|
7
|
+
## Prerequisites
|
|
8
|
+
|
|
9
|
+
Before using this SDK, you must have the Codex CLI installed and available in your system PATH:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
# Install Codex CLI (see https://github.com/openai/codex for details)
|
|
13
|
+
npm install -g @openai/codex
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Installation
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npm install codex-sdk-ts
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Requires Node.js 18+.
|
|
23
|
+
|
|
24
|
+
## Quickstart
|
|
25
|
+
|
|
26
|
+
```typescript
|
|
27
|
+
import { Codex } from "codex-sdk-ts";
|
|
28
|
+
|
|
29
|
+
const codex = new Codex();
|
|
30
|
+
const thread = codex.startThread();
|
|
31
|
+
const turn = await thread.run("Diagnose the test failure and propose a fix");
|
|
32
|
+
|
|
33
|
+
console.log(turn.finalResponse);
|
|
34
|
+
console.log(turn.items);
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Call `run()` repeatedly on the same `Thread` instance to continue that conversation.
|
|
38
|
+
|
|
39
|
+
```typescript
|
|
40
|
+
const nextTurn = await thread.run("Implement the fix");
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### Streaming responses
|
|
44
|
+
|
|
45
|
+
`run()` buffers events until the turn finishes. To react to intermediate progress—tool calls, streaming responses, and file change notifications—use `runStreamed()` instead, which returns an async generator of structured events.
|
|
46
|
+
|
|
47
|
+
```typescript
|
|
48
|
+
const { events } = await thread.runStreamed("Diagnose the test failure and propose a fix");
|
|
49
|
+
|
|
50
|
+
for await (const event of events) {
|
|
51
|
+
switch (event.type) {
|
|
52
|
+
case "item.completed":
|
|
53
|
+
console.log("item", event.item);
|
|
54
|
+
break;
|
|
55
|
+
case "turn.completed":
|
|
56
|
+
console.log("usage", event.usage);
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### Structured output
|
|
63
|
+
|
|
64
|
+
The Codex agent can produce a JSON response that conforms to a specified schema. The schema can be provided for each turn as a plain JSON object.
|
|
65
|
+
|
|
66
|
+
```typescript
|
|
67
|
+
const schema = {
|
|
68
|
+
type: "object",
|
|
69
|
+
properties: {
|
|
70
|
+
summary: { type: "string" },
|
|
71
|
+
status: { type: "string", enum: ["ok", "action_required"] },
|
|
72
|
+
},
|
|
73
|
+
required: ["summary", "status"],
|
|
74
|
+
additionalProperties: false,
|
|
75
|
+
} as const;
|
|
76
|
+
|
|
77
|
+
const turn = await thread.run("Summarize repository status", { outputSchema: schema });
|
|
78
|
+
console.log(turn.finalResponse);
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
You can also create a JSON schema from a [Zod schema](https://github.com/colinhacks/zod) using the [`zod-to-json-schema`](https://www.npmjs.com/package/zod-to-json-schema) package and setting the `target` to `"openAi"`.
|
|
82
|
+
|
|
83
|
+
```typescript
|
|
84
|
+
const schema = z.object({
|
|
85
|
+
summary: z.string(),
|
|
86
|
+
status: z.enum(["ok", "action_required"]),
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
const turn = await thread.run("Summarize repository status", {
|
|
90
|
+
outputSchema: zodToJsonSchema(schema, { target: "openAi" }),
|
|
91
|
+
});
|
|
92
|
+
console.log(turn.finalResponse);
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### Attaching images
|
|
96
|
+
|
|
97
|
+
Provide structured input entries when you need to include images alongside text. Text entries are concatenated into the final prompt while image entries are passed to the Codex CLI via `--image`.
|
|
98
|
+
|
|
99
|
+
```typescript
|
|
100
|
+
const turn = await thread.run([
|
|
101
|
+
{ type: "text", text: "Describe these screenshots" },
|
|
102
|
+
{ type: "local_image", path: "./ui.png" },
|
|
103
|
+
{ type: "local_image", path: "./diagram.jpg" },
|
|
104
|
+
]);
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### Resuming an existing thread
|
|
108
|
+
|
|
109
|
+
Threads are persisted in `~/.codex/sessions`. If you lose the in-memory `Thread` object, reconstruct it with `resumeThread()` and keep going.
|
|
110
|
+
|
|
111
|
+
```typescript
|
|
112
|
+
const savedThreadId = process.env.CODEX_THREAD_ID!;
|
|
113
|
+
const thread = codex.resumeThread(savedThreadId);
|
|
114
|
+
await thread.run("Implement the fix");
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
### Working directory controls
|
|
118
|
+
|
|
119
|
+
Codex runs in the current working directory by default. To avoid unrecoverable errors, Codex requires the working directory to be a Git repository. You can skip the Git repository check by passing the `skipGitRepoCheck` option when creating a thread.
|
|
120
|
+
|
|
121
|
+
```typescript
|
|
122
|
+
const thread = codex.startThread({
|
|
123
|
+
workingDirectory: "/path/to/project",
|
|
124
|
+
skipGitRepoCheck: true,
|
|
125
|
+
});
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
### Controlling the Codex CLI environment
|
|
129
|
+
|
|
130
|
+
By default, the Codex CLI inherits the Node.js process environment. Provide the optional `env` parameter when instantiating the
|
|
131
|
+
`Codex` client to fully control which variables the CLI receives—useful for sandboxed hosts like Electron apps.
|
|
132
|
+
|
|
133
|
+
```typescript
|
|
134
|
+
const codex = new Codex({
|
|
135
|
+
env: {
|
|
136
|
+
PATH: "/usr/local/bin",
|
|
137
|
+
},
|
|
138
|
+
});
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
The SDK still injects its required variables (such as `OPENAI_BASE_URL` and `CODEX_API_KEY`) on top of the environment you
|
|
142
|
+
provide.
|
|
143
|
+
|
|
144
|
+
### Passing `--config` overrides
|
|
145
|
+
|
|
146
|
+
Use the `config` option to provide additional Codex CLI configuration overrides. The SDK accepts a JSON object, flattens it
|
|
147
|
+
into dotted paths, and serializes values as TOML literals before passing them as repeated `--config key=value` flags.
|
|
148
|
+
|
|
149
|
+
```typescript
|
|
150
|
+
const codex = new Codex({
|
|
151
|
+
config: {
|
|
152
|
+
show_raw_agent_reasoning: true,
|
|
153
|
+
sandbox_workspace_write: { network_access: true },
|
|
154
|
+
},
|
|
155
|
+
});
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
Thread options still take precedence for overlapping settings because they are emitted after these global overrides.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import { ContentBlock } from '@modelcontextprotocol/sdk/types.js';
|
|
2
|
+
|
|
3
|
+
/** The status of a command execution. */
|
|
4
|
+
type CommandExecutionStatus = "in_progress" | "completed" | "failed";
|
|
5
|
+
/** A command executed by the agent. */
|
|
6
|
+
type CommandExecutionItem = {
|
|
7
|
+
id: string;
|
|
8
|
+
type: "command_execution";
|
|
9
|
+
/** The command line executed by the agent. */
|
|
10
|
+
command: string;
|
|
11
|
+
/** Aggregated stdout and stderr captured while the command was running. */
|
|
12
|
+
aggregated_output: string;
|
|
13
|
+
/** Set when the command exits; omitted while still running. */
|
|
14
|
+
exit_code?: number;
|
|
15
|
+
/** Current status of the command execution. */
|
|
16
|
+
status: CommandExecutionStatus;
|
|
17
|
+
};
|
|
18
|
+
/** Indicates the type of the file change. */
|
|
19
|
+
type PatchChangeKind = "add" | "delete" | "update";
|
|
20
|
+
/** A set of file changes by the agent. */
|
|
21
|
+
type FileUpdateChange = {
|
|
22
|
+
path: string;
|
|
23
|
+
kind: PatchChangeKind;
|
|
24
|
+
};
|
|
25
|
+
/** The status of a file change. */
|
|
26
|
+
type PatchApplyStatus = "completed" | "failed";
|
|
27
|
+
/** A set of file changes by the agent. Emitted once the patch succeeds or fails. */
|
|
28
|
+
type FileChangeItem = {
|
|
29
|
+
id: string;
|
|
30
|
+
type: "file_change";
|
|
31
|
+
/** Individual file changes that comprise the patch. */
|
|
32
|
+
changes: FileUpdateChange[];
|
|
33
|
+
/** Whether the patch ultimately succeeded or failed. */
|
|
34
|
+
status: PatchApplyStatus;
|
|
35
|
+
};
|
|
36
|
+
/** The status of an MCP tool call. */
|
|
37
|
+
type McpToolCallStatus = "in_progress" | "completed" | "failed";
|
|
38
|
+
/**
|
|
39
|
+
* Represents a call to an MCP tool. The item starts when the invocation is dispatched
|
|
40
|
+
* and completes when the MCP server reports success or failure.
|
|
41
|
+
*/
|
|
42
|
+
type McpToolCallItem = {
|
|
43
|
+
id: string;
|
|
44
|
+
type: "mcp_tool_call";
|
|
45
|
+
/** Name of the MCP server handling the request. */
|
|
46
|
+
server: string;
|
|
47
|
+
/** The tool invoked on the MCP server. */
|
|
48
|
+
tool: string;
|
|
49
|
+
/** Arguments forwarded to the tool invocation. */
|
|
50
|
+
arguments: unknown;
|
|
51
|
+
/** Result payload returned by the MCP server for successful calls. */
|
|
52
|
+
result?: {
|
|
53
|
+
content: ContentBlock[];
|
|
54
|
+
structured_content: unknown;
|
|
55
|
+
};
|
|
56
|
+
/** Error message reported for failed calls. */
|
|
57
|
+
error?: {
|
|
58
|
+
message: string;
|
|
59
|
+
};
|
|
60
|
+
/** Current status of the tool invocation. */
|
|
61
|
+
status: McpToolCallStatus;
|
|
62
|
+
};
|
|
63
|
+
/** Response from the agent. Either natural-language text or JSON when structured output is requested. */
|
|
64
|
+
type AgentMessageItem = {
|
|
65
|
+
id: string;
|
|
66
|
+
type: "agent_message";
|
|
67
|
+
/** Either natural-language text or JSON when structured output is requested. */
|
|
68
|
+
text: string;
|
|
69
|
+
};
|
|
70
|
+
/** Agent's reasoning summary. */
|
|
71
|
+
type ReasoningItem = {
|
|
72
|
+
id: string;
|
|
73
|
+
type: "reasoning";
|
|
74
|
+
text: string;
|
|
75
|
+
};
|
|
76
|
+
/** Captures a web search request. Completes when results are returned to the agent. */
|
|
77
|
+
type WebSearchItem = {
|
|
78
|
+
id: string;
|
|
79
|
+
type: "web_search";
|
|
80
|
+
query: string;
|
|
81
|
+
};
|
|
82
|
+
/** Describes a non-fatal error surfaced as an item. */
|
|
83
|
+
type ErrorItem = {
|
|
84
|
+
id: string;
|
|
85
|
+
type: "error";
|
|
86
|
+
message: string;
|
|
87
|
+
};
|
|
88
|
+
/** An item in the agent's to-do list. */
|
|
89
|
+
type TodoItem = {
|
|
90
|
+
text: string;
|
|
91
|
+
completed: boolean;
|
|
92
|
+
};
|
|
93
|
+
/**
|
|
94
|
+
* Tracks the agent's running to-do list. Starts when the plan is issued, updates as steps change,
|
|
95
|
+
* and completes when the turn ends.
|
|
96
|
+
*/
|
|
97
|
+
type TodoListItem = {
|
|
98
|
+
id: string;
|
|
99
|
+
type: "todo_list";
|
|
100
|
+
items: TodoItem[];
|
|
101
|
+
};
|
|
102
|
+
/** Canonical union of thread items and their type-specific payloads. */
|
|
103
|
+
type ThreadItem = AgentMessageItem | ReasoningItem | CommandExecutionItem | FileChangeItem | McpToolCallItem | WebSearchItem | TodoListItem | ErrorItem;
|
|
104
|
+
|
|
105
|
+
/** Emitted when a new thread is started as the first event. */
|
|
106
|
+
type ThreadStartedEvent = {
|
|
107
|
+
type: "thread.started";
|
|
108
|
+
/** The identifier of the new thread. Can be used to resume the thread later. */
|
|
109
|
+
thread_id: string;
|
|
110
|
+
};
|
|
111
|
+
/**
|
|
112
|
+
* Emitted when a turn is started by sending a new prompt to the model.
|
|
113
|
+
* A turn encompasses all events that happen while the agent is processing the prompt.
|
|
114
|
+
*/
|
|
115
|
+
type TurnStartedEvent = {
|
|
116
|
+
type: "turn.started";
|
|
117
|
+
};
|
|
118
|
+
/** Describes the usage of tokens during a turn. */
|
|
119
|
+
type Usage = {
|
|
120
|
+
/** The number of input tokens used during the turn. */
|
|
121
|
+
input_tokens: number;
|
|
122
|
+
/** The number of cached input tokens used during the turn. */
|
|
123
|
+
cached_input_tokens: number;
|
|
124
|
+
/** The number of output tokens used during the turn. */
|
|
125
|
+
output_tokens: number;
|
|
126
|
+
};
|
|
127
|
+
/** Emitted when a turn is completed. Typically right after the assistant's response. */
|
|
128
|
+
type TurnCompletedEvent = {
|
|
129
|
+
type: "turn.completed";
|
|
130
|
+
usage: Usage;
|
|
131
|
+
};
|
|
132
|
+
/** Indicates that a turn failed with an error. */
|
|
133
|
+
type TurnFailedEvent = {
|
|
134
|
+
type: "turn.failed";
|
|
135
|
+
error: ThreadError;
|
|
136
|
+
};
|
|
137
|
+
/** Emitted when a new item is added to the thread. Typically the item is initially "in progress". */
|
|
138
|
+
type ItemStartedEvent = {
|
|
139
|
+
type: "item.started";
|
|
140
|
+
item: ThreadItem;
|
|
141
|
+
};
|
|
142
|
+
/** Emitted when an item is updated. */
|
|
143
|
+
type ItemUpdatedEvent = {
|
|
144
|
+
type: "item.updated";
|
|
145
|
+
item: ThreadItem;
|
|
146
|
+
};
|
|
147
|
+
/** Signals that an item has reached a terminal state—either success or failure. */
|
|
148
|
+
type ItemCompletedEvent = {
|
|
149
|
+
type: "item.completed";
|
|
150
|
+
item: ThreadItem;
|
|
151
|
+
};
|
|
152
|
+
/** Fatal error emitted by the stream. */
|
|
153
|
+
type ThreadError = {
|
|
154
|
+
message: string;
|
|
155
|
+
};
|
|
156
|
+
/** Represents an unrecoverable error emitted directly by the event stream. */
|
|
157
|
+
type ThreadErrorEvent = {
|
|
158
|
+
type: "error";
|
|
159
|
+
message: string;
|
|
160
|
+
};
|
|
161
|
+
/** Top-level JSONL events emitted by codex exec. */
|
|
162
|
+
type ThreadEvent = ThreadStartedEvent | TurnStartedEvent | TurnCompletedEvent | TurnFailedEvent | ItemStartedEvent | ItemUpdatedEvent | ItemCompletedEvent | ThreadErrorEvent;
|
|
163
|
+
|
|
164
|
+
type TurnOptions = {
|
|
165
|
+
/** JSON schema describing the expected agent output. */
|
|
166
|
+
outputSchema?: unknown;
|
|
167
|
+
/** AbortSignal to cancel the turn. */
|
|
168
|
+
signal?: AbortSignal;
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
/** Completed turn. */
|
|
172
|
+
type Turn = {
|
|
173
|
+
items: ThreadItem[];
|
|
174
|
+
finalResponse: string;
|
|
175
|
+
usage: Usage | null;
|
|
176
|
+
};
|
|
177
|
+
/** Alias for `Turn` to describe the result of `run()`. */
|
|
178
|
+
type RunResult = Turn;
|
|
179
|
+
/** The result of the `runStreamed` method. */
|
|
180
|
+
type StreamedTurn = {
|
|
181
|
+
events: AsyncGenerator<ThreadEvent>;
|
|
182
|
+
};
|
|
183
|
+
/** Alias for `StreamedTurn` to describe the result of `runStreamed()`. */
|
|
184
|
+
type RunStreamedResult = StreamedTurn;
|
|
185
|
+
/** An input to send to the agent. */
|
|
186
|
+
type UserInput = {
|
|
187
|
+
type: "text";
|
|
188
|
+
text: string;
|
|
189
|
+
} | {
|
|
190
|
+
type: "local_image";
|
|
191
|
+
path: string;
|
|
192
|
+
};
|
|
193
|
+
type Input = string | UserInput[];
|
|
194
|
+
/** Represent a thread of conversation with the agent. One thread can have multiple consecutive turns. */
|
|
195
|
+
declare class Thread {
|
|
196
|
+
private _exec;
|
|
197
|
+
private _options;
|
|
198
|
+
private _id;
|
|
199
|
+
private _threadOptions;
|
|
200
|
+
/** Returns the ID of the thread. Populated after the first turn starts. */
|
|
201
|
+
get id(): string | null;
|
|
202
|
+
/** Provides the input to the agent and streams events as they are produced during the turn. */
|
|
203
|
+
runStreamed(input: Input, turnOptions?: TurnOptions): Promise<StreamedTurn>;
|
|
204
|
+
private runStreamedInternal;
|
|
205
|
+
/** Provides the input to the agent and returns the completed turn. */
|
|
206
|
+
run(input: Input, turnOptions?: TurnOptions): Promise<Turn>;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
type CodexConfigValue = string | number | boolean | CodexConfigValue[] | CodexConfigObject;
|
|
210
|
+
type CodexConfigObject = {
|
|
211
|
+
[key: string]: CodexConfigValue;
|
|
212
|
+
};
|
|
213
|
+
type CodexOptions = {
|
|
214
|
+
codexPathOverride?: string;
|
|
215
|
+
baseUrl?: string;
|
|
216
|
+
apiKey?: string;
|
|
217
|
+
/**
|
|
218
|
+
* Additional `--config key=value` overrides to pass to the Codex CLI.
|
|
219
|
+
*
|
|
220
|
+
* Provide a JSON object and the SDK will flatten it into dotted paths and
|
|
221
|
+
* serialize values as TOML literals so they are compatible with the CLI's
|
|
222
|
+
* `--config` parsing.
|
|
223
|
+
*/
|
|
224
|
+
config?: CodexConfigObject;
|
|
225
|
+
/**
|
|
226
|
+
* Environment variables passed to the Codex CLI process. When provided, the SDK
|
|
227
|
+
* will not inherit variables from `process.env`.
|
|
228
|
+
*/
|
|
229
|
+
env?: Record<string, string>;
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
type ApprovalMode = "never" | "on-request" | "on-failure" | "untrusted";
|
|
233
|
+
type SandboxMode = "read-only" | "workspace-write" | "danger-full-access";
|
|
234
|
+
type ModelReasoningEffort = "minimal" | "low" | "medium" | "high" | "xhigh";
|
|
235
|
+
type WebSearchMode = "disabled" | "cached" | "live";
|
|
236
|
+
type ThreadOptions = {
|
|
237
|
+
model?: string;
|
|
238
|
+
sandboxMode?: SandboxMode;
|
|
239
|
+
workingDirectory?: string;
|
|
240
|
+
skipGitRepoCheck?: boolean;
|
|
241
|
+
modelReasoningEffort?: ModelReasoningEffort;
|
|
242
|
+
networkAccessEnabled?: boolean;
|
|
243
|
+
webSearchMode?: WebSearchMode;
|
|
244
|
+
webSearchEnabled?: boolean;
|
|
245
|
+
approvalPolicy?: ApprovalMode;
|
|
246
|
+
additionalDirectories?: string[];
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Codex is the main class for interacting with the Codex agent.
|
|
251
|
+
*
|
|
252
|
+
* Use the `startThread()` method to start a new thread or `resumeThread()` to resume a previously started thread.
|
|
253
|
+
*/
|
|
254
|
+
declare class Codex {
|
|
255
|
+
private exec;
|
|
256
|
+
private options;
|
|
257
|
+
constructor(options?: CodexOptions);
|
|
258
|
+
/**
|
|
259
|
+
* Starts a new conversation with an agent.
|
|
260
|
+
* @returns A new thread instance.
|
|
261
|
+
*/
|
|
262
|
+
startThread(options?: ThreadOptions): Thread;
|
|
263
|
+
/**
|
|
264
|
+
* Resumes a conversation with an agent based on the thread id.
|
|
265
|
+
* Threads are persisted in ~/.codex/sessions.
|
|
266
|
+
*
|
|
267
|
+
* @param id The id of the thread to resume.
|
|
268
|
+
* @returns A new thread instance.
|
|
269
|
+
*/
|
|
270
|
+
resumeThread(id: string, options?: ThreadOptions): Thread;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export { type AgentMessageItem, type ApprovalMode, Codex, type CodexOptions, type CommandExecutionItem, type ErrorItem, type FileChangeItem, type Input, type ItemCompletedEvent, type ItemStartedEvent, type ItemUpdatedEvent, type McpToolCallItem, type ModelReasoningEffort, type ReasoningItem, type RunResult, type RunStreamedResult, type SandboxMode, Thread, type ThreadError, type ThreadErrorEvent, type ThreadEvent, type ThreadItem, type ThreadOptions, type ThreadStartedEvent, type TodoListItem, type TurnCompletedEvent, type TurnFailedEvent, type TurnOptions, type TurnStartedEvent, type Usage, type UserInput, type WebSearchItem, type WebSearchMode };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
// src/outputSchemaFile.ts
|
|
2
|
+
import { promises as fs } from "fs";
|
|
3
|
+
import os from "os";
|
|
4
|
+
import path from "path";
|
|
5
|
+
async function createOutputSchemaFile(schema) {
|
|
6
|
+
if (schema === void 0) {
|
|
7
|
+
return { cleanup: async () => {
|
|
8
|
+
} };
|
|
9
|
+
}
|
|
10
|
+
if (!isJsonObject(schema)) {
|
|
11
|
+
throw new Error("outputSchema must be a plain JSON object");
|
|
12
|
+
}
|
|
13
|
+
const schemaDir = await fs.mkdtemp(path.join(os.tmpdir(), "codex-output-schema-"));
|
|
14
|
+
const schemaPath = path.join(schemaDir, "schema.json");
|
|
15
|
+
const cleanup = async () => {
|
|
16
|
+
try {
|
|
17
|
+
await fs.rm(schemaDir, { recursive: true, force: true });
|
|
18
|
+
} catch {
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
try {
|
|
22
|
+
await fs.writeFile(schemaPath, JSON.stringify(schema), "utf8");
|
|
23
|
+
return { schemaPath, cleanup };
|
|
24
|
+
} catch (error) {
|
|
25
|
+
await cleanup();
|
|
26
|
+
throw error;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function isJsonObject(value) {
|
|
30
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// src/thread.ts
|
|
34
|
+
var Thread = class {
|
|
35
|
+
_exec;
|
|
36
|
+
_options;
|
|
37
|
+
_id;
|
|
38
|
+
_threadOptions;
|
|
39
|
+
/** Returns the ID of the thread. Populated after the first turn starts. */
|
|
40
|
+
get id() {
|
|
41
|
+
return this._id;
|
|
42
|
+
}
|
|
43
|
+
/* @internal */
|
|
44
|
+
constructor(exec, options, threadOptions, id = null) {
|
|
45
|
+
this._exec = exec;
|
|
46
|
+
this._options = options;
|
|
47
|
+
this._id = id;
|
|
48
|
+
this._threadOptions = threadOptions;
|
|
49
|
+
}
|
|
50
|
+
/** Provides the input to the agent and streams events as they are produced during the turn. */
|
|
51
|
+
async runStreamed(input, turnOptions = {}) {
|
|
52
|
+
return { events: this.runStreamedInternal(input, turnOptions) };
|
|
53
|
+
}
|
|
54
|
+
async *runStreamedInternal(input, turnOptions = {}) {
|
|
55
|
+
const { schemaPath, cleanup } = await createOutputSchemaFile(turnOptions.outputSchema);
|
|
56
|
+
const options = this._threadOptions;
|
|
57
|
+
const { prompt, images } = normalizeInput(input);
|
|
58
|
+
const generator = this._exec.run({
|
|
59
|
+
input: prompt,
|
|
60
|
+
baseUrl: this._options.baseUrl,
|
|
61
|
+
apiKey: this._options.apiKey,
|
|
62
|
+
threadId: this._id,
|
|
63
|
+
images,
|
|
64
|
+
model: options?.model,
|
|
65
|
+
sandboxMode: options?.sandboxMode,
|
|
66
|
+
workingDirectory: options?.workingDirectory,
|
|
67
|
+
skipGitRepoCheck: options?.skipGitRepoCheck,
|
|
68
|
+
outputSchemaFile: schemaPath,
|
|
69
|
+
modelReasoningEffort: options?.modelReasoningEffort,
|
|
70
|
+
signal: turnOptions.signal,
|
|
71
|
+
networkAccessEnabled: options?.networkAccessEnabled,
|
|
72
|
+
webSearchMode: options?.webSearchMode,
|
|
73
|
+
webSearchEnabled: options?.webSearchEnabled,
|
|
74
|
+
approvalPolicy: options?.approvalPolicy,
|
|
75
|
+
additionalDirectories: options?.additionalDirectories
|
|
76
|
+
});
|
|
77
|
+
try {
|
|
78
|
+
for await (const item of generator) {
|
|
79
|
+
let parsed;
|
|
80
|
+
try {
|
|
81
|
+
parsed = JSON.parse(item);
|
|
82
|
+
} catch (error) {
|
|
83
|
+
throw new Error(`Failed to parse item: ${item}`, { cause: error });
|
|
84
|
+
}
|
|
85
|
+
if (parsed.type === "thread.started") {
|
|
86
|
+
this._id = parsed.thread_id;
|
|
87
|
+
}
|
|
88
|
+
yield parsed;
|
|
89
|
+
}
|
|
90
|
+
} finally {
|
|
91
|
+
await cleanup();
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/** Provides the input to the agent and returns the completed turn. */
|
|
95
|
+
async run(input, turnOptions = {}) {
|
|
96
|
+
const generator = this.runStreamedInternal(input, turnOptions);
|
|
97
|
+
const items = [];
|
|
98
|
+
let finalResponse = "";
|
|
99
|
+
let usage = null;
|
|
100
|
+
let turnFailure = null;
|
|
101
|
+
for await (const event of generator) {
|
|
102
|
+
if (event.type === "item.completed") {
|
|
103
|
+
if (event.item.type === "agent_message") {
|
|
104
|
+
finalResponse = event.item.text;
|
|
105
|
+
}
|
|
106
|
+
items.push(event.item);
|
|
107
|
+
} else if (event.type === "turn.completed") {
|
|
108
|
+
usage = event.usage;
|
|
109
|
+
} else if (event.type === "turn.failed") {
|
|
110
|
+
turnFailure = event.error;
|
|
111
|
+
break;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
if (turnFailure) {
|
|
115
|
+
throw new Error(turnFailure.message);
|
|
116
|
+
}
|
|
117
|
+
return { items, finalResponse, usage };
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
function normalizeInput(input) {
|
|
121
|
+
if (typeof input === "string") {
|
|
122
|
+
return { prompt: input, images: [] };
|
|
123
|
+
}
|
|
124
|
+
const promptParts = [];
|
|
125
|
+
const images = [];
|
|
126
|
+
for (const item of input) {
|
|
127
|
+
if (item.type === "text") {
|
|
128
|
+
promptParts.push(item.text);
|
|
129
|
+
} else if (item.type === "local_image") {
|
|
130
|
+
images.push(item.path);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return { prompt: promptParts.join("\n\n"), images };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// src/exec.ts
|
|
137
|
+
import { spawn } from "child_process";
|
|
138
|
+
import readline from "readline";
|
|
139
|
+
var INTERNAL_ORIGINATOR_ENV = "CODEX_INTERNAL_ORIGINATOR_OVERRIDE";
|
|
140
|
+
var TYPESCRIPT_SDK_ORIGINATOR = "codex_sdk_ts";
|
|
141
|
+
var CodexExec = class {
|
|
142
|
+
executablePath;
|
|
143
|
+
envOverride;
|
|
144
|
+
configOverrides;
|
|
145
|
+
constructor(executablePath = null, env, configOverrides) {
|
|
146
|
+
this.executablePath = executablePath || findCodexPath();
|
|
147
|
+
this.envOverride = env;
|
|
148
|
+
this.configOverrides = configOverrides;
|
|
149
|
+
}
|
|
150
|
+
async *run(args) {
|
|
151
|
+
const commandArgs = ["exec", "--experimental-json"];
|
|
152
|
+
if (this.configOverrides) {
|
|
153
|
+
for (const override of serializeConfigOverrides(this.configOverrides)) {
|
|
154
|
+
commandArgs.push("--config", override);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (args.model) {
|
|
158
|
+
commandArgs.push("--model", args.model);
|
|
159
|
+
}
|
|
160
|
+
if (args.sandboxMode) {
|
|
161
|
+
commandArgs.push("--sandbox", args.sandboxMode);
|
|
162
|
+
}
|
|
163
|
+
if (args.workingDirectory) {
|
|
164
|
+
commandArgs.push("--cd", args.workingDirectory);
|
|
165
|
+
}
|
|
166
|
+
if (args.additionalDirectories?.length) {
|
|
167
|
+
for (const dir of args.additionalDirectories) {
|
|
168
|
+
commandArgs.push("--add-dir", dir);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
if (args.skipGitRepoCheck) {
|
|
172
|
+
commandArgs.push("--skip-git-repo-check");
|
|
173
|
+
}
|
|
174
|
+
if (args.outputSchemaFile) {
|
|
175
|
+
commandArgs.push("--output-schema", args.outputSchemaFile);
|
|
176
|
+
}
|
|
177
|
+
if (args.modelReasoningEffort) {
|
|
178
|
+
commandArgs.push("--config", `model_reasoning_effort="${args.modelReasoningEffort}"`);
|
|
179
|
+
}
|
|
180
|
+
if (args.networkAccessEnabled !== void 0) {
|
|
181
|
+
commandArgs.push(
|
|
182
|
+
"--config",
|
|
183
|
+
`sandbox_workspace_write.network_access=${args.networkAccessEnabled}`
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
if (args.webSearchMode) {
|
|
187
|
+
commandArgs.push("--config", `web_search="${args.webSearchMode}"`);
|
|
188
|
+
} else if (args.webSearchEnabled === true) {
|
|
189
|
+
commandArgs.push("--config", `web_search="live"`);
|
|
190
|
+
} else if (args.webSearchEnabled === false) {
|
|
191
|
+
commandArgs.push("--config", `web_search="disabled"`);
|
|
192
|
+
}
|
|
193
|
+
if (args.approvalPolicy) {
|
|
194
|
+
commandArgs.push("--config", `approval_policy="${args.approvalPolicy}"`);
|
|
195
|
+
}
|
|
196
|
+
if (args.images?.length) {
|
|
197
|
+
for (const image of args.images) {
|
|
198
|
+
commandArgs.push("--image", image);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
if (args.threadId) {
|
|
202
|
+
commandArgs.push("resume", args.threadId);
|
|
203
|
+
}
|
|
204
|
+
const env = {};
|
|
205
|
+
if (this.envOverride) {
|
|
206
|
+
Object.assign(env, this.envOverride);
|
|
207
|
+
} else {
|
|
208
|
+
for (const [key, value] of Object.entries(process.env)) {
|
|
209
|
+
if (value !== void 0) {
|
|
210
|
+
env[key] = value;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
if (!env[INTERNAL_ORIGINATOR_ENV]) {
|
|
215
|
+
env[INTERNAL_ORIGINATOR_ENV] = TYPESCRIPT_SDK_ORIGINATOR;
|
|
216
|
+
}
|
|
217
|
+
if (args.baseUrl) {
|
|
218
|
+
env.OPENAI_BASE_URL = args.baseUrl;
|
|
219
|
+
}
|
|
220
|
+
if (args.apiKey) {
|
|
221
|
+
env.CODEX_API_KEY = args.apiKey;
|
|
222
|
+
}
|
|
223
|
+
const child = spawn(this.executablePath, commandArgs, {
|
|
224
|
+
env,
|
|
225
|
+
signal: args.signal
|
|
226
|
+
});
|
|
227
|
+
let spawnError = null;
|
|
228
|
+
child.once("error", (err) => spawnError = err);
|
|
229
|
+
if (!child.stdin) {
|
|
230
|
+
child.kill();
|
|
231
|
+
throw new Error("Child process has no stdin");
|
|
232
|
+
}
|
|
233
|
+
child.stdin.write(args.input);
|
|
234
|
+
child.stdin.end();
|
|
235
|
+
if (!child.stdout) {
|
|
236
|
+
child.kill();
|
|
237
|
+
throw new Error("Child process has no stdout");
|
|
238
|
+
}
|
|
239
|
+
const stderrChunks = [];
|
|
240
|
+
if (child.stderr) {
|
|
241
|
+
child.stderr.on("data", (data) => {
|
|
242
|
+
stderrChunks.push(data);
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
const exitPromise = new Promise(
|
|
246
|
+
(resolve) => {
|
|
247
|
+
child.once("exit", (code, signal) => {
|
|
248
|
+
resolve({ code, signal });
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
);
|
|
252
|
+
const rl = readline.createInterface({
|
|
253
|
+
input: child.stdout,
|
|
254
|
+
crlfDelay: Infinity
|
|
255
|
+
});
|
|
256
|
+
try {
|
|
257
|
+
for await (const line of rl) {
|
|
258
|
+
yield line;
|
|
259
|
+
}
|
|
260
|
+
if (spawnError) throw spawnError;
|
|
261
|
+
const { code, signal } = await exitPromise;
|
|
262
|
+
if (code !== 0 || signal) {
|
|
263
|
+
const stderrBuffer = Buffer.concat(stderrChunks);
|
|
264
|
+
const detail = signal ? `signal ${signal}` : `code ${code ?? 1}`;
|
|
265
|
+
throw new Error(`Codex Exec exited with ${detail}: ${stderrBuffer.toString("utf8")}`);
|
|
266
|
+
}
|
|
267
|
+
} finally {
|
|
268
|
+
rl.close();
|
|
269
|
+
child.removeAllListeners();
|
|
270
|
+
try {
|
|
271
|
+
if (!child.killed) child.kill();
|
|
272
|
+
} catch {
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
function serializeConfigOverrides(configOverrides) {
|
|
278
|
+
const overrides = [];
|
|
279
|
+
flattenConfigOverrides(configOverrides, "", overrides);
|
|
280
|
+
return overrides;
|
|
281
|
+
}
|
|
282
|
+
function flattenConfigOverrides(value, prefix, overrides) {
|
|
283
|
+
if (!isPlainObject(value)) {
|
|
284
|
+
if (prefix) {
|
|
285
|
+
overrides.push(`${prefix}=${toTomlValue(value, prefix)}`);
|
|
286
|
+
return;
|
|
287
|
+
} else {
|
|
288
|
+
throw new Error("Codex config overrides must be a plain object");
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
const entries = Object.entries(value);
|
|
292
|
+
if (!prefix && entries.length === 0) {
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
if (prefix && entries.length === 0) {
|
|
296
|
+
overrides.push(`${prefix}={}`);
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
for (const [key, child] of entries) {
|
|
300
|
+
if (!key) {
|
|
301
|
+
throw new Error("Codex config override keys must be non-empty strings");
|
|
302
|
+
}
|
|
303
|
+
if (child === void 0) {
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
const path2 = prefix ? `${prefix}.${key}` : key;
|
|
307
|
+
if (isPlainObject(child)) {
|
|
308
|
+
flattenConfigOverrides(child, path2, overrides);
|
|
309
|
+
} else {
|
|
310
|
+
overrides.push(`${path2}=${toTomlValue(child, path2)}`);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
function toTomlValue(value, path2) {
|
|
315
|
+
if (typeof value === "string") {
|
|
316
|
+
return JSON.stringify(value);
|
|
317
|
+
} else if (typeof value === "number") {
|
|
318
|
+
if (!Number.isFinite(value)) {
|
|
319
|
+
throw new Error(`Codex config override at ${path2} must be a finite number`);
|
|
320
|
+
}
|
|
321
|
+
return `${value}`;
|
|
322
|
+
} else if (typeof value === "boolean") {
|
|
323
|
+
return value ? "true" : "false";
|
|
324
|
+
} else if (Array.isArray(value)) {
|
|
325
|
+
const rendered = value.map((item, index) => toTomlValue(item, `${path2}[${index}]`));
|
|
326
|
+
return `[${rendered.join(", ")}]`;
|
|
327
|
+
} else if (isPlainObject(value)) {
|
|
328
|
+
const parts = [];
|
|
329
|
+
for (const [key, child] of Object.entries(value)) {
|
|
330
|
+
if (!key) {
|
|
331
|
+
throw new Error("Codex config override keys must be non-empty strings");
|
|
332
|
+
}
|
|
333
|
+
if (child === void 0) {
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
parts.push(`${formatTomlKey(key)} = ${toTomlValue(child, `${path2}.${key}`)}`);
|
|
337
|
+
}
|
|
338
|
+
return `{${parts.join(", ")}}`;
|
|
339
|
+
} else if (value === null) {
|
|
340
|
+
throw new Error(`Codex config override at ${path2} cannot be null`);
|
|
341
|
+
} else {
|
|
342
|
+
const typeName = typeof value;
|
|
343
|
+
throw new Error(`Unsupported Codex config override value at ${path2}: ${typeName}`);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
var TOML_BARE_KEY = /^[A-Za-z0-9_-]+$/;
|
|
347
|
+
function formatTomlKey(key) {
|
|
348
|
+
return TOML_BARE_KEY.test(key) ? key : JSON.stringify(key);
|
|
349
|
+
}
|
|
350
|
+
function isPlainObject(value) {
|
|
351
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
352
|
+
}
|
|
353
|
+
function findCodexPath() {
|
|
354
|
+
return "codex";
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// src/codex.ts
|
|
358
|
+
var Codex = class {
|
|
359
|
+
exec;
|
|
360
|
+
options;
|
|
361
|
+
constructor(options = {}) {
|
|
362
|
+
const { codexPathOverride, env, config } = options;
|
|
363
|
+
this.exec = new CodexExec(codexPathOverride, env, config);
|
|
364
|
+
this.options = options;
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* Starts a new conversation with an agent.
|
|
368
|
+
* @returns A new thread instance.
|
|
369
|
+
*/
|
|
370
|
+
startThread(options = {}) {
|
|
371
|
+
return new Thread(this.exec, this.options, options);
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Resumes a conversation with an agent based on the thread id.
|
|
375
|
+
* Threads are persisted in ~/.codex/sessions.
|
|
376
|
+
*
|
|
377
|
+
* @param id The id of the thread to resume.
|
|
378
|
+
* @returns A new thread instance.
|
|
379
|
+
*/
|
|
380
|
+
resumeThread(id, options = {}) {
|
|
381
|
+
return new Thread(this.exec, this.options, options, id);
|
|
382
|
+
}
|
|
383
|
+
};
|
|
384
|
+
export {
|
|
385
|
+
Codex,
|
|
386
|
+
Thread
|
|
387
|
+
};
|
|
388
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/outputSchemaFile.ts","../src/thread.ts","../src/exec.ts","../src/codex.ts"],"sourcesContent":["import { promises as fs } from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nexport type OutputSchemaFile = {\n schemaPath?: string;\n cleanup: () => Promise<void>;\n};\n\nexport async function createOutputSchemaFile(schema: unknown): Promise<OutputSchemaFile> {\n if (schema === undefined) {\n return { cleanup: async () => {} };\n }\n\n if (!isJsonObject(schema)) {\n throw new Error(\"outputSchema must be a plain JSON object\");\n }\n\n const schemaDir = await fs.mkdtemp(path.join(os.tmpdir(), \"codex-output-schema-\"));\n const schemaPath = path.join(schemaDir, \"schema.json\");\n const cleanup = async () => {\n try {\n await fs.rm(schemaDir, { recursive: true, force: true });\n } catch {\n // suppress\n }\n };\n\n try {\n await fs.writeFile(schemaPath, JSON.stringify(schema), \"utf8\");\n return { schemaPath, cleanup };\n } catch (error) {\n await cleanup();\n throw error;\n }\n}\n\nfunction isJsonObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import { CodexOptions } from \"./codexOptions\";\nimport { ThreadEvent, ThreadError, Usage } from \"./events\";\nimport { CodexExec } from \"./exec\";\nimport { ThreadItem } from \"./items\";\nimport { ThreadOptions } from \"./threadOptions\";\nimport { TurnOptions } from \"./turnOptions\";\nimport { createOutputSchemaFile } from \"./outputSchemaFile\";\n\n/** Completed turn. */\nexport type Turn = {\n items: ThreadItem[];\n finalResponse: string;\n usage: Usage | null;\n};\n\n/** Alias for `Turn` to describe the result of `run()`. */\nexport type RunResult = Turn;\n\n/** The result of the `runStreamed` method. */\nexport type StreamedTurn = {\n events: AsyncGenerator<ThreadEvent>;\n};\n\n/** Alias for `StreamedTurn` to describe the result of `runStreamed()`. */\nexport type RunStreamedResult = StreamedTurn;\n\n/** An input to send to the agent. */\nexport type UserInput =\n | {\n type: \"text\";\n text: string;\n }\n | {\n type: \"local_image\";\n path: string;\n };\n\nexport type Input = string | UserInput[];\n\n/** Represent a thread of conversation with the agent. One thread can have multiple consecutive turns. */\nexport class Thread {\n private _exec: CodexExec;\n private _options: CodexOptions;\n private _id: string | null;\n private _threadOptions: ThreadOptions;\n\n /** Returns the ID of the thread. Populated after the first turn starts. */\n public get id(): string | null {\n return this._id;\n }\n\n /* @internal */\n constructor(\n exec: CodexExec,\n options: CodexOptions,\n threadOptions: ThreadOptions,\n id: string | null = null,\n ) {\n this._exec = exec;\n this._options = options;\n this._id = id;\n this._threadOptions = threadOptions;\n }\n\n /** Provides the input to the agent and streams events as they are produced during the turn. */\n async runStreamed(input: Input, turnOptions: TurnOptions = {}): Promise<StreamedTurn> {\n return { events: this.runStreamedInternal(input, turnOptions) };\n }\n\n private async *runStreamedInternal(\n input: Input,\n turnOptions: TurnOptions = {},\n ): AsyncGenerator<ThreadEvent> {\n const { schemaPath, cleanup } = await createOutputSchemaFile(turnOptions.outputSchema);\n const options = this._threadOptions;\n const { prompt, images } = normalizeInput(input);\n const generator = this._exec.run({\n input: prompt,\n baseUrl: this._options.baseUrl,\n apiKey: this._options.apiKey,\n threadId: this._id,\n images,\n model: options?.model,\n sandboxMode: options?.sandboxMode,\n workingDirectory: options?.workingDirectory,\n skipGitRepoCheck: options?.skipGitRepoCheck,\n outputSchemaFile: schemaPath,\n modelReasoningEffort: options?.modelReasoningEffort,\n signal: turnOptions.signal,\n networkAccessEnabled: options?.networkAccessEnabled,\n webSearchMode: options?.webSearchMode,\n webSearchEnabled: options?.webSearchEnabled,\n approvalPolicy: options?.approvalPolicy,\n additionalDirectories: options?.additionalDirectories,\n });\n try {\n for await (const item of generator) {\n let parsed: ThreadEvent;\n try {\n parsed = JSON.parse(item) as ThreadEvent;\n } catch (error) {\n throw new Error(`Failed to parse item: ${item}`, { cause: error });\n }\n if (parsed.type === \"thread.started\") {\n this._id = parsed.thread_id;\n }\n yield parsed;\n }\n } finally {\n await cleanup();\n }\n }\n\n /** Provides the input to the agent and returns the completed turn. */\n async run(input: Input, turnOptions: TurnOptions = {}): Promise<Turn> {\n const generator = this.runStreamedInternal(input, turnOptions);\n const items: ThreadItem[] = [];\n let finalResponse: string = \"\";\n let usage: Usage | null = null;\n let turnFailure: ThreadError | null = null;\n for await (const event of generator) {\n if (event.type === \"item.completed\") {\n if (event.item.type === \"agent_message\") {\n finalResponse = event.item.text;\n }\n items.push(event.item);\n } else if (event.type === \"turn.completed\") {\n usage = event.usage;\n } else if (event.type === \"turn.failed\") {\n turnFailure = event.error;\n break;\n }\n }\n if (turnFailure) {\n throw new Error(turnFailure.message);\n }\n return { items, finalResponse, usage };\n }\n}\n\nfunction normalizeInput(input: Input): { prompt: string; images: string[] } {\n if (typeof input === \"string\") {\n return { prompt: input, images: [] };\n }\n const promptParts: string[] = [];\n const images: string[] = [];\n for (const item of input) {\n if (item.type === \"text\") {\n promptParts.push(item.text);\n } else if (item.type === \"local_image\") {\n images.push(item.path);\n }\n }\n return { prompt: promptParts.join(\"\\n\\n\"), images };\n}\n","import { spawn } from \"node:child_process\";\nimport readline from \"node:readline\";\n\nimport type { CodexConfigObject, CodexConfigValue } from \"./codexOptions\";\nimport { SandboxMode, ModelReasoningEffort, ApprovalMode, WebSearchMode } from \"./threadOptions\";\n\nexport type CodexExecArgs = {\n input: string;\n\n baseUrl?: string;\n apiKey?: string;\n threadId?: string | null;\n images?: string[];\n // --model\n model?: string;\n // --sandbox\n sandboxMode?: SandboxMode;\n // --cd\n workingDirectory?: string;\n // --add-dir\n additionalDirectories?: string[];\n // --skip-git-repo-check\n skipGitRepoCheck?: boolean;\n // --output-schema\n outputSchemaFile?: string;\n // --config model_reasoning_effort\n modelReasoningEffort?: ModelReasoningEffort;\n // AbortSignal to cancel the execution\n signal?: AbortSignal;\n // --config sandbox_workspace_write.network_access\n networkAccessEnabled?: boolean;\n // --config web_search\n webSearchMode?: WebSearchMode;\n // legacy --config features.web_search_request\n webSearchEnabled?: boolean;\n // --config approval_policy\n approvalPolicy?: ApprovalMode;\n};\n\nconst INTERNAL_ORIGINATOR_ENV = \"CODEX_INTERNAL_ORIGINATOR_OVERRIDE\";\nconst TYPESCRIPT_SDK_ORIGINATOR = \"codex_sdk_ts\";\n\nexport class CodexExec {\n private executablePath: string;\n private envOverride?: Record<string, string>;\n private configOverrides?: CodexConfigObject;\n\n constructor(\n executablePath: string | null = null,\n env?: Record<string, string>,\n configOverrides?: CodexConfigObject,\n ) {\n this.executablePath = executablePath || findCodexPath();\n this.envOverride = env;\n this.configOverrides = configOverrides;\n }\n\n async *run(args: CodexExecArgs): AsyncGenerator<string> {\n const commandArgs: string[] = [\"exec\", \"--experimental-json\"];\n\n if (this.configOverrides) {\n for (const override of serializeConfigOverrides(this.configOverrides)) {\n commandArgs.push(\"--config\", override);\n }\n }\n\n if (args.model) {\n commandArgs.push(\"--model\", args.model);\n }\n\n if (args.sandboxMode) {\n commandArgs.push(\"--sandbox\", args.sandboxMode);\n }\n\n if (args.workingDirectory) {\n commandArgs.push(\"--cd\", args.workingDirectory);\n }\n\n if (args.additionalDirectories?.length) {\n for (const dir of args.additionalDirectories) {\n commandArgs.push(\"--add-dir\", dir);\n }\n }\n\n if (args.skipGitRepoCheck) {\n commandArgs.push(\"--skip-git-repo-check\");\n }\n\n if (args.outputSchemaFile) {\n commandArgs.push(\"--output-schema\", args.outputSchemaFile);\n }\n\n if (args.modelReasoningEffort) {\n commandArgs.push(\"--config\", `model_reasoning_effort=\"${args.modelReasoningEffort}\"`);\n }\n\n if (args.networkAccessEnabled !== undefined) {\n commandArgs.push(\n \"--config\",\n `sandbox_workspace_write.network_access=${args.networkAccessEnabled}`,\n );\n }\n\n if (args.webSearchMode) {\n commandArgs.push(\"--config\", `web_search=\"${args.webSearchMode}\"`);\n } else if (args.webSearchEnabled === true) {\n commandArgs.push(\"--config\", `web_search=\"live\"`);\n } else if (args.webSearchEnabled === false) {\n commandArgs.push(\"--config\", `web_search=\"disabled\"`);\n }\n\n if (args.approvalPolicy) {\n commandArgs.push(\"--config\", `approval_policy=\"${args.approvalPolicy}\"`);\n }\n\n if (args.images?.length) {\n for (const image of args.images) {\n commandArgs.push(\"--image\", image);\n }\n }\n\n if (args.threadId) {\n commandArgs.push(\"resume\", args.threadId);\n }\n\n const env: Record<string, string> = {};\n if (this.envOverride) {\n Object.assign(env, this.envOverride);\n } else {\n for (const [key, value] of Object.entries(process.env)) {\n if (value !== undefined) {\n env[key] = value;\n }\n }\n }\n if (!env[INTERNAL_ORIGINATOR_ENV]) {\n env[INTERNAL_ORIGINATOR_ENV] = TYPESCRIPT_SDK_ORIGINATOR;\n }\n if (args.baseUrl) {\n env.OPENAI_BASE_URL = args.baseUrl;\n }\n if (args.apiKey) {\n env.CODEX_API_KEY = args.apiKey;\n }\n\n const child = spawn(this.executablePath, commandArgs, {\n env,\n signal: args.signal,\n });\n\n let spawnError: unknown | null = null;\n child.once(\"error\", (err) => (spawnError = err));\n\n if (!child.stdin) {\n child.kill();\n throw new Error(\"Child process has no stdin\");\n }\n child.stdin.write(args.input);\n child.stdin.end();\n\n if (!child.stdout) {\n child.kill();\n throw new Error(\"Child process has no stdout\");\n }\n const stderrChunks: Buffer[] = [];\n\n if (child.stderr) {\n child.stderr.on(\"data\", (data) => {\n stderrChunks.push(data);\n });\n }\n\n const exitPromise = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>(\n (resolve) => {\n child.once(\"exit\", (code, signal) => {\n resolve({ code, signal });\n });\n },\n );\n\n const rl = readline.createInterface({\n input: child.stdout,\n crlfDelay: Infinity,\n });\n\n try {\n for await (const line of rl) {\n // `line` is a string (Node sets default encoding to utf8 for readline)\n yield line as string;\n }\n\n if (spawnError) throw spawnError;\n const { code, signal } = await exitPromise;\n if (code !== 0 || signal) {\n const stderrBuffer = Buffer.concat(stderrChunks);\n const detail = signal ? `signal ${signal}` : `code ${code ?? 1}`;\n throw new Error(`Codex Exec exited with ${detail}: ${stderrBuffer.toString(\"utf8\")}`);\n }\n } finally {\n rl.close();\n child.removeAllListeners();\n try {\n if (!child.killed) child.kill();\n } catch {\n // ignore\n }\n }\n }\n}\n\nfunction serializeConfigOverrides(configOverrides: CodexConfigObject): string[] {\n const overrides: string[] = [];\n flattenConfigOverrides(configOverrides, \"\", overrides);\n return overrides;\n}\n\nfunction flattenConfigOverrides(\n value: CodexConfigValue,\n prefix: string,\n overrides: string[],\n): void {\n if (!isPlainObject(value)) {\n if (prefix) {\n overrides.push(`${prefix}=${toTomlValue(value, prefix)}`);\n return;\n } else {\n throw new Error(\"Codex config overrides must be a plain object\");\n }\n }\n\n const entries = Object.entries(value);\n if (!prefix && entries.length === 0) {\n return;\n }\n\n if (prefix && entries.length === 0) {\n overrides.push(`${prefix}={}`);\n return;\n }\n\n for (const [key, child] of entries) {\n if (!key) {\n throw new Error(\"Codex config override keys must be non-empty strings\");\n }\n if (child === undefined) {\n continue;\n }\n const path = prefix ? `${prefix}.${key}` : key;\n if (isPlainObject(child)) {\n flattenConfigOverrides(child, path, overrides);\n } else {\n overrides.push(`${path}=${toTomlValue(child, path)}`);\n }\n }\n}\n\nfunction toTomlValue(value: CodexConfigValue, path: string): string {\n if (typeof value === \"string\") {\n return JSON.stringify(value);\n } else if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new Error(`Codex config override at ${path} must be a finite number`);\n }\n return `${value}`;\n } else if (typeof value === \"boolean\") {\n return value ? \"true\" : \"false\";\n } else if (Array.isArray(value)) {\n const rendered = value.map((item, index) => toTomlValue(item, `${path}[${index}]`));\n return `[${rendered.join(\", \")}]`;\n } else if (isPlainObject(value)) {\n const parts: string[] = [];\n for (const [key, child] of Object.entries(value)) {\n if (!key) {\n throw new Error(\"Codex config override keys must be non-empty strings\");\n }\n if (child === undefined) {\n continue;\n }\n parts.push(`${formatTomlKey(key)} = ${toTomlValue(child, `${path}.${key}`)}`);\n }\n return `{${parts.join(\", \")}}`;\n } else if (value === null) {\n throw new Error(`Codex config override at ${path} cannot be null`);\n } else {\n const typeName = typeof value;\n throw new Error(`Unsupported Codex config override value at ${path}: ${typeName}`);\n }\n}\n\nconst TOML_BARE_KEY = /^[A-Za-z0-9_-]+$/;\nfunction formatTomlKey(key: string): string {\n return TOML_BARE_KEY.test(key) ? key : JSON.stringify(key);\n}\n\nfunction isPlainObject(value: unknown): value is CodexConfigObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Find the Codex binary path.\n *\n * Unlike the original SDK which bundles the Codex binary,\n * this version expects the Codex CLI to be installed separately\n * and available in the system PATH.\n *\n * @returns The command name \"codex\" to be resolved via PATH.\n */\nfunction findCodexPath(): string {\n return \"codex\";\n}\n","import { CodexOptions } from \"./codexOptions\";\nimport { CodexExec } from \"./exec\";\nimport { Thread } from \"./thread\";\nimport { ThreadOptions } from \"./threadOptions\";\n\n/**\n * Codex is the main class for interacting with the Codex agent.\n *\n * Use the `startThread()` method to start a new thread or `resumeThread()` to resume a previously started thread.\n */\nexport class Codex {\n private exec: CodexExec;\n private options: CodexOptions;\n\n constructor(options: CodexOptions = {}) {\n const { codexPathOverride, env, config } = options;\n this.exec = new CodexExec(codexPathOverride, env, config);\n this.options = options;\n }\n\n /**\n * Starts a new conversation with an agent.\n * @returns A new thread instance.\n */\n startThread(options: ThreadOptions = {}): Thread {\n return new Thread(this.exec, this.options, options);\n }\n\n /**\n * Resumes a conversation with an agent based on the thread id.\n * Threads are persisted in ~/.codex/sessions.\n *\n * @param id The id of the thread to resume.\n * @returns A new thread instance.\n */\n resumeThread(id: string, options: ThreadOptions = {}): Thread {\n return new Thread(this.exec, this.options, options, id);\n }\n}\n"],"mappings":";AAAA,SAAS,YAAY,UAAU;AAC/B,OAAO,QAAQ;AACf,OAAO,UAAU;AAOjB,eAAsB,uBAAuB,QAA4C;AACvF,MAAI,WAAW,QAAW;AACxB,WAAO,EAAE,SAAS,YAAY;AAAA,IAAC,EAAE;AAAA,EACnC;AAEA,MAAI,CAAC,aAAa,MAAM,GAAG;AACzB,UAAM,IAAI,MAAM,0CAA0C;AAAA,EAC5D;AAEA,QAAM,YAAY,MAAM,GAAG,QAAQ,KAAK,KAAK,GAAG,OAAO,GAAG,sBAAsB,CAAC;AACjF,QAAM,aAAa,KAAK,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,EACT;AAAA,EACA;AAAA,EAER,YAAY,UAAwB,CAAC,GAAG;AACtC,UAAM,EAAE,mBAAmB,KAAK,OAAO,IAAI;AAC3C,SAAK,OAAO,IAAI,UAAU,mBAAmB,KAAK,MAAM;AACxD,SAAK,UAAU;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,YAAY,UAAyB,CAAC,GAAW;AAC/C,WAAO,IAAI,OAAO,KAAK,MAAM,KAAK,SAAS,OAAO;AAAA,EACpD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,aAAa,IAAY,UAAyB,CAAC,GAAW;AAC5D,WAAO,IAAI,OAAO,KAAK,MAAM,KAAK,SAAS,SAAS,EAAE;AAAA,EACxD;AACF;","names":["path"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "codex-sdk-ts",
|
|
3
|
+
"version": "0.0.3",
|
|
4
|
+
"description": "TypeScript SDK for Codex APIs (lightweight version without bundled binary).",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/nogataka/codex-sdk-ts.git"
|
|
8
|
+
},
|
|
9
|
+
"author": "nogataka",
|
|
10
|
+
"homepage": "https://github.com/nogataka/codex-sdk-ts#readme",
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/nogataka/codex-sdk-ts/issues"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"openai",
|
|
16
|
+
"codex",
|
|
17
|
+
"sdk",
|
|
18
|
+
"typescript",
|
|
19
|
+
"api"
|
|
20
|
+
],
|
|
21
|
+
"license": "Apache-2.0",
|
|
22
|
+
"type": "module",
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=18"
|
|
25
|
+
},
|
|
26
|
+
"module": "./dist/index.js",
|
|
27
|
+
"types": "./dist/index.d.ts",
|
|
28
|
+
"exports": {
|
|
29
|
+
".": {
|
|
30
|
+
"import": "./dist/index.js",
|
|
31
|
+
"types": "./dist/index.d.ts"
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
"files": [
|
|
35
|
+
"dist"
|
|
36
|
+
],
|
|
37
|
+
"sideEffects": false,
|
|
38
|
+
"scripts": {
|
|
39
|
+
"clean": "rm -rf dist",
|
|
40
|
+
"build": "tsup",
|
|
41
|
+
"build:watch": "tsup --watch",
|
|
42
|
+
"lint": "pnpm eslint \"src/**/*.ts\" \"tests/**/*.ts\"",
|
|
43
|
+
"lint:fix": "pnpm eslint --fix \"src/**/*.ts\" \"tests/**/*.ts\"",
|
|
44
|
+
"test": "jest",
|
|
45
|
+
"test:watch": "jest --watch",
|
|
46
|
+
"coverage": "jest --coverage",
|
|
47
|
+
"format": "prettier --check .",
|
|
48
|
+
"format:fix": "prettier --write .",
|
|
49
|
+
"prepare": "pnpm run build"
|
|
50
|
+
},
|
|
51
|
+
"devDependencies": {
|
|
52
|
+
"@modelcontextprotocol/sdk": "^1.24.0",
|
|
53
|
+
"@types/jest": "^29.5.14",
|
|
54
|
+
"@types/node": "^20.19.18",
|
|
55
|
+
"eslint": "^9.36.0",
|
|
56
|
+
"eslint-config-prettier": "^9.1.2",
|
|
57
|
+
"eslint-plugin-jest": "^29.0.1",
|
|
58
|
+
"eslint-plugin-node-import": "^1.0.5",
|
|
59
|
+
"jest": "^29.7.0",
|
|
60
|
+
"prettier": "^3.6.2",
|
|
61
|
+
"ts-jest": "^29.3.4",
|
|
62
|
+
"ts-jest-mock-import-meta": "^1.3.1",
|
|
63
|
+
"ts-node": "^10.9.2",
|
|
64
|
+
"tsup": "^8.5.0",
|
|
65
|
+
"typescript": "^5.9.2",
|
|
66
|
+
"typescript-eslint": "^8.45.0",
|
|
67
|
+
"zod": "^3.24.2",
|
|
68
|
+
"zod-to-json-schema": "^3.24.6"
|
|
69
|
+
},
|
|
70
|
+
"packageManager": "pnpm@10.28.2+sha512.41872f037ad22f7348e3b1debbaf7e867cfd448f2726d9cf74c08f19507c31d2c8e7a11525b983febc2df640b5438dee6023ebb1f84ed43cc2d654d2bc326264"
|
|
71
|
+
}
|