Modern Apps git

← Modern-Apps.git

news: add capped OpenAssistant news tools

Commit
5982970d8e3ac7ccf1b95635127c07166291204b
Author
Vayun Mathur <[email protected]>
When
2026-12-02 04:27 UTC (4 days ago)
Parents
6663c24
Implement four filtered, provider-clamped News tools for OpenAssistant: news_search_headlines (query text, limit clamped 1-10, title <=160 chars, one-liner <=200 chars), news_top_stories (category filter over WORLD/US/TECHNOLOGY/SCIENCE/LOCAL, limit 1-10, ordered by the existing FeedRanking source-count-then-newest rule), news_get_story (storyId in Story.id or raw server id form, <=8 member headlines, one-liner <=300 chars), and news_read_article (3,000-char excerpt pages by character offset with nextOffset, never the whole body or feed).

Wire DTOs live in library/intents/news (all fields defaulted for compat); the validated contracts live in news/intents over NewsRepository's Room cache (no feed refresh triggered; article bodies reuse articleBody's cache-first path and are truncated provider-side). News exports the four NoDisplay intents behind the new signature ACCESS_NEWS permission; OpenAssistant declares that permission, registers the tools in AssistantToolSpecs (snake_case) and AssistantTools (init agreement check passes), and re-clamps every field in host summarizers. Existing tool descriptions were shortened so the pinned PromptBudget header stays within 24,500 chars at 58 tools. Tests pin provider caps, category filtering, story member caps, excerpt paging/clamping, host truncation, and registration.

Verified: :news:lint :news:lintVitalRelease :library:lint :openassistant:lint :openassistant:lintVitalRelease green; :news:testDevUnitTest new NewsAssistantBackendTest 6/6 green (full news suite has one pre-existing NewsPrefsTest.noFeedSortPreferenceExists failure on untouched HEAD code, LEGACY_FEED_SORT); :openassistant:testDevUnitTest targeted suites green including PromptBudgetTest (InferenceServiceConcurrencyTest is flaky under full-suite load and passes in isolation).

Diff

