Spaces:
Running
Running
Download core/tools/openapi_import.py from Aynkhn/WorkPilot-AI: direct link, hf CLI and curl.
- Browser
- Download file 13.3 kB
-
https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/tools/openapi_import.py
- Command line
-
hf download hf://spaces/Aynkhn/WorkPilot-AI/core/tools/openapi_import.py
-
curl -L -o openapi_import.py https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/tools/openapi_import.py
13.3 kB
| """OpenAPI 3.x import: every operation becomes a tenant tool (Phase 16). | |
| ``parse_spec`` accepts JSON or YAML text (or an already-parsed dict); ``fetch_spec`` reads a | |
| URL through an injectable fetcher (tests pass fixtures, production uses httpx with the SSRF | |
| guard, a timeout and a size cap). ``import_operations`` resolves local ``$ref``s and turns | |
| each ``paths.<path>.<method>`` into an ``ImportedOperation``: | |
| * ``input_schema``: one property per path/query/header parameter, plus the JSON request | |
| body (its top-level properties are flattened when they don't collide with a parameter, | |
| otherwise the body is a single ``body`` argument); | |
| * ``suggested_tier`` from the HTTP method (GET/HEAD -> T0, POST/PUT/PATCH -> T2, | |
| DELETE -> T3). The tool is *stored* as T3 until an owner confirms a tier; | |
| * ``http``: the ``HttpOperation`` the handler executes; credentials are referenced by the | |
| tenant's secret ref and injected by the gateway, never part of the spec. | |
| Third-party descriptions are untrusted text that ends up in tool search results, so they | |
| are stripped of control characters and truncated; the owner reviews every tool before it | |
| can run outside T3/test mode (tool-poisoning defense). | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import re | |
| from collections.abc import Awaitable, Callable | |
| from typing import Any | |
| import httpx | |
| import yaml | |
| from pydantic import BaseModel | |
| from core.config import get_settings | |
| from core.tools.http_tool import HttpAuth, HttpOperation, HttpParam, check_url | |
| from core.tools.jsonschema_model import ( | |
| SchemaError, | |
| field_name, | |
| model_from_schema, | |
| property_fields, | |
| ) | |
| from core.tools.preview import canonical_json, sha256_hex | |
| from core.tools.spec import RiskTier | |
| METHODS = ("get", "head", "post", "put", "patch", "delete") | |
| SUGGESTED_TIER = { | |
| "GET": RiskTier.T0_READ, | |
| "HEAD": RiskTier.T0_READ, | |
| "POST": RiskTier.T2_EXTERNAL, | |
| "PUT": RiskTier.T2_EXTERNAL, | |
| "PATCH": RiskTier.T2_EXTERNAL, | |
| "DELETE": RiskTier.T3_CRITICAL, | |
| } | |
| MAX_REF_DEPTH = 25 | |
| MAX_DESCRIPTION = 500 | |
| _CONTROL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]") | |
| _SLUG = re.compile(r"^[a-z][a-z0-9_]{1,39}$") | |
| Fetcher = Callable[[str], Awaitable[bytes]] | |
| class OpenAPIImportError(ValueError): | |
| pass | |
| class ImportedOperation(BaseModel): | |
| name: str # "<prefix>.<operation>" | |
| operation_id: str | |
| description: str | |
| method: str | |
| path: str | |
| input_schema: dict[str, Any] | |
| suggested_tier: int | |
| http: HttpOperation | |
| def definition(self) -> dict[str, Any]: | |
| """What the owner confirms; its hash is pinned (a re-import that changes it shows up | |
| as a definition change).""" | |
| return { | |
| "name": self.name, | |
| "description": self.description, | |
| "input_schema": self.input_schema, | |
| "http": self.http.model_dump(mode="json"), | |
| } | |
| def definition_hash(self) -> str: | |
| return sha256_hex(canonical_json(self.definition())) | |
| def clean_text(text: Any, limit: int = MAX_DESCRIPTION) -> str: | |
| return _CONTROL.sub(" ", str(text or "")).strip()[:limit] | |
| def parse_spec(raw: bytes | str | dict[str, Any]) -> dict[str, Any]: | |
| if isinstance(raw, dict): | |
| doc: Any = raw | |
| else: | |
| data = raw.encode() if isinstance(raw, str) else raw | |
| if len(data) > get_settings().ext_max_spec_bytes: | |
| raise OpenAPIImportError("spec is too large") | |
| text = data.decode("utf-8", "replace") | |
| try: | |
| doc = json.loads(text) | |
| except ValueError: | |
| try: | |
| doc = yaml.safe_load(text) | |
| except yaml.YAMLError as exc: | |
| raise OpenAPIImportError(f"not JSON or YAML: {exc}") from exc | |
| if not isinstance(doc, dict): | |
| raise OpenAPIImportError("spec must be a JSON/YAML object") | |
| version = str(doc.get("openapi", "")) | |
| if not version.startswith("3."): | |
| raise OpenAPIImportError("only OpenAPI 3.x documents are supported") | |
| if not isinstance(doc.get("paths"), dict): | |
| raise OpenAPIImportError("spec has no paths") | |
| return doc | |
| async def default_fetcher(url: str) -> bytes: | |
| check_url(url) | |
| s = get_settings() | |
| async with ( | |
| httpx.AsyncClient(timeout=s.ext_http_timeout_s, follow_redirects=False) as client, | |
| client.stream("GET", url) as resp, | |
| ): | |
| if resp.status_code != 200: | |
| raise OpenAPIImportError(f"fetching spec failed: HTTP {resp.status_code}") | |
| out = b"" | |
| async for chunk in resp.aiter_bytes(): | |
| out += chunk | |
| if len(out) > s.ext_max_spec_bytes: | |
| raise OpenAPIImportError("spec is too large") | |
| return out | |
| async def fetch_spec(url: str, fetcher: Fetcher | None = None) -> dict[str, Any]: | |
| return parse_spec(await (fetcher or default_fetcher)(url)) | |
| # ------------------------------------------------------------------ $ref resolution | |
| def _pointer(root: dict[str, Any], ref: str) -> Any: | |
| if not ref.startswith("#/"): | |
| raise OpenAPIImportError(f"only local $refs are supported: {ref}") | |
| node: Any = root | |
| for part in ref[2:].split("/"): | |
| part = part.replace("~1", "/").replace("~0", "~") | |
| if not isinstance(node, dict) or part not in node: | |
| raise OpenAPIImportError(f"unresolvable $ref {ref}") | |
| node = node[part] | |
| return node | |
| def resolve(node: Any, root: dict[str, Any], seen: tuple[str, ...] = ()) -> Any: | |
| """Inline local ``$ref``s. A cycle (or excessive depth) becomes an open object.""" | |
| if len(seen) > MAX_REF_DEPTH: | |
| return {"type": "object"} | |
| if isinstance(node, dict): | |
| ref = node.get("$ref") | |
| if isinstance(ref, str): | |
| if ref in seen: | |
| return {"type": "object", "description": "recursive structure"} | |
| return resolve(_pointer(root, ref), root, (*seen, ref)) | |
| return {k: resolve(v, root, seen) for k, v in node.items()} | |
| if isinstance(node, list): | |
| return [resolve(v, root, seen) for v in node] | |
| return node | |
| # ----------------------------------------------------------------------- operations | |
| def _snake(text: str) -> str: | |
| s = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", text) | |
| s = re.sub(r"[^a-zA-Z0-9]+", "_", s).strip("_").lower() | |
| return s or "op" | |
| def server_url(doc: dict[str, Any]) -> str | None: | |
| servers = doc.get("servers") or [] | |
| if not servers or not isinstance(servers[0], dict): | |
| return None | |
| url = str(servers[0].get("url") or "") | |
| for var, spec in (servers[0].get("variables") or {}).items(): | |
| url = url.replace("{" + var + "}", str((spec or {}).get("default", ""))) | |
| return url or None | |
| def auth_from_spec(doc: dict[str, Any]) -> HttpAuth | None: | |
| """The first supported security scheme (apiKey in header/query, http bearer/basic).""" | |
| schemes = ((doc.get("components") or {}).get("securitySchemes")) or {} | |
| for scheme in schemes.values(): | |
| scheme = resolve(scheme, doc) | |
| kind = scheme.get("type") | |
| if kind == "apiKey" and scheme.get("in") in ("header", "query") and scheme.get("name"): | |
| return HttpAuth(type="api_key", location=scheme["in"], name=str(scheme["name"])) | |
| if kind == "http" and str(scheme.get("scheme", "")).lower() == "bearer": | |
| return HttpAuth(type="bearer") | |
| if kind == "http" and str(scheme.get("scheme", "")).lower() == "basic": | |
| return HttpAuth(type="basic") | |
| return None | |
| def _operation( | |
| doc: dict[str, Any], | |
| prefix: str, | |
| path: str, | |
| method: str, | |
| op: dict[str, Any], | |
| path_params: list[Any], | |
| base_url: str, | |
| sandbox_base_url: str | None, | |
| auth: HttpAuth | None, | |
| ) -> ImportedOperation: | |
| op = resolve(op, doc) | |
| params_by_key: dict[tuple[str, str], dict[str, Any]] = {} | |
| for p in [*resolve(path_params, doc), *(op.get("parameters") or [])]: | |
| if isinstance(p, dict) and p.get("name") and p.get("in") in ("path", "query", "header"): | |
| params_by_key[(p["in"], p["name"])] = p | |
| props: dict[str, Any] = {} | |
| required: list[str] = [] | |
| wire: list[HttpParam] = [] | |
| for (loc, name), p in params_by_key.items(): | |
| if loc == "header" and auth is not None and name.lower() == auth.name.lower(): | |
| continue # the credential is injected by the gateway, never an argument | |
| if name in props: | |
| continue | |
| schema = dict(p.get("schema") or {"type": "string"}) | |
| if p.get("description") and "description" not in schema: | |
| schema["description"] = clean_text(p["description"], 300) | |
| props[name] = schema | |
| if p.get("required") or loc == "path": | |
| required.append(name) | |
| wire.append(HttpParam(name=name, field=field_name(name), location=loc)) | |
| body_field: str | None = None | |
| content = ((op.get("requestBody") or {}).get("content")) or {} | |
| body_schema = (content.get("application/json") or {}).get("schema") | |
| if isinstance(body_schema, dict): | |
| body_required = bool((op.get("requestBody") or {}).get("required")) | |
| body_props = body_schema.get("properties") | |
| flat = ( | |
| body_schema.get("type", "object") == "object" | |
| and isinstance(body_props, dict) | |
| and body_props | |
| and not set(body_props) & set(props) | |
| and not {field_name(k) for k in body_props} & {w.field for w in wire} | |
| ) | |
| if flat: | |
| assert isinstance(body_props, dict) | |
| for name, sub in body_props.items(): | |
| props[name] = sub | |
| wire.append(HttpParam(name=name, field=field_name(name), location="body")) | |
| if body_required: | |
| required.extend(n for n in body_schema.get("required") or [] if n in body_props) | |
| else: | |
| props["body"] = body_schema | |
| body_field = "body" | |
| if body_required: | |
| required.append("body") | |
| input_schema = {"type": "object", "properties": props, "required": sorted(set(required))} | |
| fields = property_fields(input_schema) | |
| wire = [w.model_copy(update={"field": fields[w.name]}) for w in wire] | |
| if body_field is not None: | |
| body_field = fields["body"] | |
| op_id = str(op.get("operationId") or f"{method}_{path}") | |
| name = f"{prefix}.{_snake(op_id)}"[:200] | |
| text = op.get("summary") or op.get("description") or f"{method.upper()} {path}" | |
| upper = method.upper() | |
| return ImportedOperation( | |
| name=name, | |
| operation_id=op_id, | |
| description=clean_text(f"{clean_text(text)} ({upper} {path})"), | |
| method=upper, | |
| path=path, | |
| input_schema=input_schema, | |
| suggested_tier=int(SUGGESTED_TIER[upper]), | |
| http=HttpOperation( | |
| method=upper, | |
| path=path, | |
| base_url=base_url, | |
| sandbox_base_url=sandbox_base_url, | |
| params=wire, | |
| body_field=body_field, | |
| auth=auth, | |
| ), | |
| ) | |
| def import_operations( | |
| doc: dict[str, Any], | |
| *, | |
| prefix: str, | |
| base_url: str | None = None, | |
| sandbox_base_url: str | None = None, | |
| auth: HttpAuth | None = None, | |
| use_spec_auth: bool = True, | |
| ) -> list[ImportedOperation]: | |
| if not _SLUG.match(prefix): | |
| raise OpenAPIImportError("name must be 2-40 chars: lowercase letters, digits, _") | |
| base = base_url or server_url(doc) | |
| if not base or not base.startswith(("http://", "https://")): | |
| raise OpenAPIImportError("spec has no absolute server URL; pass base_url") | |
| check_url(base) | |
| if sandbox_base_url: | |
| check_url(sandbox_base_url) | |
| if auth is None and use_spec_auth: | |
| auth = auth_from_spec(doc) | |
| out: list[ImportedOperation] = [] | |
| names: set[str] = set() | |
| for path, item in doc["paths"].items(): | |
| item = resolve(item, doc) if isinstance(item, dict) else {} | |
| for method in METHODS: | |
| op = item.get(method) | |
| if not isinstance(op, dict): | |
| continue | |
| imported = _operation( | |
| doc, | |
| prefix, | |
| str(path), | |
| method, | |
| op, | |
| item.get("parameters") or [], | |
| base, | |
| sandbox_base_url, | |
| auth, | |
| ) | |
| n, i = imported.name, 2 | |
| while imported.name in names: | |
| imported = imported.model_copy(update={"name": f"{n}_{i}"}) | |
| i += 1 | |
| names.add(imported.name) | |
| try: | |
| model_from_schema(imported.input_schema, imported.name) | |
| except SchemaError as exc: | |
| raise OpenAPIImportError(f"{imported.name}: {exc}") from exc | |
| out.append(imported) | |
| limit = get_settings().ext_max_tools_per_import | |
| if len(out) > limit: | |
| raise OpenAPIImportError(f"spec has {len(out)} operations (max {limit} per import)") | |
| if not out: | |
| raise OpenAPIImportError("spec has no operations") | |
| return out | |