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.

fix: resolve detekt and lint failures blocking CI

Durganshu Mishra7fba07cefe67
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index 127d01f..3cd664c 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -3,7 +3,6 @@ package com.gotcha
import android.app.admin.DevicePolicyManager
import android.content.Context
import android.content.Intent
-import android.content.SharedPreferences
import android.net.Uri
import android.net.VpnService
import android.os.Build
@@ -28,7 +27,6 @@ import androidx.compose.ui.Modifier
import androidx.lifecycle.lifecycleScope
import com.gotcha.agent.ChatViewModel
import com.gotcha.audio.AudioApi
-import com.gotcha.audio.AudioModel
import com.gotcha.audio.ModelCategory
import com.gotcha.data.Settings
import com.gotcha.data.SettingsRepository
@@ -58,21 +56,13 @@ class MainActivity : ComponentActivity() {
/** Set when launched from the assistive ball's "Open Chat" option. */
private var openChatRequested by mutableStateOf(false)
- /** Used by the Settings screen to grant individual runtime permissions. */
- private val permissionLauncher =
- registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
- Toast.makeText(
- this,
- if (granted) "Permission granted."
- else "Permission denied.",
- Toast.LENGTH_SHORT
- ).show()
- }
-
/** MediaProjection consent result — stores intent for screenshot capture. */
private val mediaProjectionLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
- android.util.Log.d("ScreenCapture", "mediaProjectionLauncher: resultCode=${result.resultCode}, data=${result.data != null}")
+ android.util.Log.d(
+ "ScreenCapture",
+ "mediaProjectionLauncher: resultCode=${result.resultCode}, data=${result.data != null}"
+ )
if (result.resultCode == RESULT_OK && result.data != null) {
ScreenPerception.mediaProjectionResultData = result.data
Toast.makeText(this, "Screenshot permission granted.", Toast.LENGTH_SHORT).show()
@@ -156,7 +146,9 @@ class MainActivity : ComponentActivity() {
).show()
"special:screenshot_consent" -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
- val mpManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as android.media.projection.MediaProjectionManager
+ val mpManager = getSystemService(
+ Context.MEDIA_PROJECTION_SERVICE
+ ) as android.media.projection.MediaProjectionManager
mediaProjectionLauncher.launch(mpManager.createScreenCaptureIntent())
}
}
@@ -188,7 +180,9 @@ class MainActivity : ComponentActivity() {
// Always request if not granted in this process session (cleared on process kill)
if (ScreenPerception.mediaProjectionResultData == null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
- val mpManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as android.media.projection.MediaProjectionManager
+ val mpManager = getSystemService(
+ Context.MEDIA_PROJECTION_SERVICE
+ ) as android.media.projection.MediaProjectionManager
mediaProjectionLauncher.launch(mpManager.createScreenCaptureIntent())
}
}
@@ -411,7 +405,7 @@ class MainActivity : ComponentActivity() {
messages = listOf(ChatMessage(role = "user", content = JsonPrimitive("Reply with the single word: pong"))),
temperature = 0f
)
- response.choices.firstOrNull()?.message?.textContent?. take(60) ?: "empty response"
+ response.choices.firstOrNull()?.message?.textContent?. take(60) ?: "empty response"
}
companion object {
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index ca80d38..24c8cff 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -20,10 +20,10 @@ import com.gotcha.llm.LLMClient
import com.gotcha.llm.ToolCall
import com.gotcha.llm.visionUserMessage
import com.gotcha.tools.AgentMode
-import com.gotcha.tools.FileResolver
-import com.gotcha.tools.SubAgentSession
import com.gotcha.tools.AppNavigatorSession
+import com.gotcha.tools.FileResolver
import com.gotcha.tools.ScreenPerception
+import com.gotcha.tools.SubAgentSession
import com.gotcha.tools.ToolExecutor
import com.gotcha.tools.ToolRegistry
import com.gotcha.tools.ToolResult
@@ -47,10 +47,8 @@ import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
-import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
-import kotlinx.serialization.json.put
import java.io.ByteArrayOutputStream
enum class MessageKind { USER, ASSISTANT, TOOL, ERROR, SUBAGENT }
@@ -179,8 +177,11 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
it.copy(
subAgentCurrentAction = when (status) {
"running" -> "→ $action"
- "completed" -> if (detail.isNotBlank()) "✓ $action → ${detail.take(60)}"
- else "✓ $action"
+ "completed" -> if (detail.isNotBlank()) {
+ "✓ $action → ${detail.take(60)}"
+ } else {
+ "✓ $action"
+ }
else -> "$action: ${detail.take(60)}"
}
)
@@ -211,8 +212,11 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
it.copy(
subAgentCurrentAction = when (status) {
"running" -> "→ $action"
- "completed" -> if (detail.isNotBlank()) "✓ $action → ${detail.take(60)}"
- else "✓ $action"
+ "completed" -> if (detail.isNotBlank()) {
+ "✓ $action → ${detail.take(60)}"
+ } else {
+ "✓ $action"
+ }
else -> "$action: ${detail.take(60)}"
}
)
@@ -229,7 +233,10 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
val launchIntent = getApplication<android.app.Application>()
.packageManager.getLaunchIntentForPackage(pkg)
if (launchIntent != null) {
- launchIntent.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK or android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP)
+ launchIntent.addFlags(
+ android.content.Intent.FLAG_ACTIVITY_NEW_TASK or
+ android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP
+ )
getApplication<android.app.Application>().startActivity(launchIntent)
}
} catch (_: Exception) { }
@@ -758,49 +765,12 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
// contract and inject them as a vision user message so the LLM
// can "see" the screen alongside structured element data.
if (result.success && call.function.name == "read_screen") {
- android.util.Log.d("ScreenCapture", "read_screen auto-injection: calling captureCompressedScreenshot()")
- val uiTree = ScreenPerception.buildUiHierarchyText()
- val screenshot = captureCompressedScreenshot(sessionId)
- android.util.Log.d("ScreenCapture", "read_screen auto-injection: screenshot=${screenshot != null}")
- if (screenshot != null) {
- val observationText = ScreenPerception.buildObservationText(screenshot, uiTree)
- val visionMsg = visionUserMessage(observationText, screenshot.base64, "jpeg")
- llmHistory.add(visionMsg)
- appendUi(MessageKind.ASSISTANT, "[Screenshot captured for visual context]")
- android.util.Log.d("ScreenCapture", "read_screen auto-injection: vision message added, base64 length=${screenshot.base64.length}")
- } else {
- android.util.Log.e("ScreenCapture", "read_screen auto-injection: screenshot was null — no vision message added")
- // If MediaProjection consent hasn't been granted, request it
- if (ScreenPerception.mediaProjectionResultData == null) {
- _permissionRequests.tryEmit("special:screenshot_consent")
- }
- }
+ injectReadScreenObservation()
}
// read_screen_raw: full-resolution PNG screenshot for visual detail.
// Also saves the raw bytes to the working directory as a file.
if (result.success && call.function.name == "read_screen_raw") {
- val screenshot = captureFullResScreenshot(sessionId)
- if (screenshot != null) {
- val screenText = result.message.removePrefix("read_screen_raw:").take(500)
- // Save screenshot to working directory
- val savedPath = try {
- val ts = java.text.SimpleDateFormat("yyyyMMdd_HHmmss", java.util.Locale.US).format(java.util.Date())
- val dir = java.io.File(com.gotcha.tools.FileResolver.WORKING_DIR_BASE)
- if (!dir.exists()) dir.mkdirs()
- val file = java.io.File(dir, "screenshot_$ts.png")
- val rawBytes = android.util.Base64.decode(screenshot.base64, android.util.Base64.DEFAULT)
- file.writeBytes(rawBytes)
- file.absolutePath
- } catch (_: Exception) { null }
- val pathNote = if (savedPath != null) "\n\nSaved to: $savedPath" else ""
- val visionMsg = visionUserMessage(
- "Screen text:\n$screenText\n\nThe assistant captured a " +
- "full-resolution screenshot for visual detail.$pathNote",
- screenshot.base64, screenshot.format
- )
- llmHistory.add(visionMsg)
- appendUi(MessageKind.ASSISTANT, "[Full-resolution screenshot captured]${if (savedPath != null) " → $savedPath" else ""}")
- }
+ injectFullResScreenshot(result)
}
// Special-access markers: emit and continue (no wait needed since they open Settings)
if (perm != null && perm.startsWith("special:")) {
@@ -1076,13 +1046,15 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
// Store in LLM history with steps embedded for persistence
val stepsBlock = if (steps.isNotEmpty()) {
"\n── Steps ──\n" + steps.joinToString("\n") + "\n── Result ──\n"
- } else ""
+ } else {
+ ""
+ }
llmHistory += ChatMessage(
role = "tool",
content = JsonPrimitive(
"SUBAGENT_STEPS:$description" +
- stepsBlock +
- answer
+ stepsBlock +
+ answer
),
toolCallId = call.id
)
@@ -1130,7 +1102,8 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
*/
private fun currentTimestampMessage(): ChatMessage {
val dateTime = java.text.SimpleDateFormat(
- "EEE MMM dd yyyy, HH:mm:ss 'UTC'Z", java.util.Locale.US
+ "EEE MMM dd yyyy, HH:mm:ss 'UTC'Z",
+ java.util.Locale.US
).apply { timeZone = java.util.TimeZone.getDefault() }.format(java.util.Date())
return ChatMessage(role = "system", content = JsonPrimitive("Current date/time: $dateTime"))
}
@@ -1152,29 +1125,29 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
"between operations. Keep replies short and conversational."
AgentMode.OPERATOR ->
"You are Operator, an AI assistant running on the user's Android phone. " +
- "You can inspect, read, query, create, modify, and delete on the device. " +
- "You control the device only through the provided tools; never invent tool " +
- "names or capabilities. If a tool reports a missing permission, explain what " +
- "to grant and ask again. After changing device state, confirm what was done. " +
- "Use the sleep tool to pause and wait between operations (e.g. wait for " +
- "a recording to finish before reading it). " +
- "Use the task tool to delegate complex multi-step operations to the General " +
- "sub-agent. Prefer delegation whenever a task involves many tool calls whose " +
- "intermediate steps are not important — only the final result matters. " +
- "For example: organizing files, gathering information from multiple sources, " +
- "or performing a series of device checks. The sub-agent runs in the foreground; " +
- "you will receive its complete report when done. " +
- "Use the navigate_app tool to delegate app interaction tasks to the App " +
- "Navigator sub-agent. For example: opening an app, searching for something, " +
- "scrolling through results, or reading on-screen information. The navigator " +
- "will look at the screen, tap, swipe, and type step by step. " +
- "You will receive its complete report when done. " +
- "Keep replies short and conversational. Be careful with destructive actions.\n" +
- "If the accessibility service is enabled, you have the ability to control any app on the device.\n" +
- "When using uninstall_app: after calling it, the system will open a dialog. " +
- "Tell the user to tap OK in the system dialog to finish the uninstall. " +
- "Do NOT attempt to uninstall via shell commands (run_command, run_root_command) — " +
- "use uninstall_app only."
+ "You can inspect, read, query, create, modify, and delete on the device. " +
+ "You control the device only through the provided tools; never invent tool " +
+ "names or capabilities. If a tool reports a missing permission, explain what " +
+ "to grant and ask again. After changing device state, confirm what was done. " +
+ "Use the sleep tool to pause and wait between operations (e.g. wait for " +
+ "a recording to finish before reading it). " +
+ "Use the task tool to delegate complex multi-step operations to the General " +
+ "sub-agent. Prefer delegation whenever a task involves many tool calls whose " +
+ "intermediate steps are not important — only the final result matters. " +
+ "For example: organizing files, gathering information from multiple sources, " +
+ "or performing a series of device checks. The sub-agent runs in the foreground; " +
+ "you will receive its complete report when done. " +
+ "Use the navigate_app tool to delegate app interaction tasks to the App " +
+ "Navigator sub-agent. For example: opening an app, searching for something, " +
+ "scrolling through results, or reading on-screen information. The navigator " +
+ "will look at the screen, tap, swipe, and type step by step. " +
+ "You will receive its complete report when done. " +
+ "Keep replies short and conversational. Be careful with destructive actions.\n" +
+ "If the accessibility service is enabled, you have the ability to control any app on the device.\n" +
+ "When using uninstall_app: after calling it, the system will open a dialog. " +
+ "Tell the user to tap OK in the system dialog to finish the uninstall. " +
+ "Do NOT attempt to uninstall via shell commands (run_command, run_root_command) — " +
+ "use uninstall_app only."
}
val reminder = when (agent) {
AgentMode.MONITOR ->
@@ -1249,7 +1222,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
appendLine("Here is some useful information about the environment you are running in:")
appendLine("<env>")
appendLine(" Device model: ${android.os.Build.MODEL} (${android.os.Build.MANUFACTURER})")
- appendLine(" Android version: ${android.os.Build.VERSION.RELEASE} (API ${android.os.Build.VERSION.SDK_INT})")
+ appendLine(
+ " Android version: ${android.os.Build.VERSION.RELEASE} (API ${android.os.Build.VERSION.SDK_INT})"
+ )
appendLine(" Active agent: ${agent.name}")
appendLine(" Accessibility service enabled: ${if (accEnabled) "yes" else "no"}")
appendLine(" Notification listener enabled: ${if (notifEnabled) "yes" else "no"}")
@@ -1314,9 +1289,11 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
reasoningContent: String? = null
) {
_uiState.update {
- it.copy(messages = it.messages + UiMessage(
- nextId++, kind, text, imageBase64, subAgentSteps, subAgentCollapsed = true, reasoningContent = reasoningContent
- ))
+ it.copy(
+ messages = it.messages + UiMessage(
+ nextId++, kind, text, imageBase64, subAgentSteps, subAgentCollapsed = true, reasoningContent = reasoningContent
+ )
+ )
}
}
@@ -1326,8 +1303,11 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
when {
msg.role == "user" && (text.startsWith("[Screen State]") || text.startsWith("Screen text:")) -> {
val saved = if (text.contains("Saved to:")) " → " + text.substringAfter("Saved to:").trim() else ""
- val msgText = if (text.startsWith("Screen text:")) "[Full-resolution screenshot captured]$saved"
- else "[Screenshot captured for visual context]"
+ val msgText = if (text.startsWith("Screen text:")) {
+ "[Full-resolution screenshot captured]$saved"
+ } else {
+ "[Screenshot captured for visual context]"
+ }
UiMessage(nextId++, MessageKind.ASSISTANT, msgText)
}
msg.role == "user" -> UiMessage(nextId++, MessageKind.USER, text.ifEmpty { "(image attached)" })
@@ -1337,7 +1317,13 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
UiMessage(nextId++, MessageKind.ASSISTANT, "(no reply)", reasoningContent = msg.reasoningContent)
msg.role == "tool" && text.startsWith("SUBAGENT_STEPS:") -> {
val descEnd = text.indexOf('\n', "SUBAGENT_STEPS:".length)
- val rest = if (descEnd > 0) text.substring(descEnd + 1) else text.substring("SUBAGENT_STEPS:".length)
+ val rest = if (descEnd > 0) {
+ text.substring(
+ descEnd + 1
+ )
+ } else {
+ text.substring("SUBAGENT_STEPS:".length)
+ }
val stepsMarker = "── Steps ──\n"
val resultMarker = "\n── Result ──\n"
val steps: List<String>
@@ -1356,7 +1342,13 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
steps = emptyList()
answer = rest
}
- UiMessage(nextId++, MessageKind.SUBAGENT, answer, subAgentSteps = steps, reasoningContent = msg.reasoningContent)
+ UiMessage(
+ nextId++,
+ MessageKind.SUBAGENT,
+ answer,
+ subAgentSteps = steps,
+ reasoningContent = msg.reasoningContent
+ )
}
msg.role == "tool" -> UiMessage(nextId++, MessageKind.TOOL, text.ifEmpty { "(no result)" })
else -> null
@@ -1370,7 +1362,6 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
* Returns a [ScreenPerception.CompressedScreenshot] with base64 data, or null on failure.
*/
private suspend fun captureCompressedScreenshot(
- sessionId: String,
drawGrid: Boolean = true
): ScreenPerception.CompressedScreenshot? {
val saveDir = java.io.File(FileResolver.WORKING_DIR_BASE, "debug_screenshots")
@@ -1381,7 +1372,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
* Capture a full-resolution screenshot (uncompressed PNG).
* Used by read_screen_raw for maximum visual detail.
*/
- private suspend fun captureFullResScreenshot(sessionId: String): ScreenPerception.CompressedScreenshot? {
+ private suspend fun captureFullResScreenshot(): ScreenPerception.CompressedScreenshot? {
val saveDir = java.io.File(FileResolver.WORKING_DIR_BASE, "debug_screenshots")
return ScreenPerception.compressScreenshot(
maxDimension = 0,
@@ -1392,6 +1383,82 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
)
}
+ /**
+ * Captures a compressed screenshot + UI hierarchy after a successful
+ * read_screen call and injects them as a vision user message so the LLM
+ * can "see" the screen alongside structured element data.
+ */
+ private suspend fun injectReadScreenObservation() {
+ android.util.Log.d(
+ "ScreenCapture",
+ "read_screen auto-injection: calling captureCompressedScreenshot()"
+ )
+ val uiTree = ScreenPerception.buildUiHierarchyText()
+ val screenshot = captureCompressedScreenshot()
+ android.util.Log.d(
+ "ScreenCapture",
+ "read_screen auto-injection: screenshot=${screenshot != null}"
+ )
+ if (screenshot != null) {
+ val observationText = ScreenPerception.buildObservationText(screenshot, uiTree)
+ val visionMsg = visionUserMessage(observationText, screenshot.base64, "jpeg")
+ llmHistory.add(visionMsg)
+ appendUi(MessageKind.ASSISTANT, "[Screenshot captured for visual context]")
+ android.util.Log.d(
+ "ScreenCapture",
+ "read_screen auto-injection: vision message added, base64 length=${screenshot.base64.length}"
+ )
+ } else {
+ android.util.Log.e(
+ "ScreenCapture",
+ "read_screen auto-injection: screenshot was null — no vision message added"
+ )
+ // If MediaProjection consent hasn't been granted, request it
+ if (ScreenPerception.mediaProjectionResultData == null) {
+ _permissionRequests.tryEmit("special:screenshot_consent")
+ }
+ }
+ }
+
+ /**
+ * Captures a full-resolution PNG screenshot after read_screen_raw,
+ * saves it to the working directory, and injects it as a vision message.
+ */
+ private suspend fun injectFullResScreenshot(result: ToolResult) {
+ val screenshot = captureFullResScreenshot() ?: return
+ val screenText = result.message.removePrefix("read_screen_raw:").take(500)
+ // Save screenshot to working directory
+ val savedPath = try {
+ val ts = java.text.SimpleDateFormat(
+ "yyyyMMdd_HHmmss",
+ java.util.Locale.US
+ ).format(java.util.Date())
+ val dir = java.io.File(com.gotcha.tools.FileResolver.WORKING_DIR_BASE)
+ if (!dir.exists()) dir.mkdirs()
+ val file = java.io.File(dir, "screenshot_$ts.png")
+ val rawBytes = android.util.Base64.decode(
+ screenshot.base64,
+ android.util.Base64.DEFAULT
+ )
+ file.writeBytes(rawBytes)
+ file.absolutePath
+ } catch (_: Exception) {
+ null
+ }
+ val pathNote = if (savedPath != null) "\n\nSaved to: $savedPath" else ""
+ val visionMsg = visionUserMessage(
+ "Screen text:\n$screenText\n\nThe assistant captured a " +
+ "full-resolution screenshot for visual detail.$pathNote",
+ screenshot.base64,
+ screenshot.format
+ )
+ llmHistory.add(visionMsg)
+ appendUi(
+ MessageKind.ASSISTANT,
+ "[Full-resolution screenshot captured]${if (savedPath != null) " → $savedPath" else ""}"
+ )
+ }
+
/**
* Returns a copy of [messages] with old vision messages replaced by
* text-only versions. Only the 2 most recent vision messages keep their
@@ -1411,9 +1478,13 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
return messages.mapIndexed { idx, msg ->
if (idx in toCull) {
msg.copy(
- content = JsonPrimitive("[Previous screen observation removed to save context. Only the 2 most recent are retained.]")
+ content = JsonPrimitive(
+ "[Previous screen observation removed to save context. Only the 2 most recent are retained.]"
+ )
)
- } else msg
+ } else {
+ msg
+ }
}
}
@@ -1422,7 +1493,12 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
val sb = StringBuilder()
sb.appendLine("# Gotcha Chat Export")
sb.appendLine("**Session:** $sessionId")
- sb.appendLine("**Date:** ${java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.US).format(java.util.Date())}")
+ sb.appendLine(
+ "**Date:** ${java.text.SimpleDateFormat(
+ "yyyy-MM-dd HH:mm:ss",
+ java.util.Locale.US
+ ).format(java.util.Date())}"
+ )
sb.appendLine("**Messages:** ${llmHistory.size}")
sb.appendLine()
sb.appendLine("---")
@@ -1455,31 +1531,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
}
"tool" -> {
if (text.startsWith("SUBAGENT_STEPS:")) {
- val descEnd = text.indexOf('\n', "SUBAGENT_STEPS:".length)
- val desc = if (descEnd > 0) text.substring("SUBAGENT_STEPS:".length, descEnd)
- else text.substring("SUBAGENT_STEPS:".length)
- sb.appendLine("### Sub-Agent: $desc")
- val rest = if (descEnd > 0) text.substring(descEnd + 1) else ""
- val stepsMarker = "── Steps ──\n"
- val resultMarker = "\n── Result ──\n"
- if (rest.startsWith(stepsMarker)) {
- val afterSteps = rest.removePrefix(stepsMarker)
- val resIdx = afterSteps.indexOf(resultMarker)
- if (resIdx >= 0) {
- val steps = afterSteps.substring(0, resIdx).split("\n").filter { it.isNotBlank() }
- val answer = afterSteps.substring(resIdx + resultMarker.length)
- sb.appendLine()
- sb.appendLine("**Steps:**")
- for (s in steps) sb.appendLine("- $s")
- sb.appendLine()
- sb.appendLine("**Result:**")
- sb.appendLine(answer)
- } else {
- sb.appendLine(afterSteps)
- }
- } else {
- sb.appendLine(rest)
- }
+ appendSubAgentExport(sb, text)
} else {
sb.appendLine("### Tool Result")
sb.appendLine(text.ifEmpty { "(no result)" })
@@ -1497,6 +1549,38 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
_exportContent.tryEmit(sb.toString())
}
+ /** Formats a SUBAGENT_STEPS tool message (description, steps, result) for chat export. */
+ private fun appendSubAgentExport(sb: StringBuilder, text: String) {
+ val descEnd = text.indexOf('\n', "SUBAGENT_STEPS:".length)
+ val desc = if (descEnd > 0) {
+ text.substring("SUBAGENT_STEPS:".length, descEnd)
+ } else {
+ text.substring("SUBAGENT_STEPS:".length)
+ }
+ sb.appendLine("### Sub-Agent: $desc")
+ val rest = if (descEnd > 0) text.substring(descEnd + 1) else ""
+ val stepsMarker = "── Steps ──\n"
+ val resultMarker = "\n── Result ──\n"
+ if (!rest.startsWith(stepsMarker)) {
+ sb.appendLine(rest)
+ return
+ }
+ val afterSteps = rest.removePrefix(stepsMarker)
+ val resIdx = afterSteps.indexOf(resultMarker)
+ if (resIdx < 0) {
+ sb.appendLine(afterSteps)
+ return
+ }
+ val steps = afterSteps.substring(0, resIdx).split("\n").filter { it.isNotBlank() }
+ val answer = afterSteps.substring(resIdx + resultMarker.length)
+ sb.appendLine()
+ sb.appendLine("**Steps:**")
+ for (s in steps) sb.appendLine("- $s")
+ sb.appendLine()
+ sb.appendLine("**Result:**")
+ sb.appendLine(answer)
+ }
+
private companion object {
const val TAG = "Gotcha"
const val INTER_CALL_DELAY_MS = 400L
diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
index fff9aa7..fa52e3a 100644
--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt
+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
@@ -10,7 +10,7 @@ data class Settings(
val apiKey: String = "",
val baseUrl: String = DEFAULT_BASE_URL,
val model: String = DEFAULT_MODEL,
- val subAgentModel: String = "", // empty = same as main agent
+ val subAgentModel: String = "", // empty = same as main agent
val navigatorModel: String = "", // empty = same as main model
val maxToolRounds: Int = 30,
val maxContextTokens: Int = 40000,
diff --git a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
index 1a57991..85aca71 100644
--- a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
+++ b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
@@ -27,6 +27,8 @@ import kotlin.coroutines.resume
* service is only alive while the user has it enabled; the tool checks [instance]
* for null and returns a permission hint otherwise.
*/
+// One function per accessibility capability (tap, swipe, type, …) by design; size is inherent.
+@Suppress("TooManyFunctions")
class GotchaAccessibilityService : AccessibilityService() {
override fun onServiceConnected() {
@@ -155,11 +157,13 @@ class GotchaAccessibilityService : AccessibilityService() {
val parts = boundsStr.split(",").map { it.trim().toInt() }
if (parts.size == 4) {
targetBounds.set(parts[0], parts[1], parts[2], parts[3])
- } else return false
- } catch (e: Exception) {
+ } else {
+ return false
+ }
+ } catch (_: Exception) {
return false
}
-
+
val root = rootInActiveWindow ?: return false
var match: AccessibilityNodeInfo? = null
@@ -177,10 +181,10 @@ class GotchaAccessibilityService : AccessibilityService() {
search(node.getChild(i))
}
}
-
+
search(root)
root.recycle()
-
+
val nodeToEdit = match ?: return false
val ok = setTextOnNode(nodeToEdit, text)
nodeToEdit.recycle()
@@ -196,7 +200,7 @@ class GotchaAccessibilityService : AccessibilityService() {
/** Dispatch a tap gesture at absolute screen coordinates (API 24+). */
fun tapAt(x: Float, y: Float): Boolean = gesture(x, y, x, y, 50)
-
+
fun longPressAt(x: Float, y: Float): Boolean = gesture(x, y, x, y, 1000)
/** Dispatch a swipe gesture between two points. */
diff --git a/app/src/main/java/com/gotcha/service/MediaProjectionService.kt b/app/src/main/java/com/gotcha/service/MediaProjectionService.kt
index 29ff4b6..df8bdbc 100644
--- a/app/src/main/java/com/gotcha/service/MediaProjectionService.kt
+++ b/app/src/main/java/com/gotcha/service/MediaProjectionService.kt
@@ -89,7 +89,11 @@ class MediaProjectionService : Service() {
super.onCreate()
createNotificationChannel()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
- startForeground(NOTIFICATION_ID, buildNotification(), android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION)
+ startForeground(
+ NOTIFICATION_ID,
+ buildNotification(),
+ android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
+ )
} else {
startForeground(NOTIFICATION_ID, buildNotification())
}
@@ -139,7 +143,7 @@ class MediaProjectionService : Service() {
val screenWidth = metrics.widthPixels
val screenHeight = metrics.heightPixels
val screenDpi = metrics.densityDpi
- Log.d("ScreenCapture", "captureScreenshot: screen ${screenWidth}x${screenHeight} dpi=$screenDpi")
+ Log.d("ScreenCapture", "captureScreenshot: screen ${screenWidth}x$screenHeight dpi=$screenDpi")
imageReader = ImageReader.newInstance(
screenWidth, screenHeight,
@@ -189,7 +193,10 @@ class MediaProjectionService : Service() {
}
val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
bmp.copyPixelsFromBuffer(java.nio.ByteBuffer.wrap(packedBytes))
- Log.d("ScreenCapture", "captureScreenshot: bitmap=${bmp.width}x${bmp.height} (stride=$rowStride, pxStride=$pixelStride)")
+ Log.d(
+ "ScreenCapture",
+ "captureScreenshot: bitmap=${bmp.width}x${bmp.height} (stride=$rowStride, pxStride=$pixelStride)"
+ )
bmp
} catch (t: Throwable) {
Log.e("ScreenCapture", "captureScreenshot: bitmap creation failed: ${t.message}", t)
diff --git a/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt b/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
index 65fe5f7..1e26d85 100644
--- a/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
+++ b/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
@@ -33,8 +33,11 @@ class AccessibilityTool(private val context: Context) {
val service = GotchaAccessibilityService.instance
if (service == null) return if (isEnabled()) serviceNotRunning() else notEnabled()
val lines = service.dumpScreenText()
- val text = if (lines.isEmpty()) "No readable text is on screen right now."
- else lines.joinToString("\n") { "- $it" }
+ val text = if (lines.isEmpty()) {
+ "No readable text is on screen right now."
+ } else {
+ lines.joinToString("\n") { "- $it" }
+ }
return ToolResult.ok("read_screen_raw:$text")
}
@@ -63,40 +66,36 @@ class AccessibilityTool(private val context: Context) {
val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()
return when {
!text.isNullOrBlank() ->
- if (service.longPressByText(text)) ToolResult.ok("Long-pressed an element matching \"$text\".")
- else ToolResult.error("Found no element matching \"$text\" on screen.")
+ if (service.longPressByText(text)) {
+ ToolResult.ok("Long-pressed an element matching \"$text\".")
+ } else {
+ ToolResult.error("Found no element matching \"$text\" on screen.")
+ }
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.")
+ if (service.longPressAt(x.toFloat(), y.toFloat())) {
+ ToolResult.ok("Long-pressed at ($x, $y).")
+ } else {
+ ToolResult.error("Could not dispatch the long-press gesture.")
+ }
else -> ToolResult.error("Provide either 'text' to match, or both 'x' and 'y' coordinates.")
}
}
/** Swipe in a named direction, or between explicit coordinates. */
- fun swipe(direction: String?, x1: Int?, y1: Int?, x2: Int?, y2: Int?, normalized: Boolean = false, distance: Int? = null, index: Int? = null): ToolResult {
+ fun swipe(
+ direction: String?,
+ x1: Int?,
+ y1: Int?,
+ x2: Int?,
+ y2: Int?,
+ normalized: Boolean = false,
+ distance: Int? = null,
+ index: Int? = null
+ ): ToolResult {
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.")
- val parts = element.bounds.split(",").map { it.trim().toIntOrNull() }
- if (parts.size == 4 && parts.none { it == null }) {
- val cx = (parts[0]!! + parts[2]!!) / 2f
- val top = parts[1]!!.toFloat()
- val bottom = parts[3]!!.toFloat()
- val left = parts[0]!!.toFloat()
- val right = parts[2]!!.toFloat()
- val h = bottom - top
- val w = right - left
- val (sx, sy, ex, ey) = when (direction?.lowercase()?.trim()) {
- "up" -> listOf(cx, top + h * 0.2f, cx, top + h * 0.8f) // Scroll Up (physical swipe down)
- "down" -> listOf(cx, top + h * 0.8f, cx, top + h * 0.2f) // Scroll Down (physical swipe up)
- "left" -> listOf(left + w * 0.2f, (top + bottom) / 2f, left + w * 0.8f, (top + bottom) / 2f) // Scroll Left (physical swipe right)
- "right" -> listOf(left + w * 0.8f, (top + bottom) / 2f, 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.")
- }
- return if (service.swipe(sx, sy, ex, ey, 500)) ToolResult.ok("Swiped $direction on element $index.")
- else ToolResult.error("Could not dispatch the swipe gesture on element $index.")
- }
+ val result = swipeOnElement(service, direction, index)
+ if (result != null) return result
}
if (x1 != null && y1 != null && x2 != null && y2 != null) {
val (sx, sy, ex, ey) = if (normalized) {
@@ -107,25 +106,74 @@ class AccessibilityTool(private val context: Context) {
} else {
listOf(x1.toFloat(), y1.toFloat(), x2.toFloat(), y2.toFloat())
}
- return if (service.swipe(sx, sy, ex, ey))
+ 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.")
+ } else {
+ ToolResult.error("Could not dispatch the swipe gesture.")
+ }
}
val metrics = context.resources.displayMetrics
val w = metrics.widthPixels.toFloat()
val h = metrics.heightPixels.toFloat()
val scrollPx = distance?.toFloat()?.takeIf { it > 0f } ?: (h * 0.6f)
val (sx, sy, ex, ey) = when (direction?.lowercase()?.trim()) {
- "up" -> listOf(w / 2, h * 0.2f, w / 2, h * 0.2f + scrollPx) // Scroll Up (physical swipe down)
- "down" -> listOf(w / 2, h * 0.8f, w / 2, h * 0.8f - scrollPx) // Scroll Down (physical swipe up)
- "left" -> listOf(w * 0.2f, h / 2, w * 0.2f + scrollPx, h / 2) // Scroll Left (physical swipe right)
- "right" -> listOf(w * 0.8f, h / 2, w * 0.8f - scrollPx, h / 2) // Scroll Right (physical swipe left)
+ "up" -> listOf(w / 2, h * 0.2f, w / 2, h * 0.2f + scrollPx) // Scroll Up (physical swipe down)
+ "down" -> listOf(w / 2, h * 0.8f, w / 2, h * 0.8f - scrollPx) // Scroll Down (physical swipe up)
+ "left" -> listOf(w * 0.2f, h / 2, w * 0.2f + scrollPx, h / 2) // Scroll Left (physical swipe right)
+ "right" -> listOf(w * 0.8f, h / 2, w * 0.8f - scrollPx, h / 2) // Scroll Right (physical swipe left)
else -> return ToolResult.error(
"Provide a direction (up/down/left/right) or explicit x1,y1,x2,y2 coordinates."
)
}
- return if (service.swipe(sx, sy, ex, ey, 500)) ToolResult.ok("Swiped $direction.")
- else ToolResult.error("Could not dispatch the swipe gesture.")
+ return if (service.swipe(sx, sy, ex, ey, 500)) {
+ ToolResult.ok("Swiped $direction.")
+ } else {
+ ToolResult.error("Could not dispatch the swipe gesture.")
+ }
+ }
+
+ /**
+ * Swipe within the bounds of the element at [index], or null to fall through
+ * to the coordinate/whole-screen paths when the element bounds are unusable.
+ */
+ private fun swipeOnElement(
+ service: GotchaAccessibilityService,
+ direction: String?,
+ index: Int
+ ): ToolResult? {
+ val element = ScreenPerception.resolveElementByIndex(index)
+ ?: return ToolResult.error("No UI element with index $index found on screen.")
+ 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
+ val top = parts[1]!!.toFloat()
+ val bottom = parts[3]!!.toFloat()
+ val left = parts[0]!!.toFloat()
+ val right = parts[2]!!.toFloat()
+ val h = bottom - top
+ val w = right - left
+ val (sx, sy, ex, ey) = when (direction?.lowercase()?.trim()) {
+ "up" -> listOf(cx, top + h * 0.2f, cx, top + h * 0.8f) // Scroll Up (physical swipe down)
+ "down" -> listOf(cx, top + h * 0.8f, cx, top + h * 0.2f) // Scroll Down (physical swipe up)
+ "left" -> listOf(
+ left + w * 0.2f,
+ (top + bottom) / 2f,
+ left + w * 0.8f,
+ (top + bottom) / 2f
+ ) // Scroll Left (physical swipe right)
+ "right" -> listOf(
+ left + w * 0.8f,
+ (top + bottom) / 2f,
+ 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.")
+ }
+ return if (service.swipe(sx, sy, ex, ey, 500)) {
+ ToolResult.ok("Swiped $direction on element $index.")
+ } else {
+ ToolResult.error("Could not dispatch the swipe gesture on element $index.")
+ }
}
/** Type text into the currently focused input field or target an element directly by index. */
@@ -139,18 +187,24 @@ class AccessibilityTool(private val context: Context) {
}
// Fall through if direct setting fails, maybe it wasn't editable via ACTION_SET_TEXT
}
- return if (service.typeText(text)) ToolResult.ok("Typed \"$text\" into the focused field.")
- else ToolResult.error("No editable field is focused. Try passing the index of the text field.")
+ return if (service.typeText(text)) {
+ ToolResult.ok("Typed \"$text\" into the focused field.")
+ } else {
+ ToolResult.error("No editable field is focused. Try passing the index of the text field.")
+ }
}
/** Perform a device-wide navigation gesture via the accessibility service (back/home/recents/...). */
fun globalAction(action: String): ToolResult {
val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()
- return if (service.performGlobal(action)) ToolResult.ok("Performed global action: $action.")
- else ToolResult.error(
- "Unknown or unsupported global action '$action'. " +
- "Use back, home, recents, notifications, quick_settings, or lock_screen."
- )
+ return if (service.performGlobal(action)) {
+ ToolResult.ok("Performed global action: $action.")
+ } else {
+ ToolResult.error(
+ "Unknown or unsupported global action '$action'. " +
+ "Use back, home, recents, notifications, quick_settings, or lock_screen."
+ )
+ }
}
/** Tap a UI element by its index from the numbered elements list. */
@@ -164,9 +218,11 @@ class AccessibilityTool(private val context: Context) {
}
val cx = (parts[0]!! + parts[2]!!) / 2f
val cy = (parts[1]!! + parts[3]!!) / 2f
- return if (service.tapAt(cx, cy))
+ 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.")
+ } else {
+ ToolResult.error("Could not dispatch the tap gesture for element $index.")
+ }
}
/** Long-press a UI element by its index from the numbered elements list. */
@@ -180,9 +236,13 @@ class AccessibilityTool(private val context: Context) {
}
val cx = (parts[0]!! + parts[2]!!) / 2f
val cy = (parts[1]!! + parts[3]!!) / 2f
- return if (service.longPressAt(cx, cy))
- ToolResult.ok("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.")
+ return if (service.longPressAt(cx, cy)) {
+ ToolResult.ok(
+ "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.")
+ }
}
/**
@@ -208,7 +268,9 @@ class AccessibilityTool(private val context: Context) {
clicked = focused.performAction(AccessibilityNodeInfo.ACTION_CLICK)
}
clicked
- } else false
+ } else {
+ false
+ }
} finally { try { root?.recycle() } catch (_: Exception) { } }
if (result) return ToolResult.ok("Pressed Enter.")
} catch (_: Exception) { }
@@ -219,11 +281,6 @@ class AccessibilityTool(private val context: Context) {
)
}
- private fun requireService(): GotchaAccessibilityService? =
- GotchaAccessibilityService.instance ?: run {
- if (isEnabled()) null else null // both cases return null, but error differs
- }
-
private fun notEnabled() = ToolResult.permissionNeeded(
ToolResult.ACCESSIBILITY_ACCESS,
"This action needs the Gotcha accessibility service. I have opened Accessibility " +
diff --git a/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt b/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt
index c45b57c..5834a41 100644
--- a/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt
+++ b/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt
@@ -1,7 +1,6 @@
package com.gotcha.tools
import android.content.Context
-import android.graphics.Bitmap
import com.gotcha.data.Settings
import com.gotcha.llm.ChatMessage
import com.gotcha.llm.ChatResponse
@@ -12,11 +11,11 @@ import kotlinx.coroutines.delay
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
-import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.addJsonObject
+import kotlinx.serialization.json.buildJsonArray
+import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonObject
-import kotlinx.serialization.json.jsonPrimitive
data class AppNavigatorOutput(
val finalAnswer: String,
@@ -57,14 +56,14 @@ class AppNavigatorSession(
// 2. Build single-turn prompt
val actionLogText = actionLog.joinToString("\n") { " $it" }.ifEmpty { " (none yet)" }
-
+
// Send the tree (which is now organically filtered)
val obsText = if (screenshot != null) {
ScreenPerception.buildObservationText(screenshot, uiTree)
} else {
"── UI Elements ──\n$uiTree\n── Screenshot ──\n(failed to capture)"
}
-
+
val userMsg = buildString {
appendLine("## Task")
appendLine(task)
@@ -130,12 +129,15 @@ class AppNavigatorSession(
// 5. Execute each tool call with error recovery
for (call in toolCalls) {
val result = executeWithRetry(call)
- val summary = if (result.success) result.message.take(100)
- else "⚠ ${result.message.take(100)}"
+ val summary = if (result.success) {
+ result.message.take(100)
+ } else {
+ "⚠ ${result.message.take(100)}"
+ }
actionLog.add("Step $step: ${call.function.name} → $summary")
onStep(call.function.name, "completed", summary)
}
-
+
// Wait for animations/transitions to settle before the next observation
if (toolCalls.isNotEmpty()) {
delay(1000)
diff --git a/app/src/main/java/com/gotcha/tools/ScreenPerception.kt b/app/src/main/java/com/gotcha/tools/ScreenPerception.kt
index f500f88..eb956bd 100644
--- a/app/src/main/java/com/gotcha/tools/ScreenPerception.kt
+++ b/app/src/main/java/com/gotcha/tools/ScreenPerception.kt
@@ -67,13 +67,16 @@ object ScreenPerception {
}
Log.d("ScreenCapture", "compressScreenshot: got ${bytes.size} raw bytes")
val originalSize = bytes.size.toLong()
- val options = BitmapFactory.Options().apply {
+ val options = BitmapFactory.Options().apply {
inMutable = true
- inScaled = false
+ inScaled = false
}
val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
if (bitmap == null) {
- Log.e("ScreenCapture", "compressScreenshot: BitmapFactory.decodeByteArray returned null — invalid image data")
+ Log.e(
+ "ScreenCapture",
+ "compressScreenshot: BitmapFactory.decodeByteArray returned null — invalid image data"
+ )
return null
}
Log.d("ScreenCapture", "compressScreenshot: decoded bitmap ${bitmap.width}x${bitmap.height}")
@@ -87,14 +90,14 @@ object ScreenPerception {
} else {
bitmap
}
-
+
val forEncoding = if (maxDimension > 0) downscale(annotated, maxDimension) else annotated
-
+
val sw = forEncoding.width
val sh = forEncoding.height
val output = ByteArrayOutputStream()
forEncoding.compress(format, quality, output)
-
+
if (saveDir != null) {
try {
if (!saveDir.exists()) saveDir.mkdirs()
@@ -106,16 +109,16 @@ object ScreenPerception {
Log.e("ScreenCapture", "Failed to save debug screenshot: ${e.message}")
}
}
-
+
if (forEncoding !== annotated) forEncoding.recycle()
if (annotated !== bitmap) annotated.recycle()
bitmap.recycle()
val base64 = Base64.encodeToString(output.toByteArray(), Base64.NO_WRAP)
- val fmtName = when (format) {
- Bitmap.CompressFormat.JPEG -> "jpeg"
- Bitmap.CompressFormat.PNG -> "png"
- Bitmap.CompressFormat.WEBP_LOSSY -> "webp"
- Bitmap.CompressFormat.WEBP_LOSSLESS -> "webp"
+ // WEBP_LOSSY/WEBP_LOSSLESS enum fields need API 30 — match by name instead.
+ val fmtName = when {
+ format == Bitmap.CompressFormat.JPEG -> "jpeg"
+ format == Bitmap.CompressFormat.PNG -> "png"
+ format.name.startsWith("WEBP") -> "webp"
else -> "jpeg"
}
CompressedScreenshot(base64, sw, sh, fmtName, originalSize)
@@ -273,24 +276,24 @@ object ScreenPerception {
val top = parts[1].toFloat()
val right = parts[2].toFloat()
val bottom = parts[3].toFloat()
-
+
// Draw bounding box
canvas.drawRect(left, top, right, bottom, boxPaint)
-
+
// Draw label [Index] at the top-left of the box
val label = "[${el.index}]"
val textWidth = textPaint.measureText(label)
val fontMetrics = textPaint.fontMetrics
val textHeight = fontMetrics.descent - fontMetrics.ascent
-
+
// Keep label within bounds
val bgLeft = left
var bgTop = top - textHeight - 4f
if (bgTop < 0) bgTop = top // If goes off top edge, push inside the box
-
+
val bgRight = bgLeft + textWidth + 8f
val bgBottom = bgTop + textHeight + 8f
-
+
canvas.drawRect(bgLeft, bgTop, bgRight, bgBottom, labelBgPaint)
canvas.drawText(label, bgLeft + 4f, bgBottom - fontMetrics.descent - 4f, textPaint)
}
@@ -329,7 +332,10 @@ object ScreenPerception {
// Path 2: MediaProjection — works on all devices if user granted consent.
val projectionData = mediaProjectionResultData
val ctx = appContext ?: GotchaAccessibilityService.instance?.applicationContext
- Log.d("ScreenCapture", "Path2: projectionData=${projectionData != null}, ctx=${ctx != null}, appContext=${appContext != null}")
+ Log.d(
+ "ScreenCapture",
+ "Path2: projectionData=${projectionData != null}, ctx=${ctx != null}, appContext=${appContext != null}"
+ )
if (projectionData != null && ctx != null) {
Log.d("ScreenCapture", "Path2: calling MediaProjectionService.capture()")
val bytes = withContext(Dispatchers.IO) {
@@ -358,7 +364,9 @@ object ScreenPerception {
val (w, h) = if (bitmap.width > maxDim || bitmap.height > maxDim) {
val ratio = minOf(maxDim.toFloat() / bitmap.width, maxDim.toFloat() / bitmap.height)
(bitmap.width * ratio).toInt() to (bitmap.height * ratio).toInt()
- } else bitmap.width to bitmap.height
+ } else {
+ bitmap.width to bitmap.height
+ }
return Bitmap.createScaledBitmap(bitmap, w, h, true)
}
@@ -380,7 +388,7 @@ object ScreenPerception {
val isInteractable = node.isClickable || node.isScrollable || node.isEditable || node.isCheckable
val hasMeaningfulContent = label.isNotEmpty()
-
+
if (isInteractable || hasMeaningfulContent) {
index[0]++
out.add(
diff --git a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt b/app/src/main/java/com/gotcha/tools/SubAgentSession.kt
index 076af73..f591c3c 100644
--- a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt
+++ b/app/src/main/java/com/gotcha/tools/SubAgentSession.kt
@@ -30,7 +30,6 @@ class SubAgentSession(
private val onStep: (action: String, status: String, detail: String) -> Unit = { _, _, _ -> },
private val sessionId: String? = null
) {
- private val TAG = "SubAgentSession"
private val json = Json { ignoreUnknownKeys = true }
private var activeTokenCount = 0
private val collectedSteps = mutableListOf<String>()
@@ -47,26 +46,7 @@ class SubAgentSession(
apiTimeoutSeconds = settings.apiTimeoutSeconds
)
- val systemMsg = ChatMessage(
- role = "system",
- content = JsonPrimitive(
- "You are General, a general-purpose AI agent running on the user's Android phone. " +
- "You have access to all device tools. " +
- "Your job is to complete the task delegated to you. " +
- "Use the available tools to perform the required steps. " +
- "When you have fully completed the task and have the final answer, " +
- "call the ask_final_answer tool with your complete result. " +
- "Do NOT call ask_final_answer until all work is actually done."
- )
- )
-
- val userMsg = ChatMessage(
- role = "user",
- content = JsonPrimitive(prompt)
- )
-
- val history = mutableListOf(systemMsg, userMsg)
- activeTokenCount = (systemMsg.textContent.length + userMsg.textContent.length) / 4
+ val history = initialHistory()
val maxRounds = settings.maxToolRounds
val subAgentTools = ToolRegistry.toolsForSubAgent()
@@ -129,7 +109,7 @@ class SubAgentSession(
val args = try {
json.decodeFromString<JsonObject>(call.function.arguments.ifBlank { "{}" })
- } catch (e: Exception) {
+ } catch (_: Exception) {
val err = "Malformed args: ${call.function.arguments.take(100)}"
history.add(ChatMessage(role = "tool", content = JsonPrimitive(err), toolCallId = call.id))
collectedSteps[collectedSteps.lastIndex] = "$toolName → failed: bad arguments"
@@ -176,6 +156,28 @@ class SubAgentSession(
return SubAgentOutput(msg, collectedSteps.toList())
}
+ /** Builds the system + user messages that seed the sub-agent conversation. */
+ private fun initialHistory(): MutableList<ChatMessage> {
+ val systemMsg = ChatMessage(
+ role = "system",
+ content = JsonPrimitive(
+ "You are General, a general-purpose AI agent running on the user's Android phone. " +
+ "You have access to all device tools. " +
+ "Your job is to complete the task delegated to you. " +
+ "Use the available tools to perform the required steps. " +
+ "When you have fully completed the task and have the final answer, " +
+ "call the ask_final_answer tool with your complete result. " +
+ "Do NOT call ask_final_answer until all work is actually done."
+ )
+ )
+ val userMsg = ChatMessage(
+ role = "user",
+ content = JsonPrimitive(prompt)
+ )
+ activeTokenCount = (systemMsg.textContent.length + userMsg.textContent.length) / 4
+ return mutableListOf(systemMsg, userMsg)
+ }
+
/**
* Compacts history using an LLM summarization call (same strategy as
* ChatViewModel.checkAndCompactHistory). Preserves the system prompt
@@ -195,9 +197,11 @@ class SubAgentSession(
val exchangeText = history.subList(2, history.size).joinToString("\n\n") { msg ->
val role = msg.role.uppercase()
val text = msg.textContent.ifEmpty {
- if (!msg.toolCalls.isNullOrEmpty())
+ if (!msg.toolCalls.isNullOrEmpty()) {
"Called tools: " + msg.toolCalls.joinToString(", ") { it.function.name }
- else ""
+ } else {
+ ""
+ }
}
"[$role]: $text"
}
@@ -206,16 +210,16 @@ class SubAgentSession(
role = "system",
content = JsonPrimitive(
"You are a context compaction agent. Compress the following sub-agent " +
- "tool-call history into a dense summary preserving: what was attempted, " +
- "what succeeded, what failed, and key data discovered. Be concise but " +
- "do not lose technical specifics."
+ "tool-call history into a dense summary preserving: what was attempted, " +
+ "what succeeded, what failed, and key data discovered. Be concise but " +
+ "do not lose technical specifics."
)
)
val compactionUser = ChatMessage(
role = "user",
content = JsonPrimitive(
"Original task: ${userTask.textContent}\n\n" +
- "Intermediate exchanges:\n$exchangeText"
+ "Intermediate exchanges:\n$exchangeText"
)
)
@@ -226,10 +230,12 @@ class SubAgentSession(
history.clear()
history.add(sysPrompt)
history.add(userTask)
- history.add(ChatMessage(
- role = "assistant",
- content = JsonPrimitive("[Context compacted]\n$summary")
- ))
+ history.add(
+ ChatMessage(
+ role = "assistant",
+ content = JsonPrimitive("[Context compacted]\n$summary")
+ )
+ )
activeTokenCount = history.sumOf { it.textContent.length / 4 }
}
} catch (e: CancellationException) {
@@ -239,4 +245,8 @@ class SubAgentSession(
Log.w(TAG, "Sub-agent context compaction failed, keeping full history")
}
}
+
+ private companion object {
+ const val TAG = "SubAgentSession"
+ }
}
diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
index fcaa913..d73d48c 100644
--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
@@ -1161,21 +1161,33 @@ object ToolDefinitions {
putJsonObject("properties") {
putJsonObject("description") {
put("type", "string")
- put("description", "Brief description of what the sub-agent should do " +
- "(shown in the UI while it runs).")
+ put(
+ "description",
+ "Brief description of what the sub-agent should do " +
+ "(shown in the UI while it runs)."
+ )
}
putJsonObject("prompt") {
put("type", "string")
- put("description", "Detailed instructions for the sub-agent. " +
- "Include all context the sub-agent needs to complete the task.")
+ put(
+ "description",
+ "Detailed instructions for the sub-agent. " +
+ "Include all context the sub-agent needs to complete the task."
+ )
}
putJsonObject("subagent_type") {
put("type", "string")
- put("description", "Which sub-agent to use. Default: 'general'. " +
- "Available: general.")
+ put(
+ "description",
+ "Which sub-agent to use. Default: 'general'. " +
+ "Available: general."
+ )
}
}
- putJsonArray("required") { add("description"); add("prompt") }
+ putJsonArray("required") {
+ add("description")
+ add("prompt")
+ }
}
)
@@ -1359,7 +1371,8 @@ object ToolDefinitions {
val swipe = tool(
"swipe",
"Swipe/scroll the screen or a specific element. " +
- "If using a direction, 'down' means scroll the content down to see lower items. 'up' means scroll the content up to see higher items. " +
+ "If using a direction, 'down' means scroll the content down to see lower items. " +
+ "'up' means scroll the content up to see higher items. " +
"Needs the accessibility service enabled.",
schema {
putJsonObject("properties") {
@@ -1371,10 +1384,22 @@ object ToolDefinitions {
put("type", "integer")
put("description", "Optional index of the UI element to swipe on.")
}
- putJsonObject("x1") { put("type", "integer"); put("description", "Start X (with y1,x2,y2).") }
- putJsonObject("y1") { put("type", "integer"); put("description", "Start Y.") }
- putJsonObject("x2") { put("type", "integer"); put("description", "End X.") }
- putJsonObject("y2") { put("type", "integer"); put("description", "End Y.") }
+ putJsonObject("x1") {
+ put("type", "integer")
+ put("description", "Start X (with y1,x2,y2).")
+ }
+ putJsonObject("y1") {
+ put("type", "integer")
+ put("description", "Start Y.")
+ }
+ putJsonObject("x2") {
+ put("type", "integer")
+ put("description", "End X.")
+ }
+ putJsonObject("y2") {
+ put("type", "integer")
+ put("description", "End Y.")
+ }
putJsonObject("normalized") {
put("type", "boolean")
put("description", "If true, coordinate params are in [0, 1000] normalized space. Default true.")
@@ -1441,12 +1466,17 @@ object ToolDefinitions {
val pressKey = tool(
"press_key",
"Press a system key or perform a navigation action. " +
- "Note: 'enter' may not successfully submit forms or searches on all apps. It is much more reliable to use tap or tap_index to click the on-screen 'Search', 'Submit', or 'Go' button instead.",
+ "Note: 'enter' may not successfully submit forms or searches on all apps. It is much " +
+ "more reliable to use tap or tap_index to click the on-screen 'Search', 'Submit', " +
+ "or 'Go' button instead.",
schema {
putJsonObject("properties") {
putJsonObject("key") {
put("type", "string")
- put("description", "One of: enter, back, home, recents, notifications, quick_settings, lock_screen.")
+ put(
+ "description",
+ "One of: enter, back, home, recents, notifications, quick_settings, lock_screen."
+ )
}
}
putJsonArray("required") { add("key") }
@@ -1463,11 +1493,14 @@ object ToolDefinitions {
putJsonObject("properties") {
putJsonObject("task") {
put("type", "string")
- put("description", "Detailed step-by-step instructions of what to do in the app. " +
- "Include the app name, search terms, what to look for, and what the final " +
- "summary should contain. " +
- "Example: 'Open Google Maps, search for restaurants near me, scroll through " +
- "results, and tell me the top 5 with ratings and distances.'")
+ put(
+ "description",
+ "Detailed step-by-step instructions of what to do in the app. " +
+ "Include the app name, search terms, what to look for, and what the final " +
+ "summary should contain. " +
+ "Example: 'Open Google Maps, search for restaurants near me, scroll through " +
+ "results, and tell me the top 5 with ratings and distances.'"
+ )
}
}
putJsonArray("required") { add("task") }
diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
index 799d969..b698325 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -68,7 +68,12 @@ class ToolExecutor(
* Execute [name] with [args] on behalf of the given [agent].
* Returns an error without running the tool if the agent mode disallows it.
*/
- suspend fun execute(name: String, args: JsonObject, agent: AgentMode = AgentMode.OPERATOR, isSubAgent: Boolean = false): ToolResult {
+ suspend fun execute(
+ name: String,
+ args: JsonObject,
+ agent: AgentMode = AgentMode.OPERATOR,
+ isSubAgent: Boolean = false
+ ): ToolResult {
if (!ToolRegistry.contains(name)) {
return ToolResult.error("Unknown tool '$name'. Only the fixed tool catalog is available.")
}
@@ -128,322 +133,327 @@ class ToolExecutor(
@Suppress("CyclomaticComplexMethod", "LongMethod")
private suspend fun dispatch(name: String, args: JsonObject): ToolResult {
return when (name) {
- "dial_number" -> phoneTool.dialNumber(args.requireString("number") ?: return missing("number"))
- "get_storage_info" -> storageTool.getStorageInfo()
- "get_battery_info" -> systemTool.getBatteryInfo()
- "edit" -> editTool.edit(
- path = args.requireString("path") ?: return missing("path"),
- oldString = args.requireString("oldString") ?: return missing("oldString"),
- newString = args.requireString("newString") ?: return missing("newString"),
- replaceAll = args["replaceAll"]?.jsonPrimitive?.booleanOrNull ?: false
- )
- "list_files" -> fileTool.listFiles(
- path = args.requireString("path") ?: return missing("path"),
- recursive = args["recursive"]?.jsonPrimitive?.booleanOrNull ?: false,
- sortBy = args.requireString("sort_by"),
- include = args.requireString("include"),
- exclude = args.requireString("exclude"),
- maxDepth = args.requireInt("max_depth")
- )
- "read_file" -> fileTool.readFile(
- path = args.requireString("path") ?: return missing("path"),
- offset = args.requireInt("offset"),
- limit = args.requireInt("limit"),
- encoding = args.requireString("encoding")
- )
- "write_file" -> fileTool.writeFile(
- path = args.requireString("path") ?: return missing("path"),
- content = args.requireString("content") ?: return missing("content"),
- append = args["append"]?.jsonPrimitive?.booleanOrNull ?: false,
- binary = args["binary"]?.jsonPrimitive?.booleanOrNull ?: false
- )
- "open_app" -> systemTool.openApp(args.requireString("package_name") ?: return missing("package_name"))
- "set_brightness" -> systemTool.setBrightness(
- args["percent"]?.jsonPrimitive?.intOrNull ?: return missing("percent")
- )
- "toggle_wifi" -> systemTool.toggleWifi(
- args["enabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("enabled")
- )
- "set_wallpaper" -> wallpaperTool.setWallpaper(args.requireString("url"))
- "run_command" -> terminalTool.runCommand(
- command = args.requireString("command") ?: return missing("command"),
- workingDir = args.requireString("working_dir"),
- timeoutSeconds = args.requireInt("timeout_seconds") ?: 15
- )
- "call_number" -> phoneTool.callNumber(
- args.requireString("number") ?: return missing("number"),
- speakerphone = args["speakerphone"]?.jsonPrimitive?.booleanOrNull,
- simSlot = args.requireString("sim_slot")
- )
- "read_call_log" -> phoneTool.readCallLog(
- limit = args.requireInt("limit") ?: 10,
- callTypeFilter = args.requireString("type"),
- contact = args.requireString("contact"),
- fromDate = args.requireString("from_date"),
- toDate = args.requireString("to_date")
- )
- "find_contact" -> contactsTool.findContact(
- name = args.requireString("name"),
- number = args.requireString("number")
- )
- "add_contact" -> contactsTool.addContact(
- name = args.requireString("name") ?: return missing("name"),
- number = args.requireString("number") ?: return missing("number"),
- phoneType = args.requireString("phone_type"),
- email = args.requireString("email"),
- organization = args.requireString("organization")
- )
- "send_sms" -> smsTool.sendSms(
- number = args.requireString("number") ?: return missing("number"),
- message = args.requireString("message") ?: return missing("message"),
- deliveryReport = args["delivery_report"]?.jsonPrimitive?.booleanOrNull,
- sendAt = args.requireString("send_at")
- )
- "read_recent_sms" -> smsTool.readRecentSms(
- limit = args.requireInt("limit") ?: 10,
- fromAddress = args.requireString("from_address"),
- fromDate = args.requireString("from_date"),
- toDate = args.requireString("to_date"),
- unreadOnly = args["unread_only"]?.jsonPrimitive?.booleanOrNull,
- search = args.requireString("search"),
- includeSent = args["include_sent"]?.jsonPrimitive?.booleanOrNull
- )
- "list_calendar_events" -> calendarTool.listEvents(
- daysAhead = args.requireInt("days_ahead"),
- fromDate = args.requireString("from_date"),
- toDate = args.requireString("to_date"),
- search = args.requireString("search")
- )
- "create_calendar_event" -> calendarTool.createEvent(
- title = args.requireString("title") ?: return missing("title"),
- start = args.requireString("start") ?: return missing("start"),
- end = args.requireString("end"),
- location = args.requireString("location"),
- description = args.requireString("description"),
- allDay = args["all_day"]?.jsonPrimitive?.booleanOrNull,
- reminderMinutes = args.requireInt("reminder_minutes"),
- calendarName = args.requireString("calendar_name")
- )
- "edit_calendar_event" -> calendarTool.editEvent(
- eventId = args.requireInt("event_id")?.toLong() ?: return missing("event_id"),
- title = args.requireString("title"),
- start = args.requireString("start"),
- end = args.requireString("end"),
- location = args.requireString("location"),
- description = args.requireString("description"),
- allDay = args["all_day"]?.jsonPrimitive?.booleanOrNull,
- reminderMinutes = args.requireInt("reminder_minutes")
- )
- "delete_calendar_event" -> calendarTool.deleteEvent(
- eventId = args.requireInt("event_id")?.toLong() ?: return missing("event_id")
- )
- "set_alarm" -> alarmTool.setAlarm(
- hour = args.requireInt("hour") ?: return missing("hour"),
- minute = args.requireInt("minute") ?: return missing("minute"),
- message = args.requireString("message"),
- days = args["days"]?.jsonArray?.mapNotNull { it.jsonPrimitive?.content },
- vibrate = args["vibrate"]?.jsonPrimitive?.booleanOrNull
- )
- "set_timer" -> alarmTool.setTimer(
- seconds = args.requireInt("seconds") ?: 0,
- message = args.requireString("message"),
- hours = args.requireInt("hours"),
- minutes = args.requireInt("minutes")
- )
- "list_alarms" -> alarmTool.listAlarms()
- "list_timers" -> alarmTool.listTimers()
- "edit_alarm" -> alarmTool.editAlarm(
- id = args.requireInt("alarm_id")?.toLong() ?: return missing("alarm_id"),
- hour = args.requireInt("hour"),
- minute = args.requireInt("minute"),
- message = args.requireString("message"),
- days = args["days"]?.jsonArray?.mapNotNull { it.jsonPrimitive?.content },
- vibrate = args["vibrate"]?.jsonPrimitive?.booleanOrNull
- )
- "delete_alarm" -> alarmTool.deleteAlarm(
- id = args.requireInt("alarm_id")?.toLong() ?: return missing("alarm_id")
- )
- "delete_timer" -> alarmTool.deleteTimer(
- id = args.requireInt("timer_id")?.toLong() ?: return missing("timer_id")
- )
- "toggle_torch" -> deviceTool.toggleTorch(
- on = args["on"]?.jsonPrimitive?.booleanOrNull ?: return missing("on"),
- durationSeconds = args.requireInt("duration_seconds")
- )
- "set_volume" -> deviceTool.setVolume(
- stream = args.requireString("stream") ?: return missing("stream"),
- percent = args.requireInt("percent") ?: return missing("percent"),
- showUi = args["show_ui"]?.jsonPrimitive?.booleanOrNull ?: false
- )
- "get_volume" -> deviceTool.getVolume(args.requireString("stream"))
- "set_ringer_mode" -> deviceTool.setRingerMode(args.requireString("mode") ?: return missing("mode"))
- "vibrate" -> deviceTool.vibrate(
- durationMs = args.requireInt("duration_ms") ?: 500,
- intensity = args.requireInt("intensity") ?: 100,
- pattern = args.requireString("pattern")
- )
- "set_dnd" -> deviceTool.setDnd(
- args["enabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("enabled")
- )
- "get_location" -> locationTool.getLocation(
- fresh = args["fresh"]?.jsonPrimitive?.booleanOrNull
- )
- "list_installed_apps" -> appsTool.listInstalledApps(args.requireString("search"))
- "uninstall_app" -> appsTool.uninstallApp(args.requireString("package_name") ?: return missing("package_name"))
- "get_app_usage" -> appsTool.getAppUsage(args.requireInt("days") ?: 7)
- "get_data_usage" -> appsTool.getDataUsage(args.requireInt("days") ?: 30)
- "get_clipboard" -> clipboardTool.getClipboard()
- "set_clipboard" -> clipboardTool.setClipboard(args.requireString("text") ?: return missing("text"))
- "take_photo" -> mediaCaptureTool.takePhoto(args.requireString("camera"))
- "start_audio_recording" -> mediaCaptureTool.startAudioRecording(
- source = args.requireString("source"),
- maxDurationSeconds = args.requireInt("max_duration_seconds"),
- outputPath = args.requireString("output_path"),
- quality = args.requireString("quality")
- )
- "stop_audio_recording" -> mediaCaptureTool.stopAudioRecording()
- "get_audio_recording_status" -> mediaCaptureTool.getAudioRecordingStatus()
- "pause_audio_recording" -> mediaCaptureTool.pauseAudioRecording()
- "resume_audio_recording" -> mediaCaptureTool.resumeAudioRecording()
- "question" -> questionTool.ask(
- question = args.requireString("question") ?: return missing("question"),
- options = args["options"]?.jsonArray?.mapNotNull { it.jsonPrimitive?.content },
- allowCustom = args["allowCustom"]?.jsonPrimitive?.booleanOrNull ?: true
- )
- "websearch" -> webSearchTool.search(
- query = args.requireString("query") ?: return missing("query"),
- numResults = args.requireInt("numResults") ?: 5
- )
- "webfetch" -> webFetchTool.fetch(
- url = args.requireString("url") ?: return missing("url"),
- format = args.requireString("format")
- )
- "todowrite" -> todoTool.todowrite(
- parseTodoItems(args["items"]) ?: return missing("items")
- )
- "ask_final_answer" -> {
- ToolResult.ok(args.requireString("answer") ?: "(no answer)")
- }
- "task" -> {
- val handler = onTask
- if (handler == null) {
- ToolResult.error("Task delegation is not configured.")
- } else {
- val description = args.requireString("description") ?: return missing("description")
- val prompt = args.requireString("prompt") ?: return missing("prompt")
- handler(description, prompt)
+ "dial_number" -> phoneTool.dialNumber(args.requireString("number") ?: return missing("number"))
+ "get_storage_info" -> storageTool.getStorageInfo()
+ "get_battery_info" -> systemTool.getBatteryInfo()
+ "edit" -> editTool.edit(
+ path = args.requireString("path") ?: return missing("path"),
+ oldString = args.requireString("oldString") ?: return missing("oldString"),
+ newString = args.requireString("newString") ?: return missing("newString"),
+ replaceAll = args["replaceAll"]?.jsonPrimitive?.booleanOrNull ?: false
+ )
+ "list_files" -> fileTool.listFiles(
+ path = args.requireString("path") ?: return missing("path"),
+ recursive = args["recursive"]?.jsonPrimitive?.booleanOrNull ?: false,
+ sortBy = args.requireString("sort_by"),
+ include = args.requireString("include"),
+ exclude = args.requireString("exclude"),
+ maxDepth = args.requireInt("max_depth")
+ )
+ "read_file" -> fileTool.readFile(
+ path = args.requireString("path") ?: return missing("path"),
+ offset = args.requireInt("offset"),
+ limit = args.requireInt("limit"),
+ encoding = args.requireString("encoding")
+ )
+ "write_file" -> fileTool.writeFile(
+ path = args.requireString("path") ?: return missing("path"),
+ content = args.requireString("content") ?: return missing("content"),
+ append = args["append"]?.jsonPrimitive?.booleanOrNull ?: false,
+ binary = args["binary"]?.jsonPrimitive?.booleanOrNull ?: false
+ )
+ "open_app" -> systemTool.openApp(args.requireString("package_name") ?: return missing("package_name"))
+ "set_brightness" -> systemTool.setBrightness(
+ args["percent"]?.jsonPrimitive?.intOrNull ?: return missing("percent")
+ )
+ "toggle_wifi" -> systemTool.toggleWifi(
+ args["enabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("enabled")
+ )
+ "set_wallpaper" -> wallpaperTool.setWallpaper(args.requireString("url"))
+ "run_command" -> terminalTool.runCommand(
+ command = args.requireString("command") ?: return missing("command"),
+ workingDir = args.requireString("working_dir"),
+ timeoutSeconds = args.requireInt("timeout_seconds") ?: 15
+ )
+ "call_number" -> phoneTool.callNumber(
+ args.requireString("number") ?: return missing("number"),
+ speakerphone = args["speakerphone"]?.jsonPrimitive?.booleanOrNull,
+ simSlot = args.requireString("sim_slot")
+ )
+ "read_call_log" -> phoneTool.readCallLog(
+ limit = args.requireInt("limit") ?: 10,
+ callTypeFilter = args.requireString("type"),
+ contact = args.requireString("contact"),
+ fromDate = args.requireString("from_date"),
+ toDate = args.requireString("to_date")
+ )
+ "find_contact" -> contactsTool.findContact(
+ name = args.requireString("name"),
+ number = args.requireString("number")
+ )
+ "add_contact" -> contactsTool.addContact(
+ name = args.requireString("name") ?: return missing("name"),
+ number = args.requireString("number") ?: return missing("number"),
+ phoneType = args.requireString("phone_type"),
+ email = args.requireString("email"),
+ organization = args.requireString("organization")
+ )
+ "send_sms" -> smsTool.sendSms(
+ number = args.requireString("number") ?: return missing("number"),
+ message = args.requireString("message") ?: return missing("message"),
+ deliveryReport = args["delivery_report"]?.jsonPrimitive?.booleanOrNull,
+ sendAt = args.requireString("send_at")
+ )
+ "read_recent_sms" -> smsTool.readRecentSms(
+ limit = args.requireInt("limit") ?: 10,
+ fromAddress = args.requireString("from_address"),
+ fromDate = args.requireString("from_date"),
+ toDate = args.requireString("to_date"),
+ unreadOnly = args["unread_only"]?.jsonPrimitive?.booleanOrNull,
+ search = args.requireString("search"),
+ includeSent = args["include_sent"]?.jsonPrimitive?.booleanOrNull
+ )
+ "list_calendar_events" -> calendarTool.listEvents(
+ daysAhead = args.requireInt("days_ahead"),
+ fromDate = args.requireString("from_date"),
+ toDate = args.requireString("to_date"),
+ search = args.requireString("search")
+ )
+ "create_calendar_event" -> calendarTool.createEvent(
+ title = args.requireString("title") ?: return missing("title"),
+ start = args.requireString("start") ?: return missing("start"),
+ end = args.requireString("end"),
+ location = args.requireString("location"),
+ description = args.requireString("description"),
+ allDay = args["all_day"]?.jsonPrimitive?.booleanOrNull,
+ reminderMinutes = args.requireInt("reminder_minutes"),
+ calendarName = args.requireString("calendar_name")
+ )
+ "edit_calendar_event" -> calendarTool.editEvent(
+ eventId = args.requireInt("event_id")?.toLong() ?: return missing("event_id"),
+ title = args.requireString("title"),
+ start = args.requireString("start"),
+ end = args.requireString("end"),
+ location = args.requireString("location"),
+ description = args.requireString("description"),
+ allDay = args["all_day"]?.jsonPrimitive?.booleanOrNull,
+ reminderMinutes = args.requireInt("reminder_minutes")
+ )
+ "delete_calendar_event" -> calendarTool.deleteEvent(
+ eventId = args.requireInt("event_id")?.toLong() ?: return missing("event_id")
+ )
+ "set_alarm" -> alarmTool.setAlarm(
+ hour = args.requireInt("hour") ?: return missing("hour"),
+ minute = args.requireInt("minute") ?: return missing("minute"),
+ message = args.requireString("message"),
+ days = args["days"]?.jsonArray?.mapNotNull { it.jsonPrimitive?.content },
+ vibrate = args["vibrate"]?.jsonPrimitive?.booleanOrNull
+ )
+ "set_timer" -> alarmTool.setTimer(
+ seconds = args.requireInt("seconds") ?: 0,
+ message = args.requireString("message"),
+ hours = args.requireInt("hours"),
+ minutes = args.requireInt("minutes")
+ )
+ "list_alarms" -> alarmTool.listAlarms()
+ "list_timers" -> alarmTool.listTimers()
+ "edit_alarm" -> alarmTool.editAlarm(
+ id = args.requireInt("alarm_id")?.toLong() ?: return missing("alarm_id"),
+ hour = args.requireInt("hour"),
+ minute = args.requireInt("minute"),
+ message = args.requireString("message"),
+ days = args["days"]?.jsonArray?.mapNotNull { it.jsonPrimitive?.content },
+ vibrate = args["vibrate"]?.jsonPrimitive?.booleanOrNull
+ )
+ "delete_alarm" -> alarmTool.deleteAlarm(
+ id = args.requireInt("alarm_id")?.toLong() ?: return missing("alarm_id")
+ )
+ "delete_timer" -> alarmTool.deleteTimer(
+ id = args.requireInt("timer_id")?.toLong() ?: return missing("timer_id")
+ )
+ "toggle_torch" -> deviceTool.toggleTorch(
+ on = args["on"]?.jsonPrimitive?.booleanOrNull ?: return missing("on"),
+ durationSeconds = args.requireInt("duration_seconds")
+ )
+ "set_volume" -> deviceTool.setVolume(
+ stream = args.requireString("stream") ?: return missing("stream"),
+ percent = args.requireInt("percent") ?: return missing("percent"),
+ showUi = args["show_ui"]?.jsonPrimitive?.booleanOrNull ?: false
+ )
+ "get_volume" -> deviceTool.getVolume(args.requireString("stream"))
+ "set_ringer_mode" -> deviceTool.setRingerMode(args.requireString("mode") ?: return missing("mode"))
+ "vibrate" -> deviceTool.vibrate(
+ durationMs = args.requireInt("duration_ms") ?: 500,
+ intensity = args.requireInt("intensity") ?: 100,
+ pattern = args.requireString("pattern")
+ )
+ "set_dnd" -> deviceTool.setDnd(
+ args["enabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("enabled")
+ )
+ "get_location" -> locationTool.getLocation(
+ fresh = args["fresh"]?.jsonPrimitive?.booleanOrNull
+ )
+ "list_installed_apps" -> appsTool.listInstalledApps(args.requireString("search"))
+ "uninstall_app" -> appsTool.uninstallApp(
+ args.requireString("package_name") ?: return missing("package_name")
+ )
+ "get_app_usage" -> appsTool.getAppUsage(args.requireInt("days") ?: 7)
+ "get_data_usage" -> appsTool.getDataUsage(args.requireInt("days") ?: 30)
+ "get_clipboard" -> clipboardTool.getClipboard()
+ "set_clipboard" -> clipboardTool.setClipboard(args.requireString("text") ?: return missing("text"))
+ "take_photo" -> mediaCaptureTool.takePhoto(args.requireString("camera"))
+ "start_audio_recording" -> mediaCaptureTool.startAudioRecording(
+ source = args.requireString("source"),
+ maxDurationSeconds = args.requireInt("max_duration_seconds"),
+ outputPath = args.requireString("output_path"),
+ quality = args.requireString("quality")
+ )
+ "stop_audio_recording" -> mediaCaptureTool.stopAudioRecording()
+ "get_audio_recording_status" -> mediaCaptureTool.getAudioRecordingStatus()
+ "pause_audio_recording" -> mediaCaptureTool.pauseAudioRecording()
+ "resume_audio_recording" -> mediaCaptureTool.resumeAudioRecording()
+ "question" -> questionTool.ask(
+ question = args.requireString("question") ?: return missing("question"),
+ options = args["options"]?.jsonArray?.mapNotNull { it.jsonPrimitive?.content },
+ allowCustom = args["allowCustom"]?.jsonPrimitive?.booleanOrNull ?: true
+ )
+ "websearch" -> webSearchTool.search(
+ query = args.requireString("query") ?: return missing("query"),
+ numResults = args.requireInt("numResults") ?: 5
+ )
+ "webfetch" -> webFetchTool.fetch(
+ url = args.requireString("url") ?: return missing("url"),
+ format = args.requireString("format")
+ )
+ "todowrite" -> todoTool.todowrite(
+ parseTodoItems(args["items"]) ?: return missing("items")
+ )
+ "ask_final_answer" -> {
+ ToolResult.ok(args.requireString("answer") ?: "(no answer)")
}
- }
- "sleep" -> {
- val secs = args.requireInt("duration_seconds")?.coerceIn(1, 86400)
- ?: return missing("duration_seconds")
- for (remaining in secs downTo 1) {
- Log.d(TAG, "sleep: ${remaining}s remaining")
- delay(1000L)
+ "task" -> {
+ val handler = onTask
+ if (handler == null) {
+ ToolResult.error("Task delegation is not configured.")
+ } else {
+ val description = args.requireString("description") ?: return missing("description")
+ val prompt = args.requireString("prompt") ?: return missing("prompt")
+ handler(description, prompt)
+ }
}
- ToolResult.ok("Slept for $secs seconds.")
- }
- "read_image" -> fileTool.readFile(args.requireString("path") ?: return missing("path"))
- "glob" -> globTool.glob(
- path = args.requireString("path") ?: return missing("path"),
- pattern = args.requireString("pattern") ?: return missing("pattern")
- )
- "grep" -> grepTool.grep(
- path = args.requireString("path") ?: return missing("path"),
- pattern = args.requireString("pattern") ?: return missing("pattern"),
- include = args.requireString("include")
- )
- // ---- Tier 3 ----
- "read_screen" -> accessibilityTool.readScreen()
- "read_screen_raw" -> accessibilityTool.readScreenRaw()
- "tap" -> {
- var x = args.requireInt("x")
- var y = args.requireInt("y")
- val normalized = args.requireBoolean("normalized") ?: true
- if (normalized && x != null && y != null) {
- val (w, h) = ScreenPerception.getScreenDimensions()
- val (nx, ny) = ScreenPerception.normalizeToPixel(x, y, w, h)
- x = nx; y = ny
+ "sleep" -> {
+ val secs = args.requireInt("duration_seconds")?.coerceIn(1, 86400)
+ ?: return missing("duration_seconds")
+ for (remaining in secs downTo 1) {
+ Log.d(TAG, "sleep: ${remaining}s remaining")
+ delay(1000L)
+ }
+ ToolResult.ok("Slept for $secs seconds.")
}
- accessibilityTool.tap(text = args.requireString("text"), x = x, y = y)
- }
- "swipe" -> accessibilityTool.swipe(
- direction = args.requireString("direction"),
- x1 = args.requireInt("x1"), y1 = args.requireInt("y1"),
- x2 = args.requireInt("x2"), y2 = args.requireInt("y2"),
- normalized = args.requireBoolean("normalized") ?: true,
- index = args.requireInt("index")
- )
- "tap_index" -> {
- val index = args.requireInt("index") ?: return missing("index")
- accessibilityTool.tapByIndex(index)
- }
- "long_press" -> {
- var x = args.requireInt("x")
- var y = args.requireInt("y")
- val normalized = args.requireBoolean("normalized") ?: true
- if (normalized && x != null && y != null) {
- val (w, h) = ScreenPerception.getScreenDimensions()
- val pixelCoords = ScreenPerception.normalizeToPixel(x, y, w, h)
- x = pixelCoords.first
- y = pixelCoords.second
+ "read_image" -> fileTool.readFile(args.requireString("path") ?: return missing("path"))
+ "glob" -> globTool.glob(
+ path = args.requireString("path") ?: return missing("path"),
+ pattern = args.requireString("pattern") ?: return missing("pattern")
+ )
+ "grep" -> grepTool.grep(
+ path = args.requireString("path") ?: return missing("path"),
+ pattern = args.requireString("pattern") ?: return missing("pattern"),
+ include = args.requireString("include")
+ )
+ // ---- Tier 3 ----
+ "read_screen" -> accessibilityTool.readScreen()
+ "read_screen_raw" -> accessibilityTool.readScreenRaw()
+ "tap" -> {
+ var x = args.requireInt("x")
+ var y = args.requireInt("y")
+ val normalized = args.requireBoolean("normalized") ?: true
+ if (normalized && x != null && y != null) {
+ val (w, h) = ScreenPerception.getScreenDimensions()
+ val (nx, ny) = ScreenPerception.normalizeToPixel(x, y, w, h)
+ x = nx
+ y = ny
+ }
+ accessibilityTool.tap(text = args.requireString("text"), x = x, y = y)
}
- accessibilityTool.longPress(
- text = args.requireString("text"),
- x = x,
- y = y
+ "swipe" -> accessibilityTool.swipe(
+ direction = args.requireString("direction"),
+ x1 = args.requireInt("x1"),
+ y1 = args.requireInt("y1"),
+ x2 = args.requireInt("x2"),
+ y2 = args.requireInt("y2"),
+ normalized = args.requireBoolean("normalized") ?: true,
+ index = args.requireInt("index")
)
- }
- "long_press_index" -> {
- val index = args.requireInt("index") ?: return missing("index")
- accessibilityTool.longPressByIndex(index)
- }
- "press_key" -> {
- val key = args.requireString("key") ?: return missing("key")
- accessibilityTool.pressKey(key)
- }
- "navigate_app" -> {
- val handler = onNavigateApp
- if (handler == null) {
- ToolResult.error("App navigation is not configured.")
- } else {
- val task = args.requireString("task") ?: return missing("task")
- handler(task)
+ "tap_index" -> {
+ val index = args.requireInt("index") ?: return missing("index")
+ accessibilityTool.tapByIndex(index)
}
- }
- "input_text" -> accessibilityTool.inputText(
- text = args.requireString("text") ?: return missing("text"),
- index = args.requireInt("index")
- )
- "global_action" -> accessibilityTool.globalAction(args.requireString("action") ?: return missing("action"))
- "read_notifications" -> notificationTool.readNotifications(args.requireInt("limit") ?: 15)
- "dismiss_notifications" -> notificationTool.dismissNotifications(args.requireString("key"))
- "media_control" -> notificationTool.mediaControl(args.requireString("action") ?: return missing("action"))
- "show_overlay" -> overlayTool.showOverlay(
- text = args.requireString("text") ?: return missing("text"),
- durationMs = args.requireInt("duration_ms") ?: 4000
- )
- "hide_overlay" -> overlayTool.hideOverlay()
- "lock_screen" -> deviceAdminTool.lockScreen()
- "disable_camera" -> deviceAdminTool.disableCamera(
- args["disabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("disabled")
- )
- "set_password_policy" -> deviceAdminTool.setPasswordPolicy(
- args.requireInt("min_length") ?: return missing("min_length")
- )
- "set_firewall" -> vpnTool.setFirewall(
- args["enabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("enabled")
- )
- "get_firewall_status" -> vpnTool.getFirewallStatus()
- // ---- Tier 4 ----
- "check_root" -> rootTool.checkRoot()
- "run_root_command" -> rootTool.runRootCommand(args.requireString("command") ?: return missing("command"))
- "write_secure_settings" -> rootTool.writeSecureSetting(
- namespace = args.requireString("namespace") ?: return missing("namespace"),
- key = args.requireString("key") ?: return missing("key"),
- value = args.requireString("value") ?: return missing("value")
- )
- else -> ToolResult.error("Tool '$name' has no executor.")
+ "long_press" -> {
+ var x = args.requireInt("x")
+ var y = args.requireInt("y")
+ val normalized = args.requireBoolean("normalized") ?: true
+ if (normalized && x != null && y != null) {
+ val (w, h) = ScreenPerception.getScreenDimensions()
+ val pixelCoords = ScreenPerception.normalizeToPixel(x, y, w, h)
+ x = pixelCoords.first
+ y = pixelCoords.second
+ }
+ accessibilityTool.longPress(
+ text = args.requireString("text"),
+ x = x,
+ y = y
+ )
+ }
+ "long_press_index" -> {
+ val index = args.requireInt("index") ?: return missing("index")
+ accessibilityTool.longPressByIndex(index)
+ }
+ "press_key" -> {
+ val key = args.requireString("key") ?: return missing("key")
+ accessibilityTool.pressKey(key)
+ }
+ "navigate_app" -> {
+ val handler = onNavigateApp
+ if (handler == null) {
+ ToolResult.error("App navigation is not configured.")
+ } else {
+ val task = args.requireString("task") ?: return missing("task")
+ handler(task)
+ }
+ }
+ "input_text" -> accessibilityTool.inputText(
+ text = args.requireString("text") ?: return missing("text"),
+ index = args.requireInt("index")
+ )
+ "global_action" -> accessibilityTool.globalAction(args.requireString("action") ?: return missing("action"))
+ "read_notifications" -> notificationTool.readNotifications(args.requireInt("limit") ?: 15)
+ "dismiss_notifications" -> notificationTool.dismissNotifications(args.requireString("key"))
+ "media_control" -> notificationTool.mediaControl(args.requireString("action") ?: return missing("action"))
+ "show_overlay" -> overlayTool.showOverlay(
+ text = args.requireString("text") ?: return missing("text"),
+ durationMs = args.requireInt("duration_ms") ?: 4000
+ )
+ "hide_overlay" -> overlayTool.hideOverlay()
+ "lock_screen" -> deviceAdminTool.lockScreen()
+ "disable_camera" -> deviceAdminTool.disableCamera(
+ args["disabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("disabled")
+ )
+ "set_password_policy" -> deviceAdminTool.setPasswordPolicy(
+ args.requireInt("min_length") ?: return missing("min_length")
+ )
+ "set_firewall" -> vpnTool.setFirewall(
+ args["enabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("enabled")
+ )
+ "get_firewall_status" -> vpnTool.getFirewallStatus()
+ // ---- Tier 4 ----
+ "check_root" -> rootTool.checkRoot()
+ "run_root_command" -> rootTool.runRootCommand(args.requireString("command") ?: return missing("command"))
+ "write_secure_settings" -> rootTool.writeSecureSetting(
+ namespace = args.requireString("namespace") ?: return missing("namespace"),
+ key = args.requireString("key") ?: return missing("key"),
+ value = args.requireString("value") ?: return missing("value")
+ )
+ else -> ToolResult.error("Tool '$name' has no executor.")
}
}
diff --git a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
index 30a106b..6d589b2 100644
--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
@@ -2,8 +2,6 @@ package com.gotcha.tools
import com.gotcha.llm.FunctionDefinition
import com.gotcha.llm.ToolDefinition
-import kotlinx.serialization.json.JsonObject
-import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.add
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
@@ -57,102 +55,180 @@ object ToolRegistry {
/** Trimmed tool definitions for the App Navigator (shorter descriptions = fewer tokens). */
private val navigatorDefinitions: Map<String, ToolDefinition> = mapOf(
- "tap" to ToolDefinition(function = FunctionDefinition("tap",
- "Tap at coordinates. Use normalized=true and x,y in [0,1000] space.",
- buildJsonObject {
- put("type", "object")
- putJsonObject("properties") {
- putJsonObject("x") { put("type", "integer"); put("description", "X in [0,1000]") }
- putJsonObject("y") { put("type", "integer"); put("description", "Y in [0,1000]") }
- putJsonObject("normalized") { put("type", "boolean"); put("description", "Default true") }
- putJsonObject("text") { put("type", "string"); put("description", "Element text to match") }
+ "tap" to ToolDefinition(
+ function = FunctionDefinition(
+ "tap",
+ "Tap at coordinates. Use normalized=true and x,y in [0,1000] space.",
+ buildJsonObject {
+ put("type", "object")
+ putJsonObject("properties") {
+ putJsonObject("x") {
+ put("type", "integer")
+ put("description", "X in [0,1000]")
+ }
+ putJsonObject("y") {
+ put("type", "integer")
+ put("description", "Y in [0,1000]")
+ }
+ putJsonObject("normalized") {
+ put("type", "boolean")
+ put("description", "Default true")
+ }
+ putJsonObject("text") {
+ put("type", "string")
+ put("description", "Element text to match")
+ }
+ }
}
- }
- )),
- "tap_index" to ToolDefinition(function = FunctionDefinition("tap_index",
- "Tap a UI element by its index from the UI Elements list.",
- buildJsonObject {
- put("type", "object")
- putJsonObject("properties") {
- putJsonObject("index") { put("type", "integer"); put("description", "Element index") }
+ )
+ ),
+ "tap_index" to ToolDefinition(
+ function = FunctionDefinition(
+ "tap_index",
+ "Tap a UI element by its index from the UI Elements list.",
+ buildJsonObject {
+ put("type", "object")
+ putJsonObject("properties") {
+ putJsonObject("index") {
+ put("type", "integer")
+ put("description", "Element index")
+ }
+ }
+ putJsonArray("required") { add("index") }
}
- putJsonArray("required") { add("index") }
- }
- )),
- "long_press" to ToolDefinition(function = FunctionDefinition("long_press",
- "Long press at coordinates. Use normalized=true and x,y in [0,1000] space.",
- buildJsonObject {
- put("type", "object")
- putJsonObject("properties") {
- putJsonObject("x") { put("type", "integer"); put("description", "X in [0,1000]") }
- putJsonObject("y") { put("type", "integer"); put("description", "Y in [0,1000]") }
- putJsonObject("normalized") { put("type", "boolean"); put("description", "Default true") }
- putJsonObject("text") { put("type", "string"); put("description", "Element text to match") }
+ )
+ ),
+ "long_press" to ToolDefinition(
+ function = FunctionDefinition(
+ "long_press",
+ "Long press at coordinates. Use normalized=true and x,y in [0,1000] space.",
+ buildJsonObject {
+ put("type", "object")
+ putJsonObject("properties") {
+ putJsonObject("x") {
+ put("type", "integer")
+ put("description", "X in [0,1000]")
+ }
+ putJsonObject("y") {
+ put("type", "integer")
+ put("description", "Y in [0,1000]")
+ }
+ putJsonObject("normalized") {
+ put("type", "boolean")
+ put("description", "Default true")
+ }
+ putJsonObject("text") {
+ put("type", "string")
+ put("description", "Element text to match")
+ }
+ }
}
- }
- )),
- "long_press_index" to ToolDefinition(function = FunctionDefinition("long_press_index",
- "Long press a UI element by its index from the UI Elements list.",
- buildJsonObject {
- put("type", "object")
- putJsonObject("properties") {
- putJsonObject("index") { put("type", "integer"); put("description", "Element index") }
+ )
+ ),
+ "long_press_index" to ToolDefinition(
+ function = FunctionDefinition(
+ "long_press_index",
+ "Long press a UI element by its index from the UI Elements list.",
+ buildJsonObject {
+ put("type", "object")
+ putJsonObject("properties") {
+ putJsonObject("index") {
+ put("type", "integer")
+ put("description", "Element index")
+ }
+ }
+ putJsonArray("required") { add("index") }
}
- putJsonArray("required") { add("index") }
- }
- )),
- "swipe" to ToolDefinition(function = FunctionDefinition("swipe",
- "Scroll the screen in a direction. 'down' scrolls to see lower content (upward swipe).",
- buildJsonObject {
- put("type", "object")
- putJsonObject("properties") {
- putJsonObject("direction") { put("type", "string"); put("description", "up, down, left, or right") }
- putJsonObject("index") { put("type", "integer"); put("description", "Optional element index to scroll") }
+ )
+ ),
+ "swipe" to ToolDefinition(
+ function = FunctionDefinition(
+ "swipe",
+ "Scroll the screen in a direction. 'down' scrolls to see lower content (upward swipe).",
+ buildJsonObject {
+ put("type", "object")
+ putJsonObject("properties") {
+ putJsonObject("direction") {
+ put("type", "string")
+ put("description", "up, down, left, or right")
+ }
+ putJsonObject("index") {
+ put("type", "integer")
+ put("description", "Optional element index to scroll")
+ }
+ }
+ putJsonArray("required") { add("direction") }
}
- putJsonArray("required") { add("direction") }
- }
- )),
- "input_text" to ToolDefinition(function = FunctionDefinition("input_text",
- "Type text into a field. Provide 'index' to target it directly.",
- buildJsonObject {
- put("type", "object")
- putJsonObject("properties") {
- putJsonObject("text") { put("type", "string"); put("description", "Text to type") }
- putJsonObject("index") { put("type", "integer"); put("description", "Element index") }
+ )
+ ),
+ "input_text" to ToolDefinition(
+ function = FunctionDefinition(
+ "input_text",
+ "Type text into a field. Provide 'index' to target it directly.",
+ buildJsonObject {
+ put("type", "object")
+ putJsonObject("properties") {
+ putJsonObject("text") {
+ put("type", "string")
+ put("description", "Text to type")
+ }
+ putJsonObject("index") {
+ put("type", "integer")
+ put("description", "Element index")
+ }
+ }
+ putJsonArray("required") { add("text") }
}
- putJsonArray("required") { add("text") }
- }
- )),
- "press_key" to ToolDefinition(function = FunctionDefinition("press_key",
- "Press a system key: back, home, enter.",
- buildJsonObject {
- put("type", "object")
- putJsonObject("properties") {
- putJsonObject("key") { put("type", "string"); put("description", "back, home, enter") }
+ )
+ ),
+ "press_key" to ToolDefinition(
+ function = FunctionDefinition(
+ "press_key",
+ "Press a system key: back, home, enter.",
+ buildJsonObject {
+ put("type", "object")
+ putJsonObject("properties") {
+ putJsonObject("key") {
+ put("type", "string")
+ put("description", "back, home, enter")
+ }
+ }
+ putJsonArray("required") { add("key") }
}
- putJsonArray("required") { add("key") }
- }
- )),
- "sleep" to ToolDefinition(function = FunctionDefinition("sleep",
- "Wait for a short time (max 3s).",
- buildJsonObject {
- put("type", "object")
- putJsonObject("properties") {
- putJsonObject("duration_seconds") { put("type", "integer"); put("description", "Seconds (1-3)") }
+ )
+ ),
+ "sleep" to ToolDefinition(
+ function = FunctionDefinition(
+ "sleep",
+ "Wait for a short time (max 3s).",
+ buildJsonObject {
+ put("type", "object")
+ putJsonObject("properties") {
+ putJsonObject("duration_seconds") {
+ put("type", "integer")
+ put("description", "Seconds (1-3)")
+ }
+ }
+ putJsonArray("required") { add("duration_seconds") }
}
- putJsonArray("required") { add("duration_seconds") }
- }
- )),
- "ask_final_answer" to ToolDefinition(function = FunctionDefinition("ask_final_answer",
- "Task complete — provide the final answer summary.",
- buildJsonObject {
- put("type", "object")
- putJsonObject("properties") {
- putJsonObject("answer") { put("type", "string"); put("description", "Final summary") }
+ )
+ ),
+ "ask_final_answer" to ToolDefinition(
+ function = FunctionDefinition(
+ "ask_final_answer",
+ "Task complete — provide the final answer summary.",
+ buildJsonObject {
+ put("type", "object")
+ putJsonObject("properties") {
+ putJsonObject("answer") {
+ put("type", "string")
+ put("description", "Final summary")
+ }
+ }
+ putJsonArray("required") { add("answer") }
}
- putJsonArray("required") { add("answer") }
- }
- ))
+ )
+ )
)
fun allDefinitions(): List<ToolDefinition> = definitions.values.toList()
diff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
index 5502090..7ac51d4 100644
--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
@@ -56,9 +56,9 @@ import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
-import kotlinx.coroutines.delay
import com.gotcha.agent.ChatUiState
import com.gotcha.tools.AgentMode
+import kotlinx.coroutines.delay
import androidx.compose.foundation.Image as ComposeImage
@OptIn(ExperimentalMaterial3Api::class)
diff --git a/app/src/main/java/com/gotcha/ui/MessageBubble.kt b/app/src/main/java/com/gotcha/ui/MessageBubble.kt
index 7aae074..40ecc6b 100644
--- a/app/src/main/java/com/gotcha/ui/MessageBubble.kt
+++ b/app/src/main/java/com/gotcha/ui/MessageBubble.kt
@@ -6,9 +6,9 @@ import android.content.Context
import android.widget.Toast
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
+import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
-import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
diff --git a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
index 3ab7412..25188f9 100644
--- a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
@@ -52,7 +52,12 @@ fun SettingsScreen(
onClearLlmCache: () -> Unit,
onClearDebugScreenshots: () -> Unit,
onBack: () -> Unit,
- onRefreshAudioModels: suspend (Settings) -> Pair<List<AudioModel>, List<AudioModel>> = { Pair(emptyList(), emptyList()) },
+ onRefreshAudioModels: suspend (Settings) -> Pair<List<AudioModel>, List<AudioModel>> = {
+ Pair(
+ emptyList(),
+ emptyList()
+ )
+ },
onRefreshChatModels: suspend (Settings) -> Result<List<String>> = { Result.failure(Exception("Not available")) },
packageName: String = ""
) {
@@ -214,7 +219,11 @@ fun SettingsScreen(
onValueChange = {},
readOnly = true,
label = { Text("Sub-agent model") },
- trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = subAgentModelExpanded) },
+ trailingIcon = {
+ ExposedDropdownMenuDefaults.TrailingIcon(
+ expanded = subAgentModelExpanded
+ )
+ },
modifier = Modifier.fillMaxWidth().menuAnchor()
)
ExposedDropdownMenu(
@@ -251,7 +260,11 @@ fun SettingsScreen(
onValueChange = {},
readOnly = true,
label = { Text("Navigator model") },
- trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = navigatorModelExpanded) },
+ trailingIcon = {
+ ExposedDropdownMenuDefaults.TrailingIcon(
+ expanded = navigatorModelExpanded
+ )
+ },
modifier = Modifier.fillMaxWidth().menuAnchor()
)
ExposedDropdownMenu(