sim-cli-core 0.2.4__py3-none-any.whl → 0.3.1__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/_plugin_install.py CHANGED
@@ -33,6 +33,13 @@ from typing import Any
33
33
 
34
34
  # ── Index ───────────────────────────────────────────────────────────────────
35
35
 
36
+ # Curated wheels published by the project — primary index. Anonymous GET; updated
37
+ # whenever a new wheel is published via tools/publish-wheel.sh.
38
+ R2_MANIFEST_URL = "https://cdn.svdailab.com/manifest.json"
39
+
40
+ # Community-maintained OSS plugin catalogue — fallback for entries the curated
41
+ # manifest does not carry. Different schema (array of entries with git+homepage
42
+ # fields), normalized at lookup time.
36
43
  DEFAULT_INDEX_URL = (
37
44
  "https://raw.githubusercontent.com/svd-ai-lab/sim-plugin-index/main/index.json"
38
45
  )
@@ -46,16 +53,26 @@ def _index_cache_dir() -> Path:
46
53
 
47
54
 
48
55
  def _index_cache_path() -> Path:
56
+ """Cache file for the GitHub OSS index (``DEFAULT_INDEX_URL``)."""
49
57
  return _index_cache_dir() / "index.json"
50
58
 
51
59
 
60
+ def _r2_cache_path() -> Path:
61
+ """Cache file for the curated R2 manifest (``R2_MANIFEST_URL``)."""
62
+ return _index_cache_dir() / "manifest-r2.json"
63
+
64
+
65
+ def _cache_for(url: str) -> Path:
66
+ return _r2_cache_path() if url == R2_MANIFEST_URL else _index_cache_path()
67
+
68
+
52
69
  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/.
70
+ """Fetch a plugin index by URL. Caches under ``~/.sim/index-cache/`` keyed by URL.
54
71
 
55
72
  In ``--offline`` mode, only the local cache is consulted; an empty index
56
73
  is returned if no cache exists.
57
74
  """
58
- cache = _index_cache_path()
75
+ cache = _cache_for(url)
59
76
  if offline:
60
77
  if cache.is_file():
61
78
  try:
