anycad 1.0.2 → 1.0.3

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.
package/AGENTS.md ADDED
@@ -0,0 +1,24 @@
1
+ # AnyCAD source authoring
2
+
3
+ Before writing src/model.py, ALWAYS call cad_syntax first for every primitive and operation you plan to use. Never guess build123d or cad keyword arguments.
4
+
5
+ Never write export(...) inside src/model.py unless cad_syntax explicitly shows it; let cad_build export the @model return value.
6
+
7
+ Use this complete 12-line template for a hand-authored model. Substitute the verified geometry inside `part()`.
8
+
9
+ ```python
10
+ from cad import model
11
+ import build123d as bd
12
+
13
+
14
+ @model
15
+ def part():
16
+ solid = bd.Box(20, 20, 10)
17
+ return solid
18
+
19
+
20
+ if __name__ == "__main__":
21
+ part()
22
+ ```
23
+
24
+ `cad_source` supplies this wrapper when you give it the build function's body. `cad_construct` takes named geometry operations and writes editable `src/model.py` before building it.
package/README.md CHANGED
@@ -26,7 +26,11 @@ For Pi with the CAD CLI and skill already set up, the compact package installs w
26
26
 
27
27
  ## Use
28
28
 
29
- Open a new Pi session or run `/reload`. AnyCAD activates on recognizable CAD requests when `lmstudio/qwen3.8-9b-distill` is selected. Start a request with `CAD` to activate it explicitly. CAD turns select low reasoning effort and use the local CAD and file tools. Pi restores the previous tool and reasoning selections after the turn.
29
+ Open a new Pi session or run `/reload`. AnyCAD activates on recognizable CAD requests when `lmstudio/qwen3.8-9b-distill` is selected. Start a request with `CAD` to activate it explicitly. CAD turns use your selected Pi thinking level and the local CAD and file tools. Pi restores the previous tool selection after the turn. The showcase runs used low thinking.
30
+
31
+ Start in an empty project folder and describe the part. AnyCAD creates the source and export files as it builds. For vague descriptions, it first saves a dimensioned brief in `src/design.md` and continues to the build. Missing dimensions that determine how a part fits existing hardware still prompt a focused question.
32
+
33
+ For custom build123d source, AnyCAD checks the primitives and operations in `cad_syntax`, then uses `cad_source` to write the script, verify the build, and export STEP. A syntax or API error prompts a fresh lookup before the retry. `cad_construct` writes editable source from named geometry operations. [Source rules and minimal template](AGENTS.md)
30
34
 
31
35
  The LM Studio application, model, and provider extension are host components. AnyCAD uses the provider already configured in Pi. The default output paths are `src/model.py` and `exports/model.step` in the current project.
32
36
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "anycad",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "Local parametric CAD for Pi. A two-solid dovetail took 14.5 s, 405 output tokens, 1 call, and 0 errors on qwen3.8-9b-distill.",
5
5
  "license": "MIT",
6
6
  "repository": { "type": "git", "url": "git+https://github.com/CubM/AnyCAD.git" },
@@ -14,5 +14,5 @@
14
14
  "@earendil-works/pi-coding-agent": "*",
15
15
  "typebox": "*"
16
16
  },
17
- "files": ["src", "runtime/*.py", "vendor/text-to-cad", "showcase", "workflow.md", "install.ps1", "README.md"]
17
+ "files": ["AGENTS.md", "src", "runtime/*.py", "vendor/text-to-cad", "showcase", "workflow.md", "install.ps1", "README.md"]
18
18
  }
@@ -1,6 +1,7 @@
1
1
  """Build, inspect, and optionally export one text-to-CAD model through its official CLI."""
2
2
 
3
3
  import argparse
4
+ import json
4
5
  import os
5
6
  from pathlib import Path
6
7
  import re
@@ -55,6 +56,7 @@ def main():
55
56
  parser.add_argument("source", type=Path)
56
57
  parser.add_argument("--step", type=Path, help="Export the verified build to this path.")
57
58
  parser.add_argument("--assembly", action="store_true", help="Check interference before export.")
59
+ parser.add_argument("--expect-size", type=json.loads, help="Design brief overall X, Y, Z dimensions in millimetres.")
58
60
  args = parser.parse_args()
59
61
  cwd = Path.cwd()
60
62
  try:
@@ -63,6 +65,13 @@ def main():
63
65
  summary = run_cad(cwd, "model", "inspect", identifier).replace("\r\n", "\n")
64
66
  print("cad model inspect", identifier)
65
67
  print(summary.split("\nclosure\n", 1)[0].strip())
68
+ if args.expect_size:
69
+ bounds = json.loads(run_cad(cwd, "model", "inspect", identifier, "--query", "summary", "--json"))["summary"]["bounds"]
70
+ size = None if bounds is None else [round(value, 4) for value in bounds["size"]]
71
+ if size is None or any(abs(actual - planned) > 0.02
72
+ for actual, planned in zip(size, args.expect_size, strict=True)):
73
+ raise RuntimeError(f"Built XYZ size {size} differs from the design brief {args.expect_size} mm. Correct the source before exporting.")
74
+ print("Built XYZ size matches the design brief.")
66
75
  count = re.search(r"(?mi)^\s*parts\s+(\d+)\b", summary)
67
76
  if args.assembly or (count and int(count.group(1)) > 1):
68
77
  print("cad model interference", identifier)
@@ -18,10 +18,37 @@ RECIPES = {
18
18
  "wire = bd.Wire.make_polygon([(x0, y, z) for y, z in yz_points], close=True)\n"
19
19
  "prism = bd.extrude(bd.Face(wire), amount=length, dir=(1, 0, 0))",
20
20
  ),
