Expand description
Machi — embeddable multi-agent runtime kernel (v1 clean break).
§Layers (implemented)
| Crate | Role |
|---|---|
machi-types | ids, messages, usage, errors |
machi-protocol | tool id, content blocks, span catalogue |
machi-obs | metrics sink, redact, recording / prometheus text |
machi-tools | DynTool, stream, dispatch, approval |
machi-toolkit | cwd-jailed fs/shell tools (feature) |
machi-llm | sampler + mock / openai / ollama |
machi-agent | definition, builder, discovery |
machi-state | conversation handle, ledger, persistence |
machi-compaction | compaction strategies |
machi-runtime | turn, session, host, workflow adapter |
machi-workflow | Rhai engine, journal, validate (no LLM) |
§Vertical slice (canonical product path)
Session / handle → TurnRuntime → tools(+toolkit) → approval / stop gates →
metrics → SessionHost spawn and/or journaled workflow (+ scratch/template).
Not implemented yet (do not assume): hooks crate, long-term memory crate, proc-macro derive, full OTEL SDK export, MCP.
Optional host capabilities (e.g. git_diff_since) require explicit setup.
Re-exports§
pub use machi_agent as agent;pub use machi_llm as llm;pub use machi_protocol as protocol;pub use machi_runtime as runtime;pub use machi_tools as tools;pub use machi_types as types;pub use machi_workflow as workflow;
Structs§
- Agent
- Session-bound agent: definition + resolved prompt + tools.
- Agent
Builder - Builds a validated
Agent. - Agent
Definition - Versionable agent definition (data only).
- AgentId
- Identifies an agent instance or nested run.
- Agent
Opts - Options for
agent()/parallel()host spawns. - Agent
Registry - Shared agent definition catalogue for
agent_typeresolution. - Agent
RunResult - Result of a nested agent run.
- Always
Deny - Always denies (negative tests).
- Auto
Approve - Always allows (library tests / trusted offline hosts).
- Breaker
Config - Configuration for
CircuitBreaker. - Breaker
Sampler - Sampler wrapper that refuses traffic while the breaker is open.
- Budget
State - Budget snapshot.
- Calc
Tool - Evaluates a restricted arithmetic expression (
+ - * / ( )and numbers). - Circuit
Breaker - Thread-safe windowed circuit breaker.
- Compaction
Outcome - Result of a compaction pass.
- Completion
Requirement - Require a tool call before the turn may complete.
- Completion
Tokens Details - Completion-side token details.
- Completion
Tool Gate - Require a named tool to have been called in this conversation.
- Deadline
- An absolute deadline for a unit of work.
- Dispatch
Outcome - Outcome for a single dispatched call.
- Dispatch
Request - One tool call to execute.
- File
Workflow RunStore - Directory of
*.jsonrecords + optional shared journal root. - Gate
Chain - Composite of ordered gates (first Continue wins).
- Identity
Assembler - Identity assembler: uses only the definition’s resolved instructions.
- Image
Block - Inline image payload.
- InProcess
Host - In-process host: nested
TurnRuntimewith shared sampler, tool pool, and limits. - InProcess
Isolation - Default isolation: same process and filesystem as the parent host.
- Isolation
Env - Environment prepared for a single nested spawn.
- Journal
- In-memory journal with optional durable path.
- Journal
Entry - One recorded host call.
- Lifecycle
Fanout - Fan-out to a list of contributors.
- Machi
Error - Kernel error with stable code, message, and optional source.
- MaxMessages
- Drop oldest non-system messages until
maxremains. - Memory
Workflow RunStore - In-memory store for tests.
- Message
- A single conversation message.
- Mock
Sampler - Queue of scripted responses (FIFO) plus optional prompt-keyed responses.
- Noop
Lifecycle - No-op contributor.
- Noop
Metrics - Discards all metrics (default for tests / offline).
- Open
AiCompat Config - Configuration for an OpenAI-compatible endpoint.
- Project
Prompt Assembler - Prepend optional project preamble (e.g.
AGENTS.md) to definition instructions. - Prompt
Tokens Details - Prompt-side token details.
- Retry
Context - Context for one failed attempt.
- Retry
Policy - Configurable retry policy for
crate::retrying::RetryingSampler. - Retrying
Sampler - Wraps an
LlmSamplerwith retry / backoff / empty-response handling. - RunId
- Identifies a turn or top-level run.
- Sample
Request - One sampling request.
- Sample
Response - Sampling result.
- Session
- Thin multi-turn orchestrator (one agent, persistent conversation state).
- Session
Id - Identifies a multi-turn session.
- Spawn
Agent Tool - Tool that spawns a nested agent through a shared
SessionHost. - Spawn
Opts - Options for spawning a nested agent.
- Static
Tool Source - Fixed list of tools (primary host-registered set).
- Stationarity
Tracker - Tracks stationarity across tool-call steps within a turn.
- Token
Threshold - Drop oldest non-system messages when
token_estimateexceedsmax_tokens. - Tool
Call - A model-emitted tool invocation.
- Tool
Call Context - Context passed into every tool invocation.
- Tool
Call Id - Identifies a model tool call within a turn.
- Tool
Definition - JSON-schema facing tool definition for model APIs.
- Tool
Dispatch - Scheduler for tool batches.
- ToolId
- Canonical tool identifier (name-based for v1).
- Tool
Metadata - Metadata used by dispatch and capability filters.
- Tool
Registry - Thread-safe tool registry.
- Tool
Result - Successful tool output returned to the model.
- Turn
Options - Options for a single turn.
- Turn
Outcome - Successful or failed turn result.
- Turn
Runtime - Stateless turn engine.
- Usage
- Aggregated token usage for a sample or turn.
- Validation
Report - Successful dry-run report.
- VecConversation
State - In-memory conversation state.
- Workflow
Agent Result - Result returned from a host agent spawn.
- Workflow
Meta - Workflow catalog metadata.
- Workflow
RunId - Identifies a workflow orchestration run.
- Workflow
RunParams - Parameters for
run_workflow. - Workflow
RunRecord - Durable metadata for one workflow run.
- Workflow
Side Effects - Shared mutable store for a single workflow run.
Enums§
- Admission
- Admission decision.
- Agent
Source - Where a definition was loaded from (for discovery precedence).
- Approval
Decision - Decision for a pending tool call.
- Approval
Policy - When to consult the approval gate.
- Breaker
Outcome - Outcome recorded after a probe or live call.
- Breaker
State - Breaker state machine.
- Capability
Flag - Fine-grained capability flags for filtering.
- Capability
Mode - How nested/session capability mode filters tools.
- Concurrency
Mode - How a tool interacts with concurrent execution.
- Content
Block - Rich content unit for tool progress, tool results, and multimodal messages.
- Content
Part - One content part of a multimodal message.
- Destructiveness
- Destructiveness class for policy and approvals.
- Error
Code - Machine-stable error code for control-plane handling.
- Gate
Decision - Result of evaluating stop gates after a final assistant message.
- Host
Error - Host-side failures.
- Http
Retry Class - HTTP classification outcome.
- Image
Mime - Image MIME types commonly used in multimodal prompts.
- Instructions
- Static or deferred instructions.
- Interrupt
Behavior - Cancel behavior while a tool is running.
- Journal
Error - Journal failures.
- Pause
Kind - Why a workflow paused.
- Preflight
Overflow - Preflight decision before sampling.
- Retry
Class - Whether an automatic retry may be appropriate.
- Retry
Decision - Decision from the classifier.
- Role
- Participant role in a conversation.
- Sample
Event - One event in a streaming sample.
- Stationarity
Action - Action after observing a tool-call batch.
- Store
Error - Store failures.
- Tool
Choice - Whether the model must/may/must-not call tools.
- Tool
Policy - Tool allow/deny policy on a definition (applied at agent resolution / build).
- Tool
Progress - Progress payload shapes.
- Tool
Stream Item - One item in a tool stream.
- Turn
Abort Reason - Why a turn aborted without a normal completion.
- Turn
Input - User-facing turn input.
- Validation
Error - Validation failures.
- Workflow
Host Request - Requests the pure engine sends to the host.
- Workflow
Outcome - Terminal or pausable workflow outcome.
- Workflow
RunStatus - Coarse status for listing / resume UX.
Constants§
- DEFAULT_
AGENT_ BUDGET - Default cumulative agent-call budget.
- DEFAULT_
IDLE_ TIMEOUT - Default per-chunk idle timeout for streams (W2.2).
- DEFAULT_
MAX_ ATTEMPTS - Default max attempts (including the first try). Attempt index reaching this is fatal.
- DEFAULT_
MAX_ CONCURRENT_ CHILDREN - Default max concurrent in-flight nested agents.
- DEFAULT_
MAX_ SPAWN_ DEPTH - Default max nesting depth for nested agents (
0..DEFAULT_MAX_SPAWN_DEPTH). - EXPLORE
- Read-only exploration agent.
- EXTRA_
SPAWN_ DEPTH - Extra key: nesting depth of the agent that owns this tool call
(
0= first host-spawned level). Used byspawn_agentto fail-closed on depth. - GENERAL_
PURPOSE - Builtin agent type names.
- HARD_
STOP_ THRESHOLD - Consecutive identical tool rounds before a hard stop.
- IMAGE_
TOKEN_ COST - Fixed token cost for one image part (provider-agnostic estimate).
- MAX_
AGENT_ BUDGET - Hard ceiling for agent budget.
- MAX_
DELTA_ BYTES - Default max bytes per partial delta frame (16 KiB).
- MAX_
FRAME_ BYTES - Default max total frame/stream bytes (16 MiB).
- MAX_
JOURNAL_ BYTES - Maximum journal file size in bytes.
- MAX_
JOURNAL_ ENTRIES - Maximum journal entries (same ceiling as host-call budget).
- MAX_
RETRY_ AFTER - Cap when honoring full
Retry-Afteron 429. - MAX_
RETRY_ BACKOFF - Cap for exponential backoff (and non-429 Retry-After clamp).
- MESSAGE_
FRAME_ TOKENS - Framing overhead tokens per message (role + separators).
- NUDGE_
THRESHOLD - Consecutive identical tool rounds before a soft nudge reminder.
- ORCHESTRATOR_
DELEGATION_ PROMPT - Orchestrator delegation guidance (host / parent system prompt fragment).
- PLAN
- Plan-mode agent (no execute/spawn tools).
- PROJECT_
AGENTS_ DIR - Default relative directory under a project root.
- PROJECT_
AGENTS_ MD - Default project instruction file relative to a workspace root.
- RATE_
LIMIT_ RETRY_ THRESHOLD - After this many 429 retries, escalate instead of waiting again.
- SPAN_
COMPACT - Compaction pass.
- SPAN_
SAMPLE - One LLM sample call.
- SPAN_
SESSION - Session lifetime span.
- SPAN_
SPAWN - Nested agent spawn.
- SPAN_
TOOL - One tool execution.
- SPAN_
TOOL_ BATCH - Dispatched tool batch.
- SPAN_
TURN - Single turn span.
- SPAN_
WORKFLOW - Workflow run.
- SPAN_
WORKFLOW_ HOST - One workflow host request.
- USER_
AGENTS_ DIR - Relative directory under the user home.
Traits§
- Approval
Gate - Host-supplied gate consulted before running tools that need confirmation.
- Compaction
Strategy - Pure compaction strategy.
- Conversation
State - Mutable conversation backing a turn or session.
- DynTool
- Object-safe tool.
- Isolation
Backend - Prepares (and later tears down) an execution environment for a child agent.
- LlmSampler
- Abstraction over model providers.
- Metrics
Sink - Host-provided metrics backend.
- Prompt
Assembler - Assembles the final system prompt for an agent definition.
- Session
Host - Host capable of spawning nested agents.
- Stop
Gate - Extensible stop-gate. Gates run in order; first non-
GateDecision::Completewins. - Tool
Source - Provides tools that can be merged into a
ToolRegistry. - Turn
Lifecycle Contributor - Lifecycle hooks for a single turn. Default methods are no-ops.
- Workflow
RunStore - Host port for listing and resuming workflow runs.
Functions§
- agents_
md_ path - Resolve AGENTS.md path under a project root (does not read).
- backoff_
for_ attempt - Exponential backoff 2^attempt seconds from 2s, capped, with optional ±20% jitter.
- build_
chat_ completions_ body - Build the JSON body for Chat Completions from a kernel
SampleRequest. - builtin_
definitions - Built-in catalogue (always enabled).
- builtin_
names - Builtin name set (for user-level shadowing skip).
- by_
name_ in_ dir - Find by name in a directory (file stem or frontmatter name).
- by_
name_ resolved - Resolve
namevia multi-level discovery (cwd defaults to current dir). - check_
context_ overflow - Check whether
estimatedexceedswindow * threshold_ratio(clamped). - classify_
http_ status - Classify an HTTP status for the edge-client policy (W2.1).
- decide_
retry - Decide whether to retry after a
MachiError. - default_
probe_ args - Default
argsused when the author does not supply probe input. - discover_
in_ dir - Discover
*.mddefinitions underroot(non-recursive). - discover_
project - Discover under
{cwd}/.machi/agentswhen the directory exists. - discover_
user - Discover user-level agents when the directory exists.
- drain_
terminal - Drain a stream to the terminal result, discarding progress.
- drain_
with_ progress - Drain a stream, collecting progress items and the terminal result.
- error_
code_ for_ http - Map HTTP class + status into a
MachiErrorcode. - estimate_
conversation_ tokens - Estimate tokens for a conversation (re-export of shared estimator).
- estimate_
image_ tokens - Approximate tokens for one image attachment.
- estimate_
text_ tokens - Approximate tokens for a UTF-8 string:
ceil(bytes / 4). - evaluate_
stop_ gates - Evaluate configured gates for the agent against conversation history.
- extract_
meta - Extract
metamap by evaluating the script with dummy host functions noop. - fingerprint_
batch - Stable fingerprint for a batch of tool calls (order-sensitive).
- is_
empty_ response - True when a completed response is empty (retryable
EmptyResponse). - isolation_
error - Map isolation failures to a typed host error.
- load_
file - Load a single file.
- merge_
arc_ sources - Arc-wrapped dynamic source list helper.
- merge_
tool_ sources - Merge multiple sources into one registry.
- nudge_
message - User message carrying a stationarity nudge (for injection into the buffer).
- parse_
chat_ completions_ response - Parse a Chat Completions JSON response into a kernel
SampleResponse. - parse_
definition_ markdown - Parse a definition file: YAML frontmatter between
---fences, body = instructions. - partial_
progress_ frames - Split
inputinto UTF-8-safe partial progress frames. - project_
agent_ dirs - Walk
cwd→ filesystem root collecting existing.machi/agentsdirs (nearest first). - request_
hash - Hash a host request for divergence detection (16 digest bytes → 32 hex chars).
- resolve_
agents - Full multi-level resolve with shadowing (W5.1).
- response_
to_ stream - Convert a complete response into a short stream.
- run_
workflow - Run a workflow script to a terminal outcome.
- run_
workflow_ configured - Full configuration: metrics + side-effect store (scratch / templates).
- run_
workflow_ on_ host - Run a workflow script whose
agent/parallelcalls resolve throughhost. - run_
workflow_ on_ host_ with_ metrics - Like
run_workflow_on_hostwith an explicit metrics sink. - span_
catalogue_ snapshot - Exact newline-joined span catalogue for CI golden comparison.
- terminal_
only - Single-item terminal stream from a completed result.
- user_
agents_ dir - User home agents directory (
$HOME/.machi/agents), when resolvable. - validate_
script - Validate a script with the default agent budget.
- validate_
script_ with_ agent_ budget - Validate with an explicit agent-call budget for the probe host.
- with_
progress - Progress items then a terminal future.
Type Aliases§
- Result
- Result alias using
MachiError. - Sample
Stream - Opaque pinned sample event stream.
- Shared
Metrics - Shared metrics handle.
- Shared
Tool - Shared tool handle.
- Tool
Error - Tool error alias mapped into
MachiError. - Tool
Stream - Opaque pinned stream of tool items.