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/server.py ADDED
@@ -0,0 +1,547 @@
1
+ """sim serve — HTTP server that holds one or more live simulation sessions.
2
+
3
+ Like `ollama serve`: start once, then use `sim connect/exec/inspect/disconnect`.
4
+
5
+ sim serve # local (127.0.0.1:7600)
6
+ sim serve --host 0.0.0.0 # expose on network (Tailscale)
7
+ sim serve --host 0.0.0.0 --port 8000
8
+
9
+ Multi-session model (issue #26):
10
+
11
+ Each `/connect` opens an independent session with a fresh `session_id`.
12
+ Subsequent per-session calls route by the `X-Sim-Session` header. When
13
+ only one session is live, the header is optional — the server picks the
14
+ sole session as default. With two or more sessions live and no header,
15
+ per-session endpoints return 400. See
16
+ `docs/architecture/multi-session-and-config.md` for the full contract.
17
+
18
+ Endpoints:
19
+ POST /connect {solver, mode, ui_mode, processors} → header-less
20
+ POST /exec {code, label} → header-routed
21
+ POST /run {script, solver} → header-less (one-shot)
22
+ GET /inspect/<name> → header-routed
23
+ GET /ps → header-less (lists all)
24
+ GET /screenshot → header-less (global)
25
+ POST /disconnect → header-routed
26
+ POST /shutdown → header-less (tears down all)
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import io
31
+ import math
32
+ import os
33
+ import threading
34
+ import time
35
+ import uuid
36
+ from dataclasses import dataclass, field
37
+ from typing import Any
38
+
39
+ from fastapi import BackgroundTasks, FastAPI, Header, HTTPException, Request
40
+ from fastapi.responses import JSONResponse
41
+ from pydantic import BaseModel
42
+
43
+
44
+ def _sanitize_for_json(obj):
45
+ """Recursively replace NaN/+Inf/-Inf floats with None.
46
+
47
+ FastAPI's default JSONResponse encoder rejects out-of-range floats,
48
+ which crashes /exec and /inspect when a driver returns numeric
49
+ results that include NaN (e.g. an unsolved COMSOL evaluation).
50
+ Replacing them with None keeps the wire format strict-JSON-compliant
51
+ without losing the surrounding payload.
52
+ """
53
+ if isinstance(obj, float):
54
+ if math.isnan(obj) or math.isinf(obj):
55
+ return None
56
+ return obj
57
+ if isinstance(obj, dict):
58
+ return {k: _sanitize_for_json(v) for k, v in obj.items()}
59
+ if isinstance(obj, (list, tuple)):
60
+ return [_sanitize_for_json(v) for v in obj]
61
+ return obj
62
+
63
+
64
+ class _NaNSafeJSONResponse(JSONResponse):
65
+ def render(self, content) -> bytes:
66
+ return super().render(_sanitize_for_json(content))
67
+
68
+
69
+ app = FastAPI(title="sim", version="0.2.0", default_response_class=_NaNSafeJSONResponse)
70
+
71
+
72
+ # ── Request models ───────────────────────────────────────────────────────────
73
+
74
+ class ConnectRequest(BaseModel):
75
+ solver: str = "fluent"
76
+ mode: str = "meshing"
77
+ ui_mode: str = "gui"
78
+ processors: int = 2
79
+ workspace: str | None = None # passed through to driver.launch(workspace=...)
80
+
81
+
82
+ class ExecRequest(BaseModel):
83
+ code: str
84
+ label: str = "snippet"
85
+
86
+
87
+ class RunRequest(BaseModel):
88
+ script: str
89
+ solver: str
90
+
91
+
92
+ # ── Session state ────────────────────────────────────────────────────────────
93
+
94
+ @dataclass
95
+ class SessionState:
96
+ session_id: str
97
+ solver: str
98
+ mode: str | None = None
99
+ ui_mode: str | None = None
100
+ processors: int = 1
101
+ connected_at: float | None = None
102
+ run_count: int = 0
103
+ driver: Any = None
104
+ runs: list[dict] = field(default_factory=list)
105
+ profile: str | None = None
106
+ lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
107
+
108
+
109
+ # Module-level multi-session registry. Two independent locks: `_sessions_lock`
110
+ # for dict mutations (add/remove/iter), per-session `.lock` for body-of-work
111
+ # serialization (exec calls on the same driver).
112
+ _sessions: dict[str, SessionState] = {}
113
+ _sessions_lock = threading.Lock()
114
+
115
+
116
+ # ── Session selector ─────────────────────────────────────────────────────────
117
+
118
+
119
+ def _select_session(header_val: str | None) -> SessionState:
120
+ """Resolve the target session from header + default-picking rules.
121
+
122
+ Rules (design note §6):
123
+ 1. If header is set, use it. 404 on unknown id.
124
+ 2. Else if exactly one session live, pick it.
125
+ 3. Else 400 with a helpful message.
126
+ """
127
+ with _sessions_lock:
128
+ if header_val:
129
+ s = _sessions.get(header_val)
130
+ if s is None:
131
+ raise HTTPException(404, f"unknown session_id: {header_val}")
132
+ return s
133
+ if len(_sessions) == 1:
134
+ return next(iter(_sessions.values()))
135
+ if not _sessions:
136
+ raise HTTPException(400, "no active sessions — POST /connect first")
137
+ raise HTTPException(
138
+ 400,
139
+ f"{len(_sessions)} sessions live; set X-Sim-Session header or use `sim --session <id>`",
140
+ )
141
+
142
+
143
+ def _register_session(state: SessionState) -> None:
144
+ with _sessions_lock:
145
+ _sessions[state.session_id] = state
146
+
147
+
148
+ def _drop_session(session_id: str) -> SessionState | None:
149
+ with _sessions_lock:
150
+ return _sessions.pop(session_id, None)
151
+
152
+
153
+ def _list_sessions() -> list[SessionState]:
154
+ with _sessions_lock:
155
+ return list(_sessions.values())
156
+
157
+
158
+ # ── Endpoints ────────────────────────────────────────────────────────────────
159
+
160
+ @app.get("/version")
161
+ def version():
162
+ from sim import __version__
163
+ return {"version": __version__}
164
+
165
+
166
+ @app.get("/detect/{solver}")
167
+ def detect_solver(solver: str):
168
+ """On-demand detection of one named solver on this host.
169
+
170
+ Returns the same shape that local `sim check <solver>` produces, so
171
+ the CLI can use the same rendering code for both local and remote
172
+ detection.
173
+ """
174
+ from sim.compat import load_compatibility_by_name, safe_detect_installed
175
+ from sim.drivers import get_driver
176
+
177
+ try:
178
+ driver = get_driver(solver)
179
+ except Exception as e: # noqa: BLE001 — surface lazy-import failures distinctly
180
+ raise HTTPException(500, f"driver '{solver}' failed to load: {type(e).__name__}: {e}")
181
+ if driver is None:
182
+ raise HTTPException(404, f"unknown solver: {solver}")
183
+
184
+ installs = safe_detect_installed(driver)
185
+
186
+ resolutions: list[dict] = []
187
+ compat_dict: dict | None = None
188
+ compat = load_compatibility_by_name(solver)
189
+ if compat is not None:
190
+ compat_dict = {
191
+ "driver": compat.driver,
192
+ "sdk_package": compat.sdk_package,
193
+ "profiles": [p.to_dict() for p in compat.profiles],
194
+ }
195
+ for inst in installs:
196
+ profile = compat.resolve(inst.version)
197
+ resolutions.append({
198
+ "install": inst.to_dict(),
199
+ "profile": profile.to_dict() if profile else None,
200
+ })
201
+ else:
202
+ for inst in installs:
203
+ resolutions.append({"install": inst.to_dict(), "profile": None})
204
+
205
+ return {
206
+ "ok": True,
207
+ "data": {
208
+ "solver": solver,
209
+ "installs": [i.to_dict() for i in installs],
210
+ "resolutions": resolutions,
211
+ "compatibility": compat_dict,
212
+ },
213
+ }
214
+
215
+
216
+ def _resolve_profile(driver, solver: str):
217
+ """Best-effort lookup of which compat.yaml profile applies to the
218
+ detected install. Returns the Profile, or None on miss / failure.
219
+ Never raises.
220
+ """
221
+ from sim.compat import load_compatibility_by_name, safe_detect_installed
222
+
223
+ installs = safe_detect_installed(driver)
224
+ if not installs:
225
+ return None
226
+ compat = load_compatibility_by_name(solver)
227
+ if compat is None:
228
+ return None
229
+ for inst in sorted(installs, key=lambda i: i.version, reverse=True):
230
+ profile = compat.resolve(inst.version)
231
+ if profile is not None:
232
+ return profile
233
+ return None
234
+
235
+
236
+ @app.post("/connect")
237
+ def connect(req: ConnectRequest):
238
+ """Open a solver session. Multi-session: never conflicts with an existing one.
239
+
240
+ sim-cli runs every driver in its own process — the same Python that
241
+ runs sim serve also imports the SDK directly. There is no subprocess
242
+ isolation and no per-profile env management. The resolved profile is
243
+ attached to the response as a label so the agent (and skills layer)
244
+ can know which compat.yaml entry is in effect.
245
+ """
246
+ from sim.drivers import get_driver
247
+
248
+ try:
249
+ driver = get_driver(req.solver)
250
+ except Exception as e: # noqa: BLE001 — surface lazy-import failures distinctly
251
+ raise HTTPException(500, f"driver '{req.solver}' failed to load: {type(e).__name__}: {e}")
252
+ if driver is None:
253
+ raise HTTPException(400, f"unknown solver: {req.solver}")
254
+
255
+ if not getattr(driver, "supports_session", False):
256
+ raise HTTPException(
257
+ 400,
258
+ f"{req.solver} does not support persistent sessions. "
259
+ "Use POST /run for one-shot execution.",
260
+ )
261
+
262
+ # Single-driver-instance limitation: the current `DriverProtocol`
263
+ # classes are module-level singletons, so holding two concurrent
264
+ # sessions on the *same* driver class would alias driver internal
265
+ # state. Multi-solver parallelism (fluent + mechanical) is the
266
+ # supported case; two fluent sessions is not yet.
267
+ with _sessions_lock:
268
+ for s in _sessions.values():
269
+ if s.solver == req.solver:
270
+ raise HTTPException(
271
+ 400,
272
+ f"a {req.solver} session is already live (id={s.session_id}); "
273
+ "two concurrent sessions on the same driver aren't supported yet",
274
+ )
275
+
276
+ launch_kwargs: dict = {
277
+ "mode": req.mode,
278
+ "ui_mode": req.ui_mode,
279
+ "processors": req.processors,
280
+ }
281
+ if req.workspace is not None:
282
+ launch_kwargs["workspace"] = req.workspace
283
+ try:
284
+ info = driver.launch(**launch_kwargs)
285
+ except HTTPException:
286
+ raise
287
+ except Exception as e:
288
+ raise HTTPException(500, f"failed to launch {req.solver}: {e}")
289
+
290
+ from sim.compat import skills_block_for_profile
291
+ profile = _resolve_profile(driver, req.solver)
292
+
293
+ sid = info.get("session_id") or f"s-{uuid.uuid4().hex[:8]}"
294
+ state = SessionState(
295
+ session_id=sid,
296
+ solver=req.solver,
297
+ mode=req.mode,
298
+ ui_mode=req.ui_mode,
299
+ processors=req.processors,
300
+ connected_at=time.time(),
301
+ run_count=0,
302
+ driver=driver,
303
+ runs=[],
304
+ profile=profile.name if profile else None,
305
+ )
306
+ _register_session(state)
307
+
308
+ # Tool advertisement (Phase 3). Tells the agent which cross-driver
309
+ # actuation objects are live in the exec namespace for this session,
310
+ # plus where to find the tool's skill document. ``gui`` is the first
311
+ # entry — present whenever the driver constructed a ``GuiController``
312
+ # at launch (i.e. ui_mode=gui/desktop on a GUI-capable driver).
313
+ tools: list[str] = []
314
+ tool_refs: dict[str, str] = {}
315
+ if getattr(driver, "_gui", None) is not None:
316
+ tools.append("gui")
317
+ tool_refs["gui"] = "sim-skills/sim-cli/gui/SKILL.md"
318
+
319
+ return {
320
+ "ok": True,
321
+ "data": {
322
+ "session_id": state.session_id,
323
+ "solver": req.solver,
324
+ "mode": state.mode,
325
+ "ui_mode": state.ui_mode,
326
+ "connected_at": state.connected_at,
327
+ "run_count": 0,
328
+ "profile": state.profile,
329
+ "skills": skills_block_for_profile(req.solver, profile),
330
+ "tools": tools,
331
+ "tool_refs": tool_refs,
332
+ },
333
+ }
334
+
335
+
336
+ @app.post("/exec")
337
+ def exec_snippet(
338
+ req: ExecRequest,
339
+ x_sim_session: str | None = Header(default=None, alias="X-Sim-Session"),
340
+ ):
341
+ state = _select_session(x_sim_session)
342
+ # Serialize calls on the same session; different sessions run in parallel.
343
+ with state.lock:
344
+ result = state.driver.run(req.code, req.label)
345
+ result.setdefault("session_id", state.session_id)
346
+ result.setdefault("started_at", time.time())
347
+ state.runs.append(result)
348
+ state.run_count += 1
349
+ return {"ok": result.get("ok", True), "data": result}
350
+
351
+
352
+ @app.post("/run")
353
+ def run_script(req: RunRequest):
354
+ """One-shot script execution — no session required."""
355
+ from pathlib import Path
356
+
357
+ from sim.drivers import get_driver
358
+ from sim.runner import execute_script
359
+
360
+ script_path = Path(req.script)
361
+ if not script_path.is_file():
362
+ raise HTTPException(400, f"script not found: {req.script}")
363
+
364
+ try:
365
+ driver = get_driver(req.solver)
366
+ except Exception as e: # noqa: BLE001 — surface lazy-import failures distinctly
367
+ raise HTTPException(500, f"driver '{req.solver}' failed to load: {type(e).__name__}: {e}")
368
+ if driver is None:
369
+ raise HTTPException(400, f"unknown solver: {req.solver}")
370
+
371
+ result = execute_script(script_path, solver=req.solver, driver=driver)
372
+ parsed = driver.parse_output(result.stdout)
373
+
374
+ return {
375
+ "ok": result.exit_code == 0,
376
+ "data": {
377
+ **result.to_dict(),
378
+ "parsed": parsed,
379
+ },
380
+ }
381
+
382
+
383
+ @app.get("/inspect/{name}")
384
+ def inspect(
385
+ name: str,
386
+ x_sim_session: str | None = Header(default=None, alias="X-Sim-Session"),
387
+ ):
388
+ state = _select_session(x_sim_session)
389
+
390
+ if name == "session.summary":
391
+ return {
392
+ "ok": True,
393
+ "data": {
394
+ "session_id": state.session_id,
395
+ "solver": state.solver,
396
+ "mode": state.mode,
397
+ "ui_mode": state.ui_mode,
398
+ "connected_at": state.connected_at,
399
+ "run_count": state.run_count,
400
+ "profile": state.profile,
401
+ "connected": True,
402
+ },
403
+ }
404
+ if name == "last.result":
405
+ if not state.runs:
406
+ return {"ok": True, "data": {"has_last_run": False}}
407
+ last = state.runs[-1]
408
+ return {
409
+ "ok": True,
410
+ "data": {
411
+ "has_last_run": True,
412
+ **{k: v for k, v in last.items() if k != "code"},
413
+ },
414
+ }
415
+ # Fallback: ask the active driver to handle driver-specific inspect targets
416
+ # (e.g. ls_dyna's deck.summary, mechanical.project_directory)
417
+ driver = state.driver
418
+ if driver is not None and hasattr(driver, "query"):
419
+ try:
420
+ result = driver.query(name)
421
+ except Exception as exc:
422
+ raise HTTPException(500, f"driver query failed: {exc}") from exc
423
+ if isinstance(result, dict):
424
+ if result.get("ok") is False:
425
+ raise HTTPException(404, result.get("error", f"unknown inspect target: {name}"))
426
+ return {"ok": True, "data": result}
427
+ raise HTTPException(404, f"unknown inspect target: {name}")
428
+
429
+
430
+ @app.get("/ps")
431
+ def ps():
432
+ """List all active sessions (new multi-session shape).
433
+
434
+ With no sessions: `{sessions: [], default_session: null}`.
435
+ With one or more: `{sessions: [...], default_session: <id>}`.
436
+ """
437
+ sessions = _list_sessions()
438
+ rows = [
439
+ {
440
+ "session_id": s.session_id,
441
+ "solver": s.solver,
442
+ "mode": s.mode,
443
+ "ui_mode": s.ui_mode,
444
+ "processors": s.processors,
445
+ "connected_at": s.connected_at,
446
+ "run_count": s.run_count,
447
+ "profile": s.profile,
448
+ }
449
+ for s in sessions
450
+ ]
451
+ default = sessions[0].session_id if len(sessions) == 1 else None
452
+ return {
453
+ "sessions": rows,
454
+ "default_session": default,
455
+ "server_pid": os.getpid(),
456
+ }
457
+
458
+
459
+ @app.get("/screenshot")
460
+ def screenshot():
461
+ """Capture the server's desktop and return as PNG.
462
+
463
+ Not session-scoped — there's one physical desktop per server host.
464
+ """
465
+ import base64
466
+
467
+ try:
468
+ from PIL import ImageGrab
469
+ except ImportError:
470
+ raise HTTPException(500, "Pillow is not installed on the server")
471
+
472
+ img = ImageGrab.grab()
473
+ buf = io.BytesIO()
474
+ img.save(buf, format="PNG")
475
+ b64 = base64.b64encode(buf.getvalue()).decode()
476
+
477
+ return {
478
+ "ok": True,
479
+ "data": {
480
+ "format": "png",
481
+ "width": img.width,
482
+ "height": img.height,
483
+ "base64": b64,
484
+ },
485
+ }
486
+
487
+
488
+ def _teardown_session(session_id: str) -> str | None:
489
+ """Best-effort: tear down one session by id. Returns the id torn down, or None."""
490
+ state = _drop_session(session_id)
491
+ if state is None:
492
+ return None
493
+ if state.driver is not None:
494
+ try:
495
+ state.driver.disconnect()
496
+ except Exception:
497
+ pass
498
+ return state.session_id
499
+
500
+
501
+ def _teardown_all() -> list[str]:
502
+ """Tear down every session. Returns the ids that were torn down."""
503
+ with _sessions_lock:
504
+ ids = list(_sessions.keys())
505
+ return [sid for sid in (_teardown_session(i) for i in ids) if sid]
506
+
507
+
508
+ @app.post("/disconnect")
509
+ def disconnect(
510
+ x_sim_session: str | None = Header(default=None, alias="X-Sim-Session"),
511
+ ):
512
+ state = _select_session(x_sim_session)
513
+ sid = _teardown_session(state.session_id)
514
+ return {"ok": True, "data": {"session_id": sid, "disconnected": True}}
515
+
516
+
517
+ @app.post("/shutdown")
518
+ def shutdown(request: Request, background_tasks: BackgroundTasks):
519
+ """Stop the sim-server process cleanly.
520
+
521
+ Tears down ALL active sessions, then schedules the process to exit
522
+ once the response has been flushed. Localhost-only — when sim serve
523
+ is exposed via --host 0.0.0.0 we don't want a LAN peer to be able
524
+ to take it down.
525
+ """
526
+ client_host = request.client.host if request.client else None
527
+ if client_host not in ("127.0.0.1", "::1", "localhost"):
528
+ raise HTTPException(
529
+ 403,
530
+ f"/shutdown is localhost-only (request from {client_host})",
531
+ )
532
+
533
+ torn_down = _teardown_all()
534
+
535
+ def _exit_after_flush() -> None:
536
+ import time as _t
537
+ _t.sleep(0.1)
538
+ os._exit(0)
539
+
540
+ background_tasks.add_task(_exit_after_flush)
541
+ return {
542
+ "ok": True,
543
+ "data": {
544
+ "shutting_down": True,
545
+ "disconnected_sessions": torn_down,
546
+ },
547
+ }