portage-ucp-webmcp 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 0af5e77acced08e6ebf2e42ab60bf83281af6d61adb5c1b793d76814eea6585f
4
- data.tar.gz: f430fb109a83774a3a8b531af4946269986c5f0aae6ad0d93cf12216088afd4f
3
+ metadata.gz: d6b6ed40cbfc7d72bfb2354e1964250d4fa118bf0e505134ad8b3ad0b57b2214
4
+ data.tar.gz: af53799f73cd814caf017cf86ddd0c511b92e83290a2f49d1f6c494c4064c8d3
5
5
  SHA512:
6
- metadata.gz: 90e4e18799cb69f1bcec89cee2839f71fbaa11caea7628c100d3dbf814f016d0dbe3e60391cf6c33de3301b0f84694d0c568c1ebf2a505335bbaebe09bd9c220
7
- data.tar.gz: 8006c6d4107d530bc606f8ce5cd7e8aba1131b30d6bdccf78f544d89db7a8c9225c10076860856d3ef0838ec83fe4384b0b576f14a28912e379ff349ddaa95bb
6
+ metadata.gz: 9c07a7bac723dfd5fe5911ee856602409dca6a7c76196cf87eaa559753793dcd96ab258d4cbd82ac253ed7b73cd515f7eb8e022ac34f3d050435522e263aafeb
7
+ data.tar.gz: 8f1bd216b96fbe4f63324ec7bdfcd1fc01aecf823c4c72df050a499fb654ed65d45295e4d5baf65eddcfe9f4331428d7019d99bb4bc1adc7539ac2e777c726d1
data/CHANGELOG.md CHANGED
@@ -4,6 +4,116 @@ All notable changes to this project are documented here. Format loosely follows
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.0.0/); this project is
5
5
  pre-1.0, so APIs may still shift between minor versions.
6
6
 
7
+ ## [Unreleased]
8
+
9
+ ## [0.2.0] - 2026-09-29
10
+
11
+ - **Fixed: `assets/autofill.js` didn't parse** (docs/design-log.md §51). A
12
+ `*/` inside its header comment closed the comment early, so every real
13
+ `Autofill.call` raised `BridgeError` (`SyntaxError: Unexpected identifier
14
+ 'context'`). New `asset_syntax_spec.rb` runs `node --check` on every file
15
+ in `assets/`, in the form the gem actually hands a browser, and skips with
16
+ a message when node isn't on PATH. New `autofill_js_spec.rb` runs the real
17
+ script through `ScriptEvaluator#autofill` against a small fake checkout
18
+ DOM (`spec/support/fake_checkout_dom.js`, no npm dependency).
19
+ - **Autofill fills a `<select>`** reached through `checkout_selectors`: it
20
+ picks the option whose value matches, then the one whose visible text
21
+ matches (case-insensitive, trimmed), using `HTMLSelectElement`'s own value
22
+ setter. No matching option reports the token as `unmatched` instead of
23
+ throwing on the input setter.
24
+ - **Shipping-rate prices in any currency.** `selectCheapestRate` reads a
25
+ price through a new `ratePrice`, which tries four patterns in order and
26
+ takes the first hit: currency symbol (`\p{Sc}`, so `฿`, `¥`, `₹` …) then
27
+ amount, amount then symbol, ISO code then amount, amount then ISO code.
28
+ An ISO code only counts if it's in `Intl.supportedValuesOf("currency")`
29
+ (any three capitals where that's missing). So "Royal Mail Tracked 48
30
+ £3.50" reads as 3.50 and "DPD 24 hours £6.00" as 6, not 48 or 24.
31
+ Thousands separators are handled (`฿1,950.00` is 1950, not 1.95), and
32
+ "Free" still counts as 0.
33
+ - **`Presets::SHOPIFY.checkout_selectors`** now has two fallbacks, taken
34
+ from a live Shopify checkout (docs/design-log.md §50): `email` →
35
+ `input[autocomplete='shipping email']` and `shipping tel` →
36
+ `input[autocomplete='shipping tel-national']`. Shopify names both fields
37
+ differently from the tokens `WebmcpAutofillFields` asks for.
38
+ - **Docs for Phases 1-3** (docs/plans/webmcp-universal-outbound.md Phase 4,
39
+ no code change): the README's "Stores that don't run Portage" section now
40
+ documents `Presets`/`preset:`, `Matcher`/the read-vs-mutating confirm
41
+ rule, the fingerprint-keyed confirmed-mapping store, and a new "Approved
42
+ autofill of the store's checkout" section covering `Autofill`'s outcomes
43
+ and `Preset#checkout_selectors`. None of this had been written up before
44
+ now even though it shipped in earlier phases.
45
+ - **Checkout autofill** (docs/plans/webmcp-universal-outbound.md Phase 3):
46
+ `Bridges::ScriptEvaluator#autofill(fields, selectors:)` fills a checkout
47
+ page's own contact/shipping fields directly — by `autocomplete` attribute,
48
+ never a WebMCP tool call — via a new `assets/autofill.js`, and picks the
49
+ cheapest shipping rate among same-named radio groups it can read a price
50
+ from. Never touches a field whose own `autocomplete` is payment-shaped
51
+ (`cc-*`/`transaction-*`) or whose `type` is hidden/password, regardless of
52
+ what's asked for; never clicks a submit/pay control; stops and reports
53
+ `blocked` on the first sign of a CAPTCHA/challenge, without trying to
54
+ solve or route around it. `ScriptEvaluator.ferrum`/`.playwright`/
55
+ `.selenium` all take a new `headless:` (default `nil`, meaning "unknown"),
56
+ exposed as `#headless?`. `WebMcp::Autofill.call(bridge:, fields:,
57
+ selectors:)` is the Ruby-side gate in front of it: `:needs_headed_browser`
58
+ when the bridge is headless or never says (unknown is treated as
59
+ headless — a shopper who can't see the browser can't pay in it either),
60
+ `:unsupported` for a hand-rolled Bridge with no `#autofill` at all,
61
+ `:blocked` when the page script signals a challenge, `:filled` otherwise
62
+ (with `#filled`/`#unmatched`/`#rate`). `Presets::Preset` gained
63
+ `checkout_selectors` (default `{}`), a platform's fallback CSS selectors
64
+ per autocomplete token — Shopify's is empty pending a live check (no
65
+ browser or live storefront available this session; noted as pending in
66
+ the plan's Progress log). Everything upstream of this — the opt-in gate,
67
+ the shopper-approval prompt, building `fields` from `PORTAGE_SHIP_*` — is
68
+ `portage-cli`'s job (`WebmcpAutofillMode`, `WebmcpAutofillConfirm`,
69
+ `WebmcpAutofillFields`); this gem never reads shopper data itself.
70
+ - **Schema matching for unknown pages** (docs/plans/webmcp-universal-outbound.md
71
+ Phase 2): `WebMcp::Matcher.propose(tools)` proposes a `tool_names:` mapping
72
+ for a page `Presets.detect` doesn't recognize, scoring each of the page's
73
+ tools against every UCP action it might be by name-token overlap
74
+ (`findProducts` ↔ `search_catalog`), input-schema shape (a `query` string
75
+ → search; `product_id`/`variant_id` + `quantity` → add to cart), and the
76
+ `readOnlyHint` annotation — never a tool's `description`, which is
77
+ untrusted page content. Returns a `Proposal` (`tool:`, `confidence:`,
78
+ `reason:`) per action scored above a floor; an action nothing scores
79
+ against is simply absent. No LLM in this gem. `Matcher.tool_names(proposal)`
80
+ flattens a proposal to the plain `tool_names:` shape. Confirming a
81
+ proposal, and persisting a confirmed mapping, is `portage-cli`'s job
82
+ (`WebmcpMappingConfirm`, `WebmcpMappings`) — nothing here calls a tool or
83
+ writes anything.
84
+ - `WebMcp::Fingerprint`, extracted from `Presets.detect`'s own name-sorting:
85
+ `.names(tools)` (sorted tool names, what `Presets.detect` matches against)
86
+ and `.for(tools)` (a digest of every tool's name *and* its own input
87
+ schema — what `portage-cli`'s confirmed-mapping store keys a Phase 2
88
+ mapping by, so a lookalike page with the same tool names but a different
89
+ schema shape gets a different fingerprint).
90
+ - `WebMcp.connect` with no `capabilities:` now derives them from the tools
91
+ the page registers (`WebMcp::Capabilities`), so `Session#advertises?`
92
+ answers `true`/`false` instead of `nil`. This reads the page once inside
93
+ `connect`, so a `BridgeError` can now raise from `connect` itself.
94
+ `Transport#answers?(action)` reports whether a page tool answers an
95
+ action after `tool_names:`/`prefix:` resolution.
96
+ - **Platform presets** (docs/plans/webmcp-universal-outbound.md Phase 1):
97
+ `WebMcp.connect` takes a new `preset:` (default `:auto`), which detects a
98
+ known platform from the exact set of tool names the page registers right
99
+ now — never from page text, which is untrusted content a page could
100
+ forge — and applies its `tool_names:`/`wire:`. `nil` turns presets off;
101
+ a Symbol (`:shopify`) forces one without reading the page to detect it.
102
+ An explicit `tool_names:` still wins over the preset's own, key by key.
103
+ `WebMcp::Presets::SHOPIFY` is the first entry: `tool_names: {create_cart:
104
+ "add_to_cart"}`, and a `handoff_checkout: "proceed_to_checkout"` naming
105
+ the tool that only navigates the browser to Shopify's own checkout. Its
106
+ fingerprint is the 11 tools seven live Shopify storefronts registered
107
+ on 2026-09-28, all with identical input schemas.
108
+ - `WebMcp::Capabilities.for` takes a new `handoff_checkout:` (a preset's
109
+ hand-off-only checkout tool name) — a page that answers it now counts as
110
+ advertising checkout even with no `create_checkout` tool at all.
111
+ - `Bridges::ScriptEvaluator#location` reads the tab's current URL
112
+ (`window.location.href`) through the same `evaluate:` callable every
113
+ other call uses. Optional on the Bridge contract — used by `portage-cli`
114
+ `Buy`'s hand-off checkout path to read the checkout URL after a tool
115
+ that only navigates the tab, when the tool's own result carries none.
116
+
7
117
  ## [0.1.1] - 2026-09-24
