skills_tool_dedup.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """skill_view repeat-view dedup registry: per-task cache of (resolved skill name, file_path) ->
  2. digest of the skill_view result served. A repeat view whose result is byte-identical returns a short
  3. stub — the earlier tool result already carries the content verbatim. Content digests need no file
  4. timestamps, so a same-size rewrite in one coarse mtime tick (or on a host whose clock disagrees with
  5. the filesystem's) is never mistaken for "unchanged". Cleared via ``reset_skill_view_dedup()`` on
  6. context compression AND on a committed proactive tool-result prune, because both replace the
  7. original content with a one-line marker.
  8. """
  9. import hashlib
  10. import json
  11. import threading
  12. _skill_view_tracker: dict[str, dict[tuple, str]] = {}
  13. _skill_view_tracker_lock = threading.Lock()
  14. _SKILL_VIEW_DEDUP_CAP = 200
  15. _SKILL_VIEW_DEDUP_MESSAGE = (
  16. "Skill content unchanged since it was loaded earlier in this "
  17. "conversation — refer to the earlier skill_view result; it is still "
  18. "current and complete. (Re-issued after context compression, this "
  19. "returns the full content again.)")
  20. def dedup_skill_view(task_id, name, file_path, payload: dict, result: str) -> str | None:
  21. """The "unchanged" stub when this task was already served exactly ``result`` for this skill
  22. file; otherwise record ``result``'s digest and return None (serve the full result)."""
  23. # Never dedup setup-needed views: readiness depends on config/env state that
  24. # changes without the file changing; the model must see the refreshed status.
  25. if (not task_id or payload.get("setup_needed")
  26. or payload.get("readiness_status") == "setup_needed"):
  27. return None
  28. resolved = str(payload.get("name") or name)
  29. key = (resolved, file_path or "")
  30. digest = hashlib.sha256(result.encode("utf-8")).hexdigest()
  31. with _skill_view_tracker_lock:
  32. cache = _skill_view_tracker.setdefault(str(task_id), {})
  33. if cache.get(key) == digest:
  34. return json.dumps({
  35. "success": True, "status": "unchanged", "name": resolved,
  36. "file": file_path or "SKILL.md", "dedup": True, "content_returned": False,
  37. "message": _SKILL_VIEW_DEDUP_MESSAGE}, ensure_ascii=False)
  38. cache.pop(key, None) # re-insert at the end: FIFO eviction keeps the recently served
  39. cache[key] = digest
  40. while len(cache) > _SKILL_VIEW_DEDUP_CAP: # FIFO eviction
  41. del cache[next(iter(cache))]
  42. return None
  43. def reset_skill_view_dedup(task_id: str | None = None) -> None:
  44. """Clear the dedup cache (all tasks when task_id is None); called on context compression."""
  45. with _skill_view_tracker_lock:
  46. if task_id is None:
  47. _skill_view_tracker.clear()
  48. else:
  49. _skill_view_tracker.pop(str(task_id), None)