> ## Documentation Index
> Fetch the complete documentation index at: https://simplellmfunc.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# Runtime

> API reference for PrimitivePack, PrimitiveRegistry, PrimitiveSpec, and related types

# Runtime API Reference

## PrimitivePack

```python theme={null}
from SimpleLLMFunc.runtime import PrimitivePack
```

A named collection of primitives with a shared backend.

```python theme={null}
@dataclass
class PrimitivePack:
    namespace: str                          # e.g., "selfref", "metrics"
    backend: RuntimePrimitiveBackend        # Stateful backend instance
    primitives: List[PrimitiveHandler]      # Registered primitive functions
    guide: Optional[Dict[str, Any]] = None  # Namespace documentation
```

### Example

```python theme={null}
from SimpleLLMFunc.runtime import PrimitivePack, RuntimePrimitiveBackend, primitive

class MyBackend(RuntimePrimitiveBackend):
    pass

@primitive
async def my_action(ctx: PrimitiveCallContext, arg: str) -> dict:
    """Do something.

    Args:
        arg: Input argument.

    Returns:
        Result dict.

    Best Practices:
        - Use for X.
    """
    return {"result": arg}

pack = PrimitivePack(
    namespace="myns",
    backend=MyBackend(),
    primitives=[my_action],
    guide={"namespace": "myns", "overview": "My custom primitives."},
)
```

***

## @primitive

```python theme={null}
from SimpleLLMFunc.runtime import primitive
```

Decorator that registers a function as a runtime primitive.

### Requirements

* First parameter must be `ctx: PrimitiveCallContext`
* Docstring must include `Best Practices` section
* Must be `async def`

```python theme={null}
@primitive
async def my_primitive(ctx: PrimitiveCallContext, param: str) -> dict:
    """Description.

    Args:
        param: Description.

    Returns:
        Result.

    Best Practices:
        - When to use this primitive.
    """
    return {"value": param}
```

***

## PrimitiveCallContext

```python theme={null}
from SimpleLLMFunc.runtime import PrimitiveCallContext
```

Runtime context passed to every primitive handler.

```python theme={null}
@dataclass
class PrimitiveCallContext:
    backend: RuntimePrimitiveBackend    # The pack's backend
    fork_context: Optional[ForkContext] # Fork info if inside a fork
    event_emitter: ToolEventEmitter     # For emitting custom events
```

***

## ForkContext

```python theme={null}
from SimpleLLMFunc.runtime import ForkContext
```

Information about the current fork execution context.

```python theme={null}
@dataclass
class ForkContext:
    parent_pack_name: str
    backend_name: str
    child_fork_id: str | None = None
    source_memory_key: str | None = None
    metadata: dict[str, Any] | None = None
```

***

## PrimitiveSpec

```python theme={null}
from SimpleLLMFunc.runtime import PrimitiveSpec
```

The contract exposed to the model for discoverability.

```python theme={null}
@dataclass
class PrimitiveSpec:
    name: str                                  # Full qualified name (e.g., "selfref.context.remember")
    description: str                           # What it does
    parameters: List[PrimitiveParameterSpec]   # Parameter descriptions
    returns: str                               # Return type description
    best_practices: List[str]                  # Usage guidance
```

***

## PrimitiveParameterSpec

```python theme={null}
@dataclass
class PrimitiveParameterSpec:
    name: str
    type: str
    description: str
    required: bool = True
    default: Optional[Any] = None
```

***

## PrimitiveRegistry

```python theme={null}
from SimpleLLMFunc.runtime import PrimitiveRegistry
```

Manages installed packs and routes primitive calls.

### Key Methods

| Method                 | Description                           |
| ---------------------- | ------------------------------------- |
| `install_pack(pack)`   | Register a PrimitivePack              |
| `call(name, **kwargs)` | Execute a primitive by qualified name |
| `list_primitives()`    | List all registered primitive names   |
| `get_spec(name)`       | Get PrimitiveSpec for a primitive     |
| `list_specs()`         | Get all specs                         |
| `list_backends()`      | List installed backend packs          |

***

## RuntimePrimitiveBackend

```python theme={null}
from SimpleLLMFunc.runtime import RuntimePrimitiveBackend
```

Base class for primitive pack backends. Subclass to create stateful backends.

```python theme={null}
class RuntimePrimitiveBackend:
    """Base class. Override to add state."""
    pass
```

***

## Built-in Meta-Primitives

Always available in PyRepl without any pack installation:

| Call                               | Returns                           |
| ---------------------------------- | --------------------------------- |
| `runtime.list_primitives()`        | `List[str]` — all primitive names |
| `runtime.list_primitive_specs()`   | `List[PrimitiveSpec]` — all specs |
| `runtime.get_primitive_spec(name)` | `PrimitiveSpec` — one spec        |
| `runtime.list_backends()`          | `List[str]` — installed packs     |

***

## SelfRef Pack Registration

```python theme={null}
from SimpleLLMFunc.runtime import build_self_reference_pack, register_self_reference_primitives

# Build the pack
pack = build_self_reference_pack(selfref_backend)

# Or register directly into a PyRepl
register_self_reference_primitives(repl, selfref_backend)
```

The selfref pack provides primitives under `runtime.selfref.context.*` and `runtime.selfref.fork.*`.
