diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml
new file mode 100644
index 00000000..6b92d7b5
--- /dev/null
+++ b/.github/workflows/android.yml
@@ -0,0 +1,42 @@
+name: android
+
+on:
+ push:
+ branches:
+ - main
+ paths:
+ - 'android/**'
+ - 'shared/fixtures/**'
+ - '.github/workflows/android.yml'
+ pull_request:
+ paths:
+ - 'android/**'
+ - 'shared/fixtures/**'
+ - '.github/workflows/android.yml'
+
+permissions:
+ contents: read
+
+concurrency:
+ group: android-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ defaults:
+ run:
+ working-directory: android
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-java@v4
+ with:
+ distribution: temurin
+ java-version: '21'
+ # Android SDK is preinstalled on GitHub ubuntu runners (licenses
+ # accepted); AGP auto-installs any missing platform/build-tools.
+ - uses: gradle/actions/setup-gradle@v4
+ - name: Protocol tests (pure JVM, fixtures-driven)
+ run: ./gradlew :core:protocol:test
+ - name: Assemble debug APK
+ run: ./gradlew :app:assembleDebug
diff --git a/.gitignore b/.gitignore
index 7c12eb73..af4dd748 100644
--- a/.gitignore
+++ b/.gitignore
@@ -50,3 +50,12 @@ e2e-output/
.xyz-harness
.agents/
.pi/
+
+# Android (android/)
+android/**/build/
+android/.gradle/
+android/.kotlin/
+android/local.properties
+android/captures/
+*.keystore
+*.jks
diff --git a/android/README.md b/android/README.md
new file mode 100644
index 00000000..74b6f442
--- /dev/null
+++ b/android/README.md
@@ -0,0 +1,77 @@
+# HAPI Android Companion
+
+Native Android client (Kotlin + Jetpack Compose) for the HAPI hub. Fully
+independent from the web app; shares only the protocol contract
+(`docs/api/`) and the golden fixtures (`shared/fixtures/`).
+
+- **applicationId**: `run.hapi.companion` · **minSdk** 26 · **target/compileSdk** 36
+- **Toolchain**: Gradle 8.14.2 (wrapper) · AGP 8.11.1 · Kotlin 2.1.21 · Compose BOM 2025.05.00 · JDK 17+ (CI uses 21)
+
+## Modules
+
+| Module | Type | Responsibility |
+|---|---|---|
+| `:core:protocol` | **pure Kotlin/JVM** (no Android) | Hub wire types (kotlinx.serialization), chat pipeline port (normalize → reduce → tool groups), message-window/pagination logic, versioned patch application, modes catalog, git output parsers, `BindLink` pairing-link parsing. |
+| `:core:data` | Android library | Transport + persistence: `HapiApi` (OkHttp REST, single-flight 401 re-auth), `SseEngine` (okhttp-sse, resume/backoff state machine), StateFlow stores + AtomicFile JSON snapshots, credential store, FCM registration, WorkManager workers. Placeholder in M0 — see `DataModule.kt`. |
+| `:app` | Android application | Compose UI, navigation, deep links (`hapicompanion://bind`), FCM service (M4), hand-rolled DI (`AppGraph`, no Hilt). |
+
+Dependency direction: `:app` → `:core:data` → `:core:protocol`.
+
+## Protocol conformance fixtures
+
+`:core:protocol` is the porting target for `web/src/chat/` and is verified
+against golden fixtures generated from the web implementation (track K).
+The test task already passes the fixtures location as a system property:
+
+```kotlin
+// core/protocol/build.gradle.kts
+tasks.test {
+ systemProperty("hapi.fixtures.dir", rootDir.parentFile.resolve("shared/fixtures").absolutePath)
+}
+```
+
+Fixture-driven tests (M2) read `System.getProperty("hapi.fixtures.dir")` —
+no further build changes are needed when `shared/fixtures/**` lands. CI
+re-runs this suite whenever `android/**` or `shared/fixtures/**` change.
+
+## Building
+
+Requires an Android SDK for `:app`/`:core:data` (set `ANDROID_HOME` or
+`android/local.properties` with `sdk.dir=...`). `:core:protocol` alone needs
+only a JDK.
+
+```sh
+cd android
+./gradlew :core:protocol:test # pure JVM protocol tests (fast)
+./gradlew :app:assembleDebug # debug APK
+./gradlew :app:installDebug # install on a connected device
+```
+
+Without an Android SDK you can still run the protocol suite by configuring
+only the needed projects:
+
+```sh
+./gradlew --no-configuration-cache --configure-on-demand :core:protocol:test
+```
+
+CI (`.github/workflows/android.yml`) runs the protocol tests and
+`:app:assembleDebug` on every PR touching `android/**` or `shared/fixtures/**`.
+
+## Milestones (track B of the native-clients plan)
+
+- **M0** — this scaffold: modules, version catalog, CI, placeholder screen.
+- **M1** — foundations: wire types + modes catalog; auth + `HapiApi` (MockWebServer-tested); `SseEngine` reconnect state machine + versioned patches (gzip streaming verified); pairing UI + `hapicompanion://bind` deep link.
+- **M2** — read-only chat: chat pipeline port gated on fixtures all-green; session list; `MessageWindowStore` port; Markdown renderer; read-only chat screen (`LazyColumn(reverseLayout = true)`).
+- **M3** — interaction: composer (optimistic send/queue/steer/drafts), permission approvals UX, session controls (mode/model/abort/resume/rename/archive), new session, dictation.
+- **M4** — FCM push (register → notification actions via expedited WorkManager) + files/git viewer, Scratchlist, usage/storage stats.
+- **M5** — polish: zh-CN i18n, OLED/Material You theming, predictive back, LeakCanary pass, Play listing + self-build docs.
+
+## Firebase / push (self-build note)
+
+M0 deliberately does **not** apply the `com.google.gms.google-services`
+plugin and has no Firebase dependency, so the project builds without any
+`google-services.json`. In M4a the plugin lands together with the FCM
+service: official builds inject the default Firebase project config in CI,
+while self-builders drop in their own `app/google-services.json` (docs will
+accompany M4a; a `PushBinding` seam for hub-provided `FirebaseOptions` is
+planned for v1.x).
diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts
new file mode 100644
index 00000000..99a21d70
--- /dev/null
+++ b/android/app/build.gradle.kts
@@ -0,0 +1,63 @@
+import org.jetbrains.kotlin.gradle.dsl.JvmTarget
+
+plugins {
+ alias(libs.plugins.android.application)
+ alias(libs.plugins.kotlin.android)
+ alias(libs.plugins.kotlin.compose)
+ // NOTE: com.google.gms.google-services is deliberately NOT applied in M0.
+ // It is added in M4a together with google-services.json + the FCM service,
+ // so the scaffold builds green without any Firebase project configured.
+}
+
+android {
+ namespace = "app.hapi.companion"
+ compileSdk = 36
+
+ defaultConfig {
+ applicationId = "run.hapi.companion"
+ minSdk = 26
+ targetSdk = 36
+ versionCode = 1
+ versionName = "0.1.0"
+ }
+
+ buildTypes {
+ release {
+ isMinifyEnabled = true
+ isShrinkResources = true
+ proguardFiles(
+ getDefaultProguardFile("proguard-android-optimize.txt"),
+ "proguard-rules.pro"
+ )
+ }
+ }
+
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+
+ buildFeatures {
+ compose = true
+ }
+}
+
+kotlin {
+ compilerOptions {
+ jvmTarget.set(JvmTarget.JVM_17)
+ }
+}
+
+dependencies {
+ implementation(project(":core:protocol"))
+ implementation(project(":core:data"))
+
+ implementation(libs.androidx.core.ktx)
+ implementation(libs.androidx.activity.compose)
+
+ implementation(platform(libs.androidx.compose.bom))
+ implementation(libs.androidx.compose.ui)
+ implementation(libs.androidx.compose.material3)
+ implementation(libs.androidx.compose.ui.tooling.preview)
+ debugImplementation(libs.androidx.compose.ui.tooling)
+}
diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro
new file mode 100644
index 00000000..dcccef4d
--- /dev/null
+++ b/android/app/proguard-rules.pro
@@ -0,0 +1,3 @@
+# App-specific R8/ProGuard rules.
+# kotlinx.serialization ships its own consumer rules; add rules here only when a
+# release build actually needs them (verified via :app:assembleRelease + smoke test).
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
new file mode 100644
index 00000000..359d0d7f
--- /dev/null
+++ b/android/app/src/main/AndroidManifest.xml
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/android/app/src/main/kotlin/app/hapi/companion/AppGraph.kt b/android/app/src/main/kotlin/app/hapi/companion/AppGraph.kt
new file mode 100644
index 00000000..cc445280
--- /dev/null
+++ b/android/app/src/main/kotlin/app/hapi/companion/AppGraph.kt
@@ -0,0 +1,15 @@
+package app.hapi.companion
+
+/**
+ * Hand-rolled dependency graph seed (no Hilt/Dagger by design -- the app wires
+ * roughly 15 long-lived types, which does not justify a DI framework).
+ *
+ * From M1 on this becomes a class instantiated in `HapiApplication.onCreate()`
+ * that owns the singletons in construction order:
+ * CredentialStore -> AuthManager -> HapiApi -> SseEngine -> stores
+ * (session list / session detail / message window) -> push registration.
+ * Compose reads it via a CompositionLocal; workers/services reach it through
+ * the Application instance. Everything behind it stays constructor-injected
+ * and unit-testable without this object.
+ */
+object AppGraph
diff --git a/android/app/src/main/kotlin/app/hapi/companion/MainActivity.kt b/android/app/src/main/kotlin/app/hapi/companion/MainActivity.kt
new file mode 100644
index 00000000..3633f306
--- /dev/null
+++ b/android/app/src/main/kotlin/app/hapi/companion/MainActivity.kt
@@ -0,0 +1,69 @@
+package app.hapi.companion
+
+import android.os.Bundle
+import androidx.activity.ComponentActivity
+import androidx.activity.compose.setContent
+import androidx.activity.enableEdgeToEdge
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.height
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Surface
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.tooling.preview.Preview
+import androidx.compose.ui.unit.dp
+import app.hapi.companion.ui.theme.HapiTheme
+import app.hapi.protocol.wire.SUPPORTED_PROTOCOL_VERSION
+
+/**
+ * Single-activity entry point. M1d replaces the placeholder with the pairing
+ * flow (QR scan + `hapicompanion://bind` deep link handling -- the intent
+ * filter is already declared in the manifest) and Navigation Compose.
+ */
+class MainActivity : ComponentActivity() {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ enableEdgeToEdge()
+ setContent {
+ HapiTheme {
+ PlaceholderScreen()
+ }
+ }
+ }
+}
+
+@Composable
+private fun PlaceholderScreen() {
+ Surface(modifier = Modifier.fillMaxSize()) {
+ Column(
+ modifier = Modifier.fillMaxSize(),
+ verticalArrangement = Arrangement.Center,
+ horizontalAlignment = Alignment.CenterHorizontally,
+ ) {
+ Text(
+ text = "HAPI",
+ style = MaterialTheme.typography.displayLarge,
+ color = MaterialTheme.colorScheme.primary,
+ )
+ Spacer(modifier = Modifier.height(8.dp))
+ Text(
+ text = "Companion scaffold · protocol v$SUPPORTED_PROTOCOL_VERSION",
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ }
+}
+
+@Preview(showBackground = true)
+@Composable
+private fun PlaceholderScreenPreview() {
+ HapiTheme {
+ PlaceholderScreen()
+ }
+}
diff --git a/android/app/src/main/kotlin/app/hapi/companion/ui/theme/Theme.kt b/android/app/src/main/kotlin/app/hapi/companion/ui/theme/Theme.kt
new file mode 100644
index 00000000..2c11f192
--- /dev/null
+++ b/android/app/src/main/kotlin/app/hapi/companion/ui/theme/Theme.kt
@@ -0,0 +1,51 @@
+package app.hapi.companion.ui.theme
+
+import android.os.Build
+import androidx.compose.foundation.isSystemInDarkTheme
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.darkColorScheme
+import androidx.compose.material3.dynamicDarkColorScheme
+import androidx.compose.material3.dynamicLightColorScheme
+import androidx.compose.material3.lightColorScheme
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.LocalContext
+
+private val LightColorScheme = lightColorScheme(
+ primary = Color(0xFF3D6837),
+ secondary = Color(0xFF54634D),
+ tertiary = Color(0xFF386569),
+)
+
+private val DarkColorScheme = darkColorScheme(
+ primary = Color(0xFFA3D397),
+ secondary = Color(0xFFBCCBB2),
+ tertiary = Color(0xFFA0CFD2),
+)
+
+/**
+ * Material3 theme for the HAPI companion app.
+ *
+ * Dynamic color (Material You) on Android 12+, static fallback schemes below.
+ * M5 revisits this for OLED-black surfaces and full token coverage.
+ */
+@Composable
+fun HapiTheme(
+ darkTheme: Boolean = isSystemInDarkTheme(),
+ dynamicColor: Boolean = true,
+ content: @Composable () -> Unit,
+) {
+ val colorScheme = when {
+ dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
+ val context = LocalContext.current
+ if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
+ }
+ darkTheme -> DarkColorScheme
+ else -> LightColorScheme
+ }
+
+ MaterialTheme(
+ colorScheme = colorScheme,
+ content = content,
+ )
+}
diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml
new file mode 100644
index 00000000..972ceafb
--- /dev/null
+++ b/android/app/src/main/res/values/strings.xml
@@ -0,0 +1,4 @@
+
+
+ HAPI
+
diff --git a/android/app/src/main/res/values/themes.xml b/android/app/src/main/res/values/themes.xml
new file mode 100644
index 00000000..2da5ac2a
--- /dev/null
+++ b/android/app/src/main/res/values/themes.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
diff --git a/android/build.gradle.kts b/android/build.gradle.kts
new file mode 100644
index 00000000..a7ebbb2c
--- /dev/null
+++ b/android/build.gradle.kts
@@ -0,0 +1,9 @@
+// Root build file: declares plugin versions for all modules (applied per-module).
+plugins {
+ alias(libs.plugins.android.application) apply false
+ alias(libs.plugins.android.library) apply false
+ alias(libs.plugins.kotlin.android) apply false
+ alias(libs.plugins.kotlin.jvm) apply false
+ alias(libs.plugins.kotlin.compose) apply false
+ alias(libs.plugins.kotlin.serialization) apply false
+}
diff --git a/android/core/data/build.gradle.kts b/android/core/data/build.gradle.kts
new file mode 100644
index 00000000..45699873
--- /dev/null
+++ b/android/core/data/build.gradle.kts
@@ -0,0 +1,38 @@
+import org.jetbrains.kotlin.gradle.dsl.JvmTarget
+
+// Android library: transport + persistence layer (see DataModule.kt for the plan).
+plugins {
+ alias(libs.plugins.android.library)
+ alias(libs.plugins.kotlin.android)
+ alias(libs.plugins.kotlin.serialization)
+}
+
+android {
+ namespace = "app.hapi.data"
+ compileSdk = 36
+
+ defaultConfig {
+ minSdk = 26
+ }
+
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+}
+
+kotlin {
+ compilerOptions {
+ jvmTarget.set(JvmTarget.JVM_17)
+ }
+}
+
+dependencies {
+ api(project(":core:protocol"))
+ implementation(libs.kotlinx.coroutines.core)
+ implementation(libs.kotlinx.serialization.json)
+
+ testImplementation(libs.junit)
+ testImplementation(libs.kotlin.test)
+ testImplementation(libs.kotlinx.coroutines.test)
+}
diff --git a/android/core/data/src/main/kotlin/app/hapi/data/DataModule.kt b/android/core/data/src/main/kotlin/app/hapi/data/DataModule.kt
new file mode 100644
index 00000000..bc58ea8a
--- /dev/null
+++ b/android/core/data/src/main/kotlin/app/hapi/data/DataModule.kt
@@ -0,0 +1,27 @@
+package app.hapi.data
+
+/**
+ * Placeholder anchor for the `:core:data` module (B-M0 scaffolding).
+ *
+ * This module owns transport + persistence and will grow, per the plan
+ * (`docs`/plan track B), into:
+ *
+ * - `HapiApi` -- OkHttp-based REST client for the hub (`/api/auth`, sessions,
+ * messages, permissions, machines, git, scratchlist, transcription, usage,
+ * `/api/devices/register`), with a single-flight `Authenticator` that silently
+ * re-exchanges the stored access token on 401 (JWT expires after 4h).
+ * - `SseEngine` -- okhttp-sse subscription to `/api/events` (global + per-session),
+ * `connection-changed {resume: ok|gap}` handshake, `Last-Event-ID` resume,
+ * 30s heartbeat / 90s dead-connection detection, 1s->30s backoff with jitter,
+ * gzip streaming decode (fallback `Accept-Encoding: identity`).
+ * - Stores -- `StateFlow`-based session-list / session-detail / message-window
+ * stores applying versioned patches from `:core:protocol`, persisted as
+ * `AtomicFile` JSON snapshots (LRU, no database) for instant cold start.
+ * - `CredentialStore` -- EncryptedSharedPreferences behind an interface
+ * (per-hub accounts, swappable for a Keystore-backed implementation).
+ * - FCM device registration + expedited WorkManager workers that deliver
+ * notification actions (approve/deny/reply) through the authenticated client.
+ *
+ * Wiring is hand-rolled (no Hilt): `:app`'s `AppGraph` constructs these types.
+ */
+object DataModule
diff --git a/android/core/protocol/build.gradle.kts b/android/core/protocol/build.gradle.kts
new file mode 100644
index 00000000..98bd167b
--- /dev/null
+++ b/android/core/protocol/build.gradle.kts
@@ -0,0 +1,35 @@
+import org.jetbrains.kotlin.gradle.dsl.JvmTarget
+
+// Pure Kotlin/JVM module: hub wire types, chat pipeline, pagination/window logic,
+// patch application, BindLink parsing. NO Android dependencies -- tests run in
+// milliseconds on any JVM and validate against shared/fixtures/** golden files.
+plugins {
+ alias(libs.plugins.kotlin.jvm)
+ alias(libs.plugins.kotlin.serialization)
+}
+
+java {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+}
+
+kotlin {
+ compilerOptions {
+ jvmTarget.set(JvmTarget.JVM_17)
+ }
+}
+
+dependencies {
+ api(libs.kotlinx.serialization.json)
+
+ testImplementation(libs.junit)
+ testImplementation(libs.kotlin.test)
+ testImplementation(libs.kotlinx.coroutines.test)
+}
+
+tasks.test {
+ // Golden fixtures live at the repo root (outside the Gradle root dir).
+ // Track K (M2) drops conformance fixtures into shared/fixtures/; protocol
+ // tests read them via this system property -- no build changes needed then.
+ systemProperty("hapi.fixtures.dir", rootDir.parentFile.resolve("shared/fixtures").absolutePath)
+}
diff --git a/android/core/protocol/src/main/kotlin/app/hapi/protocol/pairing/BindLink.kt b/android/core/protocol/src/main/kotlin/app/hapi/protocol/pairing/BindLink.kt
new file mode 100644
index 00000000..dd1c579e
--- /dev/null
+++ b/android/core/protocol/src/main/kotlin/app/hapi/protocol/pairing/BindLink.kt
@@ -0,0 +1,93 @@
+package app.hapi.protocol.pairing
+
+import java.io.UnsupportedEncodingException
+import java.net.URI
+import java.net.URISyntaxException
+import java.net.URLDecoder
+
+/**
+ * Parsed companion pairing deep link.
+ *
+ * The hub prints (and renders as a QR code) a link of the form
+ * `hapicompanion://bind?hub=&code=` -- see `hub/src/startHub.ts`.
+ * The query is built with `URLSearchParams`, i.e. `application/x-www-form-urlencoded`:
+ * `%xx` escapes plus `+` for space. `code` is the raw CLI access token, possibly
+ * suffixed with `:namespace`, so it round-trips percent-encoded (`%3A`).
+ *
+ * Pure JVM on purpose (java.net.URI, no android.net.Uri) so it is unit-testable
+ * in this module; the `:app` deep-link handler converts its Intent data via
+ * `toString()` before calling [parse].
+ */
+data class BindLink(
+ val hubUrl: String,
+ val accessToken: String,
+) {
+ companion object {
+ const val SCHEME: String = "hapicompanion"
+ const val HOST: String = "bind"
+
+ /**
+ * Parses [raw] into a [BindLink].
+ *
+ * Returns null on any malformed input: unparseable URI, wrong scheme or
+ * host, missing/blank `hub` or `code` parameter, invalid percent escapes,
+ * or a `hub` value that is not an http(s) URL.
+ */
+ fun parse(raw: String): BindLink? {
+ val uri = try {
+ URI(raw.trim())
+ } catch (_: URISyntaxException) {
+ return null
+ }
+ if (!SCHEME.equals(uri.scheme, ignoreCase = true)) return null
+ val host = uri.host ?: uri.authority ?: return null
+ if (!HOST.equals(host, ignoreCase = true)) return null
+
+ val params = parseFormQuery(uri.rawQuery ?: return null) ?: return null
+ val hub = params["hub"]?.takeIf { it.isNotBlank() } ?: return null
+ val code = params["code"]?.takeIf { it.isNotBlank() } ?: return null
+ if (!isHttpUrl(hub)) return null
+ return BindLink(hubUrl = hub, accessToken = code)
+ }
+
+ /**
+ * Decodes an `application/x-www-form-urlencoded` query string.
+ * First occurrence wins for duplicate keys. Returns null if any
+ * component carries invalid escapes.
+ */
+ private fun parseFormQuery(rawQuery: String): Map? {
+ val result = LinkedHashMap()
+ for (pair in rawQuery.split('&')) {
+ if (pair.isEmpty()) continue
+ val separator = pair.indexOf('=')
+ val rawKey = if (separator >= 0) pair.substring(0, separator) else pair
+ val rawValue = if (separator >= 0) pair.substring(separator + 1) else ""
+ val key = decodeFormComponent(rawKey) ?: return null
+ val value = decodeFormComponent(rawValue) ?: return null
+ if (key !in result) result[key] = value
+ }
+ return result
+ }
+
+ private fun decodeFormComponent(component: String): String? = try {
+ // String-charset overload: the Charset overload is unavailable on
+ // Android below API 33, and this module also runs inside :app.
+ URLDecoder.decode(component, "UTF-8")
+ } catch (_: IllegalArgumentException) {
+ null
+ } catch (_: UnsupportedEncodingException) {
+ null // unreachable: UTF-8 is always supported
+ }
+
+ private fun isHttpUrl(value: String): Boolean {
+ val uri = try {
+ URI(value)
+ } catch (_: URISyntaxException) {
+ return false
+ }
+ val scheme = uri.scheme?.lowercase() ?: return false
+ if (scheme != "http" && scheme != "https") return false
+ return !(uri.host ?: uri.authority).isNullOrBlank()
+ }
+ }
+}
diff --git a/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/JsonExtensions.kt b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/JsonExtensions.kt
new file mode 100644
index 00000000..98e1e7c7
--- /dev/null
+++ b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/JsonExtensions.kt
@@ -0,0 +1,53 @@
+package app.hapi.protocol.wire
+
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+
+/**
+ * Null-safe, non-throwing accessors over kotlinx.serialization [JsonElement] trees.
+ *
+ * Hub payloads contain loosely-typed regions (e.g. `agentState`, message `content`
+ * envelopes) that are traversed defensively during normalization. These helpers
+ * accept a nullable receiver so lookups chain without intermediate null checks:
+ *
+ * ```
+ * val id = root.objOrNull?.get("session").objOrNull?.get("id").stringOrNull
+ * ```
+ *
+ * Semantics are strict on purpose: a JSON string `"42"` is NOT an int, and a JSON
+ * number is NOT a string (unlike kotlinx's lenient `JsonPrimitive.intOrNull`).
+ * `JsonNull` and absent values both map to `null`.
+ */
+
+/** This element as a [JsonObject], or null. */
+val JsonElement?.objOrNull: JsonObject?
+ get() = this as? JsonObject
+
+/** This element as a [JsonArray], or null. */
+val JsonElement?.arrayOrNull: JsonArray?
+ get() = this as? JsonArray
+
+/** The value of a JSON string, or null (numbers/booleans/null are not strings). */
+val JsonElement?.stringOrNull: String?
+ get() = (this as? JsonPrimitive)?.takeIf { it.isString }?.content
+
+/** The value of a JSON boolean, or null. */
+val JsonElement?.boolOrNull: Boolean?
+ get() = nonStringContent?.toBooleanStrictOrNull()
+
+/** The value of a JSON number representable as [Int], or null. */
+val JsonElement?.intOrNull: Int?
+ get() = nonStringContent?.toIntOrNull()
+
+/** The value of a JSON number representable as [Long], or null. */
+val JsonElement?.longOrNull: Long?
+ get() = nonStringContent?.toLongOrNull()
+
+/** The value of a JSON number, or null. */
+val JsonElement?.doubleOrNull: Double?
+ get() = nonStringContent?.toDoubleOrNull()
+
+private val JsonElement?.nonStringContent: String?
+ get() = (this as? JsonPrimitive)?.takeUnless { it.isString }?.content
diff --git a/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/ProtocolVersion.kt b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/ProtocolVersion.kt
new file mode 100644
index 00000000..c88f5643
--- /dev/null
+++ b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/ProtocolVersion.kt
@@ -0,0 +1,11 @@
+package app.hapi.protocol.wire
+
+/**
+ * Hub protocol schema version this client is built against.
+ *
+ * Bumped only when the hub wire contract (`docs/api/client-contract/`) makes an
+ * incompatible change. Conformance fixtures under `shared/fixtures/` are
+ * generated against a specific version; a mismatch turns the protocol test
+ * suite red before any UI code is touched.
+ */
+const val SUPPORTED_PROTOCOL_VERSION: Int = 1
diff --git a/android/core/protocol/src/test/kotlin/app/hapi/protocol/pairing/BindLinkTest.kt b/android/core/protocol/src/test/kotlin/app/hapi/protocol/pairing/BindLinkTest.kt
new file mode 100644
index 00000000..dcd04316
--- /dev/null
+++ b/android/core/protocol/src/test/kotlin/app/hapi/protocol/pairing/BindLinkTest.kt
@@ -0,0 +1,102 @@
+package app.hapi.protocol.pairing
+
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertNull
+
+class BindLinkTest {
+
+ @Test
+ fun `parses a plain valid link`() {
+ val link = BindLink.parse("hapicompanion://bind?hub=http://192.168.1.20:3006&code=abc123")
+
+ assertEquals(BindLink(hubUrl = "http://192.168.1.20:3006", accessToken = "abc123"), link)
+ }
+
+ @Test
+ fun `parses url-encoded values as the hub emits them`() {
+ // Exactly what `new URLSearchParams({hub, code}).toString()` produces for
+ // hub=https://demo.hapi.run and code=tok_9f8:default (form encoding).
+ val link = BindLink.parse(
+ "hapicompanion://bind?hub=https%3A%2F%2Fdemo.hapi.run&code=tok_9f8%3Adefault"
+ )
+
+ assertEquals("https://demo.hapi.run", link?.hubUrl)
+ assertEquals("tok_9f8:default", link?.accessToken)
+ }
+
+ @Test
+ fun `decodes plus as space in form-encoded values`() {
+ val link = BindLink.parse("hapicompanion://bind?hub=https%3A%2F%2Fh.example.com&code=a+b")
+
+ assertEquals("a b", link?.accessToken)
+ }
+
+ @Test
+ fun `accepts scheme and host case-insensitively`() {
+ val link = BindLink.parse("HAPICOMPANION://BIND?hub=https%3A%2F%2Fh.example.com&code=x")
+
+ assertEquals("https://h.example.com", link?.hubUrl)
+ }
+
+ @Test
+ fun `ignores extra params and keeps first occurrence of duplicates`() {
+ val link = BindLink.parse(
+ "hapicompanion://bind?v=1&hub=https%3A%2F%2Fa.example.com&code=first&code=second"
+ )
+
+ assertEquals("https://a.example.com", link?.hubUrl)
+ assertEquals("first", link?.accessToken)
+ }
+
+ @Test
+ fun `returns null when hub param is missing`() {
+ assertNull(BindLink.parse("hapicompanion://bind?code=abc123"))
+ }
+
+ @Test
+ fun `returns null when code param is missing`() {
+ assertNull(BindLink.parse("hapicompanion://bind?hub=https%3A%2F%2Fh.example.com"))
+ }
+
+ @Test
+ fun `returns null when query is absent`() {
+ assertNull(BindLink.parse("hapicompanion://bind"))
+ }
+
+ @Test
+ fun `returns null when params are blank`() {
+ assertNull(BindLink.parse("hapicompanion://bind?hub=&code=x"))
+ assertNull(BindLink.parse("hapicompanion://bind?hub=https%3A%2F%2Fh.example.com&code="))
+ }
+
+ @Test
+ fun `returns null for a wrong scheme`() {
+ assertNull(BindLink.parse("https://bind?hub=https%3A%2F%2Fh.example.com&code=x"))
+ assertNull(BindLink.parse("hapicompanionx://bind?hub=https%3A%2F%2Fh.example.com&code=x"))
+ }
+
+ @Test
+ fun `returns null for a wrong host`() {
+ assertNull(BindLink.parse("hapicompanion://pair?hub=https%3A%2F%2Fh.example.com&code=x"))
+ }
+
+ @Test
+ fun `returns null when hub is not an http url`() {
+ assertNull(BindLink.parse("hapicompanion://bind?hub=ftp%3A%2F%2Fh.example.com&code=x"))
+ assertNull(BindLink.parse("hapicompanion://bind?hub=not-a-url&code=x"))
+ }
+
+ @Test
+ fun `returns null for malformed input`() {
+ assertNull(BindLink.parse(""))
+ assertNull(BindLink.parse(" "))
+ assertNull(BindLink.parse("not a uri at all"))
+ assertNull(BindLink.parse("hapicompanion:bind?hub=https%3A%2F%2Fh.example.com&code=x"))
+ }
+
+ @Test
+ fun `returns null on invalid percent escapes`() {
+ assertNull(BindLink.parse("hapicompanion://bind?hub=https%3A%2F%2Fh.example.com&code=%zz"))
+ }
+}
diff --git a/android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/JsonExtensionsTest.kt b/android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/JsonExtensionsTest.kt
new file mode 100644
index 00000000..3a7329db
--- /dev/null
+++ b/android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/JsonExtensionsTest.kt
@@ -0,0 +1,113 @@
+package app.hapi.protocol.wire
+
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonElement
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+
+class JsonExtensionsTest {
+
+ private val root: JsonElement = Json.parseToJsonElement(
+ """
+ {
+ "session": {
+ "id": "sess_1",
+ "seq": 42,
+ "active": true,
+ "updatedAt": 1755400000000,
+ "temperature": 0.5,
+ "title": null,
+ "tags": ["alpha", "beta"]
+ },
+ "count": "42"
+ }
+ """
+ )
+
+ private val session: JsonElement? get() = root.objOrNull?.get("session")
+
+ @Test
+ fun `objOrNull distinguishes objects from other kinds`() {
+ assertTrue(root.objOrNull != null)
+ assertNull(session.objOrNull?.get("tags").objOrNull)
+ assertNull(session.objOrNull?.get("id").objOrNull)
+ assertNull((null as JsonElement?).objOrNull)
+ }
+
+ @Test
+ fun `arrayOrNull distinguishes arrays from other kinds`() {
+ val tags = session.objOrNull?.get("tags").arrayOrNull
+ assertEquals(2, tags?.size)
+ assertEquals("alpha", tags?.get(0).stringOrNull)
+ assertNull(root.arrayOrNull)
+ assertNull(session.objOrNull?.get("id").arrayOrNull)
+ }
+
+ @Test
+ fun `stringOrNull only matches real json strings`() {
+ assertEquals("sess_1", session.objOrNull?.get("id").stringOrNull)
+ assertEquals("42", root.objOrNull?.get("count").stringOrNull)
+ // Numbers, booleans, nulls and containers are not strings.
+ assertNull(session.objOrNull?.get("seq").stringOrNull)
+ assertNull(session.objOrNull?.get("active").stringOrNull)
+ assertNull(session.objOrNull?.get("title").stringOrNull)
+ assertNull(session.stringOrNull)
+ }
+
+ @Test
+ fun `intOrNull is strict about type and range`() {
+ assertEquals(42, session.objOrNull?.get("seq").intOrNull)
+ // A json string "42" is not an int.
+ assertNull(root.objOrNull?.get("count").intOrNull)
+ // Out of Int range.
+ assertNull(session.objOrNull?.get("updatedAt").intOrNull)
+ // Non-integral number.
+ assertNull(session.objOrNull?.get("temperature").intOrNull)
+ }
+
+ @Test
+ fun `longOrNull covers 64-bit timestamps`() {
+ assertEquals(1_755_400_000_000L, session.objOrNull?.get("updatedAt").longOrNull)
+ assertEquals(42L, session.objOrNull?.get("seq").longOrNull)
+ assertNull(root.objOrNull?.get("count").longOrNull)
+ }
+
+ @Test
+ fun `doubleOrNull reads json numbers`() {
+ assertEquals(0.5, session.objOrNull?.get("temperature").doubleOrNull)
+ assertEquals(42.0, session.objOrNull?.get("seq").doubleOrNull)
+ assertNull(root.objOrNull?.get("count").doubleOrNull)
+ assertNull(session.objOrNull?.get("active").doubleOrNull)
+ }
+
+ @Test
+ fun `boolOrNull only matches real json booleans`() {
+ assertEquals(true, session.objOrNull?.get("active").boolOrNull)
+ assertNull(session.objOrNull?.get("seq").boolOrNull)
+ assertNull(root.objOrNull?.get("count").boolOrNull)
+ assertNull(session.objOrNull?.get("title").boolOrNull)
+ }
+
+ @Test
+ fun `json null and absent keys read as null everywhere`() {
+ val title = session.objOrNull?.get("title")
+ assertNull(title.stringOrNull)
+ assertNull(title.objOrNull)
+ assertNull(title.arrayOrNull)
+ assertNull(title.intOrNull)
+ assertNull(title.boolOrNull)
+
+ val missing = session.objOrNull?.get("nope")
+ assertNull(missing.stringOrNull)
+ assertNull(missing.objOrNull)
+ assertNull(missing.intOrNull)
+ }
+
+ @Test
+ fun `accessors chain without intermediate null checks`() {
+ assertEquals("sess_1", root.objOrNull?.get("session").objOrNull?.get("id").stringOrNull)
+ assertNull(root.objOrNull?.get("ghost").objOrNull?.get("id").stringOrNull)
+ }
+}
diff --git a/android/gradle.properties b/android/gradle.properties
new file mode 100644
index 00000000..1b3e9c4b
--- /dev/null
+++ b/android/gradle.properties
@@ -0,0 +1,12 @@
+# Gradle
+org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=1g -Dfile.encoding=UTF-8
+org.gradle.configuration-cache=true
+org.gradle.caching=true
+org.gradle.parallel=true
+
+# AndroidX
+android.useAndroidX=true
+android.nonTransitiveRClass=true
+
+# Kotlin
+kotlin.code.style=official
diff --git a/android/gradle/libs.versions.toml b/android/gradle/libs.versions.toml
new file mode 100644
index 00000000..b814e806
--- /dev/null
+++ b/android/gradle/libs.versions.toml
@@ -0,0 +1,42 @@
+# Version catalog for hapi-android.
+# All versions verified to exist on Google Maven / Maven Central at scaffold time.
+# Keep conservative: bump deliberately, one PR at a time.
+
+[versions]
+agp = "8.11.1"
+kotlin = "2.1.21"
+composeBom = "2025.05.00"
+activityCompose = "1.10.1"
+coreKtx = "1.16.0"
+kotlinxSerialization = "1.8.1"
+kotlinxCoroutines = "1.10.2"
+junit = "4.13.2"
+
+[libraries]
+# AndroidX
+androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
+androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
+
+# Compose (versions come from the BOM)
+androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
+androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" }
+androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
+androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
+androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" }
+
+# KotlinX
+kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinxSerialization" }
+kotlinx-coroutines-core = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-core", version.ref = "kotlinxCoroutines" }
+kotlinx-coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version.ref = "kotlinxCoroutines" }
+
+# Testing
+junit = { group = "junit", name = "junit", version.ref = "junit" }
+kotlin-test = { group = "org.jetbrains.kotlin", name = "kotlin-test", version.ref = "kotlin" }
+
+[plugins]
+android-application = { id = "com.android.application", version.ref = "agp" }
+android-library = { id = "com.android.library", version.ref = "agp" }
+kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
+kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" }
+kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
+kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 00000000..1b33c55b
Binary files /dev/null and b/android/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 00000000..3735f265
--- /dev/null
+++ b/android/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,8 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionSha256Sum=7197a12f450794931532469d4ff21a59ea2c1cd59a3ec3f89c035c3c420a6999
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.2-bin.zip
+networkTimeout=10000
+validateDistributionUrl=true
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/android/gradlew b/android/gradlew
new file mode 100755
index 00000000..0f14772e
--- /dev/null
+++ b/android/gradlew
@@ -0,0 +1,251 @@
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+
+##############################################################################
+#
+# Gradle start up script for POSIX generated by Gradle.
+#
+# Important for running:
+#
+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+# noncompliant, but you have some other compliant shell such as ksh or
+# bash, then to run this script, type that shell name before the whole
+# command line, like:
+#
+# ksh Gradle
+#
+# Busybox and similar reduced shells will NOT work, because this script
+# requires all of these POSIX shell features:
+# * functions;
+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+# * compound commands having a testable exit status, especially «case»;
+# * various built-in commands including «command», «set», and «ulimit».
+#
+# Important for patching:
+#
+# (2) This script targets any POSIX shell, so it avoids extensions provided
+# by Bash, Ksh, etc; in particular arrays are avoided.
+#
+# The "traditional" practice of packing multiple parameters into a
+# space-separated string is a well documented source of bugs and security
+# problems, so this is (mostly) avoided, by progressively accumulating
+# options in "$@", and eventually passing that to Java.
+#
+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+# see the in-line comments for details.
+#
+# There are tweaks for specific operating systems such as AIX, CygWin,
+# Darwin, MinGW, and NonStop.
+#
+# (3) This script is generated from the Groovy template
+# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# within the Gradle project.
+#
+# You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
+ [ -h "$app_path" ]
+do
+ ls=$( ls -ld "$app_path" )
+ link=${ls#*' -> '}
+ case $link in #(
+ /*) app_path=$link ;; #(
+ *) app_path=$APP_HOME$link ;;
+ esac
+done
+
+# This is normally unused
+# shellcheck disable=SC2034
+APP_BASE_NAME=${0##*/}
+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+ echo "$*"
+} >&2
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in #(
+ CYGWIN* ) cygwin=true ;; #(
+ Darwin* ) darwin=true ;; #(
+ MSYS* | MINGW* ) msys=true ;; #(
+ NONSTOP* ) nonstop=true ;;
+esac
+
+CLASSPATH="\\\"\\\""
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD=$JAVA_HOME/jre/sh/java
+ else
+ JAVACMD=$JAVA_HOME/bin/java
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD=java
+ if ! command -v java >/dev/null 2>&1
+ then
+ die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ ulimit -n "$MAX_FD" ||
+ warn "Could not set maximum file descriptor limit to $MAX_FD"
+ esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+# * args from the command line
+# * the main class name
+# * -classpath
+# * -D...appname settings
+# * --module-path (only if needed)
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+ JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ for arg do
+ if
+ case $arg in #(
+ -*) false ;; # don't mess with options #(
+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
+ [ -e "$t" ] ;; #(
+ *) false ;;
+ esac
+ then
+ arg=$( cygpath --path --ignore --mixed "$arg" )
+ fi
+ # Roll the args list around exactly as many times as the number of
+ # args, so each arg winds up back in the position where it started, but
+ # possibly modified.
+ #
+ # NB: a `for` loop captures its iteration list before it begins, so
+ # changing the positional parameters here affects neither the number of
+ # iterations, nor the values presented in `arg`.
+ shift # remove old arg
+ set -- "$@" "$arg" # push replacement arg
+ done
+fi
+
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"'
+
+# Collect all arguments for the java command:
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
+# and any embedded shellness will be escaped.
+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
+# treated as '${Hostname}' itself on the command line.
+
+set -- \
+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
+ -classpath "$CLASSPATH" \
+ -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
+ "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+ die "xargs is not available"
+fi
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+# set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+ xargs -n1 |
+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+ tr '\n' ' '
+ )" '"$@"'
+
+exec "$JAVACMD" "$@"
diff --git a/android/gradlew.bat b/android/gradlew.bat
new file mode 100644
index 00000000..8de1053a
--- /dev/null
+++ b/android/gradlew.bat
@@ -0,0 +1,94 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+@rem SPDX-License-Identifier: Apache-2.0
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+@rem This is normally unused
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if %ERRORLEVEL% equ 0 goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts
new file mode 100644
index 00000000..52cddb3f
--- /dev/null
+++ b/android/settings.gradle.kts
@@ -0,0 +1,27 @@
+pluginManagement {
+ repositories {
+ google {
+ content {
+ includeGroupByRegex("com\\.android.*")
+ includeGroupByRegex("com\\.google.*")
+ includeGroupByRegex("androidx.*")
+ }
+ }
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+
+dependencyResolutionManagement {
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+
+rootProject.name = "hapi-android"
+
+include(":app")
+include(":core:protocol")
+include(":core:data")