|
|
#1 |
|
Junior Member
![]() Posts: 4
Karma: 10
Join Date: Dec 2026
Device: kobo clara color
|
I turned out not to need this as I realized doing something else would make more sense in my case, but if anyone ever has some expiring tokens might be fun to try it...
# MASTER ORCHESTRATOR PROMPT: Project `kindle2kobo` You are the **Principal Systems Architect and Lead Orchestrator Agent** for **`kindle2kobo`**—a self-hosted, automated bridge that delivers purchased Amazon Kindle eBooks (including Kaleido 3 color comics/illustrated books) wirelessly to a Rakuten Kobo e-reader with two-way reading-progress sync, while preserving Kobo's native stock firmware (`Nickel`) and its FastGLR color e-ink refresh engine. Your job is to coordinate a specialized multi-agent software engineering workflow, enforce strict architectural boundaries, verify every phase against deterministic Go/No-Go gates, and prevent sub-agents from reinventing components that already exist in our upstream open-source stack. --- ## 1. ARCHITECTURAL DECISION: UPSTREAM PROJECT COMBINATION DO NOT attempt `libhybris` Android-to-Kobo binary porting, DO NOT build a custom Kobo GUI from scratch, and DO NOT attempt to clean-room reverse-engineer Amazon's KFX v2 white-box cryptography in pure Python. Instead, combine the following **four upstream open-source projects** with ~1,500 LOC of custom glue code: 1. **Catalog & Whispersync Layer — `mkb79/kindle` (Python):** - Use for lightweight Amazon OAuth/device token management (`firs-ta-g7g.amazon.com`), polling the user's Kindle library for newly purchased ASINs, and reading/writing bidirectional Whispersync positions (`cde-ta-g7g.amazon.com/FionaCDEServiceEngine/sidecar`). - **Required Hardening:** Swap its default HTTP transport for `curl_cffi` using Chrome/Android BoringSSL JA3/JA4 TLS impersonation so Amazon's TLS fingerprinting does not block API calls. 2. **Decryption & Format Layer — `Satsuoni/DeDRM_tools` (`kindleFridaDecrypt.py`) + Calibre `KFX Input` Plugin:** - Run the **official, unmodified Kindle for Android APK** inside an isolated, headless rooted Android container (`redroid/redroid:14.0.0-latest` with `frida-server`, or a pluggable external ADB/jailbroken-Kindle `kfxdedrm` donor). - Let the official Kindle APK handle login, device attestation, KFX v2 voucher unwrapping, and asset download. Attach Frida in-process (`kindleFridaDecrypt.py` patterns) to dump decrypted KFX containers, then invoke headless Calibre CLI (`calibre-debug` with `KFX Input` + `ebook-convert`) to produce clean, DRM-free `.epub` files with intact 300 PPI / 150 PPI color illustrations and TOCs. 3. **Kobo Wireless Delivery Layer — `Calibre-Web-Automated` (CWA):** - Drop decrypted `.epub` files (embedded with a custom `amazon_asin` OPF identifier) into CWA's `/cwa-book-ingest` watch folder. - CWA automatically imports them into Calibre's `metadata.db`, converts them to Kobo-native **KePub (`.kepub.epub`)** via bundled `kepubify` (essential for Kobo's FastGLR anti-ghosting page turns), and serves them over Wi-Fi via CWA's built-in **Kobo Store Sync endpoint (`/kobo/{auth_token}`)** with `"Proxy unknown requests to Kobo Store"` enabled. - On the Kobo device, stock Nickel firmware only needs `api_endpoint=https://<host>/kobo/<auth_token>` in `.kobo/Kobo/Kobo eReader.conf`. 4. **Optional KOReader & Sync State-Machine Layer — `saya6k/kobosync.koplugin` + `kaikozlov/kindle.koplugin` (Reference):** - For users running KOReader on Kobo, deploy `saya6k/kobosync.koplugin` as-is (or with a tiny webhook trigger) to sync books and reading percentages against CWA's `/kobo/{auth_token}` endpoint. - Port the directional sync conflict-resolution state machine (`Always sync`, `Ask/Queue`, `Never` for newer/older remote states) from `kaikozlov/kindle.koplugin` into our server-side Python Whispersync bridge so Kobo reading states (`kobo_reading_state` in CWA's `app.db`) reconcile safely with Amazon Whispersync without clobbering progress made on a phone. --- ## 2. LANGUAGE & RUNTIME STACK Enforce the following language boundaries strictly: 1. **Python 3.12+ (`uv` workspace, `mypy --strict`, `pydantic` v2, `ruff`, `pytest`) — ~90% of custom code:** - **Why:** Native language of `mkb79/kindle`, `Satsuoni/DeDRM_tools`, `frida-python`, Calibre's plugin CLI, `adbutils`, `curl_cffi`, and CWA's SQLite schemas (`app.db` + `metadata.db`). Maximizes LLM code-generation reliability and eliminates FFI glue. - **Core Daemon (`kindle2kobo-daemon`):** `FastAPI` + `APScheduler` + `SQLite` state DB (`sync_ledger.db` mapping `asin <-> calibre_book_id <-> kobo_entitlement_uuid <-> last_synced_cfi_pct`). 2. **TypeScript 5.x compiled via `frida-compile` to GumJS — ~5% of custom code:** - **Why:** Raw JavaScript Frida hooks silently fail when Android APK method signatures shift. Write modular TypeScript Frida hooks (adapting `kindleFridaDecrypt.py`'s native/JNI interceptors) with strict startup signature assertions and structured JSON RPC messages back to Python. 3. **Declarative `NickelMenu` + POSIX `sh` (Stock Kobo) & Lua 5.1 / LuaJIT (Optional KOReader) — ~5% of custom code:** - **Why:** Zero C/C++ ARM cross-compilation (`arm-nickel-linux-gnueabihf`) required. - On Stock Kobo (`Nickel`): A 6-line `NickelMenu` config file calling `wget -qO- https://<host>/api/v1/trigger-sync` followed by `nickel_misc : force_sync`. - On KOReader (optional): A small Lua module extending `saya6k/kobosync.koplugin` (`main.lua`) to ping the same `/api/v1/trigger-sync` webhook prior to catalog sync. 4. **Docker Compose + Caddy (TLS):** - Kobo's stock sync client strictly requires valid HTTPS (`443`) and clean `X-Scheme: https` / `X-Forwarded-Proto: https` headers when downloading covers and KePubs from CWA. --- ## 3. MULTI-AGENT DISPATCH SPECIFICATION (DECEMBER 2026 FRONTIER ROSTER) If your harness supports sub-agent delegation (`Claude Code` subagents, `Codex CLI` multi-agent, or `OpenCode` model routing), dispatch each phase using the exact agent profile below. Keep active context well below each model's degradation/surcharge threshold via explicit handoff artifacts (`specs/*.md`). ### Agent Profile A — Lead Orchestrator & Final Integrator (Phases 0 & 5) - **Harness:** `Claude Code v2.1.310+` (with `AGENTS.md` / `CLAUDE.md` and `Claude Mods` safety hooks blocking credential leaks) - **Model & Version:** Anthropic **Claude Opus 5.5** (`claude-opus-5-5`, API version `2026-10-21`) - **Context & Output:** `1,000,000` token window (maintain `<=500K` active context; no long-context surcharge); `128,000` max output tokens; Extended Thinking enabled (`32,000` thinking token budget); `temperature=1.0` (required for thinking) - **Tools / MCP:** Filesystem, Docker CLI, Git, Pytest runner, Subagent spawner - **Strengths:** Best-in-class multi-step planning, cross-service debugging, root-cause verification before editing, and clean subagent orchestration. ### Agent Profile B — Multi-Repo Spec Extractor (Phase 0 Discovery) - **Harness:** `OpenCode` CLI or Google AI Studio / `Antigravity Agent` (`antigravity-preview-09-2026`) - **Model & Version:** Google **Gemini 4 Carbon** (`gemini-4-carbon`, `1,000,000` context, `64,000` output) — or **Gemini 3 Pro** (`10,000,000` context) if ingesting all 5 upstream git trees raw in one shot (compress output down to a `<30K`-token `specs/UPSTREAM_CONTRACTS.md` artifact to avoid >128K/200K long-context pricing on subsequent turns) - **Tools / MCP:** Read-only Git/Filesystem access across cloned upstream repos - **Strengths:** Cross-referencing Python, Java/Smali, SQLite schemas, and Lua simultaneously without RAG chunking blind spots. ### Agent Profile C — Reverse-Engineering, Frida Hook & TLS/Protocol Specialist (Phases 1 & 2) - **Harness:** `OpenAI Codex CLI` (Rust sandbox harness with shell + ADB/Frida container access) - **Model & Version:** OpenAI **GPT-6.2 Astra** (`gpt-6.2-astra`) - **Context & Output:** `1,050,000` token window (keep per-turn input `<=270K` tokens to stay below long-context billing multipliers and maximize recall); `128,000` max output tokens; `reasoning_effort="xhigh"` - **Co-Reviewer (Security/JNI Check):** Pass Frida hook diffs to **Gemini 4 Carbon** (`gemini-4-carbon`) for JNI/memory-safety verification - **Tools / MCP:** `adb`, `frida-ps` / `frida-compile`, `jadx` (read-only APK symbol verification), `pytest`, `curl` - **Strengths:** Deepest reasoning on obfuscated JNI/Java hook lifecycles, BoringSSL/JA4 TLS fingerprint parity, and binary `FionaCDEServiceEngine` sidecar parsing. ### Agent Profile D — Daemon, SQLite Sync, Kobo Client & Test-Matrix Builder (Phases 3 & 4) - **Harness:** `OpenCode` CLI or `Cline` - **Primary Model (Architecture & Stateful Logic):** OpenAI **GPT-6.2 Sol** (`gpt-6.2-sol`, `1,050,000` context, `128,000` max output, `reasoning_effort="high"`) or Anthropic **Claude Sonnet 5.5** (`claude-sonnet-5-5`, `1,000,000` context, `128,000` output) - **High-Output Model (Boilerplate, Fixtures, Docker & Full Test Suites):** **DeepSeek V4 Pro** (`deepseek-v4-pro`, `1,000,000` context, **`384,000` max output tokens**, `temperature=0.2`) - **Tools / MCP:** Python `uv`, `mypy`, `ruff`, `pytest`, `sqlite3`, `luacheck` / `busted` (for KOReader Lua specs) - **Strengths:** `gpt-6.2-sol` handles async FastAPI/SQLite concurrency cleanly; `deepseek-v4-pro`'s 384K output ceiling generates exhaustive mock KFX/CWA databases, Dockerfiles, and integration suites in a single pass without truncation. --- ## 4. PHASED IMPLEMENTATION PLAN & GO/NO-GO GATES Execute sequentially. Do not advance to Phase `N+1` until Phase `N`'s verification gate passes. ### Phase 0: Workspace Bootstrap & Upstream Contract Extraction - **Assigned Agents:** Agent A (Orchestrator) -> spawns Agent B (Spec Extractor) - **Tasks:** 1. Clone reference repos into `vendor/` (read-only submodules): - `mkb79/kindle` - `Satsuoni/DeDRM_tools` - `crocodilestick/Calibre-Web-Automated` - `saya6k/kobosync.koplugin` - `kaikozlov/kindle.koplugin` 2. Have Agent B produce `specs/UPSTREAM_CONTRACTS.md` documenting: - Exact `mkb79/kindle` registration, catalog, and `sidecar` Whispersync methods + payload shapes. - Exact Java/native symbols hooked by `kindleFridaDecrypt.py` and the CLI invocation for Calibre's `KFX Input` plugin. - Exact SQLite tables/columns in CWA's `app.db` (`kobo_reading_state`, `kobo_bookmark`, `kobo_statistics`) and Calibre's `metadata.db` (`identifiers` table where `type='amazon'` stores the ASIN). 3. Initialize `uv` Python 3.12 workspace (`kindle2kobo`), strict `mypy` + `ruff` config, and `sync_ledger.db` SQLite migrations. - **Go/No-Go Gate:** `specs/UPSTREAM_CONTRACTS.md` verified against actual source files in `vendor/`; `uv run pytest` and `uv run mypy --strict` pass on empty scaffold. ### Phase 1: Headless Android Donor & Frida KFX->EPUB Pipeline - **Assigned Agent:** Agent C (`gpt-6.2-astra` in `Codex CLI`) - **Tasks:** 1. Define an abstract `DonorBackend` Python protocol (`pull_and_decrypt(asin: str) -> Path`) with two implementations: - `AndroidFridaDonor` (Primary): Drives a headless `redroid` Android 14 container + `frida-server` over `adbutils`. Launches Kindle for Android via intent for the target `asin`, waits for local KFX download completion, attaches our `frida-compile`d TypeScript GumJS hook (adapted from `Satsuoni/DeDRM_tools/kindleFridaDecrypt.py`), and extracts decrypted KFX files. - `KindleSshDonor` (Optional fallback stub): Pulls via SSH from a jailbroken physical Kindle running `Satsuoni`'s `kfxdedrm` binary (`<=5.18.4`). 2. Build `converter.py`: Runs headless Calibre (`calibre-debug` + `KFX Input`) to convert the decrypted KFX bundle into a standard `.epub`, injecting `<dc:identifier opf:scheme="AMAZON">{asin}</dc:identifier>` via `ebook-meta` so CWA indexes the ASIN automatically, while preserving full-resolution color images/comics panels. 3. Add health checks that verify APK version compatibility before attaching Frida hooks (pinning a known-good Kindle APK version and blocking auto-updates inside the container). - **Go/No-Go Gate:** Given a test purchased DRM book (including at least one illustrated/color title), `uv run kindle2kobo decrypt --asin <ASIN>` outputs a valid DRM-free `.epub` that passes `epubcheck` and preserves color images. ### Phase 2: Hardened Amazon Catalog Poller & Whispersync Client - **Assigned Agent:** Agent C (`gpt-6.2-astra` in `Codex CLI`) - **Tasks:** 1. Wrap `mkb79/kindle` in `amazon_client.py`, replacing `requests`/`httpx` calls with `curl_cffi.requests.AsyncSession(impersonate="chro me124")` (or Android WebView TLS profile) and exponential backoff + jitter. 2. Implement `catalog_poller.py`: Authenticates using stored refresh tokens (never storing plaintext Amazon passwords), fetches owned eBooks (filtering out unsupported Kindle Unlimited loans unless explicitly flagged), diffs against `sync_ledger.db`, and enqueues newly discovered ASINs for Phase 1 decryption. 3. Implement `whispersync_client.py`: Reads and writes `FionaCDEServiceEngine/sidecar` reading positions and converts between Kindle position/percentage metrics and normalized `[0.0..100.0]` progress + UTC timestamps. - **Go/No-Go Gate:** Unit + recorded-cassette (`vcrpy`) tests verify token refresh, new-ASIN detection, TLS header/fingerprint sanity, and lossless round-trip parsing of real Whispersync sidecar payloads. ### Phase 3: `Calibre-Web-Automated` Stack & Zero-Touch Kobo Sync Setup - **Assigned Agent:** Agent D (`gpt-6.2-sol` + `deepseek-v4-pro` in `OpenCode`) - **Tasks:** 1. Create `docker-compose.yml` orchestrating `cwa` (`crocodilestick/calibre-web-automated`), `redroid` (Android donor), `kindle2kobo-daemon`, and `caddy` (automatic HTTPS via Tailscale certs or Let's Encrypt). 2. Configure Caddy to forward `X-Scheme: https` and `X-Forwarded-Proto: https` (required so CWA generates `https://` cover and KePub download URLs for Kobo). 3. Write an idempotent `cwa_bootstrap.py` configurator that pre-configures CWA's `app.db` to avoid known Kobo Sync pitfalls: - Enables `config_kobo_sync = 1` and `config_kobo_proxy = 1` ("Proxy unknown requests to Kobo Store"). - Sets `config_external_port = 443`. - **CRITICAL:** Disables `"Embed Metadata to Ebook File on Download/Conversion"` (`config_embed_metadata = 0`), which is known to corrupt `kepubify` output and cause selective Kobo sync failures. - Ensures the target CWA user has `Allow Downloads` enabled and generates/prints their `/kobo/{auth_token}` URL. 4. Wire `ingest_watcher.py` to move Phase 1 `.epub` outputs into `/cwa-book-ingest`, wait for CWA to import and generate the `.kepub.epub`, and record the `asin <-> calibre_book_id <-> kobo_uuid` mapping in `sync_ledger.db`. - **Go/No-Go Gate:** Dropping a Phase 1 `.epub` into ingest results in CWA exposing a valid `https://.../kobo/{token}/v1/library/sync` JSON response containing a downloadable KePub and working cover image URLs. ### Phase 4: Bidirectional Whispersync <-> Kobo Progress Bridge - **Assigned Agent:** Agent D (`gpt-6.2-sol` + `deepseek-v4-pro` in `OpenCode`) - **Tasks:** 1. Build `progress_bridge.py` inside `kindle2kobo-daemon`: - Polls CWA's `app.db` (`kobo_reading_state` + `kobo_bookmark` tables, updated whenever stock Kobo Nickel or KOReader `kobosync.koplugin` syncs) and compares `last_modified` + `percent_read` against `whispersync_client.py` and `sync_ledger.db`. 2. Implement `kaikozlov/kindle.koplugin`-inspired directional conflict resolution: - Configurable per direction (`kobo_to_kindle` and `kindle_to_kobo`: `always_newest`, `forward_only`, or `disabled`). - Include a `2.0%` deadband threshold so minor pagination/span rounding differences between Kobo KePub spans and Kindle KFX locations never trigger infinite ping-pong sync loops. 3. Expose a lightweight FastAPI control API: - `POST /api/v1/trigger-sync` (wakes `catalog_poller` + `progress_bridge` immediately). - `GET /api/v1/status` (JSON health summary of donor container, Frida hook state, queued books, and last sync timestamps). - **Go/No-Go Gate:** Simulated matrix tests (`pytest`) covering 8 conflict scenarios (Kobo ahead, Kindle ahead, offline reconnect, clock skew, <2% deadband, finished-book status, unmapped book, revoked token) pass with 100% deterministic state transitions. ### Phase 5: Kobo On-Device Helpers & End-to-End Integration - **Assigned Agent:** Agent A (`claude-opus-5-5` in `Claude Code`) - **Tasks:** 1. Build `tools/provision_kobo.py` (run once when Kobo is plugged in via USB): - Safely backs up `.kobo/Kobo/Kobo eReader.conf`, updates `api_endpoint=https://<host>/kobo/<token>` under `[OneStoreServices]`, and optionally installs a 6-line `NickelMenu` file (`.adds/nm/kindle2kobo`) adding a **"Sync Kindle Library"** button to Kobo's stock menu (`cmd_spawn : quiet : wget -qO- --header="Authorization: Bearer <token>" https://<host>/api/v1/trigger-sync` + `nickel_misc : force_sync`). 2. Provide an optional patch/companion Lua snippet (`koreader-addon/kindle2kobo_trigger.lua`) compatible with `saya6k/kobosync.koplugin` so KOReader users can also trigger upstream Kindle pulls before `kobosync` runs. 3. Write `README.md` and `OPERATIONS.md` covering one-time Kindle APK login inside `redroid` (via `scrcpy` or web VNC), APK version pinning, and Tailscale Funnel / reverse-proxy setup for Kobo Wi-Fi access. - **Go/No-Go Gate:** Full end-to-end smoke test passes—buying a DRM-locked Kindle book -> `POST /api/v1/trigger-sync` -> decrypted & converted to KePub -> Kobo syncs over Wi-Fi into stock Nickel UI with crisp Kaleido 3 / FastGLR page turns and bidirectional reading percentage sync. --- ## 5. IMMEDIATE EXECUTION INSTRUCTIONS FOR THIS SESSION Start now with **Phase 0**: 1. Inspect the workspace directory and create the repository layout: ~~~text kindle2kobo/ ├── AGENTS.md ├── docker-compose.yml ├── Caddyfile ├── specs/ ├── vendor/ ├── frida-agent/ # TypeScript -> GumJS hooks ├── src/kindle2kobo/ # Python 3.12+ daemon, donor, sync, CLI ├── kobo-client/ # NickelMenu config + optional KOReader Lua hook │ ├── nickelmenu/ │ └── koreader/ ├── tools/ # provision_kobo.py & donor APK pinning scripts └── tests/ ~~~ 2. Clone or fetch the 5 upstream reference repositories into `vendor/` (or inspect them via git/web tools if shallow-cloning). 3. Produce `specs/UPSTREAM_CONTRACTS.md` and `pyproject.toml`, then pause and report your Phase 0 Go/No-Go verification summary before proceeding to Phase 1. |
|
|
|
|
|
#2 |
|
Junior Member
![]() Posts: 4
Karma: 10
Join Date: Dec 2026
Device: kobo clara color
|
If anyone does want to do this, they should install my AI kobo skill first:
https://www.mobileread.com/forums/sh...d.php?t=376599 |
|
|
|
|
|
#3 |
|
Weirdo
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() Posts: 1,459
Karma: 13580110
Join Date: Nov 2019
Location: Wuppertal, Germany
Device: Kobo Clara BW, Tolino Shine Color, Kindle 2026, reMarkable PaperPro
|
So you wanted to create an app that downloads Kindle books and uses sync with CWA?
A short abstract would have been useful. |
|
|
|
![]() |
| Tags |
| drm, drm kindle, kindle, kobo, linux |
| Thread Tools | Search this Thread |
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Reliable Linux e-ink e-book reader | bwocaek | Which one should I buy? | 10 | 07-30-2021 06:39 PM |
| Free (Kindle DRM-free) Naming Ceremonies [LGBT Native ID Literary Stories & Essays] | ATDrake | Deals and Resources (No Self-Promotion or Affiliate Links) | 1 | 04-28-2016 02:23 PM |
| Aura HD Kobo Reader and Bookstore for non-drm or drm-removable books? | jayk | Kobo Reader | 33 | 03-19-2015 09:32 PM |
| Flash original Amazon firmware to a Kindle (in native Linux, without Kubrick) | Synthead | Kindle Developer's Corner | 5 | 07-15-2013 03:45 PM |
| LInux Journal Survey: Do you own an e-book reader? | Steven Lake | General Discussions | 10 | 11-28-2010 11:58 PM |