brainwires-core
Core types, traits, and error handling for the Brainwires Agent Framework.
Overview
brainwires-core defines the foundational types shared by every other crate in the framework: messages, tools, providers, tasks, plans, permissions, embeddings, vector stores, and knowledge graphs. It is intentionally lightweight, with no runtime dependencies beyond serialization and async primitives.
Design principles:
- Trait-driven —
Provider,EmbeddingProvider,VectorStore,StagingBackendare all trait objects for pluggable implementations - Serializable — every public type implements
Serialize/Deserializefor wire transport and persistence - Content-source aware — trust levels propagate through the system via
ContentSourcetagging - WASM-compatible — the
wasmfeature swaps only the chrono backend, everything else compiles as-is
┌──────────────────────────────────────────────────────────────┐
│ brainwires-core │
│ │
│ ┌──────────┐ ┌──────────┐ ┌───────────┐ ┌───────────┐ │
│ │ Message │ │ Tool │ │ Provider │ │ Task │ │
│ │ Role │ │ ToolUse │ │ (trait) │ │ TaskStatus│ │
│ │ Content │ │ ToolResult│ │ ChatOpts │ │ Priority │ │
│ │ Stream │ │ Context │ │ Streaming │ │ Hierarchy │ │
│ └──────────┘ └──────────┘ └───────────┘ └───────────┘ │
│ │
│ ┌──────────┐ ┌──────────┐ ┌───────────┐ ┌───────────┐ │
│ │ Plan │ │Permission│ │ Embedding │ │ Graph │ │
│ │ Metadata │ │ Mode │ │ (trait) │ │ Entity │ │
│ │ Budget │ │ RO/Auto/ │ │ Vector │ │ Edge │ │
│ │ Steps │ │ Full │ │ Store │ │ Search │ │
│ └──────────┘ └──────────┘ └───────────┘ └───────────┘ │
│ │
│ ┌────────────────┐ ┌──────────────┐ ┌────────────────┐ │
│ │ ContentSource │ │ WorkingSet │ │ OutputParser │ │
│ │ Trust levels │ │ LRU eviction │ │ JSON/Regex │ │
│ └────────────────┘ └──────────────┘ └────────────────┘ │
└──────────────────────────────────────────────────────────────┘
Quick Start
Add to your Cargo.toml:
[]
= "0.1"
Build a message, define a tool, and call a provider:
use ;
use HashMap;
let messages = vec!;
let tool = Tool ;
let options = deterministic;
let response = provider.chat.await?;
Features
| Feature | Default | Description |
|---|---|---|
native |
Yes | Native target support, enables planning |
planning |
Yes (via native) |
Plan parsing and structured output extraction (regex) |
wasm |
No | WASM target support (chrono/wasmbind) |
# Default (native + planning)
= "0.1"
# WASM target
= { = "0.1", = false, = ["wasm"] }
Architecture
Messages
The message protocol supports text, images, tool calls, and tool results in a unified structure.
Role variants: User, Assistant, System, Tool
MessageContent variants:
| Variant | Description |
|---|---|
Text(String) |
Simple text content |
Blocks(Vec<ContentBlock>) |
Multimodal / structured content |
ContentBlock variants:
| Variant | Fields | Description |
|---|---|---|
Text |
text |
Text block |
Image |
source: ImageSource |
Base64-encoded image |
ToolUse |
id, name, input |
Tool invocation request |
ToolResult |
tool_use_id, content, is_error |
Tool execution result |
Message constructors: Message::user(text), Message::assistant(text), Message::system(text), Message::tool_result(id, content).
StreamChunk variants:
| Variant | Description |
|---|---|
Text(String) |
Text delta |
ToolUse { id, name } |
Tool use started |
ToolInputDelta { id, partial_json } |
Incremental tool input |
ToolCall { ... } |
Full tool call request |
Usage(Usage) |
Token usage statistics |
Done |
Stream completed |
Provider Trait
The unified AI provider interface supporting both blocking and streaming modes.
ChatOptions presets:
| Preset | Temperature | Top-P | Use Case |
|---|---|---|---|
deterministic(max_tokens) |
0.0 | — | Exact reproduction |
factual(max_tokens) |
0.1 | 0.9 | Factual answers |
creative(max_tokens) |
0.3 | — | Creative tasks |
new() (default) |
0.7 | — | General use |
Tools
Tool definitions, execution results, idempotency, and staged writes.
Tool fields:
| Field | Type | Default | Description |
|---|---|---|---|
name |
String |
— | Tool identifier |
description |
String |
— | Human-readable description |
input_schema |
ToolInputSchema |
— | JSON Schema for parameters |
requires_approval |
bool |
false |
Prompt user before execution |
defer_loading |
bool |
false |
Lazy-load tool definition |
allowed_callers |
Vec<ToolCaller> |
[Direct] |
Who can invoke this tool |
input_examples |
Vec<Value> |
[] |
Example inputs |
ToolResult constructors: ToolResult::success(id, content), ToolResult::error(id, error).
ToolContext carries execution environment:
| Field | Type | Description |
|---|---|---|
working_directory |
String |
CWD for file operations |
user_id |
Option<String> |
Current user |
metadata |
HashMap<String, String> |
Arbitrary metadata |
capabilities |
Option<Value> |
Serialized capabilities |
idempotency_registry |
Option<IdempotencyRegistry> |
Deduplicates repeated calls |
staging_backend |
Option<Arc<dyn StagingBackend>> |
Batched writes with rollback |
StagingBackend trait:
Tasks
Hierarchical task tracking with status lifecycle and time metrics.
TaskStatus variants: Pending, InProgress, Completed, Failed, Blocked, Skipped
TaskPriority variants: Low (0), Normal (1), High (2), Urgent (3)
Task key methods:
| Method | Description |
|---|---|
new(id, description) |
Create a standalone task |
new_for_plan(id, desc, plan_id) |
Create a plan-linked task |
new_subtask(id, desc, parent_id) |
Create a child task |
start() / complete(summary) / fail(error) |
Status transitions |
block() / skip(reason) |
Blocking and skipping |
add_child(id) / add_dependency(id) |
Hierarchy management |
duration_secs() / elapsed_secs() |
Time tracking |
Plans
Serializable execution plans with budget constraints and step-level granularity.
PlanMetadata — full plan record with branching support:
| Field | Type | Description |
|---|---|---|
plan_id |
String |
Unique identifier |
title |
String |
Human-readable title |
plan_content |
String |
Full plan text |
status |
PlanStatus |
Draft / Active / Paused / Completed / Abandoned |
parent_plan_id |
Option<String> |
Branch parent |
child_plan_ids |
Vec<String> |
Sub-plans |
depth |
u32 |
Nesting level |
embedding |
Option<Vec<f32>> |
For semantic search |
PlanBudget — constrains plan execution:
let budget = new
.with_max_steps
.with_max_tokens
.with_max_cost_usd;
budget.check?; // Err if plan exceeds any limit
Permissions
Simple three-level permission system.
| Mode | Behavior |
|---|---|
ReadOnly |
Deny all write operations |
Auto (default) |
Approve safe ops, prompt for dangerous ones |
Full |
Auto-approve everything |
Content Source
Trust-level classification for injected content, ordered from highest to lowest trust.
| Level | Value | Requires Sanitization |
|---|---|---|
SystemPrompt |
0 | No |
UserInput |
1 | No |
AgentReasoning |
2 | No |
ExternalContent |
3 | Yes |
Higher-trust sources can override lower-trust content via can_override().
Working Set
LRU-managed file context with configurable eviction.
WorkingSetConfig defaults:
| Field | Default | Description |
|---|---|---|
max_files |
15 | Maximum tracked files |
max_tokens |
100,000 | Token budget |
stale_after_turns |
10 | Turns before auto-eviction |
auto_evict |
true |
Evict stale entries automatically |
Key methods:
| Method | Description |
|---|---|
add(path, tokens) |
Add file, returns eviction reason if budget exceeded |
add_pinned(path, tokens, label) |
Pinned files cannot be evicted |
touch(path) |
Update access count and turn |
next_turn() |
Advance turn counter, trigger eviction |
total_tokens() |
Current token usage |
Token estimation: estimate_tokens(content) — approximately 4 characters per token.
Embedding & Vector Store
Abstract traits for pluggable embedding and storage backends.
EmbeddingProvider trait:
VectorStore trait:
Knowledge Graph
Entity and relationship types for building code knowledge graphs.
EntityType variants: File, Function, Type, Variable, Concept, Error, Command
EdgeType variants with default weights:
| Variant | Weight | Description |
|---|---|---|
Defines |
1.0 | Entity defines another |
References |
0.8 | Entity references another |
DependsOn |
0.7 | Dependency relationship |
Modifies |
0.6 | Entity modifies another |
Contains |
0.5 | Containment relationship |
CoOccurs |
0.3 | Co-occurrence in same context |
RelationshipGraphT trait:
Output Parsers (requires planning feature)
Structured output extraction from AI text responses.
OutputParser trait:
Built-in parsers:
| Parser | Output | Description |
|---|---|---|
JsonOutputParser<T> |
T: DeserializeOwned |
Extracts JSON from markdown fences or prose |
JsonListParser<T> |
Vec<T> |
Extracts JSON arrays |
RegexOutputParser |
HashMap<String, String> |
Extracts named capture groups |
Error Types
FrameworkError variants:
| Variant | Description |
|---|---|
Config(String) |
Configuration error |
Provider(String) |
Provider error |
ToolExecution(String) |
Tool execution error |
Agent(String) |
Agent error |
Storage(String) |
Storage error |
PermissionDenied(String) |
Permission denied |
Serialization(serde_json::Error) |
JSON serialization error |
Other(anyhow::Error) |
Catch-all |
Usage Examples
Message Construction
use ;
let text_msg = user;
let system_msg = system;
let tool_result = tool_result;
// Access text content
if let Some = text_msg.text
Tool Definition and Result
use ;
use HashMap;
let tool = Tool ;
let result = success;
let error = error;
Chat Options Presets
use ChatOptions;
let opts = deterministic; // temp=0
let opts = factual; // temp=0.1, top_p=0.9
let opts = creative; // temp=0.3
let opts = new.temperature.max_tokens.system;
Working Set Management
use ;
use PathBuf;
let mut ws = with_config;
ws.add;
ws.add_pinned;
ws.next_turn;
ws.touch;
println!;
Plan Budget Validation
use ;
let plan = new;
let budget = new
.with_max_steps
.with_max_cost_usd;
budget.check?;
Task Hierarchy
use ;
let mut parent = new;
parent.set_priority;
parent.start;
let mut child = new_subtask;
child.start;
child.complete;
parent.add_child;
parent.complete;
println!;
Content Source Trust
use ContentSource;
let source = ExternalContent;
assert!;
let system = SystemPrompt;
assert!;
assert!;
Integration with Brainwires
Use via the brainwires facade crate:
[]
= "0.1"
Or use standalone — brainwires-core has no dependency on any other Brainwires crate.
License
Licensed under either of Apache License, Version 2.0 or MIT License at your option.