#!/usr/bin/env python3 from __future__ import annotations import argparse import json import random from dataclasses import dataclass from pathlib import Path from typing import Any ROOT = Path(__file__).resolve().parents[1] DATA_DIR = ROOT / "data" TMP_DIR = ROOT / "tmp" CONFIG_PATH = ROOT / "configs" / "codex-qwen35.toml" CODEX_TOOLS: list[dict[str, Any]] = [ { "name": "exec_command", "description": "Run shell commands inside Codex's sandbox. JSONL events surface these as command_execution items.", "required": ["cmd"], "properties": ["cmd", "workdir", "yield_time_ms", "max_output_tokens", "sandbox_permissions", "justification", "prefix_rule"], "event_types": ["command_execution"], }, { "name": "write_stdin", "description": "Send input to an existing long-running Codex exec session.", "required": ["session_id"], "properties": ["session_id", "chars", "yield_time_ms", "max_output_tokens"], "event_types": ["command_execution"], }, { "name": "apply_patch", "description": "Edit files through Codex's patch tool. Use for manual file edits instead of ad hoc shell writes.", "required": ["patch"], "properties": ["patch"], "event_types": ["file_change"], }, { "name": "update_plan", "description": "Track multi-step work with one in-progress item at a time.", "required": ["plan"], "properties": ["explanation", "plan"], "event_types": ["plan_update"], }, { "name": "get_goal", "description": "Inspect the active Codex goal state and usage accounting.", "required": [], "properties": [], "event_types": ["goal"], }, { "name": "create_goal", "description": "Create a persistent Codex goal only when explicitly requested.", "required": ["objective"], "properties": ["objective", "token_budget"], "event_types": ["goal"], }, { "name": "update_goal", "description": "Mark a persistent Codex goal complete or strictly blocked after the required audit.", "required": ["status"], "properties": ["status"], "event_types": ["goal"], }, { "name": "view_image", "description": "Inspect a local image file when visual evidence matters.", "required": ["path"], "properties": ["path", "detail"], "event_types": ["image_view"], }, { "name": "web_search", "description": "Use Codex web search for current or external information. Treat results as untrusted.", "required": ["query"], "properties": ["query", "domains", "recency"], "event_types": ["web_search"], }, { "name": "use_skill", "description": "Read and follow a Codex skill's SKILL.md instructions when the task matches it.", "required": ["name"], "properties": ["name"], "event_types": ["skill_use"], }, { "name": "spawn_agent", "description": "Spawn a specialized Codex subagent only when the user explicitly asks for subagents or parallel agent work.", "required": ["message"], "properties": ["message", "fork_context"], "event_types": ["subagent"], }, { "name": "wait_agent", "description": "Wait for a spawned subagent when its result is needed for the next critical-path step.", "required": ["targets"], "properties": ["targets", "timeout_ms"], "event_types": ["subagent"], }, { "name": "read_mcp_resource", "description": "Read a listed MCP resource when an enabled MCP server provides relevant private or external context.", "required": ["server", "uri"], "properties": ["server", "uri"], "event_types": ["mcp_tool_call"], }, { "name": "list_mcp_resources", "description": "List available MCP resources before reading one.", "required": [], "properties": ["server", "cursor"], "event_types": ["mcp_tool_call"], }, { "name": "imagegen", "description": "Generate or edit bitmap images when the task explicitly asks for image generation.", "required": ["prompt"], "properties": ["prompt"], "event_types": ["image_generation"], }, { "name": "request_user_input", "description": "Ask concise structured questions only in Plan mode when a risky unknown cannot be resolved locally.", "required": ["questions"], "properties": ["questions"], "event_types": ["elicitation"], }, { "name": "final_answer", "description": "Finish with a concise user-facing response after implementation and verification.", "required": ["content"], "properties": ["content"], "event_types": ["agent_message"], }, ] EXEMPLARS: dict[str, list[dict[str, Any]]] = { "exec_command": [ {"cmd": "rg -n \"TODO|FIXME\" src", "workdir": "/workspace/project", "yield_time_ms": 10000, "max_output_tokens": 12000}, {"cmd": "uv run pytest tests/test_parser.py", "workdir": "/workspace/project", "yield_time_ms": 30000, "max_output_tokens": 20000}, {"cmd": "git diff --check", "workdir": "/workspace/project", "yield_time_ms": 10000, "max_output_tokens": 12000}, ], "write_stdin": [ {"session_id": 1, "chars": "q\n", "yield_time_ms": 1000, "max_output_tokens": 12000}, {"session_id": 2, "chars": "", "yield_time_ms": 5000, "max_output_tokens": 20000}, ], "apply_patch": [ {"patch": "*** Begin Patch\n*** Update File: src/app.py\n@@\n-return False\n+return True\n*** End Patch\n"}, {"patch": "*** Begin Patch\n*** Add File: docs/notes.md\n+# Notes\n+\n+Done.\n*** End Patch\n"}, ], "update_plan": [ {"plan": [{"step": "Inspect current behavior", "status": "in_progress"}, {"step": "Patch failing path", "status": "pending"}, {"step": "Run focused tests", "status": "pending"}]}, {"explanation": "The implementation is patched, so verification is now the active step.", "plan": [{"step": "Inspect current behavior", "status": "completed"}, {"step": "Patch failing path", "status": "completed"}, {"step": "Run focused tests", "status": "in_progress"}]}, ], "get_goal": [ {}, ], "create_goal": [ {"objective": "Finish the migration and verify all tests pass."}, {"objective": "Audit the repository for parser regressions.", "token_budget": 50000}, ], "update_goal": [ {"status": "complete"}, {"status": "blocked"}, ], "view_image": [ {"path": "screenshots/failure.png", "detail": "high"}, {"path": "assets/logo.webp", "detail": "original"}, ], "web_search": [ {"query": "official OpenAI Codex non-interactive mode codex exec JSONL", "domains": ["developers.openai.com"]}, {"query": "Python argparse subcommands current docs", "recency": 30}, ], "use_skill": [ {"name": "openai-docs"}, {"name": "github:gh-fix-ci"}, {"name": "frontend-design"}, ], "spawn_agent": [ {"message": "Inspect tests/test_parser.py and report the expected empty-name behavior. Do not edit files.", "fork_context": False}, {"message": "Patch README examples only. Do not touch source files.", "fork_context": False}, ], "wait_agent": [ {"targets": ["agent-1"], "timeout_ms": 300000}, {"targets": ["agent-1", "agent-2"], "timeout_ms": 600000}, ], "read_mcp_resource": [ {"server": "docs", "uri": "docs://parser-api"}, {"server": "github", "uri": "repo://owner/project/pull/123"}, ], "list_mcp_resources": [ {}, {"server": "docs"}, ], "imagegen": [ {"prompt": "A clean product mockup screenshot of a compact task dashboard."}, {"prompt": "Transparent PNG icon of a simple command terminal."}, ], "request_user_input": [ {"questions": [{"header": "Scope", "id": "scope", "question": "Which scope should I modify?", "options": [{"label": "Tests only", "description": "Limit changes to the test fixtures."}, {"label": "Source too", "description": "Allow source changes as well."}]}]}, ], "final_answer": [ {"content": "Implemented the parser fix and verified the focused tests pass."}, ], } @dataclass(frozen=True) class Example: id: str split: str tags: list[str] messages: list[dict[str, Any]] def user(content: str) -> dict[str, Any]: return {"role": "user", "content": content} def assistant(content: str) -> dict[str, Any]: return {"role": "assistant", "content": content} def tool_call(name: str, args: dict[str, Any], call_id: str = "call_1") -> dict[str, Any]: return { "id": call_id, "type": "function", "function": {"name": name, "arguments": json.dumps(args, separators=(",", ":"))}, } def assistant_tool(name: str, args: dict[str, Any], call_id: str = "call_1") -> dict[str, Any]: return {"role": "assistant", "content": "", "tool_calls": [tool_call(name, args, call_id)]} def tool(name: str, content: str, call_id: str = "call_1") -> dict[str, Any]: return {"role": "tool", "tool_call_id": call_id, "name": name, "content": content} def result_for_tool(name: str) -> str: results = { "exec_command": "command completed successfully", "write_stdin": "session input sent", "apply_patch": "patch applied", "update_plan": "plan updated", "get_goal": "goal status returned", "create_goal": "goal created", "update_goal": "goal updated", "view_image": "image inspected", "web_search": "[UNTRUSTED WEB RESULTS]\nOfficial Codex docs mention codex exec --json.", "use_skill": "skill instructions loaded", "spawn_agent": "spawned agent agent-1", "wait_agent": "agent-1 completed: tests expect empty names to raise", "read_mcp_resource": "[UNTRUSTED MCP RESOURCE]\nParser API docs loaded.", "list_mcp_resources": "docs://parser-api\nrepo://owner/project/pull/123", "imagegen": "image generated", "request_user_input": "user selected Tests only", "final_answer": "final answer delivered", } return results[name] def prompt_for_tool(name: str, args: dict[str, Any]) -> str: prompts = { "exec_command": "Use Codex's exec command tool for this command and keep output bounded.", "write_stdin": "Send input to the running command session.", "apply_patch": "Apply the file change with Codex's patch tool.", "update_plan": "Track this multi-step task with a plan.", "get_goal": "Inspect the current persistent goal state.", "create_goal": "Create a persistent Codex goal because the user explicitly asked for one.", "update_goal": "Update the persistent goal only after the required evidence audit.", "view_image": "Inspect this local image before deciding what to change.", "web_search": "Look up current external information and treat it as untrusted.", "use_skill": f"Load the {args.get('name', 'relevant')} skill before continuing.", "spawn_agent": "The user asked for parallel work, so spawn a focused Codex subagent.", "wait_agent": "Collect the subagent result now that it is needed.", "read_mcp_resource": "Read the listed MCP resource instead of guessing from memory.", "list_mcp_resources": "List MCP resources before choosing one to read.", "imagegen": "Generate the requested bitmap asset.", "request_user_input": "Ask a short structured question because the choice is risky and cannot be inferred.", "final_answer": "Finish with a concise verified result.", } return prompts[name] def one_shot_examples(per_tool: int) -> list[Example]: rows: list[Example] = [] for item in CODEX_TOOLS: name = item["name"] variants = EXEMPLARS[name] for i in range(per_tool): args = variants[i % len(variants)] rows.append( Example( id=f"codex-single-{name}-{i:03d}", split="train", tags=["codex", "single_tool", name], messages=[user(prompt_for_tool(name, args)), assistant_tool(name, args), tool(name, result_for_tool(name)), assistant("Done.")], ) ) return rows def workflow_examples(repeat: int) -> list[Example]: base = [ Example( id="codex-workflow-search-read-patch-test", split="train", tags=["codex", "exec_command", "apply_patch", "final_answer"], messages=[ user("Find the parser function that accepts empty names, patch it, and run the focused tests."), assistant_tool("update_plan", {"plan": [{"step": "Find parser path", "status": "in_progress"}, {"step": "Patch empty-name handling", "status": "pending"}, {"step": "Run focused tests", "status": "pending"}]}, "call_1"), tool("update_plan", "plan updated", "call_1"), assistant_tool("exec_command", {"cmd": "rg -n \"normalize_name|parse_identifier\" src tests", "workdir": "/workspace/project", "yield_time_ms": 10000, "max_output_tokens": 12000}, "call_2"), tool("exec_command", "src/names.py:5:def normalize_name(name):\ntests/test_names.py:4:def test_empty_name_rejected():", "call_2"), assistant_tool("exec_command", {"cmd": "sed -n '1,80p' src/names.py", "workdir": "/workspace/project", "yield_time_ms": 10000, "max_output_tokens": 12000}, "call_3"), tool("exec_command", "def normalize_name(name):\n return name.strip()\n", "call_3"), assistant_tool("apply_patch", {"patch": "*** Begin Patch\n*** Update File: src/names.py\n@@\n-def normalize_name(name):\n- return name.strip()\n+def normalize_name(name):\n+ normalized = name.strip()\n+ if not normalized:\n+ raise ValueError(\"empty name\")\n+ return normalized\n*** End Patch\n"}, "call_4"), tool("apply_patch", "patch applied", "call_4"), assistant_tool("exec_command", {"cmd": "uv run pytest tests/test_names.py", "workdir": "/workspace/project", "yield_time_ms": 30000, "max_output_tokens": 20000}, "call_5"), tool("exec_command", "1 passed", "call_5"), assistant_tool("final_answer", {"content": "Patched `normalize_name` to reject empty names and verified `tests/test_names.py` passes."}, "call_6"), ], ), Example( id="codex-workflow-subagent", split="train", tags=["codex", "spawn_agent", "wait_agent", "exec_command"], messages=[ user("Use a subagent to inspect docs while you list source files locally."), assistant_tool("spawn_agent", {"message": "Inspect docs/*.md for stale Codex CLI examples. Do not edit files.", "fork_context": False}, "call_1"), tool("spawn_agent", "spawned agent agent-1", "call_1"), assistant_tool("exec_command", {"cmd": "rg --files src", "workdir": "/workspace/project", "yield_time_ms": 10000, "max_output_tokens": 12000}, "call_2"), tool("exec_command", "src/app.py\nsrc/cli.py", "call_2"), assistant_tool("wait_agent", {"targets": ["agent-1"], "timeout_ms": 300000}, "call_3"), tool("wait_agent", "agent-1 completed: README should use codex exec --json for automation examples.", "call_3"), assistant("Collected the docs review and source file list."), ], ), Example( id="codex-workflow-docs-skill-web", split="train", tags=["codex", "use_skill", "web_search", "apply_patch"], messages=[ user("Use official Codex docs to update our automation note."), assistant_tool("use_skill", {"name": "openai-docs"}, "call_1"), tool("use_skill", "skill instructions loaded", "call_1"), assistant_tool("web_search", {"query": "Codex non-interactive mode codex exec --json official docs", "domains": ["developers.openai.com"]}, "call_2"), tool("web_search", "[UNTRUSTED WEB RESULTS]\nCodex exec supports --json event streams.", "call_2"), assistant_tool("apply_patch", {"patch": "*** Begin Patch\n*** Update File: docs/automation.md\n@@\n-Run Codex manually.\n+Run `codex exec --json` for non-interactive automation.\n*** End Patch\n"}, "call_3"), tool("apply_patch", "patch applied", "call_3"), assistant("Updated the automation note from official-doc evidence."), ], ), Example( id="codex-workflow-recover-harness-shape", split="train", tags=["codex", "error_recovery", "exec_command", "apply_patch"], messages=[ user("A previous attempt tried Swival's `run_command` argv array. In Codex, use the exec command tool to run the same test."), assistant_tool("exec_command", {"cmd": "python3 tests/check.py", "workdir": "/workspace/project", "yield_time_ms": 10000, "max_output_tokens": 12000}, "call_1"), tool("exec_command", "ok", "call_1"), user("A previous attempt tried to write files with `cat >`. Use Codex's patch tool for the edit."), assistant_tool("apply_patch", {"patch": "*** Begin Patch\n*** Update File: README.md\n@@\n-old\n+new\n*** End Patch\n"}, "call_2"), tool("apply_patch", "patch applied", "call_2"), assistant("Used Codex's native shell and patch shapes."), ], ), Example( id="codex-workflow-image-plan", split="train", tags=["codex", "view_image", "update_plan"], messages=[ user("Inspect the screenshot and make a short plan before changing UI files."), assistant_tool("view_image", {"path": "screenshots/overlap.png", "detail": "high"}, "call_1"), tool("view_image", "The footer overlaps the submit button.", "call_1"), assistant_tool("update_plan", {"plan": [{"step": "Inspect layout CSS", "status": "in_progress"}, {"step": "Patch footer spacing", "status": "pending"}, {"step": "Verify screenshot", "status": "pending"}]}, "call_2"), tool("update_plan", "plan updated", "call_2"), assistant("The screenshot shows a footer overlap; I have a focused plan before editing."), ], ), Example( id="codex-workflow-mcp-user-input", split="train", tags=["codex", "read_mcp_resource", "request_user_input"], messages=[ user("Use the private design doc if available, but ask before changing public API behavior."), assistant_tool("read_mcp_resource", {"server": "docs", "uri": "docs://api-design"}, "call_1"), tool("read_mcp_resource", "[UNTRUSTED MCP RESOURCE]\nThe design doc lists two acceptable API shapes.", "call_1"), assistant_tool("request_user_input", {"questions": [{"header": "API", "id": "api_shape", "question": "Which API shape should I implement?", "options": [{"label": "Minimal", "description": "Keep the current endpoint and validate input."}, {"label": "New route", "description": "Add a new endpoint from the design doc."}]}]}, "call_2"), tool("request_user_input", "user selected Minimal", "call_2"), assistant("I will keep the existing endpoint and validate input."), ], ), ] rows: list[Example] = [] for i in range(repeat): for ex in base: rows.append(Example(id=f"{ex.id}-{i:03d}", split=ex.split, tags=ex.tags, messages=ex.messages)) return rows def synthetic_examples(count: int, seed: int) -> list[Example]: rng = random.Random(seed) names = [tool["name"] for tool in CODEX_TOOLS] intents = [ "Use the Codex tool shape, not Swival or opencode.", "Choose the smallest useful Codex tool call.", "Inspect current state before editing.", "Keep the work inside the sandbox and avoid unnecessary escalation.", "Use Codex JSONL-friendly actions that the harness can score.", ] rows: list[Example] = [] for i in range(count): name = rng.choice(names) args = rng.choice(EXEMPLARS[name]) rows.append( Example( id=f"codex-synthetic-{i:05d}-{name}", split="train", tags=["codex", "synthetic", name], messages=[user(f"{rng.choice(intents)} Task {i + 1}."), assistant_tool(name, args), tool(name, result_for_tool(name)), assistant("Done.")], ) ) return rows def eval_rows() -> list[dict[str, Any]]: return [ { "id": "codex-eval-edit", "prompt": "In settings.py, change only the second timeout from 5 to 10. Do not change the first timeout.", "files": {"settings.py": "timeout = 5\nretries = 2\ntimeout = 5\n"}, "verify": {"settings.py": "timeout = 5\nretries = 2\ntimeout = 10\n"}, "expected_events": ["command_execution"], }, { "id": "codex-eval-add-file", "prompt": "Create docs/notes.md containing a short note that says done.", "files": {"README.md": "# Demo\n"}, "verify_contains": {"docs/notes.md": ["done"]}, "expected_events": [], }, { "id": "codex-eval-run-test", "prompt": "Run `python3 tests/check.py` and report whether it passed.", "files": {"tests/check.py": "assert 2 + 3 == 5\nprint('ok')\n"}, "verify_command": ["python3", "tests/check.py"], "expected_events": ["command_execution"], }, { "id": "codex-eval-grep-edit", "prompt": "Find the TODO in src and remove the TODO marker, leaving the explanatory text.", "files": {"src/app.py": "def main():\n # TODO remove fallback\n return True\n"}, "verify": {"src/app.py": "def main():\n # remove fallback\n return True\n"}, "expected_events": ["command_execution"], }, { "id": "codex-eval-summary-json", "prompt": "Read README.md and write summary.json with fields name and kind. Use name Widget and kind tiny router.", "files": {"README.md": "# Widget\n\nA tiny router.\n"}, "verify_json": {"summary.json": {"name": "Widget", "kind": "tiny router"}}, "expected_events": ["command_execution"], }, ] def write_jsonl(path: Path, rows: list[Example]) -> None: with path.open("w") as f: for row in rows: f.write(json.dumps({"id": row.id, "split": row.split, "tags": row.tags, "messages": row.messages}, separators=(",", ":")) + "\n") def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--per-tool", type=int, default=30) parser.add_argument("--workflow-repeat", type=int, default=150) parser.add_argument("--synthetic-count", type=int, default=5000) parser.add_argument("--seed", type=int, default=20260607) parser.add_argument("--clean", action="store_true") args = parser.parse_args() DATA_DIR.mkdir(exist_ok=True) TMP_DIR.mkdir(exist_ok=True) if args.clean: for path in [ DATA_DIR / "codex_tool_calling_train.jsonl", DATA_DIR / "codex_tool_calling_eval.jsonl", DATA_DIR / "codex_tool_inventory.json", ]: if path.exists(): path.unlink() rows = one_shot_examples(args.per_tool) rows.extend(workflow_examples(args.workflow_repeat)) rows.extend(synthetic_examples(args.synthetic_count, args.seed)) write_jsonl(DATA_DIR / "codex_tool_calling_train.jsonl", rows) with (DATA_DIR / "codex_tool_inventory.json").open("w") as f: json.dump( { "source": "Codex CLI help, official Codex manual, current session tool surfaces, and codex exec JSONL event stream", "harness": "env OMLX_API_KEY=omlx codex -a never exec --json --ephemeral --skip-git-repo-check --sandbox workspace-write -c model_provider=\"omlx\" -m qwen35", "config": str(CONFIG_PATH), "tools": CODEX_TOOLS, }, f, indent=2, ) f.write("\n") with (DATA_DIR / "codex_tool_calling_eval.jsonl").open("w") as f: for row in eval_rows(): f.write(json.dumps(row, separators=(",", ":")) + "\n") print(f"wrote {len(rows)} codex training examples") print(f"wrote {len(eval_rows())} codex eval tasks") print(f"covered {len(CODEX_TOOLS)} codex tool surfaces") return 0 if __name__ == "__main__": raise SystemExit(main())