Initial import: Stitch 0.4.3 (versionCode 16)
The project's first commit, six days and 16 releases after it started. Everything up to this point existed only as files on one machine, with no history and no undo. Contents: single Gradle module, 62 Kotlin files (11,244 lines) and the Needle 2 JNI bridge, 70 tools, 87 passing unit tests, and the five documents in docs/ plus DEVELOPMENT_HISTORY.md and README.md. Not tracked: build outputs (build/, .cxx/, .gradle/), the release APKs in dist/ (~800 MB, rebuildable), local.properties, and .claude/settings.local.json — all machine-specific. The prebuilt libneedle.a files (38 MB) *are* tracked on purpose, so a checkout builds without depending on Hugging Face still serving them.
This commit is contained in:
commit
61409cb444
111 files changed
+15481
No files matched your search
@@ -0,0 +1,108 @@
|
||||
# Hotword & Assistant Surface — plan
|
||||
|
||||
> ⚠️ **HISTORICAL DOCUMENT.** This was the design plan for the wake phrase. **It shipped in Stitch 0.4.0**
|
||||
> and works as described here (teach-by-example, 5 recordings, MFCC + DTW, fully offline, bubble over any
|
||||
> app). The status line below is the original one and is no longer accurate. The one thing still untested
|
||||
> is detection with a real voice — the emulator has no microphone (see `DEVELOPMENT_HISTORY.md` §10 and
|
||||
> Stage A of `docs/UPGRADE_PLAN.md`).
|
||||
>
|
||||
> Status: planned, not built yet. Target: Stitch 0.4.0.
|
||||
> Goal: say your own wake phrase, Stitch pops up as a bubble and talks with you — and it can replace
|
||||
> Google Assistant when you hold the power button or swipe from the corner.
|
||||
|
||||
---
|
||||
|
||||
## 1. What you asked for
|
||||
|
||||
| Ask | How it will work |
|
||||
|---|---|
|
||||
| Call Stitch by a hotword | An always-ready listening service on the phone |
|
||||
| The hotword is **yours**, and changeable | You type the phrase, then say it a few times to teach it |
|
||||
| **Voice teaching** for accuracy | 5 recordings of your phrase; Stitch keeps the sound pattern, not the audio |
|
||||
| A **proper surface**, not the chat page | A floating bubble over whatever app you're in: what you said, what Stitch is doing, its answer, and a mic to keep talking |
|
||||
| Connect it **instead of Google Assistant** | Stitch registers as a digital assistant app, so you can pick it in Settings → Apps → Default apps → Digital assistant |
|
||||
| Proper conversation | Each reply is spoken and keeps the thread; follow-ups like "send it to him too" work |
|
||||
|
||||
---
|
||||
|
||||
## 2. How the hotword works
|
||||
|
||||
**Chosen approach: teach-by-example, fully on the phone.**
|
||||
|
||||
1. You type the phrase, e.g. "Hey Stitch", in Settings → Hotword.
|
||||
2. Stitch records you saying it **5 times**.
|
||||
3. Each recording is reduced to a compact sound fingerprint (MFCC features, ~13 numbers per 25 ms of audio). The audio itself is deleted; only the fingerprints are kept, in Stitch's private storage.
|
||||
4. A background service listens to short slices of the microphone and compares them with your fingerprints (DTW — the same technique older voice dialers used). A close enough match wakes Stitch.
|
||||
5. **Self-tuning:** the match threshold starts strict. You can adjust one slider ("wakes too easily ⟷ misses me") and re-record at any time.
|
||||
|
||||
**Why this and not the alternatives**
|
||||
|
||||
| Option | Verdict |
|
||||
|---|---|
|
||||
| **Teach-by-example (chosen)** | Any phrase, in your own voice and accent. Fully offline, no accounts, no keys. Fits "I say it a few times and it learns". Accuracy is good for one speaker, which is exactly this case |
|
||||
| Picovoice Porcupine | Most accurate and lightest on battery, but custom phrases need their website, an account and an access key in the app, and it isn't trained on your voice |
|
||||
| Continuous speech recognition | No training needed, but it runs Google's recognizer non-stop: heavy on battery, needs the network on many phones, and sends audio off the phone |
|
||||
|
||||
**Battery and privacy**
|
||||
- Listening runs in a foreground service with a permanent notification, as Android requires. Audio is processed in memory in small slices, never recorded to disk, never sent anywhere.
|
||||
- Default: listen **while the screen is on, or while charging**. Options: "always", "screen on or charging", "only when plugged in", "off".
|
||||
- Expected cost: roughly 2–4% of battery per hour of actual listening. The fingerprint check is cheap; the microphone is what costs.
|
||||
- A Quick Settings tile and the notification both have "pause listening".
|
||||
|
||||
---
|
||||
|
||||
## 3. The bubble
|
||||
|
||||
When the hotword fires (or you pick Stitch as your assistant and hold the power button):
|
||||
|
||||
```
|
||||
┌─────────────────────────────┐
|
||||
│ ● Listening… │ ← grows from a small circle, over any app
|
||||
├─────────────────────────────┤
|
||||
│ You: play believer on spotify│
|
||||
│ Stitch: ▶ Playing Believer │ ← action chips as steps run
|
||||
│ [mic] [✕ stop] │
|
||||
└─────────────────────────────┘
|
||||
```
|
||||
|
||||
- Built on the overlay Stitch already uses to show its steps in other apps, so no new permission beyond the one you granted.
|
||||
- Speaks replies aloud (can be turned off), listens again after a reply for a set number of seconds, so you can carry on without the hotword.
|
||||
- Tap the bubble to open the full chat with the same conversation.
|
||||
- It's the same agent underneath: same tools, same confirmations for calls and messages.
|
||||
|
||||
---
|
||||
|
||||
## 4. Replacing Google Assistant
|
||||
|
||||
- Stitch registers as a **voice interaction / assist** app. You then choose it in **Settings → Apps → Default apps → Digital assistant app**.
|
||||
- After that, the power-button hold or corner swipe opens Stitch's bubble instead of Google.
|
||||
- Google Assistant's own "Hey Google" keeps working; it's a separate system, and Stitch's hotword is independent of it.
|
||||
- Stitch will also offer a Quick Settings tile and the existing app icon, so nothing depends on this setting.
|
||||
|
||||
---
|
||||
|
||||
## 5. Work involved
|
||||
|
||||
| Piece | Detail |
|
||||
|---|---|
|
||||
| `voice/HotwordService.kt` | Foreground service, `AudioRecord` at 16 kHz, ring buffer, slice → fingerprint → match |
|
||||
| `voice/Fingerprint.kt` | MFCC + DTW; pure Kotlin, so it is unit-testable with recorded samples |
|
||||
| `voice/HotwordTraining.kt` + Settings page | Type the phrase, record 5 times, show a quality score per recording, re-record, delete |
|
||||
| `ui/AssistBubble.kt` | The bubble, built on the existing overlay: transcript, action chips, mic, stop |
|
||||
| `entry/AssistActivity.kt` + manifest | Assist/voice-interaction registration; a Quick Settings tile |
|
||||
| Settings | Hotword on/off, phrase, listening policy, sensitivity, speak replies, follow-up window |
|
||||
| Tests | Fingerprint matching against recorded samples (same phrase ≈ match, different phrase ≈ no match), policy logic |
|
||||
|
||||
**Risks and how they're handled**
|
||||
- *False wakes:* strict default threshold, a "pause listening" tile, and the bubble is silent until it hears a command.
|
||||
- *Missed wakes:* retrain with more samples; the slider helps; the phrase should be 2+ syllables (a warning appears for short phrases).
|
||||
- *OEM battery killers (Xiaomi, Samsung):* the setup page will link to the battery-optimisation exemption screen, as those systems stop background services aggressively.
|
||||
- *Phone calls / other mic users:* listening pauses whenever another app is using the microphone.
|
||||
|
||||
---
|
||||
|
||||
## 6. Not included in 0.4.0
|
||||
|
||||
- Speaker verification (only your voice can wake it) — possible later with the same fingerprints.
|
||||
- Wake phrase in multiple languages at once.
|
||||
- Listening while the phone is fully asleep on phones that stop background microphone use; where Android allows it, "always" mode covers it.
|
||||
+519
@@ -0,0 +1,519 @@
|
||||
# Project "Stitch": On-Device Android Agent (Needle + BYO AI)
|
||||
|
||||
> ⚠️ **HISTORICAL DOCUMENT — not the implementation contract.**
|
||||
> This is the original scope of work, written 19 Sep 2026 before any code existed. It is kept because it
|
||||
> records the reasoning behind the design, but the app diverged from it deliberately (see
|
||||
> `DEVELOPMENT_HISTORY.md` §4, "Plan vs. what was built"). Its "Phase 4" means Needle fine-tuning, and is
|
||||
> unrelated to the stages in `docs/UPGRADE_PLAN.md`.
|
||||
> **For what Stitch does today, read `README.md`. For where it is going, read `docs/UPGRADE_PLAN.md`.**
|
||||
>
|
||||
> Working name: **Stitch**. Needle does the on-device work, and your AI fills the gaps between steps. Rename anytime.
|
||||
> Status: **DRAFT v0.1** · 2026-09-19 · Scope of work and implementation plan
|
||||
|
||||
---
|
||||
|
||||
## 1. Summary
|
||||
|
||||
Stitch is an Android app that turns natural language (typed or spoken) into real actions on the phone.
|
||||
|
||||
- A **small on-device tool-calling model (Cactus Needle)** handles phone and device intents locally. Examples: turn on the flashlight, call Mom, set an alarm, read my notifications, reply on WhatsApp. It works offline, responds in milliseconds, and keeps data on the device.
|
||||
- A **user-connected AI (BYOK / agent)** handles anything Needle can't: writing content, reasoning, web search, and multi-step planning. Supported backends include OpenAI-compatible, Anthropic, Gemini, OpenRouter, local Ollama, Hermes Agent, and an OpenCode server.
|
||||
- The two talk through a strict JSON contract, the **Action Plan Protocol (APP)**. The cloud AI never touches the phone directly. It returns a structured plan, and the on-device **Executor** validates it, asks for confirmation when needed, and runs it with native Android APIs.
|
||||
- A **lightweight voice layer** handles input: speech-to-text on the device, with optional text-to-speech replies.
|
||||
|
||||
Example: *"Draft me a leave request and keep it in Gmail drafts."*
|
||||
1. Needle maps the request to `gmail.create_draft`, but it can't write the subject or body, so it calls the meta-tool `delegate_to_ai(task, target_tool="gmail.create_draft")`.
|
||||
2. The orchestrator sends the task, the target tool's schema, and the user profile (name, manager's email if known) to the connected AI.
|
||||
3. The AI returns an Action Plan: `[ask_user("Which dates?")] → gmail.create_draft{to, subject, body}`.
|
||||
4. The Executor asks the user for the dates, re-requests or fills the plan, then saves the draft through the Gmail API. If the Gmail API isn't connected, it falls back to opening Gmail compose with the fields prefilled and uses UI automation to save the draft.
|
||||
5. The user sees: "Saved 'Leave Request – 22–24 Sep' to Gmail Drafts" with a link to open it.
|
||||
|
||||
---
|
||||
|
||||
## 2. Research findings that shape this plan
|
||||
|
||||
| Item | Finding | Impact |
|
||||
|---|---|---|
|
||||
| **Needle 2** (Cactus Compute) | 45M params, one ~14 MB binary, ~28 MB RAM per session, Apache-2.0. It runs on Android arm64/armv7. It uses grammar-constrained JSON output: `{type: call\|respond, function_calls[], reasoning, confidence}`. It returns an **empty call list** when no tool fits instead of guessing. | The empty result and the confidence score give us a clear, reliable signal for handing a request to the cloud AI. |
|
||||
| **Needle 3** (current) | 8–29 MB. Adds structured extraction and embeddings. Needle 2 is still available (`generation=2`). | Build against Needle 3 and keep Needle 2 as a fallback. **Embeddings** let us retrieve the right tools on the device. |
|
||||
| Context window | **256-token sliding window** with pinned tool KV cache. | We **can't give Needle 80 tools at once.** We need top-k tool retrieval, and long prompts go straight to the cloud. |
|
||||
| Distribution | `libneedle.a` (C), a CLI binary with an `--serve` HTTP mode, WASM. `cactus-kotlin` SDK (`com.cactuscompute:cactus`) uses JNI on Android and includes Whisper STT. | Main path: a **JNI wrapper around libneedle** built with NDK/CMake. The Phase 0 spike checks whether cactus-kotlin already exposes Needle. |
|
||||
| Fine-tuning | `pip install "cactus-needle[train]"` → `needle finetune data.jsonl` → `needle build --lora … --out tuned.cact` | Fine-tune on **our exact tool catalog** with synthetic data generated by a large model (Phase 4). |
|
||||
| Hermes Agent (Nous) | Open-source (MIT), self-hosted, exposes an **OpenAI-compatible API server**. | Supported with no extra work through the OpenAI-compatible provider. A dedicated connector adds session and memory features later. |
|
||||
|
||||
Sources: huggingface.co/Cactus-Compute/needle2 · github.com/cactus-compute/needle · github.com/cactus-compute/cactus-kotlin · hermes-agent.nousresearch.com
|
||||
|
||||
---
|
||||
|
||||
## 3. Scope of Work (SOW)
|
||||
|
||||
### 3.1 Objectives
|
||||
1. Run common phone actions **on the device, offline, with p50 latency under 1 s** (from text to action started).
|
||||
2. Let users connect **any AI they choose** (BYOK or a self-hosted agent) in under 2 minutes.
|
||||
3. Handle **multi-step and generative tasks** through the Action Plan Protocol, run safely on the device.
|
||||
4. Accept **voice input** with on-device STT and no extra cloud dependency.
|
||||
5. **Safe by default:** every sensitive action (send, call, delete, pay) needs explicit confirmation, and everything goes to an audit log.
|
||||
|
||||
### 3.2 In scope
|
||||
| # | Workstream | Deliverables |
|
||||
|---|---|---|
|
||||
| W1 | Needle runtime | NDK/JNI wrapper, model loading from assets, tool-set caching, embeddings-based tool retrieval, benchmark harness |
|
||||
| W2 | Orchestrator | Router (local vs. cloud), Action Plan Protocol, plan validator, executor with variable binding, confirmation policy, retries |
|
||||
| W3 | AI providers | OpenAI-compatible (OpenAI, OpenRouter, Groq, DeepSeek, Together, Ollama/LM Studio on LAN, **Hermes**), Anthropic Messages, Google Gemini, OpenCode server (Phase 4); streaming; structured output; web search passthrough |
|
||||
| W4 | Tool catalog | ~50 tools across Device, Comms, Productivity, Info, UI-Automation, and Meta (see §6) |
|
||||
| W5 | Voice | Push-to-talk STT (Android on-device recognizer + sherpa-onnx offline fallback), VAD, TTS replies |
|
||||
| W6 | App UX | Onboarding, chat with action cards, permission center, provider setup, history and audit log, settings, Quick Settings tile, home widget, assistant-role entry point |
|
||||
| W7 | Security and privacy | Keystore/Tink-encrypted secrets, risk-based confirmation, prompt-injection guards, data-egress preview, local-only mode |
|
||||
| W8 | Quality | Unit, integration, and instrumented tests, a Needle accuracy eval set, CI, crash reporting (opt-in) |
|
||||
| W9 | Release | Two build flavors (`play` and `full`), Play policy declarations, privacy policy, signed releases |
|
||||
|
||||
### 3.3 Out of scope (v1)
|
||||
- iOS, wear OS, and desktop builds
|
||||
- Always-on wake word (planned for v1.x; see §11)
|
||||
- Payments and banking actions
|
||||
- Our own hosted backend or cloud (the app is **serverless**; users bring their own AI)
|
||||
- Automating third-party apps beyond the listed targets (Gmail, WhatsApp, Settings)
|
||||
|
||||
### 3.4 Assumptions
|
||||
- Minimum SDK **28 (Android 9)** and target/compile SDK **36**. (Needle runs on API 24+, but 28+ keeps permission handling simpler.)
|
||||
- A single user per device, with no accounts on our side.
|
||||
- The user supplies their own API keys and pays their provider directly.
|
||||
|
||||
### 3.5 Acceptance criteria (v1.0)
|
||||
- ≥ **95%** correct tool plus arguments on our 300-prompt local eval set (after fine-tuning; baseline measured in Phase 0).
|
||||
- Local action latency **p50 < 800 ms, p95 < 1.5 s** on a mid-range device (e.g., Pixel 6a or Galaxy A54).
|
||||
- Cloud-delegated plans validate against the schema **≥ 98%** of the time (with 1 automatic repair retry).
|
||||
- **No** HIGH-risk action runs without confirmation (enforced by tests).
|
||||
- App cold start < 1.5 s. Needle RAM < 60 MB. APK < 45 MB (without optional STT model).
|
||||
- The leave-request, WhatsApp-message, call, flashlight, and notification-summary scenarios pass end to end on 3 real devices.
|
||||
|
||||
---
|
||||
|
||||
## 4. Architecture
|
||||
|
||||
```
|
||||
┌──────────────────────────────── Android App ─────────────────────────────────┐
|
||||
│ UI (Compose) ── Chat · Voice button · Action cards · Confirm sheets │
|
||||
│ │ │
|
||||
│ Input: Text | Voice(STT) | QS Tile | Widget | Assistant role | Share-to │
|
||||
│ ▼ │
|
||||
│ ┌──────────────────────── ORCHESTRATOR ─────────────────────────┐ │
|
||||
│ │ 1. Pre-router (rules: length, "search", attachments) │ │
|
||||
│ │ 2. ToolRetriever (Needle embeddings → top-k tools + meta tools)│ │
|
||||
│ │ 3. NeedleEngine.infer(prompt, tools, facts) │ │
|
||||
│ │ ├─ call(local tool, conf ≥ τ) → Executor │ │
|
||||
│ │ ├─ call(delegate_to_ai / web_search) → CloudPlanner │ │
|
||||
│ │ └─ empty / low conf → CloudPlanner │ │
|
||||
│ │ 4. CloudPlanner → AiProvider → ActionPlan JSON │ │
|
||||
│ │ 5. PlanValidator (schema, tool exists, args, risk) │ │
|
||||
│ │ 6. Executor (steps, {{vars}}, ask_user, confirm, retry) │ │
|
||||
│ │ 7. Result → (optional) summarizer → UI/TTS │ │
|
||||
│ └────────────────────────────────────────────────────────────────┘ │
|
||||
│ ▼ │
|
||||
│ TOOL REGISTRY ── Device │ Comms │ Productivity │ Info │ UI-Automation │ Meta │
|
||||
│ ▼ │
|
||||
│ Android APIs: CameraManager, Telecom, SmsManager, ContactsContract, │
|
||||
│ CalendarContract, AlarmClock, NotificationListener, AccessibilityService, │
|
||||
│ MediaSession, Location, Gmail REST, Intents … │
|
||||
│ │
|
||||
│ Data: Room (history, audit, memory) · DataStore (settings) · Tink (secrets) │
|
||||
└────────────────────────────────────────────────────────────────────────────────┘
|
||||
│ HTTPS (only the user's chosen AI; nothing else)
|
||||
▼
|
||||
OpenAI-compat / Anthropic / Gemini / OpenRouter / Ollama / Hermes / OpenCode
|
||||
```
|
||||
|
||||
### 4.1 Routing rules
|
||||
| Condition | Route |
|
||||
|---|---|
|
||||
| Prompt > ~150 tokens, has an attachment, or contains explicit "search/look up/latest" | Cloud directly |
|
||||
| Needle returns a local tool with `confidence ≥ 0.75` and all required args | Execute locally |
|
||||
| Needle returns `delegate_to_ai` or `web_search` | Cloud, with the chosen target tool's schema attached |
|
||||
| Needle returns empty, `respond`, or `confidence < 0.75` | Cloud (full catalog summary) |
|
||||
| No AI connected (local-only mode) | Needle only. Otherwise say "This needs an AI connection" |
|
||||
|
||||
### 4.2 Why the cloud AI gets our tool catalog
|
||||
The cloud AI plans with the **same tool registry** (exported as OpenAI/Anthropic/Gemini tool schemas) and returns an **Action Plan**, not free text. Needle stays the fast local path. The Executor remains the **only** component that touches the device.
|
||||
|
||||
---
|
||||
|
||||
## 5. Action Plan Protocol (APP) v1
|
||||
|
||||
The system prompt sent to the cloud AI enforces this contract. It uses native structured output where the provider supports it (OpenAI `response_format: json_schema`, Anthropic tool-forced output, Gemini `responseSchema`), with JSON-schema validation and one repair retry.
|
||||
|
||||
```json
|
||||
{
|
||||
"app_version": "1",
|
||||
"intent": "Create a leave-request email draft",
|
||||
"reply": "Saved your leave request to Gmail Drafts.",
|
||||
"steps": [
|
||||
{ "id": "s1", "type": "ask_user", "question": "Which dates do you need off?",
|
||||
"save_as": "dates", "input": "text" },
|
||||
{ "id": "s2", "type": "tool", "tool": "contacts.search",
|
||||
"args": { "query": "manager" }, "save_as": "mgr", "optional": true },
|
||||
{ "id": "s3", "type": "tool", "tool": "gmail.create_draft",
|
||||
"args": { "to": "{{mgr.email}}", "subject": "Leave Request – {{dates}}",
|
||||
"body": "Dear {{mgr.name|Manager}},\n..." } },
|
||||
{ "id": "s4", "type": "respond", "text": "Draft saved: {{s3.result.subject}}" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Step types:** `tool`, `ask_user`, `confirm`, `respond`, `ai` (a sub-query back to the AI with prior results, e.g., "summarize these notifications"), `condition` (`if: "{{s1.result.count}} > 0"`).
|
||||
|
||||
**Executor rules**
|
||||
- Max 12 steps and max 2 nested `ai` calls per request.
|
||||
- `{{var.path|default}}` binding, resolved at step time.
|
||||
- Every `tool` step is validated against the registry schema before it runs.
|
||||
- Risk is taken from the **tool definition, never from the AI**. HIGH-risk steps always show a confirm sheet with the final resolved args.
|
||||
- Tool results sent back to the AI are **truncated and redacted** (for example, phone numbers masked unless needed).
|
||||
- Content from notifications, web pages, or screen text is wrapped as `untrusted_content` in prompts. A plan produced after reading untrusted content gets **confirmation forced on every non-read step**.
|
||||
|
||||
---
|
||||
|
||||
## 6. Tool Catalog (v1)
|
||||
|
||||
Risk levels: **L** = runs silently · **M** = runs with a snackbar and Undo · **H** = explicit confirmation required.
|
||||
|
||||
| Group | Tool | Android mechanism | Permission / special access | Risk |
|
||||
|---|---|---|---|---|
|
||||
| Device | `device.flashlight(on)` | `CameraManager.setTorchMode` | none | L |
|
||||
| | `device.volume(stream, level)` | `AudioManager` | none | L |
|
||||
| | `device.ringer_mode(mode)` / `dnd(on)` | `AudioManager`, `NotificationManager` | Notification-policy access | M |
|
||||
| | `device.brightness(level)` | `Settings.System` | `WRITE_SETTINGS` (special) | L |
|
||||
| | `device.open_settings_panel(wifi\|bt\|internet\|nfc)` | `Settings.Panel` (direct Wi-Fi/BT toggles are blocked on Android 10+) | none | L |
|
||||
| | `device.battery_status()` / `device.info()` | `BatteryManager` | none | L |
|
||||
| | `device.screenshot()` | AccessibilityService `takeScreenshot` (API 30+) | Accessibility | M |
|
||||
| | `device.rotate_lock(on)` | `Settings.System` | `WRITE_SETTINGS` | L |
|
||||
| Apps | `apps.open(name)` / `apps.list()` | `PackageManager` + launcher `<queries>` | none | L |
|
||||
| Media | `media.control(play\|pause\|next\|prev)` | `MediaSessionManager` | Notification listener | L |
|
||||
| | `media.play_search(query, app)` | `MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH` | none | L |
|
||||
| Clock | `alarm.set(time, label)` / `timer.set(sec)` / `alarm.list()` | `AlarmClock` intents | `SET_ALARM` | M |
|
||||
| Calendar | `calendar.list(range)` / `calendar.create(event)` | `CalendarContract` | `READ/WRITE_CALENDAR` | L / M |
|
||||
| Contacts | `contacts.search(query)` / `contacts.get(id)` | `ContactsContract` | `READ_CONTACTS` | L |
|
||||
| Phone | `phone.call(number\|contact)` | `ACTION_CALL` (full) / `ACTION_DIAL` (play) | `CALL_PHONE` | H |
|
||||
| | `phone.recent_calls()` | `CallLog` | `READ_CALL_LOG` (**full flavor only**) | L |
|
||||
| SMS | `sms.send(to, text)` | `SmsManager` (full) / `ACTION_SENDTO` (play) | `SEND_SMS` (**full flavor only**) | H |
|
||||
| | `sms.read_recent(from?)` | `Telephony.Sms` | `READ_SMS` (**full only**) | L |
|
||||
| WhatsApp | `whatsapp.open_chat(contact, text?)` | `https://wa.me/<num>?text=` or `ACTION_SEND` + `setPackage(com.whatsapp)` | none | M |
|
||||
| | `whatsapp.send(contact, text)` | open chat + AccessibilityService taps Send | Accessibility | H |
|
||||
| | `whatsapp.reply(notification_id, text)` | NotificationListener `RemoteInput` reply (reliable, no UI scraping) | Notification listener | H |
|
||||
| Email | `gmail.create_draft(to, cc?, subject, body)` | **Gmail REST API** `users.drafts.create` (OAuth, scope `gmail.compose`) | Google authorization | M |
|
||||
| | `gmail.send(...)` | Gmail API `messages.send` | Google authorization | H |
|
||||
| | `gmail.search(query)` / `gmail.read(id)` | Gmail API (`gmail.readonly`) | Google authorization | L |
|
||||
| | `email.compose(to, subject, body)` | `ACTION_SENDTO mailto:` (any mail app; fallback) | none | M |
|
||||
| Notifications | `notifications.list(app?, since?)` / `notifications.summarize()` | `NotificationListenerService` + Room cache | Notification listener | L |
|
||||
| | `notifications.dismiss(id)` | same | same | M |
|
||||
| Location / Nav | `location.current()` | Fused Location Provider | `ACCESS_COARSE/FINE_LOCATION` | L |
|
||||
| | `maps.navigate(dest, mode)` | `google.navigation:` / `geo:` intents | none | L |
|
||||
| Camera | `camera.capture_photo()` / `camera.record_video()` | `MediaStore` intents | none | L |
|
||||
| Files / Clipboard | `clipboard.set(text)` / `share.text(text, app?)` | `ClipboardManager`, `ACTION_SEND` | none | L |
|
||||
| Notes / Reminders | `notes.create(text)` / `reminder.create(text, time)` | Local Room + `AlarmManager` exact alarm | `SCHEDULE_EXACT_ALARM` / `USE_EXACT_ALARM` | L |
|
||||
| UI automation | `ui.read_screen()` / `ui.tap(text\|id)` / `ui.type(text)` / `ui.back()` / `ui.scroll(dir)` | `AccessibilityService` node tree | Accessibility (disclosure required) | M–H |
|
||||
| Info | `web_search(query)` | Via cloud provider's native search (Anthropic `web_search`, OpenAI web search, Gemini grounding) or a BYO **Brave/Tavily** key | network | L |
|
||||
| | `web.fetch(url)` | OkHttp + Readability-style extraction | network | L |
|
||||
| Meta | `delegate_to_ai(task, target_tool?)` | Sends to CloudPlanner | none | – |
|
||||
| | `ask_user(question)` / `respond(text)` | UI | none | – |
|
||||
| | `memory.remember(fact)` / `memory.recall(query)` | Room + Needle embeddings | none | L |
|
||||
|
||||
**Tool retrieval for Needle's 256-token window:** every tool description is embedded once with Needle embeddings. For each query we take the **top-6 tools plus 3 meta-tools** (`delegate_to_ai`, `web_search`, `ask_user`) and cache the compiled tool KV per tool-set signature (LRU of 16). Phase 0 checks the real tool budget.
|
||||
|
||||
---
|
||||
|
||||
## 7. Technology Stack
|
||||
|
||||
| Layer | Choice | Notes |
|
||||
|---|---|---|
|
||||
| Language | **Kotlin 2.x** (K2), Java 17 toolchain | |
|
||||
| UI | **Jetpack Compose** + Material 3 (Compose BOM), Navigation-Compose (type-safe routes) | Adaptive layouts |
|
||||
| Architecture | MVVM + UDF, Clean-ish layers (ui → domain → data), multi-module Gradle | |
|
||||
| DI | **Hilt** (+ KSP) | |
|
||||
| Async | Coroutines + Flow | |
|
||||
| Serialization | **kotlinx.serialization** (JSON) | Tool schemas, APP plans |
|
||||
| JSON Schema validation | `com.networknt:json-schema-validator` or a small hand-rolled validator in `:core:model` | Plan validation |
|
||||
| Networking | **OkHttp 4/5 + okhttp-sse** (streaming), kotlinx.serialization converters | No Retrofit needed |
|
||||
| Local DB | **Room** (KSP) | history, audit, notifications cache, memory, embeddings |
|
||||
| Settings | **DataStore (Proto or Preferences)** | |
|
||||
| Secrets | **Android Keystore + Google Tink** (AEAD) wrapping a DataStore | EncryptedSharedPreferences is deprecated |
|
||||
| Background | **WorkManager** (model downloads, notification indexing), foreground service type `microphone` while listening | |
|
||||
| On-device model | **Cactus Needle 3** (Needle 2 fallback) via **NDK + CMake + JNI** around `libneedle`. Alternative: `com.cactuscompute:cactus` SDK | `.cact` model bundled in `assets/` (~14–29 MB) |
|
||||
| STT (primary) | **Android `SpeechRecognizer`**. `createOnDeviceSpeechRecognizer` (API 31+) = offline, 0 MB | Default |
|
||||
| STT (offline fallback) | **sherpa-onnx** (Apache-2.0) streaming Zipformer model (~20–70 MB, downloaded on demand) + **Silero VAD** | Also covers devices without an on-device recognizer. Alternative: Cactus Whisper-tiny |
|
||||
| TTS | Android **`TextToSpeech`** | Optional voice replies |
|
||||
| Google auth | **Credential Manager** (Sign in with Google) + **`Identity.getAuthorizationClient`** for Gmail scopes | Gmail REST calls go through OkHttp |
|
||||
| AI providers | Hand-written thin clients: OpenAI Chat Completions/Responses-compatible, Anthropic Messages, Gemini `generateContent` | Kept thin; no heavy SDKs |
|
||||
| Agent connectors | Hermes Agent (OpenAI-compatible API server), OpenCode (`opencode serve` HTTP API), **MCP client** (Streamable HTTP) in v1.x | |
|
||||
| Images | Coil 3 | Avatars and app icons |
|
||||
| Logging | Timber | |
|
||||
| Crash reporting | Opt-in only: Sentry (self-hostable) or none | Privacy first |
|
||||
| Testing | JUnit5, MockK, Turbine, kotlinx-coroutines-test, Robolectric, Compose UI test, Espresso/UIAutomator, **MockWebServer** | |
|
||||
| Quality | ktlint/Spotless, Detekt, Android Lint, R8 full mode | |
|
||||
| Build | Gradle KTS, **version catalog** (`libs.versions.toml`), convention plugins in `build-logic/` | |
|
||||
| CI | GitHub Actions: lint → unit → build both flavors → (nightly) instrumented on emulator | |
|
||||
| Model tooling (dev only) | Python 3.11, `cactus-needle[train]` for fine-tuning and evals | `tools/needle/` |
|
||||
|
||||
Exact library versions get pinned in `gradle/libs.versions.toml` at the latest stable release when the project starts.
|
||||
|
||||
### 7.1 Build flavors (needed because of Play Store policy)
|
||||
| Flavor | Distribution | Differences |
|
||||
|---|---|---|
|
||||
| `play` | Google Play | No `SEND_SMS`, `READ_SMS`, or `READ_CALL_LOG` (Play restricts these to default SMS/dialer apps). Sends go through intents where the user taps Send. Accessibility automation stays behind a prominent disclosure and the Play Accessibility declaration. |
|
||||
| `full` | GitHub Releases / F-Droid-style sideload | All permissions. Direct SMS, direct calls, and full UI automation. |
|
||||
|
||||
---
|
||||
|
||||
## 8. Security, Privacy & Safety
|
||||
1. **Secrets:** API keys and OAuth tokens are encrypted with Tink AEAD using a Keystore-backed key (StrongBox when available). They never appear in logs and are excluded from backups (`dataExtractionRules`).
|
||||
2. **Egress control:** the app contacts only (a) the configured AI endpoint, (b) Google APIs if Gmail is connected, and (c) the search API if configured. A "What will be sent" preview can be turned on in Settings.
|
||||
3. **Local-only mode:** Needle only, with the network turned off for AI.
|
||||
4. **Confirmation policy:** set per tool (L/M/H), with user overrides only toward *more* strict.
|
||||
5. **Prompt-injection defenses:** untrusted-content tagging, forced confirmation after reading untrusted input, and no chaining of `ai` steps that feed untrusted content into send-type tools without confirmation.
|
||||
6. **Audit log:** every executed step with its timestamp, tool, redacted args, and result. Exportable and clearable.
|
||||
7. **Accessibility service:** limited to an allow-list of packages (Gmail, WhatsApp, Settings) and active only during a running plan. `canRetrieveWindowContent` is used only while a plan is running.
|
||||
8. **Permissions** are requested just in time, with a rationale screen, from the Permission Center.
|
||||
|
||||
---
|
||||
|
||||
## 9. Project structure: every file to create
|
||||
|
||||
```
|
||||
ai-support/
|
||||
├── README.md # Overview, build, flavors, setup
|
||||
├── LICENSE # Project license (TBD – Apache-2.0 suggested)
|
||||
├── .gitignore
|
||||
├── .editorconfig
|
||||
├── settings.gradle.kts # Module includes, repositories
|
||||
├── build.gradle.kts # Root: plugin aliases only
|
||||
├── gradle.properties # JVM args, AndroidX, config cache
|
||||
├── gradle/
|
||||
│ ├── libs.versions.toml # Version catalog (all deps pinned)
|
||||
│ └── wrapper/gradle-wrapper.properties
|
||||
├── gradlew / gradlew.bat
|
||||
├── build-logic/ # Convention plugins
|
||||
│ ├── settings.gradle.kts
|
||||
│ └── convention/
|
||||
│ ├── build.gradle.kts
|
||||
│ └── src/main/kotlin/
|
||||
│ ├── AndroidApplicationConventionPlugin.kt
|
||||
│ ├── AndroidLibraryConventionPlugin.kt
|
||||
│ ├── AndroidComposeConventionPlugin.kt
|
||||
│ ├── AndroidHiltConventionPlugin.kt
|
||||
│ ├── AndroidRoomConventionPlugin.kt
|
||||
│ ├── KotlinSerializationConventionPlugin.kt
|
||||
│ └── FlavorsConvention.kt # play / full flavors
|
||||
├── config/
|
||||
│ ├── detekt/detekt.yml
|
||||
│ └── lint/lint.xml
|
||||
├── .github/workflows/
|
||||
│ ├── ci.yml # lint, unit, assemble both flavors
|
||||
│ └── nightly-instrumented.yml
|
||||
├── docs/
|
||||
│ ├── PLAN.md # ← this document
|
||||
│ ├── ARCHITECTURE.md
|
||||
│ ├── ACTION_PLAN_PROTOCOL.md # APP v1 spec + JSON schema
|
||||
│ ├── TOOL_CATALOG.md # Generated from registry
|
||||
│ ├── PRIVACY_POLICY.md
|
||||
│ ├── PLAY_POLICY_DECLARATIONS.md # Accessibility / permissions justification
|
||||
│ └── adr/0001-needle-jni.md, 0002-app-protocol.md, 0003-flavors.md
|
||||
│
|
||||
├── app/
|
||||
│ ├── build.gradle.kts
|
||||
│ ├── proguard-rules.pro
|
||||
│ └── src/
|
||||
│ ├── main/
|
||||
│ │ ├── AndroidManifest.xml # permissions, services, queries, QS tile, assistant
|
||||
│ │ ├── kotlin/app/stitch/
|
||||
│ │ │ ├── StitchApplication.kt # @HiltAndroidApp, Timber, WorkManager config
|
||||
│ │ │ ├── MainActivity.kt # Compose host, intent handling (share/assist)
|
||||
│ │ │ ├── navigation/StitchNavHost.kt
|
||||
│ │ │ ├── navigation/Routes.kt
|
||||
│ │ │ ├── entry/AssistActivity.kt # ACTION_ASSIST / long-press entry
|
||||
│ │ │ ├── entry/StitchTileService.kt # Quick Settings tile → voice
|
||||
│ │ │ ├── entry/StitchWidget.kt # Glance home widget
|
||||
│ │ │ ├── entry/ShareReceiverActivity.kt # "Share to Stitch"
|
||||
│ │ │ └── di/AppModule.kt
|
||||
│ │ └── res/
|
||||
│ │ ├── values/strings.xml, themes.xml, colors.xml
|
||||
│ │ ├── xml/accessibility_service_config.xml
|
||||
│ │ ├── xml/data_extraction_rules.xml, backup_rules.xml
|
||||
│ │ ├── xml/stitch_widget_info.xml
|
||||
│ │ └── mipmap-*/ic_launcher*
|
||||
│ ├── play/AndroidManifest.xml # removes SMS/CallLog perms (tools:node="remove")
|
||||
│ ├── full/AndroidManifest.xml # adds SEND_SMS, READ_SMS, READ_CALL_LOG
|
||||
│ └── androidTest/…/EndToEndScenariosTest.kt
|
||||
│
|
||||
├── core/
|
||||
│ ├── common/ src/main/kotlin/app/stitch/core/common/
|
||||
│ │ ├── Result.kt, DispatcherProvider.kt, Clock.kt, Redactor.kt
|
||||
│ ├── model/ src/main/kotlin/app/stitch/core/model/
|
||||
│ │ ├── ToolSpec.kt # name, description, params (JSON schema), risk, permissions
|
||||
│ │ ├── ToolCall.kt, ToolResult.kt, RiskLevel.kt
|
||||
│ │ ├── ActionPlan.kt # APP v1 data classes (@Serializable)
|
||||
│ │ ├── PlanStep.kt # sealed: Tool, AskUser, Confirm, Respond, Ai, Condition
|
||||
│ │ ├── ChatMessage.kt, Conversation.kt
|
||||
│ │ └── ProviderConfig.kt
|
||||
│ │ └── src/main/resources/schema/action_plan_v1.schema.json
|
||||
│ ├── data/ src/main/kotlin/app/stitch/core/data/
|
||||
│ │ ├── db/StitchDatabase.kt
|
||||
│ │ ├── db/dao/{ConversationDao, MessageDao, AuditDao, NotificationDao, MemoryDao}.kt
|
||||
│ │ ├── db/entity/{ConversationEntity, MessageEntity, AuditEntity, NotificationEntity, MemoryEntity}.kt
|
||||
│ │ ├── settings/SettingsRepository.kt # DataStore
|
||||
│ │ ├── repo/{ConversationRepository, AuditRepository, MemoryRepository}.kt
|
||||
│ │ └── di/DataModule.kt
|
||||
│ ├── security/ src/main/kotlin/app/stitch/core/security/
|
||||
│ │ ├── SecretStore.kt # Tink AEAD + Keystore
|
||||
│ │ ├── ConfirmationPolicy.kt
|
||||
│ │ └── UntrustedContent.kt # tagging + injection guards
|
||||
│ └── ui/ src/main/kotlin/app/stitch/core/ui/
|
||||
│ ├── theme/{Theme, Color, Type, Shape}.kt
|
||||
│ └── components/{ActionCard, ConfirmSheet, MicButton, ProviderChip, PermissionRow}.kt
|
||||
│
|
||||
├── engine/
|
||||
│ ├── needle/
|
||||
│ │ ├── build.gradle.kts # externalNativeBuild cmake, abiFilters arm64-v8a, armeabi-v7a, x86_64
|
||||
│ │ ├── src/main/cpp/
|
||||
│ │ │ ├── CMakeLists.txt
|
||||
│ │ │ ├── needle_jni.cpp # JNI: load, setTools, infer, embed, release
|
||||
│ │ │ └── third_party/needle/ # libneedle.a per ABI + needle.h (vendored release)
|
||||
│ │ ├── src/main/assets/models/needle.cact
|
||||
│ │ └── src/main/kotlin/app/stitch/engine/needle/
|
||||
│ │ ├── NeedleNative.kt # external fun declarations
|
||||
│ │ ├── NeedleEngine.kt # suspend infer(), single-thread dispatcher, lifecycle
|
||||
│ │ ├── NeedleResult.kt # type, calls, reasoning, confidence, metrics
|
||||
│ │ ├── ToolSetCache.kt # LRU of compiled tool sets
|
||||
│ │ ├── ToolRetriever.kt # embeddings top-k
|
||||
│ │ ├── SystemFacts.kt # date, locale, battery, foreground app…
|
||||
│ │ └── di/NeedleModule.kt
|
||||
│ └── orchestrator/ src/main/kotlin/app/stitch/engine/orchestrator/
|
||||
│ ├── Orchestrator.kt # entry: handle(userInput): Flow<OrchestratorEvent>
|
||||
│ ├── PreRouter.kt
|
||||
│ ├── RouteDecision.kt
|
||||
│ ├── CloudPlanner.kt # builds prompt, calls provider, parses APP
|
||||
│ ├── PlannerPrompts.kt # system prompt, APP contract, few-shots
|
||||
│ ├── PlanValidator.kt
|
||||
│ ├── PlanRepairer.kt # one retry with validator errors
|
||||
│ ├── Executor.kt # step loop, var binding, ask/confirm suspension
|
||||
│ ├── VariableResolver.kt # {{a.b|default}}
|
||||
│ ├── OrchestratorEvent.kt # Thinking, NeedsInput, NeedsConfirm, StepDone, Reply, Error
|
||||
│ └── di/OrchestratorModule.kt
|
||||
│
|
||||
├── ai/
|
||||
│ └── providers/ src/main/kotlin/app/stitch/ai/providers/
|
||||
│ ├── AiProvider.kt # interface: chat(), planStructured(), supportsSearch
|
||||
│ ├── ProviderRegistry.kt
|
||||
│ ├── ToolSchemaExporter.kt # ToolSpec → OpenAI / Anthropic / Gemini formats
|
||||
│ ├── openai/OpenAiCompatibleProvider.kt # OpenAI, OpenRouter, Groq, Ollama, LM Studio, Hermes
|
||||
│ ├── anthropic/AnthropicProvider.kt
|
||||
│ ├── gemini/GeminiProvider.kt
|
||||
│ ├── opencode/OpenCodeProvider.kt # Phase 4
|
||||
│ ├── hermes/HermesProvider.kt # Phase 4 (extends OpenAI-compat + session)
|
||||
│ ├── mcp/McpClient.kt # v1.x
|
||||
│ ├── search/{SearchProvider, BraveSearch, TavilySearch}.kt
|
||||
│ ├── http/{HttpClientFactory, SseParser}.kt
|
||||
│ └── di/ProvidersModule.kt
|
||||
│
|
||||
├── tools/
|
||||
│ ├── api/ src/main/kotlin/app/stitch/tools/api/
|
||||
│ │ ├── DeviceTool.kt # interface { spec; suspend execute(args, ctx) }
|
||||
│ │ ├── ToolRegistry.kt # Hilt multibinding Set<DeviceTool>
|
||||
│ │ ├── ToolContext.kt # permissions checker, activity launcher, confirmer
|
||||
│ │ ├── PermissionGate.kt
|
||||
│ │ └── ArgParser.kt
|
||||
│ ├── device/ …/tools/device/{Flashlight, Volume, RingerDnd, Brightness, SettingsPanel, Battery, DeviceInfo, AppsOpen, AppsList, MediaControl, MediaPlaySearch}Tool.kt
|
||||
│ ├── comms/ …/tools/comms/{PhoneCall, RecentCalls, SmsSend, SmsRead, ContactsSearch, ContactsGet, WhatsAppOpenChat, WhatsAppSend, WhatsAppReply, EmailCompose}Tool.kt
|
||||
│ │ …/tools/comms/gmail/{GmailAuth, GmailApi, GmailCreateDraftTool, GmailSendTool, GmailSearchTool, GmailReadTool}.kt
|
||||
│ ├── productivity/ …/tools/productivity/{AlarmSet, TimerSet, AlarmList, CalendarList, CalendarCreate, NoteCreate, ReminderCreate, Clipboard, ShareText, CameraCapture, Navigate, LocationCurrent}Tool.kt
|
||||
│ ├── notifications/ …/tools/notifications/
|
||||
│ │ ├── StitchNotificationListener.kt # NotificationListenerService
|
||||
│ │ ├── NotificationIndexer.kt
|
||||
│ │ └── {NotificationsList, NotificationsSummarize, NotificationsDismiss}Tool.kt
|
||||
│ ├── automation/ …/tools/automation/
|
||||
│ │ ├── StitchAccessibilityService.kt
|
||||
│ │ ├── ScreenReader.kt # node tree → compact text for AI
|
||||
│ │ ├── UiActions.kt # tap/type/scroll/back with waits
|
||||
│ │ ├── recipes/GmailSaveDraftRecipe.kt
|
||||
│ │ ├── recipes/WhatsAppSendRecipe.kt
|
||||
│ │ └── {UiReadScreen, UiTap, UiType, UiBack, UiScroll, Screenshot}Tool.kt
|
||||
│ ├── web/ …/tools/web/{WebSearchTool, WebFetchTool}.kt
|
||||
│ └── meta/ …/tools/meta/{DelegateToAiTool, AskUserTool, RespondTool, MemoryRememberTool, MemoryRecallTool}.kt
|
||||
│
|
||||
├── voice/ src/main/kotlin/app/stitch/voice/
|
||||
│ ├── SpeechInput.kt # interface: Flow<SpeechEvent> (partial, final, level, error)
|
||||
│ ├── AndroidSpeechInput.kt # SpeechRecognizer / on-device
|
||||
│ ├── SherpaSpeechInput.kt # sherpa-onnx streaming + VAD
|
||||
│ ├── SpeechModelDownloader.kt # WorkManager, checksum
|
||||
│ ├── VoiceSessionService.kt # FGS type=microphone
|
||||
│ ├── SpeechOutput.kt # TextToSpeech wrapper
|
||||
│ └── di/VoiceModule.kt
|
||||
│
|
||||
├── feature/
|
||||
│ ├── chat/ …/feature/chat/{ChatScreen, ChatViewModel, MessageList, InputBar, ActionTimeline}.kt
|
||||
│ ├── onboarding/ …/feature/onboarding/{OnboardingScreen, WelcomeStep, ConnectAiStep, PermissionsStep, VoiceStep}.kt
|
||||
│ ├── providers/ …/feature/providers/{ProvidersScreen, ProviderEditScreen, ProviderTestUseCase, ProvidersViewModel}.kt
|
||||
│ ├── permissions/ …/feature/permissions/{PermissionCenterScreen, PermissionCenterViewModel, SpecialAccessIntents}.kt
|
||||
│ ├── history/ …/feature/history/{HistoryScreen, AuditLogScreen, HistoryViewModel}.kt
|
||||
│ └── settings/ …/feature/settings/{SettingsScreen, SafetySettings, VoiceSettings, PrivacySettings, SettingsViewModel}.kt
|
||||
│
|
||||
└── tools-dev/ (not shipped – dev tooling)
|
||||
└── needle/
|
||||
├── requirements.txt # cactus-needle[train]
|
||||
├── export_tools.py # reads generated tools.json from the app build
|
||||
├── gen_synthetic_data.py # uses a big LLM to create prompt→call pairs
|
||||
├── eval_set.jsonl # 300 hand-checked prompts
|
||||
├── run_eval.py # accuracy / latency report
|
||||
└── finetune.sh # needle finetune → needle build → .cact
|
||||
```
|
||||
|
||||
About 190 source files across **20 Gradle modules**. Modules keep the native/JNI code, tools, and providers separately testable and allow parallel work.
|
||||
|
||||
---
|
||||
|
||||
## 10. Implementation Phases & Timeline
|
||||
|
||||
Estimates assume **1 senior Android dev full-time**; with two devs, roughly 40% less. Every phase ends with a demo build.
|
||||
|
||||
| Phase | Duration | Content | Exit criteria |
|
||||
|---|---|---|---|
|
||||
| **0 – Feasibility spike** | 1 wk | Build `libneedle` for arm64 via NDK, JNI `infer`/`embed`, bench on 2 devices; measure tool budget in the 256-token window; confirm Needle 2 vs 3; test `SpeechRecognizer` on-device availability; Gmail OAuth test app | **Go/No-Go:** p50 < 500 ms inference, ≥ 80% baseline accuracy on 50 prompts |
|
||||
| **1 – Foundation & MVP** | 3 wks | Gradle skeleton, build-logic, core modules, Room/DataStore/Tink; Needle engine + retriever; Orchestrator (local path); OpenAI-compatible + Anthropic + Gemini providers; APP v1 + validator + executor; 15 tools (device, apps, alarms, contacts, media, calendar); Chat UI + action cards; push-to-talk voice (Android STT) | "Turn on the flashlight", "set an alarm for 7", "what's on my calendar" work offline; "what's the weather in Lagos" goes to the cloud |
|
||||
| **2 – Communication & email** | 3 wks | Phone, SMS (flavor-split), WhatsApp open/reply via notification, notification listener + summarize, Gmail OAuth + drafts/send/search, `email.compose` fallback, confirm sheets, audit log, Permission Center | Leave-request → Gmail draft end to end; "reply to Ali on WhatsApp: on my way" works from notification |
|
||||
| **3 – Automation & voice+** | 3 wks | AccessibilityService + recipes (Gmail save-draft fallback, WhatsApp send), `ui.*` tools, screen-context to AI, sherpa-onnx offline STT + VAD, TTS replies, QS tile, widget, assistant role, share-to-Stitch | Full scenario list passes on 3 devices; voice works in airplane mode |
|
||||
| **4 – Agents & tuning** | 2 wks | Hermes connector, OpenCode connector, web search (native + Brave/Tavily), memory tools; synthetic dataset + Needle fine-tune on our catalog; eval harness in CI | ≥ 95% local eval accuracy; Hermes/OpenCode round-trip demo |
|
||||
| **5 – Hardening & release** | 2 wks | Security review, injection red-team, perf/battery profiling, accessibility (TalkBack) for our own UI, Play declarations, privacy policy, store listing, signed `play` + `full` releases | All acceptance criteria in §3.5 met |
|
||||
|
||||
**Total: about 14 weeks to v1.0.** The MVP (Phase 1) is demoable at about week 4.
|
||||
|
||||
---
|
||||
|
||||
## 11. Roadmap after v1
|
||||
- Wake word ("Hey Stitch") via openWakeWord/ONNX in a low-power FGS
|
||||
- MCP client, so any MCP server's tools become cloud-side tools
|
||||
- Expose Stitch **as an MCP server / API on the LAN**, so desktop agents (OpenCode, Hermes, Claude Code) can drive the phone
|
||||
- Routines and triggers ("when I get home, turn on DND"), like Tasker
|
||||
- More app recipes (Telegram, Signal, Slack, Outlook)
|
||||
- Wear OS companion
|
||||
|
||||
---
|
||||
|
||||
## 12. Risks & Mitigations
|
||||
| Risk | Likelihood | Impact | Mitigation |
|
||||
|---|---|---|---|
|
||||
| Needle's Android packaging/JNI is less documented than Python/C | Med | High | Phase 0 spike; fallback: run the `needle --serve` arm64 binary as a local process on `127.0.0.1`, or use the cactus-kotlin SDK |
|
||||
| 256-token window limits tool count | High | Med | Embedding-based top-k retrieval, compact tool descriptions, fine-tuning |
|
||||
| Play policy rejects Accessibility / SMS use | High | High | `play`/`full` flavors, intent fallbacks, prominent disclosure, Notification `RemoteInput` for replies |
|
||||
| `gmail.compose` is a **restricted scope** (needs Google verification + security assessment for public use) | High | Med | Testing mode (≤100 users) during development; intent + accessibility fallback; budget for CASA before public launch |
|
||||
| WhatsApp UI changes break the send recipe | Med | Med | Prefer notification reply and wa.me prefill; resilient selectors (content-desc/resource-id), recipe versioning, graceful fallback to "tap Send yourself" |
|
||||
| Prompt injection via notifications/web | Med | High | Untrusted tagging, forced confirmations, egress limits (§8) |
|
||||
| OEM background restrictions (Xiaomi, Samsung) kill listeners | Med | Med | Battery-optimization exemption guide in onboarding, health check screen |
|
||||
| User cost/latency of cloud AI | Med | Low | Needle-first routing; show which path was used; model choice per provider |
|
||||
|
||||
---
|
||||
|
||||
## 13. Open questions for the owner
|
||||
1. **App name and package id:** is `app.stitch` OK?
|
||||
2. **Distribution:** Play Store, sideload, or both? This decides how much of the `full` flavor we build first.
|
||||
3. **Minimum Android:** is 9 (API 28) OK, or do you need older devices?
|
||||
4. **Gmail:** is Gmail API with OAuth (best UX, needs Google Cloud project + verification later) acceptable for v1, or intent-only?
|
||||
5. **Primary AI to test with first:** OpenRouter, Anthropic, OpenAI, local Ollama, or Hermes?
|
||||
6. **Languages for voice:** English only for v1, or also Urdu/Hindi/Arabic? This affects the STT model choice.
|
||||
7. **License:** open source (Apache-2.0) or closed?
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
# The Stitch signing key
|
||||
|
||||
> **Short version:** a proper release key now exists at `~/.stitch-release-key/`. **Back that folder up
|
||||
> off this machine today.** Nothing uses it yet — builds still use the old debug key on purpose, because
|
||||
> switching keys forces an uninstall. The switch happens once, deliberately, in the order below.
|
||||
|
||||
---
|
||||
|
||||
## Why any of this matters
|
||||
|
||||
Android refuses to install an app over one signed with a different key. It is a security rule and there
|
||||
is no way around it. So the key a release is signed with decides whether a future update can install
|
||||
over your phone's copy of Stitch, or whether you have to uninstall first — which erases your API key,
|
||||
wake phrase, notes, memories and reminders.
|
||||
|
||||
Until now, every Stitch release has been signed with **this machine's Android debug key**
|
||||
(`~/.android/debug.keystore`). That worked, but it is the wrong key for something you rely on:
|
||||
|
||||
- It is a throwaway key the Android tools generate automatically, and any tool can regenerate it.
|
||||
- It expires. Debug keys are valid for 30 years from creation, but they are not treated as durable.
|
||||
- If this machine is ever reinstalled and that file is lost, you can never update Stitch again without
|
||||
uninstalling it first.
|
||||
|
||||
## The new key
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Location | `~/.stitch-release-key/stitch-release.jks` |
|
||||
| Password file | `~/.stitch-release-key/keystore.properties` (permissions `600`) |
|
||||
| Alias | `stitch` |
|
||||
| Algorithm | RSA 4096, SHA384withRSA |
|
||||
| Valid until | 16 September 2056 |
|
||||
| SHA-256 | `79:43:B9:19:BA:DC:EC:CE:F7:C3:67:84:D6:E8:26:8E:7A:54:74:66:06:11:20:37:34:D6:37:9B:21:54:EE:9C` |
|
||||
|
||||
The password was randomly generated and is stored beside the keystore. That is a deliberate trade-off
|
||||
for a personal, single-user, sideloaded app: the folder is `700`, both files are `600`, and the real
|
||||
risk here is losing the key, not someone stealing it off your own machine.
|
||||
|
||||
### Back it up now
|
||||
|
||||
The whole folder, somewhere that is not this machine — an encrypted drive, a password manager's file
|
||||
attachment, or private cloud storage:
|
||||
|
||||
```sh
|
||||
tar czf stitch-release-key-backup.tar.gz -C ~ .stitch-release-key
|
||||
```
|
||||
|
||||
If you lose it, every future Stitch update requires an uninstall. The key cannot be regenerated —
|
||||
a new key with identical details is still a different key to Android.
|
||||
|
||||
## How the build uses it
|
||||
|
||||
It does not, yet. In `app/build.gradle.kts`:
|
||||
|
||||
```kotlin
|
||||
val useReleaseKey = project.hasProperty("releaseKey") && releaseKeyProps.exists()
|
||||
```
|
||||
|
||||
- `./gradlew assembleRelease` → **debug key** (unchanged; installs over your current Stitch)
|
||||
- `./gradlew assembleRelease -PreleaseKey` → **release key** (will NOT install over your current Stitch)
|
||||
|
||||
Verify either one without building:
|
||||
|
||||
```sh
|
||||
./gradlew :app:signingReport # Store: ~/.android/debug.keystore
|
||||
./gradlew :app:signingReport -PreleaseKey # Store: ~/.stitch-release-key/stitch-release.jks
|
||||
```
|
||||
|
||||
## The cutover — do these in order
|
||||
|
||||
Doing this out of order loses your data. That is the entire reason the backup feature was built first.
|
||||
|
||||
1. **Back up the key folder** off this machine (above).
|
||||
2. On the phone: **Settings → Backup & restore → Save a backup.** Choose a passphrase, write it down,
|
||||
and put the file somewhere that is not the phone.
|
||||
3. **Check the backup is real** — open the file and confirm it is a few KB of JSON with
|
||||
`"format": "stitch-backup"` at the top. An empty or missing file means stop.
|
||||
4. Build the changeover release: `./gradlew assembleRelease -PreleaseKey`, copy to `dist/`, verify the
|
||||
version with `aapt dump badging`.
|
||||
5. On the phone: **uninstall Stitch.** Everything is erased at this point — this is the moment the
|
||||
backup exists for.
|
||||
6. Install the new APK.
|
||||
7. **Settings → Backup & restore → Restore from a backup**, pick the file, type the passphrase.
|
||||
8. Close and reopen Stitch.
|
||||
9. Re-grant the special permissions — accessibility (Phone control), notification access, Do Not
|
||||
Disturb and "modify system settings". **Android does not restore these**, and no app can grant them.
|
||||
The backup cannot help here; it is a one-off cost of the changeover.
|
||||
10. Check: does the wake phrase still wake it? Does the AI provider still answer? Are your notes and
|
||||
reminders there?
|
||||
11. From then on, always build with `-PreleaseKey`, and updates install over the top as before.
|
||||
|
||||
Until step 4 happens, keep building **without** the flag.
|
||||
|
||||
## If something goes wrong
|
||||
|
||||
| Problem | What to do |
|
||||
|---|---|
|
||||
| "App not installed" when installing the new APK | The old Stitch is still there. Uninstall it first (step 5) |
|
||||
| Restore says the passphrase is wrong | AES-GCM cannot tell a wrong passphrase from a damaged file. Re-copy the file from wherever you stored it and try again. There is no recovery without the passphrase |
|
||||
| Restored, but the AI provider doesn't work | The API key restores, but check Settings → AI & provider → Test connection. If the key looks empty, paste it again |
|
||||
| Restored, but the wake phrase never triggers | The fingerprints restore, but the listening service needs a restart — close and reopen Stitch. If it still misses you, retrain (5 recordings) |
|
||||
| On-device model gone | Expected. Model files are gigabytes and are not in the backup. Download it again in Settings → On-device model |
|
||||
@@ -0,0 +1,84 @@
|
||||
# Stage A — does 0.4.1 actually work on the phone?
|
||||
|
||||
> About 20 minutes. Install `dist/Stitch-0.4.1.apk`, then work down this list and write **works** or
|
||||
> **broken: what happened** after each line. Plain words are fine — "the alarm list was empty" is more
|
||||
> useful than a technical guess.
|
||||
>
|
||||
> Everything here is untested. It was built and checked in a simulator on the PC, which has no
|
||||
> microphone, no WhatsApp, no Spotify and no real contacts. So these are not expected to all pass, and
|
||||
> finding a broken one is the point.
|
||||
|
||||
**First, after installing:** open Settings → Phone control. If it says "on but not running", switch it
|
||||
off and on again. Android always stops it when an app is updated.
|
||||
|
||||
---
|
||||
|
||||
## 1. The four tabs at the bottom — never opened on a phone
|
||||
|
||||
| # | Do this | Result |
|
||||
|---|---|---|
|
||||
| 1.1 | Set an alarm and a reminder through Chat, then open **Schedule** | |
|
||||
| 1.2 | Are they both listed, soonest first, with the right times? | |
|
||||
| 1.3 | Does Schedule show your real calendar events? | |
|
||||
| 1.4 | Ask Stitch to remember something, add a note, then open **Saved** | |
|
||||
| 1.5 | Are both there? | |
|
||||
| 1.6 | Tap **Workflows** — it should say "coming soon" and nothing else | |
|
||||
| 1.7 | With the keyboard open in Chat, can you still see what you're typing, or does the bottom bar cover it? | |
|
||||
|
||||
## 2. The six Settings pages — never opened on a phone
|
||||
|
||||
| # | Do this | Result |
|
||||
|---|---|---|
|
||||
| 2.1 | Open each of the six categories and come back with the back arrow | |
|
||||
| 2.2 | Change one setting in each, leave the page, come back — did it save? | |
|
||||
| 2.3 | Does the phone's back **gesture** work the same as the arrow? | |
|
||||
| 2.4 | Open a category, turn the phone sideways — known bug, it probably jumps back to the list. Confirm | |
|
||||
|
||||
## 3. The wake phrase — the biggest unknown
|
||||
|
||||
This has **never** been tested with a real voice. The simulator has no microphone.
|
||||
|
||||
| # | Do this | Result |
|
||||
|---|---|---|
|
||||
| 3.1 | Settings → Voice & hotword → turn on, type your phrase, record it 5 times | |
|
||||
| 3.2 | Lock the phone, open something else, say the phrase. Does the bubble appear? | |
|
||||
| 3.3 | How many times out of 10 does it hear you? | |
|
||||
| 3.4 | Does it ever wake up on its own when you haven't said it? | |
|
||||
| 3.5 | In the bubble, say something — does it understand speech? | |
|
||||
| 3.6 | Does it speak its answer back? | |
|
||||
| 3.7 | In the bubble over another app, say "read what's on screen" — does it read **that app**, or itself? | |
|
||||
| 3.8 | Check the battery overnight with listening on. Roughly how much did Stitch use? | |
|
||||
|
||||
## 4. Real apps — the simulator has none of these
|
||||
|
||||
| # | Do this | Result |
|
||||
|---|---|---|
|
||||
| 4.1 | "WhatsApp [someone] I'm on my way" — does it really send, with a confirmation first? | |
|
||||
| 4.2 | When a WhatsApp message arrives: "reply to [name]: ok" | |
|
||||
| 4.3 | "play [a song] on Spotify" — does it **play**, or just show search results? | |
|
||||
| 4.4 | Same on YouTube Music | |
|
||||
| 4.5 | "any important messages?" | |
|
||||
|
||||
## 5. The value-garbling fixes (0.4.1) — only tested as bare functions, never on a real contact list
|
||||
|
||||
| # | Do this | Result |
|
||||
|---|---|---|
|
||||
| 5.1 | Ask it to message a contact whose name is easy to misspell. Right person? | |
|
||||
| 5.2 | Type a phone number yourself and ask it to text that number. Is it the number you typed, digit for digit? | |
|
||||
| 5.3 | Set an alarm for an odd time like 2:14 AM, then say "remove the 2:14 AM alarm" | |
|
||||
| 5.4 | Did the alarm actually turn off in your Clock app — not just say it did? | |
|
||||
|
||||
## 6. One real AI key
|
||||
|
||||
| # | Do this | Result |
|
||||
|---|---|---|
|
||||
| 6.1 | Settings → AI & provider → paste a real key → **Test connection** | |
|
||||
| 6.2 | Ask something that needs thinking: "summarize my last 5 calls" | |
|
||||
| 6.3 | Ask for something multi-step: "open YouTube and search for lo-fi" — watch the floating bar and the Stop button | |
|
||||
|
||||
---
|
||||
|
||||
## When you're done
|
||||
|
||||
Send me the list with your answers. Anything broken gets fixed and shipped as **0.4.2** before any
|
||||
Hermes work starts — that's the rule in `docs/UPGRADE_PLAN.md`, Stage A.
|
||||
@@ -0,0 +1,516 @@
|
||||
# Stitch 1.0 Upgrade & Hermes Integration Plan (final)
|
||||
|
||||
> **Status:** Approved plan, implementation not started
|
||||
> **Written:** 24 September 2026 · supersedes the 24 Sep research draft
|
||||
> **Baseline:** Stitch 0.4.1 (versionCode 14, compile/target SDK 35)
|
||||
> **Owner decision (24 Sep):** the Hermes bridge lives **inside the Stitch app**. There will be no second
|
||||
> companion APK. See §3.
|
||||
>
|
||||
> Every number and claim in this document was checked against the code, the Hermes install on this
|
||||
> machine, and the upstream sources on 24 Sep 2026. Where the earlier draft was wrong, §12 records what
|
||||
> it said and what is actually true, so the mistake is not repeated.
|
||||
|
||||
---
|
||||
|
||||
## 1. In plain language
|
||||
|
||||
Today Stitch is a phone agent. You talk to it, it does things on your phone. Hermes — the AI agent running
|
||||
on your PC — has no real connection to it. The "Hermes" option in Stitch's settings is just a normal
|
||||
AI-provider entry pointing at a web address; it does not make the two systems work together.
|
||||
|
||||
This plan connects them properly, in two directions:
|
||||
|
||||
- **Stitch → Hermes.** Stitch can ask Hermes to do server work and can report whether Hermes is healthy.
|
||||
- **Hermes → Stitch.** From Hermes on your PC (or Telegram, or the web UI) you can say "turn on my phone's
|
||||
flashlight" and it happens, with the phone still deciding what is safe.
|
||||
|
||||
The important rule: **Hermes never touches your phone directly.** It asks Stitch, and Stitch applies the
|
||||
same safety checks it already applies to you — permissions, risk level, confirmation for anything
|
||||
dangerous, and proof that the action actually worked.
|
||||
|
||||
The second important rule, and your decision: **all of this goes inside Stitch.** Not a separate app.
|
||||
|
||||
---
|
||||
|
||||
## 2. What Stitch is today (verified 24 Sep 2026)
|
||||
|
||||
| Fact | Value | Where checked |
|
||||
|---|---|---|
|
||||
| Version | 0.4.1, versionCode 14 | `app/build.gradle.kts:17-18` |
|
||||
| Android tools | **70** | `app/build/all-tools.json` |
|
||||
| Tools exposed to Needle on-device | **32** | `app/build/needle-tools.json` |
|
||||
| Kotlin source | 59 files, 10,102 lines | `app/src/main/kotlin` |
|
||||
| Unit tests | 53 in 10 files, all passing | `app/src/test` |
|
||||
| On-device instrumentation tests | **0** | — |
|
||||
| Min / target Android | 9 (API 28) / 15 (API 35) | `app/build.gradle.kts:15-16` |
|
||||
| HTTP client | OkHttp 4.12.0 | `app/build.gradle.kts:72` |
|
||||
| Hermes setting today | generic OpenAI-compatible preset at `http://192.168.1.10:8642/v1` | `core/Settings.kt:77` |
|
||||
|
||||
Stitch's single biggest design strength is that **every action already flows through one executor**:
|
||||
|
||||
```
|
||||
request → permission check → prepare() → risk / confirmation → run() → verify → report
|
||||
```
|
||||
|
||||
Risk comes from the tool itself (`tools/Tool.kt`, `enum class Risk { LOW, MEDIUM, HIGH }`), never from a
|
||||
model. Tools that read other people's content set `readsUntrusted`, which forces confirmation on whatever
|
||||
happens next. This plan **extends that path**. It never creates a second way to act on the phone.
|
||||
|
||||
### What is on this machine right now
|
||||
|
||||
| Thing | State |
|
||||
|---|---|
|
||||
| Hermes gateway | Running (PID 1767) |
|
||||
| Hermes API server | **Not listening.** Defaults to `127.0.0.1:8642`, and refuses to start without `API_SERVER_KEY` |
|
||||
| Hermes MCP servers | None configured |
|
||||
| Hermes webhook platform | Not configured |
|
||||
| Hermes plugins directory | `~/.hermes/plugins` — empty |
|
||||
| `raulvidis/hermes-android` | **Cloned** at `/mnt/ssd-storage/projects/hermes-android-bridge` (not registered as a plugin) |
|
||||
| This host's reachable address | `100.x.y.z` (Tailscale). **Not** `192.168.1.10` |
|
||||
|
||||
That last row matters: Stitch's shipped Hermes preset points at an address that is not this machine.
|
||||
|
||||
### Documentation state
|
||||
|
||||
- `README.md` — updated 24 Sep, now matches the code (70 tools, 53 tests, 40-turn history).
|
||||
- `DEVELOPMENT_HISTORY.md` — accurate up to 0.4.1.
|
||||
- `docs/PLAN.md` — **historical.** The original 19 Sep scope of work. Not the implementation contract.
|
||||
- `docs/HOTWORD_PLAN.md` — **historical.** Describes the wake phrase as unbuilt; it shipped in 0.4.0.
|
||||
|
||||
---
|
||||
|
||||
## 3. The architecture decision: one app, not two
|
||||
|
||||
The existing `hermes-android` project is a **separate companion APK** that runs its own accessibility
|
||||
service and its own notification listener. Installing it alongside Stitch would be a mistake:
|
||||
|
||||
| Problem with a second app | Consequence |
|
||||
|---|---|
|
||||
| Two accessibility services both reading every screen | Double battery drain; Android delivers events to both; taps can race |
|
||||
| Two notification listeners | Both wake on every notification; duplicate parsing |
|
||||
| Two sets of sensitive permissions to grant and to trust | Twice the attack surface, twice the setup confusion |
|
||||
| The companion app has **no risk levels, no confirmation, no contact grounding** | A remote command could send an SMS to a number a model invented — the exact class of bug B-23 and C-09 were fixed to prevent |
|
||||
| Two audit trails, or none | You could not answer "what did Hermes do to my phone yesterday?" |
|
||||
|
||||
**Decision: the relay client becomes a module inside Stitch**, at
|
||||
`app/src/main/kotlin/app/stitch/bridge/`. A remote command from Hermes enters Stitch and goes down the
|
||||
*same* executor path a typed command does. Stitch remains the only thing on the phone that touches
|
||||
Android APIs.
|
||||
|
||||
### Target shape
|
||||
|
||||
```text
|
||||
┌──────────────────────────────────────────┐
|
||||
│ Hermes Agent (PC) │
|
||||
│ skills · memory · web · tools │
|
||||
└──────┬────────────────────────┬──────────┘
|
||||
│ │
|
||||
Hermes API server (:8642) hermes-stitch-link plugin
|
||||
/v1/runs · /v1/capabilities exposes stitch_* tools
|
||||
/health/detailed · approvals + in-process relay (WSS)
|
||||
│ │
|
||||
│ Stitch calls out │ Stitch dials out
|
||||
│ (HTTPS) │ (WebSocket, stays open)
|
||||
▼ ▼
|
||||
┌──────────────────────────────────────────┐
|
||||
│ STITCH (one APK) │
|
||||
│ ┌────────────────────────────────────┐ │
|
||||
│ │ bridge/ ← relay client, pairing, │ │
|
||||
│ │ remote gate, audit │ │
|
||||
│ │ hermes/ ← health, runs, status │ │
|
||||
│ └──────────────┬─────────────────────┘ │
|
||||
│ ▼ │
|
||||
│ the existing single executor: │
|
||||
│ permissions → prepare() → risk → │
|
||||
│ confirm → run() → verify → audit │
|
||||
│ ▼ │
|
||||
│ 70 tools · accessibility · Needle │
|
||||
└──────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Nothing new touches Android. `bridge/` is a **doorway**, not an executor.
|
||||
|
||||
### What gets reused from the existing bridge project
|
||||
|
||||
The clone at `/mnt/ssd-storage/projects/hermes-android-bridge` is a good donor, and small:
|
||||
|
||||
| File | Lines | Take it? |
|
||||
|---|---|---|
|
||||
| `client/RelayClient.kt` | 245 | **Yes — port.** OkHttp WebSocket, outbound, exponential backoff 1→30 s. Stitch already has OkHttp 4.12. Convert Gson → `org.json` to match Stitch |
|
||||
| `auth/PairingManager.kt` | 82 | **Yes — port, then harden** (see §6) |
|
||||
| `hermes-android-plugin/android_relay.py` | 581 | **Yes — fork.** Already has TLS support, auth rate limiting (5 fails/60 s → 5 min IP block), and single-phone enforcement. Do not rewrite this from scratch |
|
||||
| `executor/ActionExecutor.kt`, `executor/ScreenReader.kt` | ~1,400 | **No.** Stitch has its own in `automation/`, with the safety gates this one lacks |
|
||||
| `server/BridgeServer.kt`, `BridgeRouter.kt` | ~250 | **No.** That is the phone-as-HTTP-server path. Stitch dials out only |
|
||||
| `android_send_intent`, `android_broadcast` routes | — | **No. Permanently excluded.** See §6 |
|
||||
|
||||
Estimated new Stitch code for the bridge doorway: **400–600 lines**, plus the remote gate.
|
||||
|
||||
---
|
||||
|
||||
## 4. Stitch → Hermes (the "Brain" side)
|
||||
|
||||
### Do not rewrite the provider
|
||||
|
||||
The Hermes API server already serves `/v1/chat/completions`, `/v1/responses`, `/v1/messages` and
|
||||
`/v1/models`. Stitch's existing `OpenAiCompatibleProvider` is a **valid transport for chat** and stays.
|
||||
The earlier draft proposed replacing it with a native client; that is unnecessary work.
|
||||
|
||||
What is genuinely missing is status and long-job control. That is a thin layer on top:
|
||||
|
||||
**`hermes/HermesClient.kt`** — all endpoints below were confirmed present in the Hermes installed at
|
||||
`~/.hermes/hermes-agent/gateway/platforms/api_server.py`:
|
||||
|
||||
| Endpoint | Used for |
|
||||
|---|---|
|
||||
| `GET /health`, `GET /health/detailed` | Is Hermes up and ready |
|
||||
| `GET /v1/capabilities` | What this Hermes can do |
|
||||
| `GET /v1/models`, `/v1/skills`, `/v1/toolsets` | What is available |
|
||||
| `GET /api/sessions` | Existing conversations |
|
||||
| `POST /v1/runs`, `GET /v1/runs/{id}` | Start and inspect a long job |
|
||||
| `GET /v1/runs/{id}/events` | Live progress |
|
||||
| `POST /v1/runs/{id}/stop` · `/steer` · `/approval` | Control a running job |
|
||||
|
||||
`/health/detailed` is designed to return readiness and counts **without** secrets, raw paths or raw
|
||||
errors. Stitch preserves that boundary — it summarises, it never widens it.
|
||||
|
||||
### Setup work this requires on the PC (do this first, it is the real blocker)
|
||||
|
||||
1. Set `API_SERVER_KEY` in Hermes' scoped secrets. Without it the API server **will not start**.
|
||||
2. Bind the API server to the Tailscale address `100.x.y.z`, not `127.0.0.1`.
|
||||
3. Update Stitch's Hermes preset from `http://192.168.1.10:8642/v1` to the real address, over TLS.
|
||||
4. Rename the preset **"Hermes Brain (API)"** so it is not confused with the Link.
|
||||
|
||||
---
|
||||
|
||||
## 5. Hermes → Stitch (the "Link" side)
|
||||
|
||||
### Wire format
|
||||
|
||||
Keep the existing envelope so the relay and plugin stay compatible:
|
||||
|
||||
```json
|
||||
{
|
||||
"request_id": "uuid",
|
||||
"origin": "hermes",
|
||||
"method": "POST",
|
||||
"path": "/tool/flashlight",
|
||||
"params": {},
|
||||
"body": { "on": true },
|
||||
"nonce": "single-use",
|
||||
"issued_at": 0,
|
||||
"expires_at": 0,
|
||||
"idempotency_key": "uuid",
|
||||
"correlation_id": "hermes-run-id"
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"request_id": "uuid",
|
||||
"status": 200,
|
||||
"result": {
|
||||
"ok": true,
|
||||
"verified": true,
|
||||
"tool": "flashlight",
|
||||
"risk": "LOW",
|
||||
"state": { "on": true }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`verified` is mandatory and is never optimistic. This is lesson C-08: *a tool may only report what it
|
||||
proved.* If Stitch could not confirm the outcome, `verified` is `false` and the text says so.
|
||||
|
||||
### The remote gate
|
||||
|
||||
`bridge/RemoteExecutionGate.kt` sits between the WebSocket and the tool executor and checks, in order:
|
||||
|
||||
1. Device identity and signature valid
|
||||
2. Nonce unused, request not expired, idempotency key not already served
|
||||
3. Tool exists **and is on the remote allow-list** (allow-list, never deny-list)
|
||||
4. Remote kill switch is off
|
||||
5. Android runtime permission present — a remote origin cannot skip the permission flow
|
||||
6. Arguments grounded by the same rules as local (contacts, numbers, times — B-23/B-26/B-27/B-28)
|
||||
7. Risk from the tool registry → LOW runs; MEDIUM/HIGH raise a phone-side confirmation
|
||||
8. Untrusted-content state respected (prompt-injection guard)
|
||||
9. Result verified, audit row written, response returned
|
||||
|
||||
Then and only then does it call the existing executor.
|
||||
|
||||
### Default remote policy
|
||||
|
||||
| Category | Remote behaviour |
|
||||
|---|---|
|
||||
| Flashlight, volume, battery, device status, open app, current app, read screen, media control | Runs immediately |
|
||||
| Screen tap / type / key / swipe | Runs, but sensitive-button check stays on |
|
||||
| Calls, SMS, WhatsApp/Telegram send, contact or event deletion | **Phone-side confirmation, always** |
|
||||
| `send_intent`, `broadcast`, shell, filesystem | **Never exposed.** No route, no tool name |
|
||||
| Anything after untrusted content was read | Confirmation, same as local |
|
||||
|
||||
Remote mode may be **stricter** than local mode. It may never be looser.
|
||||
|
||||
**Fail closed when offline.** A queued destructive command does not execute on reconnect. It expires and
|
||||
must be re-issued. A dropped connection returns a clear failure, not silence.
|
||||
|
||||
---
|
||||
|
||||
## 6. Security
|
||||
|
||||
The reference bridge documents its own limits honestly in `SECURITY.md`: plaintext `ws://`, a 6-character
|
||||
pairing code, and unrestricted device access once paired. Fine for a prototype. Not acceptable as a
|
||||
permanent credential for your phone.
|
||||
|
||||
| Reference bridge | Stitch Link |
|
||||
|---|---|
|
||||
| 6-char pairing code, permanent | Pairing code for **first contact only**, then a 256-bit device key in Android Keystore |
|
||||
| `ws://` plaintext | **WSS/TLS**, or Tailscale, or both. Plaintext refused outside loopback |
|
||||
| No replay protection | Single-use nonce + expiry + idempotency key |
|
||||
| No revocation | Per-device rotation and instant revoke from the phone |
|
||||
| Full device access | Allow-listed tools, risk gate, phone-side confirmation |
|
||||
| No audit | Every remote command logged: origin, tool, arguments, result, timestamp |
|
||||
| — | Global **kill switch** that stops all remote commands without disabling local chat |
|
||||
| — | Optional biometric confirm for remote HIGH-risk actions |
|
||||
|
||||
Tokens never appear in URLs, logs, notifications, or source. The relay fork keeps upstream's
|
||||
`Authorization: Bearer` handshake and **drops** its legacy `?token=` query-parameter fallback.
|
||||
|
||||
---
|
||||
|
||||
## 7. The plan, in stages
|
||||
|
||||
Stages are named, not numbered, because `DEVELOPMENT_HISTORY.md` and `README.md` already reference a
|
||||
"Phase 4" from the historical `docs/PLAN.md` (Needle fine-tuning). Numbering again would collide.
|
||||
|
||||
Durations assume the working pattern that actually produced 0.4.1: AI-built, owner-verified on one phone.
|
||||
|
||||
---
|
||||
|
||||
### Stage A — Prove 0.4.1 actually works · 1–2 days · **blocks everything else**
|
||||
|
||||
Nothing in this plan is worth building on a release nobody has confirmed. These are all currently on the
|
||||
"not verified" list in `DEVELOPMENT_HISTORY.md` §10:
|
||||
|
||||
- Open the four tabs on the phone. Does Schedule show real alarms, reminders and calendar events? Does
|
||||
Saved show notes and memories?
|
||||
- Open all six Settings category pages. Does every setting still save? Does back work? What happens on
|
||||
rotation (known bug: it forgets which page was open)?
|
||||
- Wake phrase with a real voice — the emulator has no microphone, so this has **never** been tested.
|
||||
- Speech recognition and spoken replies in the bubble.
|
||||
- Real WhatsApp send, and a notification reply.
|
||||
- Music in Spotify / YouTube Music.
|
||||
- One real cloud provider key, end to end.
|
||||
- The B-26/B-27/B-28 fixes on a real contact list.
|
||||
|
||||
**Exit:** a written pass/fail for each. Anything broken is fixed and released as 0.4.2 before Stage B.
|
||||
|
||||
---
|
||||
|
||||
### Stage B — Data and identity safety net · 2–3 days
|
||||
|
||||
Two ways to lose all your settings currently exist, and both must be closed **before** any migration or
|
||||
release-signing work, not after.
|
||||
|
||||
- **Real signing key.** Releases are signed with this machine's `~/.android/debug.keystore`. Generate a
|
||||
proper release keystore, back it up off-machine, and document it. Do this *now*: changing the key later
|
||||
forces an uninstall, which erases everything.
|
||||
- **Export / restore.** A single file holding API keys, wake-phrase fingerprints, notes, memories,
|
||||
reminders, default apps and settings. Restore tested on a wiped install.
|
||||
- **Then** the SharedPreferences → Room/DataStore migration, with the export as the fallback.
|
||||
- Add the first on-device instrumentation test: install 0.4.x → upgrade → assert settings survive.
|
||||
- Fix the build warning. It comes from the **Kotlin plugin 2.4.20**, not from Gradle itself: either move
|
||||
to a Gradle version KGP supports, or set `kotlin.suppressGradlePluginWarnings=DeprecatedGradleVersionWarning`.
|
||||
|
||||
**Exit:** a release can be installed over 0.4.1, and over a factory-reset phone, without losing anything.
|
||||
|
||||
---
|
||||
|
||||
### Stage C — Hermes Brain · 3–4 days
|
||||
|
||||
- PC side: set `API_SERVER_KEY`, bind the API server to the Tailscale address, confirm it answers.
|
||||
- `hermes/HermesClient.kt` — health, capabilities, models, skills, toolsets, sessions, runs.
|
||||
- `hermes/HermesStatusRepository.kt` — one safe summary card for a phone screen.
|
||||
- Rename the preset to **"Hermes Brain (API)"** and fix its address.
|
||||
- A Hermes status card in Stitch, and a `hermes_status` tool so you can just ask.
|
||||
|
||||
**Exit:** Stitch shows live Hermes readiness and active-run counts. A long Hermes job can be started,
|
||||
watched, stopped and resumed from the phone. No secret, key or raw server path appears in any Stitch
|
||||
reply or log.
|
||||
|
||||
---
|
||||
|
||||
### Stage D — Hermes Link MVP · 1 week
|
||||
|
||||
- `bridge/` inside Stitch: `BridgeClient` (ported `RelayClient`), `BridgeProtocol`, `BridgeAuth`,
|
||||
`RemoteExecutionGate`, `PendingApproval`, `BridgeAudit`.
|
||||
- Host side: fork `android_relay.py` into `hermes-stitch-link`, TLS on, legacy `?token=` removed.
|
||||
- Pairing screen in Stitch: pair, show device key fingerprint, rotate, revoke, kill switch.
|
||||
- **12 low-risk tools only:** `ping`, `device_status`, `get_battery`, `flashlight`, `set_volume`,
|
||||
`open_app`, current app, `screen_read`, `screen_tap`, `screen_type`, `screen_key`, `media_control`.
|
||||
- Audit tab showing every remote command.
|
||||
|
||||
**Exit:** "turn on my phone's flashlight" works from the Hermes web UI. "What's my phone's battery?"
|
||||
works. Pulling the phone off Wi-Fi mid-command produces a clear failure and executes nothing later. A
|
||||
200-command soak test produces no duplicate and no unsafe action. *(200, not 1,000 — sized to one phone
|
||||
and one afternoon.)*
|
||||
|
||||
---
|
||||
|
||||
### Stage E — Full tool bridge and MCP · 1.5–2 weeks
|
||||
|
||||
- Map the remaining Stitch tools to remote routes, each marked **remote-allowed** or **local-only**.
|
||||
Every one of the 70 gets an explicit decision recorded in a generated `tool-catalog.json`.
|
||||
- Keep the upstream route names where they match (`/tap`, `/type`, `/screenshot`, `/open_app`, `/ping`…)
|
||||
so existing Hermes skills keep working. The upstream plugin ships **38 tools** — its own README says
|
||||
so — and `/intent` and `/broadcast` are **deliberately not implemented**.
|
||||
- Screenshots, screen diffs, notifications, contacts, location, clipboard, TTS, event streaming.
|
||||
- Host-side `mcp_adapter.py` so Hermes, Claude Code and OpenCode can use the same safe surface.
|
||||
- Approval / steer / stop propagation between a Hermes run and a phone confirmation.
|
||||
|
||||
**Exit:** high-risk actions always pause for phone confirmation, from every surface. Screen and
|
||||
notification text stays marked untrusted. Every one of the 70 tools has a remote decision on record.
|
||||
|
||||
---
|
||||
|
||||
### Stage F — Hardening and 1.0 · 1 week
|
||||
|
||||
- Threat model for remote control and prompt injection, written down.
|
||||
- Red-team suite: malicious notification, hostile webpage, hostile Hermes prompt, replayed command,
|
||||
expired nonce, revoked device, kill switch mid-command.
|
||||
- Battery, memory and reconnect profiling with the Link connected all day.
|
||||
- Android 16 / API 36 check, including edge-to-edge layout.
|
||||
- Release, signed with the Stage B key.
|
||||
|
||||
**Exit:** no high-risk action bypasses confirmation in any automated or manual test. Remote access can be
|
||||
revoked in one tap and takes effect immediately. The docs describe what actually shipped.
|
||||
|
||||
---
|
||||
|
||||
### Total to 1.0: roughly 4–5 weeks of working sessions.
|
||||
|
||||
---
|
||||
|
||||
## 8. Explicitly out of scope for 1.0
|
||||
|
||||
The earlier draft folded these into the release. Each is a product in its own right, and none of them is
|
||||
needed for the Hermes connection to work. They become the **post-1.0 roadmap**:
|
||||
|
||||
- **Workflow engine** (step types, variables, retry, branch, loop, triggers, visual editor, dry-run).
|
||||
The Workflows tab stays a placeholder, honestly labelled.
|
||||
- **Namespaced, searchable memory** with provenance and expiry.
|
||||
- **Voice upgrades** — offline STT fallback, speaker verification, multilingual profiles.
|
||||
- **Needle 3.** It exists (`huggingface.co/Cactus-Compute/needle3`, updated 19 Sep, tagged tool-calling,
|
||||
with `android-arm64` / `android-armv7` / `android-riscv64` builds). Worth evaluating later. Note it
|
||||
ships **no android-x86_64**, so the emulator stub (A-07) is still required either way.
|
||||
- **Task-scoped tool retrieval** by embeddings instead of sending all 70 tools every time.
|
||||
- **SAF file transfer**, editable Schedule and Saved, home dashboard.
|
||||
|
||||
---
|
||||
|
||||
## 9. Non-negotiable rules
|
||||
|
||||
1. Never let a model, Hermes, a webhook or a remote client choose its own risk level.
|
||||
2. Never expose `send_intent`, `broadcast`, shell or filesystem tools remotely. Not once, not behind a flag.
|
||||
3. Never put a secret in a URL, a log, a notification, or a document.
|
||||
4. Never report success without proof. Unverified is reported as unverified.
|
||||
5. Never persist screenshots, notification bodies or clipboard contents by default.
|
||||
6. Never let a remote request skip the Android permission flow or the untrusted-content check.
|
||||
7. Never add a remote tool without an allow-list entry, an audit row, a test, and a doc update.
|
||||
8. A second app is never the answer. If a capability is needed on the phone, it goes in Stitch.
|
||||
|
||||
---
|
||||
|
||||
## 10. Files this creates
|
||||
|
||||
Inside Stitch — new packages only, nothing existing is duplicated:
|
||||
|
||||
```text
|
||||
app/src/main/kotlin/app/stitch/
|
||||
bridge/ ← NEW: the doorway, not an executor
|
||||
BridgeClient.kt outbound WSS, reconnect (port of RelayClient.kt)
|
||||
BridgeProtocol.kt envelope encode/decode
|
||||
BridgeAuth.kt device key, nonce, pairing (port of PairingManager.kt, hardened)
|
||||
RemoteExecutionGate.kt the 9 checks in §5
|
||||
PendingApproval.kt phone-side confirmation for remote HIGH risk
|
||||
BridgeAudit.kt what happened, when, from where
|
||||
hermes/ ← NEW
|
||||
HermesClient.kt the endpoints in §4
|
||||
HermesStatusRepository.kt one safe summary
|
||||
data/ ← NEW (Stage B)
|
||||
StitchDatabase.kt · AuditRepository.kt · BackupRepository.kt
|
||||
```
|
||||
|
||||
Unchanged and reused as-is: `agent/`, `tools/`, `automation/`, `needle/`, `core/`, `voice/`,
|
||||
`notifications/`, `ai/`, `ui/`.
|
||||
|
||||
On the PC:
|
||||
|
||||
```text
|
||||
hermes-stitch-link/ ← fork of hermes-android-plugin
|
||||
plugin.yaml · __init__.py
|
||||
relay.py forked from android_relay.py, TLS-only
|
||||
tools.py stitch_* tool definitions
|
||||
mcp_adapter.py Stage E
|
||||
tests/
|
||||
```
|
||||
|
||||
The PC plugin **translates only**. It contains no Android logic. If it ever needs to know how Android
|
||||
works, something has been put in the wrong place.
|
||||
|
||||
---
|
||||
|
||||
## 11. Definition of done
|
||||
|
||||
- Stitch works fully on its own when Hermes is off or unreachable.
|
||||
- Hermes can run low-risk phone actions through Stitch, and high-risk ones only with a phone confirmation.
|
||||
- Stitch can report Hermes health and run, watch and stop Hermes jobs.
|
||||
- Every remote command, approval, result and failure is in the audit log.
|
||||
- The Link reconnects safely after network loss and after a Hermes restart.
|
||||
- TLS or Tailscale is the default; plaintext is refused off-loopback.
|
||||
- All 70 tools carry an explicit remote-allowed or local-only decision.
|
||||
- There is exactly **one** Stitch APK, signed with a backed-up release key.
|
||||
- 0.4.1 has been verified on the real phone (Stage A) and upgrades preserve all settings (Stage B).
|
||||
- README, development history and this document describe what actually shipped.
|
||||
|
||||
---
|
||||
|
||||
## 12. Corrections to the 24 Sep research draft
|
||||
|
||||
Recorded so the errors are not re-introduced. This is the same audit-trail discipline as
|
||||
`DEVELOPMENT_HISTORY.md` §8.
|
||||
|
||||
| # | The draft said | Actually |
|
||||
|---|---|---|
|
||||
| 1 | The `hermes-android` bridge "is not installed locally" | It is **cloned** at `/mnt/ssd-storage/projects/hermes-android-bridge` (remote `raulvidis/hermes-android`), with a `stitch-screens/` folder. Only its plugin registration is absent — `~/.hermes/plugins` is empty |
|
||||
| 2 | The bridge has "42 `android_*` tools" (stated 3×, and used in an exit criterion) | **38.** Its own README prints `✓ hermes-android v0.3.0 (38 tools)`. 42 counts non-tool identifiers such as `android_relay`, `android_setup`, `android_tool` |
|
||||
| 3 | Listed "README says 54 tools" as drift to fix | The same draft had already fixed it. README says 70. Stale text |
|
||||
| 4 | Implied the doc cleanup was complete | `PLAN.md` still said "DRAFT v0.1", `HOTWORD_PLAN.md` still said the wake phrase was unbuilt, and `DEVELOPMENT_HISTORY.md` was never updated at all — breaking the standing rule in `CLAUDE.md`. Fixed in this change |
|
||||
| 5 | "Enable the Hermes API server on the private host network" | Understated. It defaults to `127.0.0.1:8642` **and refuses to start without `API_SERVER_KEY`**. Both must change before anything connects |
|
||||
| 6 | — (not mentioned) | Stitch's Hermes preset points at `192.168.1.10`, which is not this machine. The reachable address is `100.x.y.z` |
|
||||
| 7 | Replace the OpenAI-compatible provider with a native client | Unnecessary. The API server serves `/v1/chat/completions`, `/v1/responses`, `/v1/messages`, `/v1/models`. Keep the provider; add status and runs on top |
|
||||
| 8 | "Never expose raw intent/broadcast" **and** "preserve compatibility with the 42-tool route names" | Contradictory — that catalogue contains `android_send_intent` and `android_broadcast`. Now an explicit permanent exclusion (§6, §9.2) |
|
||||
| 9 | Proposed creating `tools/ToolRegistry.kt`, `ToolExecutor.kt`, `ToolContract.kt`; omitted every existing package | `ToolRegistry.kt` already exists. There is no separate executor — it lives in `agent/Agent.kt`, the contract in `tools/Tool.kt`. Written without opening the source tree |
|
||||
| 10 | Room migration early; "installs without losing settings" checked only in the final phase | Moved to Stage B with an export/restore path and the first instrumentation test, before any storage change |
|
||||
| 11 | — (not mentioned) | The debug signing key. `DEVELOPMENT_HISTORY.md` §11 flags it with the only ⚠️ in the whole audit. Now Stage B |
|
||||
| 12 | Exit criteria requiring Pixel + Samsung + Xiaomi devices, and a 1,000-command soak | Not achievable — there is one phone. Replaced with the owner's phone and a 200-command soak |
|
||||
| 13 | 11–13 weeks, with workflows, memory and voice inside 1.0 | ~4–5 weeks to 1.0; those three moved to the post-1.0 roadmap (§8) |
|
||||
| 14 | "Needle 3 … [12]" citing the **needle2** model card | The card is `Cactus-Compute/needle3`. It exists and is tagged tool-calling. Still no android-x86_64 build |
|
||||
| 15 | "Update Gradle from the deprecated 8.11.1 line" | The warning is emitted by the **Kotlin** Gradle plugin 2.4.20, not by Gradle. Fix or suppress accordingly |
|
||||
| 16 | Introduced a new "Phase 4" | Collides with the historical `PLAN.md` Phase 4 (Needle fine-tuning) referenced in the README and development history. Stages are now lettered |
|
||||
|
||||
---
|
||||
|
||||
## Sources
|
||||
|
||||
Verified reachable on 24 September 2026 unless marked.
|
||||
|
||||
| # | Source | Used for |
|
||||
|---|---|---|
|
||||
| [1] | `~/.hermes/hermes-agent/gateway/platforms/api_server.py` (local) | Every endpoint in §4; `DEFAULT_HOST`/`DEFAULT_PORT`; the `API_SERVER_KEY` requirement |
|
||||
| [2] | `~/.hermes/config.yaml` (local) | No MCP servers, no webhook platform, `api_server.max_concurrent_runs: 10` |
|
||||
| [3] | `/mnt/ssd-storage/projects/hermes-android-bridge` (local clone) | Envelope format, relay design, file sizes, the 38-tool count, `SECURITY.md` limitations |
|
||||
| [4] | `app/build/all-tools.json`, `needle-tools.json` (generated by the unit tests) | 70 tools, 32 Needle tools |
|
||||
| [5] | https://hermes-agent.nousresearch.com/docs/user-guide/features/api-server | API server behaviour |
|
||||
| [6] | https://hermes-agent.nousresearch.com/docs/user-guide/features/mcp | MCP discovery and per-server filtering |
|
||||
| [7] | https://huggingface.co/Cactus-Compute/needle3 | Needle 3 platform builds and capabilities |
|
||||
| [8] | https://github.com/raulvidis/hermes-android | Upstream of the local clone |
|
||||
| [9] | https://developer.android.com/about/versions/16/behavior-changes-16 | Stage F Android 16 check |
|
||||
Reference in new issue
Block a user