simplecadapi 2.2.2__py3-none-any.whl → 2.2.3__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.
- simplecadapi/editor/cli.py +237 -0
- simplecadapi/editor/kernel.py +44 -0
- simplecadapi/editor/server.py +339 -0
- simplecadapi/editor/webui/assets/{index-B-CaJ0Xp.js → index-DL4IZ_W1.js} +2 -2
- simplecadapi/editor/webui/index.html +1 -1
- simplecadapi/skill/resources/docs/skill/SKILL.md +6 -4
- simplecadapi/skill/resources/docs/skill/references/domains/editor-collaboration.md +44 -4
- {simplecadapi-2.2.2.dist-info → simplecadapi-2.2.3.dist-info}/METADATA +13 -15
- {simplecadapi-2.2.2.dist-info → simplecadapi-2.2.3.dist-info}/RECORD +12 -12
- {simplecadapi-2.2.2.dist-info → simplecadapi-2.2.3.dist-info}/WHEEL +0 -0
- {simplecadapi-2.2.2.dist-info → simplecadapi-2.2.3.dist-info}/entry_points.txt +0 -0
- {simplecadapi-2.2.2.dist-info → simplecadapi-2.2.3.dist-info}/licenses/LICENSE +0 -0
simplecadapi/editor/cli.py
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
sca edit path/to/model.py # ... starting at one notebook
|
|
7
7
|
sca edit --port 7180 --no-browser
|
|
8
8
|
sca snapshot [WORKSPACE] # what the person has selected / is looking at
|
|
9
|
+
sca cell ls|get|put|insert|rm|run # edit the cells of the notebook the editor has open
|
|
10
|
+
sca new NAME [--kind part|assembly] # a new notebook; the editor lists it at once
|
|
9
11
|
"""
|
|
10
12
|
|
|
11
13
|
from __future__ import annotations
|
|
@@ -43,6 +45,63 @@ def configure(subparsers: argparse._SubParsersAction) -> None:
|
|
|
43
45
|
snapshot.add_argument("workspace", type=Path, nargs="?", default=Path.cwd())
|
|
44
46
|
snapshot.set_defaults(handler=_snapshot, printer=_print_snapshot)
|
|
45
47
|
|
|
48
|
+
cell = subparsers.add_parser(
|
|
49
|
+
"cell",
|
|
50
|
+
help="read and edit the cells of a notebook through the running editor",
|
|
51
|
+
description="Edit a notebook's cells through the editor that has it open: the page "
|
|
52
|
+
"shows the change live (no reload) and the editor, the one writer of the file, saves "
|
|
53
|
+
"it, so nothing is overwritten. Cells are named by number (see `sca cell ls`), by key "
|
|
54
|
+
"or by id. When the editor is not running, or has another notebook open, `ls` and "
|
|
55
|
+
"`get` read the file and the write commands refuse: edit the file directly then, "
|
|
56
|
+
"nothing else holds it.",
|
|
57
|
+
)
|
|
58
|
+
cell_sub = cell.add_subparsers(dest="cell_command", required=True)
|
|
59
|
+
|
|
60
|
+
def common(parser: argparse.ArgumentParser) -> None:
|
|
61
|
+
parser.add_argument("--notebook", "-n", type=Path, default=None, help="the notebook (default: the one the editor has open)")
|
|
62
|
+
parser.add_argument("--workspace", "-w", type=Path, default=None, help="the workspace the editor serves (default: found from the current directory)")
|
|
63
|
+
|
|
64
|
+
ls = cell_sub.add_parser("ls", help="list the cells with their state")
|
|
65
|
+
common(ls)
|
|
66
|
+
ls.add_argument("--code", action="store_true", help="include each cell's code")
|
|
67
|
+
ls.set_defaults(handler=_cell_ls, printer=_print_json)
|
|
68
|
+
get = cell_sub.add_parser("get", help="print one cell: its code, state, errors and output")
|
|
69
|
+
common(get)
|
|
70
|
+
get.add_argument("cell")
|
|
71
|
+
get.set_defaults(handler=_cell_get, printer=_print_json)
|
|
72
|
+
put = cell_sub.add_parser("put", help="replace a cell's code (the code comes from --file or stdin) and run it")
|
|
73
|
+
common(put)
|
|
74
|
+
put.add_argument("cell")
|
|
75
|
+
put.add_argument("--file", "-f", type=Path, default=None, help="read the code from this file (default: stdin)")
|
|
76
|
+
put.add_argument("--no-run", action="store_true", help="save the code without running the cell")
|
|
77
|
+
put.set_defaults(handler=_cell_put, printer=_print_json)
|
|
78
|
+
insert = cell_sub.add_parser("insert", help="add a cell (the code comes from --file or stdin)")
|
|
79
|
+
common(insert)
|
|
80
|
+
insert.add_argument("--after", default="end", help="a cell, or `start` / `end` (default)")
|
|
81
|
+
insert.add_argument("--name", default=None, help="the cell's function name")
|
|
82
|
+
insert.add_argument("--file", "-f", type=Path, default=None)
|
|
83
|
+
insert.add_argument("--no-run", action="store_true")
|
|
84
|
+
insert.set_defaults(handler=_cell_insert, printer=_print_json)
|
|
85
|
+
rm = cell_sub.add_parser("rm", help="delete a cell")
|
|
86
|
+
common(rm)
|
|
87
|
+
rm.add_argument("cell")
|
|
88
|
+
rm.set_defaults(handler=_cell_rm, printer=_print_json)
|
|
89
|
+
run = cell_sub.add_parser("run", help="run cells (default: all) and what they feed")
|
|
90
|
+
common(run)
|
|
91
|
+
run.add_argument("cells", nargs="*")
|
|
92
|
+
run.set_defaults(handler=_cell_run, printer=_print_json)
|
|
93
|
+
|
|
94
|
+
new = subparsers.add_parser(
|
|
95
|
+
"new",
|
|
96
|
+
help="create a notebook in the workspace (the running editor lists it at once)",
|
|
97
|
+
description="Write a new notebook from the template into WORKSPACE (default: the "
|
|
98
|
+
"current directory). A running editor on that workspace lists it without a reload.",
|
|
99
|
+
)
|
|
100
|
+
new.add_argument("name")
|
|
101
|
+
new.add_argument("--kind", choices=("part", "assembly"), default="part")
|
|
102
|
+
new.add_argument("--workspace", "-w", type=Path, default=None)
|
|
103
|
+
new.set_defaults(handler=_new_notebook, printer=_print_json)
|
|
104
|
+
|
|
46
105
|
|
|
47
106
|
def _execute(args: argparse.Namespace) -> tuple[dict[str, Any], int]:
|
|
48
107
|
try:
|
|
@@ -86,4 +145,182 @@ def _print_snapshot(report: dict[str, Any]) -> None:
|
|
|
86
145
|
print(json.dumps(report, indent=2, ensure_ascii=False))
|
|
87
146
|
|
|
88
147
|
|
|
148
|
+
# -- sca cell / sca new ---------------------------------------------------------
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _print_json(report: dict[str, Any]) -> None:
|
|
152
|
+
import json
|
|
153
|
+
|
|
154
|
+
print(json.dumps(report, indent=2, ensure_ascii=False))
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _find_editor(start: Path) -> tuple[Path, str] | None:
|
|
158
|
+
"""The running editor whose workspace holds *start*: ``(workspace, base url)``."""
|
|
159
|
+
import json
|
|
160
|
+
import urllib.request
|
|
161
|
+
|
|
162
|
+
here = start.expanduser().resolve()
|
|
163
|
+
for directory in (here, *here.parents):
|
|
164
|
+
record = directory / ".sca-editor" / "server.json"
|
|
165
|
+
if not record.is_file():
|
|
166
|
+
continue
|
|
167
|
+
try:
|
|
168
|
+
url = json.loads(record.read_text(encoding="utf-8"))["url"]
|
|
169
|
+
with urllib.request.urlopen(f"{url}/api/health", timeout=1.5):
|
|
170
|
+
pass
|
|
171
|
+
except (OSError, ValueError, KeyError):
|
|
172
|
+
continue # a stale record: the editor is gone
|
|
173
|
+
return directory, str(url)
|
|
174
|
+
return None
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _call(url: str, path: str, body: dict | None = None) -> dict[str, Any]:
|
|
178
|
+
import json
|
|
179
|
+
import urllib.error
|
|
180
|
+
import urllib.request
|
|
181
|
+
|
|
182
|
+
data = None if body is None else json.dumps(body).encode("utf-8")
|
|
183
|
+
request = urllib.request.Request(
|
|
184
|
+
url + path, data=data, headers={"Content-Type": "application/json"}, method="GET" if body is None else "POST"
|
|
185
|
+
)
|
|
186
|
+
try:
|
|
187
|
+
with urllib.request.urlopen(request, timeout=300) as response:
|
|
188
|
+
return json.loads(response.read())
|
|
189
|
+
except urllib.error.HTTPError as error:
|
|
190
|
+
try:
|
|
191
|
+
return json.loads(error.read())
|
|
192
|
+
except ValueError:
|
|
193
|
+
return {"error": f"editor answered {error.code}"}
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _session(args: argparse.Namespace, *, write: bool) -> tuple[str | None, Path | None, str]:
|
|
197
|
+
"""``(editor url or None, notebook path or None, relative notebook name)`` for a cell command."""
|
|
198
|
+
start = args.workspace or (args.notebook.parent if args.notebook else Path.cwd())
|
|
199
|
+
found = _find_editor(start)
|
|
200
|
+
notebook = args.notebook.expanduser().resolve() if args.notebook else None
|
|
201
|
+
if found is None:
|
|
202
|
+
if write:
|
|
203
|
+
raise ValueError(
|
|
204
|
+
"no editor is running on this workspace (start `sca edit`), or edit the notebook file "
|
|
205
|
+
"directly: nothing else holds it"
|
|
206
|
+
)
|
|
207
|
+
if notebook is None:
|
|
208
|
+
raise ValueError("no editor is running here; name the notebook with --notebook")
|
|
209
|
+
return None, notebook, notebook.name
|
|
210
|
+
workspace, url = found
|
|
211
|
+
open_path = _call(url, "/api/cells").get("notebook")
|
|
212
|
+
if notebook is None:
|
|
213
|
+
if open_path is None:
|
|
214
|
+
raise ValueError("the editor has no notebook open")
|
|
215
|
+
return url, workspace / open_path, open_path
|
|
216
|
+
relative = notebook.relative_to(workspace).as_posix() if notebook.is_relative_to(workspace) else notebook.name
|
|
217
|
+
if relative == open_path:
|
|
218
|
+
return url, notebook, relative
|
|
219
|
+
if write:
|
|
220
|
+
raise ValueError(
|
|
221
|
+
f"the editor has {open_path} open, not {relative}: edit {relative} directly "
|
|
222
|
+
"(the editor does not hold it), or open it in the editor first"
|
|
223
|
+
)
|
|
224
|
+
return None, notebook, relative
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _cells_from_file(notebook: Path) -> list[dict[str, Any]]:
|
|
228
|
+
from ..runtime._marimo import parse_notebook
|
|
229
|
+
|
|
230
|
+
parsed = parse_notebook(notebook.read_text(encoding="utf-8"))
|
|
231
|
+
cells = []
|
|
232
|
+
for cell in (parsed.cells if parsed is not None else []):
|
|
233
|
+
if getattr(cell, "name", None) == "setup":
|
|
234
|
+
continue
|
|
235
|
+
cells.append({"index": len(cells) + 1, "name": getattr(cell, "name", None), "code": cell.code, "source": "file"})
|
|
236
|
+
return cells
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _slim(report: dict[str, Any], *, code: bool) -> dict[str, Any]:
|
|
240
|
+
if "cells" not in report:
|
|
241
|
+
return report
|
|
242
|
+
keep = ("index", "key", "name", "title", "status", "errors", "output", "ref", "readonly")
|
|
243
|
+
return {
|
|
244
|
+
**report,
|
|
245
|
+
"cells": [
|
|
246
|
+
{**{k: c[k] for k in keep if k in c and c[k] not in (None, [], False)}, **({"code": c["code"]} if code else {})}
|
|
247
|
+
for c in report["cells"]
|
|
248
|
+
],
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _cell_ls(args: argparse.Namespace) -> tuple[dict[str, Any], int]:
|
|
253
|
+
url, notebook, name = _session(args, write=False)
|
|
254
|
+
if url is None:
|
|
255
|
+
assert notebook is not None
|
|
256
|
+
return {"notebook": name, "source": "file", "cells": _cells_from_file(notebook)}, 0
|
|
257
|
+
return _slim(_call(url, "/api/cells"), code=args.code), 0
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _cell_get(args: argparse.Namespace) -> tuple[dict[str, Any], int]:
|
|
261
|
+
url, notebook, name = _session(args, write=False)
|
|
262
|
+
if url is None:
|
|
263
|
+
assert notebook is not None
|
|
264
|
+
cells = _cells_from_file(notebook)
|
|
265
|
+
if not args.cell.isdigit() or not 1 <= int(args.cell) <= len(cells):
|
|
266
|
+
raise ValueError("without the editor, name a cell by its number (see `sca cell ls`)")
|
|
267
|
+
return {"notebook": name, "source": "file", **cells[int(args.cell) - 1]}, 0
|
|
268
|
+
report = _call(url, "/api/cells")
|
|
269
|
+
for cell in report.get("cells", []):
|
|
270
|
+
if args.cell in (str(cell["index"]), cell.get("key"), cell["id"]):
|
|
271
|
+
return {"notebook": report.get("notebook"), **cell}, 0
|
|
272
|
+
raise ValueError(f"no cell {args.cell!r}; run `sca cell ls`")
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _read_code(args: argparse.Namespace) -> str:
|
|
276
|
+
import sys
|
|
277
|
+
|
|
278
|
+
if args.file is not None:
|
|
279
|
+
return args.file.read_text(encoding="utf-8")
|
|
280
|
+
if sys.stdin.isatty():
|
|
281
|
+
raise ValueError("give the code with --file, or on stdin")
|
|
282
|
+
return sys.stdin.read()
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _write_op(args: argparse.Namespace, op: str, body: dict[str, Any]) -> tuple[dict[str, Any], int]:
|
|
286
|
+
url, _notebook, _name = _session(args, write=True)
|
|
287
|
+
assert url is not None
|
|
288
|
+
report = _call(url, f"/api/cells/{op}", body)
|
|
289
|
+
if "error" in report:
|
|
290
|
+
return _slim(report, code=False), 1
|
|
291
|
+
touched = set(report.get("touched", []))
|
|
292
|
+
report = _slim(report, code=False)
|
|
293
|
+
# What the change did: the touched cells with their state; the rest as a count.
|
|
294
|
+
report["cells"] = [c for c in report["cells"] if c.get("index") in touched] or report["cells"]
|
|
295
|
+
return report, 0
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _cell_put(args: argparse.Namespace) -> tuple[dict[str, Any], int]:
|
|
299
|
+
return _write_op(args, "edit", {"cell": args.cell, "code": _read_code(args), "run": not args.no_run})
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _cell_insert(args: argparse.Namespace) -> tuple[dict[str, Any], int]:
|
|
303
|
+
return _write_op(args, "insert", {"after": args.after, "name": args.name, "code": _read_code(args), "run": not args.no_run})
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _cell_rm(args: argparse.Namespace) -> tuple[dict[str, Any], int]:
|
|
307
|
+
return _write_op(args, "delete", {"cell": args.cell})
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _cell_run(args: argparse.Namespace) -> tuple[dict[str, Any], int]:
|
|
311
|
+
return _write_op(args, "run", {"cells": args.cells})
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _new_notebook(args: argparse.Namespace) -> tuple[dict[str, Any], int]:
|
|
315
|
+
from .templates import create_notebook
|
|
316
|
+
|
|
317
|
+
start = (args.workspace or Path.cwd()).expanduser().resolve()
|
|
318
|
+
found = _find_editor(start)
|
|
319
|
+
root = found[0] if found is not None else start
|
|
320
|
+
# Only the file is written: the running editor lists it on its own and the
|
|
321
|
+
# person's current notebook stays open.
|
|
322
|
+
path = create_notebook(root, args.name, args.kind)
|
|
323
|
+
return {"ok": True, "path": str(path), "editor_listed": found is not None}, 0
|
|
324
|
+
|
|
325
|
+
|
|
89
326
|
__all__ = ["configure"]
|
simplecadapi/editor/kernel.py
CHANGED
|
@@ -20,6 +20,7 @@ typing in the embedded marimo editor), and is what the server reacts to.
|
|
|
20
20
|
|
|
21
21
|
from __future__ import annotations
|
|
22
22
|
|
|
23
|
+
import functools
|
|
23
24
|
import json
|
|
24
25
|
import os
|
|
25
26
|
import re
|
|
@@ -43,6 +44,22 @@ class KernelError(RuntimeError):
|
|
|
43
44
|
pass
|
|
44
45
|
|
|
45
46
|
|
|
47
|
+
def _locked(method):
|
|
48
|
+
"""Run a cell-writing method under the kernel's write lock.
|
|
49
|
+
|
|
50
|
+
The editor's own writes and the ingest of an external edit of the notebook
|
|
51
|
+
file must not interleave: ingest compares the file with the kernel's cells,
|
|
52
|
+
and a write half-way through would look like an external change.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
@functools.wraps(method)
|
|
56
|
+
def wrapper(self, *args, **kwargs):
|
|
57
|
+
with self.write_lock:
|
|
58
|
+
return method(self, *args, **kwargs)
|
|
59
|
+
|
|
60
|
+
return wrapper
|
|
61
|
+
|
|
62
|
+
|
|
46
63
|
class MarimoKernel:
|
|
47
64
|
def __init__(
|
|
48
65
|
self,
|
|
@@ -59,6 +76,7 @@ class MarimoKernel:
|
|
|
59
76
|
self.setup_errors: list[str] = []
|
|
60
77
|
self._ran = threading.Event() # a run of cells completed (see wait_instantiated)
|
|
61
78
|
self._own_calls = 0
|
|
79
|
+
self.write_lock = threading.RLock()
|
|
62
80
|
self._own_ended = 0.0
|
|
63
81
|
self.workspace = self.notebook.parent
|
|
64
82
|
self.marimo_port = _free_port(server_port + 1)
|
|
@@ -357,6 +375,7 @@ class MarimoKernel:
|
|
|
357
375
|
"""Queue cells to run (lazy mode: their dependents turn stale)."""
|
|
358
376
|
return self.execute(_driver("\n".join(f" ctx.run_cell({cell_id!r})" for cell_id in cell_ids)))
|
|
359
377
|
|
|
378
|
+
@_locked
|
|
360
379
|
def edit_cell(self, cell_id: str, code: str) -> dict:
|
|
361
380
|
"""Replace a cell's code (persisted to the file) and run it."""
|
|
362
381
|
return self.execute(
|
|
@@ -365,6 +384,7 @@ class MarimoKernel:
|
|
|
365
384
|
+ _driver(f" ctx.edit_cell({cell_id!r}, code=__code)\n ctx.run_cell({cell_id!r})")
|
|
366
385
|
)
|
|
367
386
|
|
|
387
|
+
@_locked
|
|
368
388
|
def save_cell(self, cell_id: str, code: str) -> dict:
|
|
369
389
|
"""Replace a cell's code (persisted to the file) without running it."""
|
|
370
390
|
return self.execute(
|
|
@@ -373,6 +393,7 @@ class MarimoKernel:
|
|
|
373
393
|
+ _driver(f" ctx.edit_cell({cell_id!r}, code=__code)")
|
|
374
394
|
)
|
|
375
395
|
|
|
396
|
+
@_locked
|
|
376
397
|
def put_cell(self, code: str, *, cell_id: str | None, run: bool = True) -> str | None:
|
|
377
398
|
"""Write *code* into cell *cell_id*, or append a new cell holding it.
|
|
378
399
|
|
|
@@ -401,9 +422,11 @@ class MarimoKernel:
|
|
|
401
422
|
return line[len("SCA-CELL "):].strip()
|
|
402
423
|
return None
|
|
403
424
|
|
|
425
|
+
@_locked
|
|
404
426
|
def delete_cell(self, cell_id: str) -> dict:
|
|
405
427
|
return self.execute(_driver(f" ctx.delete_cell({cell_id!r})"))
|
|
406
428
|
|
|
429
|
+
@_locked
|
|
407
430
|
def insert_cell(self, after: str | None) -> dict:
|
|
408
431
|
"""Insert one empty, named cell after *after* (at the top if None).
|
|
409
432
|
|
|
@@ -431,6 +454,27 @@ class MarimoKernel:
|
|
|
431
454
|
)
|
|
432
455
|
)
|
|
433
456
|
|
|
457
|
+
@_locked
|
|
458
|
+
def create_cell_after(self, after: str | None, code: str, name: str | None, *, run: bool = True) -> dict:
|
|
459
|
+
"""Create a cell holding *code* after cell *after* (at the top if None)."""
|
|
460
|
+
body = (
|
|
461
|
+
" __names = [c.id for c in ctx.cells]\n"
|
|
462
|
+
+ (
|
|
463
|
+
f" __id = ctx.create_cell(__code, after={after!r}, name={name!r})\n"
|
|
464
|
+
if after
|
|
465
|
+
else (
|
|
466
|
+
f" __id = ctx.create_cell(__code, before=__names[0], name={name!r}) if __names"
|
|
467
|
+
f" else ctx.create_cell(__code, name={name!r})\n"
|
|
468
|
+
)
|
|
469
|
+
)
|
|
470
|
+
+ (" ctx.run_cell(__id)\n" if run else "")
|
|
471
|
+
+ "print('SCA-CELL', __id)\n"
|
|
472
|
+
)
|
|
473
|
+
return self.execute(
|
|
474
|
+
"import json as _json\n"
|
|
475
|
+
f"__code = _json.loads({json.dumps(json.dumps(code))})\n" + _driver(body)
|
|
476
|
+
)
|
|
477
|
+
|
|
434
478
|
def reload_modules(self, names: list[str]) -> dict:
|
|
435
479
|
"""Forget the local modules *names* and run every cell again.
|
|
436
480
|
|