feat: first commit

This commit is contained in:
Neeraj Nigam
2026-03-18 21:23:14 -05:00
commit 0b1ec4a818
25 changed files with 3068 additions and 0 deletions

0
README.md Normal file
View File

Binary file not shown.

Binary file not shown.

Binary file not shown.

49
agent.py Normal file
View File

@@ -0,0 +1,49 @@
"""Agent graph built with LangGraph StateGraph."""
from typing import Annotated, TypedDict
from langchain_core.messages import BaseMessage, AIMessage
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode
from llm import create_model
from tools import grep, list_dir, read_file, replace_in_file, write_file
TOOLS = [read_file, grep, write_file, list_dir, replace_in_file]
class AgentState(TypedDict):
messages: Annotated[list[BaseMessage], add_messages]
def call_model(state: AgentState) -> dict:
"""Invoke the LLM with the current message history."""
model = create_model().bind_tools(TOOLS)
response = model.invoke(state["messages"])
return {"messages": [response]}
def should_continue(state: AgentState) -> str:
"""Route to tools if the last message has tool calls, otherwise end."""
last = state["messages"][-1]
if isinstance(last, AIMessage) and last.tool_calls:
return "tools"
return END
def build_graph() -> StateGraph:
"""Construct and compile the agent execution graph."""
graph = StateGraph(AgentState)
graph.add_node("agent", call_model)
graph.add_node("tools", ToolNode(TOOLS))
graph.add_edge(START, "agent")
graph.add_conditional_edges("agent", should_continue, {
"tools": "tools",
END: END,
})
graph.add_edge("tools", "agent")
return graph.compile()

89
llm.py Normal file
View File

@@ -0,0 +1,89 @@
"""LLM provider abstraction module.
Supports multiple LLM backends through a provider registry pattern.
Provider selection is driven by environment variables:
- LLM_PROVIDER: Provider name (default: "openai")
- MODEL_NAME: Model identifier (default: provider-specific)
"""
import os
from collections.abc import Callable
from langchain_aws import ChatBedrock
from langchain_core.language_models import BaseChatModel
from langchain_openai import ChatOpenAI
# Type alias for provider factory functions
ProviderFactory = Callable[[str], BaseChatModel]
def _create_openai_model(model_name: str) -> ChatOpenAI:
"""Create a ChatOpenAI instance.
Authentication is handled by the langchain-openai library
via the OPENAI_API_KEY environment variable.
"""
return ChatOpenAI(model=model_name)
def _create_llama_server_model(model_name: str) -> ChatOpenAI:
"""Create a ChatOpenAI instance configured for a local llama-server.
Reads LLAMA_SERVER_URL env var for the server base URL
(default: http://localhost:8080/v1). Sets api_key to "not-needed"
since llama-server does not require authentication.
"""
base_url = os.environ.get("LLAMA_SERVER_URL", "http://localhost:8080/v1")
return ChatOpenAI(model=model_name, base_url=base_url, api_key="not-needed")
def _create_bedrock_model(model_name: str) -> ChatBedrock:
"""Create a ChatBedrock instance.
Reads AWS_REGION env var and passes it to the constructor if set.
Authentication is handled by boto3's standard credential resolution.
"""
region = os.environ.get("AWS_REGION")
kwargs: dict = {"model_id": model_name}
if region is not None:
kwargs["region_name"] = region
return ChatBedrock(**kwargs)
# Registry mapping provider names to their factory functions
PROVIDER_REGISTRY: dict[str, ProviderFactory] = {
"openai": _create_openai_model,
"llama-server": _create_llama_server_model,
"bedrock": _create_bedrock_model,
}
# Default model names per provider
DEFAULT_MODELS: dict[str, str] = {
"openai": "gpt-4o-mini",
"llama-server": "local-model",
"bedrock": "us.anthropic.claude-3-5-sonnet-20241022-v2:0",
}
def create_model() -> BaseChatModel:
"""Create a LangChain chat model based on environment configuration.
Reads LLM_PROVIDER and MODEL_NAME from environment variables.
Returns:
A LangChain-compatible chat model instance.
Raises:
ValueError: If LLM_PROVIDER is not a registered provider name.
"""
provider = os.environ.get("LLM_PROVIDER", "openai")
factory = PROVIDER_REGISTRY.get(provider)
if factory is None:
valid = ", ".join(sorted(PROVIDER_REGISTRY.keys()))
raise ValueError(
f"Unknown LLM provider: '{provider}'. Valid providers: {valid}"
)
model_name = os.environ.get("MODEL_NAME", DEFAULT_MODELS[provider])
return factory(model_name)

86
main.py Normal file
View File

@@ -0,0 +1,86 @@
import argparse
import sys
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()
from agent import build_graph
from shell import ShellSession
from tools import set_workdir
def create_agent():
"""Create and return the compiled agent graph."""
return build_graph()
def main():
parser = argparse.ArgumentParser(description="LangGraph file-system agent")
parser.add_argument("--workdir", type=str, default=None)
args = parser.parse_args()
if args.workdir is None:
print("Error: --workdir argument is required", file=sys.stderr)
sys.exit(1)
workdir = Path(args.workdir).resolve()
if not workdir.exists():
print(f"Error: Workdir does not exist: {args.workdir}", file=sys.stderr)
sys.exit(1)
if not workdir.is_dir():
print(f"Error: Workdir is not a directory: {args.workdir}", file=sys.stderr)
sys.exit(1)
set_workdir(workdir)
shell = ShellSession(cwd=str(workdir))
agent = create_agent()
print(f"Agent ready. Working directory: {workdir}")
print("Type '.exit' or '.quit' to exit.")
print("Prefix with '!' to run a shell command.\n")
while True:
try:
user_input = input("> ")
except KeyboardInterrupt:
print("\nExiting...")
break
stripped = user_input.strip()
if stripped.lower() in (".exit", ".quit"):
print("Goodbye!")
break
if not stripped:
continue
if stripped.startswith("!"):
cmd = stripped[1:].strip()
if cmd:
try:
print(shell.run(cmd), end="")
except Exception as e:
print(f"Shell error: {e}")
continue
try:
response = agent.invoke({"messages": [("user", user_input)]})
messages = response.get("messages", [])
for msg in reversed(messages):
if hasattr(msg, "type") and msg.type == "ai" and msg.content:
print(msg.content)
break
except Exception as e:
print(f"Error: {e}")
shell.close()
if __name__ == "__main__":
main()

21
pyproject.toml Normal file
View File

@@ -0,0 +1,21 @@
[project]
name = "sonic-agent"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"langgraph",
"langchain-openai",
"langchain-aws",
"boto3",
"langchain-core",
"langchain>=1.2.12",
"python-dotenv",
]
[dependency-groups]
dev = [
"pytest",
"hypothesis",
]

38
shell.py Normal file
View File

