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.

Merge branch 'development' into rishabh-development

Durganshu Mishrab083d79ed42a
diff --cc app/src/main/java/com/gotcha/MainActivity.kt
index b72b668,fbf4a22..127d01f
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@@ -33,14 -29,10 +32,11 @@@ import com.gotcha.audio.AudioMode
import com.gotcha.audio.ModelCategory
import com.gotcha.data.Settings
import com.gotcha.data.SettingsRepository
- import kotlinx.coroutines.Dispatchers
- import kotlinx.coroutines.withContext
import com.gotcha.llm.ChatMessage
import com.gotcha.llm.LLMClient
- import kotlinx.serialization.json.JsonPrimitive
import com.gotcha.service.AssistiveBallService
import com.gotcha.service.GotchaDeviceAdminReceiver
+import com.gotcha.tools.ScreenPerception
import com.gotcha.tools.ToolResult
import com.gotcha.ui.ChatScreen
import com.gotcha.ui.SessionsScreen
diff --cc app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index 854b66d,086d863..ca80d38
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@@ -43,17 -38,14 +41,19 @@@ import kotlinx.coroutines.flow.asShared
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
+ import kotlinx.coroutines.withContext
+ import kotlinx.coroutines.withTimeoutOrNull
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 }
+enum class MessageKind { USER, ASSISTANT, TOOL, ERROR, SUBAGENT }
/** Outcome of the sensitive-action confirmation step. */
private enum class ConfirmDecision { APPROVED, DENIED, TIMED_OUT }
@@@ -105,12 -87,14 +105,14 @@@ data class ChatUiState
val sttModels: List<AudioModel> = emptyList()
)
+ // Central agent orchestrator: session state, tool loop, TTS/STT, and confirmations all
+ // funnel through here. Splitting it is tracked in AGENTS.md ("what's missing").
+ @Suppress("LargeClass", "TooManyFunctions")
class ChatViewModel(application: Application) : AndroidViewModel(application) {
- private val TAG = "Gotcha"
private val settingsRepository = SettingsRepository(application)
private val historyRepository = ChatHistoryRepository(application)
- private val toolExecutor = ToolExecutor(application)
+ private lateinit var toolExecutor: ToolExecutor
private val confirmationOverlay = ConfirmationOverlay(application)
private val json = Json { ignoreUnknownKeys = true }
@@@ -996,50 -899,11 +1049,50 @@@
)
}
+ /**
+ * Handles a tool result prefixed with TASK_RESULT:description:steps|||answer.
+ * Shows a collapsible SUBAGENT bubble with intermediate steps and renders
+ * the final answer with markdown.
+ */
+ private fun handleTaskResult(call: ToolCall, result: ToolResult) {
+ val body = result.message.removePrefix("TASK_RESULT:")
+ val colon = body.indexOf(':')
+ if (colon < 0) return
+ val description = body.substring(0, colon)
+ val payload = body.substring(colon + 1)
+ val marker = "\n|||\n"
+ val splitIdx = payload.indexOf(marker)
+ val steps: List<String>
+ val answer: String
+ if (splitIdx >= 0) {
+ steps = payload.substring(0, splitIdx).split("\n").filter { it.isNotBlank() }
+ answer = payload.substring(splitIdx + marker.length)
+ } else {
+ steps = emptyList()
+ answer = payload
+ }
+ // Show as a collapsible SUBAGENT bubble in the UI
+ appendUi(MessageKind.SUBAGENT, answer, subAgentSteps = steps)
+ // Store in LLM history with steps embedded for persistence
+ val stepsBlock = if (steps.isNotEmpty()) {
+ "\n── Steps ──\n" + steps.joinToString("\n") + "\n── Result ──\n"
+ } else ""
+ llmHistory += ChatMessage(
+ role = "tool",
+ content = JsonPrimitive(
+ "SUBAGENT_STEPS:$description" +
+ stepsBlock +
+ answer
+ ),
+ toolCallId = call.id
+ )
+ }
+
private suspend fun executeCall(call: ToolCall): ToolResult {
- _uiState.update { it.copy(activity = "Running: ${call.function.name}…") }
+ _uiState.update { it.copy(activity = "Running: ${call.function.name}…", subAgentRunning = null) }
val args: JsonObject = try {
json.decodeFromString(JsonObject.serializer(), call.function.arguments.ifBlank { "{}" })
- } catch (e: Exception) {
+ } catch (_: Exception) {
return ToolResult.error("Malformed tool arguments: ${call.function.arguments.take(200)}")
}
return toolExecutor.execute(call.function.name, args, _uiState.value.activeAgent)
@@@ -1092,36 -944,25 +1145,36 @@@
val core = when (agent) {
AgentMode.MONITOR ->
"You are Monitor, a read-only AI assistant running on the user's Android phone. " +
- "You can inspect, read, and query the device, but you CANNOT create, modify, or " +
- "delete anything. 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. Use the sleep tool to pause and wait " +
- "between operations. Keep replies short and conversational."
+ "You can inspect, read, and query the device, but you CANNOT create, modify, or " +
+ "delete anything. 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. Use the sleep tool to pause and wait " +
+ "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). " +
- "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 ->
diff --cc app/src/main/java/com/gotcha/llm/LLMClient.kt
index 12095fc,5dbdce6..51e1ff9
--- a/app/src/main/java/com/gotcha/llm/LLMClient.kt
+++ b/app/src/main/java/com/gotcha/llm/LLMClient.kt
@@@ -80,12 -76,11 +76,12 @@@ class LLMClient
promptCacheKey = sessionId
)
- val response = apiService.chat(request, sessionId)
+ var response = apiService.chat(request, sessionId)
+ response = normalizeResponse(response)
- val shouldCache = (temperature == null || temperature == 0f)
- && response.choices.isNotEmpty()
- && response.choices.none { it.message.toolCalls?.isNotEmpty() == true }
+ val shouldCache = (temperature == null || temperature == 0f) &&
+ response.choices.isNotEmpty() &&
+ response.choices.none { it.message.toolCalls?.isNotEmpty() == true }
if (shouldCache) {
cache.put(cacheKey, response)
diff --cc app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
index a4458b6,44e754e..65fe5f7
--- a/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
+++ b/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
@@@ -28,26 -25,22 +28,32 @@@ class AccessibilityTool(private val con
}
}
+ /** Read screen text AND flag for full-resolution screenshot capture. */
+ fun readScreenRaw(): ToolResult {
+ 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" }
+ return ToolResult.ok("read_screen_raw:$text")
+ }
+
/** Tap either an on-screen element matching [text], or absolute coordinates. */
fun tap(text: String?, x: Int?, y: Int?): ToolResult {
- val service = requireService() ?: return notEnabled()
+ val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()
return when {
!text.isNullOrBlank() ->
- if (service.tapByText(text)) ToolResult.ok("Tapped an element matching \"$text\".")
- else ToolResult.error("Found no clickable element matching \"$text\" on screen.")
+ if (service.tapByText(text)) {
+ ToolResult.ok("Tapped an element matching \"$text\".")
+ } else {
+ ToolResult.error("Found no clickable element matching \"$text\" on screen.")
+ }
x != null && y != null ->
- if (service.tapAt(x.toFloat(), y.toFloat())) ToolResult.ok("Tapped at ($x, $y).")
- else ToolResult.error("Could not dispatch the tap gesture.")
+ if (service.tapAt(x.toFloat(), y.toFloat())) {
+ ToolResult.ok("Tapped at ($x, $y).")
+ } else {
+ ToolResult.error("Could not dispatch the tap gesture.")
+ }
else -> ToolResult.error("Provide either 'text' to match, or both 'x' and 'y' coordinates.")
}
}
diff --cc app/src/main/java/com/gotcha/tools/ToolExecutor.kt
index 82f1108,c08c180..799d969
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@@ -19,13 -19,12 +19,16 @@@ import kotlinx.serialization.json.jsonP
* preconditions (executors return permission errors instead of crashing),
* and records every execution in the [ActionLog].
*/
-class ToolExecutor(context: Context) {
+class ToolExecutor(
+ context: Context,
+ val onTask: (suspend (description: String, prompt: String) -> ToolResult)? = null,
+ val onNavigateApp: (suspend (task: String) -> ToolResult)? = null
+) {
- private val TAG = "Gotcha"
+ private companion object {
+ const val TAG = "Gotcha"
+ }
+
private val appContext = context.applicationContext
private val phoneTool = PhoneTool(appContext)
private val systemTool = SystemTool(appContext)
@@@ -67,17 -68,12 +72,17 @@@
if (!ToolRegistry.contains(name)) {
return ToolResult.error("Unknown tool '$name'. Only the fixed tool catalog is available.")
}
- if (!ToolRegistry.isAllowedForAgent(name, agent)) {
+ if (!isSubAgent && !ToolRegistry.isAllowedForAgent(name, agent)) {
return ToolResult.error(
"This action is not available in ${agent.name} mode. " +
- "Switch to Operator mode if you need to perform this action."
+ "Switch to Operator mode if you need to perform this action."
)
}
+ if (isSubAgent && !ToolRegistry.isAllowedForSubAgent(name)) {
+ return ToolResult.error(
+ "Tool '$name' is not available to sub-agents (no recursive delegation)."
+ )
+ }
val result = try {
withContext(Dispatchers.IO) { dispatch(name, args) }
} catch (e: CancellationException) {
@@@ -115,324 -114,269 +123,327 @@@
return withContext(Dispatchers.IO) { calendarTool.doDeleteEvent(eventId) }
}
+ // Single when-dispatch over the entire fixed tool catalog; size and branch count are
+ // inherent to the design (see AGENTS.md).
+ @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")
- )
- "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.")
+ "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)
}
- "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()
- "tap" -> accessibilityTool.tap(
+ }
+ "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.")
+ }
+ "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)
+ }
+ "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
+ }
+ accessibilityTool.longPress(
text = args.requireString("text"),
- x = args.requireInt("x"),
- y = args.requireInt("y")
- )
- "swipe" -> accessibilityTool.swipe(
- direction = args.requireString("direction"),
- x1 = args.requireInt("x1"),
- y1 = args.requireInt("y1"),
- x2 = args.requireInt("x2"),
- y2 = args.requireInt("y2")
- )
- "input_text" -> accessibilityTool.inputText(args.requireString("text") ?: return missing("text"))
- "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")
+ x = x,
+ y = y
)
- else -> ToolResult.error("Tool '$name' has no executor.")
+ }
+ "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 --cc app/src/main/java/com/gotcha/ui/ChatScreen.kt
index 4a811a8,585c783..5502090
--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
@@@ -3,9 -3,6 +3,7 @@@ package com.gotcha.u
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
- import androidx.compose.foundation.Image as ComposeImage
+import androidx.compose.foundation.background
- import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
@@@ -57,12 -52,10 +54,12 @@@ import androidx.compose.ui.draw.cli
import androidx.compose.ui.graphics.Color
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.agent.PendingQuestion
import com.gotcha.tools.AgentMode
+ import androidx.compose.foundation.Image as ComposeImage
@OptIn(ExperimentalMaterial3Api::class)
@Composable
diff --cc app/src/main/java/com/gotcha/ui/MessageBubble.kt
index 3a04927,246de1a..7aae074
--- a/app/src/main/java/com/gotcha/ui/MessageBubble.kt
+++ b/app/src/main/java/com/gotcha/ui/MessageBubble.kt
@@@ -17,18 -15,12 +17,16 @@@ import androidx.compose.foundation.layo
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
- import com.halilibo.richtext.markdown.Markdown
- import com.halilibo.richtext.ui.material3.Material3RichText
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.rounded.VolumeUp
+import androidx.compose.material.icons.filled.ExpandLess
+import androidx.compose.material.icons.filled.ExpandMore
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
+import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
@@@ -46,10 -36,10 +44,12 @@@ import androidx.compose.ui.graphics.Col
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
+ import com.halilibo.richtext.markdown.Markdown
+ import com.halilibo.richtext.ui.material3.Material3RichText
import com.gotcha.agent.MessageKind
import com.gotcha.agent.UiMessage
@@@ -100,14 -84,17 +100,17 @@@ fun MessageBubble
modifier = Modifier
.widthIn(max = 320.dp)
.then(
- if (isTool || isSubAgent) Modifier.combinedClickable(
- onClick = { if (isTool) expanded.value = !expanded.value },
- onLongClick = { showMenu = true }
- )
- else Modifier.combinedClickable(
- onClick = { },
- onLongClick = { showMenu = true }
- )
- if (isTool) {
++ if (isTool || isSubAgent) {
+ Modifier.combinedClickable(
- onClick = { expanded.value = !expanded.value },
++ onClick = { if (isTool) expanded.value = !expanded.value },
+ onLongClick = { showMenu = true }
+ )
+ } else {
+ Modifier.combinedClickable(
+ onClick = { },
+ onLongClick = { showMenu = true }
+ )
+ }
)
.padding(16.dp)
) {