oats.tool

Tool implementations for file operations, search, web access, and more.

oats.tool.registry

Tool registry and base definitions for the OATS agent framework.

This module provides the core abstractions for tool registration and execution:

  • Tool — Abstract base class that all tools inherit from.

  • ToolContext — Context object passed to every tool execution.

  • ToolResult — Result object returned by tools after execution.

  • ToolRegistry — Central registry for discovering and managing tools.

Module-level convenience functions:

  • get_tool_registry() — Get the singleton registry instance.

  • register_tool() — Register a tool in the global registry.

  • get_tool() — Look up a tool by name or alias.

  • list_tools() — List all registered tools.

class oats.tool.registry.ToolContext(**data)[source]

Bases: BaseModel

Context passed to every tool execution.

Carries session identity, directory paths, and optional state (file cache, agent nesting info) that tools may need.

session_id

Unique identifier for the current session.

project_dir

Root directory of the project.

working_dir

Current working directory for the tool.

user_confirmed

Whether the user has confirmed this action.

parent_session_id

ID of the parent session (for sub-agents).

agent_depth

Current nesting depth of sub-agents.

max_agent_depth

Maximum allowed sub-agent nesting depth.

file_cache

Optional file state cache set by the session processor.

session_id: str
project_dir: Path
working_dir: Path
user_confirmed: bool
parent_session_id: str | None
agent_depth: int
max_agent_depth: int
file_cache: Any | None
class Config[source]

Bases: object

Pydantic config to allow arbitrary types (e.g. Path).

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

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

class oats.tool.registry.ToolResult(title, output, metadata=<factory>, error=None, attachments=<factory>)[source]

Bases: object

Result returned by a tool after execution.

title

Short title for the result (shown in the UI).

output

The main output text.

metadata

Arbitrary key-value pairs for additional context.

error

Error message if the tool failed.

attachments

List of attachment dicts (files, images, etc.).

title: str
output: str
metadata: dict[str, Any]
error: str | None = None
attachments: list[dict[str, Any]]
__init__(title, output, metadata=<factory>, error=None, attachments=<factory>)
class oats.tool.registry.Tool[source]

Bases: ABC

Abstract base class for all tools.

Each tool must implement name(), description(), parameters(), and execute(). Optional hooks include requires_permission(), is_concurrency_safe(), and to_definition().

Subclasses represent individual capabilities (read, write, edit, bash, etc.) that the agent can invoke during a session.

abstract property name: str

Unique identifier for the tool.

abstract property description: str

Description of what the tool does.

abstract property parameters: dict[str, Any]

JSON Schema for the tool parameters.

abstractmethod async execute(args, ctx)[source]

Execute the tool with the given arguments.

Return type:

ToolResult

is_concurrency_safe(args=None)[source]

Whether this tool can safely run concurrently with other tools.

Read-only tools (read, glob, grep) are safe. Write tools (write, edit, bash) are not, because they can have side effects that conflict.

Override in subclasses to return True for read-only tools.

Return type:

bool

property aliases: list[str]

Optional alternate names for backwards compatibility.

property keywords: list[str]

Short search terms describing when this tool should be used.

property always_load: bool

Whether this tool should almost always be available to the model.

Mirrors Claude Code’s “alwaysLoad” concept in a lightweight way so essential tools stay visible even when we rank the broader tool set.

property strict: bool

Whether provider-side tool schema adherence should be as strict as the serving stack supports.

requires_permission(args, ctx)[source]

Check if this execution requires user permission.

Returns None if no permission needed, or a description of what permission is needed.

Return type:

str | None

to_definition()[source]

Convert this tool to an LLM-compatible tool definition.

Return type:

dict[str, Any]

Returns:

A dict with name, description, and parameters keys suitable for inclusion in an LLM function-calling schema.

class oats.tool.registry.ToolRegistry[source]

Bases: object

Central registry for all available tools.

Maintains a name→tool mapping and supports lookup by name or alias. Use the module-level convenience functions (register_tool(), get_tool(), list_tools()) to interact with the global instance.

__init__()[source]

Initialize an empty tool registry.

register(tool)[source]

Register a tool under its primary name.

Return type:

None

Parameters:

tool – The Tool instance to register.

get(name)[source]

Get a tool by its primary name or any of its aliases.

Return type:

Tool | None

Parameters:

name – The tool name or alias to look up.

Returns:

The Tool instance, or None if not found.

list()[source]

List all registered tools.

Return type:

list[Tool]

Returns:

A list of all Tool instances.

to_definitions()[source]

Get all tool definitions in LLM-compatible format.

Return type:

list[dict[str, Any]]

Returns:

A list of dicts with name, description, and parameters.

oats.tool.registry.get_tool_registry()[source]

Get the global tool registry, creating it if necessary.

Return type:

ToolRegistry

Returns:

The singleton ToolRegistry instance.

oats.tool.registry.register_tool(tool)[source]

Register a tool in the global registry.

Return type:

None

Parameters:

tool – A Tool instance to register.

oats.tool.registry.get_tool(name)[source]

Get a tool by name or alias from the global registry.

Return type:

Tool | None

Parameters:

name – The tool name or alias to look up.

Returns:

The Tool instance, or None if not found.

oats.tool.registry.list_tools()[source]

List all registered tools.

Return type:

list[Tool]

Returns:

A list of all Tool instances in the global registry.

oats.tool.read

Read tool for reading file contents.

Provides ReadTool which reads files with line numbers, supports offset and limit parameters for reading portions of large files, and truncates long lines for readability.

class oats.tool.read.ReadTool[source]

Bases: Tool

Read the contents of a file with line numbers.

Supports reading full files or specific ranges via offset and limit parameters. Long lines are truncated for readability. Binary files are detected and rejected.

Example

read file_path="src/main.py"
read file_path="large_file.txt" offset=100 limit=50
MAX_LINES = 2000
MAX_LINE_LENGTH = 2000
property name: str

Unique identifier for the tool.

property aliases: list[str]

Optional alternate names for backwards compatibility.

property keywords: list[str]

Short search terms describing when this tool should be used.

property always_load: bool

Whether this tool should almost always be available to the model.

Mirrors Claude Code’s “alwaysLoad” concept in a lightweight way so essential tools stay visible even when we rank the broader tool set.

property strict: bool

Whether provider-side tool schema adherence should be as strict as the serving stack supports.

is_concurrency_safe(args=None)[source]

Whether this tool can safely run concurrently with other tools.

Read-only tools (read, glob, grep) are safe. Write tools (write, edit, bash) are not, because they can have side effects that conflict.

Override in subclasses to return True for read-only tools.

Return type:

bool

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

requires_permission(args, ctx)[source]

Read operations are generally allowed but require permission outside the project.

Return type:

str | None

Parameters:
  • args – The tool arguments containing the file_path.

  • ctx – The tool execution context.

Returns:

A permission prompt string if reading outside the project directory, otherwise None.

async execute(args, ctx)[source]

Read the contents of a file and return it with line numbers.

Supports offset and limit parameters for reading portions of large files. Long lines are truncated to MAX_LINE_LENGTH.

Return type:

ToolResult

Parameters:
  • args – Must contain file_path (str). May contain offset (int, 1-based line number) and limit (int, max lines to read).

  • ctx – The tool execution context.

Returns:

A ToolResult with the file contents formatted with line numbers.

oats.tool.write

Write tool for creating and overwriting files.

Provides WriteTool which writes content to files, creating parent directories as needed. Optionally syncs with the LSP server for diagnostics if the feature is enabled.

class oats.tool.write.WriteTool[source]

Bases: Tool

Write content to a file, creating it or overwriting if it exists.

Creates parent directories as needed. Optionally syncs with the LSP server for diagnostics if the feature is enabled.

Example

write file_path="src/new_module.py" content="def hello(): ..."
property name: str

Unique identifier for the tool.

property aliases: list[str]

Optional alternate names for backwards compatibility.

property keywords: list[str]

Short search terms describing when this tool should be used.

property always_load: bool

Whether this tool should almost always be available to the model.

Mirrors Claude Code’s “alwaysLoad” concept in a lightweight way so essential tools stay visible even when we rank the broader tool set.

property strict: bool

Whether provider-side tool schema adherence should be as strict as the serving stack supports.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

requires_permission(args, ctx)[source]

Write operations always require user permission.

Return type:

str | None

Parameters:
  • args – The tool arguments containing the file_path.

  • ctx – The tool execution context.

Returns:

A permission prompt string describing the file to be written.

async execute(args, ctx)[source]

Write content to a file, creating it or overwriting if it exists.

Creates parent directories as needed. Optionally syncs with the LSP server for diagnostics if the feature is enabled.

Return type:

ToolResult

