API Reference¶
This page documents the public API of Agenter.
AutonomousCodingAgent¶
The main entry point for using Agenter.
- class agenter.AutonomousCodingAgent[source]¶
Bases:
objectPublic 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:
- __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 backendmodel (
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 requestverbosity (
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 debuggingraise_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:
- 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 requestverbosity (
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:
Data Models¶
Request and response models for the coding agent.
CodingRequest¶
- class agenter.CodingRequest[source]¶
Bases:
BaseModelRequest 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].
CodingResult¶
- class agenter.CodingResult[source]¶
Bases:
BaseModelResult 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¶
CodingEvent¶
- class agenter.CodingEvent[source]¶
Bases:
BaseModelEvent 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¶
- class agenter.CodingEventType[source]¶
-
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¶
Tools¶
Tool protocol and decorator for custom tools.
Tool Protocol¶
- class agenter.Tool[source]¶
Bases:
ProtocolProtocol 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.
- async execute(inputs)[source]¶
Execute the tool with given inputs.
- Parameters:
inputs (
dict) – Dictionary of input parameters matching input_schema.- Return type:
- Returns:
ToolResult with output and success status.
- __init__(*args, **kwargs)¶
- class agenter.FunctionTool[source]¶
Bases:
objectTool 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:
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,
)
- 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:
- 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
ToolResult¶
- class agenter.ToolResult[source]¶
Bases:
BaseModelResult 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)
- 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:
- Return type:
- 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:
objectLow-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
- read_file(path)[source]¶
Read file contents.
- Parameters:
path (
str) – Path relative to cwd.- Return type:
- Returns:
ToolResult with content in output, or error.
- write_file(path, content, *, overwrite=True)[source]¶
Write content to a file.
- Parameters:
- Return type:
- 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:
- Return type:
- 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:
- Return type:
- Returns:
ToolResult with directory listing or error.
- class agenter.PathResolver[source]¶
Bases:
objectSecure 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
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”)
- 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:
- 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.
- 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:
- 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:
objectTracks 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)
- add_usage(delta)[source]¶
Add usage delta to tracked totals.
- Parameters:
delta (
UsageDelta) – Usage delta containing tokens and cost to add.- Return type:
- class agenter.FileTracer[source]¶
Bases:
objectDefault 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}”)
- class agenter.Tracer[source]¶
Bases:
ProtocolProtocol 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())
- __init__(*args, **kwargs)¶
Validators¶
Post-execution validators.
- class agenter.SyntaxValidator[source]¶
Bases:
objectValidates Python syntax using AST parsing.
Fast, zero-dependency validation that catches syntax errors immediately.
Errors¶
Exception classes raised by Agenter.
- class agenter.AgenterError[source]¶
Bases:
ExceptionBase 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.
- class agenter.BackendError[source]¶
Bases:
AgenterErrorError 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:
- class agenter.BudgetExceededError[source]¶
Bases:
AgenterErrorBudget limit exceeded during execution.
Raised when any configured budget limit is reached (iterations, tokens, cost, or time).
- Parameters:
- class agenter.ConfigurationError[source]¶
Bases:
AgenterErrorInvalid SDK configuration.
Raised when the SDK is configured incorrectly, such as missing required environment variables or invalid parameter combinations.
- Parameters:
- class agenter.PathSecurityError[source]¶
Bases:
AgenterErrorSecurity 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:
- class agenter.ToolExecutionError[source]¶
Bases:
AgenterErrorError during tool execution.
Raised when a tool fails to execute properly. This includes both built-in file tools and custom user-defined tools.
- Parameters:
- class agenter.ValidationError[source]¶
Bases:
AgenterErrorError during code validation.
Raised when validators fail to validate the generated code. Contains details about which validators failed and specific error messages.
- Parameters:
Enums¶
- class agenter.Verbosity[source]¶
-
Verbosity level for console output.
- QUIET = 'quiet'¶
- NORMAL = 'normal'¶
- VERBOSE = 'verbose'¶
- __new__(value)¶
- class agenter.CodingStatus[source]¶
-
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:
BaseModelStructured error information for tool failures.
- Parameters:
code – Machine-readable error code from ToolErrorCode.
message – Human-readable error description.
data (
Any)
- code: ToolErrorCode¶
- model_config: ClassVar[ConfigDict] = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agenter.ToolErrorCode[source]¶
-
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)¶