@@ -0,0 +1,38 @@
"""Persistent shell session manager."""
import subprocess
class ShellSession:
"""Wraps a persistent bash subprocess."""
_SENTINEL = "__END_OF_CMD_OUTPUT__"
def __init__(self, cwd: str) -> None:
self._proc = subprocess.Popen(
["bash"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
cwd=cwd,
text=True,
)
def run(self, cmd: str) -> str:
"""Send a command and return its output."""
full_cmd = f"{cmd}\necho {self._SENTINEL}\n"
self._proc.stdin.write(full_cmd)
self._proc.stdin.flush()
lines = []
for line in self._proc.stdout:
if self._SENTINEL in line:
break
lines.append(line)
return "".join(lines)
def close(self) -> None:
"""Terminate the shell process."""
if self._proc.poll() is None:
self._proc.stdin.close()
self._proc.terminate()
self._proc.wait()

1
tests/__init__.py Normal file
View File

@@ -0,0 +1 @@
# Tests package

Binary file not shown.

25
tests/test_agent.py Normal file
View File

@@ -0,0 +1,25 @@
"""Unit tests for agent initialization."""
import os
from unittest.mock import patch
import main
class TestAgentInitialization:
@patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"})
def test_agent_has_all_four_tools(self):
"""Agent should be initialized with all four file system tools."""
agent = main.create_agent()
# The agent's tools are accessible via the graph's nodes
# create_agent stores tools in the agent; we can check
# by inspecting the tool names from the agent's tool node.
tool_node = agent.nodes.get("tools")
assert tool_node is not None, "Agent should have a 'tools' node"
# The actual ToolNode is wrapped in a PregelNode; access via .bound
tool_names = list(tool_node.bound.tools_by_name.keys())
expected = {"read_file", "grep", "write_file", "list_dir", "replace_in_file"}
assert set(tool_names) == expected, (
f"Expected tools {expected}, got {set(tool_names)}"
)

40
tests/test_cli.py Normal file
View File

@@ -0,0 +1,40 @@
"""Unit tests for --workdir CLI argument handling."""
import subprocess
import sys
from pathlib import Path
class TestWorkdirCLI:
def test_missing_workdir_argument(self):
"""CLI should exit with error when --workdir is not provided."""
result = subprocess.run(
[sys.executable, "main.py"],
capture_output=True,
text=True,
)
assert result.returncode != 0
assert "--workdir argument is required" in result.stderr
def test_nonexistent_workdir(self, tmp_path):
"""CLI should exit with error when --workdir path doesn't exist."""
nonexistent = tmp_path / "does_not_exist"
result = subprocess.run(
[sys.executable, "main.py", "--workdir", str(nonexistent)],
capture_output=True,
text=True,
)
assert result.returncode != 0
assert "Workdir does not exist" in result.stderr
def test_workdir_is_file_not_directory(self, tmp_path):
"""CLI should exit with error when --workdir is a file, not a directory."""
file_path = tmp_path / "afile.txt"
file_path.write_text("I am a file")
result = subprocess.run(
[sys.executable, "main.py", "--workdir", str(file_path)],
capture_output=True,
text=True,
)
assert result.returncode != 0
assert "Workdir is not a directory" in result.stderr

239
tests/test_llm.py Normal file
View File

@@ -0,0 +1,239 @@
"""Unit tests for the llm provider abstraction module."""
import os
from unittest.mock import MagicMock, patch
import pytest
class TestDefaultProviderBehavior:
"""3.1 - Default provider behavior: no env vars → ChatOpenAI with gpt-4o-mini."""
@patch("llm.ChatOpenAI")
def test_default_provider_returns_chatopenai(self, mock_openai):
"""With no env vars set, create_model() should use ChatOpenAI."""
mock_instance = MagicMock()
mock_openai.return_value = mock_instance
env = {"PATH": os.environ.get("PATH", "")}
with patch.dict(os.environ, env, clear=True):
from llm import create_model
result = create_model()
mock_openai.assert_called_once_with(model="gpt-4o-mini")
assert result is mock_instance
@patch("llm.ChatOpenAI")
def test_default_model_is_gpt4o_mini(self, mock_openai):
"""Default model name should be gpt-4o-mini when MODEL_NAME is not set."""
mock_openai.return_value = MagicMock()
env = {"PATH": os.environ.get("PATH", "")}
with patch.dict(os.environ, env, clear=True):
from llm import create_model
create_model()
mock_openai.assert_called_once_with(model="gpt-4o-mini")
class TestProviderDefaultModels:
"""3.2 - Each provider's default model name and instance type."""
@patch("llm.ChatOpenAI")
def test_openai_default_model(self, mock_openai):
"""OpenAI provider should default to gpt-4o-mini."""
mock_openai.return_value = MagicMock()
with patch.dict(os.environ, {"LLM_PROVIDER": "openai"}, clear=True):
from llm import create_model
create_model()
mock_openai.assert_called_once_with(model="gpt-4o-mini")
@patch("llm.ChatOpenAI")
def test_llama_server_default_model(self, mock_openai):
"""Llama-server provider should default to local-model."""
mock_openai.return_value = MagicMock()
with patch.dict(os.environ, {"LLM_PROVIDER": "llama-server"}, clear=True):
from llm import create_model
create_model()
mock_openai.assert_called_once()
_, kwargs = mock_openai.call_args
assert kwargs["model"] == "local-model"
@patch("llm.ChatBedrock")
def test_bedrock_default_model(self, mock_bedrock):
"""Bedrock provider should default to us.anthropic.claude-3-5-sonnet-20241022-v2:0."""
mock_bedrock.return_value = MagicMock()
with patch.dict(os.environ, {"LLM_PROVIDER": "bedrock"}, clear=True):
from llm import create_model
create_model()
mock_bedrock.assert_called_once()
_, kwargs = mock_bedrock.call_args
assert kwargs["model_id"] == "us.anthropic.claude-3-5-sonnet-20241022-v2:0"
class TestLlamaServerDefaults:
"""3.3 - Llama-server defaults: URL, API key, model name."""
@patch("llm.ChatOpenAI")
def test_llama_server_default_url(self, mock_openai):
"""Llama-server should default to http://localhost:8080/v1."""
mock_openai.return_value = MagicMock()
with patch.dict(os.environ, {"LLM_PROVIDER": "llama-server"}, clear=True):
from llm import create_model
create_model()
_, kwargs = mock_openai.call_args
assert kwargs["base_url"] == "http://localhost:8080/v1"
@patch("llm.ChatOpenAI")
def test_llama_server_api_key(self, mock_openai):
"""Llama-server should set api_key to 'not-needed'."""
mock_openai.return_value = MagicMock()
with patch.dict(os.environ, {"LLM_PROVIDER": "llama-server"}, clear=True):
from llm import create_model
create_model()
_, kwargs = mock_openai.call_args
assert kwargs["api_key"] == "not-needed"
@patch("llm.ChatOpenAI")
def test_llama_server_default_model_name(self, mock_openai):
"""Llama-server should default to 'local-model'."""
mock_openai.return_value = MagicMock()
with patch.dict(os.environ, {"LLM_PROVIDER": "llama-server"}, clear=True):
from llm import create_model
create_model()
_, kwargs = mock_openai.call_args
assert kwargs["model"] == "local-model"
@patch("llm.ChatOpenAI")
def test_llama_server_custom_url(self, mock_openai):
"""Llama-server should use LLAMA_SERVER_URL when set."""
mock_openai.return_value = MagicMock()
with patch.dict(
os.environ,
{"LLM_PROVIDER": "llama-server", "LLAMA_SERVER_URL": "http://myserver:9090/v1"},
clear=True,
):
from llm import create_model
create_model()
_, kwargs = mock_openai.call_args
assert kwargs["base_url"] == "http://myserver:9090/v1"
class TestImportSideEffects:
"""3.4 - Importing llm module does not create model instances."""
def test_import_does_not_call_constructors(self):
"""Importing the llm module should not instantiate any models."""
with patch("llm.ChatOpenAI") as mock_openai, \
patch("llm.ChatBedrock") as mock_bedrock:
# Force re-import by reloading
import importlib
import llm
importlib.reload(llm)
mock_openai.assert_not_called()
mock_bedrock.assert_not_called()
def test_registry_and_defaults_are_dicts(self):
"""PROVIDER_REGISTRY and DEFAULT_MODELS should be dicts at module level."""
from llm import DEFAULT_MODELS, PROVIDER_REGISTRY
assert isinstance(PROVIDER_REGISTRY, dict)
assert isinstance(DEFAULT_MODELS, dict)
def test_no_model_instances_at_module_level(self):
"""No BaseChatModel instances should exist at module level."""
import llm
from langchain_core.language_models import BaseChatModel
for attr_name in dir(llm):
attr = getattr(llm, attr_name)
assert not isinstance(attr, BaseChatModel), (
f"Module-level attribute '{attr_name}' is a model instance"
)
class TestProviderRegistry:
"""3.5 - PROVIDER_REGISTRY exposes expected provider names."""
def test_registry_has_expected_providers(self):
"""Registry should contain openai, llama-server, and bedrock."""
from llm import PROVIDER_REGISTRY
expected = {"openai", "llama-server", "bedrock"}
assert set(PROVIDER_REGISTRY.keys()) == expected
def test_registry_values_are_callable(self):
"""All registry values should be callable factory functions."""
from llm import PROVIDER_REGISTRY
for name, factory in PROVIDER_REGISTRY.items():
assert callable(factory), f"Factory for '{name}' is not callable"
def test_registry_has_three_providers(self):
"""Registry should have exactly 3 providers."""
from llm import PROVIDER_REGISTRY
assert len(PROVIDER_REGISTRY) == 3
class TestCreateAgentBackwardCompatibility:
"""3.6 - create_agent() still registers all 5 tools after refactor."""
@patch("llm.ChatOpenAI")
def test_create_agent_has_all_five_tools(self, mock_openai):
"""create_agent() should register read_file, grep, write_file, list_dir, replace_in_file."""
mock_model = MagicMock()
mock_openai.return_value = mock_model
with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}):
from main import create_agent
agent = create_agent()
tool_node = agent.nodes.get("tools")
assert tool_node is not None, "Agent should have a 'tools' node"
tool_names = set(tool_node.bound.tools_by_name.keys())
expected = {"read_file", "grep", "write_file", "list_dir", "replace_in_file"}
assert tool_names == expected, f"Expected tools {expected}, got {tool_names}"
@patch("llm.ChatOpenAI")
def test_create_agent_calls_create_model(self, mock_openai):
"""create_agent() should use create_model() to get the LLM."""
mock_openai.return_value = MagicMock()
with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}), \
patch("agent.create_model") as mock_create_model:
mock_model = MagicMock()
mock_model.bind_tools.return_value = MagicMock()
mock_create_model.return_value = mock_model
from main import create_agent
create_agent()
mock_create_model.assert_called_once()

