sim-cli-core 0.2.4__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.
- sim/__init__.py +11 -0
- sim/__main__.py +24 -0
- sim/_plugin_install.py +451 -0
- sim/_timeout.py +115 -0
- sim/cli.py +1353 -0
- sim/compat.py +411 -0
- sim/config.py +380 -0
- sim/describe.py +346 -0
- sim/driver.py +190 -0
- sim/drivers/__init__.py +161 -0
- sim/drivers/coolprop/__init__.py +3 -0
- sim/drivers/coolprop/driver.py +183 -0
- sim/drivers/openfoam/__init__.py +4 -0
- sim/drivers/openfoam/compatibility.yaml +37 -0
- sim/drivers/openfoam/driver.py +432 -0
- sim/gui/LICENSES/ATTRIBUTION.md +24 -0
- sim/gui/__init__.py +230 -0
- sim/gui/_pywinauto_tools.py +452 -0
- sim/gui/_win32_dialog.py +148 -0
- sim/history.py +170 -0
- sim/inspect.py +1088 -0
- sim/plugins.py +468 -0
- sim/runner.py +195 -0
- sim/server.py +547 -0
- sim/session.py +224 -0
- sim/testing/__init__.py +30 -0
- sim/testing/protocol_conformance.py +264 -0
- sim_cli_core-0.2.4.dist-info/METADATA +309 -0
- sim_cli_core-0.2.4.dist-info/RECORD +33 -0
- sim_cli_core-0.2.4.dist-info/WHEEL +4 -0
- sim_cli_core-0.2.4.dist-info/entry_points.txt +2 -0
- sim_cli_core-0.2.4.dist-info/licenses/LICENSE +190 -0
- sim_cli_core-0.2.4.dist-info/licenses/NOTICE +72 -0
sim/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""sim — unified CLI for LLM agents to control CAD/CAE simulation software."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
__version__ = version("sim-cli-core")
|
|
7
|
+
except PackageNotFoundError:
|
|
8
|
+
try:
|
|
9
|
+
__version__ = version("sim-runtime")
|
|
10
|
+
except PackageNotFoundError:
|
|
11
|
+
__version__ = "0.0.0+unknown"
|
sim/__main__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Allow ``python -m sim ...`` invocation (equivalent to the ``sim`` console script).
|
|
2
|
+
|
|
3
|
+
Why this exists
|
|
4
|
+
---------------
|
|
5
|
+
The console script ``sim`` (declared in ``[project.scripts]``) is the canonical
|
|
6
|
+
entry point for end users — it stays unchanged. This module forwards
|
|
7
|
+
``python -m sim ...`` to the same Click group so developers have a second
|
|
8
|
+
invocation that does *not* hold a Windows file lock on
|
|
9
|
+
``.venv/Scripts/sim.exe``.
|
|
10
|
+
|
|
11
|
+
That lock is the whole reason this file exists: with the editable install,
|
|
12
|
+
``uv sync`` rewrites ``Scripts/sim.exe`` on every sync, but a running
|
|
13
|
+
``sim serve`` has the exe open, so Windows refuses the rewrite (``os error
|
|
14
|
+
32``) and the entire sync aborts. Launching the dev server as
|
|
15
|
+
``python -m sim serve --reload`` instead means the running process holds
|
|
16
|
+
``python.exe`` (uv-managed, shared, not project-managed), and ``sim.exe``
|
|
17
|
+
stays free for ``uv sync`` to rewrite while iteration proceeds.
|
|
18
|
+
|
|
19
|
+
Same pattern used by pip, ruff, pytest, etc.
|
|
20
|
+
"""
|
|
21
|
+
from sim.cli import main
|
|
22
|
+
|
|
23
|
+
if __name__ == "__main__":
|
|
24
|
+
main()
|
sim/_plugin_install.py
ADDED
|
@@ -0,0 +1,451 @@
|
|
|
1
|
+
"""Install / uninstall / bundle plugins.
|
|
2
|
+
|
|
3
|
+
The `sim plugin` group's mutating commands route through here. Discovery
|
|
4
|
+
and validation live in :mod:`sim.plugins`; this module only handles the
|
|
5
|
+
install pipeline.
|
|
6
|
+
|
|
7
|
+
A `<source>` argument can be any of:
|
|
8
|
+
|
|
9
|
+
* ``<name>`` — resolve via the index (HTTPS-only; no git, no gh).
|
|
10
|
+
* ``<name>@<version>`` — pinned from the index.
|
|
11
|
+
* ``https://...whl`` / ``https://...tar.gz`` — direct wheel/sdist URL.
|
|
12
|
+
* ``./path/to/dir`` — local plugin source directory.
|
|
13
|
+
* ``./path/to/wheel.whl`` / ``./path/to/sdist.tar.gz`` — local artifact.
|
|
14
|
+
* ``git+https://...`` / ``git+ssh://...`` — git URL.
|
|
15
|
+
|
|
16
|
+
The resolver classifies the source with no network calls so we know up
|
|
17
|
+
front what kind of install we're attempting. Then a single ``pip install``
|
|
18
|
+
invocation does the work.
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
import shutil
|
|
26
|
+
import subprocess
|
|
27
|
+
import sys
|
|
28
|
+
import urllib.request
|
|
29
|
+
from dataclasses import dataclass, field
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
from typing import Any
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# ── Index ───────────────────────────────────────────────────────────────────
|
|
35
|
+
|
|
36
|
+
DEFAULT_INDEX_URL = (
|
|
37
|
+
"https://raw.githubusercontent.com/svd-ai-lab/sim-plugin-index/main/index.json"
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
# How long an index is treated as fresh, before we re-fetch.
|
|
41
|
+
INDEX_CACHE_TTL_SECONDS = 3600
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _index_cache_dir() -> Path:
|
|
45
|
+
return Path.home() / ".sim" / "index-cache"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _index_cache_path() -> Path:
|
|
49
|
+
return _index_cache_dir() / "index.json"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def fetch_index(url: str = DEFAULT_INDEX_URL, *, force: bool = False, offline: bool = False) -> dict[str, Any]:
|
|
53
|
+
"""Fetch the public plugin index. Caches under ~/.sim/index-cache/.
|
|
54
|
+
|
|
55
|
+
In ``--offline`` mode, only the local cache is consulted; an empty index
|
|
56
|
+
is returned if no cache exists.
|
|
57
|
+
"""
|
|
58
|
+
cache = _index_cache_path()
|
|
59
|
+
if offline:
|
|
60
|
+
if cache.is_file():
|
|
61
|
+
try:
|
|
62
|
+
return json.loads(cache.read_text(encoding="utf-8"))
|
|
63
|
+
except (OSError, json.JSONDecodeError):
|
|
64
|
+
return {"schema_version": 1, "plugins": []}
|
|
65
|
+
return {"schema_version": 1, "plugins": []}
|
|
66
|
+
|
|
67
|
+
if not force and cache.is_file():
|
|
68
|
+
try:
|
|
69
|
+
age = cache.stat().st_mtime
|
|
70
|
+
except OSError:
|
|
71
|
+
age = 0
|
|
72
|
+
import time
|
|
73
|
+
if time.time() - age < INDEX_CACHE_TTL_SECONDS:
|
|
74
|
+
try:
|
|
75
|
+
return json.loads(cache.read_text(encoding="utf-8"))
|
|
76
|
+
except (OSError, json.JSONDecodeError):
|
|
77
|
+
pass
|
|
78
|
+
|
|
79
|
+
try:
|
|
80
|
+
with urllib.request.urlopen(url, timeout=10) as resp:
|
|
81
|
+
data = resp.read().decode("utf-8")
|
|
82
|
+
except Exception: # noqa: BLE001 — degrade if no network
|
|
83
|
+
if cache.is_file():
|
|
84
|
+
try:
|
|
85
|
+
return json.loads(cache.read_text(encoding="utf-8"))
|
|
86
|
+
except (OSError, json.JSONDecodeError):
|
|
87
|
+
pass
|
|
88
|
+
return {"schema_version": 1, "plugins": []}
|
|
89
|
+
|
|
90
|
+
parsed = json.loads(data)
|
|
91
|
+
cache.parent.mkdir(parents=True, exist_ok=True)
|
|
92
|
+
cache.write_text(data, encoding="utf-8")
|
|
93
|
+
return parsed
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def index_entry(name: str, *, offline: bool = False, url: str = DEFAULT_INDEX_URL) -> dict[str, Any] | None:
|
|
97
|
+
"""Look up one plugin by name in the index."""
|
|
98
|
+
idx = fetch_index(url=url, offline=offline)
|
|
99
|
+
for entry in idx.get("plugins", []):
|
|
100
|
+
if entry.get("name") == name:
|
|
101
|
+
return entry
|
|
102
|
+
return None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
# ── Source resolution ──────────────────────────────────────────────────────
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@dataclass(frozen=True)
|
|
109
|
+
class ResolvedSource:
|
|
110
|
+
"""One install source classified into a canonical kind."""
|
|
111
|
+
kind: str # "name" | "wheel-url" | "sdist-url" | "git-url" | "local-wheel" | "local-sdist" | "local-dir" | "name-version"
|
|
112
|
+
raw: str # the original argument
|
|
113
|
+
name: str | None = None
|
|
114
|
+
version: str | None = None
|
|
115
|
+
pip_target: str = "" # what pip install gets handed
|
|
116
|
+
extras: dict[str, Any] = field(default_factory=dict)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
_NAME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*$")
|
|
120
|
+
_NAME_VERSION_RE = re.compile(r"^([A-Za-z][A-Za-z0-9_]*)@([A-Za-z0-9._\-+]+)$")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def resolve_source(source: str, *, offline: bool = False, index_url: str = DEFAULT_INDEX_URL) -> ResolvedSource:
|
|
124
|
+
"""Classify a source argument and choose what to hand to pip.
|
|
125
|
+
|
|
126
|
+
For named (index-resolved) installs, prefers wheel-from-release URL when
|
|
127
|
+
the index entry has one; falls back to git+https. Raises ``ValueError``
|
|
128
|
+
if the name isn't in the index in offline mode.
|
|
129
|
+
"""
|
|
130
|
+
s = source.strip()
|
|
131
|
+
|
|
132
|
+
# Local files / dirs first (cheapest to check).
|
|
133
|
+
p = Path(s)
|
|
134
|
+
if s.startswith(("./", "../", "/", "~")) or p.exists():
|
|
135
|
+
target = p.expanduser().resolve()
|
|
136
|
+
if target.is_file():
|
|
137
|
+
if target.suffix == ".whl":
|
|
138
|
+
return ResolvedSource(kind="local-wheel", raw=s, pip_target=str(target))
|
|
139
|
+
if target.name.endswith(".tar.gz") or target.suffix == ".tar":
|
|
140
|
+
return ResolvedSource(kind="local-sdist", raw=s, pip_target=str(target))
|
|
141
|
+
raise ValueError(f"unsupported local file extension: {target.name}")
|
|
142
|
+
if target.is_dir():
|
|
143
|
+
return ResolvedSource(kind="local-dir", raw=s, pip_target=str(target))
|
|
144
|
+
# Path doesn't exist on disk and doesn't look obviously remote — error.
|
|
145
|
+
if s.startswith(("./", "../", "/", "~")):
|
|
146
|
+
raise FileNotFoundError(f"local path does not exist: {s}")
|
|
147
|
+
|
|
148
|
+
# URLs — direct wheel/sdist or git.
|
|
149
|
+
if s.startswith("git+"):
|
|
150
|
+
return ResolvedSource(kind="git-url", raw=s, pip_target=s)
|
|
151
|
+
if s.startswith(("http://", "https://")):
|
|
152
|
+
if s.endswith(".whl"):
|
|
153
|
+
return ResolvedSource(kind="wheel-url", raw=s, pip_target=s)
|
|
154
|
+
if s.endswith(".tar.gz") or s.endswith(".tar.bz2"):
|
|
155
|
+
return ResolvedSource(kind="sdist-url", raw=s, pip_target=s)
|
|
156
|
+
# Generic URL: treat as wheel-url and let pip complain.
|
|
157
|
+
return ResolvedSource(kind="wheel-url", raw=s, pip_target=s)
|
|
158
|
+
|
|
159
|
+
# name@version
|
|
160
|
+
m = _NAME_VERSION_RE.match(s)
|
|
161
|
+
if m:
|
|
162
|
+
name, version = m.group(1), m.group(2)
|
|
163
|
+
entry = index_entry(name, offline=offline, url=index_url)
|
|
164
|
+
if entry is None and offline:
|
|
165
|
+
raise ValueError(f"plugin {name!r} not in offline index")
|
|
166
|
+
if entry is None:
|
|
167
|
+
# Optimistic: try by-name install; pip will error if it's wrong.
|
|
168
|
+
return ResolvedSource(kind="name-version", raw=s, name=name, version=version,
|
|
169
|
+
pip_target=f"sim-plugin-{name}=={version}")
|
|
170
|
+
# Prefer the same wheel as latest if it matches; else fall back to git@version.
|
|
171
|
+
if entry.get("latest_version") == version and entry.get("latest_wheel_url"):
|
|
172
|
+
return ResolvedSource(kind="name-version", raw=s, name=name, version=version,
|
|
173
|
+
pip_target=str(entry["latest_wheel_url"]))
|
|
174
|
+
git = entry.get("git")
|
|
175
|
+
if git:
|
|
176
|
+
return ResolvedSource(kind="name-version", raw=s, name=name, version=version,
|
|
177
|
+
pip_target=f"git+{git}@v{version}")
|
|
178
|
+
return ResolvedSource(kind="name-version", raw=s, name=name, version=version,
|
|
179
|
+
pip_target=f"sim-plugin-{name}=={version}")
|
|
180
|
+
|
|
181
|
+
# bare name
|
|
182
|
+
if _NAME_RE.match(s):
|
|
183
|
+
entry = index_entry(s, offline=offline, url=index_url)
|
|
184
|
+
if entry is None and offline:
|
|
185
|
+
raise ValueError(f"plugin {s!r} not in offline index")
|
|
186
|
+
if entry is None:
|
|
187
|
+
# Optimistic: assume sim-plugin-<name> is published; pip will tell us.
|
|
188
|
+
return ResolvedSource(kind="name", raw=s, name=s, pip_target=f"sim-plugin-{s}")
|
|
189
|
+
if entry.get("latest_wheel_url"):
|
|
190
|
+
return ResolvedSource(kind="name", raw=s, name=s, pip_target=str(entry["latest_wheel_url"]))
|
|
191
|
+
if entry.get("git"):
|
|
192
|
+
return ResolvedSource(kind="name", raw=s, name=s, pip_target=f"git+{entry['git']}")
|
|
193
|
+
return ResolvedSource(kind="name", raw=s, name=s, pip_target=f"sim-plugin-{s}")
|
|
194
|
+
|
|
195
|
+
raise ValueError(f"could not classify install source: {source!r}")
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
# ── pip invocation ──────────────────────────────────────────────────────────
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _pip_install(target: str, *, editable: bool = False, upgrade: bool = False,
|
|
202
|
+
extra_args: list[str] | None = None,
|
|
203
|
+
python: str | None = None) -> subprocess.CompletedProcess:
|
|
204
|
+
"""Run ``pip install`` (or ``uv pip install`` if uv is on PATH).
|
|
205
|
+
|
|
206
|
+
``python`` lets the caller pin which interpreter receives the install.
|
|
207
|
+
Defaults to ``sys.executable`` (the interpreter running ``sim``), which
|
|
208
|
+
is the right choice in 90% of cases. The canary verification proved
|
|
209
|
+
that without an explicit pin, ``uv pip install`` resolves the active
|
|
210
|
+
venv via ``$VIRTUAL_ENV`` / ``$CONDA_PREFIX`` / cwd discovery, which
|
|
211
|
+
can target the *wrong* interpreter when the user's terminal has no
|
|
212
|
+
venv activated.
|
|
213
|
+
"""
|
|
214
|
+
use_uv = shutil.which("uv") is not None
|
|
215
|
+
|
|
216
|
+
target_python = python or sys.executable
|
|
217
|
+
|
|
218
|
+
cmd: list[str]
|
|
219
|
+
if use_uv:
|
|
220
|
+
cmd = ["uv", "pip", "install", "--python", target_python]
|
|
221
|
+
else:
|
|
222
|
+
cmd = [target_python, "-m", "pip", "install"]
|
|
223
|
+
|
|
224
|
+
if upgrade:
|
|
225
|
+
cmd.append("--upgrade")
|
|
226
|
+
if editable:
|
|
227
|
+
cmd.append("-e")
|
|
228
|
+
if extra_args:
|
|
229
|
+
cmd.extend(extra_args)
|
|
230
|
+
cmd.append(target)
|
|
231
|
+
|
|
232
|
+
return subprocess.run(cmd, capture_output=True, text=True)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
# ── Top-level install ──────────────────────────────────────────────────────
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
@dataclass
|
|
239
|
+
class InstallReport:
|
|
240
|
+
ok: bool
|
|
241
|
+
name: str | None
|
|
242
|
+
source_kind: str
|
|
243
|
+
pip_target: str
|
|
244
|
+
pip_returncode: int
|
|
245
|
+
pip_stdout: str
|
|
246
|
+
pip_stderr: str
|
|
247
|
+
sync_skills: dict[str, Any] | None = None
|
|
248
|
+
error_code: str | None = None
|
|
249
|
+
message: str = ""
|
|
250
|
+
|
|
251
|
+
def to_dict(self) -> dict[str, Any]:
|
|
252
|
+
return {
|
|
253
|
+
"ok": self.ok,
|
|
254
|
+
"name": self.name,
|
|
255
|
+
"source_kind": self.source_kind,
|
|
256
|
+
"pip_target": self.pip_target,
|
|
257
|
+
"pip_returncode": self.pip_returncode,
|
|
258
|
+
"pip_stdout": self.pip_stdout[-2000:], # cap for sanity
|
|
259
|
+
"pip_stderr": self.pip_stderr[-2000:],
|
|
260
|
+
"sync_skills": self.sync_skills,
|
|
261
|
+
"error_code": self.error_code,
|
|
262
|
+
"message": self.message,
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def install_plugin(
|
|
267
|
+
source: str,
|
|
268
|
+
*,
|
|
269
|
+
editable: bool = False,
|
|
270
|
+
upgrade: bool = False,
|
|
271
|
+
offline: bool = False,
|
|
272
|
+
sync_target: Path | None = None,
|
|
273
|
+
skip_sync: bool = False,
|
|
274
|
+
python: str | None = None,
|
|
275
|
+
) -> InstallReport:
|
|
276
|
+
"""High-level installer used by ``sim plugin install``.
|
|
277
|
+
|
|
278
|
+
Returns an InstallReport — never raises for normal failures (bad source,
|
|
279
|
+
pip non-zero, sync failure). Catches and reports cleanly so the CLI
|
|
280
|
+
layer can render either JSON or human output without try/except.
|
|
281
|
+
|
|
282
|
+
``python`` overrides the install-target interpreter. Defaults to
|
|
283
|
+
``sys.executable`` (the interpreter running ``sim``).
|
|
284
|
+
"""
|
|
285
|
+
try:
|
|
286
|
+
resolved = resolve_source(source, offline=offline)
|
|
287
|
+
except (ValueError, FileNotFoundError) as e:
|
|
288
|
+
return InstallReport(
|
|
289
|
+
ok=False, name=None, source_kind="invalid", pip_target=source,
|
|
290
|
+
pip_returncode=-1, pip_stdout="", pip_stderr="",
|
|
291
|
+
error_code="PLUGIN_NOT_FOUND",
|
|
292
|
+
message=str(e),
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
proc = _pip_install(
|
|
296
|
+
resolved.pip_target,
|
|
297
|
+
editable=editable, upgrade=upgrade, python=python,
|
|
298
|
+
)
|
|
299
|
+
ok = proc.returncode == 0
|
|
300
|
+
|
|
301
|
+
if not ok:
|
|
302
|
+
return InstallReport(
|
|
303
|
+
ok=False, name=resolved.name, source_kind=resolved.kind,
|
|
304
|
+
pip_target=resolved.pip_target,
|
|
305
|
+
pip_returncode=proc.returncode,
|
|
306
|
+
pip_stdout=proc.stdout, pip_stderr=proc.stderr,
|
|
307
|
+
error_code="PLUGIN_INSTALL_FAILED",
|
|
308
|
+
message=f"pip install returned {proc.returncode}",
|
|
309
|
+
)
|
|
310
|
+
|
|
311
|
+
sync_result: dict[str, Any] | None = None
|
|
312
|
+
if not skip_sync:
|
|
313
|
+
try:
|
|
314
|
+
from sim.plugins import sync_skills_to
|
|
315
|
+
target = sync_target or _default_skills_target()
|
|
316
|
+
sync_result = sync_skills_to(target)
|
|
317
|
+
except Exception as e: # noqa: BLE001 — sync is best-effort
|
|
318
|
+
sync_result = {"ok": False, "message": f"{type(e).__name__}: {e}"}
|
|
319
|
+
|
|
320
|
+
return InstallReport(
|
|
321
|
+
ok=True, name=resolved.name, source_kind=resolved.kind,
|
|
322
|
+
pip_target=resolved.pip_target,
|
|
323
|
+
pip_returncode=proc.returncode,
|
|
324
|
+
pip_stdout=proc.stdout, pip_stderr=proc.stderr,
|
|
325
|
+
sync_skills=sync_result,
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _default_skills_target() -> Path:
|
|
330
|
+
"""Where ``sync-skills`` writes by default.
|
|
331
|
+
|
|
332
|
+
Uses ``./.claude/skills/`` if a ``.claude`` dir exists in cwd; falls
|
|
333
|
+
back to ``~/.claude/skills/``. This matches Claude Code's discovery.
|
|
334
|
+
"""
|
|
335
|
+
project = Path.cwd() / ".claude"
|
|
336
|
+
if project.is_dir():
|
|
337
|
+
return project / "skills"
|
|
338
|
+
return Path.home() / ".claude" / "skills"
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
# ── Uninstall ───────────────────────────────────────────────────────────────
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def uninstall_plugin(name: str, *, sync: bool = True,
|
|
345
|
+
python: str | None = None) -> dict[str, Any]:
|
|
346
|
+
"""Best-effort plugin uninstall.
|
|
347
|
+
|
|
348
|
+
Tries the canonical PyPI distribution name (``sim-plugin-<name>``)
|
|
349
|
+
first, then falls back to whatever package the registry says owns
|
|
350
|
+
that driver. ``python`` pins the target interpreter (defaults to
|
|
351
|
+
``sys.executable``).
|
|
352
|
+
"""
|
|
353
|
+
from sim.plugins import list_installed_plugins
|
|
354
|
+
|
|
355
|
+
rows = {p.name: p for p in list_installed_plugins()}
|
|
356
|
+
if name not in rows:
|
|
357
|
+
return {"ok": False, "error_code": "PLUGIN_NOT_FOUND",
|
|
358
|
+
"message": f"unknown plugin: {name!r}"}
|
|
359
|
+
if rows[name].builtin:
|
|
360
|
+
return {"ok": False, "error_code": "PLUGIN_INSTALL_FAILED",
|
|
361
|
+
"message": "cannot uninstall a built-in driver — wait for v1.0 cut "
|
|
362
|
+
"or remove from sim-cli's _BUILTIN_REGISTRY."}
|
|
363
|
+
|
|
364
|
+
package = rows[name].package or f"sim-plugin-{name}"
|
|
365
|
+
target_python = python or sys.executable
|
|
366
|
+
use_uv = shutil.which("uv") is not None
|
|
367
|
+
cmd = (["uv", "pip", "uninstall", "--python", target_python, package] if use_uv
|
|
368
|
+
else [target_python, "-m", "pip", "uninstall", "-y", package])
|
|
369
|
+
proc = subprocess.run(cmd, capture_output=True, text=True)
|
|
370
|
+
|
|
371
|
+
if proc.returncode != 0:
|
|
372
|
+
return {"ok": False, "error_code": "PLUGIN_INSTALL_FAILED",
|
|
373
|
+
"message": f"pip uninstall returned {proc.returncode}",
|
|
374
|
+
"pip_stderr": proc.stderr[-1000:]}
|
|
375
|
+
|
|
376
|
+
# Remove the on-disk skill copy if present.
|
|
377
|
+
if sync:
|
|
378
|
+
target = _default_skills_target() / name
|
|
379
|
+
if target.is_symlink():
|
|
380
|
+
target.unlink()
|
|
381
|
+
elif target.is_dir():
|
|
382
|
+
shutil.rmtree(target)
|
|
383
|
+
return {"ok": True, "package": package, "name": name}
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
# ── Bundle ──────────────────────────────────────────────────────────────────
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def bundle_plugins(names: list[str], output_dir: Path, *,
|
|
390
|
+
index_url: str = DEFAULT_INDEX_URL) -> dict[str, Any]:
|
|
391
|
+
"""Download wheels for the named plugins into ``output_dir`` for offline use.
|
|
392
|
+
|
|
393
|
+
Produces ``<output_dir>/index.json`` filtered to just the bundled plugins,
|
|
394
|
+
rewritten with ``file://`` URLs so ``sim plugin install --offline
|
|
395
|
+
--from-dir <output_dir>`` works.
|
|
396
|
+
"""
|
|
397
|
+
output_dir = output_dir.expanduser().resolve()
|
|
398
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
399
|
+
|
|
400
|
+
idx = fetch_index(url=index_url)
|
|
401
|
+
by_name = {e["name"]: e for e in idx.get("plugins", [])}
|
|
402
|
+
|
|
403
|
+
fetched: list[dict[str, Any]] = []
|
|
404
|
+
errors: list[dict[str, Any]] = []
|
|
405
|
+
|
|
406
|
+
for name in names:
|
|
407
|
+
entry = by_name.get(name)
|
|
408
|
+
if entry is None:
|
|
409
|
+
errors.append({"name": name, "error": "not in index"})
|
|
410
|
+
continue
|
|
411
|
+
wheel_url = entry.get("latest_wheel_url")
|
|
412
|
+
if not wheel_url:
|
|
413
|
+
errors.append({"name": name, "error": "index entry has no latest_wheel_url"})
|
|
414
|
+
continue
|
|
415
|
+
wheel_basename = Path(wheel_url.split("?")[0]).name
|
|
416
|
+
dest = output_dir / wheel_basename
|
|
417
|
+
try:
|
|
418
|
+
with urllib.request.urlopen(wheel_url, timeout=30) as resp, dest.open("wb") as f:
|
|
419
|
+
shutil.copyfileobj(resp, f)
|
|
420
|
+
except Exception as e: # noqa: BLE001 — surface fetch errors
|
|
421
|
+
errors.append({"name": name, "error": f"download failed: {e}"})
|
|
422
|
+
continue
|
|
423
|
+
|
|
424
|
+
rewritten = dict(entry)
|
|
425
|
+
rewritten["latest_wheel_url"] = f"file://{dest}"
|
|
426
|
+
fetched.append(rewritten)
|
|
427
|
+
|
|
428
|
+
bundle_idx = {"schema_version": 1, "plugins": fetched}
|
|
429
|
+
(output_dir / "index.json").write_text(
|
|
430
|
+
json.dumps(bundle_idx, indent=2) + "\n", encoding="utf-8",
|
|
431
|
+
)
|
|
432
|
+
|
|
433
|
+
return {
|
|
434
|
+
"ok": not errors,
|
|
435
|
+
"output": str(output_dir),
|
|
436
|
+
"fetched": [e["name"] for e in fetched],
|
|
437
|
+
"errors": errors,
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
__all__ = [
|
|
442
|
+
"DEFAULT_INDEX_URL",
|
|
443
|
+
"ResolvedSource",
|
|
444
|
+
"InstallReport",
|
|
445
|
+
"fetch_index",
|
|
446
|
+
"index_entry",
|
|
447
|
+
"resolve_source",
|
|
448
|
+
"install_plugin",
|
|
449
|
+
"uninstall_plugin",
|
|
450
|
+
"bundle_plugins",
|
|
451
|
+
]
|
sim/_timeout.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Windows-safe per-call timeout helper.
|
|
2
|
+
|
|
3
|
+
Used by session driver runtimes (Fluent / COMSOL) to keep a hung
|
|
4
|
+
solver RPC from blocking the whole sim server.
|
|
5
|
+
|
|
6
|
+
Design constraints:
|
|
7
|
+
- Must work on Windows (no `signal.SIGALRM`).
|
|
8
|
+
- Cannot isolate via subprocess (would lose the live session's
|
|
9
|
+
in-process state — pyfluent holds an RPC client object,
|
|
10
|
+
COMSOL/JPype pins a JVM).
|
|
11
|
+
- Consequence: we can't *kill* a hung worker thread. We let it run
|
|
12
|
+
as daemon and return to the caller with a `hung=True` marker; the
|
|
13
|
+
caller is expected to tear down the session.
|
|
14
|
+
|
|
15
|
+
`timeout_s <= 0` (or None) means "no timeout enforced" — run to
|
|
16
|
+
completion. Default is 300s (5 min), generous enough for typical
|
|
17
|
+
iterate/solve calls but not infinite.
|
|
18
|
+
"""
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import threading
|
|
22
|
+
import time
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from typing import Any, Callable
|
|
25
|
+
|
|
26
|
+
DEFAULT_TIMEOUT_S: float = 300.0
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class TimeoutResult:
|
|
31
|
+
"""What `call_with_timeout` returns.
|
|
32
|
+
|
|
33
|
+
Attributes:
|
|
34
|
+
value: callable's return value (None on exception OR hang)
|
|
35
|
+
exception: the exception the callable raised, if any
|
|
36
|
+
hung: True iff we returned early because timeout fired
|
|
37
|
+
elapsed_s: wall-clock seconds spent inside the call (capped at
|
|
38
|
+
`timeout_s` when hung=True)
|
|
39
|
+
timeout_s: the timeout budget that was in effect
|
|
40
|
+
"""
|
|
41
|
+
value: Any = None
|
|
42
|
+
exception: BaseException | None = None
|
|
43
|
+
hung: bool = False
|
|
44
|
+
elapsed_s: float = 0.0
|
|
45
|
+
timeout_s: float = 0.0
|
|
46
|
+
|
|
47
|
+
def to_dict(self) -> dict:
|
|
48
|
+
if self.hung:
|
|
49
|
+
err = f"snippet exceeded timeout_s={self.timeout_s}"
|
|
50
|
+
elif self.exception is not None:
|
|
51
|
+
err = f"{type(self.exception).__name__}: {self.exception}"
|
|
52
|
+
else:
|
|
53
|
+
err = None
|
|
54
|
+
return {
|
|
55
|
+
"hung": self.hung,
|
|
56
|
+
"elapsed_s": round(self.elapsed_s, 3),
|
|
57
|
+
"timeout_s": self.timeout_s,
|
|
58
|
+
"error": err,
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def call_with_timeout(
|
|
63
|
+
fn: Callable[[], Any],
|
|
64
|
+
timeout_s: float | None = DEFAULT_TIMEOUT_S,
|
|
65
|
+
) -> TimeoutResult:
|
|
66
|
+
"""Run `fn()` in a daemon thread; return TimeoutResult.
|
|
67
|
+
|
|
68
|
+
If timeout_s is None/<=0, runs fn() inline with no timeout guarding.
|
|
69
|
+
|
|
70
|
+
On timeout, the worker thread is abandoned (kept as daemon so the
|
|
71
|
+
process can still exit). The caller MUST tear down the solver
|
|
72
|
+
session after hung=True — otherwise subsequent RPC calls on the
|
|
73
|
+
same session may deadlock.
|
|
74
|
+
"""
|
|
75
|
+
if timeout_s is None or timeout_s <= 0:
|
|
76
|
+
t0 = time.monotonic()
|
|
77
|
+
try:
|
|
78
|
+
value = fn()
|
|
79
|
+
return TimeoutResult(
|
|
80
|
+
value=value, hung=False,
|
|
81
|
+
elapsed_s=time.monotonic() - t0,
|
|
82
|
+
timeout_s=0.0,
|
|
83
|
+
)
|
|
84
|
+
except BaseException as exc:
|
|
85
|
+
return TimeoutResult(
|
|
86
|
+
exception=exc, hung=False,
|
|
87
|
+
elapsed_s=time.monotonic() - t0,
|
|
88
|
+
timeout_s=0.0,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
box: dict = {"value": None, "exc": None, "done": False}
|
|
92
|
+
|
|
93
|
+
def _worker():
|
|
94
|
+
try:
|
|
95
|
+
box["value"] = fn()
|
|
96
|
+
except BaseException as exc:
|
|
97
|
+
box["exc"] = exc
|
|
98
|
+
finally:
|
|
99
|
+
box["done"] = True
|
|
100
|
+
|
|
101
|
+
t0 = time.monotonic()
|
|
102
|
+
t = threading.Thread(target=_worker, daemon=True, name="sim.timeout.worker")
|
|
103
|
+
t.start()
|
|
104
|
+
t.join(timeout=timeout_s)
|
|
105
|
+
elapsed = time.monotonic() - t0
|
|
106
|
+
|
|
107
|
+
if not box["done"]:
|
|
108
|
+
return TimeoutResult(
|
|
109
|
+
value=None, exception=None, hung=True,
|
|
110
|
+
elapsed_s=elapsed, timeout_s=timeout_s,
|
|
111
|
+
)
|
|
112
|
+
return TimeoutResult(
|
|
113
|
+
value=box["value"], exception=box["exc"], hung=False,
|
|
114
|
+
elapsed_s=elapsed, timeout_s=timeout_s,
|
|
115
|
+
)
|