main
MartyPM Bridge runtime manifest, source, tests and showcase for 0.1.0 d2ae474
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
#!/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 };