repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

docs/SPEC.md

Raw

Smith Product Specification

This file is the sole canonical product contract. Normative terms MUST, MUST NOT, SHOULD, and MAY define product requirements. Unless a declaration is explicitly described as shape-level, names, values, paths, formats, signatures, and observable behavior in this document are exact contracts.

Product

Product boundary

Smith MUST be a fast, extensible AI coding agent with:

Cross-crate behavior MUST use explicit typed requests, streams, events, intents, or hooks. Hidden downstream cascades are forbidden. Public interfaces MUST remain small, typed, and honest.

Every user-visible tool, slash command, theme, keybinding, prompt, layout, and feature UI MUST be supplied as a Lua plugin. Binary commands provide process lifecycle and transport entrypoints only. Built-in and user plugins MUST receive the same SDK.

Smith MUST NOT depend on Pi or couple to Pi APIs, data, or formats.

Files, wire formats, CLI behavior, configuration, and Lua SDK boundaries are exact. Internal Rust declarations are shape-level contracts unless this specification explicitly makes a symbol or representation exact.

First run

Running smith in an unconfigured workspace MUST apply defaults without a wizard, onboarding flow, or setup prompt. Capabilities MUST be probed once and failures MUST be interpreted conservatively.

The default Lua layout plugin MUST render:

All optional bordered panels MUST initially be closed and MUST be strictly opt-in. Empty history MUST show a few dim hints containing the active model, how to begin, and smith help; those hints MUST disappear after the first entry. Startup MUST make the interactive product ready in less than 100 ms.

Missing authentication

Authentication resolution MUST complete before the first provider stream. Failure MUST be fast, recoverable, and rendered in history. A missing-authentication diagnostic MUST name:

The unsent message MUST remain in the input for immediate resend. Smith MUST NOT start a setup flow.

Active work

Assistant text and thinking UI MUST update incrementally as provider events arrive. Tool calls MUST initially render as collapsed one-line entries and MUST expand when selected. Cost and context usage MUST update live in the status bar.

Input beginning with !, such as !cargo test, MUST execute directly and create a user-bash session entry. Session entries MUST also be capable of representing !! user-bash commands and their output.

Every successful mutating tool MUST invisibly record a VCS operation. Smith MUST NOT prompt for commits or expose the underlying VCS implementation.

Steering and follow-ups

Submitting normal input during an active run MUST queue a steer. Submitting with the configured modifier MUST queue a follow-up. The combined queue MUST render between history and input.

A steer MUST let already-running tools finish, skip tool calls not yet started, insert the steering messages, and make the model re-plan. Cancel actions MUST remove queued items newest-first; a user cancel MUST abort only when the queue is empty. Queue contents are process-ephemeral and MUST be empty after session continuation.

Independent navigation axes

Conversation navigation, workspace restoration, and replay MUST remain distinct:

  1. /tree MUST display the append-only session tree and permit switching the current leaf to an earlier entry. Switching MUST rewind conversation context without changing workspace files. Sending from a historical entry MUST silently create a sibling path in the same session.
  2. Workspace time travel MUST navigate the VCS operation timeline independently. The timeline MUST show operations associated with entries, inspect operation diffs, and restore an earlier operation. /undo and the timeline MUST restore the applicable earlier operation. The timeline MUST offer restoration of the operation recorded at the current conversation entry without coupling leaf movement to restoration.
  3. Replay MUST read a recorded trace and MUST never execute against or mutate the live session. Visual replay and compare execution are replay operations, not conversation or VCS navigation.

A plugin MAY offer a combined action that explicitly invokes both leaf switching and smith.vcs.op_restore, but the underlying axes MUST remain separately addressable.

Model selection

ctrl+l MUST cycle a configured model shortlist. /model MUST open a fuzzy picker. Both MUST primarily expose resolver names—aliases, groups, and buckets—and the picker MUST show each name's resolved plan. Raw provider/model IDs MUST remain available only as a fallback interface.

Exit, continuation, attachment, and replay

Quitting and every fatal path MUST restore the terminal.

smith continue MUST resume the latest session for the current working directory at the same current leaf, with empty process queues and accumulated cost still visible. smith attach without an identifier MUST fuzzy-pick among sessions.

smith replay <session> --speed 2 MUST visually replay the selected trace at twice recorded speed. --compare MUST re-execute tools in a replay execution context and diff new outputs against recorded outputs. Replay MUST not write to the source session or invoke tools against its live agent state.

Architecture

Crates

Crate Required responsibility
smith Foundation types, StreamFn, AgentTool, configuration, Lua runtime, and shared errors; no business logic.
smith-core Agent loop, sessions, tools, hooks, compaction, cost, traces, and replay.
smith-ai Providers, authentication, model registry, provider streams, and MuxProvider.
smith-tui Terminal events, widgets, layout primitives, render loop, and themes.
smith-harness Orchestration, plugin system, SDK, event bridge, built-ins, and help.
smith-cli Executable entrypoint, CLI, session commands, eval, RPC, and replay dispatch.

Internal dependency graph

Crate MAY depend on
smith no internal crate
smith-core smith
smith-ai smith
smith-tui smith
smith-harness smith, smith-core, smith-ai, smith-tui
smith-cli smith, smith-harness

Consequently:

Runtime Files

Product directories

config_dir, data_dir, and cache_dir mean the final Smith-specific directories below. Callers MUST NOT append another smith component.

Platform config_dir data_dir cache_dir
Linux ~/.config/smith/ ~/.local/share/smith/ ~/.cache/smith/
macOS ~/Library/Application Support/smith/ ~/Library/Application Support/smith/ ~/Library/Caches/smith/
Windows %APPDATA%\smith\ %LOCALAPPDATA%\smith\ %LOCALAPPDATA%\smith\cache\

When platform paths coincide, their children MUST coexist in that directory. The required layout is:

<data_dir>/
  sessions/
    {session-id}.session
    {session-id}.trace
  plugins/
    <org>/<name>/
  data/
    <org>/<name>/
  vcs/
    {project-hash}/
      jj-state/

<cache_dir>/

<config_dir>/
  config.lua
  auth.json

Workspace-local plugins MUST live at .smith/plugins/<org>/<name>/.

Persistent formats

{session-id}.session MUST be an unencrypted sequence of length-prefixed CBOR records. Its canonical filename MUST be exactly {session-id}.session. The initial metadata record(s) MUST expose enough session-header information for metadata-only discovery without reading the complete body.

{session-id}.trace MUST be a compressed deterministic replay log as specified under Core. Session and trace paths MUST be derived from the same SessionId.

Plaintext secrets MAY be persisted only in secret-registration session entries and auth.json under the local trust model. Other session content and every trace representation MUST obey the secret-proxy rules.

VCS state

VCS state MUST live at data_dir/vcs/{project-hash}/jj-state. The only Smith-managed VCS state item placed in the workspace root MUST be a .jj symlink. In a colocated Git workspace, git_target MUST be rewritten to the absolute .git path. Plugins MUST see only the stable smith.vcs.* contract, never implementation-native objects.

Shared Contracts

Required smith exports

The smith crate MUST expose:

IDs, roles, content, and messages

The required ID types are:

Role MUST have exactly these variants:

System | User | Assistant | Tool

ContentBlock is the authoritative message-content representation and MUST support exactly these shapes:

Text(String)
Image { data, media_type }
ToolCall { id, name, arguments }
ToolResult { id, result, is_error }
Thinking { content, provider_metadata? }

ToolCall.arguments MUST be JSON. provider_metadata MUST be opaque: Smith MUST preserve, store, and replay it without interpretation or consumption. Provider adapters MUST attach metadata required for later turns, including signed-thinking signatures.

Message MUST contain role and a list of ContentBlock values named content. Roles identify speakers; session-entry kinds identify events. A tool result MUST be a Tool-role message containing ToolResult; a distinct tool-result role is forbidden. User bash execution and similar activity MUST be represented by session-entry kinds, not new roles.

Provider types

ProviderUsage MUST track:

input_tokens
output_tokens
cache_read_tokens
cache_write_tokens
total_tokens

StopReason MUST have exactly:

EndTurn | ToolUse | OverMaxTokens | Aborted | StopSequence | Error

ThinkingLevel MUST have exactly:

Off | Minimal | Low | Medium | High | XHigh

ProviderEvent MUST support:

TextDelta { text }
ThinkingDelta { text, provider_metadata? }
ToolCall { id, name, arguments }
Done { usage, stop_reason }
Error(ProviderError)

ThinkingDelta.provider_metadata is optional and opaque. An adapter MUST attach it to the delta whose thinking text it authenticates. A provider-boundary ToolCall MUST be complete; vendor-specific partial argument chunks MUST be joined before crossing this boundary.

ProviderError MUST classify failures with exactly these variants, each carrying a message:

RateLimit
AuthFailed
Network
ServerError
InvalidRequest
ModelNotFound
Timeout

ProviderRequest MUST contain:

messages
system_prompt
model_id
provider_id
tool_definitions
thinking_level
token_limit
stop_sequences

Tool types

ToolDefinitionSpec MUST be serializable metadata suitable for LLM function calling and plugin metadata. ToolDefinition MUST be the runtime definition consumed by providers and the agent loop.

AgentTool MUST be asynchronous, Send, and Sync. ToolExecutionMode MUST select sequential or parallel execution according to tool metadata.

AgentToolResult MUST contain content blocks, an error flag, and optional updates. AgentToolUpdate is version-1 completion metadata: updates MUST appear in the final AgentToolResult and MUST NOT stream live while a tool is running.

Tool arguments MUST be JSON and MUST be validated against the tool's JSON Schema before execution.

StreamFn

StreamFn is the provider abstraction consumed by smith-core:

ProviderRequest -> asynchronous stream of ProviderEvent

It MUST have no dependency on smith-ai.

The agent loop MUST assemble consecutive ThinkingDelta events into one ContentBlock::Thinking by concatenating text in arrival order. Every non-empty metadata value MUST enter the assembled block. Multiple values MUST be stored in arrival order within its opaque metadata payload. Smith MUST NOT interpret those values. This assembly MUST be the sole route by which signed-thinking metadata crosses StreamFn into persisted content and later provider replay.

Restricted LuaRuntime

LuaRuntime MUST provide LuaJIT with custom require searchers. Only these standard libraries are permitted:

string, table, math, coroutine, utf8, package

package MUST use only the host's custom searchers. The following globals MUST be removed:

io, os, debug, getfenv, setfenv

Host APIs MUST be obtained with:

local smith = require("smith")

Lua bytecode caching is forbidden. Every Lua source load, including manifests, configuration, plugin entry files, required modules, and content stored in a .lua file, MUST explicitly request text-only chunk mode. Binary chunks and binary auto-detection MUST be rejected.

Configuration

Lua MUST be the configuration language. Rust MUST define and validate schemas; Lua MUST supply values. Effective configuration MUST apply these layers from lowest to highest precedence:

  1. Rust type defaults and schema;
  2. built-in Lua defaults;
  3. plugin contributions;
  4. config_dir/config.lua;
  5. CLI flags.

Later layers MUST override earlier layers. Cross-layer merging MUST recursively merge leaf fields for table-valued keys. Scalars and lists are leaves and MUST replace prior values wholesale.

Invalid values MUST produce clear path-qualified errors. Unknown keys MUST warn in the top-level schema context. Unknown keys MUST fail in strict contexts, including every models.* and compaction.* context where a typo could silently change behavior.

The full applicable cascade MUST be re-evaluated on runtime host-configuration reload. A valid configuration includes this shape:

return {
  theme = "catppuccin",
  keybindings = {
    ["ctrl+l"] = "cycle_model",
    ["ctrl+c"] = "abort",
  },
  tools = { "read", "write", "edit", "bash" },
  model = "anthropic/claude-sonnet-4",
}

Models, aliases, groups, and buckets

ModelMetadata MUST include provider ID, model ID, context window, maximum output tokens, cost when known, and capabilities for thinking, vision, tool use, and streaming.

ModelResolver MUST resolve through this chain:

requested name -> alias -> group -> bucket/account -> provider/model metadata

Resolution MUST perform no I/O. resolve MUST be a pure function of validated configuration, requested name, and rotation cursors. Identical inputs and cursors MUST yield an identical ordered plan. MuxProvider, not the resolver, MUST own cursors and advance each rotation node by one step per provider request.

Configuration loading and reload MUST validate the whole graph and MUST:

After successful validation, an unknown requested name MUST be the only resolution-time error.

Duplicate candidates reached through distinct DAG paths to the same provider/model/account MUST survive resolver flattening. MuxProvider MUST deduplicate identical candidates immediately before attempting them. ResolvedModel MUST carry all metadata required by smith-core.

FailoverStrategy MUST support ordered and round-robin. BucketStrategy MUST define account rotation, and every account in a bucket MUST be an individual failover candidate. providers.retry_count MUST configure general retry count and default to 2.

Shared errors

SmithError MUST wrap subsystem errors for:

Recoverability MUST be the default. A recoverable failure MUST become user- or model-visible content—such as an error tool result, history diagnostic, UI notification, or plugin diagnostic—and MUST leave the process able to continue.

Provider failures where another operation remains possible, tool errors, plugin faults, plugin out-of-memory errors, and rejected configuration reloads MUST be recoverable. A failure MUST be fatal only when safe continuation is impossible, including unrecoverable terminal state, invalid startup configuration, or exhaustion of every provider during non-interactive eval. Fatal paths MUST restore the terminal, emit a diagnostic, and exit nonzero.

Shipped library code MUST NOT panic on external failures or plugin input. Impossible internal states MAY use debug assertions.

Core

Agent runtime

The agent loop MUST accept an AgentContext, AgentLoopConfig, StreamFn, tool registry, and event sender. It MUST stream provider responses, emit AgentEvent values, execute tool calls, process steering and follow-ups, and continue until a stop criterion is met.

The loop MUST use:

AgentLoopConfig MUST support:

Every runtime state MUST be interruptible. Ctrl+C and programmatic abort MUST set an abort signal. Provider streaming and tool execution MUST observe it and terminate cleanly, subject only to the non-preemptible Lua rule under Concurrency.

Follow-up and steering semantics

Follow-ups MUST be held FIFO. Immediately before a run would emit AgentEnd, the loop MUST inspect the follow-up queue. If one exists, it MUST dequeue it as a fresh user message and begin a new outer turn cycle instead of ending.

A steer MUST be delivered at the next safe boundary: after the current provider stream completes or after in-flight tools finish. Before the next provider request, all queued steers MUST drain FIFO as user messages.

Once a steer is queued during parallel tool execution, no additional call from that assistant message may start. Calls already started MUST finish. Calls never started MUST receive error-flagged synthetic tool results whose content is exactly skipped: user steered.

A steer arriving during provider streaming MUST cause every tool call produced by that assistant message to skip; none may execute. Parallel transcript ordering MUST be:

  1. real results in completion order;
  2. synthetic results in original tool-call order; then
  3. drained steering messages in FIFO order.

Every skipped call MUST emit ToolExecutionStart and ToolExecutionEnd. The end event MUST carry the error flag and skip reason. Every tool call represented on a provider wire message MUST ultimately receive a result unless abort occurs before any subsequent request can carry synthetic results.

Interactive active-run input MUST default to steering; a modifier MUST select follow-up. Plugins MAY override default input behavior through the input hook and MAY send messages through smith.send_message.

Both queues MUST remain process-ephemeral. An item MUST become a session entry only when delivered, so persisted sessions contain only messages seen by the model. Compaction MUST neither consume nor discard queued messages.

A user cancel MUST pop queued items according to TUI queue rules before aborting. Programmatic abort MAY be delivered independently; after any delivered abort, undelivered queue items MUST remain available for sending, editing, or discarding. An aborted assistant tail MAY contain tool calls without results. Request assembly after resume MUST repair that tail by synthesizing aborted results for every unanswered call.

Agent and engine events

AgentEvent MUST be the source of truth for agent behavior and MUST include:

AgentStart, AgentEnd
TurnStart, TurnEnd
MessageStart, MessageUpdate, MessageEnd
ToolExecutionStart, ToolExecutionUpdate, ToolExecutionEnd
TextDelta, ThinkingDelta
Error

AgentEvent::to_session_entry(timestamp) MUST return a SessionEntry only for completed, conversation-relevant events. Streaming deltas and incomplete lifecycle events MUST NOT independently become transcript entries.

EngineEvent MUST wrap AgentEvent and add events for session lifecycle, steering and follow-up handling, UI state changes, provider and model changes, errors, and shutdown. Every frontend MUST consume EngineEvent and submit typed intents. TUI-private panel, resize, selection, focus, and scrolling variants MAY remain private to the in-process frontend and MUST NOT be exposed out of process.

Core hooks

The hook API MUST provide these exact result types and choices:

A blocked tool call MUST NOT execute. It MUST still emit ToolExecutionStart and ToolExecutionEnd; the end MUST carry an error flag and block reason. The provider MUST receive the reason as an error tool result. Lua event-return tables MUST be translated into these core types.

Session model

Session MUST contain:

SessionId
optional name
cwd
entries
current leaf
created timestamp
updated timestamp

A session MUST be an append-only branching tree with one writer at a time. Only one agent loop may append. A branch MUST be derived as the root-to-leaf path, never stored as a separate mutable object. ctx.session.branch() MUST return the current path. Existing entries MUST never be rewritten. Continuing from an older entry MUST append a new child and create an in-tree fork silently.

Append behavior:

Leaf-switch behavior:

