Skip to content

Codex Tool

CodexToolOptions dataclass

Source code in .tmp/v0/src/agents/extensions/experimental/codex/codex_tool.py
@dataclass
class CodexToolOptions:
    name: str | None = None
    description: str | None = None
    parameters: type[BaseModel] | None = None
    output_schema: OutputSchemaDescriptor | Mapping[str, Any] | None = None
    codex: Codex | None = None
    codex_options: CodexOptions | Mapping[str, Any] | None = None
    default_thread_options: ThreadOptions | Mapping[str, Any] | None = None
    thread_id: str | None = None
    sandbox_mode: SandboxMode | None = None
    working_directory: str | None = None
    skip_git_repo_check: bool | None = None
    default_turn_options: TurnOptions | Mapping[str, Any] | None = None
    span_data_max_chars: int | None = 8192
    persist_session: bool = False
    on_stream: Callable[[CodexToolStreamEvent], MaybeAwaitable[None]] | None = None
    is_enabled: bool | Callable[[RunContextWrapper[Any], Any], MaybeAwaitable[bool]] = True
    failure_error_function: ToolErrorFunction | None = default_tool_error_function
    use_run_context_thread_id: bool = False
    run_context_thread_id_key: str | None = None
    parameter_validation_mode: Literal["python", "json"] = "python"
    """Use "json" for strict types such as tuples. The default validates decoded Python values."""
    image_attachments: Mapping[str, str] | None = None

parameter_validation_mode class-attribute instance-attribute

parameter_validation_mode: Literal["python", "json"] = (
    "python"
)

Use "json" for strict types such as tuples. The default validates decoded Python values.

codex_tool

codex_tool(
    options: CodexToolOptions
    | Mapping[str, Any]
    | None = None,
    *,
    name: str | None = None,
    description: str | None = None,
    parameters: type[BaseModel] | None = None,
    output_schema: OutputSchemaDescriptor
    | Mapping[str, Any]
    | None = None,
    codex: Codex | None = None,
    codex_options: CodexOptions
    | Mapping[str, Any]
    | None = None,
    default_thread_options: ThreadOptions
    | Mapping[str, Any]
    | None = None,
    thread_id: str | None = None,
    sandbox_mode: SandboxMode | None = None,
    working_directory: str | None = None,
    skip_git_repo_check: bool | None = None,
    default_turn_options: TurnOptions
    | Mapping[str, Any]
    | None = None,
    span_data_max_chars: int | None | _UnsetType = _UNSET,
    persist_session: bool | None = None,
    on_stream: Callable[
        [CodexToolStreamEvent], MaybeAwaitable[None]
    ]
    | None = None,
    is_enabled: bool
    | Callable[
        [RunContextWrapper[Any], Any], MaybeAwaitable[bool]
    ]
    | None = None,
    failure_error_function: ToolErrorFunction
    | None
    | _UnsetType = _UNSET,
    use_run_context_thread_id: bool | None = None,
    run_context_thread_id_key: str | None = None,
    parameter_validation_mode: Literal["python", "json"]
    | None = None,
    image_attachments: Mapping[str, str] | None = None,
) -> FunctionTool

Create a Codex tool. Set parameter_validation_mode="json" for Pydantic's JSON input mode.

By default, the tool rejects local images. To allow a specific image, pass image_attachments={"diagram": "/app/diagram.png"} and tell the model to use "diagram" as the path of a local_image input.

The tool copies the mapping at creation. Codex reads the file with host permissions when the tool runs. Only grant paths whose contents and location you control. Use absolute paths without commas, which the CLI treats as image separators.

