Metadata-Version: 2.5
Name: huitzo-sdk
Version: 1.11.0
Summary: Huitzo SDK for building Intelligence Packs
Author-email: "Huitzo Inc." <ernesto@huitzo.ai>
License: Proprietary
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Python: >=3.11
Requires-Dist: cryptography>=50
Requires-Dist: packaging>=24
Requires-Dist: pydantic>=2.12
Requires-Dist: pyyaml>=6
Provides-Extra: dev
Requires-Dist: httpx>=0.28; extra == 'dev'
Requires-Dist: mypy>=1.19; extra == 'dev'
Requires-Dist: pytest-asyncio>=1.0; extra == 'dev'
Requires-Dist: pytest-cov>=7.0; extra == 'dev'
Requires-Dist: pytest>=9.0; extra == 'dev'
Requires-Dist: ruff>=0.14; extra == 'dev'
Requires-Dist: types-pyyaml>=6; extra == 'dev'
Provides-Extra: testing
Requires-Dist: pytest>=8.4; extra == 'testing'
Description-Content-Type: text/markdown

# Huitzo SDK

A Python framework for building modular command functions that integrate with the Huitzo platform.

## Features

- Simple command decorator for defining functions
- Built-in clients for LLM, Email, HTTP, Telegram, SSH, Database, and File operations
- Pluggable storage backends with namespace isolation
- Full async/await support with automatic sync function handling
- Type-safe with Pydantic validation
- Comprehensive error handling

## Installation

```bash
pip install huitzo-sdk
```

## Quick Start

### Defining a Command

```python
from pydantic import BaseModel
from huitzo_sdk import command, Context, Result

class GreetingArgs(BaseModel):
    name: str
    language: str = "en"

@command(
    name="greet",
    namespace="examples",
    version="1.0.0",
    description="Greet a user in their language"
)
async def greet_user(args: GreetingArgs, ctx: Context) -> Result:
    greetings = {"en": "Hello", "es": "Hola", "fr": "Bonjour"}
    greeting = greetings.get(args.language, "Hello")
    
    return {
        "message": f"{greeting}, {args.name}!",
        "user_id": str(ctx.user_id)
    }
```

### Using Built-in Integrations

```python
from pydantic import BaseModel
from huitzo_sdk import command, Context, Result

class WeatherArgs(BaseModel):
    city: str

@command(
    name="get_weather",
    namespace="weather",
    version="1.0.0",
)
async def get_weather(args: WeatherArgs, ctx: Context) -> Result:
    # Use built-in HTTP client
    response = await ctx.http.get(
        f"https://api.weather.com/v1/forecast?city={args.city}"
    )
    return response.json()
```

### Complete Example: Data Processing Pipeline

```python
from pydantic import BaseModel
from huitzo_sdk import command, Context, Result

class ProcessDataArgs(BaseModel):
    data_url: str
    recipient_email: str

@command(
    name="process_data",
    namespace="analytics",
    version="1.0.0",
    description="Fetch, analyze, and report on data"
)
async def process_data(args: ProcessDataArgs, ctx: Context) -> Result:
    # Fetch data from external API
    response = await ctx.http.get(args.data_url)
    data = response.json()
    
    # Store raw data
    await ctx.storage.set(f"raw_data:{str(ctx.session_id)}", data)
    
    # Analyze with LLM (limit data size to avoid token limits)
    data_summary = str(data)[:500]
    analysis = await ctx.llm.complete(
        prompt=f"Analyze this data and provide insights: {data_summary}",
        model="gpt-4"
    )
    
    # Send results via email
    await ctx.email.send(
        to=args.recipient_email,
        subject="Data Analysis Complete",
        body=f"Analysis Results:\n\n{analysis}"
    )
    
    return {
        "status": "complete",
        "session_id": str(ctx.session_id),
        "data_points": len(data)
    }
```

## Core Concepts

### Commands

Commands are functions decorated with `@command`. The decorator supports both sync and async functions.

Decorator parameters:
- `name`: Command identifier
- `namespace`: Organizational grouping
- `version`: Semantic version
- `timeout`: Maximum execution time in seconds (default: 60)
- `retries`: Number of retry attempts (default: 3)
- `description`: Optional command description

### Context

The `Context` object provides access to:
- Identity: `user_id`, `tenant_id`, `session_id`, `correlation_id`
- Metadata: `command_name`, `namespace`, `command_version`
- Integration Clients: `llm`, `email`, `http`, `telegram`, `ssh`, `db`, `files`
- Platform Services: `storage`, `secrets`, `log`, `cron`

```python
async def my_command(args: dict, ctx: Context) -> Result:
    # Access user identity
    user_id = ctx.user_id
    
    # Use integration clients
    completion = await ctx.llm.complete(
        prompt="Explain quantum computing",
        model="gpt-4"
    )
    
    # Send results via email
    await ctx.email.send(
        to="user@example.com",
        subject="Your Results",
        body=completion
    )
    
    return {"status": "sent"}
```

### Integration Clients

Built-in clients for external services:

- `LLMClient`: Language model completions and chat
- `EmailClient`: Send emails with templates
- `HTTPClient`: HTTP requests with security controls
- `TelegramClient`: Send messages and interact with Telegram
- `SSHClient`: Execute remote commands via SSH
- `DBClient`: Database operations with transaction support
- `FileClient`: File operations and storage