21
+ "loft": (
22
+ ("loft", "Circle", "Pos"),
23
+ "lower = bd.Circle(base_radius)\n"
24
+ "upper = bd.Pos(0, 0, height) * bd.Circle(top_radius)\n"
25
+ "body = bd.loft([lower, upper])",
26
+ ),
27
+ "revolve": (
28
+ ("revolve", "Plane"),
29
+ "with bd.BuildSketch(bd.Plane.XZ) as profile:\n"
30
+ " with bd.Locations((radius / 2, height / 2)):\n"
31
+ " bd.Rectangle(radius, height)\n"
32
+ "body = bd.revolve(profile.sketch, axis=bd.Axis.Z, revolution_arc=360)",
33
+ ),
34
+ "sweep": (
35
+ ("sweep", "Edge.make_line", "Circle"),
36
+ "path = bd.Edge.make_line((0, 0, 0), (0, 0, height))\n"
37
+ "body = bd.sweep(sections=bd.Circle(radius), path=path)",
38
+ ),
39
+ "helix": (
40
+ ("Helix",),
41
+ "path = bd.Helix(pitch=pitch, height=height, radius=radius)",
42
+ ),
21
43
  "fillet": (
22
44
  ("fillet", "ShapeList.filter_by"),
23
45
  "result = bd.fillet(body.edges().filter_by(bd.Axis.Z), radius)",
24
46
  ),
