botvow 0.1.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.
@@ -0,0 +1,129 @@
1
+ Metadata-Version: 2.4
2
+ Name: botvow
3
+ Version: 0.1.0
4
+ Summary: Create and verify co-signed BotVow receipts for agent-to-agent deliveries.
5
+ Author: BotVow contributors
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://botvow.org
8
+ Project-URL: Repository, https://github.com/Santiago1971/botvow
9
+ Project-URL: Issues, https://github.com/Santiago1971/botvow/issues
10
+ Project-URL: Documentation, https://github.com/Santiago1971/botvow#readme
11
+ Keywords: mcp,a2a,agents,receipts,ed25519
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Environment :: Console
20
+ Classifier: Intended Audience :: Developers
21
+ Classifier: Topic :: Security
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: cryptography>=41
26
+ Provides-Extra: schema
27
+ Requires-Dist: jsonschema>=4; extra == "schema"
28
+ Dynamic: license-file
29
+
30
+ <p align="center"><img src="assets/botvow-logo.jpg" alt="BotVow logo: an outlined cube with an orange seal and a check mark" width="520"></p>
31
+
32
+ # BotVow — the black box for Bots
33
+
34
+ <!-- mcp-name: io.github.Santiago1971/botvow -->
35
+
36
+ **BotVow ("the bot's vow") is an open, tamper-evident record of what two Bots agreed: who agreed what, who authorised it, and when — co-signed by both and verifiable by anyone with nothing but public keys.**
37
+
38
+ - **Bot 2 Bot at the core.** BotVow is built first for Bots recording the agreements they make with each other.
39
+ - **An open door, with the same rules.** Agents from other AI platforms (OpenAI, Google, Anthropic, open source, …) may also record agreements in the black box — but only by following exactly the same rules. No own rules, no extensions that change the rules, no exceptions. The verifier rejects anything else, even if every party signed it.
40
+ - **Tiny and open.** One JSON format, one ~200-line verifier, Ed25519 + SHA-256. No account, no central server, no blockchain. MIT code, CC BY 4.0 spec, and a [no-patent pledge](NO-PATENT.md).
41
+
42
+ > **What this is not.** BotVow is evidence, not a notary, a timestamping authority or a contract. It shows that the listed keys signed the listed content in the listed order. It does not prove who controls a key, that every message was recorded, or that a summary is true.
43
+
44
+ ## Install
45
+
46
+ ```bash
47
+ pip install botvow # or: pipx install botvow
48
+ botvow verify examples/bot2bot-log.json
49
+ botvow-mcp # local MCP server on stdio (also: uvx botvow)
50
+ ```
51
+
52
+ The package exposes two console scripts: `botvow` (CLI) and `botvow-mcp` (MCP server). With no arguments, `botvow` starts the MCP server, so `uvx botvow` and `pipx run botvow` speak MCP on stdio. Subcommands (`keygen`, `create`, `sign`, `verify`, `demo`, `mcp`) still run the CLI.
53
+
54
+ ## 30-second example: create and verify a receipt
55
+
56
+ Two parties, one file, one receipt. Only the SHA-256 of the file is stored, not the file itself. Keep the private keys on this machine.
57
+
58
+ ```bash
59
+ pip install -r requirements.txt
60
+
61
+ python3 tools/botvow.py keygen --name "Inspector Demo Bot (fictional)" --out /tmp/inspector.key.json
62
+ python3 tools/botvow.py keygen --name "Client Demo Bot (fictional)" --out /tmp/client.key.json
63
+
64
+ python3 tools/botvow.py create --key /tmp/inspector.key.json --key /tmp/client.key.json --payload examples/two-agents/inspection-report.txt --summary "Inspector Demo Bot delivered the inspection report to Client Demo Bot." --out /tmp/receipt.json
65
+
66
+ python3 tools/botvow.py verify /tmp/receipt.json
67
+ # VERIFY OK
68
+ # head <64 hex characters>
69
+ ```
70
+
71
+ When the two keys are on different machines, each party keeps only their own key. See [`examples/two-agents/run.sh`](examples/two-agents/run.sh). Agents can call the same steps through the local MCP server: `python3 tools/mcp_server.py` (`create_vow`, `verify_vow`). Instructions: [AGENTS.md](AGENTS.md), [llms.txt](llms.txt). Policy: [POLICY.md](POLICY.md).
72
+
73
+ ## Quick start (built-in samples)
74
+
75
+ ```bash
76
+ ./run_demo.sh # build samples, verify, tamper tests, same-rules tests, unit tests, schema
77
+ python3 tools/botvow.py verify examples/bot2bot-log.json # VERIFY OK, exit 0
78
+ python3 tools/botvow.py verify examples/open-door-log.json # VERIFY OK (Bot + agent of another AI)
79
+ python3 tools/botvow.py verify examples/bot2bot-log-tampered.json # REJECTED, exit 1
80
+ python3 tools/botvow.py verify examples/open-door-own-rules-rejected.json # REJECTED: own rules not allowed
81
+ python3 tools/botvow.py verify LOG.json --head <hex> # also compare with a published head hash
82
+ ```
83
+
84
+ ## How it works
85
+
86
+ | Element | Rule |
87
+ |---|---|
88
+ | Chain | Ordered JSON entries, each with exactly the fields in [`schema/record.schema.json`](schema/record.schema.json) |
89
+ | `genesis` | Entry 0. Lists the parties (key id, name, Ed25519 public key, `kind`: `bot` or `agent`, optional platform and A2A Agent Card). Signed by all parties |
90
+ | Other entries | `proposal`, `counter`, `agreement`, `amendment`, `termination`, `seal` — nothing else |
91
+ | Co-signing | `genesis`, `agreement` and `seal` must be signed by **all** parties |
92
+ | Hash chain | `prev_hash` links every entry to the previous one; `entry_hash` covers content and signatures |
93
+ | Same rules | `own_rules`, `exceptions`, `rules_override`… are rejected, unknown types and extra fields too |
94
+ | Privacy | Raw messages are never stored, only their SHA-256; summaries only with both parties' consent |
95
+
96
+ Full rules: [SPEC.md](SPEC.md). Policy: [POLICY.md](POLICY.md). Plans: [ROADMAP.md](ROADMAP.md). Overview: [docs/overview.md](docs/overview.md).
97
+
98
+ ### Tests in `run_demo.sh`
99
+ Bot 2 Bot log verifies · privacy (no raw messages) · selective disclosure · edit · edit + rehash · delete · reorder · outsider key · drop seal · single signature · edit genesis · **open door: Bot + agent of another AI verifies** · **agent adds its own rules/exceptions (even co-signed): rejected** · **agent invents its own entry type/field: rejected** — plus unit tests in `tests/` and the two-agent delivery example in `examples/two-agents/`.
100
+
101
+ ## Samples
102
+ All parties and keys are **fictional**. Demo keys come from fixed public seeds so the output is reproducible — **never use them for anything real**.
103
+
104
+ ## Works with A2A, MCP and HTTPS
105
+ A BotVow chain is just JSON, so it can travel as A2A task metadata, be produced and checked by an MCP tool, or be posted over plain HTTPS. Parties can link their key to an A2A Agent Card.
106
+
107
+ A local MCP server (`botvow-mcp`, or `python3 tools/mcp_server.py`) exposes `create_vow` and `verify_vow` over stdio. It does not keep receipts for you: you keep the JSON, and you can verify it later without the server. The Agent Card is at [agent-card.json](agent-card.json) and at https://botvow.org/.well-known/agent-card.json.
108
+
109
+ ## Modules
110
+
111
+ Two optional modules live under [`modules/`](modules/). They are not part of the verifier; they are small, standard-library tools that work with the same agent formats BotVow already mentions (A2A, MCP, email).
112
+
113
+ - **[Protocol translator](modules/translator/)** — rewrite a request, response, error or task between MCP, A2A 1.0, A2A 0.3 and plain email, without ever executing it. 18 tests in `modules/translator/tests/`.
114
+ - **[Local Agent Card](modules/agent-card/)** — a small profile (`local-agent-card/0.1`) so a shop, café or lodging can publish hours, dated prices and booking rules, and export them to an A2A Agent Card, schema.org JSON-LD and llms.txt. The two example cards are **FICTIONAL** and labelled as such. 10 tests in `modules/agent-card/tests/`.
115
+
116
+ ## Related work
117
+
118
+ BotVow builds on, and is narrower than, existing work: Google AP2 mandates (payments), A2A signed Agent Cards, IETF drafts on co-signed agent agreements and bilateral attestation, the Open Agent Protocol, and agent-receipt projects. See [docs/overview.md](docs/overview.md) for links.
119
+
120
+ ## Licence
121
+ Code: MIT. Specification, docs, schema and examples: CC BY 4.0. See [LICENSE](LICENSE) and [NO-PATENT.md](NO-PATENT.md).
122
+
123
+ ---
124
+
125
+ ## Em português
126
+
127
+ O **BotVow** («a promessa do bot») é a caixa negra dos Bots: um registo Bot 2 Bot, inalterável e verificável, do que dois Bots combinam (quem combinou o quê, quem autorizou e quando), assinado pelos dois. Os Bots são o núcleo. Agentes de outras IA também podem registar acordos, mas **têm de seguir as mesmas regras**, sem regras próprias nem exceções; o verificador recusa tudo o resto. Documento do projeto: [docs/projeto-botvow.md](docs/projeto-botvow.md).
128
+
129
+ This project continues the earlier prototype [Santiago1971/agent-agreement-black-box](https://github.com/Santiago1971/agent-agreement-black-box).
@@ -0,0 +1,9 @@
1
+ botvow.py,sha256=RiKY2x8EnhoYqsfIiKJfe4WmH7p5VNsX1X6doS4WrnE,33691
2
+ check_schema.py,sha256=q4dPFOs6RAWkfiM98EMhS-sJqgCWDWiv2YuJbdtKbA4,591
3
+ mcp_server.py,sha256=6xXOuJeOE1lKSUbISgFAQ70tu_YHCpqkIQFH5gwYetA,11162
4
+ botvow-0.1.0.dist-info/licenses/LICENSE,sha256=nRZdg1tcgQ5J5UEe1JetpjRZ54guRfjPLhfLJOX53VY,1642
5
+ botvow-0.1.0.dist-info/METADATA,sha256=kfUj0RMCjdK-ESH5hQzZhvc_GT-SgMEc6TOWWGs_jmE,8873
6
+ botvow-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ botvow-0.1.0.dist-info/entry_points.txt,sha256=xYXcG-IapzBxIOHo7VkB4tVdKcZMM2N4MleFXgeM12E,68
8
+ botvow-0.1.0.dist-info/top_level.txt,sha256=pAT21IphDIOeFU35I41N-KMu3wS4Kxp2gFT_rUjL4hE,31
9
+ botvow-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ botvow = botvow:main
3
+ botvow-mcp = mcp_server:main
@@ -0,0 +1,29 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 BotVow contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ ---------------------------------------------------------------------------
24
+ Scope: the MIT License above covers the code (tools/, tests/, modules/, run_demo.sh, Dockerfile).
25
+ The specification, documentation, schema and example data (README.md, SPEC.md, POLICY.md,
26
+ AGENTS.md, llms.txt, NO-PATENT.md, docs/, schema/, examples/, assets/, agent-card.json,
27
+ server.json, glama.json) are licensed under Creative Commons
28
+ Attribution 4.0 International (CC BY 4.0): https://creativecommons.org/licenses/by/4.0/
29
+ Attribution: "BotVow (https://github.com/Santiago1971/botvow)".
@@ -0,0 +1,3 @@
1
+ botvow
2
+ check_schema
3
+ mcp_server
botvow.py ADDED
@@ -0,0 +1,635 @@
1
+ #!/usr/bin/env python3
2
+ """BotVow - reference tool for spec botvow/0.1 ("the bot's vow").
3
+
4
+ The black box for Bots: a hash-chained, Ed25519 co-signed record of what two Bots agreed.
5
+ Bots are the core. Agents from other AI platforms may also record agreements, but only
6
+ under exactly the same rules - no own rules, no extensions that change the rules, no exceptions.
7
+
8
+ Usage:
9
+ python3 tools/botvow.py keygen --name NAME --out FILE.key.json
10
+ python3 tools/botvow.py pubkey --key FILE.key.json --out FILE.pub.json
11
+ python3 tools/botvow.py create --key A.key.json --key B.key.json --payload FILE --summary TEXT --out receipt.json
12
+ python3 tools/botvow.py sign --key FILE.key.json --in receipt.json --out receipt.json
13
+ python3 tools/botvow.py verify FILE [--head HEX] # exit 0 = VERIFY OK, exit 1 = REJECTED
14
+ python3 tools/botvow.py demo # write examples/*.json and run all tests
15
+
16
+ Private keys stay in the local key file. They are never written into a receipt.
17
+
18
+ Licence: MIT (see LICENSE).
19
+ """
20
+ import argparse, base64, copy, hashlib, json, os, re, sys
21
+ from datetime import datetime, timezone
22
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
23
+ from cryptography.hazmat.primitives import serialization
24
+ from cryptography.exceptions import InvalidSignature
25
+
26
+ SPEC = "botvow/0.1"
27
+ HERE = os.path.dirname(os.path.abspath(__file__))
28
+ EXAMPLES = os.path.join(HERE, "..", "examples")
29
+ GENESIS_PREV = "0" * 64
30
+ ENTRY_KEYS = {"spec", "chain_id", "seq", "prev_hash", "ts", "type", "author", "content", "signatures", "entry_hash"}
31
+ TYPES = {"genesis", "proposal", "counter", "agreement", "amendment", "termination", "seal"}
32
+ CO_SIGNED = {"genesis", "agreement", "seal"}
33
+ PARTY_KEYS = {"kid", "name", "pubkey", "kind", "platform", "agent_card"}
34
+ PARTY_KINDS = {"bot", "agent"} # "bot" = core; "agent" = agent from another AI platform
35
+ FORBIDDEN_CONTENT_KEYS = {"rules", "own_rules", "exceptions", "exception", "rules_override", "policy_override"}
36
+ SIG_KEYS = {"kid", "alg", "sig"}
37
+
38
+ def b64u(b): return base64.urlsafe_b64encode(b).rstrip(b"=").decode()
39
+ def ub64u(s): return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
40
+
41
+ def canon(obj):
42
+ """Canonical JSON (strict subset of RFC 8785: sorted keys, no spaces, UTF-8, no floats)."""
43
+ return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
44
+
45
+ def sha256_hex(b): return hashlib.sha256(b).hexdigest()
46
+ def body_of(e): return {k: v for k, v in e.items() if k not in ("signatures", "entry_hash")}
47
+ def entry_hash(e): return sha256_hex(canon({k: v for k, v in e.items() if k != "entry_hash"}))
48
+ def pub_raw(priv): return priv.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)
49
+ def kid_of(pub_bytes): return "ed25519:" + sha256_hex(pub_bytes)[:16]
50
+ def demo_key(seed): return Ed25519PrivateKey.from_private_bytes(hashlib.sha256(seed.encode()).digest())
51
+
52
+ def sign(e, priv):
53
+ e.setdefault("signatures", []).append({"kid": kid_of(pub_raw(priv)), "alg": "Ed25519", "sig": b64u(priv.sign(canon(body_of(e))))})
54
+
55
+ def make_entry(chain, seq, prev, ts, etype, author, content, signers):
56
+ e = {"spec": SPEC, "chain_id": chain, "seq": seq, "prev_hash": prev, "ts": ts, "type": etype, "author": author, "content": content}
57
+ for p in signers: sign(e, p)
58
+ e["entry_hash"] = entry_hash(e)
59
+ return e
60
+
61
+ def has_float(x):
62
+ if isinstance(x, float): return True
63
+ if isinstance(x, dict): return any(has_float(v) for v in x.values())
64
+ if isinstance(x, list): return any(has_float(v) for v in x)
65
+ return False
66
+
67
+ def build_chain(parties, steps, label):
68
+ """parties: list of (priv, name, kind, platform). steps: list of (ts, type, author_index, content, signer_indexes)."""
69
+ privs = [p[0] for p in parties]
70
+ chain = "demo-" + sha256_hex(b"".join(pub_raw(k) for k in privs) + label.encode())[:12]
71
+ plist = [{"kid": kid_of(pub_raw(k)), "name": n, "pubkey": b64u(pub_raw(k)), "kind": kind, "platform": plat}
72
+ for k, n, kind, plat in parties]
73
+ log = [make_entry(chain, 0, GENESIS_PREV, steps[0][0], "genesis", plist[0]["kid"],
74
+ {"purpose": label, "parties": plist,
75
+ "privacy": "hashes-only for raw messages; summaries only with consent of both parties"}, privs)]
76
+ for ts, etype, a, content, signers in steps[1:]:
77
+ prev = log[-1]
78
+ log.append(make_entry(chain, prev["seq"] + 1, prev["entry_hash"], ts, etype, plist[a]["kid"], content, [privs[i] for i in signers]))
79
+ return log
80
+
81
+ def verify(log, expected_head=None):
82
+ """Same rules for every party, Bot or agent. Returns a list of errors (empty = OK)."""
83
+ errors = []
84
+ if not isinstance(log, list) or not log: return ["empty log"]
85
+ g = log[0]
86
+ if g.get("type") != "genesis" or g.get("seq") != 0 or g.get("prev_hash") != GENESIS_PREV:
87
+ errors.append("entry 0 is not a valid genesis")
88
+ keys, kinds = {}, {}
89
+ for p in g.get("content", {}).get("parties", []):
90
+ if set(p) - PARTY_KEYS: errors.append(f"genesis: party {p.get('name')} has fields outside the BotVow rules: {sorted(set(p) - PARTY_KEYS)}")
91
+ if p.get("kind", "bot") not in PARTY_KINDS: errors.append(f"genesis: party kind {p.get('kind')!r} not allowed")
92
+ try:
93
+ raw = ub64u(p["pubkey"])
94
+ if kid_of(raw) != p["kid"]: errors.append(f"genesis: kid {p['kid']} does not match its pubkey")
95
+ keys[p["kid"]] = Ed25519PublicKey.from_public_bytes(raw); kinds[p["kid"]] = p.get("kind", "bot")
96
+ except Exception:
97
+ errors.append("genesis: invalid party key")
98
+ if len(keys) < 2: errors.append("genesis: needs at least two parties")
99
+ parties = set(keys)
100
+ prev = None
101
+ for i, e in enumerate(log):
102
+ tag = f"entry {i} ({e.get('type')})"
103
+ if set(e) != ENTRY_KEYS: errors.append(f"{tag}: fields differ from the BotVow rules (extra: {sorted(set(e) - ENTRY_KEYS)}, missing: {sorted(ENTRY_KEYS - set(e))})")
104
+ if e.get("spec") != SPEC: errors.append(f"{tag}: unknown spec {e.get('spec')!r}")
105
+ if e.get("type") not in TYPES: errors.append(f"{tag}: entry type not allowed by the BotVow rules")
106
+ if e.get("chain_id") != g.get("chain_id"): errors.append(f"{tag}: chain_id mismatch (splice?)")
107
+ if e.get("seq") != i: errors.append(f"{tag}: seq {e.get('seq')} != position {i} (deleted/reordered entry)")
108
+ if not re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ", str(e.get("ts", ""))): errors.append(f"{tag}: ts must be RFC 3339 UTC (…Z)")
109
+ if i > 0 and prev is not None and e.get("prev_hash") != prev.get("entry_hash"):
110
+ errors.append(f"{tag}: prev_hash does not match hash of entry {i-1} (broken chain)")
111
+ if entry_hash(e) != e.get("entry_hash"): errors.append(f"{tag}: entry_hash does not match content (entry was modified)")
112
+ c = e.get("content", {})
113
+ if not isinstance(c, dict): errors.append(f"{tag}: content must be an object"); c = {}
114
+ bad = FORBIDDEN_CONTENT_KEYS & set(c)
115
+ if bad: errors.append(f"{tag}: own rules or exceptions are not allowed ({sorted(bad)}) - every party follows the same BotVow rules")
116
+ if has_float(e): errors.append(f"{tag}: floating-point numbers are not allowed (canonical form)")
117
+ signed_by = set(); msg = canon(body_of(e))
118
+ for s in e.get("signatures", []):
119
+ if set(s) != SIG_KEYS: errors.append(f"{tag}: signature fields differ from the rules")
120
+ k = keys.get(s.get("kid"))
121
+ if k is None or s.get("alg") != "Ed25519":
122
+ errors.append(f"{tag}: signature by unknown key or algorithm {s.get('kid')}"); continue
123
+ try: k.verify(ub64u(s["sig"]), msg); signed_by.add(s["kid"])
124
+ except Exception: errors.append(f"{tag}: INVALID signature by {s['kid']}")
125
+ if e.get("author") not in signed_by: errors.append(f"{tag}: author did not sign")
126
+ if e.get("type") in CO_SIGNED and signed_by != parties: errors.append(f"{tag}: needs signatures of ALL parties")
127
+ if "summary" in c:
128
+ if c.get("consent_to_publish_summary") is not True: errors.append(f"{tag}: summary without consent of both parties")
129
+ if sha256_hex(str(c["summary"]).encode()) != c.get("summary_sha256"): errors.append(f"{tag}: summary does not match summary_sha256")
130
+ if i > 0 and prev is not None and prev.get("type") == "seal": errors.append(f"{tag}: nothing may follow a seal")
131
+ prev = e
132
+ if log[-1].get("type") != "seal": errors.append("last entry is not a seal (log may be truncated)")
133
+ elif log[-1].get("content", {}).get("entries") != len(log) - 1: errors.append("seal entry count does not match")
134
+ if expected_head and log[-1].get("entry_hash") != expected_head:
135
+ errors.append("head hash differs from the published head (truncation or fork)")
136
+ return errors
137
+
138
+ def summary(text, **extra):
139
+ d = {"summary": text, "summary_sha256": sha256_hex(text.encode()), "consent_to_publish_summary": True}
140
+ d.update(extra); return d
141
+
142
+ def build_bot2bot():
143
+ # DEMO KEYS ONLY - fixed public seeds for reproducible output. Never use for anything real.
144
+ buyer, supplier = demo_key("botvow-demo-restaurant-bot"), demo_key("botvow-demo-supplier-bot")
145
+ raw = {"proposal": "Restaurant Bot: 20 kg of fictional olive oil, delivery Friday?",
146
+ "counter": "Supplier Bot: yes, delivery Friday 10:00-12:00, price as per list of 2026-11-12."}
147
+ log = build_chain(
148
+ [(buyer, "Restaurant Demo Bot (fictional)", "bot", "bot"), (supplier, "Supplier Demo Bot (fictional)", "bot", "bot")],
149
+ [("2026-11-12T22:00:00Z", "genesis", 0, None, None),
150
+ ("2026-11-12T22:01:00Z", "proposal", 0, {"payload_sha256": sha256_hex(raw["proposal"].encode())}, [0]),
151
+ ("2026-11-12T22:02:00Z", "counter", 1, {"payload_sha256": sha256_hex(raw["counter"].encode())}, [1]),
152
+ ("2026-11-12T22:03:00Z", "agreement", 0, summary("Supplier Demo Bot delivers 20 kg of fictional olive oil to Restaurant Demo Bot on Friday between 10:00 and 12:00, at the list price of 2026-11-12. Either party may cancel in this chain before Thursday 18:00 UTC.", valid_until="2026-11-20", authorized_by="human owner of each bot (reference kept privately)"), [0, 1]),
153
+ ("2026-11-12T22:04:00Z", "seal", 1, {"entries": 4, "note": "chain closed by both Bots"}, [0, 1])],
154
+ "Bot 2 Bot agreement between two fictional demo Bots")
155
+ return log, raw
156
+
157
+ def build_open_door():
158
+ bot, agent = demo_key("botvow-demo-booking-bot"), demo_key("botvow-demo-other-ai-agent")
159
+ log = build_chain(
160
+ [(bot, "Guesthouse Demo Bot (fictional)", "bot", "bot"), (agent, "Traveller Demo Agent (fictional, another AI platform)", "agent", "other-ai")],
161
+ [("2026-11-12T22:10:00Z", "genesis", 0, None, None),
162
+ ("2026-11-12T22:11:00Z", "proposal", 1, {"payload_sha256": sha256_hex(b"Agent: one room, 2 nights, free cancellation?")}, [1]),
163
+ ("2026-11-12T22:12:00Z", "agreement", 0, summary("Guesthouse Demo Bot holds one room for 2 nights for the Traveller Demo Agent's user; free cancellation until 48 hours before arrival.", valid_until="2026-12-31"), [0, 1]),
164
+ ("2026-11-12T22:13:00Z", "seal", 0, {"entries": 3}, [0, 1])],
165
+ "Open door: a Bot and an agent from another AI platform, same rules")
166
+ return log, (bot, agent)
167
+
168
+ def report(name, log, head=None, expect_ok=True):
169
+ errs = verify(log, head); ok = not errs
170
+ print(f"[{'PASS' if ok == expect_ok else 'UNEXPECTED'}] {name}: {'VERIFY OK' if ok else 'REJECTED'}")
171
+ for e in errs: print(" -", e)
172
+ return ok == expect_ok
173
+
174
+ def rehash_resign(entry, signers):
175
+ entry["signatures"] = []
176
+ for p in signers: sign(entry, p)
177
+ entry["entry_hash"] = entry_hash(entry)
178
+
179
+ def demo():
180
+ os.makedirs(EXAMPLES, exist_ok=True)
181
+ def write(name, obj):
182
+ with open(os.path.join(EXAMPLES, name), "w", encoding="utf-8") as f:
183
+ json.dump(obj, f, indent=2, ensure_ascii=False); f.write("\n")
184
+ log, raw = build_bot2bot(); write("bot2bot-log.json", log)
185
+ tampered = copy.deepcopy(log); tampered[3]["content"]["valid_until"] = "2027-11-20"; write("bot2bot-log-tampered.json", tampered)
186
+ head = log[-1]["entry_hash"]
187
+ print(f"Spec {SPEC}\nBot 2 Bot sample: examples/bot2bot-log.json ({len(log)} entries), head {head}\n")
188
+ r = [report("1. Bot 2 Bot original log", log, head, True)]
189
+ leaked = any(p in json.dumps(log, ensure_ascii=False) for p in raw.values())
190
+ print(f"[{'PASS' if not leaked else 'UNEXPECTED'}] privacy: raw messages stored? {leaked}"); r.append(not leaked)
191
+ m = sha256_hex(raw["proposal"].encode()) == log[1]["content"]["payload_sha256"]
192
+ print(f"[{'PASS' if m else 'UNEXPECTED'}] selective disclosure: revealed proposal matches its hash? {m}\n"); r.append(m)
193
+ t = copy.deepcopy(log); t[3]["content"]["valid_until"] = "2027-11-20"; r.append(report("2. edit agreement (no re-sign)", t, head, False))
194
+ t = copy.deepcopy(log); t[3]["content"]["valid_until"] = "2027-11-20"; t[3]["entry_hash"] = entry_hash(t[3]); r.append(report("3. edit and recompute entry_hash", t, head, False))
195
+ t = copy.deepcopy(log); del t[2]; r.append(report("4. delete the counter-proposal", t, head, False))
196
+ t = copy.deepcopy(log); t[1], t[2] = t[2], t[1]; r.append(report("5. reorder entries", t, head, False))
197
+ mallory = demo_key("mallory")
198
+ t = copy.deepcopy(log); t[3]["content"]["valid_until"] = "2027-11-20"; rehash_resign(t[3], [mallory]); r.append(report("6. rewrite and sign with an outsider key", t, head, False))
199
+ r.append(report("7. truncate (drop seal)", copy.deepcopy(log)[:4], None, False))
200
+ t = copy.deepcopy(log); t[3]["signatures"] = t[3]["signatures"][:1]; t[3]["entry_hash"] = entry_hash(t[3]); r.append(report("8. agreement with one signature only", t, None, False))
201
+ t = copy.deepcopy(log); t[0]["content"]["purpose"] = "Something else"; r.append(report("9. edit the genesis", t, None, False))
202
+
203
+ print("\n--- Open door: agents from other AI platforms follow the same rules ---")
204
+ od, (bot, agent) = build_open_door(); write("open-door-log.json", od)
205
+ r.append(report("10. Bot + agent of another AI, same rules", od, None, True))
206
+ # 11. The agent adds its own rules / exceptions, and BOTH parties re-sign: still rejected.
207
+ t = copy.deepcopy(od); t[2]["content"]["own_rules"] = {"cancellation": "agent may cancel any time"}; t[2]["content"]["exceptions"] = ["skip co-signature"]
208
+ rehash_resign(t[2], [bot, agent])
209
+ for j in (3,):
210
+ t[j]["prev_hash"] = t[j-1]["entry_hash"]; rehash_resign(t[j], [bot, agent])
211
+ write("open-door-own-rules-rejected.json", t)
212
+ r.append(report("11. agent brings its own rules/exceptions (even co-signed)", t, None, False))
213
+ # 12. The agent invents its own entry type and an extra top-level field, signs alone.
214
+ t = copy.deepcopy(od); t[2]["type"] = "agent_custom_commitment"; t[2]["rules_override"] = "platform-specific"; t[2]["author"] = kid_of(pub_raw(agent))
215
+ rehash_resign(t[2], [agent]); t[3]["prev_hash"] = t[2]["entry_hash"]; rehash_resign(t[3], [bot, agent])
216
+ r.append(report("12. agent invents its own entry type and field", t, None, False))
217
+ print(f"\nSUMMARY: {sum(r)}/{len(r)} checks behaved as expected")
218
+ return all(r)
219
+
220
+
221
+ # --- Create and sign (private keys never enter the receipt) ---
222
+
223
+ KEY_FILE_FIELDS = ("spec", "kid", "name", "kind", "platform", "agent_card", "pubkey", "privkey")
224
+
225
+ def utc_now():
226
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
227
+
228
+ def priv_from_b64(s):
229
+ return Ed25519PrivateKey.from_private_bytes(ub64u(s))
230
+
231
+ def key_record(priv, name, kind="bot", platform="bot", agent_card=None):
232
+ raw = pub_raw(priv)
233
+ rec = {
234
+ "spec": "botvow/0.1-key",
235
+ "kid": kid_of(raw),
236
+ "name": name,
237
+ "kind": kind,
238
+ "platform": platform,
239
+ "pubkey": b64u(raw),
240
+ "privkey": b64u(priv.private_bytes(serialization.Encoding.Raw, serialization.PrivateFormat.Raw, serialization.NoEncryption())),
241
+ }
242
+ if agent_card:
243
+ rec["agent_card"] = agent_card
244
+ return rec
245
+
246
+ def public_party(rec):
247
+ party = {"kid": rec["kid"], "name": rec["name"], "pubkey": rec["pubkey"]}
248
+ if rec.get("kind"):
249
+ party["kind"] = rec["kind"]
250
+ if rec.get("platform"):
251
+ party["platform"] = rec["platform"]
252
+ if rec.get("agent_card"):
253
+ party["agent_card"] = rec["agent_card"]
254
+ return party
255
+
256
+ def write_json(path, obj, mode=0o644):
257
+ directory = os.path.dirname(os.path.abspath(path))
258
+ if directory:
259
+ os.makedirs(directory, exist_ok=True)
260
+ tmp = path + ".tmp"
261
+ with open(tmp, "w", encoding="utf-8") as f:
262
+ json.dump(obj, f, indent=2, ensure_ascii=False)
263
+ f.write("\n")
264
+ os.replace(tmp, path)
265
+ os.chmod(path, mode)
266
+
267
+ def load_json(path):
268
+ with open(path, encoding="utf-8") as f:
269
+ return json.load(f)
270
+
271
+ def load_party_file(path, need_private=False):
272
+ rec = load_json(path)
273
+ if "pubkey" not in rec or "kid" not in rec or "name" not in rec:
274
+ raise ValueError(f"{path}: not a BotVow key or party file (need kid, name, pubkey)")
275
+ if "privkey" in rec:
276
+ priv = priv_from_b64(rec["privkey"])
277
+ raw = pub_raw(priv)
278
+ if rec["pubkey"] != b64u(raw) or rec["kid"] != kid_of(raw):
279
+ raise ValueError(f"{path}: kid or pubkey does not match the private key")
280
+ rec["_priv"] = priv
281
+ elif need_private:
282
+ raise ValueError(f"{path}: this file has no private key (use a .key.json from keygen, not a .pub.json)")
283
+ return rec
284
+
285
+ def payload_sha256_from(path=None, digest=None, data=None):
286
+ if digest:
287
+ if not re.fullmatch(r"[0-9a-f]{64}", digest):
288
+ raise ValueError("payload SHA-256 must be 64 lowercase hex characters")
289
+ return digest
290
+ if path:
291
+ with open(path, "rb") as f:
292
+ return sha256_hex(f.read())
293
+ if data is not None:
294
+ if isinstance(data, str):
295
+ data = data.encode("utf-8")
296
+ return sha256_hex(data)
297
+ raise ValueError("provide --payload FILE or --payload-sha256 HEX (never the raw content of the receipt)")
298
+
299
+ def chain_id_for(parties, purpose):
300
+ blob = b"".join(ub64u(p["pubkey"]) for p in parties) + purpose.encode("utf-8")
301
+ return "bv-" + sha256_hex(blob)[:12]
302
+
303
+ def signed_kids(entry):
304
+ return {s.get("kid") for s in entry.get("signatures", [])}
305
+
306
+ def needs_all_signatures(entry):
307
+ return entry.get("type") in CO_SIGNED
308
+
309
+ def missing_signers(entry, party_kids):
310
+ have = signed_kids(entry)
311
+ if needs_all_signatures(entry):
312
+ return [k for k in party_kids if k not in have]
313
+ author = entry.get("author")
314
+ return [author] if author and author not in have else []
315
+
316
+ def add_signature(entry, priv):
317
+ kid = kid_of(pub_raw(priv))
318
+ if kid in signed_kids(entry):
319
+ return False
320
+ sign(entry, priv)
321
+ entry["entry_hash"] = entry_hash(entry)
322
+ return True
323
+
324
+ def receipt_status(log):
325
+ if not log:
326
+ return {"complete": False, "next": "genesis", "errors": ["empty log"]}
327
+ parties = [p["kid"] for p in log[0].get("content", {}).get("parties", [])]
328
+ last = log[-1]
329
+ missing = missing_signers(last, parties) if last else parties
330
+ if missing:
331
+ return {"complete": False, "next": "sign", "missing_kids": missing, "errors": verify(log)}
332
+ if last.get("type") != "seal":
333
+ nxt = {"genesis": "proposal", "proposal": "agreement", "counter": "agreement", "agreement": "seal", "amendment": "seal", "termination": "seal"}.get(last.get("type"), "unknown")
334
+ return {"complete": False, "next": nxt, "errors": verify(log)}
335
+ errs = verify(log)
336
+ return {"complete": not errs, "next": "done" if not errs else "fix", "errors": errs}
337
+
338
+ def create_vow(key_recs, peer_recs=None, payload_sha256=None, summary_text=None, purpose=None, receipt=None, ts=None):
339
+ """Create or advance a receipt. key_recs may include private keys; peer_recs are public only.
340
+
341
+ If every party's private key is present, a complete sealed receipt is written in one step.
342
+ Otherwise the chain is advanced as far as the available signatures allow; the other
343
+ party finishes it with sign_vow. The receipt never contains private keys or raw payloads.
344
+ """
345
+ peer_recs = peer_recs or []
346
+ receipt = copy.deepcopy(receipt) if receipt else []
347
+ ts = ts or utc_now()
348
+ by_kid = {}
349
+ for rec in list(peer_recs) + list(key_recs):
350
+ by_kid[rec["kid"]] = rec
351
+ if receipt:
352
+ for p in receipt[0].get("content", {}).get("parties", []):
353
+ by_kid.setdefault(p["kid"], p)
354
+ parties = [public_party(by_kid[k]) for k in by_kid]
355
+ if len(parties) < 2 and not receipt:
356
+ raise ValueError("a vow needs at least two parties (give two --key files, or --key and --peer)")
357
+ if receipt:
358
+ parties = receipt[0]["content"]["parties"]
359
+ purpose = purpose or "delivery"
360
+ privs = {rec["kid"]: rec["_priv"] for rec in key_recs if rec.get("_priv") is not None}
361
+
362
+ def signers_for(kids):
363
+ missing = [k for k in kids if k not in privs]
364
+ return [privs[k] for k in kids if k in privs], missing
365
+
366
+ if not receipt:
367
+ kids = [p["kid"] for p in parties]
368
+ present, missing = signers_for(kids)
369
+ if not present:
370
+ raise ValueError("no private key given to start the vow")
371
+ log = [make_entry(chain_id_for(parties, purpose), 0, GENESIS_PREV, ts, "genesis", kids[0],
372
+ {"purpose": purpose, "parties": parties,
373
+ "privacy": "hashes-only for raw messages; summaries only with consent of both parties"},
374
+ present)]
375
+ receipt = log
376
+
377
+ status = receipt_status(receipt)
378
+ all_privs_present = all(p["kid"] in privs for p in parties)
379
+
380
+ def append(etype, author_kid, content, required_kids):
381
+ prev = receipt[-1]
382
+ present, missing = signers_for(required_kids)
383
+ if author_kid not in privs:
384
+ raise ValueError(f"the author {author_kid} must sign, but no matching --key was given")
385
+ if author_kid not in {kid_of(pub_raw(p)) for p in present}:
386
+ present = [privs[author_kid]] + present
387
+ receipt.append(make_entry(prev["chain_id"], prev["seq"] + 1, prev["entry_hash"], utc_now(), etype, author_kid, content, present))
388
+ return missing
389
+
390
+ # One-shot: if every private key is here, finish the whole chain.
391
+ if all_privs_present:
392
+ while True:
393
+ status = receipt_status(receipt)
394
+ if status["next"] == "sign":
395
+ last = receipt[-1]
396
+ for kid in status.get("missing_kids", []):
397
+ add_signature(last, privs[kid])
398
+ continue
399
+ if status["next"] == "proposal":
400
+ if not payload_sha256:
401
+ raise ValueError("provide --payload FILE or --payload-sha256 HEX")
402
+ append("proposal", parties[0]["kid"], {"payload_sha256": payload_sha256}, [parties[0]["kid"]])
403
+ continue
404
+ if status["next"] == "agreement":
405
+ if not summary_text:
406
+ raise ValueError("provide --summary TEXT (a short description; the file itself is not stored)")
407
+ if not payload_sha256:
408
+ # reuse the hash already on the proposal if present
409
+ for e in receipt:
410
+ if e.get("type") == "proposal" and e.get("content", {}).get("payload_sha256"):
411
+ payload_sha256 = e["content"]["payload_sha256"]
412
+ break
413
+ if not payload_sha256:
414
+ raise ValueError("provide --payload FILE or --payload-sha256 HEX")
415
+ content = summary(summary_text, payload_sha256=payload_sha256)
416
+ append("agreement", parties[0]["kid"], content, [p["kid"] for p in parties])
417
+ continue
418
+ if status["next"] == "seal":
419
+ append("seal", parties[1]["kid"] if len(parties) > 1 else parties[0]["kid"],
420
+ {"entries": len(receipt), "note": "chain closed by both parties"},
421
+ [p["kid"] for p in parties])
422
+ continue
423
+ break
424
+ return receipt, receipt_status(receipt)
425
+
426
+ # Incremental: go as far as the keys we have allow, then stop for the other party.
427
+ while True:
428
+ status = receipt_status(receipt)
429
+ if status["next"] == "sign":
430
+ progressed = False
431
+ last = receipt[-1]
432
+ for kid in status.get("missing_kids", []):
433
+ if kid in privs:
434
+ add_signature(last, privs[kid])
435
+ progressed = True
436
+ if not progressed:
437
+ return receipt, status
438
+ continue
439
+ author = next((k for k in privs), None)
440
+ if status["next"] == "proposal":
441
+ if not payload_sha256:
442
+ raise ValueError("provide --payload FILE or --payload-sha256 HEX")
443
+ if not author:
444
+ raise ValueError("no private key given to write the proposal")
445
+ append("proposal", author, {"payload_sha256": payload_sha256}, [author])
446
+ continue
447
+ if status["next"] == "agreement":
448
+ if not summary_text:
449
+ raise ValueError("provide --summary TEXT (a short description; the file itself is not stored)")
450
+ if not payload_sha256:
451
+ for e in receipt:
452
+ if e.get("type") == "proposal" and e.get("content", {}).get("payload_sha256"):
453
+ payload_sha256 = e["content"]["payload_sha256"]
454
+ break
455
+ if not payload_sha256:
456
+ raise ValueError("provide --payload FILE or --payload-sha256 HEX")
457
+ if not author:
458
+ raise ValueError("no private key given to write the agreement")
459
+ content = summary(summary_text, payload_sha256=payload_sha256)
460
+ append("agreement", author, content, [author])
461
+ continue
462
+ if status["next"] == "seal":
463
+ if not author:
464
+ raise ValueError("no private key given to write the seal")
465
+ append("seal", author, {"entries": len(receipt), "note": "chain closed by both parties"}, [author])
466
+ continue
467
+ break
468
+ return receipt, receipt_status(receipt)
469
+
470
+ def sign_vow(key_rec, receipt):
471
+ if not key_rec.get("_priv"):
472
+ raise ValueError("sign needs a private key file from keygen")
473
+ if not receipt:
474
+ raise ValueError("empty receipt")
475
+ log = copy.deepcopy(receipt)
476
+ parties = [p["kid"] for p in log[0].get("content", {}).get("parties", [])]
477
+ kid = key_rec["kid"]
478
+ if kid not in parties:
479
+ raise ValueError(f"{kid} is not a party on this receipt")
480
+ last = log[-1]
481
+ missing = missing_signers(last, parties)
482
+ if kid not in missing:
483
+ return log, receipt_status(log)
484
+ add_signature(last, key_rec["_priv"])
485
+ return log, receipt_status(log)
486
+
487
+ def keygen(name, out_path, kind="bot", platform="bot", agent_card=None):
488
+ rec = key_record(Ed25519PrivateKey.generate(), name, kind=kind, platform=platform, agent_card=agent_card)
489
+ write_json(out_path, rec, mode=0o600)
490
+ pub_path = out_path[:-9] + ".pub.json" if out_path.endswith(".key.json") else out_path + ".pub.json"
491
+ write_pubkey(rec, pub_path)
492
+ return rec, pub_path
493
+
494
+ def write_pubkey(rec, path):
495
+ pub = public_party(rec)
496
+ pub["spec"] = "botvow/0.1-pub"
497
+ write_json(path, pub, mode=0o644)
498
+ return pub
499
+
500
+ def cmd_keygen(args):
501
+ rec, pub_path = keygen(args.name, args.out, kind=args.kind, platform=args.platform, agent_card=args.agent_card)
502
+ print(f"private key written to {args.out} (mode 600). public key written to {pub_path}.")
503
+ print(f"kid {rec['kid']}")
504
+ print("Keep the private key on this machine. Never put it in a receipt, a chat, or a repository.")
505
+ return 0
506
+
507
+ def cmd_pubkey(args):
508
+ rec = load_party_file(args.key, need_private=False)
509
+ write_pubkey(rec, args.out)
510
+ print(f"public party file written to {args.out}")
511
+ return 0
512
+
513
+ def _load_keys(paths, need_private):
514
+ return [load_party_file(p, need_private=need_private) for p in paths]
515
+
516
+ def cmd_create(args):
517
+ keys = _load_keys(args.key, need_private=True)
518
+ peers = _load_keys(args.peer or [], need_private=False)
519
+ receipt = load_json(args.receipt_in) if args.receipt_in else []
520
+ digest = payload_sha256_from(path=args.payload, digest=args.payload_sha256) if (args.payload or args.payload_sha256) else None
521
+ receipt, status = create_vow(
522
+ keys, peer_recs=peers, payload_sha256=digest, summary_text=args.summary,
523
+ purpose=args.purpose, receipt=receipt or None,
524
+ )
525
+ write_json(args.out, receipt)
526
+ _print_status(args.out, receipt, status)
527
+ return 0 if status.get("complete") else 2
528
+
529
+ def cmd_sign(args):
530
+ key = load_party_file(args.key, need_private=True)
531
+ receipt = load_json(args.receipt_in)
532
+ receipt, status = sign_vow(key, receipt)
533
+ out = args.out or args.receipt_in
534
+ write_json(out, receipt)
535
+ _print_status(out, receipt, status)
536
+ return 0 if status.get("complete") else 2
537
+
538
+ def cmd_verify(args):
539
+ log = load_json(args.file)
540
+ # A receipt must never carry a private key.
541
+ dumped = json.dumps(log)
542
+ if "privkey" in dumped:
543
+ print("REJECTED\n - receipt contains a private key field; refuse to treat this as a BotVow receipt")
544
+ return 1
545
+ errs = verify(log, args.head)
546
+ print("VERIFY OK" if not errs else "REJECTED\n" + "\n".join(" - " + e for e in errs))
547
+ if not errs:
548
+ print(f"head {log[-1]['entry_hash']}")
549
+ return 0 if not errs else 1
550
+
551
+ def _print_status(path, receipt, status):
552
+ print(f"receipt written to {path} ({len(receipt)} entries).")
553
+ if status.get("complete"):
554
+ print("VERIFY OK")
555
+ print(f"head {receipt[-1]['entry_hash']}")
556
+ else:
557
+ nxt = status.get("next")
558
+ missing = status.get("missing_kids") or []
559
+ if nxt == "sign" and missing:
560
+ print(f"incomplete: waiting for the other party to sign ({', '.join(missing)}).")
561
+ print(f" python3 tools/botvow.py sign --key THEIR.key.json --in {path} --out {path}")
562
+ elif nxt and nxt != "done":
563
+ print(f"incomplete: next step is {nxt}.")
564
+ print(f" python3 tools/botvow.py create --key YOUR.key.json --in {path} --out {path} --payload FILE --summary TEXT")
565
+ else:
566
+ print("incomplete.")
567
+
568
+ def build_parser():
569
+ p = argparse.ArgumentParser(prog="botvow", description="BotVow: create and verify co-signed receipts between Bots.")
570
+ sub = p.add_subparsers(dest="cmd")
571
+
572
+ g = sub.add_parser("keygen", help="generate a local Ed25519 key pair (private key stays on this machine)")
573
+ g.add_argument("--name", required=True)
574
+ g.add_argument("--out", required=True, help="path ending in .key.json")
575
+ g.add_argument("--kind", choices=sorted(PARTY_KINDS), default="bot")
576
+ g.add_argument("--platform", default="bot")
577
+ g.add_argument("--agent-card", dest="agent_card", default=None)
578
+ g.set_defaults(func=cmd_keygen)
579
+
580
+ u = sub.add_parser("pubkey", help="write a public-only party file from a key file")
581
+ u.add_argument("--key", required=True)
582
+ u.add_argument("--out", required=True)
583
+ u.set_defaults(func=cmd_pubkey)
584
+
585
+ c = sub.add_parser("create", help="create or advance a receipt; never stores the file, only its SHA-256")
586
+ c.add_argument("--key", action="append", required=True, help="local private key file (repeat once per signing party on this machine)")
587
+ c.add_argument("--peer", action="append", help="public party file of the other side")
588
+ c.add_argument("--payload", help="file whose SHA-256 is recorded (the file itself is not copied into the receipt)")
589
+ c.add_argument("--payload-sha256", dest="payload_sha256", help="SHA-256 of the file, if you already hashed it")
590
+ c.add_argument("--summary", help="short description, stored only with both parties' consent")
591
+ c.add_argument("--purpose", default="delivery")
592
+ c.add_argument("--in", dest="receipt_in", help="existing incomplete receipt to advance")
593
+ c.add_argument("--out", required=True, help="where to write the receipt JSON")
594
+ c.set_defaults(func=cmd_create)
595
+
596
+ s = sub.add_parser("sign", help="add this party's signature to an existing receipt")
597
+ s.add_argument("--key", required=True)
598
+ s.add_argument("--in", dest="receipt_in", required=True)
599
+ s.add_argument("--out", help="defaults to the same path as --in")
600
+ s.set_defaults(func=cmd_sign)
601
+
602
+ v = sub.add_parser("verify", help="verify a receipt (exit 0 = VERIFY OK)")
603
+ v.add_argument("file")
604
+ v.add_argument("--head", default=None)
605
+ v.set_defaults(func=cmd_verify)
606
+
607
+ d = sub.add_parser("demo", help="rebuild the sample logs and run the built-in checks")
608
+ d.set_defaults(func=lambda args: 0 if demo() else 1)
609
+ m = sub.add_parser("mcp", help="run the local MCP server on stdio (create_vow, verify_vow)")
610
+ m.set_defaults(func=lambda args: _run_mcp())
611
+ return p
612
+
613
+ def _run_mcp():
614
+ from mcp_server import main as mcp_main
615
+ return mcp_main()
616
+
617
+ def main(argv=None):
618
+ argv = list(sys.argv[1:] if argv is None else argv)
619
+ if not argv:
620
+ return _run_mcp()
621
+ # Backwards compatible: `verify FILE` without the argparse path still works through argparse.
622
+ try:
623
+ args = build_parser().parse_args(argv)
624
+ except SystemExit as e:
625
+ return int(e.code or 0)
626
+ if not getattr(args, "cmd", None):
627
+ return 0 if demo() else 1
628
+ try:
629
+ return int(args.func(args) or 0)
630
+ except (ValueError, OSError, KeyError) as e:
631
+ print(f"error: {e}", file=sys.stderr)
632
+ return 1
633
+
634
+ if __name__ == "__main__":
635
+ sys.exit(main())
check_schema.py ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env python3
2
+ """Validate every entry of a BotVow log against schema/record.schema.json (needs: pip install jsonschema)."""
3
+ import json, os, sys
4
+ import jsonschema
5
+ HERE = os.path.dirname(os.path.abspath(__file__))
6
+ schema = json.load(open(os.path.join(HERE, "..", "schema", "record.schema.json"), encoding="utf-8"))
7
+ path = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HERE, "..", "examples", "bot2bot-log.json")
8
+ log = json.load(open(path, encoding="utf-8"))
9
+ for e in log:
10
+ jsonschema.validate(e, schema)
11
+ print(f"schema OK for {len(log)} entries in {os.path.basename(path)}")
mcp_server.py ADDED
@@ -0,0 +1,295 @@
1
+ #!/usr/bin/env python3
2
+ """BotVow MCP server (stdio). Local helper only: it is not the source of truth.
3
+
4
+ Two tools: create_vow and verify_vow. Private keys stay in local key files the
5
+ user generates with `botvow keygen`. The receipt JSON is the proof; anyone can
6
+ verify it offline with tools/botvow.py, even if this process is not running.
7
+
8
+ Transport: JSON-RPC 2.0 with LSP-style Content-Length framing on stdin/stdout.
9
+
10
+ Licence: MIT (see LICENSE).
11
+ """
12
+ import json, os, sys, traceback
13
+
14
+ HERE = os.path.dirname(os.path.abspath(__file__))
15
+ if HERE not in sys.path:
16
+ sys.path.insert(0, HERE)
17
+
18
+ import botvow as bv
19
+
20
+ PROTOCOL_VERSION = "2025-06-18"
21
+ SERVER_NAME = "botvow"
22
+ SERVER_VERSION = "0.1.0"
23
+
24
+ CREATE_SCHEMA = {
25
+ "type": "object",
26
+ "properties": {
27
+ "key_paths": {
28
+ "type": "array",
29
+ "items": {"type": "string"},
30
+ "description": "Absolute or relative paths to local .key.json files from `botvow keygen`. Private keys are read from disk and never copied into the receipt or the tool result.",
31
+ },
32
+ "peer_paths": {
33
+ "type": "array",
34
+ "items": {"type": "string"},
35
+ "description": "Public-only party files (.pub.json) for the other side, when their private key is not on this machine.",
36
+ },
37
+ "payload_path": {
38
+ "type": "string",
39
+ "description": "Path of the delivered file. Only its SHA-256 is recorded.",
40
+ },
41
+ "payload_sha256": {
42
+ "type": "string",
43
+ "description": "SHA-256 of the delivered file, if you already hashed it (64 lowercase hex characters).",
44
+ },
45
+ "summary": {
46
+ "type": "string",
47
+ "description": "Short description of the commitment or delivery. Stored only with both parties' consent. Do not put personal data here.",
48
+ },
49
+ "purpose": {"type": "string", "description": "Short purpose label for a new chain. Default: delivery."},
50
+ "receipt_path": {
51
+ "type": "string",
52
+ "description": "Path of an existing receipt to advance or co-sign.",
53
+ },
54
+ "out_path": {
55
+ "type": "string",
56
+ "description": "Where to write the receipt JSON. Each party should keep their own copy.",
57
+ },
58
+ },
59
+ }
60
+
61
+ VERIFY_SCHEMA = {
62
+ "type": "object",
63
+ "properties": {
64
+ "receipt_path": {"type": "string", "description": "Path of the receipt JSON to verify."},
65
+ "receipt": {
66
+ "description": "The receipt JSON itself (an array of entries), if you are not reading a file.",
67
+ },
68
+ "head": {
69
+ "type": "string",
70
+ "description": "Optional expected head hash (64 lowercase hex characters).",
71
+ },
72
+ },
73
+ }
74
+
75
+ TOOLS = [
76
+ {
77
+ "name": "create_vow",
78
+ "description": (
79
+ "Create or advance a BotVow receipt for a commitment or a delivery between two agents. "
80
+ "Records identifiers, the SHA-256 of the file, a short summary and the date; never stores "
81
+ "the file, personal data or private keys. If both local key files are given, the receipt is "
82
+ "sealed in one step. If only one key is given, the other party later calls create_vow or "
83
+ "signs with the CLI. The receipt file is the proof; this server is not the source of truth."
84
+ ),
85
+ "inputSchema": CREATE_SCHEMA,
86
+ },
87
+ {
88
+ "name": "verify_vow",
89
+ "description": (
90
+ "Verify a BotVow receipt. Checks the hash chain and the Ed25519 signatures with the public "
91
+ "keys listed in the genesis. Returns VERIFY OK or REJECTED with reasons. Does not need "
92
+ "private keys or this server to remain running afterwards."
93
+ ),
94
+ "inputSchema": VERIFY_SCHEMA,
95
+ },
96
+ ]
97
+
98
+
99
+ def _read_message(stdin):
100
+ headers = {}
101
+ while True:
102
+ line = stdin.readline()
103
+ if line in ("", b""):
104
+ return None
105
+ line = line.decode("utf-8") if isinstance(line, bytes) else line
106
+ if line in ("\r\n", "\n"):
107
+ break
108
+ if ":" in line:
109
+ k, v = line.split(":", 1)
110
+ headers[k.strip().lower()] = v.strip()
111
+ length = int(headers.get("content-length", "0"))
112
+ if length <= 0:
113
+ return None
114
+ body = stdin.read(length)
115
+ if isinstance(body, bytes):
116
+ body = body.decode("utf-8")
117
+ return json.loads(body)
118
+
119
+
120
+ def _write_message(stdout, payload):
121
+ body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
122
+ stdout.write(f"Content-Length: {len(body)}\r\n\r\n".encode("utf-8") + body)
123
+ stdout.flush()
124
+
125
+
126
+ def _tool_result(text, structured=None, is_error=False):
127
+ out = {"content": [{"type": "text", "text": text}], "isError": bool(is_error)}
128
+ if structured is not None:
129
+ out["structuredContent"] = structured
130
+ return out
131
+
132
+
133
+ def _refuse_secrets(obj, path="$"):
134
+ if isinstance(obj, dict):
135
+ for k, v in obj.items():
136
+ if k.lower() in {"privkey", "private_key", "secret", "password"}:
137
+ raise ValueError("private keys and secrets must not be passed as tool arguments; use a local key file path")
138
+ _refuse_secrets(v, path + "." + k)
139
+ elif isinstance(obj, list):
140
+ for i, v in enumerate(obj):
141
+ _refuse_secrets(v, f"{path}[{i}]")
142
+
143
+
144
+ def call_create_vow(args):
145
+ _refuse_secrets(args)
146
+ key_paths = args.get("key_paths") or []
147
+ if not key_paths:
148
+ raise ValueError("key_paths is required (local .key.json files from botvow keygen)")
149
+ keys = [bv.load_party_file(p, need_private=True) for p in key_paths]
150
+ peers = [bv.load_party_file(p, need_private=False) for p in (args.get("peer_paths") or [])]
151
+ receipt = None
152
+ if args.get("receipt_path"):
153
+ receipt = bv.load_json(args["receipt_path"])
154
+ digest = None
155
+ if args.get("payload_path") or args.get("payload_sha256"):
156
+ digest = bv.payload_sha256_from(path=args.get("payload_path"), digest=args.get("payload_sha256"))
157
+ receipt, status = bv.create_vow(
158
+ keys,
159
+ peer_recs=peers,
160
+ payload_sha256=digest,
161
+ summary_text=args.get("summary"),
162
+ purpose=args.get("purpose") or "delivery",
163
+ receipt=receipt,
164
+ )
165
+ dumped = json.dumps(receipt)
166
+ if "privkey" in dumped:
167
+ raise RuntimeError("refusing to return a receipt that contains a private key")
168
+ out_path = args.get("out_path")
169
+ if out_path:
170
+ bv.write_json(out_path, receipt)
171
+ structured = {
172
+ "complete": bool(status.get("complete")),
173
+ "next": status.get("next"),
174
+ "head": receipt[-1]["entry_hash"] if receipt else None,
175
+ "entries": len(receipt),
176
+ "out_path": out_path,
177
+ "receipt": receipt,
178
+ "errors": status.get("errors") or [],
179
+ }
180
+ if status.get("complete"):
181
+ text = "VERIFY OK\nhead " + structured["head"]
182
+ if out_path:
183
+ text += f"\nreceipt written to {out_path}"
184
+ text += "\nKeep this receipt. This server is not the source of truth."
185
+ return _tool_result(text, structured, is_error=False)
186
+ missing = status.get("missing_kids") or []
187
+ text = "incomplete receipt: next step is " + str(status.get("next"))
188
+ if missing:
189
+ text += "; waiting for " + ", ".join(missing)
190
+ if out_path:
191
+ text += f"\nreceipt written to {out_path}"
192
+ return _tool_result(text, structured, is_error=False)
193
+
194
+
195
+ def call_verify_vow(args):
196
+ _refuse_secrets(args)
197
+ if args.get("receipt_path"):
198
+ receipt = bv.load_json(args["receipt_path"])
199
+ elif "receipt" in args:
200
+ receipt = args["receipt"]
201
+ if isinstance(receipt, str):
202
+ receipt = json.loads(receipt)
203
+ else:
204
+ raise ValueError("provide receipt_path or receipt")
205
+ if "privkey" in json.dumps(receipt):
206
+ return _tool_result(
207
+ "REJECTED\n - receipt contains a private key field; refuse to treat this as a BotVow receipt",
208
+ {"complete": False, "errors": ["private key in receipt"]},
209
+ is_error=True,
210
+ )
211
+ errs = bv.verify(receipt, args.get("head"))
212
+ if errs:
213
+ text = "REJECTED\n" + "\n".join(" - " + e for e in errs)
214
+ return _tool_result(text, {"complete": False, "errors": errs}, is_error=False)
215
+ head = receipt[-1]["entry_hash"]
216
+ text = f"VERIFY OK\nhead {head}"
217
+ return _tool_result(text, {"complete": True, "errors": [], "head": head}, is_error=False)
218
+
219
+
220
+ def handle(msg):
221
+ if not isinstance(msg, dict):
222
+ return None
223
+ method = msg.get("method")
224
+ mid = msg.get("id", None)
225
+ is_notification = "id" not in msg
226
+ if method == "initialize":
227
+ return {
228
+ "jsonrpc": "2.0",
229
+ "id": mid,
230
+ "result": {
231
+ "protocolVersion": PROTOCOL_VERSION,
232
+ "capabilities": {"tools": {"listChanged": False}},
233
+ "serverInfo": {"name": SERVER_NAME, "version": SERVER_VERSION},
234
+ "instructions": (
235
+ "BotVow records a co-signed receipt of a commitment or delivery. "
236
+ "Generate keys with `python3 tools/botvow.py keygen`. "
237
+ "Use create_vow and verify_vow. Never send private keys, file contents or personal data "
238
+ "as tool arguments. Keep the receipt JSON; this process is not the source of truth."
239
+ ),
240
+ },
241
+ }
242
+ if method == "notifications/initialized" or is_notification:
243
+ return None
244
+ if method == "ping":
245
+ return {"jsonrpc": "2.0", "id": mid, "result": {}}
246
+ if method == "tools/list":
247
+ return {"jsonrpc": "2.0", "id": mid, "result": {"tools": TOOLS}}
248
+ if method == "tools/call":
249
+ params = msg.get("params") or {}
250
+ name = params.get("name")
251
+ arguments = params.get("arguments") or {}
252
+ try:
253
+ if name == "create_vow":
254
+ result = call_create_vow(arguments)
255
+ elif name == "verify_vow":
256
+ result = call_verify_vow(arguments)
257
+ else:
258
+ result = _tool_result(f"unknown tool: {name}", is_error=True)
259
+ except Exception as e:
260
+ result = _tool_result(f"error: {e}", is_error=True)
261
+ return {"jsonrpc": "2.0", "id": mid, "result": result}
262
+ if mid is not None:
263
+ return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": f"Method not found: {method}"}}
264
+ return None
265
+
266
+
267
+ def serve(stdin=None, stdout=None):
268
+ stdin = stdin or sys.stdin.buffer
269
+ stdout = stdout or sys.stdout.buffer
270
+ while True:
271
+ try:
272
+ msg = _read_message(stdin)
273
+ except Exception:
274
+ traceback.print_exc(file=sys.stderr)
275
+ break
276
+ if msg is None:
277
+ break
278
+ try:
279
+ reply = handle(msg)
280
+ except Exception as e:
281
+ if isinstance(msg, dict) and "id" in msg:
282
+ reply = {"jsonrpc": "2.0", "id": msg.get("id"), "error": {"code": -32603, "message": str(e)}}
283
+ else:
284
+ reply = None
285
+ if reply is not None:
286
+ _write_message(stdout, reply)
287
+
288
+
289
+ def main(argv=None):
290
+ serve()
291
+ return 0
292
+
293
+
294
+ if __name__ == "__main__":
295
+ sys.exit(main())