View File

@@ -0,0 +1,232 @@
"""Property-based tests for the LLM provider abstraction module.
Uses hypothesis to verify universal properties across many generated inputs.
Each property test is tagged with its design document reference.
"""
import os
from unittest.mock import MagicMock, patch
import pytest
from hypothesis import given, settings, strategies as st, assume
from langchain_core.language_models import BaseChatModel
from llm import PROVIDER_REGISTRY, DEFAULT_MODELS, create_model
# ── Strategies ───────────────────────────────────────────────────────────────
registered_providers = st.sampled_from(list(PROVIDER_REGISTRY.keys()))
# Non-empty printable strings for model names
model_name_strategy = st.text(
alphabet=st.characters(whitelist_categories=("L", "N", "P", "S", "Z")),
min_size=1,
max_size=50,
).filter(lambda s: s.strip() != "" and s.isprintable())
# Strings that are NOT registered provider names (exclude null bytes for env var compat)
unknown_provider_strategy = st.text(
alphabet=st.characters(blacklist_characters="\x00"),
min_size=0,
max_size=50,
).filter(lambda s: s not in PROVIDER_REGISTRY)
# Non-empty strings for URL and region values (exclude null bytes for env var compat)
non_empty_text = st.text(
alphabet=st.characters(blacklist_characters="\x00"),
min_size=1,
max_size=100,
).filter(lambda s: s.strip() != "")
# ── Property 1: Provider registry produces valid models ──────────────────────
class TestProperty1ProviderRegistryProducesValidModels:
"""Feature: llm-provider-abstraction, Property 1: Provider registry produces valid models
For any registered provider name, setting LLM_PROVIDER and calling
create_model() returns an instance of BaseChatModel.
**Validates: Requirements 1.1, 2.1, 6.1**
"""
@settings(max_examples=10)
@given(provider=registered_providers)
def test_registered_provider_returns_base_chat_model(self, provider):
"""For any registered provider, create_model returns BaseChatModel."""
mock_instance = MagicMock(spec=BaseChatModel)
with patch("llm.ChatOpenAI", return_value=mock_instance), \
patch("llm.ChatBedrock", return_value=mock_instance), \
patch.dict(os.environ, {"LLM_PROVIDER": provider}, clear=True):
result = create_model()
assert isinstance(result, BaseChatModel)
# ── Property 2: Model name resolution ────────────────────────────────────────
class TestProperty2ModelNameResolution:
"""Feature: llm-provider-abstraction, Property 2: Model name resolution
For any provider × model name string, the model uses that name.
Without MODEL_NAME, uses default from DEFAULT_MODELS.
**Validates: Requirements 2.3, 2.4**
"""
@settings(max_examples=10)
@given(provider=registered_providers, model_name=model_name_strategy)
def test_custom_model_name_is_used(self, provider, model_name):
"""For any provider and model name, the model is configured with that name."""
mock_instance = MagicMock(spec=BaseChatModel)
with patch("llm.ChatOpenAI", return_value=mock_instance) as mock_openai, \
patch("llm.ChatBedrock", return_value=mock_instance) as mock_bedrock, \
patch.dict(os.environ, {"LLM_PROVIDER": provider, "MODEL_NAME": model_name}, clear=True):
create_model()
if provider in ("openai", "llama-server"):
mock_openai.assert_called_once()
_, kwargs = mock_openai.call_args
assert kwargs["model"] == model_name
else:
mock_bedrock.assert_called_once()
_, kwargs = mock_bedrock.call_args
assert kwargs["model_id"] == model_name
@settings(max_examples=10)
@given(provider=registered_providers)
def test_default_model_name_when_not_set(self, provider):
"""Without MODEL_NAME, uses default from DEFAULT_MODELS."""
mock_instance = MagicMock(spec=BaseChatModel)
expected_default = DEFAULT_MODELS[provider]
with patch("llm.ChatOpenAI", return_value=mock_instance) as mock_openai, \
patch("llm.ChatBedrock", return_value=mock_instance) as mock_bedrock, \
patch.dict(os.environ, {"LLM_PROVIDER": provider}, clear=True):
create_model()
if provider in ("openai", "llama-server"):
mock_openai.assert_called_once()
_, kwargs = mock_openai.call_args
assert kwargs["model"] == expected_default
else:
mock_bedrock.assert_called_once()
_, kwargs = mock_bedrock.call_args
assert kwargs["model_id"] == expected_default
# ── Property 3: Unknown provider error message ───────────────────────────────
class TestProperty3UnknownProviderErrorMessage:
"""Feature: llm-provider-abstraction, Property 3: Unknown provider error message
For any string NOT in PROVIDER_REGISTRY, ValueError contains the invalid
name and all valid provider names.
**Validates: Requirements 2.5, 8.1**
"""
@settings(max_examples=10)
@given(invalid_provider=unknown_provider_strategy)
def test_unknown_provider_raises_valueerror_with_details(self, invalid_provider):
"""For any non-registry string, ValueError contains invalid name and all valid names."""
with patch.dict(os.environ, {"LLM_PROVIDER": invalid_provider}, clear=True):
with pytest.raises(ValueError) as exc_info:
create_model()
error_msg = str(exc_info.value)
# Error message should contain the invalid provider name
assert invalid_provider in error_msg
# Error message should contain all valid provider names
for valid_name in PROVIDER_REGISTRY.keys():
assert valid_name in error_msg
# ── Property 4: Llama server URL configuration ───────────────────────────────
class TestProperty4LlamaServerUrlConfiguration:
"""Feature: llm-provider-abstraction, Property 4: Llama server URL configuration
For any URL string in LLAMA_SERVER_URL, the ChatOpenAI instance gets
that base_url.
**Validates: Requirements 4.2**
"""
@settings(max_examples=10)
@given(url=non_empty_text)
def test_llama_server_uses_configured_url(self, url):
"""For any URL string in LLAMA_SERVER_URL, model base_url matches."""
mock_instance = MagicMock(spec=BaseChatModel)
with patch("llm.ChatOpenAI", return_value=mock_instance) as mock_openai, \
patch.dict(os.environ, {"LLM_PROVIDER": "llama-server", "LLAMA_SERVER_URL": url}, clear=True):
create_model()
mock_openai.assert_called_once()
_, kwargs = mock_openai.call_args
assert kwargs["base_url"] == url
# ── Property 5: Bedrock region configuration ─────────────────────────────────
class TestProperty5BedrockRegionConfiguration:
"""Feature: llm-provider-abstraction, Property 5: Bedrock region configuration
For any region string in AWS_REGION, ChatBedrock gets that region.
**Validates: Requirements 5.4**
"""
@settings(max_examples=10)
@given(region=non_empty_text)
def test_bedrock_uses_configured_region(self, region):
"""For any region string in AWS_REGION, model uses that region."""
mock_instance = MagicMock(spec=BaseChatModel)
with patch("llm.ChatBedrock", return_value=mock_instance) as mock_bedrock, \
patch.dict(os.environ, {"LLM_PROVIDER": "bedrock", "AWS_REGION": region}, clear=True):
create_model()
mock_bedrock.assert_called_once()
_, kwargs = mock_bedrock.call_args
assert kwargs["region_name"] == region
# ── Property 6: Factory exception propagation ────────────────────────────────
class TestProperty6FactoryExceptionPropagation:
"""Feature: llm-provider-abstraction, Property 6: Factory exception propagation
For any exception raised by a factory, create_model() propagates it unchanged.
**Validates: Requirements 8.2**
"""
@settings(max_examples=10)
@given(
provider=registered_providers,
error_msg=st.text(min_size=1, max_size=100).filter(lambda s: s.strip() != ""),
)
def test_factory_exception_propagates_unchanged(self, provider, error_msg):
"""For any exception from factory, it propagates unchanged."""
original_exception = RuntimeError(error_msg)
# Patch the factory in the registry to raise the exception
with patch.dict(PROVIDER_REGISTRY, {provider: MagicMock(side_effect=original_exception)}), \
patch.dict(os.environ, {"LLM_PROVIDER": provider}, clear=True):
with pytest.raises(RuntimeError) as exc_info:
create_model()
# Verify the exact same exception propagated
assert exc_info.value is original_exception
assert str(exc_info.value) == error_msg

