jelly-sdk 1.0.8__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.
- jelly_sdk/__init__.py +55 -0
- jelly_sdk/core/__init__.py +23 -0
- jelly_sdk/core/auth.py +298 -0
- jelly_sdk/core/config.py +118 -0
- jelly_sdk/core/device.py +151 -0
- jelly_sdk/core/exceptions.py +52 -0
- jelly_sdk/core/http_client.py +287 -0
- jelly_sdk/knowledge_base/__init__.py +15 -0
- jelly_sdk/knowledge_base/client.py +301 -0
- jelly_sdk/knowledge_base/models.py +83 -0
- jelly_sdk/memory/__init__.py +17 -0
- jelly_sdk/memory/_gateway.py +148 -0
- jelly_sdk/memory/client.py +328 -0
- jelly_sdk/memory/intelligence.py +138 -0
- jelly_sdk/memory/local_store.py +160 -0
- jelly_sdk/memory/models.py +153 -0
- jelly_sdk/memory/sync_client.py +82 -0
- jelly_sdk/py.typed +0 -0
- jelly_sdk/search/__init__.py +14 -0
- jelly_sdk/search/client.py +284 -0
- jelly_sdk/search/models.py +79 -0
- jelly_sdk/search/sync_client.py +90 -0
- jelly_sdk-1.0.8.dist-info/METADATA +288 -0
- jelly_sdk-1.0.8.dist-info/RECORD +27 -0
- jelly_sdk-1.0.8.dist-info/WHEEL +5 -0
- jelly_sdk-1.0.8.dist-info/licenses/LICENSE +21 -0
- jelly_sdk-1.0.8.dist-info/top_level.txt +1 -0
jelly_sdk/__init__.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Jelly SDK — Unified Search and Memory for AI Agents."""
|
|
2
|
+
|
|
3
|
+
# Single source of truth is pyproject.toml; read the installed dist version so
|
|
4
|
+
# the importable version can never drift from the published package again
|
|
5
|
+
# (plan-11: the 0.6.0 hardcode vs 1.0.0 pyproject mismatch is what made the
|
|
6
|
+
# 199 shadow install confusing to diagnose).
|
|
7
|
+
try:
|
|
8
|
+
from importlib.metadata import PackageNotFoundError, version as _dist_version
|
|
9
|
+
|
|
10
|
+
__version__ = _dist_version("jelly-sdk")
|
|
11
|
+
except PackageNotFoundError: # not installed (e.g. raw sys.path import from a checkout)
|
|
12
|
+
# I-603 纪律:此处 fallback 必须随 pyproject 升版同步改——publish.sh [2b]
|
|
13
|
+
# 步骤机械断言三处一致,漏改会在发布门被拦下。
|
|
14
|
+
__version__ = "1.0.8"
|
|
15
|
+
|
|
16
|
+
from .search import JellySearch, SearchResponse, SearchResult, AskResponse, Citation
|
|
17
|
+
from .core.config import JellyConfig
|
|
18
|
+
from .core.exceptions import (
|
|
19
|
+
JellyHttpError,
|
|
20
|
+
JellyAuthError,
|
|
21
|
+
JellyQuotaExhaustedError,
|
|
22
|
+
JellyRateLimitError,
|
|
23
|
+
JellyConnectionError,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"JellySearch",
|
|
28
|
+
"SearchResponse",
|
|
29
|
+
"SearchResult",
|
|
30
|
+
"AskResponse",
|
|
31
|
+
"Citation",
|
|
32
|
+
"JellyConfig",
|
|
33
|
+
"JellyHttpError",
|
|
34
|
+
"JellyAuthError",
|
|
35
|
+
"JellyQuotaExhaustedError",
|
|
36
|
+
"JellyRateLimitError",
|
|
37
|
+
"JellyConnectionError",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def __getattr__(name):
|
|
42
|
+
"""Lazy import for optional modules (memory, knowledge_base, sync wrappers)."""
|
|
43
|
+
if name in ("JellyMemory", "MemoryEntry", "MemoryType", "MemoryLayer", "MemoryMode"):
|
|
44
|
+
from . import memory
|
|
45
|
+
return getattr(memory, name)
|
|
46
|
+
if name == "JellyMemorySync":
|
|
47
|
+
from .memory.sync_client import JellyMemorySync
|
|
48
|
+
return JellyMemorySync
|
|
49
|
+
if name == "JellySearchSync":
|
|
50
|
+
from .search.sync_client import JellySearchSync
|
|
51
|
+
return JellySearchSync
|
|
52
|
+
if name in ("JellyKnowledgeBase", "KBInfo", "CrossSearchResponse"):
|
|
53
|
+
from . import knowledge_base
|
|
54
|
+
return getattr(knowledge_base, name)
|
|
55
|
+
raise AttributeError(f"module 'jelly_sdk' has no attribute {name!r}")
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from .config import JellyConfig
|
|
2
|
+
from .auth import AuthManager
|
|
3
|
+
from .device import DeviceManager
|
|
4
|
+
from .http_client import JellyHttpClient
|
|
5
|
+
from .exceptions import (
|
|
6
|
+
JellyHttpError,
|
|
7
|
+
JellyAuthError,
|
|
8
|
+
JellyQuotaExhaustedError,
|
|
9
|
+
JellyRateLimitError,
|
|
10
|
+
JellyConnectionError,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"JellyConfig",
|
|
15
|
+
"AuthManager",
|
|
16
|
+
"DeviceManager",
|
|
17
|
+
"JellyHttpClient",
|
|
18
|
+
"JellyHttpError",
|
|
19
|
+
"JellyAuthError",
|
|
20
|
+
"JellyQuotaExhaustedError",
|
|
21
|
+
"JellyRateLimitError",
|
|
22
|
+
"JellyConnectionError",
|
|
23
|
+
]
|
jelly_sdk/core/auth.py
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Authentication — JWT Bearer + API Key dual-channel.
|
|
3
|
+
|
|
4
|
+
Priority: constructor param → cache file → auto-register via device registration.
|
|
5
|
+
"""
|
|
6
|
+
import asyncio
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import platform as _platform
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Optional
|
|
12
|
+
|
|
13
|
+
import aiohttp
|
|
14
|
+
|
|
15
|
+
from .config import JellyConfig, JELLY_DIR, LEGACY_DIR, _ensure_jelly_dir
|
|
16
|
+
from .device import DeviceManager
|
|
17
|
+
from .exceptions import JellyConnectionError
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
API_KEY_FILE = JELLY_DIR / "api_key"
|
|
22
|
+
LEGACY_API_KEY_FILE = LEGACY_DIR / ".api_key"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class AuthManager:
|
|
26
|
+
"""Manages authentication: JWT Bearer + API Key dual-channel."""
|
|
27
|
+
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
config: Optional[JellyConfig] = None,
|
|
31
|
+
device_manager: Optional[DeviceManager] = None,
|
|
32
|
+
):
|
|
33
|
+
self._config = config or JellyConfig()
|
|
34
|
+
self._device = device_manager or DeviceManager()
|
|
35
|
+
self.api_key: Optional[str] = self._config.api_key
|
|
36
|
+
self.jwt_token: Optional[str] = self._config.jwt_token
|
|
37
|
+
self.admin_key: Optional[str] = self._config.admin_key
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def base_url(self) -> str:
|
|
41
|
+
return self._config.api_base
|
|
42
|
+
|
|
43
|
+
def get_headers(self) -> dict:
|
|
44
|
+
"""Return HTTP headers with auth credentials.
|
|
45
|
+
|
|
46
|
+
If both JWT and API Key are present, both headers are sent.
|
|
47
|
+
The backend accepts either: Authorization: Bearer <jwt> or X-API-Key: <key>.
|
|
48
|
+
"""
|
|
49
|
+
headers = {"Content-Type": "application/json"}
|
|
50
|
+
if self.jwt_token:
|
|
51
|
+
headers["Authorization"] = f"Bearer {self.jwt_token}"
|
|
52
|
+
if self.api_key:
|
|
53
|
+
headers["X-API-Key"] = self.api_key
|
|
54
|
+
return headers
|
|
55
|
+
|
|
56
|
+
def _load_cached_key(self) -> Optional[str]:
|
|
57
|
+
"""Try loading API Key from cache files (new path first, then legacy).
|
|
58
|
+
|
|
59
|
+
I-614 域名切换:缓存记录签发时的 base_url——切换 JELLY_BASE_URL(如
|
|
60
|
+
jelly.datanaan.cn → .com)后旧 key 对新部署无效,此处校验不匹配即视为
|
|
61
|
+
过期(返回 None → 走自动重注册),不再把旧域名 key 发给新域名拿 401。
|
|
62
|
+
旧格式缓存(无 base_url 字段)按原样接受,向后兼容。
|
|
63
|
+
"""
|
|
64
|
+
current_base = self._config.api_base
|
|
65
|
+
# 1. Try new cache
|
|
66
|
+
if API_KEY_FILE.exists():
|
|
67
|
+
try:
|
|
68
|
+
data = json.loads(API_KEY_FILE.read_text())
|
|
69
|
+
api_key = data.get("api_key")
|
|
70
|
+
if api_key:
|
|
71
|
+
cached_base = data.get("base_url")
|
|
72
|
+
if cached_base and cached_base != current_base:
|
|
73
|
+
logger.warning(
|
|
74
|
+
"Cached API key was issued for %s but JELLY_BASE_URL is %s "
|
|
75
|
+
"— ignoring cache, re-registering against the new endpoint",
|
|
76
|
+
cached_base, current_base,
|
|
77
|
+
)
|
|
78
|
+
return None
|
|
79
|
+
logger.info("Loaded API Key from cache")
|
|
80
|
+
return api_key
|
|
81
|
+
except Exception as e:
|
|
82
|
+
logger.warning(f"Failed to load API Key from {API_KEY_FILE}: {e}")
|
|
83
|
+
|
|
84
|
+
# 2. Try legacy cache, migrate if found
|
|
85
|
+
if LEGACY_API_KEY_FILE.exists():
|
|
86
|
+
try:
|
|
87
|
+
data = json.loads(LEGACY_API_KEY_FILE.read_text())
|
|
88
|
+
api_key = data.get("api_key")
|
|
89
|
+
if api_key:
|
|
90
|
+
self._migrate_legacy_key()
|
|
91
|
+
return api_key
|
|
92
|
+
except Exception as e:
|
|
93
|
+
logger.warning(f"Failed to load API Key from {LEGACY_API_KEY_FILE}: {e}")
|
|
94
|
+
|
|
95
|
+
return None
|
|
96
|
+
|
|
97
|
+
def _save_key(self, api_key: str) -> None:
|
|
98
|
+
"""Save API Key to cache file(含签发域名,供跨域名切换校验)."""
|
|
99
|
+
_ensure_jelly_dir()
|
|
100
|
+
try:
|
|
101
|
+
API_KEY_FILE.write_text(json.dumps({
|
|
102
|
+
"api_key": api_key,
|
|
103
|
+
"base_url": self._config.api_base,
|
|
104
|
+
}))
|
|
105
|
+
API_KEY_FILE.chmod(0o600)
|
|
106
|
+
logger.info("API Key saved to cache")
|
|
107
|
+
except Exception as e:
|
|
108
|
+
logger.warning(f"Failed to save API Key: {e}")
|
|
109
|
+
|
|
110
|
+
def _migrate_legacy_key(self) -> None:
|
|
111
|
+
"""Migrate legacy API key file to new location."""
|
|
112
|
+
_ensure_jelly_dir()
|
|
113
|
+
if LEGACY_API_KEY_FILE.exists() and not API_KEY_FILE.exists():
|
|
114
|
+
try:
|
|
115
|
+
import shutil
|
|
116
|
+
shutil.copy2(LEGACY_API_KEY_FILE, API_KEY_FILE)
|
|
117
|
+
logger.info(f"Migrated API key: {LEGACY_API_KEY_FILE} → {API_KEY_FILE}")
|
|
118
|
+
except Exception as e:
|
|
119
|
+
logger.warning(f"Failed to migrate API key: {e}")
|
|
120
|
+
|
|
121
|
+
async def register_device(
|
|
122
|
+
self,
|
|
123
|
+
device_id: str,
|
|
124
|
+
*,
|
|
125
|
+
max_retries: int = 3,
|
|
126
|
+
total_timeout: float = 15.0,
|
|
127
|
+
request_timeout: float = 5.0,
|
|
128
|
+
) -> str:
|
|
129
|
+
"""Register device with backend and receive API Key.
|
|
130
|
+
|
|
131
|
+
Retries on 429 (respecting Retry-After, max 5s wait) and 5xx
|
|
132
|
+
(exponential back-off: 1s, 2s, 4s). Does **not** retry on 4xx.
|
|
133
|
+
|
|
134
|
+
Raises:
|
|
135
|
+
JellyConnectionError: When all retries are exhausted or a
|
|
136
|
+
non-retryable error occurs.
|
|
137
|
+
"""
|
|
138
|
+
body: dict = {"device_id": device_id}
|
|
139
|
+
|
|
140
|
+
# Platform / version / fingerprint enrichment
|
|
141
|
+
body["platform"] = self._detect_platform()
|
|
142
|
+
body["client_version"] = self._detect_version()
|
|
143
|
+
try:
|
|
144
|
+
fingerprint = self._device.get_device_fingerprint()
|
|
145
|
+
if fingerprint:
|
|
146
|
+
body["device_fingerprint"] = fingerprint
|
|
147
|
+
except Exception:
|
|
148
|
+
logger.debug("device_fingerprint collection failed, skipping")
|
|
149
|
+
|
|
150
|
+
# Invite token for pre-binding device to user
|
|
151
|
+
invite_token = self._config.invite_token
|
|
152
|
+
if invite_token:
|
|
153
|
+
body["invite_token"] = invite_token
|
|
154
|
+
|
|
155
|
+
last_error: Optional[Exception] = None
|
|
156
|
+
import time
|
|
157
|
+
deadline = time.monotonic() + total_timeout
|
|
158
|
+
|
|
159
|
+
async with aiohttp.ClientSession() as session:
|
|
160
|
+
for attempt in range(max_retries):
|
|
161
|
+
# Check total_timeout deadline
|
|
162
|
+
if time.monotonic() >= deadline:
|
|
163
|
+
break
|
|
164
|
+
|
|
165
|
+
try:
|
|
166
|
+
async with session.post(
|
|
167
|
+
f"{self.base_url}/v1/auth/device/register",
|
|
168
|
+
json=body,
|
|
169
|
+
timeout=aiohttp.ClientTimeout(total=request_timeout),
|
|
170
|
+
) as response:
|
|
171
|
+
if response.status == 201:
|
|
172
|
+
data = await response.json()
|
|
173
|
+
api_key = data.get("api_key")
|
|
174
|
+
if api_key:
|
|
175
|
+
logger.info("Device registered successfully")
|
|
176
|
+
return api_key
|
|
177
|
+
raise JellyConnectionError(
|
|
178
|
+
self.base_url,
|
|
179
|
+
"Registration succeeded but no api_key in response",
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
# --- 429: rate-limited ---
|
|
183
|
+
if response.status == 429:
|
|
184
|
+
retry_after = 5.0 # default cap
|
|
185
|
+
ra = response.headers.get("Retry-After")
|
|
186
|
+
if ra:
|
|
187
|
+
try:
|
|
188
|
+
retry_after = min(float(ra), 5.0)
|
|
189
|
+
except (ValueError, TypeError):
|
|
190
|
+
pass
|
|
191
|
+
last_error = JellyConnectionError(
|
|
192
|
+
self.base_url,
|
|
193
|
+
f"Rate limited (429), Retry-After={retry_after}s",
|
|
194
|
+
)
|
|
195
|
+
if attempt < max_retries - 1:
|
|
196
|
+
logger.warning(
|
|
197
|
+
f"Registration rate-limited, retrying in {retry_after}s "
|
|
198
|
+
f"(attempt {attempt + 1}/{max_retries})"
|
|
199
|
+
)
|
|
200
|
+
await asyncio.sleep(retry_after)
|
|
201
|
+
continue
|
|
202
|
+
|
|
203
|
+
# --- 5xx: server error, exponential back-off ---
|
|
204
|
+
if response.status >= 500:
|
|
205
|
+
backoff = 2 ** attempt # 1s, 2s, 4s
|
|
206
|
+
error_text = await response.text()
|
|
207
|
+
last_error = JellyConnectionError(
|
|
208
|
+
self.base_url,
|
|
209
|
+
f"Server error {response.status}",
|
|
210
|
+
)
|
|
211
|
+
if attempt < max_retries - 1:
|
|
212
|
+
logger.warning(
|
|
213
|
+
f"Registration server error {response.status}, "
|
|
214
|
+
f"retrying in {backoff}s "
|
|
215
|
+
f"(attempt {attempt + 1}/{max_retries})"
|
|
216
|
+
)
|
|
217
|
+
await asyncio.sleep(backoff)
|
|
218
|
+
continue
|
|
219
|
+
|
|
220
|
+
# --- 4xx: client error, do NOT retry ---
|
|
221
|
+
error_text = await response.text()
|
|
222
|
+
raise JellyConnectionError(
|
|
223
|
+
self.base_url,
|
|
224
|
+
f"Registration failed ({response.status})",
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
except JellyConnectionError:
|
|
228
|
+
raise
|
|
229
|
+
except (aiohttp.ClientError, OSError) as e:
|
|
230
|
+
last_error = JellyConnectionError(self.base_url, str(e))
|
|
231
|
+
backoff = 2 ** attempt
|
|
232
|
+
if attempt < max_retries - 1:
|
|
233
|
+
logger.warning(
|
|
234
|
+
f"Registration connection error: {e}, "
|
|
235
|
+
f"retrying in {backoff}s "
|
|
236
|
+
f"(attempt {attempt + 1}/{max_retries})"
|
|
237
|
+
)
|
|
238
|
+
await asyncio.sleep(backoff)
|
|
239
|
+
continue
|
|
240
|
+
|
|
241
|
+
# All retries exhausted
|
|
242
|
+
if last_error:
|
|
243
|
+
raise last_error
|
|
244
|
+
raise JellyConnectionError(self.base_url, "Registration failed after all retries")
|
|
245
|
+
|
|
246
|
+
@staticmethod
|
|
247
|
+
def _detect_platform() -> str:
|
|
248
|
+
"""Detect the current platform string."""
|
|
249
|
+
return _platform.system().lower()
|
|
250
|
+
|
|
251
|
+
@staticmethod
|
|
252
|
+
def _detect_version() -> str:
|
|
253
|
+
"""Detect SDK version."""
|
|
254
|
+
try:
|
|
255
|
+
from jelly_sdk import __version__
|
|
256
|
+
return __version__
|
|
257
|
+
except Exception:
|
|
258
|
+
return "unknown"
|
|
259
|
+
|
|
260
|
+
async def ensure_api_key(self) -> Optional[str]:
|
|
261
|
+
"""Ensure we have a valid API Key.
|
|
262
|
+
|
|
263
|
+
Order: constructor param → cache file → auto-register.
|
|
264
|
+
|
|
265
|
+
Note: auto-register may raise JellyConnectionError on failure.
|
|
266
|
+
"""
|
|
267
|
+
if self.api_key:
|
|
268
|
+
return self.api_key
|
|
269
|
+
|
|
270
|
+
# Try cache file
|
|
271
|
+
cached = self._load_cached_key()
|
|
272
|
+
if cached:
|
|
273
|
+
self.api_key = cached
|
|
274
|
+
return self.api_key
|
|
275
|
+
|
|
276
|
+
# Try auto-register
|
|
277
|
+
device_id = self._device.get_device_id()
|
|
278
|
+
if not device_id:
|
|
279
|
+
logger.warning("No device ID, cannot auto-register")
|
|
280
|
+
return None
|
|
281
|
+
|
|
282
|
+
api_key = await self.register_device(device_id)
|
|
283
|
+
|
|
284
|
+
if api_key:
|
|
285
|
+
self.api_key = api_key
|
|
286
|
+
self._save_key(api_key)
|
|
287
|
+
return self.api_key
|
|
288
|
+
|
|
289
|
+
return None
|
|
290
|
+
|
|
291
|
+
async def ensure_auth(self) -> bool:
|
|
292
|
+
"""Ensure at least one auth credential is available."""
|
|
293
|
+
if self.jwt_token:
|
|
294
|
+
return True
|
|
295
|
+
if self.api_key:
|
|
296
|
+
return True
|
|
297
|
+
api_key = await self.ensure_api_key()
|
|
298
|
+
return api_key is not None
|
jelly_sdk/core/config.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Unified configuration for Jelly SDK.
|
|
3
|
+
|
|
4
|
+
Supports environment variables with backward-compatible fallbacks:
|
|
5
|
+
- JELLY_BASE_URL (preferred) → JELLY_MEMORY_BASE_URL (legacy) → OPENCLAW_API_URL (legacy)
|
|
6
|
+
- JELLY_API_KEY
|
|
7
|
+
"""
|
|
8
|
+
import os
|
|
9
|
+
import logging
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Optional
|
|
12
|
+
|
|
13
|
+
from pydantic import BaseModel, Field
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _get_jelly_dir() -> Path:
|
|
19
|
+
"""Resolve Jelly config directory.
|
|
20
|
+
|
|
21
|
+
Priority: JELLY_CONFIG_DIR env var → ~/.jelly
|
|
22
|
+
"""
|
|
23
|
+
env = os.getenv("JELLY_CONFIG_DIR")
|
|
24
|
+
if env:
|
|
25
|
+
return Path(env)
|
|
26
|
+
return Path.home() / ".jelly"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
# Unified paths
|
|
30
|
+
JELLY_DIR = _get_jelly_dir()
|
|
31
|
+
LEGACY_DIR = Path.home() / ".jelly_memory"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class JellyConfig(BaseModel):
|
|
35
|
+
"""Unified SDK configuration."""
|
|
36
|
+
|
|
37
|
+
base_url: str = Field("http://127.0.0.1:8000", description="Jelly API base URL (set JELLY_BASE_URL env var)")
|
|
38
|
+
api_key: Optional[str] = Field(None, description="API Key (auto-registered if not set)")
|
|
39
|
+
jwt_token: Optional[str] = Field(None, description="JWT Bearer token")
|
|
40
|
+
admin_key: Optional[str] = Field(None, description="Admin API Key")
|
|
41
|
+
invite_token: Optional[str] = Field(None, description="Invite token for pre-bound device registration")
|
|
42
|
+
timeout: int = Field(30, description="HTTP timeout in seconds")
|
|
43
|
+
max_connections: int = Field(100, description="Max HTTP connections")
|
|
44
|
+
trust_env: bool = Field(True, description="Honor HTTP_PROXY/HTTPS_PROXY/NO_PROXY env vars (I-612④)")
|
|
45
|
+
max_retries: int = Field(1, description="Auto-retry count for 429/5xx on data calls (I-612⑥)")
|
|
46
|
+
|
|
47
|
+
model_config = {"validate_assignment": True}
|
|
48
|
+
|
|
49
|
+
@classmethod
|
|
50
|
+
def from_env(cls) -> "JellyConfig":
|
|
51
|
+
"""Load config from environment variables with legacy fallbacks."""
|
|
52
|
+
base_url = (
|
|
53
|
+
os.getenv("JELLY_BASE_URL")
|
|
54
|
+
or os.getenv("JELLY_MEMORY_BASE_URL")
|
|
55
|
+
or os.getenv("OPENCLAW_API_URL")
|
|
56
|
+
)
|
|
57
|
+
# If no env var is set, keep the default (localhost for local development)
|
|
58
|
+
if not base_url:
|
|
59
|
+
base_url = "http://127.0.0.1:8000"
|
|
60
|
+
logger.info(
|
|
61
|
+
"No JELLY_BASE_URL env var set. Using default %s. "
|
|
62
|
+
"For remote servers, set: export JELLY_BASE_URL=https://jelly.datanaan.cn",
|
|
63
|
+
base_url,
|
|
64
|
+
)
|
|
65
|
+
api_key = os.getenv("JELLY_API_KEY")
|
|
66
|
+
jwt_token = os.getenv("JELLY_JWT_TOKEN")
|
|
67
|
+
admin_key = os.getenv("JELLY_ADMIN_KEY")
|
|
68
|
+
invite_token = os.getenv("JELLY_INVITE_TOKEN")
|
|
69
|
+
timeout = int(os.getenv("JELLY_TIMEOUT", "30"))
|
|
70
|
+
max_connections = int(os.getenv("JELLY_MAX_CONNECTIONS", "100"))
|
|
71
|
+
trust_env = os.getenv("JELLY_TRUST_ENV", "1").lower() not in ("0", "false", "no")
|
|
72
|
+
max_retries = int(os.getenv("JELLY_MAX_RETRIES", "1"))
|
|
73
|
+
|
|
74
|
+
return cls(
|
|
75
|
+
base_url=base_url,
|
|
76
|
+
api_key=api_key,
|
|
77
|
+
jwt_token=jwt_token,
|
|
78
|
+
admin_key=admin_key,
|
|
79
|
+
invite_token=invite_token,
|
|
80
|
+
timeout=timeout,
|
|
81
|
+
max_connections=max_connections,
|
|
82
|
+
trust_env=trust_env,
|
|
83
|
+
max_retries=max_retries,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def api_base(self) -> str:
|
|
88
|
+
"""Base URL without trailing slash."""
|
|
89
|
+
return self.base_url.rstrip("/")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _ensure_jelly_dir() -> Path:
|
|
93
|
+
"""Ensure ~/.jelly/ exists, migrating from legacy path if needed."""
|
|
94
|
+
if JELLY_DIR.exists():
|
|
95
|
+
return JELLY_DIR
|
|
96
|
+
|
|
97
|
+
# Migrate from legacy path
|
|
98
|
+
if LEGACY_DIR.exists() and not LEGACY_DIR.suffix == ".migrated":
|
|
99
|
+
logger.info(f"Migrating {LEGACY_DIR} → {JELLY_DIR}")
|
|
100
|
+
JELLY_DIR.mkdir(parents=True, exist_ok=True)
|
|
101
|
+
|
|
102
|
+
for item in LEGACY_DIR.iterdir():
|
|
103
|
+
if item.name == ".migrated":
|
|
104
|
+
continue
|
|
105
|
+
target = JELLY_DIR / item.name
|
|
106
|
+
if not target.exists():
|
|
107
|
+
import shutil
|
|
108
|
+
if item.is_file():
|
|
109
|
+
shutil.copy2(item, target)
|
|
110
|
+
else:
|
|
111
|
+
shutil.copytree(item, target)
|
|
112
|
+
|
|
113
|
+
# Mark legacy as migrated
|
|
114
|
+
(LEGACY_DIR / ".migrated").touch()
|
|
115
|
+
logger.info("Migration complete")
|
|
116
|
+
|
|
117
|
+
JELLY_DIR.mkdir(parents=True, exist_ok=True)
|
|
118
|
+
return JELLY_DIR
|
jelly_sdk/core/device.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Device management — device ID resolution and caching.
|
|
3
|
+
|
|
4
|
+
Sources (in priority order):
|
|
5
|
+
1. ~/.jelly/device_id (cached)
|
|
6
|
+
2. ~/.jelly_memory/device_id (legacy, auto-migrated)
|
|
7
|
+
3. OpenClaw paired.json (if running inside OpenClaw workspace)
|
|
8
|
+
4. Auto-generated 64-char hex ID
|
|
9
|
+
"""
|
|
10
|
+
import json
|
|
11
|
+
import logging
|
|
12
|
+
import os
|
|
13
|
+
import platform as _platform
|
|
14
|
+
import secrets
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Dict, Optional
|
|
17
|
+
|
|
18
|
+
from .config import JELLY_DIR, LEGACY_DIR, _ensure_jelly_dir
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
DEVICE_ID_FILE = JELLY_DIR / "device_id"
|
|
23
|
+
LEGACY_DEVICE_ID_FILE = LEGACY_DIR / "device_id"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class DeviceManager:
|
|
27
|
+
"""Manages device identity for API registration."""
|
|
28
|
+
|
|
29
|
+
def __init__(self, device_id: Optional[str] = None):
|
|
30
|
+
self._device_id = device_id
|
|
31
|
+
self._resolved = device_id is not None
|
|
32
|
+
|
|
33
|
+
def get_device_id(self) -> str:
|
|
34
|
+
"""Get device ID, resolving from cache or generating new one."""
|
|
35
|
+
if self._resolved:
|
|
36
|
+
return self._device_id
|
|
37
|
+
|
|
38
|
+
# 1. Try new cache
|
|
39
|
+
device_id = self._read_cached(DEVICE_ID_FILE)
|
|
40
|
+
if device_id:
|
|
41
|
+
self._device_id = device_id
|
|
42
|
+
self._resolved = True
|
|
43
|
+
return device_id
|
|
44
|
+
|
|
45
|
+
# 2. Try legacy cache, migrate if found
|
|
46
|
+
device_id = self._read_cached(LEGACY_DEVICE_ID_FILE)
|
|
47
|
+
if device_id:
|
|
48
|
+
self._migrate_legacy()
|
|
49
|
+
self._device_id = device_id
|
|
50
|
+
self._resolved = True
|
|
51
|
+
return device_id
|
|
52
|
+
|
|
53
|
+
# 3. Try OpenClaw paired.json
|
|
54
|
+
device_id = self._read_paired_json()
|
|
55
|
+
if device_id:
|
|
56
|
+
self._device_id = device_id
|
|
57
|
+
self._resolved = True
|
|
58
|
+
self._cache_device_id(device_id)
|
|
59
|
+
return device_id
|
|
60
|
+
|
|
61
|
+
# 4. Auto-generate
|
|
62
|
+
device_id = secrets.token_hex(32) # 64-char hex
|
|
63
|
+
self._device_id = device_id
|
|
64
|
+
self._resolved = True
|
|
65
|
+
self._cache_device_id(device_id)
|
|
66
|
+
logger.info(f"Generated new device ID: {device_id[:16]}...")
|
|
67
|
+
return device_id
|
|
68
|
+
|
|
69
|
+
def _read_cached(self, path: Path) -> Optional[str]:
|
|
70
|
+
"""Read device ID from cache file."""
|
|
71
|
+
if path.exists():
|
|
72
|
+
try:
|
|
73
|
+
content = path.read_text().strip()
|
|
74
|
+
if content and len(content) == 64:
|
|
75
|
+
return content
|
|
76
|
+
except Exception as e:
|
|
77
|
+
logger.warning(f"Failed to read {path}: {e}")
|
|
78
|
+
return None
|
|
79
|
+
|
|
80
|
+
def _read_paired_json(self) -> Optional[str]:
|
|
81
|
+
"""Read device ID from OpenClaw paired.json.
|
|
82
|
+
|
|
83
|
+
路径解析(I-613 审计):内置候选仅含可移植路径(home / /etc);
|
|
84
|
+
非标布局经 OPENCLAW_PAIRED_JSON 环境变量注入——不把内部机器布局
|
|
85
|
+
硬编码进公开分发的 SDK(内部绝对路径会随 wheel/sdist 上 PyPI)。
|
|
86
|
+
"""
|
|
87
|
+
possible_paths = []
|
|
88
|
+
env_paired = os.getenv("OPENCLAW_PAIRED_JSON")
|
|
89
|
+
if env_paired:
|
|
90
|
+
possible_paths.append(Path(env_paired))
|
|
91
|
+
possible_paths += [
|
|
92
|
+
Path.home() / ".openclaw" / "devices" / "paired.json",
|
|
93
|
+
Path("/etc/openclaw/devices/paired.json"),
|
|
94
|
+
]
|
|
95
|
+
|
|
96
|
+
for paired_file in possible_paths:
|
|
97
|
+
if paired_file.exists():
|
|
98
|
+
try:
|
|
99
|
+
with open(paired_file) as f:
|
|
100
|
+
data = json.load(f)
|
|
101
|
+
if isinstance(data, dict):
|
|
102
|
+
# Newer format: direct {deviceId: ...} or nested
|
|
103
|
+
if "deviceId" in data:
|
|
104
|
+
return data["deviceId"]
|
|
105
|
+
# Older format: {id: {deviceId: ...}, ...}
|
|
106
|
+
devices = list(data.values())
|
|
107
|
+
if devices and isinstance(devices[0], dict):
|
|
108
|
+
devices.sort(
|
|
109
|
+
key=lambda d: d.get("tokens", {}).get("operator", {}).get("lastUsedAtMs", 0),
|
|
110
|
+
reverse=True,
|
|
111
|
+
)
|
|
112
|
+
return devices[0].get("deviceId")
|
|
113
|
+
except Exception as e:
|
|
114
|
+
logger.warning(f"Failed to read {paired_file}: {e}")
|
|
115
|
+
return None
|
|
116
|
+
|
|
117
|
+
def _cache_device_id(self, device_id: str) -> None:
|
|
118
|
+
"""Cache device ID to file."""
|
|
119
|
+
_ensure_jelly_dir()
|
|
120
|
+
try:
|
|
121
|
+
DEVICE_ID_FILE.write_text(device_id)
|
|
122
|
+
DEVICE_ID_FILE.chmod(0o600)
|
|
123
|
+
except Exception as e:
|
|
124
|
+
logger.warning(f"Failed to cache device ID: {e}")
|
|
125
|
+
|
|
126
|
+
def _migrate_legacy(self) -> None:
|
|
127
|
+
"""Migrate legacy device_id file to new location."""
|
|
128
|
+
_ensure_jelly_dir()
|
|
129
|
+
if LEGACY_DEVICE_ID_FILE.exists() and not DEVICE_ID_FILE.exists():
|
|
130
|
+
try:
|
|
131
|
+
import shutil
|
|
132
|
+
shutil.copy2(LEGACY_DEVICE_ID_FILE, DEVICE_ID_FILE)
|
|
133
|
+
logger.info(f"Migrated device_id: {LEGACY_DEVICE_ID_FILE} → {DEVICE_ID_FILE}")
|
|
134
|
+
except Exception as e:
|
|
135
|
+
logger.warning(f"Failed to migrate device_id: {e}")
|
|
136
|
+
|
|
137
|
+
def get_device_fingerprint(self) -> Dict[str, object]:
|
|
138
|
+
"""Collect device fingerprint for registration.
|
|
139
|
+
|
|
140
|
+
Returns a dict of environment metadata used to identify the
|
|
141
|
+
runtime environment. None-safe: every value is a plain type
|
|
142
|
+
that serialises to JSON.
|
|
143
|
+
"""
|
|
144
|
+
return {
|
|
145
|
+
"hostname": _platform.node(),
|
|
146
|
+
"platform": _platform.system(),
|
|
147
|
+
"platform_release": _platform.release(),
|
|
148
|
+
"python_version": _platform.python_version(),
|
|
149
|
+
"cpu_count": os.cpu_count(),
|
|
150
|
+
"is_docker": Path("/.dockerenv").exists(),
|
|
151
|
+
}
|