Expand description
§supercode
A lightweight, fully-customizable AI coding-agent SDK in Rust.
supercode is a native agent loop — it talks directly to any model through
OpenRouter (or any other OpenAI-compatible endpoint),
drives a configurable set of tools, and is designed to be a superset of what
tools like Claude Code and Codex can do: every prompt, every tool description,
and every tool’s on/off state is yours to control.
§Quick start
use supercode_harness::{Agent, Config};
// Reads OPENROUTER_API_KEY from the environment by default.
let config = Config::builder()
.model("anthropic/claude-opus-4-8")
.system_prompt("You are a terse, expert pair programmer.")
.build();
let mut agent = Agent::new(config)?;
let reply = agent.send("List the files in the current directory.").await?;
println!("{reply}");§Design
Config— the single knob box: model, endpoint, credentials, sampling, the system prompt, and per-tool overrides (enable/disable + custom descriptions).Provider— the model transport.OpenAiProviderspeaks the OpenAI chat-completions wire format and defaults to OpenRouter, so it reaches Claude, GPT, Gemini, Llama, and anything else OpenRouter exposes.Tool/ToolRegistry— the capability surface. Built-ins cover file read/write/edit, directory listing, glob, content search, and shell execution. Register your own to extend it.Agent— the loop that ties it together: it streams a turn, runs any tool calls the model requests, feeds results back, and repeats until the model produces a final answer.
Re-exports§
pub use acp_frontend::AcpFrontendCheckpoint;pub use acp_frontend::AcpFrontendConnectOptions;pub use acp_frontend::AcpFrontendRuntime;pub use claude_peer::message_claude_peer;pub use claude_peer::read_registry as read_claude_peer_registry;pub use claude_peer::ClaudePeerDelivery;pub use claude_peer::ClaudePeerEndpoint;pub use claude_peer::ClaudePeerRefusal;pub use claude_peer::ClaudePeerRefusalError;pub use claude_peer::ClaudePeerSession;pub use claude_peer::ClaudePeerStatus;pub use claude_peer::CourierRunner;pub use claude_peer::ProcessCourierRunner;pub use claude_runtime_scheduler::ClaudeCronScheduleState;pub use claude_runtime_scheduler::ClaudeRuntimeDeliveryState;pub use claude_runtime_scheduler::ClaudeRuntimeSchedulerState;pub use claude_runtime_scheduler::ClaudeRuntimeTrigger;pub use claude_runtime_scheduler::ClaudeRuntimeTriggerKind;pub use claude_runtime_scheduler::ClaudeWakeupScheduleState;pub use claude_runtime_state::ClaudeBackgroundChild;pub use claude_runtime_state::ClaudeBackgroundState;pub use claude_runtime_state::ClaudeCronJob;pub use claude_runtime_state::ClaudeQueueState;pub use claude_runtime_state::ClaudeRuntimeExecutionState;pub use claude_runtime_state::ClaudeRuntimeManifest;pub use claude_runtime_state::ClaudeRuntimePosture;pub use claude_runtime_state::ClaudeRuntimeResidue;pub use claude_runtime_state::ClaudeWakeup;pub use claude_runtime_state::CLAUDE_RUNTIME_MANIFEST_VERSION;pub use configfile::HarnessConfig;pub use live_runtime::discover_live_runtime;pub use live_runtime::find_live_runtime;pub use live_runtime::forget_live_runtime;pub use live_runtime::list_live_runtimes;pub use live_runtime::register_live_runtime;pub use live_runtime::register_live_runtime_with_metadata;pub use live_runtime::resolve_live_runtime;pub use live_runtime::LiveRuntimeEndpoint;pub use live_runtime::LiveRuntimeMetadata;pub use live_runtime::LiveRuntimeReceiptError;pub use live_runtime::LiveRuntimeRecord;pub use live_runtime::LiveRuntimeRegistration;pub use live_runtime::LiveRuntimeSource;pub use live_runtime::LiveRuntimeSupervisor;pub use live_runtime::ResolvedLiveRuntime;pub use modules::ModuleActivation;pub use modules::ModuleId;pub use frontend::HttpFrontendRuntime;pub use frontend::FrontendActions;pub use frontend::FrontendApprovalDecision;pub use frontend::FrontendAttachSnapshot;pub use frontend::FrontendAttachment;pub use frontend::FrontendCommandDescriptor;pub use frontend::FrontendConnectionState;pub use frontend::FrontendDisplayCapabilities;pub use frontend::FrontendElicitationAction;pub use frontend::FrontendEvent;pub use frontend::FrontendOperationDescriptor;pub use frontend::FrontendOperationInvocation;pub use frontend::FrontendOperationKind;pub use frontend::FrontendOperationResult;pub use frontend::FrontendRequest;pub use frontend::FrontendRequestKind;pub use frontend::FrontendResponse;pub use frontend::FrontendRuntime;pub use frontend::FrontendRuntimeDescriptor;pub use frontend::FrontendRuntimeError;pub use frontend::FrontendRuntimeMetadata;pub use frontend::FrontendTurnState;pub use frontend::FRONTEND_REPLAY_CAPACITY;pub use frontend::FRONTEND_RUNTIME_SCHEMA_VERSION;pub use harness_service::HarnessSessionService;pub use harness_service::HARNESS_SERVICE_VERSION;pub use harness_service::RUNTIME_EVENT_METHOD;pub use harness_service::SESSION_EVENT_METHOD;pub use runtime::SupercodeHttpRuntimeBackend;pub use runtime::AcpRuntimeBackend;pub use runtime::ClaudeCodeRuntimeBackend;pub use runtime::CodexRuntimeBackend;pub use runtime::HarnessEvent;pub use runtime::OpenCodeRuntimeBackend;pub use runtime::PiRuntimeBackend;pub use runtime::RuntimeAttachRequest;pub use runtime::RuntimeBackend;pub use runtime::RuntimeCapabilities;pub use runtime::RuntimeConnection;pub use runtime::RuntimeEndpoint;pub use runtime::RuntimeHandle;pub use runtime::RuntimeInput;pub use runtime::RuntimeLaunch;pub use runtime::RuntimeStartRequest;pub use runtime_lease::CoordinatedRuntime;pub use runtime_lease::CoordinatedRuntimeClient;pub use runtime_lease::RuntimeAuthorization;pub use runtime_lease::RuntimeClientId;pub use runtime_lease::RuntimeControllerLease;pub use runtime_lease::RuntimeLeaseCoordinator;pub use runtime_lease::RuntimeLeaseError;pub use runtime_lease::RuntimeLeaseSnapshot;pub use runtime_lease::RuntimeObserverLease;pub use runtime_lease::RuntimePermission;pub use runtime_lease::DEFAULT_RUNTIME_LEASE_TTL_MS;pub use runtime_registry::LocalRuntimeRegistry;pub use runtime_registry::RuntimeRegistryEntry;pub use runtime_registry::RuntimeRegistryEvent;pub use runtime_registry::RuntimeRegistryOwner;pub use runtime_registry::RuntimeRegistryQuery;pub use runtime_registry::RuntimeRegistryState;pub use runtime_registry::RuntimeRegistryWatch;pub use sandbox::landlock_available;pub use sandbox::netns_available;pub use sandbox::SandboxEnvPolicy;pub use sandbox::SandboxEscalation;pub use sdk::create_agent;pub use sdk::discover_session_page;pub use sdk::discover_sessions;pub use sdk::load_session;pub use sdk::load_session_path;pub use sdk::resume_agent;pub use sdk::submit_agent;pub use sdk::submit_agent_with_images;pub use sdk::RuntimeSubmitError;pub use sdk::SdkAgent;pub use sdk::SdkCapabilities;pub use sdk::SdkError;pub use sdk::SdkErrorCode;pub use sdk::SdkEvent;pub use sdk::SdkOperation;pub use sdk::SdkPromptSource;pub use sdk::SdkRequest;pub use sdk::SdkRuntime;pub use sdk::SdkRuntimeEvent;pub use sdk::SdkService;pub use sdk::SDK_SCHEMA_VERSION;pub use server::RpcEngine;pub use store::SessionInfo;pub use store::SessionStore;pub use support::harness_support;pub use support::harness_support_registry;pub use support::HarnessSupportDescriptor;pub use support::ImplementationKind;pub use support::NativeSupport;pub use support::RuntimeSupport;pub use support::SupportRegistryReport;pub use support::SUPPORT_REGISTRY_SCHEMA;pub use tools::shell_sandbox_unenforceable;pub use tools::SandboxPolicy;pub use tools::SchemaTier;pub use tools::Tool;pub use tools::ToolContext;pub use tools::ToolRegistry;pub use tools::WriteObserver;
Modules§
- acp_
frontend - First-class ACP client implementation of the canonical SDK runtime.
- acp_
server - Inbound Agent Client Protocol adapter for the SDK-owned Supercode runtime.
- audit
- Corpus coverage audit.
- background
- Compatibility path for native background-job state.
- catalog
- Compatibility path for session catalogs and durable locators.
- checkpoint
- §2 module 20
checkpoint(COMPOSABLE-HARNESS-DESIGN.md line 470): file checkpointing / shadow-git; D4-adjacent revert; D3 turn-diff tracking. Line 1504: “restores FILES, not context — pairs with, never replaces, the reduction sidecar.” - claude_
compat - Claude Code project compatibility helpers.
- claude_
peer - Live Claude Code peer sessions: registry discovery and message delivery.
- claude_
runtime_ scheduler - Deterministic execution cursor for imported Claude cron and wakeup state.
- claude_
runtime_ state - Lossless, non-executing reconstruction of Claude Code runtime state.
- configfile
- §3 “The Single Config File” (
docs/composable-harness/COMPOSABLE-HARNESS-DESIGN.md) — P1 of the composable-harness migration (design §5.2, phase P1). - fidelity
- Compatibility path for canonical interchange fidelity measurements.
- formatters
- §2 module 29
formatters(COMPOSABLE-HARNESS-DESIGN.md line 479): “D10/oc§10 format-on-write” — reuses the EXACTcrate::tools::WriteObserverseam P5-9 built forcheckpoint(D-5: “write-path interception seam shared with checkpoint”), rather than a second interception point. - frontend
- Protocol-neutral frontend contract for one SDK-owned Supercode runtime.
- git_
metadata - P4e (COMPOSABLE-HARNESS-DESIGN.md §1.6/§3.1
core.session.git_metadata, catalog:331 “Git integration (metadata, diff, PR)”): a persisted, TYPED record of the git branch/sha/dirty state a session was RUNNING under, captured ONCE at session start (closes the loop catalog:331 flags — supercode already preserves a foreign session’s own git-shaped fields byte-for-byte on IMPORT viaSession::raw’s verbatim capture; this is the WRITE half: supercode’s OWN sessions get the same provenance). Deliberately flat/typed (not a formatted string), the exact same rationale ascrate::usage_log::UsageRecord/crate::model_change::ModelChangeRecord(§1.13): a translatable, lossless session-data channel, not a lossy notice — so it survives a save/load round trip byte-for-byte, and a future reader (a translator,doctor/inspect stats) can consume it without re-parsing prose. - harness_
service - Versioned, language-neutral service over persisted harness sessions.
- human_
export - P4e (COMPOSABLE-HARNESS-DESIGN.md §1.6/§3.1
core.session.export_format, catalog:283 “transcript export for humans”): a READ-ONLY rendering of acrate::Session’s conversation into text a human reads directly (terminal/file/clipboard) or opens in a browser — CC’s/export+/copy, CX’s Ctrl+O copy-last. This is core, not gated by thesession.sharemodule (§1.6: “export-to-human is universal while share links … are the OC+PI-only partsession.shareactually narrows to”). - live_
runtime - Trusted local receipts for attachable Supercode runtimes.
- lsp
- §2 module 28
lsp(COMPOSABLE-HARNESS-DESIGN.md line 478): “D1 LSP diagnostics in edit path + query tool” — this module ships the WEAKEST FORM that satisfies D1: server LIFECYCLE for a HANDFUL of user-configured language servers, and diagnostics surfaced in the edit/write TOOL RESULT via the shared D-5 write-path seam (crate::tools::WriteObserver, P5-9/P5-11). - mcp
- P5-2 (COMPOSABLE-HARNESS-DESIGN.md §2 module 15
mcp.client, D7 rows 1-8): full Model Context Protocol client support — stdio (P5-1 baseline, GROWN not rewritten), remote HTTP/SSE transports, resources + templates, prompts-as-commands, server instructions, and elicitation — plus thehandle_request/serve_stdioharness-as-MCP-server direction (module 16). - mcp_
oauth - P5-2 (COMPOSABLE-HARNESS-DESIGN.md §2 module 15 D7 row 2 “OAuth”; §2.1
dep “
model.oauth→ trust-grade token storage” — the same security class applies here): OAuth PROTOCOL support for authenticated remote MCP servers. - model_
catalog - §2 module 26
model.catalog(docs/composable-harness/ COMPOSABLE-HARNESS-DESIGN.md§3.1[capabilities.model_catalog]) — P4 of the composable-harness migration (design §5.2 phase P4: “aliases + fallback chains (userconfig.rs:386-411) promoted into core” + thesmall_modelknob). - model_
change - P4c (COMPOSABLE-HARNESS-DESIGN.md §5.2 “P4” core NEW-significant item,
§1.10/§3.1
core.model_switch.allow_switch, D9 row): a persisted, TYPED record of a mid-session model switch — pi’smodel_changeprecedent (design §1.10: “persisted change records … pi’smodel_changeis the cleanest precedent”). Deliberately flat/typed (not a formatted string), mirroringcrate::usage_log::UsageRecord’s exact rationale: a translatable, lossless session-data channel (§1.13), not a lossy notice — so it survives a save/load round trip byte-for-byte in the fields that matter, and a future reader (a translator emitting this same session under another harness’s format, adoctor/inspect statscommand) can consume it without re-parsing prose. - modules
- §2 “The Bolt-on Capability Taxonomy” (
docs/composable-harness/ COMPOSABLE-HARNESS-DESIGN.md) — P3 of the composable-harness migration (design §5.2, phase P3: “AModuleIdenum (the 35 names) + resolved activation set onConfig”). - permissions
- P5-1 (COMPOSABLE-HARNESS-DESIGN.md §2 modules 10-11, §2.1 D-3, §2.2 C5, §5.3 risk 1): the permissions engine — command canonicalization + rule algebra + approval policy/cache + oc/cx import translators.
- plugins
- P5-12 (COMPOSABLE-HARNESS-DESIGN.md §2 module 18
plugins, D7 “in-process extension API, packaging/marketplaces, custom tools from files, provider injection, extension UI, plugin/package installation”; §2.1 D-10: “config-borne code execution without a trust gate is an injection hole”). - presets
- §4 “Presets” (
docs/composable-harness/COMPOSABLE-HARNESS-DESIGN.md) — P2 of the composable-harness migration (design §5.2, phase P2). - pricing_
ref - Reference pricing constants used only to translate measured byte/token savings into a dollar figure in test logs and docs (D15). These are stated constants for one Opus-class API list price (July 2026) — not a live lookup, and not used anywhere on the request path.
- reduce
- Compatibility facade for optional reversible reduction.
- runtime
- Primitive live-runtime contracts and the Codex app-server reference adapter.
- runtime_
lease - Transport-neutral observer and controller leases for live SDK runtimes.
- runtime_
registry - Authenticated inventory and attachment for live and persisted sessions.
- sandbox
- P5-10 (COMPOSABLE-HARNESS-DESIGN.md §2 module 12
permissions.sandbox, ~row 462): the OS-level enforcement BACKSTOPpermissions.rules’ rule-layer floor and the file-toolcrate::tools::SandboxPolicyboth defer to for full coverage (crate::permissionsmodule doc: “complete OS-level write confinement of arbitrary bash… iscapabilities. permissions.sandbox’s job (P5 module 10, a later unit), not this one’s” — this IS that unit). - schema
- Typed schemas for the on-disk session formats.
- sdk
- Versioned public SDK contract shared by every Supercode surface.
- server
- §2 module 31
server(COMPOSABLE-HARNESS-DESIGN.md, D7 “full programmatic RPC/HTTP server”, D8 “remote attach”, D10 “daemon”; §1.9 Obligation 9’s out-of-process half — the in-process SDK already meets the core commitment viacrate::EventSink). - session
- Compatibility path for canonical sessions and native codecs.
- session_
title - P4b (COMPOSABLE-HARNESS-DESIGN.md §5.2 “P4”, §1.6/§3.1
core.session.auto_title, catalog:150, D-9): auto-title / session summary — a small-model side-call that titles a session, mirroringcrate::reduce::summarize’s plumbing exactly: an injectable trait (real implementations call out to a model; this crate’s own tests only ever inject deterministic fakes — no real network/model call anywhere in this crate, same posture ascrate::reduce::summarize::SpanSummarizer), a fixed versioned prompt, and a “never blocks, never fails the caller” contract. - session_
tree - Compatibility path for canonical session trees.
- sidecar
- Compatibility path for native interchange sidecars.
- store
- A directory-backed store for supercode’s own sessions — naming, titles,
listing, archiving, and deletion. The analog of
claude --name/ the Codexresume/archive/deletesession lifecycle. - subagents
- P5-3 (COMPOSABLE-HARNESS-DESIGN.md §2 module 9
subagents: “D1 spawn tool; D3 sub-agents/named-defs/background+resume/teams; D5 subagent transcripts”; §2.1 D-1 “subagents → core.session(lineage), core.tools; background-mode → permissions.approvals”; §2.2 C6): the data shapes and pure-function resource-bound checks the spawn/join/background machinery incrate::agent::Agentbuilds on. Kept separate fromagent.rsso the depth/concurrency-cap arithmetic and the lineage record shape are unit-testable without a fullAgent/mock-Providerharness — the same “pure config → set, testable without the loop” precedent P3’scrate::modulesmodule documents for itself. - support
- Canonical implementation inventory for external coding harnesses.
- tokens
- Compatibility path for native runtime token budgeting.
- tools
- Tools the agent can call.
- tui
- P5-4 (COMPOSABLE-HARNESS-DESIGN.md §2 module 30
tui; §1.9 recorded deviation; §2.1tools.question/permissions.approvals(ask-UI) →tui|server): the full-screen interactive TUI, AND — because §2.1 names it as the interactive surface three EARLIER phases explicitly deferred here — the home for the three handlers that close those deferred chains: - usage_
log - P4b (COMPOSABLE-HARNESS-DESIGN.md §5.2 “P4”, §1.6/§3.1, catalog §4a
“Turn/step usage records surfaced per turn”): persisted per-turn
token/usage records.
crate::AgentEvent::Usagealready streams this data live (UX-23); this module makes it DURABLE session data — a typed, serde-round-trippable record, not a lossy display-only channel (§1.13’s lossless/sidecar discipline: this is typed session data, exactly likecrate::reduce::ReductionLog, not a text notice). - watch
- Compatibility path for passive session following.
Structs§
- Agent
- A stateful agent: configuration, a model transport, a tool set, and the
running conversation. Drive it with
Agent::send. - Chat
Message - A single message in a conversation.
- Chat
Request - A single model-completion request.
- Config
- Everything that shapes an
crate::Agent: the model and endpoint, the credentials, sampling parameters, the system prompt, and per-tool overrides. - Config
Builder - Fluent builder for
Config. - Config
File - A config file: a set of named profiles (the analog of Codex
-p/--profile). This is the SDK/embedder config surface; the supercode CLI uses a separate TOML config (userconfig::FileConfigin theclicrate) and does not expose this file or a--profileflag. - Config
Profile - The serializable subset of a
Configthat can live in a config file. (Callbacks/handlers are code-only and are not represented here.) - Context
Injection Block - P4e (§1.4/§3.1
core.context_injections): one named ambient context block – seeConfig::context_injection_blocks. - Discovery
Page - One stable newest-first discovery page.
- Discovery
Query - Filters and roots used for one catalog scan.
- Fidelity
Metric - Result of measuring one actual translation cell.
- Fidelity
Residue - Measured residue of one actual export/reload cell.
- Function
Call - The function payload of a
ToolCall. - Generated
Frontend Client - Generated typed Rust client over any facade transport.
- Harness
Catalog - Read-only entry point for discovering, loading, and following persisted harness sessions.
- Harness
Homes - Configurable session roots for the built-in harnesses.
- Harness
Id - Extensible identifier for a coding harness.
- Open
AiProvider - An OpenAI-compatible HTTP provider. The composition layer supplies its endpoint, credentials, and headers from runtime configuration.
- Prompt
Tokens Details - The cache portion of
Usage::prompt_tokens_details. - Session
- A normalized, replayable conversation loaded from a tool’s session log.
- Session
Descriptor - Lightweight metadata returned by catalog discovery.
- Session
Follower - Poll-based follower for one persisted Claude Code, Codex, Pi, OpenCode, or Grok session.
- Session
Locator - Stable identity for a persisted harness session.
- Session
Meta - Metadata recovered from a session log.
- Tool
Call - A request from the model to invoke a tool.
- Tool
Override - Per-tool customization: enable/disable a tool and/or override the description the model sees for it.
- Tool
Override Profile - A single tool’s file-settable overrides — the
ConfigProfilemirror ofToolOverride(COMPOSABLE-HARNESS-DESIGN.md §3.1[core.tools.<name>], §3.2 mapping rowcore.tools.enabled+[core.tools.<n>].*). - Tool
Schema - A tool advertised to a model.
- Usage
- Token accounting returned with a completion.
Enums§
- Agent
Event - Streaming events emitted by a native runtime agent as a turn unfolds.
- Approval
Policy - When the agent must seek approval before running a tool — the analog of
Codex’s
-a untrusted|on-request|neverand Claude’s permission modes. - Cache
Plan - Prompt-caching plan applied while building a provider request.
- Error
- Errors that can arise while configuring or running an
crate::Agent. - Fidelity
- How faithfully a reconstruction reproduces its source.
- Frontend
Facade Method - One method in the versioned language-neutral frontend facade.
- Role
- Who authored a
ChatMessage. - Session
Format - An on-disk session format supercode can both read and write.
- Session
Snapshot Reason - Why a watcher emitted a complete session snapshot.
- Session
Source - Which tool produced a session log.
- Session
Watch Event - A normalized event emitted while following a local session.
- Steering
Mode - How queued steering/follow-up messages are drained (S1.7, pi3
steeringMode/followUpMode). - Storage
Locator - Durable storage address for a persisted session.
- Tool
Advertising - How tools are advertised to the model (B6, D16).
- Tool
Outcome - The structural outcome known for a tool-result message.
Constants§
- DEFAULT_
SYSTEM_ PROMPT - A default, deliberately small system prompt. Override it freely.
- TOOL_
ERROR_ METADATA_ KEY - Canonical metadata key marking a tool result as a structured error.
- TOOL_
OUTCOME_ UNKNOWN_ METADATA_ KEY - Canonical metadata key marking a tool result whose outcome is unknown.
- UNKNOWN_
MODEL_ CONTEXT_ FLOOR - Conservative fallback context limit for an unrecognized model.
Traits§
- Frontend
Facade Transport - Transport seam consumed by the generated Rust facade client.
- Provider
- Legacy provider abstraction preserved by the composition facade.
Functions§
- core_
messages - Canonical messages participating in cross-format fidelity scoring.
- format_
reply - Format an agent’s final reply for output.
jsonwraps it as{"result": "..."}; otherwise the reply is returned as-is. The stream-json form is the liveAgentEventstream via anEventSink. - is_
tool_ error - Whether a message carries the canonical structured-error marker.
- mark_
tool_ error - Stamp a tool-result message as a structured error.
- mark_
tool_ outcome_ unknown - Stamp a tool-result message as having no structurally known outcome.
- measure_
fidelity - Measure an export/reload cell without applying a regression floor.
- messages_
equal - Compare semantic message fields shared by the supported harnesses.
- messages_
equal_ multimodal - Compare semantics plus multimodal parts and tool names.
- model_
context_ limit - Look up a model’s context-window size by its full provider slug.
- replay_
eligible - The replayable subsequence of a canonical transcript.
- tool_
outcome - Return the canonical structural outcome for a tool-result message.
Type Aliases§
- Event
Sink - A sink for
AgentEvents. - Result
- Result alias used throughout the crate.
- Stop
Gate Hook - A stop-gate hook: receives the would-be-final assistant message; returns
Some(reason)to veto termination and continue the loop (the reason is injected as a new user message), orNoneto allow the stop. SeeConfig::stop_gate.