"""Cross-chain service discovery and ranking (`find_service`). One search over every public catalog of machine-payable services, merged by endpoint and ranked for a payer that holds USDC on several networks: - ``cdp-bazaar``: Coinbase's x402 Bazaar search (x402 on Base, Solana, ...) - ``mpp``: the mpp.dev service catalog (MPP charges on Tempo) - ``crowdcode``: services CrowdCode already has reviews for - ``caller``: candidates the caller found elsewhere (e.g. AgentCash search) Ranking, best first: 1. Quality: the CrowdCode canonical score in quarter-point bands. A service with no reviews sits at the scoring prior (3.0), so positive evidence ranks above unknown services and poor evidence below them. 2. Effective price on the payer's best network: the quoted price, plus one transfer between the payer's own networks when that network's balance does not cover it. 3. The payer's balance on that network. Prices come from catalogs and can be dynamic; callers must inspect the endpoint for the live quote before paying. The query is used only for the search and is never stored. """ from __future__ import annotations import bisect import functools import os import math import re import threading import time import traceback from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass, field from typing import Any, Callable, Iterable import httpx import psycopg from crowdcode.review_sql import directory_listed from crowdcode import offerings, semantic from crowdcode.identity import normalize_api_endpoint from crowdcode.networks import fetch_service_networks from crowdcode.scoring import as_float, is_unproven CDP_SEARCH_URL = "https://api.cdp.coinbase.com/platform/v2/x402/discovery/search" MPP_CATALOG_URL = "https://mpp.dev/api/services" BASE_NETWORK = "eip155:8453" SOLANA_NETWORK = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp" TEMPO_NETWORK = "eip155:4217" MONAD_NETWORK = "eip155:143" # The token each network's payers settle in (USDC; Stargate USDC.e on Tempo). NETWORK_TOKENS = { "base": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913", "solana": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "tempo": "0x20c000000000000000000000b9537d11c60e8b50", "monad": "0x754704bc059f8c67012fed69bc8a327a5aafb603", } NETWORK_ALIASES = { BASE_NETWORK: "base", "base": "base", SOLANA_NETWORK.lower(): "solana", "solana": "solana", "solana:mainnet": "solana", TEMPO_NETWORK: "tempo", "tempo": "tempo", "tempo:4217": "tempo", "tempo:mainnet": "tempo", MONAD_NETWORK: "monad", "monad": "monad", } DEFAULT_NETWORKS = ("base", "solana", "tempo") # Moving USDC between one's own networks (Relay) costs about $0.02-0.03. TRANSFER_COST_USD = 0.03 # Services rated below this with real evidence are refused by OpenCrowd's gateway. SCORE_FLOOR = 2.0 # An unrated service's sort key: 5 x P(>3) with no evidence (scoring v4). PRIOR_SCORE = 2.5 # Within a quality band, services that several distinct payers used recently rank first. ADOPTED_PAYERS = 3 SOURCE_LIMIT = 12 # Listings offered per search, best matches first. DIRECTORY_LIMIT = 8 # Meaning (semantic.py): a cosine similarity of SEMANTIC_ZERO counts as no match and # SEMANTIC_FULL as a full one. A listing whose words do not match joins the search when # its similarity is within SEMANTIC_ADMIT_GAP of the best listing's and at least # SEMANTIC_ADMIT_FLOOR. # # Match strength is KEYWORD_SHARE shared words and the rest meaning; it is worth # RELEVANCE_WEIGHT quality points per unit, in RELEVANCE_STEPS steps, so a much better # match beats a somewhat better score, and on a near-tie in match quality still decides. # # Chosen on tests/search_eval (SRI-86) from a grid over all five, checked on both halves # of the set separately; the neighbourhood of these values scores within about one case. SEMANTIC_ZERO = 0.25 SEMANTIC_FULL = 0.55 SEMANTIC_ADMIT_FLOOR = 0.30 SEMANTIC_ADMIT_GAP = 0.20 KEYWORD_SHARE = 0.3 RELEVANCE_WEIGHT = 1.0 RELEVANCE_STEPS = 10 # Below this match a result ranks after every real match, whatever its score. WEAK_MATCH = 0.2 DEFAULT_LIMIT = 10 MAX_LIMIT = 25 MAX_CANDIDATES = 50 HTTP_TIMEOUT = 8.0 MPP_CACHE_SECONDS = 600 SEARCH_CACHE_SECONDS = 60 # Generic request words; catalog matching keys on the subject ("drug", "storage"). _STOPWORDS = frozenset( "a an and any api apis are as at be best buy by call check current data details does find " "fetch for from get give how i info information in into is it latest list look lookup me my " "name names need of on or paid please query request return service services some that the " "this to tool use using via want what which with".split() ) @dataclass class Offer: network: str | None # short name when recognised ("base"), else as advertised; None = unknown protocol: str # "x402" | "mpp" price_usd: float | None payable: bool | None # None: the network is unknown until the endpoint is inspected def as_dict(self) -> dict[str, Any]: return { "network": self.network, "protocol": self.protocol, "price_usd": self.price_usd, "payable": self.payable, } @dataclass class Candidate: endpoint: str method: str | None = None name: str | None = None description: str | None = None offers: list[Offer] = field(default_factory=list) sources: list[str] = field(default_factory=list) order: int = 0 # best position within any source's own relevance order unique_payers: int | None = None # catalog usage: distinct payers over the last 30 days document: str | None = None # what a directory listing is matched on (semantic.document) keyword: float | None = None # share of the query's words it matches similarity: float | None = None # cosine similarity of its document to the query def text(self) -> str: return self.document or semantic.document(self.name, self.description, endpoint=self.endpoint) def merge(self, other: "Candidate") -> None: self.order = min(self.order, other.order) # A listing's document is the richer text; scores computed on it stay with it. if other.document and not self.document: self.document, self.keyword, self.similarity = other.document, other.keyword, other.similarity if other.unique_payers is not None: self.unique_payers = max(self.unique_payers or 0, other.unique_payers) self.method = self.method or other.method self.name = self.name or other.name self.description = self.description or other.description known = {(o.network, o.protocol) for o in self.offers} for offer in other.offers: if (offer.network, offer.protocol) in known: continue # A concrete network replaces an "unknown network" placeholder of the same protocol. self.offers = [o for o in self.offers if not (o.network is None and o.protocol == offer.protocol)] self.offers.append(offer) known.add((offer.network, offer.protocol)) for source in other.sources: if source not in self.sources: self.sources.append(source) def network_name(value: Any) -> str | None: text = str(value or "").strip() return NETWORK_ALIASES.get(text.lower()) or NETWORK_ALIASES.get(text) def price_from_atomic(amount: Any, decimals: Any = 6) -> float | None: try: atomic = int(str(amount)) places = int(decimals) if decimals is not None else 6 except (TypeError, ValueError): return None return atomic / 10**places if atomic >= 0 else None def price_from_text(value: Any) -> float | None: if isinstance(value, (int, float)) and math.isfinite(value): return float(value) match = re.search(r"\d+(?:\.\d+)?", str(value or "")) return float(match.group(0)) if match else None def tokens(text: str) -> list[str]: words = re.findall(r"[a-z0-9]+", text.lower()) return [w for w in dict.fromkeys(words) if len(w) >= 3 and w not in _STOPWORDS] @functools.lru_cache(maxsize=16384) def _haystack(text: str) -> tuple[frozenset[str], frozenset[str], tuple[str, ...]]: """A text's words, their six-letter stems, and the words sorted for prefix lookups.""" words = frozenset(re.findall(r"[a-z0-9]+", text.lower())) return words, frozenset(w[:6] for w in words), tuple(sorted(words)) def _matches(token: str, haystack: tuple[frozenset[str], frozenset[str], tuple[str, ...]]) -> bool: # A shared six-letter stem matches word forms: "generation" and "generate-ics". words, stems, ordered = haystack if token in words or (len(token) >= 6 and token[:6] in stems): return True index = bisect.bisect_left(ordered, token) return index < len(ordered) and ordered[index].startswith(token) def relevance(query_tokens: list[str], text: str) -> float: if not query_tokens: return 0.0 haystack = _haystack(text) return sum(1 for t in query_tokens if _matches(t, haystack)) / len(query_tokens) def _endpoint(value: Any) -> str | None: try: return normalize_api_endpoint(str(value)) if value else None except ValueError: return None # --- Sources ----------------------------------------------------------------- def x402_offer(accept: dict[str, Any], networks: Iterable[str]) -> Offer: name = network_name(accept.get("network")) asset = str(accept.get("asset") or "") token = NETWORK_TOKENS.get(name or "") scheme = accept.get("scheme") payable = bool( name in networks and token is not None and (asset == token if name == "solana" else asset.lower() == token) and scheme in (None, "exact") ) return Offer( network=name or str(accept.get("network") or "") or None, protocol="x402", price_usd=price_from_atomic(accept.get("amount") or accept.get("maxAmountRequired"), (accept.get("extra") or {}).get("decimals", 6)), payable=payable, ) def cdp_candidates(payload: Any, networks: Iterable[str]) -> list[Candidate]: networks = tuple(networks) out: list[Candidate] = [] for resource in (payload or {}).get("resources") or (payload or {}).get("items") or []: endpoint = _endpoint(resource.get("resource")) if not endpoint: continue bazaar = (resource.get("extensions") or {}).get("bazaar") or {} info = bazaar.get("info") or {} method = ((info.get("input") or {}).get("method") or None) usage = (resource.get("quality") or {}).get("l30DaysUniquePayers") out.append(Candidate( endpoint=endpoint, method=method.upper() if isinstance(method, str) else None, name=bazaar.get("name"), description=resource.get("description") or bazaar.get("description"), offers=[x402_offer(a, networks) for a in resource.get("accepts") or [] if isinstance(a, dict)], sources=["cdp-bazaar"], unique_payers=usage if isinstance(usage, int) else None, )) return out def mpp_candidates(catalog: Any, query: str, networks: Iterable[str], limit: int = 2 * SOURCE_LIMIT) -> list[Candidate]: query_tokens = tokens(query) scored: list[tuple[float, Candidate]] = [] for service in (catalog or {}).get("services") or []: base = service.get("serviceUrl") if not base or service.get("status") not in (None, "active"): continue service_text = " ".join(str(v) for v in ( service.get("name"), service.get("description"), " ".join(service.get("tags") or []), " ".join(service.get("categories") or []), ) if v) for endpoint in service.get("endpoints") or []: payment = endpoint.get("payment") or {} if payment.get("method") != "tempo" or payment.get("intent") != "charge": continue # sessions open payment channels; other methods are not payable endpoint_score = relevance(query_tokens, f"{endpoint.get('description') or ''} {endpoint.get('path') or ''}") score = max(endpoint_score, 0.6 * relevance(query_tokens, service_text) + 0.4 * endpoint_score) if score < 0.5: continue url = _endpoint(str(base).rstrip("/") + str(endpoint.get("path") or "")) if not url: continue payable = "tempo" in networks and str(payment.get("currency") or "").lower() == NETWORK_TOKENS["tempo"] scored.append((score, Candidate( endpoint=url, method=str(endpoint.get("method") or "GET").upper(), name=f"{service.get('name')}: {endpoint.get('description')}" if endpoint.get("description") else service.get("name"), description=service.get("description"), offers=[Offer("tempo", "mpp", price_from_atomic(payment.get("amount"), payment.get("decimals", 6)), payable)], sources=["mpp"], ))) scored.sort(key=lambda item: -item[0]) return [candidate for _, candidate in scored[:limit]] def caller_candidates(raw: Any, networks: Iterable[str]) -> list[Candidate]: """Candidates the caller already found, e.g. AgentCash search results. Accepts ``{endpoint|url, method?, name?, description?, price_usd?, network?|networks?, protocol?|protocols?, unique_payers?, source?}``. """ networks = tuple(networks) out: list[Candidate] = [] for item in (raw or [])[:MAX_CANDIDATES]: if not isinstance(item, dict): continue endpoint = _endpoint(item.get("endpoint") or item.get("url")) if not endpoint: continue price = price_from_text(item.get("price_usd", item.get("price"))) listed = item.get("networks") or ([item["network"]] if item.get("network") else []) protocols = item.get("protocols") or ([item["protocol"]] if item.get("protocol") else ["x402"]) offers: list[Offer] = [] for value in listed: name = network_name(value) protocol = "mpp" if name == "tempo" else "x402" offers.append(Offer(name or str(value), protocol, price, name in networks if name else False)) if not offers: offers = [Offer("tempo" if p == "mpp" else None, "mpp" if p == "mpp" else "x402", price, ("tempo" in networks) if p == "mpp" else None) for p in dict.fromkeys(str(p).lower() for p in protocols)] source = str(item.get("source") or "caller")[:40] usage = item.get("unique_payers") out.append(Candidate(endpoint=endpoint, method=(str(item["method"]).upper() if item.get("method") else None), name=item.get("name"), description=item.get("description"), offers=offers, sources=[source], unique_payers=int(usage) if isinstance(usage, (int, float)) and usage >= 0 else None)) return out def listing_document(row: dict[str, Any]) -> str: """What a listing is matched on. A listing whose service describes itself nowhere is matched on what its verified buyers found it did: the published pros of its review summary.""" listing_text = row.get("listing_text") pros = row.get("review_pros") if isinstance(pros, list) and pros and not row.get("description"): listing_text = " ".join(filter(None, [listing_text, " ".join(str(p) for p in pros[:5])])) return semantic.document(row.get("name"), row.get("description"), listing_text, row.get("canonical_endpoint"), row.get("directory_slug")) def directory_candidates(rows: list[dict[str, Any]], query: str, limit: int = DIRECTORY_LIMIT, networks: dict[str, dict[str, Any]] | None = None, payer_networks: Iterable[str] = DEFAULT_NETWORKS, embedder: semantic.Embedder | None = None) -> list[Candidate]: """Listed services matching the query, with the networks CrowdCode has seen them paid or advertised on. A listing matches on its words (half the query's subject words) or, with the model loaded, on meaning: a similarity within SEMANTIC_ADMIT_GAP of the best listing's and at least SEMANTIC_ADMIT_FLOOR. """ query_tokens = tokens(query) payer_networks = tuple(payer_networks) listed = [(row, endpoint) for row in rows if (endpoint := _endpoint(row.get("canonical_endpoint")))] documents = [listing_document(row) for row, _ in listed] similarities = embedder.similarities(query, documents) if embedder is not None else None best = max(similarities, default=0.0) if similarities else 0.0 scored = [] for index, ((row, endpoint), text) in enumerate(zip(listed, documents)): keyword = relevance(query_tokens, f"{text} {endpoint}") similarity = similarities[index] if similarities is not None else None semantic_match = similarity is not None and similarity >= max(SEMANTIC_ADMIT_FLOOR, best - SEMANTIC_ADMIT_GAP) if keyword < 0.5 and not semantic_match: continue protocol = "mpp" if row.get("payment_provider") == "mppx" else "x402" seen = [n for n in ((networks or {}).get(row.get("id")) or {}).get("networks", []) if n in NETWORK_TOKENS] offers = [Offer(n, "mpp" if n == "tempo" else "x402", None, n in payer_networks) for n in seen] or [ Offer("tempo" if protocol == "mpp" else None, protocol, None, ("tempo" in payer_networks) if protocol == "mpp" else None)] candidate = Candidate(endpoint=endpoint, name=row.get("name"), description=row.get("description"), offers=offers, sources=["crowdcode"], document=text, keyword=keyword, similarity=similarity) scored.append((match_strength(keyword, similarity), candidate)) scored.sort(key=lambda item: -item[0]) return [candidate for _, candidate in scored[:limit]] def match_strength(keyword: float, similarity: float | None) -> float: """How well a candidate matches the query, 0 to 1: meaning blended with shared words.""" if similarity is None: return keyword meaning = min(1.0, max(0.0, (similarity - SEMANTIC_ZERO) / (SEMANTIC_FULL - SEMANTIC_ZERO))) return KEYWORD_SHARE * keyword + (1 - KEYWORD_SHARE) * meaning class CatalogClient: """HTTP access to the public catalogs, with short caches.""" def __init__(self, get: Callable[..., httpx.Response] | None = None) -> None: self._get = get or httpx.get self._mpp: tuple[float, Any] | None = None self._searches: dict[str, tuple[float, Any]] = {} def cdp_search(self, query: str) -> Any: key = query.strip().lower() cached = self._searches.get(key) if cached and cached[0] > time.monotonic(): return cached[1] response = self._get(CDP_SEARCH_URL, params={"query": query, "limit": SOURCE_LIMIT}, headers={"accept": "application/json"}, timeout=HTTP_TIMEOUT) response.raise_for_status() payload = response.json() if len(self._searches) > 256: self._searches.clear() self._searches[key] = (time.monotonic() + SEARCH_CACHE_SECONDS, payload) return payload def mpp_catalog(self) -> Any: if self._mpp and self._mpp[0] > time.monotonic(): return self._mpp[1] response = self._get(MPP_CATALOG_URL, headers={"accept": "application/json"}, timeout=HTTP_TIMEOUT) response.raise_for_status() payload = response.json() self._mpp = (time.monotonic() + MPP_CACHE_SECONDS, payload) return payload CATALOGS = CatalogClient() # --- Quality ------------------------------------------------------------------- def directory_rows(conn: psycopg.Connection) -> list[dict[str, Any]]: return conn.execute( f""" select id, name, directory_slug, canonical_endpoint, payment_provider, metadata->>'description' as description, metadata->>'listing_text' as listing_text, review_summary->'pros' as review_pros from services -- A hosted service its owner deleted is not offered (hosted_services.py). where coalesce(metadata->>'hosted_status', '') <> 'deleted' and {directory_listed()} """ ).fetchall() def evidence_by_endpoint(conn: psycopg.Connection, endpoints: list[str]) -> dict[str, dict[str, Any]]: """CrowdCode evidence for each endpoint that resolves to a reviewed service.""" if not endpoints: return {} rows = conn.execute( """ with matched as ( select si.identifier_value as endpoint, si.service_id from service_identifiers si where si.identifier_type = 'api_endpoint' and si.identifier_value = any(%s) union select s.canonical_endpoint, s.id from services s where s.canonical_endpoint = any(%s) ) select m.endpoint, s.id as service_id, s.score, s.score_mean, s.n_eff, count(r.id)::int as num_reviews, count(r.id) filter (where r.payment_verified)::int as num_verified_reviews from matched m join services s on s.id = m.service_id left join reviews r on r.service_id = s.id group by m.endpoint, s.id, s.score, s.score_mean, s.n_eff """, (endpoints, endpoints), ).fetchall() return {row["endpoint"]: row for row in rows} def quality(evidence: dict[str, Any] | None) -> dict[str, Any]: if not evidence: return {"score": PRIOR_SCORE, "floor_score": 3.0, "reviewed": False, "unproven": True, "n_eff": 0.0, "num_reviews": 0, "num_verified_reviews": 0} score = as_float(evidence.get("score")) n_eff = as_float(evidence.get("n_eff")) or 0.0 # The payment floor compares the review posterior mean (v3.1's number) # with 2, as every payer does; ranking uses the published score. floor_score = as_float(evidence.get("score_mean")) return { "service_id": evidence.get("service_id"), "score": score if score is not None else PRIOR_SCORE, "floor_score": floor_score if floor_score is not None else (score if score is not None else 3.0), "reviewed": (evidence.get("num_reviews") or 0) > 0, "unproven": is_unproven(n_eff), "n_eff": n_eff, "num_reviews": evidence.get("num_reviews") or 0, "num_verified_reviews": evidence.get("num_verified_reviews") or 0, } def quality_band(q: dict[str, Any]) -> float: # Quarter points: a clearly better score always wins; price only breaks near-ties. return math.floor(float(q["score"]) * 4 + 0.5) / 4 # --- Ranking ------------------------------------------------------------------- def best_offer(candidate: Candidate, networks: tuple[str, ...], balances: dict[str, float] | None) -> dict[str, Any] | None: """The payer's best offer for one service: lowest effective price, then the larger balance.""" choices = [] for offer in candidate.offers: if offer.payable is False: continue balance = balances.get(offer.network) if balances is not None and offer.network else None transfer = False fundable = True effective = offer.price_usd if balances is not None and offer.network in networks and offer.price_usd is not None: if (balance or 0.0) < offer.price_usd: transfer = True effective = offer.price_usd + TRANSFER_COST_USD shortfall = offer.price_usd - (balance or 0.0) + TRANSFER_COST_USD fundable = any(v >= shortfall for n, v in balances.items() if n != offer.network and n in networks) choices.append({ "network": offer.network, "protocol": offer.protocol, "price_usd": offer.price_usd, "effective_price_usd": round(effective, 6) if effective is not None else None, "transfer_needed": transfer, "fundable": fundable, "balance_usd": balance, }) if not choices: return None choices.sort(key=lambda c: (not c["fundable"], c["effective_price_usd"] is None, c["effective_price_usd"] or 0.0, -(c["balance_usd"] or 0.0))) return choices[0] def relevance_band(strength: float) -> float: return math.floor(strength * RELEVANCE_STEPS + 1e-9) / RELEVANCE_STEPS def rank(candidates: list[Candidate], evidence: dict[str, dict[str, Any]], networks: tuple[str, ...], balances: dict[str, float] | None) -> list[dict[str, Any]]: """Best first. With meaning known, how well a service matches and how good it is are traded off (RELEVANCE_WEIGHT quality points per unit of match); without it, quality leads as before.""" by_meaning = any(c.similarity is not None for c in candidates) ranked = [] for candidate in candidates: best = best_offer(candidate, networks, balances) if best is None: continue # nothing this payer can settle q = quality(evidence.get(candidate.endpoint)) below_floor = not q["unproven"] and q["floor_score"] < SCORE_FLOOR adopted = (candidate.unique_payers or 0) >= ADOPTED_PAYERS strength = match_strength(candidate.keyword or 0.0, candidate.similarity) if by_meaning else None merit = quality_band(q) + (RELEVANCE_WEIGHT * relevance_band(strength) if strength is not None else 0.0) # A catalog may return something that matches nothing asked for; its score is not a reason to show it first. off_topic = strength is not None and strength < WEAK_MATCH key = ( below_floor, off_topic, -round(merit, 6), not adopted, not best["fundable"], best["effective_price_usd"] is None, best["effective_price_usd"] or 0.0, -(best["balance_usd"] or 0.0), candidate.order, ) ranked.append((key, candidate, q, best, below_floor, strength)) ranked.sort(key=lambda item: item[0]) out = [] for position, (_, candidate, q, best, below_floor, strength) in enumerate(ranked, start=1): out.append({ "rank": position, "endpoint": candidate.endpoint, "method": candidate.method, "name": candidate.name, "description": (candidate.description or "")[:300] or None, "match": round(strength, 3) if strength is not None else None, "quality": {**q, "score": round(q["score"], 2), "n_eff": round(q["n_eff"], 2), "unique_payers_30d": candidate.unique_payers, **({"below_floor": True} if below_floor else {})}, "best": best, "offers": [o.as_dict() for o in candidate.offers], "sources": candidate.sources, }) return out def score_matches(candidates: list[Candidate], query: str, embedder: semantic.Embedder | None) -> bool: """Keyword and meaning for every candidate that has not been scored yet; False without the model.""" query_tokens = tokens(query) for candidate in candidates: if candidate.keyword is None: candidate.keyword = relevance(query_tokens, f"{candidate.text()} {candidate.endpoint}") if embedder is None: return False pending = [c for c in candidates if c.similarity is None] similarities = embedder.similarities(query, [c.text() for c in pending]) if similarities is None: for candidate in candidates: candidate.similarity = None # all or nothing: one scale for every candidate return False for candidate, similarity in zip(pending, similarities): candidate.similarity = similarity return True def parse_networks(value: Any) -> tuple[str, ...]: if not value: return DEFAULT_NETWORKS items = value.split(",") if isinstance(value, str) else value names = [network_name(v) for v in items] return tuple(dict.fromkeys(n for n in names if n)) or DEFAULT_NETWORKS def parse_balances(value: Any) -> dict[str, float] | None: if not isinstance(value, dict): return None out: dict[str, float] = {} for key, amount in value.items(): name = network_name(key) number = price_from_text(amount) if amount is not None else None if name and number is not None: out[name] = number return out or None _TIE_BREAKS = ( f"within a tie, services with {ADOPTED_PAYERS}+ distinct payers in 30 days first, then effective price on your best " f"network (plus ~${TRANSFER_COST_USD:.2f} for one transfer between your own networks when that network's balance " "is short), then your balance there. Catalog prices can be dynamic: inspect the endpoint for the live quote before paying." ) RANKING = ( "Ranked by how well each service matches the request (its meaning and words; `match`, 0-1) together with " "CrowdCode quality (canonical score in quarter-point bands; unreviewed services sit at 2.5, unrated): " f"a full match is worth {RELEVANCE_WEIGHT:g} quality point(s), so a much closer match beats a somewhat better score " "and on a near-tie in match the better-reviewed service wins; " + _TIE_BREAKS ) RANKING_BY_QUALITY = ( "Ranked by CrowdCode quality (canonical score in quarter-point bands; unreviewed services sit at 2.5, unrated); " + _TIE_BREAKS ) def find_services( query: str, *, networks: Any = None, balances: Any = None, candidates: Any = None, limit: Any = None, conn_factory: Callable[[], Any] | None = None, catalogs: CatalogClient | None = None, embedder: semantic.Embedder | None = None, seed: Any = None, detail: Any = None, index: offerings.OfferingIndex | None = None, ) -> dict[str, Any]: """C13: search the whole index in memory; the live catalogs only when the index has no match. ``index`` is the offering index to search (tests, the evaluation set); by default the process's shared one, refreshed in the background from ``conn_factory``. ``seed`` reproduces a ranking (the response returns the one it used); ``detail="full"`` adds each result's evidence. """ query = (query or "").strip()[:500] embedder = embedder if embedder is not None else (semantic.EMBEDDER if semantic.enabled() else None) if not query: return {"ok": False, "error": "query is required", "services": []} payer_networks = parse_networks(networks) payer_balances = parse_balances(balances) try: size = max(1, min(MAX_LIMIT, int(limit))) if limit is not None else DEFAULT_LIMIT except (TypeError, ValueError): size = DEFAULT_LIMIT if index is None and conn_factory is not None: offerings.SHARED.refresh_due(conn_factory, embedder) index = offerings.SHARED.get() if index is not None and len(index): found = find_in_index(index, query, payer_networks, payer_balances, candidates, size, embedder, seed=seed, detail=detail == "full") if found is not None: return found return find_live(query, payer_networks, payer_balances, candidates, size, conn_factory, catalogs, embedder) _PLATFORM = re.compile(r"\b(?:on |in |from |via )?(?:crowd ?code|open ?crowd)(?:\.app)?\b", re.IGNORECASE) def find_in_index(index: offerings.OfferingIndex, query: str, networks: tuple[str, ...], balances: dict[str, float] | None, candidates: Any, size: int, embedder: semantic.Embedder | None, *, seed: Any = None, detail: bool = False) -> dict[str, Any] | None: """Ranked offerings from the index, or None when nothing in it matches above the floor.""" asked = query started = time.perf_counter() # "Is there a service on CrowdCode that…": the platform's name says nothing about the capability. query = _PLATFORM.sub(" ", query).strip() or query matches = index.match(query, embedder) seen = {id(m.offering) for m in matches} extra = _caller_offerings(index, candidates, networks, query, embedder, seen) if not extra and (not matches or matches[0].strength < offerings.INDEX_FLOOR): return None matches = sorted([*matches, *extra], key=lambda m: (-m.strength, m.offering.id)) model_rows, model = index.models_in(query) used = offerings.parse_seed(seed) used = used if used is not None else offerings.new_seed() leaf_similarity = index.leaf_similarity(index.query_vector(query, embedder)) ranked, info = offerings.rank(matches, networks=networks, balances=balances, seed=used, model_rows=model_rows or None, model=model, leaf_similarity=leaf_similarity, producers=index.producers) services = [offerings.describe(r, position, detail, info.get("capability")) for position, r in enumerate(ranked[:size], start=1)] left_out = {k: v for k, v in info["left_out"].items() if v} return { "ok": True, "query": asked, "source": "index", "seed": used, **({"networks": list(networks)} if networks != DEFAULT_NETWORKS else {}), **({"balances_considered": True} if balances is not None else {}), **({"capability": info["capability"]} if info.get("capability") else {}), **({"policy": info["policy"]} if info.get("policy") else {}), **({"model": model} if model else {}), "ranking": offerings.RANKING, "services": services, "total_matches": len(ranked), **({"left_out": left_out} if left_out else {}), **({"index": {"offerings": len(index), "age_s": int(time.time() - index.built_at), "ms": round((time.perf_counter() - started) * 1000, 1)}} if detail else {}), } def _caller_offerings(index: offerings.OfferingIndex, raw: Any, networks: tuple[str, ...], query: str, embedder: semantic.Embedder | None, seen: set[int]) -> list[offerings.Match]: """Candidates the caller found elsewhere (AgentCash), as index offerings when the index has them.""" out: list[offerings.Match] = [] fresh: list[offerings.Offering] = [] for candidate in caller_candidates(raw, networks): known = index.find(candidate.endpoint, candidate.method) if known is not None: if id(known) not in seen: seen.add(id(known)) fresh.append(known) continue price = next((o.price_usd for o in candidate.offers if o.price_usd is not None), None) listed = tuple(dict.fromkeys(o.network for o in candidate.offers if o.network in networks)) unknown = tuple(n for n in networks if n != "tempo") if any(o.network is None for o in candidate.offers) else () # Not in the index: a new offering with no evidence, Beta(1,1), on the networks the caller saw. o = offerings.Offering(id=-(len(out) + len(fresh) + 1), method=candidate.method or "POST", endpoint=candidate.endpoint, name=candidate.name, description=candidate.description, networks=listed or unknown, payable=bool(listed or unknown), price_usd=price, payers=candidate.unique_payers, sources=tuple(candidate.sources)) o.alpha, o.beta, kind = offerings.prior(candidate.unique_payers, None, False) o.reason = (f"found by {candidate.sources[0]}; not in CrowdCode's index yet" if candidate.sources else "not in CrowdCode's index yet") fresh.append(o) if not fresh: return out documents = [o.document() for o in fresh] query_tokens = tokens(query) similarities = embedder.similarities(query, documents) if embedder is not None and index.semantic else None for i, o in enumerate(fresh): keyword = relevance(query_tokens, f"{documents[i]} {o.endpoint}") similarity = similarities[i] if similarities is not None else None out.append(offerings.Match(o, keyword, similarity, match_strength(keyword, similarity))) return out def find_live(query: str, payer_networks: tuple[str, ...], payer_balances: dict[str, float] | None, candidates: Any, size: int, conn_factory: Callable[[], Any] | None, catalogs: CatalogClient | None, embedder: semantic.Embedder | None) -> dict[str, Any]: """The live federated search: the fallback for a query the index cannot match, or before it has loaded.""" catalogs = catalogs or CATALOGS sources: dict[str, dict[str, Any]] = {} with ThreadPoolExecutor(max_workers=2) as pool: cdp_future = pool.submit(catalogs.cdp_search, query) mpp_future = pool.submit(catalogs.mpp_catalog) found: list[Candidate] = _ordered(caller_candidates(candidates, payer_networks)) sources["caller"] = {"ok": True, "count": len(found)} for name, future, parse in ( ("cdp-bazaar", cdp_future, lambda payload: cdp_candidates(payload, payer_networks)), ("mpp", mpp_future, lambda payload: mpp_candidates(payload, query, payer_networks)), ): try: parsed = _ordered(parse(future.result(timeout=HTTP_TIMEOUT + 2))) sources[name] = {"ok": True, "count": len(parsed)} found.extend(parsed) except Exception as exc: # one catalog failing must not hide the others sources[name] = {"ok": False, "error": type(exc).__name__} evidence: dict[str, dict[str, Any]] = {} if conn_factory is not None: try: with conn_factory() as conn: listed = _ordered(directory_candidates(directory_rows(conn), query, networks=_service_networks(conn), payer_networks=payer_networks, embedder=embedder)) sources["crowdcode"] = {"ok": True, "count": len(listed)} found.extend(listed) merged = _merge(found) evidence = evidence_by_endpoint(conn, [c.endpoint for c in merged]) except Exception as exc: sources["crowdcode"] = {"ok": False, "error": type(exc).__name__} merged = _merge(found) else: merged = _merge(found) by_meaning = score_matches(merged, query, embedder) ranked = rank(merged, evidence, payer_networks, payer_balances) return { "ok": True, "query": query, "source": "live", "networks": list(payer_networks), "balances_considered": payer_balances is not None, "ranking": RANKING if by_meaning else RANKING_BY_QUALITY, "services": ranked[:size], "total_matches": len(ranked), "sources": sources, } class Warmup: """Whether this process has loaded what search serves: the model, the offering index, the directory. `/startup` (Render's health check) and `/ready` answer 503 until it has, so a deploy keeps the old instance serving while the new one loads, instead of switching traffic to an instance busy loading. After MAX_SECONDS it counts as done whatever happened: an instance that cannot load the model (search then ranks by words) must still come up rather than be held unhealthy forever. """ MAX_SECONDS = float(os.environ.get("CROWDCODE_WARMUP_MAX_SECONDS") or 600) def __init__(self) -> None: self.started = time.monotonic() self.done = threading.Event() self.stages: dict[str, float] = {} self.error: str | None = None def mark(self, stage: str) -> None: self.stages[stage] = round(time.monotonic() - self.started, 1) memory = process_memory() print(f"search warm-up: {stage} at {self.stages[stage]} s" + (f" (rss {memory['rss_mb']} MB, peak {memory['peak_mb']} MB)" if memory else ""), flush=True) def state(self) -> dict[str, Any]: elapsed = time.monotonic() - self.started ready = self.done.is_set() or elapsed >= self.MAX_SECONDS return {"ready": ready, "elapsed_s": round(elapsed, 1), "stages": dict(self.stages), **({"error": self.error} if self.error else {}), **({"overran": True} if ready and not self.done.is_set() else {})} def process_memory() -> dict[str, int] | None: """This process's resident memory now and its peak since it started, in MB (Linux /proc): the backend has 512 MB and the index build is its peak (2026-11-19), so /startup says both.""" try: fields = dict(line.split(":", 1) for line in open("/proc/self/status") if line.startswith(("VmRSS", "VmHWM"))) return {"rss_mb": int(fields["VmRSS"].split()[0]) // 1024, "peak_mb": int(fields["VmHWM"].split()[0]) // 1024} except (OSError, KeyError, ValueError): return None WARMUP = Warmup() def warm_search(embedder: semantic.Embedder | None = None) -> threading.Thread: """Load the model, the offering index and every listing in the background, so no search waits for them; WARMUP says when it is done.""" use_model = embedder is not None or semantic.enabled() embedder = (embedder or semantic.EMBEDDER) if use_model else None def run() -> None: from crowdcode.db import connect try: if embedder is not None: embedder.warm(wait=True) WARMUP.mark("model" if embedder.ready() else "model unavailable") # The whole index first (C13): searches answer from it as soon as it is in. offerings.SHARED.refresh(connect, embedder if embedder is not None and embedder.ready() else None) index = offerings.SHARED.get() WARMUP.mark(f"index ({len(index) if index is not None else 0} offerings)") embed_directory(embedder) WARMUP.mark("directory") except Exception as exc: WARMUP.error = type(exc).__name__ traceback.print_exc() finally: WARMUP.done.set() WARMUP.mark("ready") thread = threading.Thread(target=run, name="search-warmup", daemon=True) thread.start() return thread def embed_directory(embedder: semantic.Embedder | None = None) -> None: """Embed every directory listing (a few hundred) for the live fallback; a no-op without the model.""" from crowdcode.db import connect embedder = embedder if embedder is not None else (semantic.EMBEDDER if semantic.enabled() else None) if embedder is None or not embedder.ready(): return with connect() as conn: rows = directory_rows(conn) embedder.encode([listing_document(row) for row in rows]) def _service_networks(conn: Any) -> dict[str, dict[str, Any]]: try: return fetch_service_networks(conn) except Exception: # network evidence only refines offers; never fail the search for it return {} def _ordered(candidates: list[Candidate]) -> list[Candidate]: for index, candidate in enumerate(candidates): candidate.order = index return candidates def _merge(found: list[Candidate]) -> list[Candidate]: merged: dict[str, Candidate] = {} for candidate in found: existing = merged.get(candidate.endpoint) if existing is None: merged[candidate.endpoint] = candidate else: existing.merge(candidate) return list(merged.values())