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 intent-based skill filtering and suppress previously fetched skills in prompt building
Rishabh Bajpai55eccad66791
diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.ktindex f56f7d7..2040ae4 100644--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt@@ -938,8 +938,12 @@ class AgentEngine(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)- ?: return emptyList()+ val message = SkillPromptBuilder.buildFromHistory(+ currentPackage = currentPackage,+ activeSkills = activeSkills,+ communityIds = communityIds,+ history = history+ ) ?: return emptyList()return listOf(message)}diff --git a/app/src/main/java/com/gotcha/agent/skills/Skill.kt b/app/src/main/java/com/gotcha/agent/skills/Skill.ktindex e643df1..30ca96d 100644--- a/app/src/main/java/com/gotcha/agent/skills/Skill.kt+++ b/app/src/main/java/com/gotcha/agent/skills/Skill.kt@@ -22,9 +22,28 @@ data class Skill(* served by Gmail *or* Microsoft *or* IMAP, so naming one connector would be* wrong for the other two, and this also covers permission-gated tools.*/- val requiresTools: List<String> = emptyList()+ val requiresTools: List<String> = emptyList(),+ val keywords: List<String> = emptyList()) {+ private val compiledKeywordRegexes: List<Regex> by lazy {+ keywords.map { kw ->+ Regex("""\b${Regex.escape(kw)}\b""", RegexOption.IGNORE_CASE)+ }+ }+/** True when nothing this skill teaches is currently withheld from the model. */fun isAvailable(hiddenTools: Set<String>): Boolean =requiresTools.isEmpty() || requiresTools.any { it !in hiddenTools }++ /**+ * True when keywords are empty, or when at least one keyword matches a word+ * boundary in [text] (case-insensitive). Word-boundary matching prevents false+ * positives like keyword "call" matching "recall" or "vocaller".+ */+ fun matchesIntent(text: String): Boolean {+ if (keywords.isEmpty() || text.isBlank()) return true+ return compiledKeywordRegexes.any { regex ->+ regex.containsMatchIn(text)+ }+ }}diff --git a/app/src/main/java/com/gotcha/agent/skills/SkillPromptBuilder.kt b/app/src/main/java/com/gotcha/agent/skills/SkillPromptBuilder.ktindex 7ad7b55..2883533 100644--- a/app/src/main/java/com/gotcha/agent/skills/SkillPromptBuilder.kt+++ b/app/src/main/java/com/gotcha/agent/skills/SkillPromptBuilder.kt@@ -16,6 +16,53 @@ import kotlinx.serialization.json.JsonPrimitive*/object SkillPromptBuilder {+ /** Regex matching the tool result header format emitted by ToolExecutor for search_skills. */+ val SKILL_RESULT_REGEX = Regex("""Skill \[([^\]]+)\]:""")++ /**+ * Scans conversation history for tool-result messages containing full skill bodies+ * previously fetched via `search_skills`.+ */+ fun extractFetchedSkillIds(history: List<ChatMessage>): Set<String> {+ return history.asSequence()+ .filter { it.role == "tool" }+ .flatMap { SKILL_RESULT_REGEX.findAll(it.textContent) }+ .map { it.groupValues[1] }+ .toSet()+ }++ /**+ * Extracts the text of the last genuine user (human) message from history,+ * skipping synthetic observation messages (e.g. vision/screenshot observations+ * or system notes that start with `[`).+ */+ fun extractLastHumanUserMessage(history: List<ChatMessage>): String {+ return history.lastOrNull { msg ->+ msg.role == "user" && !msg.textContent.trimStart().startsWith("[")+ }?.textContent ?: ""+ }++ /**+ * Builds the prompt block by extracting fetched skill IDs and the last human+ * user message directly from conversation history.+ */+ fun buildFromHistory(+ currentPackage: String,+ activeSkills: List<Skill>,+ communityIds: Set<String>,+ history: List<ChatMessage>+ ): ChatMessage? {+ val fetchedIds = extractFetchedSkillIds(history)+ val lastUserMsg = extractLastHumanUserMessage(history)+ return build(+ currentPackage = currentPackage,+ activeSkills = activeSkills,+ communityIds = communityIds,+ recentlyFetchedSkillIds = fetchedIds,+ lastUserMessage = lastUserMsg+ )+ }+private const val HEADER ="<available-skills>\n" +"The user is currently using %s. Here are suggested skills for this app:\n"@@ -37,11 +84,22 @@ object SkillPromptBuilder {fun build(currentPackage: String,activeSkills: List<Skill>,- communityIds: Set<String>+ communityIds: Set<String>,+ recentlyFetchedSkillIds: Set<String> = emptySet(),+ lastUserMessage: String = ""): ChatMessage? {- if (activeSkills.isEmpty()) return null- val bundled = activeSkills.filter { it.id !in communityIds }- val community = activeSkills.filter { it.id in communityIds }+ val eligible = activeSkills+ .filter { it.id !in recentlyFetchedSkillIds }+ .filter { skill ->+ if (skill.targetPackageNames.contains("*")) {+ skill.keywords.isNotEmpty() && skill.matchesIntent(lastUserMessage)+ } else {+ skill.matchesIntent(lastUserMessage)+ }+ }+ if (eligible.isEmpty()) return null+ val bundled = eligible.filter { it.id !in communityIds }+ val community = eligible.filter { it.id in communityIds }val sb = StringBuilder()sb.append(HEADER.format(currentPackage))diff --git a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt b/app/src/main/java/com/gotcha/tools/SubAgentSession.ktindex 61bcdf3..19db6bc 100644--- a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt+++ b/app/src/main/java/com/gotcha/tools/SubAgentSession.kt@@ -61,7 +61,7 @@ class SubAgentSession(val messages = buildList {addAll(history)- addAll(activeSkillsMessages(settings.disabledSkills, hiddenTools))+ addAll(activeSkillsMessages(history, settings.disabledSkills, hiddenTools))}val response = try {@@ -287,6 +287,7 @@ class SubAgentSession(DeviceCapabilities.hiddenToolNames(appContext)private fun activeSkillsMessages(+ history: List<ChatMessage>,disabledSkills: Set<String>,hiddenTools: Set<String>): List<ChatMessage> {@@ -294,8 +295,12 @@ class SubAgentSession(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)- ?: return emptyList()+ val message = SkillPromptBuilder.buildFromHistory(+ currentPackage = currentPackage,+ activeSkills = activeSkills,+ communityIds = communityIds,+ history = history+ ) ?: return emptyList()return listOf(message)}diff --git a/app/src/test/java/com/gotcha/agent/PromptCacheAndTokenOptimizationTest.kt b/app/src/test/java/com/gotcha/agent/PromptCacheAndTokenOptimizationTest.ktindex 6fe94c3..fbea458 100644--- a/app/src/test/java/com/gotcha/agent/PromptCacheAndTokenOptimizationTest.kt+++ b/app/src/test/java/com/gotcha/agent/PromptCacheAndTokenOptimizationTest.kt@@ -60,6 +60,192 @@ class PromptCacheAndTokenOptimizationTest {assertTrue("Should return null for empty skills list", msg == null)}+ @Test+ fun `SkillPromptBuilder excludes skills already fetched in history`() {+ val skill1 = Skill(id = "whatsapp_calling", description = "Call skills", instructions = "x")+ val skill2 = Skill(id = "whatsapp_messaging", description = "Message skills", instructions = "y")++ val history = listOf(+ ChatMessage(role = "user", content = kotlinx.serialization.json.JsonPrimitive("Call Mom")),+ ChatMessage(+ role = "tool",+ content = kotlinx.serialization.json.JsonPrimitive(+ "Found 1 skills matching 'calling':\n\nSkill [whatsapp_calling]:\nLine 1"+ )+ )+ )+ val fetched = SkillPromptBuilder.extractFetchedSkillIds(history)+ assertEquals(setOf("whatsapp_calling"), fetched)++ val msg = SkillPromptBuilder.build(+ currentPackage = "com.whatsapp",+ activeSkills = listOf(skill1, skill2),+ communityIds = emptySet(),+ recentlyFetchedSkillIds = fetched+ )+ assertNotNull(msg)+ val text = msg!!.textContent+ assertFalse("Should exclude whatsapp_calling since it was already fetched", text.contains("whatsapp_calling"))+ assertTrue("Should include whatsapp_messaging", text.contains("whatsapp_messaging"))+ }++ @Test+ fun `SkillPromptBuilder extractFetchedSkillIds handles malformed or non-matching tool messages safely`() {+ val history = listOf(+ ChatMessage(role = "user", content = kotlinx.serialization.json.JsonPrimitive("hello")),+ ChatMessage(role = "tool", content = kotlinx.serialization.json.JsonPrimitive("Random tool result")),+ ChatMessage(role = "tool", content = kotlinx.serialization.json.JsonPrimitive(""))+ )+ val fetched = SkillPromptBuilder.extractFetchedSkillIds(history)+ assertTrue("Should return empty set for non-matching tool messages", fetched.isEmpty())+ }++ @Test+ fun `Skill matchesIntent performs case-insensitive word-boundary matching`() {+ val skill = Skill(+ id = "call_skill",+ instructions = "x",+ keywords = listOf("call")+ )+ assertTrue("Should match 'call'", skill.matchesIntent("Call John"))+ assertTrue("Should match lower 'call'", skill.matchesIntent("can you call mom"))+ assertFalse("Should NOT match substring inside 'recall'", skill.matchesIntent("please recall this message"))+ assertFalse("Should NOT match substring inside 'vocaller'", skill.matchesIntent("vocaller app"))+ }++ @Test+ fun `SkillPromptBuilder filters skills by user intent keywords`() {+ val callSkill = Skill(+ id = "whatsapp_call",+ description = "Call features",+ instructions = "x",+ keywords = listOf("call", "phone", "ring")+ )+ val msgSkill = Skill(+ id = "whatsapp_msg",+ description = "Messaging features",+ instructions = "y",+ keywords = listOf("message", "text", "send")+ )++ val callMsg = SkillPromptBuilder.build(+ currentPackage = "com.whatsapp",+ activeSkills = listOf(callSkill, msgSkill),+ communityIds = emptySet(),+ lastUserMessage = "Can you call Alex on WhatsApp?"+ )+ assertNotNull(callMsg)+ assertTrue(callMsg!!.textContent.contains("whatsapp_call"))+ assertFalse(callMsg.textContent.contains("whatsapp_msg"))+ }++ @Test+ fun `Skill matchesIntent handles empty and blank text correctly`() {+ val skillWithKw = Skill(id = "test_kw", instructions = "x", keywords = listOf("call"))+ val skillNoKw = Skill(id = "test_nokw", instructions = "x", keywords = emptyList())++ assertTrue("Skill with keywords matches empty text", skillWithKw.matchesIntent(""))+ assertTrue("Skill with keywords matches blank text", skillWithKw.matchesIntent(" "))+ assertTrue("Skill without keywords matches empty text", skillNoKw.matchesIntent(""))+ }++ @Test+ fun `SkillPromptBuilder extractLastHumanUserMessage skips synthetic screenshot observations`() {+ val history = listOf(+ ChatMessage(+ role = "user",+ content = kotlinx.serialization.json.JsonPrimitive("Send a message on WhatsApp")+ ),+ ChatMessage(+ role = "assistant",+ content = kotlinx.serialization.json.JsonPrimitive("Opening app")+ ),+ ChatMessage(+ role = "user",+ content = kotlinx.serialization.json.JsonPrimitive("[Screen State]\nTurn observation")+ ),+ ChatMessage(+ role = "user",+ content = kotlinx.serialization.json.JsonPrimitive("[Previous screen observation removed]")+ )+ )++ val lastHumanMsg = SkillPromptBuilder.extractLastHumanUserMessage(history)+ assertEquals("Send a message on WhatsApp", lastHumanMsg)+ }++ @Test+ fun `SkillPromptBuilder SKILL_RESULT_REGEX matches ToolExecutor search_skills format`() {+ val toolOutput = "Found 2 skills matching 'test':\n\nSkill [skill_a]:\nLine 1\n\nSkill [skill_b]:\nLine 2"+ val matches = SkillPromptBuilder.SKILL_RESULT_REGEX.findAll(toolOutput).map { it.groupValues[1] }.toList()+ assertEquals(listOf("skill_a", "skill_b"), matches)+ }++ @Test+ fun `SkillPromptBuilder buildFromHistory integrates history extraction and intent filtering`() {+ val skillCall = Skill(id = "call_skill", instructions = "x", keywords = listOf("call"))+ val skillMsg = Skill(id = "msg_skill", instructions = "y", keywords = listOf("send"))++ val history = listOf(+ ChatMessage(+ role = "user",+ content = kotlinx.serialization.json.JsonPrimitive("Please call Alex")+ ),+ ChatMessage(+ role = "tool",+ content = kotlinx.serialization.json.JsonPrimitive(+ "Found 1 skills:\n\nSkill [call_skill]:\nBody"+ )+ )+ )++ val msg = SkillPromptBuilder.buildFromHistory(+ currentPackage = "com.whatsapp",+ activeSkills = listOf(skillCall, skillMsg),+ communityIds = emptySet(),+ history = history+ )++ // call_skill is excluded because it's in history; msg_skill is excluded because user said "call", not "send"+ assertTrue("Should return null when all skills are excluded by history or intent", msg == null)+ }++ @Test+ fun `SkillPromptBuilder demotes unqualified wildcard skills to search-only`() {+ val wildcardNoKw = Skill(+ id = "wildcard_unqualified",+ targetPackageNames = listOf("*"),+ description = "Generic wildcard skill",+ instructions = "x",+ keywords = emptyList()+ )+ val wildcardWithKw = Skill(+ id = "wildcard_qualified",+ targetPackageNames = listOf("*"),+ description = "Specific wildcard skill",+ instructions = "y",+ keywords = listOf("special")+ )++ val result1 = SkillPromptBuilder.build(+ currentPackage = "com.example.any",+ activeSkills = listOf(wildcardNoKw, wildcardWithKw),+ communityIds = emptySet(),+ lastUserMessage = "General task"+ )+ assertTrue("Should return null when no wildcard skills match intent", result1 == null)++ val result2 = SkillPromptBuilder.build(+ currentPackage = "com.example.any",+ activeSkills = listOf(wildcardNoKw, wildcardWithKw),+ communityIds = emptySet(),+ lastUserMessage = "Do a special action"+ )+ assertNotNull(result2)+ assertFalse(result2!!.textContent.contains("wildcard_unqualified"))+ assertTrue(result2.textContent.contains("wildcard_qualified"))+ }+@Testfun `AgentEngine cullOldObservations retains 4 most recent screen observations and culls older ones`() {val messages = mutableListOf<ChatMessage>()diff --git a/app/src/test/java/com/gotcha/agent/skills/SkillRegistryTest.kt b/app/src/test/java/com/gotcha/agent/skills/SkillRegistryTest.ktindex 4958a6e..fccf1d4 100644--- a/app/src/test/java/com/gotcha/agent/skills/SkillRegistryTest.kt+++ b/app/src/test/java/com/gotcha/agent/skills/SkillRegistryTest.kt@@ -61,6 +61,7 @@ class SkillRegistryTest {val community = SkillRegistry.getCommunitySkills()assertEquals(1, community.size)assertEquals("im_community_skill", community[0].id)+ assertTrue("keywords should default to empty list when missing in JSON", community[0].keywords.isEmpty())}@Test