8
118
 
9
119
  - `Rack::CallEndpoint` resolves the caller through core's
data/README.md CHANGED
@@ -255,7 +255,63 @@ something the consumer can list.
255
255
 
256
256
  ### Stores that don't run Portage
257
257
 
258
- `Transport` does not assume that the page was built with this gem:
258
+ `Transport` does not assume that the page was built with this gem. Three
259
+ ways to get a working `tool_names:`/`wire:` for a page you don't control,
260
+ tried in this order (`docs/plans/webmcp-universal-outbound.md`):
261
+
262
+ 1. **A built-in preset.** `WebMcp::Presets.detect(tools)` matches a page's
263
+ tools against a known platform's exact fingerprint — the whole sorted set
264
+ of tool names it registers *right now*, never anything the page's own
265
+ text says about itself (a `generator` meta tag, `window.Shopify`, a
266
+ tool's own description — all untrusted page content, same boundary as
267
+ the confirm rule below). `WebMcp.connect(bridge:, preset: :auto)` — the
268
+ default — runs detection (one extra page read, on top of the one
269
+ `capabilities: nil` already does) and applies the matching preset's
270
+ `tool_names:`/`wire:` before anything else. `preset: nil` turns presets
271
+ off entirely; a symbol (`preset: :shopify`) forces one with no detection
272
+ read at all. An explicit `tool_names:`/`wire:` you also pass to `connect`
273
+ still wins over the preset's own — `tool_names:` key by key, `wire:`
274
+ outright. Shopify (`Presets::SHOPIFY`) is the only entry so far; see
275
+ "Shopify storefronts" below. A platform can change its tool set without
276
+ notice — when it does, `detect` simply misses and the page falls through
277
+ to the next mechanism rather than being mapped wrongly.
278
+ 2. **A matched-and-confirmed mapping**, for a page no preset recognizes.
279
+ `WebMcp::Matcher.propose(tools)` scores each of the page's own tools
280
+ against every UCP action Session can drive over WebMCP, by name-token
281
+ overlap (`findProducts` ↔ `search_catalog`), input-schema shape (a
282
+ `query` string → search; `product_id`/`variant_id` + `quantity` → add to
283
+ cart), and the tool's own `readOnlyHint` — **never** its `description`,
284
+ which is page text and therefore untrusted (a page could name a mutating
285
+ tool `search_catalog` with a friendly description; nothing here reads
286
+ that string for scoring or for the mapping it returns). It returns a
287
+ `Proposal` (`tool:`, `confidence:`, `reason:`) per action that scored
288
+ above a floor; an action nothing plausible matched is simply absent
289
+ rather than given a weak guess. `Matcher` itself never calls a tool,
290
+ prompts anyone, or persists anything — that's the caller's job, and the
291
+ confirm rule it leans on is: a **read action** (`search_catalog`,
292
+ `get_product`, `get_cart`) can be used straight off the proposal, since a
293
+ wrong match there wastes a call and changes nothing; a **mutating
294
+ action** (`create_cart`, `update_cart`, `create_checkout`) needs
295
+ confirmation before its first call, since a wrong guess there could add
296
+ to, discard, or attempt to charge a stranger's cart. `portage-cli`
297
+ enforces that rule for `portage buy`: `Portage::Cli::WebmcpMappingConfirm`
298
+ prints the proposed mapping — quoting a mutating tool's own `description`
299
+ as what it is, page content, never as an instruction — and prompts on a
300
+ real TTY with `--json` off; under `--json`, or with no TTY, the run
301
+ stops instead (outcome `webmcp_mapping_unconfirmed`) and returns the
302
+ proposal for the caller to pass back as `tool_names:` itself.
303
+ `Portage::Cli::WebmcpMappings` persists a confirmed mapping in
304
+ `~/.portage/webmcp_mappings.json`, keyed by the page's tool
305
+ **fingerprint** (`WebMcp::Fingerprint.for` — sorted tool names plus a
306
+ hash of each one's own input schema) rather than by origin: any later
307
+ store whose WebMCP tools have that exact shape reuses the mapping with
308
+ no prompt at all, in effect a locally-grown preset shared across every
309
+ store running that tool set. A lookalike page whose schemas differ even
310
+ slightly gets a different fingerprint and has to be confirmed again, so
311
+ it can't borrow a mapping that turns out to have a different shape
312
+ underneath the same tool names.
313
+ 3. **An explicit `tool_names:` you pass yourself.** Always available,
314
+ preset or confirmed mapping or not — see the next bullet.
259
315
 
260
316
  - **Tool names.** An action resolves to `tool_names[action]` first, then to
261
317
  `"#{prefix}#{action}"`, then to the action itself. Map a store's own names:
@@ -302,11 +358,12 @@ Two limits bound an outbound call, and both block the thread that made it:
302
358
 
303
359
  ### Shopify storefronts
304
360
 
305
- Checked live on 2026-09-23: 6 of 8 Shopify storefronts tried (ColourPop,
306
- tentree, Kylie Cosmetics, Brooklinen, Allbirds, Billabong) register the same 11
307
- WebMCP tools of their own. Gymshark and Fashion Nova registered none. The
308
- tools take UCP-shaped arguments, so `wire: :auto` picks the UCP shape. Two
309
- names differ from Session's:
361
+ Checked live on 2026-09-28: 7 of 9 Shopify storefronts tried (ColourPop,
362
+ tentree, Kylie Cosmetics, Brooklinen, Allbirds, Billabong, The Light Yard)
363
+ register the same 11 WebMCP tools of their own, with identical schemas, and
364
+ `preset: :auto` detects all of them as `:shopify`. Gymshark and Fashion Nova
365
+ registered none. The tools take UCP-shaped arguments, so `wire: :auto` picks
366
+ the UCP shape. Two names differ from Session's:
310
367
 
311
368
  ```ruby
312
369
  session = Portage::Ucp::WebMcp.connect(bridge: bridge, tool_names: { create_cart: "add_to_cart" })
@@ -327,6 +384,71 @@ Things to know about these tools:
327
384
  `proceed_to_checkout` navigates the browser to Shopify checkout, where the
328
385
  shopper pays. Neither maps onto a Session method.
329
386
 
387
+ ### Approved autofill of the store's checkout
388
+
389
+ Once a WebMCP session hands off to the store's own checkout — a preset's
390
+ `handoff_checkout` tool (Shopify's `proceed_to_checkout`) navigates the same
391
+ bridge's browser there — the shopper can opt into having contact and
392
+ shipping fields filled in for them before they take over to pay. This is
393
+ off by default and gated behind two separate approvals, neither of which
394
+ lives in this gem:
395
+
396
+ - **The opt-in itself** is `portage-cli`'s: `portage buy --autofill`, or
397
+ `PORTAGE_WEBMCP_AUTOFILL=approve` (config.json's `"webmcp_autofill":
398
+ "approve"` also works) for every run, until the caller opts out again.
399
+ Only the literal string `"approve"` turns the env/config level on — an
400
+ unrelated truthy convention like `PORTAGE_WEBMCP_AUTOFILL=true` does
401
+ nothing, deliberately, since a mistaken export of some other tool's
402
+ boolean shouldn't silently start typing into a checkout page.
403
+ - **The shopper's approval of the exact fields.** Even opted in, nothing is
404
+ typed until a prompt lists every field and value about to be entered and
405
+ the shopper says yes — refused outright under `--json` or with no TTY on
406
+ stdin, the same posture as the mapping-confirm prompt above.
407
+
408
+ What it will fill, once both approvals are in: the contact email and
409
+ shipping address `portage-cli` already builds from `PORTAGE_SHIP_*` (plus
410
+ the new `PORTAGE_SHIP_EMAIL`), matched to the checkout page's own fields by
411
+ their WHATWG `autocomplete` attribute (`email`, `shipping given-name`,
412
+ `shipping address-line1`, `shipping postal-code`, …), and the cheapest
413
+ priced option in a same-named radio-button group it can read a price out
414
+ of (a best-effort DOM heuristic, unverified against a real rate picker — see
415
+ the Progress log in the plan). What it will never do, regardless of what
416
+ it's asked for: touch a field whose own `autocomplete` is payment-shaped
417
+ (`cc-*`, `transaction-*`) or whose `type` is `hidden`/`password` — checked
418
+ against the page's own attribute, not against what was requested, so a
419
+ mislabeled card field still can't be reached — or click a submit/pay
420
+ control. The run always still ends in a hand-off; autofill only changes
421
+ what's already filled in when the shopper gets there.
422
+
423
+ `WebMcp::Autofill.call(bridge:, fields:, selectors:)` is the gate that
424
+ actually runs it, and the outcomes a caller (or a report's `autofill:` key)
425
+ can see are:
426
+
427
+ | Outcome | Meaning |
428
+ |---|---|
429
+ | `:filled` | Ran. `#filled`/`#unmatched` list which fields matched a page element and which didn't; `#rate` lists any shipping-rate group it picked from. |
430
+ | `:needs_headed_browser` | The bridge is headless, or never says either way. A bridge's `#headless?` defaults to unknown, and unknown is treated the same as headless — the shopper has to be able to see and pay in this browser, so "assume headed" isn't the safe default. |
431
+ | `:blocked` | The checkout page itself showed a CAPTCHA/challenge marker (an embedded reCAPTCHA/hCaptcha/Turnstile iframe, a Cloudflare interstitial, a matching page title). Nothing was touched, and nothing here ever tries to solve or route around it. |
432
+ | `:unsupported` | The bridge doesn't implement `#autofill` at all — a hand-rolled `Bridge` that only meets the base `#list_tools`/`#execute_tool` contract. |
433
+
434
+ The DOM work — finding fields, refusing payment ones, detecting a
435
+ challenge, filling through each element's native value setter so a
436
+ React/Vue-controlled input actually notices — lives entirely in
437
+ `assets/autofill.js`, run through `Bridges::ScriptEvaluator#autofill`, never
438
+ as a WebMCP tool call. It treats the checkout page as untrusted content the
439
+ same way the matcher above treats a tool's `description`: it never follows
440
+ a link or acts on any instruction the page's own text might contain, and
441
+ only ever reads `autocomplete`/`type` attributes and radio-group prices,
442
+ sets a field's `.value`, or checks a radio button already on the page.
443
+
444
+ A field the standard `autocomplete` match misses falls back to
445
+ `Presets::Preset#checkout_selectors` — a platform's own CSS selectors,
446
+ keyed by the same autocomplete token, for a checkout whose markup doesn't
447
+ carry one. Shopify's has two, both taken from a live checkout on 2026-09-28:
448
+ its email field is `autocomplete="shipping email"` (not `email`) and its phone
449
+ field is `shipping tel-national` (not `shipping tel`). Every other contact and
450
+ shipping field matched by its own `autocomplete` value.
451
+
330
452
  ### Errors
331
453
 
332
454
  All errors are under `Portage::Ucp::Client::Error`, so existing `rescue` blocks
@@ -0,0 +1,288 @@
1
+ /*
2
+ * portage-ucp-webmcp checkout autofill (outbound, Phase 3:
3
+ * docs/plans/webmcp-universal-outbound.md).
4
+ *
5
+ * A single function expression Bridges::ScriptEvaluator#autofill evaluates
6
+ * in a store's checkout page (the tab that just navigated there via a
7
+ * preset's `handoff_checkout` tool) as `(<this>)(fields, selectors)`:
8
+ *
9
+ * - fields: { "<autocomplete token>": "<value>", ... } — contact email and
10
+ * shipping address only, built by portage-cli's WebmcpAutofillFields
11
+ * from the PORTAGE_SHIP_* variables and buyer context, and only after
12
+ * the shopper has approved exactly these field/value pairs in a prompt.
13
+ * Never a payment field — portage-cli never builds one.
14
+ * (No glob-then-slash in this comment: that pair closes it early, which
15
+ * is how this file once shipped unparseable — see design-log §51.)
16
+ * - selectors: { "<token>": "<css selector>" } — a platform preset's
17
+ * fallback (Presets::Preset#checkout_selectors), tried only when no
18
+ * element on the page carries a matching `autocomplete` attribute for
19
+ * that token.
20
+ *
21
+ * Always resolves — never rejects — to a JSON string envelope
22
+ * `{ ok: true, value }` where value is
23
+ * `{ blocked, filled: [...tokens], unmatched: [...tokens], rate: [...] }`,
24
+ * or `{ ok: false, code: "execute_failed", error }` for a genuine script
25
+ * crash (so a driver failure surfaces as the same BridgeError every other
26
+ * call already does).
27
+ *
28
+ * Refuses on principle, not just by omission — checkout pages are
29
+ * untrusted content, same posture as a WebMCP tool's own description
30
+ * (Phase 2's WebmcpMappingConfirm):
31
+ * - Never looks at, matches, or writes to a field whose own `autocomplete`
32
+ * value is payment-shaped (`cc-*`, `transaction-*`) or whose `type` is
33
+ * "hidden"/"password" — checked against the *page's* attribute, not
34
+ * against what was asked for, so a caller mistake (or a store that
35
+ * mislabels a card field with a shipping-looking autocomplete value)
36
+ * still can't reach it.
37
+ * - Never clicks a submit/pay control, and never follows a link or acts
38
+ * on any instruction the page's own text might contain — the only
39
+ * things this script ever does are read `autocomplete`/`type`
40
+ * attributes and radio-group prices, set a field's `.value`, and check
41
+ * a radio button already on the page.
42
+ * - Stops and reports `blocked` on the first sign of a bot
43
+ * challenge/CAPTCHA (an embedded reCAPTCHA/hCaptcha/Turnstile iframe, a
44
+ * Cloudflare "checking your browser" marker, or matching page title),
45
+ * without touching any field and without trying to solve or route
46
+ * around it.
47
+ */
48
+ (function (fields, selectors) {
49
+ "use strict";
50
+
51
+ var root = typeof window !== "undefined" ? window : globalThis;
52
+ var doc = root.document;
53
+
54
+ // cc-* (card number/name/exp/csc) and transaction-* (amount/currency) are
55
+ // the WHATWG autocomplete tokens for payment fields — never touched
56
+ // regardless of what `fields`/`selectors` ask for.
57
+ var FORBIDDEN_AUTOCOMPLETE = /(^|\s)(cc-|transaction-)/i;
58
+ var CHALLENGE_SELECTORS = [
59
+ "iframe[src*='recaptcha' i]", "iframe[src*='hcaptcha' i]", "iframe[src*='turnstile' i]",
60
+ "iframe[title*='challenge' i]", "#challenge-running", "#cf-challenge-running",
61
+ "[data-testid='challenge']"
62
+ ];
63
+ var CHALLENGE_TITLE = /checking your browser|verify you are human|attention required|just a moment/i;
64
+ // A rate's price: any currency symbol (Unicode \p{Sc}: $ £ € ฿ ¥ ₹ …) or a
65
+ // three-letter ISO 4217 code, before or after the amount ("£50.00",
66
+ // "฿1,950.00", "THB 1,950.00", "12,50 €"). The amount allows thousands
67
+ // separators (a comma, a dot, or the no-break spaces some locales use), so
68
+ // "฿1,950.00" reads as 1950, not 1.95. Checkout currency follows the
69
+ // shopper's geo-IP until an address is filled (design-log §50 saw THB on a
70
+ // UK store), so no fixed list of currencies is enough. See ratePrice for
71
+ // why these are tried one pattern at a time rather than as one regex.
72
+ var AMOUNT = "(\\d{1,3}(?:[.,\\u00a0\\u202f]\\d{3})+(?:[.,]\\d{1,2})?|\\d+(?:[.,]\\d{1,2})?)";
73
+ var ISO_CODE = "(?<![A-Za-z])([A-Z]{3})(?![A-Za-z])";
74
+ var SYMBOL_THEN_AMOUNT = new RegExp("\\p{Sc}\\s?" + AMOUNT, "u");
75
+ var AMOUNT_THEN_SYMBOL = new RegExp(AMOUNT + "\\s?\\p{Sc}", "u");
76
+ var CODE_THEN_AMOUNT = { pattern: ISO_CODE + "\\s?" + AMOUNT, code: 1, amount: 2 };
77
+ var AMOUNT_THEN_CODE = { pattern: AMOUNT + "\\s?" + ISO_CODE, code: 2, amount: 1 };
78
+
79
+ function isChallengePage() {
80
+ var found = CHALLENGE_SELECTORS.some(function (selector) {
81
+ try {
82
+ return !!doc.querySelector(selector);
83
+ } catch (error) {
84
+ return false;
85
+ }
86
+ });
87
+ return found || CHALLENGE_TITLE.test((doc && doc.title) || "");
88
+ }
89
+
90
+ function isForbidden(el) {
91
+ var auto = (el.getAttribute("autocomplete") || "").toLowerCase();
92
+ if (FORBIDDEN_AUTOCOMPLETE.test(auto)) return true;
93
+
94
+ var type = (el.getAttribute("type") || "").toLowerCase();
95
+ return type === "hidden" || type === "password";
96
+ }
97
+
98
+ function isFillable(el) {
99
+ return !!el && !isForbidden(el) && !el.disabled && !el.readOnly;
100
+ }
101
+
102
+ function findByAutocomplete(token) {
103
+ var wanted = token.trim().toLowerCase();
104
+ var candidates = doc.querySelectorAll("input[autocomplete], textarea[autocomplete], select[autocomplete]");
105
+ for (var i = 0; i < candidates.length; i += 1) {
106
+ var el = candidates[i];
107
+ var value = (el.getAttribute("autocomplete") || "").trim().toLowerCase();
108
+ if (value === wanted && isFillable(el)) return el;
109
+ }
110
+ return null;
111
+ }
112
+
113
+ function findBySelector(selector) {
114
+ if (!selector) return null;
115
+ var el;
116
+ try {
117
+ el = doc.querySelector(selector);
118
+ } catch (error) {
119
+ return null;
120
+ }
121
+ return isFillable(el) ? el : null;
122
+ }
123
+
124
+ function nativeValueSetter(el) {
125
+ var ctor = { TEXTAREA: root.HTMLTextAreaElement, SELECT: root.HTMLSelectElement }[el.tagName] ||
126
+ root.HTMLInputElement;
127
+ var proto = ctor && ctor.prototype;
128
+ var descriptor = proto && Object.getOwnPropertyDescriptor(proto, "value");
129
+ return descriptor && descriptor.set;
130
+ }
131
+
132
+ // A <select> only takes one of its own options' values: an exact option
133
+ // value first ("GB"), then the option's visible text, case-insensitive and
134
+ // trimmed ("United Kingdom"). null when neither matches, so the token is
135
+ // reported unmatched instead of leaving the select blank.
136
+ function selectOptionValue(el, value) {
137
+ var options = el.options || [];
138
+ var wanted = String(value).trim().toLowerCase();
139
+ var i;
140
+ for (i = 0; i < options.length; i += 1) {
141
+ if (options[i].value === String(value)) return options[i].value;
142
+ }
143
+ for (i = 0; i < options.length; i += 1) {
144
+ if ((options[i].text || options[i].textContent || "").trim().toLowerCase() === wanted) return options[i].value;
145
+ }
146
+ return null;
147
+ }
148
+
149
+ // Plain `el.value = x` doesn't notify a framework-controlled input (React,
150
+ // Vue) that anything changed, since it bypasses the property's own
151
+ // setter — using the native setter first, then dispatching input/change,
152
+ // is the same trick those frameworks' own test-utils use.
153
+ function fillField(el, value) {
154
+ if (el.tagName === "SELECT") {
155
+ value = selectOptionValue(el, value);
156
+ if (value === null) return false;
157
+ }
158
+
159
+ var setter = nativeValueSetter(el);
160
+ if (setter) {
161
+ setter.call(el, value);
162
+ } else {
163
+ el.value = value;
164
+ }
165
+ el.dispatchEvent(new Event("input", { bubbles: true }));
166
+ el.dispatchEvent(new Event("change", { bubbles: true }));
167
+ return true;
168
+ }
169
+
170
+ function fill(token, value) {
171
+ var el = findByAutocomplete(token) || findBySelector(selectors && selectors[token]);
172
+ return !!el && fillField(el, value);
173
+ }
174
+
175
+ // Real ISO 4217 codes, when the browser can list them (Chrome 99+,
176
+ // Node 18+), so a carrier name that happens to be three capitals (DPD,
177
+ // DHL, UPS, TNT, EMS) isn't read as a currency. Without the list, any
178
+ // three capitals count. Built at most once per autofill call.
179
+ var isoCodes;
180
+ function isIsoCode(code) {
181
+ if (isoCodes === undefined) {
182
+ isoCodes = null;
183
+ try {
184
+ if (typeof Intl !== "undefined" && typeof Intl.supportedValuesOf === "function") {
185
+ isoCodes = new Set(Intl.supportedValuesOf("currency"));
186
+ }
187
+ } catch (error) {
188
+ isoCodes = null;
189
+ }
190
+ }
191
+ return !isoCodes || isoCodes.has(code);
192
+ }
193
+
194
+ function firstIsoMatch(text, pass) {
195
+ var re = new RegExp(pass.pattern, "gu");
196
+ var m;
197
+ while ((m = re.exec(text)) !== null) {
198
+ if (isIsoCode(m[pass.code])) return m[pass.amount];
199
+ re.lastIndex = m.index + 1;
200
+ }
201
+ return null;
202
+ }
203
+
204
+ // One pass per shape, most specific first, so a number that merely sits
205
+ // next to a price isn't taken for it: in "Royal Mail Tracked 48 £3.50" a
206
+ // single leftmost-match regex read "48 £" (48); in "DPD 24 hours £6.00" it
207
+ // read "DPD 24" (24). A symbol before the amount is the usual shape, so
208
+ // it goes first; ISO codes only count once validated.
209
+ function ratePrice(text) {
210
+ var m = text.match(SYMBOL_THEN_AMOUNT) || text.match(AMOUNT_THEN_SYMBOL);
211
+ var raw = m ? m[1] : firstIsoMatch(text, CODE_THEN_AMOUNT) || firstIsoMatch(text, AMOUNT_THEN_CODE);
212
+ return raw === null ? null : parseAmount(raw);
213
+ }
214
+
215
+ // "1,950.00" / "1.950,00" / "1 950" -> 1950; "12,50" -> 12.5. A trailing
216
+ // separator with one or two digits after it is the decimal point; every
217
+ // other separator groups thousands.
218
+ function parseAmount(raw) {
219
+ var digits = raw.replace(/[\u00a0\u202f]/g, "");
220
+ var decimal = digits.match(/[.,](\d{1,2})$/);
221
+ var whole = decimal ? digits.slice(0, -decimal[0].length) : digits;
222
+ return parseFloat(whole.replace(/[.,]/g, "") + (decimal ? "." + decimal[1] : ""));
223
+ }
224
+
225
+ // Best-effort: groups same-named radio buttons whose visible label text
226
+ // looks like a shipping-rate price, and checks the cheapest option in
227
+ // each group not already selected — the DOM equivalent of
228
+ // Buy#cheapest_option_selection for a checkout with no UCP fulfillment
229
+ // groups to read. Only a single-rate Shopify checkout has been seen live
230
+ // (design-log §50/§51): it renders no radio at all, so there's nothing to
231
+ // pick. Multi-rate markup is still unverified; a group whose markup
232
+ // doesn't match this heuristic is simply left alone.
233
+ function selectCheapestRate() {
234
+ var groups = {};
235
+ var radios = doc.querySelectorAll("input[type='radio']");
236
+ for (var i = 0; i < radios.length; i += 1) {
237
+ var radio = radios[i];
238
+ if (!radio.name || radio.disabled) continue;
239
+
240
+ var label = (radio.id && doc.querySelector("label[for='" + radio.id + "']")) || radio.closest("label");
241
+ var text = ((label && label.textContent) || "").replace(/\s+/g, " ").trim();
242
+ var price = ratePrice(text);
243
+ if (price === null && !/\bfree\b/i.test(text)) continue;
244
+ if (price === null) price = 0;
245
+ (groups[radio.name] = groups[radio.name] || []).push({ radio: radio, price: price, text: text });
246
+ }
247
+
248
+ var picked = [];
249
+ Object.keys(groups).forEach(function (name) {
250
+ var options = groups[name];
251
+ if (options.length < 2) return;
252
+
253
+ var cheapest = options.reduce(function (a, b) { return b.price < a.price ? b : a; });
254
+ if (!cheapest.radio.checked) {
255
+ cheapest.radio.checked = true;
256
+ cheapest.radio.dispatchEvent(new Event("input", { bubbles: true }));
257
+ cheapest.radio.dispatchEvent(new Event("change", { bubbles: true }));
258
+ }
259
+ picked.push(cheapest.text);
260
+ });
261
+ return picked;
262
+ }
263
+
264
+ try {
265
+ if (isChallengePage()) {
266
+ return Promise.resolve(JSON.stringify({
267
+ ok: true, value: { blocked: "captcha", filled: [], unmatched: Object.keys(fields || {}), rate: [] }
268
+ }));
269
+ }
270
+
271
+ var filled = [];
272
+ var unmatched = [];
273
+ Object.keys(fields || {}).forEach(function (token) {
274
+ if (fill(token, fields[token])) {
275
+ filled.push(token);
276
+ } else {
277
+ unmatched.push(token);
278
+ }
279
+ });
280
+
281
+ var rate = selectCheapestRate();
282
+ return Promise.resolve(JSON.stringify({ ok: true, value: { blocked: null, filled: filled, unmatched: unmatched, rate: rate } }));
283
+ } catch (error) {
284
+ return Promise.resolve(JSON.stringify({
285
+ ok: false, code: "execute_failed", error: String((error && error.message) || error)
286
+ }));
287
+ }
288
+ })
@@ -0,0 +1,74 @@
1
+ module Portage
2
+ module Ucp
3
+ module WebMcp
4
+ # Phase 3 (docs/plans/webmcp-universal-outbound.md): drives the same
5
+ # bridge's browser that already holds the cart to fill the store's own
6
+ # checkout page — contact email and shipping address, nothing else.
7
+ # This module only decides *whether* to run the page script and what
8
+ # to make of its result; the actual DOM work (finding fields,
9
+ # refusing payment ones, detecting a challenge) lives entirely in
10
+ # assets/autofill.js, evaluated through Bridges::ScriptEvaluator#autofill.
11
+ #
12
+ # portage-cli owns everything upstream of this: the opt-in gate
13
+ # (WebmcpAutofillMode), the shopper-approval prompt
14
+ # (WebmcpAutofillConfirm), and building `fields` from PORTAGE_SHIP_*
15
+ # (WebmcpAutofillFields) — this module never reads shopper data or a
16
+ # config file itself. It exists in this gem, not portage-cli, because
17
+ # it's the piece that actually has to know the Bridge/Preset shapes.
18
+ module Autofill
19
+ Result = Struct.new(:outcome, :filled, :unmatched, :rate, keyword_init: true) do
20
+ def ok? = outcome == :filled
21
+ end
22
+
23
+ # @param bridge [#autofill, #headless?] the same Bridge already
24
+ # holding the cart, now pointed at the checkout page a preset's
25
+ # `handoff_checkout` tool navigated it to.
26
+ # @param fields [Hash{String=>String}] autocomplete token => value,
27
+ # already shopper-approved — this module fills exactly these and
28
+ # nothing more.
29
+ # @param selectors [Hash{String=>String}] a preset's fallback CSS
30
+ # selectors (Presets::Preset#checkout_selectors).
31
+ # @return [Result] outcome is :filled (ran; #filled/#unmatched say
32
+ # what matched), :needs_headed_browser (bridge is headless, or
33
+ # never said either way — see ScriptEvaluator.ferrum's note on why
34
+ # "unknown" is treated as headless), :blocked (a CAPTCHA/challenge
35
+ # was on the page; nothing was touched), or :unsupported (this
36
+ # bridge doesn't implement #autofill at all — a hand-rolled Bridge
37
+ # that only meets the base #list_tools/#execute_tool contract).
38
+ def self.call(bridge:, fields:, selectors: {})
39
+ return unsupported(fields) unless bridge.respond_to?(:autofill)
40
+ return needs_headed_browser(fields) if headless?(bridge)
41
+ return Result.new(outcome: :filled, filled: [], unmatched: [], rate: []) if fields.empty?
42
+
43
+ from_page(bridge.autofill(fields, selectors: selectors))
44
+ end
45
+
46
+ def self.from_page(value)
47
+ return Result.new(outcome: :blocked, filled: [], unmatched: [], rate: []) if value["blocked"]
48
+
49
+ Result.new(outcome: :filled, filled: Array(value["filled"]), unmatched: Array(value["unmatched"]),
50
+ rate: Array(value["rate"]))
51
+ end
52
+ private_class_method :from_page
53
+
54
+ # A bridge that never declares itself headless: false is treated as
55
+ # headless — the shopper has to be able to see and pay in this
56
+ # browser, so "unknown" is the safe default, not "assume headed".
57
+ def self.headless?(bridge)
58
+ !(bridge.respond_to?(:headless?) && bridge.headless? == false)
59
+ end
60
+ private_class_method :headless?
61
+
62
+ def self.unsupported(fields)
63
+ Result.new(outcome: :unsupported, filled: [], unmatched: fields.keys, rate: [])
64
+ end
65
+ private_class_method :unsupported
66
+
67
+ def self.needs_headed_browser(fields)
68
+ Result.new(outcome: :needs_headed_browser, filled: [], unmatched: fields.keys, rate: [])
69
+ end
70
+ private_class_method :needs_headed_browser
71
+ end
72
+ end
73
+ end
74
+ end
@@ -15,7 +15,16 @@ module Portage
15
15
  # and `#execute_tool(name, input)` (=> the tool's raw result), so a
16
16
  # caller with a different channel to the browser — a browser
17
17
  # extension, a CDP session, a remote grid — can write their own and
18
- # hand it to Transport directly.
18
+ # hand it to Transport directly. `#location` (=> the tab's current
19
+ # URL) is optional on top of that contract — nothing in this gem's
20
+ # own call path needs it, but `Cli::Buy`'s hand-off-only checkout
21
+ # path (docs/plans/webmcp-universal-outbound.md Phase 1) reads it
22
+ # after calling a tool that only navigates the tab rather than
23
+ # returning data, and checks `respond_to?(:location)` first since a
24
+ # hand-rolled Bridge may not implement it. `#headless?` and
25
+ # `#autofill` (Phase 3) are optional the same way, for the same
26
+ # reason: `Cli::Buy`'s autofill path checks `respond_to?` before
27
+ # using either.
19
28
  class ScriptEvaluator
20
29
  # How much of a driver's own error text a BridgeError quotes — the
21
30
  # same cap portage-ucp-decision puts on a Jev reply. Enough to name
@@ -25,22 +34,32 @@ module Portage
25
34
 
26
35
  # Ferrum: `Ferrum::Page#evaluate_async` passes its resolve callback
27
36
  # as `arguments[0]`.
28
- def self.ferrum(page, timeout: 30)
29
- new(evaluate: ->(expression) { page.evaluate_async("(#{expression}).then(arguments[0])", timeout) })
37
+ #
38
+ # @param headless [Boolean, nil] whether the browser this page runs
39
+ # in has no visible window — Ferrum knows this about itself
40
+ # (`browser.options[:headless]`), so a caller building this from
41
+ # a Ferrum::Browser can pass it straight through. nil (unset)
42
+ # means "unknown", which Phase 3's autofill treats the same as
43
+ # headless (see Autofill) — a shopper who can't see the browser
44
+ # can't pay in it either way, so the safe default when this
45
+ # isn't declared is to refuse, not to assume headed.
46
+ def self.ferrum(page, timeout: 30, headless: nil)
47
+ new(evaluate: ->(expression) { page.evaluate_async("(#{expression}).then(arguments[0])", timeout) },
48
+ headless: headless)
30
49
  end
31
50
 
32
51
  # Playwright (playwright-ruby-client): `Page#evaluate` awaits a
33
52
  # returned promise itself.
34
- def self.playwright(page)
35
- new(evaluate: ->(expression) { page.evaluate("() => #{expression}") })
53
+ def self.playwright(page, headless: nil)
54
+ new(evaluate: ->(expression) { page.evaluate("() => #{expression}") }, headless: headless)
36
55
  end
37
56
 
38
57
  # Selenium WebDriver: `execute_async_script` passes its done
39
58
  # callback as the last argument.
40
- def self.selenium(driver)
59
+ def self.selenium(driver, headless: nil)
41
60
  new(evaluate: lambda { |expression|
42
61
  driver.execute_async_script("var done = arguments[arguments.length - 1]; (#{expression}).then(done);")
43
- })
62
+ }, headless: headless)
44
63
  end
