variantgate 0.9.0__py3-none-any.whl

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.
variantgate/preview.py ADDED
@@ -0,0 +1,199 @@
1
+ """Consequence previews: what an action will do, shown before a person decides.
2
+
3
+ The agent's code renders the email, prints the diff, dry-runs the SQL or
4
+ selects the records the action touches, and sends that with the request.
5
+ People see it beside checks that compare it with the rest of the request;
6
+ any disagreement keeps an ``allow`` rule from approving.
7
+
8
+ A preview is never cut to fit: a shortened diff or email would show the
9
+ person less than the action will do, so one that does not fit is refused
10
+ with the reason before anything is sent.
11
+ """
12
+
13
+ from collections.abc import Mapping, Sequence
14
+ from typing import Any, Literal, Optional, TypedDict, Union
15
+
16
+ MAX_RECIPIENTS = 50
17
+ """The most addresses in each of ``to``, ``cc`` and ``bcc``."""
18
+
19
+ MAX_PREVIEW_ROWS = 50
20
+ """The most rows a records preview shows."""
21
+
22
+ MAX_PREVIEW_COLUMNS = 20
23
+ """The most columns a records preview has."""
24
+
25
+ _LIMITS = {
26
+ "address": 320,
27
+ "body": 20_000,
28
+ "cell": 500,
29
+ "column": 100,
30
+ "patch": 60_000,
31
+ "plan": 10_000,
32
+ "statement": 10_000,
33
+ "subject": 500,
34
+ "title": 200,
35
+ }
36
+
37
+ PreviewCell = Union[str, int, float, bool, None]
38
+ """One cell of a records preview."""
39
+
40
+
41
+ class _EmailFields(TypedDict):
42
+ kind: Literal["email"]
43
+ to: Sequence[str]
44
+ body: str
45
+
46
+
47
+ class EmailPreview(_EmailFields, total=False):
48
+ """An email the action will send, rendered as it will go out."""
49
+
50
+ subject: str
51
+ cc: Sequence[str]
52
+ bcc: Sequence[str]
53
+
54
+
55
+ class DiffPreview(TypedDict):
56
+ """A code change, as a unified diff such as ``git diff`` prints."""
57
+
58
+ kind: Literal["diff"]
59
+ patch: str
60
+
61
+
62
+ class _SqlFields(TypedDict):
63
+ kind: Literal["sql"]
64
+ statement: str
65
+
66
+
67
+ class SqlPreview(_SqlFields, total=False):
68
+ """A database statement, with what a dry run of it found."""
69
+
70
+ rows_affected: int
71
+ plan: str
72
+
73
+
74
+ class _RecordsFields(TypedDict):
75
+ kind: Literal["records"]
76
+ columns: Sequence[str]
77
+ rows: Sequence[Sequence[PreviewCell]]
78
+
79
+
80
+ class RecordsPreview(_RecordsFields, total=False):
81
+ """The records the action touches, as a small table."""
82
+
83
+ title: str
84
+ total: int
85
+
86
+
87
+ class _TextFields(TypedDict):
88
+ kind: Literal["text"]
89
+ body: str
90
+
91
+
92
+ class TextPreview(_TextFields, total=False):
93
+ """Any other output, such as a chat message or a post, as plain text."""
94
+
95
+ title: str
96
+
97
+
98
+ Preview = Union[EmailPreview, DiffPreview, SqlPreview, RecordsPreview, TextPreview]
99
+ """What the action will do, in one of five kinds."""
100
+
101
+
102
+ def _text(field: str, text: Any, limit: int, required: bool = False) -> Optional[str]:
103
+ if text is None:
104
+ return f"`preview.{field}` is required" if required else None
105
+ if not isinstance(text, str):
106
+ return f"`preview.{field}` must be text"
107
+ if required and not text.strip():
108
+ return f"`preview.{field}` must not be empty"
109
+ if len(text) > limit:
110
+ return f"`preview.{field}` must be at most {limit} characters"
111
+ return None
112
+
113
+
114
+ def _addresses(field: str, items: Optional[Sequence[str]], required: bool) -> Optional[str]:
115
+ listed = list(items or [])
116
+ if required and not listed:
117
+ return f"`preview.{field}` must name at least one address"
118
+ if len(listed) > MAX_RECIPIENTS:
119
+ return f"`preview.{field}` may name at most {MAX_RECIPIENTS} addresses"
120
+ return _first(_text(field, item, _LIMITS["address"], True) for item in listed)
121
+
122
+
123
+ def _count(field: str, count: Any) -> Optional[str]:
124
+ whole = isinstance(count, int) and not isinstance(count, bool) and count >= 0
125
+ if count is None or whole:
126
+ return None
127
+ return f"`preview.{field}` must be a whole number, 0 or more"
128
+
129
+
130
+ def _cell(cell: Any) -> Optional[str]:
131
+ if isinstance(cell, str):
132
+ return _text("rows", cell, _LIMITS["cell"])
133
+ if cell is None or isinstance(cell, (bool, int, float)):
134
+ return None
135
+ return "`preview.rows` cells must be text, numbers, true/false or null"
136
+
137
+
138
+ def _row(row: Sequence[Any], width: int) -> Optional[str]:
139
+ if len(row) != width:
140
+ return "each row in `preview.rows` must have one cell per column"
141
+ return _first(_cell(cell) for cell in row)
142
+
143
+
144
+ def _records(preview: Mapping[str, Any]) -> Optional[str]:
145
+ columns = list(preview.get("columns") or [])
146
+ rows = list(preview.get("rows") or [])
147
+ total = preview.get("total")
148
+ if not 1 <= len(columns) <= MAX_PREVIEW_COLUMNS:
149
+ return f"`preview.columns` must have 1 to {MAX_PREVIEW_COLUMNS} names"
150
+ if len(rows) > MAX_PREVIEW_ROWS:
151
+ return f"`preview.rows` may show at most {MAX_PREVIEW_ROWS} rows"
152
+ found = _first(
153
+ [_text("columns", name, _LIMITS["column"], True) for name in columns]
154
+ + [_text("title", preview.get("title"), _LIMITS["title"]), _count("total", total)]
155
+ + [_row(row, len(columns)) for row in rows]
156
+ )
157
+ if found is None and total is not None and total < len(rows):
158
+ return "`preview.total` must not be less than the rows shown"
159
+ return found
160
+
161
+
162
+ def _first(problems: Any) -> Optional[str]:
163
+ return next((problem for problem in problems if problem), None)
164
+
165
+
166
+ def preview_problem(preview: Mapping[str, Any]) -> Optional[str]:
167
+ """Why the API would refuse ``preview``, or ``None`` when it fits."""
168
+ get = preview.get
169
+ kind = get("kind")
170
+ if kind == "email":
171
+ return _first(
172
+ [
173
+ _addresses("to", get("to"), True),
174
+ _addresses("cc", get("cc"), False),
175
+ _addresses("bcc", get("bcc"), False),
176
+ _text("subject", get("subject"), _LIMITS["subject"]),
177
+ _text("body", get("body"), _LIMITS["body"]),
178
+ ]
179
+ )
180
+ if kind == "diff":
181
+ return _text("patch", get("patch"), _LIMITS["patch"], True)
182
+ if kind == "sql":
183
+ return _first(
184
+ [
185
+ _text("statement", get("statement"), _LIMITS["statement"], True),
186
+ _text("plan", get("plan"), _LIMITS["plan"]),
187
+ _count("rows_affected", get("rows_affected")),
188
+ ]
189
+ )
190
+ if kind == "records":
191
+ return _records(preview)
192
+ if kind == "text":
193
+ return _first(
194
+ [
195
+ _text("title", get("title"), _LIMITS["title"]),
196
+ _text("body", get("body"), _LIMITS["body"], True),
197
+ ]
198
+ )
199
+ return "`preview.kind` must be email, diff, sql, records or text"
variantgate/py.typed ADDED
File without changes
@@ -0,0 +1,212 @@
1
+ """Checking an approval receipt offline, before a tool does the work.
2
+
3
+ When a person approves a request, the agent's read of it carries
4
+ ``receipt``: ``vgr1.<payload>.<signature>``. The payload is base64url (no
5
+ padding) of UTF-8 JSON naming the request, workspace, agent key, action,
6
+ the most money it may move and a digest of its details. The signature is
7
+ Ed25519 over the ASCII bytes of ``vgr1.<payload>``, by a key listed at
8
+ ``GET /v1/receipt-keys``. A receipt lives five minutes.
9
+ """
10
+
11
+ import base64
12
+ import binascii
13
+ import json
14
+ import re
15
+ import time
16
+ from collections.abc import Mapping
17
+ from dataclasses import dataclass
18
+ from decimal import Decimal, InvalidOperation
19
+ from typing import Any, Optional, Protocol, Union
20
+
21
+ from ._ed25519 import verify as _signature_matches
22
+ from .canonical import canonical_json, details_digest
23
+ from .errors import VariantGateError
24
+
25
+ __all__ = [
26
+ "RECEIPT_LEEWAY_SECONDS",
27
+ "ReceiptClaims",
28
+ "ReceiptError",
29
+ "canonical_json",
30
+ "details_digest",
31
+ "verify_receipt",
32
+ ]
33
+
34
+ RECEIPT_LEEWAY_SECONDS = 30
35
+ """How far apart the issuer's clock and this one may be, in seconds."""
36
+
37
+ _PREFIX = "vgr1"
38
+ _BASE64URL = re.compile("[A-Za-z0-9_-]*")
39
+
40
+
41
+ class ReceiptError(VariantGateError):
42
+ """The receipt does not let this tool do this work. Do not act."""
43
+
44
+
45
+ class SeenReceipts(Protocol):
46
+ """Where request ids of used receipts are kept, such as a ``set``."""
47
+
48
+ def __contains__(self, request_id: object, /) -> bool: ...
49
+
50
+ def add(self, request_id: str, /) -> None: ...
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class ReceiptClaims:
55
+ """What a checked receipt says a person approved."""
56
+
57
+ request_id: str
58
+ workspace_id: str
59
+ agent_key_id: Optional[str]
60
+ action: str
61
+ amount: Optional[str]
62
+ """The most money the work may move, as a decimal string, or ``None``."""
63
+ currency: Optional[str]
64
+ digest: str
65
+ issued_at: int
66
+ expires_at: int
67
+ key_id: str
68
+
69
+
70
+ def _base64url(text: str) -> Optional[bytes]:
71
+ if not _BASE64URL.fullmatch(text):
72
+ return None
73
+ try:
74
+ data = base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
75
+ except (binascii.Error, ValueError):
76
+ return None
77
+ # One text per value: refuses padding bits that are not zero.
78
+ return data if base64.urlsafe_b64encode(data).rstrip(b"=").decode() == text else None
79
+
80
+
81
+ def _payload(part: str) -> dict[str, Any]:
82
+ raw = _base64url(part)
83
+ try:
84
+ payload = json.loads(raw) if raw else None
85
+ except ValueError:
86
+ payload = None
87
+ if not isinstance(payload, dict) or not isinstance(payload.get("kid"), str):
88
+ raise ReceiptError("not a VariantGate receipt")
89
+ return payload
90
+
91
+
92
+ def _public_key(keys: Mapping[str, Any], kid: str) -> bytes:
93
+ listed = keys.get("keys")
94
+ if isinstance(listed, list):
95
+ for entry in listed:
96
+ usable = isinstance(entry, Mapping) and entry.get("alg") == "Ed25519"
97
+ if usable and entry.get("kid") == kid and isinstance(entry.get("public_key"), str):
98
+ return _base64url(entry["public_key"]) or b""
99
+ elif isinstance(keys.get(kid), (bytes, bytearray)):
100
+ return bytes(keys[kid])
101
+ raise ReceiptError("signed by an unknown key")
102
+
103
+
104
+ def _field(payload: Mapping[str, Any], name: str, kind: type, nullable: bool = False) -> Any:
105
+ value = payload.get(name)
106
+ if (value is None and nullable) or (isinstance(value, kind) and not isinstance(value, bool)):
107
+ return value
108
+ raise ReceiptError("not a VariantGate receipt")
109
+
110
+
111
+ def _claims(payload: Mapping[str, Any]) -> ReceiptClaims:
112
+ if type(payload.get("v")) is not int or payload["v"] != 1:
113
+ raise ReceiptError("not a VariantGate receipt")
114
+ return ReceiptClaims(
115
+ request_id=_field(payload, "rid", str),
116
+ workspace_id=_field(payload, "ws", str),
117
+ agent_key_id=_field(payload, "key", str, nullable=True),
118
+ action=_field(payload, "act", str),
119
+ amount=_field(payload, "amt", str, nullable=True),
120
+ currency=_field(payload, "cur", str, nullable=True),
121
+ digest=_field(payload, "dig", str),
122
+ issued_at=_field(payload, "iat", int),
123
+ expires_at=_field(payload, "exp", int),
124
+ key_id=payload["kid"],
125
+ )
126
+
127
+
128
+ def _decimal(value: Union[str, int, Decimal], what: str) -> Decimal:
129
+ if isinstance(value, float):
130
+ raise TypeError("pass the amount as a str, int or Decimal, never a float")
131
+ try:
132
+ number = Decimal(value)
133
+ except (InvalidOperation, TypeError, ValueError):
134
+ number = Decimal("NaN")
135
+ if not number.is_finite() or number < 0:
136
+ raise ReceiptError(f"{what} is not an amount of money")
137
+ return number
138
+
139
+
140
+ def _check_amount(
141
+ claims: ReceiptClaims, amount: Union[str, int, Decimal, None], currency: Optional[str]
142
+ ) -> None:
143
+ if claims.amount is None:
144
+ if amount is not None:
145
+ raise ReceiptError("this approval states no amount")
146
+ return
147
+ if amount is None:
148
+ raise ReceiptError("this approval has an amount limit: pass the amount you will move")
149
+ if (currency or "").upper() != (claims.currency or "").upper():
150
+ raise ReceiptError("currency differs")
151
+ if _decimal(amount, "the amount") > _decimal(claims.amount, "the approved amount"):
152
+ raise ReceiptError("amount is above what was approved")
153
+
154
+
155
+ def _check_time(claims: ReceiptClaims, now: float) -> None:
156
+ if now > claims.expires_at + RECEIPT_LEEWAY_SECONDS:
157
+ raise ReceiptError("receipt has expired")
158
+ if claims.issued_at > now + RECEIPT_LEEWAY_SECONDS:
159
+ raise ReceiptError("receipt is from the future")
160
+
161
+
162
+ def _signed_claims(receipt: str, keys: Mapping[str, Any]) -> ReceiptClaims:
163
+ parts = receipt.split(".") if isinstance(receipt, str) else []
164
+ if len(parts) != 3 or parts[0] != _PREFIX:
165
+ raise ReceiptError("not a VariantGate receipt")
166
+ payload = _payload(parts[1])
167
+ public_key = _public_key(keys, payload["kid"])
168
+ signature = _base64url(parts[2]) or b""
169
+ if not _signature_matches(public_key, f"{parts[0]}.{parts[1]}".encode(), signature):
170
+ raise ReceiptError("signature does not match")
171
+ return _claims(payload)
172
+
173
+
174
+ def verify_receipt(
175
+ receipt: str,
176
+ *,
177
+ keys: Mapping[str, Any],
178
+ workspace: str,
179
+ action: str,
180
+ details: Any = None,
181
+ amount: Union[str, int, Decimal, None] = None,
182
+ currency: Optional[str] = None,
183
+ agent_key: Optional[str] = None,
184
+ seen: Optional[SeenReceipts] = None,
185
+ now: Optional[float] = None,
186
+ ) -> ReceiptClaims:
187
+ """Checks that ``receipt`` approves exactly this work now; returns its claims.
188
+
189
+ ``keys`` is the JSON object ``GET /v1/receipt-keys`` serves, or a mapping
190
+ of key id to the 32 raw bytes of an Ed25519 public key. ``details`` must
191
+ be what the request carried (``{}`` when left out); ``amount``, a str,
192
+ int or ``Decimal`` and never a float, is the money the work will move, at
193
+ most the approved amount. ``seen`` (such as a ``set``) holds request ids
194
+ already used: a receipt is refused a second time, and its id is added on
195
+ success. Raises ``ReceiptError`` with the reason otherwise.
196
+ """
197
+ claims = _signed_claims(receipt, keys)
198
+ if claims.workspace_id != workspace.lower():
199
+ raise ReceiptError("receipt is for another workspace")
200
+ if claims.action != action:
201
+ raise ReceiptError("receipt is for another action")
202
+ if claims.digest != details_digest({} if details is None else details):
203
+ raise ReceiptError("details differ from what was approved")
204
+ _check_amount(claims, amount, currency)
205
+ if agent_key is not None and claims.agent_key_id != agent_key.lower():
206
+ raise ReceiptError("approved for another agent key")
207
+ _check_time(claims, time.time() if now is None else now)
208
+ if seen is not None:
209
+ if claims.request_id in seen:
210
+ raise ReceiptError("receipt was already used")
211
+ seen.add(claims.request_id)
212
+ return claims
@@ -0,0 +1,39 @@
1
+ """Sub-agent runs: an agent links a sub-agent's run below its own.
2
+
3
+ The family is then weighed as one: what any run of it read counts for the
4
+ trifecta guard, each request answers to the plans above it too, and
5
+ stopping a run stops the runs below it. A link is locked once made and
6
+ never approves anything. Both runs belong to the client's key.
7
+ """
8
+
9
+ from typing import TYPE_CHECKING, Any, Optional
10
+ from urllib.parse import quote
11
+
12
+ from . import _http
13
+ from .errors import ApprovalApiError
14
+ from .plans import or_none
15
+ from .runs import run_id
16
+
17
+ if TYPE_CHECKING:
18
+ from .client import ApprovalClient
19
+
20
+
21
+ def _checked(value: str, what: str) -> str:
22
+ chosen = run_id(value)
23
+ if chosen is None:
24
+ raise ApprovalApiError(f"{what} needs a run id", "invalid_request", 0)
25
+ return chosen
26
+
27
+
28
+ def link_run(client: "ApprovalClient", run: str, parent: str) -> Optional[dict[str, Any]]:
29
+ """Links sub-agent run ``run`` below ``parent``.
30
+
31
+ Raises ``RunLinkedError`` when ``run`` already has another parent; the
32
+ same parent again changes nothing. A loop, a chain more than 5 runs deep
33
+ or a family of more than 100 runs is refused with ``ApprovalApiError``
34
+ (422). Returns None when the server is older than sub-agent runs (404):
35
+ the runs are then weighed apart, as before.
36
+ """
37
+ url = f"{client.api_url}/v1/runs/{quote(_checked(run, 'the sub-agent'), safe='')}/parent"
38
+ body = {"parent": _checked(parent, "the parent")}
39
+ return or_none(lambda: _http.call_object(url, client._key, "PUT", body, client.timeout))
variantgate/runs.py ADDED
@@ -0,0 +1,26 @@
1
+ """Run ids: one id for one agent session, such as a CI job or a conversation.
2
+
3
+ Every request made with it shows in one timeline, and a person can stop the
4
+ run, which denies everything waiting in it and refuses anything it asks
5
+ afterwards.
6
+ """
7
+
8
+ import re
9
+ from typing import Any, Optional
10
+
11
+ MAX_RUN_LENGTH = 200
12
+ """The longest run id the API accepts."""
13
+
14
+ _NOT_ALLOWED = re.compile(r"[^A-Za-z0-9._:-]")
15
+
16
+
17
+ def run_id(value: Any) -> Optional[str]:
18
+ """``value`` as a run id the API accepts, or ``None`` when nothing is left.
19
+
20
+ Each character the API does not accept becomes ``_``, and the id is cut
21
+ to 200 characters.
22
+ """
23
+ if not isinstance(value, str):
24
+ return None
25
+ cleaned = _NOT_ALLOWED.sub("_", value.strip())[:MAX_RUN_LENGTH]
26
+ return cleaned or None
@@ -0,0 +1,122 @@
1
+ """Fits a list of inputs into what the API takes.
2
+
3
+ At most ``MAX_SOURCES`` entries, and excerpts small enough that the request
4
+ stays well inside the API's body limit. What is kept is chosen so the person
5
+ deciding still sees the untrusted text that could have steered the agent,
6
+ and the person's own words it can be compared with.
7
+ """
8
+
9
+ import re
10
+
11
+ from .types import Source
12
+
13
+ MAX_SOURCES = 10
14
+ """The most inputs one request may list."""
15
+
16
+ MAX_LABEL_LENGTH = 200
17
+ """The longest label the API takes, in characters."""
18
+
19
+ MAX_EXCERPT_LENGTH = 2000
20
+ """The longest excerpt the API takes, in characters."""
21
+
22
+ MAX_EXCERPT_BYTES = 32_000
23
+ """The most UTF-8 bytes all excerpts of one request take together."""
24
+
25
+ _CUT_MARK = "…"
26
+ _CUT_MARK_BYTES = 3
27
+ # A lone half of a surrogate pair is not text the API can read.
28
+ _SURROGATE = re.compile("[\ud800-\udfff]")
29
+
30
+
31
+ def clip(text: str, limit: int) -> str:
32
+ """Trims ``text`` and cuts it to at most ``limit`` characters, ending in "…"."""
33
+ trimmed = _SURROGATE.sub("�", text).strip()
34
+ if len(trimmed) <= limit:
35
+ return trimmed
36
+ return trimmed[: limit - 1].rstrip() + _CUT_MARK
37
+
38
+
39
+ def utf8_length(text: str) -> int:
40
+ """The length of ``text`` in UTF-8 bytes."""
41
+ return len(text.encode("utf-8"))
42
+
43
+
44
+ def clip_bytes(text: str, max_bytes: int) -> str:
45
+ """Cuts ``text`` to at most ``max_bytes`` UTF-8 bytes, ending in "…".
46
+
47
+ Empty when not even one character fits.
48
+ """
49
+ if utf8_length(text) <= max_bytes:
50
+ return text
51
+ # A character cut in half at the end is dropped by "ignore".
52
+ head = text.encode("utf-8")[: max(0, max_bytes - _CUT_MARK_BYTES)]
53
+ trimmed = head.decode("utf-8", "ignore").rstrip()
54
+ return trimmed + _CUT_MARK if trimmed else ""
55
+
56
+
57
+ def _untrusted(source: Source) -> bool:
58
+ return source.get("trust") == "untrusted"
59
+
60
+
61
+ def _keep_rank(source: Source) -> int:
62
+ """Lower is kept first: untrusted text, then trusted text, then labels."""
63
+ if not source.get("excerpt"):
64
+ return 2
65
+ return 0 if _untrusted(source) else 1
66
+
67
+
68
+ def _folded_entry(folded: list[Source]) -> Source:
69
+ """One entry standing for ``folded``: their texts, untrusted first."""
70
+ ordered = [s for s in folded if _untrusted(s)] + [s for s in folded if not _untrusted(s)]
71
+ lines = [
72
+ f"{source['label']}: {source['excerpt']}" if source.get("excerpt") else source["label"]
73
+ for source in ordered
74
+ ]
75
+ return {
76
+ "excerpt": clip("\n".join(lines), MAX_EXCERPT_LENGTH),
77
+ "kind": "other",
78
+ "label": f"{len(folded)} more inputs",
79
+ "trust": "untrusted" if any(map(_untrusted, folded)) else "trusted",
80
+ }
81
+
82
+
83
+ def fewest(sources: list[Source]) -> list[Source]:
84
+ """At most ``MAX_SOURCES`` entries.
85
+
86
+ With more, ``MAX_SOURCES - 1`` are kept as they are, in the order read:
87
+ untrusted inputs with text first, then trusted ones with text, then the
88
+ rest, newest first within each. The others become one entry first in
89
+ the list.
90
+ """
91
+ if len(sources) <= MAX_SOURCES:
92
+ return sources
93
+ by_priority = sorted(range(len(sources)), key=lambda at: (_keep_rank(sources[at]), -at))
94
+ kept = set(by_priority[: MAX_SOURCES - 1])
95
+ folded = [source for at, source in enumerate(sources) if at not in kept]
96
+ return [_folded_entry(folded), *(s for at, s in enumerate(sources) if at in kept)]
97
+
98
+
99
+ def within_bytes(sources: list[Source]) -> list[Source]:
100
+ """Shortens excerpts until together they take at most ``MAX_EXCERPT_BYTES``.
101
+
102
+ Trusted excerpts are shortened first, then untrusted ones, oldest first.
103
+ """
104
+ fitted = [source.copy() for source in sources]
105
+ excess = sum(utf8_length(s.get("excerpt", "")) for s in fitted) - MAX_EXCERPT_BYTES
106
+ order = sorted(range(len(fitted)), key=lambda at: (_untrusted(fitted[at]), at))
107
+ for at in order:
108
+ excerpt = fitted[at].get("excerpt", "")
109
+ if excess > 0 and excerpt:
110
+ excess -= _shorten(fitted[at], excerpt, excess)
111
+ return fitted
112
+
113
+
114
+ def _shorten(source: Source, excerpt: str, excess: int) -> int:
115
+ """Cuts one excerpt by up to ``excess`` bytes; answers how many it cut."""
116
+ before = utf8_length(excerpt)
117
+ cut = clip_bytes(excerpt, max(0, before - excess))
118
+ if cut:
119
+ source["excerpt"] = cut
120
+ else:
121
+ del source["excerpt"]
122
+ return before - utf8_length(cut)