Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
079bb02
feat: add per-run request, token and estimated cost limits
markstuart-oai Nov 21, 2026
e05a2ee
feat(tools): edit selected tool results before tracing and publication
markstuart-oai Nov 21, 2026
190790f
Merge feat/simple-codex into feat/runner-tool-text-transforms
markstuart-oai Nov 22, 2026
908cfd2
Merge feat/simple-codex into feat/runner-observed-budgets
markstuart-oai Nov 22, 2026
e2a1bc4
Publish committed stream events before raising a run budget error
markstuart-oai Nov 22, 2026
9c7fbad
Merge feat/simple-codex into feat/runner-observed-budgets
markstuart-oai Nov 22, 2026
b2ed3f7
Reject stale text filter bindings before tool execution
markstuart-oai Nov 22, 2026
72a3164
Validate run budget pricing and identify the exhausted limit
markstuart-oai Nov 23, 2026
62e9fdd
Reject mismatched MCP text editors before execution
markstuart-oai Nov 23, 2026
edfb871
Check canonical MCP tool identities before skipping a text editor
markstuart-oai Nov 23, 2026
f2e800c
Preserve Runner text redaction with selected tool result edits
markstuart-oai Nov 23, 2026
e63270d
Price completed model usage in USD for run budgets
markstuart-oai Nov 23, 2026
81d7537
Drain committed events before reporting a streamed run budget stop
markstuart-oai Nov 23, 2026
2eb0c59
Keep selected tool approvals pending when the worker cannot execute them
markstuart-oai Nov 23, 2026
5eae426
Keep workspace and output editor checks before claiming approvals
markstuart-oai Nov 23, 2026
8271490
Require a budget-aware reader for saved runs
markstuart-oai Nov 23, 2026
2cf0f5e
Require the registered tool editor during discovery and recovery
markstuart-oai Nov 24, 2026
7b06723
Clarify text editing for Runner functions and MCP tools
markstuart-oai Nov 24, 2026
68e8a88
Show how to estimate USD costs from input and output tokens
markstuart-oai Nov 24, 2026
2444a27
Explain invalid tool text edits without including tool data
markstuart-oai Nov 24, 2026
bf30d8b
Require explicit MCP text editor registrations and reject missed bind…
markstuart-oai Nov 24, 2026
f5079d2
Clarify editor precedence and reject blank MCP tool names
markstuart-oai Nov 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/agents/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@
ToolNotFoundBehavior,
)
from .run_budget import RunBudget, RunBudgetError
from .run_config import MCPTextTransform
from .run_context import AgentHookContext, RunContextWrapper, TContext
from .run_error_handlers import (
RunErrorData,
Expand Down Expand Up @@ -503,6 +504,7 @@ def enable_verbose_stdout_logging() -> None:
"OutputGuardrailBlockedMessageFormatter",
"ToolNameCollisionPolicy",
"ReasoningItemIdPolicy",
"MCPTextTransform",
"ToolExecutionConfig",
"ToolCallHookContext",
"ToolDeclaration",
Expand Down
13 changes: 6 additions & 7 deletions src/agents/mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
ToolFilter,
ToolFilterContext,
ToolFilterStatic,
_FilteredTools,
)


Expand Down Expand Up @@ -1561,14 +1562,12 @@ async def fetch_pages() -> Literal["complete", "repeated_cursor", "page_limit"]:
self._cache_dirty = False
self._tools_last_published_refresh_sequence = refresh_sequence

