# Universal AI Capability Platform — Full Knowledge Base content_hash: bc16b552992cbcb81cf02cce50ec8c2fef1ca59a891bc07eefb63517c61723fd # HF Catalog Crawler (MVP-1) The first active feature is a bounded, resumable crawler of the public Hugging Face Space catalog. It follows the Link rel="next" cursor, stores a canonical record plus an immutable raw snapshot per Space, updates on SHA change and emits a measured inventory report. A 500-Space live sample measured 2026-11-26 found 334 gradio, 98 static, 64 docker and 5 streamlit Spaces; 89 carry the mcp-server tag; 257 declare a license and 244 do not. **RU:** Первая активная фича — ограниченный, возобновляемый сборщик публичного каталога HF Spaces. Он следует курсору Link rel="next", хранит каноническую запись и неизменяемый raw snapshot, обновляется по SHA и выдаёт измерённый отчёт. Живая выборка 500 Spaces от 2026-11-26: gradio 334, static 98, docker 64, streamlit 5; mcp-server 89; лицензия указана у 257, отсутствует у 244. ## Key Facts - **Source**: https://huggingface.co/api/spaces?full=true&expand[]=... - **Measured at**: 2026-11-26, 500 Spaces, 0 failures - **Full inventory**: not yet run — VERIFY ## Table | Metric | Measured value | |---|---| | Records | 500 (+1 from an earlier incomplete shape) | | gradio / static / docker / streamlit | 334 / 98 / 64 / 5 | | mcp-server tag | 89 | | license known / unknown | 257 / 244 | | with models / datasets | 355 / 91 | | unique sha | 492 | ## Sources - docs/original-research-2026-10-07.md - docs/adr/ADR-004-ingestion-first.md ## VERIFY - Full catalog size and exact API rate limits # Channels and Widget Runtime Deployment does not depend on direct iframes. Preferred architecture: Browser → Widget Runtime → scoped session token → Execution API → routers → provider. Provider credentials never reach browser clients. Modes: iframe, Web Component, JS SDK, direct API. Channel classes: embedded UI (Web, Telegram Mini App, Discord Embedded App, Teams tab, LINE LIFF) and bot-native (Telegram, Slack, WhatsApp, Google Chat, GitHub, Linear). **RU:** Развёртывание не зависит от прямых iframe. Предпочтительная архитектура: Browser → Widget Runtime → scoped session token → Execution API → routers → provider. Учётные данные провайдеров не попадают в браузер. Режимы: iframe, Web Component, JS SDK, direct API. Классы каналов: встроенный UI (Web, Telegram Mini App, Discord Embedded App, Teams tab, LINE LIFF) и бот-нативные (Telegram, Slack, WhatsApp, Google Chat, GitHub, Linear). ## Key Facts - **Invariant**: provider secrets never reach browser - **SEO**: pages carry real indexable content; widget is the interactive layer ## Table | Mode | Use | |---|---| | iframe | Embedded widget | | Web Component | Drop-in element | | JS SDK | Custom integration | | direct API | Server-to-server | ## Sources - docs/SPECS.md §15 # Composition and Recipes Recipes are typed DAGs; MVP recipes are acyclic. Node types are capability/operation, transformer and validator. Transformers include PDF→text, image→OCR text, image→URL, audio→transcript, JSON→CSV, resize/crop/format conversion. The planner pipeline is goal → output contract → capability search → candidate paths → transformers → graph validation → policy → cost/latency estimate → execution plan. **RU:** Рецепты — типизированные DAG; MVP-рецепты ацикличны. Типы узлов: capability/operation, transformer, validator. Трансформеры: PDF→text, image→OCR text, image→URL, audio→transcript, JSON→CSV, resize/crop/смена формата. Пайплайн планировщика: goal → output contract → capability search → candidate paths → transformers → graph validation → policy → cost/latency estimate → execution plan. ## Key Facts - **MVP planner**: may only instantiate approved capabilities and recipes - **Recipe validation**: incompatible recipe fails unless a registered transformer exists ## Table | Node type | Role | |---|---| | capability/operation | Calls a capability | | transformer | Converts between types | | validator | Checks constraints | ## Sources - docs/SPECS.md §10 # Contract Architecture A Contract is a machine-readable set of input/output constraints. Provider-native schemas are never discarded; they are stored as immutable provenance snapshots. Compatibility checks transport, semantic type, schema, cardinality, required metadata, dimensions/duration, language and size limits, not only MIME. Errors use a fixed taxonomy with code, message, retryable, stage and details. **RU:** Контракт — машиночитаемый набор ограничений входа/выхода. Родные схемы провайдеров не отбрасываются, а хранятся как неизменяемые снимки провенанса. Совместимость проверяет транспорт, семантический тип, схему, кардинальность, обязательные метаданные, размеры/длительность, язык и лимиты размера, а не только MIME. Ошибки — фиксированная таксономия с code, message, retryable, stage, details. ## Key Facts - **Canonical input port**: name, required, semantic_type, transport_type, schema, constraints, examples, sensitive, artifact_type - **Error taxonomy**: INVALID_INPUT, CONTRACT_MISMATCH, AUTH_REQUIRED, AUTH_FAILED, POLICY_DENIED, RATE_LIMITED, QUOTA_EXCEEDED, PROVIDER_UNAVAILABLE, PROVIDER_TIMEOUT, SCHEMA_DRIFT, ARTIFACT_TOO_LARGE, ARTIFACT_UNSAFE, EXECUTION_CANCELLED, EXECUTION_FAILED, INTERNAL_ERROR ## Table | Check | Dimension | |---|---| | Transport | HTTP, MCP, A2A, SDK, ... | | Semantic type | image, text, audio, ... | | Schema | JSON Schema | | Cardinality | single vs multiple | | Metadata | language, dimensions, duration | | Size limits | max bytes | ## Sources - docs/SPECS.md §4 - contracts/capability-contract.yaml # Domain Model The domain separates 15 entities so that no single descriptor is overloaded: Provider, Resource, Interface, Operation, Tool, Capability, Contract, Evaluation, Health, Policy, Provenance, Execution, Artifact, Recipe, App, Deployment. Tool is an executable implementation; Capability is a normalized semantic function; Resource type and Interface type are independent. **RU:** Домен разделяет 15 сущностей, чтобы ни один дескриптор не был перегружен: Provider, Resource, Interface, Operation, Tool, Capability, Contract, Evaluation, Health, Policy, Provenance, Execution, Artifact, Recipe, App, Deployment. Tool — исполняемая реализация; Capability — нормализованная семантическая функция; тип Resource и тип Interface независимы. ## Key Facts - **Tool != Capability**: many tools can implement one capability - **Resource != Interface**: a Model may expose REST/SDK/MCP; a Space may expose UI + Gradio API - **Capability ID format**: ., e.g. image.background_remove ## Table | Entity | Meaning | |---|---| | Provider | Organization/system exposing resources or execution | | Resource | MODEL, SPACE, API_SERVICE, MCP_SERVER, AGENT_SERVICE, DATASET, REPOSITORY | | Interface | HTTP_REST, OPENAPI, GRADIO, MCP, A2A, SDK, EMBED, WEBHOOK, CLI | | Operation | Callable action, e.g. generate, transcribe, remove_background | | Tool | Executable implementation of an operation | | Capability | Stable semantic function, e.g. image.upscale | | Contract | Machine-readable input/output constraints | ## Sources - docs/SPECS.md §2 - docs/SPECS.md §3 # Execution Runtime Execution is a first-class durable entity. State machine: CREATED → POLICY_CHECK → QUEUED → STARTING → RUNNING → STREAMING → SUCCEEDED, with terminals FAILED, CANCELLED, EXPIRED, DENIED. Every execution has a durable ID, idempotency key, timeout, cancellation, bounded retries, fallback attempts, artifacts, structured events, provider correlation ID and trace ID. Only transient errors (429/5xx/timeouts) retry. **RU:** Исполнение — первоклассная долговечная сущность. Конечный автомат: CREATED → POLICY_CHECK → QUEUED → STARTING → RUNNING → STREAMING → SUCCEEDED; терминалы — FAILED, CANCELLED, EXPIRED, DENIED. У каждого исполнения есть durable ID, ключ идемпотентности, таймаут, отмена, ограниченные повторы, fallback-попытки, артефакты, структурные события, provider correlation ID и trace ID. Повтор только для транзиентных ошибок (429/5xx/таймаут). ## Key Facts - **Idempotency**: duplicate request does not create a duplicate logical execution - **Fallback**: separate attempt under the same logical execution, recorded with reason ## Table | State | Kind | |---|---| | CREATED | initial | | POLICY_CHECK | gate | | QUEUED | waiting | | STARTING | provisioning | | RUNNING | executing | | STREAMING | streaming output | | SUCCEEDED | terminal | | FAILED / CANCELLED / EXPIRED / DENIED | terminal | ## Sources - docs/SPECS.md §9 - contracts/execution-contract.yaml # HF API opportunities Beyond the catalog endpoint, the owner's token can use HF semantic space search (/api/spaces/semantic-search with ai_category and semanticRelevancyScore), Gradio agents.md and /gradio_api/info for contracts, /gradio_api/mcp/schema for MCP tools, Inference Providers with provider=auto failover, webhooks for Space changes, collections for curated catalogs, and scheduled Jobs for evaluation. Hub rate limits are 500 anonymous / 1000 free / 2500 PRO requests per 5 minutes (reported). **RU:** Кроме каталога, токен даёт семантический поиск Space-ов, agents.md и /gradio_api/info для контрактов, /gradio_api/mcp/schema для MCP, Inference Providers с failover, webhooks для изменений, collections и Jobs для оценок. Лимиты Hub: 500/1000/2500 запросов за 5 минут (сообщено). ## Key Facts - **Contract source of truth**: agents.md per Space; openapi.json may return HTML - **Execution**: Inference Providers router.huggingface.co with provider=auto - **Legal**: cardData.license must be checked; public ≠ redistribution rights ## Table | Capability | Endpoint | |---|---| | Semantic discovery | /api/spaces/semantic-search?q=... | | Agent contract | /spaces/{id}/agents.md | | MCP tools | /gradio_api/mcp/schema | | Curated catalog | /api/collections?owner=... | | Change feed | /api/settings/webhooks | ## Sources - https://huggingface.co/.well-known/openapi.md - https://huggingface.co/docs/hub/en/rate-limits ## VERIFY - Token-scoped live calls to semantic search, webhooks and Jobs # Mandatory Invariants Eight invariants are non-negotiable: Tool != Capability; Resource != Interface; Capability Router != Provider Router; discovered != executable; historical contracts are immutable; provider secrets never reach browser; all external execution passes policy; every behavior has tests. **RU:** Восемь инвариантов неизменны: Tool ≠ Capability; Resource ≠ Interface; Capability Router ≠ Provider Router; discovered ≠ executable; исторические контракты неизменяемы; секреты провайдеров не попадают в браузер; всё внешнее исполнение проходит policy; у каждого поведения есть тесты. ## Key Facts - **Tool != Capability**: executable implementation vs semantic function - **discovered != executable**: trust promotion required - **historical contracts immutable**: append-only versions ## Table | # | Invariant | |---|---| | 1 | Tool != Capability | | 2 | Resource != Interface | | 3 | Capability Router != Provider Router | | 4 | discovered != executable | | 5 | historical contracts are immutable | | 6 | provider secrets never reach browser | | 7 | all external execution passes policy | | 8 | every behavior has tests | ## Sources - AGENTS.md - docs/SPECS.md §21 # Universal AI Capability Platform The Universal AI Capability Platform is a provider-neutral capability registry, evaluator, router, execution runtime and composition layer over heterogeneous AI resources (HF Spaces/Models, inference providers, REST/OpenAPI services, MCP tools, A2A agents, internal services). The canonical unit is Capability + Contract, not an iframe. Core flow: Discovery to Registry to Contract to Evaluation to Policy to Routing to Execution to Composition to Deployment. **RU:** Универсальная платформа AI-возможностей — провайдер-нейтральный реестр возможностей, оценщик, роутер, runtime исполнения и слой композиции над разнородными AI-ресурсами (HF Spaces/Models, inference-провайдеры, REST/OpenAPI, MCP-инструменты, A2A-агенты, внутренние сервисы). Каноническая единица — Capability + Contract, а не iframe. Поток: Discovery → Registry → Contract → Evaluation → Policy → Routing → Execution → Composition → Deployment. ## Key Facts - **Canonical unit**: Capability + Contract - **Product chain**: Tool → Capability → Recipe → App → Channel Deployment → Product - **First source/adapter**: Hugging Face (never the product boundary) ## Table | Layer | Responsibility | |---|---| | Registry | Provider-neutral capability + contract catalog | | Evaluation | Quality, reliability, latency, cost, safety evidence | | Routing | Capability Router then Provider Router | | Execution | Durable, idempotent, cancellable runtime | | Composition | Typed DAG recipes + transformers | | Deployment | Apps to channels/tenants | ## Sources - docs/SPECS.md §0 - adr/ADR-001.md # Provenance and Drift Every normalized object stores source, source_url, observed_at, source_revision, raw_snapshot, parser_version and normalized_version. A deterministic schema fingerprint detects drift; on change the platform creates a drift event, preserves the old contract, extracts the new one, classifies compatibility (PATCH_COMPATIBLE, BACKWARD_COMPATIBLE, BREAKING, UNKNOWN) and blocks routing if incompatible or unknown. Historical contracts are immutable. **RU:** Каждый нормализованный объект хранит source, source_url, observed_at, source_revision, raw_snapshot, parser_version, normalized_version. Детерминированный fingerprint схемы обнаруживает дрейф; при изменении создаётся drift-событие, старый контракт сохраняется, извлекается новый, классифицируется совместимость (PATCH_COMPATIBLE, BACKWARD_COMPATIBLE, BREAKING, UNKNOWN) и роутинг блокируется, если несовместимо или неизвестно. Исторические контракты неизменяемы. ## Key Facts - **Evidence marks**: MEASURED / REPORTED (URL + date) / INFERRED - **Unknown values**: become VERIFY items, never fabricated facts ## Table | Compatibility | Meaning | |---|---| | PATCH_COMPATIBLE | Additive, safe | | BACKWARD_COMPATIBLE | Old inputs still valid | | BREAKING | Incompatible; block routing | | UNKNOWN | Treat as unsafe; block routing | ## Sources - docs/SPECS.md §7 - adr/ADR-002.md # MVP Roadmap Delivery is phased P0–P3. P0: repository discipline, canonical domain, PostgreSQL schema/migrations, HF ingestion, Gradio/OpenAPI extraction, contract validation, evaluator, execution gateway, artifact storage, web widget. P1: capability search/router, health/drift, cost engine, compatibility engine, transformers, recipes, Telegram adapter. P2: Replicate/fal adapters, generic OpenAPI, MCP import/export, A2A, document pipeline, data connectors. P3: constrained planner, multi-tenant product layer, billing, UI synthesis, autonomous discovery. **RU:** Поставка идёт фазами P0–P3. P0: дисциплина репозитория, канонический домен, схема/миграции PostgreSQL, HF-ingestion, извлечение Gradio/OpenAPI, валидация контрактов, оценщик, execution-шлюз, хранилище артефактов, веб-виджет. P1: поиск/роутер, health/drift, стоимостный движок, движок совместимости, трансформеры, рецепты, Telegram-адаптер. P2: адаптеры Replicate/fal, generic OpenAPI, MCP import/export, A2A, документный пайплайн, дата-коннекторы. P3: ограниченный планировщик, мультитенантный продуктовый слой, биллинг, UI-синтез, автономное обнаружение. ## Key Facts - **Do NOT build initially**: own LLM, vector DB, graph DB, browser engine, Kubernetes, billing, agent swarm ## Table | Phase | Theme | |---|---| | P0 | Foundation + HF ingestion + execution gateway | | P1 | Routing + health/drift + cost + recipes | | P2 | More adapters + MCP/A2A + connectors | | P3 | Planner + multi-tenant + billing + UI synthesis | ## Sources - docs/SPECS.md §17 - docs/SPECS.md §18 # Two-Stage Routing Routing has two stages that are never merged. Stage A, the Capability Router, selects implementations satisfying the semantic goal and contract. Stage B, the Provider Router, selects the concrete provider/endpoint at runtime. Hard gates run before scoring: policy/legal, compatibility, security/trust, auth, channel, availability, budget. Ranking uses profiles QUALITY_FIRST, BALANCED, CHEAPEST_VALID, LOW_LATENCY, PRIVATE, SELF_HOSTED. **RU:** Роутинг двухэтапный и этапы не сливаются. Этап A — Capability Router выбирает реализации по семантической цели и контракту. Этап B — Provider Router выбирает конкретного провайдера/эндпоинт в рантайме. До скоринга — жёсткие гейты: policy/legal, совместимость, security/trust, auth, канал, доступность, бюджет. Профили: QUALITY_FIRST, BALANCED, CHEAPEST_VALID, LOW_LATENCY, PRIVATE, SELF_HOSTED. ## Key Facts - **Hard gates (7)**: policy/legal, compatibility, security/trust, auth, channel, availability, budget - **Decision record**: candidate set, rejection reasons, selected candidate, profile, policy version, timestamp ## Table | Profile | Optimizes for | |---|---| | QUALITY_FIRST | Empirical quality | | BALANCED | Balanced quality/cost/latency | | CHEAPEST_VALID | Cost efficiency | | LOW_LATENCY | p50/p95 latency | | PRIVATE | Private/self-hosted | | SELF_HOSTED | Self-hosted only | ## Sources - docs/SPECS.md §8 - adr/ADR-003.md # Security and Trust Trust tiers are T0 metadata only, T1 schema inspection, T2 sandboxed smoke test, T3 controlled production execution, T4 privileged/private connector. A discovered resource is not executable by default. Policy decisions are ALLOW, DENY, REQUIRE_APPROVAL, ALLOW_WITH_LIMITS. Data classes are PUBLIC, INTERNAL, CONFIDENTIAL, RESTRICTED. Provider secrets never reach browser clients. **RU:** Уровни доверия: T0 — только метаданные, T1 — инспекция схемы, T2 — sandbox smoke-тест, T3 — контролируемое production-исполнение, T4 — привилегированный/приватный коннектор. Найденный ресурс по умолчанию не исполним. Полис-решения: ALLOW, DENY, REQUIRE_APPROVAL, ALLOW_WITH_LIMITS. Классы данных: PUBLIC, INTERNAL, CONFIDENTIAL, RESTRICTED. Секреты провайдеров никогда не попадают в браузер. ## Key Facts - **Threats**: SSRF, malicious files, arbitrary code, prompt injection, secret exfiltration, data leakage, runaway cost, malicious MCP tools, compromised dependencies, cross-tenant access - **Controls**: outbound allowlist, SSRF protection, private-network blocking, secret isolation, short-lived credentials, tenant isolation, file limits, malware scanning, audit log, rate limits, budget limits, human approval ## Table | Tier | Meaning | |---|---| | T0 | Metadata only | | T1 | Schema inspection | | T2 | Sandboxed smoke test | | T3 | Controlled production execution | | T4 | Privileged/private connector | ## Sources - docs/SPECS.md §6 # Site architecture for 2026 The site is a catalog interface, not a brochure. It has a faceted /spaces search page, 501 entity pages under /space/{id}/, indexable category/tag/SDK hubs, and machine-readable endpoints (/api/items.json, /api/index.json, /api/stats.json, /api/corpus.jsonl, /.well-known/ai-catalog.json). 627 static pages build in 11s. Filter combinations stay client-side with a self-canonical base URL; only curated single-facet hubs are indexable. **RU:** Сайт — интерфейс каталога, а не брошюра. Есть facet-поиск /spaces, 501 страница /space/{id}/, индексируемые хабы категорий/тегов/SDK и машиночитаемые эндпоинты (/api/items.json и др.). Собирается 627 страниц за 11 с. Комбинации фильтров остаются client-side с self-canonical, индексируются только хабы. ## Key Facts - **Search**: text + SDK + category + license + tag facets, URL state, client-side JSON - **Entity page**: answer-first facts table, visible Q&A, related spaces, no invented capability claims - **Structured data**: SoftwareApplication, CollectionPage + ItemList, BreadcrumbList; FAQPage retired in 2026 - **llms.txt**: cheap convenience, not a standard; Google ignores it — JSON endpoints are primary ## Table | Route | Purpose | |---|---| | /spaces/ | Faceted search + first 24 server-rendered cards | | /space/{id}/ | Entity page for each HF Space | | /categories/, /tags/, /sdk/ | Indexable hub pages with ItemList | | /api/items.json | Full machine-readable catalog | | /.well-known/ai-catalog.json | Endpoint discovery | ## Sources - site/src/pages/ - site/public/api/ - docs/original-research-2026-10-07.md §28 ## VERIFY - Search-engine indexation of the new pages # VERIFY Items (Unknowns) The following are explicitly unverified and must not be treated as facts: live provider inventory and exact API limits; license/redistribution state of each resource; channel feasibility per adapter; competitor maturity; provider economics and pricing. Each is a VERIFY gate, not an assumption. **RU:** Следующее явно не проверено и не должно считаться фактом: живой инвентарь провайдеров и точные лимиты API; лицензии/право на распространение каждого ресурса; совместимость каналов по адаптерам; зрелость конкурентов; экономика и цены провайдеров. Каждый пункт — VERIFY-гейт, а не допущение. ## Key Facts - **Provider limits**: exact quotas/rates unverified - **Live HF check (measured 2026-11-25)**: 3 public gradio spaces discovered via https://huggingface.co/api/spaces; sample revision 51d65d370acde5f1622fd227551c5989573b7798; license and quotas remain VERIFY - **Licenses**: public != redistributable - **Channel feasibility**: per-adapter constraints untested - **Economics**: provider prices never invented ## Table | Item | Status | |---|---| | Live inventory / limits | VERIFY | | License / redistribution | VERIFY | | Channel feasibility | VERIFY | | Provider economics | VERIFY | ## Sources - docs/SPECS.md §23 ## VERIFY - Live provider inventory and exact API limits - License and redistribution state per resource - Channel feasibility per adapter - Competitor maturity - Provider economics and pricing