Path reads MUST return only root through current leaf. LLM context MUST use only that path after compaction folding; siblings MUST remain invisible.

Session forking is distinct from in-tree branching. Forking MUST clone entries through a specified entry into a new SessionId and new session file and MUST emit session_before_fork. Version 1 MUST NOT support branch deletion or pruning.

If recovery loses a parent, its subtree MUST remain detached, be reported as orphaned, remain unreachable from the root, and MUST NOT be grafted elsewhere. Conversation navigation alone MUST never alter files. Filesystem time travel remains plugin policy and MAY explicitly pair a switch with the entry's VcsOpId through smith.vcs.op_restore.

Session entries and codec

Every SessionEntry MUST have a stable EntryId, optional parent, and timestamp. Supported variants MUST include:

Readers MUST preserve a well-formed unknown entry variant as raw data so future variants survive rewrite or migration round trips.

The file framing is exact:

u32 BE len | CBOR entry bytes | u32 BE len | CBOR entry bytes | ...

Recovery MUST obey these boundaries:

smith session dump MUST emit JSONL. Session discovery MUST recognize only canonical {session-id}.session names.

Secret proxy

Registry and registration

The secret registry MUST map each SecretId to plaintext and a label. Core masking MUST operate only on registered secrets; discovery or heuristic detection MUST remain plugin-defined.

Registration paths are:

Detection plugins MAY inspect input and tool_result hook content and register values. Registration MUST:

Placeholder parsing MUST consume the maximal digit run: smith:sec:12 means ID 12, never ID 1 followed by 2.

Ingestion masking

Masking MUST use exact, case-sensitive, encoding-sensitive substring matching against registered plaintext. It MUST run before content becomes a normal session entry and after the plugin input or tool_result hook, allowing a hook to register a value and mask that same content.

Matching MUST be longest-match-first in one left-to-right pass. Emitted placeholders MUST NOT be rescanned. Plaintext MUST occur in session entries only inside secret-registration entries. On resume, the registry MUST rebuild by scanning those entries backward.

Pre-transform input MUST NOT be persisted. Only post-hook, post-transform content is scanned. If a hook re-encodes a registered secret, that derived representation is outside protection.

Rehydration

A placeholder MUST be rehydrated only immediately before tool execution, including subprocess execution and Rust or Lua execute calls. Rehydration MUST be one pass and produced plaintext MUST NOT be rescanned. Ordinary session content, provider requests, trace files, and public events MUST contain placeholders, not plaintext. Secret-registration public events and traces MUST expose only ID/label/redacted data even though the session registration record retains plaintext.

Compare replay MUST obtain plaintext from secret-registration entries in the source session file and MUST NOT obtain it from the trace. An unknown placeholder ID MUST pass through unchanged without error.

Display and local trust

The TUI MUST display a placeholder as a masked label, for example ‹secret: provider-token›. Displayed content MUST correspond to the same masked context content. smith.secret.list() and RPC MUST never reveal plaintext. A trusted local user MUST be able to recover registration plaintext through the local CLI smith session dump; RPC dump MUST redact it.

An unregistered secret receives no protection. Core MUST NOT guess secrets. The protection target is the remote LLM/provider boundary, not the trusted local user, plugins, or files.

System prompt

SystemPromptBuilder MUST compose:

Plugins MAY transform prompts only through typed hooks. Hidden global mutation is forbidden. The prompt MUST tell the agent to discover capabilities through smith help --search, smith help --guide, and smith help --example; it MUST NOT embed the complete SDK reference.

Append-only compaction

Compaction MUST neither rewrite nor delete history. Storage MUST retain every entry verbatim and remain memory-bounded through lazy loading.

A pass MUST append a summary entry on the current path containing:

from: EntryId
to: EntryId
summary text
before token estimate
after token estimate

Context assembly MUST fold only the current root-to-leaf path. Summary-covered spans MUST collapse to their summary; trim-masked tool results and thinking MUST collapse to stubs. Raw storage MUST remain unchanged.

Switching to an entry before a summary MUST expose a path without that summary, restore full visibility on that path, and permit a sibling summary. A descendant path created after a compaction point MUST inherit its mask.

A valid covered span MUST be one contiguous ancestor segment of the path on which the summary was appended: from MUST be an ancestor of to, and to an ancestor of the summary. A span crossing a fork or violating those rules MUST be diagnosed and ignored in full; its raw content MUST appear without partial collapse.

Re-compacting an already compacted path MUST cover the prior summary entry. Folding MUST apply the outermost, latest covering span, subsuming nested inner summaries. Metadata in a covered span MUST fold with it. Leaf resolution and trace/session replay MUST always read raw storage, not folded context.

Compaction trigger, budget, and ladder

Before every agent provider request except a summarization request, compaction MUST trigger only when estimated folded-path tokens strictly exceed:

threshold = floor(threshold_fraction × context_window) − output_reserve_tokens

The strict compaction.* schema MUST expose reloadable threshold_fraction, output_reserve_tokens, recency_fraction, reserve_fraction, iteration_limit, and compaction_model values. It MUST reject:

recency_fraction + reserve_fraction >= threshold_fraction

A round MUST run synchronously at that sole trigger site and MUST NOT re-enter itself. If the protected recency window alone exceeds the threshold, it MUST report that condition and stop. If a ladder pass makes no progress, the round MUST abort.

The ladder MUST run in this order and repeat until context fits or iteration_limit is reached:

  1. mask old tool-result bodies to stubs;
  2. mask old thinking blocks; then
  3. summarize the oldest eligible span with an LLM.

Summarization MUST use the active model unless compaction_model chooses another. Aliases and groups MUST resolve normally. Summarization usage MUST enter normal cost accounting.

Every round MUST protect from ladder trimming:

Protection from the ladder does not exempt an entry from a later valid covering fold.

At the iteration limit, the round MUST terminate, report, and let the provider request proceed over budget. session_compact MUST report exactly one of:

fit | iteration-limit | no-progress | recency-dominates

The blockable session_before_compact hook MAY veto the round, adjust its span, or replace its summarization prompt. session_compact MUST report the resulting outcome.

Token and cost accounting

Version 1 token estimation MUST use chars / 4; an exact tokenizer is not required. Cost tracking MUST consume ProviderUsage, multiply known usage categories by ModelMetadata.cost, and track input, output, cache-read, cache-write, total tokens, and running total cost. A model whose pricing is unknown MUST be excluded from monetary cost tracking rather than treated as zero-cost.

Tool registry

ToolRegistry MUST store shared, thread-safe AgentTool handles by name. Duplicate registration MUST follow plugin precedence. Arguments MUST be JSON-Schema validated. Final failures MUST become error tool-result content visible to the model. A transient tool failure MAY retry only according to that tool's policy.

Trace and replay

A trace MUST have a header containing magic, version, and session ID. It MUST use block-level zstd compression with approximately 4 KiB blocks.

Traces MUST capture, in order:

A state snapshot MUST contain the current leaf, both message queues, and abort flag. Secret-registration trace records MUST redact plaintext idempotently. Compare rehydration MUST use the session file, never trace data.

Trace processing MUST preserve event order and contain enough information to reconstruct session state. Replay MUST support visual replay, real-time playback, a speed multiplier, maximum-speed reconstruction, old/new tool-output comparison, and fast-forward to a turn range.

Replay MUST read the trace without modifying the source session. Compare mode MUST re-execute tools and diff outputs. Tool execution MUST use --sandbox <path> when supplied; otherwise mutating comparison MUST use an isolated temporary replay workspace, never the live session state.

AI

Provider contract

Provider MUST be thread-safe and object-safe and expose:

stream MUST be a plain method returning a stream, not an async method. provider_to_stream_fn MUST adapt a shared Provider handle into the StreamFn consumed by core.

Required providers and normalization

Smith MUST integrate:

Each adapter MUST normalize its vendor wire format into ProviderEvent and handle at its boundary:

If a streaming request receives a non-streaming JSON error body, including with HTTP status 200, the adapter MUST emit ProviderEvent::Error and MUST NOT wait indefinitely for SSE frames.

Bundled model registry

smith-ai/src/providers.json MUST be bundled into the product and authoritative at runtime. Its canonical bundled schema MUST be smith-ai/src/providers.schema.json and MUST use the models.dev provider/model shape.

The bundled registry and every provider table passed to smith.provider.register MUST satisfy the full schema. Unknown fields MUST be legal through additionalProperties, preserved semantically, and ignored when version 1 does not consume them. replace_models MUST be the provider-override flag for replacing a provider's models.

A model record MUST support:

cost MUST NOT be scalar. Missing cost means unknown pricing: the model MUST be omitted from cost tracking and MUST NOT default to zero. An absent capability is unknown, MUST act as false for gating, and MUST remain absent when preserved.

Eligible records MUST map to ModelMetadata as follows:

ModelMetadata field Registry source
context window limit.context
maximum output tokens limit.output
cost cost
thinking reasoning
vision presence of "image" in modalities.input
tool use tool_call
streaming true unless provider configuration disables it

structured_output, temperature, and attachment MUST be preserved in the registry but MUST NOT appear in version-1 ModelMetadata.

Only chat-capable models may map: modalities.output MUST contain "text", and limit.context MUST be greater than zero. Image/video generators with zero context MUST remain in the registry but MUST NOT resolve as chat models.

Authentication

The auth resolver MUST support credentials from:

Smith MUST NOT use an OS keychain or encrypt credential storage. Every loaded credential MUST be registered with the secret proxy. Authentication errors MUST be resolved before the first provider stream.

Each provider's registry auth_types map MUST declare supported methods:

AuthMethod MUST mirror exactly api_key, oauth, and organization.

auth.json MUST be a per-provider object map, for example:

{
  "anthropic": {
    "access_token": "...",
    "refresh_token": "...",
    "expires_at": 1234567890
  }
}

Provider OAuth configuration MUST support:

id
name
auth_url
token_url
scope
client_id

Stored OAuth credentials MUST contain access_token, refresh_token, and expires_at as Unix seconds. Expired credentials MUST refresh automatically.

/auth login <provider> MUST:

  1. surface the authorization URL;
  2. receive the authorization code from a local callback HTTP server on a random port or manual paste;
  3. exchange the code for credentials; and
  4. persist them to config_dir/auth.json.

OAuth MUST permit mocked flows and provider-specific configuration.

MuxProvider

MuxProvider MUST wrap providers/accounts for resolved groups and buckets. It MUST consume the deterministic resolver plan, deduplicate identical provider/model/account candidates before attempts, and apply this exact policy per candidate:

ProviderError Required behavior
RateLimit Fail over immediately.
AuthFailed Retry providers.retry_count, then fail over.
Network Retry providers.retry_count, then fail over.
ServerError Retry providers.retry_count, then fail over.
InvalidRequest Do not retry; fail over immediately.
ModelNotFound Do not retry; fail over immediately.
Timeout Retry once, then fail over.

Authentication validation and any resulting AuthFailed handling MUST occur before opening a provider stream. providers.retry_count MUST default to 2. Rate limiting MUST never consume retries. When all candidates are exhausted, MuxProvider MUST emit ProviderEvent::Error; exhaustion in eval mode MUST be fatal.

TUI

Frontend boundary

smith-tui is the built-in in-process frontend. It MUST consume EngineEvent and return intents for prompt submission, steering, commands, and abort. It MUST NOT be privileged as the only UI. smith rpc MUST expose the same event-out/intent-in engine boundary for external frontends.

An out-of-process frontend MUST be an RPC client and MUST NOT link Smith Rust code. Terminal cells, borders, widgets, buffers, and Rect rendering are terminal-only. Other frontends MUST consume engine events/intents and render independently.

Normalized events

TuiEvent MUST normalize:

Keyboard events MUST include normalized key code, modifiers, and kind press, repeat, or release. Mouse events MUST include button, scroll, position, and modifiers.

Terminal capabilities

TerminalCapabilities MUST record:

truecolor
undercurl
Kitty keyboard protocol
bracketed paste
focus events
mouse support
Kitty graphics
sixel

Capabilities MUST be probed directly without a terminfo database, once per session startup, with a 100 ms timeout per probe. Probes SHOULD run concurrently so they do not extend the product startup budget. Timeout MUST mean absence. Unsupported optional behavior MUST silently degrade to plain text.

Image protocol MUST use ImageProtocol::{Kitty, Sixel}. Detection is required, but version 1 MUST NOT render inline images.

Kitty keyboard flags MUST be pushed on TUI startup and popped on every shutdown path, including errors and signals. When synchronized output is supported, each render pass MUST be enclosed by CSI ?2026 h and CSI ?2026 l.

Components and lifecycle

Components MUST render deterministically into terminal buffers, handle normalized TuiEvent, manage focus explicitly, report whether an event was consumed, and explicitly invalidate cached state.

TuiApp MUST follow:

new -> enter terminal -> event/render loop -> shutdown -> restore terminal

The render loop MUST tick every 16 ms. Event polling MUST run on a blocking thread and send normalized events through channels. smith-harness MUST create and drive TuiApp.

Application states MUST be exactly:

Idle | Thinking | ToolRunning | ToolResult | Error | Exiting

Every state MUST be interruptible.

Widgets

The TUI MUST provide:

Overlay and layout contracts

Overlays, including modals, fuzzy search, and autocomplete, MUST support anchors Center, all four corners, and all four edge centers; offset_x; offset_y; optional margin; and width/max_height as Size::Absolute(cells) or Size::Percent.

Rust MUST provide layout primitives; Lua MUST define layout trees. Required primitives are:

One predefined border layout MUST expose center, north, east, south, and west panels. Every panel MUST carry visible, size, and its own layout. Empty panels MUST be invisible. The default layout MUST be a Lua plugin.

Composition is exact:

Layout ownership and resolution

Layout resolution MUST NOT enter Lua on a render path. On set_center_layout or set_*_panel, the harness MUST convert the Lua tree once to an owned Rust LayoutTree and drop the Lua value.

LayoutTree MUST retain no Lua handle and MUST be Send + 'static, allowing off-render-thread construction. Every frame MUST use a pure resolver:

(LayoutTree, terminal size) -> Rect for each widget slot

Equal inputs MUST produce equal outputs with zero frame-loop Lua calls. Across terminal sizes 80×24 through 400×100, resolution SHOULD remain approximately 0.4 µs and release-build p99 MUST remain below 0.8 µs.

Themes

A theme MUST be a Lua table validated by a Rust schema. Named nested tables MUST cover status bar, messages, assistant content, tool calls, tool results, errors, input, borders, selections, diffs, syntax groups, and accents. Every named section MUST contain color and style values.

Colors MUST be #rrggbb. Named or ANSI-indexed colors MUST NOT be accepted by the version-1 schema. Missing required keys and malformed values MUST produce the exact path, for example:

theme.status_bar.fg: expected "#rrggbb"

Unknown keys MUST warn. An invalid user theme MUST NOT abort Smith; the built-in default MUST be activated and a visible warning MUST name the path error.

History and tool rendering

History MUST use virtual scrolling. sticky_bottom MUST default to true. Upward user scrolling MUST set it to false; while false, new content MUST NOT move the viewport. Following MUST resume when the user reaches bottom or submits input.

Tools MAY register Lua renderCall and renderResult renderers. The harness MUST translate their output to structured render instructions. A plugin MUST NOT write arbitrary terminal output through this mechanism.

Combined input queue

Steers and follow-ups MUST render as one visually combined queue between history and input:

Version-1 TUI exclusions

Version 1 MUST NOT provide:

Harness and Lua SDK

Harness composition

smith-harness MUST load configuration, model registry, and authentication; resolve the active model; create providers and StreamFn; create the agent; load/manage plugins; expose the Lua SDK; bridge core and plugin events; translate plugin returns to core hooks; and coordinate TUI, eval, and RPC modes.

Harness MUST contain:

Agent
provider map
ModelRegistry
ModelResolver
authentication resolver
PluginManager
optional TuiApp
active provider
active model

Plugin identity and locations

Every plugin name is mandatory and MUST be:

<org>/<name>

