Embeddable Mobile Harness (C ABI)
Kompile compiles its real CLI harness (kompile-cli-main) ahead of time into an embeddable native shared library (libkompile_harness_android.so) with a 14-function C header (kompile-cli/kompile-cli-mobile-aot/include/kompile_harness.h).
Mobile apps can embed the exact same provider auth (API keys and OAuth), direct cloud and peer LLM streaming, pinned-TLS peer sync, unified harness sources, persistent memory, skills, roles, transcripts, and remote MCP configuration — without shipping a JVM, Spring, ND4J, SQLite, or Gluon.
What ships in the SDK
Each release publishes the Android ARM64 SDK archive alongside the desktop distributions on GitHub Releases:
kompile-cli-mobile-aot-<version>-android-arm64.zip
kompile-cli-mobile-aot-<version>-android-arm64.zip.sha256Inside the archive:
jni/arm64-v8a/libkompile_harness_android.so # AArch64 ELF shared library (API 28+, 16 KiB aligned)
include/kompile_harness.h # Stable kmh_* C ABI header (ABI v1)
metadata/build.properties # Target ABI, Android API level, and ABI version
bin/verify-android-ndk.sh # Fail-closed ELF / SONAME / export / DT_NEEDED verifierThe library is built with stock Oracle GraalVM 21 Native Image (21.0.10) and Android NDK r28b (28.1.13356709) — no Gluon or custom fork — and is verified before packaging by verify-android-ndk.sh:
- Target:
ELF64DYNAArch64(arm64-v8a), Android API 28+, with Android NDK identity note - Android 15+ page alignment: every
PT_LOADsegment aligned to0x4000(16 KiB) - Hardening:
GNU_RELRO,BIND_NOW, noRPATH/RUNPATH, noTEXTREL, explicit SONAMElibkompile_harness_android.so - Minimal bionic linkage:
DT_NEEDEDis locked tolibc.so,libdl.so,liblog.so,libm.so, andlibz.so - Strict public symbol surface: only the 14
kmh_*symbols are exported (controlled viakmh_android_exports.map)
Platform scope: The
kmh_*C ABI and poll-based host-tool protocol are platform-neutral (designed for JNI on Android and Swift bridging headers on iOS). Prebuilt GitHub Release archives currently shipandroid-arm64(arm64-v8a, Android API 28+).
Build from source
To build and verify the Android ARM64 SDK locally from a Kompile checkout (Linux x86_64 host with Oracle GraalVM 21.0.10, Android NDK 28.1.13356709, clang, autoconf, make, and qemu-aarch64-static):
# 1. Install the pure-Java closure (no ND4J, Spring, or desktop native deps)
mvn -B install -pl kompile-cli/kompile-cli-mobile-aot -am -DskipTests -Dkompile.skip.native=true
# 2. Cross-compile, verify ELF/ABI invariants, and package the android-arm64 ZIP
mvn -B package -pl kompile-cli/kompile-cli-mobile-aot -DskipTests \
-Dkompile.mobile.harness.aot=true \
-Dmobile.harness.android.ndk="$ANDROID_NDK_ROOT" \
-Dmobile.harness.graalvm.home="$GRAALVM_HOME" \
-Dmobile.harness.android.api=28The packaged SDK lands at:
kompile-cli/kompile-cli-mobile-aot/target/kompile-cli-mobile-aot-<version>-android-arm64.zipYou can also run the verifier directly against any extracted library:
bash bin/verify-android-ndk.sh \
--library jni/arm64-v8a/libkompile_harness_android.so \
--android-ndk "$ANDROID_NDK_ROOT"The kmh_* C ABI (kompile_harness.h)
All 14 exported functions use plain C types and UTF-8 JSON payloads:
| Group | Function | Purpose |
|---|---|---|
| Isolate | int kmh_abi_version(graal_isolatethread_t* thread) | Returns ABI version (1). |
graal_isolatethread_t* kmh_create_isolate(void) | Creates the single GraalVM isolate and attaches the calling OS thread. | |
graal_isolatethread_t* kmh_attach_thread(graal_isolate_t* isolate) | Attaches another OS thread to an existing isolate. | |
int kmh_detach_thread(graal_isolatethread_t* thread) | Detaches a previously attached thread. | |
int kmh_tear_down_isolate(graal_isolatethread_t* thread) | Tears down the isolate on process shutdown. | |
| Engine | int kmh_init(thread, const char* user_home, const char* work_dir, const char* ca_certs_pem) | Initializes the harness rooted at user_home (~/.kompile lives inside it), sets work_dir, and installs the device CA PEM bundle as the default TLS trust store. Returns 0 on success, -1 on error. |
int kmh_shutdown(thread) | Cancels active chat turns and closes the harness engine. | |
| Sync RPC | char* kmh_call(thread, const char* method, const char* params_json) | Synchronous JSON-RPC call returning a UTF-8 JSON object ({"ok":true,...} or {"ok":false,"error":...}). |
| Streaming Chat | char* kmh_chat_start(thread, const char* params_json) | Starts an async streaming chat turn and returns {"ok":true,"turnId":"...","sessionId":"..."}. |
char* kmh_chat_poll(thread, const char* turn_id, int64_t timeout_ms) | Drains queued turn events (blocks up to timeout_ms, capped at 15,000 ms) and reports finished. | |
char* kmh_chat_tool_result(thread, const char* turn_id, const char* call_id, const char* result_json, int is_error) | Supplies the host app's result for a host_tool_call event. | |
char* kmh_chat_cancel(thread, const char* turn_id) | Cancels an in-flight turn and unblocks any pending host tool call. | |
| Errors & Memory | char* kmh_last_error(thread) | Returns the thread-local last error string. |
void kmh_free(thread, char* ptr) | Frees any char* returned by kmh_*. |
Four rules to follow
- Keep
graal_isolatethread_t*thread-affine. Never pass agraal_isolatethread_t*created on Thread A to calls running on Thread B. The simplest pattern is a single dedicated OS thread (single-thread executor) owning everykmh_*call. - Always call
kmh_free(thread, ptr). Everychar*returned bykmh_call,kmh_chat_*, orkmh_last_erroris allocated in GraalVM unmanaged memory and must be freed viakmh_free— never systemfree(). - Pass the device's CA PEM bundle to
kmh_init. The AOT binary does not ship a stale JKScacertsfile. Passing concatenated X.509 PEM certificates inca_certs_peminstalls them as the defaultSSLContextfor cloud HTTPS calls while pinned-TLS Kompile peers (PeerTls) continue enforcing their explicit SHA-256 certificate fingerprints independently. - No reverse C-to-Java callbacks. Streaming tokens and host-side tools run over the poll queue (
kmh_chat_poll+kmh_chat_tool_result), which keeps JNI and Swift FFI bridges dead simple and eliminates cross-runtime re-entrancy crashes.
Minimal C embedding example
#include "kompile_harness.h"
#include <stdio.h>
#include <string.h>
int run_mobile_harness(const char* user_home, const char* work_dir, const char* ca_pem) {
graal_isolatethread_t* thread = kmh_create_isolate();
if (!thread) {
return 1;
}
if (kmh_abi_version(thread) != 1) {
kmh_tear_down_isolate(thread);
return 2;
}
if (kmh_init(thread, user_home, work_dir, ca_pem) != 0) {
char* err = kmh_last_error(thread);
fprintf(stderr, "kmh_init failed: %s\n", err ? err : "unknown");
kmh_free(thread, err);
kmh_tear_down_isolate(thread);
return 3;
}
// 1. Inspect harness status via sync JSON-RPC
char* status = kmh_call(thread, "status", "{}");
printf("status: %s\n", status);
kmh_free(thread, status);
// 2. Start a streaming chat turn, exposing a host-side tool to the model
const char* start_params =
"{"
"\"message\":\"Summarize my synced notes and check local battery status.\","
"\"provider\":\"anthropic\","
"\"model\":\"claude-sonnet-4-6\","
"\"enableTools\":true,"
"\"includeMemory\":true,"
"\"hostTools\":[{"
"\"name\":\"device_battery\","
"\"description\":\"Read current device battery level and charging state.\","
"\"inputSchema\":{\"type\":\"object\",\"properties\":{}}"
"}]"
"}";
char* started = kmh_chat_start(thread, start_params);
printf("started: %s\n", started);
// Parse "turnId" from `started` in your host JSON library, then free:
kmh_free(thread, started);
// 3. Poll events until finished == true:
// - {"type":"phase","phase":"preparing"|"generating"|"tools"|"continuing"}
// - {"type":"text","delta":"..."}
// - {"type":"thinking","delta":"..."}
// - {"type":"tool_call","callId":"...","tool":"...","argsJson":"..."}
// - {"type":"host_tool_call","callId":"...","tool":"device_battery","argsJson":"{}"}
// -> execute locally, then call:
// kmh_chat_tool_result(thread, turn_id, call_id, "{\"percent\":82}", 0)
// - {"type":"tool_result","callId":"...","tool":"...","output":"...","isError":false}
// - {"type":"done","text":"...","elapsedMs":1234,"inputTokens":...,"outputTokens":...}
// - {"type":"error","error":"...","statusCode":...}
kmh_shutdown(thread);
kmh_tear_down_isolate(thread);
return 0;
}Synchronous kmh_call methods
Every non-streaming harness operation goes through kmh_call(thread, method, params_json) and returns JSON with "ok": true | false:
| Domain | Methods | What they expose |
|---|---|---|
| Health | health, status | Harness home, work dir, installed CA cert count, active provider/model. |
| Auth & Providers | auth.status, auth.api_key, auth.switch, auth.logout, auth.oauth_start, auth.oauth_poll, auth.oauth_reply, auth.oauth_cancel, providers.list, providers.models | API-key credentials, interactive OAuth flows (poll + reply without a desktop terminal), active provider switching, and live model discovery. |
| Chat Config | config.get, config.set | Active provider, model, base URL, credential name, default memory toggle. |
| Peers & Sync | peer.execute | Full PeerService surface — pair with desktop/server Kompile peers over pinned TLS, sync memories/skills/sessions, query peer status. |
| Unified Sources | sources.execute | Full SourcesTool / HarnessSourceService surface — inspect and pull shared rules, skills, memories, and catalogs across registered sources. |
| Blob Stores | blob.list, blob.add, blob.remove | Configure object/blob storage backends used by sync and artifacts. |
| Memory | memory.execute | Read, search, save, and organize persistent harness memories. |
| Skills & Roles | skills.list, skills.save, skills.delete, roles.list, roles.set_active | Manage /skill templates and active system-prompt roles. |
| Remote MCP | mcp.list, mcp.add, mcp.remove | Register and inspect remote SSE / Streamable HTTP MCP servers. |
| Plugins | plugins.list | List compiled-in CliExtension descriptors. |
| Transcripts | sessions.list, sessions.read, sessions.rename, sessions.delete, sessions.clear_context | Browse and manage persistent chat transcripts stored under user_home. |
Built-in tools + host tool callbacks
When enableTools is true in kmh_chat_start:
- Built-in harness tools run directly inside the AOT isolate:
memory,peer,sources,webfetch, andwebsearch. - Host-provided tools are declared via the
hostToolsarray (name,description,inputSchema) onkmh_chat_start. When the model invokes a host tool, the isolate emits ahost_tool_callevent (callId,tool,argsJson) and waits up to 60 seconds for the host app to callkmh_chat_tool_result(thread, turnId, callId, resultJson, isError).
This is how Kompile's own Android app (kompile-chat-local) lets cloud or peer models call on-device .kgraph knowledge-graph tools that live in a separate native runtime, without coupling the two libraries together.
Android integration pattern (kompile-chat-local)
Kompile's Android app embeds libkompile_harness_android.so with four small building blocks you can reuse as a template:
- Thin JNI bridge (
libjnikompile_harness.so) —kompile-chat-local/mobile/android/app/src/main/cpp/kompile_harness_android_jni.cppwraps thekmh_*C calls into JNI methods, immediately copying returned UTF-8 strings intojstringand callingkmh_free(thread, res). Built withkompile-chat-local/mobile/android/tools/build-harness-jni.sh(16 KiB page-aligned, linked directly againstlibkompile_harness_android.so). - Export
AndroidCAStoreto PEM —kompile-chat-local/.../harness/AndroidCaCertificateBundle.ktreadsKeyStore.getInstance("AndroidCAStore"), base64-encodes eachX509Certificateinto PEM blocks, and passes the concatenated string tokmh_init. - Single-thread isolate owner —
kompile-chat-local/.../harness/KompileHarnessRuntime.ktfunnelscreateIsolate,init,callJson,chatStart,chatPoll,chatToolResult,chatCancel, andshutdownthrough one dedicatedExecutors.newSingleThreadExecutorthread sograal_isolatethread_t*never crosses OS threads. - Isolated Android process (
:kompile_harness) —kompile-chat-local/.../harness/KompileHarnessService.kthosts the GraalVM isolate insideandroid:process=":kompile_harness"behind aMessengerIPC boundary, isolating the harness heap and lifecycle cleanly from the UI process and on-device LLM/graph accelerators.
Related docs
- CLI Harness (TUI & Config) — desktop terminal harness sharing the same
kompile-cli-mainengine - Web Harness — browser UI over the same harness
- Peers & Sources — pairing mobile devices with desktop/server Kompile peers over pinned TLS
- Security & Permissions — Kompile's trust boundaries, credential storage, and minimal permission model
- Installation & Updates — desktop release archives and verification