Skip to content

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

feat: extend alarm and audio recording tools with enhanced management features and new control actions.

Rishabh Bajpai5ec89ee460b3
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 5e045f5..a0b1809 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -145,6 +145,11 @@
android:name=".tools.ScheduledSmsReceiver"
android:exported="false" />
+ <!-- Alarm and timer firing receiver -->
+ <receiver
+ android:name=".tools.AlarmReceiver"
+ android:exported="false" />
+
<!-- Tier 3: Device Admin — lock screen, password policy, disable camera. -->
<receiver
android:name=".service.GotchaDeviceAdminReceiver"
diff --git a/app/src/main/java/com/gotcha/tools/AlarmReceiver.kt b/app/src/main/java/com/gotcha/tools/AlarmReceiver.kt
new file mode 100644
index 0000000..1617825
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/AlarmReceiver.kt
@@ -0,0 +1,100 @@
+package com.gotcha.tools
+
+import android.app.AlarmManager
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.os.Build
+import androidx.core.app.NotificationCompat
+import java.util.Calendar
+
+class AlarmReceiver : BroadcastReceiver() {
+
+ override fun onReceive(context: Context, intent: Intent) {
+ val type = intent.getStringExtra("type") ?: return
+
+ createChannel(context)
+
+ when (type) {
+ "alarm" -> handleAlarm(context, intent)
+ "timer" -> handleTimer(context, intent)
+ }
+ }
+
+ private fun handleAlarm(context: Context, intent: Intent) {
+ val id = intent.getLongExtra("alarm_id", -1)
+ val label = intent.getStringExtra("label") ?: "Alarm"
+ val hour = intent.getIntExtra("hour", 0)
+ val minute = intent.getIntExtra("minute", 0)
+ val vibrate = intent.getBooleanExtra("vibrate", true)
+ val days = intent.getIntArrayExtra("days")
+
+ showNotification(context, "alarm_$id", label, 1000 + id.toInt())
+
+ // Reschedule if recurring
+ if (days != null && days.isNotEmpty()) {
+ val now = Calendar.getInstance()
+ val target = Calendar.getInstance().apply {
+ set(Calendar.HOUR_OF_DAY, hour)
+ set(Calendar.MINUTE, minute)
+ set(Calendar.SECOND, 0)
+ set(Calendar.MILLISECOND, 0)
+ }
+ val currentDow = now.get(Calendar.DAY_OF_WEEK)
+ for (offset in 1..7) {
+ val check = currentDow + offset
+ val dow = if (check > 7) check - 7 else check
+ if (dow in days.toSet()) {
+ target.add(Calendar.DAY_OF_MONTH, offset)
+ break
+ }
+ }
+ val rescheduleIntent = Intent(context, AlarmReceiver::class.java).apply {
+ putExtra("type", "alarm")
+ putExtra("alarm_id", id)
+ putExtra("label", label)
+ putExtra("hour", hour)
+ putExtra("minute", minute)
+ putExtra("vibrate", vibrate)
+ putExtra("days", days)
+ }
+ val pi = PendingIntent.getBroadcast(context, id.toInt(), rescheduleIntent,
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
+ val am = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
+ am.setAlarmClock(AlarmManager.AlarmClockInfo(target.timeInMillis, pi), pi)
+ }
+ }
+
+ private fun handleTimer(context: Context, intent: Intent) {
+ val id = intent.getLongExtra("timer_id", -1)
+ val label = intent.getStringExtra("label") ?: "Timer"
+ showNotification(context, "timer_$id", "$label time's up!", 2000 + id.toInt())
+ }
+
+ private fun showNotification(context: Context, tag: String, text: String, notifyId: Int) {
+ val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
+ val notification = NotificationCompat.Builder(context, CHANNEL_ID)
+ .setSmallIcon(android.R.drawable.ic_lock_idle_alarm)
+ .setContentTitle("Gotcha")
+ .setContentText(text)
+ .setPriority(NotificationCompat.PRIORITY_HIGH)
+ .setAutoCancel(true)
+ .build()
+ nm.notify(tag, notifyId, notification)
+ }
+
+ private fun createChannel(context: Context) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
+ val channel = NotificationChannel(CHANNEL_ID, "Alarms & Timers", NotificationManager.IMPORTANCE_HIGH)
+ nm.createNotificationChannel(channel)
+ }
+ }
+
+ companion object {
+ private const val CHANNEL_ID = "gotcha_alarms"
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/AlarmTool.kt b/app/src/main/java/com/gotcha/tools/AlarmTool.kt
index 29286e8..0cd76a4 100644
--- a/app/src/main/java/com/gotcha/tools/AlarmTool.kt
+++ b/app/src/main/java/com/gotcha/tools/AlarmTool.kt
@@ -1,46 +1,304 @@
package com.gotcha.tools
+import android.app.AlarmManager
+import android.app.PendingIntent
import android.content.Context
import android.content.Intent
-import android.provider.AlarmClock
+import android.content.SharedPreferences
+import java.util.Calendar
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.booleanOrNull
+import kotlinx.serialization.json.buildJsonArray
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.intOrNull
+import kotlinx.serialization.json.jsonArray
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import kotlinx.serialization.json.put
class AlarmTool(private val context: Context) {
- /** Set a clock alarm via the AlarmClock intent (needs SET_ALARM, a normal permission). */
- fun setAlarm(hour: Int, minute: Int, message: String?): ToolResult {
- if (hour !in 0..23) return ToolResult.error("Hour must be between 0 and 23 (got $hour).")
- if (minute !in 0..59) return ToolResult.error("Minute must be between 0 and 59 (got $minute).")
- val intent = Intent(AlarmClock.ACTION_SET_ALARM).apply {
- putExtra(AlarmClock.EXTRA_HOUR, hour)
- putExtra(AlarmClock.EXTRA_MINUTES, minute)
- if (!message.isNullOrBlank()) putExtra(AlarmClock.EXTRA_MESSAGE, message)
- putExtra(AlarmClock.EXTRA_SKIP_UI, true)
- addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ private val prefs: SharedPreferences = context.getSharedPreferences("gotcha_alarms", Context.MODE_PRIVATE)
+ private var nextId: Long
+ get() = prefs.getLong("next_id", 1)
+ set(v) = prefs.edit().putLong("next_id", v).apply()
+
+ private val dayNames = mapOf(
+ "sun" to Calendar.SUNDAY, "sunday" to Calendar.SUNDAY,
+ "mon" to Calendar.MONDAY, "monday" to Calendar.MONDAY,
+ "tue" to Calendar.TUESDAY, "tuesday" to Calendar.TUESDAY,
+ "wed" to Calendar.WEDNESDAY, "wednesday" to Calendar.WEDNESDAY,
+ "thu" to Calendar.THURSDAY, "thursday" to Calendar.THURSDAY,
+ "fri" to Calendar.FRIDAY, "friday" to Calendar.FRIDAY,
+ "sat" to Calendar.SATURDAY, "saturday" to Calendar.SATURDAY
+ )
+ private val dayNumbers = dayNames.values.toSet()
+
+ fun setAlarm(hour: Int, minute: Int, message: String? = null, days: List<String>? = null, vibrate: Boolean? = null): ToolResult {
+ if (hour !in 0..23) return ToolResult.error("Hour must be 0-23.")
+ if (minute !in 0..59) return ToolResult.error("Minute must be 0-59.")
+ val dayInts = parseDays(days)
+ val id = nextId++
+ val label = message?.takeIf { it.isNotBlank() }
+
+ val triggerAt = nextAlarmTime(hour, minute, dayInts)
+ val intent = Intent(context, AlarmReceiver::class.java).apply {
+ putExtra("type", "alarm")
+ putExtra("alarm_id", id)
+ putExtra("label", label ?: "Alarm")
+ putExtra("hour", hour)
+ putExtra("minute", minute)
+ putExtra("vibrate", vibrate ?: true)
+ dayInts.toIntArray().let { putExtra("days", it) }
+ }
+ val pi = PendingIntent.getBroadcast(context, id.toInt(), intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
+ val am = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
+ am.setAlarmClock(AlarmManager.AlarmClockInfo(triggerAt, pi), pi)
+
+ saveAlarm(AlarmRecord(id, hour, minute, dayInts, label, vibrate ?: true))
+
+ val dayStr = if (dayInts.isNotEmpty()) " (${days?.joinToString(",")})" else ""
+ val extra = buildString {
+ if (dayInts.isNotEmpty()) append(" repeating$dayStr")
+ if (vibrate == false) append(" silent")
+ }
+ return ToolResult.ok("Set alarm '$label' for %02d:%02d$extra (id=$id).".format(hour, minute))
+ }
+
+ fun setTimer(seconds: Int, message: String? = null, hours: Int? = null, minutes: Int? = null): ToolResult {
+ val totalSeconds = seconds + (hours ?: 0) * 3600 + (minutes ?: 0) * 60
+ if (totalSeconds < 1) return ToolResult.error("Timer length must be at least 1 second.")
+ val id = nextId++
+ val label = message?.takeIf { it.isNotBlank() }
+ val triggerAt = System.currentTimeMillis() + totalSeconds * 1000L
+
+ val intent = Intent(context, AlarmReceiver::class.java).apply {
+ putExtra("type", "timer")
+ putExtra("timer_id", id)
+ putExtra("label", label ?: "Timer")
+ putExtra("seconds", totalSeconds)
+ }
+ val pi = PendingIntent.getBroadcast(context, 10000 + id.toInt(), intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
+ val am = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
+ am.setExact(AlarmManager.RTC_WAKEUP, triggerAt, pi)
+
+ saveTimer(TimerRecord(id, totalSeconds, label))
+
+ val extra = buildString {
+ if (hours != null && hours > 0) append(" ${hours}h")
+ if (minutes != null && minutes > 0) append(" ${minutes}m")
+ if (seconds > 0) append(" ${seconds}s")
+ }
+ return ToolResult.ok("Started ${label ?: "a timer"} for${extra.trimStart()} (id=$id).")
+ }
+
+ fun listAlarms(): ToolResult {
+ val alarms = loadAlarms()
+ if (alarms.isEmpty()) return ToolResult.ok("No alarms set.")
+ val sb = StringBuilder()
+ alarms.forEach { a ->
+ val dayStr = if (a.days.isNotEmpty()) {
+ a.days.mapNotNull { e -> dayNames.entries.firstOrNull { it.value == e }?.key?.take(3) }.joinToString(",")
+ } else "once"
+ sb.append("- $dayStr %02d:%02d".format(a.hour, a.minute))
+ if (a.label != null) sb.append(" ${a.label}")
+ sb.append(" (id=${a.id})\n")
+ }
+ return ToolResult.ok(sb.trimEnd().toString())
+ }
+
+ fun listTimers(): ToolResult {
+ val timers = loadTimers()
+ if (timers.isEmpty()) return ToolResult.ok("No timers running.")
+ val sb = StringBuilder()
+ timers.forEach { t ->
+ val remaining = maxOf(0, t.triggerAt - System.currentTimeMillis()) / 1000
+ sb.append("- ${t.label ?: "Timer"}: ${remaining / 60}m ${remaining % 60}s remaining (id=${t.id})\n")
+ }
+ return ToolResult.ok(sb.trimEnd().toString())
+ }
+
+ fun editAlarm(id: Long, hour: Int? = null, minute: Int? = null, message: String? = null, days: List<String>? = null, vibrate: Boolean? = null): ToolResult {
+ val alarms = loadAlarmsMutable()
+ val idx = alarms.indexOfFirst { it.id == id }
+ if (idx == -1) return ToolResult.error("Alarm $id not found.")
+
+ val old = alarms[idx]
+ val newHour = hour ?: old.hour
+ val newMinute = minute ?: old.minute
+ val newLabel = message ?: old.label
+ val newDays = if (days != null) parseDays(days) else old.days
+ val newVibrate = vibrate ?: old.vibrate
+
+ val triggerAt = nextAlarmTime(newHour, newMinute, newDays)
+ val intent = Intent(context, AlarmReceiver::class.java).apply {
+ putExtra("type", "alarm")
+ putExtra("alarm_id", id)
+ putExtra("label", newLabel ?: "Alarm")
+ putExtra("hour", newHour)
+ putExtra("minute", newMinute)
+ putExtra("vibrate", newVibrate)
+ newDays.toIntArray().let { putExtra("days", it) }
+ }
+ val pi = PendingIntent.getBroadcast(context, id.toInt(), intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
+ val am = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
+ am.setAlarmClock(AlarmManager.AlarmClockInfo(triggerAt, pi), pi)
+
+ alarms[idx] = AlarmRecord(id, newHour, newMinute, newDays, newLabel, newVibrate)
+ saveAlarms(alarms)
+ return ToolResult.ok("Updated alarm $id.")
+ }
+
+ fun deleteAlarm(id: Long): ToolResult {
+ val alarms = loadAlarmsMutable()
+ if (alarms.none { it.id == id }) return ToolResult.error("Alarm $id not found.")
+ cancelPendingIntent(id.toInt())
+ saveAlarms(alarms.filter { it.id != id })
+ return ToolResult.ok("Deleted alarm $id.")
+ }
+
+ fun deleteTimer(id: Long): ToolResult {
+ val timers = loadTimersMutable()
+ if (timers.none { it.id == id }) return ToolResult.error("Timer $id not found.")
+ cancelPendingIntent(10000 + id.toInt())
+ saveTimers(timers.filter { it.id != id })
+ return ToolResult.ok("Deleted timer $id.")
+ }
+
+ // ---- storage ----
+
+ private data class AlarmRecord(
+ val id: Long, val hour: Int, val minute: Int,
+ val days: List<Int>, val label: String?, val vibrate: Boolean
+ )
+
+ private data class TimerRecord(
+ val id: Long, val seconds: Int, val label: String?,
+ val triggerAt: Long = System.currentTimeMillis() + seconds * 1000L
+ )
+
+ private fun saveAlarm(r: AlarmRecord) {
+ val list = loadAlarmsMutable()
+ list.add(r)
+ saveAlarms(list)
+ }
+
+ private fun saveAlarms(list: List<AlarmRecord>) {
+ val json = buildJsonArray {
+ list.forEach { a ->
+ add(buildJsonObject {
+ put("id", a.id)
+ put("hour", a.hour)
+ put("minute", a.minute)
+ val daysArr = buildJsonArray { a.days.forEach { d -> add(kotlinx.serialization.json.JsonPrimitive(d)) } }
+ put("days", daysArr)
+ if (a.label != null) put("label", a.label)
+ put("vibrate", a.vibrate)
+ })
+ }
}
- return launch(intent, "Set an alarm for %02d:%02d.".format(hour, minute), "set an alarm")
+ prefs.edit().putString("alarms", json.toString()).apply()
}
- /** Start a countdown timer via the AlarmClock intent. */
- fun setTimer(seconds: Int, message: String?): ToolResult {
- if (seconds < 1) return ToolResult.error("Timer length must be at least 1 second.")
- val intent = Intent(AlarmClock.ACTION_SET_TIMER).apply {
- putExtra(AlarmClock.EXTRA_LENGTH, seconds)
- if (!message.isNullOrBlank()) putExtra(AlarmClock.EXTRA_MESSAGE, message)
- putExtra(AlarmClock.EXTRA_SKIP_UI, true)
- addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ private fun loadAlarms(): List<AlarmRecord> = try {
+ val arr = Json.parseToJsonElement(prefs.getString("alarms", "[]") ?: "[]").jsonArray
+ arr.mapNotNull { e ->
+ val o = e.jsonObject
+ val id = o["id"]?.jsonPrimitive?.content?.toLongOrNull() ?: return@mapNotNull null
+ val hour = o["hour"]?.jsonPrimitive?.intOrNull ?: return@mapNotNull null
+ val minute = o["minute"]?.jsonPrimitive?.intOrNull ?: return@mapNotNull null
+ AlarmRecord(
+ id = id,
+ hour = hour,
+ minute = minute,
+ days = o["days"]?.jsonArray?.mapNotNull { it.jsonPrimitive.intOrNull } ?: emptyList(),
+ label = o["label"]?.jsonPrimitive?.content,
+ vibrate = o["vibrate"]?.jsonPrimitive?.booleanOrNull ?: true
+ )
+ }.filterNotNull()
+ } catch (_: Exception) { emptyList() }
+
+ private fun loadAlarmsMutable(): MutableList<AlarmRecord> = loadAlarms().toMutableList()
+
+ private fun saveTimer(r: TimerRecord) {
+ val list = loadTimersMutable()
+ list.add(r)
+ saveTimers(list)
+ }
+
+ private fun saveTimers(list: List<TimerRecord>) {
+ val json = buildJsonArray {
+ list.forEach { t ->
+ add(buildJsonObject {
+ put("id", t.id)
+ put("seconds", t.seconds)
+ if (t.label != null) put("label", t.label)
+ put("triggerAt", t.triggerAt)
+ })
+ }
}
- return launch(intent, "Started a ${seconds}s timer.", "start a timer")
+ prefs.edit().putString("timers", json.toString()).apply()
}
- private fun launch(intent: Intent, success: String, action: String): ToolResult {
- return try {
- if (intent.resolveActivity(context.packageManager) == null) {
- return ToolResult.error("No clock app on this device can $action.")
+ private fun loadTimers(): List<TimerRecord> = try {
+ val arr = Json.parseToJsonElement(prefs.getString("timers", "[]") ?: "[]").jsonArray
+ arr.mapNotNull { e ->
+ val o = e.jsonObject
+ val id = o["id"]?.jsonPrimitive?.content?.toLongOrNull() ?: return@mapNotNull null
+ val seconds = o["seconds"]?.jsonPrimitive?.intOrNull ?: return@mapNotNull null
+ TimerRecord(
+ id = id,
+ seconds = seconds,
+ label = o["label"]?.jsonPrimitive?.content,
+ triggerAt = o["triggerAt"]?.jsonPrimitive?.content?.toLongOrNull() ?: (System.currentTimeMillis() + seconds * 1000L)
+ )
+ }
+ } catch (_: Exception) { emptyList() }
+
+ private fun loadTimersMutable(): MutableList<TimerRecord> = loadTimers().toMutableList()
+
+ private fun cancelPendingIntent(requestCode: Int) {
+ val intent = Intent(context, AlarmReceiver::class.java)
+ val pi = PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_NO_CREATE)
+ if (pi != null) {
+ val am = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
+ am.cancel(pi)
+ pi.cancel()
+ }
+ }
+
+ // ---- helpers ----
+
+ private fun parseDays(days: List<String>?): List<Int> {
+ if (days.isNullOrEmpty()) return emptyList()
+ return days.mapNotNull { d -> dayNames[d.trim().lowercase()] }.distinct()
+ }
+
+ private fun nextAlarmTime(hour: Int, minute: Int, days: List<Int>): Long {
+ val now = Calendar.getInstance()
+ val target = Calendar.getInstance().apply {
+ set(Calendar.HOUR_OF_DAY, hour)
+ set(Calendar.MINUTE, minute)
+ set(Calendar.SECOND, 0)
+ set(Calendar.MILLISECOND, 0)
+ }
+ if (days.isEmpty()) {
+ if (target.before(now)) target.add(Calendar.DAY_OF_MONTH, 1)
+ return target.timeInMillis
+ }
+ val currentDow = now.get(Calendar.DAY_OF_WEEK)
+ for (offset in 0..6) {
+ val check = currentDow + offset
+ val dow = if (check > 7) check - 7 else check
+ if (dow in days) {
+ target.add(Calendar.DAY_OF_MONTH, offset)
+ if (offset == 0 && target.before(now)) continue
+ return target.timeInMillis
}
- context.startActivity(intent)
- ToolResult.ok(success)
- } catch (e: Exception) {
- ToolResult.error("Could not $action: ${e.message}")
}
+ target.add(Calendar.DAY_OF_MONTH, 7)
+ return target.timeInMillis
}
}
diff --git a/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt b/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt
index 8e62556..1fa97ea 100644
--- a/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt
+++ b/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt
@@ -1,10 +1,12 @@
package com.gotcha.tools
import android.Manifest
+import android.content.ContentValues
import android.content.Context
import android.content.pm.PackageManager
import android.media.MediaRecorder
import android.os.Build
+import android.provider.MediaStore
import android.util.Log
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
@@ -25,11 +27,9 @@ class MediaCaptureTool(private val context: Context) {
private val TAG = "Gotcha"
private var recorder: MediaRecorder? = null
private var recordingFile: File? = null
+ private var recordingStartTime: Long = 0L
+ private var recordingPaused: Boolean = false
- /**
- * Capture a photo automatically using CameraX. No camera app is opened.
- * Takes a photo from the selected camera in the background.
- */
suspend fun takePhoto(camera: String?): ToolResult {
Log.d(TAG, "takePhoto: camera=$camera")
if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
@@ -94,8 +94,12 @@ class MediaCaptureTool(private val context: Context) {
}
}
- /** Start recording audio to a file (needs RECORD_AUDIO). */
- fun startAudioRecording(): ToolResult {
+ fun startAudioRecording(
+ source: String? = null,
+ maxDurationSeconds: Int? = null,
+ outputPath: String? = null,
+ quality: String? = null
+ ): ToolResult {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO)
!= PackageManager.PERMISSION_GRANTED
) {
@@ -108,52 +112,138 @@ class MediaCaptureTool(private val context: Context) {
return ToolResult.error("A recording is already in progress. Stop it before starting a new one.")
}
return try {
- val dir = context.getExternalFilesDir("Recordings")
- ?: return ToolResult.error("No external storage is available for recordings.")
- dir.mkdirs()
- val file = File(dir, "recording_${timestamp()}.m4a")
+ val file = if (!outputPath.isNullOrBlank()) {
+ val f = File(outputPath)
+ f.parentFile?.mkdirs()
+ f
+ } else {
+ val dir = context.getExternalFilesDir("Recordings")
+ ?: return ToolResult.error("No external storage is available for recordings.")
+ dir.mkdirs()
+ File(dir, "recording_${timestamp()}.m4a")
+ }
+
+ val audioSource = when (source?.trim()?.lowercase()) {
+ "voice" -> MediaRecorder.AudioSource.VOICE_RECOGNITION
+ "camcorder" -> MediaRecorder.AudioSource.CAMCORDER
+ else -> MediaRecorder.AudioSource.MIC
+ }
+
val rec = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
MediaRecorder(context)
} else {
@Suppress("DEPRECATION")
MediaRecorder()
}
- rec.setAudioSource(MediaRecorder.AudioSource.MIC)
+ rec.setAudioSource(audioSource)
rec.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
rec.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
+
+ when (quality?.trim()?.lowercase()) {
+ "low" -> { rec.setAudioSamplingRate(16000); rec.setAudioEncodingBitRate(16000) }
+ "medium" -> { rec.setAudioSamplingRate(44100); rec.setAudioEncodingBitRate(64000) }
+ "high" -> { rec.setAudioSamplingRate(44100); rec.setAudioEncodingBitRate(192000) }
+ }
+
+ if (maxDurationSeconds != null && maxDurationSeconds > 0) {
+ rec.setMaxDuration(maxDurationSeconds * 1000)
+ }
rec.setOutputFile(file.absolutePath)
rec.prepare()
rec.start()
recorder = rec
recordingFile = file
- ToolResult.ok("Recording started. Ask to stop when finished.")
+ recordingStartTime = System.currentTimeMillis()
+ recordingPaused = false
+
+ val extras = buildString {
+ if (source != null) append(" ($source)")
+ if (maxDurationSeconds != null && maxDurationSeconds > 0) append(", max ${maxDurationSeconds}s")
+ append(" at ${file.absolutePath}")
+ if (quality != null) append(", $quality quality")
+ }
+ ToolResult.ok("Recording started$extras.")
} catch (e: Exception) {
releaseRecorder()
ToolResult.error("Could not start recording: ${e.message}")
}
}
- /** Stop the in-progress recording and report the saved file. */
fun stopAudioRecording(): ToolResult {
val rec = recorder ?: return ToolResult.error("No recording is in progress.")
return try {
rec.stop()
- val path = recordingFile?.absolutePath ?: "unknown"
+ val file = recordingFile
+ val path = file?.absolutePath ?: "unknown"
+ val dur = (System.currentTimeMillis() - recordingStartTime) / 1000
+ // Make the file accessible to other apps
+ file?.setReadable(true, false)
+ // Scan into MediaStore so music players can discover it
+ if (file != null) {
+ try {
+ val values = ContentValues().apply {
+ put(MediaStore.Audio.Media.IS_PENDING, 0)
+ put(MediaStore.Audio.Media.DATA, file.absolutePath)
+ put(MediaStore.Audio.Media.TITLE, file.nameWithoutExtension)
+ put(MediaStore.Audio.Media.DURATION, dur * 1000)
+ put(MediaStore.Audio.Media.MIME_TYPE, "audio/mp4")
+ }
+ context.contentResolver.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values)
+ } catch (_: Exception) { }
+ }
releaseRecorder()
- ToolResult.ok("Recording saved to $path.")
+ ToolResult.ok("Recording saved to $path (${dur / 60}m ${dur % 60}s).")
} catch (e: Exception) {
releaseRecorder()
ToolResult.error("Could not stop the recording cleanly: ${e.message}")
}
}
- private fun releaseRecorder() {
- try {
- recorder?.release()
- } catch (_: Exception) {
+ fun getAudioRecordingStatus(): ToolResult {
+ val rec = recorder
+ if (rec == null) return ToolResult.ok("No recording is active.")
+ val elapsed = (System.currentTimeMillis() - recordingStartTime) / 1000
+ val path = recordingFile?.absolutePath ?: "unknown"
+ val state = if (recordingPaused) "paused" else "recording"
+ return ToolResult.ok("$state for ${elapsed / 60}m ${elapsed % 60}s at $path.")
+ }
+
+ fun pauseAudioRecording(): ToolResult {
+ val rec = recorder ?: return ToolResult.error("No recording is in progress.")
+ if (recordingPaused) return ToolResult.error("Recording is already paused.")
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
+ return ToolResult.error("Pause/resume requires Android 7.0+ (API 24).")
+ }
+ return try {
+ rec.pause()
+ recordingPaused = true
+ ToolResult.ok("Recording paused.")
+ } catch (e: Exception) {
+ ToolResult.error("Could not pause: ${e.message}")
}
+ }
+
+ fun resumeAudioRecording(): ToolResult {
+ val rec = recorder ?: return ToolResult.error("No recording is in progress.")
+ if (!recordingPaused) return ToolResult.error("Recording is not paused.")
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
+ return ToolResult.error("Pause/resume requires Android 7.0+ (API 24).")
+ }
+ return try {
+ rec.resume()
+ recordingPaused = false
+ ToolResult.ok("Recording resumed.")
+ } catch (e: Exception) {
+ ToolResult.error("Could not resume: ${e.message}")
+ }
+ }
+
+ private fun releaseRecorder() {
+ try { recorder?.release() } catch (_: Exception) {}
recorder = null
recordingFile = null
+ recordingStartTime = 0L
+ recordingPaused = false
}
private fun timestamp(): String =
diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
index b9c41e4..85a137c 100644
--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
@@ -549,7 +549,9 @@ object ToolDefinitions {
val setAlarm = tool(
"set_alarm",
- "Set a clock alarm at a given hour and minute via the device clock app.",
+ "Set an alarm at a given hour and minute. Supports repeating by day of week and silent mode. " +
+ "Returns an alarm ID that can be used to edit or delete it later. " +
+ "List alarms with list_alarms. Edit with edit_alarm. Delete with delete_alarm.",
schema {
putJsonObject("properties") {
putJsonObject("hour") {
@@ -564,6 +566,15 @@ object ToolDefinitions {
put("type", "string")
put("description", "Optional alarm label.")
}
+ putJsonObject("days") {
+ put("type", "array")
+ put("description", "Repeating days: e.g. ['mon','wed','fri'] or ['weekdays']. Omit for one-time alarm.")
+ putJsonObject("items") { put("type", "string") }
+ }
+ putJsonObject("vibrate") {
+ put("type", "boolean")
+ put("description", "Whether the alarm should vibrate. Default true.")
+ }
}
putJsonArray("required") {
add("hour")
@@ -574,12 +585,21 @@ object ToolDefinitions {
val setTimer = tool(
"set_timer",
- "Start a countdown timer for a number of seconds via the device clock app.",
+ "Start a countdown timer. Returns a timer ID that can be used to delete it later. " +
+ "List timers with list_timers. Delete with delete_timer.",
schema {
putJsonObject("properties") {
putJsonObject("seconds") {
put("type", "integer")
- put("description", "Timer length in seconds.")
+ put("description", "Timer length in seconds. Combine with hours/minutes for longer durations.")
+ }
+ putJsonObject("minutes") {
+ put("type", "integer")
+ put("description", "Additional minutes (e.g. 5 for '5 minutes').")
+ }
+ putJsonObject("hours") {
+ put("type", "integer")
+ put("description", "Additional hours.")
}
putJsonObject("message") {
put("type", "string")
@@ -809,17 +829,135 @@ object ToolDefinitions {
val startAudioRecording = tool(
"start_audio_recording",
- "Start recording audio from the microphone to a file. Call stop_audio_recording to finish. " +
+ "Start recording audio from the microphone to a file. Supports configurable source, " +
+ "quality, max duration, and custom output path. Call stop_audio_recording to finish. " +
"Needs the Microphone permission.",
- schema { putJsonObject("properties") {} }
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("source") {
+ put("type", "string")
+ put("description", "Audio source: 'mic' (default), 'voice' (optimized for speech), or 'camcorder' (wider range).")
+ }
+ putJsonObject("max_duration_seconds") {
+ put("type", "integer")
+ put("description", "Auto-stop after this many seconds. 0 or omit for no limit.")
+ }
+ putJsonObject("output_path") {
+ put("type", "string")
+ put("description", "Custom file path to save the recording. Defaults to Recordings/recording_{timestamp}.m4a.")
+ }
+ putJsonObject("quality") {
+ put("type", "string")
+ put("description", "Recording quality: 'low' (16kHz, 16kbps), 'medium' (44.1kHz, 64kbps), or 'high' (44.1kHz, 192kbps). Default medium.")
+ }
+ }
+ }
)
val stopAudioRecording = tool(
"stop_audio_recording",
- "Stop the in-progress audio recording and report the saved file path.",
+ "Stop the in-progress audio recording and report the saved file path and duration.",
+ schema { putJsonObject("properties") {} }
+ )
+
+ val getAudioRecordingStatus = tool(
+ "get_audio_recording_status",
+ "Check whether a recording is active, and if so report its duration and file path.",
schema { putJsonObject("properties") {} }
)
+ val pauseAudioRecording = tool(
+ "pause_audio_recording",
+ "Pause the in-progress recording without stopping it. Resume with resume_audio_recording. " +
+ "Requires Android 7.0+.",
+ schema { putJsonObject("properties") {} }
+ )
+
+ val resumeAudioRecording = tool(
+ "resume_audio_recording",
+ "Resume a paused recording. Only works if pause_audio_recording was called first. " +
+ "Requires Android 7.0+.",
+ schema { putJsonObject("properties") {} }
+ )
+
+ val listAlarms = tool(
+ "list_alarms",
+ "List all active alarms set by set_alarm, with their IDs, times, labels, and recurrence.",
+ schema { putJsonObject("properties") {} }
+ )
+
+ val listTimers = tool(
+ "list_timers",
+ "List all running timers set by set_timer, with their IDs, labels, and remaining time.",
+ schema { putJsonObject("properties") {} }
+ )
+
+ val editAlarm = tool(
+ "edit_alarm",
+ "Edit an existing alarm by ID. Only the fields you provide will be changed. " +
+ "Get the alarm ID from list_alarms.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("alarm_id") {
+ put("type", "integer")
+ put("description", "Alarm ID from list_alarms.")
+ }
+ putJsonObject("hour") {
+ put("type", "integer")
+ put("description", "New hour (0-23). Omit to keep current.")
+ }
+ putJsonObject("minute") {
+ put("type", "integer")
+ put("description", "New minute (0-59). Omit to keep current.")
+ }
+ putJsonObject("message") {
+ put("type", "string")
+ put("description", "New label. Omit to keep current.")
+ }
+ putJsonObject("days") {
+ put("type", "array")
+ put("description", "New repeating days. Omit to keep current. Pass empty array for one-time.")
+ putJsonObject("items") { put("type", "string") }
+ }
+ putJsonObject("vibrate") {
+ put("type", "boolean")
+ put("description", "New vibrate setting. Omit to keep current.")
+ }
+ }
+ putJsonArray("required") { add("alarm_id") }
+ }
+ )
+
+ val deleteAlarm = tool(
+ "delete_alarm",
+ "Permanently delete an alarm by ID. Requires explicit user confirmation (destructive action). " +
+ "Get the alarm ID from list_alarms.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("alarm_id") {
+ put("type", "integer")
+ put("description", "Alarm ID from list_alarms.")
+ }
+ }
+ putJsonArray("required") { add("alarm_id") }
+ }
+ )
+
+ val deleteTimer = tool(
+ "delete_timer",
+ "Cancel and remove a running timer by ID. Requires explicit user confirmation (destructive action). " +
+ "Get the timer ID from list_timers.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("timer_id") {
+ put("type", "integer")
+ put("description", "Timer ID from list_timers.")
+ }
+ }
+ putJsonArray("required") { add("timer_id") }
+ }
+ )
+
val edit = tool(
"edit",
"Replace exact text in a file. Use this for surgical edits — changing specific " +
@@ -1275,10 +1413,12 @@ object ToolDefinitions {
setWallpaper, runCommand,
// Tier 0–2 additions
callNumber, readCallLog, findContact, addContact, sendSms, readRecentSms,
- listCalendarEvents, createCalendarEvent, editCalendarEvent, deleteCalendarEvent, setAlarm, setTimer,
+ listCalendarEvents, createCalendarEvent, editCalendarEvent, deleteCalendarEvent,
+ setAlarm, setTimer, listAlarms, listTimers, editAlarm, deleteAlarm, deleteTimer,
toggleTorch, setVolume, getVolume, setRingerMode, vibrate, setDnd,
getLocation, listInstalledApps, uninstallApp, getAppUsage, getDataUsage,
getClipboard, setClipboard, takePhoto, startAudioRecording, stopAudioRecording,
+ getAudioRecordingStatus, pauseAudioRecording, resumeAudioRecording,
// User interaction
question,
// Task tracking
diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
index 43f5eaf..3a466fa 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -202,11 +202,31 @@ class ToolExecutor(context: Context) {
"set_alarm" -> alarmTool.setAlarm(
hour = args.requireInt("hour") ?: return missing("hour"),
minute = args.requireInt("minute") ?: return missing("minute"),
- message = args.requireString("message")
+ message = args.requireString("message"),
+ days = args["days"]?.jsonArray?.mapNotNull { it.jsonPrimitive?.content },
+ vibrate = args["vibrate"]?.jsonPrimitive?.booleanOrNull
)
"set_timer" -> alarmTool.setTimer(
- seconds = args.requireInt("seconds") ?: return missing("seconds"),
- message = args.requireString("message")
+ seconds = args.requireInt("seconds") ?: 0,
+ message = args.requireString("message"),
+ hours = args.requireInt("hours"),
+ minutes = args.requireInt("minutes")
+ )
+ "list_alarms" -> alarmTool.listAlarms()
+ "list_timers" -> alarmTool.listTimers()
+ "edit_alarm" -> alarmTool.editAlarm(
+ id = args.requireInt("alarm_id")?.toLong() ?: return missing("alarm_id"),
+ hour = args.requireInt("hour"),
+ minute = args.requireInt("minute"),
+ message = args.requireString("message"),
+ days = args["days"]?.jsonArray?.mapNotNull { it.jsonPrimitive?.content },
+ vibrate = args["vibrate"]?.jsonPrimitive?.booleanOrNull
+ )
+ "delete_alarm" -> alarmTool.deleteAlarm(
+ id = args.requireInt("alarm_id")?.toLong() ?: return missing("alarm_id")
+ )
+ "delete_timer" -> alarmTool.deleteTimer(
+ id = args.requireInt("timer_id")?.toLong() ?: return missing("timer_id")
)
"toggle_torch" -> deviceTool.toggleTorch(
on = args["on"]?.jsonPrimitive?.booleanOrNull ?: return missing("on"),
@@ -237,8 +257,16 @@ class ToolExecutor(context: Context) {
"get_clipboard" -> clipboardTool.getClipboard()
"set_clipboard" -> clipboardTool.setClipboard(args.requireString("text") ?: return missing("text"))
"take_photo" -> mediaCaptureTool.takePhoto(args.requireString("camera"))
- "start_audio_recording" -> mediaCaptureTool.startAudioRecording()
+ "start_audio_recording" -> mediaCaptureTool.startAudioRecording(
+ source = args.requireString("source"),
+ maxDurationSeconds = args.requireInt("max_duration_seconds"),
+ outputPath = args.requireString("output_path"),
+ quality = args.requireString("quality")
+ )
"stop_audio_recording" -> mediaCaptureTool.stopAudioRecording()
+ "get_audio_recording_status" -> mediaCaptureTool.getAudioRecordingStatus()
+ "pause_audio_recording" -> mediaCaptureTool.pauseAudioRecording()
+ "resume_audio_recording" -> mediaCaptureTool.resumeAudioRecording()
"question" -> questionTool.ask(
question = args.requireString("question") ?: return missing("question"),
options = args["options"]?.jsonArray?.mapNotNull { it.jsonPrimitive?.content },
diff --git a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
index 4613ea8..5a794d9 100644
--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
@@ -31,7 +31,9 @@ object ToolRegistry {
*/
val destructiveTools: Set<String> = setOf(
"uninstall_app",
- "delete_calendar_event"
+ "delete_calendar_event",
+ "delete_alarm",
+ "delete_timer"
)
/**
@@ -47,13 +49,14 @@ object ToolRegistry {
"list_calendar_events",
// Info & sensors
"get_storage_info", "get_battery_info", "get_location", "get_volume",
+ "get_audio_recording_status",
"get_app_usage", "get_data_usage",
// Apps (read-only + intent)
"open_app", "list_installed_apps",
// Files & terminal (read-only)
"list_files", "read_file", "grep", "glob",
// Task management
- "todowrite",
+ "todowrite", "list_alarms", "list_timers",
// User interaction
"question",
// Web