API Reference

This page documents the public API of Agenter.

AutonomousCodingAgent

The main entry point for using Agenter.

class agenter.AutonomousCodingAgent[source]

Bases: object

Public interface for Agenter.

This is the main entry point. It creates backends and validators, then runs a CodingSession to completion.

All backends default to sandbox=True (safe mode).

Example

# Default backend (anthropic-sdk) - sandbox enabled by default agent = AutonomousCodingAgent() result = await agent.execute(CodingRequest(…))

# Use Claude Code backend (claude-code) - sandbox enabled by default agent = AutonomousCodingAgent(backend=”claude-code”) result = await agent.execute(CodingRequest(…))

# Disable sandbox for full filesystem access agent = AutonomousCodingAgent(backend=”claude-code”, sandbox=False)

# With custom tools (works with all backends) from agenter import tool

@tool(“search”, “Search the web”, {“query”: str}) async def search(args):

return f”Results for {args[‘query’]}”

agent = AutonomousCodingAgent(tools=[search])

Parameters:
  • backend (str | None, default: None)

  • model (str | None, default: None)

  • tools (list[Tool] | None, default: None)

  • validators (Sequence[Validator] | None, default: None)

  • use_anthropic_tools (bool, default: False)

  • sandbox (bool, default: True)

  • setting_sources (list[str] | None, default: None)

  • allowed_tools (list[str] | None, default: None)

  • tracer (Tracer | None, default: None)

  • codex_approval_policy (str, default: 'never')

  • codex_mcp_servers (list[CodexMCPServer] | None, default: None)

  • codex_reasoning_effort (str | None, default: None)

  • claude_max_thinking_tokens (int | None, default: None)

  • acp_command (str | None, default: None)

  • acp_args (list[str] | None, default: None)

  • acp_env (dict[str, str] | None, default: None)

  • acp_mcp_servers (list[Any] | None, default: None)

  • acp_permission_policy (str, default: 'deny')

  • acp_autonomous (bool, default: True)

__init__(backend=None, model=None, tools=None, validators=None, use_anthropic_tools=False, sandbox=True, setting_sources=None, allowed_tools=None, tracer=None, codex_approval_policy='never', codex_mcp_servers=None, codex_reasoning_effort=None, claude_max_thinking_tokens=None, acp_command=None, acp_args=None, acp_env=None, acp_mcp_servers=None, acp_permission_policy='deny', acp_autonomous=True)[source]

Initialize the agent.

Parameters:
  • backend (str | None, default: None) – Backend to use. If None, uses ACA_DEFAULT_BACKEND env var (falls back to “anthropic-sdk”). Options: - “anthropic-sdk”: Anthropic SDK with custom tools - “claude-code”: Claude Code SDK with native sandbox - “codex”: OpenAI Codex CLI via MCP server - “openhands”: OpenHands SDK (requires sandbox=False) - “acp”: Agent Client Protocol subprocess backend

  • model (str | None, default: None) – Model to use. Used by “anthropic-sdk”, “claude-code”, and “codex”. If None, each backend uses its own default.

  • tools (list[Tool] | None, default: None) – Additional custom tools. Works with all backends.

  • validators (Sequence[Validator] | None, default: None) – Validators to run on generated code. Defaults to [SyntaxValidator()].

  • use_anthropic_tools (bool, default: False) – Use Anthropic’s built-in text_editor_20250728 tool instead of our custom file tools. Only for “anthropic-sdk” backend.

  • sandbox (bool, default: True) – Enable sandboxed execution (default True). When True, each backend runs in its safest mode: - anthropic-sdk: Enforces allowed_write_paths within cwd - claude-code: Uses Claude Code’s native OS-level sandbox - codex: Uses “workspace-write” mode When False, backends run with full filesystem access.

  • setting_sources (list[str] | None, default: None) – Sources for loading settings (claude-code only). e.g., [“project”, “user”] to load .claude/skills from project/user dirs.

  • allowed_tools (list[str] | None, default: None) – List of tools to allow (claude-code only). Defaults to [“Read”, “Edit”, “Write”, “Bash”, “Glob”].

  • tracer (Tracer | None, default: None) – Optional tracer for recording agent interactions. Use FileTracer to save traces to files, or implement the Tracer protocol for custom tracing (e.g., to a logging service or database).

  • codex_approval_policy (str, default: 'never') – Approval policy for Codex tool execution (codex only). Options: “untrusted”, “on-request”, “on-failure”, “never”. Defaults to “never” for autonomous operation.

  • codex_mcp_servers (list[CodexMCPServer] | None, default: None) – Custom MCP servers to pass to Codex (codex only). Gives Codex access to additional tools during execution.

  • codex_reasoning_effort (str | None, default: None) – Optional Codex/OpenAI reasoning effort (codex only). Valid values: “minimal”, “low”, “medium”, “high”.

  • claude_max_thinking_tokens (int | None, default: None) – Optional thinking budget for Claude Code (claude-code only).

  • acp_command (str | None, default: None) – Executable for the ACP agent process (acp only).

  • acp_args (list[str] | None, default: None) – Arguments passed to the ACP agent process (acp only).

  • acp_env (dict[str, str] | None, default: None) – Extra environment variables for the ACP agent process (acp only).

  • acp_mcp_servers (list[Any] | None, default: None) – MCP server descriptors passed to ACP session/new (acp only).

  • acp_permission_policy (str, default: 'deny') – How Agenter answers ACP permission requests. Options: “deny” or “allow”. Defaults to “deny”.

  • acp_autonomous (bool, default: True) – Add Agenter’s autonomous backend contract to ACP prompts and auto-continue once when an ACP agent asks for confirmation. Defaults to True.

async execute(request, verbosity=Verbosity.QUIET, log_dir=None, raise_on_budget_exceeded=False)[source]

Execute a coding task.

Parameters:
  • request (CodingRequest) – The coding task request

  • verbosity (Verbosity, default: <Verbosity.QUIET: 'quiet'>) – Output verbosity level (QUIET, NORMAL, or VERBOSE)

  • log_dir (str | Path | None, default: None) – Optional path to save full prompts/responses for debugging

  • raise_on_budget_exceeded (bool, default: False) – If True, raise BudgetExceededError when budget is exceeded. If False (default), return CodingResult with status=BUDGET_EXCEEDED and populated exceeded_limit/exceeded_values.

Return type:

CodingResult

Returns:

CodingResult with status and modified files

async stream_execute(request, verbosity=Verbosity.QUIET, log_dir=None)[source]

Execute a coding task, streaming events.

Parameters:
  • request (CodingRequest) – The coding task request

  • verbosity (Verbosity, default: <Verbosity.QUIET: 'quiet'>) – Output verbosity level (QUIET, NORMAL, or VERBOSE)

  • log_dir (str | Path | None, default: None) – Optional path to save full prompts/responses for debugging

Yields:

CodingEvent for each significant step during execution

Return type:

AsyncIterator[CodingEvent]

Data Models

Request and response models for the coding agent.

CodingRequest

class agenter.CodingRequest[source]

Bases: BaseModel

Request for a coding task.

prompt

The task prompt for the agent.

cwd

Working directory for file operations.

system_prompt

Custom system prompt for the LLM. If None, uses the backend’s default system prompt. Use this to provide domain-specific instructions (e.g., APE’s RED TEAM OPERATOR context).

max_iterations

Max validation/refinement iterations (default: 5).

budget

Optional full budget control (tokens, cost, time).

allowed_write_paths

Glob patterns restricting file writes.

output_type

Optional Pydantic model for typed output. When set, the agent returns structured output matching this schema.

Parameters:

data (Any)

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

prompt: str
cwd: str
system_prompt: str | None
max_iterations: int
budget: Budget | None
allowed_write_paths: list[str] | None
output_type: type[BaseModel] | None

CodingResult

class agenter.CodingResult[source]

Bases: BaseModel

Result of a coding session.

status

Final status of the coding session.

files

Mapping of file path to content for modified files.

summary

Human-readable summary of what was done.

iterations

Number of agent iterations executed.

total_tokens

Total tokens consumed (input + output).

total_cost_usd

Estimated total cost in USD.

total_duration_seconds

Wall clock time for the session.

exceeded_limit

Which budget limit was exceeded (if status is BUDGET_EXCEEDED). One of: “iterations”, “tokens”, “cost”, “time”, or None.

exceeded_values

Details about the exceeded limit (if status is BUDGET_EXCEEDED). Contains “limit_value” (configured max) and “actual_value” (value that exceeded).

