@openai/codex-sdk 0.45.0-alpha.2 → 0.45.0-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,7 +10,7 @@ npm install @openai/codex-sdk
10
10
 
11
11
  ## Usage
12
12
 
13
- Call `startThread()` and `run()` to start a thead with Codex.
13
+ Call `startThread()` and `run()` to start a thread with Codex.
14
14
 
15
15
  ```typescript
16
16
  import { Codex } from "@openai/codex-sdk";
@@ -32,17 +32,21 @@ console.log(result);
32
32
 
33
33
  ### Streaming
34
34
 
35
- The `await run()` method completes when a thread turn is complete and agent is prepared the final response.
35
+ The `run()` method completes when a thread turn is complete and the agent has produced the final response.
36
36
 
37
- You can thread items while they are being produced by calling `await runStreamed()`.
37
+ You can stream events while they are being produced by calling `runStreamed()` and iterating the returned generator.
38
38
 
39
39
  ```typescript
40
- const result = thread.runStreamed("Diagnose the test failure and propose a fix");
40
+ const { events } = await thread.runStreamed("Diagnose the test failure and propose a fix");
41
+
42
+ for await (const event of events) {
43
+ console.log(event);
44
+ }
41
45
  ```
42
46
 
43
47
  ### Resuming a thread
44
48
 
45
- If you don't have the original `Thread` instance to continue the thread, you can resume a thread by calling `resumeThread()` and providing the thread.
49
+ If you don't have the original `Thread` instance to continue the thread, you can resume by calling `resumeThread()` and providing the thread identifier.
46
50
 
47
51
  ```typescript
48
52
  const threadId = "...";
@@ -54,7 +58,7 @@ console.log(result);
54
58
 
55
59
  ### Working directory
56
60
 
57
- By default, Codex will run in the current working directory. You can change the working directory by passing the `workingDirectory` option to the when creating a thread.
61
+ By default, Codex will run in the current working directory. You can change the working directory by passing the `workingDirectory` option when creating a thread.
58
62
 
59
63
  ```typescript
60
64
  const thread = codex.startThread({
@@ -62,7 +66,7 @@ const thread = codex.startThread({
62
66
  });
63
67
  ```
64
68
 
65
- 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 to the when creating a thread.
69
+ 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.
66
70
 