Source code in .tmp/v0/src/agents/extensions/experimental/codex/codex_tool.py
def codex_tool(
    options: CodexToolOptions | Mapping[str, Any] | None = None,
    *,
    name: str | None = None,
    description: str | None = None,
    parameters: type[BaseModel] | None = None,
    output_schema: OutputSchemaDescriptor | Mapping[str, Any] | None = None,
    codex: Codex | None = None,
    codex_options: CodexOptions | Mapping[str, Any] | None = None,
    default_thread_options: ThreadOptions | Mapping[str, Any] | None = None,
    thread_id: str | None = None,
    sandbox_mode: SandboxMode | None = None,
    working_directory: str | None = None,
    skip_git_repo_check: bool | None = None,
    default_turn_options: TurnOptions | Mapping[str, Any] | None = None,
    span_data_max_chars: int | None | _UnsetType = _UNSET,
    persist_session: bool | None = None,
    on_stream: Callable[[CodexToolStreamEvent], MaybeAwaitable[None]] | None = None,
    is_enabled: bool | Callable[[RunContextWrapper[Any], Any], MaybeAwaitable[bool]] | None = None,
    failure_error_function: ToolErrorFunction | None | _UnsetType = _UNSET,
    use_run_context_thread_id: bool | None = None,
    run_context_thread_id_key: str | None = None,
    parameter_validation_mode: Literal["python", "json"] | None = None,
    image_attachments: Mapping[str, str] | None = None,
) -> FunctionTool:
    """Create a Codex tool. Set parameter_validation_mode="json" for Pydantic's JSON input mode.

    By default, the tool rejects local images. To allow a specific image, pass
    ``image_attachments={"diagram": "/app/diagram.png"}`` and tell the model to use
    ``"diagram"`` as the ``path`` of a ``local_image`` input.

    The tool copies the mapping at creation. Codex reads the file with host permissions
    when the tool runs. Only grant paths whose contents and location you control.
    Use absolute paths without commas, which the CLI treats as image separators.
    """
    resolved_options = _coerce_tool_options(options)
    if name is not None:
        resolved_options.name = name
    if description is not None:
        resolved_options.description = description
    if parameters is not None:
        resolved_options.parameters = parameters
    if output_schema is not None:
        resolved_options.output_schema = output_schema
    if codex is not None:
        resolved_options.codex = codex
    if codex_options is not None:
        resolved_options.codex_options = codex_options
    if default_thread_options is not None:
        resolved_options.default_thread_options = default_thread_options
    if thread_id is not None:
        resolved_options.thread_id = thread_id
    if sandbox_mode is not None:
        resolved_options.sandbox_mode = sandbox_mode
    if working_directory is not None:
        resolved_options.working_directory = working_directory
    if skip_git_repo_check is not None:
        resolved_options.skip_git_repo_check = skip_git_repo_check
    if default_turn_options is not None:
        resolved_options.default_turn_options = default_turn_options
    if not isinstance(span_data_max_chars, _UnsetType):
        resolved_options.span_data_max_chars = span_data_max_chars
    if persist_session is not None:
        resolved_options.persist_session = persist_session
    if on_stream is not None:
        resolved_options.on_stream = on_stream
    if is_enabled is not None:
        resolved_options.is_enabled = is_enabled
    if not isinstance(failure_error_function, _UnsetType):
        resolved_options.failure_error_function = failure_error_function
    if use_run_context_thread_id is not None:
        resolved_options.use_run_context_thread_id = use_run_context_thread_id
    if run_context_thread_id_key is not None:
        resolved_options.run_context_thread_id_key = run_context_thread_id_key
    if image_attachments is not None:
        resolved_options.image_attachments = image_attachments
    resolved_image_attachments = dict(resolved_options.image_attachments or {})
    if any(
        not Path(path).is_absolute() or "," in path for path in resolved_image_attachments.values()
    ):
        raise UserError("Image attachment grants must use absolute host paths without commas.")
    if parameter_validation_mode is None:
        parameter_validation_mode = resolved_options.parameter_validation_mode
    if parameter_validation_mode not in ("python", "json"):
        raise UserError('parameter_validation_mode must be "python" or "json".')
    resolved_options.codex_options = coerce_codex_options(resolved_options.codex_options)
    resolved_options.default_thread_options = coerce_thread_options(
        resolved_options.default_thread_options
    )
    resolved_options.default_turn_options = coerce_turn_options(
        resolved_options.default_turn_options
    )
    name = _resolve_codex_tool_name(resolved_options.name)
    resolved_run_context_thread_id_key = _resolve_run_context_thread_id_key(
        tool_name=name,
        configured_key=resolved_options.run_context_thread_id_key,
        strict_default_key=resolved_options.use_run_context_thread_id,
    )
    description = resolved_options.description or (
        "Executes an agentic Codex task against the current workspace."
    )
    if resolved_options.parameters is not None:
        parameters_model = resolved_options.parameters
    elif resolved_options.use_run_context_thread_id:
        # In run-context mode, hide thread_id from the default tool schema.
        parameters_model = CodexToolRunContextParameters
    else:
        parameters_model = CodexToolParameters

    params_schema = ensure_strict_json_schema(parameters_model.model_json_schema())
    resolved_codex_options = _resolve_codex_options(resolved_options.codex_options)
    resolve_codex = _create_codex_resolver(resolved_options.codex, resolved_codex_options)

    validated_output_schema = _resolve_output_schema(resolved_options.output_schema)
    resolved_thread_options = _resolve_thread_options(
        resolved_options.default_thread_options,
        resolved_options.sandbox_mode,
        resolved_options.working_directory,
        resolved_options.skip_git_repo_check,
    )

    persisted_thread: Thread | None = None

    async def _on_invoke_tool(ctx: ToolContext[Any], input_json: str) -> Any:
        nonlocal persisted_thread
        resolved_thread_id: str | None = None
        try:
            parsed = _parse_tool_input(parameters_model, input_json, parameter_validation_mode)
            args = _normalize_parameters(parsed, resolved_image_attachments)

            if resolved_options.use_run_context_thread_id:
                _validate_run_context_thread_id_context(ctx, resolved_run_context_thread_id_key)

            codex = await resolve_codex()
            call_thread_id = _resolve_call_thread_id(
                args=args,
                ctx=ctx,
                configured_thread_id=resolved_options.thread_id,
                use_run_context_thread_id=resolved_options.use_run_context_thread_id,
                run_context_thread_id_key=resolved_run_context_thread_id_key,
            )
            if resolved_options.persist_session:
                # Reuse a single Codex thread across tool calls.
                thread = _get_or_create_persisted_thread(
                    codex,
                    call_thread_id,
                    resolved_thread_options,
                    persisted_thread,
                )
                if persisted_thread is None:
                    persisted_thread = thread
            else:
                thread = _get_thread(codex, call_thread_id, resolved_thread_options)

            turn_options = _build_turn_options(
                resolved_options.default_turn_options, validated_output_schema
            )
            codex_input = _build_codex_input(args)
            resolved_thread_id = thread.id or call_thread_id

            # Always stream and aggregate locally to enable on_stream callbacks.
            stream_result = await thread.run_streamed(codex_input, turn_options)
            resolved_thread_id_holder: dict[str, str | None] = {"thread_id": resolved_thread_id}
            try:
                response, usage, resolved_thread_id = await _consume_events(
                    stream_result.events,
                    args,
                    ctx,
                    thread,
                    resolved_options.on_stream,
                    resolved_options.span_data_max_chars,
                    resolved_thread_id_holder=resolved_thread_id_holder,
                )
            except BaseException:
                resolved_thread_id = resolved_thread_id_holder["thread_id"]
                raise

            if usage is not None:
                ctx.usage.add(_to_agent_usage(usage))

            if resolved_options.use_run_context_thread_id:
                _store_thread_id_in_run_context(
                    ctx,
                    resolved_run_context_thread_id_key,
                    resolved_thread_id,
                )

            return CodexToolResult(thread_id=resolved_thread_id, response=response, usage=usage)
        except BaseException:
            _try_store_thread_id_in_run_context_after_error(
                ctx=ctx,
                key=resolved_run_context_thread_id_key,
                thread_id=resolved_thread_id,
                enabled=resolved_options.use_run_context_thread_id,
            )
            raise

    function_tool = _build_wrapped_function_tool(
        name=name,
        description=description,
        params_json_schema=params_schema,
        invoke_tool_impl=_on_invoke_tool,
        on_handled_error=_build_handled_function_tool_error_handler(
            span_message="Error running Codex tool (non-fatal)",
            log_label="Codex tool",
            include_input_json_in_logs=False,
            include_tool_name_in_log_messages=False,
        ),
        failure_error_function=resolved_options.failure_error_function,
        strict_json_schema=True,
        is_enabled=resolved_options.is_enabled,
    )
    # Internal marker used for codex-tool specific runtime validation.
    function_tool._is_codex_tool = True
    return function_tool