.agents/references/agent-definition-and-run-context.md
Use this reference for changes to public Agent fields, cloning, dynamic instructions, enabled tools or handoffs, output schemas, RunContextWrapper, ToolContext, usage aggregation, or the distinction between a public agent and an internal prepared clone.
Agent and AgentBase dataclass field order is a positional compatibility boundary. Append optional fields where possible and test old positional construction when the order changes.Agent.__post_init__() is the eager boundary for invalid field categories such as names, tools, handoffs, hooks, model settings, output types, and tool-use behavior. Dynamic callbacks are validated when invoked because their result depends on the current run.Agent.clone() uses dataclasses.replace() and is shallow. Mutable fields and contained tool, handoff, hook, and provider objects remain shared unless the caller explicitly supplies replacements.clone(model=...) replaces a model whose settings still equal the old model's implicit defaults, recompute the new model's implicit defaults. Preserve explicitly customized model_settings instead of silently resetting them.FunctionTool.is_enabled and Handoff.is_enabled against the current run context. Do not cache a prior run's enabled set on the reusable agent.ToolContext.agent, handoff callbacks, and public results should identify the public agent unless an internal identity is explicitly part of the contract.ToolContext.from_agent_context() shares the underlying application object, usage accumulator, and approval mapping with its parent while adding call-scoped fields such as call ID, namespace, arguments, and conversation history.Agent.as_tool() execution has a separate run loop, approval scope, and resumable tool state. On the normal function-tool path it still shares the application object and usage accumulator, while tool_input belongs to the nested wrapper and must not overwrite the parent's scoped value.RunContextWrapper.usage is the run-wide mutable accumulator. Add each model response exactly once across streaming, non-streaming, retries, nested runs, handoffs, and resume paths.request_usage_entries when combining usage. Do not synthesize a second per-request entry from aggregate totals when the provider or retry layer already supplied request-level records.docs/agents.mddocs/context.mddocs/results.mdsrc/agents/agent.pysrc/agents/run_context.pysrc/agents/tool_context.pysrc/agents/usage.pysrc/agents/run_internal/turn_preparation.pysrc/agents/run_internal/run_loop.pytests/test_agent_config.pytests/test_agent_clone_shallow_copy.pytests/test_agent_as_tool.pytests/test_usage.py