475
tests/test_properties.py Normal file
View File

@@ -0,0 +1,475 @@
"""Property-based tests for LangGraph agent file system tools.
Uses hypothesis to verify universal properties across many generated inputs.
"""
import subprocess
import sys
import tempfile
from pathlib import Path
import pytest
from hypothesis import given, settings, strategies as st, assume
import tools
# ── Helpers ──────────────────────────────────────────────────────────────────
def _set_workdir(path: Path):
"""Set tools.WORKDIR to the given path for testing."""
tools.set_workdir(path.resolve())
# Strategy for safe filenames (no path separators, no null bytes, non-empty)
safe_filename = st.text(
alphabet=st.characters(
whitelist_categories=("L", "N", "Pd"),
whitelist_characters="_",
),
min_size=1,
max_size=20,
).filter(lambda s: s.strip() != "" and s not in (".", ".."))
# Strategy for nested directory segments
safe_dir_segment = st.text(
alphabet=st.characters(
whitelist_categories=("L", "N"),
whitelist_characters="_",
),
min_size=1,
max_size=10,
).filter(lambda s: s.strip() != "" and s not in (".", ".."))
# ── Property 1: Write-Read Round Trip ────────────────────────────────────────
class TestProperty1WriteReadRoundTrip:
"""Feature: langgraph-agent, Property 1: Write-Read Round Trip
**Validates: Requirements 2.1, 4.1, 4.3**
"""
@settings(max_examples=100)
@given(content=st.text(alphabet=st.characters(blacklist_characters="\r", blacklist_categories=("Cs",))))
def test_write_then_read_returns_identical_content(self, content):
"""For any content, write_file then read_file returns identical content."""
with tempfile.TemporaryDirectory() as td:
_set_workdir(Path(td))
result = tools.write_file.invoke({"path": "test.txt", "content": content})
assert "Successfully wrote" in result
read_result = tools.read_file.invoke({"path": "test.txt"})
assert read_result == content
# ── Property 2: Line Range Slicing ──────────────────────────────────────────
class TestProperty2LineRangeSlicing:
"""Feature: langgraph-agent, Property 2: Line Range Slicing
**Validates: Requirements 2.2, 2.4**
"""
@settings(max_examples=100)
@given(
lines=st.lists(
st.text(
alphabet=st.characters(blacklist_categories=("Cc", "Cs"), blacklist_characters="\r\n\x0b\x0c\x1c\x1d\x1e\x1f\x85"),
min_size=0,
max_size=50,
),
min_size=1,
max_size=30,
),
start_line=st.integers(min_value=-5, max_value=50),
end_line=st.integers(min_value=-5, max_value=50),
)
def test_line_range_returns_correct_slice(self, lines, start_line, end_line):
"""read_file with line range returns the correct slice of lines."""
with tempfile.TemporaryDirectory() as td:
tmp_path = Path(td)
_set_workdir(tmp_path)
content = "\n".join(lines)
tools.write_file.invoke({"path": "lines.txt", "content": content})
result = tools.read_file.invoke(
{"path": "lines.txt", "start_line": start_line, "end_line": end_line}
)
# Compute expected slice using the same logic as the implementation:
# splitlines(keepends=True) then slice [max(0, start-1) : min(N, end)]
all_lines = content.splitlines(keepends=True)
n = len(all_lines)
if n == 0:
assert result == content
else:
s_idx = max(0, start_line - 1)
e_idx = min(n, end_line)
expected = "".join(all_lines[s_idx:e_idx])
assert result == expected
# ── Property 3: Read Non-Existent File Returns Error ────────────────────────
class TestProperty3ReadNonExistentFile:
"""Feature: langgraph-agent, Property 3: Read Non-Existent File Returns Error
**Validates: Requirements 2.3**
"""
@settings(max_examples=100)
@given(filename=safe_filename)
def test_read_nonexistent_file_returns_error_string(self, filename):
"""For any non-existent file path, read_file returns an error string."""
with tempfile.TemporaryDirectory() as td:
tmp_path = Path(td)
_set_workdir(tmp_path)
# Ensure the file does not exist
target = tmp_path / filename
if target.exists():
target.unlink()
result = tools.read_file.invoke({"path": filename})
# Should return error string, not raise exception
assert isinstance(result, str)
assert "Error" in result
# ── Property 4: Grep Finds All Matches with Correct Format ──────────────────
class TestProperty4GrepFindsAllMatches:
"""Feature: langgraph-agent, Property 4: Grep Finds All Matches with Correct Format
**Validates: Requirements 3.1, 3.2, 3.4**
"""
@settings(max_examples=100)
@given(
pattern=st.text(
alphabet=st.characters(blacklist_categories=("Cc", "Cs"), blacklist_characters="\r\n\x0b\x0c\x1c\x1d\x1e\x1f\x85"),
min_size=1,
max_size=10,
).filter(lambda s: s.strip() != ""),
file_lines=st.lists(
st.text(
alphabet=st.characters(blacklist_categories=("Cc", "Cs"), blacklist_characters="\r\n\x0b\x0c\x1c\x1d\x1e\x1f\x85"),
min_size=0,
max_size=50,
),
min_size=1,
max_size=20,
),
)
def test_grep_finds_all_matches_with_correct_format(self, pattern, file_lines):
"""grep returns all lines containing the pattern with correct format."""
with tempfile.TemporaryDirectory() as td:
tmp_path = Path(td)
_set_workdir(tmp_path)
# Write test file
content = "\n".join(file_lines)
(tmp_path / "search.txt").write_text(content)
result = tools.grep.invoke({"pattern": pattern, "path": "."})
# Find expected matches
expected_matches = []
for line_num, line in enumerate(file_lines, start=1):
if pattern in line:
expected_matches.append((line_num, line))
if not expected_matches:
assert "No matches found" in result
else:
# Each match should appear in the result with correct format
for line_num, line in expected_matches:
# Format: {file_path}:{line_number}: {line_content}
assert f":{line_num}: {line}" in result
# Verify file path is included
assert "search.txt" in result
# ── Property 5: Write Creates Parent Directories ────────────────────────────
class TestProperty5WriteCreatesParentDirs:
"""Feature: langgraph-agent, Property 5: Write Creates Parent Directories
**Validates: Requirements 4.2**
"""
@settings(max_examples=100)
@given(
segments=st.lists(safe_dir_segment, min_size=1, max_size=4),
filename=safe_filename,
content=st.text(alphabet=st.characters(blacklist_characters="\r", blacklist_categories=("Cs",)), max_size=100),
)
def test_write_creates_parent_directories(self, segments, filename, content):
"""write_file creates all necessary parent directories."""
with tempfile.TemporaryDirectory() as td:
tmp_path = Path(td)
_set_workdir(tmp_path)
nested_path = "/".join(segments) + "/" + filename
result = tools.write_file.invoke({"path": nested_path, "content": content})
assert "Successfully wrote" in result
# Verify all parent directories were created
full_path = tmp_path / Path(nested_path)
assert full_path.exists()
assert full_path.read_text() == content
# ── Property 6: Write Returns Confirmation with Path ────────────────────────
class TestProperty6WriteReturnsConfirmation:
"""Feature: langgraph-agent, Property 6: Write Returns Confirmation with Path
**Validates: Requirements 4.4**
"""
@settings(max_examples=100)
@given(
filename=safe_filename,
content=st.text(alphabet=st.characters(blacklist_characters="\r", blacklist_categories=("Cs",)), max_size=100),
)
def test_write_returns_confirmation_containing_path(self, filename, content):
"""write_file return value contains the file path that was written."""
with tempfile.TemporaryDirectory() as td:
tmp_path = Path(td)
_set_workdir(tmp_path)
result = tools.write_file.invoke({"path": filename, "content": content})
assert isinstance(result, str)
assert filename in result
# ── Property 7: List Directory Completeness and Format ──────────────────────
class TestProperty7ListDirCompleteness:
"""Feature: langgraph-agent, Property 7: List Directory Completeness and Format
**Validates: Requirements 5.1, 5.2**
"""
@settings(max_examples=100)
@given(
file_names=st.lists(safe_filename, min_size=0, max_size=5, unique=True),
dir_names=st.lists(safe_dir_segment, min_size=0, max_size=5, unique=True),
)
def test_list_dir_returns_all_entries_with_correct_format(
self, file_names, dir_names
):
"""list_dir returns all entries with [FILE] or [DIR] prefix."""
with tempfile.TemporaryDirectory() as td:
tmp_path = Path(td)
_set_workdir(tmp_path)
# Ensure no overlap between file and dir names
dir_names = [d for d in dir_names if d not in file_names]
# Create files
for fname in file_names:
(tmp_path / fname).write_text("content")
# Create directories
for dname in dir_names:
(tmp_path / dname).mkdir(exist_ok=True)
result = tools.list_dir.invoke({"path": "."})
# Verify all files are listed with [FILE] prefix
for fname in file_names:
assert f"[FILE] {fname}" in result
# Verify all directories are listed with [DIR] prefix
for dname in dir_names:
assert f"[DIR] {dname}" in result
# ── Property 8: List Directory Error Handling ───────────────────────────────
class TestProperty8ListDirErrorHandling:
"""Feature: langgraph-agent, Property 8: List Directory Error Handling
**Validates: Requirements 5.3, 5.4**
"""
@settings(max_examples=100)
@given(filename=safe_filename)
def test_list_nonexistent_path_returns_error(self, filename):
"""list_dir on non-existent path returns error message."""
with tempfile.TemporaryDirectory() as td:
tmp_path = Path(td)
_set_workdir(tmp_path)
# Ensure path doesn't exist
target = tmp_path / filename
if target.exists():
if target.is_dir():
target.rmdir()
else:
target.unlink()
result = tools.list_dir.invoke({"path": filename})
assert isinstance(result, str)
assert "Error" in result
@settings(max_examples=100)
@given(filename=safe_filename)
def test_list_file_path_returns_error(self, filename):
"""list_dir on a file (not directory) returns error message."""
with tempfile.TemporaryDirectory() as td:
tmp_path = Path(td)
_set_workdir(tmp_path)
# Create a file
(tmp_path / filename).write_text("I am a file")
result = tools.list_dir.invoke({"path": filename})
assert isinstance(result, str)
assert "Error" in result
assert "Not a directory" in result
# ── Property 10: Workdir Path Containment ───────────────────────────────────
class TestProperty10WorkdirPathContainment:
"""Feature: langgraph-agent, Property 10: Workdir Path Containment
**Validates: Requirements 8.5, 8.6, 8.7**
"""
@settings(max_examples=100)
@given(
segments=st.lists(
st.sampled_from(["a", "b", "..", "subdir", "x"]),
min_size=1,
max_size=6,
)
)
def test_dot_dot_traversal_outside_workdir_rejected(self, segments):
"""Paths with .. traversal that resolve outside workdir are rejected."""
with tempfile.TemporaryDirectory() as td:
tmp_path = Path(td)
_set_workdir(tmp_path)
path = "/".join(segments) + "/file.txt"
# Determine if the resolved path would be inside or outside workdir
candidate = (tmp_path / path).resolve()
workdir_resolved = tmp_path.resolve()
try:
candidate.relative_to(workdir_resolved)
is_inside = True
except ValueError:
is_inside = False
if is_inside:
# Path is inside workdir — validate_path should succeed
result = tools.validate_path(path)
assert result == str(candidate)
else:
# Path escapes workdir — validate_path should reject
with pytest.raises(ValueError, match="Access denied"):
tools.validate_path(path)
@settings(max_examples=100)
@given(
abs_path=st.sampled_from([
"/etc/passwd",
"/tmp/evil.txt",
"/usr/bin/python",
"/var/log/syslog",
])
)
def test_absolute_paths_outside_workdir_rejected(self, abs_path):
"""Absolute paths outside workdir are rejected."""
with tempfile.TemporaryDirectory() as td:
tmp_path = Path(td)
_set_workdir(tmp_path)
with pytest.raises(ValueError, match="Access denied"):
tools.validate_path(abs_path)
def test_symlink_escaping_workdir_rejected(self, tmp_path):
"""Symlinks that resolve outside workdir are rejected."""
_set_workdir(tmp_path)
# Create a directory outside workdir
outside = tmp_path.parent / "outside_target"
outside.mkdir(exist_ok=True)
(outside / "secret.txt").write_text("secret data")
# Create symlink inside workdir pointing outside
link = tmp_path / "escape_link"
link.symlink_to(outside)
with pytest.raises(ValueError, match="Access denied"):
tools.validate_path("escape_link/secret.txt")
# ── Property 11: Workdir Validation on Startup ──────────────────────────────
class TestProperty11WorkdirValidationOnStartup:
"""Feature: langgraph-agent, Property 11: Workdir Validation on Startup
**Validates: Requirements 8.2, 8.3, 8.4**
"""
def test_missing_workdir_exits_with_error(self):
"""Missing --workdir causes exit with error."""
result = subprocess.run(
[sys.executable, "main.py"],
capture_output=True,
text=True,
)
assert result.returncode != 0
assert "--workdir argument is required" in result.stderr
def test_nonexistent_workdir_exits_with_error(self, tmp_path):
"""Non-existent --workdir path causes exit with error."""
nonexistent = tmp_path / "does_not_exist"
result = subprocess.run(
[sys.executable, "main.py", "--workdir", str(nonexistent)],
capture_output=True,
text=True,
)
assert result.returncode != 0
assert "Workdir does not exist" in result.stderr
def test_workdir_is_file_exits_with_error(self, tmp_path):
"""--workdir pointing to a file (not directory) causes exit with error."""
file_path = tmp_path / "not_a_dir.txt"
file_path.write_text("I am a file")
result = subprocess.run(
[sys.executable, "main.py", "--workdir", str(file_path)],
capture_output=True,
text=True,
)
assert result.returncode != 0
assert "Workdir is not a directory" in result.stderr
@settings(max_examples=100, deadline=None)
@given(dirname=safe_dir_segment)
def test_invalid_workdir_paths_exit_with_error(self, dirname):
"""Any non-existent workdir path causes exit with error."""
with tempfile.TemporaryDirectory() as td:
nonexistent = Path(td) / dirname / "nested" / "deep"
# Ensure it doesn't exist
assume(not nonexistent.exists())
result = subprocess.run(
[sys.executable, "main.py", "--workdir", str(nonexistent)],
capture_output=True,
text=True,
)
assert result.returncode != 0
assert "Error" in result.stderr