output

Typed structured output when output_type was specified in request. Contains the Pydantic model instance with all fields including code.

Parameters:

data (Any)

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

status: CodingStatus
files: dict[str, str]
summary: str
iterations: int
total_tokens: int
total_input_tokens: int
total_output_tokens: int
total_cost_usd: float
total_duration_seconds: float
exceeded_limit: str | None
exceeded_values: dict[str, float | int] | None
output: BaseModel | None
trace_dir: Path | None

CodingEvent

class agenter.CodingEvent[source]

Bases: BaseModel

Event emitted during coding session for observability.

Parameters:

data (Any)

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

type: CodingEventType
data: SessionStarted | IterationStarted | IterationCompleted | MessageReceived | ValidationStarted | ValidationCompleted | RequestRefused | TaskCompleted | TaskFailed | SessionEnded | None
message: PromptMessage | TextMessage | ToolCallMessage | ToolResult | RefusalMessage | None
result: CodingResult | None
timestamp: float
class agenter.CodingEventType[source]

Bases: str, Enum

Types of events emitted during coding session.

Event lifecycle:

SESSION_START → ITERATION_START → BACKEND_MESSAGE* → VALIDATION_START → VALIDATION_RESULT* → ITERATION_END → (repeat iterations) → COMPLETED/FAILED/REFUSED → SESSION_END

SESSION_START = 'session_start'
ITERATION_START = 'iteration_start'
BACKEND_MESSAGE = 'backend_message'
VALIDATION_START = 'validation_start'
VALIDATION_RESULT = 'validation_result'
ITERATION_END = 'iteration_end'
SESSION_END = 'session_end'
COMPLETED = 'completed'
FAILED = 'failed'
REFUSED = 'refused'
__new__(value)

Budget

class agenter.Budget[source]

Bases: BaseModel

Budget limits for a coding session.

Parameters:

data (Any)

max_tokens: int | None
max_cost_usd: float | None
max_time_seconds: float | None
max_iterations: int
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

Tools

Tool protocol and decorator for custom tools.

Tool Protocol

class agenter.Tool[source]

Bases: Protocol

Protocol for custom tools.

Custom tools must implement this protocol to be used with the SDK.

name

Unique identifier for the tool.

description

Human-readable description of what the tool does.

input_schema

JSON Schema defining the tool’s input parameters.

name: str
description: str
input_schema: dict
async execute(inputs)[source]

Execute the tool with given inputs.

Parameters:

inputs (dict) – Dictionary of input parameters matching input_schema.

Return type:

ToolResult

Returns:

ToolResult with output and success status.

__init__(*args, **kwargs)
class agenter.FunctionTool[source]

Bases: object

Tool wrapping a function. Compatible with Claude Agent SDK style.

This class wraps a regular or async function as a Tool that can be used with the SDK. The wrapped function can return various formats which will be normalized to ToolResult.

Parameters:
  • name (str) – Unique identifier for the tool.

  • description (str) – Human-readable description of what the tool does.

  • input_schema (dict) – JSON Schema defining the tool’s input parameters.

  • func (Callable) – The function to wrap (can be sync or async).

Example

def my_func(inputs: dict) -> str:

return f”Hello, {inputs[‘name’]}!”

tool = FunctionTool(

name=”greet”, description=”Greet a user”, input_schema={“type”: “object”, “properties”: {“name”: {“type”: “string”}}}, func=my_func,

)

__init__(name, description, input_schema, func)[source]
Parameters:
Return type:

None

async execute(inputs)[source]

Execute the wrapped function.

The function can return: - ToolResult: Used directly - tuple[str, bool]: Converted to ToolResult(output, success) - str: Converted to ToolResult(output=str, success=True) - dict: JSON-encoded and returned as successful ToolResult - Any other type: Converted to string

Parameters:

inputs (dict) – Input parameters for the function.

Return type:

ToolResult

Returns:

ToolResult with the function’s output.

tool Decorator

agenter.tool(name, description, input_schema=None)[source]

Decorator to create a Tool from a function.

Compatible with Claude Agent SDK style:

@tool(“greet”, “Greet a user”, {“name”: str}) async def greet(args):

return f”Hello, {args[‘name’]}!”

Or with JSON schema:
@tool(

name=”search”, description=”Search the web”, input_schema={“type”: “object”, “properties”: {“query”: {“type”: “string”}}}

) async def search(inputs):

