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/describe.py ADDED
@@ -0,0 +1,346 @@
1
+ """CLI manifest emitter for ``sim describe``.
2
+
3
+ Agents call ``sim describe --json`` once at session start to learn the entire
4
+ CLI surface: every command, every flag, every example, every error code,
5
+ every output schema. They then route subsequent calls from that manifest
6
+ without grepping ``--help`` or guessing.
7
+
8
+ The manifest schema is versioned (``schema_version``); breaking changes
9
+ bump the version. Additive changes are free.
10
+
11
+ The manifest is built by introspecting the click app — what's there at
12
+ runtime is what's described, so commands can never silently fall out of
13
+ sync with their documentation.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ from dataclasses import dataclass
18
+ from typing import Any
19
+
20
+ import click
21
+
22
+
23
+ SCHEMA_VERSION = 1
24
+
25
+
26
+ # ── Examples registry ───────────────────────────────────────────────────────
27
+ #
28
+ # Each command's example invocations live here. The describe command merges
29
+ # this with the click introspection. Keep examples short and realistic —
30
+ # agents copy them.
31
+
32
+ _EXAMPLES: dict[str, list[dict[str, str]]] = {
33
+ "serve": [
34
+ {"cmd": "sim serve", "summary": "Start the HTTP server on the default port."},
35
+ {"cmd": "sim serve --host 0.0.0.0 --port 7600 --reload",
36
+ "summary": "Bind to all interfaces with auto-reload (dev mode)."},
37
+ ],
38
+ "check": [
39
+ {"cmd": "sim check --all", "summary": "Detect every installed solver."},
40
+ {"cmd": "sim check coolprop --json", "summary": "Detect one driver, JSON output."},
41
+ ],
42
+ "lint": [
43
+ {"cmd": "sim lint script.py --solver gmsh",
44
+ "summary": "Validate a script before running it."},
45
+ ],
46
+ "run": [
47
+ {"cmd": "sim run script.py --solver gmsh",
48
+ "summary": "Execute a script via the chosen driver."},
49
+ {"cmd": "sim run script.py --solver gmsh --json",
50
+ "summary": "Same, but emit RunResult as JSON for an agent."},
51
+ ],
52
+ "connect": [
53
+ {"cmd": "sim connect --solver gmsh",
54
+ "summary": "Start a persistent solver session."},
55
+ ],
56
+ "exec": [
57
+ {"cmd": 'sim exec "x = 2 + 2; print(x)"',
58
+ "summary": "Run a snippet in the active session."},
59
+ {"cmd": "sim exec --file snippet.py",
60
+ "summary": "Run a file's contents in the active session."},
61
+ ],
62
+ "inspect": [
63
+ {"cmd": "sim inspect session.summary",
64
+ "summary": "Print a summary of the active session's state."},
65
+ ],
66
+ "ps": [
67
+ {"cmd": "sim ps", "summary": "List active sessions."},
68
+ {"cmd": "sim ps --json", "summary": "Same, machine-readable."},
69
+ ],
70
+ "disconnect": [
71
+ {"cmd": "sim disconnect", "summary": "Tear down the active session."},
72
+ {"cmd": "sim disconnect --stop-server", "summary": "Also stop sim-server."},
73
+ ],
74
+ "stop": [
75
+ {"cmd": "sim stop", "summary": "Stop the sim-server process."},
76
+ ],
77
+ "screenshot": [
78
+ {"cmd": "sim screenshot -o desktop.png",
79
+ "summary": "Capture the server's desktop to a PNG file."},
80
+ ],
81
+ "logs": [
82
+ {"cmd": "sim logs --limit 20", "summary": "Show the last 20 history entries."},
83
+ ],
84
+ "config show": [
85
+ {"cmd": "sim config show --json",
86
+ "summary": "Print the resolved config (project + global merged)."},
87
+ ],
88
+ "config init": [
89
+ {"cmd": "sim config init project",
90
+ "summary": "Create a starter .sim/config.toml in the current project."},
91
+ ],
92
+ "config validate": [
93
+ {"cmd": "sim config validate",
94
+ "summary": "Check sim.toml against the schema. Fails with a list of errors."},
95
+ ],
96
+ "config path": [
97
+ {"cmd": "sim config path --json",
98
+ "summary": "Print the location of the global and project config files."},
99
+ ],
100
+ "init": [
101
+ {"cmd": "sim init",
102
+ "summary": "Create a starter sim.toml in the current directory."},
103
+ ],
104
+ "setup": [
105
+ {"cmd": "sim setup --dry-run",
106
+ "summary": "Print what plugins sim would install from sim.toml."},
107
+ {"cmd": "sim setup",
108
+ "summary": "Install every plugin declared in sim.toml."},
109
+ ],
110
+ "describe": [
111
+ {"cmd": "sim describe --json",
112
+ "summary": "Emit the full CLI manifest. Run this once at session start."},
113
+ {"cmd": "sim describe run --json",
114
+ "summary": "Manifest entry for one command."},
115
+ {"cmd": "sim describe --error-codes",
116
+ "summary": "List the closed enum of error codes."},
117
+ ],
118
+ "plugin list": [
119
+ {"cmd": "sim plugin list --json",
120
+ "summary": "List every registered plugin (built-in + external)."},
121
+ ],
122
+ "plugin info": [
123
+ {"cmd": "sim plugin info coolprop",
124
+ "summary": "Show one plugin's metadata and compatibility profiles."},
125
+ ],
126
+ "plugin install": [
127
+ {"cmd": "sim plugin install coolprop",
128
+ "summary": "Install a plugin by name (resolves via the index)."},
129
+ {"cmd": "sim plugin install ./sim_plugin_coolprop-0.1.0-py3-none-any.whl",
130
+ "summary": "Install from a local wheel (offline-friendly)."},
131
+ {"cmd": "sim plugin install ./sim-plugin-coolprop -e",
132
+ "summary": "Editable install for plugin authors."},
133
+ ],
134
+ "plugin uninstall": [
135
+ {"cmd": "sim plugin uninstall coolprop",
136
+ "summary": "Remove a plugin and its synced skill dir."},
137
+ ],
138
+ "plugin bundle": [
139
+ {"cmd": "sim plugin bundle coolprop simpy gmsh -o ./plugins-bundle/",
140
+ "summary": "Fetch wheels into a directory for offline install."},
141
+ ],
142
+ "plugin sync-skills": [
143
+ {"cmd": "sim plugin sync-skills",
144
+ "summary": "Materialize installed plugins' _skills into .claude/skills/."},
145
+ ],
146
+ "plugin doctor": [
147
+ {"cmd": "sim plugin doctor --all --json",
148
+ "summary": "Run doctor on every plugin; exits with the count of FAILs."},
149
+ ],
150
+ }
151
+
152
+
153
+ # ── Error codes (closed enum) ───────────────────────────────────────────────
154
+ #
155
+ # Mirror of docs/agent-readability.md §1 — the source of truth for code
156
+ # strings agents pattern-match. Adding a new code requires updating both
157
+ # this dict and the doc.
158
+
159
+ ERROR_CODES: dict[str, str] = {
160
+ "SOLVER_NOT_INSTALLED":
161
+ "The named driver loaded but the underlying solver is not detected on this host.",
162
+ "SOLVER_NOT_DETECTED_FOR_SCRIPT":
163
+ "A script was given without --solver and no driver claimed it.",
164
+ "LINT_FAILED":
165
+ "sim lint produced at least one error-level diagnostic.",
166
+ "RUN_FAILED":
167
+ "The solver returned non-zero or the driver detected an error in the output.",
168
+ "SESSION_NOT_FOUND":
169
+ "--session <id> does not match any active session on the server.",
170
+ "PLUGIN_NOT_FOUND":
171
+ "sim plugin could not resolve a plugin name (not in the index, no local file).",
172
+ "PLUGIN_INSTALL_FAILED":
173
+ "pip install for a plugin returned non-zero.",
174
+ "PROTOCOL_VIOLATION":
175
+ "A driver returned a value that doesn't match DriverProtocol.",
176
+ "NONINTERACTIVE_INPUT_REQUIRED":
177
+ "--no-interactive is set and the command would otherwise prompt.",
178
+ }
179
+
180
+
181
+ # ── Schema descriptions ─────────────────────────────────────────────────────
182
+ #
183
+ # These mirror the dataclasses in sim.driver. We don't ship full JSON Schema
184
+ # yet (drives complexity for marginal value); a structured description
185
+ # suffices for agents to know "this dict has these keys".
186
+
187
+ SCHEMAS: dict[str, dict[str, Any]] = {
188
+ "RunResult": {
189
+ "type": "object",
190
+ "description": "Result of one solver script execution.",
191
+ "properties": {
192
+ "ok": {"type": "boolean", "description": "exit_code == 0 AND no errors."},
193
+ "exit_code": {"type": "integer"},
194
+ "stdout": {"type": "string"},
195
+ "stderr": {"type": "string"},
196
+ "errors": {"type": "array", "items": {"type": "string"}},
197
+ "duration_s": {"type": "number"},
198
+ "script": {"type": "string"},
199
+ "solver": {"type": "string"},
200
+ "timestamp": {"type": "string", "format": "date-time"},
201
+ "diagnostics": {"type": "array",
202
+ "items": {"type": "object",
203
+ "properties": {"level": {"type": "string"},
204
+ "message": {"type": "string"},
205
+ "line": {"type": ["integer", "null"]}}}},
206
+ "artifacts": {"type": "array", "items": {"type": "object"}},
207
+ "workspace_delta": {
208
+ "type": "array",
209
+ "description": "Files added/modified under cwd during the run.",
210
+ "items": {"type": "object",
211
+ "properties": {"path": {"type": "string"},
212
+ "kind": {"enum": ["added", "modified"]},
213
+ "size": {"type": "integer"}}}},
214
+ },
215
+ },
216
+ "LintResult": {
217
+ "type": "object",
218
+ "properties": {
219
+ "ok": {"type": "boolean"},
220
+ "diagnostics": {"type": "array",
221
+ "items": {"type": "object",
222
+ "properties": {"level": {"enum": ["error", "warning", "info"]},
223
+ "message": {"type": "string"},
224
+ "line": {"type": ["integer", "null"]}}}},
225
+ },
226
+ },
227
+ "ConnectionInfo": {
228
+ "type": "object",
229
+ "properties": {
230
+ "solver": {"type": "string"},
231
+ "version": {"type": ["string", "null"]},
232
+ "status": {"enum": ["ok", "not_installed", "error"]},
233
+ "message": {"type": "string"},
234
+ "solver_version": {"type": ["string", "null"]},
235
+ },
236
+ },
237
+ "ErrorEnvelope": {
238
+ "type": "object",
239
+ "description": "Returned by every command on failure when --json is set.",
240
+ "properties": {
241
+ "ok": {"const": False},
242
+ "error_code": {"enum": list(ERROR_CODES.keys())},
243
+ "message": {"type": "string", "maxLength": 280},
244
+ "details": {"type": "object"},
245
+ },
246
+ },
247
+ "PluginInfo": {
248
+ "type": "object",
249
+ "description": "Lightweight metadata exposed by every plugin via the sim.plugins entry-point group.",
250
+ "properties": {
251
+ "name": {"type": "string"},
252
+ "summary": {"type": "string"},
253
+ "homepage": {"type": "string"},
254
+ "license_class": {"enum": ["oss", "commercial"]},
255
+ "solver_name": {"type": "string"},
256
+ },
257
+ },
258
+ }
259
+
260
+
261
+ # ── Introspection ───────────────────────────────────────────────────────────
262
+
263
+
264
+ def _describe_param(param: click.Parameter) -> dict[str, Any]:
265
+ """Render one click parameter (option/argument) as a manifest entry."""
266
+ kind = "argument" if isinstance(param, click.Argument) else "option"
267
+ out: dict[str, Any] = {
268
+ "kind": kind,
269
+ "name": param.name,
270
+ "required": bool(param.required),
271
+ "multiple": bool(getattr(param, "multiple", False)),
272
+ "is_flag": bool(getattr(param, "is_flag", False)),
273
+ }
274
+ if isinstance(param, click.Option):
275
+ out["flags"] = list(param.opts) + list(param.secondary_opts or [])
276
+ if param.default is not None and not getattr(param, "is_flag", False):
277
+ try:
278
+ out["default"] = param.default if isinstance(
279
+ param.default, (str, int, float, bool, type(None))
280
+ ) else repr(param.default)
281
+ except Exception: # noqa: BLE001 — defensive against weird default reprs
282
+ out["default"] = None
283
+ help_text = getattr(param, "help", None)
284
+ if help_text:
285
+ out["help"] = help_text
286
+ return out
287
+
288
+
289
+ def _describe_command(name: str, cmd: click.Command) -> dict[str, Any]:
290
+ """Render one click command as a manifest entry.
291
+
292
+ Example lookup is normalized so callers can pass either the canonical
293
+ space-separated form (``"config show"``) or the dotted form
294
+ (``"config.show"``).
295
+ """
296
+ canonical = name.replace(".", " ")
297
+ entry: dict[str, Any] = {
298
+ "name": name,
299
+ "summary": (cmd.short_help or (cmd.help or "").splitlines()[0:1] or [""])[0],
300
+ "help": cmd.help or "",
301
+ "params": [_describe_param(p) for p in cmd.params],
302
+ "examples": _EXAMPLES.get(canonical, []),
303
+ }
304
+ return entry
305
+
306
+
307
+ def _walk(group: click.Group, prefix: str = "") -> list[dict[str, Any]]:
308
+ """Walk a click group, yielding manifest entries for every command.
309
+
310
+ Nested groups produce dotted names (``"config show"``).
311
+ """
312
+ entries: list[dict[str, Any]] = []
313
+ for sub_name, sub_cmd in sorted(group.commands.items()):
314
+ full = f"{prefix}{sub_name}" if prefix else sub_name
315
+ if isinstance(sub_cmd, click.Group):
316
+ # Describe the group itself plus walk into it.
317
+ entries.append(_describe_command(full, sub_cmd))
318
+ entries.extend(_walk(sub_cmd, prefix=f"{full} "))
319
+ else:
320
+ entries.append(_describe_command(full, sub_cmd))
321
+ return entries
322
+
323
+
324
+ def build_manifest(app: click.Group, version: str) -> dict[str, Any]:
325
+ """Top-level: build the full manifest for an app."""
326
+ return {
327
+ "schema_version": SCHEMA_VERSION,
328
+ "version": version,
329
+ "commands": _walk(app),
330
+ "schemas": SCHEMAS,
331
+ "error_codes": [
332
+ {"code": code, "description": desc}
333
+ for code, desc in ERROR_CODES.items()
334
+ ],
335
+ }
336
+
337
+
338
+ def build_command_entry(app: click.Group, command_path: str) -> dict[str, Any] | None:
339
+ """Resolve a (possibly dotted/space-separated) command path to one entry."""
340
+ parts = command_path.replace(".", " ").split()
341
+ cur: click.Command | click.Group = app
342
+ for part in parts:
343
+ if not isinstance(cur, click.Group) or part not in cur.commands:
344
+ return None
345
+ cur = cur.commands[part]
346
+ return _describe_command(command_path, cur)
sim/driver.py ADDED
@@ -0,0 +1,190 @@
1
+ """Core abstractions for sim drivers."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass, field
5
+ from pathlib import Path
6
+ from typing import Protocol, runtime_checkable
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class SolverInstall:
11
+ """One detected solver installation on a host.
12
+
13
+ Returned in lists by ``DriverProtocol.detect_installed()``. Pure data;
14
+ no SDK import required to construct or serialize.
15
+ """
16
+ name: str # driver name, e.g. "fluent"
17
+ version: str # detected solver version, normalized e.g. "25.2"
18
+ path: str # filesystem path to the installation root
19
+ source: str # how we found it: "env:AWP_ROOT252" / "registry" / "default-path"
20
+ extra: dict = field(default_factory=dict) # driver-specific metadata
21
+
22
+ def to_dict(self) -> dict:
23
+ return {
24
+ "name": self.name,
25
+ "version": self.version,
26
+ "path": self.path,
27
+ "source": self.source,
28
+ "extra": dict(self.extra),
29
+ }
30
+
31
+
32
+ @dataclass
33
+ class Diagnostic:
34
+ level: str # "error", "warning", "info"
35
+ message: str
36
+ line: int | None = None
37
+
38
+
39
+ @dataclass
40
+ class LintResult:
41
+ ok: bool
42
+ diagnostics: list[Diagnostic] = field(default_factory=list)
43
+
44
+ def to_dict(self) -> dict:
45
+ return {
46
+ "ok": self.ok,
47
+ "diagnostics": [
48
+ {"level": d.level, "message": d.message, "line": d.line}
49
+ for d in self.diagnostics
50
+ ],
51
+ }
52
+
53
+
54
+ @dataclass
55
+ class RunResult:
56
+ exit_code: int
57
+ stdout: str
58
+ stderr: str
59
+ duration_s: float
60
+ script: str
61
+ solver: str
62
+ timestamp: str
63
+ errors: list[str] = field(default_factory=list)
64
+ diagnostics: list[dict] = field(default_factory=list)
65
+ artifacts: list[dict] = field(default_factory=list)
66
+ workspace_delta: list[dict] = field(default_factory=list)
67
+ """Files added/modified under cwd during the run; each entry is
68
+ ``{"path": str, "kind": "added"|"modified", "size": int}``. Captured
69
+ by snapshotting cwd mtimes before and after the subprocess. Solver-
70
+ neutral: doesn't matter what the solver wrote — sim sees the diff."""
71
+
72
+ @property
73
+ def ok(self) -> bool:
74
+ """Comprehensive success check: exit_code AND no detected errors."""
75
+ return self.exit_code == 0 and len(self.errors) == 0
76
+
77
+ def to_dict(self) -> dict:
78
+ return {
79
+ "exit_code": self.exit_code,
80
+ "ok": self.ok,
81
+ "stdout": self.stdout,
82
+ "stderr": self.stderr,
83
+ "errors": self.errors,
84
+ "duration_s": self.duration_s,
85
+ "script": self.script,
86
+ "solver": self.solver,
87
+ "timestamp": self.timestamp,
88
+ "diagnostics": self.diagnostics,
89
+ "artifacts": self.artifacts,
90
+ "workspace_delta": self.workspace_delta,
91
+ }
92
+
93
+
94
+ @dataclass
95
+ class ConnectionInfo:
96
+ solver: str
97
+ version: str | None
98
+ status: str # "ok", "not_installed", "error"
99
+ message: str = ""
100
+ solver_version: str | None = None
101
+
102
+ def to_dict(self) -> dict:
103
+ d = {
104
+ "solver": self.solver,
105
+ "version": self.version,
106
+ "status": self.status,
107
+ "message": self.message,
108
+ }
109
+ if self.solver_version:
110
+ d["solver_version"] = self.solver_version
111
+ return d
112
+
113
+
114
+ @runtime_checkable
115
+ class DriverProtocol(Protocol):
116
+ @property
117
+ def name(self) -> str: ...
118
+ def detect(self, script: Path) -> bool: ...
119
+ def lint(self, script: Path) -> LintResult: ...
120
+ def connect(self) -> ConnectionInfo: ...
121
+ def parse_output(self, stdout: str) -> dict: ...
122
+ def run_file(self, script: Path) -> RunResult: ...
123
+
124
+ def detect_installed(self) -> list[SolverInstall]:
125
+ """Scan THIS host for installations of this driver's solver.
126
+
127
+ Pure Python. Must NOT import the SDK. Must NOT launch the solver.
128
+ Must be safe to call when nothing is installed (returns []).
129
+ Should be cheap (≤ a few hundred ms) — runs in interactive paths.
130
+
131
+ See docs/architecture/version-compat.md §7 for the contract.
132
+ Drivers that have not yet implemented this should return [] so the
133
+ protocol stays runtime_checkable for partial migrations.
134
+ """
135
+ ...
136
+
137
+ # -- Session lifecycle (optional) ----------------------------------------
138
+ # Drivers that support persistent sessions (connect/exec/disconnect)
139
+ # must set supports_session = True and implement launch/run/disconnect.
140
+ #
141
+ # ## Return-shape contract (v1.0)
142
+ #
143
+ # Every session method returns a dict with at least ``{"ok": bool}``.
144
+ # On failure, drivers SHOULD also include ``"error_code"`` (from the
145
+ # closed enum in ``sim.describe.ERROR_CODES``) and ``"message"`` (≤280
146
+ # chars). Long output goes in ``"stdout"`` / ``"stderr"`` / ``"details"``,
147
+ # never inline in ``"message"``. See ``docs/agent-readability.md``.
148
+ #
149
+ # Drivers that don't support sessions should still implement these
150
+ # methods and have launch/run raise NotImplementedError; ``disconnect``
151
+ # is allowed to be a no-op (return ``{"ok": True, "disconnected": True}``).
152
+ # Both behaviors keep the structural protocol check happy.
153
+
154
+ @property
155
+ def supports_session(self) -> bool:
156
+ """Whether this driver supports persistent sessions."""
157
+ ...
158
+
159
+ def launch(self, **kwargs) -> dict:
160
+ """Start a persistent solver session.
161
+
162
+ Required keys: ``ok`` (bool), ``session_id`` (str on success).
163
+ On failure: ``error_code`` (closed enum), ``message`` (≤280 chars).
164
+
165
+ Accepts keyword arguments from the connect request; each driver
166
+ picks what it needs and ignores the rest.
167
+ """
168
+ ...
169
+
170
+ def run(self, code: str, label: str = "") -> dict:
171
+ """Execute code in the active session.
172
+
173
+ Required keys: ``ok`` (bool). Drivers SHOULD also return
174
+ ``stdout``, ``stderr``, ``duration_s`` for parity with RunResult.
175
+ On failure: ``error_code`` (closed enum), ``message``.
176
+
177
+ ``label`` is an opaque tag the agent can use to correlate calls;
178
+ drivers should pass it through to logs but not interpret it.
179
+ """
180
+ ...
181
+
182
+ def disconnect(self) -> dict:
183
+ """Tear down the active session. Must be idempotent.
184
+
185
+ Required keys: ``ok`` (bool), ``disconnected`` (bool).
186
+ Calling on an already-disconnected driver returns
187
+ ``{"ok": True, "disconnected": True}`` — that is, idempotent
188
+ success, not an error.
189
+ """
190
+ ...