67
71
  ```typescript
68
72
  const thread = codex.startThread({
package/dist/index.d.ts CHANGED
@@ -183,7 +183,6 @@ type CodexOptions = {
183
183
  codexPathOverride?: string;
184
184
  baseUrl?: string;
185
185
  apiKey?: string;
186
- workingDirectory?: string;
187
186
  };
188
187
 
189
188
  type ApprovalMode = "never" | "on-request" | "on-failure" | "untrusted";
@@ -219,4 +218,4 @@ declare class Codex {
219
218
  resumeThread(id: string, options?: ThreadOptions): Thread;
220
219
  }
221
220
 
222
- export { type AgentMessageItem, type ApprovalMode, Codex, type CodexOptions, type CommandExecutionItem, type ErrorItem, type FileChangeItem, type Input, type ItemCompletedEvent, type ItemStartedEvent, type ItemUpdatedEvent, type McpToolCallItem, type ReasoningItem, type RunResult, type RunStreamedResult, type SandboxMode, type ThreadOptions as TheadOptions, Thread, type ThreadError, type ThreadErrorEvent, type ThreadEvent, type ThreadItem, type ThreadStartedEvent, type TodoListItem, type TurnCompletedEvent, type TurnFailedEvent, type TurnStartedEvent, type Usage, type WebSearchItem };
221
+ export { type AgentMessageItem, type ApprovalMode, Codex, type CodexOptions, type CommandExecutionItem, type ErrorItem, type FileChangeItem, type Input, type ItemCompletedEvent, type ItemStartedEvent, type ItemUpdatedEvent, type McpToolCallItem, type ReasoningItem, type RunResult, type RunStreamedResult, type SandboxMode, Thread, type ThreadError, type ThreadErrorEvent, type ThreadEvent, type ThreadItem, type ThreadOptions, type ThreadStartedEvent, type TodoListItem, type TurnCompletedEvent, type TurnFailedEvent, type TurnStartedEvent, type Usage, type WebSearchItem };
package/dist/index.js CHANGED
@@ -50,6 +50,7 @@ var Thread = class {
50
50
  const items = [];
51
51
  let finalResponse = "";
52
52
  let usage = null;
53
+ let turnFailure = null;
53
54
  for await (const event of generator) {
54
55
  if (event.type === "item.completed") {
55
56
  if (event.item.type === "agent_message") {
@@ -58,8 +59,14 @@ var Thread = class {
58
59
  items.push(event.item);
59
60
  } else if (event.type === "turn.completed") {
60
61
  usage = event.usage;
62
+ } else if (event.type === "turn.failed") {
63
+ turnFailure = event.error;
64
+ break;
61
65
  }
62
66
  }
67
+ if (turnFailure) {
68
+ throw new Error(turnFailure.message);
69
+ }
63
70
  return { items, finalResponse, usage };
64
71
  }
65
72
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/thread.ts","../src/exec.ts","../src/codex.ts"],"sourcesContent":["import { CodexOptions } from \"./codexOptions\";\nimport { ThreadEvent, Usage } from \"./events\";\nimport { CodexExec } from \"./exec\";\nimport { ThreadItem } from \"./items\";\nimport { ThreadOptions } from \"./threadOptions\";\n\n/** Completed turn. */\nexport type Turn = {\n items: ThreadItem[];\n finalResponse: string;\n usage: Usage | null;\n};\n\n/** Alias for `Turn` to describe the result of `run()`. */\nexport type RunResult = Turn;\n\n/** The result of the `runStreamed` method. */\nexport type StreamedTurn = {\n events: AsyncGenerator<ThreadEvent>;\n};\n\n/** Alias for `StreamedTurn` to describe the result of `runStreamed()`. */\nexport type RunStreamedResult = StreamedTurn;\n\n/** An input to send to the agent. */\nexport type Input = string;\n\n/** Respesent a thread of conversation with the agent. One thread can have multiple consecutive turns. */\nexport class Thread {\n private _exec: CodexExec;\n private _options: CodexOptions;\n private _id: string | null;\n private _threadOptions: ThreadOptions;\n\n /** Returns the ID of the thread. Populated after the first turn starts. */\n public get id(): string | null {\n return this._id;\n }\n\n /* @internal */\n constructor(\n exec: CodexExec,\n options: CodexOptions,\n threadOptions: ThreadOptions,\n id: string | null = null,\n ) {\n this._exec = exec;\n this._options = options;\n this._id = id;\n this._threadOptions = threadOptions;\n }\n\n /** Provides the input to the agent and streams events as they are produced during the turn. */\n async runStreamed(input: string): Promise<StreamedTurn> {\n return { events: this.runStreamedInternal(input) };\n }\n\n private async *runStreamedInternal(input: string): AsyncGenerator<ThreadEvent> {\n const options = this._threadOptions;\n const generator = this._exec.run({\n input,\n baseUrl: this._options.baseUrl,\n apiKey: this._options.apiKey,\n threadId: this._id,\n model: options?.model,\n sandboxMode: options?.sandboxMode,\n workingDirectory: options?.workingDirectory,\n skipGitRepoCheck: options?.skipGitRepoCheck,\n });\n for await (const item of generator) {\n let parsed: ThreadEvent;\n try {\n parsed = JSON.parse(item) as ThreadEvent;\n } catch (error) {\n throw new Error(`Failed to parse item: ${item}`, { cause: error });\n }\n if (parsed.type === \"thread.started\") {\n this._id = parsed.thread_id;\n }\n yield parsed;\n }\n }\n\n /** Provides the input to the agent and returns the completed turn. */\n async run(input: string): Promise<Turn> {\n const generator = this.runStreamedInternal(input);\n const items: ThreadItem[] = [];\n let finalResponse: string = \"\";\n let usage: Usage | null = null;\n for await (const event of generator) {\n if (event.type === \"item.completed\") {\n if (event.item.type === \"agent_message\") {\n finalResponse = event.item.text;\n }\n items.push(event.item);\n } else if (event.type === \"turn.completed\") {\n usage = event.usage;\n }\n }\n return { items, finalResponse, usage };\n }\n}\n","import { spawn } from \"node:child_process\";\n\nimport readline from \"node:readline\";\n\nimport { SandboxMode } from \"./threadOptions\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nexport type CodexExecArgs = {\n input: string;\n\n baseUrl?: string;\n apiKey?: string;\n threadId?: string | null;\n // --model\n model?: string;\n // --sandbox\n sandboxMode?: SandboxMode;\n // --cd\n workingDirectory?: string;\n // --skip-git-repo-check\n skipGitRepoCheck?: boolean;\n};\n\nexport class CodexExec {\n private executablePath: string;\n constructor(executablePath: string | null = null) {\n this.executablePath = executablePath || findCodexPath();\n }\n\n async *run(args: CodexExecArgs): AsyncGenerator<string> {\n const commandArgs: string[] = [\"exec\", \"--experimental-json\"];\n\n if (args.model) {\n commandArgs.push(\"--model\", args.model);\n }\n\n if (args.sandboxMode) {\n commandArgs.push(\"--sandbox\", args.sandboxMode);\n }\n\n if (args.workingDirectory) {\n commandArgs.push(\"--cd\", args.workingDirectory);\n }\n\n if (args.skipGitRepoCheck) {\n commandArgs.push(\"--skip-git-repo-check\");\n }\n\n if (args.threadId) {\n commandArgs.push(\"resume\", args.threadId);\n }\n\n const env = {\n ...process.env,\n };\n if (args.baseUrl) {\n env.OPENAI_BASE_URL = args.baseUrl;\n }\n if (args.apiKey) {\n env.CODEX_API_KEY = args.apiKey;\n }\n\n const child = spawn(this.executablePath, commandArgs, {\n env,\n });\n\n let spawnError: unknown | null = null;\n child.once(\"error\", (err) => (spawnError = err));\n\n if (!child.stdin) {\n child.kill();\n throw new Error(\"Child process has no stdin\");\n }\n child.stdin.write(args.input);\n child.stdin.end();\n\n if (!child.stdout) {\n child.kill();\n throw new Error(\"Child process has no stdout\");\n }\n const stderrChunks: Buffer[] = [];\n\n if (child.stderr) {\n child.stderr.on(\"data\", (data) => {\n stderrChunks.push(data);\n });\n }\n\n const rl = readline.createInterface({\n input: child.stdout,\n crlfDelay: Infinity,\n });\n\n try {\n for await (const line of rl) {\n // `line` is a string (Node sets default encoding to utf8 for readline)\n yield line as string;\n }\n\n const exitCode = new Promise((resolve, reject) => {\n child.once(\"exit\", (code) => {\n if (code === 0) {\n resolve(code);\n } else {\n const stderrBuffer = Buffer.concat(stderrChunks);\n reject(\n new Error(`Codex Exec exited with code ${code}: ${stderrBuffer.toString(\"utf8\")}`),\n );\n }\n });\n });\n\n if (spawnError) throw spawnError;\n await exitCode;\n } finally {\n rl.close();\n child.removeAllListeners();\n try {\n if (!child.killed) child.kill();\n } catch {\n // ignore\n }\n }\n }\n}\n\nconst scriptFileName = fileURLToPath(import.meta.url);\nconst scriptDirName = path.dirname(scriptFileName);\n\nfunction findCodexPath() {\n const { platform, arch } = process;\n\n let targetTriple = null;\n switch (platform) {\n case \"linux\":\n case \"android\":\n switch (arch) {\n case \"x64\":\n targetTriple = \"x86_64-unknown-linux-musl\";\n break;\n case \"arm64\":\n targetTriple = \"aarch64-unknown-linux-musl\";\n break;\n default:\n break;\n }\n break;\n case \"darwin\":\n switch (arch) {\n case \"x64\":\n targetTriple = \"x86_64-apple-darwin\";\n break;\n case \"arm64\":\n targetTriple = \"aarch64-apple-darwin\";\n break;\n default:\n break;\n }\n break;\n case \"win32\":\n switch (arch) {\n case \"x64\":\n targetTriple = \"x86_64-pc-windows-msvc\";\n break;\n case \"arm64\":\n targetTriple = \"aarch64-pc-windows-msvc\";\n break;\n default:\n break;\n }\n break;\n default:\n break;\n }\n\n if (!targetTriple) {\n throw new Error(`Unsupported platform: ${platform} (${arch})`);\n }\n\n const vendorRoot = path.join(scriptDirName, \"..\", \"vendor\");\n const archRoot = path.join(vendorRoot, targetTriple);\n const codexBinaryName = process.platform === \"win32\" ? \"codex.exe\" : \"codex\";\n const binaryPath = path.join(archRoot, \"codex\", codexBinaryName);\n\n return binaryPath;\n}\n","import { CodexOptions } from \"./codexOptions\";\nimport { CodexExec } from \"./exec\";\nimport { Thread } from \"./thread\";\nimport { ThreadOptions } from \"./threadOptions\";\n\n/**\n * Codex is the main class for interacting with the Codex agent.\n *\n * Use the `startThread()` method to start a new thread or `resumeThread()` to resume a previously started thread.\n */\nexport class Codex {\n private exec: CodexExec;\n private options: CodexOptions;\n\n constructor(options: CodexOptions = {}) {\n this.exec = new CodexExec(options.codexPathOverride);\n this.options = options;\n }\n\n /**\n * Starts a new conversation with an agent.\n * @returns A new thread instance.\n */\n startThread(options: ThreadOptions = {}): Thread {\n return new Thread(this.exec, this.options, options);\n }\n\n /**\n * Resumes a conversation with an agent based on the thread id.\n * Threads are persisted in ~/.codex/sessions.\n *\n * @param id The id of the thread to resume.\n * @returns A new thread instance.\n */\n resumeThread(id: string, options: ThreadOptions = {}): Thread {\n return new Thread(this.exec, this.options, options, id);\n }\n}\n"],"mappings":";AA4BO,IAAM,SAAN,MAAa;AAAA,EACV;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGR,IAAW,KAAoB;AAC7B,WAAO,KAAK;AAAA,EACd;AAAA;AAAA,EAGA,YACE,MACA,SACA,eACA,KAAoB,MACpB;AACA,SA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AAA,MACJ;AACA;AAAA,IACF,KAAK;AACH,cAAQ,MAAM;AAAA,QACZ,KAAK;AACH,yBAAe;AACf;AAAA,QACF,KAAK;AACH,yBAAe;AACf;AAAA,QACF;AACE;AAAA,MACJ;AACA;AAAA,IACF;AACE;AAAA,EACJ;AAEA,MAAI,CAAC,cAAc;AACjB,UAAM,IAAI,MAAM,yBAAyB,QAAQ,KAAK,IAAI,GAAG;AAAA,EAC/D;AAEA,QAAM,aAAa,KAAK,KAAK,eAAe,MAAM,QAAQ;AAC1D,QAAM,WAAW,KAAK,KAAK,YAAY,YAAY;AACnD,QAAM,kBAAkB,QAAQ,aAAa,UAAU,cAAc;AACrE,QAAM,aAAa,KAAK,KAAK,UAAU,SAAS,eAAe;AAE/D,SAAO;AACT;;;AChLO,IAAM,QAAN,MAAY;AAAA,EACT;AAAA,EACA;AAAA,EAER,YAAY,UAAwB,CAAC,GAAG;AACtC,SAAK,OAAO,IAAI,UAAU,QAAQ,iBAAiB;AACnD,SAAK,UAAU;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,YAAY,UAAyB,CAAC,GAAW;AAC/C,WAAO,IAAI,OAAO,KAAK,MAAM,KAAK,SAAS,OAAO;AAAA,EACpD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,aAAa,IAAY,UAAyB,CAAC,GAAW;AAC5D,WAAO,IAAI,OAAO,KAAK,MAAM,KAAK,SAAS,SAAS,EAAE;AAAA,EACxD;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/thread.ts","../src/exec.ts","../src/codex.ts"],"sourcesContent":["import { CodexOptions } from \"./codexOptions\";\nimport { ThreadEvent, ThreadError, Usage } from \"./events\";\nimport { CodexExec } from \"./exec\";\nimport { ThreadItem } from \"./items\";\nimport { ThreadOptions } from \"./threadOptions\";\n\n/** Completed turn. */\nexport type Turn = {\n items: ThreadItem[];\n finalResponse: string;\n usage: Usage | null;\n};\n\n/** Alias for `Turn` to describe the result of `run()`. */\nexport type RunResult = Turn;\n\n/** The result of the `runStreamed` method. */\nexport type StreamedTurn = {\n events: AsyncGenerator<ThreadEvent>;\n};\n\n/** Alias for `StreamedTurn` to describe the result of `runStreamed()`. */\nexport type RunStreamedResult = StreamedTurn;\n\n/** An input to send to the agent. */\nexport type Input = string;\n\n/** Respesent a thread of conversation with the agent. One thread can have multiple consecutive turns. */\nexport class Thread {\n private _exec: CodexExec;\n private _options: CodexOptions;\n private _id: string | null;\n private _threadOptions: ThreadOptions;\n\n /** Returns the ID of the thread. Populated after the first turn starts. */\n public get id(): string | null {\n return this._id;\n }\n\n /* @internal */\n constructor(\n exec: CodexExec,\n options: CodexOptions,\n threadOptions: ThreadOptions,\n id: string | null = null,\n ) {\n this._exec = exec;\n this._options = options;\n this._id = id;\n this._threadOptions = threadOptions;\n }\n\n /** Provides the input to the agent and streams events as they are produced during the turn. */\n async runStreamed(input: string): Promise<StreamedTurn> {\n return { events: this.runStreamedInternal(input) };\n }\n\n private async *runStreamedInternal(input: string): AsyncGenerator<ThreadEvent> {\n const options = this._threadOptions;\n const generator = this._exec.run({\n input,\n baseUrl: this._options.baseUrl,\n apiKey: this._options.apiKey,\n threadId: this._id,\n model: options?.model,\n sandboxMode: options?.sandboxMode,\n workingDirectory: options?.workingDirectory,\n skipGitRepoCheck: options?.skipGitRepoCheck,\n });\n for await (const item of generator) {\n let parsed: ThreadEvent;\n try {\n parsed = JSON.parse(item) as ThreadEvent;\n } catch (error) {\n throw new Error(`Failed to parse item: ${item}`, { cause: error });\n }\n if (parsed.type === \"thread.started\") {\n this._id = parsed.thread_id;\n }\n yield parsed;\n }\n }\n\n /** Provides the input to the agent and returns the completed turn. */\n async run(input: string): Promise<Turn> {\n const generator = this.runStreamedInternal(input);\n const items: ThreadItem[] = [];\n let finalResponse: string = \"\";\n let usage: Usage | null = null;\n let turnFailure: ThreadError | null = null;\n for await (const event of generator) {\n if (event.type === \"item.completed\") {\n if (event.item.type === \"agent_message\") {\n finalResponse = event.item.text;\n }\n items.push(event.item);\n } else if (event.type === \"turn.completed\") {\n usage = event.usage;\n } else if (event.type === \"turn.failed\") {\n turnFailure = event.error;\n break;\n }\n }\n if (turnFailure) {\n throw new Error(turnFailure.message);\n }\n return { items, finalResponse, usage };\n }\n}\n","import { spawn } from \"node:child_process\";\n\nimport readline from \"node:readline\";\n\nimport { SandboxMode } from \"./threadOptions\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nexport type CodexExecArgs = {\n input: string;\n\n baseUrl?: string;\n apiKey?: string;\n threadId?: string | null;\n // --model\n model?: string;\n // --sandbox\n sandboxMode?: SandboxMode;\n // --cd\n workingDirectory?: string;\n // --skip-git-repo-check\n skipGitRepoCheck?: boolean;\n};\n\nexport class CodexExec {\n private executablePath: string;\n constructor(executablePath: string | null = null) {\n this.executablePath = executablePath || findCodexPath();\n }\n\n async *run(args: CodexExecArgs): AsyncGenerator<string> {\n const commandArgs: string[] = [\"exec\", \"--experimental-json\"];\n\n if (args.model) {\n commandArgs.push(\"--model\", args.model);\n }\n\n if (args.sandboxMode) {\n commandArgs.push(\"--sandbox\", args.sandboxMode);\n }\n\n if (args.workingDirectory) {\n commandArgs.push(\"--cd\", args.workingDirectory);\n }\n\n if (args.skipGitRepoCheck) {\n commandArgs.push(\"--skip-git-repo-check\");\n }\n\n if (args.threadId) {\n commandArgs.push(\"resume\", args.threadId);\n }\n\n const env = {\n ...process.env,\n };\n if (args.baseUrl) {\n env.OPENAI_BASE_URL = args.baseUrl;\n }\n if (args.apiKey) {\n env.CODEX_API_KEY = args.apiKey;\n }\n\n const child = spawn(this.executablePath, commandArgs, {\n env,\n });\n\n let spawnError: unknown | null = null;\n child.once(\"error\", (err) => (spawnError = err));\n\n if (!child.stdin) {\n child.kill();\n throw new Error(\"Child process has no stdin\");\n }\n child.stdin.write(args.input);\n child.stdin.end();\n\n if (!child.stdout) {\n child.kill();\n throw new Error(\"Child process has no stdout\");\n }\n const stderrChunks: Buffer[] = [];\n\n if (child.stderr) {\n child.stderr.on(\"data\", (data) => {\n stderrChunks.push(data);\n });\n }\n\n const rl = readline.createInterface({\n input: child.stdout,\n crlfDelay: Infinity,\n });\n\n try {\n for await (const line of rl) {\n // `line` is a string (Node sets default encoding to utf8 for readline)\n yield line as string;\n }\n\n const exitCode = new Promise((resolve, reject) => {\n child.once(\"exit\", (code) => {\n if (code === 0) {\n resolve(code);\n } else {\n const stderrBuffer = Buffer.concat(stderrChunks);\n reject(\n new Error(`Codex Exec exited with code ${code}: ${stderrBuffer.toString(\"utf8\")}`),\n );\n }\n });\n });\n\n if (spawnError) throw spawnError;\n await exitCode;\n } finally {\n rl.close();\n child.removeAllListeners();\n try {\n if (!child.killed) child.kill();\n } catch {\n // ignore\n }\n }\n }\n}\n\nconst scriptFileName = fileURLToPath(import.meta.url);\nconst scriptDirName = path.dirname(scriptFileName);\n\nfunction findCodexPath() {\n const { platform, arch } = process;\n\n let targetTriple = null;\n switch (platform) {\n case \"linux\":\n case \"android\":\n switch (arch) {\n case \"x64\":\n targetTriple = \"x86_64-unknown-linux-musl\";\n break;\n case \"arm64\":\n targetTriple = \"aarch64-unknown-linux-musl\";\n break;\n default:\n break;\n }\n break;\n case \"darwin\":\n switch (arch) {\n case \"x64\":\n targetTriple = \"x86_64-apple-darwin\";\n break;\n case \"arm64\":\n targetTriple = \"aarch64-apple-darwin\";\n break;\n default:\n break;\n }\n break;\n case \"win32\":\n switch (arch) {\n case \"x64\":\n targetTriple = \"x86_64-pc-windows-msvc\";\n break;\n case \"arm64\":\n targetTriple = \"aarch64-pc-windows-msvc\";\n break;\n default:\n break;\n }\n break;\n default:\n break;\n }\n\n if (!targetTriple) {\n throw new Error(`Unsupported platform: ${platform} (${arch})`);\n }\n\n const vendorRoot = path.join(scriptDirName, \"..\", \"vendor\");\n const archRoot = path.join(vendorRoot, targetTriple);\n const codexBinaryName = process.platform === \"win32\" ? \"codex.exe\" : \"codex\";\n const binaryPath = path.join(archRoot, \"codex\", codexBinaryName);\n\n return binaryPath;\n}\n","import { CodexOptions } from \"./codexOptions\";\nimport { CodexExec } from \"./exec\";\nimport { Thread } from \"./thread\";\nimport { ThreadOptions } from \"./threadOptions\";\n\n/**\n * Codex is the main class for interacting with the Codex agent.\n *\n * Use the `startThread()` method to start a new thread or `resumeThread()` to resume a previously started thread.\n */\nexport class Codex {\n private exec: CodexExec;\n private options: CodexOptions;\n\n constructor(options: CodexOptions = {}) {\n this.exec = new CodexExec(options.codexPathOverride);\n this.options = options;\n }\n\n /**\n * Starts a new conversation with an agent.\n * @returns A new thread instance.\n */\n startThread(options: ThreadOptions = {}): Thread {\n return new Thread(this.exec, this.options, options);\n }\n\n /**\n * Resumes a conversation with an agent based on the thread id.\n * Threads are persisted in ~/.codex/sessions.\n *\n * @param id The id of the thread to resume.\n * @returns A new thread instance.\n */\n resumeThread(id: string, options: ThreadOptions = {}): Thread {\n return new Thread(this.exec, this.options, options, id);\n }\n}\n"],"mappings":";AA4BO,IAAM,SAAN,MAAa;AAAA,EACV;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGR,IAAW,KAAoB;AAC7B,WAAO,KAAK;AAAA,EACd;AAAA;AAAA,EAGA,YACE,MACA,SACA,eACA,KAAoB,MACpB;AACA,SAAK,QAAQ;AACb,SAAK,WAAW;AAChB,SAAK,MAAM;AACX,SAAK,iBAAiB;AAAA,EACxB;AAAA;AAAA,EAGA,MAAM,YAAY,OAAsC;AACtD,WAAO,EAAE,QAAQ,KAAK,oBAAoB,KAAK,EAAE;AAAA,EACnD;AAAA,EAEA,OAAe,oBAAoB,OAA4C;AAC7E,UAAM,UAAU,KAAK;AACrB,UAAM,YAAY,KAAK,MAAM,IAAI;AAAA,MAC/B;AAAA,MACA,SAAS,KAAK,SAAS;AAAA,MACvB,QAAQ,KAAK,SAAS;AAAA,MACtB,UAAU,KAAK;AAAA,MACf,OAAO,SAAS;AAAA,MAChB,aAAa,SAAS;AAAA,MACtB,kBAAkB,SAAS;AAAA,M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e,MAAM,QAAQ;AAC1D,QAAM,WAAW,KAAK,KAAK,YAAY,YAAY;AACnD,QAAM,kBAAkB,QAAQ,aAAa,UAAU,cAAc;AACrE,QAAM,aAAa,KAAK,KAAK,UAAU,SAAS,eAAe;AAE/D,SAAO;AACT;;;AChLO,IAAM,QAAN,MAAY;AAAA,EACT;AAAA,EACA;AAAA,EAER,YAAY,UAAwB,CAAC,GAAG;AACtC,SAAK,OAAO,IAAI,UAAU,QAAQ,iBAAiB;AACnD,SAAK,UAAU;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,YAAY,UAAyB,CAAC,GAAW;AAC/C,WAAO,IAAI,OAAO,KAAK,MAAM,KAAK,SAAS,OAAO;AAAA,EACpD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,aAAa,IAAY,UAAyB,CAAC,GAAW;AAC5D,WAAO,IAAI,OAAO,KAAK,MAAM,KAAK,SAAS,SAAS,EAAE;AAAA,EACxD;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openai/codex-sdk",
3
- "version": "0.45.0-alpha.2",
3
+ "version": "0.45.0-alpha.4",
4
4
  "description": "TypeScript SDK for Codex APIs.",
5
5
  "repository": {
6
6
  "type": "git",