minjiang-client 3.0.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.
- minjiang_client/__init__.py +20 -0
- minjiang_client/auth.py +118 -0
- minjiang_client/client.py +102 -0
- minjiang_client/core.py +305 -0
- minjiang_client/device_group.py +56 -0
- minjiang_client/errors.py +62 -0
- minjiang_client/experiment.py +221 -0
- minjiang_client/http.py +158 -0
- minjiang_client/models.py +77 -0
- minjiang_client/space.py +60 -0
- minjiang_client/task.py +102 -0
- minjiang_client/user.py +31 -0
- minjiang_client/version.py +4 -0
- minjiang_client-3.0.0.dist-info/METADATA +185 -0
- minjiang_client-3.0.0.dist-info/RECORD +17 -0
- minjiang_client-3.0.0.dist-info/WHEEL +5 -0
- minjiang_client-3.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""minjiang_client — Minjiang Studio v3 Python SDK."""
|
|
2
|
+
|
|
3
|
+
from minjiang_client.version import __version__
|
|
4
|
+
from minjiang_client.client import Client
|
|
5
|
+
from minjiang_client.core import Core
|
|
6
|
+
from minjiang_client.errors import ApiError, CoreError, CredentialsError, MinjiangError
|
|
7
|
+
from minjiang_client.models import SubmitResult
|
|
8
|
+
from minjiang_client.task import TaskTimeout
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"Client",
|
|
12
|
+
"Core",
|
|
13
|
+
"SubmitResult",
|
|
14
|
+
"ApiError",
|
|
15
|
+
"CoreError",
|
|
16
|
+
"CredentialsError",
|
|
17
|
+
"MinjiangError",
|
|
18
|
+
"TaskTimeout",
|
|
19
|
+
"__version__",
|
|
20
|
+
]
|
minjiang_client/auth.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Credentials loading for scripts (env + ~/.minjiang/v3/credentials)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from minjiang_client.errors import CredentialsError
|
|
11
|
+
|
|
12
|
+
DEFAULT_CREDENTIALS_PATH = Path.home() / ".minjiang" / "v3" / "credentials"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def credentials_path() -> Path:
|
|
16
|
+
override = (os.environ.get("MJ_CREDENTIALS") or "").strip()
|
|
17
|
+
if override:
|
|
18
|
+
return Path(override).expanduser()
|
|
19
|
+
return DEFAULT_CREDENTIALS_PATH
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def load_credentials(path: Path | None = None) -> dict[str, str]:
|
|
23
|
+
"""Load credentials JSON: ``{"base_url": "...", "token": "..."}``.
|
|
24
|
+
|
|
25
|
+
Also accepts legacy key aliases ``MJ_BASE`` / ``MJ_TOKEN`` / ``server`` / ``api_token``.
|
|
26
|
+
Missing file → empty dict (not an error).
|
|
27
|
+
"""
|
|
28
|
+
p = path or credentials_path()
|
|
29
|
+
if not p.is_file():
|
|
30
|
+
return {}
|
|
31
|
+
try:
|
|
32
|
+
raw = p.read_text(encoding="utf-8").strip()
|
|
33
|
+
if not raw:
|
|
34
|
+
return {}
|
|
35
|
+
data = json.loads(raw)
|
|
36
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
37
|
+
raise CredentialsError(f"无法读取凭据文件 {p}: {exc}") from exc
|
|
38
|
+
if not isinstance(data, dict):
|
|
39
|
+
raise CredentialsError(f"凭据文件必须是 JSON 对象: {p}")
|
|
40
|
+
out: dict[str, str] = {}
|
|
41
|
+
base = (
|
|
42
|
+
data.get("base_url")
|
|
43
|
+
or data.get("MJ_BASE")
|
|
44
|
+
or data.get("server")
|
|
45
|
+
or data.get("base")
|
|
46
|
+
)
|
|
47
|
+
token = (
|
|
48
|
+
data.get("token")
|
|
49
|
+
or data.get("MJ_TOKEN")
|
|
50
|
+
or data.get("api_token")
|
|
51
|
+
or data.get("X-Token")
|
|
52
|
+
)
|
|
53
|
+
if base:
|
|
54
|
+
out["base_url"] = str(base).strip()
|
|
55
|
+
if token:
|
|
56
|
+
out["token"] = str(token).strip()
|
|
57
|
+
return out
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def save_credentials(
|
|
61
|
+
*,
|
|
62
|
+
base_url: str,
|
|
63
|
+
token: str,
|
|
64
|
+
path: Path | None = None,
|
|
65
|
+
) -> Path:
|
|
66
|
+
"""Write credentials JSON with restrictive permissions when possible."""
|
|
67
|
+
p = path or credentials_path()
|
|
68
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
69
|
+
payload = {"base_url": base_url.rstrip("/"), "token": token}
|
|
70
|
+
text = json.dumps(payload, ensure_ascii=False, indent=2) + "\n"
|
|
71
|
+
p.write_text(text, encoding="utf-8")
|
|
72
|
+
try:
|
|
73
|
+
os.chmod(p, 0o600)
|
|
74
|
+
except OSError:
|
|
75
|
+
pass
|
|
76
|
+
return p
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def resolve_base_and_token(
|
|
80
|
+
base_url: str | None = None,
|
|
81
|
+
token: str | None = None,
|
|
82
|
+
*,
|
|
83
|
+
use_env: bool = True,
|
|
84
|
+
use_file: bool = True,
|
|
85
|
+
) -> tuple[str, str | None]:
|
|
86
|
+
"""Resolve base_url / token from args → env → credentials file."""
|
|
87
|
+
file_data: dict[str, str] = {}
|
|
88
|
+
if use_file:
|
|
89
|
+
file_data = load_credentials()
|
|
90
|
+
|
|
91
|
+
resolved_base = (base_url or "").strip()
|
|
92
|
+
if not resolved_base and use_env:
|
|
93
|
+
resolved_base = (os.environ.get("MJ_BASE") or "").strip()
|
|
94
|
+
if not resolved_base:
|
|
95
|
+
resolved_base = (file_data.get("base_url") or "").strip()
|
|
96
|
+
|
|
97
|
+
resolved_token = (token or "").strip() or None
|
|
98
|
+
if not resolved_token and use_env:
|
|
99
|
+
env_tok = (os.environ.get("MJ_TOKEN") or "").strip()
|
|
100
|
+
resolved_token = env_tok or None
|
|
101
|
+
if not resolved_token:
|
|
102
|
+
resolved_token = (file_data.get("token") or "").strip() or None
|
|
103
|
+
|
|
104
|
+
if not resolved_base:
|
|
105
|
+
raise CredentialsError(
|
|
106
|
+
"缺少 Server 地址:传入 base_url,或设置 MJ_BASE,或写入 ~/.minjiang/v3/credentials"
|
|
107
|
+
)
|
|
108
|
+
return resolved_base.rstrip("/"), resolved_token
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def env_snapshot() -> dict[str, Any]:
|
|
112
|
+
return {
|
|
113
|
+
"MJ_BASE": os.environ.get("MJ_BASE"),
|
|
114
|
+
"MJ_TOKEN_set": bool((os.environ.get("MJ_TOKEN") or "").strip()),
|
|
115
|
+
"MJ_CORE_PATH": os.environ.get("MJ_CORE_PATH"),
|
|
116
|
+
"credentials_path": str(credentials_path()),
|
|
117
|
+
"credentials_exists": credentials_path().is_file(),
|
|
118
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Top-level Client entry."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from minjiang_client.auth import resolve_base_and_token
|
|
9
|
+
from minjiang_client.core import Core, install_core
|
|
10
|
+
from minjiang_client.device_group import DeviceGroupAPI
|
|
11
|
+
from minjiang_client.experiment import ExperimentAPI
|
|
12
|
+
from minjiang_client.http import HttpSession
|
|
13
|
+
from minjiang_client.space import SpaceAPI
|
|
14
|
+
from minjiang_client.task import TaskAPI
|
|
15
|
+
from minjiang_client.user import UserAPI
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Client:
|
|
19
|
+
"""Minjiang Studio v3 Python client.
|
|
20
|
+
|
|
21
|
+
Authentication is by long-lived API Token created in Studio::
|
|
22
|
+
|
|
23
|
+
c = Client("http://127.0.0.1:8888", token="...")
|
|
24
|
+
# or
|
|
25
|
+
c = Client.from_env()
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
base_url: str,
|
|
31
|
+
token: str | None = None,
|
|
32
|
+
*,
|
|
33
|
+
timeout: float = 60.0,
|
|
34
|
+
trust_env: bool = False,
|
|
35
|
+
) -> None:
|
|
36
|
+
self.http = HttpSession(
|
|
37
|
+
base_url,
|
|
38
|
+
token=token,
|
|
39
|
+
timeout=timeout,
|
|
40
|
+
trust_env=trust_env,
|
|
41
|
+
)
|
|
42
|
+
self.user = UserAPI(self)
|
|
43
|
+
self.device_groups = DeviceGroupAPI(self)
|
|
44
|
+
self.spaces = SpaceAPI(self)
|
|
45
|
+
self.experiments = ExperimentAPI(self)
|
|
46
|
+
self.tasks = TaskAPI(self)
|
|
47
|
+
self._core: Core | None = None
|
|
48
|
+
|
|
49
|
+
@classmethod
|
|
50
|
+
def from_env(
|
|
51
|
+
cls,
|
|
52
|
+
*,
|
|
53
|
+
base_url: str | None = None,
|
|
54
|
+
token: str | None = None,
|
|
55
|
+
timeout: float = 60.0,
|
|
56
|
+
trust_env: bool = False,
|
|
57
|
+
) -> Client:
|
|
58
|
+
resolved_base, resolved_token = resolve_base_and_token(base_url, token)
|
|
59
|
+
return cls(resolved_base, token=resolved_token, timeout=timeout, trust_env=trust_env)
|
|
60
|
+
|
|
61
|
+
def close(self) -> None:
|
|
62
|
+
self.http.close()
|
|
63
|
+
|
|
64
|
+
def __enter__(self) -> Client:
|
|
65
|
+
return self
|
|
66
|
+
|
|
67
|
+
def __exit__(self, *args: object) -> None:
|
|
68
|
+
self.close()
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def base_url(self) -> str:
|
|
72
|
+
return self.http.base_url
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def token(self) -> str | None:
|
|
76
|
+
return self.http.token
|
|
77
|
+
|
|
78
|
+
def with_token(self, token: str) -> Client:
|
|
79
|
+
"""Return a new Client sharing the same base_url with a different token."""
|
|
80
|
+
return Client(self.base_url, token=token, trust_env=False)
|
|
81
|
+
|
|
82
|
+
def health(self) -> Any:
|
|
83
|
+
return self.http.get("/api/health")
|
|
84
|
+
|
|
85
|
+
def install_core(
|
|
86
|
+
self,
|
|
87
|
+
dest_dir: str | Path,
|
|
88
|
+
*,
|
|
89
|
+
platform: str | None = None,
|
|
90
|
+
) -> Path:
|
|
91
|
+
"""Download Server Core for this OS into ``dest_dir``; return the executable path.
|
|
92
|
+
|
|
93
|
+
Requires API Token. Does not set ``MJ_CORE_PATH`` — use the returned path
|
|
94
|
+
with ``Core(path)`` or set the env yourself.
|
|
95
|
+
"""
|
|
96
|
+
return install_core(self.http, dest_dir, platform=platform)
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def core(self) -> Core:
|
|
100
|
+
if self._core is None:
|
|
101
|
+
self._core = Core.discover()
|
|
102
|
+
return self._core
|
minjiang_client/core.py
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
"""Local Minjiang interpreter core discovery, Server download, and JSON RPC."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import TYPE_CHECKING, Any
|
|
11
|
+
|
|
12
|
+
from minjiang_client.errors import CoreError, CredentialsError
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from minjiang_client.http import HttpSession
|
|
16
|
+
|
|
17
|
+
_CREATE_NO_WINDOW = 0x08000000 if sys.platform == "win32" else 0
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def detect_core_platform() -> str:
|
|
21
|
+
"""Map local OS to Server catalog platform (windows / linux / darwin)."""
|
|
22
|
+
if sys.platform == "win32":
|
|
23
|
+
return "windows"
|
|
24
|
+
if sys.platform == "darwin":
|
|
25
|
+
return "darwin"
|
|
26
|
+
return "linux"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _pick_catalog_item(catalog: dict[str, Any], *, platform: str) -> dict[str, Any]:
|
|
30
|
+
items = catalog.get("items")
|
|
31
|
+
if not isinstance(items, list) or not items:
|
|
32
|
+
raise CoreError(f"当前平台 {platform} 无可用的可下发 Core")
|
|
33
|
+
selected = catalog.get("selected")
|
|
34
|
+
if isinstance(selected, dict) and (selected.get("id") or selected.get("build_id")):
|
|
35
|
+
return selected
|
|
36
|
+
return max(
|
|
37
|
+
(it for it in items if isinstance(it, dict)),
|
|
38
|
+
key=lambda it: (int(it.get("create_time") or 0), int(it.get("id") or it.get("build_id") or 0)),
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def install_core(
|
|
43
|
+
http: HttpSession,
|
|
44
|
+
dest_dir: str | Path,
|
|
45
|
+
*,
|
|
46
|
+
platform: str | None = None,
|
|
47
|
+
) -> Path:
|
|
48
|
+
"""Download the Server Core for this OS into ``dest_dir``; return the executable path.
|
|
49
|
+
|
|
50
|
+
Requires a logged-in session (API Token). Does not set ``MJ_CORE_PATH``.
|
|
51
|
+
"""
|
|
52
|
+
if not str(dest_dir or "").strip():
|
|
53
|
+
raise CoreError("dest_dir 必填")
|
|
54
|
+
if not getattr(http, "token", None):
|
|
55
|
+
raise CredentialsError("下载 Core 需要已登录(API Token)")
|
|
56
|
+
|
|
57
|
+
plat = (platform or detect_core_platform()).strip().lower() or detect_core_platform()
|
|
58
|
+
catalog = http.get("/api/interpreter/cores/catalog", params={"platform": plat})
|
|
59
|
+
if not isinstance(catalog, dict):
|
|
60
|
+
raise CoreError("Core catalog 响应无效")
|
|
61
|
+
item = _pick_catalog_item(catalog, platform=plat)
|
|
62
|
+
|
|
63
|
+
build_id = int(item.get("id") or item.get("build_id") or 0)
|
|
64
|
+
if build_id <= 0:
|
|
65
|
+
raise CoreError("Core catalog 缺少 build id")
|
|
66
|
+
filename = str(item.get("filename") or "").strip() or f"minjiang-interpreter-core-{build_id}"
|
|
67
|
+
filename = Path(filename).name
|
|
68
|
+
url = str(item.get("download_url") or "").strip() or f"/api/interpreter/cores/builds/{build_id}/download"
|
|
69
|
+
|
|
70
|
+
dest = Path(dest_dir).expanduser().resolve()
|
|
71
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
72
|
+
payload = http.download_bytes(url)
|
|
73
|
+
if not payload:
|
|
74
|
+
raise CoreError("Core 下载内容为空")
|
|
75
|
+
|
|
76
|
+
exe = dest / filename
|
|
77
|
+
exe.write_bytes(payload)
|
|
78
|
+
meta = {
|
|
79
|
+
"id": build_id,
|
|
80
|
+
"name": item.get("name") or item.get("version") or "",
|
|
81
|
+
"version": item.get("version") or "",
|
|
82
|
+
"platform": item.get("platform") or plat,
|
|
83
|
+
"filename": filename,
|
|
84
|
+
"size_bytes": item.get("size_bytes") or len(payload),
|
|
85
|
+
"create_time": item.get("create_time") or 0,
|
|
86
|
+
}
|
|
87
|
+
(dest / "core.meta.json").write_text(
|
|
88
|
+
json.dumps(meta, ensure_ascii=False, indent=2) + "\n",
|
|
89
|
+
encoding="utf-8",
|
|
90
|
+
)
|
|
91
|
+
if not exe.is_file():
|
|
92
|
+
raise CoreError(f"Core 安装失败: {exe}")
|
|
93
|
+
return exe
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def interpreter_client_settings_path() -> Path:
|
|
98
|
+
"""Interpreter Client settings.json (same layout as the desktop client)."""
|
|
99
|
+
if sys.platform == "win32":
|
|
100
|
+
base = os.environ.get("APPDATA") or str(Path.home() / "AppData" / "Roaming")
|
|
101
|
+
return Path(base) / "MinjiangInterpreterClient" / "settings.json"
|
|
102
|
+
if sys.platform == "darwin":
|
|
103
|
+
return (
|
|
104
|
+
Path.home()
|
|
105
|
+
/ "Library"
|
|
106
|
+
/ "Application Support"
|
|
107
|
+
/ "MinjiangInterpreterClient"
|
|
108
|
+
/ "settings.json"
|
|
109
|
+
)
|
|
110
|
+
# .NET ApplicationData on Linux
|
|
111
|
+
xdg = os.environ.get("XDG_CONFIG_HOME")
|
|
112
|
+
base = Path(xdg) if xdg else Path.home() / ".config"
|
|
113
|
+
return base / "MinjiangInterpreterClient" / "settings.json"
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def interpreter_client_cores_root() -> Path:
|
|
117
|
+
"""~/minjiang/interpreter_client/cores — Server-downloaded Core builds."""
|
|
118
|
+
return Path.home() / "minjiang" / "interpreter_client" / "cores"
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def find_core_exe_in_dir(directory: Path) -> Path | None:
|
|
122
|
+
"""Resolve an installed Core directory to an executable (Client-compatible)."""
|
|
123
|
+
if not directory.is_dir():
|
|
124
|
+
return None
|
|
125
|
+
meta = directory / "core.meta.json"
|
|
126
|
+
if meta.is_file():
|
|
127
|
+
try:
|
|
128
|
+
data = json.loads(meta.read_text(encoding="utf-8"))
|
|
129
|
+
name = str(data.get("filename") or "").strip()
|
|
130
|
+
if name:
|
|
131
|
+
candidate = directory / name
|
|
132
|
+
if candidate.is_file():
|
|
133
|
+
return candidate
|
|
134
|
+
except (OSError, json.JSONDecodeError, TypeError):
|
|
135
|
+
pass
|
|
136
|
+
if sys.platform == "win32":
|
|
137
|
+
exes = sorted(directory.glob("*.exe"))
|
|
138
|
+
if exes:
|
|
139
|
+
return exes[0]
|
|
140
|
+
for pat in (
|
|
141
|
+
"minjiang-interpreter-core*",
|
|
142
|
+
"minjiang-interpreter-core",
|
|
143
|
+
):
|
|
144
|
+
matches = [p for p in directory.glob(pat) if p.is_file()]
|
|
145
|
+
if matches:
|
|
146
|
+
matches.sort(key=lambda p: p.stat().st_mtime, reverse=True)
|
|
147
|
+
return matches[0]
|
|
148
|
+
return None
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _coerce_core_path(path: Path) -> Path | None:
|
|
152
|
+
path = path.expanduser()
|
|
153
|
+
if path.is_file():
|
|
154
|
+
return path
|
|
155
|
+
if path.is_dir():
|
|
156
|
+
return find_core_exe_in_dir(path)
|
|
157
|
+
return None
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _core_from_client_settings() -> Path | None:
|
|
161
|
+
settings = interpreter_client_settings_path()
|
|
162
|
+
if not settings.is_file():
|
|
163
|
+
return None
|
|
164
|
+
try:
|
|
165
|
+
data = json.loads(settings.read_text(encoding="utf-8"))
|
|
166
|
+
except (OSError, json.JSONDecodeError):
|
|
167
|
+
return None
|
|
168
|
+
if not isinstance(data, dict):
|
|
169
|
+
return None
|
|
170
|
+
raw = str(data.get("InterpreterCorePath") or "").strip()
|
|
171
|
+
if not raw:
|
|
172
|
+
return None
|
|
173
|
+
return _coerce_core_path(Path(raw))
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _core_from_client_cores_dir() -> Path | None:
|
|
177
|
+
root = interpreter_client_cores_root()
|
|
178
|
+
if not root.is_dir():
|
|
179
|
+
return None
|
|
180
|
+
dirs = [
|
|
181
|
+
p
|
|
182
|
+
for p in root.iterdir()
|
|
183
|
+
if p.is_dir() and not p.name.startswith(".")
|
|
184
|
+
]
|
|
185
|
+
dirs.sort(key=lambda p: p.stat().st_mtime, reverse=True)
|
|
186
|
+
for d in dirs:
|
|
187
|
+
found = find_core_exe_in_dir(d)
|
|
188
|
+
if found is not None:
|
|
189
|
+
return found
|
|
190
|
+
return None
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class Core:
|
|
194
|
+
"""Invoke a discovered interpreter-core binary (external; not bundled)."""
|
|
195
|
+
|
|
196
|
+
def __init__(self, path: Path | None = None, *, timeout: float = 120.0) -> None:
|
|
197
|
+
self._path = Path(path) if path else None
|
|
198
|
+
self.timeout = float(timeout)
|
|
199
|
+
|
|
200
|
+
@classmethod
|
|
201
|
+
def discover(cls, *, timeout: float = 120.0) -> Core:
|
|
202
|
+
path = resolve_core_path()
|
|
203
|
+
if path is None:
|
|
204
|
+
raise CoreError(
|
|
205
|
+
"未找到 interpreter core:请先在解释器客户端下载/选用 Core,"
|
|
206
|
+
"或设置 MJ_CORE_PATH 指向可执行文件"
|
|
207
|
+
)
|
|
208
|
+
return cls(path, timeout=timeout)
|
|
209
|
+
|
|
210
|
+
def path(self) -> Path:
|
|
211
|
+
if self._path is None:
|
|
212
|
+
self._path = resolve_core_path()
|
|
213
|
+
if self._path is None:
|
|
214
|
+
raise CoreError("interpreter core 路径未设置")
|
|
215
|
+
return self._path
|
|
216
|
+
|
|
217
|
+
def version(self) -> str:
|
|
218
|
+
bin_dir = self.path().parent
|
|
219
|
+
meta = bin_dir / "core.meta.json"
|
|
220
|
+
if meta.is_file():
|
|
221
|
+
try:
|
|
222
|
+
data = json.loads(meta.read_text(encoding="utf-8"))
|
|
223
|
+
ver = str(data.get("version") or data.get("name") or "").strip()
|
|
224
|
+
if ver:
|
|
225
|
+
return ver
|
|
226
|
+
except (OSError, json.JSONDecodeError, TypeError):
|
|
227
|
+
pass
|
|
228
|
+
ver_file = bin_dir / "CORE_VERSION"
|
|
229
|
+
if ver_file.is_file():
|
|
230
|
+
return ver_file.read_text(encoding="utf-8").strip()
|
|
231
|
+
out = self.call({"mode": "ping"})
|
|
232
|
+
return str(out.get("version") or "")
|
|
233
|
+
|
|
234
|
+
def compile(self, qis: str, target: str) -> dict[str, Any]:
|
|
235
|
+
return self.call({"mode": "compile", "qis": qis, "target": target})
|
|
236
|
+
|
|
237
|
+
def lookup(self, name: str, *, qis: str = "", target: str = "") -> dict[str, Any]:
|
|
238
|
+
return self.call({"mode": "lookup", "name": name, "qis": qis, "target": target})
|
|
239
|
+
|
|
240
|
+
def describe_target(self, target: str, *, qis: str = "") -> dict[str, Any]:
|
|
241
|
+
return self.call({"mode": "describe_target", "target": target, "qis": qis})
|
|
242
|
+
|
|
243
|
+
def call(self, payload: dict[str, Any]) -> dict[str, Any]:
|
|
244
|
+
exe = self.path()
|
|
245
|
+
if not exe.is_file():
|
|
246
|
+
raise CoreError(f"core 可执行文件不存在: {exe}")
|
|
247
|
+
raw = json.dumps(payload, ensure_ascii=False)
|
|
248
|
+
try:
|
|
249
|
+
proc = subprocess.run(
|
|
250
|
+
[str(exe)],
|
|
251
|
+
input=raw.encode("utf-8"),
|
|
252
|
+
capture_output=True,
|
|
253
|
+
timeout=self.timeout,
|
|
254
|
+
creationflags=_CREATE_NO_WINDOW,
|
|
255
|
+
)
|
|
256
|
+
except subprocess.TimeoutExpired as exc:
|
|
257
|
+
raise CoreError(
|
|
258
|
+
f"core 超时({self.timeout}s)",
|
|
259
|
+
stderr=(exc.stderr or b"").decode("utf-8", errors="replace") if exc.stderr else "",
|
|
260
|
+
) from exc
|
|
261
|
+
except OSError as exc:
|
|
262
|
+
raise CoreError(f"无法启动 core: {exc}") from exc
|
|
263
|
+
|
|
264
|
+
stdout = (proc.stdout or b"").decode("utf-8", errors="replace").strip()
|
|
265
|
+
stderr = (proc.stderr or b"").decode("utf-8", errors="replace").strip()
|
|
266
|
+
if proc.returncode != 0:
|
|
267
|
+
raise CoreError(
|
|
268
|
+
f"core 退出码 {proc.returncode}: {stderr or stdout or 'no output'}",
|
|
269
|
+
stderr=stderr,
|
|
270
|
+
returncode=proc.returncode,
|
|
271
|
+
)
|
|
272
|
+
if not stdout:
|
|
273
|
+
raise CoreError("core 无输出", stderr=stderr, returncode=proc.returncode)
|
|
274
|
+
try:
|
|
275
|
+
line = stdout.splitlines()[0]
|
|
276
|
+
data = json.loads(line)
|
|
277
|
+
except json.JSONDecodeError as exc:
|
|
278
|
+
raise CoreError(
|
|
279
|
+
f"core 输出不是 JSON: {stdout[:200]}",
|
|
280
|
+
stderr=stderr,
|
|
281
|
+
returncode=proc.returncode,
|
|
282
|
+
) from exc
|
|
283
|
+
if not isinstance(data, dict):
|
|
284
|
+
raise CoreError(f"core 返回非对象: {type(data)!r}", stderr=stderr)
|
|
285
|
+
if data.get("ok") is False or data.get("error"):
|
|
286
|
+
err = data.get("error") or data.get("msg") or data
|
|
287
|
+
raise CoreError(str(err), stderr=stderr, returncode=proc.returncode)
|
|
288
|
+
return data
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def resolve_core_path() -> Path | None:
|
|
292
|
+
"""Discovery: MJ_CORE_PATH → Interpreter Client settings → downloaded cores/."""
|
|
293
|
+
env = (os.environ.get("MJ_CORE_PATH") or "").strip()
|
|
294
|
+
if env:
|
|
295
|
+
p = Path(env).expanduser()
|
|
296
|
+
resolved = _coerce_core_path(p)
|
|
297
|
+
if resolved is not None:
|
|
298
|
+
return resolved
|
|
299
|
+
raise CoreError(f"MJ_CORE_PATH 无效(不是可执行文件或 Core 目录): {p}")
|
|
300
|
+
|
|
301
|
+
from_settings = _core_from_client_settings()
|
|
302
|
+
if from_settings is not None:
|
|
303
|
+
return from_settings
|
|
304
|
+
|
|
305
|
+
return _core_from_client_cores_dir()
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Device group API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, Any
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from minjiang_client.client import Client
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class DeviceGroupAPI:
|
|
12
|
+
def __init__(self, client: Client) -> None:
|
|
13
|
+
self._c = client
|
|
14
|
+
|
|
15
|
+
def list(
|
|
16
|
+
self,
|
|
17
|
+
*,
|
|
18
|
+
organization_id: int | None = None,
|
|
19
|
+
include_hidden: bool = False,
|
|
20
|
+
) -> list[dict[str, Any]]:
|
|
21
|
+
params: dict[str, Any] = {"include_hidden": include_hidden}
|
|
22
|
+
if organization_id is not None:
|
|
23
|
+
params["organization_id"] = organization_id
|
|
24
|
+
data = self._c.http.get("/api/device_group/list", params=params)
|
|
25
|
+
return list(data or [])
|
|
26
|
+
|
|
27
|
+
def get(self, group_id: int) -> dict[str, Any]:
|
|
28
|
+
return self._c.http.get(f"/api/device_group/{group_id}")
|
|
29
|
+
|
|
30
|
+
def create(
|
|
31
|
+
self,
|
|
32
|
+
name: str,
|
|
33
|
+
*,
|
|
34
|
+
organization_id: int,
|
|
35
|
+
description: str = "",
|
|
36
|
+
visibility: str = "public",
|
|
37
|
+
category_id: int | None = None,
|
|
38
|
+
) -> dict[str, Any]:
|
|
39
|
+
body: dict[str, Any] = {
|
|
40
|
+
"name": name,
|
|
41
|
+
"organization_id": organization_id,
|
|
42
|
+
"description": description,
|
|
43
|
+
"visibility": visibility,
|
|
44
|
+
}
|
|
45
|
+
if category_id is not None:
|
|
46
|
+
body["category_id"] = category_id
|
|
47
|
+
return self._c.http.post("/api/device_group/create", json=body)
|
|
48
|
+
|
|
49
|
+
def update(self, group_id: int, **fields: Any) -> dict[str, Any]:
|
|
50
|
+
return self._c.http.post(f"/api/device_group/update/{group_id}", json=fields)
|
|
51
|
+
|
|
52
|
+
def delete(self, group_id: int) -> Any:
|
|
53
|
+
return self._c.http.delete(f"/api/device_group/{group_id}")
|
|
54
|
+
|
|
55
|
+
def spaces(self, group_id: int, **kw: Any) -> list[dict[str, Any]]:
|
|
56
|
+
return self._c.spaces.list(device_group_id=group_id, **kw)
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""SDK exception types."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class MinjiangError(Exception):
|
|
9
|
+
"""Base error for minjiang_client."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ApiError(MinjiangError):
|
|
13
|
+
"""HTTP / Server API failure."""
|
|
14
|
+
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
status_code: int,
|
|
18
|
+
detail: Any = None,
|
|
19
|
+
*,
|
|
20
|
+
msg: str = "",
|
|
21
|
+
body: Any = None,
|
|
22
|
+
) -> None:
|
|
23
|
+
self.status_code = int(status_code)
|
|
24
|
+
self.detail = detail
|
|
25
|
+
self.msg = msg or ""
|
|
26
|
+
self.body = body
|
|
27
|
+
text = _format_detail(detail) if detail is not None else (self.msg or "API error")
|
|
28
|
+
super().__init__(f"HTTP {self.status_code}: {text}")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class CoreError(MinjiangError):
|
|
32
|
+
"""Local interpreter core failure."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, message: str, *, stderr: str = "", returncode: int | None = None) -> None:
|
|
35
|
+
self.stderr = stderr or ""
|
|
36
|
+
self.returncode = returncode
|
|
37
|
+
super().__init__(message)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class CredentialsError(MinjiangError):
|
|
41
|
+
"""Missing or invalid credentials / env config."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _format_detail(detail: Any) -> str:
|
|
45
|
+
if isinstance(detail, str):
|
|
46
|
+
return detail
|
|
47
|
+
if isinstance(detail, list):
|
|
48
|
+
parts: list[str] = []
|
|
49
|
+
for item in detail:
|
|
50
|
+
if isinstance(item, dict):
|
|
51
|
+
loc = item.get("loc")
|
|
52
|
+
msg = item.get("msg") or item.get("message") or str(item)
|
|
53
|
+
if loc:
|
|
54
|
+
parts.append(f"{'.'.join(str(x) for x in loc)}: {msg}")
|
|
55
|
+
else:
|
|
56
|
+
parts.append(str(msg))
|
|
57
|
+
else:
|
|
58
|
+
parts.append(str(item))
|
|
59
|
+
return "; ".join(parts) if parts else str(detail)
|
|
60
|
+
if isinstance(detail, dict):
|
|
61
|
+
return str(detail.get("msg") or detail.get("detail") or detail)
|
|
62
|
+
return str(detail)
|