Parameters:
  • args – Must contain file_path (str) and content (str).

  • ctx – The tool execution context.

Returns:

A ToolResult with the file path, line count, and optional LSP diagnostics.

oats.tool.edit

Edit tool for modifying existing files.

Provides EditTool which edits files by replacing text with smart fallback strategies for models that struggle with exact string matching:

  1. Exact match (primary path) — direct string replacement

  2. Fuzzy match — find closest matching block in the file (>80% confidence)

  3. Write-swap — rebuild the entire file with the intended change applied

Helper functions:

  • _fuzzy_find_best_match() — Find the best fuzzy match for a target string.

  • _apply_write_swap() — Last-resort strategy to rebuild the file.

class oats.tool.edit.EditTool[source]

Bases: Tool

Edit files by replacing exact text with fallback strategies.

Primary strategy is exact string matching. If that fails, two fallback strategies are tried:

  1. Fuzzy match — finds the closest matching block (>80% similarity)

  2. Write-swap — rebuilds the file with the best available replacement

This makes the tool robust against minor indentation or whitespace differences that can occur when LLMs generate old_string values.

Example

edit file_path="src/main.py" old_string="def old():" new_string="def new():"
property name: str

Unique identifier for the tool.

property aliases: list[str]

Optional alternate names for backwards compatibility.

property keywords: list[str]

Short search terms describing when this tool should be used.

property strict: bool

Whether provider-side tool schema adherence should be as strict as the serving stack supports.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

requires_permission(args, ctx)[source]

Edit operations always require user permission.

Return type:

str | None

Parameters:
  • args – The tool arguments containing the file_path.

  • ctx – The tool execution context.

Returns:

A permission prompt string describing the file to be edited.

async execute(args, ctx)[source]

Edit a file by replacing text, with smart fallback strategies.

Tries three strategies in order: 1. Exact match — direct string replacement. 2. Fuzzy match — find the closest matching block (>80% similarity). 3. Write-swap — rebuild the file with the intended change applied.

Return type:

ToolResult

Parameters:
  • args – Must contain file_path (str), old_string (str), new_string (str). May contain replace_all (bool).

  • ctx – The tool execution context.

Returns:

A ToolResult with the edit result and strategy used.

oats.tool.multiedit

MultiEdit tool for applying multiple edits to a file in sequence.

Provides MultiEditTool which applies multiple text replacements to a single file in sequence. Each edit sees the results of earlier ones, and the file is written only if at least one replacement was made.

class oats.tool.multiedit.MultiEditTool[source]

Bases: Tool

Apply multiple text replacements to a single file in sequence.

Each edit is applied in order so that later edits see the results of earlier ones. The file is written only if at least one replacement was made, ensuring atomicity.

Example

multiedit file_path="src/main.py" edits=[
    {"old_string": "def a():", "new_string": "def b():"},
    {"old_string": "def c():", "new_string": "def d():"}
]
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

requires_permission(args, ctx)[source]

MultiEdit operations always require user permission.

Return type:

str | None

Parameters:
  • args – The tool arguments containing file_path and edits.

  • ctx – The tool execution context.

Returns:

A permission prompt string describing the number of edits and target file.

async execute(args, ctx)[source]

Apply multiple text replacements to a single file in sequence.

Each edit is applied in order so that later edits see the results of earlier ones. The file is written only if at least one replacement was made.

Return type:

ToolResult

Parameters:
  • args – Must contain file_path (str) and edits (list of dicts with old_string, new_string, and optional replace_all).

  • ctx – The tool execution context.

Returns:

A ToolResult with per-edit results and a total replacement count.

oats.tool.patch

ApplyPatch tool for applying unified diff patches.

Provides ApplyPatchTool which applies standard unified diff format patches (like output from git diff or diff -u) to one or more files.

Data classes:

  • PatchHunk — A single hunk from a unified diff patch.

  • FilePatch — Patch metadata for a single file.

class oats.tool.patch.PatchHunk(old_start, old_count, new_start, new_count, lines)[source]

Bases: object

A single hunk from a unified diff patch.

old_start

Starting line number in the original file (1-based).

old_count

Number of lines in the original file for this hunk.

new_start

Starting line number in the new file (1-based).

new_count

Number of lines in the new file for this hunk.

lines

The hunk body lines (prefixed with +, -, or space).

old_start: int
old_count: int
new_start: int
new_count: int
lines: list[str]
__init__(old_start, old_count, new_start, new_count, lines)
class oats.tool.patch.FilePatch(old_path, new_path, hunks, is_new=False, is_deleted=False)[source]

Bases: object

Patch metadata for a single file.

old_path

Path in the original file (from --- line).

new_path

Path in the new file (from +++ line).

hunks

List of PatchHunk objects for this file.

is_new

True if this is a new file (old path is /dev/null).

is_deleted

True if this is a deleted file (new path is /dev/null).

old_path: str
new_path: str
hunks: list[PatchHunk]
is_new: bool = False
is_deleted: bool = False
__init__(old_path, new_path, hunks, is_new=False, is_deleted=False)
class oats.tool.patch.ApplyPatchTool[source]

Bases: Tool

Apply a unified diff patch to one or more files.

Accepts standard unified diff format (like output from git diff or diff -u). Supports multi-file patches, new files, and deleted files. Hunks are applied in reverse order to maintain line number integrity.

Example

Call apply_patch with a unified diff patch string as the patch argument.

property name: str

Unique identifier for the tool.

property aliases: list[str]

Optional alternate names for backwards compatibility.

property keywords: list[str]

Short search terms describing when this tool should be used.

property strict: bool

Whether provider-side tool schema adherence should be as strict as the serving stack supports.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

requires_permission(args, ctx)[source]

Patch operations always require user permission.

Return type:

str | None

Parameters:
  • args – The tool arguments containing the patch content.

  • ctx – The tool execution context.

Returns:

A permission prompt string describing the number of affected files.

async execute(args, ctx)[source]

Apply a unified diff patch to one or more files.

Parses the patch, then creates, modifies, or deletes files as specified.

Return type:

ToolResult

Parameters:
  • args – Must contain patch (str, the unified diff content). May contain strip (int, path components to strip, default 1).

  • ctx – The tool execution context.

Returns:

A ToolResult with per-file results and a summary.

oats.tool.bash

Bash tool for executing shell commands.

Provides BashTool which runs shell commands in a subprocess with configurable timeout and working directory. Output is captured and truncated if it exceeds configured limits. AWS commands are automatically classified and redacted for safety via oats.tool.aws_safety.

class oats.tool.bash.BashTool[source]

Bases: Tool

Execute shell commands in a subprocess.

Runs bash commands with configurable timeout and working directory. Output is captured and truncated if it exceeds configured limits. AWS commands are automatically classified and redacted for safety.

Example

bash command="pip install requests"
bash command="pytest tests/" timeout=60
MAX_OUTPUT_LINES = 5000
MAX_OUTPUT_BYTES = 1000000000
DEFAULT_TIMEOUT = 300
property name: str

Unique identifier for the tool.

property aliases: list[str]

Optional alternate names for backwards compatibility.

property keywords: list[str]

Short search terms describing when this tool should be used.

property always_load: bool

Whether this tool should almost always be available to the model.

Mirrors Claude Code’s “alwaysLoad” concept in a lightweight way so essential tools stay visible even when we rank the broader tool set.

property strict: bool

Whether provider-side tool schema adherence should be as strict as the serving stack supports.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

requires_permission(args, ctx)[source]

Bash commands always require user permission before execution.

Return type:

str | None

Parameters:
  • args – The tool arguments containing the command.

  • ctx – The tool execution context.

Returns:

A permission prompt string describing the command to be executed.

async execute(args, ctx)[source]

Execute a shell command and capture its output.

Runs the command in a subprocess with stdout/stderr merged. Output is truncated if it exceeds the configured limits.

Return type:

ToolResult

Parameters:
  • args – Must contain command (str). May contain timeout (int, seconds) and working_dir (str).

  • ctx – The tool execution context.

Returns:

A ToolResult with the command output and exit code.

oats.tool.glob_tool

Glob tool for finding files by pattern.

Provides GlobTool which finds files matching glob patterns, supporting both recursive (**) and non-recursive patterns. Results are sorted by modification time (newest first).

class oats.tool.glob_tool.GlobTool[source]

Bases: Tool

Find files matching a glob pattern.

Supports both recursive (**) and non-recursive patterns. Results are sorted by modification time (newest first) and truncated to MAX_RESULTS (500).

Example

glob pattern="**/*.py"
glob pattern="*.ts" path="src/"
MAX_RESULTS = 500
is_concurrency_safe(args=None)[source]

Whether this tool can safely run concurrently with other tools.

