Skip to content

Agent Mesh

feat(mobile): integrate Android 16 AppFunctions and Foreground Service

Antonio Ojeae11f8c4c3870
diff --git a/mobile/sam-node-app/android/app/build.gradle.kts b/mobile/sam-node-app/android/app/build.gradle.kts
index e079f03d..abd9eeb9 100644
--- a/mobile/sam-node-app/android/app/build.gradle.kts
+++ b/mobile/sam-node-app/android/app/build.gradle.kts
@@ -2,11 +2,13 @@ plugins {
id("com.android.application")
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
id("dev.flutter.flutter-gradle-plugin")
+ id("com.google.gms.google-services")
+ id("com.google.devtools.ksp")
}
android {
namespace = "com.example.sam_agent"
- compileSdk = flutter.compileSdkVersion
+ compileSdk = 37 // Keep as 37, Gradle usually maps this correctly, but let's check if it needs to be 37
ndkVersion = flutter.ndkVersion
compileOptions {
@@ -43,3 +45,18 @@ kotlin {
flutter {
source = "../.."
}
+
+ksp {
+ arg("appfunctions:aggregateAppFunctions", "true")
+}
+
+dependencies {
+ val appFunctionsVersion = "1.0.0-alpha09" // alpha10 seems missing or restricted
+
+ implementation("androidx.appfunctions:appfunctions:$appFunctionsVersion")
+ implementation("androidx.appfunctions:appfunctions-service:$appFunctionsVersion")
+ ksp("androidx.appfunctions:appfunctions-compiler:$appFunctionsVersion")
+
+ // JNA for calling Go C exports
+ implementation("net.java.dev.jna:jna:5.14.0@aar")
+}
diff --git a/mobile/sam-node-app/android/app/src/main/AndroidManifest.xml b/mobile/sam-node-app/android/app/src/main/AndroidManifest.xml
index f0f15198..b38c0f47 100644
--- a/mobile/sam-node-app/android/app/src/main/AndroidManifest.xml
+++ b/mobile/sam-node-app/android/app/src/main/AndroidManifest.xml
@@ -1,8 +1,18 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET"/>
+ <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
+ <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
+ <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE"/>
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION"/>
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
+ <uses-permission android:name="android.permission.WAKE_LOCK"/>
+ <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
+ <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<application
android:label="sam_agent"
- android:name="${applicationName}"
+ android:name=".SamApplication"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
@@ -31,6 +41,18 @@
<meta-data
android:name="flutterEmbedding"
android:value="2" />
+ <property
+ android:name="android.app.appfunctions.app_metadata"
+ android:resource="@xml/app_metadata" />
+ <property
+ android:name="android.app.appfunctions.app_function_schema_version"
+ android:value="1" />
+ <!-- Foreground Service for keeping SAM Node alive -->
+ <service
+ android:name=".SamNodeForegroundService"
+ android:foregroundServiceType="connectedDevice|location"
+ android:exported="false" />
+
</application>
<!-- Required to query activities that can process text, see:
https://developer.android.com/training/package-visibility and
diff --git a/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/MainActivity.kt b/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/MainActivity.kt
index 1c867092..ffa6fc93 100644
--- a/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/MainActivity.kt
+++ b/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/MainActivity.kt
@@ -1,5 +1,95 @@
package com.example.sam_agent
import io.flutter.embedding.android.FlutterActivity
+import io.flutter.embedding.engine.FlutterEngine
+import io.flutter.plugin.common.MethodChannel
+import android.util.Log
+import android.content.Context
-class MainActivity : FlutterActivity()
+class MainActivity : FlutterActivity() {
+ private val CHANNEL = "com.example.sam_agent/mesh_expose"
+
+ override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
+ super.configureFlutterEngine(flutterEngine)
+
+ MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
+ when (call.method) {
+ "startBackgroundService" -> {
+ try {
+ val intent = android.content.Intent(this, SamNodeForegroundService::class.java)
+ if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
+ startForegroundService(intent)
+ } else {
+ startService(intent)
+ }
+ result.success(true)
+ } catch (e: Exception) {
+ result.error("SERVICE_START_ERROR", "Failed to start background service: ${e.message}", null)
+ }
+ }
+ "stopBackgroundService" -> {
+ try {
+ val intent = android.content.Intent(this, SamNodeForegroundService::class.java)
+ stopService(intent)
+ result.success(true)
+ } catch (e: Exception) {
+ result.error("SERVICE_STOP_ERROR", "Failed to stop background service: ${e.message}", null)
+ }
+ }
+ "setExposeBattery" -> {
+ val enabled = call.argument<Boolean>("enabled") ?: false
+ Log.d("SAM_NODE", "setExposeBattery: $enabled")
+ // TODO: Start/Stop Battery service and register with SAM
+ result.success(true)
+ }
+ "setExposeLocation" -> {
+ val enabled = call.argument<Boolean>("enabled") ?: false
+ Log.d("SAM_NODE", "setExposeLocation: $enabled")
+ if (enabled) {
+ if (androidx.core.content.ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
+ androidx.core.app.ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION), 1001)
+ }
+ }
+ result.success(true)
+ }
+ "getBatteryData" -> {
+ try {
+ val batteryManager = getSystemService(Context.BATTERY_SERVICE) as android.os.BatteryManager
+ val batteryLevel = batteryManager.getIntProperty(android.os.BatteryManager.BATTERY_PROPERTY_CAPACITY)
+
+ val intent = registerReceiver(null, android.content.IntentFilter(android.content.Intent.ACTION_BATTERY_CHANGED))
+ val status = intent?.getIntExtra(android.os.BatteryManager.EXTRA_STATUS, -1) ?: -1
+ val isCharging = status == android.os.BatteryManager.BATTERY_STATUS_CHARGING || status == android.os.BatteryManager.BATTERY_STATUS_FULL
+
+ result.success("{\"battery_level\": $batteryLevel, \"charging\": $isCharging}")
+ } catch (e: Exception) {
+ result.error("BATTERY_ERROR", "Failed to get battery data: ${e.message}", null)
+ }
+ }
+ "getLocationData" -> {
+ try {
+ if (androidx.core.content.ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
+ result.success("{\"error\": \"Location permission not granted\"}")
+ return@setMethodCallHandler
+ }
+
+ val locationManager = getSystemService(Context.LOCATION_SERVICE) as android.location.LocationManager
+ val location: android.location.Location? = locationManager.getLastKnownLocation(android.location.LocationManager.GPS_PROVIDER)
+ ?: locationManager.getLastKnownLocation(android.location.LocationManager.NETWORK_PROVIDER)
+
+ if (location != null) {
+ result.success("{\"latitude\": ${location.latitude}, \"longitude\": ${location.longitude}}")
+ } else {
+ result.success("{\"error\": \"No location available\"}")
+ }
+ } catch (e: Exception) {
+ result.error("LOCATION_ERROR", "Failed to get location data: ${e.message}", null)
+ }
+ }
+ else -> {
+ result.notImplemented()
+ }
+ }
+ }
+ }
+}
diff --git a/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamApplication.kt b/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamApplication.kt
new file mode 100644
index 00000000..d48865b3
--- /dev/null
+++ b/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamApplication.kt
@@ -0,0 +1,15 @@
+package com.example.sam_agent
+
+import io.flutter.app.FlutterApplication
+import androidx.appfunctions.service.AppFunctionConfiguration
+
+class SamApplication : FlutterApplication(), AppFunctionConfiguration.Provider {
+
+ // Instantiate SamFunctions lazily or eagerly
+ private val samFunctions by lazy { SamFunctions() }
+
+ override val appFunctionConfiguration: AppFunctionConfiguration
+ get() = AppFunctionConfiguration.Builder()
+ .addEnclosingClassFactory(SamFunctions::class.java) { samFunctions }
+ .build()
+}
diff --git a/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamFunctions.kt b/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamFunctions.kt
new file mode 100644
index 00000000..94c5339a
--- /dev/null
+++ b/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamFunctions.kt
@@ -0,0 +1,64 @@
+package com.example.sam_agent
+
+import androidx.appfunctions.service.AppFunction
+import androidx.appfunctions.AppFunctionContext
+import com.sun.jna.Library
+import com.sun.jna.Native
+import com.sun.jna.Pointer
+
+// JNA Interface for libsam.so
+interface SamLib : Library {
+ fun GetMeshInfo(): Pointer?
+ fun CallRemoteTool(peerId: String, toolName: String, argsJson: String): Pointer?
+ fun FreeString(ptr: Pointer)
+}
+
+class SamFunctions {
+
+ // Load the library lazily
+ private val samLib: SamLib by lazy {
+ Native.load("sam", SamLib::class.java) as SamLib
+ }
+
+ /**
+ * Retrieves the current status and statistics of the SAM mesh node.
+ * Returns a JSON string containing connected_peers, dht_size, and node_id.
+ */
+ @AppFunction(isDescribedByKDoc = true)
+ suspend fun getMeshStatus(context: AppFunctionContext): String {
+ return try {
+ val ptr = samLib.GetMeshInfo()
+ if (ptr != null) {
+ val json = ptr.getString(0)
+ samLib.FreeString(ptr)
+ json ?: "{\"error\": \"null response\"}"
+ } else {
+ "{\"error\": \"failed to call GetMeshInfo\"}"
+ }
+ } catch (e: Exception) {
+ "{\"error\": \"${e.message}\"}"
+ }
+ }
+
+ /**
+ * Calls an MCP tool on a remote peer in the SAM mesh.
+ * @param peerId The ID of the remote peer.
+ * @param toolName The name of the tool to call (namespaced, e.g., 'scheme://service/tool').
+ * @param argsJson The arguments for the tool call as a JSON string (e.g., '{"key": "value"}').
+ */
+ @AppFunction(isDescribedByKDoc = true)
+ suspend fun callRemoteMeshTool(context: AppFunctionContext, peerId: String, toolName: String, argsJson: String): String {
+ return try {
+ val ptr = samLib.CallRemoteTool(peerId, toolName, argsJson)
+ if (ptr != null) {
+ val json = ptr.getString(0)
+ samLib.FreeString(ptr)
+ json ?: "{\"error\": \"null response\"}"
+ } else {
+ "{\"error\": \"failed to call CallRemoteTool\"}"
+ }
+ } catch (e: Exception) {
+ "{\"error\": \"${e.message}\"}"
+ }
+ }
+}
diff --git a/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamNodeForegroundService.kt b/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamNodeForegroundService.kt
new file mode 100644
index 00000000..f6eccd3e
--- /dev/null
+++ b/mobile/sam-node-app/android/app/src/main/kotlin/com/example/sam_agent/SamNodeForegroundService.kt
@@ -0,0 +1,74 @@
+package com.example.sam_agent
+
+import android.app.Notification
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.Service
+import android.content.Intent
+import android.os.Build
+import android.os.IBinder
+import android.os.PowerManager
+import androidx.core.app.NotificationCompat
+import android.util.Log
+
+class SamNodeForegroundService : Service() {
+
+ private val CHANNEL_ID = "SAM_NODE_CHANNEL"
+ private val NOTIFICATION_ID = 1
+ private var wakeLock: PowerManager.WakeLock? = null
+
+ override fun onCreate() {
+ super.onCreate()
+ createNotificationChannel()
+
+ // Acquire partial wake lock to keep CPU running
+ val powerManager = getSystemService(POWER_SERVICE) as PowerManager
+ wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "SamNode::WakeLock")
+ wakeLock?.acquire()
+
+ Log.d("SAM_SERVICE", "Foreground Service Created")
+ }
+
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ val notification = createNotification()
+ startForeground(NOTIFICATION_ID, notification)
+
+ Log.d("SAM_SERVICE", "Foreground Service Started")
+
+ return START_STICKY // Restart if killed
+ }
+
+ override fun onBind(intent: Intent?): IBinder? {
+ return null
+ }
+
+ override fun onDestroy() {
+ super.onDestroy()
+ wakeLock?.release()
+ Log.d("SAM_SERVICE", "Foreground Service Destroyed")
+ }
+
+ private fun createNotification(): Notification {
+ val builder = NotificationCompat.Builder(this, CHANNEL_ID)
+ .setContentTitle("SAM Node Running")
+ .setContentText("Maintaining mesh connection in background")
+ .setSmallIcon(android.R.drawable.ic_menu_share) // Placeholder icon
+ .setOngoing(true)
+ .setPriority(NotificationCompat.PRIORITY_LOW) // Low priority to avoid annoying user, but enough for Foreground
+
+ return builder.build()
+ }
+
+ private fun createNotificationChannel() {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ val name = "SAM Node Service"
+ val descriptionText = "Keeps SAM Node alive in background"
+ val importance = NotificationManager.IMPORTANCE_LOW
+ val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
+ description = descriptionText
+ }
+ val notificationManager: NotificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
+ notificationManager.createNotificationChannel(channel)
+ }
+ }
+}
diff --git a/mobile/sam-node-app/android/app/src/main/res/values/strings.xml b/mobile/sam-node-app/android/app/src/main/res/values/strings.xml
new file mode 100644
index 00000000..3f4313bf
--- /dev/null
+++ b/mobile/sam-node-app/android/app/src/main/res/values/strings.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="sam_app_description">SAM Mesh Controller</string>
+</resources>
diff --git a/mobile/sam-node-app/android/app/src/main/res/xml/app_metadata.xml b/mobile/sam-node-app/android/app/src/main/res/xml/app_metadata.xml
new file mode 100644
index 00000000..7313f5ef
--- /dev/null
+++ b/mobile/sam-node-app/android/app/src/main/res/xml/app_metadata.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<AppFunctionAppMetadata
+ xmlns:appfn="http://schemas.android.com/apk/androidx.appfunctions"
+ appfn:description="SAM (Secure Agent Mesh) node controller. Allows monitoring and managing the local mesh node."
+ appfn:displayDescription="@string/sam_app_description" />
diff --git a/mobile/sam-node-app/android/gradle/wrapper/gradle-wrapper.properties b/mobile/sam-node-app/android/gradle/wrapper/gradle-wrapper.properties
index 2d428bfb..a20f2c46 100644
--- a/mobile/sam-node-app/android/gradle/wrapper/gradle-wrapper.properties
+++ b/mobile/sam-node-app/android/gradle/wrapper/gradle-wrapper.properties
@@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-all.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-all.zip
diff --git a/mobile/sam-node-app/android/settings.gradle.kts b/mobile/sam-node-app/android/settings.gradle.kts
index c21f0c5b..bee45ae8 100644
--- a/mobile/sam-node-app/android/settings.gradle.kts
+++ b/mobile/sam-node-app/android/settings.gradle.kts
@@ -19,8 +19,10 @@ pluginManagement {
plugins {
id("dev.flutter.flutter-plugin-loader") version "1.0.0"
- id("com.android.application") version "9.0.1" apply false
+ id("com.android.application") version "9.1.0" apply false
id("org.jetbrains.kotlin.android") version "2.3.20" apply false
+ id("com.google.gms.google-services") version "4.4.2" apply false
+ id("com.google.devtools.ksp") version "2.3.9" apply false
}
include(":app")