a6ee31f55a
* feat(wisdom): add trusted publish and install foundation
* feat(wisdom): add private contribution loop
* feat(wisdom): add managed consumption workflows
* fix(wisdom): close cross-repository safety gaps
* fix(wisdom): align local package and lifecycle policy
* fix(wisdom): require explicit profile setup
* docs(wisdom): repin reconciled gateway head
* fix(wisdom): fence content downloads and approval receipts
* docs(wisdom): record generation-fenced downloads
* docs(wisdom): record unified delivery PR
* fix(ci): stop passing invalid classifier inputs
* docs(wisdom): remove internal requirements ledger
* feat(wisdom): localize dashboard and desktop copy
* feat(wisdom): complete local contribution and consumption UX
* style(wisdom): satisfy desktop lint
* chore(wisdom): refresh requirements pin
* test(dashboard): allow formatted profile copy
* test(wisdom): stabilize desktop interaction coverage
* fix(wisdom): surface dashboard action failures
* fix(wisdom): add repeatable Portal demo login
* feat(wisdom): add actionable skill notifications
* feat(wisdom): add notification install and update actions
* fix(wisdom): make Telegram skill alerts actionable
* fix(wisdom): always refresh demo Agent login
* feat(wisdom): embed Telegram notification actions
* fix(wisdom): preserve Telegram notifications after actions
* fix(wisdom): keep Telegram notification cards readable
* feat(wisdom): add Telegram candidate approval flow
* feat(wisdom): explain Telegram qualification reasons
* fix(wisdom): reconcile cross-surface candidate actions
* feat(telegram): add Collective Wisdom management command
* chore(wisdom): refresh Gateway contract pin
* chore(wisdom): advance Gateway contract pin
* feat(wisdom): align command UX across clients
* feat(slack): add Collective Wisdom management parity
* feat(wisdom): add security and professionalism reviews
* feat(wisdom): add first-time qualification guidance
* feat(wisdom): simplify qualification sharing choices
* feat(skills): add optional editorial metadata
* feat(wisdom): enrich legacy skill presentation
* fix(wisdom): harden review and update boundaries
* fix(wisdom): emit canonical review timestamps
* fix(wisdom): align with merged gateway and main
* wisdom: add agent-led sharing core (policy, evidence, schemas, templates, delivery, weekly job, share/install flows)
- hermes_wisdom/agent_led/: policy resolution (server > local > defaults),
7-day evidence builder that excludes bundled/hub/managed skills and
dismissed/handled/recently-suggested content hashes, strict pydantic
schemas for agent output with repair-or-reject, fixed copy templates
(Share / Teammate / Published / Update / Mute), idempotent retried
delivery ledger with stale-action resolution, weekly review job,
resumable Share and Install flows.
- prompts/: candidate review, recipient recommendation, share packaging.
- tests/wisdom/test_agent_led.py: 30 tests.
* wisdom: agent-led renderers and button action dispatcher
- render.py: Telegram HTML, Slack blocks, Desktop payload; editorial name
is the emphasized line, product label stays separate.
- actions.py: resolve opaque wa:<action>:<dedup> targets via the delivery
ledger; Not now -> dismissal, Mute -> fixed options, Share -> resumable
packaging flow, Install/Update -> plan command. Never publishes/installs.
* wisdom: CLI verbs, agent_led config default, conversational catalog skill
- hermes wisdom browse/review-week/act/share/dismiss/mute (all --json).
- wisdom.agent_led config block, default enabled.
- SKILL.md rewritten so natural-language catalog questions map to the CLI
verbs, share/install flows and fixed notification templates.
* wisdom: wire agent-led weekly review into gateway tick and Telegram buttons
- gateway housekeeping tick calls maybe_run_weekly_review with a home
channel sender when a Telegram adapter is available.
- Telegram: wa: callbacks resolved through the ledger (stale-safe), mute
duration keyboard, send_wisdom_agent_recommendation rich card + fallback.
* fix(wisdom): integrate local mediation and harden model and setup boundaries
* fix(wisdom): honor authoritative recommendation policy and defer on failure
* fix(wisdom): synchronize opaque suppression and recheck delivery preferences
* feat(wisdom): route weekly selection through the session-owned assessment queue
* fix(wisdom): prepare and submit the reviewed generated share package
* feat(wisdom): separate native Share preparation from publication consent
* feat(wisdom): sync native mute choices through a leased preference outbox
* feat(wisdom): bind native mute controls to durable preference choices
* feat(wisdom): add scoped desktop and dashboard notification settings
* fix(wisdom): revalidate feed recommendations before assessment and delivery
* fix(wisdom): persist validated delivery receipts before completing notices
* feat(wisdom): add private notification claim and receipt client
* Persist Wisdom send reservations and recover delivery acknowledgements
* Route legacy Wisdom controls through current native review
* Add typed private Wisdom operation outcome client
* fix(wisdom): make agent-led advice usable in the local demo
* fix(wisdom): keep requested consent outside proactive limits
* fix(wisdom): distinguish unavailable assessments and preserve digest text
* fix(wisdom): assess ongoing usefulness beyond the current task
* fix(wisdom): restore immediate qualification sharing controls
* fix(wisdom): separate qualification review from installation advice
* fix(wisdom): collapse review checklists and simplify sharing copy
* fix(wisdom): show compact sharing progress and publication receipts
* fix(wisdom): require credential prefixes rather than matching skill names
* fix(wisdom): finish package checks before presenting sharing consent
* fix(wisdom): scan local skills before qualification cards
* fix(wisdom): update moderation results on existing sharing cards
* fix(wisdom): keep sharing review accessible from receipt cards
* fix(wisdom): align mediated review cards and collapsible checks
* fix(wisdom): clarify clean security summary wording
* fix(wisdom): normalize consent plans and add explicit recheck
* fix(wisdom): keep install and update receipts concise
* fix(wisdom): collapse assessments and deduplicate operation cards
* fix(wisdom): restore private Portal review from native cards
* fix(wisdom): sync Portal publication to original consent card
* fix(wisdom): show local skill version on sharing cards
* fix(wisdom): skip agent recommendations for self-published versions
* fix(wisdom): simplify candidate notices and local-edit recovery copy
* feat(wisdom): submit locally reviewed packages with one confirmation
* feat(wisdom): expose safe receipt and outcome sync recovery
* wisdom: onboarding notice says detect and share, names the user's own skill
Copy review from the product owner on the first and returning
qualification notices (fixed delivery mode):
- the feature blurb now says the org enabled detection *and sharing*
- both notices say the detected skill is one the user created
- both close with an exclamation mark
Applied identically to hermes_wisdom.notice, the desktop and web i18n
strings, and the tests that assert the sentences.
* wisdom: one opener, no approval line, ask to share after the skill is shown
Product owner review of the candidate card.
- The Hermes written card now opens with the same sentence as the fixed card
("Your organisation has enabled Collective Wisdom, a feature designed to
automatically detect and share useful skills across all team members.")
instead of its own blurb, so there is one first time message.
- "Nothing is shared without your approval." removed from Telegram, Slack
and Desktop. The buttons already make the permission explicit.
- "Would you like to share?" no longer appears before the skill is named.
It is now the last line, after the skill name, description, why suggested
and the checks, and reads "Would you like to share it?" (matching the
agent led template wording).
Tests updated for the new order; proposalNotice removed from all desktop locales.
* wisdom: American spelling, organization
Product owner decision: user facing copy uses American spelling.
Changes "Your organisation" to "Your organization" in the chat notice,
the Hermes written card opener, the desktop and web strings, and the
tests that assert them. Identifiers such as nas_organisation:* and the
German and French locales are untouched.
* wisdom: candidate card copy round 4 (owner review)
Apply the product owner's round 4 copy decisions to the Hermes Collective
Wisdom candidate card on Telegram, Slack, Desktop and the shared views:
1. Hermes-written cards are titled "Hermes Collective Wisdom" instead of
the bare "Collective Wisdom".
2. The "Reusable skill ready to review" line is gone from the candidate
card (Telegram rich card and plain fallback, legacy agent-led share
template).
3. The skill name and description are labelled: "Skill name: <name>" and
"What it does: <description>" (Telegram, Slack, Desktop).
4. "Why suggested:" is now "Why others might benefit:".
5. A passing professionalism review reads "Safe to share at work ✓ (no
inappropriate content found)" with no per-check bullets and no "Pass";
a failed review reads "Needs a look before sharing at work (possible
inappropriate content)" and lists only the checks that flagged
something. Pending/unavailable wording is unchanged.
6. Telegram button toasts: "Will ask later...", "Preparing more
details...", "Sharing...".
7. Qualification reasons: "You used this skill consistently across many
days." and "You've really refined this skill."
8. prompts/wisdom_candidate_review.md asks for a compelling
editorial_name, a simple one_line_description and a compelling
why_coworkers_benefit under 300 characters; "Be concise and
convincing." becomes "Be concise and compelling: the goal is that the
user wants to share it."
Tests updated for the new strings; review_text() gains direct coverage.
* wisdom: re-apply owner copy after rebase
- Native share cards (advice_view/interaction_view): drop the approval line, ask "Would you like to share it?" as the last line after the checks
- Hermes-written completion card titled "Hermes Collective Wisdom"
- Qualification reasons use the owner wording (consistently across many days / really refined)
- American spelling (organization) in remaining English copy
- Desktop test asserts the current Share button; web test matches the returning notice
* fix(wisdom): pin reconciled Gateway and verify Unicode hash vectors
Pin Gateway 60cd2d6b613ae3cd4a6e65155d1142006d907e78 and byte-identical producer artifacts. Verify every content-order case and package-manifest binding. Validation: 186 focused Python tests, Ruff and contract verifier.
* fix(wisdom): reconcile optional SDK tests and frontend lint
* fix(wisdom): default to agent-written notification summaries
* fix(wisdom): restore deferred install review and browse controls
* feat(wisdom): inspect installed setup with exact package provenance
* feat(wisdom): run native-approved installed setup steps with durable evidence
* fix(wisdom): recover interrupted setup with explicit native consent
* feat(wisdom): hand native installs into guided setup review
* fix(wisdom): continue requested setup with fixed notification copy
* fix(wisdom): preserve setup while waiting for a session model
* fix(wisdom): expose canonical setup review controls on desktop
* fix(wisdom): resume setup after recorded automatic updates
* fix(wisdom): make missing setup prerequisites recheckable
* chore(wisdom): align Agent with verified Gateway contract
* fix(wisdom): stop guessing team slugs in portal links
* fix(wisdom): retire pending advice on account sign-out
* fix(wisdom): cancel advice after terminal account revocation
* fix(wisdom): fence feed responses across account sign-out
* fix(wisdom): checkpoint signed-out feed before reactivation
* fix(wisdom): link proactive advice to scoped notification settings
* fix(wisdom): coalesce queued publication recommendations by version
* fix(wisdom): keep package review navigation local and deferable
* fix(wisdom): reflect installed state in discovery controls
* fix(wisdom): show exact checks before command confirmation
* chore(wisdom): pin bounded analytics privacy contract
* chore(wisdom): pin retired legacy notification contract
* feat(wisdom): review publisher usage with exact sharing copy
* fix(wisdom): align discovery and review check summaries
* fix(wisdom): show expired consent before confirmation
* fix(wisdom): require fresh review for legacy install controls
* fix(wisdom): preserve review expiry across check toggles
* fix(wisdom): retain update policy in native install reviews
* fix(wisdom): surface failed native card edits
* fix(wisdom): persist local command approval reviews
* fix(wisdom): use saved approvals for messaging commands
* test(wisdom): provide scan result in setup handoff fixture
* test(wisdom): exercise Telegram approvals with saved review state
* fix(wisdom): retain suppression policy for offline deferral
* fix(wisdom): reconsider candidates after deferred suppression expires
* fix(wisdom): bind review checks and report verified readiness separately
* fix(wisdom): persist accepted publication intent and recover exact outcomes
* fix(sync): pin UTF-8 tree ordering across writers
* chore(wisdom): pin organisation-scoped Gateway authorization
* fix(wisdom): restrict consent delivery to user-facing sessions
* chore(wisdom): refresh reviewed Gateway contract pin
* fix(wisdom): preserve kept tools in Blank Slate exclusions
* test(auth): reset anonymous fixture with a profile-scoped cache
* fix(wisdom): gate local surfaces and work on current profile entitlement
* fix(wisdom): invalidate quiet tool cache on entitlement changes
* test(wisdom): authorize local consent gateway fixtures
* fix(wisdom): keep entitlement decoding free of native crypto imports
* test(wisdom): provide local entitlement to demo CLI subprocess
* ci: leave upstream workflow unchanged in Wisdom PR
* fix(wisdom): ship package and contracts in Nix wheels
---------
Co-authored-by: hbizi <36184542+hbizi@users.noreply.github.com>
330 lines
14 KiB
Python
330 lines
14 KiB
Python
"""Skills Hub data models, path validators, and SKILL.md helpers. Leaf module (no imports from
|
|
tools.skills_hub) so every source adapter module can import it at top level without cycles."""
|
|
|
|
import json
|
|
import logging
|
|
import re
|
|
from abc import ABC, abstractmethod
|
|
from dataclasses import dataclass, field
|
|
from pathlib import PurePosixPath
|
|
from typing import Any, Callable, Dict, Iterable, List, Optional, Union
|
|
from urllib.parse import unquote, urlsplit
|
|
|
|
import httpx
|
|
import yaml
|
|
|
|
logger = logging.getLogger("tools.skills_hub")
|
|
|
|
|
|
def hub():
|
|
"""``tools.skills_hub`` resolved at call time: its cache / HTTP / index helpers are the test-patch targets
|
|
(``patch("tools.skills_hub._read_index_cache")`` ...), so adapters look them up on every call, not at import."""
|
|
import tools.skills_hub as mod
|
|
return mod
|
|
|
|
|
|
@dataclass
|
|
class SkillMeta:
|
|
"""Minimal metadata returned by search results."""
|
|
name: str
|
|
description: str
|
|
source: str # "official", "github", "clawhub", "lobehub"
|
|
identifier: str # source-specific ID (e.g. "openai/skills/skill-creator")
|
|
trust_level: str # "builtin" | "trusted" | "community"
|
|
repo: Optional[str] = None
|
|
path: Optional[str] = None
|
|
tags: List[str] = field(default_factory=list)
|
|
extra: Dict[str, Any] = field(default_factory=dict)
|
|
editorial_name: Optional[str] = None
|
|
editorial_description: Optional[str] = None
|
|
|
|
|
|
@dataclass
|
|
class SkillBundle:
|
|
"""A downloaded skill ready for quarantine/scanning/installation."""
|
|
name: str
|
|
files: Dict[str, Union[str, bytes]] # relative_path -> file content
|
|
source: str
|
|
identifier: str
|
|
trust_level: str
|
|
metadata: Dict[str, Any] = field(default_factory=dict)
|
|
|
|
|
|
def _skill_meta_to_dict(meta: SkillMeta) -> dict:
|
|
return dict(vars(meta))
|
|
|
|
|
|
def _cached_metas(key: str) -> Optional[List[SkillMeta]]:
|
|
"""SkillMeta list from the shared index cache, or None on miss/expiry."""
|
|
cached = hub()._read_index_cache(key)
|
|
return None if cached is None else [SkillMeta(**item) for item in cached]
|
|
|
|
|
|
def _cache_metas(key: str, metas: List[SkillMeta]) -> None:
|
|
hub()._write_index_cache(key, [_skill_meta_to_dict(m) for m in metas])
|
|
|
|
|
|
def _memo_json(key: str, compute: Callable[[], Any], valid: Callable[[Any], bool] = lambda c: c is not None) -> Any:
|
|
"""Shared-index-cache memo: a cached value passing ``valid`` is returned as-is; otherwise ``compute()``
|
|
runs and a non-None result is written back."""
|
|
cached = hub()._read_index_cache(key)
|
|
if valid(cached):
|
|
return cached
|
|
data = compute()
|
|
if data is not None:
|
|
hub()._write_index_cache(key, data)
|
|
return data
|
|
|
|
|
|
def _get_json(url: str, *, timeout: int = 20, **kwargs) -> Optional[Any]:
|
|
"""Plain (unguarded) GET + JSON decode; None on non-200 or transport/decode error."""
|
|
try:
|
|
resp = httpx.get(url, timeout=timeout, **kwargs)
|
|
return resp.json() if resp.status_code == 200 else None
|
|
except (httpx.HTTPError, json.JSONDecodeError):
|
|
return None
|
|
|
|
|
|
def _get_text(url: str, *, timeout: int = 20, **kwargs) -> Optional[str]:
|
|
"""Plain (unguarded) GET; body text on 200, None on any other status or transport error."""
|
|
try:
|
|
resp = httpx.get(url, timeout=timeout, **kwargs)
|
|
except httpx.HTTPError:
|
|
return None
|
|
return resp.text if resp.status_code == 200 else None
|
|
|
|
|
|
def _matches_query(query_lower: str, *fields: Any) -> bool:
|
|
"""Case-insensitive substring match against joined fields (lists space-joined; empty query matches all)."""
|
|
parts = [" ".join(str(t) for t in f) if isinstance(f, list) else str(f) for f in fields]
|
|
return query_lower in " ".join(parts).lower()
|
|
|
|
|
|
def _first_matching(query_lower: str, items: Iterable[Any], fields_of: Callable[[Any], tuple],
|
|
to_meta: Callable[[Any], Optional[SkillMeta]], limit: int) -> List[SkillMeta]:
|
|
"""Substring-search ``items`` in order, converting hits with ``to_meta`` until ``limit``."""
|
|
results: List[SkillMeta] = []
|
|
for item in items:
|
|
if _matches_query(query_lower, *fields_of(item)) and (meta := to_meta(item)):
|
|
results.append(meta)
|
|
if len(results) >= limit:
|
|
break
|
|
return results
|
|
|
|
|
|
TRUST_RANK = {"builtin": 2, "trusted": 1, "community": 0}
|
|
|
|
|
|
def _dedupe_by_trust(results: Iterable[SkillMeta]) -> List[SkillMeta]:
|
|
"""Dedupe by identifier, keeping the higher-trust copy (first wins on ties). identifier is unique per
|
|
skill; name is not — two taps can publish same-named skills, and browse-sh reuses task names across sites."""
|
|
seen: Dict[str, SkillMeta] = {}
|
|
for r in results:
|
|
kept = seen.get(r.identifier)
|
|
if kept is None or TRUST_RANK.get(r.trust_level, 0) > TRUST_RANK.get(kept.trust_level, 0):
|
|
seen[r.identifier] = r
|
|
return list(seen.values())
|
|
|
|
|
|
class SkillSource(ABC):
|
|
"""Abstract base for all skill registry adapters. ``SOURCE_ID`` is the unique source id (e.g. 'github',
|
|
'clawhub'); ``TRUST_LEVEL`` the trust every identifier gets unless ``trust_level_for`` is overridden."""
|
|
|
|
SOURCE_ID: str = ""
|
|
TRUST_LEVEL: str = "community"
|
|
|
|
@abstractmethod
|
|
def search(self, query: str, limit: int = 10) -> List[SkillMeta]:
|
|
"""Search for skills matching a query string."""
|
|
|
|
@abstractmethod
|
|
def fetch(self, identifier: str) -> Optional[SkillBundle]:
|
|
"""Download a skill bundle by identifier."""
|
|
|
|
@abstractmethod
|
|
def inspect(self, identifier: str) -> Optional[SkillMeta]:
|
|
"""Fetch metadata for a skill without downloading all files."""
|
|
|
|
def source_id(self) -> str:
|
|
return self.SOURCE_ID
|
|
|
|
def trust_level_for(self, identifier: str) -> str:
|
|
return self.TRUST_LEVEL
|
|
|
|
|
|
class GuardedFetchMixin:
|
|
"""SSRF/policy-guarded GETs, routed through ``tools.skills_hub`` (test-patchable)."""
|
|
|
|
@staticmethod
|
|
def _fetch_text(url: str) -> Optional[str]:
|
|
resp = hub()._guarded_http_get(url, timeout=20)
|
|
return resp.text if resp is not None and resp.status_code == 200 else None
|
|
|
|
@staticmethod
|
|
def _fetch_bytes(url: str) -> Optional[bytes]:
|
|
resp = hub()._guarded_http_get(url, timeout=20)
|
|
return resp.content if resp is not None and resp.status_code == 200 else None
|
|
|
|
|
|
# --- SKILL.md frontmatter ---------------------------------------------------
|
|
def _parse_frontmatter(content: str) -> dict:
|
|
"""Parse YAML frontmatter from SKILL.md content ({} when absent/invalid)."""
|
|
content = content.lstrip("\ufeff") # tolerate UTF-8 BOM (Windows editors)
|
|
match = re.search(r'\n---\s*\n', content[3:]) if content.startswith("---") else None
|
|
if not match:
|
|
return {}
|
|
try:
|
|
parsed = yaml.safe_load(content[3:match.start() + 3])
|
|
return parsed if isinstance(parsed, dict) else {}
|
|
except yaml.YAMLError:
|
|
return {}
|
|
|
|
|
|
def _hermes_tags(fm: dict) -> Any:
|
|
"""``metadata.hermes.tags`` from parsed frontmatter, or ``[]`` (unvalidated type)."""
|
|
metadata = fm.get("metadata", {})
|
|
hermes_meta = metadata.get("hermes", {}) if isinstance(metadata, dict) else None
|
|
return hermes_meta.get("tags", []) if isinstance(hermes_meta, dict) else []
|
|
|
|
|
|
def source_url_for_bundle(bundle: SkillBundle) -> str:
|
|
"""Best available human-facing immutable-source provenance URL."""
|
|
explicit = bundle.metadata.get("source_url") or bundle.metadata.get("url")
|
|
if explicit:
|
|
return str(explicit)
|
|
if bundle.source == "github":
|
|
parts = bundle.identifier.split("/", 2)
|
|
if len(parts) >= 2:
|
|
suffix = f"/tree/main/{parts[2]}" if len(parts) == 3 else ""
|
|
return f"https://github.com/{parts[0]}/{parts[1]}{suffix}"
|
|
return bundle.identifier
|
|
|
|
|
|
# --- Bundle path validation -------------------------------------------------
|
|
def _normalize_bundle_path(path_value: str, *, field_name: str, allow_nested: bool) -> str:
|
|
"""Normalize and validate bundle-controlled paths before touching disk."""
|
|
if not isinstance(path_value, str):
|
|
raise ValueError(f"Unsafe {field_name}: expected a string")
|
|
raw = path_value.strip()
|
|
if not raw:
|
|
raise ValueError(f"Unsafe {field_name}: empty path")
|
|
normalized = raw.replace("\\", "/")
|
|
path = PurePosixPath(normalized)
|
|
parts = [part for part in path.parts if part not in {"", "."}]
|
|
# A colon in any component is rejected: on Windows it marks a drive (``C:foo``) or an NTFS Alternate Data
|
|
# Stream (``file.py:payload`` writes scanner-invisible bytes); ``/`` is the only legal separator once normalized.
|
|
if (normalized.startswith("/") or path.is_absolute() or not parts or any(part == ".." for part in parts)
|
|
or any(":" in part for part in parts) or (not allow_nested and len(parts) != 1)):
|
|
raise ValueError(f"Unsafe {field_name}: {path_value}")
|
|
return "/".join(parts)
|
|
|
|
|
|
def _validate_skill_name(name: str) -> str:
|
|
return _normalize_bundle_path(name, field_name="skill name", allow_nested=False)
|
|
|
|
|
|
def _validate_install_parent_path(category: str) -> str:
|
|
return _normalize_bundle_path(category, field_name="install parent path", allow_nested=True)
|
|
|
|
|
|
def _validate_bundle_rel_path(rel_path: str) -> str:
|
|
return _normalize_bundle_path(rel_path, field_name="bundle file path", allow_nested=True)
|
|
|
|
|
|
def _normalize_lock_install_path(install_path: str, skill_name: str) -> str:
|
|
"""Validate a lock-file ``install_path`` (the ``uninstall_skill`` rmtree target).
|
|
|
|
Must be relative, traversal-free, and end with ``<skill_name>`` — nested official skills legitimately
|
|
live at ``mlops/training/<skill_name>``; an empty/``"."``/absolute/mismatched entry could point rmtree
|
|
at the whole ``skills/`` tree or outside it.
|
|
"""
|
|
safe_skill_name = _validate_skill_name(skill_name)
|
|
normalized = _normalize_bundle_path(install_path, field_name="install path", allow_nested=True)
|
|
if normalized.split("/")[-1] != safe_skill_name:
|
|
raise ValueError(f"Unsafe install path: {install_path}")
|
|
return normalized
|
|
|
|
|
|
# --- Referenced support-file extraction from SKILL.md -----------------------
|
|
_ALLOWED_SUPPORT_DIRS = frozenset({"references", "templates", "scripts", "assets", "examples"})
|
|
_LOCAL_LINK_RE = re.compile(
|
|
r"(?:\]\(|`|(?:^|[\s\"']))((?:references|templates|scripts|assets|examples)/[^\s)`\"'<>]+)", re.MULTILINE)
|
|
_SUSPICIOUS_LOCAL_REF_RE = re.compile(
|
|
r"(?:references|templates|scripts|assets|examples)/(?:[^\s)`\"'<>]*/)?\.\.(?:/|$)")
|
|
_VALUELESS_QUERY_FLAG_RE = re.compile(r"(?:[A-Za-z0-9_~-]|%[0-9A-Fa-f]{2})+\Z")
|
|
# Same-directory links (``](./FILE.ext)`` / ``](FILE.ext)``): siblings of SKILL.md the document links
|
|
# explicitly (e.g. ./CONTEXT-FORMAT.md). Dropping them made the install "succeed" with unresolved links.
|
|
# The extension requirement keeps prose words out; support-dir links stay on _LOCAL_LINK_RE.
|
|
# Skills legitimately ship supporting docs next to SKILL.md instead of under a support directory (e.g.
|
|
# mattpocock/skills' domain-modeling links ./CONTEXT-FORMAT.md); dropping them made the install "succeed"
|
|
# while the bundle came out with unresolved links (#96310).
|
|
_SAMEDIR_LINK_RE = re.compile(r"\]\(([^)\s\"'<>]+)")
|
|
_SAMEDIR_NAME_RE = re.compile(r"^(?:\./)?[A-Za-z0-9][A-Za-z0-9._-]*$")
|
|
|
|
|
|
def _query_is_concrete(query: str) -> bool:
|
|
"""Whether a URL query is real URL syntax rather than glob prose.
|
|
|
|
A non-empty ``key=value`` part is always concrete. Valueless flags are accepted only when RFC 3986
|
|
unreserved-token shaped (percent escapes ok); ``.``, brackets and extra ``?`` are excluded because
|
|
``?x.md`` / ``?.md`` is indistinguishable from a single-char glob finishing a filename in prose.
|
|
"""
|
|
return all(("=" in part and bool(part.split("=", 1)[0])) or bool(_VALUELESS_QUERY_FLAG_RE.fullmatch(part))
|
|
for part in query.split("&"))
|
|
|
|
|
|
def _referenced_support_paths(skill_md: str) -> Optional[set[str]]:
|
|
"""Extract safe referenced paths; return None on a traversal attempt (fail closed)."""
|
|
normalized = skill_md.replace("\\", "/")
|
|
if _SUSPICIOUS_LOCAL_REF_RE.search(normalized):
|
|
return None
|
|
paths: set[str] = set()
|
|
for match in _LOCAL_LINK_RE.finditer(normalized):
|
|
candidate = match.group(1).rstrip(".,;:")
|
|
parsed = urlsplit(candidate)
|
|
raw = unquote(parsed.path)
|
|
if (candidate.endswith("?") or any(char in raw for char in "*?[]")
|
|
or (parsed.query and not _query_is_concrete(parsed.query))):
|
|
continue
|
|
try:
|
|
safe = _validate_bundle_rel_path(raw)
|
|
except ValueError:
|
|
return None
|
|
if safe.split("/", 1)[0] in _ALLOWED_SUPPORT_DIRS:
|
|
# Prose placeholders (``references/type-<name>.md``, truncated at ``<`` to
|
|
# ``references/type-``) are instructions, not files: a basename ending in a
|
|
# separator is skipped. No extension requirement — ``references/LICENSE`` is legitimate.
|
|
base = safe.rsplit("/", 1)[-1]
|
|
if re.search(r"[*?<>]", safe) or not re.search(r"[A-Za-z0-9]$", base):
|
|
continue
|
|
paths.add(safe)
|
|
for match in _SAMEDIR_LINK_RE.finditer(normalized):
|
|
raw = match.group(1).rstrip(".,;:")
|
|
# Canonicalize like the support-dir branch (drop query/fragment, percent-decode), strip leading ``./``.
|
|
name = unquote(urlsplit(raw).path)
|
|
name = name[2:] if name.startswith("./") else name
|
|
# External URLs, anchors, mailto and site-absolute targets are not same-directory file links.
|
|
if not name or "://" in raw or raw.startswith(("mailto:", "#", "/")):
|
|
continue
|
|
if name.startswith(".."):
|
|
return None
|
|
# Only unambiguous file links: an extension, no internal slash, never SKILL.md itself (casefolded —
|
|
# a ``skill.md`` entry would collide with the bundle root on macOS/Windows; skipped, not merged).
|
|
if ("/" in name or name.casefold() == "skill.md" or "." not in name.lstrip(".")
|
|
or not _SAMEDIR_NAME_RE.match(name)):
|
|
continue
|
|
try:
|
|
safe = _validate_bundle_rel_path(name)
|
|
except ValueError:
|
|
return None
|
|
paths.add(safe)
|
|
# Case-folded collisions among accepted same-dir names (``A.md`` + ``a.md``)
|
|
# would collide on install — drop the pair rather than guess.
|
|
folded: dict[str, list[str]] = {}
|
|
for p in sorted(paths):
|
|
folded.setdefault(p.casefold(), []).append(p)
|
|
for group in folded.values():
|
|
if len(group) > 1:
|
|
paths.difference_update(group)
|
|
return paths
|