Read-only tools (read, glob, grep) are safe. Write tools (write, edit, bash) are not, because they can have side effects that conflict.

Override in subclasses to return True for read-only tools.

Return type:

bool

property name: str

Unique identifier for the tool.

property aliases: list[str]

Optional alternate names for backwards compatibility.

property keywords: list[str]

Short search terms describing when this tool should be used.

property always_load: bool

Whether this tool should almost always be available to the model.

Mirrors Claude Code’s “alwaysLoad” concept in a lightweight way so essential tools stay visible even when we rank the broader tool set.

property strict: bool

Whether provider-side tool schema adherence should be as strict as the serving stack supports.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Find files matching a glob pattern.

Supports both recursive (**) and non-recursive patterns. Results are sorted by modification time (newest first) and truncated to MAX_RESULTS.

Return type:

ToolResult

Parameters:
  • args – Must contain pattern (str). May contain path (str, directory to search in).

  • ctx – The tool execution context.

Returns:

A ToolResult with the list of matching file paths.

oats.tool.grep

Grep tool for searching file contents with regex patterns.

Provides GrepTool which searches for patterns in files using ripgrep (if available) or Python regex as a fallback. Supports file type filtering, context lines, and multiple output modes.

class oats.tool.grep.GrepTool[source]

Bases: Tool

Search for regex patterns in file contents.

Uses ripgrep if available, otherwise falls back to Python regex. Supports file type filtering, context lines, and multiple output modes (content, files, count).

Example

grep pattern="def .*\(self" path="src/"
grep pattern="TODO" glob="*.py" output_mode="files"
MAX_RESULTS = 200
MAX_CONTEXT_LINES = 5
is_concurrency_safe(args=None)[source]

Whether this tool can safely run concurrently with other tools.

Read-only tools (read, glob, grep) are safe. Write tools (write, edit, bash) are not, because they can have side effects that conflict.

Override in subclasses to return True for read-only tools.

Return type:

bool

property name: str

Unique identifier for the tool.

property aliases: list[str]

Optional alternate names for backwards compatibility.

property keywords: list[str]

Short search terms describing when this tool should be used.

property always_load: bool

Whether this tool should almost always be available to the model.

Mirrors Claude Code’s “alwaysLoad” concept in a lightweight way so essential tools stay visible even when we rank the broader tool set.

property strict: bool

Whether provider-side tool schema adherence should be as strict as the serving stack supports.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Search for regex patterns in files.

Uses ripgrep if available, otherwise falls back to Python regex. Supports file type filtering, context lines, and multiple output modes.

Return type:

ToolResult

Parameters:
  • args – Must contain pattern (str). May contain path (str), glob (str), type (str), case_insensitive (bool), context_lines (int), and output_mode (str: ‘content’, ‘files’, ‘count’).

  • ctx – The tool execution context.

Returns:

A ToolResult with search results or an error message.

oats.tool.webfetch

WebFetch tool for fetching and processing web content.

Provides WebFetchTool which fetches content from URLs and converts HTML to simplified plain text/markdown. Content is truncated if it exceeds the maximum length.

class oats.tool.webfetch.WebFetchTool[source]

Bases: Tool

Fetch content from a URL and convert it to plain text/markdown.

Validates the URL, fetches the content via HTTP, and converts HTML to simplified text. Content is truncated if it exceeds the maximum length (100KB).

Example

webfetch url="https://docs.python.org/3/library/asyncio.html"
MAX_CONTENT_LENGTH = 100000
TIMEOUT = 30
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Fetch content from a URL and convert it to plain text/markdown.

Validates the URL, fetches the content via HTTP, and converts HTML to simplified text. Content is truncated if it exceeds the maximum length.

Return type:

ToolResult

Parameters:
  • args – Must contain url (str). May contain prompt (str) for describing what information to extract.

  • ctx – The tool execution context.

Returns:

A ToolResult with the fetched content and metadata.

oats.tool.websearch

WebSearch tool for searching the web.

Provides WebSearchTool which searches the web using multiple backends in priority order: SerpAPI, Brave, Tavily, Playwright/DuckDuckGo, and DuckDuckGo instant answer API.

class oats.tool.websearch.WebSearchTool[source]

Bases: Tool

Search the web for information using multiple backends.

Tries backends in priority order: SerpAPI, Brave, Tavily, Playwright/DuckDuckGo, and DuckDuckGo instant answer API. The first available backend (based on API key configuration) is used.

Example

websearch query="Python async best practices"
websearch query="sphinx documentation" num_results=3
TIMEOUT = 30
MAX_RESULTS = 10
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Search the web using the best available backend.

Tries backends in priority order: SerpAPI → Brave → Tavily → Playwright/DuckDuckGo → DuckDuckGo instant answer API.

Return type:

ToolResult

Parameters:
  • args – Must contain query (str). May contain num_results (int, default 5).

  • ctx – The tool execution context.

Returns:

A ToolResult with search results or an error message.

oats.tool.agent_tool

Sub-agent tool — spawns independent child agents with their own sessions.

Allows the LLM to delegate complex, multi-step tasks to specialized sub-agents that run their own tool loops.

Provides two tools:

  • AgentTool — Spawn a sub-agent to handle a complex task autonomously.

  • AgentStatusTool — Check the status of a background sub-agent.

Agent types control tool access:

  • general — all tools (default)

  • explore — read-only (read, glob, grep, bash, webfetch, websearch)

  • plan — planning tools (read, glob, grep, plan tools, todowrite)

  • verify — verification (read, glob, grep, bash)

class oats.tool.agent_tool.AgentTool[source]

Bases: Tool

Spawn a sub-agent to handle a complex task autonomously.

The sub-agent gets its own session, tool access, and context. It runs the full agent loop and returns the final result.

Agent types control tool access: - general: all tools (default) - explore: read-only (read, glob, grep, bash, webfetch, websearch) - plan: planning tools (read, glob, grep, plan tools, todowrite) - verify: verification (read, glob, grep, bash)

property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Spawn and run a sub-agent to handle a delegated task.

Validates the prompt, checks the agent nesting depth limit, and either runs the sub-agent synchronously or spawns it as a background task. The sub-agent gets its own session, tool access (filtered by agent type), and optional git worktree isolation.

Return type:

ToolResult

Parameters:
  • args – Must contain prompt (str). May contain agent_type (str, one of general, explore, plan, verify), model_override (str), provider_override (str), working_dir (str), run_in_background (bool), and isolation (str, none or worktree).

  • ctx – The tool execution context.

Returns:

A ToolResult with the sub-agent’s output (synchronous mode) or a launch confirmation with agent_id (background mode).

class oats.tool.agent_tool.AgentStatusTool[source]

Bases: Tool

Check the status and results of a background sub-agent.

Looks up the agent by ID in the background results cache. If the agent has completed, returns its result. If still running, reports status.

Example

agent_status agent_id="abc123"
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Check the status and results of a background sub-agent.

Looks up the agent by ID in the background results cache. If the agent has completed, returns its result. If still running, reports status.

Return type:

ToolResult

Parameters:
  • args – Must contain agent_id (str).

  • ctx – The tool execution context.

Returns:

A ToolResult with the agent status and optionally its output.

oats.tool.lsp_tool

LSP-backed code intelligence tool.

Provides LSPTool which queries a local Language Server Protocol server for code intelligence operations including go-to-definition, find-references, hover information, diagnostics, and symbol search.

class oats.tool.lsp_tool.LSPTool[source]

Bases: Tool

Query a local Language Server Protocol (LSP) server for code intelligence.

Supports operations such as go-to-definition, find-references, hover information, diagnostics, and symbol search. Automatically detects the appropriate language server for the file type.

Example

lsp operation="definition" file_path="src/main.py" line=10 column=5
lsp operation="workspace_symbols" query="MyClass"
property name: str

Unique identifier for the tool.

property aliases: list[str]

Optional alternate names for backwards compatibility.

property keywords: list[str]

Short search terms describing when this tool should be used.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

is_concurrency_safe(args=None)[source]

LSP queries are read-only and safe to run concurrently.

Return type:

bool

Returns:

True — LSP operations do not modify files.

property strict: bool

Enforce strict parameter validation for LSP operations.

async execute(args, ctx)[source]

Execute an LSP operation (definition, references, hover, etc.).

Detects the appropriate language server for the file type, syncs the file content, and runs the requested operation.

Return type:

ToolResult

Parameters:
  • args – Must contain operation (str). May contain file_path (str), line (int), column (int), query (str), and include_declaration (bool).

  • ctx – The tool execution context.

Returns:

A ToolResult with the formatted LSP response.

oats.tool.memory_tool

Memory tools — read, write, and delete persistent memories.

