sim-cli-core 0.3.6__py3-none-any.whl → 0.3.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.
sim/__init__.py CHANGED
@@ -1,11 +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"
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 CHANGED
@@ -1,24 +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()
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 CHANGED
@@ -1,352 +1,172 @@
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
- * ``sim-plugin-<name>`` / ``sim-plugin-<name>==<version>`` — exact pip
10
- package spec.
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 and no plugin
17
- registry lookup. Then a single ``pip install`` invocation does the work.
18
- """
19
- from __future__ import annotations
20
-
21
- import re
22
- import shutil
23
- import subprocess
24
- import sys
25
- from dataclasses import dataclass, field
26
- from pathlib import Path
27
- from typing import Any
28
-
29
-
30
- # ── Source resolution ──────────────────────────────────────────────────────
31
-
32
-
33
- @dataclass(frozen=True)
34
- class ResolvedSource:
35
- """One install source classified into a canonical kind."""
36
- kind: str
37
- raw: str # the original argument
38
- name: str | None = None
39
- version: str | None = None
40
- pip_target: str = "" # what pip install gets handed
41
- extras: dict[str, Any] = field(default_factory=dict)
42
-
43
-
44
- _SHORT_NAME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*$")
45
- _SIM_PLUGIN_PACKAGE_RE = re.compile(
46
- r"^(sim-plugin-[A-Za-z0-9][A-Za-z0-9_.-]*)(?:\[[A-Za-z0-9_,.-]+\])?"
47
- r"(?:\s*(?:==|!=|~=|>=|<=|>|<)\s*[A-Za-z0-9.*+!_.-]+)?$"
48
- )
49
- _VERSION_PIN_RE = re.compile(r"(?:==|!=|~=|>=|<=|>|<)\s*(.+)$")
50
-
51
-
52
- def _short_name_error(name: str) -> str:
53
- return (
54
- f"{name!r} is not an explicit plugin install source. "
55
- "See https://github.com/svd-ai-lab/sim-plugin-index for a curated "
56
- "plugin list, or pass an explicit pip-installable source: a local "
57
- "wheel/sdist path, a direct wheel/sdist URL, a git URL, or a package "
58
- f"spec such as 'sim-plugin-{name}'."
59
- )
60
-
61
-
62
- def resolve_source(source: str, *, offline: bool = False,
63
- index_url: str | None = None) -> ResolvedSource:
64
- """Classify a source argument and choose what to hand to pip.
65
-
66
- ``offline`` and ``index_url`` are accepted for API compatibility but no
67
- longer affect resolution; this resolver never reads a plugin index or maps
68
- short names to ``sim-plugin-*`` package names.
69
- """
70
- s = source.strip()
71
- _ = (offline, index_url)
72
-
73
- # Local files / dirs first (cheapest to check).
74
- p = Path(s)
75
- if s.startswith(("./", "../", "/", "~")) or p.exists():
76
- target = p.expanduser().resolve()
77
- if target.is_file():
78
- if target.suffix == ".whl":
79
- return ResolvedSource(kind="local-wheel", raw=s, pip_target=str(target))
80
- if target.name.endswith(".tar.gz") or target.suffix == ".tar":
81
- return ResolvedSource(kind="local-sdist", raw=s, pip_target=str(target))
82
- return ResolvedSource(kind="local-file", raw=s, pip_target=str(target))
83
- if target.is_dir():
84
- return ResolvedSource(kind="local-dir", raw=s, pip_target=str(target))
85
- # Path doesn't exist on disk and doesn't look obviously remote — error.
86
- if s.startswith(("./", "../", "/", "~")):
87
- raise FileNotFoundError(f"local path does not exist: {s}")
88
-
89
- # URLs — direct wheel/sdist or git.
90
- if s.startswith("git+"):
91
- return ResolvedSource(kind="git-url", raw=s, pip_target=s)
92
- if s.startswith(("http://", "https://")):
93
- if s.endswith(".whl"):
94
- return ResolvedSource(kind="wheel-url", raw=s, pip_target=s)
95
- if s.endswith(".tar.gz") or s.endswith(".tar.bz2"):
96
- return ResolvedSource(kind="sdist-url", raw=s, pip_target=s)
97
- # Generic URL: treat as wheel-url and let pip complain.
98
- return ResolvedSource(kind="wheel-url", raw=s, pip_target=s)
99
-
100
- package_match = _SIM_PLUGIN_PACKAGE_RE.match(s)
101
- if package_match:
102
- version_match = _VERSION_PIN_RE.search(s)
103
- version = version_match.group(1).strip() if version_match else None
104
- return ResolvedSource(
105
- kind="package-spec",
106
- raw=s,
107
- name=package_match.group(1),
108
- version=version,
109
- pip_target=s,
110
- )
111
-
112
- if _SHORT_NAME_RE.match(s):
113
- raise ValueError(_short_name_error(s))
114
-
115
- raise ValueError(f"could not classify install source: {source!r}")
116
-
117
-
118
- # ── pip invocation ──────────────────────────────────────────────────────────
119
-
120
-
121
- def _pip_install(target: str, *, editable: bool = False, upgrade: bool = False,
122
- extra_args: list[str] | None = None,
123
- python: str | None = None) -> subprocess.CompletedProcess:
124
- """Run ``pip install`` (or ``uv pip install`` if uv is on PATH).
125
-
126
- ``python`` lets the caller pin which interpreter receives the install.
127
- Defaults to ``sys.executable`` (the interpreter running ``sim``), which
128
- is the right choice in 90% of cases. The canary verification proved
129
- that without an explicit pin, ``uv pip install`` resolves the active
130
- venv via ``$VIRTUAL_ENV`` / ``$CONDA_PREFIX`` / cwd discovery, which
131
- can target the *wrong* interpreter when the user's terminal has no
132
- venv activated.
133
- """
134
- use_uv = shutil.which("uv") is not None
135
-
136
- target_python = python or sys.executable
137
-
138
- cmd: list[str]
139
- if use_uv:
140
- cmd = ["uv", "pip", "install", "--python", target_python]
141
- else:
142
- cmd = [target_python, "-m", "pip", "install"]
143
-
144
- if upgrade:
145
- cmd.append("--upgrade")
146
- if editable:
147
- cmd.append("-e")
148
- if extra_args:
149
- cmd.extend(extra_args)
150
- cmd.append(target)
151
-
152
- return subprocess.run(cmd, capture_output=True, text=True)
153
-
154
-
155
- # ── Top-level install ──────────────────────────────────────────────────────
156
-
157
-
158
- @dataclass
159
- class InstallReport:
160
- ok: bool
161
- name: str | None
162
- source_kind: str
163
- pip_target: str
164
- pip_returncode: int
165
- pip_stdout: str
166
- pip_stderr: str
167
- sync_skills: dict[str, Any] | None = None
168
- error_code: str | None = None
169
- message: str = ""
170
-
171
- def to_dict(self) -> dict[str, Any]:
172
- return {
173
- "ok": self.ok,
174
- "name": self.name,
175
- "source_kind": self.source_kind,
176
- "pip_target": self.pip_target,
177
- "pip_returncode": self.pip_returncode,
178
- "pip_stdout": self.pip_stdout[-2000:], # cap for sanity
179
- "pip_stderr": self.pip_stderr[-2000:],
180
- "sync_skills": self.sync_skills,
181
- "error_code": self.error_code,
182
- "message": self.message,
183
- }
184
-
185
-
186
- def install_plugin(
187
- source: str,
188
- *,
189
- editable: bool = False,
190
- upgrade: bool = False,
191
- offline: bool = False,
192
- sync_target: Path | None = None,
193
- skip_sync: bool = False,
194
- python: str | None = None,
195
- extra_index_urls: list[str] | None = None,
196
- ) -> InstallReport:
197
- """High-level installer used by ``sim plugin install``.
198
-
199
- Returns an InstallReport — never raises for normal failures (bad source,
200
- pip non-zero, sync failure). Catches and reports cleanly so the CLI
201
- layer can render either JSON or human output without try/except.
202
-
203
- ``python`` overrides the install-target interpreter. Defaults to
204
- ``sys.executable`` (the interpreter running ``sim``).
205
- """
206
- try:
207
- resolved = resolve_source(source, offline=offline)
208
- except (ValueError, FileNotFoundError) as e:
209
- return InstallReport(
210
- ok=False, name=None, source_kind="invalid", pip_target=source,
211
- pip_returncode=-1, pip_stdout="", pip_stderr="",
212
- error_code="PLUGIN_NOT_FOUND",
213
- message=str(e),
214
- )
215
-
216
- extra_args: list[str] = []
217
- for extra_index_url in extra_index_urls or []:
218
- extra_args.extend(["--extra-index-url", extra_index_url])
219
-
220
- proc = _pip_install(
221
- resolved.pip_target,
222
- editable=editable,
223
- upgrade=upgrade,
224
- python=python,
225
- extra_args=extra_args or None,
226
- )
227
- ok = proc.returncode == 0
228
-
229
- if not ok:
230
- return InstallReport(
231
- ok=False, name=resolved.name, source_kind=resolved.kind,
232
- pip_target=resolved.pip_target,
233
- pip_returncode=proc.returncode,
234
- pip_stdout=proc.stdout, pip_stderr=proc.stderr,
235
- error_code="PLUGIN_INSTALL_FAILED",
236
- message=f"pip install returned {proc.returncode}",
237
- )
238
-
239
- sync_result: dict[str, Any] | None = None
240
- if not skip_sync:
241
- try:
242
- from sim.plugins import sync_skills_to
243
- target = sync_target or _default_skills_target()
244
- sync_result = sync_skills_to(target)
245
- except Exception as e: # noqa: BLE001 — sync is best-effort
246
- sync_result = {"ok": False, "message": f"{type(e).__name__}: {e}"}
247
-
248
- return InstallReport(
249
- ok=True, name=resolved.name, source_kind=resolved.kind,
250
- pip_target=resolved.pip_target,
251
- pip_returncode=proc.returncode,
252
- pip_stdout=proc.stdout, pip_stderr=proc.stderr,
253
- sync_skills=sync_result,
254
- )
255
-
256
-
257
- def _default_skills_target() -> Path:
258
- """Where ``sync-skills`` writes by default.
259
-
260
- Uses ``./.claude/skills/`` if a ``.claude`` dir exists in cwd; falls
261
- back to ``~/.claude/skills/``. This matches Claude Code's discovery.
262
- """
263
- project = Path.cwd() / ".claude"
264
- if project.is_dir():
265
- return project / "skills"
266
- return Path.home() / ".claude" / "skills"
267
-
268
-
269
- # ── Uninstall ───────────────────────────────────────────────────────────────
270
-
271
-
272
- def uninstall_plugin(name: str, *, sync: bool = True,
273
- python: str | None = None) -> dict[str, Any]:
274
- """Best-effort plugin uninstall.
275
-
276
- Tries the canonical PyPI distribution name (``sim-plugin-<name>``)
277
- first, then falls back to whatever package the registry says owns
278
- that driver. ``python`` pins the target interpreter (defaults to
279
- ``sys.executable``).
280
- """
281
- from sim.plugins import list_installed_plugins
282
-
283
- rows = {p.name: p for p in list_installed_plugins()}
284
- if name not in rows:
285
- return {"ok": False, "error_code": "PLUGIN_NOT_FOUND",
286
- "message": f"unknown plugin: {name!r}"}
287
- if rows[name].builtin:
288
- return {"ok": False, "error_code": "PLUGIN_INSTALL_FAILED",
289
- "message": "cannot uninstall a built-in driver — wait for v1.0 cut "
290
- "or remove from sim-cli's _BUILTIN_REGISTRY."}
291
-
292
- package = rows[name].package or f"sim-plugin-{name}"
293
- target_python = python or sys.executable
294
- use_uv = shutil.which("uv") is not None
295
- cmd = (["uv", "pip", "uninstall", "--python", target_python, package] if use_uv
296
- else [target_python, "-m", "pip", "uninstall", "-y", package])
297
- proc = subprocess.run(cmd, capture_output=True, text=True)
298
-
299
- if proc.returncode != 0:
300
- return {"ok": False, "error_code": "PLUGIN_INSTALL_FAILED",
301
- "message": f"pip uninstall returned {proc.returncode}",
302
- "pip_stderr": proc.stderr[-1000:]}
303
-
304
- # Remove the on-disk skill copy if present.
305
- if sync:
306
- target = _default_skills_target() / name
307
- if target.is_symlink():
308
- target.unlink()
309
- elif target.is_dir():
310
- shutil.rmtree(target)
311
- return {"ok": True, "package": package, "name": name}
312
-
313
-
314
- # ── Bundle ──────────────────────────────────────────────────────────────────
315
-
316
-
317
- def bundle_plugins(names: list[str], output_dir: Path, *,
318
- index_url: str | None = None) -> dict[str, Any]:
319
- """The install-resolver-backed bundle flow was removed.
320
-
321
- See https://github.com/svd-ai-lab/sim-plugin-index for a curated plugin
322
- list, then download explicit wheel URLs or install exact package specs.
323
- There is no install-time resolver to map short names to wheels.
324
- """
325
- _ = (names, output_dir, index_url)
326
- return {
327
- "ok": False,
328
- "output": str(output_dir),
329
- "fetched": [],
330
- "errors": [
331
- {
332
- "name": name,
333
- "error": (
334
- "bundle no longer resolves short plugin names; see "
335
- "https://github.com/svd-ai-lab/sim-plugin-index for a "
336
- "curated plugin list, then pass explicit wheel URLs, "
337
- "local artifacts, git URLs, or exact package specs"
338
- ),
339
- }
340
- for name in names
341
- ],
342
- }
343
-
344
-
345
- __all__ = [
346
- "ResolvedSource",
347
- "InstallReport",
348
- "resolve_source",
349
- "install_plugin",
350
- "uninstall_plugin",
351
- "bundle_plugins",
352
- ]
1
+ """Migration shims for retired plugin installer commands.
2
+
3
+ ``sim`` no longer installs or uninstalls plugin packages. Package mutation
4
+ belongs to the user's uv project; sim inspects installed packages, checks
5
+ drivers, and syncs bundled skills.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+
15
+ _PACKAGE_SPEC_RE = re.compile(
16
+ r"^(sim-plugin-[A-Za-z0-9][A-Za-z0-9_.-]*)(?:\[[A-Za-z0-9_,.-]+\])?"
17
+ r"(?:\s*(?:==|!=|~=|>=|<=|>|<)\s*[A-Za-z0-9.*+!_.-]+)?$"
18
+ )
19
+ _SHORT_NAME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*$")
20
+
21
+
22
+ def _install_migration_message(source: str | None = None) -> str:
23
+ base = (
24
+ "sim plugin install is retired.\n\n"
25
+ "Add plugins with uv instead:\n"
26
+ " uv add sim-cli-core <plugin-package-spec>\n"
27
+ " uv run sim plugin sync-skills --target .agents/skills --copy\n"
28
+ " uv run sim check <solver>"
29
+ )
30
+
31
+ if source:
32
+ match = _PACKAGE_SPEC_RE.match(source.strip())
33
+ if match:
34
+ return (
35
+ f"{base}\n\n"
36
+ f"For this package spec, run:\n"
37
+ f" uv add sim-cli-core {source.strip()}"
38
+ )
39
+ if _SHORT_NAME_RE.match(source.strip()):
40
+ return (
41
+ f"{base}\n\n"
42
+ "Short solver names are not package specs. Find the package spec in "
43
+ "docs.svdailab.com/plugin-index or sim-plugin-index, then run:\n"
44
+ " uv add sim-cli-core <plugin-package-spec>"
45
+ )
46
+
47
+ return base
48
+
49
+
50
+ def _uninstall_migration_message(name: str | None = None) -> str:
51
+ package = None
52
+ if name:
53
+ clean = name.strip()
54
+ package = clean if clean.startswith("sim-plugin-") else f"sim-plugin-{clean}"
55
+ command = f" uv remove {package}" if package else " uv remove <plugin-package-spec>"
56
+ return (
57
+ "sim plugin uninstall is retired.\n\n"
58
+ "Remove plugin packages with uv instead:\n"
59
+ f"{command}\n"
60
+ " uv run sim plugin sync-skills --target .agents/skills --copy"
61
+ )
62
+
63
+
64
+ @dataclass
65
+ class InstallReport:
66
+ ok: bool
67
+ name: str | None
68
+ source_kind: str
69
+ pip_target: str
70
+ pip_returncode: int
71
+ pip_stdout: str
72
+ pip_stderr: str
73
+ sync_skills: dict[str, Any] | None = None
74
+ error_code: str | None = None
75
+ message: str = ""
76
+
77
+ def to_dict(self) -> dict[str, Any]:
78
+ return {
79
+ "ok": self.ok,
80
+ "name": self.name,
81
+ "source_kind": self.source_kind,
82
+ "pip_target": self.pip_target,
83
+ "pip_returncode": self.pip_returncode,
84
+ "pip_stdout": self.pip_stdout[-2000:],
85
+ "pip_stderr": self.pip_stderr[-2000:],
86
+ "sync_skills": self.sync_skills,
87
+ "error_code": self.error_code,
88
+ "message": self.message,
89
+ }
90
+
91
+
92
+ def install_plugin(
93
+ source: str,
94
+ *,
95
+ editable: bool = False,
96
+ upgrade: bool = False,
97
+ offline: bool = False,
98
+ sync_target: Path | None = None,
99
+ skip_sync: bool = False,
100
+ python: str | None = None,
101
+ extra_index_urls: list[str] | None = None,
102
+ ) -> InstallReport:
103
+ """Return migration guidance without invoking pip or uv pip."""
104
+ _ = (editable, upgrade, offline, sync_target, skip_sync, python, extra_index_urls)
105
+ match = _PACKAGE_SPEC_RE.match(source.strip())
106
+ return InstallReport(
107
+ ok=False,
108
+ name=match.group(1) if match else None,
109
+ source_kind="retired",
110
+ pip_target=source,
111
+ pip_returncode=-1,
112
+ pip_stdout="",
113
+ pip_stderr="",
114
+ error_code="PLUGIN_INSTALL_RETIRED",
115
+ message=_install_migration_message(source),
116
+ )
117
+
118
+
119
+ def _default_skills_target() -> Path:
120
+ """Where ``sync-skills`` writes by default.
121
+
122
+ Uses ``./.claude/skills/`` if a ``.claude`` dir exists in cwd; falls
123
+ back to ``~/.claude/skills/``. This matches Claude Code's discovery.
124
+ """
125
+ project = Path.cwd() / ".claude"
126
+ if project.is_dir():
127
+ return project / "skills"
128
+ return Path.home() / ".claude" / "skills"
129
+
130
+
131
+ def uninstall_plugin(name: str, *, sync: bool = True,
132
+ python: str | None = None) -> dict[str, Any]:
133
+ """Return migration guidance without invoking pip or uv pip."""
134
+ _ = (sync, python)
135
+ return {
136
+ "ok": False,
137
+ "name": name,
138
+ "error_code": "PLUGIN_INSTALL_RETIRED",
139
+ "message": _uninstall_migration_message(name),
140
+ }
141
+
142
+
143
+ def bundle_plugins(names: list[str], output_dir: Path, *,
144
+ index_url: str | None = None) -> dict[str, Any]:
145
+ """Return migration guidance for the removed bundle flow."""
146
+ _ = index_url
147
+ return {
148
+ "ok": False,
149
+ "output": str(output_dir),
150
+ "fetched": [],
151
+ "errors": [
152
+ {
153
+ "name": name,
154
+ "error_code": "PLUGIN_INSTALL_RETIRED",
155
+ "error": (
156
+ "sim plugin bundle is retired. Add plugin packages with "
157
+ "uv add sim-cli-core <plugin-package-spec> in the target "
158
+ "uv project instead."
159
+ ),
160
+ }
161
+ for name in names
162
+ ],
163
+ }
164
+
165
+
166
+ __all__ = [
167
+ "InstallReport",
168
+ "install_plugin",
169
+ "uninstall_plugin",
170
+ "bundle_plugins",
171
+ "_default_skills_target",
172
+ ]