Skip to content

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:

text
kompile-cli-mobile-aot-<version>-android-arm64.zip
kompile-cli-mobile-aot-<version>-android-arm64.zip.sha256

Inside the archive:

text
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 verifier

The 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: ELF64 DYN AArch64 (arm64-v8a), Android API 28+, with Android NDK identity note
  • Android 15+ page alignment: every PT_LOAD segment aligned to 0x4000 (16 KiB)
  • Hardening: GNU_RELRO, BIND_NOW, no RPATH/RUNPATH, no TEXTREL, explicit SONAME libkompile_harness_android.so
  • Minimal bionic linkage: DT_NEEDED is locked to libc.so, libdl.so, liblog.so, libm.so, and libz.so
  • Strict public symbol surface: only the 14 kmh_* symbols are exported (controlled via kmh_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 ship android-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):

bash
# 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=28

The packaged SDK lands at:

text
kompile-cli/kompile-cli-mobile-aot/target/kompile-cli-mobile-aot-<version>-android-arm64.zip

You can also run the verifier directly against any extracted library:

bash
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:

GroupFunctionPurpose
Isolateint 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.
Engineint 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 RPCchar* 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 Chatchar* 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 & Memorychar* 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 ​

  1. Keep graal_isolatethread_t* thread-affine. Never pass a graal_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 every kmh_* call.
  2. Always call kmh_free(thread, ptr). Every char* returned by kmh_call, kmh_chat_*, or kmh_last_error is allocated in GraalVM unmanaged memory and must be freed via kmh_free — never system free().
  3. Pass the device's CA PEM bundle to kmh_init. The AOT binary does not ship a stale JKS cacerts file. Passing concatenated X.509 PEM certificates in ca_certs_pem installs them as the default SSLContext for cloud HTTPS calls while pinned-TLS Kompile peers (PeerTls) continue enforcing their explicit SHA-256 certificate fingerprints independently.
  4. 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 ​

c
#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:

DomainMethodsWhat they expose
Healthhealth, statusHarness home, work dir, installed CA cert count, active provider/model.
Auth & Providersauth.status, auth.api_key, auth.switch, auth.logout, auth.oauth_start, auth.oauth_poll, auth.oauth_reply, auth.oauth_cancel, providers.list, providers.modelsAPI-key credentials, interactive OAuth flows (poll + reply without a desktop terminal), active provider switching, and live model discovery.
Chat Configconfig.get, config.setActive provider, model, base URL, credential name, default memory toggle.
Peers & Syncpeer.executeFull PeerService surface — pair with desktop/server Kompile peers over pinned TLS, sync memories/skills/sessions, query peer status.
Unified Sourcessources.executeFull SourcesTool / HarnessSourceService surface — inspect and pull shared rules, skills, memories, and catalogs across registered sources.
Blob Storesblob.list, blob.add, blob.removeConfigure object/blob storage backends used by sync and artifacts.
Memorymemory.executeRead, search, save, and organize persistent harness memories.
Skills & Rolesskills.list, skills.save, skills.delete, roles.list, roles.set_activeManage /skill templates and active system-prompt roles.
Remote MCPmcp.list, mcp.add, mcp.removeRegister and inspect remote SSE / Streamable HTTP MCP servers.
Pluginsplugins.listList compiled-in CliExtension descriptors.
Transcriptssessions.list, sessions.read, sessions.rename, sessions.delete, sessions.clear_contextBrowse 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, and websearch.
  • Host-provided tools are declared via the hostTools array (name, description, inputSchema) on kmh_chat_start. When the model invokes a host tool, the isolate emits a host_tool_call event (callId, tool, argsJson) and waits up to 60 seconds for the host app to call kmh_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:

  1. Thin JNI bridge (libjnikompile_harness.so) — kompile-chat-local/mobile/android/app/src/main/cpp/kompile_harness_android_jni.cpp wraps the kmh_* C calls into JNI methods, immediately copying returned UTF-8 strings into jstring and calling kmh_free(thread, res). Built with kompile-chat-local/mobile/android/tools/build-harness-jni.sh (16 KiB page-aligned, linked directly against libkompile_harness_android.so).
  2. Export AndroidCAStore to PEM — kompile-chat-local/.../harness/AndroidCaCertificateBundle.kt reads KeyStore.getInstance("AndroidCAStore"), base64-encodes each X509Certificate into PEM blocks, and passes the concatenated string to kmh_init.
  3. Single-thread isolate owner — kompile-chat-local/.../harness/KompileHarnessRuntime.kt funnels createIsolate, init, callJson, chatStart, chatPoll, chatToolResult, chatCancel, and shutdown through one dedicated Executors.newSingleThreadExecutor thread so graal_isolatethread_t* never crosses OS threads.
  4. Isolated Android process (:kompile_harness) — kompile-chat-local/.../harness/KompileHarnessService.kt hosts the GraalVM isolate inside android:process=":kompile_harness" behind a Messenger IPC boundary, isolating the harness heap and lifecycle cleanly from the UI process and on-device LLM/graph accelerators.

Released under the Apache-2.0 License.