# AGENTS.md — openassistant/ (':openassistant') > Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside `openassistant/` + allowed shared modules. Do not root-scan. _Install: ./install openassistant (dev by default)._ - Gradle: :openassistant / dir: openassistant/ - Package roots present: ui, data, domain, platform, network, service, util - Entry files: MainActivity.kt, Route.kt, Navigation.kt - Deps: :library:room, :library:image, :library:ml, :library:downloadservice, androidx.a2ui (model + engine) - Metadata: metadata_data/openassistant.md (present) - Rust: no / screenshotTest: yes ## Overview **Purpose:** A simple open-source local AI app — Gemma 4 E2B runs fully on device (~3.5GB RAM when active). Internet only for initial asset downloads. **Key features:** - Multiple chats with streaming responses and markdown rendering, persisted in Room - Multimodal input: photo upload and audio recording, read by Gemma 4's vision and audio towers - Tool calling into other Modern Apps over local IPC, with JSON-schema validation - A model-managed memory plus an editable system prompt; can be set as the device's default digital assistant (Assist API + voice interaction service) - Generative UI: replies can carry an A2UI block (cards, forms, buttons) rendered natively; button events come back to the model as user turns **Architecture / data-flow:** `ui/LiteRTChatUi` → `platform/AssistantViewModel` → `data/OpenAssistantRepository` (Room) + `util/InferenceService` → `platform/MamlChatEngine` (Gemma 4 on `:library:ml`'s `Gemma4Handle`; own tool loop, max 6 rounds) with `platform/AssistantTools` (explicit registry over `domain/AssistantToolSpecs`) dispatching IPC tool calls. Turns for different conversations run concurrently in the service (`domain/TurnGate`, max 3 active, same conversation serialised); the engine lock covers model calls only, never tool execution, and streamed replies flow through the bounded `domain/ReplyStreamBuffer` to the DB writer. Pure logic (tool-call parsing/markup stripping, tool loop, WAV decode, history fitting) lives in `domain/` with unit tests. `onCreateBeforeContent` only wires the `IntentLauncher` and picks up Assist-API screen context; `Content()` gates on the initial model download before the chat renders. **Entry points + reading order:** `Route` (`ConversationPage(id)` / `SettingsPage`) → `MainActivity.kt` → `ui/LiteRTChatUi.kt` → `platform/AssistantViewModel.kt` → `util/InferenceService.kt` → `platform/MamlChatEngine.kt` → `data/OpenAssistantRepository.kt`. **Gotchas:** - Chat UI files are `LiteRT*` in `ui/`; device tools and tool intents are in `platform/`, `JsonSchemaValidator` is in `domain/`; the engine entry is `platform/MamlChatEngine` - `MainActivity.intentLauncher` is a shared static other apps mirror (maps/taxi pattern) — keep it initialized in `onCreateBeforeContent` - `StubRecognitionService` is a placeholder voice-recognition hook, not a real recognizer - Tool names are snake_case (`get_notes`, `add_to_memory`, `translate_text`), matching what LiteRT-LM exposed; the system prompt references them. Add a tool in `domain/AssistantToolSpecs.kt` AND `platform/AssistantTools.kt` (an init check fails if they disagree) - Model files live in `getExternalFilesDir(null)/gemma4/` (text, embed, head, vision, audio, tokenizer); the vision/audio towers load lazily and unload after 3 idle minutes - Photo attachments: Send in `ui/LiteRTChatUi` awaits the picker copy jobs before dispatching, so the photos shown in the composer are the files bound to the sent `Message.imagePaths` and the inference request. Stored image paths ride `HistoryTurn.imagePaths` through `domain/HistoryFit` (oldest turns drop whole when the history no longer fits) and are re-encoded by the vision tower on each turn, so a photo stays visible to the model on later turns - `util/` is NOT a closed package root — don't add more files there (it holds only `InferenceService` + its `MessageStore`); assistant surfaces are in `service/` - A2UI: the model writes only ```` ```a2ui {"components":[...],"data":{...}} ```` and `domain/A2uiEnvelope` adds the protocol envelope. Surface id is `m`; the block is stored in `Message.a2ui` (DB v4) and replayed by `platform/A2uiController.sync`. androidx.a2ui ships no renderer — `ui/A2uiSurfaceView` is ours. Add a component in `platform/AssistantCatalog` (schema + prompt line together) AND the `when` in `A2uiSurfaceView` - `AssistantCatalog.PROMPT_SECTION` is appended to every system prompt, so changing it (or the catalog) invalidates the baked `gemma4_prefix.kv`: still correct, but first turns prefill until it is rebaked with `bake_gemma4_prefix` - The system header (default prompt + A2UI section + all tool declarations) is prefilled on every cold turn; `domain/PromptBudgetTest` pins its total size — keep prompt/tool-description edits within that budget - Kept photos are vision-encoded once and cached in the engine (LRU, 4 images ≈ 7 MB of soft tokens, keyed by path+size+mtime); an encode walks the accepted soft-token budgets down from the reference default before a photo is dropped, and a drop is logged — a dropped photo otherwise reads exactly like no photo was sent. The shared `AssistantTools` render-UI stash is consumed by whichever turn finishes next, so concurrent turns should not both rely on it in the same instant ## Key files ### Root — entry + inline navigation - com/vayunmathur/openassistant/MainActivity.kt — Route, Navigation, assist screen-context ### service/ — system assistant surfaces - com/vayunmathur/openassistant/service/OpenAssistantSession.kt — Assist API screen-text capture - com/vayunmathur/openassistant/service/OpenAssistantSessionService.kt - com/vayunmathur/openassistant/service/OpenAssistantVoiceInteractionService.kt - com/vayunmathur/openassistant/service/StubRecognitionService.kt — placeholder recognizer hook ### network/ — web tools - com/vayunmathur/openassistant/network/AssistantWebTools.kt — the app's networking entry point for web tools: `web_search` calls the server's `GET /api/search` (type=text/news) through `NetworkClient` (FIRST_PARTY bundle inited in MainActivity) and reshapes results on device into {title,url,snippet} hits (n<=10); `web_read`/`web_read_result` fetch the page on device (per-request system trust, since page hosts are arbitrary) and extract readable text locally via `domain/WebPageExtractor` — http/https only, localhost/.local/private IP literals refused, 10s timeouts, 2M-char body cap, 6000-char pages paged by character offset. Extracts are cached process-wide (LRU, 4 pages × 24k chars, raw HTML never retained) so paging or re-reading a page fetches once. Tool failures are typed `Error: ...` strings, never silent empties ### data/ — chats + repository - com/vayunmathur/openassistant/data/Database.kt — `DB_NAME` (`passwords-db`) + `openAssistantDbConfigs` for the backup agent - com/vayunmathur/openassistant/data/OpenAssistantRepository.kt ### ui/ — chat + settings - com/vayunmathur/openassistant/ui/LiteRTChatUi.kt - com/vayunmathur/openassistant/ui/LiteRTChatScreen.kt - com/vayunmathur/openassistant/ui/LiteRTChatBubble.kt - com/vayunmathur/openassistant/ui/LiteRTChatInput.kt - com/vayunmathur/openassistant/ui/SettingsPage.kt - com/vayunmathur/openassistant/ui/A2uiSurfaceView.kt — Compose renderer for A2UI surfaces ### domain/ — pure, unit-tested - com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt — tool names/descriptions/params - com/vayunmathur/openassistant/domain/ToolCalls.kt — call parsing, markup stripping, arg coercion - com/vayunmathur/openassistant/domain/ToolLoop.kt — generate/call/respond loop - com/vayunmathur/openassistant/domain/WavDecoder.kt - com/vayunmathur/openassistant/domain/JsonSchemaValidator.kt - com/vayunmathur/openassistant/domain/HistoryFit.kt - com/vayunmathur/openassistant/domain/A2uiBlocks.kt — split/restore ```a2ui blocks, streaming-safe - com/vayunmathur/openassistant/domain/A2uiEnvelope.kt — block → A2UI protocol messages, action → user turn - com/vayunmathur/openassistant/domain/ModelLoadFailure.kt — missing vs incomplete vs refused model load, for the error text - com/vayunmathur/openassistant/domain/HostMarkers.kt — regex-free parsing of the `[HostSendMsg …]` / `[HostConfirm …]` / `[HostCancel …]` turns (a companion-object Regex in InferenceService crashed service initialisation on Android's ICU regex compiler, #928); engine factory/load Errors are likewise converted to a typed ModelLoadFailure in InferenceService rather than crashing - com/vayunmathur/openassistant/domain/WebPageExtractor.kt — on-device readable-text extraction (title + block text, chrome stripped) and the web_read URL policy; a small tolerant duplicate of the readability idea (news's richer extractor is module-private to news) - com/vayunmathur/openassistant/domain/ReplyStream.kt — bounded chunk buffer between cumulative model callbacks and the DB writer (<=64 pending chunks, 32k live snapshot cap) - com/vayunmathur/openassistant/domain/TurnGate.kt — bounded concurrent turns (max 3 active, per-conversation serialisation) ### platform/ — ViewModel, engine + tool registry - com/vayunmathur/openassistant/platform/AppBackupAgent.kt — platform backup agent: codec-exported `passwords-db` (via `SqlCipherDbCodec`) plus `datastore_default`; raw DB, `secure_prefs` and external model files are excluded in `res/xml/data_extraction_rules.xml` - com/vayunmathur/openassistant/platform/AssistantViewModel.kt - com/vayunmathur/openassistant/platform/MamlChatEngine.kt - com/vayunmathur/openassistant/platform/AssistantDeviceTools.kt - com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt — core cross-app intent back ends (notes/todo/contacts/calendar/family/music/email/clock/weather/maps incl. `maps_search_places`/`maps_get_saved_places`/taxi) with host summarizers that re-cap place rows (≤10, name/address ≤120 chars) - com/vayunmathur/openassistant/platform/AssistantToolIntents.kt - com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt — core cross-app intent back ends (notes/todo/contacts/calendar/family/music/email/clock/weather/calculator/maps/taxi) - com/vayunmathur/openassistant/platform/AssistantToolIntents.kt — includes `summarizeAstronomyTonight` (host cap for `astronomy_get_tonight`) - com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt — core cross-app launches incl. Astronomy `TonightIntent` - com/vayunmathur/openassistant/platform/AssistantToolIntents.kt — commerce/communicate/travel intent back ends + host summarizers (`travel_get_trips` summaries capped at 10) - com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt — core cross-app handlers incl. `translateText`; `summarizeTranslateResult` (in AssistantToolIntents.kt) re-caps at 2,000 chars and surfaces truncation notices - com/vayunmathur/openassistant/platform/AssistantToolIntents.kt — includes `photos_search_photos` (Photos metadata only: count + file names/dates/dimensions/folder, capped at 10 hits; summarised by `summarizePhotoSearch`) - com/vayunmathur/openassistant/platform/AssistantToolIntents.kt — cross-app intent back ends + host summarizers (incl. YouPipe latest-subscription videos: `youpipe_get_subscriptions_latest`, metadata-only, capped at 10) - com/vayunmathur/openassistant/platform/AudioRecorder.kt - com/vayunmathur/openassistant/platform/AssistantTools.kt - com/vayunmathur/openassistant/platform/AssistantCatalog.kt — A2UI component catalog + its prompt section - com/vayunmathur/openassistant/platform/A2uiController.kt — owns the A2UI engine; events → user turns - com/vayunmathur/openassistant/platform/A2uiComposeState.kt — snapshot-state registry + data model ### util/ — inference service - com/vayunmathur/openassistant/util/InferenceService.kt — cross-app intent inference (300 s whole-job budget covering queue/engine-init/generation, one terminal reply per request via the job's replied guard plus a watchdog) — `onStartCommand` reads cross-app extras defensively: an unmarshallable/mistyped extra is logged and dropped (with an error result when the receiver itself read cleanly), never a process crash - com/vayunmathur/openassistant/util/MessageStore.kt — message/pending-call persistence for InferenceService - com/vayunmathur/openassistant/util/InferenceJobs.kt — queued job types (intent job carries the one-terminal-reply guard), the default system-prompt text, and the extraction system prompt ## Verify (this module only) ``` ./gradlew :openassistant:compileDevKotlin ./gradlew :openassistant:testDevUnitTest ./gradlew :openassistant:lint ./gradlew :openassistant:checkMetadata ```