Modern Apps git

← Modern-Apps.git

shop: add UCP discovery, streaming and checkout review

Commit
c38b815f96250b318560f3cbd55f94b04ff1edcb
Author
vayun-mathur <[email protected]>
When
2026-10-26 18:38 UTC (1 month ago)
Parents
64a9cd7

Diff

.github/ISSUE_TEMPLATE/bug_report.yml
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlindex e21d9f4dec..84cec78bc7 100644--- a/.github/ISSUE_TEMPLATE/bug_report.yml+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -57,6 +57,7 @@ body:         - screentime         - setupwizard         - share+        - shop         - securemail         - solitaire         - speech
.github/ISSUE_TEMPLATE/feature_request.yml
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.ymlindex 8257f36126..72d663b8bd 100644--- a/.github/ISSUE_TEMPLATE/feature_request.yml+++ b/.github/ISSUE_TEMPLATE/feature_request.yml@@ -57,6 +57,7 @@ body:         - screentime         - setupwizard         - share+        - shop         - securemail         - solitaire         - speech
.github/workflows/issue_labeler.yml
diff --git a/.github/workflows/issue_labeler.yml b/.github/workflows/issue_labeler.ymlindex eb847fa7d9..c0e28cbd97 100644--- a/.github/workflows/issue_labeler.yml+++ b/.github/workflows/issue_labeler.yml@@ -21,7 +21,7 @@ jobs:              if (match && match[1]) {               const selectedApp = match[1].trim().toLowerCase();-              const validApps = ['appstore', 'arrows', 'astronomy', 'auto', 'backup', 'calculator', 'calendar', 'camera', 'cast', 'chess', 'clock', 'code', 'communicate', 'contacts', 'education', 'email', 'emergency', 'euicc', 'everysync', 'files', 'findfamily', 'flashcards', 'fooddelivery', 'globalesim', 'health', 'hub', 'kart', 'keyboard', 'launcher', 'logicgate', 'logviewer', 'maps', 'measure', 'minesweeper', 'music', 'networklocation', 'nonogram', 'notes', 'office', 'openassistant', 'passwords', 'pdf', 'photos', 'pipes', 'parentalcontrols', 'screentime', 'setupwizard', 'share', 'securemail', 'solitaire', 'speech', 'sudoku', 'taxi', 'things', 'todo', 'translate', 'travel', 'tuner', 'unblockjam', 'uniflix', 'updater', 'vpn', 'watch', 'voxels', 'weather', 'web', 'wordmaker', 'youpipe'];+              const validApps = ['appstore', 'arrows', 'astronomy', 'auto', 'backup', 'calculator', 'calendar', 'camera', 'cast', 'chess', 'clock', 'code', 'communicate', 'contacts', 'education', 'email', 'emergency', 'euicc', 'everysync', 'files', 'findfamily', 'flashcards', 'fooddelivery', 'globalesim', 'health', 'hub', 'kart', 'keyboard', 'launcher', 'logicgate', 'logviewer', 'maps', 'measure', 'minesweeper', 'music', 'networklocation', 'nonogram', 'notes', 'office', 'openassistant', 'passwords', 'pdf', 'photos', 'pipes', 'parentalcontrols', 'screentime', 'setupwizard', 'share', 'shop', 'securemail', 'solitaire', 'speech', 'sudoku', 'taxi', 'things', 'todo', 'translate', 'travel', 'tuner', 'unblockjam', 'uniflix', 'updater', 'vpn', 'watch', 'voxels', 'weather', 'web', 'wordmaker', 'youpipe'];                if (validApps.includes(selectedApp)) {                 await github.rest.issues.addLabels({
README.md
diff --git a/README.md b/README.mdindex 5d216c0fa2..e0dad1541c 100644--- a/README.md+++ b/README.md@@ -84,6 +84,7 @@ Though some apps may have exceptions, generally a 64-bit device running at least | **PDF Reader** | MA-1 | [Homepage](https://maproj.org/apps/pdf) | [![F-Droid](https://img.shields.io/badge/F--Droid-Download-blue?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.pdf) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.maproj.org/obtainium-link?name=PDF&packageName=com.vayunmathur.pdf&apk=pdf-release.apk) | | **Photos** | MA-1 | [Homepage](https://maproj.org/apps/photos) | [![F-Droid](https://img.shields.io/badge/F--Droid-Download-blue?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.photos) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.maproj.org/obtainium-link?name=Photos&packageName=com.vayunmathur.photos&apk=photos-release.apk) | | **Share** | MA-2 | [Homepage](https://maproj.org/apps/share) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.share/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.maproj.org/obtainium-link?name=Share&packageName=com.vayunmathur.share&apk=share-release.apk) |+| **Shop** | MA-E | [Homepage](https://maproj.org/apps/shop) | In Progress | In Progress | | **SecureMail** | MA-1 | [Homepage](https://maproj.org/apps/securemail) | In Progress | In Progress | | **Speech Recognizer** | MA-2 | [Homepage](https://maproj.org/apps/speech) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.speech/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.maproj.org/obtainium-link?name=Speech%20Recognizer&packageName=com.vayunmathur.speech&apk=speech-release.apk) | | **Taxi (US and Canada only)** | MA-E | [Homepage](https://maproj.org/apps/taxi) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.taxi/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.maproj.org/obtainium-link?name=Taxi&packageName=com.vayunmathur.taxi&apk=taxi-release.apk) |
library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt
diff --git a/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt b/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.ktindex becbbcf1c4..44a5bbfd01 100644--- a/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt+++ b/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt@@ -3,6 +3,9 @@ package com.vayunmathur.library.network import android.content.Context import com.vayunmathur.library.log.Log import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.NonCancellable+import kotlinx.coroutines.currentCoroutineContext+import kotlinx.coroutines.ensureActive import kotlinx.coroutines.withContext import kotlinx.serialization.DeserializationStrategy import kotlinx.serialization.ExperimentalSerializationApi@@ -339,53 +342,66 @@ object NetworkClient {         readTimeoutMs: Long? = connectTimeoutMs,         sslSocketFactory: SSLSocketFactory? = null,         useSystemTrust: Boolean = false,+        followRedirects: Boolean = true,         block: suspend (stream: NetworkDataStream?, response: SimpleResponse) -> Unit,     ): SimpleResponse {-        val response = HttpUrlEngine.openResponse(-            url, method, headers, HttpUrlEngine.toBodyBytes(body),-            followRedirects = true, connectTimeoutMs = connectTimeoutMs, readTimeoutMs = readTimeoutMs,-            sslSocketFactory = resolveFactory(sslSocketFactory, useSystemTrust),-            // This entry point has always let connect failures surface as they are.-            wrapConnectErrors = false,-        )--        var simple = SimpleResponse(response.status, response.statusMessage, "", response.headers, response.finalUrl)--        if (simple.isSuccess || simple.status == STATUS_PARTIAL_CONTENT) {-            if (!response.hasStream) {-                withContext(Dispatchers.IO) { response.close() }-                block(null, simple)-                return simple+        var ownedResponse: HttpUrlEngine.OpenResponse? = null+        suspend fun closeResponse() = withContext(NonCancellable + Dispatchers.IO) {+            ownedResponse?.close()+            ownedResponse = null+        }+        try {+            currentCoroutineContext().ensureActive()+            val response = withContext(NonCancellable + Dispatchers.IO) {+                // Shield acquisition until ownership is recorded; socket timeouts still apply.+                HttpUrlEngine.openResponse(+                    url, method, headers, HttpUrlEngine.toBodyBytes(body),+                    followRedirects = followRedirects, connectTimeoutMs = connectTimeoutMs, readTimeoutMs = readTimeoutMs,+                    sslSocketFactory = resolveFactory(sslSocketFactory, useSystemTrust),+                    // This entry point has always let connect failures surface as they are.+                    wrapConnectErrors = false,+                ).also { ownedResponse = it }             }-            val raw = response.stream-            var closed = false-            val streamObj = object : NetworkDataStream {-                override val isClosedForRead: Boolean get() = closed-                override suspend fun read(buffer: ByteArray, offset: Int, length: Int): Int =-                    withContext(Dispatchers.IO) {-                        try {-                            val n = raw.read(buffer, offset, length)-                            if (n == -1) closed = true-                            n-                        } catch (_: java.io.IOException) {-                            closed = true-                            -1+            currentCoroutineContext().ensureActive()+            var simple = SimpleResponse(response.status, response.statusMessage, "", response.headers, response.finalUrl)+            if (simple.isSuccess || simple.status == STATUS_PARTIAL_CONTENT) {+                if (!response.hasStream) {+                    closeResponse()+                    block(null, simple)+                    return simple+                }+                val raw = response.stream+                var closed = false+                val streamObj = object : NetworkDataStream {+                    override val isClosedForRead: Boolean get() = closed+                    override suspend fun read(buffer: ByteArray, offset: Int, length: Int): Int =+                        withContext(Dispatchers.IO) {+                            try {+                                val n = raw.read(buffer, offset, length)+                                if (n == -1) closed = true+                                n+                            } catch (_: java.io.IOException) {+                                closed = true+                                -1+                            }                         }-                    }-            }-            try {+                }                 block(streamObj, simple)-            } finally {-                withContext(Dispatchers.IO) { response.close() }-            }-        } else {-            val errorBody = withContext(Dispatchers.IO) {-                response.use { readErrorPrefix(it.stream, ERROR_PREFIX_BYTES) }+            } else {+                val errorBody = withContext(Dispatchers.IO) {+                    try {+                        readErrorPrefix(response.stream, ERROR_PREFIX_BYTES)+                    } finally {+                        closeResponse()+                    }+                }+                simple = simple.copy(body = errorBody)+                block(null, simple)             }-            simple = simple.copy(body = errorBody)-            block(null, simple)+            return simple+        } finally {+            closeResponse()         }-        return simple     }      /**
library/network/src/test/java/com/vayunmathur/library/network/NetworkClientStreamTest.kt
diff --git a/library/network/src/test/java/com/vayunmathur/library/network/NetworkClientStreamTest.kt b/library/network/src/test/java/com/vayunmathur/library/network/NetworkClientStreamTest.ktnew file mode 100644index 0000000000..1c01d21009--- /dev/null+++ b/library/network/src/test/java/com/vayunmathur/library/network/NetworkClientStreamTest.kt@@ -0,0 +1,194 @@+package com.vayunmathur.library.network++import com.sun.net.httpserver.HttpServer+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Job+import kotlinx.coroutines.awaitCancellation+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import java.io.ByteArrayInputStream+import java.io.InputStream+import java.net.HttpURLConnection+import java.net.InetSocketAddress+import java.net.URL+import java.net.URLConnection+import java.net.URLStreamHandler+import java.util.UUID+import java.util.concurrent.ConcurrentHashMap+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import java.util.concurrent.atomic.AtomicInteger+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue++class NetworkClientStreamTest {+    @Test+    fun defaultRedirectsArePreservedAndOptOutDoesNotForwardBody() = runBlocking {+        val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)+        val destinationHits = AtomicInteger()+        val base = "http://127.0.0.1:${server.address.port}"+        server.createContext("/redirect") { exchange ->+            exchange.requestBody.use { it.readBytes() }+            exchange.responseHeaders.add("Location", "$base/destination")+            exchange.sendResponseHeaders(307, -1)+            exchange.close()+        }+        server.createContext("/destination") { exchange ->+            destinationHits.incrementAndGet()+            exchange.requestBody.use { it.readBytes() }+            exchange.sendResponseHeaders(200, 2)+            exchange.responseBody.use { it.write("ok".toByteArray()) }+        }+        server.start()+        try {+            val default = NetworkClient.stream("$base/redirect", connectTimeoutMs = 1000) { input, _ ->+                assertEquals(2, input!!.read(ByteArray(8)))+            }+            assertEquals(200, default.status)+            assertEquals("$base/destination", default.url)+            assertEquals(1, destinationHits.get())+            val suppressed = NetworkClient.stream(+                "$base/redirect", method = "POST", body = "buyer-private-data",+                followRedirects = false, connectTimeoutMs = 1000,+            ) { input, response ->+                assertEquals(307, response.status)+                assertEquals(null, input)+            }+            assertEquals("$base/redirect", suppressed.url)+            assertEquals(1, destinationHits.get())+        } finally { server.stop(0) }+    }++    @Test+    fun closesAndDisconnectsAfterSuccessOrCallbackFailure() = runBlocking {+        val success = FakeConnection()+        NetworkClient.stream(register(success)) { input, _ -> assertEquals(1, input!!.read(ByteArray(1))) }+        assertTrue(success.closed)+        assertTrue(success.disconnected)+        val failed = FakeConnection()+        assertFailsWith<IllegalStateException> {+            NetworkClient.stream(register(failed)) { _, _ -> error("parser failure") }+        }+        assertTrue(failed.closed)+        assertTrue(failed.disconnected)+    }++    @Test+    fun cancelledCallbackStillClosesAndDisconnects() = runBlocking {+        val connection = FakeConnection()+        val opened = CompletableDeferred<Unit>()+        val job = launch {+            NetworkClient.stream(register(connection)) { _, _ ->+                opened.complete(Unit)+                awaitCancellation()+            }+        }+        opened.await()+        assertFalse(connection.closed)+        job.cancel()+        job.join()+        assertTrue(connection.closed)+        assertTrue(connection.disconnected)+    }++    @Test+    fun parentCancellationClosesLegacyStyleGetAndNestedPost() = runBlocking {+        val get = FakeConnection()+        val post = FakeConnection()+        val parent = Job(coroutineContext[Job])+        val nested = CompletableDeferred<Unit>()+        val child = CoroutineScope(coroutineContext + parent).launch {+            NetworkClient.stream(+                register(get), headers = mapOf("Accept" to "text/event-stream"), followRedirects = false,+            ) { input, _ ->+                assertEquals(1, input!!.read(ByteArray(1)))+                NetworkClient.stream(register(post), method = "POST", followRedirects = false) { _, _ ->+                    nested.complete(Unit)+                    awaitCancellation()+                }+            }+        }+        try {+            nested.await()+            assertFalse(get.closed)+            assertFalse(post.closed)+            parent.cancel()+            child.join()+            assertTrue(child.isCancelled)+            assertTrue(get.closed && get.disconnected)+            assertTrue(post.closed && post.disconnected)+        } finally {+            parent.cancel()+            child.join()+        }+    }++    @Test+    fun parentCancellationDuringResponseAcquisitionStillClosesAndDisconnects() = runBlocking {+        val acquiring = CompletableDeferred<Unit>()+        val release = CountDownLatch(1)+        val connection = FakeConnection(onStatus = {+            acquiring.complete(Unit)+            check(release.await(5, TimeUnit.SECONDS)) { "Acquisition test barrier timed out" }+        })+        val parent = Job(coroutineContext[Job])+        var callbackEntered = false+        val child = CoroutineScope(coroutineContext + parent).launch {+            NetworkClient.stream(register(connection), followRedirects = false) { _, _ -> callbackEntered = true }+        }+        try {+            acquiring.await()+            parent.cancel()+            release.countDown()+            child.join()+            assertTrue(child.isCancelled)+            assertFalse(callbackEntered)+            assertTrue(connection.closed)+            assertTrue(connection.disconnected)+        } finally {+            release.countDown()+            parent.cancel()+            child.join()+        }+    }++    private class FakeConnection(private val onStatus: () -> Unit = {}) : HttpURLConnection(URL("http://example.test/stream")) {+        @Volatile var closed = false+        @Volatile var disconnected = false+        private val input = object : ByteArrayInputStream(byteArrayOf(1, 2, 3)) {+            override fun close() { closed = true; super.close() }+        }+        override fun connect() = Unit+        override fun disconnect() { disconnected = true }+        override fun usingProxy(): Boolean = false+        override fun getResponseCode(): Int { onStatus(); return 200 }+        override fun getResponseMessage(): String = "OK"+        override fun getHeaderFields(): Map<String, List<String>> = emptyMap()+        override fun getHeaderField(name: String): String? = null+        override fun getInputStream(): InputStream = input+    }++    companion object {+        private val connections = ConcurrentHashMap<String, FakeConnection>()+        private val installed = run {+            // A unique test-only scheme leaves HTTP/HTTPS and other test engines untouched.+            URL.setURLStreamHandlerFactory { protocol ->+                if (protocol != "ucpstreamtest") null else object : URLStreamHandler() {+                    override fun openConnection(url: URL): URLConnection =+                        requireNotNull(connections.remove(url.toString()))+                }+            }+            true+        }+        private fun register(connection: FakeConnection): String {+            check(installed)+            val url = "ucpstreamtest://example.test/${UUID.randomUUID()}"+            connections[url] = connection+            return url+        }+    }+}
metadata_data/photos/shop/phone/1.png
diff --git a/metadata_data/photos/shop/phone/1.png b/metadata_data/photos/shop/phone/1.pngnew file mode 100644index 0000000000..d6800e4b40Binary files /dev/null and b/metadata_data/photos/shop/phone/1.png differ
metadata_data/photos/shop/phone/2.png
diff --git a/metadata_data/photos/shop/phone/2.png b/metadata_data/photos/shop/phone/2.pngnew file mode 100644index 0000000000..8e30e64895Binary files /dev/null and b/metadata_data/photos/shop/phone/2.png differ
metadata_data/photos/shop/phone/3.png
diff --git a/metadata_data/photos/shop/phone/3.png b/metadata_data/photos/shop/phone/3.pngnew file mode 100644index 0000000000..a11b3cceafBinary files /dev/null and b/metadata_data/photos/shop/phone/3.png differ
metadata_data/photos/shop/phone/4.png
diff --git a/metadata_data/photos/shop/phone/4.png b/metadata_data/photos/shop/phone/4.pngnew file mode 100644index 0000000000..a5a543a12dBinary files /dev/null and b/metadata_data/photos/shop/phone/4.png differ
metadata_data/shop.md
diff --git a/metadata_data/shop.md b/metadata_data/shop.mdnew file mode 100644index 0000000000..0343d07c3a--- /dev/null+++ b/metadata_data/shop.md@@ -0,0 +1,11 @@+Discover UCP merchants and review shopping checkouts++Shop supports shopping through compatible merchants that advertise Universal Commerce Protocol services. Search Shopify Global Catalog where anonymous access is available, enter a merchant domain, or explicitly browse the public UCPList merchant directory.++Shop checks each merchant's live profile instead of guessing API addresses. Supported dated profiles use REST or negotiated MCP services, including JSON and supported streaming responses. Directory listings and badges are discovery leads, not a promise of access or payment authorization.++Refresh products before adding available integer-quantity variants to the cart. Keep merchant and currency totals separate, review merchant-returned buyer and fulfillment requirements, and see authoritative checkout totals and legal links where supported.++Payment continues on the merchant's site. Checkout sessions remain pending and cart items stay intact through browser handoffs or partial failures. Preparing a session or reopening a checkout link does not confirm a paid order.++Native payment completion requires a supported payment handler, provider approval and authorized merchant access. It is not enabled without those prerequisites; unsupported merchant requirements fall back to the merchant's website.
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 68c9c39b2f..907d06dd01 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -112,6 +112,7 @@ include(":communicate") include(":euicc") include(":globalesim") include(":backup")+include(":shop") include(":share") include(":launcher") include(":cast")
shop/AGENTS.md
diff --git a/shop/AGENTS.md b/shop/AGENTS.mdnew file mode 100644index 0000000000..6a4f1cc891--- /dev/null+++ b/shop/AGENTS.md@@ -0,0 +1,36 @@+# Shop (:shop)++Scope: this module plus library/network, library/image and library/ui as needed.+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.+- 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.+- No raw card entry, wallet tokenization, completion or authenticated order-read integration while provider authorization is unavailable.+- Only supported integer quantities can be added. Product refresh must succeed before cart actions.+- Product responses remain session-scoped; persisted cart snapshots omit remote image URLs.+- Merchant image hosts and cdn.shopify.com are allowed; other image hosts are dropped.+- 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.+- 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.++## Verify+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.+Never borrow a third party's profile, infer permissions from platform labels, or assert that every directory entry interoperates.
shop/build.gradle.kts
diff --git a/shop/build.gradle.kts b/shop/build.gradle.ktsnew file mode 100644index 0000000000..5a205d124f--- /dev/null+++ b/shop/build.gradle.kts@@ -0,0 +1,26 @@+plugins {+    id("common-conventions-app")+    // Listing screenshots come from Compose previews (src/screenshotTest), not from an+    // instrumented test on a device. Same `:shop:metadata` task name either way.+    id("common-conventions-preview-metadata")+}++launcherIcon {+    symbol = "shopping_bag"+}++android {+    defaultConfig {+        applicationId = "com.vayunmathur.shop"+    }+}++dependencies {+    // Shopify UCP endpoints (myshopify.com, catalog.shopify.com, cdn.shopify.com)+    // serve public-CA chains: STANDARD, not FIRST_PARTY.+    implementation(project(":library:network"))+    // Product images over the platform HTTP stack.+    implementation(project(":library:image"))+    // Hosted-checkout fallback (continue_url) in a Custom Tab.+    implementation(libs.androidx.browser)+}
shop/src/main/AndroidManifest.xml
diff --git a/shop/src/main/AndroidManifest.xml b/shop/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..ad74918447--- /dev/null+++ b/shop/src/main/AndroidManifest.xml@@ -0,0 +1,27 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++    <uses-permission android:name="android.permission.INTERNET" />+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />++    <application+        android:allowBackup="false"+        android:dataExtractionRules="@xml/data_extraction_rules"+        android:icon="@mipmap/ic_launcher"+        android:roundIcon="@mipmap/ic_launcher"+        android:label="@string/app_name"+        android:supportsRtl="true"+        android:theme="@style/Theme.General">+        <activity+            android:name=".MainActivity"+            android:exported="true"+            android:launchMode="singleTop"+            android:theme="@style/Theme.General">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+            </intent-filter>+        </activity>+    </application>++</manifest>
shop/src/main/java/com/vayunmathur/shop/MainActivity.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/MainActivity.kt b/shop/src/main/java/com/vayunmathur/shop/MainActivity.ktnew file mode 100644index 0000000000..0963f05092--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/MainActivity.kt@@ -0,0 +1,21 @@+package com.vayunmathur.shop++import androidx.activity.viewModels+import androidx.compose.runtime.Composable+import com.vayunmathur.library.ui.MaActivity+import com.vayunmathur.shop.platform.AppInit+import com.vayunmathur.shop.platform.ShopViewModel++class MainActivity : MaActivity() {+    private val viewModel: ShopViewModel by viewModels()++    override fun onCreateBeforeContent() {+        // Trust-bundle warm-up off the main thread; screens await AppInit.awaitReady().+        AppInit.start(this)+    }++    @Composable+    override fun Content() {+        Navigation(viewModel)+    }+}
shop/src/main/java/com/vayunmathur/shop/Navigation.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/Navigation.kt b/shop/src/main/java/com/vayunmathur/shop/Navigation.ktnew file mode 100644index 0000000000..2ffc3123d7--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/Navigation.kt@@ -0,0 +1,44 @@+package com.vayunmathur.shop++import androidx.compose.runtime.Composable+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.shop.platform.ShopViewModel+import com.vayunmathur.shop.ui.CartScreen+import com.vayunmathur.shop.ui.CheckoutScreen+import com.vayunmathur.shop.ui.OrdersScreen+import com.vayunmathur.shop.ui.ProductScreen+import com.vayunmathur.shop.ui.ShopTabs++@Composable+fun Navigation(viewModel: ShopViewModel) {+    val backStack = rememberNavBackStack<Route>(Route.Search)+    MainNavigation(backStack) {+        entry<Route.Search> {+            ShopTabs(+                viewModel = viewModel,+                onProductClick = { variantId, platformId, shopDomain ->+                    backStack.add(Route.ProductDetail(variantId, platformId, shopDomain))+                },+                onCheckout = { backStack.add(Route.Checkout) },+            )+        }+        entry<Route.ProductDetail> { route ->+            ProductScreen(+                viewModel = viewModel,+                variantId = route.variantId,+                platformId = route.platformId,+                shopDomain = route.shopDomain,+                onBack = { backStack.pop() },+                onCheckout = { backStack.add(Route.Checkout) },+            )+        }+        entry<Route.Cart> {+            CartScreen(viewModel, onBack = { backStack.pop() }, onCheckout = { backStack.add(Route.Checkout) })+        }+        entry<Route.Checkout> {+            CheckoutScreen(viewModel = viewModel, onBack = { backStack.pop() })+        }+        entry<Route.Orders> { OrdersScreen(viewModel = viewModel) }+    }+}
shop/src/main/java/com/vayunmathur/shop/Route.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/Route.kt b/shop/src/main/java/com/vayunmathur/shop/Route.ktnew file mode 100644index 0000000000..8e9e94d79f--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/Route.kt@@ -0,0 +1,26 @@+package com.vayunmathur.shop++import com.vayunmathur.library.util.NavKey+import kotlinx.serialization.Serializable++@Serializable+sealed interface Route : NavKey {+    @Serializable+    data object Search : Route++    @Serializable+    data class ProductDetail(+        val variantId: String,+        val platformId: String,+        val shopDomain: String,+    ) : Route++    @Serializable+    data object Cart : Route++    @Serializable+    data object Checkout : Route++    @Serializable+    data object Orders : Route+}
shop/src/main/java/com/vayunmathur/shop/data/CheckoutReview.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/data/CheckoutReview.kt b/shop/src/main/java/com/vayunmathur/shop/data/CheckoutReview.ktnew file mode 100644index 0000000000..de0b89e804--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/data/CheckoutReview.kt@@ -0,0 +1,54 @@+package com.vayunmathur.shop.data++/** Ephemeral form data: intentionally not serializable or saved in instance state. */+data class CheckoutInputs(+    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,+) {+    val hasAddress: Boolean get() = listOf(street, extendedAddress, city, region, country, postalCode).any { it.isNotBlank() }+    fun validationError(): String? = when {+        email.isNotBlank() && !Regex("^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$").matches(email) -> "Enter a valid email address."+        phone.isNotBlank() && !Regex("^\\+[1-9][0-9]{1,14}$").matches(phone) -> "Use an international phone number, such as +14155550123."+        shippingRequested && !hasAddress -> "Provide an address for merchant shipping."+        hasAddress && (street.isBlank() || city.isBlank() || !Regex("^[A-Z]{2}$").matches(country)) -> "Provide a street, city and two-letter uppercase country code."+        hasAddress && country in setOf("US", "CA") && (region.isBlank() || postalCode.isBlank()) -> "Provide a state or province and postal code."+        else -> null+    }+    override fun toString(): String = "CheckoutInputs(redacted)"+}++data class CheckoutLegalLink(val type: String, val title: String, val url: String)+data class CheckoutShippingOption(val id: String, val title: String, val description: String, val totals: List<UcpTotalEntry>)+data class CheckoutShippingGroup(val id: String, val selectedOptionId: String?, val options: List<CheckoutShippingOption>)+data class CheckoutShippingMethod(val id: String, val groups: List<CheckoutShippingGroup>)+data class CheckoutReview(+    val shipping: List<CheckoutShippingMethod> = emptyList(),+    val links: List<CheckoutLegalLink> = emptyList(),+    val browserOnlyReason: String? = null,+    val availableShippingLineIds: List<String> = emptyList(),+)++enum class CheckoutPhase { Preparing, Reviewing, Updating, BrowserRequired, Error, Expired, Uncertain }+data class NativeCheckoutState(+    val platformId: String,+    val shopDomain: String,+    val phase: CheckoutPhase = CheckoutPhase.Reviewing,+    val checkout: UcpCheckout? = null,+    val message: String? = null,+    val inputs: CheckoutInputs = CheckoutInputs(),+    val submittedInputs: CheckoutInputs? = null,+    val submittedLines: List<CartLine> = emptyList(),+) {+    val busy: Boolean get() = phase == CheckoutPhase.Preparing || phase == CheckoutPhase.Updating+    val completionEnabled: Boolean get() = false+}
shop/src/main/java/com/vayunmathur/shop/data/MerchantListing.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/data/MerchantListing.kt b/shop/src/main/java/com/vayunmathur/shop/data/MerchantListing.ktnew file mode 100644index 0000000000..f8be39c47f--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/data/MerchantListing.kt@@ -0,0 +1,12 @@+package com.vayunmathur.shop.data++/** Directory metadata is a discovery lead, never merchant access or payment authorization. */+data class MerchantListing(+    val id: String,+    val name: String,+    val domain: String,+    val siteUrl: String,+    val description: String = "",+    val directoryStatus: String = "unknown",+    val directoryVerifiedAt: String? = null,+)
shop/src/main/java/com/vayunmathur/shop/data/OrderStore.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/data/OrderStore.kt b/shop/src/main/java/com/vayunmathur/shop/data/OrderStore.ktnew file mode 100644index 0000000000..58b8666d1c--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/data/OrderStore.kt@@ -0,0 +1,38 @@+package com.vayunmathur.shop.data++import android.content.Context+import androidx.core.content.edit+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.coroutines.withContext+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/** Local pending checkout history. Payment status remains authoritative at the merchant. */+object OrderStore {+    private const val PREFS_NAME = "shop_orders"+    private const val KEY = "orders_v1"+    private const val MAX_ORDERS = 50+    private val json = Json { ignoreUnknownKeys = true }+    private val writeMutex = Mutex()++    suspend fun getAll(context: Context): List<PlacedOrder> = withContext(Dispatchers.IO) {+        val raw = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).getString(KEY, null)+            ?: return@withContext emptyList()+        runCatching { json.decodeFromString<List<PlacedOrder>>(raw) }.getOrDefault(emptyList())+    }++    suspend fun add(context: Context, order: PlacedOrder) = writeMutex.withLock {+        withContext(Dispatchers.IO) {+            val prefs = context.applicationContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)+            val current = prefs.getString(KEY, null)?.let {+                runCatching { json.decodeFromString<List<PlacedOrder>>(it) }.getOrDefault(emptyList())+            }.orEmpty()+            val others = current.filterNot {+                it.checkoutId == order.checkoutId && it.shopDomain == order.shopDomain+            }+            prefs.edit { putString(KEY, json.encodeToString((listOf(order) + others).take(MAX_ORDERS))) }+        }+    }+}
shop/src/main/java/com/vayunmathur/shop/data/ShopCartStore.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/data/ShopCartStore.kt b/shop/src/main/java/com/vayunmathur/shop/data/ShopCartStore.ktnew file mode 100644index 0000000000..fc7401e55b--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/data/ShopCartStore.kt@@ -0,0 +1,62 @@+package com.vayunmathur.shop.data++import android.content.Context+import androidx.core.content.edit+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * Local cart, persisted as JSON in SharedPreferences. Lines carry a snapshot of the+ * title/price/image at add time so the cart renders offline; prices are always+ * re-confirmed server-side before checkout is created.+ */+@OptIn(ExperimentalCoroutinesApi::class)+object ShopCartStore {++    private const val PREFS_NAME = "shop_cart"+    private const val KEY = "cart_lines_v1"++    private val json = Json { ignoreUnknownKeys = true }++    /**+     * Single writer, so back-to-back mutations commit in the order they were made โ€” a save+     * must not overtake the clear that follows a placed order.+     */+    private val io = Dispatchers.IO.limitedParallelism(1)++    /** Outlives composition: a cart edit has to be persisted even if the screen goes away. */+    private val scope = CoroutineScope(SupervisorJob() + io)++    suspend fun getAll(context: Context): List<CartLine> = withContext(io) {+        val raw = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)+            .getString(KEY, null) ?: return@withContext emptyList()+        try {+            json.decodeFromString<List<CartLine>>(raw)+        } catch (_: Exception) {+            emptyList()+        }+    }++    fun save(context: Context, items: List<CartLine>) {+        val appCtx = context.applicationContext+        val snapshot = items.toList()+        scope.launch {+            appCtx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)+                .edit { putString(KEY, json.encodeToString(snapshot)) }+        }+    }++    fun clear(context: Context) {+        val appCtx = context.applicationContext+        scope.launch {+            appCtx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)+                .edit { remove(KEY) }+        }+    }+}
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.ktnew file mode 100644index 0000000000..d8bdcc4226--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/data/UcpModels.kt@@ -0,0 +1,115 @@+package com.vayunmathur.shop.data++import kotlinx.serialization.Serializable+import kotlinx.serialization.Transient+import kotlinx.serialization.json.JsonObject++/** App projections of UCP responses, not full protocol schemas. Money uses ISO minor units. */+@Serializable+data class Money(val amount: Long = 0, val currency: String = "USD")++@Serializable+data class ProductImage(val url: String = "", val alt: String? = null)++@Serializable+data class ProductVariant(+    val id: String = "",+    val title: String = "",+    val price: Money = Money(),+    val available: Boolean = false,+    val optionValues: List<String> = emptyList(),+    val sku: String? = null,+)++@Serializable+data class UcpProduct(+    val id: String = "",+    val title: String = "",+    val description: String = "",+    val priceRange: Money = Money(),+    val url: String = "",+    val platformId: String = "shopify",+    val shopDomain: String = "",+    val images: List<ProductImage> = emptyList(),+    val variants: List<ProductVariant> = emptyList(),+    val checkoutEligible: Boolean = false,+)++@Serializable+data class CartLine(+    val variantId: String = "",+    val productTitle: String = "",+    val variantTitle: String = "",+    val unitPrice: Money = Money(),+    val imageUrl: String = "",+    val platformId: String = "shopify",+    val shopDomain: String = "",+    val quantity: Int = 1,+)++@Serializable+data class UcpTotals(+    val subtotal: Money = Money(),+    val shipping: Money? = null,+    val tax: Money? = null,+    val total: Money = Money(),+)++@Serializable+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)++@Serializable+data class UcpCheckout(+    val checkoutId: String = "",+    val status: String = "",+    val currency: String = "USD",+    val totals: UcpTotals = UcpTotals(),+    val totalEntries: List<UcpTotalEntry> = emptyList(),+    val expiresAt: String? = null,+    val continueUrl: String = "",+    val messages: List<UcpMessage> = emptyList(),+    val version: String = "2026-08-25",+    @Transient val review: CheckoutReview = CheckoutReview(),+    // Session-only source for exact writable projections. Never serialize buyer-bearing responses.+    @Transient internal val writableSource: JsonObject? = null,+) {+    override fun toString(): String = "UcpCheckout(redacted)"+}++/** Legacy storage name retained for compatibility. Handoffs are pending, not placed orders. */+@Serializable+data class PlacedOrder(+    val checkoutId: String = "",+    val placedAtMs: Long = 0,+    val total: Money = Money(),+    val itemCount: Int = 0,+    val continueUrl: String = "",+    val status: String = "pending",+    val platformId: String = "generic",+    val shopDomain: String = "",+    val lines: List<CartLine> = emptyList(),+    val totalEntries: List<UcpTotalEntry> = emptyList(),+    val expiresAt: String? = null,+    val version: String = "2026-08-25",+)++sealed interface UcpError {+    data class Transport(val reason: String) : UcpError+    data class RateLimited(val retryAfterMs: Long?) : UcpError+    data class Http(val status: Int, val snippet: String) : UcpError+    data class Malformed(val reason: String) : UcpError+    data class Rpc(val message: String) : UcpError+    data class Unsupported(val reason: String) : UcpError+}++fun UcpError.message(): String = when (this) {+    is UcpError.Transport -> "Couldn't reach the store. Check your connection and try again."+    is UcpError.RateLimited -> "The store is busy. Please wait a moment and try again."+    is UcpError.Http -> "The store returned an error ($status). Please try again."+    is UcpError.Malformed -> "The store sent an unexpected response. Please try again."+    is UcpError.Unsupported -> reason+    is UcpError.Rpc -> "The merchant couldn't process the request."+}
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.ktnew file mode 100644index 0000000000..db4fd49352--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/domain/CheckoutProjection.kt@@ -0,0 +1,123 @@+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/MerchantUrls.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/domain/MerchantUrls.kt b/shop/src/main/java/com/vayunmathur/shop/domain/MerchantUrls.ktnew file mode 100644index 0000000000..3bb50cc011--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/domain/MerchantUrls.kt@@ -0,0 +1,34 @@+package com.vayunmathur.shop.domain++import java.net.URI+import java.util.Locale++/** Public HTTPS URLs only; merchant input must not name local devices or app intents. */+object MerchantUrls {+    fun httpsUrl(value: String): String? {+        val uri = runCatching { URI(value) }.getOrNull() ?: return null+        if (!uri.scheme.equals("https", ignoreCase = true) || uri.userInfo != null) return null+        if (uri.port != -1 && uri.port != 443) return null+        val host = uri.host?.lowercase(Locale.US) ?: return null+        if (!publicHostname(host)) return null+        return uri.toASCIIString()+    }++    fun domain(value: String): String? {+        val input = value.trim()+        val url = httpsUrl(if (input.contains("://")) input else "https://$input") ?: return null+        val uri = URI(url)+        if (uri.path !in listOf("", "/") || uri.query != null || uri.fragment != null) return null+        return uri.host.lowercase(Locale.US)+    }++    private fun publicHostname(host: String): Boolean {+        if (!host.contains('.') || host.contains(':') || host.all { it.isDigit() || it == '.' }) return false+        if (host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal")) return false+        return host.split('.').all { label ->+            label.isNotEmpty() && label.length <= 63 &&+                label.first().isLetterOrDigit() && label.last().isLetterOrDigit() &&+                label.all { it in 'a'..'z' || it.isDigit() || it == '-' }+        }+    }+}
shop/src/main/java/com/vayunmathur/shop/domain/MoneyFormat.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/domain/MoneyFormat.kt b/shop/src/main/java/com/vayunmathur/shop/domain/MoneyFormat.ktnew file mode 100644index 0000000000..ef1e5b57bb--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/domain/MoneyFormat.kt@@ -0,0 +1,31 @@+package com.vayunmathur.shop.domain++import com.vayunmathur.shop.data.Money+import java.math.BigDecimal+import java.text.NumberFormat+import java.util.Currency+import java.util.Locale++/** Formats ISO 4217 minor units without floating-point rounding. */+object MoneyFormat {+    private fun currency(money: Money): Currency? =+        runCatching { Currency.getInstance(money.currency.uppercase(Locale.US)) }.getOrNull()++    private fun decimalAmount(money: Money): BigDecimal =+        BigDecimal.valueOf(money.amount).movePointLeft(+            currency(money)?.defaultFractionDigits?.takeIf { it >= 0 } ?: 2,+        )++    fun majorUnits(money: Money): Double = decimalAmount(money).toDouble()++    fun format(money: Money, locale: Locale = Locale.US): String {+        val currency = currency(money)+            ?: return "${money.currency.uppercase(Locale.US)} ${decimalAmount(money).toPlainString()}"+        val digits = currency.defaultFractionDigits.coerceAtLeast(0)+        return NumberFormat.getCurrencyInstance(locale).apply {+            this.currency = currency+            minimumFractionDigits = digits+            maximumFractionDigits = digits+        }.format(decimalAmount(money))+    }+}
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.ktnew file mode 100644index 0000000000..205aaa7dbe--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.kt@@ -0,0 +1,155 @@+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 kotlinx.coroutines.CancellationException+import kotlinx.coroutines.sync.Mutex+import java.time.Instant+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>+}++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 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 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()++    private fun publish(key: Pair<String, String>, state: NativeCheckoutState) { states[key] = state; changed(snapshot) }++    fun edit(platform: String, shop: String, inputs: CheckoutInputs) {+        val key = platform to shop+        val state = states[key] ?: NativeCheckoutState(platform, shop)+        if (!state.busy) publish(key, state.copy(inputs = inputs))+    }++    fun cartChanged(lines: List<CartLine>) {+        states.toMap().forEach { (key, state) ->+            if (state.checkout != null && state.submittedLines != lines.filter { it.platformId == key.first && it.shopDomain == key.second }) {+                publish(key, state.copy(phase = if (state.phase == CheckoutPhase.Uncertain) CheckoutPhase.Uncertain else CheckoutPhase.BrowserRequired,+                    message = "The cart changed. This session no longer represents your cart; review it on the merchant website."))+            }+        }+    }++    fun refreshExpiry() {+        states.toMap().forEach { (key, state) ->+            if (!state.busy && state.checkout != null && state.phase != CheckoutPhase.Uncertain && expired(key, state.checkout)) {+                publish(key, state.copy(phase = CheckoutPhase.Expired, message = "This checkout session expired. Continue on the merchant website."))+            }+        }+    }++    private fun expired(key: Pair<String, String>, checkout: UcpCheckout): Boolean = checkout.expiresAt?.let {+        runCatching { Instant.parse(it).toEpochMilli() <= now() }.getOrDefault(true)+    } ?: (now() - (createdAt[key] ?: now()) !in 0 until 6 * 60 * 60 * 1000L)++    suspend fun submit(platform: String, shop: String, lines: List<CartLine>, sink: PendingCheckoutSink) {+        val key = platform to shop+        val lock = locks.getOrPut(key) { Mutex() }+        if (!lock.tryLock()) return+        var mutationStarted = false+        try {+            val state = states[key] ?: NativeCheckoutState(platform, shop)+            if (state.phase in setOf(CheckoutPhase.Uncertain, CheckoutPhase.BrowserRequired, CheckoutPhase.Expired)) return+            if (lines.isEmpty() || lines.any { it.shopDomain != shop || it.platformId != platform || it.quantity !in 1..99 }) return+            state.inputs.validationError()?.let { publish(key, state.copy(phase = CheckoutPhase.Error, message = it)); return }+            val previous = state.checkout+            if (previous != null && expired(key, previous)) {+                publish(key, state.copy(phase = CheckoutPhase.Expired, message = "This session expired. Continue on the merchant website.")); return+            }+            if (previous != null && state.submittedLines != lines) {+                publish(key, state.copy(phase = CheckoutPhase.BrowserRequired, message = "The session's cart changed. Continue on the merchant website.")); return+            }+            if (previous != null && state.submittedInputs == state.inputs) return+            if (previous != null && state.submittedInputs?.hasAddress == true && !state.inputs.hasAddress) {+                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.+            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+                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) {+                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 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,+                message = reason)+            publish(key, next)+            // Persist only the existing pending history projection, never buyer, address, messages or raw response.+            sink.save(PlacedOrder(checkoutId = checkout.checkoutId, placedAtMs = now(), total = checkout.totals.total,+                itemCount = lines.sumOf { it.quantity }, continueUrl = MerchantUrls.httpsUrl(checkout.continueUrl).orEmpty(),+                status = "pending", platformId = platform, shopDomain = shop, lines = lines.map { it.copy(imageUrl = "") },+                totalEntries = checkout.totalEntries.map { it.copy(label = it.type) }, expiresAt = checkout.expiresAt, version = checkout.version))+        } catch (cancelled: CancellationException) {+            if (mutationStarted) states[key]?.let { publish(key, it.copy(phase = CheckoutPhase.Uncertain, message = "Request interrupted. Do not retry; use the merchant website.")) }+            throw cancelled+        } catch (_: Exception) {+            states[key]?.let { publish(key, it.copy(phase = if (mutationStarted) CheckoutPhase.Uncertain else CheckoutPhase.Error,+                message = if (mutationStarted) "The session may have changed. Do not retry; use the merchant website." else "Checkout is unavailable.")) }+        } finally { lock.unlock() }+    }++    suspend fun reconcile(platform: String, shop: String) {+        val key = platform to shop+        val lock = locks.getOrPut(key) { Mutex() }+        if (!lock.tryLock()) return+        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+            // 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 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,+                message = if (state.phase == CheckoutPhase.Uncertain) "Session refreshed. The uncertain write will not be replayed; continue on the merchant website." else browserReason ?: state.message))+            refreshExpiry()+        } finally { lock.unlock() }+    }+}
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.ktnew file mode 100644index 0000000000..486dd18dcf--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/network/JsonParse.kt@@ -0,0 +1,40 @@+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.ktnew file mode 100644index 0000000000..152d2b2bf3--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/network/MerchantDirectoryApi.kt@@ -0,0 +1,120 @@+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/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.ktnew file mode 100644index 0000000000..2d2835edd7--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/network/UcpApi.kt@@ -0,0 +1,157 @@+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.ktnew file mode 100644index 0000000000..db50a7a369--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/network/UcpCatalog.kt@@ -0,0 +1,283 @@+package com.vayunmathur.shop.network++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): 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) } }+        return UcpApi.serviceCall(service, "get_product", arguments).mapCatching {+            parseProductResponse(it, platform.id, shopDomain, service.version)+        }+    }++    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): 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+    }++    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"),+    )++    private fun projectProduct(+        o: JsonObject, platformId: String, defaultShop: String, price: Money, variants: List<ProductVariant>,+    ): UcpProduct {+        val url = string(o, "url")?.let(MerchantUrls::httpsUrl).orEmpty()+        val shop = MerchantUrls.domain(defaultShop) ?: string(o, "shop_domain")?.let(MerchantUrls::domain)+            ?: url.takeIf { it.isNotBlank() }?.let { URI(it).host.lowercase() }.orEmpty()+        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, url = url, platformId = platformId, shopDomain = shop,+            images = images, variants = variants,+            checkoutEligible = shop.isNotBlank() && variants.isNotEmpty() && o["native_commerce"] != JsonPrimitive(false),+        )+    }++    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 = if (defaultShop.isNotBlank()) defaultShop+            else o.text("shop_domain")?.let(MerchantUrls::domain)+                ?: MerchantUrls.httpsUrl(url)?.let { URI(it).host }.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(),+            priceRange = range?.get("min").asObject()?.let(::parseMoney) ?: variants.firstOrNull()?.price ?: Money(),+            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"),+        )+    }++    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.ktnew file mode 100644index 0000000000..f793b429ee--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/network/UcpCheckoutApi.kt@@ -0,0 +1,153 @@+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.ktnew file mode 100644index 0000000000..144439227f--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/network/UcpDiscovery.kt@@ -0,0 +1,143 @@+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.ktnew file mode 100644index 0000000000..54330e8276--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/network/UcpMcp.kt@@ -0,0 +1,202 @@+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) { /*

Diff truncated.