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: run arbitrary shell in Termux via the RUN_COMMAND API (#7)
Durganshu Mishra3702f8141bdd
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex 8e24c9a..1d1fa19 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -68,6 +68,10 @@regardless of grant). --><uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+ <!-- Tier 4: run_termux_command. Declared by Termux with protectionLevel="dangerous", so it+ still needs a runtime grant; Termux additionally requires allow-external-apps=true. -->+ <uses-permission android:name="com.termux.permission.RUN_COMMAND" />+<!-- Needed on API 30+ so open_app can see other launchable apps. --><!-- Health Connect (read-only). Granted through Health Connect's own permissionscreen, not the standard runtime dialog. -->@@ -83,6 +87,9 @@<queries><!-- Health Connect provider app (Android 13 and below). --><package android:name="com.google.android.apps.healthdata" />+ <!-- Termux RUN_COMMAND: without this, targetSdk 30+ package visibility hides Termux and+ the capability probe reports "not installed" on a device that has it. -->+ <package android:name="com.termux" /><intent><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" />@@ -222,6 +229,12 @@android:name=".tools.AlarmReceiver"android:exported="false" />+ <!-- Termux RUN_COMMAND results. Not exported: Termux fires our own PendingIntent, which+ the system delivers under Gotcha's identity. -->+ <receiver+ android:name=".tools.TermuxResultReceiver"+ android:exported="false" />+<!-- Re-registers alarms/timers after reboot (AlarmManager state doesn't survive one).BOOT_COMPLETED is a protected broadcast only the system can send. --><receiverdiff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.ktindex 9cc41ef..74e43a8 100644--- a/app/src/main/java/com/gotcha/MainActivity.kt+++ b/app/src/main/java/com/gotcha/MainActivity.kt@@ -33,6 +33,7 @@ import androidx.compose.runtime.setValueimport androidx.compose.ui.Modifierimport androidx.compose.ui.graphics.toArgbimport androidx.core.app.NotificationManagerCompat+import androidx.core.content.ContextCompatimport androidx.lifecycle.lifecycleScopeimport com.gotcha.agent.ChatViewModelimport com.gotcha.audio.AudioApi@@ -54,6 +55,7 @@ import com.gotcha.notifications.ServerMessagesimport com.gotcha.service.AssistiveBallServiceimport com.gotcha.service.GotchaDeviceAdminReceiverimport com.gotcha.tools.ScreenPerception+import com.gotcha.tools.TermuxToolimport com.gotcha.tools.ToolResultimport com.gotcha.ui.AppDrawerContentimport com.gotcha.ui.ChatScreen@@ -185,6 +187,25 @@ class MainActivity : ComponentActivity() {Toast.makeText(this, message, Toast.LENGTH_SHORT).show()}+ /**+ * Termux's RUN_COMMAND permission. It is a runtime permission (Termux declares it+ * `dangerous`), but granting it is only half the journey — Termux also needs+ * `allow-external-apps=true` — so it gets its own launcher rather than the Settings row's+ * generic path, and lands the user in Termux afterwards.+ */+ private val termuxPermissionLauncher =+ registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->+ if (granted) {+ openTermuxForExternalApps()+ } else {+ Toast.makeText(+ this,+ "Termux command permission denied — the assistant can't run Termux commands.",+ Toast.LENGTH_LONG+ ).show()+ }+ }+/** Requests all runtime permissions at once on first launch. */private val firstLaunchLauncher =registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { _ ->@@ -334,10 +355,41 @@ class MainActivity : ComponentActivity() {}}ToolResult.HEALTH_CONNECT -> requestHealthConnect()+ ToolResult.TERMUX_ACCESS -> requestTermuxAccess()// Runtime permissions are mapped in Settings → Permissions; skip here.}}+ /**+ * Grants Termux command access. Two steps, and only the first is ours: the runtime+ * permission, then Termux's own `allow-external-apps` property, which lives in Termux's+ * private storage and can only be set inside Termux.+ */+ private fun requestTermuxAccess() {+ val granted = ContextCompat.checkSelfPermission(this, TermuxTool.PERMISSION_RUN_COMMAND) ==+ android.content.pm.PackageManager.PERMISSION_GRANTED+ if (granted) {+ openTermuxForExternalApps()+ } else {+ termuxPermissionLauncher.launch(TermuxTool.PERMISSION_RUN_COMMAND)+ }+ }++ /** Opens Termux with the one manual step spelled out; no-op if Termux is not installed. */+ private fun openTermuxForExternalApps() {+ val launch = packageManager.getLaunchIntentForPackage(TermuxTool.TERMUX_PACKAGE)+ if (launch == null) {+ Toast.makeText(this, "Termux is not installed — install it from F-Droid.", Toast.LENGTH_LONG).show()+ return+ }+ Toast.makeText(+ this,+ "In Termux, add `allow-external-apps=true` to ~/.termux/termux.properties, then restart Termux.",+ Toast.LENGTH_LONG+ ).show()+ startActivity(launch)+ }+/*** Opens Health Connect's permission screen, or steers to the Play listing when* no provider is installed (Android 13 and below ship it as a separate app).diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.ktindex 7631db0..0ac305e 100644--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt@@ -1144,6 +1144,7 @@ class AgentEngine(val accEnabled = DeviceCapabilities.accessibilityEnabled(app)val notifEnabled = DeviceCapabilities.notificationListenerEnabled(app)val deviceAdmin = DeviceCapabilities.deviceAdminActive(app)+ val termux = com.gotcha.tools.TermuxTool(app).status()val vpnActive = try {val cm = app.getSystemService(@@ -1165,6 +1166,17 @@ class AgentEngine(appendLine(" Accessibility service enabled: ${if (accEnabled) "yes" else "no"}")appendLine(" Notification listener enabled: ${if (notifEnabled) "yes" else "no"}")appendLine(" Device admin active: ${if (deviceAdmin) "yes" else "no"}")+ // run_termux_command is withheld unless Termux is installed, and refuses until its+ // RUN_COMMAND permission is granted, so this line is how the model knows to say+ // "install Termux" or "allow the permission" rather than just failing.+ appendLine(+ if (termux.installed) {+ " Termux installed: yes (version ${termux.versionName ?: "unknown"}, " ++ "RUN_COMMAND granted: ${if (termux.permissionGranted) "yes" else "no"})"+ } else {+ " Termux installed: no (so run_termux_command is unavailable — no Linux user-space)"+ }+ )// Tools depending on a capability that is "no" here are withheld from// the tool list, so these lines are the model's only way to explain// what the user should enable.diff --git a/app/src/main/java/com/gotcha/tools/CapabilityCatalog.kt b/app/src/main/java/com/gotcha/tools/CapabilityCatalog.ktindex b23616c..ed0e482 100644--- a/app/src/main/java/com/gotcha/tools/CapabilityCatalog.kt+++ b/app/src/main/java/com/gotcha/tools/CapabilityCatalog.kt@@ -47,6 +47,14 @@ enum class Capability(setOf("run_root_command", "write_secure_settings")),+ TERMUX(+ // Reads as "it needs <label>, which is not available on this device right now."+ "Termux (the Linux terminal app, installed from F-Droid)",+ // Gated on Termux being installed, not on the RUN_COMMAND grant: gating on the grant+ // would hide the only tool that can raise the prompt for it. See DeviceCapabilities.+ setOf("run_termux_command")+ ),+HEALTH_CONNECT("Health Connect",setOf("get_health_summary", "get_health_records")diff --git a/app/src/main/java/com/gotcha/tools/DeviceCapabilities.kt b/app/src/main/java/com/gotcha/tools/DeviceCapabilities.ktindex fe47e02..f0704ae 100644--- a/app/src/main/java/com/gotcha/tools/DeviceCapabilities.kt+++ b/app/src/main/java/com/gotcha/tools/DeviceCapabilities.kt@@ -34,6 +34,7 @@ object DeviceCapabilities {if (notificationListenerEnabled(context)) add(Capability.NOTIFICATION_LISTENER)if (deviceAdminActive(context)) add(Capability.DEVICE_ADMIN)if (rootAvailable()) add(Capability.ROOT)+ if (termuxInstalled(context)) add(Capability.TERMUX)if (healthConnectPresent(context)) add(Capability.HEALTH_CONNECT)if (overlayAllowed(context)) add(Capability.OVERLAY)}@@ -81,6 +82,18 @@ object DeviceCapabilities {androidx.health.connect.client.HealthConnectClient.SDK_AVAILABLE}.getOrDefault(false)+ /**+ * Whether Termux is installed — deliberately *not* whether its `RUN_COMMAND` permission is+ * granted, for the same reason [healthConnectPresent] ignores its grants: the permission is+ * requested on demand by [TermuxTool], so gating on the grant would hide the only tool that+ * can ever raise the prompt. Needs `<package android:name="com.termux"/>` in the manifest's+ * `<queries>` block to see past targetSdk 30+ package visibility.+ */+ fun termuxInstalled(context: Context): Boolean =+ runCatching {+ context.packageManager.getPackageInfo(TermuxTool.TERMUX_PACKAGE, 0)+ }.isSuccess+/*** Presence of a `su` binary, cached for the process.*diff --git a/app/src/main/java/com/gotcha/tools/TermuxResultReceiver.kt b/app/src/main/java/com/gotcha/tools/TermuxResultReceiver.ktnew file mode 100644index 0000000..9f009aa--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/TermuxResultReceiver.kt@@ -0,0 +1,35 @@+package com.gotcha.tools++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent++/**+ * Receives the result of a Termux RUN_COMMAND, sent back through the [android.app.PendingIntent]+ * that [TermuxTool] attached to the request.+ *+ * Not exported, and it does not need to be: a PendingIntent is fired by the system with the+ * *creator's* identity, so Termux triggering it reaches this receiver without Termux ever having+ * permission to broadcast to us directly.+ */+class TermuxResultReceiver : BroadcastReceiver() {++ override fun onReceive(context: Context, intent: Intent) {+ val requestCode = intent.getIntExtra(EXTRA_REQUEST_CODE, -1)+ val bundle = intent.getBundleExtra(TermuxTool.RESULT_BUNDLE) ?: return+ // An unknown code means the caller already gave up (timed out) — nothing to resume.+ if (requestCode >= 0) TermuxTool.completeResult(requestCode, bundle)+ }++ companion object {+ private const val EXTRA_REQUEST_CODE = "com.gotcha.termux.REQUEST_CODE"++ /**+ * The intent Termux will send back. Explicit, so the PendingIntent can safely be mutable+ * — Termux only gets to add its result bundle, not to redirect the delivery.+ */+ internal fun resultIntent(context: Context, requestCode: Int): Intent =+ Intent(context, TermuxResultReceiver::class.java)+ .putExtra(EXTRA_REQUEST_CODE, requestCode)+ }+}diff --git a/app/src/main/java/com/gotcha/tools/TermuxTool.kt b/app/src/main/java/com/gotcha/tools/TermuxTool.ktnew file mode 100644index 0000000..5457cc1--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/TermuxTool.kt@@ -0,0 +1,272 @@+package com.gotcha.tools++import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.os.Build+import android.os.Bundle+import androidx.core.content.ContextCompat+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.withTimeoutOrNull+import java.util.concurrent.ConcurrentHashMap+import java.util.concurrent.atomic.AtomicInteger++/**+ * Tier 4 — arbitrary shell inside Termux, via Termux's official RUN_COMMAND plugin API.+ *+ * Stock Android has no usable user-space: no `pkg`/`apt`, no `python3`, few binaries. Termux+ * ships a full one, but it cannot be embedded — it runs under its own uid with its own rootfs+ * at `/data/data/com.termux/files` inside a separate SELinux context, so Gotcha can neither+ * exec its binaries nor read its files. What Termux *does* expose is+ * `com.termux.app.RunCommandService`: we send it a command, it runs it in the background (no+ * terminal pop-up) and returns stdout/stderr/exit code through a [PendingIntent].+ *+ * Two things must be true before that works, and only the first is detectable:+ * 1. `com.termux.permission.RUN_COMMAND` is granted. It is a **`dangerous`** permission that+ * Termux itself declares, so listing it in the manifest is not enough — it needs a runtime+ * grant, raised through [ToolResult.TERMUX_ACCESS]. A caveat worth knowing: a custom+ * dangerous permission whose defining app was installed *after* Gotcha may not be+ * grantable until Gotcha is updated or reinstalled.+ * 2. `allow-external-apps=true` is set in Termux's `~/.termux/termux.properties`. That file+ * lives in Termux's private storage, so we cannot read it. When it is false Termux drops+ * the intent silently and no result ever arrives — indistinguishable from here from a slow+ * command, which is why the timeout message names both causes.+ *+ * Availability is gated on the Termux package being *installed* ([Capability.TERMUX]), not on+ * the grant — gating on the grant would hide the only tool that can raise the prompt. The+ * unprivileged [TerminalTool] (`run_command`) stays the tool for Gotcha's own sandbox, which is+ * invisible from Termux's uid.+ */+class TermuxTool(+ private val context: Context,+ private val defaultTimeoutSeconds: Int = 60,+ private val maxOutputBytes: Int = 32 * 1024+) {++ /** What the model needs to know about Termux, rendered into the `<env>` block each turn. */+ data class TermuxStatus(+ val installed: Boolean,+ val permissionGranted: Boolean,+ val versionName: String?+ )++ /**+ * Irreversible, device-destroying operations we refuse even here. Deliberately+ * [RootTool]'s narrow list rather than [TerminalTool]'s: `rm -r` inside Termux's own+ * `$HOME` is ordinary housekeeping, and `pkg` needs it.+ */+ private val denyPatterns = listOf(+ Regex("""\bmkfs\b"""), // reformat a filesystem+ Regex("""\bdd\b[^\n]*\bof=/dev/"""), // raw write to a block device+ Regex("""\brm\s+-[a-z]*r[a-z]*f?\s+/(\s|$)"""), // rm -rf / (wipe the root tree)+ Regex("""\bfastboot\b"""),+ Regex("""\brecovery\b[^\n]*--wipe""")+ )++ fun status(): TermuxStatus {+ val info = runCatching { context.packageManager.getPackageInfo(TERMUX_PACKAGE, 0) }.getOrNull()+ val granted = runCatching {+ ContextCompat.checkSelfPermission(context, PERMISSION_RUN_COMMAND) ==+ PackageManager.PERMISSION_GRANTED+ }.getOrDefault(false)+ return TermuxStatus(installed = info != null, permissionGranted = granted, versionName = info?.versionName)+ }++ /** Run [command] through Termux's `sh`, returning stdout/stderr/exit code. */+ suspend fun runCommand(+ command: String,+ workingDir: String? = null,+ timeoutSeconds: Int? = null+ ): ToolResult {+ val trimmed = command.trim()+ validate(trimmed)?.let { return it }++ val status = status()+ if (!status.installed) return notInstalled()+ if (!status.permissionGranted) return permissionNeeded()++ val timeout = (timeoutSeconds ?: defaultTimeoutSeconds).coerceIn(1, MAX_TIMEOUT_SECONDS)+ val requestCode = nextRequestCode.getAndIncrement()+ val deferred = CompletableDeferred<Bundle>()+ pendingResults[requestCode] = deferred+ try {+ val pendingIntent = PendingIntent.getBroadcast(+ context,+ requestCode,+ TermuxResultReceiver.resultIntent(context, requestCode),+ pendingIntentFlags()+ )+ runCatching { context.startService(commandIntent(trimmed, workingDir, pendingIntent)) }+ .exceptionOrNull()+ ?.let { return startFailed(it) }++ val bundle = withTimeoutOrNull(timeout * 1000L) { deferred.await() }+ ?: return timedOut(trimmed, timeout)+ return formatResult(bundle)+ } finally {+ pendingResults.remove(requestCode)+ }+ }++ /** Turn Termux's result bundle into a [ToolResult]. Split out so it is testable without Termux. */+ internal fun formatResult(bundle: Bundle): ToolResult {+ val err = bundle.numeric(RESULT_ERR) ?: 0+ val errmsg = bundle.getString(RESULT_ERRMSG)?.trim().orEmpty()+ if (err != 0) {+ return ToolResult.error(+ "Termux refused or could not run the command (error code $err)" ++ if (errmsg.isEmpty()) "." else ": ${cap(errmsg)}"+ )+ }+ val exit = bundle.numeric(RESULT_EXIT_CODE) ?: -1+ val stdout = bundle.getString(RESULT_STDOUT).orEmpty()+ val stderr = bundle.getString(RESULT_STDERR).orEmpty()+ val message = buildString {+ append("exit code: $exit")+ if (stdout.isNotEmpty()) append("\nstdout:\n${cap(stdout)}")+ if (stderr.isNotEmpty()) append("\nstderr:\n${cap(stderr)}")+ if (stdout.isEmpty() && stderr.isEmpty()) append("\n(no output)")+ if (wasTruncatedByTermux(bundle, RESULT_STDOUT_ORIGINAL_LENGTH, stdout) ||+ wasTruncatedByTermux(bundle, RESULT_STDERR_ORIGINAL_LENGTH, stderr)+ ) {+ append("\n…(Termux truncated the output at its ~100KB result limit)")+ }+ if (errmsg.isNotEmpty()) append("\nTermux note: ${cap(errmsg)}")+ }+ return ToolResult(success = exit == 0, message = message)+ }++ /** Cheap checks that need neither Termux nor a permission, so they report the real problem first. */+ private fun validate(trimmed: String): ToolResult? {+ if (trimmed.isEmpty()) {+ return ToolResult.error(+ "Empty command. Provide a shell command to run in Termux (e.g. 'pkg install python -y')."+ )+ }+ if (trimmed.length > MAX_COMMAND_CHARS) {+ return ToolResult.error(+ "Command is ${trimmed.length} characters, over Termux's ~${MAX_COMMAND_CHARS / 1024}KB limit for a " ++ "single command. You may write the script to a file with write_file and run that file instead."+ )+ }+ denyPatterns.firstOrNull { it.containsMatchIn(trimmed) }?.let {+ return ToolResult.error(+ "Command blocked by safety policy (irreversible/device-destroying): $trimmed. You may use available " ++ "tools (list_files, read_file, grep) instead for safer operations."+ )+ }+ return null+ }++ private fun commandIntent(command: String, workingDir: String?, result: PendingIntent): Intent =+ Intent(ACTION_RUN_COMMAND).apply {+ setClassName(TERMUX_PACKAGE, RUN_COMMAND_SERVICE)+ putExtra(EXTRA_COMMAND_PATH, "$TERMUX_BIN_PREFIX/sh")+ putExtra(EXTRA_ARGUMENTS, arrayOf("-c", command))+ putExtra(EXTRA_WORKDIR, workingDir?.trim()?.takeIf { it.isNotEmpty() } ?: TERMUX_HOME)+ // Headless: run without opening a terminal session in front of the user.+ putExtra(EXTRA_BACKGROUND, true)+ putExtra(EXTRA_PENDING_INTENT, result)+ }++ /**+ * Termux writes the result bundle into the intent it sends back, so the PendingIntent has+ * to be mutable. It is explicit (it names our own receiver), so this is not the+ * implicit-mutable pattern lint warns about.+ */+ private fun pendingIntentFlags(): Int {+ var flags = PendingIntent.FLAG_ONE_SHOT+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) flags = flags or PendingIntent.FLAG_MUTABLE+ return flags+ }++ private fun notInstalled() = ToolResult.error(+ "Termux is not installed, so there is no Linux user-space to run this in. You may ask the user to install " ++ "Termux from F-Droid (the Play Store build is unmaintained), or use run_command for the plain " ++ "unprivileged shell available inside Gotcha's own sandbox."+ )++ private fun permissionNeeded() = ToolResult.permissionNeeded(+ ToolResult.TERMUX_ACCESS,+ "Running commands in Termux needs Termux's \"Run commands\" permission, which has not been granted. " ++ "I have asked for it — please allow it, then in Termux add the line `allow-external-apps=true` to " ++ "`~/.termux/termux.properties` and restart Termux, and ask again. (If no permission dialog appeared, " ++ "Termux was installed after Gotcha — reinstall or update Gotcha so Android can grant it.)"+ )++ private fun startFailed(cause: Throwable) = ToolResult.error(+ "Could not reach Termux's RUN_COMMAND service: ${cause.message}. Termux may have been disabled or stopped " ++ "by the system. You may open Termux once and ask again, or use run_command for the app's own sandbox."+ )++ private fun timedOut(command: String, timeout: Int) = ToolResult.error(+ "No result from Termux after ${timeout}s for: $command. Two things cause this and I cannot tell them " ++ "apart: the command may still be running in Termux (I cannot kill another app's process, so check " ++ "Termux itself), or `allow-external-apps=true` is missing from `~/.termux/termux.properties`, in which " ++ "case Termux silently ignored the request. You may retry with a larger timeout_seconds."+ )++ private fun cap(text: String): String =+ if (text.length <= maxOutputBytes) text else text.take(maxOutputBytes) + "\n…(output capped)"++ private fun wasTruncatedByTermux(bundle: Bundle, lengthKey: String, received: String): Boolean =+ (bundle.numeric(lengthKey) ?: received.length) > received.length++ /** Termux sends lengths as strings and codes as ints; tolerate either for every numeric field. */+ private fun Bundle.numeric(key: String): Int? {+ if (!containsKey(key)) return null+ runCatching { getString(key) }.getOrNull()?.let { return it.trim().toIntOrNull() }+ return runCatching { getInt(key) }.getOrNull()+ }++ companion object {+ const val TERMUX_PACKAGE = "com.termux"+ const val PERMISSION_RUN_COMMAND = "com.termux.permission.RUN_COMMAND"++ private const val RUN_COMMAND_SERVICE = "com.termux.app.RunCommandService"+ private const val ACTION_RUN_COMMAND = "com.termux.RUN_COMMAND"+ private const val EXTRA_COMMAND_PATH = "com.termux.RUN_COMMAND_PATH"+ private const val EXTRA_ARGUMENTS = "com.termux.RUN_COMMAND_ARGUMENTS"+ private const val EXTRA_WORKDIR = "com.termux.RUN_COMMAND_WORKDIR"+ private const val EXTRA_BACKGROUND = "com.termux.RUN_COMMAND_BACKGROUND"+ private const val EXTRA_PENDING_INTENT = "com.termux.RUN_COMMAND_PENDING_INTENT"++ private const val TERMUX_FILES = "/data/data/com.termux/files"+ private const val TERMUX_BIN_PREFIX = "$TERMUX_FILES/usr/bin"+ const val TERMUX_HOME = "$TERMUX_FILES/home"++ // Result-bundle keys, from termux-shared's TermuxConstants.+ internal const val RESULT_BUNDLE = "result"+ internal const val RESULT_STDOUT = "stdout"+ internal const val RESULT_STDOUT_ORIGINAL_LENGTH = "stdout_original_length"+ internal const val RESULT_STDERR = "stderr"+ internal const val RESULT_STDERR_ORIGINAL_LENGTH = "stderr_original_length"+ internal const val RESULT_EXIT_CODE = "exitCode"+ internal const val RESULT_ERR = "err"+ internal const val RESULT_ERRMSG = "errmsg"++ /** Termux caps a single command near 128KB; leave headroom for the rest of the intent. */+ private const val MAX_COMMAND_CHARS = 100 * 1024++ /** `pkg install` is slow, so this is far above [TerminalTool]'s 120s ceiling. */+ private const val MAX_TIMEOUT_SECONDS = 600++ private val nextRequestCode = AtomicInteger(1)++ /**+ * In-flight commands, keyed by PendingIntent request code so concurrent calls cannot+ * collide. Held in memory only: if Gotcha's process dies the awaiting coroutine and the+ * whole agent turn die with it, so persisting results would have nothing left to resume.+ */+ private val pendingResults = ConcurrentHashMap<Int, CompletableDeferred<Bundle>>()++ /** Hands a result from [TermuxResultReceiver] to the coroutine waiting on it. */+ internal fun completeResult(requestCode: Int, bundle: Bundle) {+ pendingResults.remove(requestCode)?.complete(bundle)+ }++ /** Test seam: awaits nothing, just exposes whether a request is still outstanding. */+ internal fun isPending(requestCode: Int): Boolean = pendingResults.containsKey(requestCode)+ }+}diff --git a/app/src/main/java/com/gotcha/tools/ToolCategories.kt b/app/src/main/java/com/gotcha/tools/ToolCategories.ktindex b833ad6..67df16b 100644--- a/app/src/main/java/com/gotcha/tools/ToolCategories.kt+++ b/app/src/main/java/com/gotcha/tools/ToolCategories.kt@@ -30,7 +30,7 @@ object ToolCategories {"take_photo","start_audio_recording", "stop_audio_recording","pause_audio_recording", "resume_audio_recording",- "run_command", "run_root_command",+ "run_command", "run_root_command", "run_termux_command","show_overlay", "hide_overlay","lock_screen", "disable_camera", "set_password_policy","dismiss_notifications", "media_control",diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.ktindex 6787712..4394ea8 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -1828,6 +1828,43 @@ object ToolDefinitions {})+ val runTermuxCommand = tool(+ "run_termux_command",+ "Run a shell command inside Termux, which has a real Linux user-space — `pkg install`/`apt`, " ++ "python3, git, ssh, compilers. Use this for anything that needs a package installed or a " ++ "non-trivial script; it runs headlessly, with no terminal opening in front of the user. " ++ "Termux runs under its own user id, so Gotcha's working directory and app files are NOT " ++ "visible here — use run_command for those. Only offered when Termux is installed.",+ schema {+ putJsonObject("properties") {+ putJsonObject("command") {+ put("type", "string")+ put(+ "description",+ "Shell command line to run in Termux, e.g. 'pkg install python -y' or " ++ "'python3 -c \"print(1+1)\"'. Pipes and multiple statements are fine."+ )+ }+ putJsonObject("working_dir") {+ put("type", "string")+ put(+ "description",+ "Absolute path inside Termux's filesystem. Defaults to Termux's home " ++ "(/data/data/com.termux/files/home)."+ )+ }+ putJsonObject("timeout_seconds") {+ put("type", "integer")+ put(+ "description",+ "Timeout in seconds (1-600). Default 60 — raise it for package installs and builds."+ )+ }+ }+ putJsonArray("required") { add("command") }+ }+ )+val writeSecureSettings = tool("write_secure_settings","Write an Android system/secure/global setting, e.g. secure/location_mode=3. " +@@ -2234,7 +2271,7 @@ object ToolDefinitions {lockScreen, disableCamera, setPasswordPolicy,// Tier 4 additions: privileged / rooted execution- checkRoot, runRootCommand, writeSecureSettings,+ checkRoot, runRootCommand, runTermuxCommand, writeSecureSettings,searchSkills,diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.ktindex f2fd4f2..9205366 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -64,6 +64,7 @@ class ToolExecutor(// Tier 4 toolsprivate val rootTool = RootTool()+ private val termuxTool = TermuxTool(appContext)private val healthTool = HealthTool(appContext)private val actionLog = ActionLog(appContext)@@ -499,6 +500,11 @@ class ToolExecutor(DeviceCapabilities.setRootAvailable(it.message.contains("Root IS available"))}"run_root_command" -> rootTool.runRootCommand(args.requireString("command") ?: return missing("command"))+ "run_termux_command" -> termuxTool.runCommand(+ command = args.requireString("command") ?: return missing("command"),+ workingDir = args.requireString("working_dir"),+ timeoutSeconds = args.requireInt("timeout_seconds")+ )"write_secure_settings" -> rootTool.writeSecureSetting(namespace = args.requireString("namespace") ?: return missing("namespace"),key = args.requireString("key") ?: return missing("key"),diff --git a/app/src/main/java/com/gotcha/tools/ToolResult.kt b/app/src/main/java/com/gotcha/tools/ToolResult.ktindex 26b9c0b..b36b438 100644--- a/app/src/main/java/com/gotcha/tools/ToolResult.kt+++ b/app/src/main/java/com/gotcha/tools/ToolResult.kt@@ -49,6 +49,14 @@ data class ToolResult(*/const val HEALTH_CONNECT = "special:health_connect"+ /**+ * Marker for Termux's `RUN_COMMAND` permission. Unusual in this list in that it *is* a+ * real runtime permission — but one declared by another app, needing Termux's+ * allow-external-apps property enabled alongside it, so the host handles both halves of+ * the journey rather than firing a bare permission dialog.+ */+ const val TERMUX_ACCESS = "special:termux_access"+fun ok(message: String) = ToolResult(true, message)fun error(message: String) = ToolResult(false, message)fun permissionNeeded(permission: String, message: String) =diff --git a/app/src/main/java/com/gotcha/ui/PermissionItems.kt b/app/src/main/java/com/gotcha/ui/PermissionItems.ktindex be7a8c6..16f31c5 100644--- a/app/src/main/java/com/gotcha/ui/PermissionItems.kt+++ b/app/src/main/java/com/gotcha/ui/PermissionItems.kt@@ -25,7 +25,14 @@ data class PermissionItem(val isGranted: (Context) -> Boolean,/** Additional runtime permissions requested together with [androidPermission] (e.g. the* matching WRITE permission for a read/write pair). Requested in the same system dialog. */- val extraPermissions: List<String> = emptyList()+ val extraPermissions: List<String> = emptyList(),+ /**+ * Whether to show the row at all. Defaults to always. Needed for permissions another app+ * declares: until that app is installed the permission does not exist, so Android denies the+ * request without a dialog — a dead toggle, and one that would keep its group flagged as+ * "has something ungranted" forever.+ */+ val isRelevant: (Context) -> Boolean = { true })// Declarative catalog of every permission the app can request; length is inherent.@@ -193,6 +200,18 @@ fun allPermissionGroups(): List<PermissionGroup> = listOf() == AppOpsManager.MODE_ALLOWED}),+ // A runtime permission rather than a special marker, so the standard toggle can+ // request it. Termux declares it, so it only exists once Termux is installed — hence+ // isRelevant. The allow-external-apps half has to be done inside Termux either way.+ PermissionItem(+ "Termux Commands (Optional)",+ "Run shell commands and install packages in Termux. Also needs " ++ "`allow-external-apps=true` in Termux's ~/.termux/termux.properties.",+ com.gotcha.tools.TermuxTool.PERMISSION_RUN_COMMAND,+ null,+ { c -> checkPerm(c, com.gotcha.tools.TermuxTool.PERMISSION_RUN_COMMAND) },+ isRelevant = { c -> com.gotcha.tools.DeviceCapabilities.termuxInstalled(c) }+ ),PermissionItem("Device Admin (Optional)","DANGEROUS: Lock screen, enforce password policy. Only enable if you really need these.",diff --git a/app/src/main/java/com/gotcha/ui/PermissionsSection.kt b/app/src/main/java/com/gotcha/ui/PermissionsSection.ktindex 2a124b0..aafb57f 100644--- a/app/src/main/java/com/gotcha/ui/PermissionsSection.kt+++ b/app/src/main/java/com/gotcha/ui/PermissionsSection.kt@@ -65,8 +65,11 @@ fun PermissionsSection(packageName: String) {)for (group in groups) {+ // Rows for permissions another app declares disappear until that app is installed.+ val items = remember(resumeSignal, group) { group.items.filter { it.isRelevant(context) } }+ if (items.isEmpty()) continueval hasUngrantedPermission = remember(resumeSignal, group) {- group.items.any { !it.isGranted(context) }+ items.any { !it.isGranted(context) }}val expanded = userToggledGroups[group.name] ?: hasUngrantedPermissionRow(@@ -89,7 +92,7 @@ fun PermissionsSection(packageName: String) {AnimatedVisibility(visible = expanded) {Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {- for (item in group.items) {+ for (item in items) {// Read live permission state from Android, re-checked on every resumeval granted = remember(resumeSignal) { item.isGranted(context) }PermissionRow(@@ -186,6 +189,10 @@ internal fun openSpecialAccess(context: android.content.Context, marker: String,`package` = it.`package`}}+ // Only the Termux half of the journey: this path has no Activity to request the runtime+ // permission from, and the allow-external-apps property can only be set inside Termux.+ // MainActivity.requestTermuxAccess handles both halves when the agent asks.+ ToolResult.TERMUX_ACCESS -> context.packageManager.getLaunchIntentForPackage("com.termux")else -> null}if (intent != null) {diff --git a/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt b/app/src/test/java/com/gotcha/tools/TermuxToolTest.ktnew file mode 100644index 0000000..8d485b8--- /dev/null+++ b/app/src/test/java/com/gotcha/tools/TermuxToolTest.kt@@ -0,0 +1,231 @@+package com.gotcha.tools++import android.content.Context+import android.content.pm.PackageInfo+import android.os.Bundle+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.test.runTest+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config++/**+ * `run_termux_command`. Real Termux cannot exist on the JVM, so this covers everything up to and+ * after the intent: the {installed, granted} decision table via ShadowPackageManager, the+ * validation guards, and result-bundle parsing — which is why [TermuxTool.formatResult] is a+ * separate function rather than inlined into the coroutine.+ *+ * The live round-trip (a real `pkg install`) is manual by necessity; see+ * docs/FEATURE_TEST_COVERAGE.md.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [30, 34])+class TermuxToolTest {++ private val context: Context = ApplicationProvider.getApplicationContext()+ private val tool = TermuxTool(context)++ private fun installTermux() {+ shadowOf(context.packageManager).installPackage(+ PackageInfo().apply {+ packageName = TermuxTool.TERMUX_PACKAGE+ versionName = "0.118.0"+ }+ )+ }++ private fun grantRunCommand() {+ shadowOf(ApplicationProvider.getApplicationContext<android.app.Application>())+ .grantPermissions(TermuxTool.PERMISSION_RUN_COMMAND)+ }++ // ---- status / decision table ----++ @Test+ fun `status reports termux absent on a clean device`() {+ val status = tool.status()+ assertFalse(status.installed)+ assertNull(status.versionName)+ }++ @Test+ fun `status reports the installed version and grant`() {+ installTermux()+ grantRunCommand()++ val status = tool.status()+ assertTrue(status.installed)+ assertTrue(status.permissionGranted)+ assertEquals("0.118.0", status.versionName)+ }++ @Test+ fun `without termux the tool points at run_command instead`() = runTest {+ val result = tool.runCommand("echo hello")++ assertFalse(result.success)+ assertNull("no permission prompt is useful without Termux", result.needsPermission)+ assertTrue(result.message.contains("not installed"))+ assertTrue(result.message.contains("run_command"))+ }++ @Test+ fun `with termux but no permission the tool asks for the grant`() = runTest {+ installTermux()++ val result = tool.runCommand("echo hello")++ assertFalse(result.success)+ assertEquals(ToolResult.TERMUX_ACCESS, result.needsPermission)+ assertTrue(+ "must name the property the user has to set: ${result.message}",+ result.message.contains("allow-external-apps")+ )+ }++ @Test+ fun `a granted call reaches termux and then times out waiting for a result`() = runTest {+ installTermux()+ grantRunCommand()++ val result = tool.runCommand("echo hello", timeoutSeconds = 1)++ // No Termux exists to answer the PendingIntent, so this is the timeout path — and it has+ // to name both indistinguishable causes.+ assertFalse(result.success)+ assertNull(result.needsPermission)+ assertTrue(result.message.contains("still be running"))+ assertTrue(result.message.contains("allow-external-apps"))+ }++ // ---- validation guards (checked before availability, so they report the real problem) ----++ @Test+ fun `empty command is rejected`() = runTest {+ val result = tool.runCommand(" ")+ assertFalse(result.success)+ assertTrue(result.message.contains("Empty command"))+ }++ @Test+ fun `device-destroying commands are blocked by the deny-list`() = runTest {+ installTermux()+ grantRunCommand()+ listOf("mkfs.ext4 /dev/block/sda", "dd if=/dev/zero of=/dev/block/sda", "rm -rf / ", "fastboot oem unlock")+ .forEach { command ->+ val result = tool.runCommand(command)+ assertFalse("expected '$command' to be blocked", result.success)+ assertTrue(result.message.contains("safety policy"))+ }+ }++ @Test+ fun `rm -r inside termux home is allowed unlike run_command`() = runTest {+ // TerminalTool blocks every `rm -r`; here it is ordinary housekeeping, so the deny-list+ // must let it through to the (absent) Termux rather than refusing it outright.+ val result = tool.runCommand("rm -rf ~/build")+ assertFalse(result.message.contains("safety policy"))+ }++ @Test+ fun `an oversized command is rejected before the intent is sent`() = runTest {+ installTermux()+ grantRunCommand()++ val result = tool.runCommand("echo " + "x".repeat(200 * 1024))++ assertFalse(result.success)+ assertTrue(result.message.contains("over Termux's"))+ assertTrue(result.message.contains("write_file"))+ }++ // ---- result-bundle parsing ----++ @Test+ fun `a successful result reports exit code and stdout`() {+ val result = tool.formatResult(resultBundle(exitCode = 0, stdout = "hello\n"))++ assertTrue(result.success)+ assertTrue(result.message.contains("exit code: 0"))+ assertTrue(result.message.contains("stdout:\nhello"))+ }++ @Test+ fun `a failing command reports stderr and a non-zero exit code`() {+ val result = tool.formatResult(resultBundle(exitCode = 127, stderr = "sh: nope: not found"))++ assertFalse(result.success)+ assertTrue(result.message.contains("exit code: 127"))+ assertTrue(result.message.contains("stderr:\nsh: nope: not found"))+ }++ @Test+ fun `a silent command says so rather than reporting nothing`() {+ val result = tool.formatResult(resultBundle(exitCode = 0))+ assertTrue(result.message.contains("(no output)"))+ }++ @Test+ fun `a termux-side error surfaces its message and fails`() {+ val bundle = resultBundle(exitCode = 0).apply {+ putInt(TermuxTool.RESULT_ERR, -101)+ putString(TermuxTool.RESULT_ERRMSG, "allow-external-apps is false")+ }++ val result = tool.formatResult(bundle)++ assertFalse(result.success)+ assertTrue(result.message.contains("error code -101"))+ assertTrue(result.message.contains("allow-external-apps is false"))+ }++ @Test+ fun `output past our cap is truncated with a marker`() {+ val result = tool.formatResult(resultBundle(exitCode = 0, stdout = "y".repeat(40 * 1024)))++ assertTrue(result.message.contains("…(output capped)"))+ assertTrue("must stay near the 32KB cap: ${result.message.length}", result.message.length < 34 * 1024)+ }++ @Test+ fun `termux truncating the bundle itself is reported too`() {+ // Termux sends the original lengths as strings, and only ever sends what fits in ~100KB.+ val bundle = resultBundle(exitCode = 0, stdout = "z".repeat(100)).apply {+ putString(TermuxTool.RESULT_STDOUT_ORIGINAL_LENGTH, "500000")+ }++ assertTrue(tool.formatResult(bundle).message.contains("~100KB result limit"))+ }++ @Test+ fun `a missing exit code does not read as success`() {+ val result = tool.formatResult(Bundle().apply { putString(TermuxTool.RESULT_STDOUT, "partial") })++ assertFalse(result.success)+ assertTrue(result.message.contains("exit code: -1"))+ }++ // ---- receiver hand-off ----++ @Test+ fun `the receiver hands a result to the waiting caller and drops unknown ones`() {+ // completeResult clears the entry it completes; an unknown code must be a no-op rather+ // than a crash, since a timed-out caller has already removed itself.+ assertFalse(TermuxTool.isPending(Int.MAX_VALUE))+ TermuxTool.completeResult(Int.MAX_VALUE, resultBundle(exitCode = 0))+ assertFalse(TermuxTool.isPending(Int.MAX_VALUE))+ }++ private fun resultBundle(exitCode: Int, stdout: String? = null, stderr: String? = null) =+ Bundle().apply {+ putInt(TermuxTool.RESULT_EXIT_CODE, exitCode)+ stdout?.let { putString(TermuxTool.RESULT_STDOUT, it) }+ stderr?.let { putString(TermuxTool.RESULT_STDERR, it) }+ }+}diff --git a/app/src/test/resources/feature-test-coverage.json b/app/src/test/resources/feature-test-coverage.jsonindex f2c994b..5ac5ff0 100644--- a/app/src/test/resources/feature-test-coverage.json+++ b/app/src/test/resources/feature-test-coverage.json@@ -564,6 +564,14 @@"reason": "Requires a rooted device and an interactive superuser grant.","manualSteps": "On a rooted device, ask the agent to run `id`; confirm the superuser prompt appears and the output shows uid=0."},+ {+ "tool": "run_termux_command",+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.TermuxToolTest"+ ],+ "notes": "installed/granted decision table, deny-list, size guard, result-bundle parsing, truncation, timeout path; the live round-trip needs a real Termux install and is verified by hand"+ },{"tool": "write_secure_settings","tier": "MANUAL_ONLY",diff --git a/docs/FEATURE_TEST_COVERAGE.md b/docs/FEATURE_TEST_COVERAGE.mdindex 9f5ec0f..de9c580 100644--- a/docs/FEATURE_TEST_COVERAGE.md+++ b/docs/FEATURE_TEST_COVERAGE.md@@ -14,12 +14,12 @@ Every tool the assistant can call is listed below, together with how it is verif| Tier | Tools | What it means ||---|---:|---|| `UNIT` | 20 | Plain JVM unit test — no Android framework needed. |-| `ROBOLECTRIC` | 18 | JVM test against Robolectric's Android framework, often across several API levels. |+| `ROBOLECTRIC` | 19 | JVM test against Robolectric's Android framework, often across several API levels. || `INSTRUMENTED` | 0 | Runs on a real device or emulator (`app/src/androidTest`). || `MANUAL_ONLY` | 64 | No automated test — verified by hand, see the checklist below. |-| **Total** | **102** | |+| **Total** | **103** | |-**38 of 102** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.+**39 of 103** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.## Foreground tools (act on the screen)@@ -71,6 +71,7 @@ Every tool the assistant can call is listed below, together with how it is verif| `resume_audio_recording` | `MANUAL_ONLY` | Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio. || `run_command` | `UNIT` | `TerminalToolTest` — argument splitting, timeout, exit codes, output truncation || `run_root_command` | `MANUAL_ONLY` | Requires a rooted device and an interactive superuser grant. |+| `run_termux_command` | `ROBOLECTRIC` | `TermuxToolTest` — installed/granted decision table, deny-list, size guard, result-bundle parsing, truncation, timeout path; the live round-trip needs a real Termux install and is verified by hand || `send_email` | `UNIT` | `EmailToolsTest`, `MimeMessageBuilderTest` — confirmation flow, recipient handling, MIME construction with attachments || `send_sms` | `MANUAL_ONLY` | Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio. || `set_alarm` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |