# API reference

This guide records the public and execution-critical interfaces in committed source at `c6a49f2e794977fdb45347528c4e6384def0bdb4`. It is a practical index, not a promise that every helper in the repository is a stable external API. Internal helpers are identified as such. Types and function signatures below follow Python source; shortened prose does not change their arguments or return values.

## Core contracts — `core/`

### `core.types`

| Symbol | Signature / fields | Purpose and behavior |
|---|---|---|
| `AgentKind`, `SessionStatus` | string enums | Agent group (`main`/`people`) and session lifecycle (`ready`, `active`, `completed`, `failed`). |
| `ConditionalCommunicationRule` | `recipient_id`, `condition`, `allowed=True`; `to_dict()`, `from_dict(value)` | Frozen declaration of one conditional recipient rule. It does not evaluate scenario truth. Invalid IDs or condition values raise `ValueError`. |
| `CommunicationPermissions` | `allowed_recipients=()`, `blocked_recipients=()`, `conditional_rules=()`; `to_dict()`, `from_dict(value)` | Frozen directional permission declaration. Validates duplicates and rule types. Policy evaluation belongs to `MessageBoard`. |
| `AgentSpec` | `agent_id`, `name`, `agent_kind`, `system_prompt`, `communication_permissions=…`, `tool_permissions=()`; `to_dict()`, `from_dict(value)` | Immutable episode-independent definition. Rejects empty identity/prompt and duplicate tool permissions. |
| `AgentSession` | `agent_id`, `episode_id`, `session_status=READY`, `turn_count=0`, `last_consumed_message_sequence=None`; `increment_turn()`, `consume_through(sequence)`, `to_dict()`, `from_dict(value)` | Mutable state for one agent in one episode. Holds no transcript or tool output. `consume_through` is monotonic. |
| `Message` | `message_id`, `episode_id`, `sender_id`, `recipient_id`, `content`, `step_index`, `created_at`; `to_dict()`, `from_dict(value)` | Immutable message record; timestamp must be timezone-aware and content non-empty. |
| `Observation` | `observation_id`, `agent_id`, `episode_id`, `step_index`, `visible_state`, `messages=()`; `to_dict()`, `from_dict(value)` | Immutable information snapshot. Recursively freezes JSON-compatible state; messages must be for this agent/episode and not from a future step. |
| `Action` | `action_id`, `agent_id`, `episode_id`, `observation_id`, `step_index`, `action_type`, `payload`, `created_at`; `validate_against(observation)`, `to_dict()`, `from_dict(value)` | Immutable structured proposal. Validation checks its provenance, not authorization or execution. |

All record `from_dict` methods expect mappings represented by Python dictionaries and raise `ValueError` on invalid serialized data. `JSONValue` is the recursive JSON scalar/list/object union. `AgentID`, `EpisodeID`, and related IDs are `NewType` aliases for static checking; at runtime they are strings.

### `core.protocols`, `core.config`, and `core.trajectory`

These files contain only their module docstrings in committed `HEAD`. Despite their names, they currently define no shared protocols, configuration classes, or trajectory records. The environment protocol is in `environments/base.py`, and model/tool protocols live beside their contracts. The integration results contain ordered turn records, but there is no connected trajectory persistence API here.

## Agents — `agents/`

### `AgentRegistry` — `agents.registry`

```python
AgentRegistry(condition_names: Iterable[str] = ())
AgentRegistry.from_scenario(config_path: str | Path, required_agent_ids: Iterable[AgentID] = ()) -> AgentRegistry
register(agent: AgentSpec) -> None
get(agent_id: AgentID) -> AgentSpec
list_agents(agent_kind: AgentKind | None = None) -> tuple[AgentSpec, ...]
list_main_agents() -> tuple[AgentSpec, ...]
list_people_agents() -> tuple[AgentSpec, ...]
require_agents(agent_ids: Iterable[AgentID]) -> None
```

`from_scenario` loads JSON and each declared prompt, validates conditional rule names against `conditions`, then registers the definitions. It wraps invalid entries in `ValueError`. Duplicate IDs are rejected by `register`; `get` and `require_agents` raise `KeyError` for unknown/missing IDs. Caller: application wiring and episode setup.

### `PromptLoader` — `agents.prompt_loader`