@@ -93,8 +110,36 @@ def fetch_index(url: str = DEFAULT_INDEX_URL, *, force: bool = False, offline: b
93
110
  return parsed
94
111
 
95
112
 
113
+ def _normalize_r2_entry(name: str, info: dict[str, Any]) -> dict[str, Any]:
114
+ """Convert an R2 manifest entry to the GitHub-style entry shape that
115
+ ``resolve_source`` consumes (``latest_version`` + ``latest_wheel_url``)."""
116
+ return {
117
+ "name": name,
118
+ "latest_version": info.get("version"),
119
+ "latest_wheel_url": info.get("wheel"),
120
+ }
121
+
122
+
123
+ def _r2_lookup(name: str, *, offline: bool = False) -> dict[str, Any] | None:
124
+ """Look up ``name`` in the R2 curated manifest, returning a normalized entry."""
125
+ manifest = fetch_index(url=R2_MANIFEST_URL, offline=offline)
126
+ plugins = manifest.get("plugins")
127
+ if not isinstance(plugins, dict):
128
+ return None
129
+ info = plugins.get(name)
130
+ if not isinstance(info, dict) or not info.get("wheel"):
131
+ return None
132
+ return _normalize_r2_entry(name, info)
133
+
134
+
96
135
  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."""
136
+ """Look up one plugin by name in a single index URL.
137
+
138
+ For ``url == R2_MANIFEST_URL`` the entry is normalized to the GitHub-style
139
+ shape so callers get a consistent dict regardless of which index served it.
140
+ """
141
+ if url == R2_MANIFEST_URL:
142
+ return _r2_lookup(name, offline=offline)
98
143
  idx = fetch_index(url=url, offline=offline)
99
144
  for entry in idx.get("plugins", []):
100
145
  if entry.get("name") == name:
@@ -102,6 +147,16 @@ def index_entry(name: str, *, offline: bool = False, url: str = DEFAULT_INDEX_UR
102
147
  return None
103
148
 
104
149
 
150
+ def index_entry_chained(name: str, *, offline: bool = False) -> dict[str, Any] | None:
151
+ """Resolve ``name`` against the curated R2 manifest first, then fall back
152
+ to the community GitHub OSS index. Returns the first hit, or ``None`` if
153
+ neither has it."""
154
+ e = _r2_lookup(name, offline=offline)
155
+ if e is not None:
156
+ return e
157
+ return index_entry(name, offline=offline, url=DEFAULT_INDEX_URL)
158
+
159
+
105
160
  # ── Source resolution ──────────────────────────────────────────────────────
106
161
 
107
162
 
@@ -120,15 +175,23 @@ _NAME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*$")
120
175
  _NAME_VERSION_RE = re.compile(r"^([A-Za-z][A-Za-z0-9_]*)@([A-Za-z0-9._\-+]+)$")
121
176
 
122
177
 
123
- def resolve_source(source: str, *, offline: bool = False, index_url: str = DEFAULT_INDEX_URL) -> ResolvedSource:
178
+ def resolve_source(source: str, *, offline: bool = False,
179
+ index_url: str | None = None) -> ResolvedSource:
124
180
  """Classify a source argument and choose what to hand to pip.
125
181
 
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.
182
+ For named installs, lookup chains the curated R2 manifest first and falls
183
+ back to the GitHub OSS index. Pass ``index_url`` to force a single source.
184
+ Prefers wheel-from-release URL when the index entry has one; falls back to
185
+ git+https. Raises ``ValueError`` if the name isn't in the index in offline
186
+ mode.
129
187
  """
130
188
  s = source.strip()
131
189
 
190
+ def _lookup(name: str) -> dict[str, Any] | None:
191
+ if index_url is None:
192
+ return index_entry_chained(name, offline=offline)
193
+ return index_entry(name, offline=offline, url=index_url)
194
+
132
195
  # Local files / dirs first (cheapest to check).
133
196
  p = Path(s)
134
197
  if s.startswith(("./", "../", "/", "~")) or p.exists():
@@ -160,7 +223,7 @@ def resolve_source(source: str, *, offline: bool = False, index_url: str = DEFAU
160
223
  m = _NAME_VERSION_RE.match(s)
161
224
  if m:
162
225
  name, version = m.group(1), m.group(2)
163
- entry = index_entry(name, offline=offline, url=index_url)
226
+ entry = _lookup(name)
164
227
  if entry is None and offline:
165
228
  raise ValueError(f"plugin {name!r} not in offline index")
166
229
  if entry is None:
@@ -171,6 +234,20 @@ def resolve_source(source: str, *, offline: bool = False, index_url: str = DEFAU
171
234
  if entry.get("latest_version") == version and entry.get("latest_wheel_url"):
172
235
  return ResolvedSource(kind="name-version", raw=s, name=name, version=version,
173
236
  pip_target=str(entry["latest_wheel_url"]))
237
+ # If the entry came from the R2 manifest, all versioned wheels live at a
238
+ # predictable path — construct the pinned URL by filename convention so
239
+ # ``name@<old-version>`` resolves without needing every version listed
240
+ # in the manifest. (R2 keeps every published wheel; manifest only tracks
241
+ # latest.)
242
+ latest_url = str(entry.get("latest_wheel_url") or "")
243
+ if latest_url.startswith("https://cdn.svdailab.com/wheels/"):
244
+ return ResolvedSource(
245
+ kind="name-version", raw=s, name=name, version=version,
246
+ pip_target=(
247
+ f"https://cdn.svdailab.com/wheels/"
248
+ f"sim_plugin_{name}-{version}-py3-none-any.whl"
249
+ ),
250
+ )
174
251
  git = entry.get("git")
175
252
  if git:
176
253
  return ResolvedSource(kind="name-version", raw=s, name=name, version=version,
@@ -180,7 +257,7 @@ def resolve_source(source: str, *, offline: bool = False, index_url: str = DEFAU
180
257
 
181
258
  # bare name
182
259
  if _NAME_RE.match(s):
183
- entry = index_entry(s, offline=offline, url=index_url)
260
+ entry = _lookup(s)
184
261
  if entry is None and offline:
185
262
  raise ValueError(f"plugin {s!r} not in offline index")
186
263
  if entry is None:
@@ -440,10 +517,12 @@ def bundle_plugins(names: list[str], output_dir: Path, *,
440
517
 
441
518
  __all__ = [
442
519
  "DEFAULT_INDEX_URL",
520
+ "R2_MANIFEST_URL",
443
521
  "ResolvedSource",
444
522
  "InstallReport",
445
523
  "fetch_index",
446
524
  "index_entry",
525
+ "index_entry_chained",
447
526
  "resolve_source",
448
527
  "install_plugin",
449
528
  "uninstall_plugin",
sim/cli.py CHANGED
@@ -13,6 +13,19 @@ from sim.drivers import get_driver
13
13
  from sim.runner import execute_script
14
14
 
15
15
 
16
+ # Reconfigure stdout/stderr to UTF-8 so non-ASCII glyphs (arrows, check marks,
17
+ # warning triangles, etc.) survive on Windows consoles that default to cp1252
18
+ # or older codepages. errors="replace" prevents crashes on terminals that
19
+ # can't render a given codepoint — affected glyphs become "?" instead of
20
+ # raising UnicodeEncodeError.
21
+ if sys.stdout.encoding and sys.stdout.encoding.lower() != "utf-8":
22
+ try:
23
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
24
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
25
+ except (AttributeError, OSError):
26
+ pass
27
+
28
+
16
29
  # ── Top-level group ──────────────────────────────────────────────────────────
17
30
 
18
31
  @click.group()
@@ -483,6 +496,47 @@ def _print_followup_hints(run_id, stdout_path, stderr_path, delta):
483
496
  click.echo(f" cat {delta[0]['path']} # likely solver log (largest write)")
484
497
 
485
498
 
499
+ def _parse_driver_option_value(value: str):
500
+ lowered = value.lower()
501
+ if lowered == "true":
502
+ return True
503
+ if lowered == "false":
504
+ return False
505
+ try:
506
+ return int(value)
507
+ except ValueError:
508
+ pass
509
+ try:
510
+ return float(value)
511
+ except ValueError:
512
+ return value
513
+
514
+
515
+ def _parse_driver_options(items: tuple[str, ...]) -> dict:
516
+ """Parse generic driver launch passthrough options from KEY=VALUE pairs."""
517
+ parsed: dict = {}
518
+ for item in items:
519
+ if "=" not in item:
520
+ raise click.BadParameter(
521
+ f"{item!r} is not KEY=VALUE",
522
+ param_hint="--driver-option",
523
+ )
524
+ key, value = item.split("=", 1)
525
+ key = key.strip()
526
+ if not key:
527
+ raise click.BadParameter(
528
+ f"{item!r} has an empty key",
529
+ param_hint="--driver-option",
530
+ )
531
+ if key in parsed:
532
+ raise click.BadParameter(
533
+ f"{key!r} was provided more than once",
534
+ param_hint="--driver-option",
535
+ )
536
+ parsed[key] = _parse_driver_option_value(value)
537
+ return parsed
538
+
539
+
486
540
  # ── connect (persistent session) ────────────────────────────────────────────
487
541
 
488
542
  @main.command()
@@ -492,11 +546,19 @@ def _print_followup_hints(run_id, stdout_path, stderr_path, delta):
492
546
  @click.option("--processors", default=1, type=int)
493
547
  @click.option("--workspace", default=None,
494
548
  help="Solver-specific working dir (e.g. flotherm FLOUSERDIR).")
549
+ @click.option("--driver-option", "driver_options", multiple=True,
550
+ metavar="KEY=VALUE",
551
+ help="Generic driver launch option passthrough. Repeat as needed.")
495
552
  @click.pass_context
496
- def connect(ctx, solver, mode, ui_mode, processors, workspace):
553
+ def connect(ctx, solver, mode, ui_mode, processors, workspace, driver_options):
497
554
  """Launch a solver and hold a persistent session."""
498
555
  from sim.session import SessionClient
499
556
 
557
+ try:
558
+ parsed_driver_options = _parse_driver_options(driver_options)
559
+ except click.BadParameter as exc:
560
+ raise click.ClickException(str(exc)) from exc
561
+
500
562
  client = SessionClient(host=ctx.obj["host"], port=ctx.obj["port"],
501
563
  session_id=ctx.obj.get("session"))
502
564
  result = client.connect(
@@ -505,6 +567,7 @@ def connect(ctx, solver, mode, ui_mode, processors, workspace):
505
567
  ui_mode=ui_mode,
506
568
  processors=processors,
507
569
  workspace=workspace,
570
+ driver_options=parsed_driver_options,
508
571
  )
509
572
 
510
573
  if ctx.obj["json"]:
@@ -1022,8 +1085,11 @@ def plugin_info_cmd(ctx, name):
1022
1085
  @click.argument("source")
1023
1086
  @click.option("-e", "--editable", is_flag=True,
1024
1087
  help="Editable install (pip install -e). For plugin authors.")
1025
- @click.option("--upgrade", is_flag=True,
1026
- help="Pass --upgrade to pip.")
1088
+ @click.option("--upgrade/--no-upgrade", default=True,
1089
+ help="Pass --upgrade to pip so the install replaces any "
1090
+ "existing version with whatever the source resolves to. "
1091
+ "Default: enabled. Use --no-upgrade to keep an existing "
1092
+ "install if one is already present.")
1027
1093
  @click.option("--offline", is_flag=True,
1028
1094
  help="Use only the local cached index; no network calls.")
1029
1095
  @click.option("--no-sync", "no_sync", is_flag=True,
sim/compat.py CHANGED
@@ -395,6 +395,28 @@ def skills_block_for_profile(driver: str, profile: "Profile | None") -> dict:
395
395
  driver_dir = (root / driver) if root is not None else None
396
396
 
397
397
  if driver_dir is None or not driver_dir.is_dir():
398
+ # Out-of-tree plugins can bundle skills through the ``sim.skills``
399
+ # entry-point. Prefer the external sim-skills tree when present so
400
+ # local development overlays win, then fall back to the installed
401
+ # plugin bundle.
402
+ try:
403
+ from sim.plugins import skills_dir_for
404
+ plugin_dir = skills_dir_for(driver)
405
+ except Exception: # noqa: BLE001 - skills are advisory context
406
+ plugin_dir = None
407
+ if plugin_dir is not None:
408
+ try:
409
+ index = plugin_dir.joinpath("SKILL.md")
410
+ if index.is_file():
411
+ return {
412
+ "root": str(plugin_dir),
413
+ "index": str(index),
414
+ "active_sdk_layer": active_sdk,
415
+ "active_solver_layer": active_solver,
416
+ }
417
+ except Exception: # noqa: BLE001 - fall through to hint
418
+ pass
419
+
398
420
  return {
399
421
  "root": None,
400
422
  "index": None,
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:
sim/inspect.py CHANGED
@@ -787,13 +787,24 @@ def generic_probes() -> list:
787
787
 
788
788
  def _find_matching_windows(
789
789
  process_name_substrings: tuple[str, ...],
790
+ target_pid: int | None = None,
790
791
  ) -> tuple[list[dict], int, list[str]]:
791
- """Shared helper: enumerate top-level windows owned by any process whose
792
- name contains one of the given substrings. Returns (matches, total_scanned,
793
- errors). Each match dict: {window, pid, proc_name, title, rect}.
794
-
795
- `rect` is (left, top, right, bottom) int tuple, or None if rect-fetch
796
- failed. `window` is the raw pywinauto wrapper (use it for capture).
792
+ """Shared helper: enumerate top-level windows for a target process.
793
+
794
+ Two filtering modes:
795
+ * ``target_pid`` is provided → return only windows whose owning process
796
+ ID matches ``target_pid``. The substring list is ignored. Use this
797
+ when the caller knows the exact process (e.g. a driver that just
798
+ spawned the target solver) — it eliminates foreground races where
799
+ another window with a generically-matching name happens to be top.
800
+ * ``target_pid`` is ``None`` → fall back to substring matching against
801
+ the owning process's name. This is the legacy default for callers
802
+ that can only describe the target by class.
803
+
804
+ Returns (matches, total_scanned, errors). Each match dict:
805
+ ``{window, pid, proc_name, title, rect}``. ``rect`` is
806
+ ``(left, top, right, bottom)`` int tuple, or ``None`` if rect-fetch
807
+ failed. ``window`` is the raw pywinauto wrapper (use it for capture).
797
808
 
798
809
  Lazy-imports pywinauto + psutil so this module stays importable on Linux
799
810
  / in headless environments.
@@ -823,8 +834,12 @@ def _find_matching_windows(
823
834
  proc_name = psutil.Process(pid).name().lower()
824
835
  except Exception:
825
836
  proc_name = ""
826
- if not any(sub in proc_name for sub in subs):
827
- continue
837
+ if target_pid is not None:
838
+ if pid != target_pid:
839
+ continue
840
+ else:
841
+ if not any(sub in proc_name for sub in subs):
842
+ continue
828
843
  title = w.window_text() or ""
829
844
  try:
830
845
  r = w.rectangle()
@@ -881,9 +896,11 @@ class GuiDialogProbe:
881
896
  self,
882
897
  process_name_substrings: tuple[str, ...] = ("fluent", "ansys", "cx", "cortex"),
883
898
  code_prefix: str = "fluent.gui",
899
+ target_pid: int | None = None,
884
900
  ):
885
901
  self.process_name_substrings = tuple(s.lower() for s in process_name_substrings)
886
902
  self.code_prefix = code_prefix
903
+ self.target_pid = target_pid
887
904
 
888
905
  def applies(self, ctx: InspectCtx) -> bool:
889
906
  try:
@@ -893,7 +910,9 @@ class GuiDialogProbe:
893
910
  return False
894
911
 
895
912
  def probe(self, ctx: InspectCtx) -> ProbeResult:
896
- matches, total, errors = _find_matching_windows(self.process_name_substrings)
913
+ matches, total, errors = _find_matching_windows(
914
+ self.process_name_substrings, target_pid=self.target_pid,
915
+ )
897
916
  diags: list[Diagnostic] = []
898
917
  if errors:
899
918
  for msg in errors:
@@ -957,10 +976,19 @@ class ScreenshotProbe:
957
976
  """Channel #8b — per-window screenshot capture via PIL.ImageGrab bbox.
958
977
 
959
978
  IMPORTANT: this probe captures ONLY the bounding box of each matched
960
- Fluent window, NOT the whole desktop. If no Fluent window is found,
979
+ target window, NOT the whole desktop. If no matching window is found,
961
980
  emits a single warning diag and nothing else — we never fall back to
962
981
  full-screen capture (that creates noisy / PII-risky artifacts).
963
982
 
983
+ Two ways to identify the target:
984
+ * ``target_pid`` (preferred when known): bind to the exact process
985
+ the caller spawned. Eliminates foreground races where another
986
+ window whose process name happens to substring-match the legacy
987
+ list wins z-order at probe time.
988
+ * ``process_name_substrings`` (default): match any process whose
989
+ name contains one of the given substrings. Used when the caller
990
+ can only describe the target by class.
991
+
964
992
  Every matched window produces:
965
993
  - one Artifact (role="screenshot", path=<png>)
966
994
  - one info Diag (source=gui:screenshot, code=sim.screenshot.captured)
@@ -974,9 +1002,11 @@ class ScreenshotProbe:
974
1002
  self,
975
1003
  filename_prefix: str = "shot",
976
1004
  process_name_substrings: tuple[str, ...] = ("fluent", "ansys", "cx", "cortex"),
1005
+ target_pid: int | None = None,
977
1006
  ):