237
tests/test_tools.py Normal file
View File

@@ -0,0 +1,237 @@
"""Unit tests for file system tools and validate_path."""
import os
from pathlib import Path
import tools
# ── Helpers ──────────────────────────────────────────────────────────────────
def _set_workdir(tmp_path: Path):
"""Set tools.WORKDIR to the given tmp_path for testing."""
tools.set_workdir(tmp_path.resolve())
# ── 6.1 validate_path ──────────────────────────────────────────────────────
class TestValidatePath:
def test_valid_relative_path(self, tmp_path):
_set_workdir(tmp_path)
(tmp_path / "hello.txt").write_text("hi")
result = tools.validate_path("hello.txt")
assert result == str(tmp_path.resolve() / "hello.txt")
def test_valid_nested_path(self, tmp_path):
_set_workdir(tmp_path)
sub = tmp_path / "a" / "b"
sub.mkdir(parents=True)
(sub / "file.txt").write_text("data")
result = tools.validate_path("a/b/file.txt")
assert result == str(sub.resolve() / "file.txt")
def test_dot_dot_traversal_rejected(self, tmp_path):
_set_workdir(tmp_path)
import pytest
with pytest.raises(ValueError, match="Access denied"):
tools.validate_path("../outside.txt")
def test_absolute_path_outside_workdir(self, tmp_path):
_set_workdir(tmp_path)
import pytest
with pytest.raises(ValueError, match="Access denied"):
tools.validate_path("/etc/passwd")
def test_symlink_escaping_workdir(self, tmp_path):
_set_workdir(tmp_path)
# Create a directory outside workdir
outside = tmp_path.parent / "outside_dir"
outside.mkdir(exist_ok=True)
(outside / "secret.txt").write_text("secret")
# Create symlink inside workdir pointing outside
link = tmp_path / "escape_link"
link.symlink_to(outside)
import pytest
with pytest.raises(ValueError, match="Access denied"):
tools.validate_path("escape_link/secret.txt")
def test_absolute_path_inside_workdir(self, tmp_path):
_set_workdir(tmp_path)
(tmp_path / "inside.txt").write_text("ok")
abs_path = str(tmp_path / "inside.txt")
result = tools.validate_path(abs_path)
assert result == str((tmp_path / "inside.txt").resolve())
# ── 6.3 read_file ──────────────────────────────────────────────────────────
class TestReadFile:
def test_read_existing_file(self, tmp_path):
_set_workdir(tmp_path)
(tmp_path / "test.txt").write_text("hello world")
result = tools.read_file.invoke({"path": "test.txt"})
assert result == "hello world"
def test_read_missing_file(self, tmp_path):
_set_workdir(tmp_path)
result = tools.read_file.invoke({"path": "nonexistent.txt"})
assert "Error: File not found" in result
def test_read_empty_file(self, tmp_path):
_set_workdir(tmp_path)
(tmp_path / "empty.txt").write_text("")
result = tools.read_file.invoke({"path": "empty.txt"})
assert result == ""
def test_read_file_outside_workdir(self, tmp_path):
_set_workdir(tmp_path)
result = tools.read_file.invoke({"path": "../outside.txt"})
assert "Access denied" in result
# ── 6.4 grep ────────────────────────────────────────────────────────────────
class TestGrep:
def test_matches_found(self, tmp_path):
_set_workdir(tmp_path)
(tmp_path / "data.txt").write_text("foo bar\nbaz\nfoo again")
result = tools.grep.invoke({"pattern": "foo"})
assert "data.txt" in result
assert "foo bar" in result
assert "foo again" in result
def test_no_matches(self, tmp_path):
_set_workdir(tmp_path)
(tmp_path / "data.txt").write_text("hello world")
result = tools.grep.invoke({"pattern": "zzz_missing"})
assert "No matches found" in result
def test_search_specific_directory(self, tmp_path):
_set_workdir(tmp_path)
sub = tmp_path / "subdir"
sub.mkdir()
(sub / "a.txt").write_text("needle here")
(tmp_path / "b.txt").write_text("needle there")
result = tools.grep.invoke({"pattern": "needle", "path": "subdir"})
assert "a.txt" in result
# b.txt is outside the searched subdir
assert "b.txt" not in result
def test_grep_path_outside_workdir(self, tmp_path):
_set_workdir(tmp_path)
result = tools.grep.invoke({"pattern": "x", "path": "../../etc"})
assert "Access denied" in result
# ── 6.5 write_file ─────────────────────────────────────────────────────────
class TestWriteFile:
def test_write_new_file(self, tmp_path):
_set_workdir(tmp_path)
result = tools.write_file.invoke({"path": "new.txt", "content": "hello"})
assert "Successfully wrote" in result
assert (tmp_path / "new.txt").read_text() == "hello"
def test_overwrite_existing_file(self, tmp_path):
_set_workdir(tmp_path)
(tmp_path / "exist.txt").write_text("old")
result = tools.write_file.invoke({"path": "exist.txt", "content": "new"})
assert "Successfully wrote" in result
assert (tmp_path / "exist.txt").read_text() == "new"
def test_write_creates_nested_dirs(self, tmp_path):
_set_workdir(tmp_path)
result = tools.write_file.invoke(
{"path": "a/b/c/deep.txt", "content": "deep"}
)
assert "Successfully wrote" in result
assert (tmp_path / "a" / "b" / "c" / "deep.txt").read_text() == "deep"
def test_write_path_outside_workdir(self, tmp_path):
_set_workdir(tmp_path)
result = tools.write_file.invoke(
{"path": "../../evil.txt", "content": "bad"}
)
assert "Access denied" in result
# ── 6.6 list_dir ───────────────────────────────────────────────────────────
class TestListDir:
def test_list_valid_directory(self, tmp_path):
_set_workdir(tmp_path)
(tmp_path / "file.txt").write_text("x")
(tmp_path / "subdir").mkdir()
result = tools.list_dir.invoke({"path": "."})
assert "[FILE] file.txt" in result
assert "[DIR] subdir" in result
def test_list_missing_path(self, tmp_path):
_set_workdir(tmp_path)
result = tools.list_dir.invoke({"path": "nonexistent"})
assert "Error: Path not found" in result
def test_list_file_path(self, tmp_path):
_set_workdir(tmp_path)
(tmp_path / "afile.txt").write_text("x")
result = tools.list_dir.invoke({"path": "afile.txt"})
assert "Error: Not a directory" in result
def test_list_path_outside_workdir(self, tmp_path):
_set_workdir(tmp_path)
result = tools.list_dir.invoke({"path": "../../"})
assert "Access denied" in result
# ── 6.8 replace_in_file ────────────────────────────────────────────────────
class TestReplaceInFile:
def test_replace_single_occurrence(self, tmp_path):
_set_workdir(tmp_path)
(tmp_path / "test.txt").write_text("hello world")
result = tools.replace_in_file.invoke(
{"path": "test.txt", "search": "world", "replace": "universe"}
)
assert "Successfully replaced 1 occurrence" in result
assert (tmp_path / "test.txt").read_text() == "hello universe"
def test_replace_multiple_occurrences(self, tmp_path):
_set_workdir(tmp_path)
(tmp_path / "test.txt").write_text("foo bar foo baz foo")
result = tools.replace_in_file.invoke(
{"path": "test.txt", "search": "foo", "replace": "qux"}
)
assert "Successfully replaced 3 occurrence" in result
assert (tmp_path / "test.txt").read_text() == "qux bar qux baz qux"
def test_replace_not_found(self, tmp_path):
_set_workdir(tmp_path)
(tmp_path / "test.txt").write_text("hello world")
result = tools.replace_in_file.invoke(
{"path": "test.txt", "search": "missing", "replace": "new"}
)
assert "Error: Search text not found" in result
def test_replace_missing_file(self, tmp_path):
_set_workdir(tmp_path)
result = tools.replace_in_file.invoke(
{"path": "nonexistent.txt", "search": "a", "replace": "b"}
)
assert "Error: File not found" in result
def test_replace_path_outside_workdir(self, tmp_path):
_set_workdir(tmp_path)
result = tools.replace_in_file.invoke(
{"path": "../outside.txt", "search": "a", "replace": "b"}
)
assert "Access denied" in result
def test_replace_on_directory(self, tmp_path):
_set_workdir(tmp_path)
(tmp_path / "subdir").mkdir()
result = tools.replace_in_file.invoke(
{"path": "subdir", "search": "a", "replace": "b"}
)
assert "Error: Not a file" in result

