-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreply_grounding.py
More file actions
2846 lines (2580 loc) · 103 KB
/
Copy pathreply_grounding.py
File metadata and controls
2846 lines (2580 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Strict, bounded contracts for evidence-grounded Benthic replies."""
from __future__ import annotations
import hashlib
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from html.parser import HTMLParser
import http.client
import ipaddress
import json
import logging
import math
import os
from dataclasses import dataclass, field
from pathlib import Path
import re
import socket
import ssl
import subprocess
import sys
import threading
import time
from typing import Callable, Literal, Mapping, Sequence
import unicodedata
from urllib.parse import (
parse_qs,
parse_qsl,
quote,
urlencode,
urljoin,
urlsplit,
urlunsplit,
)
import uuid
import xml.etree.ElementTree as ElementTree
_MAX_CLAIM_CHARS = 2_000
_X_ROOT_HOSTS = ("x.com", "twitter.com")
_X_STATUS_PATH = re.compile(
r"^/([A-Za-z0-9_]{1,50})/status/([0-9]+)"
r"(?:/(?:photo|video)/[0-9]+)?/?$"
)
_XML_CONTENT_TYPES = {
"application/atom+xml",
"application/rss+xml",
"application/xml",
"text/xml",
}
_TEXT_CONTENT_TYPES = {
"application/json",
"application/xhtml+xml",
"text/html",
"text/plain",
} | _XML_CONTENT_TYPES
_XML_DECLARATION_RE = re.compile(r"<!\s*(?:DOCTYPE|ENTITY)\b", re.I)
_REDIRECT_STATUSES = {301, 302, 303, 307, 308}
_NAT64_WELL_KNOWN_PREFIX = ipaddress.ip_network("64:ff9b::/96")
_MAX_INLINE_STYLE_CHARS = 4_096
_MAX_INLINE_DECLARATIONS = 64
_MAX_CSS_VAR_DEPTH = 8
_MAX_PAGE_STYLE_CHARS = 16_384
_MAX_PAGE_STYLE_RULES = 128
_CSS_CUSTOM_PROPERTY = re.compile(r"--[-_A-Za-z0-9]+")
_MAX_TWITTER_STDOUT_BYTES = 1_048_576
_MAX_TWITTER_STDERR_BYTES = 65_536
_TWITTER_PROCESS_SLOTS = threading.BoundedSemaphore(4)
_HTTP_URL_RE = re.compile(r"https?://[^\s<>\[\]{}\"']+", re.I)
_BACKGROUND_LINE_RE = re.compile(
r"^\s*background(?:\s+only)?\s*:\s*(https?://[^\s<>\[\]{}\"']+)\s*$",
re.I,
)
_MARKET_TIMEFRAME_RE = re.compile(r"\b[1-9][0-9]{0,2}\s*[mhdw]\b", re.I)
_MARKET_TERM_RE = re.compile(
r"\b(?:liquidity|fdv|market\s+cap|volume|ohlcv|dex\s+pool|"
r"contract(?:\s+address)?|token|coin|ticker)\b",
re.I,
)
_EVM_ASSET_ID_RE = re.compile(r"^0x[0-9a-fA-F]{40}$")
_NETWORK_SLUG_RE = re.compile(r"^[a-z0-9](?:[a-z0-9_-]{0,62}[a-z0-9])?$")
_PUBLIC_GROUNDING_PROTOCOL_PATTERNS = (
("from this evidence", re.compile(r"\bfrom\s+this\s+evidence\b", re.I)),
("supplied evidence", re.compile(r"\b(?:the\s+)?supplied\s+evidence\b", re.I)),
("typed evidence", re.compile(r"\btyped\s+evidence\b", re.I)),
("evidence bundle", re.compile(r"\bevidence\s+bundle\b", re.I)),
("evidence id", re.compile(r"\bevidence[- ]ids?\b", re.I)),
("support matrix", re.compile(r"\bsupport[- ]matrix\b", re.I)),
("verification stage", re.compile(r"\bverification[- ]stage\b", re.I)),
("does not establish", re.compile(r"\bdoes\s+not\s+establish\b", re.I)),
("unsupported claim", re.compile(r"\bunsupported\s+claims?\b", re.I)),
("verifier", re.compile(r"\bverifier\b", re.I)),
)
_PUBLIC_DNS_LABEL_RE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$")
_RESERVED_RESEARCH_HOSTS = frozenset({
"broadcasthost",
"example.com",
"example.net",
"example.org",
"ip6-localhost",
"localhost",
"localhost.localdomain",
})
_RESERVED_RESEARCH_SUFFIXES = (
".example",
".example.com",
".example.net",
".example.org",
".home.arpa",
".internal",
".invalid",
".local",
".localhost",
".onion",
".test",
)
log = logging.getLogger(__name__)
_DNS_RESOLVER_SLOTS = threading.BoundedSemaphore(4)
def _is_x_host(host: str) -> bool:
"""Match only X/Twitter roots and their dot-delimited subdomains."""
return any(
host == root or host.endswith("." + root)
for root in _X_ROOT_HOSTS
)
class GroundingFailure(ValueError):
"""A bounded grounding contract is malformed or unsupported."""
@dataclass(frozen=True)
class GroundingLimits:
max_background_sources: int = 3
max_focal_urls: int = 8
max_source_requests: int = 10
max_source_bytes: int = 2_097_152
# Total budget: 900s Sol, 30s provider fallback, and 30s trusted fetch.
source_collection_timeout: int = 960
max_evidence_bytes: int = 24_000
fetch_timeout: int = 15
trace_retention_days: int = 14
photo_reference_max_age: int = 1_800
max_response_bytes: int = 1_048_576
max_redirects: int = 3
@dataclass(frozen=True)
class EvidenceItem:
evidence_id: str
kind: Literal[
"current_message", "reply_message", "conversation_message",
"focal_url", "background_url", "media", "runtime_receipt",
]
text: str
source_ref: str
author: str | None = None
timestamp: str | None = None
url: str | None = None
content_hash: str | None = None
artifact_hash: str | None = None
@dataclass(frozen=True)
class EvidenceBundle:
trace_id: str
chat_id: int
message_id: int
direct: bool
mode: Literal["conversation", "grounded"]
focal_ids: tuple[str, ...]
items: tuple[EvidenceItem, ...]
background_source_urls: tuple[str, ...] = ()
def __post_init__(self):
if self.mode not in {"conversation", "grounded"}:
raise GroundingFailure("invalid evidence mode")
ids = tuple(item.evidence_id for item in self.items)
if len(ids) != len(set(ids)):
raise GroundingFailure("duplicate evidence id in bundle")
if any(value not in ids for value in self.focal_ids):
raise GroundingFailure("unknown focal evidence id")
def evidence_ids(self) -> frozenset[str]:
"""Return the immutable set used to validate claim references."""
return frozenset(item.evidence_id for item in self.items)
def research_candidate_limit(
evidence: EvidenceBundle,
limits: GroundingLimits) -> int:
"""Bound researched candidates without changing explicit root reservations.
Explicit background URLs continue to reserve final evidence-root slots.
Discovery gets two candidates for each unreserved root, while the nominal
request allowance prevents the model contract from exceeding the shared
turn-level request ceiling. The transport ledger remains authoritative
after focal requests, redirects, and failed responses spend real budget.
"""
explicit_count = len(evidence.background_source_urls)
remaining_slots = max(
0, limits.max_background_sources - explicit_count
)
nominal_requests = max(
0, limits.max_source_requests - explicit_count
)
return min(nominal_requests, remaining_slots * 2)
@dataclass(frozen=True)
class GroundedClaim:
claim: str
evidence_ids: tuple[str, ...]
@dataclass(frozen=True)
class ComposedReply:
decision: Literal["reply", "skip", "uncertain"]
reply: str
claims: tuple[GroundedClaim, ...]
@dataclass(frozen=True)
class VerificationVerdict:
passed: bool
unsupported_claims: tuple[str, ...]
reason: str
@dataclass(frozen=True)
class MediaObservation:
"""One bounded observation row tied to a selected image index."""
index: int
observations: tuple[str, ...]
visible_text: tuple[str, ...]
@dataclass(frozen=True)
class FetchedSource:
canonical_url: str
source_ref: str
text: str
author: str | None = None
timestamp: str | None = None
quoted: tuple["FetchedSource", ...] = field(default_factory=tuple)
response_bytes: int = 0
ResearchRole = Literal["general", "identity", "market", "thesis"]
@dataclass(frozen=True)
class ResearchCandidate:
"""One untrusted model-proposed URL and its scheduling role."""
url: str
role: ResearchRole = "general"
@dataclass(frozen=True)
class ResearchPlan:
"""Strict discovery output used by the trusted collection scheduler."""
market_intent: bool
network: str | None
asset_id: str | None
candidates: tuple[ResearchCandidate, ...]
@property
def urls(self) -> tuple[str, ...]:
"""Return candidate URLs in the model-proposed order."""
return tuple(candidate.url for candidate in self.candidates)
@dataclass(frozen=True)
class BackgroundCollectionResult:
"""Trusted discovered roots selected under the existing turn ledgers."""
urls: tuple[str, ...]
attempted_count: int
covered_roles: frozenset[ResearchRole] = frozenset()
market_required: bool = False
@property
def accepted_count(self) -> int:
"""Return how many fetched roots earned an evidence slot."""
return len(self.urls)
@property
def market_complete(self) -> bool:
"""Return whether exact identity and market lanes are both covered."""
return (
not self.market_required
or {"identity", "market"}.issubset(self.covered_roles)
)
def _message_text(message):
"""Return one Telegram message's text without flattening related messages."""
return str(message.get("text") or message.get("caption") or "")
def canonical_event_time(value):
"""Normalize supported event times to timezone-aware UTC ISO-8601.
Naive, malformed, non-finite, and boolean values return ``None`` so they
cannot accidentally support chronological claims.
"""
parsed = None
if isinstance(value, bool) or value is None:
return None
if isinstance(value, (int, float)):
try:
parsed = datetime.fromtimestamp(value, tz=timezone.utc)
except (OverflowError, OSError, ValueError):
return None
elif isinstance(value, datetime):
parsed = value
elif isinstance(value, str) and value.strip():
candidate = value.strip()
try:
parsed = datetime.fromisoformat(
candidate[:-1] + "+00:00" if candidate.endswith(("Z", "z"))
else candidate
)
except ValueError:
try:
parsed = parsedate_to_datetime(candidate)
except (TypeError, ValueError, OverflowError):
return None
if parsed is None or parsed.tzinfo is None:
return None
try:
return parsed.astimezone(timezone.utc).isoformat()
except (OverflowError, ValueError):
return None
def _message_event_time(message):
"""Prefer an ingress-normalized event field when one is explicitly present."""
value = message.get("event_time") if "event_time" in message else message.get("date")
return canonical_event_time(value)
def _clean_evidence_text(value, limit):
"""Normalize and bound one evidence item's text independently."""
value = unicodedata.normalize("NFKC", str(value or ""))
value = re.sub(r"\[photo#[0-9]+\]", "[photo omitted]", value)
value = value.replace("<", "<").replace(">", ">")
value = re.sub(r"[-=]{4,}", "---", value)
value = "".join(
char for char in value
if char in "\n\t" or (ord(char) >= 32 and ord(char) != 127)
)
return value.strip()[:limit]
def _content_hash(value):
"""Return a stable digest for normalized evidence text."""
return hashlib.sha256(value.encode("utf-8")).hexdigest()
def _urls_in(value):
"""Extract unique HTTP(S) URLs in first-seen order from one focal item."""
found = []
for match in _HTTP_URL_RE.findall(value or ""):
candidate = match.rstrip(".,!?;:)")
if candidate and candidate not in found:
found.append(candidate)
return tuple(found)
def _classified_message_urls(value):
"""Split focal and explicitly labeled background URLs line by line.
Only ``Background: URL`` and ``Background only: URL`` are accepted labels.
Any other line that combines the word background with a URL is ambiguous
and fails closed before source dispatch.
"""
focal = []
background = []
for line in str(value or "").splitlines() or ("",):
urls = _urls_in(line)
label = _BACKGROUND_LINE_RE.fullmatch(line)
if label is not None:
if len(urls) != 1 or label.group(1) != urls[0]:
raise GroundingFailure("ambiguous background URL syntax")
background.append(urls[0])
continue
if urls and re.search(r"\bbackground\b", line, flags=re.I):
raise GroundingFailure("ambiguous background URL syntax")
focal.extend(urls)
return tuple(focal), tuple(background)
def _telegram_ref(message, fallback_chat_id=0, suffix=""):
"""Build a stable Telegram source reference from typed message fields."""
chat_id = int(message.get("chat", {}).get("id", fallback_chat_id))
message_id = int(message.get("message_id", 0))
return f"telegram:{chat_id}:{message_id}{suffix}"
def _validated_source_ref(value):
"""Require a bounded, printable, whitespace-free evidence reference."""
if (
not isinstance(value, str)
or not value
or len(value.encode("utf-8")) > 512
or any(char.isspace() or not char.isprintable() for char in value)
):
raise GroundingFailure("invalid evidence source reference")
return value
def _evidence_item(evidence_id, kind, text, source_ref, **kwargs):
"""Construct one normalized evidence item with a content digest."""
# Text-document media carries a deterministic 16K excerpt plus a short
# metadata header. Other evidence retains the established 8K item bound.
clean = _clean_evidence_text(text, 16_512 if kind == "media" else 8_000)
return EvidenceItem(
evidence_id=evidence_id,
kind=kind,
text=clean,
source_ref=_validated_source_ref(source_ref),
content_hash=_content_hash(clean),
**kwargs,
)
def _fit_evidence(items, byte_limit):
"""Drop whole low-priority items and reject essential-item overflow."""
if type(byte_limit) is not int or byte_limit < 0:
raise GroundingFailure("invalid evidence byte limit")
values = list(items)
def size():
return sum(len(item.text.encode("utf-8")) for item in values)
for kind in ("background_url", "conversation_message"):
index = len(values) - 1
while size() > byte_limit and index >= 0:
if values[index].kind == kind:
values.pop(index)
index -= 1
if size() > byte_limit:
raise GroundingFailure("essential evidence exceeds byte limit")
for item in values:
if item.content_hash != _content_hash(item.text):
raise GroundingFailure("evidence content hash mismatch")
return tuple(values)
def _background_source_type(url):
"""Classify a failed source without logging its authority or body."""
try:
host = (urlsplit(url).hostname or "").lower()
except (TypeError, ValueError):
return "http"
return "twitter" if _is_x_host(host) else "http"
def collect_evidence(
message: dict,
recent_messages: Sequence[dict],
persisted_context: Sequence[Mapping[str, object]],
*,
direct: bool,
mode: str,
url_fetcher: Callable[[str, bool], FetchedSource],
background_urls: Sequence[str] = (),
media_items: Sequence[EvidenceItem] = (),
runtime_receipts: Sequence[EvidenceItem] = (),
allow_cross_chat_context: bool = False,
limits: GroundingLimits | None = None,
trace_id: str | None = None,
) -> EvidenceBundle:
"""Assemble bounded, typed, turn-local evidence for one reply."""
limits = limits or GroundingLimits()
chat_id = int(message.get("chat", {}).get("id", 0))
message_id = int(message.get("message_id", 0))
current_text = _message_text(message) or "[media attached]"
items = [_evidence_item(
"M0",
"current_message",
current_text,
_telegram_ref(message),
author=str(message.get("from", {}).get("username") or "")[:64] or None,
timestamp=_message_event_time(message),
)]
reply = message.get("reply_to_message")
if isinstance(reply, dict) and reply.get("message_id"):
items.append(_evidence_item(
"R1",
"reply_message",
_message_text(reply),
_telegram_ref(reply, chat_id),
author=str(reply.get("from", {}).get("username") or "")[:64] or None,
timestamp=_message_event_time(reply),
))
current_topic = int(message.get("message_thread_id") or 0)
seen_context = {(chat_id, message_id, "incoming")}
if isinstance(reply, dict):
seen_context.add((chat_id, int(reply.get("message_id") or 0), "incoming"))
context_rows = []
for row in list(recent_messages)[-20:]:
context_rows.append({
"role": "incoming",
"message_id": row.get("message_id"),
"chat_id": row.get("chat", {}).get("id", chat_id),
"sender": row.get("from", {}).get("username") or "?",
"sender_is_bot": bool(row.get("from", {}).get("is_bot")),
"text": _message_text(row),
"timestamp": _message_event_time(row),
"topic_id": row.get("message_thread_id"),
})
context_rows.extend(dict(row) for row in persisted_context[-50:])
context_index = 0
for row in context_rows:
row_chat = int(row.get("chat_id") or chat_id)
row_message = int(row.get("message_id") or 0)
row_topic = int(row.get("topic_id") or 0)
role = str(row.get("role") or "incoming")
key = (row_chat, row_message, role)
wrong_scope = (
row_chat != chat_id or row_topic != current_topic
) and not allow_cross_chat_context
if wrong_scope or key in seen_context or not row.get("text"):
continue
seen_context.add(key)
context_index += 1
suffix = ":bot_reply" if role == "our_reply" else ""
items.append(_evidence_item(
f"C{context_index}",
"conversation_message",
row.get("text"),
f"telegram:{row_chat}:{row_message}{suffix}",
author=str(row.get("sender") or "?")[:64],
timestamp=canonical_event_time(row.get("timestamp")),
))
focal_urls, explicit_background_urls = _classified_message_urls(current_text)
focal_urls = list(focal_urls)
explicit_background_urls = list(explicit_background_urls)
if isinstance(reply, dict):
reply_focal, reply_background = _classified_message_urls(
_message_text(reply)
)
focal_urls.extend(reply_focal)
explicit_background_urls.extend(reply_background)
def canonical_unique(values):
canonical = []
for value in values:
normalized = _canonical_source_url(value)
if normalized not in canonical:
canonical.append(normalized)
return canonical
focal_urls = canonical_unique(focal_urls)
explicit_background_urls = canonical_unique(explicit_background_urls)
explicit_background_set = set(explicit_background_urls)
focal_urls = [
value for value in focal_urls if value not in explicit_background_set
]
if len(focal_urls) > limits.max_focal_urls:
raise GroundingFailure("too many focal URLs")
discovered_background_urls = canonical_unique(background_urls)
all_background_urls = list(explicit_background_urls)
for value in discovered_background_urls:
if value not in all_background_urls and value not in focal_urls:
all_background_urls.append(value)
if len(all_background_urls) > limits.max_background_sources:
raise GroundingFailure("too many background URLs")
focal_ids = []
source_refs = set()
focal_index = 0
for url in focal_urls:
source = url_fetcher(url, True)
for candidate in (source, *source.quoted):
candidate_ref = _validated_source_ref(candidate.source_ref)
if candidate_ref in source_refs:
continue
source_refs.add(candidate_ref)
focal_index += 1
evidence_id = f"F{focal_index}"
focal_ids.append(evidence_id)
items.append(_evidence_item(
evidence_id,
"focal_url",
candidate.text,
candidate_ref,
author=candidate.author,
timestamp=canonical_event_time(candidate.timestamp),
url=candidate.canonical_url,
))
background_index = 0
for url in all_background_urls:
try:
source = url_fetcher(url, False)
except GroundingFailure:
log.warning(
"Grounding source omitted: role=background "
"source_type=%s failure_code=source_unavailable",
_background_source_type(url),
)
continue
for candidate in (source, *source.quoted):
candidate_ref = _validated_source_ref(candidate.source_ref)
if candidate_ref in source_refs:
continue
source_refs.add(candidate_ref)
background_index += 1
items.append(_evidence_item(
f"B{background_index}",
"background_url",
candidate.text,
candidate_ref,
author=candidate.author,
timestamp=canonical_event_time(candidate.timestamp),
url=candidate.canonical_url,
))
for index, item in enumerate(media_items, 1):
if not isinstance(item, EvidenceItem):
raise GroundingFailure("invalid media evidence item")
items.append(_evidence_item(
f"P{index}",
"media",
item.text,
item.source_ref,
author=item.author,
timestamp=canonical_event_time(item.timestamp),
url=item.url,
artifact_hash=item.artifact_hash,
))
for index, item in enumerate(runtime_receipts, 1):
if not isinstance(item, EvidenceItem):
raise GroundingFailure("invalid runtime receipt")
items.append(_evidence_item(
f"T{index}",
"runtime_receipt",
item.text,
item.source_ref,
author=item.author,
timestamp=canonical_event_time(item.timestamp),
url=item.url,
))
fitted = _fit_evidence(items, limits.max_evidence_bytes)
return EvidenceBundle(
trace_id=trace_id or uuid.uuid4().hex,
chat_id=chat_id,
message_id=message_id,
direct=direct,
mode=mode,
focal_ids=tuple(focal_ids),
items=fitted,
background_source_urls=tuple(all_background_urls),
)
def _embedded_ipv4_addresses(value):
"""Return IPv4 addresses carried by supported IPv6 transition formats."""
if not isinstance(value, ipaddress.IPv6Address):
return ()
embedded = []
if value.ipv4_mapped is not None:
embedded.append(value.ipv4_mapped)
if value.sixtofour is not None:
embedded.append(value.sixtofour)
if value.teredo is not None:
embedded.extend(value.teredo)
if value in _NAT64_WELL_KNOWN_PREFIX:
embedded.append(ipaddress.IPv4Address(int(value) & 0xFFFFFFFF))
return tuple(dict.fromkeys(embedded))
def _is_public_address(value):
"""Require both an address and every embedded transition address to be public."""
if not value.is_global or value.is_multicast:
return False
return all(
embedded.is_global and not embedded.is_multicast
for embedded in _embedded_ipv4_addresses(value)
)
def resolve_public_addresses(host, port, *, resolver=socket.getaddrinfo):
"""Resolve every address and reject the complete answer if any is unsafe."""
try:
rows = resolver(host, port, type=socket.SOCK_STREAM)
addresses = tuple(dict.fromkeys(str(row[4][0]) for row in rows))
except (OSError, TypeError, ValueError, IndexError) as exc:
raise GroundingFailure("hostname resolution failed") from exc
if not addresses:
raise GroundingFailure("hostname did not resolve")
try:
parsed = tuple(ipaddress.ip_address(value) for value in addresses)
except ValueError as exc:
raise GroundingFailure("hostname returned an invalid address") from exc
if any(not _is_public_address(value) for value in parsed):
raise GroundingFailure("hostname resolved to non-public address")
return addresses
def _resolve_before_deadline(host, port, resolver, timeout):
"""Bound resolver work by both a deadline and a process-wide worker cap."""
wait = max(0.0, float(timeout))
deadline = time.monotonic() + wait
acquired = _DNS_RESOLVER_SLOTS.acquire(timeout=wait)
if not acquired:
raise GroundingFailure("source DNS resolver saturated")
values = []
errors = []
def run():
try:
values.append(resolve_public_addresses(
host, port, resolver=resolver
))
except Exception as exc:
errors.append(exc)
finally:
_DNS_RESOLVER_SLOTS.release()
worker = threading.Thread(target=run, daemon=True)
try:
worker.start()
except Exception:
_DNS_RESOLVER_SLOTS.release()
raise
worker.join(max(0.0, deadline - time.monotonic()))
if worker.is_alive():
raise GroundingFailure("source DNS lookup timed out")
if errors:
error = errors[0]
if isinstance(error, GroundingFailure):
raise error
raise GroundingFailure("hostname resolution failed") from error
return values[0]
def _connect_pinned_socket(ip, port, timeout):
"""Connect a numeric validated address without hostname resolution."""
parsed = ipaddress.ip_address(ip)
family = socket.AF_INET6 if parsed.version == 6 else socket.AF_INET
sockaddr = (
(str(parsed), port, 0, 0)
if family == socket.AF_INET6
else (str(parsed), port)
)
connected = socket.socket(family, socket.SOCK_STREAM)
try:
connected.settimeout(timeout)
connected.connect(sockaddr)
return connected
except Exception:
connected.close()
raise
class _PinnedHTTPConnection(http.client.HTTPConnection):
"""Connect plain HTTP directly to the address validated by DNS policy."""
def __init__(self, host, ip, port, timeout):
super().__init__(host, port=port, timeout=timeout)
self._validated_ip = ip
def connect(self):
self.sock = _connect_pinned_socket(
self._validated_ip, self.port, self.timeout
)
class _PinnedHTTPSConnection(http.client.HTTPSConnection):
"""Connect to a pinned address while verifying TLS against the hostname."""
def __init__(self, host, ip, port, timeout):
super().__init__(
host,
port=port,
timeout=timeout,
context=ssl.create_default_context(),
)
self._validated_ip = ip
def connect(self):
raw = _connect_pinned_socket(
self._validated_ip, self.port, self.timeout
)
try:
self.sock = self._context.wrap_socket(
raw, server_hostname=self.host
)
except Exception:
raw.close()
raise
def _default_connection_factory(scheme, host, ip, port, timeout):
"""Construct a direct transport without consulting proxy environment state."""
cls = _PinnedHTTPSConnection if scheme == "https" else _PinnedHTTPConnection
return cls(host, ip, port, timeout)
def _strip_css_comments(value, maximum=_MAX_INLINE_STYLE_CHARS):
"""Remove bounded CSS comments and reject an unterminated comment."""
if len(value) > maximum:
return None
pieces = []
cursor = 0
while cursor < len(value):
start = value.find("/*", cursor)
if start < 0:
pieces.append(value[cursor:])
break
pieces.append(value[cursor:start])
end = value.find("*/", start + 2)
if end < 0:
return None
cursor = end + 2
return "".join(pieces)
def _decode_css_escapes(value):
"""Decode bounded CSS hexadecimal and single-character escapes."""
if len(value) > _MAX_INLINE_STYLE_CHARS:
return None
decoded = []
cursor = 0
hex_digits = "0123456789abcdefABCDEF"
whitespace = " \t\r\n\f"
while cursor < len(value):
char = value[cursor]
if char != "\\":
decoded.append(char)
cursor += 1
continue
cursor += 1
if cursor >= len(value):
return None
char = value[cursor]
if char in "\r\n\f":
if (
char == "\r"
and cursor + 1 < len(value)
and value[cursor + 1] == "\n"
):
cursor += 2
else:
cursor += 1
continue
if char in hex_digits:
start = cursor
while (
cursor < len(value)
and cursor - start < 6
and value[cursor] in hex_digits
):
cursor += 1
codepoint = int(value[start:cursor], 16)
if cursor < len(value) and value[cursor] in whitespace:
if (
value[cursor] == "\r"
and cursor + 1 < len(value)
and value[cursor + 1] == "\n"
):
cursor += 2
else:
cursor += 1
if (
codepoint == 0
or codepoint > 0x10FFFF
or 0xD800 <= codepoint <= 0xDFFF
):
decoded.append("\uFFFD")
else:
decoded.append(chr(codepoint))
continue
decoded.append(char)
cursor += 1
return "".join(decoded)
def _css_value_importance(value):
"""Separate a decoded trailing important marker from a declaration value."""
match = re.search(r"!\s*important\s*$", value, flags=re.I)
if match is None:
return value, False
return value[:match.start()], True
def _store_css_declaration(target, name, value, important):
"""Apply inline declaration order while preserving important precedence."""
current = target.get(name)
if current is None or important or not current[1]:
target[name] = (value, important)
def _parse_inline_style(value):
"""Parse only custom, display, and visibility inline declarations."""
without_comments = _strip_css_comments(value)
if without_comments is None:
return None
declarations = without_comments.split(";")
if len(declarations) > _MAX_INLINE_DECLARATIONS:
return None
standard = {}
custom = {}
for declaration in declarations:
if not declaration.strip() or ":" not in declaration:
continue
raw_name, raw_value = declaration.split(":", 1)
name = _decode_css_escapes(raw_name)
decoded_value = _decode_css_escapes(raw_value)
if name is None or decoded_value is None:
return None
name = name.strip()
decoded_value, important = _css_value_importance(decoded_value)
if name.startswith("--"):
if _CSS_CUSTOM_PROPERTY.fullmatch(name):
_store_css_declaration(
custom, name, decoded_value, important
)
continue
normalized_name = name.casefold()
if normalized_name in {"display", "visibility"}:
_store_css_declaration(
standard, normalized_name, decoded_value, important
)
continue
return None
return standard, custom
def _resolve_inline_css_value(value, custom, seen=(), depth=0):
"""Resolve a simple same-attribute custom property under a depth bound."""
compact = "".join(value.split())
match = re.fullmatch(
r"(?i:var)\((--[-_A-Za-z0-9]+)\)", compact
)
if match is None:
return None if "var(" in compact.casefold() else compact
name = match.group(1)
if depth >= _MAX_CSS_VAR_DEPTH or name in seen or name not in custom:
return None
return _resolve_inline_css_value(
custom[name][0], custom, seen + (name,), depth + 1
)
def _inline_style_is_hidden(value):
"""Evaluate bounded inline display and visibility declarations."""
if not value:
return False
parsed = _parse_inline_style(value)
if parsed is None:
return True
standard, custom = parsed
for property_name in ("display", "visibility"):
declaration = standard.get(property_name)
if declaration is None:
continue
resolved = _resolve_inline_css_value(declaration[0], custom)
if resolved is None:
return True
normalized = resolved.casefold()
if property_name == "display" and normalized == "none":
return True
if property_name == "visibility" and normalized in {
"hidden", "collapse",
}:
return True
return False
def _screen_media_applies(value):
"""Return whether a bounded stylesheet media attribute can affect screen text."""
if not value:
return True
media = {part.strip().casefold() for part in value.split(",") if part.strip()}
return not media or media != {"print"}
def _html_attribute_map(attrs):
"""Build a case-insensitive map only when every HTML attribute is unique."""
values = {}
for key, value in attrs:
name = str(key).casefold()
if name in values:
raise GroundingFailure("duplicate HTML attribute")
values[name] = str(value or "")
return values
class _PageStyleScanner(HTMLParser):