978
1007
  self.filename_prefix = filename_prefix
979
1008
  self.process_name_substrings = tuple(s.lower() for s in process_name_substrings)
1009
+ self.target_pid = target_pid
980
1010
 
981
1011
  def applies(self, ctx: InspectCtx) -> bool:
982
1012
  try:
@@ -999,7 +1029,9 @@ class ScreenshotProbe:
999
1029
  message=f"PIL.ImageGrab unavailable: {exc}",
1000
1030
  )])
1001
1031
 
1002
- matches, _, errors = _find_matching_windows(self.process_name_substrings)
1032
+ matches, _, errors = _find_matching_windows(
1033
+ self.process_name_substrings, target_pid=self.target_pid,
1034
+ )
1003
1035
  if errors:
1004
1036
  return ProbeResult(diagnostics=[Diagnostic(
1005
1037
  severity="warning", source="gui:screenshot",
@@ -1008,10 +1040,14 @@ class ScreenshotProbe:
1008
1040
  )])
1009
1041
 
1010
1042
  if not matches:
1043
+ target_desc = (
1044
+ f"pid={self.target_pid}" if self.target_pid is not None
1045
+ else f"{self.process_name_substrings}"
1046
+ )
1011
1047
  return ProbeResult(diagnostics=[Diagnostic(
1012
1048
  severity="info", source="gui:screenshot",
1013
1049
  code="sim.screenshot.no_window",
1014
- message=(f"no window matched {self.process_name_substrings}; "
1050
+ message=(f"no window matched {target_desc}; "
1015
1051
  f"no screenshot taken (full-screen fallback disabled)"),
1016
1052
  )])
1017
1053
 
sim/server.py CHANGED
@@ -16,7 +16,7 @@ per-session endpoints return 400. See
16
16
  `docs/architecture/multi-session-and-config.md` for the full contract.
17
17
 
18
18
  Endpoints:
19
- POST /connect {solver, mode, ui_mode, processors} → header-less
19
+ POST /connect {solver, mode, ui_mode, processors, ...} → header-less
20
20
  POST /exec {code, label} → header-routed
21
21
  POST /run {script, solver} → header-less (one-shot)
22
22
  GET /inspect/<name> → header-routed
@@ -38,7 +38,7 @@ from typing import Any
38
38
 
39
39
  from fastapi import BackgroundTasks, FastAPI, Header, HTTPException, Request
40
40
  from fastapi.responses import JSONResponse
41
- from pydantic import BaseModel
41
+ from pydantic import BaseModel, Field
42
42
 
43
43
 
44
44
  def _sanitize_for_json(obj):
@@ -76,7 +76,16 @@ class ConnectRequest(BaseModel):
76
76
  mode: str = "meshing"
77
77
  ui_mode: str = "gui"
78
78
  processors: int = 2
79
- workspace: str | None = None # passed through to driver.launch(workspace=...)
79
+ workspace: str | None = None
80
+ driver_options: dict[str, Any] = Field(default_factory=dict)
81
+
82
+
83
+ def _connect_reserved_driver_option_keys() -> set[str]:
84
+ """Return connect request fields that cannot be overridden by driver options."""
85
+ fields = getattr(ConnectRequest, "model_fields", None)
86
+ if fields is None:
87
+ fields = getattr(ConnectRequest, "__fields__", {})
88
+ return set(fields) - {"driver_options"}
80
89
 
81
90
 
82
91
  class ExecRequest(BaseModel):
@@ -98,6 +107,9 @@ class SessionState:
98
107
  mode: str | None = None
99
108
  ui_mode: str | None = None
100
109
  processors: int = 1
110
+ workspace: str | None = None
111
+ driver_options: dict = field(default_factory=dict)
112
+ launch_options: dict = field(default_factory=dict)
101
113
  connected_at: float | None = None
102
114
  run_count: int = 0
103
115
  driver: Any = None
@@ -273,13 +285,23 @@ def connect(req: ConnectRequest):
273
285
  "two concurrent sessions on the same driver aren't supported yet",
274
286
  )