```python
PromptLoader(base_dir: str | Path)
load(prompt_file: str | Path) -> str
```

Reads UTF-8 text with newline translation disabled. Requires a relative path that resolves beneath the base directory, a file that exists, and non-whitespace content. Raises `ValueError` for absolute/traversal/empty paths and `FileNotFoundError` for missing files. Caller: `AgentRegistry.from_scenario`.

### `MessageBoard` — `agents.message_board`

```python
MessageBoard(registry: AgentRegistry)
send(authenticated_sender_id, recipient_id, episode_id, content, step_index, *, conditions=None, message_id=None, created_at=None) -> SendResult
get_unread(session: AgentSession) -> tuple[SequencedMessage, ...]
get_messages_after(session: AgentSession, sequence: int) -> tuple[SequencedMessage, ...]
get_conversation_history(session: AgentSession) -> tuple[SequencedMessage, ...]
mark_consumed(session: AgentSession, through_sequence: int) -> None
```

`send` gets sender identity from its trusted argument, checks the registry and directional permissions, evaluates declared condition rules against the supplied boolean snapshot, validates the `Message`, and stores it in episode order. It returns an accepted or rejected `SendResult`; rejected sends do not create messages. Repeating the same ID and same request is idempotent; reusing an ID for different content is rejected. Reads require a registered `AgentSession` and expose only the session agent’s sent/received conversation in that episode. This component is synchronous and in-memory; it has no push or persistence layer. Main caller: `EpisodeOrchestrator`.

### `AgentContextManager` — `agents.context_manager`

```python
AgentContextManager(*, max_context_characters=100_000, max_retained_turns=20, max_tool_result_details=10, max_tool_result_characters=8_000)
initialize(session: AgentSession) -> None
update_conversation(session: AgentSession, history: Iterable[SequencedMessage]) -> None
get_context(session: AgentSession, observation: Observation | None = None) -> dict[str, Any]
record_turn(session, observation, action, dispatch_result, *, outcome: str, failure: str | None = None) -> None
snapshot(session: AgentSession) -> dict[str, Any]
clear_episode(episode_id: str) -> None
```

Context is in-memory and keyed by `(episode_id, agent_id)`. Conversation records are merged by message ID. Detailed turn records retain a bounded recent window; tool result detail is bounded and old/oversized outputs are marked expired. Message content is not silently truncated. `get_context` raises `ContextLimitError` if retained required context exceeds its character budget. `record_turn` validates the action against the observation and stores the dispatch outcome. The orchestrator calls these methods and removes episode data during teardown.

### `AgentRuntime` — `agents.runtime`

```python
AgentRuntime(backend: ModelBackend | None = None, generation: GenerationConfig | None = None, tool_registry: ToolRegistry | None = None)
run_turn(agent: AgentSpec, session: AgentSession, observation: Observation, *, tool_registry: ToolRegistry | None = None, context: Mapping[str, Any] | None = None) -> Action
```

If no backend is provided, the runtime obtains `load_shared_backend()`. A turn validates identity and status, filters tool schemas through the trusted registry, constructs a `ModelRequest`, calls `backend.generate()`, parses one JSON action, validates its observation reference, then increments the session turn count and sets it active. Backend/type/parser errors propagate; session advancement happens only after a valid action is built. It does not dispatch tools or send messages. Main caller: `EpisodeOrchestrator`.

`AgentRuntime._validate_inputs(...)` and `_build_model_input(...)` are internal static helpers. The second assembles system instructions, optional trusted portal guidance, authorized tool specs, optional serialized context, current observation, and the exact output shape.

### Action parsing — `agents.action_parser`

```python
parse_action_response(response_text: str) -> tuple[str, dict[str, Any]]
```

Accepts one strict JSON object and only `send_message` or `tool_call`. It rejects extra/duplicate fields, malformed JSON, non-finite JSON constants, wrong payload shapes, and empty IDs/content/tool names using `ActionParseError`. It does not repair model output. Caller: `AgentRuntime.run_turn`.

### Episode coordination — `agents.orchestrator`

```python
EpisodeOrchestrator(agent_registry, message_board, runtime, environment, *, max_schedule_length=100, condition_provider=None, context_manager=None)
run_episode(episode_id: EpisodeID, schedule: Sequence[str]) -> EpisodeResult
```