# Filter tools based on tool_filter
filtered_tools = tools
# Snapshot even filtered schemas to isolate callers from the cache.
if self.tool_filter is not None:
filtered_tools = await self._apply_tool_filter(filtered_tools, run_context, agent)
# Always deep-copy tools. Even when filters build a new list, the Tool
# objects (and nested input schemas) would otherwise remain shared with
# the cache and let callers corrupt required-parameter validation.
return _snapshot_tools(filtered_tools)
names = frozenset(tool.name for tool in tools)
filtered_tools = await self._apply_tool_filter(tools, run_context, agent)
return _FilteredTools(_snapshot_tools(filtered_tools), names)
return _snapshot_tools(tools)
except mcp_compat.HTTP_STATUS_ERROR_TYPES as e:
status_code = http_status_code(e)
transport_error = UserError(
Expand Down
30 changes: 30 additions & 0 deletions src/agents/mcp/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import hashlib
import inspect
import json
import weakref
from collections import Counter
from collections.abc import Awaitable, Callable, Mapping
from dataclasses import dataclass
Expand Down Expand Up @@ -62,6 +63,14 @@
from .server import MCPServer


class _FilteredTools(list["MCPTool"]):
"""Visible tools with raw-name evidence from the same complete discovery."""

def __init__(self, tools: list[MCPTool], names: frozenset[str]) -> None:
super().__init__(tools)
self._raw_names = names


_MCP_FUNCTION_TOOL_NAME_MAX_LENGTH = 64
_MCP_FUNCTION_TOOL_HASH_LENGTH = 8

Expand Down Expand Up @@ -386,7 +395,14 @@ def _convert_mcp_tools_to_function_tools(
)
for index, tool in enumerate(tools)
]
# Share one snapshot from this discovery, before agent-level omissions.
names: frozenset[str] | None
if isinstance(tools, _FilteredTools):
names = tools._raw_names
else:
names = frozenset(t.name for t in tools) if server.tool_filter is None else None
for function_tool in function_tools:
function_tool._mcp_raw_names = names
assert function_tool._mcp_tool_binding is not None
server_name, raw_tool_name, _ = function_tool._mcp_tool_binding
function_tool._mcp_tool_binding = (server_name, raw_tool_name, server_index)
Expand Down Expand Up @@ -611,6 +627,7 @@ def to_function_tool(
mcp_server_name=get_mcp_server_log_name(server.name),
),
)
function_tool._mcp_server_ref = weakref.ref(server)
function_tool._mcp_annotations = copy.deepcopy(tool.annotations)
function_tool._mcp_tool_binding = (get_mcp_server_log_name(server.name), tool.name, None)
require_clean_function(function_tool)
Expand Down Expand Up @@ -764,6 +781,10 @@ async def check_and_call() -> CallToolResult:

invoke = check_and_call
resolved_meta = await cls._resolve_meta(server, context, tool.name, json_data)
if isinstance(context, ToolContext) and context._edit_text is not None:
from ..tool import _protect_selected_task

invoke = functools.partial(_protect_selected_task, invoke)
merged_meta = cls._merge_mcp_meta(resolved_meta, meta)
call_task = asyncio.create_task(invoke())
try:
Expand All @@ -789,6 +810,8 @@ async def check_and_call() -> CallToolResult:
# will format them into model-visible tool errors when appropriate.
raise
except Exception as e:
if isinstance(context, ToolContext) and context._edit_text is not None:
raise
if isinstance(e, MCPError):
# An MCP-level error (e.g. upstream HTTP 4xx/5xx, tool not found, etc.)
# is not a programming error – re-raise so the FunctionTool failure
Expand Down Expand Up @@ -819,6 +842,13 @@ async def check_and_call() -> CallToolResult:
f"'{get_mcp_server_log_name(server.name)}': {e}"
) from e

if isinstance(context, ToolContext) and context._edit_text is not None:
from ..run_internal.tool_text import edit_mcp_result

result = await edit_mcp_result(
context._edit_text, result, server.use_structured_content
)

if _debug.DONT_LOG_TOOL_DATA:
logger.debug("MCP tool completed.")
else:
Expand Down
2 changes: 2 additions & 0 deletions src/agents/memory/resumable_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,7 @@ async def _begin_run(
_check_approved_functions,
_check_workspace_approvals,
)
from ..run_internal.tool_text import validate_pending_text_transforms

