sim-cli-core 0.2.4__py3-none-any.whl → 0.3.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.
sim/drivers/__init__.py CHANGED
@@ -35,21 +35,15 @@ log = logging.getLogger(__name__)
35
35
  _ENTRY_POINT_GROUP = "sim.drivers"
36
36
 
37
37
 
38
+ # Pure-plugin architecture (Phase 3b, 2026-04-28): every driver — including
39
+ # the historical canaries openfoam and coolprop — ships as an out-of-tree
40
+ # `sim-plugin-<name>` package, discovered via the `sim.drivers` entry-point
41
+ # group below. The built-in registry is intentionally empty; sim-cli core
42
+ # carries no solver-specific code or dependencies.
43
+ #
38
44
  # (driver_name, "module:Class") — order controls `solvers list` output order
39
- # and `lint` first-match priority.
40
- _BUILTIN_REGISTRY: list[tuple[str, str]] = [
41
- # openfoam: Phase 3a plugin-extraction canary (2026-04-28). Held as the
42
- # soak safety net while sim-plugin-openfoam ships the external counter-
43
- # part. Earlier "has a real session implementation, not a drop-in
44
- # extraction candidate" framing was wrong — the driver is a generic
45
- # HTTP client over sim-server's normal endpoints, structurally identical
46
- # to coolprop. Empty-registry cut tracked in svd-ai-lab/sim-proj#69.
47
- ("openfoam", "sim.drivers.openfoam:OpenFOAMDriver"),
48
- # coolprop: Phase 1 plugin-extraction canary. Held in the registry as
49
- # the safety net during the 1-week soak; sim-plugin-coolprop ships the
50
- # external counterpart. Removal lands in a follow-up PR after soak.
51
- ("coolprop", "sim.drivers.coolprop:CoolPropDriver"),
52
- ]
45
+ # and `lint` first-match priority. Externals from entry_points are appended.
46
+ _BUILTIN_REGISTRY: list[tuple[str, str]] = []
53
47
 
54
48
 
55
49
  def _is_valid_spec(spec: str) -> bool:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sim-cli-core
3
- Version: 0.2.4
3
+ Version: 0.3.0
4
4
  Summary: Make every engineering tool agent-native — a CLI runtime that lets LLM agents launch, drive, and observe CAD/CAE software
5
5
  Project-URL: Homepage, https://github.com/svd-ai-lab/sim-cli
6
6
  Project-URL: Repository, https://github.com/svd-ai-lab/sim-cli
@@ -11,7 +11,7 @@ Author-email: Weiqi Ji <jiweiqi10@gmail.com>
11
11
  License-Expression: Apache-2.0
12
12
  License-File: LICENSE
13
13
  License-File: NOTICE
14
- Keywords: agent,agentic,cad,cae,cfd,coolprop,fea,llm,openfoam,simulation
14
+ Keywords: agent,agentic,cad,cae,cfd,fea,llm,out-of-tree,plugins,simulation
15
15
  Classifier: Development Status :: 3 - Alpha
16
16
  Classifier: Intended Audience :: Developers
17
17
  Classifier: Intended Audience :: Science/Research
@@ -36,8 +36,6 @@ Requires-Dist: uvicorn>=0.34
36
36
  Provides-Extra: dev
37
37
  Requires-Dist: pytest>=8.0; extra == 'dev'
38
38
  Requires-Dist: ruff>=0.4; extra == 'dev'
39
- Provides-Extra: pybamm
40
- Requires-Dist: pybamm>=24.0; extra == 'pybamm'
41
39
  Description-Content-Type: text/markdown
42
40
 
43
41
  <div align="center">
@@ -158,7 +156,7 @@ That's the full loop: **detect → bootstrap → launch → drive → observe
158
156
 
159
157
  ## 🧪 Solver registry
160
158
 
161
- `sim-cli` core is **solver-agnostic** — it ships with one OSS driver as a built-in (`openfoam`), and every other solver is reached through an **out-of-tree plugin package** registered via the `sim.drivers` entry-point group. Adding a new backend is a ~200-LOC `DriverProtocol` implementation in its own `sim-plugin-<name>` repo.
159
+ `sim-cli` core is **fully solver-agnostic** — it ships with **zero built-in drivers**. Every solver, including OpenFOAM, is reached through an **out-of-tree plugin package** registered via the `sim.drivers` entry-point group. Adding a new backend is a ~200-LOC `DriverProtocol` implementation in its own `sim-plugin-<name>` repo.
162
160
 
