othrion-agent 1.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.
othrion/__init__.py ADDED
@@ -0,0 +1,332 @@
1
+ """othrion-agent — Website Agent SDK for the Othrion network.
2
+
3
+ Makes onboarding ridiculously easy:
4
+
5
+ from othrion import Agent
6
+
7
+ agent = Agent(
8
+ name="Acme Travel AI",
9
+ endpoint="https://acme.com",
10
+ owner="Acme Travel Ltd",
11
+ capabilities=["travel.search", "travel.book"],
12
+ )
13
+ agent.register() # Stage 1: POST /gateway/onboard
14
+ agent.verify() # Stage 2: sign challenge with our key
15
+ agent.get_api_key() # Stage 4: POST /gateway/keys
16
+ agent.handshake() # -> session_id
17
+ agent.serve() # expose /.well-known + /agent/* (Flask)
18
+
19
+ Install (local): pip install -e G:\\shelve-ai\\Othrion_Gateway\\sdk
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import os
26
+ import sys
27
+ from dataclasses import dataclass, field
28
+
29
+ import requests
30
+
31
+ __version__ = "1.1.0"
32
+
33
+ # ---------------------------------------------------------------------------
34
+ # Crypto — self-contained, no Othrion core repo required.
35
+ #
36
+ # The SDK used to import `wallet` from the Othrion core source tree, which
37
+ # meant `pip install othrion-agent` only worked on a machine that also had
38
+ # the core checked out. That defeats the point of a public package, so the
39
+ # four operations we need are implemented directly on `cryptography`.
40
+ # ---------------------------------------------------------------------------
41
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import ( # noqa: E402
42
+ Ed25519PrivateKey,
43
+ Ed25519PublicKey,
44
+ )
45
+ from cryptography.hazmat.primitives.serialization import ( # noqa: E402
46
+ Encoding,
47
+ PublicFormat,
48
+ )
49
+
50
+
51
+ def _generate_keypair():
52
+ priv = Ed25519PrivateKey.generate()
53
+ return priv, priv.public_key()
54
+
55
+
56
+ def _public_bytes(pub: Ed25519PublicKey) -> bytes:
57
+ return pub.public_bytes(Encoding.Raw, PublicFormat.Raw)
58
+
59
+
60
+ def _sign(priv: Ed25519PrivateKey, message: bytes) -> bytes:
61
+ return priv.sign(message)
62
+
63
+
64
+ def _verify(pub: Ed25519PublicKey, signature: bytes, message: bytes) -> bool:
65
+ from cryptography.exceptions import InvalidSignature
66
+ try:
67
+ pub.verify(signature, message)
68
+ return True
69
+ except InvalidSignature:
70
+ return False
71
+
72
+
73
+ class _Vault:
74
+ """Minimal shim so existing call sites keep working unchanged."""
75
+
76
+ generate_keypair = staticmethod(_generate_keypair)
77
+ public_bytes = staticmethod(_public_bytes)
78
+ sign = staticmethod(_sign)
79
+ verify = staticmethod(_verify)
80
+
81
+
82
+ _vault = _Vault()
83
+
84
+
85
+ @dataclass
86
+ class Agent:
87
+ """One-call client for joining and serving on the Othrion network."""
88
+
89
+ name: str
90
+ endpoint: str
91
+ owner: str = ""
92
+ capabilities: list[str] = field(default_factory=list)
93
+ gateway: str = "http://127.0.0.1:4113"
94
+ owner_type: str = "BUSINESS"
95
+ contact_email: str = ""
96
+
97
+ # populated during onboarding
98
+ application_id: str | None = None
99
+ agent_id: str | None = None
100
+ api_key: str | None = None
101
+ session_id: str | None = None
102
+
103
+ def __post_init__(self):
104
+ self._priv, self._pub = _vault.generate_keypair()
105
+ self.public_key = _vault.public_bytes(self._pub).hex()
106
+
107
+ # ---- Stage 1: register ----
108
+ def register(self) -> dict:
109
+ r = requests.post(f"{self.gateway}/gateway/onboard", json={
110
+ "agent_name": self.name,
111
+ "owner_name": self.owner or self.name,
112
+ "owner_type": self.owner_type,
113
+ "endpoint": self.endpoint,
114
+ "contact_email": self.contact_email or "noreply@example.com",
115
+ "public_key": self.public_key,
116
+ }, timeout=10)
117
+ r.raise_for_status()
118
+ body = r.json()
119
+ self.application_id = body["application_id"]
120
+ self._challenge = body["challenge"]
121
+ return body
122
+
123
+ # ---- Stage 2: verify key ownership ----
124
+ def verify(self) -> dict:
125
+ if not self.application_id:
126
+ raise RuntimeError("call register() first")
127
+ sig = _vault.sign(self._priv, self._challenge.encode()).hex()
128
+ r = requests.post(f"{self.gateway}/gateway/onboard/verify", json={
129
+ "application_id": self.application_id,
130
+ "challenge_response": sig,
131
+ }, timeout=10)
132
+ r.raise_for_status()
133
+ return r.json()
134
+
135
+ # ---- Stage 4: get API key (v1 localhost convenience endpoint) ----
136
+ def get_api_key(self, agent_id: str | None = None) -> str:
137
+ aid = agent_id or self.agent_id
138
+ if not aid:
139
+ raise RuntimeError("set agent_id (from Othrion enrollment) first")
140
+ r = requests.post(f"{self.gateway}/gateway/keys",
141
+ json={"agent_id": aid}, timeout=10)
142
+ r.raise_for_status()
143
+ self.api_key = r.json()["api_key"]
144
+ self.agent_id = aid
145
+ return self.api_key
146
+
147
+ # ---- handshake ----
148
+ def handshake(self) -> dict:
149
+ if not self.agent_id or not self.api_key:
150
+ raise RuntimeError("call get_api_key() first")
151
+ r = requests.post(f"{self.gateway}/gateway/handshake", json={
152
+ "agent_id": self.agent_id, "api_key": self.api_key,
153
+ }, timeout=10)
154
+ r.raise_for_status()
155
+ body = r.json()
156
+ self.session_id = body["session_id"]
157
+ return body
158
+
159
+ # ---- route an intent ----
160
+ def route(self, intent: str, payload: dict | None = None) -> dict:
161
+ if not self.session_id:
162
+ raise RuntimeError("call handshake() first")
163
+ r = requests.post(f"{self.gateway}/gateway/route", json={
164
+ "session_id": self.session_id,
165
+ "intent": intent,
166
+ "payload": payload or {},
167
+ }, timeout=35)
168
+ return r.json() if r.ok else {"error": r.json(), "status": r.status_code}
169
+
170
+ # ---- serve: expose WAP endpoints (Flask) ----
171
+ def serve(self, port: int = 4115, host: str = "127.0.0.1"):
172
+ """Run the standard WAP endpoints backed by this agent's capabilities."""
173
+ from flask import Flask, jsonify, request
174
+
175
+ app = Flask(self.name)
176
+ sessions: dict[str, dict] = {}
177
+
178
+ @app.get("/.well-known/othrion")
179
+ def well_known():
180
+ return jsonify({
181
+ "agent_id": self.agent_id,
182
+ "agent_name": self.name,
183
+ "endpoint": self.endpoint,
184
+ "protocol_version": "1.0",
185
+ "capabilities": self.capabilities,
186
+ })
187
+
188
+ @app.post("/agent/handshake")
189
+ def agent_handshake():
190
+ data = request.get_json(silent=True) or {}
191
+ requester = data.get("requesting_agent", "")
192
+ if not requester.startswith("OTH-"):
193
+ return jsonify({"error": "OTH-* required",
194
+ "code": "INVALID_SIGNATURE"}), 401
195
+ sid = f"WAP-{requester[-8:]}"
196
+ sessions[sid] = {"requesting_agent": requester,
197
+ "agent_level": int(data.get("agent_level", 0)),
198
+ "has_delegation": bool(data.get("has_delegation"))}
199
+ return jsonify({"accepted": True, "session_id": sid,
200
+ "capabilities": self.capabilities}), 201
201
+
202
+ @app.get("/agent/capabilities")
203
+ def agent_capabilities():
204
+ return jsonify({"agent_id": self.agent_id,
205
+ "capabilities": self.capabilities})
206
+
207
+ @app.post("/agent/action")
208
+ def agent_action():
209
+ data = request.get_json(silent=True) or {}
210
+ sid = data.get("session_id", "")
211
+ intent = data.get("intent", "")
212
+ sess = sessions.get(sid)
213
+ if sess is None:
214
+ return jsonify({"error": "unknown session",
215
+ "code": "SESSION_INVALID"}), 401
216
+ if intent not in self.capabilities:
217
+ return jsonify({"error": "not offered",
218
+ "code": "CAPABILITY_DENIED"}), 403
219
+ # permission gate — vendored so the SDK has no external imports
220
+ from .permissions import check_action
221
+ allowed, reasons = check_action(
222
+ intent=intent,
223
+ agent_level=sess["agent_level"],
224
+ has_delegation=sess["has_delegation"],
225
+ amount=data.get("amount"),
226
+ delegation_max=data.get("delegation_max"),
227
+ merchant=data.get("merchant"),
228
+ delegation_merchants=data.get("delegation_merchants"),
229
+ )
230
+ if not allowed:
231
+ return jsonify({"error": reasons[0]["detail"],
232
+ "code": reasons[0]["code"]}), 403
233
+ result = self.execute(intent, data.get("payload") or {})
234
+ return jsonify({"status": "success", "intent": intent,
235
+ "result": result})
236
+
237
+ @app.get("/agent/health")
238
+ def health():
239
+ return jsonify({"ok": True, "agent": self.name})
240
+
241
+ print(f"{self.name} serving WAP on http://{host}:{port}/ "
242
+ f"(.well-known/othrion, /agent/*)")
243
+ app.run(host=host, port=port, debug=False)
244
+
245
+ def execute(self, intent: str, payload: dict) -> dict:
246
+ """Override in subclasses — the actual website backend call."""
247
+ return {"ok": True, "intent": intent, "payload": payload}
248
+
249
+
250
+ class Bridge:
251
+ """Wrap an EXISTING AI so it becomes Othrion-enabled — no core changes.
252
+
253
+ The killer strategy: onboard in one afternoon, not six months.
254
+
255
+ from othrion import Bridge
256
+
257
+ bridge = Bridge(
258
+ existing_ai=tripgenie, # any object with .handle()
259
+ capabilities=["flight.search", "flight.book"],
260
+ name="TripGenie (Othrion Bridge)",
261
+ endpoint="https://tripgenie.com",
262
+ )
263
+ bridge.register() # Stage 1 + 2 (auto-verifies challenge)
264
+ bridge.get_api_key(agent_id="OTH-HK-00000001")
265
+ bridge.serve(port=4116) # exposes /.well-known + /agent/*
266
+
267
+ The bridge translates WAP intents into calls on the existing AI's
268
+ own interface — the AI never learns the Othrion protocol internally.
269
+ """
270
+
271
+ def __init__(
272
+ self,
273
+ existing_ai,
274
+ capabilities: list[str],
275
+ name: str = "",
276
+ endpoint: str = "",
277
+ owner: str = "",
278
+ gateway: str = "http://127.0.0.1:4113",
279
+ handler: str = "handle",
280
+ ):
281
+ """``handler`` = method name on existing_ai that accepts
282
+ (intent, payload) and returns a dict. Default: ``handle``."""
283
+ self.ai = existing_ai
284
+ self.handler_name = handler
285
+ self.agent = Agent(
286
+ name=name or f"{getattr(existing_ai, 'name', type(existing_ai).__name__)} (Bridge)",
287
+ endpoint=endpoint or "http://127.0.0.1:4116",
288
+ owner=owner,
289
+ capabilities=capabilities,
290
+ gateway=gateway,
291
+ )
292
+
293
+ # ---- onboarding (delegates to Agent, auto-verifies) ----
294
+ def register(self) -> dict:
295
+ body = self.agent.register()
296
+ self.agent.verify() # Stage 2 automatically — one call for the user
297
+ return body
298
+
299
+ def get_api_key(self, agent_id: str) -> str:
300
+ return self.agent.get_api_key(agent_id)
301
+
302
+ def handshake(self) -> dict:
303
+ return self.agent.handshake()
304
+
305
+ # ---- translation: WAP intent -> existing AI call ----
306
+ def dispatch(self, intent: str, payload: dict) -> dict:
307
+ """Translate an Othrion intent into the existing AI's own call."""
308
+ handler = getattr(self.ai, self.handler_name, None)
309
+ if handler is None:
310
+ raise RuntimeError(
311
+ f"existing AI has no '{self.handler_name}' method — "
312
+ f"pass handler='your_method' to Bridge()"
313
+ )
314
+ try:
315
+ result = handler(intent, payload)
316
+ except TypeError:
317
+ # AI expects only payload (common shape)
318
+ result = handler(payload)
319
+ if not isinstance(result, dict):
320
+ result = {"result": result}
321
+ return result
322
+
323
+ def serve(self, port: int = 4116, host: str = "127.0.0.1"):
324
+ """Serve WAP endpoints; /agent/action dispatches to the existing AI."""
325
+ # wrap the agent's execute() with our dispatcher
326
+ bridge = self
327
+
328
+ def _execute(intent: str, payload: dict) -> dict:
329
+ return bridge.dispatch(intent, payload)
330
+
331
+ self.agent.execute = _execute
332
+ self.agent.serve(port=port, host=host)
othrion/cli.py ADDED
@@ -0,0 +1,427 @@
1
+ """othrion — command-line client for the Othrion network.
2
+
3
+ pip install othrion-agent
4
+ othrion enroll --name "Acme Travel AI" --owner "Acme Travel Ltd" \\
5
+ --email ai@acme.com --region HK
6
+
7
+ WHAT THIS SOLVES
8
+ ----------------
9
+ Before this, joining required reading a spec and writing code. Now it is
10
+ one command. The private key is generated locally and NEVER leaves the
11
+ machine — Othrion only ever receives the public half.
12
+
13
+ IDENTITY FILE
14
+ -------------
15
+ ~/.othrion/identity.json (mode 0600)
16
+
17
+ Contains the private key, so it is written 0600 and never printed. Set
18
+ OTHRION_HOME to override the directory.
19
+
20
+ COMMANDS
21
+ --------
22
+ enroll generate a keypair, register, prove ownership
23
+ status show local identity and remote application state
24
+ key issue an API key for an enrolled agent
25
+ handshake open a session
26
+ send send a signed OMP envelope
27
+ verify verify a receipt offline
28
+ whoami print the agent id and public key
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import argparse
34
+ import json
35
+ import os
36
+ import stat
37
+ import sys
38
+ from datetime import datetime, timezone
39
+
40
+ import requests
41
+
42
+ DEFAULT_GATEWAY = os.environ.get("OTHRION_GATEWAY", "https://othrion.ai")
43
+ IDENTITY_DIR = os.environ.get(
44
+ "OTHRION_HOME", os.path.join(os.path.expanduser("~"), ".othrion"))
45
+ IDENTITY_FILE = os.path.join(IDENTITY_DIR, "identity.json")
46
+
47
+
48
+ # ---------------------------------------------------------------------------
49
+ # crypto — Ed25519 via the cryptography package (no Othrion core needed)
50
+ # ---------------------------------------------------------------------------
51
+
52
+ def _generate_keypair():
53
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import (
54
+ Ed25519PrivateKey,
55
+ )
56
+ from cryptography.hazmat.primitives.serialization import (
57
+ Encoding, PublicFormat,
58
+ )
59
+ priv = Ed25519PrivateKey.generate()
60
+ pub_hex = priv.public_key().public_bytes(
61
+ Encoding.Raw, PublicFormat.Raw).hex()
62
+ return priv, pub_hex
63
+
64
+
65
+ def _priv_to_hex(priv) -> str:
66
+ from cryptography.hazmat.primitives.serialization import (
67
+ Encoding, NoEncryption, PrivateFormat,
68
+ )
69
+ return priv.private_bytes(
70
+ encoding=Encoding.Raw,
71
+ format=PrivateFormat.Raw,
72
+ encryption_algorithm=NoEncryption(),
73
+ ).hex()
74
+
75
+
76
+ def _priv_from_hex(value: str):
77
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import (
78
+ Ed25519PrivateKey,
79
+ )
80
+ return Ed25519PrivateKey.from_private_bytes(bytes.fromhex(value))
81
+
82
+
83
+ # ---------------------------------------------------------------------------
84
+ # identity file
85
+ # ---------------------------------------------------------------------------
86
+
87
+ def load_identity() -> dict | None:
88
+ if not os.path.exists(IDENTITY_FILE):
89
+ return None
90
+ with open(IDENTITY_FILE, "r", encoding="utf-8") as fh:
91
+ return json.load(fh)
92
+
93
+
94
+ def save_identity(data: dict) -> None:
95
+ """Write the identity file with 0600 permissions. Never print the key."""
96
+ os.makedirs(IDENTITY_DIR, exist_ok=True)
97
+ tmp = IDENTITY_FILE + ".tmp"
98
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
99
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
100
+ json.dump(data, fh, indent=2)
101
+ os.replace(tmp, IDENTITY_FILE)
102
+ # belt and braces: some filesystems ignore the create mode
103
+ os.chmod(IDENTITY_FILE, stat.S_IRUSR | stat.S_IWUSR)
104
+
105
+
106
+ def require_identity() -> dict:
107
+ ident = load_identity()
108
+ if ident is None:
109
+ _die("no identity found — run `othrion enroll` first")
110
+ return ident
111
+
112
+
113
+ def _die(msg: str, code: int = 1):
114
+ print(f"error: {msg}", file=sys.stderr)
115
+ raise SystemExit(code)
116
+
117
+
118
+ def _ok(msg: str):
119
+ # ASCII only: redirected stdout on Windows is cp1252 and cannot encode
120
+ # a check mark. Same lesson as the console's arrow bug.
121
+ print(f" [ok] {msg}")
122
+
123
+
124
+ def _fail(msg: str):
125
+ print(f" [x] {msg}")
126
+
127
+
128
+ def _now() -> str:
129
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
130
+
131
+
132
+ # ---------------------------------------------------------------------------
133
+ # commands
134
+ # ---------------------------------------------------------------------------
135
+
136
+ def cmd_enroll(args) -> int:
137
+ existing = load_identity()
138
+ if existing and not args.force:
139
+ _die(f"already enrolled as {existing.get('agent_id') or existing.get('application_id')}"
140
+ f" — use --force to replace (this discards the current key)")
141
+
142
+ print("Othrion enrollment")
143
+ print("=" * 60)
144
+
145
+ priv, pub_hex = _generate_keypair()
146
+ print(f"\n[1/3] generated keypair locally")
147
+ print(f" public key: {pub_hex}")
148
+ print(f" private key stays on this machine")
149
+
150
+ print(f"\n[2/3] registering with {args.gateway}")
151
+ try:
152
+ r = requests.post(f"{args.gateway}/gateway/onboard", json={
153
+ "agent_name": args.name,
154
+ "owner_name": args.owner or args.name,
155
+ "owner_type": args.owner_type,
156
+ "endpoint": args.endpoint,
157
+ "contact_email": args.email,
158
+ "public_key": pub_hex,
159
+ "region": args.region.upper(),
160
+ }, timeout=25)
161
+ except requests.RequestException as exc:
162
+ _die(f"cannot reach the gateway: {exc}")
163
+ if r.status_code != 201:
164
+ _die(f"registration failed ({r.status_code}): {r.text[:300]}")
165
+ body = r.json()
166
+ application_id = body["application_id"]
167
+ challenge = body["challenge"]
168
+ _ok(f"application {application_id} created (PENDING)")
169
+
170
+ print(f"\n[3/3] proving key ownership")
171
+ signature = priv.sign(challenge.encode()).hex()
172
+ try:
173
+ r = requests.post(f"{args.gateway}/gateway/onboard/verify", json={
174
+ "application_id": application_id,
175
+ "challenge_response": signature,
176
+ }, timeout=25)
177
+ except requests.RequestException as exc:
178
+ _die(f"cannot reach the gateway: {exc}")
179
+ if r.status_code != 200:
180
+ _die(f"verification failed ({r.status_code}): {r.text[:300]}")
181
+ _ok("challenge signed — application VERIFIED")
182
+
183
+ save_identity({
184
+ "agent_name": args.name,
185
+ "owner_name": args.owner or args.name,
186
+ "owner_type": args.owner_type,
187
+ "endpoint": args.endpoint,
188
+ "contact_email": args.email,
189
+ "region": args.region.upper(),
190
+ "gateway": args.gateway,
191
+ "application_id": application_id,
192
+ "public_key": pub_hex,
193
+ "private_key": _priv_to_hex(priv),
194
+ "agent_id": None,
195
+ "api_key": None,
196
+ "enrolled_at": _now(),
197
+ })
198
+
199
+ print(f"\n{'=' * 60}")
200
+ print("ENROLLED")
201
+ print(f" application : {application_id}")
202
+ print(f" public key : {pub_hex}")
203
+ print(f" identity : {IDENTITY_FILE}")
204
+ print(f"\nNext: Othrion issues your agent id (OTH-{args.region.upper()}-########).")
205
+ print(f"Then run: othrion key --agent-id OTH-{args.region.upper()}-00000001")
206
+ return 0
207
+
208
+
209
+ def cmd_status(args) -> int:
210
+ ident = require_identity()
211
+ print("Othrion identity")
212
+ print("=" * 60)
213
+ print(f" agent name : {ident.get('agent_name')}")
214
+ print(f" owner : {ident.get('owner_name')}")
215
+ print(f" region : {ident.get('region')}")
216
+ print(f" application : {ident.get('application_id')}")
217
+ print(f" agent id : {ident.get('agent_id') or '(not yet issued)'}")
218
+ print(f" public key : {ident.get('public_key')}")
219
+ print(f" api key : {'set' if ident.get('api_key') else '(not issued)'}")
220
+ print(f" enrolled at : {ident.get('enrolled_at')}")
221
+ print(f" identity file: {IDENTITY_FILE}")
222
+
223
+ gateway = ident.get("gateway") or DEFAULT_GATEWAY
224
+ print(f"\nRemote state ({gateway})")
225
+ try:
226
+ r = requests.get(f"{gateway}/gateway/health", timeout=10)
227
+ print(f" gateway : {'up' if r.ok else 'error ' + str(r.status_code)}")
228
+ except requests.RequestException:
229
+ print(f" gateway : unreachable")
230
+ if ident.get("agent_id"):
231
+ try:
232
+ r = requests.get(f"{gateway}/api/agent/{ident['agent_id']}",
233
+ timeout=10)
234
+ if r.ok:
235
+ d = r.json()
236
+ print(f" passport : {d.get('status')} "
237
+ f"trust={d.get('trust')} band={d.get('trust_band')}")
238
+ else:
239
+ print(f" passport : not found ({r.status_code})")
240
+ except requests.RequestException:
241
+ print(f" passport : unreachable")
242
+ return 0
243
+
244
+
245
+ def cmd_key(args) -> int:
246
+ ident = require_identity()
247
+ agent_id = args.agent_id or ident.get("agent_id")
248
+ if not agent_id:
249
+ _die("no agent id — pass --agent-id (Othrion issues it after enrollment)")
250
+ gateway = ident.get("gateway") or DEFAULT_GATEWAY
251
+ try:
252
+ r = requests.post(f"{gateway}/gateway/keys",
253
+ json={"agent_id": agent_id}, timeout=20)
254
+ except requests.RequestException as exc:
255
+ _die(f"cannot reach the gateway: {exc}")
256
+ if r.status_code != 201:
257
+ _die(f"key issue failed ({r.status_code}): {r.text[:300]}")
258
+ key = r.json()["api_key"]
259
+ ident["agent_id"] = agent_id
260
+ ident["api_key"] = key
261
+ save_identity(ident)
262
+ _ok(f"API key issued for {agent_id}")
263
+ print(f" {key[:12]}... (stored in {IDENTITY_FILE})")
264
+ return 0
265
+
266
+
267
+ def cmd_handshake(args) -> int:
268
+ ident = require_identity()
269
+ if not ident.get("agent_id") or not ident.get("api_key"):
270
+ _die("run `othrion key` first")
271
+ gateway = ident.get("gateway") or DEFAULT_GATEWAY
272
+ try:
273
+ r = requests.post(f"{gateway}/gateway/handshake", json={
274
+ "agent_id": ident["agent_id"],
275
+ "api_key": ident["api_key"],
276
+ }, timeout=20)
277
+ except requests.RequestException as exc:
278
+ _die(f"cannot reach the gateway: {exc}")
279
+ if not r.ok:
280
+ _die(f"handshake rejected ({r.status_code}): {r.text[:300]}")
281
+ body = r.json()
282
+ ident["session_id"] = body["session_id"]
283
+ save_identity(ident)
284
+ _ok(f"session {body['session_id']}")
285
+ print(f" trust {body.get('trust_score')} ({body.get('trust_band')})")
286
+ return 0
287
+
288
+
289
+ def cmd_send(args) -> int:
290
+ """Send a signed OMP envelope. Requires the omp module."""
291
+ ident = require_identity()
292
+ try:
293
+ import omp
294
+ except ImportError:
295
+ _die("the omp module is required for `send` — "
296
+ "install othrion-agent with the gateway package")
297
+ gateway = ident.get("gateway") or DEFAULT_GATEWAY
298
+ priv = _priv_from_hex(ident["private_key"])
299
+
300
+ content = {"mode": "text", "message": args.message or ""}
301
+ if args.data:
302
+ try:
303
+ content = {"mode": "data", "data": json.loads(args.data)}
304
+ except json.JSONDecodeError as exc:
305
+ _die(f"--data is not valid JSON: {exc}")
306
+
307
+ env = omp.build_envelope(
308
+ from_agent=ident["agent_id"],
309
+ to_agent=args.to,
310
+ intent=args.intent,
311
+ content=content,
312
+ delegation_ref=args.delegation,
313
+ idempotency_key=args.idempotency,
314
+ signed_path="/gateway/omp/send",
315
+ )
316
+ omp.sign_envelope(env, method="POST", path="/gateway/omp/send",
317
+ private_key=priv)
318
+
319
+ try:
320
+ r = requests.post(f"{gateway}/gateway/omp/send",
321
+ json={"envelope": env}, timeout=40)
322
+ except requests.RequestException as exc:
323
+ _die(f"cannot reach the gateway: {exc}")
324
+ print(json.dumps(r.json(), indent=2))
325
+ return 0 if r.ok else 1
326
+
327
+
328
+ def cmd_verify(args) -> int:
329
+ """Verify a receipt offline — signature and expiry only."""
330
+ try:
331
+ import omp
332
+ except ImportError:
333
+ _die("the omp module is required for `verify`")
334
+ path = args.receipt
335
+ if not os.path.exists(path):
336
+ _die(f"no such file: {path}")
337
+ with open(path, "r", encoding="utf-8") as fh:
338
+ receipt = json.load(fh)
339
+ signer = (receipt.get("signature") or {}).get("key_id", "")
340
+ gateway = args.gateway or DEFAULT_GATEWAY
341
+ try:
342
+ r = requests.get(f"{gateway}/api/agent/{signer}/key", timeout=15)
343
+ except requests.RequestException as exc:
344
+ _die(f"cannot reach the gateway: {exc}")
345
+ if not r.ok:
346
+ _die(f"cannot resolve the signer's key ({r.status_code})")
347
+ pub_hex = r.json()["public_key"]
348
+ ok, reasons = omp.verify_receipt(receipt, public_key=pub_hex)
349
+ if ok:
350
+ _ok(f"receipt VALID - signed by {signer}")
351
+ print(f" outcome: {receipt.get('outcome')}")
352
+ print(f" ledger : {receipt.get('ledger_ref')}")
353
+ return 0
354
+ _fail("receipt INVALID")
355
+ for reason in reasons:
356
+ print(f" {reason['code']}: {reason['detail']}")
357
+ return 1
358
+
359
+
360
+ def cmd_whoami(args) -> int:
361
+ ident = require_identity()
362
+ print(ident.get("agent_id") or ident.get("application_id"))
363
+ return 0
364
+
365
+
366
+ # ---------------------------------------------------------------------------
367
+ # entry point
368
+ # ---------------------------------------------------------------------------
369
+
370
+ def build_parser() -> argparse.ArgumentParser:
371
+ p = argparse.ArgumentParser(
372
+ prog="othrion",
373
+ description="Join and use the Othrion trust network.",
374
+ )
375
+ p.add_argument("--version", action="version", version="othrion-agent 1.1.0")
376
+ sub = p.add_subparsers(dest="command", required=True)
377
+
378
+ e = sub.add_parser("enroll", help="generate a keypair and enroll")
379
+ e.add_argument("--name", required=True, help="agent display name")
380
+ e.add_argument("--owner", default="", help="owning business or human")
381
+ e.add_argument("--owner-type", default="BUSINESS",
382
+ choices=["BUSINESS", "HUMAN"])
383
+ e.add_argument("--email", default="", help="contact email")
384
+ e.add_argument("--endpoint", default="", help="your agent's URL")
385
+ e.add_argument("--region", default="HK", help="registration country (HK)")
386
+ e.add_argument("--gateway", default=DEFAULT_GATEWAY)
387
+ e.add_argument("--force", action="store_true",
388
+ help="replace an existing identity (discards the key)")
389
+ e.set_defaults(func=cmd_enroll)
390
+
391
+ s = sub.add_parser("status", help="show local and remote state")
392
+ s.set_defaults(func=cmd_status)
393
+
394
+ k = sub.add_parser("key", help="issue an API key")
395
+ k.add_argument("--agent-id", default=None)
396
+ k.set_defaults(func=cmd_key)
397
+
398
+ h = sub.add_parser("handshake", help="open a session")
399
+ h.set_defaults(func=cmd_handshake)
400
+
401
+ d = sub.add_parser("send", help="send a signed OMP envelope")
402
+ d.add_argument("--to", required=True, help="recipient agent id")
403
+ d.add_argument("--intent", required=True)
404
+ d.add_argument("--message", default="", help="free text (non-binding)")
405
+ d.add_argument("--data", default="", help="JSON data (binding intents)")
406
+ d.add_argument("--delegation", default=None)
407
+ d.add_argument("--idempotency", default=None)
408
+ d.set_defaults(func=cmd_send)
409
+
410
+ v = sub.add_parser("verify", help="verify a receipt offline")
411
+ v.add_argument("receipt", help="path to a receipt JSON file")
412
+ v.add_argument("--gateway", default=None)
413
+ v.set_defaults(func=cmd_verify)
414
+
415
+ w = sub.add_parser("whoami", help="print the agent id")
416
+ w.set_defaults(func=cmd_whoami)
417
+
418
+ return p
419
+
420
+
421
+ def main(argv: list[str] | None = None) -> int:
422
+ args = build_parser().parse_args(argv)
423
+ return args.func(args)
424
+
425
+
426
+ if __name__ == "__main__":
427
+ raise SystemExit(main())
othrion/permissions.py ADDED
@@ -0,0 +1,132 @@
1
+ """WAP permission model — vendored into the SDK so it is self-contained.
2
+
3
+ This is a copy of the gateway's `permissions.py`. It is duplicated
4
+ deliberately: `pip install othrion-agent` must work on a machine that has
5
+ never seen the Othrion source tree, so the SDK cannot import from it.
6
+
7
+ If you change the model, change BOTH files. The gateway copy is the
8
+ reference; this one must stay byte-compatible in behaviour.
9
+
10
+ Four levels:
11
+ L0 PUBLIC search / view / query / quote — no identity needed
12
+ L1 REGISTERED create draft / reserve / submit — valid Othrion ID
13
+ L2 DELEGATED purchase / book / approve / sign — delegation credential
14
+ L3 PRIVILEGED refunds / loans / contract changes — business authority
15
+
16
+ Pure logic — no network, no database.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from decimal import Decimal
22
+
23
+ L0, L1, L2, L3 = 0, 1, 2, 3
24
+ LEVEL_NAMES = {L0: "PUBLIC", L1: "REGISTERED", L2: "DELEGATED",
25
+ L3: "PRIVILEGED"}
26
+
27
+ INTENT_LEVELS: dict[str, int] = {
28
+ # L0 public
29
+ "travel.search": L0, "flight.search": L0, "cargo.quote": L0,
30
+ "product.search": L0, "price.check": L0,
31
+ # L1 registered
32
+ "travel.reserve": L1, "booking.draft": L1, "employment.apply": L1,
33
+ "loan.apply": L1, "document.draft": L1,
34
+ # L2 delegated
35
+ "travel.book": L2, "flight.book": L2, "purchase.order": L2,
36
+ "sign.document": L2, "bnpl.checkout": L2, "employment.hire": L2,
37
+ # L3 privileged
38
+ "refund.issue": L3, "loan.approve": L3, "contract.modify": L3,
39
+ "identity.certify": L3,
40
+ }
41
+
42
+ ALWAYS_DENIED: dict[str, str] = {
43
+ "account.password_change": "change passwords",
44
+ "account.delete": "delete accounts",
45
+ "funds.transfer": "transfer money",
46
+ "funds.withdraw": "withdraw funds",
47
+ "identity.impersonate": "impersonate another identity",
48
+ "ledger.tamper": "tamper with the ledger",
49
+ }
50
+
51
+ REQUIRES_DELEGATION = {L2}
52
+
53
+
54
+ def intent_level(intent: str) -> int | None:
55
+ """Map an intent to its permission level (longest prefix wins)."""
56
+ best: tuple[int, int] | None = None
57
+ for prefix, level in INTENT_LEVELS.items():
58
+ if intent == prefix or intent.startswith(prefix + "."):
59
+ if best is None or len(prefix) > best[0]:
60
+ best = (len(prefix), level)
61
+ return best[1] if best else None
62
+
63
+
64
+ def check_action(
65
+ *,
66
+ intent: str,
67
+ agent_level: int,
68
+ has_delegation: bool = False,
69
+ delegation_max: Decimal | None = None,
70
+ amount: Decimal | None = None,
71
+ delegation_merchants: list[str] | None = None,
72
+ merchant: str | None = None,
73
+ ) -> tuple[bool, list[dict]]:
74
+ """Evaluate whether an agent may perform an intent.
75
+
76
+ Returns (allowed, reasons) with structured {code, detail} reasons.
77
+ """
78
+ reasons: list[dict] = []
79
+
80
+ def deny(code: str, detail: str) -> None:
81
+ reasons.append({"code": code, "detail": detail})
82
+
83
+ # 0. sandbox hard deny — beats everything, even L3
84
+ if intent in ALWAYS_DENIED:
85
+ deny("ACTION_NOT_ALLOWED",
86
+ f"{intent} is never permitted ({ALWAYS_DENIED[intent]})")
87
+ return (False, reasons)
88
+
89
+ # 1. unknown intent -> not in the model
90
+ level = intent_level(intent)
91
+ if level is None:
92
+ deny("PERMISSION_DENIED", f"unknown intent {intent!r}")
93
+ return (False, reasons)
94
+
95
+ # 2. level check
96
+ if agent_level < level:
97
+ deny("PERMISSION_DENIED",
98
+ f"intent requires level {LEVEL_NAMES[level]} "
99
+ f"({level}), agent is {LEVEL_NAMES[agent_level]} ({agent_level})")
100
+ return (False, reasons)
101
+
102
+ # 3. L2 requires a live delegation credential
103
+ if level in REQUIRES_DELEGATION and not has_delegation:
104
+ deny("DELEGATION_REQUIRED",
105
+ f"{intent} requires a human delegation credential")
106
+ return (False, reasons)
107
+
108
+ # 4. delegation scope checks (amount + merchant)
109
+ if level in REQUIRES_DELEGATION and has_delegation:
110
+ if amount is not None and delegation_max is not None \
111
+ and amount > delegation_max:
112
+ deny("DELEGATION_REQUIRED",
113
+ f"amount HK${amount} exceeds delegated limit "
114
+ f"HK${delegation_max}")
115
+ return (False, reasons)
116
+ if merchant and delegation_merchants:
117
+ if merchant not in delegation_merchants:
118
+ deny("DELEGATION_REQUIRED",
119
+ f"merchant {merchant!r} not in delegated scope "
120
+ f"{delegation_merchants}")
121
+ return (False, reasons)
122
+
123
+ return (not reasons, reasons)
124
+
125
+
126
+ def required_level(intent: str) -> int | None:
127
+ """Public helper: what level does this intent need?"""
128
+ return intent_level(intent)
129
+
130
+
131
+ __all__ = ["L0", "L1", "L2", "L3", "LEVEL_NAMES", "INTENT_LEVELS",
132
+ "ALWAYS_DENIED", "intent_level", "check_action", "required_level"]
@@ -0,0 +1,195 @@
1
+ Metadata-Version: 2.4
2
+ Name: othrion-agent
3
+ Version: 1.1.0
4
+ Summary: Join and use the Othrion trust network — identity, signatures and receipts for AI agents
5
+ Author-email: Othrion <ai@othrion.ai>
6
+ License-Expression: LicenseRef-Proprietary
7
+ Project-URL: Homepage, https://othrion.ai
8
+ Project-URL: Documentation, https://othrion.ai/docs
9
+ Project-URL: Join, https://othrion.ai/join
10
+ Keywords: ai,agents,trust,identity,ed25519,protocol,omp
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
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: Topic :: Security :: Cryptography
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Operating System :: OS Independent
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ Requires-Dist: requests>=2.28
24
+ Requires-Dist: cryptography>=3.4
25
+ Provides-Extra: serve
26
+ Requires-Dist: flask>=3.0; extra == "serve"
27
+
28
+ # othrion-agent
29
+
30
+ **Join the Othrion trust network in three commands.**
31
+
32
+ Othrion is the trust and identity layer for AI representatives. You keep your
33
+ model, your framework and your cloud — you add an identity, a signature and a
34
+ receipt.
35
+
36
+ ```bash
37
+ pip install othrion-agent
38
+
39
+ othrion enroll --name "Acme Travel AI" \
40
+ --owner "Acme Travel Ltd" \
41
+ --email ai@acme.com \
42
+ --endpoint https://acme.com/agent
43
+
44
+ othrion key --agent-id OTH-HK-00000001
45
+ othrion handshake
46
+ ```
47
+
48
+ That is the whole onboarding. No email, no waiting, no manual step.
49
+
50
+ ---
51
+
52
+ ## Why
53
+
54
+ Companies already use AI to transact. The business on the other side cannot
55
+ answer one question: **who is accountable when this AI acts?**
56
+
57
+ Othrion answers it with a signed, verifiable chain:
58
+
59
+ ```
60
+ This AI (OTH-HK-00000001)
61
+ → owned by this business (Bili Tayo)
62
+ → owned by this company (PrizeSmart Ltd)
63
+ → real registration, real signatory, real address
64
+ ```
65
+
66
+ You verify it in one call and decide: accept this AI customer with confidence.
67
+
68
+ ---
69
+
70
+ ## What you get
71
+
72
+ | Command | What it does |
73
+ |---|---|
74
+ | `othrion enroll` | Generate an Ed25519 keypair locally, register, prove ownership |
75
+ | `othrion status` | Your identity, your passport, the live gateway state |
76
+ | `othrion key` | Issue a gateway API key |
77
+ | `othrion handshake` | Open a session |
78
+ | `othrion send` | Send a signed OMP envelope to another agent |
79
+ | `othrion verify` | Verify a receipt offline — signature and expiry, no network |
80
+ | `othrion whoami` | Print your agent id (useful in scripts) |
81
+
82
+ ---
83
+
84
+ ## Your private key never leaves your machine
85
+
86
+ `othrion enroll` generates the keypair **locally**. Only the public half is
87
+ sent to Othrion. The private key is written to `~/.othrion/identity.json` with
88
+ owner-only permissions and is never transmitted, logged or printed.
89
+
90
+ Othrion can verify your signatures. It can never sign as you.
91
+
92
+ ---
93
+
94
+ ## Use it from code
95
+
96
+ ```python
97
+ from othrion import Agent
98
+
99
+ agent = Agent(
100
+ name="Acme Travel AI",
101
+ endpoint="https://acme.com/agent",
102
+ capabilities=["travel.search", "travel.book"],
103
+ )
104
+ agent.register() # Stage 1
105
+ agent.verify() # Stage 2 — sign the challenge
106
+ agent.get_api_key("OTH-HK-00000001") # Stage 4
107
+ agent.handshake() # -> session_id
108
+ agent.route("travel.search", {"origin": "HKG", "destination": "MNL"})
109
+ ```
110
+
111
+ ### Already have an AI?
112
+
113
+ You do not need to rebuild it. Wrap it — your model, your code, unchanged.
114
+
115
+ ```python
116
+ from othrion import Bridge
117
+
118
+ bridge = Bridge(
119
+ existing_ai=tripgenie, # any object with .handle()
120
+ capabilities=["flight.search", "flight.book"],
121
+ )
122
+ bridge.register() # one afternoon, no core changes
123
+ bridge.serve() # exposes /.well-known/othrion + /agent/*
124
+ ```
125
+
126
+ ---
127
+
128
+ ## Serving your own agent
129
+
130
+ `serve()` needs Flask, which is an optional extra:
131
+
132
+ ```bash
133
+ pip install "othrion-agent[serve]"
134
+ ```
135
+
136
+ ```python
137
+ agent.serve(port=4115)
138
+ ```
139
+
140
+ This exposes the standard WAP endpoints:
141
+
142
+ | Endpoint | Purpose |
143
+ |---|---|
144
+ | `GET /.well-known/othrion` | Discovery metadata |
145
+ | `POST /agent/handshake` | Open a session |
146
+ | `GET /agent/capabilities` | What this agent offers |
147
+ | `POST /agent/action` | Perform an intent (permission-gated) |
148
+ | `GET /agent/health` | Liveness |
149
+
150
+ ---
151
+
152
+ ## Permission model
153
+
154
+ Every intent maps to a level. The gate is enforced on both sides.
155
+
156
+ | Level | Name | Meaning | Requires |
157
+ |---|---|---|---|
158
+ | L0 | PUBLIC | search / view / quote | nothing |
159
+ | L1 | REGISTERED | draft / reserve / submit | a valid Othrion ID |
160
+ | L2 | DELEGATED | purchase / book / sign | a delegation credential |
161
+ | L3 | PRIVILEGED | refunds / loans / certify | business authority |
162
+
163
+ A hard deny-list beats every level, including L3: password change, account
164
+ deletion, fund transfer, fund withdrawal, impersonation, ledger tampering.
165
+
166
+ ---
167
+
168
+ ## Requirements
169
+
170
+ | Item | Value |
171
+ |---|---|
172
+ | Python | 3.10 or newer |
173
+ | Registration country | `HK` (Hong Kong) — open now |
174
+ | Identity format | `OTH-HK-########` |
175
+ | Signature | Ed25519 |
176
+ | Gateway | `https://othrion.ai` |
177
+
178
+ > **Hong Kong is the only open jurisdiction today.** Philippines, Singapore,
179
+ > Malaysia, Indonesia, Taiwan, Macau, Thailand, Vietnam, UAE, Saudi Arabia and
180
+ > the UK are registered as *planned*. An agent cannot be enrolled in a country
181
+ > that is not open — that is deliberate.
182
+
183
+ ---
184
+
185
+ ## Links
186
+
187
+ - **Join:** https://othrion.ai/join
188
+ - **Docs:** https://othrion.ai/docs
189
+ - **Trust Directory:** https://othrion.ai/directory
190
+
191
+ ---
192
+
193
+ ## Licence
194
+
195
+ Proprietary. © Othrion.
@@ -0,0 +1,8 @@
1
+ othrion/__init__.py,sha256=pMcLtqklliAaAKqotsokNPfd0GUtIN9nvtsF3eiqGlg,12586
2
+ othrion/cli.py,sha256=zKQUa6G0ZIXuivQGav3E8m3H3KFBeXQLELaqqI69QV4,15658
3
+ othrion/permissions.py,sha256=e9fsUvtST--AP6XWLTMTfJ4iPA2nDMLvyHxEUcdWTAE,4920
4
+ othrion_agent-1.1.0.dist-info/METADATA,sha256=hznR-QMOy_UJsIiL5J6RHCGULtCSxDR1PdpK5DmZxek,5882
5
+ othrion_agent-1.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ othrion_agent-1.1.0.dist-info/entry_points.txt,sha256=ZTHtYa5xRlRhC-focT7XC7bIzNtjIh9JU4fEecgmm1o,45
7
+ othrion_agent-1.1.0.dist-info/top_level.txt,sha256=bGI4sl7t9DucA-wFdEQP2e1w0Q2apYhCHadop7OeSsw,8
8
+ othrion_agent-1.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,2 @@
1
+ [console_scripts]
2
+ othrion = othrion.cli:main
@@ -0,0 +1 @@
1
+ othrion