45
64
 
46
65
  # The expression #list_tools/#execute_tool hand to `evaluate:`.
@@ -49,10 +68,18 @@ module Portage
49
68
  "#{JSON.generate(input)})"
50
69
  end
51
70
 
52
- def initialize(evaluate:)
71
+ # The expression #autofill hands to `evaluate:` — assets/autofill.js
72
+ # (Phase 3), not consumer.js's tool-call protocol: this drives the
73
+ # checkout page's own DOM directly rather than a WebMCP tool.
74
+ def self.autofill_expression(fields, selectors)
75
+ "(#{Assets.read('autofill.js')})(#{JSON.generate(fields)}, #{JSON.generate(selectors)})"
76
+ end
77
+
78
+ def initialize(evaluate:, headless: nil)
53
79
  raise ArgumentError, "evaluate: must respond to #call" unless evaluate.respond_to?(:call)
54
80
 
55
81
  @evaluate = evaluate
82
+ @headless = headless
56
83
  end
57
84
 
58
85
  def list_tools
@@ -63,6 +90,38 @@ module Portage
63
90
  run("execute", name, input)
64
91
  end
65
92
 
93
+ # Not part of the merchant-side registrar's protocol (consumer.js
94
+ # has no "location" operation) — reads the tab's URL straight off
95
+ # `window.location.href` through the same `evaluate:` callable
96
+ # every other call uses, so a driver failure surfaces as the same
97
+ # BridgeError.
98
+ def location
99
+ evaluate("Promise.resolve(window.location.href)")
100
+ end
101
+
102
+ # @return [Boolean, nil] nil when the caller never said — see
103
+ # .ferrum's note on why that's treated as headless by Autofill.
104
+ def headless?
105
+ @headless
106
+ end
107
+
108
+ # Fills the checkout page's own contact/shipping fields directly —
109
+ # Phase 3's autofill, never a WebMCP tool call. See assets/autofill.js
110
+ # for exactly what it will and won't touch (never a payment field,
111
+ # never a submit control) and Autofill for the Ruby-side gate this
112
+ # sits behind (headless?, a CAPTCHA/challenge check baked into the
113
+ # script itself).
114
+ #
115
+ # @param fields [Hash{String=>String}] autocomplete token => value.
116
+ # @param selectors [Hash{String=>String}] a preset's fallback CSS
117
+ # selectors, tried only when no element on the page carries a
118
+ # matching `autocomplete` attribute for that token.
119
+ # @return [Hash] `{"blocked" => String|nil, "filled" => [...],
120
+ # "unmatched" => [...], "rate" => [...]}`.
121
+ def autofill(fields, selectors: {})
122
+ unwrap(evaluate(self.class.autofill_expression(fields, selectors)))
123
+ end
124
+
66
125
  private
