Modern Apps git

← Modern-Apps.git

openassistant: fix detekt findings

Commit
3e7c8cc4c479d6b3f5b6f35cfa3b021968476840
Author
Vayun Mathur <[email protected]>
When
2026-11-17 14:23 UTC (19 days ago)
Parents
a13e0ae
Wrap over-long lines, extract named constants (CENTS_PER_DOLLAR, host-truncation caps), split LongMethod/CyclomaticComplexMethod functions (A2uiTemplates data builders, AssistantViewModel host-action dispatcher, InferenceService.runInferenceLoop), restructure ReturnCount offenders (parseSetCartItems, invokeConfirmed, handleHostAction), and split AssistantToolIntents by moving core cross-app intents to new AssistantCoreToolIntents (TooManyFunctions). ToolRisk host-gate semantics untouched: spec risk assignments, invokeConfirmed guard order and single markConsumed, and host confirm/send markers unchanged.

Verified: ./check openassistant green; :openassistant:testDevUnitTest green.

Diff

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.ktindex 1a049b2afa..ce05de174b 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt@@ -28,8 +28,9 @@ val ASSISTANT_TOOL_SPECS: List<ToolSpec> = listOf(     ),     ToolSpec(         "create_todo",-        "Create a task in the todo app (requires confirmation). Should only be used with EXPLICIT request by user. The title may " +-            "include words like 'tomorrow 6pm' or '#tag', which are understood when no due time is given.",+        "Create a task in the todo app (requires confirmation). Should only be used with " ++            "EXPLICIT request by user. The title may include words like 'tomorrow 6pm' or " ++            "'#tag', which are understood when no due time is given.",         listOf(             p("title"),             p("due", NUMBER, "optional due time as epoch milliseconds", required = false),@@ -46,7 +47,12 @@ val ASSISTANT_TOOL_SPECS: List<ToolSpec> = listOf(         ), risk = WRITE_CONFIRM,     ),     ToolSpec("get_contacts", "Get a list of all contacts"),-    ToolSpec("create_contact", "Create a new contact (requires confirmation)", listOf(p("name"), p("phone_number")), risk = WRITE_CONFIRM),+    ToolSpec(+        "create_contact",+        "Create a new contact (requires confirmation)",+        listOf(p("name"), p("phone_number")),+        risk = WRITE_CONFIRM,+    ),     ToolSpec(         "get_calendar_events",         "Get a list of calendar events. Each event's start and end times are epoch milliseconds.",@@ -118,7 +124,8 @@ val ASSISTANT_TOOL_SPECS: List<ToolSpec> = listOf(     ToolSpec(         "render_ui",         "Render a rich UI card (A2UI) attached to your reply. Prefer this over writing a ```a2ui fence. " +-            "components_json is a JSON string: {\"components\":[...]} (or a bare component array) using the RICH UI types; " ++            "components_json is a JSON string: {\"components\":[...]} (or a bare component " ++            "array) using the RICH UI types; " +             "data_json is an optional JSON object string with initial data values.",         listOf(             p("components_json", description = "A2UI components as a JSON string"),@@ -320,6 +327,11 @@ val ASSISTANT_TOOL_SPECS: List<ToolSpec> = listOf(     ),     ToolSpec("get_shop_orders", "Get the user's Shop order summaries"),     ToolSpec("get_memories", "Get a list of all memories"),-    ToolSpec("remove_memory", "Remove a memory by its id (requires confirmation)", listOf(p("id", NUMBER)), risk = WRITE_CONFIRM),+    ToolSpec(+        "remove_memory",+        "Remove a memory by its id (requires confirmation)",+        listOf(p("id", NUMBER)),+        risk = WRITE_CONFIRM,+    ),     ToolSpec("add_to_memory", "Add a new memory to the list of memories", listOf(p("content"))), )
openassistant/src/main/java/com/vayunmathur/openassistant/network/AssistantWebTools.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/network/AssistantWebTools.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/network/AssistantWebTools.ktindex f3c63a8127..7b66f18bda 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/network/AssistantWebTools.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/network/AssistantWebTools.kt@@ -165,7 +165,13 @@ class AssistantWebTools(         } catch (expected: Exception) {             return "Error: could not read page: could not parse reader response"         }-        return formatReadResult(parsed.title, parsed.url.ifBlank { url }, parsed.text, parsed.truncated, parsed.nextOffset)+        return formatReadResult(+            parsed.title,+            parsed.url.ifBlank { url },+            parsed.text,+            parsed.truncated,+            parsed.nextOffset,+        )     }      suspend fun webReadResult(index: Int, offset: Int = 0): String {
openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiTemplates.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiTemplates.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiTemplates.ktindex f6d1567465..b31d8066fb 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiTemplates.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/A2uiTemplates.kt@@ -48,11 +48,15 @@ data class CartLineRow(     val lineTotalCents: Int, ) +private const val CENTS_PER_DOLLAR = 100+ /** Formats integer cents as a dollar string ($12.34, -$1.00). */ fun formatCents(cents: Int): String {     val sign = if (cents < 0) "-" else ""     val abs = kotlin.math.abs(cents)-    return "$sign\$${abs / 100}.${(abs % 100).toString().padStart(2, '0')}"+    val dollars = abs / CENTS_PER_DOLLAR+    val centsPart = (abs % CENTS_PER_DOLLAR).toString().padStart(2, '0')+    return "$sign\$$dollars.$centsPart" }  /** One web search result in a [A2uiTemplates.searchResults] card. */@@ -64,6 +68,26 @@ data class SearchResultItem(     val url: String, ) +private fun foodMenuData(merchantId: Int, items: List<MenuItemRow>): JsonObject =+    buildJsonObject {+        put("merchantId", merchantId)+        put(+            "items",+            JsonArray(+                items.map { item ->+                    buildJsonObject {+                        put("id", item.id)+                        put("name", item.name)+                        put("priceCents", item.priceCents)+                        val availability = if (item.available) "" else " · unavailable"+                        put("priceText", formatCents(item.priceCents) + availability)+                        put("qty", item.qty)+                    }+                },+            ),+        )+    }+ /** Host-generated A2UI cards. The model never authors these. */ object A2uiTemplates { @@ -183,7 +207,10 @@ object A2uiTemplates {                     obj(                         "id" to s("btnAction"), "component" to s("Button"), "label" to s(actionLabel),                         "primary" to JsonPrimitive(true),-                        "action" to action(actionName, (actionContext ?: emptyMap()).mapValues { valueToJson(it.value) }),+                        "action" to action(+                            actionName,+                            (actionContext ?: emptyMap()).mapValues { valueToJson(it.value) },+                        ),                     ),                 )             }@@ -310,24 +337,7 @@ object A2uiTemplates {                 ),             )         }-        val data = buildJsonObject {-            put("merchantId", merchantId)-            put(-                "items",-                JsonArray(-                    items.map { item ->-                        buildJsonObject {-                            put("id", item.id)-                            put("name", item.name)-                            put("priceCents", item.priceCents)-                            put("priceText", formatCents(item.priceCents) + if (item.available) "" else " · unavailable")-                            put("qty", item.qty)-                        }-                    },-                ),-            )-        }-        return envelope(components, data)+        return envelope(components, foodMenuData(merchantId, items))     }      /** Cart card: lines, total, and (when non-empty) a checkout handoff button. */@@ -439,27 +449,32 @@ object A2uiTemplates {                 ),             )         }-        val data = buildJsonObject {-            put("shopDomain", shopDomain)-            put(-                "variants",-                JsonArray(-                    variants.map { v ->-                        buildJsonObject {-                            put("id", v.variantId)-                            put("title", v.title)-                            put(-                                "caption",-                                formatMoney(v.price, v.currency) + if (v.available) "" else " · unavailable",-                            )-                        }-                    },-                ),-            )-            put("variant", variants.firstOrNull()?.variantId ?: "")-            put("qty", 1)-        }-        return envelope(components, data)+        return envelope(components, productCardData(shopDomain, variants))+    }++    private fun productCardData(+        shopDomain: String,+        variants: List<ProductVariantRow>,+    ): JsonObject = buildJsonObject {+        put("shopDomain", shopDomain)+        put(+            "variants",+            JsonArray(+                variants.map { v ->+                    buildJsonObject {+                        put("id", v.variantId)+                        put("title", v.title)+                        put(+                            "caption",+                            formatMoney(v.price, v.currency) ++                                if (v.available) "" else " · unavailable",+                        )+                    }+                },+            ),+        )+        put("variant", variants.firstOrNull()?.variantId ?: "")+        put("qty", 1)     }      /** Shop cart card: every store's lines and per-store totals. */@@ -595,25 +610,29 @@ object A2uiTemplates {                 ),             )         }-        val data = buildJsonObject {-            put("query", query)-            put(-                "results",-                JsonArray(-                    results.map { r ->-                        buildJsonObject {-                            put("index", r.index)-                            put("title", r.title)-                            put("displayTitle", "[${r.index}] ${r.title}")-                            put("snippet", r.snippet)-                            put("domain", r.domain)-                            put("url", r.url)-                        }-                    },-                ),-            )-        }-        return envelope(components, data)+        return envelope(components, searchResultsData(query, results))+    }++    private fun searchResultsData(+        query: String,+        results: List<SearchResultItem>,+    ): JsonObject = buildJsonObject {+        put("query", query)+        put(+            "results",+            JsonArray(+                results.map { r ->+                    buildJsonObject {+                        put("index", r.index)+                        put("title", r.title)+                        put("displayTitle", "[${r.index}] ${r.title}")+                        put("snippet", r.snippet)+                        put("domain", r.domain)+                        put("url", r.url)+                    }+                },+            ),+        )     }      private fun envelope(components: JsonArray, data: JsonObject): String =
openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCatalog.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCatalog.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCatalog.ktindex 52c8e48a00..3af3343abb 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCatalog.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCatalog.kt@@ -157,12 +157,18 @@ class AssistantCatalog(urlOpener: A2uiUrlOpener, messageFormatter: A2uiMessageFo             appendLine("""The component with id "root" is shown. Types:""")             COMPONENTS.forEach { appendLine("- ${it.name}: ${it.promptProps}") }             appendLine("""Any text may be {"path":"/field"} to show a data value. "data" sets initial values.""")-            appendLine("""Button/Picker context values may be {"path":"/field"} to send what the user entered or picked.""")+            appendLine(+                """Button/Picker context values may be {"path":"/field"} to send """ ++                    "what the user entered or picked.",+            )             appendLine(                 "Steppers and text fields only edit the card's data; they do not send a turn. " +                     "Buttons and Picker selections do.",             )-            appendLine("""When the user taps a control you receive a turn like [UI action "name": {...}]. Respond to it.""")+            appendLine(+                """When the user taps a control you receive a turn """ ++                    """like [UI action "name": {...}]. Respond to it.""",+            )             appendLine(                 "Action names are namespaced: pick.* (a Picker/list choice, context has \"id\"; " +                     "pick.conversation carries a thread_key), " +
openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.ktnew file mode 100644index 0000000000..88ad568bd1--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt@@ -0,0 +1,275 @@+package com.vayunmathur.openassistant.platform++import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import com.vayunmathur.library.log.Log+import androidx.core.net.toUri+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.email.EmailData+import com.vayunmathur.library.intents.email.EmailSearchQuery+import com.vayunmathur.library.intents.findfamily.FamilyMemberData+import com.vayunmathur.library.intents.music.MusicSearchResult+import com.vayunmathur.library.intents.music.PlayMusicData+import com.vayunmathur.library.intents.notes.NoteData+import com.vayunmathur.library.intents.todo.CompleteTodoData+import com.vayunmathur.library.intents.todo.GetTodosQuery+import com.vayunmathur.library.intents.todo.InsertTodoData+import com.vayunmathur.library.intents.todo.TodoData+import com.vayunmathur.library.intents.communicate.ConversationData+import com.vayunmathur.library.intents.communicate.ConversationMessageData+import com.vayunmathur.library.intents.communicate.FindConversationsQuery+import com.vayunmathur.library.intents.communicate.GetMessagesQuery+import com.vayunmathur.library.intents.communicate.SendMessageRequest+import com.vayunmathur.library.intents.communicate.SendMessageResult+import com.vayunmathur.library.intents.fooddelivery.CartData as FoodCartData+import com.vayunmathur.library.intents.fooddelivery.FindRestaurants+import com.vayunmathur.library.intents.fooddelivery.GetCart as FoodGetCart+import com.vayunmathur.library.intents.fooddelivery.GetMenu+import com.vayunmathur.library.intents.fooddelivery.GetOrders as FoodGetOrders+import com.vayunmathur.library.intents.fooddelivery.MenuData+import com.vayunmathur.library.intents.fooddelivery.OrderData as FoodOrderData+import com.vayunmathur.library.intents.fooddelivery.OrderLookupRequest+import com.vayunmathur.library.intents.fooddelivery.OrderLookupResult+import com.vayunmathur.library.intents.fooddelivery.OrderSummaryData+import com.vayunmathur.library.intents.fooddelivery.PrepareOrder+import com.vayunmathur.library.intents.fooddelivery.RestaurantData+import com.vayunmathur.library.intents.fooddelivery.SetCart+import com.vayunmathur.library.intents.fooddelivery.SetCartItem+import com.vayunmathur.library.intents.maps.DirectionsRequest+import com.vayunmathur.library.intents.shop.AddToCartRequest+import com.vayunmathur.library.intents.shop.CartData as ShopCartData+import com.vayunmathur.library.intents.shop.GetProductQuery+import com.vayunmathur.library.intents.shop.OrderData as ShopOrderData+import com.vayunmathur.library.intents.shop.ProductData+import com.vayunmathur.library.intents.shop.ProductDetailData+import com.vayunmathur.library.intents.shop.RemoveFromCartRequest+import com.vayunmathur.library.intents.shop.SearchProductsQuery+import com.vayunmathur.library.intents.maps.DirectionsResult+import com.vayunmathur.library.intents.taxi.RideEstimateRequest+import com.vayunmathur.library.intents.taxi.RideEstimateResult+import com.vayunmathur.library.intents.weather.WeatherData+import com.vayunmathur.openassistant.data.Memory+import com.vayunmathur.openassistant.data.MemoryDao+import kotlinx.datetime.TimeZone+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.json.JsonPrimitive+import kotlinx.serialization.serializer+++/**+ * Core cross-app intents (notes, todos, contacts, calendar, family, music,+ * email, clock, weather, maps, taxi) backing [AssistantToolIntents]; the+ * commerce/communicate intents live in the subclass so neither class+ * exceeds the TooManyFunctions limit.+ */+internal abstract class AssistantCoreToolIntents(+    protected val context: Context,+) {+    fun handleMissingApp(packageName: String): String {+        Log.dev("AssistantToolSet", "Handling missing app: $packageName")+        return AssistantToolIntents.getMissingAppMessage(packageName) ++            " Try to help the user with your own knowledge instead."+    }++    fun runTool(block: suspend () -> String): String = runBlocking {+        try {+            block()+        } catch (e: CancellationException) {+            throw e+        } catch (e: MissingAppException) {+            handleMissingApp(e.packageName)+        } catch (expected: Exception) {+            "Error: ${expected.message}"+        }+    }++    suspend fun getNotes(): String = launchIntent<Unit, List<NoteData>>(+        context,+        "com.vayunmathur.notes",+        "com.vayunmathur.notes.intents.GetIntent",+        Unit,+    ).toString()++    suspend fun insertNote(data: NoteData) = launchIntentU(+        context,+        "com.vayunmathur.notes",+        "com.vayunmathur.notes.intents.InsertIntent",+        data,+    )++    suspend fun getTodos(query: GetTodosQuery): String = launchIntent<GetTodosQuery, List<TodoData>>(+        context,+        "com.vayunmathur.todo",+        "com.vayunmathur.todo.intents.GetTodosIntent",+        query,+    ).toString()++    suspend fun insertTodo(data: InsertTodoData): String = launchIntent<InsertTodoData, String>(+        context,+        "com.vayunmathur.todo",+        "com.vayunmathur.todo.intents.InsertTodoIntent",+        data,+    )++    suspend fun completeTodo(data: CompleteTodoData): Boolean = launchIntent<CompleteTodoData, Boolean>(+        context,+        "com.vayunmathur.todo",+        "com.vayunmathur.todo.intents.CompleteTodoIntent",+        data,+    )++    suspend fun getContacts(): String = launchIntent<Unit, List<ContactData>>(+        context,+        "com.vayunmathur.contacts",+        "com.vayunmathur.contacts.intents.GetIntent",+        Unit,+    ).toString()++    suspend fun insertContact(data: ContactData) = launchIntentU(+        context,+        "com.vayunmathur.contacts",+        "com.vayunmathur.contacts.intents.InsertIntent",+        data,+    )++    suspend fun getCalendarEvents(): String = launchIntent<Unit, List<EventData>>(+        context,+        "com.vayunmathur.calendar",+        "com.vayunmathur.calendar.intents.GetIntent",+        Unit,+    ).toString()++    suspend fun insertCalendarEvent(data: EventData) = launchIntentU(+        context,+        "com.vayunmathur.calendar",+        "com.vayunmathur.calendar.intents.InsertIntent",+        data,+    )++    suspend fun getFamilyLocations(): String = launchIntent<Unit, List<FamilyMemberData>>(+        context,+        "com.vayunmathur.findfamily",+        "com.vayunmathur.findfamily.intents.GetIntent",+        Unit,+    ).toString()++    suspend fun createLocationShareLink(name: String, durationMillis: Double): String =+        launchIntent<CreateLinkRequest, String>(+            context,+            "com.vayunmathur.findfamily",+            "com.vayunmathur.findfamily.intents.CreateLinkIntent",+            CreateLinkRequest(name, durationMillis.toLong()),+        )++    suspend fun searchMusic(query: String): String =+        launchIntent<String, List<MusicSearchResult>>(+            context,+            "com.vayunmathur.music",+            "com.vayunmathur.music.intents.SearchIntent",+            query,+        ).toString()++    suspend fun playMusic(data: PlayMusicData) = launchIntentU(+        context,+        "com.vayunmathur.music",+        "com.vayunmathur.music.intents.PlayIntent",+        data,+    )++    suspend fun searchEmails(query: String): String =+        launchIntent<EmailSearchQuery, List<EmailData>>(+            context,+            "com.vayunmathur.email",+            "com.vayunmathur.email.intents.SearchIntent",+            EmailSearchQuery(query),+        ).toString()++    suspend fun getRecentEmails(): String = launchIntent<Unit, List<EmailData>>(+        context,+        "com.vayunmathur.email",+        "com.vayunmathur.email.intents.GetRecentIntent",+        Unit,+    ).toString()++    suspend fun setAlarm(data: SetAlarmData) = launchIntentU(+        context,+        "com.vayunmathur.clock",+        "com.vayunmathur.clock.intents.SetAlarmIntent",+        data,+    )++    suspend fun setTimer(data: SetTimerData) = launchIntentU(+        context,+        "com.vayunmathur.clock",+        "com.vayunmathur.clock.intents.SetTimerIntent",+        data,+    )++    suspend fun getWeather(latitude: Double, longitude: Double): String {+        val result: WeatherData = launchIntent(+            context,+            "com.vayunmathur.weather",+            "com.vayunmathur.weather.intents.GetWeatherIntent",+            WeatherLatLonRequest(latitude, longitude),+        )+        return result.error ?: result.toString()+    }++    suspend fun getWeatherByName(location: String): String {+        val result: WeatherData = launchIntent(+            context,+            "com.vayunmathur.weather",+            "com.vayunmathur.weather.intents.GetWeatherByNameIntent",+            WeatherNameRequest(location),+        )+        return result.error ?: result.toString()+    }++    suspend fun getDirections(+        fromLat: Double,+        fromLng: Double,+        toLat: Double,+        toLng: Double,+        mode: String,+    ): String {+        val result: DirectionsResult = launchIntent(+            context,+            "com.vayunmathur.maps",+            "com.vayunmathur.maps.intents.DirectionsIntent",+            DirectionsRequest(fromLat, fromLng, toLat, toLng, mode.ifBlank { "drive" }),+        )+        return summarizeDirections(result)+    }++    suspend fun getRideEstimate(+        pickupLat: Double,+        pickupLng: Double,+        destLat: Double,+        destLng: Double,+        pickupLabel: String,+        destLabel: String,+    ): String {+        val result: RideEstimateResult = launchIntent(+            context,+            "com.vayunmathur.taxi",+            "com.vayunmathur.taxi.intents.RideEstimateIntent",+            RideEstimateRequest(+                pickupLat, pickupLng, destLat, destLng,+                pickupLabel.takeIf { it.isNotBlank() },+                destLabel.takeIf { it.isNotBlank() },+            ),+        )+        return summarizeRideEstimate(result)+    }++}
openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.ktindex 63b794da44..df52989ea1 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt@@ -65,12 +65,16 @@ import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.serializer +private const val CONVERSATION_SNIPPET_CHARS = 80+private const val MESSAGE_BODY_CHARS = 200+private const val RESTAURANT_ADDRESS_CHARS = 60+ /**  * 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) {+internal class AssistantToolIntents(context: Context) : AssistantCoreToolIntents(context) {      companion object {         private val APP_NAMES = mapOf(@@ -97,203 +101,6 @@ internal class AssistantToolIntents(private val context: Context) {         }     } -    fun handleMissingApp(packageName: String): String {-        Log.dev("AssistantToolSet", "Handling missing app: $packageName")-        return getMissingAppMessage(packageName) +-            " Try to help the user with your own knowledge instead."-    }--    fun runTool(block: suspend () -> String): String = runBlocking {-        try {-            block()-        } catch (e: CancellationException) {-            throw e-        } catch (e: MissingAppException) {-            handleMissingApp(e.packageName)-        } catch (expected: Exception) {-            "Error: ${expected.message}"-        }-    }--    suspend fun getNotes(): String = launchIntent<Unit, List<NoteData>>(-        context,-        "com.vayunmathur.notes",-        "com.vayunmathur.notes.intents.GetIntent",-        Unit,-    ).toString()--    suspend fun insertNote(data: NoteData) = launchIntentU(-        context,-        "com.vayunmathur.notes",-        "com.vayunmathur.notes.intents.InsertIntent",-        data,-    )--    suspend fun getTodos(query: GetTodosQuery): String = launchIntent<GetTodosQuery, List<TodoData>>(-        context,-        "com.vayunmathur.todo",-        "com.vayunmathur.todo.intents.GetTodosIntent",-        query,-    ).toString()--    suspend fun insertTodo(data: InsertTodoData): String = launchIntent<InsertTodoData, String>(-        context,-        "com.vayunmathur.todo",-        "com.vayunmathur.todo.intents.InsertTodoIntent",-        data,-    )--    suspend fun completeTodo(data: CompleteTodoData): Boolean = launchIntent<CompleteTodoData, Boolean>(-        context,-        "com.vayunmathur.todo",-        "com.vayunmathur.todo.intents.CompleteTodoIntent",-        data,-    )--    suspend fun getContacts(): String = launchIntent<Unit, List<ContactData>>(-        context,-        "com.vayunmathur.contacts",-        "com.vayunmathur.contacts.intents.GetIntent",-        Unit,-    ).toString()--    suspend fun insertContact(data: ContactData) = launchIntentU(-        context,-        "com.vayunmathur.contacts",-        "com.vayunmathur.contacts.intents.InsertIntent",-        data,-    )--    suspend fun getCalendarEvents(): String = launchIntent<Unit, List<EventData>>(-        context,-        "com.vayunmathur.calendar",-        "com.vayunmathur.calendar.intents.GetIntent",-        Unit,-    ).toString()--    suspend fun insertCalendarEvent(data: EventData) = launchIntentU(-        context,-        "com.vayunmathur.calendar",-        "com.vayunmathur.calendar.intents.InsertIntent",-        data,-    )--    suspend fun getFamilyLocations(): String = launchIntent<Unit, List<FamilyMemberData>>(-        context,-        "com.vayunmathur.findfamily",-        "com.vayunmathur.findfamily.intents.GetIntent",-        Unit,-    ).toString()--    suspend fun createLocationShareLink(name: String, durationMillis: Double): String =-        launchIntent<CreateLinkRequest, String>(-            context,-            "com.vayunmathur.findfamily",-            "com.vayunmathur.findfamily.intents.CreateLinkIntent",-            CreateLinkRequest(name, durationMillis.toLong()),-        )--    suspend fun searchMusic(query: String): String =-        launchIntent<String, List<MusicSearchResult>>(-            context,-            "com.vayunmathur.music",-            "com.vayunmathur.music.intents.SearchIntent",-            query,-        ).toString()--    suspend fun playMusic(data: PlayMusicData) = launchIntentU(-        context,-        "com.vayunmathur.music",-        "com.vayunmathur.music.intents.PlayIntent",-        data,-    )--    suspend fun searchEmails(query: String): String =-        launchIntent<EmailSearchQuery, List<EmailData>>(-            context,-            "com.vayunmathur.email",-            "com.vayunmathur.email.intents.SearchIntent",-            EmailSearchQuery(query),-        ).toString()--    suspend fun getRecentEmails(): String = launchIntent<Unit, List<EmailData>>(-        context,-        "com.vayunmathur.email",-        "com.vayunmathur.email.intents.GetRecentIntent",-        Unit,-    ).toString()--    suspend fun setAlarm(data: SetAlarmData) = launchIntentU(-        context,-        "com.vayunmathur.clock",-        "com.vayunmathur.clock.intents.SetAlarmIntent",-        data,-    )--    suspend fun setTimer(data: SetTimerData) = launchIntentU(-        context,-        "com.vayunmathur.clock",-        "com.vayunmathur.clock.intents.SetTimerIntent",-        data,-    )--    suspend fun getWeather(latitude: Double, longitude: Double): String {-        val result: WeatherData = launchIntent(-            context,-            "com.vayunmathur.weather",-            "com.vayunmathur.weather.intents.GetWeatherIntent",-            WeatherLatLonRequest(latitude, longitude),-        )-        return result.error ?: result.toString()-    }--    suspend fun getWeatherByName(location: String): String {-        val result: WeatherData = launchIntent(-            context,-            "com.vayunmathur.weather",-            "com.vayunmathur.weather.intents.GetWeatherByNameIntent",-            WeatherNameRequest(location),-        )-        return result.error ?: result.toString()-    }--    suspend fun getDirections(-        fromLat: Double,-        fromLng: Double,-        toLat: Double,-        toLng: Double,-        mode: String,-    ): String {-        val result: DirectionsResult = launchIntent(-            context,-            "com.vayunmathur.maps",-            "com.vayunmathur.maps.intents.DirectionsIntent",-            DirectionsRequest(fromLat, fromLng, toLat, toLng, mode.ifBlank { "drive" }),-        )-        return summarizeDirections(result)-    }--    suspend fun getRideEstimate(-        pickupLat: Double,-        pickupLng: Double,-        destLat: Double,-        destLng: Double,-        pickupLabel: String,-        destLabel: String,-    ): String {-        val result: RideEstimateResult = launchIntent(-            context,-            "com.vayunmathur.taxi",-            "com.vayunmathur.taxi.intents.RideEstimateIntent",-            RideEstimateRequest(-                pickupLat, pickupLng, destLat, destLng,-                pickupLabel.takeIf { it.isNotBlank() },-                destLabel.takeIf { it.isNotBlank() },-            ),-        )-        return summarizeRideEstimate(result)-    }-     suspend fun foodOrderLookup(name: String, lat: Double, lng: Double, address: String): String {         val result: OrderLookupResult = launchIntent(             context,@@ -325,7 +132,12 @@ internal class AssistantToolIntents(private val context: Context) {         request,     ) -    suspend fun findRestaurants(query: String, lat: Double, lng: Double, limit: Int): List<RestaurantData> = launchIntent(+    suspend fun findRestaurants(+        query: String,+        lat: Double,+        lng: Double,+        limit: Int,+    ): List<RestaurantData> = launchIntent(         context,         "com.vayunmathur.fooddelivery",         "com.vayunmathur.fooddelivery.intents.FindRestaurantsIntent",@@ -374,7 +186,11 @@ internal class AssistantToolIntents(private val context: Context) {         SearchProductsQuery(query, limit),     ) -    suspend fun getProductDetail(shopDomain: String, productId: String, variantId: String?): ProductDetailData = launchIntent(+    suspend fun getProductDetail(+        shopDomain: String,+        productId: String,+        variantId: String?,+    ): ProductDetailData = launchIntent(         context,         "com.vayunmathur.shop",         "com.vayunmathur.shop.intents.GetProductIntent",@@ -518,7 +334,8 @@ fun summarizeConversations(list: List<ConversationData>): String =     } else {         list.joinToString("\n") { c ->             val who = c.displayName?.takeIf { it.isNotBlank() } ?: c.address-            "thread_key=${c.threadKey} $who [${c.line}] ${c.snippet.take(80)}"+            "thread_key=${c.threadKey} $who [${c.line}] " ++                c.snippet.take(CONVERSATION_SNIPPET_CHARS)         }     } @@ -529,7 +346,7 @@ fun summarizeConversationMessages(list: List<ConversationMessageData>): String =     } else {         list.joinToString("\n") { m ->             val dir = if (m.outgoing) "me" else m.address-            "[$dir ${m.line}] ${m.body.take(200)}"+            "[$dir ${m.line}] " + m.body.take(MESSAGE_BODY_CHARS)         }     } @@ -540,7 +357,9 @@ fun summarizeRestaurants(list: List<RestaurantData>): String =     } else {         list.joinToString("\n") { r ->             val rating = r.rating?.let { " ★$it" } ?: ""-            "merchant_id=${r.id} ${r.name}$rating ${if (r.isOpen) "open" else "closed"} ${r.address.take(60)}"+            "merchant_id=${r.id} ${r.name}$rating " ++                "${if (r.isOpen) "open" else "closed"} " ++                r.address.take(RESTAURANT_ADDRESS_CHARS)         }     } @@ -551,9 +370,12 @@ fun summarizeMenu(menu: MenuData, cap: Int = 24): String {     val shown = menu.items.take(cap)     val lines = shown.joinToString("\n") { item ->         val mods = item.modifierGroups.joinToString(";") { g ->-            "${g.name}[${g.modifiers.joinToString(",") { "${it.id}:${it.name}" }}] req=${g.required} min=${g.minSelections} max=${g.maxSelections}"+            "${g.name}[${g.modifiers.joinToString(",") { "${it.id}:${it.name}" }}] " ++                "req=${g.required} min=${g.minSelections} max=${g.maxSelections}"         }-        "item_id=${item.id} ${item.name} ${item.priceCents}c ${if (item.available) "available" else "unavailable"} ${item.category}${if (mods.isBlank()) "" else " $mods"}"+        "item_id=${item.id} ${item.name} ${item.priceCents}c " ++            "${if (item.available) "available" else "unavailable"} " ++            "${item.category}${if (mods.isBlank()) "" else " $mods"}"     }     val more = if (menu.items.size > cap) "\n(${menu.items.size - cap} more items not shown)" else ""     return "Menu ${menu.merchantName} (merchant_id=${menu.merchantId}):\n$lines$more"@@ -588,15 +410,28 @@ fun summarizeFoodOrders(list: List<FoodOrderData>, cap: Int = 10): String =  /** Parses the food_set_cart items_json arg ([{itemId, qty, modifierIds}]). */ fun parseSetCartItems(itemsJson: String): List<SetCartItem>? {-    val root = runCatching { Json.parseToJsonElement(itemsJson) }.getOrNull() ?: return null+    val root = runCatching { Json.parseToJsonElement(itemsJson) }.getOrNull()     val array = root as? kotlinx.serialization.json.JsonArray ?: return null-    return array.map { element ->-        val obj = element as? kotlinx.serialization.json.JsonObject ?: return null-        val itemId = (obj["itemId"] as? JsonPrimitive)?.content?.toIntOrNull() ?: return null-        val qty = (obj["qty"] as? JsonPrimitive)?.content?.toIntOrNull() ?: return null-        val mods = (obj["modifierIds"] as? kotlinx.serialization.json.JsonArray)-            ?.map { (it as? JsonPrimitive)?.content?.toIntOrNull() ?: return null } ?: emptyList()-        SetCartItem(itemId, qty, mods)+    val parsed = array.map { element -> parseSetCartItem(element) }+    return if (parsed.any { it == null }) null else parsed.filterNotNull()+}++/** Parses one cart item object, or null when it does not match the documented shape. */+private fun parseSetCartItem(+    element: kotlinx.serialization.json.JsonElement,+): SetCartItem? {+    val obj = element as? kotlinx.serialization.json.JsonObject ?: return null+    val itemId = (obj["itemId"] as? JsonPrimitive)?.content?.toIntOrNull()+    val qty = (obj["qty"] as? JsonPrimitive)?.content?.toIntOrNull()+    if (itemId == null || qty == null) return null+    val modElements = obj["modifierIds"] as? kotlinx.serialization.json.JsonArray+    val mods = modElements?.map { element ->+        (element as? JsonPrimitive)?.content?.toIntOrNull()+    }+    return if (mods != null && mods.any { it == null }) {+        null+    } else {+        SetCartItem(itemId, qty, mods?.filterNotNull() ?: emptyList())     } } @@ -606,7 +441,9 @@ fun summarizeProducts(list: List<ProductData>): String =         "No products found"     } else {         list.joinToString("\n") { p ->-            "variant_id=${p.variantId} product_id=${p.productId} ${p.title} ${p.price} ${p.currency} @ ${p.storeName} (${p.shopDomain}) checkout=${p.checkoutEligible}"+            "variant_id=${p.variantId} product_id=${p.productId} ${p.title} " ++                "${p.price} ${p.currency} @ ${p.storeName} (${p.shopDomain}) " ++                "checkout=${p.checkoutEligible}"         }     } @@ -614,9 +451,11 @@ fun summarizeProducts(list: List<ProductData>): String = fun summarizeProductDetail(detail: ProductDetailData): String {     if (detail.error != null) return "Error: product unavailable (${detail.error})"     val variants = detail.variants.joinToString("\n") { v ->-        "variant_id=${v.variantId} ${v.title} ${v.price} ${v.currency} ${if (v.available) "available" else "unavailable"}"+        "variant_id=${v.variantId} ${v.title} ${v.price} ${v.currency} " ++            if (v.available) "available" else "unavailable"     }-    return "Product ${detail.title} @ ${detail.storeName} (${detail.shopDomain}) from ${detail.price} ${detail.currency}:\n$variants"+    return "Product ${detail.title} @ ${detail.storeName} (${detail.shopDomain}) " ++        "from ${detail.price} ${detail.currency}:\n$variants" }  /** Shop cart for the model, grouped per store; a refused write leaves it unchanged. */
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.ktindex 08d0fe59db..670ed24822 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt@@ -27,6 +27,7 @@ import com.vayunmathur.openassistant.domain.pendingToolSummary import com.vayunmathur.openassistant.platform.AssistantDeviceTools import com.vayunmathur.openassistant.platform.AssistantToolIntents import com.vayunmathur.openassistant.network.AssistantWebTools+import com.vayunmathur.library.intents.shop.CartData as ShopCartData import kotlinx.coroutines.CancellationException import kotlinx.coroutines.runBlocking import kotlinx.serialization.json.Json@@ -383,14 +384,7 @@ class AssistantTools(             intents.runTool {                 val cart = intents.getShopCart()                 if (cart.error == null && cart.totalItems > 0) {-                    pendingRenderUi = A2uiTemplates.shopCart(-                        cart.stores.map { store ->-                            store.storeName to store.lines.map {-                                "${it.title} ${it.variantTitle} × ${it.quantity} — ${formatMoney(it.price * it.quantity, it.currency)}"-                            }-                        },-                        cart.totalItems,-                    )+                    renderShopCart(cart)                 }                 com.vayunmathur.openassistant.platform.summarizeShopCart(cart)             }@@ -405,14 +399,7 @@ class AssistantTools(                 )                 // Light write: executed once, cart rendered back, never auto-retried.                 if (cart.error == null) {-                    pendingRenderUi = A2uiTemplates.shopCart(-                        cart.stores.map { store ->-                            store.storeName to store.lines.map {-                                "${it.title} ${it.variantTitle} × ${it.quantity} — ${formatMoney(it.price * it.quantity, it.currency)}"-                            }-                        },-                        cart.totalItems,-                    )+                    renderShopCart(cart)                 }                 com.vayunmathur.openassistant.platform.summarizeShopCart(cart)             }@@ -421,14 +408,7 @@ class AssistantTools(             intents.runTool {                 val cart = intents.removeFromShopCart(a.string("variant_id"))                 if (cart.error == null) {-                    pendingRenderUi = A2uiTemplates.shopCart(-                        cart.stores.map { store ->-                            store.storeName to store.lines.map {-                                "${it.title} ${it.variantTitle} × ${it.quantity} — ${formatMoney(it.price * it.quantity, it.currency)}"-                            }-                        },-                        cart.totalItems,-                    )+                    renderShopCart(cart)                 }                 com.vayunmathur.openassistant.platform.summarizeShopCart(cart)             }@@ -440,8 +420,14 @@ class AssistantTools(                 if (cart.error == null && store != null && store.lines.isNotEmpty()) {                     pendingRenderUi = A2uiTemplates.shopCheckoutSummary(                         store.storeName, store.shopDomain,-                        store.lines.map {-                            "${it.title} ${it.variantTitle} × ${it.quantity} — ${formatMoney(it.price * it.quantity, it.currency)}"+                        store.lines.map { line ->+                            shopCartLineText(+                                line.title,+                                line.variantTitle,+                                line.quantity,+                                line.price,+                                line.currency,+                            )                         },                     )                 }@@ -520,17 +506,17 @@ class AssistantTools(     fun invokeConfirmed(pendingId: String): String {         val pending = pendingStore.get(pendingId)             ?: return "Error: pending tool call not found"-        if (pending.consumed) return "Error: pending tool call already consumed"-        if (pending.isExpired(nowMillis())) return "Error: pending tool call expired"-        val spec = specs[pending.name] ?: return "Error: unknown tool '${pending.name}'"-        val coerced = when (val result = coerceToolArgs(spec, pending.args)) {-            is ToolArgsResult.Invalid -> return result.message-            is ToolArgsResult.Ok -> result.args+        val spec = specs[pending.name]+        val coerced = spec?.let { coerceToolArgs(it, pending.args) }+        return when {+            pending.consumed -> "Error: pending tool call already consumed"+            pending.isExpired(nowMillis()) -> "Error: pending tool call expired"+            spec == null -> "Error: unknown tool '${pending.name}'"+            coerced is ToolArgsResult.Invalid -> coerced.message+            !pendingStore.markConsumed(pendingId) ->+                "Error: pending tool call already consumed"+            else -> execute(spec.name, (coerced as ToolArgsResult.Ok).args)         }-        if (!pendingStore.markConsumed(pendingId)) {-            return "Error: pending tool call already consumed"-        }-        return execute(spec.name, coerced)     }      /** Takes and clears the stashed [pendingRenderUi] envelope, if any. */@@ -584,6 +570,33 @@ class AssistantTools(         }     } +    private fun renderShopCart(cart: ShopCartData) {+        pendingRenderUi = A2uiTemplates.shopCart(+            cart.stores.map { store ->+                store.storeName to store.lines.map { line ->+                    shopCartLineText(+                        line.title,+                        line.variantTitle,+                        line.quantity,+                        line.price,+                        line.currency,+                    )+                }+            },+            cart.totalItems,+        )+    }++    private fun shopCartLineText(+        title: String,+        variantTitle: String,+        quantity: Int,+        price: Long,+        currency: String,+    ): String =+        "$title $variantTitle × $quantity — " ++            formatMoney(price * quantity, currency)+     private fun execute(name: String, args: ToolArgs): String = try {         handlers.getValue(name)(args)     } catch (e: CancellationException) {
openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantViewModel.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantViewModel.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantViewModel.ktindex af173355d8..3ce0c36279 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantViewModel.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantViewModel.kt@@ -129,70 +129,76 @@ class AssistantViewModel(         conversationId: Long,         eventName: String,         context: Map<String, Any?>,+    ): Boolean = when (eventName) {+        "msg.send" -> handleHostSendMessage(conversationId, context)+        "handoff.shop_checkout", "handoff.food_checkout" -> openUrlFromContext(context, "deepLink")+        "open.conversation" -> openConversationFromContext(context)+        "web.open" -> openUrlFromContext(context, "url")+        "web.read" -> handleHostWebRead(conversationId, context)+        "confirm.tool", "cancel.tool" -> handleHostToolGate(conversationId, eventName, context)+        else -> false+    }++    private fun handleHostSendMessage(+        conversationId: Long,+        context: Map<String, Any?>,     ): Boolean {-        when (eventName) {-            "msg.send" -> {-                val address = context["address"]?.toString().orEmpty()-                val body = context["body"]?.toString().orEmpty()-                if (address.isBlank() || body.isBlank()) return false-                val line = context["line"]?.toString().orEmpty()-                val threadRemoteId = context["thread_remote_id"]?.toString().orEmpty()-                val payload = buildJsonObject {-                    put("address", address)-                    put("line", line)-                    put("body", body)-                    if (threadRemoteId.isNotBlank()) put("thread_remote_id", threadRemoteId)-                }.toString()-                val text = "[HostSendMsg $payload]"-                viewModelScope.launch {-                    upsertMessage(Message(conversationId, text, "user"))-                    requestInference(conversationId, text, emptyList(), null)-                }-                return true-            }-            "handoff.shop_checkout" -> {-                val link = context["deepLink"]?.toString().orEmpty()-                if (link.isBlank()) return false-                openUrl(link)-                return true-            }-            "handoff.food_checkout" -> {-                val link = context["deepLink"]?.toString().orEmpty()-                if (link.isBlank()) return false-                openUrl(link)-                return true-            }-            "open.conversation" -> {-                val address = context["address"]?.toString().orEmpty()-                if (address.isBlank()) return false-                openConversation(address)-                return true-            }-            "web.open" -> {-                val url = context["url"]?.toString().orEmpty()-                if (url.isBlank()) return false-                openUrl(url)-                return true-            }-            "web.read" -> {-                val index = contextIndex(context) ?: return false-                viewModelScope.launch {-                    // Fresh instance: NetworkClient is already inited in-                    // MainActivity, and the last-search slot is process-wide-                    // (see AssistantWebTools), so index resolution works here.-                    val fetched = AssistantWebTools().webReadResultText(index)-                    val text = "[Web read $index: $fetched]"-                    upsertMessage(Message(conversationId, text, "user"))-                    requestInference(conversationId, text, emptyList(), null)-                }-                return true-            }+        val address = context["address"]?.toString().orEmpty()+        val body = context["body"]?.toString().orEmpty()+        if (address.isBlank() || body.isBlank()) return false+        val line = context["line"]?.toString().orEmpty()+        val threadRemoteId = context["thread_remote_id"]?.toString().orEmpty()+        val payload = buildJsonObject {+            put("address", address)+            put("line", line)+            put("body", body)+            if (threadRemoteId.isNotBlank()) put("thread_remote_id", threadRemoteId)+        }.toString()+        val text = "[HostSendMsg $payload]"+        viewModelScope.launch {+            upsertMessage(Message(conversationId, text, "user"))+            requestInference(conversationId, text, emptyList(), null)         }-        val marker = when (eventName) {-            "confirm.tool" -> "HostConfirm"-            "cancel.tool" -> "HostCancel"-            else -> return false+        return true+    }++    private fun openUrlFromContext(context: Map<String, Any?>, key: String): Boolean {+        val url = context[key]?.toString().orEmpty()+        if (url.isBlank()) return false+        openUrl(url)+        return true+    }++    private fun openConversationFromContext(context: Map<String, Any?>): Boolean {+        val address = context["address"]?.toString().orEmpty()+        if (address.isBlank()) return false+        openConversation(address)+        return true+    }++    private fun handleHostWebRead(+        conversationId: Long,+        context: Map<String, Any?>,+    ): Boolean {+        val index = contextIndex(context) ?: return false+        viewModelScope.launch {+            // Fresh instance: NetworkClient is already inited in+            // MainActivity, and the last-search slot is process-wide+            // (see AssistantWebTools), so index resolution works here.+            val fetched = AssistantWebTools().webReadResultText(index)+            val text = "[Web read $index: $fetched]"+            upsertMessage(Message(conversationId, text, "user"))+            requestInference(conversationId, text, emptyList(), null)         }+        return true+    }++    private fun handleHostToolGate(+        conversationId: Long,+        eventName: String,+        context: Map<String, Any?>,+    ): Boolean {+        val marker = if (eventName == "confirm.tool") "HostConfirm" else "HostCancel"         val id = context["id"]?.toString().orEmpty()         if (id.isBlank()) return false         val text = "[$marker $id]"
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 7501092f38..f1b7a7372b 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt@@ -191,11 +191,6 @@ class InferenceService : Service() {     override fun onCreate() {         super.onCreate()         startForegroundTask()-        launchPrewarm()-        launchJobLoop()-    }--    private fun launchPrewarm() {         serviceScope.launch {             try {                 ensureEngineInitialized()@@ -203,6 +198,7 @@ class InferenceService : Service() {                 Log.error("InferenceService", "Error pre-warming engine", expected)             }         }+        launchJobLoop()     }      private fun launchJobLoop() {@@ -345,7 +341,7 @@ class InferenceService : Service() {      private suspend fun loadHistory(conversationId: Long, userText: String): List<HistoryTurn> {         val cutoff = Clock.System.now().toEpochMilliseconds() - HISTORY_RECENCY_MILLIS-        return fetchHistoryFromDb(conversationId)+        return store.history(conversationId)             .filter { it.text != userText || it.timestamp < cutoff }             .map { HistoryTurn(fromUser = it.role != "assistant", text = withA2uiBlock(it.text, it.a2ui)) }     }@@ -416,7 +412,7 @@ class InferenceService : Service() {         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)+            val candidate = JsonExtractor.largestObject(text)             if (candidate != null && JsonSchemaValidator.validateJsonAgainstSchema(candidate, schema) == null) {                 Log.status("InferenceService", "Valid JSON extracted and verified against schema. Halting.")                 receiver.send(RESULT_OK_CODE, Bundle().apply { putString("json_result", candidate) })@@ -427,10 +423,12 @@ class InferenceService : Service() {             }         }         if (sent) return-        currentCoroutineContext()[Job]?.let { if (!it.isActive) failCancelled() }+        currentCoroutineContext()[Job]?.let {+            if (!it.isActive) throw CancellationException("intent cancelled")+        }         if (reply == null) failEngine() -        val finalJson = tryExtractLargestJson(reply)+        val finalJson = JsonExtractor.largestObject(reply)         if (finalJson != null && JsonSchemaValidator.validateJsonAgainstSchema(finalJson, schema) == null) {             receiver.send(RESULT_OK_CODE, Bundle().apply { putString("json_result", finalJson) })             Log.dev("InferenceService", "AI produced output: $finalJson")@@ -448,12 +446,6 @@ class InferenceService : Service() {     private fun failEngine(): Nothing =         throw IllegalStateException(getString(R.string.error_ai_engine_failed)) -    /** Fails with a cancellation; keeps throw sites out of the inference paths. */-    private fun failCancelled(): Nothing = throw CancellationException("intent cancelled")--    private fun tryExtractLargestJson(text: String): String? =-        JsonExtractor.largestObject(text)-     private suspend fun ensureEngineInitialized() = engineLock.withLock {         if (engine != null) return@withLock         val dir = ModelUrls.GemmaMaml.modelDir(applicationContext)@@ -463,18 +455,21 @@ class InferenceService : Service() {             created.close()             // Say which it was (#917): "missing or failed to load" read as "missing" to a             // user whose verified files were all there and whose GPU had refused them.-            throw IllegalStateException(modelLoadFailure(dir, detail).describe(dir.absolutePath))+            val names = (Gemma4Handle.FILES + GEMMA4_EXPECTED_BYTES.keys).distinct()+            val sizes = names.associateWith { name ->+                File(dir, name).takeIf { it.isFile }?.length()+            }+            val failure = classifyModelLoadFailure(+                sizes,+                Gemma4Handle.FILES,+                GEMMA4_EXPECTED_BYTES,+                detail,+            )+            throw IllegalStateException(failure.describe(dir.absolutePath))         }         engine = created     } -    /** What is on disk in [dir], classified against the engine's own [engineError]. */-    private fun modelLoadFailure(dir: File, engineError: String?): ModelLoadFailure {-        val names = (Gemma4Handle.FILES + GEMMA4_EXPECTED_BYTES.keys).distinct()-        val sizes = names.associateWith { name -> File(dir, name).takeIf { it.isFile }?.length() }-        return classifyModelLoadFailure(sizes, Gemma4Handle.FILES, GEMMA4_EXPECTED_BYTES, engineError)-    }-     /** The user's (or default) prompt plus the A2UI section, which custom prompts must not lose. */     private suspend fun systemPrompt(): String {         val stored = DataStoreUtils.getInstance(applicationContext).getStringAwait(KEY_SYSTEM_PROMPT)@@ -482,39 +477,14 @@ class InferenceService : Service() {         return base + "\n\n" + AssistantCatalog.PROMPT_SECTION     } -    private fun PendingToolCallEntity.toDomain(): PendingToolCall = PendingToolCall(-        id = id,-        name = toolName,-        args = runCatching {-            Json.parseToJsonElement(argsJson).jsonObject-                .mapValues { it.value.jsonPrimitive.content }-        }.getOrDefault(emptyMap()),-        summary = summary,-        createdAtMillis = createdAt,-        expiresAtMillis = expiresAt,-        consumed = consumed,-    )--    private fun PendingToolCall.toEntity(conversationId: Long): PendingToolCallEntity =-        PendingToolCallEntity(-            id = id,-            conversationId = conversationId,-            toolName = name,-            argsJson = JsonObject(args.mapValues { JsonPrimitive(it.value) }).toString(),-            summary = summary,-            createdAt = createdAtMillis,-            expiresAt = expiresAtMillis,-            consumed = consumed,-        )-     private suspend fun loadPendingDomain(id: String): PendingToolCall? {         tools.pendingById(id)?.let { return it }         val entity = runCatching { pendingDao?.getById(id) }.getOrNull() ?: return null-        return entity.toDomain().also { tools.restorePending(it) }+        return store.pendingToDomain(entity).also { tools.restorePending(it) }     }      private suspend fun persistPending(conversationId: Long, pending: PendingToolCall) {-        runCatching { pendingDao?.upsert(pending.toEntity(conversationId)) }+        runCatching { pendingDao?.upsert(store.pendingToEntity(pending, conversationId)) }     }      /**@@ -584,7 +554,9 @@ class InferenceService : Service() {                 ),             )         }-        runCatching { pendingDao?.upsert(pending.copy(consumed = true).toEntity(conversationId)) }+        runCatching {+            pendingDao?.upsert(store.pendingToEntity(pending.copy(consumed = true), conversationId))+        }         store.upsert(             DbMessage(                 conversationId = conversationId,@@ -643,7 +615,14 @@ class InferenceService : Service() {             withContext(NonCancellable) { writer.cancelAndJoin() }         }         flushTitle(conversationId)+        handleInferenceResult(conversationId, aiMsgId, result)+    } +    private suspend fun handleInferenceResult(+        conversationId: Long,+        aiMsgId: Long,+        result: ChatResult,+    ) {         when (result) {             is ChatResult.Reply -> if (result.halted || halt) {                 halt = false@@ -666,7 +645,10 @@ class InferenceService : Service() {             }             ChatResult.TooLong -> store.updateMessage(                 aiMsgId,-                getString(R.string.error_prefix, "the message is too long for the model's context"),+                getString(+                    R.string.error_prefix,+                    "the message is too long for the model's context",+                ),             )             ChatResult.Unavailable -> {                 messageDao.deleteById(aiMsgId)@@ -699,8 +681,6 @@ class InferenceService : Service() {         store.updateTitle(conversationId, title)     } -    private suspend fun fetchHistoryFromDb(id: Long): List<DbMessage> = store.history(id)-     /** Stores a finished reply: the prose as its text, any A2UI block beside it. */      override fun onDestroy() {@@ -735,6 +715,35 @@ internal class MessageStore(         upsert(existing.copy(text = text, a2ui = a2ui))     } +    /** Converts a persisted pending tool call back to its domain form. */+    fun pendingToDomain(entity: PendingToolCallEntity): PendingToolCall = PendingToolCall(+        id = entity.id,+        name = entity.toolName,+        args = runCatching {+            Json.parseToJsonElement(entity.argsJson).jsonObject+                .mapValues { it.value.jsonPrimitive.content }+        }.getOrDefault(emptyMap()),+        summary = entity.summary,+        createdAtMillis = entity.createdAt,+        expiresAtMillis = entity.expiresAt,+        consumed = entity.consumed,+    )++    /** Converts a domain pending tool call to its persisted form. */+    fun pendingToEntity(+        pending: PendingToolCall,+        conversationId: Long,+    ): PendingToolCallEntity = PendingToolCallEntity(+        id = pending.id,+        conversationId = conversationId,+        toolName = pending.name,+        argsJson = JsonObject(pending.args.mapValues { JsonPrimitive(it.value) }).toString(),+        summary = pending.summary,+        createdAt = pending.createdAtMillis,+        expiresAt = pending.expiresAtMillis,+        consumed = pending.consumed,+    )+     /** Sets the conversation title. */     suspend fun updateTitle(id: Long, title: String) {         val oldConversation = conversationDao.getById(id)