library/AGENTS.md
diff --git a/library/AGENTS.md b/library/AGENTS.mdindex 0ea6f36bd9..7f2c4a7b89 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/education/EducationProgressData.kt — aggregates-only progress summary (per-course/subject counts, ≤5 upcoming deadlines)+- com/vayunmathur/library/intents/news/NewsData.kt ### 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/news/NewsData.kt
diff --git a/library/src/main/java/com/vayunmathur/library/intents/news/NewsData.kt b/library/src/main/java/com/vayunmathur/library/intents/news/NewsData.ktnew file mode 100644index 0000000000..2fcee2d118--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/intents/news/NewsData.kt@@ -0,0 +1,95 @@+package com.vayunmathur.library.intents.news++import kotlinx.serialization.Serializable++/**+ * Shared wire DTOs for news's cross-app assistant intents+ * ([com.vayunmathur.library.util.AssistantIntent]): `SearchHeadlinesIntent`,+ * `TopStoriesIntent`, `GetStoryIntent` and `ReadArticleIntent` in+ * `com.vayunmathur.news.intents`, answered only for a co-signed caller behind+ * `com.vayunmathur.news.permissions.ACCESS_NEWS`.+ *+ * Thin and UI-free by design: category is the `NewsCategory` enum name+ * (`WORLD`, `US`, `TECHNOLOGY`, `SCIENCE`, `LOCAL`) as a plain string so this+ * package never depends on the news app's own types. Every field has a default+ * so older/newer callers can omit fields without breaking decode (library+ * DTO-compat rule). Caps named here are enforced provider-side in news's+ * `intents/` backend, not merely described to the model.+ */++/** Search cached headlines by [query] text; [category] optionally narrows by enum name. */+@Serializable+data class NewsSearchQuery(+    val query: String = "",+    val category: String? = null,+    val limit: Int = 5,+)++/** Top stories of the cached feed, feed-ranked; [category] optionally narrows by enum name. */+@Serializable+data class NewsTopQuery(+    val category: String? = null,+    val limit: Int = 5,+)++/** One story by [storyId] (a `Story.id` from a prior search/top result, or its raw server id). */+@Serializable+data class NewsStoryQuery(+    val storyId: String = "",+)++/** One 3,000-char page of an article body, starting at character [offset]. */+@Serializable+data class NewsArticleQuery(+    val url: String = "",+    val offset: Int = 0,+)++/**+ * One headline as the assistant sees it: a whole story (never a raw feed dump).+ * Provider caps: [title] ≤ 160 chars, [oneLiner] ≤ 200 chars when present.+ */+@Serializable+data class NewsHeadlineData(+    val storyId: String = "",+    val url: String = "",+    val title: String = "",+    val sourceName: String = "",+    val sourceCount: Int = 1,+    val publishedAtMillis: Long = 0L,+    val oneLiner: String? = null,+)++/** One member headline inside a [NewsStoryData]. Provider cap: [title] ≤ 160 chars. */+@Serializable+data class NewsStoryMemberData(+    val title: String = "",+    val sourceName: String = "",+    val publishedAtMillis: Long = 0L,+    val url: String = "",+)++/**+ * One story's coverage summary. Provider caps: [oneLiner] ≤ 300 chars,+ * [members] ≤ 8 headlines.+ */+@Serializable+data class NewsStoryData(+    val storyId: String = "",+    val title: String = "",+    val oneLiner: String? = null,+    val members: List<NewsStoryMemberData> = emptyList(),+)++/**+ * One page of extracted article text. Provider caps: [excerpt] ≤ 3,000 chars;+ * [nextOffset] is the offset to pass back for the next page, or null at the end.+ * The whole body never crosses in one result.+ */+@Serializable+data class NewsArticleExcerptData(+    val title: String = "",+    val byline: String? = null,+    val excerpt: String = "",+    val nextOffset: Int? = null,+)
news/AGENTS.md
diff --git a/news/AGENTS.md b/news/AGENTS.mdindex c51bc4ffb3..4a02075f50 100644--- a/news/AGENTS.md+++ b/news/AGENTS.md@@ -4,7 +4,7 @@  _Install: ./install news_ - Gradle: :news / dir: news/-- Package roots present: ui, data, domain, platform, network+- Package roots present: ui, data, domain, platform, network, intents - Entry files: MainActivity.kt, Route.kt, Navigation.kt - Deps: :library:network, :library:room, :library:image - Metadata: metadata_data/news.md (present)
news/src/main/AndroidManifest.xml
diff --git a/news/src/main/AndroidManifest.xml b/news/src/main/AndroidManifest.xmlindex fdb5564c76..e89edfe755 100644--- a/news/src/main/AndroidManifest.xml+++ b/news/src/main/AndroidManifest.xml@@ -7,6 +7,10 @@     <uses-permission android:name="android.permission.INTERNET" />     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> +    <permission+        android:name="com.vayunmathur.news.permissions.ACCESS_NEWS"+        android:protectionLevel="signature" />+     <application         android:allowBackup="true"         android:dataExtractionRules="@xml/data_extraction_rules"@@ -25,5 +29,25 @@                 <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>+        <activity+            android:name=".intents.SearchHeadlinesIntent"+            android:exported="true"+            android:theme="@android:style/Theme.NoDisplay"+            android:permission="com.vayunmathur.news.permissions.ACCESS_NEWS" />+        <activity+            android:name=".intents.TopStoriesIntent"+            android:exported="true"+            android:theme="@android:style/Theme.NoDisplay"+            android:permission="com.vayunmathur.news.permissions.ACCESS_NEWS" />+        <activity+            android:name=".intents.GetStoryIntent"+            android:exported="true"+            android:theme="@android:style/Theme.NoDisplay"+            android:permission="com.vayunmathur.news.permissions.ACCESS_NEWS" />+        <activity+            android:name=".intents.ReadArticleIntent"+            android:exported="true"+            android:theme="@android:style/Theme.NoDisplay"+            android:permission="com.vayunmathur.news.permissions.ACCESS_NEWS" />     </application> </manifest>
news/src/main/java/com/vayunmathur/news/intents/GetStoryIntent.kt
diff --git a/news/src/main/java/com/vayunmathur/news/intents/GetStoryIntent.kt b/news/src/main/java/com/vayunmathur/news/intents/GetStoryIntent.ktnew file mode 100644index 0000000000..f0b870a51a--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/intents/GetStoryIntent.kt@@ -0,0 +1,14 @@+package com.vayunmathur.news.intents++import com.vayunmathur.library.intents.news.NewsStoryQuery+import com.vayunmathur.library.intents.news.NewsStoryData+import com.vayunmathur.library.util.AssistantIntent++/** Assistant tool: One story's summary and member headlines (`news_get_story`). Validated and clamped provider-side in [NewsAssistantBackend]. */+class GetStoryIntent : AssistantIntent<NewsStoryQuery, NewsStoryData>(+    NewsStoryQuery.serializer(),+    NewsStoryData.serializer(),+) {+    override suspend fun performCalculation(input: NewsStoryQuery): NewsStoryData =+        getStory(input, newsAssistantBackend(this))+}
news/src/main/java/com/vayunmathur/news/intents/NewsAssistantBackend.kt
diff --git a/news/src/main/java/com/vayunmathur/news/intents/NewsAssistantBackend.kt b/news/src/main/java/com/vayunmathur/news/intents/NewsAssistantBackend.ktnew file mode 100644index 0000000000..3bb6dec2a3--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/intents/NewsAssistantBackend.kt@@ -0,0 +1,189 @@+package com.vayunmathur.news.intents++import android.content.Context+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.NewsStoryMemberData+import com.vayunmathur.library.intents.news.NewsStoryQuery+import com.vayunmathur.library.intents.news.NewsTopQuery+import com.vayunmathur.news.data.CachedArticle+import com.vayunmathur.news.data.NewsPrefs+import com.vayunmathur.news.data.NewsRepository+import com.vayunmathur.news.data.toFeedArticle+import com.vayunmathur.news.domain.ArticleBlock+import com.vayunmathur.news.domain.ExtractedArticle+import com.vayunmathur.news.domain.FeedRanking+import com.vayunmathur.news.domain.NewsCategory+import com.vayunmathur.news.domain.SourceCatalog+import com.vayunmathur.news.domain.Story+import com.vayunmathur.news.domain.StoryGrouping+import com.vayunmathur.news.domain.orderedBySearchHits+import kotlinx.coroutines.flow.first++internal const val DEFAULT_NEWS_LIMIT = 5+internal const val MAX_NEWS_LIMIT = 10+internal const val MAX_QUERY_CHARS = 200+internal const val MAX_HEADLINE_TITLE_CHARS = 160+internal const val MAX_HEADLINE_ONE_LINER_CHARS = 200+internal const val MAX_STORY_ONE_LINER_CHARS = 300+internal const val MAX_STORY_MEMBERS = 8+internal const val MAX_ARTICLE_EXCERPT_CHARS = 3_000++/**+ * Repository seam behind the news assistant intents. Production delegates to+ * [NewsRepository] (Room cache only — no intent ever triggers a feed refresh);+ * tests install a fake so provider logic (clamping, filtering, paging) is+ * asserted without Room or the network. Article bodies go through+ * [NewsRepository.articleBody], which serves the cached body first and only+ * then fetches that one article, exactly like the reader.+ */+internal interface NewsAssistantBackend {+    suspend fun search(query: String): List<CachedArticle>+    suspend fun cachedArticles(): List<CachedArticle>+    suspend fun articleBody(url: String): ExtractedArticle+    suspend fun localLocation(): String?+}++internal class RealNewsAssistantBackend(context: Context) : NewsAssistantBackend {+    private val appContext = context.applicationContext+    private val repo: NewsRepository get() = NewsRepository.get(appContext)++    override suspend fun search(query: String): List<CachedArticle> = repo.search(query)++    override suspend fun cachedArticles(): List<CachedArticle> = repo.articles.first()++    override suspend fun articleBody(url: String): ExtractedArticle = repo.articleBody(url)++    override suspend fun localLocation(): String? =+        runCatching { NewsPrefs(appContext).localLocation.first() }.getOrNull()+}++/** Test seam, mirroring the `overrideForTest` singletons elsewhere in this repo. */+internal var newsAssistantBackendForTest: NewsAssistantBackend? = null++internal fun newsAssistantBackend(context: Context): NewsAssistantBackend =+    newsAssistantBackendForTest ?: RealNewsAssistantBackend(context)++/** Validated category from its enum name; null when absent or unknown (caller decides). */+internal fun parseNewsCategory(raw: String?): NewsCategory? {+    val name = raw?.trim()?.takeIf { it.isNotEmpty() } ?: return null+    return NewsCategory.entries.firstOrNull { it.name.equals(name, ignoreCase = true) }+}++private fun clampLimit(limit: Int): Int =+    if (limit <= 0) DEFAULT_NEWS_LIMIT else limit.coerceAtMost(MAX_NEWS_LIMIT)++private fun Story.toHeadline(): NewsHeadlineData = NewsHeadlineData(+    storyId = id,+    url = representative.url,+    title = title.take(MAX_HEADLINE_TITLE_CHARS),+    sourceName = SourceCatalog.byId(representative.sourceId)?.name ?: representative.sourceId,+    sourceCount = sourceCount,+    publishedAtMillis = latestMillis,+    oneLiner = oneLiner?.take(MAX_HEADLINE_ONE_LINER_CHARS),+)++internal suspend fun searchHeadlines(+    input: NewsSearchQuery,+    backend: NewsAssistantBackend,+): List<NewsHeadlineData> {+    val query = input.query.trim().take(MAX_QUERY_CHARS)+    if (query.isEmpty()) return emptyList()+    val category = input.category?.let { raw ->+        parseNewsCategory(raw) ?: return emptyList()+    }+    val hits = runCatching { backend.search(query) }.getOrDefault(emptyList())+    if (hits.isEmpty()) return emptyList()+    val all = runCatching { backend.cachedArticles() }.getOrDefault(emptyList())+    val stories = StoryGrouping.group(all.map { it.toFeedArticle() })+        .orderedBySearchHits(hits.map { it.url })+    val location = if (category == NewsCategory.LOCAL) {+        runCatching { backend.localLocation() }.getOrNull()+    } else {+        null+    }+    return stories+        .filter { category == null || it.matchesFeedFilter(category, location) }+        .take(clampLimit(input.limit))+        .map { it.toHeadline() }+}++internal suspend fun topStories(+    input: NewsTopQuery,+    backend: NewsAssistantBackend,+): List<NewsHeadlineData> {+    val category = input.category?.let { raw ->+        parseNewsCategory(raw) ?: return emptyList()+    }+    val all = runCatching { backend.cachedArticles() }.getOrDefault(emptyList())+    if (all.isEmpty()) return emptyList()+    val location = if (category == NewsCategory.LOCAL) {+        runCatching { backend.localLocation() }.getOrNull()+    } else {+        null+    }+    val grouped = StoryGrouping.group(all.map { it.toFeedArticle() })+        .filter { category == null || it.matchesFeedFilter(category, location) }+    return FeedRanking.rankGroupedStories(grouped)+        .take(clampLimit(input.limit))+        .map { it.toHeadline() }+}++internal suspend fun getStory(+    input: NewsStoryQuery,+    backend: NewsAssistantBackend,+): NewsStoryData {+    val wanted = input.storyId.trim()+    if (wanted.isEmpty()) return NewsStoryData()+    val all = runCatching { backend.cachedArticles() }.getOrDefault(emptyList())+    val story = StoryGrouping.group(all.map { it.toFeedArticle() })+        .firstOrNull { it.id == wanted || it.serverStoryId == wanted }+        ?: return NewsStoryData(storyId = wanted)+    return NewsStoryData(+        storyId = story.id,+        title = story.title.take(MAX_HEADLINE_TITLE_CHARS),+        oneLiner = story.oneLiner?.take(MAX_STORY_ONE_LINER_CHARS),+        members = story.articles.take(MAX_STORY_MEMBERS).map { article ->+            NewsStoryMemberData(+                title = article.title.take(MAX_HEADLINE_TITLE_CHARS),+                sourceName = SourceCatalog.byId(article.sourceId)?.name ?: article.sourceId,+                publishedAtMillis = article.publishedAtMillis,+                url = article.url,+            )+        },+    )+}++internal suspend fun readArticle(+    input: NewsArticleQuery,+    backend: NewsAssistantBackend,+): NewsArticleExcerptData {+    val url = input.url.trim()+    if (url.isEmpty()) return NewsArticleExcerptData()+    val extracted = runCatching { backend.articleBody(url) }+        .getOrElse { return NewsArticleExcerptData(title = "", excerpt = "") }+    return articleExcerpt(extracted, input.offset)+}++/** Pure paging over one extracted article: joined block text, one capped page. */+internal fun articleExcerpt(extracted: ExtractedArticle, offset: Int): NewsArticleExcerptData {+    val text = extracted.blocks.joinToString("\n\n") { block ->+        when (block) {+            is ArticleBlock.Paragraph -> block.text+            is ArticleBlock.Heading -> block.text+            is ArticleBlock.Image -> ""+        }+    }.trim()+    val from = offset.coerceAtLeast(0).coerceAtMost(text.length)+    val excerpt = text.drop(from).take(MAX_ARTICLE_EXCERPT_CHARS)+    val next = (from + excerpt.length).takeIf { it < text.length }+    return NewsArticleExcerptData(+        title = extracted.title.take(MAX_HEADLINE_TITLE_CHARS),+        byline = extracted.byline,+        excerpt = excerpt,+        nextOffset = next,+    )+}
news/src/main/java/com/vayunmathur/news/intents/ReadArticleIntent.kt
diff --git a/news/src/main/java/com/vayunmathur/news/intents/ReadArticleIntent.kt b/news/src/main/java/com/vayunmathur/news/intents/ReadArticleIntent.ktnew file mode 100644index 0000000000..3f7aecfffd--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/intents/ReadArticleIntent.kt@@ -0,0 +1,14 @@+package com.vayunmathur.news.intents++import com.vayunmathur.library.intents.news.NewsArticleQuery+import com.vayunmathur.library.intents.news.NewsArticleExcerptData+import com.vayunmathur.library.util.AssistantIntent++/** Assistant tool: One capped page of an extracted article (`news_read_article`). Validated and clamped provider-side in [NewsAssistantBackend]. */+class ReadArticleIntent : AssistantIntent<NewsArticleQuery, NewsArticleExcerptData>(+    NewsArticleQuery.serializer(),+    NewsArticleExcerptData.serializer(),+) {+    override suspend fun performCalculation(input: NewsArticleQuery): NewsArticleExcerptData =+        readArticle(input, newsAssistantBackend(this))+}
news/src/main/java/com/vayunmathur/news/intents/SearchHeadlinesIntent.kt
diff --git a/news/src/main/java/com/vayunmathur/news/intents/SearchHeadlinesIntent.kt b/news/src/main/java/com/vayunmathur/news/intents/SearchHeadlinesIntent.ktnew file mode 100644index 0000000000..e014b9dfbf--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/intents/SearchHeadlinesIntent.kt@@ -0,0 +1,15 @@+package com.vayunmathur.news.intents++import com.vayunmathur.library.intents.news.NewsSearchQuery+import com.vayunmathur.library.intents.news.NewsHeadlineData+import com.vayunmathur.library.util.AssistantIntent+import kotlinx.serialization.builtins.ListSerializer++/** Assistant tool: Search cached headlines by text (`news_search_headlines`). Validated and clamped provider-side in [NewsAssistantBackend]. */+class SearchHeadlinesIntent : AssistantIntent<NewsSearchQuery, List<NewsHeadlineData>>(+    NewsSearchQuery.serializer(),+    ListSerializer(NewsHeadlineData.serializer()),+) {+    override suspend fun performCalculation(input: NewsSearchQuery): List<NewsHeadlineData> =+        searchHeadlines(input, newsAssistantBackend(this))+}
news/src/main/java/com/vayunmathur/news/intents/TopStoriesIntent.kt
diff --git a/news/src/main/java/com/vayunmathur/news/intents/TopStoriesIntent.kt b/news/src/main/java/com/vayunmathur/news/intents/TopStoriesIntent.ktnew file mode 100644index 0000000000..d2e10ffb47--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/intents/TopStoriesIntent.kt@@ -0,0 +1,15 @@+package com.vayunmathur.news.intents++import com.vayunmathur.library.intents.news.NewsTopQuery+import com.vayunmathur.library.intents.news.NewsHeadlineData+import com.vayunmathur.library.util.AssistantIntent+import kotlinx.serialization.builtins.ListSerializer++/** Assistant tool: Feed-ranked top stories of the cached feed (`news_top_stories`). Validated and clamped provider-side in [NewsAssistantBackend]. */+class TopStoriesIntent : AssistantIntent<NewsTopQuery, List<NewsHeadlineData>>(+    NewsTopQuery.serializer(),+    ListSerializer(NewsHeadlineData.serializer()),+) {+    override suspend fun performCalculation(input: NewsTopQuery): List<NewsHeadlineData> =+        topStories(input, newsAssistantBackend(this))+}
news/src/test/java/com/vayunmathur/news/intents/NewsAssistantBackendTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/intents/NewsAssistantBackendTest.kt b/news/src/test/java/com/vayunmathur/news/intents/NewsAssistantBackendTest.ktnew file mode 100644index 0000000000..22b32690c0--- /dev/null+++ b/news/src/test/java/com/vayunmathur/news/intents/NewsAssistantBackendTest.kt@@ -0,0 +1,125 @@+package com.vayunmathur.news.intents++import com.vayunmathur.library.intents.news.NewsArticleQuery+import com.vayunmathur.library.intents.news.NewsSearchQuery+import com.vayunmathur.library.intents.news.NewsStoryQuery+import com.vayunmathur.library.intents.news.NewsTopQuery+import com.vayunmathur.news.data.CachedArticle+import com.vayunmathur.news.domain.ArticleBlock+import com.vayunmathur.news.domain.ExtractedArticle+import kotlinx.coroutines.runBlocking+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Provider-side caps for the news assistant intents, over a fake backend (no Room/network). */+class NewsAssistantBackendTest {++    private fun article(+        url: String,+        sourceId: String = "bbc",+        title: String = "Title $url",+        published: Long = 1_000L,+        storyId: String? = null,+        oneLiner: String? = null,+        storyTitle: String? = null,+    ) = CachedArticle(+        url = url, sourceId = sourceId, title = title, publishedAtMillis = published,+        storyId = storyId, storyOneLiner = oneLiner, storyTitle = storyTitle,+    )++    private class FakeBackend(+        private val all: List<CachedArticle>,+        private val hits: List<CachedArticle> = all,+        private val body: ExtractedArticle = ExtractedArticle(url = "", title = ""),+    ) : NewsAssistantBackend {+        override suspend fun search(query: String): List<CachedArticle> = hits+        override suspend fun cachedArticles(): List<CachedArticle> = all+        override suspend fun articleBody(url: String): ExtractedArticle = body.copy(url = url)+        override suspend fun localLocation(): String? = null+    }++    @Test fun searchClampsLimitAndTruncatesFields() = runBlocking {+        val longTitle = "T".repeat(300)+        val longLiner = "L".repeat(300)+        val all = (1..15).map { i ->+            article("https://e/$i", title = longTitle, storyId = "s$i", oneLiner = longLiner)+        }+        val out = searchHeadlines(NewsSearchQuery("x", limit = 99), FakeBackend(all))+        assertEquals(MAX_NEWS_LIMIT, out.size)+        assertTrue(out.all { it.title.length <= MAX_HEADLINE_TITLE_CHARS })+        assertTrue(out.all { (it.oneLiner?.length ?: 0) <= MAX_HEADLINE_ONE_LINER_CHARS })+    }++    @Test fun searchDefaultsAndRejectsBlankOrBadCategory() = runBlocking {+        val all = listOf(article("https://e/1"))+        assertTrue(searchHeadlines(NewsSearchQuery("  "), FakeBackend(all)).isEmpty())+        assertTrue(searchHeadlines(NewsSearchQuery("x", category = "NOPE"), FakeBackend(all)).isEmpty())+        assertEquals(1, searchHeadlines(NewsSearchQuery("x", limit = 0), FakeBackend(all)).size)+    }++    @Test fun topStoriesFeedRankedAndCategoryFiltered() = runBlocking {+        // Story A: 2 sources (bbc+guardian, WORLD). Story B: 1 tech source, newer.+        val all = listOf(+            article("https://e/a1", "bbc", published = 100, storyId = "A"),+            article("https://e/a2", "guardian", published = 90, storyId = "A"),+            article("https://e/b1", "techcrunch", published = 999, storyId = "B"),+        )+        val top = topStories(NewsTopQuery(limit = 10), FakeBackend(all))+        assertEquals(listOf("srv:A", "srv:B"), top.map { it.storyId })+        val tech = topStories(NewsTopQuery(category = "TECHNOLOGY", limit = 10), FakeBackend(all))+        assertEquals(listOf("srv:B"), tech.map { it.storyId })+        assertTrue(topStories(NewsTopQuery(category = "BAD"), FakeBackend(all)).isEmpty())+    }++    @Test fun getStoryCapsMembersAndOneLiner() = runBlocking {+        val members = (1..12).map { i ->+            article("https://e/m$i", published = i.toLong(), storyId = "S", oneLiner = "L".repeat(400))+        }+        val out = getStory(NewsStoryQuery("S"), FakeBackend(members))+        assertEquals("srv:S", out.storyId)+        assertEquals(MAX_STORY_MEMBERS, out.members.size)+        assertTrue((out.oneLiner?.length ?: 0) <= MAX_STORY_ONE_LINER_CHARS)+        // Raw server id and srv:-prefixed id both resolve; unknown id is an empty story.+        assertEquals(MAX_STORY_MEMBERS, getStory(NewsStoryQuery("srv:S"), FakeBackend(members)).members.size)+        assertTrue(getStory(NewsStoryQuery("missing"), FakeBackend(members)).members.isEmpty())+    }++    @Test fun readArticlePagesByOffsetAndNeverReturnsWholeBody() = runBlocking {+        val text = "a".repeat(7_000)+        val body = ExtractedArticle(+            url = "https://e/a", title = "T".repeat(300),+            blocks = listOf(ArticleBlock.Paragraph(text)),+        )+        val backend = FakeBackend(emptyList(), body = body)+        val page1 = readArticle(NewsArticleQuery("https://e/a", offset = 0), backend)+        assertEquals(MAX_ARTICLE_EXCERPT_CHARS, page1.excerpt.length)+        assertEquals(MAX_ARTICLE_EXCERPT_CHARS, page1.nextOffset)+        assertTrue(page1.title.length <= MAX_HEADLINE_TITLE_CHARS)+        val page2 = readArticle(NewsArticleQuery("https://e/a", offset = page1.nextOffset!!), backend)+        assertEquals(MAX_ARTICLE_EXCERPT_CHARS, page2.excerpt.length)+        assertEquals(2 * MAX_ARTICLE_EXCERPT_CHARS, page2.nextOffset)+        val page3 = readArticle(NewsArticleQuery("https://e/a", offset = page2.nextOffset!!), backend)+        assertEquals(1_000, page3.excerpt.length)+        assertNull(page3.nextOffset)+        // Negative / past-end offsets clamp instead of throwing.+        assertEquals(page1.excerpt, readArticle(NewsArticleQuery("https://e/a", offset = -5), backend).excerpt)+        assertEquals("", readArticle(NewsArticleQuery("https://e/a", offset = 99_999), backend).excerpt)+        assertTrue(readArticle(NewsArticleQuery("  "), backend).excerpt.isEmpty())+    }++    @Test fun articleExcerptJoinsBlocksInOrder() {+        val body = ExtractedArticle(+            url = "https://e/a", title = "Head",+            blocks = listOf(+                ArticleBlock.Heading("Intro"),+                ArticleBlock.Paragraph("Body text"),+                ArticleBlock.Image("https://e/img"),+            ),+        )+        val out = articleExcerpt(body, 0)+        assertEquals("Intro\n\nBody text", out.excerpt)+        assertNull(out.nextOffset)+    }+}
openassistant/AGENTS.md
diff --git a/openassistant/AGENTS.md b/openassistant/AGENTS.mdindex 5b41ca093f..cec9c1de4d 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 `education_get_progress` via `AssistantCoreToolIntents.getEducationProgress` + `summarizeEducationProgress` (aggregates only, deadlines capped at 5, titles at 120 chars)+- 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/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 2f33204a2b..d658d0e1b7 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.education.permissions.ACCESS_EDUCATION" />+    <uses-permission android:name="com.vayunmathur.news.permissions.ACCESS_NEWS" />      <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.education" />+        <package android:name="com.vayunmathur.news" />     </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 d8c84507cf..8cc3b855e7 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 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' if no due time given.|title^S^1^~due^N^0^optional due time as epoch milliseconds~notes^S^0^~priority^N^0^optional priority, 1 (highest) to 4-complete_todo|C|Mark a task done (requires confirmation). Should only be used with EXPLICIT request by user.|id^S^0^task id from get_todos~title^S^0^exact task title, used when no id is given+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 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 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_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_family_locations|-|Get a list of family members and their current locations|-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^+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^ 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,38 +73,41 @@ 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 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_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_timer|C|Start a countdown timer in the Clock app for a number of seconds (requires confirmation).|seconds^N^1^timer length in seconds~label^S^0^optional label for the timer set_conversation_title|-|Set title of current conversation. Mandatory for first response|new_title^S^1^-get_weather|-|Get the current weather conditions at a specific latitude/longitude.|latitude^N^1^~longitude^N^1^-get_weather_by_name|-|Get the current weather conditions for a named place (city, address, landmark).|location^S^1^city or place name-render_ui|-|Render a rich UI card (A2UI) attached to your reply; prefer over a ```a2ui fence. components_json: {"components":[...]} (or bare array) using RICH UI types; data_json: optional data object.|components_json^S^1^A2UI components JSON string~data_json^S^0^optional data model JSON object string-get_directions|-|Get Maps directions between two coordinates: distance, duration, segment count.|from_lat^N^1^origin latitude~from_lng^N^1^origin longitude~to_lat^N^1^destination latitude~to_lng^N^1^destination longitude~mode^S^0^drive (default), transit, walk, or bicycle+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 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; web_read_result reads the best ones.|query^S^1^search query~count^N^0^optional result count, 1-10 (default 5)~kind^S^0^optional: text (default) or news-web_read|-|Read a web page by URL and return its extracted text.|url^S^1^page URL to read-web_read_result|-|Read a result from the last web_search by its 1-based index.|index^N^1^1-based index into the last web_search results~offset^N^0^optional character offset for long pages-find_conversations|-|Find Communicate conversations by name, number or snippet. Returns thread_key values for get_conversation_messages.|query^S^0^name, number or text to search (blank lists recent)~limit^N^0^optional max conversations 1-50 (default 5)-get_conversation_messages|-|Get recent messages 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 (recipient, line, draft body). Sends nothing; the user edits and taps Send, which asks for confirmation first.|recipient_name^S^0^recipient display name~address^S^1^recipient phone number or address~line^S^1^Sim, Rcs, WhatsApp, Signal, or GoogleVoice~body^S^1^draft message text~thread_remote_id^S^0^optional existing thread id to reply into-send_message_v2|C|Send via Communicate (requires confirmation, EXPLICIT request only). GoogleVoice: 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 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 ([{"itemId":1,"qty":2,"modifierIds":[]}]). Re-validated, 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 current cart (pickup or delivery) without creating an order; returns the summary the user confirms in FoodDelivery.|merchant_id^N^1^merchant id of the cart~is_pickup^N^0^1 for pickup, 0 (default) for delivery~address_id^S^0^optional saved address id~tip_cents^N^0^optional tip in cents~promo^S^0^optional promo code-place_food_order|H|Show the current cart's 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|-|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 with the user before adding it to the cart.|shop_domain^S^1^store domain from search_products~product_id^S^1^product id from search_products~variant_id^S^0^optional variant to price-shop_get_cart|-|Get the current Shop cart, grouped by store|-shop_add_to_cart|L|Add an exact variant to the Shop cart (re-verified first, shown back; no checkout).|shop_domain^S^1^store domain from search_products~variant_id^S^1^exact variant id from get_product_detail~quantity^N^0^quantity 1-99 (default 1)-shop_remove_from_cart|L|Remove a variant from the Shop cart; the cart is shown back to the user.|variant_id^S^1^variant id to remove-start_shop_checkout|H|Show one store's cart summary. User checks out in Shop; 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|-education_get_progress|-|Education progress by course/subject, streak, upcoming deadlines (aggregates only)|+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_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/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 72571df35f..61e2cea225 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt@@ -9,7 +9,6 @@ import com.vayunmathur.library.intents.calendar.EventData import com.vayunmathur.library.intents.clock.SetAlarmData import com.vayunmathur.library.intents.clock.SetTimerData import com.vayunmathur.library.intents.contacts.ContactData-import com.vayunmathur.library.intents.education.EducationProgressData import com.vayunmathur.library.intents.email.EmailData import com.vayunmathur.library.intents.email.EmailSearchQuery import com.vayunmathur.library.intents.findfamily.FamilyMemberData@@ -52,9 +51,17 @@ 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.ScreentimeUsageData 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.openassistant.data.Memory import com.vayunmathur.openassistant.data.MemoryDao import kotlinx.datetime.TimeZone@@ -95,7 +102,7 @@ internal class AssistantToolIntents(context: Context) : AssistantCoreToolIntents             "com.vayunmathur.fooddelivery" to "FoodDelivery",             "com.vayunmathur.communicate" to "Communicate",             "com.vayunmathur.shop" to "Shop",-            "com.vayunmathur.education" to "Education",+            "com.vayunmathur.news" to "News",         )          fun getMissingAppMessage(packageName: String): String {@@ -229,6 +236,34 @@ 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",@@ -315,32 +350,6 @@ fun summarizeDirections(result: DirectionsResult): String {     return "Route: $dist, $dur, ${result.segments.size} segment(s), ${result.polyline.size} point(s)" } -/**- * Aggregates-only education summary for the model: per-course/per-subject- * counts, streak/stars, and upcoming deadlines (host re-caps the list and- * re-truncates titles, so no content beyond the provider DTO can appear).- */-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. */ fun summarizeRideEstimate(result: RideEstimateResult): String =     if (!result.available) {@@ -510,6 +519,36 @@ 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"@@ -564,3 +603,26 @@ fun formatUsageDuration(millis: Long): String { }  /** 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 2c65b84b67..5f0dcc9b90 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt@@ -449,6 +449,40 @@ 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")) }
openassistant/src/test/java/com/vayunmathur/openassistant/domain/PromptBudgetTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/PromptBudgetTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/PromptBudgetTest.ktindex b998ee4ecb..135e9d1e30 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(55, ASSISTANT_TOOL_SPECS.size)+        assertEquals(58, 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 eec6d828b9..0da6f2c2f4 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt@@ -44,7 +44,7 @@ class AssistantToolsInvokeTest {         assertEquals("Error: create_note needs title", call("create_note", "content" to "x"))         assertTrue(             call("set_timer", "seconds" to "abc").contains("must be a number"))-        assertEquals(55, tools.declarations.size)+        assertEquals(58, tools.declarations.size)     }      @Test fun crossAppToolsReportMissingApps() {
openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.ktindex d44eb7985c..885015e250 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt@@ -14,7 +14,7 @@ class AssistantToolsTest {     @Test     fun namesAreUniqueSnakeCase() {         val names = ASSISTANT_TOOL_SPECS.map { it.name }-        assertEquals(55, names.size)+        assertEquals(58, names.size)         assertEquals(names.size, names.toSet().size)         for (spec in ASSISTANT_TOOL_SPECS) {             assertTrue(snake.matches(spec.name), spec.name)@@ -68,6 +68,7 @@ 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/NewsToolsSummarizeTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/NewsToolsSummarizeTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/NewsToolsSummarizeTest.ktnew file mode 100644index 0000000000..f02a6cc7f5--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/NewsToolsSummarizeTest.kt@@ -0,0 +1,57 @@+package com.vayunmathur.openassistant.platform++import com.vayunmathur.library.intents.news.NewsArticleExcerptData+import com.vayunmathur.library.intents.news.NewsHeadlineData+import com.vayunmathur.library.intents.news.NewsStoryData+import com.vayunmathur.library.intents.news.NewsStoryMemberData+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Host summarizers for the news tools re-clamp every field before it reaches the model. */+class NewsToolsSummarizeTest {++    @Test fun headlinesCapCountAndFields() {+        val list = (1..15).map { i ->+            NewsHeadlineData(+                storyId = "srv:$i", url = "https://e/$i", title = "T".repeat(300),+                sourceCount = 2, oneLiner = "L".repeat(300),+            )+        }+        val out = summarizeNewsHeadlines(list)+        assertEquals(10, out.lines().size)+        assertTrue(out.lines().all { it.length <= 500 })+        assertEquals("No headlines found", summarizeNewsHeadlines(emptyList()))+    }++    @Test fun storyCapsMembersAndOneLiner() {+        val data = NewsStoryData(+            storyId = "srv:S", title = "T".repeat(300), oneLiner = "L".repeat(400),+            members = (1..12).map { NewsStoryMemberData("M".repeat(300), "BBC", 1L, "https://e/$it") },+        )+        val out = summarizeNewsStory(data)+        // header (title + one-liner) + 8 member lines+        assertEquals(10, out.lines().size)+        assertEquals("No story found for story_id=x", summarizeNewsStory(NewsStoryData(storyId = "x")))+    }++    @Test fun articleCapsExcerptAndShowsNextOffset() {+        val data = NewsArticleExcerptData(+            title = "T".repeat(300), excerpt = "a".repeat(5_000), nextOffset = 3_000,+        )+        val out = summarizeNewsArticle(data)+        assertTrue(out.contains("a".repeat(3_000)))+        assertTrue(!out.contains("a".repeat(3_001)))+        assertTrue(out.contains("offset=3000"))+        assertEquals("Article unavailable", summarizeNewsArticle(NewsArticleExcerptData()))+    }++    @Test fun newsToolsAreRegistered() {+        val names = com.vayunmathur.openassistant.domain.ASSISTANT_TOOL_SPECS.map { it.name }+        assertTrue(+            names.containsAll(+                listOf("news_search_headlines", "news_top_stories", "news_get_story", "news_read_article"),+            ),+        )+    }+}