Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
feat(connectors): wire the new tools into the catalog, registry and Settings
Durganshu Mishra06ee38c45ea5
diff --git a/app/src/main/assets/skills/calendar.json b/app/src/main/assets/skills/calendar.jsonindex a58de30..6d33e04 100644--- a/app/src/main/assets/skills/calendar.json+++ b/app/src/main/assets/skills/calendar.json@@ -1,7 +1,7 @@{"id": "calendar_operations",- "targetPackageNames": ["com.google.android.calendar"],+ "targetPackageNames": ["com.google.android.calendar", "com.microsoft.office.outlook"],"name": "Calendar Skills","description": "Prefer the calendar connector tools over driving the Calendar app UI.",- "instructions": "Never automate the Calendar app's UI to view or manage events — use the dedicated tools instead, which read/write the device's calendar accounts directly:\n1. list_calendar_events supports date ranges and text search, and shows reminders and attendees per event.\n2. create_calendar_event supports all_day, calendar_name (to pick a specific account like 'Work'), attendees (real invites on a synced Google calendar), and recurrence (daily/weekly/monthly/yearly with recurrence_count or recurrence_until).\n3. edit_calendar_event updates only the fields you provide; get the event_id from list_calendar_events first.\n4. delete_calendar_event always asks the user to confirm before removing anything — irreversible.\nOnly fall back to UI automation (open_app + navigate_app) for things these tools can't do, e.g. viewing a calendar not synced to this device or the app's own settings."+ "instructions": "Never automate a calendar app's UI to view or manage events — use the dedicated tools instead, which read/write calendar accounts directly:\n1. list_calendar_events supports date ranges and text search, and shows reminders and attendees per event.\n2. create_calendar_event supports all_day, calendar_name (to pick a specific account like 'Work'), attendees (real invites on a synced Google calendar), and recurrence (daily/weekly/monthly/yearly with recurrence_count or recurrence_until).\n3. edit_calendar_event updates only the fields you provide; get the event_id from list_calendar_events first.\n4. delete_calendar_event always asks the user to confirm before removing anything — irreversible.\n\nChoosing a source: list_calendar_events and create_calendar_event default to source='device' (the phone's own calendar accounts) and that is almost always right. Only pass source='google' or source='microsoft' when the user asks about an account that is not synced to this phone, or when the device calendar clearly does not contain what they described.\n\nEvent ids differ by source: device events have bare numeric ids, connector events are prefixed 'gcal:' or 'ms:'. edit_calendar_event and delete_calendar_event work on device ids only — for a connector event, tell the user it must be changed in that account's own app.\n\nFor 'am I free', 'when can we meet', or scheduling around existing commitments, use check_availability rather than listing events and reasoning about the gaps yourself. It needs a connected Google (with Calendar) or Microsoft account; if none is connected, fall back to list_calendar_events and say you are reading the device calendar only.\n\nOnly fall back to UI automation (open_app + navigate_app) for things these tools can't do, e.g. the app's own settings."}diff --git a/app/src/main/assets/skills/health.json b/app/src/main/assets/skills/health.jsonnew file mode 100644index 0000000..dc029a0--- /dev/null+++ b/app/src/main/assets/skills/health.json@@ -0,0 +1,7 @@+{+ "id": "health_connect",+ "targetPackageNames": ["com.google.android.apps.healthdata", "com.google.android.apps.fitness"],+ "name": "Health and Fitness Skills",+ "description": "Read health and fitness data through Health Connect rather than a fitness app's UI.",+ "instructions": "Never automate a fitness app's UI to read step counts, sleep or workouts. Health Connect aggregates what every fitness app on the phone writes, and two tools read it:\n1. get_health_summary(days) — totals and averages over a window: steps, distance, active calories, sleep, average/peak/resting heart rate, weight. Use this for 'how did I sleep this week', 'how active have I been'.\n2. get_health_records(type, days) — individual records, for questions the summary cannot answer such as 'which days did I hit 10000 steps' or 'when did I work out'. Types: steps, distance, calories, sleep, heart_rate, resting_heart_rate, weight, exercise.\n\nBoth are read-only — the agent never writes to the user's health record.\n\nIf a metric is missing from the summary it means no app wrote that data in the window; say so rather than reporting zero. If the tool asks for permission, the Health Connect permission screen has been opened — ask the user to allow the data types they are comfortable sharing. On Android 13 and below Health Connect is a separate app that may need installing from the Play Store.\n\nThis is personal health information. Report what the data says; do not diagnose, and suggest seeing a clinician for anything that reads as a medical concern."+}diff --git a/app/src/main/assets/skills/media.json b/app/src/main/assets/skills/media.jsonnew file mode 100644index 0000000..b4a6eab--- /dev/null+++ b/app/src/main/assets/skills/media.json@@ -0,0 +1,12 @@+{+ "id": "media_playback",+ "targetPackageNames": [+ "com.spotify.music",+ "com.google.android.apps.youtube.music",+ "com.google.android.youtube",+ "com.soundcloud.android"+ ],+ "name": "Media Playback Skills",+ "description": "Control playback through the media-session tools rather than tapping player UI.",+ "instructions": "Never tap through a music or video app's UI to pause, skip or scrub. Any app with a media notification exposes a media session, and two tools drive it with no per-service account or API:\n1. get_now_playing — what every active session is playing: app, state, title, artist, album, position/duration. Use it to answer 'what song is this?' and to find the right 'app' value before controlling a specific player.\n2. media_control(action, app?, position_seconds?) — play, pause, toggle, next, previous, stop, seek, fast_forward, rewind.\n\nWhen several apps hold a session, media_control picks the one actually playing, which is usually what the user means. Pass 'app' (package name or app label, e.g. 'spotify') when they name a specific player or when get_now_playing shows more than one thing playing.\n\nseek requires position_seconds — an absolute position from the start of the track, not a relative jump. For a relative nudge use fast_forward or rewind instead.\n\nThese tools control playback but cannot start it: they need something already loaded in a player. To begin playing a specific track or playlist, use open_app and then UI automation, or ask the user to start it. Both tools need Notification access; if it is not granted the tool says so and the settings screen is opened."+}diff --git a/app/src/main/assets/skills/notion.json b/app/src/main/assets/skills/notion.jsonnew file mode 100644index 0000000..511f11e--- /dev/null+++ b/app/src/main/assets/skills/notion.json@@ -0,0 +1,7 @@+{+ "id": "notion_workspace",+ "targetPackageNames": ["notion.id"],+ "name": "Notion Skills",+ "description": "Use the Notion connector tools instead of automating the Notion app UI.",+ "instructions": "Never automate the Notion app's UI. When the Notion connector is set up (Settings → Connectors) use these tools:\n1. notion_search finds pages by title. Always start here — the other tools need a page id from it.\n2. notion_read_page returns the page's text as Markdown.\n3. notion_create_page needs a parent_page_id: Notion gives integrations no workspace root to write into, so find a parent with notion_search first.\n4. notion_append_to_page adds to the end of a page and never overwrites existing content.\n\nThe one thing that trips users up: an integration can only see pages that have been explicitly shared with it (open the page in Notion → ⋯ → Connections → add the integration). If a search comes back empty or a read returns 'could not find page', that is almost always the cause — tell the user to share the page rather than concluding it does not exist.\n\nNotion is the right destination for notes, meeting summaries, research write-ups and reference material the user wants to keep. For short-lived items with a due date, prefer create_task (Microsoft To Do); for the agent's own working plan use todowrite."+}diff --git a/app/src/main/assets/skills/outlook.json b/app/src/main/assets/skills/outlook.jsonnew file mode 100644index 0000000..173e7d9--- /dev/null+++ b/app/src/main/assets/skills/outlook.json@@ -0,0 +1,7 @@+{+ "id": "outlook_microsoft",+ "targetPackageNames": ["com.microsoft.office.outlook", "com.microsoft.todos"],+ "name": "Outlook and Microsoft To Do Skills",+ "description": "Use the Microsoft Graph connector tools instead of automating Outlook or To Do.",+ "instructions": "Never automate the Outlook or Microsoft To Do UI. When the Microsoft connector is set up (Settings → Connectors), these tools talk to the account directly:\n\nMail — the ordinary email tools cover Outlook, no separate tools exist:\n1. list_emails returns rows whose ids start with 'ms:' when Outlook is the active backend.\n2. read_email and mark_email_read route by that id prefix, so ids stay valid.\n3. send_email always shows the user a confirmation dialog before anything leaves the device.\nNote the backend order: if a Gmail connector is also set up, Gmail is used for new listings and sends. Existing 'ms:' ids still resolve to Outlook.\n\nTasks — list_tasks, create_task and complete_task read and write the user's real Microsoft To Do lists, which sync to their other devices. These are NOT the same as todowrite: todowrite is your own scratch plan for the current conversation and disappears afterwards. If the user says 'remind me to…', 'add to my to-do list', or 'put it on my list', they mean create_task. Use todowrite only to track your own steps through a multi-part request.\n\nCalendar — use list_calendar_events / create_calendar_event with source='microsoft', and check_availability for free/busy questions.\n\nIf a tool reports that the sign-in expired or needs reconnecting, tell the user to reconnect in Settings → Connectors; do not try to work around it through the UI."+}diff --git a/app/src/main/java/com/gotcha/connectors/ConnectorRegistry.kt b/app/src/main/java/com/gotcha/connectors/ConnectorRegistry.ktindex 7ad7162..1c38c38 100644--- a/app/src/main/java/com/gotcha/connectors/ConnectorRegistry.kt+++ b/app/src/main/java/com/gotcha/connectors/ConnectorRegistry.kt@@ -1,9 +1,15 @@package com.gotcha.connectorsimport android.content.Context+import com.gotcha.connectors.calendar.CalendarToolDevice+import com.gotcha.connectors.calendar.CalendarToolsimport com.gotcha.connectors.google.GoogleConnectorimport com.gotcha.connectors.imap.ImapConnectorimport com.gotcha.connectors.mail.EmailTools+import com.gotcha.connectors.microsoft.MicrosoftConnector+import com.gotcha.connectors.microsoft.TaskTools+import com.gotcha.connectors.notion.NotionConnector+import com.gotcha.connectors.notion.NotionToolsimport com.gotcha.tools.ToolResultimport kotlinx.serialization.json.JsonObject@@ -17,6 +23,9 @@ object ConnectorRegistry {@Volatileprivate var connectors: List<Connector> = emptyList()+ @Volatile+ private var routers: List<ToolRouter> = emptyList()+@Volatileprivate var emailTools: EmailTools? = null@@ -31,8 +40,24 @@ object ConnectorRegistry {val store = ConnectorCredentialStore(appContext)val imap = ImapConnector(store)val google = GoogleConnector(store)- connectors = listOf(imap, google)- emailTools = EmailTools(appContext, imap, google)+ val microsoft = MicrosoftConnector(store)+ val notion = NotionConnector(store)+ connectors = listOf(imap, google, microsoft, notion)++ val email = EmailTools(appContext, imap, google, microsoft)+ emailTools = email+ routers = listOf(+ email,+ TaskTools { microsoft },+ CalendarTools(+ // Stateless ContentResolver wrapper — safe to hold a second instance+ // beside ToolExecutor's, which still serves the confirmed-delete path.+ device = CalendarToolDevice(com.gotcha.tools.CalendarTool(appContext)),+ google = { google },+ microsoft = { microsoft }+ ),+ NotionTools { notion }+ )initialized = true}}@@ -49,8 +74,6 @@ object ConnectorRegistry {* else null. ToolExecutor calls this first; null falls through to the* built-in dispatch.*/- fun toolHandler(name: String): (suspend (String, JsonObject) -> ToolResult)? {- val email = emailTools ?: return null- return if (name in email.toolNames) email::execute else null- }+ fun toolHandler(name: String): (suspend (String, JsonObject) -> ToolResult)? =+ routers.firstOrNull { name in it.toolNames }?.let { router -> router::execute }}diff --git a/app/src/main/java/com/gotcha/tools/ToolCategories.kt b/app/src/main/java/com/gotcha/tools/ToolCategories.ktindex c7aef77..646dcc4 100644--- a/app/src/main/java/com/gotcha/tools/ToolCategories.kt+++ b/app/src/main/java/com/gotcha/tools/ToolCategories.kt@@ -35,7 +35,9 @@ object ToolCategories {"lock_screen", "disable_camera", "set_password_policy","dismiss_notifications", "media_control","vibrate", "write_secure_settings",- "send_email", "mark_email_read"+ "send_email", "mark_email_read",+ "create_task", "complete_task",+ "notion_create_page", "notion_append_to_page")fun classify(toolName: String): Category = when {diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.ktindex ea47fcf..abb3a26 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -440,9 +440,19 @@ object ToolDefinitions {val listCalendarEvents = tool("list_calendar_events","List calendar events within a date range. Supports looking ahead (days_ahead) or explicit " +- "from/to dates, title keyword search, and shows status, description preview, and calendar name.",+ "from/to dates, title keyword search, and shows status, description preview, and calendar name. " ++ "Reads the phone's own calendars by default; set source to read a connected Google or " ++ "Outlook account instead.",schema {putJsonObject("properties") {+ putJsonObject("source") {+ put("type", "string")+ put(+ "description",+ "Which calendar to read: 'device' (default, the phone's own calendars), " ++ "'google' or 'microsoft' (needs that connector in Settings)."+ )+ }putJsonObject("days_ahead") {put("type", "integer")put(@@ -469,9 +479,19 @@ object ToolDefinitions {val createCalendarEvent = tool("create_calendar_event","Add an event to a calendar. Supports optional description, all-day flag, reminder, " +- "and calendar selection. Defaults to the primary writable calendar.",+ "and calendar selection. Writes to the phone's primary writable calendar by default; " ++ "set source to write to a connected Google or Outlook account instead.",schema {putJsonObject("properties") {+ putJsonObject("source") {+ put("type", "string")+ put(+ "description",+ "Where to create it: 'device' (default), 'google' or 'microsoft' " ++ "(needs that connector in Settings). all_day, reminder_minutes and " ++ "recurrence apply to source='device' only."+ )+ }putJsonObject("title") {put("type", "string")put("description", "Event title.")@@ -541,10 +561,44 @@ object ToolDefinitions {})+ val checkAvailability = tool(+ "check_availability",+ "Find when the user is busy and free in a date range, using the free/busy data of a " ++ "connected Google Calendar or Outlook account. This is the only way to get real " ++ "availability — the phone's own calendar copy cannot answer it. Returns merged busy " ++ "blocks plus free slots of at least duration_minutes. Requires a connected account; " ++ "for on-device calendars fall back to list_calendar_events.",+ schema {+ putJsonObject("properties") {+ putJsonObject("days_ahead") {+ put("type", "integer")+ put("description", "How many days ahead to check (1-365). Default 7.")+ }+ putJsonObject("from_date") {+ put("type", "string")+ put("description", "Start date, e.g. '2026-01-01'. Overrides days_ahead.")+ }+ putJsonObject("to_date") {+ put("type", "string")+ put("description", "End date, e.g. '2026-01-31'. Defaults to one day after from_date.")+ }+ putJsonObject("duration_minutes") {+ put("type", "integer")+ put(+ "description",+ "Minimum length of a usable free slot, in minutes. Default 30."+ )+ }+ }+ }+ )+val editCalendarEvent = tool("edit_calendar_event",- "Update an existing calendar event. Only the fields you provide will be changed. " +- "Get the event ID from list_calendar_events first.",+ "Update an existing calendar event on the phone's own calendar. Only the fields you " ++ "provide will be changed. Get the event ID from list_calendar_events first — this " ++ "works on bare numeric device ids only, not on 'gcal:'/'ms:' ids from a connected " ++ "account.",schema {putJsonObject("properties") {putJsonObject("event_id") {@@ -606,8 +660,9 @@ object ToolDefinitions {val deleteCalendarEvent = tool("delete_calendar_event",- "Permanently delete a calendar event. Requires explicit user confirmation (destructive action). " +- "Get the event ID from list_calendar_events first.",+ "Permanently delete an event from the phone's own calendar. Requires explicit user " ++ "confirmation (destructive action). Get the event ID from list_calendar_events first — " ++ "bare numeric device ids only, not 'gcal:'/'ms:' ids from a connected account.",schema {putJsonObject("properties") {putJsonObject("event_id") {@@ -1664,19 +1719,45 @@ object ToolDefinitions {val mediaControl = tool("media_control",- "Control the currently playing media session: play, pause, next, previous, or stop. " +- "Needs Notification access.",+ "Control a media session in whichever app is playing — Spotify, YouTube Music, a " ++ "podcast player, anything with a media notification. Works without any per-service " ++ "API or account. When several apps hold a session, the one actually playing is " ++ "chosen; pass 'app' to target a specific one. Needs Notification access. " ++ "Use get_now_playing first if you need to know what is playing.",schema {putJsonObject("properties") {putJsonObject("action") {put("type", "string")- put("description", "One of: play, pause, next, previous, stop.")+ put(+ "description",+ "One of: play, pause, toggle, next, previous, stop, seek, fast_forward, rewind."+ )+ }+ putJsonObject("app") {+ put("type", "string")+ put(+ "description",+ "Optional: target this app specifically (matches package name or app " ++ "label, e.g. 'spotify'). Omit to use whichever app is playing."+ )+ }+ putJsonObject("position_seconds") {+ put("type", "integer")+ put("description", "Required for action='seek': position to jump to, in seconds.")}}putJsonArray("required") { add("action") }})+ val getNowPlaying = tool(+ "get_now_playing",+ "Report what every app with an active media session is currently playing: app, playback " ++ "state, title, artist, album, and position/duration. Use this to answer 'what song is " ++ "this?' or to pick the right 'app' value for media_control. Needs Notification access.",+ schema { putJsonObject("properties") {} }+ )+val showOverlay = tool("show_overlay","Display a floating text banner on top of other apps. Needs the 'Display over other apps' permission.",@@ -1936,6 +2017,210 @@ object ToolDefinitions {})+ // ---- Persistent to-do tools (Microsoft To Do connector) ----++ val listTasks = tool(+ "list_tasks",+ "List the user's real, persistent to-do items from their connected Microsoft To Do " ++ "account. These sync to the user's other devices — this is NOT the same as " ++ "todowrite, which is only your own scratch plan for the current conversation. " ++ "Returns rows of [id] state | title | due date; use the id with complete_task.",+ schema {+ putJsonObject("properties") {+ putJsonObject("list") {+ put("type", "string")+ put(+ "description",+ "Optional task-list name (e.g. 'Groceries'). Defaults to the account's main list."+ )+ }+ putJsonObject("include_completed") {+ put("type", "boolean")+ put("description", "Include already-completed tasks. Default false.")+ }+ putJsonObject("max") {+ put("type", "integer")+ put("description", "Max tasks to return (1-100). Default 25.")+ }+ }+ }+ )++ val createTask = tool(+ "create_task",+ "Add a persistent to-do item to the user's connected Microsoft To Do account, so it " ++ "survives this conversation and syncs to their other devices. Use todowrite instead " ++ "when you only need to track your own steps for the current task.",+ schema {+ putJsonObject("properties") {+ putJsonObject("title") {+ put("type", "string")+ put("description", "What the task is, e.g. 'Renew passport'.")+ }+ putJsonObject("notes") {+ put("type", "string")+ put("description", "Optional longer description.")+ }+ putJsonObject("due_date") {+ put("type", "string")+ put("description", "Optional due date as YYYY-MM-DD.")+ }+ putJsonObject("list") {+ put("type", "string")+ put("description", "Optional task-list name. Defaults to the account's main list.")+ }+ }+ putJsonArray("required") { add("title") }+ }+ )++ val completeTask = tool(+ "complete_task",+ "Mark a to-do item complete (or reopen it) by the id returned from list_tasks, " ++ "e.g. 'ms:<listId>:<taskId>'.",+ schema {+ putJsonObject("properties") {+ putJsonObject("id") {+ put("type", "string")+ put("description", "Task id from list_tasks.")+ }+ putJsonObject("completed") {+ put("type", "boolean")+ put("description", "true = mark complete (default), false = reopen.")+ }+ }+ putJsonArray("required") { add("id") }+ }+ )++ // ---- Notion connector tools ----++ val notionSearch = tool(+ "notion_search",+ "Search the user's Notion workspace for pages and databases. Only pages that have been " ++ "explicitly shared with the integration are visible — an empty result usually means " ++ "the page was never shared, not that it does not exist. Returns [id] rows; use the " ++ "id with notion_read_page or notion_append_to_page.",+ schema {+ putJsonObject("properties") {+ putJsonObject("query") {+ put("type", "string")+ put("description", "Text to match against page titles. Omit to list everything shared.")+ }+ putJsonObject("max") {+ put("type", "integer")+ put("description", "Max results to return (1-100). Default 20.")+ }+ }+ }+ )++ val notionReadPage = tool(+ "notion_read_page",+ "Read a Notion page's title and full text content as Markdown, using a page id from " ++ "notion_search.",+ schema {+ putJsonObject("properties") {+ putJsonObject("page_id") {+ put("type", "string")+ put("description", "Page id from notion_search.")+ }+ }+ putJsonArray("required") { add("page_id") }+ }+ )++ val notionCreatePage = tool(+ "notion_create_page",+ "Create a new Notion page underneath an existing one. Notion has no workspace root an " ++ "integration can write to, so a parent_page_id is always required — find one with " ++ "notion_search first. Content accepts Markdown (headings, bullets, numbered lists, " ++ "to-dos, quotes).",+ schema {+ putJsonObject("properties") {+ putJsonObject("title") {+ put("type", "string")+ put("description", "Title of the new page.")+ }+ putJsonObject("parent_page_id") {+ put("type", "string")+ put("description", "Id of the page to create this one under, from notion_search.")+ }+ putJsonObject("content") {+ put("type", "string")+ put("description", "Optional Markdown body for the new page.")+ }+ }+ putJsonArray("required") {+ add("title")+ add("parent_page_id")+ }+ }+ )++ val notionAppendToPage = tool(+ "notion_append_to_page",+ "Append Markdown content to the end of an existing Notion page. Adds to the page — it " ++ "never replaces or deletes what is already there.",+ schema {+ putJsonObject("properties") {+ putJsonObject("page_id") {+ put("type", "string")+ put("description", "Page id from notion_search.")+ }+ putJsonObject("content") {+ put("type", "string")+ put("description", "Markdown content to append.")+ }+ }+ putJsonArray("required") {+ add("page_id")+ add("content")+ }+ }+ )++ // ---- Health Connect tools (on-device, read-only) ----++ val getHealthSummary = tool(+ "get_health_summary",+ "Summarise the user's health and fitness data from Health Connect over the last N days: " ++ "steps, distance, active calories, sleep, average/peak/resting heart rate and weight. " ++ "Reads on-device data only — nothing is uploaded and nothing is ever written. Metrics " ++ "with no data are omitted rather than reported as zero.",+ schema {+ putJsonObject("properties") {+ putJsonObject("days") {+ put("type", "integer")+ put("description", "How many days back to summarise (1-365). Default 7.")+ }+ }+ }+ )++ val getHealthRecords = tool(+ "get_health_records",+ "List individual Health Connect records of one type, for questions the summary cannot " ++ "answer (e.g. 'which days did I walk over 10000 steps?', 'when did I work out?'). " ++ "Read-only.",+ schema {+ putJsonObject("properties") {+ putJsonObject("type") {+ put("type", "string")+ put(+ "description",+ "Record type: " + HealthTool.RECORD_TYPE_NAMES.joinToString(", ") + "."+ )+ }+ putJsonObject("days") {+ put("type", "integer")+ put("description", "How many days back to read (1-365). Default 7.")+ }+ }+ putJsonArray("required") { add("type") }+ }+ )+val all: List<ToolDefinition> = listOf(dialNumber, getStorageInfo, getBatteryInfo, listFiles, readFile, writeFile,openApp, setBrightness, toggleWifi,@@ -1943,6 +2228,7 @@ object ToolDefinitions {// Tier 0–2 additionscallNumber, readCallLog, findContact, addContact, sendSms, readRecentSms,listCalendarEvents, createCalendarEvent, editCalendarEvent, deleteCalendarEvent,+ checkAvailability,setAlarm, setTimer, listAlarms, listTimers, editAlarm, deleteAlarm, deleteTimer,toggleTorch, setVolume, getVolume, setRingerMode, vibrate, setDnd,getLocation, listInstalledApps, uninstallApp, getAppUsage, getDataUsage,@@ -1967,7 +2253,7 @@ object ToolDefinitions {// Tier 3 additionsreadScreen, readScreenRaw, tap, longPress, swipe, tapIndex, longPressIndex, pressKey, inputText, globalAction,navigateApp,- readNotifications, dismissNotifications, mediaControl,+ readNotifications, dismissNotifications, mediaControl, getNowPlaying,showOverlay, hideOverlay,lockScreen, disableCamera, setPasswordPolicy,@@ -1979,6 +2265,15 @@ object ToolDefinitions {// Email connector toolslistEmails, readEmail, sendEmail, markEmailRead, composeEmail,+ // Persistent to-do connector tools+ listTasks, createTask, completeTask,++ // Notion connector tools+ notionSearch, notionReadPage, notionCreatePage, notionAppendToPage,++ // Health Connect (on-device, read-only)+ getHealthSummary, getHealthRecords,+// Clock enhancementsshowAlarms, snoozeAlarm, dismissTimer)diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.ktindex f12051c..636c6a3 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -61,6 +61,7 @@ class ToolExecutor(// Tier 4 toolsprivate val rootTool = RootTool()+ private val healthTool = HealthTool(appContext)private val actionLog = ActionLog(appContext)init {@@ -231,26 +232,9 @@ class ToolExecutor(search = args.requireString("search"),includeSent = args["include_sent"]?.jsonPrimitive?.booleanOrNull)- "list_calendar_events" -> calendarTool.listEvents(- daysAhead = args.requireInt("days_ahead"),- fromDate = args.requireString("from_date"),- toDate = args.requireString("to_date"),- search = args.requireString("search")- )- "create_calendar_event" -> calendarTool.createEvent(- title = args.requireString("title") ?: return missing("title"),- start = args.requireString("start") ?: return missing("start"),- end = args.requireString("end"),- location = args.requireString("location"),- description = args.requireString("description"),- allDay = args["all_day"]?.jsonPrimitive?.booleanOrNull,- reminderMinutes = args.requireInt("reminder_minutes"),- calendarName = args.requireString("calendar_name"),- attendees = args.requireStringList("attendees"),- recurrence = args.requireString("recurrence"),- recurrenceCount = args.requireInt("recurrence_count"),- recurrenceUntil = args.requireString("recurrence_until")- )+ // list_calendar_events / create_calendar_event / check_availability are owned by+ // ConnectorRegistry's CalendarTools router, which delegates the default+ // source="device" back to this same CalendarTool."edit_calendar_event" -> calendarTool.editEvent(eventId = args.requireInt("event_id")?.toLong() ?: return missing("event_id"),title = args.requireString("title"),@@ -461,7 +445,17 @@ class ToolExecutor(app = args.requireString("app"))"dismiss_notifications" -> notificationTool.dismissNotifications(args.requireString("key"))- "media_control" -> notificationTool.mediaControl(args.requireString("action") ?: return missing("action"))+ "get_health_summary" -> healthTool.getSummary(args.requireInt("days"))+ "get_health_records" -> healthTool.getRecords(+ type = args.requireString("type") ?: return missing("type"),+ daysArg = args.requireInt("days")+ )+ "media_control" -> notificationTool.mediaControl(+ action = args.requireString("action") ?: return missing("action"),+ app = args.requireString("app"),+ positionSeconds = args.requireInt("position_seconds")+ )+ "get_now_playing" -> notificationTool.getNowPlaying()"show_overlay" -> overlayTool.showOverlay(text = args.requireString("text") ?: return missing("text"),durationMs = args.requireInt("duration_ms") ?: 4000diff --git a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt b/app/src/main/java/com/gotcha/tools/ToolRegistry.ktindex 538f239..e442643 100644--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt@@ -26,7 +26,7 @@ object ToolRegistry {val monitorTools: Set<String> = setOf("dial_number", "read_call_log", "find_contact", "read_recent_sms",- "list_calendar_events",+ "list_calendar_events", "check_availability","get_storage_info", "get_battery_info", "get_location", "get_volume","get_audio_recording_status","get_app_usage", "get_data_usage",@@ -39,7 +39,11 @@ object ToolRegistry {"get_clipboard","read_screen", "read_notifications","check_root", "search_skills",- "list_emails", "read_email"+ "list_emails", "read_email",+ "list_tasks",+ "notion_search", "notion_read_page",+ "get_health_summary", "get_health_records",+ "get_now_playing")/** Full Operator tool set minus task + navigate_app (sub-agents cannot delegate further). */diff --git a/app/src/main/java/com/gotcha/ui/ConnectorsSection.kt b/app/src/main/java/com/gotcha/ui/ConnectorsSection.ktindex 4c46a00..041898c 100644--- a/app/src/main/java/com/gotcha/ui/ConnectorsSection.kt+++ b/app/src/main/java/com/gotcha/ui/ConnectorsSection.kt@@ -2,12 +2,13 @@ package com.gotcha.uiimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.text.KeyboardOptions-import androidx.compose.material3.Button+import androidx.compose.foundation.layout.width+import androidx.compose.material3.Checkboximport androidx.compose.material3.HorizontalDividerimport androidx.compose.material3.MaterialTheme-import androidx.compose.material3.OutlinedButtonimport androidx.compose.material3.OutlinedTextFieldimport androidx.compose.material3.Textimport androidx.compose.material3.TextButton@@ -15,273 +16,226 @@ import androidx.compose.runtime.Composableimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.remember-import androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.setValue+import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContext-import androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.text.input.KeyboardType-import androidx.compose.ui.text.input.PasswordVisualTransformationimport androidx.compose.ui.unit.dpimport com.gotcha.connectors.ConnectorRegistry-import com.gotcha.connectors.google.GoogleOAuthFlow+import com.gotcha.connectors.google.GoogleConnector+import com.gotcha.connectors.imap.ImapConnectorimport com.gotcha.connectors.imap.ImapCredentials-import kotlinx.coroutines.launch+import com.gotcha.connectors.microsoft.MicrosoftConnector+import com.gotcha.connectors.notion.NotionConnector+import com.gotcha.connectors.oauth.OAuthConnectFlow/**- * Settings → Connectors: one card per connector (IMAP app-password, Gmail- * BYO-OAuth). Talks to [ConnectorRegistry] directly since connectors own their- * own credential storage — there is nothing for the Settings/SettingsRepository- * layer to persist.+ * Settings → Connectors: one card per connector, built from the two reusable+ * shapes in ConnectorCards.kt. Talks to [ConnectorRegistry] directly since+ * connectors own their own credential storage — there is nothing for the+ * Settings/SettingsRepository layer to persist.*/@Composablefun ConnectorsSection() {val context = LocalContext.currentremember { ConnectorRegistry.init(context) }- val imap = remember { ConnectorRegistry.byId("imap") as com.gotcha.connectors.imap.ImapConnector }- val google = remember { ConnectorRegistry.byId("google") as com.gotcha.connectors.google.GoogleConnector }+ val imap = remember { ConnectorRegistry.byId("imap") as ImapConnector }+ val google = remember { ConnectorRegistry.byId("google") as GoogleConnector }+ val microsoft = remember { ConnectorRegistry.byId("microsoft") as MicrosoftConnector }+ val notion = remember { ConnectorRegistry.byId("notion") as NotionConnector }Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {ImapCard(imap)HorizontalDivider(thickness = 1.dp)- GoogleCard(google, context)+ GoogleCard(google)+ HorizontalDivider(thickness = 1.dp)+ MicrosoftCard(microsoft)+ HorizontalDivider(thickness = 1.dp)+ NotionCard(notion)}}@Composable-private fun ImapCard(imap: com.gotcha.connectors.imap.ImapConnector) {- var refreshTick by remember { mutableStateOf(0) }- var email by remember { mutableStateOf(imap.credentials()?.email ?: "") }- var appPassword by remember { mutableStateOf("") }- var imapHost by remember { mutableStateOf(imap.credentials()?.imapHost ?: "imap.gmail.com") }- var imapPort by remember { mutableStateOf((imap.credentials()?.imapPort ?: 993).toString()) }- var smtpHost by remember { mutableStateOf(imap.credentials()?.smtpHost ?: "smtp.gmail.com") }- var smtpPort by remember { mutableStateOf((imap.credentials()?.smtpPort ?: 465).toString()) }- var status by remember { mutableStateOf("") }+private fun NotionCard(notion: NotionConnector) {+ val token = rememberTokenField("Internal integration token", "", secret = true)- Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {- Text("Email (IMAP)", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Medium)- Text(imap.statusLine(), style = MaterialTheme.typography.bodyMedium)+ TokenConnectorCard(+ title = "Notion",+ statusLine = notion::statusLine,+ isConnected = notion::isConnected,+ fields = listOf(token),+ blurb = "Search, read and write Notion pages using an internal integration in your own " ++ "workspace — no OAuth app to register.",+ steps = listOf(+ "1. Go to notion.so/my-integrations ▸ New integration, in your workspace.",+ "2. Give it Read, Insert and Update content capabilities.",+ "3. Copy the Internal Integration Secret and paste it below.",+ "4. Important: open each page you want reachable and use ⋯ ▸ Connections ▸ " ++ "add the integration. Pages that are not shared stay invisible to it."+ ),+ onConnect = { notion.connect(token.value) },+ onDisconnect = notion::disconnect+ )+}- if (!imap.isConnected()) {- OutlinedTextField(- value = email,- onValueChange = { email = it },- label = { Text("Email address") },- singleLine = true,- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),- modifier = Modifier.fillMaxWidth()- )- OutlinedTextField(- value = appPassword,- onValueChange = { appPassword = it },- label = { Text("App password") },- singleLine = true,- visualTransformation = PasswordVisualTransformation(),- modifier = Modifier.fillMaxWidth()- )- Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {- Text(- "Needs an app password, not your regular password. Requires " +- "2-Step Verification to be enabled first.",- style = MaterialTheme.typography.bodySmall- )- Text(- "Generate one at myaccount.google.com/apppasswords, or via " +- "Google Account ▸ Security ▸ 2-Step Verification ▸ App passwords.",- style = MaterialTheme.typography.bodySmall- )- Text(- "Other providers: check their IMAP app-password documentation.",- style = MaterialTheme.typography.bodySmall- )- }+@Composable+private fun ImapCard(imap: ImapConnector) {+ val saved = imap.credentials()+ val email = rememberTokenField("Email address", saved?.email ?: "", keyboard = KeyboardType.Email)+ val appPassword = rememberTokenField("App password", "", secret = true)+ val imapHost = rememberTokenField("IMAP host", saved?.imapHost ?: "imap.gmail.com")+ val imapPort = rememberTokenField("IMAP port", (saved?.imapPort ?: 993).toString(), keyboard = KeyboardType.Number)+ val smtpHost = rememberTokenField("SMTP host", saved?.smtpHost ?: "smtp.gmail.com")+ val smtpPort = rememberTokenField("SMTP port", (saved?.smtpPort ?: 465).toString(), keyboard = KeyboardType.Number)+ val fields = listOf(email, appPassword, imapHost, imapPort, smtpHost, smtpPort)++ TokenConnectorCard(+ title = "Email (IMAP)",+ statusLine = imap::statusLine,+ isConnected = imap::isConnected,+ fields = fields,+ steps = listOf(+ "Needs an app password, not your regular password. Requires " ++ "2-Step Verification to be enabled first.",+ "Generate one at myaccount.google.com/apppasswords, or via " ++ "Google Account ▸ Security ▸ 2-Step Verification ▸ App passwords.",+ "Other providers: check their IMAP app-password documentation."+ ),+ aboveFields = {TextButton(onClick = {- imapHost = "imap.gmail.com"- imapPort = "993"- smtpHost = "smtp.gmail.com"- smtpPort = "465"+ imapHost.value = "imap.gmail.com"+ imapPort.value = "993"+ smtpHost.value = "smtp.gmail.com"+ smtpPort.value = "465"}) { Text("Use Gmail preset") }- OutlinedTextField(- value = imapHost,- onValueChange = { imapHost = it },- label = { Text("IMAP host") },- singleLine = true,- modifier = Modifier.fillMaxWidth()- )- OutlinedTextField(- value = imapPort,- onValueChange = { imapPort = it },- label = { Text("IMAP port") },- singleLine = true,- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),- modifier = Modifier.fillMaxWidth()- )- OutlinedTextField(- value = smtpHost,- onValueChange = { smtpHost = it },- label = { Text("SMTP host") },- singleLine = true,- modifier = Modifier.fillMaxWidth()- )- OutlinedTextField(- value = smtpPort,- onValueChange = { smtpPort = it },- label = { Text("SMTP port") },- singleLine = true,- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),- modifier = Modifier.fillMaxWidth()+ },+ onConnect = {+ imap.connect(+ ImapCredentials(+ email = email.value.trim(),+ appPassword = appPassword.value.trim(),+ imapHost = imapHost.value.trim(),+ imapPort = imapPort.value.toIntOrNull() ?: 993,+ smtpHost = smtpHost.value.trim(),+ smtpPort = smtpPort.value.toIntOrNull() ?: 465+ ))- Button(- onClick = {- val port = imapPort.toIntOrNull() ?: 993- val sPort = smtpPort.toIntOrNull() ?: 465- imap.connect(- ImapCredentials(- email = email.trim(),- appPassword = appPassword.trim(),- imapHost = imapHost.trim(),- imapPort = port,- smtpHost = smtpHost.trim(),- smtpPort = sPort- )- )- status = "Saved. Credentials are verified on first use."- refreshTick++- },- enabled = email.isNotBlank() && appPassword.isNotBlank() &&- imapHost.isNotBlank() && smtpHost.isNotBlank(),- modifier = Modifier.fillMaxWidth()- ) { Text("Connect") }- } else {- OutlinedButton(- onClick = {- imap.disconnect()- appPassword = ""- status = "Disconnected."- refreshTick++- },- modifier = Modifier.fillMaxWidth()- ) { Text("Disconnect") }- }- if (status.isNotBlank()) Text(status, style = MaterialTheme.typography.bodySmall)- // Force recomposition of statusLine() after connect/disconnect.- if (refreshTick >= 0) Unit- }+ "Saved. Credentials are verified on first use."+ },+ onDisconnect = imap::disconnect+ )}@Composable-private fun GoogleCard(- google: com.gotcha.connectors.google.GoogleConnector,- context: android.content.Context-) {- val scope = rememberCoroutineScope()- var refreshTick by remember { mutableStateOf(0) }- var clientId by remember { mutableStateOf(google.credentials()?.clientId ?: "") }- var clientSecret by remember { mutableStateOf(google.credentials()?.clientSecret ?: "") }- var pastedUrl by remember { mutableStateOf("") }- var showPasteFallback by remember { mutableStateOf(false) }- var busy by remember { mutableStateOf(false) }- var status by remember { mutableStateOf("") }- val flow = remember(google) { GoogleOAuthFlow(context, google) }-- Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {- Text("Gmail (BYO OAuth)", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Medium)- Text(google.statusLine(), style = MaterialTheme.typography.bodyMedium)- Text(- "Full read/write Gmail access using your own Google Cloud OAuth client — " +- "no shared app, no verification wait.",- style = MaterialTheme.typography.bodySmall+private fun GoogleCard(google: GoogleConnector) {+ val context = LocalContext.current+ // Which Google services to request consent for. Adding one later needs a reconnect,+ // because the refresh token only carries the scopes granted at consent time.+ var wantGmail by remember {+ mutableStateOf(google.credentials()?.scopes?.contains(GoogleConnector.SCOPE_GMAIL_MODIFY) ?: true)+ }+ var wantCalendar by remember { mutableStateOf(google.hasCalendar()) }+ val scopes = {+ buildList {+ if (wantGmail) add(GoogleConnector.SCOPE_GMAIL_MODIFY)+ if (wantCalendar) add(GoogleConnector.SCOPE_CALENDAR)+ }.ifEmpty { listOf(GoogleConnector.SCOPE_GMAIL_MODIFY) }+ }+ val flow = remember(google) {+ OAuthConnectFlow(+ context = context,+ configFor = { id, secret -> google.oauthConfig(id, secret.orEmpty(), scopes()) },+ onTokens = { id, secret, tokens ->+ google.completeConnect(id, secret.orEmpty(), tokens, scopes())+ },+ accountLabel = { google.credentials()?.accountEmail.orEmpty() })- Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {- Text("1. Create a Google Cloud project.", style = MaterialTheme.typography.bodySmall)- Text("2. Enable the Gmail API.", style = MaterialTheme.typography.bodySmall)+ }++ OAuthConnectorCard(+ title = "Google (Gmail, Calendar)",+ statusLine = google::statusLine,+ isConnected = google::isConnected,+ needsReconnect = google::needsReconnect,+ initialClientId = google.credentials()?.clientId ?: "",+ initialClientSecret = google.credentials()?.clientSecret ?: "",+ flow = flow,+ onDisconnect = google::disconnect,+ blurb = "Full read/write Gmail and Google Calendar access using your own Google Cloud " ++ "OAuth client — no shared app, no verification wait.",+ steps = listOf(+ "1. Create a Google Cloud project.",+ "2. Enable the Gmail API and/or the Google Calendar API — whichever you tick below.",+ "3. Configure the OAuth consent screen (External, add yourself as a " ++ "test user — or publish it to skip weekly reconnects).",+ "4. Create a Desktop app OAuth client.",+ "5. Paste its Client ID and secret below.",+ "6. Tap Connect."+ ),+ extraFields = {+ Text("Services to authorise:", style = MaterialTheme.typography.bodySmall)+ Row(verticalAlignment = Alignment.CenterVertically) {+ Checkbox(checked = wantGmail, onCheckedChange = { wantGmail = it })+ Text("Gmail", style = MaterialTheme.typography.bodyMedium)+ Spacer(Modifier.width(16.dp))+ Checkbox(checked = wantCalendar, onCheckedChange = { wantCalendar = it })+ Text("Calendar", style = MaterialTheme.typography.bodyMedium)+ }Text(- "3. Configure the OAuth consent screen (External, add yourself as a " +- "test user — or publish it to skip weekly reconnects).",+ "Changing this needs a reconnect — the saved sign-in only carries the scopes " ++ "granted at consent time.",style = MaterialTheme.typography.bodySmall)- Text("4. Create a Desktop app OAuth client.", style = MaterialTheme.typography.bodySmall)- Text("5. Paste its Client ID and secret below.", style = MaterialTheme.typography.bodySmall)- Text("6. Tap Connect.", style = MaterialTheme.typography.bodySmall)}+ )+}- if (!google.isConnected() || google.needsReconnect()) {- OutlinedTextField(- value = clientId,- onValueChange = { clientId = it },- label = { Text("Client ID") },- singleLine = true,- modifier = Modifier.fillMaxWidth()- )+@Composable+private fun MicrosoftCard(microsoft: MicrosoftConnector) {+ val context = LocalContext.current+ // "common" covers personal and work accounts; a tenant id/domain locks it to one org.+ var tenant by remember {+ mutableStateOf(microsoft.credentials()?.tenant ?: MicrosoftConnector.DEFAULT_TENANT)+ }+ val flow = remember(microsoft) {+ OAuthConnectFlow(+ context = context,+ configFor = { id, _ -> microsoft.oauthConfig(id, tenant.trim()) },+ onTokens = { id, _, tokens -> microsoft.completeConnect(id, tenant.trim(), tokens) },+ accountLabel = { microsoft.credentials()?.accountEmail.orEmpty() }+ )+ }++ OAuthConnectorCard(+ title = "Microsoft (Outlook, Calendar, To Do)",+ statusLine = microsoft::statusLine,+ isConnected = microsoft::isConnected,+ needsReconnect = microsoft::needsReconnect,+ initialClientId = microsoft.credentials()?.clientId ?: "",+ // Public client — PKCE only, so there is no secret to paste.+ initialClientSecret = null,+ flow = flow,+ onDisconnect = microsoft::disconnect,+ blurb = "Outlook mail, calendar and To Do using your own Entra app registration. " ++ "One sign-in covers all three.",+ steps = listOf(+ "1. Go to portal.azure.com ▸ Microsoft Entra ID ▸ App registrations ▸ New.",+ "2. Under \"Redirect URI\" pick \"Public client/native\" and enter http://localhost.",+ "3. In API permissions add delegated Microsoft Graph permissions: " ++ "offline_access, User.Read, Mail.ReadWrite, Mail.Send, Calendars.ReadWrite, " ++ "Tasks.ReadWrite.",+ "4. Copy the Application (client) ID from the Overview page.",+ "5. Paste it below and tap Connect. Leave Tenant as \"common\" for personal accounts."+ ),+ extraFields = {OutlinedTextField(- value = clientSecret,- onValueChange = { clientSecret = it },- label = { Text("Client secret") },+ value = tenant,+ onValueChange = { tenant = it },+ label = { Text("Tenant (common, or your organisation's tenant ID)") },singleLine = true,- visualTransformation = PasswordVisualTransformation(),modifier = Modifier.fillMaxWidth())- Button(- onClick = {- busy = true- status = "Opening sign-in…"- scope.launch {- when (val outcome = flow.connect(clientId, clientSecret)) {- is GoogleOAuthFlow.Outcome.Connected ->- status = "Connected as ${outcome.email}."- is GoogleOAuthFlow.Outcome.Failed ->- status = outcome.message- }- busy = false- refreshTick++- }- },- enabled = !busy && clientId.isNotBlank() && clientSecret.isNotBlank(),- modifier = Modifier.fillMaxWidth()- ) { Text(if (busy) "Waiting for sign-in…" else "Connect") }-- TextButton(onClick = { showPasteFallback = !showPasteFallback }) {- Text(if (showPasteFallback) "Hide paste-URL fallback" else "Browser didn't return? Paste redirect URL")- }- if (showPasteFallback) {- OutlinedTextField(- value = pastedUrl,- onValueChange = { pastedUrl = it },- label = { Text("Pasted redirect URL") },- singleLine = true,- modifier = Modifier.fillMaxWidth()- )- Button(- onClick = {- busy = true- scope.launch {- when (val outcome = flow.connectWithPastedUrl(clientId, clientSecret, pastedUrl)) {- is GoogleOAuthFlow.Outcome.Connected ->- status = "Connected as ${outcome.email}."- is GoogleOAuthFlow.Outcome.Failed ->- status = outcome.message- }- busy = false- refreshTick++- }- },- enabled = !busy && pastedUrl.isNotBlank(),- modifier = Modifier.fillMaxWidth()- ) { Text("Finish sign-in with pasted URL") }- }- } else {- OutlinedButton(- onClick = {- google.disconnect()- clientSecret = ""- status = "Disconnected."- refreshTick++- },- modifier = Modifier.fillMaxWidth()- ) { Text("Disconnect") }}- if (status.isNotBlank()) Text(status, style = MaterialTheme.typography.bodySmall)- if (refreshTick >= 0) Unit- }+ )}diff --git a/app/src/test/java/com/gotcha/tools/ToolRegistryTest.kt b/app/src/test/java/com/gotcha/tools/ToolRegistryTest.ktindex 845cb88..f73bbcb 100644--- a/app/src/test/java/com/gotcha/tools/ToolRegistryTest.kt+++ b/app/src/test/java/com/gotcha/tools/ToolRegistryTest.kt@@ -47,4 +47,74 @@ class ToolRegistryTest {fun `unknown tools are rejected`() {assertTrue(!ToolRegistry.contains("install_apk"))}++ /**+ * Connector routers claim tool names by string. A name that is not in the+ * catalog would make the tool invisible to the model — and a typo would fail+ * silently, since ToolExecutor rejects unregistered names before dispatch.+ */+ @Test+ fun `every connector-router tool name is in the catalog`() {+ val routerToolNames = listOf(+ com.gotcha.connectors.mail.EmailTools(+ gmailBackend = { null },+ microsoftBackend = { null },+ imapBackend = { null },+ composeLauncher = { _, _, _ -> ToolResult.ok("") }+ ),+ com.gotcha.connectors.microsoft.TaskTools { null },+ com.gotcha.connectors.notion.NotionTools { null },+ com.gotcha.connectors.calendar.CalendarTools(+ device = NoopDeviceCalendar,+ google = { null },+ microsoft = { null }+ )+ ).flatMap { it.toolNames }++ assertTrue("no router claimed any tools", routerToolNames.isNotEmpty())+ routerToolNames.forEach { name ->+ assertTrue("router claims '$name' but it is not a registered tool", ToolRegistry.contains(name))+ }+ }++ /** Routers must not claim the same tool — ConnectorRegistry resolves to the first match. */+ @Test+ fun `connector routers do not claim overlapping tool names`() {+ val claimed = listOf(+ com.gotcha.connectors.microsoft.TaskTools { null }.toolNames,+ com.gotcha.connectors.notion.NotionTools { null }.toolNames,+ com.gotcha.connectors.calendar.CalendarTools(+ device = NoopDeviceCalendar,+ google = { null },+ microsoft = { null }+ ).toolNames+ )+ val all = claimed.flatten()+ assertEquals("a tool is claimed by more than one router", all.size, all.toSet().size)+ }++ private object NoopDeviceCalendar : com.gotcha.connectors.calendar.DeviceCalendar {+ override fun listEvents(+ daysAhead: Int?,+ fromDate: String?,+ toDate: String?,+ search: String?+ ): ToolResult = ToolResult.ok("")++ @Suppress("LongParameterList")+ override fun createEvent(+ title: String,+ start: String,+ end: String?,+ location: String?,+ description: String?,+ allDay: Boolean?,+ reminderMinutes: Int?,+ calendarName: String?,+ attendees: List<String>?,+ recurrence: String?,+ recurrenceCount: Int?,+ recurrenceUntil: String?+ ): ToolResult = ToolResult.ok("")+ }}diff --git a/docs/health-connect.md b/docs/health-connect.mdnew file mode 100644index 0000000..3919449--- /dev/null+++ b/docs/health-connect.md@@ -0,0 +1,62 @@+# Health Connect++Health Connect is Android's on-device store for health and fitness data. It is **not** a+connector: there is no account, no token and no network — the data never leaves the phone,+and the app only ever reads it.++Whatever fitness apps the user has (Fitbit, Samsung Health, Google Fit, Strava, a watch+companion app…) write into Health Connect, so reading it once covers all of them.++## Availability++| Android version | How it ships |+|---|---|+| 14 (API 34) and above | Built into the platform |+| 13 and below | A separate **Health Connect** app from the Play Store |++`get_health_summary` and `get_health_records` detect this. If no provider is present they+return an error telling the user to install or update Health Connect rather than failing+obscurely; tapping the permission entry in Settings opens the Play listing.++## Permissions++Health Connect uses its own `android.permission.health.*` grants, requested through Health+Connect's own screen rather than the standard Android runtime dialog. The app declares+read-only permissions for: steps, distance, active calories, sleep, heart rate, resting heart+rate, weight and exercise sessions.++Grant them from **Settings → Permissions → Health → Health Connect**, or by running a health+tool and letting it open the screen. Users can grant any subset — metrics with no permission+(or no data) are simply left out of the summary rather than reported as zero.++The Settings row reflects the **last known** grant state. Health Connect only reports grants+from a suspend call, which the synchronous permission list cannot make, so the row is+refreshed whenever a health tool runs or the permission screen returns.++## Tools++| Tool | Use for |+|---|---|+| `get_health_summary(days)` | Totals and averages over a window — "how did I sleep this week", "how active have I been". |+| `get_health_records(type, days)` | Individual records — "which days did I hit 10 000 steps", "when did I work out". Types: `steps`, `distance`, `calories`, `sleep`, `heart_rate`, `resting_heart_rate`, `weight`, `exercise`. |++Both are read-only in this version. The agent never writes to the user's health record.++## Before publishing to Google Play++Apps that read Health Connect data must complete Google's **health-data declaration form**+and be approved before they can be distributed on Play. Sideloaded and internally distributed+builds are unaffected. This does not block development, but it is a release-time+prerequisite — worth knowing before planning a Play listing.++## Manual end-to-end check++1. On a device **without** Health Connect: run `get_health_summary` and confirm it steers to+ installing it rather than crashing.+2. Grant permissions, then `get_health_summary` → figures match what the Health Connect app+ itself reports for the same window.+3. Revoke one data type in Health Connect → that metric disappears from the summary instead+ of showing zero.+4. Revoke everything → the tool reports that permissions are needed and reopens the screen.+5. `get_health_records("sleep", 7)` → individual sessions with start, end and duration.+6. `get_health_records("nonsense")` → a clear error listing the valid types.diff --git a/docs/microsoft-graph-setup.md b/docs/microsoft-graph-setup.mdnew file mode 100644index 0000000..3cd15f0--- /dev/null+++ b/docs/microsoft-graph-setup.md@@ -0,0 +1,87 @@+# Microsoft connector setup (Outlook, Calendar, To Do)++The Microsoft connector uses **your own** Entra (Azure AD) app registration, the same+bring-your-own-OAuth approach as the Gmail connector. Nothing is shared with other users of+the app, and no publisher verification is involved. One sign-in covers Outlook mail, the+Outlook calendar and Microsoft To Do.++Registering an app is free and works with a personal Microsoft account.++## 1. Register the app++1. Sign in at [portal.azure.com](https://portal.azure.com) and open **Microsoft Entra ID →+ App registrations → New registration**.+2. Name it anything (e.g. `Gotcha`).+3. Under **Supported account types**, pick the option that matches your account:+ - personal Outlook/Hotmail/Live account → *Accounts in any organizational directory and+ personal Microsoft accounts*+ - work or school account only → *Accounts in this organizational directory only*+4. Under **Redirect URI**, choose platform **Public client/native (mobile & desktop)** and+ enter `http://localhost`.+5. Register.++The redirect URI matters: Entra accepts **any port** on a `http://localhost` loopback+redirect for public clients, which is what lets the app catch the sign-in on a random local+port without you registering each one.++## 2. Add the permissions++**API permissions → Add a permission → Microsoft Graph → Delegated permissions**, then add:++| Permission | What it enables |+|---|---|+| `offline_access` | staying signed in — **without this no refresh token is issued** |+| `User.Read` | identifying which account is connected |+| `Mail.ReadWrite` | listing and reading mail, marking read/unread |+| `Mail.Send` | `send_email` |+| `Calendars.ReadWrite` | reading and creating calendar events, free/busy |+| `Tasks.ReadWrite` | Microsoft To Do |++You can leave out the ones you don't want — the corresponding tools will simply report a+permission error. On a work or school account an administrator may need to consent.++## 3. Connect++1. Copy the **Application (client) ID** from the registration's Overview page.+2. In the app: **Settings → Connectors → Microsoft**.+3. Paste the client ID. Leave **Tenant** as `common` for a personal account; for a work+ account that restricts external sign-in, use your tenant ID or domain.+4. Tap **Connect**. A browser tab opens for sign-in and consent, then returns to the app.++There is no client secret — this is a public client authenticated with PKCE.++### If the browser doesn't come back++Tap **"Browser didn't return? Paste redirect URL"**, copy the full+`http://localhost:.../?code=…` URL out of the browser's address bar, and paste it there.+This only works immediately after a Connect attempt, because it reuses that attempt's PKCE+verifier.++## What you get++| Tool | Notes |+|---|---|+| `list_emails`, `read_email`, `send_email`, `mark_email_read` | The normal email tools. Outlook message ids are prefixed `ms:`. If a Gmail connector is also set up, Gmail takes precedence for new listings and sends. |+| `list_calendar_events`, `create_calendar_event` | Pass `source="microsoft"`. The default stays the phone's own calendar. |+| `check_availability` | Free/busy across the connected account. |+| `list_tasks`, `create_task`, `complete_task` | Microsoft To Do. Distinct from `todowrite`, which is only the agent's in-conversation scratch plan. |++## Reconnecting++If the refresh token is invalidated — password change, admin revoke, MFA reset, or the grant+removed at [myaccount.microsoft.com](https://myaccount.microsoft.com/privacy#apps) — the+card shows *"Reconnect needed"* and the tools steer the agent to Settings. Tap Connect+again; the client ID is remembered.++## Manual end-to-end check++1. Connect, and confirm the card shows *Connected as …*.+2. `list_emails` → ids start with `ms:`.+3. `read_email` on one of those ids.+4. `send_email` → confirm the dialog appears **before** anything is sent.+5. `mark_email_read`, then check the message in Outlook.+6. `list_calendar_events` with `source="microsoft"`.+7. `check_availability` → busy blocks match the real calendar.+8. `list_tasks` → `create_task` → the task appears in Microsoft To Do → `complete_task`.+9. Revoke the grant at myaccount.microsoft.com, run any tool, and confirm it reports that a+ reconnect is needed rather than failing obscurely. Then reconnect.diff --git a/docs/notion-setup.md b/docs/notion-setup.mdnew file mode 100644index 0000000..ace32c7--- /dev/null+++ b/docs/notion-setup.md@@ -0,0 +1,67 @@+# Notion connector setup++The Notion connector uses an **internal integration token** rather than OAuth: you create an+integration inside your own workspace and paste its secret. There is no redirect URI, no+refresh cycle, and nothing to register with Notion for review — the same shape as the IMAP+app-password connector.++## 1. Create the integration++1. Go to [notion.so/my-integrations](https://www.notion.so/my-integrations) and click+ **New integration**.+2. Give it a name and pick the workspace it belongs to.+3. Under **Capabilities**, enable **Read content**, **Insert content** and **Update+ content**. (User information is not needed.)+4. Copy the **Internal Integration Secret** — it starts with `ntn_` (older ones start with+ `secret_`).++## 2. Connect++**Settings → Connectors → Notion**, paste the token, tap **Connect**. The token is validated+against Notion immediately, so a bad paste fails right there rather than on the first tool+call. The card then shows the integration/workspace name.++## 3. Share the pages — this is the step everyone misses++A fresh integration can see **nothing**. Notion requires each page to be shared with it+explicitly:++> open the page in Notion → **⋯** (top right) → **Connections** → **Connect to** → pick your+> integration++Sharing a page also shares everything nested under it, so sharing one top-level page per area+is usually enough.++If `notion_search` returns nothing, or `notion_read_page` reports "could not find page", this+is almost always why — not that the page is missing. Both tools say so in their output.++## What you get++| Tool | Notes |+|---|---|+| `notion_search` | Finds pages by title. Start here — the other tools need an id from it. |+| `notion_read_page` | Returns the page body as Markdown. |+| `notion_create_page` | Requires a `parent_page_id`: Notion gives integrations no workspace root to write into. |+| `notion_append_to_page` | Adds to the end of a page; never overwrites. |++Supported block types round-trip between Notion and Markdown: paragraphs, headings 1–3,+bulleted and numbered lists, to-dos (including checked state), quotes, code blocks and+dividers. Anything else is read as a `[unsupported block: …]` placeholder rather than+silently vanishing, and unrecognised Markdown is written as a plain paragraph so no content+is lost.++## Disconnecting++**Disconnect** on the card clears the stored token from the app. To revoke it properly, also+delete the integration at [notion.so/my-integrations](https://www.notion.so/my-integrations)+— Notion has no token-revocation endpoint for the app to call.++## Manual end-to-end check++1. Paste a deliberately wrong token → connecting fails and nothing is stored.+2. Paste the real token → the card names your workspace.+3. `notion_search` **before** sharing any page → empty, with the sharing guidance.+4. Share a page, then `notion_search` → the page appears with an id.+5. `notion_read_page` on that id → title, URL and Markdown body.+6. `notion_create_page` with that id as `parent_page_id` → the new page appears in Notion.+7. `notion_append_to_page` → the content is added at the end, with earlier content intact.