275
287
 
288
+ reserved_seen = _connect_reserved_driver_option_keys() & set(req.driver_options)
289
+ if reserved_seen:
290
+ names = ", ".join(sorted(reserved_seen))
291
+ raise HTTPException(
292
+ 400,
293
+ f"driver_options may not override reserved connect keys: {names}",
294
+ )
295
+
276
296
  launch_kwargs: dict = {
277
297
  "mode": req.mode,
278
298
  "ui_mode": req.ui_mode,
279
299
  "processors": req.processors,
300
+ **req.driver_options,
280
301
  }
281
302
  if req.workspace is not None:
282
303
  launch_kwargs["workspace"] = req.workspace
304
+ launch_kwargs.setdefault("cwd", req.workspace)
283
305
  try:
284
306
  info = driver.launch(**launch_kwargs)
285
307
  except HTTPException:
@@ -297,6 +319,9 @@ def connect(req: ConnectRequest):
297
319
  mode=req.mode,
298
320
  ui_mode=req.ui_mode,
299
321
  processors=req.processors,
322
+ workspace=req.workspace,
323
+ driver_options=req.driver_options,
324
+ launch_options=info.get("launch_options") or {},
300
325
  connected_at=time.time(),
301
326
  run_count=0,
302
327
  driver=driver,
