education: add OpenAssistant progress summary tool
- Commit
6663c24f9ffce09fa291784e03b240532ad523d5- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-02 04:49 UTC (4 days ago)
- Parents
cfaac1f
Add the education_get_progress tool (aggregates only: per-course/subject skill counts, streak, stars, at most five capped upcoming deadlines). Merged by hand from 50757240b: its OA summarizers were spliced into main AssistantToolIntents.kt keeping the already-merged screentime summarizers (append-merge, verified compile + OA/catalogue tests). Parent verified :openassistant and :education lintVitalRelease green.
Diff
education/AGENTS.md
diff --git a/education/AGENTS.md b/education/AGENTS.mdindex 55e84215bb..a0547dd4d1 100644--- a/education/AGENTS.md+++ b/education/AGENTS.md@@ -4,7 +4,7 @@ _Install: ./install education (dev by default)._ - Gradle: :education / dir: education/-- Package roots present: ui, data+- Package roots present: ui, data, intents - Entry files: MainActivity.kt + Route.kt + Navigation.kt (catalog → course/unit/lesson/quiz flow; dialogs are routes) - Deps: :library:room, :youpipe:extractor, :library:network - Metadata: metadata_data/education.md (present)@@ -35,6 +35,9 @@ _Install: ./install education (dev by default)._ - com/vayunmathur/education/data/Learner.kt - com/vayunmathur/education/data/SkillProgress.kt - com/vayunmathur/education/data/Deadline.kt+### intents/ — assistant IPC+- com/vayunmathur/education/intents/GetProgressIntent.kt — OpenAssistant `education_get_progress` (aggregates only)+- com/vayunmathur/education/intents/EducationProgressSummary.kt — validated summary builder: per-course/subject skill counts, ≤5 upcoming deadlines (titles ≤120 chars), no lesson/question content or deadline notes ### util/ — ViewModel + helpers - com/vayunmathur/education/util/EducationViewModel.kt - com/vayunmathur/education/util/EducationUiContract.kt
education/src/main/AndroidManifest.xml
diff --git a/education/src/main/AndroidManifest.xml b/education/src/main/AndroidManifest.xmlindex 136ec054f5..962a695ad3 100644--- a/education/src/main/AndroidManifest.xml+++ b/education/src/main/AndroidManifest.xml@@ -9,6 +9,10 @@ <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> + <permission+ android:name="com.vayunmathur.education.permissions.ACCESS_EDUCATION"+ android:protectionLevel="signature" />+ <application android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules"@@ -27,6 +31,11 @@ <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>+ <activity+ android:name=".intents.GetProgressIntent"+ android:exported="true"+ android:permission="com.vayunmathur.education.permissions.ACCESS_EDUCATION"+ android:theme="@android:style/Theme.NoDisplay" /> </application> </manifest>
education/src/main/java/com/vayunmathur/education/intents/EducationProgressSummary.kt
diff --git a/education/src/main/java/com/vayunmathur/education/intents/EducationProgressSummary.kt b/education/src/main/java/com/vayunmathur/education/intents/EducationProgressSummary.ktnew file mode 100644index 0000000000..673283566b--- /dev/null+++ b/education/src/main/java/com/vayunmathur/education/intents/EducationProgressSummary.kt@@ -0,0 +1,123 @@+package com.vayunmathur.education.intents++import com.vayunmathur.education.data.ContentRepository+import com.vayunmathur.education.data.Deadline+import com.vayunmathur.education.data.Learner+import com.vayunmathur.education.data.SkillProgress+import com.vayunmathur.education.domain.Band+import com.vayunmathur.education.domain.Grades+import com.vayunmathur.education.domain.ModuleType+import com.vayunmathur.library.intents.education.CourseProgressData+import com.vayunmathur.library.intents.education.EducationProgressData+import com.vayunmathur.library.intents.education.SubjectProgressData+import com.vayunmathur.library.intents.education.UpcomingDeadlineData++/**+ * Validated contract for the `education_get_progress` assistant tool: builds+ * the aggregates-only [EducationProgressData] from local learner state.+ *+ * Validation/clamping happens here, provider-side: counts are non-negative,+ * stars are coerced to 0..3, percentages to 0..100, only upcoming deadlines+ * are kept (sorted, at most [MAX_DEADLINES]), every title is truncated to+ * [MAX_TITLE_CHARS], and the learner is reduced to a first name. No lesson,+ * question, answer or deadline-note content is ever copied into the result;+ * progress rows for skills no longer in the content catalog are ignored.+ */+object EducationProgressSummary {+ const val MAX_DEADLINES = 5+ const val MAX_TITLE_CHARS = 120+ const val MAX_FIRST_NAME_CHARS = 40+ const val MAX_COURSES = 20++ private const val MAX_STARS = 3++ fun build(+ learner: Learner?,+ progress: List<SkillProgress>,+ content: ContentRepository,+ deadlines: List<Deadline>,+ todayEpochDay: Long,+ ): EducationProgressData {+ val bySkill = progress.associateBy { it.skillId }++ fun started(skillIds: Collection<String>): Int =+ skillIds.count { id -> bySkill[id]?.let { it.stars > 0 || it.attempts > 0 } == true }++ fun mastered(skillIds: Collection<String>): Int =+ skillIds.count { id -> (bySkill[id]?.stars ?: 0).coerceIn(0, MAX_STARS) >= MAX_STARS }++ fun percent(masteredCount: Int, total: Int): Int =+ if (total <= 0) 0 else (masteredCount * 100 / total).coerceIn(0, 100)++ val courseSkills = content.courses.map { it to content.skillIdsOfCourse(it) }+ val courses = courseSkills+ .sortedWith(compareBy({ it.first.subject.name }, { it.first.title }))+ .take(MAX_COURSES)+ .map { (course, skillIds) ->+ val masteredCount = mastered(skillIds)+ CourseProgressData(+ courseId = course.id,+ title = course.title.take(MAX_TITLE_CHARS),+ subject = course.subject.name,+ totalSkills = skillIds.size,+ startedSkills = started(skillIds),+ masteredSkills = masteredCount,+ completionPercent = percent(masteredCount, skillIds.size),+ )+ }++ val subjects = courseSkills+ .groupBy({ it.first.subject }, { it.second })+ .entries+ .sortedBy { it.key.name }+ .map { (subject, perCourse) ->+ val skillIds = perCourse.flatten().distinct()+ val masteredCount = mastered(skillIds)+ SubjectProgressData(+ subject = subject.name,+ totalSkills = skillIds.size,+ startedSkills = started(skillIds),+ masteredSkills = masteredCount,+ completionPercent = percent(masteredCount, skillIds.size),+ )+ }++ val allSkillIds = courseSkills.flatMap { it.second }.distinct()+ val upcoming = deadlines+ .filter { it.dueEpochDay >= todayEpochDay }+ .sortedWith(compareBy({ it.dueEpochDay }, { it.moduleId }))+ .take(MAX_DEADLINES)+ .map { deadline ->+ val type = runCatching { ModuleType.valueOf(deadline.moduleType) }.getOrNull()+ val title = type?.let { content.moduleTitle(it, deadline.moduleId) }+ ?.takeIf { it.isNotBlank() } ?: deadline.moduleId+ UpcomingDeadlineData(+ title = title.take(MAX_TITLE_CHARS),+ moduleType = deadline.moduleType,+ dueEpochDay = deadline.dueEpochDay,+ )+ }++ return EducationProgressData(+ learnerFirstName = learner?.name+ ?.trim()?.split(Regex("\\s+"))?.firstOrNull()+ ?.take(MAX_FIRST_NAME_CHARS)?.takeIf { it.isNotBlank() },+ band = learner?.let { bandOf(it).name },+ streakDays = (learner?.streakCount ?: 0).coerceAtLeast(0),+ totalStars = (learner?.totalStars ?: 0).coerceAtLeast(0),+ totalSkills = allSkillIds.size,+ skillsStarted = started(allSkillIds),+ skillsMastered = mastered(allSkillIds),+ courses = courses,+ subjects = subjects,+ upcomingDeadlines = upcoming,+ )+ }++ private fun bandOf(learner: Learner): Band {+ learner.bandOverride?.let { name ->+ runCatching { Band.valueOf(name) }.getOrNull()?.let { return it }+ }+ return Grades.bandForGrade(learner.gradeLevel)+ }+}
education/src/main/java/com/vayunmathur/education/intents/GetProgressIntent.kt
diff --git a/education/src/main/java/com/vayunmathur/education/intents/GetProgressIntent.kt b/education/src/main/java/com/vayunmathur/education/intents/GetProgressIntent.ktnew file mode 100644index 0000000000..f067002005--- /dev/null+++ b/education/src/main/java/com/vayunmathur/education/intents/GetProgressIntent.kt@@ -0,0 +1,31 @@+package com.vayunmathur.education.intents++import com.vayunmathur.education.data.ContentRepository+import com.vayunmathur.education.data.EducationRepository+import com.vayunmathur.library.intents.education.EducationProgressData+import com.vayunmathur.library.util.AssistantIntent+import kotlinx.coroutines.flow.first+import kotlinx.serialization.builtins.serializer+import java.time.LocalDate++/**+ * Assistant tool `education_get_progress`: returns the aggregates-only+ * progress summary built by [EducationProgressSummary] from the local Room+ * progress/deadlines and the bundled content catalog. Reads local state+ * only — no network, no refresh, no content payloads.+ */+class GetProgressIntent : AssistantIntent<Unit, EducationProgressData>(+ Unit.serializer(),+ EducationProgressData.serializer(),+) {+ override suspend fun performCalculation(input: Unit): EducationProgressData {+ val repo = EducationRepository.get(this)+ return EducationProgressSummary.build(+ learner = repo.getLearner(),+ progress = repo.getAllSkillProgress(),+ content = ContentRepository.load(this),+ deadlines = repo.deadlinesFlow().first(),+ todayEpochDay = LocalDate.now().toEpochDay(),+ )+ }+}
education/src/test/java/com/vayunmathur/education/intents/EducationProgressSummaryTest.kt
diff --git a/education/src/test/java/com/vayunmathur/education/intents/EducationProgressSummaryTest.kt b/education/src/test/java/com/vayunmathur/education/intents/EducationProgressSummaryTest.ktnew file mode 100644index 0000000000..5c28bad158--- /dev/null+++ b/education/src/test/java/com/vayunmathur/education/intents/EducationProgressSummaryTest.kt@@ -0,0 +1,154 @@+package com.vayunmathur.education.intents++import com.vayunmathur.education.data.ContentRepository+import com.vayunmathur.education.data.Deadline+import com.vayunmathur.education.data.Learner+import com.vayunmathur.education.data.SkillProgress+import com.vayunmathur.education.domain.ContentPack+import com.vayunmathur.education.domain.Course+import com.vayunmathur.education.domain.CourseUnit+import com.vayunmathur.education.domain.Exercise+import com.vayunmathur.education.domain.Lesson+import com.vayunmathur.education.domain.NumericQuestion+import com.vayunmathur.education.domain.Prompt+import com.vayunmathur.education.domain.Skill+import com.vayunmathur.education.domain.Subject+import com.vayunmathur.library.intents.education.EducationProgressData+import kotlinx.serialization.json.Json+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** Pins the aggregates-only contract of `education_get_progress`. */+class EducationProgressSummaryTest {++ private val longTitle = "C".repeat(200)++ private fun content(): ContentRepository {+ val questions = listOf("s1" to "q1", "s2" to "q2", "s3" to "q3").map { (skill, id) ->+ NumericQuestion(id = id, skillId = skill, prompt = Prompt("SECRET_PROMPT_$id"), answer = 1.0)+ }+ val math = Course(+ id = "c-math", subject = Subject.MATH, title = longTitle, gradeLevel = 4,+ units = listOf(+ CourseUnit(+ "u-math", "Units",+ lessons = listOf(Lesson("l-math", "Lessons", exercise = Exercise("ex-math", questionIds = listOf("q1", "q2")))),+ ),+ ),+ )+ val reading = Course(+ id = "c-read", subject = Subject.READING, title = "Reading", gradeLevel = 4,+ units = listOf(+ CourseUnit(+ "u-read", "Stories",+ lessons = listOf(Lesson("l-read", "Story", exercise = Exercise("ex-read", questionIds = listOf("q3")))),+ ),+ ),+ )+ return ContentRepository(+ listOf(+ ContentPack(+ id = "p", name = "Pack",+ skills = listOf(+ Skill("s1", Subject.MATH, "One"),+ Skill("s2", Subject.MATH, "Two"),+ Skill("s3", Subject.READING, "Three"),+ ),+ courses = listOf(math, reading),+ questions = questions,+ ),+ ),+ )+ }++ private fun build(+ deadlines: List<Deadline> = emptyList(),+ learner: Learner? = Learner(name = "Ada Lovelace", gradeLevel = 4, streakCount = 5, totalStars = 7),+ ): EducationProgressData = EducationProgressSummary.build(+ learner = learner,+ progress = listOf(+ SkillProgress("s1", stars = 3, attempts = 2),+ SkillProgress("s2", stars = 1, attempts = 1),+ SkillProgress("s3", stars = 0, attempts = 2),+ SkillProgress("orphan", stars = 3, attempts = 9),+ ),+ content = content(),+ deadlines = deadlines,+ todayEpochDay = TODAY,+ )++ @Test fun aggregatesPerCourseAndSubject() {+ val data = build()+ assertEquals("Ada", data.learnerFirstName)+ assertEquals("ELEMENTARY", data.band)+ assertEquals(5, data.streakDays)+ assertEquals(7, data.totalStars)+ assertEquals(3, data.totalSkills)+ assertEquals(3, data.skillsStarted)+ assertEquals(1, data.skillsMastered)++ val math = data.courses.single { it.courseId == "c-math" }+ assertEquals(2, math.totalSkills)+ assertEquals(2, math.startedSkills)+ assertEquals(1, math.masteredSkills)+ assertEquals(50, math.completionPercent)+ assertEquals(120, math.title.length)++ val readingSubject = data.subjects.single { it.subject == "READING" }+ assertEquals(1, readingSubject.totalSkills)+ assertEquals(1, readingSubject.startedSkills)+ assertEquals(0, readingSubject.masteredSkills)+ assertEquals(0, readingSubject.completionPercent)+ }++ @Test fun deadlinesAreUpcomingSortedCappedAndTruncated() {+ val deadlines = buildList {+ add(Deadline(moduleType = "COURSE", moduleId = "c-math", dueEpochDay = TODAY - 1, note = "SECRET_NOTE"))+ (0..6).forEach { i ->+ add(Deadline(moduleType = "COURSE", moduleId = "c-read", dueEpochDay = TODAY + 7 - i, note = "SECRET_NOTE"))+ }+ add(Deadline(moduleType = "LESSON", moduleId = "l-math", dueEpochDay = TODAY, note = "SECRET_NOTE"))+ }+ val data = build(deadlines)+ assertEquals(5, data.upcomingDeadlines.size)+ assertEquals(TODAY, data.upcomingDeadlines.first().dueEpochDay)+ assertTrue(data.upcomingDeadlines.all { it.dueEpochDay >= TODAY })+ assertTrue(data.upcomingDeadlines.zipWithNext().all { (a, b) -> a.dueEpochDay <= b.dueEpochDay })+ assertTrue(data.upcomingDeadlines.all { it.title.length <= 120 })+ }++ @Test fun serializedSummaryContainsNoContentOrNotes() {+ val deadlines = listOf(+ Deadline(moduleType = "COURSE", moduleId = "c-math", dueEpochDay = TODAY, note = "SECRET_NOTE"),+ )+ val encoded = Json.encodeToString(EducationProgressData.serializer(), build(deadlines))+ assertFalse(encoded.contains("SECRET_NOTE"), encoded)+ assertFalse(encoded.contains("SECRET_PROMPT"), encoded)+ assertFalse(encoded.contains("\"note\""), encoded)+ assertFalse(encoded.contains("\"content\""), encoded)+ assertFalse(encoded.contains("\"question"), encoded)+ assertFalse(encoded.contains("\"answer"), encoded)+ assertFalse(encoded.contains("\"prompt\""), encoded)+ }++ @Test fun emptyStateIsZeroed() {+ val data = EducationProgressSummary.build(+ learner = null,+ progress = emptyList(),+ content = ContentRepository(emptyList()),+ deadlines = emptyList(),+ todayEpochDay = TODAY,+ )+ assertEquals(0, data.totalSkills)+ assertEquals(0, data.skillsStarted)+ assertTrue(data.courses.isEmpty())+ assertTrue(data.upcomingDeadlines.isEmpty())+ assertEquals(null, data.learnerFirstName)+ }++ private companion object {+ const val TODAY = 20_000L+ }+}
library/AGENTS.md
diff --git a/library/AGENTS.md b/library/AGENTS.mdindex a801046121..0ea6f36bd9 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/screentime/ScreentimeData.kt — aggregates-only usage summary DTOs (total + top-5 apps)+- com/vayunmathur/library/intents/education/EducationProgressData.kt — aggregates-only progress summary (per-course/subject counts, ≤5 upcoming deadlines) ### 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/education/EducationProgressData.kt
diff --git a/library/src/main/java/com/vayunmathur/library/intents/education/EducationProgressData.kt b/library/src/main/java/com/vayunmathur/library/intents/education/EducationProgressData.ktnew file mode 100644index 0000000000..e4bbdc61c3--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/intents/education/EducationProgressData.kt@@ -0,0 +1,67 @@+package com.vayunmathur.library.intents.education++import kotlinx.serialization.Serializable++/**+ * Per-course completion aggregate for [EducationProgressData]. Counts only:+ * no lesson, question, answer or other course content crosses the wire.+ */+@Serializable+data class CourseProgressData(+ val courseId: String,+ /** Course title, truncated provider-side to at most 120 chars. */+ val title: String,+ /** Subject enum name (e.g. MATH). */+ val subject: String,+ val totalSkills: Int,+ val startedSkills: Int,+ val masteredSkills: Int,+ /** Mastered as a percentage of [totalSkills], 0..100. */+ val completionPercent: Int,+)++/** Per-subject completion aggregate; counts only, no content. */+@Serializable+data class SubjectProgressData(+ /** Subject enum name (e.g. MATH). */+ val subject: String,+ val totalSkills: Int,+ val startedSkills: Int,+ val masteredSkills: Int,+ /** Mastered as a percentage of [totalSkills], 0..100. */+ val completionPercent: Int,+)++/** One upcoming deadline: a resolved module title and its due day only. */+@Serializable+data class UpcomingDeadlineData(+ /** Module title, truncated provider-side to at most 120 chars. */+ val title: String,+ /** Module kind name (COURSE, UNIT or LESSON). */+ val moduleType: String,+ val dueEpochDay: Long,+)++/**+ * Education progress summary returned by the Education app's+ * `GetProgressIntent` to OpenAssistant's `education_get_progress` tool.+ *+ * Aggregates only by design: per-course/per-subject skill counts, streak and+ * star totals, and at most five upcoming deadlines. No lesson or question+ * content, no per-answer history and no deadline notes are included.+ */+@Serializable+data class EducationProgressData(+ /** Learner's first name only, truncated provider-side to at most 40 chars. */+ val learnerFirstName: String? = null,+ /** Band enum name (K2, ELEMENTARY or SCHOLAR), or null without a learner. */+ val band: String? = null,+ val streakDays: Int = 0,+ val totalStars: Int = 0,+ val totalSkills: Int = 0,+ val skillsStarted: Int = 0,+ val skillsMastered: Int = 0,+ val courses: List<CourseProgressData> = emptyList(),+ val subjects: List<SubjectProgressData> = emptyList(),+ val upcomingDeadlines: List<UpcomingDeadlineData> = emptyList(),+)
library/src/test/java/com/vayunmathur/library/intents/education/EducationProgressDtoTest.kt
diff --git a/library/src/test/java/com/vayunmathur/library/intents/education/EducationProgressDtoTest.kt b/library/src/test/java/com/vayunmathur/library/intents/education/EducationProgressDtoTest.ktnew file mode 100644index 0000000000..7a9e633dcd--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/intents/education/EducationProgressDtoTest.kt@@ -0,0 +1,38 @@+package com.vayunmathur.library.intents.education++import kotlinx.serialization.json.Json+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse++/** Round-trip + aggregates-only field pin for the education progress DTOs. */+class EducationProgressDtoTest {++ @Test fun roundTrips() {+ val original = EducationProgressData(+ learnerFirstName = "Ada",+ band = "ELEMENTARY",+ streakDays = 5,+ totalStars = 7,+ totalSkills = 3,+ skillsStarted = 3,+ skillsMastered = 1,+ courses = listOf(CourseProgressData("c-math", "Math", "MATH", 2, 2, 1, 50)),+ subjects = listOf(SubjectProgressData("MATH", 2, 2, 1, 50)),+ upcomingDeadlines = listOf(UpcomingDeadlineData("Math", "COURSE", 20_000L)),+ )+ val encoded = Json.encodeToString(EducationProgressData.serializer(), original)+ assertEquals(original, Json.decodeFromString(EducationProgressData.serializer(), encoded))+ // Aggregates only: no content-bearing fields exist on the wire.+ listOf("content", "question", "answer", "prompt", "note", "lessonText").forEach { field ->+ assertFalse(encoded.contains("\"$field\""), "unexpected field $field in $encoded")+ }+ }++ @Test fun defaultsAreEmptySummary() {+ val decoded = Json.decodeFromString(EducationProgressData.serializer(), "{}")+ assertEquals(0, decoded.totalSkills)+ assertEquals(emptyList(), decoded.courses)+ assertEquals(emptyList(), decoded.upcomingDeadlines)+ }+}
openassistant/AGENTS.md
diff --git a/openassistant/AGENTS.md b/openassistant/AGENTS.mdindex e19c0bda74..5b41ca093f 100644--- a/openassistant/AGENTS.md+++ b/openassistant/AGENTS.md@@ -70,8 +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 — commerce/communicate/screentime intent back ends + host summarizers (incl. `summarizeScreentimeUsage`)-- com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt — core cross-app intent back ends (notes/todo/contacts/calendar/family/music/email/clock/weather/maps/taxi/screentime)+- 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/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 e37f7ad93f..2f33204a2b 100644--- a/openassistant/src/main/AndroidManifest.xml+++ b/openassistant/src/main/AndroidManifest.xml@@ -20,6 +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="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" />@@ -58,6 +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" /> </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 4af2a4f08d..d8c84507cf 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt@@ -56,7 +56,7 @@ 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). 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+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 get_contacts|-|Get a list of all contacts| create_contact|C|Create a new contact (requires confirmation)|name^S^1^~phone_number^S^1^@@ -78,7 +78,7 @@ set_timer|C|Start a countdown timer in the Clock app for a number of seconds (re 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 this over a ```a2ui fence. components_json: {"components":[...]} (or a bare array) using the RICH UI types; data_json: optional initial 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+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_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@@ -87,24 +87,24 @@ 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 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 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+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 placed.|merchant_id^N^1^merchant id the items belong to~items_json^S^1^JSON array of {itemId, qty, modifierIds}+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 cart's order summary; the user pays in FoodDelivery. Never creates an order or charges.|merchant_id^N^1^merchant id of the cart+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; the user checks out in Shop. Never charges; opening the cart is not an order.|shop_domain^S^1^store domain to check out+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|-screentime_get_usage|-|Get today's screen time: total + top 5 apps with durations.|+education_get_progress|-|Education progress by course/subject, streak, upcoming deadlines (aggregates only)| get_memories|-|Get a list of all memories| remove_memory|C|Remove a memory by its id (requires confirmation)|id^N^1^ add_to_memory|-|Add a new memory to the list of memories|content^S^1^
openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.ktindex 64713a4def..82b35fb515 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt@@ -9,6 +9,7 @@ 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@@ -144,6 +145,14 @@ internal abstract class AssistantCoreToolIntents( data, ) + suspend fun getEducationProgress(): EducationProgressData =+ launchIntent<Unit, EducationProgressData>(+ context,+ "com.vayunmathur.education",+ "com.vayunmathur.education.intents.GetProgressIntent",+ Unit,+ )+ suspend fun getCalendarEvents(): String = launchIntent<Unit, List<EventData>>( context, "com.vayunmathur.calendar",
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 e36337d4e0..72571df35f 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt@@ -9,6 +9,7 @@ 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@@ -94,7 +95,7 @@ internal class AssistantToolIntents(context: Context) : AssistantCoreToolIntents "com.vayunmathur.fooddelivery" to "FoodDelivery", "com.vayunmathur.communicate" to "Communicate", "com.vayunmathur.shop" to "Shop",- "com.vayunmathur.screentime" to "Screentime",+ "com.vayunmathur.education" to "Education", ) fun getMissingAppMessage(packageName: String): String {@@ -314,6 +315,32 @@ 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) {@@ -483,11 +510,32 @@ fun summarizeShopOrders(list: List<ShopOrderData>, cap: Int = 10): String = } } -/**- * Host summary for `screentime_get_usage`: today's total plus the top apps- * with durations. Aggregates only — the provider returns no per-event data,- * and this caps the list again host-side so the model never sees 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"+ result.error == "GOOGLE_VOICE_REQUIRES_ACTIVITY" ->+ "Error: Google Voice messages cannot be sent from here; the conversation must be opened in Communicate instead"+ result.error != null -> "Error: message not sent (${result.error})"+ else -> "Error: message not sent"+}++@OptIn(ExperimentalSerializationApi::class)+suspend inline fun <reified Input : Any> launchIntentU(+ context: Context,+ packageName: String,+ className: String,+ input: Input,+) {+ val stringOutput = MainActivity.intentLauncher.launch(+ context,+ packageName,+ className,+ serializer<Input>(),+ input,+ )+ if (stringOutput == "package $packageName doesn't exist") throw MissingAppException(packageName)+}+ fun summarizeScreentimeUsage(data: ScreentimeUsageData): String { if (!data.hasUsageAccess || data.error != null) { return "Screen time unavailable: usage access is not granted in Screentime"@@ -502,6 +550,7 @@ fun summarizeScreentimeUsage(data: ScreentimeUsageData): String { } /** Compact duration for usage summaries: `2h 15m`, `45m`, or `30s`. */+ fun formatUsageDuration(millis: Long): String { val totalSeconds = millis / 1_000 val hours = totalSeconds / 3_600@@ -515,27 +564,3 @@ fun formatUsageDuration(millis: Long): String { } /** Maps a provider send outcome to the model-facing string; GV is typed. */-fun summarizeSendResult(result: SendMessageResult): String = when {- result.success -> "Success: Message sent"- result.error == "GOOGLE_VOICE_REQUIRES_ACTIVITY" ->- "Error: Google Voice messages cannot be sent from here; the conversation must be opened in Communicate instead"- result.error != null -> "Error: message not sent (${result.error})"- else -> "Error: message not sent"-}--@OptIn(ExperimentalSerializationApi::class)-suspend inline fun <reified Input : Any> launchIntentU(- context: Context,- packageName: String,- className: String,- input: Input,-) {- val stringOutput = MainActivity.intentLauncher.launch(- context,- packageName,- className,- serializer<Input>(),- input,- )- if (stringOutput == "package $packageName doesn't exist") throw MissingAppException(packageName)-}
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 c6bbeae7b9..2c65b84b67 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt@@ -460,6 +460,11 @@ class AssistantTools( runBlocking { webTools.webReadResult(a.number("index").toInt(), a.number("offset").toInt()) } }, "render_ui" to { a -> renderUi(a.string("components_json"), a.string("data_json")) },+ "education_get_progress" to { _ ->+ intents.runTool {+ com.vayunmathur.openassistant.platform.summarizeEducationProgress(intents.getEducationProgress())+ }+ }, "get_memories" to { _ -> intents.runTool { device.getMemories(memoryDao) } }, "remove_memory" to { a -> intents.runTool { device.removeMemory(memoryDao, a.number("id")) } }, "add_to_memory" to { a -> intents.runTool { device.addToMemory(memoryDao, a.string("content")) } },
openassistant/src/test/java/com/vayunmathur/openassistant/util/EducationProgressSummarizeTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/EducationProgressSummarizeTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/EducationProgressSummarizeTest.ktnew file mode 100644index 0000000000..0fea7337ad--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/EducationProgressSummarizeTest.kt@@ -0,0 +1,40 @@+package com.vayunmathur.openassistant.util++import com.vayunmathur.library.intents.education.CourseProgressData+import com.vayunmathur.library.intents.education.EducationProgressData+import com.vayunmathur.library.intents.education.SubjectProgressData+import com.vayunmathur.library.intents.education.UpcomingDeadlineData+import com.vayunmathur.openassistant.platform.summarizeEducationProgress+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Host summarizer for `education_get_progress`: aggregates in, capped text out. */+class EducationProgressSummarizeTest {++ @Test fun summarizesAggregatesAndCapsDeadlinesAndTitles() {+ val longTitle = "T".repeat(200)+ val data = EducationProgressData(+ learnerFirstName = "Ada",+ band = "ELEMENTARY",+ streakDays = 5,+ totalStars = 7,+ totalSkills = 3,+ skillsStarted = 3,+ skillsMastered = 1,+ courses = listOf(CourseProgressData("c-math", longTitle, "MATH", 2, 2, 1, 50)),+ subjects = listOf(SubjectProgressData("MATH", 2, 2, 1, 50)),+ upcomingDeadlines = (1..7).map { UpcomingDeadlineData(longTitle, "COURSE", 20_000L + it) },+ )+ val text = summarizeEducationProgress(data)+ assertTrue(text.contains("1/3 skills mastered"), text)+ assertTrue(text.contains("subject MATH: 1/2 mastered (50%)"), text)+ assertEquals(5, text.lines().count { it.startsWith("deadline ") })+ assertTrue(text.lines().all { it.length <= 200 }, text)+ }++ @Test fun emptySummaryIsOneLine() {+ val text = summarizeEducationProgress(EducationProgressData())+ assertTrue(text.contains("0/0 skills mastered"), text)+ }+}