tryagentkey 0.5.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.
tryagentkey/keys.py ADDED
@@ -0,0 +1,24 @@
1
+ """ak_ API key: base64url JSON bundle of the agent's own sign-in (byte-compatible with the JS SDK)."""
2
+ import base64, json
3
+ from urllib.parse import urlparse
4
+ from .errors import AgentKeyError
5
+
6
+ PREFIX = "ak_"
7
+
8
+ def _b64(s):
9
+ return base64.urlsafe_b64encode(s.encode()).decode().rstrip("=")
10
+
11
+ def encode_api_key(agent_id, sign_in):
12
+ return PREFIX + _b64(json.dumps({"v": 1, "agent_id": agent_id, "url": sign_in["url"], "email": sign_in["email"], "password": sign_in["password"], "apikey": sign_in["apikey"]}, separators=(",", ":")))
13
+
14
+ def decode_api_key(key):
15
+ if not isinstance(key, str) or not key.startswith(PREFIX):
16
+ raise AgentKeyError("invalid_api_key", "AGENTKEY_API_KEY must start with ak_. Run `npx tryagentkey link`.")
17
+ raw = key[len(PREFIX):]
18
+ try:
19
+ k = json.loads(base64.urlsafe_b64decode(raw + "=" * (-len(raw) % 4)).decode())
20
+ except Exception:
21
+ raise AgentKeyError("invalid_api_key", "AGENTKEY_API_KEY is damaged. Run `npx tryagentkey link` again.")
22
+ if k.get("v") != 1 or urlparse(k.get("url", "")).scheme != "https" or not all(k.get(f) for f in ("agent_id", "email", "password", "apikey")):
23
+ raise AgentKeyError("invalid_api_key", "AGENTKEY_API_KEY is not valid. Run `npx tryagentkey link` again.")
24
+ return k
@@ -0,0 +1,186 @@
1
+ """Free Local Mode vault, file-compatible with the JS SDK (~/.agentkey/vault.enc).
2
+ AES-256-GCM, key = HKDF(machine.key, hostname). Never stores website cookies.
3
+
4
+ A saved login is not permission. Each permission is scoped to one site, one saved login
5
+ version, one project folder and one agent name; standing (until revoked), single-use or
6
+ expiring. Every check re-reads the file, so a revoke takes effect in a running agent."""
7
+ import json, os, socket, uuid, datetime, time
8
+ from pathlib import Path
9
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
10
+ from cryptography.hazmat.primitives.kdf.hkdf import HKDF
11
+ from cryptography.hazmat.primitives import hashes
12
+ from .errors import AgentKeyError
13
+ from .env import agentkey_home
14
+
15
+ AAD = b"AgentKey.local.vault.v1"
16
+
17
+ def _write(p, data):
18
+ tmp = Path(f"{p}.{os.urandom(4).hex()}.tmp")
19
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
20
+ with os.fdopen(fd, "wb") as f:
21
+ f.write(data)
22
+ try:
23
+ os.chmod(tmp, 0o600)
24
+ except OSError:
25
+ pass
26
+ os.replace(tmp, p) # atomic on Windows, macOS and Linux
27
+
28
+ def _machine_key(home):
29
+ home.mkdir(parents=True, exist_ok=True)
30
+ p = home / "machine.key"
31
+ if not p.exists():
32
+ _write(p, os.urandom(32))
33
+ return HKDF(algorithm=hashes.SHA256(), length=32, salt=socket.gethostname().encode(), info=AAD).derive(p.read_bytes())
34
+
35
+ def _now_iso():
36
+ d = datetime.datetime.now(datetime.timezone.utc)
37
+ return d.strftime("%Y-%m-%dT%H:%M:%S.") + f"{d.microsecond // 1000:03d}Z"
38
+
39
+ def _ts(iso):
40
+ return datetime.datetime.fromisoformat(iso.replace("Z", "+00:00")).timestamp()
41
+
42
+ def normalize(d):
43
+ """Older vaults stored unscoped approvals[origin]=True; those are dropped (ask once again, no retyping)."""
44
+ if not d:
45
+ return d
46
+ d.setdefault("logins", {}); d.setdefault("permissions", {}); d.setdefault("secrets", {})
47
+ for l in d["logins"].values():
48
+ l.setdefault("item_id", str(uuid.uuid4())); l.setdefault("version", 1)
49
+ d.pop("approvals", None)
50
+ return d
51
+
52
+ def permission_valid(p, login, origin, project_id, agent, now=None):
53
+ now = time.time() if now is None else now
54
+ return bool(p and login and p.get("origin") == origin and p.get("project_id") == project_id and p.get("agent") == agent
55
+ and p.get("item_id") == login.get("item_id") and p.get("item_version") == login.get("version") and not p.get("revoked_at")
56
+ and (p.get("expires_at") is None or _ts(p["expires_at"]) > now)
57
+ and (p.get("max_uses") is None or p.get("uses", 0) < p["max_uses"]))
58
+
59
+ def _public(p):
60
+ return {"id": p["id"], "origin": p["origin"], "project": p.get("project", ""), "project_id": p["project_id"], "agent": p["agent"],
61
+ "created_at": p["created_at"], "expires_at": p.get("expires_at"), "kind": "standing" if p.get("max_uses") is None else "limited",
62
+ "uses": p.get("uses", 0), "max_uses": p.get("max_uses"), "last_used_at": p.get("last_used_at")}
63
+
64
+ def _self_valid(d, p):
65
+ return permission_valid(p, d["logins"].get(p["origin"]), p["origin"], p["project_id"], p["agent"])
66
+
67
+ class LocalVault:
68
+ def __init__(self, home=None):
69
+ self.home = Path(home) if home else agentkey_home()
70
+ self.file = self.home / "vault.enc"
71
+ self._key = _machine_key(self.home)
72
+ self._data = self._read()
73
+
74
+ def _read(self):
75
+ if not self.file.exists():
76
+ return None
77
+ raw = self.file.read_bytes()
78
+ iv, tag, ct = raw[:12], raw[12:28], raw[28:]
79
+ try:
80
+ return normalize(json.loads(AESGCM(self._key).decrypt(iv, ct + tag, AAD)))
81
+ except Exception:
82
+ raise AgentKeyError("vault_unreadable", "The local vault was made on another computer or is damaged. Move ~/.agentkey/vault.enc aside and run `npx tryagentkey init`.")
83
+
84
+ def reload(self):
85
+ self._data = self._read()
86
+ return self._data
87
+
88
+ def _save(self):
89
+ iv = os.urandom(12)
90
+ out = AESGCM(self._key).encrypt(iv, json.dumps(self._data, separators=(",", ":")).encode(), AAD)
91
+ _write(self.file, iv + out[-16:] + out[:-16])
92
+
93
+ def exists(self):
94
+ return self.reload() is not None
95
+
96
+ @property
97
+ def id(self):
98
+ return (self._data or {}).get("vault_id")
99
+
100
+ def init(self):
101
+ self.reload()
102
+ if self._data is None:
103
+ self._data = {"v": 1, "vault_id": str(uuid.uuid4()), "logins": {}, "permissions": {}, "secrets": {}}
104
+ self._save()
105
+ return self._data["vault_id"]
106
+
107
+ def sites(self):
108
+ d = self.reload() or {"logins": {}, "permissions": {}}
109
+ return [{"origin": o, "username": v["username"], "saved_at": v.get("saved_at"),
110
+ "permissions": sum(1 for p in d["permissions"].values() if p["origin"] == o and _self_valid(d, p))} for o, v in d["logins"].items()]
111
+
112
+ def has_login(self, origin):
113
+ d = self.reload()
114
+ return bool(d and d["logins"].get(origin))
115
+
116
+ def put_login(self, origin, username, password):
117
+ self.init()
118
+ prev = self._data["logins"].get(origin) or {}
119
+ self._data["logins"][origin] = {"item_id": prev.get("item_id") or str(uuid.uuid4()), "version": prev.get("version", 0) + 1,
120
+ "username": str(username or ""), "password": str(password), "saved_at": _now_iso()}
121
+ for pid in [k for k, p in self._data["permissions"].items() if not _self_valid(self._data, p)]:
122
+ del self._data["permissions"][pid]
123
+ self._save()
124
+
125
+ def grant(self, origin, project_id, agent, project="", expires_at=None, max_uses=None):
126
+ self.init()
127
+ l = self._data["logins"].get(origin)
128
+ if not l: raise AgentKeyError("login_not_saved")
129
+ if not project_id or not agent: raise AgentKeyError("scope_required")
130
+ p = {"id": str(uuid.uuid4()), "origin": origin, "item_id": l["item_id"], "item_version": l["version"], "project_id": project_id,
131
+ "project": str(project or ""), "agent": str(agent), "created_at": _now_iso(),
132
+ "expires_at": datetime.datetime.fromtimestamp(expires_at, datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z") if expires_at else None,
133
+ "max_uses": None if max_uses is None else max(1, int(max_uses)), "uses": 0, "last_used_at": None}
134
+ self._data["permissions"][p["id"]] = p
135
+ self._save()
136
+ return _public(p)
137
+
138
+ def find_permission(self, origin, project_id, agent):
139
+ d = self.reload()
140
+ if not d: return None
141
+ l = d["logins"].get(origin)
142
+ for p in d["permissions"].values():
143
+ if permission_valid(p, l, origin, project_id, agent):
144
+ return _public(p)
145
+ return None
146
+
147
+ def permissions(self):
148
+ d = self.reload()
149
+ return [_public(p) for p in d["permissions"].values() if _self_valid(d, p)] if d else []
150
+
151
+ def _use_credential(self, permission_id, origin, project_id, agent):
152
+ """Fill step only, right before typing. Re-checks from disk and counts the use; never returned to agents or tools."""
153
+ d = self.reload()
154
+ p = (d or {}).get("permissions", {}).get(permission_id)
155
+ l = (d or {}).get("logins", {}).get(origin)
156
+ if not permission_valid(p, l, origin, project_id, agent):
157
+ raise AgentKeyError("permission_revoked", "This permission was revoked or ran out. Run ak.login again to ask the owner.")
158
+ p["uses"] = p.get("uses", 0) + 1; p["last_used_at"] = _now_iso()
159
+ if p.get("max_uses") is not None and p["uses"] >= p["max_uses"]:
160
+ del d["permissions"][permission_id]
161
+ self._save()
162
+ return {"username": l["username"], "password": l["password"]}
163
+
164
+ def revoke(self, target):
165
+ d = self.reload()
166
+ if not d: return 0
167
+ gone = [k for k, p in d["permissions"].items() if target == "all" or k == target or p["origin"] == target]
168
+ for k in gone: del d["permissions"][k]
169
+ if gone: self._save()
170
+ return len(gone)
171
+
172
+ def forget(self, origin):
173
+ if self.reload():
174
+ self._data["logins"].pop(origin, None)
175
+ for k in [k for k, p in self._data["permissions"].items() if p["origin"] == origin]:
176
+ del self._data["permissions"][k]
177
+ self._save()
178
+
179
+ def set_secret(self, name, value):
180
+ self.init(); self._data["secrets"][name] = str(value); self._save()
181
+
182
+ def get_secret(self, name):
183
+ return (self.reload() or {}).get("secrets", {}).get(name)
184
+
185
+ def secret_names(self):
186
+ return list((self.reload() or {}).get("secrets", {}))
@@ -0,0 +1,76 @@
1
+ """AgentKey MCP over stdio for Python hosts (`uvx agentkey-mcp`). Same tools and allowlists as @tryagentkey/mcp."""
2
+ import json, sys, os
3
+ from .client import AgentKeyClient, token_source
4
+ from .keys import decode_api_key
5
+ from .env import read_env
6
+ from .errors import AgentKeyError
7
+
8
+ _ID = {"type": "string", "format": "uuid"}
9
+ TOOLS = [
10
+ {"name": "agentkey_request", "description": "Request owner-approved credential use. Never returns credentials.", "inputSchema": {"type": "object", "properties": {"agent_id": _ID, "executor_id": _ID, "origin": {"type": "string", "format": "uri"}, "site_name": {"type": "string"}, "signin_url": {"type": "string"}}, "required": ["agent_id", "executor_id", "origin", "site_name"], "additionalProperties": False}},
11
+ {"name": "agentkey_request_status", "description": "Read redacted approval status.", "inputSchema": {"type": "object", "properties": {"request_id": _ID}, "required": ["request_id"], "additionalProperties": False}},
12
+ {"name": "agentkey_use", "description": "Use an active grant through its enrolled executor. Returns pending operation, not a secret.", "inputSchema": {"type": "object", "properties": {"grant_id": _ID, "origin": {"type": "string"}, "executor_key_id": _ID, "idempotency_key": _ID}, "required": ["grant_id", "origin", "executor_key_id", "idempotency_key"], "additionalProperties": False}},
13
+ {"name": "agentkey_receipt", "description": "Read redacted executor operation receipt.", "inputSchema": {"type": "object", "properties": {"operation_id": _ID}, "required": ["operation_id"], "additionalProperties": False}},
14
+ ]
15
+
16
+ def handler(client):
17
+ st = {"init": False, "ready": False}
18
+ def err(i, c, m): return {"jsonrpc": "2.0", "id": i, "error": {"code": c, "message": m}}
19
+ def handle(msg):
20
+ i = msg.get("id") if isinstance(msg, dict) else None
21
+ if not isinstance(msg, dict) or msg.get("jsonrpc") != "2.0" or not isinstance(msg.get("method"), str):
22
+ return err(None, -32600, "Invalid Request")
23
+ if "id" not in msg:
24
+ if msg["method"] == "notifications/initialized" and st["init"]: st["ready"] = True
25
+ return None
26
+ m = msg["method"]
27
+ if m == "initialize":
28
+ v = (msg.get("params") or {}).get("protocolVersion")
29
+ if st["init"] or v not in ("2025-06-18", "2024-11-05"): return err(i, -32602, "Unsupported initialization")
30
+ st["init"] = True
31
+ return {"jsonrpc": "2.0", "id": i, "result": {"protocolVersion": v, "capabilities": {"tools": {}}, "serverInfo": {"name": "AgentKey", "version": "0.5.0"}}}
32
+ if m == "ping": return {"jsonrpc": "2.0", "id": i, "result": {}}
33
+ if not st["ready"]: return err(i, -32000, "Server not initialized")
34
+ if m == "tools/list": return {"jsonrpc": "2.0", "id": i, "result": {"tools": TOOLS}}
35
+ if m != "tools/call": return err(i, -32601, "Method not found")
36
+ p = msg.get("params") or {}; name, a = p.get("name"), p.get("arguments") or {}
37
+ tool = next((t for t in TOOLS if t["name"] == name), None)
38
+ if not tool or not isinstance(a, dict) or any(k not in tool["inputSchema"]["properties"] or not isinstance(v, str) for k, v in a.items()) or any(k not in a for k in tool["inputSchema"]["required"]):
39
+ return err(i, -32602, "Invalid params")
40
+ try:
41
+ if name == "agentkey_request": data = client.request(**a)
42
+ elif name == "agentkey_request_status": data = client.request_status(a["request_id"])
43
+ elif name == "agentkey_use": data = client.use(**a)
44
+ else: data = client.receipt(a["operation_id"])
45
+ res = {"content": [{"type": "text", "text": json.dumps(data)}], "isError": False}
46
+ except Exception:
47
+ res = {"content": [{"type": "text", "text": "AgentKey request failed"}], "isError": True}
48
+ return {"jsonrpc": "2.0", "id": i, "result": res}
49
+ return handle
50
+
51
+ def client_from_env(env=None):
52
+ cfg = read_env(env)
53
+ if cfg["api_key"]:
54
+ return AgentKeyClient(cfg["base_url"], token_source(decode_api_key(cfg["api_key"])))
55
+ if cfg["legacy_token"]:
56
+ t = cfg["legacy_token"]; return AgentKeyClient(cfg["base_url"], lambda: t)
57
+ return None
58
+
59
+ def serve(client, inp=sys.stdin, out=sys.stdout):
60
+ h = handler(client)
61
+ for line in inp:
62
+ if not line.strip(): continue
63
+ try:
64
+ r = h(json.loads(line)) if len(line) <= 65536 else {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "Request too large"}}
65
+ except ValueError:
66
+ r = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}}
67
+ if r: out.write(json.dumps(r) + "\n"); out.flush()
68
+
69
+ def main():
70
+ try:
71
+ c = client_from_env()
72
+ except AgentKeyError as e:
73
+ sys.stderr.write(f"AgentKey setup problem: {e}\n"); sys.exit(1)
74
+ if not c:
75
+ sys.stderr.write("Set AGENTKEY_API_KEY (run `npx tryagentkey link`).\n"); sys.exit(1)
76
+ serve(c)
tryagentkey/runtime.py ADDED
@@ -0,0 +1,249 @@
1
+ """AgentKey runtime for an agent's own existing browser (Python port of @tryagentkey/runtime).
2
+ Never launches a browser or exports cookies. The private key and opened credentials stay in this
3
+ process; nothing here logs or returns them. Envelopes are byte-compatible with the JS runtime."""
4
+ import base64, hashlib, json, os, re, secrets, time
5
+ from urllib.parse import urlparse
6
+ from urllib.request import Request, urlopen
7
+ from urllib.error import HTTPError
8
+ from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey
9
+ from cryptography.hazmat.primitives.kdf.hkdf import HKDF
10
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
11
+ from cryptography.hazmat.primitives import hashes, serialization
12
+ from .errors import AgentKeyError
13
+ from .confirm import _a
14
+
15
+ UUID = re.compile(r"^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$", re.I)
16
+ NAMES = ["ownerID", "requestID", "agentID", "executorID", "executorKeyID", "itemID"]
17
+ ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
18
+ DEFAULT_BASE = "https://agentkey.waiwiser.com/api/public/agentkey-api"
19
+ _b64e = lambda b: base64.b64encode(b).decode()
20
+ _b64d = lambda s: base64.b64decode(s)
21
+ _u64e = lambda b: base64.urlsafe_b64encode(b).decode().rstrip("=")
22
+ _u64d = lambda s: base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
23
+
24
+ class RuntimeKey:
25
+ def __init__(self, private_key):
26
+ self.private_key = private_key
27
+ self.public_key_b64 = _b64e(private_key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw))
28
+ @classmethod
29
+ def generate(cls):
30
+ return cls(X25519PrivateKey.generate())
31
+ def export(self):
32
+ """Same shape as the JS exportRuntimeKey ({jwk, publicKeyB64}); keep it in the runtime's own secret store."""
33
+ d = self.private_key.private_bytes(serialization.Encoding.Raw, serialization.PrivateFormat.Raw, serialization.NoEncryption())
34
+ x = self.private_key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)
35
+ return {"jwk": {"crv": "X25519", "d": _u64e(d), "ext": True, "key_ops": ["deriveBits"], "kty": "OKP", "x": _u64e(x)}, "publicKeyB64": self.public_key_b64}
36
+ @classmethod
37
+ def load(cls, saved):
38
+ k = cls(X25519PrivateKey.from_private_bytes(_u64d(saved["jwk"]["d"])))
39
+ if saved.get("publicKeyB64") and saved["publicKeyB64"] != k.public_key_b64:
40
+ raise AgentKeyError("invalid_runtime_key")
41
+ return k
42
+
43
+ def _safe_int(v):
44
+ return isinstance(v, int) and not isinstance(v, bool) and abs(v) <= 2**53 - 1
45
+
46
+ def _valid_origin(o):
47
+ try:
48
+ u = urlparse(o)
49
+ return isinstance(o, str) and u.scheme == "https" and f"https://{u.netloc}" == o and "@" not in u.netloc and bool(u.netloc)
50
+ except Exception:
51
+ return False
52
+
53
+ def _target_binding(s, now_ms):
54
+ if "deliveryTarget" not in s:
55
+ return []
56
+ t = s["deliveryTarget"]
57
+ if (not isinstance(t, dict) or t.get("version") != 2 or not re.fullmatch(r"[a-f0-9]{32}", str(t.get("targetID", "")))
58
+ or not re.fullmatch(r"[A-Za-z0-9+/]{43}=", str(t.get("executorPublicKey", ""))) or t.get("origin") != s.get("origin")
59
+ or not _safe_int(t.get("expiresAt")) or t["expiresAt"] <= now_ms or t["expiresAt"] > now_ms + 300000 or s.get("maxUses") != 1):
60
+ raise AgentKeyError("scope_mismatch")
61
+ return ["AgentKey.deliveryTarget.v2", t["targetID"], t["executorPublicKey"], t["origin"], str(t["expiresAt"])]
62
+
63
+ def scope_binding(s, now_ms=None):
64
+ now_ms = time.time() * 1000 if now_ms is None else now_ms
65
+ if not isinstance(s, dict):
66
+ raise AgentKeyError("scope_mismatch")
67
+ if "auxOrigins" in s and (not isinstance(s["auxOrigins"], list) or len(s["auxOrigins"]) > 4 or not all(_valid_origin(o) for o in s["auxOrigins"])):
68
+ raise AgentKeyError("scope_mismatch")
69
+ aux = sorted(set(s.get("auxOrigins") or []))
70
+ if "standingGrantID" in s:
71
+ names = ["ownerID", "standingGrantID", "agentID", "executorID", "executorKeyID", "itemID"]
72
+ if not all(isinstance(s.get(n), str) and UUID.match(s[n]) for n in names): raise AgentKeyError("scope_mismatch")
73
+ if (not _safe_int(s.get("itemVersion")) or s["itemVersion"] < 1 or s.get("action") != "credential.fill" or not _valid_origin(s.get("origin"))
74
+ or any(k in s for k in ("requestID", "expiresAt", "maxUses", "deliveryTarget"))):
75
+ raise AgentKeyError("scope_mismatch")
76
+ return "\n".join(["AgentKey.standing-envelope.v1", *[s[n].lower() for n in names], str(s["itemVersion"]), s["origin"], s["action"], *aux]).encode()
77
+ if not all(isinstance(s.get(n), str) and UUID.match(s[n]) for n in NAMES): raise AgentKeyError("scope_mismatch")
78
+ if (s.get("action") != "credential.fill" or not _valid_origin(s.get("origin")) or not _safe_int(s.get("itemVersion")) or not _safe_int(s.get("expiresAt"))
79
+ or not _safe_int(s.get("maxUses")) or s["maxUses"] < 1 or s["maxUses"] > 3):
80
+ raise AgentKeyError("scope_mismatch")
81
+ if now_ms / 1000 >= s["expiresAt"]: raise AgentKeyError("inactive_grant")
82
+ head = "AgentKey.envelope.v2" if s.get("deliveryTarget") else "AgentKey.envelope.v1"
83
+ return "\n".join([head, *[s[n].lower() for n in NAMES], str(s["itemVersion"]), s["origin"], s["action"], str(s["expiresAt"]), str(s["maxUses"]), *aux, *_target_binding(s, now_ms)]).encode()
84
+
85
+ def _open_sealed(e, key, binding):
86
+ peer = X25519PublicKey.from_public_bytes(_b64d(e["ephemeralPublicKey"]))
87
+ shared = key.private_key.exchange(peer)
88
+ k = HKDF(algorithm=hashes.SHA256(), length=32, salt=b"AgentKey.executor.v1", info=binding).derive(shared)
89
+ c = _b64d(e["sealed"])
90
+ if len(c) < 28: raise AgentKeyError("invalid_envelope")
91
+ try:
92
+ return json.loads(AESGCM(k).decrypt(c[:12], c[12:], binding))
93
+ except Exception:
94
+ raise AgentKeyError("scope_mismatch") from None
95
+
96
+ def open_session_envelope(encoded, pairing_id, key):
97
+ binding = "\n".join(["AgentKey.deviceSession.v1", pairing_id.lower(), key.public_key_b64]).encode()
98
+ e = json.loads(_b64d(encoded))
99
+ if not isinstance(e, dict) or e.get("version") != 1: raise AgentKeyError("invalid_envelope")
100
+ p = _open_sealed(e, key, binding)
101
+ if p.get("pairing_id") != pairing_id or not isinstance(p.get("access_token"), str) or not isinstance(p.get("refresh_token"), str):
102
+ raise AgentKeyError("invalid_envelope")
103
+ return {"access_token": p["access_token"], "refresh_token": p["refresh_token"], "expires_at": p.get("expires_at") or 0}
104
+
105
+ def open_grant_envelope(encoded, scope, key):
106
+ binding = scope_binding(scope)
107
+ if not isinstance(encoded, str) or len(encoded) > 65536: raise AgentKeyError("invalid_envelope")
108
+ e = json.loads(_b64d(encoded))
109
+ if not isinstance(e, dict) or e.get("version") != (2 if scope.get("deliveryTarget") else 1): raise AgentKeyError("invalid_envelope")
110
+ p = _open_sealed(e, key, binding)
111
+ if (not isinstance(p, dict) or not p.get("scope") or scope_binding(p["scope"]) != binding or not isinstance(p.get("username"), str)
112
+ or not isinstance(p.get("password"), str) or "session" in p):
113
+ raise AgentKeyError("scope_mismatch")
114
+ return {"username": p["username"], "password": p["password"]}
115
+
116
+ def _base(base_url):
117
+ u = urlparse(base_url)
118
+ if u.scheme != "https" or u.username or u.password or u.query or u.fragment or u.path.rstrip("/") not in ("", "/api/public/agentkey-api"):
119
+ raise AgentKeyError("invalid_service")
120
+ return f"https://{u.netloc}{u.path.rstrip('/')}"
121
+
122
+ class AgentKeyRuntime:
123
+ def __init__(self, base_url=DEFAULT_BASE, key=None, session=None, on_session=None, opener=urlopen):
124
+ self.base_url, self.key, self.session, self.on_session, self._open = _base(base_url), key, session, on_session, opener
125
+
126
+ def _call(self, method, path, body=None, bearer=None):
127
+ h = {}
128
+ if bearer: h["Authorization"] = "Bearer " + bearer
129
+ if body is not None: h["Content-Type"] = "application/json"
130
+ req = Request(self.base_url + path, data=json.dumps(body).encode() if body is not None else None, method=method, headers=h)
131
+ try:
132
+ with self._open(req, timeout=15) as r:
133
+ return json.loads(r.read() or b"{}")
134
+ except HTTPError as e:
135
+ try:
136
+ j = json.loads(e.read() or b"{}")
137
+ except Exception:
138
+ j = {}
139
+ raise AgentKeyError(str(j.get("code") or j.get("error") or "request_failed")[:80], j.get("help")) from None
140
+
141
+ @classmethod
142
+ def enroll(cls, agent_token, agent_id, base_url=DEFAULT_BASE, label=None, key=None, opener=urlopen, on_session=None):
143
+ """Enroll a fresh runtime with the agent's own requester token. Returns (runtime, owner approval link)."""
144
+ key = key or RuntimeKey.generate()
145
+ rt = cls(base_url, key, None, on_session, opener)
146
+ code = "".join(ALPHA[b % 36] for b in secrets.token_bytes(8))
147
+ body = {"agent_id": agent_id, "code_hash": hashlib.sha256(code.encode()).hexdigest()}
148
+ if label: body["label"] = label
149
+ p = rt._call("POST", "/v1/executor/pairings", body, agent_token)
150
+ red = rt._call("POST", "/v1/executor/redeem", {"code": code, "public_key": key.public_key_b64})
151
+ rt.session = open_session_envelope(red["sealed_session"], red["pairing_id"], key)
152
+ if on_session: on_session(rt.session)
153
+ return rt, p.get("approval_url")
154
+
155
+ def _token(self):
156
+ if not self.session: raise AgentKeyError("not_enrolled")
157
+ if self.session.get("expires_at") and self.session["expires_at"] * 1000 < time.time() * 1000 + 60000:
158
+ self.session = self._call("POST", "/v1/executor/session/refresh", {"refresh_token": self.session["refresh_token"]})
159
+ if self.on_session: self.on_session(self.session)
160
+ return self.session["access_token"]
161
+
162
+ def self_rows(self):
163
+ rows = self._call("GET", "/v1/executor/self", None, self._token()).get("executors") or []
164
+ return [e for e in rows if e.get("enabled") and e.get("public_key") == self.key.public_key_b64]
165
+
166
+ def enrollment(self):
167
+ rows = self.self_rows()
168
+ if len(rows) != 1: raise AgentKeyError("executor_not_enabled")
169
+ return rows[0]
170
+
171
+ def wait_until_enabled(self, timeout=600, interval=3, sleep=time.sleep):
172
+ end = time.monotonic() + timeout
173
+ while True:
174
+ rows = self.self_rows()
175
+ if len(rows) == 1: return rows[0]
176
+ if time.monotonic() > end: raise AgentKeyError("owner_approval_pending", "Still waiting for the owner to trust this agent browser.")
177
+ sleep(interval)
178
+
179
+ def register_target(self, origin, target_id=None, ttl_ms=300000):
180
+ e = self.enrollment()
181
+ target_id = target_id or secrets.token_hex(16)
182
+ self._call("POST", "/v1/executor/targets", {"executor_id": e["executor_id"], "key_id": e["key_id"], "target_id": target_id, "origin": origin,
183
+ "expires_epoch_ms": int(time.time() * 1000) + min(ttl_ms, 300000)}, self._token())
184
+ return {"target_id": target_id, "executor_id": e["executor_id"]}
185
+
186
+ def complete(self, operation_id, outcome):
187
+ return self._call("POST", f"/v1/executor/operations/{operation_id}/complete", {"outcome": outcome}, self._token())
188
+
189
+ async def fill_operation(self, operation_id, page, verify=None, target_bound=False,
190
+ username_selector='input[autocomplete="username"],input[type="email"],input[name*="user" i],input[name*="email" i]',
191
+ password_selector='input[type="password"]', submit=True):
192
+ """Claim one operation and fill it into the agent's EXISTING page. Fails closed unless the page origin matches the grant.
193
+ Reports exactly one outcome; a submitted form is 'unknown' unless verify() confirms the signed-in state."""
194
+ if not UUID.match(operation_id or ""): raise AgentKeyError("invalid_request")
195
+ page_origin = _origin_of(page.url)
196
+ claim = self._call("POST", f"/v1/executor/{'target-operations' if target_bound else 'operations'}/{operation_id}/claim", {}, self._token())
197
+ cred, outcome, submitted, verification, failure = None, "failed", False, "not_requested", None
198
+ try:
199
+ if claim["scope"]["origin"] != page_origin or _origin_of(page.url) != page_origin:
200
+ raise AgentKeyError("page_origin_mismatch")
201
+ cred = open_grant_envelope(claim["encoded"], claim["scope"], self.key)
202
+ pw = page.locator(password_selector)
203
+ if await _a(pw.count()) != 1: raise AgentKeyError("login_form_ambiguous")
204
+ user = page.locator(username_selector)
205
+ uc = await _a(user.count())
206
+ if uc > 1: raise AgentKeyError("login_form_ambiguous")
207
+ if uc == 1: await _a(user.first.fill(cred["username"]))
208
+ await _a(pw.fill(cred["password"]))
209
+ cred = None
210
+ if submit:
211
+ submitted = True # set before dispatch: a timeout may still have submitted
212
+ await _a(pw.press("Enter"))
213
+ if verify:
214
+ verification = "matched" if await _a(verify(page)) else "not_matched"
215
+ outcome = "completed" if verification == "matched" else "unknown"
216
+ else:
217
+ outcome = "unknown"
218
+ else:
219
+ outcome = "completed"
220
+ except Exception as e:
221
+ failure = e
222
+ outcome = "unknown" if submitted else "failed"
223
+ if submitted and verify: verification = "unconfirmed"
224
+ finally:
225
+ cred = None
226
+ self.complete(operation_id, outcome) # exactly one completion attempt; never retry an uncertain submission
227
+ if failure and not submitted: raise failure
228
+ r = {"operation_id": operation_id, "outcome": outcome, "submitted": submitted, "verification": verification}
229
+ if failure: r["code"] = "submission_unconfirmed"
230
+ return r
231
+
232
+ def _origin_of(u):
233
+ p = urlparse(str(u))
234
+ return f"{p.scheme}://{p.netloc}"
235
+
236
+ def file_store(path):
237
+ """Same file as the JS SDK: .agentkey/runtime.json ({key, session}), owner-only."""
238
+ def load():
239
+ try:
240
+ with open(path, encoding="utf-8") as f: return json.load(f)
241
+ except Exception:
242
+ return None
243
+ def save(v):
244
+ os.makedirs(os.path.dirname(path), exist_ok=True)
245
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
246
+ with os.fdopen(fd, "w", encoding="utf-8") as f: json.dump(v, f)
247
+ try: os.chmod(path, 0o600)
248
+ except OSError: pass
249
+ return {"load": load, "save": save}
tryagentkey/tools.py ADDED
@@ -0,0 +1,21 @@
1
+ """Pre-shaped tool specs for LangChain, CrewAI and OpenAI Agents. None return passwords."""
2
+ LOGIN_SCHEMA = {"type": "object", "properties": {"url": {"type": "string", "description": "https sign-in page"}}, "required": ["url"], "additionalProperties": False}
3
+
4
+ def openai_tools():
5
+ return [{"type": "function", "function": {"name": "agentkey_login", "description": "Sign the agent's browser in to a site with an owner-approved login. Never returns the password.", "parameters": LOGIN_SCHEMA}}]
6
+
7
+ def langchain_tool(ak, page):
8
+ from langchain_core.tools import tool
9
+ @tool("agentkey_login")
10
+ def agentkey_login(url: str) -> dict:
11
+ """Sign in to a site with an owner-approved AgentKey login. Never returns the password."""
12
+ return ak.login(url, page=page)
13
+ return agentkey_login
14
+
15
+ def crewai_tool(ak, page):
16
+ from crewai.tools import tool
17
+ @tool("agentkey_login")
18
+ def agentkey_login(url: str) -> dict:
19
+ """Sign in to a site with an owner-approved AgentKey login. Never returns the password."""
20
+ return ak.login(url, page=page)
21
+ return agentkey_login
@@ -0,0 +1,58 @@
1
+ Metadata-Version: 2.5
2
+ Name: tryagentkey
3
+ Version: 0.5.0
4
+ Summary: 30-second auth & local secrets vault for AI agents. Zero config, local-first.
5
+ Project-URL: Homepage, https://github.com/edan-ais/agentkey
6
+ Project-URL: Repository, https://github.com/edan-ais/agentkey
7
+ Author: AgentKey, Inc.
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ License-File: NOTICE
11
+ Classifier: Operating System :: MacOS
12
+ Classifier: Operating System :: Microsoft :: Windows
13
+ Classifier: Operating System :: POSIX :: Linux
14
+ Classifier: Programming Language :: Python :: 3
15
+ Requires-Python: >=3.9
16
+ Requires-Dist: cryptography>=41
17
+ Provides-Extra: playwright
18
+ Requires-Dist: playwright>=1.40; extra == 'playwright'
19
+ Description-Content-Type: text/markdown
20
+
21
+ # AgentKey for Python
22
+
23
+ 30-second auth for AI agents. Works on Windows, macOS and Linux (Python 3.9+).
24
+
25
+ ```
26
+ pip install "tryagentkey[playwright]"
27
+ ```
28
+ ```python
29
+ from tryagentkey import agentkey
30
+ ak = agentkey()
31
+ ak.login("https://github.com/login", page=page) # sync or async Playwright
32
+ ```
33
+
34
+ - **Free Local Mode** (default): a local Approve page opens the first time; the login is locked on this computer in `~/.agentkey/vault.enc` (shared with the JS SDK). No website cookies are saved.
35
+ - **Permissions**: each approval covers one site, one saved login, this project folder and this agent name ("until revoked" or "only this time"). Valid permissions are reused without asking; `tryagentkey permissions` / `tryagentkey revoke <id|site|--all>` manage them.
36
+ - **Positive confirmation**: `signed_in` is only true with evidence (your `verify`, `success_selector`, or a visible sign-out control on a nonblank page without a login form or challenge). Blank or unsupported pages return `failed`; an unconfirmed submit returns `unverified` and is never retried.
37
+ - **Cloud mode**: set `AGENTKEY_API_KEY` (from `npx tryagentkey link`). The same one call does it all: trust this browser once, owner approval link, fill in your page, confirm. Paid plans sync across iPhone, web and Chrome.
38
+ - **MCP**: `uvx --from tryagentkey tryagentkey-mcp` (or `npx -y @tryagentkey/mcp`).
39
+ - **CLI**: `tryagentkey status`, `tryagentkey doctor`, `tryagentkey permissions`, `tryagentkey revoke`, `tryagentkey secret set NAME VALUE`.
40
+ - Starters in `examples/`: Playwright, LangChain, CrewAI, OpenAI Agents, browser-use.
41
+
42
+ Your agent and model never receive the password.
43
+
44
+ ## Local host trust and login evidence
45
+
46
+ Free Local Mode trusts the code and OS account that run the SDK. It keeps saved
47
+ website passwords out of public login results and the normal vault facade, but
48
+ is not a sandbox against arbitrary code in that process or OS account. Its local
49
+ key is stored beside encrypted vault data; hostname binding is not a secret.
50
+ Use a separately trusted runtime/OS principal when the calling program itself
51
+ must not be able to read credentials. Do not give untrusted model-generated code
52
+ access to the SDK process, its files, browser connection, or execution account.
53
+
54
+ A navigation away from a login page never proves sign-in. Supply a site-specific
55
+ account verifier or authenticated success selector when possible. Without one,
56
+ the generic fallback requires a visible sign-out control on a nonblank page
57
+ without a login form or challenge. This generic signal does not identify which
58
+ account signed in; verify the account identity before account-sensitive work.
@@ -0,0 +1,20 @@
1
+ tryagentkey/__init__.py,sha256=L41l9Qzri-kVmGU1tM664QxtP9BobjORlwzQzh9y4X0,375
2
+ tryagentkey/approve.py,sha256=0uqfFZz3J5Tmw9Li_Y8uOHt1n3pXQ4jtMcvdWe77W3A,5940
3
+ tryagentkey/cli.py,sha256=Fz1grqcnEfxVJ0ppsCSQ3L7KCXdkCouCdA9S-30lMpE,2496
4
+ tryagentkey/client.py,sha256=zdi8VWjKDo9cLmLBLu-MBiA4nukzJX1GocBvKKBTGwk,4809
5
+ tryagentkey/confirm.py,sha256=bAMGtlX2ciUBMoXxH13A12CrpHr35opzNLuJdgZVKrg,3844
6
+ tryagentkey/core.py,sha256=GVyVOXlBfWV5-kWl_aczVMFk_jQ3urhkq4Tl1i0nTPE,11531
7
+ tryagentkey/env.py,sha256=uBJoXKp88etgIK2gpIhvI4GGC--6kN0cGNHT6JU2eIo,1260
8
+ tryagentkey/errors.py,sha256=8rDiX_RblroXb8uU75oKPy2zsXNOWQLgy1QJT7AAhOQ,177
9
+ tryagentkey/fill.py,sha256=3wjHuZE-f0AQNjJTxIW5sUFpPiYsga2QKgt6gU4jbBE,3369
10
+ tryagentkey/keys.py,sha256=eDpFJfOu45jXMbDFr-p5cXMwLDFrxnV6Z5yqSUTVvEY,1272
11
+ tryagentkey/local_vault.py,sha256=n21I5uVK8y1rAAi4dGcMrEKhZ7Qoq6DC7HmJMK-UimE,8554
12
+ tryagentkey/mcp_server.py,sha256=0W_UU9XCQzupwdlLvTrgjxINozgEMc1ZdeVTuf_JVkk,4968
13
+ tryagentkey/runtime.py,sha256=11MSIOdRTovq3TwOLmqEGmYaTeNn4iCaxq2Ny7PhNHY,14663
14
+ tryagentkey/tools.py,sha256=IdxZNijkdNLCO0JW6gvyW5Qqnbx90XSsobQlveQ1nzs,1100
15
+ tryagentkey-0.5.0.dist-info/METADATA,sha256=1y4d2ir8tfYXLIfLFXkr1wF26St7U8do_O8yOTC5TKE,3354
16
+ tryagentkey-0.5.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
17
+ tryagentkey-0.5.0.dist-info/entry_points.txt,sha256=NE2lAhCHDoDTt-0DB66QC8JMKpBExQkcRmGxNlAoRPk,174
18
+ tryagentkey-0.5.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
19
+ tryagentkey-0.5.0.dist-info/licenses/NOTICE,sha256=nknBPLb8cobvR-0PM0ARexN9VNZBT_3b88HX3AUXlGA,58
20
+ tryagentkey-0.5.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any