Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

feat: add support for scheduled SMS, enhanced contact searching, and expanded tool parameters

Rishabh Bajpai2b1319508c0b
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 2a219d1..5e045f5 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -36,6 +36,7 @@
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+ <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />
@@ -139,6 +140,11 @@
</intent-filter>
</service>
+ <!-- Scheduled SMS delivery receiver -->
+ <receiver
+ android:name=".tools.ScheduledSmsReceiver"
+ android:exported="false" />
+
<!-- Tier 3: Device Admin — lock screen, password policy, disable camera. -->
<receiver
android:name=".service.GotchaDeviceAdminReceiver"
diff --git a/app/src/main/java/com/gotcha/tools/ContactsTool.kt b/app/src/main/java/com/gotcha/tools/ContactsTool.kt
index f54a75d..5cf63a7 100644
--- a/app/src/main/java/com/gotcha/tools/ContactsTool.kt
+++ b/app/src/main/java/com/gotcha/tools/ContactsTool.kt
@@ -4,15 +4,16 @@ import android.Manifest
import android.content.ContentProviderOperation
import android.content.Context
import android.content.pm.PackageManager
+import android.net.Uri
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.")
+ 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.")
+ }
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED
) {
@@ -25,36 +26,140 @@ class ContactsTool(private val context: Context) {
val projection = arrayOf(
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
- ContactsContract.CommonDataKinds.Phone.TYPE
+ ContactsContract.CommonDataKinds.Phone.TYPE,
+ ContactsContract.CommonDataKinds.Phone.CONTACT_ID
)
+ val selection = StringBuilder()
+ val selectionArgs = mutableListOf<String>()
+ if (!name.isNullOrBlank()) {
+ selection.append("${ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME} LIKE ?")
+ selectionArgs.add("%$name%")
+ }
+ if (!number.isNullOrBlank()) {
+ if (selection.isNotEmpty()) selection.append(" OR ")
+ selection.append("${ContactsContract.CommonDataKinds.Phone.NUMBER} LIKE ?")
+ selectionArgs.add("%$number%")
+ }
+ val contacts = mutableListOf<Map<String, String>>()
context.contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection,
- "${ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME} LIKE ?",
- arrayOf("%$query%"),
+ selection.toString(),
+ selectionArgs.toTypedArray(),
"${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 typeIdx = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.TYPE)
+ while (cursor.moveToNext()) {
val displayName = cursor.getString(nameIdx) ?: "unknown"
- val number = cursor.getString(numIdx) ?: continue
- results.append("- $displayName: $number\n")
- count++
+ val phoneNumber = cursor.getString(numIdx) ?: continue
+ val phoneType = when (cursor.getInt(typeIdx)) {
+ ContactsContract.CommonDataKinds.Phone.TYPE_HOME -> "home"
+ ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE -> "mobile"
+ ContactsContract.CommonDataKinds.Phone.TYPE_WORK -> "work"
+ ContactsContract.CommonDataKinds.Phone.TYPE_MAIN -> "main"
+ ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK -> "fax work"
+ ContactsContract.CommonDataKinds.Phone.TYPE_FAX_HOME -> "fax home"
+ ContactsContract.CommonDataKinds.Phone.TYPE_PAGER -> "pager"
+ ContactsContract.CommonDataKinds.Phone.TYPE_OTHER -> "other"
+ else -> "other"
+ }
+ contacts.add(mapOf(
+ "name" to displayName,
+ "number" to phoneNumber,
+ "type" to phoneType
+ ))
+ }
+ }
+ if (contacts.isEmpty()) {
+ val hint = if (!name.isNullOrBlank()) "'$name'" else "'$number'"
+ return ToolResult.ok("No contact matching $hint was found.")
+ }
+ // Group by contact name for richer output
+ val grouped = contacts.groupBy { it["name"]!! }
+ val sb = StringBuilder()
+ grouped.entries.take(10).forEach { (contactName, entries) ->
+ val emails = resolveEmail(entries.first()["number"] ?: "")
+ val org = resolveOrganization(entries.first()["number"] ?: "")
+ sb.append("- $contactName")
+ if (org != null) sb.append(" ($org)")
+ sb.append(":\n")
+ entries.forEach { e ->
+ sb.append(" ${e["type"]}: ${e["number"]}\n")
}
- if (count == 0) ToolResult.ok("No contact matching '$query' was found.")
- else ToolResult.ok("Matches for '$query':\n$results")
+ if (emails.isNotEmpty()) {
+ sb.append(" email: ${emails.joinToString(", ")}\n")
+ }
+ }
+ if (grouped.size > 10) {
+ sb.append("... and ${grouped.size - 10} more contacts with that name.\n")
}
+ ToolResult.ok(sb.toString().trimEnd())
} 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 {
+ private fun resolveEmail(number: String): List<String> {
+ return try {
+ val uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number))
+ val emails = mutableListOf<String>()
+ context.contentResolver.query(
+ uri,
+ arrayOf(ContactsContract.PhoneLookup._ID),
+ null, null, null
+ )?.use { cursor ->
+ if (cursor.moveToFirst()) {
+ val contactId = cursor.getString(0)
+ context.contentResolver.query(
+ ContactsContract.CommonDataKinds.Email.CONTENT_URI,
+ arrayOf(ContactsContract.CommonDataKinds.Email.ADDRESS),
+ "${ContactsContract.CommonDataKinds.Email.CONTACT_ID} = ?",
+ arrayOf(contactId), null
+ )?.use { emailCursor ->
+ while (emailCursor.moveToNext()) {
+ emails.add(emailCursor.getString(0))
+ }
+ }
+ }
+ }
+ emails
+ } catch (_: Exception) { emptyList() }
+ }
+
+ private fun resolveOrganization(number: String): String? {
+ return try {
+ val uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number))
+ context.contentResolver.query(
+ uri,
+ arrayOf(ContactsContract.PhoneLookup._ID),
+ null, null, null
+ )?.use { cursor ->
+ if (cursor.moveToFirst()) {
+ val contactId = cursor.getString(0)
+ context.contentResolver.query(
+ ContactsContract.Data.CONTENT_URI,
+ arrayOf(ContactsContract.CommonDataKinds.Organization.COMPANY),
+ "${ContactsContract.Data.CONTACT_ID} = ? AND ${ContactsContract.Data.MIMETYPE} = ?",
+ arrayOf(contactId, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE),
+ null
+ )?.use { orgCursor ->
+ if (orgCursor.moveToFirst()) orgCursor.getString(0) else null
+ }
+ } else null
+ }
+ } catch (_: Exception) { null }
+ }
+
+ fun addContact(
+ name: String,
+ number: String,
+ phoneType: String? = null,
+ email: String? = null,
+ organization: String? = null
+ ): ToolResult {
val displayName = name.trim()
val phone = number.trim()
if (displayName.isEmpty()) return ToolResult.error("Please provide a name for the new contact.")
@@ -68,6 +173,23 @@ class ContactsTool(private val context: Context) {
)
}
return try {
+ // Duplicate detection
+ val dupes = findExisting(displayName, phone)
+ 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."
+ )
+ }
+ val typeVal = when (phoneType?.trim()?.lowercase()) {
+ "home" -> ContactsContract.CommonDataKinds.Phone.TYPE_HOME
+ "mobile" -> ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE
+ "work" -> ContactsContract.CommonDataKinds.Phone.TYPE_WORK
+ "main" -> ContactsContract.CommonDataKinds.Phone.TYPE_MAIN
+ "fax" -> ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK
+ "pager" -> ContactsContract.CommonDataKinds.Phone.TYPE_PAGER
+ else -> ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE
+ }
val ops = arrayListOf<ContentProviderOperation>()
ops.add(
ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
@@ -78,31 +200,61 @@ 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()
)
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.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone)
- .withValue(
- ContactsContract.CommonDataKinds.Phone.TYPE,
- ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE
- )
+ .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, typeVal)
.build()
)
+ if (!email.isNullOrBlank()) {
+ 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.CommonDataKinds.Email.ADDRESS, email.trim())
+ .withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
+ .build()
+ )
+ }
+ if (!organization.isNullOrBlank()) {
+ 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.CommonDataKinds.Organization.COMPANY, organization.trim())
+ .withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
+ .build()
+ )
+ }
context.contentResolver.applyBatch(ContactsContract.AUTHORITY, ops)
- ToolResult.ok("Added contact '$displayName' with number $phone.")
+ val extras = buildString {
+ append(" with number $phone")
+ if (phoneType != null) append(" ($phoneType)")
+ if (!email.isNullOrBlank()) append(", email $email")
+ if (!organization.isNullOrBlank()) append(", $organization")
+ }
+ ToolResult.ok("Added contact '$displayName'$extras.")
} catch (e: Exception) {
ToolResult.error("Could not add the contact: ${e.message}")
}
}
+
+ private fun findExisting(name: String, number: String): Int {
+ return try {
+ context.contentResolver.query(
+ ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
+ arrayOf("COUNT(*)"),
+ "${ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME} = ? OR ${ContactsContract.CommonDataKinds.Phone.NUMBER} = ?",
+ arrayOf(name, number), null
+ )?.use { cursor ->
+ if (cursor.moveToFirst()) cursor.getInt(0) else 0
+ } ?: 0
+ } catch (_: Exception) { 0 }
+ }
}
diff --git a/app/src/main/java/com/gotcha/tools/PhoneTool.kt b/app/src/main/java/com/gotcha/tools/PhoneTool.kt
index 5c3a101..c07a38d 100644
--- a/app/src/main/java/com/gotcha/tools/PhoneTool.kt
+++ b/app/src/main/java/com/gotcha/tools/PhoneTool.kt
@@ -4,9 +4,16 @@ import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
+import android.media.AudioManager
import android.net.Uri
+import android.os.Build
import android.provider.CallLog
+import android.provider.ContactsContract
+import android.telephony.SubscriptionManager
import androidx.core.content.ContextCompat
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
class PhoneTool(private val context: Context) {
@@ -35,8 +42,7 @@ class PhoneTool(private val context: Context) {
}
}
- /** Place a call directly (needs CALL_PHONE). Gated by the sensitive-action confirmation dialog. */
- fun callNumber(number: String): ToolResult {
+ fun callNumber(number: String, speakerphone: Boolean? = null, simSlot: String? = null): ToolResult {
val trimmed = number.trim()
if (trimmed.isEmpty() || !trimmed.matches(numberPattern)) {
return ToolResult.error("'$number' does not look like a valid phone number.")
@@ -52,9 +58,27 @@ class PhoneTool(private val context: Context) {
return try {
val intent = Intent(Intent.ACTION_CALL, Uri.parse("tel:$trimmed")).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ if (simSlot != null) {
+ val subId = resolveSubId(simSlot)
+ if (subId != null) {
+ putExtra("android.telephony.extra.SUBSCRIPTION_INDEX", subId)
+ }
+ }
}
context.startActivity(intent)
- ToolResult.ok("Calling $trimmed.")
+
+ val extras = mutableListOf<String>()
+ if (speakerphone == true) {
+ try {
+ val am = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
+ @Suppress("DEPRECATION")
+ am.isSpeakerphoneOn = true
+ extras.add("Speakerphone on.")
+ } catch (_: Exception) { }
+ }
+ if (simSlot != null) extras.add("Using $simSlot.")
+ val extra = if (extras.isNotEmpty()) " ${extras.joinToString(" ")}" else ""
+ ToolResult.ok("Calling $trimmed.$extra")
} catch (e: SecurityException) {
ToolResult.permissionNeeded(
Manifest.permission.CALL_PHONE,
@@ -65,8 +89,29 @@ class PhoneTool(private val context: Context) {
}
}
- /** Read recent call-log entries (needs READ_CALL_LOG). */
- fun readCallLog(limit: Int): ToolResult {
+ private fun resolveSubId(simSlot: String): Int? {
+ return try {
+ val subs = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
+ context.getSystemService(SubscriptionManager::class.java)?.activeSubscriptionInfoList
+ } else {
+ @Suppress("DEPRECATION")
+ SubscriptionManager.from(context).activeSubscriptionInfoList
+ } ?: return null
+ when (simSlot.trim().lowercase()) {
+ "sim1", "slot1", "1", "primary", "main" -> subs.firstOrNull()?.subscriptionId
+ "sim2", "slot2", "2", "secondary" -> subs.getOrNull(1)?.subscriptionId
+ else -> null
+ }
+ } catch (_: Exception) { null }
+ }
+
+ fun readCallLog(
+ limit: Int,
+ callTypeFilter: String? = null,
+ contact: String? = null,
+ fromDate: String? = null,
+ toDate: String? = null
+ ): ToolResult {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CALL_LOG)
!= PackageManager.PERMISSION_GRANTED
) {
@@ -77,15 +122,60 @@ class PhoneTool(private val context: Context) {
}
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
- )
+ val selection = StringBuilder()
+ val selectionArgs = mutableListOf<String>()
+
+ if (callTypeFilter != null) {
+ val typeVal = when (callTypeFilter.trim().lowercase()) {
+ "incoming" -> CallLog.Calls.INCOMING_TYPE
+ "outgoing" -> CallLog.Calls.OUTGOING_TYPE
+ "missed" -> CallLog.Calls.MISSED_TYPE
+ "rejected" -> CallLog.Calls.REJECTED_TYPE
+ else -> null
+ }
+ if (typeVal != null) {
+ if (selection.isNotEmpty()) selection.append(" AND ")
+ selection.append("${CallLog.Calls.TYPE} = ?")
+ selectionArgs.add(typeVal.toString())
+ }
+ }
+
+ if (contact != null) {
+ if (selection.isNotEmpty()) selection.append(" AND ")
+ selection.append("(${CallLog.Calls.NUMBER} LIKE ? OR ${CallLog.Calls.CACHED_NAME} LIKE ?)")
+ selectionArgs.add("%$contact%")
+ selectionArgs.add("%$contact%")
+ }
+
+ val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
+ if (fromDate != null) {
+ val fromMillis = try { dateFormat.parse(fromDate)?.time } catch (_: Exception) { null }
+ if (fromMillis != null) {
+ if (selection.isNotEmpty()) selection.append(" AND ")
+ selection.append("${CallLog.Calls.DATE} >= ?")
+ selectionArgs.add(fromMillis.toString())
+ }
+ }
+ if (toDate != 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} <= ?")
+ selectionArgs.add(toMillis.toString())
+ }
+ }
+
context.contentResolver.query(
- CallLog.Calls.CONTENT_URI, projection, null, null,
+ CallLog.Calls.CONTENT_URI,
+ arrayOf(
+ CallLog.Calls.NUMBER,
+ CallLog.Calls.CACHED_NAME,
+ CallLog.Calls.TYPE,
+ CallLog.Calls.DATE,
+ CallLog.Calls.DURATION
+ ),
+ selection.ifEmpty { null }.toString(),
+ selectionArgs.toTypedArray().ifEmpty { null },
"${CallLog.Calls.DATE} DESC"
).use { cursor ->
if (cursor == null) return ToolResult.error("Could not read the call log.")
@@ -98,7 +188,10 @@ class PhoneTool(private val context: Context) {
var count = 0
while (cursor.moveToNext() && count < take) {
val number = cursor.getString(numberIdx) ?: "unknown"
- val name = cursor.getString(nameIdx)
+ var name = cursor.getString(nameIdx)
+ if (name.isNullOrBlank()) {
+ name = resolveContactName(number)
+ }
val type = when (cursor.getInt(typeIdx)) {
CallLog.Calls.INCOMING_TYPE -> "incoming"
CallLog.Calls.OUTGOING_TYPE -> "outgoing"
@@ -106,11 +199,12 @@ class PhoneTool(private val context: Context) {
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 date = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
+ .format(Date(cursor.getLong(dateIdx)))
+ val durSecs = cursor.getLong(durIdx)
+ val dur = if (durSecs >= 60) "${durSecs / 60}m ${durSecs % 60}s" else "${durSecs}s"
val who = if (!name.isNullOrBlank()) "$name ($number)" else number
- entries.append("- $date $type $who ${dur}s\n")
+ entries.append("- $date $type $who $dur\n")
count++
}
if (count == 0) ToolResult.ok("The call log is empty.")
@@ -120,4 +214,19 @@ class PhoneTool(private val context: Context) {
ToolResult.error("Could not read the call log: ${e.message}")
}
}
+
+ private fun resolveContactName(number: String): String? {
+ return try {
+ val uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number))
+ context.contentResolver.query(
+ uri,
+ arrayOf(ContactsContract.PhoneLookup.DISPLAY_NAME),
+ null, null, null
+ )?.use { cursor ->
+ if (cursor.moveToFirst()) {
+ cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup.DISPLAY_NAME))
+ } else null
+ }
+ } catch (_: Exception) { null }
+ }
}
diff --git a/app/src/main/java/com/gotcha/tools/ScheduledSmsReceiver.kt b/app/src/main/java/com/gotcha/tools/ScheduledSmsReceiver.kt
new file mode 100644
index 0000000..a56055d
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/ScheduledSmsReceiver.kt
@@ -0,0 +1,30 @@
+package com.gotcha.tools
+
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.os.Build
+import android.telephony.SmsManager
+
+class ScheduledSmsReceiver : BroadcastReceiver() {
+
+ override fun onReceive(context: Context, intent: Intent) {
+ val number = intent.getStringExtra("number") ?: return
+ val message = intent.getStringExtra("message") ?: return
+
+ val smsManager = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ context.getSystemService(SmsManager::class.java)
+ } else {
+ @Suppress("DEPRECATION")
+ SmsManager.getDefault()
+ }
+ try {
+ val parts = smsManager.divideMessage(message)
+ if (parts.size > 1) {
+ smsManager.sendMultipartTextMessage(number, null, parts, null, null)
+ } else {
+ smsManager.sendTextMessage(number, null, message, null, null)
+ }
+ } catch (_: Exception) { }
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/SmsTool.kt b/app/src/main/java/com/gotcha/tools/SmsTool.kt
index d6108a8..2ab9a5a 100644
--- a/app/src/main/java/com/gotcha/tools/SmsTool.kt
+++ b/app/src/main/java/com/gotcha/tools/SmsTool.kt
@@ -1,19 +1,36 @@
package com.gotcha.tools
import android.Manifest
+import android.app.Activity
+import android.app.AlarmManager
+import android.app.PendingIntent
+import android.content.BroadcastReceiver
import android.content.Context
+import android.content.Intent
+import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.Build
+import android.os.Handler
+import android.os.Looper
import android.provider.Telephony
import android.telephony.SmsManager
import androidx.core.content.ContextCompat
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.TimeUnit
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 {
+ fun sendSms(
+ number: String,
+ message: String,
+ deliveryReport: Boolean? = null,
+ sendAt: String? = null
+ ): ToolResult {
val trimmed = number.trim()
if (!trimmed.matches(numberPattern)) {
return ToolResult.error("'$number' does not look like a valid phone number.")
@@ -27,20 +44,65 @@ class SmsTool(private val context: Context) {
"The SMS permission is not granted. Go to Settings → Permissions → SMS and enable it, then 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()
+
+ // Scheduled send
+ if (sendAt != null) {
+ val delayMs = parseSendAt(sendAt)
+ if (delayMs == null) {
+ return ToolResult.error(
+ "Could not parse send_at. Use an ISO-8601 timestamp like '2026-01-15T14:30:00' or epoch millis."
+ )
}
+ if (delayMs <= 0) {
+ return ToolResult.error("send_at must be in the future.")
+ }
+ scheduleSms(trimmed, message, delayMs)
+ val eta = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
+ .format(Date(System.currentTimeMillis() + delayMs))
+ return ToolResult.ok("Scheduled SMS to $trimmed for $eta (in ${delayMs / 60000} minutes).")
+ }
+
+ return try {
+ val smsManager = smsManager()
+
val parts = smsManager.divideMessage(message)
- if (parts.size > 1) {
- smsManager.sendMultipartTextMessage(trimmed, null, parts, null, null)
+ val segmentCount = parts.size
+ val encoding = detectEncoding(message)
+ var deliveryResult: String? = null
+ val sentLatch = if (deliveryReport == true) CountDownLatch(1) else null
+
+ if (deliveryReport == true) {
+ val sentIntent = createSentIntent(trimmed, message, sentLatch)
+ if (segmentCount > 1) {
+ val sentIntents = arrayListOf<PendingIntent>().apply {
+ repeat(segmentCount) { add(sentIntent) }
+ }
+ smsManager.sendMultipartTextMessage(trimmed, null, parts, sentIntents, null)
+ } else {
+ smsManager.sendTextMessage(trimmed, null, message, sentIntent, null)
+ }
+ sentLatch?.await(10, TimeUnit.SECONDS)
+ // Read delivery result from the receiver
+ deliveryResult = lastDeliveryResult
} else {
- smsManager.sendTextMessage(trimmed, null, message, null, null)
+ if (segmentCount > 1) {
+ smsManager.sendMultipartTextMessage(trimmed, null, parts, null, null)
+ } else {
+ smsManager.sendTextMessage(trimmed, null, message, null, null)
+ }
}
- ToolResult.ok("Sent a text to $trimmed.")
+
+ // Show recent conversation context
+ val threadContext = getConversationThread(trimmed)
+
+ buildString {
+ append("Sent a text to $trimmed.")
+ append(" $segmentCount segment(s)")
+ if (encoding != "GSM 7-bit") append(" (using $encoding)")
+ append(".")
+ if (deliveryResult != null) append(" Delivery: $deliveryResult.")
+ if (threadContext != null) append("\n\nConversation:\n$threadContext")
+ }.let { ToolResult.ok(it) }
} catch (e: SecurityException) {
ToolResult.permissionNeeded(
Manifest.permission.SEND_SMS,
@@ -51,8 +113,105 @@ class SmsTool(private val context: Context) {
}
}
- /** Read recent inbox messages (needs READ_SMS). */
- fun readRecentSms(limit: Int): ToolResult {
+ private var lastDeliveryResult: String? = null
+
+ private var deliveryReceiver: BroadcastReceiver? = null
+
+ private fun createSentIntent(number: String, message: String, latch: CountDownLatch?): PendingIntent {
+ val intent = Intent("com.gotcha.SMS_SENT").apply {
+ setPackage(context.packageName)
+ putExtra("number", number)
+ putExtra("message", message)
+ }
+ val pi = PendingIntent.getBroadcast(
+ context, System.currentTimeMillis().toInt() and 0x7FFFFFFF,
+ intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
+ )
+ if (deliveryReceiver == null) {
+ val receiver = object : BroadcastReceiver() {
+ override fun onReceive(ctx: Context, intent: Intent) {
+ val code = resultCode
+ lastDeliveryResult = when (code) {
+ Activity.RESULT_OK -> "Sent"
+ SmsManager.RESULT_ERROR_GENERIC_FAILURE -> "Generic failure"
+ SmsManager.RESULT_ERROR_NO_SERVICE -> "No service"
+ SmsManager.RESULT_ERROR_NULL_PDU -> "Null PDU"
+ SmsManager.RESULT_ERROR_RADIO_OFF -> "Radio off"
+ else -> "Unknown ($code)"
+ }
+ latch?.countDown()
+ }
+ }
+ deliveryReceiver = receiver
+ context.registerReceiver(receiver, IntentFilter("com.gotcha.SMS_SENT"),
+ Context.RECEIVER_EXPORTED
+ )
+ }
+ return pi
+ }
+
+ private fun smsManager(): SmsManager {
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ context.getSystemService(SmsManager::class.java)
+ } else {
+ @Suppress("DEPRECATION")
+ SmsManager.getDefault()
+ }
+ }
+
+ private fun detectEncoding(message: String): String {
+ val gsm7 = setOf(
+ '@', '\u00a3', '\u0024', '\u00a5', '\u00e8', '\u00e9', '\u00f9', '\u00ec',
+ '\u00f2', '\u00c7', '\u000a', '\u00d8', '\u00f8', '\u000d', '\u00c5', '\u00e5',
+ '\u0394', '\u005f', '\u03a6', '\u0393', '\u039b', '\u03a9', '\u03a0', '\u03a8',
+ '\u03a3', '\u0398', '\u039e', '\u0020', '\u00c6', '\u00e6', '\u00df', '\u00c9',
+ ' ', '!', '"', '#', '\u00a4', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/',
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?',
+ '\u00a1', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
+ 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
+ '\u00c4', '\u00d6', '\u00d1', '\u00dc', '\u00a7', '\u00bf',
+ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
+ 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
+ '\u00e4', '\u00f6', '\u00f1', '\u00fc', '\u00e0'
+ )
+ return if (message.all { it in gsm7 }) "GSM 7-bit" else "UCS-2"
+ }
+
+ private fun parseSendAt(sendAt: String): Long? {
+ try {
+ return sendAt.toLongOrNull()?.minus(System.currentTimeMillis())
+ } catch (_: Exception) {}
+ try {
+ val formats = listOf(
+ "yyyy-MM-dd'T'HH:mm:ss",
+ "yyyy-MM-dd'T'HH:mm",
+ "yyyy-MM-dd HH:mm:ss",
+ "yyyy-MM-dd HH:mm"
+ )
+ for (fmt in formats) {
+ try {
+ val date = SimpleDateFormat(fmt, Locale.getDefault()).parse(sendAt)
+ if (date != null) return date.time - System.currentTimeMillis()
+ } catch (_: Exception) {}
+ }
+ } catch (_: Exception) {}
+ return null
+ }
+
+ private fun scheduleSms(number: String, message: String, delayMs: Long) {
+ val intent = Intent(context, ScheduledSmsReceiver::class.java).apply {
+ putExtra("number", number)
+ putExtra("message", message)
+ }
+ val pi = PendingIntent.getBroadcast(
+ context, number.hashCode() and 0x7FFFFFFF,
+ intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
+ )
+ val alarm = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
+ alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + delayMs, pi)
+ }
+
+ fun readRecentSms(limit: Int, fromAddress: String? = null): ToolResult {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_SMS)
!= PackageManager.PERMISSION_GRANTED
) {
@@ -63,13 +222,16 @@ class SmsTool(private val context: Context) {
}
val take = limit.coerceIn(1, 50)
return try {
- val projection = arrayOf(
- Telephony.Sms.ADDRESS,
- Telephony.Sms.BODY,
- Telephony.Sms.DATE
- )
+ val selection = if (!fromAddress.isNullOrBlank()) {
+ "${Telephony.Sms.ADDRESS} LIKE ?"
+ } else null
+ val selectionArgs = if (!fromAddress.isNullOrBlank()) {
+ arrayOf("%$fromAddress%")
+ } else null
context.contentResolver.query(
- Telephony.Sms.Inbox.CONTENT_URI, projection, null, null,
+ Telephony.Sms.Inbox.CONTENT_URI,
+ arrayOf(Telephony.Sms.ADDRESS, Telephony.Sms.BODY, Telephony.Sms.DATE),
+ selection, selectionArgs,
"${Telephony.Sms.DATE} DESC"
).use { cursor ->
if (cursor == null) return ToolResult.error("Could not read messages.")
@@ -81,16 +243,46 @@ class SmsTool(private val context: Context) {
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)))
+ val date = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
+ .format(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")
+ if (count == 0) {
+ val hint = if (!fromAddress.isNullOrBlank()) " from '$fromAddress'" else ""
+ ToolResult.ok("The SMS inbox is empty$hint.")
+ } else ToolResult.ok("Last $count message(s):\n$out")
}
} catch (e: Exception) {
ToolResult.error("Could not read messages: ${e.message}")
}
}
+
+ private fun getConversationThread(number: String): String? {
+ return try {
+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_SMS)
+ != PackageManager.PERMISSION_GRANTED
+ ) return null
+ context.contentResolver.query(
+ Telephony.Sms.Inbox.CONTENT_URI,
+ arrayOf(Telephony.Sms.ADDRESS, Telephony.Sms.BODY, Telephony.Sms.DATE),
+ "${Telephony.Sms.ADDRESS} LIKE ?",
+ arrayOf("%${number.take(10)}%"),
+ "${Telephony.Sms.DATE} DESC"
+ )?.use { cursor ->
+ val addrIdx = cursor.getColumnIndexOrThrow(Telephony.Sms.ADDRESS)
+ val bodyIdx = cursor.getColumnIndexOrThrow(Telephony.Sms.BODY)
+ val dateIdx = cursor.getColumnIndexOrThrow(Telephony.Sms.DATE)
+ val lines = mutableListOf<String>()
+ while (cursor.moveToNext() && lines.size < 3) {
+ val addr = cursor.getString(addrIdx) ?: "unknown"
+ val body = (cursor.getString(bodyIdx) ?: "").take(160)
+ val date = SimpleDateFormat("HH:mm", Locale.getDefault())
+ .format(Date(cursor.getLong(dateIdx)))
+ lines.add("$date $addr: $body")
+ }
+ if (lines.isEmpty()) null else lines.reversed().joinToString("\n")
+ }
+ } catch (_: Exception) { null }
+ }
}
diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
index e33e48a..dfe29fa 100644
--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
@@ -241,13 +241,21 @@ object ToolDefinitions {
"Place a phone call directly — the call is dialed immediately. This is the DEFAULT tool for " +
"any 'call X' / 'phone X' / 'ring X' request. Resolve names to numbers with find_contact " +
"first if needed. Needs the Phone permission. Only fall back to dial_number if the user " +
- "explicitly wants to press call themselves.",
+ "explicitly wants to press call themselves. Supports speakerphone toggle and SIM selection.",
schema {
putJsonObject("properties") {
putJsonObject("number") {
put("type", "string")
put("description", "Phone number to call, e.g. +49123456789")
}
+ putJsonObject("speakerphone") {
+ put("type", "boolean")
+ put("description", "Enable speakerphone for the call. Default false.")
+ }
+ 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.")
+ }
}
putJsonArray("required") { add("number") }
}
@@ -255,35 +263,59 @@ object ToolDefinitions {
val readCallLog = tool(
"read_call_log",
- "Read the most recent call-log entries (incoming/outgoing/missed) with names, times and duration.",
+ "Read the most recent call-log entries (incoming/outgoing/missed) with names, times and duration. " +
+ "Supports filtering by call type, contact name/number, and date range.",
schema {
putJsonObject("properties") {
putJsonObject("limit") {
put("type", "integer")
put("description", "How many recent calls to return (1-50). Default 10.")
}
+ putJsonObject("type") {
+ put("type", "string")
+ put("description", "Filter by call type: 'incoming', 'outgoing', 'missed', or 'rejected'. Omit for all.")
+ }
+ putJsonObject("contact") {
+ put("type", "string")
+ put("description", "Filter by contact name or number (partial match).")
+ }
+ putJsonObject("from_date") {
+ put("type", "string")
+ put("description", "Start date, e.g. '2026-01-01'. Only calls on or after this date.")
+ }
+ putJsonObject("to_date") {
+ put("type", "string")
+ put("description", "End date, e.g. '2026-01-31'. Only calls on or before this date.")
+ }
}
}
)
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.",
+ "Look up a saved contact by name or phone number (partial match). Returns matching contacts with " +
+ "their phone numbers (with type labels like mobile/home/work), email, and organization. " +
+ "Use this to resolve requests like 'call mom' before dial_number/call_number, " +
+ "or to identify who called from a number.",
schema {
putJsonObject("properties") {
putJsonObject("name") {
put("type", "string")
put("description", "Contact name or partial name to search for.")
}
+ putJsonObject("number") {
+ put("type", "string")
+ put("description", "Phone number to reverse-lookup (find who owns this number).")
+ }
}
- putJsonArray("required") { add("name") }
}
)
val addContact = tool(
"add_contact",
- "Create a new contact with a name and phone number.",
+ "Create a new contact with a name, phone number, and optional fields. " +
+ "Automatically detects and warns about duplicate contacts before creating. " +
+ "Supports adding email and organization alongside the phone number.",
schema {
putJsonObject("properties") {
putJsonObject("name") {
@@ -294,6 +326,18 @@ object ToolDefinitions {
put("type", "string")
put("description", "Phone number for the contact.")
}
+ putJsonObject("phone_type") {
+ put("type", "string")
+ put("description", "Phone number label: 'mobile' (default), 'home', 'work', 'main', 'fax', or 'pager'.")
+ }
+ putJsonObject("email") {
+ put("type", "string")
+ put("description", "Optional email address for the contact.")
+ }
+ putJsonObject("organization") {
+ put("type", "string")
+ put("description", "Optional company or organization name.")
+ }
}
putJsonArray("required") {
add("name")
@@ -304,7 +348,10 @@ object ToolDefinitions {
val sendSms = tool(
"send_sms",
- "Send a text (SMS) message directly to a number. The message is sent immediately. Needs the SMS permission.",
+ "Send a text (SMS) message directly to a number. The message is sent immediately. " +
+ "Supports delivery confirmation, auto-detects GSM 7-bit vs UCS-2 encoding, " +
+ "reports segment count, shows recent conversation context after sending, " +
+ "and can schedule future delivery. Needs the SMS permission.",
schema {
putJsonObject("properties") {
putJsonObject("number") {
@@ -315,6 +362,14 @@ object ToolDefinitions {
put("type", "string")
put("description", "Text body to send.")
}
+ putJsonObject("delivery_report") {
+ put("type", "boolean")
+ put("description", "Request a delivery confirmation (reports Sent/Failed). Default false.")
+ }
+ 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.")
+ }
}
putJsonArray("required") {
add("number")
@@ -325,13 +380,18 @@ object ToolDefinitions {
val readRecentSms = tool(
"read_recent_sms",
- "Read the most recent received SMS messages from the inbox (sender, time, body).",
+ "Read the most recent received SMS messages from the inbox (sender, time, body). " +
+ "Supports optional filter by sender address.",
schema {
putJsonObject("properties") {
putJsonObject("limit") {
put("type", "integer")
put("description", "How many recent messages to return (1-50). Default 10.")
}
+ putJsonObject("from_address") {
+ put("type", "string")
+ put("description", "Filter by sender address (partial match, e.g. a contact name or phone number).")
+ }
}
}
)
diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
index 00cbe44..be4c269 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -132,18 +132,39 @@ class ToolExecutor(context: Context) {
workingDir = args.requireString("working_dir"),
timeoutSeconds = args.requireInt("timeout_seconds") ?: 15
)
- "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"))
+ "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")
+ 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")
+ 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")
)
- "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"),