Modern Apps git

← Modern-Apps.git

openassistant: maml chat engine and tool registry

Commit
7298e6cad40fa6075a6787089a0a6f0ab2990426
Author
vayun-mathur <[email protected]>
When
2026-10-26 21:38 UTC (1 month ago)
Parents
8062530

Diff

openassistant/build.gradle.kts
diff --git a/openassistant/build.gradle.kts b/openassistant/build.gradle.ktsindex f03d057239..68abaf8613 100644--- a/openassistant/build.gradle.kts+++ b/openassistant/build.gradle.kts@@ -43,6 +43,8 @@ dependencies {     implementation(project(":library:image"))      // ai+    // Gemma 4 chat runs on `:library:ml`'s Vulkan runtime (Gemma4Handle).+    implementation(project(":library:ml"))     implementation(libs.litertlm.android)     // litertlm 0.14.0 needs kotlinx-coroutines 1.11.0 (close$default on the     // SendChannel interface); requesting it directly wins over the transitive 1.9.0.
openassistant/src/main/java/com/vayunmathur/openassistant/data/OpenAssistantRepository.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/data/OpenAssistantRepository.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/data/OpenAssistantRepository.ktindex 8e985ea357..501e6ca72d 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/data/OpenAssistantRepository.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/data/OpenAssistantRepository.kt@@ -47,7 +47,7 @@ class OpenAssistantRepository private constructor(context: Context) :     suspend fun upsertMemory(value: Memory): Long = memoryDao.upsert(value)     suspend fun deleteMemory(value: Memory): Int = memoryDao.delete(value) -    /** Backing DAOs for [com.vayunmathur.openassistant.util.AssistantToolSet] and similar consumers. */+    /** Backing DAOs for [com.vayunmathur.openassistant.platform.AssistantTools] and similar consumers. */     internal val conversationDaoRef get(): ConversationDao = conversationDao     internal val messageDaoRef get(): MessageDao = messageDao     internal val memoryDaoRef get(): MemoryDao = memoryDao
openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.ktnew file mode 100644index 0000000000..1fba3b3948--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt@@ -0,0 +1,93 @@+package com.vayunmathur.openassistant.domain++import com.vayunmathur.openassistant.domain.ToolParamType.NUMBER+import com.vayunmathur.openassistant.domain.ToolParamType.STRING++private fun p(name: String, type: ToolParamType = STRING, description: String = "", required: Boolean = true) =+    ToolParamSpec(name, description, type, required)++/**+ * Every tool the assistant may call, in snake_case as LiteRT-LM's reflection exposed them,+ * with the descriptions the old `@Tool`/`@ToolParam` annotations carried.+ */+val ASSISTANT_TOOL_SPECS: List<ToolSpec> = listOf(+    ToolSpec("get_notes", "Get a list of all notes"),+    ToolSpec(+        "create_note",+        "Create a new note in the notes app. Should only be used with EXPLICIT request by user",+        listOf(p("title"), p("content")),+    ),+    ToolSpec("get_contacts", "Get a list of all contacts"),+    ToolSpec("create_contact", "Create a new contact", listOf(p("name"), p("phone_number"))),+    ToolSpec(+        "get_calendar_events",+        "Get a list of calendar events. Each event's start and end times are epoch milliseconds.",+    ),+    ToolSpec(+        "create_calendar_event",+        "Create a new calendar event. Start and end times must be epoch milliseconds.",+        listOf(+            p("title"),+            p("start", NUMBER, "start time as epoch milliseconds"),+            p("end", NUMBER, "end time as epoch milliseconds"),+            p("location", required = false),+        ),+    ),+    ToolSpec("get_family_locations", "Get a list of family members and their current locations"),+    ToolSpec(+        "create_location_share_link",+        "Create a temporary FindFamily link that shares the user's live location.",+        listOf(+            p("name", description = "name or label for who the link is for"),+            p("duration_millis", NUMBER, "how long the link stays active, in milliseconds"),+        ),+    ),+    ToolSpec("search_music", "Search for music (songs, albums, artists, or playlists)", listOf(p("query"))),+    ToolSpec(+        "play_music",+        "Play music given its id and type (song, album, artist, or playlist)",+        listOf(p("id", NUMBER), p("type")),+    ),+    ToolSpec("search_emails", "Search emails by keyword", listOf(p("query"))),+    ToolSpec("get_recent_emails", "Get recent emails from the inbox"),+    ToolSpec("get_local_current_date_time", "Get the current date and time in the local timezone."),+    ToolSpec("get_app_list", "Get a list of installed apps on the device"),+    ToolSpec("open_app", "Open an app given its package id", listOf(p("package_id", description = "package id"))),+    ToolSpec("send_message", "Send a message", listOf(p("recipient"), p("message"))),+    ToolSpec("make_phone_call", "Make a phone call", listOf(p("recipient"))),+    ToolSpec(+        "set_alarm",+        "Set an alarm in the Clock app at a specific hour and minute (24-hour time).",+        listOf(+            p("hour", NUMBER, "hour in 24-hour format, 0-23"),+            p("minute", NUMBER, "minute, 0-59"),+            p("label", description = "optional label for the alarm", required = false),+        ),+    ),+    ToolSpec(+        "set_timer",+        "Start a countdown timer in the Clock app for a number of seconds.",+        listOf(+            p("seconds", NUMBER, "timer length in seconds"),+            p("label", description = "optional label for the timer", required = false),+        ),+    ),+    ToolSpec(+        "set_conversation_title",+        "Set title of current conversation. Mandatory for first response",+        listOf(p("new_title")),+    ),+    ToolSpec(+        "get_weather",+        "Get the current weather conditions at a specific latitude/longitude.",+        listOf(p("latitude", NUMBER), p("longitude", NUMBER)),+    ),+    ToolSpec(+        "get_weather_by_name",+        "Get the current weather conditions for a named place (city, address, landmark).",+        listOf(p("location", description = "city or place name")),+    ),+    ToolSpec("get_memories", "Get a list of all memories"),+    ToolSpec("remove_memory", "Remove a memory by its id", listOf(p("id", NUMBER))),+    ToolSpec("add_to_memory", "Add a new memory to the list of memories", listOf(p("content"))),+)
openassistant/src/main/java/com/vayunmathur/openassistant/domain/HistoryFit.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/HistoryFit.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/HistoryFit.ktnew file mode 100644index 0000000000..ab0a6550fc--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/HistoryFit.kt@@ -0,0 +1,25 @@+package com.vayunmathur.openassistant.domain++/**+ * [history] plus [current], with the oldest history dropped until [fits] accepts it.+ *+ * The current turn is never dropped; null when even it alone does not fit. The kept history+ * starts on a user turn. [fits] must be monotone (fewer turns never fit worse), which lets+ * this binary-search the cut instead of measuring once per dropped turn.+ */+fun <T> fitConversation(+    history: List<T>,+    current: T,+    isUserTurn: (T) -> Boolean,+    fits: (List<T>) -> Boolean,+): List<T>? {+    if (fits(history + current)) return history + current+    if (!fits(listOf(current))) return null+    var low = 1+    var high = history.size+    while (low < high) {+        val mid = (low + high) / 2+        if (fits(history.drop(mid) + current)) high = mid else low = mid + 1+    }+    return history.drop(low).dropWhile { !isUserTurn(it) } + current+}
openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolCalls.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolCalls.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolCalls.ktnew file mode 100644index 0000000000..daf1906c98--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolCalls.kt@@ -0,0 +1,166 @@+package com.vayunmathur.openassistant.domain++/** A tool call the model emitted, with every argument still as its raw text. */+data class ParsedToolCall(val name: String, val arguments: Map<String, String>)++enum class ToolParamType(val gemmaName: String) {+    STRING("STRING"),+    NUMBER("NUMBER"),+}++data class ToolParamSpec(+    val name: String,+    val description: String,+    val type: ToolParamType,+    val required: Boolean = true,+)++data class ToolSpec(+    val name: String,+    val description: String,+    val params: List<ToolParamSpec> = emptyList(),+)++/** Coerced arguments: strings stay strings, numbers are Doubles as LiteRT passed them. */+class ToolArgs(private val values: Map<String, Any>) {+    fun string(name: String, default: String = ""): String = values[name] as? String ?: default+    fun number(name: String): Double = values[name] as? Double ?: 0.0+}++sealed interface ToolArgsResult {+    data class Ok(val args: ToolArgs) : ToolArgsResult+    data class Invalid(val message: String) : ToolArgsResult+}++fun coerceToolArgs(spec: ToolSpec, raw: Map<String, String>): ToolArgsResult {+    val values = HashMap<String, Any>()+    for (param in spec.params) {+        val value = raw[param.name]?.takeUnless { param.type == ToolParamType.NUMBER && it.isBlank() }+        if (value == null) {+            if (param.required) return ToolArgsResult.Invalid("Error: ${spec.name} needs ${param.name}")+            continue+        }+        values[param.name] = when (param.type) {+            ToolParamType.STRING -> value+            ToolParamType.NUMBER -> value.trim().toDoubleOrNull()+                ?: return ToolArgsResult.Invalid("Error: ${param.name} must be a number, got '$value'")+        }+    }+    return ToolArgsResult.Ok(ToolArgs(values))+}++const val TOOL_CALL_OPEN = "<|tool_call>"+const val TOOL_CALL_CLOSE = "<tool_call|>"+private const val CALL_PREFIX = "call:"+private const val QUOTE = "<|\"|>"++private val MARKUP_BLOCKS = listOf(+    TOOL_CALL_OPEN to TOOL_CALL_CLOSE,+    "<|tool_response>" to "<tool_response|>",+    "<|tool>" to "<tool|>",+)+private val PARTIAL_CANDIDATES = MARKUP_BLOCKS.flatMap { listOf(it.first, it.second) } ++    listOf("<|turn>", "<turn|>", QUOTE)+private val LONGEST_MARKER = PARTIAL_CANDIDATES.maxOf { it.length }++/** Whether [reply] holds a tool call whose closing marker has arrived. */+fun hasCompleteToolCall(reply: String): Boolean {+    val open = reply.indexOf(TOOL_CALL_OPEN)+    return open >= 0 && reply.indexOf(TOOL_CALL_CLOSE, open) >= 0+}++/** The raw text between the first complete pair of tool-call markers, or null. */+fun toolCallBody(reply: String): String? {+    val open = reply.indexOf(TOOL_CALL_OPEN)+    if (open < 0) return null+    val close = reply.indexOf(TOOL_CALL_CLOSE, open)+    if (close < 0) return null+    return reply.substring(open + TOOL_CALL_OPEN.length, close)+}++/**+ * The first complete call in [reply], or null when there is none or it is malformed.+ *+ * Accepts both `<|"|>`-quoted values and bare ones: Gemma writes numbers unquoted+ * (`seconds:120`), which a quoted-only parser silently drops.+ */+fun parseToolCall(reply: String): ParsedToolCall? {+    val body = toolCallBody(reply)?.trim()?.removePrefix(CALL_PREFIX) ?: return null+    val brace = body.indexOf('{')+    val end = body.lastIndexOf('}')+    if (brace <= 0 || end < brace) return null+    val name = body.substring(0, brace).trim()+    if (name.isEmpty()) return null+    val arguments = parseArguments(body.substring(brace + 1, end)) ?: return null+    return ParsedToolCall(name, arguments)+}++/** Best-effort tool name of a malformed call, for addressing the error response. */+fun toolCallNameGuess(reply: String): String =+    toolCallBody(reply)?.trim()?.removePrefix(CALL_PREFIX)?.substringBefore('{')?.trim()+        ?.takeIf { it.isNotEmpty() } ?: "unknown"++private fun parseArguments(body: String): Map<String, String>? {+    val out = LinkedHashMap<String, String>()+    var at = 0+    while (at < body.length) {+        while (at < body.length && (body[at] == ',' || body[at].isWhitespace())) at+++        if (at >= body.length) break+        val colon = body.indexOf(':', at)+        if (colon < 0) return null+        val key = body.substring(at, colon).trim().trim('"')+        if (key.isEmpty()) return null+        var value = colon + 1+        while (value < body.length && body[value].isWhitespace()) value+++        if (body.startsWith(QUOTE, value)) {+            val close = body.indexOf(QUOTE, value + QUOTE.length)+            if (close < 0) return null+            out[key] = body.substring(value + QUOTE.length, close)+            at = close + QUOTE.length+        } else {+            var close = value+            while (close < body.length && body[close] != ',') close+++            out[key] = body.substring(value, close).trim().trim('"')+            at = close+        }+    }+    return out+}++/**+ * [text] with tool markup removed, for display.+ *+ * Complete blocks are cut out; an unclosed block drops everything after its opener. With+ * [streaming], a trailing fragment that could still grow into a marker (`<|too`) is hidden too.+ */+fun stripToolMarkup(text: String, streaming: Boolean = true): String {+    val out = StringBuilder()+    var at = 0+    while (at < text.length) {+        val next = MARKUP_BLOCKS+            .map { (open, close) -> Triple(text.indexOf(open, at), open, close) }+            .filter { it.first >= 0 }+            .minByOrNull { it.first }+        if (next == null) {+            out.append(text, at, text.length)+            break+        }+        val (open, opener, closer) = next+        out.append(text, at, open)+        val close = text.indexOf(closer, open + opener.length)+        if (close < 0) {+            at = text.length+            break+        }+        at = close + closer.length+    }+    if (streaming) trimPartialMarker(out)+    return out.toString()+}++private fun trimPartialMarker(out: StringBuilder) {+    val lt = out.lastIndexOf("<")+    if (lt < 0 || out.length - lt >= LONGEST_MARKER) return+    val tail = out.substring(lt)+    if (PARTIAL_CANDIDATES.any { it.startsWith(tail) }) out.setLength(lt)+}
openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolLoop.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolLoop.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolLoop.ktnew file mode 100644index 0000000000..1047516d4e--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolLoop.kt@@ -0,0 +1,65 @@+package com.vayunmathur.openassistant.domain++/** One model round: generate after [continuation] inside the open model turn. */+fun interface ChatGenerator {+    /** [onText] gets the cumulative raw reply; returning false stops. Null means the model failed. */+    suspend fun generate(continuation: String, onText: (String) -> Boolean): String?+}++sealed interface ToolLoopOutcome {+    val text: String++    data class Finished(override val text: String) : ToolLoopOutcome+    data class Halted(override val text: String) : ToolLoopOutcome+    data class Failed(override val text: String) : ToolLoopOutcome+}++const val MAX_TOOL_ROUNDS = 6++/**+ * Runs generate -> tool call -> tool response rounds until the model answers in prose.+ *+ * Each call and its response are appended to the continuation so they stay inside the open+ * model turn. Malformed calls get an error response rather than ending the turn. [onVisible]+ * receives the user-visible text so far (markup stripped); returning false halts.+ */+suspend fun runToolLoop(+    generator: ChatGenerator,+    executeTool: suspend (ParsedToolCall) -> String,+    renderToolResponse: (name: String, value: String) -> String,+    maxRounds: Int = MAX_TOOL_ROUNDS,+    onVisible: (String) -> Boolean,+): ToolLoopOutcome {+    var continuation = ""+    var visible = ""+    for (round in 0 until maxRounds) {+        var halted = false+        val reply = generator.generate(continuation) { partial ->+            if (!onVisible(joinVisible(visible, stripToolMarkup(partial)))) {+                halted = true+                false+            } else {+                !hasCompleteToolCall(partial)+            }+        } ?: return ToolLoopOutcome.Failed(visible)+        visible = joinVisible(visible, stripToolMarkup(reply, streaming = false))+        if (halted) return ToolLoopOutcome.Halted(visible)+        if (!hasCompleteToolCall(reply) || round == maxRounds - 1) break+        val call = parseToolCall(reply)+        val (name, result) = if (call == null) {+            toolCallNameGuess(reply) to "Error: malformed tool call; use name{arg:value}"+        } else {+            call.name to executeTool(call)+        }+        continuation += reply.substringBefore(TOOL_CALL_CLOSE) + TOOL_CALL_CLOSE ++            renderToolResponse(name, result)+    }+    return ToolLoopOutcome.Finished(visible)+}++/** Prose from successive rounds, separated by a blank line. */+fun joinVisible(before: String, after: String): String = when {+    before.isBlank() -> after.trimStart()+    after.isBlank() -> before+    else -> before.trimEnd() + "\n\n" + after.trimStart()+}
openassistant/src/main/java/com/vayunmathur/openassistant/domain/WavDecoder.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/WavDecoder.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/WavDecoder.ktnew file mode 100644index 0000000000..3ea83bde47--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/WavDecoder.kt@@ -0,0 +1,54 @@+package com.vayunmathur.openassistant.domain++import java.nio.ByteBuffer+import java.nio.ByteOrder++const val WAV_SAMPLE_RATE = 16_000+const val WAV_MAX_SECONDS = 30++private const val RIFF_HEADER = 12+private const val CHUNK_HEADER = 8+private const val FMT_MIN = 16+private const val PCM = 1+private const val BITS = 16+private const val PCM_SCALE = 32768f++/**+ * 16 kHz mono 16-bit PCM samples from a WAV file's bytes, scaled to -1..1 and capped at+ * [maxSamples]; null for anything else. There is no resampler, so other formats are refused.+ */+fun decodeWavMono16k(bytes: ByteArray, maxSamples: Int = WAV_SAMPLE_RATE * WAV_MAX_SECONDS): FloatArray? {+    if (bytes.size < RIFF_HEADER || chunkId(bytes, 0) != "RIFF" || chunkId(bytes, 8) != "WAVE") return null+    val wav = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)+    var described = false+    var dataAt = -1+    var dataBytes = 0+    var at = RIFF_HEADER+    while (at + CHUNK_HEADER <= bytes.size) {+        val size = wav.getInt(at + 4)+        if (size < 0) break+        val body = at + CHUNK_HEADER+        when (chunkId(bytes, at)) {+            "fmt " -> {+                if (size < FMT_MIN || body + FMT_MIN > bytes.size) return null+                val ok = wav.getShort(body).toInt() == PCM &&+                    wav.getShort(body + 2).toInt() == 1 &&+                    wav.getInt(body + 4) == WAV_SAMPLE_RATE &&+                    wav.getShort(body + 14).toInt() == BITS+                if (!ok) return null+                described = true+            }+            "data" -> {+                dataAt = body+                dataBytes = minOf(size, bytes.size - body)+            }+        }+        at = body + size + (size and 1)+    }+    if (!described || dataAt < 0) return null+    val count = minOf(dataBytes / 2, maxSamples)+    val pcm = ByteBuffer.wrap(bytes, dataAt, dataBytes).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer()+    return FloatArray(count) { pcm.get(it) / PCM_SCALE }+}++private fun chunkId(bytes: ByteArray, at: Int): String = String(bytes, at, 4, Charsets.US_ASCII)
openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.ktnew file mode 100644index 0000000000..7d472b0c34--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt@@ -0,0 +1,124 @@+package com.vayunmathur.openassistant.platform++import android.content.Context+import com.vayunmathur.library.intents.calendar.EventData+import com.vayunmathur.library.intents.clock.SetAlarmData+import com.vayunmathur.library.intents.clock.SetTimerData+import com.vayunmathur.library.intents.contacts.ContactData+import com.vayunmathur.library.intents.music.PlayMusicData+import com.vayunmathur.library.intents.notes.NoteData+import com.vayunmathur.library.ml.Gemma4Handle+import com.vayunmathur.openassistant.data.MemoryDao+import com.vayunmathur.openassistant.domain.ASSISTANT_TOOL_SPECS+import com.vayunmathur.openassistant.domain.ParsedToolCall+import com.vayunmathur.openassistant.domain.ToolArgs+import com.vayunmathur.openassistant.domain.ToolArgsResult+import com.vayunmathur.openassistant.domain.ToolSpec+import com.vayunmathur.openassistant.domain.coerceToolArgs+import com.vayunmathur.openassistant.util.AssistantDeviceTools+import com.vayunmathur.openassistant.util.AssistantToolIntents+import kotlinx.coroutines.CancellationException++fun ToolSpec.toDeclaration(): Gemma4Handle.ToolDeclaration = Gemma4Handle.ToolDeclaration(+    name = name,+    description = description,+    parameters = params.map {+        Gemma4Handle.ToolDeclaration.Parameter(it.name, it.description, it.type.gemmaName, it.required)+    },+)++/** The assistant's tools: [ASSISTANT_TOOL_SPECS] bound to the intent and device back ends. */+class AssistantTools(context: Context, private val memoryDao: MemoryDao?) {+    private val intents = AssistantToolIntents(context)+    private val device = AssistantDeviceTools(context)+    private val specs = ASSISTANT_TOOL_SPECS.associateBy { it.name }++    val declarations: List<Gemma4Handle.ToolDeclaration> = ASSISTANT_TOOL_SPECS.map { it.toDeclaration() }++    private val handlers: Map<String, (ToolArgs) -> String> = mapOf(+        "get_notes" to { _ -> intents.runTool { intents.getNotes() } },+        "create_note" to { a ->+            intents.runTool {+                intents.insertNote(NoteData(a.string("title"), a.string("content")))+                "Success: Created note '${a.string("title")}'"+            }+        },+        "get_contacts" to { _ -> intents.runTool { intents.getContacts() } },+        "create_contact" to { a ->+            intents.runTool {+                intents.insertContact(ContactData(a.string("name"), a.string("phone_number")))+                "Success: Created contact '${a.string("name")}'"+            }+        },+        "get_calendar_events" to { _ -> intents.runTool { intents.getCalendarEvents() } },+        "create_calendar_event" to { a ->+            intents.runTool {+                val title = a.string("title")+                intents.insertCalendarEvent(+                    EventData(title, a.number("start").toLong(), a.number("end").toLong(), a.string("location")),+                )+                "Success: Created event '$title'"+            }+        },+        "get_family_locations" to { _ -> intents.runTool { intents.getFamilyLocations() } },+        "create_location_share_link" to { a ->+            intents.runTool { intents.createLocationShareLink(a.string("name"), a.number("duration_millis")) }+        },+        "search_music" to { a -> intents.runTool { intents.searchMusic(a.string("query")) } },+        "play_music" to { a ->+            intents.runTool {+                intents.playMusic(PlayMusicData(a.number("id").toLong(), a.string("type")))+                "Success: Playing music"+            }+        },+        "search_emails" to { a -> intents.runTool { intents.searchEmails(a.string("query")) } },+        "get_recent_emails" to { _ -> intents.runTool { intents.getRecentEmails() } },+        "get_local_current_date_time" to { _ -> device.getLocalCurrentDateTime() },+        "get_app_list" to { _ -> device.getAppList() },+        "open_app" to { a -> device.openApp(a.string("package_id"), intents::handleMissingApp) },+        "send_message" to { a -> device.sendMessage(a.string("recipient"), a.string("message")) },+        "make_phone_call" to { a -> device.makePhoneCall(a.string("recipient")) },+        "set_alarm" to { a ->+            val hour = a.number("hour").toInt()+            val minute = a.number("minute").toInt()+            intents.runTool {+                intents.setAlarm(SetAlarmData(hour, minute, a.string("label")))+                "Success: Alarm set for %02d:%02d".format(hour, minute)+            }+        },+        "set_timer" to { a ->+            val seconds = a.number("seconds").toInt()+            intents.runTool {+                intents.setTimer(SetTimerData(seconds, a.string("label")))+                "Success: Timer started for ${seconds}s"+            }+        },+        "set_conversation_title" to { a -> device.setConversationTitle(a.string("new_title")) },+        "get_weather" to { a ->+            intents.runTool { intents.getWeather(a.number("latitude"), a.number("longitude")) }+        },+        "get_weather_by_name" to { a -> intents.runTool { intents.getWeatherByName(a.string("location")) } },+        "get_memories" to { _ -> intents.runTool { device.getMemories(memoryDao) } },+        "remove_memory" to { a -> intents.runTool { device.removeMemory(memoryDao, a.number("id")) } },+        "add_to_memory" to { a -> intents.runTool { device.addToMemory(memoryDao, a.string("content")) } },+    )++    init {+        check(handlers.keys == specs.keys) { "tool handlers and specs disagree" }+    }++    /** Runs [call]. Never throws: unknown tools and bad arguments come back as an error string. */+    fun invoke(call: ParsedToolCall): String {+        val spec = specs[call.name] ?: return "Error: unknown tool '${call.name}'"+        return when (val coerced = coerceToolArgs(spec, call.arguments)) {+            is ToolArgsResult.Invalid -> coerced.message+            is ToolArgsResult.Ok -> try {+                handlers.getValue(spec.name)(coerced.args)+            } catch (e: CancellationException) {+                throw e+            } catch (expected: Exception) {+                "Error: ${expected.message}"+            }+        }+    }+}
openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.ktnew file mode 100644index 0000000000..9872350aac--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt@@ -0,0 +1,233 @@+package com.vayunmathur.openassistant.platform++import android.graphics.Bitmap+import android.graphics.BitmapFactory+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.ml.Gemma4AudioHandle+import com.vayunmathur.library.ml.Gemma4Handle+import com.vayunmathur.library.ml.Gemma4VisionHandle+import com.vayunmathur.library.ml.Sampling+import com.vayunmathur.openassistant.domain.ChatGenerator+import com.vayunmathur.openassistant.domain.ToolLoopOutcome+import com.vayunmathur.openassistant.domain.decodeWavMono16k+import com.vayunmathur.openassistant.domain.fitConversation+import com.vayunmathur.openassistant.domain.runToolLoop+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.asCoroutineDispatcher+import kotlinx.coroutines.cancel+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.coroutines.withContext+import java.io.File+import java.util.concurrent.Executors++/** One stored message, text only: media is only ever attached to the current turn. */+data class HistoryTurn(val fromUser: Boolean, val text: String)++data class ChatRequest(+    val system: String,+    val history: List<HistoryTurn>,+    val userText: String,+    val imagePaths: List<String> = emptyList(),+    val audioPath: String? = null,+)++sealed interface ChatResult {+    data class Reply(val text: String, val halted: Boolean) : ChatResult+    data object TooLong : ChatResult+    data object Unavailable : ChatResult+}++/**+ * Gemma 4 on the maml runtime, replacing LiteRT-LM's Engine/Conversation.+ *+ * The handles are not thread-safe, so every JNI call runs on one dedicated thread and a+ * [Mutex] covers a whole turn, tool rounds included. The vision and audio towers load on+ * first use and close after [TOWER_IDLE_MILLIS] without one.+ */+class MamlChatEngine(private val modelDir: File) : AutoCloseable {+    private val executor = Executors.newSingleThreadExecutor { Thread(it, "maml-engine") }+    private val engineThread = executor.asCoroutineDispatcher()+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)+    private val mutex = Mutex()++    private var handle: Gemma4Handle? = null+    private var vision: Gemma4VisionHandle? = null+    private var audio: Gemma4AudioHandle? = null+    private var towerIdleJob: Job? = null+    private var prefixKey: Int? = null++    /** Loads the model if needed; false when it cannot come up. */+    suspend fun load(): Boolean = mutex.withLock { withContext(engineThread) { model() != null } }++    suspend fun chat(request: ChatRequest, tools: AssistantTools, onText: (String) -> Boolean): ChatResult =+        mutex.withLock {+            val model = withContext(engineThread) { model() } ?: return@withLock ChatResult.Unavailable+            val declarations = tools.declarations+            val current = withContext(engineThread) { currentTurn(request) }+            val history = request.history.map {+                Gemma4Handle.Turn(if (it.fromUser) Gemma4Handle.Role.USER else Gemma4Handle.Role.MODEL, it.text)+            }+            val conversation = withContext(engineThread) {+                seedPrefix(model, request.system, declarations)+                val ceiling = Gemma4Handle.promptCeiling(CHAT_REPLY_LIMIT)+                fitConversation(history, current, { it.role == Gemma4Handle.Role.USER }) {+                    model.positionsFor(it, request.system, declarations, CHAT_REPLY_LIMIT) <= ceiling+                }+            } ?: return@withLock ChatResult.TooLong+            if (conversation.size < history.size + 1) {+                Log.status(TAG, "dropped ${history.size + 1 - conversation.size} oldest turns to fit")+            }+            val sampling = Sampling.Chat.copy(seed = System.nanoTime())+            val generator = ChatGenerator { continuation, onRaw ->+                withContext(engineThread) {+                    model.generate(conversation, request.system, declarations, CHAT_REPLY_LIMIT, continuation, sampling, onRaw)+                }+            }+            val outcome = runToolLoop(+                generator = generator,+                executeTool = { call ->+                    withContext(Dispatchers.IO) { tools.invoke(call) }.also {+                        Log.status(TAG, "tool ${call.name} -> ${it.take(LOG_CHARS)}")+                    }+                },+                renderToolResponse = Gemma4Handle::renderToolResponse,+                onVisible = onText,+            )+            when (outcome) {+                is ToolLoopOutcome.Finished -> ChatResult.Reply(outcome.text, halted = false)+                is ToolLoopOutcome.Halted -> ChatResult.Reply(outcome.text, halted = true)+                is ToolLoopOutcome.Failed -> ChatResult.Unavailable+            }+        }++    /** Single-turn structured extraction: greedy, no tools, no history. Null when unavailable. */+    suspend fun extract(system: String, userText: String, imagePaths: List<String>, onText: (String) -> Boolean): String? =+        mutex.withLock {+            withContext(engineThread) {+                val model = model() ?: return@withContext null+                val turn = currentTurn(ChatRequest(system, emptyList(), userText, imagePaths))+                model.generate(listOf(turn), system, emptyList(), EXTRACT_REPLY_LIMIT, "", Sampling.Greedy, onText)+            }+        }++    private fun model(): Gemma4Handle? {+        handle?.takeIf { it.isAvailable }?.let { return it }+        handle?.close()+        val opened = Gemma4Handle.inDirectory(modelDir)+        if (!opened.isAvailable) {+            Log.status(TAG, "gemma4 did not load from $modelDir")+            opened.close()+            handle = null+            return null+        }+        handle = opened+        prefixKey = null+        return opened+    }++    private fun seedPrefix(model: Gemma4Handle, system: String, tools: List<Gemma4Handle.ToolDeclaration>) {+        val declared = Gemma4Handle.declareTools(tools)+        val key = (system + "\u0000" + declared).hashCode()+        if (key == prefixKey) return+        prefixKey = key+        if (!model.loadPrefix("<bos><|turn>system\n$system$declared<turn|>\n")) {+            Log.status(TAG, "no matching baked prefix; the system block will be prefilled")+        }+    }++    private fun currentTurn(request: ChatRequest): Gemma4Handle.Turn {+        val images = if (request.imagePaths.isEmpty()) emptyList() else encodeImages(request.imagePaths)+        val clips = request.audioPath?.let { encodeAudio(it) }?.let { listOf(it) } ?: emptyList()+        if (request.imagePaths.isNotEmpty() || request.audioPath != null) scheduleTowerUnload()+        return Gemma4Handle.Turn(Gemma4Handle.Role.USER, request.userText, images, clips)+    }++    private fun encodeImages(paths: List<String>): List<FloatArray> {+        val tower = vision?.takeIf { it.isAvailable }+            ?: Gemma4VisionHandle.inDirectory(modelDir).also { vision = it }+        if (!tower.isAvailable) {+            Log.status(TAG, "vision tower unavailable; dropping ${paths.size} images")+            return emptyList()+        }+        return paths.mapNotNull { path ->+            val bitmap = decodeDownscaled(path) ?: return@mapNotNull null+            tower.encode(bitmap, Gemma4VisionHandle.SOFT_TOKENS_DEFAULT).also { bitmap.recycle() }+        }+    }++    private fun encodeAudio(path: String): FloatArray? {+        val file = File(path)+        if (!file.isFile) return null+        val samples = runCatching { decodeWavMono16k(file.readBytes()) }.getOrNull()+        if (samples == null) {+            Log.status(TAG, "$path is not 16 kHz mono 16-bit PCM")+            return null+        }+        val tower = audio?.takeIf { it.isAvailable }+            ?: Gemma4AudioHandle.inDirectory(modelDir).also { audio = it }+        if (!tower.isAvailable) {+            Log.status(TAG, "audio tower unavailable; dropping the clip")+            return null+        }+        return tower.encode(samples)+    }++    private fun scheduleTowerUnload() {+        towerIdleJob?.cancel()+        towerIdleJob = scope.launch {+            delay(TOWER_IDLE_MILLIS)+            mutex.withLock {+                withContext(engineThread) {+                    vision?.close()+                    vision = null+                    audio?.close()+                    audio = null+                }+            }+        }+    }++    override fun close() {+        scope.cancel()+        executor.execute {+            vision?.close()+            audio?.close()+            handle?.close()+            vision = null+            audio = null+            handle = null+        }+        executor.shutdown()+    }++    private companion object {+        const val TAG = "MamlChatEngine"+        const val CHAT_REPLY_LIMIT = 1024+        const val EXTRACT_REPLY_LIMIT = 1024+        const val TOWER_IDLE_MILLIS = 3 * 60_000L+        const val MAX_IMAGE_SIDE = 1024+        const val LOG_CHARS = 120++        fun decodeDownscaled(path: String): Bitmap? {+            val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }+            BitmapFactory.decodeFile(path, bounds)+            if (bounds.outWidth <= 0 || bounds.outHeight <= 0) {+                Log.status(TAG, "cannot decode $path")+                return null+            }+            var sample = 1+            while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= MAX_IMAGE_SIDE) sample *= 2+            val options = BitmapFactory.Options().apply {+                inSampleSize = sample+                inPreferredConfig = Bitmap.Config.ARGB_8888+            }+            return runCatching { BitmapFactory.decodeFile(path, options) }.getOrNull()+        }+    }+}
openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantDeviceTools.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantDeviceTools.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantDeviceTools.ktindex 51860ba14b..ae8bedf125 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantDeviceTools.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantDeviceTools.kt@@ -12,7 +12,7 @@ import kotlin.time.Clock  /**  * Device-local tools (app list, messaging, memories, clock helpers) backing- * [AssistantToolSet]. Split from [AssistantToolIntents] so neither class+ * [com.vayunmathur.openassistant.platform.AssistantTools]. Split from [AssistantToolIntents] so neither class  * exceeds the TooManyFunctions limit.  */ internal class AssistantDeviceTools(private val context: Context) {
openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolIntents.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolIntents.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolIntents.ktindex 647a5f8495..14597dda06 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolIntents.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolIntents.kt@@ -23,10 +23,14 @@ import kotlinx.datetime.toLocalDateTime import kotlin.time.Clock import kotlinx.coroutines.CancellationException import kotlinx.coroutines.runBlocking+import com.vayunmathur.openassistant.MainActivity+import kotlinx.serialization.ExperimentalSerializationApi+import kotlinx.serialization.json.Json+import kotlinx.serialization.serializer  /**- * Intent-launching back end for [AssistantToolSet]. Holds no @Tool functions- * itself so the tool class stays under the TooManyFunctions limit; every tool+ * Intent-launching back end for the assistant tool registry+ * ([com.vayunmathur.openassistant.platform.AssistantTools]); every tool  * delegates here for the actual cross-app call.  */ internal class AssistantToolIntents(private val context: Context) {@@ -205,3 +209,49 @@ internal class AssistantToolIntents(private val context: Context) {         return "Success: Added memory"     } }++class MissingAppException(val packageName: String) : Exception("App $packageName is not installed.")+[email protected]+data class WeatherLatLonRequest(val latitude: Double, val longitude: Double)+[email protected]+data class WeatherNameRequest(val name: String)+[email protected]+data class CreateLinkRequest(val name: String, val expiryMillis: Long)++@OptIn(ExperimentalSerializationApi::class)+suspend inline fun <reified Input : Any, reified Output : Any> launchIntent(+    context: Context,+    packageName: String,+    className: String,+    input: Input,+): Output {+    val stringOutput = MainActivity.intentLauncher.launch(+        context,+        packageName,+        className,+        serializer<Input>(),+        input,+    )+    if (stringOutput == "package $packageName doesn't exist") throw MissingAppException(packageName)+    return Json.decodeFromString(serializer<Output>(), stringOutput)+}++@OptIn(ExperimentalSerializationApi::class)+suspend inline fun <reified Input : Any> launchIntentU(+    context: Context,+    packageName: String,+    className: String,+    input: Input,+) {+    val stringOutput = MainActivity.intentLauncher.launch(+        context,+        packageName,+        className,+        serializer<Input>(),+        input,+    )+    if (stringOutput == "package $packageName doesn't exist") throw MissingAppException(packageName)+}
openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolSet.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolSet.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolSet.ktdeleted file mode 100644index 5c9a68cc29..0000000000--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantToolSet.kt+++ /dev/null@@ -1,220 +0,0 @@-package com.vayunmathur.openassistant.util-import android.annotation.SuppressLint-import android.content.Context-import com.vayunmathur.library.log.Log-import com.google.ai.edge.litertlm.Tool-import com.google.ai.edge.litertlm.ToolParam-import com.google.ai.edge.litertlm.ToolSet-import com.vayunmathur.library.intents.calendar.EventData-import com.vayunmathur.library.intents.clock.SetAlarmData-import com.vayunmathur.library.intents.clock.SetTimerData-import com.vayunmathur.library.intents.contacts.ContactData-import com.vayunmathur.library.intents.music.PlayMusicData-import com.vayunmathur.library.intents.notes.NoteData-import com.vayunmathur.openassistant.MainActivity-import com.vayunmathur.openassistant.data.MemoryDao-import com.vayunmathur.openassistant.data.MessageDao-import kotlinx.datetime.TimeZone-import kotlinx.datetime.toLocalDateTime-import kotlin.time.Clock-import kotlinx.coroutines.CancellationException-import kotlinx.coroutines.runBlocking-import kotlinx.serialization.ExperimentalSerializationApi-import kotlinx.serialization.json.Json-import kotlinx.serialization.serializer--class AssistantToolSet(-    private val context: Context,-    private val memoryDao: MemoryDao? = null,-    private val messageDao: MessageDao? = null,-    private val conversationId: Long = -1L,-) : ToolSet {-    private val intents = AssistantToolIntents(context)-    private val device = AssistantDeviceTools(context)--    @Tool(description = "Get a list of all notes")-    fun getNotes(): String = intents.runTool {-        intents.getNotes()-    }--    @Tool(description = "Create a new note in the notes app. Should only be used with EXPLICIT request by user")-    fun createNote(title: String, content: String): String = intents.runTool {-        intents.insertNote(NoteData(title, content))-        "Success: Created note '$title'"-    }--    @Tool(description = "Get a list of all contacts")-    fun getContacts(): String = intents.runTool {-        intents.getContacts()-    }--    @Tool(description = "Create a new contact")-    fun createContact(name: String, phoneNumber: String): String = intents.runTool {-        intents.insertContact(ContactData(name, phoneNumber))-        "Success: Created contact '$name'"-    }--    @Tool(description = "Get a list of calendar events. Each event's start and end times are epoch milliseconds.")-    fun getCalendarEvents(): String = intents.runTool {-        intents.getCalendarEvents()-    }--    @Tool(description = "Create a new calendar event. Start and end times must be epoch milliseconds.")-    fun createCalendarEvent(-        title: String,-        @ToolParam(description = "start time as epoch milliseconds") start: Double,-        @ToolParam(description = "end time as epoch milliseconds") end: Double,-        location: String = "",-    ): String = intents.runTool {-        intents.insertCalendarEvent(EventData(title, start.toLong(), end.toLong(), location))-        "Success: Created event '$title'"-    }--    @Tool(description = "Get a list of family members and their current locations")-    fun getFamilyLocations(): String = intents.runTool {-        intents.getFamilyLocations()-    }--    @Tool(description = "Create a temporary FindFamily link that shares the user's live location.")-    fun createLocationShareLink(-        @ToolParam(description = "name or label for who the link is for") name: String,-        @ToolParam(description = "how long the link stays active, in milliseconds") durationMillis: Double,-    ): String = intents.runTool {-        intents.createLocationShareLink(name, durationMillis)-    }--    @Tool(description = "Search for music (songs, albums, artists, or playlists)")-    fun searchMusic(query: String): String = intents.runTool {-        intents.searchMusic(query)-    }--    @Tool(description = "Play music given its id and type (song, album, artist, or playlist)")-    fun playMusic(id: Double, type: String): String = intents.runTool {-        intents.playMusic(PlayMusicData(id.toLong(), type))-        "Success: Playing music"-    }--    @Tool(description = "Search emails by keyword")-    fun searchEmails(query: String): String = intents.runTool {-        intents.searchEmails(query)-    }--    @Tool(description = "Get recent emails from the inbox")-    fun getRecentEmails(): String = intents.runTool {-        intents.getRecentEmails()-    }--    @Tool(description = "Get the current date and time in the local timezone.")-    fun getLocalCurrentDateTime(): String = device.getLocalCurrentDateTime()--    @SuppressLint("QueryPermissionsNeeded")-    @Tool(description = "Get a list of installed apps on the device")-    fun getAppList(): String = device.getAppList()--    @Tool(description = "Open an app given its package id")-    fun openApp(@ToolParam(description = "package id") packageId: String): String =-        device.openApp(packageId, intents::handleMissingApp)--    @Tool(description = "Send a message")-    fun sendMessage(recipient: String, message: String): String =-        device.sendMessage(recipient, message)--    @Tool(description = "Make a phone call")-    fun makePhoneCall(recipient: String): String = device.makePhoneCall(recipient)--    @Tool(description = "Set an alarm in the Clock app at a specific hour and minute (24-hour time).")-    fun setAlarm(-        @ToolParam(description = "hour in 24-hour format, 0-23") hour: Double,-        @ToolParam(description = "minute, 0-59") minute: Double,-        @ToolParam(description = "optional label for the alarm") label: String = "",-    ): String = intents.runTool {-        intents.setAlarm(SetAlarmData(hour.toInt(), minute.toInt(), label))-        "Success: Alarm set for %02d:%02d".format(hour.toInt(), minute.toInt())-    }--    @Tool(description = "Start a countdown timer in the Clock app for a number of seconds.")-    fun setTimer(-        @ToolParam(description = "timer length in seconds") seconds: Double,-        @ToolParam(description = "optional label for the timer") label: String = "",-    ): String = intents.runTool {-        intents.setTimer(SetTimerData(seconds.toInt(), label))-        "Success: Timer started for ${seconds.toInt()}s"-    }--    @Tool("Set title of current conversation. Mandatory for first response")-    fun setConversationTitle(newTitle: String): String = device.setConversationTitle(newTitle)--    @Tool(description = "Get the current weather conditions at a specific latitude/longitude.")-    fun getWeather(latitude: Double, longitude: Double): String = intents.runTool {-        intents.getWeather(latitude, longitude)-    }--    @Tool(description = "Get the current weather conditions for a named place (city, address, landmark).")-    fun getWeatherByName(-        @ToolParam(description = "city or place name") location: String,-    ): String = intents.runTool {-        intents.getWeatherByName(location)-    }--    @Tool(description = "Get a list of all memories")-    fun getMemories(): String = intents.runTool {-        device.getMemories(memoryDao)-    }--    @Tool(description = "Remove a memory by its id")-    fun removeMemory(id: Double): String = intents.runTool {-        device.removeMemory(memoryDao, id)-    }--    @Tool(description = "Add a new memory to the list of memories")-    fun addToMemory(content: String): String = intents.runTool {-        device.addToMemory(memoryDao, content)-    }-}--class MissingAppException(val packageName: String) : Exception("App $packageName is not installed.")-class StopInferenceException : Exception("STOP")-[email protected]-data class WeatherLatLonRequest(val latitude: Double, val longitude: Double)-[email protected]-data class WeatherNameRequest(val name: String)-[email protected]-data class CreateLinkRequest(val name: String, val expiryMillis: Long)--@OptIn(ExperimentalSerializationApi::class)-suspend inline fun <reified Input : Any, reified Output : Any> launchIntent(-    context: Context,-    packageName: String,-    className: String,-    input: Input,-): Output {-    val stringOutput = MainActivity.intentLauncher.launch(-        context,-        packageName,-        className,-        serializer<Input>(),-        input,-    )-    if (stringOutput == "package $packageName doesn't exist") throw MissingAppException(packageName)-    return Json.decodeFromString(serializer<Output>(), stringOutput)-}--@OptIn(ExperimentalSerializationApi::class)-suspend inline fun <reified Input : Any> launchIntentU(-    context: Context,-    packageName: String,-    className: String,-    input: Input,-) {-    val stringOutput = MainActivity.intentLauncher.launch(-        context,-        packageName,-        className,-        serializer<Input>(),-        input,-    )-    if (stringOutput == "package $packageName doesn't exist") throw MissingAppException(packageName)-}
openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.ktindex 17535a9f60..397ee99bae 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt@@ -13,38 +13,35 @@ import android.os.ResultReceiver import com.vayunmathur.library.log.Log import androidx.core.app.NotificationCompat import androidx.core.content.IntentCompat-import com.google.ai.edge.litertlm.Backend-import com.google.ai.edge.litertlm.Content-import com.google.ai.edge.litertlm.Contents-import com.google.ai.edge.litertlm.Conversation-import com.google.ai.edge.litertlm.ConversationConfig-import com.google.ai.edge.litertlm.Engine-import com.google.ai.edge.litertlm.EngineConfig-import com.google.ai.edge.litertlm.ExperimentalApi-import com.google.ai.edge.litertlm.ExperimentalFlags-import com.google.ai.edge.litertlm.tool import com.vayunmathur.library.util.SecureResultReceiver import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.openassistant.platform.AssistantTools+import com.vayunmathur.openassistant.platform.ChatRequest+import com.vayunmathur.openassistant.platform.ChatResult+import com.vayunmathur.openassistant.platform.HistoryTurn+import com.vayunmathur.openassistant.platform.MamlChatEngine import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.cancel+import kotlinx.coroutines.cancelAndJoin+import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout-import kotlinx.coroutines.flow.catch import java.io.File+import java.util.concurrent.atomic.AtomicReference import kotlin.time.Clock-import com.vayunmathur.openassistant.data.AppDatabase import com.vayunmathur.openassistant.data.Message as DbMessage import com.vayunmathur.openassistant.data.OpenAssistantRepository-import kotlinx.serialization.json.Json-import kotlinx.serialization.json.JsonObject-import kotlinx.serialization.json.jsonPrimitive import com.vayunmathur.openassistant.R import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.selects.select@@ -62,10 +59,9 @@ class InferenceService : Service() {         internal const val EMBEDDING_OK_CODE = 0         private const val INTENT_TIMEOUT_MILLIS = 45000L         private const val INTENT_QUEUE_TTL_MILLIS = 45000L-        private const val INFERENCE_TIMEOUT_MILLIS = 45000L         private const val HISTORY_RECENCY_MILLIS = 1000L-        private const val ENGINE_SETTLE_MILLIS = 100L-        private const val INTENT_CONVERSATION_ID = -2L+        private const val DB_WRITE_INTERVAL_MILLIS = 100L+        private const val MODEL_DIR = "gemma4"          /** The system prompt used when the user has not set a custom one. */         val DEFAULT_SYSTEM_PROMPT = """@@ -105,7 +101,7 @@ class InferenceService : Service() {         /**          * A SigLIP2 embedding request from another app (photos). [mode] is          * "text", "image", or "info". Runs on [SiglipEmbedder], independent of-         * the litertlm chat [Engine], so it can be served while the LLM is busy.+         * the chat [MamlChatEngine], so it can be served while the LLM is busy.          */         data class Embedding(             val mode: String,@@ -134,10 +130,9 @@ class InferenceService : Service() {         InferenceEmbeddingHandler(applicationContext, serviceScope)     } -    /** Guards the on-demand SigLIP2 model download so we start it at most once. */-    private var engine: Engine? = null-    private var currentConversation: Conversation? = null-    private var currentConversationId: Long = -1L+    private var engine: MamlChatEngine? = null+    private val engineLock = Mutex()+    private val tools by lazy { AssistantTools(applicationContext, memoryDao) }      private val repository by lazy { OpenAssistantRepository.get(applicationContext) }     private val conversationDao get() = repository.conversationDaoRef@@ -198,7 +193,7 @@ class InferenceService : Service() {      // Embeddings run on their own consumer so they don't wait behind the     // (possibly long) chat/intent LLM jobs — they use SiglipEmbedder, not the-    // litertlm Engine.+    // chat engine.     private fun launchEmbeddingLoop() {         serviceScope.launch {             for (job in embeddingQueue) {@@ -295,15 +290,8 @@ class InferenceService : Service() {         try {             Log.debug("InferenceService", "Executing Intent Inference")             ensureEngineInitialized()--            currentConversation?.close()-            currentConversation = null-            delay(ENGINE_SETTLE_MILLIS)--            setupIntentConversation(job.schema)-             withTimeout(INTENT_TIMEOUT_MILLIS) {-                runIntentInferenceLoop(job.userText, job.imagePaths, job.schema, job.receiver)+                runIntentInference(job.userText, job.imagePaths, job.schema, job.receiver)             }         } catch (e: TimeoutCancellationException) {             Log.error("InferenceService", "Intent inference timed out after 45 seconds")@@ -312,8 +300,7 @@ class InferenceService : Service() {                 Bundle().apply { putString("error", getString(R.string.error_inference_timeout)) },             )         } catch (e: CancellationException) {-            if (e.message != "HALT") throw e-            Log.status("InferenceService", "Intent inference halted successfully via schema match.")+            throw e         } catch (expected: Exception) {             Log.error("InferenceService", "Error during intent inference", expected)             job.receiver.send(@@ -325,10 +312,6 @@ class InferenceService : Service() {                     )                 },             )-        } finally {-            currentConversation?.close()-            currentConversation = null-            currentConversationId = -1L         }     } @@ -347,46 +330,36 @@ class InferenceService : Service() {     // ---------- SigLIP2 embedding provider (served to the photos app) ----------     // Dispatch lives in [InferenceEmbeddingHandler]; queue types are public aliases above. -    private suspend fun resetConversation(conversationId: Long, userText: String) {-        currentConversation?.close()-        currentConversation = null-        delay(ENGINE_SETTLE_MILLIS)+    private suspend fun loadHistory(conversationId: Long, userText: String): List<HistoryTurn> {         val cutoff = Clock.System.now().toEpochMilliseconds() - HISTORY_RECENCY_MILLIS-        val history = fetchHistoryFromDb(conversationId)+        return fetchHistoryFromDb(conversationId)             .filter { it.text != userText || it.timestamp < cutoff }-        setupConversation(conversationId, history)+            .map { HistoryTurn(fromUser = it.role != "assistant", text = it.text) }     }      private suspend fun executeStandardInference(job: InferenceJob.Standard) {         try {             ensureEngineInitialized()-            val stale = currentConversationId != job.conversationId ||-                currentConversation == null ||-                currentConversation?.isAlive != true-            if (stale) {-                resetConversation(job.conversationId, job.userText)-            }             runInferenceLoop(job.conversationId, job.userText, job.imagePaths, job.audioPath)         } catch (e: CancellationException) {-            if (e.message != "HALT") throw e-            Log.status("InferenceService", "Standard inference halted successfully.")+            throw e         } catch (expected: Exception) {             Log.error("InferenceService", "Inference failed, resetting engine for retry", expected)-            retryStandardInference(job, expected)+            retryStandardInference(job)         }     } -    private suspend fun retryStandardInference(job: InferenceJob.Standard, ignored: Exception) {-        currentConversation?.close()-        currentConversation = null-        currentConversationId = -1L-        engine?.close()-        engine = null+    private suspend fun retryStandardInference(job: InferenceJob.Standard) {+        engineLock.withLock {+            engine?.close()+            engine = null+        }         try {             ensureEngineInitialized()-            resetConversation(job.conversationId, job.userText)             runInferenceLoop(job.conversationId, job.userText, job.imagePaths, job.audioPath)-        } catch (retryExpected: IllegalStateException) {+        } catch (e: CancellationException) {+            throw e+        } catch (retryExpected: Exception) {             Log.error("InferenceService", "Retry also failed", retryExpected)             val detail = retryExpected.localizedMessage ?: ""             upsertMessageToDb(@@ -400,96 +373,53 @@ class InferenceService : Service() {         }     } -    private fun setupIntentConversation(schema: String) {-        val systemPrompt = """-            You are a highly specialized data extraction engine.-            Your sole purpose is to analyze the provided images/text and output a SINGLE valid JSON object that adheres STRICTLY to the provided JSON schema.--            EXTREMELY IMPORTANT:-            1. DO NOT respond with any conversational text.-            2. DO NOT include any preamble, explanation, or postscript.-            3. Output ONLY the raw JSON object.-            4. Ensure all keys and values are properly quoted.+    private fun intentSystemPrompt(schema: String): String = """+        You are a highly specialized data extraction engine.+        Your sole purpose is to analyze the provided images/text and output a SINGLE valid JSON object that adheres STRICTLY to the provided JSON schema. -            SCHEMA:-            $schema+        EXTREMELY IMPORTANT:+        1. DO NOT respond with any conversational text.+        2. DO NOT include any preamble, explanation, or postscript.+        3. Output ONLY the raw JSON object.+        4. Ensure all keys and values are properly quoted. -            Start extraction immediately.-            """.trimIndent()+        SCHEMA:+        $schema -        currentConversation = engine?.createConversation(-            ConversationConfig(-                systemInstruction = Contents.of(systemPrompt),-                initialMessages = emptyList(),-                automaticToolCalling = false,-            ),-        )-        currentConversationId = INTENT_CONVERSATION_ID-    }+        Start extraction immediately.+        """.trimIndent() -    private suspend fun runIntentInferenceLoop(+    private suspend fun runIntentInference(         userText: String,         imagePaths: Array<String>,         schema: String,         receiver: ResultReceiver,     ) {-        val conv = currentConversation ?: return--        val initialContents = mutableListOf<Content>()-        imagePaths.forEach { path -> initialContents.add(Content.ImageFile(path)) }-        if (userText.isNotBlank()) {-            initialContents.add(Content.Text(userText))-        }--        val nextMessage = com.google.ai.edge.litertlm.Message.user(Contents.of(initialContents))--        var fullResponseText = ""-        Log.debug(-            "InferenceService",-            "Sending intent inference request (Streaming mode for safe interruption)",-        )--        val stream = conv.sendMessageAsync(nextMessage)--        stream.collect { chunk ->-            val chunkText = chunk.contents.contents-                .filterIsInstance<Content.Text>()-                .joinToString("") { it.text }-            fullResponseText += chunkText--            // Try to extract JSON and check if it matches schema-            val jsonCandidate = tryExtractLargestJson(fullResponseText)-            if (jsonCandidate != null) {-                val validationError = JsonSchemaValidator.validateJsonAgainstSchema(-                    jsonCandidate,-                    schema,-                )-                if (validationError == null) {-                    Log.status(-                        "InferenceService",-                        "Valid JSON extracted and verified against schema. Halting.",-                    )-                    receiver.send(-                        EMBEDDING_OK_CODE,-                        Bundle().apply { putString("json_result", jsonCandidate) },-                    )-                    throw CancellationException("HALT")-                }+        val chat = engine ?: throw IllegalStateException(getString(R.string.error_ai_engine_failed))+        val job = currentCoroutineContext()[Job]+        var sent = false+        Log.debug("InferenceService", "Sending intent inference request (streaming for early halt)")+        val reply = chat.extract(intentSystemPrompt(schema), userText, imagePaths.toList()) { text ->+            if (job?.isActive == false) return@extract false+            val candidate = tryExtractLargestJson(text)+            if (candidate != null && JsonSchemaValidator.validateJsonAgainstSchema(candidate, schema) == null) {+                Log.status("InferenceService", "Valid JSON extracted and verified against schema. Halting.")+                receiver.send(EMBEDDING_OK_CODE, Bundle().apply { putString("json_result", candidate) })+                sent = true+                false+            } else {+                true             }         }--        // If it finished without tryExtractLargestJson triggering HALT (e.g. at the very end)-        val finalJson = tryExtractLargestJson(fullResponseText)-        if (finalJson != null) {-            val validationError = JsonSchemaValidator.validateJsonAgainstSchema(finalJson, schema)-            if (validationError == null) {-                receiver.send(-                    EMBEDDING_OK_CODE,-                    Bundle().apply { putString("json_result", finalJson) },-                )-                Log.dev("InferenceService", "AI produced output: $finalJson")-                return-            }+        if (sent) return+        currentCoroutineContext()[Job]?.let { if (!it.isActive) throw CancellationException("intent cancelled") }+        if (reply == null) throw IllegalStateException(getString(R.string.error_ai_engine_failed))++        val finalJson = tryExtractLargestJson(reply)+        if (finalJson != null && JsonSchemaValidator.validateJsonAgainstSchema(finalJson, schema) == null) {+            receiver.send(EMBEDDING_OK_CODE, Bundle().apply { putString("json_result", finalJson) })+            Log.dev("InferenceService", "AI produced output: $finalJson")+            return         }          Log.error("InferenceService", "AI finished generation without providing a schema-matching JSON.")@@ -502,53 +432,20 @@ class InferenceService : Service() {     private fun tryExtractLargestJson(text: String): String? =         JsonExtractor.largestObject(text) -    private suspend fun ensureEngineInitialized() {-        if (engine != null) return--        @OptIn(ExperimentalApi::class)-        ExperimentalFlags.enableSpeculativeDecoding = true--        val modelFile = File(applicationContext.getExternalFilesDir(null)!!, "gemma4-2b.litertlm")-        if (!modelFile.exists()) {-            throw IllegalStateException("Model file missing at ${modelFile.absolutePath}")-        }--        val config = EngineConfig(-            modelPath = modelFile.absolutePath,-            backend = Backend.GPU(),-            visionBackend = Backend.GPU(),-            audioBackend = Backend.CPU(),-            cacheDir = applicationContext.cacheDir.absolutePath,-        )--        val newEngine = Engine(config)-        withContext(Dispatchers.IO) {-            newEngine.initialize()+    private suspend fun ensureEngineInitialized() = engineLock.withLock {+        if (engine != null) return@withLock+        val dir = File(applicationContext.getExternalFilesDir(null), MODEL_DIR)+        val created = MamlChatEngine(dir)+        if (!created.load()) {+            created.close()+            throw IllegalStateException("Model missing or failed to load at ${dir.absolutePath}")         }-        engine = newEngine+        engine = created     } -    private suspend fun setupConversation(id: Long, history: List<DbMessage>) {+    private suspend fun systemPrompt(): String {         val stored = DataStoreUtils.getInstance(applicationContext).getStringAwait(KEY_SYSTEM_PROMPT)-        val systemPrompt = if (stored.isNullOrBlank()) DEFAULT_SYSTEM_PROMPT else stored--        val initialMessages = history.map { msg ->-            when (msg.role) {-                "user" -> com.google.ai.edge.litertlm.Message.user(Contents.of(msg.text))-                "assistant" -> com.google.ai.edge.litertlm.Message.model(Contents.of(msg.text))-                else -> com.google.ai.edge.litertlm.Message.user(Contents.of(msg.text))-            }-        }--        currentConversation = engine?.createConversation(-            ConversationConfig(-                systemInstruction = Contents.of(systemPrompt),-                initialMessages = initialMessages,-                tools = listOf(tool(AssistantToolSet(applicationContext, memoryDao, messageDao, id))),-                automaticToolCalling = true,-            ),-        )-        currentConversationId = id+        return if (stored.isNullOrBlank()) DEFAULT_SYSTEM_PROMPT else stored     }      private suspend fun runInferenceLoop(@@ -557,7 +454,14 @@ class InferenceService : Service() {         imagePaths: Array<String>,         audioPath: String?,     ) {-        val conv = currentConversation ?: return+        val chat = engine ?: throw IllegalStateException(getString(R.string.error_ai_engine_failed))+        val request = ChatRequest(+            system = systemPrompt(),+            history = loadHistory(conversationId, userText),+            userText = userText,+            imagePaths = imagePaths.toList(),+            audioPath = audioPath?.takeIf { File(it).exists() },+        )          val aiMsgId = upsertMessageToDb(             DbMessage(@@ -568,50 +472,61 @@ class InferenceService : Service() {             ),         ) -        var fullResponseText = ""-        val contents = mutableListOf<Content>()-        imagePaths.forEach { path -> contents.add(Content.ImageFile(path)) }-        audioPath?.let { if (File(it).exists()) contents.add(Content.AudioFile(it)) }-        if (userText.isNotBlank()) contents.add(Content.Text(userText))--        val stream = conv.sendMessageAsync(com.google.ai.edge.litertlm.Message.user(Contents.of(contents)))+        val job = currentCoroutineContext()[Job]+        val latest = AtomicReference("")+        val writer = serviceScope.launch {+            var written = ""+            while (isActive) {+                delay(DB_WRITE_INTERVAL_MILLIS)+                flushTitle(conversationId)+                val text = latest.get()+                if (text.isNotBlank() && text != written) {+                    updateMessageInDb(aiMsgId, text)+                    written = text+                }+            }+        }+        val result = try {+            chat.chat(request, tools) { text ->+                if (halt || job?.isActive == false) {+                    false+                } else {+                    latest.set(text)+                    true+                }+            }+        } catch (e: Exception) {+            withContext(NonCancellable) { messageDao.deleteById(aiMsgId) }+            throw e+        } finally {+            withContext(NonCancellable) { writer.cancelAndJoin() }+        }+        flushTitle(conversationId) -        stream.catch { e ->-            Log.debug("InferenceService", "Caught inference error: ${e::class.simpleName}", e)-            if (isBenignInterruption(e)) {+        when (result) {+            is ChatResult.Reply -> if (result.halted || halt) {                 halt = false                 messageDao.deleteById(aiMsgId)-            } else {-                messageDao.deleteById(aiMsgId)-                throw e+                Log.status("InferenceService", "Standard inference halted successfully.")+            } else if (result.text.isNotBlank()) {+                updateMessageInDb(aiMsgId, result.text)             }-        }.collect { chunk ->-            if (halt) {-                halt = false+            ChatResult.TooLong -> updateMessageInDb(+                aiMsgId,+                getString(R.string.error_prefix, "the message is too long for the model's context"),+            )+            ChatResult.Unavailable -> {                 messageDao.deleteById(aiMsgId)-                throw CancellationException("HALT")-            }-            val chunkText = chunk.contents.contents-                .filterIsInstance<Content.Text>()-                .joinToString("") { it.text }-            fullResponseText += chunkText--            if (newTitle != null) {-                updateTitleInDb(conversationId, newTitle!!)-                newTitle = null-            }--            if (fullResponseText.isNotBlank()) {-                updateMessageInDb(aiMsgId, fullResponseText)+                throw IllegalStateException(getString(R.string.error_ai_engine_failed))             }         }     } -    private fun isBenignInterruption(e: Throwable): Boolean =-        e is MissingAppException ||-            e is StopInferenceException ||-            e.cause is StopInferenceException ||-            halt+    private suspend fun flushTitle(conversationId: Long) {+        val title = newTitle ?: return+        newTitle = null+        updateTitleInDb(conversationId, title)+    }      private suspend fun fetchHistoryFromDb(id: Long): List<DbMessage> = messageDao.getByConversation(id)     private suspend fun upsertMessageToDb(msg: DbMessage): Long = messageDao.upsert(msg)@@ -628,8 +543,8 @@ class InferenceService : Service() {      override fun onDestroy() {         serviceScope.cancel()-        currentConversation?.close()         engine?.close()+        engine = null         super.onDestroy()     } }
openassistant/src/test/java/com/vayunmathur/openassistant/domain/HistoryFitTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/HistoryFitTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/HistoryFitTest.ktnew file mode 100644index 0000000000..d25f6c4f05--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/HistoryFitTest.kt@@ -0,0 +1,38 @@+package com.vayunmathur.openassistant.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++class HistoryFitTest {++    private data class T(val user: Boolean, val cost: Int)++    private fun fitsUnder(budget: Int): (List<T>) -> Boolean = { turns -> turns.sumOf { it.cost } <= budget }++    private val history = listOf(T(true, 10), T(false, 10), T(true, 10), T(false, 10))+    private val current = T(true, 5)++    @Test+    fun keepsEverythingWhenItFits() {+        assertEquals(history + current, fitConversation(history, current, T::user, fitsUnder(100)))+    }++    @Test+    fun dropsOldestTurnsAndStartsOnAUserTurn() {+        assertEquals(listOf(T(true, 10), T(false, 10), current), fitConversation(history, current, T::user, fitsUnder(30)))+        // 35 fits three turns, but the oldest kept would be a model turn, so it goes too.+        assertEquals(listOf(T(true, 10), T(false, 10), current), fitConversation(history, current, T::user, fitsUnder(35)))+    }++    @Test+    fun neverDropsTheCurrentTurn() {+        assertEquals(listOf(current), fitConversation(history, current, T::user, fitsUnder(5)))+        assertNull(fitConversation(history, current, T::user, fitsUnder(4)))+    }++    @Test+    fun emptyHistory() {+        assertEquals(listOf(current), fitConversation(emptyList(), current, T::user, fitsUnder(5)))+    }+}
openassistant/src/test/java/com/vayunmathur/openassistant/domain/ToolCallsTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/ToolCallsTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/ToolCallsTest.ktnew file mode 100644index 0000000000..b8e216eab1--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/ToolCallsTest.kt@@ -0,0 +1,73 @@+package com.vayunmathur.openassistant.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertIs+import kotlin.test.assertNull+import kotlin.test.assertTrue++class ToolCallsTest {++    private val q = "<|\"|>"++    @Test+    fun parsesQuotedAndBareArguments() {+        val reply = "Sure.<|tool_call>call:set_timer{label:${q}tea${q},seconds:120}<tool_call|>"+        assertEquals(+            ParsedToolCall("set_timer", mapOf("label" to "tea", "seconds" to "120")),+            parseToolCall(reply),+        )+    }++    @Test+    fun parsesCallWithoutArguments() {+        assertEquals(ParsedToolCall("get_notes", emptyMap()), parseToolCall("<|tool_call>call:get_notes{}<tool_call|>"))+    }++    @Test+    fun quotedValueMayContainCommasAndColons() {+        val call = parseToolCall("<|tool_call>call:create_note{content:${q}a, b: c${q},title:${q}x${q}}<tool_call|>")+        assertEquals("a, b: c", call?.arguments?.get("content"))+        assertEquals("x", call?.arguments?.get("title"))+    }++    @Test+    fun incompleteOrMalformedCallsDoNotParse() {+        assertNull(parseToolCall("<|tool_call>call:set_timer{seconds:12"))+        assertFalse(hasCompleteToolCall("<|tool_call>call:set_timer{seconds:12"))+        assertNull(parseToolCall("<|tool_call>call:{seconds:1}<tool_call|>"))+        assertNull(parseToolCall("<|tool_call>call:x{label:${q}open}<tool_call|>"))+        assertEquals("x", toolCallNameGuess("<|tool_call>call:x{label:${q}open}<tool_call|>"))+        assertNull(parseToolCall("plain text"))+    }++    @Test+    fun stripsCompleteBlocksAndUnclosedTails() {+        val reply = "Hello <|tool_call>call:a{}<tool_call|>world"+        assertEquals("Hello world", stripToolMarkup(reply))+        assertEquals("Let me check", stripToolMarkup("Let me check<|tool_call>call:get_no"))+        assertEquals("A", stripToolMarkup("A<|tool_response>response:x{value:1}"))+    }++    @Test+    fun hidesHalfWrittenMarkersOnlyWhileStreaming() {+        assertEquals("Hi ", stripToolMarkup("Hi <|too"))+        assertEquals("Hi ", stripToolMarkup("Hi <"))+        assertEquals("Hi <", stripToolMarkup("Hi <", streaming = false))+        assertEquals("a <b", stripToolMarkup("a <b"))+        assertEquals("x < y and more", stripToolMarkup("x < y and more"))+    }++    @Test+    fun coercesNumbersAndReportsBadArguments() {+        val spec = ASSISTANT_TOOL_SPECS.first { it.name == "set_timer" }+        val ok = assertIs<ToolArgsResult.Ok>(coerceToolArgs(spec, mapOf("seconds" to " 90.0 ")))+        assertEquals(90.0, ok.args.number("seconds"))+        assertEquals("", ok.args.string("label"))+        val bad = assertIs<ToolArgsResult.Invalid>(coerceToolArgs(spec, mapOf("seconds" to "soon")))+        assertTrue(bad.message.startsWith("Error:"))+        assertIs<ToolArgsResult.Invalid>(coerceToolArgs(spec, emptyMap()))+        assertIs<ToolArgsResult.Invalid>(coerceToolArgs(spec, mapOf("seconds" to "")))+    }+}
openassistant/src/test/java/com/vayunmathur/openassistant/domain/ToolLoopTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/ToolLoopTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/ToolLoopTest.ktnew file mode 100644index 0000000000..e5964923f1--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/ToolLoopTest.kt@@ -0,0 +1,89 @@+package com.vayunmathur.openassistant.domain++import kotlinx.coroutines.runBlocking+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertIs+import kotlin.test.assertTrue++class ToolLoopTest {++    private class FakeGenerator(private val replies: List<String>) : ChatGenerator {+        val continuations = mutableListOf<String>()+        override suspend fun generate(continuation: String, onText: (String) -> Boolean): String? {+            continuations += continuation+            val reply = replies.getOrNull(continuations.size - 1) ?: return null+            var out = ""+            for (ch in reply) {+                out += ch+                if (!onText(out)) return out+            }+            return out+        }+    }++    private val render = { name: String, value: String -> "<R:$name=$value>" }++    @Test+    fun callThenTextRunsTheToolAndContinuesInsideTheTurn() = runBlocking<Unit> {+        val generator = FakeGenerator(+            listOf("<|tool_call>call:set_timer{seconds:60}<tool_call|><|tool_response>", "Timer set."),+        )+        val calls = mutableListOf<ParsedToolCall>()+        val shown = mutableListOf<String>()+        val outcome = runToolLoop(generator, { calls += it; "ok" }, render) { shown += it; true }+        assertEquals(ToolLoopOutcome.Finished("Timer set."), outcome)+        assertEquals(listOf(ParsedToolCall("set_timer", mapOf("seconds" to "60"))), calls)+        assertEquals("<|tool_call>call:set_timer{seconds:60}<tool_call|><R:set_timer=ok>", generator.continuations[1])+        assertTrue(shown.none { "<" in it })+    }++    @Test+    fun stopsGeneratingAsSoonAsACallCloses() = runBlocking<Unit> {+        val generator = FakeGenerator(listOf("<|tool_call>call:get_notes{}<tool_call|> trailing junk", "done"))+        runToolLoop(generator, { "[]" }, render) { true }+        assertEquals("<|tool_call>call:get_notes{}<tool_call|><R:get_notes=[]>", generator.continuations[1])+    }++    @Test+    fun roundCapEndsTheTurn() = runBlocking<Unit> {+        val call = "<|tool_call>call:get_notes{}<tool_call|>"+        val generator = FakeGenerator(List(10) { call })+        var executed = 0+        val outcome = runToolLoop(generator, { executed++; "x" }, render, maxRounds = 6) { true }+        assertIs<ToolLoopOutcome.Finished>(outcome)+        assertEquals(6, generator.continuations.size)+        assertEquals(5, executed)+    }++    @Test+    fun malformedCallGetsAnErrorResponseNotACrash() = runBlocking<Unit> {+        val generator = FakeGenerator(listOf("<|tool_call>call:oops<tool_call|>", "Sorry."))+        var executed = 0+        val outcome = runToolLoop(generator, { executed++; "x" }, render) { true }+        assertEquals(ToolLoopOutcome.Finished("Sorry."), outcome)+        assertEquals(0, executed)+        assertTrue(generator.continuations[1].contains("<R:oops=Error: malformed tool call"))+    }++    @Test+    fun haltStopsTheLoop() = runBlocking<Unit> {+        val generator = FakeGenerator(listOf("Hello there", "unused"))+        val outcome = runToolLoop(generator, { "x" }, render) { it.length < 5 }+        assertEquals(ToolLoopOutcome.Halted("Hello"), outcome)+        assertEquals(1, generator.continuations.size)+    }++    @Test+    fun proseFromEveryRoundIsKept() = runBlocking<Unit> {+        val generator = FakeGenerator(listOf("Checking.<|tool_call>call:get_notes{}<tool_call|>", "You have none."))+        val outcome = runToolLoop(generator, { "[]" }, render) { true }+        assertEquals(ToolLoopOutcome.Finished("Checking.\n\nYou have none."), outcome)+    }++    @Test+    fun generatorFailureIsReported() = runBlocking<Unit> {+        val outcome = runToolLoop(FakeGenerator(emptyList()), { "x" }, render) { true }+        assertIs<ToolLoopOutcome.Failed>(outcome)+    }+}
openassistant/src/test/java/com/vayunmathur/openassistant/domain/WavDecoderTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/WavDecoderTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/WavDecoderTest.ktnew file mode 100644index 0000000000..4bf41a2d6e--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/WavDecoderTest.kt@@ -0,0 +1,52 @@+package com.vayunmathur.openassistant.domain++import java.nio.ByteBuffer+import java.nio.ByteOrder+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull++class WavDecoderTest {++    private fun wav(samples: ShortArray, rate: Int = 16_000, channels: Int = 1, bits: Int = 16, extraChunk: Boolean = false): ByteArray {+        val extra = if (extraChunk) 8 + 5 + 1 else 0+        val data = samples.size * 2+        val buffer = ByteBuffer.allocate(44 + extra + data).order(ByteOrder.LITTLE_ENDIAN)+        buffer.put("RIFF".toByteArray()).putInt(36 + extra + data).put("WAVE".toByteArray())+        buffer.put("fmt ".toByteArray()).putInt(16).putShort(1).putShort(channels.toShort())+            .putInt(rate).putInt(rate * channels * bits / 8).putShort((channels * bits / 8).toShort())+            .putShort(bits.toShort())+        if (extraChunk) buffer.put("LIST".toByteArray()).putInt(5).put(ByteArray(5 + 1))+        buffer.put("data".toByteArray()).putInt(data)+        samples.forEach { buffer.putShort(it) }+        return buffer.array()+    }++    @Test+    fun decodesTheRecordersCanonicalHeader() {+        val out = assertNotNull(decodeWavMono16k(wav(shortArrayOf(0, 16384, -32768, 32767))))+        assertEquals(listOf(0f, 0.5f, -1f, 32767 / 32768f), out.toList())+    }++    @Test+    fun skipsUnknownChunksIncludingOddPadding() {+        val out = assertNotNull(decodeWavMono16k(wav(shortArrayOf(100, 200), extraChunk = true)))+        assertEquals(2, out.size)+    }++    @Test+    fun capsAtTheSampleLimit() {+        val out = assertNotNull(decodeWavMono16k(wav(ShortArray(10)), maxSamples = 4))+        assertEquals(4, out.size)+    }++    @Test+    fun refusesOtherFormats() {+        assertNull(decodeWavMono16k(wav(ShortArray(4), rate = 44_100)))+        assertNull(decodeWavMono16k(wav(ShortArray(4), channels = 2)))+        assertNull(decodeWavMono16k(wav(ShortArray(4), bits = 8)))+        assertNull(decodeWavMono16k(ByteArray(10)))+        assertNull(decodeWavMono16k("RIFF0000WAVE".toByteArray()))+    }+}
openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.ktnew file mode 100644index 0000000000..3903fb1ceb--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt@@ -0,0 +1,62 @@+package com.vayunmathur.openassistant.platform++import com.vayunmathur.library.ml.declareGemma4Tools+import com.vayunmathur.openassistant.domain.ASSISTANT_TOOL_SPECS+import com.vayunmathur.openassistant.domain.ToolParamType+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class AssistantToolsTest {++    private val snake = Regex("[a-z]+(_[a-z]+)*")++    @Test+    fun namesAreUniqueSnakeCase() {+        val names = ASSISTANT_TOOL_SPECS.map { it.name }+        assertEquals(25, names.size)+        assertEquals(names.size, names.toSet().size)+        for (spec in ASSISTANT_TOOL_SPECS) {+            assertTrue(snake.matches(spec.name), spec.name)+            assertTrue(spec.description.isNotBlank(), spec.name)+            assertEquals(spec.params.size, spec.params.map { it.name }.toSet().size, spec.name)+            spec.params.forEach { assertTrue(snake.matches(it.name), "${spec.name}.${it.name}") }+        }+    }++    @Test+    fun declarationsMirrorTheSpecs() {+        for (spec in ASSISTANT_TOOL_SPECS) {+            val declaration = spec.toDeclaration()+            assertEquals(spec.name, declaration.name)+            assertEquals(spec.description, declaration.description)+            assertEquals(spec.params.map { it.name }, declaration.parameters.map { it.name })+            assertEquals(spec.params.map { it.required }, declaration.parameters.map { it.required })+            assertEquals(spec.params.map { it.type.gemmaName }, declaration.parameters.map { it.type })+        }+    }++    @Test+    fun declarationTextNamesEveryToolAndMarksOptionalParams() {+        val text = declareGemma4Tools(ASSISTANT_TOOL_SPECS.map { it.toDeclaration() })+        ASSISTANT_TOOL_SPECS.forEach { assertTrue("declaration:${it.name}{" in text, it.name) }+        val timer = declareGemma4Tools(listOf(ASSISTANT_TOOL_SPECS.first { it.name == "set_timer" }.toDeclaration()))+        assertTrue("required:[<|\"|>seconds<|\"|>]" in timer, timer)+    }++    @Test+    fun numericParamsAreTheOnesLiteRtPassedAsDouble() {+        val numeric = ASSISTANT_TOOL_SPECS.flatMap { spec ->+            spec.params.filter { it.type == ToolParamType.NUMBER }.map { "${spec.name}.${it.name}" }+        }.toSet()+        assertEquals(+            setOf(+                "create_calendar_event.start", "create_calendar_event.end",+                "create_location_share_link.duration_millis", "play_music.id",+                "set_alarm.hour", "set_alarm.minute", "set_timer.seconds",+                "get_weather.latitude", "get_weather.longitude", "remove_memory.id",+            ),+            numeric,+        )+    }+}