Provides three tools for managing persistent memories that survive across sessions:

  • MemoryReadTool — List or search persistent memories.

  • MemoryWriteTool — Create or update a persistent memory.

  • MemoryDeleteTool — Delete a persistent memory by ID.

Helper functions:

  • _get_manager() — Create a MemoryManager from the tool context.

class oats.tool.memory_tool.MemoryReadTool[source]

Bases: Tool

List or search persistent memories across sessions.

Memories contain user preferences, project context, feedback, and references. Supports keyword search and type filtering.

Example

memory_read
memory_read query="authentication"
memory_read type_filter="project"
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

List or search persistent memories.

If a query is provided, searches memories by keyword. Otherwise, loads all memories. An optional type filter can narrow results.

Return type:

ToolResult

Parameters:
  • args – May contain query (str) and type_filter (str).

  • ctx – The tool execution context.

Returns:

A ToolResult with the matching memories.

class oats.tool.memory_tool.MemoryWriteTool[source]

Bases: Tool

Create or update a persistent memory for future sessions.

Supports four memory types: user (preferences/role), feedback (how to approach work), project (ongoing goals/decisions), and reference (external resources). Scope can be project (local to repo) or user (global).

Example

memory_write title="Preferred style" content="Use PEP 8" type="user"
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Save a new persistent memory.

Return type:

ToolResult

Parameters:
  • args – Must contain title (str) and content (str). May contain type (str), tags (list of str), and scope (str).

  • ctx – The tool execution context.

Returns:

A ToolResult confirming the memory was saved with its ID.

class oats.tool.memory_tool.MemoryDeleteTool[source]

Bases: Tool

Delete a persistent memory by its ID (partial match accepted).

Searches all memories for an ID that starts with the given prefix and deletes the first match.

Example

memory_delete memory_id="abc12345"
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Delete a persistent memory by its ID (partial match accepted).

Return type:

ToolResult

Parameters:
  • args – Must contain memory_id (str — first 8 chars is enough).

  • ctx – The tool execution context.

Returns:

A ToolResult confirming deletion or an error.

oats.tool.plan

Planning mode tools for creating implementation plans before execution.

Provides three tools for the planning workflow:

  • PlanEnterTool — Enter planning mode and create a plan file.

  • PlanExitTool — Exit planning mode and request user approval.

  • PlanStatusTool — Check the current planning mode status.

Helper functions:

  • is_planning_mode() — Check if a session is in planning mode.

  • get_plan_state() — Get the full planning state for a session.

class oats.tool.plan.PlanEnterTool[source]

Bases: Tool

Enter planning mode to create an implementation plan.

Creates a skeleton plan file and stores the planning state in session-scoped storage. While in planning mode, file-modifying tools are blocked.

Example

plan_enter reason="Adding user authentication feature"
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Enter planning mode and create an initial plan file.

Creates a skeleton plan file at the specified path (default .coder/plan.md) and stores the planning state in session-scoped storage. While in planning mode, file-modifying tools are blocked.

Return type:

ToolResult

Parameters:
  • args – May contain reason (str) and plan_file (str, path for the plan file).

  • ctx – The tool execution context.

Returns:

A ToolResult confirming entry into planning mode with instructions.

class oats.tool.plan.PlanExitTool[source]

Bases: Tool

Exit planning mode and request user approval for the plan.

Deactivates the planning state, allowing file-modifying tools to resume. Presents the plan summary for user review.

Example

plan_exit summary="Plan to add auth: 3 steps, 4 files modified"
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Exit planning mode and present the plan for user approval.

Reads the plan file content, deactivates planning mode, and sets the session state to awaiting_approval. The user can then approve, request changes, or cancel.

Return type:

ToolResult

Parameters:
  • args – May contain summary (str) — a brief summary of the plan.

  • ctx – The tool execution context.

Returns:

A ToolResult with the plan content and approval options.

class oats.tool.plan.PlanStatusTool[source]

Bases: Tool

Check the current planning mode status for the session.

Returns whether the session is in planning mode, the plan file path, the reason for entering planning mode, and any summary information.

Example

plan_status
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Check the current planning mode status for the session.

Return type:

ToolResult

Parameters:
  • args – Unused (no parameters required).

  • ctx – The tool execution context.

Returns:

A ToolResult with the planning mode status and metadata.

async oats.tool.plan.is_planning_mode(session_id)[source]

Check if a session is currently in planning mode.

Return type:

bool

Parameters:

session_id – The session identifier.

Returns:

True if the session has an active planning state.

async oats.tool.plan.get_plan_state(session_id)[source]

Get the full planning state for a session.

Return type:

dict[str, Any] | None

Parameters:

session_id – The session identifier.

Returns:

The planning state dict, or None if no state exists.

oats.tool.question

Question tool for asking the user questions during execution.

Provides two tools for user interaction:

  • QuestionTool — Ask one or more structured questions with options.

  • AskUserTool — Ask a single simple yes/no or choice question.

Both tools publish events to the event bus so the UI can display questions and collect responses.

class oats.tool.question.QuestionTool[source]

Bases: Tool

Ask the user one or more questions and get their response.

Publishes questions to the event bus so the UI can display them. Supports multiple-choice questions with optional multi-select. In CLI mode, questions are formatted for terminal display.

Example

question questions=[{"question": "Which approach?", "header": "Approach",
             "options": [{"label": "A", "description": "Option A"},
                         {"label": "B", "description": "Option B"}]}]
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Publish one or more questions to the user and await a response.

Sends a PERMISSION_REQUEST event to the bus so the UI can display the questions. In CLI mode, the questions are formatted for display.

Return type:

ToolResult

Parameters:
  • args – Must contain questions — a list of dicts with keys question, header, options, and optional multiSelect.

  • ctx – The tool execution context.

Returns:

A ToolResult with the formatted questions and a flag indicating that a response is awaited.

class oats.tool.question.AskUserTool[source]

Bases: Tool

Simplified tool for asking a single yes/no or choice question.

Publishes a PERMISSION_REQUEST event to the event bus so the UI can display the question and collect a response. Supports optional multiple-choice options and a default value.

Example

ask_user question="Should I proceed with the deletion?"
ask_user question="Which color?" options=["red", "blue", "green"]
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Ask the user a simple question with optional choices.

Publishes a PERMISSION_REQUEST event to the bus so the UI can display the question and collect a response.

Return type:

ToolResult

Parameters:
  • args – Must contain question (str). May contain options (list of str) and default (str).

  • ctx – The tool execution context.

Returns:

A ToolResult with the formatted question and a flag indicating that a response is awaited.

oats.tool.todowrite

TodoWrite tool for task management.

Provides TodoWriteTool and TodoReadTool for creating, managing, and reading structured task lists. Tasks are persisted to session-scoped storage via KeyValueStorage.

Data models:

  • TodoItem — A single task item with content, status, and active form.

  • TodoList — A list of TodoItem objects.

class oats.tool.todowrite.TodoItem(**data)[source]

Bases: BaseModel

A single task item in the todo list.

content

The task description in imperative form.

status

Current status — pending, in_progress, or completed.

active_form

Present tense description of what is being done (e.g., “Implementing feature”).

content: str
status: Literal['pending', 'in_progress', 'completed']
active_form: str
model_config: ClassVar[ConfigDict] = {}

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

class oats.tool.todowrite.TodoList(**data)[source]

Bases: BaseModel

List of todo items for a session.

items

The list of TodoItem objects.

items: list[TodoItem]
model_config: ClassVar[ConfigDict] = {}

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

class oats.tool.todowrite.TodoWriteTool[source]

Bases: Tool

Create and manage a structured task list for tracking progress.

Persists todo items to session-scoped storage. Supports three statuses: pending, in_progress, and completed. Each item has a description (content) and a present-tense active form.

Example

todowrite todos=[
    {"content": "Implement auth", "status": "in_progress", "activeForm": "Implementing auth"},
    {"content": "Write tests", "status": "pending", "activeForm": "Writing tests"}
]
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Store the updated todo list for the current session.

Parses the incoming todo items, validates them, persists them to session-scoped storage, and returns a formatted summary.

Return type:

ToolResult

Parameters:
  • args – Must contain todos — a list of dicts with keys content, status, and activeForm.

  • ctx – The tool execution context.

Returns:

A ToolResult with the formatted todo list and progress summary.

class oats.tool.todowrite.TodoReadTool[source]

Bases: Tool

Read and display the current task list for the session.

Loads the persisted todo list from session-scoped storage and formats it with status icons and a progress summary.

Example

toread
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Read and display the current todo list for the session.

Retrieves the stored todo list from session-scoped storage and formats it with status icons and a progress summary.

Return type:

ToolResult

Parameters:
  • args – Unused (no parameters required).

  • ctx – The tool execution context.

Returns:

