Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
feat(tools): hide tools whose device capability is missing
Durganshu Mishraddeee909eca2
diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.ktindex c75aca9..62993e6 100644--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt@@ -15,6 +15,7 @@ import com.gotcha.llm.ToolCallimport com.gotcha.llm.visionUserMessageimport com.gotcha.tools.AgentModeimport com.gotcha.tools.AppNavigatorSession+import com.gotcha.tools.DeviceCapabilitiesimport com.gotcha.tools.FileResolverimport com.gotcha.tools.ScreenPerceptionimport com.gotcha.tools.SubAgentSession@@ -384,7 +385,7 @@ class AgentEngine(val response = try {llm.chat(messages,- ToolRegistry.toolsForAgent(agent, hiddenConnectorTools()),+ ToolRegistry.toolsForAgent(agent, hiddenTools()),sessionId = sessionId)} catch (e: CancellationException) {@@ -805,17 +806,20 @@ class AgentEngine(call.function.name,args,agent,- hiddenTools = hiddenConnectorTools()+ hiddenTools = hiddenTools())}/**- * Tools withheld this turn because every connector that could serve them is- * disconnected or switched off. Recomputed per call — the user can connect or- * toggle a connector mid-conversation.+ * Tools withheld this turn: those whose connector is disconnected or switched+ * off, plus those whose device capability is missing (accessibility off, not+ * rooted, …). Recomputed per call — the user can connect an account or grant+ * a permission mid-conversation, and the `<env>` block reports both so the+ * model can see a capability appear rather than only inferring it.*/- private fun hiddenConnectorTools(): Set<String> =- ConnectorRegistry.hiddenToolNames(settings.disabledConnectors)+ private fun hiddenTools(): Set<String> =+ ConnectorRegistry.hiddenToolNames(settings.disabledConnectors) ++ DeviceCapabilities.hiddenToolNames(appContext)/*** Environment block sent as the first system message.@@ -847,7 +851,7 @@ class AgentEngine(private fun activeSkillsMessages(): List<ChatMessage> {val currentPackage = ScreenPerception.getCurrentPackageName() ?: return emptyList()val disabledSkills = settingsProvider().disabledSkills- val activeSkills = SkillRegistry.getSkillsForPackage(currentPackage, hiddenConnectorTools())+ val activeSkills = SkillRegistry.getSkillsForPackage(currentPackage, hiddenTools()).filter { !disabledSkills.contains(it.id) }val communityIds = SkillRegistry.getCommunitySkills().map { it.id }.toSet()val message = SkillPromptBuilder.build(currentPackage, activeSkills, communityIds)@@ -950,28 +954,11 @@ class AgentEngine(pm.getPackageInfo(app.packageName, 0).versionName ?: "unknown"} catch (_: Exception) { "unknown" }- val accEnabled = try {- val expected = "${app.packageName}/com.gotcha.service.GotchaAccessibilityService"- val enabled = android.provider.Settings.Secure.getString(- app.contentResolver, android.provider.Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES- ) ?: ""- enabled.contains(expected, ignoreCase = true)- } catch (_: Exception) { false }-- val notifEnabled = try {- val expected = app.packageName- val enabled = android.provider.Settings.Secure.getString(- app.contentResolver, "enabled_notification_listeners"- ) ?: ""- enabled.contains(expected, ignoreCase = true)- } catch (_: Exception) { false }-- val deviceAdmin = try {- val dpm = app.getSystemService(android.app.admin.DevicePolicyManager::class.java)- dpm?.isAdminActive(- android.content.ComponentName(app, com.gotcha.service.GotchaDeviceAdminReceiver::class.java)- ) ?: false- } catch (_: Exception) { false }+ // Same probes that decide tool exposure, so the status the model reads can+ // never disagree with the tools it was offered.+ val accEnabled = DeviceCapabilities.accessibilityEnabled(app)+ val notifEnabled = DeviceCapabilities.notificationListenerEnabled(app)+ val deviceAdmin = DeviceCapabilities.deviceAdminActive(app)val vpnActive = try {val cm = app.getSystemService(@@ -993,6 +980,13 @@ class AgentEngine(appendLine(" Accessibility service enabled: ${if (accEnabled) "yes" else "no"}")appendLine(" Notification listener enabled: ${if (notifEnabled) "yes" else "no"}")appendLine(" Device admin active: ${if (deviceAdmin) "yes" else "no"}")+ // Tools depending on a capability that is "no" here are withheld from+ // the tool list, so these lines are the model's only way to explain+ // what the user should enable.+ appendLine(+ " Display over other apps: " ++ if (DeviceCapabilities.overlayAllowed(app)) "yes" else "no"+ )appendLine(" VPN active: ${if (vpnActive) "yes" else "no"}")appendLine(" App version: $versionName")appendLine(" Working directory: ${FileResolver.WORKING_DIR_BASE}")diff --git a/app/src/main/java/com/gotcha/tools/CapabilityCatalog.kt b/app/src/main/java/com/gotcha/tools/CapabilityCatalog.ktnew file mode 100644index 0000000..b23616c--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/CapabilityCatalog.kt@@ -0,0 +1,79 @@+package com.gotcha.tools++/**+ * A device-side capability that a group of tools depends on — an accessibility+ * service, a special-access grant, root. The connector analogue is+ * [com.gotcha.connectors.ConnectorSpec]; this is the same idea for things the+ * user grants on the device rather than signs into.+ *+ * One difference matters. A connector that is missing is missing until the user+ * sets it up, and the tools are hidden accordingly. A permission can be granted+ * *on demand*, so hiding the tools must not hide the possibility: the `<env>`+ * block reports each capability's status every turn, which is what lets the+ * agent still say "enable accessibility in Settings and ask me again".+ */+enum class Capability(+ /** Human name used in the tool-unavailable message. */+ val label: String,+ /** Tools that cannot function without it. */+ val tools: Set<String>+) {+ ACCESSIBILITY(+ "the accessibility service",+ setOf(+ "tap", "tap_index", "long_press", "long_press_index", "swipe",+ "input_text", "press_key", "global_action",+ "read_screen", "read_screen_raw",+ "navigate_app"+ )+ ),++ NOTIFICATION_LISTENER(+ "notification access",+ // media_control and get_now_playing read MediaSessions, which Android+ // only hands out to an enabled notification listener.+ setOf("read_notifications", "dismiss_notifications", "media_control", "get_now_playing")+ ),++ DEVICE_ADMIN(+ "device admin",+ setOf("lock_screen", "disable_camera", "set_password_policy")+ ),++ ROOT(+ "root",+ // check_root deliberately stays exposed: it is how the agent finds out,+ // and it is the only tool here that is useful on an unrooted device.+ setOf("run_root_command", "write_secure_settings")+ ),++ HEALTH_CONNECT(+ "Health Connect",+ setOf("get_health_summary", "get_health_records")+ ),++ OVERLAY(+ "the display-over-other-apps permission",+ setOf("show_overlay", "hide_overlay")+ )+}++/**+ * The static half of capability gating: which tools each capability owns.+ * [DeviceCapabilities] supplies the runtime answer to which ones are available.+ */+object CapabilityCatalog {++ /** Every tool that depends on some device capability. */+ val allGatedTools: Set<String> = Capability.entries.flatMapTo(mutableSetOf()) { it.tools }++ /**+ * Tools to withhold given the capabilities currently available. Unlike+ * connectors there is no union rule — each tool has exactly one owner.+ */+ fun hiddenTools(available: Set<Capability>): Set<String> =+ Capability.entries.filterNot { it in available }.flatMapTo(mutableSetOf()) { it.tools }++ /** The capability [tool] needs, or null if it needs none. */+ fun ownerOf(tool: String): Capability? = Capability.entries.firstOrNull { tool in it.tools }+}diff --git a/app/src/main/java/com/gotcha/tools/DeviceCapabilities.kt b/app/src/main/java/com/gotcha/tools/DeviceCapabilities.ktnew file mode 100644index 0000000..fe47e02--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/DeviceCapabilities.kt@@ -0,0 +1,118 @@+package com.gotcha.tools++import android.content.Context+import java.io.File++/**+ * Runtime probes for the [Capability] set. Cheap enough to call once per LLM+ * round: everything here is a settings string read or a service lookup, except+ * root — see [rootAvailable].+ *+ * Single source of truth on purpose. `AgentEngine.buildEnvironmentString()`+ * renders these same values into the `<env>` block, so the status the model+ * reads and the tools it is offered can never disagree.+ */+object DeviceCapabilities {++ /** Paths a `su` binary lives at on the common root solutions. */+ private val SU_PATHS = listOf(+ "/system/bin/su",+ "/system/xbin/su",+ "/sbin/su",+ "/system/sbin/su",+ "/vendor/bin/su",+ "/su/bin/su",+ // Magisk is present even when the su binary itself is path-hidden.+ "/data/adb/magisk/busybox"+ )++ @Volatile+ private var cachedRoot: Boolean? = null++ fun available(context: Context): Set<Capability> = buildSet {+ if (accessibilityEnabled(context)) add(Capability.ACCESSIBILITY)+ if (notificationListenerEnabled(context)) add(Capability.NOTIFICATION_LISTENER)+ if (deviceAdminActive(context)) add(Capability.DEVICE_ADMIN)+ if (rootAvailable()) add(Capability.ROOT)+ if (healthConnectPresent(context)) add(Capability.HEALTH_CONNECT)+ if (overlayAllowed(context)) add(Capability.OVERLAY)+ }++ /** Tools to withhold from the model right now. */+ fun hiddenToolNames(context: Context): Set<String> =+ CapabilityCatalog.hiddenTools(available(context))++ fun accessibilityEnabled(context: Context): Boolean = secureListContains(+ context,+ android.provider.Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,+ "${context.packageName}/com.gotcha.service.GotchaAccessibilityService"+ )++ fun notificationListenerEnabled(context: Context): Boolean =+ secureListContains(context, "enabled_notification_listeners", context.packageName)++ fun deviceAdminActive(context: Context): Boolean = runCatching {+ context.getSystemService(android.app.admin.DevicePolicyManager::class.java)?.isAdminActive(+ android.content.ComponentName(+ context,+ com.gotcha.service.GotchaDeviceAdminReceiver::class.java+ )+ ) ?: false+ }.getOrDefault(false)++ fun overlayAllowed(context: Context): Boolean =+ runCatching { android.provider.Settings.canDrawOverlays(context) }.getOrDefault(false)++ /**+ * Whether Health Connect exists on the device — deliberately *not* whether+ * its permissions are granted.+ *+ * [HealthPermissionState] is a cache that starts false on every process+ * start and is only filled by a health tool actually running. Gating on it+ * would hide the health tools at launch, which would stop HealthTool from+ * ever running, which would leave the cache false: a user who had granted+ * the permission would silently lose the feature after every restart.+ * Availability is synchronous and has no such cycle, and leaving the tools+ * exposed while ungranted is what lets HealthTool raise the permission+ * prompt.+ */+ fun healthConnectPresent(context: Context): Boolean = runCatching {+ androidx.health.connect.client.HealthConnectClient.getSdkStatus(context) ==+ androidx.health.connect.client.HealthConnectClient.SDK_AVAILABLE+ }.getOrDefault(false)++ /**+ * Presence of a `su` binary, cached for the process.+ *+ * Deliberately a file-existence check rather than [RootTool.checkRoot]:+ * actually running `su` pops the Magisk grant dialog, and this runs on every+ * round. A false positive only means two extra schemas are offered and the+ * real probe fails later; `check_root` stays exposed to do it properly.+ */+ fun rootAvailable(): Boolean = cachedRoot ?: run {+ val found = runCatching { SU_PATHS.any { File(it).exists() } }.getOrDefault(false)+ cachedRoot = found+ found+ }++ /**+ * Records what the real `su` probe found. [rootAvailable] only looks for the+ * binary at the usual paths, so a device where `su` lives elsewhere would+ * keep the root tools hidden forever; running `check_root` — which stays+ * exposed precisely for this — corrects the guess.+ */+ fun setRootAvailable(value: Boolean) {+ cachedRoot = value+ }++ /** Clears the root cache. Only used by tests. */+ fun resetRootCacheForTesting() {+ cachedRoot = null+ }++ private fun secureListContains(context: Context, key: String, needle: String): Boolean =+ runCatching {+ (android.provider.Settings.Secure.getString(context.contentResolver, key) ?: "")+ .contains(needle, ignoreCase = true)+ }.getOrDefault(false)+}diff --git a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt b/app/src/main/java/com/gotcha/tools/SubAgentSession.ktindex 0c58357..77c79da 100644--- a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt+++ b/app/src/main/java/com/gotcha/tools/SubAgentSession.kt@@ -52,9 +52,7 @@ class SubAgentSession(val history = initialHistory()val maxRounds = settings.maxToolRounds- // Sub-agents inherit the parent's connector gating: no point paying for- // schemas of tools nothing can serve, once per round, again.- val hiddenTools = ConnectorRegistry.hiddenToolNames(settings.disabledConnectors)+ val hiddenTools = hiddenTools()val subAgentTools = ToolRegistry.toolsForSubAgent(hiddenTools)for (round in 0 until maxRounds) {@@ -275,6 +273,14 @@ class SubAgentSession(}}+ /**+ * Sub-agents inherit the parent's gating: no point paying for schemas of+ * tools nothing can serve, once per round, again.+ */+ private fun hiddenTools(): Set<String> =+ ConnectorRegistry.hiddenToolNames(settings.disabledConnectors) ++ DeviceCapabilities.hiddenToolNames(appContext)+private fun activeSkillsMessages(disabledSkills: Set<String>,hiddenTools: Set<String>diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.ktindex 594c35b..20820e6 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -89,7 +89,7 @@ class ToolExecutor(return ToolResult.error("Unknown tool '$name'. Only the fixed tool catalog is available.")}if (name in hiddenTools) {- return ToolResult.error(connectorUnavailableMessage(name))+ return ToolResult.error(unavailableMessage(name))}if (!isSubAgent && !ToolRegistry.isAllowedForAgent(name, agent)) {return ToolResult.error(@@ -480,7 +480,11 @@ class ToolExecutor()// ---- Tier 4 ----- "check_root" -> rootTool.checkRoot()+ "check_root" -> rootTool.checkRoot().also {+ // The real probe beats the binary-path guess that gates the other+ // root tools, so let it correct the cache either way.+ DeviceCapabilities.setRootAvailable(it.message.contains("Root IS available"))+ }"run_root_command" -> rootTool.runRootCommand(args.requireString("command") ?: return missing("command"))"write_secure_settings" -> rootTool.writeSecureSetting(namespace = args.requireString("namespace") ?: return missing("namespace"),@@ -503,8 +507,12 @@ class ToolExecutor(}}- /** Names the connectors that would make [name] work, so the model can steer the user. */- private fun connectorUnavailableMessage(name: String): String {+ /** Names what would make [name] work, so the model can steer the user there. */+ private fun unavailableMessage(name: String): String {+ CapabilityCatalog.ownerOf(name)?.let { capability ->+ return "Tool '$name' is unavailable: it needs ${capability.label}, which is not " ++ "available on this device right now. Tell the user what to enable; do not retry."+ }val owners = com.gotcha.connectors.ConnectorCatalog.ownersOf(name).joinToString(" or ") { it.displayName }val suffix = if (owners.isBlank()) {diff --git a/app/src/test/java/com/gotcha/tools/CapabilityGatingTest.kt b/app/src/test/java/com/gotcha/tools/CapabilityGatingTest.ktnew file mode 100644index 0000000..5ca8a06--- /dev/null+++ b/app/src/test/java/com/gotcha/tools/CapabilityGatingTest.kt@@ -0,0 +1,97 @@+package com.gotcha.tools++import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++/**+ * Device-capability tool gating. Exercises [CapabilityCatalog] directly — the+ * runtime probes in [DeviceCapabilities] need a real device, but the rules that+ * decide what gets hidden do not.+ */+class CapabilityGatingTest {++ @Test+ fun `nothing available hides every capability-gated tool`() {+ val hidden = CapabilityCatalog.hiddenTools(emptySet())+ assertEquals(CapabilityCatalog.allGatedTools, hidden)+ assertTrue("tap" in hidden)+ assertTrue("navigate_app" in hidden)+ assertTrue("read_notifications" in hidden)+ assertTrue("run_root_command" in hidden)+ }++ @Test+ fun `everything available hides nothing`() {+ assertTrue(CapabilityCatalog.hiddenTools(Capability.entries.toSet()).isEmpty())+ }++ @Test+ fun `capabilities gate independently`() {+ val hidden = CapabilityCatalog.hiddenTools(setOf(Capability.ACCESSIBILITY))+ assertFalse("tap" in hidden)+ assertFalse("read_screen" in hidden)+ assertTrue("read_notifications" in hidden)+ assertTrue("lock_screen" in hidden)+ }++ @Test+ fun `check_root stays exposed so the agent can discover root`() {+ // Gating the discovery tool on the thing it discovers would be circular,+ // and it is the one root tool that is useful on an unrooted device.+ assertFalse("check_root" in CapabilityCatalog.allGatedTools)+ assertTrue("run_root_command" in Capability.ROOT.tools)+ assertTrue("write_secure_settings" in Capability.ROOT.tools)+ }++ @Test+ fun `gated tools all exist and belong to exactly one capability`() {+ CapabilityCatalog.allGatedTools.forEach {+ assertTrue("unknown tool $it", ToolRegistry.contains(it))+ }+ val counts = CapabilityCatalog.allGatedTools.associateWith { tool ->+ Capability.entries.count { tool in it.tools }+ }+ counts.forEach { (tool, n) -> assertEquals("$tool has $n owners", 1, n) }+ }++ @Test+ fun `capability gating does not overlap connector gating`() {+ // A tool gated twice would need both owners consulted; keeping the two+ // sets disjoint means each hidden tool has one explainable reason.+ val overlap = CapabilityCatalog.allGatedTools intersect+ com.gotcha.connectors.ConnectorCatalog.allOwnedTools+ assertTrue("gated by both: $overlap", overlap.isEmpty())+ }++ @Test+ fun `ownerOf names the capability a tool needs`() {+ assertEquals(Capability.ACCESSIBILITY, CapabilityCatalog.ownerOf("swipe"))+ assertEquals(Capability.NOTIFICATION_LISTENER, CapabilityCatalog.ownerOf("get_now_playing"))+ assertNull(CapabilityCatalog.ownerOf("read_file"))+ assertNull(CapabilityCatalog.ownerOf("check_root"))+ }++ @Test+ fun `tools that work without any special access are never gated`() {+ // Regression guard: these are the fallbacks the agent relies on when the+ // fancier route is unavailable.+ listOf(+ "open_app", "list_installed_apps", "question", "sleep",+ "read_file", "write_file", "websearch", "compose_email",+ "list_calendar_events", "set_alarm", "run_command"+ ).forEach {+ assertFalse("$it must never be capability-gated", it in CapabilityCatalog.allGatedTools)+ }+ }++ @Test+ fun `hidden capability tools drop out of the operator schema list`() {+ val hidden = CapabilityCatalog.hiddenTools(emptySet())+ val exposed = ToolRegistry.toolsForAgent(AgentMode.OPERATOR, hidden).map { it.function.name }+ assertTrue(hidden.none { it in exposed })+ assertTrue("check_root" in exposed)+ }+}