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

# Builtins

> API reference for SelfReference, PyRepl, and FileToolset

# Builtins API Reference

## SelfReference

```python theme={null}
from SimpleLLMFunc.builtin import SelfReference
```

Durable backend for agent memory, context management, and fork orchestration.

### Constructor

```python theme={null}
SelfReference()
```

### Key Methods

| Method                       | Description                                 |
| ---------------------------- | ------------------------------------------- |
| `bind_history(key, history)` | Bind a conversation history to a memory key |
| `get_history(key)`           | Get the current history for a key           |
| `get_experiences(key)`       | Get stored experiences for a key            |

### Memory Key Isolation

Each key has independent state:

* History (conversation transcript)
* Experiences (durable facts)
* Summary state (compaction checkpoints)
* Fork handles (child agent state)

### Usage with @llm\_chat

```python theme={null}
# Automatic (recommended)
@llm_chat(llm_interface=llm, self_reference_key="agent_main", ...)
async def agent(...):
    ...

# Explicit backend
selfref = SelfReference()
selfref.bind_history("my_key", initial_history)

@llm_chat(llm_interface=llm, self_reference=selfref, self_reference_key="my_key", ...)
async def agent(...):
    ...
```

### Runtime Primitives (via PyRepl)

When SelfRef is active, these are available in `execute_code`:

```python theme={null}
# Context
runtime.selfref.context.inspect() -> dict
runtime.selfref.context.remember(text: str) -> dict  # {id, text}
runtime.selfref.context.forget(experience_id: str) -> bool
runtime.selfref.context.compact(
    goal: str,
    instruction: str,
    discoveries: list[str],
    completed: list[str],
    current_status: str,
    likely_next_work: str,
    relevant_files_directories: list[str],
    remember: list[str] = [],
) -> dict  # {assistant_message, ...}

# Fork
runtime.selfref.fork.spawn(
    task: str,
    instruction: str,
    ...
) -> dict  # {fork_id, status}
runtime.selfref.fork.gather_all(include_history: bool = False) -> dict  # {fork_id: ForkResult}
```

***

## PyRepl

```python theme={null}
from SimpleLLMFunc.builtin import PyRepl
```

Persistent IPython REPL in a subprocess with runtime primitive support.

### Constructor

```python theme={null}
PyRepl(working_directory: Optional[Path | str] = None)
```

| Parameter           | Default      | Description                            |
| ------------------- | ------------ | -------------------------------------- |
| `working_directory` | `None` (cwd) | Working directory for the REPL process |

### Properties

| Property   | Type         | Description                                  |
| ---------- | ------------ | -------------------------------------------- |
| `.toolset` | `List[Tool]` | The two tools: `execute_code` + `reset_repl` |

### Methods

| Method                         | Description                                |
| ------------------------------ | ------------------------------------------ |
| `install_primitive_pack(pack)` | Register a PrimitivePack in this REPL      |
| `get_runtime_backend(name)`    | Get an installed backend by pack namespace |
| `reset()`                      | Clear REPL variables (preserves backends)  |

### Tools Provided

#### execute\_code

```python theme={null}
async def execute_code(code: str, event_emitter=None) -> dict:
    """Run Python code in the persistent REPL."""
```

Returns:

```python theme={null}
{
    "stdout": str,          # Captured stdout
    "stderr": str,          # Captured stderr
    "return_value": str,    # Repr of last expression (or None)
    "artifacts": list,      # Captured image artifacts for direct PyRepl.execute calls
    "error": str | None,    # Error message if failed
    "execution_time_ms": float,
}
```

When used through the agent toolset, `execute_code` returns a natural-language summary. If code outputs images through `display(Image(...))`, an image-rich last expression, or `ImgPath(...)` / `ImgUrl(...)`, the tool result becomes multimodal so the model can inspect the image.

#### reset\_repl

```python theme={null}
async def reset_repl() -> str:
    """Clear REPL variables. Preserves runtime backends."""
```

### Example

```python theme={null}
from SimpleLLMFunc.builtin import PyRepl

repl = PyRepl(working_directory="/path/to/project")

@llm_chat(llm_interface=llm, toolkit=repl.toolset, stream=True)
async def code_agent(message: str, history: list | None = None):
    """Execute Python to solve problems."""
    pass
```

### Custom Events

| Event Name      | Data            | Description           |
| --------------- | --------------- | --------------------- |
| `kernel_stdout` | `{"text": str}` | Real-time stdout line |
| `kernel_stderr` | `{"text": str}` | Real-time stderr line |

### Execution Limits

| Setting            | Default                     |
| ------------------ | --------------------------- |
| Execution timeout  | 600 seconds                 |
| Input idle timeout | 300 seconds                 |
| Output truncation  | \~20,000 tokens → temp file |

***

## FileToolset

```python theme={null}
from SimpleLLMFunc.builtin import FileToolset
```

Workspace-scoped file operations with stale-write protection.

### Constructor

```python theme={null}
FileToolset(workspace: Path | str)
```

All paths are resolved relative to `workspace`. Path traversal above workspace is rejected.

### Properties

| Property   | Type         | Description      |
| ---------- | ------------ | ---------------- |
| `.toolset` | `List[Tool]` | The 5 file tools |

### Tools Provided

#### read\_file

```python theme={null}
async def read_file(path: str, start_line: int = None, end_line: int = None) -> str
```

Returns line-numbered content: `<lineno> | <content>`.

#### read\_image

```python theme={null}
async def read_image(path: str) -> ImgPath
```

Returns image as multimodal content (detail="high").

#### grep

```python theme={null}
async def grep(pattern: str, path_pattern: str) -> str
```

Regex search over workspace files. `path_pattern` scopes which files to search.

#### sed

```python theme={null}
async def sed(path: str, start_line: int, end_line: int, pattern_to_be_replaced: str, new_string: str) -> str
```

Regex find-and-replace within a line range. Protected by hash-based stale detection.

#### echo\_into

```python theme={null}
async def echo_into(path: str, content: str) -> str
```

Overwrite entire file. Protected by hash-based stale detection (file must be read first).

### Stale-Write Protection

FileToolset tracks file hashes on read. If a file was modified externally between read and write, `sed` and `echo_into` will reject the write and ask the agent to re-read.

### Example

```python theme={null}
from SimpleLLMFunc.builtin import FileToolset

files = FileToolset("/path/to/workspace")

@llm_chat(llm_interface=llm, toolkit=files.toolset, stream=True)
async def file_agent(message: str, history: list | None = None):
    """An agent that can read and edit files in the workspace."""
    pass
```
