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.
Add Tier 3 tools for enhanced device control and accessibility
Durganshu Mishrafd10fe52dbc0
diff --git a/RUNNING.md b/RUNNING.mdindex eaba85e..f7406e8 100644--- a/RUNNING.md+++ b/RUNNING.md@@ -113,6 +113,12 @@ Type natural-language requests. Examples:- **Sensitive actions** (dial, wallpaper, cache clear, write file, run command,set brightness) pop an **Allow / Deny** dialog. You can disable this inSettings → *Confirm sensitive actions*.+- **Confirmations while another app is in front** (e.g. the accessibility tools+ after `open_app` hands control to Settings): the Allow / Deny prompt is drawn as a+ **floating overlay on top of that app**, so it stays visible and the agent doesn't+ block behind it. This needs the **"Display over other apps"** permission — grant it+ once for Gotcha, otherwise the confirmation falls back to the in-app dialog and,+ if it can't be shown, times out after 60 s (treated as a decline) rather than hanging.- **Permissions** are requested on first use. If you deny one, the assistantexplains what's needed instead of crashing. Two need manual grants:- **Storage** (reading Downloads/Pictures/etc.): a standard runtime prompt.diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex 74da230..dbfe455 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -34,6 +34,13 @@android:name="android.permission.PACKAGE_USAGE_STATS"tools:ignore="ProtectedPermissions" />+ <!-- Tier 3: component-based / device-wide special access -->+ <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />+ <uses-permission+ android:name="android.permission.MANAGE_EXTERNAL_STORAGE"+ tools:ignore="ScopedStorage" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+<!-- Needed on API 30+ so open_app can see other launchable apps. --><queries><intent>@@ -70,6 +77,46 @@android:name="android.support.FILE_PROVIDER_PATHS"android:resource="@xml/file_paths" /></provider>++ <!-- Tier 3: AccessibilityService — drives other apps' UIs (user enables in Settings). -->+ <service+ android:name=".service.GotchaAccessibilityService"+ android:exported="false"+ android:label="@string/app_name"+ android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">+ <intent-filter>+ <action android:name="android.accessibilityservice.AccessibilityService" />+ </intent-filter>+ <meta-data+ android:name="android.accessibilityservice"+ android:resource="@xml/accessibility_service_config" />+ </service>++ <!-- Tier 3: NotificationListenerService — reads/dismisses notifications, media control. -->+ <service+ android:name=".service.GotchaNotificationListenerService"+ android:exported="false"+ android:label="@string/app_name"+ android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">+ <intent-filter>+ <action android:name="android.service.notification.NotificationListenerService" />+ </intent-filter>+ </service>++ <!-- Tier 3: Device Admin — lock screen, password policy, disable camera. -->+ <receiver+ android:name=".service.GotchaDeviceAdminReceiver"+ android:exported="true"+ android:description="@string/device_admin_description"+ android:label="@string/app_name"+ android:permission="android.permission.BIND_DEVICE_ADMIN">+ <meta-data+ android:name="android.app.device_admin"+ android:resource="@xml/device_admin" />+ <intent-filter>+ <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />+ </intent-filter>+ </receiver></application></manifest>diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.ktindex f605f4e..d106727 100644--- a/app/src/main/java/com/gotcha/MainActivity.kt+++ b/app/src/main/java/com/gotcha/MainActivity.kt@@ -1,7 +1,9 @@package com.gotcha+import android.app.admin.DevicePolicyManagerimport android.content.Intentimport android.net.Uri+import android.os.Buildimport android.os.Bundleimport android.provider.Settings as AndroidSettingsimport android.widget.Toast@@ -26,6 +28,7 @@ import com.gotcha.data.Settingsimport com.gotcha.data.SettingsRepositoryimport com.gotcha.llm.ChatMessageimport com.gotcha.llm.LLMClient+import com.gotcha.service.GotchaDeviceAdminReceiverimport com.gotcha.tools.ToolResultimport com.gotcha.ui.ChatScreenimport com.gotcha.ui.SettingsScreen@@ -69,6 +72,35 @@ class MainActivity : ComponentActivity() {ToolResult.DND_ACCESS -> startActivity(Intent(AndroidSettings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS))+ ToolResult.ACCESSIBILITY_ACCESS -> startActivity(+ Intent(AndroidSettings.ACTION_ACCESSIBILITY_SETTINGS)+ )+ ToolResult.NOTIFICATION_LISTENER_ACCESS -> startActivity(+ Intent(AndroidSettings.ACTION_NOTIFICATION_LISTENER_SETTINGS)+ )+ ToolResult.ALL_FILES_ACCESS -> startActivity(+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) Intent(+ AndroidSettings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,+ Uri.parse("package:$packageName")+ ) else Intent(AndroidSettings.ACTION_APPLICATION_DETAILS_SETTINGS,+ Uri.parse("package:$packageName"))+ )+ ToolResult.OVERLAY_ACCESS -> startActivity(+ Intent(+ AndroidSettings.ACTION_MANAGE_OVERLAY_PERMISSION,+ Uri.parse("package:$packageName")+ )+ )+ ToolResult.DEVICE_ADMIN -> startActivity(+ Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN).putExtra(+ DevicePolicyManager.EXTRA_DEVICE_ADMIN,+ GotchaDeviceAdminReceiver.componentName(this@MainActivity)+ ).putExtra(+ DevicePolicyManager.EXTRA_ADD_EXPLANATION,+ "Gotcha uses device administration to lock the screen, enforce " ++ "password policy, and disable the camera when you ask it to."+ )+ )else -> permissionLauncher.launch(permission)}}@@ -86,6 +118,16 @@ class MainActivity : ComponentActivity() {}}+ override fun onStart() {+ super.onStart()+ chatViewModel.setForeground(true)+ }++ override fun onStop() {+ super.onStop()+ chatViewModel.setForeground(false)+ }+@Composableprivate fun GotchaApp() {val state by chatViewModel.uiState.collectAsState()diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.ktindex 1fe42ed..181f781 100644--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt@@ -12,8 +12,10 @@ import com.gotcha.llm.ToolCallimport com.gotcha.tools.ToolExecutorimport com.gotcha.tools.ToolRegistryimport com.gotcha.tools.ToolResult+import com.gotcha.ui.ConfirmationOverlayimport kotlinx.coroutines.CompletableDeferredimport kotlinx.coroutines.delay+import kotlinx.coroutines.withTimeoutOrNullimport kotlinx.coroutines.flow.MutableSharedFlowimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.SharedFlow@@ -27,6 +29,9 @@ import kotlinx.serialization.json.JsonObjectenum class MessageKind { USER, ASSISTANT, TOOL, ERROR }+/** Outcome of the sensitive-action confirmation step. */+private enum class ConfirmDecision { APPROVED, DENIED, TIMED_OUT }+data class UiMessage(val id: Long,val kind: MessageKind,@@ -52,11 +57,16 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {private val settingsRepository = SettingsRepository(application)private val historyRepository = ChatHistoryRepository(application)private val toolExecutor = ToolExecutor(application)+ private val confirmationOverlay = ConfirmationOverlay(application)private val json = Json { ignoreUnknownKeys = true }private var settings: Settings = Settings()private var client: LLMClient? = null+ /** Set by the Activity in onStart/onStop; drives whether confirmations use the overlay. */+ @Volatile+ private var appInForeground = true+/** LLM-shaped history (excludes the system prompt, which is prepended per call). */private val llmHistory = mutableListOf<ChatMessage>()private var nextId = 0L@@ -117,6 +127,16 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {confirmationGate = null}+ /** Called from the Activity's onStart/onStop so confirmations know if they'd be hidden. */+ fun setForeground(foreground: Boolean) {+ appInForeground = foreground+ }++ override fun onCleared() {+ confirmationOverlay.dismiss()+ super.onCleared()+ }+fun clearChat() {if (_uiState.value.isBusy) returnllmHistory.clear()@@ -156,10 +176,17 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {message.content?.takeIf { it.isNotBlank() }?.let { appendUi(MessageKind.ASSISTANT, it) }- val approved = requestConfirmationIfNeeded(toolCalls)+ val decision = requestConfirmation(toolCalls)for (call in toolCalls) {- val result = if (approved) executeCall(call)- else ToolResult.error("The user declined to run '${call.function.name}'. Do not retry.")+ val result = when (decision) {+ ConfirmDecision.APPROVED -> executeCall(call)+ ConfirmDecision.DENIED ->+ ToolResult.error("The user declined to run '${call.function.name}'. Do not retry.")+ ConfirmDecision.TIMED_OUT -> ToolResult.error(+ "Confirmation for '${call.function.name}' timed out with no response. " ++ "Do not retry automatically; tell the user to ask again when ready."+ )+ }llmHistory += ChatMessage(role = "tool",content = result.message,@@ -179,25 +206,53 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {)}- private suspend fun requestConfirmationIfNeeded(toolCalls: List<ToolCall>): Boolean {- if (!settings.confirmSensitiveActions) return true+ /**+ * Gates sensitive tool calls behind user approval. When Gotcha is in the+ * foreground the in-app Compose dialog is used; when it has been backgrounded (e.g.+ * after `open_app` launched another app) a floating overlay is shown instead so the+ * prompt is visible over that app rather than hidden behind it. Either way the wait+ * is bounded by [CONFIRM_TIMEOUT_MS] so the tool loop can never hang indefinitely.+ */+ private suspend fun requestConfirmation(toolCalls: List<ToolCall>): ConfirmDecision {+ if (!settings.confirmSensitiveActions) return ConfirmDecision.APPROVEDval sensitive = toolCalls.filter { ToolRegistry.isSensitive(it.function.name) }- if (sensitive.isEmpty()) return true+ if (sensitive.isEmpty()) return ConfirmDecision.APPROVED++ val names = sensitive.map { it.function.name }+ val description = sensitive.joinToString("\n") { c ->+ "${c.function.name}(${c.function.arguments.take(200)})"+ }val gate = CompletableDeferred<Boolean>()confirmationGate = gate- _uiState.update {- it.copy(- activity = null,- pendingConfirmation = PendingConfirmation(- toolNames = sensitive.map { c -> c.function.name },- description = sensitive.joinToString("\n") { c ->- "${c.function.name}(${c.function.arguments.take(200)})"- }- )++ val useOverlay = !appInForeground && confirmationOverlay.canShow()+ if (useOverlay) {+ confirmationOverlay.show(+ summary = "Allow these actions?\n$description",+ onAllow = { confirmPendingActions(true) },+ onDeny = { confirmPendingActions(false) })+ } else {+ _uiState.update {+ it.copy(+ activity = null,+ pendingConfirmation = PendingConfirmation(names, description)+ )+ }+ }++ val approved = withTimeoutOrNull(CONFIRM_TIMEOUT_MS) { gate.await() }++ confirmationOverlay.dismiss()+ _uiState.update { it.copy(pendingConfirmation = null) }+ confirmationGate = null++ return when (approved) {+ true -> ConfirmDecision.APPROVED+ false -> ConfirmDecision.DENIED+ null -> ConfirmDecision.TIMED_OUT}- return gate.await()}private suspend fun executeCall(call: ToolCall): ToolResult {@@ -262,5 +317,6 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {const val MAX_ITERATIONS = 6const val MAX_HISTORY_MESSAGES = 40const val INTER_CALL_DELAY_MS = 400L+ const val CONFIRM_TIMEOUT_MS = 60_000L}}diff --git a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.ktnew file mode 100644index 0000000..b25e5cf--- /dev/null+++ b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt@@ -0,0 +1,140 @@+package com.gotcha.service++import android.accessibilityservice.AccessibilityService+import android.accessibilityservice.GestureDescription+import android.graphics.Path+import android.os.Build+import android.view.accessibility.AccessibilityEvent+import android.view.accessibility.AccessibilityNodeInfo++/**+ * Tier 3 — AccessibilityService.+ *+ * The single biggest capability jump on the ladder: once the user enables this in+ * Settings → Accessibility, the app can read the on-screen text of any app and+ * perform taps/swipes/typing/global gestures on its behalf.+ *+ * The service exposes itself through a static [instance] so the (stateless)+ * [com.gotcha.tools.AccessibilityTool] can reach the live, bound service. The+ * service is only alive while the user has it enabled; the tool checks [instance]+ * for null and returns a permission hint otherwise.+ */+class GotchaAccessibilityService : AccessibilityService() {++ override fun onServiceConnected() {+ super.onServiceConnected()+ instance = this+ }++ // Passive: we drive the UI on demand from tools rather than reacting to events.+ override fun onAccessibilityEvent(event: AccessibilityEvent?) {}++ override fun onInterrupt() {}++ override fun onUnbind(intent: android.content.Intent?): Boolean {+ instance = null+ return super.onUnbind(intent)+ }++ override fun onDestroy() {+ if (instance === this) instance = null+ super.onDestroy()+ }++ // ---- Capabilities used by AccessibilityTool ----++ /** Recursively collect visible, non-blank text/content-descriptions from the active window. */+ fun dumpScreenText(limit: Int = 200): List<String> {+ val root = rootInActiveWindow ?: return emptyList()+ val out = ArrayList<String>()+ collectText(root, out, limit)+ root.recycle()+ return out+ }++ private fun collectText(node: AccessibilityNodeInfo?, out: MutableList<String>, limit: Int) {+ if (node == null || out.size >= limit) return+ val text = node.text?.toString()?.trim()+ val desc = node.contentDescription?.toString()?.trim()+ if (!text.isNullOrEmpty()) out.add(text)+ else if (!desc.isNullOrEmpty()) out.add(desc)+ for (i in 0 until node.childCount) {+ collectText(node.getChild(i), out, limit)+ }+ }++ /** Tap the first clickable node whose text/description contains [query] (case-insensitive). */+ fun tapByText(query: String): Boolean {+ val root = rootInActiveWindow ?: return false+ val match = findClickable(root, query.lowercase())+ val performed = match?.performAction(AccessibilityNodeInfo.ACTION_CLICK) ?: false+ root.recycle()+ return performed+ }++ private fun findClickable(node: AccessibilityNodeInfo?, query: String): AccessibilityNodeInfo? {+ if (node == null) return null+ val hay = ((node.text?.toString() ?: "") + " " + (node.contentDescription?.toString() ?: ""))+ .lowercase()+ if (hay.contains(query)) {+ var candidate: AccessibilityNodeInfo? = node+ while (candidate != null && !candidate.isClickable) candidate = candidate.parent+ if (candidate != null) return candidate+ }+ for (i in 0 until node.childCount) {+ findClickable(node.getChild(i), query)?.let { return it }+ }+ return null+ }++ /** Type [text] into the currently focused editable field. */+ fun typeText(text: String): Boolean {+ val focused = findFocus(AccessibilityNodeInfo.FOCUS_INPUT) ?: return false+ val args = android.os.Bundle().apply {+ putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, text)+ }+ val ok = focused.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, args)+ focused.recycle()+ return ok+ }++ /** Dispatch a tap gesture at absolute screen coordinates (API 24+). */+ fun tapAt(x: Float, y: Float): Boolean = gesture(x, y, x, y, 50)++ /** Dispatch a swipe gesture between two points. */+ fun swipe(x1: Float, y1: Float, x2: Float, y2: Float, durationMs: Long = 300): Boolean =+ gesture(x1, y1, x2, y2, durationMs)++ private fun gesture(x1: Float, y1: Float, x2: Float, y2: Float, durationMs: Long): Boolean {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return false+ val path = Path().apply {+ moveTo(x1, y1)+ lineTo(x2, y2)+ }+ val stroke = GestureDescription.StrokeDescription(path, 0, durationMs.coerceIn(1, 60_000))+ val gesture = GestureDescription.Builder().addStroke(stroke).build()+ return dispatchGesture(gesture, null, null)+ }++ /** Perform a global action by name; returns false for unknown names. */+ fun performGlobal(action: String): Boolean {+ val code = when (action.lowercase().trim()) {+ "back" -> GLOBAL_ACTION_BACK+ "home" -> GLOBAL_ACTION_HOME+ "recents", "recent_apps" -> GLOBAL_ACTION_RECENTS+ "notifications" -> GLOBAL_ACTION_NOTIFICATIONS+ "quick_settings" -> GLOBAL_ACTION_QUICK_SETTINGS+ "lock_screen" ->+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) GLOBAL_ACTION_LOCK_SCREEN else -1+ else -> -1+ }+ return if (code >= 0) performGlobalAction(code) else false+ }++ companion object {+ /** The live service instance while the user has it enabled; null otherwise. */+ @Volatile+ var instance: GotchaAccessibilityService? = null+ private set+ }+}diff --git a/app/src/main/java/com/gotcha/service/GotchaDeviceAdminReceiver.kt b/app/src/main/java/com/gotcha/service/GotchaDeviceAdminReceiver.ktnew file mode 100644index 0000000..3954f3c--- /dev/null+++ b/app/src/main/java/com/gotcha/service/GotchaDeviceAdminReceiver.kt@@ -0,0 +1,20 @@+package com.gotcha.service++import android.app.admin.DeviceAdminReceiver+import android.content.ComponentName+import android.content.Context++/**+ * Tier 3 — Device Admin component. Once the user activates it (via+ * ACTION_ADD_DEVICE_ADMIN), [com.gotcha.tools.DeviceAdminTool] can lock the+ * screen, enforce password policy, and disable the camera through DevicePolicyManager.+ *+ * Remote wipe is deliberately NOT wired up: it would irreversibly destroy the user's+ * real device, which is out of scope for this assistant.+ */+class GotchaDeviceAdminReceiver : DeviceAdminReceiver() {+ companion object {+ fun componentName(context: Context): ComponentName =+ ComponentName(context, GotchaDeviceAdminReceiver::class.java)+ }+}diff --git a/app/src/main/java/com/gotcha/service/GotchaNotificationListenerService.kt b/app/src/main/java/com/gotcha/service/GotchaNotificationListenerService.ktnew file mode 100644index 0000000..3e9b4ef--- /dev/null+++ b/app/src/main/java/com/gotcha/service/GotchaNotificationListenerService.kt@@ -0,0 +1,55 @@+package com.gotcha.service++import android.service.notification.NotificationListenerService+import android.service.notification.StatusBarNotification++/**+ * Tier 3 — NotificationListenerService.+ *+ * Once the user grants Notification access, this service can read and dismiss the+ * notifications of every app. Like the accessibility service it publishes a static+ * [instance] so the stateless [com.gotcha.tools.NotificationTool] can query the+ * live, bound service; when the user has not granted access the instance is null.+ */+class GotchaNotificationListenerService : NotificationListenerService() {++ override fun onListenerConnected() {+ super.onListenerConnected()+ instance = this+ }++ override fun onListenerDisconnected() {+ instance = null+ super.onListenerDisconnected()+ }++ override fun onDestroy() {+ if (instance === this) instance = null+ super.onDestroy()+ }++ // We don't need to react to posts/removals; tools pull on demand.+ override fun onNotificationPosted(sbn: StatusBarNotification?) {}+ override fun onNotificationRemoved(sbn: StatusBarNotification?) {}++ /** Snapshot of the currently-active notifications (safe wrapper around the platform call). */+ fun currentNotifications(): Array<StatusBarNotification> =+ try {+ activeNotifications ?: emptyArray()+ } catch (_: Exception) {+ emptyArray()+ }++ /** Dismiss a single notification by its platform key. */+ fun dismiss(key: String) = cancelNotification(key)++ /** Dismiss all dismissible notifications. */+ fun dismissAll() = cancelAllNotifications()++ companion object {+ /** The live service instance while the user has granted access; null otherwise. */+ @Volatile+ var instance: GotchaNotificationListenerService? = null+ private set+ }+}diff --git a/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt b/app/src/main/java/com/gotcha/tools/AccessibilityTool.ktnew file mode 100644index 0000000..43c328c--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt@@ -0,0 +1,105 @@+package com.gotcha.tools++import android.content.Context+import android.provider.Settings+import android.text.TextUtils+import com.gotcha.service.GotchaAccessibilityService++/**+ * Tier 3 — drives arbitrary app UIs through the [GotchaAccessibilityService].+ *+ * Every method first checks that the service is actually enabled and bound; if not+ * it returns [ToolResult.permissionNeeded] with the [ToolResult.ACCESSIBILITY_ACCESS]+ * marker so the UI can deep-link the user to Settings → Accessibility.+ */+class AccessibilityTool(private val context: Context) {++ /** Read the visible on-screen text of whatever app is in the foreground. */+ fun readScreen(): ToolResult {+ val service = requireService() ?: return notEnabled()+ val lines = service.dumpScreenText()+ return if (lines.isEmpty()) {+ ToolResult.ok("No readable text is on screen right now.")+ } else {+ ToolResult.ok("On-screen text (${lines.size} items):\n" + lines.joinToString("\n") { "- $it" })+ }+ }++ /** Tap either an on-screen element matching [text], or absolute coordinates. */+ fun tap(text: String?, x: Int?, y: Int?): ToolResult {+ val service = requireService() ?: return notEnabled()+ return when {+ !text.isNullOrBlank() ->+ if (service.tapByText(text)) ToolResult.ok("Tapped an element matching \"$text\".")+ else ToolResult.error("Found no clickable element matching \"$text\" on screen.")+ x != null && y != null ->+ if (service.tapAt(x.toFloat(), y.toFloat())) ToolResult.ok("Tapped at ($x, $y).")+ else ToolResult.error("Could not dispatch the tap gesture.")+ else -> ToolResult.error("Provide either 'text' to match, or both 'x' and 'y' coordinates.")+ }+ }++ /** Swipe in a named direction, or between explicit coordinates. */+ fun swipe(direction: String?, x1: Int?, y1: Int?, x2: Int?, y2: Int?): ToolResult {+ val service = requireService() ?: return notEnabled()+ if (x1 != null && y1 != null && x2 != null && y2 != null) {+ return if (service.swipe(x1.toFloat(), y1.toFloat(), x2.toFloat(), y2.toFloat()))+ ToolResult.ok("Swiped from ($x1, $y1) to ($x2, $y2).")+ else ToolResult.error("Could not dispatch the swipe gesture.")+ }+ val metrics = context.resources.displayMetrics+ val w = metrics.widthPixels.toFloat()+ val h = metrics.heightPixels.toFloat()+ val (sx, sy, ex, ey) = when (direction?.lowercase()?.trim()) {+ "up" -> listOf(w / 2, h * 0.7f, w / 2, h * 0.3f)+ "down" -> listOf(w / 2, h * 0.3f, w / 2, h * 0.7f)+ "left" -> listOf(w * 0.7f, h / 2, w * 0.3f, h / 2)+ "right" -> listOf(w * 0.3f, h / 2, w * 0.7f, h / 2)+ else -> return ToolResult.error(+ "Provide a direction (up/down/left/right) or explicit x1,y1,x2,y2 coordinates."+ )+ }+ return if (service.swipe(sx, sy, ex, ey)) ToolResult.ok("Swiped $direction.")+ else ToolResult.error("Could not dispatch the swipe gesture.")+ }++ /** Type text into the currently focused input field. */+ fun inputText(text: String): ToolResult {+ val service = requireService() ?: return notEnabled()+ return if (service.typeText(text)) ToolResult.ok("Typed \"$text\" into the focused field.")+ else ToolResult.error("No editable field is focused. Tap a text field first, then input text.")+ }++ /** Perform a device-wide navigation gesture (back/home/recents/notifications/quick_settings/lock_screen). */+ fun globalAction(action: String): ToolResult {+ val service = requireService() ?: return notEnabled()+ return if (service.performGlobal(action)) ToolResult.ok("Performed global action: $action.")+ else ToolResult.error(+ "Unknown or unsupported global action '$action'. " ++ "Use back, home, recents, notifications, quick_settings, or lock_screen."+ )+ }++ private fun requireService(): GotchaAccessibilityService? =+ if (isEnabled()) GotchaAccessibilityService.instance else null++ private fun notEnabled() = ToolResult.permissionNeeded(+ ToolResult.ACCESSIBILITY_ACCESS,+ "This action needs the Gotcha accessibility service. I have opened Accessibility " ++ "settings — please enable Gotcha there and ask again."+ )++ /** True when this app's service is listed in the system's enabled-accessibility-services setting. */+ private fun isEnabled(): Boolean {+ val expected = "${context.packageName}/${GotchaAccessibilityService::class.java.name}"+ val enabled = Settings.Secure.getString(+ context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES+ ) ?: return false+ val splitter = TextUtils.SimpleStringSplitter(':')+ splitter.setString(enabled)+ while (splitter.hasNext()) {+ if (splitter.next().equals(expected, ignoreCase = true)) return true+ }+ return false+ }+}diff --git a/app/src/main/java/com/gotcha/tools/DeviceAdminTool.kt b/app/src/main/java/com/gotcha/tools/DeviceAdminTool.ktnew file mode 100644index 0000000..c59f47e--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/DeviceAdminTool.kt@@ -0,0 +1,69 @@+package com.gotcha.tools++import android.app.admin.DevicePolicyManager+import android.content.Context+import com.gotcha.service.GotchaDeviceAdminReceiver++/**+ * Tier 3 — device-administration actions via [DevicePolicyManager], guarded by the+ * [GotchaDeviceAdminReceiver] admin component. Every action first checks the component+ * is active; if not it returns the [ToolResult.DEVICE_ADMIN] marker so the UI can launch+ * the activation dialog.+ *+ * Remote wipe is intentionally omitted (irreversible destruction of the user's device).+ */+class DeviceAdminTool(private val context: Context) {++ private val dpm: DevicePolicyManager+ get() = context.getSystemService(Context.DEVICE_POLICY_SERVICE) as DevicePolicyManager++ private val admin get() = GotchaDeviceAdminReceiver.componentName(context)++ /** Immediately lock the screen. */+ fun lockScreen(): ToolResult {+ if (!isActive()) return notActive()+ return try {+ dpm.lockNow()+ ToolResult.ok("Locked the screen.")+ } catch (e: Exception) {+ ToolResult.error("Could not lock the screen: ${e.message}")+ }+ }++ /** Enable or disable all device cameras via policy. */+ fun disableCamera(disabled: Boolean): ToolResult {+ if (!isActive()) return notActive()+ return try {+ dpm.setCameraDisabled(admin, disabled)+ ToolResult.ok(if (disabled) "Camera disabled for the whole device." else "Camera re-enabled.")+ } catch (e: Exception) {+ ToolResult.error("Could not change the camera policy: ${e.message}")+ }+ }++ /** Enforce a minimum unlock-password length (0 clears the length requirement). */+ fun setPasswordPolicy(minLength: Int): ToolResult {+ if (!isActive()) return notActive()+ val length = minLength.coerceIn(0, 16)+ return try {+ dpm.setPasswordQuality(admin, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC)+ dpm.setPasswordMinimumLength(admin, length)+ val sufficient = dpm.isActivePasswordSufficient+ ToolResult.ok(+ "Set the minimum password length to $length. " ++ if (sufficient) "The current password meets the policy."+ else "The current password does NOT meet the policy — the user will be prompted to update it."+ )+ } catch (e: Exception) {+ ToolResult.error("Could not set the password policy: ${e.message}")+ }+ }++ private fun isActive(): Boolean = dpm.isAdminActive(admin)++ private fun notActive() = ToolResult.permissionNeeded(+ ToolResult.DEVICE_ADMIN,+ "This needs Gotcha to be an active device administrator. I have opened the activation " ++ "screen — please confirm it there and ask again."+ )+}diff --git a/app/src/main/java/com/gotcha/tools/FileTool.kt b/app/src/main/java/com/gotcha/tools/FileTool.ktindex 82bc44c..52b4509 100644--- a/app/src/main/java/com/gotcha/tools/FileTool.kt+++ b/app/src/main/java/com/gotcha/tools/FileTool.kt@@ -31,8 +31,17 @@ class FileTool(private val context: Context) {)}+ /**+ * Tier 3 — the whole shared-storage tree, read *and* write, behind+ * "All files access" (MANAGE_EXTERNAL_STORAGE). Only reachable when the user has+ * granted that special access; otherwise resolve() returns a permission hint.+ */+ private val manageRoots: Map<String, File> by lazy {+ mapOf("storage" to Environment.getExternalStorageDirectory())+ }+private val allowedRootNames: String- get() = (sandboxRoots.keys + publicRoots.keys).joinToString(", ")+ get() = (sandboxRoots.keys + publicRoots.keys + manageRoots.keys).joinToString(", ")fun listFiles(path: String): ToolResult {val resolved = resolve(path, writable = false) ?: return badPath(path)@@ -77,8 +86,8 @@ class FileTool(private val context: Context) {fun writeFile(path: String, content: String, append: Boolean): ToolResult {val resolved = resolve(path, writable = true)?: return ToolResult.error(- "Writing is only allowed under the app sandbox roots (${sandboxRoots.keys.joinToString(", ")}). " +- "Path '$path' is outside them."+ "Writing is only allowed under the app sandbox roots (${sandboxRoots.keys.joinToString(", ")}) " ++ "or the 'storage' root (needs All-files access). Path '$path' is outside them.")(resolved as? PermissionMissing)?.let { return it.result }val file = (resolved as Resolved).file@@ -106,6 +115,10 @@ class FileTool(private val context: Context) {val root: File = when {sandboxRoots.containsKey(rootName) -> sandboxRoots[rootName] ?: return null+ manageRoots.containsKey(rootName) -> {+ checkAllFilesAccess()?.let { return PermissionMissing(it) }+ manageRoots.getValue(rootName)+ }!writable && publicRoots.containsKey(rootName) -> {checkMediaPermission()?.let { return PermissionMissing(it) }publicRoots.getValue(rootName)@@ -137,6 +150,24 @@ class FileTool(private val context: Context) {)}+ /**+ * Tier 3 gate for the 'storage' root. On API 30+ this is the MANAGE_EXTERNAL_STORAGE+ * "All files access" special grant; on older devices broad read access falls back to+ * READ/WRITE_EXTERNAL_STORAGE (handled here as the media permission).+ */+ private fun checkAllFilesAccess(): ToolResult? {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+ return if (Environment.isExternalStorageManager()) null+ else ToolResult.permissionNeeded(+ ToolResult.ALL_FILES_ACCESS,+ "Reading or writing all of shared storage needs \"All files access\". I have opened " ++ "that settings page — please enable it for Gotcha and ask again."+ )+ }+ // Pre-R: broad shared-storage access rides on the legacy storage permission.+ return checkMediaPermission()+ }+private fun badPath(path: String) = ToolResult.error("Path '$path' is not allowed. Use one of the allowed roots ($allowedRootNames), " +"optionally followed by a relative sub-path; '..' and absolute paths are rejected."diff --git a/app/src/main/java/com/gotcha/tools/NotificationTool.kt b/app/src/main/java/com/gotcha/tools/NotificationTool.ktnew file mode 100644index 0000000..77f4ff1--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/NotificationTool.kt@@ -0,0 +1,103 @@+package com.gotcha.tools++import android.content.ComponentName+import android.content.Context+import android.media.session.MediaController+import android.media.session.MediaSessionManager+import android.provider.Settings+import android.view.KeyEvent+import com.gotcha.service.GotchaNotificationListenerService+import java.text.SimpleDateFormat+import java.util.Date+import java.util.Locale++/**+ * Tier 3 — reads/dismisses notifications from any app and controls media playback,+ * all through the [GotchaNotificationListenerService]. Media control uses+ * [MediaSessionManager], which itself requires the notification-listener grant.+ */+class NotificationTool(private val context: Context) {++ fun readNotifications(limit: Int): ToolResult {+ val service = requireService() ?: return notEnabled()+ val notifications = service.currentNotifications()+ if (notifications.isEmpty()) return ToolResult.ok("There are no active notifications.")+ val pm = context.packageManager+ val fmt = SimpleDateFormat("HH:mm", Locale.getDefault())+ val out = notifications+ .sortedByDescending { it.postTime }+ .take(limit.coerceIn(1, 50))+ .joinToString("\n") { sbn ->+ val extras = sbn.notification.extras+ val title = extras.getCharSequence("android.title")?.toString()?.trim().orEmpty()+ val text = extras.getCharSequence("android.text")?.toString()?.trim().orEmpty()+ val app = try {+ pm.getApplicationLabel(pm.getApplicationInfo(sbn.packageName, 0)).toString()+ } catch (_: Exception) {+ sbn.packageName+ }+ val body = listOf(title, text).filter { it.isNotEmpty() }.joinToString(" — ")+ "- [${fmt.format(Date(sbn.postTime))}] $app: ${body.ifEmpty { "(no text)" }} {key=${sbn.key}}"+ }+ return ToolResult.ok("Active notifications (${notifications.size}):\n$out")+ }++ /** Dismiss a specific notification by key, or all of them when [key] is blank/null. */+ fun dismissNotifications(key: String?): ToolResult {+ val service = requireService() ?: return notEnabled()+ return if (key.isNullOrBlank()) {+ service.dismissAll()+ ToolResult.ok("Dismissed all dismissible notifications.")+ } else {+ service.dismiss(key)+ ToolResult.ok("Dismissed notification with key $key.")+ }+ }++ /** Control the active media session: play, pause, next, previous, stop. */+ fun mediaControl(action: String): ToolResult {+ if (!hasNotificationAccess()) return notEnabled()+ val keyCode = when (action.lowercase().trim()) {+ "play", "pause", "toggle", "playpause" -> KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE+ "next", "skip" -> KeyEvent.KEYCODE_MEDIA_NEXT+ "previous", "prev", "back" -> KeyEvent.KEYCODE_MEDIA_PREVIOUS+ "stop" -> KeyEvent.KEYCODE_MEDIA_STOP+ else -> return ToolResult.error(+ "Unknown media action '$action'. Use play, pause, next, previous, or stop."+ )+ }+ return try {+ val msm = context.getSystemService(Context.MEDIA_SESSION_SERVICE) as MediaSessionManager+ val component = ComponentName(context, GotchaNotificationListenerService::class.java)+ val controllers: List<MediaController> = msm.getActiveSessions(component)+ val controller = controllers.firstOrNull()+ ?: return ToolResult.error("No app is currently playing media.")+ controller.dispatchMediaButtonEvent(KeyEvent(KeyEvent.ACTION_DOWN, keyCode))+ controller.dispatchMediaButtonEvent(KeyEvent(KeyEvent.ACTION_UP, keyCode))+ ToolResult.ok("Sent media '$action' to ${controller.packageName}.")+ } catch (e: SecurityException) {+ notEnabled()+ } catch (e: Exception) {+ ToolResult.error("Could not control media: ${e.message}")+ }+ }++ private fun requireService(): GotchaNotificationListenerService? =+ if (hasNotificationAccess()) GotchaNotificationListenerService.instance else null++ private fun notEnabled() = ToolResult.permissionNeeded(+ ToolResult.NOTIFICATION_LISTENER_ACCESS,+ "This needs Notification access. I have opened the Notification-access settings — " ++ "please enable Gotcha there and ask again."+ )++ private fun hasNotificationAccess(): Boolean {+ val flat = Settings.Secure.getString(+ context.contentResolver, "enabled_notification_listeners"+ ) ?: return false+ val expected = ComponentName(context, GotchaNotificationListenerService::class.java)+ return flat.split(":").any {+ ComponentName.unflattenFromString(it) == expected+ }+ }+}diff --git a/app/src/main/java/com/gotcha/tools/OverlayTool.kt b/app/src/main/java/com/gotcha/tools/OverlayTool.ktnew file mode 100644index 0000000..83620aa--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/OverlayTool.kt@@ -0,0 +1,103 @@+package com.gotcha.tools++import android.content.Context+import android.graphics.Color+import android.graphics.PixelFormat+import android.os.Build+import android.os.Handler+import android.os.Looper+import android.provider.Settings+import android.view.Gravity+import android.view.WindowManager+import android.widget.TextView++/**+ * Tier 3 — draws a floating text overlay on top of other apps using SYSTEM_ALERT_WINDOW.+ *+ * View/WindowManager work must happen on the main thread, so every mutation is posted to+ * the main looper. A single overlay view is tracked at a time; showing a new one replaces it.+ */+class OverlayTool(private val context: Context) {++ private val mainHandler = Handler(Looper.getMainLooper())+ private val windowManager: WindowManager+ get() = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager++ @Volatile+ private var overlayView: TextView? = null+ private var autoHide: Runnable? = null++ /** Show [text] as a floating banner for [durationMs] (0 = until hide_overlay is called). */+ fun showOverlay(text: String, durationMs: Int): ToolResult {+ if (!canDrawOverlays()) return notEnabled()+ if (text.isBlank()) return ToolResult.error("Provide some text to display in the overlay.")+ val duration = durationMs.coerceIn(0, 300_000)+ mainHandler.post {+ removeView()+ val view = TextView(context).apply {+ this.text = text+ setTextColor(Color.WHITE)+ setBackgroundColor(Color.argb(220, 0, 0, 0))+ setPadding(32, 24, 32, 24)+ textSize = 16f+ }+ windowManager.addView(view, layoutParams())+ overlayView = view+ if (duration > 0) {+ autoHide = Runnable { removeView() }.also { mainHandler.postDelayed(it, duration.toLong()) }+ }+ }+ return ToolResult.ok(+ if (duration > 0) "Showing an overlay for ${duration / 1000}s: \"$text\"."+ else "Showing a persistent overlay: \"$text\". Call hide_overlay to remove it."+ )+ }++ fun hideOverlay(): ToolResult {+ if (overlayView == null) return ToolResult.ok("No overlay is currently showing.")+ mainHandler.post { removeView() }+ return ToolResult.ok("Overlay hidden.")+ }++ private fun removeView() {+ autoHide?.let { mainHandler.removeCallbacks(it) }+ autoHide = null+ overlayView?.let {+ try {+ windowManager.removeView(it)+ } catch (_: Exception) {+ // View may already be detached; ignore.+ }+ }+ overlayView = null+ }++ private fun layoutParams(): WindowManager.LayoutParams {+ val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+ WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY+ } else {+ @Suppress("DEPRECATION")+ WindowManager.LayoutParams.TYPE_PHONE+ }+ return WindowManager.LayoutParams(+ WindowManager.LayoutParams.WRAP_CONTENT,+ WindowManager.LayoutParams.WRAP_CONTENT,+ type,+ WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or+ WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,+ PixelFormat.TRANSLUCENT+ ).apply {+ gravity = Gravity.TOP or Gravity.CENTER_HORIZONTAL+ y = 120+ }+ }++ private fun canDrawOverlays(): Boolean =+ Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.canDrawOverlays(context)++ private fun notEnabled() = ToolResult.permissionNeeded(+ ToolResult.OVERLAY_ACCESS,+ "Drawing over other apps needs the \"Display over other apps\" permission. I have opened " ++ "that settings page — please enable it for Gotcha and ask again."+ )+}diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.ktindex 3704abd..b4d64a9 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -56,7 +56,8 @@ object ToolDefinitions {val listFiles = tool("list_files","List files in an allowed directory. Allowed roots: 'files' (app files), 'cache' (app cache), " +- "'external' (app external files), 'downloads', 'pictures', 'dcim', 'documents'. " ++ "'external' (app external files), 'downloads', 'pictures', 'dcim', 'documents', and " ++ "'storage' (the whole shared-storage tree, needs All-files access). " +"An optional relative sub-path may be appended, e.g. 'downloads/reports'.",schema {putJsonObject("properties") {@@ -74,7 +75,8 @@ object ToolDefinitions {val readFile = tool("read_file",- "Read a text file from an allowed directory (same roots as list_files). Output is capped.",+ "Read a text file from an allowed directory (same roots as list_files, including 'storage' " ++ "with All-files access). Output is capped.",schema {putJsonObject("properties") {putJsonObject("path") {@@ -88,7 +90,8 @@ object ToolDefinitions {val writeFile = tool("write_file",- "Write or append a text file inside the app sandbox (roots 'files', 'cache', 'external' only).",+ "Write or append a text file. Roots 'files', 'cache', 'external' work in the app sandbox; " ++ "the 'storage' root writes anywhere in shared storage but needs All-files access.",schema {putJsonObject("properties") {putJsonObject("path") {@@ -551,6 +554,191 @@ object ToolDefinitions {schema { putJsonObject("properties") {} })+ // ---- Tier 3 additions (component-based / device-wide access) ----++ val readScreen = tool(+ "read_screen",+ "Read the visible text of whatever app is currently on screen, using the accessibility " ++ "service. Use this to 'see' the foreground app before tapping or typing. Needs the " ++ "Gotcha accessibility service to be enabled.",+ schema { putJsonObject("properties") {} }+ )++ val tap = tool(+ "tap",+ "Tap the screen via the accessibility service — either an on-screen element matching " ++ "some text/label, or absolute pixel coordinates. Prefer matching by text. Needs the " ++ "accessibility service enabled.",+ schema {+ putJsonObject("properties") {+ putJsonObject("text") {+ put("type", "string")+ put("description", "Visible text/label of the element to tap (case-insensitive, partial match).")+ }+ putJsonObject("x") {+ put("type", "integer")+ put("description", "Absolute X pixel coordinate (use with y instead of text).")+ }+ putJsonObject("y") {+ put("type", "integer")+ put("description", "Absolute Y pixel coordinate (use with x instead of text).")+ }+ }+ }+ )++ val swipe = tool(+ "swipe",+ "Swipe the screen via the accessibility service — a named direction (up/down/left/right) " ++ "or explicit start/end coordinates. Use for scrolling and navigation. Needs the " ++ "accessibility service enabled.",+ schema {+ putJsonObject("properties") {+ putJsonObject("direction") {+ put("type", "string")+ put("description", "One of: up, down, left, right.")+ }+ putJsonObject("x1") { put("type", "integer"); put("description", "Start X (with y1,x2,y2).") }+ putJsonObject("y1") { put("type", "integer"); put("description", "Start Y.") }+ putJsonObject("x2") { put("type", "integer"); put("description", "End X.") }+ putJsonObject("y2") { put("type", "integer"); put("description", "End Y.") }+ }+ }+ )++ val inputText = tool(+ "input_text",+ "Type text into the currently focused input field via the accessibility service. Tap a " ++ "text field first so it is focused. Needs the accessibility service enabled.",+ schema {+ putJsonObject("properties") {+ putJsonObject("text") {+ put("type", "string")+ put("description", "Text to type into the focused field.")+ }+ }+ putJsonArray("required") { add("text") }+ }+ )++ val globalAction = tool(+ "global_action",+ "Perform a device-wide navigation gesture via the accessibility service: back, home, " ++ "recents, notifications, quick_settings, or lock_screen. Needs the accessibility service enabled.",+ schema {+ putJsonObject("properties") {+ putJsonObject("action") {+ put("type", "string")+ put("description", "One of: back, home, recents, notifications, quick_settings, lock_screen.")+ }+ }+ putJsonArray("required") { add("action") }+ }+ )++ val readNotifications = tool(+ "read_notifications",+ "Read the currently active notifications from all apps (app, time, title/text, and a " ++ "dismiss key). Needs Notification access.",+ schema {+ putJsonObject("properties") {+ putJsonObject("limit") {+ put("type", "integer")+ put("description", "How many recent notifications to return (1-50). Default 15.")+ }+ }+ }+ )++ val dismissNotifications = tool(+ "dismiss_notifications",+ "Dismiss a notification by its key (from read_notifications), or all notifications if no " ++ "key is given. Needs Notification access.",+ schema {+ putJsonObject("properties") {+ putJsonObject("key") {+ put("type", "string")+ put("description", "The notification key to dismiss. Omit to dismiss all.")+ }+ }+ }+ )++ val mediaControl = tool(+ "media_control",+ "Control the currently playing media session: play, pause, next, previous, or stop. " ++ "Needs Notification access.",+ schema {+ putJsonObject("properties") {+ putJsonObject("action") {+ put("type", "string")+ put("description", "One of: play, pause, next, previous, stop.")+ }+ }+ putJsonArray("required") { add("action") }+ }+ )++ val showOverlay = tool(+ "show_overlay",+ "Display a floating text banner on top of other apps. Needs the 'Display over other apps' permission.",+ schema {+ putJsonObject("properties") {+ putJsonObject("text") {+ put("type", "string")+ put("description", "Text to display in the overlay.")+ }+ putJsonObject("duration_ms") {+ put("type", "integer")+ put("description", "How long to show it, in milliseconds (0 = until hidden). Default 4000.")+ }+ }+ putJsonArray("required") { add("text") }+ }+ )++ val hideOverlay = tool(+ "hide_overlay",+ "Remove the floating overlay shown by show_overlay.",+ schema { putJsonObject("properties") {} }+ )++ val lockScreen = tool(+ "lock_screen",+ "Immediately lock the device screen. Needs Gotcha to be an active device administrator.",+ schema { putJsonObject("properties") {} }+ )++ val disableCamera = tool(+ "disable_camera",+ "Disable or re-enable all device cameras via device-admin policy. Needs Gotcha to be " ++ "an active device administrator.",+ schema {+ putJsonObject("properties") {+ putJsonObject("disabled") {+ put("type", "boolean")+ put("description", "true to disable the camera, false to re-enable it.")+ }+ }+ putJsonArray("required") { add("disabled") }+ }+ )++ val setPasswordPolicy = tool(+ "set_password_policy",+ "Enforce a minimum unlock-password length via device-admin policy. Needs Gotcha to be " ++ "an active device administrator.",+ schema {+ putJsonObject("properties") {+ putJsonObject("min_length") {+ put("type", "integer")+ put("description", "Minimum password length to enforce (0-16). 0 clears the requirement.")+ }+ }+ putJsonArray("required") { add("min_length") }+ }+ )+val all: List<ToolDefinition> = listOf(dialNumber, getStorageInfo, getBatteryInfo, listFiles, readFile, writeFile,clearAppCache, openApp, toggleDarkMode, setBrightness, toggleWifi,@@ -560,6 +748,11 @@ object ToolDefinitions {listCalendarEvents, createCalendarEvent, setAlarm, setTimer,toggleTorch, setVolume, setRingerMode, vibrate, setDnd,getLocation, listInstalledApps, uninstallApp, getAppUsage, getDataUsage,- getClipboard, setClipboard, takePhoto, startAudioRecording, stopAudioRecording+ getClipboard, setClipboard, takePhoto, startAudioRecording, stopAudioRecording,+ // Tier 3 additions+ readScreen, tap, swipe, inputText, globalAction,+ readNotifications, dismissNotifications, mediaControl,+ showOverlay, hideOverlay,+ lockScreen, disableCamera, setPasswordPolicy)}diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.ktindex beae955..6930f1a 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -31,6 +31,11 @@ class ToolExecutor(context: Context) {private val appsTool = AppsTool(appContext)private val clipboardTool = ClipboardTool(appContext)private val mediaCaptureTool = MediaCaptureTool(appContext)+ // Tier 3 tools+ private val accessibilityTool = AccessibilityTool(appContext)+ private val notificationTool = NotificationTool(appContext)+ private val overlayTool = OverlayTool(appContext)+ private val deviceAdminTool = DeviceAdminTool(appContext)private val actionLog = ActionLog(appContext)suspend fun execute(name: String, args: JsonObject): ToolResult {@@ -119,6 +124,35 @@ class ToolExecutor(context: Context) {"take_photo" -> mediaCaptureTool.takePhoto()"start_audio_recording" -> mediaCaptureTool.startAudioRecording()"stop_audio_recording" -> mediaCaptureTool.stopAudioRecording()+ // ---- Tier 3 ----+ "read_screen" -> accessibilityTool.readScreen()+ "tap" -> accessibilityTool.tap(+ text = args.requireString("text"),+ x = args.requireInt("x"),+ y = args.requireInt("y")+ )+ "swipe" -> accessibilityTool.swipe(+ direction = args.requireString("direction"),+ x1 = args.requireInt("x1"), y1 = args.requireInt("y1"),+ x2 = args.requireInt("x2"), y2 = args.requireInt("y2")+ )+ "input_text" -> accessibilityTool.inputText(args.requireString("text") ?: return missing("text"))+ "global_action" -> accessibilityTool.globalAction(args.requireString("action") ?: return missing("action"))+ "read_notifications" -> notificationTool.readNotifications(args.requireInt("limit") ?: 15)+ "dismiss_notifications" -> notificationTool.dismissNotifications(args.requireString("key"))+ "media_control" -> notificationTool.mediaControl(args.requireString("action") ?: return missing("action"))+ "show_overlay" -> overlayTool.showOverlay(+ text = args.requireString("text") ?: return missing("text"),+ durationMs = args.requireInt("duration_ms") ?: 4000+ )+ "hide_overlay" -> overlayTool.hideOverlay()+ "lock_screen" -> deviceAdminTool.lockScreen()+ "disable_camera" -> deviceAdminTool.disableCamera(+ args["disabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("disabled")+ )+ "set_password_policy" -> deviceAdminTool.setPasswordPolicy(+ args.requireInt("min_length") ?: return missing("min_length")+ )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 25ec2d7..10c07c8 100644--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt@@ -22,7 +22,12 @@ object ToolRegistry {"call_number", "read_call_log", "find_contact", "add_contact","send_sms", "read_recent_sms", "create_calendar_event", "list_calendar_events","get_location", "uninstall_app",- "take_photo", "start_audio_recording", "stop_audio_recording"+ "take_photo", "start_audio_recording", "stop_audio_recording",+ // Tier 3: device-wide / other-app control is always sensitive.+ "read_screen", "tap", "swipe", "input_text", "global_action",+ "read_notifications", "dismiss_notifications", "media_control",+ "show_overlay", "hide_overlay",+ "lock_screen", "disable_camera", "set_password_policy")fun allDefinitions(): List<ToolDefinition> = definitions.values.toList()diff --git a/app/src/main/java/com/gotcha/tools/ToolResult.kt b/app/src/main/java/com/gotcha/tools/ToolResult.ktindex 6b72afd..59d61f6 100644--- a/app/src/main/java/com/gotcha/tools/ToolResult.kt+++ b/app/src/main/java/com/gotcha/tools/ToolResult.kt@@ -22,6 +22,23 @@ data class ToolResult(/** Marker for the "Do Not Disturb access" (notification-policy) special app access. */const val DND_ACCESS = "special:dnd_access"+ // ---- Tier 3: component-based / device-wide special access ----++ /** Marker for enabling the AccessibilityService (Settings → Accessibility). */+ const val ACCESSIBILITY_ACCESS = "special:accessibility_access"++ /** Marker for enabling the NotificationListenerService (Notification access). */+ const val NOTIFICATION_LISTENER_ACCESS = "special:notification_listener_access"++ /** Marker for the "All files access" (MANAGE_EXTERNAL_STORAGE) special access. */+ const val ALL_FILES_ACCESS = "special:all_files_access"++ /** Marker for the "Display over other apps" (SYSTEM_ALERT_WINDOW) special access. */+ const val OVERLAY_ACCESS = "special:overlay_access"++ /** Marker for activating the Device Admin component. */+ const val DEVICE_ADMIN = "special:device_admin"+fun ok(message: String) = ToolResult(true, message)fun error(message: String) = ToolResult(false, message)fun permissionNeeded(permission: String, message: String) =diff --git a/app/src/main/java/com/gotcha/ui/ConfirmationOverlay.kt b/app/src/main/java/com/gotcha/ui/ConfirmationOverlay.ktnew file mode 100644index 0000000..9f0687c--- /dev/null+++ b/app/src/main/java/com/gotcha/ui/ConfirmationOverlay.kt@@ -0,0 +1,137 @@+package com.gotcha.ui++import android.content.Context+import android.graphics.Color+import android.graphics.PixelFormat+import android.graphics.drawable.GradientDrawable+import android.os.Build+import android.os.Handler+import android.os.Looper+import android.provider.Settings+import android.view.Gravity+import android.view.View+import android.view.WindowManager+import android.widget.Button+import android.widget.LinearLayout+import android.widget.TextView++/**+ * A confirmation prompt drawn as a floating window on top of whatever app is in the+ * foreground, using SYSTEM_ALERT_WINDOW.+ *+ * Unlike the in-app Compose dialog, this stays visible after Gotcha hands control+ * to another app (e.g. after `open_app` launches Settings), so a sensitive accessibility+ * action can still be approved instead of the tool loop blocking on a dialog the user+ * can no longer see. All window work is posted to the main thread.+ */+class ConfirmationOverlay(context: Context) {++ private val appContext = context.applicationContext+ private val mainHandler = Handler(Looper.getMainLooper())+ private val windowManager: WindowManager+ get() = appContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager++ @Volatile+ private var view: View? = null++ /** Whether we currently hold the "Display over other apps" permission. */+ fun canShow(): Boolean =+ Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.canDrawOverlays(appContext)++ fun show(summary: String, onAllow: () -> Unit, onDeny: () -> Unit) {+ mainHandler.post {+ removeView()+ val card = buildCard(summary, onAllow, onDeny)+ try {+ windowManager.addView(card, layoutParams())+ view = card+ } catch (_: Exception) {+ view = null+ }+ }+ }++ fun dismiss() {+ mainHandler.post { removeView() }+ }++ private fun removeView() {+ view?.let {+ try {+ windowManager.removeView(it)+ } catch (_: Exception) {+ // Already detached; ignore.+ }+ }+ view = null+ }++ private fun buildCard(summary: String, onAllow: () -> Unit, onDeny: () -> Unit): View {+ val container = LinearLayout(appContext).apply {+ orientation = LinearLayout.VERTICAL+ setPadding(dp(20), dp(20), dp(20), dp(20))+ background = GradientDrawable().apply {+ cornerRadius = dp(16).toFloat()+ setColor(Color.parseColor("#1E1E1E"))+ setStroke(dp(1), Color.parseColor("#3A3A3A"))+ }+ }++ val title = TextView(appContext).apply {+ text = "Gotcha — confirm action"+ setTextColor(Color.WHITE)+ textSize = 16f+ setPadding(0, 0, 0, dp(8))+ }++ val body = TextView(appContext).apply {+ text = summary+ setTextColor(Color.parseColor("#CCCCCC"))+ textSize = 13f+ }++ val buttonRow = LinearLayout(appContext).apply {+ orientation = LinearLayout.HORIZONTAL+ gravity = Gravity.END+ setPadding(0, dp(16), 0, 0)+ }+ val deny = Button(appContext).apply {+ text = "Deny"+ setOnClickListener { onDeny() }+ }+ val allow = Button(appContext).apply {+ text = "Allow"+ setOnClickListener { onAllow() }+ }+ buttonRow.addView(deny)+ buttonRow.addView(allow)++ container.addView(title)+ container.addView(body)+ container.addView(buttonRow)+ return container+ }++ private fun layoutParams(): WindowManager.LayoutParams {+ val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+ WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY+ } else {+ @Suppress("DEPRECATION")+ WindowManager.LayoutParams.TYPE_PHONE+ }+ // FLAG_NOT_FOCUSABLE keeps us from stealing the keyboard, but the window still+ // receives touch events, so the Allow/Deny buttons remain tappable.+ return WindowManager.LayoutParams(+ dp(320),+ WindowManager.LayoutParams.WRAP_CONTENT,+ type,+ WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,+ PixelFormat.TRANSLUCENT+ ).apply {+ gravity = Gravity.CENTER+ }+ }++ private fun dp(value: Int): Int =+ (value * appContext.resources.displayMetrics.density).toInt()+}diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex bdf0d36..a11654b 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -1,4 +1,6 @@<?xml version="1.0" encoding="utf-8"?><resources><string name="app_name">Gotcha</string>+ <string name="accessibility_service_description">Lets Gotcha read on-screen content and perform taps, swipes and text input on your behalf, so the assistant can operate other apps for you.</string>+ <string name="device_admin_description">Lets Gotcha lock the screen, enforce password policy and disable the camera when you ask it to.</string></resources>diff --git a/app/src/main/res/xml/accessibility_service_config.xml b/app/src/main/res/xml/accessibility_service_config.xmlnew file mode 100644index 0000000..8db913b--- /dev/null+++ b/app/src/main/res/xml/accessibility_service_config.xml@@ -0,0 +1,9 @@+<?xml version="1.0" encoding="utf-8"?>+<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"+ android:accessibilityEventTypes="typeAllMask"+ android:accessibilityFeedbackType="feedbackGeneric"+ android:accessibilityFlags="flagDefault|flagRetrieveInteractiveWindows"+ android:canPerformGestures="true"+ android:canRetrieveWindowContent="true"+ android:description="@string/accessibility_service_description"+ android:notificationTimeout="100" />diff --git a/app/src/main/res/xml/device_admin.xml b/app/src/main/res/xml/device_admin.xmlnew file mode 100644index 0000000..cd4a42b--- /dev/null+++ b/app/src/main/res/xml/device_admin.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<device-admin xmlns:android="http://schemas.android.com/apk/res/android">+ <uses-policies>+ <force-lock />+ <limit-password />+ <disable-camera />+ </uses-policies>+</device-admin>