67
126
 
68
127
  def run(operation, name = nil, input = nil)
@@ -0,0 +1,44 @@
1
+ module Portage
2
+ module Ucp
3
+ module WebMcp
4
+ # The UCP capabilities a page's WebMCP tools add up to, so a Session
5
+ # over them answers #advertises? with true/false instead of nil. A page
6
+ # has no manifest to read them from (unlike Client.discover), and a
7
+ # Session built without them can't gate on them: before this,
8
+ # Cli::Buy#webmcp_flow's cart/checkout check always failed against a
9
+ # real page.
10
+ #
11
+ # A capability counts when the page answers the action that starts it
12
+ # (after Transport's own tool_names:/prefix: resolution), not every
13
+ # action under it: a catalog with search but no lookup is still a
14
+ # catalog.
15
+ module Capabilities
16
+ STARTING_ACTIONS = {
17
+ "dev.ucp.shopping.catalog" => %w[search_catalog get_product lookup_catalog],
18
+ "dev.ucp.shopping.cart" => %w[create_cart],
19
+ "dev.ucp.shopping.checkout" => %w[create_checkout],
20
+ "dev.ucp.shopping.order" => %w[get_order]
21
+ }.freeze
22
+
23
+ CHECKOUT = "dev.ucp.shopping.checkout".freeze
24
+
25
+ # Reads the page's tools once, through the transport's cache.
26
+ #
27
+ # @param transport [Transport]
28
+ # @param handoff_checkout [String, nil] a preset's hand-off-only
29
+ # checkout tool (e.g. Shopify's `proceed_to_checkout`) — decision 1
30
+ # in docs/plans/webmcp-universal-outbound.md: a page that answers
31
+ # it counts as advertising checkout even though it only navigates
32
+ # the shopper to the store's own checkout, not `create_checkout`.
33
+ # @return [Array<String>]
34
+ def self.for(transport, handoff_checkout: nil)
35
+ STARTING_ACTIONS.filter_map do |capability, actions|
36
+ answers = actions.any? { |action| transport.answers?(action) }
37
+ answers ||= capability == CHECKOUT && handoff_checkout && transport.answers?(handoff_checkout)
38
+ capability if answers
39
+ end
40
+ end
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,41 @@
1
+ require "digest"
2
+ require "json"
3
+
4
+ module Portage
5
+ module Ucp
6
+ module WebMcp
7
+ # A page's WebMCP tools, reduced to what identifies its *shape* rather
8
+ # than any single store — shared by Presets.detect (Phase 1, name-only)
9
+ # and portage-cli's confirmed-mapping store (Phase 2, name + schema).
10
+ # Neither reads a tool's `description`: that's page text, and this
11
+ # gem's whole trust posture (see Presets' module comment) is that page
12
+ # text never decides a mapping — only what the page actually
13
+ # registers.
14
+ module Fingerprint
15
+ # @param tools [Array<Hash>] as Bridge#list_tools/Transport#tools
16
+ # returns them (string- or symbol-keyed).
17
+ # @return [Array<String>] tool names, sorted. What Presets.detect
18
+ # compares a preset's own fingerprint against — a platform's tool
19
+ # set is assumed stable enough that names alone are a safe key.
20
+ def self.names(tools)
21
+ tools.map { |tool| (tool["name"] || tool[:name]).to_s }.sort
22
+ end
23
+
24
+ # @return [String] a single digest of every tool's name *and* its
25
+ # own input schema — used to key a confirmed Phase 2 mapping
26
+ # (docs/plans/webmcp-universal-outbound.md decision 3), which is
27
+ # shared across origins with the exact same shape but must not be
28
+ # reused by a lookalike page whose schemas differ even though its
29
+ # tool names happen to match.
30
+ def self.for(tools)
31
+ parts = tools.map do |tool|
32
+ name = (tool["name"] || tool[:name]).to_s
33
+ schema = tool["inputSchema"] || tool[:inputSchema] || {}
34
+ "#{name}:#{Digest::SHA256.hexdigest(JSON.generate(schema))}"
35
+ end
36
+ Digest::SHA256.hexdigest(parts.sort.join("|"))
37
+ end
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,170 @@
1
+ module Portage
2
+ module Ucp
3
+ module WebMcp
4
+ # The Phase 2 fallback for a page `Presets.detect` doesn't recognize
5
+ # (docs/plans/webmcp-universal-outbound.md): proposes a `tool_names:`
6
+ # mapping from what the page's own tools *look like* — their names,
7
+ # tokenized and compared to each UCP action's own name; their input
8
+ # schema's property shape; and their `readOnlyHint` annotation.
9
+ #
10
+ # Deliberately never reads a tool's `description`: that's page text,
11
+ # the same untrusted-content boundary Presets draws (see its module
12
+ # comment) — a page could name a mutating tool `search_catalog` and
13
+ # write a friendly description, and nothing here would be fooled by
14
+ # either, because neither is consulted for scoring or for the
15
+ # `tool_names` this method returns.
16
+ #
17
+ # No LLM lives in this gem. A caller free to run its own matching
18
+ # (an agent with a model already in the loop) can just build a
19
+ # `tool_names:` hash directly and skip this — see the `shop-via-ucp`
20
+ # skill. This is the deterministic fallback for a caller with none.
21
+ #
22
+ # A proposal is not a mapping: nothing here calls a tool, prompts
23
+ # anyone, or persists anything. That's `portage-cli`'s job — it also
24
+ # enforces the confirm-before-mutate rule this method's docstring
25
+ # below leans on (`Portage::Cli::WebmcpMappingConfirm`,
26
+ # `Portage::Cli::WebmcpMappings`).
27
+ module Matcher
28
+ # @!attribute tool [String] the page's own tool name this action was
29
+ # matched to.
30
+ # @!attribute confidence [Float] 0.0-1.0, weighted from name-token
31
+ # overlap, input-schema shape and readOnlyHint agreement.
32
+ # @!attribute reason [String] plain-language explanation — never
33
+ # quotes the tool's own description (see module comment).
34
+ Proposal = Struct.new(:tool, :confidence, :reason, keyword_init: true)
35
+
36
+ Candidate = Struct.new(:tokens, :read_only, :shape, keyword_init: true)
37
+
38
+ # Weighted the way the module comment orders its evidence: what the
39
+ # tool is *called* matters most, what its *schema* looks like next,
40
+ # and the *hint* — often absent altogether — least.
41
+ WEIGHTS = { name: 0.5, shape: 0.35, read_only: 0.15 }.freeze
42
+
43
+ # Below this, a "match" is closer to noise than a proposal — every
44
+ # action stays unmapped rather than offering a guess nobody should
45
+ # trust, confirmed or not.
46
+ MIN_CONFIDENCE = 0.3
47
+
48
+ def self.candidate(tokens, read_only:, &shape)
49
+ Candidate.new(tokens: tokens, read_only: read_only, shape: shape)
50
+ end
51
+ private_class_method :candidate
52
+
53
+ # One entry per UCP action this gem's Session can drive over WebMCP
54
+ # (Transport#candidates_for's own action names). `update_checkout`/
55
+ # `complete_checkout`/order actions aren't included: WebMCP checkout
56
+ # is hand-off-only today (see docs/plans/webmcp-universal-outbound.md
57
+ # Context, "Checkout stays a hand-off"), so there's nothing for a
58
+ # matched `create_checkout` to be followed by yet.
59
+ CANDIDATES = {
60
+ "search_catalog" => candidate(%w[search find catalog products query lookup browse],
61
+ read_only: true) do |props|
62
+ props.include?("query")
63
+ end,
64
+ "get_product" => candidate(%w[get product item detail show fetch], read_only: true) do |props|
65
+ props.intersect?(%w[product_id id]) && !props.include?("quantity")
66
+ end,
67
+ "get_cart" => candidate(%w[get cart view fetch], read_only: true) do |props|
68
+ props.intersect?(%w[cart_id id]) && !props.include?("quantity")
69
+ end,
70
+ "create_cart" => candidate(%w[add cart create], read_only: false) do |props|
71
+ (props & %w[product_id variant_id quantity]).size >= 2
72
+ end,
73
+ "update_cart" => candidate(%w[update cart change modify lines], read_only: false) do |props|
74
+ props.include?("line_items") || (props.include?("cart_id") && props.include?("quantity"))
75
+ end,
76
+ "create_checkout" => candidate(%w[checkout create start begin proceed], read_only: false) do |props|
77
+ props.include?("line_items")
78
+ end
79
+ }.freeze
80
+
81
+ # @param tools [Array<Hash>] as Bridge#list_tools/Transport#tools
82
+ # returns them.
83
+ # @return [Hash{String => Proposal}] one entry per action a tool
84
+ # scored above MIN_CONFIDENCE against — an action with no
85
+ # plausible match on this page is simply absent, not given a weak
86
+ # guess.
87
+ def self.propose(tools)
88
+ CANDIDATES.each_with_object({}) do |(action, candidate), proposals|
89
+ best = best_match(candidate, tools)
90
+ proposals[action] = best if best
91
+ end
92
+ end
93
+
94
+ # @param proposal [Hash{String => Proposal}] as .propose returns.
95
+ # @return [Hash{String => String}] action => tool name, the shape
96
+ # `tool_names:` itself takes.
97
+ def self.tool_names(proposal) = proposal.transform_values(&:tool)
98
+
99
+ def self.best_match(candidate, tools)
100
+ tools.filter_map { |tool| score(candidate, tool) }.max_by(&:confidence)
101
+ end
102
+ private_class_method :best_match
103
+
104
+ def self.score(candidate, tool)
105
+ name = (tool["name"] || tool[:name]).to_s
106
+ return nil if name.empty?
107
+
108
+ overlap = tokenize(name) & candidate.tokens
109
+ return nil if overlap.empty?
110
+
111
+ name_score = overlap.size.to_f / candidate.tokens.size
112
+ properties = input_properties(tool)
113
+ shape_match = candidate.shape.call(properties)
114
+ read_only_hint = read_only_hint_of(tool)
115
+
116
+ confidence = weighted_confidence(name_score, shape_match, candidate.read_only, read_only_hint)
117
+ return nil if confidence < MIN_CONFIDENCE
118
+
119
+ Proposal.new(tool: name, confidence: confidence.round(2),
120
+ reason: reason_for(overlap, shape_match, candidate.read_only, read_only_hint))
121
+ end
122
+ private_class_method :score
123
+
124
+ def self.weighted_confidence(name_score, shape_match, expected_read_only, read_only_hint)
125
+ read_only_score = if read_only_hint.nil?
126
+ 0.5
127
+ else
128
+ read_only_hint == expected_read_only ? 1.0 : 0.0
129
+ end
130
+ (WEIGHTS[:name] * name_score) + (WEIGHTS[:shape] * (shape_match ? 1.0 : 0.0)) +
131
+ (WEIGHTS[:read_only] * read_only_score)
132
+ end
133
+ private_class_method :weighted_confidence
134
+
135
+ def self.reason_for(overlap, shape_match, expected_read_only, read_only_hint)
136
+ parts = ["name shares #{overlap.sort.join(', ')}"]
137
+ parts << "input schema matches the expected shape" if shape_match
138
+ parts << "readOnlyHint (#{read_only_hint.inspect}) agrees" if read_only_hint == expected_read_only
139
+ parts << "readOnlyHint (#{read_only_hint.inspect}) disagrees" if !read_only_hint.nil? &&
140
+ read_only_hint != expected_read_only
141
+ parts.join("; ")
142
+ end
143
+ private_class_method :reason_for
144
+
145
+ def self.input_properties(tool)
146
+ schema = tool["inputSchema"] || tool[:inputSchema] || {}
147
+ properties = schema["properties"] || schema[:properties] || {}
148
+ properties.keys.map(&:to_s)
149
+ end
150
+ private_class_method :input_properties
151
+
152
+ def self.read_only_hint_of(tool)
153
+ annotations = tool["annotations"] || tool[:annotations]
154
+ return nil unless annotations
155
+
156
+ value = annotations.key?("readOnlyHint") ? annotations["readOnlyHint"] : annotations[:readOnlyHint]
157
+ value.nil? ? nil : !!value
158
+ end
159
+ private_class_method :read_only_hint_of
160
+
161
+ # camelCase and snake_case alike, e.g. "findProducts" -> %w[find
162
+ # products], "search_catalog" -> %w[search catalog].
163
+ def self.tokenize(name)
164
+ name.to_s.gsub(/([a-z0-9])([A-Z])/, '\1_\2').split(/[_\-\s]+/).map(&:downcase).reject(&:empty?)
165
+ end
166
+ private_class_method :tokenize
167
+ end
168
+ end
169
+ end
170
+ end
@@ -0,0 +1,88 @@
1
+ module Portage
2
+ module Ucp
3
+ module WebMcp
4
+ # Built-in `tool_names:`/`wire:` mappings for platforms whose WebMCP
5
+ # pages are known to register one fixed tool set, so a caller doesn't
6
+ # have to pass `tool_names:` by hand against every store running that
7
+ # platform (docs/plans/webmcp-universal-outbound.md).
8
+ #
9
+ # `Presets.detect` picks a preset only from an exact match against the
10
+ # tool names a page registers *right now* — never from anything the
11
+ # page's own text says about itself (a `generator` meta tag,
12
+ # `window.Shopify`, a tool's own description). Any of that is page
13
+ # content, which is untrusted; a fingerprint is what the mapping
14
+ # actually depends on, and forging one costs registering all of it.
15
+ module Presets
16
+ # @!attribute checkout_selectors
17
+ # [Hash{String=>String}] Phase 3 (docs/plans/
18
+ # webmcp-universal-outbound.md) fallback CSS selectors, keyed by
19
+ # the same autocomplete token `Autofill`/assets/autofill.js
20
+ # already tries first — only reached when the checkout page's own
21
+ # markup doesn't carry a matching `autocomplete` attribute for
22
+ # that field.
23
+ Preset = Struct.new(:tool_names, :wire, :fingerprint, :handoff_checkout, :checkout_selectors,
24
+ keyword_init: true) do
25
+ def checkout_selectors = self[:checkout_selectors] || {}
26
+ end
27
+
28
+ # Shopify's own WebMCP tools (`window.Shopify.actions`, not this
29
+ # gem's registrar). Fingerprint taken live on 2026-09-28: ColourPop,
30
+ # tentree, Kylie Cosmetics, Brooklinen, Allbirds, Billabong and The
31
+ # Light Yard all register exactly these 11 tools, with identical
32
+ # input schemas (Gymshark and Fashion Nova register none). Shopify
33
+ # can change this set without notice; when it does, `detect` misses
34
+ # and the page is treated as unknown rather than mapped wrongly.
35
+ #
36
+ # `update_cart_lines` (addresses existing cart lines by line id, not
37
+ # by variant) and `proceed_to_checkout` (a navigation, not data)
38
+ # don't fit any Session method's contract, so neither gets a
39
+ # `tool_names:` entry — see the README's "Shopify storefronts"
40
+ # section. `proceed_to_checkout` is instead named as
41
+ # `handoff_checkout:`, the hand-off-only checkout tool Capabilities
42
+ # counts as checkout (decision 1) and Buy's WebMCP flow calls
43
+ # directly rather than through Session. `browse_store`,
44
+ # `show_variant`, `manage_orders` and `search_shop_policies_and_faqs`
45
+ # are left unmapped: none has been checked against a Session method.
46
+ SHOPIFY = Preset.new(
47
+ tool_names: { create_cart: "add_to_cart" },
48
+ wire: :auto,
49
+ fingerprint: %w[search_catalog browse_store get_product show_variant add_to_cart get_cart
50
+ update_cart_lines cancel_cart proceed_to_checkout manage_orders
51
+ search_shop_policies_and_faqs].freeze,
52
+ handoff_checkout: "proceed_to_checkout",
53
+ # Taken live on 2026-09-28 against The Light Yard's checkout
54
+ # (design-log §50). Shopify prefixes every contact/shipping token
55
+ # with the "shipping" section and uses different detail tokens for
56
+ # two of the fields WebmcpAutofillFields asks for: the email field
57
+ # is `shipping email` (not `email`) and the phone field is
58
+ # `shipping tel-national` (not `shipping tel`). Both selectors
59
+ # match on that attribute, not on Shopify's generated ids. Every
60
+ # other field matched by its own autocomplete value. `shipping
61
+ # country` hits Shopify's own autofill-capture input, which
62
+ # Shopify copies into the country `<select>` itself.
63
+ checkout_selectors: {
64
+ "email" => "input[autocomplete='shipping email']",
65
+ "shipping tel" => "input[autocomplete='shipping tel-national']"
66
+ }.freeze
67
+ ).freeze
68
+
69
+ ALL = { shopify: SHOPIFY }.freeze
70
+
71
+ # @param tools [Array<Hash>] a page's tools, as Bridge#list_tools/
72
+ # Transport#tools returns them.
73
+ # @return [Symbol, nil] the preset whose fingerprint is the exact set
74
+ # of names the page registers, or nil when none matches (an
75
+ # unrecognized page, or a known platform whose tool set has since
76
+ # changed).
77
+ def self.detect(tools)
78
+ names = Fingerprint.names(tools)
79
+ ALL.find { |_key, preset| preset.fingerprint.sort == names }&.first
80
+ end
81
+
82
+ # @param name [Symbol]
83
+ # @return [Preset]
84
+ def self.fetch(name) = ALL.fetch(name)
85
+ end
86
+ end
87
+ end
88
+ end
@@ -60,6 +60,10 @@ module Portage
60
60
  self
