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: improve tool error messages with actionable suggestions and usage hints

Rishabh Bajpaib44b8a6a7c63
diff --git a/.gitignore b/.gitignore
index b707e70..90f440c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -97,3 +97,5 @@ Desktop.ini
*.swp
*.tmp
temp.json
+
+taste.md
diff --git a/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt b/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
index 1e26d85..c774f46 100644
--- a/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
+++ b/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
@@ -49,15 +49,24 @@ class AccessibilityTool(private val context: Context) {
if (service.tapByText(text)) {
ToolResult.ok("Tapped an element matching \"$text\".")
} else {
- ToolResult.error("Found no clickable element matching \"$text\" on screen.")
+ ToolResult.error(
+ "Found no clickable element matching \"$text\" on screen. " +
+ "Use read_screen to see available elements and try tap_index with the correct index."
+ )
}
x != null && y != null ->
if (service.tapAt(x.toFloat(), y.toFloat())) {
ToolResult.ok("Tapped at ($x, $y).")
} else {
- ToolResult.error("Could not dispatch the tap gesture.")
+ ToolResult.error(
+ "Could not dispatch the tap gesture. The accessibility service may be busy — you may try " +
+ "read_screen first to refresh state."
+ )
}
- else -> ToolResult.error("Provide either 'text' to match, or both 'x' and 'y' coordinates.")
+ else -> ToolResult.error(
+ "Provide either 'text' to match, or both 'x' and 'y' coordinates. You may also use tap_index with " +
+ "an index from read_screen."
+ )
}
}
@@ -69,15 +78,24 @@ class AccessibilityTool(private val context: Context) {
if (service.longPressByText(text)) {
ToolResult.ok("Long-pressed an element matching \"$text\".")
} else {
- ToolResult.error("Found no element matching \"$text\" on screen.")
+ ToolResult.error(
+ "Found no element matching \"$text\" on screen. You may use read_screen to see available elements, " +
+ "then try long_press_index with the correct index."
+ )
}
x != null && y != null ->
if (service.longPressAt(x.toFloat(), y.toFloat())) {
ToolResult.ok("Long-pressed at ($x, $y).")
} else {
- ToolResult.error("Could not dispatch the long-press gesture.")
+ ToolResult.error(
+ "Could not dispatch the long-press gesture. The accessibility service may be busy — you may try " +
+ "read_screen first to refresh state, then retry."
+ )
}
- else -> ToolResult.error("Provide either 'text' to match, or both 'x' and 'y' coordinates.")
+ else -> ToolResult.error(
+ "Provide either 'text' to match, or both 'x' and 'y' coordinates. You may also use long_press_index with " +
+ "an index from read_screen."
+ )
}
}
@@ -109,7 +127,9 @@ class AccessibilityTool(private val context: Context) {
return if (service.swipe(sx, sy, ex, ey)) {
ToolResult.ok("Swiped from (${sx.toInt()}, ${sy.toInt()}) to (${ex.toInt()}, ${ey.toInt()}).")
} else {
- ToolResult.error("Could not dispatch the swipe gesture.")
+ ToolResult.error(
+ "Could not dispatch the swipe gesture. You may ensure the screen is not animating and try again."
+ )
}
}
val metrics = context.resources.displayMetrics
@@ -128,7 +148,9 @@ class AccessibilityTool(private val context: Context) {
return if (service.swipe(sx, sy, ex, ey, 500)) {
ToolResult.ok("Swiped $direction.")
} else {
- ToolResult.error("Could not dispatch the swipe gesture.")
+ ToolResult.error(
+ "Could not dispatch the swipe gesture. The screen may be animating — you could wait and try again."
+ )
}
}
@@ -142,7 +164,10 @@ class AccessibilityTool(private val context: Context) {
index: Int
): ToolResult? {
val element = ScreenPerception.resolveElementByIndex(index)
- ?: return ToolResult.error("No UI element with index $index found on screen.")
+ ?: return ToolResult.error(
+ "No UI element with index $index found on screen. The screen may have changed — use read_screen " +
+ "to refresh the element list."
+ )
val parts = element.bounds.split(",").map { it.trim().toIntOrNull() }
if (parts.size != 4 || parts.any { it == null }) return null
val cx = (parts[0]!! + parts[2]!!) / 2f
@@ -167,7 +192,10 @@ class AccessibilityTool(private val context: Context) {
left + w * 0.2f,
(top + bottom) / 2f
) // Scroll Right (physical swipe left)
- else -> return ToolResult.error("Provide a direction (up/down/left/right) when using index.")
+ else -> return ToolResult.error(
+ "Provide a direction (up/down/left/right) when using index. You may also try swipe without an index to " +
+ "scroll the whole screen."
+ )
}
return if (service.swipe(sx, sy, ex, ey, 500)) {
ToolResult.ok("Swiped $direction on element $index.")
@@ -181,7 +209,10 @@ class AccessibilityTool(private val context: Context) {
val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()
if (index != null) {
val element = ScreenPerception.resolveElementByIndex(index)
- ?: return ToolResult.error("No UI element with index $index found on screen.")
+ ?: return ToolResult.error(
+ "No UI element with index $index found on screen. The screen may have changed — use " +
+ "read_screen to refresh the element list"
+ )
if (service.typeTextIntoNodeByBounds(element.bounds, text)) {
return ToolResult.ok("Typed \"$text\" into element $index.")
}
@@ -211,7 +242,10 @@ class AccessibilityTool(private val context: Context) {
fun tapByIndex(index: Int): ToolResult {
val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()
val element = ScreenPerception.resolveElementByIndex(index)
- ?: return ToolResult.error("No UI element with index $index found on screen.")
+ ?: return ToolResult.error(
+ "No UI element with index $index found on screen. The screen may have changed — use read_screen " +
+ "to refresh the element list."
+ )
val parts = element.bounds.split(",").map { it.trim().toIntOrNull() }
if (parts.size != 4 || parts.any { it == null }) {
return ToolResult.error("Invalid bounds for element $index.")
@@ -221,7 +255,10 @@ class AccessibilityTool(private val context: Context) {
return if (service.tapAt(cx, cy)) {
ToolResult.ok("Tapped element $index: \"${element.text.take(50)}\" at (${cx.toInt()}, ${cy.toInt()}).")
} else {
- ToolResult.error("Could not dispatch the tap gesture for element $index.")
+ ToolResult.error(
+ "Could not dispatch the tap gesture for element $index. The accessibility service may be busy — try " +
+ "read_screen first and retry."
+ )
}
}
@@ -229,7 +266,10 @@ class AccessibilityTool(private val context: Context) {
fun longPressByIndex(index: Int): ToolResult {
val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()
val element = ScreenPerception.resolveElementByIndex(index)
- ?: return ToolResult.error("No UI element with index $index found on screen.")
+ ?: return ToolResult.error(
+ "No UI element with index $index found on screen. The screen may have changed — use read_screen " +
+ "to refresh the element list."
+ )
val parts = element.bounds.split(",").map { it.trim().toIntOrNull() }
if (parts.size != 4 || parts.any { it == null }) {
return ToolResult.error("Invalid bounds for element $index.")
@@ -241,7 +281,10 @@ class AccessibilityTool(private val context: Context) {
"Long-pressed element $index: \"${element.text.take(50)}\" at (${cx.toInt()}, ${cy.toInt()})."
)
} else {
- ToolResult.error("Could not dispatch the long-press gesture for element $index.")
+ ToolResult.error(
+ "Could not dispatch the long-press gesture for element $index. The accessibility service may be busy — try " +
+ "read_screen first and retry."
+ )
}
}
diff --git a/app/src/main/java/com/gotcha/tools/AppsTool.kt b/app/src/main/java/com/gotcha/tools/AppsTool.kt
index 395fd93..45f63c3 100644
--- a/app/src/main/java/com/gotcha/tools/AppsTool.kt
+++ b/app/src/main/java/com/gotcha/tools/AppsTool.kt
@@ -67,7 +67,9 @@ class AppsTool(private val context: Context) {
)
}
} catch (e: Exception) {
- ToolResult.error("Could not list apps: ${e.message}")
+ ToolResult.error(
+ "Could not list apps: ${e.message}. You may check that the system is not restricting package visibility."
+ )
}
}
@@ -78,7 +80,11 @@ class AppsTool(private val context: Context) {
*/
fun uninstallApp(packageName: String): ToolResult {
val pkg = packageName.trim()
- if (pkg.isEmpty()) return ToolResult.error("Please provide the app name or package name.")
+ if (pkg.isEmpty()) {
+ return ToolResult.error(
+ "Please provide the app name or package name. You may use list_installed_apps to discover the correct name."
+ )
+ }
val pm = context.packageManager
// Try exact package match first
@@ -108,7 +114,8 @@ class AppsTool(private val context: Context) {
}
return ToolResult.error(
- "No app found matching '$packageName'. Use list_installed_apps to find the correct package name."
+ "No app found matching '$packageName'. You may use list_installed_apps to find the correct package name or try " +
+ "a shorter part of the app name."
)
}
@@ -129,7 +136,11 @@ class AppsTool(private val context: Context) {
} catch (_: Exception) {
false
}
- if (!installed) return ToolResult.error("No app with package '$packageName' is installed.")
+ if (!installed) {
+ return ToolResult.error(
+ "No app with package '$packageName' is installed. You may use list_installed_apps to verify the correct name."
+ )
+ }
val label = try {
pm.getApplicationLabel(pm.getApplicationInfo(packageName, 0)).toString()
diff --git a/app/src/main/java/com/gotcha/tools/CalendarTool.kt b/app/src/main/java/com/gotcha/tools/CalendarTool.kt
index b20611d..5eb88a7 100644
--- a/app/src/main/java/com/gotcha/tools/CalendarTool.kt
+++ b/app/src/main/java/com/gotcha/tools/CalendarTool.kt
@@ -88,7 +88,9 @@ class CalendarTool(private val context: Context) {
selectionArgs,
"${CalendarContract.Instances.BEGIN} ASC"
).use { cursor ->
- if (cursor == null) return ToolResult.error("Could not read the calendar.")
+ if (cursor == null) {
+ return ToolResult.error("Could not read the calendar (permission may not be granted).")
+ }
val idIdx = cursor.getColumnIndexOrThrow(CalendarContract.Instances.EVENT_ID)
val titleIdx = cursor.getColumnIndexOrThrow(CalendarContract.Instances.TITLE)
val beginIdx = cursor.getColumnIndexOrThrow(CalendarContract.Instances.BEGIN)
@@ -146,7 +148,11 @@ class CalendarTool(private val context: Context) {
reminderMinutes: Int? = null,
calendarName: String? = null
): ToolResult {
- if (title.isBlank()) return ToolResult.error("Please provide a title for the event.")
+ if (title.isBlank()) {
+ return ToolResult.error(
+ "Please provide a title for the event. The title is required to create one."
+ )
+ }
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_CALENDAR)
!= PackageManager.PERMISSION_GRANTED
) {
@@ -156,11 +162,17 @@ class CalendarTool(private val context: Context) {
)
}
val startMs = parseWhen(start)
- ?: return ToolResult.error("Could not understand the start time '$start'. Use 'yyyy-MM-dd HH:mm' or epoch millis.")
+ ?: return ToolResult.error(
+ "Could not understand the start time '$start'. Use 'yyyy-MM-dd HH:mm' (e.g. '2026-07-17 15:30') " +
+ "or epoch milliseconds."
+ )
val endMs = if (end.isNullOrBlank()) {
startMs + 60 * 60 * 1000
} else {
- parseWhen(end) ?: return ToolResult.error("Could not understand the end time '$end'.")
+ parseWhen(end) ?: return ToolResult.error(
+ "Could not understand the end time '$end'. Use 'yyyy-MM-dd HH:mm' (e.g. " +
+ "'2026-07-17 17:00') or epoch milliseconds."
+ )
}
if (allDay == true) {
@@ -180,7 +192,10 @@ class CalendarTool(private val context: Context) {
} else {
null
?: defaultWritableCalendarId()
- ?: return ToolResult.error("No writable calendar was found on this device.")
+ ?: return ToolResult.error(
+ "No writable calendar was found on this device. You may add a Google account or use the " +
+ "device's calendar app to set one up."
+ )
}
val values = ContentValues().apply {
@@ -194,7 +209,10 @@ class CalendarTool(private val context: Context) {
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.")
+ ?: return ToolResult.error(
+ "The calendar rejected the new event. You may check that the calendar is writable and try " +
+ "again."
+ )
// Add reminder if requested
if (reminderMinutes != null && reminderMinutes >= 0) {
@@ -238,11 +256,17 @@ class CalendarTool(private val context: Context) {
val values = ContentValues()
if (title != null) values.put(CalendarContract.Events.TITLE, title)
if (start != null) {
- val ms = parseWhen(start) ?: return ToolResult.error("Could not understand the start time '$start'.")
+ val ms = parseWhen(start) ?: return ToolResult.error(
+ "Could not understand the start time '$start'. Use 'yyyy-MM-dd " +
+ "HH:mm' (e.g. '2026-07-17 15:30') or epoch milliseconds."
+ )
values.put(CalendarContract.Events.DTSTART, ms)
}
if (end != null) {
- val ms = parseWhen(end) ?: return ToolResult.error("Could not understand the end time '$end'.")
+ val ms = parseWhen(end) ?: return ToolResult.error(
+ "Could not understand the end time '$end'. Use 'yyyy-MM-dd HH:mm' " +
+ "(e.g. '2026-07-17 17:00') or epoch milliseconds."
+ )
values.put(CalendarContract.Events.DTEND, ms)
}
if (location != null) values.put(CalendarContract.Events.EVENT_LOCATION, location)
@@ -252,7 +276,9 @@ class CalendarTool(private val context: Context) {
val uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId)
val rows = context.contentResolver.update(uri, values, null, null)
if (rows == 0) {
- return ToolResult.error("Event $eventId not found or could not be updated.")
+ return ToolResult.error(
+ "Event $eventId not found or could not be updated. You may use list_calendar_events to find the correct event ID."
+ )
}
// Update reminders: clear existing, add new if requested
@@ -295,7 +321,9 @@ class CalendarTool(private val context: Context) {
val uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId)
val rows = context.contentResolver.delete(uri, null, null)
if (rows == 0) {
- return ToolResult.error("Event $eventId not found or could not be deleted.")
+ return ToolResult.error(
+ "Event $eventId not found or could not be deleted. You may use list_calendar_events to verify the correct event ID."
+ )
}
ToolResult.ok("Deleted event $eventId.")
} catch (e: Exception) {
diff --git a/app/src/main/java/com/gotcha/tools/ContactsTool.kt b/app/src/main/java/com/gotcha/tools/ContactsTool.kt
index 6530ea4..8573eff 100644
--- a/app/src/main/java/com/gotcha/tools/ContactsTool.kt
+++ b/app/src/main/java/com/gotcha/tools/ContactsTool.kt
@@ -13,7 +13,10 @@ class ContactsTool(private val context: Context) {
@Suppress("CyclomaticComplexMethod")
fun findContact(name: String? = null, number: String? = null): ToolResult {
if (name.isNullOrBlank() && number.isNullOrBlank()) {
- return ToolResult.error("Provide either a name or a phone number to search for.")
+ return ToolResult.error(
+ "Provide either a name or a phone number to search for. You may check the call log with read_call_log " +
+ "first to find recent contacts."
+ )
}
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED
@@ -49,7 +52,11 @@ class ContactsTool(private val context: Context) {
selectionArgs.toTypedArray(),
"${ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME} ASC"
).use { cursor ->
- if (cursor == null) return ToolResult.error("Could not read contacts.")
+ if (cursor == null) {
+ return ToolResult.error(
+ "Could not read contacts. You may check that the Contacts permission is granted in Settings → Permissions."
+ )
+ }
val nameIdx = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
val numIdx = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER)
val typeIdx = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.TYPE)
@@ -78,7 +85,10 @@ class ContactsTool(private val context: Context) {
}
if (contacts.isEmpty()) {
val hint = if (!name.isNullOrBlank()) "'$name'" else "'$number'"
- return ToolResult.ok("No contact matching $hint was found.")
+ return ToolResult.ok(
+ "No contact matching $hint was found. You may try a partial name, search by phone number instead, or check " +
+ "read_call_log for recently contacted people."
+ )
}
// Group by contact name for richer output
val grouped = contacts.groupBy { it["name"]!! }
@@ -101,7 +111,9 @@ class ContactsTool(private val context: Context) {
}
ToolResult.ok(sb.toString().trimEnd())
} catch (e: Exception) {
- ToolResult.error("Could not look up contacts: ${e.message}")
+ ToolResult.error(
+ "Could not look up contacts: ${e.message}. You may verify the Contacts permission is granted and try again."
+ )
}
}
@@ -172,8 +184,16 @@ class ContactsTool(private val context: Context) {
): 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 (displayName.isEmpty()) {
+ return ToolResult.error(
+ "Please provide a name for the new contact. You may use find_contact to look up the correct spelling if needed."
+ )
+ }
+ if (phone.isEmpty()) {
+ return ToolResult.error(
+ "Please provide a phone number for the new contact. You may use find_contact or read_call_log to find the number."
+ )
+ }
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_CONTACTS)
!= PackageManager.PERMISSION_GRANTED
) {
@@ -266,7 +286,9 @@ class ContactsTool(private val context: Context) {
}
ToolResult.ok("Added contact '$displayName'$extras.")
} catch (e: Exception) {
- ToolResult.error("Could not add the contact: ${e.message}")
+ ToolResult.error(
+ "Could not add the contact: ${e.message}. You may check that the Contacts permission is granted and try again."
+ )
}
}
diff --git a/app/src/main/java/com/gotcha/tools/EditTool.kt b/app/src/main/java/com/gotcha/tools/EditTool.kt
index d16ef76..670da73 100644
--- a/app/src/main/java/com/gotcha/tools/EditTool.kt
+++ b/app/src/main/java/com/gotcha/tools/EditTool.kt
@@ -17,8 +17,16 @@ class EditTool(private val context: Context) {
}
fun edit(path: String, oldString: String, newString: String, replaceAll: Boolean): ToolResult {
- if (oldString.isBlank()) return ToolResult.error("oldString cannot be blank.")
- if (newString == oldString) return ToolResult.error("newString must differ from oldString.")
+ if (oldString.isBlank()) {
+ return ToolResult.error(
+ "oldString cannot be blank. Provide the exact text you want to replace."
+ )
+ }
+ if (newString == oldString) {
+ return ToolResult.error(
+ "newString must differ from oldString. Provide the replacement text."
+ )
+ }
val resolved = resolver.resolveForWrite(path)
return when (resolved) {
@@ -30,10 +38,15 @@ class EditTool(private val context: Context) {
if (perm != null) return perm
if (!file.exists()) {
return ToolResult.error(
- "File '$path' does not exist (resolved: ${file.canonicalPath})."
+ "File '$path' does not exist (resolved: ${file.canonicalPath}). " +
+ "You may verify the path with list_files or glob first."
+ )
+ }
+ if (!file.isFile) {
+ return ToolResult.error(
+ "'$path' is not a regular file. You may use list_files to see what is at that path."
)
}
- if (!file.isFile) return ToolResult.error("'$path' is not a regular file.")
if (file.length() > MAX_FILE_BYTES) return ToolResult.error("File too large to edit (max 1 MB).")
try {
@@ -45,13 +58,14 @@ class EditTool(private val context: Context) {
if (count == 0) {
return ToolResult.error(
"No match found for the specified text in '$path'. " +
- "The text must match exactly, including whitespace and indentation."
+ "You may use grep or read_file to locate the exact text first — the match must be exact, including " +
+ "whitespace and indentation."
)
}
if (count > 1 && !replaceAll) {
return ToolResult.error(
"Found $count matches in '$path'. " +
- "Provide more surrounding context or use replaceAll=true."
+ "You may provide more surrounding context in oldString, or pass replaceAll=true to replace all occurrences."
)
}
diff --git a/app/src/main/java/com/gotcha/tools/FileTool.kt b/app/src/main/java/com/gotcha/tools/FileTool.kt
index 9cfb3c7..9564a86 100644
--- a/app/src/main/java/com/gotcha/tools/FileTool.kt
+++ b/app/src/main/java/com/gotcha/tools/FileTool.kt
@@ -81,7 +81,10 @@ class FileTool(private val context: Context) {
if (!file.exists()) {
val archiveResult = tryReadArchiveEntry(originalPath)
if (archiveResult != null) return archiveResult
- return ToolResult.error("Path '$originalPath' does not exist (resolved: ${file.canonicalPath}).")
+ return ToolResult.error(
+ "Path '$originalPath' does not exist (resolved: ${file.canonicalPath}). You may use list_files or glob " +
+ "to discover valid paths."
+ )
}
if (file.isDirectory) return listResolved(file, originalPath, null, null, null, false, null)
val ext = file.extension.lowercase()
@@ -174,7 +177,11 @@ class FileTool(private val context: Context) {
val bytes = file.readBytes()
val mime = resolver.detectMime(bytes)
if (mime == null || !resolver.isImageMime(mime)) {
- return ToolResult.error("File '${file.name}' is not a recognized image format.")
+ return ToolResult.error(
+ "File '${file.name}' is not a recognized image format. Supported: ${IMAGE_EXTENSIONS.joinToString(
+ ", "
+ )}. Use read_file without format detection for text/binary."
+ )
}
val opts = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, opts)
@@ -300,7 +307,10 @@ class FileTool(private val context: Context) {
} else {
""
}
- return ToolResult.error("Entry '$entryPath' not found in '${archiveFile.name}'.$hint")
+ return ToolResult.error(
+ "Entry '$entryPath' not found in '${archiveFile.name}'.$hint You may use read_file on the archive directly (without an " +
+ "entry path) to list its contents first."
+ )
}
if (entry.isDirectory) {
val children = zf.entries().asSequence()
@@ -475,7 +485,11 @@ class FileTool(private val context: Context) {
is FileResolver.ResolveResult.Error -> ToolResult.error(resolved.message)
is FileResolver.ResolveResult.Ok -> {
val f = resolved.file
- if (!f.exists()) return ToolResult.error("Path '$path' does not exist.")
+ if (!f.exists()) {
+ return ToolResult.error(
+ "Path '$path' does not exist. You may use list_files or glob to discover valid paths."
+ )
+ }
val perm = resolver.checkReadPermission(f)
if (perm != null) return perm
val type = when {
diff --git a/app/src/main/java/com/gotcha/tools/GlobTool.kt b/app/src/main/java/com/gotcha/tools/GlobTool.kt
index 6e073d2..153ec5a 100644
--- a/app/src/main/java/com/gotcha/tools/GlobTool.kt
+++ b/app/src/main/java/com/gotcha/tools/GlobTool.kt
@@ -21,7 +21,11 @@ class GlobTool(private val context: Context) {
}
fun glob(path: String, pattern: String): ToolResult {
- if (pattern.isBlank()) return ToolResult.error("Glob pattern cannot be empty.")
+ if (pattern.isBlank()) {
+ return ToolResult.error(
+ "Glob pattern cannot be empty. Use '*' for all files, '**/*.kt' for Kotlin files recursively."
+ )
+ }
val resolved = resolver.resolveForRead(path)
return when (resolved) {
@@ -31,7 +35,11 @@ class GlobTool(private val context: Context) {
val root = resolved.file
val perm = resolver.checkReadPermission(root)
if (perm != null) return perm
- if (!root.exists()) return ToolResult.error("Path '$path' does not exist.")
+ if (!root.exists()) {
+ return ToolResult.error(
+ "Path '$path' does not exist. You may verify the path with list_files first."
+ )
+ }
val regex = globToRegex(pattern)
val results = mutableListOf<String>()
@@ -63,7 +71,9 @@ class GlobTool(private val context: Context) {
}
if (results.isEmpty()) {
- return ToolResult.ok("No files matching '$pattern' found in '$path'.")
+ return ToolResult.ok(
+ "No files matching '$pattern' found in '$path'. You may try a broader pattern (e.g. '*', '**', or '**/*.txt')."
+ )
}
val truncated = if (aborted) "\n…(truncated, max $MAX_RESULTS results)" else ""
return ToolResult.ok(
diff --git a/app/src/main/java/com/gotcha/tools/GrepTool.kt b/app/src/main/java/com/gotcha/tools/GrepTool.kt
index 2013163..4dcaddf 100644
--- a/app/src/main/java/com/gotcha/tools/GrepTool.kt
+++ b/app/src/main/java/com/gotcha/tools/GrepTool.kt
@@ -20,11 +20,17 @@ class GrepTool(private val context: Context) {
@Suppress("CyclomaticComplexMethod", "NestedBlockDepth", "LoopWithTooManyJumpStatements")
fun grep(path: String, pattern: String, include: String?): ToolResult {
- if (pattern.isBlank()) return ToolResult.error("Search pattern cannot be empty.")
+ if (pattern.isBlank()) {
+ return ToolResult.error(
+ "Search pattern cannot be empty. Provide a text pattern or regex to search for (e.g. 'error', 'TODO', 'function')."
+ )
+ }
val regex = try {
Regex(pattern, setOf(RegexOption.IGNORE_CASE))
} catch (e: Exception) {
- return ToolResult.error("Invalid regex pattern: ${e.message}")
+ return ToolResult.error(
+ "Invalid regex pattern: ${e.message}. You may try a simpler text pattern without special characters."
+ )
}
val resolved = resolver.resolveForRead(path)
@@ -35,7 +41,11 @@ class GrepTool(private val context: Context) {
val root = resolved.file
val perm = resolver.checkReadPermission(root)
if (perm != null) return perm
- if (!root.exists()) return ToolResult.error("Path '$path' does not exist.")
+ if (!root.exists()) {
+ return ToolResult.error(
+ "Path '$path' does not exist. You may verify the path with list_files or glob first."
+ )
+ }
val includeGlob = include?.let {
try {
@@ -106,7 +116,11 @@ class GrepTool(private val context: Context) {
}
return if (results.isEmpty()) {
- ToolResult.ok("No matches found for pattern '$pattern' in '$path'.")
+ ToolResult.ok(
+ "No matches found for pattern '$pattern' in '$path'. You may try a different pattern, a broader path, or check " +
+ "the " +
+ "file content with read_file first."
+ )
} else {
val truncated = if (matchCount >= MAX_MATCHES || filesSearched >= MAX_FILES) {
"\n…(truncated, max $MAX_MATCHES matches)"
diff --git a/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt b/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt
index 924259b..4185a4b 100644
--- a/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt
+++ b/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt
@@ -111,7 +111,10 @@ class MediaCaptureTool(private val context: Context) {
)
}
if (recorder != null) {
- return ToolResult.error("A recording is already in progress. Stop it before starting a new one.")
+ return ToolResult.error(
+ "A recording is already in progress. You may stop it with stop_audio_recording before starting a new one, or check " +
+ "status with get_audio_recording_status."
+ )
}
return try {
val file = if (!outputPath.isNullOrBlank()) {
@@ -183,7 +186,10 @@ class MediaCaptureTool(private val context: Context) {
}
fun stopAudioRecording(): ToolResult {
- val rec = recorder ?: return ToolResult.error("No recording is in progress.")
+ val rec = recorder ?: return ToolResult.error(
+ "No recording is in progress. Use start_audio_recording to begin one, or check " +
+ "status with get_audio_recording_status."
+ )
return try {
rec.stop()
val file = recordingFile
@@ -222,8 +228,15 @@ class MediaCaptureTool(private val context: Context) {
}
fun pauseAudioRecording(): ToolResult {
- val rec = recorder ?: return ToolResult.error("No recording is in progress.")
- if (recordingPaused) return ToolResult.error("Recording is already paused.")
+ val rec = recorder ?: return ToolResult.error(
+ "No recording is in progress. Use start_audio_recording to begin one, or check " +
+ "status with get_audio_recording_status."
+ )
+ if (recordingPaused) {
+ return ToolResult.error(
+ "Recording is already paused. You may resume it with resume_audio_recording or stop it with stop_audio_recording."
+ )
+ }
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
return ToolResult.error("Pause/resume requires Android 7.0+ (API 24).")
}
@@ -237,8 +250,15 @@ class MediaCaptureTool(private val context: Context) {
}
fun resumeAudioRecording(): ToolResult {
- val rec = recorder ?: return ToolResult.error("No recording is in progress.")
- if (!recordingPaused) return ToolResult.error("Recording is not paused.")
+ val rec = recorder ?: return ToolResult.error(
+ "No recording is in progress. Use start_audio_recording to begin one, or check " +
+ "status with get_audio_recording_status."
+ )
+ if (!recordingPaused) {
+ return ToolResult.error(
+ "Recording is not paused. Use pause_audio_recording first, or stop the recording with stop_audio_recording."
+ )
+ }
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
return ToolResult.error("Pause/resume requires Android 7.0+ (API 24).")
}
diff --git a/app/src/main/java/com/gotcha/tools/NotificationTool.kt b/app/src/main/java/com/gotcha/tools/NotificationTool.kt
index b20aa63..93f4291 100644
--- a/app/src/main/java/com/gotcha/tools/NotificationTool.kt
+++ b/app/src/main/java/com/gotcha/tools/NotificationTool.kt
@@ -71,7 +71,10 @@ class NotificationTool(private val context: Context) {
val component = ComponentName(context, GotchaNotificationListenerService::class.java)
val controllers: List<MediaController> = msm.getActiveSessions(component)
val controller = controllers.firstOrNull()
- ?: return ToolResult.error("No app is currently playing media.")
+ ?: return ToolResult.error(
+ "No app is currently playing media. You may open a music or video app with open_app first, " +
+ "then try media_control again."
+ )
controller.dispatchMediaButtonEvent(KeyEvent(KeyEvent.ACTION_DOWN, keyCode))
controller.dispatchMediaButtonEvent(KeyEvent(KeyEvent.ACTION_UP, keyCode))
ToolResult.ok("Sent media '$action' to ${controller.packageName}.")
diff --git a/app/src/main/java/com/gotcha/tools/OverlayTool.kt b/app/src/main/java/com/gotcha/tools/OverlayTool.kt
index 50a52ec..5a96397 100644
--- a/app/src/main/java/com/gotcha/tools/OverlayTool.kt
+++ b/app/src/main/java/com/gotcha/tools/OverlayTool.kt
@@ -30,7 +30,11 @@ class OverlayTool(private val context: Context) {
/** Show [text] as a floating banner for [durationMs] (0 = until hide_overlay is called). */
fun showOverlay(text: String, durationMs: Int): ToolResult {
if (!canDrawOverlays()) return notEnabled()
- if (text.isBlank()) return ToolResult.error("Provide some text to display in the overlay.")
+ if (text.isBlank()) {
+ return ToolResult.error(
+ "Provide some text to display in the overlay. Use show_overlay with a text parameter."
+ )
+ }
val duration = durationMs.coerceIn(0, 300_000)
mainHandler.post {
removeView()
diff --git a/app/src/main/java/com/gotcha/tools/PhoneTool.kt b/app/src/main/java/com/gotcha/tools/PhoneTool.kt
index 1c00525..cd97175 100644
--- a/app/src/main/java/com/gotcha/tools/PhoneTool.kt
+++ b/app/src/main/java/com/gotcha/tools/PhoneTool.kt
@@ -22,18 +22,26 @@ class PhoneTool(private val context: Context) {
fun dialNumber(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.")
+ return ToolResult.error(
+ "'$number' does not look like a valid phone number. You may try find_contact or read_call_log to look " +
+ "up the correct number."
+ )
}
val digitsOnly = trimmed.filter { it.isDigit() }
if (digitsOnly.isEmpty()) {
- return ToolResult.error("'$number' has no digits — a phone number needs at least one digit.")
+ return ToolResult.error(
+ "'$number' has no digits — a phone number needs at least one digit. You may find a contact first with find_contact or " +
+ "check the call log with read_call_log."
+ )
}
return try {
val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:$trimmed")).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
if (intent.resolveActivity(context.packageManager) == null) {
- return ToolResult.error("No dialer app is available on this device.")
+ return ToolResult.error(
+ "No dialer app is available on this device. You may try call_number instead if the Phone permission is granted."
+ )
}
context.startActivity(intent)
ToolResult.ok("Opened the dialer with $trimmed. The user must press call themselves.")
@@ -45,7 +53,10 @@ class PhoneTool(private val context: Context) {
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.")
+ return ToolResult.error(
+ "'$number' does not look like a valid phone number. You may look up the correct number with find_contact or " +
+ "check recent calls with read_call_log."
+ )
}
if (ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED
@@ -85,7 +96,10 @@ class PhoneTool(private val context: Context) {
"The Phone permission is not granted. Go to Settings → Permissions → Phone and enable it, then ask again."
)
} catch (e: Exception) {
- ToolResult.error("Could not place the call: ${e.message}")
+ ToolResult.error(
+ "Could not place the call: ${e.message}. You may try dial_number instead (opens dialer without calling), or check " +
+ "the number with find_contact first."
+ )
}
}
@@ -186,7 +200,11 @@ class PhoneTool(private val context: Context) {
selectionArgs.toTypedArray().ifEmpty { null },
"${CallLog.Calls.DATE} DESC"
).use { cursor ->
- if (cursor == null) return ToolResult.error("Could not read the call log.")
+ if (cursor == null) {
+ return ToolResult.error(
+ "Could not read the call log. You may check the Call Log permission in Settings → Permissions."
+ )
+ }
val numberIdx = cursor.getColumnIndexOrThrow(CallLog.Calls.NUMBER)
val nameIdx = cursor.getColumnIndexOrThrow(CallLog.Calls.CACHED_NAME)
val typeIdx = cursor.getColumnIndexOrThrow(CallLog.Calls.TYPE)
diff --git a/app/src/main/java/com/gotcha/tools/RootTool.kt b/app/src/main/java/com/gotcha/tools/RootTool.kt
index 6662dd9..c834cab 100644
--- a/app/src/main/java/com/gotcha/tools/RootTool.kt
+++ b/app/src/main/java/com/gotcha/tools/RootTool.kt
@@ -51,10 +51,11 @@ class RootTool(
/** Run an arbitrary command as root and return stdout/stderr/exit code. */
fun runRootCommand(command: String): ToolResult {
val trimmed = command.trim()
- if (trimmed.isEmpty()) return ToolResult.error("Empty command.")
+ if (trimmed.isEmpty()) return ToolResult.error("Empty command. Provide the shell command to run as root.")
denyPatterns.firstOrNull { it.containsMatchIn(trimmed) }?.let {
return ToolResult.error(
- "Command blocked by safety policy (irreversible/device-destroying): $trimmed"
+ "Command blocked by safety policy (irreversible/device-destroying): $trimmed. You may use available tools (list_files," +
+ "read_file, grep) instead for safer operations."
)
}
val result = exec(trimmed) ?: return notRooted()
@@ -91,7 +92,9 @@ class RootTool(
s.any { it in "\n\r;&|`$()<>\"'\\ " }
private fun notRooted() = ToolResult.error(
- "This action needs root, but no `su` binary is available — the device isn't rooted, so I can't do it."
+ "This action needs root, but no `su` binary is available — the device isn't rooted, so I can't do it. You may try non-root " +
+ "alternatives such " +
+ "as list_files, read_file, or grep for filesystem operations."
)
private data class ExecResult(val exit: Int, val output: String)
diff --git a/app/src/main/java/com/gotcha/tools/SmsTool.kt b/app/src/main/java/com/gotcha/tools/SmsTool.kt
index c0203c7..457f0dc 100644
--- a/app/src/main/java/com/gotcha/tools/SmsTool.kt
+++ b/app/src/main/java/com/gotcha/tools/SmsTool.kt
@@ -31,9 +31,16 @@ class SmsTool(private val context: Context) {
): ToolResult {
val trimmed = number.trim()
if (!trimmed.matches(numberPattern)) {
- return ToolResult.error("'$number' does not look like a valid phone number.")
+ return ToolResult.error(
+ "'$number' does not look like a valid phone number. You may use find_contact or read_call_log to look " +
+ "up the correct number."
+ )
+ }
+ if (message.isBlank()) {
+ return ToolResult.error(
+ "The message text is empty. Please provide the text you want to send."
+ )
}
- if (message.isBlank()) return ToolResult.error("The message text is empty.")
if (ContextCompat.checkSelfPermission(context, Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED
) {
diff --git a/app/src/main/java/com/gotcha/tools/SystemTool.kt b/app/src/main/java/com/gotcha/tools/SystemTool.kt
index 9db4b5f..5107557 100644
--- a/app/src/main/java/com/gotcha/tools/SystemTool.kt
+++ b/app/src/main/java/com/gotcha/tools/SystemTool.kt
@@ -150,7 +150,9 @@ class SystemTool(private val context: Context) {
)
}
}
- ToolResult.error("No launchable app found matching '$packageName'.")
+ ToolResult.error(
+ "No launchable app found matching '$packageName'. You may use list_installed_apps to find the correct name or package name."
+ )
} catch (e: Exception) {
ToolResult.error("Could not open app: ${e.message}")
}
diff --git a/app/src/main/java/com/gotcha/tools/TerminalTool.kt b/app/src/main/java/com/gotcha/tools/TerminalTool.kt
index cf63e6f..48b9ec8 100644
--- a/app/src/main/java/com/gotcha/tools/TerminalTool.kt
+++ b/app/src/main/java/com/gotcha/tools/TerminalTool.kt
@@ -33,14 +33,19 @@ class TerminalTool(
timeoutSeconds: Int? = null
): ToolResult = withContext(Dispatchers.IO) {
val trimmed = command.trim()
- if (trimmed.isEmpty()) return@withContext ToolResult.error("Empty command.")
+ if (trimmed.isEmpty()) {
+ return@withContext ToolResult.error(
+ "Empty command. Provide a shell command to run (e.g. 'ls', 'ps', 'getprop')."
+ )
+ }
val timeout = (timeoutSeconds ?: defaultTimeoutSeconds).toLong()
.coerceIn(1, 120)
denyPatterns.firstOrNull { it.containsMatchIn(trimmed) }?.let {
return@withContext ToolResult.error(
- "Command blocked by safety policy (matched deny-list): $trimmed"
+ "Command blocked by safety policy (matched deny-list): $trimmed. You may use available tools" +
+ "(list_files, grep, etc.) instead."
)
}
@@ -69,7 +74,8 @@ class TerminalTool(
if (!finished) {
process.destroyForcibly()
return@withContext ToolResult.error(
- "Command timed out after ${timeout}s and was killed: $trimmed"
+ "Command timed out after ${timeout}s and was killed: $trimmed. You may try a simpler command or split " +
+ "it into smaller steps."
)
}
outThread.join(2000)
diff --git a/app/src/main/java/com/gotcha/tools/WallpaperTool.kt b/app/src/main/java/com/gotcha/tools/WallpaperTool.kt
index c5ec6ae..8e3075f 100644
--- a/app/src/main/java/com/gotcha/tools/WallpaperTool.kt
+++ b/app/src/main/java/com/gotcha/tools/WallpaperTool.kt
@@ -26,13 +26,16 @@ class WallpaperTool(private val context: Context) {
httpClient.newCall(request).execute().use { response ->
if (!response.isSuccessful) {
return@withContext ToolResult.error(
- "Image download failed (HTTP ${response.code}) from $imageUrl."
+ "Image download failed (HTTP ${response.code}) from $imageUrl. You may verify the URL with webfetch first."
)
}
val body = response.body
- ?: return@withContext ToolResult.error("Empty response from $imageUrl.")
+ ?: return@withContext ToolResult.error("Empty response from $imageUrl. You may try a different image URL.")
val bitmap = BitmapFactory.decodeStream(body.byteStream())
- ?: return@withContext ToolResult.error("Downloaded data is not a decodable image.")
+ ?: return@withContext ToolResult.error(
+ "Downloaded data is not a decodable image. The URL may not point to a valid " +
+ "image file."
+ )
WallpaperManager.getInstance(context).setBitmap(bitmap)
}
ToolResult.ok("Wallpaper updated from $imageUrl.")
diff --git a/app/src/main/java/com/gotcha/tools/WebSearchTool.kt b/app/src/main/java/com/gotcha/tools/WebSearchTool.kt
index eaf8c6c..8b1fe43 100644
--- a/app/src/main/java/com/gotcha/tools/WebSearchTool.kt
+++ b/app/src/main/java/com/gotcha/tools/WebSearchTool.kt
@@ -25,7 +25,11 @@ class WebSearchTool {
fun search(query: String, numResults: Int): ToolResult {
val trimmed = query.trim()
- if (trimmed.isEmpty()) return ToolResult.error("Search query cannot be empty.")
+ if (trimmed.isEmpty()) {
+ return ToolResult.error(
+ "Search query cannot be empty. Provide keywords or a question to search for."
+ )
+ }
val count = numResults.coerceIn(1, 10)
return try {
@@ -41,10 +45,15 @@ class WebSearchTool {
.build()
val response = client.newCall(request).execute()
- val body = response.body ?: return ToolResult.error("Empty response (HTTP ${response.code}).")
+ val body = response.body ?: return ToolResult.error(
+ "Empty response (HTTP ${response.code}). The search engine may be " +
+ "temporarily unavailable."
+ )
if (!response.isSuccessful) {
- return ToolResult.error("Search failed (HTTP ${response.code}).")
+ return ToolResult.error(
+ "Search failed (HTTP ${response.code}). The search engine may be rate-limiting or temporarily down."
+ )
}
val html = body.string()
@@ -53,7 +62,9 @@ class WebSearchTool {
if (resultRows.isEmpty()) {
// DDG sometimes puts ads-only on first page; check for "no results" indicator
- return ToolResult.ok("No search results found for '$trimmed'. Try a different query.")
+ return ToolResult.ok(
+ "No search results found for '$trimmed'. You may try different keywords or rephrase the query."
+ )
}
val results = mutableListOf<String>()
@@ -81,14 +92,22 @@ class WebSearchTool {
}
if (results.isEmpty()) {
- return ToolResult.ok("Found search results page but could not extract any results for '$trimmed'.")
+ return ToolResult.ok(
+ "Found search results page but could not extract any results for '$trimmed'. You may try a different query " +
+ "or use webfetch on a known URL."
+ )
}
ToolResult.ok("Search results for '$trimmed' (top ${results.size}):\n\n${results.joinToString("\n")}")
} catch (e: java.net.UnknownHostException) {
- ToolResult.error("Could not reach the search engine: ${e.message}")
+ ToolResult.error(
+ "Could not reach the search engine: ${e.message}. You may check your internet connection or try webfetch on a known URL."
+ )
} catch (_: java.net.SocketTimeoutException) {
- ToolResult.error("Search timed out after ${TIMEOUT_SECONDS}s.")
+ ToolResult.error(
+ "Search timed out after ${TIMEOUT_SECONDS}s. The search engine may be slow — you may try a simpler query or " +
+ "use webfetch on a known URL."
+ )
} catch (e: Exception) {
ToolResult.error("Search failed: ${e.message}")
}