A ToolResult with the formatted todo list and progress summary.

oats.tool.init_tools

Tool initialization and registration for the OATS agent framework.

This module imports all available tools and provides the init_tools() function to register them based on the active feature profile. The profile is controlled via the CODER_PROFILE environment variable (minimal | standard | full | custom), with individual feature groups overridable via CODER_FEATURE_<GROUP>=0|1.

Core tools (read, write, edit, glob, grep, bash, patch) are always loaded. Additional tool groups (web, planning, memory, agents, LSP, MCP) are registered conditionally based on feature flags.

class oats.tool.init_tools.Tool[source]

Bases: ABC

Abstract base class for all tools.

Each tool must implement name(), description(), parameters(), and execute(). Optional hooks include requires_permission(), is_concurrency_safe(), and to_definition().

Subclasses represent individual capabilities (read, write, edit, bash, etc.) that the agent can invoke during a session.

abstract property name: str

Unique identifier for the tool.

abstract property description: str

Description of what the tool does.

abstract property parameters: dict[str, Any]

JSON Schema for the tool parameters.

abstractmethod async execute(args, ctx)[source]

Execute the tool with the given arguments.

Return type:

ToolResult

is_concurrency_safe(args=None)[source]

Whether this tool can safely run concurrently with other tools.

Read-only tools (read, glob, grep) are safe. Write tools (write, edit, bash) are not, because they can have side effects that conflict.

Override in subclasses to return True for read-only tools.

Return type:

bool

property aliases: list[str]

Optional alternate names for backwards compatibility.

property keywords: list[str]

Short search terms describing when this tool should be used.

property always_load: bool

Whether this tool should almost always be available to the model.

Mirrors Claude Code’s “alwaysLoad” concept in a lightweight way so essential tools stay visible even when we rank the broader tool set.

property strict: bool

Whether provider-side tool schema adherence should be as strict as the serving stack supports.

requires_permission(args, ctx)[source]

Check if this execution requires user permission.

Returns None if no permission needed, or a description of what permission is needed.

Return type:

str | None

to_definition()[source]

Convert this tool to an LLM-compatible tool definition.

Return type:

dict[str, Any]

Returns:

A dict with name, description, and parameters keys suitable for inclusion in an LLM function-calling schema.

class oats.tool.init_tools.ToolContext(**data)[source]

Bases: BaseModel

Context passed to every tool execution.

Carries session identity, directory paths, and optional state (file cache, agent nesting info) that tools may need.

session_id

Unique identifier for the current session.

project_dir

Root directory of the project.

working_dir

Current working directory for the tool.

user_confirmed

Whether the user has confirmed this action.

parent_session_id

ID of the parent session (for sub-agents).

agent_depth

Current nesting depth of sub-agents.

max_agent_depth

Maximum allowed sub-agent nesting depth.

file_cache

Optional file state cache set by the session processor.

session_id: str
project_dir: Path
working_dir: Path
user_confirmed: bool
parent_session_id: str | None
agent_depth: int
max_agent_depth: int
file_cache: Any | None
class Config[source]

Bases: object

Pydantic config to allow arbitrary types (e.g. Path).

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

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

class oats.tool.init_tools.ToolResult(title, output, metadata=<factory>, error=None, attachments=<factory>)[source]

Bases: object

Result returned by a tool after execution.

title

Short title for the result (shown in the UI).

output

The main output text.

metadata

Arbitrary key-value pairs for additional context.

error

Error message if the tool failed.

attachments

List of attachment dicts (files, images, etc.).

title: str
output: str
metadata: dict[str, Any]
error: str | None = None
attachments: list[dict[str, Any]]
__init__(title, output, metadata=<factory>, error=None, attachments=<factory>)
class oats.tool.init_tools.ToolRegistry[source]

Bases: object

Central registry for all available tools.

Maintains a name→tool mapping and supports lookup by name or alias. Use the module-level convenience functions (register_tool(), get_tool(), list_tools()) to interact with the global instance.

__init__()[source]

Initialize an empty tool registry.

register(tool)[source]

Register a tool under its primary name.

Return type:

None

Parameters:

tool – The Tool instance to register.

get(name)[source]

Get a tool by its primary name or any of its aliases.

Return type:

Tool | None

Parameters:

name – The tool name or alias to look up.

Returns:

The Tool instance, or None if not found.

list()[source]

List all registered tools.

Return type:

list[Tool]

Returns:

A list of all Tool instances.

to_definitions()[source]

Get all tool definitions in LLM-compatible format.

Return type:

list[dict[str, Any]]

Returns:

A list of dicts with name, description, and parameters.

oats.tool.init_tools.get_tool(name)[source]

Get a tool by name or alias from the global registry.

Return type:

Tool | None

Parameters:

name – The tool name or alias to look up.

Returns:

The Tool instance, or None if not found.

oats.tool.init_tools.list_tools()[source]

List all registered tools.

Return type:

list[Tool]

Returns:

A list of all Tool instances in the global registry.

oats.tool.init_tools.register_tool(tool)[source]

Register a tool in the global registry.

Return type:

None

Parameters:

tool – A Tool instance to register.

class oats.tool.init_tools.BashTool[source]

Bases: Tool

Execute shell commands in a subprocess.

Runs bash commands with configurable timeout and working directory. Output is captured and truncated if it exceeds configured limits. AWS commands are automatically classified and redacted for safety.

Example

bash command="pip install requests"
bash command="pytest tests/" timeout=60
MAX_OUTPUT_LINES = 5000
MAX_OUTPUT_BYTES = 1000000000
DEFAULT_TIMEOUT = 300
property name: str

Unique identifier for the tool.

property aliases: list[str]

Optional alternate names for backwards compatibility.

property keywords: list[str]

Short search terms describing when this tool should be used.

property always_load: bool

Whether this tool should almost always be available to the model.

Mirrors Claude Code’s “alwaysLoad” concept in a lightweight way so essential tools stay visible even when we rank the broader tool set.

property strict: bool

Whether provider-side tool schema adherence should be as strict as the serving stack supports.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

requires_permission(args, ctx)[source]

Bash commands always require user permission before execution.

Return type:

str | None

Parameters:
  • args – The tool arguments containing the command.

  • ctx – The tool execution context.

Returns:

A permission prompt string describing the command to be executed.

async execute(args, ctx)[source]

Execute a shell command and capture its output.

Runs the command in a subprocess with stdout/stderr merged. Output is truncated if it exceeds the configured limits.

Return type:

ToolResult

Parameters:
  • args – Must contain command (str). May contain timeout (int, seconds) and working_dir (str).

  • ctx – The tool execution context.

Returns:

A ToolResult with the command output and exit code.

class oats.tool.init_tools.ReadTool[source]

Bases: Tool

Read the contents of a file with line numbers.

Supports reading full files or specific ranges via offset and limit parameters. Long lines are truncated for readability. Binary files are detected and rejected.

Example

read file_path="src/main.py"
read file_path="large_file.txt" offset=100 limit=50
MAX_LINES = 2000
MAX_LINE_LENGTH = 2000
property name: str

Unique identifier for the tool.

property aliases: list[str]

Optional alternate names for backwards compatibility.

property keywords: list[str]

Short search terms describing when this tool should be used.

property always_load: bool

Whether this tool should almost always be available to the model.

Mirrors Claude Code’s “alwaysLoad” concept in a lightweight way so essential tools stay visible even when we rank the broader tool set.

property strict: bool

Whether provider-side tool schema adherence should be as strict as the serving stack supports.

is_concurrency_safe(args=None)[source]

Whether this tool can safely run concurrently with other tools.

Read-only tools (read, glob, grep) are safe. Write tools (write, edit, bash) are not, because they can have side effects that conflict.

Override in subclasses to return True for read-only tools.

Return type:

bool

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

requires_permission(args, ctx)[source]

Read operations are generally allowed but require permission outside the project.

Return type:

str | None

Parameters:
  • args – The tool arguments containing the file_path.

  • ctx – The tool execution context.

Returns:

A permission prompt string if reading outside the project directory, otherwise None.

async execute(args, ctx)[source]

Read the contents of a file and return it with line numbers.

Supports offset and limit parameters for reading portions of large files. Long lines are truncated to MAX_LINE_LENGTH.

Return type:

ToolResult

Parameters:
  • args – Must contain file_path (str). May contain offset (int, 1-based line number) and limit (int, max lines to read).

  • ctx – The tool execution context.

Returns:

A ToolResult with the file contents formatted with line numbers.

class oats.tool.init_tools.WriteTool[source]

Bases: Tool

Write content to a file, creating it or overwriting if it exists.

Creates parent directories as needed. Optionally syncs with the LSP server for diagnostics if the feature is enabled.

Example

