cadskill 0.1.0__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.
@@ -0,0 +1,48 @@
1
+ Metadata-Version: 2.5
2
+ Name: cadskill
3
+ Version: 0.1.0
4
+ Summary: 3D CAD for Claude and Codex: build, inspect and export solid models by writing CadQuery scripts.
5
+ Project-URL: Homepage, https://github.com/stepandel/cadskill
6
+ Project-URL: Source, https://github.com/stepandel/cadskill
7
+ Keywords: 3d,cad,cadquery,claude,codex,mcp,step,stl
8
+ Classifier: Operating System :: MacOS
9
+ Classifier: Operating System :: POSIX :: Linux
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Topic :: Multimedia :: Graphics :: 3D Modeling
12
+ Requires-Python: <3.13,>=3.12
13
+ Requires-Dist: cadquery<3,>=2.5
14
+ Requires-Dist: mcp<2,>=1.12
15
+ Description-Content-Type: text/markdown
16
+
17
+ # CadSkill
18
+
19
+ 3D CAD for Claude and Codex. Your agent builds real solid models by writing
20
+ [CadQuery](https://cadquery.readthedocs.io) scripts, checks them with
21
+ measurements and rendered views, and exports STEP, STL and other files.
22
+
23
+ Install on macOS or Linux with one line:
24
+
25
+ ```sh
26
+ curl -LsSf https://raw.githubusercontent.com/stepandel/cadskill/main/install.sh | sh
27
+ ```
28
+
29
+ or, if you already have [uv](https://docs.astral.sh/uv/):
30
+
31
+ ```sh
32
+ uv tool install cadskill
33
+ cadskill install
34
+ ```
35
+
36
+ For Codex, add `--agent codex` to the installer or run:
37
+
38
+ ```sh
39
+ cadskill install --agent codex
40
+ ```
41
+
42
+ This installs the skill into `~/.agents/skills/cadskill`; add `--project`
43
+ to use `./.agents/skills/cadskill` instead. Then start a new Codex session
44
+ and ask it to model a part, or invoke `$cadskill` explicitly.
45
+
46
+ This package provides two commands: `cadskill`, which your agent runs from a
47
+ shell, and `cadskill-mcp`, an MCP server with the same tools. See the
48
+ [project page](https://github.com/stepandel/cadskill) for everything else.
@@ -0,0 +1,13 @@
1
+ cadskill_mcp/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ cadskill_mcp/cli.py,sha256=wyPhamCAPKM3MsMzb2ijW_DtNhZHKV3ovQZRk2cSycA,21659
3
+ cadskill_mcp/daemon.py,sha256=t5HVek54WQSiJ9HqgoW4gl0uilzkIBndzybdSp-F7UI,4864
4
+ cadskill_mcp/runner.py,sha256=rizjwAafWNB9EZDme2Fm1rzSm8LvyR2iSwtyOGJa0Bw,6150
5
+ cadskill_mcp/server.py,sha256=g9Nbp0PYlr1Y7rmU38NeQosfqGFhaplzVI_reSkZ3fE,23005
6
+ cadskill_mcp/store.py,sha256=Ek5VzSqfsJ8YOIEc8SH5uJt8DL1LkYKiTalJtQimj28,3851
7
+ cadskill_mcp/worker.py,sha256=3-WtkOzWeqv1yYxH1otuLaVe-4T0WIVjUcar2dRq6iU,25254
8
+ cadskill_mcp/skill/SKILL.md,sha256=3rGcP-7bMRzPHdW4NWzn8YHKXelAY1UNmDNKwIK5tfU,8564
9
+ cadskill_mcp/static/viewer.html,sha256=hVitcx0qBtKK2vRjlzzDi534prCa247KjnfRGXqnM9M,1248497
10
+ cadskill-0.1.0.dist-info/METADATA,sha256=x2htAN4JY0RiRshWbPMHj3C7eWXIcBYJ1XBi9EDCO2A,1670
11
+ cadskill-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
12
+ cadskill-0.1.0.dist-info/entry_points.txt,sha256=TWiQ3Blom-dIL2bHtYxw355JJtpZJJFPOktF4xYweSI,91
13
+ cadskill-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ cadskill = cadskill_mcp.cli:main
3
+ cadskill-mcp = cadskill_mcp.server:main
File without changes
cadskill_mcp/cli.py ADDED
@@ -0,0 +1,474 @@
1
+ """The `cadskill` command: CadSkill for any agent that can run a shell command.
2
+
3
+ Each subcommand is one tool of the MCP server (server.py), asked of a
4
+ background process that keeps the CAD kernel loaded (daemon.py). Answers are
5
+ printed as text; pictures are written to a file and the path is printed, for
6
+ the agent to open. `cadskill install` puts the skill that teaches all this
7
+ into Claude's or Codex's skills folder.
8
+
9
+ This module imports nothing heavy, so a command costs little more than the
10
+ request it sends.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import base64
16
+ import json
17
+ import os
18
+ import shutil
19
+ import subprocess
20
+ import sys
21
+ import time
22
+ import urllib.error
23
+ import urllib.request
24
+ import webbrowser
25
+ from importlib.metadata import version as _installed
26
+ from pathlib import Path
27
+
28
+ from .store import clean, root
29
+
30
+ VERSION = _installed("cadskill")
31
+ SKILL_NAME = "cadskill"
32
+ INSTALL_LINE = "curl -LsSf https://raw.githubusercontent.com/stepandel/cadskill/main/install.sh | sh"
33
+ SKILL_SOURCE = Path(__file__).parent / "skill"
34
+ WORK_DIR = ".cadskill" # in the current folder: pictures and pages for the agent to open
35
+ START_WAIT = 100 # how long one command waits for a kernel that is still starting
36
+ VIEWS = ["four", "iso", "front", "back", "left", "right", "top", "bottom"]
37
+ FORMATS = ["step", "stl", "3mf", "brep", "glb", "svg", "html"]
38
+
39
+ _local = urllib.request.build_opener(urllib.request.ProxyHandler({})) # never send a local request to a proxy
40
+
41
+
42
+ class Failure(Exception):
43
+ """Something to print and exit 1."""
44
+
45
+
46
+ # ---------------------------------------------------------------- the background process
47
+
48
+ def _state() -> dict | None:
49
+ try:
50
+ return json.loads((root() / ".daemon.json").read_text())
51
+ except (OSError, ValueError):
52
+ return None
53
+
54
+
55
+ def _post(state: dict, tool: str, args: dict, timeout: float) -> dict:
56
+ request = urllib.request.Request(
57
+ state["url"] + "call", data=json.dumps({"tool": tool, "args": args}).encode(),
58
+ headers={"authorization": f"Bearer {state['token']}", "content-type": "application/json"})
59
+ with _local.open(request, timeout=timeout) as response:
60
+ return json.load(response)
61
+
62
+
63
+ def _alive(state: dict | None) -> dict | None:
64
+ if not state:
65
+ return None
66
+ try:
67
+ return _post(state, "ping", {}, 3)
68
+ except (OSError, ValueError, KeyError):
69
+ return None
70
+
71
+
72
+ def _daemon(start: bool = True) -> dict | None:
73
+ """The running background process, started first if need be."""
74
+ state = _state()
75
+ pong = _alive(state)
76
+ if pong and pong.get("version") == VERSION:
77
+ return state
78
+ if pong: # left over from an older install: replace it
79
+ _stop(state)
80
+ if not start:
81
+ return None
82
+ base = root()
83
+ base.mkdir(parents=True, exist_ok=True)
84
+ with open(base / ".daemon.log", "ab") as log:
85
+ subprocess.Popen([sys.executable, "-m", "cadskill_mcp.daemon"], cwd=base, stdin=subprocess.DEVNULL,
86
+ stdout=log, stderr=log, start_new_session=True)
87
+ deadline = time.monotonic() + 30
88
+ while time.monotonic() < deadline:
89
+ time.sleep(0.2)
90
+ state = _state()
91
+ if _alive(state):
92
+ return state
93
+ raise Failure(f"The CadSkill background process did not start. See {base / '.daemon.log'}.")
94
+
95
+
96
+ def _stop(state: dict) -> None:
97
+ try:
98
+ _post(state, "stop", {}, 3)
99
+ except (OSError, ValueError):
100
+ return
101
+ for _ in range(50):
102
+ if not _alive(state):
103
+ return
104
+ time.sleep(0.1)
105
+
106
+
107
+ def call(tool: str, args: dict, timeout: float = 60) -> dict:
108
+ """Ask the background process to run one tool, waiting out a kernel that is still starting."""
109
+ args = {k: v for k, v in args.items() if v is not None}
110
+ state = _daemon()
111
+ began, told = time.monotonic(), False
112
+ while True:
113
+ try:
114
+ reply = _post(state, tool, args, timeout + 60)
115
+ except (OSError, ValueError) as exc:
116
+ raise Failure(f"The CadSkill background process stopped answering ({exc}). Run the command again.") from None
117
+ if not reply.get("starting") or time.monotonic() - began > START_WAIT:
118
+ return reply
119
+ if not told:
120
+ print("The CAD kernel is starting (one to two minutes the first time on a computer). Waiting...",
121
+ file=sys.stderr, flush=True)
122
+ told = True
123
+ time.sleep(3)
124
+
125
+
126
+ # ---------------------------------------------------------------- arguments
127
+
128
+ def _model(value: str) -> str:
129
+ """A model is named directly or by its script: `bracket` and `parts/bracket.py` are the same model."""
130
+ return clean(Path(value).stem if value.endswith(".py") else value)
131
+
132
+
133
+ def _vector(value: str) -> list[float]:
134
+ try:
135
+ numbers = [float(v) for v in value.split(",")]
136
+ except ValueError:
137
+ numbers = []
138
+ if len(numbers) != 3:
139
+ raise argparse.ArgumentTypeError(f"expected three numbers like 0,-1,0, not '{value}'")
140
+ return numbers
141
+
142
+
143
+ def _names(value: str) -> list[str]:
144
+ return [v.strip() for v in value.split(",") if v.strip()]
145
+
146
+
147
+ def _selection(value: str) -> dict:
148
+ """PART, KIND, PART/KIND, any of them with :SELECTOR or @ROWS. E.g. `lid/faces:>Z`, `edges@3,4`, `post`."""
149
+ if value.lstrip().startswith("{"):
150
+ try:
151
+ return json.loads(value)
152
+ except ValueError:
153
+ raise argparse.ArgumentTypeError(f"not valid JSON: {value}") from None
154
+ out: dict = {}
155
+ head, _, selector = value.partition(":")
156
+ if selector:
157
+ out["selector"] = selector
158
+ head, _, rows = head.partition("@")
159
+ if rows:
160
+ try:
161
+ out["index"] = [int(v) for v in rows.split(",")]
162
+ except ValueError:
163
+ raise argparse.ArgumentTypeError(f"rows after @ must be numbers like @3,4, not '{rows}'") from None
164
+ part, _, kind = head.rpartition("/")
165
+ if not part and kind not in ("faces", "edges", "vertices"):
166
+ part, kind = kind, ""
167
+ if kind and kind not in ("faces", "edges", "vertices"):
168
+ raise argparse.ArgumentTypeError(f"'{kind}' is not faces, edges or vertices")
169
+ if part:
170
+ out["part"] = part
171
+ if kind:
172
+ out["kind"] = kind
173
+ if ("selector" in out or "index" in out) and "kind" not in out:
174
+ raise argparse.ArgumentTypeError(f"say what to select in '{value}': faces, edges or vertices before the : or @")
175
+ return out
176
+
177
+
178
+ def _parser() -> argparse.ArgumentParser:
179
+ p = argparse.ArgumentParser(prog="cadskill", description="Build, check and export CAD models from CadQuery scripts.")
180
+ p.add_argument("--version", action="version", version=f"cadskill {VERSION}")
181
+ sub = p.add_subparsers(dest="command", required=True, metavar="command")
182
+ selection = "PART, KIND or PART/KIND, then :SELECTOR or @ROWS. E.g. 'lid/faces:>Z', 'edges@3,4', 'post'."
183
+
184
+ def add(name: str, summary: str, model: bool = True) -> argparse.ArgumentParser:
185
+ s = sub.add_parser(name, help=summary, description=summary)
186
+ if model:
187
+ s.add_argument("model", help="Model name, or its script (bracket.py is the model 'bracket').")
188
+ return s
189
+
190
+ s = add("run", "Build a model from a script and save it as a new version.", model=False)
191
+ s.add_argument("script", help="The CadQuery script. Its file name is the model's name.")
192
+ s.add_argument("--model", help="Model name, if not the script's file name.")
193
+ s.add_argument("--note", help="A few words on what this version changes.")
194
+ s.add_argument("--timeout", type=int, default=60, metavar="SECONDS")
195
+ s.add_argument("--png", help=f"Where to write the picture. Default: {WORK_DIR}/MODEL.png")
196
+
197
+ s = add("render", "Draw the current version. Views have no perspective.")
198
+ s.add_argument("--view", choices=VIEWS, default="four", help="'four' is iso + top + front + right in one picture.")
199
+ s.add_argument("--direction", type=_vector, metavar="X,Y,Z", help="Camera position relative to the model, instead of a view. Write --direction=-1,1,1 when it starts with a minus.")
200
+ s.add_argument("--parts", type=_names, metavar="A,B", help="Only draw these parts.")
201
+ s.add_argument("--section", type=_vector, metavar="X,Y,Z",
202
+ help="Cut with a plane and remove the side this normal points to. 0,-1,0 removes the front half.")
203
+ s.add_argument("--section-at", type=_vector, metavar="X,Y,Z", help="A point on the section plane. Default: the origin.")
204
+ s.add_argument("--highlight", type=_selection, metavar="SELECTION", help="Draw these in red, the rest faded. " + selection)
205
+ s.add_argument("--width", type=int, default=1000)
206
+ s.add_argument("--height", type=int, default=760)
207
+ s.add_argument("--png", help=f"Where to write the picture. Default: {WORK_DIR}/MODEL-render.png")
208
+
209
+ s = add("inspect", "List a part's faces, edges or vertices with position, type, size and direction.")
210
+ s.add_argument("kind", nargs="?", choices=["faces", "edges", "vertices"], default="faces")
211
+ s.add_argument("--part", help="Part name. May be omitted when the model has one part.")
212
+ s.add_argument("--selector", help="CadQuery selector to filter by, e.g. '>Z' or '%%CIRCLE'.")
213
+
214
+ s = add("measure", "Shortest distance between two selections, and the angle when both are flat or straight.")
215
+ s.add_argument("a", type=_selection, metavar="A", help=selection)
216
+ s.add_argument("b", type=_selection, metavar="B")
217
+
218
+ s = add("export", "Write the current version to a file.")
219
+ s.add_argument("format", choices=FORMATS, help="html is the 3D viewer with the model inside: one file, no server.")
220
+ s.add_argument("--parts", type=_names, metavar="A,B", help="Only export these parts.")
221
+ s.add_argument("--out", help=f"Where to write it. Default: the model's exports folder ({WORK_DIR}/MODEL.html for html).")
222
+
223
+ s = add("import", "Copy a STEP, BREP or other file into a model, for its script to load with asset(\"name\").")
224
+ s.add_argument("file")
225
+
226
+ add("show", "Print the current script, its version number and its parts.")
227
+ add("versions", "List a model's saved versions, oldest first.")
228
+ s = add("restore", "Go back to an earlier version: it is rebuilt and saved as the newest.")
229
+ s.add_argument("version", type=int)
230
+ s.add_argument("--to", metavar="SCRIPT", help="Also write the restored script to this file.")
231
+ s.add_argument("--png", help=f"Where to write the picture. Default: {WORK_DIR}/MODEL.png")
232
+ add("models", "List the models saved on this computer.", model=False)
233
+
234
+ s = add("view", "Open the live 3D viewer in the browser. It follows the model as it changes.", model=False)
235
+ s.add_argument("--no-open", action="store_true", help="Only print the address.")
236
+
237
+ s = add("install", "Install the CadSkill skill for Claude or Codex.", model=False)
238
+ s.add_argument("--agent", choices=["claude", "codex"], default="claude", help="Agent to install for. Default: claude.")
239
+ s.add_argument("--project", action="store_true", help="Into this project (.claude/skills or .agents/skills) instead of your home folder.")
240
+ s.add_argument("--allow", action="store_true",
241
+ help="Also let Claude run cadskill commands without asking each time (edits Claude's settings.json).")
242
+ s.add_argument("--desktop", action="store_true",
243
+ help="Also register the MCP server with the Claude desktop app, so chat sessions get the tools.")
244
+ s = add("uninstall", "Remove the CadSkill skill, and the desktop app's entry if there is one.", model=False)
245
+ s.add_argument("--agent", choices=["claude", "codex"], default="claude", help="Agent to remove the skill from. Default: claude.")
246
+ s.add_argument("--project", action="store_true")
247
+ add("status", "Say whether the background process is running.", model=False)
248
+ add("stop", "Stop the background process.", model=False)
249
+ add("mcp", "Run the MCP server on stdio instead (for hosts that use MCP).", model=False)
250
+ return p
251
+
252
+
253
+ # ---------------------------------------------------------------- output
254
+
255
+ def _work_file(name: str) -> Path:
256
+ """A file in ./.cadskill, which is kept out of git."""
257
+ folder = Path(WORK_DIR)
258
+ if not folder.exists():
259
+ folder.mkdir()
260
+ (folder / ".gitignore").write_text("*\n")
261
+ return folder / name
262
+
263
+
264
+ def _finish(reply: dict, png: Path | None = None) -> int:
265
+ """Print an answer; write its picture, if any, to `png`."""
266
+ print(reply["text"], file=sys.stderr if reply["error"] else sys.stdout)
267
+ if reply.get("images") and png is not None:
268
+ png.parent.mkdir(parents=True, exist_ok=True)
269
+ png.write_bytes(base64.b64decode(reply["images"][0]))
270
+ print(f"Picture: {png}")
271
+ return 1 if reply["error"] else 0
272
+
273
+
274
+ # ---------------------------------------------------------------- installing the skill
275
+
276
+ def _claude_home(project: bool) -> Path:
277
+ if project:
278
+ return Path.cwd() / ".claude"
279
+ return Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude").expanduser()
280
+
281
+
282
+ def _skill_target(project: bool, agent: str) -> Path:
283
+ if agent == "codex":
284
+ home = (Path.cwd() if project else Path.home()) / ".agents"
285
+ else:
286
+ home = _claude_home(project)
287
+ return home / "skills" / SKILL_NAME
288
+
289
+
290
+ ALLOW_RULE = "Bash(cadskill:*)"
291
+ DESKTOP_NAME = "cadskill" # the MCP server's name in the desktop app's settings
292
+
293
+
294
+ def _desktop_config() -> Path:
295
+ """The Claude desktop app's settings file, where its local MCP servers are listed."""
296
+ if sys.platform == "darwin":
297
+ base = Path.home() / "Library" / "Application Support"
298
+ elif sys.platform == "win32":
299
+ base = Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming")
300
+ else:
301
+ base = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")
302
+ return base / "Claude" / "claude_desktop_config.json"
303
+
304
+
305
+ def _edit_desktop(change) -> bool:
306
+ """Apply `change` to the desktop app's server list; keep a copy of the file as it was. True if it changed."""
307
+ path = _desktop_config()
308
+ try:
309
+ data = json.loads(path.read_text()) if path.exists() else {}
310
+ except ValueError:
311
+ raise Failure(f"{path} is not valid JSON, so it was left alone.") from None
312
+ before = json.dumps(data, sort_keys=True)
313
+ change(data.setdefault("mcpServers", {}))
314
+ if json.dumps(data, sort_keys=True) == before:
315
+ return False
316
+ path.parent.mkdir(parents=True, exist_ok=True)
317
+ if path.exists():
318
+ shutil.copy2(path, path.with_suffix(".json.before-cadskill"))
319
+ path.write_text(json.dumps(data, indent=2) + "\n")
320
+ return True
321
+
322
+
323
+ def _register_desktop() -> None:
324
+ # The desktop app does not start servers with your shell's PATH, so it needs the full path.
325
+ server = shutil.which("cadskill-mcp") or str(Path(sys.argv[0]).resolve().with_name("cadskill-mcp"))
326
+ if not Path(server).exists():
327
+ raise Failure("Could not find the cadskill-mcp program to register. Install CadSkill with its installer first:\n"
328
+ f" {INSTALL_LINE}")
329
+ _edit_desktop(lambda servers: servers.update({DESKTOP_NAME: {"command": server, "args": []}}))
330
+ print(f"Registered with the Claude desktop app: {_desktop_config()}\n"
331
+ "Quit and reopen the app; the CadSkill tools then appear in chat sessions that use this computer.")
332
+
333
+
334
+ def _install(project: bool, allow: bool, desktop: bool = False, agent: str = "claude") -> int:
335
+ if agent == "codex" and (allow or desktop):
336
+ raise Failure("--allow and --desktop apply to Claude only. For Codex, use `cadskill install --agent codex` "
337
+ "(optionally with --project). Codex manages its own command permissions.")
338
+ target = _skill_target(project, agent)
339
+ if target.exists():
340
+ shutil.rmtree(target)
341
+ shutil.copytree(SKILL_SOURCE, target)
342
+ print(f"Installed the skill: {target}")
343
+
344
+ if allow:
345
+ settings = _claude_home(project) / "settings.json"
346
+ try:
347
+ data = json.loads(settings.read_text()) if settings.exists() else {}
348
+ except ValueError:
349
+ raise Failure(f"{settings} is not valid JSON, so it was left alone. Add \"{ALLOW_RULE}\" to "
350
+ "permissions.allow yourself.") from None
351
+ rules = data.setdefault("permissions", {}).setdefault("allow", [])
352
+ if ALLOW_RULE not in rules:
353
+ rules.append(ALLOW_RULE)
354
+ settings.write_text(json.dumps(data, indent=2) + "\n")
355
+ print(f"Claude may now run cadskill commands without asking: {settings}")
356
+ elif agent == "claude":
357
+ print("Claude will ask before each cadskill command until you allow it. `cadskill install --allow` allows "
358
+ "them all up front; note that building a model runs its script as Python.")
359
+ else:
360
+ print("Codex uses its existing command permissions; no permission settings were changed.")
361
+
362
+ if desktop:
363
+ _register_desktop()
364
+
365
+ found = shutil.which("cadskill")
366
+ label = "Codex" if agent == "codex" else "Claude"
367
+ if not found:
368
+ print(f"\nWarning: `cadskill` is not on your PATH, so {label} will not find it.\n"
369
+ f"Install it for good with\n {INSTALL_LINE}\nthen open a new terminal.")
370
+ print(f"\nStart a new {label} session and ask for a part, e.g. \"model a 60 x 40 mm mounting plate with four M4 holes\".")
371
+ print("The first build on this computer takes a minute or two while the CAD kernel loads.")
372
+ return 0
373
+
374
+
375
+ def _uninstall(project: bool, agent: str = "claude") -> int:
376
+ target = _skill_target(project, agent)
377
+ if target.exists():
378
+ shutil.rmtree(target)
379
+ print(f"Removed {target}")
380
+ else:
381
+ print(f"Nothing to remove at {target}")
382
+ if agent == "claude" and not project and _desktop_config().exists() and _edit_desktop(lambda servers: servers.pop(DESKTOP_NAME, None)):
383
+ print(f"Removed the desktop app's entry: {_desktop_config()}")
384
+ print(f"Your models are untouched in {root()}. To remove the command too: `uv tool uninstall cadskill`.")
385
+ return 0
386
+
387
+
388
+ # ---------------------------------------------------------------- commands
389
+
390
+ def _run_command(a: argparse.Namespace) -> int:
391
+ c = a.command
392
+ if c == "install":
393
+ return _install(a.project, a.allow, a.desktop, a.agent)
394
+ if c == "uninstall":
395
+ return _uninstall(a.project, a.agent)
396
+ if c == "mcp":
397
+ from .server import main as serve
398
+ serve()
399
+ return 0
400
+ if c == "status":
401
+ state = _daemon(start=False)
402
+ if not state:
403
+ print("Not running. It starts with the first command.")
404
+ return 0
405
+ pong = _post(state, "ping", {}, 3)
406
+ print(f"Running at {state['url']} (process {state['pid']}); the CAD kernel is "
407
+ f"{'ready' if pong['ready'] else 'still starting'}. Models are in {root()}.")
408
+ return 0
409
+ if c == "stop":
410
+ state = _state()
411
+ if _alive(state):
412
+ _stop(state)
413
+ print("Stopped.")
414
+ else:
415
+ print("Not running.")
416
+ return 0
417
+ if c == "view":
418
+ url = _daemon()["url"]
419
+ if not a.no_open:
420
+ webbrowser.open(url)
421
+ print(f"The live viewer is at {url} (this computer only). It updates after every build.")
422
+ return 0
423
+ if c == "models":
424
+ return _finish(call("list_models", {}))
425
+
426
+ if c == "run":
427
+ script = Path(a.script)
428
+ if not script.is_file():
429
+ raise Failure(f"There is no script at {script}.")
430
+ model = clean(a.model) if a.model else _model(a.script)
431
+ reply = call("run_model", {"code": script.read_text(), "model": model, "note": a.note,
432
+ "timeout_seconds": a.timeout}, a.timeout)
433
+ return _finish(reply, Path(a.png) if a.png else _work_file(f"{model}.png"))
434
+
435
+ model = _model(a.model)
436
+ if c == "render":
437
+ args = {"model": model, "view": a.view, "direction": a.direction, "parts": a.parts, "section_normal": a.section,
438
+ "section_origin": a.section_at, "highlight": a.highlight, "width": a.width, "height": a.height}
439
+ return _finish(call("render", args), Path(a.png) if a.png else _work_file(f"{model}-render.png"))
440
+ if c == "inspect":
441
+ return _finish(call("inspect", {"model": model, "part": a.part, "kind": a.kind, "selector": a.selector}))
442
+ if c == "measure":
443
+ return _finish(call("measure", {"model": model, "a": a.a, "b": a.b}))
444
+ if c == "export":
445
+ out = a.out or (str(_work_file(f"{model}.html")) if a.format == "html" else None)
446
+ args = {"model": model, "format": a.format, "parts": a.parts, "path": str(Path(out).resolve()) if out else None}
447
+ return _finish(call("export", args, 180))
448
+ if c == "import":
449
+ return _finish(call("import_file", {"model": model, "path": str(Path(a.file).expanduser().resolve())}))
450
+ if c == "show":
451
+ return _finish(call("get_model", {"model": model}))
452
+ if c == "versions":
453
+ return _finish(call("list_versions", {"model": model}))
454
+ if c == "restore":
455
+ reply = call("restore_version", {"model": model, "version": a.version})
456
+ code = _finish(reply, Path(a.png) if a.png else _work_file(f"{model}.png"))
457
+ if code == 0 and a.to:
458
+ Path(a.to).write_text((root() / model / "current.py").read_text())
459
+ print(f"Script written to {a.to}")
460
+ return code
461
+ raise Failure(f"Unknown command {c}.")
462
+
463
+
464
+ def main(argv: list[str] | None = None) -> int:
465
+ args = _parser().parse_args(argv)
466
+ try:
467
+ return _run_command(args)
468
+ except Failure as exc:
469
+ print(exc, file=sys.stderr)
470
+ return 1
471
+
472
+
473
+ if __name__ == "__main__":
474
+ sys.exit(main())