Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
feat: implement sub-agent infrastructure with restricted tool access and model listing support
Rishabh Bajpai500a62e7a961
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.ktindex 53faef7..e832a16 100644--- a/app/src/main/java/com/gotcha/MainActivity.kt+++ b/app/src/main/java/com/gotcha/MainActivity.kt@@ -276,6 +276,18 @@ class MainActivity : ComponentActivity() {Pair(ttsModels, sttModels)}},+ onRefreshChatModels = { s ->+ withContext(Dispatchers.IO) {+ val client = LLMClient(+ apiKey = s.apiKey,+ baseUrl = s.baseUrl,+ model = s.model,+ context = this@MainActivity,+ apiTimeoutSeconds = s.apiTimeoutSeconds+ )+ client.listModels()+ }+ },packageName = packageName)}diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.ktindex 3e3d01f..1562775 100644--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt@@ -21,6 +21,7 @@ import com.gotcha.llm.ToolCallimport com.gotcha.llm.visionUserMessageimport com.gotcha.tools.AgentModeimport com.gotcha.tools.FileResolver+import com.gotcha.tools.SubAgentSessionimport com.gotcha.tools.ToolExecutorimport com.gotcha.tools.ToolRegistryimport com.gotcha.tools.ToolResult@@ -47,7 +48,7 @@ import kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.putimport 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 }@@ -76,6 +77,7 @@ data class ChatUiState(val messages: List<UiMessage> = emptyList(),val isBusy: Boolean = false,val activity: String? = null, // e.g. "Running: set_brightness…"+ val subAgentRunning: String? = null, // description while sub-agent is activeval pendingConfirmation: PendingConfirmation? = null,val pendingQuestion: PendingQuestion? = null,val isConfigured: Boolean = false,@@ -83,8 +85,8 @@ data class ChatUiState(val activeAgent: AgentMode = AgentMode.OPERATOR,val contextUsagePercent: Float = 0f,// TTS / STT state- val isListening: Boolean = false, // Android STT active- val isRecording: Boolean = false, // API STT recording+ val isListening: Boolean = false,+ val isRecording: Boolean = false,val ttsModels: List<AudioModel> = emptyList(),val sttModels: List<AudioModel> = emptyList())@@ -94,7 +96,7 @@ 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: ToolExecutorprivate val confirmationOverlay = ConfirmationOverlay(application)private val json = Json { ignoreUnknownKeys = true }@@ -134,6 +136,23 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {val permissionRequests: SharedFlow<String> = _permissionRequests.asSharedFlow()init {+ toolExecutor = ToolExecutor(application) { description, prompt ->+ _uiState.update { it.copy(subAgentRunning = description) }+ val subSession = SubAgentSession(+ appContext = getApplication(),+ toolExecutor = toolExecutor,+ settings = settings,+ description = description,+ prompt = prompt+ )+ val result = subSession.run()+ _uiState.update { it.copy(subAgentRunning = null) }+ if (result.startsWith("Task failed") || result.startsWith("Task exceeded")) {+ ToolResult.error(result)+ } else {+ ToolResult.ok("TASK_RESULT:$description:$result")+ }+ }refreshSettings()viewModelScope.launch {val sessions = historyRepository.listSessions()@@ -177,6 +196,19 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {_uiState.update { it.copy(isConfigured = settings.isConfigured) }}+ suspend fun refreshChatModels(): Result<List<String>> {+ val cfg = settings+ if (!cfg.isConfigured) return Result.failure(Exception("API not configured"))+ val client = LLMClient(+ apiKey = cfg.apiKey,+ baseUrl = cfg.baseUrl,+ model = cfg.model,+ context = getApplication(),+ apiTimeoutSeconds = cfg.apiTimeoutSeconds+ )+ return client.listModels()+ }+fun sendMessage(text: String, imageBase64: String? = null) {val trimmed = text.trim()if (trimmed.isEmpty() && imageBase64 == null) return@@ -201,7 +233,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {} finally {withContext(NonCancellable) {saveCurrentSession()- _uiState.update { it.copy(isBusy = false, activity = null) }+ _uiState.update { it.copy(isBusy = false, activity = null, subAgentRunning = null) }agentJob = null}}@@ -573,6 +605,8 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {handleBinaryResult(call, result)} else if (result.success && result.message.startsWith("QUESTION:")) {handleQuestionResult(call, result)+ } else if (result.success && result.message.startsWith("TASK_RESULT:")) {+ handleTaskResult(call, result)} else if (result.success && result.message.startsWith("CONFIRM_UNINSTALL:")) {handleUninstallConfirm(call, result)} else if (result.success && result.message.startsWith("CONFIRM_DELETE_ALARM:")) {@@ -847,8 +881,29 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {)}+ /**+ * Handles a tool result prefixed with TASK_RESULT:description:result.+ * Shows the result as a SUBAGENT message bubble and stores a clean+ * tool result in the LLM history.+ */+ 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 answer = body.substring(colon + 1)+ // Show as a styled SUBAGENT bubble in the UI+ appendUi(MessageKind.SUBAGENT, "$description\n\n$answer")+ // Store clean text in LLM history+ llmHistory += ChatMessage(+ role = "tool",+ content = JsonPrimitive("Task \"$description\" completed. Result:\n$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) {diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.ktindex 0d2dd06..13df17f 100644--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt@@ -10,6 +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 agentval maxToolRounds: Int = 30,val maxContextTokens: Int = 40000,val apiTimeoutSeconds: Long = 0L,@@ -52,6 +53,7 @@ class SettingsRepository(context: Context) {baseUrl = prefs.getString(KEY_BASE_URL, Settings.DEFAULT_BASE_URL)?: Settings.DEFAULT_BASE_URL,model = prefs.getString(KEY_MODEL, Settings.DEFAULT_MODEL) ?: Settings.DEFAULT_MODEL,+ subAgentModel = prefs.getString(KEY_SUB_AGENT_MODEL, "") ?: "",maxToolRounds = prefs.getInt(KEY_MAX_TOOL_ROUNDS, 30),maxContextTokens = prefs.getInt(KEY_MAX_CONTEXT_TOKENS, 40000),apiTimeoutSeconds = prefs.getLong(KEY_API_TIMEOUT, 0L),@@ -70,6 +72,7 @@ class SettingsRepository(context: Context) {.putString(KEY_API_KEY, settings.apiKey).putString(KEY_BASE_URL, settings.baseUrl).putString(KEY_MODEL, settings.model)+ .putString(KEY_SUB_AGENT_MODEL, settings.subAgentModel).putInt(KEY_MAX_TOOL_ROUNDS, settings.maxToolRounds).putInt(KEY_MAX_CONTEXT_TOKENS, settings.maxContextTokens).putLong(KEY_API_TIMEOUT, settings.apiTimeoutSeconds)@@ -88,6 +91,7 @@ class SettingsRepository(context: Context) {const val KEY_API_KEY = "api_key"const val KEY_BASE_URL = "base_url"const val KEY_MODEL = "model"+ const val KEY_SUB_AGENT_MODEL = "sub_agent_model"const val KEY_MAX_TOOL_ROUNDS = "max_tool_rounds"const val KEY_MAX_CONTEXT_TOKENS = "max_context_tokens"const val KEY_API_TIMEOUT = "api_timeout"diff --git a/app/src/main/java/com/gotcha/llm/ApiService.kt b/app/src/main/java/com/gotcha/llm/ApiService.ktindex b60b8a6..3134cf5 100644--- a/app/src/main/java/com/gotcha/llm/ApiService.kt+++ b/app/src/main/java/com/gotcha/llm/ApiService.kt@@ -8,7 +8,9 @@ interface ApiService {@POST("chat/completions")suspend fun chat(@Body request: ChatRequest,- // Passed per-request; Retrofit omits the header entirely when null.@Header("X-Session-Id") sessionId: String? = null): ChatResponse++ @retrofit2.http.GET("models")+ suspend fun listModels(): ModelListResponse}diff --git a/app/src/main/java/com/gotcha/llm/LLMClient.kt b/app/src/main/java/com/gotcha/llm/LLMClient.ktindex 7520518..fa95c68 100644--- a/app/src/main/java/com/gotcha/llm/LLMClient.kt+++ b/app/src/main/java/com/gotcha/llm/LLMClient.kt@@ -97,6 +97,11 @@ class LLMClient(cache.clear()}+ suspend fun listModels(): Result<List<String>> = runCatching {+ val response = apiService.listModels()+ response.data.map { it.id }.sorted()+ }+private fun buildCacheKey(model: String,messages: List<ChatMessage>,diff --git a/app/src/main/java/com/gotcha/llm/Models.kt b/app/src/main/java/com/gotcha/llm/Models.ktindex 9636865..d1f65b9 100644--- a/app/src/main/java/com/gotcha/llm/Models.kt+++ b/app/src/main/java/com/gotcha/llm/Models.kt@@ -120,3 +120,18 @@ data class Choice(@SerialName("finish_reason")val finishReason: String? = null)++/** Response from GET /v1/models (OpenAI-compatible). */+@Serializable+data class ModelListResponse(+ val data: List<ModelInfo>+)++@Serializable+data class ModelInfo(+ val id: String,+ @SerialName("object")+ val objectType: String = "model",+ @SerialName("owned_by")+ val ownedBy: String = ""+)diff --git a/app/src/main/java/com/gotcha/tools/AgentDefinition.kt b/app/src/main/java/com/gotcha/tools/AgentDefinition.ktnew file mode 100644index 0000000..46ccdf6--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/AgentDefinition.kt@@ -0,0 +1,17 @@+package com.gotcha.tools++data class AgentDefinition(+ val name: String,+ val description: String,+ val isSubagent: Boolean+) {+ companion object {+ val GENERAL = AgentDefinition(+ name = "GENERAL",+ description = "General-purpose agent for multi-step tasks. " ++ "Delegates complex work so the main agent stays responsive. " ++ "Runs all Operator tools and returns a final summary.",+ isSubagent = true+ )+ }+}diff --git a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt b/app/src/main/java/com/gotcha/tools/SubAgentSession.ktnew file mode 100644index 0000000..52493b1--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/SubAgentSession.kt@@ -0,0 +1,158 @@+package com.gotcha.tools++import android.content.Context+import android.util.Log+import com.gotcha.data.Settings+import com.gotcha.llm.ChatMessage+import com.gotcha.llm.LLMClient+import kotlinx.coroutines.CancellationException+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.jsonPrimitive++/**+ * Runs an independent LLM tool loop for a delegated sub-agent task.+ * Intermediate tool calls and results stay internal — only the final+ * answer (from [ask_final_answer] or a text-only response) is returned.+ */+class SubAgentSession(+ private val appContext: Context,+ private val toolExecutor: ToolExecutor,+ private val settings: Settings,+ private val description: String,+ private val prompt: String+) {+ private val TAG = "SubAgentSession"+ private val json = Json { ignoreUnknownKeys = true }++ /** Sub-agent session token tracking for model-appropriate trim. */+ private var activeTokenCount = 0++ suspend fun run(): String {+ val model = settings.subAgentModel.ifBlank { settings.model }+ Log.d(TAG, "Starting sub-agent with model=$model: $description")++ val subLlm = LLMClient(+ apiKey = settings.apiKey,+ baseUrl = settings.baseUrl,+ model = model,+ context = appContext,+ 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. " ++ "Keep intermediate tool calls focused; only the final answer will be delivered."+ )+ )++ val userMsg = ChatMessage(+ role = "user",+ content = JsonPrimitive(prompt)+ )++ val history = mutableListOf(systemMsg, userMsg)+ activeTokenCount = (systemMsg.textContent.length + userMsg.textContent.length) / 4++ val maxRounds = settings.maxToolRounds+ val subAgentTools = ToolRegistry.toolsForSubAgent()++ for (round in 0 until maxRounds) {+ Log.d(TAG, "Sub-agent round ${round + 1}/$maxRounds")++ val response = try {+ subLlm.chat(history.toList(), subAgentTools)+ } catch (e: CancellationException) {+ throw e+ } catch (e: Exception) {+ Log.e(TAG, "Sub-agent LLM call failed: ${e.message}")+ return "Task failed: ${e.message}"+ }++ response.usage?.totalTokens?.let { activeTokenCount = it }++ val message = response.choices.firstOrNull()?.message+ if (message == null) {+ return "Task failed: empty response from model"+ }++ val toolCalls = message.toolCalls.orEmpty()++ if (toolCalls.isEmpty()) {+ history.add(message)+ val text = message.textContent.ifEmpty { "(no output)" }+ Log.d(TAG, "Sub-agent finished (text response): ${text.take(100)}")+ return text+ }++ history.add(message)++ val finalCall = toolCalls.firstOrNull { it.function.name == "ask_final_answer" }+ if (finalCall != null) {+ val answer = try {+ val args = json.decodeFromString<JsonObject>(finalCall.function.arguments)+ args["answer"]?.jsonPrimitive?.content ?: "(no answer provided)"+ } catch (e: Exception) {+ "(failed to parse ask_final_answer arguments: ${e.message})"+ }+ Log.d(TAG, "Sub-agent finished (ask_final_answer): ${answer.take(100)}")+ return answer+ }++ for (call in toolCalls) {+ val args = try {+ json.decodeFromString<JsonObject>(call.function.arguments.ifBlank { "{}" })+ } catch (e: Exception) {+ history.add(+ ChatMessage(+ role = "tool",+ content = JsonPrimitive("Malformed arguments: ${call.function.arguments.take(200)}"),+ toolCallId = call.id+ )+ )+ continue+ }++ val result = try {+ toolExecutor.execute(call.function.name, args, AgentMode.OPERATOR, isSubAgent = true)+ } catch (e: CancellationException) {+ throw e+ } catch (e: Exception) {+ ToolResult.error("Tool '${call.function.name}' failed: ${e.message}")+ }++ history.add(+ ChatMessage(+ role = "tool",+ content = JsonPrimitive(result.message),+ toolCallId = call.id+ )+ )+ }++ // Compact history if it exceeds 80% of context limit+ if (activeTokenCount > settings.maxContextTokens * 0.8) {+ trimHistory(history)+ }+ }++ return "Task exceeded $maxRounds tool rounds without producing a final answer."+ }++ private fun trimHistory(history: MutableList<ChatMessage>) {+ // Keep system prompt + last ~10 messages+ val sysPrompt = history.firstOrNull { it.role == "system" }+ history.clear()+ if (sysPrompt != null) history.add(sysPrompt)+ activeTokenCount = history.sumOf { it.textContent.length / 4 }+ }+}diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.ktindex 5c67d02..b5e4e08 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -1067,6 +1067,56 @@ object ToolDefinitions {})+ val task = tool(+ "task",+ "Delegate a multi-step task to a sub-agent. The sub-agent runs independently " ++ "with full access to all Operator tools and returns a final report. " ++ "Use this when the work involves many steps whose intermediate details are " ++ "not important to you — only the final result matters. " ++ "Available sub-agents: GENERAL — a general-purpose agent that can perform " ++ "any multi-step operation using all available device tools. " ++ "Cannot be called from within a sub-agent (no recursive delegation). " ++ "Only available to Operator mode.",+ schema {+ 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).")+ }+ putJsonObject("prompt") {+ put("type", "string")+ 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.")+ }+ }+ putJsonArray("required") { add("description"); add("prompt") }+ }+ )++ val ask_final_answer = tool(+ "ask_final_answer",+ "Signal that the delegated task is complete and provide the final result. " ++ "Only available to General sub-agent. " ++ "Call this once all required steps have been executed and you have the " ++ "complete answer to report back. " ++ "Do NOT call this before the work is actually done.",+ schema {+ putJsonObject("properties") {+ putJsonObject("answer") {+ put("type", "string")+ put("description", "The complete final result to report back.")+ }+ }+ putJsonArray("required") { add("answer") }+ }+ )+val glob = tool("glob","Find files matching a glob pattern within an allowed directory. " +@@ -1451,6 +1501,9 @@ object ToolDefinitions {question,// Sleep / delay utility (available to both agents)sleep,+ // Sub-agent delegation (Operator only)+ task,+ ask_final_answer,// Task trackingtodowrite,// Surgical file editing (Operator only)diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.ktindex 1e17587..5a7c4d9 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -19,7 +19,10 @@ import kotlinx.serialization.json.jsonPrimitive* 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+) {private val TAG = "Gotcha"private val appContext = context.applicationContext@@ -59,16 +62,21 @@ class ToolExecutor(context: Context) {* 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): 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.")}- 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.")}+ 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) {@@ -301,6 +309,19 @@ class ToolExecutor(context: Context) {"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)+ }+ }"sleep" -> {val secs = args.requireInt("duration_seconds")?.coerceIn(1, 86400)?: return missing("duration_seconds")diff --git a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt b/app/src/main/java/com/gotcha/tools/ToolRegistry.ktindex d4ad1ab..f95283d 100644--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt@@ -2,33 +2,15 @@ package com.gotcha.toolsimport com.gotcha.llm.ToolDefinition-/**- * Agent mode the user can switch between mid-conversation (PRD §6).- * Monitor = read-only observer; Operator = full permissions.- */enum class AgentMode { MONITOR, OPERATOR }-/**- * Fixed, code-defined tool catalog. The LLM can never add tools at runtime- * (PRD §11.2 #1) — only this registry decides what is exposed.- */object ToolRegistry {private val definitions: Map<String, ToolDefinition> =ToolDefinitions.all.associateBy { it.function.name }- /**- * Sensitive-action confirmation is removed. Permissions are pre-configured- * in Settings → Permissions. Only destructive tools (see [destructiveTools])- * require a dedicated user confirmation dialog.- */val sensitiveTools: Set<String> = emptySet()- /**- * Destructive tools that require explicit, separate user confirmation even when- * sensitive-action confirmation is enabled. Each call presents a dedicated dialog- * to the user before the tool is actually executed.- */val destructiveTools: Set<String> = setOf("uninstall_app","delete_calendar_event",@@ -36,43 +18,27 @@ object ToolRegistry {"delete_timer")- /**- * Tools available to Monitor mode — read-only / informational only.- * The Monitor can inspect, list, read, and query, but cannot create,- * modify, or delete anything. `dial_number` and `open_app` are allowed- * because they are intent hand-offs (user presses call / system launches app).- */val monitorTools: Set<String> = setOf(- // Phone & communications (read-only + intent hand-offs)"dial_number", "read_call_log", "find_contact", "read_recent_sms",- // Calendar (read-only)"list_calendar_events",- // Info & sensors"get_storage_info", "get_battery_info", "get_location", "get_volume","get_audio_recording_status","get_app_usage", "get_data_usage",- // Apps (read-only + intent)"open_app", "list_installed_apps",- // Files & terminal (read-only)"list_files", "read_file", "grep", "glob",- // Task management"todowrite", "list_alarms", "list_timers",- // User interaction"question","sleep",- // Web"websearch", "webfetch",- // Clipboard (read-only)"get_clipboard",- // Tier 3: read-only accessibility + notifications"read_screen", "read_notifications",- // Tier 3: VpnService status (read-only)"get_firewall_status",- // Tier 4: root check (read-only)"check_root")- /** Operator has access to every tool in the catalog. */+ /** Full Operator tool set minus task (sub-agents cannot delegate further). */+ val subAgentTools: Set<String> = definitions.keys - "task"+private val operatorTools: Set<String> = definitions.keysfun allDefinitions(): List<ToolDefinition> = definitions.values.toList()@@ -85,15 +51,18 @@ object ToolRegistry {fun isDestructive(name: String): Boolean = name in destructiveTools- /** Whether [name] is callable by the given [agent] mode. */fun isAllowedForAgent(name: String, agent: AgentMode): Boolean = when (agent) {AgentMode.MONITOR -> name in monitorToolsAgentMode.OPERATOR -> name in operatorTools}- /** Returns the subset of tool definitions visible to the given [agent]. */+ fun isAllowedForSubAgent(name: String): Boolean = name in subAgentTools+fun toolsForAgent(agent: AgentMode): List<ToolDefinition> = when (agent) {AgentMode.MONITOR -> definitions.filterKeys { it in monitorTools }.values.toList()AgentMode.OPERATOR -> definitions.values.toList()}++ fun toolsForSubAgent(): List<ToolDefinition> =+ definitions.filterKeys { it in subAgentTools }.values.toList()}diff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.ktindex 6568b08..bb2a3d8 100644--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt@@ -144,6 +144,27 @@ fun ChatScreen(}}+ if (state.subAgentRunning != null) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .background(Color(0xFF1A1A2E), RoundedCornerShape(8.dp))+ .padding(horizontal = 16.dp, vertical = 8.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ CircularProgressIndicator(+ modifier = Modifier.width(16.dp),+ color = Color(0xFFE0D4FF)+ )+ Spacer(modifier = Modifier.width(8.dp))+ Text(+ "⚡ ${state.subAgentRunning}",+ style = MaterialTheme.typography.bodySmall,+ color = Color(0xFFE0D4FF)+ )+ }+ }+if (!state.isConfigured) {TextButton(onClick = onOpenSettings,diff --git a/app/src/main/java/com/gotcha/ui/MessageBubble.kt b/app/src/main/java/com/gotcha/ui/MessageBubble.ktindex 5732296..7399400 100644--- a/app/src/main/java/com/gotcha/ui/MessageBubble.kt+++ b/app/src/main/java/com/gotcha/ui/MessageBubble.kt@@ -61,6 +61,12 @@ fun MessageBubble(MessageKind.ASSISTANT -> colors.surfaceVariant to colors.onSurfaceVariantMessageKind.TOOL -> colors.secondaryContainer to colors.onSecondaryContainerMessageKind.ERROR -> colors.errorContainer to colors.onErrorContainer+ MessageKind.SUBAGENT -> {+ // Distinct indigo/purple palette for sub-agent messages+ val bg = androidx.compose.ui.graphics.Color(0xFF1A1A2E)+ val fg = androidx.compose.ui.graphics.Color(0xFFE0D4FF)+ bg to fg+ }}val expanded = remember { mutableStateOf(!isTool) }var showMenu by remember { mutableStateOf(false) }@@ -115,7 +121,15 @@ fun MessageBubble(}}if (message.text.isNotEmpty()) {- val displayText = if (isTool) "🔧 ${message.text}" else message.text+ val displayText = when (message.kind) {+ MessageKind.TOOL -> "🔧 ${message.text}"+ MessageKind.SUBAGENT -> {+ val firstLine = message.text.substringBefore("\n")+ val rest = message.text.substringAfter("\n", "")+ "⚡ General Agent: $firstLine" + if (rest.isNotBlank()) "\n$rest" else ""+ }+ else -> message.text+ }val firstLine = displayText.substringBefore("\n").trimEnd()val hasMore = displayText.contains("\n")@@ -134,7 +148,7 @@ fun MessageBubble()}} else {- if (message.kind == MessageKind.TOOL) {+ if (message.kind == MessageKind.TOOL || message.kind == MessageKind.SUBAGENT) {Text(text = displayText,style = MaterialTheme.typography.bodySmalldiff --git a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt b/app/src/main/java/com/gotcha/ui/SettingsScreen.ktindex 3ed54ae..768f69f 100644--- a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt+++ b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt@@ -52,11 +52,13 @@ fun SettingsScreen(onClearLlmCache: () -> Unit,onBack: () -> Unit,onRefreshAudioModels: suspend (Settings) -> Pair<List<AudioModel>, List<AudioModel>> = { Pair(emptyList(), emptyList()) },+ onRefreshChatModels: suspend (Settings) -> Result<List<String>> = { Result.failure(Exception("Not available")) },packageName: String = "") {var apiKey by remember { mutableStateOf(initial.apiKey) }var baseUrl by remember { mutableStateOf(initial.baseUrl) }var model by remember { mutableStateOf(initial.model) }+ var subAgentModel by remember { mutableStateOf(initial.subAgentModel) }var maxToolRounds by remember { mutableStateOf(initial.maxToolRounds.toString()) }var maxContextTokens by remember { mutableStateOf(initial.maxContextTokens.toString()) }var apiTimeoutSeconds by remember { mutableStateOf(initial.apiTimeoutSeconds.toString()) }@@ -71,10 +73,12 @@ fun SettingsScreen(// Discovered model listsvar availableTtsModels by remember { mutableStateOf<List<AudioModel>>(emptyList()) }var availableSttModels by remember { mutableStateOf<List<AudioModel>>(emptyList()) }+ var availableChatModels by remember { mutableStateOf<List<String>>(emptyList()) }var showKey by remember { mutableStateOf(false) }var status by remember { mutableStateOf<String?>(null) }var testing by remember { mutableStateOf(false) }var refreshingModels by remember { mutableStateOf(false) }+ var refreshingChatModels by remember { mutableStateOf(false) }// Collapsible sectionsvar aiConfigExpanded by remember { mutableStateOf(false) }var speechExpanded by remember { mutableStateOf(false) }@@ -85,11 +89,14 @@ fun SettingsScreen(var sttProviderExpanded by remember { mutableStateOf(false) }var ttsModelExpanded by remember { mutableStateOf(false) }var sttModelExpanded by remember { mutableStateOf(false) }+ var modelExpanded by remember { mutableStateOf(false) }+ var subAgentModelExpanded by remember { mutableStateOf(false) }fun currentSettings() = Settings(apiKey = apiKey.trim(),baseUrl = baseUrl.trim(),model = model.trim(),+ subAgentModel = subAgentModel.trim(),maxToolRounds = maxToolRounds.toIntOrNull()?.takeIf { it > 0 } ?: 30,maxContextTokens = maxContextTokens.toIntOrNull()?.takeIf { it > 0 } ?: 40000,apiTimeoutSeconds = apiTimeoutSeconds.toLongOrNull()?.takeIf { it >= 0 } ?: 0L,@@ -99,7 +106,8 @@ fun SettingsScreen(sttProvider = sttProvider,sttApiBaseUrl = sttApiBaseUrl.trim(),sttApiModel = sttApiModel.trim(),- autoReadReplies = autoReadReplies+ autoReadReplies = autoReadReplies,+ assistiveBallEnabled = initial.assistiveBallEnabled)Scaffold(@@ -147,13 +155,107 @@ fun SettingsScreen(singleLine = true,modifier = Modifier.fillMaxWidth())- OutlinedTextField(- value = model,- onValueChange = { model = it },- label = { Text("Model name") },- singleLine = true,- modifier = Modifier.fillMaxWidth()- )+ ExposedDropdownMenuBox(+ expanded = modelExpanded,+ onExpandedChange = { modelExpanded = it }+ ) {+ OutlinedTextField(+ value = model.ifEmpty { "(select model)" },+ onValueChange = {},+ readOnly = false,+ label = { Text("Main model") },+ trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = modelExpanded) },+ modifier = Modifier.fillMaxWidth().menuAnchor()+ )+ ExposedDropdownMenu(+ expanded = modelExpanded,+ onDismissRequest = { modelExpanded = false }+ ) {+ if (availableChatModels.isEmpty()) {+ DropdownMenuItem(+ text = { Text("No models — refresh below") },+ onClick = { modelExpanded = false }+ )+ } else {+ availableChatModels.forEach { m ->+ DropdownMenuItem(+ text = { Text(m) },+ onClick = {+ model = m+ modelExpanded = false+ }+ )+ }+ }+ // Always allow manual text input+ DropdownMenuItem(+ text = { Text("✏️ Custom model…") },+ onClick = {+ modelExpanded = false+ }+ )+ }+ }+ ExposedDropdownMenuBox(+ expanded = subAgentModelExpanded,+ onExpandedChange = { subAgentModelExpanded = it }+ ) {+ val subLabel = if (subAgentModel.isBlank()) "Same as main agent" else subAgentModel+ OutlinedTextField(+ value = subLabel,+ onValueChange = {},+ readOnly = true,+ label = { Text("Sub-agent model") },+ trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = subAgentModelExpanded) },+ modifier = Modifier.fillMaxWidth().menuAnchor()+ )+ ExposedDropdownMenu(+ expanded = subAgentModelExpanded,+ onDismissRequest = { subAgentModelExpanded = false }+ ) {+ DropdownMenuItem(+ text = { Text("Same as main agent") },+ onClick = {+ subAgentModel = ""+ subAgentModelExpanded = false+ }+ )+ if (availableChatModels.isNotEmpty()) {+ availableChatModels.forEach { m ->+ DropdownMenuItem(+ text = { Text(m) },+ onClick = {+ subAgentModel = m+ subAgentModelExpanded = false+ }+ )+ }+ }+ }+ }+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ OutlinedButton(+ onClick = {+ refreshingChatModels = true+ status = "Refreshing models…"+ scope.launch {+ val result = onRefreshChatModels(currentSettings())+ result.onSuccess { models ->+ availableChatModels = models+ status = "Found ${models.size} models"+ }.onFailure { e ->+ status = "Failed: ${e.message}"+ }+ refreshingChatModels = false+ }+ },+ enabled = !refreshingChatModels,+ modifier = Modifier.weight(1f)+ ) { Text(if (refreshingChatModels) "Refreshing…" else "Refresh models") }+ }OutlinedTextField(value = maxToolRounds,onValueChange = { maxToolRounds = it },