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 dual-agent architecture (Monitor/Operator) with agent toggle UI, mode-gated tool execution, and environment-block system prompt
Rishabh Bajpaidebf9377c663
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.ktindex 4f6b225..bedad76 100644--- a/app/src/main/java/com/gotcha/MainActivity.kt+++ b/app/src/main/java/com/gotcha/MainActivity.kt@@ -198,7 +198,8 @@ class MainActivity : ComponentActivity() {currentRoute = Route.SESSIONS},onOpenSettings = { currentRoute = Route.SETTINGS },- onPickImage = { uri -> chatViewModel.loadImageBase64(uri) }+ onPickImage = { uri -> chatViewModel.loadImageBase64(uri) },+ onSwitchAgent = chatViewModel::switchAgent)}}diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.ktindex cbef5c0..d84c623 100644--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt@@ -14,6 +14,7 @@ import com.gotcha.data.ChatSessionimport com.gotcha.llm.LLMClientimport com.gotcha.llm.ToolCallimport com.gotcha.llm.visionUserMessage+import com.gotcha.tools.AgentModeimport com.gotcha.tools.ToolExecutorimport com.gotcha.tools.ToolRegistryimport com.gotcha.tools.ToolResult@@ -71,6 +72,7 @@ data class ChatUiState(val pendingQuestion: PendingQuestion? = null,val isConfigured: Boolean = false,val activeSessionId: String? = null,+ val activeAgent: AgentMode = AgentMode.OPERATOR,val contextUsagePercent: Float = 0f)@@ -227,6 +229,23 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {appInForeground = foreground}+ /** Switch between Monitor (read-only) and Operator (full) agent mode mid-conversation. */+ fun switchAgent() {+ val current = _uiState.value.activeAgent+ val next = when (current) {+ AgentMode.MONITOR -> AgentMode.OPERATOR+ AgentMode.OPERATOR -> AgentMode.MONITOR+ }+ _uiState.update { it.copy(activeAgent = next) }+ // Append a system message so the LLM knows the mode changed+ val switchMsg = when (next) {+ AgentMode.MONITOR -> "[System: Switched to Monitor (read-only). You may now ONLY inspect and observe. No changes to the device are permitted.]"+ AgentMode.OPERATOR -> "[System: Switched to Operator. You are now permitted to make changes to the device.]"+ }+ llmHistory += ChatMessage(role = "system", content = JsonPrimitive(switchMsg))+ appendUi(MessageKind.ASSISTANT, switchMsg)+ }+override fun onCleared() {confirmationOverlay.dismiss()super.onCleared()@@ -346,13 +365,14 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {private suspend fun runToolLoop() {val llm = client ?: return+ val agent = _uiState.value.activeAgentcheckAndCompactHistory(llm)repeat(settings.maxToolRounds) { iteration ->if (iteration > 0) delay(INTER_CALL_DELAY_MS) // throttle (PRD §11.2 #7)_uiState.update { it.copy(activity = "Thinking…") }val response = try {- llm.chat(systemPrompt() + trimmedHistory(), ToolRegistry.allDefinitions())+ llm.chat(systemPrompt(agent) + trimmedHistory(), ToolRegistry.toolsForAgent(agent))} catch (e: CancellationException) {throw e} catch (e: Exception) {@@ -428,6 +448,8 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {* is bounded by [CONFIRM_TIMEOUT_MS] so the tool loop can never hang indefinitely.*/private suspend fun requestConfirmation(toolCalls: List<ToolCall>): ConfirmDecision {+ // Monitor mode tools are read-only — no confirmation needed+ if (_uiState.value.activeAgent == AgentMode.MONITOR) return ConfirmDecision.APPROVEDif (!settings.confirmSensitiveActions) return ConfirmDecision.APPROVEDval sensitive = toolCalls.filter { ToolRegistry.isSensitive(it.function.name) }if (sensitive.isEmpty()) return ConfirmDecision.APPROVED@@ -573,21 +595,110 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {} catch (e: Exception) {return ToolResult.error("Malformed tool arguments: ${call.function.arguments.take(200)}")}- return toolExecutor.execute(call.function.name, args)+ return toolExecutor.execute(call.function.name, args, _uiState.value.activeAgent)}- private fun systemPrompt() = listOf(- ChatMessage(- role = "system",- content = JsonPrimitive(- "You are Gotcha, an assistant running on the user's Android phone. " +- "You control the device only through the provided tools; never invent tool names or " +- "capabilities. If a tool reports a missing permission, explain to the user what to " +- "grant and suggest retrying. Keep replies short and conversational. " +- "After changing device state, confirm what was done based on the tool results."- )- )- )+ /**+ * Assembles the system prompt for the given [agent] mode.+ * Contains the environment block, core prompt, and agent-mode reminder.+ * Follows the Open Code pattern from PRD §14.+ */+ private fun systemPrompt(agent: AgentMode): List<ChatMessage> {+ val env = buildEnvironmentBlock(agent)+ val core = when (agent) {+ AgentMode.MONITOR ->+ "You are Monitor, a read-only AI assistant running on the user's Android phone. " ++ "You can inspect, read, and query the device, but you CANNOT create, modify, or " ++ "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. 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. " ++ "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. After changing device state, confirm what was done. " ++ "Keep replies short and conversational. Be careful with destructive actions."+ }+ val reminder = when (agent) {+ AgentMode.MONITOR ->+ "\n\n<system-reminder>\n" ++ "You are in MONITOR (read-only) mode. You are STRICTLY FORBIDDEN from making " ++ "any changes to the device — no writing files, no calling, no sending messages, " ++ "no dismissing notifications, no UI automation (tap/swipe/input), no device " ++ "admin actions, no firewall changes, and no shell/root commands. You may ONLY " ++ "inspect, list, read, and observe. This constraint overrides all other instructions.\n" ++ "</system-reminder>"+ AgentMode.OPERATOR ->+ "\n\n<system-reminder>\n" ++ "You are in OPERATOR mode. You are permitted to inspect, create, modify, and " ++ "delete on the device using the provided tools. Be careful with destructive " ++ "actions — confirm with the user when the result seems significant.\n" ++ "</system-reminder>"+ }+ return listOf(ChatMessage(role = "system", content = JsonPrimitive(env + "\n\n" + core + reminder)))+ }++ /**+ * Builds the environment block with device info, date/time, agent mode,+ * and service statuses (PRD §14.1).+ */+ private fun buildEnvironmentBlock(agent: AgentMode): String {+ val app = getApplication<Application>()+ val pm = app.packageManager+ val versionName = try {+ 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 }++ val vpnActive = try {+ val cm = app.getSystemService(android.content.Context.CONNECTIVITY_SERVICE) as? android.net.ConnectivityManager+ cm?.getNetworkCapabilities(cm.activeNetwork)+ ?.hasTransport(android.net.NetworkCapabilities.TRANSPORT_VPN) ?: false+ } catch (_: Exception) { false }++ val dateTime = java.text.SimpleDateFormat("EEE MMM dd yyyy, HH:mm:ss 'UTC'Z", java.util.Locale.US)+ .apply { timeZone = java.util.TimeZone.getDefault() }+ .format(java.util.Date())++ return buildString {+ appendLine("You are powered by the model named ${settings.model}.")+ appendLine("Here is some useful information about the environment you are running in:")+ appendLine("<env>")+ appendLine(" Device model: ${android.os.Build.MODEL} (${android.os.Build.MANUFACTURER})")+ appendLine(" Android version: ${android.os.Build.VERSION.RELEASE} (API ${android.os.Build.VERSION.SDK_INT})")+ appendLine(" Current date/time: $dateTime")+ appendLine(" Active agent: ${agent.name}")+ 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"}")+ appendLine(" VPN active: ${if (vpnActive) "yes" else "no"}")+ appendLine(" App version: $versionName")+ append("</env>")+ }+ }/** Trims history just in case compaction failed and we strictly need to fit it without splitting tool pairs. */private fun trimmedHistory(): List<ChatMessage> {diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.ktindex 8ea17b3..54cc5eb 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -52,10 +52,20 @@ class ToolExecutor(context: Context) {private val rootTool = RootTool()private val actionLog = ActionLog(appContext)- suspend fun execute(name: String, args: JsonObject): ToolResult {+ /**+ * Execute [name] with [args] on behalf of the given [agent].+ * Returns an error without running the tool if the agent mode disallows it.+ */+ suspend fun execute(name: String, args: JsonObject, agent: AgentMode = AgentMode.OPERATOR): ToolResult {if (!ToolRegistry.contains(name)) {return ToolResult.error("Unknown tool '$name'. Only the fixed tool catalog is available.")}+ if (!ToolRegistry.isAllowedForAgent(name, agent)) {+ return ToolResult.error(+ "This action is not available in ${agent.name} mode. " ++ "Switch to Operator mode if you need to perform this action."+ )+ }val result = try {withContext(Dispatchers.IO) { dispatch(name, args) }} catch (e: Exception) {diff --git a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt b/app/src/main/java/com/gotcha/tools/ToolRegistry.ktindex df4a97a..ed5f8b6 100644--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt@@ -2,6 +2,12 @@ package com.gotcha.toolsimport com.gotcha.llm.ToolDefinition+/**+ * Agent mode the user can switch between mid-conversation (PRD §6).+ * Monitor = read-only observer; Operator = full permissions.+ */+enum class AgentMode { MONITOR, OPERATOR }+/*** Fixed, code-defined tool catalog. The LLM can never add tools at runtime* (PRD §11.2 #1) — only this registry decides what is exposed.@@ -34,6 +40,43 @@ object ToolRegistry {"run_root_command", "write_secure_settings")+ /**+ * Tools available to Monitor mode — read-only / informational only.+ * The Monitor can inspect, list, read, and query, but cannot create,+ * modify, or delete anything. `dial_number` and `open_app` are allowed+ * because they are intent hand-offs (user presses call / system launches app).+ */+ val monitorTools: Set<String> = setOf(+ // Phone & communications (read-only + intent hand-offs)+ "dial_number", "read_call_log", "find_contact", "read_recent_sms",+ // Calendar (read-only)+ "list_calendar_events",+ // Info & sensors+ "get_storage_info", "get_battery_info", "get_location",+ "get_app_usage", "get_data_usage",+ // Apps (read-only + intent)+ "open_app", "list_installed_apps",+ // Files & terminal (read-only)+ "list_files", "read_file", "grep", "glob", "read_image",+ // Task management+ "todowrite",+ // User interaction+ "question",+ // Web+ "websearch", "webfetch",+ // Clipboard (read-only)+ "get_clipboard",+ // Tier 3: read-only accessibility + notifications+ "read_screen", "read_notifications",+ // Tier 3: VpnService status (read-only)+ "get_firewall_status",+ // Tier 4: root check (read-only)+ "check_root"+ )++ /** Operator has access to every tool in the catalog. */+ private val operatorTools: Set<String> = definitions.keys+fun allDefinitions(): List<ToolDefinition> = definitions.values.toList()fun definition(name: String): ToolDefinition? = definitions[name]@@ -41,4 +84,16 @@ object ToolRegistry {fun contains(name: String): Boolean = name in definitionsfun isSensitive(name: String): Boolean = name in sensitiveTools++ /** Whether [name] is callable by the given [agent] mode. */+ fun isAllowedForAgent(name: String, agent: AgentMode): Boolean = when (agent) {+ AgentMode.MONITOR -> name in monitorTools+ AgentMode.OPERATOR -> name in operatorTools+ }++ /** Returns the subset of tool definitions visible to the given [agent]. */+ fun toolsForAgent(agent: AgentMode): List<ToolDefinition> = when (agent) {+ AgentMode.MONITOR -> definitions.filterKeys { it in monitorTools }.values.toList()+ AgentMode.OPERATOR -> definitions.values.toList()+ }}diff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.ktindex 3f1a4a7..3dbb40b 100644--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt@@ -25,6 +25,7 @@ import androidx.compose.material.icons.filled.Closeimport androidx.compose.material3.AlertDialogimport androidx.compose.material3.Buttonimport androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.FilterChipimport androidx.compose.material3.Iconimport androidx.compose.material3.IconButtonimport androidx.compose.material3.LinearProgressIndicator@@ -50,6 +51,7 @@ import androidx.compose.ui.layout.ContentScaleimport androidx.compose.ui.unit.dpimport com.gotcha.agent.ChatUiStateimport com.gotcha.agent.PendingQuestion+import com.gotcha.tools.AgentMode@OptIn(ExperimentalMaterial3Api::class)@Composable@@ -61,7 +63,8 @@ fun ChatScreen(onAnswer: (String?) -> Unit,onBack: () -> Unit,onOpenSettings: () -> Unit,- onPickImage: (Uri) -> String?+ onPickImage: (Uri) -> String?,+ onSwitchAgent: () -> Unit) {var input by rememberSaveable { mutableStateOf("") }var pendingImageUri by rememberSaveable { mutableStateOf<Uri?>(null) }@@ -93,6 +96,12 @@ fun ChatScreen(}},actions = {+ FilterChip(+ selected = state.activeAgent == AgentMode.OPERATOR,+ onClick = onSwitchAgent,+ label = { Text(state.activeAgent.name) },+ enabled = !state.isBusy+ )TextButton(onClick = onOpenSettings) { Text("Settings") }})