cbomly 0.3.1__tar.gz → 0.4.0__tar.gz

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.
Files changed (52) hide show
  1. {cbomly-0.3.1/src/cbomly.egg-info → cbomly-0.4.0}/PKG-INFO +11 -7
  2. {cbomly-0.3.1 → cbomly-0.4.0}/README.md +10 -6
  3. {cbomly-0.3.1 → cbomly-0.4.0}/pyproject.toml +1 -1
  4. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/__init__.py +1 -1
  5. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/cbom.py +69 -1
  6. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/cli.py +11 -5
  7. cbomly-0.4.0/src/cbomly/detect/ai.py +298 -0
  8. cbomly-0.4.0/src/cbomly/detect/manifest.py +97 -0
  9. cbomly-0.4.0/src/cbomly/detect/vendors.py +313 -0
  10. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/report.py +85 -4
  11. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/scanner.py +27 -3
  12. {cbomly-0.3.1 → cbomly-0.4.0/src/cbomly.egg-info}/PKG-INFO +11 -7
  13. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly.egg-info/SOURCES.txt +3 -0
  14. {cbomly-0.3.1 → cbomly-0.4.0}/tests/test_cli.py +23 -3
  15. {cbomly-0.3.1 → cbomly-0.4.0}/LICENSE +0 -0
  16. {cbomly-0.3.1 → cbomly-0.4.0}/NOTICE +0 -0
  17. {cbomly-0.3.1 → cbomly-0.4.0}/setup.cfg +0 -0
  18. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/__main__.py +0 -0
  19. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/algorithms.py +0 -0
  20. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/cbom_names.py +0 -0
  21. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/detect/__init__.py +0 -0
  22. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/detect/deps.py +0 -0
  23. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/detect/keys.py +0 -0
  24. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/detect/services.py +0 -0
  25. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/detect/source.py +0 -0
  26. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/findings.py +0 -0
  27. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/importer.py +0 -0
  28. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/inventory.py +0 -0
  29. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/packs/au.toml +0 -0
  30. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/packs/baseline.toml +0 -0
  31. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/packs/ca.toml +0 -0
  32. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/packs/eu.toml +0 -0
  33. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/packs/india.toml +0 -0
  34. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/packs/jp.toml +0 -0
  35. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/packs/pci-dss.toml +0 -0
  36. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/packs/sg.toml +0 -0
  37. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/packs/uk.toml +0 -0
  38. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/packs/us-cnsa2.toml +0 -0
  39. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/packs/us-fda.toml +0 -0
  40. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/packs/us.toml +0 -0
  41. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/rules.py +0 -0
  42. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/sbom.py +0 -0
  43. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/syft_fetch.py +0 -0
  44. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly/upload.py +0 -0
  45. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly.egg-info/dependency_links.txt +0 -0
  46. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly.egg-info/entry_points.txt +0 -0
  47. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly.egg-info/requires.txt +0 -0
  48. {cbomly-0.3.1 → cbomly-0.4.0}/src/cbomly.egg-info/top_level.txt +0 -0
  49. {cbomly-0.3.1 → cbomly-0.4.0}/tests/test_keys.py +0 -0
  50. {cbomly-0.3.1 → cbomly-0.4.0}/tests/test_rules.py +0 -0
  51. {cbomly-0.3.1 → cbomly-0.4.0}/tests/test_source.py +0 -0
  52. {cbomly-0.3.1 → cbomly-0.4.0}/tests/test_upload.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cbomly
3
- Version: 0.3.1
3
+ Version: 0.4.0
4
4
  Summary: Find the cryptography in your software, write a CycloneDX CBOM, and check it is quantum-safe.
5
5
  Author-email: Cbomly <team@cbomly.com>
6
6
  License-Expression: Apache-2.0
@@ -30,8 +30,8 @@ Dynamic: license-file
30
30
 
31
31
  Cbomly scans a codebase and writes a **CBOM** (cryptographic bill of materials): a list of every
32
32
  algorithm, key and certificate your product uses, with the file and line where it was found. It also
33
- writes the normal software list (**SBOM**) and a plain-English report that says what a future quantum
34
- computer would break, and what to replace it with.
33
+ writes the normal software list (**SBOM**), lists the **AI models** and **third-party services** the product
34
+ uses, and a plain-English report that says what a future quantum computer would break, and what to replace it with.
35
35
 
36
36
  It runs locally on Linux, macOS and Windows. Nothing is uploaded unless you run `cbomly upload` to keep your
