Files
hermes-agent/hermes_wisdom/client.py
T
shannonsands a6ee31f55a feat(wisdom): add Hermes Collective Wisdom Agent V1 (#94266)
* 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>
2026-09-11 19:04:06 +10:00

888 lines
30 KiB
Python

"""Bounded, schema-validated Gateway client for Collective Wisdom."""
from __future__ import annotations
import base64
import json
import logging
import re
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Literal
from urllib.parse import quote
import requests
from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, ValidationError, model_validator
from tools.skills_sync_client import (
ObjectSet,
SyncClient,
)
from tools.skills_sync_client import (
resolve_identity,
resolve_sync_base_url,
)
from tools.skills_sync_client_wire import KIND_BLOB, KIND_COMMIT, KIND_TREE, wire_address
from .contract import ContentFile, SystemSpecification, parse_manifest_bytes
from .package import PackagePolicyError, verify_content_files
from .client_delivery import (
ClientDeliveryClaim,
ClientDeliveryResponse,
Identifier,
receipt_projection,
)
from .delivery import DeliveryReceipt
from .client_outcome import ClientOperationOutcome, ClientOperationResponse
logger = logging.getLogger(__name__)
class WisdomError(RuntimeError):
exit_code = 8
def __init__(
self, message: str, *, status: int | None = None, code: str | None = None
):
super().__init__(message)
self.status = status
self.code = code
class WisdomAuthError(WisdomError):
exit_code = 3
class WisdomNotFound(WisdomError):
exit_code = 4
class WisdomConflict(WisdomError):
exit_code = 5
class WisdomValidationError(WisdomError):
exit_code = 6
class WireModel(BaseModel):
model_config = ConfigDict(extra="allow")
class AgentLedNotificationDefaults(BaseModel):
model_config = ConfigDict(strict=True, extra="forbid")
skill_ready_to_share: bool
teammate_published: bool
update_available: bool
class AgentLedPolicyResponse(BaseModel):
model_config = ConfigDict(strict=True, extra="ignore")
org_id: str = Field(min_length=1)
usage_evidence_window_days: int = Field(ge=1, le=90)
min_aggregate_invocations: int = Field(ge=1, le=10_000)
consecutive_day_usage_counts: bool
repeated_edits_count: bool
max_recommendations_per_user_per_week: int = Field(ge=0, le=100)
publication_mode: Literal["open", "moderated", "managed"]
install_popularity_threshold: int = Field(ge=1, le=100_000)
notification_defaults: AgentLedNotificationDefaults
manager_review_email_cadence: Literal["immediate", "daily"]
not_now_suppression_days: int = Field(ge=1, le=365)
version: int = Field(ge=1)
updated_by_user_id: str | None
class WisdomSuppression(BaseModel):
model_config = ConfigDict(strict=True, extra="forbid")
key: str = Field(pattern=r"^sha256:[a-f0-9]{64}$")
suppress_until: str
class WisdomSuppressionResponse(WisdomSuppression):
org_id: str
class WisdomSuppressionList(BaseModel):
model_config = ConfigDict(strict=True, extra="forbid")
org_id: str
suppressions: list[WisdomSuppression] = Field(max_length=100)
class WisdomMuteResponse(BaseModel):
model_config = ConfigDict(strict=True, extra="forbid")
org_id: str
muted: bool
duration: Literal["1_day", "1_week", "30_days", "forever"] | None
muted_until: str | None
forever: bool
revision: int = Field(default=0, ge=0)
mutation_id: str | None = None
updated_at: str | None = None
class Draft(WireModel):
id: str
supersedesDraftId: str | None = None
orgId: str
ownerUserId: str
slug: str
draftCommit: str
contentHash: str
authorDescription: str | None
authorDescriptionHash: str | None
state: Literal[
"vetting",
"ready",
"owner_approved",
"publishing",
"pending_moderation",
"changes_requested",
"published",
"declined",
"invalidated",
]
moderationNote: str | None = None
moderationDeciderUserId: str | None = None
moderationDecidedAt: str | None = None
packageManifestHash: str | None
packageManifestSchemaVersion: int | None
systemSpec: SystemSpecification | None
scan: dict[str, Any] | None
scanVerdict: str | None
security_check: dict[str, Any] | None = None
professionalism_check: dict[str, Any] | None = None
explanation: str | None
updatedAt: str
@model_validator(mode="after")
def require_return_metadata(self) -> Draft:
if self.state == "changes_requested" and (
not self.moderationNote
or not self.moderationDeciderUserId
or not self.moderationDecidedAt
):
raise ValueError(
"changes_requested drafts require complete moderator return metadata"
)
return self
class DraftDetail(WireModel):
draft: Draft
effective_policy: dict[str, Any]
class DraftResponse(WireModel):
draft: Draft
class DraftList(WireModel):
drafts: list[Draft]
class SkillSummary(WireModel):
id: str
slug: str
state: str
created_by_user_id: str
latest_version: int | None
author_description: str | None
verified_facts: dict[str, Any] | None
explanation: str | None
install_count: int
takedown_generation: int
system_spec: SystemSpecification | None
security_check: dict[str, Any] | None = None
professionalism_check: dict[str, Any] | None = None
class SkillList(WireModel):
skills: list[SkillSummary]
next_cursor: str | None
class SkillDetail(WireModel):
skill: dict[str, Any]
versions: list[dict[str, Any]]
class VersionDetail(WireModel):
skill: dict[str, Any]
version: dict[str, Any]
class VersionContent(WireModel):
commit: str
content_hash: str
files: list[dict[str, Any]]
class InstallationRecord(WireModel):
installed_version: int = Field(gt=0)
effective_update_mode: Literal["MANUAL", "AUTO_WITH_NOTICE", "REQUIRED"]
class InstallationItem(WireModel):
skill_id: str
installed_version: int = Field(gt=0)
latest_version: int | None = Field(default=None, gt=0)
update_mode: Literal["MANUAL", "AUTO_WITH_NOTICE", "REQUIRED"]
skill_state: str
takedown_generation: int | None = Field(default=None, ge=0)
class InstallationList(WireModel):
installations: list[InstallationItem]
class InstallationDeactivation(WireModel):
skill_id: str
installation_id: str
state: Literal["inactive"]
class FeedEvent(WireModel):
event_id: str
kind: Literal[
"new",
"updated",
"archived",
"taken_down",
"restored",
"installed",
"installation_updated",
"uninstalled",
]
skill_id: str
version: int | None = Field(default=None, gt=0)
takedown_generation: int | None = Field(default=None, ge=0)
installation_id: str | None
update_mode: Literal["MANUAL", "AUTO_WITH_NOTICE", "REQUIRED"] | None
occurred_at: datetime
class Feed(WireModel):
events: list[FeedEvent]
next_cursor: str
has_more: bool
@dataclass(frozen=True)
class ReconstructedDraft:
detail: DraftDetail
files: list[tuple[str, str, bytes]]
content_files: list[ContentFile]
content_hash: str
def _walk_private_commit(
sync: SyncClient, commit_hash: str
) -> list[tuple[str, str, bytes]]:
kind, body = sync.get_object(commit_hash)
if wire_address(body) != commit_hash or kind != KIND_COMMIT:
raise WisdomValidationError(
"owner-private draft commit failed integrity validation"
)
try:
commit = json.loads(body.decode("utf-8"))
tree_hash = str(commit["tree"])
except (
KeyError,
TypeError,
ValueError,
UnicodeDecodeError,
json.JSONDecodeError,
) as exc:
raise WisdomValidationError("owner-private draft commit is malformed") from exc
out: list[tuple[str, str, bytes]] = []
seen_nodes: set[tuple[str, str]] = set()
def walk(tree: str, prefix: str) -> None:
node_key = (tree, prefix)
if node_key in seen_nodes:
raise WisdomValidationError("owner-private draft contains a tree cycle")
seen_nodes.add(node_key)
node_kind, node_body = sync.get_object(tree)
if node_kind != KIND_TREE or wire_address(node_body) != tree:
raise WisdomValidationError(
"owner-private draft tree failed integrity validation"
)
try:
parsed = json.loads(node_body.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
raise WisdomValidationError(
"owner-private draft tree is malformed"
) from exc
entries = parsed.get("entries")
if not isinstance(entries, list):
raise WisdomValidationError("owner-private draft tree has no entries")
for entry in entries:
if not isinstance(entry, dict):
raise WisdomValidationError(
"owner-private draft tree entry is malformed"
)
name = entry.get("name")
address = entry.get("hash")
entry_kind = entry.get("kind")
if not isinstance(name, str) or not isinstance(address, str):
raise WisdomValidationError(
"owner-private draft tree entry is malformed"
)
path = f"{prefix}{name}"
if entry_kind == KIND_TREE:
walk(address, path + "/")
elif entry_kind == KIND_BLOB:
blob_kind, blob = sync.get_object(address)
if blob_kind != KIND_BLOB or wire_address(blob) != address:
raise WisdomValidationError(
f"draft blob failed integrity validation: {path}"
)
out.append((
path,
"exec" if entry.get("mode") == "exec" else "file",
blob,
))
else:
raise WisdomValidationError(f"unsupported draft object kind at {path}")
walk(tree_hash, "")
return out
class WisdomClient:
def __init__(self, *, timeout: float = 30.0) -> None:
identity = resolve_identity()
base = resolve_sync_base_url()
if not base:
raise WisdomAuthError("Collective Wisdom Gateway is not configured")
self.identity = identity
self.base = base.rstrip("/")
self.timeout = timeout
self.session = requests.Session()
self.session.headers.update({
"Authorization": f"Bearer {identity['api_key']}",
"Accept": "application/json",
})
self.sync = SyncClient(self.base, identity["api_key"], timeout=timeout)
@property
def display_scopes(self) -> tuple[str, ...]:
scopes = self.identity.get("claims", {}).get("wisdom_scopes")
return (
tuple(item for item in scopes if isinstance(item, str))
if isinstance(scopes, list)
else ()
)
@property
def display_org_id(self) -> str | None:
claims = self.identity.get("claims", {})
value = claims.get("org_id") or claims.get("orgId")
return str(value) if value else None
def _url(self, path: str) -> str:
return f"{self.base}/v1/sync/wisdom/{path.lstrip('/')}"
def _request(
self,
method: str,
path: str,
*,
model: type[BaseModel] | None = None,
json_body: dict[str, Any] | None = None,
params: dict[str, Any] | None = None,
) -> Any:
try:
response = self.session.request(
method,
self._url(path),
json=json_body,
params=params,
timeout=self.timeout,
)
except requests.Timeout as exc:
raise WisdomError("Collective Wisdom Gateway timed out") from exc
except requests.RequestException as exc:
raise WisdomError("Collective Wisdom Gateway is unavailable") from exc
body: Any = None
if response.content:
try:
body = response.json()
except ValueError as exc:
raise WisdomError(
"Collective Wisdom Gateway returned a malformed response"
) from exc
code = body.get("error") if isinstance(body, dict) else None
if response.status_code in (401, 403):
raise WisdomAuthError(
"Collective Wisdom is unavailable for this account",
status=response.status_code,
code=code,
)
if response.status_code == 404:
raise WisdomNotFound(
"Collective Wisdom item not found", status=404, code=code
)
if response.status_code == 409:
raise WisdomConflict(
str(code or "Collective Wisdom state changed; refresh and retry"),
status=409,
code=code,
)
if response.status_code == 422:
raise WisdomValidationError(
str(code or "Collective Wisdom rejected invalid content"),
status=422,
code=code,
)
if response.status_code < 200 or response.status_code >= 300:
raise WisdomError(
f"Collective Wisdom Gateway failed ({response.status_code})",
status=response.status_code,
code=code,
)
if model is None:
return body
try:
return model.model_validate(body)
except ValidationError as exc:
raise WisdomError(
"Collective Wisdom Gateway response failed schema validation"
) from exc
def capability(self) -> dict[str, Any]:
try:
response = self.session.get(
f"{self.base}/v1/sync/capabilities", timeout=self.timeout
)
response.raise_for_status()
body = response.json()
except (requests.RequestException, ValueError) as exc:
raise WisdomError("Gateway capabilities are unavailable") from exc
if "wisdom" not in (body.get("features") or []):
raise WisdomAuthError("Gateway does not advertise Collective Wisdom")
return body
def agent_led_policy(self) -> AgentLedPolicyResponse:
policy = self._request("GET", "agent-led/policy", model=AgentLedPolicyResponse)
if not self.display_org_id or policy.org_id != self.display_org_id:
raise WisdomError(
"Recommendation policy does not match the active organization"
)
return policy
def _delivery_identity(self) -> tuple[str, str]:
org = self.display_org_id
user = self.identity.get("owner")
if not org or not isinstance(user, str) or not user or user == "unknown":
raise WisdomAuthError("Notification delivery requires an active account")
return org, user
def _delivery_response(self, response, identity, claim, *, event_id=None):
if (
self._delivery_identity() != identity
or (response.org_id, response.recipient_user_id) != identity
or response.request_id != claim.request_id
or response.reference != claim.reference
or (event_id is not None and response.event_id != event_id)
):
raise WisdomError("Notification delivery response does not match the request")
return response
def claim_notification_delivery(self, request_id: str, reference: dict) -> ClientDeliveryResponse:
"""Caller persists request_id first; a replay never extends the send lease."""
identity = self._delivery_identity()
try:
claim = ClientDeliveryClaim(request_id=request_id, reference=reference)
except ValidationError as exc:
raise WisdomValidationError("Invalid notification delivery reference") from exc
response = self._request(
"POST", "agent-led/deliveries/claim", model=ClientDeliveryResponse,
json_body=claim.model_dump(mode="json"),
)
return self._delivery_response(response, identity, claim)
def settle_notification_delivery(
self, event_id: str, request_id: str, reference: dict, *,
outcome: Literal["acknowledged", "not_sent", "uncertain"],
receipt: DeliveryReceipt | None = None,
) -> ClientDeliveryResponse:
"""Reconcile a known local result without resending or granting consent."""
identity = self._delivery_identity()
try:
claim = ClientDeliveryClaim(request_id=request_id, reference=reference)
TypeAdapter(Identifier).validate_python(event_id, strict=True)
if outcome not in {"acknowledged", "not_sent", "uncertain"}:
raise ValueError("Unknown settlement")
if (outcome == "acknowledged") != (receipt is not None):
raise ValueError("Only acknowledgements require receipts")
body = {"request_id": request_id, "outcome": outcome}
if receipt is not None:
body["receipt"] = receipt_projection(receipt).model_dump(mode="json")
except (ValidationError, ValueError) as exc:
raise WisdomValidationError("Invalid notification delivery settlement") from exc
response = self._request(
"POST", f"agent-led/deliveries/{quote(event_id, safe='')}/settle",
model=ClientDeliveryResponse, json_body=body,
)
self._delivery_response(response, identity, claim, event_id=event_id)
if response.state != outcome:
raise WisdomError("Notification delivery settlement was not acknowledged")
return response
def _preference_org(self, response):
if not self.display_org_id or response.org_id != self.display_org_id:
raise WisdomError("Preference does not match the active organization")
return response
def report_operation_outcome(self, event_id: str, outcome: dict) -> ClientOperationResponse:
"""Sync a persisted local journal result. Never apply, publish or grant consent."""
identity = self._delivery_identity()
try:
TypeAdapter(Identifier).validate_python(event_id, strict=True)
report = ClientOperationOutcome.model_validate(outcome)
except ValidationError as exc:
raise WisdomValidationError("Invalid operation outcome") from exc
response = self._request(
"POST", f"agent-led/deliveries/{quote(event_id, safe='')}/outcomes",
model=ClientOperationResponse, json_body=report.model_dump(mode="json"),
)
if (
self._delivery_identity() != identity
or (response.org_id, response.recipient_user_id) != identity
or response.event_id != event_id
or response.outcome != report
):
raise WisdomError("Operation outcome response does not match the request")
return response
def suppress_recommendation(self, key: str) -> WisdomSuppressionResponse:
if not isinstance(key, str) or not re.fullmatch(r"sha256:[a-f0-9]{64}", key):
raise WisdomValidationError("Invalid suppression key")
return self._preference_org(
self._request(
"PUT",
f"agent-led/suppressions/{quote(key, safe='')}",
model=WisdomSuppressionResponse,
json_body={},
)
)
def recommendation_suppressions(self, keys: list[str]) -> list[WisdomSuppression]:
if len(keys) > 100 or len(set(keys)) != len(keys):
raise WisdomValidationError("Expected up to 100 distinct suppression keys")
for key in keys:
if not isinstance(key, str) or not re.fullmatch(
r"sha256:[a-f0-9]{64}", key
):
raise WisdomValidationError("Invalid suppression key")
result = self._preference_org(
self._request(
"POST",
"agent-led/suppressions/check",
model=WisdomSuppressionList,
json_body={"keys": keys},
)
)
if any(row.key not in keys for row in result.suppressions) or len({
row.key for row in result.suppressions
}) != len(result.suppressions):
raise WisdomError("Gateway returned unexpected suppression keys")
return result.suppressions
def recommendation_mute(self) -> WisdomMuteResponse:
return self._preference_org(
self._request(
"GET",
"agent-led/mute",
model=WisdomMuteResponse,
params={"include_revision": "1"},
)
)
def set_recommendation_mute(
self,
duration: str | None,
*,
expected_revision: int | None = None,
mutation_id: str | None = None,
requested_at: str | None = None,
) -> WisdomMuteResponse:
if duration not in {None, "1_day", "1_week", "30_days", "forever"}:
raise WisdomValidationError("Unsupported mute duration")
guarded = any(
value is not None
for value in (expected_revision, mutation_id, requested_at)
)
if guarded and (
type(expected_revision) is not int
or not 0 <= expected_revision < 2_147_483_647
or not mutation_id
or not requested_at
):
raise WisdomValidationError(
"Queued mute requires revision, mutation ID and request time"
)
payload = {"duration": duration}
if guarded:
payload.update(
expected_revision=expected_revision,
mutation_id=mutation_id,
requested_at=requested_at,
)
return self._preference_org(
self._request(
"DELETE" if duration is None and not guarded else "PUT",
"agent-led/mute",
model=WisdomMuteResponse,
json_body=payload if duration is not None or guarded else None,
)
)
def register_identity(self, installation_id: str) -> dict[str, Any]:
return self._request(
"POST",
"installation-identities",
json_body={"installation_id": installation_id},
)
def upload_private_objects(self, objects: ObjectSet) -> None:
self.sync.put_objects(objects.objects)
def submit_draft(
self,
*,
slug: str,
commit: str,
content_hash: str,
description: str,
professionalism_review: dict[str, Any] | None = None,
) -> Draft:
payload: dict[str, Any] = {
"slug": slug,
"draft_commit": commit,
"content_hash": content_hash,
"author_description": description,
}
if professionalism_review is not None:
payload["professionalism_review"] = professionalism_review
body = self._request(
"POST",
"drafts",
model=DraftResponse,
json_body=payload,
)
return body.draft
def list_drafts(self) -> list[Draft]:
return self._request("GET", "drafts", model=DraftList).drafts
def draft(self, draft_id: str) -> DraftDetail:
return self._request(
"GET", f"drafts/{quote(draft_id, safe='')}", model=DraftDetail
)
def reconstruct_draft(self, draft_id: str) -> ReconstructedDraft:
detail = self.draft(draft_id)
files = _walk_private_commit(self.sync, detail.draft.draftCommit)
records, content_hash = verify_content_files(files)
if content_hash != detail.draft.contentHash:
raise WisdomValidationError(
"server draft content does not match its authoritative hash"
)
return ReconstructedDraft(
detail=detail, files=files, content_files=records, content_hash=content_hash
)
def revise_draft(
self,
draft_id: str,
*,
commit: str,
content_hash: str,
description: str,
expected_content_hash: str,
expected_description_hash: str,
expected_manifest_hash: str,
professionalism_review: dict[str, Any] | None = None,
) -> Draft:
"""Create a newly vetted successor for an immutable owner draft."""
payload: dict[str, Any] = {
"draft_commit": commit,
"content_hash": content_hash,
"author_description": description,
"expected_content_hash": expected_content_hash,
"expected_author_description_hash": expected_description_hash,
"expected_package_manifest_hash": expected_manifest_hash,
}
if professionalism_review is not None:
payload["professionalism_review"] = professionalism_review
body = self._request(
"POST",
f"drafts/{quote(draft_id, safe='')}/revise",
json_body=payload,
)
return Draft.model_validate(body.get("draft", body))
def approve(
self,
draft_id: str,
*,
content_hash: str,
description_hash: str,
manifest_hash: str,
) -> Draft:
body = self._request(
"POST",
f"drafts/{quote(draft_id, safe='')}/approve",
json_body={
"content_hash": content_hash,
"author_description_hash": description_hash,
"package_manifest_hash": manifest_hash,
},
)
return Draft.model_validate(body.get("draft", body))
def publish(self, draft_id: str, *, content_hash: str) -> dict[str, Any]:
return self._request(
"POST",
f"drafts/{quote(draft_id, safe='')}/publish",
json_body={"content_hash": content_hash, "base_commit": None},
)
def decline(self, draft_id: str) -> dict[str, Any]:
return self._request("POST", f"drafts/{quote(draft_id, safe='')}/decline")
def list_skills(self, *, cursor: str | None = None) -> SkillList:
return self._request(
"GET",
"skills",
model=SkillList,
params={"cursor": cursor} if cursor else None,
)
def skill(self, skill_id: str) -> SkillDetail:
return self._request(
"GET", f"skills/{quote(skill_id, safe='')}", model=SkillDetail
)
def version(self, skill_id: str, version: int) -> VersionDetail:
return self._request(
"GET",
f"skills/{quote(skill_id, safe='')}/versions/{version}",
model=VersionDetail,
)
def content(
self,
skill_id: str,
version: int,
*,
installation_id: str,
takedown_generation: int,
) -> tuple[VersionContent, list[tuple[str, str, bytes]]]:
response = self._request(
"GET",
f"skills/{quote(skill_id, safe='')}/versions/{version}/content",
model=VersionContent,
params={
"installation_id": installation_id,
"takedown_generation": takedown_generation,
},
)
return self._decode_version_content(response)
def raw_copy(
self, skill_id: str, version: int
) -> tuple[VersionContent, list[tuple[str, str, bytes]]]:
"""Read an immutable published package without creating install state."""
response = self._request(
"GET",
f"skills/{quote(skill_id, safe='')}/versions/{version}/raw",
model=VersionContent,
)
return self._decode_version_content(response)
@staticmethod
def _decode_version_content(
response: VersionContent,
) -> tuple[VersionContent, list[tuple[str, str, bytes]]]:
decoded: list[tuple[str, str, bytes]] = []
for item in response.files:
try:
raw = base64.b64decode(item["content_base64"], validate=True)
except (KeyError, TypeError, ValueError) as exc:
raise WisdomValidationError(
"version content contains malformed base64"
) from exc
if wire_address(raw) != item.get("hash"):
raise WisdomValidationError(
f"version blob failed integrity validation: {item.get('path', '?')}"
)
decoded.append((str(item["path"]), str(item["mode"]), raw))
records, derived = verify_content_files(decoded)
if derived != response.content_hash:
raise WisdomValidationError(
"version content hash failed integrity validation"
)
manifest_body = next(
(body for path, _, body in decoded if path == "skill.manifest.json"), None
)
if manifest_body is None:
raise WisdomValidationError("version content has no package manifest")
try:
parse_manifest_bytes(manifest_body)
except (UnicodeDecodeError, ValueError) as exc:
raise WisdomValidationError("version package manifest is invalid") from exc
return response, decoded
def record_install(
self,
*,
skill_id: str,
installation_id: str,
version: int,
takedown_generation: int,
update_mode: str | None,
) -> InstallationRecord:
payload: dict[str, Any] = {
"skill_id": skill_id,
"installation_id": installation_id,
"version": version,
"takedown_generation": takedown_generation,
}
if update_mode:
payload["update_mode"] = update_mode
return self._request(
"POST", "installations", model=InstallationRecord, json_body=payload
)
def installations(self, installation_id: str) -> list[dict[str, Any]]:
result = self._request(
"GET",
f"installations/{quote(installation_id, safe='')}",
model=InstallationList,
)
return [item.model_dump(mode="json") for item in result.installations]
def deactivate_install(
self, installation_id: str, skill_id: str
) -> InstallationDeactivation:
return self._request(
"DELETE",
f"installations/{quote(installation_id, safe='')}/skills/{quote(skill_id, safe='')}",
model=InstallationDeactivation,
)
def feed(
self, cursor: str | None = None, *, installation_id: str | None = None
) -> Feed:
params: dict[str, str] = {}
if cursor:
params["cursor"] = cursor
if installation_id:
params["installation_id"] = installation_id
return self._request("GET", "feed", model=Feed, params=params or None)