@maslowcnc/abundance-bridge 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +185 -19
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -523,6 +523,7 @@ var SERVER_INSTRUCTIONS = `Tools for inspecting and editing the Abundance CAD pr
523
523
  Connect:
524
524
  - Call bridge_status first. If no tab is connected, show the user its pairing_instructions and wait for them to pair.
525
525
  - If several tabs are connected, list_sessions and use_session to pick one.
526
+ - Each Claude chat runs its own bridge and only one holds the connection. If bridge_status says another chat holds it, call take_over_bridge when the user wants to work on Abundance in this chat (ask if that's unclear). The page reconnects here within a few seconds, and the other chat loses access until it takes the bridge back.
526
527
 
527
528
  Understand before changing:
528
529
  - get_project for owner/repo, units, progress, errors, and whether edits are allowed.
@@ -546,6 +547,11 @@ Organize the project as a hierarchy of molecules. This matters as much as gettin
546
547
  - To build a molecule, in one apply_edits: add_atom type Molecule with a name and a ref such as "leg"; add atoms into it with molecule "leg" (each Input atom inside becomes an input of the molecule, named after the Input); connect the finished shape to "leg/Output", input "number or geometry" (add_atom also returns the Output atom's ID); then wire the molecule onward in the parent and set its inputs.
547
548
  - When you finish, tell the user which molecules you made and what each one builds.
548
549
 
550
+ Fit parts together with Assembly instead of modeling the joints:
551
+ - Assembly makes its parts disjoint: where parts overlap, a part higher in its inputs list cuts into the parts below it. So don't model slots, holes, notches, or pockets for parts that fit together. Build each part whole, position the parts overlapping as they sit in the finished design, and assemble them. Put the part that should stay whole above the part it cuts into; the input order decides which part gets cut.
552
+ - For clearance around a joint, add keepout geometry: a slightly larger shape around the cutting part, colored "Keep Out" with a Color atom, placed above the part it should cut in the Assembly. Keepout geometry cuts like any part but is left out of fusions, cut layouts, and gcode, and Extract Tag's "Not Keep Out" option removes it.
553
+ - Tag parts before they go into an Assembly when you may need them separately later (to lay out, export, or reuse); Extract Tag pulls tagged parts back out of the assembly.
554
+
549
555
  Edit:
550
556
  - Edit tools only work after the user ticks "Allow edits" in the AI agent chip at the top of the Abundance window. If edits are refused, ask them to, and don't retry until they have.
551
557
  - set_param uses the labels from get_atom's params. Number fields accept numbers or equations that reference inputs.
@@ -570,6 +576,12 @@ var BRIDGE_TOOLS = [
570
576
  inputSchema: { type: "object", properties: {} },
571
577
  annotations: { readOnlyHint: true }
572
578
  },
579
+ {
580
+ name: "take_over_bridge",
581
+ description: "Move the Abundance connection to this chat from another Claude chat (or other AI app) whose bridge holds it. Connected tabs reconnect here within a few seconds; the other chat's Abundance tools stop working until it takes the bridge back.",
582
+ inputSchema: { type: "object", properties: {} },
583
+ annotations: { readOnlyHint: false, destructiveHint: false }
584
+ },
573
585
  {
574
586
  name: "list_sessions",
575
587
  description: "List the Abundance browser tabs connected to the bridge and which one tools use by default.",
@@ -617,7 +629,7 @@ function annotationsFor(tool) {
617
629
  }
618
630
  return { readOnlyHint: true };
619
631
  }
620
- function createMcpServer(hub, { outDir, tokenInfo, version, getListenError }) {
632
+ function createMcpServer(hub, { outDir, tokenInfo, version }) {
621
633
  const server = new Server(
622
634
  { name: "abundance-bridge", version },
623
635
  { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS }
@@ -648,6 +660,11 @@ function createMcpServer(hub, { outDir, tokenInfo, version, getListenError }) {
648
660
  });
649
661
  async function callTool(name, args, request, extra) {
650
662
  if (name === "bridge_status") return textResult(status());
663
+ if (name === "take_over_bridge") {
664
+ await hub.claim();
665
+ await waitForSession(hub, 5e3);
666
+ return textResult(status());
667
+ }
651
668
  if (name === "get_code_atom_guide") {
652
669
  return { content: [{ type: "text", text: await codeAtomGuide() }] };
653
670
  }
@@ -664,13 +681,8 @@ function createMcpServer(hub, { outDir, tokenInfo, version, getListenError }) {
664
681
  if (!tool) {
665
682
  throw new ToolError(ERROR_CODES.METHOD_NOT_FOUND, `Unknown tool ${name}`);
666
683
  }
667
- const listenError = getListenError?.();
668
- if (listenError) {
669
- throw new ToolError(
670
- ERROR_CODES.NO_PROJECT,
671
- `The bridge could not listen on port ${hub.port}: ${listenError.message}. Another bridge may already be running.`
672
- );
673
- }
684
+ const notListening = notListeningMessage();
685
+ if (notListening) throw new ToolError(ERROR_CODES.NO_PROJECT, notListening);
674
686
  const sessionId = args.session_id;
675
687
  delete args.session_id;
676
688
  const outputPath = args.output_path;
@@ -700,10 +712,24 @@ function createMcpServer(hub, { outDir, tokenInfo, version, getListenError }) {
700
712
  if (tool.output === "file") return fileResult(result, outputPath);
701
713
  return textResult(result);
702
714
  }
715
+ function notListeningMessage() {
716
+ if (hub.wss) return null;
717
+ if (hub.handedOff) {
718
+ return "Another Claude chat took over the Abundance bridge. If the user wants to work on Abundance in this chat again, call take_over_bridge.";
719
+ }
720
+ if (hub.listenError?.code === "EADDRINUSE") {
721
+ return `Another Claude chat (or another AI app) holds the Abundance bridge on port ${hub.port}. If the user wants to work on Abundance in this chat, call take_over_bridge.`;
722
+ }
723
+ if (hub.listenError) {
724
+ return `The bridge could not listen on port ${hub.port}: ${hub.listenError.message}.`;
725
+ }
726
+ return "The bridge is not listening yet.";
727
+ }
703
728
  function status() {
704
729
  const sessions = hub.listSessions();
705
- const listenError = getListenError?.();
706
- const pairing = sessions.length > 0 ? null : [
730
+ const listenError = hub.listenError;
731
+ const notListening = notListeningMessage();
732
+ const pairing = sessions.length > 0 || notListening ? null : [
707
733
  "No Abundance tab is connected. To pair:",
708
734
  "1. Open Abundance (https://abundance.maslowcnc.com or the local dev server) in Chrome or Firefox.",
709
735
  `2. Open "Connect an AI agent": the sparkle button on the right in run mode, "AI Agent" in the editor's menu, or add #agent to the end of the page address.`,
