sim-cli-core 0.2.4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sim/__init__.py +11 -0
- sim/__main__.py +24 -0
- sim/_plugin_install.py +451 -0
- sim/_timeout.py +115 -0
- sim/cli.py +1353 -0
- sim/compat.py +411 -0
- sim/config.py +380 -0
- sim/describe.py +346 -0
- sim/driver.py +190 -0
- sim/drivers/__init__.py +161 -0
- sim/drivers/coolprop/__init__.py +3 -0
- sim/drivers/coolprop/driver.py +183 -0
- sim/drivers/openfoam/__init__.py +4 -0
- sim/drivers/openfoam/compatibility.yaml +37 -0
- sim/drivers/openfoam/driver.py +432 -0
- sim/gui/LICENSES/ATTRIBUTION.md +24 -0
- sim/gui/__init__.py +230 -0
- sim/gui/_pywinauto_tools.py +452 -0
- sim/gui/_win32_dialog.py +148 -0
- sim/history.py +170 -0
- sim/inspect.py +1088 -0
- sim/plugins.py +468 -0
- sim/runner.py +195 -0
- sim/server.py +547 -0
- sim/session.py +224 -0
- sim/testing/__init__.py +30 -0
- sim/testing/protocol_conformance.py +264 -0
- sim_cli_core-0.2.4.dist-info/METADATA +309 -0
- sim_cli_core-0.2.4.dist-info/RECORD +33 -0
- sim_cli_core-0.2.4.dist-info/WHEEL +4 -0
- sim_cli_core-0.2.4.dist-info/entry_points.txt +2 -0
- sim_cli_core-0.2.4.dist-info/licenses/LICENSE +190 -0
- sim_cli_core-0.2.4.dist-info/licenses/NOTICE +72 -0
sim/cli.py
ADDED
|
@@ -0,0 +1,1353 @@
|
|
|
1
|
+
"""sim CLI — unified interface for LLM agents to control CAD/CAE simulation software."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json as json_mod
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import click
|
|
10
|
+
|
|
11
|
+
from sim import __version__, config as _cfg, history as _history
|
|
12
|
+
from sim.drivers import get_driver
|
|
13
|
+
from sim.runner import execute_script
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
# ── Top-level group ──────────────────────────────────────────────────────────
|
|
17
|
+
|
|
18
|
+
@click.group()
|
|
19
|
+
@click.version_option(version=__version__)
|
|
20
|
+
@click.option("--json", "output_json", is_flag=True, help="JSON output for all commands.")
|
|
21
|
+
@click.option("--host", default=None,
|
|
22
|
+
help="Remote sim-server host. "
|
|
23
|
+
"Default: SIM_HOST env > config [server].host > localhost.")
|
|
24
|
+
@click.option("--port", default=None, type=int,
|
|
25
|
+
help="sim-server port. Default: SIM_PORT env > config [server].port > 7600.")
|
|
26
|
+
@click.option("--session", "session_id", default=None,
|
|
27
|
+
help="Target session id (multi-session). "
|
|
28
|
+
"Default: SIM_SESSION env > server's sole session.")
|
|
29
|
+
@click.option("--no-interactive", "no_interactive", is_flag=True,
|
|
30
|
+
help="Fail fast (NONINTERACTIVE_INPUT_REQUIRED) instead of prompting. "
|
|
31
|
+
"Auto-on when stdout is not a TTY.")
|
|
32
|
+
@click.pass_context
|
|
33
|
+
def main(ctx, output_json, host, port, session_id, no_interactive):
|
|
34
|
+
"""sim — unified CLI for LLM agents to control CAD/CAE simulation software."""
|
|
35
|
+
ctx.ensure_object(dict)
|
|
36
|
+
ctx.obj["json"] = output_json
|
|
37
|
+
# Flag > env > config > default. --host on the CLI wins because it is
|
|
38
|
+
# the most immediate caller intent. For the host side, "localhost" is
|
|
39
|
+
# the conventional default that triggers auto-start behavior in
|
|
40
|
+
# session.py; don't change that when config says otherwise unless the
|
|
41
|
+
# user explicitly asked.
|
|
42
|
+
ctx.obj["host"] = host or os.environ.get("SIM_HOST") or "localhost"
|
|
43
|
+
ctx.obj["port"] = port if port is not None else _cfg.resolve_server_port()
|
|
44
|
+
ctx.obj["session"] = session_id or os.environ.get("SIM_SESSION") or None
|
|
45
|
+
# --no-interactive: explicit flag wins; otherwise auto-on when piped.
|
|
46
|
+
ctx.obj["no_interactive"] = (
|
|
47
|
+
no_interactive
|
|
48
|
+
or os.environ.get("SIM_NO_INTERACTIVE") in ("1", "true", "True")
|
|
49
|
+
or not sys.stdin.isatty()
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# ── serve ────────────────────────────────────────────────────────────────────
|
|
54
|
+
|
|
55
|
+
@main.command()
|
|
56
|
+
@click.option("--host", "serve_host", default="127.0.0.1",
|
|
57
|
+
help="Bind address. Use 0.0.0.0 for Tailscale/network access.")
|
|
58
|
+
@click.option("--port", "serve_port", default=7600, type=int)
|
|
59
|
+
@click.option("--reload", is_flag=True, default=False,
|
|
60
|
+
help="Auto-reload on code changes (dev mode).")
|
|
61
|
+
def serve(serve_host, serve_port, reload):
|
|
62
|
+
"""Start the sim HTTP server (like ollama serve)."""
|
|
63
|
+
import uvicorn
|
|
64
|
+
|
|
65
|
+
click.echo(f"[sim] server starting on {serve_host}:{serve_port}")
|
|
66
|
+
if serve_host == "0.0.0.0":
|
|
67
|
+
click.echo("[sim] accessible on network (Tailscale)")
|
|
68
|
+
if reload:
|
|
69
|
+
click.echo("[sim] auto-reload enabled (watching for file changes)")
|
|
70
|
+
uvicorn.run(
|
|
71
|
+
"sim.server:app",
|
|
72
|
+
host=serve_host,
|
|
73
|
+
port=serve_port,
|
|
74
|
+
log_level="info",
|
|
75
|
+
reload=reload,
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# ── check ────────────────────────────────────────────────────────────────────
|
|
80
|
+
|
|
81
|
+
def _is_local_host(host: str) -> bool:
|
|
82
|
+
return host in ("localhost", "127.0.0.1", "::1", "")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _check_local(solver: str) -> dict:
|
|
86
|
+
"""Run on-demand detection in this process. Returns the same shape
|
|
87
|
+
as the /detect/{solver} HTTP endpoint."""
|
|
88
|
+
from sim.compat import load_compatibility_by_name, safe_detect_installed
|
|
89
|
+
|
|
90
|
+
try:
|
|
91
|
+
driver = get_driver(solver)
|
|
92
|
+
except Exception as e: # noqa: BLE001 — surface lazy-import failures distinctly
|
|
93
|
+
return {"ok": False, "error": f"driver '{solver}' failed to load: {type(e).__name__}: {e}"}
|
|
94
|
+
if driver is None:
|
|
95
|
+
return {"ok": False, "error": f"unknown solver: {solver}"}
|
|
96
|
+
|
|
97
|
+
installs = safe_detect_installed(driver)
|
|
98
|
+
resolutions: list[dict] = []
|
|
99
|
+
compat_dict: dict | None = None
|
|
100
|
+
compat = load_compatibility_by_name(solver)
|
|
101
|
+
if compat is not None:
|
|
102
|
+
compat_dict = {
|
|
103
|
+
"driver": compat.driver,
|
|
104
|
+
"sdk_package": compat.sdk_package,
|
|
105
|
+
"profiles": [p.to_dict() for p in compat.profiles],
|
|
106
|
+
}
|
|
107
|
+
for inst in installs:
|
|
108
|
+
profile = compat.resolve(inst.version)
|
|
109
|
+
resolutions.append({
|
|
110
|
+
"install": inst.to_dict(),
|
|
111
|
+
"profile": profile.to_dict() if profile else None,
|
|
112
|
+
})
|
|
113
|
+
else:
|
|
114
|
+
for inst in installs:
|
|
115
|
+
resolutions.append({"install": inst.to_dict(), "profile": None})
|
|
116
|
+
|
|
117
|
+
return {
|
|
118
|
+
"ok": True,
|
|
119
|
+
"data": {
|
|
120
|
+
"solver": solver,
|
|
121
|
+
"installs": [i.to_dict() for i in installs],
|
|
122
|
+
"resolutions": resolutions,
|
|
123
|
+
"compatibility": compat_dict,
|
|
124
|
+
},
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _check_remote(solver: str, host: str, port: int) -> dict:
|
|
129
|
+
"""Hit GET /detect/{solver} on a remote sim serve."""
|
|
130
|
+
import httpx
|
|
131
|
+
|
|
132
|
+
from sim.session import _httpx_client
|
|
133
|
+
|
|
134
|
+
url = f"http://{host}:{port}/detect/{solver}"
|
|
135
|
+
try:
|
|
136
|
+
with _httpx_client(host, timeout=15.0) as c:
|
|
137
|
+
r = c.get(url)
|
|
138
|
+
except httpx.RequestError as e:
|
|
139
|
+
return {"ok": False, "error": f"cannot reach sim serve at {host}:{port} - {e}"}
|
|
140
|
+
if r.status_code != 200:
|
|
141
|
+
return {"ok": False, "error": f"{r.status_code}: {r.text}"}
|
|
142
|
+
return r.json()
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _render_check(data: dict) -> None:
|
|
146
|
+
"""Pretty-print a /detect/{solver} response."""
|
|
147
|
+
solver = data["solver"]
|
|
148
|
+
installs = data.get("installs", [])
|
|
149
|
+
resolutions = data.get("resolutions", [])
|
|
150
|
+
compat = data.get("compatibility")
|
|
151
|
+
|
|
152
|
+
click.echo(f"[sim] check: {solver}")
|
|
153
|
+
if not installs:
|
|
154
|
+
click.echo(f" no {solver} installations detected on this host")
|
|
155
|
+
click.echo(f" ensure the solver is installed and re-run `sim check {solver}`")
|
|
156
|
+
return
|
|
157
|
+
|
|
158
|
+
click.echo(f" detected {len(installs)} installation(s):\n")
|
|
159
|
+
for entry in resolutions:
|
|
160
|
+
inst = entry["install"]
|
|
161
|
+
profile = entry.get("profile")
|
|
162
|
+
click.echo(f" - {solver} {inst['version']}")
|
|
163
|
+
click.echo(f" path: {inst['path']}")
|
|
164
|
+
click.echo(f" source: {inst['source']}")
|
|
165
|
+
simulink = inst.get("extra", {}).get("simulink_installed")
|
|
166
|
+
if simulink is True:
|
|
167
|
+
click.echo(f" simulink: installed")
|
|
168
|
+
elif simulink is False:
|
|
169
|
+
click.echo(f" simulink: not found on disk")
|
|
170
|
+
if profile is None:
|
|
171
|
+
if compat is None:
|
|
172
|
+
click.echo(" profile: (driver has no compatibility.yaml yet)")
|
|
173
|
+
else:
|
|
174
|
+
click.echo(" profile: [X] unsupported by any current profile")
|
|
175
|
+
else:
|
|
176
|
+
click.echo(f" profile: {profile['name']}")
|
|
177
|
+
if profile.get("sdk"):
|
|
178
|
+
click.echo(f" sdk pin: {profile['sdk']}")
|
|
179
|
+
click.echo()
|
|
180
|
+
|
|
181
|
+
if compat:
|
|
182
|
+
sdk_label = compat.get("sdk_package") or "(SDK-less)"
|
|
183
|
+
click.echo(f" driver compatibility.yaml: {compat['driver']} → {sdk_label}")
|
|
184
|
+
click.echo(f" available profiles: {', '.join(p['name'] for p in compat['profiles'])}")
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _check_all_local() -> dict:
|
|
188
|
+
"""Aggregate safe_detect_installed() across every registered driver.
|
|
189
|
+
|
|
190
|
+
Returns a flat list of solver entries. Installed drivers emit one row
|
|
191
|
+
per detected installation (using SolverInstall.to_dict() shape, plus
|
|
192
|
+
status="ok"). Drivers with no installation emit a single stub row
|
|
193
|
+
with status="not_installed". Driver errors are captured as status="error".
|
|
194
|
+
"""
|
|
195
|
+
from sim.compat import safe_detect_installed
|
|
196
|
+
from sim.drivers import iter_drivers
|
|
197
|
+
|
|
198
|
+
rows: list[dict] = []
|
|
199
|
+
for reg_name, driver, import_error in iter_drivers():
|
|
200
|
+
if import_error is not None:
|
|
201
|
+
rows.append({
|
|
202
|
+
"name": reg_name, "status": "error",
|
|
203
|
+
"message": f"{type(import_error).__name__}: {import_error}",
|
|
204
|
+
})
|
|
205
|
+
continue
|
|
206
|
+
name = getattr(driver, "name", driver.__class__.__name__)
|
|
207
|
+
try:
|
|
208
|
+
installs = safe_detect_installed(driver)
|
|
209
|
+
except Exception as e: # should not happen — safe_* already swallows
|
|
210
|
+
rows.append({"name": name, "status": "error", "message": f"{type(e).__name__}: {e}"})
|
|
211
|
+
continue
|
|
212
|
+
if not installs:
|
|
213
|
+
rows.append({"name": name, "status": "not_installed"})
|
|
214
|
+
continue
|
|
215
|
+
for inst in installs:
|
|
216
|
+
entry = inst.to_dict()
|
|
217
|
+
entry["status"] = "ok"
|
|
218
|
+
rows.append(entry)
|
|
219
|
+
|
|
220
|
+
# Stable ordering: alphabetical by driver name, then version descending.
|
|
221
|
+
rows.sort(key=lambda r: (r["name"], _version_sort_key(r.get("version"))))
|
|
222
|
+
return {"ok": True, "data": {"solvers": rows}}
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _version_sort_key(v: str | None) -> tuple:
|
|
226
|
+
"""Sort key that places higher versions first (for same driver name)."""
|
|
227
|
+
if not v:
|
|
228
|
+
return (1, "") # unversioned / not_installed entries go last
|
|
229
|
+
return (0, tuple(-int(p) if p.isdigit() else p for p in v.replace("v", "").split(".")))
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _render_check_all(data: dict) -> None:
|
|
233
|
+
"""Pretty-print the aggregated `sim check` output."""
|
|
234
|
+
rows = data.get("solvers", [])
|
|
235
|
+
installed = [r for r in rows if r.get("status") == "ok"]
|
|
236
|
+
missing = [r for r in rows if r.get("status") == "not_installed"]
|
|
237
|
+
errored = [r for r in rows if r.get("status") == "error"]
|
|
238
|
+
|
|
239
|
+
click.echo(f"[sim] check: scanned {len(set(r['name'] for r in rows))} drivers")
|
|
240
|
+
click.echo(f" installed: {len(installed)} not_installed: {len(missing)} error: {len(errored)}")
|
|
241
|
+
click.echo()
|
|
242
|
+
if installed:
|
|
243
|
+
click.echo(" installed:")
|
|
244
|
+
for r in installed:
|
|
245
|
+
ver = r.get("version", "?")
|
|
246
|
+
src = r.get("source", "")
|
|
247
|
+
path = r.get("path", "")
|
|
248
|
+
click.echo(f" {r['name']:<14} {ver:<12} {src:<28} {path}")
|
|
249
|
+
click.echo()
|
|
250
|
+
if errored:
|
|
251
|
+
click.echo(" errors:")
|
|
252
|
+
for r in errored:
|
|
253
|
+
click.echo(f" {r['name']:<14} {r.get('message', '')}")
|
|
254
|
+
click.echo()
|
|
255
|
+
if missing:
|
|
256
|
+
click.echo(f" not installed ({len(missing)}): {', '.join(r['name'] for r in missing)}")
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
@main.command()
|
|
260
|
+
@click.argument("solver", required=False)
|
|
261
|
+
@click.option("--all", "check_all", is_flag=True, default=False,
|
|
262
|
+
help="Explicitly aggregate across all drivers. Same as passing no solver argument.")
|
|
263
|
+
@click.pass_context
|
|
264
|
+
def check(ctx, solver, check_all):
|
|
265
|
+
"""Detect installed versions of a solver and resolve their profile.
|
|
266
|
+
|
|
267
|
+
With SOLVER given, checks that one driver (existing behaviour).
|
|
268
|
+
With no SOLVER (or --all), enumerates every registered driver and
|
|
269
|
+
returns the aggregated installation list.
|
|
270
|
+
|
|
271
|
+
By default scans THIS host. With `--host <ip>` (top-level option),
|
|
272
|
+
asks the remote sim serve to scan its own host.
|
|
273
|
+
"""
|
|
274
|
+
host = ctx.obj["host"]
|
|
275
|
+
port = ctx.obj["port"]
|
|
276
|
+
is_local = _is_local_host(host)
|
|
277
|
+
|
|
278
|
+
if solver is None or check_all:
|
|
279
|
+
if not is_local:
|
|
280
|
+
click.echo("[sim] check --all: remote aggregation not yet implemented; "
|
|
281
|
+
"pass a specific solver name to query a remote host.", err=True)
|
|
282
|
+
sys.exit(2)
|
|
283
|
+
resp = _check_all_local()
|
|
284
|
+
if ctx.obj["json"]:
|
|
285
|
+
click.echo(json_mod.dumps(resp, indent=2, default=str))
|
|
286
|
+
sys.exit(0 if resp.get("ok") else 1)
|
|
287
|
+
_render_check_all(resp["data"])
|
|
288
|
+
sys.exit(0)
|
|
289
|
+
|
|
290
|
+
if is_local:
|
|
291
|
+
resp = _check_local(solver)
|
|
292
|
+
else:
|
|
293
|
+
resp = _check_remote(solver, host, port)
|
|
294
|
+
|
|
295
|
+
if ctx.obj["json"]:
|
|
296
|
+
click.echo(json_mod.dumps(resp, indent=2, default=str))
|
|
297
|
+
sys.exit(0 if resp.get("ok") else 1)
|
|
298
|
+
|
|
299
|
+
if not resp.get("ok"):
|
|
300
|
+
click.echo(f"[sim] check: {resp.get('error', 'unknown error')}", err=True)
|
|
301
|
+
sys.exit(1)
|
|
302
|
+
|
|
303
|
+
_render_check(resp["data"])
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
# ── lint ─────────────────────────────────────────────────────────────────────
|
|
307
|
+
|
|
308
|
+
@main.command()
|
|
309
|
+
@click.argument("script", type=click.Path(exists=True))
|
|
310
|
+
@click.pass_context
|
|
311
|
+
def lint(ctx, script):
|
|
312
|
+
"""Validate a simulation script before execution."""
|
|
313
|
+
script_path = Path(script)
|
|
314
|
+
from sim.drivers import iter_drivers
|
|
315
|
+
|
|
316
|
+
driver = None
|
|
317
|
+
for _name, d, import_error in iter_drivers():
|
|
318
|
+
if import_error is not None or d is None:
|
|
319
|
+
continue
|
|
320
|
+
if d.detect(script_path):
|
|
321
|
+
driver = d
|
|
322
|
+
break
|
|
323
|
+
if driver is None:
|
|
324
|
+
from sim.driver import Diagnostic, LintResult
|
|
325
|
+
result = LintResult(
|
|
326
|
+
ok=False,
|
|
327
|
+
diagnostics=[Diagnostic(
|
|
328
|
+
level="error",
|
|
329
|
+
message=(
|
|
330
|
+
f"No registered driver claims {script_path.name!r}. "
|
|
331
|
+
"Install the matching plugin (e.g. `sim plugin install <solver>`) "
|
|
332
|
+
"or pass `sim run` if you want to attempt execution anyway."
|
|
333
|
+
),
|
|
334
|
+
)],
|
|
335
|
+
)
|
|
336
|
+
else:
|
|
337
|
+
result = driver.lint(script_path)
|
|
338
|
+
if ctx.obj["json"]:
|
|
339
|
+
click.echo(json_mod.dumps(result.to_dict(), indent=2))
|
|
340
|
+
else:
|
|
341
|
+
for d in result.diagnostics:
|
|
342
|
+
symbol = "✓" if d.level == "info" else "⚠" if d.level == "warning" else "✗"
|
|
343
|
+
loc = f" (line {d.line})" if d.line else ""
|
|
344
|
+
click.echo(f" {symbol} {d.message}{loc}")
|
|
345
|
+
click.echo(f"[sim] lint: {'passed' if result.ok else 'failed'}")
|
|
346
|
+
sys.exit(0 if result.ok else 1)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
# ── run (one-shot script) ───────────────────────────────────────────────────
|
|
350
|
+
|
|
351
|
+
@main.command()
|
|
352
|
+
@click.argument("script", type=click.Path(exists=True))
|
|
353
|
+
@click.option("--solver", required=True, help="Solver to execute against.")
|
|
354
|
+
@click.pass_context
|
|
355
|
+
def run(ctx, script, solver):
|
|
356
|
+
"""Execute a simulation script in a subprocess (one-shot)."""
|
|
357
|
+
try:
|
|
358
|
+
driver = get_driver(solver)
|
|
359
|
+
except Exception as e: # noqa: BLE001 — surface lazy-import failures distinctly
|
|
360
|
+
click.echo(f"[sim] error: driver '{solver}' failed to load: {type(e).__name__}: {e}", err=True)
|
|
361
|
+
sys.exit(1)
|
|
362
|
+
if driver is None:
|
|
363
|
+
click.echo(f"[sim] error: no driver for '{solver}'", err=True)
|
|
364
|
+
sys.exit(1)
|
|
365
|
+
|
|
366
|
+
result = execute_script(Path(script), solver=solver, driver=driver)
|
|
367
|
+
parsed = driver.parse_output(result.stdout)
|
|
368
|
+
|
|
369
|
+
run_id = _history.append({
|
|
370
|
+
"cwd": str(Path.cwd()),
|
|
371
|
+
"solver": solver,
|
|
372
|
+
"session_id": "", # one-shot runs have no session
|
|
373
|
+
"kind": "run",
|
|
374
|
+
"label": Path(script).name,
|
|
375
|
+
"script": str(script),
|
|
376
|
+
"ok": result.exit_code == 0,
|
|
377
|
+
"duration_ms": int(result.duration_s * 1000),
|
|
378
|
+
"error": (result.stderr or None) if result.exit_code != 0 else None,
|
|
379
|
+
"parsed_output": parsed,
|
|
380
|
+
"workspace_delta": result.workspace_delta,
|
|
381
|
+
})
|
|
382
|
+
|
|
383
|
+
# Persist raw stdout/stderr to disk so the agent can use grep/tail/awk
|
|
384
|
+
# directly without going through `sim logs --field`. Path is
|
|
385
|
+
# deterministic (`<sim_home>/runs/<id>.{stdout,stderr}`) so
|
|
386
|
+
# `sim logs <id> --field stdout` can find it without us storing the
|
|
387
|
+
# path in history.jsonl.
|
|
388
|
+
stdout_path, stderr_path = _write_run_outputs(run_id, result)
|
|
389
|
+
|
|
390
|
+
if ctx.obj["json"]:
|
|
391
|
+
data = result.to_dict()
|
|
392
|
+
data["id"] = run_id
|
|
393
|
+
data["parsed_output"] = parsed
|
|
394
|
+
data["stdout_path"] = str(stdout_path) if stdout_path else None
|
|
395
|
+
data["stderr_path"] = str(stderr_path) if stderr_path else None
|
|
396
|
+
click.echo(json_mod.dumps(data, indent=2))
|
|
397
|
+
else:
|
|
398
|
+
status = "converged" if result.ok else "failed"
|
|
399
|
+
click.echo(f"[sim] run: {script} via {solver}")
|
|
400
|
+
click.echo(f"[sim] status: {status} ({result.duration_s}s)")
|
|
401
|
+
click.echo(f"[sim] log: saved as #{run_id}")
|
|
402
|
+
# Workspace delta: tell the agent which files this run produced
|
|
403
|
+
# (mesh, time directories, log.simpleFoam, postProcessing, …).
|
|
404
|
+
# ALWAYS print, not just on failure: agents need this to know
|
|
405
|
+
# where to look for KPIs even when the run succeeded. Gating it
|
|
406
|
+
# on failure forces successful agents to guess and `ls` blindly.
|
|
407
|
+
_print_workspace_delta(result.workspace_delta)
|
|
408
|
+
if result.exit_code != 0:
|
|
409
|
+
# Stdout/stderr tail is debugging info; surfaces inline only
|
|
410
|
+
# on failure so successful runs don't dump 10K log lines
|
|
411
|
+
# into the agent's context. Full content is in the raw files
|
|
412
|
+
# listed by _print_followup_hints below either way.
|
|
413
|
+
tail_lines = 20
|
|
414
|
+
if result.stderr:
|
|
415
|
+
stderr_tail = "\n".join(result.stderr.splitlines()[-tail_lines:])
|
|
416
|
+
click.echo(f"[sim] stderr (last {tail_lines} lines):\n{stderr_tail}")
|
|
417
|
+
if result.stdout:
|
|
418
|
+
stdout_tail = "\n".join(result.stdout.splitlines()[-tail_lines:])
|
|
419
|
+
click.echo(f"[sim] stdout (last {tail_lines} lines):\n{stdout_tail}")
|
|
420
|
+
# Drill-in hints: where to find the full run record + any
|
|
421
|
+
# workspace files that look like solver logs. ALWAYS print:
|
|
422
|
+
# successful runs need to point the agent at log.simpleFoam
|
|
423
|
+
# (for KPI extraction) just as much as failed ones do (for
|
|
424
|
+
# debugging). Same hint, different motivation.
|
|
425
|
+
_print_followup_hints(run_id, stdout_path, stderr_path,
|
|
426
|
+
result.workspace_delta)
|
|
427
|
+
sys.exit(result.exit_code)
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def _write_run_outputs(run_id: str, result):
|
|
431
|
+
"""Persist full stdout/stderr to disk for grep-friendly access.
|
|
432
|
+
|
|
433
|
+
Files land under ``<sim_home>/runs/<id>.{stdout,stderr}``. Empty
|
|
434
|
+
streams are not written (returns None for that side). Failures here
|
|
435
|
+
are swallowed — file persistence must not break the run reporting.
|
|
436
|
+
"""
|
|
437
|
+
from sim.config import sim_home
|
|
438
|
+
runs_dir = sim_home() / "runs"
|
|
439
|
+
try:
|
|
440
|
+
runs_dir.mkdir(parents=True, exist_ok=True)
|
|
441
|
+
except OSError:
|
|
442
|
+
return None, None
|
|
443
|
+
stdout_path = stderr_path = None
|
|
444
|
+
if result.stdout:
|
|
445
|
+
stdout_path = runs_dir / f"{run_id}.stdout"
|
|
446
|
+
try:
|
|
447
|
+
stdout_path.write_text(result.stdout, encoding="utf-8")
|
|
448
|
+
except OSError:
|
|
449
|
+
stdout_path = None
|
|
450
|
+
if result.stderr:
|
|
451
|
+
stderr_path = runs_dir / f"{run_id}.stderr"
|
|
452
|
+
try:
|
|
453
|
+
stderr_path.write_text(result.stderr, encoding="utf-8")
|
|
454
|
+
except OSError:
|
|
455
|
+
stderr_path = None
|
|
456
|
+
return stdout_path, stderr_path
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _print_workspace_delta(delta, max_inline: int = 10):
|
|
460
|
+
"""Print up to ``max_inline`` workspace changes; mention overflow."""
|
|
461
|
+
if not delta:
|
|
462
|
+
return
|
|
463
|
+
click.echo(f"[sim] workspace files written ({len(delta)}):")
|
|
464
|
+
for entry in delta[:max_inline]:
|
|
465
|
+
kb = entry["size"] / 1024
|
|
466
|
+
size = f"{kb:.1f} KB" if kb >= 1 else f"{entry['size']} B"
|
|
467
|
+
click.echo(f" {entry['kind']:8s} {entry['path']} ({size})")
|
|
468
|
+
if len(delta) > max_inline:
|
|
469
|
+
click.echo(f" ... and {len(delta) - max_inline} more")
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def _print_followup_hints(run_id, stdout_path, stderr_path, delta):
|
|
473
|
+
"""Tell the agent how to drill in further without guessing CLI flags."""
|
|
474
|
+
click.echo("[sim] for more detail:")
|
|
475
|
+
if stdout_path:
|
|
476
|
+
click.echo(f" cat {stdout_path} # full stdout (grep-friendly)")
|
|
477
|
+
if stderr_path:
|
|
478
|
+
click.echo(f" cat {stderr_path} # full stderr")
|
|
479
|
+
click.echo(f" sim logs {run_id} # all fields summary")
|
|
480
|
+
click.echo(f" sim logs {run_id} --field workspace # full file list")
|
|
481
|
+
if delta:
|
|
482
|
+
# Suggest the largest workspace file as a likely diagnostic source.
|
|
483
|
+
click.echo(f" cat {delta[0]['path']} # likely solver log (largest write)")
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
# ── connect (persistent session) ────────────────────────────────────────────
|
|
487
|
+
|
|
488
|
+
@main.command()
|
|
489
|
+
@click.option("--solver", required=True, help="Solver name (e.g. fluent).")
|
|
490
|
+
@click.option("--mode", default="meshing", type=click.Choice(["meshing", "solver"]))
|
|
491
|
+
@click.option("--ui-mode", default="no_gui", type=click.Choice(["no_gui", "gui"]))
|
|
492
|
+
@click.option("--processors", default=1, type=int)
|
|
493
|
+
@click.option("--workspace", default=None,
|
|
494
|
+
help="Solver-specific working dir (e.g. flotherm FLOUSERDIR).")
|
|
495
|
+
@click.pass_context
|
|
496
|
+
def connect(ctx, solver, mode, ui_mode, processors, workspace):
|
|
497
|
+
"""Launch a solver and hold a persistent session."""
|
|
498
|
+
from sim.session import SessionClient
|
|
499
|
+
|
|
500
|
+
client = SessionClient(host=ctx.obj["host"], port=ctx.obj["port"],
|
|
501
|
+
session_id=ctx.obj.get("session"))
|
|
502
|
+
result = client.connect(
|
|
503
|
+
solver=solver,
|
|
504
|
+
mode=mode,
|
|
505
|
+
ui_mode=ui_mode,
|
|
506
|
+
processors=processors,
|
|
507
|
+
workspace=workspace,
|
|
508
|
+
)
|
|
509
|
+
|
|
510
|
+
if ctx.obj["json"]:
|
|
511
|
+
click.echo(json_mod.dumps(result, indent=2, default=str))
|
|
512
|
+
else:
|
|
513
|
+
if result.get("ok"):
|
|
514
|
+
data = result.get("data") or {}
|
|
515
|
+
sid = data.get("session_id", "?")
|
|
516
|
+
click.echo(f"[sim] connect: session ready (id={sid})")
|
|
517
|
+
click.echo(f"[sim] hint: use `sim --session {sid} ...` or set SIM_SESSION={sid}")
|
|
518
|
+
if data:
|
|
519
|
+
click.echo(json_mod.dumps(data, indent=4, default=str))
|
|
520
|
+
else:
|
|
521
|
+
click.echo(f"[sim] connect: failed - {result.get('error', 'unknown')}", err=True)
|
|
522
|
+
sys.exit(1)
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
# ── exec (snippet in live session) ──────────────────────────────────────────
|
|
526
|
+
|
|
527
|
+
@main.command(name="exec")
|
|
528
|
+
@click.argument("code", required=False)
|
|
529
|
+
@click.option("--file", "code_file", type=click.Path(exists=True), help="Read code from file.")
|
|
530
|
+
@click.option("--label", default="cli-snippet", help="Label for this execution.")
|
|
531
|
+
@click.pass_context
|
|
532
|
+
def exec_cmd(ctx, code, code_file, label):
|
|
533
|
+
"""Execute a code snippet in the live session."""
|
|
534
|
+
if code_file:
|
|
535
|
+
code = Path(code_file).read_text(encoding="utf-8")
|
|
536
|
+
if not code:
|
|
537
|
+
click.echo("[sim] error: provide code as argument or via --file", err=True)
|
|
538
|
+
sys.exit(1)
|
|
539
|
+
|
|
540
|
+
from sim.session import SessionClient
|
|
541
|
+
client = SessionClient(host=ctx.obj["host"], port=ctx.obj["port"],
|
|
542
|
+
session_id=ctx.obj.get("session"))
|
|
543
|
+
result = client.run(code=code, label=label)
|
|
544
|
+
|
|
545
|
+
if ctx.obj["json"]:
|
|
546
|
+
click.echo(json_mod.dumps(result, indent=2, default=str))
|
|
547
|
+
else:
|
|
548
|
+
data = result.get("data", {})
|
|
549
|
+
ok = data.get("ok", False)
|
|
550
|
+
status = "OK" if ok else "FAIL"
|
|
551
|
+
click.echo(f" [{status}] label={label!r} elapsed={data.get('elapsed_s', 0)}s")
|
|
552
|
+
if data.get("stdout"):
|
|
553
|
+
for line in data["stdout"].rstrip().splitlines():
|
|
554
|
+
click.echo(f" stdout: {line}")
|
|
555
|
+
if data.get("stderr"):
|
|
556
|
+
for line in data["stderr"].rstrip().splitlines():
|
|
557
|
+
click.echo(f" stderr: {line}")
|
|
558
|
+
if data.get("error"):
|
|
559
|
+
click.echo(f" error: {data['error']}")
|
|
560
|
+
if data.get("result") is not None:
|
|
561
|
+
click.echo(f" result: {data['result']}")
|
|
562
|
+
if not ok:
|
|
563
|
+
sys.exit(2)
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
# ── inspect (live session state) ─────────────────────────────────────────────
|
|
567
|
+
|
|
568
|
+
@main.command()
|
|
569
|
+
@click.argument("name", default="session.summary")
|
|
570
|
+
@click.pass_context
|
|
571
|
+
def inspect(ctx, name):
|
|
572
|
+
"""Query live session state.
|
|
573
|
+
|
|
574
|
+
Common targets across all drivers:
|
|
575
|
+
session.summary, session.versions, session.mode, last.result, workflow.summary
|
|
576
|
+
|
|
577
|
+
Driver-specific targets (resolved by the driver's query() method):
|
|
578
|
+
ls_dyna: deck.summary, deck.text, workdir.files, results.summary
|
|
579
|
+
mechanical: mechanical.project_directory, mechanical.files, mechanical.product_info
|
|
580
|
+
fluent: field.catalog, workflow.summary
|
|
581
|
+
...
|
|
582
|
+
"""
|
|
583
|
+
from sim.session import SessionClient
|
|
584
|
+
client = SessionClient(host=ctx.obj["host"], port=ctx.obj["port"],
|
|
585
|
+
session_id=ctx.obj.get("session"))
|
|
586
|
+
result = client.query(name=name)
|
|
587
|
+
|
|
588
|
+
if ctx.obj["json"]:
|
|
589
|
+
click.echo(json_mod.dumps(result, indent=2, default=str))
|
|
590
|
+
else:
|
|
591
|
+
if result.get("ok"):
|
|
592
|
+
click.echo(json_mod.dumps(result["data"], indent=2, default=str))
|
|
593
|
+
else:
|
|
594
|
+
click.echo(f"[sim] error: {result.get('error')}", err=True)
|
|
595
|
+
sys.exit(1)
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
# ── ps (list active sessions) ───────────────────────────────────────────────
|
|
599
|
+
|
|
600
|
+
@main.command()
|
|
601
|
+
@click.pass_context
|
|
602
|
+
def ps(ctx):
|
|
603
|
+
"""List active sessions.
|
|
604
|
+
|
|
605
|
+
Shape: {sessions: [...], default_session, server_pid}. The 'default'
|
|
606
|
+
session is the one that applies to per-session calls when neither
|
|
607
|
+
--session nor X-Sim-Session is set.
|
|
608
|
+
"""
|
|
609
|
+
from sim.session import SessionClient
|
|
610
|
+
client = SessionClient(host=ctx.obj["host"], port=ctx.obj["port"],
|
|
611
|
+
session_id=ctx.obj.get("session"))
|
|
612
|
+
result = client.status()
|
|
613
|
+
|
|
614
|
+
if ctx.obj["json"]:
|
|
615
|
+
click.echo(json_mod.dumps(result, indent=2, default=str))
|
|
616
|
+
return
|
|
617
|
+
|
|
618
|
+
# Server may be unreachable (no 'sessions' key when an error dict is returned).
|
|
619
|
+
if "sessions" not in result:
|
|
620
|
+
click.echo(f"[sim] ps: {result.get('error', 'unreachable')}", err=True)
|
|
621
|
+
sys.exit(1)
|
|
622
|
+
|
|
623
|
+
sessions = result.get("sessions") or []
|
|
624
|
+
default = result.get("default_session")
|
|
625
|
+
if not sessions:
|
|
626
|
+
click.echo("[sim] no active sessions")
|
|
627
|
+
return
|
|
628
|
+
click.echo(f"[sim] {len(sessions)} session(s) — default: {default or '(none; set --session)'}")
|
|
629
|
+
for s in sessions:
|
|
630
|
+
marker = "*" if s["session_id"] == default else " "
|
|
631
|
+
click.echo(
|
|
632
|
+
f" {marker} {s['session_id']:<10} {s['solver']:<10} "
|
|
633
|
+
f"mode={s.get('mode','-')} ui={s.get('ui_mode','-')} "
|
|
634
|
+
f"runs={s.get('run_count', 0)} profile={s.get('profile') or '-'}"
|
|
635
|
+
)
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
# ── disconnect ───────────────────────────────────────────────────────────────
|
|
639
|
+
|
|
640
|
+
@main.command()
|
|
641
|
+
@click.option(
|
|
642
|
+
"--stop-server",
|
|
643
|
+
is_flag=True,
|
|
644
|
+
help="Also stop the sim-server process after disconnecting (use this when "
|
|
645
|
+
"the server was auto-spawned by `sim connect` and you're done with it).",
|
|
646
|
+
)
|
|
647
|
+
@click.pass_context
|
|
648
|
+
def disconnect(ctx, stop_server):
|
|
649
|
+
"""Tear down the active session.
|
|
650
|
+
|
|
651
|
+
By default this only ends the solver session inside sim-server. The
|
|
652
|
+
server process keeps running so subsequent `sim connect` calls are
|
|
653
|
+
instant. Pass --stop-server to also kill the server (or use `sim stop`
|
|
654
|
+
on its own).
|
|
655
|
+
"""
|
|
656
|
+
from sim.session import SessionClient
|
|
657
|
+
client = SessionClient(host=ctx.obj["host"], port=ctx.obj["port"],
|
|
658
|
+
session_id=ctx.obj.get("session"))
|
|
659
|
+
result = client.disconnect()
|
|
660
|
+
|
|
661
|
+
if stop_server:
|
|
662
|
+
# Try to stop the server even if the disconnect failed (e.g. there
|
|
663
|
+
# was no active session) — the user explicitly asked for cleanup.
|
|
664
|
+
stop_result = client.stop()
|
|
665
|
+
# Merge for json output; for human output we just print both lines
|
|
666
|
+
result = {
|
|
667
|
+
"ok": result.get("ok", False) or stop_result.get("ok", False),
|
|
668
|
+
"data": {
|
|
669
|
+
"disconnect": result.get("data") or {"error": result.get("error")},
|
|
670
|
+
"stop": stop_result.get("data") or {"error": stop_result.get("error")},
|
|
671
|
+
},
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
if ctx.obj["json"]:
|
|
675
|
+
click.echo(json_mod.dumps(result, indent=2, default=str))
|
|
676
|
+
else:
|
|
677
|
+
if stop_server:
|
|
678
|
+
click.echo("[sim] disconnected and stopped sim-server")
|
|
679
|
+
elif result.get("ok"):
|
|
680
|
+
sid = result.get("data", {}).get("session_id", "?")
|
|
681
|
+
click.echo(f"[sim] disconnected (session_id={sid})")
|
|
682
|
+
else:
|
|
683
|
+
click.echo(f"[sim] error: {result.get('error')}", err=True)
|
|
684
|
+
sys.exit(1)
|
|
685
|
+
|
|
686
|
+
|
|
687
|
+
# ── stop ─────────────────────────────────────────────────────────────────────
|
|
688
|
+
|
|
689
|
+
@main.command()
|
|
690
|
+
@click.pass_context
|
|
691
|
+
def stop(ctx):
|
|
692
|
+
"""Stop the sim-server process.
|
|
693
|
+
|
|
694
|
+
This is the counterpart to the auto-spawn that `sim connect` does:
|
|
695
|
+
after `sim connect`/`exec`/`disconnect`, run `sim stop` to fully tear
|
|
696
|
+
down the background uvicorn process and free port 7600.
|
|
697
|
+
|
|
698
|
+
Disconnects any active session as part of shutdown — there's no need
|
|
699
|
+
to call `sim disconnect` first.
|
|
700
|
+
"""
|
|
701
|
+
from sim.session import SessionClient
|
|
702
|
+
client = SessionClient(host=ctx.obj["host"], port=ctx.obj["port"],
|
|
703
|
+
session_id=ctx.obj.get("session"))
|
|
704
|
+
result = client.stop()
|
|
705
|
+
|
|
706
|
+
if ctx.obj["json"]:
|
|
707
|
+
click.echo(json_mod.dumps(result, indent=2, default=str))
|
|
708
|
+
else:
|
|
709
|
+
if result.get("ok"):
|
|
710
|
+
data = result.get("data", {})
|
|
711
|
+
sid = data.get("disconnected_session")
|
|
712
|
+
if sid:
|
|
713
|
+
click.echo(f"[sim] stopped sim-server (also disconnected session {sid})")
|
|
714
|
+
else:
|
|
715
|
+
click.echo("[sim] stopped sim-server")
|
|
716
|
+
else:
|
|
717
|
+
click.echo(f"[sim] error: {result.get('error')}", err=True)
|
|
718
|
+
sys.exit(1)
|
|
719
|
+
|
|
720
|
+
|
|
721
|
+
# ── screenshot ───────────────────────────────────────────────────────────────
|
|
722
|
+
|
|
723
|
+
@main.command()
|
|
724
|
+
@click.option("-o", "--output", default="screenshot.png", help="Output file path.")
|
|
725
|
+
@click.pass_context
|
|
726
|
+
def screenshot(ctx, output):
|
|
727
|
+
"""Capture the server desktop and save as PNG."""
|
|
728
|
+
import base64
|
|
729
|
+
from pathlib import Path
|
|
730
|
+
|
|
731
|
+
from sim.session import SessionClient
|
|
732
|
+
client = SessionClient(host=ctx.obj["host"], port=ctx.obj["port"],
|
|
733
|
+
session_id=ctx.obj.get("session"))
|
|
734
|
+
result = client.screenshot()
|
|
735
|
+
|
|
736
|
+
if not result.get("ok"):
|
|
737
|
+
click.echo(f"[sim] error: {result.get('error')}", err=True)
|
|
738
|
+
sys.exit(1)
|
|
739
|
+
|
|
740
|
+
png_bytes = base64.b64decode(result["data"]["base64"])
|
|
741
|
+
out_path = Path(output)
|
|
742
|
+
out_path.write_bytes(png_bytes)
|
|
743
|
+
w, h = result["data"]["width"], result["data"]["height"]
|
|
744
|
+
click.echo(f"[sim] screenshot saved: {out_path} ({w}x{h})")
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
# ── config ───────────────────────────────────────────────────────────────────
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
@main.group()
|
|
751
|
+
def config():
|
|
752
|
+
"""Inspect and manage the two-tier sim config.
|
|
753
|
+
|
|
754
|
+
Resolution order: env var > .sim/config.toml > ~/.sim/config.toml > default.
|
|
755
|
+
With no config files present, behavior is unchanged from pre-config sim.
|
|
756
|
+
"""
|
|
757
|
+
|
|
758
|
+
|
|
759
|
+
@config.command("path")
|
|
760
|
+
@click.pass_context
|
|
761
|
+
def config_path(ctx):
|
|
762
|
+
"""Print the paths of both config files (whether they exist or not)."""
|
|
763
|
+
paths = {
|
|
764
|
+
"global": str(_cfg.global_config_path()),
|
|
765
|
+
"project": str(_cfg.project_config_path()),
|
|
766
|
+
"global_exists": _cfg.global_config_path().is_file(),
|
|
767
|
+
"project_exists": _cfg.project_config_path().is_file(),
|
|
768
|
+
"history": str(_cfg.history_path()),
|
|
769
|
+
}
|
|
770
|
+
if ctx.obj["json"]:
|
|
771
|
+
click.echo(json_mod.dumps(paths, indent=2))
|
|
772
|
+
else:
|
|
773
|
+
mark = lambda b: "(exists)" if b else "(absent)" # noqa: E731
|
|
774
|
+
click.echo(f" global: {paths['global']} {mark(paths['global_exists'])}")
|
|
775
|
+
click.echo(f" project: {paths['project']} {mark(paths['project_exists'])}")
|
|
776
|
+
click.echo(f" history: {paths['history']}")
|
|
777
|
+
|
|
778
|
+
|
|
779
|
+
@config.command("show")
|
|
780
|
+
@click.pass_context
|
|
781
|
+
def config_show(ctx):
|
|
782
|
+
"""Print the merged (effective) config."""
|
|
783
|
+
_cfg.clear_cache()
|
|
784
|
+
merged = _cfg.load_config()
|
|
785
|
+
if ctx.obj["json"]:
|
|
786
|
+
click.echo(json_mod.dumps({
|
|
787
|
+
"merged": merged,
|
|
788
|
+
"server_port": _cfg.resolve_server_port(),
|
|
789
|
+
"server_host": _cfg.resolve_server_host(),
|
|
790
|
+
}, indent=2))
|
|
791
|
+
else:
|
|
792
|
+
click.echo(f" server.host: {_cfg.resolve_server_host()}")
|
|
793
|
+
click.echo(f" server.port: {_cfg.resolve_server_port()}")
|
|
794
|
+
solvers = _cfg.list_solver_pins()
|
|
795
|
+
if solvers:
|
|
796
|
+
click.echo(" solver pins:")
|
|
797
|
+
for name, pin in solvers.items():
|
|
798
|
+
parts = [f"{k}={v!r}" for k, v in pin.items()]
|
|
799
|
+
click.echo(f" {name}: {', '.join(parts)}")
|
|
800
|
+
else:
|
|
801
|
+
click.echo(" solver pins: (none)")
|
|
802
|
+
|
|
803
|
+
|
|
804
|
+
@config.command("init")
|
|
805
|
+
@click.option("--scope", default="project", type=click.Choice(["project", "global"]),
|
|
806
|
+
help="Which config file to create (default: project).")
|
|
807
|
+
@click.pass_context
|
|
808
|
+
def config_init(ctx, scope):
|
|
809
|
+
"""Create a stub config file. Safe: does not overwrite existing files."""
|
|
810
|
+
path = _cfg.init_config_file(scope)
|
|
811
|
+
if ctx.obj["json"]:
|
|
812
|
+
click.echo(json_mod.dumps({"ok": True, "path": str(path), "scope": scope}))
|
|
813
|
+
else:
|
|
814
|
+
click.echo(f"[sim] config: wrote {scope} stub at {path}")
|
|
815
|
+
|
|
816
|
+
|
|
817
|
+
@config.command("validate")
|
|
818
|
+
@click.argument("path", type=click.Path(exists=True, dir_okay=False, path_type=Path),
|
|
819
|
+
required=False)
|
|
820
|
+
@click.pass_context
|
|
821
|
+
def config_validate(ctx, path):
|
|
822
|
+
"""Validate a sim.toml against the schema. Defaults to the current project's sim.toml."""
|
|
823
|
+
target = path or _cfg.project_sim_toml_path()
|
|
824
|
+
errors = _cfg.validate_sim_toml(target)
|
|
825
|
+
out = {"ok": not errors, "path": str(target), "errors": errors}
|
|
826
|
+
if ctx.obj["json"]:
|
|
827
|
+
click.echo(json_mod.dumps(out, indent=2))
|
|
828
|
+
else:
|
|
829
|
+
if not errors:
|
|
830
|
+
click.echo(f"[sim] config validate: {target} OK")
|
|
831
|
+
else:
|
|
832
|
+
click.echo(f"[sim] config validate: {target} FAIL", err=True)
|
|
833
|
+
for e in errors:
|
|
834
|
+
click.echo(f" - {e}", err=True)
|
|
835
|
+
sys.exit(0 if not errors else 2)
|
|
836
|
+
|
|
837
|
+
|
|
838
|
+
# ── init / setup (project bootstrap) ─────────────────────────────────────────
|
|
839
|
+
|
|
840
|
+
|
|
841
|
+
@main.command()
|
|
842
|
+
@click.option("--force", is_flag=True, help="Overwrite an existing sim.toml.")
|
|
843
|
+
@click.pass_context
|
|
844
|
+
def init(ctx, force):
|
|
845
|
+
"""Create a starter sim.toml in the current directory.
|
|
846
|
+
|
|
847
|
+
Idempotent. Use --force to regenerate from the template.
|
|
848
|
+
"""
|
|
849
|
+
path = _cfg.init_sim_toml(force=force)
|
|
850
|
+
out = {"ok": True, "path": str(path), "created": not (path.exists() and not force)}
|
|
851
|
+
if ctx.obj["json"]:
|
|
852
|
+
click.echo(json_mod.dumps(out, indent=2))
|
|
853
|
+
else:
|
|
854
|
+
click.echo(f"[sim] init: {path}")
|
|
855
|
+
|
|
856
|
+
|
|
857
|
+
@main.command()
|
|
858
|
+
@click.option("--config", "config_path", type=click.Path(exists=True, dir_okay=False, path_type=Path),
|
|
859
|
+
default=None, help="Override the sim.toml location.")
|
|
860
|
+
@click.option("--offline", is_flag=True,
|
|
861
|
+
help="Resolve plugins from the cached index only (no network).")
|
|
862
|
+
@click.option("--dry-run", is_flag=True,
|
|
863
|
+
help="Print what would happen without installing anything.")
|
|
864
|
+
@click.pass_context
|
|
865
|
+
def setup(ctx, config_path, offline, dry_run):
|
|
866
|
+
"""Read sim.toml and install / verify everything it declares.
|
|
867
|
+
|
|
868
|
+
Idempotent: re-running after a successful setup is a no-op modulo plugin
|
|
869
|
+
upgrades. Designed to be the *one* command an agent runs to bring a
|
|
870
|
+
fresh checkout into a runnable state.
|
|
871
|
+
"""
|
|
872
|
+
from sim._plugin_install import install_plugin
|
|
873
|
+
|
|
874
|
+
path = config_path or _cfg.project_sim_toml_path()
|
|
875
|
+
errors = _cfg.validate_sim_toml(path) if path.is_file() else ["sim.toml not found"]
|
|
876
|
+
if errors:
|
|
877
|
+
out = {"ok": False, "error_code": "PLUGIN_NOT_FOUND",
|
|
878
|
+
"message": "sim.toml is missing or invalid",
|
|
879
|
+
"errors": errors, "path": str(path)}
|
|
880
|
+
click.echo(json_mod.dumps(out, indent=2) if ctx.obj["json"]
|
|
881
|
+
else f"[sim] setup: error — {out['message']}\n " + "\n ".join(errors),
|
|
882
|
+
err=not ctx.obj["json"])
|
|
883
|
+
sys.exit(2)
|
|
884
|
+
|
|
885
|
+
import sys as _sys
|
|
886
|
+
if sys.version_info >= (3, 11):
|
|
887
|
+
import tomllib as _tomllib
|
|
888
|
+
else:
|
|
889
|
+
import tomli as _tomllib # type: ignore[no-redef]
|
|
890
|
+
data = _tomllib.loads(path.read_text(encoding="utf-8"))
|
|
891
|
+
|
|
892
|
+
plugins = (data.get("sim") or {}).get("plugins") or []
|
|
893
|
+
actions: list[dict] = []
|
|
894
|
+
fail = False
|
|
895
|
+
|
|
896
|
+
for entry in plugins:
|
|
897
|
+
source = _cfg.derive_install_source(entry)
|
|
898
|
+
if dry_run:
|
|
899
|
+
actions.append({"name": entry.get("name"), "source": source, "action": "would-install"})
|
|
900
|
+
continue
|
|
901
|
+
report = install_plugin(source, offline=offline)
|
|
902
|
+
actions.append({
|
|
903
|
+
"name": entry.get("name"),
|
|
904
|
+
"source": source,
|
|
905
|
+
"ok": report.ok,
|
|
906
|
+
"message": report.message,
|
|
907
|
+
})
|
|
908
|
+
if not report.ok:
|
|
909
|
+
fail = True
|
|
910
|
+
|
|
911
|
+
summary = {
|
|
912
|
+
"ok": not fail,
|
|
913
|
+
"path": str(path),
|
|
914
|
+
"dry_run": dry_run,
|
|
915
|
+
"plugins": actions,
|
|
916
|
+
}
|
|
917
|
+
if ctx.obj["json"]:
|
|
918
|
+
click.echo(json_mod.dumps(summary, indent=2))
|
|
919
|
+
else:
|
|
920
|
+
verb = "would install" if dry_run else "installed"
|
|
921
|
+
click.echo(f"[sim] setup: {verb} {len(actions)} plugin(s) from {path}")
|
|
922
|
+
for a in actions:
|
|
923
|
+
mark = "OK" if a.get("ok", True) else "FAIL"
|
|
924
|
+
click.echo(f" [{mark}] {a['name']} ← {a['source']}")
|
|
925
|
+
if a.get("message") and not a.get("ok", True):
|
|
926
|
+
click.echo(f" {a['message']}")
|
|
927
|
+
sys.exit(0 if not fail else 4)
|
|
928
|
+
|
|
929
|
+
|
|
930
|
+
# ── plugin (manage installed sim plugins) ────────────────────────────────────
|
|
931
|
+
|
|
932
|
+
|
|
933
|
+
@main.group()
|
|
934
|
+
def plugin():
|
|
935
|
+
"""Manage installed sim plugins (drivers + bundled skills).
|
|
936
|
+
|
|
937
|
+
Plugins extend sim with additional solvers. Each plugin ships its
|
|
938
|
+
driver + skill in one wheel; see docs/plugin-install.md for the install
|
|
939
|
+
flows (online by name, local wheel, air-gapped bundle, etc.).
|
|
940
|
+
"""
|
|
941
|
+
|
|
942
|
+
|
|
943
|
+
@plugin.command("list")
|
|
944
|
+
@click.pass_context
|
|
945
|
+
def plugin_list(ctx):
|
|
946
|
+
"""List every plugin currently registered with sim."""
|
|
947
|
+
from sim import plugins as _plugins
|
|
948
|
+
|
|
949
|
+
rows = _plugins.list_installed_plugins()
|
|
950
|
+
if ctx.obj["json"]:
|
|
951
|
+
click.echo(json_mod.dumps([r.to_dict() for r in rows], indent=2))
|
|
952
|
+
return
|
|
953
|
+
|
|
954
|
+
if not rows:
|
|
955
|
+
click.echo("[sim] plugin list: no plugins registered")
|
|
956
|
+
return
|
|
957
|
+
|
|
958
|
+
click.echo(f"[sim] {len(rows)} plugin(s) registered:")
|
|
959
|
+
for r in rows:
|
|
960
|
+
kind = "(builtin)" if r.builtin else "(plugin)"
|
|
961
|
+
ver = f" {r.version}" if r.version else ""
|
|
962
|
+
pkg = f" [{r.package}{ver}]" if r.package else ""
|
|
963
|
+
skills = " +skills" if r.has_skills else ""
|
|
964
|
+
click.echo(f" {r.name:20s} {kind}{pkg}{skills}")
|
|
965
|
+
if r.summary:
|
|
966
|
+
click.echo(f" {r.summary}")
|
|
967
|
+
|
|
968
|
+
|
|
969
|
+
@plugin.command("info")
|
|
970
|
+
@click.argument("name")
|
|
971
|
+
@click.pass_context
|
|
972
|
+
def plugin_info_cmd(ctx, name):
|
|
973
|
+
"""Show one plugin's metadata + compatibility summary."""
|
|
974
|
+
from sim import plugins as _plugins
|
|
975
|
+
from sim.compat import load_compatibility_by_name
|
|
976
|
+
|
|
977
|
+
rows = {p.name: p for p in _plugins.list_installed_plugins()}
|
|
978
|
+
if name not in rows:
|
|
979
|
+
msg = {"ok": False, "error_code": "PLUGIN_NOT_FOUND",
|
|
980
|
+
"message": f"unknown plugin: {name!r}"}
|
|
981
|
+
click.echo(json_mod.dumps(msg) if ctx.obj["json"] else msg["message"], err=not ctx.obj["json"])
|
|
982
|
+
sys.exit(2)
|
|
983
|
+
|
|
984
|
+
plugin_row = rows[name]
|
|
985
|
+
compat = load_compatibility_by_name(name)
|
|
986
|
+
out = {
|
|
987
|
+
"ok": True,
|
|
988
|
+
"plugin": plugin_row.to_dict(),
|
|
989
|
+
"compatibility": (
|
|
990
|
+
{
|
|
991
|
+
"driver": compat.driver,
|
|
992
|
+
"sdk_package": compat.sdk_package,
|
|
993
|
+
"profiles": [p.to_dict() for p in compat.profiles],
|
|
994
|
+
} if compat else None
|
|
995
|
+
),
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
if ctx.obj["json"]:
|
|
999
|
+
click.echo(json_mod.dumps(out, indent=2))
|
|
1000
|
+
return
|
|
1001
|
+
|
|
1002
|
+
click.echo(f"[sim] plugin: {plugin_row.name}")
|
|
1003
|
+
if plugin_row.solver_name:
|
|
1004
|
+
click.echo(f" solver: {plugin_row.solver_name}")
|
|
1005
|
+
if plugin_row.summary:
|
|
1006
|
+
click.echo(f" summary: {plugin_row.summary}")
|
|
1007
|
+
if plugin_row.package:
|
|
1008
|
+
ver = f" {plugin_row.version}" if plugin_row.version else ""
|
|
1009
|
+
click.echo(f" package: {plugin_row.package}{ver}")
|
|
1010
|
+
click.echo(f" module: {plugin_row.driver_module}")
|
|
1011
|
+
click.echo(f" builtin: {plugin_row.builtin}")
|
|
1012
|
+
click.echo(f" has skills: {plugin_row.has_skills}")
|
|
1013
|
+
if plugin_row.license_class:
|
|
1014
|
+
click.echo(f" license class: {plugin_row.license_class}")
|
|
1015
|
+
if plugin_row.homepage:
|
|
1016
|
+
click.echo(f" homepage: {plugin_row.homepage}")
|
|
1017
|
+
if compat:
|
|
1018
|
+
click.echo(f" profiles: {', '.join(p.name for p in compat.profiles)}")
|
|
1019
|
+
|
|
1020
|
+
|
|
1021
|
+
@plugin.command("install")
|
|
1022
|
+
@click.argument("source")
|
|
1023
|
+
@click.option("-e", "--editable", is_flag=True,
|
|
1024
|
+
help="Editable install (pip install -e). For plugin authors.")
|
|
1025
|
+
@click.option("--upgrade", is_flag=True,
|
|
1026
|
+
help="Pass --upgrade to pip.")
|
|
1027
|
+
@click.option("--offline", is_flag=True,
|
|
1028
|
+
help="Use only the local cached index; no network calls.")
|
|
1029
|
+
@click.option("--no-sync", "no_sync", is_flag=True,
|
|
1030
|
+
help="Skip sync-skills after install.")
|
|
1031
|
+
@click.option("--target", "sync_target", type=click.Path(file_okay=False, path_type=Path),
|
|
1032
|
+
default=None,
|
|
1033
|
+
help="Override sync-skills target dir (default: ./.claude/skills or ~/.claude/skills).")
|
|
1034
|
+
@click.option("--python", "python_exe", default=None,
|
|
1035
|
+
help="Pin the target Python interpreter for the install. "
|
|
1036
|
+
"Defaults to the interpreter running sim — use this "
|
|
1037
|
+
"when sim is on PATH but the desired venv isn't activated.")
|
|
1038
|
+
@click.pass_context
|
|
1039
|
+
def plugin_install(ctx, source, editable, upgrade, offline, no_sync, sync_target,
|
|
1040
|
+
python_exe):
|
|
1041
|
+
"""Install a plugin from any supported source.
|
|
1042
|
+
|
|
1043
|
+
\b
|
|
1044
|
+
Examples:
|
|
1045
|
+
sim plugin install coolprop # by name (online index)
|
|
1046
|
+
sim plugin install coolprop@0.1.0 # pinned version
|
|
1047
|
+
sim plugin install ./sim_plugin_coolprop-0.1.0-py3-none-any.whl
|
|
1048
|
+
sim plugin install ./sim-plugin-coolprop -e # editable, for authors
|
|
1049
|
+
sim plugin install git+https://github.com/svd-ai-lab/sim-plugin-coolprop
|
|
1050
|
+
sim plugin install --offline coolprop # use cached index only
|
|
1051
|
+
sim plugin install coolprop --python /path/to/venv/bin/python
|
|
1052
|
+
"""
|
|
1053
|
+
from sim._plugin_install import install_plugin
|
|
1054
|
+
|
|
1055
|
+
report = install_plugin(
|
|
1056
|
+
source,
|
|
1057
|
+
editable=editable, upgrade=upgrade, offline=offline,
|
|
1058
|
+
sync_target=sync_target, skip_sync=no_sync,
|
|
1059
|
+
python=python_exe,
|
|
1060
|
+
)
|
|
1061
|
+
|
|
1062
|
+
if ctx.obj["json"]:
|
|
1063
|
+
click.echo(json_mod.dumps(report.to_dict(), indent=2))
|
|
1064
|
+
else:
|
|
1065
|
+
if report.ok:
|
|
1066
|
+
click.echo(f"[sim] plugin install: ok ({report.source_kind} → {report.pip_target})")
|
|
1067
|
+
if report.sync_skills:
|
|
1068
|
+
if report.sync_skills.get("ok"):
|
|
1069
|
+
linked = len(report.sync_skills.get("linked", []))
|
|
1070
|
+
copied = len(report.sync_skills.get("copied", []))
|
|
1071
|
+
if linked or copied:
|
|
1072
|
+
click.echo(f"[sim] sync-skills: {linked} linked, {copied} copied")
|
|
1073
|
+
else:
|
|
1074
|
+
click.echo(f"[sim] plugin install: FAIL — {report.message}", err=True)
|
|
1075
|
+
if report.pip_stderr:
|
|
1076
|
+
click.echo(report.pip_stderr.rstrip(), err=True)
|
|
1077
|
+
|
|
1078
|
+
sys.exit(0 if report.ok else 4)
|
|
1079
|
+
|
|
1080
|
+
|
|
1081
|
+
@plugin.command("uninstall")
|
|
1082
|
+
@click.argument("name")
|
|
1083
|
+
@click.option("--python", "python_exe", default=None,
|
|
1084
|
+
help="Pin the target Python interpreter for the uninstall.")
|
|
1085
|
+
@click.pass_context
|
|
1086
|
+
def plugin_uninstall(ctx, name, python_exe):
|
|
1087
|
+
"""Uninstall a plugin and remove its synced skill directory."""
|
|
1088
|
+
from sim._plugin_install import uninstall_plugin
|
|
1089
|
+
|
|
1090
|
+
result = uninstall_plugin(name, python=python_exe)
|
|
1091
|
+
if ctx.obj["json"]:
|
|
1092
|
+
click.echo(json_mod.dumps(result, indent=2))
|
|
1093
|
+
else:
|
|
1094
|
+
if result["ok"]:
|
|
1095
|
+
click.echo(f"[sim] plugin uninstall: removed {result['package']}")
|
|
1096
|
+
else:
|
|
1097
|
+
click.echo(f"[sim] plugin uninstall: FAIL — {result.get('message')}", err=True)
|
|
1098
|
+
sys.exit(0 if result.get("ok") else 4)
|
|
1099
|
+
|
|
1100
|
+
|
|
1101
|
+
@plugin.command("bundle")
|
|
1102
|
+
@click.argument("names", nargs=-1, required=True)
|
|
1103
|
+
@click.option("--output", "-o", type=click.Path(file_okay=False, path_type=Path),
|
|
1104
|
+
default=Path("./plugins-bundle"),
|
|
1105
|
+
help="Output directory for wheels + filtered index.json.")
|
|
1106
|
+
@click.pass_context
|
|
1107
|
+
def plugin_bundle(ctx, names, output):
|
|
1108
|
+
"""Download wheels for the named plugins into a directory for offline install.
|
|
1109
|
+
|
|
1110
|
+
\b
|
|
1111
|
+
Examples:
|
|
1112
|
+
sim plugin bundle coolprop simpy gmsh -o ./plugins-bundle/
|
|
1113
|
+
sim plugin install --offline --from-dir ./plugins-bundle/ coolprop
|
|
1114
|
+
"""
|
|
1115
|
+
from sim._plugin_install import bundle_plugins
|
|
1116
|
+
|
|
1117
|
+
result = bundle_plugins(list(names), output)
|
|
1118
|
+
|
|
1119
|
+
if ctx.obj["json"]:
|
|
1120
|
+
click.echo(json_mod.dumps(result, indent=2))
|
|
1121
|
+
else:
|
|
1122
|
+
if result["ok"]:
|
|
1123
|
+
click.echo(f"[sim] plugin bundle: wrote {len(result['fetched'])} plugin(s) to {result['output']}")
|
|
1124
|
+
for n in result["fetched"]:
|
|
1125
|
+
click.echo(f" + {n}")
|
|
1126
|
+
else:
|
|
1127
|
+
click.echo(f"[sim] plugin bundle: PARTIAL — {len(result['fetched'])} ok, {len(result['errors'])} failed", err=True)
|
|
1128
|
+
for err in result["errors"]:
|
|
1129
|
+
click.echo(f" ! {err['name']}: {err['error']}", err=True)
|
|
1130
|
+
sys.exit(0 if result.get("ok") else 4)
|
|
1131
|
+
|
|
1132
|
+
|
|
1133
|
+
@plugin.command("sync-skills")
|
|
1134
|
+
@click.option("--target", type=click.Path(file_okay=False, path_type=Path), default=None,
|
|
1135
|
+
help="Where to materialize plugin _skills/ dirs (default: per-project .claude/skills/).")
|
|
1136
|
+
@click.option("--copy", "copy_mode", is_flag=True,
|
|
1137
|
+
help="Copy instead of symlink (Windows-friendly).")
|
|
1138
|
+
@click.pass_context
|
|
1139
|
+
def plugin_sync_skills(ctx, target, copy_mode):
|
|
1140
|
+
"""Materialize every installed plugin's bundled skill into a target dir.
|
|
1141
|
+
|
|
1142
|
+
Idempotent. Symlinks where supported; ``--copy`` on environments where
|
|
1143
|
+
symlinks aren't available (Windows without dev mode).
|
|
1144
|
+
"""
|
|
1145
|
+
from sim import plugins as _plugins
|
|
1146
|
+
from sim._plugin_install import _default_skills_target
|
|
1147
|
+
|
|
1148
|
+
dest = target or _default_skills_target()
|
|
1149
|
+
result = _plugins.sync_skills_to(dest, copy=copy_mode)
|
|
1150
|
+
|
|
1151
|
+
if ctx.obj["json"]:
|
|
1152
|
+
click.echo(json_mod.dumps(result, indent=2))
|
|
1153
|
+
else:
|
|
1154
|
+
click.echo(f"[sim] plugin sync-skills: target={result['target']}")
|
|
1155
|
+
if result.get("linked"):
|
|
1156
|
+
click.echo(f" linked: {', '.join(result['linked'])}")
|
|
1157
|
+
if result.get("copied"):
|
|
1158
|
+
click.echo(f" copied: {', '.join(result['copied'])}")
|
|
1159
|
+
if result.get("skipped"):
|
|
1160
|
+
click.echo(f" skipped (no _skills bundle): {len(result['skipped'])} plugin(s)")
|
|
1161
|
+
sys.exit(0 if result.get("ok") else 4)
|
|
1162
|
+
|
|
1163
|
+
|
|
1164
|
+
@plugin.command("doctor")
|
|
1165
|
+
@click.argument("name", required=False)
|
|
1166
|
+
@click.option("--all", "all_plugins", is_flag=True,
|
|
1167
|
+
help="Run doctor on every registered plugin.")
|
|
1168
|
+
@click.option("--deep", is_flag=True,
|
|
1169
|
+
help="Also call detect_installed() to check the solver itself.")
|
|
1170
|
+
@click.pass_context
|
|
1171
|
+
def plugin_doctor(ctx, name, all_plugins, deep):
|
|
1172
|
+
"""Validate that a plugin loads, conforms to DriverProtocol, and has skills.
|
|
1173
|
+
|
|
1174
|
+
Exit code is the count of FAILed checks; 0 means clean. Use this in CI
|
|
1175
|
+
to catch plugin-side regressions, and in `sim setup` to verify a fresh
|
|
1176
|
+
install.
|
|
1177
|
+
"""
|
|
1178
|
+
from sim import plugins as _plugins
|
|
1179
|
+
|
|
1180
|
+
if not name and not all_plugins:
|
|
1181
|
+
msg = "specify a plugin name or pass --all"
|
|
1182
|
+
click.echo(json_mod.dumps({"ok": False, "error_code": "PLUGIN_NOT_FOUND",
|
|
1183
|
+
"message": msg}) if ctx.obj["json"] else f"[sim] error: {msg}")
|
|
1184
|
+
sys.exit(2)
|
|
1185
|
+
|
|
1186
|
+
if all_plugins:
|
|
1187
|
+
reports = _plugins.doctor_all(deep=deep)
|
|
1188
|
+
else:
|
|
1189
|
+
reports = [_plugins.doctor(name, deep=deep)]
|
|
1190
|
+
|
|
1191
|
+
fails = sum(r.fail_count for r in reports)
|
|
1192
|
+
|
|
1193
|
+
if ctx.obj["json"]:
|
|
1194
|
+
click.echo(json_mod.dumps({
|
|
1195
|
+
"ok": fails == 0,
|
|
1196
|
+
"fail_count": fails,
|
|
1197
|
+
"warn_count": sum(r.warn_count for r in reports),
|
|
1198
|
+
"reports": [r.to_dict() for r in reports],
|
|
1199
|
+
}, indent=2))
|
|
1200
|
+
else:
|
|
1201
|
+
for r in reports:
|
|
1202
|
+
mark = "OK" if r.ok else f"FAIL ({r.fail_count})"
|
|
1203
|
+
click.echo(f"[sim] plugin doctor {r.name}: {mark}")
|
|
1204
|
+
for c in r.checks:
|
|
1205
|
+
click.echo(f" [{c.status:4s}] {c.label:20s} {c.message}")
|
|
1206
|
+
click.echo(f"\n[sim] {fails} fail(s), {sum(r.warn_count for r in reports)} warn(s) "
|
|
1207
|
+
f"across {len(reports)} plugin(s)")
|
|
1208
|
+
|
|
1209
|
+
sys.exit(fails)
|
|
1210
|
+
|
|
1211
|
+
|
|
1212
|
+
# ── describe (CLI manifest for agents) ───────────────────────────────────────
|
|
1213
|
+
|
|
1214
|
+
|
|
1215
|
+
@main.command()
|
|
1216
|
+
@click.argument("target", required=False)
|
|
1217
|
+
@click.option("--schema", "schema_name", default=None,
|
|
1218
|
+
help="Print one schema by name (RunResult, LintResult, ...).")
|
|
1219
|
+
@click.option("--error-codes", "error_codes_only", is_flag=True,
|
|
1220
|
+
help="Print just the closed enum of error codes.")
|
|
1221
|
+
@click.pass_context
|
|
1222
|
+
def describe(ctx, target, schema_name, error_codes_only):
|
|
1223
|
+
"""Emit the full CLI manifest as JSON.
|
|
1224
|
+
|
|
1225
|
+
Agents call this once at session start to learn every command, flag,
|
|
1226
|
+
error code, and output schema. ``sim describe <command>`` returns one
|
|
1227
|
+
command's contract; ``sim describe --schema RunResult`` returns one
|
|
1228
|
+
type's JSON Schema; ``sim describe --error-codes`` returns the closed
|
|
1229
|
+
enum.
|
|
1230
|
+
"""
|
|
1231
|
+
from sim import describe as _describe
|
|
1232
|
+
|
|
1233
|
+
out: object
|
|
1234
|
+
if error_codes_only:
|
|
1235
|
+
out = [{"code": code, "description": desc}
|
|
1236
|
+
for code, desc in _describe.ERROR_CODES.items()]
|
|
1237
|
+
elif schema_name:
|
|
1238
|
+
schema = _describe.SCHEMAS.get(schema_name)
|
|
1239
|
+
if schema is None:
|
|
1240
|
+
click.echo(json_mod.dumps({
|
|
1241
|
+
"ok": False,
|
|
1242
|
+
"error_code": "PLUGIN_NOT_FOUND", # close-enough generic; schema lookup fail
|
|
1243
|
+
"message": f"unknown schema: {schema_name!r}",
|
|
1244
|
+
}))
|
|
1245
|
+
sys.exit(2)
|
|
1246
|
+
out = schema
|
|
1247
|
+
elif target:
|
|
1248
|
+
entry = _describe.build_command_entry(main, target)
|
|
1249
|
+
if entry is None:
|
|
1250
|
+
click.echo(json_mod.dumps({
|
|
1251
|
+
"ok": False,
|
|
1252
|
+
"error_code": "PLUGIN_NOT_FOUND",
|
|
1253
|
+
"message": f"unknown command: {target!r}",
|
|
1254
|
+
}))
|
|
1255
|
+
sys.exit(2)
|
|
1256
|
+
out = entry
|
|
1257
|
+
else:
|
|
1258
|
+
out = _describe.build_manifest(main, version=__version__)
|
|
1259
|
+
|
|
1260
|
+
# describe is JSON-by-default — agents are the primary consumer.
|
|
1261
|
+
click.echo(json_mod.dumps(out, indent=2, default=str))
|
|
1262
|
+
|
|
1263
|
+
|
|
1264
|
+
# ── logs (run history) ───────────────────────────────────────────────────────
|
|
1265
|
+
|
|
1266
|
+
@main.command()
|
|
1267
|
+
@click.argument("target", required=False)
|
|
1268
|
+
@click.option("--field", help="Extract a specific field from run parsed output.")
|
|
1269
|
+
@click.option("--solver", "filter_solver", help="Only show runs of this solver.")
|
|
1270
|
+
@click.option("--session", "filter_session", help="Only show runs of this session id.")
|
|
1271
|
+
@click.option("--all", "show_all", is_flag=True,
|
|
1272
|
+
help="Show runs across all projects (default: current cwd only).")
|
|
1273
|
+
@click.option("--limit", default=50, type=int, help="Max rows to show (default 50).")
|
|
1274
|
+
@click.pass_context
|
|
1275
|
+
def logs(ctx, target, field, filter_solver, filter_session, show_all, limit):
|
|
1276
|
+
"""Browse global run history at ~/.sim/history.jsonl.
|
|
1277
|
+
|
|
1278
|
+
By default lists runs recorded from the current project (cwd filter).
|
|
1279
|
+
Pass --all for a global view, or filter with --solver / --session.
|
|
1280
|
+
Use `sim logs last` to see the most recent run; `sim logs <run_id>`
|
|
1281
|
+
for a specific one.
|
|
1282
|
+
"""
|
|
1283
|
+
cwd_filter = None if show_all else str(Path.cwd())
|
|
1284
|
+
|
|
1285
|
+
if target:
|
|
1286
|
+
record = _history.get_by_id(target, cwd=cwd_filter)
|
|
1287
|
+
if record is None:
|
|
1288
|
+
click.echo(f"[sim] error: no run '{target}' found", err=True)
|
|
1289
|
+
sys.exit(1)
|
|
1290
|
+
parsed = record.get("parsed_output") or {}
|
|
1291
|
+
if field:
|
|
1292
|
+
# Resolution order:
|
|
1293
|
+
# 1. stdout / stderr → read raw file at <sim_home>/runs/<id>.<field>
|
|
1294
|
+
# (we don't inline these into history.jsonl — too big)
|
|
1295
|
+
# 2. top-level record key (covers workspace_delta, ok, etc.)
|
|
1296
|
+
# 3. parsed_output key (per-driver fields)
|
|
1297
|
+
# Synonym: `workspace` → `workspace_delta` for ergonomics.
|
|
1298
|
+
value = _MISSING = object()
|
|
1299
|
+
if field in ("stdout", "stderr"):
|
|
1300
|
+
from sim.config import sim_home
|
|
1301
|
+
p = sim_home() / "runs" / f"{record.get('run_id')}.{field}"
|
|
1302
|
+
if p.is_file():
|
|
1303
|
+
value = p.read_text(encoding="utf-8")
|
|
1304
|
+
else:
|
|
1305
|
+
value = "" # empty stream OR pre-v3 record without files
|
|
1306
|
+
else:
|
|
1307
|
+
top_alias = {"workspace": "workspace_delta"}
|
|
1308
|
+
key = top_alias.get(field, field)
|
|
1309
|
+
if key in record:
|
|
1310
|
+
value = record[key]
|
|
1311
|
+
elif field in parsed:
|
|
1312
|
+
value = parsed[field]
|
|
1313
|
+
else:
|
|
1314
|
+
click.echo(f"[sim] error: field '{field}' not found", err=True)
|
|
1315
|
+
sys.exit(1)
|
|
1316
|
+
if ctx.obj["json"]:
|
|
1317
|
+
click.echo(json_mod.dumps({field: value}, default=str))
|
|
1318
|
+
else:
|
|
1319
|
+
if isinstance(value, (list, dict)):
|
|
1320
|
+
click.echo(json_mod.dumps(value, indent=2, default=str))
|
|
1321
|
+
else:
|
|
1322
|
+
click.echo(value)
|
|
1323
|
+
else:
|
|
1324
|
+
if ctx.obj["json"]:
|
|
1325
|
+
click.echo(json_mod.dumps(parsed, indent=2))
|
|
1326
|
+
else:
|
|
1327
|
+
for k, v in parsed.items():
|
|
1328
|
+
click.echo(f" {k}: {v}")
|
|
1329
|
+
return
|
|
1330
|
+
|
|
1331
|
+
runs = _history.read(
|
|
1332
|
+
cwd=cwd_filter,
|
|
1333
|
+
solver=filter_solver,
|
|
1334
|
+
session_id=filter_session,
|
|
1335
|
+
limit=limit,
|
|
1336
|
+
)
|
|
1337
|
+
if not runs:
|
|
1338
|
+
if ctx.obj["json"]:
|
|
1339
|
+
click.echo("[]")
|
|
1340
|
+
else:
|
|
1341
|
+
click.echo("[sim] no runs recorded")
|
|
1342
|
+
return
|
|
1343
|
+
if ctx.obj["json"]:
|
|
1344
|
+
click.echo(json_mod.dumps(runs, indent=2))
|
|
1345
|
+
else:
|
|
1346
|
+
for r in runs:
|
|
1347
|
+
status = "ok" if r.get("ok") else "fail"
|
|
1348
|
+
ts = (r.get("ts") or "")[:19]
|
|
1349
|
+
rid = r.get("run_id", "?")
|
|
1350
|
+
solver = r.get("solver") or "-"
|
|
1351
|
+
kind = r.get("kind", "-")
|
|
1352
|
+
label = r.get("script") or r.get("label") or ""
|
|
1353
|
+
click.echo(f" #{rid} {ts} {solver:<10} {kind:<5} {status:<4} {label}")
|