← Commit history
.gitignoreadded+2
@@ -0,0 +1,2 @@+dist/+node_modules/
CHANGELOG.mdadded+15
@@ -0,0 +1,15 @@+# Changelog++## 0.1.0 (unreleased)++- First version, tested against SolidCraft 0.53 on Windows.+- solidcraft_* verbs over SolidCraft's own MCP server, in the live window or headless.+- Starts SolidCraft's MCP server with --all-tools and --structured; replies come back as data.+- Never replaces the user's open design: new_design and open use a new tab in live mode,+  replaceActive is refused while the design has unsaved changes, and live batches that would+  replace it are refused.+- Background launch with measured cold/warm progress and blocked_on_user when agent access is off.+- solidcraft_state summarises the design and saves a picture; images are file paths unless inline.+- WSL /mnt/<drive> paths map to Windows paths; WSL-only paths are refused with a hint.+- Strips Adom Bridge's own fields (_callerBudgetMs, aiThread...) before calling SolidCraft.+- Headless run with parameter overrides, settings, progress, and the required uninstall verb.
PUBLISHING.mdadded+29
@@ -0,0 +1,29 @@+# Publishing the SolidCraft bridge++Maintainer notes. Not shipped in the package.++Page: https://wiki.adom.inc/martypm/solidcraft-bridge (owner martypm). Keyword: solidcraft.++## Develop++    node test/run-tests.js                       # stand-in SolidCraft, no app needed+    (cd dist/dev && python3 -m http.server 47391 --bind 127.0.0.1) &+    scripts/dev-deploy.sh                        # install the working copy on this PC, pinned++The dev install remembers the localhost manifest URL. After publishing, reinstall from the wiki+manifest (below) and unpin with bridge_dev_mode {"name":"solidcraft","on":false}.++## Release++1. Bump the version in bridge/bridge.json, bridge/package.json, package.json and page.json.+2. node test/run-tests.js, then scripts/build-release.sh (writes dist/).+3. Runtime:+       adom-wiki release create martypm/solidcraft-bridge <ver> --title "<ver>" --changelog "..."+       adom-wiki release upload martypm/solidcraft-bridge <ver> dist/solidcraft-bridge-v<ver>.zip --platform any+   then push dist/adom-bridge-solidcraft-manifest.json to the page files, and check the zip URL+   in it downloads without signing in.+4. Skills: adom-wiki pkg publish (tarball: SKILL.md, README.md, package.json, install.sh,+   uninstall.sh only).+5. Install from the wiki on the PC:+       adom-bridge bridge_install '{"manifestUrl":"https://wiki.adom.inc/api/v1/pages/martypm/solidcraft-bridge/files/adom-bridge-solidcraft-manifest.json"}'+6. Open the page in pup and look at it before calling it done.
adom-bridge-solidcraft-manifest.jsonadded+12
@@ -0,0 +1,12 @@+{+  "manifest_version": 1,+  "name": "solidcraft",+  "version": "0.1.0",+  "url": "https://wiki.adom.inc/download/martypm/solidcraft-bridge/0.1.0/solidcraft-bridge-v0.1.0.zip",+  "sha256": "7f977dc092a18d5f2bf1c566bad81aa37400581c5a99a85647690645cfc8fb93",+  "size": 16446,+  "verbPrefixes": ["solidcraft_"],+  "healthEndpoint": "/health",+  "updateManifestUrl": "https://wiki.adom.inc/api/v1/pages/martypm/solidcraft-bridge/files/adom-bridge-solidcraft-manifest.json",+  "released_at": "2026-12-03T06:33:02Z"+}
bridge/LICENSEadded+21
@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 MartyPM++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.
bridge/bridge.jsonadded+111
@@ -0,0 +1,111 @@+{+  "manifest_version": 1,+  "name": "solidcraft",+  "displayName": "SolidCraft",+  "version": "0.1.0",+  "description": "Drive SolidCraft, the open-source parametric CAD app, on this PC: the live window or headless jobs, through SolidCraft's own MCP server. Say \"solidcraft\" to the AI to reach this bridge.",+  "homepage": "https://wiki.adom.inc/martypm/solidcraft-bridge",+  "docs": "https://wiki.adom.inc/martypm/solidcraft-bridge",+  "author": "MartyPM",+  "license": "MIT",+  "spawn": {+    "kind": "node",+    "entrypoint": "server.js",+    "port": 0,+    "healthEndpoint": "/health",+    "stopMethod": "kill",+    "killImageName": "node.exe",+    "persistent": true+  },+  "verbPrefixes": [+    "solidcraft_"+  ],+  "verbs": [+    "solidcraft_status",+    "solidcraft_describe",+    "solidcraft_readiness",+    "solidcraft_start",+    "solidcraft_state",+    "solidcraft_tools",+    "solidcraft_call",+    "solidcraft_run",+    "solidcraft_settings",+    "solidcraft_progress",+    "solidcraft_uninstall",+    "solidcraft_open",+    "solidcraft_new_design",+    "solidcraft_execute",+    "solidcraft_batch",+    "solidcraft_set_parameter",+    "solidcraft_check_parameters",+    "solidcraft_undo",+    "solidcraft_redo",+    "solidcraft_measure",+    "solidcraft_topology",+    "solidcraft_inspect",+    "solidcraft_screenshot",+    "solidcraft_compare_picture",+    "solidcraft_save",+    "solidcraft_export",+    "solidcraft_skill",+    "solidcraft_commands",+    "solidcraft_describe_command",+    "solidcraft_find",+    "solidcraft_command",+    "solidcraft_pending"+  ],+  "statusVerb": "solidcraft_status",+  "uninstall": "solidcraft_uninstall",+  "risk": "write",+  "dependencies": {+    "node": ">=18"+  },+  "category": "CAD",+  "tags": [+    "solidcraft",+    "cad",+    "parametric",+    "mcp",+    "step",+    "3d-printing"+  ],+  "platforms": {+    "windows": {+      "supported": true+    },+    "macos": {+      "supported": false,+      "reason": "Not tested yet; the server is plain Node and finds solidcraft-cli on PATH."+    },+    "linux": {+      "supported": false,+      "reason": "Not tested yet."+    }+  },+  "timeouts": {+    "default": 60,+    "verbs": {+      "start": 90,+      "run": 600,+      "execute": 130,+      "batch": 310,+      "export": 310,+      "command": 130,+      "pending": 75+    }+  },+  "detect": {+    "hostApp": "SolidCraft",+    "appPathsExe": "solidcraft.exe",+    "paths": {+      "windows": [+        "%ProgramFiles%\\SolidCraft\\solidcraft.exe",+        "%LOCALAPPDATA%\\Programs\\SolidCraft\\solidcraft.exe"+      ]+    }+  },+  "prewarm": {+    "assets": []+  },+  "updateManifestUrl": "https://wiki.adom.inc/api/v1/pages/martypm/solidcraft-bridge/files/adom-bridge-solidcraft-manifest.json"+}
bridge/package.jsonadded+11
@@ -0,0 +1,11 @@+{+  "name": "adom-solidcraft-bridge",+  "version": "0.1.0",+  "private": true,+  "description": "SolidCraft bridge for Adom Bridge",+  "main": "server.js",+  "scripts": {+    "start": "node server.js"+  },+  "license": "MIT"+}
bridge/server.jsadded+782
@@ -0,0 +1,782 @@+#!/usr/bin/env node+'use strict';+/*+ * SolidCraft bridge for Adom Bridge (ab). Keyword: solidcraft. Verb prefix: solidcraft_.+ *+ * ab spawns this file with `--port <port>`; we bind ADOM_BIND_HOST (127.0.0.1) and serve:+ *   GET  /health, /status   -> health for ab's status chip+ *   POST /command           -> {command|verb, args} -> one JSON response per verb+ *+ * The bridge is an MCP CLIENT of SolidCraft's own MCP server (solidcraft-cli). Two sessions:+ *   live      solidcraft-cli mcp --connect 127.0.0.1:27878   drives the open SolidCraft window+ *   headless  solidcraft-cli mcp --headless --allow-path ...  no window, batch work+ * Tool names and argument schemas come from SolidCraft at runtime (tools/list), never hardcoded,+ * so a SolidCraft update that adds or renames tools needs no bridge release.+ *+ * Node >= 18, no dependencies.+ */++const http = require('http');+const net = require('net');+const fs = require('fs');+const os = require('os');+const path = require('path');+const { spawn, execFile } = require('child_process');++const BRIDGE = 'solidcraft';+const VERSION = readVersion();+const BIND = process.env.ADOM_BIND_HOST || '127.0.0.1';+const IS_WIN = process.platform === 'win32';+const WIN_PATHS = IS_WIN || process.env.SOLIDCRAFT_BRIDGE_WIN_PATHS === '1'; // tests exercise path mapping on Linux+const LIVE_HOST = process.env.SOLIDCRAFT_CONTROL_HOST || '127.0.0.1';+const LIVE_PORT = parseInt(process.env.SOLIDCRAFT_CONTROL_PORT || '27878', 10);+const STATE_DIR = process.env.SOLIDCRAFT_BRIDGE_STATE || path.join(os.homedir(), '.adom', 'bridges', BRIDGE);+const SHOT_DIR = process.env.SOLIDCRAFT_BRIDGE_SHOTS || path.join(__dirname, 'screenshots');+const DEFAULT_SHARED = path.join(os.homedir(), 'cad-projects');+// --all-tools: list every tool, not only the 8 core ones (the rest answer by name either way).+// --structured: every result also carries {result, notes?} as data.+const MCP_FLAGS = ['--all-tools', '--structured'];+const ENABLE_HINT = 'In SolidCraft open Preferences > Assistant > Agents through MCP and tick "Let AI agents connect".';++function readVersion() {+  try { return JSON.parse(fs.readFileSync(path.join(__dirname, 'bridge.json'), 'utf8')).version; } catch { return '0.0.0'; }+}+function log(...a) { process.stdout.write(`[${BRIDGE}] ${a.join(' ')}\n`); }+function mkdirp(d) { try { fs.mkdirSync(d, { recursive: true }); } catch {} }++// ---------------------------------------------------------------------------------------------+// Locating SolidCraft+// ---------------------------------------------------------------------------------------------++/** The command that starts solidcraft-cli: [exe, ...prefixArgs]. SOLIDCRAFT_CLI_CMD (a JSON array)+ *  overrides it, which is how the tests point the bridge at a stand-in server. */+function cliCommand() {+  if (process.env.SOLIDCRAFT_CLI_CMD) {+    try { const a = JSON.parse(process.env.SOLIDCRAFT_CLI_CMD); if (Array.isArray(a) && a.length) return a; } catch {}+  }+  const exe = findInstall('solidcraft-cli');+  return exe ? [exe] : null;+}++function findInstall(base) {+  const name = IS_WIN ? `${base}.exe` : base;+  if (process.env.SOLIDCRAFT_HOME) {+    const p = path.join(process.env.SOLIDCRAFT_HOME, name);+    if (fs.existsSync(p)) return p;+  }+  const dirs = IS_WIN+    ? [process.env.ProgramFiles, process.env['ProgramFiles(x86)'], process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'Programs')]+        .filter(Boolean).map((d) => path.join(d, 'SolidCraft'))+    : ['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin', path.join(os.homedir(), '.local', 'bin'), '/Applications/SolidCraft.app/Contents/MacOS'];+  for (const d of dirs) { const p = path.join(d, name); if (fs.existsSync(p)) return p; }+  return null;+}++function appExe() {+  if (process.env.SOLIDCRAFT_APP) return process.env.SOLIDCRAFT_APP;+  return findInstall(IS_WIN ? 'solidcraft' : 'SolidCraft') || findInstall('solidcraft');+}++function portOpen(host, port, ms = 700) {+  return new Promise((resolve) => {+    const s = net.connect({ host, port });+    const done = (v) => { try { s.destroy(); } catch {} resolve(v); };+    s.setTimeout(ms, () => done(false));+    s.once('connect', () => done(true));+    s.once('error', () => done(false));+  });+}++// ---------------------------------------------------------------------------------------------+// Paths: accept WSL and Windows forms, answer in both+// ---------------------------------------------------------------------------------------------++/** /mnt/c/x/y -> C:\x\y on Windows. Other strings pass through unchanged. */+function toHostPath(p) {+  if (typeof p !== 'string' || !WIN_PATHS) return p;+  const m = /^\/mnt\/([a-zA-Z])(\/.*)?$/.exec(p);+  if (m) return `${m[1].toUpperCase()}:${(m[2] || '\\').replace(/\//g, '\\')}`;+  return p;+}+/** C:\x\y -> /mnt/c/x/y, so a caller in WSL can read the file straight away. */+function toWslPath(p) {+  const m = /^([a-zA-Z]):[\\/](.*)$/.exec(p || '');+  return m ? `/mnt/${m[1].toLowerCase()}/${m[2].replace(/\\/g, '/')}` : null;+}+/** A Linux-only path (not /mnt/<drive>) means nothing to a Windows SolidCraft. */+function isForeignLinuxPath(p) {+  return WIN_PATHS && typeof p === 'string' && p.startsWith('/') && !/^\/mnt\/[a-zA-Z](\/|$)/.test(p);+}+/** Convert every string that looks like a path, at any depth. Returns {value, foreign[]}. */+function convertPaths(v, foreign = []) {+  if (typeof v === 'string') {+    if (isForeignLinuxPath(v) && /\.[a-z0-9]{1,5}$|\/$/i.test(v)) foreign.push(v);+    return { value: toHostPath(v), foreign };+  }+  if (Array.isArray(v)) return { value: v.map((x) => convertPaths(x, foreign).value), foreign };+  if (v && typeof v === 'object') {+    const o = {};+    for (const [k, x] of Object.entries(v)) o[k] = convertPaths(x, foreign).value;+    return { value: o, foreign };+  }+  return { value: v, foreign };+}++// ---------------------------------------------------------------------------------------------+// MCP client over stdio (newline-delimited JSON-RPC 2.0)+// ---------------------------------------------------------------------------------------------++class McpSession {+  constructor(mode, argv) {+    this.mode = mode;+    this.argv = argv;+    this.proc = null;+    this.ready = null;+    this.nextId = 1;+    this.pending = new Map();+    this.buf = '';+    this.stderrTail = '';+    this.tools = null;+    this.serverInfo = null;+    this.startedAt = 0;+    this.exitInfo = null;+  }++  get alive() { return !!this.proc && this.proc.exitCode === null && !this.proc.killed; }++  start() {+    if (this.ready) return this.ready;+    const cmd = cliCommand();+    if (!cmd) return Promise.reject(Object.assign(new Error('solidcraft-cli not found'), { errorCode: 'solidcraft_not_installed' }));+    const [exe, ...pre] = cmd;+    this.startedAt = Date.now();+    this.exitInfo = null;+    this.proc = spawn(exe, [...pre, ...this.argv], { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });+    this.proc.stdout.setEncoding('utf8');+    this.proc.stdout.on('data', (d) => this.onData(d));+    this.proc.stderr.setEncoding('utf8');+    this.proc.stderr.on('data', (d) => { this.stderrTail = (this.stderrTail + d).slice(-4000); });+    this.proc.on('error', (e) => this.onExit(null, e.message));+    this.proc.on('exit', (code, sig) => this.onExit(code, sig));+    this.ready = this.request('initialize', {+      protocolVersion: '2025-06-18',+      capabilities: { roots: { listChanged: false } },+      clientInfo: { name: 'adom-solidcraft-bridge', version: VERSION },+    }, 20000).then((res) => {+      this.serverInfo = res;+      this.notify('notifications/initialized');+      return this.refreshTools();+    }).then(() => this).catch((e) => { this.stop(); throw e; });+    return this.ready;+  }++  async refreshTools() {+    const res = await this.request('tools/list', {}, 20000);+    this.tools = (res && res.tools) || [];+    return this.tools;+  }++  onData(d) {+    this.buf += d;+    let i;+    while ((i = this.buf.indexOf('\n')) >= 0) {+      const line = this.buf.slice(0, i).trim();+      this.buf = this.buf.slice(i + 1);+      if (!line) continue;+      let msg;+      try { msg = JSON.parse(line); } catch { this.stderrTail = (this.stderrTail + '\n[stdout] ' + line).slice(-4000); continue; }+      this.onMessage(msg);+    }+  }++  onMessage(msg) {+    if (msg.id !== undefined && msg.method) return this.onServerRequest(msg);+    if (msg.id === undefined) return; // a notification: nothing we act on yet+    const p = this.pending.get(msg.id);+    if (!p) return;+    this.pending.delete(msg.id);+    clearTimeout(p.timer);+    if (msg.error) p.reject(Object.assign(new Error(msg.error.message || 'MCP error'), { errorCode: 'mcp_error', mcpError: msg.error }));+    else p.resolve(msg.result);+  }++  onServerRequest(msg) {+    let result, error;+    if (msg.method === 'ping') result = {};+    else if (msg.method === 'roots/list') result = { roots: allowedRoots().map((d) => ({ uri: 'file:///' + d.replace(/\\/g, '/').replace(/^\//, ''), name: path.basename(d) })) };+    else error = { code: -32601, message: `method not supported by the Adom bridge: ${msg.method}` };+    this.write(error ? { jsonrpc: '2.0', id: msg.id, error } : { jsonrpc: '2.0', id: msg.id, result });+  }++  onExit(code, sig) {+    this.exitInfo = { code, signal: sig, at: new Date().toISOString(), stderr: this.stderrTail.trim().slice(-1500) };+    const err = Object.assign(new Error(`solidcraft-cli (${this.mode}) exited${code !== null && code !== undefined ? ' with code ' + code : ''}${sig ? ' (' + sig + ')' : ''}`), { errorCode: 'session_closed', stderr: this.exitInfo.stderr });+    for (const p of this.pending.values()) { clearTimeout(p.timer); p.reject(err); }+    this.pending.clear();+    this.proc = null;+    this.ready = null;+    this.tools = null;+  }++  write(obj) {+    if (!this.proc || !this.proc.stdin.writable) throw Object.assign(new Error('session not running'), { errorCode: 'session_closed' });+    this.proc.stdin.write(JSON.stringify(obj) + '\n');+  }++  notify(method, params) { try { this.write({ jsonrpc: '2.0', method, ...(params ? { params } : {}) }); } catch {} }++  request(method, params, timeoutMs = 55000) {+    return new Promise((resolve, reject) => {+      const id = this.nextId++;+      const timer = setTimeout(() => {+        this.pending.delete(id);+        reject(Object.assign(new Error(`${method} took longer than ${Math.round(timeoutMs / 1000)}s`), { errorCode: 'timed_out', stillRunning: true }));+      }, timeoutMs);+      this.pending.set(id, { resolve, reject, timer });+      try { this.write({ jsonrpc: '2.0', id, method, params }); } catch (e) { clearTimeout(timer); this.pending.delete(id); reject(e); }+    });+  }++  async callTool(name, args, timeoutMs) {+    await this.start();+    return this.request('tools/call', { name, arguments: args || {} }, timeoutMs);+  }++  stop() {+    const p = this.proc;+    this.proc = null; this.ready = null; this.tools = null;+    if (p) { try { p.stdin.end(); } catch {} setTimeout(() => { try { p.kill(); } catch {} }, 1500); }+  }+}++const sessions = { live: null, headless: null };+let headlessRoots = [];++function allowedRoots() {+  const s = loadSettings();+  return [...new Set([s.sharedFolder, ...(s.allowPaths || []), ...headlessRoots].filter(Boolean))];+}++function liveSession() {+  if (!sessions.live) sessions.live = new McpSession('live', ['mcp', '--connect', `${LIVE_HOST}:${LIVE_PORT}`, ...MCP_FLAGS]);+  return sessions.live;+}++function headlessSession(extraRoots = []) {+  const want = [...new Set([...allowedRoots(), ...extraRoots.map(toHostPath)])];+  const cur = sessions.headless;+  if (cur && want.every((r) => headlessRoots.includes(r))) return cur;+  if (cur) cur.stop(); // allow-paths are fixed at launch: restart with the wider set+  headlessRoots = want;+  for (const r of want) mkdirp(r);+  sessions.headless = new McpSession('headless', ['mcp', '--headless', ...MCP_FLAGS, ...want.flatMap((r) => ['--allow-path', r])]);+  return sessions.headless;+}++// ---------------------------------------------------------------------------------------------+// Settings, history, progress, screenshots+// ---------------------------------------------------------------------------------------------++function loadSettings() {+  let s = {};+  try { s = JSON.parse(fs.readFileSync(path.join(STATE_DIR, 'settings.json'), 'utf8')); } catch {}+  return { sharedFolder: DEFAULT_SHARED, allowPaths: [], inlineImages: false, ...s };+}+function saveSettings(s) { mkdirp(STATE_DIR); fs.writeFileSync(path.join(STATE_DIR, 'settings.json'), JSON.stringify(s, null, 2)); }++function history() { try { return JSON.parse(fs.readFileSync(path.join(STATE_DIR, 'history.json'), 'utf8')); } catch { return {}; } }+function recordTiming(phase, kind, seconds) {+  const h = history();+  const k = `${phase}:${kind}`;+  h[k] = [...(h[k] || []), Math.round(seconds * 10) / 10].slice(-5);+  mkdirp(STATE_DIR);+  try { fs.writeFileSync(path.join(STATE_DIR, 'history.json'), JSON.stringify(h, null, 2)); } catch {}+}+function estimate(phase, kind, fallback) {+  const xs = (history()[`${phase}:${kind}`] || []).slice().sort((a, b) => a - b);+  return xs.length ? { sec: xs[Math.floor(xs.length / 2)], confidence: 'measured' } : { sec: fallback, confidence: 'estimated' };+}+function timingSummary() {+  const out = {};+  for (const [k, xs] of Object.entries(history())) {+    const s = xs.slice().sort((a, b) => a - b);+    out[k] = { p50: s[Math.floor(s.length / 2)], p90: s[Math.min(s.length - 1, Math.floor(s.length * 0.9))], samples: s.length };+  }+  return out;+}++const active = new Map(); // jobId -> progress block+let jobSeq = 0;+function beginJob(phase, stepLabel, est, startKind) {+  const id = `${phase}-${++jobSeq}`;+  const t0 = Date.now();+  const job = { id, t0, block: { phase, stepLabel, percent: 0, elapsedSec: 0, estimatedSec: est.sec, etaSec: est.sec, confidence: est.confidence, startKind } };+  active.set(id, job);+  job.update = (percent, label, extra = {}) => {+    const el = (Date.now() - t0) / 1000;+    const b = job.block;+    b.percent = Math.max(b.percent, Math.min(99, Math.round(percent)));+    if (label) b.stepLabel = label;+    b.elapsedSec = Math.round(el);+    if (b.elapsedSec > b.estimatedSec) b.estimatedSec = b.elapsedSec + 5;+    b.etaSec = Math.max(0, b.estimatedSec - b.elapsedSec);+    Object.assign(b, extra);+  };+  job.finish = (ok, extra = {}) => {+    active.delete(id);+    const el = (Date.now() - t0) / 1000;+    if (ok) recordTiming(phase, startKind, el);+    return { ...job.block, ...extra, percent: ok ? 100 : job.block.percent, elapsedSec: Math.round(el), etaSec: 0, measured: { phase, seconds: Math.round(el * 10) / 10, startKind } };+  };+  return job;+}++let lastPrune = 0;+function pruneShots() {+  if (Date.now() - lastPrune < 10 * 60 * 1000) return;+  lastPrune = Date.now();+  let files;+  try { files = fs.readdirSync(SHOT_DIR).map((f) => { const p = path.join(SHOT_DIR, f); return { p, t: fs.statSync(p).mtimeMs }; }); } catch { return; }+  files.sort((a, b) => a.t - b.t);+  const cutoff = Date.now() - 48 * 3600 * 1000;+  let keep = files.length;+  for (const f of files) {+    if (f.t < cutoff || keep > 300) { try { fs.unlinkSync(f.p); keep--; } catch {} }+  }+}++function saveImage(b64, mime) {+  mkdirp(SHOT_DIR);+  pruneShots();+  const ext = /jpe?g/.test(mime || '') ? 'jpg' : 'png';+  const p = path.join(SHOT_DIR, `shot-${Date.now()}-${Math.random().toString(36).slice(2, 6)}.${ext}`);+  fs.writeFileSync(p, Buffer.from(b64, 'base64'));+  return p;+}++/** Turn an MCP tool result into a plain bridge response body. */+function shapeToolResult(res, { inline } = {}) {+  const content = (res && res.content) || [];+  const text = content.filter((c) => c.type === 'text').map((c) => c.text).join('\n');+  let data;+  let notes;+  const sc = res && res.structuredContent;+  if (sc !== undefined && sc !== null) {+    if (typeof sc === 'object' && !Array.isArray(sc) && 'result' in sc) { data = sc.result; notes = sc.notes; } else data = sc;+  } else if (text) { try { data = JSON.parse(text); } catch {} }+  const images = content.filter((c) => c.type === 'image' && c.data).map((c) => {+    const file = saveImage(c.data, c.mimeType);+    const img = { path: file, wslPath: toWslPath(file), mimeType: c.mimeType || 'image/png', bytes: Math.round(c.data.length * 0.75) };+    if (inline && c.data.length < 2.8e6) img.image = c.data;+    return img;+  });+  const out = { text: data === undefined ? text || undefined : undefined, data, notes, images: images.length ? images : undefined };+  const others = content.filter((c) => c.type !== 'text' && c.type !== 'image');+  if (others.length) out.otherContent = others;+  return out;+}++// ---------------------------------------------------------------------------------------------+// Verb plumbing+// ---------------------------------------------------------------------------------------------++function ok(body) { return { success: true, ...body }; }+function fail(errorCode, error, extra = {}) { return { success: false, errorCode, error, ...extra }; }++/** Turn a thrown error into the standard failure, with a hint naming the next move. */+function failFrom(e, mode) {+  const code = e.errorCode || 'error';+  const extra = {};+  if (e.stderr) extra.stderr = e.stderr;+  if (e.mcpError) extra.mcpError = e.mcpError;+  if (code === 'solidcraft_not_installed') extra._hint = 'SolidCraft is not installed on this machine. Ask the user to install it from https://solidcraft.io/download, then call solidcraft_status.';+  else if (code === 'session_closed' && mode === 'live') extra._hint = `The live connection to SolidCraft closed. SolidCraft may have been closed or restarted (its access token changes on every launch). Call solidcraft_status; if the app is up, retry: the bridge reconnects automatically. If it keeps failing: ${ENABLE_HINT}`;+  else if (code === 'timed_out') { extra.stillRunning = true; extra.statusVerb = 'solidcraft_status'; extra._hint = 'SolidCraft has not answered yet; it may still be working, or waiting on a dialog in its window. Call solidcraft_state to see the window before retrying.'; }+  else if (code === 'mcp_error') extra._hint = 'SolidCraft rejected the call. Check the arguments against the tool schema: solidcraft_tools {"name":"<tool>"}.';+  return fail(code, e.message, { mode, ...extra });+}++async function liveReady() {+  const cmd = cliCommand();+  if (!cmd) return fail('solidcraft_not_installed', 'solidcraft-cli was not found', { _hint: 'Ask the user to install SolidCraft from https://solidcraft.io/download.' });+  if (!(await portOpen(LIVE_HOST, LIVE_PORT))) {+    return fail('app_not_running', `Nothing is listening on SolidCraft's control port ${LIVE_HOST}:${LIVE_PORT}.`, {+      _hint: `SolidCraft is closed, or agent access is off. Call solidcraft_start to launch it in the background. If it is already open: ${ENABLE_HINT} For work without a window, pass mode:"headless".`,+      _next: ['solidcraft_start', 'solidcraft_status'],+    });+  }+  return null;+}++/** Pick the session for a verb. mode: "live" (default) or "headless". */+async function sessionFor(args) {+  const mode = (args && args.mode) || 'live';+  if (mode === 'headless') {+    if (!cliCommand()) return { err: fail('solidcraft_not_installed', 'solidcraft-cli was not found', { _hint: 'Ask the user to install SolidCraft from https://solidcraft.io/download.' }) };+    const extra = [].concat((args && args.allowPaths) || []);+    return { mode, s: headlessSession(extra) };+  }+  if (mode !== 'live') return { err: fail('bad_args', `mode must be "live" or "headless", not "${mode}"`) };+  const notReady = await liveReady();+  if (notReady) return { err: notReady };+  return { mode, s: liveSession() };+}++async function callNamedTool(tool, args, opts = {}) {+  const { mode, s, err } = await sessionFor(args);+  if (err) return err;+  const { mode: _m, allowPaths: _a, inline, timeoutSec, replaceActive, ...rest } = args || {};+  const conv = convertPaths(rest);+  if (conv.foreign.length) {+    return fail('path_not_shared', `These paths exist only inside WSL, so SolidCraft on Windows cannot see them: ${conv.foreign.join(', ')}`, {+      _hint: `Put the file in the shared folder (${toWslPath(loadSettings().sharedFolder) || loadSettings().sharedFolder}) and pass that path; /mnt/c/... paths are converted for you.`,+    });+  }+  try {+    await s.start();+    if (mode === 'live') {+      const g = await guardActiveDesign(s, tool, conv.value, !!replaceActive);+      if (g.err) return { ...g.err, mode };+      if (g.args) conv.value = g.args;+    }+    let res;+    try {+      res = await s.callTool(tool, conv.value, (timeoutSec || opts.timeoutSec || 55) * 1000);+    } catch (e) {+      if (e.errorCode === 'mcp_error' && /unknown tool|no such tool|not found|-32601/i.test(`${e.message} ${e.mcpError && e.mcpError.code}`)) {+        return fail('tool_unavailable', `SolidCraft (${mode}) has no "${tool}" tool: ${e.message}`, {+          mode, availableTools: (s.tools || []).map((t) => t.name),+          _hint: 'This SolidCraft version has no such tool. Pick one from availableTools and call it with solidcraft_call {"tool":"<name>","arguments":{...}}, or run the command through solidcraft_find + solidcraft_command.',+        });+      }+      throw e;+    }+    const shaped = shapeToolResult(res, { inline: inline !== undefined ? !!inline : loadSettings().inlineImages });+    if (res && res.isError) {+      return fail('tool_error', shaped.text || `SolidCraft's ${tool} tool reported an error`, { mode, tool, ...shaped, _hint: `Check the arguments against the schema: solidcraft_tools {"name":"${tool}"}. For modelling guidance call solidcraft_skill.` });+    }+    return ok({ mode, tool, ...shaped, ...(opts.hint ? { _hint: opts.hint } : {}), ...(opts.next ? { _next: opts.next } : {}) });+  } catch (e) { return failFrom(e, mode); }+}++// ---- Protecting the user's open design (live mode only) -------------------------------------+// In the live app, `new_design` and `open` REPLACE the active design, discarding unsaved changes.+// The user is usually working in that design, so the bridge never replaces it unless the caller+// passes replaceActive:true, and even then refuses while it has unsaved changes.+async function activeDesignDirty(s) {+  try {+    const r = shapeToolResult(await s.callTool('inspect_design', { timeline: false, bodies: false, sketches: false, joints: false, measure: false }, 20000));+    return { dirty: !!(r.data && r.data.dirty), name: r.data && r.data.name };+  } catch { return { dirty: true, name: null }; } // unknown counts as dirty: never risk the user's work+}+const unsavedErr = (d) => fail('unsaved_changes', `The open design${d.name ? ` "${d.name}"` : ''} has unsaved changes; replacing it would lose them.`, {+  _hint: 'Leave replaceActive off so the bridge opens a new tab, or ask the user to save first.',+});+async function guardActiveDesign(s, tool, a, replaceActive) {+  if (tool === 'new_design') {+    if (!replaceActive) return { args: { new_tab: true, ...a } };+    if (a.new_tab) return {};+    const d = await activeDesignDirty(s); return d.dirty ? { err: unsavedErr(d) } : {};+  }+  if (tool === 'open') {+    if (replaceActive) { const d = await activeDesignDirty(s); return d.dirty ? { err: unsavedErr(d) } : {}; }+    const name = path.basename(String(a.path || a.file || 'Opened')).replace(/\.[^.]+$/, '');+    try { await s.callTool('new_design', { new_tab: true, name }, 30000); } catch (e) { return { err: fail('new_tab_failed', `Could not open a new tab for the file: ${e.message}`, { _hint: 'Ask the user, or pass replaceActive:true to replace the active design (refused while it has unsaved changes).' }) }; }+    return {};+  }+  if (tool === 'batch' && !replaceActive) {+    const steps = Array.isArray(a.commands) ? a.commands : [];+    const bad = steps.findIndex((st) => st && (st.command === 'open' || (st.command === 'new_design' && !(st.params && st.params.new_tab))));+    if (bad >= 0) return { err: fail('would_replace_design', `Step ${bad} (${steps[bad].command}) would replace the user's open design.`, { _hint: 'Run solidcraft_new_design (it opens a new tab) or solidcraft_open first, then batch the modelling steps; or give new_design {"new_tab":true}.' }) };+  }+  return {};+}++// Thin verbs: solidcraft_<verb> -> SolidCraft MCP tool. Arguments pass straight through, so they+// follow SolidCraft's own schema (see solidcraft_tools). Tool names per SolidCraft 0.49: find_commands,+// call_command, batch, inspect_design, measure, body_topology, skill_reference and pending are the+// core; the rest are listed only with --all-tools but always answer by name.+const TOOL_VERBS = {+  find:             { tool: 'find_commands',     risk: 'read',  sum: 'Search SolidCraft commands by words; returns ids and their parameters.', next: ['solidcraft_command', 'solidcraft_batch'] },+  command:          { tool: 'call_command',      risk: 'write', sum: 'Run one SolidCraft command by id with JSON params, as the toolbar does.', next: ['solidcraft_state', 'solidcraft_measure'], timeoutSec: 120 },+  pending:          { tool: 'pending',           risk: 'read',  sum: 'The result of a SolidCraft request that was still running (waits up to 60 s).', timeoutSec: 70 },+  open:             { tool: 'open',              risk: 'read',  sum: 'Open a design or import a STEP/IGES/STL/3MF/KiCad file.', next: ['solidcraft_inspect', 'solidcraft_state'] },+  new_design:       { tool: 'new_design',        risk: 'write', sum: 'Start a new empty design.', next: ['solidcraft_execute', 'solidcraft_batch'] },+  execute:          { tool: 'execute',           risk: 'write', sum: 'Run one SolidCraft command (sketch, extrude, fillet, shell, hole, pattern...).', next: ['solidcraft_state', 'solidcraft_measure'], timeoutSec: 120 },+  batch:            { tool: 'batch',             risk: 'write', sum: 'Run several SolidCraft commands as one step.', next: ['solidcraft_state', 'solidcraft_measure'], timeoutSec: 300 },+  set_parameter:    { tool: 'set_parameter',     risk: 'write', sum: 'Change a named parameter and rebuild the timeline.', next: ['solidcraft_check_parameters', 'solidcraft_state'] },+  check_parameters: { tool: 'check_parameters',  risk: 'read',  sum: 'Check every named parameter rebuilds cleanly.' },+  undo:             { tool: 'undo',              risk: 'write', sum: 'Undo the last change.' },+  redo:             { tool: 'redo',              risk: 'write', sum: 'Redo the last undone change.' },+  measure:          { tool: 'measure',           risk: 'read',  sum: 'Measure distances, sizes and clearances.' },+  topology:         { tool: 'body_topology',     risk: 'read',  sum: 'List the faces, edges and vertices of a body.' },+  inspect:          { tool: 'inspect_design',    risk: 'read',  sum: 'Describe the open design: bodies, features, parameters.' },+  screenshot:       { tool: 'screenshot',        risk: 'read',  sum: 'Render the current view as an image.' },+  compare_picture:  { tool: 'compare_picture',   risk: 'read',  sum: 'Compare the current view with a reference picture.' },+  save:             { tool: 'save',              risk: 'write', sum: 'Save the design (.sc).' },+  export:           { tool: 'export',            risk: 'write', sum: 'Export STEP, STL, 3MF, DXF and more.', timeoutSec: 300 },+  skill:            { tool: 'skill_reference',   risk: 'read',  sum: "Read one of SolidCraft's own modelling skills (modeling, editing, checking, mechanisms, reporting)." },+  commands:         { tool: 'list_commands',     risk: 'read',  sum: 'List every SolidCraft modelling command.' },+  describe_command: { tool: 'describe_command',  risk: 'read',  sum: 'Show the arguments of one SolidCraft command.' },+};++// ---------------------------------------------------------------------------------------------+// Verbs+// ---------------------------------------------------------------------------------------------++const focusEvents = [];++async function vStatus() {+  const cmd = cliCommand();+  const app = appExe();+  const live = cmd ? await portOpen(LIVE_HOST, LIVE_PORT) : false;+  const sess = (s) => s && { connected: s.alive, tools: s.tools ? s.tools.length : null, server: s.serverInfo && s.serverInfo.serverInfo, lastExit: s.exitInfo || undefined };+  let hint;+  if (!cmd) hint = 'SolidCraft is not installed. Ask the user to install it from https://solidcraft.io/download.';+  else if (!live) hint = `SolidCraft is installed but its control port is closed: the app is not running, or agent access is off. Call solidcraft_start, or work without a window with mode:"headless". ${ENABLE_HINT}`;+  else hint = 'SolidCraft is running and accepts agents. Call solidcraft_state to see the design, or solidcraft_tools to list what it can do.';+  return ok({+    bridge: BRIDGE, version: VERSION,+    installed: !!cmd, cli: cmd ? cmd.join(' ') : null, app: app || null,+    appRunning: live, controlPort: `${LIVE_HOST}:${LIVE_PORT}`,+    sessions: { live: sess(sessions.live) || null, headless: sess(sessions.headless) || null },+    sharedFolder: loadSettings().sharedFolder, sharedFolderWsl: toWslPath(loadSettings().sharedFolder),+    activeJobs: active.size,+    _hint: hint,+    _next: !cmd ? [] : live ? ['solidcraft_state', 'solidcraft_tools'] : ['solidcraft_start'],+  });+}++async function vStart(args = {}) {+  const exe = appExe();+  if (!exe) return fail('solidcraft_not_installed', 'SolidCraft was not found', { _hint: 'Ask the user to install SolidCraft from https://solidcraft.io/download.' });+  if (await portOpen(LIVE_HOST, LIVE_PORT)) {+    return ok({ alreadyRunning: true, windowEtiquette: 'background', startKind: 'warm', progress: { phase: 'start', stepLabel: 'SolidCraft is already running - reusing it', percent: 100, elapsedSec: 0, etaSec: 0, confidence: 'measured', startKind: 'warm' }, _hint: 'SolidCraft is already running and accepts agents. Call solidcraft_state.', _next: ['solidcraft_state'] });+  }+  if (args.foreground && !args.foregroundReason) {+    return fail('foreground_reason_required', 'foreground:true needs a foregroundReason the user would accept.', { _hint: 'Leave foreground off (SolidCraft opens minimised), or pass foregroundReason explaining why the user must see the window now.' });+  }+  const est = estimate('start', 'cold', 30);+  const job = beginJob('start', 'Launching SolidCraft', est, 'cold');+  const fg = !!args.foreground;+  if (IS_WIN) {+    spawn('cmd.exe', ['/d', '/c', 'start', '""', fg ? '' : '/min', `"${exe}"`].filter(Boolean), { detached: true, stdio: 'ignore', windowsHide: true, windowsVerbatimArguments: true }).unref();+  } else {+    spawn(exe, [], { detached: true, stdio: 'ignore' }).unref();+  }+  focusEvents.push({ at: new Date().toISOString(), event: fg ? 'launched-foreground' : 'launched-minimised', cause: fg ? args.foregroundReason : 'solidcraft_start' });+  const waitSec = Math.min(Math.max(parseInt(args.waitSec || 75, 10), 5), 85);+  const t0 = Date.now();+  while ((Date.now() - t0) / 1000 < waitSec) {+    await new Promise((r) => setTimeout(r, 1000));+    const el = (Date.now() - t0) / 1000;+    job.update(Math.min(95, (el / job.block.estimatedSec) * 90), el < 5 ? 'Launching SolidCraft' : 'Waiting for SolidCraft to accept agents');+    if (await portOpen(LIVE_HOST, LIVE_PORT)) {+      const progress = job.finish(true, { stepLabel: 'SolidCraft is up and accepts agents' });+      return ok({ started: true, windowEtiquette: fg ? 'foreground' : 'background', startKind: 'cold', progress, _hint: 'SolidCraft is running. Call solidcraft_state to see it.', _next: ['solidcraft_state', 'solidcraft_open', 'solidcraft_new_design'] });+    }+  }+  const progress = job.finish(false, { blockedBy: 'Tick "Let AI agents connect" in SolidCraft', failedSteps: ['wait_for_control_port'] });+  return fail('blocked_on_user', `SolidCraft was launched but its control port ${LIVE_PORT} did not open within ${waitSec}s.`, {+    stillRunning: true, blockedBy: `the user must allow agents: ${ENABLE_HINT}`, windowEtiquette: fg ? 'foreground' : 'background', progress,+    _hint: `SolidCraft starts with agent access off until the user enables it once. Ask the user to do this: ${ENABLE_HINT} Then call solidcraft_status. Do not relaunch it.`,+  });+}++async function vState(args = {}) {+  const status = await vStatus();+  const out = { appRunning: status.appRunning, windowEtiquette: 'background', focusEvents: focusEvents.slice(-20) };+  if (!status.appRunning && (args.mode || 'live') === 'live') {+    return ok({ ...out, _hint: 'SolidCraft is not running (or agent access is off), so there is no live design to show. Call solidcraft_start.', _next: ['solidcraft_start'] });+  }+  // A summary by default: a full inspect of a real part (every body measured, every sketch) runs to+  // hundreds of KB, far more than an AI should read to orient itself. full:true asks for everything.+  const inspectArgs = args.full ? { mode: args.mode } : { mode: args.mode, timeline: 'summary', bodies: 'names', sketches: false, joints: 'summary' };+  const inspect = await callNamedTool('inspect_design', inspectArgs);+  out.design = inspect.success ? (inspect.data !== undefined ? inspect.data : inspect.text) : { error: inspect.error, errorCode: inspect.errorCode };+  if (args.screenshot !== false) {+    const shot = await callNamedTool('screenshot', { mode: args.mode, inline: args.inline });+    out.shots = shot.success ? shot.images || [] : [];+    if (!shot.success) out.screenshotError = { error: shot.error, errorCode: shot.errorCode };+  }+  out._hint = 'This is the design as SolidCraft sees it now. For the whole SolidCraft window including dialogs, call adom-bridge desktop_screenshot_window {"titleContains":"SolidCraft"}.';+  out._next = ['solidcraft_execute', 'solidcraft_set_parameter', 'solidcraft_measure', 'solidcraft_export'];+  return ok(out);+}++async function vTools(args = {}) {+  const { mode, s, err } = await sessionFor(args);+  if (err) return err;+  try {+    await s.start();+    await s.refreshTools();+    const tools = s.tools;+    if (args.name) {+      const t = tools.find((x) => x.name === args.name);+      if (!t) return fail('tool_unavailable', `No tool named "${args.name}"`, { mode, availableTools: tools.map((x) => x.name) });+      return ok({ mode, tool: t, _hint: `Call it with solidcraft_call {"tool":"${t.name}","arguments":{...}}, or its solidcraft_<verb> shortcut if one exists.` });+    }+    return ok({ mode, count: tools.length, tools: tools.map((t) => ({ name: t.name, description: t.description })), _hint: 'Pass {"name":"<tool>"} for one tool\'s full argument schema.' });+  } catch (e) { return failFrom(e, mode); }+}++async function vCall(args = {}) {+  if (!args.tool) return fail('bad_args', 'tool is required', { _hint: 'solidcraft_call {"tool":"<name>","arguments":{...}}. List names with solidcraft_tools.' });+  return callNamedTool(args.tool, { ...(args.arguments || {}), mode: args.mode, allowPaths: args.allowPaths, inline: args.inline, timeoutSec: args.timeoutSec });+}++async function vRun(args = {}) {+  const cmd = cliCommand();+  if (!cmd) return fail('solidcraft_not_installed', 'solidcraft-cli was not found', { _hint: 'Ask the user to install SolidCraft from https://solidcraft.io/download.' });+  if (!args.in) return fail('bad_args', '"in" (the .sc design to run) is required', { _hint: 'solidcraft_run {"in":"/mnt/c/Users/<you>/cad-projects/part.sc","params":{"slots":7},"out":"...part.step"}' });+  const conv = convertPaths({ in: args.in, out: args.out, save: args.save });+  if (conv.foreign.length) return fail('path_not_shared', `WSL-only paths: ${conv.foreign.join(', ')}`, { _hint: 'Use the shared folder under /mnt/c so SolidCraft on Windows can see the files.' });+  const argv = ['run', '--in', conv.value.in];+  for (const [k, v] of Object.entries(args.params || {})) argv.push('--param', `${k}=${v}`);+  if (conv.value.out) argv.push('--out', conv.value.out);+  if (conv.value.save) argv.push('--save', conv.value.save);+  const est = estimate('run', 'cold', 20);+  const job = beginJob('run', `Rebuilding ${path.basename(String(args.in))}`, est, 'cold');+  const tick = setInterval(() => job.update(((Date.now() - job.t0) / 1000 / job.block.estimatedSec) * 90), 1000);+  const [exe, ...pre] = cmd;+  return new Promise((resolve) => {+    execFile(exe, [...pre, ...argv], { timeout: (args.timeoutSec || 590) * 1000, windowsHide: true, maxBuffer: 16 * 1024 * 1024 }, (e, stdout, stderr) => {+      clearInterval(tick);+      const progress = job.finish(!e);+      const files = [conv.value.out, conv.value.save].filter(Boolean).map((p) => ({ path: p, wslPath: toWslPath(p), exists: fs.existsSync(p) }));+      if (e) return resolve(fail('run_failed', `solidcraft-cli run failed: ${e.message}`, { exitCode: e.code, stdout: stdout.slice(-4000), stderr: stderr.slice(-4000), progress, _hint: 'Read stderr: usually a parameter name that does not exist in the design, or an output folder SolidCraft may not write to.' }));+      let data; try { data = JSON.parse(stdout); } catch {}+      resolve(ok({ files, data, stdout: data === undefined ? stdout.slice(-4000) : undefined, progress, _hint: 'Done. The files are listed with their WSL paths.' }));+    });+  });+}++async function vSettings(args = {}) {+  const s = loadSettings();+  let changed = false;+  if (args.sharedFolder) { s.sharedFolder = toHostPath(args.sharedFolder); changed = true; }+  if (Array.isArray(args.allowPaths)) { s.allowPaths = args.allowPaths.map(toHostPath); changed = true; }+  if (args.inlineImages !== undefined) { s.inlineImages = !!args.inlineImages; changed = true; }+  if (changed) { saveSettings(s); mkdirp(s.sharedFolder); }+  return ok({ settings: { ...s, sharedFolderWsl: toWslPath(s.sharedFolder) }, changed, _hint: changed ? 'Saved. A running headless session restarts with the new folders on its next call.' : 'Pass sharedFolder, allowPaths[] or inlineImages to change them.' });+}++function vProgress() {+  return ok({ active: [...active.values()].map((j) => j.block), _hint: active.size ? 'Poll again in a second.' : 'Nothing is running.' });+}++function vUninstall() {+  const removed = [], failed = [];+  for (const s of Object.values(sessions)) if (s) s.stop();+  for (const p of [SHOT_DIR, STATE_DIR]) {+    try { if (fs.existsSync(p)) { fs.rmSync(p, { recursive: true, force: true }); removed.push(p); } } catch (e) { failed.push({ path: p, error: e.message }); }+  }+  return ok({ removed, failed, kept: ['SolidCraft itself', 'the shared project folder and your designs'], _hint: 'The bridge removed only its own files. SolidCraft and your designs are untouched.' });+}++const OWN_VERBS = {+  status:   { fn: vStatus,   risk: 'read',  sum: 'Is SolidCraft installed and running; which sessions are up.' },+  describe: { fn: vDescribe, risk: 'read',  sum: 'This catalog, plus SolidCraft\'s live tool list when connected.' },+  readiness:{ fn: vStatus,   risk: 'read',  sum: 'Same as status.' },+  start:    { fn: vStart,    risk: 'process', sum: 'Launch SolidCraft minimised and wait until it accepts agents.', args: '{foreground?, foregroundReason?, waitSec?}' },+  state:    { fn: vState,    risk: 'read',  sum: 'The open design (summary: parameters, timeline, body names) plus a picture of it.', args: '{mode?, screenshot?, inline?, full?}' },+  tools:    { fn: vTools,    risk: 'read',  sum: 'List SolidCraft\'s MCP tools, or one tool\'s schema.', args: '{mode?, name?}' },+  call:     { fn: vCall,     risk: 'write', sum: 'Call any SolidCraft MCP tool by name.', args: '{tool, arguments?, mode?, allowPaths?, inline?, timeoutSec?}' },+  run:      { fn: vRun,      risk: 'write', sum: 'Headless rebuild of a .sc design with parameter overrides, then export/save.', args: '{in, params?, out?, save?, timeoutSec?}' },+  settings: { fn: vSettings, risk: 'config', sum: 'Shared project folder, extra allowed folders, inline images.', args: '{sharedFolder?, allowPaths?, inlineImages?}' },+  progress: { fn: vProgress, risk: 'read',  sum: 'Live progress of slow verbs (start, run).' },+  uninstall:{ fn: vUninstall,risk: 'write', sum: 'Remove everything this bridge created. Never touches SolidCraft or designs.' },+};++async function vDescribe() {+  const verbs = {};+  for (const [k, v] of Object.entries(OWN_VERBS)) verbs[`solidcraft_${k}`] = { summary: v.sum, risk: v.risk, args: v.args || '{}' };+  for (const [k, v] of Object.entries(TOOL_VERBS)) verbs[`solidcraft_${k}`] = { summary: v.sum, risk: v.risk, mcpTool: v.tool, args: `SolidCraft's ${v.tool} schema (solidcraft_tools {"name":"${v.tool}"}) plus {mode?, inline?, timeoutSec?}` };+  const live = sessions.live && sessions.live.tools;+  return ok({+    bridge: BRIDGE, version: VERSION, keyword: 'solidcraft', verbs,+    liveTools: live ? live.map((t) => t.name) : undefined,+    timings: timingSummary(),+    pitfalls: [+      'mode defaults to "live" (the open SolidCraft window). Pass mode:"headless" to work without a window.',+      'SolidCraft only reads and writes inside allowed folders. Keep files in the shared folder (solidcraft_settings).',+      'WSL paths under /mnt/<drive>/ are converted to Windows paths; other Linux paths are refused.',+      'SolidCraft\'s access token changes on every launch; the bridge reconnects by itself.',+      'Live mode never replaces the user\'s open design: new_design and open use a new tab unless replaceActive:true, which is refused while the design has unsaved changes.',+      'Live window screenshots are large (about 1 MB); images come back as file paths unless inline:true.',+    ],+    _hint: 'Start with solidcraft_status, then solidcraft_state. For modelling guidance read SolidCraft\'s own skills with solidcraft_skill.',+  });+}++// Fields ab (or the CLI) adds to every call. SolidCraft refuses unknown arguments, so they must+// never reach a tool: anything starting with "_" plus ab's caller-identity fields.+const AB_FIELDS = new Set(['aiThread', 'containerName', 'caller', 'reason', 'target']);+function stripAbFields(args) {+  if (!args || typeof args !== 'object' || Array.isArray(args)) return {};+  const out = {};+  for (const [k, v] of Object.entries(args)) if (!k.startsWith('_') && !AB_FIELDS.has(k)) out[k] = v;+  return out;+}++async function dispatch(verb, rawArgs) {+  const args = stripAbFields(rawArgs);+  const bare = String(verb).replace(/^solidcraft_/, '');+  if (OWN_VERBS[bare]) return OWN_VERBS[bare].fn(args || {});+  if (TOOL_VERBS[bare]) { const t = TOOL_VERBS[bare]; return callNamedTool(t.tool, args || {}, { next: t.next, timeoutSec: t.timeoutSec }); }+  return fail('unknown_verb', `No verb ${verb}`, { _hint: 'Call solidcraft_describe for the full list.' });+}++// ---------------------------------------------------------------------------------------------+// HTTP server for ab+// ---------------------------------------------------------------------------------------------++const httpSrv = http.createServer((req, res) => {+  const reply = (code, obj) => {+    const body = Buffer.from(JSON.stringify(obj));+    res.writeHead(code, { 'content-type': 'application/json', 'content-length': body.length });+    res.end(body);+  };+  if (req.method === 'GET' && (req.url === '/health' || req.url === '/status')) {+    return reply(200, { ok: true, bridge: BRIDGE, version: VERSION, installed: !!cliCommand(), liveConnected: !!(sessions.live && sessions.live.alive), activeJobs: active.size });+  }+  if (req.method === 'POST' && req.url === '/command') {+    let body = '';+    req.on('data', (c) => { body += c; if (body.length > 8 * 1024 * 1024) req.destroy(); });+    req.on('end', async () => {+      let parsed;+      try { parsed = JSON.parse(body || '{}'); } catch { return reply(400, { success: false, error: 'bad json' }); }+      const verb = parsed.command || parsed.verb;+      if (!verb) return reply(400, { success: false, error: 'missing command/verb' });+      const thread = String(req.headers['x-adom-caller-thread'] || '').slice(0, 120);+      log(`${verb}${thread ? ' from ' + thread : ''}`);+      let out;+      try { out = await dispatch(verb, parsed.args); } catch (e) { out = fail('internal_error', e.message, { _hint: 'This is a bridge bug; file it on the solidcraft-bridge wiki page.' }); }+      reply(200, out);+    });+    return;+  }+  reply(404, { success: false, error: 'not found' });+});++function argPort() {+  const i = process.argv.indexOf('--port');+  if (i >= 0) { const p = parseInt(process.argv[i + 1], 10); if (!Number.isNaN(p)) return p; }+  return 0;+}++let fellBack = false;+function listen(p) {+  httpSrv.once('error', (e) => {+    if (e && e.code === 'EADDRINUSE' && !fellBack) { fellBack = true; log(`port ${p} in use, using an ephemeral port`); setTimeout(() => listen(0), 50); }+    else { log(`listen error: ${e && e.code}`); process.exit(1); }+  });+  httpSrv.listen(p, BIND, () => log(`bridge ${VERSION} up on ${BIND}:${httpSrv.address().port}`));+}++function shutdown() { for (const s of Object.values(sessions)) if (s) s.stop(); setTimeout(() => process.exit(0), 200); }+process.on('SIGINT', shutdown);+process.on('SIGTERM', shutdown);++if (require.main === module) listen(argPort());+module.exports = { toHostPath, toWslPath, convertPaths, shapeToolResult, dispatch, httpSrv };
screenshots/showcase.pngadded
⋯ 1 unchanged line ⋯
scripts/build-release.shadded+27
@@ -0,0 +1,27 @@+#!/usr/bin/env bash+# Build the runtime zip and its update manifest into dist/. Run the tests first.+set -euo pipefail+cd "$(dirname "$0")/.."+VER=$(node -p 'require("./bridge/bridge.json").version')+[ "$VER" = "$(node -p 'require("./bridge/package.json").version')" ] || { echo "ERROR: bridge.json and bridge/package.json versions differ"; exit 1; }+OWNER=martypm SLUG=solidcraft-bridge+ZIP="solidcraft-bridge-v$VER.zip"+rm -rf dist && mkdir dist+(cd bridge && zip -qX "../dist/$ZIP" server.js bridge.json package.json LICENSE)+SHA=$(sha256sum "dist/$ZIP" | cut -d' ' -f1); SIZE=$(stat -c %s "dist/$ZIP")+cat > dist/adom-bridge-solidcraft-manifest.json <<JSON+{+  "manifest_version": 1,+  "name": "solidcraft",+  "version": "$VER",+  "url": "https://wiki.adom.inc/download/$OWNER/$SLUG/$VER/$ZIP",+  "sha256": "$SHA",+  "size": $SIZE,+  "verbPrefixes": ["solidcraft_"],+  "healthEndpoint": "/health",+  "updateManifestUrl": "https://wiki.adom.inc/api/v1/pages/$OWNER/$SLUG/files/adom-bridge-solidcraft-manifest.json",+  "released_at": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"+}+JSON+echo "OK: dist/$ZIP ($SIZE bytes, sha256 $SHA)"+unzip -l "dist/$ZIP"
scripts/dev-deploy.shadded+18
@@ -0,0 +1,18 @@+#!/usr/bin/env bash+# Install the working copy on this PC as a dev build. Needs `python3 -m http.server 47391 --bind+# 127.0.0.1` running in dist/dev (WSL mirrored networking lets Windows reach it).+set -euo pipefail+cd "$(dirname "$0")/.."+A='"aiThread":"solidcraft-bridge-build","containerName":"hydrogen-local"'+scripts/build-release.sh | grep "^OK:"+mkdir -p dist/dev && cp dist/solidcraft-bridge-v*.zip dist/dev/+python3 - <<'PY'+import json,glob,os+m=json.load(open('dist/adom-bridge-solidcraft-manifest.json'))+m['url']='http://127.0.0.1:47391/'+os.path.basename(m['url'])+json.dump(m,open('dist/dev/manifest.json','w'),indent=2)+PY+adom-bridge bridge_dev_mode "{\"name\":\"solidcraft\",\"on\":false,$A}" >/dev/null+adom-bridge bridge_install "{\"manifestUrl\":\"http://127.0.0.1:47391/manifest.json\",\"force\":true,$A}" | grep -E '"(success|version)"'+adom-bridge bridge_dev_mode "{\"name\":\"solidcraft\",\"on\":true,$A}" >/dev/null+echo "OK: dev build installed and pinned"
test/mock-app.jsadded+9
@@ -0,0 +1,9 @@+#!/usr/bin/env node+'use strict';+// A stand-in for the SolidCraft app: after a short delay it opens the control port, like the+// real app with "Let AI agents connect" ticked. MOCK_APP_NO_AGENTS=1 never opens it.+const net = require('net');+const port = parseInt(process.env.SOLIDCRAFT_CONTROL_PORT, 10);+if (process.env.MOCK_APP_NO_AGENTS === '1') setTimeout(() => process.exit(0), 20000);+else setTimeout(() => net.createServer((s) => s.end()).listen(port, '127.0.0.1'), 1500);+setTimeout(() => process.exit(0), 60000);
test/mock-cli.jsadded+86
@@ -0,0 +1,86 @@+#!/usr/bin/env node+'use strict';+// A stand-in for solidcraft-cli, used only by the tests. It speaks the same newline-delimited+// MCP over stdio for `mcp --headless` / `mcp --connect`, and fakes `run`.+const net = require('net');+const fs = require('fs');+const argv = process.argv.slice(2);++const PNG = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';+const params = { wall: '2 mm', slots: '7' };+let dirty = false;+const log = [];+// Like SolidCraft 0.49: tools/list gives 8 core tools unless --all-tools; every tool answers by name.+const CORE = ['find_commands', 'call_command', 'batch', 'inspect_design', 'measure', 'body_topology', 'pending', 'skill_reference'];+const EXTRA = ['execute', 'set_parameter', 'undo', 'redo', 'new_design', 'check_parameters', 'screenshot', 'compare_picture',+  'open', 'save', 'export', 'list_commands', 'describe_command', 'running'];+const ALL = [...CORE, ...EXTRA];++if (argv[0] === 'run') {+  const get = (f) => { const i = argv.indexOf(f); return i >= 0 ? argv[i + 1] : null; };+  const ps = argv.flatMap((a, i) => (a === '--param' ? [argv[i + 1]] : []));+  if (ps.some((p) => p.startsWith('missing='))) { process.stderr.write('error: no parameter named "missing"\n'); process.exit(2); }+  if (get('--out')) fs.writeFileSync(get('--out'), `STEP from ${get('--in')} ${ps.join(' ')}`);+  process.stdout.write(`rebuilt ${get('--in')} with ${ps.join(', ')}\n`);+  process.exit(0);+}++if (argv[0] !== 'mcp') { process.stderr.write('usage: mock-cli mcp|run\n'); process.exit(64); }++const mode = argv.includes('--headless') ? 'headless' : 'live';+const allTools = argv.includes('--all-tools');+const structured = argv.includes('--structured');+const TOOLS = (allTools ? ALL : CORE).map((name) => ({ name, description: `mock ${name}`, inputSchema: { type: 'object' } }));+const allow = argv.flatMap((a, i) => (a === '--allow-path' ? [argv[i + 1]] : []));++function serve() {+  let buf = '';+  let pinged = false;+  const send = (o) => process.stdout.write(JSON.stringify(o) + '\n');+  process.stdin.setEncoding('utf8');+  process.stdin.on('data', (d) => {+    buf += d;+    let i;+    while ((i = buf.indexOf('\n')) >= 0) {+      const line = buf.slice(0, i).trim(); buf = buf.slice(i + 1);+      if (!line) continue;+      const m = JSON.parse(line);+      if (m.id === 'srv-ping') continue; // the client's answer to our ping+      if (m.method === 'initialize') send({ jsonrpc: '2.0', id: m.id, result: { protocolVersion: '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'solidcraft-mock', version: '0.49.1', mode, allow } } });+      else if (m.method === 'notifications/initialized') { if (!pinged) { pinged = true; send({ jsonrpc: '2.0', id: 'srv-ping', method: 'ping' }); } }+      else if (m.method === 'tools/list') send({ jsonrpc: '2.0', id: m.id, result: { tools: TOOLS } });+      else if (m.method === 'tools/call') {+        if (!ALL.includes(m.params.name)) send({ jsonrpc: '2.0', id: m.id, error: { code: -32602, message: `unknown tool: ${m.params.name}` } });+        else send({ jsonrpc: '2.0', id: m.id, result: call(m.params.name, m.params.arguments || {}) });+      }+      else if (m.id !== undefined) send({ jsonrpc: '2.0', id: m.id, error: { code: -32601, message: 'no such method' } });+    }+  });+  process.stdin.on('end', () => process.exit(0));+}++function call(name, a) {+  log.push({ name, a });+  const text = (t) => ({ content: [{ type: 'text', text: typeof t === 'string' ? t : JSON.stringify(t) }], ...(structured ? { structuredContent: { result: t, notes: ['mock note'] } } : {}) });+  switch (name) {+    case 'inspect_design': return text({ name: 'MockPart', dirty, bodies: 1, features: ['sketch', 'extrude'], parameters: params, mode });+    case 'running': return text(log);+    case 'screenshot': return { content: [{ type: 'image', data: PNG, mimeType: 'image/png' }] };+    case 'set_parameter':+      if (!(a.name in params)) return { isError: true, content: [{ type: 'text', text: `no parameter named ${a.name}` }] };+      params[a.name] = a.value; dirty = true; return text({ ok: true, parameters: params });+    case 'find_commands': return text([{ id: 'solid.box', label: 'Box', input: '{width, depth, height}' }]);+    case 'call_command': return text({ feature: 'Box1', bodies_created: ['Body1'], id: a.id, params: a.params });+    case 'save': dirty = false; return text({ ok: true, echo: a });+    case 'open': case 'export': return text({ ok: true, echo: a });+    case 'slow': return new Promise(() => {});+    default: return text({ ok: true, tool: name, echo: a });+  }+}++if (mode === 'live') {+  const [host, port] = (argv[argv.indexOf('--connect') + 1] || '').split(':');+  const s = net.connect({ host, port: +port });+  s.once('connect', () => { s.destroy(); serve(); });+  s.once('error', () => { process.stderr.write(`error: could not connect to SolidCraft at ${host}:${port}\n`); process.exit(3); });+} else serve();
test/run-tests.jsadded+249
@@ -0,0 +1,249 @@+#!/usr/bin/env node+'use strict';+// End-to-end tests: start the real bridge server against the stand-in SolidCraft and drive it over+// HTTP exactly as Adom Bridge does. Run: node test/run-tests.js+const { spawn } = require('child_process');+const http = require('http');+const net = require('net');+const fs = require('fs');+const os = require('os');+const path = require('path');+const assert = require('assert');++const ROOT = path.join(__dirname, '..');+const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'solidcraft-bridge-test-'));++function freePort() {+  return new Promise((r) => { const s = net.createServer().listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); }); });+}++function startBridge(env) {+  return new Promise((resolve, reject) => {+    const p = spawn(process.execPath, [path.join(ROOT, 'bridge', 'server.js'), '--port', '0'], { env: { ...process.env, ...env }, stdio: ['ignore', 'pipe', 'pipe'] });+    let out = '';+    p.stdout.on('data', (d) => { out += d; const m = /up on 127\.0\.0\.1:(\d+)/.exec(out); if (m) resolve({ proc: p, port: +m[1] }); });+    p.stderr.on('data', (d) => process.stderr.write(d));+    p.on('exit', (c) => reject(new Error('bridge exited ' + c + '\n' + out)));+  });+}++function post(port, command, args) {+  return new Promise((resolve, reject) => {+    const body = JSON.stringify({ command, args });+    const req = http.request({ host: '127.0.0.1', port, path: '/command', method: 'POST', headers: { 'content-type': 'application/json', 'x-adom-caller-thread': 'tests' } }, (res) => {+      let d = ''; res.on('data', (c) => (d += c)); res.on('end', () => resolve(JSON.parse(d)));+    });+    req.on('error', reject); req.end(body);+  });+}+function get(port, p) {+  return new Promise((resolve, reject) => http.get({ host: '127.0.0.1', port, path: p }, (res) => { let d = ''; res.on('data', (c) => (d += c)); res.on('end', () => resolve(JSON.parse(d))); }).on('error', reject));+}++const results = [];+async function t(name, fn) {+  try { await fn(); results.push(['PASS', name]); } catch (e) { results.push(['FAIL', name, e.message]); }+}++(async () => {+  // Pure path mapping, as it behaves on Windows.+  process.env.SOLIDCRAFT_BRIDGE_WIN_PATHS = '1';+  delete require.cache[require.resolve('../bridge/server.js')];+  const lib = require('../bridge/server.js');+  await t('maps /mnt/c paths to Windows paths', () => {+    assert.strictEqual(lib.toHostPath('/mnt/c/Users/User/cad-projects/a.sc'), 'C:\\Users\\User\\cad-projects\\a.sc');+    assert.strictEqual(lib.toWslPath('C:\\Users\\User\\x.step'), '/mnt/c/Users/User/x.step');+  });+  await t('flags WSL-only paths nested in arguments', () => {+    const r = lib.convertPaths({ file: '/home/adom/a.step', opts: { out: '/mnt/d/out.stl' } });+    assert.deepStrictEqual(r.foreign, ['/home/adom/a.step']);+    assert.strictEqual(r.value.opts.out, 'D:\\out.stl');+  });+  delete process.env.SOLIDCRAFT_BRIDGE_WIN_PATHS;++  const ctrl = await freePort();+  const env = {+    SOLIDCRAFT_CLI_CMD: JSON.stringify([process.execPath, path.join(__dirname, 'mock-cli.js')]),+    SOLIDCRAFT_APP: path.join(__dirname, 'mock-app.js'),+    SOLIDCRAFT_CONTROL_PORT: String(ctrl),+    SOLIDCRAFT_BRIDGE_STATE: path.join(TMP, 'state'),+    SOLIDCRAFT_BRIDGE_SHOTS: path.join(TMP, 'shots'),+    HOME: TMP,+  };+  const { proc, port } = await startBridge(env);++  try {+    await t('health endpoint answers', async () => {+      const h = await get(port, '/health');+      assert.strictEqual(h.ok, true); assert.strictEqual(h.bridge, 'solidcraft'); assert.strictEqual(h.installed, true);+    });+    await t('status says the app is not running and suggests start', async () => {+      const r = await post(port, 'solidcraft_status');+      assert.strictEqual(r.success, true); assert.strictEqual(r.appRunning, false);+      assert.deepStrictEqual(r._next, ['solidcraft_start']);+    });+    await t('a live verb with the app closed returns app_not_running with a hint', async () => {+      const r = await post(port, 'solidcraft_inspect');+      assert.strictEqual(r.errorCode, 'app_not_running'); assert.match(r._hint, /solidcraft_start/);+    });+    await t('unknown verb is refused with a hint', async () => {+      const r = await post(port, 'solidcraft_nope');+      assert.strictEqual(r.errorCode, 'unknown_verb'); assert.ok(r._hint);+    });+    await t('foreground start without a reason is refused', async () => {+      const r = await post(port, 'solidcraft_start', { foreground: true });+      assert.strictEqual(r.errorCode, 'foreground_reason_required');+    });+    await t('start launches the app minimised and waits for the control port', async () => {+      const r = await post(port, 'solidcraft_start', {});+      assert.strictEqual(r.success, true, JSON.stringify(r)); assert.strictEqual(r.windowEtiquette, 'background');+      assert.strictEqual(r.progress.percent, 100); assert.strictEqual(r.progress.startKind, 'cold');+    });+    await t('start again reports warm reuse', async () => {+      const r = await post(port, 'solidcraft_start', {});+      assert.strictEqual(r.alreadyRunning, true); assert.strictEqual(r.startKind, 'warm');+    });+    await t('tools lists SolidCraft tools from the live session', async () => {+      const r = await post(port, 'solidcraft_tools');+      assert.strictEqual(r.success, true, JSON.stringify(r)); assert.strictEqual(r.mode, 'live'); assert.strictEqual(r.count, 22);+    });+    await t('tools {name} returns one schema', async () => {+      const r = await post(port, 'solidcraft_tools', { name: 'export' });+      assert.strictEqual(r.tool.name, 'export');+    });+    await t('inspect returns parsed design data', async () => {+      const r = await post(port, 'solidcraft_inspect');+      assert.strictEqual(r.success, true); assert.strictEqual(r.data.bodies, 1); assert.strictEqual(r.data.mode, 'live');+    });+    await t('set_parameter changes a parameter', async () => {+      const r = await post(port, 'solidcraft_set_parameter', { name: 'wall', value: '2.4 mm' });+      assert.strictEqual(r.success, true); assert.strictEqual(r.data.parameters.wall, '2.4 mm');+    });+    await t('a tool error comes back as tool_error with a schema hint', async () => {+      const r = await post(port, 'solidcraft_set_parameter', { name: 'missing', value: 1 });+      assert.strictEqual(r.errorCode, 'tool_error'); assert.match(r._hint, /solidcraft_tools/);+    });+    await t('state returns the design and a saved screenshot', async () => {+      const r = await post(port, 'solidcraft_state', { inline: true });+      assert.strictEqual(r.success, true); assert.strictEqual(r.design.bodies, 1);+      assert.strictEqual(r.shots.length, 1); assert.ok(fs.existsSync(r.shots[0].path)); assert.ok(r.shots[0].image);+      assert.ok(Array.isArray(r.focusEvents) && r.focusEvents.length >= 1);+    });+    await t('inline:false leaves the image out of the response', async () => {+      const r = await post(port, 'solidcraft_screenshot', { inline: false });+      assert.strictEqual(r.images[0].image, undefined); assert.ok(r.images[0].path);+    });+    await t('call reaches any tool by name', async () => {+      const r = await post(port, 'solidcraft_call', { tool: 'list_commands', arguments: { filter: 'sketch' } });+      assert.strictEqual(r.success, true); assert.strictEqual(r.data.echo.filter, 'sketch');+    });+    await t('live new_design opens a new tab by default', async () => {+      const r = await post(port, 'solidcraft_new_design', { name: 'A' });+      assert.strictEqual(r.success, true); assert.deepStrictEqual(r.data.echo, { new_tab: true, name: 'A' });+    });+    await t('live open goes to a new tab first, never over the active design', async () => {+      await post(port, 'solidcraft_open', { path: '/mnt/c/x/board.kicad_pcb' });+      const log = (await post(port, 'solidcraft_call', { tool: 'running' })).data;+      const i = log.findIndex((c) => c.name === 'open');+      assert.ok(i > 0); assert.deepStrictEqual(log[i - 1], { name: 'new_design', a: { new_tab: true, name: 'board' } });+    });+    await t('replacing a design with unsaved changes is refused', async () => {+      await post(port, 'solidcraft_set_parameter', { name: 'wall', value: '3 mm' });+      const r = await post(port, 'solidcraft_open', { path: '/mnt/c/x/a.sc', replaceActive: true });+      assert.strictEqual(r.errorCode, 'unsaved_changes'); assert.match(r.error, /MockPart/);+      const r2 = await post(port, 'solidcraft_new_design', { replaceActive: true });+      assert.strictEqual(r2.errorCode, 'unsaved_changes');+    });+    await t('replaceActive works once the design is saved', async () => {+      await post(port, 'solidcraft_save', {});+      const r = await post(port, 'solidcraft_new_design', { replaceActive: true, name: 'B' });+      assert.strictEqual(r.success, true); assert.deepStrictEqual(r.data.echo, { name: 'B' });+    });+    await t('a live batch that would replace the design is refused', async () => {+      const r = await post(port, 'solidcraft_batch', { commands: [{ command: 'open', params: { path: 'a.sc' } }, { command: 'solid.box' }] });+      assert.strictEqual(r.errorCode, 'would_replace_design');+      const ok2 = await post(port, 'solidcraft_batch', { commands: [{ command: 'new_design', params: { new_tab: true } }, { command: 'solid.box' }] });+      assert.strictEqual(ok2.success, true);+    });+    await t('headless new_design is passed through unchanged', async () => {+      const r = await post(port, 'solidcraft_new_design', { mode: 'headless', name: 'H' });+      assert.deepStrictEqual(r.data.echo, { name: 'H' });+    });+    await t('ab fields never reach SolidCraft', async () => {+      const r = await post(port, 'solidcraft_call', { tool: 'list_commands', arguments: { q: 1 }, _callerBudgetMs: 60000, aiThread: 't', containerName: 'c' });+      assert.strictEqual(r.success, true); assert.deepStrictEqual(r.data.echo, { q: 1 });+      const r2 = await post(port, 'solidcraft_commands', { q: 2, _callerBudgetMs: 1, aiThread: 't' });+      assert.deepStrictEqual(r2.data.echo, { q: 2 });+    });+    await t('structured replies are unwrapped into data and notes', async () => {+      const r = await post(port, 'solidcraft_inspect');+      assert.deepStrictEqual(r.notes, ['mock note']); assert.strictEqual(r.text, undefined);+    });+    await t('find and command run SolidCraft commands by id', async () => {+      const f = await post(port, 'solidcraft_find', { query: 'box' });+      assert.strictEqual(f.data[0].id, 'solid.box');+      const c = await post(port, 'solidcraft_command', { id: 'solid.box', params: { width: 10, depth: 10, height: 5 } });+      assert.strictEqual(c.success, true); assert.strictEqual(c.data.params.height, 5);+    });+    await t('call to a tool SolidCraft lacks lists the real ones', async () => {+      const r = await post(port, 'solidcraft_call', { tool: 'teleport' });+      assert.strictEqual(r.errorCode, 'tool_unavailable'); assert.ok(r.availableTools.includes('execute'));+    });+    await t('headless mode uses a separate session with allowed folders', async () => {+      const r = await post(port, 'solidcraft_inspect', { mode: 'headless', allowPaths: [path.join(TMP, 'extra')] });+      assert.strictEqual(r.success, true, JSON.stringify(r)); assert.strictEqual(r.data.mode, 'headless');+      const s = await post(port, 'solidcraft_status');+      assert.strictEqual(s.sessions.headless.connected, true); assert.strictEqual(s.sessions.live.connected, true);+    });+    await t('run rebuilds with parameters and writes the output', async () => {+      const out = path.join(TMP, 'part.step');+      const r = await post(port, 'solidcraft_run', { in: path.join(TMP, 'part.sc'), params: { slots: 9 }, out });+      assert.strictEqual(r.success, true, JSON.stringify(r)); assert.ok(fs.readFileSync(out, 'utf8').includes('slots=9'));+      assert.strictEqual(r.progress.percent, 100);+    });+    await t('run failure returns stderr and a hint', async () => {+      const r = await post(port, 'solidcraft_run', { in: path.join(TMP, 'part.sc'), params: { missing: 1 } });+      assert.strictEqual(r.errorCode, 'run_failed'); assert.match(r.stderr, /no parameter/);+    });+    await t('settings saves the shared folder', async () => {+      const r = await post(port, 'solidcraft_settings', { sharedFolder: path.join(TMP, 'shared') });+      assert.strictEqual(r.changed, true); assert.ok(fs.existsSync(path.join(TMP, 'shared')));+    });+    await t('describe lists every declared verb', async () => {+      const r = await post(port, 'solidcraft_describe');+      const declared = require('../bridge/bridge.json').verbs.sort();+      assert.deepStrictEqual(Object.keys(r.verbs).sort(), declared);+      assert.ok(r.timings['start:cold']);+    });+    await t('progress is idle when nothing runs', async () => {+      const r = await post(port, 'solidcraft_progress');+      assert.deepStrictEqual(r.active, []);+    });+    await t('uninstall removes only the bridge state and is idempotent', async () => {+      const r1 = await post(port, 'solidcraft_uninstall');+      assert.strictEqual(r1.success, true); assert.ok(!fs.existsSync(path.join(TMP, 'state')));+      assert.ok(fs.existsSync(path.join(TMP, 'shared')));+      const r2 = await post(port, 'solidcraft_uninstall');+      assert.strictEqual(r2.success, true); assert.deepStrictEqual(r2.removed, []);+    });+  } finally {+    proc.kill();+  }++  // A second bridge where the app launches but agent access stays off.+  const ctrl2 = await freePort();+  const b2 = await startBridge({ ...env, SOLIDCRAFT_CONTROL_PORT: String(ctrl2), MOCK_APP_NO_AGENTS: '1', SOLIDCRAFT_BRIDGE_STATE: path.join(TMP, 'state2') });+  try {+    await t('start with agents off reports blocked_on_user, not a timeout', async () => {+      const r = await post(b2.port, 'solidcraft_start', { waitSec: 5 });+      assert.strictEqual(r.errorCode, 'blocked_on_user'); assert.match(r.blockedBy, /Let AI agents connect/);+      assert.strictEqual(r.stillRunning, true);+    });+  } finally { b2.proc.kill(); }++  for (const r of results) console.log(r.join('  '));+  const failed = results.filter((r) => r[0] === 'FAIL').length;+  console.log(`\n${results.length - failed}/${results.length} passed`);+  fs.rmSync(TMP, { recursive: true, force: true });+  process.exit(failed ? 1 : 0);+})().catch((e) => { console.error(e); process.exit(1); });