@maslowcnc/abundance-bridge 0.1.2 → 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 +180 -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.
@@ -575,6 +576,12 @@ var BRIDGE_TOOLS = [
575
576
  inputSchema: { type: "object", properties: {} },
576
577
  annotations: { readOnlyHint: true }
577
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
+ },
578
585
  {
579
586
  name: "list_sessions",
580
587
  description: "List the Abundance browser tabs connected to the bridge and which one tools use by default.",
@@ -622,7 +629,7 @@ function annotationsFor(tool) {
622
629
  }
623
630
  return { readOnlyHint: true };
624
631
  }
625
- function createMcpServer(hub, { outDir, tokenInfo, version, getListenError }) {
632
+ function createMcpServer(hub, { outDir, tokenInfo, version }) {
626
633
  const server = new Server(
627
634
  { name: "abundance-bridge", version },
628
635
  { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS }
@@ -653,6 +660,11 @@ function createMcpServer(hub, { outDir, tokenInfo, version, getListenError }) {
653
660
  });
654
661
  async function callTool(name, args, request, extra) {
655
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
+ }
656
668
  if (name === "get_code_atom_guide") {
657
669
  return { content: [{ type: "text", text: await codeAtomGuide() }] };
658
670
  }
@@ -669,13 +681,8 @@ function createMcpServer(hub, { outDir, tokenInfo, version, getListenError }) {
669
681
  if (!tool) {
670
682
  throw new ToolError(ERROR_CODES.METHOD_NOT_FOUND, `Unknown tool ${name}`);
671
683
  }
672
- const listenError = getListenError?.();
673
- if (listenError) {
674
- throw new ToolError(
675
- ERROR_CODES.NO_PROJECT,
676
- `The bridge could not listen on port ${hub.port}: ${listenError.message}. Another bridge may already be running.`
677
- );
678
- }
684
+ const notListening = notListeningMessage();
685
+ if (notListening) throw new ToolError(ERROR_CODES.NO_PROJECT, notListening);
679
686
  const sessionId = args.session_id;
680
687
  delete args.session_id;
681
688
  const outputPath = args.output_path;
@@ -705,10 +712,24 @@ function createMcpServer(hub, { outDir, tokenInfo, version, getListenError }) {
705
712
  if (tool.output === "file") return fileResult(result, outputPath);
706
713
  return textResult(result);
707
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
+ }
708
728
  function status() {
709
729
  const sessions = hub.listSessions();
710
- const listenError = getListenError?.();
711
- const pairing = sessions.length > 0 ? null : [
730
+ const listenError = hub.listenError;
731
+ const notListening = notListeningMessage();
732
+ const pairing = sessions.length > 0 || notListening ? null : [
712
733
  "No Abundance tab is connected. To pair:",
713
734
  "1. Open Abundance (https://abundance.maslowcnc.com or the local dev server) in Chrome or Firefox.",
714
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.`,
@@ -717,8 +738,9 @@ function createMcpServer(hub, { outDir, tokenInfo, version, getListenError }) {
717
738
  "5. To let the agent change the project, the user also turns on Allow edits in the AI agent chip."
718
739
  ].join("\n");
719
740
  return {
720
- listening: !listenError && !!hub.wss,
741
+ listening: !!hub.wss,
721
742
  port: hub.port,
743
+ not_listening: notListening,
722
744
  listen_error: listenError ? listenError.message : null,
723
745
  token_file: tokenInfo.file,
724
746
  output_dir: outDir,
@@ -739,6 +761,19 @@ function createMcpServer(hub, { outDir, tokenInfo, version, getListenError }) {
739
761
  }
740
762
  return { server, status };
741
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
+ }
742
777
  async function precompileCode(name, args) {
743
778
  try {
744
779
  await precompileCodeUnchecked(name, args);
@@ -801,7 +836,7 @@ function errorResult(err) {
801
836
 
802
837
  // ../../bridge/pageHub.js
803
838
  import { EventEmitter } from "node:events";
804
- import { WebSocketServer } from "ws";
839
+ import WebSocket, { WebSocketServer } from "ws";
805
840
 
806
841
  // ../../bridge/token.js
807
842
  import crypto from "node:crypto";
@@ -848,6 +883,8 @@ function tokensMatch(expected, provided) {
848
883
 
849
884
  // ../../bridge/pageHub.js
850
885
  var HEARTBEAT_MS = 2e4;
886
+ var HANDOFF_PATH = "/handoff";
887
+ var HANDED_OFF = 4007;
851
888
  var PageHub = class extends EventEmitter {
852
889
  /**
853
890
  * @param {object} options
@@ -882,6 +919,7 @@ var PageHub = class extends EventEmitter {
882
919
  this._idsByClient = /* @__PURE__ */ new Map();
883
920
  this.wss = null;
884
921
  this.listenError = null;
922
+ this.handedOff = false;
885
923
  }
886
924
  /** Start listening. Resolves with the bound port. */
887
925
  start() {
@@ -892,6 +930,10 @@ var PageHub = class extends EventEmitter {
892
930
  maxPayload: 256 * 1024 * 1024,
893
931
  verifyClient: (info, done) => {
894
932
  const origin = info.origin || info.req.headers.origin;
933
+ if (info.req.url === HANDOFF_PATH && !origin) {
934
+ done(true);
935
+ return;
936
+ }
895
937
  if (!isAllowedOrigin(origin, this.extraOrigins)) {
896
938
  this.emit("rejected", { reason: "origin", origin });
897
939
  done(false, 403, "Origin not allowed");
@@ -910,6 +952,8 @@ var PageHub = class extends EventEmitter {
910
952
  wss.on("error", (err) => this.emit("error", err));
911
953
  this.wss = wss;
912
954
  this.port = wss.address().port;
955
+ this.listenError = null;
956
+ this.handedOff = false;
913
957
  this._heartbeat = setInterval(() => this._pingAll(), HEARTBEAT_MS);
914
958
  this._heartbeat.unref?.();
915
959
  resolve(this.port);
@@ -924,10 +968,54 @@ var PageHub = class extends EventEmitter {
924
968
  session.ws.terminate();
925
969
  }
926
970
  this.sessions.clear();
927
- if (this.wss) {
928
- await new Promise((resolve) => this.wss.close(() => resolve()));
929
- 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;
930
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");
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()));
931
1019
  }
932
1020
  // ------------------------------------------------------------------ sessions
933
1021
  listSessions() {
@@ -1014,6 +1102,10 @@ var PageHub = class extends EventEmitter {
1014
1102
  }
1015
1103
  // ------------------------------------------------------------------ internals
1016
1104
  _onConnection(ws, req) {
1105
+ if (req.url === HANDOFF_PATH) {
1106
+ this._onHandoffConnection(ws);
1107
+ return;
1108
+ }
1017
1109
  const origin = req.headers.origin;
1018
1110
  ws.isAlive = true;
1019
1111
  ws.on("pong", () => {
@@ -1052,6 +1144,36 @@ var PageHub = class extends EventEmitter {
1052
1144
  ws.on("error", () => {
1053
1145
  });
1054
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
+ }
1055
1177
  _handleHello(ws, msg, origin) {
1056
1178
  const params = msg.params || {};
1057
1179
  if (params.protocolVersion !== PROTOCOL_VERSION) {
@@ -1191,6 +1313,44 @@ function pickInfo(params) {
1191
1313
  }
1192
1314
  return info;
1193
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
+ }
1194
1354
 
1195
1355
  // ../../bridge/index.js
1196
1356
  var here = path3.dirname(fileURLToPath2(import.meta.url));
@@ -1259,12 +1419,14 @@ async function main() {
1259
1419
  "rejected",
1260
1420
  ({ reason, origin }) => log(`refused connection from ${origin || "unknown origin"}: ${reason}`)
1261
1421
  );
1262
- let listenError = null;
1422
+ hub.on(
1423
+ "handed-off",
1424
+ () => log("another bridge took over the port; take_over_bridge takes it back")
1425
+ );
1263
1426
  try {
1264
1427
  const port = await hub.start();
1265
1428
  log(`listening on ws://127.0.0.1:${port}`);
1266
1429
  } catch (err) {
1267
- listenError = err;
1268
1430
  log(`could not listen on port ${opts.port}: ${err.message}`);
1269
1431
  }
1270
1432
  log(
@@ -1274,8 +1436,7 @@ async function main() {
1274
1436
  const { server } = createMcpServer(hub, {
1275
1437
  outDir: opts.outDir,
1276
1438
  tokenInfo,
1277
- version: VERSION,
1278
- getListenError: () => listenError
1439
+ version: VERSION
1279
1440
  });
1280
1441
  const transport = new StdioServerTransport();
1281
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.2",
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": {