261
tools.py Normal file
View File

@@ -0,0 +1,261 @@
"""File system tools for the LangGraph agent."""
from pathlib import Path
from langchain_core.tools import tool
# Module-level WORKDIR variable, set by main.py during CLI parsing
WORKDIR: Path | None = None
def set_workdir(path: Path) -> None:
"""Set the workdir for all tools."""
global WORKDIR
WORKDIR = path
def get_workdir() -> Path | None:
"""Get the current workdir."""
return WORKDIR
def validate_path(path: str) -> str:
"""Resolve path against WORKDIR and reject paths outside the boundary.
Args:
path: A relative or absolute file path.
Returns:
The resolved absolute path string.
Raises:
ValueError: If the resolved path is outside the workdir.
"""
if WORKDIR is None:
raise RuntimeError("WORKDIR is not set")
candidate = Path(path)
if not candidate.is_absolute():
candidate = WORKDIR / candidate
resolved = candidate.resolve()
try:
resolved.relative_to(WORKDIR.resolve())
except ValueError:
raise ValueError(
f"Error: Access denied — path is outside the workdir: {path}"
)
return str(resolved)
@tool
def read_file(
path: str, start_line: int | None = None, end_line: int | None = None
) -> str:
"""Read a file and return its contents.
Args:
path: Path to the file to read.
start_line: Optional 1-indexed start line (inclusive).
end_line: Optional 1-indexed end line (inclusive).
Returns:
The file contents, optionally filtered to the specified line range.
Returns an error string if the file doesn't exist or path is outside workdir.
"""
try:
resolved = validate_path(path)
except ValueError as e:
return str(e)
resolved_path = Path(resolved)
if not resolved_path.exists():
return f"Error: File not found: {path}"
try:
content = resolved_path.read_text()
except PermissionError:
return f"Error: Permission denied: {path}"
if start_line is None and end_line is None:
return content
lines = content.splitlines(keepends=True)
total_lines = len(lines)
if total_lines == 0:
return content
if start_line is None:
start_idx = 0
else:
start_idx = max(0, start_line - 1)
if end_line is None:
end_idx = total_lines
else:
end_idx = min(total_lines, end_line)
return "".join(lines[start_idx:end_idx])
@tool
def grep(pattern: str, path: str = ".") -> str:
"""Search for a pattern in files under the given path.
Args:
pattern: The substring pattern to search for.
path: Directory or file path to search in (default: current directory).
Returns:
Matching lines formatted as {file_path}:{line_number}: {line_content}.
Returns a descriptive message if no matches found.
Returns an error string if path is outside workdir or doesn't exist.
"""
try:
resolved = validate_path(path)
except ValueError as e:
return str(e)
resolved_path = Path(resolved)
if not resolved_path.exists():
return f"Error: Path not found: {path}"
results = []
if resolved_path.is_file():
files_to_search = [resolved_path]
else:
files_to_search = [f for f in resolved_path.rglob("*") if f.is_file()]
for file_path in files_to_search:
try:
content = file_path.read_text()
except (PermissionError, UnicodeDecodeError):
continue
for line_num, line in enumerate(content.splitlines(), start=1):
if pattern in line:
try:
display_path = file_path.relative_to(WORKDIR)
except ValueError:
display_path = file_path
results.append(f"{display_path}:{line_num}: {line}")
if not results:
return f"No matches found for pattern: {pattern}"
return "\n".join(results)
@tool
def write_file(path: str, content: str) -> str:
"""Write content to a file.
Args:
path: Path to the file to write.
content: Content to write to the file.
Returns:
A confirmation message with the file path on success.
Returns an error string if path is outside workdir or permission denied.
"""
try:
resolved = validate_path(path)
except ValueError as e:
return str(e)
resolved_path = Path(resolved)
resolved_path.parent.mkdir(parents=True, exist_ok=True)
try:
resolved_path.write_text(content)
except PermissionError:
return f"Error: Permission denied: {path}"
return f"Successfully wrote to {path}"
@tool
def list_dir(path: str = ".") -> str:
"""List entries in a directory.
Args:
path: Path to the directory to list (default: current directory).
Returns:
A formatted list of entries with [FILE] or [DIR] prefix.
Returns an error string if path doesn't exist, isn't a directory,
or is outside workdir.
"""
try:
resolved = validate_path(path)
except ValueError as e:
return str(e)
resolved_path = Path(resolved)
if not resolved_path.exists():
return f"Error: Path not found: {path}"
if not resolved_path.is_dir():
return f"Error: Not a directory: {path}"
entries = []
for entry in sorted(resolved_path.iterdir()):
if entry.is_dir():
entries.append(f"[DIR] {entry.name}")
else:
entries.append(f"[FILE] {entry.name}")
return "\n".join(entries)
@tool
def replace_in_file(path: str, search: str, replace: str) -> str:
"""Search for text in a file and replace first occurance with new text.
Args:
path: Path to the file to modify.
search: The text to search for.
replace: The text to replace it with.
Returns:
A confirmation message with the number of replacements made.
Returns an error string if file doesn't exist, path is outside workdir,
or the search text is not found.
"""
try:
resolved = validate_path(path)
except ValueError as e:
return str(e)
resolved_path = Path(resolved)
if not resolved_path.exists():
return f"Error: File not found: {path}"
if not resolved_path.is_file():
return f"Error: Not a file: {path}"
try:
content = resolved_path.read_text()
except PermissionError:
return f"Error: Permission denied: {path}"
if search not in content:
return f"Error: Search text not found in {path}"
count = content.count(search)
new_content = content.replace(search, replace)
try:
resolved_path.write_text(new_content)
except PermissionError:
return f"Error: Permission denied: {path}"
return f"Successfully replaced {count} occurrence(s) in {path}"

1275
uv.lock generated Normal file

File diff suppressed because it is too large Load Diff