### Platform Services

Built-in platform utilities:

- `StorageClient`: Persistent key-value storage with namespace isolation
- `SecretsClient`: Secure credential management
- `LogClient`: Structured logging
- `CronClient`: Schedule recurring tasks

### Storage

Persistent storage with namespace isolation:

```python
from huitzo_sdk.storage import InMemoryBackend, StorageNamespace

# Create storage backend
backend = InMemoryBackend()
storage = StorageNamespace(backend=backend, namespace="my-app")

# Store and retrieve data
await storage.set("user:123", {"name": "Alice", "score": 100})
user_data = await storage.get("user:123")
```

### Error Handling

The SDK provides a comprehensive error hierarchy:

```python
from huitzo_sdk import (
    HuitzoError,
    ValidationError,
    CommandTimeoutError,
    IntegrationError,
    LLMError,
    HTTPError,
    StorageError
)

try:
    result = await ctx.llm.complete(prompt="Hello")
except LLMError as e:
    print(f"LLM failed: {e}")
except CommandTimeoutError as e:
    print(f"Request timed out: {e}")
except HuitzoError as e:
    print(f"Huitzo error: {e}")
```

### Testing a pack with scenarios

`huitzo_sdk.testing` runs a pack's commands offline against a real `Context`
(in-memory storage, stubbed LLM/HTTP/email, recorded effects, frozen time and
ids, hosted-runtime refusals) and replays the examples in
`<pack>/scenarios/*.yaml`:

```bash
python -m huitzo_sdk.testing.replay path/to/pack --json
```

The pack's ordinary `pytest` run collects the scenarios too. See
[docs/testing.md](docs/testing.md) and
[docs/scenario-format.md](docs/scenario-format.md).

### Change impact

`huitzo_sdk.impact` compares two copies of a pack (before and after an edit)
and says which commands the edit is expected to change, without importing or running
either copy:

```bash
python -I -m huitzo_sdk.impact path/to/base path/to/edited --json
```

**Experimental and unsupported.** The report format and verdicts may change
without notice, and a command reported "not expected to change" (`unaffected`
in the JSON) is not guaranteed to be unchanged: do not use it to skip tests or
scenario replay. It is advisory, not a security boundary: it says which
commands an edit is expected to change. When it recognises that
it cannot follow a construct, it reports the command as expected to change,
with the reason; it can still be wrong, and replaying every scenario is the
gate. It is for ordering attention (which commands to look at first, and why)
and for finding commands no scenario covers. Precision needs declarations: see
[Measured quality](docs/impact.md#measured-quality) and
[docs/impact.md](docs/impact.md).

### State declarations

A pack can declare its storage collections (`state.collections`) and, per
command, what it `reads`, `writes`, `returns` and `calls`. Code reaches a
declared collection through `ctx.storage.collection(name, Model, scope=...,
key_prefix=...)`, a typed accessor whose keys are always
`<key_prefix>/<id>`. The check compares the code with the declarations,
statically:

```bash
python -I -m huitzo_sdk.impact.check path/to/pack --json
```

With `declarations: strict` every finding is an error (Studio-generated
packs); the default `advisory` reports warnings. See
[docs/state.md](docs/state.md).

## Development

### Prerequisites

- Python 3.11 or higher
- [uv](https://github.com/astral-sh/uv) (recommended) or pip

### Setup

```bash
# Clone the repository
git clone https://github.com/Huitzo-Inc/sdk.git
cd sdk

# Install dependencies
uv sync --dev

# Or with pip
pip install -e ".[dev]"
```

### Running Tests

```bash
# Run all tests
pytest

# Run with coverage
pytest --cov=huitzo_sdk --cov-report=term-missing

# Run specific test file
pytest tests/test_command.py
```

### Code Quality

```bash
# Type checking
mypy src/huitzo_sdk

# Linting and formatting
ruff check src tests
ruff format src tests
```

## Project Structure

```
huitzo-sdk/
├── src/
│   └── huitzo_sdk/
│       ├── __init__.py       # Public API exports
│       ├── command.py        # @command decorator
│       ├── context.py        # Context object
│       ├── types.py          # Core type definitions
│       ├── errors.py         # Error hierarchy
│       ├── integrations/     # Integration clients
│       │   ├── llm.py
│       │   ├── email.py
│       │   ├── http.py
│       │   ├── telegram.py
│       │   └── files.py
│       ├── storage/          # Storage backends
│       │   ├── protocol.py
│       │   ├── memory.py
│       │   └── namespace.py
│       └── testing/          # Testing context, scenarios, replay runner
├── docs/                     # Testing guide and scenario format
├── tests/                    # Test suite
├── pyproject.toml           # Project configuration
└── README.md                # This file
```

## Contributing

We welcome contributions! Please:

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes with tests
4. Ensure all tests pass (`pytest`)
5. Run linters (`ruff check src tests`)
6. Commit your changes (`git commit -m 'Add amazing feature'`)
7. Push to the branch (`git push origin feature/amazing-feature`)
8. Open a Pull Request

## License

See the [LICENSE](LICENSE) file for details.

## Support

- Email: support@huitzo.com
- Community: [Discord](https://discord.gg/huitzo)
- Documentation: [docs.huitzo.com](https://docs.huitzo.com)
- Issues: [GitHub Issues](https://github.com/Huitzo-Inc/sdk/issues)
