Modern Apps git

← Modern-Apps.git

astronomy: add astronomy_get_tonight OpenAssistant tool

Commit
1cc7950333a073326a475742a89d9141b0438c45
Author
Vayun Mathur <[email protected]>
When
2026-12-02 04:38 UTC (4 days ago)
Parents
d75dccb
Implements the Astronomy row of docs/openassistant-intents-audit.md as revised by the task: a single tonight highlights summary instead of a list of sky objects, so no ephemeris table ever reaches the model.

- library/intents/astronomy: TonightQuery (optional latitude/longitude pair) and AstronomyTonightData (one summary string plus typed error), with MAX_TONIGHT_SUMMARY_CHARS = 600 enforced by both provider and host.
- astronomy/intents: TonightIntent, exported under the new signature-level ACCESS_ASTRONOMY permission (declared by OpenAssistant), validates the location pair (both-or-neither, finite, lat -90..90, lon -180..180) and falls back to Astronomy's saved observer location. TonightSummary builds the text from the existing domain code: RiseSetCalculator for Sun/Moon rise and set, LunarCalculator for phase and illumination, and PlanetaryCalculator for the brightest planets (max 3) above the horizon in the evening, over the bundled catalogs. Fully offline.
- openassistant: astronomy_get_tonight catalogue row (READ, optional latitude/longitude) and handler, a getAstronomyTonight back end, and summarizeAstronomyTonight host-capping the summary again. ToolArgs gains numberOrNull so absent optional numbers are distinguishable from 0.0. Adding the tool pushed the pinned prompt header over 24,500 chars, so the longest existing tool descriptions were trimmed (wording only) and the header is now 24,361; spec-count assertions move 54 to 55.

Tests pin the shape at every layer: TonightSummaryTest checks the single-line capped summary (Sun/Moon/planet shape, no newlines, no table), the 600-char cap, and location validation/fallback; the host summarizer test covers summary, error, blank and cap cases; AssistantTools tests cover the new numeric params and the missing-app path.

Verification (explicit):
- :library:lint green.
- :openassistant:lint and :openassistant:testDevUnitTest green (220 tests; one earlier full run flaked in InferenceServiceConcurrencyTest, which passes isolated and on rerun).
- :astronomy:testDevUnitTest: the new TonightSummaryTest (4 tests) passes, but the full task is NOT green at this base: SettingsScreenInteractionsTest 'sliders announce formatted values instead of percentages' fails (also isolated), in UI code this change does not touch.
- :astronomy:lint and :astronomy:lintVitalRelease are NOT green at this base: exactly 2 pre-existing RouteScreenshotCoverage errors in astronomy/Route.kt (ObjectDetail, HistoryDatePicker), also in code this change does not touch; the lint reports contain no findings in any new or changed file, and :astronomy:ktlintMainSourceSetCheck/:astronomy:ktlintTestSourceSetCheck pass for the new files. The parent should expect those two pre-existing failures when re-running release lint on merge.
- AGENTS.md updated for astronomy, library and openassistant.

Diff

