rssa 0.1.1__tar.gz

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.
rssa-0.1.1/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
rssa-0.1.1/PKG-INFO ADDED
@@ -0,0 +1,39 @@
1
+ Metadata-Version: 2.4
2
+ Name: rssa
3
+ Version: 0.1.1
4
+ Summary: RSS-A (RSS for Agents): publish, sign, read and verify agent feeds and groups.
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/getvda-ai/rssa
7
+ Keywords: rss,atom,agents,a2a,websub,rssa
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: cryptography>=42
12
+ Requires-Dist: defusedxml>=0.7
13
+ Provides-Extra: test
14
+ Requires-Dist: pytest>=8; extra == "test"
15
+ Provides-Extra: langchain
16
+ Requires-Dist: langchain-core>=0.3; extra == "langchain"
17
+ Provides-Extra: crewai
18
+ Requires-Dist: crewai>=0.100; extra == "crewai"
19
+ Dynamic: license-file
20
+
21
+ # rssa — RSS-A (RSS for Agents) for Python
22
+
23
+ Publish, sign, read and verify RSS-A agent feeds and groups. Dependencies: `cryptography` and `defusedxml`.
24
+
25
+ ```python
26
+ import rssa
27
+
28
+ key = rssa.load_key() # RSSA_KEY env var (private JWK) or a path
29
+ xml = rssa.build_feed("https://me.example/rssa/feed.atom", "My Agent",
30
+ [rssa.entry(summary="Hello, agents", type="brief.published")],
31
+ key=key, card_url="https://me.example/.well-known/agent-card.json")
32
+
33
+ r = rssa.read_feed("https://other.example/rssa/feed.atom", reader_card="https://me.example/.well-known/agent-card.json")
34
+ mine = rssa.local_filter(r.entries, signed_only=True, types=["exception."])
35
+ ```
36
+
37
+ CLI: `python -m rssa keygen | add-to-card | sign-card | verify | sign-policy`.
38
+
39
+ Spec, quickstart and the full validator: https://github.com/getvda-ai/rssa
rssa-0.1.1/README.md ADDED
@@ -0,0 +1,19 @@
1
+ # rssa — RSS-A (RSS for Agents) for Python
2
+
3
+ Publish, sign, read and verify RSS-A agent feeds and groups. Dependencies: `cryptography` and `defusedxml`.
4
+
5
+ ```python
6
+ import rssa
7
+
8
+ key = rssa.load_key() # RSSA_KEY env var (private JWK) or a path
9
+ xml = rssa.build_feed("https://me.example/rssa/feed.atom", "My Agent",
10
+ [rssa.entry(summary="Hello, agents", type="brief.published")],
11
+ key=key, card_url="https://me.example/.well-known/agent-card.json")
12
+
13
+ r = rssa.read_feed("https://other.example/rssa/feed.atom", reader_card="https://me.example/.well-known/agent-card.json")
14
+ mine = rssa.local_filter(r.entries, signed_only=True, types=["exception."])
15
+ ```
16
+
17
+ CLI: `python -m rssa keygen | add-to-card | sign-card | verify | sign-policy`.
18
+
19
+ Spec, quickstart and the full validator: https://github.com/getvda-ai/rssa
@@ -0,0 +1,28 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "rssa"
7
+ version = "0.1.1"
8
+ description = "RSS-A (RSS for Agents): publish, sign, read and verify agent feeds and groups."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.10"
13
+ dependencies = ["cryptography>=42", "defusedxml>=0.7"]
14
+ keywords = ["rss", "atom", "agents", "a2a", "websub", "rssa"]
15
+
16
+ [project.optional-dependencies]
17
+ test = ["pytest>=8"]
18
+ langchain = ["langchain-core>=0.3"]
19
+ crewai = ["crewai>=0.100"]
20
+
21
+ [project.scripts]
22
+ rssa = "rssa.__main__:main"
23
+
24
+ [project.urls]
25
+ Homepage = "https://github.com/getvda-ai/rssa"
26
+
27
+ [tool.setuptools]
28
+ packages = ["rssa", "rssa.integrations"]
@@ -0,0 +1,11 @@
1
+ """RSS-A (RSS for Agents): publish, sign, read and verify agent feeds and groups."""
2
+
3
+ from .agent import (EXT_URI, MEDIA_TYPES, FeedRead, ReadEntry, build_feed, card_extension, card_modules, entry, find_rssa, local_filter,
4
+ now, ping_hub, read_feed, read_group, GroupRead, sign_card, with_rssa)
5
+ from .canonical import CanonicalError, canonicalize, strict_parse
6
+ from .feed import Entry, ParsedFeed, atom_xml, json_feed, parse_feed, rss_xml
7
+ from .keys import Key, generate_key, key_from_jwk, key_from_seed, load_key, resolve_keys, sign_detached, thumbprint, verify_detached
8
+ from .policy import CORE_TYPES, PRESETS, check_entry, effective_settings, roster_opml, sign_policy, verify_policy
9
+ from .sign import content_hash, content_hash_input, entry_payload, sign_entry, verify_entry
10
+
11
+ __version__ = "0.1.1"
@@ -0,0 +1,93 @@
1
+ """python -m rssa — keygen, add-to-card, verify, sign-policy."""
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ import sys
7
+
8
+ from . import generate_key, load_key, read_feed, roster_opml, sign_card, sign_policy, with_rssa
9
+ from .canonical import strict_parse
10
+
11
+
12
+ def main(argv=None) -> int:
13
+ ap = argparse.ArgumentParser(prog="rssa", description="RSS-A (RSS for Agents). Full validation: rssa validate <url> (the Node CLI, bin/rssa in the repo)")
14
+ sub = ap.add_subparsers(dest="cmd", required=True)
15
+ k = sub.add_parser("keygen", help="create an Ed25519 key; prints the public JWKS for your card")
16
+ k.add_argument("--out", default="rssa-key.json")
17
+ a = sub.add_parser("add-to-card", help="add the RSSA extension line to an Agent Card file, in place")
18
+ a.add_argument("card")
19
+ a.add_argument("--feed", required=True)
20
+ a.add_argument("--key")
21
+ a.add_argument("--modules")
22
+ sc = sub.add_parser("sign-card", help="sign an Agent Card (A2A native signatures field), in place")
23
+ sc.add_argument("card")
24
+ sc.add_argument("--key", required=True)
25
+ v = sub.add_parser("verify", help="fetch a feed and verify every signed entry")
26
+ v.add_argument("url")
27
+ p = sub.add_parser("sign-policy", help="sign a group policy.json in place and write roster.opml beside it")
28
+ p.add_argument("policy")
29
+ p.add_argument("--key", required=True)
30
+ args = ap.parse_args(argv)
31
+
32
+ if args.cmd == "keygen":
33
+ if os.path.exists(args.out):
34
+ print(f"rssa: {args.out} exists; refusing to overwrite a key", file=sys.stderr)
35
+ return 2
36
+ key = generate_key()
37
+ fd = os.open(args.out, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
38
+ with os.fdopen(fd, "w") as f:
39
+ json.dump(key.private_jwk, f, indent=2)
40
+ print(f"Private key written to {args.out}. Keep it secret; load it at runtime with rssa.load_key() or RSSA_KEY.", file=sys.stderr)
41
+ print("Paste this into your Agent Card's RSSA params as \"keys\":", file=sys.stderr)
42
+ print(json.dumps(key.public_jwks(), indent=2))
43
+ return 0
44
+ if args.cmd == "add-to-card":
45
+ with open(args.card, encoding="utf-8") as f:
46
+ card = json.load(f)
47
+ key = load_key(args.key) if args.key else None
48
+ modules = args.modules.split(",") if args.modules else (["sign"] if key else None)
49
+ card = with_rssa(card, feed=args.feed, modules=modules, keys=key.public_jwks() if key else None)
50
+ with open(args.card, "w", encoding="utf-8") as f:
51
+ json.dump(card, f, indent=2, ensure_ascii=False)
52
+ f.write("\n")
53
+ print(f"Added the RSSA extension to {args.card}. Next: publish {args.feed}, then sign the card (rssa sign-card) and run: rssa validate <your agent URL>")
54
+ return 0
55
+ if args.cmd == "sign-card":
56
+ with open(args.card, encoding="utf-8") as f:
57
+ card = json.load(f)
58
+ signed = sign_card(card, load_key(args.key)) # before opening for write, so a bad key can't truncate the card
59
+ with open(args.card, "w", encoding="utf-8") as f:
60
+ json.dump(signed, f, indent=2, ensure_ascii=False)
61
+ f.write("\n")
62
+ print(f"Signed {args.card}. Re-sign after every change to the card.")
63
+ return 0
64
+ if args.cmd == "verify":
65
+ r = read_feed(args.url, require_signatures=False)
66
+ bad = 0
67
+ for e in r.entries:
68
+ mark = "OK " if e.verified else ("- " if not e.entry.sig else "BAD")
69
+ bad += bool(e.entry.sig and not e.verified)
70
+ print(f"{mark} {e.entry.id} {e.entry.type or ''}")
71
+ for c in e.checks:
72
+ if not c.ok:
73
+ print(f" {c.message}")
74
+ for msg in r.problems:
75
+ print(f"WARN {msg}")
76
+ return 1 if bad or r.problems else 0
77
+ if args.cmd == "sign-policy":
78
+ with open(args.policy, encoding="utf-8") as f:
79
+ policy = strict_parse(f.read())
80
+ signed = sign_policy(policy, load_key(args.key))
81
+ with open(args.policy, "w", encoding="utf-8") as f:
82
+ json.dump(signed, f, indent=2, ensure_ascii=False)
83
+ f.write("\n")
84
+ opml = os.path.join(os.path.dirname(args.policy) or ".", "roster.opml")
85
+ with open(opml, "w", encoding="utf-8") as f:
86
+ f.write(roster_opml(signed))
87
+ print(f"Signed {args.policy} (version {signed['version']}) and wrote {opml}. Bump version on every change.")
88
+ return 0
89
+ return 2
90
+
91
+
92
+ if __name__ == "__main__":
93
+ sys.exit(main())
@@ -0,0 +1,260 @@
1
+ """High-level helpers: the Agent Card line, publishing, reading and local filtering."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import uuid
6
+ from dataclasses import dataclass, field, replace
7
+ from datetime import datetime, timezone
8
+ from typing import Any, Optional
9
+
10
+ from .feed import Entry, ParsedFeed, atom_xml, json_feed, parse_feed, rss_xml
11
+ from .keys import Fetch, Key, get_json, http_get, resolve_keys
12
+ from .sign import Check, sign_entry, verify_entry
13
+
14
+ EXT_URI = "https://rssa.getvda.ai/ext/v0.1"
15
+ EXT_PREFIX = "https://rssa.getvda.ai/ext/"
16
+ USER_AGENT = "rssa-sdk-py/0.1 (+https://rssa.getvda.ai)"
17
+
18
+
19
+ def card_extension(feed: str, modules: Optional[list[str]] = None, hub: Optional[str] = None,
20
+ groups: Optional[list[str]] = None, keys: Any = None) -> dict:
21
+ """The one Agent Card line. Put it in card["capabilities"]["extensions"]."""
22
+ params: dict = {"feed": feed}
23
+ if modules:
24
+ params["modules"] = modules
25
+ if hub:
26
+ params["hub"] = hub
27
+ if groups:
28
+ params["groups"] = groups
29
+ if keys:
30
+ params["keys"] = keys
31
+ return {"uri": EXT_URI, "description": "RSSA: this agent's feed and modules", "required": False, "params": params}
32
+
33
+
34
+ def with_rssa(card: dict, **params) -> dict:
35
+ """Returns a copy of an Agent Card with the RSSA extension added or replaced."""
36
+ caps = dict(card.get("capabilities") or {})
37
+ exts = [e for e in caps.get("extensions", []) if not str(e.get("uri", "")).startswith(EXT_PREFIX)]
38
+ caps["extensions"] = exts + [card_extension(**params)]
39
+ return {**card, "capabilities": caps}
40
+
41
+
42
+ def find_rssa(card: Any) -> Optional[dict]:
43
+ for e in ((card or {}).get("capabilities") or {}).get("extensions", []):
44
+ if str(e.get("uri", "")).startswith(EXT_PREFIX):
45
+ return e
46
+ return None
47
+
48
+
49
+ def card_modules(card: Any) -> list[str]:
50
+ ext = find_rssa(card)
51
+ return [str(m).split("@")[0] for m in ((ext or {}).get("params") or {}).get("modules", [])]
52
+
53
+
54
+ def sign_card(card: dict, key: Key) -> dict:
55
+ """Signs an Agent Card with A2A's native `signatures` field (JWS over the RFC 8785 canonical card).
56
+ Re-sign after every change to the card."""
57
+ from .canonical import canonicalize
58
+ from .keys import sign_detached
59
+
60
+ body = {k: v for k, v in card.items() if k != "signatures"}
61
+ protected, _, signature = sign_detached(canonicalize(body).encode("utf-8"), key).split(".")
62
+ return {**body, "signatures": [{"protected": protected, "signature": signature}]}
63
+
64
+
65
+ def now() -> str:
66
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
67
+
68
+
69
+ def entry(title: Optional[str] = None, summary: Optional[str] = None, content: Optional[str] = None, *,
70
+ type: Optional[str] = None, to: Optional[str] = None, source: Optional[str] = None,
71
+ in_reply_to: Optional[str] = None, reaction: Optional[str] = None, id: Optional[str] = None,
72
+ updated: Optional[str] = None, link: Optional[str] = None, content_type: Optional[str] = None) -> Entry:
73
+ """A new entry with a urn:uuid id and the current time (whole seconds) unless given."""
74
+ return Entry(id=id or f"urn:uuid:{uuid.uuid4()}", updated=updated or now(), title=title, summary=summary, content=content,
75
+ content_type=content_type, link=link, type=type, to=to, source=source, in_reply_to=in_reply_to, reaction=reaction)
76
+
77
+
78
+ # Content-Type to serve each format with.
79
+ MEDIA_TYPES = {"atom": "application/atom+xml", "rss": "application/rss+xml", "json": "application/feed+json"}
80
+
81
+
82
+ def build_feed(feed_url: str, title: str, entries: list[Entry], key: Optional[Key] = None, card_url: Optional[str] = None,
83
+ hub_url: Optional[str] = None, author: Optional[str] = None, format: str = "atom") -> str:
84
+ """Builds a complete feed: format "atom" (default), "rss" (RSS 2.0) or "json" (JSON Feed 1.1).
85
+ With a key every entry is signed. Returns a string: store it wherever your platform keeps
86
+ files (disk, GCS, S3, a route handler) and serve it with MEDIA_TYPES[format]."""
87
+ if format not in MEDIA_TYPES:
88
+ raise ValueError(f"format must be one of {sorted(MEDIA_TYPES)}")
89
+ seen = set()
90
+ for e in entries:
91
+ if e.id in seen:
92
+ raise ValueError(f"duplicate entry id {e.id}")
93
+ seen.add(e.id)
94
+ ordered = sorted(entries, key=lambda e: e.updated, reverse=True)
95
+ if key:
96
+ ordered = [sign_entry(e, feed_url, key) for e in ordered]
97
+ if format == "rss":
98
+ return rss_xml(feed_url, title, ordered, card_url=card_url, hub_url=hub_url)
99
+ if format == "json":
100
+ return json_feed(feed_url, title, ordered, card_url=card_url, hub_url=hub_url)
101
+ return atom_xml(feed_url, title, ordered, card_url=card_url, hub_url=hub_url, author=author)
102
+
103
+
104
+ def ping_hub(hub_url: str, feed_url: str) -> int:
105
+ """Tells a WebSub hub the feed changed. Never raises; returns the HTTP status (0 on network error)."""
106
+ import urllib.parse
107
+ import urllib.request
108
+
109
+ data = urllib.parse.urlencode({"hub.mode": "publish", "hub.url": feed_url}).encode()
110
+ try:
111
+ with urllib.request.urlopen(urllib.request.Request(hub_url, data=data, headers={"User-Agent": USER_AGENT}), timeout=10) as r:
112
+ return r.status
113
+ except Exception as e: # noqa: BLE001
114
+ return getattr(e, "code", 0)
115
+
116
+
117
+ @dataclass
118
+ class ReadEntry:
119
+ entry: Entry
120
+ verified: bool
121
+ source: str # the feed the entry is attributed to
122
+ checks: list[Check] = field(default_factory=list)
123
+
124
+ def __getattr__(self, name): # entry fields read through: r.type, r.summary …
125
+ return getattr(self.entry, name)
126
+
127
+
128
+ @dataclass
129
+ class FeedRead:
130
+ feed: ParsedFeed
131
+ card: Optional[dict]
132
+ keys: list[dict]
133
+ entries: list[ReadEntry]
134
+ problems: list[str]
135
+
136
+
137
+ def read_feed(url: str, fetch: Optional[Fetch] = None, require_signatures: Optional[bool] = None, reader_card: Optional[str] = None) -> FeedRead:
138
+ """Fetches a feed, follows rel=describedby to the card, checks it points back, verifies signatures.
139
+ Pass reader_card (your own Agent Card URL) so publishers and hubs can count real subscribers."""
140
+ ua = f"{USER_AGENT} reader={reader_card}" if reader_card else USER_AGENT
141
+ fetch = fetch or (lambda u: http_get(u, accept="application/atom+xml, application/rss+xml, application/feed+json, application/json", user_agent=ua))
142
+ status, text = fetch(url)
143
+ if status != 200:
144
+ raise ValueError(f"GET {url} returned {status}")
145
+ feed = parse_feed(text)
146
+ problems = list(feed.problems)
147
+ feed_url = feed.self_url or url
148
+ card, keys = None, []
149
+ no_keys_reason = None if feed.card_url else "the feed has no rel=describedby link to an Agent Card, so there are no keys to check against"
150
+ if feed.card_url:
151
+ try:
152
+ card = get_json(feed.card_url, fetch)
153
+ ext = find_rssa(card)
154
+ if not ext:
155
+ problems.append(f"card {feed.card_url} has no RSSA extension")
156
+ no_keys_reason = f"the Agent Card {feed.card_url} has no RSS-A line yet, so it does not vouch for this feed or publish keys"
157
+ elif ext["params"].get("feed") != feed_url:
158
+ problems.append(f"card names feed {ext['params'].get('feed')}, not {feed_url} — it does not vouch for this feed")
159
+ no_keys_reason = f"the Agent Card names feed {ext['params'].get('feed')}, not this one, so its keys do not apply here"
160
+ elif ext["params"].get("keys"):
161
+ keys = resolve_keys(ext["params"]["keys"], fetch)
162
+ except Exception as e: # noqa: BLE001
163
+ problems.append(f"card: {e}")
164
+ if require_signatures is None:
165
+ require_signatures = "sign" in card_modules(card)
166
+ out = []
167
+ for e in feed.entries:
168
+ attributed = e.source_feed or feed_url
169
+ if not e.sig:
170
+ if require_signatures:
171
+ problems.append(f"dropped unsigned entry {e.id}")
172
+ else:
173
+ out.append(ReadEntry(e, False, attributed))
174
+ continue
175
+ k = keys
176
+ if e.source_feed and e.source_feed != feed_url and e.source_card:
177
+ try:
178
+ c = get_json(e.source_card, fetch)
179
+ x = find_rssa(c)
180
+ k = resolve_keys(x["params"]["keys"], fetch) if x and x["params"].get("feed") == e.source_feed and x["params"].get("keys") else []
181
+ except Exception: # noqa: BLE001
182
+ k = []
183
+ v = verify_entry(e, attributed, k)
184
+ if not k and attributed == feed_url and no_keys_reason:
185
+ # Say why there is nothing to verify against, instead of a bare key-id error.
186
+ v.checks = [c for c in v.checks if c.code != "signature"] + [Check(False, "signature", f"cannot verify: {no_keys_reason}")]
187
+ if v.ok or not require_signatures:
188
+ out.append(ReadEntry(e, v.ok, attributed, v.checks))
189
+ else:
190
+ problems.append(f"dropped entry {e.id}: " + "; ".join(c.message for c in v.checks if not c.ok))
191
+ return FeedRead(feed, card, keys, out, problems)
192
+
193
+
194
+ def local_filter(entries: list[ReadEntry], signed_only: bool = False, types: Optional[list[str]] = None,
195
+ to: Optional[list[str]] = None, sources: Optional[list[str]] = None) -> list[ReadEntry]:
196
+ """Consumer-side guardrail, applied with plain code before any model reads an entry.
197
+ Type patterns ending in "." match prefixes ("exception."). Entries without rssa:to count as "group"."""
198
+ def type_ok(t):
199
+ return types is None or (t is not None and any(t == p or (p.endswith(".") and t.startswith(p)) for p in types))
200
+ return [r for r in entries
201
+ if (not signed_only or r.verified) and type_ok(r.entry.type)
202
+ and (to is None or (r.entry.to or "group") in to) and (sources is None or r.source in sources)]
203
+
204
+
205
+ @dataclass
206
+ class GroupRead:
207
+ policy: dict
208
+ policy_verified: bool
209
+ entries: list[ReadEntry] # newest first
210
+ problems: list[str]
211
+
212
+
213
+ def read_group(policy_url: str, fetch: Optional[Fetch] = None, reader_card: Optional[str] = None) -> GroupRead:
214
+ """Hubless group reading (open groups, two-party links, or checking a hub): fetches and
215
+ verifies the policy, reads every member feed, checks two-way membership, then applies
216
+ the group's policy in time order. Dropped entries are listed in `problems` with the reason."""
217
+ from datetime import datetime as _dt
218
+
219
+ from .policy import check_entry, effective_settings, verify_policy
220
+
221
+ ua = f"{USER_AGENT} reader={reader_card}" if reader_card else USER_AGENT
222
+ fetch = fetch or (lambda u: http_get(u, accept="application/atom+xml, application/rss+xml, application/feed+json, application/json", user_agent=ua))
223
+ policy = get_json(policy_url, fetch)
224
+ problems: list[str] = []
225
+ pok, perr = verify_policy(policy, fetch)
226
+ if not pok:
227
+ problems.append(f"policy signature: {perr}")
228
+ s = effective_settings(policy)
229
+ refs = {policy.get("group"), policy_url}
230
+ every: list[ReadEntry] = []
231
+ for m in policy.get("members", []):
232
+ try:
233
+ fr = read_feed(m["feed"], fetch=fetch, require_signatures=s["signatures"] == "required" or None)
234
+ except Exception as e: # noqa: BLE001
235
+ problems.append(f"{m['feed']}: {e}")
236
+ continue
237
+ groups = (((find_rssa(fr.card) or {}).get("params")) or {}).get("groups") or []
238
+ if not refs & set(groups):
239
+ problems.append(f"{m['feed']}: its Agent Card does not list this group — not a member (two-way membership)")
240
+ continue
241
+ problems += [f"{m['feed']}: {p}" for p in fr.problems]
242
+ every += fr.entries
243
+ ts = lambda r: _dt.fromisoformat(r.entry.updated.replace("Z", "+00:00")).timestamp()
244
+ every.sort(key=ts)
245
+ depth: dict[str, int] = {}
246
+ root: dict[str, str] = {}
247
+ last: dict[str, float] = {}
248
+ kept: list[ReadEntry] = []
249
+ for r in every:
250
+ e = r.entry
251
+ v = check_entry(e, r.source, s, depth_of=depth.get, root_of=root.get, last_post=lambda f, rt: last.get(f"{f} {rt}"))
252
+ if v:
253
+ problems.append(f"dropped {e.id}: " + "; ".join(m for _, m in v))
254
+ continue
255
+ d = depth.get(e.in_reply_to, 0) + 1 if e.in_reply_to else 0
256
+ rt = root.get(e.in_reply_to, e.in_reply_to) if e.in_reply_to else e.id
257
+ depth[e.id], root[e.id] = d, rt
258
+ last[f"{r.source} {rt}"] = ts(r)
259
+ kept.append(r)
260
+ return GroupRead(policy, pok, list(reversed(kept)), problems)