return results, True

Parameters:
  • name (str)

  • description (str)

  • input_schema (dict | None, default: None)

Return type:

Callable[[Callable], FunctionTool]

ToolResult

class agenter.ToolResult[source]

Bases: BaseModel

Result from tool execution.

This is the return type for all tool execute() methods and is also used as a BackendMessage when streaming tool results.

Parameters:
  • output – The tool’s output message or data.

  • success – Whether the tool executed successfully.

  • tool_name – Name of the tool (set by backend when streaming).

  • error – Optional structured error information.

  • metadata – Optional additional metadata about the execution.

Example

# Successful result return ToolResult(output=”File created successfully”, success=True)

# Failed result with structured error return ToolResult(

output=”File not found: config.py”, success=False, error=ToolError(code=ToolErrorCode.FILE_NOT_FOUND, message=”config.py”),

)

# Using the factory method for errors return ToolResult.from_error(ToolErrorCode.FILE_NOT_FOUND, “config.py”)

Parameters:

data (Any)

type: Literal['tool_result']
output: str
success: bool
tool_name: str | None
error: ToolError | None
metadata: dict[str, Any]
classmethod from_error(code, message, *, tool_name=None, metadata=None)[source]

Create a failed ToolResult with structured error information.

This factory method reduces boilerplate when creating error results.

Parameters:
  • code (ToolErrorCode) – Machine-readable error code from ToolErrorCode.

  • message (str) – Human-readable error description.

  • tool_name (str | None, default: None) – Optional tool name (for streaming context).

  • metadata (dict[str, Any] | None, default: None) – Optional additional metadata.

Return type:

ToolResult

Returns:

A ToolResult with success=False and structured error.

Example

return ToolResult.from_error(ToolErrorCode.FILE_NOT_FOUND, “config.py”) # Equivalent to: # return ToolResult( # output=”Error: config.py”, # success=False, # error=ToolError(code=ToolErrorCode.FILE_NOT_FOUND, message=”config.py”), # )

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

File System

File operations and path resolution utilities.

class agenter.FileOperations[source]

Bases: object

Low-level file operations with path security and modification tracking.

This class provides the core file I/O primitives that both AnthropicTextEditor and FileTools use. It handles: - Path resolution and security checks via PathResolver - File existence checks - Parent directory creation for writes - Modification tracking

All methods return ToolResult. For write operations, the new content is stored in result.metadata[“new_content”].

Parameters:

resolver (PathResolver) – PathResolver instance for secure path handling.

Example

resolver = PathResolver(cwd=Path(“/project”)) ops = FileOperations(resolver)

result = ops.read_file(“src/main.py”) if result.success:

print(result.output)

result = ops.write_file(“src/new.py”, “print(‘hello’)”) print(ops.files_modified) # {“src/new.py”: “print(‘hello’)”}

__init__(resolver)[source]
Parameters:

resolver (PathResolver)

Return type:

None

property cwd: Path

The working directory.

property files_modified: dict[str, str]

Files modified since last reset (path -> content).

reset()[source]

Clear modification tracking.

Return type:

None

read_file(path)[source]

Read file contents.

Parameters:

path (str) – Path relative to cwd.

Return type:

ToolResult

Returns:

ToolResult with content in output, or error.

write_file(path, content, *, overwrite=True)[source]

Write content to a file.

Parameters:
  • path (str) – Path relative to cwd.

  • content (str) – Content to write.

  • overwrite (bool, default: True) – If False, fail if file exists.

Return type:

ToolResult

Returns:

ToolResult with success message. New content in metadata[“new_content”].

replace_string(path, old_str, new_str)[source]

Replace a unique string in a file.

The old_str must match exactly one location in the file.

Parameters:
  • path (str) – Path relative to cwd.

  • old_str (str) – String to find (must be unique).

  • new_str (str) – Replacement string.

Return type:

ToolResult

Returns:

ToolResult with success message. New content in metadata[“new_content”].

list_directory(path, *, max_depth=3, include_hidden=False)[source]

List directory contents.

Parameters:
  • path (str) – Path relative to cwd.

  • max_depth (int, default: 3) – Maximum recursion depth.

  • include_hidden (bool, default: False) – Include files starting with ‘.’.

