solidcraft 0.51.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- solidcraft/__init__.py +22 -0
- solidcraft/__main__.py +53 -0
- solidcraft/_cli.py +45 -0
- solidcraft/_daemon.py +139 -0
- solidcraft/_encode.py +42 -0
- solidcraft/_generated/__init__.py +3 -0
- solidcraft/_generated/commands.py +15729 -0
- solidcraft/_generated/tools.py +348 -0
- solidcraft/_mcp.py +108 -0
- solidcraft/_session.py +218 -0
- solidcraft/_types.py +28 -0
- solidcraft-0.51.1.dist-info/METADATA +44 -0
- solidcraft-0.51.1.dist-info/RECORD +18 -0
- solidcraft-0.51.1.dist-info/WHEEL +4 -0
- solidcraft-0.51.1.dist-info/entry_points.txt +3 -0
- solidcraft-0.51.1.dist-info/licenses/LICENSE-APACHE +177 -0
- solidcraft-0.51.1.dist-info/licenses/LICENSE-MIT +21 -0
- solidcraft-0.51.1.dist-info/licenses/NOTICE +45 -0
solidcraft/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Drive SolidCraft from Python: every engine command and MCP tool, typed, generated from the build.
|
|
2
|
+
|
|
3
|
+
import solidcraft as sc
|
|
4
|
+
d = sc.session() # the session daemon's design, or a headless one
|
|
5
|
+
d.cmd.solid.box(length=60, width=40, height=8, body_name="Plate")
|
|
6
|
+
d.cmd.solid.hole(position=[30, 20, 8], diameter=6)
|
|
7
|
+
print(d.changes())
|
|
8
|
+
print(sc.find("fillet")) # command ids, labels and parameters
|
|
9
|
+
|
|
10
|
+
Design notes: docs/python-api.md in the SolidCraft repository.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from ._encode import EncodeError
|
|
14
|
+
from ._mcp import SolidCraftError
|
|
15
|
+
from ._session import Session, connect, find, headless, session
|
|
16
|
+
|
|
17
|
+
try:
|
|
18
|
+
from ._generated import VERSION as __version__
|
|
19
|
+
except ImportError: # pragma: no cover
|
|
20
|
+
__version__ = "0"
|
|
21
|
+
|
|
22
|
+
__all__ = ["EncodeError", "Session", "SolidCraftError", "connect", "find", "headless", "session", "__version__"]
|
solidcraft/__main__.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""``solidcraft-session``: start or stop the session daemon that keeps one design across scripts.
|
|
2
|
+
|
|
3
|
+
solidcraft-session serve [--in design.sc] [--allow-path DIR]... [--connect HOST:PORT]
|
|
4
|
+
solidcraft-session stop
|
|
5
|
+
solidcraft-session status
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
|
|
13
|
+
from ._daemon import Remote, daemon_running, serve, session_file
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def main(argv: list[str] | None = None) -> int:
|
|
17
|
+
args = list(sys.argv[1:] if argv is None else argv)
|
|
18
|
+
op = args.pop(0) if args else "status"
|
|
19
|
+
if op == "serve":
|
|
20
|
+
mcp: list[str] = []
|
|
21
|
+
i = 0
|
|
22
|
+
connect = False
|
|
23
|
+
allowed = False
|
|
24
|
+
while i < len(args):
|
|
25
|
+
a = args[i]
|
|
26
|
+
if a in ("--in", "--allow-path", "--connect", "--token") and i + 1 < len(args):
|
|
27
|
+
mcp += [a, args[i + 1]]
|
|
28
|
+
connect = connect or a == "--connect"
|
|
29
|
+
allowed = allowed or a == "--allow-path"
|
|
30
|
+
i += 2
|
|
31
|
+
else:
|
|
32
|
+
print(f"solidcraft-session: unknown argument {a}", file=sys.stderr)
|
|
33
|
+
return 2
|
|
34
|
+
if not connect:
|
|
35
|
+
mcp.insert(0, "--headless")
|
|
36
|
+
if not allowed:
|
|
37
|
+
mcp += ["--allow-path", os.getcwd()]
|
|
38
|
+
serve(mcp)
|
|
39
|
+
return 0
|
|
40
|
+
if op == "stop":
|
|
41
|
+
if daemon_running():
|
|
42
|
+
Remote().stop()
|
|
43
|
+
return 0
|
|
44
|
+
if op == "status":
|
|
45
|
+
up = daemon_running()
|
|
46
|
+
print(f"{'running' if up else 'not running'} ({session_file()})")
|
|
47
|
+
return 0 if up else 1
|
|
48
|
+
print(__doc__, file=sys.stderr)
|
|
49
|
+
return 2
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
if __name__ == "__main__":
|
|
53
|
+
sys.exit(main())
|
solidcraft/_cli.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""``solidcraft``: run the ``solidcraft-cli`` this package finds, with every argument passed on.
|
|
2
|
+
|
|
3
|
+
uvx solidcraft mcp # the MCP server, over stdio
|
|
4
|
+
uvx solidcraft --version
|
|
5
|
+
uvx solidcraft run replay.json --in part.sc
|
|
6
|
+
|
|
7
|
+
The binary is the one the client uses (``find_cli``): ``$SOLIDCRAFT_CLI``, the one bundled in a
|
|
8
|
+
platform wheel, then ``PATH``. With no arguments it prints the CLI's help.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
|
|
17
|
+
from ._mcp import SolidCraftError, find_cli
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def main(argv: list[str] | None = None) -> int:
|
|
21
|
+
args = list(sys.argv[1:] if argv is None else argv) or ["--help"]
|
|
22
|
+
try:
|
|
23
|
+
cli = find_cli()
|
|
24
|
+
except SolidCraftError as e:
|
|
25
|
+
print(f"solidcraft: {e}", file=sys.stderr)
|
|
26
|
+
return 1
|
|
27
|
+
try:
|
|
28
|
+
if os.name != "nt":
|
|
29
|
+
sys.stdout.flush()
|
|
30
|
+
sys.stderr.flush()
|
|
31
|
+
os.execvp(cli, [cli, *args]) # a bare SOLIDCRAFT_CLI is looked up on PATH, as Popen does; replaces this process: stdio, signals and exit code are the CLI's
|
|
32
|
+
p = subprocess.Popen([cli, *args])
|
|
33
|
+
except OSError as e:
|
|
34
|
+
print(f"solidcraft: cannot run {cli}: {e}", file=sys.stderr)
|
|
35
|
+
return 127
|
|
36
|
+
# Windows: Ctrl+C reaches the CLI too (same console); wait for it to finish and pass on its code.
|
|
37
|
+
while True:
|
|
38
|
+
try:
|
|
39
|
+
return p.wait()
|
|
40
|
+
except KeyboardInterrupt:
|
|
41
|
+
continue
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
if __name__ == "__main__":
|
|
45
|
+
sys.exit(main())
|
solidcraft/_daemon.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""The session daemon: one ``solidcraft-cli mcp`` process that several scripts share, so a design
|
|
2
|
+
lives on between them (an agent runs each script as its own process).
|
|
3
|
+
|
|
4
|
+
``solidcraft-session serve`` starts it and writes ``{"port", "token", "pid"}`` to the session file
|
|
5
|
+
(``$SOLIDCRAFT_SESSION``, default ``~/.solidcraft/session.json``, readable by the owner only). A
|
|
6
|
+
script's :func:`solidcraft.session` finds the file and connects to ``127.0.0.1:port``. Each request
|
|
7
|
+
is one JSON line ``{"token", "tool", "args"}``, answered with ``{"result", "notes", "images"}`` or
|
|
8
|
+
``{"error"}``. Only loopback connections that know the token are served."""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import secrets
|
|
15
|
+
import socket
|
|
16
|
+
import socketserver
|
|
17
|
+
import threading
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any, Sequence
|
|
20
|
+
|
|
21
|
+
from ._mcp import Client, SolidCraftError
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def session_file() -> Path:
|
|
25
|
+
env = os.environ.get("SOLIDCRAFT_SESSION")
|
|
26
|
+
return Path(env) if env else Path.home() / ".solidcraft" / "session.json"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def serve(mcp_args: Sequence[str], path: Path | None = None, cli: str | None = None, ready: threading.Event | None = None) -> None:
|
|
30
|
+
"""Serve until a ``stop`` request; ``mcp_args`` go to ``solidcraft-cli mcp``."""
|
|
31
|
+
path = path or session_file()
|
|
32
|
+
client = Client(mcp_args, cli=cli)
|
|
33
|
+
token = secrets.token_hex(16)
|
|
34
|
+
lock = threading.Lock()
|
|
35
|
+
|
|
36
|
+
class Handler(socketserver.StreamRequestHandler):
|
|
37
|
+
def handle(self) -> None:
|
|
38
|
+
for raw in self.rfile:
|
|
39
|
+
try:
|
|
40
|
+
req = json.loads(raw)
|
|
41
|
+
except ValueError:
|
|
42
|
+
return
|
|
43
|
+
if not isinstance(req, dict) or not secrets.compare_digest(str(req.get("token", "")), token):
|
|
44
|
+
self._reply({"error": "bad token"})
|
|
45
|
+
return
|
|
46
|
+
op = req.get("op")
|
|
47
|
+
if op == "info":
|
|
48
|
+
self._reply({"result": {"server_version": client.server_version, "instructions": client.instructions}})
|
|
49
|
+
continue
|
|
50
|
+
if op == "stop":
|
|
51
|
+
self._reply({"result": "stopping"})
|
|
52
|
+
threading.Thread(target=server.shutdown, daemon=True).start()
|
|
53
|
+
return
|
|
54
|
+
try:
|
|
55
|
+
with lock:
|
|
56
|
+
result, notes, images = client.call_tool(str(req.get("tool")), req.get("args") or {})
|
|
57
|
+
self._reply({"result": result, "notes": notes, "images": images})
|
|
58
|
+
except SolidCraftError as e:
|
|
59
|
+
self._reply({"error": str(e)})
|
|
60
|
+
|
|
61
|
+
def _reply(self, msg: dict) -> None:
|
|
62
|
+
self.wfile.write((json.dumps(msg) + "\n").encode("utf-8"))
|
|
63
|
+
self.wfile.flush()
|
|
64
|
+
|
|
65
|
+
class Server(socketserver.ThreadingTCPServer):
|
|
66
|
+
daemon_threads = True
|
|
67
|
+
allow_reuse_address = True
|
|
68
|
+
|
|
69
|
+
server = Server(("127.0.0.1", 0), Handler)
|
|
70
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
71
|
+
tmp = path.with_suffix(".tmp")
|
|
72
|
+
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
73
|
+
with os.fdopen(fd, "w") as f:
|
|
74
|
+
json.dump({"port": server.server_address[1], "token": token, "pid": os.getpid()}, f)
|
|
75
|
+
os.replace(tmp, path)
|
|
76
|
+
if ready is not None:
|
|
77
|
+
ready.set()
|
|
78
|
+
try:
|
|
79
|
+
server.serve_forever()
|
|
80
|
+
finally:
|
|
81
|
+
server.server_close()
|
|
82
|
+
client.close()
|
|
83
|
+
try:
|
|
84
|
+
if json.loads(path.read_text()).get("token") == token:
|
|
85
|
+
path.unlink()
|
|
86
|
+
except (OSError, ValueError):
|
|
87
|
+
pass
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class Remote:
|
|
91
|
+
"""A connection to a running session daemon."""
|
|
92
|
+
|
|
93
|
+
def __init__(self, path: Path | None = None) -> None:
|
|
94
|
+
info = json.loads((path or session_file()).read_text())
|
|
95
|
+
self._token = info["token"]
|
|
96
|
+
self._sock = socket.create_connection(("127.0.0.1", int(info["port"])), timeout=None)
|
|
97
|
+
self._file = self._sock.makefile("rwb")
|
|
98
|
+
about = self._request({"op": "info"})["result"]
|
|
99
|
+
self.server_version: str = about.get("server_version", "")
|
|
100
|
+
self.instructions: str = about.get("instructions", "")
|
|
101
|
+
|
|
102
|
+
def _request(self, msg: dict) -> dict:
|
|
103
|
+
msg["token"] = self._token
|
|
104
|
+
self._file.write((json.dumps(msg) + "\n").encode("utf-8"))
|
|
105
|
+
self._file.flush()
|
|
106
|
+
line = self._file.readline()
|
|
107
|
+
if not line:
|
|
108
|
+
raise SolidCraftError("the SolidCraft session daemon closed the connection")
|
|
109
|
+
reply = json.loads(line)
|
|
110
|
+
if "error" in reply:
|
|
111
|
+
raise SolidCraftError(reply["error"])
|
|
112
|
+
return reply
|
|
113
|
+
|
|
114
|
+
def call_tool(self, name: str, arguments: dict) -> tuple[Any, list[str], list[dict]]:
|
|
115
|
+
r = self._request({"tool": name, "args": arguments})
|
|
116
|
+
return r.get("result"), list(r.get("notes") or []), list(r.get("images") or [])
|
|
117
|
+
|
|
118
|
+
def stop(self) -> None:
|
|
119
|
+
try:
|
|
120
|
+
self._request({"op": "stop"})
|
|
121
|
+
except (SolidCraftError, OSError):
|
|
122
|
+
pass
|
|
123
|
+
|
|
124
|
+
def close(self) -> None:
|
|
125
|
+
try:
|
|
126
|
+
self._file.close()
|
|
127
|
+
self._sock.close()
|
|
128
|
+
except OSError:
|
|
129
|
+
pass
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def daemon_running(path: Path | None = None) -> bool:
|
|
133
|
+
p = path or session_file()
|
|
134
|
+
try:
|
|
135
|
+
info = json.loads(p.read_text())
|
|
136
|
+
with socket.create_connection(("127.0.0.1", int(info["port"])), timeout=1):
|
|
137
|
+
return True
|
|
138
|
+
except (OSError, ValueError, KeyError):
|
|
139
|
+
return False
|
solidcraft/_encode.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Arguments as JSON: NumPy arrays and scalars, pandas Series, tuples and anything else that
|
|
2
|
+
offers ``tolist()`` or ``__float__`` become plain JSON values. The client imports none of those
|
|
3
|
+
libraries."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import math
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class EncodeError(ValueError):
|
|
12
|
+
"""An argument that cannot be sent: a NaN or an infinity, or a value with no JSON form."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def plain(value: Any, where: str = "argument") -> Any:
|
|
16
|
+
"""``value`` as JSON-ready Python data; ``where`` names it in an error."""
|
|
17
|
+
if value is None or isinstance(value, (bool, str)):
|
|
18
|
+
return value
|
|
19
|
+
if isinstance(value, int):
|
|
20
|
+
return value
|
|
21
|
+
if isinstance(value, float):
|
|
22
|
+
if not math.isfinite(value):
|
|
23
|
+
raise EncodeError(f"{where} is {value}; SolidCraft takes finite numbers only")
|
|
24
|
+
return value
|
|
25
|
+
if isinstance(value, dict):
|
|
26
|
+
return {str(k): plain(v, f"{where}[{k!r}]") for k, v in value.items()}
|
|
27
|
+
if isinstance(value, (list, tuple)):
|
|
28
|
+
return [plain(v, f"{where}[{i}]") for i, v in enumerate(value)]
|
|
29
|
+
# A feature or body object of this package passes its name.
|
|
30
|
+
name = getattr(value, "__solidcraft_name__", None)
|
|
31
|
+
if isinstance(name, str):
|
|
32
|
+
return name
|
|
33
|
+
tolist = getattr(value, "tolist", None)
|
|
34
|
+
if callable(tolist): # NumPy arrays and scalars, pandas Series
|
|
35
|
+
return plain(tolist(), where)
|
|
36
|
+
if hasattr(value, "__index__"):
|
|
37
|
+
return int(value.__index__())
|
|
38
|
+
if hasattr(value, "__float__"):
|
|
39
|
+
return plain(float(value), where)
|
|
40
|
+
if hasattr(value, "__iter__"):
|
|
41
|
+
return [plain(v, f"{where}[{i}]") for i, v in enumerate(value)]
|
|
42
|
+
raise EncodeError(f"{where}: a {type(value).__name__} cannot be sent to SolidCraft")
|