61
61
  end
62
62
 
63
+ # Whether a page tool answers `action` among the tools read so far
64
+ # (no re-read on a miss, unlike a call).
65
+ def answers?(action) = !find(candidates_for(action.to_s)).nil?
66
+
63
67
  def call_tool(name:, arguments:, meta: nil)
64
68
  tool = resolve(name.to_s)
65
69
  input = if wire_for(tool) == :ucp
@@ -104,10 +108,12 @@ module Portage
104
108
  # A page may register tools after load (or re-register on client-side
105
109
  # navigation), so one miss re-reads the page before giving up.
106
110
  def resolve(action)
107
- candidates = [@tool_names[action], "#{@prefix}#{action}", action].compact.uniq
111
+ candidates = candidates_for(action)
108
112
  find(candidates) || refresh!.then { find(candidates) } || raise(not_found(action, candidates))
109
113
  end
110
114
 
115
+ def candidates_for(action) = [@tool_names[action], "#{@prefix}#{action}", action].compact.uniq
116
+
111
117
  def find(candidates)
112
118
  candidates.each do |candidate|
113
119
  tool = tools.find { |t| t["name"] == candidate }
@@ -1,7 +1,7 @@
1
1
  module Portage
2
2
  module Ucp
3
3
  module WebMcp
4
- VERSION = "0.1.1".freeze
4
+ VERSION = "0.2.0".freeze
5
5
  end