Return type:

ToolResult

Returns:

ToolResult with directory listing or error.

check_exists(path)[source]

Check if a path exists.

Parameters:

path (str) – Path relative to cwd.

Return type:

ToolResult

Returns:

ToolResult with “file”, “directory”, or “not_found”.

is_directory(path)[source]

Check if path is a directory.

Parameters:

path (str) – Path relative to cwd.

Return type:

bool

Returns:

True if path is a directory, False otherwise.

class agenter.PathResolver[source]

Bases: object

Secure path resolution within a working directory.

This class handles path resolution with security checks to prevent directory traversal attacks and enforce write restrictions.

Parameters:
  • cwd (Path) – The working directory. All paths are resolved relative to this.

  • allowed_write_paths (list[str] | None, default: None) – Optional list of glob patterns that restrict which paths can be written to. If None, all paths within cwd are writable. Uses gitignore-style glob patterns (via pathspec) with root-anchored semantics.

Pattern Semantics (gitignore-style via pathspec):

Patterns are anchored to the working directory root and use familiar gitignore glob semantics:

  • ‘*’ matches within a single path component

  • ‘**’ matches zero or more directories at any depth

  • ‘?’ matches any single character

  • ‘[seq]’ matches any character in seq

Examples

  • ‘src/**/*.py’ matches ‘src/foo.py’, ‘src/sub/bar.py’, ‘src/a/b/c.py’

  • ‘tests/**’ matches everything under tests/ at any depth

  • *.py’ matches only Python files at the root

  • **/*.py’ matches Python files at any depth

Example

