Modern Apps git

← Modern-Apps.git

shop: route all merchant traffic via maproj.org proxy

Commit
71d007cc3a7d836f341d9880f25f0470559c3d19
Author
vayun-mathur <[email protected]>
When
2026-10-28 18:18 UTC (1 month ago)
Parents
83d45e7

Diff

shop/AGENTS.md
diff --git a/shop/AGENTS.md b/shop/AGENTS.mdindex a3b304f9d8..e86892dc43 100644--- a/shop/AGENTS.md+++ b/shop/AGENTS.md@@ -5,14 +5,11 @@ Package roots: ui, data, domain, platform, network. Entry types: MainActivity, Route, Navigation. Navigation remains a root-only graph.  ## Behavior-- Anonymous catalog and checkout preparation using supported UCP 2026-08-25 and 2026-04-08 profiles.-- Select one complete advertised profile and exact capability/service versions; do not merge releases.-- Merchant services must advertise a supported REST or MCP binding and a public HTTPS endpoint.-- Empty merchant input uses Shopify Global Catalog subject to its access policy; manual merchant input remains supported.-- The Merchants tab explicitly loads the public UCPList directory. Cache/filter locally and validate live discovery on selection.-- Directory status labels are informational leads, never access grants or independently verified integrations.-- MCP handles negotiated sessions and bounded JSON/SSE responses; unsafe endpoints and redirects are rejected.-- REST uses the selected dated operation schema and app-owned platform identity, not MCP wrapper bodies.+- All merchant traffic goes through the first-party proxy (`api.maproj.org/shop/v1/*`); the device never speaks UCP directly and never fetches merchant hosts (product images arrive as proxied `/shop/v1/image?url=` URLs).+- The `network/` package holds only the thin `ShopBackend` interface + DTOs over `library:network`. Dated discovery, REST/MCP transport, versioning, SSRF guards, wire limits, and the idempotency ledger live server-side.+- Anonymous catalog and checkout preparation using supported UCP 2026-08-25 and 2026-04-08 profiles, resolved server-side. The server selects one complete advertised profile and exact capability/service versions; it never merges releases.+- Server error codes mirror the former client `UcpError` (`transport | rate_limited | http | malformed | rpc | unsupported | uncertain`, plus `retryAfterMs`): `unsupported` routes to the merchant website, anything else on a write is uncertain and never auto-retried on either side.+- The Merchants tab loads the directory through the proxy. Cache/filter locally; the server validates on first use. - Buyer/fulfillment review is ephemeral. Merchant totals and legal links are authoritative. - Checkout writes require explicit user action and a stable idempotency key per intent. Never replay an uncertain mutation automatically. - Preserve cart lines through partial failures and browser handoffs. A session or browser return is not a paid order.@@ -25,7 +22,7 @@ Entry types: MainActivity, Route, Navigation. Navigation remains a root-only gra - Await AppInit readiness before network operations so the standard trust bundle is initialized.  ## Responsibilities-- Network adapters own dated discovery, REST/MCP transport, error envelopes and merchant directory parsing.+- `ShopBackend` owns the four server calls (search/product/checkout/merchants) plus error-envelope mapping. It never talks to merchant hosts. - ShopViewModel owns explicit cart and per-merchant native-review state. Buyer PII must never enter logs or persisted history. - Local stores retain pending checkout records for browser recovery, not order confirmations. - UI uses shared app scaffolds and controls; one public composable per file. Metadata previews are class members with PreviewTest and Preview.@@ -34,5 +31,5 @@ Entry types: MainActivity, Route, Navigation. Navigation remains a root-only gra Run scoped Shop compilation, unit tests, lint and metadata rendering. If shared networking changes, run its focused tests and lint too. Use fake transports/fixtures for checkout writes and stream lifecycle tests. No live checkout creation/update/completion or order-read checks without an authorized sandbox. -The sibling server hosts app-owned platform identities at https://maproj.org/.well-known/ucp?version=2026-08-25 and the April equivalent. The original profile URL and pinned routes remain available. Validate both profiles against dated official platform schemas and deploy aliases before exercising the updated client identity.+The sibling server proxies all merchant traffic at https://api.maproj.org/shop/v1/* (search, product, checkout-sessions, merchants, image). The app-owned UCP platform identities remain at https://maproj.org/.well-known/ucp?version=2026-08-25 and the April equivalent; the server presents them to merchants on the app's behalf. Never borrow a third party's profile, infer permissions from platform labels, or assert that every directory entry interoperates.
shop/src/main/java/com/vayunmathur/shop/data/UcpModels.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/data/UcpModels.kt b/shop/src/main/java/com/vayunmathur/shop/data/UcpModels.ktindex fcd8d1467c..dc73ee6b88 100644--- a/shop/src/main/java/com/vayunmathur/shop/data/UcpModels.kt+++ b/shop/src/main/java/com/vayunmathur/shop/data/UcpModels.kt@@ -70,6 +70,10 @@ data class UcpTotalEntry(val type: String, val label: String, val money: Money) @Serializable data class UcpMessage(val type: String = "", val text: String = "", val path: String? = null, val code: String? = null, val severity: String? = null) +/** Server-echoed cart fingerprint: the variant ids + quantities the proxy sent to the merchant. */+@Serializable+data class SubmittedLine(val variantId: String = "", val quantity: Int = 0)+ @Serializable data class UcpCheckout(     val checkoutId: String = "",@@ -84,6 +88,7 @@ data class UcpCheckout(     @Transient val review: CheckoutReview = CheckoutReview(),     // Session-only source for exact writable projections. Never serialize buyer-bearing responses.     @Transient internal val writableSource: JsonObject? = null,+    val submittedLines: List<SubmittedLine> = emptyList(), ) {     override fun toString(): String = "UcpCheckout(redacted)" }
shop/src/main/java/com/vayunmathur/shop/domain/CheckoutProjection.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/domain/CheckoutProjection.kt b/shop/src/main/java/com/vayunmathur/shop/domain/CheckoutProjection.ktdeleted file mode 100644index db4fd49352..0000000000--- a/shop/src/main/java/com/vayunmathur/shop/domain/CheckoutProjection.kt+++ /dev/null@@ -1,123 +0,0 @@-package com.vayunmathur.shop.domain--import com.vayunmathur.shop.data.CartLine-import com.vayunmathur.shop.data.CheckoutInputs-import com.vayunmathur.shop.data.UcpCheckout-import kotlinx.serialization.json.*--/** Explicit projections verified against the official dated checkout/fulfillment schemas. */-internal object CheckoutProjection {-    val versions = setOf("2026-08-25", "2026-04-08")--    fun checkout(version: String, lines: List<CartLine>, inputs: CheckoutInputs, previous: UcpCheckout?, fulfillment: Boolean): JsonObject {-        require(version in versions)-        require(inputs.validationError() == null)-        require(lines.isNotEmpty() && lines.all { it.quantity in 1..99 })-        val sourceLines = previous?.writableSource?.get("line_items") as? JsonArray-        if (previous != null) require(sourceLines != null) { "Missing authoritative line items" }-        val projectedLines = if (previous == null) lines.map { line -> buildJsonObject {-            putJsonObject("item") {-                put("id", line.variantId)-                if (version == "2026-08-25") putJsonObject("quantity_unit") { put("unit", "C62"); put("scale", 0) }-            }-            put("quantity", line.quantity)-        } } else {-            require(sourceLines!!.size == lines.size) { "Checkout line items changed" }-            require(sourceLines.map { it.jsonObject["item"]!!.jsonObject["id"]!!.jsonPrimitive.content }.sorted() == lines.map { it.variantId }.sorted()) { "Checkout item identities changed" }-            val authoritativeIds = sourceLines.map { it.jsonObject["id"]!!.jsonPrimitive.content }-            require(authoritativeIds.all { it.isNotBlank() } && authoritativeIds.distinct().size == authoritativeIds.size) { "Invalid merchant line IDs" }-            sourceLines.map { element ->-                val remote = element.jsonObject-                val item = remote["item"]!!.jsonObject-                val id = item["id"]!!.jsonPrimitive.content-                val local = lines.single { it.variantId == id }-                require(remote["quantity"]?.jsonPrimitive?.intOrNull == local.quantity) { "Checkout quantity changed" }-                val unit = item["quantity_unit"] as? JsonObject-                require(unit == null || (unit["unit"]?.jsonPrimitive?.content == "C62" && unit["scale"]?.jsonPrimitive?.intOrNull == 0)) { "Unsupported quantity basis" }-                buildJsonObject {-                    put("id", remote["id"] ?: error("Missing merchant line ID"))-                    putJsonObject("item") {-                        put("id", id)-                        if (version == "2026-08-25") putJsonObject("quantity_unit") { put("unit", "C62"); put("scale", 0) }-                    }-                    put("quantity", local.quantity)-                    remote["parent_id"]?.let { put("parent_id", it) }-                }-            }-        }-        return buildJsonObject {-            put("line_items", JsonArray(projectedLines))-            putJsonObject("buyer") {-                if (previous != null || inputs.firstName.isNotBlank()) put("first_name", inputs.firstName)-                if (previous != null || inputs.lastName.isNotBlank()) put("last_name", inputs.lastName)-                if (previous != null || inputs.email.isNotBlank()) put("email", inputs.email)-                if (previous != null || inputs.phone.isNotBlank()) put("phone_number", inputs.phone)-            }-            if (fulfillment && (inputs.hasAddress || inputs.options.isNotEmpty())) {-                val responseFulfillment = previous?.writableSource?.get("fulfillment") as? JsonObject-                val responseMethods = responseFulfillment?.get("methods") as? JsonArray-                val methods = if (!responseMethods.isNullOrEmpty()) responseMethods else {-                    require(previous != null && inputs.shippingRequested && inputs.hasAddress) { "First create a session to obtain merchant shipping choices" }-                    val hints = (responseFulfillment?.get("available_methods") as? JsonArray).orEmpty().map { it.jsonObject }.filter { it["type"]?.jsonPrimitive?.content == "shipping" }-                    val ids = hints.flatMap { it["line_item_ids"]!!.jsonArray }.distinct()-                    require(ids.isNotEmpty()) { "Merchant did not advertise shipping" }-                    // Update permits creating a method without an ID. Merchant assigns it; hints supply exact line IDs.-                    JsonArray(listOf(buildJsonObject { put("type", "shipping"); put("line_item_ids", JsonArray(ids)) }))-                }-                val knownKeys = methods.flatMap { method ->-                    val methodId = method.jsonObject["id"]?.jsonPrimitive?.content-                    (method.jsonObject["groups"] as? JsonArray).orEmpty().map { "$methodId/${it.jsonObject["id"]!!.jsonPrimitive.content}" }-                }.toSet()-                require(inputs.options.keys.all { it in knownKeys }) { "Unknown shipping group" }-                putJsonObject("fulfillment") {-                    put("methods", JsonArray(methods.map { element ->-                        val method = element.jsonObject-                        require(method["type"]?.jsonPrimitive?.content == "shipping") { "Unsupported fulfillment" }-                        val methodId = method["id"]?.jsonPrimitive?.content-                        require(methodId == null && responseMethods.isNullOrEmpty() || !methodId.isNullOrBlank())-                        if (version == "2026-08-25") require((method["destinations"] as? JsonArray).orEmpty().all { it.jsonObject["type"]?.jsonPrimitive?.content == "shipping_address" }) { "Unsupported shipping destination" }-                        val methodLines = method["line_item_ids"]!!.jsonArray.map { it.jsonPrimitive.content }-                        val checkoutIds = sourceLines!!.map { it.jsonObject["id"]!!.jsonPrimitive.content }.toSet()-                        require(methodLines.isNotEmpty() && methodLines.all { it in checkoutIds }) { "Stale fulfillment lines" }-                        buildJsonObject {-                            methodId?.let { put("id", it) }-                            put("type", "shipping")-                            put("line_item_ids", method["line_item_ids"] ?: error("Missing fulfillment lines"))-                            if (inputs.hasAddress) {-                                val destinations = method["destinations"] as? JsonArray-                                val selectedId = (method["selected_destination_id"] as? JsonPrimitive)?.contentOrNull-                                val destination = destinations?.map { it.jsonObject }?.firstOrNull { it["id"]?.jsonPrimitive?.content == selectedId }-                                    ?: destinations?.firstOrNull()?.jsonObject-                                val destinationId = destination?.get("id")-                                putJsonArray("destinations") { add(buildJsonObject {-                                    destinationId?.let { put("id", it) }-                                    if (version == "2026-08-25") put("type", "shipping_address")-                                    put("first_name", inputs.firstName); put("last_name", inputs.lastName); put("phone_number", inputs.phone)-                                    put("street_address", inputs.street); put("extended_address", inputs.extendedAddress)-                                    put("address_locality", inputs.city); put("address_region", inputs.region)-                                    put("address_country", inputs.country); put("postal_code", inputs.postalCode)-                                }) }-                                // An authored address can omit its ID; only select IDs actually issued by the merchant.-                                destinationId?.let { put("selected_destination_id", it) }-                            } else method["selected_destination_id"]?.let { put("selected_destination_id", it) }-                            val groups = method["groups"] as? JsonArray ?: JsonArray(emptyList())-                            put("groups", JsonArray(groups.map { groupElement ->-                                val group = groupElement.jsonObject-                                val groupId = group["id"]!!.jsonPrimitive.content-                                require(groupId.isNotBlank())-                                require(group["line_item_ids"]!!.jsonArray.all { it.jsonPrimitive.content in methodLines }) { "Stale fulfillment group" }-                                val selected = inputs.options["$methodId/$groupId"]-                                if (selected != null) require((group["options"] as? JsonArray)?.any { it.jsonObject["id"]?.jsonPrimitive?.content == selected } == true) { "Unknown shipping option" }-                                buildJsonObject {-                                    put("id", groupId)-                                    if (selected != null) put("selected_option_id", selected)-                                    else group["selected_option_id"]?.let { put("selected_option_id", it) }-                                }-                            }))-                        }-                    }))-                }-            } else require(!inputs.hasAddress && inputs.options.isEmpty()) { "Merchant shipping must be supported before submitting an address" }-        }-    }-}
shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.kt b/shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.ktindex 205aaa7dbe..062d54a5e2 100644--- a/shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.kt+++ b/shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.kt@@ -1,10 +1,9 @@ package com.vayunmathur.shop.domain  import com.vayunmathur.shop.data.*-import com.vayunmathur.shop.network.UcpCheckoutApi-import com.vayunmathur.shop.network.UcpDiscovery-import com.vayunmathur.shop.network.UcpHttpException-import com.vayunmathur.shop.network.UcpService+import com.vayunmathur.shop.network.ShopBackend+import com.vayunmathur.shop.network.ShopBackendException+import com.vayunmathur.shop.network.ShopHttpBackend import kotlinx.coroutines.CancellationException import kotlinx.coroutines.sync.Mutex import java.time.Instant@@ -12,29 +11,33 @@ import java.util.UUID  /** Deliberately has no completion operation. Tests never need a merchant or payment credentials. */ internal interface NativeCheckoutGateway {-    suspend fun resolve(shop: String, version: String? = null): Result<UcpService>-    suspend fun mutate(service: UcpService, lines: List<CartLine>, inputs: CheckoutInputs, previous: UcpCheckout?, intent: String): Result<UcpCheckout>-    suspend fun get(service: UcpService, id: String): Result<UcpCheckout>+    suspend fun create(shop: String, lines: List<CartLine>, inputs: CheckoutInputs, intent: String): Result<UcpCheckout>+    suspend fun update(shop: String, sessionId: String, lines: List<CartLine>, inputs: CheckoutInputs, intent: String): Result<UcpCheckout>+    suspend fun get(shop: String, sessionId: String): Result<UcpCheckout> } -internal object MerchantCheckoutGateway : NativeCheckoutGateway {-    override suspend fun resolve(shop: String, version: String?): Result<UcpService> = UcpDiscovery.resolve(shop, "dev.ucp.shopping.checkout", version)-    override suspend fun mutate(service: UcpService, lines: List<CartLine>, inputs: CheckoutInputs, previous: UcpCheckout?, intent: String): Result<UcpCheckout> = UcpCheckoutApi.mutate(service, lines, inputs, previous, intent)-    override suspend fun get(service: UcpService, id: String): Result<UcpCheckout> = UcpCheckoutApi.getCheckout(service, id)+internal class ServerCheckoutGateway(+    private val backend: ShopBackend = ShopHttpBackend,+) : NativeCheckoutGateway {+    override suspend fun create(shop: String, lines: List<CartLine>, inputs: CheckoutInputs, intent: String): Result<UcpCheckout> =+        backend.createCheckout(shop, lines, inputs, intent)+    override suspend fun update(shop: String, sessionId: String, lines: List<CartLine>, inputs: CheckoutInputs, intent: String): Result<UcpCheckout> =+        backend.updateCheckout(shop, sessionId, lines, inputs, intent)+    override suspend fun get(shop: String, sessionId: String): Result<UcpCheckout> =+        backend.getCheckout(shop, sessionId) }  internal fun interface PendingCheckoutSink { suspend fun save(order: PlacedOrder) }  /** Single-owner ephemeral state; mutex guards each merchant against overlapping writes and reads. */ internal class NativeCheckoutCoordinator(-    private val gateway: NativeCheckoutGateway = MerchantCheckoutGateway,+    private val gateway: NativeCheckoutGateway = ServerCheckoutGateway(),     private val now: () -> Long = System::currentTimeMillis,     private val newIntent: () -> String = { UUID.randomUUID().toString() },     private val changed: (List<NativeCheckoutState>) -> Unit = {}, ) {     private val states = linkedMapOf<Pair<String, String>, NativeCheckoutState>()     private val locks = mutableMapOf<Pair<String, String>, Mutex>()-    private val services = mutableMapOf<Pair<String, String>, UcpService>()     private val createdAt = mutableMapOf<Pair<String, String>, Long>()     val snapshot: List<NativeCheckoutState> get() = states.values.toList() @@ -89,31 +92,26 @@ internal class NativeCheckoutCoordinator(                 publish(key, state.copy(phase = CheckoutPhase.BrowserRequired, message = "Removing a submitted shipping address requires the merchant website.")); return             }             publish(key, state.copy(phase = if (previous == null) CheckoutPhase.Preparing else CheckoutPhase.Updating, message = null))-            val service = services[key] ?: gateway.resolve(shop, previous?.version).getOrElse {-                publish(key, state.copy(phase = CheckoutPhase.Error, message = "Merchant checkout discovery failed. Use the merchant website.")); return-            }.also { services[key] = it }-            if (service.version !in CheckoutProjection.versions || service.transport !in setOf("rest", "mcp")) {-                publish(key, state.copy(phase = CheckoutPhase.BrowserRequired, message = "This merchant's checkout version or transport requires its website.")); return-            }-            // Validate everything before handing a write to the transport. No ambiguous failures are retried.+            // The server builds the exact dated projection and owns the idempotency+            // ledger: a write is attempted exactly once and never auto-retried.             val sentInputs = if (previous == null) state.inputs.copy(street = "", extendedAddress = "", city = "", region = "", country = "", postalCode = "", options = emptyMap(), shippingRequested = false) else state.inputs-            val projection = runCatching { CheckoutProjection.checkout(service.version, lines, sentInputs, previous, "dev.ucp.shopping.fulfillment" in service.capabilities) }-            if (projection.isFailure) {-                publish(key, state.copy(phase = CheckoutPhase.BrowserRequired, message = "The merchant's writable checkout requirements are unsupported. Use its website.")); return-            }             val intent = newIntent()             mutationStarted = true-            val checkout = gateway.mutate(service, lines.toList(), sentInputs, previous, intent).getOrElse {-                val unsupported = (it as? UcpHttpException)?.error is UcpError.Unsupported+            val checkout = (if (previous == null) gateway.create(shop, lines.toList(), sentInputs, intent)+                else gateway.update(shop, previous.checkoutId, lines.toList(), sentInputs, intent)).getOrElse {+                val unsupported = (it as? ShopBackendException)?.error is UcpError.Unsupported                 publish(key, state.copy(phase = if (unsupported) CheckoutPhase.BrowserRequired else CheckoutPhase.Uncertain,                     message = if (unsupported) "These requirements need the merchant website." else "The request may have reached the merchant. Do not retry; check the session or use its website."))                 return             }-            if (previous != null && checkout.checkoutId != previous.checkoutId || checkout.version != service.version) {+            if (previous != null && checkout.checkoutId != previous.checkoutId) {                 publish(key, state.copy(phase = CheckoutPhase.Uncertain, message = "The merchant returned a different session. Do not retry.")); return             }             createdAt.putIfAbsent(key, now())-            val responseMatchesCart = runCatching { CheckoutProjection.checkout(service.version, lines, sentInputs, checkout, "dev.ucp.shopping.fulfillment" in service.capabilities) }.isSuccess+            val responseMatchesCart = checkout.submittedLines.size == lines.size &&+                checkout.submittedLines.all { submitted ->+                    lines.any { it.variantId == submitted.variantId && it.quantity == submitted.quantity }+                }             val reason = checkout.review.browserOnlyReason ?: if (!responseMatchesCart) "The merchant returned changed or unsupported line items. Review them on its website." else null             val next = state.copy(checkout = checkout, submittedInputs = sentInputs, submittedLines = lines.toList(),                 phase = if (expired(key, checkout)) CheckoutPhase.Expired else if (reason != null) CheckoutPhase.BrowserRequired else CheckoutPhase.Reviewing,@@ -140,11 +138,13 @@ internal class NativeCheckoutCoordinator(         try {             val state = states[key] ?: return             val checkout = state.checkout ?: return-            val service = services[key] ?: return-            val refreshed = gateway.get(service, checkout.checkoutId).getOrNull() ?: return-            if (refreshed.checkoutId != checkout.checkoutId || refreshed.version != checkout.version) return+            val refreshed = gateway.get(shop, checkout.checkoutId).getOrNull() ?: return+            if (refreshed.checkoutId != checkout.checkoutId) return             // A GET can show authoritative review but cannot prove that an uncertain write was applied.-            val responseMatchesCart = runCatching { CheckoutProjection.checkout(service.version, state.submittedLines, state.submittedInputs ?: CheckoutInputs(), refreshed, "dev.ucp.shopping.fulfillment" in service.capabilities) }.isSuccess+            val responseMatchesCart = refreshed.submittedLines.isEmpty() || (refreshed.submittedLines.size == state.submittedLines.size &&+                refreshed.submittedLines.all { submitted ->+                    state.submittedLines.any { it.variantId == submitted.variantId && it.quantity == submitted.quantity }+                })             val browserReason = refreshed.review.browserOnlyReason ?: if (!responseMatchesCart) "The merchant session's line items changed. Continue on its website." else null             publish(key, state.copy(checkout = refreshed,                 phase = if (state.phase == CheckoutPhase.Uncertain) CheckoutPhase.Uncertain else if (browserReason != null) CheckoutPhase.BrowserRequired else state.phase,
shop/src/main/java/com/vayunmathur/shop/network/JsonParse.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/network/JsonParse.kt b/shop/src/main/java/com/vayunmathur/shop/network/JsonParse.ktdeleted file mode 100644index 486dd18dcf..0000000000--- a/shop/src/main/java/com/vayunmathur/shop/network/JsonParse.kt+++ /dev/null@@ -1,40 +0,0 @@-package com.vayunmathur.shop.network--import kotlinx.serialization.json.JsonArray-import kotlinx.serialization.json.JsonElement-import kotlinx.serialization.json.JsonObject-import kotlinx.serialization.json.JsonPrimitive--/**- * Nullable JSON navigation helpers. This repo's kotlinx.serialization predates the- * `jsonObjectOrNull` / `jsonArrayOrNull` / `jsonPrimitiveOrNull` extensions, so- * dynamic UCP payloads (vendor extensions vary per platform) navigate via `as?`- * casts here instead of throwing accessors.- */-internal fun JsonObject.field(key: String): JsonElement? = this[key]--internal fun JsonElement?.asObject(): JsonObject? = this as? JsonObject--internal fun JsonElement?.asArray(): JsonArray? = this as? JsonArray--internal fun JsonElement?.asPrimitive(): JsonPrimitive? = this as? JsonPrimitive--internal fun JsonObject.text(key: String): String? =-    (this[key] as? JsonPrimitive)?.let { runCatching { it.content }.getOrNull() }--internal fun JsonObject.flag(key: String): Boolean? =-    (this[key] as? JsonPrimitive)?.let { runCatching { it.content }.getOrNull() }-        ?.let { it == "true" }--internal fun JsonObject.money(key: String): Long? =-    (this[key] as? JsonPrimitive)?.let {-        runCatching { it.content.toLong() }.getOrNull()-            ?: runCatching { it.content.toDouble().toLong() }.getOrNull()-    }--/** UCP truthiness: JSON true or the string "true" (some stores encode flags as strings). */-internal fun JsonElement?.isTruthy(): Boolean? {-    val text = (this as? JsonPrimitive)?.let { runCatching { it.content }.getOrNull() }-        ?: return null-    return text == "true"-}
shop/src/main/java/com/vayunmathur/shop/network/MerchantDirectoryApi.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/network/MerchantDirectoryApi.kt b/shop/src/main/java/com/vayunmathur/shop/network/MerchantDirectoryApi.ktdeleted file mode 100644index 152d2b2bf3..0000000000--- a/shop/src/main/java/com/vayunmathur/shop/network/MerchantDirectoryApi.kt+++ /dev/null@@ -1,120 +0,0 @@-package com.vayunmathur.shop.network--import com.vayunmathur.library.network.NetworkClient-import com.vayunmathur.library.network.RawResponse-import com.vayunmathur.shop.data.MerchantListing-import com.vayunmathur.shop.data.UcpError-import com.vayunmathur.shop.domain.MerchantUrls-import kotlinx.coroutines.CancellationException-import kotlinx.coroutines.TimeoutCancellationException-import kotlinx.coroutines.currentCoroutineContext-import kotlinx.coroutines.ensureActive-import kotlinx.coroutines.sync.Mutex-import kotlinx.coroutines.sync.withLock-import kotlinx.coroutines.withTimeout-import kotlinx.serialization.json.Json-import kotlinx.serialization.json.JsonArray-import java.io.ByteArrayOutputStream-import java.net.URI--internal object MerchantDirectoryApi {-    private val repository = MerchantDirectoryRepository()-    suspend fun load(force: Boolean = false): Result<List<MerchantListing>> = repository.load(force)-}--internal class MerchantDirectoryRepository(-    private val request: suspend () -> RawResponse = {-        val bytes = ByteArrayOutputStream()-        val response = NetworkClient.stream(-            "https://ucplist.ai/api/listings?category=merchants",-            headers = mapOf("Accept" to "application/json"),-            followRedirects = false,-            connectTimeoutMs = 10_000,-            readTimeoutMs = 10_000,-        ) { stream, response ->-            require(response.contentLength == null || response.contentLength!! <= MAX_BYTES) { "Directory response is too large" }-            if (stream == null) {-                bytes.write(response.body.toByteArray())-            } else {-                val buffer = ByteArray(8192)-                while (true) {-                    val count = stream.read(buffer)-                    if (count < 0) break-                    currentCoroutineContext().ensureActive()-                    require(bytes.size() + count <= MAX_BYTES) { "Directory response is too large" }-                    bytes.write(buffer, 0, count)-                }-            }-        }-        RawResponse(response.status, response.statusMessage, bytes.toByteArray(), response.headers, response.url)-    },-    private val clock: () -> Long = System::currentTimeMillis,-) {-    private val mutex = Mutex()-    private var cached: List<MerchantListing>? = null-    private var fetchedAt = 0L-    private var refreshAt = 0L--    suspend fun load(force: Boolean = false): Result<List<MerchantListing>> = mutex.withLock {-        val now = clock()-        cached?.takeIf { !force && now - fetchedAt in 0 until 86_400_000 }?.let {-            return@withLock Result.success(it)-        }-        if (now < refreshAt) {-            return@withLock Result.failure(UcpHttpException(UcpError.RateLimited(refreshAt - now)))-        }-        refreshAt = now + 60_000-        try {-            val response = withTimeout(15_000) { request() }-            if (response.status == 429) {-                val seconds = response.header("Retry-After")?.toLongOrNull()?.coerceIn(60, 86_400) ?: 60-                refreshAt = clock() + seconds * 1000-                return@withLock Result.failure(UcpHttpException(UcpError.RateLimited(seconds * 1000)))-            }-            if (!response.isSuccess) {-                return@withLock Result.failure(UcpHttpException(UcpError.Http(response.status, "")))-            }-            require(response.bytes.size <= MAX_BYTES) { "Directory response is too large" }-            val listings = parseListings(response.text)-            cached = listings-            fetchedAt = clock()-            Result.success(listings)-        } catch (_: TimeoutCancellationException) {-            currentCoroutineContext().ensureActive()-            Result.failure(UcpHttpException(UcpError.Transport("Merchant directory timed out")))-        } catch (cancelled: CancellationException) {-            throw cancelled-        } catch (error: Exception) {-            Result.failure(error)-        }-    }--    companion object {-        private const val MAX_BYTES = 2 * 1024 * 1024--        internal fun parseListings(body: String): List<MerchantListing> {-            val array = Json.parseToJsonElement(body) as? JsonArray-                ?: throw UcpHttpException(UcpError.Malformed("Expected merchant directory array"))-            require(array.size <= 5000) { "Directory has too many records" }-            return array.mapNotNull { item ->-                val row = item.asObject() ?: return@mapNotNull null-                if (row.text("category") != "merchants") return@mapNotNull null-                val id = row.text("id")?.takeIf { it.isNotBlank() && it.length <= 200 } ?: return@mapNotNull null-                val name = row.text("name")?.takeIf { it.isNotBlank() && it.length <= 200 } ?: return@mapNotNull null-                val site = row.text("url")?.let(MerchantUrls::httpsUrl) ?: return@mapNotNull null-                val endpoint = row.text("ucpEndpoint")?.takeIf(String::isNotBlank)-                val discoveryUrl = if (endpoint == null) site else MerchantUrls.httpsUrl(endpoint) ?: return@mapNotNull null-                val domain = MerchantUrls.domain(URI(discoveryUrl).host) ?: return@mapNotNull null-                MerchantListing(-                    id = id,-                    name = name,-                    domain = domain,-                    siteUrl = site,-                    description = row.text("description").orEmpty().take(600),-                    directoryStatus = row.text("ucpStatus").orEmpty().take(40),-                    directoryVerifiedAt = row.text("verifiedAt")?.take(80),-                )-            }.distinctBy { it.id to it.domain }.take(1000)-        }-    }-}
shop/src/main/java/com/vayunmathur/shop/network/ShopBackend.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/network/ShopBackend.kt b/shop/src/main/java/com/vayunmathur/shop/network/ShopBackend.ktnew file mode 100644index 0000000000..e0454e3edb--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/network/ShopBackend.kt@@ -0,0 +1,210 @@+package com.vayunmathur.shop.network++import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.shop.data.CartLine+import com.vayunmathur.shop.data.CatalogOptionSelection+import com.vayunmathur.shop.data.CheckoutInputs+import com.vayunmathur.shop.data.MerchantListing+import com.vayunmathur.shop.data.UcpCheckout+import com.vayunmathur.shop.data.UcpError+import com.vayunmathur.shop.data.UcpProduct+import com.vayunmathur.shop.data.message+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.TimeoutCancellationException+import kotlinx.coroutines.currentCoroutineContext+import kotlinx.coroutines.ensureActive+import kotlinx.coroutines.withTimeout+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json+import java.net.URLEncoder++/**+ * The only network surface of the shop app. All UCP behavior (merchant+ * discovery, REST/MCP transport, dated projections, SSRF guards, idempotency+ * ledger, image proxying) lives behind the api.maproj.org shop endpoints; this+ * client sends plain cart/buyer data and decodes display models.+ *+ * Error semantics mirror the former direct-UCP mapping so messages survive+ * the move unchanged: `unsupported` โ†’ merchant website; everything else on a+ * write โ†’ uncertain (never auto-retried).+ */+interface ShopBackend {+    suspend fun search(query: String, shop: String? = null, limit: Int = 20, country: String = "US"): Result<List<UcpProduct>>+    suspend fun getProduct(+        shop: String,+        productId: String,+        variantId: String? = null,+        title: String? = null,+        selectedOptions: List<CatalogOptionSelection> = emptyList(),+    ): Result<UcpProduct>+    suspend fun createCheckout(shop: String, lines: List<CartLine>, inputs: CheckoutInputs, idempotencyKey: String): Result<UcpCheckout>+    suspend fun getCheckout(shop: String, sessionId: String): Result<UcpCheckout>+    suspend fun updateCheckout(shop: String, sessionId: String, lines: List<CartLine>, inputs: CheckoutInputs, idempotencyKey: String): Result<UcpCheckout>+    suspend fun listMerchants(refresh: Boolean = false): Result<List<MerchantListing>>+}++class ShopBackendException(val error: UcpError) : Exception(error.toString())++internal object ShopHttpBackend : ShopBackend {+    internal const val BASE = "https://api.maproj.org/shop/v1"+    internal val json = Json { ignoreUnknownKeys = true; encodeDefaults = true; explicitNulls = false }+    internal var request: suspend (method: String, url: String, body: String?) -> BackendRawResponse = { method, url, body ->+        val response = withTimeout(30_000) {+            NetworkClient.execute(+                url, method,+                headers = mapOf(+                    "Accept" to "application/json",+                    "Content-Type" to "application/json",+                ),+                body = body,+                followRedirects = false,+                connectTimeoutMs = 10_000,+                readTimeoutMs = 10_000,+            )+        }+        BackendRawResponse(response.status, response.text, response.headers, response.header("Retry-After"))+    }++    override suspend fun search(query: String, shop: String?, limit: Int, country: String): Result<List<UcpProduct>> =+        catching {+            require(query.isNotBlank() && query.length <= 200) { "Invalid query" }+            require(limit in 1..50) { "Invalid limit" }+            require(country.matches(Regex("^[A-Z]{2}$"))) { "Invalid country" }+            val url = buildString {+                append("$BASE/search?query=").append(query.encode())+                append("&limit=").append(limit)+                append("&country=").append(country)+                if (!shop.isNullOrBlank()) append("&shop=").append(shop.encode())+            }+            val raw = get(url)+            raw.parse<ShopSearchResponse>().products.map { it.toModel() }+        }++    override suspend fun getProduct(+        shop: String,+        productId: String,+        variantId: String?,+        title: String?,+        selectedOptions: List<CatalogOptionSelection>,+    ): Result<UcpProduct> = catching {+        require(shop.isNotBlank() && productId.isNotBlank()) { "Invalid product request" }+        val url = buildString {+            append("$BASE/product?shop=").append(shop.encode())+            append("&id=").append(productId.encode())+            if (!variantId.isNullOrBlank()) append("&variant=").append(variantId.encode())+            if (!title.isNullOrBlank()) append("&title=").append(title.encode())+            if (selectedOptions.isNotEmpty()) {+                val selected = selectedOptions.map {+                    ShopCatalogOption(it.name, it.label, it.id)+                }+                append("&selected=").append(json.encodeToString(selected).encode())+            }+        }+        get(url).parse<ShopProductResponse>().product.toModel()+    }++    override suspend fun createCheckout(shop: String, lines: List<CartLine>, inputs: CheckoutInputs, idempotencyKey: String): Result<UcpCheckout> =+        catching {+            checkLines(lines, shop)+            require(idempotencyKey.isNotBlank() && idempotencyKey.length <= 256) { "Invalid idempotency key" }+            val request = ShopCreateCheckoutRequest(shop, lines.map { it.toRequestLine() }, inputs.toRequestInputs(), idempotencyKey)+            post("$BASE/checkout-sessions", json.encodeToString(request)).parseSession()+        }++    override suspend fun getCheckout(shop: String, sessionId: String): Result<UcpCheckout> =+        catching {+            require(shop.isNotBlank() && sessionId.isNotBlank()) { "Invalid checkout request" }+            get("$BASE/checkout-sessions?shop=${shop.encode()}&id=${sessionId.encode()}").parseSession()+        }++    override suspend fun updateCheckout(+        shop: String,+        sessionId: String,+        lines: List<CartLine>,+        inputs: CheckoutInputs,+        idempotencyKey: String,+    ): Result<UcpCheckout> = catching {+        checkLines(lines, shop)+        require(sessionId.isNotBlank()) { "Invalid checkout request" }+        require(idempotencyKey.isNotBlank() && idempotencyKey.length <= 256) { "Invalid idempotency key" }+        val request = ShopUpdateCheckoutRequest(shop, sessionId, lines.map { it.toRequestLine() }, inputs.toRequestInputs(), idempotencyKey)+        put("$BASE/checkout-sessions", json.encodeToString(request)).parseSession()+    }++    override suspend fun listMerchants(refresh: Boolean): Result<List<MerchantListing>> =+        catching {+            val url = "$BASE/merchants" + if (refresh) "?refresh=true" else ""+            get(url).parse<ShopMerchantsResponse>().merchants.map { it.toModel() }+        }++    private fun checkLines(lines: List<CartLine>, shop: String) {+        require(lines.isNotEmpty() && lines.all { it.shopDomain == shop && it.quantity in 1..99 }) { "Invalid checkout lines" }+    }++    private suspend fun get(url: String): BackendRawResponse = request("GET", url, null)+    private suspend fun post(url: String, body: String): BackendRawResponse = request("POST", url, body)+    private suspend fun put(url: String, body: String): BackendRawResponse = request("PUT", url, body)++    private inline fun <reified T> BackendRawResponse.parse(): T {+        checkStatus()+        return runCatching { json.decodeFromString<T>(body) }+            .getOrElse { throw ShopBackendException(UcpError.Malformed("The server sent an unexpected response. Please try again.")) }+    }++    private fun BackendRawResponse.parseSession(): UcpCheckout {+        checkStatus()+        val session = runCatching { json.decodeFromString<ShopCheckoutSession>(body) }+            .getOrElse { throw ShopBackendException(UcpError.Malformed("The server sent an unexpected response. Please try again.")) }+        return session.toModel()+    }++    private fun BackendRawResponse.checkStatus() {+        if (status in 200..299) return+        // The server's error envelope mirrors the former UcpError codes.+        val envelope = runCatching { json.decodeFromString<ShopErrorEnvelope>(body) }.getOrNull()?.error+        if (envelope != null) {+            throw ShopBackendException(+                when (envelope.code) {+                    "transport" -> UcpError.Transport(envelope.message.ifBlank { "Couldn't reach the store. Check your connection and try again." })+                    "rate_limited" -> UcpError.RateLimited(envelope.retryAfterMs ?: retryAfter?.toLongOrNull()?.times(1000))+                    "http" -> UcpError.Http(status, "")+                    "malformed" -> UcpError.Malformed(envelope.message.ifBlank { "The store sent an unexpected response. Please try again." })+                    "rpc" -> UcpError.Rpc(envelope.message.ifBlank { "The merchant couldn't process the request." })+                    "uncertain" -> UcpError.Transport("The request may have reached the merchant. Do not retry; check the session or use its website.")+                    // "unsupported" and anything unknown: the merchant website is the fallback.+                    else -> UcpError.Unsupported(envelope.message.ifBlank { "These requirements need the merchant website." })+                },+            )+        }+        if (status == 429) throw ShopBackendException(UcpError.RateLimited(retryAfter?.toLongOrNull()?.times(1000)))+        throw ShopBackendException(UcpError.Http(status, ""))+    }++    private suspend fun <T> catching(block: suspend () -> T): Result<T> = try {+        Result.success(block())+    } catch (_: TimeoutCancellationException) {+        currentCoroutineContext().ensureActive()+        Result.failure(ShopBackendException(UcpError.Transport("Merchant request timed out")))+    } catch (cancelled: CancellationException) {+        throw cancelled+    } catch (error: ShopBackendException) {+        Result.failure(error)+    } catch (_: IllegalArgumentException) {+        Result.failure(ShopBackendException(UcpError.Malformed("Invalid shop request")))+    } catch (_: Exception) {+        Result.failure(ShopBackendException(UcpError.Transport("Couldn't reach the store. Check your connection and try again.")))+    }+}++internal data class BackendRawResponse(+    val status: Int,+    val body: String,+    val headers: Map<String, List<String>>,+    val retryAfter: String?,+)++internal fun String.encode(): String = URLEncoder.encode(this, "UTF-8")++/** Split cart lines by merchant: one server checkout session per shop. */+internal fun splitByShop(lines: List<CartLine>): Map<Pair<String, String>, List<CartLine>> =+    lines.groupBy { Pair(it.platformId, it.shopDomain) }
shop/src/main/java/com/vayunmathur/shop/network/ShopDtos.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/network/ShopDtos.kt b/shop/src/main/java/com/vayunmathur/shop/network/ShopDtos.ktnew file mode 100644index 0000000000..a4e6d44e86--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/network/ShopDtos.kt@@ -0,0 +1,341 @@+package com.vayunmathur.shop.network++import com.vayunmathur.shop.data.CartLine+import com.vayunmathur.shop.data.CatalogOptionSelection+import com.vayunmathur.shop.data.CheckoutInputs+import com.vayunmathur.shop.data.MerchantListing+import com.vayunmathur.shop.data.Money+import com.vayunmathur.shop.data.UcpCheckout+import com.vayunmathur.shop.data.UcpProduct+import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable++/**+ * Request/response DTOs for the first-party proxy (api.maproj.org, shop/v1 endpoints).+ *+ * The server owns all UCP behavior (discovery, REST/MCP transport, dated+ * projections, idempotency ledger); the client sends plain cart/buyer data+ * and decodes display models. Field names mirror the server JSON exactly.+ */+@Serializable+data class ShopCheckoutLine(+    val variantId: String,+    val quantity: Int,+)++@Serializable+data class ShopCheckoutInputs(+    val firstName: String = "",+    val lastName: String = "",+    val email: String = "",+    val phone: String = "",+    val street: String = "",+    val extendedAddress: String = "",+    val city: String = "",+    val region: String = "",+    val country: String = "",+    val postalCode: String = "",+    val options: Map<String, String> = emptyMap(),+    val shippingRequested: Boolean = false,+)++@Serializable+data class ShopCreateCheckoutRequest(+    val shop: String,+    val lines: List<ShopCheckoutLine>,+    val inputs: ShopCheckoutInputs,+    val idempotencyKey: String,+)++@Serializable+data class ShopUpdateCheckoutRequest(+    val shop: String,+    val sessionId: String,+    val lines: List<ShopCheckoutLine>,+    val inputs: ShopCheckoutInputs,+    val idempotencyKey: String,+)++@Serializable+data class ShopSubmittedLine(+    val variantId: String = "",+    val quantity: Int = 0,+)++@Serializable+data class ShopMoney(+    val amount: Long = 0,+    val currency: String = "USD",+)++@Serializable+data class ShopTotalEntry(+    val type: String = "",+    @SerialName("display_text") val displayText: String = "",+    val amount: Long = 0,+    val currency: String = "USD",+)++@Serializable+data class ShopMessage(+    val type: String = "",+    val text: String = "",+    val path: String? = null,+    val code: String? = null,+    val severity: String? = null,+)++@Serializable+data class ShopShippingOption(+    val id: String = "",+    val title: String = "",+    val description: String = "",+    val totals: List<ShopTotalEntry> = emptyList(),+)++@Serializable+data class ShopShippingGroup(+    val id: String = "",+    @SerialName("selected_option_id") val selectedOptionId: String? = null,+    val options: List<ShopShippingOption> = emptyList(),+)++@Serializable+data class ShopShippingMethod(+    val id: String = "",+    val groups: List<ShopShippingGroup> = emptyList(),+)++@Serializable+data class ShopLegalLink(+    val type: String = "",+    val title: String = "",+    val url: String = "",+)++@Serializable+data class ShopReview(+    val shipping: List<ShopShippingMethod> = emptyList(),+    val links: List<ShopLegalLink> = emptyList(),+    val browserOnlyReason: String? = null,+    val availableShippingLineIds: List<String> = emptyList(),+)++@Serializable+data class ShopTotals(+    val subtotal: ShopMoney = ShopMoney(),+    val total: ShopMoney = ShopMoney(),+)++@Serializable+data class ShopCheckoutSession(+    val checkoutId: String = "",+    val status: String = "",+    val currency: String = "USD",+    val totals: ShopTotals = ShopTotals(),+    val totalEntries: List<ShopTotalEntry> = emptyList(),+    val continueUrl: String = "",+    val expiresAt: String? = null,+    val messages: List<ShopMessage> = emptyList(),+    val version: String = "2026-08-25",+    val review: ShopReview = ShopReview(),+    val submittedLines: List<ShopSubmittedLine> = emptyList(),+)++@Serializable+data class ShopProductImage(+    val url: String = "",+    val alt: String? = null,+)++@Serializable+data class ShopCatalogOption(+    val name: String = "",+    val label: String = "",+    val id: String? = null,+)++@Serializable+data class ShopVariant(+    val id: String = "",+    val title: String = "",+    val price: ShopMoney = ShopMoney(),+    val available: Boolean = false,+    val optionValues: List<String> = emptyList(),+    val sku: String? = null,+    val storeName: String = "",+    val shopDomain: String = "",+    val selectedOptions: List<ShopCatalogOption> = emptyList(),+)++@Serializable+data class ShopProduct(+    val id: String = "",+    val title: String = "",+    val description: String = "",+    val priceRange: ShopMoney = ShopMoney(),+    val priceRangeMax: ShopMoney? = null,+    val url: String = "",+    val platformId: String = "shopify",+    val shopDomain: String = "",+    val images: List<ShopProductImage> = emptyList(),+    val variants: List<ShopVariant> = emptyList(),+    val checkoutEligible: Boolean = false,+    val descriptionHtml: String = "",+    val storeName: String = "",+)++@Serializable+data class ShopMerchant(+    val id: String = "",+    val name: String = "",+    val domain: String = "",+    val siteUrl: String = "",+    val description: String = "",+    val directoryStatus: String = "unknown",+    val directoryVerifiedAt: String? = null,+)++@Serializable+data class ShopSearchResponse(+    val products: List<ShopProduct> = emptyList(),+)++@Serializable+data class ShopProductResponse(+    val product: ShopProduct = ShopProduct(),+)++@Serializable+data class ShopMerchantsResponse(+    val merchants: List<ShopMerchant> = emptyList(),+)++@Serializable+data class ShopErrorBody(+    val code: String = "",+    val message: String = "",+    val retryAfterMs: Long? = null,+)++@Serializable+data class ShopErrorEnvelope(+    val error: ShopErrorBody = ShopErrorBody(),+)++/** Display-model conversions: server DTOs to the UI models. */+internal fun ShopMoney.toModel(): Money = Money(amount, currency)++internal fun ShopProduct.toModel(): UcpProduct = UcpProduct(+    id = id,+    title = title,+    description = description,+    priceRange = priceRange.toModel(),+    priceRangeMax = priceRangeMax?.toModel(),+    url = url,+    platformId = platformId,+    shopDomain = shopDomain,+    images = images.map { com.vayunmathur.shop.data.ProductImage(it.url, it.alt) },+    variants = variants.map { variant ->+        com.vayunmathur.shop.data.ProductVariant(+            id = variant.id,+            title = variant.title,+            price = variant.price.toModel(),+            available = variant.available,+            optionValues = variant.optionValues,+            sku = variant.sku,+            storeName = variant.storeName,+            shopDomain = variant.shopDomain,+            selectedOptions = variant.selectedOptions.map {+                CatalogOptionSelection(it.name, it.label, it.id)+            },+        )+    },+    checkoutEligible = checkoutEligible,+    descriptionHtml = descriptionHtml,+    storeName = storeName,+)++internal fun ShopMerchant.toModel(): MerchantListing = MerchantListing(+    id = id,+    name = name,+    domain = domain,+    siteUrl = siteUrl,+    description = description,+    directoryStatus = directoryStatus,+    directoryVerifiedAt = directoryVerifiedAt,+)++internal fun ShopCheckoutSession.toModel(): UcpCheckout = UcpCheckout(+    checkoutId = checkoutId,+    status = status,+    currency = currency,+    totals = com.vayunmathur.shop.data.UcpTotals(+        subtotal = totals.subtotal.toModel(),+        total = totals.total.toModel(),+    ),+    totalEntries = totalEntries.map {+        com.vayunmathur.shop.data.UcpTotalEntry(it.type, it.displayText.ifBlank { it.type }, it.amount.toModel(it.currency))+    },+    continueUrl = continueUrl,+    expiresAt = expiresAt,+    messages = messages.map {+        com.vayunmathur.shop.data.UcpMessage(it.type, it.text, it.path, it.code, it.severity)+    },+    version = version,+    review = com.vayunmathur.shop.data.CheckoutReview(+        shipping = review.shipping.map { method ->+            com.vayunmathur.shop.data.CheckoutShippingMethod(+                id = method.id,+                groups = method.groups.map { group ->+                    com.vayunmathur.shop.data.CheckoutShippingGroup(+                        id = group.id,+                        selectedOptionId = group.selectedOptionId,+                        options = group.options.map { option ->+                            com.vayunmathur.shop.data.CheckoutShippingOption(+                                id = option.id,+                                title = option.title,+                                description = option.description,+                                totals = option.totals.map { total ->+                                    com.vayunmathur.shop.data.UcpTotalEntry(+                                        total.type,+                                        total.displayText.ifBlank { total.type },+                                        total.amount.toModel(total.currency),+                                    )+                                },+                            )+                        },+                    )+                },+            )+        },+        links = review.links.map {+            com.vayunmathur.shop.data.CheckoutLegalLink(it.type, it.title, it.url)+        },+        browserOnlyReason = review.browserOnlyReason,+        availableShippingLineIds = review.availableShippingLineIds,+    ),+    submittedLines = submittedLines.map {+        com.vayunmathur.shop.data.SubmittedLine(it.variantId, it.quantity)+    },+)++private fun Long.toModel(currency: String): Money = Money(this, currency)++internal fun CartLine.toRequestLine(): ShopCheckoutLine =+    ShopCheckoutLine(variantId = variantId, quantity = quantity)++internal fun CheckoutInputs.toRequestInputs(): ShopCheckoutInputs = ShopCheckoutInputs(+    firstName = firstName,+    lastName = lastName,+    email = email,+    phone = phone,+    street = street,+    extendedAddress = extendedAddress,+    city = city,+    region = region,+    country = country,+    postalCode = postalCode,+    options = options,+    shippingRequested = shippingRequested,+)
shop/src/main/java/com/vayunmathur/shop/network/UcpApi.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/network/UcpApi.kt b/shop/src/main/java/com/vayunmathur/shop/network/UcpApi.ktdeleted file mode 100644index 2d2835edd7..0000000000--- a/shop/src/main/java/com/vayunmathur/shop/network/UcpApi.kt+++ /dev/null@@ -1,157 +0,0 @@-package com.vayunmathur.shop.network--import com.vayunmathur.shop.data.UcpError-import com.vayunmathur.shop.domain.MerchantUrls-import kotlinx.coroutines.CancellationException-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.TimeoutCancellationException-import kotlinx.coroutines.currentCoroutineContext-import kotlinx.coroutines.ensureActive-import kotlinx.coroutines.withContext-import kotlinx.coroutines.withTimeout-import kotlinx.serialization.json.Json-import kotlinx.serialization.json.JsonObject-import kotlinx.serialization.json.JsonPrimitive-import kotlinx.serialization.json.buildJsonObject-import kotlinx.serialization.json.put-import kotlinx.serialization.json.putJsonObject--/** Anonymous advertised-service dispatch. No tool request is automatically replayed. */-internal object UcpApi {-    const val AGENT_PROFILE_URL = "https://maproj.org/.well-known/agent-profile.json"-    const val VERSION = "2026-08-25"-    const val APRIL_VERSION = "2026-04-08"-    val json = Json { ignoreUnknownKeys = true; encodeDefaults = true; explicitNulls = false }-    internal var transport: UcpTransport = UcpNetworkTransport--    fun profileUrl(version: String): String {-        require(version == VERSION || version == APRIL_VERSION) { "Unsupported UCP version" }-        return "https://maproj.org/.well-known/ucp?version=$version"-    }--    suspend fun serviceCall(service: UcpService, tool: String, arguments: JsonObject): Result<JsonObject> = ioCall {-        catching {-            profileUrl(service.version)-            require(MerchantUrls.httpsUrl(service.endpoint) != null && java.net.URI(service.endpoint).fragment == null) {-                "Invalid merchant endpoint"-            }-            require(arguments.toString().toByteArray(Charsets.UTF_8).size <= UcpWire.MAX_BODY_BYTES) { "Request exceeds limit" }-            require(tool in setOf("search_catalog", "lookup_catalog", "get_product", "create_checkout", "get_checkout", "update_checkout")) {-                "Unsupported operation; completion and cancellation are disabled"-            }-            // Snapshot the injection seam for the entire session, including cleanup.-            val wire = transport-            withTimeout(UcpWire.CALL_TIMEOUT_MS) {-                when (service.transport) {-                    "rest" -> UcpRest.call(wire, service, tool, arguments)-                    "mcp" -> UcpMcp.call(wire, service.endpoint, tool, arguments, service.version)-                    else -> throw UcpHttpException(UcpError.Unsupported("Unsupported shopping transport"))-                }-            }-        }-    }--    suspend fun mcpCall(endpoint: String, tool: String, arguments: JsonObject, version: String = VERSION): Result<JsonObject> =-        serviceCall(UcpService(version, "mcp", endpoint, emptySet(), emptySet()), tool, arguments)--    internal fun parseObject(body: String): JsonObject =-        runCatching { json.parseToJsonElement(body) as? JsonObject }.getOrNull()-            ?: throw UcpHttpException(UcpError.Malformed("Expected JSON object"))--    internal fun validateResult(data: JsonObject, version: String = VERSION, operation: String? = null): JsonObject {-        if (data["ucp"].asObject()?.text("status") == "error" || data.containsKey("error")) {-            throw UcpHttpException(UcpError.Rpc("Merchant returned a UCP error"))-        }-        val validationErrors = data["messages"].asArray()?.any { it.asObject()?.text("type") == "error" } == true-        // Business validation belongs in native review, not in catalog or protocol error handling.-        if (validationErrors && (operation !in checkoutOperations || !isCheckoutSession(data, version))) {-            throw UcpHttpException(UcpError.Rpc("Merchant returned a UCP error"))-        }-        if (data["ucp"].asObject()?.text("version") != version) {-            throw UcpHttpException(UcpError.Malformed("Unexpected UCP response version"))-        }-        return data-    }--    private val checkoutOperations = setOf("create_checkout", "get_checkout", "update_checkout")-    private val checkoutStatuses = setOf("incomplete", "requires_escalation", "ready_for_complete", "complete_in_progress", "completed", "canceled")-    private val totalTypes = setOf("subtotal", "items_discount", "discount", "fulfillment", "tax", "fee", "total")--    private fun string(o: JsonObject, key: String): String? =-        (o[key] as? JsonPrimitive)?.takeIf { it.isString }?.content--    private fun integer(o: JsonObject, key: String, version: String): Long? {-        val value = (o[key] as? JsonPrimitive)?.takeUnless { it.isString }?.content?.toLongOrNull() ?: return null-        if (version == VERSION && (value < -9_007_199_254_740_991L || value > 9_007_199_254_740_991L)) return null-        return value-    }--    private fun isCheckoutSession(data: JsonObject, version: String): Boolean {-        if (version !in setOf(VERSION, APRIL_VERSION) || string(data, "id").isNullOrBlank() ||-            string(data, "status") !in checkoutStatuses || string(data, "currency")?.matches(Regex("^[A-Z]{3}$")) != true) return false-        val totals = data["totals"].asArray() ?: return false-        if (!validTotals(data, version) || totals.count { it.asObject()?.let { total -> string(total, "type") } == "subtotal" } != 1 ||-            totals.count { it.asObject()?.let { total -> string(total, "type") } == "total" } != 1) return false-        val lines = data["line_items"].asArray() ?: return false-        return lines.all { element ->-            val line = element.asObject() ?: return@all false-            val item = line["item"].asObject() ?: return@all false-            !string(line, "id").isNullOrBlank() && !string(item, "id").isNullOrBlank() &&-                string(item, "title") != null && integer(item, "price", version)?.let { it >= 0 } == true &&-                integer(line, "quantity", version)?.let { it >= 1 } == true && validTotals(line, version)-        }-    }--    private fun validTotals(o: JsonObject, version: String): Boolean = o["totals"].asArray()?.all { element ->-        val total = element.asObject() ?: return@all false-        val type = string(total, "type")?.takeIf { it.isNotBlank() } ?: return@all false-        if (integer(total, "amount", version) == null ||-            (total.containsKey("display_text") && string(total, "display_text") == null) ||-            (type !in totalTypes && string(total, "display_text") == null)) return@all false-        if (!total.containsKey("lines")) return@all true-        total["lines"].asArray()?.all subLineLoop@ { subElement ->-            val subLine = subElement.asObject() ?: return@subLineLoop false-            string(subLine, "display_text") != null && integer(subLine, "amount", version) != null-        } == true-    } == true--    internal fun unwrapResult(envelope: JsonObject, version: String = VERSION, operation: String? = null): JsonObject {-        envelope["error"]?.let { throw UcpHttpException(UcpError.Rpc("Merchant RPC rejected the request")) }-        val result = envelope["result"] as? JsonObject-            ?: throw UcpHttpException(UcpError.Malformed("Missing MCP result"))-        if (result["isError"].isTruthy() == true) {-            throw UcpHttpException(UcpError.Rpc("Merchant tool rejected the request"))-        }-        val data = result["structuredContent"] as? JsonObject-            ?: result["content"].asArray()?.firstNotNullOfOrNull { item ->-                val content = item.asObject() ?: return@firstNotNullOfOrNull null-                if (content.text("type") != "text") return@firstNotNullOfOrNull null-                content.text("text")?.let { runCatching { json.parseToJsonElement(it) as? JsonObject }.getOrNull() }-            }-            ?: throw UcpHttpException(UcpError.Malformed("Missing structured tool content"))-        return validateResult(data, version, operation)-    }--    internal fun withAgentProfile(arguments: JsonObject, version: String = VERSION): JsonObject = buildJsonObject {-        arguments.forEach { (key, value) -> put(key, value) }-        putJsonObject("meta") {-            arguments["meta"].asObject()?.forEach { (key, value) -> put(key, value) }-            putJsonObject("ucp-agent") { put("profile", profileUrl(version)) }-        }-    }--    internal suspend fun <T> catching(block: suspend () -> T): Result<T> = try {-        Result.success(block())-    } catch (_: TimeoutCancellationException) {-        currentCoroutineContext().ensureActive()-        Result.failure(UcpHttpException(UcpError.Transport("Merchant request timed out")))-    } catch (cancelled: CancellationException) {-        throw cancelled-    } catch (error: Exception) {-        Result.failure(error)-    }--    internal suspend fun <T> ioCall(block: suspend () -> T): T = withContext(Dispatchers.IO) { block() }-}--class UcpHttpException(val error: UcpError) : Exception(error.toString())
shop/src/main/java/com/vayunmathur/shop/network/UcpCatalog.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/network/UcpCatalog.kt b/shop/src/main/java/com/vayunmathur/shop/network/UcpCatalog.ktdeleted file mode 100644index 8d81d97238..0000000000--- a/shop/src/main/java/com/vayunmathur/shop/network/UcpCatalog.kt+++ /dev/null@@ -1,361 +0,0 @@-package com.vayunmathur.shop.network--import com.vayunmathur.shop.data.CatalogOptionSelection-import com.vayunmathur.shop.data.Money-import com.vayunmathur.shop.data.ProductImage-import com.vayunmathur.shop.data.ProductVariant-import com.vayunmathur.shop.data.UcpError-import com.vayunmathur.shop.data.UcpProduct-import com.vayunmathur.shop.domain.MerchantUrls-import kotlinx.serialization.json.JsonObject-import kotlinx.serialization.json.JsonPrimitive-import kotlinx.serialization.json.buildJsonObject-import kotlinx.serialization.json.put-import kotlinx.serialization.json.putJsonArray-import kotlinx.serialization.json.putJsonObject-import java.net.URI--/** Dated UCP catalog bindings; responses remain session-scoped. */-object UcpCatalog {-    suspend fun search(query: String, shipsTo: String = "US", limit: Int = 20): Result<List<UcpProduct>> =-        UcpApi.serviceCall(-            UcpService(UcpApi.VERSION, "mcp", requireNotNull(UcpPlatforms.SHOPIFY.globalCatalogMcp),-                setOf("dev.ucp.shopping.catalog.search"), emptySet()),-            "search_catalog", searchArguments(query, shipsTo, limit, UcpApi.VERSION),-        ).mapCatching { parseProducts(it, "shopify", "", UcpApi.VERSION) }--    suspend fun searchStore(-        platform: UcpPlatform, shopDomain: String, query: String, limit: Int = 20,-    ): Result<List<UcpProduct>> {-        val service = UcpDiscovery.resolve(shopDomain, "dev.ucp.shopping.catalog.search")-            .getOrElse { return Result.failure(it) }-        return UcpApi.serviceCall(service, "search_catalog", searchArguments(query, "US", limit, service.version))-            .mapCatching { parseProducts(it, platform.id, shopDomain, service.version) }-    }--    suspend fun lookup(platform: UcpPlatform, shopDomain: String, ids: List<String>): Result<List<UcpProduct>> {-        if (ids.isEmpty()) return Result.success(emptyList())-        val service = UcpDiscovery.resolve(shopDomain, "dev.ucp.shopping.catalog.lookup")-            .getOrElse { return Result.failure(it) }-        return UcpApi.serviceCall(service, "lookup_catalog", lookupArguments(ids, service.version))-            .mapCatching { parseProducts(it, platform.id, shopDomain, service.version) }-    }--    suspend fun getProduct(-        platform: UcpPlatform, shopDomain: String, id: String,-        selectedOptions: List<CatalogOptionSelection> = emptyList(),-    ): Result<UcpProduct> {-        val service = UcpDiscovery.resolve(shopDomain, "dev.ucp.shopping.catalog.lookup")-            .getOrElse { return Result.failure(it) }-        val arguments = buildJsonObject {-            putJsonObject("catalog") {-                put("id", id)-                putJsonObject("context") { put("address_country", "US") }-                if (selectedOptions.isNotEmpty()) {-                    putJsonArray("selected") {-                        selectedOptions.forEach { selection ->-                            add(buildJsonObject {-                                put("name", selection.name)-                                put("label", selection.label)-                                selection.id?.let { put("id", it) }-                            })-                        }-                    }-                }-            }-        }-        return UcpApi.serviceCall(service, "get_product", arguments).mapCatching {-            parseProductResponse(it, platform.id, shopDomain, service.version)-        }-    }--    /** Confirm the exact SKU using a fresh merchant response, not the cached search snapshot. */-    suspend fun refreshProduct(-        platform: UcpPlatform, shopDomain: String, variantId: String, productId: String? = null,-        selectedOptions: List<CatalogOptionSelection> = emptyList(), productTitle: String? = null,-    ): Result<UcpProduct> {-        val detail = getProduct(platform, shopDomain, productId?.takeIf { it.isNotBlank() } ?: variantId, selectedOptions)-        if (detail.isFailure || detail.getOrThrow().variants.any { it.id == variantId }) return detail-        // Some detail services return only their featured option, ignoring the requested selection.-        // A separate advertised merchant search can confirm the exact SKU; never retry denied/limited requests.-        if (!productTitle.isNullOrBlank()) {-            return searchStore(platform, shopDomain, productTitle, limit = 10).mapCatching { products ->-                val matched = products.firstOrNull { product -> product.variants.any { it.id == variantId } }-                    ?: throw UcpHttpException(UcpError.Unsupported("The store did not return a live price for this option."))-                val alternatives = detail.getOrThrow().takeIf { it.id == matched.id }?.variants.orEmpty()-                    .filter { option -> option.price.currency == matched.priceRange.currency && matched.variants.none { it.id == option.id } }-                matched.copy(variants = matched.variants + alternatives)-            }-        }-        return Result.failure(UcpHttpException(UcpError.Unsupported("The store did not return a live price for this option.")))-    }--    internal fun searchArguments(query: String, country: String, limit: Int): JsonObject =-        searchArguments(query, country, limit, UcpApi.VERSION)--    internal fun searchArguments(query: String, country: String, limit: Int, version: String): JsonObject =-        when (version) {-            UcpApi.VERSION -> augustSearchArguments(query, country, limit)-            UcpApi.APRIL_VERSION -> aprilSearchArguments(query, country, limit)-            else -> malformed("Unsupported catalog version")-        }--    // MCP's catalog argument wraps the dated REST request; serviceCall owns transport projection.-    private fun augustSearchArguments(query: String, country: String, limit: Int): JsonObject = buildJsonObject {-        putJsonObject("catalog") {-            put("query", query)-            putJsonObject("context") { put("address_country", country) }-            putJsonObject("pagination") { put("limit", limit.coerceIn(1, 50)) }-        }-    }--    private fun aprilSearchArguments(query: String, country: String, limit: Int): JsonObject = buildJsonObject {-        putJsonObject("catalog") {-            put("query", query)-            putJsonObject("context") { put("address_country", country) }-            putJsonObject("pagination") { put("limit", limit.coerceIn(1, 50)) }-        }-    }--    internal fun lookupArguments(ids: List<String>, version: String): JsonObject {-        requireVersion(version)-        return buildJsonObject {-            putJsonObject("catalog") { putJsonArray("ids") { ids.forEach { add(JsonPrimitive(it)) } } }-        }-    }--    /** Strict wire entry point: the expected version comes from the selected discovery leaf. */-    internal fun parseProducts(-        result: JsonObject, platformId: String, shopDomain: String, expectedVersion: String,-    ): List<UcpProduct> {-        validateResponse(result, expectedVersion)-        val products = result["products"].asArray() ?: malformed("Missing products")-        return products.map { element ->-            val product = element.asObject() ?: malformed("Invalid product")-            when (expectedVersion) {-                UcpApi.VERSION -> parseAugustProduct(product, platformId, shopDomain)-                UcpApi.APRIL_VERSION -> parseAprilProduct(product, platformId, shopDomain)-                else -> malformed("Unsupported catalog version")-            }-        }-    }--    internal fun parseProductResponse(-        result: JsonObject, platformId: String, shopDomain: String, expectedVersion: String,-    ): UcpProduct {-        validateResponse(result, expectedVersion)-        val product = result["product"].asObject() ?: malformed("Missing product")-        return when (expectedVersion) {-            UcpApi.VERSION -> parseAugustProduct(product, platformId, shopDomain)-            UcpApi.APRIL_VERSION -> parseAprilProduct(product, platformId, shopDomain)-            else -> malformed("Unsupported catalog version")-        }-    }--    private fun parseAugustProduct(o: JsonObject, platformId: String, shop: String): UcpProduct {-        validateProduct(o)-        val range = priceRange(o, ::parseMoney)-        val variants = o["variants"].asArray()!!.map { element ->-            val variant = element.asObject() ?: malformed("Invalid variant")-            validateVariant(variant)-            projectVariant(variant, parseMoney(variant["price"].asObject()!!), augustQuantity(variant))-        }-        return projectProduct(o, platformId, shop, range, variants)-    }--    private fun parseAprilProduct(o: JsonObject, platformId: String, shop: String): UcpProduct {-        validateProduct(o)-        val range = priceRange(o, ::parseAprilMoney)-        val variants = o["variants"].asArray()!!.map { element ->-            val variant = element.asObject() ?: malformed("Invalid variant")-            validateVariant(variant)-            // April has no quantity_unit descriptor. Do not import August semantics into this leaf.-            projectVariant(variant, parseAprilMoney(variant["price"].asObject()!!), true)-        }-        return projectProduct(o, platformId, shop, range, variants)-    }--    private fun validateResponse(result: JsonObject, version: String) {-        requireVersion(version)-        if (string(result["ucp"].asObject(), "version") != version) malformed("Unexpected UCP response version")-        if (result["ucp"].asObject()?.text("status") == "error" ||-            result["messages"].asArray()?.any { it.asObject()?.text("type") == "error" } == true) {-            throw UcpHttpException(UcpError.Rpc("Merchant returned a UCP error"))-        }-    }--    private fun requireVersion(version: String) {-        if (version != UcpApi.VERSION && version != UcpApi.APRIL_VERSION) malformed("Unsupported catalog version")-    }--    private fun validateProduct(o: JsonObject) {-        if (string(o, "id").isNullOrBlank() || string(o, "title") == null ||-            o["description"].asObject() == null || o["price_range"].asObject() == null ||-            o["variants"].asArray().isNullOrEmpty()) malformed("Invalid dated product")-    }--    private fun validateVariant(o: JsonObject) {-        if (string(o, "id").isNullOrBlank() || string(o, "title") == null ||-            o["description"].asObject() == null || o["price"].asObject() == null) malformed("Invalid dated variant")-    }--    private fun priceRange(o: JsonObject, money: (JsonObject) -> Money): Pair<Money, Money> {-        val range = o["price_range"].asObject() ?: malformed("Missing price range")-        val min = money(range["min"].asObject() ?: malformed("Missing minimum price"))-        val max = money(range["max"].asObject() ?: malformed("Missing maximum price"))-        if (min.currency != max.currency || min.amount > max.amount) malformed("Invalid price range")-        return min to max-    }--    private fun augustQuantity(o: JsonObject): Boolean {-        if (!o.containsKey("quantity_unit")) return true-        val unit = o["quantity_unit"].asObject() ?: return false-        return string(unit, "unit") == "C62" && string(unit, "display_text") != null &&-            (!unit.containsKey("scale") || integer(unit, "scale") == 0L) &&-            (!unit.containsKey("increment") || integer(unit, "increment") == 1L)-    }--    private fun projectVariant(o: JsonObject, price: Money, supportedQuantity: Boolean): ProductVariant = ProductVariant(-        id = string(o, "id")!!,-        title = string(o, "title")!!,-        price = price,-        available = o["availability"].asObject()?.get("available") == JsonPrimitive(true) && supportedQuantity,-        optionValues = o["options"].asArray()?.mapNotNull { string(it.asObject(), "label") }.orEmpty(),-        sku = string(o, "sku"),-        storeName = sellerName(o),-        shopDomain = sellerDomain(o),-        selectedOptions = parseSelectedOptions(o),-    )--    private fun projectProduct(-        o: JsonObject, platformId: String, defaultShop: String, price: Pair<Money, Money>, variants: List<ProductVariant>,-    ): UcpProduct {-        val url = string(o, "url")?.let(MerchantUrls::httpsUrl).orEmpty()-        val shop = MerchantUrls.domain(defaultShop)-            ?: variants.firstOrNull()?.shopDomain?.takeIf { it.isNotBlank() }-            ?: string(o, "shop_domain")?.let(MerchantUrls::domain)-            ?: merchantDomainFromUrl(url)-        val images = o["media"].asArray()?.mapNotNull { item ->-            val media = item.asObject() ?: return@mapNotNull null-            if (string(media, "type") != "image") return@mapNotNull null-            val image = string(media, "url")?.let(MerchantUrls::httpsUrl) ?: return@mapNotNull null-            val host = URI(image).host.lowercase()-            if (host != shop && host != "cdn.shopify.com") return@mapNotNull null-            ProductImage(image, string(media, "alt_text"))-        }.orEmpty()-        return UcpProduct(-            id = string(o, "id")!!, title = string(o, "title")!!,-            description = string(o["description"].asObject(), "plain").orEmpty(),-            priceRange = price.first, priceRangeMax = price.second,-            url = url, platformId = platformId, shopDomain = shop,-            images = images, variants = variants,-            descriptionHtml = string(o["description"].asObject(), "html").orEmpty(),-            storeName = variants.firstOrNull { it.shopDomain.isBlank() || it.shopDomain == shop }?.storeName.orEmpty(),-            checkoutEligible = shop.isNotBlank() && variants.isNotEmpty() && o["native_commerce"] != JsonPrimitive(false),-        )-    }--    private fun parseSelectedOptions(variant: JsonObject): List<CatalogOptionSelection> =-        variant["options"].asArray()?.mapNotNull { element ->-            val option = element.asObject() ?: return@mapNotNull null-            val name = string(option, "name") ?: return@mapNotNull null-            val label = string(option, "label") ?: return@mapNotNull null-            CatalogOptionSelection(name, label, string(option, "id"))-        }.orEmpty()--    private fun sellerName(variant: JsonObject): String =-        string(variant["seller"].asObject(), "name")?.trim()?.take(200).orEmpty()--    private fun sellerDomain(variant: JsonObject): String {-        val seller = variant["seller"].asObject()-        return string(seller, "domain")?.let(MerchantUrls::domain)-            ?: string(seller, "url")?.let(MerchantUrls::httpsUrl)?.let { MerchantUrls.domain(URI(it).host) }-            ?: ""-    }--    private fun merchantDomainFromUrl(url: String): String =-        url.takeIf { it.isNotBlank() }?.let { URI(it).host.lowercase() }-            ?.takeUnless { it == "shop.app" || it.endsWith(".shop.app") || it == "catalog.shopify.com" }.orEmpty()--    private fun string(o: JsonObject?, key: String): String? =-        (o?.get(key) as? JsonPrimitive)?.takeIf { it.isString }?.content--    private fun integer(o: JsonObject, key: String): Long? =-        (o[key] as? JsonPrimitive)?.takeUnless { it.isString }?.content?.toLongOrNull()--    private fun malformed(reason: String): Nothing = throw UcpHttpException(UcpError.Malformed(reason))--    // Compatibility parser for existing callers/fixtures without the UCP response envelope.-    internal fun parseProducts(result: JsonObject, platformId: String, shopDomain: String): List<UcpProduct> {-        val items = result["products"].asArray()-            ?: throw UcpHttpException(UcpError.Malformed("Missing products"))-        return items.mapNotNull { it.asObject()?.let { product -> parseProduct(product, platformId, shopDomain) } }-    }--    internal fun parseProduct(o: JsonObject, platformId: String, defaultShop: String): UcpProduct? {-        val id = o.text("id")?.takeIf { it.isNotBlank() } ?: return null-        val variants = o["variants"].asArray()?.mapNotNull { it.asObject()?.let(::parseVariant) }.orEmpty()-        val range = o["price_range"].asObject()-        val url = o.text("url").orEmpty()-        val shop = MerchantUrls.domain(defaultShop)-            ?: variants.firstOrNull()?.shopDomain?.takeIf { it.isNotBlank() }-            ?: o.text("shop_domain")?.let(MerchantUrls::domain)-            ?: MerchantUrls.httpsUrl(url)?.let(::merchantDomainFromUrl).orEmpty()-        val images = o["media"].asArray()?.mapNotNull { item ->-            val media = item.asObject() ?: return@mapNotNull null-            if (media.text("type") != "image") return@mapNotNull null-            val imageUrl = media.text("url")?.let(MerchantUrls::httpsUrl) ?: return@mapNotNull null-            val imageHost = URI(imageUrl).host-            if (imageHost != shop && imageHost != "cdn.shopify.com") return@mapNotNull null-            ProductImage(imageUrl, media.text("alt_text"))-        }.orEmpty()-        return UcpProduct(-            id = id,-            title = o.text("title").orEmpty(),-            description = o["description"].asObject()?.text("plain") ?: o.text("description").orEmpty(),-            descriptionHtml = o["description"].asObject()?.text("html").orEmpty(),-            storeName = variants.firstOrNull { it.shopDomain.isBlank() || it.shopDomain == shop }?.storeName.orEmpty(),-            priceRange = range?.get("min").asObject()?.let(::parseMoney) ?: variants.firstOrNull()?.price ?: Money(),-            priceRangeMax = range?.get("max").asObject()?.let(::parseMoney),-            url = url,-            platformId = platformId,-            shopDomain = shop,-            images = images,-            variants = variants,-            // Core catalog eligibility is not payment permission. Discovery checks checkout support later.-            checkoutEligible = o["native_commerce"].isTruthy() ?: (shop.isNotBlank() && variants.isNotEmpty()),-        )-    }--    internal fun parseVariant(o: JsonObject): ProductVariant? {-        val id = o.text("id")?.takeIf { it.isNotBlank() } ?: return null-        val price = o["price"].asObject()?.let { runCatching { parseMoney(it) }.getOrNull() } ?: return null-        // The UI supports integer 'each' quantities, not weighed/fractional quantities or subscriptions.-        val unit = o["quantity_unit"].asObject()-        val supportedQuantity = unit == null || (unit.text("unit") == "C62" && unit.money("scale") == 0L)-        return ProductVariant(-            id = id,-            title = o.text("title").orEmpty(),-            price = price,-            available = (o["availability"].asObject()?.get("available").isTruthy() == true) && supportedQuantity,-            optionValues = o["options"].asArray()?.mapNotNull { it.asObject()?.text("label") }.orEmpty(),-            sku = o.text("sku"),-            storeName = sellerName(o),-            shopDomain = sellerDomain(o),-            selectedOptions = parseSelectedOptions(o),-        )-    }--    internal fun parseMoney(o: JsonObject): Money {-        val money = parseAprilMoney(o)-        if (money.amount > 9_007_199_254_740_991L) malformed("Amount exceeds August catalog limit")-        return money-    }--    private fun parseAprilMoney(o: JsonObject): Money {-        val amount = integer(o, "amount")?.takeIf { it >= 0 } ?: malformed("Invalid amount")-        val currency = string(o, "currency")?.takeIf { it.matches(Regex("^[A-Z]{3}$")) }-            ?: malformed("Invalid currency")-        return Money(amount, currency)-    }-}
shop/src/main/java/com/vayunmathur/shop/network/UcpCheckoutApi.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/network/UcpCheckoutApi.kt b/shop/src/main/java/com/vayunmathur/shop/network/UcpCheckoutApi.ktdeleted file mode 100644index f793b429ee..0000000000--- a/shop/src/main/java/com/vayunmathur/shop/network/UcpCheckoutApi.kt+++ /dev/null@@ -1,153 +0,0 @@-package com.vayunmathur.shop.network--import com.vayunmathur.shop.data.CheckoutInputs-import com.vayunmathur.shop.data.CheckoutReview-import com.vayunmathur.shop.data.CheckoutLegalLink-import com.vayunmathur.shop.data.CheckoutShippingMethod-import com.vayunmathur.shop.data.CheckoutShippingGroup-import com.vayunmathur.shop.data.CheckoutShippingOption-import com.vayunmathur.shop.domain.CheckoutProjection-import com.vayunmathur.shop.domain.MerchantUrls-import com.vayunmathur.shop.data.CartLine-import com.vayunmathur.shop.data.Money-import com.vayunmathur.shop.data.UcpCheckout-import com.vayunmathur.shop.data.UcpError-import com.vayunmathur.shop.data.UcpMessage-import com.vayunmathur.shop.data.UcpTotalEntry-import com.vayunmathur.shop.data.UcpTotals-import kotlinx.serialization.json.JsonObject-import kotlinx.serialization.json.buildJsonObject-import kotlinx.serialization.json.put-import kotlinx.serialization.json.putJsonArray-import kotlinx.serialization.json.putJsonObject--/** Checkout session preparation only; payment/completion needs an authorized payment integration. */-object UcpCheckoutApi {-    suspend fun createCheckout(platform: UcpPlatform, shopDomain: String, lines: List<CartLine>): Result<UcpCheckout> {-        if (lines.isEmpty() || lines.any { it.shopDomain != shopDomain || it.platformId != platform.id || it.quantity !in 1..99 }) {-            return Result.failure(UcpHttpException(UcpError.Malformed("Invalid checkout lines")))-        }-        val service = UcpDiscovery.resolve(shopDomain, "dev.ucp.shopping.checkout")-            .getOrElse { return Result.failure(it) }-        return mutate(service, lines, CheckoutInputs(), null, java.util.UUID.randomUUID().toString())-    }--    suspend fun getCheckout(shopDomain: String, checkoutId: String): Result<UcpCheckout> {-        val service = UcpDiscovery.resolve(shopDomain, "dev.ucp.shopping.checkout")-            .getOrElse { return Result.failure(it) }-        return getCheckout(service, checkoutId)-    }--    internal suspend fun getCheckout(service: UcpService, checkoutId: String): Result<UcpCheckout> =-        UcpApi.serviceCall(service, "get_checkout", buildJsonObject { put("id", checkoutId) })-            .mapCatching { parseCheckout(it, service.version, service.capabilities) }--    internal suspend fun mutate(service: UcpService, lines: List<CartLine>, inputs: CheckoutInputs, previous: UcpCheckout?, idempotencyKey: String): Result<UcpCheckout> {-        val arguments = runCatching { mutationArguments(service, lines, inputs, previous, idempotencyKey) }-            .getOrElse { return Result.failure(UcpHttpException(UcpError.Unsupported("These checkout requirements need the merchant website."))) }-        return UcpApi.serviceCall(service, if (previous == null) "create_checkout" else "update_checkout", arguments)-            .mapCatching { parseCheckout(it, service.version, service.capabilities) }-    }--    internal fun mutationArguments(service: UcpService, lines: List<CartLine>, inputs: CheckoutInputs, previous: UcpCheckout?, idempotencyKey: String): JsonObject = buildJsonObject {-        previous?.let { put("id", it.checkoutId) }-        put("checkout", CheckoutProjection.checkout(service.version, lines, inputs, previous, "dev.ucp.shopping.fulfillment" in service.capabilities))-        putJsonObject("meta") { put("idempotency_key", idempotencyKey) }-    }--    internal fun parseCheckout(result: JsonObject, version: String = "2026-08-25", capabilities: Set<String> = emptySet()): UcpCheckout {-        val responseVersion = result["ucp"].asObject()?.text("version")-        if (version !in CheckoutProjection.versions || (responseVersion != null && responseVersion != version)) {-            throw UcpHttpException(UcpError.Malformed("Checkout version mismatch"))-        }-        val id = result.text("id")?.takeIf { it.isNotBlank() }-            ?: throw UcpHttpException(UcpError.Malformed("Missing checkout ID"))-        val status = result.text("status") ?: throw UcpHttpException(UcpError.Malformed("Missing checkout status"))-        if (status !in setOf("incomplete", "requires_escalation", "ready_for_complete", "complete_in_progress", "completed", "canceled")) {-            throw UcpHttpException(UcpError.Malformed("Unknown checkout status"))-        }-        val currency = result.text("currency") ?: throw UcpHttpException(UcpError.Malformed("Missing currency"))-        val entries = result["totals"].asArray()?.map { item ->-            val total = item.asObject() ?: throw UcpHttpException(UcpError.Malformed("Invalid total"))-            val type = total.text("type") ?: throw UcpHttpException(UcpError.Malformed("Missing total type"))-            UcpTotalEntry(type, total.text("display_text") ?: type, Money(-                total.money("amount") ?: throw UcpHttpException(UcpError.Malformed("Missing total amount")), currency,-            ))-        } ?: throw UcpHttpException(UcpError.Malformed("Missing totals"))-        fun required(type: String): Money = entries.singleOrNull { it.type == type }?.money-            ?: throw UcpHttpException(UcpError.Malformed("Expected exactly one $type"))-        return UcpCheckout(-            checkoutId = id,-            status = status,-            currency = currency,-            totals = UcpTotals(subtotal = required("subtotal"), total = required("total")),-            totalEntries = entries,-            continueUrl = result.text("continue_url").orEmpty(),-            expiresAt = result.text("expires_at"),-            messages = result["messages"].asArray()?.mapNotNull { it.asObject()?.let { message ->-                UcpMessage(message.text("type").orEmpty(), message.text("content").orEmpty(), message.text("path"), message.text("code"), message.text("severity"))-            } }.orEmpty(),-            version = version,-            review = parseReview(result, currency, capabilities),-            writableSource = JsonObject(result.filterKeys { it == "line_items" || it == "fulfillment" }),-        )-    }--    private fun parseReview(result: JsonObject, currency: String, capabilities: Set<String>): CheckoutReview {-        val methods = result["fulfillment"].asObject()?.get("methods").asArray().orEmpty()-        val supported = "dev.ucp.shopping.fulfillment" in capabilities-        val available = result["fulfillment"].asObject()?.get("available_methods").asArray().orEmpty()-        val availableShipping = if (!supported) emptyList() else available.filter { it.asObject()?.text("type") == "shipping" }-            .flatMap { it.asObject()?.get("line_item_ids").asArray().orEmpty().mapNotNull { id -> (id as? kotlinx.serialization.json.JsonPrimitive)?.content } }.distinct()-        var reason: String? = null-        if (methods.isEmpty() && available.isNotEmpty() && availableShipping.isEmpty()) reason = "Available fulfillment choices require the merchant website."-        val negotiated = result["ucp"].asObject()?.get("capabilities").asObject()?.keys.orEmpty()-        if (negotiated.any { it !in setOf("dev.ucp.shopping.checkout", "dev.ucp.shopping.fulfillment") }) reason = "This checkout uses additional extensions that require the merchant website."-        if (methods.isNotEmpty() && !supported) reason = "The merchant's fulfillment extension is not supported."-        if (methods.any { it.asObject()?.text("type") != "shipping" }) reason = "This fulfillment method requires the merchant website."-        if (methods.any { it.asObject()?.text("id").isNullOrBlank() || it.asObject()?.get("line_item_ids").asArray().isNullOrEmpty() }) reason = "The merchant's fulfillment identifiers are missing. Use its website."-        if (result["actions"].asArray()?.isNotEmpty() == true || result["actions"].asObject()?.isNotEmpty() == true || result["policies"].asArray()?.isNotEmpty() == true) reason = "Additional merchant requirements must be reviewed on its website."-        val buyerPaths = setOf("first_name", "last_name", "email", "phone_number").map { "$.buyer.$it" }.toSet()-        val addressPath = Regex("^\\$\\.fulfillment\\.methods\\[[0-9]+]\\.destinations\\[[0-9]+]\\.(first_name|last_name|phone_number|street_address|extended_address|address_locality|address_region|address_country|postal_code)$")-        val optionPath = Regex("^\\$\\.fulfillment\\.methods\\[[0-9]+]\\.groups\\[[0-9]+]\\.selected_option_id$")-        if (result["messages"].asArray().orEmpty().any { element ->-            val message = element.asObject()-            val path = message?.text("path").orEmpty()-            message?.text("type") == "error" && (message.text("severity") != "recoverable" || (path !in buyerPaths && !addressPath.matches(path) && !optionPath.matches(path)))-        }) reason = "The merchant requires information or approval that must be provided on its website."-        if (result.text("status") in setOf("requires_escalation", "complete_in_progress", "completed", "canceled")) reason = "Continue on the merchant website. Shop cannot complete or confirm purchases."-        val shipping = if (!supported) emptyList() else methods.mapNotNull { element ->-            val method = element.asObject() ?: return@mapNotNull null-            if (method.text("type") != "shipping") return@mapNotNull null-            val methodId = method.text("id") ?: return@mapNotNull null-            CheckoutShippingMethod(methodId, method["groups"].asArray().orEmpty().mapNotNull groupLoop@ { groupElement ->-                val group = groupElement.asObject() ?: return@groupLoop null-                val groupId = group.text("id") ?: return@groupLoop null-                CheckoutShippingGroup(groupId, group.text("selected_option_id"), group["options"].asArray().orEmpty().mapNotNull optionLoop@ { optionElement ->-                    val option = optionElement.asObject() ?: return@optionLoop null-                    val optionId = option.text("id") ?: return@optionLoop null-                    CheckoutShippingOption(optionId, option.text("title") ?: optionId,-                        option["description"].asObject()?.text("plain") ?: option.text("description").orEmpty(),-                        option["totals"].asArray().orEmpty().mapNotNull { totalElement ->-                            val total = totalElement.asObject() ?: return@mapNotNull null-                            val amount = total.money("amount") ?: return@mapNotNull null-                            UcpTotalEntry(total.text("type").orEmpty(), total.text("display_text") ?: total.text("type").orEmpty(), Money(amount, currency))-                        })-                })-            })-        }-        val links = result["links"].asArray().orEmpty().mapNotNull { element ->-            val link = element.asObject() ?: return@mapNotNull null-            val url = link.text("url")?.let(MerchantUrls::httpsUrl) ?: return@mapNotNull null-            CheckoutLegalLink(link.text("type").orEmpty(), link.text("title") ?: link.text("type").orEmpty(), url)-        }-        if (result["links"].asArray()?.size != links.size) reason = reason ?: "Legal links are missing or unsupported; review terms on the merchant website."-        return CheckoutReview(shipping, links, reason, availableShipping)-    }--    fun splitByShop(lines: List<CartLine>): Map<Pair<String, String>, List<CartLine>> =-        lines.groupBy { Pair(it.platformId, it.shopDomain) }--    fun platformFor(platformId: String): UcpPlatform =-        UcpPlatforms.ALL.firstOrNull { it.id == platformId } ?: UcpPlatforms.GENERIC-}
shop/src/main/java/com/vayunmathur/shop/network/UcpDiscovery.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/network/UcpDiscovery.kt b/shop/src/main/java/com/vayunmathur/shop/network/UcpDiscovery.ktdeleted file mode 100644index 144439227f..0000000000--- a/shop/src/main/java/com/vayunmathur/shop/network/UcpDiscovery.kt+++ /dev/null@@ -1,143 +0,0 @@-package com.vayunmathur.shop.network--import com.vayunmathur.shop.data.UcpError-import com.vayunmathur.shop.domain.MerchantUrls-import kotlinx.coroutines.withTimeout-import kotlinx.serialization.json.JsonObject-import kotlinx.serialization.json.JsonPrimitive-import java.net.URI--/** Selects one self-contained dated profile, never combining its registries with another leaf. */-internal object UcpDiscovery {-    private const val MAX_REDIRECTS = 3-    private val versions = listOf(UcpApi.VERSION, UcpApi.APRIL_VERSION)--    suspend fun resolve(-        shopDomain: String, capability: String, preferredVersion: String? = null,-    ): Result<UcpService> = resolve(shopDomain, capability, preferredVersion, setOf("mcp", "rest"))--    private suspend fun resolve(-        shopDomain: String, capability: String, preferredVersion: String?, transports: Set<String>,-    ): Result<UcpService> = UcpApi.ioCall {-        UcpApi.catching {-            if (preferredVersion != null && preferredVersion !in versions) {-                unsupported("This merchant uses an unsupported UCP version.")-            }-            val shop = MerchantUrls.domain(shopDomain) ?: unsupported("Invalid merchant domain.")-            val transport = UcpApi.transport-            withTimeout(UcpWire.CALL_TIMEOUT_MS) {-                val root = fetch("https://$shop/.well-known/ucp", transport)-                val ucp = root["ucp"].asObject() ?: malformed("Missing UCP profile")-                val alternatives = ucp["supported_versions"].asObject()-                var failure: UcpHttpException? = null-                for (version in preferredVersion?.let(::listOf) ?: versions) {-                    try {-                        val leaf = if (string(ucp, "version") == version) root else {-                            val link = alternatives?.let { string(it, version) } ?: continue-                            fetch(publicUrl(link), transport)-                        }-                        return@withTimeout parseService(leaf, capability, version, transports)-                    } catch (error: UcpHttpException) {-                        failure = error-                    }-                }-                throw failure ?: UcpHttpException(UcpError.Unsupported("This merchant does not offer a supported dated shopping service."))-            }-        }-    }--    /** Compatibility path for checkout callers still using current-version MCP only. */-    suspend fun endpoint(shopDomain: String, capability: String): Result<String> =-        resolve(shopDomain, capability, UcpApi.VERSION, setOf("mcp")).map { it.endpoint }--    private suspend fun fetch(initialUrl: String, transport: UcpTransport): JsonObject {-        var url = publicUrl(initialUrl)-        val visited = mutableSetOf<String>()-        repeat(MAX_REDIRECTS + 1) { hop ->-            if (!visited.add(url)) malformed("Merchant profile redirect loop")-            val response = transport.execute(UcpRequest(-                url = url, headers = mapOf("Accept" to "application/json"), followRedirects = false,-            ))-            if (response.bytes.size > UcpWire.MAX_BODY_BYTES) malformed("Merchant profile exceeds size limit")-            if (response.status in setOf(301, 302, 303, 307, 308)) {-                if (hop == MAX_REDIRECTS) malformed("Too many merchant profile redirects")-                val location = response.headers.entries.firstOrNull { it.key.equals("Location", true) }-                    ?.value?.singleOrNull() ?: malformed("Missing merchant profile redirect target")-                url = publicUrl(runCatching { URI(url).resolve(location).toString() }.getOrNull()-                    ?: malformed("Invalid merchant profile redirect target"))-            } else {-                UcpWire.checkStatus(response.status)-                return runCatching { UcpApi.json.parseToJsonElement(UcpWire.utf8(response.bytes)) as? JsonObject }-                    .getOrNull() ?: malformed("Invalid merchant profile")-            }-        }-        malformed("Too many merchant profile redirects")-    }--    internal fun parseService(-        profile: JsonObject, capability: String, expectedVersion: String,-    ): UcpService = parseService(profile, capability, expectedVersion, setOf("mcp", "rest"))--    private fun parseService(-        profile: JsonObject, capability: String, expectedVersion: String, transports: Set<String>,-    ): UcpService {-        if (expectedVersion !in versions) unsupported("This merchant uses an unsupported UCP version.")-        val ucp = profile["ucp"].asObject() ?: malformed("Missing UCP profile")-        if (string(ucp, "version") != expectedVersion) {-            unsupported("This merchant uses an unsupported UCP version.")-        }-        val capabilities = exactRegistry(ucp, "capabilities", expectedVersion)-        if (capability !in capabilities) unsupported("This merchant does not advertise $capability.")-        val services = ucp["services"].asObject() ?: malformed("Missing service registry")-        val candidates = services["dev.ucp.shopping"].asArray()?.mapNotNull { it.asObject() }.orEmpty()-        var invalidEndpoint = false-        for (service in candidates) {-            val transport = string(service, "transport") ?: continue-            if (string(service, "version") != expectedVersion || transport !in transports) continue-            val endpoint = string(service, "endpoint")?.let { runCatching { publicUrl(it) }.getOrNull() }-            if (endpoint == null || (transport == "rest" && URI(endpoint).query != null)) {-                invalidEndpoint = true-                continue-            }-            return UcpService(-                expectedVersion, transport, endpoint, capabilities,-                paymentHandlerIds(ucp, expectedVersion),-            )-        }-        if (invalidEndpoint) malformed("Invalid advertised endpoint")-        unsupported("This merchant does not offer a supported shopping service.")-    }--    private fun exactRegistry(ucp: JsonObject, name: String, version: String): Set<String> {-        val registry = ucp[name].asObject() ?: malformed("Missing $name registry")-        return registry.entries.filter { (_, entries) ->-            entries.asArray()?.any { it.asObject()?.let { entry -> string(entry, "version") == version } == true } == true-        }.map { it.key }.toSet()-    }--    private fun paymentHandlerIds(ucp: JsonObject, version: String): Set<String> {-        val registry = ucp["payment_handlers"].asObject() ?: malformed("Missing payment_handlers registry")-        return registry.values.flatMap { entries ->-            entries.asArray()?.mapNotNull { entry ->-                val handler = entry.asObject() ?: return@mapNotNull null-                if (string(handler, "version") != version) return@mapNotNull null-                string(handler, "id")?.takeIf { it.isNotBlank() }-            }.orEmpty()-        }.toSet()-    }--    internal fun parseEndpoint(profile: JsonObject, capability: String): String =-        parseService(profile, capability, UcpApi.VERSION, setOf("mcp")).endpoint--    private fun string(o: JsonObject, key: String): String? =-        (o[key] as? JsonPrimitive)?.takeIf { it.isString }?.content--    private fun publicUrl(value: String): String {-        val url = MerchantUrls.httpsUrl(value) ?: malformed("Invalid public HTTPS URL")-        if (URI(url).fragment != null) malformed("Invalid public HTTPS URL")-        return url-    }--    private fun malformed(reason: String): Nothing = throw UcpHttpException(UcpError.Malformed(reason))-    private fun unsupported(reason: String): Nothing = throw UcpHttpException(UcpError.Unsupported(reason))-}
shop/src/main/java/com/vayunmathur/shop/network/UcpMcp.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/network/UcpMcp.kt b/shop/src/main/java/com/vayunmathur/shop/network/UcpMcp.ktdeleted file mode 100644index 54330e8276..0000000000--- a/shop/src/main/java/com/vayunmathur/shop/network/UcpMcp.kt+++ /dev/null@@ -1,202 +0,0 @@-package com.vayunmathur.shop.network--import com.vayunmathur.library.network.NetworkDataStream-import com.vayunmathur.shop.data.UcpError-import com.vayunmathur.shop.domain.MerchantUrls-import kotlinx.coroutines.NonCancellable-import kotlinx.coroutines.withContext-import kotlinx.coroutines.withTimeoutOrNull-import kotlinx.serialization.json.JsonObject-import kotlinx.serialization.json.JsonElement-import kotlinx.serialization.json.buildJsonObject-import kotlinx.serialization.json.put-import kotlinx.serialization.json.putJsonObject-import java.net.URI-import java.util.UUID--internal object UcpMcp {-    private const val MODERN = "2025-03-26"-    private const val LEGACY = "2024-11-05"-    private class LegacyRequired : Exception()--    suspend fun call(wire: UcpTransport, endpoint: String, tool: String, arguments: JsonObject, version: String): JsonObject =-        try { modern(wire, endpoint, tool, arguments, version) }-        catch (_: LegacyRequired) { legacy(wire, endpoint, tool, arguments, version) }--    private fun headers(version: String, session: Map<String, String> = emptyMap()): Map<String, String> = mapOf(-        "UCP-Agent" to "profile=\"${UcpApi.profileUrl(version)}\"",-        "Content-Type" to "application/json",-        "Accept" to "application/json, text/event-stream",-        "Request-Id" to UUID.randomUUID().toString(),-    ) + session--    private fun rpc(method: String, params: JsonObject): JsonObject = buildJsonObject {-        put("jsonrpc", "2.0")-        put("id", UUID.randomUUID().toString())-        put("method", method)-        put("params", params)-    }--    private fun initialize(protocol: String) = rpc("initialize", buildJsonObject {-        put("protocolVersion", protocol)-        putJsonObject("capabilities") {}-        putJsonObject("clientInfo") { put("name", "Shop"); put("version", "0.1") }-    })--    private fun notification() = buildJsonObject {-        put("jsonrpc", "2.0"); put("method", "notifications/initialized")-    }--    private fun toolCall(tool: String, arguments: JsonObject, version: String) = rpc("tools/call", buildJsonObject {-        put("name", tool); put("arguments", UcpApi.withAgentProfile(arguments, version))-    })--    private fun checkEnvelope(value: JsonObject) {-        require(value.text("jsonrpc") == "2.0") { "Invalid JSON-RPC version" }-    }--    private fun checkReply(value: JsonObject, id: JsonElement): JsonObject {-        checkEnvelope(value)-        require(value["id"] == id && value.text("method") == null) { "Mismatched MCP response ID" }-        value["error"]?.let { throw UcpHttpException(UcpError.Rpc("Merchant RPC rejected the request")) }-        require(value["result"].asObject() != null) { "Missing RPC result" }-        return value-    }--    private suspend fun send(wire: UcpTransport, endpoint: String, envelope: JsonObject, headers: Map<String, String>) {-        val request = UcpRequest(endpoint, "POST", headers + ("Request-Id" to UUID.randomUUID().toString()), envelope.toString())-        UcpWire.checkRequest(request)-        wire.stream(request) { _, response ->-            UcpWire.checkStatus(response.status)-        }-    }--    private suspend fun serverMessage(wire: UcpTransport, endpoint: String, value: JsonObject, headers: Map<String, String>) {-        checkEnvelope(value)-        val method = value.text("method") ?: return-        val id = value["id"] ?: return // Notifications do not require replies.-        val reply = buildJsonObject {-            put("jsonrpc", "2.0"); put("id", id)-            if (method == "ping") putJsonObject("result") {}-            else putJsonObject("error") { put("code", -32601); put("message", "Method not supported") }-        }-        send(wire, endpoint, reply, headers)-    }--    private suspend fun awaitReply(-        reader: UcpSse, wire: UcpTransport, endpoint: String, id: JsonElement, headers: Map<String, String>,-    ): JsonObject {-        while (true) {-            val event = reader.next() ?: throw UcpHttpException(UcpError.Transport("MCP stream ended before response"))-            if (event.event != "message") continue-            val value = UcpApi.parseObject(event.data)-            checkEnvelope(value)-            if (value.text("method") != null) serverMessage(wire, endpoint, value, headers)-            else if (value["id"] == id) return checkReply(value, id)-        }-    }--    private suspend fun postReply(-        wire: UcpTransport, endpoint: String, envelope: JsonObject, headers: Map<String, String>,-        initializing: Boolean = false, onHeaders: (Map<String, List<String>>) -> Unit = {},-    ): JsonObject {-        var result: JsonObject? = null-        val request = UcpRequest(endpoint, "POST", headers + ("Request-Id" to UUID.randomUUID().toString()), envelope.toString())-        UcpWire.checkRequest(request)-        wire.stream(request) { stream, response ->-            if (initializing && response.status in setOf(400, 404, 405, 415, 501)) throw LegacyRequired()-            UcpWire.checkStatus(response.status)-            onHeaders(response.headers)-            requireNotNull(stream) { "Missing MCP response" }-            val type = response.header("Content-Type")?.substringBefore(';')?.trim()?.lowercase()-            val id = requireNotNull(envelope["id"])-            result = when (type) {-                "application/json" -> checkReply(UcpApi.parseObject(UcpWire.readBody(stream)), id)-                "text/event-stream" -> {-                    val announcedSession = if (initializing) response.header("Mcp-Session-Id") else null-                    val replyHeaders = headers + (announcedSession?.let { mapOf("Mcp-Session-Id" to it) } ?: emptyMap())-                    awaitReply(UcpSse(stream), wire, endpoint, id, replyHeaders)-                }-                else -> throw UcpHttpException(UcpError.Malformed("Unsupported MCP content type"))-            }-        }-        return requireNotNull(result)-    }--    private suspend fun modern(wire: UcpTransport, endpoint: String, tool: String, arguments: JsonObject, version: String): JsonObject {-        var sessionId: String? = null-        var protocol = MODERN-        try {-            val initialized = postReply(wire, endpoint, initialize(MODERN), headers(version), true) { responseHeaders ->-                sessionId = responseHeaders.entries.firstOrNull { it.key.equals("Mcp-Session-Id", true) }-                    ?.value?.firstOrNull()?.also {-                        require(it.isNotBlank() && it.length <= 1024 && it.all { c -> c.code in 33..126 }) { "Invalid MCP session ID" }-                    }-            }["result"].asObject() ?: error("Missing initialization result")-            protocol = initialized.text("protocolVersion") ?: error("Missing MCP protocol version")-            if (protocol == LEGACY) throw LegacyRequired()-            require(protocol in setOf(MODERN, "2025-06-18", "2025-11-25")) { "Unsupported MCP protocol version" }-            val session = mapOf("MCP-Protocol-Version" to protocol) +-                (sessionId?.let { mapOf("Mcp-Session-Id" to it) } ?: emptyMap())-            val sessionHeaders = headers(version, session)-            send(wire, endpoint, notification(), sessionHeaders)-            val reply = postReply(wire, endpoint, toolCall(tool, arguments, version), sessionHeaders)-            return UcpApi.unwrapResult(reply, version, tool)-        } finally {-            sessionId?.let { id ->-                // Cleanup is best effort, but bounded and independent of caller cancellation.-                withContext(NonCancellable) {-                    withTimeoutOrNull(2_000) {-                        try {-                            wire.stream(UcpRequest(endpoint, "DELETE", headers(version, mapOf(-                                "Mcp-Session-Id" to id, "MCP-Protocol-Version" to protocol,-                            )))) { _, _ -> }-                        } catch (_: Exception) { /* Session expiry is merchant-controlled. */ }-                    }-                }-            }-        }-    }--    internal fun legacyEndpoint(endpoint: String, announcement: String): String {-        val origin = URI(endpoint)-        val target = origin.resolve(announcement)-        require(target.fragment == null && MerchantUrls.httpsUrl(target.toString()) != null &&-            target.scheme.equals(origin.scheme, true) && target.host.equals(origin.host, true) &&-            (target.port == -1 || target.port == 443) && (origin.port == -1 || origin.port == 443)) {-            "Unsafe legacy MCP message endpoint"-        }-        return target.toASCIIString()-    }--    private suspend fun legacy(wire: UcpTransport, endpoint: String, tool: String, arguments: JsonObject, version: String): JsonObject {-        var result: JsonObject? = null-        val baseHeaders = headers(version, mapOf("MCP-Protocol-Version" to LEGACY))-        wire.stream(UcpRequest(endpoint, "GET", baseHeaders + ("Accept" to "text/event-stream"))) { stream, response ->-            UcpWire.checkStatus(response.status)-            require(response.header("Content-Type")?.substringBefore(';')?.trim()?.equals("text/event-stream", true) == true) {-                "Expected legacy MCP event stream"-            }-            val reader = UcpSse(requireNotNull(stream))-            var messageEndpoint: String? = null-            while (messageEndpoint == null) {-                val event = reader.next() ?: error("Missing legacy MCP endpoint announcement")-                if (event.event == "endpoint") messageEndpoint = legacyEndpoint(endpoint, event.data)-                else if (event.event == "message") {-                    val value = UcpApi.parseObject(event.data)-                    checkEnvelope(value)-                    require(value["id"] == null) { "Server request before endpoint announcement" }-                }-            }-            val initializedRequest = initialize(LEGACY)-            send(wire, messageEndpoint, initializedRequest, baseHeaders)-            val initialized = awaitReply(reader, wire, messageEndpoint, requireNotNull(initializedRequest["id"]), baseHeaders)-            require(initialized["result"].asObject()?.text("protocolVersion") == LEGACY) { "Unsupported legacy MCP version" }-            send(wire, messageEndpoint, notification(), baseHeaders)-            val request = toolCall(tool, arguments, version)-            send(wire, messageEndpoint, request, baseHeaders)-            result = UcpApi.unwrapResult(awaitReply(reader, wire, messageEndpoint, requireNotNull(request["id"]), baseHeaders), version, tool)-        }-        return requireNotNull(result)-    }-}
shop/src/main/java/com/vayunmathur/shop/network/UcpPlatforms.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/network/UcpPlatforms.kt b/shop/src/main/java/com/vayunmathur/shop/network/UcpPlatforms.ktindex c250d26ce3..cce12e0197 100644--- a/shop/src/main/java/com/vayunmathur/shop/network/UcpPlatforms.kt+++ b/shop/src/main/java/com/vayunmathur/shop/network/UcpPlatforms.kt@@ -1,6 +1,6 @@ package com.vayunmathur.shop.network -/** Labels only. Merchant endpoint and access permissions must be discovered, not inferred. */+/** Labels only. Merchant endpoint and access permissions are resolved server-side, not inferred. */ data class UcpPlatform(val id: String, val displayName: String, val globalCatalogMcp: String? = null)  object UcpPlatforms {
shop/src/main/java/com/vayunmathur/shop/network/UcpRest.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/network/UcpRest.kt b/shop/src/main/java/com/vayunmathur/shop/network/UcpRest.ktdeleted file mode 100644index 738cbb8d1a..0000000000--- a/shop/src/main/java/com/vayunmathur/shop/network/UcpRest.kt+++ /dev/null@@ -1,63 +0,0 @@-package com.vayunmathur.shop.network--import kotlinx.serialization.json.JsonObject-import java.net.URI-import java.util.UUID--/** Operation paths and direct request bodies from both dated shopping OpenAPI releases. */-internal object UcpRest {-    internal fun request(service: UcpService, tool: String, arguments: JsonObject): UcpRequest {-        val id = arguments.text("id")-        val path = when (tool) {-            "search_catalog" -> "catalog/search"-            "lookup_catalog" -> "catalog/lookup"-            "get_product" -> "catalog/product"-            "create_checkout" -> "checkout-sessions"-            "get_checkout", "update_checkout" -> {-                require(!id.isNullOrBlank()) { "Missing checkout ID" }-                // Encode one opaque path segment, not a URI or additional operation path.-                val segment = java.net.URLEncoder.encode(id, "UTF-8").replace("+", "%20").replace(".", "%2E")-                "checkout-sessions/$segment"-            }-            else -> error("Unsupported REST operation")-        }-        val method = when (tool) { "get_checkout" -> "GET"; "update_checkout" -> "PUT"; else -> "POST" }-        val body = when (tool) {-            "get_checkout" -> null-            "create_checkout", "update_checkout" -> requireNotNull(arguments["checkout"].asObject()) { "Missing checkout body" }-            else -> requireNotNull(arguments["catalog"].asObject()) { "Missing catalog body" }-        }-        val endpoint = URI(service.endpoint)-        require(endpoint.rawQuery == null && endpoint.rawFragment == null) { "Invalid REST base endpoint" }-        val headers = mutableMapOf(-            "UCP-Agent" to "profile=\"${UcpApi.profileUrl(service.version)}\"",-            "Request-Id" to UUID.randomUUID().toString(),-            "Accept" to "application/json",-            "Content-Type" to "application/json",-        )-        val meta = arguments["meta"].asObject()-        val key = meta?.text("idempotency_key") ?: meta?.text("idempotency-key")-        require(tool !in setOf("create_checkout", "update_checkout") || !key.isNullOrBlank()) {-            "Checkout writes require a caller-provided idempotency key"-        }-        if (key != null) {-            require(key.isNotBlank() && key.length <= 256) { "Invalid idempotency key" }-            headers["Idempotency-Key"] = key-        }-        return UcpRequest(service.endpoint.trimEnd('/') + "/" + path, method, headers, body?.toString())-            .also(UcpWire::checkRequest)-    }--    suspend fun call(wire: UcpTransport, service: UcpService, tool: String, arguments: JsonObject): JsonObject {-        var result: JsonObject? = null-        wire.stream(request(service, tool, arguments)) { stream, response ->-            UcpWire.checkStatus(response.status)-            require(response.header("Content-Type")?.substringBefore(';')?.trim()?.equals("application/json", true) == true) {-                "Expected JSON REST response"-            }-            requireNotNull(stream) { "Missing REST response" }-            result = UcpApi.validateResult(UcpApi.parseObject(UcpWire.readBody(stream)), service.version, tool)-        }-        return requireNotNull(result)-    }-}
shop/src/main/java/com/vayunmathur/shop/network/UcpService.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/network/UcpService.kt b/shop/src/main/java/com/vayunmathur/shop/network/UcpService.ktdeleted file mode 100644index 3306f52001..0000000000--- a/shop/src/main/java/com/vayunmathur/shop/network/UcpService.kt+++ /dev/null@@ -1,9 +0,0 @@-package com.vayunmathur.shop.network--internal data class UcpService(-    val version: String,-    val transport: String,-    val endpoint: String,-    val capabilities: Set<String>,-    val paymentHandlerIds: Set<String>,-)
shop/src/main/java/com/vayunmathur/shop/network/UcpSse.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/network/UcpSse.kt b/shop/src/main/java/com/vayunmathur/shop/network/UcpSse.ktdeleted file mode 100644index 95c79a28c8..0000000000--- a/shop/src/main/java/com/vayunmathur/shop/network/UcpSse.kt+++ /dev/null@@ -1,81 +0,0 @@-package com.vayunmathur.shop.network--import com.vayunmathur.library.network.NetworkDataStream-import kotlinx.coroutines.currentCoroutineContext-import kotlinx.coroutines.ensureActive-import java.io.ByteArrayOutputStream--internal data class UcpSseEvent(val event: String, val data: String)--/** Byte framing preserves split UTF-8 characters and supports LF, CRLF and CR. */-internal class UcpSse(private val stream: NetworkDataStream) {-    private val buffer = ByteArray(4096)-    private var position = 0-    private var available = 0-    private var total = 0-    private var events = 0-    private var skipLf = false--    private suspend fun byte(): Int {-        currentCoroutineContext().ensureActive()-        if (position == available) {-            available = stream.read(buffer)-            position = 0-            if (available < 0) return -1-            require(available > 0) { "SSE stream made no read progress" }-            total += available-            require(total <= UcpWire.MAX_BODY_BYTES) { "SSE body exceeds limit" }-        }-        return buffer[position++].toInt() and 255-    }--    private suspend fun line(): String? {-        val out = ByteArrayOutputStream()-        while (true) {-            val b = byte()-            if (skipLf) {-                skipLf = false-                if (b == 10) continue-            }-            if (b < 0) {-                require(out.size() == 0) { "Truncated SSE line" }-                return null-            }-            if (b == 13 || b == 10) {-                skipLf = b == 13-                return UcpWire.utf8(out.toByteArray())-            }-            require(out.size() < UcpWire.MAX_EVENT_BYTES) { "SSE line exceeds limit" }-            out.write(b)-        }-    }--    suspend fun next(): UcpSseEvent? {-        var event = "message"-        val data = StringBuilder()-        var size = 0-        var hasData = false-        while (true) {-            val line = line() ?: run {-                require(!hasData) { "Truncated SSE event" }-                return null-            }-            size += line.toByteArray(Charsets.UTF_8).size + 1-            require(size <= UcpWire.MAX_EVENT_BYTES) { "SSE event exceeds limit" }-            if (line.isEmpty()) {-                require(++events <= UcpWire.MAX_EVENTS) { "Too many SSE events" }-                if (hasData) return UcpSseEvent(event.ifEmpty { "message" }, data.toString().removeSuffix("\n"))-                event = "message"-                size = 0-                continue-            }-            if (line.startsWith(':')) continue-            val field = line.substringBefore(':')-            val value = if (line.contains(':')) line.substringAfter(':').removePrefix(" ") else ""-            when (field) {-                "event" -> event = value-                "data" -> { hasData = true; data.append(value).append('\n') }-            }-        }-    }-}
shop/src/main/java/com/vayunmathur/shop/network/UcpTransport.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/network/UcpTransport.kt b/shop/src/main/java/com/vayunmathur/shop/network/UcpTransport.ktdeleted file mode 100644index 3849329161..0000000000--- a/shop/src/main/java/com/vayunmathur/shop/network/UcpTransport.kt+++ /dev/null@@ -1,82 +0,0 @@-package com.vayunmathur.shop.network--import com.vayunmathur.library.network.NetworkClient-import com.vayunmathur.library.network.NetworkDataStream-import com.vayunmathur.library.network.RawResponse-import com.vayunmathur.library.network.SimpleResponse-import com.vayunmathur.shop.data.UcpError-import kotlinx.coroutines.currentCoroutineContext-import kotlinx.coroutines.ensureActive-import java.io.ByteArrayOutputStream-import java.nio.ByteBuffer-import java.nio.charset.CodingErrorAction--internal data class UcpRequest(-    val url: String,-    val method: String = "GET",-    val headers: Map<String, String> = emptyMap(),-    val body: String? = null,-    val followRedirects: Boolean = false,-)--internal interface UcpTransport {-    suspend fun execute(request: UcpRequest): RawResponse-    suspend fun stream(request: UcpRequest, block: suspend (NetworkDataStream?, SimpleResponse) -> Unit): SimpleResponse-}--internal object UcpNetworkTransport : UcpTransport {-    override suspend fun execute(request: UcpRequest): RawResponse {-        // Buffer through the capped streaming reader: shared execute's binary path is unbounded.-        var bytes = ByteArray(0)-        val response = stream(request) { input, response ->-            bytes = if (input == null) response.body.toByteArray(Charsets.UTF_8)-                else UcpWire.readBody(input).toByteArray(Charsets.UTF_8)-            require(bytes.size <= UcpWire.MAX_BODY_BYTES) { "Merchant body exceeds limit" }-        }-        return RawResponse(response.status, response.statusMessage, bytes, response.headers, response.url)-    }--    override suspend fun stream(request: UcpRequest, block: suspend (NetworkDataStream?, SimpleResponse) -> Unit): SimpleResponse {-        UcpWire.checkRequest(request)-        return NetworkClient.stream(-            request.url, request.method, request.headers, request.body,-            connectTimeoutMs = 10_000, readTimeoutMs = 10_000,-            followRedirects = request.followRedirects, block = block,-        )-    }-}--internal object UcpWire {-    const val MAX_BODY_BYTES = 1024 * 1024-    const val MAX_EVENT_BYTES = 64 * 1024-    const val MAX_EVENTS = 256-    const val CALL_TIMEOUT_MS = 30_000L--    fun checkRequest(request: UcpRequest) {-        require((request.body?.toByteArray(Charsets.UTF_8)?.size ?: 0) <= MAX_BODY_BYTES) { "Request exceeds limit" }-        require(request.headers.values.none { it.contains('\r') || it.contains('\n') }) { "Invalid request header" }-    }--    fun checkStatus(status: Int) {-        if (status !in 200..299) throw UcpHttpException(-            if (status == 429) UcpError.RateLimited(null) else UcpError.Http(status, ""),-        )-    }--    fun utf8(bytes: ByteArray): String = Charsets.UTF_8.newDecoder()-        .onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT)-        .decode(ByteBuffer.wrap(bytes)).toString().removePrefix("\uFEFF")--    suspend fun readBody(stream: NetworkDataStream): String {-        val out = ByteArrayOutputStream()-        val buffer = ByteArray(4096)-        while (true) {-            currentCoroutineContext().ensureActive()-            val count = stream.read(buffer)-            if (count < 0) break-            require(out.size() + count <= MAX_BODY_BYTES) { "Merchant body exceeds limit" }-            out.write(buffer, 0, count)-        }-        return utf8(out.toByteArray())-    }-}
shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt b/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.ktindex cecfc45821..593a165dea 100644--- a/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt+++ b/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt@@ -18,14 +18,16 @@ import com.vayunmathur.shop.data.UcpCheckout import com.vayunmathur.shop.data.UcpProduct import com.vayunmathur.shop.data.message import com.vayunmathur.shop.domain.MerchantUrls-import com.vayunmathur.shop.network.UcpCatalog-import com.vayunmathur.shop.network.UcpCheckoutApi-import com.vayunmathur.shop.network.UcpHttpException-import com.vayunmathur.shop.network.UcpPlatforms+import com.vayunmathur.shop.network.ShopBackend+import com.vayunmathur.shop.network.ShopBackendException+import com.vayunmathur.shop.network.ShopHttpBackend+import com.vayunmathur.shop.network.splitByShop import kotlinx.coroutines.launch  /** Session catalog state plus persisted cart and pending checkout history. */-class ShopViewModel : ViewModel() {+class ShopViewModel(+    private val backend: ShopBackend = ShopHttpBackend,+) : ViewModel() {     var query by mutableStateOf("")         private set     var searchShopDomain by mutableStateOf("")@@ -99,11 +101,9 @@ class ShopViewModel : ViewModel() {         viewModelScope.launch {             try {                 AppInit.awaitReady()-                val response = if (shop == null) UcpCatalog.search(q)-                    else UcpCatalog.searchStore(UcpPlatforms.GENERIC, shop, q)-                response.fold(+                backend.search(q, shop).fold(                     onSuccess = { results = it },-                    onFailure = { searchError = it.toUcpMessage() },+                    onFailure = { searchError = it.toBackendMessage() },                 )             } finally {                 searching = false@@ -111,7 +111,7 @@ class ShopViewModel : ViewModel() {         }     } -    fun addToCart(product: UcpProduct, variantId: String, quantity: Int, context: Context) {+    fun addToCart(product: com.vayunmathur.shop.data.UcpProduct, variantId: String, quantity: Int, context: Context) {         val variant = product.variants.firstOrNull { it.id == variantId } ?: return         if (!variant.available || !product.checkoutEligible || quantity !in 1..99) return         val existing = cart.indexOfFirst {@@ -156,7 +156,7 @@ class ShopViewModel : ViewModel() {         viewModelScope.launch {             try {                 AppInit.awaitReady()-                for ((key, lines) in UcpCheckoutApi.splitByShop(snapshot)) {+           

Diff truncated.