astronomy/AGENTS.md
diff --git a/astronomy/AGENTS.md b/astronomy/AGENTS.mdindex 02bfc27d77..56a7aea28e 100644--- a/astronomy/AGENTS.md+++ b/astronomy/AGENTS.md@@ -4,7 +4,7 @@  _Install: ./install astronomy (dev by default)._ - Gradle: :astronomy / dir: astronomy/-- Package roots present: ui, data, domain, platform+- Package roots present: ui, data, domain, platform, intents - Entry files: MainActivity.kt, Route.kt, Navigation.kt - Deps: (none declared — bundled catalogs, Rust ephemeris) - Metadata: metadata_data/astronomy.md (present)@@ -13,7 +13,7 @@ _Install: ./install astronomy (dev by default)._ ## Overview **Purpose:** Offline AR night-sky viewer — sensor-tracked sky map, camera passthrough, time scrubber, bundled star/planet catalogs, rise/set search. 100% offline. **Key features:** `ui/SkyCanvas` + grid/art layers over `domain/projection/` (stereographic) fed by `domain/engine/` calculators (solar/lunar/planetary/rise-set/time) with a Rust core (`domain/AstronomyNative`); catalogs in `data/` validated at build time by `scripts/` generators.-**Entry points:** `Route` → `MainActivity.kt` → `Navigation.kt` → `ui/SkyMapPage.kt` → `platform/AstronomyViewModel.kt` → `domain/engine/TimeEngine.kt`.+**Entry points:** `Route` → `MainActivity.kt` → `Navigation.kt` → `ui/SkyMapPage.kt` → `platform/AstronomyViewModel.kt` → `domain/engine/TimeEngine.kt`. Assistant entry: `intents/TonightIntent` (OpenAssistant `astronomy_get_tonight`) returns one capped tonight summary (Sun/Moon times, Moon phase, brightest visible planets) computed by the domain calculators; DTOs in `library/intents/astronomy/`, signature-permission gated. **Gotchas:** Catalog data is generated (`scripts/` DB generators) — never hand-edit; sensor + location drive the sky, test with movement, not static.  ## Key files@@ -35,6 +35,9 @@ _Install: ./install astronomy (dev by default)._ - com/vayunmathur/astronomy/domain/projection/SkyProjection.kt - com/vayunmathur/astronomy/domain/projection/StereographicProjection.kt - com/vayunmathur/astronomy/domain/projection/ViewState.kt+### intents/ — assistant IPC+- com/vayunmathur/astronomy/intents/TonightIntent.kt — validated `TonightQuery` → capped `AstronomyTonightData` summary; explicit location pair or saved observer fallback+- com/vayunmathur/astronomy/intents/TonightSummary.kt — location validation + pure tonight-summary builder over the domain calculators ### platform/ — ViewModel + location - com/vayunmathur/astronomy/platform/AstronomyViewModel.kt - com/vayunmathur/astronomy/platform/AstronomyUiContract.kt
astronomy/src/main/AndroidManifest.xml
diff --git a/astronomy/src/main/AndroidManifest.xml b/astronomy/src/main/AndroidManifest.xmlindex b23193bc60..0ae057039c 100644--- a/astronomy/src/main/AndroidManifest.xml+++ b/astronomy/src/main/AndroidManifest.xml@@ -6,6 +6,10 @@     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />     <uses-permission android:name="android.permission.CAMERA" />     <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+    <permission+        android:name="com.vayunmathur.astronomy.permissions.ACCESS_ASTRONOMY"+        android:protectionLevel="signature" />+     <uses-feature android:name="android.hardware.camera" android:required="false" />     <uses-feature android:name="android.hardware.camera.autofocus" android:required="false" /> @@ -31,5 +35,11 @@                 <category android:name="android.intent.category.DEFAULT" />             </intent-filter>         </activity>++        <activity+            android:name=".intents.TonightIntent"+            android:exported="true"+            android:theme="@android:style/Theme.NoDisplay"+            android:permission="com.vayunmathur.astronomy.permissions.ACCESS_ASTRONOMY" />     </application> </manifest>
astronomy/src/main/java/com/vayunmathur/astronomy/intents/TonightIntent.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/intents/TonightIntent.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/intents/TonightIntent.ktnew file mode 100644index 0000000000..e88a3ab1cf--- /dev/null+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/intents/TonightIntent.kt@@ -0,0 +1,62 @@+package com.vayunmathur.astronomy.intents++import com.vayunmathur.astronomy.data.CatalogRepository+import com.vayunmathur.library.intents.astronomy.AstronomyTonightData+import com.vayunmathur.library.intents.astronomy.TonightQuery+import com.vayunmathur.library.util.AssistantIntent+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.serialization.InternalSerializationApi+import kotlinx.serialization.serializer+import java.time.ZoneId+import java.time.format.DateTimeFormatter+import kotlin.time.Clock+import kotlin.time.ExperimentalTime++/**+ * Headless activity behind OpenAssistant's `astronomy_get_tonight` tool.+ * Computes tonight's highlights (Sun/Moon times, Moon phase, brightest+ * visible planets) with the app's domain calculators over its bundled+ * catalogs and returns one short capped summary — never an ephemeris table.+ * Fully offline; reads only the saved observer location when the query+ * carries no explicit location.+ */+@OptIn(InternalSerializationApi::class, ExperimentalTime::class)+class TonightIntent :+    AssistantIntent<TonightQuery, AstronomyTonightData>(+        inputSerializer = serializer<TonightQuery>(),+        outputSerializer = serializer<AstronomyTonightData>(),+    ) {+    override suspend fun performCalculation(input: TonightQuery): AstronomyTonightData {+        val saved = DataStoreUtils.getInstance(this)+        val location =+            when (+                val resolved =+                    resolveTonightLocation(+                        input,+                        saved.getDouble(SAVED_LAT_KEY),+                        saved.getDouble(SAVED_LON_KEY),+                    )+            ) {+                is TonightLocationResult.Rejected -> return AstronomyTonightData(error = resolved.error)+                is TonightLocationResult.Resolved -> resolved+            }+        val catalog = CatalogRepository(this)+        catalog.loadAll()+        val formatter = DateTimeFormatter.ofPattern("HH:mm").withZone(ZoneId.systemDefault())+        val summary =+            buildTonightSummary(+                latDeg = location.latDeg,+                lonDeg = location.lonDeg,+                nowMillis = Clock.System.now().toEpochMilliseconds(),+                planets = catalog.planets,+                earth = catalog.earth,+                formatTime = { millis -> formatter.format(java.time.Instant.ofEpochMilli(millis)) },+            )+        return AstronomyTonightData(summary = summary)+    }++    private companion object {+        const val SAVED_LAT_KEY = "astro_lat"+        const val SAVED_LON_KEY = "astro_lon"+    }+}
astronomy/src/main/java/com/vayunmathur/astronomy/intents/TonightSummary.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/intents/TonightSummary.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/intents/TonightSummary.ktnew file mode 100644index 0000000000..9d08550f5f--- /dev/null+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/intents/TonightSummary.kt@@ -0,0 +1,158 @@+package com.vayunmathur.astronomy.intents++import com.vayunmathur.astronomy.data.model.OrbitalElements+import com.vayunmathur.astronomy.domain.engine.CoordinateTransforms+import com.vayunmathur.astronomy.domain.engine.LunarCalculator+import com.vayunmathur.astronomy.domain.engine.PlanetaryCalculator+import com.vayunmathur.astronomy.domain.engine.RiseSetCalculator+import com.vayunmathur.astronomy.domain.engine.TimeEngine+import com.vayunmathur.astronomy.domain.engine.toRad+import com.vayunmathur.library.intents.astronomy.MAX_TONIGHT_SUMMARY_CHARS+import com.vayunmathur.library.intents.astronomy.TonightQuery+import kotlin.math.floor+import kotlin.math.roundToInt+import kotlin.time.ExperimentalTime+import kotlin.time.Instant++/** Maximum number of planets named in the summary. */+internal const val MAX_TONIGHT_PLANETS = 3++/**+ * Resolves the observer location for a [TonightQuery]: the explicit pair when+ * supplied, otherwise the saved pair. Returns null with the reason in+ * [TonightLocationResult.error] when the input is incomplete, non-finite or+ * out of range, or when no location is available at all.+ */+internal sealed interface TonightLocationResult {+    data class Resolved(+        val latDeg: Double,+        val lonDeg: Double,+    ) : TonightLocationResult++    data class Rejected(+        val error: String,+    ) : TonightLocationResult+}++internal fun resolveTonightLocation(+    query: TonightQuery,+    savedLatDeg: Double?,+    savedLonDeg: Double?,+): TonightLocationResult {+    val lat = query.latitude+    val lon = query.longitude+    if ((lat == null) != (lon == null)) {+        return TonightLocationResult.Rejected("latitude and longitude must be provided together")+    }+    val resolvedLat = lat ?: savedLatDeg+    val resolvedLon = lon ?: savedLonDeg+    if (resolvedLat == null || resolvedLon == null) {+        return TonightLocationResult.Rejected("no location provided and no saved location in Astronomy")+    }+    if (!resolvedLat.isFinite() || !resolvedLon.isFinite()) {+        return TonightLocationResult.Rejected("latitude and longitude must be finite")+    }+    if (resolvedLat !in -90.0..90.0) {+        return TonightLocationResult.Rejected("latitude out of range (-90 to 90)")+    }+    if (resolvedLon !in -180.0..180.0) {+        return TonightLocationResult.Rejected("longitude out of range (-180 to 180)")+    }+    return TonightLocationResult.Resolved(resolvedLat, resolvedLon)+}++/** Caps [text] at [MAX_TONIGHT_SUMMARY_CHARS], marking any truncation. */+internal fun capTonightSummary(text: String): String =+    if (text.length <= MAX_TONIGHT_SUMMARY_CHARS) {+        text+    } else {+        text.take(MAX_TONIGHT_SUMMARY_CHARS - 3).trimEnd() + "..."+    }++/**+ * Builds tonight's highlights summary from the app's existing domain code:+ * [RiseSetCalculator] for Sun/Moon rise and set, [LunarCalculator] for phase,+ * and [PlanetaryCalculator] for the brightest planets above the horizon in+ * the evening. [formatTime] renders an epoch-millis instant for the user;+ * injecting it keeps this pure and deterministic in tests.+ */+@OptIn(ExperimentalTime::class)+internal fun buildTonightSummary(+    latDeg: Double,+    lonDeg: Double,+    nowMillis: Long,+    planets: List<OrbitalElements>,+    earth: OrbitalElements?,+    formatTime: (Long) -> String,+): String {+    val latRad = latDeg.toRad()+    val lonRad = lonDeg.toRad()+    val jdNow = TimeEngine.instantToJulianDate(Instant.fromEpochMilliseconds(nowMillis))+    val jd0 = floor(jdNow - 0.5) + 0.5++    fun formatJd(jd: Double?): String? =+        jd?.let { formatTime(TimeEngine.julianDateToInstant(it).toEpochMilliseconds()) }++    val sun = RiseSetCalculator.sunRiseSet(jd0, latRad, lonRad)+    val sunPart =+        when {+            sun.isCircumpolar -> "Sun does not set tonight (circumpolar)"+            sun.isNeverUp -> "Sun does not rise today (polar night)"+            else ->+                listOfNotNull(+                    formatJd(sun.riseJd)?.let { "sunrise $it" },+                    formatJd(sun.setJd)?.let { "sunset $it" },+                ).joinToString(", ").ifBlank { null }+        }++    // Evening reference: shortly after sunset, or late evening when the Sun+    // has no set time (polar day/night).+    val eveningJd = sun.setJd?.plus(1.5 / 24.0) ?: (jd0 + 21.0 / 24.0)+    val moon = LunarCalculator.calc(eveningJd)+    val moonRiseSet = RiseSetCalculator.moonRiseSet(jd0, latRad, lonRad)+    val moonTimes =+        listOfNotNull(+            formatJd(moonRiseSet.riseJd)?.let { "rises $it" },+            formatJd(moonRiseSet.setJd)?.let { "sets $it" },+        ).joinToString(", ")+    val moonPart =+        buildString {+            append("Moon: ")+            append(LunarCalculator.phaseName(moon.phase))+            append(", ")+            append((moon.illumination * 100).roundToInt())+            append("% lit")+            if (moonTimes.isNotBlank()) append(", $moonTimes")+        }++    val planetPart =+        visiblePlanetNames(planets, earth, eveningJd, latRad, lonRad)+            .takeIf { it.isNotEmpty() }+            ?.let { names -> "Visible planets: ${names.joinToString(", ")}" }++    val parts = listOfNotNull(sunPart?.let { "Sun: $it" }, moonPart, planetPart)+    return capTonightSummary("Tonight: " + parts.joinToString(". ") + ".")+}++/** Names of the brightest planets above the horizon at [jd], brightest first. */+@OptIn(ExperimentalTime::class)+private fun visiblePlanetNames(+    planets: List<OrbitalElements>,+    earth: OrbitalElements?,+    jd: Double,+    latRad: Double,+    lonRad: Double,+): List<String> {+    if (earth == null) return emptyList()+    val lst = TimeEngine.lstRad(jd, lonRad)+    return PlanetaryCalculator+        .calcAll(planets, earth, jd)+        .mapNotNull { result ->+            val magnitude = result.magnitude ?: return@mapNotNull null+            val altAz = CoordinateTransforms.raDecToAltAz(result.raDec, lst, latRad)+            if (altAz.altDeg <= 0.0) return@mapNotNull null+            result.name to magnitude+        }.sortedBy { it.second }+        .take(MAX_TONIGHT_PLANETS)+        .map { (name, magnitude) -> "$name (mag ${"%.1f".format(magnitude)})" }+}
astronomy/src/test/java/com/vayunmathur/astronomy/intents/TonightSummaryTest.kt
diff --git a/astronomy/src/test/java/com/vayunmathur/astronomy/intents/TonightSummaryTest.kt b/astronomy/src/test/java/com/vayunmathur/astronomy/intents/TonightSummaryTest.ktnew file mode 100644index 0000000000..f57f386e4a--- /dev/null+++ b/astronomy/src/test/java/com/vayunmathur/astronomy/intents/TonightSummaryTest.kt@@ -0,0 +1,87 @@+package com.vayunmathur.astronomy.intents++import com.vayunmathur.astronomy.data.BuiltInCatalogs+import com.vayunmathur.library.intents.astronomy.MAX_TONIGHT_SUMMARY_CHARS+import com.vayunmathur.library.intents.astronomy.TonightQuery+import java.time.Instant+import java.time.ZoneOffset+import java.time.format.DateTimeFormatter+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class TonightSummaryTest {+    private val formatter = DateTimeFormatter.ofPattern("HH:mm").withZone(ZoneOffset.UTC)+    private val formatTime: (Long) -> String = { formatter.format(Instant.ofEpochMilli(it)) }++    @Test+    fun summaryShapeIsSingleLineCappedText() {+        val earth = BuiltInCatalogs.orbital.first { it.id == "EARTH" }+        val summary =+            buildTonightSummary(+                latDeg = 40.7128,+                lonDeg = -74.0060,+                nowMillis = Instant.parse("2025-06-21T12:00:00Z").toEpochMilli(),+                planets = BuiltInCatalogs.orbital,+                earth = earth,+                formatTime = formatTime,+            )+        assertTrue(summary.startsWith("Tonight: Sun: sunrise "), summary)+        assertTrue(summary.contains("sunset "), summary)+        assertTrue(summary.contains("Moon: "), summary)+        assertTrue(summary.contains("% lit"), summary)+        assertFalse(summary.contains("\n"), summary)+        assertTrue(summary.length <= MAX_TONIGHT_SUMMARY_CHARS, "len=${summary.length}")+        // No ephemeris table: at most the capped highlight planets are named.+        val planetSegment = summary.substringAfter("Visible planets: ", "")+        if (planetSegment.isNotBlank()) {+            assertTrue(planetSegment.count { it == ',' } <= MAX_TONIGHT_PLANETS - 1, summary)+            assertTrue(planetSegment.contains("mag "), summary)+        }+    }++    @Test+    fun capTruncatesLongText() {+        val capped = capTonightSummary("x".repeat(MAX_TONIGHT_SUMMARY_CHARS + 500))+        assertEquals(MAX_TONIGHT_SUMMARY_CHARS, capped.length)+        assertTrue(capped.endsWith("..."))+        assertEquals("short", capTonightSummary("short"))+    }++    @Test+    fun locationValidationRejectsPartialAndOutOfRange() {+        assertTrue(+            resolveTonightLocation(TonightQuery(latitude = 10.0), null, null)+                is TonightLocationResult.Rejected,+        )+        assertTrue(+            resolveTonightLocation(TonightQuery(91.0, 0.0), null, null)+                is TonightLocationResult.Rejected,+        )+        assertTrue(+            resolveTonightLocation(TonightQuery(0.0, -181.0), null, null)+                is TonightLocationResult.Rejected,+        )+        assertTrue(+            resolveTonightLocation(TonightQuery(Double.NaN, 0.0), null, null)+                is TonightLocationResult.Rejected,+        )+        assertTrue(+            resolveTonightLocation(TonightQuery(), null, null)+                is TonightLocationResult.Rejected,+        )+    }++    @Test+    fun locationFallsBackToSavedAndExplicitWins() {+        val saved = resolveTonightLocation(TonightQuery(), 40.0, -74.0)+        assertEquals(TonightLocationResult.Resolved(40.0, -74.0), saved)+        val explicit = resolveTonightLocation(TonightQuery(1.0, 2.0), 40.0, -74.0)+        assertEquals(TonightLocationResult.Resolved(1.0, 2.0), explicit)+        assertEquals(+            TonightLocationResult.Resolved(-90.0, 180.0),+            resolveTonightLocation(TonightQuery(-90.0, 180.0), null, null),+        )+    }+}
library/AGENTS.md
diff --git a/library/AGENTS.md b/library/AGENTS.mdindex a365ba4057..3bb1307016 100644--- a/library/AGENTS.md+++ b/library/AGENTS.md@@ -32,6 +32,7 @@ - com/vayunmathur/library/intents/weather/WeatherData.kt - com/vayunmathur/library/intents/health/HealthMetricData.kt — aggregate-only health summary query/result (no record-level fields) - com/vayunmathur/library/intents/calculator/CalculatorData.kt+- com/vayunmathur/library/intents/astronomy/AstronomyData.kt — `TonightQuery`/`AstronomyTonightData` (capped summary, `MAX_TONIGHT_SUMMARY_CHARS`) ### util/ — navigation, intents, messenger, storage, games glue - com/vayunmathur/library/util/Navigation.kt — `NavKey` + `MainNavigation` + `rememberNavBackStack` - com/vayunmathur/library/util/NavigationBottomBar.kt
library/src/main/java/com/vayunmathur/library/intents/astronomy/AstronomyData.kt
diff --git a/library/src/main/java/com/vayunmathur/library/intents/astronomy/AstronomyData.kt b/library/src/main/java/com/vayunmathur/library/intents/astronomy/AstronomyData.ktnew file mode 100644index 0000000000..723e98e39b--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/intents/astronomy/AstronomyData.kt@@ -0,0 +1,35 @@+package com.vayunmathur.library.intents.astronomy++import kotlinx.serialization.Serializable++/** Maximum characters in a tonight summary; provider and host both enforce it. */+const val MAX_TONIGHT_SUMMARY_CHARS = 600++/**+ * Input for Astronomy's `TonightIntent`: an optional observer location.+ *+ * Both coordinates must be supplied together, or neither (the Astronomy app+ * then uses its saved observer location). Ranges are validated provider-side:+ * latitude in [-90, 90], longitude in [-180, 180], both finite.+ */+@Serializable+data class TonightQuery(+    val latitude: Double? = null,+    val longitude: Double? = null,+)++/**+ * Tonight's visible-highlights summary from the Astronomy app.+ *+ * [summary] is short capped text (at most [MAX_TONIGHT_SUMMARY_CHARS]+ * characters): sunset/sunrise, Moon phase and rise/set, and the brightest+ * visible planets. It is deliberately not an ephemeris table — no per-object+ * rise/set/altitude rows cross the wire. [error] is non-null only when no+ * summary could be computed (invalid or missing location); [summary] is+ * empty in that case.+ */+@Serializable+data class AstronomyTonightData(+    val summary: String = "",+    val error: String? = null,+)
openassistant/AGENTS.md
diff --git a/openassistant/AGENTS.md b/openassistant/AGENTS.mdindex ab9886eca1..60c7b3c9a5 100644--- a/openassistant/AGENTS.md+++ b/openassistant/AGENTS.md@@ -73,6 +73,8 @@ _Install: ./install openassistant (dev by default)._ - 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/AssistantCoreToolIntents.kt — core cross-app intent back ends (notes/todo/contacts/calendar/family/music/email/clock/weather/calculator/maps/taxi)+- com/vayunmathur/openassistant/platform/AssistantToolIntents.kt — includes `summarizeAstronomyTonight` (host cap for `astronomy_get_tonight`)+- com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt — core cross-app launches incl. Astronomy `TonightIntent` - 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/AndroidManifest.xml
diff --git a/openassistant/src/main/AndroidManifest.xml b/openassistant/src/main/AndroidManifest.xmlindex f81fbe8614..0c3a462ec9 100644--- a/openassistant/src/main/AndroidManifest.xml+++ b/openassistant/src/main/AndroidManifest.xml@@ -37,6 +37,7 @@     <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />      <uses-permission android:name="android.permission.RECORD_AUDIO" />+    <uses-permission android:name="com.vayunmathur.astronomy.permissions.ACCESS_ASTRONOMY" />      <permission         android:name="com.vayunmathur.openassistant.permission.ACCESS_INFERENCE"
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 39ee27fbc3..eccca3e5d3 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt@@ -73,22 +73,22 @@ get_app_list|-|Get installed apps (max 100)| open_app|-|Open an app given its package id|package_id^S^1^package id 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/minute 24h (confirmation).|hour^N^1^hour 0-23 (24h)~minute^N^1^minute 0-59~label^S^0^optional label-set_timer|C|Start Clock countdown timer in seconds (confirmation).|seconds^N^1^timer length in seconds~label^S^0^optional label for the timer+set_alarm|C|Set Clock alarm at hour/minute 24h (confirmation).|hour^N^1^hour 0-23 (24h)~minute^N^1^minute 0-59~label^S^0^label+set_timer|C|Start Clock countdown timer in seconds (confirmation).|seconds^N^1^timer length in seconds~label^S^0^label for the timer set_conversation_title|-|Set current conversation title. Mandatory first response.|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 place.|location^S^1^place name screentime_get_usage|-|Today's screen time: total + top 5 apps.| render_ui|-|Render rich UI card (A2UI) with reply; prefer over ```a2ui fence. components_json {"components":[...]} or array; data_json optional.|components_json^S^1^A2UI components JSON~data_json^S^0^data JSON get_directions|-|Directions between coordinates: distance, duration.|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 (default), transit, walk, or bicycle-maps_search_places|-|Search Maps places; returns lat/lng.|query^S^1^name or category~near_lat^N^0^near latitude~near_lng^N^0^near longitude~category^S^0^e.g. Cafe~limit^N^0^1-10 (default 5)-maps_get_saved_places|-|Saved Maps places (name + coordinates).|query^S^0^filter~limit^N^0^max 1-10 (default 10)+maps_search_places|-|Search Maps places; returns lat/lng.|query^S^1^name or category~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 + coordinates).|query^S^0^filter~limit^N^0^max 1-10 (def 10) get_ride_estimate|-|Taxi fare + pickup 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 label~dest_label^S^0^dest label-food_order_lookup|-|Check if a named restaurant is orderable nearby (FoodDelivery).|name^S^1^name~lat^N^1^latitude~lng^N^1^longitude~address^S^0^optional address+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 expression via Calculator (functions, pi/e, units 5km+2mi).|expression^S^1^expression (200 chars) calculator_convert_unit|-|Convert a value between units via Calculator (incl. currency like USD).|value^N^1^value~from_unit^S^1^from: km, ft, degC, USD~to_unit^S^1^to: mi, m, degF, 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 (default 5)~kind^S^0^text (default) or news+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 (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 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)@@ -102,7 +102,7 @@ food_set_cart|L|Replace FoodDelivery cart with items_json [{itemId,qty,modifierI food_prepare_order|-|Price cart (pickup/delivery); no order created.|merchant_id^N^1^merchant id~is_pickup^N^0^1 pickup, 0 delivery (default)~address_id^S^0^address id~tip_cents^N^0^tip (cents)~promo^S^0^promo place_food_order|H|Show the current cart's order summary. The user places and pays in FoodDelivery itself; this never creates an order or charges a card.|merchant_id^N^1^merchant id 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^max (default 5)+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^max (def 5) get_product_detail|-|One product's variants (prices, availability). Confirm variant before adding to cart.|shop_domain^S^1^domain~product_id^S^1^product id~variant_id^S^0^variant to price shop_get_cart|-|Get the current Shop cart, grouped by store| shop_add_to_cart|L|Add exact variant to Shop cart (re-verified; no checkout).|shop_domain^S^1^domain~variant_id^S^1^exact variant id~quantity^N^0^qty 1-99 (default 1)@@ -118,4 +118,5 @@ news_read_article|-|Read a News article (3000 chars/page)|url^S^1^from a news re 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 remove_memory|C|Remove a memory by its id (requires confirmation)|id^N^1^ add_to_memory|-|Add a new memory to the list of memories|content^S^1^+astronomy_get_tonight|-|Tonight: sunset, Moon, planets.|latitude^N^0^~longitude^N^0^ """
openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolCalls.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolCalls.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolCalls.ktindex 01c16b9ef5..258ab193b4 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolCalls.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ToolCalls.kt@@ -43,6 +43,7 @@ data class ToolSpec( class ToolArgs(private val values: Map<String, Any>) {     fun string(name: String, default: String = ""): String = values[name] as? String ?: default     fun number(name: String): Double = values[name] as? Double ?: 0.0+    fun numberOrNull(name: String): Double? = values[name] as? Double }  /** Contract for tool args result. */
openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantAggregateSummarizers.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantAggregateSummarizers.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantAggregateSummarizers.ktindex 3e05b35a1d..64f611ca8e 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantAggregateSummarizers.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantAggregateSummarizers.kt@@ -1,5 +1,7 @@ package com.vayunmathur.openassistant.platform +import com.vayunmathur.library.intents.astronomy.AstronomyTonightData+import com.vayunmathur.library.intents.astronomy.MAX_TONIGHT_SUMMARY_CHARS import com.vayunmathur.library.intents.education.EducationProgressData import com.vayunmathur.library.intents.health.HealthMetricSummaryData import com.vayunmathur.library.intents.news.NewsArticleExcerptData@@ -122,3 +124,10 @@ fun summarizeNewsArticle(data: NewsArticleExcerptData): String {     val more = data.nextOffset?.let { "\n(next page: news_read_article offset=$it)" } ?: ""     return "${data.title.take(160)}$byline\n${data.excerpt.take(3_000)}$more" }++fun summarizeAstronomyTonight(result: AstronomyTonightData): String =+    when {+        result.error != null -> "Error: ${result.error}"+        result.summary.isBlank() -> "No astronomy summary available"+        else -> result.summary.take(MAX_TONIGHT_SUMMARY_CHARS)+    }
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 c8a7c20ff1..eef47a2c0a 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt@@ -76,6 +76,8 @@ import kotlinx.serialization.serializer import com.vayunmathur.library.intents.screentime.ScreentimeUsageData import com.vayunmathur.library.intents.screentime.ScreentimeUsageQuery import com.vayunmathur.library.intents.education.EducationProgressData+import com.vayunmathur.library.intents.astronomy.AstronomyTonightData+import com.vayunmathur.library.intents.astronomy.TonightQuery   /**@@ -363,4 +365,13 @@ internal abstract class AssistantCoreToolIntents(             Unit,         ) +    suspend fun getAstronomyTonight(latitude: Double?, longitude: Double?): String {+        val result: AstronomyTonightData = launchIntent(+            context,+            "com.vayunmathur.astronomy",+            "com.vayunmathur.astronomy.intents.TonightIntent",+            TonightQuery(latitude, longitude),+        )+        return summarizeAstronomyTonight(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 79f7189f19..e3b0c8dcec 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt@@ -78,6 +78,8 @@ import com.vayunmathur.library.intents.news.NewsSearchQuery import com.vayunmathur.library.intents.news.NewsStoryData import com.vayunmathur.library.intents.news.NewsStoryQuery import com.vayunmathur.library.intents.news.NewsTopQuery+import com.vayunmathur.library.intents.astronomy.AstronomyTonightData+import com.vayunmathur.library.intents.astronomy.MAX_TONIGHT_SUMMARY_CHARS  private const val CONVERSATION_SNIPPET_CHARS = 80 private const val MESSAGE_BODY_CHARS = 200@@ -137,6 +139,11 @@ internal class AssistantToolIntents(context: Context) : AssistantCoreToolIntents             "com.vayunmathur.fooddelivery" to "FoodDelivery",             "com.vayunmathur.communicate" to "Communicate",             "com.vayunmathur.shop" to "Shop",+            "com.vayunmathur.astronomy" to "Astronomy",+            "com.vayunmathur.education" to "Education",+            "com.vayunmathur.health" to "Health",+            "com.vayunmathur.news" to "News",+            "com.vayunmathur.screentime" to "Screentime",         )          fun getMissingAppMessage(packageName: String): String {
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 df5a17d951..d85104c790 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt@@ -218,6 +218,11 @@ class AssistantTools(                 )             }         },+        "astronomy_get_tonight" to { a ->+            intents.runTool {+                intents.getAstronomyTonight(a.numberOrNull("latitude"), a.numberOrNull("longitude"))+            }+        },         "get_directions" to { a ->             intents.runTool {                 intents.getDirections(
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 a437f6dbb0..3c6fee3846 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/PromptBudgetTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/PromptBudgetTest.kt@@ -22,7 +22,7 @@ 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(65, ASSISTANT_TOOL_SPECS.size)+        assertEquals(66, ASSISTANT_TOOL_SPECS.size)         assertTrue(header <= MAX_HEADER_CHARS, "header=$header over budget $MAX_HEADER_CHARS")     } 
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 361599d0c3..8368d97acf 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(65, tools.declarations.size)+        assertEquals(66, tools.declarations.size)     }      @Test fun crossAppToolsReportMissingApps() {@@ -73,6 +73,10 @@ class AssistantToolsInvokeTest {             call("get_weather", "latitude" to "1.5", "longitude" to "2.5")                 .startsWith("The Weather app is required"))         assertTrue(call("get_weather_by_name", "location" to "Lisbon").startsWith("The Weather app"))+        assertTrue(call("astronomy_get_tonight").startsWith("The Astronomy app is required"))+        assertTrue(+            call("astronomy_get_tonight", "latitude" to "40.7", "longitude" to "-74.0")+                .startsWith("The Astronomy app is required"))         assertTrue(             call(                 "get_directions",
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 8201df0a5c..6d1856dc41 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(65, names.size)+        assertEquals(66, names.size)         assertEquals(names.size, names.toSet().size)         for (spec in ASSISTANT_TOOL_SPECS) {             assertTrue(snake.matches(spec.name), spec.name)@@ -72,6 +72,8 @@ class AssistantToolsTest {                 "search_products.limit", "shop_add_to_cart.quantity",                 "calculator_convert_unit.value",                 "news_search_headlines.limit", "news_top_stories.limit", "news_read_article.offset",+                "astronomy_get_tonight.latitude", "astronomy_get_tonight.longitude",+                "astronomy_get_tonight.latitude", "astronomy_get_tonight.longitude",             ),             numeric,         )
openassistant/src/test/java/com/vayunmathur/openassistant/util/SummarizeNewToolsTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/SummarizeNewToolsTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/SummarizeNewToolsTest.ktindex 4338ce39e4..fdd2a164e8 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/util/SummarizeNewToolsTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/SummarizeNewToolsTest.kt@@ -35,6 +35,7 @@ import com.vayunmathur.openassistant.platform.summarizeSendResult import com.vayunmathur.openassistant.platform.summarizeDirections import com.vayunmathur.openassistant.platform.summarizeRideEstimate import com.vayunmathur.openassistant.platform.summarizeOrderLookup+import com.vayunmathur.openassistant.platform.summarizeAstronomyTonight import com.vayunmathur.openassistant.platform.parseSetCartItems  /**@@ -108,6 +109,24 @@ class SummarizeNewToolsTest {         assertEquals(10, summarizeFoodOrders(many).lines().size)     } +    @Test fun astronomyTonightSummarizesCapsAndErrors() {+        val data = com.vayunmathur.library.intents.astronomy.AstronomyTonightData(+            summary = "Tonight: sunset 20:00. Moon: Full Moon, 100% lit.")+        assertEquals(data.summary, summarizeAstronomyTonight(data))+        assertEquals(+            "Error: latitude out of range (-90 to 90)",+            summarizeAstronomyTonight(+                com.vayunmathur.library.intents.astronomy.AstronomyTonightData(+                    error = "latitude out of range (-90 to 90)")),+        )+        assertEquals("No astronomy summary available", summarizeAstronomyTonight(+            com.vayunmathur.library.intents.astronomy.AstronomyTonightData()))+        val long = summarizeAstronomyTonight(+            com.vayunmathur.library.intents.astronomy.AstronomyTonightData(+                summary = "x".repeat(2_000)))+        assertEquals(com.vayunmathur.library.intents.astronomy.MAX_TONIGHT_SUMMARY_CHARS, long.length)+    }+     @Test fun parseSetCartItemsAcceptsOnlyTheDocumentedShape() {         assertEquals(             listOf(