88import logging
99import mimetypes
1010import re
11+ from bisect import bisect_left
1112from collections .abc import Callable , Mapping , Sequence
1213from pathlib import PurePosixPath
1314from typing import Any , Literal , Self , TypeVar
@@ -179,8 +180,8 @@ async def load(
179180 if ttl_ms < 0 :
180181 raise ValueError ("ttl_ms must not be negative" )
181182 paths = _check_paths (list (await provider .list_files ()))
182- visible = [ path for path in paths if not any (segment .startswith ("." ) for segment in path .split ("/" ))]
183- skill_paths = sorted ( path for path in visible if path .split ("/" )[- 1 ] == _SKILL_FILE )
183+ visible = sorted ( path for path in paths if not any (segment .startswith ("." ) for segment in path .split ("/" )))
184+ skill_paths = [ path for path in visible if path .split ("/" )[- 1 ] == _SKILL_FILE ]
184185
185186 skills : dict [str , Skill ] = {}
186187 served : set [str ] = set ()
@@ -312,6 +313,15 @@ def _check_paths(paths: list[str]) -> list[str]:
312313 return paths
313314
314315
316+ def _paths_under (sorted_paths : Sequence [str ], prefix : str ) -> list [str ]:
317+ """Return the paths that start with `prefix`; they are contiguous in sorted order, so no full scan is needed."""
318+ start = bisect_left (sorted_paths , prefix )
319+ end = start
320+ while end < len (sorted_paths ) and sorted_paths [end ].startswith (prefix ):
321+ end += 1
322+ return list (sorted_paths [start :end ])
323+
324+
315325def _fingerprint (data : bytes ) -> _Fingerprint :
316326 return _Fingerprint (digest = hashlib .sha256 (data ).hexdigest (), size = len (data ))
317327
@@ -321,7 +331,7 @@ async def _load_skill(
321331 parse_frontmatter : Callable [[str ], Mapping [str , Any ]],
322332 skill_path : str ,
323333 skill_md : bytes ,
324- visible : Sequence [str ],
334+ sorted_visible : Sequence [str ],
325335 fingerprints : dict [str , _Fingerprint ],
326336) -> tuple [Skill , list [str ]]:
327337 """Build the `Skill` whose `SKILL.md` is `skill_path`, along with the paths of its files.
@@ -331,7 +341,7 @@ async def _load_skill(
331341 """
332342 frontmatter = _parse_frontmatter (skill_md , parse_frontmatter )
333343 root = skill_path .removesuffix (_SKILL_FILE )
334- skill_files = [ path for path in visible if path . startswith ( root )]
344+ skill_files = _paths_under ( sorted_visible , root )
335345 for path in skill_files :
336346 if path not in fingerprints :
337347 fingerprints [path ] = _fingerprint (await provider .read_file (path ))
0 commit comments