write file_path="src/new_module.py" content="def hello(): ..."
property name: str

Unique identifier for the tool.

property aliases: list[str]

Optional alternate names for backwards compatibility.

property keywords: list[str]

Short search terms describing when this tool should be used.

property always_load: bool

Whether this tool should almost always be available to the model.

Mirrors Claude Code’s “alwaysLoad” concept in a lightweight way so essential tools stay visible even when we rank the broader tool set.

property strict: bool

Whether provider-side tool schema adherence should be as strict as the serving stack supports.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

requires_permission(args, ctx)[source]

Write operations always require user permission.

Return type:

str | None

Parameters:
  • args – The tool arguments containing the file_path.

  • ctx – The tool execution context.

Returns:

A permission prompt string describing the file to be written.

async execute(args, ctx)[source]

Write content to a file, creating it or overwriting if it exists.

Creates parent directories as needed. Optionally syncs with the LSP server for diagnostics if the feature is enabled.

Return type:

ToolResult

Parameters:
  • args – Must contain file_path (str) and content (str).

  • ctx – The tool execution context.

Returns:

A ToolResult with the file path, line count, and optional LSP diagnostics.

class oats.tool.init_tools.EditTool[source]

Bases: Tool

Edit files by replacing exact text with fallback strategies.

Primary strategy is exact string matching. If that fails, two fallback strategies are tried:

  1. Fuzzy match — finds the closest matching block (>80% similarity)

  2. Write-swap — rebuilds the file with the best available replacement

This makes the tool robust against minor indentation or whitespace differences that can occur when LLMs generate old_string values.

Example

edit file_path="src/main.py" old_string="def old():" new_string="def new():"
property name: str

Unique identifier for the tool.

property aliases: list[str]

Optional alternate names for backwards compatibility.

property keywords: list[str]

Short search terms describing when this tool should be used.

property strict: bool

Whether provider-side tool schema adherence should be as strict as the serving stack supports.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

requires_permission(args, ctx)[source]

Edit operations always require user permission.

Return type:

str | None

Parameters:
  • args – The tool arguments containing the file_path.

  • ctx – The tool execution context.

Returns:

A permission prompt string describing the file to be edited.

async execute(args, ctx)[source]

Edit a file by replacing text, with smart fallback strategies.

Tries three strategies in order: 1. Exact match — direct string replacement. 2. Fuzzy match — find the closest matching block (>80% similarity). 3. Write-swap — rebuild the file with the intended change applied.

Return type:

ToolResult

Parameters:
  • args – Must contain file_path (str), old_string (str), new_string (str). May contain replace_all (bool).

  • ctx – The tool execution context.

Returns:

A ToolResult with the edit result and strategy used.

class oats.tool.init_tools.GlobTool[source]

Bases: Tool

Find files matching a glob pattern.

Supports both recursive (**) and non-recursive patterns. Results are sorted by modification time (newest first) and truncated to MAX_RESULTS (500).

Example

glob pattern="**/*.py"
glob pattern="*.ts" path="src/"
MAX_RESULTS = 500
is_concurrency_safe(args=None)[source]

Whether this tool can safely run concurrently with other tools.

Read-only tools (read, glob, grep) are safe. Write tools (write, edit, bash) are not, because they can have side effects that conflict.

Override in subclasses to return True for read-only tools.

Return type:

bool

property name: str

Unique identifier for the tool.

property aliases: list[str]

Optional alternate names for backwards compatibility.

property keywords: list[str]

Short search terms describing when this tool should be used.

property always_load: bool

Whether this tool should almost always be available to the model.

Mirrors Claude Code’s “alwaysLoad” concept in a lightweight way so essential tools stay visible even when we rank the broader tool set.

property strict: bool

Whether provider-side tool schema adherence should be as strict as the serving stack supports.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Find files matching a glob pattern.

Supports both recursive (**) and non-recursive patterns. Results are sorted by modification time (newest first) and truncated to MAX_RESULTS.

Return type:

ToolResult

Parameters:
  • args – Must contain pattern (str). May contain path (str, directory to search in).

  • ctx – The tool execution context.

Returns:

A ToolResult with the list of matching file paths.

class oats.tool.init_tools.GrepTool[source]

Bases: Tool

Search for regex patterns in file contents.

Uses ripgrep if available, otherwise falls back to Python regex. Supports file type filtering, context lines, and multiple output modes (content, files, count).

Example

grep pattern="def .*\(self" path="src/"
grep pattern="TODO" glob="*.py" output_mode="files"
MAX_RESULTS = 200
MAX_CONTEXT_LINES = 5
is_concurrency_safe(args=None)[source]

Whether this tool can safely run concurrently with other tools.

Read-only tools (read, glob, grep) are safe. Write tools (write, edit, bash) are not, because they can have side effects that conflict.

Override in subclasses to return True for read-only tools.

Return type:

bool

property name: str

Unique identifier for the tool.

property aliases: list[str]

Optional alternate names for backwards compatibility.

property keywords: list[str]

Short search terms describing when this tool should be used.

property always_load: bool

Whether this tool should almost always be available to the model.

Mirrors Claude Code’s “alwaysLoad” concept in a lightweight way so essential tools stay visible even when we rank the broader tool set.

property strict: bool

Whether provider-side tool schema adherence should be as strict as the serving stack supports.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Search for regex patterns in files.

Uses ripgrep if available, otherwise falls back to Python regex. Supports file type filtering, context lines, and multiple output modes.

Return type:

ToolResult

Parameters:
  • args – Must contain pattern (str). May contain path (str), glob (str), type (str), case_insensitive (bool), context_lines (int), and output_mode (str: ‘content’, ‘files’, ‘count’).

  • ctx – The tool execution context.

Returns:

A ToolResult with search results or an error message.

class oats.tool.init_tools.WebFetchTool[source]

Bases: Tool

Fetch content from a URL and convert it to plain text/markdown.

Validates the URL, fetches the content via HTTP, and converts HTML to simplified text. Content is truncated if it exceeds the maximum length (100KB).

Example

webfetch url="https://docs.python.org/3/library/asyncio.html"
MAX_CONTENT_LENGTH = 100000
TIMEOUT = 30
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Fetch content from a URL and convert it to plain text/markdown.

Validates the URL, fetches the content via HTTP, and converts HTML to simplified text. Content is truncated if it exceeds the maximum length.

Return type:

ToolResult

Parameters:
  • args – Must contain url (str). May contain prompt (str) for describing what information to extract.

  • ctx – The tool execution context.

Returns:

A ToolResult with the fetched content and metadata.

class oats.tool.init_tools.WebSearchTool[source]

Bases: Tool

Search the web for information using multiple backends.

Tries backends in priority order: SerpAPI, Brave, Tavily, Playwright/DuckDuckGo, and DuckDuckGo instant answer API. The first available backend (based on API key configuration) is used.

Example

websearch query="Python async best practices"
websearch query="sphinx documentation" num_results=3
TIMEOUT = 30
MAX_RESULTS = 10
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Search the web using the best available backend.

Tries backends in priority order: SerpAPI → Brave → Tavily → Playwright/DuckDuckGo → DuckDuckGo instant answer API.

Return type:

ToolResult

Parameters:
  • args – Must contain query (str). May contain num_results (int, default 5).

  • ctx – The tool execution context.

Returns:

A ToolResult with search results or an error message.

class oats.tool.init_tools.TodoWriteTool[source]

Bases: Tool

Create and manage a structured task list for tracking progress.

Persists todo items to session-scoped storage. Supports three statuses: pending, in_progress, and completed. Each item has a description (content) and a present-tense active form.

Example

todowrite todos=[
    {"content": "Implement auth", "status": "in_progress", "activeForm": "Implementing auth"},
    {"content": "Write tests", "status": "pending", "activeForm": "Writing tests"}
]
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Store the updated todo list for the current session.

Parses the incoming todo items, validates them, persists them to session-scoped storage, and returns a formatted summary.

Return type:

ToolResult

Parameters:
  • args – Must contain todos — a list of dicts with keys content, status, and activeForm.

  • ctx – The tool execution context.

Returns:

A ToolResult with the formatted todo list and progress summary.

class oats.tool.init_tools.TodoReadTool[source]

Bases: Tool

Read and display the current task list for the session.

Loads the persisted todo list from session-scoped storage and formats it with status icons and a progress summary.

Example

toread
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Read and display the current todo list for the session.

Retrieves the stored todo list from session-scoped storage and formats it with status icons and a progress summary.

Return type:

ToolResult

Parameters:
  • args – Unused (no parameters required).

  • ctx – The tool execution context.

Returns:

A ToolResult with the formatted todo list and progress summary.

class oats.tool.init_tools.QuestionTool[source]

Bases: Tool