@@ -323,6 +348,9 @@ def connect(req: ConnectRequest):
323
348
  "solver": req.solver,
324
349
  "mode": state.mode,
325
350
  "ui_mode": state.ui_mode,
351
+ "workspace": state.workspace,
352
+ "driver_options": state.driver_options,
353
+ "launch_options": state.launch_options,
326
354
  "connected_at": state.connected_at,
327
355
  "run_count": 0,
328
356
  "profile": state.profile,
@@ -395,6 +423,9 @@ def inspect(
395
423
  "solver": state.solver,
396
424
  "mode": state.mode,
397
425
  "ui_mode": state.ui_mode,
426
+ "workspace": state.workspace,
427
+ "driver_options": state.driver_options,
428
+ "launch_options": state.launch_options,
398
429
  "connected_at": state.connected_at,
399
430
  "run_count": state.run_count,
400
431
  "profile": state.profile,
@@ -442,6 +473,9 @@ def ps():
442
473
  "mode": s.mode,
443
474
  "ui_mode": s.ui_mode,
444
475
  "processors": s.processors,
476
+ "workspace": s.workspace,
477
+ "driver_options": s.driver_options,
478
+ "launch_options": s.launch_options,
445
479
  "connected_at": s.connected_at,
446
480
  "run_count": s.run_count,
447
481
  "profile": s.profile,
sim/session.py CHANGED
@@ -152,7 +152,8 @@ class SessionClient:
152
152
 
153
153
  def connect(self, solver: str, mode: str = "meshing",
154
154
  ui_mode: str = "no_gui", processors: int = 1,
155
- workspace: str | None = None) -> dict:
155
+ workspace: str | None = None,
156
+ driver_options: dict | None = None) -> dict:
156
157
  # Auto-start local server if needed
157
158
  if self._is_local() and not self._server_reachable():
158
159
  if not self._auto_start_server():
@@ -164,6 +165,8 @@ class SessionClient:
164
165
  }
165
166
  if workspace is not None:
166
167
  body["workspace"] = workspace
168
+ if driver_options:
169
+ body["driver_options"] = driver_options
167
170
  resp = self._request("post", "/connect", timeout=CONNECT_TIMEOUT_S, json=body)
168
171
  # Remember the new session_id so subsequent calls on this client
169
172
  # route to it even if another session shows up later.