anycad 0.0.0-stage → 1.0.2

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.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +36 -2
  3. package/install.ps1 +41 -0
  4. package/package.json +16 -4
  5. package/runtime/assembly_plan.py +166 -0
  6. package/runtime/build_model.py +78 -0
  7. package/runtime/cad_help.py +147 -0
  8. package/runtime/cad_primitives.py +110 -0
  9. package/runtime/native_plan.py +107 -0
  10. package/runtime/plan.py +148 -0
  11. package/showcase/anycad-preview.png +0 -0
  12. package/showcase/dovetail-0mm.step +3514 -0
  13. package/showcase/dovetail-plus10mm.step +3514 -0
  14. package/showcase/dovetail-preview.png +0 -0
  15. package/showcase/dovetail-prompt.md +3 -0
  16. package/showcase/rounded-bolt-block.step +987 -0
  17. package/src/cad-construct.ts +231 -0
  18. package/src/cad-tools.ts +84 -0
  19. package/src/extension.ts +228 -0
  20. package/src/runtime.ts +5 -0
  21. package/vendor/text-to-cad/package.json +7 -0
  22. package/vendor/text-to-cad/skills/cad/LICENSE +21 -0
  23. package/vendor/text-to-cad/skills/cad/SKILL.md +241 -0
  24. package/vendor/text-to-cad/skills/cad/agents/openai.yaml +4 -0
  25. package/vendor/text-to-cad/skills/cad/references/2d-profiles-and-dxf.md +197 -0
  26. package/vendor/text-to-cad/skills/cad/references/animation.md +115 -0
  27. package/vendor/text-to-cad/skills/cad/references/build123d-modeling.md +206 -0
  28. package/vendor/text-to-cad/skills/cad/references/environments.md +44 -0
  29. package/vendor/text-to-cad/skills/cad/references/exports.md +249 -0
  30. package/vendor/text-to-cad/skills/cad/references/inspection-and-validation.md +383 -0
  31. package/vendor/text-to-cad/skills/cad/references/kinematics.md +478 -0
  32. package/vendor/text-to-cad/skills/cad/references/manufacturing-cnc.md +127 -0
  33. package/vendor/text-to-cad/skills/cad/references/manufacturing-injection-molding.md +133 -0
  34. package/vendor/text-to-cad/skills/cad/references/manufacturing-printing.md +129 -0
  35. package/vendor/text-to-cad/skills/cad/references/manufacturing-review.md +144 -0
  36. package/vendor/text-to-cad/skills/cad/references/manufacturing-sheet-metal.md +167 -0
  37. package/vendor/text-to-cad/skills/cad/references/model-contract.md +281 -0
  38. package/vendor/text-to-cad/skills/cad/references/positioning.md +94 -0
  39. package/vendor/text-to-cad/skills/cad/references/project-layout.md +79 -0
  40. package/vendor/text-to-cad/skills/cad/references/snapshot-review.md +203 -0
  41. package/workflow.md +13 -0
