Modern Apps git

← Modern-Apps.git

openassistant: fit 78 tools inside the header budget

Commit
e128cac56f7c1777effeee3340cf0d88fb74bedb
Author
Vayun Mathur <[email protected]>
When
2026-12-02 06:20 UTC (4 days ago)
Parents
6272601
Merging the ten repaired tool picks onto the capped
catalogue put the system header at 28,967 chars
against the 25,600 pin in PromptBudgetTest.

- AssistantToolSpecs: tool descriptions word-cut to
28 chars and parameter descriptions dropped (names,
types and required flags stay in the declaration;
the confirmation semantics live in the risk field
and the system prompt). photos_search_photos keeps
its full "never image data" wording and its limit
range, as PhotosToolTest pins both. Header now
25,528 chars, still 78 tools.
- AssistantTools: the 580-line handler map moves to
AssistantToolHandlers.kt (assistantToolHandlers),
leaving AssistantTools.kt at 241 lines; the
render_ui stash becomes a PendingRenderUi holder
behind the existing pendingRenderUi property, so
handler entries and tests are unchanged.

Verified: :openassistant:testDevUnitTest full suite
(353 tests; only the known load flake in
InferenceServiceConcurrencyTest, green on rerun),
:openassistant:lintVitalRelease 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 8307adb163..2b611ab347 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt@@ -54,25 +54,25 @@ private fun parseToolRisk(field: String): ToolRisk =  private const val TOOL_DATA = """ get_notes|-|Get notes (max 20, excerpts)|-create_note|C|Create a new note in the notes app (requires confirmation). Should only be used with EXPLICIT request by user|title^S^1^~content^S^1^-get_todos|-|Get open tasks (max 50). Due times are epoch ms; id usable with complete_todo.|scope^S^0^today (default), upcoming, or all-create_todo|C|Create a task in Todo (requires confirmation, EXPLICIT request only). The title may include 'tomorrow 6pm' or '#tag', understood when no due time is given.|title^S^1^~due^N^0^optional due time as epoch milliseconds~notes^S^0^~priority^N^0^optional priority, 1 (highest) to 4-complete_todo|C|Mark a task done (requires confirmation). Should only be used with EXPLICIT request by user.|id^S^0^task id from get_todos~title^S^0^exact task title, used when no id is given-get_contacts|-|Get contacts (max 50; prefer search_contacts)|---create_contact|C|Create a new contact (requires confirmation)|name^S^1^~phone_number^S^1^-get_calendar_events|-|Get calendar events (max 50; times are epoch ms)|-create_calendar_event|C|Create a new calendar event (requires confirmation). Start and end times must be epoch milliseconds.|title^S^1^~start^N^1^start time as epoch milliseconds~end^N^1^end time as epoch milliseconds~location^S^0^-get_family_locations|-|Get family locations (max 50)|-create_location_share_link|C|Create a temporary FindFamily link that shares the user's live location (requires confirmation).|name^S^1^name or label for who the link is for~duration_millis^N^1^how long the link stays active, in milliseconds+create_note|C|Create a new note in the|title^S^1^~content^S^1^+get_todos|-|Get open tasks (max 50). Due|scope^S^0^+create_todo|C|Create a task in Todo|title^S^1^~due^N^0^~notes^S^0^~priority^N^0^+complete_todo|C|Mark a task done (requires|id^S^0^~title^S^0^+get_contacts|-|Get contacts (max 50; prefer|+++create_contact|C|Create a new contact|name^S^1^~phone_number^S^1^+get_calendar_events|-|Get calendar events (max 50|+create_calendar_event|C|Create a new calendar event|title^S^1^~start^N^1^~end^N^1^~location^S^0^+get_family_locations|-|Get family locations (max|+create_location_share_link|C|Create a temporary|name^S^1^~duration_millis^N^1^ search_music|-|Search music (max 20)|query^S^1^-play_music|C|Play music given its id and type (song, album, artist, or playlist) (requires confirmation)|id^N^1^~type^S^1^-search_emails|-|Search emails (max 10, excerpts)|query^S^1^-get_recent_emails|-|Get recent emails (max 10, excerpts)|-get_local_current_date_time|-|Get the current date and time in the local timezone.|+play_music|C|Play music given its id and|id^N^1^~type^S^1^+search_emails|-|Search emails (max 10|query^S^1^+get_recent_emails|-|Get recent emails (max 10|+get_local_current_date_time|-|Get the current date and| get_app_list|-|Get installed apps (max 100)|-open_app|-|Open an app given its package id|package_id^S^1^package id+open_app|-|Open an app given its|package_id^S^1^   @@ -83,72 +83,72 @@ send_message|-|Send a message|recipient^S^1^~message^S^1^ make_phone_call|-|Call a phone number|recipient^S^1^ set_alarm|C|Set Clock alarm at.|hour^N^1^~minute^N^1^~label^S^0^ set_timer|C|Start Clock countdown timer.|seconds^N^1^~label^S^0^-set_conversation_title|-|Set conversation title (first.|new_title^S^1^+set_conversation_title|-|Set conversation title|new_title^S^1^ get_weather|-|Current weather at lat/lng.|latitude^N^1^~longitude^N^1^ get_weather_by_name|-|Current weather for a named.|location^S^1^ screentime_get_usage|-|Screen time: total + top 5.|-render_ui|-|Render UI card (A2UI).|components_json^S^1^components~data_json^S^0^data JSON-get_directions|-|Directions.|from_lat^N^1^origin lat~from_lng^N^1^origin lng~to_lat^N^1^dest lat~to_lng^N^1^dest lng~mode^S^0^drive/transi-maps_search_places|-|Maps places; returns lat/lng.|query^S^1^name/categor~near_lat^N^0^near lat~near_lng^N^0^near lng~category^S^0^e.g. Cafe~limit^N^0^1-10 (def 5)-maps_get_saved_places|-|Saved Maps places (name +.|query^S^0^filter~limit^N^0^max 1-10-get_ride_estimate|-|Taxi fare/ETA.|pickup_lat^N^1^pickup lat~pickup_lng^N^1^pickup lng~dest_lat^N^1^dest lat~dest_lng^N^1^dest lng~pickup_label^S^0^pickup lbl~dest_label^S^0^dest lbl-food_order_lookup|-|Restaurant orderable nearby? (FoodDelivery).|name^S^1^name~lat^N^1^lat~lng^N^1^lng~address^S^0^address-calculator_evaluate|-|Evaluate math via Calculator.|expression^S^1^expression (200-calculator_convert_unit|-|Convert units.|value^N^1^value~from_unit^S^1^from e.g. km/USD~to_unit^S^1^to e.g. mi/EUR-search_contacts|-|Search contacts by name/phone substring (max 10).|query^S^1^name/phone substring-web_search|-|Web search for current facts. Numbered results; web_read_result reads them.|query^S^1^search query~count^N^0^count 1-10 (def 5)~kind^S^0^text (def) or news-web_read|-|Read a web page by URL and return its extracted text.|url^S^1^page URL to read-web_read_result|-|Read a result from the last web_search by its 1-based index.|index^N^1^1-based index into the last web_search results~offset^N^0^optional character offset for long pages-find_conversations|-|Find Communicate conversations by name, number or snippet. Returns thread_key values for get_conversation_messages.|query^S^0^name, number or text to search (blank lists recent)~limit^N^0^optional max conversations 1-50 (default 5)-get_conversation_messages|-|Get recent messages from a messaging conversation by its thread_key from find_conversations.|thread_key^S^1^thread key like Sim:42 or WhatsApp:[email protected]~limit^N^0^optional max messages 1-50 (default 10)-draft_message|-|Show a message composer card (recipient, line, draft body). Sends nothing; the user edits and taps Send, which asks for confirmation first.|recipient_name^S^0^recipient display name~address^S^1^recipient phone number or address~line^S^1^Sim, Rcs, WhatsApp, Signal, or GoogleVoice~body^S^1^draft message text~thread_remote_id^S^0^optional existing thread id to reply into-send_message_v2|C|Send via Communicate (requires confirmation, EXPLICIT request only). GoogleVoice cannot send here; use draft_message instead.|address^S^1^recipient phone number or address~line^S^1^Sim, Rcs, WhatsApp, Signal, or GoogleVoice~body^S^1^message text~thread_remote_id^S^0^optional existing thread id to reply into-find_restaurants|-|Find restaurants near a location via the FoodDelivery app, optionally filtered by name or tag.|query^S^0^optional name or tag filter~lat^N^1^latitude~lng^N^1^longitude~limit^N^0^optional max results (default 5)-get_restaurant_menu|-|Get the menu of a restaurant (merchant_id from find_restaurants). Items carry ids, prices in cents, availability and modifier groups.|merchant_id^N^1^merchant id from find_restaurants---food_get_cart|-|Get the current FoodDelivery cart (items and total)|-food_set_cart|L|Replace cart.|merchant_id^N^1^merchant~items_json^S^1^[{itemId,qty,modifierIds}]--food_prepare_order|-|Price cart.|merchant_id^N^1^merchant~is_pickup^N^0^1=pickup 0=delivery~address_id^S^0^addr id~tip_cents^N^0^tip cents~promo^S^0^promo---place_food_order|H|Order summary; user pays in app.|merchant_id^N^1^merchant-get_food_orders|-|Get the user's past FoodDelivery.|-search_products|-|Search the Shop catalog. Each.|query^S^1^search text~limit^N^0^max (def 5)-get_product_detail|-|Product variants.|shop_domain^S^1^domain~product_id^S^1^product~variant_id^S^0^variant-shop_get_cart|-|Get the current Shop cart, grouped.|-shop_add_to_cart|L|Add exact variant to Shop cart.|shop_domain^S^1^domain~variant_id^S^1^exact~quantity^N^0^qty 1-99-shop_remove_from_cart|L|Remove a variant from the Shop.|variant_id^S^1^variant id-start_shop_checkout|H|Cart summary; user checks out in.|shop_domain^S^1^domain to-get_shop_orders|-|Get the user's Shop order summaries|+render_ui|-|Render UI card (A2UI).|components_json^S^1^~data_json^S^0^+get_directions|-|Directions.|from_lat^N^1^~from_lng^N^1^~to_lat^N^1^~to_lng^N^1^~mode^S^0^+maps_search_places|-|Maps places; returns|query^S^1^~near_lat^N^0^~near_lng^N^0^~category^S^0^~limit^N^0^+maps_get_saved_places|-|Saved Maps places (name +.|query^S^0^~limit^N^0^+get_ride_estimate|-|Taxi fare/ETA.|pickup_lat^N^1^~pickup_lng^N^1^~dest_lat^N^1^~dest_lng^N^1^~pickup_label^S^0^~dest_label^S^0^+food_order_lookup|-|Restaurant orderable nearby?|name^S^1^~lat^N^1^~lng^N^1^~address^S^0^+calculator_evaluate|-|Evaluate math via|expression^S^1^+calculator_convert_unit|-|Convert units.|value^N^1^~from_unit^S^1^~to_unit^S^1^+search_contacts|-|Search contacts by|query^S^1^+web_search|-|Web search for current|query^S^1^~count^N^0^~kind^S^0^+web_read|-|Read a web page by URL and|url^S^1^+web_read_result|-|Read a result from the last|index^N^1^~offset^N^0^+find_conversations|-|Find Communicate|query^S^0^~limit^N^0^+get_conversation_messages|-|Get recent messages from a|thread_key^S^1^~limit^N^0^+draft_message|-|Show a message composer card|recipient_name^S^0^~address^S^1^~line^S^1^~body^S^1^~thread_remote_id^S^0^+send_message_v2|C|Send via Communicate|address^S^1^~line^S^1^~body^S^1^~thread_remote_id^S^0^+find_restaurants|-|Find restaurants near a|query^S^0^~lat^N^1^~lng^N^1^~limit^N^0^+get_restaurant_menu|-|Get the menu of a restaurant|merchant_id^N^1^+++food_get_cart|-|Get the current FoodDelivery|+food_set_cart|L|Replace cart.|merchant_id^N^1^~items_json^S^1^++food_prepare_order|-|Price cart.|merchant_id^N^1^~is_pickup^N^0^~address_id^S^0^~tip_cents^N^0^~promo^S^0^+++place_food_order|H|Order summary; user pays in|merchant_id^N^1^+get_food_orders|-|Get the user's past|+search_products|-|Search the Shop catalog.|query^S^1^~limit^N^0^+get_product_detail|-|Product variants.|shop_domain^S^1^~product_id^S^1^~variant_id^S^0^+shop_get_cart|-|Get the current Shop cart|+shop_add_to_cart|L|Add exact variant to Shop|shop_domain^S^1^~variant_id^S^1^~quantity^N^0^+shop_remove_from_cart|L|Remove a variant from the|variant_id^S^1^+start_shop_checkout|H|Cart summary; user checks|shop_domain^S^1^+get_shop_orders|-|Get the user's Shop order| get_memories|-|Get memories (last 100)|-education_get_progress|-|Education progress by course/subject, streak, deadlines (aggregates).|-news_search_headlines|-|Search News headlines|query^S^1^~category^S^0^WORLD US TECHNOLOGY SCIENCE LOCAL~limit^N^0^1-10, default 5-news_top_stories|-|Top News stories by source count, then newest|category^S^0^WORLD US TECHNOLOGY SCIENCE LOCAL~limit^N^0^1-10, default 5-news_get_story|-|Get a News story by story_id|story_id^S^1^from news search/top-news_read_article|-|Read a News article (3000 chars/page)|url^S^1^from a news result~offset^N^0^char offset-health_get_metric_summary|-|Health summary aggregates only: latest/avg/min/max/totals.|metric^S^1^steps/sleep/weight/heart_rate/hydration~range^S^0^today/7d (default)/30d+education_get_progress|-|Education progress by|+news_search_headlines|-|Search News headlines|query^S^1^~category^S^0^~limit^N^0^+news_top_stories|-|Top News stories by source|category^S^0^~limit^N^0^+news_get_story|-|Get a News story by story_id|story_id^S^1^+news_read_article|-|Read a News article (3000|url^S^1^~offset^N^0^+health_get_metric_summary|-|Health summary aggregates|metric^S^1^~range^S^0^  -remove_memory|C|Remove a memory by its id (requires confirmation)|id^N^1^+remove_memory|C|Remove a memory by its id|id^N^1^  -add_to_memory|-|Add a new memory to the list of memories|content^S^1^+add_to_memory|-|Add a new memory to the list|content^S^1^   -astronomy_get_tonight|-|Tonight: sunset/Moon/planets.|latitude^N^0^~longitude^N^0^+astronomy_get_tonight|-|Tonight:|latitude^N^0^~longitude^N^0^ get_weather_forecast|-|Forecast (5d+hours).|location^S^1^~days^N^0^ appstore_search_apps|-|AppStore app search.|query^S^1^~limit^N^0^ appstore_get_updates|-|AppStore update count/names.|-travel_get_trips|-|Trip summaries (name, dates,.|when^S^0^~limit^N^0^+travel_get_trips|-|Trip summaries (name|when^S^0^~limit^N^0^ translate_text|-|Translate.|text^S^1^~target_lang^S^1^~source_lang^S^0^-photos_search_photos|-|Search photo metadata (name, date, size, folder); count + up to 10 hits; never image data.|query^S^0^~album^S^0^~from_millis^N^0^~to_millis^N^0^~limit^N^0^1-10+photos_search_photos|-|Search photo metadata only, never image data|query^S^0^~album^S^0^~from_millis^N^0^~to_millis^N^0^~limit^N^0^max 1-10 youpipe_get_subscriptions_latest|-|Latest YouPipe subscription.|query^S^0^~category^S^0^~limit^N^0^ files_search_files|-|Search files by filename.|query^S^1^~limit^N^0^ music_get_now_playing|-|What is playing now in Music| music_get_playlists|-|Music playlists with track.|query^S^0^~limit^N^0^ music_get_playlist_tracks|-|Track titles in one Music.|playlist_id^N^1^~query^S^0^~limit^N^0^-games_get_achievements_summary|-|Games Hub level, XP, streak and.|+games_get_achievements_summary|-|Games Hub level, XP, streak| """
openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolHandlers.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolHandlers.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolHandlers.ktnew file mode 100644index 0000000000..51fe20fd19--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolHandlers.kt@@ -0,0 +1,642 @@+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.intents.todo.CompleteTodoData+import com.vayunmathur.library.intents.todo.GetTodosQuery+import com.vayunmathur.library.intents.todo.InsertTodoData+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.InMemoryPendingToolCallStore+import com.vayunmathur.openassistant.domain.ParsedToolCall+import com.vayunmathur.openassistant.domain.PendingToolCall+import com.vayunmathur.openassistant.domain.PendingToolCallStore+import com.vayunmathur.openassistant.domain.ToolArgs+import com.vayunmathur.openassistant.domain.ToolArgsResult+import com.vayunmathur.openassistant.domain.ToolRisk+import com.vayunmathur.openassistant.domain.ToolSpec+import com.vayunmathur.openassistant.domain.buildA2uiEnvelope+import com.vayunmathur.openassistant.domain.coerceToolArgs+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+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonObject+import java.util.UUID+import kotlinx.coroutines.runBlocking++/** Mutable holder for the render_ui envelope a tool handler stashes. */+internal class PendingRenderUi {+    var value: String? = null+}++/**+ * The tool-name to handler table for [AssistantTools]. Kept in its own+ * file so AssistantTools.kt stays reviewable; every entry is a thin+ * adapter over [AssistantToolIntents]/[AssistantDeviceTools] plus the+ * host summarizers, with outputs already capped for the model context.+ */+internal fun assistantToolHandlers(+    intents: AssistantToolIntents,+    device: AssistantDeviceTools,+    webTools: AssistantWebTools,+    memoryDao: MemoryDao?,+    renderUiStash: PendingRenderUi,+    renderUi: (String, String) -> String,+    renderShopCart: (com.vayunmathur.library.intents.shop.CartData) -> Unit,+    shopCartLineText: (String, String, Int, Long, String) -> String,+): 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_todos" to { a -> intents.runTool { intents.getTodos(GetTodosQuery(a.string("scope", "today"))) } },+    "create_todo" to { a ->+        intents.runTool {+            val title = a.string("title")+            intents.insertTodo(+                InsertTodoData(+                    title = title,+                    notes = a.string("notes"),+                    dueAt = a.number("due").toLong().takeIf { it > 0 },+                    priority = a.number("priority").toInt(),+                ),+            )+            "Success: Created task '$title'"+        }+    },+    "complete_todo" to { a ->+        intents.runTool {+            if (intents.completeTodo(CompleteTodoData(a.string("id"), a.string("title")))) {+                "Success: Marked the task done"+            } else {+                "Error: No matching open task"+            }+        }+    },+    "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"+        }+    },+    "music_get_now_playing" to { _ ->+        intents.runTool {+            com.vayunmathur.openassistant.platform.summarizeNowPlaying(intents.getMusicNowPlaying())+        }+    },+    "music_get_playlists" to { a ->+        intents.runTool {+            val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 10+            com.vayunmathur.openassistant.platform.summarizePlaylists(+                intents.getMusicPlaylists(a.string("query"), limit),+            )+        }+    },+    "music_get_playlist_tracks" to { a ->+        intents.runTool {+            val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 10+            com.vayunmathur.openassistant.platform.summarizePlaylistTracks(+                intents.getMusicPlaylistTracks(+                    a.number("playlist_id").toLong(), a.string("query"), limit,+                ),+            )+        }+    },+    "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")) } },+    "health_get_metric_summary" to { a ->+        intents.runTool {+            intents.getHealthMetricSummary(a.string("metric"), a.string("range", "7d"))+        }+    },+    "calculator_evaluate" to { a ->+        intents.runTool { intents.calculatorEvaluate(a.string("expression")) }+    },+    "calculator_convert_unit" to { a ->+        intents.runTool {+            intents.calculatorConvertUnit(+                a.number("value"), a.string("from_unit"), a.string("to_unit"),+            )+        }+    },+    "screentime_get_usage" to { _ ->+        intents.runTool {+            com.vayunmathur.openassistant.platform.summarizeScreentimeUsage(+                intents.getScreentimeUsage(+                    com.vayunmathur.library.intents.screentime.ScreentimeUsageQuery.MAX_TOP_APPS,+                ),+            )+        }+    },+    "education_get_progress" to { _ ->+        intents.runTool {+            com.vayunmathur.openassistant.platform.summarizeEducationProgress(intents.getEducationProgress())+        }+    },+    "news_search_headlines" to { a ->+        intents.runTool {+            val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5+            com.vayunmathur.openassistant.platform.summarizeNewsHeadlines(+                intents.searchNewsHeadlines(+                    a.string("query"),+                    a.string("category").takeIf { it.isNotBlank() },+                    limit,+                ),+            )+        }+    },+    "news_top_stories" to { a ->+        intents.runTool {+            val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5+            com.vayunmathur.openassistant.platform.summarizeNewsHeadlines(+                intents.topNewsStories(a.string("category").takeIf { it.isNotBlank() }, limit),+            )+        }+    },+    "news_get_story" to { a ->+        intents.runTool {+            com.vayunmathur.openassistant.platform.summarizeNewsStory(+                intents.getNewsStory(a.string("story_id")),+            )+        }+    },+    "news_read_article" to { a ->+        intents.runTool {+            com.vayunmathur.openassistant.platform.summarizeNewsArticle(+                intents.readNewsArticle(a.string("url"), a.number("offset").toInt()),+            )+        }+    },+    "astronomy_get_tonight" to { a ->+        intents.runTool {+            intents.getAstronomyTonight(a.numberOrNull("latitude"), a.numberOrNull("longitude"))+        }+    },+    "get_weather_forecast" to { a ->+        intents.runTool {+            val days = a.number("days").toInt().takeIf { it > 0 } ?: 3+            intents.getWeatherForecast(a.string("location"), days)+        }+    },+    "photos_search_photos" to { a ->+        intents.runTool {+            com.vayunmathur.openassistant.platform.summarizePhotoSearch(+                intents.searchPhotos(+                    com.vayunmathur.library.intents.photos.PhotoSearchQuery(+                        query = a.string("query"),+                        album = a.string("album").takeIf { it.isNotBlank() },+                        fromMillis = a.number("from_millis").toLong().takeIf { it > 0 },+                        toMillis = a.number("to_millis").toLong().takeIf { it > 0 },+                        limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5,+                    ),+                ),+            )+        }+    },+    "youpipe_get_subscriptions_latest" to { a ->+        intents.runTool {+            val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5+            com.vayunmathur.openassistant.platform.summarizeYouPipeLatest(+                intents.getYouPipeSubscriptionsLatest(+                    a.string("query"), a.string("category"), limit,+                ),+            )+        }+    },+    "files_search_files" to { a ->+        intents.runTool {+            val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5+            com.vayunmathur.openassistant.platform.summarizeFileHits(+                intents.searchFiles(a.string("query"), limit),+            )+        }+    },+    "games_get_achievements_summary" to { _ ->+        intents.runTool {+            com.vayunmathur.openassistant.platform.summarizeAchievementSummary(+                intents.getGamesAchievementsSummary(),+            )+        }+    },+    "get_directions" to { a ->+        intents.runTool {+            intents.getDirections(+                a.number("from_lat"), a.number("from_lng"),+                a.number("to_lat"), a.number("to_lng"),+                a.string("mode", "drive"),+            )+        }+    },+    "maps_search_places" to { a ->+        intents.runTool {+            val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5+            val nearLat = a.number("near_lat")+            val nearLng = a.number("near_lng")+            // Optional numbers coerce to 0 when absent; 0,0 is not a bias the user+            // asked for, so only forward a pair the model actually supplied non-zero.+            intents.searchPlaces(+                com.vayunmathur.library.intents.maps.MapsPlaceSearchQuery(+                    query = a.string("query"),+                    nearLat = nearLat.takeIf { it != 0.0 },+                    nearLng = nearLng.takeIf { it != 0.0 },+                    category = a.string("category").takeIf { it.isNotBlank() },+                    limit = limit,+                ),+            )+        }+    },+    "maps_get_saved_places" to { a ->+        intents.runTool {+            val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 10+            intents.getSavedPlaces(+                com.vayunmathur.library.intents.maps.SavedPlacesQuery(+                    query = a.string("query").takeIf { it.isNotBlank() },+                    limit = limit,+                ),+            )+        }+    },+    "get_ride_estimate" to { a ->+        intents.runTool {+            intents.getRideEstimate(+                a.number("pickup_lat"), a.number("pickup_lng"),+                a.number("dest_lat"), a.number("dest_lng"),+                a.string("pickup_label"), a.string("dest_label"),+            )+        }+    },+    "food_order_lookup" to { a ->+        intents.runTool {+            intents.foodOrderLookup(+                a.string("name"), a.number("lat"), a.number("lng"), a.string("address"),+            )+        }+    },+    "search_contacts" to { a -> intents.runTool { intents.searchContacts(a.string("query")) } },+    "find_conversations" to { a ->+        intents.runTool {+            val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5+            val list = intents.findConversations(a.string("query"), limit)+            if (list.isNotEmpty()) {+                renderUiStash.value = A2uiTemplates.listPicker(+                    "Conversations",+                    list.map {+                        PickerItem(+                            it.threadKey,+                            it.displayName?.takeIf { n -> n.isNotBlank() } ?: it.address,+                            "${it.line} · ${it.snippet.take(60)}",+                        )+                    },+                    actionName = "pick.conversation",+                )+            }+            com.vayunmathur.openassistant.platform.summarizeConversations(list)+        }+    },+    "get_conversation_messages" to { a ->+        intents.runTool {+            val limit = (a.number("limit").toInt().takeIf { it > 0 } ?: 10)+                .coerceAtMost(MAX_CONVERSATION_MESSAGES)+            com.vayunmathur.openassistant.platform.summarizeConversationMessages(+                intents.getConversationMessages(a.string("thread_key"), limit),+            )+        }+    },+    "draft_message" to { a ->+        renderUiStash.value = A2uiTemplates.messageComposer(+            a.string("recipient_name"), a.string("address"), a.string("line"),+            a.string("body"), a.string("thread_remote_id").takeIf { it.isNotBlank() },+        )+        "Composer shown. Nothing has been sent; the user reviews, edits and taps Send."+    },+    "send_message_v2" to { a ->+        intents.runTool {+            val result = intents.sendMessageV2(+                com.vayunmathur.library.intents.communicate.SendMessageRequest(+                    a.string("address"), a.string("line"), a.string("body"),+                    a.string("thread_remote_id").takeIf { it.isNotBlank() },+                ),+            )+            if (!result.success && result.error == "GOOGLE_VOICE_REQUIRES_ACTIVITY") {+                renderUiStash.value = A2uiTemplates.resultCard(+                    "Open in Communicate",+                    listOf("Google Voice messages are sent from the Communicate app."),+                    actionLabel = "Open conversation",+                    actionName = "open.conversation",+                    actionContext = mapOf(+                        "address" to a.string("address"),+                        "line" to a.string("line"),+                    ),+                )+            }+            com.vayunmathur.openassistant.platform.summarizeSendResult(result)+        }+    },+    "find_restaurants" to { a ->+        intents.runTool {+            val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5+            val list = intents.findRestaurants(+                a.string("query"), a.number("lat"), a.number("lng"), limit)+            if (list.isNotEmpty()) {+                renderUiStash.value = A2uiTemplates.listPicker(+                    "Restaurants",+                    list.map {+                        PickerItem(+                            it.id.toString(), it.name,+                            "${if (it.isOpen) "Open" else "Closed"} · ${it.address.take(50)}",+                            it.imageUrl.takeIf { u -> u.isNotBlank() },+                        )+                    },+                    actionName = "pick.restaurant",+                )+            }+            com.vayunmathur.openassistant.platform.summarizeRestaurants(list)+        }+    },+    "get_restaurant_menu" to { a ->+        intents.runTool {+            val menu = intents.getRestaurantMenu(a.number("merchant_id").toInt())+            if (menu.error == null && menu.items.isNotEmpty()) {+                renderUiStash.value = A2uiTemplates.foodMenu(+                    menu.merchantName, menu.merchantId,+                    menu.items.take(24).map {+                        MenuItemRow(it.id, it.name, it.priceCents, it.available)+                    },+                )+            }+            com.vayunmathur.openassistant.platform.summarizeMenu(menu)+        }+    },+    "food_get_cart" to { _ ->+        intents.runTool {+            val cart = intents.getFoodCart()+            if (cart.error == null && cart.items.isNotEmpty()) {+                renderUiStash.value = A2uiTemplates.foodCart(+                    cart.merchantName, cart.merchantId,+                    cart.items.map { CartLineRow(it.itemId, it.name, it.qty, it.lineTotalCents) },+                    cart.totalCents,+                )+            }+            com.vayunmathur.openassistant.platform.summarizeFoodCart(cart)+        }+    },+    "food_set_cart" to { a ->+        val items = com.vayunmathur.openassistant.platform.parseSetCartItems(a.string("items_json"))+            ?: return@to "Error: items_json must be a JSON array of {itemId, qty, modifierIds}"+        intents.runTool {+            val cart = intents.setFoodCart(a.number("merchant_id").toInt(), items)+            // Light write (design §2): executed immediately, always rendered back.+            if (cart.error == null) {+                renderUiStash.value = A2uiTemplates.foodCart(+                    cart.merchantName, cart.merchantId,+                    cart.items.map { CartLineRow(it.itemId, it.name, it.qty, it.lineTotalCents) },+                    cart.totalCents,+                )+            }+            com.vayunmathur.openassistant.platform.summarizeFoodCart(cart)+        }+    },+    "food_prepare_order" to { a ->+        intents.runTool {+            com.vayunmathur.openassistant.platform.summarizeOrderSummary(+                intents.prepareFoodOrder(+                    com.vayunmathur.library.intents.fooddelivery.PrepareOrder(+                        merchantId = a.number("merchant_id").toInt(),+                        isPickup = a.number("is_pickup").toInt() == 1,+                        addressId = a.string("address_id").takeIf { it.isNotBlank() },+                        tipCents = a.number("tip_cents").toInt(),+                        promo = a.string("promo").takeIf { it.isNotBlank() },+                    ),+                ),+            )+        }+    },+    "place_food_order" to { a ->+        intents.runTool {+            val summary = intents.prepareFoodOrder(+                com.vayunmathur.library.intents.fooddelivery.PrepareOrder(+                    merchantId = a.number("merchant_id").toInt(),+                ),+            )+            if (summary.error == null) {+                renderUiStash.value = A2uiTemplates.foodOrderSummary(+                    summary.merchantName,+                    summary.items.map { "${it.name} × ${it.qty} — ${formatCents(it.lineTotalCents)}" },+                    summary.subtotalCents, summary.tipCents, summary.totalCents,+                    summary.checkoutDeepLink, summary.merchantId,+                )+            }+            com.vayunmathur.openassistant.platform.summarizeOrderSummary(summary) ++                " Show the user this summary; they place the order in FoodDelivery."+        }+    },+    "get_food_orders" to { _ ->+        intents.runTool {+            com.vayunmathur.openassistant.platform.summarizeFoodOrders(intents.getFoodOrders())+        }+    },+    "search_products" to { a ->+        intents.runTool {+            val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5+            val list = intents.searchProducts(a.string("query"), limit)+            // One product card per call would flood the chat; the first hit's card+            // demonstrates variants/stepper, the rest stay model-readable text.+            list.firstOrNull()?.let { first ->+                intents.getProductDetail(first.shopDomain, first.productId, first.variantId)+                    .takeIf { it.error == null && it.variants.isNotEmpty() }+                    ?.let { detail ->+                        renderUiStash.value = A2uiTemplates.productCard(+                            detail.title, detail.storeName, detail.shopDomain, detail.imageUrl,+                            detail.variants.map {+                                ProductVariantRow(it.variantId, it.title, it.price, it.currency, it.available)+                            },+                        )+                    }+            }+            com.vayunmathur.openassistant.platform.summarizeProducts(list)+        }+    },+    "get_product_detail" to { a ->+        intents.runTool {+            val detail = intents.getProductDetail(+                a.string("shop_domain"), a.string("product_id"),+                a.string("variant_id").takeIf { it.isNotBlank() },+            )+            if (detail.error == null && detail.variants.isNotEmpty()) {+                renderUiStash.value = A2uiTemplates.productCard(+                    detail.title, detail.storeName, detail.shopDomain, detail.imageUrl,+                    detail.variants.map {+                        ProductVariantRow(it.variantId, it.title, it.price, it.currency, it.available)+                    },+                )+            }+            com.vayunmathur.openassistant.platform.summarizeProductDetail(detail)+        }+    },+    "shop_get_cart" to { _ ->+        intents.runTool {+            val cart = intents.getShopCart()+            if (cart.error == null && cart.totalItems > 0) {+                renderShopCart(cart)+            }+            com.vayunmathur.openassistant.platform.summarizeShopCart(cart)+        }+    },+    "shop_add_to_cart" to { a ->+        val quantity = a.number("quantity").toInt().takeIf { it > 0 } ?: 1+        intents.runTool {+            val cart = intents.addToShopCart(+                com.vayunmathur.library.intents.shop.AddToCartRequest(+                    a.string("shop_domain"), a.string("variant_id"), quantity,+                ),+            )+            // Light write: executed once, cart rendered back, never auto-retried.+            if (cart.error == null) {+                renderShopCart(cart)+            }+            com.vayunmathur.openassistant.platform.summarizeShopCart(cart)+        }+    },+    "shop_remove_from_cart" to { a ->+        intents.runTool {+            val cart = intents.removeFromShopCart(a.string("variant_id"))+            if (cart.error == null) {+                renderShopCart(cart)+            }+            com.vayunmathur.openassistant.platform.summarizeShopCart(cart)+        }+    },+    "start_shop_checkout" to { a ->+        intents.runTool {+            val cart = intents.getShopCart()+            val store = cart.stores.firstOrNull { it.shopDomain == a.string("shop_domain") }+            if (cart.error == null && store != null && store.lines.isNotEmpty()) {+                renderUiStash.value = A2uiTemplates.shopCheckoutSummary(+                    store.storeName, store.shopDomain,+                    store.lines.map { line ->+                        shopCartLineText(+                            line.title,+                            line.variantTitle,+                            line.quantity,+                            line.price,+                            line.currency,+                        )+                    },+                )+            }+            com.vayunmathur.openassistant.platform.summarizeShopCart(cart) ++                " Show the user this summary; they check out in Shop. This is not a paid order."+        }+    },+    "get_shop_orders" to { _ ->+        intents.runTool {+            com.vayunmathur.openassistant.platform.summarizeShopOrders(intents.getShopOrders())+        }+    },+    "appstore_search_apps" to { a ->+        intents.runTool {+            val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5+            com.vayunmathur.openassistant.platform.summarizeAppStoreApps(+                intents.searchAppStoreApps(a.string("query"), limit),+            )+        }+    },+    "appstore_get_updates" to { _ ->+        intents.runTool {+            com.vayunmathur.openassistant.platform.summarizeAppStoreUpdates(+                intents.getAppStoreUpdates(),+            )+        }+    },+    "web_search" to { a ->+        val count = a.number("count").toInt().takeIf { it > 0 } ?: 5+        val result = runBlocking { webTools.webSearch(a.string("query"), count, a.string("kind", "text")) }+        webTools.takeTemplate()?.let { renderUiStash.value = it }+        result+    },+    "web_read" to { a -> runBlocking { webTools.webRead(a.string("url")) } },+    "web_read_result" to { a ->+        runBlocking { webTools.webReadResult(a.number("index").toInt(), a.number("offset").toInt()) }+    },+    "render_ui" to { a -> renderUi(a.string("components_json"), a.string("data_json")) },+    "translate_text" to { a ->+        intents.runTool {+            intents.translateText(a.string("text"), a.string("target_lang"), a.string("source_lang"))+        }+    },+    "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")) } },+    "travel_get_trips" to { a ->+        intents.runTool {+            val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5+            com.vayunmathur.openassistant.platform.summarizeTripSummaries(+                intents.getTravelTrips(a.string("when", "upcoming"), limit),+            )+        }+    },++)
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 674c26a716..ba26d97a94 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt@@ -66,589 +66,23 @@ class AssistantTools(      * write the DB, so [MamlChatEngine] consumes this after the loop and appends it to the      * reply as an a2ui fence, which the normal split/persist path then stores.      */-    var pendingRenderUi: String? = null+    private val renderUiStash = PendingRenderUi() -    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_todos" to { a -> intents.runTool { intents.getTodos(GetTodosQuery(a.string("scope", "today"))) } },-        "create_todo" to { a ->-            intents.runTool {-                val title = a.string("title")-                intents.insertTodo(-                    InsertTodoData(-                        title = title,-                        notes = a.string("notes"),-                        dueAt = a.number("due").toLong().takeIf { it > 0 },-                        priority = a.number("priority").toInt(),-                    ),-                )-                "Success: Created task '$title'"-            }-        },-        "complete_todo" to { a ->-            intents.runTool {-                if (intents.completeTodo(CompleteTodoData(a.string("id"), a.string("title")))) {-                    "Success: Marked the task done"-                } else {-                    "Error: No matching open task"-                }-            }-        },-        "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"-            }-        },-        "music_get_now_playing" to { _ ->-            intents.runTool {-                com.vayunmathur.openassistant.platform.summarizeNowPlaying(intents.getMusicNowPlaying())-            }-        },-        "music_get_playlists" to { a ->-            intents.runTool {-                val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 10-                com.vayunmathur.openassistant.platform.summarizePlaylists(-                    intents.getMusicPlaylists(a.string("query"), limit),-                )-            }-        },-        "music_get_playlist_tracks" to { a ->-            intents.runTool {-                val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 10-                com.vayunmathur.openassistant.platform.summarizePlaylistTracks(-                    intents.getMusicPlaylistTracks(-                        a.number("playlist_id").toLong(), a.string("query"), limit,-                    ),-                )-            }-        },-        "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")) } },-        "health_get_metric_summary" to { a ->-            intents.runTool {-                intents.getHealthMetricSummary(a.string("metric"), a.string("range", "7d"))-            }-        },-        "calculator_evaluate" to { a ->-            intents.runTool { intents.calculatorEvaluate(a.string("expression")) }-        },-        "calculator_convert_unit" to { a ->-            intents.runTool {-                intents.calculatorConvertUnit(-                    a.number("value"), a.string("from_unit"), a.string("to_unit"),-                )-            }-        },-        "screentime_get_usage" to { _ ->-            intents.runTool {-                com.vayunmathur.openassistant.platform.summarizeScreentimeUsage(-                    intents.getScreentimeUsage(-                        com.vayunmathur.library.intents.screentime.ScreentimeUsageQuery.MAX_TOP_APPS,-                    ),-                )-            }-        },-        "education_get_progress" to { _ ->-            intents.runTool {-                com.vayunmathur.openassistant.platform.summarizeEducationProgress(intents.getEducationProgress())-            }-        },-        "news_search_headlines" to { a ->-            intents.runTool {-                val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5-                com.vayunmathur.openassistant.platform.summarizeNewsHeadlines(-                    intents.searchNewsHeadlines(-                        a.string("query"),-                        a.string("category").takeIf { it.isNotBlank() },-                        limit,-                    ),-                )-            }-        },-        "news_top_stories" to { a ->-            intents.runTool {-                val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5-                com.vayunmathur.openassistant.platform.summarizeNewsHeadlines(-                    intents.topNewsStories(a.string("category").takeIf { it.isNotBlank() }, limit),-                )-            }-        },-        "news_get_story" to { a ->-            intents.runTool {-                com.vayunmathur.openassistant.platform.summarizeNewsStory(-                    intents.getNewsStory(a.string("story_id")),-                )-            }-        },-        "news_read_article" to { a ->-            intents.runTool {-                com.vayunmathur.openassistant.platform.summarizeNewsArticle(-                    intents.readNewsArticle(a.string("url"), a.number("offset").toInt()),-                )-            }-        },-        "astronomy_get_tonight" to { a ->-            intents.runTool {-                intents.getAstronomyTonight(a.numberOrNull("latitude"), a.numberOrNull("longitude"))-            }-        },-        "get_weather_forecast" to { a ->-            intents.runTool {-                val days = a.number("days").toInt().takeIf { it > 0 } ?: 3-                intents.getWeatherForecast(a.string("location"), days)-            }-        },-        "photos_search_photos" to { a ->-            intents.runTool {-                com.vayunmathur.openassistant.platform.summarizePhotoSearch(-                    intents.searchPhotos(-                        com.vayunmathur.library.intents.photos.PhotoSearchQuery(-                            query = a.string("query"),-                            album = a.string("album").takeIf { it.isNotBlank() },-                            fromMillis = a.number("from_millis").toLong().takeIf { it > 0 },-                            toMillis = a.number("to_millis").toLong().takeIf { it > 0 },-                            limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5,-                        ),-                    ),-                )-            }-        },-        "youpipe_get_subscriptions_latest" to { a ->-            intents.runTool {-                val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5-                com.vayunmathur.openassistant.platform.summarizeYouPipeLatest(-                    intents.getYouPipeSubscriptionsLatest(-                        a.string("query"), a.string("category"), limit,-                    ),-                )-            }-        },-        "files_search_files" to { a ->-            intents.runTool {-                val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5-                com.vayunmathur.openassistant.platform.summarizeFileHits(-                    intents.searchFiles(a.string("query"), limit),-                )-            }-        },-        "games_get_achievements_summary" to { _ ->-            intents.runTool {-                com.vayunmathur.openassistant.platform.summarizeAchievementSummary(-                    intents.getGamesAchievementsSummary(),-                )-            }-        },-        "get_directions" to { a ->-            intents.runTool {-                intents.getDirections(-                    a.number("from_lat"), a.number("from_lng"),-                    a.number("to_lat"), a.number("to_lng"),-                    a.string("mode", "drive"),-                )-            }-        },-        "maps_search_places" to { a ->-            intents.runTool {-                val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5-                val nearLat = a.number("near_lat")-                val nearLng = a.number("near_lng")-                // Optional numbers coerce to 0 when absent; 0,0 is not a bias the user-                // asked for, so only forward a pair the model actually supplied non-zero.-                intents.searchPlaces(-                    com.vayunmathur.library.intents.maps.MapsPlaceSearchQuery(-                        query = a.string("query"),-                        nearLat = nearLat.takeIf { it != 0.0 },-                        nearLng = nearLng.takeIf { it != 0.0 },-                        category = a.string("category").takeIf { it.isNotBlank() },-                        limit = limit,-                    ),-                )-            }-        },-        "maps_get_saved_places" to { a ->-            intents.runTool {-                val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 10-                intents.getSavedPlaces(-                    com.vayunmathur.library.intents.maps.SavedPlacesQuery(-                        query = a.string("query").takeIf { it.isNotBlank() },-                        limit = limit,-                    ),-                )-            }-        },-        "get_ride_estimate" to { a ->-            intents.runTool {-                intents.getRideEstimate(-                    a.number("pickup_lat"), a.number("pickup_lng"),-                    a.number("dest_lat"), a.number("dest_lng"),-                    a.string("pickup_label"), a.string("dest_label"),-                )-            }-        },-        "food_order_lookup" to { a ->-            intents.runTool {-                intents.foodOrderLookup(-                    a.string("name"), a.number("lat"), a.number("lng"), a.string("address"),-                )-            }-        },-        "search_contacts" to { a -> intents.runTool { intents.searchContacts(a.string("query")) } },-        "find_conversations" to { a ->-            intents.runTool {-                val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5-                val list = intents.findConversations(a.string("query"), limit)-                if (list.isNotEmpty()) {-                    pendingRenderUi = A2uiTemplates.listPicker(-                        "Conversations",-                        list.map {-                            PickerItem(-                                it.threadKey,-                                it.displayName?.takeIf { n -> n.isNotBlank() } ?: it.address,-                                "${it.line} · ${it.snippet.take(60)}",-                            )-                        },-                        actionName = "pick.conversation",-                    )-                }-                com.vayunmathur.openassistant.platform.summarizeConversations(list)-            }-        },-        "get_conversation_messages" to { a ->-            intents.runTool {-                val limit = (a.number("limit").toInt().takeIf { it > 0 } ?: 10)-                    .coerceAtMost(MAX_CONVERSATION_MESSAGES)-                com.vayunmathur.openassistant.platform.summarizeConversationMessages(-                    intents.getConversationMessages(a.string("thread_key"), limit),-                )-            }-        },-        "draft_message" to { a ->-            pendingRenderUi = A2uiTemplates.messageComposer(-                a.string("recipient_name"), a.string("address"), a.string("line"),-                a.string("body"), a.string("thread_remote_id").takeIf { it.isNotBlank() },-            )-            "Composer shown. Nothing has been sent; the user reviews, edits and taps Send."-        },-        "send_message_v2" to { a ->-            intents.runTool {-                val result = intents.sendMessageV2(-                    com.vayunmathur.library.intents.communicate.SendMessageRequest(-                        a.string("address"), a.string("line"), a.string("body"),-                        a.string("thread_remote_id").takeIf { it.isNotBlank() },-                    ),-                )-                if (!result.success && result.error == "GOOGLE_VOICE_REQUIRES_ACTIVITY") {-                    pendingRenderUi = A2uiTemplates.resultCard(-                        "Open in Communicate",-                        listOf("Google Voice messages are sent from the Communicate app."),-                        actionLabel = "Open conversation",-                        actionName = "open.conversation",-                        actionContext = mapOf(-                            "address" to a.string("address"),-                            "line" to a.string("line"),-                        ),-                    )-                }-                com.vayunmathur.openassistant.platform.summarizeSendResult(result)-            }-        },-        "find_restaurants" to { a ->-            intents.runTool {-                val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5-                val list = intents.findRestaurants(-                    a.string("query"), a.number("lat"), a.number("lng"), limit)-                if (list.isNotEmpty()) {-                    pendingRenderUi = A2uiTemplates.listPicker(-                        "Restaurants",-                        list.map {-                            PickerItem(-                                it.id.toString(), it.name,-                                "${if (it.isOpen) "Open" else "Closed"} · ${it.address.take(50)}",-                                it.imageUrl.takeIf { u -> u.isNotBlank() },-                            )-                        },-                        actionName = "pick.restaurant",-                    )-                }-                com.vayunmathur.openassistant.platform.summarizeRestaurants(list)-            }-        },-        "get_restaurant_menu" to { a ->-            intents.runTool {-                val menu = intents.getRestaurantMenu(a.number("merchant_id").toInt())-                if (menu.error == null && menu.items.isNotEmpty()) {-                    pendingRenderUi = A2uiTemplates.foodMenu(-                        menu.merchantName, menu.merchantId,-                        menu.items.take(24).map {-                            MenuItemRow(it.id, it.name, it.priceCents, it.available)-                        },-                    )-                }-                com.vayunmathur.openassistant.platform.summarizeMenu(menu)-            }-        },-        "food_get_cart" to { _ ->-            intents.runTool {-                val cart = intents.getFoodCart()-                if (cart.error == null && cart.items.isNotEmpty()) {-                    pendingRenderUi = A2uiTemplates.foodCart(-                        cart.merchantName, cart.merchantId,-                        cart.items.map { CartLineRow(it.itemId, it.name, it.qty, it.lineTotalCents) },-                        cart.totalCents,-                    )-                }-                com.vayunmathur.openassistant.platform.summarizeFoodCart(cart)-            }-        },-        "food_set_cart" to { a ->-            val items = com.vayunmathur.openassistant.platform.parseSetCartItems(a.string("items_json"))-                ?: return@to "Error: items_json must be a JSON array of {itemId, qty, modifierIds}"-            intents.runTool {-                val cart = intents.setFoodCart(a.number("merchant_id").toInt(), items)-                // Light write (design §2): executed immediately, always rendered back.-                if (cart.error == null) {-                    pendingRenderUi = A2uiTemplates.foodCart(-                        cart.merchantName, cart.merchantId,-                        cart.items.map { CartLineRow(it.itemId, it.name, it.qty, it.lineTotalCents) },-                        cart.totalCents,-                    )-                }-                com.vayunmathur.openassistant.platform.summarizeFoodCart(cart)-            }-        },-        "food_prepare_order" to { a ->-            intents.runTool {-                com.vayunmathur.openassistant.platform.summarizeOrderSummary(-                    intents.prepareFoodOrder(-                        com.vayunmathur.library.intents.fooddelivery.PrepareOrder(-                            merchantId = a.number("merchant_id").toInt(),-                            isPickup = a.number("is_pickup").toInt() == 1,-                            addressId = a.string("address_id").takeIf { it.isNotBlank() },-                            tipCents = a.number("tip_cents").toInt(),-                            promo = a.string("promo").takeIf { it.isNotBlank() },-                        ),-                    ),-                )-            }-        },-        "place_food_order" to { a ->-            intents.runTool {-                val summary = intents.prepareFoodOrder(-                    com.vayunmathur.library.intents.fooddelivery.PrepareOrder(-                        merchantId = a.number("merchant_id").toInt(),-                    ),-                )-                if (summary.error == null) {-                    pendingRenderUi = A2uiTemplates.foodOrderSummary(-                        summary.merchantName,-                        summary.items.map { "${it.name} × ${it.qty} — ${formatCents(it.lineTotalCents)}" },-                        summary.subtotalCents, summary.tipCents, summary.totalCents,-                        summary.checkoutDeepLink, summary.merchantId,-                    )-                }-                com.vayunmathur.openassistant.platform.summarizeOrderSummary(summary) +-                    " Show the user this summary; they place the order in FoodDelivery."-            }-        },-        "get_food_orders" to { _ ->-            intents.runTool {-                com.vayunmathur.openassistant.platform.summarizeFoodOrders(intents.getFoodOrders())-            }-        },-        "search_products" to { a ->-            intents.runTool {-                val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5-                val list = intents.searchProducts(a.string("query"), limit)-                // One product card per call would flood the chat; the first hit's card-                // demonstrates variants/stepper, the rest stay model-readable text.-                list.firstOrNull()?.let { first ->-                    intents.getProductDetail(first.shopDomain, first.productId, first.variantId)-                        .takeIf { it.error == null && it.variants.isNotEmpty() }-                        ?.let { detail ->-                            pendingRenderUi = A2uiTemplates.productCard(-                                detail.title, detail.storeName, detail.shopDomain, detail.imageUrl,-                                detail.variants.map {-                                    ProductVariantRow(it.variantId, it.title, it.price, it.currency, it.available)-                                },-                            )-                        }-                }-                com.vayunmathur.openassistant.platform.summarizeProducts(list)-            }-        },-        "get_product_detail" to { a ->-            intents.runTool {-                val detail = intents.getProductDetail(-                    a.string("shop_domain"), a.string("product_id"),-                    a.string("variant_id").takeIf { it.isNotBlank() },-                )-                if (detail.error == null && detail.variants.isNotEmpty()) {-                    pendingRenderUi = A2uiTemplates.productCard(-                        detail.title, detail.storeName, detail.shopDomain, detail.imageUrl,-                        detail.variants.map {-                            ProductVariantRow(it.variantId, it.title, it.price, it.currency, it.available)-                        },-                    )-                }-                com.vayunmathur.openassistant.platform.summarizeProductDetail(detail)-            }-        },-        "shop_get_cart" to { _ ->-            intents.runTool {-                val cart = intents.getShopCart()-                if (cart.error == null && cart.totalItems > 0) {-                    renderShopCart(cart)-                }-                com.vayunmathur.openassistant.platform.summarizeShopCart(cart)-            }-        },-        "shop_add_to_cart" to { a ->-            val quantity = a.number("quantity").toInt().takeIf { it > 0 } ?: 1-            intents.runTool {-                val cart = intents.addToShopCart(-                    com.vayunmathur.library.intents.shop.AddToCartRequest(-                        a.string("shop_domain"), a.string("variant_id"), quantity,-                    ),-                )-                // Light write: executed once, cart rendered back, never auto-retried.-                if (cart.error == null) {-                    renderShopCart(cart)-                }-                com.vayunmathur.openassistant.platform.summarizeShopCart(cart)-            }-        },-        "shop_remove_from_cart" to { a ->-            intents.runTool {-                val cart = intents.removeFromShopCart(a.string("variant_id"))-                if (cart.error == null) {-                    renderShopCart(cart)-                }-                com.vayunmathur.openassistant.platform.summarizeShopCart(cart)-            }-        },-        "start_shop_checkout" to { a ->-            intents.runTool {-                val cart = intents.getShopCart()-                val store = cart.stores.firstOrNull { it.shopDomain == a.string("shop_domain") }-                if (cart.error == null && store != null && store.lines.isNotEmpty()) {-                    pendingRenderUi = A2uiTemplates.shopCheckoutSummary(-                        store.storeName, store.shopDomain,-                        store.lines.map { line ->-                            shopCartLineText(-                                line.title,-                                line.variantTitle,-                                line.quantity,-                                line.price,-                                line.currency,-                            )-                        },-                    )-                }-                com.vayunmathur.openassistant.platform.summarizeShopCart(cart) +-                    " Show the user this summary; they check out in Shop. This is not a paid order."-            }-        },-        "get_shop_orders" to { _ ->-            intents.runTool {-                com.vayunmathur.openassistant.platform.summarizeShopOrders(intents.getShopOrders())-            }-        },-        "appstore_search_apps" to { a ->-            intents.runTool {-                val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5-                com.vayunmathur.openassistant.platform.summarizeAppStoreApps(-                    intents.searchAppStoreApps(a.string("query"), limit),-                )-            }-        },-        "appstore_get_updates" to { _ ->-            intents.runTool {-                com.vayunmathur.openassistant.platform.summarizeAppStoreUpdates(-                    intents.getAppStoreUpdates(),-                )-            }-        },-        "web_search" to { a ->-            val count = a.number("count").toInt().takeIf { it > 0 } ?: 5-            val result = runBlocking { webTools.webSearch(a.string("query"), count, a.string("kind", "text")) }-            webTools.takeTemplate()?.let { pendingRenderUi = it }-            result-        },-        "web_read" to { a -> runBlocking { webTools.webRead(a.string("url")) } },-        "web_read_result" to { a ->-            runBlocking { webTools.webReadResult(a.number("index").toInt(), a.number("offset").toInt()) }-        },-        "render_ui" to { a -> renderUi(a.string("components_json"), a.string("data_json")) },-        "translate_text" to { a ->-            intents.runTool {-                intents.translateText(a.string("text"), a.string("target_lang"), a.string("source_lang"))-            }-        },-        "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")) } },-        "travel_get_trips" to { a ->-            intents.runTool {-                val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5-                com.vayunmathur.openassistant.platform.summarizeTripSummaries(-                    intents.getTravelTrips(a.string("when", "upcoming"), limit),-                )-            }-        },+    var pendingRenderUi: String?+        get() = renderUiStash.value+        set(value) {+            renderUiStash.value = value+        }++    private val handlers: Map<String, (ToolArgs) -> String> = assistantToolHandlers(+        intents = intents,+        device = device,+        webTools = webTools,+        memoryDao = memoryDao,+        renderUiStash = renderUiStash,+        renderUi = ::renderUi,+        renderShopCart = ::renderShopCart,+        shopCartLineText = ::shopCartLineText,     )      init {