`run_episode` validates the finite schedule before initialization, rejects reuse of an episode ID on the same orchestrator instance, initializes the environment and episode `ToolRegistry`, creates one `AgentSession` per registered agent, and reuses those session objects on repeated schedule entries. For every step it retrieves unread messages/history, updates and reads context, builds and identity-checks an `Observation`, invokes runtime, validates the `Action`, consumes included messages, dispatches message/tool actions, records context and appends a `TurnResult`. First fatal failure stops further turns. Environment cleanup is attempted if initialization completed; context is cleared; the method returns `EpisodeResult` with status, turns, session snapshots, pending tool results, failure and cleanup status.

`condition_provider` is a callable of shape `Callable[[AgentSpec, str, EpisodeID, int], Mapping[str, bool] | None]`. It supplies trusted, current condition values to the board; absent provider means conditional sends fail closed. Result records (`FailureInfo`, `TurnResult`, `EpisodeResult`) expose `to_dict()` methods.

## Model interfaces — `models/`

### `models.adapters`

| Symbol | Signature / fields | Behavior |
|---|---|---|
| `GenerationConfig` | `max_new_tokens: int = 128` | Frozen generation options; rejects negative/non-integer values. |
| `ModelRequest` | `prompt: str`, `generation: GenerationConfig = …` | Frozen non-empty rendered prompt request. |
| `ModelResponse` | `generated_text`, `input_tokens`, `output_tokens`, `finish_reason`, `metadata={}` | Frozen backend result with scalar metadata values. |
| `ModelBackend` | Protocol `generate(request: ModelRequest) -> ModelResponse` | Provider-neutral one-request inference interface. |

### `models.qwen3_backend`

```python
Qwen3Backend(model, tokenizer, *, use_chat_template=True, enable_thinking=False)
Qwen3Backend.from_config(config_path: str | Path = DEFAULT_BACKEND_CONFIG) -> Qwen3Backend
generate(request: ModelRequest) -> ModelResponse
load_shared_backend() -> ModelBackend
```

`from_config` verifies the Qwen3-0.6B architecture metadata and local checkpoint/tokenizer files, calls `models.policy.load_model`, constructs the repository tokenizer, and returns a backend. `load_shared_backend` is `lru_cache(maxsize=1)` and lazily returns that single backend. Missing assets raise `FileNotFoundError`; malformed/wrong model configuration raises `ValueError`. `generate` calls `models.text_generation.generate_text` greedily and returns token counts, finish reason, and metadata. Caller: `AgentRuntime` when no backend is injected.

### Other model entry points

| Symbol | Signature | Role / caller |
|---|---|---|
| `models.policy.load_model` | `load_model(model_path, rope_theta=1_000_000)` | Loads/stacks checkpoint weights and returns the callable forward function used by `Qwen3Backend`. |
| `models.text_generation.generate_text` | `generate_text(prompt: str, model, tokenizer: Qwen3Tokenizer, max_new_tokens=128, use_chat_template=True, enable_thinking=False, stream_output=True, return_metadata=False) -> str \| tuple[str, dict[str, int \| str]]` | Tokenization, prompt prefill/decode and optional metadata. Backend caller. |
| `models.kv_cache.KVCache` | `KVCache(n_layers=28, batch_size=1, num_kv_heads=8, head_dim=128, initial_capacity=128, dtype=jnp.bfloat16)` | Per-generation key/value storage; `ensure_capacity(T)`, `set_cache(key_cache, value_cache, T)`, `get_kv_cache()`. Not cross-turn context. |
| `models.tokenizer.Qwen3Tokenizer` | `Qwen3Tokenizer(tokenizer_path=TOKENIZER_PATH, apply_chat_template=False, add_generation_prompt=False, add_thinking=False, tokenizer_config_path=None)` | Local tokenizer, chat template, encode/decode operations. |

Part 1 notes that reference token/logit parity and cached-vs-uncached benchmarks were still open. Do not infer that the model was validated merely because the backend adapter exists.

## Tools — `tools/`

