feat: ClaudeMeter — Wear OS rate-limit tracker for Claude Code

- wear: Compose for Wear UI, polls api.anthropic.com, shows 5h/7d utilization
- mobile: companion app — token input + Data Layer API + WiFi ADB install
- ADB pairing via libadb-android (SPAKE2 + TLS), pm install on watch
- Build: AGP 8.7.3, Gradle 8.13, Kotlin 1.9.22, compileSdk 35
This commit is contained in:
wenil
2026-06-19 11:43:24 +03:00
commit 4083609b12
19 changed files with 1301 additions and 0 deletions
+68
View File
@@ -0,0 +1,68 @@
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "com.eps.claudemeter"
compileSdk = 35
defaultConfig {
applicationId = "com.eps.claudemeter"
minSdk = 26
targetSdk = 35
versionCode = 1
versionName = "0.1"
}
buildFeatures { compose = true }
composeOptions { kotlinCompilerExtensionVersion = "1.5.8" }
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions { jvmTarget = "17" }
packaging {
resources {
excludes += setOf(
"META-INF/DEPENDENCIES", "META-INF/LICENSE", "META-INF/LICENSE.txt",
"META-INF/NOTICE", "META-INF/NOTICE.txt",
"META-INF/*.SF", "META-INF/*.DSA", "META-INF/*.RSA",
)
}
}
}
dependencies {
implementation("androidx.core:core-ktx:1.12.0")
implementation("androidx.activity:activity-compose:1.8.2")
implementation(platform("androidx.compose:compose-bom:2024.02.00"))
implementation("androidx.compose.ui:ui")
implementation("androidx.compose.material3:material3")
implementation("androidx.compose.material:material-icons-extended")
// Coroutines
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")
// Wearable Data Layer — передача токена на часы
implementation("com.google.android.gms:play-services-wearable:18.1.0")
// libadb-android — full ADB protocol: SPAKE2 pairing + TLS connection + streams
implementation("com.github.MuntashirAkon:libadb-android:3.1.1")
// sun-security-android — exposes android.sun.security.x509.* at compile time
implementation("com.github.MuntashirAkon:sun-security-android:1.1")
// hiddenapibypass — access hidden Android APIs at runtime
implementation("org.lsposed.hiddenapibypass:hiddenapibypass:6.1")
// Conscrypt — TLS 1.3 provider, required for ADB pairing
implementation("org.conscrypt:conscrypt-android:2.5.2")
}
// ponytail: копируем wear APK в assets mobile перед сборкой
tasks.register<Copy>("copyWearApk") {
from(project(":wear").layout.buildDirectory.file("outputs/apk/debug/wear-debug.apk"))
into(layout.projectDirectory.dir("src/main/assets"))
rename { "wear.apk" }
dependsOn(":wear:assembleDebug")
}
tasks.named("preBuild") { dependsOn("copyWearApk") }
+22
View File
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".App"
android:label="Claude Meter Setup"
android:theme="@android:style/Theme.DeviceDefault.Light"
android:supportsRtl="true">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -0,0 +1,112 @@
package com.eps.claudemeter
import android.content.Context
import android.os.Build
import android.sun.misc.BASE64Encoder
import android.sun.security.provider.X509Factory
import android.sun.security.x509.*
import io.github.muntashirakon.adb.AbsAdbConnectionManager
import java.io.*
import java.nio.charset.StandardCharsets
import java.security.*
import java.security.cert.Certificate
import java.security.cert.CertificateException
import java.security.cert.CertificateFactory
import java.security.spec.PKCS8EncodedKeySpec
import java.util.*
// ponytail: один менеджер, ключи генерируются один раз и хранятся в filesDir.
// X.509 сертификат через android.sun.security.x509 — так делает официальный пример libadb-android.
class AdbConnectionManager private constructor(context: Context) : AbsAdbConnectionManager() {
private val mPrivateKey: PrivateKey
private val mCertificate: Certificate
init {
setApi(Build.VERSION.SDK_INT)
val priv = readPrivateKey(context)
val cert = readCertificate(context)
if (priv != null && cert != null) {
mPrivateKey = priv
mCertificate = cert
} else {
// генерация новой пары ключей
val kpg = KeyPairGenerator.getInstance("RSA")
kpg.initialize(2048, SecureRandom.getInstance("SHA1PRNG"))
val keyPair = kpg.generateKeyPair()
mPrivateKey = keyPair.private
val subject = "CN=ClaudeMeter"
val algo = "SHA512withRSA"
val notAfter = Date(System.currentTimeMillis() + 86400000L)
val extensions = CertificateExtensions()
extensions.set("SubjectKeyIdentifier",
SubjectKeyIdentifierExtension(KeyIdentifier(keyPair.public).identifier))
extensions.set("PrivateKeyUsage", PrivateKeyUsageExtension(Date(), notAfter))
val x500 = X500Name(subject)
val info = X509CertInfo()
info.set("version", CertificateVersion(2))
info.set("serialNumber", CertificateSerialNumber(Random().nextInt() and Int.MAX_VALUE))
info.set("algorithmID", CertificateAlgorithmId(AlgorithmId.get(algo)))
info.set("subject", CertificateSubjectName(x500))
info.set("key", CertificateX509Key(keyPair.public))
info.set("validity", CertificateValidity(Date(), notAfter))
info.set("issuer", CertificateIssuerName(x500))
info.set("extensions", extensions)
val certImpl = X509CertImpl(info)
certImpl.sign(mPrivateKey, algo)
mCertificate = certImpl
writePrivateKey(context, mPrivateKey)
writeCertificate(context, mCertificate)
}
}
override fun getPrivateKey(): PrivateKey = mPrivateKey
override fun getCertificate(): Certificate = mCertificate
override fun getDeviceName(): String = "ClaudeMeter"
companion object {
@Volatile private var instance: AdbConnectionManager? = null
fun get(context: Context): AdbConnectionManager =
instance ?: synchronized(this) {
instance ?: AdbConnectionManager(context.applicationContext).also { instance = it }
}
private fun readPrivateKey(ctx: Context): PrivateKey? {
val f = File(ctx.filesDir, "private.key")
if (!f.exists()) return null
val bytes = f.readBytes()
return KeyFactory.getInstance("RSA").generatePrivate(PKCS8EncodedKeySpec(bytes))
}
private fun writePrivateKey(ctx: Context, key: PrivateKey) {
File(ctx.filesDir, "private.key").writeBytes(key.encoded)
}
private fun readCertificate(ctx: Context): Certificate? {
val f = File(ctx.filesDir, "cert.pem")
if (!f.exists()) return null
FileInputStream(f).use { inp ->
return CertificateFactory.getInstance("X.509").generateCertificate(inp)
}
}
private fun writeCertificate(ctx: Context, cert: Certificate) {
val f = File(ctx.filesDir, "cert.pem")
FileOutputStream(f).use { out ->
out.write(X509Factory.BEGIN_CERT.toByteArray(StandardCharsets.UTF_8))
out.write('\n'.code)
BASE64Encoder().encode(cert.encoded, out)
out.write('\n'.code)
out.write(X509Factory.END_CERT.toByteArray(StandardCharsets.UTF_8))
}
}
}
}
@@ -0,0 +1,26 @@
package com.eps.claudemeter
import android.app.Application
import android.content.Context
import android.os.Build
import org.conscrypt.Conscrypt
import org.lsposed.hiddenapibypass.HiddenApiBypass
import java.security.Security
import io.github.muntashirakon.adb.PRNGFixes
// ponytail: HiddenApiBypass в attachBaseContext (первое что выполняется),
// Conscrypt + PRNGFixes в onCreate. Без этого pairing не работает.
class App : Application() {
override fun onCreate() {
super.onCreate()
PRNGFixes.apply()
Security.insertProviderAt(Conscrypt.newProvider(), 1)
}
override fun attachBaseContext(base: Context) {
super.attachBaseContext(base)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
HiddenApiBypass.addHiddenApiExemptions("L")
}
}
}
@@ -0,0 +1,292 @@
package com.eps.claudemeter
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Send
import androidx.compose.material.icons.filled.Bluetooth
import androidx.compose.material.icons.filled.Download
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.ui.unit.dp
import com.google.android.gms.wearable.PutDataMapRequest
import com.google.android.gms.wearable.Wearable
import io.github.muntashirakon.adb.AdbStream
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
// ponytail: один экран, три секции: токен → спаривание → установка APK.
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MaterialTheme {
Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
SetupScreen()
}
}
}
}
}
@Composable
private fun SetupScreen() {
val ctx = LocalContext.current
val scope = rememberCoroutineScope()
// --- токен ---
var token by remember { mutableStateOf("") }
var tokenStatus by remember { mutableStateOf<String?>(null) }
var sendingToken by remember { mutableStateOf(false) }
// --- спаривание ---
var watchIp by remember { mutableStateOf("") }
var pairPort by remember { mutableStateOf("") }
var pairCode by remember { mutableStateOf("") }
var pairStatus by remember { mutableStateOf<String?>(null) }
var pairing by remember { mutableStateOf(false) }
// --- установка ---
var sessionPort by remember { mutableStateOf("") }
var installStatus by remember { mutableStateOf<String?>(null) }
var installing by remember { mutableStateOf(false) }
Column(
Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(24.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
Text("Claude Meter", style = MaterialTheme.typography.headlineMedium)
// === секция 1: токен ===
HorizontalDivider()
Text("1. Токен Claude Code", style = MaterialTheme.typography.titleMedium)
Text(
"Вставь accessToken из ~/.claude/.credentials.json",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
OutlinedTextField(
value = token,
onValueChange = { token = it },
label = { Text("OAuth токен") },
modifier = Modifier.fillMaxWidth(),
minLines = 2
)
Button(
onClick = {
sendingToken = true; tokenStatus = null
val req = PutDataMapRequest.create("/token").apply {
dataMap.putString("token", token.trim())
dataMap.putLong("ts", System.currentTimeMillis())
}.asPutDataRequest().setUrgent()
Wearable.getDataClient(ctx)
.putDataItem(req)
.addOnSuccessListener { tokenStatus = "Отправлено на часы"; sendingToken = false }
.addOnFailureListener { e -> tokenStatus = "Ошибка: ${e.message}"; sendingToken = false }
},
enabled = token.isNotBlank() && !sendingToken,
modifier = Modifier.fillMaxWidth()
) {
Icon(Icons.AutoMirrored.Filled.Send, contentDescription = null)
Spacer(Modifier.width(8.dp))
Text("Отправить токен")
}
tokenStatus?.let { Text(it, color = MaterialTheme.colorScheme.primary) }
// === секция 2: спаривание ===
Spacer(Modifier.height(8.dp))
HorizontalDivider()
Text("2. Спаривание с часами", style = MaterialTheme.typography.titleMedium)
Text(
"На часах: Settings → Developer options → Wireless debugging →\n" +
"«Pair device with pairing code». Введи порт и код с экрана часов.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
OutlinedTextField(
value = watchIp,
onValueChange = { watchIp = it },
label = { Text("IP часов") },
modifier = Modifier.fillMaxWidth(),
singleLine = true,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Next
)
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
OutlinedTextField(
value = pairPort,
onValueChange = { pairPort = it.filter { c -> c.isDigit() } },
label = { Text("Pairing порт") },
modifier = Modifier.weight(1f),
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
OutlinedTextField(
value = pairCode,
onValueChange = { pairCode = it.filter { c -> c.isDigit() }.take(6) },
label = { Text("Код (6 цифр)") },
modifier = Modifier.weight(1f),
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
}
Button(
onClick = {
scope.launch {
pairing = true; pairStatus = null
try {
withContext(Dispatchers.IO) {
val mgr = AdbConnectionManager.get(ctx)
mgr.setHostAddress(watchIp.trim())
val ok = mgr.pair(watchIp.trim(), pairPort.trim().toInt(), pairCode.trim())
if (!ok) throw Exception("Pairing failed")
}
pairStatus = "✅ Спарено! Теперь введи session порт (Шаг 3)"
} catch (e: Exception) {
pairStatus = "${e.message ?: e.javaClass.simpleName}"
}
pairing = false
}
},
enabled = watchIp.isNotBlank() && pairPort.isNotBlank() && pairCode.length == 6 && !pairing,
modifier = Modifier.fillMaxWidth()
) {
Icon(Icons.Default.Bluetooth, contentDescription = null)
Spacer(Modifier.width(8.dp))
Text(if (pairing) "Спаривание..." else "Спарить")
}
pairStatus?.let {
Text(
it,
style = MaterialTheme.typography.bodyMedium,
color = if (it.startsWith("")) MaterialTheme.colorScheme.primary
else if (it.startsWith("")) MaterialTheme.colorScheme.error
else MaterialTheme.colorScheme.onSurfaceVariant
)
}
// === секция 3: установка APK ===
Spacer(Modifier.height(8.dp))
HorizontalDivider()
Text("3. Установка приложения на часы", style = MaterialTheme.typography.titleMedium)
Text(
"Session порт показан на главном экране Wireless debugging (не pairing порт!).",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
OutlinedTextField(
value = sessionPort,
onValueChange = { sessionPort = it.filter { c -> c.isDigit() } },
label = { Text("Session порт") },
modifier = Modifier.fillMaxWidth(),
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
Button(
onClick = {
scope.launch {
installing = true; installStatus = null
try {
installStatus = "Копирую APK из assets..."
val apkFile = File(ctx.cacheDir, "wear.apk")
withContext(Dispatchers.IO) {
ctx.assets.open("wear.apk").use { inp ->
apkFile.outputStream().use { inp.copyTo(it) }
}
}
installStatus = "Подключаюсь к ${watchIp}:${sessionPort}..."
withContext(Dispatchers.IO) {
val mgr = AdbConnectionManager.get(ctx)
mgr.setHostAddress(watchIp.trim())
val connected = mgr.connect(watchIp.trim(), sessionPort.trim().toInt())
if (!connected) throw Exception("Не удалось подключиться. Спарены?")
// 1. push APK через shell:cat
installStatus = "Загружаю APK на часы..."
pushFile(mgr, apkFile, "/data/local/tmp/wear.apk")
// 2. pm install
installStatus = "Устанавливаю..."
val output = execShell(mgr, "pm install -r /data/local/tmp/wear.apk 2>&1; echo END")
if (!output.contains("Success")) {
throw Exception("Install failed: $output")
}
mgr.disconnect()
}
installStatus = "✅ Установлено на часы!"
} catch (e: Exception) {
installStatus = "${e.message ?: e.javaClass.simpleName}"
try { AdbConnectionManager.get(ctx).disconnect() } catch (_: Exception) {}
}
installing = false
}
},
enabled = watchIp.isNotBlank() && sessionPort.isNotBlank() && !installing,
modifier = Modifier.fillMaxWidth()
) {
Icon(Icons.Default.Download, contentDescription = null)
Spacer(Modifier.width(8.dp))
Text(if (installing) "Установка..." else "Установить на часы")
}
installStatus?.let {
Text(
it,
style = MaterialTheme.typography.bodyMedium,
color = if (it.startsWith("")) MaterialTheme.colorScheme.primary
else if (it.startsWith("")) MaterialTheme.colorScheme.error
else MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
// ponytail: push файла через shell:cat > path, потом закрытие потока = EOF для cat.
private fun pushFile(mgr: AdbConnectionManager, file: File, remotePath: String) {
val stream: AdbStream = mgr.openStream("shell:cat > $remotePath")
val out = stream.openOutputStream()
file.inputStream().use { inp ->
val buf = ByteArray(65536)
while (true) {
val n = inp.read(buf)
if (n < 0) break
out.write(buf, 0, n)
}
}
out.flush()
out.close()
stream.close()
}
// ponytail: shell команда с sentinel, чтобы получить полный вывод.
private fun execShell(mgr: AdbConnectionManager, command: String): String {
val stream: AdbStream = mgr.openStream("shell:$command")
val sb = StringBuilder()
val inp = stream.openInputStream()
val buf = ByteArray(4096)
while (true) {
val n = inp.read(buf)
if (n < 0) break
sb.append(String(buf, 0, n, Charsets.UTF_8))
if (sb.contains("END")) break
}
stream.close()
return sb.toString().replace("END", "").trim()
}