health: add health_get_metric_summary OpenAssistant tool
- Commit
6827508e7f4f3b330cfe772cd4b9e89170e1e43e- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-02 04:28 UTC (4 days ago)
- Parents
5982970
Implements the Health row of docs/openassistant-intents-audit.md: OpenAssistant can now answer aggregate health questions (steps, sleep, weight, heart rate, hydration and the other dashboard metrics) over a recent window without any raw health record ever leaving the Health app. - library/intents/health: HealthMetricQuery (metric + range today/7d/30d) and HealthMetricSummaryData carrying aggregates only - latest, average, min/max, total, recordCount and daysWithData, with no record ids, per-record timestamps/values or lists of any kind. - health/intents/GetMetricSummaryIntent: validated provider contract (unknown metric/range and the dual-series blood pressure metric return a typed error DTO), half-open local-calendar windows, and SQL aggregates only - new avgInRange/countInRange DAO queries plus the existing sum/min/ max/daily-bucket/last-record reads, display-scaled (height m to cm) and rounded. Exported under the new signature-level ACCESS_HEALTH permission, which OpenAssistant declares. - openassistant: health_get_metric_summary catalogue row (READ) and handler, a getHealthMetricSummary back end, and a host summarizer rendering one line of at most 300 chars. Adding the tool pushed the pinned prompt header over its 24,500-char budget, so the longest existing tool descriptions were trimmed (wording only, no behaviour change) to bring it back under; the spec-count assertions move 54 to 55. Tests pin the aggregate-only contract at every layer: DTO JSON keys, provider validation/aggregation/scaling/window maths, and the host summarizer output. AGENTS.md files updated for health, library and openassistant. Verified: :health:lint, :health:lintVitalRelease and :health:testDevUnitTest green; :openassistant:lint, :openassistant:lintVitalRelease and :openassistant:testDevUnitTest green (including PromptBudgetTest); :library:lint and :library:testDebugUnitTest green.
Diff
health/AGENTS.md
diff --git a/health/AGENTS.md b/health/AGENTS.mdindex 7e077f9b36..5ed16a2153 100644--- a/health/AGENTS.md+++ b/health/AGENTS.md@@ -4,7 +4,7 @@ _Install: ./install health (dev by default)._ - Gradle: :health / dir: health/-- Package roots present: ui, data, domain, platform, service, notifications+- Package roots present: ui, data, domain, platform, service, notifications, intents - Entry files: MainActivity.kt, Route.kt (sealed nav destinations incl. DialogPage dialog routes), Navigation.kt + ui/NavigationEntries.kt - Deps: :library:room - Metadata: metadata_data/health.md (present)@@ -61,6 +61,8 @@ _Install: ./install health (dev by default)._ - com/vayunmathur/health/platform/DoseActionReceiver.kt - com/vayunmathur/health/platform/DoseReminderActivity.kt - com/vayunmathur/health/platform/HealthBootReceiver.kt+### intents/ — assistant IPC+- com/vayunmathur/health/intents/GetMetricSummaryIntent.kt — OpenAssistant `health_get_metric_summary`: validated metric/range over a recent local-calendar window, SQL aggregates only (latest/average/min/max/total/count via `HealthRepository` aggregate queries); no raw records cross in the `library.intents.health` DTO ### notifications/ + service/ — channels and dose sound - com/vayunmathur/health/notifications/DoseNotification.kt - com/vayunmathur/health/notifications/MedicationChannels.kt
health/src/main/AndroidManifest.xml
diff --git a/health/src/main/AndroidManifest.xml b/health/src/main/AndroidManifest.xmlindex 91a8b1681c..47623b59c1 100644--- a/health/src/main/AndroidManifest.xml+++ b/health/src/main/AndroidManifest.xml@@ -8,6 +8,12 @@ <!-- Sensors permission at install instead of auto-granting it. --> <uses-permission android:name="com.vayunmathur.permission.SENSORS_OPTOUT" /> + <!-- Assistant tool (health_get_metric_summary) for openassistant.+ Signature-level: only apps signed with the Modern Apps key can call. -->+ <permission+ android:name="com.vayunmathur.health.permissions.ACCESS_HEALTH"+ android:protectionLevel="signature" />+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" tools:node="remove" /> @@ -147,6 +153,12 @@ android:resource="@xml/file_paths" /> </provider> + <activity+ android:name=".intents.GetMetricSummaryIntent"+ android:exported="true"+ android:theme="@android:style/Theme.NoDisplay"+ android:permission="com.vayunmathur.health.permissions.ACCESS_HEALTH" />+ <activity android:name=".platform.DoseReminderActivity" android:showWhenLocked="true"
health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt b/health/src/main/java/com/vayunmathur/health/data/HealthRepository.ktindex bae2ef7ae5..7b7e36eacd 100644--- a/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt+++ b/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt@@ -40,6 +40,16 @@ class HealthRepository private constructor(context: Context) : startTime: kotlin.time.Instant, endTime: kotlin.time.Instant, ): Flow<NutritionData> = dao.sumNutritionInRange(type, startTime, endTime)+ suspend fun avgInRange(+ type: RecordType,+ startTime: kotlin.time.Instant,+ endTime: kotlin.time.Instant,+ ): Double? = dao.avgInRange(type, startTime, endTime)+ suspend fun countInRange(+ type: RecordType,+ startTime: kotlin.time.Instant,+ endTime: kotlin.time.Instant,+ ): Int = dao.countInRange(type, startTime, endTime) fun minInRange( type: RecordType, startTime: kotlin.time.Instant,
health/src/main/java/com/vayunmathur/health/data/Record.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/Record.kt b/health/src/main/java/com/vayunmathur/health/data/Record.ktindex 2de3424e99..3a2612d2a8 100644--- a/health/src/main/java/com/vayunmathur/health/data/Record.kt+++ b/health/src/main/java/com/vayunmathur/health/data/Record.kt@@ -236,7 +236,10 @@ interface HealthDao { startTime: kotlin.time.Instant, endTime: kotlin.time.Instant, ): Flow<NutritionData>-+ @Query("SELECT AVG(value) FROM Record WHERE type = :type AND startTime >= :startTime AND startTime < :endTime")+ suspend fun avgInRange(type: RecordType, startTime: kotlin.time.Instant, endTime: kotlin.time.Instant): Double?+ @Query("SELECT COUNT(*) FROM Record WHERE type = :type AND startTime >= :startTime AND startTime < :endTime")+ suspend fun countInRange(type: RecordType, startTime: kotlin.time.Instant, endTime: kotlin.time.Instant): Int @Query("SELECT MIN(value) FROM Record WHERE type = :type AND startTime >= :startTime AND startTime < :endTime") fun minInRange(type: RecordType, startTime: kotlin.time.Instant, endTime: kotlin.time.Instant): Flow<Double?> @Query("SELECT MAX(value) FROM Record WHERE type = :type AND startTime >= :startTime AND startTime < :endTime")
health/src/main/java/com/vayunmathur/health/intents/GetMetricSummaryIntent.kt
diff --git a/health/src/main/java/com/vayunmathur/health/intents/GetMetricSummaryIntent.kt b/health/src/main/java/com/vayunmathur/health/intents/GetMetricSummaryIntent.ktnew file mode 100644index 0000000000..0d8ba84631--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/intents/GetMetricSummaryIntent.kt@@ -0,0 +1,204 @@+package com.vayunmathur.health.intents++import com.vayunmathur.health.data.HealthRepository+import com.vayunmathur.health.data.RecordType+import com.vayunmathur.health.ui.HealthMetricConfig+import com.vayunmathur.library.intents.health.HealthMetricQuery+import com.vayunmathur.library.intents.health.HealthMetricSummaryData+import com.vayunmathur.library.util.AssistantIntent+import java.time.LocalDate+import java.time.ZoneId+import kotlin.math.roundToLong+import kotlinx.coroutines.flow.first+import kotlinx.serialization.InternalSerializationApi+import kotlinx.serialization.serializer++/** One dashboard metric as the assistant may query it. */+internal data class HealthMetricSpec(+ val key: String,+ val recordType: RecordType,+ val unit: String,+ /** Cumulative metrics sum per day (steps, sleep); point metrics average recorded values. */+ val cumulative: Boolean,+ /** Stored-to-display scale (height is stored in metres, displayed in centimetres). */+ val scale: Double = 1.0,+)++/**+ * Every dashboard metric except blood pressure, which is a dual systolic /+ * diastolic series and has no single aggregate value. Keys are the+ * lower-cased [HealthMetricConfig] names (`steps`, `heart_rate`, …).+ */+internal val HEALTH_METRIC_SPECS: List<HealthMetricSpec> =+ HealthMetricConfig.entries+ .filter { it != HealthMetricConfig.BLOOD_PRESSURE }+ .map { config ->+ HealthMetricSpec(+ key = config.name.lowercase(),+ recordType = config.recordType,+ unit = config.unit,+ cumulative = !config.isLineChart,+ scale = if (config.recordType == RecordType.Height) 100.0 else 1.0,+ )+ }++private val HEALTH_METRIC_ALIASES = mapOf(+ "calories" to "energy",+ "calories_total" to "energy",+ "total_calories" to "energy",+ "exercise" to "exercise_duration",+)++/** Normalises a model-supplied metric name to a [HealthMetricSpec], or null when unknown. */+internal fun parseHealthMetric(raw: String): HealthMetricSpec? {+ val normalised = raw.trim().lowercase().replace('-', '_').replace(' ', '_')+ val key = HEALTH_METRIC_ALIASES[normalised] ?: normalised+ return HEALTH_METRIC_SPECS.firstOrNull { it.key == key }+}++/** Days covered by a range name (`today` / `7d` / `30d`), or null when unknown. */+internal fun parseHealthRangeDays(raw: String): Int? = when (raw.trim().lowercase()) {+ "today" -> 1+ "7d" -> 7+ "30d" -> 30+ else -> null+}++/** Half-open local-calendar window `[start, end)` in epoch millis ending tomorrow. */+internal fun healthWindowMillis(rangeDays: Int, today: LocalDate, zone: ZoneId): Pair<Long, Long> {+ val start = today.minusDays((rangeDays - 1).toLong()).atStartOfDay(zone).toInstant().toEpochMilli()+ val end = today.plusDays(1).atStartOfDay(zone).toInstant().toEpochMilli()+ return start to end+}++/** Raw window aggregates as read from the repository, before scaling and rounding. */+internal data class HealthWindowAggregates(+ val latestValue: Double? = null,+ val average: Double? = null,+ val min: Double? = null,+ val max: Double? = null,+ val total: Double? = null,+ val recordCount: Int = 0,+ val daysWithData: Int = 0,+)++private fun scaled(value: Double, spec: HealthMetricSpec): Double =+ (value * spec.scale * 100).roundToLong() / 100.0++/**+ * Builds the aggregate-only DTO: cumulative metrics keep [HealthWindowAggregates.total]+ * and report a per-day average over the whole window; point metrics keep the+ * mean recorded value and never report a total. Values are display-scaled and+ * rounded to two decimals so the result stays a few hundred characters.+ */+internal fun buildHealthMetricSummary(+ spec: HealthMetricSpec,+ range: String,+ windowStartMillis: Long,+ windowEndMillis: Long,+ windowDays: Int,+ aggregates: HealthWindowAggregates,+): HealthMetricSummaryData {+ val total = if (spec.cumulative) aggregates.total?.let { scaled(it, spec) } else null+ val average = if (spec.cumulative) {+ if (total != null && windowDays > 0) (total / windowDays * 100).roundToLong() / 100.0 else null+ } else {+ aggregates.average?.let { scaled(it, spec) }+ }+ return HealthMetricSummaryData(+ metric = spec.key,+ range = range.trim().lowercase(),+ unit = spec.unit,+ cumulative = spec.cumulative,+ latestValue = aggregates.latestValue?.let { scaled(it, spec) },+ average = average,+ min = aggregates.min?.let { scaled(it, spec) },+ max = aggregates.max?.let { scaled(it, spec) },+ total = total,+ recordCount = aggregates.recordCount,+ daysWithData = aggregates.daysWithData,+ windowStartMillis = windowStartMillis,+ windowEndMillis = windowEndMillis,+ )+}++private fun errorSummary(input: HealthMetricQuery, error: String) = HealthMetricSummaryData(+ metric = input.metric.take(80),+ range = input.range.take(20),+ unit = "",+ error = error,+)++/**+ * "Headless" activity launched by OpenAssistant's `health_get_metric_summary`+ * tool. Reads only SQL aggregates (sum / average / min / max / count, daily+ * buckets and the single latest value) from [HealthRepository] over a recent+ * local-calendar window and returns them as a [HealthMetricSummaryData]. No+ * raw record ever crosses to the caller. No UI — the activity finishes+ * immediately as dictated by the [AssistantIntent] base class.+ */+@OptIn(InternalSerializationApi::class)+class GetMetricSummaryIntent : AssistantIntent<HealthMetricQuery, HealthMetricSummaryData>(+ inputSerializer = serializer<HealthMetricQuery>(),+ outputSerializer = serializer<HealthMetricSummaryData>(),+) {+ // Broad catch is deliberate: a headless assistant intent must return a payload, never throw.+ @Suppress("TooGenericExceptionCaught")+ override suspend fun performCalculation(input: HealthMetricQuery): HealthMetricSummaryData {+ val spec = parseHealthMetric(input.metric) ?: return errorSummary(+ input,+ "unknown health metric '${input.metric.take(40)}'; " ++ "use steps, sleep, weight, heart_rate, hydration or another dashboard metric",+ )+ val days = parseHealthRangeDays(input.range) ?: return errorSummary(+ input,+ "unknown range '${input.range.take(20)}'; use today, 7d or 30d",+ )+ return try {+ val repository = HealthRepository.get(this)+ val zone = ZoneId.systemDefault()+ val (startMillis, endMillis) = healthWindowMillis(days, LocalDate.now(zone), zone)+ val start = kotlin.time.Instant.fromEpochMilliseconds(startMillis)+ val end = kotlin.time.Instant.fromEpochMilliseconds(endMillis)+ val daily = if (spec.cumulative) {+ repository.getDailySums(spec.recordType, start, end)+ } else {+ repository.getDailyAvgs(spec.recordType, start, end)+ }+ val last = repository.getLastRecord(spec.recordType)+ val lastMillis = last?.startTime?.toEpochMilli()+ buildHealthMetricSummary(+ spec = spec,+ range = input.range,+ windowStartMillis = startMillis,+ windowEndMillis = endMillis,+ windowDays = days,+ aggregates = HealthWindowAggregates(+ latestValue = if (last != null && lastMillis != null &&+ lastMillis >= startMillis && lastMillis < endMillis+ ) {+ last.value+ } else {+ null+ },+ average = if (spec.cumulative) {+ null+ } else {+ repository.avgInRange(spec.recordType, start, end)+ },+ min = repository.minInRange(spec.recordType, start, end).first(),+ max = repository.maxInRange(spec.recordType, start, end).first(),+ total = if (spec.cumulative) {+ repository.sumInRange(spec.recordType, start, end).first()+ } else {+ null+ },+ recordCount = repository.countInRange(spec.recordType, start, end),+ daysWithData = daily.size,+ ),+ )+ } catch (e: Exception) {+ errorSummary(input, e.message ?: "failed to read health summary")+ }+ }+}
health/src/test/java/com/vayunmathur/health/intents/GetMetricSummaryIntentTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/intents/GetMetricSummaryIntentTest.kt b/health/src/test/java/com/vayunmathur/health/intents/GetMetricSummaryIntentTest.ktnew file mode 100644index 0000000000..1fc15dd8e9--- /dev/null+++ b/health/src/test/java/com/vayunmathur/health/intents/GetMetricSummaryIntentTest.kt@@ -0,0 +1,128 @@+package com.vayunmathur.health.intents++import com.vayunmathur.health.data.RecordType+import com.vayunmathur.library.intents.health.HealthMetricSummaryData+import java.time.LocalDate+import java.time.ZoneId+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.jsonObject+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pins the validated, aggregate-only contract of `health_get_metric_summary`:+ * metric/range validation, cumulative-vs-point aggregation, display scaling+ * and rounding, the window arithmetic, and that the produced DTO has no+ * record-level fields.+ */+class GetMetricSummaryIntentTest {++ @Test+ fun parsesKnownMetricsCaseAndSeparatorInsensitively() {+ assertEquals(RecordType.Steps, parseHealthMetric("steps")?.recordType)+ assertEquals(RecordType.Sleep, parseHealthMetric(" Sleep ")?.recordType)+ assertEquals(RecordType.HeartRate, parseHealthMetric("heart-rate")?.recordType)+ assertEquals(RecordType.Weight, parseHealthMetric("WEIGHT")?.recordType)+ assertEquals(RecordType.Hydration, parseHealthMetric("hydration")?.recordType)+ assertNotNull(parseHealthMetric("calories_total"))+ }++ @Test+ fun rejectsUnknownAndDualSeriesMetrics() {+ assertNull(parseHealthMetric("blood_pressure"))+ assertNull(parseHealthMetric("fhir_records"))+ assertNull(parseHealthMetric(""))+ assertNull(parseHealthMetric("medications"))+ }++ @Test+ fun parsesRangesStrictly() {+ assertEquals(1, parseHealthRangeDays("today"))+ assertEquals(7, parseHealthRangeDays("7D"))+ assertEquals(30, parseHealthRangeDays(" 30d "))+ assertNull(parseHealthRangeDays("year"))+ assertNull(parseHealthRangeDays("all"))+ assertNull(parseHealthRangeDays(""))+ }++ @Test+ fun windowCoversRangeDaysEndingTomorrow() {+ val zone = ZoneId.of("UTC")+ val today = LocalDate.of(2026, 12, 2)+ val (start, end) = healthWindowMillis(7, today, zone)+ assertEquals(LocalDate.of(2026, 11, 26).atStartOfDay(zone).toInstant().toEpochMilli(), start)+ assertEquals(LocalDate.of(2026, 12, 3).atStartOfDay(zone).toInstant().toEpochMilli(), end)+ val (todayStart, todayEnd) = healthWindowMillis(1, today, zone)+ assertEquals(today.atStartOfDay(zone).toInstant().toEpochMilli(), todayStart)+ assertEquals(end, todayEnd)+ }++ @Test+ fun cumulativeSummaryReportsTotalAndPerDayAverage() {+ val spec = parseHealthMetric("steps")!!+ val summary = buildHealthMetricSummary(+ spec = spec, range = "7d",+ windowStartMillis = 1_000L, windowEndMillis = 2_000L, windowDays = 7,+ aggregates = HealthWindowAggregates(+ latestValue = 8200.0, min = 100.0, max = 9000.0,+ total = 14000.0, recordCount = 12, daysWithData = 5,+ ),+ )+ assertTrue(summary.cumulative)+ assertEquals(14000.0, summary.total)+ assertEquals(2000.0, summary.average)+ assertEquals(8200.0, summary.latestValue)+ assertEquals(12, summary.recordCount)+ assertEquals(5, summary.daysWithData)+ assertNull(summary.error)+ }++ @Test+ fun pointSummaryReportsMeanAndNoTotal() {+ val spec = parseHealthMetric("weight")!!+ val summary = buildHealthMetricSummary(+ spec = spec, range = "30d",+ windowStartMillis = 1_000L, windowEndMillis = 2_000L, windowDays = 30,+ aggregates = HealthWindowAggregates(+ latestValue = 72.567, average = 72.251, min = 71.0, max = 73.0,+ total = 999.0, recordCount = 4, daysWithData = 4,+ ),+ )+ assertFalse(summary.cumulative)+ assertNull(summary.total)+ assertEquals(72.25, summary.average)+ assertEquals(72.57, summary.latestValue)+ assertEquals("kg", summary.unit)+ }++ @Test+ fun heightIsScaledFromMetresToCentimetres() {+ val spec = parseHealthMetric("height")!!+ val summary = buildHealthMetricSummary(+ spec = spec, range = "today",+ windowStartMillis = 1_000L, windowEndMillis = 2_000L, windowDays = 1,+ aggregates = HealthWindowAggregates(latestValue = 1.75, average = 1.75, recordCount = 1, daysWithData = 1),+ )+ assertEquals(175.0, summary.latestValue)+ assertEquals("cm", summary.unit)+ }++ @Test+ fun emptyWindowStaysAggregateOnlyAndSmall() {+ val spec = parseHealthMetric("sleep")!!+ val summary: HealthMetricSummaryData = buildHealthMetricSummary(+ spec = spec, range = "7d",+ windowStartMillis = 1_000L, windowEndMillis = 2_000L, windowDays = 7,+ aggregates = HealthWindowAggregates(total = 0.0),+ )+ assertEquals(0, summary.recordCount)+ val encoded = Json.encodeToString(HealthMetricSummaryData.serializer(), summary)+ val keys = Json.parseToJsonElement(encoded).jsonObject.keys+ assertFalse(keys.any { it in setOf("id", "records", "values", "startTime", "endTime", "metadata") })+ assertTrue(encoded.length < 400)+ }+}
library/AGENTS.md
diff --git a/library/AGENTS.md b/library/AGENTS.mdindex 7f2c4a7b89..4d6eb0c1e1 100644--- a/library/AGENTS.md+++ b/library/AGENTS.md@@ -29,7 +29,7 @@ - com/vayunmathur/library/intents/music/MusicData.kt - com/vayunmathur/library/intents/taxi/RideEstimateData.kt - com/vayunmathur/library/intents/weather/WeatherData.kt-- com/vayunmathur/library/intents/news/NewsData.kt+- com/vayunmathur/library/intents/health/HealthMetricData.kt — aggregate-only health summary query/result (no record-level fields) ### 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/health/HealthMetricData.kt
diff --git a/library/src/main/java/com/vayunmathur/library/intents/health/HealthMetricData.kt b/library/src/main/java/com/vayunmathur/library/intents/health/HealthMetricData.ktnew file mode 100644index 0000000000..1544936dc4--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/intents/health/HealthMetricData.kt@@ -0,0 +1,53 @@+package com.vayunmathur.library.intents.health++import kotlinx.serialization.Serializable++/**+ * Query for the Health app's `GetMetricSummaryIntent`: one metric over one+ * recent window. [metric] is a dashboard metric name (`steps`, `sleep`,+ * `weight`, `heart_rate`, `hydration`, …) and [range] is `today`, `7d` or+ * `30d`; both are validated and normalised provider-side in Health, where an+ * unknown value comes back as [HealthMetricSummaryData.error] rather than a+ * best-effort guess.+ */+@Serializable+data class HealthMetricQuery(+ val metric: String,+ val range: String = "7d",+)++/**+ * Aggregate-only health summary returned by the Health app's+ * `GetMetricSummaryIntent` to OpenAssistant's `health_get_metric_summary`+ * tool.+ *+ * This DTO deliberately carries no record-level data: no record ids, no+ * timestamps of individual records, no per-record values and no lists at+ * all. The only numbers are window aggregates — [latestValue] (the single+ * most recent value inside the window), [average] (mean recorded value for+ * point metrics, mean daily total for cumulative metrics such as steps),+ * [min]/[max], [total] (cumulative metrics only) — plus the [recordCount]+ * and [daysWithData] that say how much data those aggregates summarise.+ *+ * [error] is non-null only when the query was invalid or no summary could+ * be produced; the other fields are then at their defaults and callers+ * should check [error] first.+ */+@Serializable+data class HealthMetricSummaryData(+ val metric: String,+ val range: String,+ val unit: String,+ /** True when [total] is meaningful and [average] is a per-day average. */+ val cumulative: Boolean = false,+ val latestValue: Double? = null,+ val average: Double? = null,+ val min: Double? = null,+ val max: Double? = null,+ val total: Double? = null,+ val recordCount: Int = 0,+ val daysWithData: Int = 0,+ val windowStartMillis: Long = 0,+ val windowEndMillis: Long = 0,+ val error: String? = null,+)
library/src/test/java/com/vayunmathur/library/intents/health/HealthMetricDataTest.kt
diff --git a/library/src/test/java/com/vayunmathur/library/intents/health/HealthMetricDataTest.kt b/library/src/test/java/com/vayunmathur/library/intents/health/HealthMetricDataTest.ktnew file mode 100644index 0000000000..bea872edf8--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/intents/health/HealthMetricDataTest.kt@@ -0,0 +1,81 @@+package com.vayunmathur.library.intents.health++import kotlinx.serialization.json.Json+import kotlinx.serialization.json.jsonObject+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * The health IPC DTOs travel as JSON over the `AssistantIntent` binder.+ * These pin the aggregate-only contract: a summary round-trips unchanged+ * and its JSON carries no record-level keys (no ids, no per-record+ * timestamps or values, no lists).+ */+class HealthMetricDataTest {++ private val json = Json++ @Test+ fun query_roundTrips_withDefaultRange() {+ val original = HealthMetricQuery(metric = "steps")+ val decoded = json.decodeFromString(+ HealthMetricQuery.serializer(),+ json.encodeToString(HealthMetricQuery.serializer(), original),+ )+ assertEquals(original, decoded)+ assertEquals("7d", decoded.range)+ }++ @Test+ fun summary_roundTrips() {+ val original = HealthMetricSummaryData(+ metric = "steps",+ range = "7d",+ unit = "steps",+ cumulative = true,+ latestValue = 8200.0,+ average = 2000.0,+ min = 100.0,+ max = 9000.0,+ total = 14000.0,+ recordCount = 12,+ daysWithData = 5,+ windowStartMillis = 1_000L,+ windowEndMillis = 2_000L,+ )+ val decoded = json.decodeFromString(+ HealthMetricSummaryData.serializer(),+ json.encodeToString(HealthMetricSummaryData.serializer(), original),+ )+ assertEquals(original, decoded)+ }++ @Test+ fun summary_json_hasOnlyAggregateKeys() {+ val encoded = json.encodeToString(+ HealthMetricSummaryData.serializer(),+ HealthMetricSummaryData(+ metric = "weight", range = "30d", unit = "kg",+ latestValue = 72.5, average = 72.25, min = 71.0, max = 73.0,+ recordCount = 4, daysWithData = 4,+ windowStartMillis = 1_000L, windowEndMillis = 2_000L,+ ),+ )+ val keys = json.parseToJsonElement(encoded).jsonObject.keys+ // Default-valued fields are omitted from the wire; every present key+ // must be one of the aggregate keys below.+ val allowed = setOf(+ "metric", "range", "unit", "cumulative", "latestValue", "average",+ "min", "max", "total", "recordCount", "daysWithData",+ "windowStartMillis", "windowEndMillis", "error",+ )+ assertTrue(keys.all { it in allowed }, "unexpected keys: ${keys - allowed}")+ assertTrue("latestValue" in keys && "average" in keys)+ // No record-level surface: no ids, no per-record time/value fields, no lists.+ assertFalse(keys.any { it.contains("record") && it != "recordCount" })+ assertFalse(keys.any { it in setOf("id", "records", "values", "startTime", "endTime", "metadata") })+ assertTrue(encoded.length < 400, "summary JSON must stay small, was ${encoded.length}")+ }+}
openassistant/AGENTS.md
diff --git a/openassistant/AGENTS.md b/openassistant/AGENTS.mdindex cec9c1de4d..45dfa7132f 100644--- a/openassistant/AGENTS.md+++ b/openassistant/AGENTS.md@@ -70,7 +70,7 @@ _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 — includes the News tools (`news_search_headlines`, `news_top_stories`, `news_get_story`, `news_read_article`) launching `com.vayunmathur.news` intents, with host summarizers re-clamping headlines/story/article pages+- 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/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 d658d0e1b7..9a743d83f6 100644--- a/openassistant/src/main/AndroidManifest.xml+++ b/openassistant/src/main/AndroidManifest.xml@@ -20,7 +20,7 @@ <uses-permission android:name="com.vayunmathur.maps.permissions.ACCESS_MAPS" /> <uses-permission android:name="com.vayunmathur.taxi.permissions.ACCESS_RIDES" /> <uses-permission android:name="com.vayunmathur.fooddelivery.permissions.ACCESS_ORDERS" />- <uses-permission android:name="com.vayunmathur.news.permissions.ACCESS_NEWS" />+ <uses-permission android:name="com.vayunmathur.health.permissions.ACCESS_HEALTH" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" />@@ -59,7 +59,7 @@ <package android:name="com.vayunmathur.maps" /> <package android:name="com.vayunmathur.taxi" /> <package android:name="com.vayunmathur.fooddelivery" />- <package android:name="com.vayunmathur.news" />+ <package android:name="com.vayunmathur.health" /> </queries> <application
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 8cc3b855e7..654207395a 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt@@ -54,18 +54,18 @@ private fun parseToolRisk(field: String): ToolRisk = private const val TOOL_DATA = """ get_notes|-|Get a list of all notes|-create_note|C|Create a note (requires confirmation, EXPLICIT only)|title^S^1^~content^S^1^-get_todos|-|Get open Todo tasks. Due times are epoch ms; ids work with complete_todo.|scope^S^0^today (default), upcoming, or all-create_todo|C|Create a Todo task (requires confirmation, EXPLICIT only). Title may include 'tomorrow 6pm' or '#tag'.|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, EXPLICIT only)|id^S^0^task id from get_todos~title^S^0^exact task title, used when no id is given+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+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^-get_calendar_events|-|Get calendar events (times are epoch ms).|-create_calendar_event|C|Create a calendar event (requires confirmation). Times are epoch ms.|title^S^1^~start^N^1^start time as epoch milliseconds~end^N^1^end time as epoch milliseconds~location^S^0^+get_calendar_events|-|Get a list of calendar events. Each event's start and end times are epoch milliseconds.|+create_calendar_event|C|Create a new calendar event (requires confirmation). Start and end times must be epoch milliseconds.|title^S^1^~start^N^1^start time as epoch milliseconds~end^N^1^end time as epoch milliseconds~location^S^0^ get_family_locations|-|Get a list of family members and their current locations|-create_location_share_link|C|Create a temporary live-location FindFamily link (requires confirmation).|name^S^1^name or label for who the link is for~duration_millis^N^1^how long the link stays active, in milliseconds-search_music|-|Search music (songs, albums, artists, playlists)|query^S^1^-play_music|C|Play music by id/type (requires confirmation)|id^N^1^~type^S^1^+create_location_share_link|C|Create a temporary FindFamily link that shares the user's live location (requires confirmation).|name^S^1^name or label for who the link is for~duration_millis^N^1^how long the link stays active, in milliseconds+search_music|-|Search for music (songs, albums, artists, or playlists)|query^S^1^+play_music|C|Play music given its id and type (song, album, artist, or playlist) (requires confirmation)|id^N^1^~type^S^1^ search_emails|-|Search emails by keyword|query^S^1^ get_recent_emails|-|Get recent emails from the inbox| get_local_current_date_time|-|Get the current date and time in the local timezone.|@@ -73,41 +73,38 @@ get_app_list|-|Get a list of installed apps on the device| 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|-|Make a phone call|recipient^S^1^-set_alarm|C|Set a Clock alarm (24-hour, 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_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|-|Current weather at latitude/longitude.|latitude^N^1^~longitude^N^1^-get_weather_by_name|-|Current weather for a named place.|location^S^1^city or place name-render_ui|-|Render a rich UI card (A2UI); prefer over a ```a2ui fence. components_json: {"components":[...]} or a bare array, RICH UI types; data_json: optional 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|-|Maps directions between coordinates: distance, duration, segments.|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 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 if a restaurant is orderable near a location (FoodDelivery).|name^S^1^restaurant name~lat^N^1^latitude~lng^N^1^longitude~address^S^0^optional address-search_contacts|-|Search contacts by name/phone substring (max 10).|query^S^1^name or phone substring to search for-web_search|-|Search the web for current facts. Numbered results; read with web_read_result.|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, extracted text.|url^S^1^page URL to read-web_read_result|-|Read a web_search result by 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/snippet. Returns thread_key for 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 conversation messages by 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. Sends nothing; user edits, taps Send, confirms 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 only). GoogleVoice: use draft_message.|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 FoodDelivery restaurants near a location, optional name/tag filter.|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 a restaurant menu (merchant_id from find_restaurants): ids, prices (cents), availability, modifiers.|merchant_id^N^1^merchant id from find_restaurants-food_get_cart|-|Current FoodDelivery cart (items, total)|-food_set_cart|L|Replace the FoodDelivery cart with items_json [{itemId,qty,modifierIds}]. Re-validated and shown back; no order, 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 cart (pickup/delivery), creating no order; 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 cart order summary. User places/pays in FoodDelivery; never creates an order or charges.|merchant_id^N^1^merchant id of the cart-get_food_orders|-|Past FoodDelivery orders|-search_products|-|Search Shop: each result is a purchasable variant (variant_id, store, price).|query^S^1^search text~limit^N^0^optional max results (default 5)-get_product_detail|-|Get product variants with prices/availability. Confirm variant with user before 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|-|Current Shop cart, by store|-shop_add_to_cart|L|Add a variant to Shop cart (re-verified, 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 Shop cart variant; cart shown back.|variant_id^S^1^variant id to remove-start_shop_checkout|H|Show one store's Shop cart summary. User checks out in Shop; never creates a checkout or charges.|shop_domain^S^1^store domain to check out-get_shop_orders|-|Shop order summaries|-news_search_headlines|-|Search News headlines|query^S^1^~category^S^0^WORLD US TECHNOLOGY SCIENCE LOCAL~limit^N^0^1-10, default 5-news_top_stories|-|Top News stories by source count, then newest|category^S^0^WORLD US TECHNOLOGY SCIENCE LOCAL~limit^N^0^1-10, default 5-news_get_story|-|Get a News story by story_id|story_id^S^1^from news search/top-news_read_article|-|Read a News article (3000 chars/page)|url^S^1^from a news result~offset^N^0^char offset+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+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_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_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+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+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+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^ add_to_memory|-|Add a new memory to the list of memories|content^S^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 82b35fb515..896ccbb32f 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt@@ -55,6 +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.openassistant.data.Memory import com.vayunmathur.openassistant.data.MemoryDao import kotlinx.datetime.TimeZone@@ -71,7 +73,7 @@ import kotlinx.serialization.serializer /** * Core cross-app intents (notes, todos, contacts, calendar, family, music,- * email, clock, weather, maps, taxi) backing [AssistantToolIntents]; the+ * email, clock, weather, health, maps, taxi) backing [AssistantToolIntents]; the * commerce/communicate intents live in the subclass so neither class * exceeds the TooManyFunctions limit. */@@ -246,6 +248,16 @@ 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,
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 61e2cea225..3be3e6627b 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt@@ -51,17 +51,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.education.EducationProgressData import com.vayunmathur.library.intents.weather.WeatherData-import com.vayunmathur.library.intents.screentime.ScreentimeUsageQuery-import com.vayunmathur.library.intents.screentime.ScreentimeUsageData-import com.vayunmathur.library.intents.news.NewsArticleExcerptData-import com.vayunmathur.library.intents.news.NewsArticleQuery-import com.vayunmathur.library.intents.news.NewsHeadlineData-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.health.HealthMetricSummaryData import com.vayunmathur.openassistant.data.Memory import com.vayunmathur.openassistant.data.MemoryDao import kotlinx.datetime.TimeZone@@ -95,6 +86,7 @@ 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",@@ -102,7 +94,6 @@ internal class AssistantToolIntents(context: Context) : AssistantCoreToolIntents "com.vayunmathur.fooddelivery" to "FoodDelivery", "com.vayunmathur.communicate" to "Communicate", "com.vayunmathur.shop" to "Shop",- "com.vayunmathur.news" to "News", ) fun getMissingAppMessage(packageName: String): String {@@ -236,34 +227,6 @@ internal class AssistantToolIntents(context: Context) : AssistantCoreToolIntents Unit, ) - suspend fun searchNewsHeadlines(query: String, category: String?, limit: Int): List<NewsHeadlineData> = launchIntent(- context,- "com.vayunmathur.news",- "com.vayunmathur.news.intents.SearchHeadlinesIntent",- NewsSearchQuery(query, category, limit),- )-- suspend fun topNewsStories(category: String?, limit: Int): List<NewsHeadlineData> = launchIntent(- context,- "com.vayunmathur.news",- "com.vayunmathur.news.intents.TopStoriesIntent",- NewsTopQuery(category, limit),- )-- suspend fun getNewsStory(storyId: String): NewsStoryData = launchIntent(- context,- "com.vayunmathur.news",- "com.vayunmathur.news.intents.GetStoryIntent",- NewsStoryQuery(storyId),- )-- suspend fun readNewsArticle(url: String, offset: Int): NewsArticleExcerptData = launchIntent(- context,- "com.vayunmathur.news",- "com.vayunmathur.news.intents.ReadArticleIntent",- NewsArticleQuery(url, offset),- )- suspend fun getContactsList(): List<ContactData> = launchIntent<Unit, List<ContactData>>( context, "com.vayunmathur.contacts",@@ -350,6 +313,46 @@ 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.+ */+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. */ fun summarizeRideEstimate(result: RideEstimateResult): String = if (!result.available) {@@ -519,36 +522,6 @@ fun summarizeShopOrders(list: List<ShopOrderData>, cap: Int = 10): String = } } -/** Host-truncated headline list for the model (provider caps already applied; re-clamped here). */-fun summarizeNewsHeadlines(list: List<NewsHeadlineData>): String =- if (list.isEmpty()) {- "No headlines found"- } else {- list.take(10).joinToString("\n") { h ->- "story_id=${h.storyId} url=${h.url} [${h.sourceCount} source(s)] " +- h.title.take(160) + (h.oneLiner?.take(200)?.let { " — $it" } ?: "")- }- }--/** Host-truncated story coverage for the model. */-fun summarizeNewsStory(data: NewsStoryData): String {- if (data.members.isEmpty()) return "No story found for story_id=${data.storyId}"- val header = "Story ${data.title.take(160)}" +- (data.oneLiner?.take(300)?.let { "\n$it" } ?: "")- val lines = data.members.take(8).joinToString("\n") { m ->- "url=${m.url} [${m.sourceName}] ${m.title.take(160)}"- }- return "$header\n$lines"-}--/** Host-truncated article page for the model; never the whole body in one result. */-fun summarizeNewsArticle(data: NewsArticleExcerptData): String {- if (data.excerpt.isEmpty() && data.title.isEmpty()) return "Article unavailable"- val byline = data.byline?.takeIf { it.isNotBlank() }?.let { "\n$it" } ?: ""- 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"-}- /** Maps a provider send outcome to the model-facing string; GV is typed. */ fun summarizeSendResult(result: SendMessageResult): String = when { result.success -> "Success: Message sent"@@ -574,55 +547,3 @@ suspend inline fun <reified Input : Any> launchIntentU( ) if (stringOutput == "package $packageName doesn't exist") throw MissingAppException(packageName) }--fun summarizeScreentimeUsage(data: ScreentimeUsageData): String {- if (!data.hasUsageAccess || data.error != null) {- return "Screen time unavailable: usage access is not granted in Screentime"- }- if (data.apps.isEmpty()) return "No screen time recorded today (0m total)"- val lines = data.apps.take(ScreentimeUsageQuery.MAX_TOP_APPS)- .joinToString("\n") { app ->- "${app.label.take(ScreentimeUsageQuery.MAX_LABEL_CHARS)} " +- "(${app.packageName}): ${formatUsageDuration(app.totalMillis)}"- }- return "Today: ${formatUsageDuration(data.totalMillis)} total\n$lines"-}--/** Compact duration for usage summaries: `2h 15m`, `45m`, or `30s`. */--fun formatUsageDuration(millis: Long): String {- val totalSeconds = millis / 1_000- val hours = totalSeconds / 3_600- val minutes = (totalSeconds % 3_600) / 60- val seconds = totalSeconds % 60- return when {- hours > 0 -> "${hours}h ${minutes}m"- minutes > 0 -> "${minutes}m"- else -> "${seconds}s"- }-}--/** Maps a provider send outcome to the model-facing string; GV is typed. */--fun summarizeEducationProgress(data: EducationProgressData): String {- val header = buildString {- data.learnerFirstName?.let { append("$it: ") }- append("streak ${data.streakDays}d, ${data.totalStars} stars, ")- append("${data.skillsMastered}/${data.totalSkills} skills mastered, ")- append("${data.skillsStarted} started")- data.band?.let { append(" (band $it)") }- }- val courses = data.courses.joinToString("\n") { c ->- "course ${c.title.take(120)} [${c.subject}]: " +- "${c.masteredSkills}/${c.totalSkills} mastered (${c.completionPercent}%), ${c.startedSkills} started"- }- val subjects = data.subjects.joinToString("\n") { s ->- "subject ${s.subject}: ${s.masteredSkills}/${s.totalSkills} mastered (${s.completionPercent}%), ${s.startedSkills} started"- }- val deadlines = data.upcomingDeadlines.take(5).joinToString("\n") { d ->- "deadline ${d.title.take(120)} [${d.moduleType}] dueEpochDay=${d.dueEpochDay}"- }- return listOf(header, courses, subjects, deadlines).filter { it.isNotBlank() }.joinToString("\n")-}--/** 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 5f0dcc9b90..1c90330afd 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt@@ -155,13 +155,9 @@ class AssistantTools( intents.runTool { intents.getWeather(a.number("latitude"), a.number("longitude")) } }, "get_weather_by_name" to { a -> intents.runTool { intents.getWeatherByName(a.string("location")) } },- "screentime_get_usage" to { _ ->+ "health_get_metric_summary" to { a -> intents.runTool {- com.vayunmathur.openassistant.platform.summarizeScreentimeUsage(- intents.getScreentimeUsage(- com.vayunmathur.library.intents.screentime.ScreentimeUsageQuery.MAX_TOP_APPS,- ),- )+ intents.getHealthMetricSummary(a.string("metric"), a.string("range", "7d")) } }, "get_directions" to { a ->@@ -449,40 +445,6 @@ class AssistantTools( com.vayunmathur.openassistant.platform.summarizeShopOrders(intents.getShopOrders()) } },- "news_search_headlines" to { a ->- intents.runTool {- val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5- com.vayunmathur.openassistant.platform.summarizeNewsHeadlines(- intents.searchNewsHeadlines(- a.string("query"),- a.string("category").takeIf { it.isNotBlank() },- limit,- ),- )- }- },- "news_top_stories" to { a ->- intents.runTool {- val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 5- com.vayunmathur.openassistant.platform.summarizeNewsHeadlines(- intents.topNewsStories(a.string("category").takeIf { it.isNotBlank() }, limit),- )- }- },- "news_get_story" to { a ->- intents.runTool {- com.vayunmathur.openassistant.platform.summarizeNewsStory(- intents.getNewsStory(a.string("story_id")),- )- }- },- "news_read_article" to { a ->- intents.runTool {- com.vayunmathur.openassistant.platform.summarizeNewsArticle(- intents.readNewsArticle(a.string("url"), a.number("offset").toInt()),- )- }- }, "web_search" to { a -> val count = a.number("count").toInt().takeIf { it > 0 } ?: 5 val result = runBlocking { webTools.webSearch(a.string("query"), count, a.string("kind", "text")) }@@ -494,11 +456,6 @@ class AssistantTools( runBlocking { webTools.webReadResult(a.number("index").toInt(), a.number("offset").toInt()) } }, "render_ui" to { a -> renderUi(a.string("components_json"), a.string("data_json")) },- "education_get_progress" to { _ ->- intents.runTool {- com.vayunmathur.openassistant.platform.summarizeEducationProgress(intents.getEducationProgress())- }- }, "get_memories" to { _ -> intents.runTool { device.getMemories(memoryDao) } }, "remove_memory" to { a -> intents.runTool { device.removeMemory(memoryDao, a.number("id")) } }, "add_to_memory" to { a -> intents.runTool { device.addToMemory(memoryDao, a.string("content")) } },
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 135e9d1e30..b998ee4ecb 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(58, ASSISTANT_TOOL_SPECS.size)+ assertEquals(55, 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 0da6f2c2f4..eec6d828b9 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(58, tools.declarations.size)+ assertEquals(55, 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 885015e250..d44eb7985c 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(58, names.size)+ assertEquals(55, names.size) assertEquals(names.size, names.toSet().size) for (spec in ASSISTANT_TOOL_SPECS) { assertTrue(snake.matches(spec.name), spec.name)@@ -68,7 +68,6 @@ class AssistantToolsTest { "food_prepare_order.merchant_id", "food_prepare_order.is_pickup", "food_prepare_order.tip_cents", "place_food_order.merchant_id", "search_products.limit", "shop_add_to_cart.quantity",- "news_search_headlines.limit", "news_top_stories.limit", "news_read_article.offset", ), numeric, )
openassistant/src/test/java/com/vayunmathur/openassistant/platform/HealthMetricSummaryTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/HealthMetricSummaryTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/HealthMetricSummaryTest.ktnew file mode 100644index 0000000000..d478b3f055--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/HealthMetricSummaryTest.kt@@ -0,0 +1,79 @@+package com.vayunmathur.openassistant.platform++import com.vayunmathur.library.intents.health.HealthMetricSummaryData+import com.vayunmathur.openassistant.domain.ASSISTANT_TOOL_SPECS+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * Pins the host side of `health_get_metric_summary`: the tool is catalogued+ * as a read, and its summarizer renders aggregates only — one short line, no+ * record-level fields, typed errors and empty windows.+ */+class HealthMetricSummaryTest {++ @Test+ fun toolIsCatalogued() {+ val spec = ASSISTANT_TOOL_SPECS.firstOrNull { it.name == "health_get_metric_summary" }+ assertNotNull(spec)+ assertEquals(listOf("metric", "range"), spec.params.map { it.name })+ assertTrue(spec.params.first().required)+ assertFalse(spec.params.last().required)+ }++ @Test+ fun summarizesCumulativeMetricInOneShortLine() {+ val out = summarizeHealthMetric(+ HealthMetricSummaryData(+ metric = "steps", range = "7d", unit = "steps", cumulative = true,+ latestValue = 8200.0, average = 2000.0, min = 100.0, max = 9000.0,+ total = 14000.0, recordCount = 12, daysWithData = 5,+ ),+ )+ assertTrue(out.startsWith("steps (last 7 days):"), out)+ assertTrue("latest 8200 steps" in out, out)+ assertTrue("avg/day 2000 steps" in out, out)+ assertTrue("total 14000 steps" in out, out)+ assertTrue("12 records over 5 day(s)" in out, out)+ assertTrue(out.length <= 300, "was ${out.length}")+ }++ @Test+ fun summarizesPointMetricWithoutTotal() {+ val out = summarizeHealthMetric(+ HealthMetricSummaryData(+ metric = "weight", range = "30d", unit = "kg",+ latestValue = 72.57, average = 72.25, min = 71.0, max = 73.0,+ recordCount = 4, daysWithData = 4,+ ),+ )+ assertTrue("latest 72.57 kg" in out, out)+ assertTrue("avg 72.25 kg" in out, out)+ assertFalse("total" in out, out)+ assertTrue(out.length <= 300)+ }++ @Test+ fun emptyAndErrorSummariesAreTyped() {+ assertEquals(+ "No sleep data in the last 7 days.",+ summarizeHealthMetric(HealthMetricSummaryData(metric = "sleep", range = "7d", unit = "hr")),+ )+ val error = summarizeHealthMetric(+ HealthMetricSummaryData(metric = "x", range = "7d", unit = "", error = "unknown health metric 'x'"),+ )+ assertTrue(error.startsWith("Error: health summary unavailable"), error)+ assertTrue(error.length <= 300)+ }++ @Test+ fun formatsValuesWithoutTrailingZeros() {+ assertEquals("8000", formatHealthValue(8000.0))+ assertEquals("7.5", formatHealthValue(7.5))+ assertEquals("72.25", formatHealthValue(72.25))+ assertEquals("0", formatHealthValue(0.0))+ }+}