processed = input._last_processed_response
if processed is not None and processed.native_approvals:
Expand All @@ -346,6 +347,7 @@ async def _begin_run(
_check_workspace_approvals(pending, tool_hooks.agent, processed)
if tool_not_found_behavior == "raise_error":
_check_approved_functions(pending, tool_hooks.agent, tool_hooks.context)
await validate_pending_text_transforms(input, tool_hooks.settings, tool_hooks.context)
active = self._checkpoint.model_copy(
update={
"version": 2 if current_redactor() is not None else self._checkpoint.version,
Expand Down
21 changes: 18 additions & 3 deletions src/agents/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,12 @@
from .memory.resumable_session import ResumableSession
from .models._run_context import ModelToolHooks
from .result import RunResult, RunResultStreaming
from .run_budget import _check_resume, _prepare_budget
from .run_budget import _prepare_budget
from .run_config import (
DEFAULT_MAX_TURNS,
CallModelData,
CallModelInputFilter,
MCPTextTransform,
ModelInputData,
OutputGuardrailBlockedMessageArgs,
OutputGuardrailBlockedMessageFormatter,
Expand Down Expand Up @@ -97,6 +98,7 @@
update_run_state_for_interruption,
usage_delta,
validate_output_guardrails_with_server_managed_conversation,
validate_resumed_agent_tools,
validate_session_conversation_settings,
)
from .run_internal.agent_tool_configuration import agent_tool_configuration_run
Expand Down Expand Up @@ -223,6 +225,7 @@
"OutputGuardrailBlockedMessageFormatter",
"ToolNameCollisionPolicy",
"ReasoningItemIdPolicy",
"MCPTextTransform",
"ToolExecutionConfig",
"ToolCallHookContext",
"ToolDeclaration",
Expand Down Expand Up @@ -768,7 +771,13 @@ async def _run_impl(
)
context_wrapper._resolve_function_approval_owners(starting_agent)
validate_resume_policy(run_state, context_wrapper, run_config)
await _check_resume(run_state, run_config.budget, context_wrapper)
await validate_resumed_agent_tools(
run_state,
run_config.budget,
context_wrapper,
run_config.tool_execution,
manual_root=not isinstance(session, ResumableRun),
)
context = context_wrapper.context

reject_unrecoverable_terminal_state(run_state)
Expand Down Expand Up @@ -3042,7 +3051,13 @@ async def run_loop() -> None:
):
try:
if is_resumed_state and run_state is not None:
await _check_resume(run_state, run_config.budget, context_wrapper)
await validate_resumed_agent_tools(
run_state,
run_config.budget,
context_wrapper,
run_config.tool_execution,
manual_root=not isinstance(session, ResumableRun),
)
if isinstance(session, ResumableRun):
await session.begin(
input,
Expand Down
58 changes: 4 additions & 54 deletions src/agents/run_budget.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from __future__ import annotations

import copy
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Literal

Expand All @@ -22,7 +21,6 @@
from .models.interface import Model
from .result import RunResultStreaming
from .run_config import RunConfig
from .run_context import RunContextWrapper
from .run_state import RunState
from .tool import Tool

Expand Down Expand Up @@ -181,11 +179,10 @@ def _check_model(model: object) -> None:
raise UserError("RunBudget cannot enforce native sampling limits with CodexProvider.")


def _tool_budget(tool: Tool) -> RunBudget | None:
def _tool_config(tool: Tool) -> RunConfig | None:
invoker = getattr(tool, "on_invoke_tool", None)
impl = getattr(invoker, "_invoke_tool_impl", None)
config = getattr(impl, "__agents_run_config__", None)
return config.budget if config is not None else None
return getattr(impl, "__agents_run_config__", None)


async def _admit(
Expand Down Expand Up @@ -230,58 +227,11 @@ async def _admit(
raise


async def _check_resume(
state: RunState[Any], limits: RunBudget | None, context: RunContextWrapper[Any]
) -> bool:
"""Validate pending policies and report whether this subtree owns a budget."""
from ._tool_identity import get_function_tool_lookup_key_for_call, get_function_tool_lookup_keys
from .agent_tool_state import get_agent_tool_resume_state, peek_agent_tool_run_result
from .tool import FunctionTool, _function_tool_enabled

def _check_resumed_budget(state: RunState[Any], limits: RunBudget | None) -> bool:
saved = state._context._budget if state._context is not None else None
if (saved.limits if saved is not None else None) != limits:
raise UserError("Resume requires the same RunBudget limits and missing_usage policy.")
budgeted = saved is not None
for action in getattr(state._last_processed_response, "functions", ()):
if not action.function_tool._is_agent_tool:
continue
result = peek_agent_tool_run_result(
action.tool_call, scope_id=state._agent_tool_state_scope_id
)
child = get_agent_tool_resume_state(result)
if child is None and result is not None and result.interruptions:
child = result.to_state()
if child is None:
continue
# Turn resolution can rebind a queued call after load_state(). Check
# the current qualified binding and grant only for required branches.
key = get_function_tool_lookup_key_for_call(action.tool_call)
tools = state._current_agent.tools if state._current_agent is not None else []
bindings = [
tool
for tool in tools
if isinstance(tool, FunctionTool) and key in get_function_tool_lookup_keys(tool)
]
policies = (_tool_budget(tool) for tool in bindings)
policy = next((value for value in policies if value is not None), None)
if await _check_resume(child, policy, context):
owner = state._context
if owner is not None and owner is not context:
# Agent.as_tool keeps the nested wrapper but forwards application
# context and usage. Leave the saved state untouched on refusal.
owner = copy.copy(owner)
owner.context = context.context
owner.usage = context.usage
if (
len(bindings) != 1
or bindings[0]._agent_instance is not action.function_tool._agent_instance
or owner is None
or state._current_agent is None
or not await _function_tool_enabled(bindings[0], owner, state._current_agent)
):
raise UserError("A pending RunBudget requires the same unique enabled agent tool.")
budgeted = True
return budgeted
return saved is not None


def _prepare_budget(
Expand Down
Loading
Loading