6
6
  end
7
7
  end
@@ -13,6 +13,11 @@ require_relative "webmcp/bridges/script_evaluator"
13
13
  require_relative "webmcp/jsonable"
14
14
  require_relative "webmcp/page_wait"
15
15
  require_relative "webmcp/transport"
16
+ require_relative "webmcp/capabilities"
17
+ require_relative "webmcp/fingerprint"
18
+ require_relative "webmcp/presets"
19
+ require_relative "webmcp/matcher"
20
+ require_relative "webmcp/autofill"
16
21
 
17
22
  module Portage
18
23
  module Ucp
@@ -37,20 +42,55 @@ module Portage
37
42
  # )
38
43
  # session.search_catalog(query: "mug")
39
44
  #
45
+ # @param capabilities [Array<String>, nil] nil (the default) derives
46
+ # them from the tools the page registers right now (see
47
+ # Capabilities), which reads the page once here, so a BridgeError can
48
+ # raise from connect itself.
49
+ # @param preset [Symbol, nil] :auto (the default) detects a known
50
+ # platform from the page's own tools (Presets.detect) and, on a
51
+ # match, uses its tool_names:/wire: — reading the page once more, for
52
+ # the same BridgeError reason as capabilities: above. nil turns
53
+ # presets off entirely (today's behavior, before this parameter
54
+ # existed). A Symbol (:shopify) forces that preset without reading
55
+ # the page to detect it. Either way, an explicit tool_names:/wire: in
56
+ # transport_options wins over the preset's own — tool_names: key by
57
+ # key, wire: outright — since a caller who bothered to pass one knows
58
+ # this page better than a fingerprint match does.
40
59
  # @param transport_options [Hash] forwarded to Transport (prefix:,
