Modern Apps git

← Modern-Apps.git

openassistant: cap existing tool outputs against context floods

Commit
be95e38437eaf093d14c3077d0620f6455fbfc9f
Author
Vayun Mathur <[email protected]>
When
2026-12-02 05:07 UTC (4 days ago)
Parents
c5a2238
Host summarizers in AssistantToolIntents (summarizeNotes/Contacts/
CalendarEvents/Todos/FamilyLocations/MusicResults/Emails/AppList/
Memories) replace raw .toString() returns: each caps item count and
per-field chars, states its max size in constants, and appends an
'…and N more' notice instead of silently dropping. Provider-side
clamps where the audit puts them: notes 50×(120/300), contacts 200,
calendar 500→50, email body 2000→300 + 10 results, music 20 total,
findfamily 50. Spec descriptions state the caps and
get_conversation_messages clamps 100→50; PromptBudget stays green.
get_app_list sorts and caps 100; get_memories returns last 100.

Tests: new AssistantCapsTest pins every cap (count, field length,
notice); EmailIntentsTest updated 2000→300; AssistantToolsInvokeTest
updated for the new app-list format.

Verified: :openassistant:lint :openassistant:lintVitalRelease
:openassistant:testDevUnitTest green; provider lints green except
pre-existing :music:lint UI errors (DialogAsRoute/
RouteScreenshotCoverage in untouched files); provider tests green
except pre-existing calendar/contacts UI test failures, also in
untouched files.

Diff