Both components MUST contain only lowercase ASCII letters, digits, _, and -. smith/* is reserved for built-ins. Installed global code MUST live at data_dir/plugins/<org>/<name>/; workspace code MUST live at .smith/plugins/<org>/<name>/; persistent plugin data MUST live at data_dir/data/<org>/<name>/.

Manifest

Every plugin root MUST contain smith-plugin.lua. The manifest chunk MUST run in an empty environment with no globals, Smith SDK, or host I/O and MUST only construct and return pure data. Access to os, require, or any other global, and any function-valued field, MUST reject the manifest.

Required fields are:

return {
  name = "org/name",
  version = "0.1.0",
  entry = "init.lua",
}

Optional fields are:

smith_api
description
license
authors
repository
dependencies
secrets
heap_limit
interfaces
implements

heap_limit is bytes. interfaces lists exported interface descriptors; implements lists implemented interface names. If omitted, smith_api MUST default to integer generation 1. The host MUST validate the manifest before executing entry code.

Plugin API compatibility

Plugin API versions MUST be integer generations, not semantic-version ranges. Generation 1 is the default. From Smith 1.0.0 onward, generation 1 MUST remain supported permanently. Future breaking APIs MUST use explicit generations 2, 3, and later.

A plugin MUST opt into a newer generation explicitly. A generation newer than the host supports MUST prevent loading. smith plugins MUST list the plugin as disabled and report both required and supported generations; silent or best-effort loading across an unknown generation is forbidden.

Loading and registration precedence

A plugin entry MUST return a registration table or factory. Loading MUST occur in this order:

  1. Load the manifest in its isolated environment.
  2. Validate name, version, source, API generation, dependencies, and declared secrets.
  3. Load entry Lua source in the restricted runtime.
  4. Collect registrations.
  5. Materialize host-side handles.
  6. Register tools, events, commands, providers, interfaces, and TUI contributions.

Lua registration is canonical. Smith MUST NOT expose a Rust trait-object plugin API.

Plugins MUST load by precedence:

  1. built-ins;
  2. global user plugins;
  3. workspace-local plugins;
  4. explicit CLI/configuration overrides.

Later registrations MUST override earlier registrations unless a registration explicitly defines duplication as an error.

Installation and uninstallation

Version 1 MUST install from a local directory or Git URL and MUST NOT require or expose a central plugin registry.

smith install <path-or-git-url> [--force]

Installation MUST:

  1. resolve the source into temporary staging;
  2. read and validate manifest, namespace, and API compatibility in staging outside the global plugin root;
  3. leave the entire global plugin root untouched on failure;
  4. copy validated code to data_dir/plugins/<org>/<name>/;
  5. refuse an existing destination unless --force is present; and
  6. never execute entry code during installation.

Any existing destination directory is a duplicate regardless of version. --force MUST fully replace code while preserving data_dir/data/<org>/<name>/. A Git installation MUST omit .git and produce an immutable file snapshot; update is reinstallation.

smith uninstall <org>/<name> [--purge-data]

Uninstall MUST remove installed global code, retain plugin data by default, remove data_dir/data/<org>/<name>/ only with --purge-data, and MUST NOT remove a workspace-local plugin.

Plugin interfaces

An interface package MUST export a pure-data descriptor with:

The same descriptor MUST drive runtime validation and generated LuaLS stubs using ---@class, ---@field, and ---@param. Interface-only, implementation-only, externally referenced implementation, and combined interface/implementation packages MUST all work through manifest interfaces and implements.

An adapter entry MUST export:

adapts = "<org>/<name>"

and a make(wrapped) factory returning a conforming implementation. The manager MUST inject the wrapped plugin's exports into make.

Configuration MUST select an implementation with:

interfaces = { ["community/subagent"] = "org/name" }

Binding precedence is:

  1. explicit configuration;
  2. otherwise, the last-loaded plugin declaring implements for that interface.

Conformance MUST be checked at bind time. Failure MUST report the plugin, interface name/generation, every missing or malformed export with exact path, exports actually provided, and any adapter installed for that plugin.

Consumers MUST receive a view exposing only declared functions; private fields MUST be hidden. Calls MUST validate descriptor arguments and name the failing function and parameter. Each resolved binding MUST be a singleton shared by all consumers.

Plugin event bridge

Every Lua event table MUST contain type. The catalog and blocking behavior are:

Event May block Required behavior
resources_discover No Contribute skill, prompt, and theme paths.
session_start, session_shutdown No Report started/loaded/reloaded and shutdown lifecycle.
session_before_switch Yes Run before leaf/session switching.
session_before_fork Yes Run before session clone/fork.
session_before_compact Yes Customize or block compaction.
session_compact, session_tree No Completed notifications.
before_agent_start No May inject messages or modify system prompt.
agent_start, agent_end, turn_start, turn_end No Agent lifecycle.
model_select No Active model changed.
message_start, message_update, message_end No Message streaming lifecycle.
thinking_delta, text_delta No Token deltas.
tool_execution_start No Execution began or call was blocked.
tool_call Yes Runs before execution.
tool_execution_update, tool_result, tool_execution_end No Updates and completion; tool_result may modify result.
input No Intercept, transform, or mark input handled.
user_bash No User ! and !! commands.
context No Modify messages before an LLM call.
before_provider_request, after_provider_response No Inspect/replace request; observe response.
config_changed No Carries changed configuration paths.
plugin_loaded, plugin_unloaded No Plugin lifecycle.
panel_toggle, resize No TUI lifecycle.
provider_registered No Emitted after provider addition/override.
VCS events No Report VCS operations.
error events No Report classified errors.
shutdown No Host shutdown.

Handler return contracts are exact:

-- tool_call
{ block = true, reason = "..." }
{ args = replacement }
{ cancel = true }
nil -- or {}, allow

-- tool_result
{ content = replacement }
{ retry = true }
{ cancel = true }
nil -- keep original

-- turn_end
{ stop = true } -- ShouldStopAfterTurn
nil             -- continue

-- input
{ action = "handled" | "continue", text = transformed_or_nil }

-- context
{ messages = modified }
nil

-- session_before_*
{ block = true, reason = "..." }
nil

All other return values MUST be ignored. The bridge MUST translate accepted returns into AgentLoopConfig hooks.

Extension contexts

The SDK MUST expose:

Event handlers, tool execute, and command handlers MUST receive this context shape:

ctx = {
  ui = {
    notify = function(message, level) end, -- "info"|"success"|"error"|"warning"
    confirm = function(title, message) end,   -- -> bool
    select = function(title, items) end,      -- -> chosen item
    input = function(title, placeholder) end, -- -> string
    set_status = function(key, text) end,
    set_widget = function(key, lines) end,
  },
  session = { -- read-only
    id = "...", name = "...",
    entries = function() end,     -- -> table
    entry_count = function() end, -- -> number
    branch = function() end,      -- -> table
  },
  model = { id = "...", provider = "..." },
  cwd = "/path/to/workspace",
  signal = AbortSignal,
  shutdown = function() end,
}

Lua SDK surface

require("smith") MUST expose:

Registration signatures MUST support:

smith.tool.register({
  name = "my_tool",
  description = "shown to the LLM",
  parameters = { -- JSON Schema table
  },
  execute = function(input, ctx)
    return { content = { { type = "text", text = "..." } } }
  end,
})

smith.command.register("name", {
  description = "...",
  autocomplete = function(prefix) end, -- optional -> { {value, label}, ... }
  handler = function(args, ctx) end,
})

smith.shortcut.register("ctrl+shift+p", {
  description = "...",
  handler = function(ctx) end,
})

Every tool parameter table MUST validate as JSON Schema.

Provider registration

smith.provider.register(name, table) MUST add a provider or merge an existing provider with these rules:

smith.provider.unregister(name) MUST remove one provider. smith.provider.unregister_model(provider, model_id) MUST remove one model. Every provider table MUST pass the bundled full schema.

Public binding annotations

Every public Lua SDK function MUST have LuaLS/EmmyLua ---@ annotations; LuaLS is the only supported annotation dialect. Each binding MUST declare:

Runtime argument schemas and generated documentation MUST derive from these annotations so runtime validation and documentation remain synchronized.

Built-in plugins and commands

Built-ins MUST be Lua plugins, not host-language feature special cases. They MUST provide:

/model MUST be a fuzzy picker over resolver names.

Built-in tool contracts

read

path: string
offset?: number
limit?: number

read MUST read text files, support line windows, bound output for LLM context, and either reject binary input or return explicit binary metadata.

write

path: string
content: string

write MUST create missing parent directories, write atomically through temporary-file-plus-rename, and record a VCS operation after success.

edit

path: string
old_text: exact string
new_text: string
allow_multiple?: bool

Execution order and error codes are exact:

  1. Read the file; missing file returns ENOENT.
  2. Reject empty old_text with EEMPTY and binary content with EBINARY.
  3. Count exact matches; zero returns ENOMATCH; multiple returns EMULTI unless allow_multiple is true.
  4. Immediately before writing, re-read and hash; any change returns ESTALE.
  5. Atomically write using temporary-file-plus-rename; locking/write conflict returns ELOCK.
  6. Return replacement count and before/after hashes, then record the VCS operation.

bash

command: string
timeout?: number
cwd?: string

bash MUST execute off the UI thread, capture stdout, stderr, and exit status, enforce timeout, include output-truncation metadata, and observe abort.

find, grep, and ls

VCS SDK

The read-only API is exact:

smith.vcs.status()               -- { modified={}, added={}, deleted={}, renamed={} }
smith.vcs.diff(opts)             -- { hunks={}, text="..." }
smith.vcs.diff_revs(a, b)        -- diff between revisions/operations
smith.vcs.op_log({ limit = n })  -- { { id, description, time, op_type } }
smith.vcs.op_show(op_id)         -- { id, description, diff, files }
smith.vcs.annotate(path, opts)   -- line attribution data
smith.vcs.interdiff(a, b)        -- patch-vs-patch comparison
smith.vcs.evolog(rev)            -- logical change evolution

The mutation API MUST accept explicit validated inputs:

smith.vcs.commit(message)
smith.vcs.undo()
smith.vcs.redo()
smith.vcs.op_restore(op_id)
smith.vcs.restore_paths(paths, rev)
smith.vcs.split(opts)
smith.vcs.squash(source, dest)
smith.vcs.parallelize(revs)
smith.vcs.sparse(paths)
smith.vcs.workspace_add(name, opts)

Implementation-native details MUST remain hidden behind these Smith-shaped tables.

Plugin sandbox and heap limits

Local plugins are trusted but constrained to SDK capabilities. Raw io, os, and debug MUST be unavailable; filesystem/environment access MUST use the SDK. Version 1 MUST NOT implement path capabilities. Built-in and user plugins MUST receive identical APIs.

A plugin MAY declare heap_limit in bytes; configuration MAY override it and MUST win. Every plugin MUST own a separate Lua state and heap-limit domain. Shared-state per-plugin limits MUST NOT be offered.

The limit MUST be exact where the target supports enforcement. Exceeding it MUST be a recoverable plugin memory error. A target unable to enforce limits MUST loudly reject heap-limit configuration and MUST NOT silently apply zero or an ineffective limit.

The limit MUST include the plugin Lua heap and host-created Lua values. Host allocations held on behalf of the plugin are outside that heap limit and MUST be bounded through whole-domain teardown. After out-of-memory, whole-domain replacement SHOULD be used rather than in-place retry.

Dependency resolution

A dependency MUST name a plugin and minimum Smith API generation:

dependencies = {
  { name = "acme/logger", smith_api = 1 },
}

Version 1 MUST resolve only already-available plugins and MUST NOT perform network dependency resolution or semantic-version range solving.

After manifests load and before entry execution, each built-in, global, and workspace plugin set MUST be resolved by:

  1. building a graph from validated manifests;
  2. disabling a plugin with an absent dependency and reporting that dependency;
  3. disabling a plugin whose dependency supports a lower API generation than requested;
  4. detecting cycles, disabling every plugin in each cycle, reporting the complete path, and never partially loading it; and
  5. loading topologically so dependency registrations exist before dependent entry code.

Dependencies express only presence and API generation. Normal registration precedence MUST still apply, including overrides across dependency edges.

Plugin domains and hot reload

A reload MUST replace a complete plugin domain, never mutate one in place. A domain MUST own:

Nothing plugin-owned may outlive its domain. Every registration MUST be keyed by domain generation; registrations that cannot be tied to a domain MUST be rejected. Raw callback handles MUST remain only in the generation-keyed registry. Every dispatch MUST verify the active generation before entering Lua. An inactive generation MUST be rejected diagnostically and MUST NOT begin execution. The loader MUST audit for escaped registrations associated with inactive generations.

Reload MUST be requestable by:

Built-in smith/* plugins MUST use the same mechanism.

For plugin P with active domain D and candidate D', reload MUST:

  1. construct D' and validate/load its manifest, entry, and registrations in isolation;
  2. on failure, drop D', retain D, and report the error;
  3. on success, atomically replace registrations and subscriptions with D', mark D retired, and activate D'; and
  4. drop D after its allowed in-flight work and deferred bus dispatch complete, tearing down its Lua state, registrations, subscriptions, caches, and scratch memory.

Reload MUST be all-or-nothing. Failure MUST leave the old domain and bindings active and no candidate state. Repeated reloads MUST plateau in live memory after warmup; immediate RSS reduction is not required.

Domain teardown MUST wait for an executing Lua callback; Lua MUST NOT be preempted. A bus handler follows the condemned/deferred rules below. A tool invocation already running under D MUST finish under its pinned domain and deliver its result; invocations begun after swap MUST use D'. No new stale callback may begin after swap.

Reload MUST preserve session identity/entries, agent state, and other plugin domains. If P backs an interface, candidate binding and conformance MUST be revalidated before commit. Existing interface views MUST transparently dispatch their next call to D'. Conformance failure MUST roll back. Dependents MUST NOT reload; stable names MUST rebind, and a removed registration MUST produce a normal missing-registration error on next use.

Plugin errors

Every plugin error MUST include plugin name and phase and MUST NOT corrupt the host, terminal, or another plugin.

Host library code MUST NOT panic on plugin input.

Inter-plugin bus

smith.bus.* is the only sanctioned direct plugin-to-plugin messaging channel. It MUST remain separate from lifecycle events, and plugins MUST NOT emit core event types through it.

local handle = smith.bus.on("acme/index-ready", function(payload, ctx)
  ctx.ui.notify("index has " .. payload.count .. " files", "info")
end)

smith.bus.emit("acme/index-ready", { count = 128 })
smith.bus.off(handle)

Rules:

Plugins MAY also compose through stable registries and the core event bridge.

Runtime configuration reload

Reload MUST preserve the process and active session and use validate-then-atomic-swap semantics. It MUST re-evaluate layers 1–4. Layer-5 CLI flags are resolved once, MUST remain unchanged, and MUST continue to override the candidate.

Reload triggers are:

config/reload MUST return success with changed paths or the validation failure verbatim. Eval mode MUST read configuration at startup and MUST NOT expose runtime reload.

Reload order is exact:

  1. Evaluate the cascade into a candidate.
  2. Validate every value against host schemas.
  3. Validate the complete alias/group/bucket graph, not only the active chain.
  4. If any step fails, report all failures together with exact key paths, discard the candidate, retain active configuration, and permit a later retry.
  5. Atomically activate a valid candidate.
  6. Apply theme, keybindings, active tool set, then resolved model/provider, in that order.
  7. Re-render the TUI with the new theme on the next frame.
  8. Emit config_changed with changed paths and no secrets.

Changed-path calculation MUST compare effective post-CLI configuration, omit changes masked by CLI values, treat a list-valued key as one path, include additions/removals, and emit an empty list for an idempotent reload.

An in-flight turn MUST retain the model, tools, and system prompt captured at its start; the next turn MUST use new values. Running tools MUST finish with old values. Session identity, entries, and plugin domains MUST remain unchanged. Configuration reload MUST NOT load, unload, or reload plugin code.

The following are fixed for process lifetime and MUST NOT hot-reload:

Runtime provider changes MUST use smith.provider.*. Credential resolution MUST NOT be cached across reload; the next provider stream MUST resolve from the new effective configuration and auth sources.

CLI and RPC

CLI

The executable MUST be smith. Global options are exact:

--model <model>
--provider <provider>
--session <id-or-name>
--config <path>
--no-config

Commands and behavior are:

Interactive slash commands MUST be registered by Lua plugins and MUST NOT be binary subcommands.

The entrypoint MUST parse CLI input, resolve configuration, create Harness, and dispatch to interactive, eval, RPC, replay, session, plugin, or help handling. Errors and signals MUST restore terminal state. Fatal commands MUST diagnose and exit nonzero.

RPC projection model

smith rpc MUST expose JSON-RPC 2.0 bidirectionally over standard input/output. Its catalog MUST be a structural projection of the Lua SDK, not a direct mirror. Every surface has independent origin (SDK-mirrored or RPC-only) and shape (data request/response, callback, or notification).

These data/configuration surfaces MUST project as client request to server response methods:

fs
search
env
time
log
provider
alias
group
bucket
vcs
config
secret
active_tools
credentials
send_message
abort
shutdown
getContextUsage

Callback-bearing APIs MUST invert direction:

Registration originates client-to-server. Invocation MUST be a server-to-client JSON-RPC request whose reply is awaited. Other non-callback operations in a projected callback namespace MAY remain ordinary client-to-server requests. Callback registration therefore requires bidirectional RPC.

Headless RPC MUST omit Lua-runtime-only tui and shortcut surfaces because it has no terminal or keyboard.

RPC-only driver methods

External clients MUST receive these RPC-only methods:

session/open
session/attach
session/list
session/dump
session/snapshot
session/fork
session/subscribe
prompt/submit
command/run

session/dump MUST return persisted transcript, tree, current leaf, and fold state, with secret registration plaintext redacted. session/snapshot MUST return ephemeral queue state and in-flight run status needed for mid-session attachment; this state MUST NOT be persisted as a session entry.

RPC frontend event boundary

RPC MUST be a peer frontend to the TUI. Its event stream MUST adapt the same EngineEvent stream, not dispatch through the Lua plugin bridge. Public event names and hook responses MAY project the equivalent plugin-event vocabulary, but their source of truth MUST remain EngineEvent and core hooks.

Nonblocking events MUST be server-to-client notifications. Blocking tool_call and session_before_* events MUST be server-to-client requests accepting allow/block/replace responses according to their hook contracts. Even an observer that registers no behavior MUST support this reverse request channel and return a neutral response.

Frontend-private events for panel toggling, resizing, selection, focus, and scrolling MUST be omitted.

The wire MUST let a headless frontend reconstruct transcript, tools, combined steering/follow-up queue, conversation tree/current leaf, model, cost, folds, and secret placeholders, with these exact rules:

Secret plaintext MUST never cross RPC. Only smith:sec:N placeholders and labels/IDs MAY cross.

RPC transport framing is intentionally selectable: line-delimited JSON and Content-Length framing are both permitted.

Security

Trust boundary

Smith MUST treat the local user, operating system, filesystem, local plugins, Smith code, and local session/configuration/cache files as trusted. It MUST treat the remote LLM and provider network-response content as untrusted. Provider/LLM response data is the only untrusted content domain in the version-1 product model.

Required controls

  1. ToolRegistry MUST determine which tools the LLM may invoke.
  2. The secret proxy MUST prevent registered plaintext secrets from entering LLM context, traces, public events, or RPC.
  3. Restricted Lua MUST expose no raw operating-system or filesystem APIs.
  4. Users MUST configure active tools. Confirmation dialogs MUST NOT be treated as a security boundary.
  5. Credentials MUST remain plaintext in permitted local storage, with no keychain integration or encryption.

The plugin sandbox is a constrained product API, not a hostile-code security boundary. Version 1 MUST NOT perform heuristic secret discovery in core and MUST NOT implement filesystem path capabilities.

Concurrency

Execution domains

Plugin actor

Hooks, bus calls, and plugin callbacks MUST use channel-actor dispatch:

Responsiveness and cancellation

A UI keypress MUST be acknowledged within 16 ms, including while plugin CPU work runs. The engine MUST never synchronously block the UI.

Every long-running operation MUST observe abort except already executing Lua. Lua cannot be preempted. On abort, the engine MUST abandon a pending hook dispatch, drop its reply receiver, and continue; Lua may finish, and its late reply MUST be discarded. Any hard cancellation of runaway Lua MUST occur only by whole-domain teardown, never in-place interruption, and normal teardown MUST wait for currently executing Lua.

Hook deadlines are soft. A hook MAY block only its own dispatching turn and queued plugin dispatches; the shared plugin thread creates head-of-line blocking only inside plugin dispatch. It MUST NOT block the UI, tool pool, or engine runtime. Exceeding the configured soft deadline MUST produce a plugin diagnostic and MUST NOT kill the hook.

Performance

The product MUST satisfy:

A release MUST NOT exceed a mandatory threshold because of a performance regression.

Memory behavior

Session discovery MUST be lazy and metadata-only: it MUST read session headers, never complete bodies, and perform work proportional to session count rather than corpus bytes.

Virtual scrolling MUST materialize no more than viewport rows per frame. Row formatting MUST stop at the visible window through lazy wrapping; showing a slice of a multi-MiB message MUST NOT format the complete message.

Arenas MUST be scratch-only and phase-local to measured rendering or request scratch. Persisted/session data MUST use stable IDs and owned strings, never arena references. Custom or unsafe arena implementations MUST NOT be used. Arena references MUST NOT cross asynchronous, thread, or persistence boundaries.

Arena decisions MUST consider allocator-call pressure, elapsed time, and peak/plateau stability, not allocation count alone. Render-frame scratch qualifies; request-build scratch MUST NOT be presumed faster when serialization dominates.

Provider request assembly at compaction-scale contexts MUST have transient peak memory no greater than a small multiple of serialized request size and MUST release that transient memory fully after send. Peak memory, not CPU alone, is an acceptance requirement.

Release Artifacts

Target matrix

Platform Target triple Obligation
Windows x86_64 x86_64-pc-windows-msvc required
Windows ARM64 aarch64-pc-windows-msvc required
macOS Intel x86_64-apple-darwin required
macOS Apple Silicon aarch64-apple-darwin required
Linux x86_64 glibc x86_64-unknown-linux-gnu required
Linux ARM64 glibc aarch64-unknown-linux-gnu required
Linux x86_64 musl x86_64-unknown-linux-musl required
Linux ARM64 musl aarch64-unknown-linux-musl required
Android ARM64 aarch64-linux-android required
Linux riscv64 glibc riscv64gc-unknown-linux-gnu best-effort
Linux riscv64 musl riscv64gc-unknown-linux-musl best-effort
FreeBSD x86_64 x86_64-unknown-freebsd best-effort
OpenBSD x86_64 x86_64-unknown-openbsd best-effort

Linux glibc, Linux musl, and Android Bionic MUST remain distinct libc targets. Android MUST link the compiler-runtime builtins required by Rust; an environment unable to supply them cannot produce the required artifact.

Failure of a required target MUST stop release. A best-effort failure MUST be skipped, documented with its reason in release notes, and MUST NOT block other artifacts. Every target MUST be accounted for as built or skipped; none may be silently omitted. The matrix MUST be cross-compiled from one host wherever a target permits it.

Names and guarantees

Every built target MUST produce:

smith-{triple}-v{version}.{zip|tar.gz}

and an entry in:

checksums-sha256.txt

Windows artifacts MUST use the MSVC ABI; GNU ABI MUST NOT substitute. Linux glibc artifacts MUST run on glibc 2.28 or newer, including Debian 10, RHEL 8, and Ubuntu 18.10. Raising that minimum is a product-specification change.

Version 1 MUST NOT ship install scripts, package manifests, distribution metadata, or code signing.

Documentation

smith help is the product documentation interface and MUST support topic lookup, dotted SDK addressing, full listing, text search, examples, named runnable examples, and named guides through the exact CLI flags above.

Documentation lookup MUST use the first available source in this order:

  1. content embedded in the binary;
  2. <prefix>/share/smith/docs/;
  3. SMITH_DOCS_PATH.

The system prompt MUST direct capability discovery to smith help --search, smith help --guide, and smith help --example rather than embedding the complete SDK.

Every public Lua function's runtime schema and documentation MUST derive from its LuaLS annotations. Interface descriptors MUST generate matching LuaLS ---@class, ---@field, and ---@param stubs. Documentation examples declared by ---@usage MUST be runnable as written.

Documentation completeness MUST guarantee that every Rust SDK function has corresponding Lua binding documentation, every public Lua binding exists in code and is documented, and every event appears in at least one example.

Diagnostics documented as path-qualified—configuration, themes, interface conformance, tool arguments, plugins, and reload—MUST preserve those exact paths in user-visible output.

Product Acceptance

A Smith release conforms only if every applicable MUST and MUST NOT in this specification holds. At minimum, end-to-end acceptance MUST demonstrate:

Markdown source
# Smith Product Specification

This file is the sole canonical product contract. Normative terms **MUST**, **MUST NOT**, **SHOULD**, and **MAY** define product requirements. Unless a declaration is explicitly described as shape-level, names, values, paths, formats, signatures, and observable behavior in this document are exact contracts.

## Product

### Product boundary

Smith MUST be a fast, extensible AI coding agent with:

- an interactive terminal UI;
- non-interactive evaluation;
- JSON-RPC 2.0 over standard input/output;
- a Lua plugin system;
- a provider-independent agent loop;
- deterministic session storage and replay; and
- built-in coding tools implemented through the same Lua plugin API as user tools.

Cross-crate behavior MUST use explicit typed requests, streams, events, intents, or hooks. Hidden downstream cascades are forbidden. Public interfaces MUST remain small, typed, and honest.

Every user-visible tool, slash command, theme, keybinding, prompt, layout, and feature UI MUST be supplied as a Lua plugin. Binary commands provide process lifecycle and transport entrypoints only. Built-in and user plugins MUST receive the same SDK.

Smith MUST NOT depend on Pi or couple to Pi APIs, data, or formats.

Files, wire formats, CLI behavior, configuration, and Lua SDK boundaries are exact. Internal Rust declarations are shape-level contracts unless this specification explicitly makes a symbol or representation exact.

### First run

Running `smith` in an unconfigured workspace MUST apply defaults without a wizard, onboarding flow, or setup prompt. Capabilities MUST be probed once and failures MUST be interpreted conservatively.

The default Lua layout plugin MUST render:

- a status bar showing the active model, context percentage, and accumulated cost;
- message history;
- input; and
- a hint bar.

All optional bordered panels MUST initially be closed and MUST be strictly opt-in. Empty history MUST show a few dim hints containing the active model, how to begin, and `smith help`; those hints MUST disappear after the first entry. Startup MUST make the interactive product ready in less than 100 ms.

### Missing authentication

Authentication resolution MUST complete before the first provider stream. Failure MUST be fast, recoverable, and rendered in history. A missing-authentication diagnostic MUST name:

- the missing credential;
- the environment variable to set; and
- `/auth login <provider>` when that provider offers OAuth.

The unsent message MUST remain in the input for immediate resend. Smith MUST NOT start a setup flow.

### Active work

Assistant text and thinking UI MUST update incrementally as provider events arrive. Tool calls MUST initially render as collapsed one-line entries and MUST expand when selected. Cost and context usage MUST update live in the status bar.

Input beginning with `!`, such as `!cargo test`, MUST execute directly and create a user-bash session entry. Session entries MUST also be capable of representing `!!` user-bash commands and their output.

Every successful mutating tool MUST invisibly record a VCS operation. Smith MUST NOT prompt for commits or expose the underlying VCS implementation.

### Steering and follow-ups

Submitting normal input during an active run MUST queue a steer. Submitting with the configured modifier MUST queue a follow-up. The combined queue MUST render between history and input.

A steer MUST let already-running tools finish, skip tool calls not yet started, insert the steering messages, and make the model re-plan. Cancel actions MUST remove queued items newest-first; a user cancel MUST abort only when the queue is empty. Queue contents are process-ephemeral and MUST be empty after session continuation.

### Independent navigation axes

Conversation navigation, workspace restoration, and replay MUST remain distinct:

1. `/tree` MUST display the append-only session tree and permit switching the current leaf to an earlier entry. Switching MUST rewind conversation context without changing workspace files. Sending from a historical entry MUST silently create a sibling path in the same session.
2. Workspace time travel MUST navigate the VCS operation timeline independently. The timeline MUST show operations associated with entries, inspect operation diffs, and restore an earlier operation. `/undo` and the timeline MUST restore the applicable earlier operation. The timeline MUST offer restoration of the operation recorded at the current conversation entry without coupling leaf movement to restoration.
3. Replay MUST read a recorded trace and MUST never execute against or mutate the live session. Visual replay and compare execution are replay operations, not conversation or VCS navigation.

A plugin MAY offer a combined action that explicitly invokes both leaf switching and `smith.vcs.op_restore`, but the underlying axes MUST remain separately addressable.

### Model selection

`ctrl+l` MUST cycle a configured model shortlist. `/model` MUST open a fuzzy picker. Both MUST primarily expose resolver names—aliases, groups, and buckets—and the picker MUST show each name's resolved plan. Raw provider/model IDs MUST remain available only as a fallback interface.

### Exit, continuation, attachment, and replay

Quitting and every fatal path MUST restore the terminal.

`smith continue` MUST resume the latest session for the current working directory at the same current leaf, with empty process queues and accumulated cost still visible. `smith attach` without an identifier MUST fuzzy-pick among sessions.

`smith replay <session> --speed 2` MUST visually replay the selected trace at twice recorded speed. `--compare` MUST re-execute tools in a replay execution context and diff new outputs against recorded outputs. Replay MUST not write to the source session or invoke tools against its live agent state.

## Architecture

### Crates

| Crate | Required responsibility |
|---|---|
| `smith` | Foundation types, `StreamFn`, `AgentTool`, configuration, Lua runtime, and shared errors; no business logic. |
| `smith-core` | Agent loop, sessions, tools, hooks, compaction, cost, traces, and replay. |
| `smith-ai` | Providers, authentication, model registry, provider streams, and `MuxProvider`. |
| `smith-tui` | Terminal events, widgets, layout primitives, render loop, and themes. |
| `smith-harness` | Orchestration, plugin system, SDK, event bridge, built-ins, and help. |
| `smith-cli` | Executable entrypoint, CLI, session commands, eval, RPC, and replay dispatch. |

### Internal dependency graph

| Crate | MAY depend on |
|---|---|
| `smith` | no internal crate |
| `smith-core` | `smith` |
| `smith-ai` | `smith` |
| `smith-tui` | `smith` |
| `smith-harness` | `smith`, `smith-core`, `smith-ai`, `smith-tui` |
| `smith-cli` | `smith`, `smith-harness` |

Consequently:

- `smith` MUST NOT depend on a downstream crate.
- `smith-core`, `smith-ai`, and `smith-tui` MUST NOT depend on one another.
- `smith-cli` MUST NOT depend directly on `smith-core`, `smith-ai`, or `smith-tui`.
- `smith` MUST NOT re-export `smith-core` domain types; callers MUST import a domain type from its owning crate.
- `mod.rs` files MUST contain only module declarations and re-exports.
- Crate roots and dedicated public-API modules MAY declare public API.
- Other implementation-module items MUST remain crate-private unless an exception names the crate, implementation path, exact symbols, and reason. No such exceptions exist in version 1.

## Runtime Files

### Product directories

`config_dir`, `data_dir`, and `cache_dir` mean the final Smith-specific directories below. Callers MUST NOT append another `smith` component.

| Platform | `config_dir` | `data_dir` | `cache_dir` |
|---|---|---|---|
| Linux | `~/.config/smith/` | `~/.local/share/smith/` | `~/.cache/smith/` |
| macOS | `~/Library/Application Support/smith/` | `~/Library/Application Support/smith/` | `~/Library/Caches/smith/` |
| Windows | `%APPDATA%\smith\` | `%LOCALAPPDATA%\smith\` | `%LOCALAPPDATA%\smith\cache\` |

When platform paths coincide, their children MUST coexist in that directory. The required layout is:

```text
<data_dir>/
  sessions/
    {session-id}.session
    {session-id}.trace
  plugins/
    <org>/<name>/
  data/
    <org>/<name>/
  vcs/
    {project-hash}/
      jj-state/

<cache_dir>/

<config_dir>/
  config.lua
  auth.json
```

Workspace-local plugins MUST live at `.smith/plugins/<org>/<name>/`.

### Persistent formats

`{session-id}.session` MUST be an unencrypted sequence of length-prefixed CBOR records. Its canonical filename MUST be exactly `{session-id}.session`. The initial metadata record(s) MUST expose enough session-header information for metadata-only discovery without reading the complete body.

`{session-id}.trace` MUST be a compressed deterministic replay log as specified under Core. Session and trace paths MUST be derived from the same `SessionId`.

Plaintext secrets MAY be persisted only in secret-registration session entries and `auth.json` under the local trust model. Other session content and every trace representation MUST obey the secret-proxy rules.

### VCS state

VCS state MUST live at `data_dir/vcs/{project-hash}/jj-state`. The only Smith-managed VCS state item placed in the workspace root MUST be a `.jj` symlink. In a colocated Git workspace, `git_target` MUST be rewritten to the absolute `.git` path. Plugins MUST see only the stable `smith.vcs.*` contract, never implementation-native objects.

## Shared Contracts

### Required `smith` exports

The `smith` crate MUST expose:

- IDs and message types;
- provider request, event, usage, error, and model-metadata types;
- `AgentTool`, `AgentToolResult`, `AgentToolUpdate`, `ToolExecutionMode`, `ToolDefinition`, and `ToolDefinitionSpec`;
- `StreamFn`;
- `LuaRuntime`;
- `Config`;
- `ModelAlias`, `ModelGroup`, `ProviderBucket`, `ModelResolver`, `ResolvedModel`, and `ResolveError`; and
- `SmithError`.

### IDs, roles, content, and messages

The required ID types are:

- `EntryId(String)`, containing a time-sortable UUID v7;
- `SessionId(String)`;
- `SecretId(String)`; and
- `VcsOpId(String)`.

`Role` MUST have exactly these variants:

```text
System | User | Assistant | Tool
```

`ContentBlock` is the authoritative message-content representation and MUST support exactly these shapes:

```text
Text(String)
Image { data, media_type }
ToolCall { id, name, arguments }
ToolResult { id, result, is_error }
Thinking { content, provider_metadata? }
```

`ToolCall.arguments` MUST be JSON. `provider_metadata` MUST be opaque: Smith MUST preserve, store, and replay it without interpretation or consumption. Provider adapters MUST attach metadata required for later turns, including signed-thinking signatures.

`Message` MUST contain `role` and a list of `ContentBlock` values named `content`. Roles identify speakers; session-entry kinds identify events. A tool result MUST be a `Tool`-role message containing `ToolResult`; a distinct tool-result role is forbidden. User bash execution and similar activity MUST be represented by session-entry kinds, not new roles.

### Provider types

`ProviderUsage` MUST track:

```text
input_tokens
output_tokens
cache_read_tokens
cache_write_tokens
total_tokens
```

`StopReason` MUST have exactly:

```text
EndTurn | ToolUse | OverMaxTokens | Aborted | StopSequence | Error
```

`ThinkingLevel` MUST have exactly:

```text
Off | Minimal | Low | Medium | High | XHigh
```

`ProviderEvent` MUST support:

```text
TextDelta { text }
ThinkingDelta { text, provider_metadata? }
ToolCall { id, name, arguments }
Done { usage, stop_reason }
Error(ProviderError)
```

`ThinkingDelta.provider_metadata` is optional and opaque. An adapter MUST attach it to the delta whose thinking text it authenticates. A provider-boundary `ToolCall` MUST be complete; vendor-specific partial argument chunks MUST be joined before crossing this boundary.

`ProviderError` MUST classify failures with exactly these variants, each carrying a message:

```text
RateLimit
AuthFailed
Network
ServerError
InvalidRequest
ModelNotFound
Timeout
```

`ProviderRequest` MUST contain:

```text
messages
system_prompt
model_id
provider_id
tool_definitions
thinking_level
token_limit
stop_sequences
```

### Tool types

`ToolDefinitionSpec` MUST be serializable metadata suitable for LLM function calling and plugin metadata. `ToolDefinition` MUST be the runtime definition consumed by providers and the agent loop.

`AgentTool` MUST be asynchronous, `Send`, and `Sync`. `ToolExecutionMode` MUST select sequential or parallel execution according to tool metadata.

`AgentToolResult` MUST contain content blocks, an error flag, and optional updates. `AgentToolUpdate` is version-1 completion metadata: updates MUST appear in the final `AgentToolResult` and MUST NOT stream live while a tool is running.

Tool arguments MUST be JSON and MUST be validated against the tool's JSON Schema before execution.

### `StreamFn`

`StreamFn` is the provider abstraction consumed by `smith-core`:

```text
ProviderRequest -> asynchronous stream of ProviderEvent
```

It MUST have no dependency on `smith-ai`.

The agent loop MUST assemble consecutive `ThinkingDelta` events into one `ContentBlock::Thinking` by concatenating text in arrival order. Every non-empty metadata value MUST enter the assembled block. Multiple values MUST be stored in arrival order within its opaque metadata payload. Smith MUST NOT interpret those values. This assembly MUST be the sole route by which signed-thinking metadata crosses `StreamFn` into persisted content and later provider replay.

### Restricted `LuaRuntime`

`LuaRuntime` MUST provide LuaJIT with custom `require` searchers. Only these standard libraries are permitted:

```text
string, table, math, coroutine, utf8, package
```

`package` MUST use only the host's custom searchers. The following globals MUST be removed:

```text
io, os, debug, getfenv, setfenv
```

Host APIs MUST be obtained with:

```lua
local smith = require("smith")
```

Lua bytecode caching is forbidden. Every Lua source load, including manifests, configuration, plugin entry files, required modules, and content stored in a `.lua` file, MUST explicitly request text-only chunk mode. Binary chunks and binary auto-detection MUST be rejected.

### Configuration

Lua MUST be the configuration language. Rust MUST define and validate schemas; Lua MUST supply values. Effective configuration MUST apply these layers from lowest to highest precedence:

1. Rust type defaults and schema;
2. built-in Lua defaults;
3. plugin contributions;
4. `config_dir/config.lua`;
5. CLI flags.

Later layers MUST override earlier layers. Cross-layer merging MUST recursively merge leaf fields for table-valued keys. Scalars and lists are leaves and MUST replace prior values wholesale.

Invalid values MUST produce clear path-qualified errors. Unknown keys MUST warn in the top-level schema context. Unknown keys MUST fail in strict contexts, including every `models.*` and `compaction.*` context where a typo could silently change behavior.

The full applicable cascade MUST be re-evaluated on runtime host-configuration reload. A valid configuration includes this shape:

```lua
return {
  theme = "catppuccin",
  keybindings = {
    ["ctrl+l"] = "cycle_model",
    ["ctrl+c"] = "abort",
  },
  tools = { "read", "write", "edit", "bash" },
  model = "anthropic/claude-sonnet-4",
}
```

### Models, aliases, groups, and buckets

`ModelMetadata` MUST include provider ID, model ID, context window, maximum output tokens, cost when known, and capabilities for thinking, vision, tool use, and streaming.

`ModelResolver` MUST resolve through this chain:

```text
requested name -> alias -> group -> bucket/account -> provider/model metadata
```

Resolution MUST perform no I/O. `resolve` MUST be a pure function of validated configuration, requested name, and rotation cursors. Identical inputs and cursors MUST yield an identical ordered plan. `MuxProvider`, not the resolver, MUST own cursors and advance each rotation node by one step per provider request.

Configuration loading and reload MUST validate the whole graph and MUST:

- detect a real cycle and report its complete path, for example `cycle detected at config load: a → b → a`;
- accept DAG diamonds without false cycle reports;
- reject a name defined as multiple kinds and name every conflicting kind;
- reject empty groups;
- reject buckets with empty account lists;
- reject dangling references and name the referrer;
- reject duplicate members within one group list; and
- reject a bucket target that is not a concrete model.

After successful validation, an unknown requested name MUST be the only resolution-time error.

Duplicate candidates reached through distinct DAG paths to the same provider/model/account MUST survive resolver flattening. `MuxProvider` MUST deduplicate identical candidates immediately before attempting them. `ResolvedModel` MUST carry all metadata required by `smith-core`.

`FailoverStrategy` MUST support `ordered` and `round-robin`. `BucketStrategy` MUST define account rotation, and every account in a bucket MUST be an individual failover candidate. `providers.retry_count` MUST configure general retry count and default to `2`.

### Shared errors

`SmithError` MUST wrap subsystem errors for:

- `ProviderError`;
- authentication;
- tools, including defined tool error codes;
- configuration validation;
- Lua execution;
- I/O;
- session and trace codecs; and
- model resolution.

Recoverability MUST be the default. A recoverable failure MUST become user- or model-visible content—such as an error tool result, history diagnostic, UI notification, or plugin diagnostic—and MUST leave the process able to continue.

Provider failures where another operation remains possible, tool errors, plugin faults, plugin out-of-memory errors, and rejected configuration reloads MUST be recoverable. A failure MUST be fatal only when safe continuation is impossible, including unrecoverable terminal state, invalid startup configuration, or exhaustion of every provider during non-interactive eval. Fatal paths MUST restore the terminal, emit a diagnostic, and exit nonzero.

Shipped library code MUST NOT panic on external failures or plugin input. Impossible internal states MAY use debug assertions.

## Core

### Agent runtime

The agent loop MUST accept an `AgentContext`, `AgentLoopConfig`, `StreamFn`, tool registry, and event sender. It MUST stream provider responses, emit `AgentEvent` values, execute tool calls, process steering and follow-ups, and continue until a stop criterion is met.

The loop MUST use:

- an outer loop for turns and follow-up user messages; and
- an inner loop for provider streaming, tool calls, and steering.

`AgentLoopConfig` MUST support:

- `max_tool_calls_per_turn`, default `100`;
- `max_turns_per_user_message`, default `50`;
- sequential or parallel tool execution;
- `model_metadata` for context and cost calculations; and
- typed hook callbacks.

Every runtime state MUST be interruptible. Ctrl+C and programmatic abort MUST set an abort signal. Provider streaming and tool execution MUST observe it and terminate cleanly, subject only to the non-preemptible Lua rule under Concurrency.

### Follow-up and steering semantics

Follow-ups MUST be held FIFO. Immediately before a run would emit `AgentEnd`, the loop MUST inspect the follow-up queue. If one exists, it MUST dequeue it as a fresh user message and begin a new outer turn cycle instead of ending.

A steer MUST be delivered at the next safe boundary: after the current provider stream completes or after in-flight tools finish. Before the next provider request, all queued steers MUST drain FIFO as user messages.

Once a steer is queued during parallel tool execution, no additional call from that assistant message may start. Calls already started MUST finish. Calls never started MUST receive error-flagged synthetic tool results whose content is exactly `skipped: user steered`.

A steer arriving during provider streaming MUST cause every tool call produced by that assistant message to skip; none may execute. Parallel transcript ordering MUST be:

1. real results in completion order;
2. synthetic results in original tool-call order; then
3. drained steering messages in FIFO order.

Every skipped call MUST emit `ToolExecutionStart` and `ToolExecutionEnd`. The end event MUST carry the error flag and skip reason. Every tool call represented on a provider wire message MUST ultimately receive a result unless abort occurs before any subsequent request can carry synthetic results.

Interactive active-run input MUST default to steering; a modifier MUST select follow-up. Plugins MAY override default input behavior through the `input` hook and MAY send messages through `smith.send_message`.

Both queues MUST remain process-ephemeral. An item MUST become a session entry only when delivered, so persisted sessions contain only messages seen by the model. Compaction MUST neither consume nor discard queued messages.

A user cancel MUST pop queued items according to TUI queue rules before aborting. Programmatic abort MAY be delivered independently; after any delivered abort, undelivered queue items MUST remain available for sending, editing, or discarding. An aborted assistant tail MAY contain tool calls without results. Request assembly after resume MUST repair that tail by synthesizing aborted results for every unanswered call.

### Agent and engine events

`AgentEvent` MUST be the source of truth for agent behavior and MUST include:

```text
AgentStart, AgentEnd
TurnStart, TurnEnd
MessageStart, MessageUpdate, MessageEnd
ToolExecutionStart, ToolExecutionUpdate, ToolExecutionEnd
TextDelta, ThinkingDelta
Error
```

`AgentEvent::to_session_entry(timestamp)` MUST return a `SessionEntry` only for completed, conversation-relevant events. Streaming deltas and incomplete lifecycle events MUST NOT independently become transcript entries.

`EngineEvent` MUST wrap `AgentEvent` and add events for session lifecycle, steering and follow-up handling, UI state changes, provider and model changes, errors, and shutdown. Every frontend MUST consume `EngineEvent` and submit typed intents. TUI-private panel, resize, selection, focus, and scrolling variants MAY remain private to the in-process frontend and MUST NOT be exposed out of process.

### Core hooks

The hook API MUST provide these exact result types and choices:

- `BeforeToolCallResult`: allow, block, replace arguments, or cancel;
- `AfterToolCallResult`: keep, replace result, retry, or cancel;
- `ShouldStopAfterTurn`: stop or continue;
- `PrepareNextTurn`: mutate queued prompts/messages; and
- `TransformContext`: mutate LLM context before a provider request.

A blocked tool call MUST NOT execute. It MUST still emit `ToolExecutionStart` and `ToolExecutionEnd`; the end MUST carry an error flag and block reason. The provider MUST receive the reason as an error tool result. Lua event-return tables MUST be translated into these core types.

### Session model

`Session` MUST contain:

```text
SessionId
optional name
cwd
entries
current leaf
created timestamp
updated timestamp
```

A session MUST be an append-only branching tree with one writer at a time. Only one agent loop may append. A branch MUST be derived as the root-to-leaf path, never stored as a separate mutable object. `ctx.session.branch()` MUST return the current path. Existing entries MUST never be rewritten. Continuing from an older entry MUST append a new child and create an in-tree fork silently.

Append behavior:

- An ordinary append MUST add a child of the current leaf and move the leaf to the new entry.
- An ordinary append while positioned on a non-leaf entry MUST create a fork implicitly.

Leaf-switch behavior:

- A switch MUST target any surviving entry and MUST be recorded by appending leaf-switch metadata.
- Loading MUST resolve the current leaf by replaying surviving records in file order.
- During replay, an ordinary append MUST move the leaf to itself; a leaf-switch operation MUST move it to its target.
- The last surviving replayed operation MUST determine the leaf.
- A leaf switch whose target was lost during recovery MUST be ignored.
- Switching MUST NOT modify workspace files.

Path reads MUST return only root through current leaf. LLM context MUST use only that path after compaction folding; siblings MUST remain invisible.

Session forking is distinct from in-tree branching. Forking MUST clone entries through a specified entry into a new `SessionId` and new session file and MUST emit `session_before_fork`. Version 1 MUST NOT support branch deletion or pruning.

If recovery loses a parent, its subtree MUST remain detached, be reported as orphaned, remain unreachable from the root, and MUST NOT be grafted elsewhere. Conversation navigation alone MUST never alter files. Filesystem time travel remains plugin policy and MAY explicitly pair a switch with the entry's `VcsOpId` through `smith.vcs.op_restore`.

### Session entries and codec

Every `SessionEntry` MUST have a stable `EntryId`, optional parent, and timestamp. Supported variants MUST include:

- user message;
- assistant message;
- tool call;
- tool result;
- system-prompt snapshot;
- compaction summary;
- secret registration;
- model/provider change;
- VCS operation;
- user bash execution, including `!` and `!!` command and output;
- leaf switch; and
- metadata required for migration and replay.

Readers MUST preserve a well-formed unknown entry variant as raw data so future variants survive rewrite or migration round trips.

The file framing is exact:

```text
u32 BE len | CBOR entry bytes | u32 BE len | CBOR entry bytes | ...
```

Recovery MUST obey these boundaries:

- A truncated tail MUST stop parsing and preserve every prior record.
- A corrupt entry body with an intact length prefix MUST be skipped by exactly that length and MUST produce a warning.
- A corrupt length prefix desynchronizes framing; prior entries survive and the remainder is unrecoverable and MUST be treated as truncation.
- Decoding MUST occur in two stages: raw CBOR, then typed decoding.
- Well-formed CBOR with an unknown variant tag MUST remain raw and survive a rewrite round trip.
- Invalid CBOR MUST be classified as a corrupt body and skipped when its framing is intact.

`smith session dump` MUST emit JSONL. Session discovery MUST recognize only canonical `{session-id}.session` names.

### Secret proxy

#### Registry and registration

The secret registry MUST map each `SecretId` to plaintext and a label. Core masking MUST operate only on registered secrets; discovery or heuristic detection MUST remain plugin-defined.

Registration paths are:

- automatically for every credential loaded by the auth resolver;
- automatically when a plugin reads one of its declared secrets through the SDK;
- explicitly through `/secret`; and
- programmatically through `smith.secret.register(value, label)`.

Detection plugins MAY inspect `input` and `tool_result` hook content and register values. Registration MUST:

- reject a value matching `smith:sec:<digits>` and return a diagnostic;
- be idempotent by exact plaintext and return the existing `SecretId`; and
- after resume, allocate above the greatest ID found in the session.

Placeholder parsing MUST consume the maximal digit run: `smith:sec:12` means ID `12`, never ID `1` followed by `2`.

#### Ingestion masking

Masking MUST use exact, case-sensitive, encoding-sensitive substring matching against registered plaintext. It MUST run before content becomes a normal session entry and after the plugin `input` or `tool_result` hook, allowing a hook to register a value and mask that same content.

Matching MUST be longest-match-first in one left-to-right pass. Emitted placeholders MUST NOT be rescanned. Plaintext MUST occur in session entries only inside secret-registration entries. On resume, the registry MUST rebuild by scanning those entries backward.

Pre-transform input MUST NOT be persisted. Only post-hook, post-transform content is scanned. If a hook re-encodes a registered secret, that derived representation is outside protection.

#### Rehydration

A placeholder MUST be rehydrated only immediately before tool execution, including subprocess execution and Rust or Lua `execute` calls. Rehydration MUST be one pass and produced plaintext MUST NOT be rescanned. Ordinary session content, provider requests, trace files, and public events MUST contain placeholders, not plaintext. Secret-registration public events and traces MUST expose only ID/label/redacted data even though the session registration record retains plaintext.

Compare replay MUST obtain plaintext from secret-registration entries in the source session file and MUST NOT obtain it from the trace. An unknown placeholder ID MUST pass through unchanged without error.

#### Display and local trust

The TUI MUST display a placeholder as a masked label, for example `‹secret: provider-token›`. Displayed content MUST correspond to the same masked context content. `smith.secret.list()` and RPC MUST never reveal plaintext. A trusted local user MUST be able to recover registration plaintext through the local CLI `smith session dump`; RPC dump MUST redact it.

An unregistered secret receives no protection. Core MUST NOT guess secrets. The protection target is the remote LLM/provider boundary, not the trusted local user, plugins, or files.

### System prompt

`SystemPromptBuilder` MUST compose:

- base identity;
- active model and tool capabilities;
- plugin prompt contributions;
- workspace and context facts;
- safety and tool-use instructions; and
- user overrides.

Plugins MAY transform prompts only through typed hooks. Hidden global mutation is forbidden. The prompt MUST tell the agent to discover capabilities through `smith help --search`, `smith help --guide`, and `smith help --example`; it MUST NOT embed the complete SDK reference.

### Append-only compaction

Compaction MUST neither rewrite nor delete history. Storage MUST retain every entry verbatim and remain memory-bounded through lazy loading.

A pass MUST append a summary entry on the current path containing:

```text
from: EntryId
to: EntryId
summary text
before token estimate
after token estimate
```

Context assembly MUST fold only the current root-to-leaf path. Summary-covered spans MUST collapse to their summary; trim-masked tool results and thinking MUST collapse to stubs. Raw storage MUST remain unchanged.

Switching to an entry before a summary MUST expose a path without that summary, restore full visibility on that path, and permit a sibling summary. A descendant path created after a compaction point MUST inherit its mask.

A valid covered span MUST be one contiguous ancestor segment of the path on which the summary was appended: `from` MUST be an ancestor of `to`, and `to` an ancestor of the summary. A span crossing a fork or violating those rules MUST be diagnosed and ignored in full; its raw content MUST appear without partial collapse.

Re-compacting an already compacted path MUST cover the prior summary entry. Folding MUST apply the outermost, latest covering span, subsuming nested inner summaries. Metadata in a covered span MUST fold with it. Leaf resolution and trace/session replay MUST always read raw storage, not folded context.

### Compaction trigger, budget, and ladder

Before every agent provider request except a summarization request, compaction MUST trigger only when estimated folded-path tokens strictly exceed:

```text
threshold = floor(threshold_fraction × context_window) − output_reserve_tokens
```

The strict `compaction.*` schema MUST expose reloadable `threshold_fraction`, `output_reserve_tokens`, `recency_fraction`, `reserve_fraction`, `iteration_limit`, and `compaction_model` values. It MUST reject:

```text
recency_fraction + reserve_fraction >= threshold_fraction
```

A round MUST run synchronously at that sole trigger site and MUST NOT re-enter itself. If the protected recency window alone exceeds the threshold, it MUST report that condition and stop. If a ladder pass makes no progress, the round MUST abort.

The ladder MUST run in this order and repeat until context fits or `iteration_limit` is reached:

1. mask old tool-result bodies to stubs;
2. mask old thinking blocks; then
3. summarize the oldest eligible span with an LLM.

Summarization MUST use the active model unless `compaction_model` chooses another. Aliases and groups MUST resolve normally. Summarization usage MUST enter normal cost accounting.

Every round MUST protect from ladder trimming:

- secret-registration entries, structurally hoisted from collapsed spans while excluded or masked in provider rendering;
- the system-prompt snapshot;
- existing compaction summaries used as summarizer input;
- a token-budget recency window containing newest entries up to `recency_fraction` of model context.

Protection from the ladder does not exempt an entry from a later valid covering fold.

At the iteration limit, the round MUST terminate, report, and let the provider request proceed over budget. `session_compact` MUST report exactly one of:

```text
fit | iteration-limit | no-progress | recency-dominates
```

The blockable `session_before_compact` hook MAY veto the round, adjust its span, or replace its summarization prompt. `session_compact` MUST report the resulting outcome.

### Token and cost accounting

Version 1 token estimation MUST use `chars / 4`; an exact tokenizer is not required. Cost tracking MUST consume `ProviderUsage`, multiply known usage categories by `ModelMetadata.cost`, and track input, output, cache-read, cache-write, total tokens, and running total cost. A model whose pricing is unknown MUST be excluded from monetary cost tracking rather than treated as zero-cost.

### Tool registry

`ToolRegistry` MUST store shared, thread-safe `AgentTool` handles by name. Duplicate registration MUST follow plugin precedence. Arguments MUST be JSON-Schema validated. Final failures MUST become error tool-result content visible to the model. A transient tool failure MAY retry only according to that tool's policy.

### Trace and replay

A trace MUST have a header containing magic, version, and session ID. It MUST use block-level zstd compression with approximately 4 KiB blocks.

- Entries smaller than 64 bytes MUST NOT be compressed individually.
- Every block MUST carry a raw-fallback flag.
- A trace MUST NOT exceed its uncompressed framed size by more than the fixed 9-byte header for each block.

Traces MUST capture, in order:

- provider requests and provider events;
- tool calls and results;
- every session-entry append, including leaf switches, summaries, delivered steers/follow-ups, and secret registrations;
- TUI events as opaque JSON;
- plugin events as opaque JSON;
- VCS operation IDs; and
- an agent-state snapshot at every run end and abort.

A state snapshot MUST contain the current leaf, both message queues, and abort flag. Secret-registration trace records MUST redact plaintext idempotently. Compare rehydration MUST use the session file, never trace data.

Trace processing MUST preserve event order and contain enough information to reconstruct session state. Replay MUST support visual replay, real-time playback, a speed multiplier, maximum-speed reconstruction, old/new tool-output comparison, and fast-forward to a turn range.

Replay MUST read the trace without modifying the source session. Compare mode MUST re-execute tools and diff outputs. Tool execution MUST use `--sandbox <path>` when supplied; otherwise mutating comparison MUST use an isolated temporary replay workspace, never the live session state.

## AI

### Provider contract

`Provider` MUST be thread-safe and object-safe and expose:

- provider ID and display name;
- authentication validation that fails before its first stream; and
- `stream(ProviderRequest)`, returning a boxed asynchronous stream of `ProviderEvent`.

`stream` MUST be a plain method returning a stream, not an async method. `provider_to_stream_fn` MUST adapt a shared `Provider` handle into the `StreamFn` consumed by core.

### Required providers and normalization

Smith MUST integrate:

- Anthropic;
- OpenAI;
- Google; and
- OpenAI-compatible local and remote endpoints.

Each adapter MUST normalize its vendor wire format into `ProviderEvent` and handle at its boundary:

- streaming and non-streaming APIs;
- partial tool-call argument chunks;
- thinking/reasoning fields, including reasoning text delivered inside `content` before a final answer;
- provider-specific stop reasons;
- cache-usage fields; and
- model-capability flags.

If a streaming request receives a non-streaming JSON error body, including with HTTP status 200, the adapter MUST emit `ProviderEvent::Error` and MUST NOT wait indefinitely for SSE frames.

### Bundled model registry

`smith-ai/src/providers.json` MUST be bundled into the product and authoritative at runtime. Its canonical bundled schema MUST be `smith-ai/src/providers.schema.json` and MUST use the models.dev provider/model shape.

The bundled registry and every provider table passed to `smith.provider.register` MUST satisfy the full schema. Unknown fields MUST be legal through `additionalProperties`, preserved semantically, and ignored when version 1 does not consume them. `replace_models` MUST be the provider-override flag for replacing a provider's models.

A model record MUST support:

- `cost`, when present, as an object with USD-per-million-token fields `input`, `output`, `cache_read`, and `cache_write`, plus optional `reasoning`, `input_audio`, and `output_audio`;
- tiered cost fields `tiers` and `context_over_200k`, preserved but not consumed in version 1;
- `limit`, with required `context` and `output` for chat models and optional `input`;
- input and output modalities;
- tri-state capability fields `attachment`, `reasoning`, `tool_call`, `structured_output`, and `temperature`; and
- `reasoning_options`, preserved but not consumed in version 1.

`cost` MUST NOT be scalar. Missing cost means unknown pricing: the model MUST be omitted from cost tracking and MUST NOT default to zero. An absent capability is unknown, MUST act as false for gating, and MUST remain absent when preserved.

Eligible records MUST map to `ModelMetadata` as follows:

| `ModelMetadata` field | Registry source |
|---|---|
| context window | `limit.context` |
| maximum output tokens | `limit.output` |
| cost | `cost` |
| thinking | `reasoning` |
| vision | presence of `"image"` in `modalities.input` |
| tool use | `tool_call` |
| streaming | `true` unless provider configuration disables it |

`structured_output`, `temperature`, and `attachment` MUST be preserved in the registry but MUST NOT appear in version-1 `ModelMetadata`.

Only chat-capable models may map: `modalities.output` MUST contain `"text"`, and `limit.context` MUST be greater than zero. Image/video generators with zero context MUST remain in the registry but MUST NOT resolve as chat models.

### Authentication

The auth resolver MUST support credentials from:

- environment variables;
- `config_dir/auth.json`; and
- plaintext Lua configuration when explicitly supplied.

Smith MUST NOT use an OS keychain or encrypt credential storage. Every loaded credential MUST be registered with the secret proxy. Authentication errors MUST be resolved before the first provider stream.

Each provider's registry `auth_types` map MUST declare supported methods:

- `api_key`, including its `env_var`;
- `oauth`; and
- `organization`, representing an organization-scoped credential such as an API key plus organization ID.

`AuthMethod` MUST mirror exactly `api_key`, `oauth`, and `organization`.

`auth.json` MUST be a per-provider object map, for example:

```json
{
  "anthropic": {
    "access_token": "...",
    "refresh_token": "...",
    "expires_at": 1234567890
  }
}
```

Provider OAuth configuration MUST support:

```text
id
name
auth_url
token_url
scope
client_id
```

Stored OAuth credentials MUST contain `access_token`, `refresh_token`, and `expires_at` as Unix seconds. Expired credentials MUST refresh automatically.

`/auth login <provider>` MUST:

1. surface the authorization URL;
2. receive the authorization code from a local callback HTTP server on a random port or manual paste;
3. exchange the code for credentials; and
4. persist them to `config_dir/auth.json`.

OAuth MUST permit mocked flows and provider-specific configuration.

### `MuxProvider`

`MuxProvider` MUST wrap providers/accounts for resolved groups and buckets. It MUST consume the deterministic resolver plan, deduplicate identical provider/model/account candidates before attempts, and apply this exact policy per candidate:

| `ProviderError` | Required behavior |
|---|---|
| `RateLimit` | Fail over immediately. |
| `AuthFailed` | Retry `providers.retry_count`, then fail over. |
| `Network` | Retry `providers.retry_count`, then fail over. |
| `ServerError` | Retry `providers.retry_count`, then fail over. |
| `InvalidRequest` | Do not retry; fail over immediately. |
| `ModelNotFound` | Do not retry; fail over immediately. |
| `Timeout` | Retry once, then fail over. |

Authentication validation and any resulting `AuthFailed` handling MUST occur before opening a provider stream. `providers.retry_count` MUST default to `2`. Rate limiting MUST never consume retries. When all candidates are exhausted, `MuxProvider` MUST emit `ProviderEvent::Error`; exhaustion in eval mode MUST be fatal.

## TUI

### Frontend boundary

`smith-tui` is the built-in in-process frontend. It MUST consume `EngineEvent` and return intents for prompt submission, steering, commands, and abort. It MUST NOT be privileged as the only UI. `smith rpc` MUST expose the same event-out/intent-in engine boundary for external frontends.

An out-of-process frontend MUST be an RPC client and MUST NOT link Smith Rust code. Terminal cells, borders, widgets, buffers, and `Rect` rendering are terminal-only. Other frontends MUST consume engine events/intents and render independently.

### Normalized events

`TuiEvent` MUST normalize:

- keyboard;
- mouse;
- terminal resize;
- focus gained/lost; and
- paste.

Keyboard events MUST include normalized key code, modifiers, and kind `press`, `repeat`, or `release`. Mouse events MUST include button, scroll, position, and modifiers.

### Terminal capabilities

`TerminalCapabilities` MUST record:

```text
truecolor
undercurl
Kitty keyboard protocol
bracketed paste
focus events
mouse support
Kitty graphics
sixel
```

Capabilities MUST be probed directly without a terminfo database, once per session startup, with a 100 ms timeout per probe. Probes SHOULD run concurrently so they do not extend the product startup budget. Timeout MUST mean absence. Unsupported optional behavior MUST silently degrade to plain text.

Image protocol MUST use `ImageProtocol::{Kitty, Sixel}`. Detection is required, but version 1 MUST NOT render inline images.

Kitty keyboard flags MUST be pushed on TUI startup and popped on every shutdown path, including errors and signals. When synchronized output is supported, each render pass MUST be enclosed by `CSI ?2026 h` and `CSI ?2026 l`.

### Components and lifecycle

Components MUST render deterministically into terminal buffers, handle normalized `TuiEvent`, manage focus explicitly, report whether an event was consumed, and explicitly invalidate cached state.

`TuiApp` MUST follow:

```text
new -> enter terminal -> event/render loop -> shutdown -> restore terminal
```

The render loop MUST tick every 16 ms. Event polling MUST run on a blocking thread and send normalized events through channels. `smith-harness` MUST create and drive `TuiApp`.

Application states MUST be exactly:

```text
Idle | Thinking | ToolRunning | ToolResult | Error | Exiting
```

Every state MUST be interruptible.

### Widgets

The TUI MUST provide:

- text and truncated text;
- spacer;
- Markdown;
- message list;
- input area;
- status bar and hint bar;
- spinner;
- progress, cost, and context indicators;
- tool-call and tool-result views;
- unified and side-by-side diff views;
- syntax-highlighted code;
- fuzzy list;
- tabs;
- scrollable viewport;
- overlay; and
- border-layout panels.

### Overlay and layout contracts

Overlays, including modals, fuzzy search, and autocomplete, MUST support anchors `Center`, all four corners, and all four edge centers; `offset_x`; `offset_y`; optional margin; and `width`/`max_height` as `Size::Absolute(cells)` or `Size::Percent`.

Rust MUST provide layout primitives; Lua MUST define layout trees. Required primitives are:

- `column`: children stacked vertically;
- `row`: children stacked horizontally;
- `box`: one child, optional `width` and `height` as `Size`, and optional border/title; border style MUST be `BorderStyle::{Single, Double, Rounded, Thick, None}`;
- `expanded`: one child taking space left after fixed siblings;
- `scrollable`: one child with vertical, horizontal, or both directions;
- `overlay`: one child and the overlay options above;
- `spacer`: optional fixed `Size`;
- `tabs`: labeled children and active index; and
- `split`: two children, horizontal or vertical orientation, and `split_ratio: f32`.

One predefined border layout MUST expose center, north, east, south, and west panels. Every panel MUST carry `visible`, `size`, and its own layout. Empty panels MUST be invisible. The default layout MUST be a Lua plugin.

Composition is exact:

- An `overlay` floats over its container and remains outside flow tiling; siblings tile as if absent and overlap is allowed.
- `tabs` reserves one terminal row for labels and gives all remaining area to the active child.
- `scrollable` is layout-transparent: it is a viewport, not an axis partition.
- `Size::Percent` rounds to the nearest terminal cell.

### Layout ownership and resolution

Layout resolution MUST NOT enter Lua on a render path. On `set_center_layout` or `set_*_panel`, the harness MUST convert the Lua tree once to an owned Rust `LayoutTree` and drop the Lua value.

`LayoutTree` MUST retain no Lua handle and MUST be `Send + 'static`, allowing off-render-thread construction. Every frame MUST use a pure resolver:

```text
(LayoutTree, terminal size) -> Rect for each widget slot
```

Equal inputs MUST produce equal outputs with zero frame-loop Lua calls. Across terminal sizes 80×24 through 400×100, resolution SHOULD remain approximately 0.4 µs and release-build p99 MUST remain below 0.8 µs.

### Themes

A theme MUST be a Lua table validated by a Rust schema. Named nested tables MUST cover status bar, messages, assistant content, tool calls, tool results, errors, input, borders, selections, diffs, syntax groups, and accents. Every named section MUST contain color and style values.

Colors MUST be `#rrggbb`. Named or ANSI-indexed colors MUST NOT be accepted by the version-1 schema. Missing required keys and malformed values MUST produce the exact path, for example:

```text
theme.status_bar.fg: expected "#rrggbb"
```

Unknown keys MUST warn. An invalid user theme MUST NOT abort Smith; the built-in default MUST be activated and a visible warning MUST name the path error.

### History and tool rendering

History MUST use virtual scrolling. `sticky_bottom` MUST default to `true`. Upward user scrolling MUST set it to `false`; while false, new content MUST NOT move the viewport. Following MUST resume when the user reaches bottom or submits input.

Tools MAY register Lua `renderCall` and `renderResult` renderers. The harness MUST translate their output to structured render instructions. A plugin MUST NOT write arbitrary terminal output through this mechanism.

### Combined input queue

Steers and follow-ups MUST render as one visually combined queue between history and input:

- Follow-ups MUST appear above steers.
- Within each kind, items MUST appear oldest to newest.
- Steers therefore sit nearest the input because they deliver sooner.
- The kinds MUST remain visually distinct.
- Promote/demote MUST toggle kind and place the item newest in the destination kind while preserving original enqueue time. A round trip need not restore its prior within-kind position.
- Up-arrow MUST cycle queued messages newest to oldest.
- Selecting an item for editing MUST remove it from the queue.
- Re-sending an edited item MUST restore its remembered `(kind, index-within-kind)` position, clamped to current destination length.
- If its kind changed while edited, re-send MUST place it newest in the new kind.
- Re-sending empty edited text MUST delete it.
- While queued items exist, cancel keys—`Ctrl+C` and `Esc` by default, both rebindable—MUST remove the newest enqueue time across both kinds instead of their normal action.
- Only an empty queue permits user cancel to abort.
- An edited item is outside the queue. Cancel MUST first remove all remaining queued items; when none remain, the next cancel MUST discard the edit and restore it before any later cancel may abort.

### Version-1 TUI exclusions

Version 1 MUST NOT provide:

- Vim-style normal-mode editing;
- inline Kitty image rendering;
- interactive split-pane resizing, although `split` exists; or
- multiple simultaneous sessions in one TUI.

## Harness and Lua SDK

### Harness composition

`smith-harness` MUST load configuration, model registry, and authentication; resolve the active model; create providers and `StreamFn`; create the agent; load/manage plugins; expose the Lua SDK; bridge core and plugin events; translate plugin returns to core hooks; and coordinate TUI, eval, and RPC modes.

`Harness` MUST contain:

```text
Agent
provider map
ModelRegistry
ModelResolver
authentication resolver
PluginManager
optional TuiApp
active provider
active model
```

### Plugin identity and locations

Every plugin name is mandatory and MUST be:

```text
<org>/<name>
```

Both components MUST contain only lowercase ASCII letters, digits, `_`, and `-`. `smith/*` is reserved for built-ins. Installed global code MUST live at `data_dir/plugins/<org>/<name>/`; workspace code MUST live at `.smith/plugins/<org>/<name>/`; persistent plugin data MUST live at `data_dir/data/<org>/<name>/`.

### Manifest

Every plugin root MUST contain `smith-plugin.lua`. The manifest chunk MUST run in an empty environment with no globals, Smith SDK, or host I/O and MUST only construct and return pure data. Access to `os`, `require`, or any other global, and any function-valued field, MUST reject the manifest.

Required fields are:

```lua
return {
  name = "org/name",
  version = "0.1.0",
  entry = "init.lua",
}
```

Optional fields are:

```text
smith_api
description
license
authors
repository
dependencies
secrets
heap_limit
interfaces
implements
```

`heap_limit` is bytes. `interfaces` lists exported interface descriptors; `implements` lists implemented interface names. If omitted, `smith_api` MUST default to integer generation `1`. The host MUST validate the manifest before executing entry code.

### Plugin API compatibility

Plugin API versions MUST be integer generations, not semantic-version ranges. Generation `1` is the default. From Smith `1.0.0` onward, generation `1` MUST remain supported permanently. Future breaking APIs MUST use explicit generations `2`, `3`, and later.

A plugin MUST opt into a newer generation explicitly. A generation newer than the host supports MUST prevent loading. `smith plugins` MUST list the plugin as disabled and report both required and supported generations; silent or best-effort loading across an unknown generation is forbidden.

### Loading and registration precedence

A plugin entry MUST return a registration table or factory. Loading MUST occur in this order:

1. Load the manifest in its isolated environment.
2. Validate name, version, source, API generation, dependencies, and declared secrets.
3. Load entry Lua source in the restricted runtime.
4. Collect registrations.
5. Materialize host-side handles.
6. Register tools, events, commands, providers, interfaces, and TUI contributions.

Lua registration is canonical. Smith MUST NOT expose a Rust trait-object plugin API.

Plugins MUST load by precedence:

1. built-ins;
2. global user plugins;
3. workspace-local plugins;
4. explicit CLI/configuration overrides.

Later registrations MUST override earlier registrations unless a registration explicitly defines duplication as an error.

### Installation and uninstallation

Version 1 MUST install from a local directory or Git URL and MUST NOT require or expose a central plugin registry.

```text
smith install <path-or-git-url> [--force]
```

Installation MUST:

1. resolve the source into temporary staging;
2. read and validate manifest, namespace, and API compatibility in staging outside the global plugin root;
3. leave the entire global plugin root untouched on failure;
4. copy validated code to `data_dir/plugins/<org>/<name>/`;
5. refuse an existing destination unless `--force` is present; and
6. never execute entry code during installation.

Any existing destination directory is a duplicate regardless of version. `--force` MUST fully replace code while preserving `data_dir/data/<org>/<name>/`. A Git installation MUST omit `.git` and produce an immutable file snapshot; update is reinstallation.

```text
smith uninstall <org>/<name> [--purge-data]
```

Uninstall MUST remove installed global code, retain plugin data by default, remove `data_dir/data/<org>/<name>/` only with `--purge-data`, and MUST NOT remove a workspace-local plugin.

### Plugin interfaces

An interface package MUST export a pure-data descriptor with:

- `name`: `<org>/<name>`;
- `generation`: an integer interface generation distinct from plugin API and reload-domain generations;
- `functions`: a map from function name to `{ params, returns }`, using typed named parameters that MAY be optional; and
- `events`: bus topic names.

The same descriptor MUST drive runtime validation and generated LuaLS stubs using `---@class`, `---@field`, and `---@param`. Interface-only, implementation-only, externally referenced implementation, and combined interface/implementation packages MUST all work through manifest `interfaces` and `implements`.

An adapter entry MUST export:

```lua
adapts = "<org>/<name>"
```

and a `make(wrapped)` factory returning a conforming implementation. The manager MUST inject the wrapped plugin's exports into `make`.

Configuration MUST select an implementation with:

```lua
interfaces = { ["community/subagent"] = "org/name" }
```

Binding precedence is:

1. explicit configuration;
2. otherwise, the last-loaded plugin declaring `implements` for that interface.

Conformance MUST be checked at bind time. Failure MUST report the plugin, interface name/generation, every missing or malformed export with exact path, exports actually provided, and any adapter installed for that plugin.

Consumers MUST receive a view exposing only declared functions; private fields MUST be hidden. Calls MUST validate descriptor arguments and name the failing function and parameter. Each resolved binding MUST be a singleton shared by all consumers.

### Plugin event bridge

Every Lua event table MUST contain `type`. The catalog and blocking behavior are:

| Event | May block | Required behavior |
|---|---:|---|
| `resources_discover` | No | Contribute skill, prompt, and theme paths. |
| `session_start`, `session_shutdown` | No | Report started/loaded/reloaded and shutdown lifecycle. |
| `session_before_switch` | Yes | Run before leaf/session switching. |
| `session_before_fork` | Yes | Run before session clone/fork. |
| `session_before_compact` | Yes | Customize or block compaction. |
| `session_compact`, `session_tree` | No | Completed notifications. |
| `before_agent_start` | No | May inject messages or modify system prompt. |
| `agent_start`, `agent_end`, `turn_start`, `turn_end` | No | Agent lifecycle. |
| `model_select` | No | Active model changed. |
| `message_start`, `message_update`, `message_end` | No | Message streaming lifecycle. |
| `thinking_delta`, `text_delta` | No | Token deltas. |
| `tool_execution_start` | No | Execution began or call was blocked. |
| `tool_call` | Yes | Runs before execution. |
| `tool_execution_update`, `tool_result`, `tool_execution_end` | No | Updates and completion; `tool_result` may modify result. |
| `input` | No | Intercept, transform, or mark input handled. |
| `user_bash` | No | User `!` and `!!` commands. |
| `context` | No | Modify messages before an LLM call. |
| `before_provider_request`, `after_provider_response` | No | Inspect/replace request; observe response. |
| `config_changed` | No | Carries changed configuration paths. |
| `plugin_loaded`, `plugin_unloaded` | No | Plugin lifecycle. |
| `panel_toggle`, `resize` | No | TUI lifecycle. |
| `provider_registered` | No | Emitted after provider addition/override. |
| VCS events | No | Report VCS operations. |
| error events | No | Report classified errors. |
| `shutdown` | No | Host shutdown. |

Handler return contracts are exact:

```lua
-- tool_call
{ block = true, reason = "..." }
{ args = replacement }
{ cancel = true }
nil -- or {}, allow

-- tool_result
{ content = replacement }
{ retry = true }
{ cancel = true }
nil -- keep original

-- turn_end
{ stop = true } -- ShouldStopAfterTurn
nil             -- continue

-- input
{ action = "handled" | "continue", text = transformed_or_nil }

-- context
{ messages = modified }
nil

-- session_before_*
{ block = true, reason = "..." }
nil
```

All other return values MUST be ignored. The bridge MUST translate accepted returns into `AgentLoopConfig` hooks.

### Extension contexts

The SDK MUST expose:

- `ExtensionContext` for agent lifecycle, model, context, tools, config, and logging;
- `ExtensionCommandContext` for slash-command arguments, selection, output, and session; and
- `ExtensionUIContext` for selection, confirmation, prompt, status, layout, and widgets.

Event handlers, tool `execute`, and command handlers MUST receive this context shape:

```lua
ctx = {
  ui = {
    notify = function(message, level) end, -- "info"|"success"|"error"|"warning"
    confirm = function(title, message) end,   -- -> bool
    select = function(title, items) end,      -- -> chosen item
    input = function(title, placeholder) end, -- -> string
    set_status = function(key, text) end,
    set_widget = function(key, lines) end,
  },
  session = { -- read-only
    id = "...", name = "...",
    entries = function() end,     -- -> table
    entry_count = function() end, -- -> number
    branch = function() end,      -- -> table
  },
  model = { id = "...", provider = "..." },
  cwd = "/path/to/workspace",
  signal = AbortSignal,
  shutdown = function() end,
}
```

### Lua SDK surface

`require("smith")` MUST expose:

- `smith.fs.*`;
- `smith.search.*`;
- `smith.env.*`;
- `smith.time.*`;
- `smith.log.*`;
- `smith.tool.*`;
- `smith.command.*`;
- `smith.provider.*`;
- `smith.alias.*`;
- `smith.group.*`;
- `smith.bucket.*`;
- `smith.tui.*`;
- `smith.vcs.*`;
- `smith.bus.*`;
- `smith.config.*`, with read access and `smith.config.reload()`;
- `smith.secret.*`, including `register(value, label)` and `list()`; `list()` MUST expose only IDs and labels;
- `smith.shortcut.*`;
- `smith.credentials.*`, including `get(provider)` and `set(provider, value)` over auth storage;
- `smith.active_tools.*`, including `get()`, `all()`, and `set(names)`;
- `smith.send_message(text, { deliver_as = "steer" | "followUp" })`;
- `smith.send_user_message(text)`;
- `smith.abort()`;
- `smith.shutdown()`; and
- `smith.getContextUsage()`.

Registration signatures MUST support:

```lua
smith.tool.register({
  name = "my_tool",
  description = "shown to the LLM",
  parameters = { -- JSON Schema table
  },
  execute = function(input, ctx)
    return { content = { { type = "text", text = "..." } } }
  end,
})

smith.command.register("name", {
  description = "...",
  autocomplete = function(prefix) end, -- optional -> { {value, label}, ... }
  handler = function(args, ctx) end,
})

smith.shortcut.register("ctrl+shift+p", {
  description = "...",
  handler = function(ctx) end,
})
```

Every tool parameter table MUST validate as JSON Schema.

### Provider registration

`smith.provider.register(name, table)` MUST add a provider or merge an existing provider with these rules:

- `base_url`, `api_key`, and `api` override prior values;
- `headers` merge by key;
- `oauth` replaces the entire prior value;
- `models` merge by model ID, then recursively field by field under the same rules;
- omitted fields retain prior values; and
- `replace_models = true` removes existing models before applying new models.

`smith.provider.unregister(name)` MUST remove one provider. `smith.provider.unregister_model(provider, model_id)` MUST remove one model. Every provider table MUST pass the bundled full schema.

### Public binding annotations

Every public Lua SDK function MUST have LuaLS/EmmyLua `---@` annotations; LuaLS is the only supported annotation dialect. Each binding MUST declare:

- `---@param` for every argument, with name, type, and description;
- `---@return` for every result, with type and description; and
- a `---@usage` block with a runnable example.

Runtime argument schemas and generated documentation MUST derive from these annotations so runtime validation and documentation remain synchronized.

### Built-in plugins and commands

Built-ins MUST be Lua plugins, not host-language feature special cases. They MUST provide:

- tools `read`, `write`, `edit`, `bash`, `find`, `grep`, and `ls`;
- slash commands `/undo`, `/redo`, `/history`, `/tree`, `/reload-config`, `/secret`, `/auth login <provider>`, `/model`, and replay/time-travel commands;
- VCS tools;
- default layout, keybindings, theme, and prompts.

`/model` MUST be a fuzzy picker over resolver names.

### Built-in tool contracts

#### `read`

```text
path: string
offset?: number
limit?: number
```

`read` MUST read text files, support line windows, bound output for LLM context, and either reject binary input or return explicit binary metadata.

#### `write`

```text
path: string
content: string
```

`write` MUST create missing parent directories, write atomically through temporary-file-plus-rename, and record a VCS operation after success.

#### `edit`

```text
path: string
old_text: exact string
new_text: string
allow_multiple?: bool
```

Execution order and error codes are exact:

1. Read the file; missing file returns `ENOENT`.
2. Reject empty `old_text` with `EEMPTY` and binary content with `EBINARY`.
3. Count exact matches; zero returns `ENOMATCH`; multiple returns `EMULTI` unless `allow_multiple` is true.
4. Immediately before writing, re-read and hash; any change returns `ESTALE`.
5. Atomically write using temporary-file-plus-rename; locking/write conflict returns `ELOCK`.
6. Return replacement count and before/after hashes, then record the VCS operation.

#### `bash`

```text
command: string
timeout?: number
cwd?: string
```

`bash` MUST execute off the UI thread, capture stdout, stderr, and exit status, enforce timeout, include output-truncation metadata, and observe abort.

#### `find`, `grep`, and `ls`

- `find` MUST honor gitignore-style files and return sorted paths subject to limits.
- `grep` MUST support context lines, glob filters, case-insensitive matching, literal and regular-expression modes, and match limits.
- `ls` MUST return alphabetically sorted entries, suffix directories, bound output, and return explicit errors.

### VCS SDK

The read-only API is exact:

```lua
smith.vcs.status()               -- { modified={}, added={}, deleted={}, renamed={} }
smith.vcs.diff(opts)             -- { hunks={}, text="..." }
smith.vcs.diff_revs(a, b)        -- diff between revisions/operations
smith.vcs.op_log({ limit = n })  -- { { id, description, time, op_type } }
smith.vcs.op_show(op_id)         -- { id, description, diff, files }
smith.vcs.annotate(path, opts)   -- line attribution data
smith.vcs.interdiff(a, b)        -- patch-vs-patch comparison
smith.vcs.evolog(rev)            -- logical change evolution
```

The mutation API MUST accept explicit validated inputs:

```lua
smith.vcs.commit(message)
smith.vcs.undo()
smith.vcs.redo()
smith.vcs.op_restore(op_id)
smith.vcs.restore_paths(paths, rev)
smith.vcs.split(opts)
smith.vcs.squash(source, dest)
smith.vcs.parallelize(revs)
smith.vcs.sparse(paths)
smith.vcs.workspace_add(name, opts)
```

Implementation-native details MUST remain hidden behind these Smith-shaped tables.

### Plugin sandbox and heap limits

Local plugins are trusted but constrained to SDK capabilities. Raw `io`, `os`, and `debug` MUST be unavailable; filesystem/environment access MUST use the SDK. Version 1 MUST NOT implement path capabilities. Built-in and user plugins MUST receive identical APIs.

A plugin MAY declare `heap_limit` in bytes; configuration MAY override it and MUST win. Every plugin MUST own a separate Lua state and heap-limit domain. Shared-state per-plugin limits MUST NOT be offered.

The limit MUST be exact where the target supports enforcement. Exceeding it MUST be a recoverable plugin memory error. A target unable to enforce limits MUST loudly reject heap-limit configuration and MUST NOT silently apply zero or an ineffective limit.

The limit MUST include the plugin Lua heap and host-created Lua values. Host allocations held on behalf of the plugin are outside that heap limit and MUST be bounded through whole-domain teardown. After out-of-memory, whole-domain replacement SHOULD be used rather than in-place retry.

### Dependency resolution

A dependency MUST name a plugin and minimum Smith API generation:

```lua
dependencies = {
  { name = "acme/logger", smith_api = 1 },
}
```

Version 1 MUST resolve only already-available plugins and MUST NOT perform network dependency resolution or semantic-version range solving.

After manifests load and before entry execution, each built-in, global, and workspace plugin set MUST be resolved by:

1. building a graph from validated manifests;
2. disabling a plugin with an absent dependency and reporting that dependency;
3. disabling a plugin whose dependency supports a lower API generation than requested;
4. detecting cycles, disabling every plugin in each cycle, reporting the complete path, and never partially loading it; and
5. loading topologically so dependency registrations exist before dependent entry code.

Dependencies express only presence and API generation. Normal registration precedence MUST still apply, including overrides across dependency edges.

### Plugin domains and hot reload

A reload MUST replace a complete plugin domain, never mutate one in place. A domain MUST own:

- Lua runtime and registry handles;
- tool, command, provider, shortcut, and interface registrations;
- event and `smith.bus` subscriptions;
- TUI layouts/widgets and render caches;
- host scratch allocations; and
- cancellation tokens for plugin tasks.

Nothing plugin-owned may outlive its domain. Every registration MUST be keyed by domain generation; registrations that cannot be tied to a domain MUST be rejected. Raw callback handles MUST remain only in the generation-keyed registry. Every dispatch MUST verify the active generation before entering Lua. An inactive generation MUST be rejected diagnostically and MUST NOT begin execution. The loader MUST audit for escaped registrations associated with inactive generations.

Reload MUST be requestable by:

- `smith plugins reload <org>/<name>`;
- workspace-local file change when watch reload is enabled; and
- reinstallation of a loaded plugin.

Built-in `smith/*` plugins MUST use the same mechanism.

For plugin `P` with active domain `D` and candidate `D'`, reload MUST:

1. construct `D'` and validate/load its manifest, entry, and registrations in isolation;
2. on failure, drop `D'`, retain `D`, and report the error;
3. on success, atomically replace registrations and subscriptions with `D'`, mark `D` retired, and activate `D'`; and
4. drop `D` after its allowed in-flight work and deferred bus dispatch complete, tearing down its Lua state, registrations, subscriptions, caches, and scratch memory.

Reload MUST be all-or-nothing. Failure MUST leave the old domain and bindings active and no candidate state. Repeated reloads MUST plateau in live memory after warmup; immediate RSS reduction is not required.

Domain teardown MUST wait for an executing Lua callback; Lua MUST NOT be preempted. A bus handler follows the condemned/deferred rules below. A tool invocation already running under `D` MUST finish under its pinned domain and deliver its result; invocations begun after swap MUST use `D'`. No new stale callback may begin after swap.

Reload MUST preserve session identity/entries, agent state, and other plugin domains. If `P` backs an interface, candidate binding and conformance MUST be revalidated before commit. Existing interface views MUST transparently dispatch their next call to `D'`. Conformance failure MUST roll back. Dependents MUST NOT reload; stable names MUST rebind, and a removed registration MUST produce a normal missing-registration error on next use.

### Plugin errors

Every plugin error MUST include plugin name and phase and MUST NOT corrupt the host, terminal, or another plugin.

- **Manifest/validation:** invalid name/version, unsupported `smith_api`, or missing/cyclic dependency MUST disable the plugin, list the reason in `smith plugins`, and allow unrelated plugins to load.
- **Entry load:** Lua failure or invalid collected registration MUST discard all partial registrations and disable the plugin. During reload, the old domain MUST remain active.
- **Event handler:** the host MUST catch and log through `smith.log`; treat the return as absent; continue other handlers. For blocking events, failure means no decision and MUST NOT block.
- **Tool execute:** a Lua error or returned tool error MUST become a normal error tool result; host and loop MUST continue.
- **Bus handler:** the host MUST catch/log and continue later subscribers.
- **Out of memory:** the host MUST report a recoverable memory error and MAY replace the domain.

Host library code MUST NOT panic on plugin input.

### Inter-plugin bus

`smith.bus.*` is the only sanctioned direct plugin-to-plugin messaging channel. It MUST remain separate from lifecycle events, and plugins MUST NOT emit core event types through it.

```lua
local handle = smith.bus.on("acme/index-ready", function(payload, ctx)
  ctx.ui.notify("index has " .. payload.count .. " files", "info")
end)

smith.bus.emit("acme/index-ready", { count = 128 })
smith.bus.off(handle)
```

Rules:

- Topics MUST use `<org>/<topic>` and the plugin-name character set. `smith/*` is reserved for built-ins. A plugin MAY emit any nonreserved topic; its own organization is conventional.
- Payloads MUST be top-level plain Lua data tables. Functions, userdata, and host handles MUST NOT cross the bus.
- Delivery MUST be synchronous, on the plugin thread, in subscriber-registration order within the current tick.
- An emit during delivery MUST enter one global FIFO regardless of topic and run only after the current dispatch, in emit order.
- The bus MUST never re-enter; maximum dispatch depth is `1`.
- If teardown is requested during dispatch, the domain MUST be condemned immediately. Remaining deliveries to it MUST be skipped with a diagnostic; actual drop MUST wait until the entire dispatch FIFO drains.
- A handler MAY request its own teardown and MUST finish normally.
- Subscriptions MUST be domain-owned and removed on unload/reload; stale subscribers MUST not survive.
- Subscriber errors MUST not prevent later subscribers.
- Messages emitted before subscriber load MUST not replay. The bus is fire-and-forget, not durable.

Plugins MAY also compose through stable registries and the core event bridge.

### Runtime configuration reload

Reload MUST preserve the process and active session and use validate-then-atomic-swap semantics. It MUST re-evaluate layers 1–4. Layer-5 CLI flags are resolved once, MUST remain unchanged, and MUST continue to override the candidate.

Reload triggers are:

- `/reload-config`;
- `smith.config.reload()`;
- `config_dir/config.lua` change when config watch reload is enabled;
- RPC `config/reload`; and
- automatic cascade re-evaluation after every plugin reload, whether or not layer-3 contributions changed.

`config/reload` MUST return success with changed paths or the validation failure verbatim. Eval mode MUST read configuration at startup and MUST NOT expose runtime reload.

Reload order is exact:

1. Evaluate the cascade into a candidate.
2. Validate every value against host schemas.
3. Validate the complete alias/group/bucket graph, not only the active chain.
4. If any step fails, report all failures together with exact key paths, discard the candidate, retain active configuration, and permit a later retry.
5. Atomically activate a valid candidate.
6. Apply theme, keybindings, active tool set, then resolved model/provider, in that order.
7. Re-render the TUI with the new theme on the next frame.
8. Emit `config_changed` with changed paths and no secrets.

Changed-path calculation MUST compare effective post-CLI configuration, omit changes masked by CLI values, treat a list-valued key as one path, include additions/removals, and emit an empty list for an idempotent reload.

An in-flight turn MUST retain the model, tools, and system prompt captured at its start; the next turn MUST use new values. Running tools MUST finish with old values. Session identity, entries, and plugin domains MUST remain unchanged. Configuration reload MUST NOT load, unload, or reload plugin code.

The following are fixed for process lifetime and MUST NOT hot-reload:

- CLI flags;
- config, data, and cache directory locations;
- active session identity and storage paths;
- run mode: interactive, eval, or RPC; and
- bundled `providers.json`.

Runtime provider changes MUST use `smith.provider.*`. Credential resolution MUST NOT be cached across reload; the next provider stream MUST resolve from the new effective configuration and auth sources.

## CLI and RPC

### CLI

The executable MUST be `smith`. Global options are exact:

```text
--model <model>
--provider <provider>
--session <id-or-name>
--config <path>
--no-config
```

Commands and behavior are:

- `smith` MUST start the interactive TUI in a new automatically named session.
- `smith new <name>` MUST start a new named interactive session.
- `smith attach [id-or-name]` MUST attach to that session; no argument MUST open fuzzy selection.
- `smith continue` MUST continue the latest current-working-directory session.
- `smith resume` MUST fuzzy-select among sessions in the current working directory.
- `smith session list [--cwd]` MUST list sessions.
- `smith session dump [id] [--last N] [--output path]` MUST write JSONL.
- `smith plugins` MUST list every plugin, including disabled plugins and each reason.
- `smith plugins reload <org>/<name>` MUST atomically reload one loaded plugin.
- `smith install <plugin> [--force]` MUST install a local-path or Git-source plugin under the installation contract.
- `smith uninstall <plugin> [--purge-data]` MUST uninstall under the retention contract.
- `smith eval <prompt> [--json] [--session id]` MUST run non-interactive evaluation.
- `smith rpc` MUST run JSON-RPC 2.0 over stdin/stdout and include `config/reload`.
- `smith completions <shell>` MUST generate completions for the requested shell.
- `smith help [topic] [--search q] [--list] [--examples] [--example name] [--guide name]` MUST select help, search, listing, examples, and guides. Dotted function addressing is required: `smith help tool.register` resolves `register` under `tool`.
- `smith replay <session> [--speed f64] [--compare] [--sandbox path] [--turns N] [--from-turn N] [--format text|json|summary] [--continue-on-diff bool]` MUST apply the selected replay controls.

Interactive slash commands MUST be registered by Lua plugins and MUST NOT be binary subcommands.

The entrypoint MUST parse CLI input, resolve configuration, create `Harness`, and dispatch to interactive, eval, RPC, replay, session, plugin, or help handling. Errors and signals MUST restore terminal state. Fatal commands MUST diagnose and exit nonzero.

### RPC projection model

`smith rpc` MUST expose JSON-RPC 2.0 bidirectionally over standard input/output. Its catalog MUST be a structural projection of the Lua SDK, not a direct mirror. Every surface has independent origin (SDK-mirrored or RPC-only) and shape (data request/response, callback, or notification).

These data/configuration surfaces MUST project as client request to server response methods:

```text
fs
search
env
time
log
provider
alias
group
bucket
vcs
config
secret
active_tools
credentials
send_message
abort
shutdown
getContextUsage
```

Callback-bearing APIs MUST invert direction:

- `tool.register`, including `execute`;
- command handlers and autocomplete callbacks; and
- `bus.on` callbacks.

Registration originates client-to-server. Invocation MUST be a server-to-client JSON-RPC request whose reply is awaited. Other non-callback operations in a projected callback namespace MAY remain ordinary client-to-server requests. Callback registration therefore requires bidirectional RPC.

Headless RPC MUST omit Lua-runtime-only `tui` and `shortcut` surfaces because it has no terminal or keyboard.

### RPC-only driver methods

External clients MUST receive these RPC-only methods:

```text
session/open
session/attach
session/list
session/dump
session/snapshot
session/fork
session/subscribe
prompt/submit
command/run
```

`session/dump` MUST return persisted transcript, tree, current leaf, and fold state, with secret registration plaintext redacted. `session/snapshot` MUST return ephemeral queue state and in-flight run status needed for mid-session attachment; this state MUST NOT be persisted as a session entry.

### RPC frontend event boundary

RPC MUST be a peer frontend to the TUI. Its event stream MUST adapt the same `EngineEvent` stream, not dispatch through the Lua plugin bridge. Public event names and hook responses MAY project the equivalent plugin-event vocabulary, but their source of truth MUST remain `EngineEvent` and core hooks.

Nonblocking events MUST be server-to-client notifications. Blocking `tool_call` and `session_before_*` events MUST be server-to-client requests accepting allow/block/replace responses according to their hook contracts. Even an observer that registers no behavior MUST support this reverse request channel and return a neutral response.

Frontend-private events for panel toggling, resizing, selection, focus, and scrolling MUST be omitted.

The wire MUST let a headless frontend reconstruct transcript, tools, combined steering/follow-up queue, conversation tree/current leaf, model, cost, folds, and secret placeholders, with these exact rules:

- `session_compact` notifications MUST contain `covered_span: { summary_id, start, end }`. Folds are assembled at runtime and raw persisted entries remain unchanged.
- `session_tree` notifications MUST contain `{ id, parent, kind }` records and the current leaf; branches remain emergent.
- Mid-session attachment MUST use `session/snapshot`; notifications have no replay and omit reconstructible prior ephemeral state.
- Cost/context usage MUST be polling-only through `getContextUsage` in version 1. No push event is required; a future `context_usage` notification is permitted.

Secret plaintext MUST never cross RPC. Only `smith:sec:N` placeholders and labels/IDs MAY cross.

RPC transport framing is intentionally selectable: line-delimited JSON and `Content-Length` framing are both permitted.

## Security

### Trust boundary

Smith MUST treat the local user, operating system, filesystem, local plugins, Smith code, and local session/configuration/cache files as trusted. It MUST treat the remote LLM and provider network-response content as untrusted. Provider/LLM response data is the only untrusted content domain in the version-1 product model.

### Required controls

1. `ToolRegistry` MUST determine which tools the LLM may invoke.
2. The secret proxy MUST prevent registered plaintext secrets from entering LLM context, traces, public events, or RPC.
3. Restricted Lua MUST expose no raw operating-system or filesystem APIs.
4. Users MUST configure active tools. Confirmation dialogs MUST NOT be treated as a security boundary.
5. Credentials MUST remain plaintext in permitted local storage, with no keychain integration or encryption.

The plugin sandbox is a constrained product API, not a hostile-code security boundary. Version 1 MUST NOT perform heuristic secret discovery in core and MUST NOT implement filesystem path capabilities.

## Concurrency

### Execution domains

- The engine/main domain MUST own the harness event loop and agent state.
- The UI side MUST render and poll input without blocking the engine. Rendering MUST remain synchronous on the UI render thread; blocking terminal polling MUST use its dedicated poller thread and channels.
- A tool thread pool MUST execute subprocess, file, and host-side plugin-tool work off the UI thread. Lua portions MUST dispatch to the plugin actor rather than move Lua values to the pool.
- Provider HTTP streaming MUST use asynchronous tasks.
- One dedicated operating-system plugin thread MUST own every plugin Lua state. Lua states MUST be created and dropped there; Lua values MUST never cross a thread boundary.

### Plugin actor

Hooks, bus calls, and plugin callbacks MUST use channel-actor dispatch:

- The engine sends a plain-data request and awaits asynchronously.
- Only plain data may cross the boundary.
- Requests MUST execute serially in arrival order across all plugins.
- Bus ordering and domain-generation rules MUST execute on this thread.

### Responsiveness and cancellation

A UI keypress MUST be acknowledged within 16 ms, including while plugin CPU work runs. The engine MUST never synchronously block the UI.

Every long-running operation MUST observe abort except already executing Lua. Lua cannot be preempted. On abort, the engine MUST abandon a pending hook dispatch, drop its reply receiver, and continue; Lua may finish, and its late reply MUST be discarded. Any hard cancellation of runaway Lua MUST occur only by whole-domain teardown, never in-place interruption, and normal teardown MUST wait for currently executing Lua.

Hook deadlines are soft. A hook MAY block only its own dispatching turn and queued plugin dispatches; the shared plugin thread creates head-of-line blocking only inside plugin dispatch. It MUST NOT block the UI, tool pool, or engine runtime. Exceeding the configured soft deadline MUST produce a plugin diagnostic and MUST NOT kill the hook.

## Performance

The product MUST satisfy:

- each stripped release binary is smaller than 20 MB;
- interactive startup is less than 100 ms;
- `smith --help` completes in less than 100 ms;
- a TUI frame draw completes in less than 2 ms within the 16 ms frame budget;
- layout resolution over 80×24 through 400×100 has release-build p99 below 0.8 µs, with approximately 0.4 µs as the target;
- encoding a 1,000-entry session completes in less than 5 ms;
- UI keypress acknowledgment is at most 16 ms; and
- an agent-loop turn SHOULD complete in less than 30 seconds, excluding provider/network stalls beyond configured timeout.

A release MUST NOT exceed a mandatory threshold because of a performance regression.

### Memory behavior

Session discovery MUST be lazy and metadata-only: it MUST read session headers, never complete bodies, and perform work proportional to session count rather than corpus bytes.

Virtual scrolling MUST materialize no more than viewport rows per frame. Row formatting MUST stop at the visible window through lazy wrapping; showing a slice of a multi-MiB message MUST NOT format the complete message.

Arenas MUST be scratch-only and phase-local to measured rendering or request scratch. Persisted/session data MUST use stable IDs and owned strings, never arena references. Custom or unsafe arena implementations MUST NOT be used. Arena references MUST NOT cross asynchronous, thread, or persistence boundaries.

Arena decisions MUST consider allocator-call pressure, elapsed time, and peak/plateau stability, not allocation count alone. Render-frame scratch qualifies; request-build scratch MUST NOT be presumed faster when serialization dominates.

Provider request assembly at compaction-scale contexts MUST have transient peak memory no greater than a small multiple of serialized request size and MUST release that transient memory fully after send. Peak memory, not CPU alone, is an acceptance requirement.

## Release Artifacts

### Target matrix

| Platform | Target triple | Obligation |
|---|---|---|
| Windows x86_64 | `x86_64-pc-windows-msvc` | required |
| Windows ARM64 | `aarch64-pc-windows-msvc` | required |
| macOS Intel | `x86_64-apple-darwin` | required |
| macOS Apple Silicon | `aarch64-apple-darwin` | required |
| Linux x86_64 glibc | `x86_64-unknown-linux-gnu` | required |
| Linux ARM64 glibc | `aarch64-unknown-linux-gnu` | required |
| Linux x86_64 musl | `x86_64-unknown-linux-musl` | required |
| Linux ARM64 musl | `aarch64-unknown-linux-musl` | required |
| Android ARM64 | `aarch64-linux-android` | required |
| Linux riscv64 glibc | `riscv64gc-unknown-linux-gnu` | best-effort |
| Linux riscv64 musl | `riscv64gc-unknown-linux-musl` | best-effort |
| FreeBSD x86_64 | `x86_64-unknown-freebsd` | best-effort |
| OpenBSD x86_64 | `x86_64-unknown-openbsd` | best-effort |

Linux glibc, Linux musl, and Android Bionic MUST remain distinct libc targets. Android MUST link the compiler-runtime builtins required by Rust; an environment unable to supply them cannot produce the required artifact.

Failure of a required target MUST stop release. A best-effort failure MUST be skipped, documented with its reason in release notes, and MUST NOT block other artifacts. Every target MUST be accounted for as built or skipped; none may be silently omitted. The matrix MUST be cross-compiled from one host wherever a target permits it.

### Names and guarantees

Every built target MUST produce:

```text
smith-{triple}-v{version}.{zip|tar.gz}
```

and an entry in:

```text
checksums-sha256.txt
```

Windows artifacts MUST use the MSVC ABI; GNU ABI MUST NOT substitute. Linux glibc artifacts MUST run on glibc 2.28 or newer, including Debian 10, RHEL 8, and Ubuntu 18.10. Raising that minimum is a product-specification change.

Version 1 MUST NOT ship install scripts, package manifests, distribution metadata, or code signing.

## Documentation

`smith help` is the product documentation interface and MUST support topic lookup, dotted SDK addressing, full listing, text search, examples, named runnable examples, and named guides through the exact CLI flags above.

Documentation lookup MUST use the first available source in this order:

1. content embedded in the binary;
2. `<prefix>/share/smith/docs/`;
3. `SMITH_DOCS_PATH`.

The system prompt MUST direct capability discovery to `smith help --search`, `smith help --guide`, and `smith help --example` rather than embedding the complete SDK.

Every public Lua function's runtime schema and documentation MUST derive from its LuaLS annotations. Interface descriptors MUST generate matching LuaLS `---@class`, `---@field`, and `---@param` stubs. Documentation examples declared by `---@usage` MUST be runnable as written.

Documentation completeness MUST guarantee that every Rust SDK function has corresponding Lua binding documentation, every public Lua binding exists in code and is documented, and every event appears in at least one example.

Diagnostics documented as path-qualified—configuration, themes, interface conformance, tool arguments, plugins, and reload—MUST preserve those exact paths in user-visible output.

## Product Acceptance

A Smith release conforms only if every applicable **MUST** and **MUST NOT** in this specification holds. At minimum, end-to-end acceptance MUST demonstrate:

- first run reaches an unbordered default layout without onboarding and accepts input within the startup limit;
- missing auth fails before streaming, preserves input, and gives credential, environment, and OAuth guidance when available;
- streaming, tools, live usage, direct bash, VCS recording, steering, follow-ups, cancellation, and abort repair produce the specified ordered transcript;
- conversation leaf switching never changes files, VCS restoration never implicitly changes conversation leaf, and replay never mutates the live session;
- continuation restores leaf/history/cost but no ephemeral queue;
- truncated/corrupt/unknown session records recover at the specified framing boundaries;
- registered secrets remain placeholders at provider, trace, event, display, and RPC boundaries and rehydrate only for tools;
- resolver validation, deterministic rotation, deduplication, retries, failover, and signed-thinking replay behave exactly as specified;
- built-in and user facilities use the same restricted Lua SDK, plugin precedence, domain teardown, error isolation, bus ordering, and atomic reload rules;
- TUI and RPC consume the same engine behavior while exposing only their permitted frontend-specific surfaces;
- configuration reload is all-or-nothing and preserves in-flight continuity;
- layout resolution keeps every child within its parent, tiles flow siblings without overlap, gives `expanded` the exact remainder, and makes `split` tile exactly while honoring its ratio within one cell;
- widget and theme acceptance records each styled cell's symbol, foreground, background, and modifiers; text-only records validate layout only;
- all mandatory performance and memory limits hold; and
- every release artifact satisfies its target, naming, checksum, ABI, libc, size, and failure-policy requirements.