Ask the user one or more questions and get their response.

Publishes questions to the event bus so the UI can display them. Supports multiple-choice questions with optional multi-select. In CLI mode, questions are formatted for terminal display.

Example

question questions=[{"question": "Which approach?", "header": "Approach",
             "options": [{"label": "A", "description": "Option A"},
                         {"label": "B", "description": "Option B"}]}]
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Publish one or more questions to the user and await a response.

Sends a PERMISSION_REQUEST event to the bus so the UI can display the questions. In CLI mode, the questions are formatted for display.

Return type:

ToolResult

Parameters:
  • args – Must contain questions — a list of dicts with keys question, header, options, and optional multiSelect.

  • ctx – The tool execution context.

Returns:

A ToolResult with the formatted questions and a flag indicating that a response is awaited.

class oats.tool.init_tools.AskUserTool[source]

Bases: Tool

Simplified tool for asking a single yes/no or choice question.

Publishes a PERMISSION_REQUEST event to the event bus so the UI can display the question and collect a response. Supports optional multiple-choice options and a default value.

Example

ask_user question="Should I proceed with the deletion?"
ask_user question="Which color?" options=["red", "blue", "green"]
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Ask the user a simple question with optional choices.

Publishes a PERMISSION_REQUEST event to the bus so the UI can display the question and collect a response.

Return type:

ToolResult

Parameters:
  • args – Must contain question (str). May contain options (list of str) and default (str).

  • ctx – The tool execution context.

Returns:

A ToolResult with the formatted question and a flag indicating that a response is awaited.

class oats.tool.init_tools.MultiEditTool[source]

Bases: Tool

Apply multiple text replacements to a single file in sequence.

Each edit is applied in order so that later edits see the results of earlier ones. The file is written only if at least one replacement was made, ensuring atomicity.

Example

multiedit file_path="src/main.py" edits=[
    {"old_string": "def a():", "new_string": "def b():"},
    {"old_string": "def c():", "new_string": "def d():"}
]
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

requires_permission(args, ctx)[source]

MultiEdit operations always require user permission.

Return type:

str | None

Parameters:
  • args – The tool arguments containing file_path and edits.

  • ctx – The tool execution context.

Returns:

A permission prompt string describing the number of edits and target file.

async execute(args, ctx)[source]

Apply multiple text replacements to a single file in sequence.

Each edit is applied in order so that later edits see the results of earlier ones. The file is written only if at least one replacement was made.

Return type:

ToolResult

Parameters:
  • args – Must contain file_path (str) and edits (list of dicts with old_string, new_string, and optional replace_all).

  • ctx – The tool execution context.

Returns:

A ToolResult with per-edit results and a total replacement count.

class oats.tool.init_tools.ApplyPatchTool[source]

Bases: Tool

Apply a unified diff patch to one or more files.

Accepts standard unified diff format (like output from git diff or diff -u). Supports multi-file patches, new files, and deleted files. Hunks are applied in reverse order to maintain line number integrity.

Example

Call apply_patch with a unified diff patch string as the patch argument.

property name: str

Unique identifier for the tool.

property aliases: list[str]

Optional alternate names for backwards compatibility.

property keywords: list[str]

Short search terms describing when this tool should be used.

property strict: bool

Whether provider-side tool schema adherence should be as strict as the serving stack supports.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

requires_permission(args, ctx)[source]

Patch operations always require user permission.

Return type:

str | None

Parameters:
  • args – The tool arguments containing the patch content.

  • ctx – The tool execution context.

Returns:

A permission prompt string describing the number of affected files.

async execute(args, ctx)[source]

Apply a unified diff patch to one or more files.

Parses the patch, then creates, modifies, or deletes files as specified.

Return type:

ToolResult

Parameters:
  • args – Must contain patch (str, the unified diff content). May contain strip (int, path components to strip, default 1).

  • ctx – The tool execution context.

Returns:

A ToolResult with per-file results and a summary.

class oats.tool.init_tools.PlanEnterTool[source]

Bases: Tool

Enter planning mode to create an implementation plan.

Creates a skeleton plan file and stores the planning state in session-scoped storage. While in planning mode, file-modifying tools are blocked.

Example

plan_enter reason="Adding user authentication feature"
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Enter planning mode and create an initial plan file.

Creates a skeleton plan file at the specified path (default .coder/plan.md) and stores the planning state in session-scoped storage. While in planning mode, file-modifying tools are blocked.

Return type:

ToolResult

Parameters:
  • args – May contain reason (str) and plan_file (str, path for the plan file).

  • ctx – The tool execution context.

Returns:

A ToolResult confirming entry into planning mode with instructions.

class oats.tool.init_tools.PlanExitTool[source]

Bases: Tool

Exit planning mode and request user approval for the plan.

Deactivates the planning state, allowing file-modifying tools to resume. Presents the plan summary for user review.

Example

plan_exit summary="Plan to add auth: 3 steps, 4 files modified"
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Exit planning mode and present the plan for user approval.

Reads the plan file content, deactivates planning mode, and sets the session state to awaiting_approval. The user can then approve, request changes, or cancel.

Return type:

ToolResult

Parameters:
  • args – May contain summary (str) — a brief summary of the plan.

  • ctx – The tool execution context.

Returns:

A ToolResult with the plan content and approval options.

class oats.tool.init_tools.PlanStatusTool[source]

Bases: Tool

Check the current planning mode status for the session.

Returns whether the session is in planning mode, the plan file path, the reason for entering planning mode, and any summary information.

Example

plan_status
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Check the current planning mode status for the session.

Return type:

ToolResult

Parameters:
  • args – Unused (no parameters required).

  • ctx – The tool execution context.

Returns:

A ToolResult with the planning mode status and metadata.

class oats.tool.init_tools.GenerateREADMETool[source]

Bases: Tool

Generate README.md files with detailed module overviews in subdirectories.

Scans each subdirectory and creates a README.md file that provides:

  • A detailed overview of the modules in that subdirectory

  • Module names and descriptions

  • Key functions and classes

  • Usage examples where applicable

Example

generate_readme
generate_readme path="./oats/cli"
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Scan a directory and generate README.md files for each subdirectory.

Validates the target path, analyzes Python modules in each subdirectory (extracting docstrings via AST), and writes a README.md file per subdirectory with module overviews, descriptions, and usage examples.

Return type:

ToolResult

Parameters:
  • args – May contain path (str, directory to scan, default: current dir).

  • ctx – The tool execution context.

Returns:

A ToolResult with a summary of README files generated.

class oats.tool.init_tools.AgentTool[source]

Bases: Tool

Spawn a sub-agent to handle a complex task autonomously.

The sub-agent gets its own session, tool access, and context. It runs the full agent loop and returns the final result.

Agent types control tool access: - general: all tools (default) - explore: read-only (read, glob, grep, bash, webfetch, websearch) - plan: planning tools (read, glob, grep, plan tools, todowrite) - verify: verification (read, glob, grep, bash)

property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Spawn and run a sub-agent to handle a delegated task.

Validates the prompt, checks the agent nesting depth limit, and either runs the sub-agent synchronously or spawns it as a background task. The sub-agent gets its own session, tool access (filtered by agent type), and optional git worktree isolation.

Return type:

ToolResult

Parameters:
  • args – Must contain prompt (str). May contain agent_type (str, one of general, explore, plan, verify), model_override (str), provider_override (str), working_dir (str), run_in_background (bool), and isolation (str, none or worktree).

  • ctx – The tool execution context.

Returns:

A ToolResult with the sub-agent’s output (synchronous mode) or a launch confirmation with agent_id (background mode).

class oats.tool.init_tools.AgentStatusTool[source]

Bases: Tool

Check the status and results of a background sub-agent.

Looks up the agent by ID in the background results cache. If the agent has completed, returns its result. If still running, reports status.

Example

agent_status agent_id="abc123"
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Check the status and results of a background sub-agent.

Looks up the agent by ID in the background results cache. If the agent has completed, returns its result. If still running, reports status.

Return type:

ToolResult

Parameters:
  • args – Must contain agent_id (str).

  • ctx – The tool execution context.

Returns:

A ToolResult with the agent status and optionally its output.

class oats.tool.init_tools.MemoryReadTool[source]

Bases: Tool

List or search persistent memories across sessions.

Memories contain user preferences, project context, feedback, and references. Supports keyword search and type filtering.

Example

memory_read
memory_read query="authentication"
memory_read type_filter="project"
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

List or search persistent memories.

If a query is provided, searches memories by keyword. Otherwise, loads all memories. An optional type filter can narrow results.

Return type:

ToolResult

Parameters:
  • args – May contain query (str) and type_filter (str).

  • ctx – The tool execution context.

Returns:

A ToolResult with the matching memories.