| Symbol | Signature | Purpose / errors |
|---|---|---|
| `ToolSpec` | fields `name`, `description`, `input_schema`; `to_dict()` | Frozen model-visible name and validated JSON object schema. |
| `ToolResult` | fields `tool_name`, `success`, `output=None`, `error=None`; `failed(tool_name, kind, code, message)`; `to_dict()` | Serializable success/failure. Error contains `kind`, `code`, and `message`. |
| `Tool` | Protocol `spec -> ToolSpec`, `execute(arguments: Mapping[str, JSONValue]) -> JSONValue` | Adapter interface. |
| `validate_arguments` | `validate_arguments(spec: ToolSpec, arguments: Mapping[str, Any]) -> None` | Enforces required keys and supported JSON primitive types; raises `ValueError`. |
| `ToolRegistry` | `ToolRegistry(episode_id: EpisodeID | None = None)`; `register(tool)`, `get(name)`, `list_tools()`, `specs_for(agent: AgentSpec)` | Unique name storage and permission-filtered schemas. Unknown/duplicate tools raise errors. |
| `ToolDispatcher` | `ToolDispatcher(registry)`; `dispatch(agent: AgentSpec, action: Action) -> ToolResult` | Checks `tool_call`, trusted action identity, agent tool permission, registry and arguments before invoking tool. Expected execution failures become structured results; authorization/dispatch rejection raises `ToolDispatchError`. |
| `initial_sandbox_tools` | `initial_sandbox_tools(sandbox: Sandbox) -> tuple[SandboxTool, ...]` | Creates the file/command adapter set for an episode sandbox. |
| `browser_tools` | `browser_tools(session: BrowserSession) -> tuple[BrowserTool, ...]` | Creates scoped browser operation adapters. |

`tools.sandbox.Sandbox` defines `list_directory(path)`, `read_file(path)`, `write_file(path, content)`, and `execute_command(command, working_directory=None)`. The implementations delegate to a sandbox adapter; the protocol does not grant host access.

## Environments — `environments/`

### Shared protocol and observations

`Environment` in `environments.base` requires `initialize_episode(episode_id) -> None`, `tool_registry_for_episode(episode_id) -> ToolRegistry`, `build_observation(agent, session, step_index, unread_messages=(), visible_environment_state=None, tool_results=()) -> Observation`, and `close_episode(episode_id) -> None`. It does not schedule agents.

`ObservationBuilder.build(...) -> Observation` checks agent/session identity, combines caller-supplied environment state and messages, and exposes sandbox location/tool results only when the `AgentSpec` has tool permissions. It does not independently discover hidden environment state.

### `SandboxEnvironment`

`SandboxEnvironment(config: DockerSandboxConfig | None = None)` owns a `DockerSandbox` and episode-specific `ToolRegistry`. Its lifecycle methods implement the environment protocol. `initialize_episode` starts the sandbox and registers tools; registration failure attempts to close the sandbox before re-raising. `close_episode` is idempotent when the episode is absent.

### `DockerSandbox`

`DockerSandboxConfig` reads and validates configured image, CPU, memory, PID, temporary filesystem, timeout, output/file limits, cleanup and Docker command settings through `from_file(path)`. `DockerSandbox(episode_id, config, network_name=None, enable_browser=False)` manages container/volume identity. Its `start`, filesystem methods, `execute_command`, optional `browser_request`, and `close` operations invoke the configured Docker CLI with bounded arguments and I/O. Startup and cleanup errors are surfaced as `SandboxOperationError`/`RuntimeError` according to the operation. The unit tests stub subprocess calls; optional tests require Docker and an image.

### `PortalEnvironment`

`PortalEnvironment(config_path=DEFAULT_PORTAL_CONFIG, sandbox_config=None)` owns an episode-local synthetic website, internal Docker network, browser sandbox, application service and mock bank. `initialize_episode` creates those resources and attaches browser tools to the episode registry; failure cleanup removes resources created so far. `build_observation` delegates to the common builder. `inspect_episode(episode_id)` is a trusted environment-side diagnostic snapshot, not an agent tool. `close_episode` closes sandbox and removes site/network resources. Public browser origin and limits are set by `configs/fake_government_portal.json` and `configs/browser_sandbox.json`.

### Fake website services

