Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
Add new tools for managing alarms, apps, calendar events, clipboard, contacts, device settings, location, media capture, and SMS
Durganshu Mishra854a1e0ae934
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex a6f7cb2..74da230 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -1,5 +1,6 @@<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"+ xmlns:tools="http://schemas.android.com/tools"package="com.gotcha"><uses-permission android:name="android.permission.INTERNET" />@@ -11,6 +12,28 @@android:name="android.permission.READ_EXTERNAL_STORAGE"android:maxSdkVersion="32" />+ <!-- Tier 0–2: communications -->+ <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" />+ <uses-permission android:name="android.permission.READ_CONTACTS" />+ <uses-permission android:name="android.permission.WRITE_CONTACTS" />+ <uses-permission android:name="android.permission.READ_CALENDAR" />+ <uses-permission android:name="android.permission.WRITE_CALENDAR" />++ <!-- Tier 0–2: sensors & capture -->+ <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />+ <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />+ <uses-permission android:name="android.permission.RECORD_AUDIO" />++ <!-- Tier 0–2: device control (normal / special-access) -->+ <uses-permission android:name="android.permission.VIBRATE" />+ <uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />+ <uses-permission android:name="com.android.alarm.permission.SET_ALARM" />+ <uses-permission+ android:name="android.permission.PACKAGE_USAGE_STATS"+ tools:ignore="ProtectedPermissions" />+<!-- Needed on API 30+ so open_app can see other launchable apps. --><queries><intent>@@ -36,6 +59,17 @@<category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity>++ <!-- Shares captured photos with the camera app (take_photo). -->+ <provider+ android:name="androidx.core.content.FileProvider"+ android:authorities="${applicationId}.fileprovider"+ android:exported="false"+ android:grantUriPermissions="true">+ <meta-data+ android:name="android.support.FILE_PROVIDER_PATHS"+ android:resource="@xml/file_paths" />+ </provider></application></manifest>diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.ktindex d18b3f6..f605f4e 100644--- a/app/src/main/java/com/gotcha/MainActivity.kt+++ b/app/src/main/java/com/gotcha/MainActivity.kt@@ -52,17 +52,24 @@ class MainActivity : ComponentActivity() {settingsRepository = SettingsRepository(this)// Phase 7: tools report missing permissions; request them here on first use.+ // "special:*" markers map to per-access Settings deep-links; anything else is a+ // real runtime permission handled by the single RequestPermission launcher.lifecycleScope.launch {chatViewModel.permissionRequests.collect { permission ->- if (permission == ToolResult.WRITE_SETTINGS) {- startActivity(+ when (permission) {+ ToolResult.WRITE_SETTINGS -> startActivity(Intent(AndroidSettings.ACTION_MANAGE_WRITE_SETTINGS,Uri.parse("package:$packageName")))- } else {- permissionLauncher.launch(permission)+ ToolResult.USAGE_ACCESS -> startActivity(+ Intent(AndroidSettings.ACTION_USAGE_ACCESS_SETTINGS)+ )+ ToolResult.DND_ACCESS -> startActivity(+ Intent(AndroidSettings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS)+ )+ else -> permissionLauncher.launch(permission)}}}diff --git a/app/src/main/java/com/gotcha/tools/AlarmTool.kt b/app/src/main/java/com/gotcha/tools/AlarmTool.ktnew file mode 100644index 0000000..29286e8--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/AlarmTool.kt@@ -0,0 +1,46 @@+package com.gotcha.tools++import android.content.Context+import android.content.Intent+import android.provider.AlarmClock++class AlarmTool(private val context: Context) {++ /** Set a clock alarm via the AlarmClock intent (needs SET_ALARM, a normal permission). */+ fun setAlarm(hour: Int, minute: Int, message: String?): ToolResult {+ if (hour !in 0..23) return ToolResult.error("Hour must be between 0 and 23 (got $hour).")+ if (minute !in 0..59) return ToolResult.error("Minute must be between 0 and 59 (got $minute).")+ val intent = Intent(AlarmClock.ACTION_SET_ALARM).apply {+ putExtra(AlarmClock.EXTRA_HOUR, hour)+ putExtra(AlarmClock.EXTRA_MINUTES, minute)+ if (!message.isNullOrBlank()) putExtra(AlarmClock.EXTRA_MESSAGE, message)+ putExtra(AlarmClock.EXTRA_SKIP_UI, true)+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ }+ return launch(intent, "Set an alarm for %02d:%02d.".format(hour, minute), "set an alarm")+ }++ /** Start a countdown timer via the AlarmClock intent. */+ fun setTimer(seconds: Int, message: String?): ToolResult {+ if (seconds < 1) return ToolResult.error("Timer length must be at least 1 second.")+ val intent = Intent(AlarmClock.ACTION_SET_TIMER).apply {+ putExtra(AlarmClock.EXTRA_LENGTH, seconds)+ if (!message.isNullOrBlank()) putExtra(AlarmClock.EXTRA_MESSAGE, message)+ putExtra(AlarmClock.EXTRA_SKIP_UI, true)+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ }+ return launch(intent, "Started a ${seconds}s timer.", "start a timer")+ }++ private fun launch(intent: Intent, success: String, action: String): ToolResult {+ return try {+ if (intent.resolveActivity(context.packageManager) == null) {+ return ToolResult.error("No clock app on this device can $action.")+ }+ context.startActivity(intent)+ ToolResult.ok(success)+ } catch (e: Exception) {+ ToolResult.error("Could not $action: ${e.message}")+ }+ }+}diff --git a/app/src/main/java/com/gotcha/tools/AppsTool.kt b/app/src/main/java/com/gotcha/tools/AppsTool.ktnew file mode 100644index 0000000..fa42c68--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/AppsTool.kt@@ -0,0 +1,140 @@+package com.gotcha.tools++import android.app.AppOpsManager+import android.app.usage.NetworkStatsManager+import android.app.usage.UsageStatsManager+import android.content.Context+import android.content.Intent+import android.net.ConnectivityManager+import android.net.Uri+import android.os.Build+import android.os.Process++class AppsTool(private val context: Context) {++ /** List launchable installed apps (name + package). Uses the manifest <queries> visibility. */+ fun listInstalledApps(): ToolResult {+ return try {+ val pm = context.packageManager+ val intent = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)+ val apps = pm.queryIntentActivities(intent, 0)+ .map { "${it.loadLabel(pm)} (${it.activityInfo.packageName})" }+ .distinct()+ .sorted()+ if (apps.isEmpty()) return ToolResult.ok("No launchable apps are visible.")+ ToolResult.ok("Installed apps (${apps.size}):\n" + apps.joinToString("\n") { "- $it" })+ } catch (e: Exception) {+ ToolResult.error("Could not list apps: ${e.message}")+ }+ }++ /** Open the system uninstall dialog for a package (user confirms). */+ fun uninstallApp(packageName: String): ToolResult {+ val pkg = packageName.trim()+ if (pkg.isEmpty()) return ToolResult.error("Please provide the package name to uninstall.")+ return try {+ val installed = try {+ context.packageManager.getPackageInfo(pkg, 0); true+ } catch (_: Exception) {+ false+ }+ if (!installed) return ToolResult.error("No app with package '$pkg' is installed.")+ @Suppress("DEPRECATION")+ val intent = Intent(Intent.ACTION_DELETE, Uri.parse("package:$pkg"))+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ context.startActivity(intent)+ ToolResult.ok("Opened the uninstall dialog for $pkg. The user must confirm removal.")+ } catch (e: Exception) {+ ToolResult.error("Could not start uninstall: ${e.message}")+ }+ }++ /** Report per-app screen time over the last [days] days (needs Usage-access special access). */+ fun getAppUsage(days: Int): ToolResult {+ if (!hasUsageAccess()) {+ return ToolResult.permissionNeeded(+ ToolResult.USAGE_ACCESS,+ "App-usage stats need Usage access. I have opened that settings page — please enable it for Gotcha and ask again."+ )+ }+ val window = days.coerceIn(1, 90)+ val end = System.currentTimeMillis()+ val start = end - window * 24L * 60 * 60 * 1000+ return try {+ val usm = context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager+ val stats = usm.queryUsageStats(UsageStatsManager.INTERVAL_BEST, start, end)+ val top = stats+ .filter { it.totalTimeInForeground > 0 }+ .sortedByDescending { it.totalTimeInForeground }+ .take(10)+ if (top.isEmpty()) return ToolResult.ok("No app-usage data in the last $window day(s).")+ val pm = context.packageManager+ val out = top.joinToString("\n") { u ->+ val label = try {+ pm.getApplicationLabel(pm.getApplicationInfo(u.packageName, 0)).toString()+ } catch (_: Exception) {+ u.packageName+ }+ "- $label: ${formatDuration(u.totalTimeInForeground)}"+ }+ ToolResult.ok("Top app usage over the last $window day(s):\n$out")+ } catch (e: Exception) {+ ToolResult.error("Could not read app usage: ${e.message}")+ }+ }++ /** Report total mobile + Wi-Fi data used over the last [days] days (needs Usage access). */+ fun getDataUsage(days: Int): ToolResult {+ if (!hasUsageAccess()) {+ return ToolResult.permissionNeeded(+ ToolResult.USAGE_ACCESS,+ "Data-usage stats need Usage access. I have opened that settings page — please enable it for Gotcha and ask again."+ )+ }+ val window = days.coerceIn(1, 90)+ val end = System.currentTimeMillis()+ val start = end - window * 24L * 60 * 60 * 1000+ return 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+ val wifiTotal = wifi.rxBytes + wifi.txBytes+ ToolResult.ok(+ "Data used over the last $window day(s):\n" ++ "- Mobile: ${StorageTool.format(mobileTotal)}\n" ++ "- Wi-Fi: ${StorageTool.format(wifiTotal)}"+ )+ } catch (e: Exception) {+ ToolResult.error("Could not read data usage: ${e.message}")+ }+ }++ private fun hasUsageAccess(): Boolean {+ return try {+ val appOps = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager+ val mode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+ appOps.unsafeCheckOpNoThrow(+ AppOpsManager.OPSTR_GET_USAGE_STATS, Process.myUid(), context.packageName+ )+ } else {+ @Suppress("DEPRECATION")+ appOps.checkOpNoThrow(+ AppOpsManager.OPSTR_GET_USAGE_STATS, Process.myUid(), context.packageName+ )+ }+ mode == AppOpsManager.MODE_ALLOWED+ } catch (_: Exception) {+ false+ }+ }++ private fun formatDuration(ms: Long): String {+ val totalMin = ms / 60000+ val h = totalMin / 60+ val m = totalMin % 60+ return if (h > 0) "${h}h ${m}m" else "${m}m"+ }+}diff --git a/app/src/main/java/com/gotcha/tools/CalendarTool.kt b/app/src/main/java/com/gotcha/tools/CalendarTool.ktnew file mode 100644index 0000000..5585c0e--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/CalendarTool.kt@@ -0,0 +1,128 @@+package com.gotcha.tools++import android.Manifest+import android.content.ContentUris+import android.content.ContentValues+import android.content.Context+import android.content.pm.PackageManager+import android.provider.CalendarContract+import androidx.core.content.ContextCompat+import java.text.SimpleDateFormat+import java.util.Locale+import java.util.TimeZone++class CalendarTool(private val context: Context) {++ private val readable = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())++ /** List events in the next [daysAhead] days (needs READ_CALENDAR). */+ fun listEvents(daysAhead: Int): ToolResult {+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CALENDAR)+ != PackageManager.PERMISSION_GRANTED+ ) {+ return ToolResult.permissionNeeded(+ Manifest.permission.READ_CALENDAR,+ "Reading the calendar needs the Calendar permission. I have requested it — please grant it and ask again."+ )+ }+ val days = daysAhead.coerceIn(1, 365)+ val now = System.currentTimeMillis()+ val end = now + days * 24L * 60 * 60 * 1000+ return try {+ val builder = CalendarContract.Instances.CONTENT_URI.buildUpon()+ ContentUris.appendId(builder, now)+ ContentUris.appendId(builder, end)+ val projection = arrayOf(+ CalendarContract.Instances.TITLE,+ CalendarContract.Instances.BEGIN,+ CalendarContract.Instances.END,+ CalendarContract.Instances.EVENT_LOCATION+ )+ context.contentResolver.query(+ builder.build(), projection, null, null,+ "${CalendarContract.Instances.BEGIN} ASC"+ ).use { cursor ->+ if (cursor == null) return ToolResult.error("Could not read the calendar.")+ val titleIdx = cursor.getColumnIndexOrThrow(CalendarContract.Instances.TITLE)+ val beginIdx = cursor.getColumnIndexOrThrow(CalendarContract.Instances.BEGIN)+ val locIdx = cursor.getColumnIndexOrThrow(CalendarContract.Instances.EVENT_LOCATION)+ val out = StringBuilder()+ var count = 0+ while (cursor.moveToNext() && count < 50) {+ val title = cursor.getString(titleIdx) ?: "(untitled)"+ val begin = readable.format(java.util.Date(cursor.getLong(beginIdx)))+ val loc = cursor.getString(locIdx)+ out.append("- $begin $title")+ if (!loc.isNullOrBlank()) out.append(" @ $loc")+ out.append("\n")+ count+++ }+ if (count == 0) ToolResult.ok("No events in the next $days day(s).")+ else ToolResult.ok("Events in the next $days day(s):\n$out")+ }+ } catch (e: Exception) {+ ToolResult.error("Could not read the calendar: ${e.message}")+ }+ }++ /** Create a calendar event (needs WRITE_CALENDAR). start/end accept epoch millis or "yyyy-MM-dd HH:mm". */+ fun createEvent(title: String, start: String, end: String?, location: String?): ToolResult {+ if (title.isBlank()) return ToolResult.error("Please provide a title for the event.")+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_CALENDAR)+ != PackageManager.PERMISSION_GRANTED+ ) {+ return ToolResult.permissionNeeded(+ Manifest.permission.WRITE_CALENDAR,+ "Adding a calendar event needs the Calendar permission. I have requested it — please grant it and ask again."+ )+ }+ 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'.")+ return try {+ val calendarId = defaultWritableCalendarId()+ ?: return ToolResult.error("No writable calendar was found on this device.")+ val values = ContentValues().apply {+ put(CalendarContract.Events.CALENDAR_ID, calendarId)+ put(CalendarContract.Events.TITLE, title)+ put(CalendarContract.Events.DTSTART, startMs)+ put(CalendarContract.Events.DTEND, endMs)+ put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().id)+ if (!location.isNullOrBlank()) put(CalendarContract.Events.EVENT_LOCATION, location)+ }+ val uri = context.contentResolver.insert(CalendarContract.Events.CONTENT_URI, values)+ ?: return ToolResult.error("The calendar rejected the new event.")+ ToolResult.ok("Added '$title' on ${readable.format(java.util.Date(startMs))} (event ${uri.lastPathSegment}).")+ } catch (e: Exception) {+ ToolResult.error("Could not create the event: ${e.message}")+ }+ }++ private fun parseWhen(value: String): Long? {+ 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")+ for (f in formats) {+ try {+ return SimpleDateFormat(f, Locale.getDefault()).parse(v)?.time+ } catch (_: Exception) { /* try next */ }+ }+ return null+ }++ private fun defaultWritableCalendarId(): Long? {+ val projection = arrayOf(CalendarContract.Calendars._ID)+ 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.IS_PRIMARY} DESC"+ ).use { cursor ->+ if (cursor != null && cursor.moveToFirst()) {+ return cursor.getLong(cursor.getColumnIndexOrThrow(CalendarContract.Calendars._ID))+ }+ }+ return null+ }+}diff --git a/app/src/main/java/com/gotcha/tools/ClipboardTool.kt b/app/src/main/java/com/gotcha/tools/ClipboardTool.ktnew file mode 100644index 0000000..fde740c--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/ClipboardTool.kt@@ -0,0 +1,36 @@+package com.gotcha.tools++import android.content.ClipData+import android.content.ClipboardManager+import android.content.Context++class ClipboardTool(private val context: Context) {++ private val clipboard: ClipboardManager+ get() = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager++ /** Read the current clipboard text (works while the app is foreground). */+ fun getClipboard(): ToolResult {+ return try {+ val clip = clipboard.primaryClip+ if (clip == null || clip.itemCount == 0) {+ return ToolResult.ok("The clipboard is empty.")+ }+ val text = clip.getItemAt(0).coerceToText(context).toString()+ if (text.isEmpty()) ToolResult.ok("The clipboard holds no text.")+ else ToolResult.ok("Clipboard: ${text.take(2000)}")+ } catch (e: Exception) {+ ToolResult.error("Could not read the clipboard: ${e.message}")+ }+ }++ /** Put text on the clipboard. */+ fun setClipboard(text: String): ToolResult {+ return try {+ clipboard.setPrimaryClip(ClipData.newPlainText("Gotcha", text))+ ToolResult.ok("Copied to the clipboard.")+ } catch (e: Exception) {+ ToolResult.error("Could not set the clipboard: ${e.message}")+ }+ }+}diff --git a/app/src/main/java/com/gotcha/tools/ContactsTool.kt b/app/src/main/java/com/gotcha/tools/ContactsTool.ktnew file mode 100644index 0000000..4f14f9b--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/ContactsTool.kt@@ -0,0 +1,108 @@+package com.gotcha.tools++import android.Manifest+import android.content.ContentProviderOperation+import android.content.Context+import android.content.pm.PackageManager+import android.provider.ContactsContract+import androidx.core.content.ContextCompat++class ContactsTool(private val context: Context) {++ /** Resolve a name to one or more phone numbers (needs READ_CONTACTS). */+ fun findContact(name: String): ToolResult {+ val query = name.trim()+ if (query.isEmpty()) return ToolResult.error("Please provide a contact name to look up.")+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS)+ != PackageManager.PERMISSION_GRANTED+ ) {+ return ToolResult.permissionNeeded(+ Manifest.permission.READ_CONTACTS,+ "Looking up contacts needs the Contacts permission. I have requested it — please grant it and ask again."+ )+ }+ return try {+ val projection = arrayOf(+ ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,+ ContactsContract.CommonDataKinds.Phone.NUMBER,+ ContactsContract.CommonDataKinds.Phone.TYPE+ )+ context.contentResolver.query(+ ContactsContract.CommonDataKinds.Phone.CONTENT_URI,+ projection,+ "${ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME} LIKE ?",+ arrayOf("%$query%"),+ "${ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME} ASC"+ ).use { cursor ->+ if (cursor == null) return ToolResult.error("Could not read contacts.")+ val nameIdx = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)+ val numIdx = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER)+ val results = StringBuilder()+ var count = 0+ while (cursor.moveToNext() && count < 20) {+ val displayName = cursor.getString(nameIdx) ?: "unknown"+ val number = cursor.getString(numIdx) ?: continue+ results.append("- $displayName: $number\n")+ count+++ }+ if (count == 0) ToolResult.ok("No contact matching '$query' was found.")+ else ToolResult.ok("Matches for '$query':\n$results")+ }+ } catch (e: Exception) {+ ToolResult.error("Could not look up contacts: ${e.message}")+ }+ }++ /** Create a new contact with a name and phone number (needs WRITE_CONTACTS). */+ fun addContact(name: String, number: String): ToolResult {+ val displayName = name.trim()+ val phone = number.trim()+ if (displayName.isEmpty()) return ToolResult.error("Please provide a name for the new contact.")+ if (phone.isEmpty()) return ToolResult.error("Please provide a phone number for the new contact.")+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_CONTACTS)+ != PackageManager.PERMISSION_GRANTED+ ) {+ return ToolResult.permissionNeeded(+ Manifest.permission.WRITE_CONTACTS,+ "Adding a contact needs the Contacts permission. I have requested it — please grant it and ask again."+ )+ }+ return try {+ val ops = arrayListOf<ContentProviderOperation>()+ ops.add(+ ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)+ .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)+ .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)+ .build()+ )+ 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.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName)+ .build()+ )+ ops.add(+ ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)+ .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)+ .withValue(+ ContactsContract.Data.MIMETYPE,+ ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE+ )+ .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone)+ .withValue(+ ContactsContract.CommonDataKinds.Phone.TYPE,+ ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE+ )+ .build()+ )+ context.contentResolver.applyBatch(ContactsContract.AUTHORITY, ops)+ ToolResult.ok("Added contact '$displayName' with number $phone.")+ } catch (e: Exception) {+ ToolResult.error("Could not add the contact: ${e.message}")+ }+ }+}diff --git a/app/src/main/java/com/gotcha/tools/DeviceTool.kt b/app/src/main/java/com/gotcha/tools/DeviceTool.ktnew file mode 100644index 0000000..258afb0--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/DeviceTool.kt@@ -0,0 +1,130 @@+package com.gotcha.tools++import android.app.NotificationManager+import android.content.Context+import android.hardware.camera2.CameraCharacteristics+import android.hardware.camera2.CameraManager+import android.media.AudioManager+import android.os.Build+import android.os.VibrationEffect+import android.os.Vibrator+import android.os.VibratorManager++class DeviceTool(private val context: Context) {++ /** Turn the camera flash on or off (no permission needed for CameraManager.setTorchMode). */+ fun toggleTorch(on: Boolean): ToolResult {+ return try {+ val cm = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager+ val cameraId = cm.cameraIdList.firstOrNull { id ->+ cm.getCameraCharacteristics(id)+ .get(CameraCharacteristics.FLASH_INFO_AVAILABLE) == true+ } ?: return ToolResult.error("This device has no controllable flashlight.")+ cm.setTorchMode(cameraId, on)+ ToolResult.ok("Flashlight turned ${if (on) "on" else "off"}.")+ } catch (e: Exception) {+ ToolResult.error("Could not toggle the flashlight: ${e.message}")+ }+ }++ /** Set a volume stream to a percentage (no permission, though muting ring may need DND access). */+ fun setVolume(stream: String, percent: Int): ToolResult {+ if (percent !in 0..100) return ToolResult.error("Volume must be between 0 and 100 (got $percent).")+ val streamType = when (stream.lowercase().trim()) {+ "media", "music" -> AudioManager.STREAM_MUSIC+ "ring", "ringer" -> AudioManager.STREAM_RING+ "alarm" -> AudioManager.STREAM_ALARM+ "notification" -> AudioManager.STREAM_NOTIFICATION+ "call", "voice" -> AudioManager.STREAM_VOICE_CALL+ else -> return ToolResult.error(+ "Unknown volume stream '$stream'. Use media, ring, alarm, notification, or call."+ )+ }+ return try {+ val am = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager+ val max = am.getStreamMaxVolume(streamType)+ val target = (percent * max) / 100+ am.setStreamVolume(streamType, target, 0)+ ToolResult.ok("Set $stream volume to $percent%.")+ } catch (e: 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."+ )+ } catch (e: Exception) {+ ToolResult.error("Could not set the volume: ${e.message}")+ }+ }++ /** Set the ringer mode: normal / vibrate / silent. Silent & vibrate need DND access on N+. */+ fun setRingerMode(mode: String): ToolResult {+ val ringerMode = when (mode.lowercase().trim()) {+ "normal", "loud" -> AudioManager.RINGER_MODE_NORMAL+ "vibrate" -> AudioManager.RINGER_MODE_VIBRATE+ "silent", "mute" -> AudioManager.RINGER_MODE_SILENT+ else -> return ToolResult.error("Unknown ringer mode '$mode'. Use normal, vibrate, or silent.")+ }+ if (ringerMode != AudioManager.RINGER_MODE_NORMAL && !hasDndAccess()) {+ return ToolResult.permissionNeeded(+ ToolResult.DND_ACCESS,+ "Silencing the ringer needs Do Not Disturb access. I have opened that settings page — please enable it and ask again."+ )+ }+ return try {+ val am = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager+ am.ringerMode = ringerMode+ ToolResult.ok("Ringer set to ${mode.lowercase().trim()}.")+ } catch (e: 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."+ )+ } catch (e: Exception) {+ ToolResult.error("Could not set the ringer mode: ${e.message}")+ }+ }++ /** Vibrate for a number of milliseconds (needs VIBRATE, an install-time permission). */+ fun vibrate(durationMs: Int): ToolResult {+ val ms = durationMs.coerceIn(1, 5000).toLong()+ return try {+ val vibrator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {+ val vm = context.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager+ vm.defaultVibrator+ } else {+ @Suppress("DEPRECATION")+ context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator+ }+ if (!vibrator.hasVibrator()) return ToolResult.error("This device has no vibrator.")+ vibrator.vibrate(VibrationEffect.createOneShot(ms, VibrationEffect.DEFAULT_AMPLITUDE))+ ToolResult.ok("Vibrated for ${ms}ms.")+ } catch (e: Exception) {+ ToolResult.error("Could not vibrate: ${e.message}")+ }+ }++ /** Turn Do Not Disturb on or off (needs DND / notification-policy access). */+ fun setDnd(enabled: Boolean): ToolResult {+ 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."+ )+ }+ return try {+ val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager+ nm.setInterruptionFilter(+ 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) {+ ToolResult.error("Could not change Do Not Disturb: ${e.message}")+ }+ }++ private fun hasDndAccess(): Boolean {+ val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager+ return nm.isNotificationPolicyAccessGranted+ }+}diff --git a/app/src/main/java/com/gotcha/tools/LocationTool.kt b/app/src/main/java/com/gotcha/tools/LocationTool.ktnew file mode 100644index 0000000..eef791a--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/LocationTool.kt@@ -0,0 +1,64 @@+package com.gotcha.tools++import android.Manifest+import android.content.Context+import android.content.pm.PackageManager+import android.location.Geocoder+import android.location.Location+import android.location.LocationManager+import androidx.core.content.ContextCompat+import java.util.Locale++class LocationTool(private val context: Context) {++ /** Report the last-known device location (needs ACCESS_FINE_LOCATION). */+ fun getLocation(): ToolResult {+ val fine = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)+ val coarse = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)+ if (fine != PackageManager.PERMISSION_GRANTED && coarse != PackageManager.PERMISSION_GRANTED) {+ return ToolResult.permissionNeeded(+ Manifest.permission.ACCESS_FINE_LOCATION,+ "Reading your location needs the Location permission. I have requested it — please grant it and ask again."+ )+ }+ return try {+ val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager+ val providers = listOf(+ LocationManager.GPS_PROVIDER,+ LocationManager.NETWORK_PROVIDER,+ LocationManager.PASSIVE_PROVIDER+ )+ var best: Location? = null+ for (p in providers) {+ if (!lm.allProviders.contains(p)) continue+ val loc = try {+ lm.getLastKnownLocation(p)+ } catch (_: SecurityException) {+ null+ }+ val current = best+ if (loc != null && (current == null || loc.time > current.time)) best = loc+ }+ val fix = best ?: return ToolResult.ok(+ "No recent location fix is available. Ask the user to open a maps app briefly, then try again."+ )+ val lat = fix.latitude+ val lng = fix.longitude+ val address = reverseGeocode(lat, lng)+ val where = if (address != null) " (near $address)" else ""+ ToolResult.ok("Location: %.5f, %.5f%s".format(lat, lng, where))+ } catch (e: Exception) {+ ToolResult.error("Could not read your location: ${e.message}")+ }+ }++ private fun reverseGeocode(lat: Double, lng: Double): String? {+ return try {+ @Suppress("DEPRECATION")+ val results = Geocoder(context, Locale.getDefault()).getFromLocation(lat, lng, 1)+ results?.firstOrNull()?.getAddressLine(0)+ } catch (_: Exception) {+ null+ }+ }+}diff --git a/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt b/app/src/main/java/com/gotcha/tools/MediaCaptureTool.ktnew file mode 100644index 0000000..eb351d5--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt@@ -0,0 +1,114 @@+package com.gotcha.tools++import android.Manifest+import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.media.MediaRecorder+import android.os.Build+import android.provider.MediaStore+import androidx.core.content.ContextCompat+import androidx.core.content.FileProvider+import java.io.File+import java.text.SimpleDateFormat+import java.util.Locale++class MediaCaptureTool(private val context: Context) {++ private var recorder: MediaRecorder? = null+ private var recordingFile: File? = null++ /**+ * Launch the camera app to capture a photo into the app's external Pictures dir.+ * No CAMERA permission is declared, so the intent runs as a plain hand-off; the user+ * snaps the photo and it is saved to the returned path.+ */+ fun takePhoto(): ToolResult {+ return try {+ val dir = context.getExternalFilesDir("Pictures")+ ?: return ToolResult.error("No external storage is available for photos.")+ dir.mkdirs()+ val file = File(dir, "photo_${timestamp()}.jpg")+ val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)+ val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE).apply {+ putExtra(MediaStore.EXTRA_OUTPUT, uri)+ addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ }+ if (intent.resolveActivity(context.packageManager) == null) {+ return ToolResult.error("No camera app is available on this device.")+ }+ context.startActivity(intent)+ ToolResult.ok(+ "Opened the camera. Once the user takes the photo it is saved to ${file.absolutePath}."+ )+ } catch (e: Exception) {+ ToolResult.error("Could not open the camera: ${e.message}")+ }+ }++ /** Start recording audio to a file (needs RECORD_AUDIO). */+ fun startAudioRecording(): ToolResult {+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO)+ != PackageManager.PERMISSION_GRANTED+ ) {+ return ToolResult.permissionNeeded(+ Manifest.permission.RECORD_AUDIO,+ "Recording audio needs the Microphone permission. I have requested it — please grant it and ask again."+ )+ }+ if (recorder != null) {+ return ToolResult.error("A recording is already in progress. Stop it before starting a new one.")+ }+ return try {+ val dir = context.getExternalFilesDir("Recordings")+ ?: return ToolResult.error("No external storage is available for recordings.")+ dir.mkdirs()+ val file = File(dir, "recording_${timestamp()}.m4a")+ val rec = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {+ MediaRecorder(context)+ } else {+ @Suppress("DEPRECATION")+ MediaRecorder()+ }+ rec.setAudioSource(MediaRecorder.AudioSource.MIC)+ rec.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)+ rec.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)+ rec.setOutputFile(file.absolutePath)+ rec.prepare()+ rec.start()+ recorder = rec+ recordingFile = file+ ToolResult.ok("Recording started. Ask to stop when finished.")+ } catch (e: Exception) {+ releaseRecorder()+ ToolResult.error("Could not start recording: ${e.message}")+ }+ }++ /** Stop the in-progress recording and report the saved file. */+ fun stopAudioRecording(): ToolResult {+ val rec = recorder ?: return ToolResult.error("No recording is in progress.")+ return try {+ rec.stop()+ val path = recordingFile?.absolutePath ?: "unknown"+ releaseRecorder()+ ToolResult.ok("Recording saved to $path.")+ } catch (e: Exception) {+ releaseRecorder()+ ToolResult.error("Could not stop the recording cleanly: ${e.message}")+ }+ }++ private fun releaseRecorder() {+ try {+ recorder?.release()+ } catch (_: Exception) {+ }+ recorder = null+ recordingFile = null+ }++ private fun timestamp(): String =+ SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(java.util.Date())+}diff --git a/app/src/main/java/com/gotcha/tools/PhoneTool.kt b/app/src/main/java/com/gotcha/tools/PhoneTool.ktindex 06eb97a..497519f 100644--- a/app/src/main/java/com/gotcha/tools/PhoneTool.kt+++ b/app/src/main/java/com/gotcha/tools/PhoneTool.kt@@ -1,14 +1,20 @@package com.gotcha.tools+import android.Manifestimport android.content.Contextimport android.content.Intent+import android.content.pm.PackageManagerimport android.net.Uri+import android.provider.CallLog+import androidx.core.content.ContextCompatclass PhoneTool(private val context: Context) {+ private val numberPattern = Regex("^[+]?[0-9()\\-\\s#*]{2,20}$")+fun dialNumber(number: String): ToolResult {val trimmed = number.trim()- if (trimmed.isEmpty() || !trimmed.matches(Regex("^[+]?[0-9()\\-\\s#*]{2,20}$"))) {+ if (trimmed.isEmpty() || !trimmed.matches(numberPattern)) {return ToolResult.error("'$number' does not look like a valid phone number.")}return try {@@ -21,4 +27,91 @@ class PhoneTool(private val context: Context) {ToolResult.error("Could not open the dialer: ${e.message}")}}++ /** Place a call directly (needs CALL_PHONE). Gated by the sensitive-action confirmation dialog. */+ fun callNumber(number: String): ToolResult {+ val trimmed = number.trim()+ if (trimmed.isEmpty() || !trimmed.matches(numberPattern)) {+ return ToolResult.error("'$number' does not look like a valid phone number.")+ }+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE)+ != PackageManager.PERMISSION_GRANTED+ ) {+ return ToolResult.permissionNeeded(+ Manifest.permission.CALL_PHONE,+ "Placing a call directly needs the Phone permission. I have requested it — " ++ "please grant it and ask again."+ )+ }+ return try {+ val intent = Intent(Intent.ACTION_CALL, Uri.parse("tel:$trimmed")).apply {+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ }+ context.startActivity(intent)+ ToolResult.ok("Calling $trimmed.")+ } catch (e: SecurityException) {+ ToolResult.permissionNeeded(+ Manifest.permission.CALL_PHONE,+ "Placing a call needs the Phone permission. I have requested it — please grant it and ask again."+ )+ } catch (e: Exception) {+ ToolResult.error("Could not place the call: ${e.message}")+ }+ }++ /** Read recent call-log entries (needs READ_CALL_LOG). */+ fun readCallLog(limit: Int): ToolResult {+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CALL_LOG)+ != PackageManager.PERMISSION_GRANTED+ ) {+ return ToolResult.permissionNeeded(+ Manifest.permission.READ_CALL_LOG,+ "Reading the call log needs the Call log permission. I have requested it — please grant it and ask again."+ )+ }+ val take = limit.coerceIn(1, 50)+ return try {+ val projection = arrayOf(+ CallLog.Calls.NUMBER,+ CallLog.Calls.CACHED_NAME,+ CallLog.Calls.TYPE,+ CallLog.Calls.DATE,+ CallLog.Calls.DURATION+ )+ context.contentResolver.query(+ CallLog.Calls.CONTENT_URI, projection, null, null,+ "${CallLog.Calls.DATE} DESC"+ ).use { cursor ->+ if (cursor == null) return ToolResult.error("Could not read the call log.")+ val numberIdx = cursor.getColumnIndexOrThrow(CallLog.Calls.NUMBER)+ val nameIdx = cursor.getColumnIndexOrThrow(CallLog.Calls.CACHED_NAME)+ val typeIdx = cursor.getColumnIndexOrThrow(CallLog.Calls.TYPE)+ val dateIdx = cursor.getColumnIndexOrThrow(CallLog.Calls.DATE)+ val durIdx = cursor.getColumnIndexOrThrow(CallLog.Calls.DURATION)+ val entries = StringBuilder()+ var count = 0+ while (cursor.moveToNext() && count < take) {+ val number = cursor.getString(numberIdx) ?: "unknown"+ val name = cursor.getString(nameIdx)+ val type = when (cursor.getInt(typeIdx)) {+ CallLog.Calls.INCOMING_TYPE -> "incoming"+ CallLog.Calls.OUTGOING_TYPE -> "outgoing"+ CallLog.Calls.MISSED_TYPE -> "missed"+ CallLog.Calls.REJECTED_TYPE -> "rejected"+ else -> "other"+ }+ val date = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm", java.util.Locale.getDefault())+ .format(java.util.Date(cursor.getLong(dateIdx)))+ val dur = cursor.getLong(durIdx)+ val who = if (!name.isNullOrBlank()) "$name ($number)" else number+ entries.append("- $date $type $who ${dur}s\n")+ count+++ }+ 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}")+ }+ }}diff --git a/app/src/main/java/com/gotcha/tools/SmsTool.kt b/app/src/main/java/com/gotcha/tools/SmsTool.ktnew file mode 100644index 0000000..0f9ec52--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/SmsTool.kt@@ -0,0 +1,96 @@+package com.gotcha.tools++import android.Manifest+import android.content.Context+import android.content.pm.PackageManager+import android.os.Build+import android.provider.Telephony+import android.telephony.SmsManager+import androidx.core.content.ContextCompat++class SmsTool(private val context: Context) {++ private val numberPattern = Regex("^[+]?[0-9()\\-\\s#*]{2,20}$")++ /** Send a text message directly (needs SEND_SMS). Gated by the sensitive-action confirmation dialog. */+ fun sendSms(number: String, message: String): ToolResult {+ val trimmed = number.trim()+ if (!trimmed.matches(numberPattern)) {+ return ToolResult.error("'$number' does not look like a valid phone number.")+ }+ if (message.isBlank()) return ToolResult.error("The message text is empty.")+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.SEND_SMS)+ != PackageManager.PERMISSION_GRANTED+ ) {+ return ToolResult.permissionNeeded(+ Manifest.permission.SEND_SMS,+ "Sending a text needs the SMS permission. I have requested it — please grant it and ask again."+ )+ }+ return try {+ val smsManager = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {+ context.getSystemService(SmsManager::class.java)+ } else {+ @Suppress("DEPRECATION")+ SmsManager.getDefault()+ }+ val parts = smsManager.divideMessage(message)+ if (parts.size > 1) {+ smsManager.sendMultipartTextMessage(trimmed, null, parts, null, null)+ } else {+ smsManager.sendTextMessage(trimmed, null, message, null, null)+ }+ ToolResult.ok("Sent a text to $trimmed.")+ } catch (e: SecurityException) {+ ToolResult.permissionNeeded(+ Manifest.permission.SEND_SMS,+ "Sending a text needs the SMS permission. I have requested it — please grant it and ask again."+ )+ } catch (e: Exception) {+ ToolResult.error("Could not send the text: ${e.message}")+ }+ }++ /** Read recent inbox messages (needs READ_SMS). */+ fun readRecentSms(limit: Int): ToolResult {+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_SMS)+ != PackageManager.PERMISSION_GRANTED+ ) {+ return ToolResult.permissionNeeded(+ Manifest.permission.READ_SMS,+ "Reading texts needs the SMS permission. I have requested it — please grant it and ask again."+ )+ }+ val take = limit.coerceIn(1, 50)+ return try {+ val projection = arrayOf(+ Telephony.Sms.ADDRESS,+ Telephony.Sms.BODY,+ Telephony.Sms.DATE+ )+ context.contentResolver.query(+ Telephony.Sms.Inbox.CONTENT_URI, projection, null, null,+ "${Telephony.Sms.DATE} DESC"+ ).use { cursor ->+ if (cursor == null) return ToolResult.error("Could not read messages.")+ val addrIdx = cursor.getColumnIndexOrThrow(Telephony.Sms.ADDRESS)+ val bodyIdx = cursor.getColumnIndexOrThrow(Telephony.Sms.BODY)+ val dateIdx = cursor.getColumnIndexOrThrow(Telephony.Sms.DATE)+ val out = StringBuilder()+ var count = 0+ while (cursor.moveToNext() && count < take) {+ val addr = cursor.getString(addrIdx) ?: "unknown"+ val body = (cursor.getString(bodyIdx) ?: "").take(300)+ val date = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm", java.util.Locale.getDefault())+ .format(java.util.Date(cursor.getLong(dateIdx)))+ out.append("- $date from $addr: $body\n")+ count+++ }+ if (count == 0) ToolResult.ok("The SMS inbox is empty.")+ else ToolResult.ok("Last $count message(s):\n$out")+ }+ } catch (e: Exception) {+ ToolResult.error("Could not read messages: ${e.message}")+ }+ }+}diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.ktindex 65804a5..c2c940e 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -192,9 +192,369 @@ object ToolDefinitions {})+ // ---- Tier 0–2 additions ----++ val callNumber = tool(+ "call_number",+ "Place a phone call directly (the call starts immediately). Prefer dial_number if the user " ++ "should press call themselves. Needs the Phone permission.",+ schema {+ putJsonObject("properties") {+ putJsonObject("number") {+ put("type", "string")+ put("description", "Phone number to call, e.g. +49123456789")+ }+ }+ putJsonArray("required") { add("number") }+ }+ )++ val readCallLog = tool(+ "read_call_log",+ "Read the most recent call-log entries (incoming/outgoing/missed) with names, times and duration.",+ schema {+ putJsonObject("properties") {+ putJsonObject("limit") {+ put("type", "integer")+ put("description", "How many recent calls to return (1-50). Default 10.")+ }+ }+ }+ )++ val findContact = tool(+ "find_contact",+ "Look up a saved contact by name (partial match) and return their phone number(s). " ++ "Use this to resolve requests like 'call mom' before dial_number/call_number.",+ schema {+ putJsonObject("properties") {+ putJsonObject("name") {+ put("type", "string")+ put("description", "Contact name or partial name to search for.")+ }+ }+ putJsonArray("required") { add("name") }+ }+ )++ val addContact = tool(+ "add_contact",+ "Create a new contact with a name and phone number.",+ schema {+ putJsonObject("properties") {+ putJsonObject("name") {+ put("type", "string")+ put("description", "Full display name for the contact.")+ }+ putJsonObject("number") {+ put("type", "string")+ put("description", "Phone number for the contact.")+ }+ }+ putJsonArray("required") {+ add("name")+ add("number")+ }+ }+ )++ val sendSms = tool(+ "send_sms",+ "Send a text (SMS) message directly to a number. The message is sent immediately. Needs the SMS permission.",+ schema {+ putJsonObject("properties") {+ putJsonObject("number") {+ put("type", "string")+ put("description", "Recipient phone number.")+ }+ putJsonObject("message") {+ put("type", "string")+ put("description", "Text body to send.")+ }+ }+ putJsonArray("required") {+ add("number")+ add("message")+ }+ }+ )++ val readRecentSms = tool(+ "read_recent_sms",+ "Read the most recent received SMS messages from the inbox (sender, time, body).",+ schema {+ putJsonObject("properties") {+ putJsonObject("limit") {+ put("type", "integer")+ put("description", "How many recent messages to return (1-50). Default 10.")+ }+ }+ }+ )++ val listCalendarEvents = tool(+ "list_calendar_events",+ "List upcoming calendar events within a number of days from now.",+ schema {+ putJsonObject("properties") {+ putJsonObject("days_ahead") {+ put("type", "integer")+ put("description", "How many days ahead to include (1-365). Default 7.")+ }+ }+ }+ )++ val createCalendarEvent = tool(+ "create_calendar_event",+ "Add an event to the device's primary calendar.",+ schema {+ putJsonObject("properties") {+ putJsonObject("title") {+ put("type", "string")+ put("description", "Event title.")+ }+ putJsonObject("start") {+ put("type", "string")+ put("description", "Start time as 'yyyy-MM-dd HH:mm' (device local time) or epoch milliseconds.")+ }+ putJsonObject("end") {+ put("type", "string")+ put("description", "End time, same format as start. Defaults to one hour after start.")+ }+ putJsonObject("location") {+ put("type", "string")+ put("description", "Optional event location.")+ }+ }+ putJsonArray("required") {+ add("title")+ add("start")+ }+ }+ )++ val setAlarm = tool(+ "set_alarm",+ "Set a clock alarm at a given hour and minute via the device clock app.",+ schema {+ putJsonObject("properties") {+ putJsonObject("hour") {+ put("type", "integer")+ put("description", "Hour in 24h format (0-23).")+ }+ putJsonObject("minute") {+ put("type", "integer")+ put("description", "Minute (0-59).")+ }+ putJsonObject("message") {+ put("type", "string")+ put("description", "Optional alarm label.")+ }+ }+ putJsonArray("required") {+ add("hour")+ add("minute")+ }+ }+ )++ val setTimer = tool(+ "set_timer",+ "Start a countdown timer for a number of seconds via the device clock app.",+ schema {+ putJsonObject("properties") {+ putJsonObject("seconds") {+ put("type", "integer")+ put("description", "Timer length in seconds.")+ }+ putJsonObject("message") {+ put("type", "string")+ put("description", "Optional timer label.")+ }+ }+ putJsonArray("required") { add("seconds") }+ }+ )++ val toggleTorch = tool(+ "toggle_torch",+ "Turn the camera flashlight (torch) on or off.",+ schema {+ putJsonObject("properties") {+ putJsonObject("on") {+ put("type", "boolean")+ put("description", "true to turn the flashlight on, false to turn it off.")+ }+ }+ putJsonArray("required") { add("on") }+ }+ )++ val setVolume = tool(+ "set_volume",+ "Set a volume stream to a percentage. Streams: media, ring, alarm, notification, call.",+ schema {+ putJsonObject("properties") {+ putJsonObject("stream") {+ put("type", "string")+ put("description", "Which stream: media, ring, alarm, notification, or call.")+ }+ putJsonObject("percent") {+ put("type", "integer")+ put("description", "Target volume 0-100.")+ }+ }+ putJsonArray("required") {+ add("stream")+ add("percent")+ }+ }+ )++ val setRingerMode = tool(+ "set_ringer_mode",+ "Set the ringer mode: normal, vibrate, or silent. Silent/vibrate need Do Not Disturb access.",+ schema {+ putJsonObject("properties") {+ putJsonObject("mode") {+ put("type", "string")+ put("description", "One of: normal, vibrate, silent.")+ }+ }+ putJsonArray("required") { add("mode") }+ }+ )++ val vibrate = tool(+ "vibrate",+ "Vibrate the device for a short duration.",+ schema {+ putJsonObject("properties") {+ putJsonObject("duration_ms") {+ put("type", "integer")+ put("description", "Vibration length in milliseconds (1-5000). Default 500.")+ }+ }+ }+ )++ val setDnd = tool(+ "set_dnd",+ "Turn Do Not Disturb on or off. Needs Do Not Disturb (notification-policy) access.",+ schema {+ putJsonObject("properties") {+ putJsonObject("enabled") {+ put("type", "boolean")+ put("description", "true to enable Do Not Disturb, false to disable.")+ }+ }+ putJsonArray("required") { add("enabled") }+ }+ )++ val getLocation = tool(+ "get_location",+ "Report the device's last-known location (latitude/longitude and a nearby address if available). " ++ "Needs the Location permission.",+ schema { putJsonObject("properties") {} }+ )++ val listInstalledApps = tool(+ "list_installed_apps",+ "List the launchable apps installed on the device with their package names.",+ schema { putJsonObject("properties") {} }+ )++ val uninstallApp = tool(+ "uninstall_app",+ "Open the system uninstall dialog for an app package. The user confirms removal.",+ schema {+ putJsonObject("properties") {+ putJsonObject("package_name") {+ put("type", "string")+ put("description", "Package name to uninstall, e.g. com.example.app")+ }+ }+ putJsonArray("required") { add("package_name") }+ }+ )++ val getAppUsage = tool(+ "get_app_usage",+ "Report per-app screen time (top apps) over a recent window. Needs Usage-access special access.",+ schema {+ putJsonObject("properties") {+ putJsonObject("days") {+ put("type", "integer")+ put("description", "Look-back window in days (1-90). Default 7.")+ }+ }+ }+ )++ val getDataUsage = tool(+ "get_data_usage",+ "Report total mobile and Wi-Fi data used over a recent window. Needs Usage-access special access.",+ schema {+ putJsonObject("properties") {+ putJsonObject("days") {+ put("type", "integer")+ put("description", "Look-back window in days (1-90). Default 30.")+ }+ }+ }+ )++ val getClipboard = tool(+ "get_clipboard",+ "Read the current text on the clipboard.",+ schema { putJsonObject("properties") {} }+ )++ val setClipboard = tool(+ "set_clipboard",+ "Copy text onto the clipboard.",+ schema {+ putJsonObject("properties") {+ putJsonObject("text") {+ put("type", "string")+ put("description", "Text to place on the clipboard.")+ }+ }+ putJsonArray("required") { add("text") }+ }+ )++ val takePhoto = tool(+ "take_photo",+ "Open the camera app to capture a photo; the image is saved into the app's storage. " ++ "Returns the file path where the photo will be saved.",+ schema { putJsonObject("properties") {} }+ )++ val startAudioRecording = tool(+ "start_audio_recording",+ "Start recording audio from the microphone to a file. Call stop_audio_recording to finish. " ++ "Needs the Microphone permission.",+ schema { putJsonObject("properties") {} }+ )++ val stopAudioRecording = tool(+ "stop_audio_recording",+ "Stop the in-progress audio recording and report the saved file path.",+ schema { putJsonObject("properties") {} }+ )+val all: List<ToolDefinition> = listOf(dialNumber, getStorageInfo, getBatteryInfo, listFiles, readFile, writeFile,clearAppCache, openApp, toggleDarkMode, setBrightness, toggleWifi,- setWallpaper, runCommand+ setWallpaper, runCommand,+ // Tier 0–2 additions+ callNumber, readCallLog, findContact, addContact, sendSms, readRecentSms,+ listCalendarEvents, createCalendarEvent, setAlarm, setTimer,+ toggleTorch, setVolume, setRingerMode, vibrate, setDnd,+ getLocation, listInstalledApps, uninstallApp, getAppUsage, getDataUsage,+ getClipboard, setClipboard, takePhoto, startAudioRecording, stopAudioRecording)}diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.ktindex 23c4419..beae955 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -22,6 +22,15 @@ class ToolExecutor(context: Context) {private val fileTool = FileTool(appContext)private val terminalTool = TerminalTool()private val wallpaperTool = WallpaperTool(appContext)+ private val contactsTool = ContactsTool(appContext)+ private val smsTool = SmsTool(appContext)+ private val calendarTool = CalendarTool(appContext)+ private val alarmTool = AlarmTool(appContext)+ private val deviceTool = DeviceTool(appContext)+ private val locationTool = LocationTool(appContext)+ private val appsTool = AppsTool(appContext)+ private val clipboardTool = ClipboardTool(appContext)+ private val mediaCaptureTool = MediaCaptureTool(appContext)private val actionLog = ActionLog(appContext)suspend fun execute(name: String, args: JsonObject): ToolResult {@@ -60,6 +69,56 @@ class ToolExecutor(context: Context) {"toggle_wifi" -> systemTool.toggleWifi()"set_wallpaper" -> wallpaperTool.setWallpaper(args.requireString("url"))"run_command" -> terminalTool.runCommand(args.requireString("command") ?: return missing("command"))+ "call_number" -> phoneTool.callNumber(args.requireString("number") ?: return missing("number"))+ "read_call_log" -> phoneTool.readCallLog(args.requireInt("limit") ?: 10)+ "find_contact" -> contactsTool.findContact(args.requireString("name") ?: return missing("name"))+ "add_contact" -> contactsTool.addContact(+ name = args.requireString("name") ?: return missing("name"),+ number = args.requireString("number") ?: return missing("number")+ )+ "send_sms" -> smsTool.sendSms(+ number = args.requireString("number") ?: return missing("number"),+ message = args.requireString("message") ?: return missing("message")+ )+ "read_recent_sms" -> smsTool.readRecentSms(args.requireInt("limit") ?: 10)+ "list_calendar_events" -> calendarTool.listEvents(args.requireInt("days_ahead") ?: 7)+ "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")+ )+ "set_alarm" -> alarmTool.setAlarm(+ hour = args.requireInt("hour") ?: return missing("hour"),+ minute = args.requireInt("minute") ?: return missing("minute"),+ message = args.requireString("message")+ )+ "set_timer" -> alarmTool.setTimer(+ seconds = args.requireInt("seconds") ?: return missing("seconds"),+ message = args.requireString("message")+ )+ "toggle_torch" -> deviceTool.toggleTorch(+ args["on"]?.jsonPrimitive?.booleanOrNull ?: return missing("on")+ )+ "set_volume" -> deviceTool.setVolume(+ stream = args.requireString("stream") ?: return missing("stream"),+ percent = args.requireInt("percent") ?: return missing("percent")+ )+ "set_ringer_mode" -> deviceTool.setRingerMode(args.requireString("mode") ?: return missing("mode"))+ "vibrate" -> deviceTool.vibrate(args.requireInt("duration_ms") ?: 500)+ "set_dnd" -> deviceTool.setDnd(+ args["enabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("enabled")+ )+ "get_location" -> locationTool.getLocation()+ "list_installed_apps" -> appsTool.listInstalledApps()+ "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()+ "start_audio_recording" -> mediaCaptureTool.startAudioRecording()+ "stop_audio_recording" -> mediaCaptureTool.stopAudioRecording()else -> ToolResult.error("Tool '$name' has no executor.")}}@@ -67,6 +126,10 @@ class ToolExecutor(context: Context) {private fun JsonObject.requireString(key: String): String? =this[key]?.jsonPrimitive?.takeIf { it.isString || it.content.isNotEmpty() }?.content+ /** Parse an integer argument; tolerates numbers sent as JSON strings by the LLM. */+ private fun JsonObject.requireInt(key: String): Int? =+ this[key]?.jsonPrimitive?.let { it.intOrNull ?: it.content.trim().toIntOrNull() }+private fun missing(param: String) =ToolResult.error("Missing or invalid required parameter '$param'.")}diff --git a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt b/app/src/main/java/com/gotcha/tools/ToolRegistry.ktindex 78b68ce..25ec2d7 100644--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt@@ -17,7 +17,12 @@ object ToolRegistry {*/val sensitiveTools: Set<String> = setOf("dial_number", "set_wallpaper", "clear_app_cache",- "write_file", "run_command", "set_brightness"+ "write_file", "run_command", "set_brightness",+ // Tier 0–2 additions: outbound actions, personal-data reads, and captures.+ "call_number", "read_call_log", "find_contact", "add_contact",+ "send_sms", "read_recent_sms", "create_calendar_event", "list_calendar_events",+ "get_location", "uninstall_app",+ "take_photo", "start_audio_recording", "stop_audio_recording")fun allDefinitions(): List<ToolDefinition> = definitions.values.toList()diff --git a/app/src/main/java/com/gotcha/tools/ToolResult.kt b/app/src/main/java/com/gotcha/tools/ToolResult.ktindex 9c1b12d..6b72afd 100644--- a/app/src/main/java/com/gotcha/tools/ToolResult.kt+++ b/app/src/main/java/com/gotcha/tools/ToolResult.kt@@ -16,6 +16,12 @@ data class ToolResult(/** Marker for the WRITE_SETTINGS special app access (not a runtime permission). */const val WRITE_SETTINGS = "special:write_settings"+ /** Marker for the "Usage access" special app access (app-usage + data-usage stats). */+ const val USAGE_ACCESS = "special:usage_access"++ /** Marker for the "Do Not Disturb access" (notification-policy) special app access. */+ const val DND_ACCESS = "special:dnd_access"+fun ok(message: String) = ToolResult(true, message)fun error(message: String) = ToolResult(false, message)fun permissionNeeded(permission: String, message: String) =diff --git a/app/src/main/res/xml/file_paths.xml b/app/src/main/res/xml/file_paths.xmlnew file mode 100644index 0000000..b5760e4--- /dev/null+++ b/app/src/main/res/xml/file_paths.xml@@ -0,0 +1,5 @@+<?xml version="1.0" encoding="utf-8"?>+<paths>+ <!-- Captured photos live under getExternalFilesDir("Pictures"). -->+ <external-files-path name="captures" path="." />+</paths>