47
+ "chamfer": (
48
+ ("chamfer", "ShapeList.group_by"),
49
+ "bottom_edges = body.edges().group_by(bd.Axis.Z)[0]\n"
50
+ "result = bd.chamfer(bottom_edges, length=chamfer_size)",
51
+ ),
25
52
  "box": (
26
53
  ("Box", "Pos"),
27
54
  "body = bd.Pos(cx, cy, (z0 + z1) / 2) * bd.Box(width, depth, z1 - z0)",
@@ -83,6 +83,35 @@ def fused_plan(plan):
83
83
  return {**plan, "steps": steps, "result": last, "void": [list(point) for point in dict.fromkeys(map(tuple, probes))]}
84
84
 
85
85
 
86
+ def write_centered_brief(path, plan):
87
+ stock, hole = plan["steps"]
88
+ if stock["op"] == "block":
89
+ width, depth = stock["x1"] - stock["x0"], stock["y1"] - stock["y0"]
90
+ else:
91
+ width, depth = stock["width"], stock["depth"]
92
+ if stock["op"] == "stock":
93
+ z0 = stock.get("bottom", 0)
94
+ z1 = z0 + stock["height"]
95
+ else:
96
+ z0, z1 = stock["z0"], stock["z1"]
97
+ x, y = hole["x_centers"][0], hole["y_centers"][0]
98
+ profile = f" with R{stock['radius']:g} vertical corners" if stock["op"] == "rounded_prism" else ""
99
+ path.write_text(
100
+ "# CAD design brief\n\n"
101
+ "A flat-based block with one centered through bore.\n\n"
102
+ "## Dimensions and feature order\n\n"
103
+ f"1. Build {width:g} × {depth:g} × {z1 - z0:g} mm stock{profile}. "
104
+ f"The bore axis is X={x:g}, Y={y:g} mm.\n"
105
+ f"2. Drill a Ø{hole['diameter']:g} mm through bore along Z from {z0:g} to {z1:g} mm.\n\n"
106
+ "## Assumptions and checks\n\n"
107
+ "- Z is vertical and the bottom face is the resting surface.\n"
108
+ "- The build checks that the result is one valid solid and that its bore centerline is open.\n"
109
+ "- Inspect the dimensions and export the verified model to STEP.\n",
110
+ encoding="utf-8",
111
+ )
112
+ print("Saved the resolved design brief in src/design.md.")
113
+
114
+
86
115
  def main():
87
116
  root = Path.cwd()
88
117
  path = root / "geometry-plan.json"
@@ -95,6 +124,8 @@ def main():
95
124
  code = compile_source(plan, number_of_solids)
96
125
  target = root / "src/model.py"
97
126
  target.parent.mkdir(exist_ok=True)
127
+ if plan.get("design_brief"):
128
+ write_centered_brief(target.with_name("design.md"), plan)
98
129
  shutil.copyfile(Path(__file__).with_name("cad_primitives.py"), target.with_name("cad_primitives.py"))
99
130
  target.write_text(code, encoding="utf-8")
100
131
  print(f"Saved src/model.py with {len(plan['steps'])} features and {number_of_solids} expected solids.")
package/runtime/plan.py CHANGED
@@ -140,8 +140,6 @@ def compile_source(plan, expected_solids):
140
140
  raise ValueError("Connect these unused steps to the final result: " + ", ".join(unused))
141
141
  void = points(plan.get("void", []))
142
142
  material = points(plan.get("material", []))
143
- if not (void or material):
144
- raise ValueError("Pi's plan omitted a geometry probe.")
145
143
  lines += [f" return shapes.checked({result}, solids={expected_solids}, material={material!r}, void={void!r})",
146
144
  "", "", "@model", "def part():", " return geometry()", "", "",
147
145
  'if __name__ == "__main__":', " part()", ""]
@@ -0,0 +1,87 @@
1
+ """Write a model with AnyCAD's standard build123d entry point."""
2
+
3
+ import ast
4
+ import json
5
+ from pathlib import Path
6
+ import sys
7
+ import textwrap
8
+
9
+
10
+ def is_main_guard(node):
11
+ return isinstance(node, ast.If) and ast.unparse(node.test) in (
12
+ "__name__ == '__main__'", "'__main__' == __name__",
13
+ )
14
+
15
+
16
+ def is_model_invocation(node, names):
17
+ value = getattr(node, "value", None)
18
+ return isinstance(value, ast.Call) and isinstance(value.func, ast.Name) and value.func.id in names
19
+
20
+
21
+ def model_body(code):
22
+ tree = ast.parse(code)
23
+ if any(isinstance(node, ast.Return) for node in tree.body):
24
+ return "", code, "part"
25
+ defined = [node for node in tree.body if isinstance(node, ast.FunctionDef)]
26
+ preferred = [node for node in defined if node.name == "part"
27
+ or any(ast.unparse(item) == "model" for item in node.decorator_list)]
28
+ functions = preferred or defined
29
+ if len(functions) != 1:
30
+ return "", code, "part"
31
+ function = functions[0]
32
+ if function.args.posonlyargs or function.args.args or function.args.kwonlyargs:
33
+ raise ValueError("The CAD model function needs zero arguments.")
34
+ support = [
35
+ node for node in tree.body
36
+ if node is not function and not is_main_guard(node)
37
+ and not is_model_invocation(node, {function.name})
38
+ ]
39
+ lines = code.splitlines()
40
+ body = textwrap.dedent("\n".join(lines[function.body[0].lineno - 1:function.body[-1].end_lineno]))
41
+ if function.body[0].lineno == function.lineno:
42
+ body = "\n".join(map(ast.unparse, function.body))
43
+ return ast.unparse(ast.Module(body=support, type_ignores=[])), body, function.name
44
+
45
+
46
+ def check_apis(tree, verified):
47
+ missing = set()
48
+ for node in ast.walk(tree):
49
+ if not isinstance(node, ast.Call) or not isinstance(node.func, (ast.Name, ast.Attribute)):
50
+ continue
51
+ name = ast.unparse(node.func)
52
+ operation = name.rsplit(".", 1)[-1]
53
+ if name.startswith(("bd.", "build123d.")):
54
+ if name.split(".", 1)[1] not in verified:
55
+ missing.add(name)
56
+ elif name.startswith("model.") and name not in verified:
57
+ missing.add(name)
58
+ elif (operation == "export" or operation.startswith("export_")) and name not in verified:
59
+ missing.add(name)
60
+ if missing:
61
+ raise ValueError("Call cad_syntax for these unverified operations or let AnyCAD export STEP: " + ", ".join(sorted(missing)))
62
+
63
+
64
+ def main():
65
+ payload = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
66
+ code = textwrap.dedent(payload["body"]).strip("\n")
67
+ extra, body, name = model_body(code)
68
+ setup = ast.parse("\n\n".join(filter(None, (payload.get("setup"), extra))))
69
+ future = [node for node in setup.body if isinstance(node, ast.ImportFrom) and node.module == "__future__"]
70
+ support = [node for node in setup.body if node not in future and not is_main_guard(node)
71
+ and not is_model_invocation(node, {name, "part"})]
72
+ source = "\n\n\n".join(filter(None, (
73
+ "\n".join(map(ast.unparse, future)),
74
+ "import build123d as bd\nfrom cad import model",
75
+ ast.unparse(ast.Module(body=support, type_ignores=[])),
76
+ "@model\ndef part():\n" + textwrap.indent(body, " "),
77
+ 'if __name__ == "__main__":\n part()\n',
78
+ )))
79
+ output = Path("src/model.py")
80
+ compile(source, str(output), "exec")
81
+ check_apis(ast.parse(source), set(payload.get("verifiedApis", [])))
82
+ output.parent.mkdir(exist_ok=True)
83
+ output.write_text(source, encoding="utf-8")
84
+
85
+
86
+ if __name__ == "__main__":
87
+ main()
@@ -2,7 +2,7 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { Type, type TSchema } from "typebox";
3
3
  import { writeFile } from "node:fs/promises";
4
4
  import { join } from "node:path";
5
- import { runtimeScript } from "./runtime.ts";
5
+ import { runtimeScript, sizeArgs } from "./runtime.ts";
6
6
  import registerNativeTools from "./cad-tools.ts";
7
7
 
8
8
  const ref = Type.String({ description: "Name of a previous step" });
@@ -63,7 +63,7 @@ function relevantSteps(text: string) {
63
63
  return availableSteps.filter((schema) => wanted.has(schema.properties.op.const));
64
64
  }
65
65
 
66
- export default function (pi: ExtensionAPI, cwd: string, requestText: string, fallback: boolean, centered: boolean) {
66
+ export default function (pi: ExtensionAPI, cwd: string, requestText: string, fallback: boolean, centered: boolean, autoBrief: boolean) {
67
67
  const active = registerNativeTools(pi, cwd, fallback, true);
68
68
  const nominal = centered && requestText.match(/\bfor (?:an? )?(?:m\s*([0-9.]+)|([0-9.]+)\s*mm) bolt\b/);
69
69
  const namedHole = /[ø⌀]|\b(?:diameter|\d+(?:\.\d+)?\s*mm (?:through[- ]?)?(?:hole|bore))\b/.test(requestText);
@@ -75,7 +75,7 @@ export default function (pi: ExtensionAPI, cwd: string, requestText: string, fal
75
75
  await writeFile(join(ctx.cwd, "geometry-plan.json"), JSON.stringify(args, null, 2) + "\n", "utf8");
76
76
  const result = await pi.exec("python", [runtimeScript("native_plan.py")], { cwd: ctx.cwd, signal, timeout: 10000 });
77
77
  if (result.code !== 0) throw new Error((result.stderr + "\n" + result.stdout).trim());
78
- const build = await pi.exec("python", [runtimeScript("build_model.py"), "src/model.py", "--step", "exports/model.step"], {
78
+ const build = await pi.exec("python", ["-X", "utf8", runtimeScript("build_model.py"), "src/model.py", "--step", "exports/model.step", ...sizeArgs(args)], {
79
79
  cwd: ctx.cwd, signal, timeout: 35000,
80
80
  });
81
81
  if (build.code !== 0) throw new Error((build.stderr + "\n" + build.stdout).trim());
@@ -197,7 +197,8 @@ export default function (pi: ExtensionAPI, cwd: string, requestText: string, fal
197
197
  pi.registerTool({
198
198
  name: "cad_solid",
199
199
  label: "Make a fused CAD part",
200
- description: "Build one block or fuse several stocks into one part, then apply all cuts in order. Dimensions are millimetres. Stock width is X and depth is Y. Z extents and port stops are absolute. A drill pattern cuts every combination of its center coordinates.",
200
+ description: "Build one block or fuse several stocks into one part, then apply all cuts in order. Dimensions are millimetres. Stock width is X and depth is Y. Z extents and port stops are absolute. A drill pattern cuts every combination of its center coordinates."
201
+ + (autoBrief ? " This tool writes the dimensioned design brief before generating the source." : ""),
201
202
  parameters: Type.Object({
202
203
  stocks: stockFields,
203
204
  cuts: cutFields,
@@ -207,7 +208,7 @@ export default function (pi: ExtensionAPI, cwd: string, requestText: string, fal
207
208
  }),
208
209
  async execute(_id, args, signal, _update, ctx) {
209
210
  return savePlan(ctx, signal, centered ? {
210
- ...args, centered_bore: true, corner_default: defaultCorners, clearance,
211
+ ...args, centered_bore: true, corner_default: defaultCorners, clearance, design_brief: autoBrief,
211
212
  } : args);
212
213
  },
213
214
  });
@@ -219,7 +220,7 @@ export default function (pi: ExtensionAPI, cwd: string, requestText: string, fal
219
220
  parameters: Type.Object({
220
221
  steps: Type.Array(Type.Union(relevantSteps(requestText)), { minItems: 1 }),
221
222
  solids: Type.Integer({ minimum: 1, description: "Number of separate solid occurrences expected" }),
222
- void: Type.Array(xyz, { description: "Actual points that must be empty, such as a centerline within a bore" }),
223
+ void: Type.Optional(Type.Array(xyz, { description: "Actual points that must be empty, such as a centerline within a bore" })),
223
224
  material: Type.Optional(Type.Array(xyz)),
224
225
  parameter: Type.Optional(Type.Object({ name: Type.String(), default: Type.Number() })),
225
226
  }),
@@ -0,0 +1,43 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { mkdir, writeFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+
6
+ const entries = Type.Array(Type.String({ minLength: 1 }), { minItems: 1 });
7
+
8
+ export default function registerCadPlan(pi: ExtensionAPI) {
9
+ pi.registerTool({
10
+ name: "cad_plan",
11
+ label: "Write CAD design brief",
12
+ description: "Turn an underspecified CAD request into a dimensioned brief. Record the chosen part, dimensions and axes, ordered features, assumptions, and geometry checks. Creates the source and export folders so the CAD build can begin immediately.",
13
+ defaultActive: false,
14
+ parameters: Type.Object({
15
+ part: Type.String({ minLength: 1, description: "Part and intended use in one sentence" }),
16
+ dimensions: entries,
17
+ size: Type.Tuple([Type.Number({ minimum: 0 }), Type.Number({ minimum: 0 }), Type.Number({ minimum: 0 })],
18
+ { description: "Finished width, depth, and height in mm. Match the feature dimensions. For a solid circular loft use the largest diameter for both width and depth." }),
19
+ features: entries,
20
+ assumptions: entries,
21
+ checks: entries,
22
+ }),
23
+ async execute(_id, args, _signal, _update, ctx) {
24
+ const sourceDir = join(ctx.cwd, "src");
25
+ await Promise.all([
26
+ mkdir(sourceDir, { recursive: true }),
27
+ mkdir(join(ctx.cwd, "exports"), { recursive: true }),
28
+ ]);
29
+ const sections = [
30
+ ["Dimensions and placement", args.dimensions],
31
+ ["Feature order", args.features],
32
+ ["Assumptions", args.assumptions],
33
+ ["Checks", args.checks],
34
+ ] as const;
35
+ const size = `Finished size in X × Y × Z: ${args.size.join(" × ")} mm.`;
36
+ const brief = ["# CAD design brief", args.part, size, ...sections.map(([title, values]) =>
37
+ `## ${title}\n\n${values.map((value) => `- ${value}`).join("\n")}`,
38
+ )].join("\n\n");
39
+ await writeFile(join(sourceDir, "design.md"), brief + "\n", "utf8");
40
+ return { content: [{ type: "text", text: `Wrote src/design.md. ${size} Build the part at this size.` }], details: {} };
41
+ },
42
+ });
43
+ }
package/src/cad-tools.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { Type } from "typebox";
3
3
  import { existsSync, readFileSync } from "node:fs";
4
- import { readFile, writeFile } from "node:fs/promises";
4
+ import { mkdtemp, readFile, rm, rmdir, writeFile } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
5
6
  import { join } from "node:path";
6
- import { runtimeScript } from "./runtime.ts";
7
+ import { runtimeScript, sizeArgs } from "./runtime.ts";
7
8
 
8
9
  type Dimension = { start: number; end: number; label: string };
9
10
 
@@ -21,8 +22,8 @@ function dimensions(source: string): Map<string, Dimension> {
21
22
  export default function (pi: ExtensionAPI, cwd: string, buildWithoutSource = true, buildAfterDimensions = false) {
22
23
  const modelPath = join(cwd, "src", "model.py");
23
24
  const names = existsSync(modelPath) ? dimensions(readFileSync(modelPath, "utf8")) : new Map<string, Dimension>();
24
- async function buildModel(cwd: string, signal?: AbortSignal, assembly = false) {
25
- const command = [runtimeScript("build_model.py"), "src/model.py", "--step", "exports/model.step"];
25
+ async function buildModel(cwd: string, signal?: AbortSignal, assembly = false, input: object = {}) {
26
+ const command = ["-X", "utf8", runtimeScript("build_model.py"), "src/model.py", "--step", "exports/model.step", ...sizeArgs(input)];
26
27
  if (assembly) command.push("--assembly");
27
28
  const result = await pi.exec("python", command, { cwd, signal, timeout: 35000 });
28
29
  if (result.code !== 0) throw new Error((result.stderr + "\n" + result.stdout).trim());
@@ -63,22 +64,52 @@ export default function (pi: ExtensionAPI, cwd: string, buildWithoutSource = tru
63
64
  description: "Build src/model.py with cad run, inspect its live ID, and export exports/model.step. Use once after editing. Set assembly to check part interference.",
64
65
  parameters: Type.Object({ assembly: Type.Optional(Type.Boolean()) }),
65
66
  async execute(_id, args, signal, _update, ctx) {
66
- return { content: [{ type: "text", text: await buildModel(ctx.cwd, signal, args.assembly) }], details: {} };
67
+ if (!existsSync(join(ctx.cwd, "src", "model.py"))) {
68
+ throw new Error("No CAD source exists yet. Create the part with a native feature tool, or use cad_syntax followed by cad_source.");
69
+ }
70
+ return { content: [{ type: "text", text: await buildModel(ctx.cwd, signal, args.assembly, args) }], details: {} };
71
+ },
72
+ });
73
+
74
+ if (buildWithoutSource) pi.registerTool({
75
+ name: "cad_source",
76
+ label: "Write and build CAD source",
77
+ description: "After cad_syntax, provide the Python body that builds and returns the final shape at the design brief's finished size. Use bd for build123d. Assign labels with shape.label = 'name'. The tool supplies the imports, decorated function, and entry point, then builds, inspects, and exports STEP.",
78
+ parameters: Type.Object({
79
+ body: Type.String({ minLength: 1, description: "Statements inside the build function, ending in return of the final shape" }),
80
+ setup: Type.Optional(Type.String({ description: "Top-level model.param declarations or other supporting code" })),
81
+ assembly: Type.Optional(Type.Boolean()),
82
+ }),
83
+ async execute(_id, args, signal, _update, ctx) {
84
+ const dir = await mkdtemp(join(tmpdir(), "anycad-source-"));
85
+ const payload = join(dir, "source.json");
86
+ try {
87
+ await writeFile(payload, JSON.stringify(args), "utf8");
88
+ const result = await pi.exec("python", ["-X", "utf8", runtimeScript("write_source.py"), payload], {
89
+ cwd: ctx.cwd, signal, timeout: 10000,
90
+ });
91
+ if (result.code !== 0) throw new Error(result.stderr.trim() || result.stdout.trim());
92
+ } finally {
93
+ await rm(payload, { force: true });
94
+ await rmdir(dir);
95
+ }
96
+ return { content: [{ type: "text", text: await buildModel(ctx.cwd, signal, args.assembly, args) }], details: {} };
67
97
  },
68
98
  });
69
99
 
70
100
  pi.registerTool({
71
101
  name: "cad_syntax",
72
102
  label: "Look up local CAD syntax",
73
- description: "Get the installed build123d signature and a concise example. Keywords include box, cylinder, fillet, extrude, slot, split, parameter, and probe.",
103
+ description: "Look up installed build123d signatures and local examples before writing CAD source or fixing an API error. Submit the operation keywords together, such as extrude, loft, revolve, or the exact API name.",
74
104
  parameters: Type.Object({ keywords: Type.Array(Type.String(), { minItems: 1, maxItems: 5 }) }),
75
105
  async execute(_id, args, signal, _update, ctx) {
76
- const command = [runtimeScript("cad_help.py"), "--", ...args.keywords];
106
+ const command = ["-X", "utf8", runtimeScript("cad_help.py"), "--", ...args.keywords];
77
107
  const result = await pi.exec("python", command, { cwd: ctx.cwd, signal, timeout: 15000 });
78
108
  if (result.code !== 0) throw new Error((result.stderr + "\n" + result.stdout).trim());
79
109
  return { content: [{ type: "text", text: result.stdout.trim() }], details: {} };
80
110
  },
81
111
  });
82
112
  return ["cad_syntax", ...(names.size ? ["cad_dimensions"] : []),
113
+ ...(buildWithoutSource ? ["cad_source"] : []),
83
114
  ...(buildWithoutSource || (names.size && !buildAfterDimensions) ? ["cad_build"] : [])];
84
115
  }
package/src/extension.ts CHANGED
@@ -2,11 +2,12 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { Type } from "typebox";
3
3
  import { existsSync, readFileSync } from "node:fs";
4
4
  import { writeFile } from "node:fs/promises";
5
- import { join } from "node:path";
5
+ import { join, resolve } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
- import { runtimeScript } from "./runtime.ts";
7
+ import { runtimeScript, sizeArgs } from "./runtime.ts";
8
8
  import registerNativeTools from "./cad-tools.ts";
9
9
  import registerFeatureTools from "./cad-construct.ts";
10
+ import registerCadPlan from "./cad-plan.ts";
10
11
 
11
12
  const mm = Type.Number();
12
13
  const box = Type.Object({
@@ -18,9 +19,11 @@ const drill = Type.Object({
18
19
  diameter: mm, counter_diameter: mm, counter_depth: mm, x_centers: centers, y_centers: centers,
19
20
  });
20
21
  const parameter = Type.Object({ name: Type.String(), default: mm });
21
- const cadTools = new Set(["cad_dimensions", "cad_build", "cad_syntax", "cad_construct", "cad_solid", "cad_split_support", "cad_dovetail"]);
22
+ const cadTools = new Set(["cad_plan", "cad_dimensions", "cad_build", "cad_source", "cad_syntax", "cad_construct", "cad_solid", "cad_split_support", "cad_dovetail"]);
22
23
  const fileTools = new Set(["read", "write", "edit"]);
23
24
  const workflow = readFileSync(fileURLToPath(new URL("../workflow.md", import.meta.url)), "utf8");
25
+ const sourceRulesPath = fileURLToPath(new URL("../AGENTS.md", import.meta.url));
26
+ const sourceRules = readFileSync(sourceRulesPath, "utf8");
24
27
  const dimensionsOrReference = /\b(?:\d+(?:\.\d+)?\s*(?:mm|cm|inch(?:es)?|in)\b|[a-z]{2,}[-_]\d+|datasheet|drawing|model number)|[@][^\s]+/i;
25
28
 
26
29
  function cadRequest(text: string) {
@@ -42,7 +45,16 @@ function simpleDrilledStock(request: string) {
42
45
  && !/\b(?:more holes|additional|another|holes|counterbore\w*|all edges|all \d+ exterior|chamfer\w*|fillet\w*|thread\w*|slot\w*|pocket\w*|side port|along [xy]|assembly)\b/.test(request);
43
46
  }
44
47
 
45
- function registerRequestTools(pi: ExtensionAPI, cwd: string, text: string, fallback: boolean, centered = false) {
48
+ function needsDesignBrief(request: string) {
49
+ if (/^(?:CAD:\s*)?(?:how (?:do I|can I|to)|what is|explain)\b/i.test(request.trim())) return false;
50
+ if (!/\b(?:make|create|design|model|draw|build|generate)\b/i.test(request)) return false;
51
+ if (/\b(?:make it up|choose (?:the |reasonable )?dimensions|rough concept|use assumptions)\b/i.test(request)) return true;
52
+ const sizes = request.match(/\b\d+(?:\.\d+)?\s*(?:mm|cm|inches?|in)\b|[Ø⌀]\s*\d+(?:\.\d+)?|\bR\s*\d+(?:\.\d+)?\b/gi);
53
+ const specifiedStock = /\b\d+(?:\.\d+)?\s*[x×]\s*\d+(?:\.\d+)?\s*[x×]\s*\d+|\b\d+(?:\.\d+)?\s*mm cube\b/i.test(request);
54
+ return !specifiedStock && (sizes?.length ?? 0) < 3;
55
+ }
56
+
57
+ function registerRequestTools(pi: ExtensionAPI, cwd: string, text: string, fallback: boolean, centered = false, autoBrief = false) {
46
58
  const request = text.toLowerCase();
47
59
  const split = request.includes("split") && request.includes("shaft") && request.includes("counterbore");
48
60
  const dovetail = request.includes("dovetail") && request.includes("slider");
@@ -65,14 +77,14 @@ function registerRequestTools(pi: ExtensionAPI, cwd: string, text: string, fallb
65
77
  const sliderLabel = labels.find((label) => /(?:slider|carriage)/i.test(label));
66
78
  const active = split || dovetail
67
79
  ? registerNativeTools(pi, cwd, fallback, true)
68
- : registerFeatureTools(pi, cwd, request, fallback, centered);
80
+ : registerFeatureTools(pi, cwd, request, fallback, centered, autoBrief);
69
81
 
70
82
  async function build(kind: string, args: object, cwd: string, signal?: AbortSignal) {
71
83
  await writeFile(join(cwd, "geometry-plan.json"), JSON.stringify({ ...args, kind }, null, 2) + "\n", "utf8");
72
84
  const source = await pi.exec("python", [runtimeScript("assembly_plan.py")], { cwd, signal, timeout: 10000 });
73
85
  if (source.code !== 0) throw new Error((source.stdout + "\n" + source.stderr).trim());
74
86
  const result = await pi.exec("python", [
75
- runtimeScript("build_model.py"), "src/model.py", "--step", "exports/model.step", "--assembly",
87
+ "-X", "utf8", runtimeScript("build_model.py"), "src/model.py", "--step", "exports/model.step", "--assembly", ...sizeArgs(args),
76
88
  ], { cwd, signal, timeout: 45000 });
77
89
  if (result.code !== 0) throw new Error((result.stdout + "\n" + result.stderr).trim());
78
90
  return { content: [{ type: "text" as const, text: result.stdout.trim() }], details: {} };
@@ -177,14 +189,24 @@ export default function (pi: ExtensionAPI) {
177
189
  registerRequestTools(pi, process.cwd(), readFileSync(benchmarkPrompt, "utf8"), false);
178
190
  }
179
191
 
180
- let previous: { tools: string[]; thinking: ReturnType<ExtensionAPI["getThinkingLevel"]> } | undefined;
181
- let beforeInput: ReturnType<ExtensionAPI["getThinkingLevel"]> | undefined;
182
- pi.on("input", (event, ctx) => {
183
- if (event.streamingBehavior || ctx.model?.provider !== "lmstudio" || ctx.model.id !== "qwen3.8-9b-distill") return;
184
- if (!benchmark && (!cadRequest(event.text) || !pi.getActiveTools().length)) return;
185
- beforeInput ??= pi.getThinkingLevel();
186
- pi.setThinkingLevel("low");
187
- });
192
+ registerCadPlan(pi);
193
+ let previousTools: string[] | undefined;
194
+ let turn: {
195
+ tools: string[];
196
+ fallback?: string[];
197
+ autoBrief: boolean;
198
+ planPending: boolean;
199
+ syntaxFirst: boolean;
200
+ syntaxChecked: boolean;
201
+ operations: string[];
202
+ size?: number[];
203
+ signatures: Set<string>;
204
+ } | undefined;
205
+ function selectTools() {
206
+ if (turn) pi.setActiveTools(turn.planPending ? ["cad_plan"]
207
+ : turn.syntaxFirst && !turn.syntaxChecked ? ["cad_syntax"] : turn.tools);
208
+ }
209
+
188
210
  pi.on("before_agent_start", (event, ctx) => {
189
211
  if (event.messageType !== "user" || ctx.model?.provider !== "lmstudio" || ctx.model.id !== "qwen3.8-9b-distill") return;
190
212
  const request = event.prompt;
@@ -199,10 +221,12 @@ export default function (pi: ExtensionAPI) {
199
221
  if (!benchmark && !cadRequest(request) && !followsCad) return;
200
222
  const tools = pi.getActiveTools().filter((name) => !cadTools.has(name));
201
223
  if (!benchmark && !tools.length) return;
202
- previous = { tools: benchmark ? pi.getActiveTools() : tools, thinking: beforeInput ?? pi.getThinkingLevel() };
203
- pi.setThinkingLevel("low");
204
224
  event.systemPromptOptions.sections["native_cad_workflow"] = workflow;
225
+ if (!event.systemPromptOptions.contextFiles.some((file) => resolve(file.path) === resolve(sourceRulesPath))) {
226
+ event.systemPromptOptions.sections["native_cad_source_rules"] = sourceRules;
227
+ }
205
228
  if (benchmark) return;
229
+ previousTools ??= tools;
206
230
 
207
231
  const hasInterface = event.images?.length || priorText.some((text) => dimensionsOrReference.test(text))
208
232
  || earlier.some((content) => typeof content !== "string" && content.some((item) => item.type === "image"));
@@ -210,19 +234,95 @@ export default function (pi: ExtensionAPI) {
210
234
  pi.setActiveTools([]);
211
235
  return { systemPrompt: "You are a CAD designer. Read the user's request and ask one concise question for the actual mounting interface or dimensions you need before modeling. Refer to the object and adjustment the user described." };
212
236
  }
213
- const simple = simpleDrilledStock(request.toLowerCase());
214
- const available = registerRequestTools(pi, ctx.cwd, request, true, simple);
215
- const relevant = simple ? available.filter((name) => name === "cad_solid" || name === "cad_dimensions") : available;
216
- pi.setActiveTools(simple ? relevant : [...tools.filter((name) => fileTools.has(name)), ...relevant]);
237
+ const hasSource = existsSync(join(ctx.cwd, "src", "model.py"));
238
+ if (!hasSource) {
239
+ event.systemPromptOptions.sections["native_cad_project"] =
240
+ "This project has no src/model.py yet. Create the requested part directly with a CAD tool. The tools create source and export files. For custom Python, look up the operation with cad_syntax and pass the body of the build function to cad_source.";
241
+ }
242
+ const operations = [...new Set(request.toLowerCase().match(/\b(?:loft|revolve|sweep|helix)\b/g) ?? [])];
243
+ const syntaxFirst = operations.length > 0;
244
+ if (operations.includes("loft") && /\b(?:circle|circular|round)\b/i.test(request)) {
245
+ event.systemPromptOptions.sections["native_cad_loft"] =
246
+ "For a circular loft, follow the cad_syntax example using positioned bd.Circle sections at the requested Z heights and bd.loft([lower, upper]). Use these sketch sections directly.";
247
+ }
248
+ const simple = !syntaxFirst && simpleDrilledStock(request.toLowerCase());
249
+ const brief = needsDesignBrief(request);
250
+ const autoBrief = brief && simple && !hasSource;
251
+ const available = registerRequestTools(pi, ctx.cwd, request, true, simple, autoBrief);
252
+ const canRead = /\.(?:py|step|stp|stl|dxf)\b|\B@[^\s]+/i.test(request);
253
+ const files = tools.filter((name) => hasSource ? fileTools.has(name) : canRead && name === "read");
254
+ const full = [...files, ...available.filter((name) => hasSource || name !== "cad_build"), "cad_plan"];
255
+ const initial = simple
256
+ ? full.filter((name) => ["cad_solid", "cad_dimensions", "cad_syntax"].includes(name) || !autoBrief && name === "cad_plan")
257
+ : syntaxFirst
258
+ ? full.filter((name) => !cadTools.has(name) || ["cad_source", "cad_build", "cad_syntax", "cad_plan"].includes(name))
259
+ : full;
260
+ turn = { tools: initial, fallback: simple ? full : undefined, autoBrief,
261
+ planPending: brief && !autoBrief, syntaxFirst, syntaxChecked: false, operations, signatures: new Set() };
262
+ selectTools();
217
263
  });
218
- pi.on("agent_settled", () => {
219
- if (previous) {
220
- pi.setActiveTools(previous.tools);
221
- pi.setThinkingLevel(previous.thinking);
222
- } else if (beforeInput) {
223
- pi.setThinkingLevel(beforeInput);
264
+
265
+ pi.on("tool_call", (event, ctx) => {
266
+ if (!turn) return;
267
+ if (turn.size && ["cad_source", "cad_build", "cad_solid", "cad_construct", "cad_split_support", "cad_dovetail"].includes(event.toolName)) {
268
+ (event.input as { expectedSize?: number[] }).expectedSize = turn.size;
224
269
  }
225
- previous = undefined;
226
- beforeInput = undefined;
270
+ if (event.toolName === "cad_source") {
271
+ (event.input as { verifiedApis?: string[] }).verifiedApis = [...turn.signatures];
272
+ }
273
+ if (event.toolName === "cad_syntax" && turn.operations.length) {
274
+ const input = event.input as { keywords: string[] };
275
+ input.keywords = [...new Set([...turn.operations, ...input.keywords])].slice(0, 5);
276
+ }
277
+ if (turn.syntaxChecked) return;
278
+ const path = (event.input as { path?: unknown }).path;
279
+ const editsSource = (event.toolName === "write" || event.toolName === "edit")
280
+ && typeof path === "string" && resolve(ctx.cwd, path) === resolve(ctx.cwd, "src", "model.py");
281
+ if (event.toolName === "cad_source" || editsSource) {
282
+ return { block: true, reason: "Call cad_syntax with the relevant build123d operations before writing CAD source." };
283
+ }
284
+ });
285
+
286
+ pi.on("tool_result", (event, ctx) => {
287
+ if (!turn) return;
288
+ if (event.toolName === "cad_plan" && !event.isError) {
289
+ const { features, size } = event.input as { features: string[]; size: number[] };
290
+ turn.size = size;
291
+ const needed = features.join(" ").toLowerCase().match(/\b(?:loft|revolve|sweep|helix|chamfer|fillet|extrude)\b/g) ?? [];
292
+ turn.operations = [...new Set([...turn.operations, ...needed])].slice(0, 5);
293
+ turn.planPending = false;
294
+ turn.tools = turn.tools.filter((name) => name !== "cad_plan");
295
+ selectTools();
296
+ } else if (event.toolName === "cad_syntax" && !event.isError) {
297
+ for (const item of event.content) {
298
+ if (item.type !== "text") continue;
299
+ for (const match of item.text.matchAll(/^([A-Za-z_][\w.]*)\(/gm)) turn.signatures.add(match[1]);
300
+ }
301
+ turn.syntaxChecked = true;
302
+ selectTools();
303
+ } else if (event.isError && turn.fallback && event.toolName === "cad_solid") {
304
+ turn.planPending = turn.autoBrief && !existsSync(join(ctx.cwd, "src", "design.md"));
305
+ turn.tools = turn.fallback;
306
+ turn.fallback = undefined;
307
+ selectTools();
308
+ } else if (event.isError && turn.size && event.content.some((item) =>
309
+ item.type === "text" && item.text.includes("differs from the design brief"))) {
310
+ turn.tools = [...new Set([...turn.tools, "cad_plan"])];
311
+ selectTools();
312
+ return { content: [...event.content, { type: "text",
313
+ text: "When the brief's overall size contradicts its feature dimensions, correct the brief with cad_plan and rebuild. Keep every dimension explicitly supplied by the user." }] };
314
+ } else if (event.isError && (event.toolName === "cad_source" || event.toolName === "cad_build")
315
+ && event.content.some((item) => item.type === "text"
316
+ && /\b(?:SyntaxError|NameError|TypeError|AttributeError|StdFail_NotDone)\b/.test(item.text))) {
317
+ turn.syntaxFirst = true;
318
+ turn.syntaxChecked = false;
319
+ selectTools();
320
+ }
321
+ });
322
+
323
+ pi.on("agent_settled", () => {
324
+ if (previousTools) pi.setActiveTools(previousTools);
325
+ previousTools = undefined;
326
+ turn = undefined;
227
327
  });
228
328
  }
package/src/runtime.ts CHANGED
@@ -3,3 +3,8 @@ import { fileURLToPath } from "node:url";
3
3
  export function runtimeScript(name: string) {
4
4
  return fileURLToPath(new URL(`../runtime/${name}`, import.meta.url));
5
5
  }
6
+
7
+ export function sizeArgs(input: object) {
8
+ const size = (input as { expectedSize?: number[] }).expectedSize;
9
+ return size ? ["--expect-size", JSON.stringify(size)] : [];
10
+ }
package/workflow.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  Before using any CAD tool, decide whether the design needs to fit existing hardware. If its attachment dimensions are missing, reply with one question asking for the hardware model, drawing, or mounting dimensions. Build when the request has enough information for the intended fit.
4
4
 
5
+ For a vague build request, write a design brief before creating geometry. Call `cad_plan` to record overall dimensions, placement and axes, actual feature sizes and order, assumptions, and checks. Keep the features focused on the intended use and choose reasonable defaults for dimensions left open. Build the part from the brief. If `cad_solid` offers to write the brief, call it directly and it will save the resolved dimensions before generating the model.
6
+
5
7
  Use the requested dimensions, features, labels and absolute coordinates in millimetres. To update a matching native source, use `cad_dimensions` with every named input. Use `cad_solid` for one block or fused part with basic stock and cuts. For split shaft supports use `cad_split_support`. For dovetail guides with a separate moving slider use `cad_dovetail`. Use `cad_construct` for other combinations of supported native features. These tools run the checked model build and export its STEP.
6
8
 
7
9
  Choose reasonable editable defaults for unspecified dimensions and state them in the final reply. When a bolt must pass through and the hole diameter is open, add roughly 0.5 mm to the nominal diameter for a small bolt. For example, an M5 bolt can use a Ø5.5 mm clearance hole. Preserve any explicitly requested hole dimensions.
@@ -10,4 +12,4 @@ Enter every requested feature into the matching fields. A bore uses the stated d
10
12
 
11
13
  The feature tool fields already specify the supported CAD syntax. For these designs, submit one complete feature call directly, with every requested addition and cut. The tool computes probes from the feature coordinates when it supplies that check. Resolve any error from the build before retrying.
12
14
 
13
- Consult `cad_syntax` by keyword for an unfamiliar feature. For geometry outside the feature tools, write editable build123d `src/model.py` using `from cad import model` and an invoked zero-argument `@model` function, then run `cad_build`. End after a successful build, inspection and export.
15
+ Before writing custom build123d source, call `cad_syntax` with the operations you need, such as loft or extrude. Adapt the returned example by substituting the design's dimensions and placement. After an API or Python syntax error, look up the operation again before correcting the source. CAD feature tools already handle their underlying API calls. For other geometry, call `cad_source` with the Python statements that build and return the shape. It provides the imports and model entry point, writes editable source, builds, inspects, and exports in one call. Use `cad_build` to rebuild an existing source file. End after verifying the output.