class oats.tool.init_tools.MemoryWriteTool[source]

Bases: Tool

Create or update a persistent memory for future sessions.

Supports four memory types: user (preferences/role), feedback (how to approach work), project (ongoing goals/decisions), and reference (external resources). Scope can be project (local to repo) or user (global).

Example

memory_write title="Preferred style" content="Use PEP 8" type="user"
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Save a new persistent memory.

Return type:

ToolResult

Parameters:
  • args – Must contain title (str) and content (str). May contain type (str), tags (list of str), and scope (str).

  • ctx – The tool execution context.

Returns:

A ToolResult confirming the memory was saved with its ID.

class oats.tool.init_tools.MemoryDeleteTool[source]

Bases: Tool

Delete a persistent memory by its ID (partial match accepted).

Searches all memories for an ID that starts with the given prefix and deletes the first match.

Example

memory_delete memory_id="abc12345"
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Delete a persistent memory by its ID (partial match accepted).

Return type:

ToolResult

Parameters:
  • args – Must contain memory_id (str — first 8 chars is enough).

  • ctx – The tool execution context.

Returns:

A ToolResult confirming deletion or an error.

class oats.tool.init_tools.ToolSearchTool[source]

Bases: Tool

Search the tool catalog and return callable schemas for matched tools.

Supports two query modes:

  1. Exact-select — prefix with select: and comma-separated tool names

  2. Fuzzy search — natural language query scored against tool names, descriptions, aliases, and keywords

Example

tool_search query="select:deploy_app_with_docker_compose,get_app_logs"
tool_search query="deploy docker app"
property name: str

Unique identifier for the tool.

property aliases: list[str]

Optional alternate names for backwards compatibility.

property keywords: list[str]

Short search terms describing when this tool should be used.

property always_load: bool

Whether this tool should almost always be available to the model.

Mirrors Claude Code’s “alwaysLoad” concept in a lightweight way so essential tools stay visible even when we rank the broader tool set.

property strict: bool

Whether provider-side tool schema adherence should be as strict as the serving stack supports.

is_concurrency_safe(args=None)[source]

Whether this tool can safely run concurrently with other tools.

Read-only tools (read, glob, grep) are safe. Write tools (write, edit, bash) are not, because they can have side effects that conflict.

Override in subclasses to return True for read-only tools.

Return type:

bool

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Search the tool catalog and return schemas for matched tools.

Return type:

ToolResult

Parameters:
  • args – Must contain query (str) and optionally max_results (int).

  • ctx – The tool execution context.

Returns:

A ToolResult with matched tool schemas or an error message.

class oats.tool.init_tools.PlaywrightSearchTool[source]

Bases: Tool

Search the web using a headless Chromium browser (no API keys needed).

Uses Playwright to launch a headless browser, search Bing (primary) or DuckDuckGo (fallback), and extract real web results with titles, URLs, and snippets. Registered alongside WebSearchTool and wired as a fallback when no search API keys are configured.

Example

playwright_search query="Python async best practices"
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

property keywords: list[str]

Short search terms describing when this tool should be used.

async execute(args, ctx)[source]

Search the web using a headless Chromium browser.

Delegates to playwright_search() which tries Bing first, then DuckDuckGo as a fallback.

Return type:

ToolResult

Parameters:
  • args – Must contain query (str). May contain num_results (int, default 5).

  • ctx – The tool execution context.

Returns:

A ToolResult with search results or an error message.

class oats.tool.init_tools.LSPTool[source]

Bases: Tool

Query a local Language Server Protocol (LSP) server for code intelligence.

Supports operations such as go-to-definition, find-references, hover information, diagnostics, and symbol search. Automatically detects the appropriate language server for the file type.

Example

lsp operation="definition" file_path="src/main.py" line=10 column=5
lsp operation="workspace_symbols" query="MyClass"
property name: str

Unique identifier for the tool.

property aliases: list[str]

Optional alternate names for backwards compatibility.

property keywords: list[str]

Short search terms describing when this tool should be used.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

is_concurrency_safe(args=None)[source]

LSP queries are read-only and safe to run concurrently.

Return type:

bool

Returns:

True — LSP operations do not modify files.

property strict: bool

Enforce strict parameter validation for LSP operations.

async execute(args, ctx)[source]

Execute an LSP operation (definition, references, hover, etc.).

Detects the appropriate language server for the file type, syncs the file content, and runs the requested operation.

Return type:

ToolResult

Parameters:
  • args – Must contain operation (str). May contain file_path (str), line (int), column (int), query (str), and include_declaration (bool).

  • ctx – The tool execution context.

Returns:

A ToolResult with the formatted LSP response.

oats.tool.generate_readme

README Generator Tool for the OATS platform.

Provides GenerateREADMETool which scans directories and generates README.md files that provide detailed overviews of the modules in each subdirectory, including module names, descriptions, key functions, and classes.

Helper function:

  • register_generate_readme_tool() — Register the tool with the global registry.

class oats.tool.generate_readme.GenerateREADMETool[source]

Bases: Tool

Generate README.md files with detailed module overviews in subdirectories.

Scans each subdirectory and creates a README.md file that provides:

  • A detailed overview of the modules in that subdirectory

  • Module names and descriptions

  • Key functions and classes

  • Usage examples where applicable

Example

generate_readme
generate_readme path="./oats/cli"
property name: str

Unique identifier for the tool.

property description: str

Description of what the tool does.

property parameters: dict[str, Any]

JSON Schema for the tool parameters.

async execute(args, ctx)[source]

Scan a directory and generate README.md files for each subdirectory.

Validates the target path, analyzes Python modules in each subdirectory (extracting docstrings via AST), and writes a README.md file per subdirectory with module overviews, descriptions, and usage examples.

Return type:

ToolResult

Parameters:
  • args – May contain path (str, directory to scan, default: current dir).

  • ctx – The tool execution context.

Returns:

A ToolResult with a summary of README files generated.

oats.tool.generate_readme.register_generate_readme_tool()[source]

Register the README generation tool with the global tool registry.

Creates a GenerateREADMETool instance and registers it via oats.tool.registry.register_tool().

Return type:

None

oats.tool.aws_safety

AWS-aware helpers for the bash tool.

Three responsibilities, all thin:

  1. Classify an aws … command as READ / MUTATE / AUTH / UNKNOWN so the caller can decide how much approval it needs.

  2. Redact AWS credentials that might leak into command output (access keys, session tokens, account IDs in ARNs if requested).

  3. Detect commands that need a real TTY (like aws sso login) and tell the caller to ask the user to run them manually with ! <cmd>.

This is deliberately not a new tool. AWS flows through bash — we just give bash a sharper eye when it sees the aws binary.

class oats.tool.aws_safety.AwsRisk(*values)[source]

Bases: str, Enum

Risk classification for AWS CLI commands.

Used to determine how much user approval a command needs before execution.

READ = 'read'
MUTATE = 'mutate'
AUTH = 'auth'
UNKNOWN = 'unknown'
class oats.tool.aws_safety.AwsCommandInfo(is_aws, risk, service=None, operation=None, needs_tty=False, reason='')[source]

Bases: object

Metadata about a parsed AWS CLI command.

is_aws

Whether the command invokes the AWS CLI.

risk

The risk classification of the command.

service

The AWS service (e.g. ‘s3’, ‘ec2’, ‘iam’).

operation

The operation verb (e.g. ‘ls’, ‘cp’, ‘describe-instances’).

needs_tty

Whether the command requires a real TTY (e.g. SSO login).

reason

A short human-readable explanation of the classification.

is_aws: bool
risk: AwsRisk
service: str | None = None
operation: str | None = None
needs_tty: bool = False
reason: str = ''
__init__(is_aws, risk, service=None, operation=None, needs_tty=False, reason='')
oats.tool.aws_safety.classify(command)[source]

Classify an aws ... shell command by risk level.

Parses the command to extract the AWS service and operation verb, then classifies it as AwsRisk.READ, AwsRisk.MUTATE, AwsRisk.AUTH, or AwsRisk.UNKNOWN.

Return type:

AwsCommandInfo

Parameters:

command – The full shell command string.

Returns:

An AwsCommandInfo with the classification result.

oats.tool.aws_safety.redact_secrets(text)[source]

Scrub AWS access keys, secret keys, and session tokens from text.

Applies three regex patterns to detect and redact: - Access key IDs (AKIA/ASIA/AIDA/AROA/AGPA/ANPA prefixes) - Secret access keys (key=value or key: value patterns) - Session tokens (key=value or key: value patterns)

Return type:

tuple[str, int]

Parameters:

text – The text to scrub (typically command output).

Returns:

A tuple of (redacted_text, num_redactions) where num_redactions is the total number of secrets that were redacted.