Base: codex-main originale (prima del fork aKode)
This commit is contained in:
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;
|
||||
}
|
||||
Reference in New Issue
Block a user