init commit

This commit is contained in:
2026-03-11 07:21:21 -05:00
commit 5aff2183d6
29 changed files with 2270 additions and 0 deletions

15
app/models/__init__.py Normal file
View File

@@ -0,0 +1,15 @@
"""SneakyCode data models."""
from app.models.config import AppConfig, load_config
from app.models.message import Message
from app.models.tool_call import ToolCall, ToolCallFunction, ToolResult, ToolResultStatus
__all__ = [
"AppConfig",
"load_config",
"Message",
"ToolCall",
"ToolCallFunction",
"ToolResult",
"ToolResultStatus",
]

127
app/models/config.py Normal file
View File

@@ -0,0 +1,127 @@
"""Pydantic configuration models mapping to config/config.yaml."""
import os
from pathlib import Path
import yaml
from pydantic import BaseModel, Field, model_validator
class LLMConfig(BaseModel):
"""LLM backend configuration."""
model: str = Field(description="Model name to use")
endpoint: str = Field(description="Base URL of the LLM API")
api_path: str = Field(default="/v1/chat/completions", description="API endpoint path")
temperature: float = Field(default=0.1, description="Sampling temperature")
max_tokens: int = Field(default=4096, description="Maximum tokens in LLM response")
timeout: int = Field(default=120, description="Request timeout in seconds")
class AgentConfig(BaseModel):
"""Agent loop configuration."""
max_iterations: int = Field(default=25, description="Maximum tool-call loop iterations")
max_conversation_tokens: int = Field(
default=32000, description="Token budget for conversation history"
)
workspace_root: Path = Field(
default=Path("."), description="Root directory for file operations"
)
class PermissionsConfig(BaseModel):
"""Tool permission tiers."""
auto_approve: list[str] = Field(default_factory=list, description="Auto-approved tools")
prompt_user: list[str] = Field(default_factory=list, description="Tools requiring confirmation")
deny: list[str] = Field(default_factory=list, description="Tools that are blocked entirely")
class ShellToolConfig(BaseModel):
"""Shell tool restrictions."""
allowed_commands: list[str] = Field(default_factory=list, description="Allowed shell commands")
denied_commands: list[str] = Field(default_factory=list, description="Blocked shell commands")
max_output_bytes: int = Field(default=65536, description="Max output capture size in bytes")
class FilesystemToolConfig(BaseModel):
"""Filesystem tool limits."""
max_file_size_bytes: int = Field(default=1_048_576, description="Max file size for read/write")
binary_detection: bool = Field(default=True, description="Detect and reject binary files")
class ToolsConfig(BaseModel):
"""Aggregate tool configuration."""
shell: ShellToolConfig = Field(default_factory=ShellToolConfig)
filesystem: FilesystemToolConfig = Field(default_factory=FilesystemToolConfig)
class DisplayConfig(BaseModel):
"""Terminal display preferences."""
show_tool_calls: bool = Field(default=True, description="Show tool call details in output")
show_token_usage: bool = Field(default=True, description="Show token usage stats")
stream_output: bool = Field(default=True, description="Stream LLM output to terminal")
class AppConfig(BaseModel):
"""Top-level application configuration composing all sub-configs."""
llm: LLMConfig
agent: AgentConfig = Field(default_factory=AgentConfig)
permissions: PermissionsConfig = Field(default_factory=PermissionsConfig)
tools: ToolsConfig = Field(default_factory=ToolsConfig)
display: DisplayConfig = Field(default_factory=DisplayConfig)
@model_validator(mode="after")
def resolve_workspace_root(self) -> "AppConfig":
"""Resolve workspace_root to an absolute path."""
self.agent.workspace_root = self.agent.workspace_root.resolve()
return self
# Default config file location relative to project root
_DEFAULT_CONFIG_PATH = Path("config/config.yaml")
def load_config(config_path: Path | None = None) -> AppConfig:
"""Load and validate application config from YAML.
Resolution order:
1. Explicit config_path argument
2. SNEAKYCODE_CONFIG environment variable
3. config/config.yaml (default)
Args:
config_path: Optional explicit path to config file.
Returns:
Validated AppConfig instance.
Raises:
FileNotFoundError: If the resolved config file does not exist.
ValueError: If the config file is invalid YAML or fails validation.
"""
if config_path is None:
env_path = os.environ.get("SNEAKYCODE_CONFIG")
if env_path:
config_path = Path(env_path)
else:
config_path = _DEFAULT_CONFIG_PATH
config_path = config_path.resolve()
if not config_path.exists():
raise FileNotFoundError(f"Config file not found: {config_path}")
with open(config_path) as f:
raw = yaml.safe_load(f)
if not isinstance(raw, dict):
raise ValueError(f"Config file must contain a YAML mapping, got {type(raw).__name__}")
return AppConfig(**raw)

50
app/models/message.py Normal file
View File

@@ -0,0 +1,50 @@
"""Message schema for LLM conversation history."""
from typing import Any, Literal
from pydantic import BaseModel, Field
from app.models.tool_call import ToolCall
class Message(BaseModel):
"""A single message in the conversation history.
Follows the OpenAI chat completions message format with support for
system, user, assistant, and tool roles.
"""
role: Literal["system", "user", "assistant", "tool"] = Field(
description="Role of the message sender"
)
content: str | None = Field(default=None, description="Text content of the message")
tool_calls: list[ToolCall] | None = Field(
default=None, description="Tool calls made by the assistant"
)
tool_call_id: str | None = Field(
default=None, description="ID of the tool call this message responds to (role=tool)"
)
name: str | None = Field(
default=None, description="Name of the tool that produced this message (role=tool)"
)
def to_api_dict(self) -> dict[str, Any]:
"""Serialize to a dict suitable for the OpenAI-compatible API.
Strips None-valued fields to keep the payload clean.
"""
data: dict[str, Any] = {"role": self.role}
if self.content is not None:
data["content"] = self.content
if self.tool_calls is not None:
data["tool_calls"] = [tc.model_dump() for tc in self.tool_calls]
if self.tool_call_id is not None:
data["tool_call_id"] = self.tool_call_id
if self.name is not None:
data["name"] = self.name
return data

37
app/models/tool_call.py Normal file
View File

@@ -0,0 +1,37 @@
"""Tool call and result models following OpenAI function-calling spec."""
from enum import StrEnum
from pydantic import BaseModel, Field
class ToolCallFunction(BaseModel):
"""Function details within a tool call."""
name: str = Field(description="Name of the tool function to call")
arguments: str = Field(description="JSON-encoded string of function arguments")
class ToolCall(BaseModel):
"""A single tool call from the LLM, per OpenAI spec."""
id: str = Field(description="Unique identifier for this tool call")
type: str = Field(default="function", description="Type of tool call")
function: ToolCallFunction = Field(description="Function to invoke")
class ToolResultStatus(StrEnum):
"""Status of a tool execution result."""
SUCCESS = "success"
ERROR = "error"
class ToolResult(BaseModel):
"""Result of executing a tool call."""
tool_call_id: str = Field(description="ID of the tool call this result corresponds to")
tool_name: str = Field(description="Name of the tool that was executed")
status: ToolResultStatus = Field(description="Whether the tool execution succeeded or failed")
output: str = Field(default="", description="Tool output on success")
error: str | None = Field(default=None, description="Error message on failure")