Skip to main content

supercode_harness/
lib.rs

1//! # Volter Harness
2//!
3//! A lightweight, fully-customizable AI coding-agent SDK in Rust.
4//!
5//! `supercode` is a native agent loop — it talks directly to any model through
6//! [OpenRouter](https://openrouter.ai) (or any other OpenAI-compatible endpoint),
7//! drives a configurable set of tools, and is designed to be a superset of what
8//! tools like Claude Code and Codex can do: every prompt, every tool description,
9//! and every tool's on/off state is yours to control.
10//!
11//! ## Quick start
12//!
13//! ```no_run
14//! use supercode_harness::{Agent, Config};
15//!
16//! # async fn run() -> supercode_harness::Result<()> {
17//! // Reads OPENROUTER_API_KEY from the environment by default.
18//! let config = Config::builder()
19//!     .model("anthropic/claude-opus-4-8")
20//!     .system_prompt("You are a terse, expert pair programmer.")
21//!     .build();
22//!
23//! let mut agent = Agent::new(config)?;
24//! let reply = agent.send("List the files in the current directory.").await?;
25//! println!("{reply}");
26//! # Ok(())
27//! # }
28//! ```
29//!
30//! ## Design
31//!
32//! - [`Config`] — the single knob box: model, endpoint, credentials, sampling,
33//!   the system prompt, and per-tool overrides (enable/disable + custom
34//!   descriptions).
35//! - [`Provider`] — the model transport. [`OpenAiProvider`] speaks the
36//!   OpenAI chat-completions wire format and defaults to OpenRouter, so it
37//!   reaches Claude, GPT, Gemini, Llama, and anything else OpenRouter exposes.
38//! - [`Tool`] / [`ToolRegistry`] — the capability surface. Built-ins cover
39//!   file read/write/edit, directory listing, glob, content search, and shell
40//!   execution. Register your own to extend it.
41//! - [`Agent`] — the loop that ties it together: it streams a turn, runs any
42//!   tool calls the model requests, feeds results back, and repeats until the
43//!   model produces a final answer.
44
45#![warn(missing_docs)]
46
47#[cfg(feature = "adapter-acp")]
48/// The supercode ontology (`docs/ONTOLOGY.md`): the one model under sessions and the
49/// orchestration.
50pub use supercode_interchange::ontology;
51/// The orchestration piece of the ontology: a harness's operational home as one typed value.
52pub use supercode_interchange::orchestration;
53
54#[cfg(feature = "adapter-acp")]
55pub mod acp_frontend;
56#[cfg(feature = "adapter-acp")]
57pub mod acp_server;
58mod agent;
59pub mod agent_package;
60pub mod approvals;
61pub mod audit;
62pub mod channels;
63pub mod checkpoint;
64pub mod claude_compat;
65pub mod claude_peer;
66pub mod claude_relay;
67pub mod claude_runtime_state;
68pub mod codex_peer;
69mod config;
70pub mod config_schema;
71pub mod configfile;
72pub mod context_injection;
73mod error;
74pub mod formatters;
75#[cfg(feature = "adapter-api")]
76pub mod frontend;
77#[cfg(not(feature = "adapter-api"))]
78#[allow(dead_code)]
79mod frontend;
80#[allow(missing_docs)]
81mod frontend_contract_generated;
82pub mod git_metadata;
83pub mod goals;
84pub mod harness_auth;
85pub mod harness_command;
86#[cfg(feature = "adapter-api")]
87pub mod harness_service;
88#[cfg(not(feature = "adapter-api"))]
89#[allow(dead_code)]
90mod harness_service;
91pub mod hermes_import;
92pub mod human_export;
93pub mod interop_settings;
94pub mod jobs;
95pub mod jobs_control;
96pub mod jobs_notepad;
97pub mod launch_agent;
98pub mod live_runtime;
99pub mod lsp;
100#[cfg(feature = "adapter-api")]
101pub mod mail_agent;
102#[cfg(feature = "adapter-api")]
103pub mod mail_file;
104#[cfg(feature = "adapter-api")]
105pub mod mail_mcp;
106pub mod mail_question;
107#[cfg(feature = "adapter-api")]
108pub mod mail_route;
109#[cfg(feature = "adapter-api")]
110pub mod mail_send;
111pub mod mail_transcript;
112#[cfg(feature = "adapter-api")]
113pub mod mail_watch;
114pub mod mailbox;
115pub mod mcp;
116pub mod mcp_oauth;
117pub mod memory;
118pub mod model_catalog;
119pub mod model_change;
120pub mod modules;
121mod native_materialize;
122pub mod orchestration_doors;
123pub mod orchestrator;
124pub mod orchestrator_door;
125pub mod output_style;
126pub mod parity;
127pub mod path_rules;
128pub mod permissions;
129pub mod plugins;
130pub mod presets;
131pub mod pricing;
132pub mod pricing_ref;
133pub mod profiles;
134pub mod profiles_control;
135mod provider;
136pub mod reduce;
137#[cfg(feature = "adapter-api")]
138pub mod relay_endpoint;
139mod residue_store;
140pub mod routes;
141pub mod runs;
142pub mod runtime;
143pub mod runtime_lease;
144#[cfg(feature = "adapter-api")]
145pub mod runtime_mail;
146#[cfg(feature = "adapter-api")]
147pub mod runtime_registry;
148mod safe_path;
149pub mod sandbox;
150pub mod schema;
151pub mod sdk;
152#[cfg(feature = "adapter-api")]
153pub mod server;
154#[cfg(not(feature = "adapter-api"))]
155#[allow(dead_code, unused_imports)]
156mod server;
157pub mod session_activity;
158pub mod session_index;
159pub mod session_journal;
160pub mod session_title;
161pub mod session_tree;
162pub mod sessions_control;
163pub mod skills;
164pub mod skills_control;
165pub mod slow_log;
166pub mod startup_prompts;
167pub mod store;
168pub mod subagents;
169pub mod support;
170pub mod teams;
171pub mod token_spend;
172pub mod tools;
173pub mod triggers;
174pub mod trust;
175pub mod tui;
176pub mod turn_record;
177pub mod usage_log;
178pub mod workflow_doors;
179
180#[cfg(feature = "adapter-acp")]
181pub use acp_frontend::{AcpFrontendCheckpoint, AcpFrontendConnectOptions, AcpFrontendRuntime};
182pub use agent::{Agent, ContextUsage};
183pub use approvals::{
184    approval_harnesses, lists_approvals, plan_reply, ApprovalChoice, ApprovalDecision,
185    ApprovalDoor, ApprovalKind, ApprovalOption, ApprovalRegistry, ApprovalResolution,
186    ApprovalResolveError, ApprovalRow, ApprovalStatus, ApprovalsQuery, ApprovalsResolveParams,
187};
188pub use channels::{
189    channel_status, list_channels, ChannelError, ChannelRow, ChannelStatus, CHANNELS_SCHEMA,
190    CHANNEL_HARNESSES,
191};
192pub use claude_peer::{
193    read_claude_peer_settings, read_registry as read_claude_peer_registry, resolve_live_session,
194    update_claude_peer_settings, user_settings_path as claude_user_settings_path,
195    write_claude_peer_settings, ClaudeCrossSessionInbound, ClaudePeerRefusal,
196    ClaudePeerRefusalError, ClaudePeerSession, ClaudePeerSettings, ClaudePeerSettingsError,
197    ClaudePeerStatus,
198};
199pub use claude_runtime_state::{
200    ClaudeBackgroundChild, ClaudeBackgroundState, ClaudeCronJob, ClaudeQueueState,
201    ClaudeRuntimeManifest, ClaudeRuntimePosture, ClaudeRuntimeResidue, ClaudeWakeup,
202    CLAUDE_RUNTIME_MANIFEST_VERSION,
203};
204pub use config::{
205    project_root_for, ApprovalPolicy, CachePlan, Config, ConfigBuilder, ConfigFile, ConfigProfile,
206    ContextInjectionBlock, HookDecision, LifecycleEvent, LifecycleHook, PreToolOutcome,
207    SteeringMode, StopGateHook, ToolAdvertising, ToolOverride, ToolOverrideProfile,
208    DEFAULT_SYSTEM_PROMPT,
209};
210pub use configfile::HarnessConfig;
211pub use interop_settings::{
212    configure_harness_interop_settings, inspect_harness_interop_settings, HarnessAdvisorySeverity,
213    HarnessInteropAdvisory, HarnessInteropControl, HarnessInteropSettingsError,
214    HarnessInteropSettingsReport, HarnessSettingChange, HarnessSettingChoice,
215    HarnessSettingRecommendation, HarnessSettingScope, CLAUDE_CROSS_SESSION_INBOUND_KEY,
216    HARNESS_INTEROP_SETTINGS_SCHEMA,
217};
218pub use jobs::{
219    get_job, list_jobs, supports_jobs, JobDeliver, JobPayload, JobSchedule, JobScope, JobSource,
220    JobsListing, JobsQuery, ScheduledJob, CLAUDE_SESSION_SCAN_LIMIT, JOB_HARNESSES,
221};
222pub use jobs_control::{
223    harness_program, mutate, supports_job_control, JobControlError, JobDeliverSpec, JobMutation,
224    JobMutationOutcome, JobPayloadSpec, JobScheduleSpec, JobVerb, CONTROLLED_JOB_HARNESSES,
225};
226pub use jobs_notepad::{JobNotepad, JobNotepadEntry, JobNotepadRequest};
227pub use live_runtime::{
228    discover_live_runtime, find_live_runtime, forget_live_runtime, list_live_runtimes,
229    register_live_runtime, register_live_runtime_with_metadata, resolve_live_runtime,
230    LiveRuntimeEndpoint, LiveRuntimeMetadata, LiveRuntimeReceiptError, LiveRuntimeRecord,
231    LiveRuntimeRegistration, LiveRuntimeSource, LiveRuntimeSupervisor, ResolvedLiveRuntime,
232};
233pub use memory::{
234    search_memory, show_memory, supports_memory, MemoryDocument, MemoryError, MemoryMatch,
235    MemoryQuery, MemoryScope, MemorySearchQuery, MEMORY_HARNESSES, MEMORY_SCHEMA,
236};
237pub use modules::{ModuleActivation, ModuleId};
238pub use orchestrator::{
239    clear_lease, daemon_entry, install_service, live_lease, lock_path, read_lease, resolve_program,
240    service_name, service_status, service_unit, uninstall_service, write_lease, write_unit, Lease,
241    OrchestratorError, ServiceState, ServiceUnit, DAEMON_ENTRY, LOCK_FILE, SERVICE_DIR,
242    SERVICE_NAME,
243};
244pub use orchestrator_door::{
245    daemon_is_live, socket_path, Door, DoorAnswer, DoorError, NODE_BIN_ENV, SOCKET_FILE,
246};
247pub use profiles::{
248    get_profile, list_profiles, ProfileError, ProfileKind, ProfileRow, HERMES_DEFAULT_PROFILE,
249    PROFILES_SCHEMA, PROFILE_HARNESSES,
250};
251pub use profiles_control::{
252    supports_profile_control, ProfileControlError, ProfileMutation, ProfileMutationOutcome,
253    ProfileVerb, CONTROLLED_PROFILE_HARNESSES,
254};
255pub use routes::{list_routes, RouteError, RouteMatch, RouteRow, ROUTES_SCHEMA, ROUTE_HARNESSES};
256pub use runs::{
257    get_run, list_runs, supports_runs, HarnessRun, RunDelivery, RunSource, RunsListing, RunsQuery,
258    RUN_HARNESSES,
259};
260pub use sessions_control::{
261    controlled_verbs, supports_session_control, SessionControlError, SessionDoor, SessionMutation,
262    SessionMutationOutcome, SessionVerb, CONTROLLED_SESSION_HARNESSES,
263};
264pub use supercode_interchange::catalog::{
265    orchestrator_profile_dirs, DiscoveryPage, DiscoveryQuery, HarnessCatalog, HarnessHomes,
266    HarnessId, SessionDescriptor, SessionLocator, StorageLocator,
267};
268pub use teams::{
269    connector_service_binary as teams_connector_service_binary,
270    connector_service_name as teams_connector_service_name,
271    connector_service_status as teams_connector_service_status,
272    connector_service_unit as teams_connector_service_unit,
273    install_connector_service as install_teams_connector_service,
274    install_service as install_teams_service, service_status as teams_service_status,
275    service_unit as teams_service_unit, teams_entry, teams_home,
276    uninstall_connector_service as uninstall_teams_connector_service,
277    uninstall_service as uninstall_teams_service, write_unit as write_teams_unit, TeamsError,
278    SERVICE_DIR as TEAMS_SERVICE_DIR, SERVICE_NAME as TEAMS_SERVICE_NAME, TEAMS_ENTRY,
279    TEAMS_PACKAGE,
280};
281pub use triggers::{
282    list_triggers, TriggerError, TriggerKind, TriggerRow, TRIGGERS_SCHEMA, TRIGGER_HARNESSES,
283};
284
285/// Format an agent's final reply for output. `json` wraps it as
286/// `{"result": "..."}`; otherwise the reply is returned as-is. The
287/// stream-json form is the live [`AgentEvent`] stream via an [`EventSink`].
288pub fn format_reply(reply: &str, json: bool) -> String {
289    if json {
290        serde_json::json!({ "result": reply }).to_string()
291    } else {
292        reply.to_string()
293    }
294}
295pub use error::{Error, Result};
296#[cfg(feature = "adapter-api")]
297pub use frontend::HttpFrontendRuntime;
298pub use frontend::{
299    FrontendActions, FrontendApprovalDecision, FrontendAttachSnapshot, FrontendAttachment,
300    FrontendCommandDescriptor, FrontendConnectionState, FrontendDisplayCapabilities,
301    FrontendElicitationAction, FrontendEvent, FrontendOperationDescriptor,
302    FrontendOperationInvocation, FrontendOperationKind, FrontendOperationResult, FrontendRequest,
303    FrontendRequestKind, FrontendResponse, FrontendRuntime, FrontendRuntimeDescriptor,
304    FrontendRuntimeError, FrontendRuntimeMetadata, FrontendTurnState, FRONTEND_REPLAY_CAPACITY,
305    FRONTEND_RUNTIME_SCHEMA_VERSION,
306};
307pub use frontend_contract_generated::{
308    FrontendFacadeMethod, FrontendFacadeTransport, GeneratedFrontendClient,
309};
310pub use harness_auth::{
311    harness_authentication_methods, harness_authentication_plan, inspect_harness_authentication,
312    HarnessAuthenticationEnvironment, HarnessAuthenticationError, HarnessAuthenticationInteraction,
313    HarnessAuthenticationLaunch, HarnessAuthenticationMethod, HarnessAuthenticationMethodId,
314    HarnessAuthenticationPlan, HarnessAuthenticationReport, HarnessAuthenticationState,
315    HarnessBrowserBehavior, HARNESS_AUTHENTICATION_SCHEMA,
316};
317pub use harness_service::{
318    DetachedAnswer, DetachedCall, HarnessSessionService, OpenedRuntime, ReturnedRuntime,
319    RuntimeOpen, DETACHED_CALL_DEADLINE, DETACHED_METHODS, HARNESS_SERVICE_VERSION,
320    RUNTIME_CONTROL_DEADLINE, RUNTIME_EVENT_METHOD, RUNTIME_OPEN_DEADLINE, RUNTIME_OPEN_METHODS,
321    SESSION_ACTIVITY_EVENT_METHOD, SESSION_DISCOVER_DEADLINE, SESSION_EVENT_METHOD,
322    SESSION_INDEX_EVENT_METHOD,
323};
324pub use provider::{
325    model_context_limit, ChatRequest, OpenAiProvider, PromptTokensDetails, Provider, RetryLog,
326    RetryNotice, ToolSchema, Usage, SERVED_MODEL_KEY, UNKNOWN_MODEL_CONTEXT_FLOOR,
327};
328#[cfg(feature = "adapter-api")]
329pub use runtime::SupercodeHttpRuntimeBackend;
330pub use runtime::{
331    AcpRuntimeBackend, BearerToken, ClaudeCodeRuntimeBackend, CodexRuntimeBackend, HarnessEvent,
332    McpServerLaunch, OpenCodeRuntimeBackend, PiRuntimeBackend, ResolvedRuntimeConnection,
333    RuntimeAttachRequest, RuntimeBackend, RuntimeCapabilities, RuntimeConnectLaunch,
334    RuntimeConnection, RuntimeEndpoint, RuntimeHandle, RuntimeInput, RuntimeLaunch,
335    RuntimeStartRequest,
336};
337pub use runtime_lease::{
338    CoordinatedRuntime, CoordinatedRuntimeClient, RuntimeAuthorization, RuntimeClientId,
339    RuntimeControllerLease, RuntimeLeaseCoordinator, RuntimeLeaseError, RuntimeLeaseSnapshot,
340    RuntimeObserverLease, RuntimePermission, DEFAULT_RUNTIME_LEASE_TTL_MS,
341};
342#[cfg(feature = "adapter-api")]
343pub use runtime_registry::{
344    LocalRuntimeRegistry, RuntimeRegistryEntry, RuntimeRegistryEvent, RuntimeRegistryOwner,
345    RuntimeRegistryQuery, RuntimeRegistryState, RuntimeRegistryWatch,
346};
347pub use sandbox::{landlock_available, netns_available, SandboxEnvPolicy, SandboxEscalation};
348pub use sdk::{
349    create_agent, discover_session_page, discover_sessions, load_session, load_session_path,
350    resume_agent, show_model_input, submit_agent, submit_agent_with_images, RuntimeSubmitError,
351    SdkAgent, SdkCapabilities, SdkError, SdkErrorCode, SdkEvent, SdkOperation, SdkPromptSource,
352    SdkRequest, SdkRuntime, SdkRuntimeEvent, SdkService, SDK_SCHEMA_VERSION,
353};
354pub use server::RpcEngine;
355pub use session_activity::{
356    SessionActivity, SessionActivityEvidence, SessionPresence, SessionTurnState,
357};
358pub use session_index::{SessionIndexChange, SessionIndexDelta, SessionIndexKey};
359pub use skills::{
360    declared_skill_name, list_skills, skill_roots, writable_skill_roots, SkillHomes, SkillRow,
361    SkillScope, SkillsQuery, SKILL_HARNESSES,
362};
363pub use skills_control::{
364    mutate_skill, supports_skill_control, SkillControlError, SkillMutation, SkillMutationOutcome,
365    SkillVerb, CONTROLLED_SKILL_HARNESSES,
366};
367pub use store::{SessionInfo, SessionStore};
368pub use supercode_interchange::session::{
369    CrossSurface, OrchestrationNouns, Recurrence, Session, SessionFormat, SessionMeta,
370    SessionSource, SurfaceKey, Trigger, WorkspaceKind, WorkspaceRef,
371};
372pub use supercode_interchange::watch::{SessionFollower, SessionSnapshotReason, SessionWatchEvent};
373pub use supercode_interchange::{
374    core_messages, measure_fidelity, messages_equal, messages_equal_multimodal, replay_eligible,
375    Fidelity, FidelityMetric, FidelityResidue,
376};
377pub use supercode_interchange::{
378    is_tool_error, mark_tool_error, mark_tool_outcome_unknown, tool_outcome, ChatMessage,
379    FunctionCall, Role, ToolCall, ToolOutcome, TOOL_ERROR_METADATA_KEY,
380    TOOL_OUTCOME_UNKNOWN_METADATA_KEY,
381};
382pub use supercode_runtime::{AgentEvent, EventSink};
383pub use support::{
384    harness_support, harness_support_registry, HarnessSupportDescriptor, ImplementationKind,
385    NativeSupport, RuntimeSupport, SupportRegistryReport, SUPPORT_REGISTRY_SCHEMA,
386};
387pub use tools::{
388    shell_sandbox_unenforceable, SandboxPolicy, SchemaTier, Tool, ToolContext, ToolRegistry,
389    WriteObserver,
390};
391
392/// The checkout this binary was built from, when it runs as a build of it. An installed binary (one inside a
393/// `node_modules`, where npm and a local install place it) never reads it: on the machine that built it the checkout
394/// still exists, and its source tree would resolve its packages against whatever `node_modules` sits above it.
395pub fn build_checkout() -> Option<std::path::PathBuf> {
396    let exe = std::env::current_exe().ok()?;
397    if exe
398        .ancestors()
399        .any(|dir| dir.file_name().is_some_and(|name| name == "node_modules"))
400    {
401        return None;
402    }
403    std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
404        .ancestors()
405        .nth(2)
406        .map(std::path::Path::to_path_buf)
407}