havenai-connect 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,35 @@
1
+ Metadata-Version: 2.5
2
+ Name: havenai-connect
3
+ Version: 0.1.0
4
+ Summary: Lightweight Haven GPU connector CLI (havenai.ru) — expose local vLLM with auto-discovery, E2EE blind relay, and PoME verification
5
+ License: Apache-2.0
6
+ Keywords: gpu,haven,inference,llm,pome,vllm
7
+ Classifier: Development Status :: 4 - Beta
8
+ Classifier: Intended Audience :: Developers
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Requires-Python: >=3.11
14
+ Requires-Dist: cryptography>=42.0
15
+ Requires-Dist: httpx>=0.27
16
+ Requires-Dist: pome-verify>=0.2.0
17
+ Requires-Dist: ridgepoint>=0.1.2
18
+ Requires-Dist: websockets>=12.0
19
+ Description-Content-Type: text/markdown
20
+
21
+ # havenai-connect
22
+
23
+ Lightweight connector CLI for **Haven** ([havenai.ru](https://havenai.ru)) — attested LLM inference network.
24
+
25
+ Install next to any running `vLLM` server — no open firewall ports, no static IP, no manual GPU/model configuration:
26
+
27
+ ```bash
28
+ pip install havenai-connect
29
+ haven connect --key hvn_sk_... --hub wss://havenai.ru/ws/provider
30
+ ```
31
+
32
+ What it does:
33
+ - Auto-discovers your GPU SKU, VRAM, loaded model, quantization, KV cache, prefix caching, and safe session-slot capacity.
34
+ - Opens an outbound encrypted WebSocket tunnel (`wss://`) to the Haven hub.
35
+ - Signs every response with a cryptographic `pome-verify` (`ResponseEnvelope` + Ed25519) proof and supports E2EE Blind Relay.
@@ -0,0 +1,15 @@
1
+ # havenai-connect
2
+
3
+ Lightweight connector CLI for **Haven** ([havenai.ru](https://havenai.ru)) — attested LLM inference network.
4
+
5
+ Install next to any running `vLLM` server — no open firewall ports, no static IP, no manual GPU/model configuration:
6
+
7
+ ```bash
8
+ pip install havenai-connect
9
+ haven connect --key hvn_sk_... --hub wss://havenai.ru/ws/provider
10
+ ```
11
+
12
+ What it does:
13
+ - Auto-discovers your GPU SKU, VRAM, loaded model, quantization, KV cache, prefix caching, and safe session-slot capacity.
14
+ - Opens an outbound encrypted WebSocket tunnel (`wss://`) to the Haven hub.
15
+ - Signs every response with a cryptographic `pome-verify` (`ResponseEnvelope` + Ed25519) proof and supports E2EE Blind Relay.
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "havenai-connect"
7
+ version = "0.1.0"
8
+ description = "Lightweight Haven GPU connector CLI (havenai.ru) — expose local vLLM with auto-discovery, E2EE blind relay, and PoME verification"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = { text = "Apache-2.0" }
12
+ keywords = ["llm", "vllm", "gpu", "inference", "pome", "haven"]
13
+ classifiers = [
14
+ "Development Status :: 4 - Beta",
15
+ "Intended Audience :: Developers",
16
+ "License :: OSI Approved :: Apache Software License",
17
+ "Programming Language :: Python :: 3.11",
18
+ "Programming Language :: Python :: 3.12",
19
+ "Programming Language :: Python :: 3.13",
20
+ ]
21
+ dependencies = [
22
+ "websockets>=12.0",
23
+ "httpx>=0.27",
24
+ "cryptography>=42.0",
25
+ "pome-verify>=0.2.0",
26
+ "ridgepoint>=0.1.2",
27
+ ]
28
+
29
+ [project.scripts]
30
+ haven = "haven.connector.cli:main"
31
+ haven-connect = "haven.connector.cli:connect_main"
32
+ havenai-connect = "haven.connector.cli:connect_main"
33
+
34
+ [tool.hatch.build.targets.wheel]
35
+ packages = ["src/haven"]
@@ -0,0 +1,3 @@
1
+ """Haven — attested, session-slot-aware LLM inference routing & connector."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1 @@
1
+ """External library boundaries (`ridgepoint` sizing & `pome` verification)."""
@@ -0,0 +1,408 @@
1
+ """Pure library adapter delegating cryptographic verification to `pome` & `pome.blind`.
2
+
3
+ Delegates directly to `pome` / `pome.blind` (`SPEC-01`) when installed, with a
4
+ wire-compatible SPEC-01 fallback so Haven works seamlessly while `pome.blind` lands
5
+ in parallel.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import datetime
11
+ import hashlib
12
+ import json
13
+ import secrets
14
+ from typing import Any
15
+
16
+ from cryptography.exceptions import InvalidSignature
17
+ from cryptography.hazmat.primitives import serialization
18
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
19
+
20
+ from haven.connector.crypto import b64url_decode, b64url_encode
21
+
22
+ _BLIND_REQ_DOMAIN = b"pome-blind-req-v0.1:"
23
+ _BLIND_SIG_DOMAIN = b"pome-blind-settlement-v0.1:"
24
+
25
+
26
+ def _canonical_bytes(obj: dict[str, Any]) -> bytes:
27
+ return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode(
28
+ "utf-8"
29
+ )
30
+
31
+
32
+ def _sha256_hex(raw: bytes) -> str:
33
+ return hashlib.sha256(raw).hexdigest()
34
+
35
+
36
+ class PomeVerifierAdapter:
37
+ """Thin boundary around the external `pome` and `pome.blind` Python packages."""
38
+
39
+ def __init__(self) -> None:
40
+ self._pome: Any = None
41
+ self._pome_blind: Any = None
42
+ try:
43
+ import pome
44
+
45
+ self._pome = pome
46
+ except ImportError:
47
+ self._pome = None
48
+ try:
49
+ import pome.blind as pome_blind
50
+
51
+ self._pome_blind = pome_blind
52
+ except ImportError:
53
+ self._pome_blind = None
54
+
55
+ @property
56
+ def pome_installed(self) -> bool:
57
+ return self._pome is not None
58
+
59
+ def compute_request_digest(self, payload: dict[str, Any]) -> str:
60
+ """Delegate canonical request hashing to `pome.canonical` when available."""
61
+ if self._pome is not None:
62
+ try:
63
+ from pome.canonical import request_digest
64
+
65
+ return str(request_digest(payload))
66
+ except Exception:
67
+ pass
68
+ return "sha256:" + _sha256_hex(_canonical_bytes(payload))
69
+
70
+ def resolve_manifest_id(
71
+ self,
72
+ model_id: str,
73
+ model_source_url: str,
74
+ weight_dtype: str,
75
+ reported_manifest_id: str | None = None,
76
+ ) -> str:
77
+ """Use `pome`-reported manifest digest if supplied by engine/plugin; else canonical ref."""
78
+ if reported_manifest_id and reported_manifest_id.strip():
79
+ return reported_manifest_id.strip()
80
+ canonical_key = f"{model_source_url or model_id}|{weight_dtype.lower()}"
81
+ return "manifest:" + _sha256_hex(canonical_key.encode("utf-8"))[:24]
82
+
83
+ def verify_envelope(
84
+ self,
85
+ envelope_payload: dict[str, Any] | str | None,
86
+ expected_request_digest: str,
87
+ provider_signing_pubkey_b64: str | None = None,
88
+ ) -> str:
89
+ """Delegate response-envelope chain + Ed25519 signature verification to `pome==0.2.0`."""
90
+ if envelope_payload is None:
91
+ return "UNVERIFIED"
92
+ if self._pome is None:
93
+ return "DEGRADED"
94
+ try:
95
+ from pome.envelope import ResponseEnvelope
96
+
97
+ raw = (
98
+ envelope_payload
99
+ if isinstance(envelope_payload, str)
100
+ else json.dumps(envelope_payload, separators=(",", ":"), ensure_ascii=False)
101
+ )
102
+ env = ResponseEnvelope.from_json(raw)
103
+ if env.request_digest != expected_request_digest:
104
+ return "REJECTED"
105
+ if not env.verify_chain():
106
+ return "REJECTED"
107
+ has_proofs = len(env.chunks) > 0 and all(bool(c.proof) for c in env.chunks)
108
+ if provider_signing_pubkey_b64:
109
+ if not env.signature:
110
+ return "REJECTED"
111
+ pub = Ed25519PublicKey.from_public_bytes(b64url_decode(provider_signing_pubkey_b64))
112
+ if not env.verify_signature(pub):
113
+ return "REJECTED"
114
+ return "L3-VERIFIED" if has_proofs else "DEGRADED"
115
+ return "VERIFIED-SOFT" if has_proofs else "DEGRADED"
116
+ except Exception:
117
+ return "REJECTED"
118
+
119
+ def build_signed_envelope(
120
+ self,
121
+ *,
122
+ private_key: Ed25519PrivateKey,
123
+ manifest_ref: str,
124
+ request_digest: str,
125
+ output_text: str,
126
+ engine_name: str,
127
+ engine_version: str,
128
+ engine_gpu: str,
129
+ ) -> dict[str, Any] | None:
130
+ """Build & Ed25519-sign a real `pome==0.2.0` hash-chained ResponseEnvelope."""
131
+ if self._pome is None:
132
+ return None
133
+ from pome import ResponseEnvelope
134
+
135
+ raw_bytes = output_text.encode("utf-8")
136
+ out_sha = _sha256_hex(raw_bytes)
137
+ # Split output bytes into deterministic chunks committed via SHA-256 proofs
138
+ step = max(32, len(raw_bytes) // 4) if raw_bytes else 32
139
+ chunks: list[tuple[tuple[int, ...], bytes]] = []
140
+ if not raw_bytes:
141
+ chunks.append(((0,), hashlib.sha256(b"").digest()))
142
+ else:
143
+ for offset in range(0, len(raw_bytes), step):
144
+ part = raw_bytes[offset : offset + step]
145
+ tok_ids = tuple(part[:32])
146
+ proof = hashlib.sha256(part).digest()
147
+ chunks.append((tok_ids, proof))
148
+
149
+ issued_at = datetime.datetime.now(datetime.UTC).isoformat().replace("+00:00", "Z")
150
+ env = ResponseEnvelope.assemble(
151
+ manifest_ref=manifest_ref,
152
+ request_digest=request_digest,
153
+ chunks=chunks,
154
+ nonce=secrets.token_hex(12),
155
+ engine_name=engine_name,
156
+ engine_version=engine_version,
157
+ engine_gpu=engine_gpu,
158
+ issued_at=issued_at,
159
+ tier_hint="L3",
160
+ attestation={
161
+ "pome_version": str(getattr(self._pome, "__version__", "0.2.0")),
162
+ "output_sha256": out_sha,
163
+ "output_bytes": len(raw_bytes),
164
+ },
165
+ )
166
+ env.sign(private_key)
167
+ return dict(env.to_dict())
168
+
169
+ def verify_output_against_envelope(
170
+ self,
171
+ *,
172
+ envelope_payload: dict[str, Any],
173
+ output_text: str,
174
+ provider_signing_pubkey_b64: str,
175
+ ) -> dict[str, Any]:
176
+ """Cryptographically verify an output string against a signed `pome` ResponseEnvelope."""
177
+ pome_ver = str(getattr(self._pome, "__version__", "0.2.0")) if self._pome else "unavailable"
178
+ if self._pome is None:
179
+ return {
180
+ "verified": False,
181
+ "pome_version": pome_ver,
182
+ "tier": "UNVERIFIED",
183
+ "chain_valid": False,
184
+ "signature_valid": False,
185
+ "output_match": False,
186
+ "chunks_checked": 0,
187
+ "reason": "pome-verify package is not installed on verifier",
188
+ }
189
+ from pome.envelope import ResponseEnvelope
190
+
191
+ try:
192
+ raw = json.dumps(envelope_payload, separators=(",", ":"), ensure_ascii=False)
193
+ env = ResponseEnvelope.from_json(raw)
194
+ except Exception as exc:
195
+ return {
196
+ "verified": False,
197
+ "pome_version": pome_ver,
198
+ "tier": "REJECTED",
199
+ "chain_valid": False,
200
+ "signature_valid": False,
201
+ "output_match": False,
202
+ "chunks_checked": 0,
203
+ "reason": f"Malformed POME ResponseEnvelope: {exc}",
204
+ }
205
+ chain_valid = bool(env.verify_chain())
206
+ sig_valid = False
207
+ if provider_signing_pubkey_b64 and env.signature:
208
+ try:
209
+ pub = Ed25519PublicKey.from_public_bytes(b64url_decode(provider_signing_pubkey_b64))
210
+ sig_valid = bool(env.verify_signature(pub))
211
+ except Exception:
212
+ sig_valid = False
213
+
214
+ att = env.attestation or {}
215
+ expected_sha = str(att.get("output_sha256", ""))
216
+ actual_sha = _sha256_hex(output_text.encode("utf-8"))
217
+ output_match = bool(expected_sha) and expected_sha == actual_sha
218
+
219
+ ok = chain_valid and sig_valid and output_match
220
+ if ok:
221
+ reason = (
222
+ f"pome-verify {pome_ver}: Ed25519 host signature, {len(env.chunks)}-chunk "
223
+ "hash chain, and SHA-256 output commitment all passed."
224
+ )
225
+ elif not output_match:
226
+ reason = (
227
+ "Output digest mismatch — text was altered or generated by a different model/host."
228
+ )
229
+ elif not sig_valid:
230
+ reason = "Ed25519 host signature verification failed."
231
+ else:
232
+ reason = "ResponseEnvelope chunk hash chain verification failed."
233
+
234
+ return {
235
+ "verified": ok,
236
+ "pome_version": pome_ver,
237
+ "tier": "L3-VERIFIED" if ok else "REJECTED",
238
+ "chain_valid": chain_valid,
239
+ "signature_valid": sig_valid,
240
+ "output_match": output_match,
241
+ "chunks_checked": len(env.chunks),
242
+ "reason": reason,
243
+ "envelope": env.to_dict(),
244
+ }
245
+
246
+ # ── SPEC-01: pome.blind Zero-Content Settlement & Commitment ────────────
247
+
248
+ def compute_blind_commitment(
249
+ self,
250
+ *,
251
+ manifest_ref: str,
252
+ client_nonce: str,
253
+ ephemeral_pubkey_b64: str,
254
+ req_ciphertext_b64: str,
255
+ ) -> str:
256
+ """Compute `brc:<sha256>` commitment without decrypting ciphertext (SPEC-01 §2.1)."""
257
+ if self._pome_blind is not None:
258
+ try:
259
+ return str(
260
+ self._pome_blind.compute_blind_request_commitment(
261
+ manifest_ref=manifest_ref,
262
+ client_nonce=client_nonce,
263
+ ephemeral_pubkey_b64=ephemeral_pubkey_b64,
264
+ req_ciphertext_b64=req_ciphertext_b64,
265
+ )
266
+ )
267
+ except Exception:
268
+ pass
269
+ payload = _canonical_bytes(
270
+ {
271
+ "manifest_ref": manifest_ref,
272
+ "client_nonce": client_nonce,
273
+ "ephemeral_pubkey": ephemeral_pubkey_b64,
274
+ "req_ciphertext_sha256": _sha256_hex(req_ciphertext_b64.encode("ascii")),
275
+ }
276
+ )
277
+ return "brc:" + _sha256_hex(_BLIND_REQ_DOMAIN + payload)
278
+
279
+ def sign_blind_settlement(
280
+ self,
281
+ *,
282
+ private_key: Ed25519PrivateKey,
283
+ manifest_ref: str,
284
+ blind_request_commitment: str,
285
+ chain_head: str,
286
+ prompt_tokens: int,
287
+ cached_prompt_tokens: int,
288
+ completion_tokens: int,
289
+ chunk_count: int,
290
+ stream_ciphertext_bytes: int,
291
+ tier_hint: str = "BLIND-SIGNED",
292
+ ) -> dict[str, Any]:
293
+ """Build & Ed25519-sign a `BlindSettlementProof` dict (SPEC-01 §3.1)."""
294
+ issued_at = datetime.datetime.now(datetime.UTC).isoformat()
295
+ nonce = secrets.token_hex(12)
296
+ if self._pome_blind is not None:
297
+ try:
298
+ proof = self._pome_blind.BlindSettlementProof(
299
+ manifest_ref=manifest_ref,
300
+ blind_request_commitment=blind_request_commitment,
301
+ chain_head=chain_head,
302
+ prompt_tokens=prompt_tokens,
303
+ cached_prompt_tokens=cached_prompt_tokens,
304
+ completion_tokens=completion_tokens,
305
+ chunk_count=chunk_count,
306
+ stream_ciphertext_bytes=stream_ciphertext_bytes,
307
+ tier_hint=tier_hint,
308
+ issued_at=issued_at,
309
+ nonce=nonce,
310
+ ).sign(private_key)
311
+ return dict(proof.to_dict())
312
+ except Exception:
313
+ pass
314
+
315
+ pub_raw = private_key.public_key().public_bytes(
316
+ serialization.Encoding.Raw, serialization.PublicFormat.Raw
317
+ )
318
+ signer_key_id = _sha256_hex(pub_raw)[:16]
319
+ unsigned = {
320
+ "pome_blind_version": "0.1",
321
+ "manifest_ref": manifest_ref,
322
+ "blind_request_commitment": blind_request_commitment,
323
+ "chain_head": chain_head,
324
+ "prompt_tokens": int(prompt_tokens),
325
+ "cached_prompt_tokens": int(cached_prompt_tokens),
326
+ "completion_tokens": int(completion_tokens),
327
+ "chunk_count": int(chunk_count),
328
+ "stream_ciphertext_bytes": int(stream_ciphertext_bytes),
329
+ "tier_hint": tier_hint,
330
+ "issued_at": issued_at,
331
+ "nonce": nonce,
332
+ "signer_key_id": signer_key_id,
333
+ }
334
+ sig_raw = private_key.sign(_BLIND_SIG_DOMAIN + _canonical_bytes(unsigned))
335
+ signed = dict(unsigned)
336
+ signed["signature"] = b64url_encode(sig_raw)
337
+ return signed
338
+
339
+ def verify_blind_settlement(
340
+ self,
341
+ *,
342
+ proof_dict: dict[str, Any] | None,
343
+ expected_blind_commitment: str,
344
+ expected_manifest_ref: str,
345
+ signing_pubkey_b64: str,
346
+ observed_stream_bytes: int,
347
+ ) -> tuple[bool, str, str]:
348
+ """Verify zero-content `BlindSettlementProof` on Control Plane (SPEC-01 §3.2).
349
+
350
+ Returns `(valid, reason, effective_tier)`.
351
+ """
352
+ if not isinstance(proof_dict, dict) or not signing_pubkey_b64:
353
+ return False, "missing_proof_or_key", "REJECTED"
354
+
355
+ try:
356
+ pub_raw = b64url_decode(signing_pubkey_b64)
357
+ if len(pub_raw) != 32:
358
+ return False, "invalid_signing_pubkey", "REJECTED"
359
+ pub_key = Ed25519PublicKey.from_public_bytes(pub_raw)
360
+ except ValueError:
361
+ return False, "malformed_signing_pubkey", "REJECTED"
362
+
363
+ if self._pome_blind is not None:
364
+ try:
365
+ proof_obj = self._pome_blind.BlindSettlementProof.from_dict(proof_dict)
366
+ res = self._pome_blind.verify_blind_settlement(
367
+ proof_obj,
368
+ expected_blind_commitment=expected_blind_commitment,
369
+ expected_manifest_ref=expected_manifest_ref,
370
+ provider_public_key=pub_key,
371
+ observed_stream_bytes=observed_stream_bytes,
372
+ )
373
+ return bool(res.valid), str(res.reason), str(res.effective_tier)
374
+ except Exception:
375
+ pass
376
+
377
+ # SPEC-01 wire-compatible verification fallback
378
+ if proof_dict.get("blind_request_commitment") != expected_blind_commitment:
379
+ return False, "blind_request_commitment_mismatch", "REJECTED"
380
+ if proof_dict.get("manifest_ref") != expected_manifest_ref:
381
+ return False, "manifest_ref_mismatch", "REJECTED"
382
+
383
+ try:
384
+ prompt_tok = int(proof_dict["prompt_tokens"])
385
+ cached_tok = int(proof_dict["cached_prompt_tokens"])
386
+ comp_tok = int(proof_dict["completion_tokens"])
387
+ chunk_cnt = int(proof_dict["chunk_count"])
388
+ stream_bytes = int(proof_dict["stream_ciphertext_bytes"])
389
+ sig_b64 = str(proof_dict["signature"])
390
+ except (KeyError, TypeError, ValueError):
391
+ return False, "malformed_proof_fields", "REJECTED"
392
+
393
+ if not (0 <= cached_tok <= prompt_tok <= 2_000_000):
394
+ return False, "invalid_prompt_token_bounds", "REJECTED"
395
+ if not (1 <= chunk_cnt <= max(1, comp_tok) and comp_tok <= 2_000_000):
396
+ return False, "invalid_completion_token_bounds", "REJECTED"
397
+ if stream_bytes != observed_stream_bytes or stream_bytes < chunk_cnt * 16:
398
+ return False, "stream_ciphertext_bytes_mismatch", "REJECTED"
399
+ if comp_tok > max(32, observed_stream_bytes * 4):
400
+ return False, "completion_tokens_exceed_byte_ceiling", "REJECTED"
401
+
402
+ unsigned = {k: v for k, v in proof_dict.items() if k != "signature"}
403
+ try:
404
+ pub_key.verify(b64url_decode(sig_b64), _BLIND_SIG_DOMAIN + _canonical_bytes(unsigned))
405
+ except (InvalidSignature, ValueError):
406
+ return False, "invalid_ed25519_signature", "REJECTED"
407
+
408
+ return True, "ok", "BLIND-SIGNED"