Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / openassistant / AGENTS.md

AGENTS.md11.8 KiBRenderedCodeRaw
1# AGENTS.md — openassistant/ (':openassistant')
2
3> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside `openassistant/` + allowed shared modules. Do not root-scan.
4
5_Install: ./install openassistant (dev by default)._
6- Gradle: :openassistant / dir: openassistant/
7- Package roots present: ui, data, domain, platform, network, service, util
8- Entry files: MainActivity.kt, Route.kt, Navigation.kt
9- Deps: :library:room, :library:image, :library:ml, :library:downloadservice, androidx.a2ui (model + engine)
10- Metadata: metadata_data/openassistant.md (present)
11- Rust: no / screenshotTest: yes
12
13## Overview
14**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.
15**Key features:**
16- Multiple chats with streaming responses and markdown rendering, persisted in Room
17- Multimodal input: photo upload and audio recording, read by Gemma 4's vision and audio towers
18- Tool calling into other Modern Apps over local IPC, with JSON-schema validation
19- A model-managed memory plus an editable system prompt; can be set as the device's default digital assistant (Assist API + voice interaction service)
20- Generative UI: replies can carry an A2UI block (cards, forms, buttons) rendered natively; button events come back to the model as user turns
21**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.
22**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`.
23**Gotchas:**
24- 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`
25- `MainActivity.intentLauncher` is a shared static other apps mirror (maps/taxi pattern) — keep it initialized in `onCreateBeforeContent`
26- `StubRecognitionService` is a placeholder voice-recognition hook, not a real recognizer
27- 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)
28- 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
29- 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
30- `util/` is NOT a closed package root — don't add more files there (it holds only `InferenceService`); assistant surfaces are in `service/`
31- A2UI: the model writes only ```` ```a2ui {"components":[...],"data":{...}} ```` and `domain/A2uiEnvelope` adds the protocol envelope. Surface id is `m<messageId>`; 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`
32- `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`
33- 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
34- 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
35
36## Key files
37### Root — entry + inline navigation
38- com/vayunmathur/openassistant/MainActivity.kt — Route, Navigation, assist screen-context
39### service/ — system assistant surfaces
40- com/vayunmathur/openassistant/service/OpenAssistantSession.kt — Assist API screen-text capture
41- com/vayunmathur/openassistant/service/OpenAssistantSessionService.kt
42- com/vayunmathur/openassistant/service/OpenAssistantVoiceInteractionService.kt
43- com/vayunmathur/openassistant/service/StubRecognitionService.kt — placeholder recognizer hook
44### network/ — web tools
45- 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
46### data/ — chats + repository
47- com/vayunmathur/openassistant/data/Database.kt — `DB_NAME` (`passwords-db`) + `openAssistantDbConfigs` for the backup agent
48- com/vayunmathur/openassistant/data/OpenAssistantRepository.kt
49### ui/ — chat + settings
50- com/vayunmathur/openassistant/ui/LiteRTChatUi.kt
51- com/vayunmathur/openassistant/ui/LiteRTChatScreen.kt
52- com/vayunmathur/openassistant/ui/LiteRTChatBubble.kt
53- com/vayunmathur/openassistant/ui/LiteRTChatInput.kt
54- com/vayunmathur/openassistant/ui/SettingsPage.kt
55- com/vayunmathur/openassistant/ui/A2uiSurfaceView.kt — Compose renderer for A2UI surfaces
56### domain/ — pure, unit-tested
57- com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt — tool names/descriptions/params
58- com/vayunmathur/openassistant/domain/ToolCalls.kt — call parsing, markup stripping, arg coercion
59- com/vayunmathur/openassistant/domain/ToolLoop.kt — generate/call/respond loop
60- com/vayunmathur/openassistant/domain/WavDecoder.kt
61- com/vayunmathur/openassistant/domain/JsonSchemaValidator.kt
62- com/vayunmathur/openassistant/domain/HistoryFit.kt
63- com/vayunmathur/openassistant/domain/A2uiBlocks.kt — split/restore ```a2ui blocks, streaming-safe
64- com/vayunmathur/openassistant/domain/A2uiEnvelope.kt — block → A2UI protocol messages, action → user turn
65- com/vayunmathur/openassistant/domain/ModelLoadFailure.kt — missing vs incomplete vs refused model load, for the error text
66- 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
67- 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)
68- com/vayunmathur/openassistant/domain/ReplyStream.kt — bounded chunk buffer between cumulative model callbacks and the DB writer (<=64 pending chunks, 32k live snapshot cap)
69- com/vayunmathur/openassistant/domain/TurnGate.kt — bounded concurrent turns (max 3 active, per-conversation serialisation)
70### platform/ — ViewModel, engine + tool registry
71- 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`
72- com/vayunmathur/openassistant/platform/AssistantViewModel.kt
73- com/vayunmathur/openassistant/platform/MamlChatEngine.kt
74- com/vayunmathur/openassistant/platform/AssistantDeviceTools.kt
75- 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)
76- com/vayunmathur/openassistant/platform/AssistantToolIntents.kt
77- com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt — core cross-app intent back ends (notes/todo/contacts/calendar/family/music/email/clock/weather/calculator/maps/taxi)
78- com/vayunmathur/openassistant/platform/AssistantToolIntents.kt — includes `summarizeAstronomyTonight` (host cap for `astronomy_get_tonight`)
79- com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt — core cross-app launches incl. Astronomy `TonightIntent`
80- com/vayunmathur/openassistant/platform/AssistantToolIntents.kt — commerce/communicate/travel intent back ends + host summarizers (`travel_get_trips` summaries capped at 10)
81- 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
82- 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`)
83- 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)
84- com/vayunmathur/openassistant/platform/AudioRecorder.kt
85- com/vayunmathur/openassistant/platform/AssistantTools.kt
86- com/vayunmathur/openassistant/platform/AssistantCatalog.kt — A2UI component catalog + its prompt section
87- com/vayunmathur/openassistant/platform/A2uiController.kt — owns the A2UI engine; events → user turns
88- com/vayunmathur/openassistant/platform/A2uiComposeState.kt — snapshot-state registry + data model
89### util/ — inference service
90- com/vayunmathur/openassistant/util/InferenceService.kt
91
92## Verify (this module only)
93```
94./gradlew :openassistant:compileDevKotlin
95./gradlew :openassistant:testDevUnitTest
96./gradlew :openassistant:lint
97./gradlew :openassistant:checkMetadata
98```