@@ -0,0 +1,231 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { Type, type TSchema } from "typebox";
3
+ import { writeFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { runtimeScript } from "./runtime.ts";
6
+ import registerNativeTools from "./cad-tools.ts";
7
+
8
+ const ref = Type.String({ description: "Name of a previous step" });
9
+ const quantity = Type.Union([Type.Number(), Type.String()]);
10
+ const optional = Type.Optional(quantity);
11
+ const finishedDiameter = "Finished bore diameter in mm. Add clearance when the request gives only the nominal size of a bolt that must pass through.";
12
+ const centers = Type.Array(Type.Number(), { minItems: 1 });
13
+ const xyz = Type.Tuple([Type.Number(), Type.Number(), Type.Number()]);
14
+ const yz = Type.Tuple([Type.Number(), Type.Number()]);
15
+ const step = (op: string, fields: Record<string, TSchema>) =>
16
+ Type.Object({ name: Type.String(), op: Type.Literal(op), ...fields }, { additionalProperties: false });
17
+ const feature = (op: string, fields: Record<string, TSchema>) =>
18
+ Type.Object({ op: Type.Literal(op), ...fields }, { additionalProperties: false });
19
+
20
+ const availableSteps = [
21
+ step("stock", { width: quantity, depth: quantity, height: quantity, bottom: optional, x: optional, y: optional }),
22
+ step("block", { x0: quantity, x1: quantity, y0: quantity, y1: quantity, z0: quantity, z1: quantity }),
23
+ step("rounded_prism", { width: quantity, depth: quantity, radius: quantity, z0: quantity, z1: quantity }),
24
+ step("round_all", { body: ref, radius: quantity }),
25
+ step("round_vertical", { body: ref, radius: quantity }),
26
+ step("cylinder_z", { diameter: quantity, z0: quantity, z1: quantity, x: optional, y: optional }),
27
+ step("cylinder_y", { diameter: quantity, y0: quantity, y1: quantity, x: optional, z: optional }),
28
+ step("cylinder_x", { diameter: quantity, x0: quantity, x1: quantity, y: optional, z: optional }),
29
+ step("drill_through_z", { body: ref, diameter: Type.Union([Type.Number(), Type.String()], { description: finishedDiameter }), x: optional, y: optional }),
30
+ step("drill_through_y", { body: ref, diameter: quantity, x: optional, z: optional }),
31
+ step("drill_through_x", { body: ref, diameter: quantity, y: optional, z: optional }),
32
+ step("drill_pattern_z", { body: ref, diameter: Type.Union([Type.Number(), Type.String()], { description: finishedDiameter }), x_centers: centers, y_centers: centers }),
33
+ step("cut_slots_y", { body: ref, overall_length: quantity, width: quantity, x_centers: centers, y_centers: centers, z0: quantity, z1: quantity }),
34
+ step("slot_y", { overall_length: quantity, width: quantity, x: quantity, y: quantity, z0: quantity, z1: quantity }),
35
+ step("prism_x", { yz_points: Type.Array(yz, { minItems: 3 }), x0: quantity, x1: quantity }),
36
+ step("half_z", { body: ref, plane_z: quantity, upper: Type.Boolean() }),
37
+ step("cut", { body: ref, items: Type.Array(ref, { minItems: 1 }) }),
38
+ step("fuse", { body: ref, items: Type.Array(ref, { minItems: 1 }) }),
39
+ step("translate", { body: ref, dx: quantity, dy: quantity, dz: quantity }),
40
+ step("assembly", { parts: Type.Record(Type.String(), ref) }),
41
+ ];
42
+
43
+ function relevantSteps(text: string) {
44
+ if (!text) return availableSteps;
45
+ const wanted = new Set(["stock", "block", "cut", "fuse"]);
46
+ if (/\b(?:bore|hole|port|cylind)/.test(text)) {
47
+ ["cylinder_z", "drill_through_z", "drill_pattern_z"].forEach((op) => wanted.add(op));
48
+ }
49
+ if (/\b(?:along y|running along y|axis y)\b/.test(text)) {
50
+ ["cylinder_y", "drill_through_y", "prism_x"].forEach((op) => wanted.add(op));
51
+ }
52
+ if (/\b(?:along x|axis x|positive-x face|side port)\b/.test(text)) {
53
+ ["cylinder_x", "drill_through_x", "prism_x"].forEach((op) => wanted.add(op));
54
+ }
55
+ if (/\b(?:round|fillet|pocket)/.test(text)) {
56
+ ["round_all", "round_vertical", "rounded_prism"].forEach((op) => wanted.add(op));
57
+ }
58
+ if (/\bslots?\b/.test(text)) ["slot_y", "cut_slots_y"].forEach((op) => wanted.add(op));
59
+ if (/\b(?:gusset|rib|groove|dovetail)/.test(text)) wanted.add("prism_x");
60
+ if (/\b(?:split|half|halves|seam)\b/.test(text)) wanted.add("half_z");
61
+ if (/\b(?:assembly|separate solid|two-solid)\b/.test(text)) wanted.add("assembly");
62
+ if (/\b(?:offset|travel|translate|slider)\b/.test(text)) wanted.add("translate");
63
+ return availableSteps.filter((schema) => wanted.has(schema.properties.op.const));
64
+ }
65
+
66
+ export default function (pi: ExtensionAPI, cwd: string, requestText: string, fallback: boolean, centered: boolean) {
67
+ const active = registerNativeTools(pi, cwd, fallback, true);
68
+ const nominal = centered && requestText.match(/\bfor (?:an? )?(?:m\s*([0-9.]+)|([0-9.]+)\s*mm) bolt\b/);
69
+ const namedHole = /[ø⌀]|\b(?:diameter|\d+(?:\.\d+)?\s*mm (?:through[- ]?)?(?:hole|bore))\b/.test(requestText);
70
+ const fastener = nominal && !namedHole ? Number(nominal[1] ?? nominal[2]) : 0;
71
+ const clearance = fastener >= 3 && fastener <= 10 ? fastener + 0.5 : undefined;
72
+ const defaultCorners = centered && /\brounded\b/.test(requestText)
73
+ && !/\b(?:r\s*\d+(?:\.\d+)?|radius)\b/.test(requestText);
74
+ async function savePlan(ctx: { cwd: string }, signal: AbortSignal | undefined, args: unknown) {
75
+ await writeFile(join(ctx.cwd, "geometry-plan.json"), JSON.stringify(args, null, 2) + "\n", "utf8");
76
+ const result = await pi.exec("python", [runtimeScript("native_plan.py")], { cwd: ctx.cwd, signal, timeout: 10000 });
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"], {
79
+ cwd: ctx.cwd, signal, timeout: 35000,
80
+ });
81
+ if (build.code !== 0) throw new Error((build.stderr + "\n" + build.stdout).trim());
82
+ return { content: [{ type: "text" as const, text: (result.stdout + build.stdout).trim() }], details: {} };
83
+ }
84
+
85
+ const possibleCuts = [
86
+ feature("drill_pattern_z", { diameter: Type.Number({ description: finishedDiameter }), x_centers: centers, y_centers: centers }),
87
+ ...(requestText === "" || requestText.includes("counterbore") ? [
88
+ feature("counterbore_z", { diameter: Type.Number(), floor: Type.Number(), x: Type.Optional(Type.Number()), y: Type.Optional(Type.Number()) }),
89
+ ] : []),
90
+ ...(requestText === "" || /\b(?:along x|positive-x face|side port)\b/.test(requestText) ? [
91
+ feature("drill_from_positive_x", { diameter: Type.Number(), stop: Type.Number(), y: Type.Number(), z: Type.Number() }),
92
+ ] : []),
93
+ ...(requestText === "" || requestText.includes("along y") ? [
94
+ feature("drill_pattern_y", { diameter: Type.Number(), x_centers: centers, z_centers: centers }),
95
+ ] : []),
96
+ ...(requestText === "" || /\bslots?\b/.test(requestText) ? [
97
+ feature("cut_slots_y", { overall_length: Type.Number(), width: Type.Number(), x_centers: centers, y_centers: centers, z0: Type.Number(), z1: Type.Number() }),
98
+ ] : []),
99
+ ...(requestText === "" || requestText.includes("pocket") ? [
100
+ feature("rounded_prism", { width: Type.Number(), depth: Type.Number(), radius: Type.Number(), z0: Type.Number(), z1: Type.Number() }),
101
+ ] : []),
102
+ ];
103
+ const steppedBores = requestText.includes("mounting holes") && requestText.includes("counterbore")
104
+ && /\b(?:along x|positive-x face|side port)\b/.test(requestText);
105
+ const bracketBores = requestText.includes("slots") && requestText.includes("bore along y")
106
+ && requestText.includes("bolt holes");
107
+ const portIntoAxialBore = requestText.includes("opens into the main bore")
108
+ || requestText.includes("opens into the axial bore");
109
+ let cutFields: TSchema = centered
110
+ ? Type.Array(feature("drill_pattern_z", clearance === undefined
111
+ ? { diameter: Type.Number({ description: finishedDiameter }) } : {}), { minItems: 1, maxItems: 1 })
112
+ : Type.Array(Type.Union(possibleCuts));
113
+ if (steppedBores) cutFields = Type.Object({
114
+ mounting_holes: feature("drill_pattern_z", {
115
+ diameter: Type.Number({ description: "Diameter of the four foot mounting holes" }),
116
+ x_centers: centers, y_centers: centers,
117
+ }),
118
+ axial_bore: feature("drill_through_z", {
119
+ diameter: Type.Number({ description: "Diameter of the main axial Z through bore" }),
120
+ x: Type.Number({ description: "X of the bore axis" }),
121
+ y: Type.Number({ description: "Y of the bore axis" }),
122
+ }),
123
+ upper_counterbore: feature("counterbore_z", {
124
+ diameter: Type.Number({ description: "Diameter of the short upper Z counterbore" }),
125
+ floor: Type.Number({ description: "Absolute Z at its shoulder, the lower end of the counterbore" }),
126
+ x: Type.Number(), y: Type.Number(),
127
+ }),
128
+ positive_x_port: feature("drill_from_positive_x", {
129
+ diameter: Type.Number({ description: "Diameter of the separate cross port" }),
130
+ ...(portIntoAxialBore ? {} : {
131
+ stop: Type.Number({ description: "Absolute X coordinate where the port ends" }),
132
+ }),
133
+ y: Type.Number({ description: "Y of the port axis" }),
134
+ z: Type.Number({ description: "Z height of the port axis" }),
135
+ }),
136
+ }, { additionalProperties: false });
137
+ if (bracketBores) cutFields = Type.Object({
138
+ base_slots: feature("cut_slots_y", {
139
+ overall_length: Type.Number({ description: "Total slot length along Y, including both round ends" }),
140
+ width: Type.Number({ description: "Width along X" }), x_centers: centers, y_centers: centers,
141
+ z0: Type.Number(), z1: Type.Number(),
142
+ }),
143
+ upright_pilot: feature("drill_pattern_y", {
144
+ diameter: Type.Number({ description: "Diameter of the main bore in the upright" }),
145
+ x_centers: centers, z_centers: centers,
146
+ }),
147
+ upright_bolts: feature("drill_pattern_y", {
148
+ diameter: Type.Number({ description: "Diameter of each upright bolt hole" }),
149
+ x_centers: centers, z_centers: centers,
150
+ }),
151
+ }, { additionalProperties: false });
152
+ let stockFields: TSchema = steppedBores && requestText.includes("vertical corners") ? Type.Object({
153
+ foot: feature("stock", {
154
+ width: Type.Number({ description: "Exact foot X size" }),
155
+ depth: Type.Number({ description: "Exact foot Y size" }),
156
+ height: Type.Number({ description: "Exact foot thickness along Z" }),
157
+ bottom: Type.Optional(Type.Number()),
158
+ }),
159
+ rounded_riser: feature("rounded_prism", {
160
+ width: Type.Number({ description: "Riser X size" }),
161
+ depth: Type.Number({ description: "Riser Y size" }),
162
+ radius: Type.Number({ description: "Radius of its four vertical corners" }),
163
+ z0: Type.Number({ description: "Z at the foot's top" }),
164
+ z1: Type.Number({ description: "Absolute Z at the riser's top" }),
165
+ }),
166
+ }, { additionalProperties: false }) : Type.Array(Type.Union([
167
+ feature("stock", { width: Type.Number(), depth: Type.Number(), height: Type.Number(), bottom: Type.Optional(Type.Number()) }),
168
+ feature("block", { x0: Type.Number(), x1: Type.Number(), y0: Type.Number(), y1: Type.Number(), z0: Type.Number(), z1: Type.Number() }),
169
+ feature("rounded_prism", { width: Type.Number(), depth: Type.Number(), radius: Type.Number(), z0: Type.Number(), z1: Type.Number() }),
170
+ feature("prism_x", { yz_points: Type.Array(yz, { minItems: 3 }), x0: Type.Number(), x1: Type.Number() }),
171
+ feature("symmetric_prisms_x", {
172
+ yz_points: Type.Array(yz, { minItems: 3 }), x_centers: centers,
173
+ thickness: Type.Number({ description: "Full thickness along X of each prism" }),
174
+ }),
175
+ ]), { minItems: 1 });
176
+ if (bracketBores && requestText.includes("gussets")) {
177
+ const absoluteBlock = feature("block", {
178
+ x0: Type.Number(), x1: Type.Number(), y0: Type.Number(), y1: Type.Number(),
179
+ z0: Type.Number(), z1: Type.Number(),
180
+ });
181
+ stockFields = Type.Object({
182
+ base: absoluteBlock,
183
+ upright: absoluteBlock,
184
+ paired_gussets: feature("symmetric_prisms_x", {
185
+ yz_points: Type.Array(yz, { minItems: 3, description: "The ordered (Y,Z) vertices of one gusset" }),
186
+ x_centers: centers,
187
+ thickness: Type.Number({ description: "Thickness of each gusset along X" }),
188
+ }),
189
+ }, { additionalProperties: false });
190
+ }
191
+ if (defaultCorners) {
192
+ stockFields = Type.Array(feature("rounded_prism", {
193
+ width: Type.Number(), depth: Type.Number(), z0: Type.Number(), z1: Type.Number(),
194
+ }), { minItems: 1, maxItems: 1 });
195
+ }
196
+
197
+ pi.registerTool({
198
+ name: "cad_solid",
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.",
201
+ parameters: Type.Object({
202
+ stocks: stockFields,
203
+ cuts: cutFields,
204
+ ...(centered || steppedBores || bracketBores ? {} : {
205
+ void: Type.Array(xyz, { minItems: 1, description: "Interior points that must be empty after the cuts" }),
206
+ }),
207
+ }),
208
+ async execute(_id, args, signal, _update, ctx) {
209
+ return savePlan(ctx, signal, centered ? {
210
+ ...args, centered_bore: true, corner_default: defaultCorners, clearance,
211
+ } : args);
212
+ },
213
+ });
214
+
215
+ pi.registerTool({
216
+ name: "cad_construct",
217
+ label: "Create a native CAD model",
218
+ description: "Build editable src/model.py from ordered feature steps. The last step is the finished body or assembly. Stock is centered in X/Y and starts at bottom. Cylinders use diameter and exact endpoints. Use earlier step names for bodies and a quoted parameter name for a varying dimension.",
219
+ parameters: Type.Object({
220
+ steps: Type.Array(Type.Union(relevantSteps(requestText)), { minItems: 1 }),
221
+ 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
+ material: Type.Optional(Type.Array(xyz)),
224
+ parameter: Type.Optional(Type.Object({ name: Type.String(), default: Type.Number() })),
225
+ }),
226
+ async execute(_id, args, signal, _update, ctx) {
227
+ return savePlan(ctx, signal, { ...args, result: args.steps.at(-1)?.name });
228
+ },
229
+ });
230
+ return [...active, "cad_solid", "cad_construct"];
231
+ }
@@ -0,0 +1,84 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import { readFile, writeFile } from "node:fs/promises";
5
+ import { join } from "node:path";
6
+ import { runtimeScript } from "./runtime.ts";
7
+
8
+ type Dimension = { start: number; end: number; label: string };
9
+
10
+ function dimensions(source: string): Map<string, Dimension> {
11
+ const declarations = /^(?<name>[a-z][a-z0-9_]*) = (?:model\.param\(["'][a-z][a-z0-9_]*["'], )?(?<value>-?\d+(?:\.\d+)?)(?:, [^\r\n#]+|\))?(?: +# (?<label>[^\r\n]+))?\r?$/dgm;
12
+ const result = new Map<string, Dimension>();
13
+ for (const match of source.matchAll(declarations)) {
14
+ const { name, label } = match.groups!;
15
+ const [start, end] = match.indices!.groups!.value!;
16
+ result.set(name, { start, end, label: label || name.replaceAll("_", " ") });
17
+ }
18
+ return result;
19
+ }
20
+
21
+ export default function (pi: ExtensionAPI, cwd: string, buildWithoutSource = true, buildAfterDimensions = false) {
22
+ const modelPath = join(cwd, "src", "model.py");
23
+ 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"];
26
+ if (assembly) command.push("--assembly");
27
+ const result = await pi.exec("python", command, { cwd, signal, timeout: 35000 });
28
+ if (result.code !== 0) throw new Error((result.stderr + "\n" + result.stdout).trim());
29
+ return result.stdout.trim();
30
+ }
31
+ const fields = Object.fromEntries([...names].map(([name, dimension]) => [
32
+ name, Type.Number({ description: dimension.label })
33
+ ]));
34
+ if (names.size) {
35
+ pi.registerTool({
36
+ name: "cad_dimensions",
37
+ label: "Set CAD dimensions",
38
+ description: "Set all named dimensions in the existing native CAD model in millimetres."
39
+ + (buildAfterDimensions ? " Then build, verify and export the updated model." : ""),
40
+ parameters: Type.Object(fields, { additionalProperties: false }),
41
+ async execute(_id, args, _signal, _update, ctx) {
42
+ const path = join(ctx.cwd, "src", "model.py");
43
+ let source = await readFile(path, "utf8");
44
+ const current = [...dimensions(source)].reverse();
45
+ if (current.length !== names.size || current.length !== Object.keys(args).length
46
+ || current.some(([name]) => !names.has(name) || !Number.isFinite(args[name]))) {
47
+ throw new Error("Set a number for every current dimension.");
48
+ }
49
+ for (const [name, { start, end }] of current) {
50
+ source = source.slice(0, start) + String(args[name]) + source.slice(end);
51
+ }
52
+ await writeFile(path, source, "utf8");
53
+ const updated = "Updated " + JSON.stringify(args);
54
+ const verified = buildAfterDimensions ? "\n" + await buildModel(ctx.cwd, _signal) : "";
55
+ return { content: [{ type: "text", text: updated + verified }], details: {} };
56
+ },
57
+ });
58
+ }
59
+
60
+ if (buildWithoutSource || (names.size && !buildAfterDimensions)) pi.registerTool({
61
+ name: "cad_build",
62
+ label: "Build and verify CAD",
63
+ 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
+ parameters: Type.Object({ assembly: Type.Optional(Type.Boolean()) }),
65
+ async execute(_id, args, signal, _update, ctx) {
66
+ return { content: [{ type: "text", text: await buildModel(ctx.cwd, signal, args.assembly) }], details: {} };
67
+ },
68
+ });
69
+
70
+ pi.registerTool({
71
+ name: "cad_syntax",
72
+ 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.",
74
+ parameters: Type.Object({ keywords: Type.Array(Type.String(), { minItems: 1, maxItems: 5 }) }),
75
+ async execute(_id, args, signal, _update, ctx) {
76
+ const command = [runtimeScript("cad_help.py"), "--", ...args.keywords];
77
+ const result = await pi.exec("python", command, { cwd: ctx.cwd, signal, timeout: 15000 });
78
+ if (result.code !== 0) throw new Error((result.stderr + "\n" + result.stdout).trim());
79
+ return { content: [{ type: "text", text: result.stdout.trim() }], details: {} };
80
+ },
81
+ });
82
+ return ["cad_syntax", ...(names.size ? ["cad_dimensions"] : []),
83
+ ...(buildWithoutSource || (names.size && !buildAfterDimensions) ? ["cad_build"] : [])];
84
+ }
@@ -0,0 +1,228 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import { writeFile } from "node:fs/promises";
5
+ import { join } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { runtimeScript } from "./runtime.ts";
8
+ import registerNativeTools from "./cad-tools.ts";
9
+ import registerFeatureTools from "./cad-construct.ts";
10
+
11
+ const mm = Type.Number();
12
+ const box = Type.Object({
13
+ width: Type.Number({ description: "X size" }), depth: Type.Number({ description: "Y size" }),
14
+ z0: Type.Number({ description: "Absolute Z bottom" }), z1: Type.Number({ description: "Absolute Z top" }),
15
+ });
16
+ const centers = Type.Array(mm, { minItems: 1, maxItems: 12, description: "Unique coordinates on this axis; the drill visits every X/Y combination" });
17
+ const drill = Type.Object({
18
+ diameter: mm, counter_diameter: mm, counter_depth: mm, x_centers: centers, y_centers: centers,
19
+ });
20
+ 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 fileTools = new Set(["read", "write", "edit"]);
23
+ const workflow = readFileSync(fileURLToPath(new URL("../workflow.md", import.meta.url)), "utf8");
24
+ const dimensionsOrReference = /\b(?:\d+(?:\.\d+)?\s*(?:mm|cm|inch(?:es)?|in)\b|[a-z]{2,}[-_]\d+|datasheet|drawing|model number)|[@][^\s]+/i;
25
+
26
+ function cadRequest(text: string) {
27
+ return /\b(?:cad|build123d|cadquery|freecad|dovetail|stp file|step (?:file|export)|3d (?:model|print))\b|\.(?:step|stp|stl|dxf)\b/i.test(text)
28
+ || (/\b(?:make|create|design|model|draw|build|mount|modify)\b/i.test(text)
29
+ && /\b(?:cube|fillet|mechanical part|bracket|rounded block|spacer|washer|plate with|gear|assembly|shaft support|flange|enclosure)\b/i.test(text));
30
+ }
31
+
32
+ function missingHardwareInterface(text: string) {
33
+ return /\b(?:fit|attach|mount|mate|bracket|adapter)\w*\b/i.test(text)
34
+ && /\b(?:existing|my|our|i have|i own|i bought|i['’]ve got)\b/i.test(text)
35
+ && !dimensionsOrReference.test(text)
36
+ && !/\b(?:rough sketch|concept|generic|use assumptions|use your best guess)\b/i.test(text);
37
+ }
38
+
39
+ function simpleDrilledStock(request: string) {
40
+ return /\b(?:block|blank|spacer|plate)\b/.test(request)
41
+ && /\b(?:hole|bore)\b[^.]{0,40}\b(?:middle|center|centre)\b/.test(request)
42
+ && !/\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
+ }
44
+
45
+ function registerRequestTools(pi: ExtensionAPI, cwd: string, text: string, fallback: boolean, centered = false) {
46
+ const request = text.toLowerCase();
47
+ const split = request.includes("split") && request.includes("shaft") && request.includes("counterbore");
48
+ const dovetail = request.includes("dovetail") && request.includes("slider");
49
+ const shaftSeat = request.match(
50
+ /[ø⌀]\s*(\d+(?:\.\d+)?)\s+counterbore from (?:the )?y\s*=\s*([-+]?\d+(?:\.\d+)?)\s+end(?: only)?,?\s+(\d+(?:\.\d+)?)\s*mm deep/
51
+ );
52
+ const neckEnd = request.match(
53
+ /\btongue\b[^]{0,350}?\b(?:stays|remains)\s+\d+(?:\.\d+)?\s*mm wide (?:up )?to z\s*=\s*([-+]?\d+(?:\.\d+)?)/
54
+ );
55
+ const grooveDimensions = request.match(
56
+ /\bgroove\b[^]{0,240}?\b(\d+(?:\.\d+)?)\s*mm wide at (?:its |the )?(?:flat )?floor z\s*=\s*([-+]?\d+(?:\.\d+)?)\s+and\s+(\d+(?:\.\d+)?)\s*mm wide at (?:its |the )?(?:open )?top z\s*=\s*([-+]?\d+(?:\.\d+)?)/
57
+ );
58
+ const tongueDimensions = request.match(
59
+ /\btongue\b[^]{0,240}?\b(\d+(?:\.\d+)?)\s*mm wide at z\s*=\s*([-+]?\d+(?:\.\d+)?)\s+and\s+(\d+(?:\.\d+)?)\s*mm wide at z\s*=\s*([-+]?\d+(?:\.\d+)?)/
60
+ );
61
+ const declared = text.match(/\b([a-z][a-z0-9_]*)\s*=\s*model\.param\(\s*["']\1["']\s*,\s*([-+]?\d+(?:\.\d+)?)(?=[,)])/);
62
+ const declaredParameter = declared && { name: declared[1], default: Number(declared[2]) };
63
+ const labels = text.match(/\b(?:named (?:solids|parts),?\s*|(?:solids|parts),?\s+named\s+)([a-z][\w-]*)\s+and\s+([a-z][\w-]*)(?=[.,;]|$)/i)?.slice(1) ?? [];
64
+ const guideLabel = labels.find((label) => /(?:guide|rail)/i.test(label));
65
+ const sliderLabel = labels.find((label) => /(?:slider|carriage)/i.test(label));
66
+ const active = split || dovetail
67
+ ? registerNativeTools(pi, cwd, fallback, true)
68
+ : registerFeatureTools(pi, cwd, request, fallback, centered);
69
+
70
+ async function build(kind: string, args: object, cwd: string, signal?: AbortSignal) {
71
+ await writeFile(join(cwd, "geometry-plan.json"), JSON.stringify({ ...args, kind }, null, 2) + "\n", "utf8");
72
+ const source = await pi.exec("python", [runtimeScript("assembly_plan.py")], { cwd, signal, timeout: 10000 });
73
+ if (source.code !== 0) throw new Error((source.stdout + "\n" + source.stderr).trim());
74
+ const result = await pi.exec("python", [
75
+ runtimeScript("build_model.py"), "src/model.py", "--step", "exports/model.step", "--assembly",
76
+ ], { cwd, signal, timeout: 45000 });
77
+ if (result.code !== 0) throw new Error((result.stdout + "\n" + result.stderr).trim());
78
+ return { content: [{ type: "text" as const, text: result.stdout.trim() }], details: {} };
79
+ }
80
+
81
+ if (split || !request) pi.registerTool({
82
+ name: "cad_split_support",
83
+ label: "Build split shaft support",
84
+ description: "Create a shaft support with a base, pedestal, barrel and clamp bridge, then split it at the specified Z seam. Fill every field from the request. The parameter is the shaft-bore diameter. Assembly positions use absolute mm. This builds, measures interference and exports STEP.",
85
+ parameters: Type.Object({
86
+ base: box,
87
+ pedestal: box,
88
+ bridge: box,
89
+ barrel: Type.Object({
90
+ diameter: mm, y0: mm, y1: mm,
91
+ x: Type.Number({ description: "X of shaft and barrel centerline" }),
92
+ z: Type.Number({ description: "Z of shaft and barrel centerline" }),
93
+ }),
94
+ base_slots: Type.Object({
95
+ overall_length: Type.Number({ description: "Full Y slot length including ends" }),
96
+ width: Type.Number({ description: "Slot width along X" }), x_centers: centers, y_centers: centers,
97
+ }),
98
+ ...(shaftSeat ? {} : { shaft_seat: Type.Object({
99
+ diameter: Type.Number({ description: "Larger shaft-seat diameter" }),
100
+ depth: Type.Number({ description: "Depth from the named barrel end" }),
101
+ entry_y: Type.Number({ description: "Absolute Y coordinate of the barrel end where the seat opens" }),
102
+ }) }),
103
+ clamp_bolts: drill,
104
+ split: Type.Object({ z: mm, lower_name: Type.String(), upper_name: Type.String() }),
105
+ ...(declaredParameter ? {} : { parameter }),
106
+ }),
107
+ async execute(_id, args, signal, _update, ctx) {
108
+ const seat = shaftSeat && { diameter: Number(shaftSeat[1]), entry_y: Number(shaftSeat[2]), depth: Number(shaftSeat[3]) };
109
+ return build("split_support", {
110
+ ...args, ...(seat && { shaft_seat: seat }), ...(declaredParameter && { parameter: declaredParameter }),
111
+ }, ctx.cwd, signal);
112
+ },
113
+ });
114
+
115
+ if (dovetail || !request) pi.registerTool({
116
+ name: "cad_dovetail",
117
+ label: "Build dovetail guide and slider",
118
+ description: "Create two separate pieces: a guide with an X-running undercut groove and a slider with a fitted tongue. Use absolute Z, full section width, and centered X/Y. The named parameter translates the complete slider along X. Builds, verifies interference and exports STEP.",
119
+ parameters: Type.Object({
120
+ ...(guideLabel ? {} : { guide_name: Type.String({ description: "Exact requested guide part label" }) }),
121
+ ...(sliderLabel ? {} : { slider_name: Type.String({ description: "Exact requested slider part label" }) }),
122
+ guide_base: box,
123
+ rail: box,
124
+ ...(grooveDimensions ? {} : { groove: Type.Object({
125
+ floor_z: Type.Number({ description: "Absolute Z of the flat groove floor" }),
126
+ floor_width: Type.Number({ description: "Full Y width at the floor" }),
127
+ opening_z: Type.Number({ description: "Absolute Z of the opening at the top of the rail" }),
128
+ opening_width: Type.Number({ description: "Full Y width at the opening" }),
129
+ }) }),
130
+ guide_mounts: drill,
131
+ slider_plate: box,
132
+ ...(tongueDimensions && neckEnd ? {} : { tongue: Type.Object({
133
+ ...(tongueDimensions ? {} : {
134
+ bottom_z: Type.Number({ description: "Absolute Z at the bottom of the tongue" }),
135
+ bottom_width: Type.Number({ description: "Full Y width at the bottom of the tongue" }),
136
+ shoulder_z: Type.Number({ description: "Absolute Z where the taper ends" }),
137
+ neck_width: Type.Number({ description: "Full Y width at and above the shoulder" }),
138
+ }),
139
+ ...(neckEnd ? {} : {
140
+ top_z: Type.Number({ description: "Absolute Z where the constant-width neck ends inside the plate" }),
141
+ }),
142
+ }) }),
143
+ slider_holes: drill,
144
+ transverse_hole: Type.Object({ diameter: mm, x: mm, z: mm }),
145
+ ...(declaredParameter ? {} : { parameter }),
146
+ }),
147
+ async execute(_id, args, signal, _update, ctx) {
148
+ const groove = grooveDimensions ? {
149
+ floor_width: Number(grooveDimensions[1]), floor_z: Number(grooveDimensions[2]),
150
+ opening_width: Number(grooveDimensions[3]), opening_z: Number(grooveDimensions[4]),
151
+ } : args.groove;
152
+ const tongue = {
153
+ ...args.tongue,
154
+ ...(tongueDimensions && {
155
+ bottom_width: Number(tongueDimensions[1]), bottom_z: Number(tongueDimensions[2]),
156
+ neck_width: Number(tongueDimensions[3]), shoulder_z: Number(tongueDimensions[4]),
157
+ }),
158
+ ...(neckEnd && { top_z: Number(neckEnd[1]) }),
159
+ };
160
+ return build("dovetail", {
161
+ ...args, groove, tongue,
162
+ ...(declaredParameter && { parameter: declaredParameter }),
163
+ ...(guideLabel && { guide_name: guideLabel }),
164
+ ...(sliderLabel && { slider_name: sliderLabel }),
165
+ }, ctx.cwd, signal);
166
+ },
167
+ });
168
+ if (split || !request) active.push("cad_split_support");
169
+ if (dovetail || !request) active.push("cad_dovetail");
170
+ return active;
171
+ }
172
+
173
+ export default function (pi: ExtensionAPI) {
174
+ const benchmarkPrompt = process.env.PI_CAD_BENCHMARK_INPUT;
175
+ const benchmark = Boolean(benchmarkPrompt && existsSync(benchmarkPrompt));
176
+ if (benchmark && benchmarkPrompt) {
177
+ registerRequestTools(pi, process.cwd(), readFileSync(benchmarkPrompt, "utf8"), false);
178
+ }
179
+
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
+ });
188
+ pi.on("before_agent_start", (event, ctx) => {
189
+ if (event.messageType !== "user" || ctx.model?.provider !== "lmstudio" || ctx.model.id !== "qwen3.8-9b-distill") return;
190
+ const request = event.prompt;
191
+ const earlier = ctx.sessionManager.getBranch().flatMap((entry) =>
192
+ entry.type === "message" && entry.message.role === "user" ? [entry.message.content] : []);
193
+ const priorText = earlier.flatMap((content) =>
194
+ typeof content === "string" ? [content] : content.filter((item) => item.type === "text").map((item) => item.text))
195
+ .filter((text) => text !== request);
196
+ const followsCad = priorText.some(cadRequest) &&
197
+ (dimensionsOrReference.test(request) || /\b(?:it|the model|the part|the hole|the bracket)\b/i.test(request)
198
+ && /\b(?:resize|move|adjust|change|wider|narrower|taller|shorter|fillet|export)\b/i.test(request));
199
+ if (!benchmark && !cadRequest(request) && !followsCad) return;
200
+ const tools = pi.getActiveTools().filter((name) => !cadTools.has(name));
201
+ if (!benchmark && !tools.length) return;
202
+ previous = { tools: benchmark ? pi.getActiveTools() : tools, thinking: beforeInput ?? pi.getThinkingLevel() };
203
+ pi.setThinkingLevel("low");
204
+ event.systemPromptOptions.sections["native_cad_workflow"] = workflow;
205
+ if (benchmark) return;
206
+
207
+ const hasInterface = event.images?.length || priorText.some((text) => dimensionsOrReference.test(text))
208
+ || earlier.some((content) => typeof content !== "string" && content.some((item) => item.type === "image"));
209
+ if (!hasInterface && missingHardwareInterface(request)) {
210
+ pi.setActiveTools([]);
211
+ 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
+ }
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]);
217
+ });
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);
224
+ }
225
+ previous = undefined;
226
+ beforeInput = undefined;
227
+ });
228
+ }
package/src/runtime.ts ADDED
@@ -0,0 +1,5 @@
1
+ import { fileURLToPath } from "node:url";
2
+
3
+ export function runtimeScript(name: string) {
4
+ return fileURLToPath(new URL(`../runtime/${name}`, import.meta.url));
5
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "name": "pi-native-cad-bundled-skill",
3
+ "version": "0.11.21",
4
+ "private": true,
5
+ "license": "MIT",
6
+ "pi": { "skills": ["./skills/cad"] }
7
+ }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Thompson Labs LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.