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.

refactor: unify file access via FileResolver and expand tool arguments

Rishabh Bajpai3a0e7e73beb6
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index ca96a3f..25cd613 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -11,6 +11,9 @@
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="32" />
+ <uses-permission
+ android:name="android.permission.WRITE_EXTERNAL_STORAGE"
+ android:maxSdkVersion="29" />
<!-- Tier 0–2: communications -->
<uses-permission android:name="android.permission.SEND_SMS" />
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index 2a4e96d..0631876 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -20,6 +20,7 @@ import com.gotcha.llm.LLMClient
import com.gotcha.llm.ToolCall
import com.gotcha.llm.visionUserMessage
import com.gotcha.tools.AgentMode
+import com.gotcha.tools.FileResolver
import com.gotcha.tools.ToolExecutor
import com.gotcha.tools.ToolRegistry
import com.gotcha.tools.ToolResult
@@ -146,6 +147,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
activeSessionId = java.util.UUID.randomUUID().toString()
activeSessionTokenCount = 0
}
+ setupWorkingDir(activeSessionId!!)
_uiState.update { it.copy(activeSessionId = activeSessionId) }
updateContextUsage()
rebuildUiMessages()
@@ -385,6 +387,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
nextId = 0
activeSessionId = java.util.UUID.randomUUID().toString()
activeSessionTokenCount = 0
+ setupWorkingDir(activeSessionId!!)
_uiState.update { it.copy(messages = emptyList(), activeSessionId = activeSessionId) }
updateContextUsage()
}
@@ -408,6 +411,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
activeSessionId = session.id
activeSessionTokenCount = session.tokenCount
nextId = 0
+ setupWorkingDir(session.id)
updateContextUsage()
rebuildUiMessages()
}
@@ -564,6 +568,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
Log.d(TAG, "Permission $perm -> granted=$granted")
if (granted) {
result = executeCall(call)
+ // If the granted permission was a storage permission,
+ // ensure the per-chat working directory now exists.
+ setupWorkingDir(activeSessionId!!)
} else {
result = ToolResult(false, "${result.message} Permission was not granted.")
}
@@ -571,6 +578,8 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
if (result.success && result.message.startsWith("IMAGE_DATA:")) {
handleImageResult(call, result)
+ } else if (result.success && result.message.startsWith("BINARY_DATA:")) {
+ handleBinaryResult(call, result)
} else if (result.success && result.message.startsWith("QUESTION:")) {
handleQuestionResult(call, result)
} else if (result.success && result.message.startsWith("CONFIRM_UNINSTALL:")) {
@@ -714,6 +723,38 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
appendUi(MessageKind.TOOL, "${call.function.name}: Read image $filename ($dimensions)")
}
+ /**
+ * Handles a tool result that contains binary data (prefixed with BINARY_DATA:).
+ * Format: BINARY_DATA:<mime>:<bytes>:<filename>:<base64>
+ * Stores a text summary in history; the raw base64 is available if needed.
+ */
+ private fun handleBinaryResult(call: ToolCall, result: ToolResult) {
+ val body = result.message.removePrefix("BINARY_DATA:")
+ val parts = body.split(":", limit = 4)
+ if (parts.size < 4) {
+ llmHistory += ChatMessage(
+ role = "tool", content = JsonPrimitive("Failed to parse binary data."),
+ toolCallId = call.id
+ )
+ return
+ }
+ val mime = parts[0]
+ val bytesStr = parts[1]
+ val filename = parts[2]
+ val fileSize = try { bytesStr.toLong() } catch (_: Exception) { 0L }
+ val sizeDisplay = when {
+ fileSize >= 1024 * 1024 -> "${fileSize / (1024 * 1024)} MB"
+ fileSize >= 1024 -> "${fileSize / 1024} KB"
+ else -> "$fileSize B"
+ }
+ llmHistory += ChatMessage(
+ role = "tool",
+ content = JsonPrimitive("Read binary file: $filename ($mime, $sizeDisplay)"),
+ toolCallId = call.id
+ )
+ appendUi(MessageKind.TOOL, "${call.function.name}: Read $filename ($mime)")
+ }
+
/**
* Handles a tool result that contains a question (prefixed with QUESTION:).
* Shows the question to the user in a dialog, waits for their answer,
@@ -825,6 +866,21 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
return toolExecutor.execute(call.function.name, args, _uiState.value.activeAgent)
}
+ /**
+ * Sets up the per-chat working directory at:
+ * /storage/emulated/0/Gotcha/chats/{sessionId}/
+ *
+ * Updates [FileResolver.WORKING_DIR_BASE] so file tools resolve relative
+ * paths against this directory.
+ */
+ private fun setupWorkingDir(sessionId: String) {
+ val base = "/storage/emulated/0/Gotcha/chats/$sessionId"
+ val dir = java.io.File(base)
+ if (!dir.exists()) dir.mkdirs()
+ FileResolver.WORKING_DIR_BASE = dir.absolutePath
+ Log.d(TAG, "setupWorkingDir: ${dir.absolutePath}")
+ }
+
/**
* Assembles the system prompt for the given [agent] mode.
* Contains the environment block, core prompt, and agent-mode reminder.
@@ -927,6 +983,8 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
appendLine(" Device admin active: ${if (deviceAdmin) "yes" else "no"}")
appendLine(" VPN active: ${if (vpnActive) "yes" else "no"}")
appendLine(" App version: $versionName")
+ appendLine(" Working directory: ${FileResolver.WORKING_DIR_BASE}")
+ appendLine(" (Relative paths in read_file/write_file/list_files resolve against the working directory.)")
append("</env>")
}
}
diff --git a/app/src/main/java/com/gotcha/tools/EditTool.kt b/app/src/main/java/com/gotcha/tools/EditTool.kt
index 781df85..a69f8a1 100644
--- a/app/src/main/java/com/gotcha/tools/EditTool.kt
+++ b/app/src/main/java/com/gotcha/tools/EditTool.kt
@@ -1,140 +1,66 @@
package com.gotcha.tools
import android.content.Context
-import android.os.Build
-import android.os.Environment
import java.io.File
/**
* Surgical text replacement tool — replaces exact text in a file.
- * Same path-resolution rules as [FileTool].
+ * Uses absolute paths with [FileResolver] for resolution and permission checks.
*
* Only available to Operator (write operation).
*/
class EditTool(private val context: Context) {
+ private val resolver = FileResolver(context)
+
companion object {
private const val MAX_FILE_BYTES = 1024 * 1024
}
- 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 manageRoots: Map<String, File> by lazy {
- mapOf("storage" to Environment.getExternalStorageDirectory())
- }
-
- private fun resolveFile(path: String, writable: Boolean): Pair<File, ToolResult?>? {
- val normalized = path.trim().trimStart('/')
- val rootName = normalized.substringBefore('/').lowercase()
- val rest = normalized.substringAfter('/', "")
-
- val rootInfo: Pair<File, ToolResult?>? = when {
- sandboxRoots.containsKey(rootName) -> {
- val f = sandboxRoots[rootName] ?: return null
- Pair(f, null)
- }
- writable && manageRoots.containsKey(rootName) -> {
- val perm = checkAllFilesAccess()
- if (perm != null) return Pair(File(""), perm)
- Pair(manageRoots.getValue(rootName), null)
- }
- !writable && publicRoots.containsKey(rootName) -> {
- val perm = checkMediaPermission()
- if (perm != null) return Pair(File(""), perm)
- Pair(publicRoots.getValue(rootName), null)
- }
- else -> null
- }
- if (rootInfo == null) return null
- val (root, permErr) = rootInfo
- if (permErr != null) return rootInfo
-
- 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
- }
- return Pair(target, null)
- }
-
fun edit(path: String, oldString: String, newString: String, replaceAll: Boolean): ToolResult {
if (oldString.isBlank()) return ToolResult.error("oldString cannot be blank.")
if (newString == oldString) return ToolResult.error("newString must differ from oldString.")
- if (!isSandboxPath(path)) {
- return ToolResult.error("Editing is only allowed under the app sandbox roots (files, cache, external) " +
- "or the 'storage' root (needs All-files access). Path '$path' is outside them.")
- }
-
- val resolved = resolveFile(path, writable = true) ?: return ToolResult.error(
- "Path '$path' is not allowed. Use sandbox roots (files, cache, external) or 'storage' with All-files access."
- )
- val (file, permError) = resolved
- if (permError != null) return permError
- if (!file.exists()) return ToolResult.error("File '$path' does not exist.")
- if (!file.isFile) return ToolResult.error("'$path' is not a regular file.")
- if (file.length() > MAX_FILE_BYTES) return ToolResult.error("File too large to edit (max 1 MB).")
-
- return try {
- val content = file.readText(Charsets.UTF_8)
-
- val count = if (replaceAll) {
- content.split(oldString).size - 1
- } else {
- if (content.contains(oldString)) 1 else 0
- }
-
- if (count == 0) {
- return ToolResult.error("No match found for the specified text in '$path'. " +
- "The text must match exactly, including whitespace and indentation.")
- }
-
- if (count > 1 && !replaceAll) {
- return ToolResult.error("Found $count matches in '$path'. " +
- "Provide more surrounding context or use replaceAll=true.")
+ val resolved = resolver.resolveForWrite(path)
+ return when (resolved) {
+ is FileResolver.ResolveResult.PermissionNeeded -> resolved.result
+ is FileResolver.ResolveResult.Error -> ToolResult.error(resolved.message)
+ is FileResolver.ResolveResult.Ok -> {
+ val file = resolved.file
+ val perm = resolver.checkWritePermission(file)
+ if (perm != null) return perm
+ if (!file.exists()) return ToolResult.error("File '$path' does not exist (resolved: ${file.canonicalPath}).")
+ if (!file.isFile) return ToolResult.error("'$path' is not a regular file.")
+ if (file.length() > MAX_FILE_BYTES) return ToolResult.error("File too large to edit (max 1 MB).")
+
+ try {
+ val content = file.readText(Charsets.UTF_8)
+ val count = if (replaceAll) content.split(oldString).size - 1
+ else if (content.contains(oldString)) 1 else 0
+
+ if (count == 0) {
+ return ToolResult.error("No match found for the specified text in '$path'. " +
+ "The text must match exactly, including whitespace and indentation.")
+ }
+ if (count > 1 && !replaceAll) {
+ return ToolResult.error("Found $count matches in '$path'. " +
+ "Provide more surrounding context or use replaceAll=true.")
+ }
+
+ val newContent = if (replaceAll) content.replace(oldString, newString)
+ else content.replaceFirst(oldString, newString)
+ file.writeText(newContent, Charsets.UTF_8)
+
+ val verb = if (replaceAll) "Replaced $count occurrences" else "Replaced 1 occurrence"
+ val diff = buildDiffSnippet(oldString, newString)
+ ToolResult.ok("$verb in '${file.canonicalPath}'.\n$diff")
+ } catch (e: Exception) {
+ ToolResult.error("Could not edit '$path': ${e.message}")
+ }
}
-
- val newContent = if (replaceAll) {
- content.replace(oldString, newString)
- } else {
- content.replaceFirst(oldString, newString)
- }
-
- file.writeText(newContent, Charsets.UTF_8)
-
- // Build a simple diff snippet
- val diff = buildDiffSnippet(oldString, newString)
- val verb = if (replaceAll) "Replaced $count occurrences" else "Replaced 1 occurrence"
- val sizeInfo = "(${file.length() / 1024} KB)"
-
- ToolResult.ok("$verb in '$path' $sizeInfo.\n$diff")
- } catch (e: Exception) {
- ToolResult.error("Could not edit '$path': ${e.message}")
}
}
- /** Quick check: is this path under a writable root? */
- private fun isSandboxPath(path: String): Boolean {
- val rootName = path.trim().trimStart('/').substringBefore('/').lowercase()
- return rootName in sandboxRoots || rootName in manageRoots
- }
-
private fun buildDiffSnippet(oldStr: String, newStr: String): String {
val oldLines = oldStr.split("\n")
val newLines = newStr.split("\n")
@@ -149,23 +75,4 @@ class EditTool(private val context: Context) {
if (oldLines.size > max || newLines.size > max) sb.appendLine("…(${oldLines.size}→${newLines.size} lines)")
return sb.toString().trimEnd()
}
-
- private fun checkMediaPermission(): ToolResult? {
- val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
- android.Manifest.permission.READ_MEDIA_IMAGES
- } else {
- android.Manifest.permission.READ_EXTERNAL_STORAGE
- }
- val granted = androidx.core.content.ContextCompat.checkSelfPermission(context, permission) ==
- android.content.pm.PackageManager.PERMISSION_GRANTED
- return if (granted) null else ToolResult.permissionNeeded(permission, "")
- }
-
- private fun checkAllFilesAccess(): ToolResult? {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
- return if (Environment.isExternalStorageManager()) null
- else ToolResult.permissionNeeded(ToolResult.ALL_FILES_ACCESS, "")
- }
- return checkMediaPermission()
- }
}
diff --git a/app/src/main/java/com/gotcha/tools/FileResolver.kt b/app/src/main/java/com/gotcha/tools/FileResolver.kt
new file mode 100644
index 0000000..543b5da
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/FileResolver.kt
@@ -0,0 +1,190 @@
+package com.gotcha.tools
+
+import android.content.Context
+import android.os.Build
+import android.os.Environment
+import androidx.core.content.ContextCompat
+import java.io.File
+
+/**
+ * Shared path resolution and permission checking for all file-related tools.
+ *
+ * Accepts any absolute or relative path. Relative paths are resolved against a
+ * configurable [defaultWorkingDir]. Permission checks are based on the actual
+ * canonical path — not on artificial "named roots".
+ *
+ * Permission model by API level:
+ * - API 23-29: READ_EXTERNAL_STORAGE / WRITE_EXTERNAL_STORAGE (runtime)
+ * - API 30-32: MANAGE_EXTERNAL_STORAGE (special access) for broad; READ/WRITE per media dir
+ * - API 33+: READ_MEDIA_IMAGES + MANAGE_EXTERNAL_STORAGE for broad; per-media-dir per type
+ * - App sandbox: always readable/writable
+ */
+class FileResolver(private val context: Context) {
+
+ companion object {
+ private const val ALL_FILES_ACCESS_GUIDE =
+ "Reading or writing outside the app sandbox needs \"All files access\". " +
+ "I have opened that settings page — please enable it for Gotcha and try again."
+
+ private const val READ_STORAGE_GUIDE =
+ "Reading from shared storage needs storage permission. I have requested it — " +
+ "please grant it and ask again."
+
+ private const val WRITE_STORAGE_GUIDE =
+ "Writing to shared storage needs storage permission. I have requested it — " +
+ "please grant it and ask again."
+
+ var WORKING_DIR_BASE: String = "/storage/emulated/0/Gotcha"
+
+ fun formatSizeStatic(bytes: Long): String = when {
+ bytes >= 1024L * 1024 * 1024 -> "%.1f GB".format(bytes.toDouble() / (1024 * 1024 * 1024))
+ bytes >= 1024L * 1024 -> "%.1f MB".format(bytes.toDouble() / (1024 * 1024))
+ bytes >= 1024L -> "${bytes / 1024} KB"
+ else -> "$bytes B"
+ }
+ }
+
+ private val appSandboxPaths: Set<String> by lazy {
+ setOf(
+ context.filesDir.absolutePath,
+ context.cacheDir.absolutePath,
+ context.getExternalFilesDir(null)?.absolutePath ?: ""
+ ).filter { it.isNotEmpty() }.toSet()
+ }
+
+ fun canonicalPath(input: String, cwd: String = WORKING_DIR_BASE): String {
+ val path = if (input.startsWith("/")) input else File(cwd, input).absolutePath
+ return File(path).canonicalPath
+ }
+
+ sealed class ResolveResult {
+ data class Ok(val file: File) : ResolveResult()
+ data class PermissionNeeded(val result: ToolResult) : ResolveResult()
+ data class Error(val message: String) : ResolveResult()
+ }
+
+ fun resolveForRead(path: String, cwd: String = WORKING_DIR_BASE): ResolveResult {
+ val canonical = canonicalPath(path, cwd)
+ if (isInAppSandbox(canonical)) return ResolveResult.Ok(File(canonical))
+ return when {
+ // API 30+: need MANAGE_EXTERNAL_STORAGE for broad shared-storage read
+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager() -> {
+ if (isBelowExternalStorage(canonical))
+ ResolveResult.PermissionNeeded(
+ ToolResult.permissionNeeded(ToolResult.ALL_FILES_ACCESS, ALL_FILES_ACCESS_GUIDE)
+ )
+ else ResolveResult.Ok(File(canonical))
+ }
+ // API 23-29: need READ_EXTERNAL_STORAGE for shared-storage read
+ Build.VERSION.SDK_INT in 23..29 -> {
+ val has = hasPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
+ if (!has && isBelowExternalStorage(canonical))
+ ResolveResult.PermissionNeeded(
+ ToolResult.permissionNeeded(
+ android.Manifest.permission.READ_EXTERNAL_STORAGE, READ_STORAGE_GUIDE
+ )
+ )
+ else ResolveResult.Ok(File(canonical))
+ }
+ else -> ResolveResult.Ok(File(canonical))
+ }
+ }
+
+ fun resolveForWrite(path: String, cwd: String = WORKING_DIR_BASE): ResolveResult {
+ val canonical = canonicalPath(path, cwd)
+ if (isInAppSandbox(canonical)) return ResolveResult.Ok(File(canonical))
+ return when {
+ // API 30+: need MANAGE_EXTERNAL_STORAGE for shared-storage write
+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager() -> {
+ ResolveResult.PermissionNeeded(
+ ToolResult.permissionNeeded(ToolResult.ALL_FILES_ACCESS, ALL_FILES_ACCESS_GUIDE)
+ )
+ }
+ // API 23-29: need WRITE_EXTERNAL_STORAGE for shared-storage write
+ Build.VERSION.SDK_INT in 23..29 -> {
+ val has = hasPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
+ if (!has && isBelowExternalStorage(canonical))
+ ResolveResult.PermissionNeeded(
+ ToolResult.permissionNeeded(
+ android.Manifest.permission.WRITE_EXTERNAL_STORAGE, WRITE_STORAGE_GUIDE
+ )
+ )
+ else ResolveResult.Ok(File(canonical))
+ }
+ else -> ResolveResult.Ok(File(canonical))
+ }
+ }
+
+ fun checkReadPermission(file: File): ToolResult? {
+ val canonical = file.canonicalPath
+ if (isInAppSandbox(canonical)) return null
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) {
+ if (isBelowExternalStorage(canonical))
+ return ToolResult.permissionNeeded(ToolResult.ALL_FILES_ACCESS, ALL_FILES_ACCESS_GUIDE)
+ }
+ if (Build.VERSION.SDK_INT in 23..29 && isBelowExternalStorage(canonical)) {
+ val perm = android.Manifest.permission.READ_EXTERNAL_STORAGE
+ if (!hasPermission(perm)) return ToolResult.permissionNeeded(perm, READ_STORAGE_GUIDE)
+ }
+ return null
+ }
+
+ fun checkWritePermission(file: File): ToolResult? {
+ val canonical = file.canonicalPath
+ if (isInAppSandbox(canonical)) return null
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) {
+ return ToolResult.permissionNeeded(ToolResult.ALL_FILES_ACCESS, ALL_FILES_ACCESS_GUIDE)
+ }
+ if (Build.VERSION.SDK_INT in 23..29 && isBelowExternalStorage(canonical)) {
+ val perm = android.Manifest.permission.WRITE_EXTERNAL_STORAGE
+ if (!hasPermission(perm)) return ToolResult.permissionNeeded(perm, WRITE_STORAGE_GUIDE)
+ }
+ return null
+ }
+
+ fun formatSize(bytes: Long): String = formatSizeStatic(bytes)
+
+ fun detectMime(bytes: ByteArray): String? {
+ if (bytes.size >= 8 && bytes[0] == 0x89.toByte() && bytes[1] == 0x50.toByte() && bytes[2] == 0x4E.toByte() && bytes[3] == 0x47.toByte()) return "image/png"
+ if (bytes.size >= 3 && bytes[0] == 0xFF.toByte() && bytes[1] == 0xD8.toByte() && bytes[2] == 0xFF.toByte()) return "image/jpeg"
+ if (bytes.size >= 3 && bytes[0] == 0x47.toByte() && bytes[1] == 0x49.toByte() && bytes[2] == 0x46.toByte()) return "image/gif"
+ if (bytes.size >= 2 && bytes[0] == 0x42.toByte() && bytes[1] == 0x4D.toByte()) return "image/bmp"
+ if (bytes.size >= 12 && startsWith(bytes.copyOfRange(0,4), byteArrayOf(0x52,0x49,0x46,0x46)) &&
+ startsWith(bytes.copyOfRange(8,12), byteArrayOf(0x57,0x45,0x42,0x50))) return "image/webp"
+ if (bytes.size >= 5 && bytes[0] == 0x25.toByte() && bytes[1] == 0x50.toByte() && bytes[2] == 0x44.toByte() && bytes[3] == 0x46.toByte() && bytes[4] == 0x2D.toByte()) return "application/pdf"
+ if (bytes.size >= 4 && startsWith(bytes.copyOfRange(0,4), byteArrayOf(0x50,0x4B,0x03,0x04))) return "application/zip"
+ if (bytes.size >= 28 && startsWith(bytes.copyOfRange(0,5), byteArrayOf(0x52,0x61,0x72,0x21,0x1A))) return "application/x-rar-compressed"
+ if (bytes.size >= 3 && startsWith(bytes.copyOfRange(0,3), byteArrayOf(0x1F.toByte(), 0x8B.toByte(), 0x08.toByte()))) return "application/gzip"
+ if (bytes.size >= 4 && startsWith(bytes.copyOfRange(0,4), byteArrayOf(0x2E,0x73,0x6E,0x64))) return "audio/basic"
+ if (bytes.size >= 4 && bytes[0] == 0x4D.toByte() && bytes[1] == 0x54.toByte() && bytes[2] == 0x68.toByte() && bytes[3] == 0x64.toByte()) return "audio/midi"
+ if (bytes.size >= 4 && startsWith(bytes.copyOfRange(0,4), byteArrayOf(0x66,0x74,0x79,0x70))) return "video/mp4"
+ return null
+ }
+
+ fun isImageMime(mime: String): Boolean = mime.startsWith("image/")
+ fun isArchiveMime(mime: String): Boolean = mime == "application/zip" || mime == "application/x-rar-compressed" || mime == "application/gzip"
+ fun isDocumentMime(mime: String): Boolean = mime == "application/pdf"
+
+ val IMAGE_DATA_PREFIX = "IMAGE_DATA:"
+
+ private fun hasPermission(permission: String): Boolean =
+ ContextCompat.checkSelfPermission(context, permission) ==
+ android.content.pm.PackageManager.PERMISSION_GRANTED
+
+ private fun isInAppSandbox(canonical: String): Boolean {
+ return appSandboxPaths.any { canonical.startsWith(it) }
+ }
+
+ private fun isBelowExternalStorage(canonical: String): Boolean {
+ val ext = Environment.getExternalStorageDirectory().absolutePath
+ return canonical.startsWith(ext)
+ }
+
+ private fun startsWith(data: ByteArray, prefix: ByteArray): Boolean {
+ if (data.size < prefix.size) return false
+ for (i in prefix.indices) {
+ if (data[i] != prefix[i]) return false
+ }
+ return true
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/FileTool.kt b/app/src/main/java/com/gotcha/tools/FileTool.kt
index 52b4509..b18b8d4 100644
--- a/app/src/main/java/com/gotcha/tools/FileTool.kt
+++ b/app/src/main/java/com/gotcha/tools/FileTool.kt
@@ -1,175 +1,437 @@
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 android.graphics.BitmapFactory
+import android.util.Base64
import java.io.File
+import java.util.zip.ZipEntry
+import java.util.zip.ZipFile
/**
- * Sandboxed filesystem access (PRD §4.1). Paths are rooted at named allow-listed
- * roots; canonical-path containment checks reject traversal and absolute escapes.
+ * Universal filesystem tool — reads/writes/lists files anywhere on the device
+ * using absolute paths. No more named-root sandboxing. Accepts any absolute
+ * path directly; relative paths are resolved against the default working
+ * directory (see [FileResolver.WORKING_DIR_BASE]).
+ *
+ * Automatically detects file types by extension and magic bytes:
+ * - Text files → line-by-line streaming with offset/limit support
+ * - Images → base64 with IMAGE_DATA prefix (for vision models)
+ * - Archives (zip, rar, gz) → list contents; supports entry reading via "archive.zip/path"
+ * - PDF → base64 document passthrough
+ * - Other binary → base64 with MIME type
+ * - Unknown → best-effort text read
*/
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 resolver = FileResolver(context)
+
+ companion object {
+ private const val MAX_TEXT_BYTES = 64 * 1024
+ private const val MAX_TEXT_LINES = 2000
+ private const val MAX_LINE_LENGTH = 2000
+ private const val MAX_LIST_ENTRIES = 500
+ private const val MAX_LIST_DEPTH = 10
+ private const val MAX_IMAGE_BYTES = 20 * 1024 * 1024
+ private const val MAX_BINARY_BYTES = 20 * 1024 * 1024
+
+ private val TEXT_EXTENSIONS = setOf(
+ "txt", "md", "json", "xml", "html", "htm", "css", "js", "ts", "jsx", "tsx",
+ "kt", "java", "py", "rb", "go", "rs", "c", "cpp", "h", "hpp", "swift",
+ "sh", "bash", "zsh", "bat", "ps1", "yml", "yaml", "toml", "ini", "cfg",
+ "conf", "log", "csv", "tsv", "sql", "r", "m", "gradle", "properties",
+ "env", "gitignore", "dockerfile", "cfg", "plist", "tex", "bib",
+ "svg", "gradle.kts"
)
- }
+ private val IMAGE_EXTENSIONS = setOf("png", "jpg", "jpeg", "gif", "webp", "bmp")
+ private val ARCHIVE_EXTENSIONS = setOf("zip", "apk", "aar", "jar", "war")
+ private val OFFICE_EXTENSIONS = setOf("docx", "xlsx", "pptx")
- 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 ARCHIVE_DELIMITERS = setOf(
+ ".zip/", ".apk/", ".aar/", ".jar/", ".war/",
+ ".docx/", ".xlsx/", ".pptx/"
)
}
- /**
- * Tier 3 — the whole shared-storage tree, read *and* write, behind
- * "All files access" (MANAGE_EXTERNAL_STORAGE). Only reachable when the user has
- * granted that special access; otherwise resolve() returns a permission hint.
- */
- private val manageRoots: Map<String, File> by lazy {
- mapOf("storage" to Environment.getExternalStorageDirectory())
+ fun readFile(
+ path: String,
+ offset: Int? = null,
+ limit: Int? = null,
+ encoding: String? = null
+ ): ToolResult {
+ val resolved = resolver.resolveForRead(path)
+ return when (resolved) {
+ is FileResolver.ResolveResult.PermissionNeeded -> resolved.result
+ is FileResolver.ResolveResult.Error -> ToolResult.error(resolved.message)
+ is FileResolver.ResolveResult.Ok -> readResolved(resolved.file, path, offset, limit, encoding)
+ }
}
- private val allowedRootNames: String
- get() = (sandboxRoots.keys + publicRoots.keys + manageRoots.keys).joinToString(", ")
+ private fun readResolved(
+ file: File,
+ originalPath: String,
+ offset: Int?,
+ limit: Int?,
+ encoding: String?
+ ): ToolResult {
+ if (!file.exists()) {
+ val archiveResult = tryReadArchiveEntry(originalPath)
+ if (archiveResult != null) return archiveResult
+ return ToolResult.error("Path '$originalPath' does not exist (resolved: ${file.canonicalPath}).")
+ }
+ if (file.isDirectory) return listResolved(file, originalPath, null, null, null, false, null)
+ val ext = file.extension.lowercase()
+ val perm = resolver.checkReadPermission(file)
+ if (perm != null) return perm
- 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 when {
+ ext in IMAGE_EXTENSIONS -> readImageFile(file)
+ ext == "pdf" -> readFileBase64(file, "application/pdf")
+ ext in ARCHIVE_EXTENSIONS -> listArchiveContents(file)
+ ext in OFFICE_EXTENSIONS -> {
+ val list = listArchiveContents(file)
+ if (list.success) ToolResult.ok(
+ "Office document detected (${file.name}). It is a ZIP archive containing:\n" +
+ list.message + "\nUse read_file on a specific entry, e.g. '${originalPath}/word/document.xml' for .docx."
+ ) else list
+ }
+ ext in TEXT_EXTENSIONS -> readTextFile(file, offset, limit, encoding)
+ else -> readUnknownFile(file, encoding)
}
- 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.")
+ private fun readTextFile(file: File, offset: Int?, limit: Int?, encoding: String?): ToolResult {
+ val enc = encoding ?: Charsets.UTF_8.name()
+ val maxLines = limit ?: MAX_TEXT_LINES
+ val startLine = (offset ?: 1).coerceAtLeast(1)
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
+ val lines = file.readLines(java.nio.charset.Charset.forName(enc))
+ if (startLine > lines.size) {
+ return ToolResult.error(
+ "File '${file.name}' has ${lines.size} lines, but offset $startLine was requested."
+ )
+ }
+ val endLine = minOf(startLine + maxLines - 1, lines.size)
+ val selected = lines.subList(startLine - 1, endLine)
+ val truncated = endLine < lines.size
+ val shownBytes = selected.sumOf { it.length }
+ val capReached = shownBytes > MAX_TEXT_BYTES
+ val sb = StringBuilder()
+ var byteCount = 0
+ for ((i, line) in selected.withIndex()) {
+ val lineNum = startLine + i
+ val display = if (line.length > MAX_LINE_LENGTH)
+ line.take(MAX_LINE_LENGTH) + "…(line truncated)"
+ else line
+ val next = if (i > 0 || offset != null) "$lineNum: $display\n" else "$display\n"
+ if (byteCount + next.length > MAX_TEXT_BYTES && byteCount > 0) {
+ sb.append("…(output capped at ${MAX_TEXT_BYTES / 1024} KB)")
+ break
}
- total
+ sb.append(next)
+ byteCount += next.length
+ if (capReached && byteCount >= MAX_TEXT_BYTES) break
}
- val text = String(buffer, 0, read)
- ToolResult.ok(if (truncated) "$text\n…(truncated at ${maxBytes / 1024} KB)" else text)
+
+ val result = sb.toString().trimEnd()
+ val summary = buildString {
+ append(result)
+ if (truncated || capReached) {
+ append("\n")
+ if (truncated) append("(Showing lines $startLine-$endLine of ${lines.size}. Use offset=${endLine + 1} to continue.)")
+ if (capReached) append(" (Output capped at ${MAX_TEXT_BYTES / 1024} KB.)")
+ }
+ }
+ ToolResult.ok(summary.ifEmpty { "(empty file)" })
+ } catch (e: java.nio.charset.UnsupportedCharsetException) {
+ ToolResult.error("Unsupported encoding '$enc'. Try UTF-8, ISO-8859-1, or UTF-16.")
} catch (e: Exception) {
- ToolResult.error("Could not read '$path': ${e.message}")
+ ToolResult.error("Could not read '${file.name}': ${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(", ")}) " +
- "or the 'storage' root (needs All-files access). Path '$path' is outside them."
+ private fun readImageFile(file: File): ToolResult {
+ if (file.length() > MAX_IMAGE_BYTES) {
+ return ToolResult.error("Image too large (${resolver.formatSize(file.length())}). Max: ${MAX_IMAGE_BYTES / 1024 / 1024} MB.")
+ }
+ return try {
+ val bytes = file.readBytes()
+ val mime = resolver.detectMime(bytes)
+ if (mime == null || !resolver.isImageMime(mime))
+ return ToolResult.error("File '${file.name}' is not a recognized image format.")
+ val opts = BitmapFactory.Options().apply { inJustDecodeBounds = true }
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, opts)
+ if (opts.outWidth <= 0 || opts.outHeight <= 0)
+ return ToolResult.error("File '${file.name}' could not be decoded as an image.")
+ val base64 = Base64.encodeToString(bytes, Base64.NO_WRAP)
+ val displayName = file.name
+ ToolResult.ok(
+ "${resolver.IMAGE_DATA_PREFIX}$mime:${opts.outWidth}x${opts.outHeight}:${bytes.size}:$displayName:$base64"
)
- (resolved as? PermissionMissing)?.let { return it.result }
- val file = (resolved as Resolved).file
+ } catch (e: Exception) {
+ ToolResult.error("Could not read image '${file.name}': ${e.message}")
+ }
+ }
+
+ private fun readFileBase64(file: File, mime: String): ToolResult {
+ if (file.length() > MAX_BINARY_BYTES) {
+ return ToolResult.error("File too large (${resolver.formatSize(file.length())}). Max: ${MAX_BINARY_BYTES / 1024 / 1024} MB.")
+ }
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).")
+ val bytes = file.readBytes()
+ val base64 = Base64.encodeToString(bytes, Base64.NO_WRAP)
+ ToolResult.ok("BINARY_DATA:$mime:${bytes.size}:${file.name}:$base64")
} catch (e: Exception) {
- ToolResult.error("Could not write '$path': ${e.message}")
+ ToolResult.error("Could not read '${file.name}': ${e.message}")
}
}
- private sealed interface Resolution
- private data class Resolved(val file: File) : Resolution
- private data class PermissionMissing(val result: ToolResult) : Resolution
+ private fun readUnknownFile(file: File, encoding: String?): ToolResult {
+ val sample = try { file.inputStream().use { it.readNBytes(512) } } catch (_: Exception) { ByteArray(0) }
+ if (sample.isEmpty()) return readTextFile(file, null, 200, encoding)
+ val nullRatio = sample.count { it.toInt() == 0 }.toFloat() / sample.size
+ val nonprintableRatio = sample.count {
+ val v = it.toInt() and 0xFF; v < 32 && v != 9 && v != 10 && v != 13
+ }.toFloat() / sample.size
+ val mime = resolver.detectMime(sample)
+ if (mime != null && resolver.isImageMime(mime)) return readImageFile(file)
+ if (mime != null && mime == "application/pdf") return readFileBase64(file, "application/pdf")
+ if (mime != null && resolver.isArchiveMime(mime)) return listArchiveContents(file)
- /**
- * 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('/', "")
+ return if (nullRatio > 0.05f || nonprintableRatio > 0.3f) {
+ readFileBase64(file, "application/octet-stream")
+ } else {
+ readTextFile(file, null, 200, encoding ?: Charsets.UTF_8.name())
+ }
+ }
- val root: File = when {
- sandboxRoots.containsKey(rootName) -> sandboxRoots[rootName] ?: return null
- manageRoots.containsKey(rootName) -> {
- checkAllFilesAccess()?.let { return PermissionMissing(it) }
- manageRoots.getValue(rootName)
+ private fun listArchiveContents(file: File): ToolResult {
+ return try {
+ when (file.extension.lowercase()) {
+ "zip", "apk", "aar", "jar", "war", "docx", "xlsx", "pptx" -> {
+ val zf = ZipFile(file)
+ val entries = zf.entries().asSequence().toList()
+ zf.close()
+ if (entries.isEmpty()) return ToolResult.ok("Archive '${file.name}' is empty.")
+ val totalSize = entries.sumOf { it.size.coerceAtLeast(0) }
+ val sb = StringBuilder()
+ sb.appendLine("Archive: ${file.name} (${resolver.formatSize(file.length())}, ${entries.size} entries, ${resolver.formatSize(totalSize)} uncompressed)")
+ for (e in entries.take(200)) {
+ val flag = if (e.isDirectory) "/" else ""
+ val size = if (e.size > 0) " ${resolver.formatSize(e.size)}" else ""
+ sb.appendLine(" $flag${e.name}$size")
+ }
+ if (entries.size > 200) sb.appendLine(" …(${entries.size - 200} more)")
+ ToolResult.ok(sb.toString().trimEnd())
+ }
+ else -> ToolResult.error("Unsupported archive format: .${file.extension}")
}
- !writable && publicRoots.containsKey(rootName) -> {
- checkMediaPermission()?.let { return PermissionMissing(it) }
- publicRoots.getValue(rootName)
+ } catch (e: Exception) {
+ ToolResult.error("Could not read archive '${file.name}': ${e.message}")
+ }
+ }
+
+ private fun tryReadArchiveEntry(path: String): ToolResult? {
+ for (delim in ARCHIVE_DELIMITERS) {
+ val idx = path.indexOf(delim)
+ if (idx < 0) continue
+ val archivePath = path.substring(0, idx + delim.length - 1)
+ val entryPath = path.substring(idx + delim.length)
+ val archiveFile = File(archivePath)
+ if (!archiveFile.exists()) continue
+ try {
+ val zf = ZipFile(archiveFile)
+ val result = readZipEntry(zf, archiveFile, archivePath, entryPath)
+ zf.close()
+ return result
+ } catch (e: Exception) {
+ return ToolResult.error("Could not read entry '$entryPath' from archive: ${e.message}")
}
- else -> return null
}
+ 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
+ private fun readZipEntry(zf: ZipFile, archiveFile: File, archivePath: String, entryPath: String): ToolResult {
+ val entry = zf.getEntry(entryPath)
+ if (entry == null) {
+ val siblings = zf.entries().asSequence().map { it?.name ?: "" }.toList()
+ val matching = siblings.filter { it.contains(entryPath, ignoreCase = true) }.take(5)
+ val hint = if (matching.isNotEmpty())
+ " Did you mean one of: ${matching.joinToString(", ")}?"
+ else ""
+ return ToolResult.error("Entry '$entryPath' not found in '${archiveFile.name}'.$hint")
+ }
+ if (entry.isDirectory) {
+ val children = zf.entries().asSequence()
+ .filter { it != null && it.name.startsWith(entryPath) && !it.isDirectory }.take(100).toList()
+ if (children.isEmpty()) return ToolResult.ok("(empty directory)")
+ val listing = children.joinToString("\n") { " ${it!!.name} (${resolver.formatSize(it.size)})" }
+ return ToolResult.ok("Contents of '$entryPath' (${children.size} files):\n$listing")
+ }
+ val ext = entryPath.substringAfterLast('.', "").lowercase()
+ val bytes = zf.getInputStream(entry).readBytes()
+ if (ext in IMAGE_EXTENSIONS) {
+ val mime = resolver.detectMime(bytes) ?: "image/$ext"
+ val opts = BitmapFactory.Options().apply { inJustDecodeBounds = true }
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, opts)
+ val dims = if (opts.outWidth > 0) "${opts.outWidth}x${opts.outHeight}" else "unknown"
+ val base64 = Base64.encodeToString(bytes, Base64.NO_WRAP)
+ return ToolResult.ok("${resolver.IMAGE_DATA_PREFIX}$mime:$dims:${bytes.size}:$entryPath:$base64")
}
- return Resolved(target)
+ if (ext in TEXT_EXTENSIONS || resolver.detectMime(bytes) == null) {
+ val text = String(bytes, Charsets.UTF_8)
+ return ToolResult.ok("[$archivePath / $entryPath]\n$text")
+ }
+ val mime = resolver.detectMime(bytes) ?: "application/octet-stream"
+ val base64 = Base64.encodeToString(bytes, Base64.NO_WRAP)
+ return ToolResult.ok("BINARY_DATA:$mime:${bytes.size}:$entryPath:$base64")
}
- 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."
- )
+ fun writeFile(
+ path: String,
+ content: String,
+ append: Boolean = false,
+ binary: Boolean = false
+ ): ToolResult {
+ val resolved = resolver.resolveForWrite(path)
+ return when (resolved) {
+ is FileResolver.ResolveResult.PermissionNeeded -> resolved.result
+ is FileResolver.ResolveResult.Error -> ToolResult.error(resolved.message)
+ is FileResolver.ResolveResult.Ok -> {
+ val perm = resolver.checkWritePermission(resolved.file)
+ if (perm != null) return perm
+ writeResolved(resolved.file, path, content, append, binary)
+ }
+ }
}
- /**
- * Tier 3 gate for the 'storage' root. On API 30+ this is the MANAGE_EXTERNAL_STORAGE
- * "All files access" special grant; on older devices broad read access falls back to
- * READ/WRITE_EXTERNAL_STORAGE (handled here as the media permission).
- */
- private fun checkAllFilesAccess(): ToolResult? {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
- return if (Environment.isExternalStorageManager()) null
- else ToolResult.permissionNeeded(
- ToolResult.ALL_FILES_ACCESS,
- "Reading or writing all of shared storage needs \"All files access\". I have opened " +
- "that settings page — please enable it for Gotcha and ask again."
+ private fun writeResolved(
+ file: File,
+ originalPath: String,
+ content: String,
+ append: Boolean,
+ binary: Boolean
+ ): ToolResult {
+ return try {
+ file.parentFile?.mkdirs()
+ if (binary) {
+ val bytes = Base64.decode(content, Base64.NO_WRAP)
+ if (append) file.appendBytes(bytes) else file.writeBytes(bytes)
+ ToolResult.ok("Wrote ${resolver.formatSize(bytes.size.toLong())} binary data to '$originalPath' (resolved: ${file.canonicalPath}).")
+ } else {
+ val bytes = content.toByteArray(Charsets.UTF_8)
+ if (append) file.appendBytes(bytes) else file.writeBytes(bytes)
+ ToolResult.ok("${if (append) "Appended" else "Wrote"} ${resolver.formatSize(bytes.size.toLong())} to '$originalPath' (resolved: ${file.canonicalPath}).")
+ }
+ } catch (e: Exception) {
+ ToolResult.error("Could not write '$originalPath': ${e.message}")
+ }
+ }
+
+ fun listFiles(
+ path: String,
+ recursive: Boolean = false,
+ sortBy: String? = null,
+ include: String? = null,
+ exclude: String? = null,
+ maxDepth: Int? = null
+ ): ToolResult {
+ val resolved = resolver.resolveForRead(path)
+ return when (resolved) {
+ is FileResolver.ResolveResult.PermissionNeeded -> resolved.result
+ is FileResolver.ResolveResult.Error -> ToolResult.error(resolved.message)
+ is FileResolver.ResolveResult.Ok -> listResolved(
+ resolved.file, path, sortBy, include, exclude, recursive, maxDepth
)
}
- // Pre-R: broad shared-storage access rides on the legacy storage permission.
- return checkMediaPermission()
}
- 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."
- )
+ private fun listResolved(
+ file: File,
+ originalPath: String,
+ sortBy: String?,
+ include: String?,
+ exclude: String?,
+ recursive: Boolean,
+ maxDepth: Int?
+ ): ToolResult {
+ if (!file.exists()) return ToolResult.error("Path '$originalPath' does not exist (resolved: ${file.canonicalPath}).")
+ if (!file.isDirectory) {
+ return ToolResult.ok("${file.name} (${resolver.formatSize(file.length())})\nResolved: ${file.canonicalPath}")
+ }
+ val perm = resolver.checkReadPermission(file)
+ if (perm != null) return perm
+
+ val results = mutableListOf<Pair<String, File>>()
+ val depthLimit = maxDepth ?: if (recursive) MAX_LIST_DEPTH else 1
+ var aborted = false
+
+ fun walk(dir: File, depth: Int) {
+ if (aborted || depth > depthLimit) return
+ val entries = dir.listFiles()?.sortedWith(when (sortBy?.lowercase()) {
+ "date" -> compareBy<File> { it.lastModified() }
+ "size" -> compareBy<File> { it.length() }
+ else -> compareBy { it.name.lowercase() }
+ }) ?: return
+ for (entry in entries) {
+ if (results.size >= MAX_LIST_ENTRIES) { aborted = true; return }
+ val relPath = if (depth == 0) entry.name else entry.absolutePath
+ val name = entry.name.lowercase()
+ if (include != null && !name.contains(include.lowercase())) continue
+ if (exclude != null && name.contains(exclude.lowercase())) continue
+ results.add(relPath to entry)
+ if (entry.isDirectory && recursive) walk(entry, depth + 1)
+ }
+ }
+
+ walk(file, 0)
+
+ if (results.isEmpty()) return ToolResult.ok("'${file.canonicalPath}' is empty.")
+ val sb = StringBuilder()
+ sb.appendLine("${file.canonicalPath} (${results.size} entries):")
+ for ((relPath, entry) in results) {
+ val typeChar = when {
+ entry.isDirectory -> '/'
+ entry.canExecute() -> '*'
+ else -> ' '
+ }
+ sb.appendLine(" $typeChar $relPath ${resolver.formatSize(entry.length())}")
+ }
+ if (aborted) sb.append("…(truncated, max $MAX_LIST_ENTRIES entries)")
+ return ToolResult.ok(sb.toString().trimEnd())
+ }
+
+ fun fileInfo(path: String): ToolResult {
+ val resolved = resolver.resolveForRead(path)
+ return when (resolved) {
+ is FileResolver.ResolveResult.PermissionNeeded -> resolved.result
+ is FileResolver.ResolveResult.Error -> ToolResult.error(resolved.message)
+ is FileResolver.ResolveResult.Ok -> {
+ val f = resolved.file
+ if (!f.exists()) return ToolResult.error("Path '$path' does not exist.")
+ val perm = resolver.checkReadPermission(f)
+ if (perm != null) return perm
+ val type = when {
+ f.isDirectory -> "directory"
+ f.isFile -> "file"
+ else -> "other"
+ }
+ val size = resolver.formatSize(f.length())
+ val modified = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.US)
+ .format(java.util.Date(f.lastModified()))
+ val executable = if (f.canExecute()) ", executable" else ""
+ val readable = if (f.canRead()) "readable" else "not readable"
+ ToolResult.ok(
+ "Path: ${f.canonicalPath}\n" +
+ "Type: $type\n" +
+ "Size: $size\n" +
+ "Modified: $modified\n" +
+ "Permissions: $readable$executable"
+ )
+ }
+ }
+ }
+
+ fun resolvePath(input: String): String {
+ return resolver.canonicalPath(input)
+ }
}
diff --git a/app/src/main/java/com/gotcha/tools/GlobTool.kt b/app/src/main/java/com/gotcha/tools/GlobTool.kt
index 7fb2329..8b4723f 100644
--- a/app/src/main/java/com/gotcha/tools/GlobTool.kt
+++ b/app/src/main/java/com/gotcha/tools/GlobTool.kt
@@ -1,128 +1,73 @@
package com.gotcha.tools
import android.content.Context
-import android.os.Build
-import android.os.Environment
import java.io.File
/**
* Pattern-based file discovery tool — finds files matching a glob pattern
- * within named-root paths. Same path-resolution as [FileTool].
+ * within any directory. Uses absolute paths. The [FileResolver] handles
+ * permission checks.
*
- * Supports: `*` (single segment), `**` (recursive), `?` (single char).
+ * Supports: `*` (single segment), `**` (recursive), `?` (single char),
+ * `{a,b}` (alternation).
*/
class GlobTool(private val context: Context) {
+ private val resolver = FileResolver(context)
+
companion object {
private const val MAX_RESULTS = 500
private const val MAX_DEPTH = 10
}
- 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 manageRoots: Map<String, File> by lazy {
- mapOf("storage" to Environment.getExternalStorageDirectory())
- }
-
- private fun resolveRoot(path: String): Pair<File, ToolResult?>? {
- 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
- manageRoots.containsKey(rootName) -> {
- val perm = checkAllFilesAccess()
- if (perm != null) return Pair(File(""), perm)
- manageRoots.getValue(rootName)
- }
- publicRoots.containsKey(rootName) -> {
- val perm = checkMediaPermission()
- if (perm != null) return Pair(File(""), perm)
- 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
- }
- return Pair(target, null)
- }
-
- /**
- * Find files matching [pattern] within [path].
- * Pattern uses glob syntax: `*` matches any non-/ chars, `**` matches
- * any path, `?` matches a single non-/ char.
- */
fun glob(path: String, pattern: String): ToolResult {
if (pattern.isBlank()) return ToolResult.error("Glob pattern cannot be empty.")
- val resolved = resolveRoot(path) ?: return ToolResult.error(
- "Path '$path' is not allowed. Use one of: files, cache, external, " +
- "downloads, pictures, dcim, documents, storage."
- )
- val (root, permError) = resolved
- if (permError != null) return permError
- if (!root.exists()) return ToolResult.error("Path '$path' does not exist.")
-
- val regex = globToRegex(pattern)
- val results = mutableListOf<String>()
- var aborted = false
-
- fun walk(dir: File, depth: Int) {
- if (aborted || depth > MAX_DEPTH) return
- val entries = dir.listFiles() ?: return
- for (file in entries.sortedBy { it.name.lowercase() }) {
- if (aborted) return
- if (results.size >= MAX_RESULTS) { aborted = true; return }
-
- val relPath = relativePath(file)
- if (regex.matches(relPath)) {
- results.add(if (file.isDirectory) "$relPath/" else relPath)
+ val resolved = resolver.resolveForRead(path)
+ return when (resolved) {
+ is FileResolver.ResolveResult.PermissionNeeded -> resolved.result
+ is FileResolver.ResolveResult.Error -> ToolResult.error(resolved.message)
+ is FileResolver.ResolveResult.Ok -> {
+ val root = resolved.file
+ val perm = resolver.checkReadPermission(root)
+ if (perm != null) return perm
+ if (!root.exists()) return ToolResult.error("Path '$path' does not exist.")
+
+ val regex = globToRegex(pattern)
+ val results = mutableListOf<String>()
+ var aborted = false
+
+ fun walk(dir: File, depth: Int) {
+ if (aborted || depth > MAX_DEPTH) return
+ val entries = dir.listFiles() ?: return
+ for (file in entries.sortedBy { it.name.lowercase() }) {
+ if (aborted) return
+ if (results.size >= MAX_RESULTS) { aborted = true; return }
+
+ val relPath = file.absolutePath.removePrefix(root.absolutePath).trimStart('/')
+ if (regex.matches(relPath)) {
+ results.add(if (file.isDirectory) "$relPath/" else relPath)
+ }
+
+ if (file.isDirectory) walk(file, depth + 1)
+ }
}
- if (file.isDirectory) {
- walk(file, depth + 1)
+ if (root.isDirectory) walk(root, 0)
+ else {
+ if (regex.matches(root.name)) results.add(root.absolutePath)
}
- }
- }
- if (root.isDirectory) {
- walk(root, 0)
- } else {
- if (regex.matches(root.name)) {
- results.add(relativePath(root))
+ if (results.isEmpty()) {
+ return ToolResult.ok("No files matching '$pattern' found in '$path'.")
+ }
+ val truncated = if (aborted) "\n…(truncated, max $MAX_RESULTS results)" else ""
+ return ToolResult.ok("${results.size} file(s) matching '$pattern' in '$path':\n" +
+ results.joinToString("\n") + truncated)
}
}
-
- if (results.isEmpty()) {
- return ToolResult.ok("No files matching '$pattern' found in '$path'.")
- }
- val truncated = if (aborted) "\n…(truncated, max $MAX_RESULTS results)" else ""
- return ToolResult.ok("${results.size} file(s) matching '$pattern' in '$path':\n" +
- results.joinToString("\n") + truncated)
}
- /** Convert a glob pattern to a regex. */
private fun globToRegex(glob: String): Regex {
val sb = StringBuilder()
var i = 0
@@ -131,12 +76,10 @@ class GlobTool(private val context: Context) {
when (c) {
'*' -> {
if (i + 1 < glob.length && glob[i + 1] == '*') {
- // ** matches everything
sb.append(".*")
i += 2
- if (i < glob.length && glob[i] == '/') i++ // skip trailing /
+ if (i < glob.length && glob[i] == '/') i++
} else {
- // * matches non-/ chars
sb.append("[^/]*")
i++
}
@@ -162,34 +105,4 @@ class GlobTool(private val context: Context) {
Regex(".*")
}
}
-
- private fun relativePath(file: File): String {
- val canonical = file.absolutePath
- for (root in sandboxRoots.values + publicRoots.values + manageRoots.values) {
- val rootPath = root?.absolutePath ?: continue
- if (canonical.startsWith(rootPath + "/")) {
- return canonical.substring(rootPath.length + 1)
- }
- }
- return file.name
- }
-
- private fun checkMediaPermission(): ToolResult? {
- val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
- android.Manifest.permission.READ_MEDIA_IMAGES
- } else {
- android.Manifest.permission.READ_EXTERNAL_STORAGE
- }
- val granted = androidx.core.content.ContextCompat.checkSelfPermission(context, permission) ==
- android.content.pm.PackageManager.PERMISSION_GRANTED
- return if (granted) null else ToolResult.permissionNeeded(permission, "")
- }
-
- private fun checkAllFilesAccess(): ToolResult? {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
- return if (Environment.isExternalStorageManager()) null
- else ToolResult.permissionNeeded(ToolResult.ALL_FILES_ACCESS, "")
- }
- return checkMediaPermission()
- }
}
diff --git a/app/src/main/java/com/gotcha/tools/GrepTool.kt b/app/src/main/java/com/gotcha/tools/GrepTool.kt
index d801b0d..2e721c0 100644
--- a/app/src/main/java/com/gotcha/tools/GrepTool.kt
+++ b/app/src/main/java/com/gotcha/tools/GrepTool.kt
@@ -1,17 +1,16 @@
package com.gotcha.tools
import android.content.Context
-import android.os.Build
-import android.os.Environment
import java.io.File
-import java.io.FileInputStream
/**
- * Content-search tool — searches file contents by regex within named-root paths.
- * Same path-resolution rules as [FileTool] and [VisionTool].
+ * Content-search tool — searches file contents by regex within any directory.
+ * Uses absolute paths. The [FileResolver] handles permission checks.
*/
class GrepTool(private val context: Context) {
+ private val resolver = FileResolver(context)
+
companion object {
private const val MAX_DEPTH = 10
private const val MAX_FILES = 500
@@ -19,186 +18,93 @@ class GrepTool(private val context: Context) {
private const val MAX_FILE_BYTES = 1024 * 1024
}
- 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 manageRoots: Map<String, File> by lazy {
- mapOf("storage" to Environment.getExternalStorageDirectory())
- }
-
- private fun resolveRoot(path: String): Pair<File, ToolResult?>? {
- 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
- manageRoots.containsKey(rootName) -> {
- val perm = checkAllFilesAccess()
- if (perm != null) return Pair(File(""), perm)
- manageRoots.getValue(rootName)
- }
- publicRoots.containsKey(rootName) -> {
- val perm = checkMediaPermission()
- if (perm != null) return Pair(File(""), perm)
- 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
- }
- return Pair(target, null)
- }
-
- /** Search files in [path] (or its subtree) for lines matching [pattern]. */
fun grep(path: String, pattern: String, include: String?): ToolResult {
if (pattern.isBlank()) return ToolResult.error("Search pattern cannot be empty.")
-
val regex = try {
Regex(pattern, setOf(RegexOption.IGNORE_CASE))
} catch (e: Exception) {
return ToolResult.error("Invalid regex pattern: ${e.message}")
}
- val resolved = resolveRoot(path) ?: return ToolResult.error(
- "Path '$path' is not allowed. Use one of: files, cache, external, " +
- "downloads, pictures, dcim, documents, storage."
- )
- val (root, permError) = resolved
- if (permError != null) return permError
-
- if (!root.exists()) return ToolResult.error("Path '$path' does not exist.")
-
- val includeGlob = include?.let {
- try {
- Regex(it.replace(".", "\\.").replace("*", ".*").replace("?", "."), RegexOption.IGNORE_CASE)
- } catch (_: Exception) { null }
- }
-
- val results = mutableListOf<String>()
- var filesSearched = 0
- var matchCount = 0
- var aborted = false
-
- fun walk(dir: File, depth: Int) {
- if (aborted || depth > MAX_DEPTH) return
- val entries = dir.listFiles() ?: return
- for (file in entries.sortedBy { it.name.lowercase() }) {
- if (aborted) return
- if (filesSearched >= MAX_FILES) { aborted = true; return }
-
- if (file.isDirectory) {
- walk(file, depth + 1)
- } else if (file.isFile) {
- if (includeGlob != null && !includeGlob.matches(file.name)) continue
- if (file.length() > MAX_FILE_BYTES) continue
- val relPath = relativePath(file)
- filesSearched++
-
+ val resolved = resolver.resolveForRead(path)
+ return when (resolved) {
+ is FileResolver.ResolveResult.PermissionNeeded -> resolved.result
+ is FileResolver.ResolveResult.Error -> ToolResult.error(resolved.message)
+ is FileResolver.ResolveResult.Ok -> {
+ val root = resolved.file
+ val perm = resolver.checkReadPermission(root)
+ if (perm != null) return perm
+ if (!root.exists()) return ToolResult.error("Path '$path' does not exist.")
+
+ val includeGlob = include?.let {
try {
- val text = file.readText(Charsets.UTF_8)
- val lines = text.split("\n")
- for ((idx, line) in lines.withIndex()) {
- if (regex.containsMatchIn(line)) {
- matchCount++
- val display = line.take(200).replace("\t", " ").trim()
- results.add("${relPath}:${idx + 1}: $display")
- if (matchCount >= MAX_MATCHES) { aborted = true; return }
+ Regex(it.replace(".", "\\.").replace("*", ".*").replace("?", "."), RegexOption.IGNORE_CASE)
+ } catch (_: Exception) { null }
+ }
+
+ val results = mutableListOf<String>()
+ var filesSearched = 0
+ var matchCount = 0
+ var aborted = false
+
+ fun walk(dir: File, depth: Int) {
+ if (aborted || depth > MAX_DEPTH) return
+ val entries = dir.listFiles() ?: return
+ for (file in entries.sortedBy { it.name.lowercase() }) {
+ if (aborted) return
+ if (filesSearched >= MAX_FILES) { aborted = true; return }
+ if (file.isDirectory) { walk(file, depth + 1); continue }
+ if (!file.isFile) continue
+ if (includeGlob != null && !includeGlob.matches(file.name)) continue
+ if (file.length() > MAX_FILE_BYTES) continue
+ filesSearched++
+
+ try {
+ val text = file.readText(Charsets.UTF_8)
+ val lines = text.split("\n")
+ for ((idx, line) in lines.withIndex()) {
+ if (regex.containsMatchIn(line)) {
+ matchCount++
+ val display = line.take(200).replace("\t", " ").trim()
+ results.add("${file.absolutePath}:${idx + 1}: $display")
+ if (matchCount >= MAX_MATCHES) { aborted = true; return }
+ }
}
- }
- } catch (_: Exception) {
- // Skip binary or unreadable files silently
+ } catch (_: Exception) { }
}
}
- }
- }
- if (root.isDirectory) {
- walk(root, 0)
- } else if (root.isFile) {
- if (includeGlob == null || includeGlob.matches(root.name)) {
- if (root.length() <= MAX_FILE_BYTES) {
- filesSearched = 1
- try {
- val text = root.readText(Charsets.UTF_8)
- val lines = text.split("\n")
- for ((idx, line) in lines.withIndex()) {
- if (regex.containsMatchIn(line)) {
- matchCount++
- results.add("${root.name}:${idx + 1}: ${line.take(200).trim()}")
- if (matchCount >= MAX_MATCHES) break
- }
+ if (root.isDirectory) walk(root, 0)
+ else if (root.isFile) {
+ if (includeGlob == null || includeGlob.matches(root.name)) {
+ if (root.length() <= MAX_FILE_BYTES) {
+ filesSearched = 1
+ try {
+ val text = root.readText(Charsets.UTF_8)
+ val lines = text.split("\n")
+ for ((idx, line) in lines.withIndex()) {
+ if (regex.containsMatchIn(line)) {
+ matchCount++
+ results.add("${root.name}:${idx + 1}: ${line.take(200).trim()}")
+ if (matchCount >= MAX_MATCHES) break
+ }
+ }
+ } catch (_: Exception) { }
}
- } catch (_: Exception) { }
+ }
}
- }
- }
- return if (results.isEmpty()) {
- ToolResult.ok("No matches found for pattern '$pattern' in '$path'.")
- } else {
- val truncated = if (matchCount >= MAX_MATCHES || filesSearched >= MAX_FILES) {
- "\n…(truncated, max ${MAX_MATCHES} matches)"
- } else ""
- val summary = if (filesSearched > 1) " (searched $filesSearched files)" else ""
- ToolResult.ok("Found ${results.size} match(es) for '$pattern' in '$path'$summary:\n" +
- results.joinToString("\n") + truncated)
- }
- }
-
- private fun relativePath(file: File): String {
- val canonical = file.absolutePath
- // Try to produce a short relative path by stripping common roots
- for (root in sandboxRoots.values + publicRoots.values + manageRoots.values) {
- val rootPath = root?.absolutePath ?: continue
- if (canonical.startsWith(rootPath + "/")) {
- return canonical.substring(rootPath.length + 1)
+ return if (results.isEmpty()) {
+ ToolResult.ok("No matches found for pattern '$pattern' in '$path'.")
+ } else {
+ val truncated = if (matchCount >= MAX_MATCHES || filesSearched >= MAX_FILES) {
+ "\n…(truncated, max $MAX_MATCHES matches)"
+ } else ""
+ val summary = if (filesSearched > 1) " (searched $filesSearched files)" else ""
+ ToolResult.ok("Found ${results.size} match(es) for '$pattern' in '$path'$summary:\n" +
+ results.joinToString("\n") + truncated)
+ }
}
}
- return file.name
- }
-
- private fun checkMediaPermission(): ToolResult? {
- val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
- android.Manifest.permission.READ_MEDIA_IMAGES
- } else {
- android.Manifest.permission.READ_EXTERNAL_STORAGE
- }
- val granted = androidx.core.content.ContextCompat.checkSelfPermission(context, permission) ==
- android.content.pm.PackageManager.PERMISSION_GRANTED
- return if (granted) null else ToolResult.permissionNeeded(
- permission,
- "Searching public folders needs a storage permission."
- )
- }
-
- private fun checkAllFilesAccess(): ToolResult? {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
- return if (Environment.isExternalStorageManager()) null
- else ToolResult.permissionNeeded(
- ToolResult.ALL_FILES_ACCESS,
- "Searching the 'storage' root needs \"All files access\"."
- )
- }
- return checkMediaPermission()
}
}
diff --git a/app/src/main/java/com/gotcha/tools/TerminalTool.kt b/app/src/main/java/com/gotcha/tools/TerminalTool.kt
index 8a067b3..db58a91 100644
--- a/app/src/main/java/com/gotcha/tools/TerminalTool.kt
+++ b/app/src/main/java/com/gotcha/tools/TerminalTool.kt
@@ -2,30 +2,42 @@ package com.gotcha.tools
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
+import java.io.File
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.
+ *
+ * Accepts a [workingDir] to run the command in a specific directory,
+ * and a [timeoutSeconds] override.
*/
class TerminalTool(
- private val timeoutSeconds: Long = 15,
+ private val defaultTimeoutSeconds: Long = 15,
private val maxOutputBytes: Int = 32 * 1024
) {
private val denyPatterns = listOf(
- Regex("""\brm\s+-[a-z]*r"""), // recursive delete
+ Regex("""\brm\s+-[a-z]*r"""),
Regex("""\bmkfs\b"""),
Regex("""\bdd\s+"""),
Regex("""\breboot\b"""),
- Regex("""\bsu\b"""), // privilege escalation attempts
- Regex(""":\(\)\s*\{"""), // fork bomb
+ Regex("""\bsu\b"""),
+ Regex(""":\(\)\s*\{"""),
Regex("""\bsetprop\b""")
)
- suspend fun runCommand(command: String): ToolResult = withContext(Dispatchers.IO) {
+ suspend fun runCommand(
+ command: String,
+ workingDir: String? = null,
+ timeoutSeconds: Int? = null
+ ): ToolResult = withContext(Dispatchers.IO) {
val trimmed = command.trim()
if (trimmed.isEmpty()) return@withContext ToolResult.error("Empty command.")
+
+ val timeout = (timeoutSeconds ?: defaultTimeoutSeconds).toLong()
+ .coerceIn(1, 120)
+
denyPatterns.firstOrNull { it.containsMatchIn(trimmed) }?.let {
return@withContext ToolResult.error(
"Command blocked by safety policy (matched deny-list): $trimmed"
@@ -33,9 +45,15 @@ class TerminalTool(
}
try {
- val process = ProcessBuilder("sh", "-c", trimmed)
+ val pb = ProcessBuilder("sh", "-c", trimmed)
.redirectErrorStream(false)
- .start()
+
+ if (workingDir != null) {
+ val dir = File(workingDir)
+ if (dir.isDirectory) pb.directory(dir)
+ }
+
+ val process = pb.start()
val stdout = process.inputStream.bufferedReader()
val stderr = process.errorStream.bufferedReader()
@@ -46,11 +64,11 @@ class TerminalTool(
val errThread = Thread { drain(stderr::read, errBuilder) }
outThread.start(); errThread.start()
- val finished = process.waitFor(timeoutSeconds, TimeUnit.SECONDS)
+ val finished = process.waitFor(timeout, TimeUnit.SECONDS)
if (!finished) {
process.destroyForcibly()
return@withContext ToolResult.error(
- "Command timed out after ${timeoutSeconds}s and was killed: $trimmed"
+ "Command timed out after ${timeout}s and was killed: $trimmed"
)
}
outThread.join(2000); errThread.join(2000)
@@ -68,7 +86,10 @@ class TerminalTool(
}
}
- private fun drain(read: (CharArray, Int, Int) -> Int, into: StringBuilder) {
+ private fun drain(
+ read: (CharArray, Int, Int) -> Int,
+ into: StringBuilder
+ ) {
val buf = CharArray(4096)
try {
while (true) {
@@ -79,8 +100,6 @@ class TerminalTool(
if (into.length >= maxOutputBytes) into.append("\n…(output capped)")
}
}
- } catch (_: Exception) {
- // Stream closed by process death/timeout.
- }
+ } catch (_: Exception) { }
}
}
diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
index 832fd37..e33e48a 100644
--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
@@ -55,18 +55,34 @@ object ToolDefinitions {
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', and " +
- "'storage' (the whole shared-storage tree, needs All-files access). " +
- "An optional relative sub-path may be appended, e.g. 'downloads/reports'.",
+ "List files and directories at the given path. Accepts absolute paths like " +
+ "'/storage/emulated/0/Download' or paths relative to the working directory. " +
+ "Supports recursive listing, sorting, and filtering.",
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."
- )
+ put("description", "Absolute or relative directory path to list.")
+ }
+ putJsonObject("recursive") {
+ put("type", "boolean")
+ put("description", "List recursively (with depth limit). Default false.")
+ }
+ putJsonObject("sort_by") {
+ put("type", "string")
+ put("description", "Sort by: 'name' (default), 'date', or 'size'.")
+ }
+ putJsonObject("include") {
+ put("type", "string")
+ put("description", "Only show entries whose name contains this substring (case-insensitive).")
+ }
+ putJsonObject("exclude") {
+ put("type", "string")
+ put("description", "Exclude entries whose name contains this substring (case-insensitive).")
+ }
+ putJsonObject("max_depth") {
+ put("type", "integer")
+ put("description", "Max directory depth for recursive listing (1-20). Default 10.")
}
}
putJsonArray("required") { add("path") }
@@ -75,13 +91,31 @@ object ToolDefinitions {
val readFile = tool(
"read_file",
- "Read a text file from an allowed directory (same roots as list_files, including 'storage' " +
- "with All-files access). Output is capped.",
+ "Read any file — text, image, archive, or binary — at the given path. Accepts absolute paths " +
+ "like '/storage/emulated/0/notes.txt' or paths relative to the working directory. " +
+ "Automatically detects file type:\n" +
+ "- Text files: returns content line-by-line with offset/limit support\n" +
+ "- Images: feeds visual content to the vision model so you can 'see' them\n" +
+ "- Archives (zip/apk/aar/jar/war): lists contents; supports reading entries via 'archive.zip/path'\n" +
+ "- PDF & other binaries: returns base64 data\n" +
+ "This tool replaces read_image — use read_file for ALL file reading needs.",
schema {
putJsonObject("properties") {
putJsonObject("path") {
put("type", "string")
- put("description", "File path rooted at an allowed root, e.g. 'files/notes.txt'.")
+ put("description", "Absolute or relative path to the file or directory to read.")
+ }
+ putJsonObject("offset") {
+ put("type", "integer")
+ put("description", "1-indexed line number to start reading from (text files only).")
+ }
+ putJsonObject("limit") {
+ put("type", "integer")
+ put("description", "Max number of lines to return (text files only, default 2000).")
+ }
+ putJsonObject("encoding") {
+ put("type", "string")
+ put("description", "Text encoding (UTF-8, ISO-8859-1, UTF-16). Default UTF-8.")
}
}
putJsonArray("required") { add("path") }
@@ -90,22 +124,27 @@ object ToolDefinitions {
val writeFile = tool(
"write_file",
- "Write or append a text file. Roots 'files', 'cache', 'external' work in the app sandbox; " +
- "the 'storage' root writes anywhere in shared storage but needs All-files access.",
+ "Write or append content to a file at the given path. Accepts absolute paths like " +
+ "'/storage/emulated/0/notes.txt' or paths relative to the working directory. " +
+ "Supports both text and binary content. Parent directories are created automatically.",
schema {
putJsonObject("properties") {
putJsonObject("path") {
put("type", "string")
- put("description", "File path rooted at a sandbox root, e.g. 'files/notes.txt'.")
+ put("description", "Absolute or relative file path to write to.")
}
putJsonObject("content") {
put("type", "string")
- put("description", "Text content to write.")
+ put("description", "Text content to write (or base64-encoded content when binary=true).")
}
putJsonObject("append") {
put("type", "boolean")
put("description", "Append instead of overwrite. Default false.")
}
+ putJsonObject("binary") {
+ put("type", "boolean")
+ put("description", "If true, content is base64-encoded binary data. Default false.")
+ }
}
putJsonArray("required") {
add("path")
@@ -174,13 +213,21 @@ object ToolDefinitions {
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.",
+ "Useful commands: ls, cat, find, getprop, pm list packages, df, uptime, date, id, ps. " +
+ "No root; many system paths are unreadable. Output is capped and commands time out.",
schema {
putJsonObject("properties") {
putJsonObject("command") {
put("type", "string")
- put("description", "Shell command line, e.g. 'getprop ro.build.version.release'")
+ put("description", "Shell command to execute, e.g. 'ls -la /storage/emulated/0'")
+ }
+ putJsonObject("working_dir") {
+ put("type", "string")
+ put("description", "Working directory for the command (absolute path). Defaults to the app's working directory.")
+ }
+ putJsonObject("timeout_seconds") {
+ put("type", "integer")
+ put("description", "Timeout in seconds (1-120). Default 15.")
}
}
putJsonArray("required") { add("command") }
@@ -767,18 +814,14 @@ object ToolDefinitions {
val readImage = tool(
"read_image",
- "Read an image file from an allowed directory and feed its visual content to the " +
- "vision model. The image appears as if you 'see' it — you can describe, analyze, or " +
- "read text from it. Use this for photos, screenshots, diagrams, scanned documents, " +
- "and any image stored on the device. " +
- "Allowed roots are the same as list_files/read_file: 'files', 'cache', 'external', " +
- "'downloads', 'pictures', 'dcim', 'documents', and 'storage' (needs All-files access). " +
- "Supported formats: PNG, JPEG, GIF, WebP, BMP.",
+ "DEPRECATED — use read_file instead which handles images, text, archives, and all other formats. " +
+ "Reads an image file and makes it visible to the vision model. " +
+ "This tool is kept for backward compatibility; new code should call read_file.",
schema {
putJsonObject("properties") {
putJsonObject("path") {
put("type", "string")
- put("description", "Image file path rooted at an allowed root, e.g. 'downloads/photo.jpg'.")
+ put("description", "Absolute or relative path to the image file.")
}
}
putJsonArray("required") { add("path") }
@@ -1069,8 +1112,7 @@ object ToolDefinitions {
glob, grep,
// Web search + fetch
webSearch, webFetch,
- // Image reading (available to both Monitor and Operator)
- readImage,
+ // DEPRECATED: readImage excluded from the active catalog — use read_file instead.
// Tier 3 additions
readScreen, tap, swipe, inputText, globalAction,
readNotifications, dismissNotifications, mediaControl,
diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
index 834c721..00cbe44 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -44,7 +44,6 @@ class ToolExecutor(context: Context) {
private val editTool = EditTool(appContext)
private val globTool = GlobTool(appContext)
private val grepTool = GrepTool(appContext)
- private val visionTool = VisionTool(appContext)
private val accessibilityTool = AccessibilityTool(appContext)
private val notificationTool = NotificationTool(appContext)
private val overlayTool = OverlayTool(appContext)
@@ -100,12 +99,25 @@ class ToolExecutor(context: Context) {
newString = args.requireString("newString") ?: return missing("newString"),
replaceAll = args["replaceAll"]?.jsonPrimitive?.booleanOrNull ?: false
)
- "list_files" -> fileTool.listFiles(args.requireString("path") ?: return missing("path"))
- "read_file" -> fileTool.readFile(args.requireString("path") ?: return missing("path"))
+ "list_files" -> fileTool.listFiles(
+ path = args.requireString("path") ?: return missing("path"),
+ recursive = args["recursive"]?.jsonPrimitive?.booleanOrNull ?: false,
+ sortBy = args.requireString("sort_by"),
+ include = args.requireString("include"),
+ exclude = args.requireString("exclude"),
+ maxDepth = args.requireInt("max_depth")
+ )
+ "read_file" -> fileTool.readFile(
+ path = args.requireString("path") ?: return missing("path"),
+ offset = args.requireInt("offset"),
+ limit = args.requireInt("limit"),
+ encoding = args.requireString("encoding")
+ )
"write_file" -> fileTool.writeFile(
path = args.requireString("path") ?: return missing("path"),
content = args.requireString("content") ?: return missing("content"),
- append = args["append"]?.jsonPrimitive?.booleanOrNull ?: false
+ append = args["append"]?.jsonPrimitive?.booleanOrNull ?: false,
+ binary = args["binary"]?.jsonPrimitive?.booleanOrNull ?: false
)
"open_app" -> systemTool.openApp(args.requireString("package_name") ?: return missing("package_name"))
"set_brightness" -> systemTool.setBrightness(
@@ -115,7 +127,11 @@ class ToolExecutor(context: Context) {
args["enabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("enabled")
)
"set_wallpaper" -> wallpaperTool.setWallpaper(args.requireString("url"))
- "run_command" -> terminalTool.runCommand(args.requireString("command") ?: return missing("command"))
+ "run_command" -> terminalTool.runCommand(
+ command = args.requireString("command") ?: return missing("command"),
+ workingDir = args.requireString("working_dir"),
+ timeoutSeconds = args.requireInt("timeout_seconds") ?: 15
+ )
"call_number" -> phoneTool.callNumber(args.requireString("number") ?: return missing("number"))
"read_call_log" -> phoneTool.readCallLog(args.requireInt("limit") ?: 10)
"find_contact" -> contactsTool.findContact(args.requireString("name") ?: return missing("name"))
@@ -189,7 +205,7 @@ class ToolExecutor(context: Context) {
"todowrite" -> todoTool.todowrite(
parseTodoItems(args["items"]) ?: return missing("items")
)
- "read_image" -> visionTool.readImage(args.requireString("path") ?: return missing("path"))
+ "read_image" -> fileTool.readFile(args.requireString("path") ?: return missing("path"))
"glob" -> globTool.glob(
path = args.requireString("path") ?: return missing("path"),
pattern = args.requireString("pattern") ?: return missing("pattern")
diff --git a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
index c557486..26ca124 100644
--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
@@ -66,7 +66,7 @@ object ToolRegistry {
// Apps (read-only + intent)
"open_app", "list_installed_apps",
// Files & terminal (read-only)
- "list_files", "read_file", "grep", "glob", "read_image",
+ "list_files", "read_file", "grep", "glob",
// Task management
"todowrite",
// User interaction
diff --git a/app/src/main/java/com/gotcha/tools/VisionTool.kt b/app/src/main/java/com/gotcha/tools/VisionTool.kt
deleted file mode 100644
index 5af18a1..0000000
--- a/app/src/main/java/com/gotcha/tools/VisionTool.kt
+++ /dev/null
@@ -1,183 +0,0 @@
-package com.gotcha.tools
-
-import android.content.Context
-import android.graphics.BitmapFactory
-import android.os.Build
-import android.os.Environment
-import android.provider.Settings
-import android.util.Base64
-import java.io.File
-
-/**
- * Tool for reading image files and making their contents visible to the LLM.
- *
- * Returns a structured result with the [IMAGE_DATA_PREFIX] marker that the tool
- * loop in ChatViewModel detects and injects as vision content (user role with
- * image_url) so the model can "see" the image.
- */
-class VisionTool(private val context: Context) {
-
- companion object {
- const val IMAGE_DATA_PREFIX = "IMAGE_DATA:"
- private const val MAX_IMAGE_BYTES = 20 * 1024 * 1024
-
- private val SUPPORTED_EXTENSIONS = setOf("png", "jpg", "jpeg", "gif", "webp", "bmp")
-
- private val MAGIC_PNG = byteArrayOf(-119, 80, 78, 71, 13, 10, 26, 10)
- private val MAGIC_JPEG = byteArrayOf(-1, -40, -1)
- private val MAGIC_GIF = byteArrayOf(71, 73, 70, 56)
- private val MAGIC_WEBP_RIFF = byteArrayOf(82, 73, 70, 70)
- private val MAGIC_WEBP_WEBP = byteArrayOf(87, 69, 66, 80)
- private val MAGIC_BMP = byteArrayOf(66, 77)
- }
-
- 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 manageRoots: Map<String, File> by lazy {
- mapOf("storage" to Environment.getExternalStorageDirectory())
- }
-
- private val allowedRootNames: String
- get() = (sandboxRoots.keys + publicRoots.keys + manageRoots.keys).joinToString(", ")
-
- fun readImage(path: String): ToolResult {
- val normalized = path.trim().trimStart('/')
- val rootName = normalized.substringBefore('/').lowercase()
- val rest = normalized.substringAfter('/', "")
-
- val root: File = when {
- sandboxRoots.containsKey(rootName) -> sandboxRoots[rootName] ?: return badPath(path)
- manageRoots.containsKey(rootName) -> {
- val perm = checkAllFilesAccess()
- if (perm != null) return perm
- manageRoots.getValue(rootName)
- }
- publicRoots.containsKey(rootName) -> {
- val perm = checkMediaPermission()
- if (perm != null) return perm
- publicRoots.getValue(rootName)
- }
- else -> return badPath(path)
- }
-
- 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 ToolResult.error("Path '$path' is outside its allowed root.")
- }
-
- if (!target.exists()) return ToolResult.error("File '$path' does not exist.")
- if (!target.isFile) return ToolResult.error("'$path' is not a regular file.")
-
- val ext = target.extension.lowercase()
- if (ext !in SUPPORTED_EXTENSIONS) {
- return ToolResult.error(
- "Unsupported image format '.$ext'. Supported: ${SUPPORTED_EXTENSIONS.joinToString(", ")}"
- )
- }
-
- if (target.length() > MAX_IMAGE_BYTES) {
- return ToolResult.error(
- "Image too large (${target.length() / 1024 / 1024} MB). Max: ${MAX_IMAGE_BYTES / 1024 / 1024} MB."
- )
- }
-
- return try {
- val bytes = target.readBytes()
-
- val mime = detectMime(bytes)
- if (mime == null) {
- return ToolResult.error("File '$path' is not a recognized image format.")
- }
-
- val opts = BitmapFactory.Options().apply { inJustDecodeBounds = true }
- BitmapFactory.decodeByteArray(bytes, 0, bytes.size, opts)
- if (opts.outWidth <= 0 || opts.outHeight <= 0) {
- return ToolResult.error("File '$path' could not be decoded as an image.")
- }
-
- val base64 = Base64.encodeToString(bytes, Base64.NO_WRAP)
- val displayName = target.name
-
- ToolResult.ok(
- "$IMAGE_DATA_PREFIX$mime:${opts.outWidth}x${opts.outHeight}:${bytes.size}:$displayName:$base64"
- )
- } catch (e: Exception) {
- ToolResult.error("Could not read image '$path': ${e.message}")
- }
- }
-
- private fun detectMime(bytes: ByteArray): String? {
- return when {
- startsWith(bytes, MAGIC_PNG) -> "image/png"
- startsWith(bytes, MAGIC_JPEG) -> "image/jpeg"
- startsWith(bytes, MAGIC_GIF) -> "image/gif"
- startsWith(bytes, MAGIC_BMP) -> "image/bmp"
- startsWith(bytes, MAGIC_WEBP_RIFF) && bytes.size >= 12 &&
- startsWith(bytes.copyOfRange(8, 12), MAGIC_WEBP_WEBP) -> "image/webp"
- else -> null
- }
- }
-
- private fun startsWith(data: ByteArray, prefix: ByteArray): Boolean {
- if (data.size < prefix.size) return false
- for (i in prefix.indices) {
- if (data[i] != prefix[i]) return false
- }
- return true
- }
-
- private fun formatSize(bytes: Long): String = when {
- bytes >= 1024 * 1024 -> "${bytes / (1024 * 1024)} MB"
- bytes >= 1024 -> "${bytes / 1024} KB"
- else -> "$bytes B"
- }
-
- private fun checkMediaPermission(): ToolResult? {
- val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
- android.Manifest.permission.READ_MEDIA_IMAGES
- } else {
- android.Manifest.permission.READ_EXTERNAL_STORAGE
- }
- val granted = androidx.core.content.ContextCompat.checkSelfPermission(context, permission) ==
- android.content.pm.PackageManager.PERMISSION_GRANTED
- return if (granted) null else ToolResult.permissionNeeded(
- permission,
- "Reading images from public folders needs a storage permission. I have requested it — " +
- "please grant it and ask again."
- )
- }
-
- private fun checkAllFilesAccess(): ToolResult? {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
- return if (Environment.isExternalStorageManager()) null
- else ToolResult.permissionNeeded(
- ToolResult.ALL_FILES_ACCESS,
- "Reading images from the 'storage' root needs \"All files access\". I have opened " +
- "that settings page — please enable it for Gotcha and ask again."
- )
- }
- return checkMediaPermission()
- }
-
- 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."
- )
-}