Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude-plugin/marketplace.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
32 changes: 32 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
95 changes: 95 additions & 0 deletions packages/core/src/executor.test.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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();
}
});
});
136 changes: 133 additions & 3 deletions packages/core/src/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, (...args: unknown[]) => void> = {};
const prefixes: Record<string, string> = {
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<string, unknown>);
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).
*
Expand Down Expand Up @@ -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[];
Expand Down Expand Up @@ -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__);
Expand Down Expand Up @@ -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
Expand All @@ -486,6 +614,7 @@ export function executeScript(
"__replicadExports__",
"__shapeitupExports__",
"__paramOverrides__",
"__console__",
wrappedWithSource
);
const {
Expand All @@ -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
Expand Down
Loading