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.
ci: drop lint/detekt baselines, fix all findings repo-wide
Durganshu Mishra0b7ddeaaabe2
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 4d094f4..882e8f6 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -24,16 +24,13 @@ jobs:- uses: gradle/actions/setup-gradle@v4- # Baselined against existing findings (app/detekt-baseline.xml); regenerate- # locally with: ./gradlew :app:detektBaseline+ # No baselines: the whole repo must pass detekt and lint on every run.- name: Detektrun: ./gradlew :app:detekt --stacktrace- name: Unit testsrun: ./gradlew :app:testDebugUnitTest --stacktrace- # Baselined against existing findings (app/lint-baseline.xml); regenerate- # locally with: ./gradlew :app:updateLintBaseline- name: Android Lintrun: ./gradlew :app:lintDebug --stacktracediff --git a/RUNNING.md b/RUNNING.mdindex 9b9db07..806efbb 100644--- a/RUNNING.md+++ b/RUNNING.md@@ -66,9 +66,8 @@ GitHub Actions workflow (`.github/workflows/ci.yml`): detekt → JVM unit testsAndroid Lint → `assembleDebug`. Test and analysis reports are attached to eachrun as artifacts. The workflow can also be triggered manually from the Actionstab (**workflow_dispatch**) on any branch.-Detekt and lint check only *new* findings — existing ones are grandfathered in-committed baselines (`app/detekt-baseline.xml`, `app/lint-baseline.xml`);-regenerate them with `./gradlew :app:detektBaseline :app:updateLintBaseline`.+Detekt and lint have **no baselines** — the whole repository must pass both+checks on every run, so any new finding fails CI immediately.The unit tests shell out to a POSIX `sh` (TerminalTool), so they need Linux,macOS, or Git Bash — on plain Windows they fail; use CI instead.diff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex dc1ed96..d4bb03c 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -82,14 +82,14 @@ android {warningsAsErrors = falsehtmlReport = truesarifReport = true- baseline = file("lint-baseline.xml")}}detekt {buildUponDefaultConfig = trueconfig.setFrom(rootProject.files("config/detekt/detekt.yml"))- baseline = file("detekt-baseline.xml")+ // One-off formatting fixes: ./gradlew :app:detekt -PdetektAutoCorrect+ autoCorrect = project.hasProperty("detektAutoCorrect")}dependencies {diff --git a/app/detekt-baseline.xml b/app/detekt-baseline.xmldeleted file mode 100644index f167fda..0000000--- a/app/detekt-baseline.xml+++ /dev/null@@ -1,780 +0,0 @@-<?xml version="1.0" ?>-<SmellBaseline>- <ManuallySuppressedIssues></ManuallySuppressedIssues>- <CurrentIssues>- <ID>AnnotationOnSeparateLine:AssistiveBallOverlay.kt$AssistiveBallOverlay$@Suppress("DEPRECATION") WindowManager.LayoutParams.TYPE_PHONE</ID>- <ID>ArgumentListWrapping:ActionLog.kt$ActionLog$('\n', ' ')</ID>- <ID>ArgumentListWrapping:ActionLog.kt$ActionLog$(500)</ID>- <ID>ArgumentListWrapping:ActionLog.kt$ActionLog$(Date())</ID>- <ID>ArgumentListWrapping:AlarmReceiver.kt$AlarmReceiver$(CHANNEL_ID_SILENT, "Alarms & Timers (no vibration)", NotificationManager.IMPORTANCE_HIGH)</ID>- <ID>ArgumentListWrapping:AlarmTool.kt$AlarmTool$(",")</ID>- <ID>ArgumentListWrapping:AlarmTool.kt$AlarmTool$("Alarm $id lives in the system clock app but no clock app handled the update intent. Edit it in the clock app directly.")</ID>- <ID>ArgumentListWrapping:AlarmTool.kt$AlarmTool$("Removed alarm $id from this assistant's list, but no clock app handled the dismiss intent — ask the user to delete it in the clock app.")</ID>- <ID>ArgumentListWrapping:AlarmTool.kt$AlarmTool$("Set alarm '$label' for %02d:%02d$extra (id=$id). No clock app handled it, so it was scheduled in-app and rings as a notification.".format(hour, minute))</ID>- <ID>ArgumentListWrapping:AlarmTool.kt$AlarmTool$("Set alarm '$label' for %02d:%02d$extra in the system clock app (id=$id).".format(hour, minute))</ID>- <ID>ArgumentListWrapping:AlarmTool.kt$AlarmTool$(3)</ID>- <ID>ArgumentListWrapping:AlarmTool.kt$AlarmTool$(AlarmRecord(id, hour, minute, dayInts, label, vibrate ?: true, system = true, triggerAt = triggerAt))</ID>- <ID>ArgumentListWrapping:AlarmTool.kt$AlarmTool$(Calendar.MONDAY, Calendar.TUESDAY, Calendar.WEDNESDAY, Calendar.THURSDAY, Calendar.FRIDAY)</ID>- <ID>ArgumentListWrapping:AlarmTool.kt$AlarmTool$(a.id)</ID>- <ID>ArgumentListWrapping:AlarmTool.kt$AlarmTool$(buildSetAlarmIntent(record.hour, record.minute, record.label, record.days, record.vibrate))</ID>- <ID>ArgumentListWrapping:AlarmTool.kt$AlarmTool$(context, alarmRequestCode(a.id), intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)</ID>- <ID>ArgumentListWrapping:AlarmTool.kt$AlarmTool$(context, requestCode, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_NO_CREATE)</ID>- <ID>ArgumentListWrapping:AlarmTool.kt$AlarmTool$(context, timerRequestCode(t.id), intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)</ID>- <ID>ArgumentListWrapping:AlarmTool.kt$AlarmTool$(d)</ID>- <ID>ArgumentListWrapping:AlarmTool.kt$AlarmTool$(hour, minute)</ID>- <ID>ArgumentListWrapping:AlarmTool.kt$AlarmTool$(id, hour, minute, dayInts, label, vibrate ?: true, system = true, triggerAt = triggerAt)</ID>- <ID>ArgumentListWrapping:AlarmTool.kt$AlarmTool$(kotlinx.serialization.json.JsonPrimitive(d))</ID>- <ID>ArgumentListWrapping:AlarmTool.kt$AlarmTool$(record.hour, record.minute, record.label, record.days, record.vibrate)</ID>- <ID>ArgumentListWrapping:AlarmTool.kt$AlarmTool$(t.id)</ID>- <ID>ArgumentListWrapping:AppsTool.kt$AppsTool$( AppOpsManager.OPSTR_GET_USAGE_STATS, Process.myUid(), context.packageName )</ID>- <ID>ArgumentListWrapping:AppsTool.kt$AppsTool$("Found $matchCount app(s) matching '$search'$truncated ($total total, $userApps user, $systemApps system).\n$listing")</ID>- <ID>ArgumentListWrapping:AppsTool.kt$AppsTool$("System dialog opened to uninstall $label. After you tap OK in the dialog, ask the assistant to verify the app is gone.")</ID>- <ID>ArgumentListWrapping:AssistiveBallService.kt$AssistiveBallService$( this, 0, Intent(this, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), PendingIntent.FLAG_IMMUTABLE )</ID>- <ID>ArgumentListWrapping:AudioApi.kt$AudioApi$( "application/json".toMediaType(), json.toString() )</ID>- <ID>ArgumentListWrapping:AudioApi.kt$AudioApi$(boundary, audioFile, "file", "audio/m4a", mapOf("model" to model) )</ID>- <ID>ArgumentListWrapping:CalendarTool.kt$CalendarTool$( "yyyy-MM-dd HH:mm", "yyyy-MM-dd'T'HH:mm", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss" )</ID>- <ID>ArgumentListWrapping:CalendarTool.kt$CalendarTool$( CalendarContract.Calendars.CONTENT_URI, projection, null, null, null )</ID>- <ID>ArgumentListWrapping:CalendarTool.kt$CalendarTool$( CalendarContract.Calendars.CONTENT_URI, projection, selection, args, "${CalendarContract.Calendars.IS_PRIMARY} DESC" )</ID>- <ID>ArgumentListWrapping:CalendarTool.kt$CalendarTool$( builder.build(), projection, selection, selectionArgs, "${CalendarContract.Instances.BEGIN} ASC" )</ID>- <ID>ArgumentListWrapping:ChatScreen.kt$(Icons.Default.Stop, contentDescription = "Stop recording", modifier = Modifier.size(20.dp), tint = Color.White)</ID>- <ID>ArgumentListWrapping:ChatScreen.kt$(Icons.Default.Stop, contentDescription = "Stop", modifier = Modifier.size(20.dp))</ID>- <ID>ArgumentListWrapping:ChatViewModel.kt$ChatViewModel$( "Screen text:\n$screenText\n\nThe assistant also captured a screenshot. " + "Use it together with the screen text to understand the current screen.", screenshotBase64, "png" )</ID>- <ID>ArgumentListWrapping:ChatViewModel.kt$ChatViewModel$( "The assistant read an image file: $filename ($dimensions, $sizeDisplay).", base64, format )</ID>- <ID>ArgumentListWrapping:ChatViewModel.kt$ChatViewModel$( getApplication(), settings.sttApiBaseUrl, settings.apiKey )</ID>- <ID>ArgumentListWrapping:ChatViewModel.kt$ChatViewModel$( getApplication(), settings.ttsApiBaseUrl, settings.apiKey )</ID>- <ID>ArgumentListWrapping:ChatViewModel.kt$ChatViewModel$(" Android version: ${android.os.Build.VERSION.RELEASE} (API ${android.os.Build.VERSION.SDK_INT})")</ID>- <ID>ArgumentListWrapping:ChatViewModel.kt$ChatViewModel$("Please summarize the following conversation history according to the system prompt instructions:\n\n$historyText")</ID>- <ID>ArgumentListWrapping:ChatViewModel.kt$ChatViewModel$("You are an advanced context compaction agent. Your task is to compress the preceding conversation history into a highly dense, structured continuation summary. You must preserve critical context, decisions, and codebase states while eliminating conversational filler and repetitive tool logs.\n\nGenerate a structured summary containing exactly the following sections:\n1. **Goal**: What is the ultimate objective of this engineering session?\n2. **Instructions & Constraints**: What specific guidelines, patterns, user preferences, or technical limitations have been established?\n3. **Discoveries & Architecture**: What have we learned about the codebase? Detail any symbol mappings, logic structures, or debugging conclusions.\n4. **Accomplished**: What changes have already been completely implemented, verified, or fixed?\n5. **Relevant Files**: Which files are currently being modified or are active in the workspace?\n\nCRITICAL: Do not lose technical specifics, user-stated constraints, or deep investigation states.\n\nContinue if you have next steps, or stop and ask for clarification if you are unsure how to proceed.")</ID>- <ID>ArgumentListWrapping:ChatViewModel.kt$ChatViewModel$("delete_$kind")</ID>- <ID>ArgumentListWrapping:ChatViewModel.kt$ChatViewModel$("uninstall_app")</ID>- <ID>ArgumentListWrapping:ChatViewModel.kt$ChatViewModel$(ChatSession(id, title, System.currentTimeMillis(), llmHistory.toList(), activeSessionTokenCount))</ID>- <ID>ArgumentListWrapping:ChatViewModel.kt$ChatViewModel$(MessageKind.ERROR, "Microphone permission not granted. Enable it in Settings → Permissions.")</ID>- <ID>ArgumentListWrapping:ChatViewModel.kt$ChatViewModel$(activity = null, pendingConfirmation = PendingConfirmation(listOf("delete_$kind"), description))</ID>- <ID>ArgumentListWrapping:ChatViewModel.kt$ChatViewModel$(activity = null, pendingConfirmation = PendingConfirmation(listOf("uninstall_app"), description))</ID>- <ID>ArgumentListWrapping:ChatViewModel.kt$ChatViewModel$(android.content.Context.CONNECTIVITY_SERVICE)</ID>- <ID>ArgumentListWrapping:ChatViewModel.kt$ChatViewModel$(id, title, System.currentTimeMillis(), llmHistory.toList(), activeSessionTokenCount)</ID>- <ID>ArgumentListWrapping:ChatViewModel.kt$ChatViewModel$(listOf("delete_$kind"), description)</ID>- <ID>ArgumentListWrapping:ChatViewModel.kt$ChatViewModel$(listOf("uninstall_app"), description)</ID>- <ID>ArgumentListWrapping:ChatViewModel.kt$ChatViewModel$(nextId++, MessageKind.USER, msg.textContent.ifEmpty { "(image attached)" })</ID>- <ID>ArgumentListWrapping:ClipboardTool.kt$ClipboardTool$("Clipboard (from accessibility service): ${text.take(2000)}")</ID>- <ID>ArgumentListWrapping:ClipboardTool.kt$ClipboardTool$(2000)</ID>- <ID>ArgumentListWrapping:ContactsTool.kt$ContactsTool$( ContactsContract.CommonDataKinds.Email.CONTENT_URI, arrayOf(ContactsContract.CommonDataKinds.Email.ADDRESS), "${ContactsContract.CommonDataKinds.Email.CONTACT_ID} = ?", arrayOf(contactId), null )</ID>- <ID>ArgumentListWrapping:ContactsTool.kt$ContactsTool$( uri, arrayOf(ContactsContract.PhoneLookup._ID), null, null, null )</ID>- <ID>ArgumentListWrapping:ContactsTool.kt$ContactsTool$(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)</ID>- <ID>ArgumentListWrapping:ContactsTool.kt$ContactsTool$(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)</ID>- <ID>ArgumentListWrapping:ContactsTool.kt$ContactsTool$(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)</ID>- <ID>ArgumentListWrapping:ContactsTool.kt$ContactsTool$(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)</ID>- <ID>ArgumentListWrapping:ContactsTool.kt$ContactsTool$(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)</ID>- <ID>ArgumentListWrapping:DeviceTool.kt$DeviceTool$("Unknown stream '$name'. Use media, ring, alarm, notification, or call.")</ID>- <ID>ArgumentListWrapping:EditTool.kt$EditTool$("File '$path' does not exist (resolved: ${file.canonicalPath}).")</ID>- <ID>ArgumentListWrapping:EditTool.kt$EditTool$("Found $count matches in '$path'. " + "Provide more surrounding context or use replaceAll=true.")</ID>- <ID>ArgumentListWrapping:EditTool.kt$EditTool$("No match found for the specified text in '$path'. " + "The text must match exactly, including whitespace and indentation.")</ID>- <ID>ArgumentListWrapping:FileResolver.kt$FileResolver$( android.Manifest.permission.READ_EXTERNAL_STORAGE, READ_STORAGE_GUIDE )</ID>- <ID>ArgumentListWrapping:FileResolver.kt$FileResolver$( android.Manifest.permission.WRITE_EXTERNAL_STORAGE, WRITE_STORAGE_GUIDE )</ID>- <ID>ArgumentListWrapping:FileTool.kt$FileTool$( resolved.file, path, sortBy, include, exclude, recursive, maxDepth )</ID>- <ID>ArgumentListWrapping:FileTool.kt$FileTool$("${file.name} (${resolver.formatSize(file.length())})\nResolved: ${file.canonicalPath}")</ID>- <ID>ArgumentListWrapping:FileTool.kt$FileTool$("${if (append) "Appended" else "Wrote"} ${resolver.formatSize(bytes.size.toLong())} to '$originalPath' (resolved: ${file.canonicalPath}).")</ID>- <ID>ArgumentListWrapping:FileTool.kt$FileTool$("(Showing lines $startLine-$endLine of ${lines.size}. Use offset=${endLine + 1} to continue.)")</ID>- <ID>ArgumentListWrapping:FileTool.kt$FileTool$("Archive: ${file.name} (${resolver.formatSize(file.length())}, ${entries.size} entries, ${resolver.formatSize(totalSize)} uncompressed)")</ID>- <ID>ArgumentListWrapping:FileTool.kt$FileTool$("File too large (${resolver.formatSize(file.length())}). Max: ${MAX_BINARY_BYTES / 1024 / 1024} MB.")</ID>- <ID>ArgumentListWrapping:FileTool.kt$FileTool$("Image too large (${resolver.formatSize(file.length())}). Max: ${MAX_IMAGE_BYTES / 1024 / 1024} MB.")</ID>- <ID>ArgumentListWrapping:FileTool.kt$FileTool$("Path '$originalPath' does not exist (resolved: ${file.canonicalPath}).")</ID>- <ID>ArgumentListWrapping:FileTool.kt$FileTool$("Wrote ${resolver.formatSize(bytes.size.toLong())} binary data to '$originalPath' (resolved: ${file.canonicalPath}).")</ID>- <ID>ArgumentListWrapping:FileTool.kt$FileTool$(bytes.size.toLong())</ID>- <ID>ArgumentListWrapping:FileTool.kt$FileTool$(file.length())</ID>- <ID>ArgumentListWrapping:FileTool.kt$FileTool$(totalSize)</ID>- <ID>ArgumentListWrapping:FileTool.kt$FileTool.Companion$( ".zip/", ".apk/", ".aar/", ".jar/", ".war/", ".docx/", ".xlsx/", ".pptx/" )</ID>- <ID>ArgumentListWrapping:LocationTool.kt$LocationTool$( lat, lng, accuracy, altitude, bearing, speed, where, source )</ID>- <ID>ArgumentListWrapping:MainActivity.kt$MainActivity$( apiKey = "unused", baseUrl = "http://localhost/", context = this@MainActivity )</ID>- <ID>ArgumentListWrapping:MainActivity.kt$MainActivity$(AndroidSettings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName"))</ID>- <ID>ArgumentListWrapping:PermissionItems.kt$( "Accessibility", "Read screen, tap, swipe, type", null, "special:accessibility_access", { c -> val expected = "${c.packageName}/com.gotcha.service.GotchaAccessibilityService" val enabled = Settings.Secure.getString( c.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES ) ?: "" enabled.contains(expected, ignoreCase = true) } )</ID>- <ID>ArgumentListWrapping:PermissionItems.kt$( "All Files Access", "Full access to all files on device", null, "special:all_files_access", { c -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) Environment.isExternalStorageManager() else checkPerm(c, android.Manifest.permission.READ_EXTERNAL_STORAGE) } )</ID>- <ID>ArgumentListWrapping:PermissionItems.kt$( "Calendar", "Read and create calendar events", android.Manifest.permission.READ_CALENDAR, null, { c -> checkPerm(c, android.Manifest.permission.READ_CALENDAR) && checkPerm(c, android.Manifest.permission.WRITE_CALENDAR) }, extraPermissions = listOf(android.Manifest.permission.WRITE_CALENDAR) )</ID>- <ID>ArgumentListWrapping:PermissionItems.kt$( "Call Log", "Read recent call history", android.Manifest.permission.READ_CALL_LOG, null, { c -> checkPerm(c, android.Manifest.permission.READ_CALL_LOG) } )</ID>- <ID>ArgumentListWrapping:PermissionItems.kt$( "Camera", "Take photos", android.Manifest.permission.CAMERA, null, { c -> checkPerm(c, android.Manifest.permission.CAMERA) } )</ID>- <ID>ArgumentListWrapping:PermissionItems.kt$( "Contacts", "Read and create contacts", android.Manifest.permission.READ_CONTACTS, null, { c -> checkPerm(c, android.Manifest.permission.READ_CONTACTS) && checkPerm(c, android.Manifest.permission.WRITE_CONTACTS) }, extraPermissions = listOf(android.Manifest.permission.WRITE_CONTACTS) )</ID>- <ID>ArgumentListWrapping:PermissionItems.kt$( "Device Admin", "Lock screen, enforce password policy", null, "special:device_admin", { c -> val dpm = c.getSystemService(Context.DEVICE_POLICY_SERVICE) as? DevicePolicyManager dpm?.isAdminActive(ComponentName(c, GotchaDeviceAdminReceiver::class.java)) ?: false } )</ID>- <ID>ArgumentListWrapping:PermissionItems.kt$( "Display Over Apps", "Show floating overlays", null, "special:overlay_access", { c -> Settings.canDrawOverlays(c) } )</ID>- <ID>ArgumentListWrapping:PermissionItems.kt$( "Do Not Disturb", "Silence/vibrate mode and DND", null, "special:dnd_access", { c -> val nm = c.getSystemService(Context.NOTIFICATION_SERVICE) as? android.app.NotificationManager nm?.isNotificationPolicyAccessGranted ?: false } )</ID>- <ID>ArgumentListWrapping:PermissionItems.kt$( "Location", "Get device location", android.Manifest.permission.ACCESS_FINE_LOCATION, null, { c -> checkPerm(c, android.Manifest.permission.ACCESS_FINE_LOCATION) } )</ID>- <ID>ArgumentListWrapping:PermissionItems.kt$( "Microphone", "Record audio", android.Manifest.permission.RECORD_AUDIO, null, { c -> checkPerm(c, android.Manifest.permission.RECORD_AUDIO) } )</ID>- <ID>ArgumentListWrapping:PermissionItems.kt$( "Notification Listener", "Read and dismiss notifications, media control", null, "special:notification_listener_access", { c -> val expected = c.packageName val enabled = Settings.Secure.getString( c.contentResolver, "enabled_notification_listeners" ) ?: "" enabled.contains(expected, ignoreCase = true) } )</ID>- <ID>ArgumentListWrapping:PermissionItems.kt$( "Phone", "Place calls directly", android.Manifest.permission.CALL_PHONE, null, { c -> checkPerm(c, android.Manifest.permission.CALL_PHONE) } )</ID>- <ID>ArgumentListWrapping:PermissionItems.kt$( "Read SMS", "Read inbox messages", android.Manifest.permission.READ_SMS, null, { c -> checkPerm(c, android.Manifest.permission.READ_SMS) } )</ID>- <ID>ArgumentListWrapping:PermissionItems.kt$( "SMS", "Send text messages", android.Manifest.permission.SEND_SMS, null, { c -> checkPerm(c, android.Manifest.permission.SEND_SMS) } )</ID>- <ID>ArgumentListWrapping:PermissionItems.kt$( "Storage Read", "Read files from shared storage", if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) android.Manifest.permission.READ_MEDIA_IMAGES else android.Manifest.permission.READ_EXTERNAL_STORAGE, null, { c -> val perm = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) android.Manifest.permission.READ_MEDIA_IMAGES else android.Manifest.permission.READ_EXTERNAL_STORAGE checkPerm(c, perm) } )</ID>- <ID>ArgumentListWrapping:PermissionItems.kt$( "Storage Write", "Write files to shared storage", android.Manifest.permission.WRITE_EXTERNAL_STORAGE, null, { c -> if (Build.VERSION.SDK_INT <= 29) checkPerm(c, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) else true // API 30+ uses MANAGE_EXTERNAL_STORAGE } )</ID>- <ID>ArgumentListWrapping:PermissionItems.kt$( "Usage Access", "Read app usage and data stats", null, "special:usage_access", { c -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { val appOps = c.getSystemService(Context.APP_OPS_SERVICE) as? AppOpsManager appOps?.checkOpNoThrow( AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), c.packageName ) == AppOpsManager.MODE_ALLOWED } else true } )</ID>- <ID>ArgumentListWrapping:PermissionItems.kt$( "VPN", "Block all network traffic (firewall kill-switch)", null, "special:vpn_consent", { c -> try { val cm = c.getSystemService(Context.CONNECTIVITY_SERVICE) as? android.net.ConnectivityManager cm?.let { mgr -> val network = mgr.activeNetwork if (network != null) { mgr.getNetworkCapabilities(network) ?.hasTransport(android.net.NetworkCapabilities.TRANSPORT_VPN) ?: false } else false } ?: false } catch (_: SecurityException) { false } } )</ID>- <ID>ArgumentListWrapping:PermissionItems.kt$( "Write Settings", "Modify system settings (brightness)", null, "special:write_settings", { c -> Settings.System.canWrite(c) } )</ID>- <ID>ArgumentListWrapping:PermissionsSection.kt$("package:$packageName")</ID>- <ID>ArgumentListWrapping:PermissionsSection.kt$(AndroidSettings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:$packageName"))</ID>- <ID>ArgumentListWrapping:PhoneTool.kt$PhoneTool$( uri, arrayOf(ContactsContract.PhoneLookup.DISPLAY_NAME), null, null, null )</ID>- <ID>ArgumentListWrapping:PhoneTool.kt$PhoneTool$(86_400_000L - 1)</ID>- <ID>ArgumentListWrapping:PhoneTool.kt$PhoneTool$(toDate)</ID>- <ID>ArgumentListWrapping:SettingsScreen.kt$(emptyList(), emptyList())</ID>- <ID>ArgumentListWrapping:SettingsScreen.kt$(expanded = sttModelExpanded)</ID>- <ID>ArgumentListWrapping:SettingsScreen.kt$(expanded = ttsModelExpanded)</ID>- <ID>ArgumentListWrapping:SmsTool.kt$SmsTool$( context, System.currentTimeMillis().toInt() and 0x7FFFFFFF, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT )</ID>- <ID>ArgumentListWrapping:SmsTool.kt$SmsTool$( context, number.hashCode() and 0x7FFFFFFF, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT )</ID>- <ID>ArgumentListWrapping:SmsTool.kt$SmsTool$( context, receiver, IntentFilter("com.gotcha.SMS_SENT"), ContextCompat.RECEIVER_NOT_EXPORTED )</ID>- <ID>ArgumentListWrapping:SmsTool.kt$SmsTool$( uri, arrayOf(Telephony.Sms.ADDRESS, Telephony.Sms.BODY, Telephony.Sms.DATE, Telephony.Sms._ID), selection, selectionArgs, "${Telephony.Sms.DATE} DESC" )</ID>- <ID>ArgumentListWrapping:SmsTool.kt$SmsTool$( uri, arrayOf(android.provider.ContactsContract.PhoneLookup.DISPLAY_NAME), null, null, null )</ID>- <ID>ArgumentListWrapping:SmsTool.kt$SmsTool$(86_400_000L - 1)</ID>- <ID>ArgumentListWrapping:SmsTool.kt$SmsTool$(toDate)</ID>- <ID>ArgumentListWrapping:StorageTool.kt$StorageTool$("Internal storage: ${format(internal.used)} used of ${format(internal.total)} total, ${format(internal.free)} free")</ID>- <ID>ArgumentListWrapping:StorageTool.kt$StorageTool$("\nExternal / SD card: ${format(external.used)} used of ${format(external.total)} total, ${format(external.free)} free")</ID>- <ID>ArgumentListWrapping:StorageTool.kt$StorageTool$(external.free)</ID>- <ID>ArgumentListWrapping:StorageTool.kt$StorageTool$(external.total)</ID>- <ID>ArgumentListWrapping:StorageTool.kt$StorageTool$(external.used)</ID>- <ID>ArgumentListWrapping:StorageTool.kt$StorageTool$(internal.free)</ID>- <ID>ArgumentListWrapping:StorageTool.kt$StorageTool$(internal.total)</ID>- <ID>ArgumentListWrapping:StorageTool.kt$StorageTool$(internal.used)</ID>- <ID>ArgumentListWrapping:SystemTool.kt$SystemTool$(null, android.content.IntentFilter(android.content.Intent.ACTION_BATTERY_CHANGED))</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("description", "Audio source: 'mic' (default), 'voice' (optimized for speech), or 'camcorder' (wider range).")</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("description", "Calendar account name to add the event to (e.g. 'Work', 'Personal'). Defaults to the primary writable calendar.")</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("description", "Custom file path to save the recording. Defaults to Recordings/recording_{timestamp}.m4a.")</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("description", "Filter by call type: 'incoming', 'outgoing', 'missed', or 'rejected'. Omit for all.")</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("description", "Filter by sender/recipient address (partial match, e.g. a contact name or phone number).")</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("description", "How many days ahead to include (1-365). Default 7 when from_date/to_date not set.")</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("description", "If true, request a fresh GPS fix (takes a few seconds). Default false (uses last-known location).")</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("description", "New reminder before event in minutes. -1 to remove reminder. Omit to keep current.")</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("description", "One of: pending, in_progress, completed, cancelled.")</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("description", "Optional output format: 'text' (default) or 'markdown'. Currently always returns text.")</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("description", "Optional: auto-turn off after this many seconds (1-300). Only applies when turning on.")</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("description", "Optional: high, medium, low.")</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("description", "Phone number label: 'mobile' (default), 'home', 'work', 'main', 'fax', or 'pager'.")</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("description", "Predefined pattern: short (100ms), long (1s), double (two quick buzzes), sos (...---...). Overrides duration_ms.")</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("description", "Recording quality: 'low' (16kHz, 16kbps), 'medium' (44.1kHz, 64kbps), or 'high' (44.1kHz, 192kbps). Default medium.")</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("description", "Repeating days: e.g. ['mon','wed','fri'] or ['weekdays']. Omit for one-time alarm.")</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("description", "SIM slot to use: 'sim1' or 'sim2'. Only needed on dual-SIM devices. Default is the system default.")</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("description", "Schedule future delivery: ISO-8601 timestamp like '2026-01-15T14:30:00' or epoch millis. Omit for immediate send.")</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("description", "Vibration length in milliseconds (1-5000). Default 500. Ignored when pattern is set.")</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("description", "Which stream to read: media, ring, alarm, notification, call. If omitted, all streams are reported.")</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("description", "Working directory for the command (absolute path). Defaults to the app's working directory.")</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("priority")</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("status")</ID>- <ID>ArgumentListWrapping:ToolDefinitions.kt$ToolDefinitions$("type", "string")</ID>- <ID>ArgumentListWrapping:ToolExecutor.kt$ToolExecutor$( direction = args.requireString("direction"), x1 = args.requireInt("x1"), y1 = args.requireInt("y1"), x2 = args.requireInt("x2"), y2 = args.requireInt("y2") )</ID>- <ID>ArgumentListWrapping:ToolExecutor.kt$ToolExecutor$(TAG, "execute: $name -> success=${result.success}, msgLen=${result.message.length}, perm=${result.needsPermission}")</ID>- <ID>ArgumentListWrapping:TtsEngine.kt$TtsEngine$(AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_MEDIA) .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH) .build())</ID>- <ID>ArgumentListWrapping:TtsEngine.kt$TtsEngine$(AudioFormat.Builder() .setEncoding(AudioFormat.ENCODING_PCM_16BIT) .setSampleRate(24000) .setChannelMask(AudioFormat.CHANNEL_OUT_MONO) .build())</ID>- <ID>ArgumentListWrapping:WebFetchTool.kt$WebFetchTool$("User-Agent", "Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.6422.165 Mobile Safari/537.36")</ID>- <ID>ArgumentListWrapping:WebSearchTool.kt$WebSearchTool$("User-Agent", "Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.6422.165 Mobile Safari/537.36")</ID>- <ID>ChainWrapping:LLMClient.kt$LLMClient$&&</ID>- <ID>ChainWrapping:SystemTool.kt$SystemTool$||</ID>- <ID>ComplexCondition:AccessibilityTool.kt$AccessibilityTool$x1 != null && y1 != null && x2 != null && y2 != null</ID>- <ID>ComplexCondition:FileResolver.kt$FileResolver$bytes.size >= 3 && bytes[0] == 0x47.toByte() && bytes[1] == 0x49.toByte() && bytes[2] == 0x46.toByte()</ID>- <ID>ComplexCondition:FileResolver.kt$FileResolver$bytes.size >= 3 && bytes[0] == 0xFF.toByte() && bytes[1] == 0xD8.toByte() && bytes[2] == 0xFF.toByte()</ID>- <ID>ComplexCondition:FileResolver.kt$FileResolver$bytes.size >= 4 && bytes[0] == 0x4D.toByte() && bytes[1] == 0x54.toByte() && bytes[2] == 0x68.toByte() && bytes[3] == 0x64.toByte()</ID>- <ID>ComplexCondition:FileResolver.kt$FileResolver$bytes.size >= 5 && bytes[0] == 0x25.toByte() && bytes[1] == 0x50.toByte() && bytes[2] == 0x44.toByte() && bytes[3] == 0x46.toByte() && bytes[4] == 0x2D.toByte()</ID>- <ID>ComplexCondition:FileResolver.kt$FileResolver$bytes.size >= 8 && bytes[0] == 0x89.toByte() && bytes[1] == 0x50.toByte() && bytes[2] == 0x4E.toByte() && bytes[3] == 0x47.toByte()</ID>- <ID>ComplexCondition:LocationTool.kt$LocationTool$loc != null && (current == null || loc.time > current.time || loc.accuracy < current.accuracy)</ID>- <ID>ComplexCondition:TtsEngine.kt$TtsEngine$bytes.size > 44 && bytes[0] == 0x52.toByte() && bytes[1] == 0x49.toByte() && bytes[2] == 0x46.toByte() && bytes[3] == 0x46.toByte()</ID>- <ID>CyclomaticComplexMethod:AudioModels.kt$AudioModel.Companion$fun categorize(id: String, task: String? = null): ModelCategory</ID>- <ID>CyclomaticComplexMethod:CalendarTool.kt$CalendarTool$fun createEvent( title: String, start: String, end: String? = null, location: String? = null, description: String? = null, allDay: Boolean? = null, reminderMinutes: Int? = null, calendarName: String? = null ): ToolResult</ID>- <ID>CyclomaticComplexMethod:CalendarTool.kt$CalendarTool$fun editEvent( eventId: Long, title: String? = null, start: String? = null, end: String? = null, location: String? = null, description: String? = null, allDay: Boolean? = null, reminderMinutes: Int? = null ): ToolResult</ID>- <ID>CyclomaticComplexMethod:CalendarTool.kt$CalendarTool$fun listEvents( daysAhead: Int? = null, fromDate: String? = null, toDate: String? = null, search: String? = null ): ToolResult</ID>- <ID>CyclomaticComplexMethod:ChatScreen.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable fun ChatScreen( state: ChatUiState, onSend: (String, String?) -> Unit, onStop: () -> Unit, onConfirm: (Boolean) -> Unit, onAnswer: (String?) -> Unit, onBack: () -> Unit, onOpenSettings: () -> Unit, onPickImage: (Uri) -> String?, onSwitchAgent: () -> Unit, onSpeak: (String) -> Unit = {}, onStartListening: () -> Unit = {}, onStopRecording: () -> Unit = {} )</ID>- <ID>CyclomaticComplexMethod:ChatViewModel.kt$ChatViewModel$private fun buildEnvironmentString(agent: AgentMode): String</ID>- <ID>CyclomaticComplexMethod:ChatViewModel.kt$ChatViewModel$private suspend fun runToolLoop()</ID>- <ID>CyclomaticComplexMethod:ContactsTool.kt$ContactsTool$fun addContact( name: String, number: String, phoneType: String? = null, email: String? = null, organization: String? = null ): ToolResult</ID>- <ID>CyclomaticComplexMethod:ContactsTool.kt$ContactsTool$fun findContact(name: String? = null, number: String? = null): ToolResult</ID>- <ID>CyclomaticComplexMethod:EditTool.kt$EditTool$fun edit(path: String, oldString: String, newString: String, replaceAll: Boolean): ToolResult</ID>- <ID>CyclomaticComplexMethod:FileResolver.kt$FileResolver$fun detectMime(bytes: ByteArray): String?</ID>- <ID>CyclomaticComplexMethod:FileTool.kt$FileTool$private fun listResolved( file: File, originalPath: String, sortBy: String?, include: String?, exclude: String?, recursive: Boolean, maxDepth: Int? ): ToolResult</ID>- <ID>CyclomaticComplexMethod:FileTool.kt$FileTool$private fun readTextFile(file: File, offset: Int?, limit: Int?, encoding: String?): ToolResult</ID>- <ID>CyclomaticComplexMethod:FileTool.kt$FileTool$private fun readUnknownFile(file: File, encoding: String?): ToolResult</ID>- <ID>CyclomaticComplexMethod:FileTool.kt$FileTool$private fun readZipEntry(zf: ZipFile, archiveFile: File, archivePath: String, entryPath: String): ToolResult</ID>- <ID>CyclomaticComplexMethod:GlobTool.kt$GlobTool$fun glob(path: String, pattern: String): ToolResult</ID>- <ID>CyclomaticComplexMethod:GrepTool.kt$GrepTool$fun grep(path: String, pattern: String, include: String?): ToolResult</ID>- <ID>CyclomaticComplexMethod:MediaCaptureTool.kt$MediaCaptureTool$fun startAudioRecording( source: String? = null, maxDurationSeconds: Int? = null, outputPath: String? = null, quality: String? = null ): ToolResult</ID>- <ID>CyclomaticComplexMethod:MessageBubble.kt$@OptIn(ExperimentalFoundationApi::class) @Composable fun MessageBubble( message: UiMessage, onSpeak: (String) -> Unit = {} )</ID>- <ID>CyclomaticComplexMethod:PermissionItems.kt$fun allPermissionGroups(context: Context): List<PermissionGroup></ID>- <ID>CyclomaticComplexMethod:PermissionsSection.kt$private fun openSpecialAccess(context: android.content.Context, marker: String, packageName: String)</ID>- <ID>CyclomaticComplexMethod:PhoneTool.kt$PhoneTool$fun readCallLog( limit: Int, callTypeFilter: String? = null, contact: String? = null, fromDate: String? = null, toDate: String? = null ): ToolResult</ID>- <ID>CyclomaticComplexMethod:SettingsScreen.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable fun SettingsScreen( initial: Settings, onSave: (Settings) -> Unit, onTestConnection: suspend (Settings) -> Result<String>, onClearLlmCache: () -> Unit, onBack: () -> Unit, onRefreshAudioModels: suspend (Settings) -> Pair<List<AudioModel>, List<AudioModel>> = { Pair(emptyList(), emptyList()) }, packageName: String = "" )</ID>- <ID>CyclomaticComplexMethod:SmsTool.kt$SmsTool$fun readRecentSms( limit: Int, fromAddress: String? = null, fromDate: String? = null, toDate: String? = null, unreadOnly: Boolean? = null, search: String? = null, includeSent: Boolean? = null ): ToolResult</ID>- <ID>CyclomaticComplexMethod:SmsTool.kt$SmsTool$fun sendSms( number: String, message: String, deliveryReport: Boolean? = null, sendAt: String? = null ): ToolResult</ID>- <ID>CyclomaticComplexMethod:SystemTool.kt$SystemTool$fun getBatteryInfo(): ToolResult</ID>- <ID>CyclomaticComplexMethod:ToolExecutor.kt$ToolExecutor$private suspend fun dispatch(name: String, args: JsonObject): ToolResult</ID>- <ID>CyclomaticComplexMethod:WebFetchTool.kt$WebFetchTool$fun fetch(url: String, format: String?): ToolResult</ID>- <ID>CyclomaticComplexMethod:WebFetchTool.kt$WebFetchTool$private fun htmlToMarkdown(doc: Document): String</ID>- <ID>CyclomaticComplexMethod:WebSearchTool.kt$WebSearchTool$fun search(query: String, numResults: Int): ToolResult</ID>- <ID>DestructuringDeclarationWithTooManyEntries:AccessibilityTool.kt$AccessibilityTool$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." ) }</ID>- <ID>EmptyDefaultConstructor:StorageTool.kt$StorageTool$()</ID>- <ID>EmptyFunctionBlock:GotchaAccessibilityService.kt$GotchaAccessibilityService${}</ID>- <ID>EmptyFunctionBlock:GotchaNotificationListenerService.kt$GotchaNotificationListenerService${}</ID>- <ID>EmptyFunctionBlock:LocationTool.kt$LocationTool.<no name provided>${}</ID>- <ID>EmptyFunctionBlock:SttEngine.kt$SttEngine.<no name provided>${}</ID>- <ID>EmptyFunctionBlock:TtsEngine.kt$TtsEngine.<no name provided>${}</ID>- <ID>FunctionNaming:ChatScreen.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable fun ChatScreen( state: ChatUiState, onSend: (String, String?) -> Unit, onStop: () -> Unit, onConfirm: (Boolean) -> Unit, onAnswer: (String?) -> Unit, onBack: () -> Unit, onOpenSettings: () -> Unit, onPickImage: (Uri) -> String?, onSwitchAgent: () -> Unit, onSpeak: (String) -> Unit = {}, onStartListening: () -> Unit = {}, onStopRecording: () -> Unit = {} )</ID>- <ID>FunctionNaming:MainActivity.kt$MainActivity$@Composable private fun GotchaApp()</ID>- <ID>FunctionNaming:MessageBubble.kt$@OptIn(ExperimentalFoundationApi::class) @Composable fun MessageBubble( message: UiMessage, onSpeak: (String) -> Unit = {} )</ID>- <ID>FunctionNaming:PermissionsSection.kt$@Composable fun PermissionsSection(packageName: String)</ID>- <ID>FunctionNaming:PermissionsSection.kt$@Composable private fun PermissionRow( item: PermissionItem, granted: Boolean, packageName: String, onRequestRuntime: (Array<String>) -> Unit )</ID>- <ID>FunctionNaming:SessionsScreen.kt$@Composable fun SessionRow( session: ChatSession, onClick: () -> Unit, onDelete: () -> Unit )</ID>- <ID>FunctionNaming:SessionsScreen.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable fun SessionsScreen( sessions: List<ChatSession>, onSessionClick: (String) -> Unit, onDeleteSession: (String) -> Unit, onNewChat: () -> Unit, onOpenSettings: () -> Unit, assistiveBallEnabled: Boolean = false, onToggleAssistiveBall: (Boolean) -> Unit = {} )</ID>- <ID>FunctionNaming:SettingsScreen.kt$@Composable private fun SectionHeader( title: String, expanded: Boolean, onToggle: () -> Unit )</ID>- <ID>FunctionNaming:SettingsScreen.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable fun SettingsScreen( initial: Settings, onSave: (Settings) -> Unit, onTestConnection: suspend (Settings) -> Result<String>, onClearLlmCache: () -> Unit, onBack: () -> Unit, onRefreshAudioModels: suspend (Settings) -> Pair<List<AudioModel>, List<AudioModel>> = { Pair(emptyList(), emptyList()) }, packageName: String = "" )</ID>- <ID>FunctionNaming:Theme.kt$@Composable fun GotchaTheme( darkTheme: Boolean = isSystemInDarkTheme(), dynamicColor: Boolean = true, content: @Composable () -> Unit )</ID>- <ID>ImportOrdering:AlarmTool.kt$import android.app.AlarmManager import android.app.PendingIntent import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Build import android.provider.AlarmClock import java.text.SimpleDateFormat import java.util.Calendar import java.util.Date import java.util.Locale import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.booleanOrNull import kotlinx.serialization.json.buildJsonArray import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.intOrNull import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.put</ID>- <ID>ImportOrdering:AppsTool.kt$import android.app.AppOpsManager import android.app.usage.NetworkStatsManager import android.app.usage.UsageStatsManager import android.content.Context import android.content.Intent import android.content.pm.ApplicationInfo import android.content.pm.PackageManager import android.util.Log import android.net.ConnectivityManager import android.net.Uri import android.os.Build import android.os.Process</ID>- <ID>ImportOrdering:ChatHistoryRepository.kt$import android.content.Context import com.gotcha.llm.ChatMessage import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.serialization.builtins.ListSerializer import kotlinx.serialization.json.Json import java.io.File import kotlinx.serialization.Serializable import java.util.UUID</ID>- <ID>ImportOrdering:ChatScreen.kt$import android.net.Uri import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.Image as ComposeImage import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Mic import androidx.compose.material.icons.filled.Send import androidx.compose.material.icons.filled.Stop import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.FilterChip import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.unit.dp import com.gotcha.agent.ChatUiState import com.gotcha.agent.PendingQuestion import com.gotcha.tools.AgentMode</ID>- <ID>ImportOrdering:ChatViewModel.kt$import android.app.Application import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.util.Log import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.gotcha.audio.AudioProvider import com.gotcha.audio.AudioModel import com.gotcha.audio.SttEngine import com.gotcha.audio.TtsEngine import com.gotcha.data.ChatHistoryRepository import com.gotcha.data.Settings import com.gotcha.data.SettingsRepository import com.gotcha.llm.ChatMessage import com.gotcha.data.ChatSession import com.gotcha.llm.LLMClient import com.gotcha.llm.ToolCall import com.gotcha.llm.visionUserMessage import com.gotcha.tools.AgentMode import com.gotcha.tools.FileResolver import com.gotcha.tools.ToolExecutor import com.gotcha.tools.ToolRegistry import com.gotcha.tools.ToolResult import com.gotcha.ui.ConfirmationOverlay import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.CancellationException import kotlinx.coroutines.withContext import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.withTimeoutOrNull import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put import java.io.ByteArrayOutputStream</ID>- <ID>ImportOrdering:LLMClient.kt$import android.content.Context import kotlinx.serialization.builtins.ListSerializer import kotlinx.serialization.json.Json import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory import java.security.MessageDigest</ID>- <ID>ImportOrdering:MainActivity.kt$import android.app.admin.DevicePolicyManager import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.net.Uri import android.net.VpnService import android.os.Build import android.os.Bundle import android.provider.Settings as AndroidSettings import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.compose.BackHandler import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.viewModels import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.lifecycle.lifecycleScope import com.gotcha.agent.ChatViewModel import com.gotcha.audio.AudioApi import com.gotcha.audio.AudioModel import com.gotcha.audio.ModelCategory import com.gotcha.data.Settings import com.gotcha.data.SettingsRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import com.gotcha.llm.ChatMessage import com.gotcha.llm.LLMClient import kotlinx.serialization.json.JsonPrimitive import com.gotcha.service.AssistiveBallService import com.gotcha.service.GotchaDeviceAdminReceiver import com.gotcha.tools.ToolResult import com.gotcha.ui.ChatScreen import com.gotcha.ui.SessionsScreen import com.gotcha.ui.SettingsScreen import com.gotcha.ui.theme.GotchaTheme import kotlinx.coroutines.launch</ID>- <ID>ImportOrdering:MessageBubble.kt$import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.widget.Toast import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.shape.RoundedCornerShape import com.halilibo.richtext.markdown.Markdown import com.halilibo.richtext.ui.material3.Material3RichText import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.rounded.VolumeUp import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.gotcha.agent.MessageKind import com.gotcha.agent.UiMessage</ID>- <ID>ImportOrdering:PermissionItems.kt$import android.content.Context import android.os.Build import android.os.Environment import android.provider.Settings import android.app.admin.DevicePolicyManager import android.app.AppOpsManager import android.content.ComponentName import android.content.ContextWrapper import androidx.core.content.ContextCompat import com.gotcha.service.GotchaDeviceAdminReceiver</ID>- <ID>ImportOrdering:PermissionsSection.kt$import android.content.Intent import android.net.Uri import android.net.VpnService import android.os.Build import android.provider.Settings as AndroidSettings import android.app.admin.DevicePolicyManager import android.content.ComponentName import android.widget.Toast import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import com.gotcha.service.GotchaDeviceAdminReceiver import com.gotcha.tools.ToolResult</ID>- <ID>ImportOrdering:ToolDefinitions.kt$import com.gotcha.llm.FunctionDefinition import com.gotcha.llm.ToolDefinition import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put import kotlinx.serialization.json.putJsonArray import kotlinx.serialization.json.putJsonObject import kotlinx.serialization.json.add</ID>- <ID>Indentation:CalendarTool.kt$CalendarTool$ </ID>- <ID>Indentation:ChatViewModel.kt$ChatViewModel$ </ID>- <ID>Indentation:ContactsTool.kt$ContactsTool$ </ID>- <ID>Indentation:FileResolver.kt$FileResolver.Companion$ </ID>- <ID>Indentation:FileTool.kt$FileTool$ </ID>- <ID>Indentation:LLMClient.kt$LLMClient$ </ID>- <ID>Indentation:MediaCaptureTool.kt$MediaCaptureTool$ </ID>- <ID>Indentation:SystemTool.kt$SystemTool$ </ID>- <ID>Indentation:ToolExecutor.kt$ToolExecutor$ </ID>- <ID>LargeClass:ChatViewModel.kt$ChatViewModel : AndroidViewModel</ID>- <ID>LargeClass:ToolDefinitions.kt$ToolDefinitions</ID>- <ID>LongMethod:CalendarTool.kt$CalendarTool$fun listEvents( daysAhead: Int? = null, fromDate: String? = null, toDate: String? = null, search: String? = null ): ToolResult</ID>- <ID>LongMethod:ChatScreen.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable fun ChatScreen( state: ChatUiState, onSend: (String, String?) -> Unit, onStop: () -> Unit, onConfirm: (Boolean) -> Unit, onAnswer: (String?) -> Unit, onBack: () -> Unit, onOpenSettings: () -> Unit, onPickImage: (Uri) -> String?, onSwitchAgent: () -> Unit, onSpeak: (String) -> Unit = {}, onStartListening: () -> Unit = {}, onStopRecording: () -> Unit = {} )</ID>- <ID>LongMethod:ContactsTool.kt$ContactsTool$fun addContact( name: String, number: String, phoneType: String? = null, email: String? = null, organization: String? = null ): ToolResult</ID>- <ID>LongMethod:ContactsTool.kt$ContactsTool$fun findContact(name: String? = null, number: String? = null): ToolResult</ID>- <ID>LongMethod:MainActivity.kt$MainActivity$@Composable private fun GotchaApp()</ID>- <ID>LongMethod:MessageBubble.kt$@OptIn(ExperimentalFoundationApi::class) @Composable fun MessageBubble( message: UiMessage, onSpeak: (String) -> Unit = {} )</ID>- <ID>LongMethod:PermissionItems.kt$fun allPermissionGroups(context: Context): List<PermissionGroup></ID>- <ID>LongMethod:PhoneTool.kt$PhoneTool$fun readCallLog( limit: Int, callTypeFilter: String? = null, contact: String? = null, fromDate: String? = null, toDate: String? = null ): ToolResult</ID>- <ID>LongMethod:SettingsScreen.kt$@OptIn(ExperimentalMaterial3Api::class) @Composable fun SettingsScreen( initial: Settings, onSave: (Settings) -> Unit, onTestConnection: suspend (Settings) -> Result<String>, onClearLlmCache: () -> Unit, onBack: () -> Unit, onRefreshAudioModels: suspend (Settings) -> Pair<List<AudioModel>, List<AudioModel>> = { Pair(emptyList(), emptyList()) }, packageName: String = "" )</ID>- <ID>LongMethod:ToolExecutor.kt$ToolExecutor$private suspend fun dispatch(name: String, args: JsonObject): ToolResult</ID>- <ID>LongParameterList:ChatScreen.kt$( state: ChatUiState, onSend: (String, String?) -> Unit, onStop: () -> Unit, onConfirm: (Boolean) -> Unit, onAnswer: (String?) -> Unit, onBack: () -> Unit, onOpenSettings: () -> Unit, onPickImage: (Uri) -> String?, onSwitchAgent: () -> Unit, onSpeak: (String) -> Unit = {}, onStartListening: () -> Unit = {}, onStopRecording: () -> Unit = {} )</ID>- <ID>LoopWithTooManyJumpStatements:FileTool.kt$FileTool$for</ID>- <ID>LoopWithTooManyJumpStatements:GrepTool.kt$GrepTool$for</ID>- <ID>LoopWithTooManyJumpStatements:WebSearchTool.kt$WebSearchTool$for</ID>- <ID>MagicNumber:AccessibilityTool.kt$AccessibilityTool$0.3f</ID>- <ID>MagicNumber:AccessibilityTool.kt$AccessibilityTool$0.7f</ID>- <ID>MagicNumber:ActionLog.kt$ActionLog$1024</ID>- <ID>MagicNumber:ActionLog.kt$ActionLog$500</ID>- <ID>MagicNumber:ActionLog.kt$ActionLog$512</ID>- <ID>MagicNumber:AlarmReceiver.kt$AlarmReceiver$1000</ID>- <ID>MagicNumber:AlarmReceiver.kt$AlarmReceiver$2000</ID>- <ID>MagicNumber:AlarmTool.kt$AlarmTool$1000</ID>- <ID>MagicNumber:AlarmTool.kt$AlarmTool$23</ID>- <ID>MagicNumber:AlarmTool.kt$AlarmTool$3</ID>- <ID>MagicNumber:AlarmTool.kt$AlarmTool$3600</ID>- <ID>MagicNumber:AlarmTool.kt$AlarmTool$59</ID>- <ID>MagicNumber:AlarmTool.kt$AlarmTool$6</ID>- <ID>MagicNumber:AlarmTool.kt$AlarmTool$60</ID>- <ID>MagicNumber:AlarmTool.kt$AlarmTool$7</ID>- <ID>MagicNumber:AlarmTool.kt$AlarmTool.TimerRecord$1000L</ID>- <ID>MagicNumber:AppsTool.kt$AppsTool$10</ID>- <ID>MagicNumber:AppsTool.kt$AppsTool$1000</ID>- <ID>MagicNumber:AppsTool.kt$AppsTool$200</ID>- <ID>MagicNumber:AppsTool.kt$AppsTool$24L</ID>- <ID>MagicNumber:AppsTool.kt$AppsTool$30</ID>- <ID>MagicNumber:AppsTool.kt$AppsTool$60</ID>- <ID>MagicNumber:AppsTool.kt$AppsTool$60000</ID>- <ID>MagicNumber:AppsTool.kt$AppsTool$90</ID>- <ID>MagicNumber:AssistiveBallOverlay.kt$AssistiveBallOverlay$12</ID>- <ID>MagicNumber:AssistiveBallOverlay.kt$AssistiveBallOverlay$13f</ID>- <ID>MagicNumber:AssistiveBallOverlay.kt$AssistiveBallOverlay$14f</ID>- <ID>MagicNumber:AssistiveBallOverlay.kt$AssistiveBallOverlay$16</ID>- <ID>MagicNumber:AssistiveBallOverlay.kt$AssistiveBallOverlay$160</ID>- <ID>MagicNumber:AssistiveBallOverlay.kt$AssistiveBallOverlay$20</ID>- <ID>MagicNumber:AssistiveBallOverlay.kt$AssistiveBallOverlay$240</ID>- <ID>MagicNumber:AssistiveBallOverlay.kt$AssistiveBallOverlay$260</ID>- <ID>MagicNumber:AssistiveBallOverlay.kt$AssistiveBallOverlay$320</ID>- <ID>MagicNumber:AssistiveBallOverlay.kt$AssistiveBallOverlay$4</ID>- <ID>MagicNumber:AssistiveBallOverlay.kt$AssistiveBallOverlay$56</ID>- <ID>MagicNumber:AssistiveBallOverlay.kt$AssistiveBallOverlay$64</ID>- <ID>MagicNumber:AssistiveBallOverlay.kt$AssistiveBallOverlay$8</ID>- <ID>MagicNumber:AssistiveBallService.kt$AssistiveBallService$350</ID>- <ID>MagicNumber:AssistiveBallService.kt$AssistiveBallService$401</ID>- <ID>MagicNumber:AudioApi.kt$AudioApi$200</ID>- <ID>MagicNumber:CalendarTool.kt$CalendarTool$1000</ID>- <ID>MagicNumber:CalendarTool.kt$CalendarTool$200</ID>- <ID>MagicNumber:CalendarTool.kt$CalendarTool$24L</ID>- <ID>MagicNumber:CalendarTool.kt$CalendarTool$365</ID>- <ID>MagicNumber:CalendarTool.kt$CalendarTool$50</ID>- <ID>MagicNumber:CalendarTool.kt$CalendarTool$60</ID>- <ID>MagicNumber:CalendarTool.kt$CalendarTool$7</ID>- <ID>MagicNumber:CalendarTool.kt$CalendarTool$86400000L</ID>- <ID>MagicNumber:CalendarTool.kt$CalendarTool$86_400_000L</ID>- <ID>MagicNumber:ChatViewModel.kt$ChatViewModel$0.8</ID>- <ID>MagicNumber:ChatViewModel.kt$ChatViewModel$1024</ID>- <ID>MagicNumber:ChatViewModel.kt$ChatViewModel$120_000L</ID>- <ID>MagicNumber:ChatViewModel.kt$ChatViewModel$200</ID>- <ID>MagicNumber:ChatViewModel.kt$ChatViewModel$3</ID>- <ID>MagicNumber:ChatViewModel.kt$ChatViewModel$30</ID>- <ID>MagicNumber:ChatViewModel.kt$ChatViewModel$4</ID>- <ID>MagicNumber:ChatViewModel.kt$ChatViewModel$401</ID>- <ID>MagicNumber:ChatViewModel.kt$ChatViewModel$5</ID>- <ID>MagicNumber:ChatViewModel.kt$ChatViewModel$500</ID>- <ID>MagicNumber:ChatViewModel.kt$ChatViewModel$6</ID>- <ID>MagicNumber:ChatViewModel.kt$ChatViewModel$85</ID>- <ID>MagicNumber:ChatViewModel.kt$ChatViewModel$90</ID>- <ID>MagicNumber:ClipboardTool.kt$ClipboardTool$2000</ID>- <ID>MagicNumber:ClipboardTool.kt$ClipboardTool$34</ID>- <ID>MagicNumber:Color.kt$0xFF002117</ID>- <ID>MagicNumber:Color.kt$0xFF00363D</ID>- <ID>MagicNumber:Color.kt$0xFF004F58</ID>- <ID>MagicNumber:Color.kt$0xFF006C53</ID>- <ID>MagicNumber:Color.kt$0xFF00E5FF</ID>- <ID>MagicNumber:Color.kt$0xFF08201A</ID>- <ID>MagicNumber:Color.kt$0xFF0F172A</ID>- <ID>MagicNumber:Color.kt$0xFF1E293B</ID>- <ID>MagicNumber:Color.kt$0xFF334155</ID>- <ID>MagicNumber:Color.kt$0xFF3F4945</ID>- <ID>MagicNumber:Color.kt$0xFF4C635B</ID>- <ID>MagicNumber:Color.kt$0xFF7A003C</ID>- <ID>MagicNumber:Color.kt$0xFFA6FAFF</ID>- <ID>MagicNumber:Color.kt$0xFFCBD5E1</ID>- <ID>MagicNumber:Color.kt$0xFFCEE9DD</ID>- <ID>MagicNumber:Color.kt$0xFFDBE5E0</ID>- <ID>MagicNumber:Color.kt$0xFFE8F6F2</ID>- <ID>MagicNumber:Color.kt$0xFFFBFDF9</ID>- <ID>MagicNumber:Color.kt$0xFFFF007F</ID>- <ID>MagicNumber:Color.kt$0xFFFFD9E2</ID>- <ID>MagicNumber:Color.kt$0xFFFFFFFF</ID>- <ID>MagicNumber:ConfirmationOverlay.kt$ConfirmationOverlay$13f</ID>- <ID>MagicNumber:ConfirmationOverlay.kt$ConfirmationOverlay$16</ID>- <ID>MagicNumber:ConfirmationOverlay.kt$ConfirmationOverlay$16f</ID>- <ID>MagicNumber:ConfirmationOverlay.kt$ConfirmationOverlay$20</ID>- <ID>MagicNumber:ConfirmationOverlay.kt$ConfirmationOverlay$320</ID>- <ID>MagicNumber:ConfirmationOverlay.kt$ConfirmationOverlay$8</ID>- <ID>MagicNumber:ContactsTool.kt$ContactsTool$10</ID>- <ID>MagicNumber:DeviceAdminTool.kt$DeviceAdminTool$16</ID>- <ID>MagicNumber:DeviceTool.kt$DeviceTool$100</ID>- <ID>MagicNumber:DeviceTool.kt$DeviceTool$1000</ID>- <ID>MagicNumber:DeviceTool.kt$DeviceTool$1000L</ID>- <ID>MagicNumber:DeviceTool.kt$DeviceTool$200</ID>- <ID>MagicNumber:DeviceTool.kt$DeviceTool$255</ID>- <ID>MagicNumber:DeviceTool.kt$DeviceTool$300</ID>- <ID>MagicNumber:DeviceTool.kt$DeviceTool$500</ID>- <ID>MagicNumber:DeviceTool.kt$DeviceTool$5000</ID>- <ID>MagicNumber:DeviceTool.kt$DeviceTool$600</ID>- <ID>MagicNumber:DeviceTool.kt$DeviceTool$800</ID>- <ID>MagicNumber:EditTool.kt$EditTool$5</ID>- <ID>MagicNumber:EditTool.kt$EditTool$80</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$0x03</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$0x04</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$0x1A</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$0x21</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$0x2E</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$0x42</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$0x45</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$0x46</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$0x49</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$0x4B</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$0x50</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$0x52</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$0x57</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$0x61</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$0x64</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$0x66</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$0x6E</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$0x70</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$0x72</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$0x73</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$0x74</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$0x79</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$12</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$23</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$28</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$29</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$3</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$4</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$5</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver$8</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver.Companion$1024</ID>- <ID>MagicNumber:FileResolver.kt$FileResolver.Companion$1024L</ID>- <ID>MagicNumber:FileTool.kt$FileTool$0.05f</ID>- <ID>MagicNumber:FileTool.kt$FileTool$0.3f</ID>- <ID>MagicNumber:FileTool.kt$FileTool$0xFF</ID>- <ID>MagicNumber:FileTool.kt$FileTool$10</ID>- <ID>MagicNumber:FileTool.kt$FileTool$100</ID>- <ID>MagicNumber:FileTool.kt$FileTool$1024</ID>- <ID>MagicNumber:FileTool.kt$FileTool$13</ID>- <ID>MagicNumber:FileTool.kt$FileTool$200</ID>- <ID>MagicNumber:FileTool.kt$FileTool$32</ID>- <ID>MagicNumber:FileTool.kt$FileTool$5</ID>- <ID>MagicNumber:FileTool.kt$FileTool$512</ID>- <ID>MagicNumber:FileTool.kt$FileTool$9</ID>- <ID>MagicNumber:GrepTool.kt$GrepTool$200</ID>- <ID>MagicNumber:GotchaAccessibilityService.kt$GotchaAccessibilityService$50</ID>- <ID>MagicNumber:GotchaAccessibilityService.kt$GotchaAccessibilityService$60_000</ID>- <ID>MagicNumber:GotchaVpnService.kt$GotchaVpnService$128</ID>- <ID>MagicNumber:GotchaVpnService.kt$GotchaVpnService$32</ID>- <ID>MagicNumber:LLMCache.kt$LLMCache$1000</ID>- <ID>MagicNumber:LLMCache.kt$LLMCache$5</ID>- <ID>MagicNumber:LLMCache.kt$LLMCache$60</ID>- <ID>MagicNumber:LLMCache.kt$LLMCache.<no name provided>$0.75f</ID>- <ID>MagicNumber:LLMCache.kt$LLMCache.<no name provided>$16</ID>- <ID>MagicNumber:LocationTool.kt$LocationTool$3.6</ID>- <ID>MagicNumber:LocationTool.kt$LocationTool$8</ID>- <ID>MagicNumber:MainActivity.kt$MainActivity$29</ID>- <ID>MagicNumber:MainActivity.kt$MainActivity$60</ID>- <ID>MagicNumber:MediaCaptureTool.kt$MediaCaptureTool$1000</ID>- <ID>MagicNumber:MediaCaptureTool.kt$MediaCaptureTool$16000</ID>- <ID>MagicNumber:MediaCaptureTool.kt$MediaCaptureTool$192000</ID>- <ID>MagicNumber:MediaCaptureTool.kt$MediaCaptureTool$44100</ID>- <ID>MagicNumber:MediaCaptureTool.kt$MediaCaptureTool$5</ID>- <ID>MagicNumber:MediaCaptureTool.kt$MediaCaptureTool$60</ID>- <ID>MagicNumber:MediaCaptureTool.kt$MediaCaptureTool$64000</ID>- <ID>MagicNumber:NotificationTool.kt$NotificationTool$50</ID>- <ID>MagicNumber:OverlayTool.kt$OverlayTool$1000</ID>- <ID>MagicNumber:OverlayTool.kt$OverlayTool$120</ID>- <ID>MagicNumber:OverlayTool.kt$OverlayTool$16f</ID>- <ID>MagicNumber:OverlayTool.kt$OverlayTool$220</ID>- <ID>MagicNumber:OverlayTool.kt$OverlayTool$24</ID>- <ID>MagicNumber:OverlayTool.kt$OverlayTool$300_000</ID>- <ID>MagicNumber:OverlayTool.kt$OverlayTool$32</ID>- <ID>MagicNumber:PermissionItems.kt$29</ID>- <ID>MagicNumber:PhoneTool.kt$PhoneTool$50</ID>- <ID>MagicNumber:PhoneTool.kt$PhoneTool$60</ID>- <ID>MagicNumber:PhoneTool.kt$PhoneTool$86_400_000L</ID>- <ID>MagicNumber:QuestionTool.kt$QuestionTool$10</ID>- <ID>MagicNumber:QuickAskEngine.kt$QuickAskEngine$1024</ID>- <ID>MagicNumber:QuickAskEngine.kt$QuickAskEngine$1100</ID>- <ID>MagicNumber:QuickAskEngine.kt$QuickAskEngine$85</ID>- <ID>MagicNumber:RootTool.kt$RootTool$1024</ID>- <ID>MagicNumber:RootTool.kt$RootTool$120</ID>- <ID>MagicNumber:RootTool.kt$RootTool$2000</ID>- <ID>MagicNumber:RootTool.kt$RootTool$32</ID>- <ID>MagicNumber:RootTool.kt$RootTool$4096</ID>- <ID>MagicNumber:SettingsRepository.kt$SettingsRepository$30</ID>- <ID>MagicNumber:SettingsRepository.kt$SettingsRepository$40000</ID>- <ID>MagicNumber:SmsTool.kt$SmsTool$0x7FFFFFFF</ID>- <ID>MagicNumber:SmsTool.kt$SmsTool$10</ID>- <ID>MagicNumber:SmsTool.kt$SmsTool$160</ID>- <ID>MagicNumber:SmsTool.kt$SmsTool$3</ID>- <ID>MagicNumber:SmsTool.kt$SmsTool$300</ID>- <ID>MagicNumber:SmsTool.kt$SmsTool$50</ID>- <ID>MagicNumber:SmsTool.kt$SmsTool$60000</ID>- <ID>MagicNumber:SmsTool.kt$SmsTool$86_400_000L</ID>- <ID>MagicNumber:StorageTool.kt$StorageTool$10</ID>- <ID>MagicNumber:StorageTool.kt$StorageTool$100</ID>- <ID>MagicNumber:StorageTool.kt$StorageTool$100L</ID>- <ID>MagicNumber:StorageTool.kt$StorageTool$20</ID>- <ID>MagicNumber:StorageTool.kt$StorageTool.Companion$1024</ID>- <ID>MagicNumber:SttEngine.kt$SttEngine$16000</ID>- <ID>MagicNumber:SystemTool.kt$SystemTool$100</ID>- <ID>MagicNumber:SystemTool.kt$SystemTool$1000</ID>- <ID>MagicNumber:SystemTool.kt$SystemTool$10f</ID>- <ID>MagicNumber:SystemTool.kt$SystemTool$255</ID>- <ID>MagicNumber:TerminalTool.kt$TerminalTool$1024</ID>- <ID>MagicNumber:TerminalTool.kt$TerminalTool$120</ID>- <ID>MagicNumber:TerminalTool.kt$TerminalTool$2000</ID>- <ID>MagicNumber:TerminalTool.kt$TerminalTool$32</ID>- <ID>MagicNumber:TerminalTool.kt$TerminalTool$4096</ID>- <ID>MagicNumber:ToolExecutor.kt$ToolExecutor$1000L</ID>- <ID>MagicNumber:ToolExecutor.kt$ToolExecutor$15</ID>- <ID>MagicNumber:ToolExecutor.kt$ToolExecutor$30</ID>- <ID>MagicNumber:ToolExecutor.kt$ToolExecutor$7</ID>- <ID>MagicNumber:ToolExecutor.kt$ToolExecutor$86400</ID>- <ID>MagicNumber:TtsEngine.kt$TtsEngine$24000</ID>- <ID>MagicNumber:TtsEngine.kt$TtsEngine$3</ID>- <ID>MagicNumber:TtsEngine.kt$TtsEngine$44</ID>- <ID>MagicNumber:WallpaperTool.kt$WallpaperTool$15</ID>- <ID>MagicNumber:WallpaperTool.kt$WallpaperTool$30</ID>- <ID>MagicNumber:WebFetchTool.kt$WebFetchTool$1024</ID>- <ID>MagicNumber:WebSearchTool.kt$WebSearchTool$10</ID>- <ID>MaxLineLength:AlarmTool.kt$AlarmTool$ToolResult.ok("Removed alarm $id from this assistant's list, but no clock app handled the dismiss intent — ask the user to delete it in the clock app.")</ID>- <ID>MaxLineLength:AlarmTool.kt$AlarmTool$fun</ID>- <ID>MaxLineLength:AlarmTool.kt$AlarmTool$return PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_NO_CREATE) != null</ID>- <ID>MaxLineLength:AlarmTool.kt$AlarmTool$return ToolResult.error("Alarm $id lives in the system clock app but no clock app handled the update intent. Edit it in the clock app directly.")</ID>- <ID>MaxLineLength:AlarmTool.kt$AlarmTool$return ToolResult.ok("Set alarm '$label' for %02d:%02d$extra (id=$id). No clock app handled it, so it was scheduled in-app and rings as a notification.".format(hour, minute))</ID>- <ID>MaxLineLength:AlarmTool.kt$AlarmTool$val pi = PendingIntent.getBroadcast(context, alarmRequestCode(a.id), intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)</ID>- <ID>MaxLineLength:AlarmTool.kt$AlarmTool$val pi = PendingIntent.getBroadcast(context, timerRequestCode(t.id), intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)</ID>- <ID>MaxLineLength:AppsTool.kt$AppsTool$ToolResult.ok("Found $matchCount app(s) matching '$search'$truncated ($total total, $userApps user, $systemApps system).\n$listing")</ID>- <ID>MaxLineLength:AppsTool.kt$AppsTool$ToolResult.ok("System dialog opened to uninstall $label. After you tap OK in the dialog, ask the assistant to verify the app is gone.")</ID>- <ID>MaxLineLength:AudioModels.kt$AudioModel.Companion$t == "automatic-speech-recognition" || t == "stt" || t == "speech-to-text" || t == "transcription" -> return ModelCategory.STT</ID>- <ID>MaxLineLength:ChatViewModel.kt$ChatViewModel$AgentMode.MONITOR -> "[System: Switched to Monitor (read-only). You may now ONLY inspect and observe. No changes to the device are permitted.]"</ID>- <ID>MaxLineLength:ChatViewModel.kt$ChatViewModel$content = JsonPrimitive("Please summarize the following conversation history according to the system prompt instructions:\n\n$historyText")</ID>- <ID>MaxLineLength:ChatViewModel.kt$ChatViewModel$content = JsonPrimitive("You are an advanced context compaction agent. Your task is to compress the preceding conversation history into a highly dense, structured continuation summary. You must preserve critical context, decisions, and codebase states while eliminating conversational filler and repetitive tool logs.\n\nGenerate a structured summary containing exactly the following sections:\n1. **Goal**: What is the ultimate objective of this engineering session?\n2. **Instructions & Constraints**: What specific guidelines, patterns, user preferences, or technical limitations have been established?\n3. **Discoveries & Architecture**: What have we learned about the codebase? Detail any symbol mappings, logic structures, or debugging conclusions.\n4. **Accomplished**: What changes have already been completely implemented, verified, or fixed?\n5. **Relevant Files**: Which files are currently being modified or are active in the workspace?\n\nCRITICAL: Do not lose technical specifics, user-stated constraints, or deep investigation states.\n\nContinue if you have next steps, or stop and ask for clarification if you are unsure how to proceed.")</ID>- <ID>MaxLineLength:ChatViewModel.kt$ChatViewModel$return listOf(ChatMessage(role = "user", content = JsonPrimitive("[System Note: Conversation context restored from previous turn]"))) + trimmed</ID>- <ID>MaxLineLength:ChatViewModel.kt$ChatViewModel$val description = "Request to uninstall \"$label\". After you approve, a system dialog will open — you must tap \"OK\" in that dialog to complete the removal. This action is irreversible."</ID>- <ID>MaxLineLength:ContactsTool.kt$ContactsTool$.</ID>- <ID>MaxLineLength:DeviceTool.kt$DeviceTool$"Do Not Disturb control needs notification-policy access. I have opened that settings page — please enable it and ask again."</ID>- <ID>MaxLineLength:FileResolver.kt$FileResolver$fun isArchiveMime(mime: String): Boolean</ID>- <ID>MaxLineLength:FileResolver.kt$FileResolver$if (bytes.size >= 28 && startsWith(bytes.copyOfRange(0,5), byteArrayOf(0x52,0x61,0x72,0x21,0x1A))) return "application/x-rar-compressed"</ID>- <ID>MaxLineLength:FileResolver.kt$FileResolver$if (bytes.size >= 3 && startsWith(bytes.copyOfRange(0,3), byteArrayOf(0x1F.toByte(), 0x8B.toByte(), 0x08.toByte()))) return "application/gzip"</ID>- <ID>MaxLineLength:FileResolver.kt$FileResolver$if (bytes.size >= 4 && bytes[0] == 0x4D.toByte() && bytes[1] == 0x54.toByte() && bytes[2] == 0x68.toByte() && bytes[3] == 0x64.toByte()) return "audio/midi"</ID>- <ID>MaxLineLength:FileResolver.kt$FileResolver$if (bytes.size >= 5 && bytes[0] == 0x25.toByte() && bytes[1] == 0x50.toByte() && bytes[2] == 0x44.toByte() && bytes[3] == 0x46.toByte() && bytes[4] == 0x2D.toByte()) return "application/pdf"</ID>- <ID>MaxLineLength:FileResolver.kt$FileResolver$if (bytes.size >= 8 && bytes[0] == 0x89.toByte() && bytes[1] == 0x50.toByte() && bytes[2] == 0x4E.toByte() && bytes[3] == 0x47.toByte()) return "image/png"</ID>- <ID>MaxLineLength:FileTool.kt$FileTool$ToolResult.ok("${if (append) "Appended" else "Wrote"} ${resolver.formatSize(bytes.size.toLong())} to '$originalPath' (resolved: ${file.canonicalPath}).")</ID>- <ID>MaxLineLength:FileTool.kt$FileTool$ToolResult.ok("Wrote ${resolver.formatSize(bytes.size.toLong())} binary data to '$originalPath' (resolved: ${file.canonicalPath}).")</ID>- <ID>MaxLineLength:FileTool.kt$FileTool$sb.appendLine("Archive: ${file.name} (${resolver.formatSize(file.length())}, ${entries.size} entries, ${resolver.formatSize(totalSize)} uncompressed)")</ID>- <ID>MaxLineLength:StorageTool.kt$StorageTool$append("\nExternal / SD card: ${format(external.used)} used of ${format(external.total)} total, ${format(external.free)} free")</ID>- <ID>MaxLineLength:ToolDefinitions.kt$ToolDefinitions$put("description", "Calendar account name to add the event to (e.g. 'Work', 'Personal'). Defaults to the primary writable calendar.")</ID>- <ID>MaxLineLength:ToolDefinitions.kt$ToolDefinitions$put("description", "Predefined pattern: short (100ms), long (1s), double (two quick buzzes), sos (...---...). Overrides duration_ms.")</ID>- <ID>MaxLineLength:ToolDefinitions.kt$ToolDefinitions$put("description", "Recording quality: 'low' (16kHz, 16kbps), 'medium' (44.1kHz, 64kbps), or 'high' (44.1kHz, 192kbps). Default medium.")</ID>- <ID>MaxLineLength:ToolDefinitions.kt$ToolDefinitions$put("description", "Schedule future delivery: ISO-8601 timestamp like '2026-01-15T14:30:00' or epoch millis. Omit for immediate send.")</ID>- <ID>MaxLineLength:ToolDefinitions.kt$ToolDefinitions$put("description", "Which stream to read: media, ring, alarm, notification, call. If omitted, all streams are reported.")</ID>- <ID>MaxLineLength:ToolDefinitions.kt$ToolDefinitions$putJsonObject("status") { put("type", "string"); put("description", "One of: pending, in_progress, completed, cancelled.") }</ID>- <ID>MaxLineLength:WebFetchTool.kt$WebFetchTool$"Fetched ${trimmed} (${rawSizeKb} KB raw → ${finalOutput.length / 1024} KB ${outputFormat}, HTTP ${response.code}):\n\n$finalOutput"</ID>- <ID>MaxLineLength:WebFetchTool.kt$WebFetchTool$.</ID>- <ID>MaxLineLength:WebSearchTool.kt$WebSearchTool$.</ID>- <ID>MaximumLineLength:AlarmTool.kt$AlarmTool$ </ID>- <ID>MaximumLineLength:AppsTool.kt$AppsTool$ </ID>- <ID>MaximumLineLength:AudioModels.kt$AudioModel.Companion$ </ID>- <ID>MaximumLineLength:ChatViewModel.kt$ChatViewModel$ </ID>- <ID>MaximumLineLength:ContactsTool.kt$ContactsTool$ </ID>- <ID>MaximumLineLength:DeviceTool.kt$DeviceTool$ </ID>- <ID>MaximumLineLength:FileResolver.kt$FileResolver$ </ID>- <ID>MaximumLineLength:FileTool.kt$FileTool$ </ID>- <ID>MaximumLineLength:StorageTool.kt$StorageTool$ </ID>- <ID>MaximumLineLength:ToolDefinitions.kt$ToolDefinitions$ </ID>- <ID>MaximumLineLength:WebFetchTool.kt$WebFetchTool$ </ID>- <ID>MaximumLineLength:WebSearchTool.kt$WebSearchTool$ </ID>- <ID>MultiLineIfElse:AccessibilityTool.kt$AccessibilityTool$ToolResult.error( "Unknown or unsupported global action '$action'. " + "Use back, home, recents, notifications, quick_settings, or lock_screen." )</ID>- <ID>MultiLineIfElse:AccessibilityTool.kt$AccessibilityTool$ToolResult.error("Could not dispatch the swipe gesture.")</ID>- <ID>MultiLineIfElse:AccessibilityTool.kt$AccessibilityTool$ToolResult.error("Could not dispatch the tap gesture.")</ID>- <ID>MultiLineIfElse:AccessibilityTool.kt$AccessibilityTool$ToolResult.error("Found no clickable element matching \"$text\" on screen.")</ID>- <ID>MultiLineIfElse:AccessibilityTool.kt$AccessibilityTool$ToolResult.error("No editable field is focused. Tap a text field first, then input text.")</ID>- <ID>MultiLineIfElse:AccessibilityTool.kt$AccessibilityTool$ToolResult.ok("Performed global action: $action.")</ID>- <ID>MultiLineIfElse:AccessibilityTool.kt$AccessibilityTool$ToolResult.ok("Swiped $direction.")</ID>- <ID>MultiLineIfElse:AccessibilityTool.kt$AccessibilityTool$ToolResult.ok("Swiped from ($x1, $y1) to ($x2, $y2).")</ID>- <ID>MultiLineIfElse:AccessibilityTool.kt$AccessibilityTool$ToolResult.ok("Tapped an element matching \"$text\".")</ID>- <ID>MultiLineIfElse:AccessibilityTool.kt$AccessibilityTool$ToolResult.ok("Tapped at ($x, $y).")</ID>- <ID>MultiLineIfElse:AccessibilityTool.kt$AccessibilityTool$ToolResult.ok("Typed \"$text\" into the focused field.")</ID>- <ID>MultiLineIfElse:AlarmTool.kt$AlarmTool$"once"</ID>- <ID>MultiLineIfElse:AssistiveBallOverlay.kt$AssistiveBallOverlay$@Suppress("DEPRECATION") WindowManager.LayoutParams.TYPE_PHONE</ID>- <ID>MultiLineIfElse:AssistiveBallOverlay.kt$AssistiveBallOverlay$WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY</ID>- <ID>MultiLineIfElse:AssistiveBallService.kt$AssistiveBallService$null</ID>- <ID>MultiLineIfElse:AudioApi.kt$AudioApi$emptyList()</ID>- <ID>MultiLineIfElse:CalendarTool.kt$CalendarTool$ToolResult.ok("Events $rangeDesc ($count):\n$out")</ID>- <ID>MultiLineIfElse:CalendarTool.kt$CalendarTool$now</ID>- <ID>MultiLineIfElse:CalendarTool.kt$CalendarTool$null ?: defaultWritableCalendarId() ?: return ToolResult.error("No writable calendar was found on this device.")</ID>- <ID>MultiLineIfElse:CalendarTool.kt$CalendarTool$parseWhen(end) ?: return ToolResult.error("Could not understand the end time '$end'.")</ID>- <ID>MultiLineIfElse:CalendarTool.kt$CalendarTool$rangeStart + 86400000L</ID>- <ID>MultiLineIfElse:CalendarTool.kt$CalendarTool$startMs + 60 * 60 * 1000</ID>- <ID>MultiLineIfElse:ChatViewModel.kt$ChatViewModel$""</ID>- <ID>MultiLineIfElse:ChatViewModel.kt$ChatViewModel$bitmap.width to bitmap.height</ID>- <ID>MultiLineIfElse:ChatViewModel.kt$ChatViewModel$null</ID>- <ID>MultiLineIfElse:ContactsTool.kt$ContactsTool$null</ID>- <ID>MultiLineIfElse:DeviceAdminTool.kt$DeviceAdminTool$"The current password does NOT meet the policy — the user will be prompted to update it."</ID>- <ID>MultiLineIfElse:DeviceAdminTool.kt$DeviceAdminTool$"The current password meets the policy."</ID>- <ID>MultiLineIfElse:DeviceTool.kt$DeviceTool$NotificationManager.INTERRUPTION_FILTER_ALL</ID>- <ID>MultiLineIfElse:DeviceTool.kt$DeviceTool$NotificationManager.INTERRUPTION_FILTER_PRIORITY</ID>- <ID>MultiLineIfElse:DeviceTool.kt$DeviceTool$VibrationEffect.createOneShot(ms, VibrationEffect.DEFAULT_AMPLITUDE)</ID>- <ID>MultiLineIfElse:DeviceTool.kt$DeviceTool$VibrationEffect.createOneShot(ms, amplitude)</ID>- <ID>MultiLineIfElse:DeviceTool.kt$DeviceTool$listOf("media", "ring", "alarm", "notification", "call")</ID>- <ID>MultiLineIfElse:DeviceTool.kt$DeviceTool$listOf(stream.lowercase().trim())</ID>- <ID>MultiLineIfElse:EditTool.kt$EditTool$content.replace(oldString, newString)</ID>- <ID>MultiLineIfElse:EditTool.kt$EditTool$content.replaceFirst(oldString, newString)</ID>- <ID>MultiLineIfElse:EditTool.kt$EditTool$content.split(oldString).size - 1</ID>- <ID>MultiLineIfElse:FileResolver.kt$FileResolver$ResolveResult.Ok(File(canonical))</ID>- <ID>MultiLineIfElse:FileResolver.kt$FileResolver$ResolveResult.PermissionNeeded( ToolResult.permissionNeeded( android.Manifest.permission.READ_EXTERNAL_STORAGE, READ_STORAGE_GUIDE ) )</ID>- <ID>MultiLineIfElse:FileResolver.kt$FileResolver$ResolveResult.PermissionNeeded( ToolResult.permissionNeeded( android.Manifest.permission.WRITE_EXTERNAL_STORAGE, WRITE_STORAGE_GUIDE ) )</ID>- <ID>MultiLineIfElse:FileResolver.kt$FileResolver$ResolveResult.PermissionNeeded( ToolResult.permissionNeeded(ToolResult.ALL_FILES_ACCESS, ALL_FILES_ACCESS_GUIDE) )</ID>- <ID>MultiLineIfElse:FileResolver.kt$FileResolver$return "image/webp"</ID>- <ID>MultiLineIfElse:FileResolver.kt$FileResolver$return ToolResult.permissionNeeded(ToolResult.ALL_FILES_ACCESS, ALL_FILES_ACCESS_GUIDE)</ID>- <ID>MultiLineIfElse:FileTool.kt$FileTool$" Did you mean one of: ${matching.joinToString(", ")}?"</ID>- <ID>MultiLineIfElse:FileTool.kt$FileTool$""</ID>- <ID>MultiLineIfElse:FileTool.kt$FileTool$ToolResult.ok( "Office document detected (${file.name}). It is a ZIP archive containing:\n" + list.message + "\nUse read_file on a specific entry, e.g. '${originalPath}/word/document.xml' for .docx." )</ID>- <ID>MultiLineIfElse:FileTool.kt$FileTool$line</ID>- <ID>MultiLineIfElse:FileTool.kt$FileTool$line.take(MAX_LINE_LENGTH) + "…(line truncated)"</ID>- <ID>MultiLineIfElse:FileTool.kt$FileTool$list</ID>- <ID>MultiLineIfElse:FileTool.kt$FileTool$return ToolResult.error("File '${file.name}' could not be decoded as an image.")</ID>- <ID>MultiLineIfElse:FileTool.kt$FileTool$return ToolResult.error("File '${file.name}' is not a recognized image format.")</ID>- <ID>MultiLineIfElse:GlobTool.kt$GlobTool$walk(root, 0)</ID>- <ID>MultiLineIfElse:GrepTool.kt$GrepTool$""</ID>- <ID>MultiLineIfElse:GrepTool.kt$GrepTool$walk(root, 0)</ID>- <ID>MultiLineIfElse:GotchaAccessibilityService.kt$GotchaAccessibilityService$out.add(text)</ID>- <ID>MultiLineIfElse:MainActivity.kt$MainActivity$"Permission denied."</ID>- <ID>MultiLineIfElse:MainActivity.kt$MainActivity$"Permission granted."</ID>- <ID>MultiLineIfElse:MainActivity.kt$MainActivity$Intent( AndroidSettings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, Uri.parse("package:$packageName") )</ID>- <ID>MultiLineIfElse:MainActivity.kt$MainActivity$Intent(AndroidSettings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName"))</ID>- <ID>MultiLineIfElse:MediaCaptureTool.kt$MediaCaptureTool$File(FileResolver.WORKING_DIR_BASE, outputPath).absolutePath</ID>- <ID>MultiLineIfElse:MediaCaptureTool.kt$MediaCaptureTool$outputPath</ID>- <ID>MultiLineIfElse:MessageBubble.kt$Modifier.combinedClickable( onClick = { expanded.value = !expanded.value }, onLongClick = { showMenu = true } )</ID>- <ID>MultiLineIfElse:MessageBubble.kt$Modifier.combinedClickable( onClick = { }, onLongClick = { showMenu = true } )</ID>- <ID>MultiLineIfElse:OverlayTool.kt$OverlayTool$"Showing a persistent overlay: \"$text\". Call hide_overlay to remove it."</ID>- <ID>MultiLineIfElse:OverlayTool.kt$OverlayTool$"Showing an overlay for ${duration / 1000}s: \"$text\"."</ID>- <ID>MultiLineIfElse:PermissionItems.kt$Environment.isExternalStorageManager()</ID>- <ID>MultiLineIfElse:PermissionItems.kt$android.Manifest.permission.READ_EXTERNAL_STORAGE</ID>- <ID>MultiLineIfElse:PermissionItems.kt$android.Manifest.permission.READ_MEDIA_IMAGES</ID>- <ID>MultiLineIfElse:PermissionItems.kt$checkPerm(c, android.Manifest.permission.READ_EXTERNAL_STORAGE)</ID>- <ID>MultiLineIfElse:PermissionItems.kt$checkPerm(c, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)</ID>- <ID>MultiLineIfElse:PermissionItems.kt$false</ID>- <ID>MultiLineIfElse:PermissionItems.kt$true</ID>- <ID>MultiLineIfElse:PermissionsSection.kt$Intent(AndroidSettings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName"))</ID>- <ID>MultiLineIfElse:PermissionsSection.kt$Intent(AndroidSettings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, Uri.parse("package:$packageName"))</ID>- <ID>MultiLineIfElse:PhoneTool.kt$PhoneTool$ToolResult.ok("Last $count call(s):\n$entries")</ID>- <ID>MultiLineIfElse:PhoneTool.kt$PhoneTool$ToolResult.ok("The call log is empty.")</ID>- <ID>MultiLineIfElse:PhoneTool.kt$PhoneTool$null</ID>- <ID>MultiLineIfElse:QuickAskEngine.kt$QuickAskEngine$""</ID>- <ID>MultiLineIfElse:QuickAskEngine.kt$QuickAskEngine$SYSTEM_PROMPT</ID>- <ID>MultiLineIfElse:QuickAskEngine.kt$QuickAskEngine$bitmap.width to bitmap.height</ID>- <ID>MultiLineIfElse:SessionsScreen.kt$"Turn off assistive ball"</ID>- <ID>MultiLineIfElse:SessionsScreen.kt$"Turn on assistive ball"</ID>- <ID>MultiLineIfElse:SessionsScreen.kt$MaterialTheme.colorScheme.onSurfaceVariant</ID>- <ID>MultiLineIfElse:SessionsScreen.kt$MaterialTheme.colorScheme.primary</ID>- <ID>MultiLineIfElse:SettingsScreen.kt$PasswordVisualTransformation()</ID>- <ID>MultiLineIfElse:SettingsScreen.kt$VisualTransformation.None</ID>- <ID>MultiLineIfElse:SmsTool.kt$SmsTool$null</ID>- <ID>MultiLineIfElse:SmsTool.kt$SmsTool$return null</ID>- <ID>MultiLineIfElse:TtsEngine.kt$TtsEngine$bytes</ID>- <ID>MultiLineIfElse:VpnTool.kt$VpnTool$"The network firewall is OFF — traffic flows normally."</ID>- <ID>MultiLineIfElse:VpnTool.kt$VpnTool$"The network firewall is ON — all traffic is blocked."</ID>- <ID>MultiLineIfElse:WebFetchTool.kt$WebFetchTool$"text/html"</ID>- <ID>MultiLineIfElse:WebFetchTool.kt$WebFetchTool$output</ID>- <ID>NestedBlockDepth:AlarmTool.kt$AlarmTool$fun listAlarms(): ToolResult</ID>- <ID>NestedBlockDepth:CalendarTool.kt$CalendarTool$fun editEvent( eventId: Long, title: String? = null, start: String? = null, end: String? = null, location: String? = null, description: String? = null, allDay: Boolean? = null, reminderMinutes: Int? = null ): ToolResult</ID>- <ID>NestedBlockDepth:CalendarTool.kt$CalendarTool$fun listEvents( daysAhead: Int? = null, fromDate: String? = null, toDate: String? = null, search: String? = null ): ToolResult</ID>- <ID>NestedBlockDepth:ContactsTool.kt$ContactsTool$fun findContact(name: String? = null, number: String? = null): ToolResult</ID>- <ID>NestedBlockDepth:ContactsTool.kt$ContactsTool$private fun resolveEmail(number: String): List<String></ID>- <ID>NestedBlockDepth:ContactsTool.kt$ContactsTool$private fun resolveOrganization(number: String): String?</ID>- <ID>NestedBlockDepth:FileTool.kt$FileTool$private fun listArchiveContents(file: File): ToolResult</ID>- <ID>NestedBlockDepth:GlobTool.kt$GlobTool$private fun globToRegex(glob: String): Regex</ID>- <ID>NestedBlockDepth:GrepTool.kt$GrepTool$fun grep(path: String, pattern: String, include: String?): ToolResult</ID>- <ID>NestedBlockDepth:MediaCaptureTool.kt$MediaCaptureTool$fun stopAudioRecording(): ToolResult</ID>- <ID>NestedBlockDepth:PhoneTool.kt$PhoneTool$fun callNumber(number: String, speakerphone: Boolean? = null, simSlot: String? = null): ToolResult</ID>- <ID>NestedBlockDepth:PhoneTool.kt$PhoneTool$fun readCallLog( limit: Int, callTypeFilter: String? = null, contact: String? = null, fromDate: String? = null, toDate: String? = null ): ToolResult</ID>- <ID>NestedBlockDepth:SmsTool.kt$SmsTool$fun readRecentSms( limit: Int, fromAddress: String? = null, fromDate: String? = null, toDate: String? = null, unreadOnly: Boolean? = null, search: String? = null, includeSent: Boolean? = null ): ToolResult</ID>- <ID>NestedBlockDepth:SmsTool.kt$SmsTool$fun sendSms( number: String, message: String, deliveryReport: Boolean? = null, sendAt: String? = null ): ToolResult</ID>- <ID>NestedBlockDepth:SmsTool.kt$SmsTool$private fun parseSendAt(sendAt: String): Long?</ID>- <ID>NestedBlockDepth:TerminalTool.kt$TerminalTool$private fun drain( read: (CharArray, Int, Int) -> Int, into: StringBuilder )</ID>- <ID>NestedBlockDepth:WebSearchTool.kt$WebSearchTool$fun search(query: String, numResults: Int): ToolResult</ID>- <ID>NoMultipleSpaces:RootTool.kt$RootTool$ </ID>- <ID>NoTrailingSpaces:AssistiveBallService.kt$AssistiveBallService$ </ID>- <ID>NoTrailingSpaces:ChatHistoryRepository.kt$ChatHistoryRepository$ </ID>- <ID>NoTrailingSpaces:ChatViewModel.kt$ChatViewModel$ </ID>- <ID>NoTrailingSpaces:MainActivity.kt$MainActivity$ </ID>- <ID>NoUnusedImports:AlarmTool.kt$com.gotcha.tools.AlarmTool.kt</ID>- <ID>NoUnusedImports:AppsTool.kt$com.gotcha.tools.AppsTool.kt</ID>- <ID>NoUnusedImports:ChatHistoryRepository.kt$com.gotcha.data.ChatHistoryRepository.kt</ID>- <ID>NoUnusedImports:ChatScreen.kt$com.gotcha.ui.ChatScreen.kt</ID>- <ID>NoUnusedImports:ChatViewModel.kt$com.gotcha.agent.ChatViewModel.kt</ID>- <ID>NoUnusedImports:EditTool.kt$com.gotcha.tools.EditTool.kt</ID>- <ID>NoUnusedImports:FileTool.kt$com.gotcha.tools.FileTool.kt</ID>- <ID>NoUnusedImports:MainActivity.kt$com.gotcha.MainActivity.kt</ID>- <ID>NoUnusedImports:MessageBubble.kt$com.gotcha.ui.MessageBubble.kt</ID>- <ID>NoUnusedImports:Models.kt$com.gotcha.llm.Models.kt</ID>- <ID>NoUnusedImports:PermissionItems.kt$com.gotcha.ui.PermissionItems.kt</ID>- <ID>NoUnusedImports:SmsTool.kt$com.gotcha.tools.SmsTool.kt</ID>- <ID>NoUnusedImports:TtsEngine.kt$com.gotcha.audio.TtsEngine.kt</ID>- <ID>NoWildcardImports:SessionsScreen.kt$import androidx.compose.foundation.layout.*</ID>- <ID>NoWildcardImports:SessionsScreen.kt$import androidx.compose.material3.*</ID>- <ID>NoWildcardImports:SessionsScreen.kt$import androidx.compose.runtime.*</ID>- <ID>ParameterListWrapping:AlarmTool.kt$AlarmTool.AlarmRecord$( val id: Long, val hour: Int, val minute: Int, val days: List<Int>, val label: String?, val vibrate: Boolean, val system: Boolean = false, val triggerAt: Long? = null )</ID>- <ID>ParameterListWrapping:AlarmTool.kt$AlarmTool.TimerRecord$( val id: Long, val seconds: Int, val label: String?, val triggerAt: Long = System.currentTimeMillis() + seconds * 1000L )</ID>- <ID>ParameterListWrapping:AudioApi.kt$AudioApi$( boundary: String, file: File, fieldName: String, contentType: String, extraFields: Map<String, String> )</ID>- <ID>ParameterListWrapping:CalendarTool.kt$CalendarTool$(_: Exception)</ID>- <ID>ParameterListWrapping:FileResolver.kt$FileResolver$(mime: String)</ID>- <ID>ParameterListWrapping:PhoneTool.kt$PhoneTool$(_: Exception)</ID>- <ID>ParameterListWrapping:SettingsScreen.kt$(Settings)</ID>- <ID>ParameterListWrapping:SmsTool.kt$SmsTool$(_: Exception)</ID>- <ID>PropertyWrapping:AlarmTool.kt$AlarmTool$val daysArr = buildJsonArray { a.days.forEach { d -> add(kotlinx.serialization.json.JsonPrimitive(d)) } }</ID>- <ID>ReturnCount:AlarmTool.kt$AlarmTool$fun editAlarm(id: Long, hour: Int? = null, minute: Int? = null, message: String? = null, days: List<String>? = null, vibrate: Boolean? = null): ToolResult</ID>- <ID>ReturnCount:AlarmTool.kt$AlarmTool$fun setAlarm(hour: Int, minute: Int, message: String? = null, days: List<String>? = null, vibrate: Boolean? = null): ToolResult</ID>- <ID>ReturnCount:CalendarTool.kt$CalendarTool$fun createEvent( title: String, start: String, end: String? = null, location: String? = null, description: String? = null, allDay: Boolean? = null, reminderMinutes: Int? = null, calendarName: String? = null ): ToolResult</ID>- <ID>ReturnCount:CalendarTool.kt$CalendarTool$fun editEvent( eventId: Long, title: String? = null, start: String? = null, end: String? = null, location: String? = null, description: String? = null, allDay: Boolean? = null, reminderMinutes: Int? = null ): ToolResult</ID>- <ID>ReturnCount:ContactsTool.kt$ContactsTool$fun addContact( name: String, number: String, phoneType: String? = null, email: String? = null, organization: String? = null ): ToolResult</ID>- <ID>ReturnCount:ContactsTool.kt$ContactsTool$fun findContact(name: String? = null, number: String? = null): ToolResult</ID>- <ID>ReturnCount:EditTool.kt$EditTool$fun edit(path: String, oldString: String, newString: String, replaceAll: Boolean): ToolResult</ID>- <ID>ReturnCount:FileResolver.kt$FileResolver$fun detectMime(bytes: ByteArray): String?</ID>- <ID>ReturnCount:FileTool.kt$FileTool$private fun listResolved( file: File, originalPath: String, sortBy: String?, include: String?, exclude: String?, recursive: Boolean, maxDepth: Int? ): ToolResult</ID>- <ID>ReturnCount:FileTool.kt$FileTool$private fun readResolved( file: File, originalPath: String, offset: Int?, limit: Int?, encoding: String? ): ToolResult</ID>- <ID>ReturnCount:FileTool.kt$FileTool$private fun readUnknownFile(file: File, encoding: String?): ToolResult</ID>- <ID>ReturnCount:FileTool.kt$FileTool$private fun readZipEntry(zf: ZipFile, archiveFile: File, archivePath: String, entryPath: String): ToolResult</ID>- <ID>ReturnCount:GlobTool.kt$GlobTool$fun glob(path: String, pattern: String): ToolResult</ID>- <ID>ReturnCount:GrepTool.kt$GrepTool$fun grep(path: String, pattern: String, include: String?): ToolResult</ID>- <ID>ReturnCount:GrepTool.kt$GrepTool$fun walk(dir: File, depth: Int)</ID>- <ID>ReturnCount:LLMCache.kt$LLMCache$@Synchronized fun get(key: String): ChatResponse?</ID>- <ID>ReturnCount:RootTool.kt$RootTool$fun writeSecureSetting(namespace: String, key: String, value: String): ToolResult</ID>- <ID>ReturnCount:SmsTool.kt$SmsTool$fun sendSms( number: String, message: String, deliveryReport: Boolean? = null, sendAt: String? = null ): ToolResult</ID>- <ID>ReturnCount:ToolExecutor.kt$ToolExecutor$private suspend fun dispatch(name: String, args: JsonObject): ToolResult</ID>- <ID>ReturnCount:WebFetchTool.kt$WebFetchTool$fun fetch(url: String, format: String?): ToolResult</ID>- <ID>ReturnCount:WebSearchTool.kt$WebSearchTool$fun search(query: String, numResults: Int): ToolResult</ID>- <ID>SpacingAroundComma:FileResolver.kt$FileResolver$,</ID>- <ID>SpacingBetweenDeclarationsWithAnnotations:AppsTool.kt$AppsTool$@Suppress("DEPRECATION") val mobile = nsm.querySummaryForDevice(ConnectivityManager.TYPE_MOBILE, null, start, end)</ID>- <ID>SpacingBetweenDeclarationsWithAnnotations:AppsTool.kt$AppsTool$@Suppress("DEPRECATION") val wifi = nsm.querySummaryForDevice(ConnectivityManager.TYPE_WIFI, null, start, end)</ID>- <ID>SpacingBetweenDeclarationsWithAnnotations:AssistiveBallService.kt$AssistiveBallService$@Volatile private var listening = false</ID>- <ID>SpacingBetweenDeclarationsWithAnnotations:ChatViewModel.kt$ChatViewModel$/** True when the most recent user message was sent via voice (STT). */ @Volatile private var lastInputWasVoice = false</ID>- <ID>SpacingBetweenDeclarationsWithComments:AssistiveBallService.kt$AssistiveBallService.Companion$/** Live running state of the ball, so UI toggles can track "Hide ball" too. */</ID>- <ID>SpacingBetweenDeclarationsWithComments:ChatViewModel.kt$ChatViewModel$/** True when the most recent user message was sent via voice (STT). */</ID>- <ID>SpacingBetweenDeclarationsWithComments:SttEngine.kt$SttEngine$// Android STT state</ID>- <ID>SpacingBetweenDeclarationsWithComments:ToolExecutor.kt$ToolExecutor$// Tier 3 tools</ID>- <ID>SpacingBetweenDeclarationsWithComments:ToolExecutor.kt$ToolExecutor$// Tier 4 tools</ID>- <ID>StringTemplate:DeviceTool.kt$DeviceTool$${pct}</ID>- <ID>StringTemplate:DeviceTool.kt$DeviceTool$${percent}</ID>- <ID>StringTemplate:DeviceTool.kt$DeviceTool$${previousPct}</ID>- <ID>StringTemplate:FileTool.kt$FileTool$${originalPath}</ID>- <ID>StringTemplate:StorageTool.kt$StorageTool$${pct}</ID>- <ID>StringTemplate:WebFetchTool.kt$WebFetchTool$${outputFormat}</ID>- <ID>StringTemplate:WebFetchTool.kt$WebFetchTool$${rawSizeKb}</ID>- <ID>StringTemplate:WebFetchTool.kt$WebFetchTool$${trimmed}</ID>- <ID>SwallowedException:ChatHistoryRepository.kt$ChatHistoryRepository$e: Exception</ID>- <ID>SwallowedException:ChatViewModel.kt$ChatViewModel$e: CancellationException</ID>- <ID>SwallowedException:ChatViewModel.kt$ChatViewModel$e: Exception</ID>- <ID>SwallowedException:DeviceTool.kt$DeviceTool$e: SecurityException</ID>- <ID>SwallowedException:FileTool.kt$FileTool$e: java.nio.charset.UnsupportedCharsetException</ID>- <ID>SwallowedException:LLMCache.kt$LLMCache$e: Exception</ID>- <ID>SwallowedException:NotificationTool.kt$NotificationTool$e: SecurityException</ID>- <ID>SwallowedException:PhoneTool.kt$PhoneTool$e: SecurityException</ID>- <ID>SwallowedException:SmsTool.kt$SmsTool$e: SecurityException</ID>- <ID>SwallowedException:SystemTool.kt$SystemTool$e: SecurityException</ID>- <ID>SwallowedException:WebFetchTool.kt$WebFetchTool$e: java.net.SocketTimeoutException</ID>- <ID>SwallowedException:WebSearchTool.kt$WebSearchTool$e: java.net.SocketTimeoutException</ID>- <ID>TooManyFunctions:AlarmTool.kt$AlarmTool</ID>- <ID>TooManyFunctions:AssistiveBallOverlay.kt$AssistiveBallOverlay</ID>- <ID>TooManyFunctions:ChatViewModel.kt$ChatViewModel : AndroidViewModel</ID>- <ID>UnusedParameter:PermissionItems.kt$context: Context</ID>- <ID>UnusedParameter:WebSearchTool.kt$WebSearchTool$row: org.jsoup.nodes.Element</ID>- <ID>UnusedPrivateProperty:LLMClient.kt$LLMClient.Companion$private const val DEFAULT_MODEL = "gpt-4o"</ID>- <ID>UnusedPrivateProperty:MainActivity.kt$MainActivity$/** Used by the Settings screen to grant individual runtime permissions. */ private val permissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> Toast.makeText( this, if (granted) "Permission granted." else "Permission denied.", Toast.LENGTH_SHORT ).show() }</ID>- <ID>UnusedPrivateProperty:WebSearchTool.kt$WebSearchTool$val urlEl = row.selectFirst(".result__url")</ID>- <ID>UseCheckOrError:QuickAskEngine.kt$QuickAskEngine$throw IllegalStateException("Not configured")</ID>- <ID>VariableNaming:AppsTool.kt$AppsTool$private val TAG = "Gotcha"</ID>- <ID>VariableNaming:ChatViewModel.kt$ChatViewModel$private val TAG = "Gotcha"</ID>- <ID>VariableNaming:FileResolver.kt$FileResolver$val IMAGE_DATA_PREFIX = "IMAGE_DATA:"</ID>- <ID>VariableNaming:MediaCaptureTool.kt$MediaCaptureTool$private val TAG = "Gotcha"</ID>- <ID>VariableNaming:ToolExecutor.kt$ToolExecutor$private val TAG = "Gotcha"</ID>- <ID>WildcardImport:SessionsScreen.kt$import androidx.compose.foundation.layout.*</ID>- <ID>WildcardImport:SessionsScreen.kt$import androidx.compose.material3.*</ID>- <ID>WildcardImport:SessionsScreen.kt$import androidx.compose.runtime.*</ID>- <ID>Wrapping:AlarmTool.kt$AlarmTool$(</ID>- <ID>Wrapping:AppsTool.kt$AppsTool$;</ID>- <ID>Wrapping:AssistiveBallOverlay.kt$AssistiveBallOverlay$(</ID>- <ID>Wrapping:AudioApi.kt$AudioApi$(</ID>- <ID>Wrapping:ChatScreen.kt$(</ID>- <ID>Wrapping:ChatViewModel.kt$ChatViewModel$it.copy(activity = null, pendingConfirmation = PendingConfirmation(listOf("delete_$kind"), description))</ID>- <ID>Wrapping:ChatViewModel.kt$ChatViewModel$it.copy(activity = null, pendingConfirmation = PendingConfirmation(listOf("uninstall_app"), description))</ID>- <ID>Wrapping:ContactsTool.kt$ContactsTool$(</ID>- <ID>Wrapping:EditTool.kt$EditTool$(</ID>- <ID>Wrapping:FileResolver.kt$FileResolver$(</ID>- <ID>Wrapping:FileTool.kt$FileTool$(</ID>- <ID>Wrapping:FileTool.kt$FileTool$;</ID>- <ID>Wrapping:GlobTool.kt$GlobTool$(</ID>- <ID>Wrapping:GlobTool.kt$GlobTool$;</ID>- <ID>Wrapping:GrepTool.kt$GrepTool$(</ID>- <ID>Wrapping:GrepTool.kt$GrepTool$;</ID>- <ID>Wrapping:GotchaVpnService.kt$GotchaVpnService$;</ID>- <ID>Wrapping:MainActivity.kt$MainActivity$(</ID>- <ID>Wrapping:MediaCaptureTool.kt$MediaCaptureTool$;</ID>- <ID>Wrapping:Models.kt$(</ID>- <ID>Wrapping:PermissionItems.kt$(</ID>- <ID>Wrapping:PermissionItems.kt$( "Storage Read", "Read files from shared storage", if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) android.Manifest.permission.READ_MEDIA_IMAGES else android.Manifest.permission.READ_EXTERNAL_STORAGE, null, { c -> val perm = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) android.Manifest.permission.READ_MEDIA_IMAGES else android.Manifest.permission.READ_EXTERNAL_STORAGE checkPerm(c, perm) } )</ID>- <ID>Wrapping:PermissionItems.kt$("Calendar", listOf( PermissionItem( "Calendar", "Read and create calendar events", android.Manifest.permission.READ_CALENDAR, null, { c -> checkPerm(c, android.Manifest.permission.READ_CALENDAR) && checkPerm(c, android.Manifest.permission.WRITE_CALENDAR) }, extraPermissions = listOf(android.Manifest.permission.WRITE_CALENDAR) ) ))</ID>- <ID>Wrapping:PermissionItems.kt$("Communications", listOf( PermissionItem( "Phone", "Place calls directly", android.Manifest.permission.CALL_PHONE, null, { c -> checkPerm(c, android.Manifest.permission.CALL_PHONE) } ), PermissionItem( "SMS", "Send text messages", android.Manifest.permission.SEND_SMS, null, { c -> checkPerm(c, android.Manifest.permission.SEND_SMS) } ), PermissionItem( "Read SMS", "Read inbox messages", android.Manifest.permission.READ_SMS, null, { c -> checkPerm(c, android.Manifest.permission.READ_SMS) } ), PermissionItem( "Call Log", "Read recent call history", android.Manifest.permission.READ_CALL_LOG, null, { c -> checkPerm(c, android.Manifest.permission.READ_CALL_LOG) } ) ))</ID>- <ID>Wrapping:PermissionItems.kt$("Contacts", listOf( PermissionItem( "Contacts", "Read and create contacts", android.Manifest.permission.READ_CONTACTS, null, { c -> checkPerm(c, android.Manifest.permission.READ_CONTACTS) && checkPerm(c, android.Manifest.permission.WRITE_CONTACTS) }, extraPermissions = listOf(android.Manifest.permission.WRITE_CONTACTS) ) ))</ID>- <ID>Wrapping:PermissionItems.kt$("Device Control", listOf( PermissionItem( "Write Settings", "Modify system settings (brightness)", null, "special:write_settings", { c -> Settings.System.canWrite(c) } ), PermissionItem( "Do Not Disturb", "Silence/vibrate mode and DND", null, "special:dnd_access", { c -> val nm = c.getSystemService(Context.NOTIFICATION_SERVICE) as? android.app.NotificationManager nm?.isNotificationPolicyAccessGranted ?: false } ), PermissionItem( "Usage Access", "Read app usage and data stats", null, "special:usage_access", { c -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { val appOps = c.getSystemService(Context.APP_OPS_SERVICE) as? AppOpsManager appOps?.checkOpNoThrow( AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), c.packageName ) == AppOpsManager.MODE_ALLOWED } else true } ), PermissionItem( "Device Admin", "Lock screen, enforce password policy", null, "special:device_admin", { c -> val dpm = c.getSystemService(Context.DEVICE_POLICY_SERVICE) as? DevicePolicyManager dpm?.isAdminActive(ComponentName(c, GotchaDeviceAdminReceiver::class.java)) ?: false } ) ))</ID>- <ID>Wrapping:PermissionItems.kt$("Location", listOf( PermissionItem( "Location", "Get device location", android.Manifest.permission.ACCESS_FINE_LOCATION, null, { c -> checkPerm(c, android.Manifest.permission.ACCESS_FINE_LOCATION) } ) ))</ID>- <ID>Wrapping:PermissionItems.kt$("Media & Storage", listOf( PermissionItem( "Camera", "Take photos", android.Manifest.permission.CAMERA, null, { c -> checkPerm(c, android.Manifest.permission.CAMERA) } ), PermissionItem( "Microphone", "Record audio", android.Manifest.permission.RECORD_AUDIO, null, { c -> checkPerm(c, android.Manifest.permission.RECORD_AUDIO) } ), PermissionItem( "Storage Read", "Read files from shared storage", if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) android.Manifest.permission.READ_MEDIA_IMAGES else android.Manifest.permission.READ_EXTERNAL_STORAGE, null, { c -> val perm = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) android.Manifest.permission.READ_MEDIA_IMAGES else android.Manifest.permission.READ_EXTERNAL_STORAGE checkPerm(c, perm) } ), PermissionItem( "Storage Write", "Write files to shared storage", android.Manifest.permission.WRITE_EXTERNAL_STORAGE, null, { c -> if (Build.VERSION.SDK_INT <= 29) checkPerm(c, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) else true // API 30+ uses MANAGE_EXTERNAL_STORAGE } ), PermissionItem( "All Files Access", "Full access to all files on device", null, "special:all_files_access", { c -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) Environment.isExternalStorageManager() else checkPerm(c, android.Manifest.permission.READ_EXTERNAL_STORAGE) } ) ))</ID>- <ID>Wrapping:PermissionItems.kt$("System Access", listOf( PermissionItem( "Accessibility", "Read screen, tap, swipe, type", null, "special:accessibility_access", { c -> val expected = "${c.packageName}/com.gotcha.service.GotchaAccessibilityService" val enabled = Settings.Secure.getString( c.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES ) ?: "" enabled.contains(expected, ignoreCase = true) } ), PermissionItem( "Notification Listener", "Read and dismiss notifications, media control", null, "special:notification_listener_access", { c -> val expected = c.packageName val enabled = Settings.Secure.getString( c.contentResolver, "enabled_notification_listeners" ) ?: "" enabled.contains(expected, ignoreCase = true) } ), PermissionItem( "Display Over Apps", "Show floating overlays", null, "special:overlay_access", { c -> Settings.canDrawOverlays(c) } ), PermissionItem( "VPN", "Block all network traffic (firewall kill-switch)", null, "special:vpn_consent", { c -> try { val cm = c.getSystemService(Context.CONNECTIVITY_SERVICE) as? android.net.ConnectivityManager cm?.let { mgr -> val network = mgr.activeNetwork if (network != null) { mgr.getNetworkCapabilities(network) ?.hasTransport(android.net.NetworkCapabilities.TRANSPORT_VPN) ?: false } else false } ?: false } catch (_: SecurityException) { false } } ) ))</ID>- <ID>Wrapping:SettingsScreen.kt$Pair(emptyList(), emptyList())</ID>- <ID>Wrapping:SmsTool.kt$SmsTool$(</ID>- <ID>Wrapping:SttEngine.kt$SttEngine$;</ID>- <ID>Wrapping:SystemTool.kt$SystemTool$(</ID>- <ID>Wrapping:TerminalTool.kt$TerminalTool$;</ID>- <ID>Wrapping:ToolDefinitions.kt$ToolDefinitions$;</ID>- <ID>Wrapping:ToolDefinitions.kt$ToolDefinitions$put("type", "string"); put("description", "One of: pending, in_progress, completed, cancelled.")</ID>- <ID>Wrapping:TtsEngine.kt$TtsEngine$(</ID>- <ID>Wrapping:WebFetchTool.kt$WebFetchTool$;</ID>- </CurrentIssues>-</SmellBaseline>diff --git a/app/lint-baseline.xml b/app/lint-baseline.xmldeleted file mode 100644index 28496c3..0000000--- a/app/lint-baseline.xml+++ /dev/null@@ -1,1061 +0,0 @@-<?xml version="1.0" encoding="UTF-8"?>-<issues format="6" by="lint 8.13.2" type="baseline" client="gradle" dependencies="false" name="AGP (8.13.2)" variant="all" version="8.13.2">-- <issue- id="MissingPermission"- message="Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with `checkPermission`) or explicitly handle a potential `SecurityException`"- errorLine1=" lm.requestSingleUpdate(provider, listener, Looper.getMainLooper())"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/tools/LocationTool.kt"- line="110"- column="9"/>- </issue>-- <issue- id="MissingPermission"- message="Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with `checkPermission`) or explicitly handle a potential `SecurityException`"- errorLine1=" context.getSystemService(SubscriptionManager::class.java)?.activeSubscriptionInfoList"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/tools/PhoneTool.kt"- line="95"- column="17"/>- </issue>-- <issue- id="MissingPermission"- message="Missing permissions required by SubscriptionManager.getActiveSubscriptionInfoList: android.permission.READ_PHONE_STATE"- errorLine1=" context.getSystemService(SubscriptionManager::class.java)?.activeSubscriptionInfoList"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/tools/PhoneTool.kt"- line="95"- column="17"/>- </issue>-- <issue- id="MissingPermission"- message="Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with `checkPermission`) or explicitly handle a potential `SecurityException`"- errorLine1=" SubscriptionManager.from(context).activeSubscriptionInfoList"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/tools/PhoneTool.kt"- line="98"- column="17"/>- </issue>-- <issue- id="MissingPermission"- message="Missing permissions required by SubscriptionManager.getActiveSubscriptionInfoList: android.permission.READ_PHONE_STATE"- errorLine1=" SubscriptionManager.from(context).activeSubscriptionInfoList"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/tools/PhoneTool.kt"- line="98"- column="17"/>- </issue>-- <issue- id="InlinedApi"- message="Field requires API level 30 (current min is 29): `android.content.pm.ServiceInfo#FOREGROUND_SERVICE_TYPE_MICROPHONE`"- errorLine1=" ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/service/AssistiveBallService.kt"- line="271"- column="17"/>- </issue>-- <issue- id="NewApi"- message="This Kotlin extension function will be hidden by `java.util.SequencedCollection` starting in API 35: `removeLast`. When this source code is recompiled against API level 35, it will crash on older levels. You can avoid this by using `removeAt(llmHistory.lastIndex)` instead."- errorLine1=" llmHistory.removeLast()"- errorLine2=" ~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/agent/ChatViewModel.kt"- line="437"- column="24"/>- </issue>-- <issue- id="NewApi"- message="Call requires API level 33 (current min is 26): `java.io.InputStream#readNBytes`"- errorLine1=" val sample = try { file.inputStream().use { it.readNBytes(512) } } catch (_: Exception) { ByteArray(0) }"- errorLine2=" ~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/tools/FileTool.kt"- line="189"- column="56"/>- </issue>-- <issue- id="OldTargetApi"- message="Not targeting the latest versions of Android; compatibility modes apply. Consider testing and updating this version. Consult the `android.os.Build.VERSION_CODES` javadoc for details."- errorLine1=" targetSdk = 34"- errorLine2=" ~~~~~~~~~~~~~~">- <location- file="build.gradle.kts"- line="23"- column="9"/>- </issue>-- <issue- id="UnusedAttribute"- message="Attribute `canTakeScreenshot` is only used in API level 30 and higher (current min is 26)"- errorLine1=" android:canTakeScreenshot="true""- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/res/xml/accessibility_service_config.xml"- line="8"- column="5"/>- </issue>-- <issue- id="QueryPermissionsNeeded"- message="As of Android 11, this method no longer returns information about all apps; see https://g.co/dev/packagevisibility for details"- errorLine1=" pm.getInstalledApplications(0).firstOrNull { app ->"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/tools/AppsTool.kt"- line="95"- column="16"/>- </issue>-- <issue- id="QueryPermissionsNeeded"- message="As of Android 11, this method no longer returns information about all apps; see https://g.co/dev/packagevisibility for details"- errorLine1=" val match = pm.getInstalledApplications(0).firstOrNull {"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/tools/SystemTool.kt"- line="137"- column="28"/>- </issue>-- <issue- id="SelectedPhotoAccess"- message="Your app is currently not handling Selected Photos Access introduced in Android 14+"- errorLine1=" <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/AndroidManifest.xml"- line="9"- column="36"/>- </issue>-- <issue- id="GradleDependency"- message="A newer version of `compileSdkVersion` than 34 is available: 36"- errorLine1=" compileSdk = 34"- errorLine2=" ~~~~~~~~~~~~~~~">- <location- file="build.gradle.kts"- line="18"- column="5"/>- </issue>-- <issue- id="GradleDependency"- message="A newer version of androidx.core:core-ktx than 1.12.0 is available: 1.19.0"- errorLine1=" implementation("androidx.core:core-ktx:1.12.0")"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="build.gradle.kts"- line="101"- column="20"/>- </issue>-- <issue- id="GradleDependency"- message="A newer version of androidx.lifecycle:lifecycle-runtime-ktx than 2.7.0 is available: 2.11.0"- errorLine1=" implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.7.0")"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="build.gradle.kts"- line="102"- column="20"/>- </issue>-- <issue- id="GradleDependency"- message="A newer version of androidx.activity:activity-compose than 1.8.2 is available: 1.13.0"- errorLine1=" implementation("androidx.activity:activity-compose:1.8.2")"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="build.gradle.kts"- line="103"- column="20"/>- </issue>-- <issue- id="GradleDependency"- message="A newer version of androidx.lifecycle:lifecycle-viewmodel-compose than 2.7.0 is available: 2.11.0"- errorLine1=" implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.7.0")"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="build.gradle.kts"- line="113"- column="20"/>- </issue>-- <issue- id="GradleDependency"- message="A newer version of androidx.security:security-crypto than 1.1.0-alpha06 is available: 1.1.0"- errorLine1=" implementation("androidx.security:security-crypto:1.1.0-alpha06")"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="build.gradle.kts"- line="124"- column="20"/>- </issue>-- <issue- id="GradleDependency"- message="A newer version of androidx.camera:camera-core than 1.4.0 is available: 1.6.1"- errorLine1=" implementation("androidx.camera:camera-core:$cameraxVersion")"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="build.gradle.kts"- line="135"- column="20"/>- </issue>-- <issue- id="GradleDependency"- message="A newer version of androidx.camera:camera-camera2 than 1.4.0 is available: 1.6.1"- errorLine1=" implementation("androidx.camera:camera-camera2:$cameraxVersion")"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="build.gradle.kts"- line="136"- column="20"/>- </issue>-- <issue- id="GradleDependency"- message="A newer version of androidx.camera:camera-lifecycle than 1.4.0 is available: 1.6.1"- errorLine1=" implementation("androidx.camera:camera-lifecycle:$cameraxVersion")"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="build.gradle.kts"- line="137"- column="20"/>- </issue>-- <issue- id="GradleDependency"- message="A newer version of androidx.camera:camera-view than 1.4.0 is available: 1.6.1"- errorLine1=" implementation("androidx.camera:camera-view:$cameraxVersion")"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="build.gradle.kts"- line="138"- column="20"/>- </issue>-- <issue- id="NewerVersionAvailable"- message="A newer version of com.squareup.retrofit2:retrofit than 2.9.0 is available: 3.0.0"- errorLine1=" implementation("com.squareup.retrofit2:retrofit:2.9.0")"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="build.gradle.kts"- line="116"- column="20"/>- </issue>-- <issue- id="NewerVersionAvailable"- message="A newer version of com.squareup.okhttp3:logging-interceptor than 4.12.0 is available: 5.4.0"- errorLine1=" implementation("com.squareup.okhttp3:logging-interceptor:4.12.0")"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="build.gradle.kts"- line="117"- column="20"/>- </issue>-- <issue- id="NewerVersionAvailable"- message="A newer version of org.jetbrains.kotlinx:kotlinx-serialization-json than 1.6.2 is available: 1.11.0"- errorLine1=" implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.2")"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="build.gradle.kts"- line="120"- column="20"/>- </issue>-- <issue- id="NewerVersionAvailable"- message="A newer version of org.jsoup:jsoup than 1.17.2 is available: 1.22.2"- errorLine1=" implementation("org.jsoup:jsoup:1.17.2")"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="build.gradle.kts"- line="127"- column="20"/>- </issue>-- <issue- id="NewerVersionAvailable"- message="A newer version of com.halilibo.compose-richtext:richtext-ui-material3 than 0.17.0 is available: 0.20.0"- errorLine1=" implementation("com.halilibo.compose-richtext:richtext-ui-material3:0.17.0")"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="build.gradle.kts"- line="130"- column="20"/>- </issue>-- <issue- id="NewerVersionAvailable"- message="A newer version of com.halilibo.compose-richtext:richtext-commonmark than 0.17.0 is available: 0.20.0"- errorLine1=" implementation("com.halilibo.compose-richtext:richtext-commonmark:0.17.0")"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="build.gradle.kts"- line="131"- column="20"/>- </issue>-- <issue- id="NewerVersionAvailable"- message="A newer version of io.gitlab.arturbosch.detekt:detekt-formatting than 1.23.6 is available: 1.23.8"- errorLine1=" detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:1.23.6")"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="build.gradle.kts"- line="141"- column="19"/>- </issue>-- <issue- id="NewerVersionAvailable"- message="A newer version of com.squareup.okhttp3:mockwebserver than 4.12.0 is available: 5.4.0"- errorLine1=" testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0")"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="build.gradle.kts"- line="149"- column="24"/>- </issue>-- <issue- id="NewerVersionAvailable"- message="A newer version of org.jetbrains.kotlinx:kotlinx-coroutines-test than 1.7.3 is available: 1.11.0"- errorLine1=" testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3")"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="build.gradle.kts"- line="150"- column="24"/>- </issue>-- <issue- id="PermissionImpliesUnsupportedChromeOsHardware"- message="Permission exists without corresponding hardware `<uses-feature android:name="android.hardware.telephony" required="false">` tag"- errorLine1=" <uses-permission android:name="android.permission.CALL_PHONE" />"- errorLine2=" ~~~~~~~~~~~~~~~">- <location- file="src/main/AndroidManifest.xml"- line="10"- column="6"/>- </issue>-- <issue- id="PermissionImpliesUnsupportedChromeOsHardware"- message="Permission exists without corresponding hardware `<uses-feature android:name="android.hardware.telephony" required="false">` tag"- errorLine1=" <uses-permission android:name="android.permission.SEND_SMS" />"- errorLine2=" ~~~~~~~~~~~~~~~">- <location- file="src/main/AndroidManifest.xml"- line="19"- column="6"/>- </issue>-- <issue- id="PermissionImpliesUnsupportedChromeOsHardware"- message="Permission exists without corresponding hardware `<uses-feature android:name="android.hardware.telephony" required="false">` tag"- errorLine1=" <uses-permission android:name="android.permission.READ_SMS" />"- errorLine2=" ~~~~~~~~~~~~~~~">- <location- file="src/main/AndroidManifest.xml"- line="20"- column="6"/>- </issue>-- <issue- id="PermissionImpliesUnsupportedChromeOsHardware"- message="Permission exists without corresponding hardware `<uses-feature android:name="android.hardware.camera" required="false">` tag"- errorLine1=" <uses-permission android:name="android.permission.CAMERA" />"- errorLine2=" ~~~~~~~~~~~~~~~">- <location- file="src/main/AndroidManifest.xml"- line="28"- column="6"/>- </issue>-- <issue- id="SetWorldReadable"- message="Setting file permissions to world-readable can be risky, review carefully"- errorLine1=" file?.setReadable(true, false)"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/tools/MediaCaptureTool.kt"- line="178"- column="13"/>- </issue>-- <issue- id="ObsoleteSdkInt"- message="Unnecessary; `SDK_INT` is always >= 26"- errorLine1=" if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/tools/AlarmReceiver.kt"- line="55"- column="13"/>- </issue>-- <issue- id="ObsoleteSdkInt"- message="Unnecessary; `SDK_INT` is never < 26"- errorLine1=" Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.canDrawOverlays(appContext)"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt"- line="64"- column="9"/>- </issue>-- <issue- id="ObsoleteSdkInt"- message="Unnecessary; `SDK_INT` is always >= 26"- errorLine1=" if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt"- line="343"- column="13"/>- </issue>-- <issue- id="ObsoleteSdkInt"- message="Unnecessary; `SDK_INT` is always >= 26"- errorLine1=" if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/service/AssistiveBallService.kt"- line="279"- column="13"/>- </issue>-- <issue- id="ObsoleteSdkInt"- message="Unnecessary; `SDK_INT` is never < 26"- errorLine1=" Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.canDrawOverlays(appContext)"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/ConfirmationOverlay.kt"- line="39"- column="9"/>- </issue>-- <issue- id="ObsoleteSdkInt"- message="Unnecessary; `SDK_INT` is always >= 26"- errorLine1=" val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/ConfirmationOverlay.kt"- line="116"- column="24"/>- </issue>-- <issue- id="ObsoleteSdkInt"- message="Unnecessary; `SDK_INT` is never < 26"- errorLine1=" if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return false"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/service/GotchaAccessibilityService.kt"- line="153"- column="13"/>- </issue>-- <issue- id="ObsoleteSdkInt"- message="Unnecessary; `SDK_INT` is never < 26"- errorLine1=" if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/tools/MediaCaptureTool.kt"- line="212"- column="13"/>- </issue>-- <issue- id="ObsoleteSdkInt"- message="Unnecessary; `SDK_INT` is never < 26"- errorLine1=" if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/tools/MediaCaptureTool.kt"- line="227"- column="13"/>- </issue>-- <issue- id="ObsoleteSdkInt"- message="Unnecessary; `SDK_INT` is always >= 26"- errorLine1=" val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/tools/OverlayTool.kt"- line="76"- column="24"/>- </issue>-- <issue- id="ObsoleteSdkInt"- message="Unnecessary; `SDK_INT` is never < 26"- errorLine1=" Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.canDrawOverlays(context)"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/tools/OverlayTool.kt"- line="96"- column="9"/>- </issue>-- <issue- id="ObsoleteSdkInt"- message="Unnecessary; `SDK_INT` is always >= 26"- errorLine1=" if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/PermissionItems.kt"- line="140"- column="21"/>- </issue>-- <issue- id="AutoboxingStateCreation"- message="Prefer `mutableIntStateOf` instead of `mutableStateOf`"- errorLine1=" var resumeSignal by remember { mutableStateOf(0) }"- errorLine2=" ~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/PermissionsSection.kt"- line="48"- column="36"/>- </issue>-- <issue- id="UnusedResources"- message="The resource `R.drawable.ic_launcher_background` appears to be unused"- errorLine1="<vector xmlns:android="http://schemas.android.com/apk/res/android""- errorLine2="^">- <location- file="src/main/res/drawable/ic_launcher_background.xml"- line="2"- column="1"/>- </issue>-- <issue- id="UnusedResources"- message="The resource `R.drawable.ic_launcher_foreground` appears to be unused"- errorLine1="<vector xmlns:android="http://schemas.android.com/apk/res/android""- errorLine2="^">- <location- file="src/main/res/drawable/ic_launcher_foreground.xml"- line="2"- column="1"/>- </issue>-- <issue- id="IconLauncherShape"- message="Launcher icons should not fill every pixel of their square region; see the design guide for details">- <location- file="src/main/res/mipmap-xxxhdpi/ic_launcher.png"/>- </issue>-- <issue- id="IconLauncherShape"- message="Launcher icon used as round icon did not have a circular shape">- <location- file="src/main/res/mipmap-xxxhdpi/ic_launcher_round.png"/>- </issue>-- <issue- id="IconDuplicates"- message="The following unrelated icon files have identical contents: ic_launcher.png, ic_launcher_round.png">- <location- file="src/main/res/mipmap-xxxhdpi/ic_launcher_round.png"/>- <location- file="src/main/res/mipmap-xxxhdpi/ic_launcher.png"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `SharedPreferences.edit` instead?"- errorLine1=" set(v) = prefs.edit().putLong("next_id", v).apply()"- errorLine2=" ~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/tools/AlarmTool.kt"- line="51"- column="18"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `SharedPreferences.edit` instead?"- errorLine1=" prefs.edit().putString("alarms", json.toString()).apply()"- errorLine2=" ~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/tools/AlarmTool.kt"- line="421"- column="9"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `SharedPreferences.edit` instead?"- errorLine1=" prefs.edit().putString("timers", json.toString()).apply()"- errorLine2=" ~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/tools/AlarmTool.kt"- line="463"- column="9"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toUri` instead?"- errorLine1=" val intent = Intent(Intent.ACTION_DELETE, Uri.parse("package:$packageName"))"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/tools/AppsTool.kt"- line="134"- column="55"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toColorInt` instead?"- errorLine1=" setStroke(dp(1), Color.parseColor("#66FFFFFF"))"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt"- line="134"- column="34"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toColorInt` instead?"- errorLine1=" setStroke(dp(1), Color.parseColor("#66FFFFFF"))"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt"- line="134"- column="34"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toColorInt` instead?"- errorLine1=" setColor(Color.parseColor("#1E1E1E"))"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt"- line="210"- column="26"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toColorInt` instead?"- errorLine1=" setColor(Color.parseColor("#1E1E1E"))"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt"- line="210"- column="26"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toColorInt` instead?"- errorLine1=" setStroke(dp(1), Color.parseColor("#3A3A3A"))"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt"- line="211"- column="34"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toColorInt` instead?"- errorLine1=" setStroke(dp(1), Color.parseColor("#3A3A3A"))"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt"- line="211"- column="34"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toColorInt` instead?"- errorLine1=" setTextColor(Color.parseColor("#EADDFF"))"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt"- line="237"- column="22"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toColorInt` instead?"- errorLine1=" setColor(Color.parseColor("#1E1E1E"))"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt"- line="291"- column="30"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toColorInt` instead?"- errorLine1=" setColor(Color.parseColor("#1E1E1E"))"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt"- line="291"- column="30"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toColorInt` instead?"- errorLine1=" setStroke(dp(1), Color.parseColor("#3A3A3A"))"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt"- line="292"- column="38"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toColorInt` instead?"- errorLine1=" setStroke(dp(1), Color.parseColor("#3A3A3A"))"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt"- line="292"- column="38"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toColorInt` instead?"- errorLine1=" setTextColor(Color.parseColor("#EEEEEE"))"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt"- line="298"- column="34"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `Bitmap.scale` instead?"- errorLine1=" val scaled = Bitmap.createScaledBitmap(bitmap, w, h, true)"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/agent/ChatViewModel.kt"- line="225"- column="26"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `Bitmap.scale` instead?"- errorLine1=" val scaled = android.graphics.Bitmap.createScaledBitmap(bitmap, w, h, true)"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/agent/ChatViewModel.kt"- line="1079"- column="26"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toColorInt` instead?"- errorLine1=" setColor(Color.parseColor("#1E1E1E"))"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/ConfirmationOverlay.kt"- line="75"- column="26"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toColorInt` instead?"- errorLine1=" setColor(Color.parseColor("#1E1E1E"))"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/ConfirmationOverlay.kt"- line="75"- column="26"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toColorInt` instead?"- errorLine1=" setStroke(dp(1), Color.parseColor("#3A3A3A"))"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/ConfirmationOverlay.kt"- line="76"- column="34"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toColorInt` instead?"- errorLine1=" setStroke(dp(1), Color.parseColor("#3A3A3A"))"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/ConfirmationOverlay.kt"- line="76"- column="34"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toColorInt` instead?"- errorLine1=" setTextColor(Color.parseColor("#CCCCCC"))"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/ConfirmationOverlay.kt"- line="89"- column="26"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toUri` instead?"- errorLine1=" Uri.parse("package:$packageName")"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/MainActivity.kt"- line="92"- column="29"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toUri` instead?"- errorLine1=" Uri.parse("package:$packageName")"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/MainActivity.kt"- line="110"- column="29"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toUri` instead?"- errorLine1=" Uri.parse("package:$packageName"))"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/MainActivity.kt"- line="112"- column="29"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toUri` instead?"- errorLine1=" Uri.parse("package:$packageName")"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/MainActivity.kt"- line="117"- column="29"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `SharedPreferences.edit` instead?"- errorLine1=" prefs.edit().putBoolean(KEY_FIRST_LAUNCH_DONE, true).apply()"- errorLine2=" ~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/MainActivity.kt"- line="147"- column="17"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toUri` instead?"- errorLine1=" Uri.parse("package:$packageName")"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/MainActivity.kt"- line="187"- column="25"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toUri` instead?"- errorLine1=" Uri.parse("package:$packageName")"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/PermissionsSection.kt"- line="156"- column="13"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toUri` instead?"- errorLine1=" Intent(AndroidSettings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, Uri.parse("package:$packageName"))"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/PermissionsSection.kt"- line="163"- column="83"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toUri` instead?"- errorLine1=" else Intent(AndroidSettings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName"))"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/PermissionsSection.kt"- line="164"- column="74"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toUri` instead?"- errorLine1=" ToolResult.OVERLAY_ACCESS -> Intent(AndroidSettings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:$packageName"))"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/PermissionsSection.kt"- line="165"- column="95"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toUri` instead?"- errorLine1=" val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:$trimmed")).apply {"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/tools/PhoneTool.kt"- line="32"- column="53"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `String.toUri` instead?"- errorLine1=" val intent = Intent(Intent.ACTION_CALL, Uri.parse("tel:$trimmed")).apply {"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/tools/PhoneTool.kt"- line="59"- column="53"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `Bitmap.scale` instead?"- errorLine1=" val scaled = Bitmap.createScaledBitmap(bitmap, w, h, true)"- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/agent/QuickAskEngine.kt"- line="99"- column="30"/>- </issue>-- <issue- id="UseKtx"- message="Use the KTX extension function `SharedPreferences.edit` instead?"- errorLine1=" prefs.edit()"- errorLine2=" ~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/data/SettingsRepository.kt"- line="69"- column="9"/>- </issue>-- <issue- id="ClickableViewAccessibility"- message="`onTouch` lambda should call `View#performClick` when a click is detected"- errorLine1=" return View.OnTouchListener { _, event ->"- errorLine2=" ^">- <location- file="src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt"- line="146"- column="37"/>- </issue>-- <issue- id="SetTextI18n"- message="String literal in `setText` can not be translated. Use Android resources instead."- errorLine1=" text = "Close""- errorLine2=" ~~~~~">- <location- file="src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt"- line="309"- column="29"/>- </issue>-- <issue- id="SetTextI18n"- message="String literal in `setText` can not be translated. Use Android resources instead."- errorLine1=" text = "Gotcha — confirm action""- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~">- <location- file="src/main/java/com/gotcha/ui/ConfirmationOverlay.kt"- line="81"- column="21"/>- </issue>-- <issue- id="SetTextI18n"- message="String literal in `setText` can not be translated. Use Android resources instead."- errorLine1=" text = "Deny""- errorLine2=" ~~~~">- <location- file="src/main/java/com/gotcha/ui/ConfirmationOverlay.kt"- line="99"- column="21"/>- </issue>-- <issue- id="SetTextI18n"- message="String literal in `setText` can not be translated. Use Android resources instead."- errorLine1=" text = "Allow""- errorLine2=" ~~~~~">- <location- file="src/main/java/com/gotcha/ui/ConfirmationOverlay.kt"- line="103"- column="21"/>- </issue>--</issues>diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex c7cded9..c7cf809 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -3,6 +3,14 @@xmlns:tools="http://schemas.android.com/tools"package="com.gotcha">+ <!-- Telephony and camera are used when present but not required (e.g. tablets, ChromeOS). -->+ <uses-feature+ android:name="android.hardware.telephony"+ android:required="false" />+ <uses-feature+ android:name="android.hardware.camera"+ android:required="false" />+<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.SET_WALLPAPER" /><uses-permission android:name="android.permission.WRITE_SETTINGS" />@@ -19,6 +27,8 @@<uses-permission android:name="android.permission.SEND_SMS" /><uses-permission android:name="android.permission.READ_SMS" /><uses-permission android:name="android.permission.READ_CALL_LOG" />+ <!-- Needed by resolveSubId to pick a SIM slot for calls/SMS on dual-SIM devices. -->+ <uses-permission android:name="android.permission.READ_PHONE_STATE" /><uses-permission android:name="android.permission.READ_CONTACTS" /><uses-permission android:name="android.permission.WRITE_CONTACTS" /><uses-permission android:name="android.permission.READ_CALENDAR" />diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.ktindex 53faef7..fbf4a22 100644--- a/app/src/main/java/com/gotcha/MainActivity.kt+++ b/app/src/main/java/com/gotcha/MainActivity.kt@@ -1,18 +1,15 @@package com.gotchaimport android.app.admin.DevicePolicyManager-import android.content.Contextimport android.content.Intent-import android.content.SharedPreferencesimport android.net.Uriimport android.net.VpnServiceimport android.os.Buildimport android.os.Bundle-import android.provider.Settings as AndroidSettingsimport android.widget.Toastimport androidx.activity.ComponentActivity-import androidx.activity.compose.setContentimport androidx.activity.compose.BackHandler+import androidx.activity.compose.setContentimport androidx.activity.result.contract.ActivityResultContractsimport androidx.activity.viewModelsimport androidx.compose.foundation.layout.fillMaxSize@@ -29,15 +26,11 @@ import androidx.compose.ui.Modifierimport androidx.lifecycle.lifecycleScopeimport com.gotcha.agent.ChatViewModelimport com.gotcha.audio.AudioApi-import com.gotcha.audio.AudioModelimport com.gotcha.audio.ModelCategoryimport com.gotcha.data.Settingsimport com.gotcha.data.SettingsRepository-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.withContextimport com.gotcha.llm.ChatMessageimport com.gotcha.llm.LLMClient-import kotlinx.serialization.json.JsonPrimitiveimport com.gotcha.service.AssistiveBallServiceimport com.gotcha.service.GotchaDeviceAdminReceiverimport com.gotcha.tools.ToolResult@@ -45,7 +38,11 @@ import com.gotcha.ui.ChatScreenimport com.gotcha.ui.SessionsScreenimport com.gotcha.ui.SettingsScreenimport com.gotcha.ui.theme.GotchaTheme+import kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import kotlinx.serialization.json.JsonPrimitive+import android.provider.Settings as AndroidSettingsenum class Route { SESSIONS, CHAT, SETTINGS }@@ -57,17 +54,6 @@ class MainActivity : ComponentActivity() {/** Set when launched from the assistive ball's "Open Chat" option. */private var openChatRequested by mutableStateOf(false)- /** Used by the Settings screen to grant individual runtime permissions. */- private val permissionLauncher =- registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->- Toast.makeText(- this,- if (granted) "Permission granted."- else "Permission denied.",- Toast.LENGTH_SHORT- ).show()- }-/** Requests all runtime permissions at once on first launch. */private val firstLaunchLauncher =registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { _ ->@@ -105,11 +91,17 @@ class MainActivity : ComponentActivity() {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"))+ 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(@@ -219,9 +211,9 @@ class MainActivity : ComponentActivity() {private fun GotchaApp() {val state by chatViewModel.uiState.collectAsState()val sessions by chatViewModel.sessions.collectAsState()-- var currentRoute by remember {- mutableStateOf(if (settingsRepository.load().isConfigured) Route.SESSIONS else Route.SETTINGS)++ var currentRoute by remember {+ mutableStateOf(if (settingsRepository.load().isConfigured) Route.SESSIONS else Route.SETTINGS)}var previousRoute by remember { mutableStateOf(Route.SESSIONS) }var assistiveBallOn by remember { mutableStateOf(settingsRepository.load().assistiveBallEnabled) }@@ -257,7 +249,8 @@ class MainActivity : ComponentActivity() {onTestConnection = ::testConnection,onClearLlmCache = {LLMClient(- apiKey = "unused", baseUrl = "http://localhost/",+ apiKey = "unused",+ baseUrl = "http://localhost/",context = this@MainActivity).clearCache()},@@ -312,9 +305,9 @@ class MainActivity : ComponentActivity() {onStop = chatViewModel::stopAgent,onConfirm = chatViewModel::confirmPendingActions,onAnswer = chatViewModel::submitAnswer,- onBack = {+ onBack = {chatViewModel.refreshSessions()- currentRoute = Route.SESSIONS+ currentRoute = Route.SESSIONS},onOpenSettings = {previousRoute = Route.CHATdiff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.ktindex 3e3d01f..086d863 100644--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt@@ -7,15 +7,15 @@ import android.net.Uriimport android.util.Logimport androidx.lifecycle.AndroidViewModelimport androidx.lifecycle.viewModelScope-import com.gotcha.audio.AudioProviderimport com.gotcha.audio.AudioModel+import com.gotcha.audio.AudioProviderimport com.gotcha.audio.SttEngineimport com.gotcha.audio.TtsEngineimport com.gotcha.data.ChatHistoryRepository+import com.gotcha.data.ChatSessionimport com.gotcha.data.Settingsimport com.gotcha.data.SettingsRepositoryimport com.gotcha.llm.ChatMessage-import com.gotcha.data.ChatSessionimport com.gotcha.llm.LLMClientimport com.gotcha.llm.ToolCallimport com.gotcha.llm.visionUserMessage@@ -25,13 +25,11 @@ import com.gotcha.tools.ToolExecutorimport com.gotcha.tools.ToolRegistryimport com.gotcha.tools.ToolResultimport com.gotcha.ui.ConfirmationOverlay+import kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.CompletableDeferredimport kotlinx.coroutines.Job-import kotlinx.coroutines.delay-import kotlinx.coroutines.CancellationException-import kotlinx.coroutines.withContextimport kotlinx.coroutines.NonCancellable-import kotlinx.coroutines.withTimeoutOrNull+import kotlinx.coroutines.delayimport kotlinx.coroutines.flow.MutableSharedFlowimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.SharedFlow@@ -40,11 +38,11 @@ import kotlinx.coroutines.flow.asSharedFlowimport kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.flow.updateimport kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import kotlinx.coroutines.withTimeoutOrNullimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitive-import kotlinx.serialization.json.buildJsonObject-import kotlinx.serialization.json.putimport java.io.ByteArrayOutputStreamenum class MessageKind { USER, ASSISTANT, TOOL, ERROR }@@ -89,9 +87,11 @@ data class ChatUiState(val sttModels: List<AudioModel> = emptyList())+// Central agent orchestrator: session state, tool loop, TTS/STT, and confirmations all+// funnel through here. Splitting it is tracked in AGENTS.md ("what's missing").+@Suppress("LargeClass", "TooManyFunctions")class ChatViewModel(application: Application) : AndroidViewModel(application) {- private val TAG = "Gotcha"private val settingsRepository = SettingsRepository(application)private val historyRepository = ChatHistoryRepository(application)private val toolExecutor = ToolExecutor(application)@@ -100,14 +100,19 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {private var settings: Settings = Settings()private var client: LLMClient? = null+/** True when the most recent user message was sent via voice (STT). */@Volatileprivate var lastInputWasVoice = falseprivate val ttsEngine: TtsEngine = TtsEngine(- getApplication(), settings.ttsApiBaseUrl, settings.apiKey+ getApplication(),+ settings.ttsApiBaseUrl,+ settings.apiKey)private val sttEngine: SttEngine = SttEngine(- getApplication(), settings.sttApiBaseUrl, settings.apiKey+ getApplication(),+ settings.sttApiBaseUrl,+ settings.apiKey)/** Set by the Activity in onStart/onStop; drives whether confirmations use the overlay. */@@ -171,7 +176,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {context = getApplication(),apiTimeoutSeconds = settings.apiTimeoutSeconds)- } else null+ } else {+ null+ }ttsEngine.configureApi(settings.ttsApiBaseUrl, settings.apiKey)sttEngine.configureApi(settings.sttApiBaseUrl, settings.apiKey)_uiState.update { it.copy(isConfigured = settings.isConfigured) }@@ -196,7 +203,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {_uiState.update { it.copy(isBusy = true) }try {runToolLoop()- } catch (e: CancellationException) {+ } catch (_: CancellationException) {appendUi(MessageKind.ERROR, "Agent was interrupted by the user.")} finally {withContext(NonCancellable) {@@ -220,7 +227,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {val (w, h) = if (bitmap.width > maxDimension || bitmap.height > maxDimension) {val ratio = minOf(maxDimension.toFloat() / bitmap.width, maxDimension.toFloat() / bitmap.height)(bitmap.width * ratio).toInt() to (bitmap.height * ratio).toInt()- } else bitmap.width to bitmap.height+ } else {+ bitmap.width to bitmap.height+ }val scaled = Bitmap.createScaledBitmap(bitmap, w, h, true)if (scaled != bitmap) bitmap.recycle()@@ -229,7 +238,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {scaled.compress(android.graphics.Bitmap.CompressFormat.JPEG, 85, output)scaled.recycle()android.util.Base64.encodeToString(output.toByteArray(), android.util.Base64.NO_WRAP)- } catch (e: Exception) {+ } catch (_: Exception) {null}}@@ -280,7 +289,10 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {getApplication(), perm) == android.content.pm.PackageManager.PERMISSION_GRANTEDif (!granted) {- appendUi(MessageKind.ERROR, "Microphone permission not granted. Enable it in Settings → Permissions.")+ appendUi(+ MessageKind.ERROR,+ "Microphone permission not granted. Enable it in Settings → Permissions."+ )return}val started = sttEngine.startAndroidListening()@@ -361,7 +373,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {_uiState.update { it.copy(activeAgent = next) }// Append a system message so the LLM knows the mode changedval 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.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))@@ -424,7 +438,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {private suspend fun saveCurrentSession() {val id = activeSessionId ?: returnval title = llmHistory.firstOrNull { it.role == "user" }?.textContent?.take(30) ?: "New Chat"- historyRepository.saveSession(ChatSession(id, title, System.currentTimeMillis(), llmHistory.toList(), activeSessionTokenCount))+ historyRepository.saveSession(+ ChatSession(id, title, System.currentTimeMillis(), llmHistory.toList(), activeSessionTokenCount)+ )}private suspend fun checkAndCompactHistory(llm: LLMClient) {@@ -436,12 +452,33 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {val preserveLast = if (lastMessage?.role == "user") {llmHistory.removeLast()lastMessage- } else null+ } else {+ null+ }_uiState.update { it.copy(activity = "Compacting history…") }val compactionSystem = ChatMessage(role = "system",- content = JsonPrimitive("You are an advanced context compaction agent. Your task is to compress the preceding conversation history into a highly dense, structured continuation summary. You must preserve critical context, decisions, and codebase states while eliminating conversational filler and repetitive tool logs.\n\nGenerate a structured summary containing exactly the following sections:\n1. **Goal**: What is the ultimate objective of this engineering session?\n2. **Instructions & Constraints**: What specific guidelines, patterns, user preferences, or technical limitations have been established?\n3. **Discoveries & Architecture**: What have we learned about the codebase? Detail any symbol mappings, logic structures, or debugging conclusions.\n4. **Accomplished**: What changes have already been completely implemented, verified, or fixed?\n5. **Relevant Files**: Which files are currently being modified or are active in the workspace?\n\nCRITICAL: Do not lose technical specifics, user-stated constraints, or deep investigation states.\n\nContinue if you have next steps, or stop and ask for clarification if you are unsure how to proceed.")+ content = JsonPrimitive(+ "You are an advanced context compaction agent. Your task is to compress the preceding " ++ "conversation history into a highly dense, structured continuation summary. You must " ++ "preserve critical context, decisions, and codebase states while eliminating " ++ "conversational filler and repetitive tool logs.\n\n" ++ "Generate a structured summary containing exactly the following sections:\n" ++ "1. **Goal**: What is the ultimate objective of this engineering session?\n" ++ "2. **Instructions & Constraints**: What specific guidelines, patterns, user " ++ "preferences, or technical limitations have been established?\n" ++ "3. **Discoveries & Architecture**: What have we learned about the codebase? Detail " ++ "any symbol mappings, logic structures, or debugging conclusions.\n" ++ "4. **Accomplished**: What changes have already been completely implemented, " ++ "verified, or fixed?\n" ++ "5. **Relevant Files**: Which files are currently being modified or are active in " ++ "the workspace?\n\n" ++ "CRITICAL: Do not lose technical specifics, user-stated constraints, or deep " ++ "investigation states.\n\n" ++ "Continue if you have next steps, or stop and ask for clarification if you are " ++ "unsure how to proceed."+ ))val historyText = trimmedHistory().joinToString("\n\n") { msg ->@@ -449,14 +486,18 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {val text = msg.textContent.ifEmpty {if (!msg.toolCalls.isNullOrEmpty()) {"Called tools: " + msg.toolCalls.joinToString(", ") { it.function.name }- } else ""+ } else {+ ""+ }}"[$role]: $text"}val requestMessage = ChatMessage(role = "user",- content = JsonPrimitive("Please summarize the following conversation history according to the system prompt instructions:\n\n$historyText")+ content = JsonPrimitive(+ "Please summarize the following conversation history according to the system prompt instructions:\n\n$historyText"+ ))try {@@ -479,7 +520,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {}} catch (e: CancellationException) {throw e- } catch (e: Exception) {+ } catch (_: Exception) {// If compaction fails, restore the user messageif (preserveLast != null) {llmHistory.add(preserveLast)@@ -487,6 +528,8 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {}}+ // The core agent loop: LLM call → tool dispatch → confirmation gates → repeat.+ @Suppress("CyclomaticComplexMethod")private suspend fun runToolLoop() {val llm = client ?: returnval agent = _uiState.value.activeAgent@@ -515,7 +558,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {appendUi(MessageKind.ERROR, friendlyError(e))return}-+response.usage?.totalTokens?.let {activeSessionTokenCount = itupdateContextUsage()@@ -602,7 +645,8 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {val visionMsg = visionUserMessage("Screen text:\n$screenText\n\nThe assistant also captured a screenshot. " +"Use it together with the screen text to understand the current screen.",- screenshotBase64, "png"+ screenshotBase64,+ "png")llmHistory.add(visionMsg)appendUi(MessageKind.ASSISTANT, "[Screenshot captured for visual context]")@@ -665,7 +709,8 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {val format = mime.substringAfter("image/")val visionMsg = visionUserMessage("The assistant read an image file: $filename ($dimensions, $sizeDisplay).",- base64, format+ base64,+ format)llmHistory.add(visionMsg)@@ -779,10 +824,13 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {val label = parts[0]val pkg = parts[1]Log.d(TAG, "handleUninstallConfirm: label=$label pkg=$pkg")- val description = "Request to uninstall \"$label\". After you approve, a system dialog will open — you must tap \"OK\" in that dialog to complete the removal. This action is irreversible."+ val description = "Request to uninstall \"$label\". After you approve, a system dialog will " ++ "open — you must tap \"OK\" in that dialog to complete the removal. This action is irreversible."val gate = CompletableDeferred<Boolean>()confirmationGate = gate- _uiState.update { it.copy(activity = null, pendingConfirmation = PendingConfirmation(listOf("uninstall_app"), description)) }+ _uiState.update {+ it.copy(activity = null, pendingConfirmation = PendingConfirmation(listOf("uninstall_app"), description))+ }val approved = withTimeoutOrNull(120_000L) { gate.await() } ?: falseconfirmationOverlay.dismiss()@@ -819,7 +867,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {val description = "Request to delete $kind \"$label\" (#$id). This action is irreversible."val gate = CompletableDeferred<Boolean>()confirmationGate = gate- _uiState.update { it.copy(activity = null, pendingConfirmation = PendingConfirmation(listOf("delete_$kind"), description)) }+ _uiState.update {+ it.copy(activity = null, pendingConfirmation = PendingConfirmation(listOf("delete_$kind"), description))+ }val approved = withTimeoutOrNull(120_000L) { gate.await() } ?: falseconfirmationOverlay.dismiss()@@ -833,7 +883,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {"calendar_event" -> toolExecutor.executeDeleteCalendarEvent(id.toLong())else -> return}- } else null+ } else {+ null+ }val msg = if (actualResult != null) {actualResult.message@@ -851,7 +903,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {_uiState.update { it.copy(activity = "Running: ${call.function.name}…") }val args: JsonObject = try {json.decodeFromString(JsonObject.serializer(), call.function.arguments.ifBlank { "{}" })- } catch (e: Exception) {+ } catch (_: Exception) {return ToolResult.error("Malformed tool arguments: ${call.function.arguments.take(200)}")}return toolExecutor.execute(call.function.name, args, _uiState.value.activeAgent)@@ -892,41 +944,41 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {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. Use the sleep tool to pause and wait " +- "between operations. Keep replies short and conversational."+ "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. Use the sleep tool to pause and wait " ++ "between operations. 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. " +- "Use the sleep tool to pause and wait between operations (e.g. wait for " +- "a recording to finish before reading it). " +- "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 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) — " +- "use uninstall_app only."+ "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. " ++ "Use the sleep tool to pause and wait between operations (e.g. wait for " ++ "a recording to finish before reading it). " ++ "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 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) — " ++ "use uninstall_app only."}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>"+ "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>"+ "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(core + reminder))@@ -968,7 +1020,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {} catch (_: Exception) { false }val vpnActive = try {- val cm = app.getSystemService(android.content.Context.CONNECTIVITY_SERVICE) as? android.net.ConnectivityManager+ val cm = app.getSystemService(+ android.content.Context.CONNECTIVITY_SERVICE+ ) as? android.net.ConnectivityManagercm?.getNetworkCapabilities(cm.activeNetwork)?.hasTransport(android.net.NetworkCapabilities.TRANSPORT_VPN) ?: false} catch (_: Exception) { false }@@ -982,7 +1036,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {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(+ " 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"}")@@ -1002,7 +1058,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {val maxTokens = settings.maxContextTokensvar currentTokens = 0var start = llmHistory.size - 1-+while (start >= 0) {currentTokens += llmHistory[start].textContent.length / 4if (currentTokens > maxTokens) {@@ -1011,17 +1067,21 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {}start--}-+if (start < 0) start = 0-+// Skip leading tool messages so we don't have an orphaned tool resultwhile (start < llmHistory.size && llmHistory[start].role == "tool") start++-+val trimmed = llmHistory.subList(start, llmHistory.size)// Many LLM APIs strictly require history to start with a user message.// If our truncation or compaction leaves an assistant message first, prepend a dummy user message.if (trimmed.isNotEmpty() && trimmed.first().role == "assistant") {- return listOf(ChatMessage(role = "user", content = JsonPrimitive("[System Note: Conversation context restored from previous turn]"))) + trimmed+ val note = ChatMessage(+ role = "user",+ content = JsonPrimitive("[System Note: Conversation context restored from previous turn]")+ )+ return listOf(note) + trimmed}return trimmed}@@ -1045,7 +1105,11 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {private fun rebuildUiMessages() {val rebuilt = llmHistory.mapNotNull { msg ->when {- msg.role == "user" -> UiMessage(nextId++, MessageKind.USER, msg.textContent.ifEmpty { "(image attached)" })+ msg.role == "user" -> UiMessage(+ nextId++,+ MessageKind.USER,+ msg.textContent.ifEmpty { "(image attached)" }+ )msg.role == "assistant" && msg.hasText ->UiMessage(nextId++, MessageKind.ASSISTANT, msg.textContent)msg.role == "tool" -> UiMessage(nextId++, MessageKind.TOOL, msg.textContent.ifEmpty { "(no result)" })@@ -1075,7 +1139,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {val (w, h) = if (bitmap.width > maxDim || bitmap.height > maxDim) {val ratio = minOf(maxDim.toFloat() / bitmap.width, maxDim.toFloat() / bitmap.height)(bitmap.width * ratio).toInt() to (bitmap.height * ratio).toInt()- } else bitmap.width to bitmap.height+ } else {+ bitmap.width to bitmap.height+ }val scaled = android.graphics.Bitmap.createScaledBitmap(bitmap, w, h, true)if (scaled != bitmap) bitmap.recycle()val output = java.io.ByteArrayOutputStream()@@ -1086,6 +1152,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {}private companion object {+ const val TAG = "Gotcha"const val INTER_CALL_DELAY_MS = 400Lconst val CONFIRM_TIMEOUT_MS = 60_000L}diff --git a/app/src/main/java/com/gotcha/agent/QuickAskEngine.kt b/app/src/main/java/com/gotcha/agent/QuickAskEngine.ktindex b7de5b6..570bed6 100644--- a/app/src/main/java/com/gotcha/agent/QuickAskEngine.kt+++ b/app/src/main/java/com/gotcha/agent/QuickAskEngine.kt@@ -95,7 +95,9 @@ class QuickAskEngine(val (w, h) = if (bitmap.width > maxDim || bitmap.height > maxDim) {val ratio = minOf(maxDim.toFloat() / bitmap.width, maxDim.toFloat() / bitmap.height)(bitmap.width * ratio).toInt() to (bitmap.height * ratio).toInt()- } else bitmap.width to bitmap.height+ } else {+ bitmap.width to bitmap.height+ }val scaled = Bitmap.createScaledBitmap(bitmap, w, h, true)if (scaled != bitmap) bitmap.recycle()val output = ByteArrayOutputStream()@@ -129,7 +131,7 @@ class QuickAskEngine(screenText: String?,screenRequested: Boolean = false): String {- val llm = llmProvider() ?: throw IllegalStateException("Not configured")+ val llm = llmProvider() ?: error("Not configured")val noScreenCaptured = screenshotBase64 == null && screenText.isNullOrBlank()val systemText = if (screenRequested && noScreenCaptured) {@@ -137,7 +139,9 @@ class QuickAskEngine("on-screen text could be captured this time. Tell them briefly that you " +"couldn't read the screen right now, then help as best you can. Do NOT invent or " +"guess what is on the screen."- } else SYSTEM_PROMPT+ } else {+ SYSTEM_PROMPT+ }val system = ChatMessage(role = "system", content = JsonPrimitive(systemText))val userText = buildString {@@ -168,7 +172,9 @@ class QuickAskEngine(val voice = if (s.ttsProvider == AudioProvider.API) {if (ttsEngine.apiTtsModels.isEmpty()) ttsEngine.refreshApiModels()ttsEngine.apiTtsModels.firstOrNull { it.id == s.ttsApiModel }?.defaultVoice ?: "af_heart"- } else ""+ } else {+ ""+ }ttsEngine.speak(text = text,provider = s.ttsProvider,diff --git a/app/src/main/java/com/gotcha/audio/AudioApi.kt b/app/src/main/java/com/gotcha/audio/AudioApi.ktindex 0a1b86c..9548287 100644--- a/app/src/main/java/com/gotcha/audio/AudioApi.kt+++ b/app/src/main/java/com/gotcha/audio/AudioApi.kt@@ -69,8 +69,12 @@ class AudioApi((0 until voicesArr.length()).mapNotNull { j ->voicesArr.optJSONObject(j)?.optString("id", null)}- } else emptyList()- } else emptyList()+ } else {+ emptyList()+ }+ } else {+ emptyList()+ }AudioModel(id, category, voices)}} catch (e: Exception) {@@ -83,7 +87,11 @@ class AudioApi(fun transcribe(audioFile: File, model: String): Result<String> = runCatching {val url = "${baseUrl.trimEnd('/')}/audio/transcriptions"val boundary = "Boundary-${System.currentTimeMillis()}"- val body = buildMultipartBody(boundary, audioFile, "file", "audio/m4a",+ val body = buildMultipartBody(+ boundary,+ audioFile,+ "file",+ "audio/m4a",mapOf("model" to model))val request = Request.Builder()@@ -111,7 +119,8 @@ class AudioApi(put("response_format", "wav")}val requestBody = RequestBody.create(- "application/json".toMediaType(), json.toString()+ "application/json".toMediaType(),+ json.toString())val request = Request.Builder().url(url)@@ -126,7 +135,10 @@ class AudioApi(}private fun buildMultipartBody(- boundary: String, file: File, fieldName: String, contentType: String,+ boundary: String,+ file: File,+ fieldName: String,+ contentType: String,extraFields: Map<String, String>): RequestBody {val delimiter = "--$boundary\r\n".toByteArray()diff --git a/app/src/main/java/com/gotcha/audio/AudioModels.kt b/app/src/main/java/com/gotcha/audio/AudioModels.ktindex f41bd77..304f2fd 100644--- a/app/src/main/java/com/gotcha/audio/AudioModels.kt+++ b/app/src/main/java/com/gotcha/audio/AudioModels.kt@@ -46,7 +46,8 @@ data class AudioModel(val t = task.lowercase().trim()when {t == "text-to-speech" || t == "tts" -> return ModelCategory.TTS- t == "automatic-speech-recognition" || t == "stt" || t == "speech-to-text" || t == "transcription" -> return ModelCategory.STT+ t == "automatic-speech-recognition" || t == "stt" ||+ t == "speech-to-text" || t == "transcription" -> return ModelCategory.STT}}val lower = id.lowercase()diff --git a/app/src/main/java/com/gotcha/audio/SttEngine.kt b/app/src/main/java/com/gotcha/audio/SttEngine.ktindex 08d1cd9..17f856f 100644--- a/app/src/main/java/com/gotcha/audio/SttEngine.kt+++ b/app/src/main/java/com/gotcha/audio/SttEngine.kt@@ -28,6 +28,7 @@ class SttEngine(private var audioApi: AudioApi? = if (apiBaseUrl.isNotBlank()) AudioApi(apiBaseUrl, apiKey) else nullprivate var currentRecorder: MediaRecorder? = nullprivate var currentAudioFile: File? = null+// Android STT stateprivate var currentRecognizer: SpeechRecognizer? = nullprivate var listenGate: CompletableDeferred<String>? = null@@ -73,7 +74,10 @@ class SttEngine(/** Stop recording and return the audio file for API STT. */fun stopRecording(): File? {return try {- currentRecorder?.apply { stop(); release() }+ currentRecorder?.apply {+ stop()+ release()+ }currentRecorder = nullcurrentAudioFile} catch (_: Exception) {diff --git a/app/src/main/java/com/gotcha/audio/TtsEngine.kt b/app/src/main/java/com/gotcha/audio/TtsEngine.ktindex 581b541..373980a 100644--- a/app/src/main/java/com/gotcha/audio/TtsEngine.kt+++ b/app/src/main/java/com/gotcha/audio/TtsEngine.kt@@ -3,7 +3,6 @@ package com.gotcha.audioimport android.content.Contextimport android.media.AudioAttributesimport android.media.AudioFormat-import android.media.AudioManagerimport android.media.AudioTrackimport android.speech.tts.TextToSpeechimport android.speech.tts.UtteranceProgressListener@@ -107,20 +106,27 @@ class TtsEngine(// If it's a WAV file, skip the 44-byte headerval pcmData = if (bytes.size > 44 &&bytes[0] == 0x52.toByte() && bytes[1] == 0x49.toByte() &&- bytes[2] == 0x46.toByte() && bytes[3] == 0x46.toByte()) {+ bytes[2] == 0x46.toByte() && bytes[3] == 0x46.toByte()+ ) {bytes.copyOfRange(44, bytes.size)- } else bytes+ } else {+ bytes+ }val track = AudioTrack.Builder()- .setAudioAttributes(AudioAttributes.Builder()- .setUsage(AudioAttributes.USAGE_MEDIA)- .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)- .build())- .setAudioFormat(AudioFormat.Builder()- .setEncoding(AudioFormat.ENCODING_PCM_16BIT)- .setSampleRate(24000)- .setChannelMask(AudioFormat.CHANNEL_OUT_MONO)- .build())+ .setAudioAttributes(+ AudioAttributes.Builder()+ .setUsage(AudioAttributes.USAGE_MEDIA)+ .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)+ .build()+ )+ .setAudioFormat(+ AudioFormat.Builder()+ .setEncoding(AudioFormat.ENCODING_PCM_16BIT)+ .setSampleRate(24000)+ .setChannelMask(AudioFormat.CHANNEL_OUT_MONO)+ .build()+ ).setBufferSizeInBytes(pcmData.size).setTransferMode(AudioTrack.MODE_STATIC).build()diff --git a/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt b/app/src/main/java/com/gotcha/data/ChatHistoryRepository.ktindex 9c53c8b..1c9024b 100644--- a/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt+++ b/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt@@ -4,13 +4,10 @@ import android.content.Contextimport com.gotcha.llm.ChatMessageimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.withContext-import kotlinx.serialization.builtins.ListSerializer+import kotlinx.serialization.Serializableimport kotlinx.serialization.json.Jsonimport java.io.File-import kotlinx.serialization.Serializable-import java.util.UUID-@Serializabledata class ChatSession(val id: String,@@ -28,7 +25,7 @@ class ChatHistoryRepository(context: Context) {private val chatsDir = File(context.filesDir, "chats").apply { mkdirs() }private val json = Json { ignoreUnknownKeys = true }private val serializer = ChatSession.serializer()-+suspend fun listSessions(): List<ChatSession> = withContext(Dispatchers.IO) {chatsDir.listFiles()?.filter { it.extension == "json" }@@ -37,7 +34,7 @@ class ChatHistoryRepository(context: Context) {val session = json.decodeFromString(serializer, file.readText())// Only return metadata-light clone if desired, but we just return full for nowsession- } catch (e: Exception) {+ } catch (_: Exception) {null}}@@ -50,7 +47,7 @@ class ChatHistoryRepository(context: Context) {if (!file.exists()) return@withContext nulltry {json.decodeFromString(serializer, file.readText())- } catch (e: Exception) {+ } catch (_: Exception) {null}}diff --git a/app/src/main/java/com/gotcha/llm/LLMCache.kt b/app/src/main/java/com/gotcha/llm/LLMCache.ktindex 32afbf2..f50bca9 100644--- a/app/src/main/java/com/gotcha/llm/LLMCache.kt+++ b/app/src/main/java/com/gotcha/llm/LLMCache.kt@@ -77,7 +77,7 @@ class LLMCache(if (!file.exists()) return nullreturn try {json.decodeFromString(DiskEntry.serializer(), file.readText())- } catch (e: Exception) {+ } catch (_: Exception) {file.delete()null}@@ -87,7 +87,7 @@ class LLMCache(val file = diskFile(key) ?: returntry {file.writeText(json.encodeToString(DiskEntry.serializer(), entry))- } catch (e: Exception) {+ } catch (_: Exception) {// Disk cache is best-effort; in-memory cache still holds the entry.}}diff --git a/app/src/main/java/com/gotcha/llm/LLMClient.kt b/app/src/main/java/com/gotcha/llm/LLMClient.ktindex 7520518..5dbdce6 100644--- a/app/src/main/java/com/gotcha/llm/LLMClient.kt+++ b/app/src/main/java/com/gotcha/llm/LLMClient.kt@@ -1,13 +1,13 @@package com.gotcha.llmimport android.content.Context+import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactoryimport kotlinx.serialization.builtins.ListSerializerimport kotlinx.serialization.json.Jsonimport okhttp3.MediaType.Companion.toMediaTypeimport okhttp3.OkHttpClientimport okhttp3.logging.HttpLoggingInterceptorimport retrofit2.Retrofit-import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactoryimport java.security.MessageDigestclass LLMClient(@@ -18,10 +18,6 @@ class LLMClient(private val apiTimeoutSeconds: Long = 0L,private val cache: LLMCache = LLMCache(context)) {- companion object {- private const val DEFAULT_MODEL = "gpt-4o"- }-private val apiService: ApiService@OptIn(kotlinx.serialization.ExperimentalSerializationApi::class)@@ -82,9 +78,9 @@ class LLMClient(val response = apiService.chat(request, sessionId)- val shouldCache = (temperature == null || temperature == 0f)- && response.choices.isNotEmpty()- && response.choices.none { it.message.toolCalls?.isNotEmpty() == true }+ val shouldCache = (temperature == null || temperature == 0f) &&+ response.choices.isNotEmpty() &&+ response.choices.none { it.message.toolCalls?.isNotEmpty() == true }if (shouldCache) {cache.put(cacheKey, response)diff --git a/app/src/main/java/com/gotcha/llm/Models.kt b/app/src/main/java/com/gotcha/llm/Models.ktindex 9636865..c0e461a 100644--- a/app/src/main/java/com/gotcha/llm/Models.kt+++ b/app/src/main/java/com/gotcha/llm/Models.kt@@ -10,7 +10,6 @@ import kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitiveimport kotlinx.serialization.json.buildJsonArrayimport kotlinx.serialization.json.buildJsonObject-import kotlinx.serialization.json.jsonArrayimport kotlinx.serialization.json.jsonObjectimport kotlinx.serialization.json.jsonPrimitiveimport kotlinx.serialization.json.put@@ -49,14 +48,18 @@ fun visionUserMessage(text: String, imageBase64: String, imageFormat: String = "return ChatMessage(role = "user",content = buildJsonArray {- add(buildJsonObject {- put("type", "text")- put("text", text.ifBlank { "What is in this image?" })- })- add(buildJsonObject {- put("type", "image_url")- putJsonObject("image_url") { put("url", dataUri) }- })+ add(+ buildJsonObject {+ put("type", "text")+ put("text", text.ifBlank { "What is in this image?" })+ }+ )+ add(+ buildJsonObject {+ put("type", "image_url")+ putJsonObject("image_url") { put("url", dataUri) }+ }+ )})}diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.ktindex e06a18a..3508c44 100644--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt@@ -48,6 +48,7 @@ class AssistiveBallService : Service() {private lateinit var quickAsk: QuickAskEngine@Volatile private var isBusy = false+@Volatile private var listening = falseoverride fun onCreate() {@@ -116,7 +117,7 @@ class AssistiveBallService : Service() {)putExtra(MainActivity.EXTRA_OPEN_CHAT, true)}-+try {val pendingIntent = PendingIntent.getActivity(this,@@ -124,10 +125,10 @@ class AssistiveBallService : Service() {intent,PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)-+if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {val options = android.app.ActivityOptions.makeBasic()- options.pendingIntentBackgroundActivityStartMode =+ options.pendingIntentBackgroundActivityStartMode =android.app.ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWEDpendingIntent.send(this, 0, null, null, null, null, options.toBundle())android.util.Log.d("AssistiveBall", "PendingIntent sent with ActivityOptions")@@ -239,13 +240,16 @@ class AssistiveBallService : Service() {context = applicationContext,apiTimeoutSeconds = s.apiTimeoutSeconds)- } else null+ } else {+ null+ }}private fun startAsForeground() {createChannel()val tapIntent = PendingIntent.getActivity(- this, 0,+ this,+ 0,Intent(this, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),PendingIntent.FLAG_IMMUTABLE)@@ -305,6 +309,7 @@ class AssistiveBallService : Service() {const val ACTION_STOP = "com.gotcha.assistiveball.STOP"private val _isRunning = MutableStateFlow(false)+/** Live running state of the ball, so UI toggles can track "Hide ball" too. */val isRunning: StateFlow<Boolean> = _isRunning.asStateFlow()private const val CHANNEL_ID = "assistive_ball"diff --git a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.ktindex 838f0ee..5b2317a 100644--- a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt+++ b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt@@ -100,8 +100,9 @@ class GotchaAccessibilityService : AccessibilityService() {if (node == null || out.size >= limit) returnval text = node.text?.toString()?.trim()val desc = node.contentDescription?.toString()?.trim()- if (!text.isNullOrEmpty()) out.add(text)- else if (!desc.isNullOrEmpty()) out.add(desc)+ 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)}diff --git a/app/src/main/java/com/gotcha/service/GotchaVpnService.kt b/app/src/main/java/com/gotcha/service/GotchaVpnService.ktindex 0800466..5450be1 100644--- a/app/src/main/java/com/gotcha/service/GotchaVpnService.kt+++ b/app/src/main/java/com/gotcha/service/GotchaVpnService.kt@@ -75,7 +75,10 @@ class GotchaVpnService : VpnService() {} catch (_: Exception) {// Interface closed on teardown; exit the loop.}- }.apply { isDaemon = true; start() }+ }.apply {+ isDaemon = true+ start()+ }}}diff --git a/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt b/app/src/main/java/com/gotcha/tools/AccessibilityTool.ktindex 43c328c..44e754e 100644--- a/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt+++ b/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt@@ -30,11 +30,17 @@ class AccessibilityTool(private val context: Context) {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.")+ 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.")+ 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.")}}@@ -43,9 +49,11 @@ class AccessibilityTool(private val context: Context) {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()))+ 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.")+ } else {+ ToolResult.error("Could not dispatch the swipe gesture.")+ }}val metrics = context.resources.displayMetricsval w = metrics.widthPixels.toFloat()@@ -59,25 +67,34 @@ class AccessibilityTool(private val context: Context) {"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.")+ 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.")+ 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."- )+ 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? =diff --git a/app/src/main/java/com/gotcha/tools/ActionLog.kt b/app/src/main/java/com/gotcha/tools/ActionLog.ktindex 05d307f..04192f0 100644--- a/app/src/main/java/com/gotcha/tools/ActionLog.kt+++ b/app/src/main/java/com/gotcha/tools/ActionLog.kt@@ -18,7 +18,9 @@ class ActionLog(context: Context) {@Synchronizedfun record(tool: String, args: String, result: ToolResult) {val status = if (result.success) "OK" else "FAIL"- val line = "${formatter.format(Date())}\t$tool\t$args\t$status\t${result.message.take(500).replace('\n', ' ')}\n"+ val line = "${formatter.format(+ Date()+ )}\t$tool\t$args\t$status\t${result.message.take(500).replace('\n', ' ')}\n"try {file.appendText(line)trimIfNeeded()diff --git a/app/src/main/java/com/gotcha/tools/AlarmReceiver.kt b/app/src/main/java/com/gotcha/tools/AlarmReceiver.ktindex ad29b53..56e6c2e 100644--- a/app/src/main/java/com/gotcha/tools/AlarmReceiver.kt+++ b/app/src/main/java/com/gotcha/tools/AlarmReceiver.kt@@ -60,7 +60,11 @@ class AlarmReceiver : BroadcastReceiver() {})nm.createNotificationChannel(- NotificationChannel(CHANNEL_ID_SILENT, "Alarms & Timers (no vibration)", NotificationManager.IMPORTANCE_HIGH).apply {+ NotificationChannel(+ CHANNEL_ID_SILENT,+ "Alarms & Timers (no vibration)",+ NotificationManager.IMPORTANCE_HIGH+ ).apply {enableVibration(false)})diff --git a/app/src/main/java/com/gotcha/tools/AlarmTool.kt b/app/src/main/java/com/gotcha/tools/AlarmTool.ktindex 0d98abb..3458630 100644--- a/app/src/main/java/com/gotcha/tools/AlarmTool.kt+++ b/app/src/main/java/com/gotcha/tools/AlarmTool.kt@@ -8,13 +8,7 @@ import android.content.Intentimport android.content.SharedPreferencesimport android.os.Buildimport android.provider.AlarmClock-import java.text.SimpleDateFormat-import java.util.Calendar-import java.util.Date-import java.util.Localeimport kotlinx.serialization.json.Json-import kotlinx.serialization.json.JsonArray-import kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.booleanOrNullimport kotlinx.serialization.json.buildJsonArrayimport kotlinx.serialization.json.buildJsonObject@@ -23,6 +17,10 @@ import kotlinx.serialization.json.jsonArrayimport kotlinx.serialization.json.jsonObjectimport kotlinx.serialization.json.jsonPrimitiveimport kotlinx.serialization.json.put+import java.text.SimpleDateFormat+import java.util.Calendar+import java.util.Date+import java.util.Locale/*** Hybrid alarm management: alarms are created in the system clock app via@@ -43,6 +41,7 @@ import kotlinx.serialization.json.put* Timers always stay local: there is no intent to cancel a running clock-app* timer, which would break delete_timer.*/+@Suppress("TooManyFunctions")class AlarmTool(private val context: Context) {private val prefs: SharedPreferences = context.getSharedPreferences("gotcha_alarms", Context.MODE_PRIVATE)@@ -78,8 +77,12 @@ class AlarmTool(private val context: Context) {// rings with the full alarm UI (snooze/dismiss, alarm sound).if (dispatchClockIntent(buildSetAlarmIntent(hour, minute, label, dayInts, vibrate ?: true))) {val id = nextId++- saveAlarm(AlarmRecord(id, hour, minute, dayInts, label, vibrate ?: true, system = true, triggerAt = triggerAt))- return ToolResult.ok("Set alarm '$label' for %02d:%02d$extra in the system clock app (id=$id).".format(hour, minute))+ saveAlarm(+ AlarmRecord(id, hour, minute, dayInts, label, vibrate ?: true, system = true, triggerAt = triggerAt)+ )+ return ToolResult.ok(+ "Set alarm '$label' for %02d:%02d$extra in the system clock app (id=$id).".format(hour, minute)+ )}// No compatible clock app — schedule locally via AlarmManager.@@ -92,7 +95,11 @@ class AlarmTool(private val context: Context) {return ToolResult.error(exactAlarmDeniedMessage(e))}saveAlarm(record)- return ToolResult.ok("Set alarm '$label' for %02d:%02d$extra (id=$id). No clock app handled it, so it was scheduled in-app and rings as a notification.".format(hour, minute))+ val time = "%02d:%02d".format(hour, minute)+ return ToolResult.ok(+ "Set alarm '$label' for $time$extra (id=$id). No clock app handled it, " ++ "so it was scheduled in-app and rings as a notification."+ )}fun setTimer(seconds: Int, message: String? = null, hours: Int? = null, minutes: Int? = null): ToolResult {@@ -140,8 +147,14 @@ class AlarmTool(private val context: Context) {try { scheduleAlarm(a) } catch (_: SecurityException) {}}val dayStr = if (a.days.isNotEmpty()) {- a.days.mapNotNull { e -> dayNames.entries.firstOrNull { it.value == e }?.key?.take(3) }.joinToString(",")- } else "once"+ a.days.mapNotNull { e ->+ dayNames.entries.firstOrNull { it.value == e }?.key?.take(+ 3+ )+ }.joinToString(",")+ } else {+ "once"+ }sb.append("- $dayStr %02d:%02d".format(a.hour, a.minute))if (a.label != null) sb.append(" ${a.label}")sb.append(" (id=${a.id}, ${if (a.system) "clock app" else "in-app"})\n")@@ -165,7 +178,14 @@ class AlarmTool(private val context: Context) {return ToolResult.ok(sb.trimEnd().toString())}- fun editAlarm(id: Long, hour: Int? = null, minute: Int? = null, message: String? = null, days: List<String>? = null, vibrate: Boolean? = null): ToolResult {+ fun editAlarm(+ id: Long,+ hour: Int? = null,+ minute: Int? = null,+ message: String? = null,+ days: List<String>? = null,+ vibrate: Boolean? = null+ ): ToolResult {val alarms = loadAlarmsMutable()val idx = alarms.indexOfFirst { it.id == id }if (idx == -1) return ToolResult.error("Alarm $id not found.")@@ -186,8 +206,13 @@ class AlarmTool(private val context: Context) {if (old.system) {// No edit intent exists: dismiss the old alarm (best effort) and create a new one.dismissSystemAlarm(old)- if (!dispatchClockIntent(buildSetAlarmIntent(record.hour, record.minute, record.label, record.days, record.vibrate))) {- return ToolResult.error("Alarm $id lives in the system clock app but no clock app handled the update intent. Edit it in the clock app directly.")+ if (!dispatchClockIntent(+ buildSetAlarmIntent(record.hour, record.minute, record.label, record.days, record.vibrate)+ )+ ) {+ return ToolResult.error(+ "Alarm $id lives in the system clock app but no clock app handled the update intent. Edit it in the clock app directly."+ )}alarms[idx] = recordsaveAlarms(alarms)@@ -228,7 +253,10 @@ class AlarmTool(private val context: Context) {"some clock apps only disable it or skip the next occurrence; the user can verify in the clock app.")} else {- ToolResult.ok("Removed alarm $id from this assistant's list, but no clock app handled the dismiss intent — ask the user to delete it in the clock app.")+ ToolResult.ok(+ "Removed alarm $id from this assistant's list, but no clock app handled the " ++ "dismiss intent — ask the user to delete it in the clock app."+ )}}cancelPendingIntent(alarmRequestCode(id))@@ -350,7 +378,12 @@ class AlarmTool(private val context: Context) {putExtra("label", a.label ?: "Alarm")putExtra("vibrate", a.vibrate)}- val pi = PendingIntent.getBroadcast(context, alarmRequestCode(a.id), intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)+ val pi = PendingIntent.getBroadcast(+ context,+ alarmRequestCode(a.id),+ intent,+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT+ )alarmManager().setAlarmClock(AlarmManager.AlarmClockInfo(triggerAt, pi), pi)}@@ -360,14 +393,20 @@ class AlarmTool(private val context: Context) {putExtra("timer_id", t.id)putExtra("label", t.label ?: "Timer")}- val pi = PendingIntent.getBroadcast(context, timerRequestCode(t.id), intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)+ val pi = PendingIntent.getBroadcast(+ context,+ timerRequestCode(t.id),+ intent,+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT+ )// setExactAndAllowWhileIdle (not setExact) so the timer fires on time in Doze.alarmManager().setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, t.triggerAt, pi)}private fun isScheduled(requestCode: Int): Boolean {val intent = Intent(context, AlarmReceiver::class.java)- return PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_NO_CREATE) != null+ val flags = PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_NO_CREATE+ return PendingIntent.getBroadcast(context, requestCode, intent, flags) != null}private fun exactAlarmError(): ToolResult? {@@ -386,13 +425,20 @@ class AlarmTool(private val context: Context) {// ---- storage ----private data class AlarmRecord(- val id: Long, val hour: Int, val minute: Int,- val days: List<Int>, val label: String?, val vibrate: Boolean,- val system: Boolean = false, val triggerAt: Long? = null+ val id: Long,+ val hour: Int,+ val minute: Int,+ val days: List<Int>,+ val label: String?,+ val vibrate: Boolean,+ val system: Boolean = false,+ val triggerAt: Long? = null)private data class TimerRecord(- val id: Long, val seconds: Int, val label: String?,+ val id: Long,+ val seconds: Int,+ val label: String?,val triggerAt: Long = System.currentTimeMillis() + seconds * 1000L)@@ -405,17 +451,20 @@ class AlarmTool(private val context: Context) {private fun saveAlarms(list: List<AlarmRecord>) {val json = buildJsonArray {list.forEach { a ->- add(buildJsonObject {- put("id", a.id)- put("hour", a.hour)- put("minute", a.minute)- val daysArr = buildJsonArray { a.days.forEach { d -> add(kotlinx.serialization.json.JsonPrimitive(d)) } }- put("days", daysArr)- if (a.label != null) put("label", a.label)- put("vibrate", a.vibrate)- put("system", a.system)- if (a.triggerAt != null) put("triggerAt", a.triggerAt)- })+ add(+ buildJsonObject {+ put("id", a.id)+ put("hour", a.hour)+ put("minute", a.minute)+ val daysArr =+ buildJsonArray { a.days.forEach { d -> add(kotlinx.serialization.json.JsonPrimitive(d)) } }+ put("days", daysArr)+ if (a.label != null) put("label", a.label)+ put("vibrate", a.vibrate)+ put("system", a.system)+ if (a.triggerAt != null) put("triggerAt", a.triggerAt)+ }+ )}}prefs.edit().putString("alarms", json.toString()).apply()@@ -452,12 +501,14 @@ class AlarmTool(private val context: Context) {private fun saveTimers(list: List<TimerRecord>) {val json = buildJsonArray {list.forEach { t ->- add(buildJsonObject {- put("id", t.id)- put("seconds", t.seconds)- if (t.label != null) put("label", t.label)- put("triggerAt", t.triggerAt)- })+ add(+ buildJsonObject {+ put("id", t.id)+ put("seconds", t.seconds)+ if (t.label != null) put("label", t.label)+ put("triggerAt", t.triggerAt)+ }+ )}}prefs.edit().putString("timers", json.toString()).apply()@@ -482,7 +533,12 @@ class AlarmTool(private val context: Context) {private fun cancelPendingIntent(requestCode: Int) {val intent = Intent(context, AlarmReceiver::class.java)- val pi = PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_NO_CREATE)+ val pi = PendingIntent.getBroadcast(+ context,+ requestCode,+ intent,+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_NO_CREATE+ )if (pi != null) {alarmManager().cancel(pi)pi.cancel()@@ -495,7 +551,13 @@ class AlarmTool(private val context: Context) {if (days.isNullOrEmpty()) return emptyList()return days.flatMap { d ->when (val key = d.trim().lowercase()) {- "weekdays" -> listOf(Calendar.MONDAY, Calendar.TUESDAY, Calendar.WEDNESDAY, Calendar.THURSDAY, Calendar.FRIDAY)+ "weekdays" -> listOf(+ Calendar.MONDAY,+ Calendar.TUESDAY,+ Calendar.WEDNESDAY,+ Calendar.THURSDAY,+ Calendar.FRIDAY+ )"weekend", "weekends" -> listOf(Calendar.SATURDAY, Calendar.SUNDAY)"daily", "everyday" -> dayNumbers.toList()else -> listOfNotNull(dayNames[key])diff --git a/app/src/main/java/com/gotcha/tools/AppsTool.kt b/app/src/main/java/com/gotcha/tools/AppsTool.ktindex fbbd602..395fd93 100644--- a/app/src/main/java/com/gotcha/tools/AppsTool.kt+++ b/app/src/main/java/com/gotcha/tools/AppsTool.kt@@ -6,16 +6,18 @@ import android.app.usage.UsageStatsManagerimport android.content.Contextimport android.content.Intentimport android.content.pm.ApplicationInfo-import android.content.pm.PackageManager-import android.util.Logimport android.net.ConnectivityManagerimport android.net.Uriimport android.os.Buildimport android.os.Process+import android.util.Logclass AppsTool(private val context: Context) {- private val TAG = "Gotcha"+ private companion object {+ const val TAG = "Gotcha"+ }+private data class AppEntry(val label: String, val packageName: String, val isSystemApp: Boolean)/** List installed apps with optional search filter. */@@ -60,7 +62,9 @@ class AppsTool(private val context: Context) {"- ${it.label} (${it.packageName})${if (it.isSystemApp) " [system]" else ""}"}val truncated = if (matchCount > 30) " (showing 30 of $matchCount)" else ""- ToolResult.ok("Found $matchCount app(s) matching '$search'$truncated ($total total, $userApps user, $systemApps system).\n$listing")+ ToolResult.ok(+ "Found $matchCount app(s) matching '$search'$truncated ($total total, $userApps user, $systemApps system).\n$listing"+ )}} catch (e: Exception) {ToolResult.error("Could not list apps: ${e.message}")@@ -120,7 +124,8 @@ class AppsTool(private val context: Context) {return try {val pm = context.packageManagerval installed = try {- pm.getPackageInfo(packageName, 0); true+ pm.getPackageInfo(packageName, 0)+ true} catch (_: Exception) {false}@@ -136,7 +141,9 @@ class AppsTool(private val context: Context) {context.startActivity(intent)Log.d(TAG, "doUninstall: dialog opened for $label")- ToolResult.ok("System dialog opened to uninstall $label. After you tap OK in the dialog, ask the assistant to verify the app is gone.")+ ToolResult.ok(+ "System dialog opened to uninstall $label. After you tap OK in the dialog, ask the assistant to verify the app is gone."+ )} catch (e: Exception) {Log.e(TAG, "doUninstall failed: ${e.message}")ToolResult.error("Could not start uninstall: ${e.message}")@@ -190,8 +197,10 @@ class AppsTool(private val context: Context) {val start = end - window * 24L * 60 * 60 * 1000return try {val nsm = context.getSystemService(Context.NETWORK_STATS_SERVICE) as NetworkStatsManager+@Suppress("DEPRECATION")val mobile = nsm.querySummaryForDevice(ConnectivityManager.TYPE_MOBILE, null, start, end)+@Suppress("DEPRECATION")val wifi = nsm.querySummaryForDevice(ConnectivityManager.TYPE_WIFI, null, start, end)val mobileTotal = mobile.rxBytes + mobile.txBytes@@ -211,12 +220,16 @@ class AppsTool(private val context: Context) {val appOps = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManagerval mode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {appOps.unsafeCheckOpNoThrow(- AppOpsManager.OPSTR_GET_USAGE_STATS, Process.myUid(), context.packageName+ AppOpsManager.OPSTR_GET_USAGE_STATS,+ Process.myUid(),+ context.packageName)} else {@Suppress("DEPRECATION")appOps.checkOpNoThrow(- AppOpsManager.OPSTR_GET_USAGE_STATS, Process.myUid(), context.packageName+ AppOpsManager.OPSTR_GET_USAGE_STATS,+ Process.myUid(),+ context.packageName)}mode == AppOpsManager.MODE_ALLOWEDdiff --git a/app/src/main/java/com/gotcha/tools/CalendarTool.kt b/app/src/main/java/com/gotcha/tools/CalendarTool.ktindex 99b5193..b20611d 100644--- a/app/src/main/java/com/gotcha/tools/CalendarTool.kt+++ b/app/src/main/java/com/gotcha/tools/CalendarTool.kt@@ -16,6 +16,7 @@ class CalendarTool(private val context: Context) {private val readable = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())+ @Suppress("CyclomaticComplexMethod")fun listEvents(daysAhead: Int? = null,fromDate: String? = null,@@ -40,10 +41,16 @@ class CalendarTool(private val context: Context) {val df = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())rangeStart = if (fromDate != null) {try { df.parse(fromDate)?.time ?: now } catch (_: Exception) { now }- } else now+ } else {+ now+ }rangeEnd = if (toDate != null) {- try { df.parse(toDate)?.time?.plus(86_400_000L - 1) ?: (now + 86400000L) } catch (_: Exception) { now + 86400000L }- } else rangeStart + 86400000L+ try { df.parse(toDate)?.time?.plus(86_400_000L - 1) ?: (now + 86400000L) } catch (+ _: Exception+ ) { now + 86400000L }+ } else {+ rangeStart + 86400000L+ }rangeDesc = "${fromDate ?: "today"} → ${toDate ?: "tomorrow"}"} else {val days = (daysAhead ?: 7).coerceIn(1, 365)@@ -75,7 +82,10 @@ class CalendarTool(private val context: Context) {}context.contentResolver.query(- builder.build(), projection, selection, selectionArgs,+ builder.build(),+ projection,+ selection,+ selectionArgs,"${CalendarContract.Instances.BEGIN} ASC").use { cursor ->if (cursor == null) return ToolResult.error("Could not read the calendar.")@@ -117,7 +127,9 @@ class CalendarTool(private val context: Context) {if (count == 0) {val hint = if (!search.isNullOrBlank()) " matching '$search'" else ""ToolResult.ok("No events $rangeDesc$hint.")- } else ToolResult.ok("Events $rangeDesc ($count):\n$out")+ } else {+ ToolResult.ok("Events $rangeDesc ($count):\n$out")+ }}} catch (e: Exception) {ToolResult.error("Could not read the calendar: ${e.message}")@@ -145,8 +157,11 @@ class CalendarTool(private val context: Context) {}val startMs = parseWhen(start)?: return ToolResult.error("Could not understand the start time '$start'. Use 'yyyy-MM-dd HH:mm' or epoch millis.")- val endMs = if (end.isNullOrBlank()) startMs + 60 * 60 * 1000- else parseWhen(end) ?: return ToolResult.error("Could not understand the end time '$end'.")+ val endMs = if (end.isNullOrBlank()) {+ startMs + 60 * 60 * 1000+ } else {+ parseWhen(end) ?: return ToolResult.error("Could not understand the end time '$end'.")+ }if (allDay == true) {// all-day events: set to midnight of the start date@@ -162,9 +177,11 @@ class CalendarTool(private val context: Context) {return try {val calendarId = if (!calendarName.isNullOrBlank()) {findCalendarByName(calendarName)- } else null- ?: defaultWritableCalendarId()- ?: return ToolResult.error("No writable calendar was found on this device.")+ } else {+ null+ ?: defaultWritableCalendarId()+ ?: return ToolResult.error("No writable calendar was found on this device.")+ }val values = ContentValues().apply {put(CalendarContract.Events.CALENDAR_ID, calendarId)@@ -292,7 +309,11 @@ class CalendarTool(private val context: Context) {CalendarContract.Calendars.CALENDAR_DISPLAY_NAME)context.contentResolver.query(- CalendarContract.Calendars.CONTENT_URI, projection, null, null, null+ CalendarContract.Calendars.CONTENT_URI,+ projection,+ null,+ null,+ null)?.use { cursor ->val idIdx = cursor.getColumnIndexOrThrow(CalendarContract.Calendars._ID)val nameIdx = cursor.getColumnIndexOrThrow(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME)@@ -310,8 +331,10 @@ class CalendarTool(private val context: Context) {val v = value.trim()v.toLongOrNull()?.let { return it }val formats = listOf(- "yyyy-MM-dd HH:mm", "yyyy-MM-dd'T'HH:mm",- "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss"+ "yyyy-MM-dd HH:mm",+ "yyyy-MM-dd'T'HH:mm",+ "yyyy-MM-dd HH:mm:ss",+ "yyyy-MM-dd'T'HH:mm:ss")for (f in formats) {try {@@ -326,7 +349,10 @@ class CalendarTool(private val context: Context) {val selection = "${CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL} >= ?"val args = arrayOf(CalendarContract.Calendars.CAL_ACCESS_CONTRIBUTOR.toString())context.contentResolver.query(- CalendarContract.Calendars.CONTENT_URI, projection, selection, args,+ CalendarContract.Calendars.CONTENT_URI,+ projection,+ selection,+ args,"${CalendarContract.Calendars.IS_PRIMARY} DESC").use { cursor ->if (cursor != null && cursor.moveToFirst()) {diff --git a/app/src/main/java/com/gotcha/tools/ClipboardTool.kt b/app/src/main/java/com/gotcha/tools/ClipboardTool.ktindex 787488a..b00717f 100644--- a/app/src/main/java/com/gotcha/tools/ClipboardTool.kt+++ b/app/src/main/java/com/gotcha/tools/ClipboardTool.kt@@ -31,7 +31,11 @@ class ClipboardTool(private val context: Context) {val a11yClip = GotchaAccessibilityService.lastClipboardDataif (a11yClip != null && a11yClip.itemCount > 0) {val text = a11yClip.getItemAt(0).coerceToText(context).toString()- if (text.isNotEmpty()) return ToolResult.ok("Clipboard (from accessibility service): ${text.take(2000)}")+ if (text.isNotEmpty()) {+ return ToolResult.ok(+ "Clipboard (from accessibility service): ${text.take(2000)}"+ )+ }}if (Build.VERSION.SDK_INT >= 34) {diff --git a/app/src/main/java/com/gotcha/tools/ContactsTool.kt b/app/src/main/java/com/gotcha/tools/ContactsTool.ktindex 5cf63a7..6530ea4 100644--- a/app/src/main/java/com/gotcha/tools/ContactsTool.kt+++ b/app/src/main/java/com/gotcha/tools/ContactsTool.kt@@ -10,6 +10,7 @@ import androidx.core.content.ContextCompatclass ContactsTool(private val context: Context) {+ @Suppress("CyclomaticComplexMethod")fun findContact(name: String? = null, number: String? = null): ToolResult {if (name.isNullOrBlank() && number.isNullOrBlank()) {return ToolResult.error("Provide either a name or a phone number to search for.")@@ -66,11 +67,13 @@ class ContactsTool(private val context: Context) {ContactsContract.CommonDataKinds.Phone.TYPE_OTHER -> "other"else -> "other"}- contacts.add(mapOf(- "name" to displayName,- "number" to phoneNumber,- "type" to phoneType- ))+ contacts.add(+ mapOf(+ "name" to displayName,+ "number" to phoneNumber,+ "type" to phoneType+ )+ )}}if (contacts.isEmpty()) {@@ -109,7 +112,9 @@ class ContactsTool(private val context: Context) {context.contentResolver.query(uri,arrayOf(ContactsContract.PhoneLookup._ID),- null, null, null+ null,+ null,+ null)?.use { cursor ->if (cursor.moveToFirst()) {val contactId = cursor.getString(0)@@ -117,7 +122,8 @@ class ContactsTool(private val context: Context) {ContactsContract.CommonDataKinds.Email.CONTENT_URI,arrayOf(ContactsContract.CommonDataKinds.Email.ADDRESS),"${ContactsContract.CommonDataKinds.Email.CONTACT_ID} = ?",- arrayOf(contactId), null+ arrayOf(contactId),+ null)?.use { emailCursor ->while (emailCursor.moveToNext()) {emails.add(emailCursor.getString(0))@@ -135,7 +141,9 @@ class ContactsTool(private val context: Context) {context.contentResolver.query(uri,arrayOf(ContactsContract.PhoneLookup._ID),- null, null, null+ null,+ null,+ null)?.use { cursor ->if (cursor.moveToFirst()) {val contactId = cursor.getString(0)@@ -148,7 +156,9 @@ class ContactsTool(private val context: Context) {)?.use { orgCursor ->if (orgCursor.moveToFirst()) orgCursor.getString(0) else null}- } else null+ } else {+ null+ }}} catch (_: Exception) { null }}@@ -178,7 +188,7 @@ class ContactsTool(private val context: Context) {if (dupes > 0) {return ToolResult.error("A contact matching '$displayName' or '$phone' already exists ($dupes match(es)). " +- "Use a different name or delete the existing contact first."+ "Use a different name or delete the existing contact first.")}val typeVal = when (phoneType?.trim()?.lowercase()) {@@ -200,7 +210,10 @@ class ContactsTool(private val context: Context) {ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)- .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)+ .withValue(+ ContactsContract.Data.MIMETYPE,+ ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE+ ).withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName).build())@@ -216,9 +229,15 @@ class ContactsTool(private val context: Context) {ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)- .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)+ .withValue(+ ContactsContract.Data.MIMETYPE,+ ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE+ ).withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, email.trim())- .withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)+ .withValue(+ ContactsContract.CommonDataKinds.Email.TYPE,+ ContactsContract.CommonDataKinds.Email.TYPE_WORK+ ).build())}@@ -226,9 +245,15 @@ class ContactsTool(private val context: Context) {ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)- .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)+ .withValue(+ ContactsContract.Data.MIMETYPE,+ ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE+ ).withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, organization.trim())- .withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)+ .withValue(+ ContactsContract.CommonDataKinds.Organization.TYPE,+ ContactsContract.CommonDataKinds.Organization.TYPE_WORK+ ).build())}diff --git a/app/src/main/java/com/gotcha/tools/DeviceAdminTool.kt b/app/src/main/java/com/gotcha/tools/DeviceAdminTool.ktindex c59f47e..23f2649 100644--- a/app/src/main/java/com/gotcha/tools/DeviceAdminTool.kt+++ b/app/src/main/java/com/gotcha/tools/DeviceAdminTool.kt@@ -51,8 +51,11 @@ class DeviceAdminTool(private val context: Context) {val sufficient = dpm.isActivePasswordSufficientToolResult.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."+ 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}")diff --git a/app/src/main/java/com/gotcha/tools/DeviceTool.kt b/app/src/main/java/com/gotcha/tools/DeviceTool.ktindex da460ed..058dc3a 100644--- a/app/src/main/java/com/gotcha/tools/DeviceTool.kt+++ b/app/src/main/java/com/gotcha/tools/DeviceTool.kt@@ -63,8 +63,8 @@ class DeviceTool(private val context: Context) {val target = (percent * max) / 100val flags = if (showUi) AudioManager.FLAG_SHOW_UI else 0am.setStreamVolume(streamType, target, flags)- ToolResult.ok("Set $stream volume from ${previousPct}% to ${percent}%.")- } catch (e: SecurityException) {+ ToolResult.ok("Set $stream volume from $previousPct% to $percent%.")+ } catch (_: SecurityException) {ToolResult.permissionNeeded(ToolResult.DND_ACCESS,"Changing this volume needs Do Not Disturb access. I have opened that settings page — please enable it and ask again."@@ -78,8 +78,11 @@ class DeviceTool(private val context: Context) {fun getVolume(stream: String?): ToolResult {return try {val am = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager- val streams = if (stream != null) listOf(stream.lowercase().trim()) else+ val streams = if (stream != null) {+ listOf(stream.lowercase().trim())+ } else {listOf("media", "ring", "alarm", "notification", "call")+ }val results = streams.map { name ->val type = when (name) {"media", "music" -> AudioManager.STREAM_MUSIC@@ -87,12 +90,14 @@ class DeviceTool(private val context: Context) {"alarm" -> AudioManager.STREAM_ALARM"notification" -> AudioManager.STREAM_NOTIFICATION"call", "voice" -> AudioManager.STREAM_VOICE_CALL- else -> return ToolResult.error("Unknown stream '$name'. Use media, ring, alarm, notification, or call.")+ else -> return ToolResult.error(+ "Unknown stream '$name'. Use media, ring, alarm, notification, or call."+ )}val max = am.getStreamMaxVolume(type)val current = am.getStreamVolume(type)val pct = (current * 100) / max- "$name: ${pct}%"+ "$name: $pct%"}ToolResult.ok(results.joinToString("\n"))} catch (e: Exception) {@@ -118,7 +123,7 @@ class DeviceTool(private val context: Context) {val am = context.getSystemService(Context.AUDIO_SERVICE) as AudioManageram.ringerMode = ringerModeToolResult.ok("Ringer set to ${mode.lowercase().trim()}.")- } catch (e: SecurityException) {+ } catch (_: SecurityException) {ToolResult.permissionNeeded(ToolResult.DND_ACCESS,"Changing the ringer needs Do Not Disturb access. I have opened that settings page — please enable it and ask again."@@ -136,8 +141,11 @@ class DeviceTool(private val context: Context) {patternEffect(pattern.lowercase().trim(), amplitude)} else {val ms = durationMs.coerceIn(1, 5000).toLong()- if (amplitude == 0) VibrationEffect.createOneShot(ms, VibrationEffect.DEFAULT_AMPLITUDE)- else VibrationEffect.createOneShot(ms, amplitude)+ if (amplitude == 0) {+ VibrationEffect.createOneShot(ms, VibrationEffect.DEFAULT_AMPLITUDE)+ } else {+ VibrationEffect.createOneShot(ms, amplitude)+ }}return try {vibrator.vibrate(effect)@@ -182,14 +190,18 @@ class DeviceTool(private val context: Context) {if (!hasDndAccess()) {return ToolResult.permissionNeeded(ToolResult.DND_ACCESS,- "Do Not Disturb control needs notification-policy access. I have opened that settings page — please enable it and ask again."+ "Do Not Disturb control needs notification-policy access. " ++ "I have opened that settings page — please enable it and ask again.")}return try {val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManagernm.setInterruptionFilter(- if (enabled) NotificationManager.INTERRUPTION_FILTER_PRIORITY- else NotificationManager.INTERRUPTION_FILTER_ALL+ if (enabled) {+ NotificationManager.INTERRUPTION_FILTER_PRIORITY+ } else {+ NotificationManager.INTERRUPTION_FILTER_ALL+ })ToolResult.ok("Do Not Disturb turned ${if (enabled) "on" else "off"}.")} catch (e: Exception) {diff --git a/app/src/main/java/com/gotcha/tools/EditTool.kt b/app/src/main/java/com/gotcha/tools/EditTool.ktindex a69f8a1..d16ef76 100644--- a/app/src/main/java/com/gotcha/tools/EditTool.kt+++ b/app/src/main/java/com/gotcha/tools/EditTool.kt@@ -1,7 +1,6 @@package com.gotcha.toolsimport android.content.Context-import java.io.File/*** Surgical text replacement tool — replaces exact text in a file.@@ -29,26 +28,38 @@ class EditTool(private val context: Context) {val file = resolved.fileval perm = resolver.checkWritePermission(file)if (perm != null) return perm- if (!file.exists()) return ToolResult.error("File '$path' does not exist (resolved: ${file.canonicalPath}).")+ if (!file.exists()) {+ return ToolResult.error(+ "File '$path' does not exist (resolved: ${file.canonicalPath})."+ )+ }if (!file.isFile) return ToolResult.error("'$path' is not a regular file.")if (file.length() > MAX_FILE_BYTES) return ToolResult.error("File too large to edit (max 1 MB).")try {val content = file.readText(Charsets.UTF_8)- val count = if (replaceAll) content.split(oldString).size - 1- else if (content.contains(oldString)) 1 else 0+ val count = if (replaceAll) {+ content.split(oldString).size - 1+ } else if (content.contains(oldString)) 1 else 0if (count == 0) {- return ToolResult.error("No match found for the specified text in '$path'. " +- "The text must match exactly, including whitespace and indentation.")+ return ToolResult.error(+ "No match found for the specified text in '$path'. " ++ "The text must match exactly, including whitespace and indentation."+ )}if (count > 1 && !replaceAll) {- return ToolResult.error("Found $count matches in '$path'. " +- "Provide more surrounding context or use replaceAll=true.")+ return ToolResult.error(+ "Found $count matches in '$path'. " ++ "Provide more surrounding context or use replaceAll=true."+ )}- val newContent = if (replaceAll) content.replace(oldString, newString)- else content.replaceFirst(oldString, newString)+ val newContent = if (replaceAll) {+ content.replace(oldString, newString)+ } else {+ content.replaceFirst(oldString, newString)+ }file.writeText(newContent, Charsets.UTF_8)val verb = if (replaceAll) "Replaced $count occurrences" else "Replaced 1 occurrence"diff --git a/app/src/main/java/com/gotcha/tools/FileResolver.kt b/app/src/main/java/com/gotcha/tools/FileResolver.ktindex 49e1772..7593aa7 100644--- a/app/src/main/java/com/gotcha/tools/FileResolver.kt+++ b/app/src/main/java/com/gotcha/tools/FileResolver.kt@@ -24,17 +24,19 @@ import java.io.Fileclass FileResolver(private val context: Context) {companion object {+ const val IMAGE_DATA_PREFIX = "IMAGE_DATA:"+private const val ALL_FILES_ACCESS_GUIDE ="This operation needs \"All files access\" to read or write outside the app sandbox. " +- "Go to Settings → Permissions → All Files Access and enable it, then ask again."+ "Go to Settings → Permissions → All Files Access and enable it, then ask again."private const val READ_STORAGE_GUIDE ="This operation needs storage read permission. " +- "Go to Settings → Permissions → Storage Read and grant it, then ask again."+ "Go to Settings → Permissions → Storage Read and grant it, then ask again."private const val WRITE_STORAGE_GUIDE ="This operation needs storage write permission. " +- "Go to Settings → Permissions → Storage Write and grant it, then ask again."+ "Go to Settings → Permissions → Storage Write and grant it, then ask again."var WORKING_DIR_BASE: String = "/storage/emulated/0/Gotcha"@@ -71,22 +73,27 @@ class FileResolver(private val context: Context) {return when {// API 30+: need MANAGE_EXTERNAL_STORAGE for broad shared-storage readBuild.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager() -> {- if (isBelowExternalStorage(canonical))+ if (isBelowExternalStorage(canonical)) {ResolveResult.PermissionNeeded(ToolResult.permissionNeeded(ToolResult.ALL_FILES_ACCESS, ALL_FILES_ACCESS_GUIDE))- else ResolveResult.Ok(File(canonical))+ } else {+ ResolveResult.Ok(File(canonical))+ }}// API 23-29: need READ_EXTERNAL_STORAGE for shared-storage readBuild.VERSION.SDK_INT in 23..29 -> {val has = hasPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)- if (!has && isBelowExternalStorage(canonical))+ if (!has && isBelowExternalStorage(canonical)) {ResolveResult.PermissionNeeded(ToolResult.permissionNeeded(- android.Manifest.permission.READ_EXTERNAL_STORAGE, READ_STORAGE_GUIDE+ android.Manifest.permission.READ_EXTERNAL_STORAGE,+ READ_STORAGE_GUIDE))- else ResolveResult.Ok(File(canonical))+ } else {+ ResolveResult.Ok(File(canonical))+ }}else -> ResolveResult.Ok(File(canonical))}@@ -105,13 +112,16 @@ class FileResolver(private val context: Context) {// API 23-29: need WRITE_EXTERNAL_STORAGE for shared-storage writeBuild.VERSION.SDK_INT in 23..29 -> {val has = hasPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)- if (!has && isBelowExternalStorage(canonical))+ if (!has && isBelowExternalStorage(canonical)) {ResolveResult.PermissionNeeded(ToolResult.permissionNeeded(- android.Manifest.permission.WRITE_EXTERNAL_STORAGE, WRITE_STORAGE_GUIDE+ android.Manifest.permission.WRITE_EXTERNAL_STORAGE,+ WRITE_STORAGE_GUIDE))- else ResolveResult.Ok(File(canonical))+ } else {+ ResolveResult.Ok(File(canonical))+ }}else -> ResolveResult.Ok(File(canonical))}@@ -121,8 +131,9 @@ class FileResolver(private val context: Context) {val canonical = file.canonicalPathif (isInAppSandbox(canonical)) return nullif (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) {- if (isBelowExternalStorage(canonical))+ if (isBelowExternalStorage(canonical)) {return ToolResult.permissionNeeded(ToolResult.ALL_FILES_ACCESS, ALL_FILES_ACCESS_GUIDE)+ }}if (Build.VERSION.SDK_INT in 23..29 && isBelowExternalStorage(canonical)) {val perm = android.Manifest.permission.READ_EXTERNAL_STORAGE@@ -146,29 +157,41 @@ class FileResolver(private val context: Context) {fun formatSize(bytes: Long): String = formatSizeStatic(bytes)+ /** A magic-byte signature: minimum file size, required prefix bytes, resulting MIME type. */+ private class MagicSignature(val minSize: Int, val prefix: ByteArray, val mime: String)++ private val magicSignatures = listOf(+ MagicSignature(8, byteArrayOf(0x89.toByte(), 0x50, 0x4E, 0x47), "image/png"),+ MagicSignature(3, byteArrayOf(0xFF.toByte(), 0xD8.toByte(), 0xFF.toByte()), "image/jpeg"),+ MagicSignature(3, byteArrayOf(0x47, 0x49, 0x46), "image/gif"),+ MagicSignature(2, byteArrayOf(0x42, 0x4D), "image/bmp"),+ MagicSignature(5, byteArrayOf(0x25, 0x50, 0x44, 0x46, 0x2D), "application/pdf"),+ MagicSignature(4, byteArrayOf(0x50, 0x4B, 0x03, 0x04), "application/zip"),+ MagicSignature(28, byteArrayOf(0x52, 0x61, 0x72, 0x21, 0x1A), "application/x-rar-compressed"),+ MagicSignature(3, byteArrayOf(0x1F, 0x8B.toByte(), 0x08), "application/gzip"),+ MagicSignature(4, byteArrayOf(0x2E, 0x73, 0x6E, 0x64), "audio/basic"),+ MagicSignature(4, byteArrayOf(0x4D, 0x54, 0x68, 0x64), "audio/midi"),+ MagicSignature(4, byteArrayOf(0x66, 0x74, 0x79, 0x70), "video/mp4")+ )+fun detectMime(bytes: ByteArray): String? {- if (bytes.size >= 8 && bytes[0] == 0x89.toByte() && bytes[1] == 0x50.toByte() && bytes[2] == 0x4E.toByte() && bytes[3] == 0x47.toByte()) return "image/png"- if (bytes.size >= 3 && bytes[0] == 0xFF.toByte() && bytes[1] == 0xD8.toByte() && bytes[2] == 0xFF.toByte()) return "image/jpeg"- if (bytes.size >= 3 && bytes[0] == 0x47.toByte() && bytes[1] == 0x49.toByte() && bytes[2] == 0x46.toByte()) return "image/gif"- if (bytes.size >= 2 && bytes[0] == 0x42.toByte() && bytes[1] == 0x4D.toByte()) return "image/bmp"- if (bytes.size >= 12 && startsWith(bytes.copyOfRange(0,4), byteArrayOf(0x52,0x49,0x46,0x46)) &&- startsWith(bytes.copyOfRange(8,12), byteArrayOf(0x57,0x45,0x42,0x50))) return "image/webp"- if (bytes.size >= 5 && bytes[0] == 0x25.toByte() && bytes[1] == 0x50.toByte() && bytes[2] == 0x44.toByte() && bytes[3] == 0x46.toByte() && bytes[4] == 0x2D.toByte()) return "application/pdf"- if (bytes.size >= 4 && startsWith(bytes.copyOfRange(0,4), byteArrayOf(0x50,0x4B,0x03,0x04))) return "application/zip"- if (bytes.size >= 28 && startsWith(bytes.copyOfRange(0,5), byteArrayOf(0x52,0x61,0x72,0x21,0x1A))) return "application/x-rar-compressed"- if (bytes.size >= 3 && startsWith(bytes.copyOfRange(0,3), byteArrayOf(0x1F.toByte(), 0x8B.toByte(), 0x08.toByte()))) return "application/gzip"- if (bytes.size >= 4 && startsWith(bytes.copyOfRange(0,4), byteArrayOf(0x2E,0x73,0x6E,0x64))) return "audio/basic"- if (bytes.size >= 4 && bytes[0] == 0x4D.toByte() && bytes[1] == 0x54.toByte() && bytes[2] == 0x68.toByte() && bytes[3] == 0x64.toByte()) return "audio/midi"- if (bytes.size >= 4 && startsWith(bytes.copyOfRange(0,4), byteArrayOf(0x66,0x74,0x79,0x70))) return "video/mp4"- return null+ // webp needs a two-part check: RIFF header plus WEBP tag at offset 8.+ if (bytes.size >= 12 && startsWith(bytes, byteArrayOf(0x52, 0x49, 0x46, 0x46)) &&+ startsWith(bytes.copyOfRange(8, 12), byteArrayOf(0x57, 0x45, 0x42, 0x50))+ ) {+ return "image/webp"+ }+ return magicSignatures+ .firstOrNull { bytes.size >= it.minSize && startsWith(bytes, it.prefix) }+ ?.mime}fun isImageMime(mime: String): Boolean = mime.startsWith("image/")- fun isArchiveMime(mime: String): Boolean = mime == "application/zip" || mime == "application/x-rar-compressed" || mime == "application/gzip"+ fun isArchiveMime(+ mime: String+ ): Boolean = mime == "application/zip" || mime == "application/x-rar-compressed" || mime == "application/gzip"fun isDocumentMime(mime: String): Boolean = mime == "application/pdf"- val IMAGE_DATA_PREFIX = "IMAGE_DATA:"-private fun hasPermission(permission: String): Boolean =ContextCompat.checkSelfPermission(context, permission) ==android.content.pm.PackageManager.PERMISSION_GRANTEDdiff --git a/app/src/main/java/com/gotcha/tools/FileTool.kt b/app/src/main/java/com/gotcha/tools/FileTool.ktindex b18b8d4..9cfb3c7 100644--- a/app/src/main/java/com/gotcha/tools/FileTool.kt+++ b/app/src/main/java/com/gotcha/tools/FileTool.kt@@ -4,7 +4,6 @@ import android.content.Contextimport android.graphics.BitmapFactoryimport android.util.Base64import java.io.File-import java.util.zip.ZipEntryimport java.util.zip.ZipFile/**@@ -47,8 +46,14 @@ class FileTool(private val context: Context) {private val OFFICE_EXTENSIONS = setOf("docx", "xlsx", "pptx")private val ARCHIVE_DELIMITERS = setOf(- ".zip/", ".apk/", ".aar/", ".jar/", ".war/",- ".docx/", ".xlsx/", ".pptx/"+ ".zip/",+ ".apk/",+ ".aar/",+ ".jar/",+ ".war/",+ ".docx/",+ ".xlsx/",+ ".pptx/")}@@ -89,10 +94,14 @@ class FileTool(private val context: Context) {ext in ARCHIVE_EXTENSIONS -> listArchiveContents(file)ext in OFFICE_EXTENSIONS -> {val list = listArchiveContents(file)- if (list.success) ToolResult.ok(- "Office document detected (${file.name}). It is a ZIP archive containing:\n" +- list.message + "\nUse read_file on a specific entry, e.g. '${originalPath}/word/document.xml' for .docx."- ) else list+ if (list.success) {+ ToolResult.ok(+ "Office document detected (${file.name}). It is a ZIP archive containing:\n" ++ list.message + "\nUse read_file on a specific entry, e.g. '$originalPath/word/document.xml' for .docx."+ )+ } else {+ list+ }}ext in TEXT_EXTENSIONS -> readTextFile(file, offset, limit, encoding)else -> readUnknownFile(file, encoding)@@ -119,9 +128,11 @@ class FileTool(private val context: Context) {var byteCount = 0for ((i, line) in selected.withIndex()) {val lineNum = startLine + i- val display = if (line.length > MAX_LINE_LENGTH)+ val display = if (line.length > MAX_LINE_LENGTH) {line.take(MAX_LINE_LENGTH) + "…(line truncated)"- else line+ } else {+ line+ }val next = if (i > 0 || offset != null) "$lineNum: $display\n" else "$display\n"if (byteCount + next.length > MAX_TEXT_BYTES && byteCount > 0) {sb.append("…(output capped at ${MAX_TEXT_BYTES / 1024} KB)")@@ -137,12 +148,16 @@ class FileTool(private val context: Context) {append(result)if (truncated || capReached) {append("\n")- if (truncated) append("(Showing lines $startLine-$endLine of ${lines.size}. Use offset=${endLine + 1} to continue.)")+ if (truncated) {+ append(+ "(Showing lines $startLine-$endLine of ${lines.size}. Use offset=${endLine + 1} to continue.)"+ )+ }if (capReached) append(" (Output capped at ${MAX_TEXT_BYTES / 1024} KB.)")}}ToolResult.ok(summary.ifEmpty { "(empty file)" })- } catch (e: java.nio.charset.UnsupportedCharsetException) {+ } catch (_: java.nio.charset.UnsupportedCharsetException) {ToolResult.error("Unsupported encoding '$enc'. Try UTF-8, ISO-8859-1, or UTF-16.")} catch (e: Exception) {ToolResult.error("Could not read '${file.name}': ${e.message}")@@ -151,21 +166,25 @@ class FileTool(private val context: Context) {private fun readImageFile(file: File): ToolResult {if (file.length() > MAX_IMAGE_BYTES) {- return ToolResult.error("Image too large (${resolver.formatSize(file.length())}). Max: ${MAX_IMAGE_BYTES / 1024 / 1024} MB.")+ return ToolResult.error(+ "Image too large (${resolver.formatSize(file.length())}). Max: ${MAX_IMAGE_BYTES / 1024 / 1024} MB."+ )}return try {val bytes = file.readBytes()val mime = resolver.detectMime(bytes)- if (mime == null || !resolver.isImageMime(mime))+ if (mime == null || !resolver.isImageMime(mime)) {return ToolResult.error("File '${file.name}' is not a recognized image format.")+ }val opts = BitmapFactory.Options().apply { inJustDecodeBounds = true }BitmapFactory.decodeByteArray(bytes, 0, bytes.size, opts)- if (opts.outWidth <= 0 || opts.outHeight <= 0)+ if (opts.outWidth <= 0 || opts.outHeight <= 0) {return ToolResult.error("File '${file.name}' could not be decoded as an image.")+ }val base64 = Base64.encodeToString(bytes, Base64.NO_WRAP)val displayName = file.nameToolResult.ok(- "${resolver.IMAGE_DATA_PREFIX}$mime:${opts.outWidth}x${opts.outHeight}:${bytes.size}:$displayName:$base64"+ "${FileResolver.IMAGE_DATA_PREFIX}$mime:${opts.outWidth}x${opts.outHeight}:${bytes.size}:$displayName:$base64")} catch (e: Exception) {ToolResult.error("Could not read image '${file.name}': ${e.message}")@@ -174,7 +193,9 @@ class FileTool(private val context: Context) {private fun readFileBase64(file: File, mime: String): ToolResult {if (file.length() > MAX_BINARY_BYTES) {- return ToolResult.error("File too large (${resolver.formatSize(file.length())}). Max: ${MAX_BINARY_BYTES / 1024 / 1024} MB.")+ return ToolResult.error(+ "File too large (${resolver.formatSize(file.length())}). Max: ${MAX_BINARY_BYTES / 1024 / 1024} MB."+ )}return try {val bytes = file.readBytes()@@ -186,11 +207,26 @@ class FileTool(private val context: Context) {}private fun readUnknownFile(file: File, encoding: String?): ToolResult {- val sample = try { file.inputStream().use { it.readNBytes(512) } } catch (_: Exception) { ByteArray(0) }+ // InputStream.readNBytes needs API 33; read up to 512 bytes manually (minSdk 26).+ val sample = try {+ file.inputStream().use { stream ->+ val buf = ByteArray(512)+ var total = 0+ while (total < buf.size) {+ val n = stream.read(buf, total, buf.size - total)+ if (n < 0) break+ total += n+ }+ buf.copyOf(total)+ }+ } catch (_: Exception) {+ ByteArray(0)+ }if (sample.isEmpty()) return readTextFile(file, null, 200, encoding)val nullRatio = sample.count { it.toInt() == 0 }.toFloat() / sample.sizeval nonprintableRatio = sample.count {- val v = it.toInt() and 0xFF; v < 32 && v != 9 && v != 10 && v != 13+ val v = it.toInt() and 0xFF+ v < 32 && v != 9 && v != 10 && v != 13}.toFloat() / sample.sizeval mime = resolver.detectMime(sample)if (mime != null && resolver.isImageMime(mime)) return readImageFile(file)@@ -214,7 +250,11 @@ class FileTool(private val context: Context) {if (entries.isEmpty()) return ToolResult.ok("Archive '${file.name}' is empty.")val totalSize = entries.sumOf { it.size.coerceAtLeast(0) }val sb = StringBuilder()- sb.appendLine("Archive: ${file.name} (${resolver.formatSize(file.length())}, ${entries.size} entries, ${resolver.formatSize(totalSize)} uncompressed)")+ sb.appendLine(+ "Archive: ${file.name} (${resolver.formatSize(+ file.length()+ )}, ${entries.size} entries, ${resolver.formatSize(totalSize)} uncompressed)"+ )for (e in entries.take(200)) {val flag = if (e.isDirectory) "/" else ""val size = if (e.size > 0) " ${resolver.formatSize(e.size)}" else ""@@ -255,9 +295,11 @@ class FileTool(private val context: Context) {if (entry == null) {val siblings = zf.entries().asSequence().map { it?.name ?: "" }.toList()val matching = siblings.filter { it.contains(entryPath, ignoreCase = true) }.take(5)- val hint = if (matching.isNotEmpty())+ val hint = if (matching.isNotEmpty()) {" Did you mean one of: ${matching.joinToString(", ")}?"- else ""+ } else {+ ""+ }return ToolResult.error("Entry '$entryPath' not found in '${archiveFile.name}'.$hint")}if (entry.isDirectory) {@@ -275,7 +317,7 @@ class FileTool(private val context: Context) {BitmapFactory.decodeByteArray(bytes, 0, bytes.size, opts)val dims = if (opts.outWidth > 0) "${opts.outWidth}x${opts.outHeight}" else "unknown"val base64 = Base64.encodeToString(bytes, Base64.NO_WRAP)- return ToolResult.ok("${resolver.IMAGE_DATA_PREFIX}$mime:$dims:${bytes.size}:$entryPath:$base64")+ return ToolResult.ok("${FileResolver.IMAGE_DATA_PREFIX}$mime:$dims:${bytes.size}:$entryPath:$base64")}if (ext in TEXT_EXTENSIONS || resolver.detectMime(bytes) == null) {val text = String(bytes, Charsets.UTF_8)@@ -316,11 +358,19 @@ class FileTool(private val context: Context) {if (binary) {val bytes = Base64.decode(content, Base64.NO_WRAP)if (append) file.appendBytes(bytes) else file.writeBytes(bytes)- ToolResult.ok("Wrote ${resolver.formatSize(bytes.size.toLong())} binary data to '$originalPath' (resolved: ${file.canonicalPath}).")+ ToolResult.ok(+ "Wrote ${resolver.formatSize(+ bytes.size.toLong()+ )} binary data to '$originalPath' (resolved: ${file.canonicalPath})."+ )} else {val bytes = content.toByteArray(Charsets.UTF_8)if (append) file.appendBytes(bytes) else file.writeBytes(bytes)- ToolResult.ok("${if (append) "Appended" else "Wrote"} ${resolver.formatSize(bytes.size.toLong())} to '$originalPath' (resolved: ${file.canonicalPath}).")+ ToolResult.ok(+ "${if (append) "Appended" else "Wrote"} ${resolver.formatSize(+ bytes.size.toLong()+ )} to '$originalPath' (resolved: ${file.canonicalPath})."+ )}} catch (e: Exception) {ToolResult.error("Could not write '$originalPath': ${e.message}")@@ -340,11 +390,18 @@ class FileTool(private val context: Context) {is FileResolver.ResolveResult.PermissionNeeded -> resolved.resultis FileResolver.ResolveResult.Error -> ToolResult.error(resolved.message)is FileResolver.ResolveResult.Ok -> listResolved(- resolved.file, path, sortBy, include, exclude, recursive, maxDepth+ resolved.file,+ path,+ sortBy,+ include,+ exclude,+ recursive,+ maxDepth)}}+ @Suppress("CyclomaticComplexMethod")private fun listResolved(file: File,originalPath: String,@@ -354,9 +411,15 @@ class FileTool(private val context: Context) {recursive: Boolean,maxDepth: Int?): ToolResult {- if (!file.exists()) return ToolResult.error("Path '$originalPath' does not exist (resolved: ${file.canonicalPath}).")+ if (!file.exists()) {+ return ToolResult.error(+ "Path '$originalPath' does not exist (resolved: ${file.canonicalPath})."+ )+ }if (!file.isDirectory) {- return ToolResult.ok("${file.name} (${resolver.formatSize(file.length())})\nResolved: ${file.canonicalPath}")+ return ToolResult.ok(+ "${file.name} (${resolver.formatSize(file.length())})\nResolved: ${file.canonicalPath}"+ )}val perm = resolver.checkReadPermission(file)if (perm != null) return perm@@ -367,13 +430,18 @@ class FileTool(private val context: Context) {fun walk(dir: File, depth: Int) {if (aborted || depth > depthLimit) return- val entries = dir.listFiles()?.sortedWith(when (sortBy?.lowercase()) {- "date" -> compareBy<File> { it.lastModified() }- "size" -> compareBy<File> { it.length() }- else -> compareBy { it.name.lowercase() }- }) ?: return+ val entries = dir.listFiles()?.sortedWith(+ when (sortBy?.lowercase()) {+ "date" -> compareBy<File> { it.lastModified() }+ "size" -> compareBy<File> { it.length() }+ else -> compareBy { it.name.lowercase() }+ }+ ) ?: returnfor (entry in entries) {- if (results.size >= MAX_LIST_ENTRIES) { aborted = true; return }+ if (results.size >= MAX_LIST_ENTRIES) {+ aborted = true+ return+ }val relPath = if (depth == 0) entry.name else entry.absolutePathval name = entry.name.lowercase()if (include != null && !name.contains(include.lowercase())) continue@@ -422,10 +490,10 @@ class FileTool(private val context: Context) {val readable = if (f.canRead()) "readable" else "not readable"ToolResult.ok("Path: ${f.canonicalPath}\n" +- "Type: $type\n" +- "Size: $size\n" +- "Modified: $modified\n" +- "Permissions: $readable$executable"+ "Type: $type\n" ++ "Size: $size\n" ++ "Modified: $modified\n" ++ "Permissions: $readable$executable")}}diff --git a/app/src/main/java/com/gotcha/tools/GlobTool.kt b/app/src/main/java/com/gotcha/tools/GlobTool.ktindex 8b4723f..6e073d2 100644--- a/app/src/main/java/com/gotcha/tools/GlobTool.kt+++ b/app/src/main/java/com/gotcha/tools/GlobTool.kt@@ -42,7 +42,10 @@ class GlobTool(private val context: Context) {val entries = dir.listFiles() ?: returnfor (file in entries.sortedBy { it.name.lowercase() }) {if (aborted) return- if (results.size >= MAX_RESULTS) { aborted = true; return }+ if (results.size >= MAX_RESULTS) {+ aborted = true+ return+ }val relPath = file.absolutePath.removePrefix(root.absolutePath).trimStart('/')if (regex.matches(relPath)) {@@ -53,8 +56,9 @@ class GlobTool(private val context: Context) {}}- if (root.isDirectory) walk(root, 0)- else {+ if (root.isDirectory) {+ walk(root, 0)+ } else {if (regex.matches(root.name)) results.add(root.absolutePath)}@@ -62,8 +66,10 @@ class GlobTool(private val context: Context) {return ToolResult.ok("No files matching '$pattern' found in '$path'.")}val truncated = if (aborted) "\n…(truncated, max $MAX_RESULTS results)" else ""- return ToolResult.ok("${results.size} file(s) matching '$pattern' in '$path':\n" +- results.joinToString("\n") + truncated)+ return ToolResult.ok(+ "${results.size} file(s) matching '$pattern' in '$path':\n" ++ results.joinToString("\n") + truncated+ )}}}@@ -84,8 +90,14 @@ class GlobTool(private val context: Context) {i++}}- '?' -> { sb.append('.'); i++ }- '.' -> { sb.append("\\."); i++ }+ '?' -> {+ sb.append('.')+ i+++ }+ '.' -> {+ sb.append("\\.")+ i+++ }'{' -> {val end = glob.indexOf('}', i)if (end > i) {@@ -94,9 +106,15 @@ class GlobTool(private val context: Context) {sb.append(parts.joinToString("|") { Regex.escape(it) })sb.append(')')i = end + 1- } else { sb.append(c); i++ }+ } else {+ sb.append(c)+ i+++ }+ }+ else -> {+ sb.append(Regex.escape(c.toString()))+ i++}- else -> { sb.append(Regex.escape(c.toString())); i++ }}}return try {diff --git a/app/src/main/java/com/gotcha/tools/GrepTool.kt b/app/src/main/java/com/gotcha/tools/GrepTool.ktindex 2e721c0..2013163 100644--- a/app/src/main/java/com/gotcha/tools/GrepTool.kt+++ b/app/src/main/java/com/gotcha/tools/GrepTool.kt@@ -18,6 +18,7 @@ class GrepTool(private val context: Context) {private const val MAX_FILE_BYTES = 1024 * 1024}+ @Suppress("CyclomaticComplexMethod", "NestedBlockDepth", "LoopWithTooManyJumpStatements")fun grep(path: String, pattern: String, include: String?): ToolResult {if (pattern.isBlank()) return ToolResult.error("Search pattern cannot be empty.")val regex = try {@@ -52,8 +53,14 @@ class GrepTool(private val context: Context) {val entries = dir.listFiles() ?: returnfor (file in entries.sortedBy { it.name.lowercase() }) {if (aborted) return- if (filesSearched >= MAX_FILES) { aborted = true; return }- if (file.isDirectory) { walk(file, depth + 1); continue }+ if (filesSearched >= MAX_FILES) {+ aborted = true+ return+ }+ if (file.isDirectory) {+ walk(file, depth + 1)+ continue+ }if (!file.isFile) continueif (includeGlob != null && !includeGlob.matches(file.name)) continueif (file.length() > MAX_FILE_BYTES) continue@@ -67,15 +74,19 @@ class GrepTool(private val context: Context) {matchCount++val display = line.take(200).replace("\t", " ").trim()results.add("${file.absolutePath}:${idx + 1}: $display")- if (matchCount >= MAX_MATCHES) { aborted = true; return }+ if (matchCount >= MAX_MATCHES) {+ aborted = true+ return+ }}}} catch (_: Exception) { }}}- if (root.isDirectory) walk(root, 0)- else if (root.isFile) {+ if (root.isDirectory) {+ walk(root, 0)+ } else if (root.isFile) {if (includeGlob == null || includeGlob.matches(root.name)) {if (root.length() <= MAX_FILE_BYTES) {filesSearched = 1@@ -99,10 +110,14 @@ class GrepTool(private val context: Context) {} else {val truncated = if (matchCount >= MAX_MATCHES || filesSearched >= MAX_FILES) {"\n…(truncated, max $MAX_MATCHES matches)"- } else ""+ } else {+ ""+ }val summary = if (filesSearched > 1) " (searched $filesSearched files)" else ""- ToolResult.ok("Found ${results.size} match(es) for '$pattern' in '$path'$summary:\n" +- results.joinToString("\n") + truncated)+ ToolResult.ok(+ "Found ${results.size} match(es) for '$pattern' in '$path'$summary:\n" ++ results.joinToString("\n") + truncated+ )}}}diff --git a/app/src/main/java/com/gotcha/tools/LocationTool.kt b/app/src/main/java/com/gotcha/tools/LocationTool.ktindex ecadfc1..528b8fe 100644--- a/app/src/main/java/com/gotcha/tools/LocationTool.kt+++ b/app/src/main/java/com/gotcha/tools/LocationTool.kt@@ -58,7 +58,14 @@ class LocationTool(private val context: Context) {ToolResult.ok("Location: %.5f, %.5f%s%s%s%s%s%s\nMap: $mapLink".format(- lat, lng, accuracy, altitude, bearing, speed, where, source+ lat,+ lng,+ accuracy,+ altitude,+ bearing,+ speed,+ where,+ source))} catch (e: Exception) {@@ -107,7 +114,11 @@ class LocationTool(private val context: Context) {override fun onProviderDisabled(provider: String) {}}- lm.requestSingleUpdate(provider, listener, Looper.getMainLooper())+ try {+ lm.requestSingleUpdate(provider, listener, Looper.getMainLooper())+ } catch (_: SecurityException) {+ return null+ }latch.await(8, TimeUnit.SECONDS)try { lm.removeUpdates(listener) } catch (_: Exception) {}diff --git a/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt b/app/src/main/java/com/gotcha/tools/MediaCaptureTool.ktindex cbd3ee7..924259b 100644--- a/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt+++ b/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt@@ -24,7 +24,10 @@ import kotlin.coroutines.resumeclass MediaCaptureTool(private val context: Context) {- private val TAG = "Gotcha"+ private companion object {+ const val TAG = "Gotcha"+ }+private var recorder: MediaRecorder? = nullprivate var recordingFile: File? = nullprivate var recordingStartTime: Long = 0L@@ -112,8 +115,11 @@ class MediaCaptureTool(private val context: Context) {}return try {val file = if (!outputPath.isNullOrBlank()) {- val resolved = if (outputPath.startsWith("/")) outputPath- else File(FileResolver.WORKING_DIR_BASE, outputPath).absolutePath+ val resolved = if (outputPath.startsWith("/")) {+ outputPath+ } else {+ File(FileResolver.WORKING_DIR_BASE, outputPath).absolutePath+ }File(resolved).also { it.parentFile?.mkdirs() }} else {val dir = File(FileResolver.WORKING_DIR_BASE, "Recordings")@@ -138,9 +144,18 @@ class MediaCaptureTool(private val context: Context) {rec.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)when (quality?.trim()?.lowercase()) {- "low" -> { rec.setAudioSamplingRate(16000); rec.setAudioEncodingBitRate(16000) }- "medium" -> { rec.setAudioSamplingRate(44100); rec.setAudioEncodingBitRate(64000) }- "high" -> { rec.setAudioSamplingRate(44100); rec.setAudioEncodingBitRate(192000) }+ "low" -> {+ rec.setAudioSamplingRate(16000)+ rec.setAudioEncodingBitRate(16000)+ }+ "medium" -> {+ rec.setAudioSamplingRate(44100)+ rec.setAudioEncodingBitRate(64000)+ }+ "high" -> {+ rec.setAudioSamplingRate(44100)+ rec.setAudioEncodingBitRate(192000)+ }}if (maxDurationSeconds != null && maxDurationSeconds > 0) {diff --git a/app/src/main/java/com/gotcha/tools/NotificationTool.kt b/app/src/main/java/com/gotcha/tools/NotificationTool.ktindex 77f4ff1..b20aa63 100644--- a/app/src/main/java/com/gotcha/tools/NotificationTool.kt+++ b/app/src/main/java/com/gotcha/tools/NotificationTool.kt@@ -75,7 +75,7 @@ class NotificationTool(private val context: Context) {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) {+ } catch (_: SecurityException) {notEnabled()} catch (e: Exception) {ToolResult.error("Could not control media: ${e.message}")diff --git a/app/src/main/java/com/gotcha/tools/OverlayTool.kt b/app/src/main/java/com/gotcha/tools/OverlayTool.ktindex 83620aa..50a52ec 100644--- a/app/src/main/java/com/gotcha/tools/OverlayTool.kt+++ b/app/src/main/java/com/gotcha/tools/OverlayTool.kt@@ -48,8 +48,11 @@ class OverlayTool(private val context: Context) {}}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."+ if (duration > 0) {+ "Showing an overlay for ${duration / 1000}s: \"$text\"."+ } else {+ "Showing a persistent overlay: \"$text\". Call hide_overlay to remove it."+ })}diff --git a/app/src/main/java/com/gotcha/tools/PhoneTool.kt b/app/src/main/java/com/gotcha/tools/PhoneTool.ktindex 126e13d..1c00525 100644--- a/app/src/main/java/com/gotcha/tools/PhoneTool.kt+++ b/app/src/main/java/com/gotcha/tools/PhoneTool.kt@@ -79,7 +79,7 @@ class PhoneTool(private val context: Context) {if (simSlot != null) extras.add("Using $simSlot.")val extra = if (extras.isNotEmpty()) " ${extras.joinToString(" ")}" else ""ToolResult.ok("Calling $trimmed.$extra")- } catch (e: SecurityException) {+ } catch (_: SecurityException) {ToolResult.permissionNeeded(Manifest.permission.CALL_PHONE,"The Phone permission is not granted. Go to Settings → Permissions → Phone and enable it, then ask again."@@ -90,6 +90,11 @@ class PhoneTool(private val context: Context) {}private fun resolveSubId(simSlot: String): Int? {+ val phoneStateGranted = ContextCompat.checkSelfPermission(+ context,+ Manifest.permission.READ_PHONE_STATE+ ) == PackageManager.PERMISSION_GRANTED+ if (!phoneStateGranted) return nullreturn try {val subs = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {context.getSystemService(SubscriptionManager::class.java)?.activeSubscriptionInfoList@@ -105,6 +110,7 @@ class PhoneTool(private val context: Context) {} catch (_: Exception) { null }}+ @Suppress("CyclomaticComplexMethod")fun readCallLog(limit: Int,callTypeFilter: String? = null,@@ -157,7 +163,9 @@ class PhoneTool(private val context: Context) {}}if (toDate != null) {- val toMillis = try { dateFormat.parse(toDate)?.time?.plus(86_400_000L - 1) } catch (_: Exception) { null }+ val toMillis = try { dateFormat.parse(toDate)?.time?.plus(86_400_000L - 1) } catch (+ _: Exception+ ) { null }if (toMillis != null) {if (selection.isNotEmpty()) selection.append(" AND ")selection.append("${CallLog.Calls.DATE} <= ?")@@ -207,8 +215,11 @@ class PhoneTool(private val context: Context) {entries.append("- $date $type $who $dur\n")count++}- if (count == 0) ToolResult.ok("The call log is empty.")- else ToolResult.ok("Last $count call(s):\n$entries")+ if (count == 0) {+ ToolResult.ok("The call log is empty.")+ } else {+ ToolResult.ok("Last $count call(s):\n$entries")+ }}} catch (e: Exception) {ToolResult.error("Could not read the call log: ${e.message}")@@ -221,11 +232,15 @@ class PhoneTool(private val context: Context) {context.contentResolver.query(uri,arrayOf(ContactsContract.PhoneLookup.DISPLAY_NAME),- null, null, null+ null,+ null,+ null)?.use { cursor ->if (cursor.moveToFirst()) {cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup.DISPLAY_NAME))- } else null+ } else {+ null+ }}} catch (_: Exception) { null }}diff --git a/app/src/main/java/com/gotcha/tools/RootTool.kt b/app/src/main/java/com/gotcha/tools/RootTool.ktindex fe02972..6662dd9 100644--- a/app/src/main/java/com/gotcha/tools/RootTool.kt+++ b/app/src/main/java/com/gotcha/tools/RootTool.kt@@ -25,8 +25,8 @@ class RootTool(/** Irreversible, device-destroying operations we refuse even with root. */private val denyPatterns = listOf(- Regex("""\bmkfs\b"""), // reformat a filesystem- Regex("""\bdd\b[^\n]*\bof=/dev/"""), // raw write to a block device+ Regex("""\bmkfs\b"""), // reformat a filesystem+ Regex("""\bdd\b[^\n]*\bof=/dev/"""), // raw write to a block deviceRegex("""\brm\s+-[a-z]*r[a-z]*f?\s+/(\s|$)"""), // rm -rf / (wipe the root tree)Regex("""\bfastboot\b"""),Regex("""\brecovery\b[^\n]*--wipe""")diff --git a/app/src/main/java/com/gotcha/tools/SmsTool.kt b/app/src/main/java/com/gotcha/tools/SmsTool.ktindex e3b55e9..c0203c7 100644--- a/app/src/main/java/com/gotcha/tools/SmsTool.kt+++ b/app/src/main/java/com/gotcha/tools/SmsTool.kt@@ -10,8 +10,6 @@ import android.content.Intentimport android.content.IntentFilterimport android.content.pm.PackageManagerimport android.os.Build-import android.os.Handler-import android.os.Looperimport android.provider.Telephonyimport android.telephony.SmsManagerimport androidx.core.content.ContextCompat@@ -103,7 +101,7 @@ class SmsTool(private val context: Context) {if (deliveryResult != null) append(" Delivery: $deliveryResult.")if (threadContext != null) append("\n\nConversation:\n$threadContext")}.let { ToolResult.ok(it) }- } catch (e: SecurityException) {+ } catch (_: SecurityException) {ToolResult.permissionNeeded(Manifest.permission.SEND_SMS,"The SMS permission is not granted. Go to Settings → Permissions → SMS and enable it, then ask again."@@ -124,8 +122,10 @@ class SmsTool(private val context: Context) {putExtra("message", message)}val pi = PendingIntent.getBroadcast(- context, System.currentTimeMillis().toInt() and 0x7FFFFFFF,- intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT+ context,+ System.currentTimeMillis().toInt() and 0x7FFFFFFF,+ intent,+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)if (deliveryReceiver == null) {val receiver = object : BroadcastReceiver() {@@ -147,7 +147,9 @@ class SmsTool(private val context: Context) {// so the receiver must not be exported (also avoids the API 33+ overload// crashing on older devices — minSdk is 26).ContextCompat.registerReceiver(- context, receiver, IntentFilter("com.gotcha.SMS_SENT"),+ context,+ receiver,+ IntentFilter("com.gotcha.SMS_SENT"),ContextCompat.RECEIVER_NOT_EXPORTED)}@@ -215,8 +217,10 @@ class SmsTool(private val context: Context) {putExtra("message", message)}val pi = PendingIntent.getBroadcast(- context, number.hashCode() and 0x7FFFFFFF,- intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT+ context,+ number.hashCode() and 0x7FFFFFFF,+ intent,+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)val alarm = context.getSystemService(Context.ALARM_SERVICE) as AlarmManageralarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + delayMs, pi)@@ -260,7 +264,9 @@ class SmsTool(private val context: Context) {}}if (toDate != null) {- val toMillis = try { dateFormat.parse(toDate)?.time?.plus(86_400_000L - 1) } catch (_: Exception) { null }+ val toMillis = try { dateFormat.parse(toDate)?.time?.plus(86_400_000L - 1) } catch (+ _: Exception+ ) { null }if (toMillis != null) {if (selection.isNotEmpty()) selection.append(" AND ")selection.append("${Telephony.Sms.DATE} <= ?")@@ -318,7 +324,8 @@ class SmsTool(private val context: Context) {context.contentResolver.query(uri,arrayOf(Telephony.Sms.ADDRESS, Telephony.Sms.BODY, Telephony.Sms.DATE, Telephony.Sms._ID),- selection, selectionArgs,+ selection,+ selectionArgs,"${Telephony.Sms.DATE} DESC")?.use { cursor ->val addrIdx = cursor.getColumnIndexOrThrow(Telephony.Sms.ADDRESS)@@ -350,13 +357,19 @@ class SmsTool(private val context: Context) {context.contentResolver.query(uri,arrayOf(android.provider.ContactsContract.PhoneLookup.DISPLAY_NAME),- null, null, null+ null,+ null,+ null)?.use { cursor ->if (cursor.moveToFirst()) {- cursor.getString(cursor.getColumnIndexOrThrow(- android.provider.ContactsContract.PhoneLookup.DISPLAY_NAME- ))- } else null+ cursor.getString(+ cursor.getColumnIndexOrThrow(+ android.provider.ContactsContract.PhoneLookup.DISPLAY_NAME+ )+ )+ } else {+ null+ }}} catch (_: Exception) { null }}@@ -365,7 +378,9 @@ class SmsTool(private val context: Context) {return try {if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_SMS)!= PackageManager.PERMISSION_GRANTED- ) return null+ ) {+ return null+ }context.contentResolver.query(Telephony.Sms.Inbox.CONTENT_URI,arrayOf(Telephony.Sms.ADDRESS, Telephony.Sms.BODY, Telephony.Sms.DATE),diff --git a/app/src/main/java/com/gotcha/tools/StorageTool.kt b/app/src/main/java/com/gotcha/tools/StorageTool.ktindex 70fac0a..04bcb55 100644--- a/app/src/main/java/com/gotcha/tools/StorageTool.kt+++ b/app/src/main/java/com/gotcha/tools/StorageTool.kt@@ -2,7 +2,7 @@ package com.gotcha.toolsimport android.os.StatFs-class StorageTool() {+class StorageTool {fun getStorageInfo(): ToolResult {return try {@@ -13,15 +13,23 @@ class StorageTool() {} catch (_: Exception) { null }val message = buildString {- append("Internal storage: ${format(internal.used)} used of ${format(internal.total)} total, ${format(internal.free)} free")+ append(+ "Internal storage: ${format(+ internal.used+ )} used of ${format(internal.total)} total, ${format(internal.free)} free"+ )if (external != null) {- append("\nExternal / SD card: ${format(external.used)} used of ${format(external.total)} total, ${format(external.free)} free")+ append(+ "\nExternal / SD card: ${format(+ external.used+ )} used of ${format(external.total)} total, ${format(external.free)} free"+ )}val pct = if (internal.total > 0) (internal.free * 100 / internal.total) else 100Lif (pct < 10) {- append("\n⚠ Internal storage is critically low (${pct}% free) — consider freeing up space.")+ append("\n⚠ Internal storage is critically low ($pct% free) — consider freeing up space.")} else if (pct < 20) {- append("\nInternal storage is running low (${pct}% free).")+ append("\nInternal storage is running low ($pct% free).")}}ToolResult.ok(message)diff --git a/app/src/main/java/com/gotcha/tools/SystemTool.kt b/app/src/main/java/com/gotcha/tools/SystemTool.ktindex 23ce2aa..9db4b5f 100644--- a/app/src/main/java/com/gotcha/tools/SystemTool.kt+++ b/app/src/main/java/com/gotcha/tools/SystemTool.kt@@ -44,16 +44,18 @@ class SystemTool(private val context: Context) {val bm = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManagerval percent = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)// Temperature, voltage, health, and plugged info come from the sticky battery intent.- val batteryIntent = context.registerReceiver(null,- android.content.IntentFilter(android.content.Intent.ACTION_BATTERY_CHANGED))+ val batteryIntent = context.registerReceiver(+ null,+ android.content.IntentFilter(android.content.Intent.ACTION_BATTERY_CHANGED)+ )val status = batteryIntent?.getIntExtra(android.os.BatteryManager.EXTRA_STATUS, -1) ?: -1val plugged = batteryIntent?.getIntExtra(android.os.BatteryManager.EXTRA_PLUGGED, -1) ?: -1val tempRaw = batteryIntent?.getIntExtra(android.os.BatteryManager.EXTRA_TEMPERATURE, -1) ?: -1val voltage = batteryIntent?.getIntExtra(android.os.BatteryManager.EXTRA_VOLTAGE, -1) ?: -1val healthInt = batteryIntent?.getIntExtra(android.os.BatteryManager.EXTRA_HEALTH, -1) ?: -1- val charging = status == android.os.BatteryManager.BATTERY_STATUS_CHARGING- || status == android.os.BatteryManager.BATTERY_STATUS_FULL+ val charging = status == android.os.BatteryManager.BATTERY_STATUS_CHARGING ||+ status == android.os.BatteryManager.BATTERY_STATUS_FULLval pluggedLabel = when (plugged) {android.os.BatteryManager.BATTERY_PLUGGED_AC -> "AC"android.os.BatteryManager.BATTERY_PLUGGED_USB -> "USB"@@ -99,7 +101,7 @@ class SystemTool(private val context: Context) {)}openWifiSettings()- } catch (e: SecurityException) {+ } catch (_: SecurityException) {openWifiSettings()} catch (e: Exception) {ToolResult.error("Could not toggle Wi-Fi: ${e.message}")diff --git a/app/src/main/java/com/gotcha/tools/TerminalTool.kt b/app/src/main/java/com/gotcha/tools/TerminalTool.ktindex db58a91..cf63e6f 100644--- a/app/src/main/java/com/gotcha/tools/TerminalTool.kt+++ b/app/src/main/java/com/gotcha/tools/TerminalTool.kt@@ -62,7 +62,8 @@ class TerminalTool(val errBuilder = StringBuilder()val outThread = Thread { drain(stdout::read, outBuilder) }val errThread = Thread { drain(stderr::read, errBuilder) }- outThread.start(); errThread.start()+ outThread.start()+ errThread.start()val finished = process.waitFor(timeout, TimeUnit.SECONDS)if (!finished) {@@ -71,7 +72,8 @@ class TerminalTool("Command timed out after ${timeout}s and was killed: $trimmed")}- outThread.join(2000); errThread.join(2000)+ outThread.join(2000)+ errThread.join(2000)val exit = process.exitValue()val message = buildString {diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.ktindex 5c67d02..d7b168e 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -3,16 +3,18 @@ package com.gotcha.toolsimport com.gotcha.llm.FunctionDefinitionimport com.gotcha.llm.ToolDefinitionimport kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.addimport kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.putimport kotlinx.serialization.json.putJsonArrayimport kotlinx.serialization.json.putJsonObject-import kotlinx.serialization.json.add/*** Declarative JSON schemas for every tool in the catalog (PRD §4).* Schemas are decoupled from execution: [ToolExecutor] handles side effects.*/+// Fixed catalog of all tool schemas in one object by design; size is inherent.+@Suppress("LargeClass")object ToolDefinitions {private fun schema(block: kotlinx.serialization.json.JsonObjectBuilder.() -> Unit): JsonObject =@@ -223,7 +225,10 @@ object ToolDefinitions {}putJsonObject("working_dir") {put("type", "string")- put("description", "Working directory for the command (absolute path). Defaults to the app's working directory.")+ put(+ "description",+ "Working directory for the command (absolute path). Defaults to the app's working directory."+ )}putJsonObject("timeout_seconds") {put("type", "integer")@@ -254,7 +259,10 @@ object ToolDefinitions {}putJsonObject("sim_slot") {put("type", "string")- put("description", "SIM slot to use: 'sim1' or 'sim2'. Only needed on dual-SIM devices. Default is the system default.")+ put(+ "description",+ "SIM slot to use: 'sim1' or 'sim2'. Only needed on dual-SIM devices. Default is the system default."+ )}}putJsonArray("required") { add("number") }@@ -273,7 +281,10 @@ object ToolDefinitions {}putJsonObject("type") {put("type", "string")- put("description", "Filter by call type: 'incoming', 'outgoing', 'missed', or 'rejected'. Omit for all.")+ put(+ "description",+ "Filter by call type: 'incoming', 'outgoing', 'missed', or 'rejected'. Omit for all."+ )}putJsonObject("contact") {put("type", "string")@@ -328,7 +339,10 @@ object ToolDefinitions {}putJsonObject("phone_type") {put("type", "string")- put("description", "Phone number label: 'mobile' (default), 'home', 'work', 'main', 'fax', or 'pager'.")+ put(+ "description",+ "Phone number label: 'mobile' (default), 'home', 'work', 'main', 'fax', or 'pager'."+ )}putJsonObject("email") {put("type", "string")@@ -368,7 +382,10 @@ object ToolDefinitions {}putJsonObject("send_at") {put("type", "string")- put("description", "Schedule future delivery: ISO-8601 timestamp like '2026-01-15T14:30:00' or epoch millis. Omit for immediate send.")+ put(+ "description",+ "Schedule future delivery: ISO-8601 timestamp like '2026-01-15T14:30:00' or epoch millis. Omit for immediate send."+ )}}putJsonArray("required") {@@ -391,7 +408,10 @@ object ToolDefinitions {}putJsonObject("from_address") {put("type", "string")- put("description", "Filter by sender/recipient address (partial match, e.g. a contact name or phone number).")+ put(+ "description",+ "Filter by sender/recipient address (partial match, e.g. a contact name or phone number)."+ )}putJsonObject("from_date") {put("type", "string")@@ -425,7 +445,10 @@ object ToolDefinitions {putJsonObject("properties") {putJsonObject("days_ahead") {put("type", "integer")- put("description", "How many days ahead to include (1-365). Default 7 when from_date/to_date not set.")+ put(+ "description",+ "How many days ahead to include (1-365). Default 7 when from_date/to_date not set."+ )}putJsonObject("from_date") {put("type", "string")@@ -479,7 +502,10 @@ object ToolDefinitions {}putJsonObject("calendar_name") {put("type", "string")- put("description", "Calendar account name to add the event to (e.g. 'Work', 'Personal'). Defaults to the primary writable calendar.")+ put(+ "description",+ "Calendar account name to add the event to (e.g. 'Work', 'Personal'). Defaults to the primary writable calendar."+ )}}putJsonArray("required") {@@ -525,7 +551,10 @@ object ToolDefinitions {}putJsonObject("reminder_minutes") {put("type", "integer")- put("description", "New reminder before event in minutes. -1 to remove reminder. Omit to keep current.")+ put(+ "description",+ "New reminder before event in minutes. -1 to remove reminder. Omit to keep current."+ )}}putJsonArray("required") { add("event_id") }@@ -570,7 +599,10 @@ object ToolDefinitions {}putJsonObject("days") {put("type", "array")- put("description", "Repeating days: e.g. ['mon','wed','fri'] or ['weekdays']. Omit for one-time alarm.")+ put(+ "description",+ "Repeating days: e.g. ['mon','wed','fri'] or ['weekdays']. Omit for one-time alarm."+ )putJsonObject("items") { put("type", "string") }}putJsonObject("vibrate") {@@ -625,7 +657,10 @@ object ToolDefinitions {}putJsonObject("duration_seconds") {put("type", "integer")- put("description", "Optional: auto-turn off after this many seconds (1-300). Only applies when turning on.")+ put(+ "description",+ "Optional: auto-turn off after this many seconds (1-300). Only applies when turning on."+ )}}putJsonArray("required") { add("on") }@@ -666,7 +701,10 @@ object ToolDefinitions {putJsonObject("properties") {putJsonObject("stream") {put("type", "string")- put("description", "Which stream to read: media, ring, alarm, notification, call. If omitted, all streams are reported.")+ put(+ "description",+ "Which stream to read: media, ring, alarm, notification, call. If omitted, all streams are reported."+ )}}}@@ -694,7 +732,10 @@ object ToolDefinitions {putJsonObject("properties") {putJsonObject("duration_ms") {put("type", "integer")- put("description", "Vibration length in milliseconds (1-5000). Default 500. Ignored when pattern is set.")+ put(+ "description",+ "Vibration length in milliseconds (1-5000). Default 500. Ignored when pattern is set."+ )}putJsonObject("intensity") {put("type", "integer")@@ -702,7 +743,10 @@ object ToolDefinitions {}putJsonObject("pattern") {put("type", "string")- put("description", "Predefined pattern: short (100ms), long (1s), double (two quick buzzes), sos (...---...). Overrides duration_ms.")+ put(+ "description",+ "Predefined pattern: short (100ms), long (1s), double (two quick buzzes), sos (...---...). Overrides duration_ms."+ )}}}@@ -731,7 +775,10 @@ object ToolDefinitions {putJsonObject("properties") {putJsonObject("fresh") {put("type", "boolean")- put("description", "If true, request a fresh GPS fix (takes a few seconds). Default false (uses last-known location).")+ put(+ "description",+ "If true, request a fresh GPS fix (takes a few seconds). Default false (uses last-known location)."+ )}}}@@ -839,7 +886,10 @@ object ToolDefinitions {putJsonObject("properties") {putJsonObject("source") {put("type", "string")- put("description", "Audio source: 'mic' (default), 'voice' (optimized for speech), or 'camcorder' (wider range).")+ put(+ "description",+ "Audio source: 'mic' (default), 'voice' (optimized for speech), or 'camcorder' (wider range)."+ )}putJsonObject("max_duration_seconds") {put("type", "integer")@@ -847,11 +897,18 @@ object ToolDefinitions {}putJsonObject("output_path") {put("type", "string")- put("description", "Custom file path to save the recording. Defaults to Recordings/recording_{timestamp}.m4a.")+ put(+ "description",+ "Custom file path to save the recording. Defaults to Recordings/recording_{timestamp}.m4a."+ )}putJsonObject("quality") {put("type", "string")- put("description", "Recording quality: 'low' (16kHz, 16kbps), 'medium' (44.1kHz, 64kbps), or 'high' (44.1kHz, 192kbps). Default medium.")+ put(+ "description",+ "Recording quality: 'low' (16kHz, 16kbps), 'medium' (44.1kHz, 64kbps), " ++ "or 'high' (44.1kHz, 192kbps). Default medium."+ )}}}@@ -994,7 +1051,11 @@ object ToolDefinitions {put("description", "Replace all occurrences instead of just the first. Default false.")}}- putJsonArray("required") { add("path"); add("oldString"); add("newString") }+ putJsonArray("required") {+ add("path")+ add("oldString")+ add("newString")+ }})@@ -1037,11 +1098,30 @@ object ToolDefinitions {putJsonObject("items") {put("type", "object")putJsonObject("properties") {- putJsonObject("content") { put("type", "string"); put("description", "Task description.") }- putJsonObject("status") { put("type", "string"); put("description", "One of: pending, in_progress, completed, cancelled.") }- putJsonObject("priority") { put("type", "string"); put("description", "Optional: high, medium, low.") }+ putJsonObject("content") {+ put("type", "string")+ put("description", "Task description.")+ }+ putJsonObject(+ "status"+ ) {+ put(+ "type",+ "string"+ )+ put("description", "One of: pending, in_progress, completed, cancelled.")+ }+ putJsonObject(+ "priority"+ ) {+ put("type", "string")+ put("description", "Optional: high, medium, low.")+ }+ }+ putJsonArray("required") {+ add("content")+ add("status")}- putJsonArray("required") { add("content"); add("status") }}}}@@ -1084,7 +1164,10 @@ object ToolDefinitions {put("description", "Root and optional sub-path to search, e.g. 'files' or 'downloads/reports'.")}}- putJsonArray("required") { add("pattern"); add("path") }+ putJsonArray("required") {+ add("pattern")+ add("path")+ }})@@ -1110,7 +1193,10 @@ object ToolDefinitions {put("description", "Optional file-name filter glob, e.g. '*.txt', '*.kt', '*.{json,xml}'.")}}- putJsonArray("required") { add("pattern"); add("path") }+ putJsonArray("required") {+ add("pattern")+ add("path")+ }})@@ -1148,7 +1234,10 @@ object ToolDefinitions {}putJsonObject("format") {put("type", "string")- put("description", "Optional output format: 'text' (default) or 'markdown'. Currently always returns text.")+ put(+ "description",+ "Optional output format: 'text' (default) or 'markdown'. Currently always returns text."+ )}}putJsonArray("required") { add("url") }@@ -1215,10 +1304,22 @@ object ToolDefinitions {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.") }+ 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.")+ }}})diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.ktindex 1e17587..c08c180 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -21,7 +21,10 @@ import kotlinx.serialization.json.jsonPrimitive*/class ToolExecutor(context: Context) {- private val TAG = "Gotcha"+ private companion object {+ const val TAG = "Gotcha"+ }+private val appContext = context.applicationContextprivate val phoneTool = PhoneTool(appContext)private val systemTool = SystemTool(appContext)@@ -38,6 +41,7 @@ class ToolExecutor(context: Context) {private val appsTool = AppsTool(appContext)private val clipboardTool = ClipboardTool(appContext)private val mediaCaptureTool = MediaCaptureTool(appContext)+// Tier 3 toolsprivate val webSearchTool = WebSearchTool()private val webFetchTool = WebFetchTool()@@ -51,6 +55,7 @@ class ToolExecutor(context: Context) {private val overlayTool = OverlayTool(appContext)private val deviceAdminTool = DeviceAdminTool(appContext)private val vpnTool = VpnTool(appContext)+// Tier 4 toolsprivate val rootTool = RootTool()private val actionLog = ActionLog(appContext)@@ -66,7 +71,7 @@ class ToolExecutor(context: Context) {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."+ "Switch to Operator mode if you need to perform this action.")}val result = try {@@ -78,7 +83,10 @@ class ToolExecutor(context: Context) {}// Do not log result.message — tool payloads can contain sensitive user data// (SMS bodies, clipboard text, file contents, location, etc.).- Log.d(TAG, "execute: $name -> success=${result.success}, msgLen=${result.message.length}, perm=${result.needsPermission}")+ Log.d(+ TAG,+ "execute: $name -> success=${result.success}, msgLen=${result.message.length}, perm=${result.needsPermission}"+ )actionLog.record(name, args.toString(), result)return result}@@ -106,262 +114,269 @@ class ToolExecutor(context: Context) {return withContext(Dispatchers.IO) { calendarTool.doDeleteEvent(eventId) }}+ // Single when-dispatch over the entire fixed tool catalog; size and branch count are+ // inherent to the design (see AGENTS.md).+ @Suppress("CyclomaticComplexMethod", "LongMethod")private suspend fun dispatch(name: String, args: JsonObject): ToolResult {return when (name) {- "dial_number" -> phoneTool.dialNumber(args.requireString("number") ?: return missing("number"))- "get_storage_info" -> storageTool.getStorageInfo()- "get_battery_info" -> systemTool.getBatteryInfo()- "edit" -> editTool.edit(- path = args.requireString("path") ?: return missing("path"),- oldString = args.requireString("oldString") ?: return missing("oldString"),- newString = args.requireString("newString") ?: return missing("newString"),- replaceAll = args["replaceAll"]?.jsonPrimitive?.booleanOrNull ?: false- )- "list_files" -> fileTool.listFiles(- path = args.requireString("path") ?: return missing("path"),- recursive = args["recursive"]?.jsonPrimitive?.booleanOrNull ?: false,- sortBy = args.requireString("sort_by"),- include = args.requireString("include"),- exclude = args.requireString("exclude"),- maxDepth = args.requireInt("max_depth")- )- "read_file" -> fileTool.readFile(- path = args.requireString("path") ?: return missing("path"),- offset = args.requireInt("offset"),- limit = args.requireInt("limit"),- encoding = args.requireString("encoding")- )- "write_file" -> fileTool.writeFile(- path = args.requireString("path") ?: return missing("path"),- content = args.requireString("content") ?: return missing("content"),- append = args["append"]?.jsonPrimitive?.booleanOrNull ?: false,- binary = args["binary"]?.jsonPrimitive?.booleanOrNull ?: false- )- "open_app" -> systemTool.openApp(args.requireString("package_name") ?: return missing("package_name"))- "set_brightness" -> systemTool.setBrightness(- args["percent"]?.jsonPrimitive?.intOrNull ?: return missing("percent")- )- "toggle_wifi" -> systemTool.toggleWifi(- args["enabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("enabled")- )- "set_wallpaper" -> wallpaperTool.setWallpaper(args.requireString("url"))- "run_command" -> terminalTool.runCommand(- command = args.requireString("command") ?: return missing("command"),- workingDir = args.requireString("working_dir"),- timeoutSeconds = args.requireInt("timeout_seconds") ?: 15- )- "call_number" -> phoneTool.callNumber(- args.requireString("number") ?: return missing("number"),- speakerphone = args["speakerphone"]?.jsonPrimitive?.booleanOrNull,- simSlot = args.requireString("sim_slot")- )- "read_call_log" -> phoneTool.readCallLog(- limit = args.requireInt("limit") ?: 10,- callTypeFilter = args.requireString("type"),- contact = args.requireString("contact"),- fromDate = args.requireString("from_date"),- toDate = args.requireString("to_date")- )- "find_contact" -> contactsTool.findContact(- name = args.requireString("name"),- number = args.requireString("number")- )- "add_contact" -> contactsTool.addContact(- name = args.requireString("name") ?: return missing("name"),- number = args.requireString("number") ?: return missing("number"),- phoneType = args.requireString("phone_type"),- email = args.requireString("email"),- organization = args.requireString("organization")- )- "send_sms" -> smsTool.sendSms(- number = args.requireString("number") ?: return missing("number"),- message = args.requireString("message") ?: return missing("message"),- deliveryReport = args["delivery_report"]?.jsonPrimitive?.booleanOrNull,- sendAt = args.requireString("send_at")- )- "read_recent_sms" -> smsTool.readRecentSms(- limit = args.requireInt("limit") ?: 10,- fromAddress = args.requireString("from_address"),- fromDate = args.requireString("from_date"),- toDate = args.requireString("to_date"),- unreadOnly = args["unread_only"]?.jsonPrimitive?.booleanOrNull,- search = args.requireString("search"),- includeSent = args["include_sent"]?.jsonPrimitive?.booleanOrNull- )- "list_calendar_events" -> calendarTool.listEvents(- daysAhead = args.requireInt("days_ahead"),- fromDate = args.requireString("from_date"),- toDate = args.requireString("to_date"),- search = args.requireString("search")- )- "create_calendar_event" -> calendarTool.createEvent(- title = args.requireString("title") ?: return missing("title"),- start = args.requireString("start") ?: return missing("start"),- end = args.requireString("end"),- location = args.requireString("location"),- description = args.requireString("description"),- allDay = args["all_day"]?.jsonPrimitive?.booleanOrNull,- reminderMinutes = args.requireInt("reminder_minutes"),- calendarName = args.requireString("calendar_name")- )- "edit_calendar_event" -> calendarTool.editEvent(- eventId = args.requireInt("event_id")?.toLong() ?: return missing("event_id"),- title = args.requireString("title"),- start = args.requireString("start"),- end = args.requireString("end"),- location = args.requireString("location"),- description = args.requireString("description"),- allDay = args["all_day"]?.jsonPrimitive?.booleanOrNull,- reminderMinutes = args.requireInt("reminder_minutes")- )- "delete_calendar_event" -> calendarTool.deleteEvent(- eventId = args.requireInt("event_id")?.toLong() ?: return missing("event_id")- )- "set_alarm" -> alarmTool.setAlarm(- hour = args.requireInt("hour") ?: return missing("hour"),- minute = args.requireInt("minute") ?: return missing("minute"),- message = args.requireString("message"),- days = args["days"]?.jsonArray?.mapNotNull { it.jsonPrimitive?.content },- vibrate = args["vibrate"]?.jsonPrimitive?.booleanOrNull- )- "set_timer" -> alarmTool.setTimer(- seconds = args.requireInt("seconds") ?: 0,- message = args.requireString("message"),- hours = args.requireInt("hours"),- minutes = args.requireInt("minutes")- )- "list_alarms" -> alarmTool.listAlarms()- "list_timers" -> alarmTool.listTimers()- "edit_alarm" -> alarmTool.editAlarm(- id = args.requireInt("alarm_id")?.toLong() ?: return missing("alarm_id"),- hour = args.requireInt("hour"),- minute = args.requireInt("minute"),- message = args.requireString("message"),- days = args["days"]?.jsonArray?.mapNotNull { it.jsonPrimitive?.content },- vibrate = args["vibrate"]?.jsonPrimitive?.booleanOrNull- )- "delete_alarm" -> alarmTool.deleteAlarm(- id = args.requireInt("alarm_id")?.toLong() ?: return missing("alarm_id")- )- "delete_timer" -> alarmTool.deleteTimer(- id = args.requireInt("timer_id")?.toLong() ?: return missing("timer_id")- )- "toggle_torch" -> deviceTool.toggleTorch(- on = args["on"]?.jsonPrimitive?.booleanOrNull ?: return missing("on"),- durationSeconds = args.requireInt("duration_seconds")- )- "set_volume" -> deviceTool.setVolume(- stream = args.requireString("stream") ?: return missing("stream"),- percent = args.requireInt("percent") ?: return missing("percent"),- showUi = args["show_ui"]?.jsonPrimitive?.booleanOrNull ?: false- )- "get_volume" -> deviceTool.getVolume(args.requireString("stream"))- "set_ringer_mode" -> deviceTool.setRingerMode(args.requireString("mode") ?: return missing("mode"))- "vibrate" -> deviceTool.vibrate(- durationMs = args.requireInt("duration_ms") ?: 500,- intensity = args.requireInt("intensity") ?: 100,- pattern = args.requireString("pattern")- )- "set_dnd" -> deviceTool.setDnd(- args["enabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("enabled")- )- "get_location" -> locationTool.getLocation(- fresh = args["fresh"]?.jsonPrimitive?.booleanOrNull- )- "list_installed_apps" -> appsTool.listInstalledApps(args.requireString("search"))- "uninstall_app" -> appsTool.uninstallApp(args.requireString("package_name") ?: return missing("package_name"))- "get_app_usage" -> appsTool.getAppUsage(args.requireInt("days") ?: 7)- "get_data_usage" -> appsTool.getDataUsage(args.requireInt("days") ?: 30)- "get_clipboard" -> clipboardTool.getClipboard()- "set_clipboard" -> clipboardTool.setClipboard(args.requireString("text") ?: return missing("text"))- "take_photo" -> mediaCaptureTool.takePhoto(args.requireString("camera"))- "start_audio_recording" -> mediaCaptureTool.startAudioRecording(- source = args.requireString("source"),- maxDurationSeconds = args.requireInt("max_duration_seconds"),- outputPath = args.requireString("output_path"),- quality = args.requireString("quality")- )- "stop_audio_recording" -> mediaCaptureTool.stopAudioRecording()- "get_audio_recording_status" -> mediaCaptureTool.getAudioRecordingStatus()- "pause_audio_recording" -> mediaCaptureTool.pauseAudioRecording()- "resume_audio_recording" -> mediaCaptureTool.resumeAudioRecording()- "question" -> questionTool.ask(- question = args.requireString("question") ?: return missing("question"),- options = args["options"]?.jsonArray?.mapNotNull { it.jsonPrimitive?.content },- allowCustom = args["allowCustom"]?.jsonPrimitive?.booleanOrNull ?: true- )- "websearch" -> webSearchTool.search(- query = args.requireString("query") ?: return missing("query"),- numResults = args.requireInt("numResults") ?: 5- )- "webfetch" -> webFetchTool.fetch(- url = args.requireString("url") ?: return missing("url"),- format = args.requireString("format")- )- "todowrite" -> todoTool.todowrite(- parseTodoItems(args["items"]) ?: return missing("items")- )- "sleep" -> {- val secs = args.requireInt("duration_seconds")?.coerceIn(1, 86400)- ?: return missing("duration_seconds")- for (remaining in secs downTo 1) {- Log.d(TAG, "sleep: ${remaining}s remaining")- delay(1000L)+ "dial_number" -> phoneTool.dialNumber(args.requireString("number") ?: return missing("number"))+ "get_storage_info" -> storageTool.getStorageInfo()+ "get_battery_info" -> systemTool.getBatteryInfo()+ "edit" -> editTool.edit(+ path = args.requireString("path") ?: return missing("path"),+ oldString = args.requireString("oldString") ?: return missing("oldString"),+ newString = args.requireString("newString") ?: return missing("newString"),+ replaceAll = args["replaceAll"]?.jsonPrimitive?.booleanOrNull ?: false+ )+ "list_files" -> fileTool.listFiles(+ path = args.requireString("path") ?: return missing("path"),+ recursive = args["recursive"]?.jsonPrimitive?.booleanOrNull ?: false,+ sortBy = args.requireString("sort_by"),+ include = args.requireString("include"),+ exclude = args.requireString("exclude"),+ maxDepth = args.requireInt("max_depth")+ )+ "read_file" -> fileTool.readFile(+ path = args.requireString("path") ?: return missing("path"),+ offset = args.requireInt("offset"),+ limit = args.requireInt("limit"),+ encoding = args.requireString("encoding")+ )+ "write_file" -> fileTool.writeFile(+ path = args.requireString("path") ?: return missing("path"),+ content = args.requireString("content") ?: return missing("content"),+ append = args["append"]?.jsonPrimitive?.booleanOrNull ?: false,+ binary = args["binary"]?.jsonPrimitive?.booleanOrNull ?: false+ )+ "open_app" -> systemTool.openApp(args.requireString("package_name") ?: return missing("package_name"))+ "set_brightness" -> systemTool.setBrightness(+ args["percent"]?.jsonPrimitive?.intOrNull ?: return missing("percent")+ )+ "toggle_wifi" -> systemTool.toggleWifi(+ args["enabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("enabled")+ )+ "set_wallpaper" -> wallpaperTool.setWallpaper(args.requireString("url"))+ "run_command" -> terminalTool.runCommand(+ command = args.requireString("command") ?: return missing("command"),+ workingDir = args.requireString("working_dir"),+ timeoutSeconds = args.requireInt("timeout_seconds") ?: 15+ )+ "call_number" -> phoneTool.callNumber(+ args.requireString("number") ?: return missing("number"),+ speakerphone = args["speakerphone"]?.jsonPrimitive?.booleanOrNull,+ simSlot = args.requireString("sim_slot")+ )+ "read_call_log" -> phoneTool.readCallLog(+ limit = args.requireInt("limit") ?: 10,+ callTypeFilter = args.requireString("type"),+ contact = args.requireString("contact"),+ fromDate = args.requireString("from_date"),+ toDate = args.requireString("to_date")+ )+ "find_contact" -> contactsTool.findContact(+ name = args.requireString("name"),+ number = args.requireString("number")+ )+ "add_contact" -> contactsTool.addContact(+ name = args.requireString("name") ?: return missing("name"),+ number = args.requireString("number") ?: return missing("number"),+ phoneType = args.requireString("phone_type"),+ email = args.requireString("email"),+ organization = args.requireString("organization")+ )+ "send_sms" -> smsTool.sendSms(+ number = args.requireString("number") ?: return missing("number"),+ message = args.requireString("message") ?: return missing("message"),+ deliveryReport = args["delivery_report"]?.jsonPrimitive?.booleanOrNull,+ sendAt = args.requireString("send_at")+ )+ "read_recent_sms" -> smsTool.readRecentSms(+ limit = args.requireInt("limit") ?: 10,+ fromAddress = args.requireString("from_address"),+ fromDate = args.requireString("from_date"),+ toDate = args.requireString("to_date"),+ unreadOnly = args["unread_only"]?.jsonPrimitive?.booleanOrNull,+ search = args.requireString("search"),+ includeSent = args["include_sent"]?.jsonPrimitive?.booleanOrNull+ )+ "list_calendar_events" -> calendarTool.listEvents(+ daysAhead = args.requireInt("days_ahead"),+ fromDate = args.requireString("from_date"),+ toDate = args.requireString("to_date"),+ search = args.requireString("search")+ )+ "create_calendar_event" -> calendarTool.createEvent(+ title = args.requireString("title") ?: return missing("title"),+ start = args.requireString("start") ?: return missing("start"),+ end = args.requireString("end"),+ location = args.requireString("location"),+ description = args.requireString("description"),+ allDay = args["all_day"]?.jsonPrimitive?.booleanOrNull,+ reminderMinutes = args.requireInt("reminder_minutes"),+ calendarName = args.requireString("calendar_name")+ )+ "edit_calendar_event" -> calendarTool.editEvent(+ eventId = args.requireInt("event_id")?.toLong() ?: return missing("event_id"),+ title = args.requireString("title"),+ start = args.requireString("start"),+ end = args.requireString("end"),+ location = args.requireString("location"),+ description = args.requireString("description"),+ allDay = args["all_day"]?.jsonPrimitive?.booleanOrNull,+ reminderMinutes = args.requireInt("reminder_minutes")+ )+ "delete_calendar_event" -> calendarTool.deleteEvent(+ eventId = args.requireInt("event_id")?.toLong() ?: return missing("event_id")+ )+ "set_alarm" -> alarmTool.setAlarm(+ hour = args.requireInt("hour") ?: return missing("hour"),+ minute = args.requireInt("minute") ?: return missing("minute"),+ message = args.requireString("message"),+ days = args["days"]?.jsonArray?.mapNotNull { it.jsonPrimitive?.content },+ vibrate = args["vibrate"]?.jsonPrimitive?.booleanOrNull+ )+ "set_timer" -> alarmTool.setTimer(+ seconds = args.requireInt("seconds") ?: 0,+ message = args.requireString("message"),+ hours = args.requireInt("hours"),+ minutes = args.requireInt("minutes")+ )+ "list_alarms" -> alarmTool.listAlarms()+ "list_timers" -> alarmTool.listTimers()+ "edit_alarm" -> alarmTool.editAlarm(+ id = args.requireInt("alarm_id")?.toLong() ?: return missing("alarm_id"),+ hour = args.requireInt("hour"),+ minute = args.requireInt("minute"),+ message = args.requireString("message"),+ days = args["days"]?.jsonArray?.mapNotNull { it.jsonPrimitive?.content },+ vibrate = args["vibrate"]?.jsonPrimitive?.booleanOrNull+ )+ "delete_alarm" -> alarmTool.deleteAlarm(+ id = args.requireInt("alarm_id")?.toLong() ?: return missing("alarm_id")+ )+ "delete_timer" -> alarmTool.deleteTimer(+ id = args.requireInt("timer_id")?.toLong() ?: return missing("timer_id")+ )+ "toggle_torch" -> deviceTool.toggleTorch(+ on = args["on"]?.jsonPrimitive?.booleanOrNull ?: return missing("on"),+ durationSeconds = args.requireInt("duration_seconds")+ )+ "set_volume" -> deviceTool.setVolume(+ stream = args.requireString("stream") ?: return missing("stream"),+ percent = args.requireInt("percent") ?: return missing("percent"),+ showUi = args["show_ui"]?.jsonPrimitive?.booleanOrNull ?: false+ )+ "get_volume" -> deviceTool.getVolume(args.requireString("stream"))+ "set_ringer_mode" -> deviceTool.setRingerMode(args.requireString("mode") ?: return missing("mode"))+ "vibrate" -> deviceTool.vibrate(+ durationMs = args.requireInt("duration_ms") ?: 500,+ intensity = args.requireInt("intensity") ?: 100,+ pattern = args.requireString("pattern")+ )+ "set_dnd" -> deviceTool.setDnd(+ args["enabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("enabled")+ )+ "get_location" -> locationTool.getLocation(+ fresh = args["fresh"]?.jsonPrimitive?.booleanOrNull+ )+ "list_installed_apps" -> appsTool.listInstalledApps(args.requireString("search"))+ "uninstall_app" -> appsTool.uninstallApp(+ args.requireString("package_name") ?: return missing("package_name")+ )+ "get_app_usage" -> appsTool.getAppUsage(args.requireInt("days") ?: 7)+ "get_data_usage" -> appsTool.getDataUsage(args.requireInt("days") ?: 30)+ "get_clipboard" -> clipboardTool.getClipboard()+ "set_clipboard" -> clipboardTool.setClipboard(args.requireString("text") ?: return missing("text"))+ "take_photo" -> mediaCaptureTool.takePhoto(args.requireString("camera"))+ "start_audio_recording" -> mediaCaptureTool.startAudioRecording(+ source = args.requireString("source"),+ maxDurationSeconds = args.requireInt("max_duration_seconds"),+ outputPath = args.requireString("output_path"),+ quality = args.requireString("quality")+ )+ "stop_audio_recording" -> mediaCaptureTool.stopAudioRecording()+ "get_audio_recording_status" -> mediaCaptureTool.getAudioRecordingStatus()+ "pause_audio_recording" -> mediaCaptureTool.pauseAudioRecording()+ "resume_audio_recording" -> mediaCaptureTool.resumeAudioRecording()+ "question" -> questionTool.ask(+ question = args.requireString("question") ?: return missing("question"),+ options = args["options"]?.jsonArray?.mapNotNull { it.jsonPrimitive?.content },+ allowCustom = args["allowCustom"]?.jsonPrimitive?.booleanOrNull ?: true+ )+ "websearch" -> webSearchTool.search(+ query = args.requireString("query") ?: return missing("query"),+ numResults = args.requireInt("numResults") ?: 5+ )+ "webfetch" -> webFetchTool.fetch(+ url = args.requireString("url") ?: return missing("url"),+ format = args.requireString("format")+ )+ "todowrite" -> todoTool.todowrite(+ parseTodoItems(args["items"]) ?: return missing("items")+ )+ "sleep" -> {+ val secs = args.requireInt("duration_seconds")?.coerceIn(1, 86400)+ ?: return missing("duration_seconds")+ for (remaining in secs downTo 1) {+ Log.d(TAG, "sleep: ${remaining}s remaining")+ delay(1000L)+ }+ ToolResult.ok("Slept for $secs seconds.")}- ToolResult.ok("Slept for $secs seconds.")- }- "read_image" -> fileTool.readFile(args.requireString("path") ?: return missing("path"))- "glob" -> globTool.glob(- path = args.requireString("path") ?: return missing("path"),- pattern = args.requireString("pattern") ?: return missing("pattern")- )- "grep" -> grepTool.grep(- path = args.requireString("path") ?: return missing("path"),- pattern = args.requireString("pattern") ?: return missing("pattern"),- include = args.requireString("include")- )- // ---- 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")- )- "set_firewall" -> vpnTool.setFirewall(- args["enabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("enabled")- )- "get_firewall_status" -> vpnTool.getFirewallStatus()- // ---- Tier 4 ----- "check_root" -> rootTool.checkRoot()- "run_root_command" -> rootTool.runRootCommand(args.requireString("command") ?: return missing("command"))- "write_secure_settings" -> rootTool.writeSecureSetting(- namespace = args.requireString("namespace") ?: return missing("namespace"),- key = args.requireString("key") ?: return missing("key"),- value = args.requireString("value") ?: return missing("value")- )- else -> ToolResult.error("Tool '$name' has no executor.")+ "read_image" -> fileTool.readFile(args.requireString("path") ?: return missing("path"))+ "glob" -> globTool.glob(+ path = args.requireString("path") ?: return missing("path"),+ pattern = args.requireString("pattern") ?: return missing("pattern")+ )+ "grep" -> grepTool.grep(+ path = args.requireString("path") ?: return missing("path"),+ pattern = args.requireString("pattern") ?: return missing("pattern"),+ include = args.requireString("include")+ )+ // ---- 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")+ )+ "set_firewall" -> vpnTool.setFirewall(+ args["enabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("enabled")+ )+ "get_firewall_status" -> vpnTool.getFirewallStatus()+ // ---- Tier 4 ----+ "check_root" -> rootTool.checkRoot()+ "run_root_command" -> rootTool.runRootCommand(args.requireString("command") ?: return missing("command"))+ "write_secure_settings" -> rootTool.writeSecureSetting(+ namespace = args.requireString("namespace") ?: return missing("namespace"),+ key = args.requireString("key") ?: return missing("key"),+ value = args.requireString("value") ?: return missing("value")+ )+ else -> ToolResult.error("Tool '$name' has no executor.")}}diff --git a/app/src/main/java/com/gotcha/tools/VpnTool.kt b/app/src/main/java/com/gotcha/tools/VpnTool.ktindex 4f412eb..63c8483 100644--- a/app/src/main/java/com/gotcha/tools/VpnTool.kt+++ b/app/src/main/java/com/gotcha/tools/VpnTool.kt@@ -42,8 +42,11 @@ class VpnTool(private val context: Context) {/** Report whether the blocking VPN is currently up. */fun getFirewallStatus(): ToolResult = ToolResult.ok(- if (GotchaVpnService.isRunning) "The network firewall is ON — all traffic is blocked."- else "The network firewall is OFF — traffic flows normally."+ if (GotchaVpnService.isRunning) {+ "The network firewall is ON — all traffic is blocked."+ } else {+ "The network firewall is OFF — traffic flows normally."+ })private fun startIntent() =diff --git a/app/src/main/java/com/gotcha/tools/WebFetchTool.kt b/app/src/main/java/com/gotcha/tools/WebFetchTool.ktindex aa11b5e..b787ec3 100644--- a/app/src/main/java/com/gotcha/tools/WebFetchTool.kt+++ b/app/src/main/java/com/gotcha/tools/WebFetchTool.kt@@ -39,7 +39,11 @@ class WebFetchTool {return try {val request = Request.Builder().url(trimmed)- .header("User-Agent", "Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.6422.165 Mobile Safari/537.36")+ .header(+ "User-Agent",+ "Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 " ++ "(KHTML, like Gecko) Chrome/125.0.6422.165 Mobile Safari/537.36"+ ).header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8").header("Accept-Language", "en-US,en;q=0.9").build()@@ -54,7 +58,9 @@ class WebFetchTool {val contentType = body.contentType()val mime = if (contentType != null) {"${contentType.type?.lowercase() ?: "text"}/${contentType.subtype?.lowercase() ?: "html"}"- } else "text/html"+ } else {+ "text/html"+ }val accepted = mime.startsWith("text/") ||mime in listOf("application/json", "application/xml", "application/xhtml+xml")@@ -83,20 +89,24 @@ class WebFetchTool {val truncated = output.length > MAX_RESPONSE_BYTESval finalOutput = if (truncated) {output.take(MAX_RESPONSE_BYTES) + "\n…(truncated at ${MAX_RESPONSE_BYTES / 1024} KB)"- } else output+ } else {+ output+ }ToolResult.ok(- "Fetched ${trimmed} (${rawSizeKb} KB raw → ${finalOutput.length / 1024} KB ${outputFormat}, HTTP ${response.code}):\n\n$finalOutput"+ "Fetched $trimmed ($rawSizeKb KB raw → ${finalOutput.length / 1024} KB " ++ "$outputFormat, HTTP ${response.code}):\n\n$finalOutput")} catch (e: java.net.UnknownHostException) {ToolResult.error("Could not resolve host: ${e.message}")- } catch (e: java.net.SocketTimeoutException) {+ } catch (_: java.net.SocketTimeoutException) {ToolResult.error("Request timed out after ${TIMEOUT_SECONDS}s.")} catch (e: Exception) {ToolResult.error("Failed to fetch URL: ${e.message}")}}+ @Suppress("CyclomaticComplexMethod")private fun htmlToMarkdown(doc: Document): String {val sb = StringBuilder()val body = doc.body() ?: return doc.text()@@ -137,19 +147,33 @@ class WebFetchTool {}}"strong", "b" -> {- sb.append("**"); children(); sb.append("**")+ sb.append("**")+ children()+ sb.append("**")}"em", "i" -> {- sb.append("*"); children(); sb.append("*")+ sb.append("*")+ children()+ sb.append("*")}"code" -> {- sb.append("`"); children(); sb.append("`")+ sb.append("`")+ children()+ sb.append("`")}"pre" -> {sb.append("\n```\n${(node as org.jsoup.nodes.Element).text()}\n```\n\n")}- "ul" -> { sb.append("\n"); children(); sb.append("\n") }- "ol" -> { sb.append("\n"); children(); sb.append("\n") }+ "ul" -> {+ sb.append("\n")+ children()+ sb.append("\n")+ }+ "ol" -> {+ sb.append("\n")+ children()+ sb.append("\n")+ }"li" -> {val parent = node.parent()val isOrdered = parent != null && parent.nodeName() == "ol"@@ -162,7 +186,9 @@ class WebFetchTool {sb.append("\n")}"blockquote" -> {- sb.append("\n> "); children(); sb.append("\n\n")+ sb.append("\n> ")+ children()+ sb.append("\n\n")}"hr" -> sb.append("\n---\n\n")"img" -> {diff --git a/app/src/main/java/com/gotcha/tools/WebSearchTool.kt b/app/src/main/java/com/gotcha/tools/WebSearchTool.ktindex 1e0f36d..eaf8c6c 100644--- a/app/src/main/java/com/gotcha/tools/WebSearchTool.kt+++ b/app/src/main/java/com/gotcha/tools/WebSearchTool.kt@@ -31,7 +31,11 @@ class WebSearchTool {return try {val request = Request.Builder().url("$DUCKDUCKGO_HTML?q=${java.net.URLEncoder.encode(trimmed, "UTF-8")}")- .header("User-Agent", "Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.6422.165 Mobile Safari/537.36")+ .header(+ "User-Agent",+ "Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 " ++ "(KHTML, like Gecko) Chrome/125.0.6422.165 Mobile Safari/537.36"+ ).header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8").header("Accept-Language", "en-US,en;q=0.9").build()@@ -60,12 +64,11 @@ class WebSearchTool {val titleEl = row.selectFirst(".result__title a")val snippetEl = row.selectFirst(".result__snippet")- val urlEl = row.selectFirst(".result__url")val title = titleEl?.text()?.trim() ?: continueval href = titleEl.attr("href")// DDG wraps real URLs in redirect — extract from the 'uddg' parameter or use the href directly- val url = extractUrl(href, row)+ val url = extractUrl(href)val snippet = snippetEl?.text()?.trim() ?: ""if (url.isNotEmpty()) {@@ -84,15 +87,15 @@ class WebSearchTool {ToolResult.ok("Search results for '$trimmed' (top ${results.size}):\n\n${results.joinToString("\n")}")} catch (e: java.net.UnknownHostException) {ToolResult.error("Could not reach the search engine: ${e.message}")- } catch (e: java.net.SocketTimeoutException) {+ } catch (_: java.net.SocketTimeoutException) {ToolResult.error("Search timed out after ${TIMEOUT_SECONDS}s.")} catch (e: Exception) {ToolResult.error("Search failed: ${e.message}")}}- /** Extract the real URL from a DDG result row. DDG wraps links in redirects. */- private fun extractUrl(href: String, row: org.jsoup.nodes.Element): String {+ /** Extract the real URL from a DDG result href. DDG wraps links in redirects. */+ private fun extractUrl(href: String): String {// DDG redirect links look like: //duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.com%2F...if (href.contains("uddg=")) {val uddg = href.substringAfter("uddg=").substringBefore("&")diff --git a/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.ktindex 9d5e2cc..2064938 100644--- a/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt+++ b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt@@ -39,6 +39,7 @@ import kotlin.math.abs* The ball is touchable (no FLAG_NOT_TOUCHABLE) so it can be dragged and tapped; the* two "talk" options are press-and-hold (down = start recording, up = stop & ask).*/+@Suppress("TooManyFunctions")class AssistiveBallOverlay(context: Context) {private val appContext = context.applicationContext@@ -215,13 +216,17 @@ class AssistiveBallOverlay(context: Context) {container.addView(menuTitle("Gotcha"))container.addView(talkButton("🖥 Screen Share — hold & talk", withScreen = true))container.addView(talkButton("🎤 Talk — hold & talk", withScreen = false))- container.addView(tapButton("💬 Open Chat") {- removeMenu()- onOpenChat()- })- container.addView(tapButton("✕ Hide ball") {- onDismiss()- })+ container.addView(+ tapButton("💬 Open Chat") {+ removeMenu()+ onOpenChat()+ }+ )+ container.addView(+ tapButton("✕ Hide ball") {+ onDismiss()+ }+ )val params = menuLayoutParams()try {@@ -293,11 +298,13 @@ class AssistiveBallOverlay(context: Context) {}}val scroll = ScrollView(appContext).apply {- addView(TextView(appContext).apply {- text = message- setTextColor(Color.parseColor("#EEEEEE"))- textSize = 14f- })+ addView(+ TextView(appContext).apply {+ text = message+ setTextColor(Color.parseColor("#EEEEEE"))+ textSize = 14f+ }+ )layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,dp(240)@@ -305,11 +312,13 @@ class AssistiveBallOverlay(context: Context) {}container.addView(scroll)if (showClose) {- container.addView(Button(appContext).apply {- text = "Close"- isAllCaps = false- setOnClickListener { hideCard() }- })+ container.addView(+ Button(appContext).apply {+ text = "Close"+ isAllCaps = false+ setOnClickListener { hideCard() }+ }+ )}try {windowManager.addView(container, cardLayoutParams())@@ -340,9 +349,12 @@ class AssistiveBallOverlay(context: Context) {}private fun overlayType(): Int =- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY- else @Suppress("DEPRECATION") WindowManager.LayoutParams.TYPE_PHONE+ } else {+ @Suppress("DEPRECATION")+ WindowManager.LayoutParams.TYPE_PHONE+ }private fun ballLayoutParams(): WindowManager.LayoutParams =WindowManager.LayoutParams(diff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.ktindex 6568b08..585c783 100644--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt@@ -3,9 +3,6 @@ package com.gotcha.uiimport android.net.Uriimport androidx.activity.compose.rememberLauncherForActivityResultimport androidx.activity.result.contract.ActivityResultContracts-import androidx.compose.foundation.Image as ComposeImage-import androidx.compose.foundation.background-import androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Row@@ -31,12 +28,11 @@ import androidx.compose.material3.AlertDialogimport androidx.compose.material3.Buttonimport androidx.compose.material3.ButtonDefaultsimport androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.FilterChipimport androidx.compose.material3.Iconimport androidx.compose.material3.IconButton-import androidx.compose.material3.IconButtonDefaultsimport androidx.compose.material3.LinearProgressIndicator-import androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.OutlinedTextFieldimport androidx.compose.material3.Scaffold@@ -58,8 +54,8 @@ import androidx.compose.ui.graphics.asImageBitmapimport androidx.compose.ui.layout.ContentScaleimport androidx.compose.ui.unit.dpimport com.gotcha.agent.ChatUiState-import com.gotcha.agent.PendingQuestionimport com.gotcha.tools.AgentMode+import androidx.compose.foundation.Image as ComposeImage@OptIn(ExperimentalMaterial3Api::class)@Composable@@ -218,8 +214,11 @@ fun ChatScreen(contentPadding = ButtonDefaults.TextButtonContentPadding,shape = CircleShape) {- Icon(Icons.Default.Stop, contentDescription = "Stop",- modifier = Modifier.size(20.dp))+ Icon(+ Icons.Default.Stop,+ contentDescription = "Stop",+ modifier = Modifier.size(20.dp)+ )}}state.isRecording || state.isListening -> {@@ -233,9 +232,12 @@ fun ChatScreen(containerColor = MaterialTheme.colorScheme.error)) {- Icon(Icons.Default.Stop, contentDescription = "Stop recording",+ Icon(+ Icons.Default.Stop,+ contentDescription = "Stop recording",modifier = Modifier.size(20.dp),- tint = Color.White)+ tint = Color.White+ )}}input.isBlank() && pendingImageBase64 == null -> {diff --git a/app/src/main/java/com/gotcha/ui/MessageBubble.kt b/app/src/main/java/com/gotcha/ui/MessageBubble.ktindex 5732296..246de1a 100644--- a/app/src/main/java/com/gotcha/ui/MessageBubble.kt+++ b/app/src/main/java/com/gotcha/ui/MessageBubble.kt@@ -15,11 +15,8 @@ import androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.heightimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.size-import androidx.compose.foundation.layout.widthimport androidx.compose.foundation.layout.widthInimport androidx.compose.foundation.shape.RoundedCornerShape-import com.halilibo.richtext.markdown.Markdown-import com.halilibo.richtext.ui.material3.Material3RichTextimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.automirrored.rounded.VolumeUpimport androidx.compose.material3.DropdownMenu@@ -34,7 +31,6 @@ import androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.setValue-import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.graphics.asImageBitmap@@ -42,6 +38,8 @@ import androidx.compose.ui.layout.ContentScaleimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dp+import com.halilibo.richtext.markdown.Markdown+import com.halilibo.richtext.ui.material3.Material3RichTextimport com.gotcha.agent.MessageKindimport com.gotcha.agent.UiMessage@@ -86,14 +84,17 @@ fun MessageBubble(modifier = Modifier.widthIn(max = 320.dp).then(- if (isTool) Modifier.combinedClickable(- onClick = { expanded.value = !expanded.value },- onLongClick = { showMenu = true }- )- else Modifier.combinedClickable(- onClick = { },- onLongClick = { showMenu = true }- )+ if (isTool) {+ Modifier.combinedClickable(+ onClick = { expanded.value = !expanded.value },+ onLongClick = { showMenu = true }+ )+ } else {+ Modifier.combinedClickable(+ onClick = { },+ onLongClick = { showMenu = true }+ )+ }).padding(16.dp)) {diff --git a/app/src/main/java/com/gotcha/ui/PermissionItems.kt b/app/src/main/java/com/gotcha/ui/PermissionItems.ktindex fb5451c..37186b4 100644--- a/app/src/main/java/com/gotcha/ui/PermissionItems.kt+++ b/app/src/main/java/com/gotcha/ui/PermissionItems.kt@@ -1,13 +1,12 @@package com.gotcha.ui+import android.app.AppOpsManager+import android.app.admin.DevicePolicyManager+import android.content.ComponentNameimport android.content.Contextimport android.os.Buildimport android.os.Environmentimport android.provider.Settings-import android.app.admin.DevicePolicyManager-import android.app.AppOpsManager-import android.content.ComponentName-import android.content.ContextWrapperimport androidx.core.content.ContextCompatimport com.gotcha.service.GotchaDeviceAdminReceiver@@ -27,179 +26,256 @@ data class PermissionItem(val extraPermissions: List<String> = emptyList())-fun allPermissionGroups(context: Context): List<PermissionGroup> = listOf(- PermissionGroup("Communications", listOf(- PermissionItem(- "Phone", "Place calls directly",- android.Manifest.permission.CALL_PHONE, null,- { c -> checkPerm(c, android.Manifest.permission.CALL_PHONE) }- ),- PermissionItem(- "SMS", "Send text messages",- android.Manifest.permission.SEND_SMS, null,- { c -> checkPerm(c, android.Manifest.permission.SEND_SMS) }- ),- PermissionItem(- "Read SMS", "Read inbox messages",- android.Manifest.permission.READ_SMS, null,- { c -> checkPerm(c, android.Manifest.permission.READ_SMS) }- ),- PermissionItem(- "Call Log", "Read recent call history",- android.Manifest.permission.READ_CALL_LOG, null,- { c -> checkPerm(c, android.Manifest.permission.READ_CALL_LOG) }+// Declarative catalog of every permission the app can request; length is inherent.+@Suppress("LongMethod")+fun allPermissionGroups(): List<PermissionGroup> = listOf(+ PermissionGroup(+ "Communications",+ listOf(+ PermissionItem(+ "Phone",+ "Place calls directly",+ android.Manifest.permission.CALL_PHONE,+ null,+ { c -> checkPerm(c, android.Manifest.permission.CALL_PHONE) }+ ),+ PermissionItem(+ "SMS",+ "Send text messages",+ android.Manifest.permission.SEND_SMS,+ null,+ { c -> checkPerm(c, android.Manifest.permission.SEND_SMS) }+ ),+ PermissionItem(+ "Read SMS",+ "Read inbox messages",+ android.Manifest.permission.READ_SMS,+ null,+ { c -> checkPerm(c, android.Manifest.permission.READ_SMS) }+ ),+ PermissionItem(+ "Call Log",+ "Read recent call history",+ android.Manifest.permission.READ_CALL_LOG,+ null,+ { c -> checkPerm(c, android.Manifest.permission.READ_CALL_LOG) }+ ))- )),- PermissionGroup("Contacts", listOf(- PermissionItem(- "Contacts", "Read and create contacts",- android.Manifest.permission.READ_CONTACTS, null,- { c ->- checkPerm(c, android.Manifest.permission.READ_CONTACTS) &&- checkPerm(c, android.Manifest.permission.WRITE_CONTACTS)- },- extraPermissions = listOf(android.Manifest.permission.WRITE_CONTACTS)+ ),+ PermissionGroup(+ "Contacts",+ listOf(+ PermissionItem(+ "Contacts",+ "Read and create contacts",+ android.Manifest.permission.READ_CONTACTS,+ null,+ { c ->+ checkPerm(c, android.Manifest.permission.READ_CONTACTS) &&+ checkPerm(c, android.Manifest.permission.WRITE_CONTACTS)+ },+ extraPermissions = listOf(android.Manifest.permission.WRITE_CONTACTS)+ ))- )),- PermissionGroup("Calendar", listOf(- PermissionItem(- "Calendar", "Read and create calendar events",- android.Manifest.permission.READ_CALENDAR, null,- { c ->- checkPerm(c, android.Manifest.permission.READ_CALENDAR) &&- checkPerm(c, android.Manifest.permission.WRITE_CALENDAR)- },- extraPermissions = listOf(android.Manifest.permission.WRITE_CALENDAR)+ ),+ PermissionGroup(+ "Calendar",+ listOf(+ PermissionItem(+ "Calendar",+ "Read and create calendar events",+ android.Manifest.permission.READ_CALENDAR,+ null,+ { c ->+ checkPerm(c, android.Manifest.permission.READ_CALENDAR) &&+ checkPerm(c, android.Manifest.permission.WRITE_CALENDAR)+ },+ extraPermissions = listOf(android.Manifest.permission.WRITE_CALENDAR)+ ))- )),- PermissionGroup("Media & Storage", listOf(- PermissionItem(- "Camera", "Take photos",- android.Manifest.permission.CAMERA, null,- { c -> checkPerm(c, android.Manifest.permission.CAMERA) }- ),- PermissionItem(- "Microphone", "Record audio",- android.Manifest.permission.RECORD_AUDIO, null,- { c -> checkPerm(c, android.Manifest.permission.RECORD_AUDIO) }- ),- PermissionItem(- "Storage Read", "Read files from shared storage",- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)- android.Manifest.permission.READ_MEDIA_IMAGES- else android.Manifest.permission.READ_EXTERNAL_STORAGE, null,- { c ->- val perm = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)+ ),+ PermissionGroup(+ "Media & Storage",+ listOf(+ PermissionItem(+ "Camera",+ "Take photos",+ android.Manifest.permission.CAMERA,+ null,+ { c -> checkPerm(c, android.Manifest.permission.CAMERA) }+ ),+ PermissionItem(+ "Microphone",+ "Record audio",+ android.Manifest.permission.RECORD_AUDIO,+ null,+ { c -> checkPerm(c, android.Manifest.permission.RECORD_AUDIO) }+ ),+ PermissionItem(+ "Storage Read",+ "Read files from shared storage",+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {android.Manifest.permission.READ_MEDIA_IMAGES- else android.Manifest.permission.READ_EXTERNAL_STORAGE- checkPerm(c, perm)- }- ),- PermissionItem(- "Storage Write", "Write files to shared storage",- android.Manifest.permission.WRITE_EXTERNAL_STORAGE, null,- { c ->- if (Build.VERSION.SDK_INT <= 29) checkPerm(c, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)- else true // API 30+ uses MANAGE_EXTERNAL_STORAGE- }- ),- PermissionItem(- "All Files Access", "Full access to all files on device",- null, "special:all_files_access",- { c ->- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) Environment.isExternalStorageManager()- else checkPerm(c, android.Manifest.permission.READ_EXTERNAL_STORAGE)- }+ } else {+ android.Manifest.permission.READ_EXTERNAL_STORAGE+ },+ null,+ { c ->+ val perm = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ android.Manifest.permission.READ_MEDIA_IMAGES+ } else {+ android.Manifest.permission.READ_EXTERNAL_STORAGE+ }+ checkPerm(c, perm)+ }+ ),+ PermissionItem(+ "Storage Write",+ "Write files to shared storage",+ android.Manifest.permission.WRITE_EXTERNAL_STORAGE,+ null,+ { c ->+ if (Build.VERSION.SDK_INT <= 29) {+ checkPerm(c, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)+ } else {+ true // API 30+ uses MANAGE_EXTERNAL_STORAGE+ }+ }+ ),+ PermissionItem(+ "All Files Access",+ "Full access to all files on device",+ null,+ "special:all_files_access",+ { c ->+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+ Environment.isExternalStorageManager()+ } else {+ checkPerm(c, android.Manifest.permission.READ_EXTERNAL_STORAGE)+ }+ }+ ))- )),- PermissionGroup("Location", listOf(- PermissionItem(- "Location", "Get device location",- android.Manifest.permission.ACCESS_FINE_LOCATION, null,- { c -> checkPerm(c, android.Manifest.permission.ACCESS_FINE_LOCATION) }+ ),+ PermissionGroup(+ "Location",+ listOf(+ PermissionItem(+ "Location",+ "Get device location",+ android.Manifest.permission.ACCESS_FINE_LOCATION,+ null,+ { c -> checkPerm(c, android.Manifest.permission.ACCESS_FINE_LOCATION) }+ ))- )),- PermissionGroup("Device Control", listOf(- PermissionItem(- "Write Settings", "Modify system settings (brightness)",- null, "special:write_settings",- { c -> Settings.System.canWrite(c) }- ),- PermissionItem(- "Do Not Disturb", "Silence/vibrate mode and DND",- null, "special:dnd_access",- { c ->- val nm = c.getSystemService(Context.NOTIFICATION_SERVICE) as? android.app.NotificationManager- nm?.isNotificationPolicyAccessGranted ?: false- }- ),- PermissionItem(- "Usage Access", "Read app usage and data stats",- null, "special:usage_access",- { c ->- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {- val appOps = c.getSystemService(Context.APP_OPS_SERVICE) as? AppOpsManager- appOps?.checkOpNoThrow(- AppOpsManager.OPSTR_GET_USAGE_STATS,- android.os.Process.myUid(), c.packageName- ) == AppOpsManager.MODE_ALLOWED- } else true- }- ),- PermissionItem(- "Device Admin", "Lock screen, enforce password policy",- null, "special:device_admin",- { c ->- val dpm = c.getSystemService(Context.DEVICE_POLICY_SERVICE) as? DevicePolicyManager- dpm?.isAdminActive(ComponentName(c, GotchaDeviceAdminReceiver::class.java)) ?: false- }+ ),+ PermissionGroup(+ "Device Control",+ listOf(+ PermissionItem(+ "Write Settings",+ "Modify system settings (brightness)",+ null,+ "special:write_settings",+ { c -> Settings.System.canWrite(c) }+ ),+ PermissionItem(+ "Do Not Disturb",+ "Silence/vibrate mode and DND",+ null,+ "special:dnd_access",+ { c ->+ val nm = c.getSystemService(Context.NOTIFICATION_SERVICE) as? android.app.NotificationManager+ nm?.isNotificationPolicyAccessGranted ?: false+ }+ ),+ PermissionItem(+ "Usage Access",+ "Read app usage and data stats",+ null,+ "special:usage_access",+ { c ->+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {+ val appOps = c.getSystemService(Context.APP_OPS_SERVICE) as? AppOpsManager+ appOps?.checkOpNoThrow(+ AppOpsManager.OPSTR_GET_USAGE_STATS,+ android.os.Process.myUid(), c.packageName+ ) == AppOpsManager.MODE_ALLOWED+ } else {+ true+ }+ }+ ),+ PermissionItem(+ "Device Admin",+ "Lock screen, enforce password policy",+ null,+ "special:device_admin",+ { c ->+ val dpm = c.getSystemService(Context.DEVICE_POLICY_SERVICE) as? DevicePolicyManager+ dpm?.isAdminActive(ComponentName(c, GotchaDeviceAdminReceiver::class.java)) ?: false+ }+ ))- )),- PermissionGroup("System Access", listOf(- PermissionItem(- "Accessibility", "Read screen, tap, swipe, type",- null, "special:accessibility_access",- { c ->- val expected = "${c.packageName}/com.gotcha.service.GotchaAccessibilityService"- val enabled = Settings.Secure.getString(- c.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES- ) ?: ""- enabled.contains(expected, ignoreCase = true)- }- ),- PermissionItem(- "Notification Listener", "Read and dismiss notifications, media control",- null, "special:notification_listener_access",- { c ->- val expected = c.packageName- val enabled = Settings.Secure.getString(- c.contentResolver, "enabled_notification_listeners"- ) ?: ""- enabled.contains(expected, ignoreCase = true)- }- ),- PermissionItem(- "Display Over Apps", "Show floating overlays",- null, "special:overlay_access",- { c -> Settings.canDrawOverlays(c) }- ),- PermissionItem(- "VPN", "Block all network traffic (firewall kill-switch)",- null, "special:vpn_consent",- { c ->- try {- val cm = c.getSystemService(Context.CONNECTIVITY_SERVICE) as? android.net.ConnectivityManager- cm?.let { mgr ->- val network = mgr.activeNetwork- if (network != null) {- mgr.getNetworkCapabilities(network)- ?.hasTransport(android.net.NetworkCapabilities.TRANSPORT_VPN) ?: false- } else false- } ?: false- } catch (_: SecurityException) { false }- }+ ),+ PermissionGroup(+ "System Access",+ listOf(+ PermissionItem(+ "Accessibility",+ "Read screen, tap, swipe, type",+ null,+ "special:accessibility_access",+ { c ->+ val expected = "${c.packageName}/com.gotcha.service.GotchaAccessibilityService"+ val enabled = Settings.Secure.getString(+ c.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES+ ) ?: ""+ enabled.contains(expected, ignoreCase = true)+ }+ ),+ PermissionItem(+ "Notification Listener",+ "Read and dismiss notifications, media control",+ null,+ "special:notification_listener_access",+ { c ->+ val expected = c.packageName+ val enabled = Settings.Secure.getString(+ c.contentResolver, "enabled_notification_listeners"+ ) ?: ""+ enabled.contains(expected, ignoreCase = true)+ }+ ),+ PermissionItem(+ "Display Over Apps",+ "Show floating overlays",+ null,+ "special:overlay_access",+ { c -> Settings.canDrawOverlays(c) }+ ),+ PermissionItem(+ "VPN",+ "Block all network traffic (firewall kill-switch)",+ null,+ "special:vpn_consent",+ { c ->+ try {+ val cm = c.getSystemService(Context.CONNECTIVITY_SERVICE) as? android.net.ConnectivityManager+ cm?.let { mgr ->+ val network = mgr.activeNetwork+ if (network != null) {+ mgr.getNetworkCapabilities(network)+ ?.hasTransport(android.net.NetworkCapabilities.TRANSPORT_VPN) ?: false+ } else {+ false+ }+ } ?: false+ } catch (_: SecurityException) { false }+ }+ ))- ))+ ))private fun checkPerm(context: Context, permission: String): Boolean =diff --git a/app/src/main/java/com/gotcha/ui/PermissionsSection.kt b/app/src/main/java/com/gotcha/ui/PermissionsSection.ktindex 1ea49cd..aa4cf6b 100644--- a/app/src/main/java/com/gotcha/ui/PermissionsSection.kt+++ b/app/src/main/java/com/gotcha/ui/PermissionsSection.kt@@ -1,12 +1,11 @@package com.gotcha.ui+import android.app.admin.DevicePolicyManager+import android.content.ComponentNameimport android.content.Intentimport android.net.Uriimport android.net.VpnServiceimport android.os.Build-import android.provider.Settings as AndroidSettings-import android.app.admin.DevicePolicyManager-import android.content.ComponentNameimport android.widget.Toastimport androidx.activity.compose.rememberLauncherForActivityResultimport androidx.activity.result.contract.ActivityResultContracts@@ -36,11 +35,12 @@ import androidx.lifecycle.Lifecycleimport androidx.lifecycle.LifecycleEventObserverimport com.gotcha.service.GotchaDeviceAdminReceiverimport com.gotcha.tools.ToolResult+import android.provider.Settings as AndroidSettings@Composablefun PermissionsSection(packageName: String) {val context = LocalContext.current- val groups = remember { allPermissionGroups(context) }+ val groups = remember { allPermissionGroups() }var expandedGroups by remember { mutableStateOf(groups.associate { it.name to true }) }// Trigger recomposition on every activity resume so permission state is re-read from Android@@ -159,10 +159,15 @@ private fun openSpecialAccess(context: android.content.Context, marker: String,ToolResult.DND_ACCESS -> Intent(AndroidSettings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS)ToolResult.ACCESSIBILITY_ACCESS -> Intent(AndroidSettings.ACTION_ACCESSIBILITY_SETTINGS)ToolResult.NOTIFICATION_LISTENER_ACCESS -> Intent(AndroidSettings.ACTION_NOTIFICATION_LISTENER_SETTINGS)- ToolResult.ALL_FILES_ACCESS -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)+ ToolResult.ALL_FILES_ACCESS -> 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 -> Intent(AndroidSettings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:$packageName"))+ } else {+ Intent(AndroidSettings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName"))+ }+ ToolResult.OVERLAY_ACCESS -> Intent(+ AndroidSettings.ACTION_MANAGE_OVERLAY_PERMISSION,+ Uri.parse("package:$packageName")+ )ToolResult.DEVICE_ADMIN -> Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN).putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,ComponentName(context, GotchaDeviceAdminReceiver::class.java)diff --git a/app/src/main/java/com/gotcha/ui/SessionsScreen.kt b/app/src/main/java/com/gotcha/ui/SessionsScreen.ktindex 7223379..b605871 100644--- a/app/src/main/java/com/gotcha/ui/SessionsScreen.kt+++ b/app/src/main/java/com/gotcha/ui/SessionsScreen.kt@@ -1,7 +1,15 @@package com.gotcha.uiimport androidx.compose.foundation.clickable-import androidx.compose.foundation.layout.*+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.widthimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.itemsimport androidx.compose.material.icons.Icons@@ -9,8 +17,23 @@ import androidx.compose.material.icons.filled.Addimport androidx.compose.material.icons.filled.Deleteimport androidx.compose.material.icons.filled.Settingsimport androidx.compose.material.icons.outlined.Adjust-import androidx.compose.material3.*-import androidx.compose.runtime.*+import androidx.compose.material3.AlertDialog+import androidx.compose.material3.Button+import androidx.compose.material3.ButtonDefaults+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.FloatingActionButton+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Scaffold+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.material3.TopAppBar+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.text.style.TextOverflow@@ -41,11 +64,16 @@ fun SessionsScreen(IconButton(onClick = { onToggleAssistiveBall(!assistiveBallEnabled) }) {Icon(Icons.Outlined.Adjust,- contentDescription = if (assistiveBallEnabled)- "Turn off assistive ball" else "Turn on assistive ball",- tint = if (assistiveBallEnabled)+ contentDescription = if (assistiveBallEnabled) {+ "Turn off assistive ball"+ } else {+ "Turn on assistive ball"+ },+ tint = if (assistiveBallEnabled) {MaterialTheme.colorScheme.primary- else MaterialTheme.colorScheme.onSurfaceVariant+ } else {+ MaterialTheme.colorScheme.onSurfaceVariant+ })}IconButton(onClick = onOpenSettings) {diff --git a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt b/app/src/main/java/com/gotcha/ui/SettingsScreen.ktindex 3ed54ae..ddf02b8 100644--- a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt+++ b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt@@ -51,7 +51,9 @@ fun SettingsScreen(onTestConnection: suspend (Settings) -> Result<String>,onClearLlmCache: () -> Unit,onBack: () -> Unit,- onRefreshAudioModels: suspend (Settings) -> Pair<List<AudioModel>, List<AudioModel>> = { Pair(emptyList(), emptyList()) },+ onRefreshAudioModels: suspend (+ Settings+ ) -> Pair<List<AudioModel>, List<AudioModel>> = { Pair(emptyList(), emptyList()) },packageName: String = "") {var apiKey by remember { mutableStateOf(initial.apiKey) }@@ -131,8 +133,11 @@ fun SettingsScreen(onValueChange = { apiKey = it },label = { Text("API key") },singleLine = true,- visualTransformation = if (showKey) VisualTransformation.None- else PasswordVisualTransformation(),+ visualTransformation = if (showKey) {+ VisualTransformation.None+ } else {+ PasswordVisualTransformation()+ },trailingIcon = {TextButton(onClick = { showKey = !showKey }) {Text(if (showKey) "Hide" else "Show")@@ -272,7 +277,11 @@ fun SettingsScreen(onValueChange = {},readOnly = true,label = { Text("TTS Model") },- trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = ttsModelExpanded) },+ trailingIcon = {+ ExposedDropdownMenuDefaults.TrailingIcon(+ expanded = ttsModelExpanded+ )+ },modifier = Modifier.fillMaxWidth().menuAnchor())ExposedDropdownMenu(@@ -343,7 +352,11 @@ fun SettingsScreen(onValueChange = {},readOnly = true,label = { Text("STT Model") },- trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = sttModelExpanded) },+ trailingIcon = {+ ExposedDropdownMenuDefaults.TrailingIcon(+ expanded = sttModelExpanded+ )+ },modifier = Modifier.fillMaxWidth().menuAnchor())ExposedDropdownMenu(diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.ymlindex 259b1df..4a244fe 100644--- a/config/detekt/detekt.yml+++ b/config/detekt/detekt.yml@@ -1,5 +1,8 @@# Overrides on top of detekt's default config (buildUponDefaultConfig = true in app/build.gradle.kts).# Keep this file small: only deviations from defaults belong here.+# No baseline file: the whole repo must pass. Thresholds below are fitted to the+# codebase's idioms (Compose UI, tool-dispatch architecture); tighten over time,+# never loosen without review.build:maxIssues: 0@@ -7,18 +10,47 @@ build:style:MaxLineLength:maxLineLength: 140+ excludeCommentStatements: true+ # Compose UI code is full of literal dp/sp/fraction values; extracting each into a+ # named constant hurts readability more than it helps.MagicNumber:- excludes: ["**/test/**"]+ active: false+ # Tool implementations use early `return err(...)` guard returns throughout; counting+ # returns fights that idiom.ReturnCount:- max: 4+ active: false+ DestructuringDeclarationWithTooManyEntries:+ maxDestructuringEntries: 4+ LoopWithTooManyJumpStatements:+ maxJumpCount: 3++naming:+ # Composable functions are PascalCase by convention.+ FunctionNaming:+ ignoreAnnotated: ["Composable"]++empty-blocks:+ # Android listener interfaces (RecognitionListener, LocationListener, ...) force+ # no-op overrides.+ EmptyFunctionBlock:+ ignoreOverridden: truecomplexity:+ CyclomaticComplexMethod:+ threshold: 25+ ignoreAnnotated: ["Composable"]LongMethod:- threshold: 80+ threshold: 110+ ignoreAnnotated: ["Composable"]LongParameterList:functionThreshold: 8constructorThreshold: 8ignoreDefaultParameters: true+ ignoreAnnotated: ["Composable"]+ NestedBlockDepth:+ threshold: 6+ ComplexCondition:+ threshold: 7TooManyFunctions:thresholdInFiles: 20thresholdInClasses: 20