hya-sdk Reference & Client Integration
You can drive a running Hya v2 backend from any language over /v2 HTTP/JSON+SSE or gRPC, or use Hya’s official typed Rust client crate hya-sdk (crates/hya-sdk).
hya-sdk wraps /v2 HTTP + Server-Sent Events (SSE) using the generated hya_api::v2 ProtoJSON types and provides:
Sdk— High-level directory-scoped client with daemon-safe timeouts, turn helpers, session lifecycle & catalog pagination methods,BundleApicallers (ordinary and unbounded), interaction responders, and live SSE streaming.Client— Low-level unscoped HTTP client accepting a customreqwest::Client(for custom headers such asx-hya-bridge-tokenover a remote relay bridge).SessionMirror— Deterministic in-memory reducer that folds liveStreamFrameupdates—includingExtensionEventframes andSessionInfo.extensionsprojections—into a ready-to-render transcript view.
1. Quickstart (Rust hya-sdk)
Add hya-sdk and hya-api to your Cargo.toml (for workspace or path consumers):
[dependencies]futures = "0.3"hya-api = { path = "crates/hya-api" }hya-sdk = { path = "crates/hya-sdk" }reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }serde_json = "1"tokio = { version = "1", features = ["macros", "rt-multi-thread"] }Connecting, streaming a turn & calling a Bundle API
Open the SSE stream before submitting a turn with create_turn so you never miss early seq == 0 streaming deltas (Sdk::prompt admits a prompt and blocks until it finishes, which is convenient when you don’t need live streaming):
use futures::StreamExt;use hya_api::v2 as pb;use hya_sdk::{Sdk, SessionMirror};use reqwest::Method;
#[tokio::main]async fn main() -> Result<(), Box<dyn std::error::Error>> { // Loopback daemon client: bypasses env proxies, 5s connect timeout, 30s ordinary call timeout. // Turn waits, SSE streams, and `*_unbounded` bundle API calls have no request timeout. let sdk = Sdk::for_local_daemon("http://127.0.0.1:8080", "/home/me/my-app")?;
// 1. Fetch startup catalog (models, agents, skills, commands, pending interactions) let boot = sdk.bootstrap().await?; println!("Connected! Models available: {}", boot.models.len());
// 2. Create a session in the target working directory let session = sdk .create_session(pb::CreateSessionRequest { agent: "hya-main".into(), model: "hya/offline".into(), workdir: Some("/home/me/my-app".into()), ..Default::default() }) .await?;
// 3. Open the live SSE stream BEFORE admitting a turn let mut stream = sdk.stream_session(&session.id, session.last_seq).await?; let mut mirror = SessionMirror::from_session(&session, Vec::new());
// 4. Admit a prompt turn asynchronously let _turn = sdk .create_turn( &session.id, pb::create_turn_request::Kind::Prompt(pb::PromptTurn { text: "Summarize Cargo.toml".into(), ..Default::default() }), ) .await?;
// 5. Fold StreamFrames until an assistant message finishes without requesting tools while let Some(frame) = stream.next().await { let frame = frame?; let needs_resync = mirror.apply(&frame); if needs_resync { let refreshed = sdk.get_session(&session.id).await?; let messages = sdk.list_messages(&session.id).await?; // Single-page transcript (at most 50 messages). For longer histories, loop over // sdk.list_messages_page(&session.id, &page) until page.has_more == false before seeding. mirror = SessionMirror::from_session(&refreshed, messages.messages); continue; } if let Some(pb::stream_frame::Frame::Event(event)) = &frame.frame { match &event.payload { Some(pb::stream_event::Payload::MessageFinished(fin)) if fin.finish != pb::FinishReason::ToolCalls as i32 && mirror .message(&fin.message) .is_some_and(|m| m.role == pb::Role::Assistant as i32) => { break; } Some(pb::stream_event::Payload::ServerStopping(stop)) => { eprintln!("Server stopping (reason={}); reconnect when ready", stop.reason); break; } _ => {} } } }
// 6. Inspect mirrored messages and bundle extension state / APIs println!("Messages in mirror: {}", mirror.messages().len()); if let Some(wf_state) = mirror.extension("hya/workflow") { println!("Workflow projection: {wf_state}"); } let workflows = sdk .invoke_global_bundle_api("hya/workflow", Method::GET, "/workflows", None, None) .await?; println!("Available workflows: {workflows}");
Ok(())}Handling reconnects and resync
Sdk::stream_session opens a single SSE attempt without hidden retries or successor discovery, keeping client state deterministic:
- When
mirror.apply(&frame)returnstrue(caused by aresyncframe when a slow consumer lagged behind the server’s ring buffer, or bysessionRevertedon/undo//redo), re-fetch the session withsdk.get_session(&id)and page through the transcript withsdk.list_messages_page(&id, &page)(orGET /v2/sessions/{id}/messages?page.cursor=...over raw HTTP), advancingpage.cursor = next.next_cursorwhilenext.has_moreistrueand appending each page’s messages in order. Oncehas_more == false, re-seed withSessionMirror::from_session(&session, all_messages). Seeding withsdk.list_messages(&id)alone fetches only the first page (up to 50 messages) while advancing the mirror tosession.last_seq, leaving later pages missing. By the timeapplyreturns,last_seqhas already advanced to the resync watermark or the revert event sequence. A revert can also hide or restore messages, so refresh the transcript together with the session. - On
serverStopping(reason == "restart"), wait for the replacement daemon advertised in<db>.server.json, construct a newSdk, and reconnect frommirror.last_seq. On"stop"or"signal", treat the backend as stopped. - Ephemeral
seq == 0streaming deltas can be lost across a restart and are never replayed; durable parts and transcript reads are always authoritative. - Root sessions record requested
tempChatandephemeralmarks in their creation batch throughPOST /v2/sessions(ephemeralapplies to untitled roots). An open session event stream keeps a discardable session alive; once the reaper begins deleting it, new session event streams receivesession_not_found(HTTP404or gRPCNOT_FOUND).
2. hya-sdk API Reference
2.1 Sdk (Directory-Scoped Client)
Scoped calls send directory as a query parameter on GET/DELETE or body field on mutations (the server rejects the removed x-hya-directory header). Sdk::create_session sends request.workdir as supplied. Set that field explicitly to choose a working directory, since the SDK does not fill it from sdk.directory().
Constructors & Accessors
| Method | Behavior |
|---|---|
Sdk::new(base_url, directory) -> Self |
Builds a client with a default reqwest::Client and no per-request timeout. Pass "" for directory to query the global scope. |
Sdk::for_local_daemon(base_url, directory) -> Result<Self, SdkError> |
Builds the CLI’s loopback daemon client: disables environment HTTP proxies (.no_proxy()), sets a 5 s connect timeout and 30 s timeout on ordinary calls, while leaving wait_turn, stream_session, and *_unbounded bundle API calls with no request timeout. |
sdk.directory(&self) -> &str |
Returns the configured directory scope (empty string means global scope). |
Bootstrap, Sessions, Transcripts & Catalogs
| Method | Signature | HTTP Route |
|---|---|---|
bootstrap |
async fn(&self) -> Result<pb::Bootstrap, SdkError> |
GET /v2/bootstrap[?directory=...] |
create_session |
async fn(&self, request: pb::CreateSessionRequest) -> Result<pb::SessionInfo, SdkError> |
POST /v2/sessions |
get_session |
async fn(&self, session: &str) -> Result<pb::SessionInfo, SdkError> |
GET /v2/sessions/{id} |
list_sessions |
async fn(&self, page: Option<pb::PageRequest>) -> Result<pb::ListSessionsResponse, SdkError> |
GET /v2/sessions |
list_project_sessions |
async fn(&self, project: &str, page: Option<pb::PageRequest>) -> Result<pb::ListSessionsResponse, SdkError> |
GET /v2/sessions?projectId=... |
update_session |
async fn(&self, request: pb::UpdateSessionRequest) -> Result<pb::SessionInfo, SdkError> |
PATCH /v2/sessions/{id} |
fork_session |
async fn(&self, session: &str) -> Result<pb::SessionInfo, SdkError> |
POST /v2/sessions/{id}/fork (copies the transcript at the session’s current head). |
delete_session |
async fn(&self, session: &str) -> Result<(), SdkError> |
DELETE /v2/sessions/{id} (deletes the session and its descendant subagent tree). |
list_messages |
async fn(&self, session: &str) -> Result<pb::ListMessagesResponse, SdkError> |
GET /v2/sessions/{id}/messages returns the first page (up to 50 messages). Use list_messages_page across page.next_cursor until page.has_more == false before seeding SessionMirror::from_session. |
list_messages_page |
async fn(&self, session: &str, page: &pb::PageRequest) -> Result<pb::ListMessagesResponse, SdkError> |
GET /v2/sessions/{id}/messages?page.cursor=...&page.limit=... (one page of the projected transcript). |
list_models |
async fn(&self, page: &pb::PageRequest) -> Result<pb::ListModelsResponse, SdkError> |
GET /v2/models (one page of selectable models). |
list_session_commands |
async fn(&self, session: &str, page: &pb::PageRequest) -> Result<pb::ListCommandsResponse, SdkError> |
GET /v2/commands?session={id} (one page of slash commands expanded for session). |
list_session_permission_modes |
async fn(&self, session: &str) -> Result<pb::ListPermissionModesResponse, SdkError> |
GET /v2/permission-modes?session={id} (modes accepted by UpdateSession.permission_mode for session). |
todo |
async fn(&self, session: &str) -> Result<pb::TodoList, SdkError> |
GET /v2/sessions/{id}/todo |
list_events |
async fn(&self, session: &str, since_seq: u64) -> Result<pb::ListEventsResponse, SdkError> |
GET /v2/sessions/{id}/events?sinceSeq=... |
list_raw_events |
async fn(&self, session: &str, since_seq: u64) -> Result<pb::ListEventsResponse, SdkError> |
GET /v2/sessions/{id}/events?sinceSeq=...&includeRaw=true |
Paged reads pass page.cursor and page.limit as query parameters. For example, to fork a session and read the first 50 messages of the fork:
use hya_api::v2 as pb;
let fork = sdk.fork_session(&session.id).await?;let transcript = sdk .list_messages_page(&fork.id, &pb::PageRequest { limit: 50, cursor: String::new() }) .await?;Projects
| Method | Signature | HTTP Route |
|---|---|---|
list_projects |
async fn(&self) -> Result<Vec<pb::ProjectInfo>, SdkError> |
GET /v2/projects |
get_project |
async fn(&self, project: &str) -> Result<pb::ProjectInfo, SdkError> |
GET /v2/projects/{id} |
create_project |
async fn(&self, name: &str, roots: Vec<String>) -> Result<pb::ProjectInfo, SdkError> |
POST /v2/projects |
update_project |
async fn(&self, request: pb::UpdateProjectRequest) -> Result<pb::ProjectInfo, SdkError> |
PATCH /v2/projects/{id} |
delete_project |
async fn(&self, project: &str) -> Result<(), SdkError> |
DELETE /v2/projects/{id} |
resolve_project |
async fn(&self, path: &str) -> Result<Option<pb::ProjectInfo>, SdkError> |
GET /v2/projects/resolve?path=... |
ensure_project_for_path |
async fn(&self, path: &str) -> Result<pb::EnsureProjectForPathResponse, SdkError> |
POST /v2/projects/ensure |
Turns, Interactions & Streaming
| Method | Signature | HTTP Route & Notes |
|---|---|---|
create_turn |
async fn(&self, session: &str, kind: pb::create_turn_request::Kind) -> Result<pb::TurnInfo, SdkError> |
POST /v2/sessions/{id}/turns (admits Prompt, Command, or Shell turn and returns immediately). |
prompt |
async fn(&self, session: &str, text: impl Into<String>) -> Result<pb::TurnInfo, SdkError> |
Convenience helper: admits a PromptTurn and waits up to 120 s for its terminal state. |
wait_turn |
async fn(&self, session: &str, turn: &str, timeout: Duration) -> Result<pb::TurnInfo, SdkError> |
POST /v2/sessions/{id}/turns/{turn}/wait (timeoutMs capped at 600_000; unbounded HTTP timeout). |
cancel_turn |
async fn(&self, session: &str, turn: &str) -> Result<pb::TurnInfo, SdkError> |
POST /v2/sessions/{id}/turns/{turn}/cancel. |
cancel_matching_turn |
async fn(&self, session: &str, turn: &str) -> Result<pb::TurnInfo, SdkError> |
POST /v2/sessions/{id}/turns/{turn}/cancel with {"onlyIfCurrent": true} (leaves a newer turn running). |
list_interactions |
async fn(&self) -> Result<Vec<pb::Interaction>, SdkError> |
GET /v2/interactions (pending permissions and user questions). |
respond_interaction |
async fn(&self, request_id: &str, response: pb::respond_interaction_request::Response) -> Result<bool, SdkError> |
POST /v2/interactions/{id}/respond (returns whether the response was applied). |
stream_session |
async fn(&self, session: &str, since_seq: u64) -> Result<Pin<Box<dyn Stream<Item = Result<pb::StreamFrame, SdkError>> + Send>>, SdkError> |
GET /v2/sessions/{id}/events/stream?sinceSeq=... (single-attempt SSE stream; unbounded HTTP timeout). |
Bundle APIs (BundleApi)
| Method | Signature | HTTP Route & Notes |
|---|---|---|
list_bundle_apis |
async fn(&self, session: Option<&str>) -> Result<pb::ListBundleApisResponse, SdkError> |
GET /v2/bundle-apis (filters by session and/or client’s directory). |
invoke_session_bundle_api |
async fn(&self, session: &str, bundle: &str, method: reqwest::Method, path: &str, query: Option<&str>, body: Option<&Value>) -> Result<Value, SdkError> |
METHOD /v2/sessions/{session}/bundles/{bundle}/{path} (bundle is percent-encoded automatically). |
invoke_session_bundle_api_unbounded |
Same signature as invoke_session_bundle_api |
Identical route with no request timeout, for long-running bundle endpoints. |
invoke_global_bundle_api |
async fn(&self, bundle: &str, method: reqwest::Method, path: &str, query: Option<&str>, body: Option<&Value>) -> Result<Value, SdkError> |
METHOD /v2/bundles/{bundle}/api/{path}. When query is None and sdk.directory() is non-empty, passes ?directory=<scope> automatically. |
invoke_global_bundle_api_unbounded |
Same signature as invoke_global_bundle_api |
Identical route with no request timeout. |
2.2 Client (Low-Level Unscoped HTTP Client)
Use Client when you want direct request/response structs without an implicit directory scope, or when you need to supply a custom reqwest::Client (for example, attaching x-hya-bridge-token default headers for hya relay bridge):
use hya_sdk::Client;use reqwest::header::{HeaderMap, HeaderValue};
let mut headers = HeaderMap::new();headers.insert("x-hya-bridge-token", HeaderValue::from_str(&bridge_token)?);let http = reqwest::Client::builder().default_headers(headers).build()?;let client = Client::with_http_client("http://127.0.0.1:41234", http);let projects = client.list_projects().await?;The request methods return Result<_, ClientError>.
| Method group | Methods on Client |
|---|---|
| Constructors | Client::new(base_url) -> Self, Client::with_http_client(base_url, reqwest::Client) -> Self |
| Projects | list_projects(), get_project(id), create_project(&CreateProjectRequest), update_project(&UpdateProjectRequest), delete_project(id), resolve_project(path), ensure_project_for_path(path) |
| Sessions & Turns | create_session(&CreateSessionRequest), list_sessions(), list_project_sessions(project), create_turn_request(&CreateTurnRequest), wait_turn_request(&WaitTurnRequest), prompt_text(session, text), list_events_request(&ListEventsRequest) |
| Interactions | list_interactions(kind: Option<pb::InteractionType>), respond_interaction(id, &RespondInteractionRequest) |
| Bundle APIs | list_bundle_apis(session, directory), invoke_session_bundle_api(...), invoke_global_bundle_api(...) |
2.3 SessionMirror (Transcript & Extension Reducer)
SessionMirror implements the exact hya.v2 stream folding contract so Rust clients do not re-implement live-vs-durable part reconciliation:
| Member | Signature / Behavior |
|---|---|
SessionMirror::default() |
Creates an empty mirror at last_seq == 0. |
SessionMirror::from_messages(messages: Vec<pb::MessageInfo>, last_seq: u64) -> Self |
Seeds from ListMessages at the durable watermark last_seq. Pending tool calls with empty input_json are marked live-lost until full input arrives. |
SessionMirror::from_session(session: &pb::SessionInfo, messages: Vec<pb::MessageInfo>) -> Self |
Seeds messages at session.last_seq and seeds session.extensions. |
seed_extensions(&mut self, extensions: Option<&pbjson_types::Struct>) |
Replaces the per-bundle extensions map from SessionInfo.extensions. |
apply(&mut self, frame: &pb::StreamFrame) -> bool |
Folds one StreamFrame. Returns true on Resync or SessionReverted (caller must re-read durable messages/session). Ignores durable frames with seq <= self.last_seq. |
last_seq: u64 |
Public field holding the highest applied durable sequence number. |
message(&self, id: &str) -> Option<&pb::MessageInfo> |
Looks up one mirrored message by ID. |
messages(&self) -> Vec<&pb::MessageInfo> |
Returns all mirrored messages in MessageId order (the BTreeMap key order). |
extensions(&self) -> &BTreeMap<String, Value> |
Returns all seeded bundle extension projections keyed by bundle ID. |
extension(&self, bundle: &str) -> Option<&Value> |
Returns the seeded extension projection for one bundle ID (e.g. "hya/workflow"). |
extension_events(&self) -> &[pb::ExtensionEvent] |
Returns all streamed ExtensionEvent frames in arrival order. |
Folding invariants enforced by SessionMirror:
- Parts are keyed by
part.id: a durablepartStartedfor an already-seen live part never duplicates it. - Live
partAppendedframes (seq == 0) grow a part only until it becomes durable (partStarted,partReplaced, or seeded fromListMessages); stale late deltas are ignored. - On
resync, incomplete non-durable parts become live-lost: partial toolinput_jsonis cleared and further live deltas are ignored until a durablepartReplacedor fulltoolStateChangedarrives. partDeletedremoves the part;sessionRevertedreturnstrueso the caller re-seeds fromlist_messages_page.
2.4 Error Types (SdkError & ClientError)
| Type | Variants |
|---|---|
SdkError |
Http(reqwest::Error), Api { code: String, message: String }, StreamDecode(serde_json::Error), Stream(String) |
ClientError |
Http(reqwest::Error), Api { code: String, message: String }, Decode(serde_json::Error) |
stream_session uses error_for_status() on the initial SSE response, mapping non-2xx handshake errors to SdkError::Http.
For ordinary API requests, non-2xx responses carrying the standard v2 JSON error envelope ({ "error": { "code": "...", "message": "..." } }) decode into Api { code, message }; other error bodies fall back to code = "<http-status>". See hya.v2 Protocol Overview — Pagination & Error Codes for the stable error code table.
3. Direct gRPC Clients (hya-api / proto/hya/v2)
Prefer gRPC over HTTP/JSON? Point any tonic, Go, Python, or Connect/gRPC client (HTTP/2 cleartext h2c locally, or over the encrypted relay) at the same http://127.0.0.1:<port> address using the .proto definitions in proto/hya/v2/.
In Rust workspace crates, hya_api::v2 exports all generated prost messages and tonic client stubs out of the box. Inspect the x-hya-error-code trailing metadata header on gRPC errors to distinguish stable wire codes such as session_busy vs failed_precondition.
Editor MCP leases
A local editor can call Mcp/OpenMcpSession or POST /v2/mcp/session with {"session":"<id>","peers":[]} to replace an existing session’s MCP peers with an empty set. Read the initial response’s session field and keep the stream open to own the lease. Creating a session through this RPC requires at least one peer.
Configured HTTP MCP peer headers are sent only to the peer URL’s origin. The backend rejects cross-origin redirects and classic SSE endpoints on another origin, while resolving relative SSE endpoints against same-origin redirected stream URLs.
4. Lightweight Shell / TypeScript / Python Integration
If you don’t need a persistent server connection, spawn hya exec --json as a subprocess and read one committed event per line from stdout:
hya exec --json "Find unused dependencies in package.json"When you do want persistent sessions, live multi-client sync, bundle APIs, or interactive permission approvals from a custom web or desktop frontend, start or discover the daemon with hya server start --json (parse its url field) and speak /v2 HTTP + SSE directly:
// Minimal browser / Bun / Node fetch + EventSource patternconst base = "http://127.0.0.1:8080"
const { session } = await fetch(`${base}/v2/sessions`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ agent: "hya-main", model: "hya/offline", workdir: "/tmp" }),}).then((r) => r.json())
const events = new EventSource(`${base}/v2/sessions/${session.id}/events/stream`)events.onmessage = (e) => { const frame = JSON.parse(e.data) console.log("Frame:", frame)}
await fetch(`${base}/v2/sessions/${session.id}/turns`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ prompt: { text: "Hello from TypeScript!" } }),})
// Invoke a native or JS bundle endpoint via BundleApi:const workflows = await fetch( `${base}/v2/bundles/hya%2Fworkflow/api/workflows?directory=/tmp`,).then((r) => r.json())console.log("Workflows:", workflows)Remote Relay note: If your custom client connects through a local
hya relay bridge --json, pass the printedtokenon every HTTP/SSE request asx-hya-bridge-token: <token>, and send requests from a native/Node/Bun process rather than directly from a third-party browserOrigin(browserOrigin/Sec-Fetch-*headers are blocked over the relay to protect remote shells from malicious web pages).