Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View 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);
}
}

View 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>;
};

View 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
View 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;
}
}

View 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
View 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;

View 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);
}

View 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 };
}

View 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[];
};

View 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;
};