41
60
  # tool_names:, wire:, reregister_wait:).
42
- def self.connect(bridge: nil, evaluate: nil, capabilities: nil, **transport_options)
61
+ def self.connect(bridge: nil, evaluate: nil, capabilities: nil, preset: :auto, **transport_options)
43
62
  bridge ||= Bridges::ScriptEvaluator.new(evaluate: evaluate) if evaluate
44
63
  raise ArgumentError, "connect requires either bridge: or evaluate:" unless bridge
45
64
 
46
- Portage::Ucp::Client::Session.new(transport: Transport.new(bridge: bridge, **transport_options),
47
- capabilities: capabilities)
65
+ resolved = resolve_preset(bridge, preset)
66
+ transport = Transport.new(bridge: bridge, **transport_options_for(resolved, transport_options))
67
+ Portage::Ucp::Client::Session.new(
68
+ transport: transport,
69
+ capabilities: capabilities || Capabilities.for(transport, handoff_checkout: resolved&.handoff_checkout)
70
+ )
48
71
  end
49
72
 
50
73
  # Page script installing a spec-shaped `document.modelContext` where
51
74
  # the browser has none — inject as an init script before navigation so
52
75
  # pages register into something the consumer can read.
53
76
  def self.polyfill_js = Assets.read("polyfill.js")
