Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

feat: add tools for phone dialing, storage management, system settings, and terminal commands

Durganshu920e2f8f45eb
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 75a1462..a6f7cb2 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -11,6 +11,14 @@
android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="32" />
+ <!-- Needed on API 30+ so open_app can see other launchable apps. -->
+ <queries>
+ <intent>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent>
+ </queries>
+
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index 3d24c0a..d18b3f6 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -1,30 +1,131 @@
package com.gotcha
+import android.content.Intent
+import android.net.Uri
import android.os.Bundle
+import android.provider.Settings as AndroidSettings
+import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.activity.viewModels
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
-import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
+import androidx.lifecycle.lifecycleScope
+import com.gotcha.agent.ChatViewModel
+import com.gotcha.data.Settings
+import com.gotcha.data.SettingsRepository
+import com.gotcha.llm.ChatMessage
+import com.gotcha.llm.LLMClient
+import com.gotcha.tools.ToolResult
+import com.gotcha.ui.ChatScreen
+import com.gotcha.ui.SettingsScreen
import com.gotcha.ui.theme.GotchaTheme
+import kotlinx.coroutines.launch
class MainActivity : ComponentActivity() {
+
+ private val chatViewModel: ChatViewModel by viewModels()
+ private lateinit var settingsRepository: SettingsRepository
+
+ private val permissionLauncher =
+ registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
+ Toast.makeText(
+ this,
+ if (granted) "Permission granted — ask the assistant again."
+ else "Permission denied. The assistant cannot perform that action.",
+ Toast.LENGTH_SHORT
+ ).show()
+ }
+
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
+ settingsRepository = SettingsRepository(this)
+
+ // Phase 7: tools report missing permissions; request them here on first use.
+ lifecycleScope.launch {
+ chatViewModel.permissionRequests.collect { permission ->
+ if (permission == ToolResult.WRITE_SETTINGS) {
+ startActivity(
+ Intent(
+ AndroidSettings.ACTION_MANAGE_WRITE_SETTINGS,
+ Uri.parse("package:$packageName")
+ )
+ )
+ } else {
+ permissionLauncher.launch(permission)
+ }
+ }
+ }
+
setContent {
GotchaTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
- Text(
- text = "Gotcha",
- style = MaterialTheme.typography.headlineMedium
- )
+ GotchaApp()
}
}
}
}
+
+ @Composable
+ private fun GotchaApp() {
+ val state by chatViewModel.uiState.collectAsState()
+ // Route straight to settings until an API key exists (Phase 6 gating).
+ var showSettings by remember { mutableStateOf(!settingsRepository.load().isConfigured) }
+
+ LaunchedEffect(Unit) { chatViewModel.refreshSettings() }
+
+ if (showSettings) {
+ SettingsScreen(
+ initial = settingsRepository.load(),
+ onSave = { settings ->
+ settingsRepository.save(settings)
+ chatViewModel.refreshSettings()
+ },
+ onTestConnection = ::testConnection,
+ onClearLlmCache = {
+ LLMClient(
+ apiKey = "unused", baseUrl = "http://localhost/",
+ context = this@MainActivity
+ ).clearCache()
+ },
+ onBack = { showSettings = false }
+ )
+ } else {
+ ChatScreen(
+ state = state,
+ onSend = chatViewModel::sendMessage,
+ onConfirm = chatViewModel::confirmPendingActions,
+ onClearChat = chatViewModel::clearChat,
+ onOpenSettings = { showSettings = true }
+ )
+ }
+ }
+
+ /** Cheap "ping" request to validate credentials (Phase 6). */
+ private suspend fun testConnection(settings: Settings): Result<String> = runCatching {
+ val client = LLMClient(
+ apiKey = settings.apiKey,
+ baseUrl = settings.baseUrl,
+ model = settings.model,
+ context = this
+ )
+ val response = client.chat(
+ messages = listOf(ChatMessage(role = "user", content = "Reply with the single word: pong")),
+ temperature = 0f
+ )
+ response.choices.firstOrNull()?.message?.content?.take(60) ?: "empty response"
+ }
}
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
new file mode 100644
index 0000000..1fe42ed
--- /dev/null
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -0,0 +1,266 @@
+package com.gotcha.agent
+
+import android.app.Application
+import androidx.lifecycle.AndroidViewModel
+import androidx.lifecycle.viewModelScope
+import com.gotcha.data.ChatHistoryRepository
+import com.gotcha.data.Settings
+import com.gotcha.data.SettingsRepository
+import com.gotcha.llm.ChatMessage
+import com.gotcha.llm.LLMClient
+import com.gotcha.llm.ToolCall
+import com.gotcha.tools.ToolExecutor
+import com.gotcha.tools.ToolRegistry
+import com.gotcha.tools.ToolResult
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.SharedFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asSharedFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonObject
+
+enum class MessageKind { USER, ASSISTANT, TOOL, ERROR }
+
+data class UiMessage(
+ val id: Long,
+ val kind: MessageKind,
+ val text: String
+)
+
+/** A batch of tool calls waiting for the user's confirm/deny (Phase 7). */
+data class PendingConfirmation(
+ val toolNames: List<String>,
+ val description: String
+)
+
+data class ChatUiState(
+ val messages: List<UiMessage> = emptyList(),
+ val isBusy: Boolean = false,
+ val activity: String? = null, // e.g. "Running: toggle_dark_mode…"
+ val pendingConfirmation: PendingConfirmation? = null,
+ val isConfigured: Boolean = false
+)
+
+class ChatViewModel(application: Application) : AndroidViewModel(application) {
+
+ private val settingsRepository = SettingsRepository(application)
+ private val historyRepository = ChatHistoryRepository(application)
+ private val toolExecutor = ToolExecutor(application)
+ private val json = Json { ignoreUnknownKeys = true }
+
+ private var settings: Settings = Settings()
+ private var client: LLMClient? = null
+
+ /** LLM-shaped history (excludes the system prompt, which is prepended per call). */
+ private val llmHistory = mutableListOf<ChatMessage>()
+ private var nextId = 0L
+ private var confirmationGate: CompletableDeferred<Boolean>? = null
+
+ private val _uiState = MutableStateFlow(ChatUiState())
+ val uiState: StateFlow<ChatUiState> = _uiState.asStateFlow()
+
+ /** Permission names (or ToolResult.WRITE_SETTINGS) the Activity should request. */
+ private val _permissionRequests = MutableSharedFlow<String>(extraBufferCapacity = 4)
+ val permissionRequests: SharedFlow<String> = _permissionRequests.asSharedFlow()
+
+ init {
+ refreshSettings()
+ viewModelScope.launch {
+ llmHistory.addAll(historyRepository.load())
+ rebuildUiMessages()
+ }
+ }
+
+ /** Re-reads settings; call after the settings screen saves. */
+ fun refreshSettings() {
+ settings = settingsRepository.load()
+ client = if (settings.isConfigured) {
+ LLMClient(
+ apiKey = settings.apiKey,
+ baseUrl = settings.baseUrl,
+ model = settings.model,
+ context = getApplication()
+ )
+ } else null
+ _uiState.update { it.copy(isConfigured = settings.isConfigured) }
+ }
+
+ fun sendMessage(text: String) {
+ val trimmed = text.trim()
+ if (trimmed.isEmpty() || _uiState.value.isBusy) return
+ if (client == null) {
+ appendUi(MessageKind.ERROR, "No API key configured. Open settings to add one.")
+ return
+ }
+ llmHistory += ChatMessage(role = "user", content = trimmed)
+ appendUi(MessageKind.USER, trimmed)
+ viewModelScope.launch {
+ _uiState.update { it.copy(isBusy = true) }
+ try {
+ runToolLoop()
+ } finally {
+ historyRepository.save(llmHistory)
+ _uiState.update { it.copy(isBusy = false, activity = null) }
+ }
+ }
+ }
+
+ fun confirmPendingActions(approved: Boolean) {
+ _uiState.update { it.copy(pendingConfirmation = null) }
+ confirmationGate?.complete(approved)
+ confirmationGate = null
+ }
+
+ fun clearChat() {
+ if (_uiState.value.isBusy) return
+ llmHistory.clear()
+ nextId = 0
+ _uiState.update { it.copy(messages = emptyList()) }
+ viewModelScope.launch { historyRepository.clear() }
+ }
+
+ private suspend fun runToolLoop() {
+ val llm = client ?: return
+ repeat(MAX_ITERATIONS) { iteration ->
+ if (iteration > 0) delay(INTER_CALL_DELAY_MS) // throttle (PRD §11.2 #7)
+ _uiState.update { it.copy(activity = "Thinking…") }
+
+ val response = try {
+ llm.chat(systemPrompt() + trimmedHistory(), ToolRegistry.allDefinitions())
+ } catch (e: Exception) {
+ appendUi(MessageKind.ERROR, friendlyError(e))
+ return
+ }
+
+ val message = response.choices.firstOrNull()?.message
+ if (message == null) {
+ appendUi(MessageKind.ERROR, "The model returned an empty response.")
+ return
+ }
+
+ val toolCalls = message.toolCalls.orEmpty()
+ if (toolCalls.isEmpty()) {
+ val content = message.content ?: "(no reply)"
+ llmHistory += ChatMessage(role = "assistant", content = content)
+ appendUi(MessageKind.ASSISTANT, content)
+ return
+ }
+
+ llmHistory += message
+ message.content?.takeIf { it.isNotBlank() }
+ ?.let { appendUi(MessageKind.ASSISTANT, it) }
+
+ val approved = requestConfirmationIfNeeded(toolCalls)
+ for (call in toolCalls) {
+ val result = if (approved) executeCall(call)
+ else ToolResult.error("The user declined to run '${call.function.name}'. Do not retry.")
+ llmHistory += ChatMessage(
+ role = "tool",
+ content = result.message,
+ toolCallId = call.id
+ )
+ appendUi(
+ if (result.success) MessageKind.TOOL else MessageKind.ERROR,
+ "${call.function.name}: ${result.message}"
+ )
+ result.needsPermission?.let { _permissionRequests.tryEmit(it) }
+ }
+ historyRepository.save(llmHistory)
+ }
+ appendUi(
+ MessageKind.ERROR,
+ "Stopped after $MAX_ITERATIONS tool rounds to avoid an infinite loop."
+ )
+ }
+
+ private suspend fun requestConfirmationIfNeeded(toolCalls: List<ToolCall>): Boolean {
+ if (!settings.confirmSensitiveActions) return true
+ val sensitive = toolCalls.filter { ToolRegistry.isSensitive(it.function.name) }
+ if (sensitive.isEmpty()) return true
+
+ val gate = CompletableDeferred<Boolean>()
+ confirmationGate = gate
+ _uiState.update {
+ it.copy(
+ activity = null,
+ pendingConfirmation = PendingConfirmation(
+ toolNames = sensitive.map { c -> c.function.name },
+ description = sensitive.joinToString("\n") { c ->
+ "${c.function.name}(${c.function.arguments.take(200)})"
+ }
+ )
+ )
+ }
+ return gate.await()
+ }
+
+ private suspend fun executeCall(call: ToolCall): ToolResult {
+ _uiState.update { it.copy(activity = "Running: ${call.function.name}…") }
+ val args: JsonObject = try {
+ json.decodeFromString(JsonObject.serializer(), call.function.arguments.ifBlank { "{}" })
+ } catch (e: Exception) {
+ return ToolResult.error("Malformed tool arguments: ${call.function.arguments.take(200)}")
+ }
+ return toolExecutor.execute(call.function.name, args)
+ }
+
+ private fun systemPrompt() = listOf(
+ ChatMessage(
+ role = "system",
+ content = "You are Gotcha, an assistant running on the user's Android phone. " +
+ "You control the device only through the provided tools; never invent tool names or " +
+ "capabilities. If a tool reports a missing permission, explain to the user what to " +
+ "grant and suggest retrying. Keep replies short and conversational. " +
+ "After changing device state, confirm what was done based on the tool results."
+ )
+ )
+
+ /** Keeps the prompt bounded (PRD §11.2 #6) without splitting a tool-call/result pair. */
+ private fun trimmedHistory(): List<ChatMessage> {
+ if (llmHistory.size <= MAX_HISTORY_MESSAGES) return llmHistory
+ var start = llmHistory.size - MAX_HISTORY_MESSAGES
+ while (start < llmHistory.size && llmHistory[start].role == "tool") start++
+ return llmHistory.subList(start, llmHistory.size)
+ }
+
+ private fun friendlyError(e: Exception): String = when {
+ e is retrofit2.HttpException && e.code() == 401 ->
+ "The API rejected the key (401). Check your API key in settings."
+ e is retrofit2.HttpException ->
+ "The API returned an error (HTTP ${e.code()}). ${e.message()}"
+ e is java.io.IOException ->
+ "Network problem: ${e.message ?: "could not reach the API"}. Check your connection."
+ else -> "Something went wrong: ${e.message}"
+ }
+
+ private fun appendUi(kind: MessageKind, text: String) {
+ _uiState.update {
+ it.copy(messages = it.messages + UiMessage(nextId++, kind, text))
+ }
+ }
+
+ private fun rebuildUiMessages() {
+ val rebuilt = llmHistory.mapNotNull { msg ->
+ when {
+ msg.role == "user" -> UiMessage(nextId++, MessageKind.USER, msg.content ?: "")
+ msg.role == "assistant" && !msg.content.isNullOrBlank() ->
+ UiMessage(nextId++, MessageKind.ASSISTANT, msg.content)
+ msg.role == "tool" -> UiMessage(nextId++, MessageKind.TOOL, msg.content ?: "")
+ else -> null
+ }
+ }
+ _uiState.update { it.copy(messages = rebuilt) }
+ }
+
+ private companion object {
+ const val MAX_ITERATIONS = 6
+ const val MAX_HISTORY_MESSAGES = 40
+ const val INTER_CALL_DELAY_MS = 400L
+ }
+}
diff --git a/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt b/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt
new file mode 100644
index 0000000..c1300a2
--- /dev/null
+++ b/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt
@@ -0,0 +1,41 @@
+package com.gotcha.data
+
+import android.content.Context
+import com.gotcha.llm.ChatMessage
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.builtins.ListSerializer
+import kotlinx.serialization.json.Json
+import java.io.File
+
+/**
+ * Persists the single conversation (LLM-shaped messages, including tool
+ * calls/results) as JSON in the app sandbox so history survives restarts.
+ */
+class ChatHistoryRepository(context: Context) {
+
+ private val file = File(context.filesDir, "chat_history.json")
+ private val json = Json { ignoreUnknownKeys = true }
+ private val serializer = ListSerializer(ChatMessage.serializer())
+
+ suspend fun load(): List<ChatMessage> = withContext(Dispatchers.IO) {
+ if (!file.exists()) return@withContext emptyList()
+ try {
+ json.decodeFromString(serializer, file.readText())
+ } catch (e: Exception) {
+ emptyList() // corrupt history is dropped rather than crashing
+ }
+ }
+
+ suspend fun save(messages: List<ChatMessage>) = withContext(Dispatchers.IO) {
+ try {
+ file.writeText(json.encodeToString(serializer, messages))
+ } catch (_: Exception) {
+ // Persistence is best-effort.
+ }
+ }
+
+ suspend fun clear() = withContext(Dispatchers.IO) {
+ file.delete()
+ }
+}
diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
new file mode 100644
index 0000000..d83f880
--- /dev/null
+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
@@ -0,0 +1,61 @@
+package com.gotcha.data
+
+import android.content.Context
+import android.content.SharedPreferences
+import androidx.security.crypto.EncryptedSharedPreferences
+import androidx.security.crypto.MasterKey
+
+data class Settings(
+ val apiKey: String = "",
+ val baseUrl: String = DEFAULT_BASE_URL,
+ val model: String = DEFAULT_MODEL,
+ val confirmSensitiveActions: Boolean = true
+) {
+ val isConfigured: Boolean get() = apiKey.isNotBlank() && baseUrl.isNotBlank()
+
+ companion object {
+ const val DEFAULT_BASE_URL = "https://api.openai.com/v1/"
+ const val DEFAULT_MODEL = "gpt-4o"
+ }
+}
+
+/** Stores credentials in EncryptedSharedPreferences (PRD R6). Never logged. */
+class SettingsRepository(context: Context) {
+
+ private val prefs: SharedPreferences by lazy {
+ val masterKey = MasterKey.Builder(context.applicationContext)
+ .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
+ .build()
+ EncryptedSharedPreferences.create(
+ context.applicationContext,
+ "gotcha_settings",
+ masterKey,
+ EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
+ EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
+ )
+ }
+
+ fun load(): Settings = Settings(
+ apiKey = prefs.getString(KEY_API_KEY, "") ?: "",
+ 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,
+ confirmSensitiveActions = prefs.getBoolean(KEY_CONFIRM_SENSITIVE, true)
+ )
+
+ fun save(settings: Settings) {
+ prefs.edit()
+ .putString(KEY_API_KEY, settings.apiKey)
+ .putString(KEY_BASE_URL, settings.baseUrl)
+ .putString(KEY_MODEL, settings.model)
+ .putBoolean(KEY_CONFIRM_SENSITIVE, settings.confirmSensitiveActions)
+ .apply()
+ }
+
+ private companion object {
+ const val KEY_API_KEY = "api_key"
+ const val KEY_BASE_URL = "base_url"
+ const val KEY_MODEL = "model"
+ const val KEY_CONFIRM_SENSITIVE = "confirm_sensitive"
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/ActionLog.kt b/app/src/main/java/com/gotcha/tools/ActionLog.kt
new file mode 100644
index 0000000..05d307f
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/ActionLog.kt
@@ -0,0 +1,36 @@
+package com.gotcha.tools
+
+import android.content.Context
+import java.io.File
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+
+/**
+ * Append-only local audit log of every tool execution (PRD §11.2 #3):
+ * timestamp, tool name, args, and result. Stored in the app sandbox only.
+ */
+class ActionLog(context: Context) {
+
+ private val file: File = File(context.filesDir, "action_log.txt")
+ private val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US)
+
+ @Synchronized
+ fun record(tool: String, args: String, result: ToolResult) {
+ val status = if (result.success) "OK" else "FAIL"
+ val line = "${formatter.format(Date())}\t$tool\t$args\t$status\t${result.message.take(500).replace('\n', ' ')}\n"
+ try {
+ file.appendText(line)
+ trimIfNeeded()
+ } catch (_: Exception) {
+ // Logging must never break tool execution.
+ }
+ }
+
+ private fun trimIfNeeded(maxBytes: Long = 512 * 1024) {
+ if (file.length() > maxBytes) {
+ val lines = file.readLines()
+ file.writeText(lines.drop(lines.size / 2).joinToString("\n", postfix = "\n"))
+ }
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/FileTool.kt b/app/src/main/java/com/gotcha/tools/FileTool.kt
new file mode 100644
index 0000000..82bc44c
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/FileTool.kt
@@ -0,0 +1,144 @@
+package com.gotcha.tools
+
+import android.Manifest
+import android.content.Context
+import android.content.pm.PackageManager
+import android.os.Build
+import android.os.Environment
+import androidx.core.content.ContextCompat
+import java.io.File
+
+/**
+ * Sandboxed filesystem access (PRD §4.1). Paths are rooted at named allow-listed
+ * roots; canonical-path containment checks reject traversal and absolute escapes.
+ */
+class FileTool(private val context: Context) {
+
+ private val sandboxRoots: Map<String, File?> by lazy {
+ mapOf(
+ "files" to context.filesDir,
+ "cache" to context.cacheDir,
+ "external" to context.getExternalFilesDir(null)
+ )
+ }
+
+ private val publicRoots: Map<String, File> by lazy {
+ mapOf(
+ "downloads" to Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
+ "pictures" to Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
+ "dcim" to Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
+ "documents" to Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
+ )
+ }
+
+ private val allowedRootNames: String
+ get() = (sandboxRoots.keys + publicRoots.keys).joinToString(", ")
+
+ fun listFiles(path: String): ToolResult {
+ val resolved = resolve(path, writable = false) ?: return badPath(path)
+ (resolved as? PermissionMissing)?.let { return it.result }
+ val dir = (resolved as Resolved).file
+ if (!dir.exists()) return ToolResult.error("Directory '$path' does not exist.")
+ if (!dir.isDirectory) return ToolResult.error("'$path' is a file, not a directory.")
+ val entries = dir.listFiles()
+ ?: return ToolResult.error("Cannot read '$path' (no access).")
+ if (entries.isEmpty()) return ToolResult.ok("'$path' is empty.")
+ val listing = entries.sortedBy { it.name.lowercase() }.take(200).joinToString("\n") {
+ if (it.isDirectory) "${it.name}/" else "${it.name} (${StorageTool.format(it.length())})"
+ }
+ return ToolResult.ok("Contents of '$path' (${entries.size} entries):\n$listing")
+ }
+
+ fun readFile(path: String, maxBytes: Int = 64 * 1024): ToolResult {
+ val resolved = resolve(path, writable = false) ?: return badPath(path)
+ (resolved as? PermissionMissing)?.let { return it.result }
+ val file = (resolved as Resolved).file
+ if (!file.exists()) return ToolResult.error("File '$path' does not exist.")
+ if (!file.isFile) return ToolResult.error("'$path' is not a regular file.")
+ return try {
+ val truncated = file.length() > maxBytes
+ val buffer = ByteArray(maxBytes)
+ val read = file.inputStream().use { input ->
+ var total = 0
+ while (total < maxBytes) {
+ val n = input.read(buffer, total, maxBytes - total)
+ if (n < 0) break
+ total += n
+ }
+ total
+ }
+ val text = String(buffer, 0, read)
+ ToolResult.ok(if (truncated) "$text\n…(truncated at ${maxBytes / 1024} KB)" else text)
+ } catch (e: Exception) {
+ ToolResult.error("Could not read '$path': ${e.message}")
+ }
+ }
+
+ fun writeFile(path: String, content: String, append: Boolean): ToolResult {
+ val resolved = resolve(path, writable = true)
+ ?: return ToolResult.error(
+ "Writing is only allowed under the app sandbox roots (${sandboxRoots.keys.joinToString(", ")}). " +
+ "Path '$path' is outside them."
+ )
+ (resolved as? PermissionMissing)?.let { return it.result }
+ val file = (resolved as Resolved).file
+ return try {
+ file.parentFile?.mkdirs()
+ if (append) file.appendText(content) else file.writeText(content)
+ ToolResult.ok("${if (append) "Appended to" else "Wrote"} '$path' (${content.length} chars).")
+ } catch (e: Exception) {
+ ToolResult.error("Could not write '$path': ${e.message}")
+ }
+ }
+
+ private sealed interface Resolution
+ private data class Resolved(val file: File) : Resolution
+ private data class PermissionMissing(val result: ToolResult) : Resolution
+
+ /**
+ * Resolves "root/relative/path" to a File, enforcing that the canonical path
+ * stays inside the named root. Returns null for unknown roots or escapes.
+ */
+ private fun resolve(path: String, writable: Boolean): Resolution? {
+ val normalized = path.trim().trimStart('/')
+ val rootName = normalized.substringBefore('/').lowercase()
+ val rest = normalized.substringAfter('/', "")
+
+ val root: File = when {
+ sandboxRoots.containsKey(rootName) -> sandboxRoots[rootName] ?: return null
+ !writable && publicRoots.containsKey(rootName) -> {
+ checkMediaPermission()?.let { return PermissionMissing(it) }
+ publicRoots.getValue(rootName)
+ }
+ else -> return null
+ }
+
+ val target = if (rest.isEmpty()) root else File(root, rest)
+ val canonicalRoot = root.canonicalPath
+ val canonicalTarget = target.canonicalPath
+ if (canonicalTarget != canonicalRoot && !canonicalTarget.startsWith("$canonicalRoot/")) {
+ return null // path traversal attempt
+ }
+ return Resolved(target)
+ }
+
+ private fun checkMediaPermission(): ToolResult? {
+ val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ Manifest.permission.READ_MEDIA_IMAGES
+ } else {
+ Manifest.permission.READ_EXTERNAL_STORAGE
+ }
+ val granted = ContextCompat.checkSelfPermission(context, permission) ==
+ PackageManager.PERMISSION_GRANTED
+ return if (granted) null else ToolResult.permissionNeeded(
+ permission,
+ "Reading public folders needs a storage permission. I have requested it — " +
+ "please grant it and ask again."
+ )
+ }
+
+ private fun badPath(path: String) = ToolResult.error(
+ "Path '$path' is not allowed. Use one of the allowed roots ($allowedRootNames), " +
+ "optionally followed by a relative sub-path; '..' and absolute paths are rejected."
+ )
+}
diff --git a/app/src/main/java/com/gotcha/tools/PhoneTool.kt b/app/src/main/java/com/gotcha/tools/PhoneTool.kt
new file mode 100644
index 0000000..06eb97a
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/PhoneTool.kt
@@ -0,0 +1,24 @@
+package com.gotcha.tools
+
+import android.content.Context
+import android.content.Intent
+import android.net.Uri
+
+class PhoneTool(private val context: Context) {
+
+ fun dialNumber(number: String): ToolResult {
+ val trimmed = number.trim()
+ if (trimmed.isEmpty() || !trimmed.matches(Regex("^[+]?[0-9()\\-\\s#*]{2,20}$"))) {
+ return ToolResult.error("'$number' does not look like a valid phone number.")
+ }
+ return try {
+ val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:$trimmed")).apply {
+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ }
+ context.startActivity(intent)
+ ToolResult.ok("Opened the dialer with $trimmed. The user must press call themselves.")
+ } catch (e: Exception) {
+ ToolResult.error("Could not open the dialer: ${e.message}")
+ }
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/StorageTool.kt b/app/src/main/java/com/gotcha/tools/StorageTool.kt
new file mode 100644
index 0000000..406995a
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/StorageTool.kt
@@ -0,0 +1,53 @@
+package com.gotcha.tools
+
+import android.content.Context
+import android.os.Environment
+import android.os.StatFs
+import java.io.File
+
+class StorageTool(private val context: Context) {
+
+ fun getStorageInfo(): ToolResult {
+ return try {
+ val stat = StatFs(Environment.getDataDirectory().path)
+ val total = stat.blockCountLong * stat.blockSizeLong
+ val free = stat.availableBlocksLong * stat.blockSizeLong
+ val used = total - free
+ ToolResult.ok(
+ "Internal storage: ${format(used)} used of ${format(total)} total, ${format(free)} free."
+ )
+ } catch (e: Exception) {
+ ToolResult.error("Could not read storage info: ${e.message}")
+ }
+ }
+
+ fun clearAppCache(): ToolResult {
+ return try {
+ val dirs = listOfNotNull(context.cacheDir, context.externalCacheDir)
+ val before = dirs.sumOf { dirSize(it) }
+ dirs.forEach { dir ->
+ dir.listFiles()?.forEach { it.deleteRecursively() }
+ }
+ val after = dirs.sumOf { dirSize(it) }
+ ToolResult.ok("Cleared the app cache, freeing ${format(before - after)}.")
+ } catch (e: Exception) {
+ ToolResult.error("Could not clear cache: ${e.message}")
+ }
+ }
+
+ private fun dirSize(dir: File): Long =
+ dir.walkBottomUp().filter { it.isFile }.sumOf { it.length() }
+
+ companion object {
+ fun format(bytes: Long): String {
+ val units = arrayOf("B", "KB", "MB", "GB", "TB")
+ var value = bytes.coerceAtLeast(0).toDouble()
+ var unit = 0
+ while (value >= 1024 && unit < units.lastIndex) {
+ value /= 1024
+ unit++
+ }
+ return "%.1f %s".format(value, units[unit])
+ }
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/SystemTool.kt b/app/src/main/java/com/gotcha/tools/SystemTool.kt
new file mode 100644
index 0000000..5518403
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/SystemTool.kt
@@ -0,0 +1,117 @@
+package com.gotcha.tools
+
+import android.app.UiModeManager
+import android.content.Context
+import android.content.Intent
+import android.os.BatteryManager
+import android.os.Build
+import android.provider.Settings
+
+class SystemTool(private val context: Context) {
+
+ fun toggleDarkMode(enabled: Boolean): ToolResult {
+ return try {
+ val uiModeManager = context.getSystemService(Context.UI_MODE_SERVICE) as UiModeManager
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ uiModeManager.setApplicationNightMode(
+ if (enabled) UiModeManager.MODE_NIGHT_YES else UiModeManager.MODE_NIGHT_NO
+ )
+ ToolResult.ok("${if (enabled) "Dark" else "Light"} mode enabled for the app.")
+ } else {
+ // System-wide night mode below Android 12 needs privileged access;
+ // fall back to reporting the limitation honestly.
+ ToolResult.error(
+ "Changing the theme programmatically requires Android 12+. " +
+ "On this device the user can toggle dark mode in Settings > Display."
+ )
+ }
+ } catch (e: Exception) {
+ ToolResult.error("Could not change theme: ${e.message}")
+ }
+ }
+
+ fun setBrightness(percent: Int): ToolResult {
+ if (percent !in 0..100) {
+ return ToolResult.error("Brightness must be between 0 and 100 (got $percent).")
+ }
+ if (!Settings.System.canWrite(context)) {
+ return ToolResult.permissionNeeded(
+ ToolResult.WRITE_SETTINGS,
+ "Missing the 'Modify system settings' special access. " +
+ "I have opened the settings page — please enable it for Gotcha and ask again."
+ )
+ }
+ return try {
+ val resolver = context.contentResolver
+ Settings.System.putInt(
+ resolver,
+ Settings.System.SCREEN_BRIGHTNESS_MODE,
+ Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
+ )
+ Settings.System.putInt(
+ resolver,
+ Settings.System.SCREEN_BRIGHTNESS,
+ (percent * 255) / 100
+ )
+ ToolResult.ok("Screen brightness set to $percent%.")
+ } catch (e: Exception) {
+ ToolResult.error("Could not set brightness: ${e.message}")
+ }
+ }
+
+ fun getBatteryInfo(): ToolResult {
+ return try {
+ val bm = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
+ val percent = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
+ val charging = bm.isCharging
+ ToolResult.ok("Battery at $percent%, ${if (charging) "charging" else "not charging"}.")
+ } catch (e: Exception) {
+ ToolResult.error("Could not read battery info: ${e.message}")
+ }
+ }
+
+ fun toggleWifi(): ToolResult {
+ return try {
+ val intent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ Intent(Settings.Panel.ACTION_WIFI)
+ } else {
+ Intent(Settings.ACTION_WIFI_SETTINGS)
+ }.apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }
+ context.startActivity(intent)
+ ToolResult.ok("Opened the Wi-Fi settings panel so the user can toggle Wi-Fi.")
+ } catch (e: Exception) {
+ ToolResult.error("Could not open Wi-Fi settings: ${e.message}")
+ }
+ }
+
+ fun openApp(packageName: String): ToolResult {
+ return try {
+ val pm = context.packageManager
+ val launch = pm.getLaunchIntentForPackage(packageName)
+ if (launch != null) {
+ launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ context.startActivity(launch)
+ return ToolResult.ok("Launched $packageName.")
+ }
+ // Fuzzy fallback: match against installed app labels.
+ val query = packageName.lowercase()
+ val match = pm.getInstalledApplications(0).firstOrNull {
+ pm.getApplicationLabel(it).toString().lowercase().contains(query) ||
+ it.packageName.lowercase().contains(query)
+ }
+ if (match != null) {
+ val intent = pm.getLaunchIntentForPackage(match.packageName)
+ if (intent != null) {
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ context.startActivity(intent)
+ return ToolResult.ok(
+ "Launched ${pm.getApplicationLabel(match)} (${match.packageName})."
+ )
+ }
+ }
+ ToolResult.error("No launchable app found matching '$packageName'.")
+ } catch (e: Exception) {
+ ToolResult.error("Could not open app: ${e.message}")
+ }
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/TerminalTool.kt b/app/src/main/java/com/gotcha/tools/TerminalTool.kt
new file mode 100644
index 0000000..8a067b3
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/TerminalTool.kt
@@ -0,0 +1,86 @@
+package com.gotcha.tools
+
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import java.util.concurrent.TimeUnit
+
+/**
+ * Unprivileged shell execution (PRD §4.1): app uid only, hard timeout,
+ * capped output, and a deny-list for clearly destructive/dangerous invocations.
+ */
+class TerminalTool(
+ private val timeoutSeconds: Long = 15,
+ private val maxOutputBytes: Int = 32 * 1024
+) {
+
+ private val denyPatterns = listOf(
+ Regex("""\brm\s+-[a-z]*r"""), // recursive delete
+ Regex("""\bmkfs\b"""),
+ Regex("""\bdd\s+"""),
+ Regex("""\breboot\b"""),
+ Regex("""\bsu\b"""), // privilege escalation attempts
+ Regex(""":\(\)\s*\{"""), // fork bomb
+ Regex("""\bsetprop\b""")
+ )
+
+ suspend fun runCommand(command: String): ToolResult = withContext(Dispatchers.IO) {
+ val trimmed = command.trim()
+ if (trimmed.isEmpty()) return@withContext ToolResult.error("Empty command.")
+ denyPatterns.firstOrNull { it.containsMatchIn(trimmed) }?.let {
+ return@withContext ToolResult.error(
+ "Command blocked by safety policy (matched deny-list): $trimmed"
+ )
+ }
+
+ try {
+ val process = ProcessBuilder("sh", "-c", trimmed)
+ .redirectErrorStream(false)
+ .start()
+
+ val stdout = process.inputStream.bufferedReader()
+ val stderr = process.errorStream.bufferedReader()
+
+ val outBuilder = StringBuilder()
+ val errBuilder = StringBuilder()
+ val outThread = Thread { drain(stdout::read, outBuilder) }
+ val errThread = Thread { drain(stderr::read, errBuilder) }
+ outThread.start(); errThread.start()
+
+ val finished = process.waitFor(timeoutSeconds, TimeUnit.SECONDS)
+ if (!finished) {
+ process.destroyForcibly()
+ return@withContext ToolResult.error(
+ "Command timed out after ${timeoutSeconds}s and was killed: $trimmed"
+ )
+ }
+ outThread.join(2000); errThread.join(2000)
+
+ val exit = process.exitValue()
+ val message = buildString {
+ append("exit code: $exit")
+ if (outBuilder.isNotEmpty()) append("\nstdout:\n$outBuilder")
+ if (errBuilder.isNotEmpty()) append("\nstderr:\n$errBuilder")
+ if (outBuilder.isEmpty() && errBuilder.isEmpty()) append("\n(no output)")
+ }
+ ToolResult(success = exit == 0, message = message)
+ } catch (e: Exception) {
+ ToolResult.error("Failed to run command: ${e.message}")
+ }
+ }
+
+ private fun drain(read: (CharArray, Int, Int) -> Int, into: StringBuilder) {
+ val buf = CharArray(4096)
+ try {
+ while (true) {
+ val n = read(buf, 0, buf.size)
+ if (n < 0) break
+ if (into.length < maxOutputBytes) {
+ into.append(buf, 0, minOf(n, maxOutputBytes - into.length))
+ if (into.length >= maxOutputBytes) into.append("\n…(output capped)")
+ }
+ }
+ } catch (_: Exception) {
+ // Stream closed by process death/timeout.
+ }
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
new file mode 100644
index 0000000..65804a5
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
@@ -0,0 +1,200 @@
+package com.gotcha.tools
+
+import com.gotcha.llm.FunctionDefinition
+import com.gotcha.llm.ToolDefinition
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.put
+import kotlinx.serialization.json.putJsonArray
+import kotlinx.serialization.json.putJsonObject
+import kotlinx.serialization.json.add
+
+/**
+ * Declarative JSON schemas for every tool in the catalog (PRD §4).
+ * Schemas are decoupled from execution: [ToolExecutor] handles side effects.
+ */
+object ToolDefinitions {
+
+ private fun schema(block: kotlinx.serialization.json.JsonObjectBuilder.() -> Unit): JsonObject =
+ buildJsonObject {
+ put("type", "object")
+ block()
+ }
+
+ private fun tool(name: String, description: String, parameters: JsonObject) =
+ ToolDefinition(function = FunctionDefinition(name, description, parameters))
+
+ val dialNumber = tool(
+ "dial_number",
+ "Open the phone dialer pre-filled with a phone number. The user still has to press call.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("number") {
+ put("type", "string")
+ put("description", "Phone number to dial, e.g. +49123456789")
+ }
+ }
+ putJsonArray("required") { add("number") }
+ }
+ )
+
+ val getStorageInfo = tool(
+ "get_storage_info",
+ "Report total, used and free internal storage of the device.",
+ schema { putJsonObject("properties") {} }
+ )
+
+ val getBatteryInfo = tool(
+ "get_battery_info",
+ "Report battery percentage and charging state.",
+ schema { putJsonObject("properties") {} }
+ )
+
+ val listFiles = tool(
+ "list_files",
+ "List files in an allowed directory. Allowed roots: 'files' (app files), 'cache' (app cache), " +
+ "'external' (app external files), 'downloads', 'pictures', 'dcim', 'documents'. " +
+ "An optional relative sub-path may be appended, e.g. 'downloads/reports'.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("path") {
+ put("type", "string")
+ put(
+ "description",
+ "Directory to list: one of the allowed roots optionally followed by a relative sub-path."
+ )
+ }
+ }
+ putJsonArray("required") { add("path") }
+ }
+ )
+
+ val readFile = tool(
+ "read_file",
+ "Read a text file from an allowed directory (same roots as list_files). Output is capped.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("path") {
+ put("type", "string")
+ put("description", "File path rooted at an allowed root, e.g. 'files/notes.txt'.")
+ }
+ }
+ putJsonArray("required") { add("path") }
+ }
+ )
+
+ val writeFile = tool(
+ "write_file",
+ "Write or append a text file inside the app sandbox (roots 'files', 'cache', 'external' only).",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("path") {
+ put("type", "string")
+ put("description", "File path rooted at a sandbox root, e.g. 'files/notes.txt'.")
+ }
+ putJsonObject("content") {
+ put("type", "string")
+ put("description", "Text content to write.")
+ }
+ putJsonObject("append") {
+ put("type", "boolean")
+ put("description", "Append instead of overwrite. Default false.")
+ }
+ }
+ putJsonArray("required") {
+ add("path")
+ add("content")
+ }
+ }
+ )
+
+ val clearAppCache = tool(
+ "clear_app_cache",
+ "Clear this app's own cache directory and report how much space was freed.",
+ schema { putJsonObject("properties") {} }
+ )
+
+ val openApp = tool(
+ "open_app",
+ "Launch an installed app by its package name (e.g. com.android.settings) or by a human name " +
+ "the executor will try to resolve.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("package_name") {
+ put("type", "string")
+ put("description", "Android package name, e.g. com.google.android.youtube")
+ }
+ }
+ putJsonArray("required") { add("package_name") }
+ }
+ )
+
+ val toggleDarkMode = tool(
+ "toggle_dark_mode",
+ "Enable or disable dark theme for this app (and the system where supported).",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("enabled") {
+ put("type", "boolean")
+ put("description", "true for dark, false for light")
+ }
+ }
+ putJsonArray("required") { add("enabled") }
+ }
+ )
+
+ val setBrightness = tool(
+ "set_brightness",
+ "Set the screen brightness to a percentage between 0 and 100. Requires the 'Modify system settings' special access.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("percent") {
+ put("type", "integer")
+ put("description", "Brightness 0-100")
+ }
+ }
+ putJsonArray("required") { add("percent") }
+ }
+ )
+
+ val toggleWifi = tool(
+ "toggle_wifi",
+ "Open the system Wi-Fi settings panel so the user can toggle Wi-Fi (apps cannot toggle it directly on modern Android).",
+ schema { putJsonObject("properties") {} }
+ )
+
+ val setWallpaper = tool(
+ "set_wallpaper",
+ "Set the home-screen wallpaper from an image URL, or a random image if no URL is given.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("url") {
+ put("type", "string")
+ put("description", "Direct image URL. Omit for a random wallpaper.")
+ }
+ }
+ }
+ )
+
+ val runCommand = tool(
+ "run_command",
+ "Run a shell command as the unprivileged app user and return stdout/stderr/exit code. " +
+ "Useful commands: ls, cat, getprop, pm list packages, df, uptime, date, id, ps. " +
+ "No root; many system paths are unreadable. Output is capped and the command times out.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("command") {
+ put("type", "string")
+ put("description", "Shell command line, e.g. 'getprop ro.build.version.release'")
+ }
+ }
+ putJsonArray("required") { add("command") }
+ }
+ )
+
+ val all: List<ToolDefinition> = listOf(
+ dialNumber, getStorageInfo, getBatteryInfo, listFiles, readFile, writeFile,
+ clearAppCache, openApp, toggleDarkMode, setBrightness, toggleWifi,
+ setWallpaper, runCommand
+ )
+}
diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
new file mode 100644
index 0000000..23c4419
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -0,0 +1,72 @@
+package com.gotcha.tools
+
+import android.content.Context
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.booleanOrNull
+import kotlinx.serialization.json.intOrNull
+import kotlinx.serialization.json.jsonPrimitive
+
+/**
+ * Single dispatch point for all tool side effects. Validates args, checks
+ * preconditions (executors return permission errors instead of crashing),
+ * and records every execution in the [ActionLog].
+ */
+class ToolExecutor(context: Context) {
+
+ private val appContext = context.applicationContext
+ private val phoneTool = PhoneTool(appContext)
+ private val systemTool = SystemTool(appContext)
+ private val storageTool = StorageTool(appContext)
+ private val fileTool = FileTool(appContext)
+ private val terminalTool = TerminalTool()
+ private val wallpaperTool = WallpaperTool(appContext)
+ private val actionLog = ActionLog(appContext)
+
+ suspend fun execute(name: String, args: JsonObject): ToolResult {
+ if (!ToolRegistry.contains(name)) {
+ return ToolResult.error("Unknown tool '$name'. Only the fixed tool catalog is available.")
+ }
+ val result = try {
+ withContext(Dispatchers.IO) { dispatch(name, args) }
+ } catch (e: Exception) {
+ ToolResult.error("Tool '$name' failed: ${e.message}")
+ }
+ actionLog.record(name, args.toString(), result)
+ return result
+ }
+
+ 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()
+ "clear_app_cache" -> storageTool.clearAppCache()
+ "list_files" -> fileTool.listFiles(args.requireString("path") ?: return missing("path"))
+ "read_file" -> fileTool.readFile(args.requireString("path") ?: return missing("path"))
+ "write_file" -> fileTool.writeFile(
+ path = args.requireString("path") ?: return missing("path"),
+ content = args.requireString("content") ?: return missing("content"),
+ append = args["append"]?.jsonPrimitive?.booleanOrNull ?: false
+ )
+ "open_app" -> systemTool.openApp(args.requireString("package_name") ?: return missing("package_name"))
+ "toggle_dark_mode" -> systemTool.toggleDarkMode(
+ args["enabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("enabled")
+ )
+ "set_brightness" -> systemTool.setBrightness(
+ args["percent"]?.jsonPrimitive?.intOrNull ?: return missing("percent")
+ )
+ "toggle_wifi" -> systemTool.toggleWifi()
+ "set_wallpaper" -> wallpaperTool.setWallpaper(args.requireString("url"))
+ "run_command" -> terminalTool.runCommand(args.requireString("command") ?: return missing("command"))
+ else -> ToolResult.error("Tool '$name' has no executor.")
+ }
+ }
+
+ private fun JsonObject.requireString(key: String): String? =
+ this[key]?.jsonPrimitive?.takeIf { it.isString || it.content.isNotEmpty() }?.content
+
+ private fun missing(param: String) =
+ ToolResult.error("Missing or invalid required parameter '$param'.")
+}
diff --git a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
new file mode 100644
index 0000000..78b68ce
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
@@ -0,0 +1,30 @@
+package com.gotcha.tools
+
+import com.gotcha.llm.ToolDefinition
+
+/**
+ * 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 }
+
+ /**
+ * Tools whose execution mutates device state or is otherwise sensitive;
+ * these require user confirmation when the confirmation toggle is on (Phase 7).
+ */
+ val sensitiveTools: Set<String> = setOf(
+ "dial_number", "set_wallpaper", "clear_app_cache",
+ "write_file", "run_command", "set_brightness"
+ )
+
+ fun allDefinitions(): List<ToolDefinition> = definitions.values.toList()
+
+ fun definition(name: String): ToolDefinition? = definitions[name]
+
+ fun contains(name: String): Boolean = name in definitions
+
+ fun isSensitive(name: String): Boolean = name in sensitiveTools
+}
diff --git a/app/src/main/java/com/gotcha/tools/ToolResult.kt b/app/src/main/java/com/gotcha/tools/ToolResult.kt
new file mode 100644
index 0000000..9c1b12d
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/ToolResult.kt
@@ -0,0 +1,24 @@
+package com.gotcha.tools
+
+/**
+ * Outcome of a tool execution, fed back to the LLM as a role=tool message.
+ *
+ * @param needsPermission when non-null, the Android permission (or special-access
+ * marker such as [ToolResult.WRITE_SETTINGS]) that must be granted before the
+ * tool can run. The UI layer uses this to trigger a runtime request.
+ */
+data class ToolResult(
+ val success: Boolean,
+ val message: String,
+ val needsPermission: String? = null
+) {
+ companion object {
+ /** Marker for the WRITE_SETTINGS special app access (not a runtime permission). */
+ const val WRITE_SETTINGS = "special:write_settings"
+
+ fun ok(message: String) = ToolResult(true, message)
+ fun error(message: String) = ToolResult(false, message)
+ fun permissionNeeded(permission: String, message: String) =
+ ToolResult(false, message, needsPermission = permission)
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/WallpaperTool.kt b/app/src/main/java/com/gotcha/tools/WallpaperTool.kt
new file mode 100644
index 0000000..c5ec6ae
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/WallpaperTool.kt
@@ -0,0 +1,49 @@
+package com.gotcha.tools
+
+import android.app.WallpaperManager
+import android.content.Context
+import android.graphics.BitmapFactory
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import java.util.concurrent.TimeUnit
+
+class WallpaperTool(private val context: Context) {
+
+ private val httpClient = OkHttpClient.Builder()
+ .connectTimeout(15, TimeUnit.SECONDS)
+ .readTimeout(30, TimeUnit.SECONDS)
+ .build()
+
+ suspend fun setWallpaper(url: String?): ToolResult = withContext(Dispatchers.IO) {
+ val imageUrl = url?.takeIf { it.isNotBlank() } ?: DEFAULT_RANDOM_URL
+ if (!imageUrl.startsWith("https://") && !imageUrl.startsWith("http://")) {
+ return@withContext ToolResult.error("'$imageUrl' is not a valid http(s) image URL.")
+ }
+ try {
+ val request = Request.Builder().url(imageUrl).build()
+ httpClient.newCall(request).execute().use { response ->
+ if (!response.isSuccessful) {
+ return@withContext ToolResult.error(
+ "Image download failed (HTTP ${response.code}) from $imageUrl."
+ )
+ }
+ val body = response.body
+ ?: return@withContext ToolResult.error("Empty response from $imageUrl.")
+ val bitmap = BitmapFactory.decodeStream(body.byteStream())
+ ?: return@withContext ToolResult.error("Downloaded data is not a decodable image.")
+ WallpaperManager.getInstance(context).setBitmap(bitmap)
+ }
+ ToolResult.ok("Wallpaper updated from $imageUrl.")
+ } catch (e: SecurityException) {
+ ToolResult.error("Missing SET_WALLPAPER permission: ${e.message}")
+ } catch (e: Exception) {
+ ToolResult.error("Could not set wallpaper: ${e.message}")
+ }
+ }
+
+ companion object {
+ private const val DEFAULT_RANDOM_URL = "https://picsum.photos/1080/1920"
+ }
+}
diff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
new file mode 100644
index 0000000..d336f6f
--- /dev/null
+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
@@ -0,0 +1,137 @@
+package com.gotcha.ui
+
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.lazy.rememberLazyListState
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.Button
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Scaffold
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.material3.TopAppBar
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.unit.dp
+import com.gotcha.agent.ChatUiState
+
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun ChatScreen(
+ state: ChatUiState,
+ onSend: (String) -> Unit,
+ onConfirm: (Boolean) -> Unit,
+ onClearChat: () -> Unit,
+ onOpenSettings: () -> Unit
+) {
+ var input by rememberSaveable { mutableStateOf("") }
+ val listState = rememberLazyListState()
+
+ LaunchedEffect(state.messages.size) {
+ if (state.messages.isNotEmpty()) {
+ listState.animateScrollToItem(state.messages.size - 1)
+ }
+ }
+
+ Scaffold(
+ topBar = {
+ TopAppBar(
+ title = { Text("Gotcha") },
+ actions = {
+ TextButton(onClick = onClearChat, enabled = !state.isBusy) { Text("Clear") }
+ TextButton(onClick = onOpenSettings) { Text("Settings") }
+ }
+ )
+ }
+ ) { padding ->
+ Column(modifier = Modifier.fillMaxSize().padding(padding)) {
+ LazyColumn(
+ state = listState,
+ modifier = Modifier.weight(1f).fillMaxWidth()
+ ) {
+ items(state.messages, key = { it.id }) { message ->
+ MessageBubble(message)
+ }
+ }
+
+ if (state.activity != null) {
+ Row(
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ CircularProgressIndicator(modifier = Modifier.width(16.dp))
+ Spacer(modifier = Modifier.width(8.dp))
+ Text(state.activity, style = MaterialTheme.typography.bodySmall)
+ }
+ }
+
+ if (!state.isConfigured) {
+ TextButton(
+ onClick = onOpenSettings,
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Text("Set your API key in settings to start chatting →")
+ }
+ }
+
+ Row(
+ modifier = Modifier.fillMaxWidth().padding(8.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ OutlinedTextField(
+ value = input,
+ onValueChange = { input = it },
+ modifier = Modifier.weight(1f),
+ placeholder = { Text("Ask me to do something…") },
+ enabled = !state.isBusy && state.isConfigured,
+ maxLines = 4
+ )
+ Spacer(modifier = Modifier.width(8.dp))
+ Button(
+ onClick = {
+ onSend(input)
+ input = ""
+ },
+ enabled = !state.isBusy && state.isConfigured && input.isNotBlank()
+ ) {
+ Text("Send")
+ }
+ }
+ }
+ }
+
+ state.pendingConfirmation?.let { pending ->
+ AlertDialog(
+ onDismissRequest = { onConfirm(false) },
+ title = { Text("Allow these actions?") },
+ text = {
+ Text(
+ "The assistant wants to run:\n\n${pending.description}",
+ style = MaterialTheme.typography.bodyMedium
+ )
+ },
+ confirmButton = {
+ Button(onClick = { onConfirm(true) }) { Text("Allow") }
+ },
+ dismissButton = {
+ TextButton(onClick = { onConfirm(false) }) { Text("Deny") }
+ }
+ )
+ }
+}
diff --git a/app/src/main/java/com/gotcha/ui/MessageBubble.kt b/app/src/main/java/com/gotcha/ui/MessageBubble.kt
new file mode 100644
index 0000000..39ae238
--- /dev/null
+++ b/app/src/main/java/com/gotcha/ui/MessageBubble.kt
@@ -0,0 +1,60 @@
+package com.gotcha.ui
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.widthIn
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Surface
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.unit.dp
+import com.gotcha.agent.MessageKind
+import com.gotcha.agent.UiMessage
+
+@Composable
+fun MessageBubble(message: UiMessage) {
+ val isUser = message.kind == MessageKind.USER
+ val colors = MaterialTheme.colorScheme
+ val (container, content) = when (message.kind) {
+ MessageKind.USER -> colors.primaryContainer to colors.onPrimaryContainer
+ MessageKind.ASSISTANT -> colors.surfaceVariant to colors.onSurfaceVariant
+ MessageKind.TOOL -> colors.secondaryContainer to colors.onSecondaryContainer
+ MessageKind.ERROR -> colors.errorContainer to colors.onErrorContainer
+ }
+
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 12.dp, vertical = 4.dp),
+ horizontalArrangement = if (isUser) Arrangement.End else Arrangement.Start
+ ) {
+ Surface(
+ color = container,
+ contentColor = content,
+ shape = RoundedCornerShape(
+ topStart = 16.dp,
+ topEnd = 16.dp,
+ bottomStart = if (isUser) 16.dp else 4.dp,
+ bottomEnd = if (isUser) 4.dp else 16.dp
+ )
+ ) {
+ Box(modifier = Modifier.widthIn(max = 300.dp).padding(12.dp)) {
+ Text(
+ text = when (message.kind) {
+ MessageKind.TOOL -> "🔧 ${message.text}"
+ else -> message.text
+ },
+ style = when (message.kind) {
+ MessageKind.TOOL -> MaterialTheme.typography.bodySmall
+ else -> MaterialTheme.typography.bodyMedium
+ }
+ )
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
new file mode 100644
index 0000000..4b62076
--- /dev/null
+++ b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
@@ -0,0 +1,159 @@
+package com.gotcha.ui
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.Button
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Scaffold
+import androidx.compose.material3.Switch
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.material3.TopAppBar
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.text.input.PasswordVisualTransformation
+import androidx.compose.ui.text.input.VisualTransformation
+import androidx.compose.ui.unit.dp
+import com.gotcha.data.Settings
+import kotlinx.coroutines.launch
+
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun SettingsScreen(
+ initial: Settings,
+ onSave: (Settings) -> Unit,
+ onTestConnection: suspend (Settings) -> Result<String>,
+ onClearLlmCache: () -> Unit,
+ onBack: () -> Unit
+) {
+ var apiKey by remember { mutableStateOf(initial.apiKey) }
+ var baseUrl by remember { mutableStateOf(initial.baseUrl) }
+ var model by remember { mutableStateOf(initial.model) }
+ var confirmSensitive by remember { mutableStateOf(initial.confirmSensitiveActions) }
+ var showKey by remember { mutableStateOf(false) }
+ var status by remember { mutableStateOf<String?>(null) }
+ var testing by remember { mutableStateOf(false) }
+ val scope = rememberCoroutineScope()
+
+ fun currentSettings() = Settings(
+ apiKey = apiKey.trim(),
+ baseUrl = baseUrl.trim(),
+ model = model.trim(),
+ confirmSensitiveActions = confirmSensitive
+ )
+
+ Scaffold(
+ topBar = {
+ TopAppBar(
+ title = { Text("Settings") },
+ navigationIcon = { TextButton(onClick = onBack) { Text("← Back") } }
+ )
+ }
+ ) { padding ->
+ Column(
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(padding)
+ .padding(16.dp)
+ .verticalScroll(rememberScrollState()),
+ verticalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ OutlinedTextField(
+ value = apiKey,
+ onValueChange = { apiKey = it },
+ label = { Text("API key") },
+ singleLine = true,
+ visualTransformation = if (showKey) VisualTransformation.None
+ else PasswordVisualTransformation(),
+ trailingIcon = {
+ TextButton(onClick = { showKey = !showKey }) {
+ Text(if (showKey) "Hide" else "Show")
+ }
+ },
+ modifier = Modifier.fillMaxWidth()
+ )
+ OutlinedTextField(
+ value = baseUrl,
+ onValueChange = { baseUrl = it },
+ label = { Text("Base URL (OpenAI-compatible)") },
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth()
+ )
+ OutlinedTextField(
+ value = model,
+ onValueChange = { model = it },
+ label = { Text("Model name") },
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth()
+ )
+
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text("Confirm sensitive actions", style = MaterialTheme.typography.bodyLarge)
+ Switch(checked = confirmSensitive, onCheckedChange = { confirmSensitive = it })
+ }
+
+ Button(
+ onClick = {
+ onSave(currentSettings())
+ status = "Saved."
+ },
+ enabled = apiKey.isNotBlank() && baseUrl.isNotBlank() && model.isNotBlank(),
+ modifier = Modifier.fillMaxWidth()
+ ) { Text("Save") }
+
+ OutlinedButton(
+ onClick = {
+ testing = true
+ status = "Testing connection…"
+ scope.launch {
+ val result = onTestConnection(currentSettings())
+ status = result.fold(
+ onSuccess = { "✓ Connected: $it" },
+ onFailure = { "✗ Connection failed: ${it.message}" }
+ )
+ testing = false
+ }
+ },
+ enabled = !testing && apiKey.isNotBlank() && baseUrl.isNotBlank(),
+ modifier = Modifier.fillMaxWidth()
+ ) { Text("Test connection") }
+
+ OutlinedButton(
+ onClick = {
+ onClearLlmCache()
+ status = "LLM response cache cleared."
+ },
+ modifier = Modifier.fillMaxWidth()
+ ) { Text("Clear LLM cache") }
+
+ status?.let {
+ Text(it, style = MaterialTheme.typography.bodyMedium)
+ }
+
+ Text(
+ "The API key is stored encrypted on this device and never leaves it " +
+ "except in requests to the base URL above.",
+ style = MaterialTheme.typography.bodySmall
+ )
+ }
+ }
+}
diff --git a/app/src/test/java/com/gotcha/tools/TerminalToolTest.kt b/app/src/test/java/com/gotcha/tools/TerminalToolTest.kt
new file mode 100644
index 0000000..b835269
--- /dev/null
+++ b/app/src/test/java/com/gotcha/tools/TerminalToolTest.kt
@@ -0,0 +1,46 @@
+package com.gotcha.tools
+
+import kotlinx.coroutines.test.runTest
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class TerminalToolTest {
+
+ private val tool = TerminalTool(timeoutSeconds = 5)
+
+ @Test
+ fun `simple command returns stdout and exit code`() = runTest {
+ val result = tool.runCommand("echo hello")
+ assertTrue(result.success)
+ assertTrue(result.message.contains("hello"))
+ assertTrue(result.message.contains("exit code: 0"))
+ }
+
+ @Test
+ fun `failing command reports nonzero exit`() = runTest {
+ val result = tool.runCommand("false")
+ assertFalse(result.success)
+ }
+
+ @Test
+ fun `destructive commands are blocked by the deny-list`() = runTest {
+ listOf("rm -rf /", "su -c id", "dd if=/dev/zero of=x", "reboot").forEach { cmd ->
+ val result = tool.runCommand(cmd)
+ assertFalse("expected '$cmd' to be blocked", result.success)
+ assertTrue(result.message.contains("safety policy"))
+ }
+ }
+
+ @Test
+ fun `long output is capped`() = runTest {
+ val small = TerminalTool(timeoutSeconds = 5, maxOutputBytes = 100)
+ val result = small.runCommand("seq 1 10000")
+ assertTrue(result.message.contains("output capped"))
+ }
+
+ @Test
+ fun `empty command is rejected`() = runTest {
+ assertFalse(tool.runCommand(" ").success)
+ }
+}
diff --git a/app/src/test/java/com/gotcha/tools/ToolRegistryTest.kt b/app/src/test/java/com/gotcha/tools/ToolRegistryTest.kt
new file mode 100644
index 0000000..845cb88
--- /dev/null
+++ b/app/src/test/java/com/gotcha/tools/ToolRegistryTest.kt
@@ -0,0 +1,50 @@
+package com.gotcha.tools
+
+import com.gotcha.llm.ToolDefinition
+import kotlinx.serialization.builtins.ListSerializer
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ToolRegistryTest {
+
+ private val json = Json { ignoreUnknownKeys = true }
+
+ @Test
+ fun `all definitions serialize as valid function schemas`() {
+ val defs = ToolRegistry.allDefinitions()
+ assertTrue(defs.isNotEmpty())
+ defs.forEach { def ->
+ assertEquals("function", def.type)
+ assertTrue(def.function.name.isNotBlank())
+ assertTrue(def.function.description.isNotBlank())
+ val encoded = json.encodeToString(ToolDefinition.serializer(), def)
+ val obj = json.parseToJsonElement(encoded).jsonObject
+ val params = obj["function"]!!.jsonObject["parameters"]!!.jsonObject
+ assertEquals("object", params["type"]!!.jsonPrimitive.content)
+ }
+ }
+
+ @Test
+ fun `definitions round-trip through serialization`() {
+ val serializer = ListSerializer(ToolDefinition.serializer())
+ val defs = ToolRegistry.allDefinitions()
+ val decoded = json.decodeFromString(serializer, json.encodeToString(serializer, defs))
+ assertEquals(defs, decoded)
+ }
+
+ @Test
+ fun `sensitive tools are all registered tools`() {
+ ToolRegistry.sensitiveTools.forEach { name ->
+ assertTrue("'$name' marked sensitive but not registered", ToolRegistry.contains(name))
+ }
+ }
+
+ @Test
+ fun `unknown tools are rejected`() {
+ assertTrue(!ToolRegistry.contains("install_apk"))
+ }
+}