calendar/src/main/java/com/vayunmathur/calendar/intents/GetIntent.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/intents/GetIntent.kt b/calendar/src/main/java/com/vayunmathur/calendar/intents/GetIntent.ktindex ad03979c81..a709d87ad1 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/intents/GetIntent.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/intents/GetIntent.kt@@ -29,6 +29,6 @@ class GetIntent: AssistantIntent<Unit, List<EventData>>(serializer<Unit>(), seri     }      private companion object {-        const val MAX_RESULTS = 500+        const val MAX_RESULTS = 50     } }
contacts/src/main/java/com/vayunmathur/contacts/intents/GetIntent.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/intents/GetIntent.kt b/contacts/src/main/java/com/vayunmathur/contacts/intents/GetIntent.ktindex 9543e7a842..05b2dffcba 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/intents/GetIntent.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/intents/GetIntent.kt@@ -10,6 +10,11 @@ import kotlinx.serialization.serializer /** Assistant intent returning every contact's name and phone number from the provider. */ class GetIntent: AssistantIntent<Unit, List<ContactData>>(serializer<Unit>(), serializer<List<ContactData>>()) { +    private companion object {+        /** Binder guard: sorted provider query, hard cap (host steers to search_contacts). */+        const val MAX_RESULTS = 200+    }+     override suspend fun performCalculation(input: Unit): List<ContactData> {         val contacts = mutableListOf<ContactData>()         contentResolver.query(@@ -30,6 +35,6 @@ class GetIntent: AssistantIntent<Unit, List<ContactData>>(serializer<Unit>(), se                 ))             }         }-        return contacts+        return contacts.take(MAX_RESULTS)     } }
email/src/main/java/com/vayunmathur/email/intents/EmailDataMapper.kt
diff --git a/email/src/main/java/com/vayunmathur/email/intents/EmailDataMapper.kt b/email/src/main/java/com/vayunmathur/email/intents/EmailDataMapper.ktindex db00c31497..a8bde6657b 100644--- a/email/src/main/java/com/vayunmathur/email/intents/EmailDataMapper.kt+++ b/email/src/main/java/com/vayunmathur/email/intents/EmailDataMapper.kt@@ -4,7 +4,8 @@ import com.vayunmathur.email.data.EmailMessage import com.vayunmathur.email.data.plainTextBody import com.vayunmathur.library.intents.email.EmailData -private const val EMAIL_DATA_BODY_SNIPPET_LEN = 2000+/** List-view excerpt only: 300 chars (was 2000; 30 × 2000 flooded the context window). */+const val EMAIL_DATA_BODY_SNIPPET_LEN = 300  fun EmailMessage.toEmailData() = EmailData(     subject = subject,
email/src/main/java/com/vayunmathur/email/intents/GetRecentIntent.kt
diff --git a/email/src/main/java/com/vayunmathur/email/intents/GetRecentIntent.kt b/email/src/main/java/com/vayunmathur/email/intents/GetRecentIntent.ktindex b1e1532519..6654c7cc3d 100644--- a/email/src/main/java/com/vayunmathur/email/intents/GetRecentIntent.kt+++ b/email/src/main/java/com/vayunmathur/email/intents/GetRecentIntent.kt@@ -7,9 +7,10 @@ import kotlinx.serialization.serializer  /** Assistant intent returning the most recent emails for the caller. */ class GetRecentIntent : AssistantIntent<Unit, List<EmailData>>(serializer<Unit>(), serializer<List<EmailData>>()) {+    private companion object { const val MAX_RESULTS = 10 }      override suspend fun performCalculation(input: Unit): List<EmailData> {         val dao = EmailRepository.get(this).getDatabase().queryDao()-        return dao.getRecentInboxMessages().map { it.toEmailData() }+        return dao.getRecentInboxMessages().take(MAX_RESULTS).map { it.toEmailData() }     } }
email/src/main/java/com/vayunmathur/email/intents/SearchIntent.kt
diff --git a/email/src/main/java/com/vayunmathur/email/intents/SearchIntent.kt b/email/src/main/java/com/vayunmathur/email/intents/SearchIntent.ktindex b3dfaaf6d2..80447442b5 100644--- a/email/src/main/java/com/vayunmathur/email/intents/SearchIntent.kt+++ b/email/src/main/java/com/vayunmathur/email/intents/SearchIntent.kt@@ -11,9 +11,10 @@ class SearchIntent : AssistantIntent<EmailSearchQuery, List<EmailData>>(     serializer<EmailSearchQuery>(),     serializer<List<EmailData>>(), ) {+    private companion object { const val MAX_RESULTS = 10 }      override suspend fun performCalculation(input: EmailSearchQuery): List<EmailData> {         val dao = EmailRepository.get(this).getDatabase().queryDao()-        return dao.searchMessages(input.query).map { it.toEmailData() }+        return dao.searchMessages(input.query).take(MAX_RESULTS).map { it.toEmailData() }     } }
email/src/test/java/com/vayunmathur/email/intents/EmailIntentsTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/intents/EmailIntentsTest.kt b/email/src/test/java/com/vayunmathur/email/intents/EmailIntentsTest.ktindex 35c00c91e6..5179fb9b1c 100644--- a/email/src/test/java/com/vayunmathur/email/intents/EmailIntentsTest.kt+++ b/email/src/test/java/com/vayunmathur/email/intents/EmailIntentsTest.kt@@ -90,7 +90,7 @@ class EmailIntentsTest {     @Test     fun `toEmailData caps long bodies at the snippet length`() {         val data = message(9L, body = "x".repeat(2500)).toEmailData()-        assertEquals(2000, data.body!!.length)+        assertEquals(300, data.body!!.length)     }      @Test
findfamily/src/main/java/com/vayunmathur/findfamily/intents/GetIntent.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/intents/GetIntent.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/intents/GetIntent.ktindex ea7b05f609..2e0a78afb0 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/intents/GetIntent.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/intents/GetIntent.kt@@ -10,11 +10,12 @@ import kotlinx.serialization.serializer /** Assistant intent returning family members' names and latest locations. */ class GetIntent :     AssistantIntent<Unit, List<FamilyMemberData>>(serializer<Unit>(), serializer<List<FamilyMemberData>>()) {+    private companion object { const val MAX_RESULTS = 50 }      override suspend fun performCalculation(input: Unit): List<FamilyMemberData> {         val repository = FindFamilyRepository.get(this)         val latestLocations = repository.latestLocationsOnce().associateBy { it.userid }-        return repository.getAllUsers().map { user ->+        return repository.getAllUsers().take(MAX_RESULTS).map { user ->             val location = latestLocations[user.id]             FamilyMemberData(                 user.name,
music/src/main/java/com/vayunmathur/music/intents/SearchIntent.kt
diff --git a/music/src/main/java/com/vayunmathur/music/intents/SearchIntent.kt b/music/src/main/java/com/vayunmathur/music/intents/SearchIntent.ktindex af24ebe34b..0d212f9e64 100644--- a/music/src/main/java/com/vayunmathur/music/intents/SearchIntent.kt+++ b/music/src/main/java/com/vayunmathur/music/intents/SearchIntent.kt@@ -12,7 +12,8 @@ class SearchIntent :     AssistantIntent<String, List<MusicSearchResult>>(         serializer<String>(),         serializer<List<MusicSearchResult>>(),-    ) {+) {+    private companion object { const val MAX_RESULTS = 20 }      override suspend fun performCalculation(input: String): List<MusicSearchResult> {         val repo = MusicRepository.get(this)@@ -28,6 +29,6 @@ class SearchIntent :         val playlists = repo.getAllPlaylists()             .filter { it.name.contains(input, ignoreCase = true) }             .map { MusicSearchResult(it.id, it.name, "playlist") }-        return songs + albums + artists + playlists+        return (songs + albums + artists + playlists).take(MAX_RESULTS)     } }
notes/src/main/java/com/vayunmathur/notes/intents/GetIntent.kt
diff --git a/notes/src/main/java/com/vayunmathur/notes/intents/GetIntent.kt b/notes/src/main/java/com/vayunmathur/notes/intents/GetIntent.ktindex 48cb2a9225..c6e33ec96b 100644--- a/notes/src/main/java/com/vayunmathur/notes/intents/GetIntent.kt+++ b/notes/src/main/java/com/vayunmathur/notes/intents/GetIntent.kt@@ -6,11 +6,17 @@ import com.vayunmathur.notes.data.NotesRepository import kotlinx.serialization.builtins.ListSerializer import kotlinx.serialization.builtins.serializer -/** Assistant intent returning all notes as shared note DTOs. */+/** Assistant intent returning capped notes as shared note DTOs (binder + context guard). */ class GetIntent: AssistantIntent<Unit, List<NoteData>>(Unit.serializer(), ListSerializer(NoteData.serializer())) { +    private companion object {+        const val MAX_RESULTS = 50+        const val MAX_TITLE_CHARS = 120+        const val MAX_CONTENT_CHARS = 300+    }+     override suspend fun performCalculation(input: Unit): List<NoteData> {         val repo = NotesRepository.get(this)-        return repo.getAll().map { NoteData(it.title, it.content) }+        return repo.getAll().take(MAX_RESULTS).map { NoteData(it.title.take(MAX_TITLE_CHARS), it.content.take(MAX_CONTENT_CHARS)) }     } }
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 7511accabb..f68e6f9152 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt@@ -53,23 +53,23 @@ private fun parseToolRisk(field: String): ToolRisk =     }  private const val TOOL_DATA = """-get_notes|-|Get a list of all notes|+get_notes|-|Get notes (max 20, excerpts)| create_note|C|Create a new note in the notes app (requires confirmation). Should only be used with EXPLICIT request by user|title^S^1^~content^S^1^-get_todos|-|Get 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+get_todos|-|Get open tasks (max 50). Due times are epoch ms; id usable with complete_todo.|scope^S^0^today (default), upcoming, or all create_todo|C|Create a task in Todo (requires confirmation, EXPLICIT request only). The title may include 'tomorrow 6pm' or '#tag', understood when no due time is given.|title^S^1^~due^N^0^optional due time as epoch milliseconds~notes^S^0^~priority^N^0^optional priority, 1 (highest) to 4 complete_todo|C|Mark a task done (requires confirmation). Should only be used with EXPLICIT request by user.|id^S^0^task id from get_todos~title^S^0^exact task title, used when no id is given-get_contacts|-|Get a list of all contacts|+get_contacts|-|Get contacts (max 50; prefer search_contacts)| create_contact|C|Create a new contact (requires confirmation)|name^S^1^~phone_number^S^1^-get_calendar_events|-|Get a list of calendar events. Each event's start and end times are epoch milliseconds.|+get_calendar_events|-|Get calendar events (max 50; times are epoch ms)| create_calendar_event|C|Create a new calendar event (requires confirmation). Start and end times must be epoch milliseconds.|title^S^1^~start^N^1^start time as epoch milliseconds~end^N^1^end time as epoch milliseconds~location^S^0^-get_family_locations|-|Get a list of family members and their current locations|+get_family_locations|-|Get family locations (max 50)| create_location_share_link|C|Create a temporary FindFamily link that shares the user's live location (requires confirmation).|name^S^1^name or label for who the link is for~duration_millis^N^1^how long the link stays active, in milliseconds-search_music|-|Search for music (songs, albums, artists, or playlists)|query^S^1^+search_music|-|Search music (max 20)|query^S^1^ play_music|C|Play music given its id and type (song, album, artist, or playlist) (requires confirmation)|id^N^1^~type^S^1^-search_emails|-|Search emails by keyword|query^S^1^-get_recent_emails|-|Get recent emails from the inbox|+search_emails|-|Search emails (max 10, excerpts)|query^S^1^+get_recent_emails|-|Get recent emails (max 10, excerpts)| get_local_current_date_time|-|Get the current date and time in the local timezone.|-get_app_list|-|Get a list of installed apps on the device|+get_app_list|-|Get installed apps (max 100)| open_app|-|Open an app given its package id|package_id^S^1^package id send_message|-|Send a message|recipient^S^1^~message^S^1^ make_phone_call|-|Make a phone call|recipient^S^1^@@ -89,7 +89,7 @@ web_search|-|Search the web for current/external facts. Returns numbered results web_read|-|Read a web page by URL and return its extracted text.|url^S^1^page URL to read web_read_result|-|Read a result from the last web_search by its 1-based index.|index^N^1^1-based index into the last web_search results~offset^N^0^optional character offset for long pages find_conversations|-|Find Communicate conversations by name, number or snippet. Returns thread_key values for get_conversation_messages.|query^S^0^name, number or text to search (blank lists recent)~limit^N^0^optional max conversations 1-50 (default 5)-get_conversation_messages|-|Get recent messages from a messaging conversation by its thread_key from find_conversations.|thread_key^S^1^thread key like Sim:42 or WhatsApp:[email protected]~limit^N^0^optional max messages 1-100 (default 10)+get_conversation_messages|-|Get recent messages from a messaging conversation by its thread_key from find_conversations.|thread_key^S^1^thread key like Sim:42 or WhatsApp:[email protected]~limit^N^0^optional max messages 1-50 (default 10) draft_message|-|Show a message composer card (recipient, line, draft body). Sends nothing; the user edits and taps Send, which asks for confirmation first.|recipient_name^S^0^recipient display name~address^S^1^recipient phone number or address~line^S^1^Sim, Rcs, WhatsApp, Signal, or GoogleVoice~body^S^1^draft message text~thread_remote_id^S^0^optional existing thread id to reply into send_message_v2|C|Send via Communicate (requires confirmation, EXPLICIT request only). GoogleVoice cannot send here; use draft_message instead.|address^S^1^recipient phone number or address~line^S^1^Sim, Rcs, WhatsApp, Signal, or GoogleVoice~body^S^1^message text~thread_remote_id^S^0^optional existing thread id to reply into find_restaurants|-|Find restaurants near a location via the FoodDelivery app, optionally filtered by name or tag.|query^S^0^optional name or tag filter~lat^N^1^latitude~lng^N^1^longitude~limit^N^0^optional max results (default 5)@@ -106,7 +106,7 @@ shop_add_to_cart|L|Add an exact variant to the Shop cart (re-verified first, sho 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, and opening the cart is not a paid order.|shop_domain^S^1^store domain to check out get_shop_orders|-|Get the user's Shop order summaries|-get_memories|-|Get a list of all memories|+get_memories|-|Get memories (last 100)| 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 4b0f24cb95..ecf57f844a 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt@@ -98,12 +98,14 @@ internal abstract class AssistantCoreToolIntents(         }     } -    suspend fun getNotes(): String = launchIntent<Unit, List<NoteData>>(-        context,-        "com.vayunmathur.notes",-        "com.vayunmathur.notes.intents.GetIntent",-        Unit,-    ).toString()+    suspend fun getNotes(): String = summarizeNotes(+        launchIntent<Unit, List<NoteData>>(+            context,+            "com.vayunmathur.notes",+            "com.vayunmathur.notes.intents.GetIntent",+            Unit,+        ),+    )      suspend fun insertNote(data: NoteData) = launchIntentU(         context,@@ -112,12 +114,14 @@ internal abstract class AssistantCoreToolIntents(         data,     ) -    suspend fun getTodos(query: GetTodosQuery): String = launchIntent<GetTodosQuery, List<TodoData>>(-        context,-        "com.vayunmathur.todo",-        "com.vayunmathur.todo.intents.GetTodosIntent",-        query,-    ).toString()+    suspend fun getTodos(query: GetTodosQuery): String = summarizeTodos(+        launchIntent<GetTodosQuery, List<TodoData>>(+            context,+            "com.vayunmathur.todo",+            "com.vayunmathur.todo.intents.GetTodosIntent",+            query,+        ),+    )      suspend fun insertTodo(data: InsertTodoData): String = launchIntent<InsertTodoData, String>(         context,@@ -133,12 +137,14 @@ internal abstract class AssistantCoreToolIntents(         data,     ) -    suspend fun getContacts(): String = launchIntent<Unit, List<ContactData>>(-        context,-        "com.vayunmathur.contacts",-        "com.vayunmathur.contacts.intents.GetIntent",-        Unit,-    ).toString()+    suspend fun getContacts(): String = summarizeContacts(+        launchIntent<Unit, List<ContactData>>(+            context,+            "com.vayunmathur.contacts",+            "com.vayunmathur.contacts.intents.GetIntent",+            Unit,+        ),+    )      suspend fun insertContact(data: ContactData) = launchIntentU(         context,@@ -147,12 +153,14 @@ internal abstract class AssistantCoreToolIntents(         data,     ) -    suspend fun getCalendarEvents(): String = launchIntent<Unit, List<EventData>>(-        context,-        "com.vayunmathur.calendar",-        "com.vayunmathur.calendar.intents.GetIntent",-        Unit,-    ).toString()+    suspend fun getCalendarEvents(): String = summarizeCalendarEvents(+        launchIntent<Unit, List<EventData>>(+            context,+            "com.vayunmathur.calendar",+            "com.vayunmathur.calendar.intents.GetIntent",+            Unit,+        ),+    )      suspend fun insertCalendarEvent(data: EventData) = launchIntentU(         context,@@ -161,12 +169,14 @@ internal abstract class AssistantCoreToolIntents(         data,     ) -    suspend fun getFamilyLocations(): String = launchIntent<Unit, List<FamilyMemberData>>(-        context,-        "com.vayunmathur.findfamily",-        "com.vayunmathur.findfamily.intents.GetIntent",-        Unit,-    ).toString()+    suspend fun getFamilyLocations(): String = summarizeFamilyLocations(+        launchIntent<Unit, List<FamilyMemberData>>(+            context,+            "com.vayunmathur.findfamily",+            "com.vayunmathur.findfamily.intents.GetIntent",+            Unit,+        ),+    )      suspend fun createLocationShareLink(name: String, durationMillis: Double): String =         launchIntent<CreateLinkRequest, String>(@@ -176,13 +186,14 @@ internal abstract class AssistantCoreToolIntents(             CreateLinkRequest(name, durationMillis.toLong()),         ) -    suspend fun searchMusic(query: String): String =+    suspend fun searchMusic(query: String): String = summarizeMusicResults(         launchIntent<String, List<MusicSearchResult>>(             context,             "com.vayunmathur.music",             "com.vayunmathur.music.intents.SearchIntent",             query,-        ).toString()+        ),+    )      suspend fun playMusic(data: PlayMusicData) = launchIntentU(         context,@@ -191,20 +202,23 @@ internal abstract class AssistantCoreToolIntents(         data,     ) -    suspend fun searchEmails(query: String): String =+    suspend fun searchEmails(query: String): String = summarizeEmails(         launchIntent<EmailSearchQuery, List<EmailData>>(             context,             "com.vayunmathur.email",             "com.vayunmathur.email.intents.SearchIntent",             EmailSearchQuery(query),-        ).toString()+        ),+    ) -    suspend fun getRecentEmails(): String = launchIntent<Unit, List<EmailData>>(-        context,-        "com.vayunmathur.email",-        "com.vayunmathur.email.intents.GetRecentIntent",-        Unit,-    ).toString()+    suspend fun getRecentEmails(): String = summarizeEmails(+        launchIntent<Unit, List<EmailData>>(+            context,+            "com.vayunmathur.email",+            "com.vayunmathur.email.intents.GetRecentIntent",+            Unit,+        ),+    )      suspend fun setAlarm(data: SetAlarmData) = launchIntentU(         context,
openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantDeviceTools.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantDeviceTools.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantDeviceTools.ktindex 97b906a9b1..72bde3de8c 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantDeviceTools.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantDeviceTools.kt@@ -25,11 +25,11 @@ internal class AssistantDeviceTools(private val context: Context) {         // MAIN/LAUNCHER declaration already makes every launchable app visible. A package         // with no launcher entry is not an app the model can open anyway.         val launcher = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)-        return pm.queryIntentActivities(launcher, PackageManager.MATCH_ALL)+        val labels = pm.queryIntentActivities(launcher, PackageManager.MATCH_ALL)             .mapNotNull { it.activityInfo?.applicationInfo }             .distinctBy { it.packageName }             .map { it.loadLabel(pm).toString() }-            .toString()+        return summarizeAppList(labels)     }      fun openApp(packageId: String, onMissing: (String) -> String): String {@@ -79,7 +79,7 @@ internal class AssistantDeviceTools(private val context: Context) {     }      suspend fun getMemories(memoryDao: MemoryDao?): String =-        memoryDao?.getAll()?.joinToString("\n") { "[${it.id}] ${it.content}" }+        memoryDao?.getAll()?.let { summarizeMemories(it) }             ?: "Error: MemoryDao is null"      suspend fun removeMemory(memoryDao: MemoryDao?, id: Double): String {
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 b8b5bb0fb6..2721498413 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt@@ -73,6 +73,36 @@ private const val CONVERSATION_SNIPPET_CHARS = 80 private const val MESSAGE_BODY_CHARS = 200 private const val RESTAURANT_ADDRESS_CHARS = 60 +// Context-flood caps for existing read tools (docs/openassistant-intents-audit.md §3.1).+// Every summarizer below states its max output size; dropped items are announced+// with a "…and N more" line, never silently dropped.+const val MAX_NOTES_SHOWN = 20 // 20 × (120 title + 300 excerpt) ≈ 8.6k chars max+const val NOTE_TITLE_CHARS = 120+const val NOTE_CONTENT_CHARS = 300+const val MAX_CONTACTS_SHOWN = 50 // 50 × ~130 chars ≈ 6.5k chars max+const val CONTACT_NAME_CHARS = 80+const val CONTACT_PHONE_CHARS = 40+const val MAX_EVENTS_SHOWN = 50 // 50 × ~230 chars ≈ 11.5k chars max+const val EVENT_TITLE_CHARS = 120+const val EVENT_LOCATION_CHARS = 80+const val MAX_TODOS_SHOWN = 50 // 50 × ~340 chars ≈ 17k chars worst, typical ≪+const val TODO_TITLE_CHARS = 120+const val TODO_NOTES_CHARS = 200+const val MAX_FAMILY_SHOWN = 50 // 50 × ~230 chars ≈ 11.5k chars max+const val FAMILY_NAME_CHARS = 80+const val FAMILY_LOCATION_CHARS = 120+const val MAX_MUSIC_SHOWN = 20 // 20 × ~140 chars ≈ 2.8k chars max+const val MUSIC_NAME_CHARS = 120+const val MAX_EMAILS_SHOWN = 10 // 10 × ~530 chars ≈ 5.3k chars max (was 30 × 2000 ≈ 66k)+const val EMAIL_SUBJECT_CHARS = 120+const val EMAIL_FROM_CHARS = 80+const val EMAIL_BODY_CHARS = 300+const val MAX_APPS_SHOWN = 100 // 100 × ~85 chars ≈ 8.5k chars max+const val APP_LABEL_CHARS = 80+const val MAX_MEMORIES_SHOWN = 100 // 100 × ~210 chars ≈ 21k chars worst, typical ≪+const val MEMORY_CONTENT_CHARS = 200+const val MAX_CONVERSATION_MESSAGES = 50+ /**  * Intent-launching back end for the assistant tool registry  * ([com.vayunmathur.openassistant.platform.AssistantTools]); every tool@@ -237,10 +267,10 @@ internal class AssistantToolIntents(context: Context) : AssistantCoreToolIntents     )      suspend fun searchContacts(query: String): String =-        filterContacts(query, getContactsList()).toString()+        summarizeContacts(filterContacts(query, getContactsList()))      suspend fun getMemories(memoryDao: MemoryDao?): String =-        memoryDao?.getAll()?.joinToString("\n") { "[${it.id}] ${it.content}" }+        memoryDao?.getAll()?.let { summarizeMemories(it) }             ?: "Error: MemoryDao is null"      suspend fun removeMemory(memoryDao: MemoryDao?, id: Double): String {@@ -289,6 +319,106 @@ suspend inline fun <reified Input : Any, reified Output : Any> launchIntent(     return Json.decodeFromString(serializer<Output>(), stringOutput) } +/** Host-capped notes for the model: at most [MAX_NOTES_SHOWN], each field truncated. */+fun summarizeNotes(list: List<NoteData>): String {+    if (list.isEmpty()) return "No notes found"+    val shown = list.take(MAX_NOTES_SHOWN)+    val lines = shown.joinToString("\n") { n ->+        "- " + n.title.take(NOTE_TITLE_CHARS) + ": " + n.content.take(NOTE_CONTENT_CHARS)+    }+    val more = if (list.size > MAX_NOTES_SHOWN) "\n…and ${list.size - MAX_NOTES_SHOWN} more" else ""+    return lines + more+}++/** Host-capped contacts for the model: at most [MAX_CONTACTS_SHOWN]. */+fun summarizeContacts(list: List<ContactData>): String {+    if (list.isEmpty()) return "No contacts found"+    val shown = list.take(MAX_CONTACTS_SHOWN)+    val lines = shown.joinToString("\n") { c ->+        "- " + c.name.take(CONTACT_NAME_CHARS) + " " + c.phoneNumber.take(CONTACT_PHONE_CHARS)+    }+    val more = if (list.size > MAX_CONTACTS_SHOWN) "\n…and ${list.size - MAX_CONTACTS_SHOWN} more" else ""+    return lines + more+}++/** Host-capped calendar events for the model: at most [MAX_EVENTS_SHOWN]. */+fun summarizeCalendarEvents(list: List<EventData>): String {+    if (list.isEmpty()) return "No calendar events found"+    val shown = list.take(MAX_EVENTS_SHOWN)+    val lines = shown.joinToString("\n") { e ->+        "- " + e.title.take(EVENT_TITLE_CHARS) + " [" + e.start + ".." + e.end + "] " ++            e.location.take(EVENT_LOCATION_CHARS)+    }+    val more = if (list.size > MAX_EVENTS_SHOWN) "\n…and ${list.size - MAX_EVENTS_SHOWN} more" else ""+    return lines + more+}++/** Host-capped todos for the model: at most [MAX_TODOS_SHOWN] (provider binder cap stays 200). */+fun summarizeTodos(list: List<TodoData>): String {+    if (list.isEmpty()) return "No tasks found"+    val shown = list.take(MAX_TODOS_SHOWN)+    val lines = shown.joinToString("\n") { t ->+        "- [" + t.id + "] " + t.title.take(TODO_TITLE_CHARS) ++            (t.dueAt?.let { " due=$it" } ?: "") ++            (if (t.notes.isNotBlank()) " " + t.notes.take(TODO_NOTES_CHARS) else "")+    }+    val more = if (list.size > MAX_TODOS_SHOWN) "\n…and ${list.size - MAX_TODOS_SHOWN} more" else ""+    return lines + more+}++/** Host-capped family locations for the model: at most [MAX_FAMILY_SHOWN]. */+fun summarizeFamilyLocations(list: List<FamilyMemberData>): String {+    if (list.isEmpty()) return "No family members found"+    val shown = list.take(MAX_FAMILY_SHOWN)+    val lines = shown.joinToString("\n") { m ->+        "- " + m.name.take(FAMILY_NAME_CHARS) + " @ " ++            m.locationName.take(FAMILY_LOCATION_CHARS) + " (" + m.lat + "," + m.lon + ")"+    }+    val more = if (list.size > MAX_FAMILY_SHOWN) "\n…and ${list.size - MAX_FAMILY_SHOWN} more" else ""+    return lines + more+}++/** Host-capped music hits for the model: at most [MAX_MUSIC_SHOWN]. */+fun summarizeMusicResults(list: List<MusicSearchResult>): String {+    if (list.isEmpty()) return "No music found"+    val shown = list.take(MAX_MUSIC_SHOWN)+    val lines = shown.joinToString("\n") { r -> "- [" + r.type + " id=" + r.id + "] " + r.name.take(MUSIC_NAME_CHARS) }+    val more = if (list.size > MAX_MUSIC_SHOWN) "\n…and ${list.size - MAX_MUSIC_SHOWN} more" else ""+    return lines + more+}++/** Host-capped emails for the model: at most [MAX_EMAILS_SHOWN], body excerpt only. */+fun summarizeEmails(list: List<EmailData>): String {+    if (list.isEmpty()) return "No emails found"+    val shown = list.take(MAX_EMAILS_SHOWN)+    val lines = shown.joinToString("\n") { e ->+        "- " + (if (e.isRead) "" else "[unread] ") + e.subject.take(EMAIL_SUBJECT_CHARS) ++            " from " + e.from.take(EMAIL_FROM_CHARS) + " (" + e.date + ")" ++            (e.body?.takeIf { it.isNotBlank() }?.let { ": " + it.take(EMAIL_BODY_CHARS) } ?: "")+    }+    val more = if (list.size > MAX_EMAILS_SHOWN) "\n…and ${list.size - MAX_EMAILS_SHOWN} more" else ""+    return lines + more+}++/** Host-capped app list for the model: sorted, at most [MAX_APPS_SHOWN] labels. */+fun summarizeAppList(labels: List<String>): String {+    if (labels.isEmpty()) return "No apps found"+    val sorted = labels.sorted()+    val shown = sorted.take(MAX_APPS_SHOWN)+    val lines = shown.joinToString("\n") { "- " + it.take(APP_LABEL_CHARS) }+    val more = if (sorted.size > MAX_APPS_SHOWN) "\n…and ${sorted.size - MAX_APPS_SHOWN} more" else ""+    return lines + more+}++/** Host-capped memories for the model: last [MAX_MEMORIES_SHOWN] (ids ascending in, newest last). */+fun summarizeMemories(list: List<Memory>): String {+    if (list.isEmpty()) return "No memories"+    val shown = list.takeLast(MAX_MEMORIES_SHOWN)+    val lines = shown.joinToString("\n") { m -> "[" + m.id + "] " + m.content.take(MEMORY_CONTENT_CHARS) }+    val more = if (list.size > MAX_MEMORIES_SHOWN) "\n…and ${list.size - MAX_MEMORIES_SHOWN} more" else ""+    return lines + more+}+ /** Pure contact filter for `search_contacts`: case-insensitive substring on name/phone, capped. */ fun filterContacts(query: String, contacts: List<ContactData>, cap: Int = 10): List<ContactData> {     val needle = query.trim().lowercase()
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 fbd6d02602..10a7298b22 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt@@ -237,7 +237,8 @@ class AssistantTools(         },         "get_conversation_messages" to { a ->             intents.runTool {-                val limit = a.number("limit").toInt().takeIf { it > 0 } ?: 10+                val limit = (a.number("limit").toInt().takeIf { it > 0 } ?: 10)+                    .coerceAtMost(MAX_CONVERSATION_MESSAGES)                 com.vayunmathur.openassistant.platform.summarizeConversationMessages(                     intents.getConversationMessages(a.string("thread_key"), limit),                 )
openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantCapsTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantCapsTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantCapsTest.ktnew file mode 100644index 0000000000..76c606009e--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantCapsTest.kt@@ -0,0 +1,81 @@+package com.vayunmathur.openassistant.platform++import com.vayunmathur.library.intents.calendar.EventData+import com.vayunmathur.library.intents.contacts.ContactData+import com.vayunmathur.library.intents.email.EmailData+import com.vayunmathur.library.intents.findfamily.FamilyMemberData+import com.vayunmathur.library.intents.music.MusicSearchResult+import com.vayunmathur.library.intents.notes.NoteData+import com.vayunmathur.library.intents.todo.TodoData+import com.vayunmathur.openassistant.data.Memory+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Pins every context-flood cap (audit §3.1): count, per-field chars, truncation notice. */+class AssistantCapsTest {+    @Test fun notesCap() {+        val out = summarizeNotes((1..25).map { NoteData("t".repeat(200), "c".repeat(500)) })+        assertEquals(20, out.lines().count { it.startsWith("- ") })+        assertTrue(out.endsWith("…and 5 more"))+        assertTrue(out.lines().all { it.length <= 2 + NOTE_TITLE_CHARS + 2 + NOTE_CONTENT_CHARS })+    }++    @Test fun contactsCap() {+        val out = summarizeContacts((1..60).map { ContactData("n".repeat(100), "1".repeat(50)) })+        assertEquals(50, out.lines().count { it.startsWith("- ") })+        assertTrue(out.endsWith("…and 10 more"))+    }++    @Test fun calendarCap() {+        val out = summarizeCalendarEvents((1..60).map { EventData("e".repeat(200), 1, 2, "l".repeat(100)) })+        assertEquals(50, out.lines().count { it.startsWith("- ") })+        assertTrue(out.endsWith("…and 10 more"))+    }++    @Test fun todosCap() {+        val out = summarizeTodos((1..60).map { TodoData("$it", "t".repeat(200), "n".repeat(300)) })+        assertEquals(50, out.lines().count { it.startsWith("- ") })+        assertTrue(out.endsWith("…and 10 more"))+    }++    @Test fun familyCap() {+        val out = summarizeFamilyLocations((1..60).map { FamilyMemberData("f".repeat(100), "l".repeat(200), 1.0, 2.0) })+        assertEquals(50, out.lines().count { it.startsWith("- ") })+        assertTrue(out.endsWith("…and 10 more"))+    }++    @Test fun musicCap() {+        val out = summarizeMusicResults((1..30).map { MusicSearchResult(it.toLong(), "m".repeat(200), "song") })+        assertEquals(20, out.lines().count { it.startsWith("- ") })+        assertTrue(out.endsWith("…and 10 more"))+    }++    @Test fun emailsCapCountAndBody() {+        val out = summarizeEmails((1..15).map { EmailData("s".repeat(200), "f".repeat(100), null, "d", "b".repeat(2000), false) })+        assertEquals(10, out.lines().count { it.startsWith("- ") })+        assertTrue(out.endsWith("…and 5 more"))+        // Before: 30 × 2000-char bodies ≈ 66k chars. Now at most 10 × ~530.+        assertTrue(out.length < 6_000, "was ${out.length}")+    }++    @Test fun appListCapSorted() {+        val out = summarizeAppList((1..150).map { "App $it" }.reversed())+        assertEquals(100, out.lines().count { it.startsWith("- ") })+        assertTrue(out.endsWith("…and 50 more"))+        assertTrue(out.lines()[0].contains("App 1"))+    }++    @Test fun memoriesCapLast100() {+        val out = summarizeMemories((1..120).map { Memory("m".repeat(300), it.toLong()) })+        assertEquals(100, out.lines().size - 1)+        assertTrue(out.endsWith("…and 20 more"))+        assertTrue(out.startsWith("[21]"))+    }++    @Test fun noNoticeWhenUnderCap() {+        assertTrue(!summarizeNotes(listOf(NoteData("a", "b"))).contains("more"))+        assertEquals("No notes found", summarizeNotes(emptyList()))+        assertEquals("No emails found", summarizeEmails(emptyList()))+    }+}
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 5234d321e5..bc5e8ba3e8 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt@@ -94,7 +94,8 @@ class AssistantToolsInvokeTest {         val dateTime = call("get_local_current_date_time")         assertTrue(dateTime.contains("epochMillis="), dateTime)         // App list renders whatever Robolectric reports installed (possibly none).-        assertTrue(call("get_app_list").startsWith("["))+        val appList = call("get_app_list")+        assertTrue(appList == "No apps found" || appList.startsWith("- "), appList)         // Unknown package has no launch intent: missing-app handler answers.         assertTrue(             call("open_app", "package_id" to "com.example.absent")