77
+
78
+ def self.resolve_preset(bridge, preset)
79
+ case preset
80
+ when :auto then (name = Presets.detect(bridge.list_tools)) && Presets.fetch(name)
81
+ when nil then nil
82
+ else Presets.fetch(preset)
83
+ end
84
+ end
85
+ private_class_method :resolve_preset
86
+
87
+ def self.transport_options_for(preset, transport_options)
88
+ return transport_options unless preset
89
+
90
+ { wire: preset.wire }.merge(transport_options)
91
+ .merge(tool_names: preset.tool_names.merge(transport_options[:tool_names] || {}))
92
+ end
93
+ private_class_method :transport_options_for
54
94
  end
55
95
  end
56
96
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: portage-ucp-webmcp
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.1
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Tom Whitbread
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-09-25 00:00:00.000000000 Z
11
+ date: 2026-09-29 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: portage-ucp
@@ -173,13 +173,19 @@ files:
173
173
  - README.md
174
174
  - lib/portage/ucp/webmcp.rb
175
175
  - lib/portage/ucp/webmcp/assets.rb
176
+ - lib/portage/ucp/webmcp/assets/autofill.js
176
177
  - lib/portage/ucp/webmcp/assets/consumer.js
177
178
  - lib/portage/ucp/webmcp/assets/polyfill.js
178
179
  - lib/portage/ucp/webmcp/assets/registrar.js
180
+ - lib/portage/ucp/webmcp/autofill.rb
179
181
  - lib/portage/ucp/webmcp/bridges/script_evaluator.rb
182
+ - lib/portage/ucp/webmcp/capabilities.rb
180
183
  - lib/portage/ucp/webmcp/errors.rb
184
+ - lib/portage/ucp/webmcp/fingerprint.rb
181
185
  - lib/portage/ucp/webmcp/jsonable.rb
186
+ - lib/portage/ucp/webmcp/matcher.rb
182
187
  - lib/portage/ucp/webmcp/page_wait.rb
188
+ - lib/portage/ucp/webmcp/presets.rb
183
189
  - lib/portage/ucp/webmcp/rack/app.rb
184
190
  - lib/portage/ucp/webmcp/rack/call_endpoint.rb
185
191
  - lib/portage/ucp/webmcp/rack/request_limits.rb