163
161
  Plugin coverage spans CFD, multiphysics, electronics thermal, implicit and explicit structural FEA, pre/post-processing, mesh generation, embodied-AI / GPU physics, molecular dynamics, optimization / MDAO, battery modeling, thermo properties, power-systems and RF simulation, and discrete-event modeling. Browse the curated index:
164
162
 
@@ -169,6 +167,13 @@ sim plugin install <name> # e.g. sim plugin install ltspice
169
167
 
170
168
  The index is served from [`sim-plugin-index`](https://github.com/svd-ai-lab/sim-plugin-index); reference plugins to read for shape: [`sim-plugin-coolprop`](https://github.com/svd-ai-lab/sim-plugin-coolprop) (one-shot, no SDK gate), [`sim-plugin-ltspice`](https://github.com/svd-ai-lab/sim-plugin-ltspice) (one-shot with vendor binary), [`sim-plugin-pybamm`](https://github.com/svd-ai-lab/sim-plugin-pybamm) (heavy SDK).
171
169
 
170
+ **Private plugins** (vendor-IP-sensitive backends not in the public index) install directly by URL — same `sim plugin install` flow:
171
+
172
+ ```bash
173
+ sim plugin install git+https://github.com/<org>/sim-plugin-<name>
174
+ # (you need read-access to the repo; without it, git clone returns 401)
175
+ ```
176
+
172
177
  Per-solver protocols, snippets, and demo workflows live in [`sim-skills`](https://github.com/svd-ai-lab/sim-skills) and the per-plugin repos.
173
178
 
174
179
  ---
@@ -13,21 +13,16 @@ sim/plugins.py,sha256=bzBgKKruMwzC2lWVoH49K-J0ksc6Nv7l4RAcTOW2vbA,17554
13
13
  sim/runner.py,sha256=QGT9wAfN7mrO1n7BSn1x49c7kerSCXLscyJ2dCwZCOo,6641
14
14
  sim/server.py,sha256=O7Zkojlbn-W8NavXitvuZmj4V4VqJg9NlReptQp17mw,18592
15
15
  sim/session.py,sha256=XYA_MbAkgPT_-g3NHTyaYwgwvjhjo5QSEIWrtxK2G7o,8228
16
- sim/drivers/__init__.py,sha256=Y_ZUbKW70mO08ts1Oul0zL9qEY0vxBgxC2WK5rkf2tA,6203
17
- sim/drivers/coolprop/__init__.py,sha256=KQORHEBEGrsBY61NTV0E_-t-nL20GlcWSYY4iLHPTik,65
18
- sim/drivers/coolprop/driver.py,sha256=Ar0irDwCZqovyCUvsG21y_MWcR3jEEogziJzUROSIg8,6306
19
- sim/drivers/openfoam/__init__.py,sha256=mDaqEoon0RkAxxFBOA44hejB9W0Dj15F23NxHEtWIrY,152
20
- sim/drivers/openfoam/compatibility.yaml,sha256=GUQY9DdLfIDZIXn3T6SIyk5G4IL48eyb3vO1FtKHm1k,1312
21
- sim/drivers/openfoam/driver.py,sha256=v_CArZ-zeYncbVBrE_wd_WvxrzLrx8tpFAxX3L_Ngec,15486
16
+ sim/drivers/__init__.py,sha256=_azo1aQDJgYPJ70INn3sQ4Z3whXlKAj6_PZVxbZlQ14,5820
22
17
  sim/gui/__init__.py,sha256=464_Dy-Un-arkWkRFP1T2IR2sf1O4bMRiZYVgzE_dyg,8446
23
18
  sim/gui/_pywinauto_tools.py,sha256=dsBPf1tTpc2LBcZDO9_szwfu_F8Vjel9sdVh0iGcdkc,16949
24
19
  sim/gui/_win32_dialog.py,sha256=4hErvQxY4SwW_fTpX3FTUxhugkRYpkTRdBiBDu9_1DE,4731
25
20
  sim/gui/LICENSES/ATTRIBUTION.md,sha256=X5EdZV0Gt0FdG9FpeCZ-22I3cqRg9SmoQt-86DqCBak,1150
26
21
  sim/testing/__init__.py,sha256=iGwbSfJucKuhNLOiDnUmQCBlkhukWyp7cj89YDhoEOk,855
27
22
  sim/testing/protocol_conformance.py,sha256=q0r7QgPoAyU-eMqN4fJWx0XZv8YNolGghu9-zDC8bls,9867
28
- sim_cli_core-0.2.4.dist-info/METADATA,sha256=pJBJpEnzo96IFo22XB4O7Irfi5Uehzyd2r9TtNcGrxo,16465
29
- sim_cli_core-0.2.4.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
30
- sim_cli_core-0.2.4.dist-info/entry_points.txt,sha256=hpg7D0fRhpgmo1IyN35XQPoyIZRSw7SLNG7tW0eacGA,37
31
- sim_cli_core-0.2.4.dist-info/licenses/LICENSE,sha256=7toF0XzHlqSXvTlZ8W77R6pg2ilzKN73EOG0SioX7wQ,10762
32
- sim_cli_core-0.2.4.dist-info/licenses/NOTICE,sha256=IpKSNJwFq360Dy4be4dJ3wtNJ9BmjgcpxiYWUW4uoTs,3721
33
- sim_cli_core-0.2.4.dist-info/RECORD,,
23
+ sim_cli_core-0.3.0.dist-info/METADATA,sha256=3Av09vdIVbqbMoItPm3HSyR4b8lrFsOHpwwSenYZlhs,16685
24
+ sim_cli_core-0.3.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
25
+ sim_cli_core-0.3.0.dist-info/entry_points.txt,sha256=hpg7D0fRhpgmo1IyN35XQPoyIZRSw7SLNG7tW0eacGA,37
26
+ sim_cli_core-0.3.0.dist-info/licenses/LICENSE,sha256=7toF0XzHlqSXvTlZ8W77R6pg2ilzKN73EOG0SioX7wQ,10762
27
+ sim_cli_core-0.3.0.dist-info/licenses/NOTICE,sha256=IpKSNJwFq360Dy4be4dJ3wtNJ9BmjgcpxiYWUW4uoTs,3721
28
+ sim_cli_core-0.3.0.dist-info/RECORD,,
@@ -1,3 +0,0 @@
1
- from .driver import CoolPropDriver
2
-
3
- __all__ = ["CoolPropDriver"]
@@ -1,183 +0,0 @@
1
- """CoolProp driver for sim.
2
-
3
- CoolProp is an open-source thermophysical-property database (Bell et al.,
4
- Fundamentals of CoolProp, IECR 2014). REFPROP-equivalent for ~120 pure
5
- fluids and humid-air psychrometrics. Pip-installable
6
- (`pip install CoolProp`); ships compiled C++ kernel + Python bindings.
7
-
8
- Scripts are plain `.py`:
9
- from CoolProp.CoolProp import PropsSI
10
- h = PropsSI('H', 'T', 300, 'P', 101325, 'Water')
11
- T_sat = PropsSI('T', 'P', 101325, 'Q', 0, 'Water') # at 1 atm
12
- """
13
- from __future__ import annotations
14
-
15
- import ast
16
- import json
17
- import re
18
- import shutil
19
- import subprocess
20
- import sys
21
- from pathlib import Path
22
-
23
- from sim.driver import ConnectionInfo, Diagnostic, LintResult, SolverInstall
24
- from sim.runner import run_subprocess
25
-
26
-
27
- _IMPORT_RE = re.compile(
28
- r"^\s*(import\s+CoolProp|from\s+CoolProp\b)", re.MULTILINE,
29
- )
30
- _USAGE_RE = re.compile(
31
- r"\b(PropsSI|HAPropsSI|AbstractState|PhaseSI|generate_update_pair)\b",
32
- )
33
-
34
-
35
- def _probe_python_for_coolprop(python_exe: Path) -> str | None:
36
- if not python_exe.is_file():
37
- return None
38
- try:
39
- proc = subprocess.run(
40
- [str(python_exe), "-c", "import CoolProp; print(CoolProp.__version__)"],
41
- capture_output=True, text=True, timeout=20,
42
- )
43
- except (subprocess.TimeoutExpired, OSError):
44
- return None
45
- if proc.returncode != 0:
46
- return None
47
- v = (proc.stdout or "").strip()
48
- return v or None
49
-
50
-
51
- class CoolPropDriver:
52
- """Sim driver for CoolProp (thermophysical properties)."""
53
-
54
- @property
55
- def name(self) -> str:
56
- return "coolprop"
57
-
58
- @property
59
- def supports_session(self) -> bool:
60
- return False
61
-
62
- def detect(self, script: Path) -> bool:
63
- try:
64
- if script.suffix.lower() != ".py":
65
- return False
66
- text = script.read_text(encoding="utf-8", errors="replace")
67
- return bool(_IMPORT_RE.search(text))
68
- except (OSError, UnicodeDecodeError):
69
- return False
70
-
71
- def lint(self, script: Path) -> LintResult:
72
- diagnostics: list[Diagnostic] = []
73
- if script.suffix.lower() != ".py":
74
- return LintResult(
75
- ok=False,
76
- diagnostics=[Diagnostic(
77
- level="error",
78
- message=f"Unsupported file type: {script.suffix} (expected .py)",
79
- )],
80
- )
81
- try:
82
- text = script.read_text(encoding="utf-8", errors="replace")
83
- except OSError as e:
84
- return LintResult(
85
- ok=False,
86
- diagnostics=[Diagnostic(level="error", message=f"Cannot read: {e}")],
87
- )
88
-
89
- if not _IMPORT_RE.search(text):
90
- diagnostics.append(Diagnostic(
91
- level="error", message="No `import CoolProp` / `from CoolProp` found",
92
- ))
93
-
94
- try:
95
- ast.parse(text)
96
- except SyntaxError as e:
97
- diagnostics.append(Diagnostic(
98
- level="error", message=f"Syntax error: {e}", line=e.lineno,
99
- ))
100
-
101
- if _IMPORT_RE.search(text) and not _USAGE_RE.search(text):
102
- diagnostics.append(Diagnostic(
103
- level="warning",
104
- message=(
105
- "No PropsSI / HAPropsSI / AbstractState / PhaseSI call — "
106
- "script may not do anything"
107
- ),
108
- ))
109
-
110
- ok = not any(d.level == "error" for d in diagnostics)
111
- return LintResult(ok=ok, diagnostics=diagnostics)
112
-
113
- def connect(self) -> ConnectionInfo:
114
- installs = self.detect_installed()
115
- if not installs:
116
- return ConnectionInfo(
117
- solver="coolprop", version=None, status="not_installed",
118
- message="CoolProp not importable from any known Python env",
119
- )
120
- top = installs[0]
121
- return ConnectionInfo(
122
- solver="coolprop", version=top.version, status="ok",
123
- message=f"CoolProp {top.version} in {top.path}",
124
- solver_version=top.version,
125
- )
126
-
127
- def detect_installed(self) -> list[SolverInstall]:
128
- found: dict[str, SolverInstall] = {}
129
-
130
- def _record(python: Path, source: str) -> None:
131
- ver = _probe_python_for_coolprop(python)
132
- if ver is None:
133
- return
134
- key = str(python.resolve())
135
- if key in found:
136
- return
137
- short = ".".join(ver.split(".")[:2])
138
- found[key] = SolverInstall(
139
- name="coolprop", version=short,
140
- path=str(python.parent), source=source,
141
- extra={"raw_version": ver, "python": str(python)},
142
- )
143
-
144
- _record(Path(sys.executable), "sys.executable")
145
- for name in ("python3", "python"):
146
- p = shutil.which(name)
147
- if p:
148
- _record(Path(p), f"which:{name}")
149
- return sorted(found.values(), key=lambda i: i.version, reverse=True)
150
-
151
- def parse_output(self, stdout: str) -> dict:
152
- for line in reversed(stdout.strip().splitlines()):
153
- line = line.strip()
154
- if line.startswith("{"):
155
- try:
156
- return json.loads(line)
157
- except json.JSONDecodeError:
158
- continue
159
- return {}
160
-
161
- def run_file(self, script: Path):
162
- if script.suffix.lower() != ".py":
163
- raise RuntimeError(
164
- f"coolprop driver only accepts .py scripts (got {script.suffix})"
165
- )
166
- installs = self.detect_installed()
167
- if not installs:
168
- raise RuntimeError("CoolProp is not installed in any known Python env")
169
- python_exe = installs[0].extra.get("python", sys.executable)
170
- return run_subprocess(
171
- [python_exe, str(script)], script=script, solver=self.name,
172
- )
173
-
174
- # Session lifecycle stubs — CoolProp is one-shot, but DriverProtocol is
175
- # runtime_checkable so every method must exist. See `sim.driver`.
176
- def launch(self, **kwargs) -> dict:
177
- raise NotImplementedError("coolprop driver does not support sessions")
178
-
179
- def run(self, code: str, label: str = "") -> dict:
180
- raise NotImplementedError("coolprop driver does not support sessions")
181
-
182
- def disconnect(self) -> dict:
183
- return {"ok": True, "disconnected": True}
@@ -1,4 +0,0 @@
1
- """OpenFOAM driver for sim — remote execution via sim-server."""
2
- from sim.drivers.openfoam.driver import OpenFOAMDriver
3
-
4
- __all__ = ["OpenFOAMDriver"]
@@ -1,37 +0,0 @@
1
- # sim-cli — OpenFOAM driver compatibility matrix.
2
- #
3
- # OpenFOAM has no Python binding. The "SDK" is the OpenFOAM bashrc itself
4
- # — the inline OpenFOAMDriver sources it and shells out to solver binaries
5
- # (blockMesh, simpleFoam, pisoFoam, …).
6
- #
7
- # Detection inputs (see driver.py detect_installed):
8
- # - WM_PROJECT_DIR / WM_PROJECT_VERSION env vars (set by etc/bashrc)
9
- # - /opt/openfoam* /usr/lib/openfoam* ~/OpenFOAM/OpenFOAM-* defaults
10
- # - which simpleFoam (PATH probe as last resort)
11
- #
12
- # Version normalization: ESI releases are "v2312" / "v2406" — we strip the
13
- # leading "v" and use the YYMM short form ("23.12", "24.06") so the same
14
- # resolver helper that handles Ansys "25.2" can match these too.
15
-
16
- driver: openfoam
17
- # (no sdk_package — OpenFOAM has no Python binding)
18
-
19
- profiles:
20
-
21
- - name: openfoam_v2406
22
- solver_versions: ["24.06", "v2406"]
23
- active_solver_layer: "v2406"
24
- notes: |
25
- ESI OpenFOAM v2406 (June 2024). Latest stable at time of writing.
26
-
27
- - name: openfoam_v2312
28
- solver_versions: ["23.12", "v2312"]
29
- active_solver_layer: "v2312"
30
- notes: |
31
- ESI OpenFOAM v2312 (December 2023).
32
-
33
- - name: openfoam_v2206
34
- solver_versions: ["22.06", "v2206"]
35
- active_solver_layer: "v2206"
36
- notes: |
37
- ESI OpenFOAM v2206. Older but still common in production.
@@ -1,432 +0,0 @@
1
- """OpenFOAM driver for sim.
2
-
3
- OpenFOAM runs on a remote Linux machine. This driver communicates with
4
- it via sim-server (HTTP). No local OpenFOAM installation needed.
5
-
6
- Two execution models:
7
-
8
- Phase 1 — One-shot local:
9
- run_file(script) executes a Python script locally via subprocess.
10
- Only useful if OpenFOAM is installed on the same machine.
11
-
12
- Phase 2 — Remote session via sim-server:
13
- launch(host, port) → POST /connect {solver: "openfoam"}
14
- run(code, label) → POST /exec {code, label}
15
- query(name) → GET /inspect/<name>
16
- disconnect() → POST /disconnect
17
-
18
- The ``#!openfoam`` shebang in code sent to /exec triggers shell-mode
19
- execution on the remote server — the code is run as a bash script
20
- with the OpenFOAM environment sourced, not as Python.
21
- """
22
- from __future__ import annotations
23
-
24
- import ast
25
- import json
26
- import re
27
- import sys
28
- import time
29
- import uuid
30
- from datetime import datetime, timezone
31
- from pathlib import Path
32
-
33
- import httpx
34
-
35
- from sim.driver import ConnectionInfo, Diagnostic, LintResult, RunResult, SolverInstall
36
-
37
-
38
- # ---------------------------------------------------------------------------
39
- # Detection helpers (for local OpenFOAM, if present)
40
- # ---------------------------------------------------------------------------
41
-
42
- def _openfoam_version_from_path(install_dir: Path) -> str | None:
43
- """Extract a normalized OpenFOAM version from an install dir name.
44
-
45
- Examples:
46
- /opt/openfoam-v2406 -> "v2406"
47
- /opt/openfoam2312 -> "v2312"
48
- /usr/lib/openfoam/openfoam-v2206 -> "v2206"
49
- ~/OpenFOAM/OpenFOAM-11 -> "11"
50
- """
51
- name = install_dir.name.lower()
52
- m = re.search(r"v?(\d{4})", name)
53
- if m:
54
- return f"v{m.group(1)}"
55
- m = re.search(r"openfoam-(\d+)$", name)
56
- if m:
57
- return m.group(1)
58
- return None
59
-
60
-
61
- _OPENFOAM_PATTERNS = re.compile(
62
- r"(#\s*openfoam|#!openfoam|blockMesh|simpleFoam|icoFoam|pisoFoam"
63
- r"|snappyHexMesh|OpenFOAMCase|foam\.run_command|foam\.solve)",
64
- re.IGNORECASE,
65
- )
66
-
67
-
68
- class OpenFOAMDriver:
69
- """Sim driver for OpenFOAM (remote via sim-server).
70
-
71
- DriverProtocol surface:
72
- name, detect, lint, connect, parse_output, run_file
73
-
74
- Extended remote-session API:
75
- launch(host, port) → connect to remote sim-server
76
- run(code, label) → execute on remote (shell or Python)
77
- query(name) → inspect remote session state
78
- disconnect() → tear down remote session
79
- """
80
-
81
- def __init__(self):
82
- self._host: str | None = None
83
- self._port: int | None = None
84
- self._session_id: str | None = None
85
- self._client: httpx.Client | None = None
86
- self._timeout: float = 300.0 # solver can run minutes
87
-
88
- @property
89
- def name(self) -> str:
90
- return "openfoam"
91
-
92
- @property
93
- def supports_session(self) -> bool:
94
- return False
95
-
96
- # -- DriverProtocol -------------------------------------------------------
97
-
98
- def detect(self, script: Path) -> bool:
99
- """Detect OpenFOAM scripts.
100
-
101
- Accepts:
102
- - .foam files (OpenFOAM case markers)
103
- - .py files with OpenFOAM-related imports/comments
104
- - Shell scripts with #!openfoam shebang
105
- """
106
- ext = script.suffix.lower()
107
- if ext == ".foam":
108
- return True
109
- if ext in (".py", ".sh"):
110
- try:
111
- header = script.read_bytes()[:4096].decode("utf-8", errors="replace")
112
- return bool(_OPENFOAM_PATTERNS.search(header))
113
- except OSError:
114
- return False
115
- return False
116
-
117
- def lint(self, script: Path) -> LintResult:
118
- """Validate script syntax without executing."""
119
- ext = script.suffix.lower()
120
-
121
- if ext == ".foam":
122
- return LintResult(ok=True, diagnostics=[
123
- Diagnostic(level="info", message="OpenFOAM case marker file")
124
- ])
125
-
126
- if ext == ".sh":
127
- # Shell scripts — just check file exists and is non-empty
128
- try:
129
- text = script.read_text(errors="replace")
130
- if not text.strip():
131
- return LintResult(ok=False, diagnostics=[
132
- Diagnostic(level="error", message="Script is empty")
133
- ])
134
- return LintResult(ok=True, diagnostics=[])
135
- except OSError as e:
136
- return LintResult(ok=False, diagnostics=[
137
- Diagnostic(level="error", message=f"Cannot read file: {e}")
138
- ])
139
-
140
- if ext == ".py":
141
- try:
142
- text = script.read_text(errors="replace")
143
- ast.parse(text)
144
- return LintResult(ok=True, diagnostics=[])
145
- except SyntaxError as e:
146
- return LintResult(ok=False, diagnostics=[
147
- Diagnostic(level="error", message=f"Syntax error: {e}", line=e.lineno)
148
- ])
149
-
150
- return LintResult(ok=False, diagnostics=[
151
- Diagnostic(level="error", message=f"Unsupported file type '{ext}'")
152
- ])
153
-
154
- def connect(self) -> ConnectionInfo:
155
- """Check remote sim-server availability (if host/port set) or local OF."""
156
- if self._host:
157
- try:
158
- r = httpx.get(
159
- f"http://{self._host}:{self._port}/ps",
160
- timeout=5.0,
161
- )
162
- data = r.json()
163
- return ConnectionInfo(
164
- solver="openfoam",
165
- version=data.get("openfoam_version", "remote"),
166
- status="ok",
167
- message=f"sim-server at {self._host}:{self._port} reachable",
168
- )
169
- except Exception as e:
170
- return ConnectionInfo(
171
- solver="openfoam",
172
- version=None,
173
- status="unreachable",
174
- message=f"Cannot reach sim-server at {self._host}:{self._port}: {e}",
175
- )
176
-
177
- # No remote host set — report as needing configuration
178
- return ConnectionInfo(
179
- solver="openfoam",
180
- version=None,
181
- status="not_configured",
182
- message="OpenFOAM runs remotely. Call launch(host, port) to connect to sim-server.",
183
- )
184
-
185
- def detect_installed(self) -> list[SolverInstall]:
186
- """Enumerate OpenFOAM installations on this host.
187
-
188
- Strategy (deduplicated by install path; ordered with the highest
189
- version first):
190
- 1. WM_PROJECT_DIR / WM_PROJECT_VERSION env vars (the canonical
191
- signal — set after the user has sourced etc/bashrc)
192
- 2. /opt/openfoam-v* and /opt/openfoam* (ESI Ubuntu / RHEL packages)
193
- 3. /usr/lib/openfoam/openfoam-v* (Foundation deb defaults)
194
- 4. ~/OpenFOAM/OpenFOAM-v* (manual user installs)
195
- 5. `which simpleFoam` PATH probe — last resort, used to surface a
196
- usable install whose location doesn't match any default
197
-
198
- Pure stdlib. Does NOT source bashrc — that happens later in the
199
- runner's op_connect. Returns [] when nothing is found.
200
- """
201
- import os
202
- import shutil
203
-
204
- found: dict[str, SolverInstall] = {}
205
-
206
- def _record(install_dir: Path, source: str, version_hint: str | None = None) -> None:
207
- if not install_dir.is_dir():
208
- return
209
- version = version_hint or _openfoam_version_from_path(install_dir)
210
- if version is None:
211
- return
212
- key = str(install_dir.resolve())
213
- if key in found:
214
- return
215
- found[key] = SolverInstall(
216
- name="openfoam",
217
- version=version,
218
- path=key,
219
- source=source,
220
- extra={"raw_version": version},
221
- )
222
-
223
- # 1) Inherited env vars
224
- env_dir = os.environ.get("WM_PROJECT_DIR")
225
- env_ver = os.environ.get("WM_PROJECT_VERSION")
226
- if env_dir:
227
- _record(Path(env_dir), source="env:WM_PROJECT_DIR", version_hint=env_ver)
228
-
229
- # 2,3,4) Default install dirs
230
- scan_roots = [
231
- Path("/opt"),
232
- Path("/usr/lib"),
233
- Path("/usr/lib/openfoam"),
234
- Path.home() / "OpenFOAM",
235
- ]
236
- for root in scan_roots:
237
- if not root.is_dir():
238
- continue
239
- for child in sorted(root.iterdir()):
240
- n = child.name.lower()
241
- if "openfoam" not in n:
242
- continue
243
- # ESI sometimes nests as openfoam-v2406/ → has etc/bashrc directly,
244
- # sometimes as openfoam/openfoam-v2406/ — handle both layers.
245
- if (child / "etc" / "bashrc").is_file():
246
- _record(child, source=f"default-path:{root}")
247
- else:
248
- for sub in child.iterdir() if child.is_dir() else []:
249
- if (sub / "etc" / "bashrc").is_file():
250
- _record(sub, source=f"default-path:{root}")
251
-
252
- # 5) PATH probe
253
- sfoam = shutil.which("simpleFoam")
254
- if sfoam:
255
- # simpleFoam typically lives at <install>/platforms/linux64GccDPInt32Opt/bin/
256
- # walk up to find the install root (the dir that contains etc/bashrc)
257
- p = Path(sfoam).resolve()
258
- for parent in p.parents:
259
- if (parent / "etc" / "bashrc").is_file():
260
- _record(parent, source="which:simpleFoam")
261
- break
262
-
263
- # Highest version first (string sort works for "v2406" > "v2312" > "v2206")
264
- return sorted(found.values(), key=lambda i: i.version, reverse=True)
265
-
266
- def parse_output(self, stdout: str) -> dict:
267
- """Extract last JSON object from stdout."""
268
- for line in reversed(stdout.strip().splitlines()):
269
- line = line.strip()
270
- if line.startswith("{"):
271
- try:
272
- return json.loads(line)
273
- except json.JSONDecodeError:
274
- continue
275
- return {}
276
-
277
- def run_file(self, script: Path) -> RunResult:
278
- """Execute a local script with the OpenFOAM environment sourced.
279
-
280
- ``--solver openfoam`` is supposed to mean "run this in an OpenFOAM
281
- environment". Without sourcing ``etc/bashrc`` the agent's script
282
- sees an empty PATH/WM_PROJECT_DIR and gets a confusing
283
- ``blockMesh: not found`` from the wrong layer. We source bashrc
284
- once and then exec the script so the OF tooling is reachable.
285
-
286
- Falls back to bare ``python3 SCRIPT`` only if no OF install is
287
- detected (caller will fail downstream anyway).
288
- """
289
- from sim.runner import run_subprocess
290
-
291
- installs = self.detect_installed()
292
- bashrc = None
293
- for inst in installs:
294
- candidate = Path(inst.path) / "etc" / "bashrc"
295
- if candidate.is_file():
296
- bashrc = candidate
297
- break
298
-
299
- if bashrc is None:
300
- return run_subprocess(
301
- [sys.executable, str(script)],
302
- script=script,
303
- solver=self.name,
304
- )
305
-
306
- # Wrap so the OF env is in place before the script runs. exec
307
- # replaces the bash shell so the PID seen by the runner is the
308
- # script's, not bash's.
309
- import shlex
310
- runner = "python3" if script.suffix == ".py" else "bash"
311
- cmd = [
312
- "bash", "-c",
313
- f"source {shlex.quote(str(bashrc))} && "
314
- f"exec {runner} {shlex.quote(str(script))}",
315
- ]
316
- return run_subprocess(cmd, script=script, solver=self.name)
317
-
318
- # -- Phase 2: Remote session via sim-server --------------------------------
319
-
320
- def launch(
321
- self,
322
- host: str = "localhost",
323
- port: int = 7600,
324
- timeout: float = 300.0,
325
- ) -> dict:
326
- """Connect to a remote sim-server running OpenFOAM.
327
-
328
- Args:
329
- host: sim-server hostname or IP.
330
- port: sim-server port (default 7600).
331
- timeout: HTTP timeout for long-running solver commands.
332
- """
333
- if self._session_id is not None:
334
- raise RuntimeError("Session already active. Call disconnect() first.")
335
-
336
- self._host = host
337
- self._port = port
338
- self._timeout = timeout
339
- self._client = httpx.Client(timeout=timeout)
340
-
341
- try:
342
- r = self._client.post(
343
- f"http://{host}:{port}/connect",
344
- json={"solver": "openfoam"},
345
- )
346
- except httpx.ConnectError as e:
347
- self._client.close()
348
- self._client = None
349
- raise RuntimeError(f"Cannot reach sim-server at {host}:{port}: {e}")
350
-
351
- if r.status_code != 200:
352
- detail = r.json().get("detail", r.text)
353
- raise RuntimeError(f"sim-server /connect failed: {detail}")
354
-
355
- data = r.json()
356
- self._session_id = data.get("data", {}).get("session_id")
357
- return data
358
-
359
- def run(self, code: str, label: str = "openfoam-snippet") -> dict:
360
- """Execute code on the remote OpenFOAM session.
361
-
362
- If code starts with ``#!openfoam``, the server runs it as a
363
- shell script with the OpenFOAM environment sourced.
364
- Otherwise, it runs as Python code.
365
-
366
- Args:
367
- code: Shell commands (with #!openfoam prefix) or Python code.
368
- label: Human-readable label for this execution step.
369
- """
370
- if self._client is None:
371
- raise RuntimeError("Not connected. Call launch() first.")
372
-
373
- r = self._client.post(
374
- f"http://{self._host}:{self._port}/exec",
375
- json={"code": code, "label": label},
376
- )
377
-
378
- if r.status_code != 200:
379
- detail = r.json().get("detail", r.text)
380
- return {"ok": False, "label": label, "error": detail}
381
-
382
- data = r.json()
383
- return data.get("data", data)
384
-
385
- def query(self, name: str = "session.summary") -> dict:
386
- """Query remote session state.
387
-
388
- Supported: "session.summary", "last.result"
389
- """
390
- if self._client is None:
391
- raise RuntimeError("Not connected. Call launch() first.")
392
-
393
- r = self._client.get(
394
- f"http://{self._host}:{self._port}/inspect/{name}",
395
- )
396
- data = r.json()
397
- return data.get("data", data)
398
-
399
- def disconnect(self) -> dict:
400
- """Disconnect from the remote sim-server session."""
401
- result = {"ok": False, "reason": "no active session"}
402
-
403
- if self._client is not None:
404
- try:
405
- r = self._client.post(
406
- f"http://{self._host}:{self._port}/disconnect",
407
- )
408
- result = r.json()
409
- except Exception:
410
- pass
411
- try:
412
- self._client.close()
413
- except Exception:
414
- pass
415
-
416
- self._client = None
417
- self._session_id = None
418
- return result
419
-
420
- @property
421
- def is_connected(self) -> bool:
422
- return self._client is not None and self._session_id is not None
423
-
424
- def ps(self) -> dict:
425
- """Check remote session status."""
426
- if self._client is None:
427
- return {"connected": False}
428
- try:
429
- r = self._client.get(f"http://{self._host}:{self._port}/ps")
430
- return r.json()
431
- except Exception:
432
- return {"connected": False, "error": "request failed"}