37
37
  reports in a free dashboard at [app.cbomly.com](https://app.cbomly.com), and even then only findings are
@@ -119,9 +119,9 @@ Output goes to `./cbomly-out/`:
119
119
 
120
120
  | File | What it is |
121
121
  |---|---|
122
- | `cbom.cdx.json` | CycloneDX 1.6 BOM: the software components from Syft, one `cryptographic-asset` per algorithm, key, certificate and protocol (each with file and line evidence and a `cbomly:status`), and crypto services (KMS, HSM, CA) under `services` |
123
- | `summary.md` | The readable report: what is quantum-vulnerable, where, what to do, the full crypto inventory, and vendors |
124
- | `findings.json` | Findings, rule results, inventory and vendors, for scripts and `cbomly upload` |
122
+ | `cbom.cdx.json` | CycloneDX 1.6 BOM: the software components from Syft, one `cryptographic-asset` per algorithm, key, certificate and protocol (each with file and line evidence and a `cbomly:status`), one `machine-learning-model` per AI model, and every third-party service (crypto services, AI providers, payments, email…) under `services` |
123
+ | `summary.md` | The readable report: what is quantum-vulnerable, where, what to do, the full crypto inventory, AI models and libraries, and the vendor inventory |
124
+ | `findings.json` | Findings, rule results, inventory, AI (`ai`) and vendor inventory (`third_party_services`), for scripts and `cbomly upload` |
125
125
 
126
126
  ## Dashboard and CI
127
127
 
@@ -155,12 +155,16 @@ the trend view, alerts for new RSA/ECC and the release gate.
155
155
  | Dependencies (via Syft) | Crypto libraries such as OpenSSL, Bouncy Castle and Go's standard library, and whether the version supports post-quantum algorithms |
156
156
  | Post-quantum use | ML-KEM, ML-DSA, SLH-DSA and hybrid X25519MLKEM768 are recognised and reported as good news |
157
157
  | Third-party crypto services | AWS KMS, CloudHSM, Certificate Manager and Secrets Manager, Google Cloud KMS and Secret Manager, Azure Key Vault, HashiCorp Vault, Thales Luna, YubiHSM, Fortanix, PKCS#11 HSMs, Let's Encrypt and eMudhra, listed as vendors |
158
+ | AI models | Model files (Safetensors, GGUF, ONNX, PyTorch, TensorFlow, Keras, Core ML, TFLite and more, with SHA-256; Git LFS pointers count too), Hugging Face model ids in code, and hosted models named in code or config (GPT, Claude, Gemini, Llama, Mistral, DeepSeek and others). Pickle-based model files are flagged because they can run code when loaded |
159
+ | AI libraries | ML frameworks (PyTorch, TensorFlow, Transformers, scikit-learn…), model runtimes (ONNX Runtime, llama.cpp, Ollama, vLLM…), LLM and agent frameworks (LangChain, LlamaIndex, Vercel AI SDK…) and AI provider SDKs, from imports, manifests and the SBOM |
160
+ | Third-party services (vendor inventory) | About 90 services across AI providers, cloud (per service, e.g. Amazon S3), payments, email, SMS, identity, analytics, monitoring, hosted databases, search and more, found from SDK imports, API hostnames, API-key variable names, manifests (requirements.txt, package.json, go.mod, pom.xml, Gemfile, Cargo.toml, .csproj…) and the SBOM |
158
161
  | Safe crypto | AES (with key size and mode), ChaCha20-Poly1305, SHA-2, SHA-3, BLAKE2, HMAC, key derivation (PBKDF2, HKDF, scrypt, Argon2, bcrypt) and secure random number generators. Listed in the CBOM and marked quantum-safe, so the inventory is complete. AES-128 is marked "weakened by quantum" |
159
162
 
160
163
  Every algorithm, certificate, key and protocol gets one status: **broken**, **deprecated**,
161
164
  **quantum-vulnerable**, **weakened** (by quantum attacks, e.g. AES-128) or **safe**. Certificates also
162
- show issuer, public key, signature and expiry. Keys show size or curve. The **Vendors** section lists
165
+ show issuer, public key, signature and expiry. Keys show size or curve. The **Crypto vendors** section lists
163
166
  who supplies or controls your crypto: library makers, certificate issuers, and key management services.
167
+ AI detection and the vendor inventory always run; they never send anything anywhere.
164
168
 
165
169
  Detection is pattern-based, so it is fast and needs no build, but it can miss crypto hidden inside
166
170
  compiled binaries or wrapper functions, and it can report false positives. Findings carry a
@@ -4,8 +4,8 @@
4
4
 
5
5
  Cbomly scans a codebase and writes a **CBOM** (cryptographic bill of materials): a list of every
6
6
  algorithm, key and certificate your product uses, with the file and line where it was found. It also
7
- writes the normal software list (**SBOM**) and a plain-English report that says what a future quantum
8
- computer would break, and what to replace it with.
7
+ writes the normal software list (**SBOM**), lists the **AI models** and **third-party services** the product
8
+ uses, and a plain-English report that says what a future quantum computer would break, and what to replace it with.
9
9
 
10
10
  It runs locally on Linux, macOS and Windows. Nothing is uploaded unless you run `cbomly upload` to keep your
11
11
  reports in a free dashboard at [app.cbomly.com](https://app.cbomly.com), and even then only findings are
@@ -93,9 +93,9 @@ Output goes to `./cbomly-out/`:
93
93
 
94
94
  | File | What it is |
95
95
  |---|---|
96
- | `cbom.cdx.json` | CycloneDX 1.6 BOM: the software components from Syft, one `cryptographic-asset` per algorithm, key, certificate and protocol (each with file and line evidence and a `cbomly:status`), and crypto services (KMS, HSM, CA) under `services` |
97
- | `summary.md` | The readable report: what is quantum-vulnerable, where, what to do, the full crypto inventory, and vendors |
98
- | `findings.json` | Findings, rule results, inventory and vendors, for scripts and `cbomly upload` |
96
+ | `cbom.cdx.json` | CycloneDX 1.6 BOM: the software components from Syft, one `cryptographic-asset` per algorithm, key, certificate and protocol (each with file and line evidence and a `cbomly:status`), one `machine-learning-model` per AI model, and every third-party service (crypto services, AI providers, payments, email…) under `services` |
97
+ | `summary.md` | The readable report: what is quantum-vulnerable, where, what to do, the full crypto inventory, AI models and libraries, and the vendor inventory |
98
+ | `findings.json` | Findings, rule results, inventory, AI (`ai`) and vendor inventory (`third_party_services`), for scripts and `cbomly upload` |
99
99
 
100
100
  ## Dashboard and CI
101
101
 
@@ -129,12 +129,16 @@ the trend view, alerts for new RSA/ECC and the release gate.
129
129
  | Dependencies (via Syft) | Crypto libraries such as OpenSSL, Bouncy Castle and Go's standard library, and whether the version supports post-quantum algorithms |
130
130
  | Post-quantum use | ML-KEM, ML-DSA, SLH-DSA and hybrid X25519MLKEM768 are recognised and reported as good news |
131
131
  | Third-party crypto services | AWS KMS, CloudHSM, Certificate Manager and Secrets Manager, Google Cloud KMS and Secret Manager, Azure Key Vault, HashiCorp Vault, Thales Luna, YubiHSM, Fortanix, PKCS#11 HSMs, Let's Encrypt and eMudhra, listed as vendors |
132
+ | AI models | Model files (Safetensors, GGUF, ONNX, PyTorch, TensorFlow, Keras, Core ML, TFLite and more, with SHA-256; Git LFS pointers count too), Hugging Face model ids in code, and hosted models named in code or config (GPT, Claude, Gemini, Llama, Mistral, DeepSeek and others). Pickle-based model files are flagged because they can run code when loaded |
133
+ | AI libraries | ML frameworks (PyTorch, TensorFlow, Transformers, scikit-learn…), model runtimes (ONNX Runtime, llama.cpp, Ollama, vLLM…), LLM and agent frameworks (LangChain, LlamaIndex, Vercel AI SDK…) and AI provider SDKs, from imports, manifests and the SBOM |
134
+ | Third-party services (vendor inventory) | About 90 services across AI providers, cloud (per service, e.g. Amazon S3), payments, email, SMS, identity, analytics, monitoring, hosted databases, search and more, found from SDK imports, API hostnames, API-key variable names, manifests (requirements.txt, package.json, go.mod, pom.xml, Gemfile, Cargo.toml, .csproj…) and the SBOM |
132
135
  | Safe crypto | AES (with key size and mode), ChaCha20-Poly1305, SHA-2, SHA-3, BLAKE2, HMAC, key derivation (PBKDF2, HKDF, scrypt, Argon2, bcrypt) and secure random number generators. Listed in the CBOM and marked quantum-safe, so the inventory is complete. AES-128 is marked "weakened by quantum" |
133
136
 
134
137
  Every algorithm, certificate, key and protocol gets one status: **broken**, **deprecated**,
135
138
  **quantum-vulnerable**, **weakened** (by quantum attacks, e.g. AES-128) or **safe**. Certificates also
136
- show issuer, public key, signature and expiry. Keys show size or curve. The **Vendors** section lists
139
+ show issuer, public key, signature and expiry. Keys show size or curve. The **Crypto vendors** section lists
137
140
  who supplies or controls your crypto: library makers, certificate issuers, and key management services.
141
+ AI detection and the vendor inventory always run; they never send anything anywhere.
138
142
 
139
143
  Detection is pattern-based, so it is fast and needs no build, but it can miss crypto hidden inside
140
144
  compiled binaries or wrapper functions, and it can report false positives. Findings carry a
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "cbomly"
7
- version = "0.3.1"
7
+ version = "0.4.0"
8
8
  description = "Find the cryptography in your software, write a CycloneDX CBOM, and check it is quantum-safe."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -1,3 +1,3 @@
1
1
  """Cbomly: find the cryptography in your software and check it is quantum-safe."""
2
2
 
3
- __version__ = "0.3.1"
3
+ __version__ = "0.4.0"
@@ -12,6 +12,7 @@ import hashlib
12
12
  import uuid
13
13
  from collections import OrderedDict
14
14
  from datetime import UTC, datetime
15
+ from urllib.parse import quote
15
16
 
16
17
  from . import __version__, algorithms, inventory
17
18
  from .cbom_names import display_name
@@ -70,6 +71,18 @@ def _algorithm_component(name: str, alg: algorithms.Algorithm, group: list[Findi
70
71
  }
71
72
 
72
73
 
74
+ def _ref_plain(kind: str, key: str) -> str:
75
+ return f"{kind}/{hashlib.sha1(key.encode()).hexdigest()[:12]}"
76
+
77
+
78
+ def _where(p: dict) -> str:
79
+ return f"{p['file']}:{p['line']}" if p.get("line") else p["file"]
80
+
81
+
82
+ def _loc(p: dict) -> dict:
83
+ return {"location": p["file"], **({"line": p["line"]} if p.get("line") else {})}
84
+
85
+
73
86
  def _props(alg: algorithms.Algorithm, status: str) -> list[dict]:
74
87
  return [
75
88
  {"name": "cbomly:status", "value": status},
@@ -80,7 +93,8 @@ def _props(alg: algorithms.Algorithm, status: str) -> list[dict]:
80
93
 
81
94
 
82
95
  def build(findings: list[Finding], sbom: dict | None, target_name: str, crypto_libs: list[dict] | None = None,
83
- tool_versions: dict | None = None, services: list[dict] | None = None) -> dict:
96
+ tool_versions: dict | None = None, services: list[dict] | None = None, ai_inv: dict | None = None,
97
+ vendor_inv: list[dict] | None = None) -> dict:
84
98
  now = datetime.now(UTC).replace(microsecond=0).isoformat().replace("+00:00", "Z")
85
99
  bom: dict = {
86
100
  "$schema": "http://cyclonedx.org/schema/bom-1.6.schema.json",
@@ -207,6 +221,60 @@ def build(findings: list[Finding], sbom: dict | None, target_name: str, crypto_l
207
221
  bom.setdefault("services", []).append(e)
208
222
  e["properties"].append({"name": "cbomly:location", "value": f"{svc['file']}:{svc['line']}"})
209
223
 
224
+ # 6. other third-party services (vendor inventory)
225
+ for v in vendor_inv or []:
226
+ if v["service"] in seen_svc:
227
+ continue
228
+ props = [{"name": "cbomly:service-category", "value": v["category"]}]
229
+ props += [{"name": "cbomly:location", "value": _where(p)} for p in v["places"]]
230
+ props += [{"name": "cbomly:package", "value": p} for p in v["packages"]]
231
+ e = {"bom-ref": _ref_plain("service", f"{v['vendor']}/{v['service']}"), "provider": {"name": v["vendor"]},
232
+ "name": v["service"], "x-trust-boundary": True, "properties": props}
233
+ seen_svc[v["service"]] = e
234
+ bom.setdefault("services", []).append(e)
235
+ other_refs = [e["bom-ref"] for e in seen_svc.values()]
236
+
237
+ # 7. AI: libraries (tag SBOM components, or add them) and models
238
+ by_ref = {c.get("bom-ref"): c for c in bom["components"]}
239
+ for lib in (ai_inv or {}).get("libraries", []):
240
+ tags = [{"name": "cbomly:ai-library", "value": lib["name"]}, {"name": "cbomly:ai-role", "value": lib["role"]}]
241
+ tagged = [by_ref[r] for r in lib["bom_refs"] if r in by_ref]
242
+ for c in tagged:
243
+ c.setdefault("properties", []).extend(tags)
244
+ if not tagged:
245
+ ref = _ref_plain("ai/library", lib["name"])
246
+ comp = {"type": "library", "name": lib["name"], "bom-ref": ref, "properties": tags}
247
+ if lib["places"]:
248
+ comp["evidence"] = {"occurrences": [_loc(p) for p in lib["places"]]}
249
+ bom["components"].append(comp)
250
+ other_refs.append(ref)
251
+ for m in (ai_inv or {}).get("models", []):
252
+ ref = _ref_plain("ai/model", f"{m['kind']}:{m['name']}:{m['places'][0]['file']}" if m["kind"] == "file" else f"{m['kind']}:{m['name']}")
253
+ source = {"file": "file", "huggingface": "huggingface-hub", "hosted": "hosted-api", "local": "local-runtime"}[m["kind"]]
254
+ props = [{"name": "cbomly:ai-model-source", "value": source}]
255
+ comp = {"type": "machine-learning-model", "name": m["name"], "bom-ref": ref}
256
+ if m["kind"] == "file":
257
+ props.append({"name": "cbomly:model-format", "value": m["format"]})
258
+ if m["pickle"]:
259
+ props.append({"name": "cbomly:pickle-format", "value": "true"})
260
+ if m.get("size"):
261
+ props.append({"name": "cbomly:size-bytes", "value": str(m["size"])})
262
+ if m.get("sha256"):
263
+ comp["hashes"] = [{"alg": "SHA-256", "content": m["sha256"]}]
264
+ else:
265
+ comp["supplier"] = {"name": m["supplier"]}
266
+ if m["kind"] == "huggingface":
267
+ org, _, model = m["name"].partition("/")
268
+ comp["group"] = org
269
+ comp["purl"] = f"pkg:huggingface/{quote(org)}/{quote(model)}"
270
+ if m.get("runtime"):
271
+ props.append({"name": "cbomly:ai-runtime", "value": m["runtime"]})
272
+ comp["evidence"] = {"occurrences": [_loc(p) for p in m["places"]]}
273
+ comp["properties"] = props
274
+ bom["components"].append(comp)
275
+ other_refs.append(ref)
276
+
277
+ crypto_refs += other_refs
210
278
  if crypto_refs:
211
279
  existing = next((d for d in bom["dependencies"] if d.get("ref") == root_ref), None)
212
280
  if existing is None:
@@ -10,7 +10,7 @@ from datetime import UTC, datetime
10
10
  from pathlib import Path
11
11
 
12
12
  from . import __version__, algorithms, cbom, inventory, report, rules, sbom, scanner
13
- from .detect import deps
13
+ from .detect import ai, deps, vendors
14
14
  from .rules import SEVERITIES
15
15
 
16
16
 
@@ -76,7 +76,7 @@ def cmd_scan(a) -> int:
76
76
  base = [".git", ".hg", ".svn", "cbomly-out"] if a.include_vendored else list(scanner.DEFAULT_EXCLUDES)
77
77
  excludes = base + a.exclude + [Path(a.out).name]
78
78
 
79
- log(f"Scanning {target} for cryptography…")
79
+ log(f"Scanning {target} for cryptography, AI and third-party services…")
80
80
  findings, stats = scanner.scan_path(target, excludes)
81
81
  log(f" {stats.files_scanned} files read, {len(findings)} crypto uses found")
82
82
 
@@ -105,22 +105,28 @@ def write_outputs(a, name, packs, findings, sb, stats, notes, tool_versions, sou
105
105
  """Shared by `scan` and `import`: evaluate rules, write the three output files, print the summary."""
106
106
  libs = deps.crypto_libraries(sb)
107
107
  ev = rules.evaluate(packs, findings, sb)
108
- bom = cbom.build(findings, sb, name, libs, tool_versions, stats.services)
108
+ ai_inv = ai.inventory(stats.ai_models, stats.ai_libs + ai.libs_from_sbom(sb))
109
+ hub = [{"vendor": "Hugging Face", "service": "Hugging Face Hub and Inference", "category": "ai", "source": "code",
110
+ "file": m["file"], "line": m["line"]} for m in stats.ai_models if m["kind"] == "huggingface"]
111
+ vendor_inv = vendors.inventory(stats.vendors + hub + vendors.from_sbom(sb), stats.services)
112
+ bom = cbom.build(findings, sb, name, libs, tool_versions, stats.services, ai_inv, vendor_inv)
109
113
  n_sw = len(sb.get("components", [])) if sb else None
110
114
 
111
115
  out = Path(a.out)
112
116
  out.mkdir(parents=True, exist_ok=True)
113
117
  (out / "cbom.cdx.json").write_text(json.dumps(bom, indent=2) + "\n", encoding="utf-8")
114
- summary = report.markdown(name, findings, ev, libs, n_sw, notes, stats.services)
118
+ summary = report.markdown(name, findings, ev, libs, n_sw, notes, stats.services, ai_inv, vendor_inv)
115
119
  (out / "summary.md").write_text(summary, encoding="utf-8")
116
120
  doc = results_doc(name, findings, ev, libs, n_sw, stats)
121
+ doc["ai"] = ai_inv
122
+ doc["third_party_services"] = vendor_inv
117
123
  doc["source"] = source or {"type": "scan"}
118
124
  (out / "findings.json").write_text(json.dumps(doc, indent=2) + "\n", encoding="utf-8")
119
125
 
120
126
  if not a.quiet:
121
127
  color = sys.stdout.isatty() and not a.no_color and not os.environ.get("NO_COLOR")
122
128
  title = "Cbomly import complete" if source and source.get("type") == "import" else "Cbomly scan complete"
123
- print(report.terminal(findings, ev, str(out), color, title))
129
+ print(report.terminal(findings, ev, str(out), color, title, ai_inv, vendor_inv))
124
130
 
125
131
  if a.fail_on:
126
132
  worst = ev.worst_severity()
@@ -0,0 +1,298 @@
1
+ """Find AI in a codebase: model files, models the code calls or downloads, and AI libraries.
2
+
3
+ Always on. Buyers increasingly ask which AI models a product contains or sends data to
4
+ (EU AI Act, customer AI questionnaires, CycloneDX AI BOMs), and model files saved with
5
+ Python's pickle can run code when they are loaded.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import re
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+
15
+ from .manifest import purl_key
16
+ from .source import ALL
17
+
18
+ # ---------------------------------------------------------------- model files
19
+ # extension -> (format, pickle-based?)
20
+ MODEL_EXTS = {
21
+ ".safetensors": ("Safetensors", False), ".gguf": ("GGUF", False), ".ggml": ("GGML", False),
22
+ ".onnx": ("ONNX", False), ".tflite": ("TensorFlow Lite", False), ".keras": ("Keras", False),
23
+ ".mlmodel": ("Core ML", False), ".llamafile": ("llamafile", False), ".pdmodel": ("PaddlePaddle", False),
24
+ ".caffemodel": ("Caffe", False), ".nemo": ("NVIDIA NeMo", False), ".mar": ("TorchServe archive", True),
25
+ ".pt": ("PyTorch", True), ".pth": ("PyTorch", True), ".ckpt": ("Checkpoint", True),
26
+ }
27
+ MODEL_NAMES = {
28
+ "saved_model.pb": ("TensorFlow SavedModel", False), "flax_model.msgpack": ("Flax", False),
29
+ "tf_model.h5": ("Keras/HDF5", False),
30
+ }
31
+ MODEL_DIRS = {".mlpackage": "Core ML package", ".mlmodelc": "Core ML compiled model"}
32
+ HASH_LIMIT = 512 * 1024 * 1024
33
+
34
+
35
+ def model_format(path: Path) -> tuple[str, bool, str] | None:
36
+ """(format, pickle-based, confidence) if this file looks like model weights."""
37
+ name, ext = path.name.lower(), path.suffix.lower()
38
+ if name in MODEL_NAMES:
39
+ return (*MODEL_NAMES[name], "high")
40
+ if ext in MODEL_EXTS:
41
+ return (*MODEL_EXTS[ext], "high")
42
+ if ext == ".bin" and re.match(r"(?:pytorch_model|model|adapter_model)(?:-\d+-of-\d+)?\.bin$", name):
43
+ return ("PyTorch", True, "high")
44
+ if ext == ".bin" and name.startswith("ggml-"):
45
+ return ("GGML", False, "high")
46
+ if ext in (".h5", ".hdf5") and "model" in path.as_posix().lower():
47
+ return ("Keras/HDF5", False, "medium")
48
+ if ext in (".pkl", ".pickle", ".joblib") and re.search(r"model|clf|classifier|regressor|estimator", path.as_posix().lower()):
49
+ return ("Pickle (e.g. scikit-learn)", True, "medium")
50
+ return None
51
+
52
+
53
+ def model_dir(rel: str) -> str | None:
54
+ """'app/Foo.mlpackage/Data/x' -> 'app/Foo.mlpackage' for model formats that are folders."""
55
+ parts = rel.split("/")
56
+ for i, p in enumerate(parts[:-1]):
57
+ if any(p.lower().endswith(s) for s in MODEL_DIRS):
58
+ return "/".join(parts[: i + 1])
59
+ return None
60
+
61
+
62
+ def model_file(path: Path, rel: str) -> dict | None:
63
+ fmt = model_format(path)
64
+ if not fmt:
65
+ return None
66
+ rec = {"kind": "file", "name": path.name, "format": fmt[0], "pickle": fmt[1], "confidence": fmt[2],
67
+ "file": rel, "size": None, "sha256": None}
68
+ try:
69
+ size = path.stat().st_size
70
+ rec["size"] = size
71
+ with path.open("rb") as fh:
72
+ head = fh.read(200)
73
+ if head.startswith(b"version https://git-lfs"):
74
+ # Git LFS pointer: the real file isn't checked out, but the pointer has its hash and size.
75
+ text = (head + fh.read(300)).decode("ascii", "replace")
76
+ m = re.search(r"oid sha256:([0-9a-f]{64})", text)
77
+ n = re.search(r"\nsize (\d+)", text)
78
+ rec.update(sha256=m.group(1) if m else None, size=int(n.group(1)) if n else None, lfs_pointer=True)
79
+ elif size <= HASH_LIMIT:
80
+ h = hashlib.sha256(head)
81
+ for chunk in iter(lambda: fh.read(1 << 20), b""):
82
+ h.update(chunk)
83
+ rec["sha256"] = h.hexdigest()
84
+ except OSError:
85
+ pass
86
+ return rec
87
+
88
+
89
+ # ---------------------------------------------------------------- models named in code
90
+ HF_ID = r"(?P<id>[A-Za-z0-9][\w.-]{0,95}/[A-Za-z0-9][\w.-]{0,95})"
91
+ Q = r"""["'`]"""
92
+ HF_PATTERNS = [
93
+ re.compile(rf"\.from_pretrained\(\s*{Q}{HF_ID}{Q}"),
94
+ re.compile(rf"\b(?:hf_hub_download|snapshot_download)\([^)]*?repo_id\s*=\s*{Q}{HF_ID}{Q}", re.DOTALL),
95
+ re.compile(rf"\b(?:hf_hub_download|snapshot_download)\(\s*{Q}{HF_ID}{Q}"),
96
+ re.compile(rf"\bpipeline\([^)]*?model\s*=\s*{Q}{HF_ID}{Q}", re.DOTALL),
97
+ re.compile(rf"\b(?:SentenceTransformer|CrossEncoder|AutoModel\w*|LLM)\(\s*(?:model\s*=\s*)?{Q}{HF_ID}{Q}"),
98
+ re.compile(rf"\bhuggingface\.co/(?!datasets/|spaces/|docs/|blog/|api/|models\b|settings/|join\b|login\b|learn/|papers/|tasks/|organizations/){HF_ID}"),
99
+ re.compile(rf"\bhf\.co/(?!datasets/|spaces/|docs/|blog/){HF_ID}"),
100
+ ]
101
+ # Hosted model names, matched only inside a string literal.
102
+ HOSTED = [
103
+ ("OpenAI", (r"gpt-[\w.-]+|chatgpt-[\w.-]+|o[134](?:-mini|-pro|-preview|-deep-research)?(?:-[\d-]+)?|text-embedding-[\w.-]+|"
104
+ r"dall-e-[23]|whisper-1|tts-1(?:-hd)?|gpt-image-[\w.-]+|omni-moderation-[\w.-]+|codex-[\w.-]+")),
105
+ ("Anthropic", r"claude-[\w.@-]+|anthropic\.claude-[\w.:-]+|us\.anthropic\.claude-[\w.:-]+"),
106
+ ("Google", r"gemini-[\w.-]+|text-bison[\w.@-]*|chat-bison[\w.@-]*|textembedding-gecko[\w.@-]*|text-embedding-00\d|imagen-[\w.-]+|gemma-?[\d.]+[\w.:-]*"),
107
+ ("Mistral AI", r"(?:open-)?(?:mistral|mixtral|codestral|pixtral|ministral|magistral|devstral)-[\w.-]+|mistral\.[\w.:-]+"),
108
+ ("Cohere", r"command-[\w.-]+|command|embed-(?:english|multilingual)-[\w.-]+|rerank-[\w.-]+|cohere\.[\w.:-]+"),
109
+ ("Meta", r"(?:meta-)?llama-?[234][\w.:-]*|meta\.llama[\w.:-]+|codellama[\w.:-]*"),
110
+ ("DeepSeek", r"deepseek-[\w.:-]+"),
111
+ ("xAI", r"grok-[\w.-]+"),
112
+ ("Alibaba", r"qwen[\d.]*(?:-[\w.:-]+|:[\w.-]+)?"),
113
+ ("Microsoft", r"phi-?[34][\w.:-]*"),
114
+ ("Amazon", r"amazon\.(?:titan|nova)[\w.:-]+"),
115
+ ("AI21 Labs", r"ai21\.[\w.:-]+|jamba-[\w.-]+"),
116
+ ]
117
+ HOSTED_RX = re.compile(rf"{Q}(?P<m>{'|'.join(f'(?:{rx})' for _, rx in HOSTED)}){Q}", re.IGNORECASE)
118
+ # YAML, .env and properties files often write the model without quotes: `model: gpt-4o`, `OPENAI_MODEL=gpt-4o`.
119
+ HOSTED_KV = re.compile(rf"^[ \t]*[\w.-]*model[\w.-]*[ \t]*[:=][ \t]*(?P<m>{'|'.join(f'(?:{rx})' for _, rx in HOSTED)})[ \t]*(?:#.*)?$",
120
+ re.IGNORECASE | re.MULTILINE)
121
+ HOSTED_BY = [(sup, re.compile(rf"^(?:{rx})$", re.IGNORECASE)) for sup, rx in HOSTED]
122
+ WEAK = re.compile(r"^(?:o[134]|command|gemma\d*|qwen[\d.]*)$", re.IGNORECASE) # need "model" on the same line
123
+ OLLAMA = re.compile(rf"\bollama\s+(?:pull|run)\s+(?P<m>[\w.-]+(?::[\w.-]+)?)|\bollama\.(?:chat|generate|embed\w*)\([^)]*?model\s*=\s*{Q}(?P<m2>[\w.:/-]+){Q}", re.DOTALL)
124
+ SKIP_NAMES = {"package.json", "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "poetry.lock", "cargo.lock",
125
+ "composer.lock", "gemfile.lock", "go.sum", "uv.lock", "pipfile.lock"}
126
+ # Not model ids even if they look like org/name.
127
+ HF_NOT = re.compile(r"^(?:http|www\.|[\w.-]+\.(?:com|org|io|net|json|txt|py|bin|md)$)|/(?:tree|blob|resolve|raw)$", re.IGNORECASE)
128
+
129
+
130
+ def _supplier(name: str) -> str:
131
+ for sup, rx in HOSTED_BY:
132
+ if rx.match(name):
133
+ return sup
134
+ return "Unknown"
135
+
136
+
137
+ def scan_text(rel: str, text: str, ext: str) -> list[dict]:
138
+ """Model references in code and config: Hugging Face ids, hosted model names, Ollama models."""
139
+ if ext not in ALL or Path(rel).name.lower() in SKIP_NAMES:
140
+ return []
141
+ out: list[dict] = []
142
+ seen: set[tuple] = set()
143
+
144
+ def add(kind, name, supplier, pos, **extra):
145
+ if (kind, name) in seen:
146
+ return
147
+ seen.add((kind, name))
148
+ out.append({"kind": kind, "name": name, "supplier": supplier, "file": rel,
149
+ "line": text.count("\n", 0, pos) + 1, **extra})
150
+
151
+ for rx in HF_PATTERNS:
152
+ for m in rx.finditer(text):
153
+ mid = m.group("id").rstrip(".")
154
+ if not HF_NOT.search(mid):
155
+ add("huggingface", mid, mid.split("/")[0], m.start("id"))
156
+ for m in HOSTED_RX.finditer(text):
157
+ name = m.group("m")
158
+ if WEAK.match(name):
159
+ ls = text.rfind("\n", 0, m.start()) + 1
160
+ le = text.find("\n", m.end())
161
+ if "model" not in text[ls: le if le >= 0 else None].lower():
162
+ continue
163
+ add("hosted", name, _supplier(name), m.start("m"))
164
+ for m in HOSTED_KV.finditer(text):
165
+ add("hosted", m.group("m"), _supplier(m.group("m")), m.start("m"))
166
+ for m in OLLAMA.finditer(text):
167
+ name = m.group("m") or m.group("m2")
168
+ add("local", name, _supplier(name.split(":")[0]) if _supplier(name.split(":")[0]) != "Unknown" else "Ollama library",
169
+ m.start(), runtime="Ollama")
170
+ return out
171
+
172
+
173
+ # ---------------------------------------------------------------- AI libraries
174
+ @dataclass(frozen=True)
175
+ class Lib:
176
+ name: str
177
+ role: str # framework | runtime | orchestration | sdk
178
+ code: re.Pattern | None
179
+ pkg: re.Pattern | None
180
+
181
+
182
+ def L(name, role, code=None, pkg=None):
183
+ return Lib(name, role, re.compile(code, re.MULTILINE) if code else None, re.compile(rf"^(?:{pkg})$") if pkg else None)
184
+
185
+
186
+ LIBS: list[Lib] = [
187
+ L("PyTorch", "framework", r"^\s*(?:import\s+torch\b|from\s+torch\b)", r"pypi/torch|pypi/pytorch|cargo/tch|maven/org\.pytorch/[\w-]+"),
188
+ L("TensorFlow", "framework", rf"^\s*(?:import\s+tensorflow\b|from\s+tensorflow\b)|{Q}@tensorflow/tfjs[\w-]*{Q}",
189
+ r"pypi/tensorflow(?:-cpu|-gpu|-macos|-intel)?|npm/@tensorflow/tfjs[\w-]*|maven/org\.tensorflow/[\w-]+"),
190
+ L("Keras", "framework", r"^\s*(?:import\s+keras\b|from\s+keras\b)", r"pypi/keras"),
191
+ L("JAX", "framework", r"^\s*(?:import\s+jax\b|from\s+jax\b|import\s+flax\b|from\s+flax\b)", r"pypi/jax|pypi/flax"),
192
+ L("scikit-learn", "framework", r"^\s*(?:import\s+sklearn\b|from\s+sklearn\b)", r"pypi/scikit-learn"),
193
+ L("XGBoost", "framework", r"^\s*import\s+xgboost\b", r"pypi/xgboost|maven/ml\.dmlc/xgboost4j[\w-]*"),
194
+ L("LightGBM", "framework", r"^\s*import\s+lightgbm\b", r"pypi/lightgbm"),
195
+ L("Hugging Face Transformers", "framework", rf"^\s*(?:from|import)\s+transformers\b|{Q}@(?:xenova|huggingface)/transformers{Q}",
196
+ r"pypi/transformers|npm/@xenova/transformers|npm/@huggingface/transformers"),
197
+ L("Hugging Face Diffusers", "framework", r"^\s*(?:from|import)\s+diffusers\b", r"pypi/diffusers"),
198
+ L("PEFT / Accelerate", "framework", r"^\s*(?:from|import)\s+(?:peft|accelerate)\b", r"pypi/peft|pypi/accelerate"),
199
+ L("Sentence Transformers", "framework", r"^\s*(?:from|import)\s+sentence_transformers\b", r"pypi/sentence-transformers"),
200
+ L("spaCy", "framework", r"^\s*import\s+spacy\b", r"pypi/spacy"),
201
+ L("ONNX Runtime", "runtime", rf"^\s*import\s+onnxruntime\b|{Q}onnxruntime-(?:node|web|react-native){Q}|Microsoft\.ML\.OnnxRuntime",
202
+ r"pypi/onnxruntime(?:-gpu)?|npm/onnxruntime-(?:node|web|react-native)|nuget/microsoft\.ml\.onnxruntime[\w.]*|cargo/ort|maven/com\.microsoft\.onnxruntime/[\w-]+"),
203
+ L("TensorFlow Lite", "runtime", r"\btflite_runtime\b|\bInterpreter\(model_path=|org\.tensorflow\.lite\b", r"pypi/tflite-runtime|maven/org\.tensorflow/tensorflow-lite[\w-]*"),
204
+ L("Core ML", "runtime", r"^\s*import\s+CoreML\b|^\s*import\s+coremltools\b", r"pypi/coremltools"),
205
+ L("llama.cpp", "runtime", r"^\s*from\s+llama_cpp\b|node-llama-cpp", r"pypi/llama-cpp-python|npm/node-llama-cpp|cargo/llama-cpp-2"),
206
+ L("vLLM", "runtime", r"^\s*from\s+vllm\b", r"pypi/vllm"),
207
+ L("Ollama", "runtime", rf"^\s*import\s+ollama\b|{Q}ollama{Q}|localhost:11434|github\.com/ollama/ollama/api", r"pypi/ollama|npm/ollama|golang/github\.com/ollama/ollama"),
208
+ L("MLX", "runtime", r"^\s*(?:import|from)\s+mlx(?:_lm)?\b", r"pypi/mlx|pypi/mlx-lm"),
209
+ L("Candle", "runtime", None, r"cargo/candle-(?:core|nn|transformers)"),
210
+ L("ML.NET", "framework", r"\bMicrosoft\.ML\b", r"nuget/microsoft\.ml"),
211
+ L("Deep Java Library", "framework", r"\bai\.djl\b", r"maven/ai\.djl[\w.]*/[\w-]+"),
212
+ L("LangChain", "orchestration", rf"^\s*(?:from|import)\s+langchain\w*|{Q}(?:@langchain/[\w-]+|langchain(?:/[\w/-]+)?){Q}|\bdev\.langchain4j\b|tmc/langchaingo",
213
+ r"pypi/langchain(?:-[\w-]+)?|npm/langchain|npm/@langchain/[\w-]+|maven/dev\.langchain4j/[\w-]+|golang/github\.com/tmc/langchaingo|gem/langchainrb"),
214
+ L("LlamaIndex", "orchestration", rf"^\s*(?:from|import)\s+llama_index\b|{Q}llamaindex{Q}", r"pypi/llama-index(?:-[\w-]+)?|npm/llamaindex"),
215
+ L("Vercel AI SDK", "orchestration", rf"from\s+{Q}ai{Q}|{Q}@ai-sdk/[\w-]+{Q}", r"npm/ai|npm/@ai-sdk/[\w-]+"),
216
+ L("Semantic Kernel", "orchestration", r"Microsoft\.SemanticKernel|^\s*(?:from|import)\s+semantic_kernel\b", r"nuget/microsoft\.semantickernel[\w.]*|pypi/semantic-kernel"),
217
+ L("Spring AI", "orchestration", r"org\.springframework\.ai\b", r"maven/org\.springframework\.ai/[\w-]+"),
218
+ L("LiteLLM", "orchestration", r"^\s*(?:import|from)\s+litellm\b", r"pypi/litellm"),
219
+ L("DSPy", "orchestration", r"^\s*import\s+dspy\b", r"pypi/dspy(?:-ai)?"),
220
+ L("CrewAI", "orchestration", r"^\s*from\s+crewai\b", r"pypi/crewai"),
221
+ L("OpenAI Agents SDK", "orchestration", rf"^\s*from\s+agents\s+import\s+Agent\b|{Q}@openai/agents{Q}", r"pypi/openai-agents|npm/@openai/agents"),
222
+ L("Model Context Protocol SDK", "orchestration", rf"^\s*from\s+mcp\b|{Q}@modelcontextprotocol/sdk[\w/.-]*{Q}", r"pypi/mcp|npm/@modelcontextprotocol/sdk"),
223
+ L("OpenAI SDK", "sdk", None, r"pypi/openai|npm/openai|golang/github\.com/(?:openai/openai-go|sashabaranov/go-openai)(?:/v\d+)?|maven/com\.openai/openai-java|nuget/openai|gem/ruby-openai|composer/openai-php/client|cargo/async-openai"),
224
+ L("Anthropic SDK", "sdk", None, r"pypi/anthropic|npm/@anthropic-ai/sdk|golang/github\.com/anthropics/anthropic-sdk-go|maven/com\.anthropic/anthropic-java|nuget/anthropic(?:\.sdk)?"),
225
+ L("Google Gen AI SDK", "sdk", None, r"pypi/google-generativeai|pypi/google-genai|npm/@google/(?:generative-ai|genai)|golang/google\.golang\.org/genai"),
226
+ L("Mistral SDK", "sdk", None, r"pypi/mistralai|npm/@mistralai/mistralai"),
227
+ L("Cohere SDK", "sdk", None, r"pypi/cohere|npm/cohere-ai"),
228
+ L("Hugging Face Hub", "sdk", None, r"pypi/huggingface-hub|npm/@huggingface/(?:inference|hub)"),
229
+ ]
230
+ ROLE_LABEL = {"framework": "ML framework", "runtime": "Model runtime", "orchestration": "LLM / agent framework", "sdk": "AI provider SDK"}
231
+
232
+
233
+ def scan_libs(rel: str, text: str, ext: str) -> list[dict]:
234
+ if ext not in ALL:
235
+ return []
236
+ out = []
237
+ for lib in LIBS:
238
+ if lib.code:
239
+ m = lib.code.search(text)
240
+ if m:
241
+ out.append({"name": lib.name, "role": lib.role, "source": "code", "file": rel,
242
+ "line": text.count("\n", 0, m.start()) + 1})
243
+ return out
244
+
245
+
246
+ def _lib_for(key: str) -> Lib | None:
247
+ for lib in LIBS:
248
+ if lib.pkg and lib.pkg.match(key):
249
+ return lib
250
+ return None
251
+
252
+
253
+ def libs_from_manifest(rel: str, deps: list[tuple[str, int]]) -> list[dict]:
254
+ out = []
255
+ for key, line in deps:
256
+ lib = _lib_for(key)
257
+ if lib:
258
+ out.append({"name": lib.name, "role": lib.role, "source": "manifest", "file": rel, "line": line, "package": key})
259
+ return out
260
+
261
+
262
+ def libs_from_sbom(sbom: dict | None) -> list[dict]:
263
+ out = []
264
+ for c in (sbom or {}).get("components", []):
265
+ key = purl_key(c.get("purl") or "")
266
+ lib = _lib_for(key) if key else None
267
+ if lib:
268
+ out.append({"name": lib.name, "role": lib.role, "source": "sbom", "package": key, "purl": c.get("purl"),
269
+ "version": c.get("version"), "bom-ref": c.get("bom-ref")})
270
+ return out
271
+
272
+
273
+ # ---------------------------------------------------------------- grouping
274
+ def inventory(models: list[dict], libs: list[dict]) -> dict:
275
+ """{"models": [...], "libraries": [...]}, one entry per model or library, with every place seen."""
276
+ gm: dict[tuple, dict] = {}
277
+ for r in models:
278
+ key = ("file", r["file"]) if r["kind"] == "file" else (r["kind"], r["name"])
279
+ e = gm.setdefault(key, {k: v for k, v in r.items() if k not in ("file", "line")} | {"places": []})
280
+ e["places"].append({"file": r["file"], "line": r.get("line")})
281
+ gl: dict[str, dict] = {}
282
+ for r in libs:
283
+ e = gl.setdefault(r["name"], {"name": r["name"], "role": r["role"], "role_label": ROLE_LABEL[r["role"]],
284
+ "found_in": [], "packages": [], "versions": [], "places": [], "bom_refs": []})
285
+ if r["source"] not in e["found_in"]:
286
+ e["found_in"].append(r["source"])
287
+ for k, dst in (("package", "packages"), ("version", "versions"), ("bom-ref", "bom_refs")):
288
+ if r.get(k) and r[k] not in e[dst]:
289
+ e[dst].append(r[k])
290
+ if r.get("file"):
291
+ p = {"file": r["file"], "line": r.get("line")}
292
+ if p not in e["places"]:
293
+ e["places"].append(p)
294
+ kind_order = ["file", "huggingface", "local", "hosted"]
295
+ models_out = sorted(gm.values(), key=lambda e: (kind_order.index(e["kind"]), e["name"].lower()))
296
+ role_order = list(ROLE_LABEL)
297
+ libs_out = sorted(gl.values(), key=lambda e: (role_order.index(e["role"]), e["name"]))
298
+ return {"models": models_out, "libraries": libs_out}