diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 4a81869..d6e68f7 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -12,7 +12,7 @@ { "name": "shapeitup", "description": "CAD scripting toolkit: create/modify .shape.ts files, validate geometry, check collisions, export STEP/STL/3MF via Replicad + OpenCascade. Runs headless; live 3D preview available if the ShapeItUp VS Code extension is installed.", - "version": "1.30.1", + "version": "1.31.0", "author": { "name": "Asbjorn Rorvik", "email": "rorvik.asbjorn@gmail.com" diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c001c2..92011a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,38 @@ Releases 1.17.0–1.24.0 are described only in their Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); the project follows semantic versioning at the extension level. +## [1.31.0] - 2026-10-22 + +Extension `1.31.0` / mcp-server `1.31.0` — three things benchmark agents hit +while building parts through the MCP tools. + +### Added +- **A script's `console.log` / `console.warn` now reaches the tool result.** + It used to go to the MCP server's stderr, so nobody saw it, and a + try/catch that logged its error and carried on read as a clean success. + `create_shape`, `modify_shape`, `preview_shape`, `tune_params` and + `get_render_status` now end with a `Console output:` block holding the last + 100 lines (500 characters each), and failed renders include whatever the + script printed before it threw. The VS Code viewer is unchanged: every call + still reaches the real console too. + +### Fixed +- **`.or()` on an edge or face finder threw `or is not a function`.** The + `finders` API reference taught `e.inDirection("X").or(e2 => + e2.inDirection("Y"))`, but Replicad only has `.either([...])`, and that + ANDs with the chain before it, so the same line written with `either` + matches nothing. `.or()` now exists on EdgeFinder, FaceFinder and + CornerFinder and keeps the chain so far OR the callback, as the reference + reads. It takes a callback or an array, like `.and()`. The bundled editor + typings declare it and the single-callback `.and()`. +- **`get_render_status` promised a volume it did not report.** Without a + declared material, renders skipped OCCT measurement, so the only way to + learn a part's volume was `export_shape { bom: true }`. A single-part + result is now always measured (volume, surface area, centre of mass); on + the examples this cost nothing measurable. Assemblies keep the fast path, + and the `get_render_status`, `tune_params` and `verify_shape` descriptions + now say when volume is reported and how to get it otherwise. + ## [1.30.1] - 2026-10-12 Extension `1.30.1` / mcp-server `1.30.1` — Codex setup docs and three fixes. diff --git a/packages/core/src/executor.test.ts b/packages/core/src/executor.test.ts index 4693695..770c11e 100644 --- a/packages/core/src/executor.test.ts +++ b/packages/core/src/executor.test.ts @@ -1,6 +1,9 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; import { + createScriptConsole, executeScript, + SCRIPT_CONSOLE_MAX_LINES, + SCRIPT_CONSOLE_MAX_LINE_CHARS, extractConfigStatic, extractExpectedContactsStatic, extractParamsStatic, @@ -1400,3 +1403,95 @@ describe("executeScript — declared vs effective params", () => { expect("declared" in params[0]!).toBe(false); }); }); + +// A script's console.log used to go only to the host's console — the MCP +// server's stderr, where no agent sees it. +describe("executeScript — script console capture", () => { + /** A real-console stand-in that records what was forwarded to it. */ + const sink = () => { + const calls: Array<[string, unknown[]]> = []; + const target = new Proxy({} as Console, { + get: (_t, name) => (...args: unknown[]) => { calls.push([String(name), args]); }, + }); + return { target, calls }; + }; + + it("captures the script's console calls and still forwards them", () => { + const { target, calls } = sink(); + const sc = createScriptConsole(target); + const js = ` + function main() { + console.log("width", 40, { ok: true }); + try { throw new Error("no edges matched"); } + catch (e) { console.warn("fillet skipped:", e); } + console.error("boom"); + return 1; + } + export { main as default }; + `; + executeScript(js, {}, {}, undefined, undefined, sc.console); + expect(sc.lines()).toEqual([ + "width 40 { ok: true }", + "[warn] fillet skipped: Error: no edges matched", + "[error] boom", + ]); + expect(calls.map(([name]) => name)).toEqual(["log", "warn", "error"]); + }); + + it("keeps what was printed before the script threw", () => { + const sc = createScriptConsole(sink().target); + const js = ` + function main() { + console.log("before"); + throw new Error("after"); + } + export { main as default }; + `; + expect(() => executeScript(js, {}, {}, undefined, undefined, sc.console)).toThrow("after"); + expect(sc.lines()).toEqual(["before"]); + }); + + it("keeps the newest lines and says how many it dropped", () => { + const sc = createScriptConsole(sink().target); + for (let i = 0; i < SCRIPT_CONSOLE_MAX_LINES + 5; i++) sc.console.log(`line ${i}`); + const lines = sc.lines(); + expect(lines[0]).toBe("… 5 earlier lines dropped"); + expect(lines).toHaveLength(SCRIPT_CONSOLE_MAX_LINES + 1); + expect(lines.at(-1)).toBe(`line ${SCRIPT_CONSOLE_MAX_LINES + 4}`); + }); + + it("splits multi-line messages and cuts long lines", () => { + const sc = createScriptConsole(sink().target); + sc.console.log("a\nb"); + sc.console.log("x".repeat(SCRIPT_CONSOLE_MAX_LINE_CHARS + 50)); + const lines = sc.lines(); + expect(lines.slice(0, 2)).toEqual(["a", "b"]); + expect(lines[2]).toHaveLength(SCRIPT_CONSOLE_MAX_LINE_CHARS); + expect(lines[2]!.endsWith("…")).toBe(true); + }); + + it("names class instances instead of walking into them", () => { + const sc = createScriptConsole(sink().target); + class Solid { oc = { HEAPU8: new Uint8Array(1 << 20) }; } + class Vector { get repr() { return "x: 1, y: 2, z: 3"; } } + sc.console.log(new Solid(), new Vector(), [1, [2, [3, [4]]]], new Float32Array(3)); + expect(sc.lines()).toEqual(["[Solid] Vector(x: 1, y: 2, z: 3) [1, [2, [3, [Array(1)]]]] Float32Array(3)"]); + }); + + it("records a failed console.assert only", () => { + const sc = createScriptConsole(sink().target); + sc.console.assert(true, "fine"); + sc.console.assert(false, "wall too thin"); + expect(sc.lines()).toEqual(["[error] Assertion failed: wall too thin"]); + }); + + it("uses the real console when none is passed", () => { + const spy = vi.spyOn(console, "log").mockImplementation(() => {}); + try { + executeScript(`function main() { console.log("hi"); return 1; }\nexport { main as default };`, {}, {}); + expect(spy).toHaveBeenCalledWith("hi"); + } finally { + spy.mockRestore(); + } + }); +}); diff --git a/packages/core/src/executor.ts b/packages/core/src/executor.ts index fe01246..398d3f9 100644 --- a/packages/core/src/executor.ts +++ b/packages/core/src/executor.ts @@ -240,6 +240,127 @@ export function rewriteImports(js: string): string { return code; } +/** Lines of script console output kept per execution — the newest win. */ +export const SCRIPT_CONSOLE_MAX_LINES = 100; +/** Characters kept per console line; longer lines end in "…". */ +export const SCRIPT_CONSOLE_MAX_LINE_CHARS = 500; + +/** + * The `console` a script sees, plus what it printed. + * + * Agents drive scripts through MCP tools, where the real console is the + * server's stderr — a `console.log` there reached nobody, and a try/catch that + * logged its error looked exactly like success. The stand-in keeps the lines so + * the tool result can show them, and still forwards every call to the real + * console, so the VS Code worker's DevTools output is unchanged. + */ +export interface ScriptConsole { + console: Console; + /** Captured lines, oldest first, led by a "… N earlier lines dropped" note when the cap was hit. */ + lines(): string[]; +} + +export function createScriptConsole(target: Console = globalThis.console): ScriptConsole { + const kept: string[] = []; + let dropped = 0; + const record = (prefix: string, args: unknown[]) => { + let text: string; + try { + text = args.map((a) => formatConsoleValue(a, 0)).join(" "); + } catch { + text = "[unprintable]"; + } + for (const raw of text.split("\n")) { + const line = prefix + raw; + kept.push( + line.length > SCRIPT_CONSOLE_MAX_LINE_CHARS + ? `${line.slice(0, SCRIPT_CONSOLE_MAX_LINE_CHARS - 1)}…` + : line, + ); + if (kept.length > SCRIPT_CONSOLE_MAX_LINES) { + kept.shift(); + dropped++; + } + } + }; + const forward = (name: string, args: unknown[]) => { + const fn = (target as any)?.[name]; + if (typeof fn === "function") { + try { + fn.apply(target, args); + } catch {} + } + }; + const captured: Record void> = {}; + const prefixes: Record = { + log: "", info: "", debug: "", dir: "", table: "", + warn: "[warn] ", error: "[error] ", trace: "[trace] ", + }; + for (const [name, prefix] of Object.entries(prefixes)) { + captured[name] = (...args: unknown[]) => { + record(prefix, args); + forward(name, args); + }; + } + captured.assert = (condition?: unknown, ...args: unknown[]) => { + if (!condition) record("[error] ", args.length ? ["Assertion failed:", ...args] : ["Assertion failed"]); + forward("assert", [condition, ...args]); + }; + // Anything not captured (time, group, count, ...) goes straight through. + const stand = new Proxy(target, { + get(t, prop) { + if (typeof prop === "string" && prop in captured) return captured[prop]; + const v = (t as any)[prop]; + return typeof v === "function" ? v.bind(t) : v; + }, + }); + return { + console: stand, + lines: () => (dropped > 0 ? [`… ${dropped} earlier line${dropped === 1 ? "" : "s"} dropped`, ...kept] : [...kept]), + }; +} + +/** + * Render one console argument without walking into a live OCCT object: a + * replicad shape holds the whole WASM module, so naive serialisation of + * `console.log(shape)` would try to stringify hundreds of MB of heap. + */ +function formatConsoleValue(v: unknown, depth: number): string { + if (typeof v === "string") return depth === 0 ? v : JSON.stringify(v); + if (v === null || v === undefined || typeof v === "number" || typeof v === "boolean") return String(v); + if (typeof v === "bigint") return `${v}n`; + if (typeof v === "symbol") return v.toString(); + if (typeof v === "function") return `[Function${v.name ? `: ${v.name}` : ""}]`; + if (v instanceof Error) return `${v.name}: ${v.message}`; + if (ArrayBuffer.isView(v)) { + const len = (v as unknown as { length?: number }).length ?? v.byteLength; + return `${v.constructor.name}(${len})`; + } + const MAX_ITEMS = 20; + if (Array.isArray(v)) { + if (depth >= 3) return `[Array(${v.length})]`; + const items = v.slice(0, MAX_ITEMS).map((x) => formatConsoleValue(x, depth + 1)); + if (v.length > MAX_ITEMS) items.push(`… ${v.length - MAX_ITEMS} more`); + return `[${items.join(", ")}]`; + } + const proto = Object.getPrototypeOf(v); + if (proto !== Object.prototype && proto !== null) { + // Class instances: name it, plus replicad's own one-line summary where it + // has one (Vector, BoundingBox, Edge, ...). + const name = proto?.constructor?.name || "Object"; + let repr: unknown; + try { + repr = (v as { repr?: unknown }).repr; + } catch {} + return typeof repr === "string" ? `${name}(${repr})` : `[${name}]`; + } + if (depth >= 3) return "{…}"; + const entries = Object.entries(v as Record); + const shown = entries.slice(0, MAX_ITEMS).map(([k, x]) => `${k}: ${formatConsoleValue(x, depth + 1)}`); + if (entries.length > MAX_ITEMS) shown.push(`… ${entries.length - MAX_ITEMS} more`); + return shown.length ? `{ ${shown.join(", ")} }` : "{}"; +} + /** * Execute a user .shape.ts script (already transpiled/bundled to JS). * @@ -273,6 +394,11 @@ export function executeScript( * engine use, since they can't add a parameter to `core.execute()`. */ fileName?: string, + /** + * The `console` the script's code resolves to — see {@link createScriptConsole}. + * Defaults to the real one. + */ + scriptConsole?: Console, ): { result: any; params: ParamDef[]; @@ -318,8 +444,10 @@ export function executeScript( // on the skill-docs-recommended "export default main alongside named // factory" pattern, i.e. it punished correct usage. + // `console` is a parameter so the script's code (local imports included) + // binds to the stand-in lexically, without touching the global one. const wrapped = ` - return (function(__replicad__, __shapeitup__, __paramOverrides__) { + return (function(__replicad__, __shapeitup__, __paramOverrides__, console) { function highlightFinder(__shape__, __finder__, __opts__) { __opts__ = __opts__ || {}; var matches = __finder__.find(__shape__); @@ -465,7 +593,7 @@ export function executeScript( } return { result: __result__, params: __params__, declaredParams: __declaredParams__, material: __material__, config: __config__, sim: __sim__ }; - })(__replicadExports__, __shapeitupExports__, __paramOverrides__); + })(__replicadExports__, __shapeitupExports__, __paramOverrides__, __console__); `; // Prepend the V8 `sourceURL` pragma so stack traces from user code are @@ -486,6 +614,7 @@ export function executeScript( "__replicadExports__", "__shapeitupExports__", "__paramOverrides__", + "__console__", wrappedWithSource ); const { @@ -498,7 +627,8 @@ export function executeScript( } = fn( replicadExports, shapeitupExports, - paramOverrides || null + paramOverrides || null, + scriptConsole ?? globalThis.console ); // Resolve the script-level `export const material = ...` via the shared diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index d66b82c..18991a7 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -16,7 +16,7 @@ import type { PreviewTargetReport, } from "@shapeitup/shared"; import { faceTargetFinder, resolveFaceTarget } from "./face-target"; -import { executeScript } from "./executor"; +import { createScriptConsole, executeScript } from "./executor"; export { extractParamsStatic, extractConfigStatic, extractExpectedContactsStatic } from "./executor"; import { describeFaces, normalizeParts, tessellatePart, type MeshQuality, type PartInput, type PartStatsLevel, type TessellatedPart } from "./tessellate"; import { exportShapes, exportShapesSplit } from "./exporter"; @@ -171,6 +171,12 @@ export interface ExecutionResult { * declares no `sim`. */ sim?: unknown; + /** + * What the script printed through `console.*`, bounded — see + * createScriptConsole. Empty when it printed nothing. When execute() throws, + * read it from {@link Core.lastConsoleOutput} instead. + */ + consoleOutput: string[]; } /** @@ -779,6 +785,13 @@ export interface Core { * numbers (e.g. an aggregator computing total mass / CoM). */ partStats?: PartStatsLevel; + /** + * Measure a single-part result in full (volume, area, centre of mass) + * when `partStats` is not given. One part costs one measurement, so a + * caller that reports numbers (the MCP server) can afford it; the viewer + * leaves it off and keeps its fast path. + */ + measureSinglePart?: boolean; /** See the matching field on the implementation. */ previewOp?: PreviewFaceOp; /** See {@link PreviewCombine} — a combine applied without writing it. */ @@ -809,6 +822,12 @@ export interface Core { * pointer. Uses the cached OCCT module — callers don't have to thread `oc`. */ resolveError(e: unknown): string; + /** + * The console output of the most recent execute() — the same lines as + * `ExecutionResult.consoleOutput`, but also there when execute() threw, + * which is when a script's own logging matters most. + */ + lastConsoleOutput(): string[]; /** Free OCCT handles from the last execution. Called automatically on each execute(). */ cleanup(): void; } @@ -874,6 +893,7 @@ export async function initCore( instrumentReplicadExports(replicadExports); let lastParts: PartInput[] = []; + let lastScriptConsole: ReturnType | undefined; function cleanup() { for (const part of lastParts) { @@ -1172,6 +1192,7 @@ export async function initCore( onPart?: (part: TessellatedPart, index: number, total: number) => void; meshQuality?: MeshQuality; partStats?: PartStatsLevel; + measureSinglePart?: boolean; /** * Apply a face operation to the result of `main()` without it being in * the source. Drives the viewer's live preview — see applyPreviewOp. @@ -1203,8 +1224,12 @@ export async function initCore( | { strict?: boolean; meshQuality?: MeshQuality } | undefined; let scriptSim: unknown; + const scriptConsole = createScriptConsole(); + lastScriptConsole = scriptConsole; try { - const execResult = executeScript(js, replicadExports, shapeitupStdlib, paramOverrides); + const execResult = executeScript( + js, replicadExports, shapeitupStdlib, paramOverrides, undefined, scriptConsole.console, + ); result = execResult.result; params = execResult.params; material = execResult.material; @@ -1357,8 +1382,13 @@ export async function initCore( // for mass by declaring a material. const hasMaterial = !!material || parts.some((p) => !!(p as { material?: unknown }).material); + // `measureSinglePart` is the same trade made for a single part: one + // measurement, and without it an agent asking "what is this part's + // volume?" had to export a BOM to find out. + const measureAll = + hasMaterial || (streaming?.measureSinglePart === true && parts.length === 1); const partStats: PartStatsLevel = - streaming?.partStats ?? (hasMaterial ? "full" : "bbox"); + streaming?.partStats ?? (measureAll ? "full" : "bbox"); // Tessellate + measure + emit each part before moving to the next, so // `onPart` callers can stream to the viewer as the worker goes. for (let i = 0; i < parts.length; i++) { @@ -1488,6 +1518,7 @@ export async function initCore( material, cutAtOutcomes, sim: scriptSim, + consoleOutput: scriptConsole.lines(), }; } @@ -1526,6 +1557,7 @@ export async function initCore( exportLastSplit, replicad: () => replicad, resolveError: (e: unknown) => resolveWasmException(e, oc), + lastConsoleOutput: () => lastScriptConsole?.lines() ?? [], cleanup, }; } diff --git a/packages/core/src/stdlib/finder-patch.test.ts b/packages/core/src/stdlib/finder-patch.test.ts new file mode 100644 index 0000000..622e280 --- /dev/null +++ b/packages/core/src/stdlib/finder-patch.test.ts @@ -0,0 +1,110 @@ +/** + * The finder `.and()` / `.or()` patches against real OCCT edges, faces and + * drawing corners. + * + * A 10 x 20 x 30 box has 12 edges, four along each axis, and 6 faces, so every + * expected count below can be checked by hand. + */ +import { describe, it, expect, beforeAll } from "vitest"; +import { loadOCCTForTest } from "../testing/occt.js"; +import { ensureFinderPatched, patchFinderOr } from "./finder-patch.js"; + +let rc: typeof import("replicad"); +let box: any; + +beforeAll(async () => { + const oc = await loadOCCTForTest(); + rc = await import("replicad"); + rc.setOC(oc); + ensureFinderPatched(); + // Centred on X/Y, z from 0 to 30. + box = rc.makeBaseBox(10, 20, 30); +}, 120_000); + +const edges = () => new (rc as any).EdgeFinder(); +const faces = () => new (rc as any).FaceFinder(); + +describe("EdgeFinder/FaceFinder .or()", () => { + it("keeps what the chain keeps OR what the callback keeps — the documented example", () => { + expect(edges().inDirection("X").find(box)).toHaveLength(4); + expect(edges().inDirection("X").or((e: any) => e.inDirection("Y")).find(box)).toHaveLength(8); + }); + + it("is not either([fn]) appended to the chain, which ANDs", () => { + // Why the patch can't just forward to either: this is X AND Y. + expect(edges().inDirection("X").either([(e: any) => e.inDirection("Y")]).find(box)).toHaveLength(0); + }); + + it("takes an array of callbacks", () => { + const all = edges() + .inDirection("X") + .or([(e: any) => e.inDirection("Y"), (e: any) => e.inDirection("Z")]) + .find(box); + expect(all).toHaveLength(12); + }); + + it("ANDs filters chained after it with the union", () => { + // Top face: two X edges and two Y edges at z = 30. + const top = edges().inDirection("X").or((e: any) => e.inDirection("Y")).inPlane("XY", 30).find(box); + expect(top).toHaveLength(4); + }); + + it("on a bare finder is either()", () => { + expect(edges().or((e: any) => e.inDirection("Z")).find(box)).toHaveLength(4); + }); + + it("works on FaceFinder", () => { + const caps = faces().inPlane("XY", 0).or((f: any) => f.inPlane("XY", 30)).find(box); + expect(caps).toHaveLength(2); + }); + + it("works inside a fillet/chamfer callback, as the API reference shows it", () => { + const before = rc.measureShapeVolumeProperties(box).volume; + const chamfered = box.chamfer(0.5, (e: any) => e.inDirection("X").or((e2: any) => e2.inDirection("Y"))); + const after = rc.measureShapeVolumeProperties(chamfered).volume; + // A 0.5 mm chamfer removes 0.125 mm³ per mm of edge. X edges alone are + // 4 x 10 mm (5 mm³), Y edges alone 4 x 20 mm (10 mm³); both together + // remove 15 mm³, a little less where they meet at the corners. + expect(before - after).toBeGreaterThan(14); + expect(before - after).toBeLessThanOrEqual(15.001); + }); + + it("says what it takes when given something else", () => { + expect(() => edges().inDirection("X").or(42)).toThrow(/EdgeFinder\.or\(\) takes a callback/); + }); + + it("leaves an existing or() alone and is idempotent", () => { + const own = function or() {}; + class EdgeFinder { + either() {} + } + (EdgeFinder.prototype as any).or = own; + patchFinderOr({ EdgeFinder }); + expect((EdgeFinder.prototype as any).or).toBe(own); + + const real = (rc as any).EdgeFinder.prototype.or; + patchFinderOr(rc); + expect((rc as any).EdgeFinder.prototype.or).toBe(real); + }); +}); + +describe("CornerFinder .or()", () => { + it("rounds two opposite corners of a drawing", () => { + // 10 x 20 rectangle centred on the origin; a r2 fillet on a square corner + // removes r² (1 - π/4) of area. Two corners, extruded 1 mm. + const plate = rc + .drawRectangle(10, 20) + .fillet(2, (c: any) => c.atPoint([5, 10]).or((c2: any) => c2.atPoint([-5, -10]))) + .sketchOnPlane("XY") + .extrude(1); + const removed = 200 - rc.measureShapeVolumeProperties(plate as any).volume; + expect(removed).toBeCloseTo(2 * 4 * (1 - Math.PI / 4), 3); + }); +}); + +describe("EdgeFinder .and() with a single callback", () => { + it("still works next to .or()", () => { + const oneVertical = edges().inDirection("Z").and((e: any) => e.containsPoint([5, 10, 15])).find(box); + expect(oneVertical).toHaveLength(1); + }); +}); diff --git a/packages/core/src/stdlib/finder-patch.ts b/packages/core/src/stdlib/finder-patch.ts index 5a9ec88..6d9c648 100644 --- a/packages/core/src/stdlib/finder-patch.ts +++ b/packages/core/src/stdlib/finder-patch.ts @@ -1,32 +1,46 @@ /** - * ShapeItUp compatibility patch for Replicad EdgeFinder/FaceFinder `.and()`. + * ShapeItUp compatibility patches for Replicad's finders (EdgeFinder, + * FaceFinder, and CornerFinder for 2D drawings): `.and()` and `.or()`. * * Replicad's `.and()` expects an array of predicate callbacks. But the natural * single-callback form `.inDirection("Z").and(e => e.containsPoint(p))` is * widely taught in docs and feels consistent with `.not()`. Without this patch * a single callback throws "findersList.forEach is not a function" from deep - * inside Replicad. + * inside Replicad. We coerce a single function argument to [fn] so both forms + * work. * - * We coerce a single function argument to [fn] so both forms work. The patch - * is idempotent — applying it twice is a no-op thanks to the `__shapeitupPatched` - * sentinel — and safe to call before OCCT is loaded: we only mutate class - * prototypes, which exist on the replicad module at import time. + * Replicad has no `.or()` at all — its OR combinator is `.either([...])`. Our + * docs taught `e.inDirection("X").or(e2 => e2.inDirection("Y"))`, which threw + * "or is not a function"; a script that caught that error went on with no + * fillet at all. `.or()` now exists and means what that line reads as: the + * chain so far OR the callback. That is NOT `either([fn])` appended to the + * chain — `either` adds one more AND-ed filter, so + * `e.inDirection("X").either([e2 => e2.inDirection("Y")])` keeps edges that are + * both X and Y, i.e. none. + * + * The patches are idempotent — applying them twice is a no-op thanks to the + * `__shapeitupPatched` sentinel — and safe to call before OCCT is loaded: we + * only mutate class prototypes, which exist on the replicad module at import + * time. */ import * as replicad from "replicad"; let patched = false; +// CornerFinder shares the Finder base (same `filters` list, same `either`), so +// it gets the same combinators — the bundled typings declare them on that base. +const FINDER_CLASSES = ["EdgeFinder", "FaceFinder", "CornerFinder"]; + /** - * Patch EdgeFinder.prototype.and / FaceFinder.prototype.and in-place to accept - * a single callback in addition to the documented array form. Idempotent. + * Patch each finder class's `.and` in-place to accept a single callback in + * addition to the documented array form. Idempotent. * * Exported so tests can invoke it against a mock replicad module, but the - * stdlib auto-applies it at module load via {@link ensureFinderAndPatched}. + * stdlib auto-applies it at module load via {@link ensureFinderPatched}. */ export function patchFinderAnd(mod: any): void { - const classes = ["EdgeFinder", "FaceFinder"]; - for (const name of classes) { + for (const name of FINDER_CLASSES) { const Klass = mod?.[name]; if (!Klass?.prototype) continue; const originalAnd = Klass.prototype.and; @@ -42,12 +56,58 @@ export function patchFinderAnd(mod: any): void { } /** - * Apply the finder `.and()` patch exactly once per process. Called from - * `stdlib/index.ts` at module load — the replicad module is a singleton, so - * patching the class prototypes once covers every subsequent Shape3D call. + * Add `.or()` to each finder class. Takes a callback or an array of callbacks, + * like the patched `.and()`. + * + * `a.b.or(c)` keeps what `a.b` keeps OR what `c` keeps, and filters chained + * after it AND with that union. On a bare finder there is no chain to OR with, + * so `e.or([f, g])` is exactly `e.either([f, g])`. + * + * Built on Replicad's own `either`: the filters gathered so far move into one + * of its branches. Left alone if Replicad ever ships an `or` of its own. + */ +export function patchFinderOr(mod: any): void { + for (const name of FINDER_CLASSES) { + const Klass = mod?.[name]; + if (!Klass?.prototype || typeof Klass.prototype.either !== "function") continue; + if (typeof Klass.prototype.or === "function") continue; + Klass.prototype.or = function patchedOr(findersList: any) { + const list = typeof findersList === "function" ? [findersList] : findersList; + if (!Array.isArray(list)) { + throw new TypeError( + `${name}.or() takes a callback, e.g. .or(e => e.inDirection("Y")), or an array of them — got ${typeof findersList}.`, + ); + } + const chainSoFar = this.filters; + if (!Array.isArray(chainSoFar) || chainSoFar.length === 0) { + return this.either(list); + } + this.filters = []; + try { + return this.either([ + (f: any) => { + f.filters = chainSoFar; + return f; + }, + ...list, + ]); + } catch (e) { + this.filters = chainSoFar; + throw e; + } + }; + (Klass.prototype.or as any).__shapeitupPatched = true; + } +} + +/** + * Apply the finder `.and()` / `.or()` patches exactly once per process. Called + * from `stdlib/index.ts` at module load — the replicad module is a singleton, + * so patching the class prototypes once covers every subsequent Shape3D call. */ -export function ensureFinderAndPatched(): void { +export function ensureFinderPatched(): void { if (patched) return; patched = true; patchFinderAnd(replicad); + patchFinderOr(replicad); } diff --git a/packages/core/src/stdlib/index.ts b/packages/core/src/stdlib/index.ts index 1ad471c..53bb431 100644 --- a/packages/core/src/stdlib/index.ts +++ b/packages/core/src/stdlib/index.ts @@ -33,14 +33,15 @@ import * as pins from "./pins"; import * as cradles from "./cradles"; import * as standardsRaw from "./standards"; import { guardUnknownKeys } from "./standards"; -import { ensureFinderAndPatched } from "./finder-patch"; +import { ensureFinderPatched } from "./finder-patch"; import { ensureThreadGuardPatched } from "./threads-patch"; // Patch Replicad's EdgeFinder/FaceFinder `.and()` to accept a single callback -// in addition to the documented array form. Idempotent, safe to call before -// OCCT is loaded (the patch only mutates class prototypes on the replicad -// module). See finder-patch.ts for the full rationale. -ensureFinderAndPatched(); +// in addition to the documented array form, and add the `.or()` it lacks. +// Idempotent, safe to call before OCCT is loaded (the patch only mutates class +// prototypes on the replicad module). See finder-patch.ts for the full +// rationale. +ensureFinderPatched(); // Patch `_3DShape.prototype.fuse` / `.cut` to throw at call time (with a clear // message naming the fuse-safe alternatives) when either operand is a diff --git a/packages/extension/package.json b/packages/extension/package.json index 120dc23..48a91ba 100644 --- a/packages/extension/package.json +++ b/packages/extension/package.json @@ -2,7 +2,7 @@ "name": "shapeitup-vscode", "displayName": "ShapeItUp", "description": "Scripted CAD for VS Code — write TypeScript, see 3D, export STEP/STL/3MF (Bambu Studio & OrcaSlicer ready). AI-powered with Claude Code MCP integration.", - "version": "1.30.1", + "version": "1.31.0", "publisher": "shapeitup", "license": "MIT", "icon": "icon.png", diff --git a/packages/extension/typings/replicad/index.d.ts b/packages/extension/typings/replicad/index.d.ts index 88b0b05..ff6e0d0 100644 --- a/packages/extension/typings/replicad/index.d.ts +++ b/packages/extension/typings/replicad/index.d.ts @@ -1070,7 +1070,21 @@ declare abstract class Finder { * * @category Filter Combination */ - and(findersList: ((f: this) => this)[]): this; + // ShapeItUp typings note: the runtime patch in + // packages/core/src/stdlib/finder-patch.ts also accepts a single callback. + and(findersList: ((f: this) => this)[] | ((f: this) => this)): this; + /** + * Keep what the chain so far keeps OR what the callback(s) keep. Filters + * chained after it AND with that union. + * + * ShapeItUp addition (packages/core/src/stdlib/finder-patch.ts) — not in + * upstream Replicad. Unlike {@link either}, which adds one more AND-ed + * filter, `e.inDirection("X").or(e2 => e2.inDirection("Y"))` keeps both + * the X and the Y edges. + * + * @category Filter Combination + */ + or(findersList: ((f: this) => this)[] | ((f: this) => this)): this; /** * Invert the result of a particular finder * diff --git a/packages/mcp-server/package.json b/packages/mcp-server/package.json index c3c56c9..caa8964 100644 --- a/packages/mcp-server/package.json +++ b/packages/mcp-server/package.json @@ -1,6 +1,6 @@ { "name": "@shapeitup/mcp-server", - "version": "1.30.1", + "version": "1.31.0", "description": "ShapeItUp MCP server — scripted CAD tools (Replicad/OpenCascade) for Claude Code, Codex, Cursor, Claude Desktop, and other MCP clients.", "type": "module", "bin": { diff --git a/packages/mcp-server/src/engine.ts b/packages/mcp-server/src/engine.ts index 16f2c0b..f4f11b0 100644 --- a/packages/mcp-server/src/engine.ts +++ b/packages/mcp-server/src/engine.ts @@ -544,6 +544,12 @@ export interface EngineStatus { scriptConfig?: { strict?: boolean; meshQuality?: "preview" | "final"; localFrame?: boolean }; timings?: Record; warnings?: string[]; + /** + * What the script printed through `console.*` during this run, bounded + * (see core's createScriptConsole). Set on failures too — a script's own + * logging is most useful when it threw. Absent when it printed nothing. + */ + consoleOutput?: string[]; /** * False when BRepCheck flagged at least one rendered part as invalid * (non-manifold shell, self-intersection, open topology). When false, the @@ -1024,7 +1030,8 @@ export async function executeShapeFile( * Tessellation-time policy override. Used by `export_shape` when the caller * asks for a BOM sidecar — BOM rows need real volume / mass, which cost the * ~200 ms/part OCCT measurement. Default undefined → `core.execute` picks - * its own (currently `"bbox"`), so normal renders keep their fast path. + * its own: `"full"` for a single part or a declared material, otherwise + * `"bbox"`, so assemblies keep their fast path. */ opts?: { partStats?: "none" | "bbox" | "full"; @@ -1320,7 +1327,12 @@ export async function executeShapeFile( // Thread the caller's `partStats` override (when supplied) into core's // streaming options. Only `"full"` is observably more expensive, so // callers opt in explicitly — e.g. the BOM sidecar path in export_shape. - const streaming = opts?.partStats ? { partStats: opts.partStats } : undefined; + // Without an override, a single-part result is still measured in full: + // that is one OCCT measurement, and it is what puts volume, area and the + // real centre of mass into create_shape / get_render_status. + const streaming = opts?.partStats + ? { partStats: opts.partStats } + : { measureSinglePart: true }; const result = await core.execute(js, paramOverrides, streaming); lastParts = result.parts; lastFileName = absPath; @@ -1448,6 +1460,7 @@ export async function executeShapeFile( hasRemovedMaterial, cutAtCallCount: cutAtCallCount > 0 ? cutAtCallCount : undefined, cutAtFailedCount: cutAtCallCount > 0 ? cutAtFailedCount : undefined, + consoleOutput: result.consoleOutput.length > 0 ? result.consoleOutput : undefined, timestamp: new Date().toISOString(), }; writeStatusFile(successStatus, globalStorageDir); @@ -1465,6 +1478,8 @@ export async function executeShapeFile( // can specialize. Fall back to `undefined` when the source isn't // available — hint generator just uses the generic multi-cause copy. status.hint = inferErrorHint(status.error, status.operation, status.stack, code); + const consoleOutput = core.lastConsoleOutput(); + if (consoleOutput.length > 0) status.consoleOutput = consoleOutput; // Bug #1: OCCT exceptions (thread ops especially) poison the WASM heap — // Emscripten's handle table is corrupted on the C++-exception path, and @@ -2172,7 +2187,7 @@ export function inferErrorHint( // Null shape handed to an operation — usually means a cut consumed the // whole shape or a variable got reassigned/deleted. if (/Standard_NullObject/i.test(msg)) { - return `An operation received a null shape — this often means a boolean cut consumed the shape entirely, or a variable was reassigned. Add \`console.log\` around the failing call to confirm the shape is still valid.`; + return `An operation received a null shape — this often means a boolean cut consumed the shape entirely, or a variable was reassigned. Add \`console.log\` around the failing call to confirm the shape is still valid — its output appears under "Console output" in the result.`; } // Parameter-out-of-range: revolve angle in radians, fillet radius > edge, diff --git a/packages/mcp-server/src/status-report.test.ts b/packages/mcp-server/src/status-report.test.ts new file mode 100644 index 0000000..98af5ff --- /dev/null +++ b/packages/mcp-server/src/status-report.test.ts @@ -0,0 +1,106 @@ +/** + * What a render's status text tells an agent, through the real engine. + * + * Two gaps benchmark agents hit: a script's `console.log` / `console.warn` + * went to the server's stderr (so a try/catch that logged and carried on read + * as a clean success), and a single part's volume was only available from an + * `export_shape { bom: true }`. + */ +import { describe, it, expect, beforeEach } from "vitest"; +import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { clearBundleCache, executeShapeFile } from "./engine.js"; +import { formatStatusText } from "./tools.js"; + +async function render(source: string[]) { + const workdir = mkdtempSync(join(tmpdir(), "siu-status-")); + const storage = mkdtempSync(join(tmpdir(), "siu-status-storage-")); + try { + const file = join(workdir, "part.shape.ts"); + writeFileSync(file, source.join("\n")); + const { status } = await executeShapeFile(file, storage); + return { status, text: formatStatusText(status) }; + } finally { + rmSync(workdir, { recursive: true, force: true }); + rmSync(storage, { recursive: true, force: true }); + } +} + +beforeEach(() => clearBundleCache()); + +describe("status text — the script's console output", () => { + it("shows what a try/catch logged instead of reading as a clean success", async () => { + const { status, text } = await render([ + `import { drawRectangle } from "replicad";`, + `export default function main() {`, + ` let box = drawRectangle(10, 10).sketchOnPlane("XY").extrude(5);`, + ` console.log("box built");`, + ` try {`, + ` box = box.fillet(1, (e) => (e as any).inDirection("X").orr((e2: any) => e2.inDirection("Y")));`, + ` } catch (err) {`, + ` console.warn("fillet skipped:", err);`, + ` }`, + ` return box;`, + `}`, + ]); + expect(status.success).toBe(true); + expect(status.consoleOutput).toEqual([ + "box built", + expect.stringMatching(/^\[warn\] fillet skipped: TypeError: .*orr is not a function/), + ]); + expect(text).toMatch(/\nConsole output:\n {2}box built\n {2}\[warn\] fillet skipped: TypeError/); + }, 60_000); + + it("keeps the output of a script that threw", async () => { + const { status, text } = await render([ + `export default function main() {`, + ` console.log("wall =", 0.4);`, + ` throw new Error("wall too thin");`, + `}`, + ]); + expect(status.success).toBe(false); + expect(status.consoleOutput).toEqual(["wall = 0.4"]); + expect(text).toMatch(/^Render FAILED\nError: .*wall too thin[\s\S]*\nConsole output:\n {2}wall = 0\.4\n/); + }, 60_000); + + it("adds nothing when the script printed nothing", async () => { + const { status, text } = await render([ + `import { drawRectangle } from "replicad";`, + `export default function main() {`, + ` return drawRectangle(10, 10).sketchOnPlane("XY").extrude(5);`, + `}`, + ]); + expect(status.consoleOutput).toBeUndefined(); + expect(text).not.toContain("Console output"); + }, 60_000); +}); + +describe("status text — volume without a material", () => { + it("measures a single part", async () => { + const { status, text } = await render([ + `import { drawRectangle } from "replicad";`, + `export default function main() {`, + ` return drawRectangle(10, 20).sketchOnPlane("XY").extrude(5);`, + `}`, + ]); + expect(status.properties?.totalVolume).toBeCloseTo(1000, 6); + expect(status.properties?.totalSurfaceArea).toBeCloseTo(2 * (200 + 50 + 100), 6); + expect(status.properties?.centerOfMass?.[2]).toBeCloseTo(2.5, 6); + expect(text).toContain("volume: 1000.00 mm³ (1.00 cm³)"); + }, 60_000); + + it("keeps the fast path for an assembly", async () => { + const { status } = await render([ + `import { drawRectangle } from "replicad";`, + `export default function main() {`, + ` const a = drawRectangle(10, 10).sketchOnPlane("XY").extrude(5);`, + ` const b = drawRectangle(10, 10).sketchOnPlane("XY").extrude(5).translateX(20);`, + ` return [{ shape: a, name: "a" }, { shape: b, name: "b" }];`, + `}`, + ]); + expect(status.success).toBe(true); + expect(status.properties?.totalVolume).toBeUndefined(); + expect(status.properties?.parts?.every((p) => p.volume === undefined)).toBe(true); + }, 60_000); +}); diff --git a/packages/mcp-server/src/tools.ts b/packages/mcp-server/src/tools.ts index 06e8a11..078dfb3 100644 --- a/packages/mcp-server/src/tools.ts +++ b/packages/mcp-server/src/tools.ts @@ -864,8 +864,21 @@ export function partExtendsBelowBed(opts: { return true; } +/** + * The script's own `console.*` output. Without this a `console.log` went to the + * MCP server's stderr, and a try/catch that logged its error and carried on + * read as a clean success. + */ +function formatConsoleOutput(status: EngineStatus): string { + const lines = Array.isArray(status.consoleOutput) + ? status.consoleOutput.filter((l): l is string => typeof l === "string") + : []; + return lines.length ? `\nConsole output:\n${lines.map((l) => ` ${l}`).join("\n")}` : ""; +} + export function formatStatusText(status: EngineStatus, verbosity: "summary" | "full" = "summary"): string { const lastShot = formatLastScreenshotLine(status); + const consoleOutput = formatConsoleOutput(status); if (!status.success) { const hint = status.hint ? `\nHint: ${status.hint}` : ""; const operation = status.operation ? `\nFailed operation: ${status.operation}` : ""; @@ -895,7 +908,7 @@ export function formatStatusText(status: EngineStatus, verbosity: "summary" | "f const resetNote = status.engineReset ? `\nEngine was re-initialized after a WASM exception. Next call will take ~500ms.` : ""; - return `Render FAILED\nError: ${status.error}${hint}${operation}${stack}${resetNote}\nFile: ${status.fileName || "unknown"}\nTip: call get_preview to view the last successful render for visual comparison (the PNG is NOT overwritten on failure).${lastShot}\nTime: ${status.timestamp}${getVersionTag()}`; + return `Render FAILED\nError: ${status.error}${hint}${operation}${stack}${resetNote}${consoleOutput}\nFile: ${status.fileName || "unknown"}\nTip: call get_preview to view the last successful render for visual comparison (the PNG is NOT overwritten on failure).${lastShot}\nTime: ${status.timestamp}${getVersionTag()}`; } const parts = status.partNames?.length ? `\nParts: ${status.partNames.join(", ")}` : ""; const paramEntries = status.currentParams ? Object.entries(status.currentParams) : []; @@ -1005,9 +1018,9 @@ export function formatStatusText(status: EngineStatus, verbosity: "summary" | "f if (geomInvalid) { // Hoist the warnings block above stats so the structural problem is the // first thing the reader sees, not an otherwise-normal-looking summary. - return `${headline}\nFile: ${status.fileName || "unknown"}${warnings}\nStats: ${status.stats}${parts}${bbox}${material}${properties}${belowZeroWarn}${currentParams}${timings}${cutAtSummary}${lastShot}\nTime: ${status.timestamp}${getVersionTag()}`; + return `${headline}\nFile: ${status.fileName || "unknown"}${warnings}\nStats: ${status.stats}${parts}${bbox}${material}${properties}${belowZeroWarn}${currentParams}${timings}${cutAtSummary}${consoleOutput}${lastShot}\nTime: ${status.timestamp}${getVersionTag()}`; } - return `${headline}\nFile: ${status.fileName || "unknown"}\nStats: ${status.stats}${parts}${bbox}${material}${properties}${belowZeroWarn}${currentParams}${timings}${warnings}${cutAtSummary}${lastShot}\nTime: ${status.timestamp}${getVersionTag()}`; + return `${headline}\nFile: ${status.fileName || "unknown"}\nStats: ${status.stats}${parts}${bbox}${material}${properties}${belowZeroWarn}${currentParams}${timings}${warnings}${cutAtSummary}${consoleOutput}${lastShot}\nTime: ${status.timestamp}${getVersionTag()}`; } /** @@ -4427,7 +4440,7 @@ export function registerTools(server: McpServer) { server.tool( "tune_params", - "Re-execute an existing .shape.ts with ephemeral `params` overrides WITHOUT modifying the file — the file on disk is untouched. Returns the same stats as get_render_status (volume, surface area, bounding box, timings, warnings) so agents can binary-search a design constraint (target volume, bounding box, mass, fit tolerance) before committing the winning value with modify_shape. Pass `captureScreenshot: true` to also render a PNG of the tuned configuration through the bundled headless SVG pipeline (runs standalone; the ShapeItUp VSCode extension, when open, will also reflect the render in its interactive viewer). Pass `persist: true` to also write the override map to a `.shapeitup-params.json` sidecar next to the file so every later execution (render_preview, open_shape, export_shape, etc.) picks them up automatically; clear with `clear_params`.", + "Re-execute an existing .shape.ts with ephemeral `params` overrides WITHOUT modifying the file — the file on disk is untouched. Returns the same stats as get_render_status (bounding box, timings, warnings, console output, and volume / surface area for a single part or a script that exports a `material`) so agents can binary-search a design constraint (target volume, bounding box, mass, fit tolerance) before committing the winning value with modify_shape. Pass `captureScreenshot: true` to also render a PNG of the tuned configuration through the bundled headless SVG pipeline (runs standalone; the ShapeItUp VSCode extension, when open, will also reflect the render in its interactive viewer). Pass `persist: true` to also write the override map to a `.shapeitup-params.json` sidecar next to the file so every later execution (render_preview, open_shape, export_shape, etc.) picks them up automatically; clear with `clear_params`.", { filePath: z.string().describe("Path to the .shape.ts file. Absolute paths pass through; relative paths are resolved by probing each heartbeat-reported VSCode workspace root (first existing match wins), else anchored to process.cwd()."), params: z.record(z.string(), z.union([z.number(), z.boolean(), z.string()])).describe("Map of param name → override value. Only listed params are overridden; others fall back to the file's declared defaults. Accepts numbers, booleans, and strings so enum-style switches (`{ finish: \"satin\" }`) and feature flags (`{ useHeatSet: true }`) work alongside the usual numeric dimensions."), @@ -5287,7 +5300,7 @@ export function registerTools(server: McpServer) { server.tool( "get_render_status", - "Get the result of the last shape render — whether it succeeded or failed, with stats, geometric properties (volume, area, center of mass, mass when material is exported), and bounding box. Reads the shared status file, which both MCP-driven and VSCode-driven renders write to. Includes currentParams — the resolved values of every exported param, so you don't need to re-read the file to inspect parameter state. For multi-part assemblies, returns per-part stats (name, volume, surface area, center of mass, bounding box, mass) — no separate list_parts tool needed.", + "Get the result of the last shape render — whether it succeeded or failed, with stats, geometric properties, bounding box, and what the script printed with console.log / console.warn (last 100 lines, failed renders included). Volume, surface area and center of mass are measured when the result is a single part; for a multi-part assembly only when the script exports a `material`, which also gives mass. For an assembly without one, `export_shape` with `bom: true` reports each part's volume. Reads the shared status file, which both MCP-driven and VSCode-driven renders write to. Includes currentParams — the resolved values of every exported param, so you don't need to re-read the file to inspect parameter state. For multi-part assemblies, returns per-part stats (name, bounding box, and volume, surface area, center of mass and mass when measured) — no separate list_parts tool needed.", {}, safeHandler("get_render_status", async () => { const statusFile = join(GLOBAL_STORAGE, "shapeitup-status.json"); @@ -6470,7 +6483,7 @@ export function registerTools(server: McpServer) { server.tool( "verify_shape", - "Single-call inspection bundle: executes the shape ONCE and runs any combination of geometry, collision, and joint checks against that single execution. Faster than calling describe_geometry → check_collisions → validate_joints separately (each of those re-executes the shape). Returns a structured JSON report with one section per requested check plus a top-level `ok` flag and `summary`. Pick `checks` to scope the work; per-check options are prefixed (geometryFormat, collisionTolerance, jointTolerance, etc.). Use the individual tools for one-off queries; use this when verifying an assembly comprehensively.", + "Single-call inspection bundle: executes the shape ONCE and runs any combination of geometry, collision, and joint checks against that single execution. Faster than calling describe_geometry → check_collisions → validate_joints separately (each of those re-executes the shape). Returns a structured JSON report with one section per requested check plus a top-level `ok` flag and `summary`. Pick `checks` to scope the work; per-check options are prefixed (geometryFormat, collisionTolerance, jointTolerance, etc.). Use the individual tools for one-off queries; use this when verifying an assembly comprehensively. The report has no volume or mass: get_render_status shows them for the render this call makes (a single part, or a script that exports a `material`).", { filePath: z.string().optional().describe("Path to the .shape.ts file. Mutually exclusive with `code`."), code: z.string().optional().describe("Inline .shape.ts source — written to a temp file, executed, then deleted. Use `workingDir` for relative-import resolution. Mutually exclusive with `filePath`."), @@ -7862,7 +7875,9 @@ EdgeFinder + FaceFinder: .containsPoint([x,y,z]) .atDistance(d, point?) .atAngleWith(dir, angle?) -.and(fn), .or(fn), .not(fn) — compose predicates +.and(fn | [fn, ...]), .not(fn) — compose predicates +.or(fn) — the chain so far OR fn; later filters AND with the union +.either([fn, ...]) — Replicad's OR: one more AND-ed filter, so use it on a bare finder EdgeFinder only: .ofLength(len) — length, or circumference for CIRCLE diff --git a/skills/shapeitup/SKILL.md b/skills/shapeitup/SKILL.md index 2b941f1..b7a0e4e 100644 --- a/skills/shapeitup/SKILL.md +++ b/skills/shapeitup/SKILL.md @@ -520,11 +520,12 @@ f => f.containsPoint([x, y, z]) ```typescript e.inDirection("Z").and(e2 => e2.atDistance(5, [0,0,0])) +e.inDirection("X").or(e2 => e2.inDirection("Y")) e.either([e2 => e2.inDirection("X"), e2 => e2.inDirection("Y")]) e.not(e2 => e2.inPlane("XY")) ``` -Note: `.either(...)` is the canonical OR combinator (Replicad API); some older docs called it `.or`. +`.or(fn)` (a ShapeItUp addition) ORs with everything chained before it: `e.inDirection("X").or(e2 => e2.inDirection("Y"))` keeps X edges and Y edges. Replicad's `.either([...])` adds one more AND-ed filter instead, so on a bare finder the two are the same, but `e.inDirection("X").either([e2 => e2.inDirection("Y")])` keeps nothing. ### `highlightFinder` (injected into every script, no import) @@ -1036,7 +1037,7 @@ Full parameter tables for every stdlib namespace are available via `get_api_refe - `filletEdge` / `chamferEdge` `(shape, edgeFinder, size)` — round or bevel ONE edge, named by a point on it: `(e) => e.containsPoint([0, -depth / 2, thickness])`. Write the coordinates as expressions — a frozen point stops lying on the edge once the part resizes, and the operation vanishes. Note that OCCT carries a fillet across edges that meet smoothly, so on a rounded outline one pick rounds the whole loop. - `extrudeFace` / `filletFace` / `chamferFace` `(shape, faceFinder, size)` — push or pull one planar face along its normal (negative pushes in, holes preserved), or round / bevel the edges around it. These are what the viewer writes when you select a face and press Extrude, Fillet or Chamfer. All three take a **FaceFinder**, not an EdgeFinder: `filletFace` reads the face's own wires, which is exact, whereas `e.inPlane(...)` also catches arcs that merely start in the plane and curve away — and OCCT then rejects the operation. Bind the offset to a parameter — `f.inPlane("XY", thickness)`, not `f.inPlane("XY", 8)` — or the operation silently stops matching the moment that dimension changes. - `joinBodies` / `cutBodies` / `intersectBodies` `(target, tool | tools[])` — Fusion 360's Modify → Combine over whole bodies: union, subtract, keep-only-the-overlap. Prefer these over a bare `.fuse` / `.cut` / `.intersect` when the bodies are MEANT to interact — they measure the result and warn on the three silent failures (a join of bodies that never touch, which returns one "body" of separate lumps; a cut that ate the whole target; an intersect with no overlap, which returns the target unchanged rather than an empty solid). "Keep Tools" needs no argument: a tool that should survive keeps its entry in the returned parts list. These are what the viewer writes when you select two bodies and press Join, Cut or Intersect. -- **Hollowing** — `shellFace(shape, finder, thickness)` leaves the faces the finder MATCHES open and offsets the rest inward; you point at the opening, not at what to keep. More than one match is legitimate (a tube open at both ends). The thickness limit is not a fraction of the part's size — it is the thinnest region the offset passes through, which is often a corner radius: one 60x45x24 box with the top removed caps at 5.0mm with r5 corners and 23mm with sharp ones, same bounding box. Probe rather than predict. `.either([...])` belongs on the bare finder; chaining it after a constraint ANDs instead. +- **Hollowing** — `shellFace(shape, finder, thickness)` leaves the faces the finder MATCHES open and offsets the rest inward; you point at the opening, not at what to keep. More than one match is legitimate (a tube open at both ends). The thickness limit is not a fraction of the part's size — it is the thinnest region the offset passes through, which is often a corner radius: one 60x45x24 box with the top removed caps at 5.0mm with r5 corners and 23mm with sharp ones, same bounding box. Probe rather than predict. `.either([...])` belongs on the bare finder; chaining it after a constraint ANDs instead (`.or(...)` is the one that ORs with the chain). - **Copies** — `joinBodies(arm, arm.clone().mirror("YZ"))` makes one symmetric part; a second entry with the same expression makes a left hand and a right hand. Mirror carries no coordinates at all, so it is the one operation with nothing in it that can go stale. The `.clone()` is required: `.mirror` consumes its receiver and the original is still needed. For repeats use `patterns.repeat(body, patterns.grid(3, 2, 30, 25))` or `patterns.polar(8, 40)` — **not** `patterns.spread(() => body, …)`, whose factory form frees the body on the first placement and throws "This object has been deleted" on the second. - **Positioning a body** — plain replicad `.translate(x, y, z)` and `.rotate(deg, pivot, axis)`, which is what the viewer writes when you drag the Move triad or a Rotate arc. Rotation needs a pivot, and a pivot must never be frozen coordinates: `rotate(45, [20, 5, 3], …)` is correct the day it is written and silently wrong once a parameter moves the body. Write `shape.boundingBox.center` — it recomputes, so the body keeps turning about its own centre — or omit the pivot entirely for `rotate(deg)`, which turns about +Z through the origin. A self-pivot names the shape twice, so give it a `const` rather than rotating an inline expression. `.rotate(…).translate(…)` turns first and then slides; the other order makes the translation part of the radius. **Transforms consume their receiver**: `.translate` / `.rotate` / `.mirror` / `.scale` all end with `this.delete()` (unlike `.fuse` / `.cut` / `.intersect`, which leave both operands alive), so a shape you transform and also name elsewhere must be `.clone()`d first — otherwise the other use reads a freed object and the render dies with "This object has been deleted" on a line that looks fine. `{ shape: boss }, { shape: boss.clone().translate(-40, 0, 0) }` is what the viewer writes for a copy. - `pins` — `pin`, `pivot`, `teeBar` (shafts and hinge axles)