resolver = PathResolver(Path(“/project”), [“src//*.py”, “tests/”])

# This works - within cwd path = resolver.resolve(“src/main.py”)

# This raises PathSecurityError - outside cwd path = resolver.resolve(“../secret.txt”)

__init__(cwd, allowed_write_paths=None)[source]
Parameters:
Return type:

None

property cwd: Path

The resolved working directory.

resolve(path)[source]

Resolve a path relative to cwd, ensuring it stays within cwd.

Parameters:

path (str) – Path to resolve. Can be relative or absolute.

Return type:

Path

Returns:

The resolved absolute path.

Raises:

PathSecurityError – If the resolved path is outside the working directory.

is_write_allowed(resolved_path)[source]

Check if a path matches allowed write patterns.

Uses gitignore-style glob patterns anchored to the working directory. This provides intuitive matching where ‘src/**/*.py’ matches all Python files under src/ at any depth.

Parameters:

resolved_path (Path) – An already-resolved absolute path.

Return type:

bool

Returns:

True if writing to this path is allowed, False otherwise.

resolve_and_check_write(path)[source]

Resolve a path and verify write access in one call.

Convenience method that combines resolve() and is_write_allowed().

Parameters:

path (str) – Path to resolve and check.

Return type:

Path

Returns:

The resolved absolute path.

Raises:

PathSecurityError – If the path is outside cwd or not writable.

Runtime

Budget tracking and file tracing utilities.

class agenter.BudgetMeter[source]

Bases: object

Tracks resource usage and checks budget limits.

Monitors tokens, cost, time, and iterations against configured limits.

Example

tracker = BudgetMeter(Budget(max_tokens=1000)) tracker.add_usage(UsageDelta(tokens=500, cost_usd=0.25)) tracker.add_iteration() exceeded, reason = tracker.exceeded() if exceeded:

print(f”Limit hit: {reason.value}”) # e.g., “iterations”

Parameters:

budget (Budget)

__init__(budget)[source]
Parameters:

budget (Budget)

add_usage(delta)[source]

Add usage delta to tracked totals.

Parameters:

delta (UsageDelta) – Usage delta containing tokens and cost to add.

Return type:

None

add_iteration()[source]

Record a completed iteration.

Return type:

None

exceeded()[source]

Check if any budget limit is exceeded.

Returns:

bool, limit_type: BudgetLimitType | None)

Return type:

tuple[bool, BudgetLimitType | None]

usage()[source]

Return current usage statistics.

Return type:

dict

class agenter.FileTracer[source]

Bases: object

Default tracer that saves interactions to timestamped files.

Creates a directory structure like:
logs/agenter_20251231_120000/

001_prompt.txt 001_response.txt 001_tool_read_file.txt 002_prompt.txt …

Example

# Auto-create timestamped directory tracer = FileTracer()

# Use specific directory tracer = FileTracer(“./my_traces”)

# Pass to agent agent = AutonomousCodingAgent(tracer=tracer) result = await agent.execute(request) print(f”Traces saved to: {tracer.output_dir}”)

Parameters:

output_dir (Path | str | None, default: None)

__init__(output_dir=None)[source]

Initialize the file tracer.

Parameters:

output_dir (Path | str | None, default: None) – Directory for trace files. If None, creates a timestamped directory under ./logs/

Return type:

None

property output_dir: Path

Directory where traces are saved.

trace_prompt(agent, system_prompt, user_prompt)[source]

Record a prompt sent to the LLM.

Parameters:
  • agent (str)

  • system_prompt (str)

  • user_prompt (str)

Return type:

None

trace_response(agent, content)[source]

Record a response from the LLM.

Parameters:
Return type:

None

log_tool_call(agent, tool_name, args)[source]

Record a tool call.

Parameters:
Return type:

None

log_tool_result(agent, tool_name, result, success)[source]

Record a tool result (appends to existing tool file).

Parameters:
Return type:

None

class agenter.Tracer[source]

Bases: Protocol

Protocol for tracing agent interactions.

Implement this protocol to create custom tracers that integrate with external logging systems, databases, or observability platforms.

Example

class MyTracer:
def trace_prompt(self, agent: str, system_prompt: str, user_prompt: str) -> None:

send_to_logging_service({“type”: “prompt”, “agent”: agent, …})

agent = AutonomousCodingAgent(tracer=MyTracer())

property output_dir: Path | None

Directory where traces are saved, if applicable.

trace_prompt(agent, system_prompt, user_prompt)[source]

Record a prompt sent to the LLM.

Parameters:
  • agent (str)

  • system_prompt (str)

  • user_prompt (str)

Return type:

None

trace_response(agent, content)[source]

Record a response from the LLM.

Parameters:
Return type:

None

log_tool_call(agent, tool_name, args)[source]

Record a tool call.

Parameters:
Return type:

None

log_tool_result(agent, tool_name, result, success)[source]

Record a tool result.

Parameters:
Return type:

None

__init__(*args, **kwargs)

Validators

Post-execution validators.

class agenter.SyntaxValidator[source]

Bases: object

Validates Python syntax using AST parsing.

Fast, zero-dependency validation that catches syntax errors immediately.

is_blocking: bool = True
async validate(files, cwd)[source]

Check Python files for syntax errors.

Parameters:
Return type:

ValidationResult

class agenter.ValidationResult[source]

Bases: BaseModel

Result of running validators on modified files.

Parameters:

data (Any)

passed: bool
errors: list[str]
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

Errors

Exception classes raised by Agenter.

class agenter.AgenterError[source]

Bases: Exception

Base exception for all SDK errors.

All exceptions raised by the SDK inherit from this class, making it easy to catch all SDK-related errors with a single except clause.

Parameters:

message (str) – Human-readable error description.

__init__(message)[source]
Parameters:

message (str)

Return type:

None

class agenter.BackendError[source]

Bases: AgenterError

Error from the coding backend (e.g., API failure).

Raised when communication with the LLM backend fails, including authentication errors, rate limits, and network issues.

Parameters:
  • message (str) – Human-readable error description.

  • backend (str | None, default: None) – Name of the backend that failed (e.g., “anthropic-sdk”, “claude-code”).

  • cause (Exception | None, default: None) – The underlying exception, if any.

__init__(message, *, backend=None, cause=None)[source]
Parameters:
Return type:

None

class agenter.BudgetExceededError[source]

Bases: AgenterError

Budget limit exceeded during execution.

Raised when any configured budget limit is reached (iterations, tokens, cost, or time).

Parameters:
  • message (str) – Human-readable error description.

  • limit_type (str) – Type of limit exceeded (“iterations”, “tokens”, “cost”, “time”).

  • limit_value (float | int) – The configured limit value.

  • actual_value (float | int) – The actual value that exceeded the limit.

__init__(message, *, limit_type, limit_value, actual_value)[source]
Parameters:
Return type:

None

class agenter.ConfigurationError[source]

Bases: AgenterError

Invalid SDK configuration.

Raised when the SDK is configured incorrectly, such as missing required environment variables or invalid parameter combinations.

Parameters:
  • message (str) – Human-readable error description.

  • parameter (str | None, default: None) – The configuration parameter that is invalid.

  • value (str | None, default: None) – The invalid value, if applicable.

__init__(message, *, parameter=None, value=None)[source]
Parameters:
  • message (str)

  • parameter (str | None, default: None)

  • value (str | None, default: None)

Return type:

None

class agenter.PathSecurityError[source]

Bases: AgenterError

Security violation in path operations.

Raised when a path operation would violate security constraints, such as attempting to access files outside the working directory or writing to disallowed paths.

Parameters:
  • message (str) – Human-readable error description.

  • path (str | Path) – The problematic path.

  • cwd (str | Path | None, default: None) – The configured working directory.

  • reason (str | None, default: None) – Specific reason for the security violation.

__init__(message, *, path, cwd=None, reason=None)[source]
Parameters:
Return type:

None

class agenter.ToolExecutionError[source]

Bases: AgenterError

Error during tool execution.

Raised when a tool fails to execute properly. This includes both built-in file tools and custom user-defined tools.

Parameters:
  • message (str) – Human-readable error description.

  • tool_name (str) – Name of the tool that failed.

  • inputs (dict | None, default: None) – The inputs that were passed to the tool.

  • cause (Exception | None, default: None) – The underlying exception, if any.

__init__(message, *, tool_name, inputs=None, cause=None)[source]
Parameters:
Return type:

None

class agenter.ValidationError[source]

Bases: AgenterError

Error during code validation.

Raised when validators fail to validate the generated code. Contains details about which validators failed and specific error messages.

Parameters:
  • message (str) – Human-readable error description.

  • validator (str | None, default: None) – Name of the validator that failed.

  • errors (list[str] | None, default: None) – List of specific validation error messages.

__init__(message, *, validator=None, errors=None)[source]
Parameters:
Return type:

None

Enums

class agenter.Verbosity[source]

Bases: str, Enum

Verbosity level for console output.

QUIET = 'quiet'
NORMAL = 'normal'
VERBOSE = 'verbose'
__new__(value)
class agenter.CodingStatus[source]

Bases: str, Enum

Status of a coding session.

Status semantics:

COMPLETED: Task succeeded within all budget constraints. COMPLETED_WITH_LIMIT_EXCEEDED: Task succeeded (validation passed) but

exceeded one or more budget limits. The work is valid but consumed more resources than configured.

BUDGET_EXCEEDED: Task was stopped because budget limits were reached

before the task could complete successfully.

REFUSED: LLM explicitly refused the request due to safety, policy,

or capability limitations. Use result.refusal_reason for details.

FAILED: True failure (exception, unrecoverable error, not budget-related).

COMPLETED = 'completed'
COMPLETED_WITH_LIMIT_EXCEEDED = 'completed_with_limit_exceeded'
FAILED = 'failed'
BUDGET_EXCEEDED = 'budget_exceeded'
REFUSED = 'refused'
__new__(value)
class agenter.ToolError[source]

Bases: BaseModel

Structured error information for tool failures.

Parameters:
  • code – Machine-readable error code from ToolErrorCode.

  • message – Human-readable error description.

  • data (Any)

code: ToolErrorCode
message: str
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class agenter.ToolErrorCode[source]

Bases: str, Enum

Standardized error codes for tool failures.

FILE_NOT_FOUND = 'file_not_found'
PATH_SECURITY = 'path_security'
INVALID_INPUT = 'invalid_input'
STRING_NOT_FOUND = 'string_not_found'
IO_ERROR = 'io_error'
UNKNOWN_TOOL = 'unknown_tool'
NOT_A_DIRECTORY = 'not_a_directory'
EXECUTION_ERROR = 'execution_error'
__new__(value)

Logging

agenter.configure_logging(level='INFO', quiet=False)[source]

Configure agenter logging output.

Parameters:
  • level (Literal['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], default: 'INFO') – Minimum log level to display. Default is INFO which hides verbose debug output.

  • quiet (bool, default: False) – If True, silence all agenter logs completely.

Return type:

None

Example

>>> from agenter.logging import configure_logging
>>> configure_logging(level="INFO")  # Hide debug messages
>>> configure_logging(quiet=True)    # Silence all logs