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: enhance calendar, SMS, and location tools with expanded filter parameters and configuration options.

Rishabh Bajpai545dced0aab5
diff --git a/app/src/main/java/com/gotcha/tools/CalendarTool.kt b/app/src/main/java/com/gotcha/tools/CalendarTool.kt
index 65d6ebc..a825344 100644
--- a/app/src/main/java/com/gotcha/tools/CalendarTool.kt
+++ b/app/src/main/java/com/gotcha/tools/CalendarTool.kt
@@ -8,6 +8,7 @@ import android.content.pm.PackageManager
import android.provider.CalendarContract
import androidx.core.content.ContextCompat
import java.text.SimpleDateFormat
+import java.util.Date
import java.util.Locale
import java.util.TimeZone
@@ -15,8 +16,12 @@ 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 {
+ fun listEvents(
+ daysAhead: Int? = null,
+ fromDate: String? = null,
+ toDate: String? = null,
+ search: String? = null
+ ): ToolResult {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CALENDAR)
!= PackageManager.PERMISSION_GRANTED
) {
@@ -25,48 +30,107 @@ class CalendarTool(private val context: Context) {
"The Calendar permission is not granted. Go to Settings → Permissions → Calendar and enable it, then ask again."
)
}
- val days = daysAhead.coerceIn(1, 365)
- val now = System.currentTimeMillis()
- val end = now + days * 24L * 60 * 60 * 1000
return try {
+ val now = System.currentTimeMillis()
+ val rangeStart: Long
+ val rangeEnd: Long
+ val rangeDesc: String
+
+ if (fromDate != null || toDate != null) {
+ val df = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
+ rangeStart = if (fromDate != null) {
+ try { df.parse(fromDate)?.time ?: now } catch (_: Exception) { now }
+ } else now
+ rangeEnd = if (toDate != null) {
+ try { df.parse(toDate)?.time?.plus(86_400_000L - 1) ?: (now + 86400000L) } catch (_: Exception) { now + 86400000L }
+ } else rangeStart + 86400000L
+ rangeDesc = "${fromDate ?: "today"} → ${toDate ?: "tomorrow"}"
+ } else {
+ val days = (daysAhead ?: 7).coerceIn(1, 365)
+ rangeStart = now
+ rangeEnd = now + days * 24L * 60 * 60 * 1000
+ rangeDesc = "next $days day(s)"
+ }
+
val builder = CalendarContract.Instances.CONTENT_URI.buildUpon()
- ContentUris.appendId(builder, now)
- ContentUris.appendId(builder, end)
+ ContentUris.appendId(builder, rangeStart)
+ ContentUris.appendId(builder, rangeEnd)
+
val projection = arrayOf(
CalendarContract.Instances.TITLE,
CalendarContract.Instances.BEGIN,
CalendarContract.Instances.END,
- CalendarContract.Instances.EVENT_LOCATION
+ CalendarContract.Instances.EVENT_LOCATION,
+ CalendarContract.Instances.DESCRIPTION,
+ CalendarContract.Instances.STATUS,
+ CalendarContract.Instances.CALENDAR_DISPLAY_NAME
)
+
+ var selection: String? = null
+ var selectionArgs: Array<String>? = null
+ if (!search.isNullOrBlank()) {
+ selection = "${CalendarContract.Instances.TITLE} LIKE ?"
+ selectionArgs = arrayOf("%$search%")
+ }
+
context.contentResolver.query(
- builder.build(), projection, null, null,
+ builder.build(), projection, selection, selectionArgs,
"${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 endIdx = cursor.getColumnIndexOrThrow(CalendarContract.Instances.END)
val locIdx = cursor.getColumnIndexOrThrow(CalendarContract.Instances.EVENT_LOCATION)
+ val descIdx = cursor.getColumnIndexOrThrow(CalendarContract.Instances.DESCRIPTION)
+ val statusIdx = cursor.getColumnIndexOrThrow(CalendarContract.Instances.STATUS)
+ val calIdx = cursor.getColumnIndexOrThrow(CalendarContract.Instances.CALENDAR_DISPLAY_NAME)
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 begin = readable.format(Date(cursor.getLong(beginIdx)))
+ val end = readable.format(Date(cursor.getLong(endIdx)))
val loc = cursor.getString(locIdx)
- out.append("- $begin $title")
- if (!loc.isNullOrBlank()) out.append(" @ $loc")
+ val desc = cursor.getString(descIdx)
+ val status = when (cursor.getInt(statusIdx)) {
+ CalendarContract.Instances.STATUS_CONFIRMED -> "confirmed"
+ CalendarContract.Instances.STATUS_TENTATIVE -> "tentative"
+ CalendarContract.Instances.STATUS_CANCELED -> "cancelled"
+ else -> null
+ }
+ val calName = cursor.getString(calIdx)
+
+ out.append("- $begin")
+ if (status != null) out.append(" [$status]")
+ out.append(" $title")
+ if (calName != null) out.append(" 📅 $calName")
+ out.append("\n ends $end")
+ if (!loc.isNullOrBlank()) out.append("\n 📍 $loc")
+ if (!desc.isNullOrBlank()) out.append("\n ${desc.take(200)}")
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")
+ if (count == 0) {
+ val hint = if (!search.isNullOrBlank()) " matching '$search'" else ""
+ ToolResult.ok("No events $rangeDesc$hint.")
+ } else ToolResult.ok("Events $rangeDesc ($count):\n$out")
}
} 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 {
+ fun createEvent(
+ title: String,
+ start: String,
+ end: String? = null,
+ location: String? = null,
+ description: String? = null,
+ allDay: Boolean? = null,
+ reminderMinutes: Int? = null,
+ calendarName: String? = null
+ ): ToolResult {
if (title.isBlank()) return ToolResult.error("Please provide a title for the event.")
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_CALENDAR)
!= PackageManager.PERMISSION_GRANTED
@@ -80,33 +144,89 @@ class CalendarTool(private val context: Context) {
?: 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'.")
+
+ if (allDay == true) {
+ // all-day events: set to midnight of the start date
+ val cal = java.util.Calendar.getInstance()
+ cal.timeInMillis = startMs
+ cal.set(java.util.Calendar.HOUR_OF_DAY, 0)
+ cal.set(java.util.Calendar.MINUTE, 0)
+ cal.set(java.util.Calendar.SECOND, 0)
+ cal.set(java.util.Calendar.MILLISECOND, 0)
+ // startMs is already set above from parseWhen
+ }
+
return try {
- val calendarId = defaultWritableCalendarId()
- ?: return ToolResult.error("No writable calendar was found on this device.")
+ val calendarId = if (!calendarName.isNullOrBlank()) {
+ findCalendarByName(calendarName)
+ } else null
+ ?: 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 (allDay == true) put(CalendarContract.Events.ALL_DAY, 1)
if (!location.isNullOrBlank()) put(CalendarContract.Events.EVENT_LOCATION, location)
+ if (!description.isNullOrBlank()) put(CalendarContract.Events.DESCRIPTION, description)
}
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}).")
+
+ // Add reminder if requested
+ if (reminderMinutes != null && reminderMinutes >= 0) {
+ val reminderValues = ContentValues().apply {
+ put(CalendarContract.Reminders.EVENT_ID, uri.lastPathSegment!!.toLong())
+ put(CalendarContract.Reminders.MINUTES, reminderMinutes)
+ put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT)
+ }
+ context.contentResolver.insert(CalendarContract.Reminders.CONTENT_URI, reminderValues)
+ }
+
+ val extras = buildString {
+ if (allDay == true) append(" all-day")
+ if (reminderMinutes != null && reminderMinutes >= 0) append(", reminder $reminderMinutes min before")
+ }
+ ToolResult.ok("Added '$title' on ${readable.format(Date(startMs))}$extras.")
} catch (e: Exception) {
ToolResult.error("Could not create the event: ${e.message}")
}
}
+ private fun findCalendarByName(name: String): Long? {
+ val projection = arrayOf(
+ CalendarContract.Calendars._ID,
+ CalendarContract.Calendars.CALENDAR_DISPLAY_NAME
+ )
+ context.contentResolver.query(
+ CalendarContract.Calendars.CONTENT_URI, projection, null, null, null
+ )?.use { cursor ->
+ val idIdx = cursor.getColumnIndexOrThrow(CalendarContract.Calendars._ID)
+ val nameIdx = cursor.getColumnIndexOrThrow(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME)
+ while (cursor.moveToNext()) {
+ val calName = cursor.getString(nameIdx)
+ if (calName?.contains(name, ignoreCase = true) == true) {
+ return cursor.getLong(idIdx)
+ }
+ }
+ }
+ return null
+ }
+
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")
+ val formats = listOf(
+ "yyyy-MM-dd HH:mm", "yyyy-MM-dd'T'HH:mm",
+ "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss"
+ )
for (f in formats) {
try {
return SimpleDateFormat(f, Locale.getDefault()).parse(v)?.time
- } catch (_: Exception) { /* try next */ }
+ } catch (_: Exception) { }
}
return null
}
diff --git a/app/src/main/java/com/gotcha/tools/LocationTool.kt b/app/src/main/java/com/gotcha/tools/LocationTool.kt
index 62470f8..ecadfc1 100644
--- a/app/src/main/java/com/gotcha/tools/LocationTool.kt
+++ b/app/src/main/java/com/gotcha/tools/LocationTool.kt
@@ -5,14 +5,18 @@ import android.content.Context
import android.content.pm.PackageManager
import android.location.Geocoder
import android.location.Location
+import android.location.LocationListener
import android.location.LocationManager
+import android.os.Bundle
+import android.os.Looper
import androidx.core.content.ContextCompat
import java.util.Locale
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.TimeUnit
class LocationTool(private val context: Context) {
- /** Report the last-known device location (needs ACCESS_FINE_LOCATION). */
- fun getLocation(): ToolResult {
+ fun getLocation(fresh: Boolean? = null): 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) {
@@ -23,42 +27,98 @@ class LocationTool(private val context: Context) {
}
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 hasFine = fine == PackageManager.PERMISSION_GRANTED
+
+ val fix = if (fresh == true) {
+ requestFreshFix(lm, hasFine)
+ } else {
+ getBestLastKnown(lm)
+ }
+
+ if (fix == null) {
+ val hint = if (fresh == true) {
+ "Could not get a fresh GPS fix. Make sure location is enabled and you're outdoors or near a window."
+ } else {
+ "No recent location fix is available. Try again with fresh=true to request a new GPS fix."
}
- val current = best
- if (loc != null && (current == null || loc.time > current.time)) best = loc
+ return ToolResult.ok(hint)
}
- 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))
+ val accuracy = if (fix.hasAccuracy()) " (±${fix.accuracy.toInt()}m)" else ""
+ val altitude = if (fix.hasAltitude()) ", alt ${fix.altitude.toInt()}m" else ""
+ val bearing = if (fix.hasBearing()) ", bearing ${fix.bearing.toInt()}°" else ""
+ val speed = if (fix.hasSpeed()) ", speed ${"%.1f".format(fix.speed * 3.6)} km/h" else ""
+ val source = if (fresh == true) " (fresh fix)" else ""
+
+ val mapLink = "https://maps.google.com/maps?q=$lat,$lng"
+ val where = if (address != null) " near $address" else ""
+
+ ToolResult.ok(
+ "Location: %.5f, %.5f%s%s%s%s%s%s\nMap: $mapLink".format(
+ lat, lng, accuracy, altitude, bearing, speed, where, source
+ )
+ )
} catch (e: Exception) {
ToolResult.error("Could not read your location: ${e.message}")
}
}
+ private fun getBestLastKnown(lm: LocationManager): Location? {
+ 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 || loc.accuracy < current.accuracy)) best = loc
+ }
+ return best
+ }
+
+ private fun requestFreshFix(lm: LocationManager, fine: Boolean): Location? {
+ val latch = CountDownLatch(1)
+ var result: Location? = null
+
+ val provider = if (fine && lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
+ LocationManager.GPS_PROVIDER
+ } else if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
+ LocationManager.NETWORK_PROVIDER
+ } else {
+ return null
+ }
+
+ @Suppress("DEPRECATION")
+ val listener = object : LocationListener {
+ override fun onLocationChanged(location: Location) {
+ result = location
+ latch.countDown()
+ }
+ override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}
+ override fun onProviderEnabled(provider: String) {}
+ override fun onProviderDisabled(provider: String) {}
+ }
+
+ lm.requestSingleUpdate(provider, listener, Looper.getMainLooper())
+ latch.await(8, TimeUnit.SECONDS)
+ try { lm.removeUpdates(listener) } catch (_: Exception) {}
+
+ return result
+ }
+
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
- }
+ } catch (_: Exception) { null }
}
}
diff --git a/app/src/main/java/com/gotcha/tools/SmsTool.kt b/app/src/main/java/com/gotcha/tools/SmsTool.kt
index 24f90f1..8e02808 100644
--- a/app/src/main/java/com/gotcha/tools/SmsTool.kt
+++ b/app/src/main/java/com/gotcha/tools/SmsTool.kt
@@ -218,7 +218,15 @@ class SmsTool(private val context: Context) {
alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + delayMs, pi)
}
- fun readRecentSms(limit: Int, fromAddress: String? = null): ToolResult {
+ fun readRecentSms(
+ limit: Int,
+ fromAddress: String? = null,
+ fromDate: String? = null,
+ toDate: String? = null,
+ unreadOnly: Boolean? = null,
+ search: String? = null,
+ includeSent: Boolean? = null
+ ): ToolResult {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_SMS)
!= PackageManager.PERMISSION_GRANTED
) {
@@ -229,42 +237,126 @@ class SmsTool(private val context: Context) {
}
val take = limit.coerceIn(1, 50)
return try {
- 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,
- 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.")
- 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 = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
- .format(Date(cursor.getLong(dateIdx)))
- out.append("- $date from $addr: $body\n")
- count++
+ val selection = StringBuilder()
+ val selectionArgs = mutableListOf<String>()
+
+ if (!fromAddress.isNullOrBlank()) {
+ if (selection.isNotEmpty()) selection.append(" AND ")
+ selection.append("${Telephony.Sms.ADDRESS} LIKE ?")
+ selectionArgs.add("%$fromAddress%")
+ }
+
+ 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("${Telephony.Sms.DATE} >= ?")
+ selectionArgs.add(fromMillis.toString())
}
- 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")
+ }
+ 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("${Telephony.Sms.DATE} <= ?")
+ selectionArgs.add(toMillis.toString())
+ }
+ }
+
+ if (unreadOnly == true) {
+ if (selection.isNotEmpty()) selection.append(" AND ")
+ selection.append("${Telephony.Sms.READ} = 0")
+ }
+
+ if (!search.isNullOrBlank()) {
+ if (selection.isNotEmpty()) selection.append(" AND ")
+ selection.append("${Telephony.Sms.BODY} LIKE ?")
+ selectionArgs.add("%$search%")
+ }
+
+ val sel: String? = if (selection.isNotEmpty()) selection.toString() else null
+ val selArgs: Array<String>? = selectionArgs.toTypedArray().ifEmpty { null }
+
+ val out = StringBuilder()
+
+ // Inbox messages
+ querySms(Telephony.Sms.Inbox.CONTENT_URI, take, sel, selArgs, out, "from")
+
+ // Sent messages (optional)
+ if (includeSent == true) {
+ querySms(Telephony.Sms.Sent.CONTENT_URI, take, sel, selArgs, out, "to")
+ }
+
+ if (out.isEmpty()) {
+ val hint = buildString {
+ if (!fromAddress.isNullOrBlank()) append(" from '$fromAddress'")
+ if (unreadOnly == true) append(" unread")
+ if (!search.isNullOrBlank()) append(" matching '$search'")
+ }
+ ToolResult.ok("The SMS inbox is empty$hint.")
+ } else {
+ ToolResult.ok(out.trimEnd().toString())
}
} catch (e: Exception) {
ToolResult.error("Could not read messages: ${e.message}")
}
}
+ private fun querySms(
+ uri: android.net.Uri,
+ take: Int,
+ selection: String?,
+ selectionArgs: Array<String>?,
+ out: StringBuilder,
+ direction: String
+ ) {
+ context.contentResolver.query(
+ uri,
+ arrayOf(Telephony.Sms.ADDRESS, Telephony.Sms.BODY, Telephony.Sms.DATE, Telephony.Sms._ID),
+ selection, selectionArgs,
+ "${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)
+ var count = 0
+ while (cursor.moveToNext() && count < take) {
+ val addr = cursor.getString(addrIdx) ?: "unknown"
+ val name = resolveSmsContactName(addr)
+ val sender = if (name != null) "$name ($addr)" else addr
+ val body = (cursor.getString(bodyIdx) ?: "").take(300)
+ val date = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
+ .format(Date(cursor.getLong(dateIdx)))
+ when (direction) {
+ "from" -> out.append("- $date from $sender: $body\n")
+ "to" -> out.append("- $date to $sender: $body\n")
+ }
+ count++
+ }
+ }
+ }
+
+ private fun resolveSmsContactName(number: String): String? {
+ return try {
+ val uri = android.net.Uri.withAppendedPath(
+ android.provider.ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
+ android.net.Uri.encode(number)
+ )
+ context.contentResolver.query(
+ uri,
+ arrayOf(android.provider.ContactsContract.PhoneLookup.DISPLAY_NAME),
+ null, null, null
+ )?.use { cursor ->
+ if (cursor.moveToFirst()) {
+ cursor.getString(cursor.getColumnIndexOrThrow(
+ android.provider.ContactsContract.PhoneLookup.DISPLAY_NAME
+ ))
+ } else null
+ }
+ } catch (_: Exception) { null }
+ }
+
private fun getConversationThread(number: String): String? {
return try {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_SMS)
diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
index dfe29fa..719923e 100644
--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
@@ -380,17 +380,38 @@ object ToolDefinitions {
val readRecentSms = tool(
"read_recent_sms",
- "Read the most recent received SMS messages from the inbox (sender, time, body). " +
- "Supports optional filter by sender address.",
+ "Read SMS messages from the inbox (and optionally sent folder) with filters. " +
+ "Supports filtering by sender, date range, unread status, and body keyword search. " +
+ "Contact names are resolved automatically when available.",
schema {
putJsonObject("properties") {
putJsonObject("limit") {
put("type", "integer")
- put("description", "How many recent messages to return (1-50). Default 10.")
+ put("description", "How many 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).")
+ put("description", "Filter by sender/recipient address (partial match, e.g. a contact name or phone number).")
+ }
+ putJsonObject("from_date") {
+ put("type", "string")
+ put("description", "Start date, e.g. '2026-01-01'. Only messages on or after this date.")
+ }
+ putJsonObject("to_date") {
+ put("type", "string")
+ put("description", "End date, e.g. '2026-01-31'. Only messages on or before this date.")
+ }
+ putJsonObject("unread_only") {
+ put("type", "boolean")
+ put("description", "Only show unread messages. Default false.")
+ }
+ putJsonObject("search") {
+ put("type", "string")
+ put("description", "Filter messages whose body contains this text (case-insensitive).")
+ }
+ putJsonObject("include_sent") {
+ put("type", "boolean")
+ put("description", "Also include sent messages alongside inbox messages. Default false.")
}
}
}
@@ -398,12 +419,25 @@ object ToolDefinitions {
val listCalendarEvents = tool(
"list_calendar_events",
- "List upcoming calendar events within a number of days from now.",
+ "List calendar events within a date range. Supports looking ahead (days_ahead) or explicit " +
+ "from/to dates, title keyword search, and shows status, description preview, and calendar name.",
schema {
putJsonObject("properties") {
putJsonObject("days_ahead") {
put("type", "integer")
- put("description", "How many days ahead to include (1-365). Default 7.")
+ put("description", "How many days ahead to include (1-365). Default 7 when from_date/to_date not set.")
+ }
+ putJsonObject("from_date") {
+ put("type", "string")
+ put("description", "Start date, e.g. '2026-01-01'. Overrides days_ahead.")
+ }
+ putJsonObject("to_date") {
+ put("type", "string")
+ put("description", "End date, e.g. '2026-01-31'. Defaults to one day after from_date.")
+ }
+ putJsonObject("search") {
+ put("type", "string")
+ put("description", "Filter events whose title contains this text (case-insensitive).")
}
}
}
@@ -411,7 +445,8 @@ object ToolDefinitions {
val createCalendarEvent = tool(
"create_calendar_event",
- "Add an event to the device's primary calendar.",
+ "Add an event to a calendar. Supports optional description, all-day flag, reminder, " +
+ "and calendar selection. Defaults to the primary writable calendar.",
schema {
putJsonObject("properties") {
putJsonObject("title") {
@@ -430,6 +465,22 @@ object ToolDefinitions {
put("type", "string")
put("description", "Optional event location.")
}
+ putJsonObject("description") {
+ put("type", "string")
+ put("description", "Optional notes or description for the event.")
+ }
+ putJsonObject("all_day") {
+ put("type", "boolean")
+ put("description", "Set as an all-day event. Default false.")
+ }
+ putJsonObject("reminder_minutes") {
+ put("type", "integer")
+ put("description", "Reminder before the event, in minutes. Default is no custom reminder.")
+ }
+ putJsonObject("calendar_name") {
+ put("type", "string")
+ put("description", "Calendar account name to add the event to (e.g. 'Work', 'Personal'). Defaults to the primary writable calendar.")
+ }
}
putJsonArray("required") {
add("title")
@@ -592,9 +643,17 @@ object ToolDefinitions {
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") {} }
+ "Report the device's location (latitude/longitude, accuracy, altitude, speed, bearing, " +
+ "and a nearby address if available). Also returns a Google Maps link. " +
+ "Can request a fresh GPS fix instead of the last-known location. Needs the Location permission.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("fresh") {
+ put("type", "boolean")
+ put("description", "If true, request a fresh GPS fix (takes a few seconds). Default false (uses last-known location).")
+ }
+ }
+ }
)
val listInstalledApps = tool(
diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
index be4c269..8d42fc4 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -163,14 +163,28 @@ class ToolExecutor(context: Context) {
)
"read_recent_sms" -> smsTool.readRecentSms(
limit = args.requireInt("limit") ?: 10,
- fromAddress = args.requireString("from_address")
+ fromAddress = args.requireString("from_address"),
+ fromDate = args.requireString("from_date"),
+ toDate = args.requireString("to_date"),
+ unreadOnly = args["unread_only"]?.jsonPrimitive?.booleanOrNull,
+ search = args.requireString("search"),
+ includeSent = args["include_sent"]?.jsonPrimitive?.booleanOrNull
+ )
+ "list_calendar_events" -> calendarTool.listEvents(
+ daysAhead = args.requireInt("days_ahead"),
+ fromDate = args.requireString("from_date"),
+ toDate = args.requireString("to_date"),
+ search = args.requireString("search")
)
- "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")
+ location = args.requireString("location"),
+ description = args.requireString("description"),
+ allDay = args["all_day"]?.jsonPrimitive?.booleanOrNull,
+ reminderMinutes = args.requireInt("reminder_minutes"),
+ calendarName = args.requireString("calendar_name")
)
"set_alarm" -> alarmTool.setAlarm(
hour = args.requireInt("hour") ?: return missing("hour"),
@@ -200,7 +214,9 @@ class ToolExecutor(context: Context) {
"set_dnd" -> deviceTool.setDnd(
args["enabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("enabled")
)
- "get_location" -> locationTool.getLocation()
+ "get_location" -> locationTool.getLocation(
+ fresh = args["fresh"]?.jsonPrimitive?.booleanOrNull
+ )
"list_installed_apps" -> appsTool.listInstalledApps(args.requireString("search"))
"uninstall_app" -> appsTool.uninstallApp(args.requireString("package_name") ?: return missing("package_name"))
"get_app_usage" -> appsTool.getAppUsage(args.requireInt("days") ?: 7)