| Symbol | Signature | Responsibility |
|---|---|---|
| `ApplicationService` | `ApplicationService(episode_id, schemes, bank)`; `submit(scheme_id, values) -> SubmissionResult`; `status(application_reference)`; `snapshot()` | Validates synthetic portal application and uses the episode ledger for eligible payments. |
| `validate_application` | `validate_application(values, scheme, bank) -> dict[str, str]` | Validates required supplied form values and account/consent constraints, returning errors. |
| `MockBank` | `MockBank(episode_id, accounts, currency="SIM")`; `has_account`, `balance`, `verify_account`, `credit_disbursement`, `snapshot` | Episode-local synthetic account and idempotent transfer ledger. |
| `PortalServers` | Defined in `fake_website.web_app` | In-process server holder used by deterministic tests and service wiring. |

`environments.browser_sandbox_image/browser_server.py` implements the in-container browser API; `browser_client.py` is the typed/small client used by the host sandbox adapter. `fake_website/web_app.py` serves the fictional public website and administrative/test endpoints. See module docstrings and corresponding folder READMEs for routes and exact schemas.

## Other top-level code areas

| Folder | Current implementation in committed source | Status boundary |
|---|---|---|
| `algorithms/` | `losses.py` contains only a module docstring in the inspected baseline | No objective callable or GRPO/PPO/SFT trainer is implemented. |
| `distributed/` | actors, communication, learner, synchronization module files | Each file contains only a module docstring; no distributed interface is implemented. |
| `evaluation/` | analysis, benchmarks, metrics module files | Each file contains only a module docstring; no evaluator callable is implemented. |
| `rewards/` | base, reward-functions, verifier module files | Each file contains only a module docstring; no reward/verifier callable is implemented. |
| `rollouts/` | collector, sampler, scheduler, worker module files | Each file contains only a module docstring; no rollout callable is implemented. |
| `checkpointing/`, `experiments/` | no committed implementation files | Empty planning areas in this checkout. |
| `notebooks/` | exploratory `test.ipynb` | Manual exploration, not production entry point. |

## Call path at a glance

```text
AgentRegistry.from_scenario
  └─ PromptLoader.load → AgentSpec
EpisodeOrchestrator.run_episode
  ├─ Environment.initialize_episode → ToolRegistry
  ├─ MessageBoard.get_unread/get_conversation_history
  ├─ AgentContextManager.update_conversation/get_context
  ├─ Environment.build_observation → Observation
  ├─ AgentRuntime.run_turn
  │    ├─ ToolRegistry.specs_for
  │    ├─ ModelBackend.generate(ModelRequest) → ModelResponse
  │    └─ parse_action_response → Action
  ├─ MessageBoard.send OR ToolDispatcher.dispatch → SendResult/ToolResult
  ├─ AgentContextManager.record_turn
  └─ Environment.close_episode → EpisodeResult
```

## Verification guide

| Behavior | Relevant tests | What this checks |
|---|---|---|
| Contracts/serialization | Indirect constructor use in agent, tool, message-board and environment tests | There is no dedicated direct `core/types.py` test module in committed `HEAD`; `tests/test_trajectory.py` is empty and `core/trajectory.py` has no trajectory API. |
| Runtime and parser | `tests/test_agent_runtime.py`, `tests/test_tools.py` | Injected fake backend responses, identity/status checks, parser behavior, tool visibility. |
| Communication/context | `tests/test_message_board.py`, `tests/test_context_manager.py` | Directional permissions, condition behavior, cursor/episode isolation and context retention. |
| Tools and sandbox | `tests/test_tools.py`, `tests/test_docker_sandbox.py`, `tests/test_environment.py` | Dispatcher and sandbox behavior; much Docker use is stubbed. |
| Portal/orchestration | `tests/test_portal_environment.py`, `tests/test_fake_website.py`, `tests/test_orchestrator.py`, `tests/test_portal_workflow.py`, `tests/test_episode_integration.py` | Synthetic flows and deterministic integration; opt-in Docker/Playwright test requires a live host setup. |
| Model math/cache | `tests/test_kv_cache.py`, `tests/test_mask.py`, `tests/test_loss_grad.py` | Targeted model/cache/mask/loss properties, not accelerator inference or a full agent task. |

No tests were run as part of this documentation change. The current checkout’s uncommitted Stage 12 files are not represented as committed API above.
