Base: codex-main originale (prima del fork aKode)
This commit is contained in:
3
sdk/typescript/.prettierignore
Normal file
3
sdk/typescript/.prettierignore
Normal file
@@ -0,0 +1,3 @@
|
||||
dist
|
||||
node_modules
|
||||
coverage
|
||||
5
sdk/typescript/.prettierrc
Normal file
5
sdk/typescript/.prettierrc
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"printWidth": 100,
|
||||
"singleQuote": false,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
160
sdk/typescript/README.md
Normal file
160
sdk/typescript/README.md
Normal file
@@ -0,0 +1,160 @@
|
||||
# Codex SDK
|
||||
|
||||
Embed the Codex agent in your workflows and apps.
|
||||
|
||||
The TypeScript SDK wraps the `codex` CLI from `@openai/codex`. It spawns the CLI and exchanges JSONL events over stdin/stdout.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @openai/codex-sdk
|
||||
```
|
||||
|
||||
Requires Node.js 18+.
|
||||
|
||||
## Quickstart
|
||||
|
||||
```typescript
|
||||
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);
|
||||
```
|
||||
|
||||
Call `run()` repeatedly on the same `Thread` instance to continue that conversation.
|
||||
|
||||
```typescript
|
||||
const nextTurn = await thread.run("Implement the fix");
|
||||
```
|
||||
|
||||
### Streaming responses
|
||||
|
||||
`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.
|
||||
|
||||
```typescript
|
||||
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;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Structured output
|
||||
|
||||
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.
|
||||
|
||||
```typescript
|
||||
const schema = {
|
||||
type: "object",
|
||||
properties: {
|
||||
summary: { type: "string" },
|
||||
status: { type: "string", enum: ["ok", "action_required"] },
|
||||
},
|
||||
required: ["summary", "status"],
|
||||
additionalProperties: false,
|
||||
} as const;
|
||||
|
||||
const turn = await thread.run("Summarize repository status", { outputSchema: schema });
|
||||
console.log(turn.finalResponse);
|
||||
```
|
||||
|
||||
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"`.
|
||||
|
||||
```typescript
|
||||
const schema = z.object({
|
||||
summary: z.string(),
|
||||
status: z.enum(["ok", "action_required"]),
|
||||
});
|
||||
|
||||
const turn = await thread.run("Summarize repository status", {
|
||||
outputSchema: zodToJsonSchema(schema, { target: "openAi" }),
|
||||
});
|
||||
console.log(turn.finalResponse);
|
||||
```
|
||||
|
||||
### Attaching images
|
||||
|
||||
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`.
|
||||
|
||||
```typescript
|
||||
const turn = await thread.run([
|
||||
{ type: "text", text: "Describe these screenshots" },
|
||||
{ type: "local_image", path: "./ui.png" },
|
||||
{ type: "local_image", path: "./diagram.jpg" },
|
||||
]);
|
||||
```
|
||||
|
||||
### Resuming an existing thread
|
||||
|
||||
Threads are persisted in `~/.codex/sessions`. If you lose the in-memory `Thread` object, reconstruct it with `resumeThread()` and keep going.
|
||||
|
||||
```typescript
|
||||
const savedThreadId = process.env.CODEX_THREAD_ID!;
|
||||
const thread = codex.resumeThread(savedThreadId);
|
||||
await thread.run("Implement the fix");
|
||||
```
|
||||
|
||||
### Working directory controls
|
||||
|
||||
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.
|
||||
|
||||
```typescript
|
||||
const thread = codex.startThread({
|
||||
workingDirectory: "/path/to/project",
|
||||
skipGitRepoCheck: true,
|
||||
});
|
||||
```
|
||||
|
||||
### Controlling the Codex CLI environment
|
||||
|
||||
By default, the Codex CLI inherits the Node.js process environment. Provide the optional `env` parameter when instantiating the
|
||||
`Codex` client to fully control which variables the CLI receives—useful for sandboxed hosts like Electron apps.
|
||||
|
||||
```typescript
|
||||
const codex = new Codex({
|
||||
env: {
|
||||
PATH: "/usr/local/bin",
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
The SDK still injects its required variables (such as `CODEX_API_KEY`) on top of the environment you provide. If you set
|
||||
`baseUrl`, the SDK passes it as a `--config openai_base_url=...` override.
|
||||
|
||||
### Passing `--config` overrides
|
||||
|
||||
Use the `config` option to provide additional Codex CLI configuration overrides. The SDK accepts a JSON object, flattens it
|
||||
into dotted paths, and serializes values as TOML literals before passing them as repeated `--config key=value` flags.
|
||||
|
||||
```typescript
|
||||
const codex = new Codex({
|
||||
config: {
|
||||
show_raw_agent_reasoning: true,
|
||||
sandbox_workspace_write: { network_access: true },
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
For configuration keys that cannot be expressed as dotted paths, pass raw TOML overrides with `configOverrides`. Each entry
|
||||
is forwarded unchanged as a separate `--config` argument, without modifying `CODEX_HOME`:
|
||||
|
||||
```typescript
|
||||
const codex = new Codex({
|
||||
config: { default_permissions: "audit" },
|
||||
configOverrides: ['permissions.audit.filesystem={":root"="read","/path/to/project/.env"="deny"}'],
|
||||
});
|
||||
```
|
||||
|
||||
Raw overrides are applied after structured `config` overrides and take precedence over them. SDK-managed settings, such as
|
||||
`baseUrl`, and thread-specific options are applied afterward and take precedence.
|
||||
21
sdk/typescript/eslint.config.js
Normal file
21
sdk/typescript/eslint.config.js
Normal file
@@ -0,0 +1,21 @@
|
||||
import eslint from "@eslint/js";
|
||||
import { defineConfig } from "eslint/config";
|
||||
import tseslint from "typescript-eslint";
|
||||
import nodeImport from "eslint-plugin-node-import";
|
||||
|
||||
export default defineConfig(eslint.configs.recommended, tseslint.configs.recommended, {
|
||||
plugins: {
|
||||
"node-import": nodeImport,
|
||||
},
|
||||
|
||||
rules: {
|
||||
"node-import/prefer-node-protocol": 2,
|
||||
"@typescript-eslint/no-unused-vars": [
|
||||
"error",
|
||||
{
|
||||
argsIgnorePattern: "^_",
|
||||
varsIgnorePattern: "^_",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
32
sdk/typescript/jest.config.cjs
Normal file
32
sdk/typescript/jest.config.cjs
Normal file
@@ -0,0 +1,32 @@
|
||||
/** @type {import('jest').Config} */
|
||||
module.exports = {
|
||||
preset: "ts-jest/presets/default-esm",
|
||||
testEnvironment: "node",
|
||||
extensionsToTreatAsEsm: [".ts"],
|
||||
setupFilesAfterEnv: ["<rootDir>/tests/setupCodexHome.ts"],
|
||||
moduleNameMapper: {
|
||||
"^(\\.{1,2}/.*)\\.js$": "$1",
|
||||
},
|
||||
testMatch: ["**/tests/**/*.test.ts"],
|
||||
transform: {
|
||||
"^.+\\.tsx?$": [
|
||||
"ts-jest",
|
||||
{
|
||||
useESM: true,
|
||||
tsconfig: "tsconfig.json",
|
||||
diagnostics: {
|
||||
ignoreCodes: [1343],
|
||||
},
|
||||
astTransformers: {
|
||||
before: [
|
||||
{
|
||||
path: "ts-jest-mock-import-meta",
|
||||
// Workaround for meta.url not working in jest
|
||||
options: { metaObjectReplacement: { url: "file://" + __dirname + "/dist/index.js" } },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
68
sdk/typescript/package.json
Normal file
68
sdk/typescript/package.json
Normal file
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"name": "@openai/codex-sdk",
|
||||
"version": "0.0.0-dev",
|
||||
"description": "TypeScript SDK for Codex APIs.",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/openai/codex.git",
|
||||
"directory": "sdk/typescript"
|
||||
},
|
||||
"keywords": [
|
||||
"openai",
|
||||
"codex",
|
||||
"sdk",
|
||||
"typescript",
|
||||
"api"
|
||||
],
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"import": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"sideEffects": false,
|
||||
"scripts": {
|
||||
"clean": "rm -rf dist",
|
||||
"build": "tsup",
|
||||
"build:watch": "tsup --watch",
|
||||
"lint": "pnpm eslint \"src/**/*.ts\" \"tests/**/*.ts\"",
|
||||
"lint:fix": "pnpm eslint --fix \"src/**/*.ts\" \"tests/**/*.ts\"",
|
||||
"test": "jest",
|
||||
"test:watch": "jest --watch",
|
||||
"coverage": "jest --coverage",
|
||||
"format": "prettier --check .",
|
||||
"format:fix": "prettier --write .",
|
||||
"prepare": "pnpm run build"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@modelcontextprotocol/conformance": "github:modelcontextprotocol/conformance#49103de6ed70804e940637bf3e9e29e4a3f54e64",
|
||||
"@modelcontextprotocol/sdk": "^1.24.0",
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/node": "^20.19.18",
|
||||
"eslint": "^9.36.0",
|
||||
"eslint-config-prettier": "^9.1.2",
|
||||
"eslint-plugin-jest": "^29.0.1",
|
||||
"eslint-plugin-node-import": "^1.0.5",
|
||||
"jest": "^29.7.0",
|
||||
"prettier": "^3.6.2",
|
||||
"ts-jest": "^29.3.4",
|
||||
"ts-jest-mock-import-meta": "^1.3.1",
|
||||
"ts-node": "^10.9.2",
|
||||
"tsup": "^8.5.0",
|
||||
"typescript": "^5.9.2",
|
||||
"typescript-eslint": "^8.45.0",
|
||||
"zod": "^3.24.2",
|
||||
"zod-to-json-schema": "^3.24.6"
|
||||
},
|
||||
"packageManager": "pnpm@10.34.5+sha512.a4ee05f2f73658255bd6a89859c065a45c28a57daefae2c893a168ee2b73168c37b91e83e57ea67654ad03f03031746430e8bce38e362e042605fb8abc80192e"
|
||||
}
|
||||
90
sdk/typescript/samples/basic_streaming.ts
Executable file
90
sdk/typescript/samples/basic_streaming.ts
Executable file
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env -S NODE_NO_WARNINGS=1 pnpm ts-node-esm --files
|
||||
|
||||
import { createInterface } from "node:readline/promises";
|
||||
import { stdin as input, stdout as output } from "node:process";
|
||||
|
||||
import { Codex } from "@openai/codex-sdk";
|
||||
import type { ThreadEvent, ThreadItem } from "@openai/codex-sdk";
|
||||
import { codexPathOverride } from "./helpers.ts";
|
||||
|
||||
const codex = new Codex({ codexPathOverride: codexPathOverride() });
|
||||
const thread = codex.startThread();
|
||||
const rl = createInterface({ input, output });
|
||||
|
||||
const handleItemCompleted = (item: ThreadItem): void => {
|
||||
switch (item.type) {
|
||||
case "agent_message":
|
||||
console.log(`Assistant: ${item.text}`);
|
||||
break;
|
||||
case "reasoning":
|
||||
console.log(`Reasoning: ${item.text}`);
|
||||
break;
|
||||
case "command_execution": {
|
||||
const exitText = item.exit_code !== undefined ? ` Exit code ${item.exit_code}.` : "";
|
||||
console.log(`Command ${item.command} ${item.status}.${exitText}`);
|
||||
break;
|
||||
}
|
||||
case "file_change": {
|
||||
for (const change of item.changes) {
|
||||
console.log(`File ${change.kind} ${change.path}`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleItemUpdated = (item: ThreadItem): void => {
|
||||
switch (item.type) {
|
||||
case "todo_list": {
|
||||
console.log(`Todo:`);
|
||||
for (const todo of item.items) {
|
||||
console.log(`\t ${todo.completed ? "x" : " "} ${todo.text}`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleEvent = (event: ThreadEvent): void => {
|
||||
switch (event.type) {
|
||||
case "item.completed":
|
||||
handleItemCompleted(event.item);
|
||||
break;
|
||||
case "item.updated":
|
||||
case "item.started":
|
||||
handleItemUpdated(event.item);
|
||||
break;
|
||||
case "turn.completed":
|
||||
console.log(
|
||||
`Used ${event.usage.input_tokens} input tokens, ${event.usage.cached_input_tokens} cached input tokens, ${event.usage.cache_write_input_tokens} cache write input tokens, ${event.usage.output_tokens} output tokens, ${event.usage.reasoning_output_tokens} reasoning output tokens.`,
|
||||
);
|
||||
break;
|
||||
case "turn.failed":
|
||||
console.error(`Turn failed: ${event.error.message}`);
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
const main = async (): Promise<void> => {
|
||||
try {
|
||||
while (true) {
|
||||
const inputText = await rl.question(">");
|
||||
const trimmed = inputText.trim();
|
||||
if (trimmed.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const { events } = await thread.runStreamed(inputText);
|
||||
for await (const event of events) {
|
||||
handleEvent(event);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
rl.close();
|
||||
}
|
||||
};
|
||||
|
||||
main().catch((err) => {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
console.error(`Unexpected error: ${message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
8
sdk/typescript/samples/helpers.ts
Normal file
8
sdk/typescript/samples/helpers.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import path from "node:path";
|
||||
|
||||
export function codexPathOverride() {
|
||||
return (
|
||||
process.env.CODEX_EXECUTABLE ??
|
||||
path.join(process.cwd(), "..", "..", "codex-rs", "target", "debug", "codex")
|
||||
);
|
||||
}
|
||||
22
sdk/typescript/samples/structured_output.ts
Executable file
22
sdk/typescript/samples/structured_output.ts
Executable file
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env -S NODE_NO_WARNINGS=1 pnpm ts-node-esm --files
|
||||
|
||||
import { Codex } from "@openai/codex-sdk";
|
||||
|
||||
import { codexPathOverride } from "./helpers.ts";
|
||||
|
||||
const codex = new Codex({ codexPathOverride: codexPathOverride() });
|
||||
|
||||
const thread = codex.startThread();
|
||||
|
||||
const schema = {
|
||||
type: "object",
|
||||
properties: {
|
||||
summary: { type: "string" },
|
||||
status: { type: "string", enum: ["ok", "action_required"] },
|
||||
},
|
||||
required: ["summary", "status"],
|
||||
additionalProperties: false,
|
||||
} as const;
|
||||
|
||||
const turn = await thread.run("Summarize repository status", { outputSchema: schema });
|
||||
console.log(turn.finalResponse);
|
||||
19
sdk/typescript/samples/structured_output_zod.ts
Executable file
19
sdk/typescript/samples/structured_output_zod.ts
Executable file
@@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env -S NODE_NO_WARNINGS=1 pnpm ts-node-esm --files
|
||||
|
||||
import { Codex } from "@openai/codex-sdk";
|
||||
import { codexPathOverride } from "./helpers.ts";
|
||||
import z from "zod";
|
||||
import zodToJsonSchema from "zod-to-json-schema";
|
||||
|
||||
const codex = new Codex({ codexPathOverride: codexPathOverride() });
|
||||
const thread = codex.startThread();
|
||||
|
||||
const schema = z.object({
|
||||
summary: z.string(),
|
||||
status: z.enum(["ok", "action_required"]),
|
||||
});
|
||||
|
||||
const turn = await thread.run("Summarize repository status", {
|
||||
outputSchema: zodToJsonSchema(schema, { target: "openAi" }),
|
||||
});
|
||||
console.log(turn.finalResponse);
|
||||
39
sdk/typescript/src/codex.ts
Normal file
39
sdk/typescript/src/codex.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { CodexOptions } from "./codexOptions";
|
||||
import { CodexExec } from "./exec";
|
||||
import { Thread } from "./thread";
|
||||
import { ThreadOptions } from "./threadOptions";
|
||||
|
||||
/**
|
||||
* Codex is the main class for interacting with the Codex agent.
|
||||
*
|
||||
* Use the `startThread()` method to start a new thread or `resumeThread()` to resume a previously started thread.
|
||||
*/
|
||||
export class Codex {
|
||||
private exec: CodexExec;
|
||||
private options: CodexOptions;
|
||||
|
||||
constructor(options: CodexOptions = {}) {
|
||||
const { codexPathOverride, env, config, configOverrides } = options;
|
||||
this.exec = new CodexExec(codexPathOverride, env, config, configOverrides);
|
||||
this.options = options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a new conversation with an agent.
|
||||
* @returns A new thread instance.
|
||||
*/
|
||||
startThread(options: ThreadOptions = {}): Thread {
|
||||
return new Thread(this.exec, this.options, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resumes a conversation with an agent based on the thread id.
|
||||
* Threads are persisted in ~/.codex/sessions.
|
||||
*
|
||||
* @param id The id of the thread to resume.
|
||||
* @returns A new thread instance.
|
||||
*/
|
||||
resumeThread(id: string, options: ThreadOptions = {}): Thread {
|
||||
return new Thread(this.exec, this.options, options, id);
|
||||
}
|
||||
}
|
||||
27
sdk/typescript/src/codexOptions.ts
Normal file
27
sdk/typescript/src/codexOptions.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
export type CodexConfigValue = string | number | boolean | CodexConfigValue[] | CodexConfigObject;
|
||||
|
||||
export type CodexConfigObject = { [key: string]: CodexConfigValue };
|
||||
|
||||
export type CodexOptions = {
|
||||
codexPathOverride?: string;
|
||||
baseUrl?: string;
|
||||
apiKey?: string;
|
||||
/**
|
||||
* Additional `--config key=value` overrides to pass to the Codex CLI.
|
||||
*
|
||||
* Provide a JSON object and the SDK will flatten it into dotted paths and
|
||||
* serialize values as TOML literals so they are compatible with the CLI's
|
||||
* `--config` parsing.
|
||||
*/
|
||||
config?: CodexConfigObject;
|
||||
/**
|
||||
* Raw `--config key=value` overrides to pass unchanged to the Codex CLI after
|
||||
* structured configuration and before SDK-managed or thread-specific overrides.
|
||||
*/
|
||||
configOverrides?: string[];
|
||||
/**
|
||||
* Environment variables passed to the Codex CLI process. When provided, the SDK
|
||||
* will not inherit variables from `process.env`.
|
||||
*/
|
||||
env?: Record<string, string>;
|
||||
};
|
||||
84
sdk/typescript/src/events.ts
Normal file
84
sdk/typescript/src/events.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
// based on event types from codex-rs/exec/src/exec_events.rs
|
||||
|
||||
import type { ThreadItem } from "./items";
|
||||
|
||||
/** Emitted when a new thread is started as the first event. */
|
||||
export type ThreadStartedEvent = {
|
||||
type: "thread.started";
|
||||
/** The identifier of the new thread. Can be used to resume the thread later. */
|
||||
thread_id: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Emitted when a turn is started by sending a new prompt to the model.
|
||||
* A turn encompasses all events that happen while the agent is processing the prompt.
|
||||
*/
|
||||
export type TurnStartedEvent = {
|
||||
type: "turn.started";
|
||||
};
|
||||
|
||||
/** Describes the usage of tokens during a turn. */
|
||||
export type Usage = {
|
||||
/** The number of input tokens used during the turn. */
|
||||
input_tokens: number;
|
||||
/** The number of cached input tokens used during the turn. */
|
||||
cached_input_tokens: number;
|
||||
/** The number of input tokens written to the prompt cache during the turn. */
|
||||
cache_write_input_tokens: number;
|
||||
/** The number of output tokens used during the turn. */
|
||||
output_tokens: number;
|
||||
/** The number of reasoning output tokens used during the turn. */
|
||||
reasoning_output_tokens: number;
|
||||
};
|
||||
|
||||
/** Emitted when a turn is completed. Typically right after the assistant's response. */
|
||||
export type TurnCompletedEvent = {
|
||||
type: "turn.completed";
|
||||
usage: Usage;
|
||||
};
|
||||
|
||||
/** Indicates that a turn failed with an error. */
|
||||
export type TurnFailedEvent = {
|
||||
type: "turn.failed";
|
||||
error: ThreadError;
|
||||
};
|
||||
|
||||
/** Emitted when a new item is added to the thread. Typically the item is initially "in progress". */
|
||||
export type ItemStartedEvent = {
|
||||
type: "item.started";
|
||||
item: ThreadItem;
|
||||
};
|
||||
|
||||
/** Emitted when an item is updated. */
|
||||
export type ItemUpdatedEvent = {
|
||||
type: "item.updated";
|
||||
item: ThreadItem;
|
||||
};
|
||||
|
||||
/** Signals that an item has reached a terminal state—either success or failure. */
|
||||
export type ItemCompletedEvent = {
|
||||
type: "item.completed";
|
||||
item: ThreadItem;
|
||||
};
|
||||
|
||||
/** Fatal error emitted by the stream. */
|
||||
export type ThreadError = {
|
||||
message: string;
|
||||
};
|
||||
|
||||
/** Represents an unrecoverable error emitted directly by the event stream. */
|
||||
export type ThreadErrorEvent = {
|
||||
type: "error";
|
||||
message: string;
|
||||
};
|
||||
|
||||
/** Top-level JSONL events emitted by codex exec. */
|
||||
export type ThreadEvent =
|
||||
| ThreadStartedEvent
|
||||
| TurnStartedEvent
|
||||
| TurnCompletedEvent
|
||||
| TurnFailedEvent
|
||||
| ItemStartedEvent
|
||||
| ItemUpdatedEvent
|
||||
| ItemCompletedEvent
|
||||
| ThreadErrorEvent;
|
||||
506
sdk/typescript/src/exec.ts
Normal file
506
sdk/typescript/src/exec.ts
Normal file
@@ -0,0 +1,506 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { statSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import readline from "node:readline";
|
||||
import { createRequire } from "node:module";
|
||||
|
||||
import type { CodexConfigObject, CodexConfigValue } from "./codexOptions";
|
||||
import { SandboxMode, ModelReasoningEffort, ApprovalMode, WebSearchMode } from "./threadOptions";
|
||||
import type { CyberAccessProgram } from "./turnOptions";
|
||||
|
||||
export type CodexExecArgs = {
|
||||
input: string;
|
||||
|
||||
baseUrl?: string;
|
||||
apiKey?: string;
|
||||
threadId?: string | null;
|
||||
// --thread-source; only applies when creating a new thread
|
||||
threadSource?: string;
|
||||
images?: string[];
|
||||
// --model
|
||||
model?: string;
|
||||
// --sandbox
|
||||
sandboxMode?: SandboxMode;
|
||||
// --cd
|
||||
workingDirectory?: string;
|
||||
// --add-dir
|
||||
additionalDirectories?: string[];
|
||||
// --skip-git-repo-check
|
||||
skipGitRepoCheck?: boolean;
|
||||
// --output-schema
|
||||
outputSchemaFile?: string;
|
||||
// --cyber-access-program
|
||||
cyberAccessProgram?: CyberAccessProgram;
|
||||
// --config model_reasoning_effort
|
||||
modelReasoningEffort?: ModelReasoningEffort;
|
||||
// AbortSignal to cancel the execution
|
||||
signal?: AbortSignal;
|
||||
// --config sandbox_workspace_write.network_access
|
||||
networkAccessEnabled?: boolean;
|
||||
// --config web_search
|
||||
webSearchMode?: WebSearchMode;
|
||||
// legacy --config features.web_search_request
|
||||
webSearchEnabled?: boolean;
|
||||
// --config approval_policy
|
||||
approvalPolicy?: ApprovalMode;
|
||||
};
|
||||
|
||||
const INTERNAL_ORIGINATOR_ENV = "CODEX_INTERNAL_ORIGINATOR_OVERRIDE";
|
||||
const TYPESCRIPT_SDK_ORIGINATOR = "codex_sdk_ts";
|
||||
const CODEX_NPM_NAME = "@openai/codex";
|
||||
|
||||
const PLATFORM_PACKAGE_BY_TARGET: Record<string, string> = {
|
||||
"x86_64-unknown-linux-musl": "@openai/codex-linux-x64",
|
||||
"aarch64-unknown-linux-musl": "@openai/codex-linux-arm64",
|
||||
"x86_64-apple-darwin": "@openai/codex-darwin-x64",
|
||||
"aarch64-apple-darwin": "@openai/codex-darwin-arm64",
|
||||
"x86_64-pc-windows-msvc": "@openai/codex-win32-x64",
|
||||
"aarch64-pc-windows-msvc": "@openai/codex-win32-arm64",
|
||||
};
|
||||
|
||||
const moduleRequire = createRequire(import.meta.url);
|
||||
|
||||
type CodexPathResolution = {
|
||||
executablePath: string;
|
||||
pathDirs: string[];
|
||||
};
|
||||
|
||||
export class CodexExec {
|
||||
private executablePath: string;
|
||||
private pathDirs: string[];
|
||||
private envOverride?: Record<string, string>;
|
||||
private configOverrides?: CodexConfigObject;
|
||||
private rawConfigOverrides?: string[];
|
||||
|
||||
constructor(
|
||||
executablePath: string | null = null,
|
||||
env?: Record<string, string>,
|
||||
configOverrides?: CodexConfigObject,
|
||||
rawConfigOverrides?: string[],
|
||||
) {
|
||||
if (executablePath) {
|
||||
this.executablePath = executablePath;
|
||||
this.pathDirs = [];
|
||||
} else {
|
||||
const resolved = findCodexPath();
|
||||
this.executablePath = resolved.executablePath;
|
||||
this.pathDirs = resolved.pathDirs;
|
||||
}
|
||||
this.envOverride = env;
|
||||
this.configOverrides = configOverrides;
|
||||
this.rawConfigOverrides = rawConfigOverrides;
|
||||
}
|
||||
|
||||
async *run(args: CodexExecArgs): AsyncGenerator<string> {
|
||||
const commandArgs: string[] = ["exec", "--experimental-json"];
|
||||
|
||||
if (this.configOverrides) {
|
||||
for (const override of serializeConfigOverrides(this.configOverrides)) {
|
||||
commandArgs.push("--config", override);
|
||||
}
|
||||
}
|
||||
|
||||
if (this.rawConfigOverrides) {
|
||||
for (const override of this.rawConfigOverrides) {
|
||||
commandArgs.push("--config", override);
|
||||
}
|
||||
}
|
||||
|
||||
if (args.baseUrl) {
|
||||
commandArgs.push(
|
||||
"--config",
|
||||
`openai_base_url=${toTomlValue(args.baseUrl, "openai_base_url")}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (args.model) {
|
||||
commandArgs.push("--model", args.model);
|
||||
}
|
||||
|
||||
if (args.threadSource !== undefined && !args.threadId) {
|
||||
commandArgs.push("--thread-source", args.threadSource);
|
||||
}
|
||||
|
||||
if (args.sandboxMode) {
|
||||
commandArgs.push("--sandbox", args.sandboxMode);
|
||||
}
|
||||
|
||||
if (args.workingDirectory) {
|
||||
commandArgs.push("--cd", args.workingDirectory);
|
||||
}
|
||||
|
||||
if (args.additionalDirectories?.length) {
|
||||
for (const dir of args.additionalDirectories) {
|
||||
commandArgs.push("--add-dir", dir);
|
||||
}
|
||||
}
|
||||
|
||||
if (args.skipGitRepoCheck) {
|
||||
commandArgs.push("--skip-git-repo-check");
|
||||
}
|
||||
|
||||
if (args.outputSchemaFile) {
|
||||
commandArgs.push("--output-schema", args.outputSchemaFile);
|
||||
}
|
||||
|
||||
if (args.cyberAccessProgram !== undefined) {
|
||||
commandArgs.push("--cyber-access-program", args.cyberAccessProgram);
|
||||
}
|
||||
|
||||
if (args.modelReasoningEffort) {
|
||||
commandArgs.push("--config", `model_reasoning_effort="${args.modelReasoningEffort}"`);
|
||||
}
|
||||
|
||||
if (args.networkAccessEnabled !== undefined) {
|
||||
commandArgs.push(
|
||||
"--config",
|
||||
`sandbox_workspace_write.network_access=${args.networkAccessEnabled}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (args.webSearchMode) {
|
||||
commandArgs.push("--config", `web_search="${args.webSearchMode}"`);
|
||||
} else if (args.webSearchEnabled === true) {
|
||||
commandArgs.push("--config", `web_search="live"`);
|
||||
} else if (args.webSearchEnabled === false) {
|
||||
commandArgs.push("--config", `web_search="disabled"`);
|
||||
}
|
||||
|
||||
if (args.approvalPolicy) {
|
||||
commandArgs.push("--config", `approval_policy="${args.approvalPolicy}"`);
|
||||
}
|
||||
|
||||
if (args.threadId) {
|
||||
commandArgs.push("resume", args.threadId);
|
||||
}
|
||||
|
||||
if (args.images?.length) {
|
||||
for (const image of args.images) {
|
||||
commandArgs.push("--image", image);
|
||||
}
|
||||
}
|
||||
|
||||
const env: Record<string, string> = {};
|
||||
if (this.envOverride) {
|
||||
Object.assign(env, this.envOverride);
|
||||
} else {
|
||||
for (const [key, value] of Object.entries(process.env)) {
|
||||
if (value !== undefined) {
|
||||
env[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!env[INTERNAL_ORIGINATOR_ENV]) {
|
||||
env[INTERNAL_ORIGINATOR_ENV] = TYPESCRIPT_SDK_ORIGINATOR;
|
||||
}
|
||||
if (args.apiKey) {
|
||||
env.CODEX_API_KEY = args.apiKey;
|
||||
}
|
||||
if (this.pathDirs.length > 0) {
|
||||
prependPathDirs(env, this.pathDirs);
|
||||
}
|
||||
|
||||
const child = spawn(this.executablePath, commandArgs, {
|
||||
env,
|
||||
signal: args.signal,
|
||||
});
|
||||
|
||||
let spawnError: unknown | null = null;
|
||||
child.once("error", (err) => (spawnError = err));
|
||||
|
||||
if (!child.stdin) {
|
||||
child.kill();
|
||||
throw new Error("Child process has no stdin");
|
||||
}
|
||||
child.stdin.write(args.input);
|
||||
child.stdin.end();
|
||||
|
||||
if (!child.stdout) {
|
||||
child.kill();
|
||||
throw new Error("Child process has no stdout");
|
||||
}
|
||||
const stderrChunks: Buffer[] = [];
|
||||
|
||||
if (child.stderr) {
|
||||
child.stderr.on("data", (data) => {
|
||||
stderrChunks.push(data);
|
||||
});
|
||||
}
|
||||
|
||||
const exitPromise = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>(
|
||||
(resolve) => {
|
||||
child.once("exit", (code, signal) => {
|
||||
resolve({ code, signal });
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const rl = readline.createInterface({
|
||||
input: child.stdout,
|
||||
crlfDelay: Infinity,
|
||||
});
|
||||
|
||||
try {
|
||||
for await (const line of rl) {
|
||||
// `line` is a string (Node sets default encoding to utf8 for readline)
|
||||
yield line as string;
|
||||
}
|
||||
|
||||
if (spawnError) throw spawnError;
|
||||
const { code, signal } = await exitPromise;
|
||||
if (code !== 0 || signal) {
|
||||
const stderrBuffer = Buffer.concat(stderrChunks);
|
||||
const detail = signal ? `signal ${signal}` : `code ${code ?? 1}`;
|
||||
throw new Error(`Codex Exec exited with ${detail}: ${stderrBuffer.toString("utf8")}`);
|
||||
}
|
||||
} finally {
|
||||
rl.close();
|
||||
child.removeAllListeners();
|
||||
try {
|
||||
if (!child.killed) child.kill();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function serializeConfigOverrides(configOverrides: CodexConfigObject): string[] {
|
||||
const overrides: string[] = [];
|
||||
flattenConfigOverrides(configOverrides, "", overrides);
|
||||
return overrides;
|
||||
}
|
||||
|
||||
function flattenConfigOverrides(
|
||||
value: CodexConfigValue,
|
||||
prefix: string,
|
||||
overrides: string[],
|
||||
): void {
|
||||
if (!isPlainObject(value)) {
|
||||
if (prefix) {
|
||||
overrides.push(`${prefix}=${toTomlValue(value, prefix)}`);
|
||||
return;
|
||||
} else {
|
||||
throw new Error("Codex config overrides must be a plain object");
|
||||
}
|
||||
}
|
||||
|
||||
const entries = Object.entries(value);
|
||||
if (!prefix && entries.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (prefix && entries.length === 0) {
|
||||
overrides.push(`${prefix}={}`);
|
||||
return;
|
||||
}
|
||||
|
||||
for (const [key, child] of entries) {
|
||||
if (!key) {
|
||||
throw new Error("Codex config override keys must be non-empty strings");
|
||||
}
|
||||
if (child === undefined) {
|
||||
continue;
|
||||
}
|
||||
const path = prefix ? `${prefix}.${key}` : key;
|
||||
if (isPlainObject(child)) {
|
||||
flattenConfigOverrides(child, path, overrides);
|
||||
} else {
|
||||
overrides.push(`${path}=${toTomlValue(child, path)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function toTomlValue(value: CodexConfigValue, path: string): string {
|
||||
if (typeof value === "string") {
|
||||
return JSON.stringify(value);
|
||||
} else if (typeof value === "number") {
|
||||
if (!Number.isFinite(value)) {
|
||||
throw new Error(`Codex config override at ${path} must be a finite number`);
|
||||
}
|
||||
return `${value}`;
|
||||
} else if (typeof value === "boolean") {
|
||||
return value ? "true" : "false";
|
||||
} else if (Array.isArray(value)) {
|
||||
const rendered = value.map((item, index) => toTomlValue(item, `${path}[${index}]`));
|
||||
return `[${rendered.join(", ")}]`;
|
||||
} else if (isPlainObject(value)) {
|
||||
const parts: string[] = [];
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
if (!key) {
|
||||
throw new Error("Codex config override keys must be non-empty strings");
|
||||
}
|
||||
if (child === undefined) {
|
||||
continue;
|
||||
}
|
||||
parts.push(`${formatTomlKey(key)} = ${toTomlValue(child, `${path}.${key}`)}`);
|
||||
}
|
||||
return `{${parts.join(", ")}}`;
|
||||
} else if (value === null) {
|
||||
throw new Error(`Codex config override at ${path} cannot be null`);
|
||||
} else {
|
||||
const typeName = typeof value;
|
||||
throw new Error(`Unsupported Codex config override value at ${path}: ${typeName}`);
|
||||
}
|
||||
}
|
||||
|
||||
const TOML_BARE_KEY = /^[A-Za-z0-9_-]+$/;
|
||||
function formatTomlKey(key: string): string {
|
||||
return TOML_BARE_KEY.test(key) ? key : JSON.stringify(key);
|
||||
}
|
||||
|
||||
function isPlainObject(value: unknown): value is CodexConfigObject {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function findCodexPath(): CodexPathResolution {
|
||||
const { platform, arch } = process;
|
||||
|
||||
let targetTriple = null;
|
||||
switch (platform) {
|
||||
case "linux":
|
||||
case "android":
|
||||
switch (arch) {
|
||||
case "x64":
|
||||
targetTriple = "x86_64-unknown-linux-musl";
|
||||
break;
|
||||
case "arm64":
|
||||
targetTriple = "aarch64-unknown-linux-musl";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case "darwin":
|
||||
switch (arch) {
|
||||
case "x64":
|
||||
targetTriple = "x86_64-apple-darwin";
|
||||
break;
|
||||
case "arm64":
|
||||
targetTriple = "aarch64-apple-darwin";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case "win32":
|
||||
switch (arch) {
|
||||
case "x64":
|
||||
targetTriple = "x86_64-pc-windows-msvc";
|
||||
break;
|
||||
case "arm64":
|
||||
targetTriple = "aarch64-pc-windows-msvc";
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (!targetTriple) {
|
||||
throw new Error(`Unsupported platform: ${platform} (${arch})`);
|
||||
}
|
||||
|
||||
const platformPackage = PLATFORM_PACKAGE_BY_TARGET[targetTriple];
|
||||
if (!platformPackage) {
|
||||
throw new Error(`Unsupported target triple: ${targetTriple}`);
|
||||
}
|
||||
|
||||
let vendorRoot: string;
|
||||
try {
|
||||
const codexPackageJsonPath = moduleRequire.resolve(`${CODEX_NPM_NAME}/package.json`);
|
||||
const codexRequire = createRequire(codexPackageJsonPath);
|
||||
const platformPackageJsonPath = codexRequire.resolve(`${platformPackage}/package.json`);
|
||||
vendorRoot = path.join(path.dirname(platformPackageJsonPath), "vendor");
|
||||
} catch {
|
||||
throw new Error(
|
||||
`Unable to locate Codex CLI binaries. Ensure ${CODEX_NPM_NAME} is installed with optional dependencies.`,
|
||||
);
|
||||
}
|
||||
|
||||
const codexBinaryName = process.platform === "win32" ? "codex.exe" : "codex";
|
||||
const nativePackage = resolveNativePackage(vendorRoot, targetTriple, codexBinaryName);
|
||||
if (!nativePackage) {
|
||||
throw new Error(
|
||||
`Unable to locate Codex CLI binaries for ${targetTriple}. Ensure ${CODEX_NPM_NAME} is installed with optional dependencies.`,
|
||||
);
|
||||
}
|
||||
|
||||
return nativePackage;
|
||||
}
|
||||
|
||||
export function resolveNativePackage(
|
||||
vendorRoot: string,
|
||||
targetTriple: string,
|
||||
codexBinaryName: string,
|
||||
): CodexPathResolution | null {
|
||||
const packageRoot = path.join(vendorRoot, targetTriple);
|
||||
const packageBinaryPath = path.join(packageRoot, "bin", codexBinaryName);
|
||||
if (isFile(packageBinaryPath) && isFile(path.join(packageRoot, "codex-package.json"))) {
|
||||
return {
|
||||
executablePath: packageBinaryPath,
|
||||
pathDirs: existingDirs(path.join(packageRoot, "codex-path")),
|
||||
};
|
||||
}
|
||||
|
||||
const legacyBinaryPath = path.join(packageRoot, "codex", codexBinaryName);
|
||||
if (isFile(legacyBinaryPath)) {
|
||||
return {
|
||||
executablePath: legacyBinaryPath,
|
||||
pathDirs: existingDirs(path.join(packageRoot, "path")),
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function existingDirs(...dirs: string[]): string[] {
|
||||
return dirs.filter(isDirectory);
|
||||
}
|
||||
|
||||
export function prependPathDirs(
|
||||
env: Record<string, string>,
|
||||
pathDirs: string[],
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): void {
|
||||
const pathKey = pathEnvKey(env, platform);
|
||||
if (platform === "win32") {
|
||||
for (const key of Object.keys(env)) {
|
||||
if (key.toLowerCase() === "path" && key !== pathKey) {
|
||||
delete env[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const existingEntries = (env[pathKey] ?? "")
|
||||
.split(path.delimiter)
|
||||
.filter((entry) => entry.length > 0 && !pathDirs.includes(entry));
|
||||
env[pathKey] = [...pathDirs, ...existingEntries].join(path.delimiter);
|
||||
}
|
||||
|
||||
function pathEnvKey(env: Record<string, string>, platform: NodeJS.Platform): string {
|
||||
if (platform !== "win32") {
|
||||
return "PATH";
|
||||
}
|
||||
|
||||
const matchingKeys = Object.keys(env).filter((key) => key.toLowerCase() === "path");
|
||||
return matchingKeys.includes("Path") ? "Path" : (matchingKeys.at(-1) ?? "PATH");
|
||||
}
|
||||
|
||||
function isFile(filePath: string): boolean {
|
||||
try {
|
||||
return statSync(filePath).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isDirectory(filePath: string): boolean {
|
||||
try {
|
||||
return statSync(filePath).isDirectory();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
40
sdk/typescript/src/index.ts
Normal file
40
sdk/typescript/src/index.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
export type {
|
||||
ThreadEvent,
|
||||
ThreadStartedEvent,
|
||||
TurnStartedEvent,
|
||||
TurnCompletedEvent,
|
||||
TurnFailedEvent,
|
||||
ItemStartedEvent,
|
||||
ItemUpdatedEvent,
|
||||
ItemCompletedEvent,
|
||||
ThreadError,
|
||||
ThreadErrorEvent,
|
||||
Usage,
|
||||
} from "./events";
|
||||
export type {
|
||||
ThreadItem,
|
||||
AgentMessageItem,
|
||||
ReasoningItem,
|
||||
CommandExecutionItem,
|
||||
FileChangeItem,
|
||||
McpToolCallItem,
|
||||
WebSearchItem,
|
||||
TodoListItem,
|
||||
ErrorItem,
|
||||
} from "./items";
|
||||
|
||||
export { Thread } from "./thread";
|
||||
export type { RunResult, RunStreamedResult, Input, UserInput } from "./thread";
|
||||
|
||||
export { Codex } from "./codex";
|
||||
|
||||
export type { CodexOptions } from "./codexOptions";
|
||||
|
||||
export type {
|
||||
ThreadOptions,
|
||||
ApprovalMode,
|
||||
SandboxMode,
|
||||
ModelReasoningEffort,
|
||||
WebSearchMode,
|
||||
} from "./threadOptions";
|
||||
export type { CyberAccessProgram, TurnOptions } from "./turnOptions";
|
||||
128
sdk/typescript/src/items.ts
Normal file
128
sdk/typescript/src/items.ts
Normal file
@@ -0,0 +1,128 @@
|
||||
// based on item types from codex-rs/exec/src/exec_events.rs
|
||||
|
||||
import type { ContentBlock as McpContentBlock } from "@modelcontextprotocol/sdk/types.js";
|
||||
|
||||
/** The status of a command execution. */
|
||||
export type CommandExecutionStatus = "in_progress" | "completed" | "failed";
|
||||
|
||||
/** A command executed by the agent. */
|
||||
export type CommandExecutionItem = {
|
||||
id: string;
|
||||
type: "command_execution";
|
||||
/** The command line executed by the agent. */
|
||||
command: string;
|
||||
/** Aggregated stdout and stderr captured while the command was running. */
|
||||
aggregated_output: string;
|
||||
/** Set when the command exits; omitted while still running. */
|
||||
exit_code?: number;
|
||||
/** Current status of the command execution. */
|
||||
status: CommandExecutionStatus;
|
||||
};
|
||||
|
||||
/** Indicates the type of the file change. */
|
||||
export type PatchChangeKind = "add" | "delete" | "update";
|
||||
|
||||
/** A set of file changes by the agent. */
|
||||
export type FileUpdateChange = {
|
||||
path: string;
|
||||
kind: PatchChangeKind;
|
||||
};
|
||||
|
||||
/** The status of a file change. */
|
||||
export type PatchApplyStatus = "completed" | "failed";
|
||||
|
||||
/** A set of file changes by the agent. Emitted once the patch succeeds or fails. */
|
||||
export type FileChangeItem = {
|
||||
id: string;
|
||||
type: "file_change";
|
||||
/** Individual file changes that comprise the patch. */
|
||||
changes: FileUpdateChange[];
|
||||
/** Whether the patch ultimately succeeded or failed. */
|
||||
status: PatchApplyStatus;
|
||||
};
|
||||
|
||||
/** The status of an MCP tool call. */
|
||||
export type McpToolCallStatus = "in_progress" | "completed" | "failed";
|
||||
|
||||
/**
|
||||
* Represents a call to an MCP tool. The item starts when the invocation is dispatched
|
||||
* and completes when the MCP server reports success or failure.
|
||||
*/
|
||||
export type McpToolCallItem = {
|
||||
id: string;
|
||||
type: "mcp_tool_call";
|
||||
/** Name of the MCP server handling the request. */
|
||||
server: string;
|
||||
/** The tool invoked on the MCP server. */
|
||||
tool: string;
|
||||
/** Arguments forwarded to the tool invocation. */
|
||||
arguments: unknown;
|
||||
/** Result payload returned by the MCP server for successful calls. */
|
||||
result?: {
|
||||
content: McpContentBlock[];
|
||||
_meta?: unknown;
|
||||
structured_content: unknown;
|
||||
};
|
||||
/** Error message reported for failed calls. */
|
||||
error?: {
|
||||
message: string;
|
||||
};
|
||||
/** Current status of the tool invocation. */
|
||||
status: McpToolCallStatus;
|
||||
};
|
||||
|
||||
/** Response from the agent. Either natural-language text or JSON when structured output is requested. */
|
||||
export type AgentMessageItem = {
|
||||
id: string;
|
||||
type: "agent_message";
|
||||
/** Either natural-language text or JSON when structured output is requested. */
|
||||
text: string;
|
||||
};
|
||||
|
||||
/** Agent's reasoning summary. */
|
||||
export type ReasoningItem = {
|
||||
id: string;
|
||||
type: "reasoning";
|
||||
text: string;
|
||||
};
|
||||
|
||||
/** Captures a web search request. Completes when results are returned to the agent. */
|
||||
export type WebSearchItem = {
|
||||
id: string;
|
||||
type: "web_search";
|
||||
query: string;
|
||||
};
|
||||
|
||||
/** Describes a non-fatal error surfaced as an item. */
|
||||
export type ErrorItem = {
|
||||
id: string;
|
||||
type: "error";
|
||||
message: string;
|
||||
};
|
||||
|
||||
/** An item in the agent's to-do list. */
|
||||
export type TodoItem = {
|
||||
text: string;
|
||||
completed: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Tracks the agent's running to-do list. Starts when the plan is issued, updates as steps change,
|
||||
* and completes when the turn ends.
|
||||
*/
|
||||
export type TodoListItem = {
|
||||
id: string;
|
||||
type: "todo_list";
|
||||
items: TodoItem[];
|
||||
};
|
||||
|
||||
/** Canonical union of thread items and their type-specific payloads. */
|
||||
export type ThreadItem =
|
||||
| AgentMessageItem
|
||||
| ReasoningItem
|
||||
| CommandExecutionItem
|
||||
| FileChangeItem
|
||||
| McpToolCallItem
|
||||
| WebSearchItem
|
||||
| TodoListItem
|
||||
| ErrorItem;
|
||||
40
sdk/typescript/src/outputSchemaFile.ts
Normal file
40
sdk/typescript/src/outputSchemaFile.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { promises as fs } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
export type OutputSchemaFile = {
|
||||
schemaPath?: string;
|
||||
cleanup: () => Promise<void>;
|
||||
};
|
||||
|
||||
export async function createOutputSchemaFile(schema: unknown): Promise<OutputSchemaFile> {
|
||||
if (schema === undefined) {
|
||||
return { cleanup: async () => {} };
|
||||
}
|
||||
|
||||
if (!isJsonObject(schema)) {
|
||||
throw new Error("outputSchema must be a plain JSON object");
|
||||
}
|
||||
|
||||
const schemaDir = await fs.mkdtemp(path.join(os.tmpdir(), "codex-output-schema-"));
|
||||
const schemaPath = path.join(schemaDir, "schema.json");
|
||||
const cleanup = async () => {
|
||||
try {
|
||||
await fs.rm(schemaDir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// suppress
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
await fs.writeFile(schemaPath, JSON.stringify(schema), "utf8");
|
||||
return { schemaPath, cleanup };
|
||||
} catch (error) {
|
||||
await cleanup();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function isJsonObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
159
sdk/typescript/src/thread.ts
Normal file
159
sdk/typescript/src/thread.ts
Normal file
@@ -0,0 +1,159 @@
|
||||
import { CodexOptions } from "./codexOptions";
|
||||
import { ThreadEvent, ThreadError, Usage } from "./events";
|
||||
import { CodexExec } from "./exec";
|
||||
import { ThreadItem } from "./items";
|
||||
import { ThreadOptions } from "./threadOptions";
|
||||
import { TurnOptions } from "./turnOptions";
|
||||
import { createOutputSchemaFile } from "./outputSchemaFile";
|
||||
|
||||
/** Completed turn. */
|
||||
export type Turn = {
|
||||
items: ThreadItem[];
|
||||
finalResponse: string;
|
||||
usage: Usage | null;
|
||||
};
|
||||
|
||||
/** Alias for `Turn` to describe the result of `run()`. */
|
||||
export type RunResult = Turn;
|
||||
|
||||
/** The result of the `runStreamed` method. */
|
||||
export type StreamedTurn = {
|
||||
events: AsyncGenerator<ThreadEvent>;
|
||||
};
|
||||
|
||||
/** Alias for `StreamedTurn` to describe the result of `runStreamed()`. */
|
||||
export type RunStreamedResult = StreamedTurn;
|
||||
|
||||
/** An input to send to the agent. */
|
||||
export type UserInput =
|
||||
| {
|
||||
type: "text";
|
||||
text: string;
|
||||
}
|
||||
| {
|
||||
type: "local_image";
|
||||
path: string;
|
||||
};
|
||||
|
||||
export type Input = string | UserInput[];
|
||||
|
||||
/** Represent a thread of conversation with the agent. One thread can have multiple consecutive turns. */
|
||||
export class Thread {
|
||||
private _exec: CodexExec;
|
||||
private _options: CodexOptions;
|
||||
private _id: string | null;
|
||||
private _threadOptions: ThreadOptions;
|
||||
|
||||
/** Returns the ID of the thread. Populated after the first turn starts. */
|
||||
public get id(): string | null {
|
||||
return this._id;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
constructor(
|
||||
exec: CodexExec,
|
||||
options: CodexOptions,
|
||||
threadOptions: ThreadOptions,
|
||||
id: string | null = null,
|
||||
) {
|
||||
this._exec = exec;
|
||||
this._options = options;
|
||||
this._id = id;
|
||||
this._threadOptions = threadOptions;
|
||||
}
|
||||
|
||||
/** Provides the input to the agent and streams events as they are produced during the turn. */
|
||||
async runStreamed(input: Input, turnOptions: TurnOptions = {}): Promise<StreamedTurn> {
|
||||
return { events: this.runStreamedInternal(input, turnOptions) };
|
||||
}
|
||||
|
||||
private async *runStreamedInternal(
|
||||
input: Input,
|
||||
turnOptions: TurnOptions = {},
|
||||
): AsyncGenerator<ThreadEvent> {
|
||||
const { schemaPath, cleanup } = await createOutputSchemaFile(turnOptions.outputSchema);
|
||||
const options = this._threadOptions;
|
||||
const { prompt, images } = normalizeInput(input);
|
||||
const generator = this._exec.run({
|
||||
input: prompt,
|
||||
baseUrl: this._options.baseUrl,
|
||||
apiKey: this._options.apiKey,
|
||||
threadId: this._id,
|
||||
images,
|
||||
model: options?.model,
|
||||
threadSource: options?.threadSource,
|
||||
sandboxMode: options?.sandboxMode,
|
||||
workingDirectory: options?.workingDirectory,
|
||||
skipGitRepoCheck: options?.skipGitRepoCheck,
|
||||
outputSchemaFile: schemaPath,
|
||||
cyberAccessProgram: turnOptions.cyberAccessProgram,
|
||||
modelReasoningEffort: options?.modelReasoningEffort,
|
||||
signal: turnOptions.signal,
|
||||
networkAccessEnabled: options?.networkAccessEnabled,
|
||||
webSearchMode: options?.webSearchMode,
|
||||
webSearchEnabled: options?.webSearchEnabled,
|
||||
approvalPolicy: options?.approvalPolicy,
|
||||
additionalDirectories: options?.additionalDirectories,
|
||||
});
|
||||
try {
|
||||
for await (const item of generator) {
|
||||
let parsed: ThreadEvent;
|
||||
try {
|
||||
parsed = JSON.parse(item) as ThreadEvent;
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to parse item: ${item}`, { cause: error });
|
||||
}
|
||||
if (parsed.type === "thread.started") {
|
||||
this._id = parsed.thread_id;
|
||||
} else if (parsed.type === "turn.completed") {
|
||||
parsed.usage.cache_write_input_tokens ??= 0;
|
||||
}
|
||||
yield parsed;
|
||||
}
|
||||
} finally {
|
||||
await cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
/** Provides the input to the agent and returns the completed turn. */
|
||||
async run(input: Input, turnOptions: TurnOptions = {}): Promise<Turn> {
|
||||
const generator = this.runStreamedInternal(input, turnOptions);
|
||||
const items: ThreadItem[] = [];
|
||||
let finalResponse: string = "";
|
||||
let usage: Usage | null = null;
|
||||
let turnFailure: ThreadError | null = null;
|
||||
for await (const event of generator) {
|
||||
if (event.type === "item.completed") {
|
||||
if (event.item.type === "agent_message") {
|
||||
finalResponse = event.item.text;
|
||||
}
|
||||
items.push(event.item);
|
||||
} else if (event.type === "turn.completed") {
|
||||
usage = event.usage;
|
||||
} else if (event.type === "turn.failed") {
|
||||
turnFailure = event.error;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (turnFailure) {
|
||||
throw new Error(turnFailure.message);
|
||||
}
|
||||
return { items, finalResponse, usage };
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeInput(input: Input): { prompt: string; images: string[] } {
|
||||
if (typeof input === "string") {
|
||||
return { prompt: input, images: [] };
|
||||
}
|
||||
const promptParts: string[] = [];
|
||||
const images: string[] = [];
|
||||
for (const item of input) {
|
||||
if (item.type === "text") {
|
||||
promptParts.push(item.text);
|
||||
} else if (item.type === "local_image") {
|
||||
images.push(item.path);
|
||||
}
|
||||
}
|
||||
return { prompt: promptParts.join("\n\n"), images };
|
||||
}
|
||||
30
sdk/typescript/src/threadOptions.ts
Normal file
30
sdk/typescript/src/threadOptions.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
export type ApprovalMode = "never" | "on-request" | "on-failure" | "untrusted";
|
||||
|
||||
export type SandboxMode = "read-only" | "workspace-write" | "danger-full-access";
|
||||
|
||||
export type ModelReasoningEffort =
|
||||
| "minimal"
|
||||
| "low"
|
||||
| "medium"
|
||||
| "high"
|
||||
| "xhigh"
|
||||
| "max"
|
||||
| "ultra"
|
||||
| "persistent";
|
||||
|
||||
export type WebSearchMode = "disabled" | "cached" | "live";
|
||||
|
||||
export type ThreadOptions = {
|
||||
model?: string;
|
||||
/** Source classification applied when this thread is first created. */
|
||||
threadSource?: string;
|
||||
sandboxMode?: SandboxMode;
|
||||
workingDirectory?: string;
|
||||
skipGitRepoCheck?: boolean;
|
||||
modelReasoningEffort?: ModelReasoningEffort;
|
||||
networkAccessEnabled?: boolean;
|
||||
webSearchMode?: WebSearchMode;
|
||||
webSearchEnabled?: boolean;
|
||||
approvalPolicy?: ApprovalMode;
|
||||
additionalDirectories?: string[];
|
||||
};
|
||||
13
sdk/typescript/src/turnOptions.ts
Normal file
13
sdk/typescript/src/turnOptions.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
export type CyberAccessProgram = "standard" | "daybreak_blue" | "daybreak_red";
|
||||
|
||||
export type TurnOptions = {
|
||||
/**
|
||||
* Experimental Cyber selection for this turn with the built-in OpenAI provider.
|
||||
* Omit to use server defaults.
|
||||
*/
|
||||
cyberAccessProgram?: CyberAccessProgram;
|
||||
/** JSON schema describing the expected agent output. */
|
||||
outputSchema?: unknown;
|
||||
/** AbortSignal to cancel the turn. */
|
||||
signal?: AbortSignal;
|
||||
};
|
||||
165
sdk/typescript/tests/abort.test.ts
Normal file
165
sdk/typescript/tests/abort.test.ts
Normal file
@@ -0,0 +1,165 @@
|
||||
import { describe, expect, it } from "@jest/globals";
|
||||
|
||||
import {
|
||||
assistantMessage,
|
||||
responseCompleted,
|
||||
responseStarted,
|
||||
exec_command_call as execCommandCall,
|
||||
sse,
|
||||
SseResponseBody,
|
||||
startResponsesTestProxy,
|
||||
} from "./responsesProxy";
|
||||
import { createMockClient } from "./testCodex";
|
||||
|
||||
function* infiniteShellCall(): Generator<SseResponseBody> {
|
||||
while (true) {
|
||||
yield sse(responseStarted(), execCommandCall(), responseCompleted());
|
||||
}
|
||||
}
|
||||
|
||||
describe("AbortSignal support", () => {
|
||||
it("aborts run() when signal is aborted", async () => {
|
||||
const { url, close } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: infiniteShellCall(),
|
||||
});
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread();
|
||||
|
||||
// Create an abort controller and abort it immediately
|
||||
const controller = new AbortController();
|
||||
controller.abort("Test abort");
|
||||
|
||||
// The operation should fail because the signal is already aborted
|
||||
await expect(thread.run("Hello, world!", { signal: controller.signal })).rejects.toThrow();
|
||||
} finally {
|
||||
cleanup();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
it("aborts runStreamed() when signal is aborted", async () => {
|
||||
const { url, close } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: infiniteShellCall(),
|
||||
});
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread();
|
||||
|
||||
// Create an abort controller and abort it immediately
|
||||
const controller = new AbortController();
|
||||
controller.abort("Test abort");
|
||||
|
||||
const { events } = await thread.runStreamed("Hello, world!", { signal: controller.signal });
|
||||
|
||||
// Attempting to iterate should fail
|
||||
let iterationStarted = false;
|
||||
try {
|
||||
for await (const event of events) {
|
||||
iterationStarted = true;
|
||||
// Should not get here
|
||||
expect(event).toBeUndefined();
|
||||
}
|
||||
// If we get here, the test should fail
|
||||
throw new Error(
|
||||
"Expected iteration to throw due to aborted signal, but it completed successfully",
|
||||
);
|
||||
} catch (error) {
|
||||
// We expect an error to be thrown
|
||||
expect(iterationStarted).toBe(false); // Should fail before any iteration
|
||||
expect(error).toBeDefined();
|
||||
}
|
||||
} finally {
|
||||
cleanup();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
it("aborts run() when signal is aborted during execution", async () => {
|
||||
const { url, close } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: infiniteShellCall(),
|
||||
});
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread();
|
||||
|
||||
const controller = new AbortController();
|
||||
|
||||
// Start the operation and abort it immediately after
|
||||
const runPromise = thread.run("Hello, world!", { signal: controller.signal });
|
||||
|
||||
// Abort after a tiny delay to simulate aborting during execution
|
||||
setTimeout(() => controller.abort("Aborted during execution"), 10);
|
||||
|
||||
// The operation should fail
|
||||
await expect(runPromise).rejects.toThrow();
|
||||
} finally {
|
||||
cleanup();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
it("aborts runStreamed() when signal is aborted during iteration", async () => {
|
||||
const { url, close } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: infiniteShellCall(),
|
||||
});
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread();
|
||||
|
||||
const controller = new AbortController();
|
||||
|
||||
const { events } = await thread.runStreamed("Hello, world!", { signal: controller.signal });
|
||||
|
||||
// Abort during iteration
|
||||
let eventCount = 0;
|
||||
await expect(
|
||||
(async () => {
|
||||
for await (const event of events) {
|
||||
void event; // Consume the event
|
||||
eventCount++;
|
||||
// Abort after first event
|
||||
if (eventCount === 1) {
|
||||
controller.abort("Aborted during iteration");
|
||||
}
|
||||
// Continue iterating - should eventually throw
|
||||
}
|
||||
})(),
|
||||
).rejects.toThrow();
|
||||
} finally {
|
||||
cleanup();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
it("completes normally when signal is not aborted", async () => {
|
||||
const { url, close } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [sse(responseStarted(), assistantMessage("Hi!"), responseCompleted())],
|
||||
});
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread();
|
||||
|
||||
const controller = new AbortController();
|
||||
|
||||
// Don't abort - should complete successfully
|
||||
const result = await thread.run("Hello, world!", { signal: controller.signal });
|
||||
|
||||
expect(result.finalResponse).toBe("Hi!");
|
||||
expect(result.items).toHaveLength(1);
|
||||
} finally {
|
||||
cleanup();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
});
|
||||
37
sdk/typescript/tests/codexExecSpy.ts
Normal file
37
sdk/typescript/tests/codexExecSpy.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import * as child_process from "node:child_process";
|
||||
|
||||
jest.mock("node:child_process", () => {
|
||||
const actual = jest.requireActual<typeof import("node:child_process")>("node:child_process");
|
||||
return { ...actual, spawn: jest.fn(actual.spawn) };
|
||||
});
|
||||
|
||||
const actualChildProcess =
|
||||
jest.requireActual<typeof import("node:child_process")>("node:child_process");
|
||||
const spawnMock = child_process.spawn as jest.MockedFunction<typeof actualChildProcess.spawn>;
|
||||
|
||||
export function codexExecSpy(): {
|
||||
args: string[][];
|
||||
envs: (Record<string, string> | undefined)[];
|
||||
restore: () => void;
|
||||
} {
|
||||
const previousImplementation = spawnMock.getMockImplementation() ?? actualChildProcess.spawn;
|
||||
const args: string[][] = [];
|
||||
const envs: (Record<string, string> | undefined)[] = [];
|
||||
|
||||
spawnMock.mockImplementation(((...spawnArgs: Parameters<typeof child_process.spawn>) => {
|
||||
const commandArgs = spawnArgs[1];
|
||||
args.push(Array.isArray(commandArgs) ? [...commandArgs] : []);
|
||||
const options = spawnArgs[2] as child_process.SpawnOptions | undefined;
|
||||
envs.push(options?.env as Record<string, string> | undefined);
|
||||
return previousImplementation(...spawnArgs);
|
||||
}) as typeof actualChildProcess.spawn);
|
||||
|
||||
return {
|
||||
args,
|
||||
envs,
|
||||
restore: () => {
|
||||
spawnMock.mockClear();
|
||||
spawnMock.mockImplementation(previousImplementation);
|
||||
},
|
||||
};
|
||||
}
|
||||
365
sdk/typescript/tests/exec.test.ts
Normal file
365
sdk/typescript/tests/exec.test.ts
Normal file
@@ -0,0 +1,365 @@
|
||||
import * as child_process from "node:child_process";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { PassThrough } from "node:stream";
|
||||
|
||||
import { describe, expect, it } from "@jest/globals";
|
||||
|
||||
import type { CodexConfigObject } from "../src/codexOptions";
|
||||
|
||||
jest.mock("node:child_process", () => {
|
||||
const actual = jest.requireActual<typeof import("node:child_process")>("node:child_process");
|
||||
return { ...actual, spawn: jest.fn() };
|
||||
});
|
||||
|
||||
const _actualChildProcess =
|
||||
jest.requireActual<typeof import("node:child_process")>("node:child_process");
|
||||
const spawnMock = child_process.spawn as jest.MockedFunction<typeof _actualChildProcess.spawn>;
|
||||
|
||||
class FakeChildProcess extends EventEmitter {
|
||||
stdin = new PassThrough();
|
||||
stdout = new PassThrough();
|
||||
stderr = new PassThrough();
|
||||
killed = false;
|
||||
|
||||
kill(): boolean {
|
||||
this.killed = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function createEarlyExitChild(exitCode = 2): FakeChildProcess {
|
||||
const child = new FakeChildProcess();
|
||||
setImmediate(() => {
|
||||
child.stderr.write("boom");
|
||||
child.emit("exit", exitCode, null);
|
||||
setImmediate(() => {
|
||||
child.stdout.end();
|
||||
child.stderr.end();
|
||||
});
|
||||
});
|
||||
return child;
|
||||
}
|
||||
|
||||
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
describe("CodexExec", () => {
|
||||
it("rejects when exit happens before stdout closes", async () => {
|
||||
const { CodexExec } = await import("../src/exec");
|
||||
const child = createEarlyExitChild();
|
||||
spawnMock.mockReturnValue(child as unknown as child_process.ChildProcess);
|
||||
|
||||
const exec = new CodexExec("codex");
|
||||
const runPromise = (async () => {
|
||||
for await (const _ of exec.run({ input: "hi" })) {
|
||||
// no-op
|
||||
}
|
||||
})().then(
|
||||
() => ({ status: "resolved" as const }),
|
||||
(error) => ({ status: "rejected" as const, error }),
|
||||
);
|
||||
|
||||
const result = await Promise.race([
|
||||
runPromise,
|
||||
delay(500).then(() => ({ status: "timeout" as const })),
|
||||
]);
|
||||
|
||||
expect(result.status).toBe("rejected");
|
||||
if (result.status === "rejected") {
|
||||
expect(result.error).toBeInstanceOf(Error);
|
||||
expect(result.error.message).toMatch(/Codex Exec exited/);
|
||||
}
|
||||
});
|
||||
|
||||
it("places resume args before image args", async () => {
|
||||
const { CodexExec } = await import("../src/exec");
|
||||
spawnMock.mockClear();
|
||||
const child = new FakeChildProcess();
|
||||
spawnMock.mockReturnValue(child as unknown as child_process.ChildProcess);
|
||||
|
||||
setImmediate(() => {
|
||||
child.stdout.end();
|
||||
child.stderr.end();
|
||||
child.emit("exit", 0, null);
|
||||
});
|
||||
|
||||
const exec = new CodexExec("codex");
|
||||
for await (const _ of exec.run({ input: "hi", images: ["img.png"], threadId: "thread-id" })) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
const commandArgs = spawnMock.mock.calls[0]?.[1] as string[] | undefined;
|
||||
expect(commandArgs).toBeDefined();
|
||||
const resumeIndex = commandArgs!.indexOf("resume");
|
||||
const imageIndex = commandArgs!.indexOf("--image");
|
||||
expect(resumeIndex).toBeGreaterThan(-1);
|
||||
expect(imageIndex).toBeGreaterThan(-1);
|
||||
expect(resumeIndex).toBeLessThan(imageIndex);
|
||||
});
|
||||
|
||||
const configOverrideCases: {
|
||||
name: string;
|
||||
config?: CodexConfigObject;
|
||||
configOverrides?: string[];
|
||||
expectedOverrides: string[];
|
||||
}[] = [
|
||||
{
|
||||
name: "ordinary and dotted structured keys without changing their meaning",
|
||||
config: {
|
||||
model_providers: { "mock.name": "Mock provider" },
|
||||
"features.shell_snapshot": false,
|
||||
features: { plugins: false },
|
||||
sandbox_workspace_write: { network_access: true },
|
||||
},
|
||||
expectedOverrides: [
|
||||
'model_providers.mock.name="Mock provider"',
|
||||
"features.shell_snapshot=false",
|
||||
"features.plugins=false",
|
||||
"sandbox_workspace_write.network_access=true",
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "raw inline filesystem permissions without altering literal map keys",
|
||||
configOverrides: [
|
||||
'permissions.worker.filesystem={glob_scan_max_depth=4,":root"="read",":workspace_roots"="read","/repo/.env"="deny","/repo/**/*.pem"="deny","/repo/with spaces/.env"="deny","C:\\\\repo\\\\secret.env"="deny"}',
|
||||
],
|
||||
expectedOverrides: [
|
||||
'permissions.worker.filesystem={glob_scan_max_depth=4,":root"="read",":workspace_roots"="read","/repo/.env"="deny","/repo/**/*.pem"="deny","/repo/with spaces/.env"="deny","C:\\\\repo\\\\secret.env"="deny"}',
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "raw profile names containing periods and spaces",
|
||||
configOverrides: [
|
||||
'permissions={"scan.profile with spaces"={filesystem={":root"="read","/repo/.env"="deny"}}}',
|
||||
],
|
||||
expectedOverrides: [
|
||||
'permissions={"scan.profile with spaces"={filesystem={":root"="read","/repo/.env"="deny"}}}',
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "structured overrides before ordered raw overrides and duplicates",
|
||||
config: { approval_policy: "never", features: { plugins: false } },
|
||||
configOverrides: ['approval_policy="on-failure"', 'approval_policy="on-request"'],
|
||||
expectedOverrides: [
|
||||
'approval_policy="never"',
|
||||
"features.plugins=false",
|
||||
'approval_policy="on-failure"',
|
||||
'approval_policy="on-request"',
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "an empty raw override list without changing structured configuration",
|
||||
config: { retry_budget: 3 },
|
||||
configOverrides: [],
|
||||
expectedOverrides: ["retry_budget=3"],
|
||||
},
|
||||
];
|
||||
|
||||
it.each(configOverrideCases)(
|
||||
"passes $name to the Codex CLI",
|
||||
async ({ config, configOverrides, expectedOverrides }) => {
|
||||
const { CodexExec } = await import("../src/exec");
|
||||
spawnMock.mockClear();
|
||||
const child = new FakeChildProcess();
|
||||
spawnMock.mockReturnValue(child as unknown as child_process.ChildProcess);
|
||||
|
||||
setImmediate(() => {
|
||||
child.stdout.end();
|
||||
child.stderr.end();
|
||||
child.emit("exit", 0, null);
|
||||
});
|
||||
|
||||
const exec = new CodexExec("codex", undefined, config, configOverrides);
|
||||
for await (const _ of exec.run({ input: "hi" })) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
const commandArgs = spawnMock.mock.calls[0]?.[1] as string[] | undefined;
|
||||
expect(commandArgs).toEqual([
|
||||
"exec",
|
||||
"--experimental-json",
|
||||
...expectedOverrides.flatMap((override) => ["--config", override]),
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
it("passes the thread source when starting a new thread", async () => {
|
||||
const { CodexExec } = await import("../src/exec");
|
||||
spawnMock.mockClear();
|
||||
const child = new FakeChildProcess();
|
||||
spawnMock.mockReturnValue(child as unknown as child_process.ChildProcess);
|
||||
|
||||
setImmediate(() => {
|
||||
child.stdout.end();
|
||||
child.stderr.end();
|
||||
child.emit("exit", 0, null);
|
||||
});
|
||||
|
||||
const exec = new CodexExec("codex");
|
||||
for await (const _ of exec.run({ input: "hi", threadSource: "automated_review" })) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
expect(spawnMock.mock.calls[0]?.[1]).toEqual([
|
||||
"exec",
|
||||
"--experimental-json",
|
||||
"--thread-source",
|
||||
"automated_review",
|
||||
]);
|
||||
});
|
||||
|
||||
it("lets SDK-managed and thread settings override raw configuration when resuming", async () => {
|
||||
const { CodexExec } = await import("../src/exec");
|
||||
spawnMock.mockClear();
|
||||
const child = new FakeChildProcess();
|
||||
spawnMock.mockReturnValue(child as unknown as child_process.ChildProcess);
|
||||
|
||||
setImmediate(() => {
|
||||
child.stdout.end();
|
||||
child.stderr.end();
|
||||
child.emit("exit", 0, null);
|
||||
});
|
||||
|
||||
const exec = new CodexExec("codex", undefined, { approval_policy: "never" }, [
|
||||
'approval_policy="on-failure"',
|
||||
'openai_base_url="https://raw.example.test"',
|
||||
"sandbox_workspace_write={network_access=true}",
|
||||
]);
|
||||
for await (const _ of exec.run({
|
||||
input: "resume with overrides",
|
||||
threadId: "thread-id",
|
||||
threadSource: "should_not_override",
|
||||
baseUrl: "https://managed.example.test",
|
||||
approvalPolicy: "on-request",
|
||||
networkAccessEnabled: false,
|
||||
})) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
const commandArgs = spawnMock.mock.calls[0]?.[1] as string[] | undefined;
|
||||
expect(commandArgs).toEqual([
|
||||
"exec",
|
||||
"--experimental-json",
|
||||
"--config",
|
||||
'approval_policy="never"',
|
||||
"--config",
|
||||
'approval_policy="on-failure"',
|
||||
"--config",
|
||||
'openai_base_url="https://raw.example.test"',
|
||||
"--config",
|
||||
"sandbox_workspace_write={network_access=true}",
|
||||
"--config",
|
||||
'openai_base_url="https://managed.example.test"',
|
||||
"--config",
|
||||
"sandbox_workspace_write.network_access=false",
|
||||
"--config",
|
||||
'approval_policy="on-request"',
|
||||
"resume",
|
||||
"thread-id",
|
||||
]);
|
||||
});
|
||||
|
||||
it("allows overriding the env passed to the Codex CLI", async () => {
|
||||
const { CodexExec } = await import("../src/exec");
|
||||
spawnMock.mockClear();
|
||||
const child = new FakeChildProcess();
|
||||
spawnMock.mockReturnValue(child as unknown as child_process.ChildProcess);
|
||||
|
||||
setImmediate(() => {
|
||||
child.stdout.end();
|
||||
child.stderr.end();
|
||||
child.emit("exit", 0, null);
|
||||
});
|
||||
|
||||
process.env.CODEX_ENV_SHOULD_NOT_LEAK = "leak";
|
||||
|
||||
try {
|
||||
const exec = new CodexExec("codex", {
|
||||
CODEX_HOME: "/tmp/codex-home",
|
||||
CUSTOM_ENV: "custom",
|
||||
});
|
||||
|
||||
for await (const _ of exec.run({
|
||||
input: "custom env",
|
||||
apiKey: "test",
|
||||
baseUrl: "https://example.test",
|
||||
})) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
const commandArgs = spawnMock.mock.calls[0]?.[1] as string[] | undefined;
|
||||
expect(commandArgs).toBeDefined();
|
||||
const spawnOptions = spawnMock.mock.calls[0]?.[2] as child_process.SpawnOptions | undefined;
|
||||
const spawnEnv = spawnOptions?.env as Record<string, string> | undefined;
|
||||
expect(spawnEnv).toBeDefined();
|
||||
if (!spawnEnv || !commandArgs) {
|
||||
throw new Error("Spawn args missing");
|
||||
}
|
||||
|
||||
expect(spawnEnv.CODEX_HOME).toBe("/tmp/codex-home");
|
||||
expect(spawnEnv.CUSTOM_ENV).toBe("custom");
|
||||
expect(spawnEnv.CODEX_ENV_SHOULD_NOT_LEAK).toBeUndefined();
|
||||
expect(spawnEnv.CODEX_API_KEY).toBe("test");
|
||||
expect(spawnEnv.CODEX_INTERNAL_ORIGINATOR_OVERRIDE).toBeDefined();
|
||||
expect(commandArgs).toContain("--config");
|
||||
expect(commandArgs).toContain(`openai_base_url=${JSON.stringify("https://example.test")}`);
|
||||
} finally {
|
||||
delete process.env.CODEX_ENV_SHOULD_NOT_LEAK;
|
||||
}
|
||||
});
|
||||
|
||||
it("resolves the package-layout binary and PATH directory", async () => {
|
||||
const { resolveNativePackage } = await import("../src/exec");
|
||||
const vendorRoot = mkdtempSync(path.join(tmpdir(), "codex-sdk-vendor-"));
|
||||
const packageRoot = path.join(vendorRoot, "x86_64-unknown-linux-musl");
|
||||
const binDir = path.join(packageRoot, "bin");
|
||||
const pathDir = path.join(packageRoot, "codex-path");
|
||||
mkdirSync(binDir, { recursive: true });
|
||||
mkdirSync(pathDir, { recursive: true });
|
||||
writeFileSync(path.join(packageRoot, "codex-package.json"), "{}");
|
||||
writeFileSync(path.join(binDir, "codex"), "");
|
||||
|
||||
expect(resolveNativePackage(vendorRoot, "x86_64-unknown-linux-musl", "codex")).toEqual({
|
||||
executablePath: path.join(binDir, "codex"),
|
||||
pathDirs: [pathDir],
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to the legacy binary layout", async () => {
|
||||
const { resolveNativePackage } = await import("../src/exec");
|
||||
const vendorRoot = mkdtempSync(path.join(tmpdir(), "codex-sdk-vendor-"));
|
||||
const packageRoot = path.join(vendorRoot, "x86_64-unknown-linux-musl");
|
||||
const binDir = path.join(packageRoot, "codex");
|
||||
const pathDir = path.join(packageRoot, "path");
|
||||
mkdirSync(binDir, { recursive: true });
|
||||
mkdirSync(pathDir, { recursive: true });
|
||||
writeFileSync(path.join(binDir, "codex"), "");
|
||||
|
||||
expect(resolveNativePackage(vendorRoot, "x86_64-unknown-linux-musl", "codex")).toEqual({
|
||||
executablePath: path.join(binDir, "codex"),
|
||||
pathDirs: [pathDir],
|
||||
});
|
||||
});
|
||||
|
||||
it("prepends package PATH entries without duplicating them", async () => {
|
||||
const { prependPathDirs } = await import("../src/exec");
|
||||
const pathDir = path.join(tmpdir(), "codex-path");
|
||||
const env = { PATH: `/usr/bin${path.delimiter}${pathDir}` };
|
||||
|
||||
prependPathDirs(env, [pathDir]);
|
||||
|
||||
expect(env).toEqual({ PATH: `${pathDir}${path.delimiter}/usr/bin` });
|
||||
});
|
||||
|
||||
it("preserves the Windows Path key when prepending package PATH entries", async () => {
|
||||
const { prependPathDirs } = await import("../src/exec");
|
||||
const pathDir = path.join(tmpdir(), "codex-path");
|
||||
const env = { PATH: "/usr/bin", Path: `C\\Windows${path.delimiter}${pathDir}` };
|
||||
|
||||
prependPathDirs(env, [pathDir], "win32");
|
||||
|
||||
expect(env).toEqual({ Path: `${pathDir}${path.delimiter}C\\Windows` });
|
||||
});
|
||||
});
|
||||
158
sdk/typescript/tests/mcpConformance.test.ts
Normal file
158
sdk/typescript/tests/mcpConformance.test.ts
Normal file
@@ -0,0 +1,158 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { existsSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, it } from "@jest/globals";
|
||||
|
||||
import { codexExecPath } from "./testCodex";
|
||||
|
||||
const conformanceTimeoutMs = 300_000;
|
||||
const reviewerRegressionTimeoutMs = 180_000;
|
||||
|
||||
function requireFile(filePath: string, description: string): string {
|
||||
if (!existsSync(filePath)) {
|
||||
throw new Error(`MCP conformance ${description} does not exist: ${filePath}`);
|
||||
}
|
||||
|
||||
return filePath;
|
||||
}
|
||||
|
||||
function conformanceDirectory(): string {
|
||||
const repositoryRoot = path.resolve(process.cwd(), "../..");
|
||||
const candidates = [
|
||||
path.join(repositoryRoot, "public", "scripts", "mcp_conformance"),
|
||||
path.join(repositoryRoot, "scripts", "mcp_conformance"),
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (existsSync(path.join(candidate, "run_codex_compliance.py"))) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`MCP conformance harness is missing; checked ${candidates.join(" and ")}`);
|
||||
}
|
||||
|
||||
describe("MCP client conformance", () => {
|
||||
it(
|
||||
"does not introduce shipping, intermediate, or modern official conformance regressions",
|
||||
() => {
|
||||
const directory = conformanceDirectory();
|
||||
const require = createRequire(import.meta.url);
|
||||
const conformancePackage = require.resolve("@modelcontextprotocol/conformance/package.json");
|
||||
const officialConformanceCli = requireFile(
|
||||
path.join(path.dirname(conformancePackage), "dist", "index.js"),
|
||||
"pinned official CLI",
|
||||
);
|
||||
const codexBinary = requireFile(codexExecPath, "built Codex binary");
|
||||
const baseline = requireFile(
|
||||
path.join(directory, "regression-baseline-v1.json"),
|
||||
"committed regression baseline",
|
||||
);
|
||||
const reportDirectory = process.env.RUNNER_TEMP ?? os.tmpdir();
|
||||
const reportPath = path.join(reportDirectory, `codex-mcp-conformance-${process.pid}.json`);
|
||||
const result = spawnSync(
|
||||
"python3",
|
||||
[
|
||||
path.join(directory, "run_codex_compliance.py"),
|
||||
codexBinary,
|
||||
"--mode",
|
||||
"all",
|
||||
"--transport",
|
||||
"all",
|
||||
"--auth",
|
||||
"--conformance-cli",
|
||||
officialConformanceCli,
|
||||
"--baseline-report",
|
||||
baseline,
|
||||
"--report",
|
||||
reportPath,
|
||||
],
|
||||
{
|
||||
encoding: "utf8",
|
||||
maxBuffer: 16 * 1024 * 1024,
|
||||
timeout: conformanceTimeoutMs - 10_000,
|
||||
},
|
||||
);
|
||||
|
||||
if (result.error) {
|
||||
throw new Error(`MCP conformance runner could not complete: ${result.error.message}`, {
|
||||
cause: result.error,
|
||||
});
|
||||
}
|
||||
|
||||
if (result.status !== 0) {
|
||||
throw new Error(
|
||||
[
|
||||
`MCP conformance regression gate exited with ${result.status ?? result.signal}.`,
|
||||
`Report: ${reportPath}`,
|
||||
result.stdout,
|
||||
result.stderr,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n"),
|
||||
);
|
||||
}
|
||||
},
|
||||
conformanceTimeoutMs,
|
||||
);
|
||||
|
||||
it(
|
||||
"does not introduce production reviewer or catalog-boundary regressions",
|
||||
() => {
|
||||
const directory = conformanceDirectory();
|
||||
const codexBinary = requireFile(codexExecPath, "built Codex binary");
|
||||
const reviewer = requireFile(
|
||||
path.join(directory, "review_regressions.py"),
|
||||
"production reviewer regression runner",
|
||||
);
|
||||
const baseline = requireFile(
|
||||
path.join(directory, "review-regression-baseline-v1.json"),
|
||||
"committed production reviewer regression baseline",
|
||||
);
|
||||
const reportDirectory = process.env.RUNNER_TEMP ?? os.tmpdir();
|
||||
const reportPath = path.join(reportDirectory, `codex-mcp-review-${process.pid}.json`);
|
||||
const result = spawnSync(
|
||||
"python3",
|
||||
[
|
||||
reviewer,
|
||||
codexBinary,
|
||||
"--mode",
|
||||
"all",
|
||||
"--baseline-report",
|
||||
baseline,
|
||||
"--report",
|
||||
reportPath,
|
||||
],
|
||||
{
|
||||
encoding: "utf8",
|
||||
maxBuffer: 16 * 1024 * 1024,
|
||||
timeout: reviewerRegressionTimeoutMs - 10_000,
|
||||
},
|
||||
);
|
||||
|
||||
if (result.error) {
|
||||
throw new Error(
|
||||
`MCP production reviewer regression runner could not complete: ${result.error.message}`,
|
||||
{ cause: result.error },
|
||||
);
|
||||
}
|
||||
|
||||
if (result.status !== 0) {
|
||||
throw new Error(
|
||||
[
|
||||
`MCP production reviewer regression gate exited with ${result.status ?? result.signal}.`,
|
||||
`Report: ${reportPath}`,
|
||||
result.stdout,
|
||||
result.stderr,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n"),
|
||||
);
|
||||
}
|
||||
},
|
||||
reviewerRegressionTimeoutMs,
|
||||
);
|
||||
});
|
||||
224
sdk/typescript/tests/responsesProxy.ts
Normal file
224
sdk/typescript/tests/responsesProxy.ts
Normal file
@@ -0,0 +1,224 @@
|
||||
import http from "node:http";
|
||||
|
||||
const DEFAULT_RESPONSE_ID = "resp_mock";
|
||||
const DEFAULT_MESSAGE_ID = "msg_mock";
|
||||
|
||||
type ResponseCompletedUsage = {
|
||||
input_tokens: number;
|
||||
input_tokens_details: { cached_tokens: number } | null;
|
||||
output_tokens: number;
|
||||
output_tokens_details: { reasoning_tokens: number } | null;
|
||||
total_tokens: number;
|
||||
};
|
||||
|
||||
const DEFAULT_COMPLETED_USAGE: ResponseCompletedUsage = {
|
||||
input_tokens: 42,
|
||||
input_tokens_details: { cached_tokens: 12 },
|
||||
output_tokens: 5,
|
||||
output_tokens_details: null,
|
||||
total_tokens: 47,
|
||||
};
|
||||
|
||||
export type SseEvent = {
|
||||
type: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
export type SseResponseBody = {
|
||||
kind: "sse";
|
||||
events: SseEvent[];
|
||||
};
|
||||
|
||||
export type ResponsesProxyOptions = {
|
||||
responseBodies: Generator<SseResponseBody> | SseResponseBody[];
|
||||
statusCode?: number;
|
||||
};
|
||||
|
||||
export type ResponsesProxy = {
|
||||
url: string;
|
||||
close: () => Promise<void>;
|
||||
requests: RecordedRequest[];
|
||||
};
|
||||
|
||||
export type ResponsesApiRequest = {
|
||||
model?: string;
|
||||
input: Array<{
|
||||
role: string;
|
||||
content?: Array<{ type: string; text: string }>;
|
||||
}>;
|
||||
text?: {
|
||||
format?: Record<string, unknown>;
|
||||
};
|
||||
};
|
||||
|
||||
export type RecordedRequest = {
|
||||
body: string;
|
||||
json: ResponsesApiRequest;
|
||||
headers: http.IncomingHttpHeaders;
|
||||
};
|
||||
|
||||
function formatSseEvent(event: SseEvent): string {
|
||||
return `event: ${event.type}\n` + `data: ${JSON.stringify(event)}\n\n`;
|
||||
}
|
||||
|
||||
export async function startResponsesTestProxy(
|
||||
options: ResponsesProxyOptions,
|
||||
): Promise<ResponsesProxy> {
|
||||
function* createGenerator(array: SseResponseBody[]): Generator<SseResponseBody> {
|
||||
for (const elem of array) {
|
||||
yield elem;
|
||||
}
|
||||
throw new Error("not enough responses provided");
|
||||
}
|
||||
|
||||
const responseBodies: Generator<SseResponseBody> = Array.isArray(options.responseBodies)
|
||||
? createGenerator(options.responseBodies)
|
||||
: options.responseBodies;
|
||||
|
||||
const requests: RecordedRequest[] = [];
|
||||
|
||||
function readRequestBody(req: http.IncomingMessage): Promise<string> {
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
const chunks: Buffer[] = [];
|
||||
req.on("data", (chunk) => {
|
||||
chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
|
||||
});
|
||||
req.on("end", () => {
|
||||
resolve(Buffer.concat(chunks).toString("utf8"));
|
||||
});
|
||||
req.on("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
async function handle(): Promise<void> {
|
||||
if (req.method === "POST" && req.url === "/responses") {
|
||||
const body = await readRequestBody(req);
|
||||
const json = JSON.parse(body);
|
||||
requests.push({ body, json, headers: { ...req.headers } });
|
||||
|
||||
const status = options.statusCode ?? 200;
|
||||
res.statusCode = status;
|
||||
res.setHeader("content-type", "text/event-stream");
|
||||
|
||||
const responseBody = responseBodies.next().value;
|
||||
for (const event of responseBody.events) {
|
||||
res.write(formatSseEvent(event));
|
||||
}
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
res.statusCode = 404;
|
||||
res.end();
|
||||
}
|
||||
|
||||
handle().catch(() => {
|
||||
res.statusCode = 500;
|
||||
res.end();
|
||||
});
|
||||
});
|
||||
|
||||
const url = await new Promise<string>((resolve, reject) => {
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") {
|
||||
reject(new Error("Unable to determine proxy address"));
|
||||
return;
|
||||
}
|
||||
server.off("error", reject);
|
||||
const info = address;
|
||||
resolve(`http://${info.address}:${info.port}`);
|
||||
});
|
||||
server.once("error", reject);
|
||||
});
|
||||
|
||||
async function close(): Promise<void> {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.close((err) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
return { url, close, requests };
|
||||
}
|
||||
|
||||
export function sse(...events: SseEvent[]): SseResponseBody {
|
||||
return {
|
||||
kind: "sse",
|
||||
events,
|
||||
};
|
||||
}
|
||||
|
||||
export function responseStarted(responseId: string = DEFAULT_RESPONSE_ID): SseEvent {
|
||||
return {
|
||||
type: "response.created",
|
||||
response: {
|
||||
id: responseId,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function assistantMessage(text: string, itemId: string = DEFAULT_MESSAGE_ID): SseEvent {
|
||||
return {
|
||||
type: "response.output_item.done",
|
||||
item: {
|
||||
type: "message",
|
||||
role: "assistant",
|
||||
id: itemId,
|
||||
content: [
|
||||
{
|
||||
type: "output_text",
|
||||
text,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function exec_command_call(): SseEvent {
|
||||
return {
|
||||
type: "response.output_item.done",
|
||||
item: {
|
||||
type: "function_call",
|
||||
call_id: `call_id${Math.random().toString(36).slice(2)}`,
|
||||
name: "exec_command",
|
||||
arguments: JSON.stringify({
|
||||
cmd: "echo 'Hello, world!'",
|
||||
yield_time_ms: 100,
|
||||
}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function responseFailed(errorMessage: string): SseEvent {
|
||||
return {
|
||||
type: "error",
|
||||
error: { code: "rate_limit_exceeded", message: errorMessage },
|
||||
};
|
||||
}
|
||||
|
||||
export function responseCompleted(
|
||||
responseId: string = DEFAULT_RESPONSE_ID,
|
||||
usage: ResponseCompletedUsage = DEFAULT_COMPLETED_USAGE,
|
||||
): SseEvent {
|
||||
const inputDetails = usage.input_tokens_details ? { ...usage.input_tokens_details } : null;
|
||||
const outputDetails = usage.output_tokens_details ? { ...usage.output_tokens_details } : null;
|
||||
return {
|
||||
type: "response.completed",
|
||||
response: {
|
||||
id: responseId,
|
||||
usage: {
|
||||
input_tokens: usage.input_tokens,
|
||||
input_tokens_details: inputDetails,
|
||||
output_tokens: usage.output_tokens,
|
||||
output_tokens_details: outputDetails,
|
||||
total_tokens: usage.total_tokens,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
902
sdk/typescript/tests/run.test.ts
Normal file
902
sdk/typescript/tests/run.test.ts
Normal file
@@ -0,0 +1,902 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { codexExecSpy } from "./codexExecSpy";
|
||||
import { describe, expect, it } from "@jest/globals";
|
||||
|
||||
import {
|
||||
assistantMessage,
|
||||
responseCompleted,
|
||||
responseStarted,
|
||||
sse,
|
||||
responseFailed,
|
||||
startResponsesTestProxy,
|
||||
SseResponseBody,
|
||||
} from "./responsesProxy";
|
||||
import { createMockClient, createTestClient } from "./testCodex";
|
||||
|
||||
describe("Codex", () => {
|
||||
it("returns thread events", async () => {
|
||||
const { url, close } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [sse(responseStarted(), assistantMessage("Hi!"), responseCompleted())],
|
||||
});
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread();
|
||||
const result = await thread.run("Hello, world!");
|
||||
|
||||
const expectedItems = [
|
||||
{
|
||||
id: expect.any(String),
|
||||
type: "agent_message",
|
||||
text: "Hi!",
|
||||
},
|
||||
];
|
||||
expect(result.items).toEqual(expectedItems);
|
||||
expect(result.usage).toEqual({
|
||||
cache_write_input_tokens: 0,
|
||||
cached_input_tokens: 12,
|
||||
input_tokens: 42,
|
||||
output_tokens: 5,
|
||||
reasoning_output_tokens: 0,
|
||||
});
|
||||
expect(thread.id).toEqual(expect.any(String));
|
||||
} finally {
|
||||
cleanup();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
it("sends previous items when run is called twice", async () => {
|
||||
const { url, close, requests } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [
|
||||
sse(
|
||||
responseStarted("response_1"),
|
||||
assistantMessage("First response", "item_1"),
|
||||
responseCompleted("response_1"),
|
||||
),
|
||||
sse(
|
||||
responseStarted("response_2"),
|
||||
assistantMessage("Second response", "item_2"),
|
||||
responseCompleted("response_2"),
|
||||
),
|
||||
],
|
||||
});
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread();
|
||||
await thread.run("first input");
|
||||
await thread.run("second input");
|
||||
|
||||
// Check second request continues the same thread
|
||||
expect(requests.length).toBeGreaterThanOrEqual(2);
|
||||
const secondRequest = requests[1];
|
||||
expect(secondRequest).toBeDefined();
|
||||
const payload = secondRequest!.json;
|
||||
|
||||
const assistantEntry = payload.input.find(
|
||||
(entry: { role: string }) => entry.role === "assistant",
|
||||
);
|
||||
expect(assistantEntry).toBeDefined();
|
||||
const assistantText = assistantEntry?.content?.find(
|
||||
(item: { type: string; text: string }) => item.type === "output_text",
|
||||
)?.text;
|
||||
expect(assistantText).toBe("First response");
|
||||
} finally {
|
||||
cleanup();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
it("continues the thread when run is called twice with options", async () => {
|
||||
const { url, close, requests } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [
|
||||
sse(
|
||||
responseStarted("response_1"),
|
||||
assistantMessage("First response", "item_1"),
|
||||
responseCompleted("response_1"),
|
||||
),
|
||||
sse(
|
||||
responseStarted("response_2"),
|
||||
assistantMessage("Second response", "item_2"),
|
||||
responseCompleted("response_2"),
|
||||
),
|
||||
],
|
||||
});
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread();
|
||||
await thread.run("first input");
|
||||
await thread.run("second input");
|
||||
|
||||
// Check second request continues the same thread
|
||||
expect(requests.length).toBeGreaterThanOrEqual(2);
|
||||
const secondRequest = requests[1];
|
||||
expect(secondRequest).toBeDefined();
|
||||
const payload = secondRequest!.json;
|
||||
|
||||
expect(payload.input.at(-1)!.content![0]!.text).toBe("second input");
|
||||
const assistantEntry = payload.input.find(
|
||||
(entry: { role: string }) => entry.role === "assistant",
|
||||
);
|
||||
expect(assistantEntry).toBeDefined();
|
||||
const assistantText = assistantEntry?.content?.find(
|
||||
(item: { type: string; text: string }) => item.type === "output_text",
|
||||
)?.text;
|
||||
expect(assistantText).toBe("First response");
|
||||
} finally {
|
||||
cleanup();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
it("resumes thread by id", async () => {
|
||||
const { url, close, requests } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [
|
||||
sse(
|
||||
responseStarted("response_1"),
|
||||
assistantMessage("First response", "item_1"),
|
||||
responseCompleted("response_1"),
|
||||
),
|
||||
sse(
|
||||
responseStarted("response_2"),
|
||||
assistantMessage("Second response", "item_2"),
|
||||
responseCompleted("response_2"),
|
||||
),
|
||||
],
|
||||
});
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const originalThread = client.startThread();
|
||||
await originalThread.run("first input");
|
||||
|
||||
const resumedThread = client.resumeThread(originalThread.id!);
|
||||
const result = await resumedThread.run("second input");
|
||||
|
||||
expect(resumedThread.id).toBe(originalThread.id);
|
||||
expect(result.finalResponse).toBe("Second response");
|
||||
|
||||
expect(requests.length).toBeGreaterThanOrEqual(2);
|
||||
const secondRequest = requests[1];
|
||||
expect(secondRequest).toBeDefined();
|
||||
const payload = secondRequest!.json;
|
||||
|
||||
const assistantEntry = payload.input.find(
|
||||
(entry: { role: string }) => entry.role === "assistant",
|
||||
);
|
||||
expect(assistantEntry).toBeDefined();
|
||||
const assistantText = assistantEntry?.content?.find(
|
||||
(item: { type: string; text: string }) => item.type === "output_text",
|
||||
)?.text;
|
||||
expect(assistantText).toBe("First response");
|
||||
} finally {
|
||||
cleanup();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
it("passes turn options to exec", async () => {
|
||||
const { url, close, requests } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [
|
||||
sse(
|
||||
responseStarted("response_1"),
|
||||
assistantMessage("Turn options applied", "item_1"),
|
||||
responseCompleted("response_1"),
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
const { args: spawnArgs, restore } = codexExecSpy();
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread({
|
||||
model: "gpt-test-1",
|
||||
threadSource: "automated_review",
|
||||
sandboxMode: "workspace-write",
|
||||
});
|
||||
await thread.run("apply options");
|
||||
|
||||
const payload = requests[0];
|
||||
expect(payload).toBeDefined();
|
||||
const json = payload!.json as { model?: string } | undefined;
|
||||
|
||||
expect(json?.model).toBe("gpt-test-1");
|
||||
expect(spawnArgs.length).toBeGreaterThan(0);
|
||||
const commandArgs = spawnArgs[0];
|
||||
|
||||
expectPair(commandArgs, ["--sandbox", "workspace-write"]);
|
||||
expectPair(commandArgs, ["--model", "gpt-test-1"]);
|
||||
expectPair(commandArgs, ["--thread-source", "automated_review"]);
|
||||
const metadata = JSON.parse(payload!.headers["x-codex-turn-metadata"] as string) as {
|
||||
thread_source?: string;
|
||||
};
|
||||
expect(metadata.thread_source).toBe("automated_review");
|
||||
} finally {
|
||||
cleanup();
|
||||
restore();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
it("passes cyber access program selections only to the turns that specify them", async () => {
|
||||
const { url, close } = await startResponsesTestProxy({
|
||||
responseBodies: [
|
||||
sse(responseCompleted("response_1")),
|
||||
sse(responseCompleted("response_2")),
|
||||
sse(responseCompleted("response_3")),
|
||||
sse(responseCompleted("response_4")),
|
||||
],
|
||||
});
|
||||
const { args: spawnArgs, restore } = codexExecSpy();
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread();
|
||||
await thread.run("select blue", { cyberAccessProgram: "daybreak_blue" });
|
||||
const threadId = thread.id;
|
||||
expect(threadId).toEqual(expect.any(String));
|
||||
|
||||
const streamed = await thread.runStreamed("select red", {
|
||||
cyberAccessProgram: "daybreak_red",
|
||||
});
|
||||
for await (const _ of streamed.events) {
|
||||
// Consume the streamed turn before resuming the thread.
|
||||
}
|
||||
await thread.run("select standard", { cyberAccessProgram: "standard" });
|
||||
await thread.run("use automatic selection");
|
||||
|
||||
expect(spawnArgs).toHaveLength(4);
|
||||
expectPair(spawnArgs[0], ["--cyber-access-program", "daybreak_blue"]);
|
||||
expectPair(spawnArgs[1], ["--cyber-access-program", "daybreak_red"]);
|
||||
expectPair(spawnArgs[2], ["--cyber-access-program", "standard"]);
|
||||
expect(spawnArgs[3]).not.toContain("--cyber-access-program");
|
||||
for (const args of spawnArgs.slice(1)) {
|
||||
expectPair(args, ["resume", threadId!]);
|
||||
}
|
||||
} finally {
|
||||
cleanup();
|
||||
restore();
|
||||
await close();
|
||||
}
|
||||
}, 15_000);
|
||||
|
||||
it.each(["high", "persistent"] as const)(
|
||||
"passes %s modelReasoningEffort to exec",
|
||||
async (effort) => {
|
||||
const { url, close } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [
|
||||
sse(
|
||||
responseStarted("response_1"),
|
||||
assistantMessage("Reasoning effort applied", "item_1"),
|
||||
responseCompleted("response_1"),
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
const { args: spawnArgs, restore } = codexExecSpy();
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread({
|
||||
modelReasoningEffort: effort,
|
||||
});
|
||||
await thread.run("apply reasoning effort");
|
||||
|
||||
const commandArgs = spawnArgs[0];
|
||||
expect(commandArgs).toBeDefined();
|
||||
expectPair(commandArgs, ["--config", `model_reasoning_effort="${effort}"`]);
|
||||
} finally {
|
||||
cleanup();
|
||||
restore();
|
||||
await close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("passes networkAccessEnabled to exec", async () => {
|
||||
const { url, close } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [
|
||||
sse(
|
||||
responseStarted("response_1"),
|
||||
assistantMessage("Network access enabled", "item_1"),
|
||||
responseCompleted("response_1"),
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
const { args: spawnArgs, restore } = codexExecSpy();
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread({
|
||||
networkAccessEnabled: true,
|
||||
});
|
||||
await thread.run("test network access");
|
||||
|
||||
const commandArgs = spawnArgs[0];
|
||||
expect(commandArgs).toBeDefined();
|
||||
expectPair(commandArgs, ["--config", "sandbox_workspace_write.network_access=true"]);
|
||||
} finally {
|
||||
cleanup();
|
||||
restore();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
it("passes webSearchEnabled to exec", async () => {
|
||||
const { url, close } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [
|
||||
sse(
|
||||
responseStarted("response_1"),
|
||||
assistantMessage("Web search enabled", "item_1"),
|
||||
responseCompleted("response_1"),
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
const { args: spawnArgs, restore } = codexExecSpy();
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread({
|
||||
webSearchEnabled: true,
|
||||
});
|
||||
await thread.run("test web search");
|
||||
|
||||
const commandArgs = spawnArgs[0];
|
||||
expect(commandArgs).toBeDefined();
|
||||
expectPair(commandArgs, ["--config", 'web_search="live"']);
|
||||
} finally {
|
||||
cleanup();
|
||||
restore();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
it("passes webSearchMode to exec", async () => {
|
||||
const { url, close } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [
|
||||
sse(
|
||||
responseStarted("response_1"),
|
||||
assistantMessage("Web search cached", "item_1"),
|
||||
responseCompleted("response_1"),
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
const { args: spawnArgs, restore } = codexExecSpy();
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread({
|
||||
webSearchMode: "cached",
|
||||
});
|
||||
await thread.run("test web search mode");
|
||||
|
||||
const commandArgs = spawnArgs[0];
|
||||
expect(commandArgs).toBeDefined();
|
||||
expectPair(commandArgs, ["--config", 'web_search="cached"']);
|
||||
} finally {
|
||||
cleanup();
|
||||
restore();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
it("passes webSearchEnabled false to exec", async () => {
|
||||
const { url, close } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [
|
||||
sse(
|
||||
responseStarted("response_1"),
|
||||
assistantMessage("Web search disabled", "item_1"),
|
||||
responseCompleted("response_1"),
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
const { args: spawnArgs, restore } = codexExecSpy();
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread({
|
||||
webSearchEnabled: false,
|
||||
});
|
||||
await thread.run("test web search disabled");
|
||||
|
||||
const commandArgs = spawnArgs[0];
|
||||
expect(commandArgs).toBeDefined();
|
||||
expectPair(commandArgs, ["--config", 'web_search="disabled"']);
|
||||
} finally {
|
||||
cleanup();
|
||||
restore();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
it("passes approvalPolicy to exec", async () => {
|
||||
const { url, close } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [
|
||||
sse(
|
||||
responseStarted("response_1"),
|
||||
assistantMessage("Approval policy set", "item_1"),
|
||||
responseCompleted("response_1"),
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
const { args: spawnArgs, restore } = codexExecSpy();
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread({
|
||||
approvalPolicy: "on-request",
|
||||
});
|
||||
await thread.run("test approval policy");
|
||||
|
||||
const commandArgs = spawnArgs[0];
|
||||
expect(commandArgs).toBeDefined();
|
||||
expectPair(commandArgs, ["--config", 'approval_policy="on-request"']);
|
||||
} finally {
|
||||
cleanup();
|
||||
restore();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
it("passes CodexOptions config overrides as TOML --config flags", async () => {
|
||||
const { url, close } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [
|
||||
sse(
|
||||
responseStarted("response_1"),
|
||||
assistantMessage("Config overrides applied", "item_1"),
|
||||
responseCompleted("response_1"),
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
const { args: spawnArgs, restore } = codexExecSpy();
|
||||
const { client, cleanup } = createTestClient({
|
||||
baseUrl: url,
|
||||
apiKey: "test",
|
||||
config: {
|
||||
approval_policy: "never",
|
||||
sandbox_workspace_write: { network_access: true },
|
||||
retry_budget: 3,
|
||||
tool_rules: { allow: ["git status", "git diff"] },
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const thread = client.startThread();
|
||||
await thread.run("apply config overrides");
|
||||
|
||||
const commandArgs = spawnArgs[0];
|
||||
expect(commandArgs).toBeDefined();
|
||||
expectPair(commandArgs, ["--config", 'approval_policy="never"']);
|
||||
expectPair(commandArgs, ["--config", "sandbox_workspace_write.network_access=true"]);
|
||||
expectPair(commandArgs, ["--config", "retry_budget=3"]);
|
||||
expectPair(commandArgs, ["--config", 'tool_rules.allow=["git status", "git diff"]']);
|
||||
} finally {
|
||||
cleanup();
|
||||
restore();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
it("lets thread options override CodexOptions config overrides", async () => {
|
||||
const { url, close } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [
|
||||
sse(
|
||||
responseStarted("response_1"),
|
||||
assistantMessage("Thread overrides applied", "item_1"),
|
||||
responseCompleted("response_1"),
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
const { args: spawnArgs, restore } = codexExecSpy();
|
||||
const { client, cleanup } = createTestClient({
|
||||
baseUrl: url,
|
||||
apiKey: "test",
|
||||
config: { approval_policy: "never" },
|
||||
});
|
||||
|
||||
try {
|
||||
const thread = client.startThread({ approvalPolicy: "on-request" });
|
||||
await thread.run("override approval policy");
|
||||
|
||||
const commandArgs = spawnArgs[0];
|
||||
const approvalPolicyOverrides = collectConfigValues(commandArgs, "approval_policy");
|
||||
expect(approvalPolicyOverrides).toEqual([
|
||||
'approval_policy="never"',
|
||||
'approval_policy="on-request"',
|
||||
]);
|
||||
expect(approvalPolicyOverrides.at(-1)).toBe('approval_policy="on-request"');
|
||||
} finally {
|
||||
cleanup();
|
||||
restore();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
it("passes raw permission maps unchanged while preserving override precedence", async () => {
|
||||
const { url, close } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [
|
||||
sse(
|
||||
responseStarted("response_1"),
|
||||
assistantMessage("Raw config overrides applied", "item_1"),
|
||||
responseCompleted("response_1"),
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
// TODO(anp): Add the sandbox helper to the SDK workflow so this can use a deny-read override.
|
||||
const writablePath = path.join(os.tmpdir(), "codex-sdk-config.env");
|
||||
const permissionOverride = `permissions.sdk_test.filesystem={":root"="read",${JSON.stringify(writablePath)}="write"}`;
|
||||
const { args: spawnArgs, restore } = codexExecSpy();
|
||||
const { client, cleanup } = createTestClient({
|
||||
baseUrl: url,
|
||||
apiKey: "test",
|
||||
config: { approval_policy: "never", default_permissions: "sdk_test" },
|
||||
configOverrides: [permissionOverride, 'approval_policy="on-failure"'],
|
||||
});
|
||||
|
||||
try {
|
||||
const thread = client.startThread({ approvalPolicy: "on-request" });
|
||||
await thread.run("apply raw config overrides");
|
||||
|
||||
const commandArgs = spawnArgs[0];
|
||||
expectPair(commandArgs, ["--config", permissionOverride]);
|
||||
expectPair(commandArgs, ["--config", 'default_permissions="sdk_test"']);
|
||||
expect(collectConfigValues(commandArgs, "approval_policy")).toEqual([
|
||||
'approval_policy="never"',
|
||||
'approval_policy="on-failure"',
|
||||
'approval_policy="on-request"',
|
||||
]);
|
||||
} finally {
|
||||
cleanup();
|
||||
restore();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
it("passes additionalDirectories as repeated flags", async () => {
|
||||
const { url, close } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [
|
||||
sse(
|
||||
responseStarted("response_1"),
|
||||
assistantMessage("Additional directories applied", "item_1"),
|
||||
responseCompleted("response_1"),
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
const { args: spawnArgs, restore } = codexExecSpy();
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread({
|
||||
additionalDirectories: ["../backend", "/tmp/shared"],
|
||||
});
|
||||
await thread.run("test additional dirs");
|
||||
|
||||
const commandArgs = spawnArgs[0];
|
||||
expect(commandArgs).toBeDefined();
|
||||
if (!commandArgs) {
|
||||
throw new Error("Command args missing");
|
||||
}
|
||||
|
||||
// Find the --add-dir flags
|
||||
const addDirArgs: string[] = [];
|
||||
for (let i = 0; i < commandArgs.length; i += 1) {
|
||||
if (commandArgs[i] === "--add-dir") {
|
||||
addDirArgs.push(commandArgs[i + 1] ?? "");
|
||||
}
|
||||
}
|
||||
expect(addDirArgs).toEqual(["../backend", "/tmp/shared"]);
|
||||
} finally {
|
||||
cleanup();
|
||||
restore();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
it("writes output schema to a temporary file and forwards it", async () => {
|
||||
const { url, close, requests } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [
|
||||
sse(
|
||||
responseStarted("response_1"),
|
||||
assistantMessage("Structured response", "item_1"),
|
||||
responseCompleted("response_1"),
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
const { args: spawnArgs, restore } = codexExecSpy();
|
||||
|
||||
const schema = {
|
||||
type: "object",
|
||||
properties: {
|
||||
answer: { type: "string" },
|
||||
},
|
||||
required: ["answer"],
|
||||
additionalProperties: false,
|
||||
} as const;
|
||||
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread();
|
||||
await thread.run("structured", { outputSchema: schema });
|
||||
|
||||
expect(requests.length).toBeGreaterThanOrEqual(1);
|
||||
const payload = requests[0];
|
||||
expect(payload).toBeDefined();
|
||||
const text = payload!.json.text;
|
||||
expect(text).toBeDefined();
|
||||
expect(text?.format).toEqual({
|
||||
name: "codex_output_schema",
|
||||
type: "json_schema",
|
||||
strict: true,
|
||||
schema,
|
||||
});
|
||||
|
||||
const commandArgs = spawnArgs[0];
|
||||
expect(commandArgs).toBeDefined();
|
||||
const schemaFlagIndex = commandArgs!.indexOf("--output-schema");
|
||||
expect(schemaFlagIndex).toBeGreaterThan(-1);
|
||||
const schemaPath = commandArgs![schemaFlagIndex + 1];
|
||||
expect(typeof schemaPath).toBe("string");
|
||||
if (typeof schemaPath !== "string") {
|
||||
throw new Error("--output-schema flag missing path argument");
|
||||
}
|
||||
expect(fs.existsSync(schemaPath)).toBe(false);
|
||||
} finally {
|
||||
cleanup();
|
||||
restore();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
it("combines structured text input segments", async () => {
|
||||
const { url, close, requests } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [
|
||||
sse(
|
||||
responseStarted("response_1"),
|
||||
assistantMessage("Combined input applied", "item_1"),
|
||||
responseCompleted("response_1"),
|
||||
),
|
||||
],
|
||||
});
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread();
|
||||
await thread.run([
|
||||
{ type: "text", text: "Describe file changes" },
|
||||
{ type: "text", text: "Focus on impacted tests" },
|
||||
]);
|
||||
|
||||
const payload = requests[0];
|
||||
expect(payload).toBeDefined();
|
||||
const lastUser = payload!.json.input.at(-1);
|
||||
expect(lastUser?.content?.[0]?.text).toBe("Describe file changes\n\nFocus on impacted tests");
|
||||
} finally {
|
||||
cleanup();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
it("forwards images to exec", async () => {
|
||||
const { url, close } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [
|
||||
sse(
|
||||
responseStarted("response_1"),
|
||||
assistantMessage("Images applied", "item_1"),
|
||||
responseCompleted("response_1"),
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
const { args: spawnArgs, restore } = codexExecSpy();
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "codex-images-"));
|
||||
const imagesDirectoryEntries: [string, string] = [
|
||||
path.join(tempDir, "first.png"),
|
||||
path.join(tempDir, "second.jpg"),
|
||||
];
|
||||
imagesDirectoryEntries.forEach((image, index) => {
|
||||
fs.writeFileSync(image, `image-${index}`);
|
||||
});
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread();
|
||||
await thread.run([
|
||||
{ type: "text", text: "describe the images" },
|
||||
{ type: "local_image", path: imagesDirectoryEntries[0] },
|
||||
{ type: "local_image", path: imagesDirectoryEntries[1] },
|
||||
]);
|
||||
|
||||
const commandArgs = spawnArgs[0];
|
||||
expect(commandArgs).toBeDefined();
|
||||
const forwardedImages: string[] = [];
|
||||
for (let i = 0; i < commandArgs!.length; i += 1) {
|
||||
if (commandArgs![i] === "--image") {
|
||||
forwardedImages.push(commandArgs![i + 1] ?? "");
|
||||
}
|
||||
}
|
||||
expect(forwardedImages).toEqual(imagesDirectoryEntries);
|
||||
} finally {
|
||||
cleanup();
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
restore();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
it("runs in provided working directory", async () => {
|
||||
const { url, close } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [
|
||||
sse(
|
||||
responseStarted("response_1"),
|
||||
assistantMessage("Working directory applied", "item_1"),
|
||||
responseCompleted("response_1"),
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
const { args: spawnArgs, restore } = codexExecSpy();
|
||||
const workingDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "codex-working-dir-"));
|
||||
const { client, cleanup } = createTestClient({
|
||||
baseUrl: url,
|
||||
apiKey: "test",
|
||||
});
|
||||
|
||||
try {
|
||||
const thread = client.startThread({
|
||||
workingDirectory,
|
||||
skipGitRepoCheck: true,
|
||||
});
|
||||
await thread.run("use custom working directory");
|
||||
|
||||
const commandArgs = spawnArgs[0];
|
||||
expectPair(commandArgs, ["--cd", workingDirectory]);
|
||||
} finally {
|
||||
cleanup();
|
||||
fs.rmSync(workingDirectory, { recursive: true, force: true });
|
||||
restore();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
it("throws if working directory is not git and no skipGitRepoCheck is provided", async () => {
|
||||
const { url, close } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [
|
||||
sse(
|
||||
responseStarted("response_1"),
|
||||
assistantMessage("Working directory applied", "item_1"),
|
||||
responseCompleted("response_1"),
|
||||
),
|
||||
],
|
||||
});
|
||||
const workingDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "codex-working-dir-"));
|
||||
const { client, cleanup } = createTestClient({
|
||||
baseUrl: url,
|
||||
apiKey: "test",
|
||||
});
|
||||
|
||||
try {
|
||||
const thread = client.startThread({
|
||||
workingDirectory,
|
||||
});
|
||||
await expect(thread.run("use custom working directory")).rejects.toThrow(
|
||||
/Not inside a trusted directory/,
|
||||
);
|
||||
} finally {
|
||||
cleanup();
|
||||
fs.rmSync(workingDirectory, { recursive: true, force: true });
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
it("sets the codex sdk originator header", async () => {
|
||||
const { url, close, requests } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [sse(responseStarted(), assistantMessage("Hi!"), responseCompleted())],
|
||||
});
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread();
|
||||
await thread.run("Hello, originator!");
|
||||
|
||||
expect(requests.length).toBeGreaterThan(0);
|
||||
const originatorHeader = requests[0]!.headers["originator"];
|
||||
if (Array.isArray(originatorHeader)) {
|
||||
expect(originatorHeader).toContain("codex_sdk_ts");
|
||||
} else {
|
||||
expect(originatorHeader).toBe("codex_sdk_ts");
|
||||
}
|
||||
} finally {
|
||||
cleanup();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
it("throws ThreadRunError on turn failures", async () => {
|
||||
const { url, close } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: (function* (): Generator<SseResponseBody> {
|
||||
yield sse(responseStarted("response_1"));
|
||||
while (true) {
|
||||
yield sse(responseFailed("rate limit exceeded"));
|
||||
}
|
||||
})(),
|
||||
});
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread();
|
||||
await expect(thread.run("fail")).rejects.toThrow("stream disconnected before completion:");
|
||||
} finally {
|
||||
cleanup();
|
||||
await close();
|
||||
}
|
||||
}, 10000); // TODO(pakrym): remove timeout
|
||||
});
|
||||
|
||||
/**
|
||||
* Given a list of args to `codex` and a `key`, collects all `--config`
|
||||
* overrides for that key.
|
||||
*/
|
||||
function collectConfigValues(args: string[] | undefined, key: string): string[] {
|
||||
if (!args) {
|
||||
throw new Error("args is undefined");
|
||||
}
|
||||
|
||||
const values: string[] = [];
|
||||
for (let i = 0; i < args.length; i += 1) {
|
||||
if (args[i] !== "--config") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const override = args[i + 1];
|
||||
if (override?.startsWith(`${key}=`)) {
|
||||
values.push(override);
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
function expectPair(args: string[] | undefined, pair: [string, string]) {
|
||||
if (!args) {
|
||||
throw new Error("args is undefined");
|
||||
}
|
||||
const index = args.findIndex((arg, i) => arg === pair[0] && args[i + 1] === pair[1]);
|
||||
if (index === -1) {
|
||||
throw new Error(`Pair ${pair[0]} ${pair[1]} not found in args`);
|
||||
}
|
||||
expect(args[index + 1]).toBe(pair[1]);
|
||||
}
|
||||
209
sdk/typescript/tests/runStreamed.test.ts
Normal file
209
sdk/typescript/tests/runStreamed.test.ts
Normal file
@@ -0,0 +1,209 @@
|
||||
import { describe, expect, it } from "@jest/globals";
|
||||
|
||||
import { ThreadEvent } from "../src/index";
|
||||
|
||||
import {
|
||||
assistantMessage,
|
||||
responseCompleted,
|
||||
responseStarted,
|
||||
sse,
|
||||
startResponsesTestProxy,
|
||||
} from "./responsesProxy";
|
||||
import { createMockClient } from "./testCodex";
|
||||
|
||||
describe("Codex", () => {
|
||||
it("returns thread events", async () => {
|
||||
const { url, close } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [sse(responseStarted(), assistantMessage("Hi!"), responseCompleted())],
|
||||
});
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread();
|
||||
const result = await thread.runStreamed("Hello, world!");
|
||||
|
||||
const events: ThreadEvent[] = [];
|
||||
for await (const event of result.events) {
|
||||
events.push(event);
|
||||
}
|
||||
|
||||
expect(events).toEqual([
|
||||
{
|
||||
type: "thread.started",
|
||||
thread_id: expect.any(String),
|
||||
},
|
||||
{
|
||||
type: "turn.started",
|
||||
},
|
||||
{
|
||||
type: "item.completed",
|
||||
item: {
|
||||
id: "item_0",
|
||||
type: "agent_message",
|
||||
text: "Hi!",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
usage: {
|
||||
cache_write_input_tokens: 0,
|
||||
cached_input_tokens: 12,
|
||||
input_tokens: 42,
|
||||
output_tokens: 5,
|
||||
reasoning_output_tokens: 0,
|
||||
},
|
||||
},
|
||||
]);
|
||||
expect(thread.id).toEqual(expect.any(String));
|
||||
} finally {
|
||||
cleanup();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
it("sends previous items when runStreamed is called twice", async () => {
|
||||
const { url, close, requests } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [
|
||||
sse(
|
||||
responseStarted("response_1"),
|
||||
assistantMessage("First response", "item_1"),
|
||||
responseCompleted("response_1"),
|
||||
),
|
||||
sse(
|
||||
responseStarted("response_2"),
|
||||
assistantMessage("Second response", "item_2"),
|
||||
responseCompleted("response_2"),
|
||||
),
|
||||
],
|
||||
});
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const thread = client.startThread();
|
||||
const first = await thread.runStreamed("first input");
|
||||
await drainEvents(first.events);
|
||||
|
||||
const second = await thread.runStreamed("second input");
|
||||
await drainEvents(second.events);
|
||||
|
||||
// Check second request continues the same thread
|
||||
expect(requests.length).toBeGreaterThanOrEqual(2);
|
||||
const secondRequest = requests[1];
|
||||
expect(secondRequest).toBeDefined();
|
||||
const payload = secondRequest!.json;
|
||||
|
||||
const assistantEntry = payload.input.find(
|
||||
(entry: { role: string }) => entry.role === "assistant",
|
||||
);
|
||||
expect(assistantEntry).toBeDefined();
|
||||
const assistantText = assistantEntry?.content?.find(
|
||||
(item: { type: string; text: string }) => item.type === "output_text",
|
||||
)?.text;
|
||||
expect(assistantText).toBe("First response");
|
||||
} finally {
|
||||
cleanup();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
it("resumes thread by id when streaming", async () => {
|
||||
const { url, close, requests } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [
|
||||
sse(
|
||||
responseStarted("response_1"),
|
||||
assistantMessage("First response", "item_1"),
|
||||
responseCompleted("response_1"),
|
||||
),
|
||||
sse(
|
||||
responseStarted("response_2"),
|
||||
assistantMessage("Second response", "item_2"),
|
||||
responseCompleted("response_2"),
|
||||
),
|
||||
],
|
||||
});
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
try {
|
||||
const originalThread = client.startThread();
|
||||
const first = await originalThread.runStreamed("first input");
|
||||
await drainEvents(first.events);
|
||||
|
||||
const resumedThread = client.resumeThread(originalThread.id!);
|
||||
const second = await resumedThread.runStreamed("second input");
|
||||
await drainEvents(second.events);
|
||||
|
||||
expect(resumedThread.id).toBe(originalThread.id);
|
||||
|
||||
expect(requests.length).toBeGreaterThanOrEqual(2);
|
||||
const secondRequest = requests[1];
|
||||
expect(secondRequest).toBeDefined();
|
||||
const payload = secondRequest!.json;
|
||||
|
||||
const assistantEntry = payload.input.find(
|
||||
(entry: { role: string }) => entry.role === "assistant",
|
||||
);
|
||||
expect(assistantEntry).toBeDefined();
|
||||
const assistantText = assistantEntry?.content?.find(
|
||||
(item: { type: string; text: string }) => item.type === "output_text",
|
||||
)?.text;
|
||||
expect(assistantText).toBe("First response");
|
||||
} finally {
|
||||
cleanup();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
it("applies output schema turn options when streaming", async () => {
|
||||
const { url, close, requests } = await startResponsesTestProxy({
|
||||
statusCode: 200,
|
||||
responseBodies: [
|
||||
sse(
|
||||
responseStarted("response_1"),
|
||||
assistantMessage("Structured response", "item_1"),
|
||||
responseCompleted("response_1"),
|
||||
),
|
||||
],
|
||||
});
|
||||
const { client, cleanup } = createMockClient(url);
|
||||
|
||||
const schema = {
|
||||
type: "object",
|
||||
properties: {
|
||||
answer: { type: "string" },
|
||||
},
|
||||
required: ["answer"],
|
||||
additionalProperties: false,
|
||||
} as const;
|
||||
|
||||
try {
|
||||
const thread = client.startThread();
|
||||
const streamed = await thread.runStreamed("structured", { outputSchema: schema });
|
||||
await drainEvents(streamed.events);
|
||||
|
||||
expect(requests.length).toBeGreaterThanOrEqual(1);
|
||||
const payload = requests[0];
|
||||
expect(payload).toBeDefined();
|
||||
const text = payload!.json.text;
|
||||
expect(text).toBeDefined();
|
||||
expect(text?.format).toEqual({
|
||||
name: "codex_output_schema",
|
||||
type: "json_schema",
|
||||
strict: true,
|
||||
schema,
|
||||
});
|
||||
} finally {
|
||||
cleanup();
|
||||
await close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
async function drainEvents(events: AsyncGenerator<ThreadEvent>): Promise<void> {
|
||||
let done = false;
|
||||
do {
|
||||
done = (await events.next()).done ?? false;
|
||||
} while (!done);
|
||||
}
|
||||
28
sdk/typescript/tests/setupCodexHome.ts
Normal file
28
sdk/typescript/tests/setupCodexHome.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { afterEach, beforeEach } from "@jest/globals";
|
||||
|
||||
const originalCodexHome = process.env.CODEX_HOME;
|
||||
let currentCodexHome: string | undefined;
|
||||
|
||||
beforeEach(async () => {
|
||||
currentCodexHome = await fs.mkdtemp(path.join(os.tmpdir(), "codex-sdk-test-"));
|
||||
process.env.CODEX_HOME = currentCodexHome;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
const codexHomeToDelete = currentCodexHome;
|
||||
currentCodexHome = undefined;
|
||||
|
||||
if (originalCodexHome === undefined) {
|
||||
delete process.env.CODEX_HOME;
|
||||
} else {
|
||||
process.env.CODEX_HOME = originalCodexHome;
|
||||
}
|
||||
|
||||
if (codexHomeToDelete) {
|
||||
await fs.rm(codexHomeToDelete, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
108
sdk/typescript/tests/testCodex.ts
Normal file
108
sdk/typescript/tests/testCodex.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import path from "node:path";
|
||||
|
||||
import { Codex } from "../src/codex";
|
||||
import type { CodexConfigObject } from "../src/codexOptions";
|
||||
|
||||
export const codexExecPath =
|
||||
process.env.CODEX_EXEC_PATH ??
|
||||
path.join(process.cwd(), "..", "..", "codex-rs", "target", "debug", "codex");
|
||||
|
||||
type CreateTestClientOptions = {
|
||||
apiKey?: string;
|
||||
baseUrl?: string;
|
||||
config?: CodexConfigObject;
|
||||
configOverrides?: string[];
|
||||
env?: Record<string, string>;
|
||||
inheritEnv?: boolean;
|
||||
};
|
||||
|
||||
export type TestClient = {
|
||||
cleanup: () => void;
|
||||
client: Codex;
|
||||
};
|
||||
|
||||
export function createMockClient(url: string): TestClient {
|
||||
return createTestClient({
|
||||
config: {
|
||||
model_provider: "mock",
|
||||
model_providers: {
|
||||
mock: {
|
||||
name: "Mock provider for test",
|
||||
base_url: url,
|
||||
wire_api: "responses",
|
||||
supports_websockets: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function createTestClient(options: CreateTestClientOptions = {}): TestClient {
|
||||
const env =
|
||||
options.inheritEnv === false ? { ...options.env } : { ...getCurrentEnv(), ...options.env };
|
||||
|
||||
return {
|
||||
cleanup: () => {},
|
||||
client: new Codex({
|
||||
codexPathOverride: codexExecPath,
|
||||
baseUrl: options.baseUrl,
|
||||
apiKey: options.apiKey,
|
||||
config: mergeTestConfig(options.baseUrl, options.config),
|
||||
configOverrides: options.configOverrides,
|
||||
env,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function mergeTestConfig(
|
||||
baseUrl: string | undefined,
|
||||
config: CodexConfigObject | undefined,
|
||||
): CodexConfigObject | undefined {
|
||||
const mergedConfig: CodexConfigObject | undefined =
|
||||
!baseUrl || hasExplicitProviderConfig(config)
|
||||
? config
|
||||
: {
|
||||
...config,
|
||||
// Built-in providers are merged before user config, so tests need a
|
||||
// custom provider entry to force SSE against the local mock server.
|
||||
model_provider: "mock",
|
||||
model_providers: {
|
||||
mock: {
|
||||
name: "Mock provider for test",
|
||||
base_url: baseUrl,
|
||||
wire_api: "responses",
|
||||
supports_websockets: false,
|
||||
},
|
||||
},
|
||||
};
|
||||
const featureOverrides = mergedConfig?.features;
|
||||
|
||||
return {
|
||||
...mergedConfig,
|
||||
// Disable plugins in SDK integration tests so background curated-plugin
|
||||
// sync does not race temp CODEX_HOME cleanup.
|
||||
features:
|
||||
featureOverrides && typeof featureOverrides === "object" && !Array.isArray(featureOverrides)
|
||||
? { ...featureOverrides, plugins: false }
|
||||
: { plugins: false },
|
||||
};
|
||||
}
|
||||
|
||||
function hasExplicitProviderConfig(config: CodexConfigObject | undefined): boolean {
|
||||
return config?.model_provider !== undefined || config?.model_providers !== undefined;
|
||||
}
|
||||
|
||||
function getCurrentEnv(): Record<string, string> {
|
||||
const env: Record<string, string> = {};
|
||||
|
||||
for (const [key, value] of Object.entries(process.env)) {
|
||||
if (key === "CODEX_INTERNAL_ORIGINATOR_OVERRIDE") {
|
||||
continue;
|
||||
}
|
||||
if (value !== undefined) {
|
||||
env[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return env;
|
||||
}
|
||||
24
sdk/typescript/tsconfig.json
Normal file
24
sdk/typescript/tsconfig.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"resolveJsonModule": true,
|
||||
"lib": ["ES2022"],
|
||||
"types": ["node", "jest"],
|
||||
"sourceMap": true,
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"noImplicitAny": true,
|
||||
"outDir": "dist",
|
||||
"stripInternal": true
|
||||
},
|
||||
"include": ["src", "tests", "tsup.config.ts", "samples"],
|
||||
"exclude": ["dist", "node_modules"]
|
||||
}
|
||||
12
sdk/typescript/tsup.config.ts
Normal file
12
sdk/typescript/tsup.config.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { defineConfig } from "tsup";
|
||||
|
||||
export default defineConfig({
|
||||
entry: ["src/index.ts"],
|
||||
format: ["esm"],
|
||||
dts: true,
|
||||
sourcemap: true,
|
||||
clean: true,
|
||||
minify: false,
|
||||
target: "node18",
|
||||
shims: false,
|
||||
});
|
||||
Reference in New Issue
Block a user