maps: add OpenAssistant place search tools
- Commit
7fd9db02376dd28ab4c9ea1a072740019e822334- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-02 04:25 UTC (4 days ago)
- Parents
6827508
maps_search_places and maps_get_saved_places for OpenAssistant (library/intents/maps DTOs, validated contracts in maps/intents, OA registration), all filtered and capped at 10 results with 120-char fields. Merged by hand from 414e47e52: OA-side hunks were spliced onto main (health summarizers preserved), :openassistant compileReleaseKotlin and lintVitalRelease verified green. Maps DialogAsRoute fixes land separately (agent-lint-maps2).
Diff
library/AGENTS.md
diff --git a/library/AGENTS.md b/library/AGENTS.mdindex 4d6eb0c1e1..8e070effe5 100644--- a/library/AGENTS.md+++ b/library/AGENTS.md@@ -26,6 +26,7 @@ - com/vayunmathur/library/intents/findfamily/FamilyMemberData.kt - com/vayunmathur/library/intents/fooddelivery/OrderLookupData.kt - com/vayunmathur/library/intents/maps/DirectionsData.kt+- com/vayunmathur/library/intents/maps/PlaceData.kt — capped place DTOs (`MapsPlaceSearchQuery`, `SavedPlacesQuery`, `PlaceData`; shared caps `MAX_PLACE_RESULTS=10`, `MAX_PLACE_TEXT_CHARS=120`) - com/vayunmathur/library/intents/music/MusicData.kt - com/vayunmathur/library/intents/taxi/RideEstimateData.kt - com/vayunmathur/library/intents/weather/WeatherData.kt
library/src/main/java/com/vayunmathur/library/intents/maps/PlaceData.kt
diff --git a/library/src/main/java/com/vayunmathur/library/intents/maps/PlaceData.kt b/library/src/main/java/com/vayunmathur/library/intents/maps/PlaceData.ktnew file mode 100644index 0000000000..6fa4644fef--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/intents/maps/PlaceData.kt@@ -0,0 +1,60 @@+package com.vayunmathur.library.intents.maps++import kotlinx.serialization.Serializable++/**+ * Shared wire types for maps' place assistant intents+ * ([SearchPlacesIntent][com.vayunmathur.maps.intents.SearchPlacesIntent] and+ * [SavedPlacesIntent][com.vayunmathur.maps.intents.SavedPlacesIntent]) — a co-signed caller+ * (OpenAssistant) resolves a place name to coordinates it can chain into `get_directions` /+ * `get_ride_estimate`, or reads the user's saved places back as summaries.+ *+ * Capped by contract, provider-side: at most [MAX_PLACE_RESULTS] rows, and [PlaceData.name] /+ * [PlaceData.address] at most [MAX_PLACE_TEXT_CHARS] chars each. Thin and UI-free; every field+ * has a default so older/newer callers can omit fields without breaking decode (library+ * DTO-compat rule).+ */+/** Hard result cap for both place tools; the provider clamps every limit to `1..MAX`. */+const val MAX_PLACE_RESULTS = 10++/** Per-field text cap for [PlaceData.name] and [PlaceData.address]. */+const val MAX_PLACE_TEXT_CHARS = 120++/** Default result count for [MapsPlaceSearchQuery] when the caller omits [limit]. */+const val DEFAULT_PLACE_LIMIT = 5++/**+ * Text place search: [query] is a place name or a category word (e.g. "coffee");+ * [nearLat]/[nearLng] optionally bias ranking towards a point the caller already holds+ * (never read from family location); [category] optionally filters by category label.+ */+@Serializable+data class MapsPlaceSearchQuery(+ val query: String = "",+ val nearLat: Double? = null,+ val nearLng: Double? = null,+ val category: String? = null,+ val limit: Int = DEFAULT_PLACE_LIMIT,+)++/** The user's saved (starred + listed) places, optionally name-filtered by [query]. */+@Serializable+data class SavedPlacesQuery(+ val query: String? = null,+ val limit: Int = MAX_PLACE_RESULTS,+)++/**+ * One place as the assistant sees it: a short stable [id], capped [name]/[address], and the+ * coordinates a follow-up directions/ride call needs. No phone, hours, photos, or ratings —+ * summaries only.+ */+@Serializable+data class PlaceData(+ val id: String = "",+ val name: String = "",+ val address: String? = null,+ val lat: Double = 0.0,+ val lng: Double = 0.0,+ val category: String? = null,+)
library/src/test/java/com/vayunmathur/library/intents/MapsPlaceDtoTest.kt
diff --git a/library/src/test/java/com/vayunmathur/library/intents/MapsPlaceDtoTest.kt b/library/src/test/java/com/vayunmathur/library/intents/MapsPlaceDtoTest.ktnew file mode 100644index 0000000000..e41021d0a6--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/intents/MapsPlaceDtoTest.kt@@ -0,0 +1,72 @@+package com.vayunmathur.library.intents++import com.vayunmathur.library.intents.maps.DEFAULT_PLACE_LIMIT+import com.vayunmathur.library.intents.maps.MAX_PLACE_RESULTS+import com.vayunmathur.library.intents.maps.MAX_PLACE_TEXT_CHARS+import com.vayunmathur.library.intents.maps.MapsPlaceSearchQuery+import com.vayunmathur.library.intents.maps.PlaceData+import com.vayunmathur.library.intents.maps.SavedPlacesQuery+import kotlinx.serialization.json.Json+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/**+ * The maps place DTOs travel as JSON over the `AssistantIntent` binder. These pin the wire+ * shape, the all-defaults decode compatibility, and the shared cap constants both the maps+ * provider and the OpenAssistant host clamp to.+ */+class MapsPlaceDtoTest {+ private val json = Json++ @Test+ fun placeCaps_areTheContractValues() {+ assertEquals(10, MAX_PLACE_RESULTS)+ assertEquals(120, MAX_PLACE_TEXT_CHARS)+ assertEquals(5, DEFAULT_PLACE_LIMIT)+ }++ @Test+ fun searchQuery_roundTrips_withAllFields() {+ val original = MapsPlaceSearchQuery(+ query = "coffee", nearLat = 37.8, nearLng = -122.4, category = "Cafe", limit = 7,+ )+ val decoded = json.decodeFromString(+ MapsPlaceSearchQuery.serializer(),+ json.encodeToString(MapsPlaceSearchQuery.serializer(), original),+ )+ assertEquals(original, decoded)+ }++ @Test+ fun searchQuery_decodesFromEmptyObject_withDefaults() {+ val decoded = json.decodeFromString(MapsPlaceSearchQuery.serializer(), "{}")+ assertEquals(MapsPlaceSearchQuery(), decoded)+ assertNull(decoded.nearLat)+ assertNull(decoded.category)+ }++ @Test+ fun savedQuery_andPlaceData_roundTrip() {+ val query = SavedPlacesQuery(query = "home", limit = 3)+ assertEquals(+ query,+ json.decodeFromString(+ SavedPlacesQuery.serializer(),+ json.encodeToString(SavedPlacesQuery.serializer(), query),+ ),+ )+ val place = PlaceData(+ id = "poi:1:2:3", name = "Cafe", address = "1 Main St",+ lat = 37.8, lng = -122.4, category = "Cafe",+ )+ assertEquals(+ place,+ json.decodeFromString(+ PlaceData.serializer(),+ json.encodeToString(PlaceData.serializer(), place),+ ),+ )+ assertEquals(SavedPlacesQuery(), json.decodeFromString(SavedPlacesQuery.serializer(), "{}"))+ }+}
maps/AGENTS.md
diff --git a/maps/AGENTS.md b/maps/AGENTS.mdindex d6df913428..39e5e2756b 100644--- a/maps/AGENTS.md+++ b/maps/AGENTS.md@@ -57,6 +57,8 @@ _Install: ./install maps (dev by default)._ - com/vayunmathur/maps/data/transit/TransitousModels.kt ### intents/ — assistant IPC - com/vayunmathur/maps/intents/DirectionsIntent.kt+- com/vayunmathur/maps/intents/SearchPlacesIntent.kt — OpenAssistant `maps_search_places`: offline POI text search (optional near/category), provider-clamped to ≤10 rows, name/address ≤120 chars; coordinates chain into directions/taxi tools+- com/vayunmathur/maps/intents/SavedPlacesIntent.kt — OpenAssistant `maps_get_saved_places`: saved (starred + listed) places, summaries only (name + coordinates), ≤10 rows ### intents/ — cross-app estimate/lookup clients - com/vayunmathur/maps/intents/RideEstimateClient.kt — launches taxi intents - com/vayunmathur/maps/intents/OrderLookupClient.kt — launches fooddelivery intents
maps/src/main/AndroidManifest.xml
diff --git a/maps/src/main/AndroidManifest.xml b/maps/src/main/AndroidManifest.xmlindex 65852429e1..22f542c7ce 100644--- a/maps/src/main/AndroidManifest.xml+++ b/maps/src/main/AndroidManifest.xml@@ -102,6 +102,18 @@ android:theme="@android:style/Theme.NoDisplay" android:permission="com.vayunmathur.maps.permissions.ACCESS_MAPS" /> + <activity+ android:name=".intents.SearchPlacesIntent"+ android:exported="true"+ android:theme="@android:style/Theme.NoDisplay"+ android:permission="com.vayunmathur.maps.permissions.ACCESS_MAPS" />++ <activity+ android:name=".intents.SavedPlacesIntent"+ android:exported="true"+ android:theme="@android:style/Theme.NoDisplay"+ android:permission="com.vayunmathur.maps.permissions.ACCESS_MAPS" />+ <service android:name=".service.NavigationService" android:foregroundServiceType="location"
maps/src/main/java/com/vayunmathur/maps/intents/SavedPlacesIntent.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/intents/SavedPlacesIntent.kt b/maps/src/main/java/com/vayunmathur/maps/intents/SavedPlacesIntent.ktnew file mode 100644index 0000000000..540072efd6--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/intents/SavedPlacesIntent.kt@@ -0,0 +1,60 @@+package com.vayunmathur.maps.intents++import com.vayunmathur.library.intents.maps.MAX_PLACE_RESULTS+import com.vayunmathur.library.intents.maps.MAX_PLACE_TEXT_CHARS+import com.vayunmathur.library.intents.maps.PlaceData+import com.vayunmathur.library.intents.maps.SavedPlacesQuery+import com.vayunmathur.library.util.AssistantIntent+import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.maps.data.SavedPlace+import com.vayunmathur.maps.data.SavedPlaceStore+import kotlinx.serialization.builtins.ListSerializer++/**+ * Assistant tool `maps_get_saved_places`: the user's saved places as summaries, exported as a+ * signature-guarded (`com.vayunmathur.maps.permissions.ACCESS_MAPS`) NoDisplay+ * [AssistantIntent].+ *+ * Provider-side caps: the limit is clamped to `1..[MAX_PLACE_RESULTS]` and every name to+ * [MAX_PLACE_TEXT_CHARS] chars. Summaries only — a [SavedPlace] holds just a name and+ * coordinates, which is all that crosses: no list names, no timestamps, nothing else the+ * store keeps. Reads the local DataStore only; never triggers a sync or a network call.+ */+class SavedPlacesIntent : AssistantIntent<SavedPlacesQuery, List<PlaceData>>(+ SavedPlacesQuery.serializer(),+ ListSerializer(PlaceData.serializer()),+) {+ override suspend fun performCalculation(input: SavedPlacesQuery): List<PlaceData> {+ val store = SavedPlaceStore(DataStoreUtils.getInstance(this))+ val all = (store.savedInitial() + store.listsInitial().values.flatten())+ .distinctBy { it.name to (it.lat to it.lon) }+ return savedPlacesToData(all, input.query, input.limit)+ }+}++/**+ * Pure provider mapping for [SavedPlacesIntent]: optional case-insensitive name filter,+ * clamped limit, capped names. Kept free of DataStore so the caps are unit-testable.+ */+internal fun savedPlacesToData(+ places: List<SavedPlace>,+ query: String?,+ limit: Int,+): List<PlaceData> {+ val needle = query?.trim()?.lowercase()?.takeIf { it.isNotEmpty() }+ val filtered = if (needle == null) {+ places+ } else {+ places.filter { it.name.lowercase().contains(needle) }+ }+ return filtered.take(clampPlaceLimit(limit, MAX_PLACE_RESULTS)).map { place ->+ PlaceData(+ id = "saved:${place.lat}:${place.lon}:${place.name.hashCode()}",+ name = place.name.take(MAX_PLACE_TEXT_CHARS),+ address = null,+ lat = place.lat,+ lng = place.lon,+ category = null,+ )+ }+}
maps/src/main/java/com/vayunmathur/maps/intents/SearchPlacesIntent.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/intents/SearchPlacesIntent.kt b/maps/src/main/java/com/vayunmathur/maps/intents/SearchPlacesIntent.ktnew file mode 100644index 0000000000..3d0e521f74--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/intents/SearchPlacesIntent.kt@@ -0,0 +1,80 @@+package com.vayunmathur.maps.intents++import com.vayunmathur.library.intents.maps.DEFAULT_PLACE_LIMIT+import com.vayunmathur.library.intents.maps.MAX_PLACE_RESULTS+import com.vayunmathur.library.intents.maps.MAX_PLACE_TEXT_CHARS+import com.vayunmathur.library.intents.maps.MapsPlaceSearchQuery+import com.vayunmathur.library.intents.maps.PlaceData+import com.vayunmathur.library.util.AssistantIntent+import com.vayunmathur.maps.data.PoiCategories+import com.vayunmathur.maps.data.PoiIndex+import kotlinx.serialization.builtins.ListSerializer++/**+ * Assistant tool `maps_search_places`: text search over the offline POI index, exported as a+ * signature-guarded (`com.vayunmathur.maps.permissions.ACCESS_MAPS`) NoDisplay+ * [AssistantIntent]. This is the front door that resolves a place name to the coordinates+ * `get_directions` / `get_ride_estimate` consume.+ *+ * Provider-side caps (the catalogue spec is model-facing text, not enforcement): the limit is+ * clamped to `1..[MAX_PLACE_RESULTS]`, the query to [MAX_QUERY_CHARS] chars, and every returned+ * name/address to [MAX_PLACE_TEXT_CHARS] chars. Reads the local index only — no network, no+ * Google calls, and no family location: the near bias is whatever coordinates the caller+ * already holds, validated to WGS84 ranges or ignored.+ */+class SearchPlacesIntent : AssistantIntent<MapsPlaceSearchQuery, List<PlaceData>>(+ MapsPlaceSearchQuery.serializer(),+ ListSerializer(PlaceData.serializer()),+) {+ override suspend fun performCalculation(input: MapsPlaceSearchQuery): List<PlaceData> {+ val query = input.query.trim().take(MAX_QUERY_CHARS)+ val category = input.category?.trim()?.takeIf { it.isNotEmpty() }+ // A category-only ask ("coffee near me") is itself a valid offline query: the index+ // answers purely categorical words with the nearest places of that kind.+ val effectiveQuery = query.ifEmpty { category.orEmpty() }+ if (effectiveQuery.isEmpty()) return emptyList()+ val limit = clampPlaceLimit(input.limit, DEFAULT_PLACE_LIMIT)+ PoiIndex.initialize(this)+ val records = runCatching {+ PoiIndex.searchByName(+ effectiveQuery,+ validLat(input.nearLat) ?: 0.0,+ validLng(input.nearLng) ?: 0.0,+ // Over-fetch when a category post-filter will drop rows, then re-cap.+ limit = if (category != null && query.isNotEmpty()) MAX_PLACE_RESULTS * 2 else limit,+ )+ }.getOrDefault(emptyList())+ return records+ .filter { category == null || query.isEmpty() ||+ PoiCategories.label(it.type).equals(category, ignoreCase = true) }+ .take(limit)+ .map { record ->+ record.toPlaceData(+ address = runCatching { PoiIndex.attributesAt(record.ordinal)?.address }.getOrNull(),+ )+ }+ }+}++/** Longest query the provider will search for; longer input is truncated, not rejected. */+private const val MAX_QUERY_CHARS = 200++/** Clamp a caller-supplied limit to `1..[MAX_PLACE_RESULTS]`; non-positive means default. */+internal fun clampPlaceLimit(limit: Int, default: Int): Int =+ if (limit <= 0) default else limit.coerceAtMost(MAX_PLACE_RESULTS)++/** A latitude is usable only inside WGS84 range; anything else is no bias, not an error. */+internal fun validLat(lat: Double?): Double? = lat?.takeIf { it in -90.0..90.0 }++/** A longitude is usable only inside WGS84 range; anything else is no bias, not an error. */+internal fun validLng(lng: Double?): Double? = lng?.takeIf { it in -180.0..180.0 }++/** Map one index record to the capped wire row; [address] comes from the attribute sidecar. */+internal fun PoiIndex.PoiRecord.toPlaceData(address: String?): PlaceData = PlaceData(+ id = "poi:$latE7:$lonE7:${name.hashCode()}",+ name = name.take(MAX_PLACE_TEXT_CHARS),+ address = address?.take(MAX_PLACE_TEXT_CHARS),+ lat = lat,+ lng = lon,+ category = PoiCategories.label(type),+)
maps/src/screenshotTest/kotlin/com/vayunmathur/maps/ui/FakeMapPreview.kt
diff --git a/maps/src/screenshotTest/kotlin/com/vayunmathur/maps/ui/FakeMapPreview.kt b/maps/src/screenshotTest/kotlin/com/vayunmathur/maps/ui/FakeMapPreview.ktnew file mode 100644index 0000000000..0fed6d84e3--- /dev/null+++ b/maps/src/screenshotTest/kotlin/com/vayunmathur/maps/ui/FakeMapPreview.kt@@ -0,0 +1,82 @@+package com.vayunmathur.maps.ui++import androidx.compose.foundation.Canvas+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.StrokeCap+import androidx.compose.ui.graphics.drawscope.Stroke++/**+ * SCREENSHOT-ONLY fake basemap scene.+ *+ * Lives in `src/screenshotTest`, so it never ships in the APK. The real map+ * is a Vulkan surface over the `.mamaps` archive, which Layoutlib cannot+ * render, so listing captures previously showed the real search / route /+ * navigation chrome over a flat empty surface. A still street-map scene+ * behind that real chrome is representative, so this draws one: fixed city+ * blocks, roads, a river, a park and a route line, all from fractions of+ * the canvas size — no tiles, no randomness, no time, byte-stable renders.+ * It is a synthetic illustration, not a claim that the real renderer ran.+ */+@Composable+internal fun FakeMapPreview(modifier: Modifier = Modifier) {+ Canvas(modifier) {+ val w = size.width+ val h = size.height++ // Land / block base.+ drawRect(Color(0xFFEDE8DD))+ // Park, lower left.+ drawRect(Color(0xFFC8E2B8), topLeft = Offset(w * 0.04f, h * 0.58f), size = Size(w * 0.30f, h * 0.34f))+ // River, diagonal band across the top right.+ val river = Path().apply {+ moveTo(w * 0.52f, 0f)+ lineTo(w, 0f)+ lineTo(w, h * 0.30f)+ lineTo(w * 0.78f, h * 0.38f)+ lineTo(w * 0.60f, h * 0.16f)+ close()+ }+ drawPath(river, Color(0xFFA9CCE8))++ // Minor streets: fixed grid.+ val minor = Color(0xFFFFFFFF)+ for (i in 1..6) {+ val x = w * i / 7f+ drawLine(minor, Offset(x, 0f), Offset(x + w * 0.04f, h), strokeWidth = w * 0.012f)+ }+ for (i in 1..8) {+ val y = h * i / 9f+ drawLine(minor, Offset(0f, y), Offset(w, y - h * 0.03f), strokeWidth = w * 0.012f)+ }+ // Major roads with casing.+ val roads = listOf(+ Offset(0f, h * 0.42f) to Offset(w, h * 0.34f),+ Offset(w * 0.30f, 0f) to Offset(w * 0.38f, h),+ Offset(0f, h * 0.72f) to Offset(w, h * 0.82f),+ )+ roads.forEach { (a, b) ->+ drawLine(Color(0xFFD8CFBC), a, b, strokeWidth = w * 0.045f)+ drawLine(Color(0xFFFFF6D8), a, b, strokeWidth = w * 0.034f)+ }++ // Route line the chrome is giving directions for.+ val route = Path().apply {+ moveTo(w * 0.16f, h * 0.92f)+ lineTo(w * 0.34f, h * 0.62f)+ lineTo(w * 0.36f, h * 0.40f)+ lineTo(w * 0.62f, h * 0.36f)+ lineTo(w * 0.80f, h * 0.22f)+ }+ drawPath(route, Color(0xFF2F6FDE), style = Stroke(width = w * 0.016f, cap = StrokeCap.Round))+ // Start dot + destination pin.+ drawCircle(Color(0xFF2F6FDE), radius = w * 0.014f, center = Offset(w * 0.16f, h * 0.92f))+ drawCircle(Color.White, radius = w * 0.008f, center = Offset(w * 0.16f, h * 0.92f))+ drawCircle(Color(0xFFE53935), radius = w * 0.020f, center = Offset(w * 0.80f, h * 0.22f))+ drawCircle(Color.White, radius = w * 0.009f, center = Offset(w * 0.80f, h * 0.22f))+ }+}
maps/src/test/java/com/vayunmathur/maps/intents/MapsPlaceIntentsTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/intents/MapsPlaceIntentsTest.kt b/maps/src/test/java/com/vayunmathur/maps/intents/MapsPlaceIntentsTest.ktnew file mode 100644index 0000000000..c18dd16bff--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/intents/MapsPlaceIntentsTest.kt@@ -0,0 +1,86 @@+package com.vayunmathur.maps.intents++import com.vayunmathur.library.intents.maps.MAX_PLACE_RESULTS+import com.vayunmathur.library.intents.maps.MAX_PLACE_TEXT_CHARS+import com.vayunmathur.maps.data.PoiIndex+import com.vayunmathur.maps.data.SavedPlace+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Provider-side caps for the maps place assistant intents: limits clamp to+ * `1..[MAX_PLACE_RESULTS]`, names/addresses truncate to [MAX_PLACE_TEXT_CHARS], and the saved+ * mapping returns summaries only. Pure helpers — no archive or DataStore needed.+ */+class MapsPlaceIntentsTest {++ @Test+ fun `place limit clamps to the hard cap`() {+ assertEquals(MAX_PLACE_RESULTS, clampPlaceLimit(999, 5))+ assertEquals(MAX_PLACE_RESULTS, clampPlaceLimit(MAX_PLACE_RESULTS + 1, 5))+ assertEquals(3, clampPlaceLimit(3, 5))+ assertEquals(1, clampPlaceLimit(1, 5))+ }++ @Test+ fun `non-positive place limit falls back to the default`() {+ assertEquals(5, clampPlaceLimit(0, 5))+ assertEquals(5, clampPlaceLimit(-4, 5))+ assertEquals(MAX_PLACE_RESULTS, clampPlaceLimit(0, MAX_PLACE_RESULTS))+ }++ @Test+ fun `near bias is validated to WGS84 ranges`() {+ assertEquals(37.8, validLat(37.8))+ assertEquals(-122.4, validLng(-122.4))+ assertNull(validLat(91.0))+ assertNull(validLat(-90.1))+ assertNull(validLng(181.0))+ assertNull(validLat(null))+ assertNull(validLng(null))+ }++ @Test+ fun `search rows truncate name and address and carry chainable coordinates`() {+ val longName = "N".repeat(300)+ val longAddress = "A".repeat(300)+ val record = PoiIndex.PoiRecord(+ latE7 = 378_000_000, lonE7 = -1_224_000_000, type = 1, name = longName,+ )+ val data = record.toPlaceData(longAddress)+ assertEquals(MAX_PLACE_TEXT_CHARS, data.name.length)+ assertEquals(MAX_PLACE_TEXT_CHARS, data.address?.length)+ assertEquals(37.8, data.lat, 1e-9)+ assertEquals(-122.4, data.lng, 1e-9)+ assertEquals("Cafe", data.category)+ assertTrue(data.id.startsWith("poi:"))+ }++ @Test+ fun `saved places cap count and name length and stay summaries only`() {+ val places = (1..25).map { SavedPlace("P".repeat(200) + it, it.toDouble(), (-it).toDouble()) }+ val out = savedPlacesToData(places, query = null, limit = 999)+ assertEquals(MAX_PLACE_RESULTS, out.size)+ assertTrue(out.all { it.name.length == MAX_PLACE_TEXT_CHARS })+ assertTrue(out.all { it.address == null && it.category == null })+ assertTrue(out.all { it.id.startsWith("saved:") })+ }++ @Test+ fun `saved places filter by name substring case-insensitively`() {+ val places = listOf(+ SavedPlace("Home", 1.0, 2.0),+ SavedPlace("home office", 3.0, 4.0),+ SavedPlace("Gym", 5.0, 6.0),+ )+ assertEquals(+ listOf("Home", "home office"),+ savedPlacesToData(places, "HOME", 10).map { it.name },+ )+ assertEquals(3, savedPlacesToData(places, " ", 10).size)+ assertEquals(3, savedPlacesToData(places, null, 10).size)+ assertEquals(1, savedPlacesToData(places, null, 1).size)+ }+}
openassistant/AGENTS.md
diff --git a/openassistant/AGENTS.md b/openassistant/AGENTS.mdindex 45dfa7132f..83ff0ec2ac 100644--- a/openassistant/AGENTS.md+++ b/openassistant/AGENTS.md@@ -70,7 +70,8 @@ _Install: ./install openassistant (dev by default)._ - com/vayunmathur/openassistant/platform/AssistantViewModel.kt - com/vayunmathur/openassistant/platform/MamlChatEngine.kt - com/vayunmathur/openassistant/platform/AssistantDeviceTools.kt-- com/vayunmathur/openassistant/platform/AssistantToolIntents.kt — cross-app intent back ends + host summarizers (incl. `summarizeHealthMetric`: one ≤300-char aggregate line for `health_get_metric_summary`, never record-level data)+- com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt — core cross-app intent back ends (notes/todo/contacts/calendar/family/music/email/clock/weather/maps incl. `maps_search_places`/`maps_get_saved_places`/taxi) with host summarizers that re-cap place rows (≤10, name/address ≤120 chars)+- com/vayunmathur/openassistant/platform/AssistantToolIntents.kt - com/vayunmathur/openassistant/platform/AudioRecorder.kt - com/vayunmathur/openassistant/platform/AssistantTools.kt - com/vayunmathur/openassistant/platform/AssistantCatalog.kt — A2UI component catalog + its prompt section
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 654207395a..7511accabb 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt@@ -56,7 +56,7 @@ private const val TOOL_DATA = """ get_notes|-|Get a list of all notes| 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 the user's open tasks from the todo app. Due times are epoch milliseconds; each task has an 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). Title may include 'tomorrow 6pm' or '#tag' when no due time is given.|title^S^1^~due^N^0^due time, epoch milliseconds~notes^S^0^~priority^N^0^priority, 1 (highest) to 4+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 a list of all contacts| create_contact|C|Create a new contact (requires confirmation)|name^S^1^~phone_number^S^1^@@ -76,34 +76,35 @@ make_phone_call|-|Make a phone call|recipient^S^1^ set_alarm|C|Set an alarm in the Clock app at a specific hour and minute (24-hour time) (requires confirmation).|hour^N^1^hour in 24-hour format, 0-23~minute^N^1^minute, 0-59~label^S^0^optional label for the alarm set_timer|C|Start a countdown timer in the Clock app for a number of seconds (requires confirmation).|seconds^N^1^timer length in seconds~label^S^0^optional label for the timer set_conversation_title|-|Set title of current conversation. Mandatory for first response|new_title^S^1^-get_weather|-|Get current weather at a latitude/longitude.|latitude^N^1^~longitude^N^1^-get_weather_by_name|-|Get current weather for a named place.|location^S^1^city or place name-health_get_metric_summary|-|Aggregate Health summary: latest, average, min/max, totals and counts only.|metric^S^1^steps, sleep, weight, heart_rate, hydration~range^S^0^today, 7d (default), 30d-render_ui|-|Render a rich UI card (A2UI) attached to your reply; prefer this over a ```a2ui fence, using the RICH UI types.|components_json^S^1^A2UI components as a JSON string~data_json^S^0^optional data JSON object-get_directions|-|Get Maps directions between two coordinates.|from_lat^N^1^origin latitude~from_lng^N^1^origin longitude~to_lat^N^1^destination latitude~to_lng^N^1^destination longitude~mode^S^0^drive (default), transit, walk, or bicycle-get_ride_estimate|-|Get a Taxi ride fare and pickup ETA estimate.|pickup_lat^N^1^pickup latitude~pickup_lng^N^1^pickup longitude~dest_lat^N^1^destination latitude~dest_lng^N^1^destination longitude~pickup_label^S^0^optional pickup label~dest_label^S^0^optional destination label+get_weather|-|Get the current weather conditions at a specific latitude/longitude.|latitude^N^1^~longitude^N^1^+get_weather_by_name|-|Get the current weather conditions for a named place (city, address, landmark).|location^S^1^city or place name+render_ui|-|Render a rich UI card (A2UI) attached to your reply; prefer this over a ```a2ui fence. components_json: {"components":[...]} (or a bare array) using the RICH UI types; data_json: optional initial data object.|components_json^S^1^A2UI components as a JSON string~data_json^S^0^optional initial data model as a JSON object string+get_directions|-|Get Maps directions between two coordinates: distance, duration, segment count.|from_lat^N^1^origin latitude~from_lng^N^1^origin longitude~to_lat^N^1^destination latitude~to_lng^N^1^destination longitude~mode^S^0^drive (default), transit, walk, or bicycle+maps_search_places|-|Search Maps places by name/category; returns lat/lng for get_directions/get_ride_estimate.|query^S^1^name or category~near_lat^N^0^latitude to search near~near_lng^N^0^longitude to search near~category^S^0^category e.g. Cafe~limit^N^0^max 1-10 (default 5)+maps_get_saved_places|-|Get user's saved Maps places (name and coordinates only).|query^S^0^name filter~limit^N^0^max 1-10 (default 10)+get_ride_estimate|-|Get a ride fare and pickup ETA estimate from the Taxi app.|pickup_lat^N^1^pickup latitude~pickup_lng^N^1^pickup longitude~dest_lat^N^1^destination latitude~dest_lng^N^1^destination longitude~pickup_label^S^0^optional pickup label~dest_label^S^0^optional destination label food_order_lookup|-|Check whether a named restaurant is orderable near a location via the FoodDelivery app.|name^S^1^restaurant name~lat^N^1^latitude~lng^N^1^longitude~address^S^0^optional address search_contacts|-|Search contacts by name or phone number substring (case-insensitive, max 10 results).|query^S^1^name or phone substring to search for-web_search|-|Search the web for current/external facts. Returns numbered results.|query^S^1^search query~count^N^0^optional result count, 1-10 (default 5)~kind^S^0^optional: text (default) or news+web_search|-|Search the web for current/external facts. Returns numbered results; web_read_result reads the best ones.|query^S^1^search query~count^N^0^optional result count, 1-10 (default 5)~kind^S^0^optional: text (default) 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.|query^S^0^name, number or text to search (blank lists recent)~limit^N^0^max conversations 1-50 (default 5)-get_conversation_messages|-|Get recent messages from a conversation by its thread_key.|thread_key^S^1^thread key like Sim:42 or WhatsApp:[email protected]~limit^N^0^max messages 1-100 (default 10)-draft_message|-|Show a message composer card. Sends nothing; the user edits and taps Send (confirmation first).|recipient_name^S^0^recipient display name~address^S^1^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^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_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-100 (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 the FoodDelivery cart with items_json: a JSON array like [{"itemId":1,"qty":2,"modifierIds":[]}]. Cart is re-validated and shown back; no order placed, no money moves.|merchant_id^N^1^merchant id the items belong to~items_json^S^1^JSON array of {itemId, qty, modifierIds}-food_prepare_order|-|Price the current cart (pickup or delivery) without creating an order; returns a summary for in-app confirmation.|merchant_id^N^1^merchant id of the cart~is_pickup^N^0^1 for pickup, 0 (default) for delivery~address_id^S^0^optional saved address id~tip_cents^N^0^optional tip in cents~promo^S^0^optional promo code-place_food_order|H|Show the order summary for the current cart. The user places and pays in FoodDelivery; this never creates an order or charges a card.|merchant_id^N^1^merchant id of the cart+food_set_cart|L|Replace the FoodDelivery cart with items_json: a JSON array like [{"itemId":1,"qty":2,"modifierIds":[]}]. The cart is re-validated and shown back to the user right away; no order is placed and no money moves.|merchant_id^N^1^merchant id the items belong to~items_json^S^1^JSON array of {itemId, qty, modifierIds}+food_prepare_order|-|Price the current cart (pickup or delivery) without creating an order; returns the summary the user confirms in FoodDelivery.|merchant_id^N^1^merchant id of the cart~is_pickup^N^0^1 for pickup, 0 (default) for delivery~address_id^S^0^optional saved address id~tip_cents^N^0^optional tip in cents~promo^S^0^optional promo code+place_food_order|H|Show the order summary for the current cart. The user places and pays for the order in the FoodDelivery app itself; this never creates an order or charges a card.|merchant_id^N^1^merchant id of the cart get_food_orders|-|Get the user's past FoodDelivery orders| search_products|-|Search the Shop catalog. Each result is one purchasable variant with its variant_id, store and exact price.|query^S^1^search text~limit^N^0^optional max results (default 5)-get_product_detail|-|Get one product's variants with exact prices and availability. Confirm the exact variant before adding to cart.|shop_domain^S^1^store domain from search_products~product_id^S^1^product id from search_products~variant_id^S^0^optional variant to price+get_product_detail|-|Get one product's variants with exact prices and availability. Confirm the exact variant with the user before adding it to the cart.|shop_domain^S^1^store domain from search_products~product_id^S^1^product id from search_products~variant_id^S^0^optional variant to price shop_get_cart|-|Get the current Shop cart, grouped by store| shop_add_to_cart|L|Add an exact variant to the Shop cart (re-verified first, shown back; no checkout).|shop_domain^S^1^store domain from search_products~variant_id^S^1^exact variant id from get_product_detail~quantity^N^0^quantity 1-99 (default 1) shop_remove_from_cart|L|Remove a variant from the Shop cart; the cart is shown back to the user.|variant_id^S^1^variant id to remove-start_shop_checkout|H|Show the per-store cart summary for one store. The user checks out in the Shop app itself; this never creates a checkout or charges anything.|shop_domain^S^1^store domain to check out+start_shop_checkout|H|Show the per-store cart summary for one store. The user checks out in the Shop app itself; this never creates a checkout or charges anything, and opening the cart is not a paid order.|shop_domain^S^1^store domain to check out get_shop_orders|-|Get the user's Shop order summaries| get_memories|-|Get a list of all memories| remove_memory|C|Remove a memory by its id (requires confirmation)|id^N^1^
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.ktindex 896ccbb32f..4b0f24cb95 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt@@ -9,7 +9,6 @@ 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.education.EducationProgressData import com.vayunmathur.library.intents.email.EmailData import com.vayunmathur.library.intents.email.EmailSearchQuery import com.vayunmathur.library.intents.findfamily.FamilyMemberData@@ -41,8 +40,9 @@ 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.screentime.ScreentimeUsageData-import com.vayunmathur.library.intents.screentime.ScreentimeUsageQuery+import com.vayunmathur.library.intents.maps.MapsPlaceSearchQuery+import com.vayunmathur.library.intents.maps.PlaceData+import com.vayunmathur.library.intents.maps.SavedPlacesQuery import com.vayunmathur.library.intents.shop.AddToCartRequest import com.vayunmathur.library.intents.shop.CartData as ShopCartData import com.vayunmathur.library.intents.shop.GetProductQuery@@ -55,8 +55,8 @@ 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.library.intents.health.HealthMetricQuery import com.vayunmathur.library.intents.health.HealthMetricSummaryData+import com.vayunmathur.library.intents.health.HealthMetricQuery import com.vayunmathur.openassistant.data.Memory import com.vayunmathur.openassistant.data.MemoryDao import kotlinx.datetime.TimeZone@@ -73,7 +73,7 @@ import kotlinx.serialization.serializer /** * Core cross-app intents (notes, todos, contacts, calendar, family, music,- * email, clock, weather, health, maps, taxi) backing [AssistantToolIntents]; the+ * email, clock, weather, maps, taxi) backing [AssistantToolIntents]; the * commerce/communicate intents live in the subclass so neither class * exceeds the TooManyFunctions limit. */@@ -147,14 +147,6 @@ internal abstract class AssistantCoreToolIntents( data, ) - suspend fun getEducationProgress(): EducationProgressData =- launchIntent<Unit, EducationProgressData>(- context,- "com.vayunmathur.education",- "com.vayunmathur.education.intents.GetProgressIntent",- Unit,- )- suspend fun getCalendarEvents(): String = launchIntent<Unit, List<EventData>>( context, "com.vayunmathur.calendar",@@ -248,16 +240,6 @@ internal abstract class AssistantCoreToolIntents( return result.error ?: result.toString() } - suspend fun getHealthMetricSummary(metric: String, range: String): String {- val result: HealthMetricSummaryData = launchIntent(- context,- "com.vayunmathur.health",- "com.vayunmathur.health.intents.GetMetricSummaryIntent",- HealthMetricQuery(metric, range.ifBlank { "7d" }),- )- return summarizeHealthMetric(result)- }- suspend fun getDirections( fromLat: Double, fromLng: Double,@@ -274,12 +256,25 @@ internal abstract class AssistantCoreToolIntents( return summarizeDirections(result) } - suspend fun getScreentimeUsage(limit: Int): ScreentimeUsageData = launchIntent(- context,- "com.vayunmathur.screentime",- "com.vayunmathur.screentime.intents.GetUsageIntent",- ScreentimeUsageQuery(limit),- )+ suspend fun searchPlaces(query: MapsPlaceSearchQuery): String {+ val result: List<PlaceData> = launchIntent(+ context,+ "com.vayunmathur.maps",+ "com.vayunmathur.maps.intents.SearchPlacesIntent",+ query,+ )+ return summarizePlaces(result, emptyMessage = "No places found")+ }++ suspend fun getSavedPlaces(query: SavedPlacesQuery): String {+ val result: List<PlaceData> = launchIntent(+ context,+ "com.vayunmathur.maps",+ "com.vayunmathur.maps.intents.SavedPlacesIntent",+ query,+ )+ return summarizePlaces(result, emptyMessage = "No saved places found")+ } suspend fun getRideEstimate( pickupLat: Double,@@ -302,4 +297,14 @@ internal abstract class AssistantCoreToolIntents( return summarizeRideEstimate(result) } ++ suspend fun getHealthMetricSummary(metric: String, range: String): String {+ val result: HealthMetricSummaryData = launchIntent(+ context,+ "com.vayunmathur.health",+ "com.vayunmathur.health.intents.GetMetricSummaryIntent",+ HealthMetricQuery(metric, range.ifBlank { "7d" }),+ )+ return summarizeHealthMetric(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 3be3e6627b..b8b5bb0fb6 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt@@ -40,6 +40,9 @@ 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.maps.MAX_PLACE_RESULTS+import com.vayunmathur.library.intents.maps.MAX_PLACE_TEXT_CHARS+import com.vayunmathur.library.intents.maps.PlaceData import com.vayunmathur.library.intents.shop.AddToCartRequest import com.vayunmathur.library.intents.shop.CartData as ShopCartData import com.vayunmathur.library.intents.shop.GetProductQuery@@ -51,8 +54,8 @@ 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.library.intents.health.HealthMetricSummaryData+import com.vayunmathur.library.intents.weather.WeatherData import com.vayunmathur.openassistant.data.Memory import com.vayunmathur.openassistant.data.MemoryDao import kotlinx.datetime.TimeZone@@ -86,7 +89,6 @@ internal class AssistantToolIntents(context: Context) : AssistantCoreToolIntents "com.vayunmathur.music" to "Music", "com.vayunmathur.email" to "Email", "com.vayunmathur.weather" to "Weather",- "com.vayunmathur.health" to "Health", "com.vayunmathur.clock" to "Clock", "com.vayunmathur.todo" to "Todo", "com.vayunmathur.maps" to "Maps",@@ -313,45 +315,22 @@ fun summarizeDirections(result: DirectionsResult): String { return "Route: $dist, $dur, ${result.segments.size} segment(s), ${result.polyline.size} point(s)" } -private const val HEALTH_SUMMARY_CHARS = 300--/** Formats an aggregate health value without trailing zeros (8000, 7.5, 72.25). */-fun formatHealthValue(value: Double): String =- if (value == value.toLong().toDouble()) {- value.toLong().toString()- } else {- "%.2f".format(value).trimEnd('0').trimEnd('.')- }- /**- * One-line aggregate health summary for the model. The DTO already carries- * aggregates only; this renders them (latest, average, min/max, total,- * counts) in a few hundred characters and never any record-level data.+ * Host-truncated place list for the model: one line per place with the coordinates a+ * follow-up `get_directions`/`get_ride_estimate` call needs. Re-caps count and text on the+ * host even though the provider already clamps — the wire is not trusted to stay capped. */-fun summarizeHealthMetric(summary: HealthMetricSummaryData): String {- if (summary.error != null) return "Error: health summary unavailable (${summary.error})".take(HEALTH_SUMMARY_CHARS)- val rangeLabel = when (summary.range) {- "today" -> "today"- "7d" -> "last 7 days"- "30d" -> "last 30 days"- else -> summary.range- }- if (summary.recordCount == 0) return "No ${summary.metric} data in the $rangeLabel."- val parts = mutableListOf<String>()- summary.latestValue?.let { parts += "latest ${formatHealthValue(it)} ${summary.unit}".trim() }- summary.average?.let {- val label = if (summary.cumulative) "avg/day" else "avg"- parts += "$label ${formatHealthValue(it)} ${summary.unit}".trim()- }- val min = summary.min- val max = summary.max- if (min != null && max != null) {- parts += "range ${formatHealthValue(min)}-${formatHealthValue(max)} ${summary.unit}".trim()+fun summarizePlaces(list: List<PlaceData>, emptyMessage: String = "No places found"): String =+ if (list.isEmpty()) {+ emptyMessage+ } else {+ list.take(MAX_PLACE_RESULTS).joinToString("\n") { p ->+ val address = p.address?.take(MAX_PLACE_TEXT_CHARS)?.takeIf { it.isNotBlank() }+ ?.let { " — $it" } ?: ""+ val category = p.category?.takeIf { it.isNotBlank() }?.let { " [$it]" } ?: ""+ "id=${p.id} ${p.name.take(MAX_PLACE_TEXT_CHARS)}$address$category lat=${p.lat} lng=${p.lng}"+ } }- summary.total?.let { parts += "total ${formatHealthValue(it)} ${summary.unit}".trim() }- parts += "${summary.recordCount} records over ${summary.daysWithData} day(s)"- return "${summary.metric} ($rangeLabel): ${parts.joinToString("; ")}".take(HEALTH_SUMMARY_CHARS)-} /** Short ride-estimate summary for the model. */ fun summarizeRideEstimate(result: RideEstimateResult): String =@@ -547,3 +526,45 @@ suspend inline fun <reified Input : Any> launchIntentU( ) if (stringOutput == "package $packageName doesn't exist") throw MissingAppException(packageName) }++private const val HEALTH_SUMMARY_CHARS = 300++fun formatHealthValue(value: Double): String =+ if (value == value.toLong().toDouble()) {+ value.toLong().toString()+ } else {+ "%.2f".format(value).trimEnd('0').trimEnd('.')+ }++/**+ * One-line aggregate health summary for the model. The DTO already carries+ * aggregates only; this renders them (latest, average, min/max, total,+ * counts) in a few hundred characters and never any record-level data.+ */++fun summarizeHealthMetric(summary: HealthMetricSummaryData): String {+ if (summary.error != null) return "Error: health summary unavailable (${summary.error})".take(HEALTH_SUMMARY_CHARS)+ val rangeLabel = when (summary.range) {+ "today" -> "today"+ "7d" -> "last 7 days"+ "30d" -> "last 30 days"+ else -> summary.range+ }+ if (summary.recordCount == 0) return "No ${summary.metric} data in the $rangeLabel."+ val parts = mutableListOf<String>()+ summary.latestValue?.let { parts += "latest ${formatHealthValue(it)} ${summary.unit}".trim() }+ summary.average?.let {+ val label = if (summary.cumulative) "avg/day" else "avg"+ parts += "$label ${formatHealthValue(it)} ${summary.unit}".trim()+ }+ val min = summary.min+ val max = summary.max+ if (min != null && max != null) {+ parts += "range ${formatHealthValue(min)}-${formatHealthValue(max)} ${summary.unit}".trim()+ }+ summary.total?.let { parts += "total ${formatHealthValue(it)} ${summary.unit}".trim() }+ parts += "${summary.recordCount} records over ${summary.daysWithData} day(s)"+ return "${summary.metric} ($rangeLabel): ${parts.joinToString("; ")}".take(HEALTH_SUMMARY_CHARS)+}++/** Short ride-estimate summary for the model. */
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 1c90330afd..fbd6d02602 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt@@ -169,6 +169,35 @@ class AssistantTools( ) } },+ "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(
openassistant/src/test/java/com/vayunmathur/openassistant/domain/PromptBudgetTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/PromptBudgetTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/PromptBudgetTest.ktindex b998ee4ecb..d3f41646e4 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/PromptBudgetTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/PromptBudgetTest.kt@@ -10,10 +10,10 @@ import kotlin.test.assertTrue /** * The system header (prompt + A2UI section + tool declarations) is prefilled- * on every cold turn and occupies context before any history. At v2.6.11 it- * was ~9.6k chars (25 tools); by HEAD it had grown to 26,483 chars (54 tools,- * measured with this same arithmetic), crowding out history and slowing- * every first turn. This pins the budget so it cannot silently regrow.+ * on every cold turn and occupies context before any history, so its size+ * crowds out history and slows every first turn. This pins the budget so it+ * cannot silently regrow: adding a tool means raising [MAX_HEADER_CHARS]+ * explicitly in the same change, as the two maps place tools did. */ class PromptBudgetTest { @@ -22,11 +22,11 @@ class PromptBudgetTest { val header = declared.length + InferenceService.DEFAULT_SYSTEM_PROMPT.length + AssistantCatalog.PROMPT_SECTION.length println("HEADER declared=${declared.length} prompt=${InferenceService.DEFAULT_SYSTEM_PROMPT.length} a2ui=${AssistantCatalog.PROMPT_SECTION.length} total=$header")- assertEquals(55, ASSISTANT_TOOL_SPECS.size)+ assertEquals(56, ASSISTANT_TOOL_SPECS.size) assertTrue(header <= MAX_HEADER_CHARS, "header=$header over budget $MAX_HEADER_CHARS") } companion object {- const val MAX_HEADER_CHARS = 24_500+ const val MAX_HEADER_CHARS = 25_600 } }
openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.ktindex eec6d828b9..5234d321e5 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt@@ -44,7 +44,7 @@ class AssistantToolsInvokeTest { assertEquals("Error: create_note needs title", call("create_note", "content" to "x")) assertTrue( call("set_timer", "seconds" to "abc").contains("must be a number"))- assertEquals(55, tools.declarations.size)+ assertEquals(56, tools.declarations.size) } @Test fun crossAppToolsReportMissingApps() {
openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.ktindex d44eb7985c..432534589c 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt@@ -14,7 +14,7 @@ class AssistantToolsTest { @Test fun namesAreUniqueSnakeCase() { val names = ASSISTANT_TOOL_SPECS.map { it.name }- assertEquals(55, names.size)+ assertEquals(56, names.size) assertEquals(names.size, names.toSet().size) for (spec in ASSISTANT_TOOL_SPECS) { assertTrue(snake.matches(spec.name), spec.name)@@ -58,6 +58,8 @@ class AssistantToolsTest { "create_todo.due", "create_todo.priority", "get_directions.from_lat", "get_directions.from_lng", "get_directions.to_lat", "get_directions.to_lng",+ "maps_search_places.near_lat", "maps_search_places.near_lng",+ "maps_search_places.limit", "maps_get_saved_places.limit", "get_ride_estimate.pickup_lat", "get_ride_estimate.pickup_lng", "get_ride_estimate.dest_lat", "get_ride_estimate.dest_lng", "food_order_lookup.lat", "food_order_lookup.lng",
openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.ktindex a0e178b6c2..30461c4481 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantToolIntentsTest.kt@@ -26,6 +26,7 @@ import kotlinx.coroutines.test.runTest import org.robolectric.Robolectric import com.vayunmathur.openassistant.platform.AssistantToolIntents import com.vayunmathur.openassistant.platform.MissingAppException+import com.vayunmathur.openassistant.platform.summarizePlaces import com.vayunmathur.openassistant.platform.summarizeConversations import com.vayunmathur.openassistant.platform.summarizeConversationMessages import com.vayunmathur.openassistant.platform.summarizeSendResult@@ -174,6 +175,23 @@ class AssistantToolIntentsTest { .contains("Google Voice")) } + @Test fun mapsPlaceSummariesCapCountAndText() {+ val long = "x".repeat(300)+ val places = (1..15).map {+ com.vayunmathur.library.intents.maps.PlaceData(+ id = "poi:$it", name = long, address = long, lat = 1.0, lng = 2.0, category = "Cafe")+ }+ val out = summarizePlaces(places)+ val lines = out.lines()+ assertEquals(10, lines.size)+ assertTrue(lines.all { it.length <= 10 + 120 + 3 + 120 + 8 + 40 }, out)+ assertTrue(out.contains("lat=1.0 lng=2.0"), out)+ assertEquals("No places found", summarizePlaces(emptyList()))+ assertEquals(+ "No saved places found",+ summarizePlaces(emptyList(), emptyMessage = "No saved places found"))+ }+ @Test fun foodToolsThrowMissingAppAndSummariesParse() = runTest { assertFailsWith<MissingAppException> { tools.findRestaurants("sushi", 1.0, 2.0, 5) } assertFailsWith<MissingAppException> { tools.getRestaurantMenu(7) }