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: implement SkillRegistry system to load, manage, and toggle application-specific operational skills via settings UI
Rishabh Bajpai4cb5bf992a8d
diff --git a/app/src/main/assets/skills/settings.json b/app/src/main/assets/skills/settings.jsonnew file mode 100644index 0000000..9780b1c--- /dev/null+++ b/app/src/main/assets/skills/settings.json@@ -0,0 +1,7 @@+{+ "id": "settings_operations",+ "targetPackageNames": ["com.android.settings"],+ "name": "Android Settings Skills",+ "description": "Optimal instructions for navigating Android system settings.",+ "instructions": "When interacting with Android Settings, do NOT scroll manually to find a setting. This takes too long and fails frequently.\n1. Find the search bar or search icon at the top/bottom of the main Settings page.\n2. Tap it and type the exact setting you are looking for (e.g. 'Wi-Fi', 'Bluetooth', 'Display').\n3. Wait for the search results to load and tap the corresponding result.\n4. If a setting requires a toggle, look for a switch element and tap it to enable/disable. \n5. If you can't find settings by searching, cancel the search and start searching manually by swiping.."+}diff --git a/app/src/main/assets/skills/settings/settings_search.json b/app/src/main/assets/skills/settings/settings_search.jsonnew file mode 100644index 0000000..8ac125d--- /dev/null+++ b/app/src/main/assets/skills/settings/settings_search.json@@ -0,0 +1,6 @@+{+ "id": "settings_search",+ "targetPackageNames": ["com.android.settings"],+ "description": "Helps navigate Android Settings efficiently using search.",+ "instructions": "In the Settings app, ALWAYS look for a search bar or search icon (magnifying glass) at the top/bottom of the screen. Tap it and use 'input_text' to search for the specific setting instead of scrolling manually in the home setting page. When you tap on it, you will see a keyboard appearing on the screen. Do not start typing on the keyboard. Use the tool 'input_text' and then use 'tap' tool to select the appropriate settings. Use the tool 'swipe' in order to see the hidden settings that are behind the keyboard."+}diff --git a/app/src/main/assets/skills/whatsapp.json b/app/src/main/assets/skills/whatsapp.jsonnew file mode 100644index 0000000..a4e7ac8--- /dev/null+++ b/app/src/main/assets/skills/whatsapp.json@@ -0,0 +1,7 @@+{+ "id": "whatsapp_operations",+ "targetPackageNames": ["com.whatsapp"],+ "name": "WhatsApp Skills",+ "description": "Optimal physical instructions for interacting with WhatsApp UI elements.",+ "instructions": "When interacting with WhatsApp, use the physical UI layout optimally:\n1. To send a new message, do NOT search for the contact manually by scrolling. Use the 'Search' button (magnifying glass) at the top right, type the contact's name, and tap the result.\n2. To make a call, navigate to the 'Calls' tab first, then tap the 'New Call' button at the bottom right, search for the contact, and tap the audio or video call icon.\n3. The message input field usually has the accessibility text 'Message'. Use `input_text` with index to target it directly when in a chat.\n4. Always look for the currently opened chat or the chat list to find the contact. If you can find the contact directly over there, then open from there. Otherwise, use the search contact tool.\n5 Before sending any call message or starting any audio or video call, always ask the user whether they want to continue or not. Only if the user says yes, proceed without asking."+}diff --git a/app/src/main/assets/skills/whatsapp/messaging/whatsapp_chat.json b/app/src/main/assets/skills/whatsapp/messaging/whatsapp_chat.jsonnew file mode 100644index 0000000..17d7d84--- /dev/null+++ b/app/src/main/assets/skills/whatsapp/messaging/whatsapp_chat.json@@ -0,0 +1,6 @@+{+ "id": "whatsapp_chat",+ "targetPackageNames": ["com.whatsapp"],+ "description": "Helps navigate WhatsApp efficiently when chatting with contacts.",+ "instructions": "To send a WhatsApp message, use 'input_text' with the specific index of the search button (magnifying glass) at the top to find the contact first. Never swipe or scroll randomly to find a contact. Once the contact is opened, use 'input_text' on the message text field at the bottom of the screen to type your message."+}diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.ktindex aaf426d..2856c0c 100644--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt@@ -317,6 +317,7 @@ class AgentEngine(addAll(cullOldImages(trimmedHistory()))add(baseEnvironmentBlock(agent))add(currentTimestampMessage())+ addAll(activeSkillsMessages())}val response = try {llm.chat(messages, ToolRegistry.toolsForAgent(agent), sessionId = sessionId)@@ -731,6 +732,30 @@ class AgentEngine(return ChatMessage(role = "system", content = JsonPrimitive("Current date/time: $dateTime"))}+ /**+ * Injects context-aware skills based on the currently foregrounded package.+ * This makes the agent behave optimally for the specific app on screen.+ */+ private fun activeSkillsMessages(): List<ChatMessage> {+ val currentPackage = ScreenPerception.getCurrentPackageName() ?: return emptyList()+ val disabledSkills = settingsProvider().disabledSkills+ val activeSkills = com.gotcha.agent.skills.SkillRegistry.getSkillsForPackage(currentPackage)+ .filter { !disabledSkills.contains(it.id) }++ if (activeSkills.isEmpty()) return emptyList()++ val instructions = activeSkills.joinToString("\n\n") { "Skill [${it.id}]:\n${it.instructions}" }+ return listOf(+ ChatMessage(+ role = "system",+ content = JsonPrimitive(+ "<active-skills>\nThe user is currently using $currentPackage. " ++ "Use the following skills to operate it optimally:\n\n$instructions\n</active-skills>"+ )+ )+ )+ }+/*** Agent-specific core prompt + system-reminder, sent at the tail of the* message array (right before the latest user message). Placing these@@ -745,7 +770,7 @@ class AgentEngine("delete anything. You control the device only through the provided tools; never " +"invent tool names or capabilities. If a tool reports a missing permission, " +"explain what to grant and ask again. Use the sleep tool to pause and wait " +- "between operations. Keep replies short and conversational."+ "between operations. Use the search_skills tool when interacting with unfamiliar apps or complex operations to learn the optimal steps. Keep replies short and conversational."AgentMode.OPERATOR ->"You are Operator, an AI assistant running on the user's Android phone. " +"You can inspect, read, query, create, modify, and delete on the device. " +@@ -767,6 +792,7 @@ class AgentEngine("You will receive its complete report when done. " +"Keep replies short and conversational. Be careful with destructive actions.\n" +"If the accessibility service is enabled, you have the ability to control any app on the device.\n" ++ "When interacting with unfamiliar apps, system settings, or complex workflows, use the search_skills tool to fetch context-aware operational instructions.\n" +"When using uninstall_app: after calling it, the system will open a dialog. " +"Tell the user to tap OK in the system dialog to finish the uninstall. " +"Do NOT attempt to uninstall via shell commands (run_command, run_root_command) — " +diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.ktindex d3bc073..10df897 100644--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt@@ -160,6 +160,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Ainit {ScreenPerception.appContext = application+ com.gotcha.agent.skills.SkillRegistry.init(application)refreshSettings()viewModelScope.launch {// Always start on a fresh session so the home screen greets with andiff --git a/app/src/main/java/com/gotcha/agent/skills/Skill.kt b/app/src/main/java/com/gotcha/agent/skills/Skill.ktnew file mode 100644index 0000000..2d2c1b2--- /dev/null+++ b/app/src/main/java/com/gotcha/agent/skills/Skill.kt@@ -0,0 +1,11 @@+package com.gotcha.agent.skills++import kotlinx.serialization.Serializable++@Serializable+data class Skill(+ val id: String,+ val targetPackageNames: List<String> = emptyList(),+ val instructions: String,+ val description: String = ""+)diff --git a/app/src/main/java/com/gotcha/agent/skills/SkillRegistry.kt b/app/src/main/java/com/gotcha/agent/skills/SkillRegistry.ktnew file mode 100644index 0000000..44b318d--- /dev/null+++ b/app/src/main/java/com/gotcha/agent/skills/SkillRegistry.kt@@ -0,0 +1,59 @@+package com.gotcha.agent.skills++import android.content.Context+import android.util.Log+import kotlinx.serialization.json.Json+import kotlinx.serialization.decodeFromString+import java.io.File++object SkillRegistry {+ private val json = Json { ignoreUnknownKeys = true }+ private val skills = mutableListOf<Skill>()++ fun init(context: Context) {+ skills.clear()+ try {+ loadSkillsFromAssets(context, "skills")+ } catch (e: Exception) {+ Log.e("SkillRegistry", "Failed to load skills", e)+ }+ }++ private fun loadSkillsFromAssets(context: Context, path: String) {+ val assetManager = context.assets+ val list = assetManager.list(path) ?: return+ for (item in list) {+ val fullPath = if (path.isEmpty()) item else "$path/$item"+ if (item.endsWith(".json")) {+ try {+ val text = assetManager.open(fullPath).bufferedReader().use { it.readText() }+ val skill = json.decodeFromString<Skill>(text)+ skills.add(skill)+ Log.d("SkillRegistry", "Loaded skill: ${skill.id}")+ } catch (e: Exception) {+ Log.e("SkillRegistry", "Error parsing $fullPath", e)+ }+ } else if (!item.contains(".")) {+ // Heuristic for directories: no extension.+ loadSkillsFromAssets(context, fullPath)+ }+ }+ }++ fun getAllSkills(): List<Skill> = skills.toList()++ fun getSkillById(id: String): Skill? = skills.find { it.id == id }++ fun getSkillsForPackage(packageName: String): List<Skill> {+ return skills.filter { it.targetPackageNames.contains(packageName) }+ }++ fun searchSkills(query: String): List<Skill> {+ val q = query.lowercase()+ return skills.filter { skill ->+ skill.id.lowercase().contains(q) ||+ skill.description.lowercase().contains(q) ||+ skill.targetPackageNames.any { it.lowercase().contains(q) }+ }+ }+}diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.ktindex 9b6c5c3..9fac7c1 100644--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt@@ -38,7 +38,8 @@ data class Settings(val sttApiModel: String = "",val autoReadReplies: Boolean = false,val assistiveBallEnabled: Boolean = false,- val themeMode: ThemeMode = ThemeMode.SYSTEM+ val themeMode: ThemeMode = ThemeMode.SYSTEM,+ val disabledSkills: Set<String> = emptySet()) {/** True when the active provider has everything it needs to make requests. */val isConfigured: Boolean@@ -111,7 +112,8 @@ class SettingsRepository(context: Context) {assistiveBallEnabled = prefs.getBoolean(KEY_ASSISTIVE_BALL, false),themeMode = runCatching {ThemeMode.valueOf(prefs.getString(KEY_THEME_MODE, "SYSTEM") ?: "SYSTEM")- }.getOrDefault(ThemeMode.SYSTEM)+ }.getOrDefault(ThemeMode.SYSTEM),+ disabledSkills = prefs.getStringSet(KEY_DISABLED_SKILLS, emptySet()) ?: emptySet())fun save(settings: Settings) {@@ -137,6 +139,7 @@ class SettingsRepository(context: Context) {.putBoolean(KEY_AUTO_READ, settings.autoReadReplies).putBoolean(KEY_ASSISTIVE_BALL, settings.assistiveBallEnabled).putString(KEY_THEME_MODE, settings.themeMode.name)+ .putStringSet(KEY_DISABLED_SKILLS, settings.disabledSkills).apply()}@@ -178,5 +181,6 @@ class SettingsRepository(context: Context) {const val KEY_AUTO_READ = "auto_read"const val KEY_ASSISTIVE_BALL = "assistive_ball_enabled"const val KEY_THEME_MODE = "theme_mode"+ const val KEY_DISABLED_SKILLS = "disabled_skills"}}diff --git a/app/src/main/java/com/gotcha/tools/ScreenPerception.kt b/app/src/main/java/com/gotcha/tools/ScreenPerception.ktindex eb956bd..aeb7582 100644--- a/app/src/main/java/com/gotcha/tools/ScreenPerception.kt+++ b/app/src/main/java/com/gotcha/tools/ScreenPerception.kt@@ -203,6 +203,14 @@ object ScreenPerception {return Pair(1080, 2340)}+ fun getCurrentPackageName(): String? {+ val service = GotchaAccessibilityService.instance ?: return null+ val root = service.rootInActiveWindow ?: return null+ val pkg = root.packageName?.toString()+ root.recycle()+ return pkg+ }+private fun drawCoordinateGrid(bitmap: Bitmap): Bitmap {val canvas = Canvas(bitmap)val w = bitmap.width.toFloat()diff --git a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt b/app/src/main/java/com/gotcha/tools/SubAgentSession.ktindex cd7699b..440f716 100644--- a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt+++ b/app/src/main/java/com/gotcha/tools/SubAgentSession.kt@@ -54,8 +54,13 @@ class SubAgentSession(for (round in 0 until maxRounds) {Log.d(TAG, "Sub-agent round ${round + 1}/$maxRounds")+ val messages = buildList {+ addAll(history)+ addAll(activeSkillsMessages(settings.disabledSkills))+ }+val response = try {- subLlm.chat(history.toList(), subAgentTools, sessionId = sessionId)+ subLlm.chat(messages, subAgentTools, sessionId = sessionId)} catch (e: CancellationException) {throw e} catch (e: Throwable) {@@ -165,6 +170,7 @@ class SubAgentSession("You have access to all device tools. " +"Your job is to complete the task delegated to you. " +"Use the available tools to perform the required steps. " ++ "When interacting with unfamiliar apps, system settings, or complex workflows, use the search_skills tool to fetch context-aware operational instructions.\n" +"When you have fully completed the task and have the final answer, " +"call the ask_final_answer tool with your complete result. " +"Do NOT call ask_final_answer until all work is actually done."@@ -250,6 +256,25 @@ class SubAgentSession(}}+ private fun activeSkillsMessages(disabledSkills: Set<String>): List<ChatMessage> {+ val currentPackage = com.gotcha.tools.ScreenPerception.getCurrentPackageName() ?: return emptyList()+ val activeSkills = com.gotcha.agent.skills.SkillRegistry.getSkillsForPackage(currentPackage)+ .filter { !disabledSkills.contains(it.id) }++ if (activeSkills.isEmpty()) return emptyList()++ val instructions = activeSkills.joinToString("\n\n") { "Skill [${it.id}]:\n${it.instructions}" }+ return listOf(+ ChatMessage(+ role = "system",+ content = JsonPrimitive(+ "<active-skills>\nThe user is currently using $currentPackage. " ++ "Use the following skills to operate it optimally:\n\n$instructions\n</active-skills>"+ )+ )+ )+ }+private companion object {const val TAG = "SubAgentSession"}diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.ktindex bae5fc9..7b8b89f 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -1699,6 +1699,20 @@ object ToolDefinitions {})+ val searchSkills = tool(+ "search_skills",+ "Search the skills registry for contextual instructions on how to optimally interact with a given app or perform a system operation.",+ schema {+ putJsonObject("properties") {+ putJsonObject("query") {+ put("type", "string")+ put("description", "The package name, app name, or operation to search for (e.g. 'com.whatsapp', 'whatsapp', 'settings_search').")+ }+ }+ putJsonArray("required") { add("query") }+ }+ )+val all: List<ToolDefinition> = listOf(dialNumber, getStorageInfo, getBatteryInfo, listFiles, readFile, writeFile,openApp, setBrightness, toggleWifi,@@ -1735,6 +1749,8 @@ object ToolDefinitions {lockScreen, disableCamera, setPasswordPolicy,// Tier 4 additions: privileged / rooted execution- checkRoot, runRootCommand, writeSecureSettings+ checkRoot, runRootCommand, writeSecureSettings,++ searchSkills)}diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.ktindex 82ec249..e2030da 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -449,6 +449,16 @@ class ToolExecutor(key = args.requireString("key") ?: return missing("key"),value = args.requireString("value") ?: return missing("value"))+ "search_skills" -> {+ val query = args.requireString("query") ?: return missing("query")+ val results = com.gotcha.agent.skills.SkillRegistry.searchSkills(query)+ if (results.isEmpty()) {+ ToolResult.ok("No skills found matching '$query'.")+ } else {+ val instructions = results.joinToString("\n\n") { "Skill [${it.id}]:\n${it.instructions}" }+ ToolResult.ok("Found ${results.size} skills matching '$query':\n\n$instructions")+ }+ }else -> ToolResult.error("Tool '$name' has no executor.")}}diff --git a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt b/app/src/main/java/com/gotcha/tools/ToolRegistry.ktindex 05d047d..24335c8 100644--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt@@ -38,7 +38,7 @@ object ToolRegistry {"websearch", "webfetch","get_clipboard","read_screen", "read_notifications",- "check_root"+ "check_root", "search_skills")/** Full Operator tool set minus task + navigate_app (sub-agents cannot delegate further). */diff --git a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt b/app/src/main/java/com/gotcha/ui/SettingsScreen.ktindex 089a95d..775bfff 100644--- a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt+++ b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt@@ -95,6 +95,7 @@ fun SettingsScreen(var sttApiModel by remember { mutableStateOf(initial.sttApiModel) }var autoReadReplies by remember { mutableStateOf(initial.autoReadReplies) }var themeMode by remember { mutableStateOf(initial.themeMode) }+ var disabledSkills by remember { mutableStateOf(initial.disabledSkills) }// Discovered model listsvar availableTtsModels by remember { mutableStateOf<List<AudioModel>>(emptyList()) }var availableSttModels by remember { mutableStateOf<List<AudioModel>>(emptyList()) }@@ -107,6 +108,7 @@ fun SettingsScreen(// Collapsible sectionsvar aiConfigExpanded by remember { mutableStateOf(false) }var speechExpanded by remember { mutableStateOf(false) }+ var skillsExpanded by remember { mutableStateOf(false) }val scope = rememberCoroutineScope()// Dropdown expanded states@@ -139,7 +141,8 @@ fun SettingsScreen(sttApiModel = sttApiModel.trim(),autoReadReplies = autoReadReplies,assistiveBallEnabled = initial.assistiveBallEnabled,- themeMode = themeMode+ themeMode = themeMode,+ disabledSkills = disabledSkills)val refreshChatModelsAction = {@@ -737,6 +740,49 @@ fun SettingsScreen() { Text("Save Speech Settings") }}}++ HorizontalDivider(thickness = 1.dp)++ // ---- Skills (collapsible, collapsed by default) ----+ SectionHeader(+ title = "Skills / Plugins",+ expanded = skillsExpanded,+ onToggle = { skillsExpanded = !skillsExpanded }+ )+ AnimatedVisibility(visible = skillsExpanded) {+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {+ val allSkills = com.gotcha.agent.skills.SkillRegistry.getAllSkills()+ if (allSkills.isEmpty()) {+ Text("No skills loaded.", style = MaterialTheme.typography.bodyMedium)+ } else {+ allSkills.forEach { skill ->+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(modifier = Modifier.weight(1f).padding(end = 8.dp)) {+ Text(skill.id, style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Bold)+ if (skill.description.isNotBlank()) {+ Text(skill.description, style = MaterialTheme.typography.bodySmall)+ }+ }+ Switch(+ checked = !disabledSkills.contains(skill.id),+ onCheckedChange = { enabled ->+ disabledSkills = if (enabled) {+ disabledSkills - skill.id+ } else {+ disabledSkills + skill.id+ }+ onSave(currentSettings())+ }+ )+ }+ }+ }+ }+ }// Status textstatus?.let {