@@ -712,8 +738,9 @@ function createMcpServer(hub, { outDir, tokenInfo, version, getListenError }) {
712
738
  "5. To let the agent change the project, the user also turns on Allow edits in the AI agent chip."
713
739
  ].join("\n");
714
740
  return {
715
- listening: !listenError && !!hub.wss,
741
+ listening: !!hub.wss,
716
742
  port: hub.port,
743
+ not_listening: notListening,
717
744
  listen_error: listenError ? listenError.message : null,
718
745
  token_file: tokenInfo.file,
719
746
  output_dir: outDir,
@@ -734,6 +761,19 @@ function createMcpServer(hub, { outDir, tokenInfo, version, getListenError }) {
734
761
  }
735
762
  return { server, status };
736
763
  }
764
+ function waitForSession(hub, timeoutMs) {
765
+ if (hub.sessions.size > 0) return Promise.resolve();
766
+ return new Promise((resolve) => {
767
+ const done = () => {
768
+ clearTimeout(timer);
769
+ hub.off("session", done);
770
+ resolve();
771
+ };
772
+ const timer = setTimeout(done, timeoutMs);
773
+ timer.unref?.();
774
+ hub.on("session", done);
775
+ });
776
+ }
737
777
  async function precompileCode(name, args) {
738
778
  try {
739
779
  await precompileCodeUnchecked(name, args);
@@ -796,7 +836,7 @@ function errorResult(err) {
796
836
 
797
837
  // ../../bridge/pageHub.js
798
838
  import { EventEmitter } from "node:events";
799
- import { WebSocketServer } from "ws";
839
+ import WebSocket, { WebSocketServer } from "ws";
800
840
 
801
841
  // ../../bridge/token.js
802
842
  import crypto from "node:crypto";
@@ -843,6 +883,8 @@ function tokensMatch(expected, provided) {
843
883
 
844
884
  // ../../bridge/pageHub.js
845
885
  var HEARTBEAT_MS = 2e4;
886
+ var HANDOFF_PATH = "/handoff";
887
+ var HANDED_OFF = 4007;
846
888
  var PageHub = class extends EventEmitter {
847
889
  /**
848
890
  * @param {object} options
@@ -877,6 +919,7 @@ var PageHub = class extends EventEmitter {
877
919
  this._idsByClient = /* @__PURE__ */ new Map();
878
920
  this.wss = null;
879
921
  this.listenError = null;
922
+ this.handedOff = false;
880
923
  }
881
924
  /** Start listening. Resolves with the bound port. */
882
925
  start() {
@@ -887,6 +930,10 @@ var PageHub = class extends EventEmitter {
887
930
  maxPayload: 256 * 1024 * 1024,
888
931
  verifyClient: (info, done) => {
889
932
  const origin = info.origin || info.req.headers.origin;
933
+ if (info.req.url === HANDOFF_PATH && !origin) {
934
+ done(true);
935
+ return;
936
+ }
890
937
  if (!isAllowedOrigin(origin, this.extraOrigins)) {
891
938
  this.emit("rejected", { reason: "origin", origin });
892
939
  done(false, 403, "Origin not allowed");
@@ -905,6 +952,8 @@ var PageHub = class extends EventEmitter {
905
952
  wss.on("error", (err) => this.emit("error", err));
906
953
  this.wss = wss;
907
954
  this.port = wss.address().port;
955
+ this.listenError = null;
956
+ this.handedOff = false;
908
957
  this._heartbeat = setInterval(() => this._pingAll(), HEARTBEAT_MS);
909
958
  this._heartbeat.unref?.();
910
959
  resolve(this.port);
@@ -919,10 +968,54 @@ var PageHub = class extends EventEmitter {
919
968
  session.ws.terminate();
920
969
  }
921
970
  this.sessions.clear();
922
- if (this.wss) {
923
- await new Promise((resolve) => this.wss.close(() => resolve()));
924
- this.wss = null;
971
+ await this._closeServer();
972
+ }
973
+ /**
974
+ * Listen on the port, taking it from another bridge if one holds it.
975
+ * Resolves with the bound port.
976
+ */
977
+ async claim() {
978
+ if (this.wss) return this.port;
979
+ try {
980
+ return await this.start();
981
+ } catch (err) {
982
+ if (err.code !== "EADDRINUSE") throw err;
983
+ }
984
+ await requestHandoff({
985
+ host: this.host,
986
+ port: this.port,
987
+ token: this.token
988
+ });
989
+ for (let attempt = 0; ; attempt++) {
990
+ try {
991
+ return await this.start();
992
+ } catch (err) {
993
+ if (err.code !== "EADDRINUSE" || attempt >= 20) throw err;
994
+ await new Promise((resolve) => setTimeout(resolve, 100));
995
+ }
996
+ }
997
+ }
998
+ /** Give the port to another bridge. Pages reconnect to it on their own. */
999
+ async _handOff() {
1000
+ clearInterval(this._heartbeat);
1001
+ for (const session of this.sessions.values()) {
1002
+ this._failPending(
1003
+ session,
1004
+ "Another Claude chat took over the Abundance bridge."
1005
+ );
1006
+ session.ws.close(HANDED_OFF, "Another bridge took over");
925
1007
  }
1008
+ this.sessions.clear();
1009
+ this.handedOff = true;
1010
+ await this._closeServer();
1011
+ this.emit("handed-off");
1012
+ }
1013
+ async _closeServer() {
1014
+ const wss = this.wss;
1015
+ this.wss = null;
1016
+ if (!wss) return;
1017
+ for (const client of wss.clients) client.terminate();
1018
+ await new Promise((resolve) => wss.close(() => resolve()));
926
1019
  }
927
1020
  // ------------------------------------------------------------------ sessions
928
1021
  listSessions() {
@@ -1009,6 +1102,10 @@ var PageHub = class extends EventEmitter {
1009
1102
  }
1010
1103
  // ------------------------------------------------------------------ internals
1011
1104
  _onConnection(ws, req) {
1105
+ if (req.url === HANDOFF_PATH) {
1106
+ this._onHandoffConnection(ws);
1107
+ return;
1108
+ }
1012
1109
  const origin = req.headers.origin;
1013
1110
  ws.isAlive = true;
1014
1111
  ws.on("pong", () => {
@@ -1047,6 +1144,36 @@ var PageHub = class extends EventEmitter {
1047
1144
  ws.on("error", () => {
1048
1145
  });
1049
1146
  }
1147
+ _onHandoffConnection(ws) {
1148
+ const timer = setTimeout(() => ws.terminate(), this.helloTimeoutMs);
1149
+ timer.unref?.();
1150
+ ws.once("message", (data) => {
1151
+ clearTimeout(timer);
1152
+ const msg = parseMessage(data.toString());
1153
+ if (msg?.method !== "bridge.handoff" || msg.id === void 0) {
1154
+ ws.close(CLOSE_CODES.HELLO_TIMEOUT, "Expected bridge.handoff");
1155
+ return;
1156
+ }
1157
+ if (!tokensMatch(this.token, msg.params?.token)) {
1158
+ this._send(
1159
+ ws,
1160
+ makeError(
1161
+ msg.id,
1162
+ ERROR_CODES.PERMISSION_DENIED,
1163
+ "Pairing token does not match this bridge."
1164
+ )
1165
+ );
1166
+ ws.close(CLOSE_CODES.BAD_TOKEN, "Bad pairing token");
1167
+ this.emit("rejected", { reason: "handoff-token", origin: null });
1168
+ return;
1169
+ }
1170
+ this._send(ws, makeResult(msg.id, { ok: true }));
1171
+ ws.close();
1172
+ this._handOff().catch((err) => this.emit("error", err));
1173
+ });
1174
+ ws.on("error", () => {
1175
+ });
1176
+ }
1050
1177
  _handleHello(ws, msg, origin) {
1051
1178
  const params = msg.params || {};
1052
1179
  if (params.protocolVersion !== PROTOCOL_VERSION) {
@@ -1186,6 +1313,44 @@ function pickInfo(params) {
1186
1313
  }
1187
1314
  return info;
1188
1315
  }
1316
+ function requestHandoff({ host, port, token, timeoutMs = 5e3 }) {
1317
+ const refused = (detail) => new ToolError(
1318
+ ERROR_CODES.CONFLICT,
1319
+ `The program on port ${port} did not hand over the bridge (${detail}). It may be an older Abundance bridge: close the other Claude chat, or restart its abundance MCP server, then try again.`
1320
+ );
1321
+ return new Promise((resolve, reject) => {
1322
+ const ws = new WebSocket(`ws://${host}:${port}${HANDOFF_PATH}`);
1323
+ const finish = (err) => {
1324
+ clearTimeout(timer);
1325
+ ws.removeAllListeners();
1326
+ ws.on("error", () => {
1327
+ });
1328
+ ws.terminate();
1329
+ if (err) reject(err);
1330
+ else resolve();
1331
+ };
1332
+ const timer = setTimeout(() => finish(refused("no answer")), timeoutMs);
1333
+ timer.unref?.();
1334
+ ws.on("open", () => {
1335
+ ws.send(JSON.stringify(makeRequest(1, "bridge.handoff", { token })));
1336
+ });
1337
+ ws.on("message", (data) => {
1338
+ const msg = parseMessage(data.toString());
1339
+ if (msg?.id !== 1) return;
1340
+ if (msg.error) {
1341
+ finish(new ToolError(ERROR_CODES.PERMISSION_DENIED, msg.error.message));
1342
+ } else {
1343
+ finish();
1344
+ }
1345
+ });
1346
+ ws.on(
1347
+ "unexpected-response",
1348
+ (_req, res) => finish(refused(`HTTP ${res.statusCode}`))
1349
+ );
1350
+ ws.on("error", (err) => finish(refused(err.message)));
1351
+ ws.on("close", () => finish(refused("connection closed")));
1352
+ });
1353
+ }
1189
1354
 
1190
1355
  // ../../bridge/index.js
1191
1356
  var here = path3.dirname(fileURLToPath2(import.meta.url));
@@ -1254,12 +1419,14 @@ async function main() {
1254
1419
  "rejected",
1255
1420
  ({ reason, origin }) => log(`refused connection from ${origin || "unknown origin"}: ${reason}`)
1256
1421
  );
1257
- let listenError = null;
1422
+ hub.on(
1423
+ "handed-off",
1424
+ () => log("another bridge took over the port; take_over_bridge takes it back")
1425
+ );
1258
1426
  try {
1259
1427
  const port = await hub.start();
1260
1428
  log(`listening on ws://127.0.0.1:${port}`);
1261
1429
  } catch (err) {
1262
- listenError = err;
1263
1430
  log(`could not listen on port ${opts.port}: ${err.message}`);
1264
1431
  }
1265
1432
  log(
@@ -1269,8 +1436,7 @@ async function main() {
1269
1436
  const { server } = createMcpServer(hub, {
1270
1437
  outDir: opts.outDir,
1271
1438
  tokenInfo,
1272
- version: VERSION,
1273
- getListenError: () => listenError
1439
+ version: VERSION
1274
1440
  });
1275
1441
  const transport = new StdioServerTransport();
1276
1442
  await server.connect(transport);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maslowcnc/abundance-bridge",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "MCP server that lets AI agents such as Claude inspect and edit the Abundance CAD project open in your browser.",
5
5
  "homepage": "https://abundance.maslowcnc.com",
6
6
  "repository": {