@markasso/mcp 0.10.0 → 0.10.1

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/markasso-mcp.js +349 -88
  2. package/package.json +1 -1
@@ -5747,7 +5747,7 @@ function escapeXml(str) {
5747
5747
  }
5748
5748
  //#endregion
5749
5749
  //#region package.json
5750
- var version = "0.10.0";
5750
+ var version = "0.10.1";
5751
5751
  //#endregion
5752
5752
  //#region ../src/core/layout.ts
5753
5753
  /** Space kept on both sides of a label between ranks. */
@@ -9384,10 +9384,41 @@ var AGENT_COLOR = "#c77dff";
9384
9384
  var JOIN_TIMEOUT_MS = 1e4;
9385
9385
  /** Close code the room uses for an agent without a valid licence. */
9386
9386
  var CLOSE_LICENCE_REQUIRED = 4402;
9387
+ /** Close code the room uses when it has no place for another peer. */
9388
+ var CLOSE_ROOM_FULL = 1013;
9389
+ /** Close code (with reason "replaced") for a socket a newer one replaced. */
9390
+ var CLOSE_REPLACED = 1e3;
9391
+ var RECONNECT_BASE_MS = 1e3;
9392
+ var RECONNECT_MAX_MS = 1e4;
9393
+ /**
9394
+ * How long the link keeps trying to get back into the room after a drop,
9395
+ * join timeouts included: the attempts never outlast this window.
9396
+ */
9397
+ var RECONNECT_WINDOW_MS = 45e3;
9387
9398
  var LICENCE_MESSAGE = "Drawing live with an AI agent needs a Markasso Cloud licence. Get one at https://markasso.it/cloud, then set MARKASSO_LICENSE in this MCP server's environment.";
9388
9399
  var LiveError = class extends Error {
9389
9400
  name = "LiveError";
9390
9401
  };
9402
+ /** A close the room means as final: retrying would only repeat it. */
9403
+ function isFinalClose(close) {
9404
+ return close.code === CLOSE_LICENCE_REQUIRED || close.code === CLOSE_ROOM_FULL || close.code === CLOSE_REPLACED && close.reason === "replaced";
9405
+ }
9406
+ /** " (code 1006: reason)" for a status line, empty when nothing is known. */
9407
+ function describeClose(close) {
9408
+ if (!close) return "";
9409
+ const parts = [close.code !== null ? `code ${close.code}` : "", close.reason].filter(Boolean);
9410
+ return parts.length > 0 ? ` (${parts.join(": ")})` : "";
9411
+ }
9412
+ /** One connection attempt that did not get into the room. */
9413
+ var AttemptFailed = class extends LiveError {
9414
+ close;
9415
+ final;
9416
+ constructor(message, close, final) {
9417
+ super(message);
9418
+ this.close = close;
9419
+ this.final = final;
9420
+ }
9421
+ };
9391
9422
  /**
9392
9423
  * Whether a live link points at the Markasso instance this server is set up
9393
9424
  * for (`MARKASSO_URL`, default markasso.it). The licence key is a paid
@@ -9439,13 +9470,34 @@ var REJECTION_TEXT = {
9439
9470
  };
9440
9471
  var LiveLink = class LiveLink {
9441
9472
  diagram;
9473
+ origin;
9442
9474
  name;
9443
9475
  room;
9444
9476
  url;
9445
9477
  socket = null;
9446
9478
  peers = [];
9447
9479
  selfId = "";
9448
- open = false;
9480
+ /**
9481
+ * One identity for the whole session, reused on every reconnect: the room
9482
+ * then replaces the stale socket instead of seeing a second peer, and
9483
+ * still accepts replies to requests it routed to this agent before a drop.
9484
+ */
9485
+ clientId = randomClientId();
9486
+ _state = "connecting";
9487
+ /** How the last socket or attempt ended (see describeClose). */
9488
+ _lastClose = null;
9489
+ /**
9490
+ * Bumped for each socket and on leave: events of an older socket arriving
9491
+ * late are ignored, so they never act on the current connection.
9492
+ */
9493
+ attemptId = 0;
9494
+ reconnectTimer = null;
9495
+ reconnectAttempt = 0;
9496
+ reconnectDeadline = 0;
9497
+ /** The close that started the current reconnect, for its notice. */
9498
+ dropClose = null;
9499
+ /** One-shot notes for the model's next tool answer (see takeNotices). */
9500
+ notices = [];
9449
9501
  inbox = [];
9450
9502
  /**
9451
9503
  * Delivered request ids the agent may answer, each with the elements the
@@ -9467,10 +9519,32 @@ var LiveLink = class LiveLink {
9467
9519
  /** Set while replaying a remote undo/redo, which History re-emits. */
9468
9520
  constructor(diagram, room, origin, name) {
9469
9521
  this.diagram = diagram;
9522
+ this.origin = origin;
9470
9523
  this.name = name;
9471
9524
  this.room = room;
9472
9525
  this.url = `${origin}/?live=${encodeURIComponent(room)}`;
9473
9526
  }
9527
+ /** Only a link in the room sends edits, activity and answers. */
9528
+ get open() {
9529
+ return this._state === "connected";
9530
+ }
9531
+ get state() {
9532
+ return this._state;
9533
+ }
9534
+ get lastClose() {
9535
+ return this._lastClose;
9536
+ }
9537
+ /** Notes about the connection since the last call, each reported once. */
9538
+ takeNotices() {
9539
+ const taken = this.notices;
9540
+ this.notices = [];
9541
+ return taken;
9542
+ }
9543
+ /** Throws a LiveError that says why the room cannot be reached now. */
9544
+ assertConnected() {
9545
+ if (this._state === "reconnecting") throw new LiveError("The live session is reconnecting: try again in a few seconds.");
9546
+ if (!this.open) throw new LiveError("Not connected to the live room: call live_join again.");
9547
+ }
9474
9548
  /**
9475
9549
  * Attributes the agent's own edits to the request it is working on, when
9476
9550
  * only one waits for an answer (see `answerable`). Deleted elements leave
@@ -9546,7 +9620,7 @@ var LiveLink = class LiveLink {
9546
9620
  const live = new LiveLink(diagram, room, origin, name);
9547
9621
  return {
9548
9622
  link: live,
9549
- ...await live.connect(origin)
9623
+ ...await live.openSocket((msg) => live.enterRoom(msg, true))
9550
9624
  };
9551
9625
  }
9552
9626
  get connected() {
@@ -9580,15 +9654,21 @@ var LiveLink = class LiveLink {
9580
9654
  await this.outbox.idle(timeoutMs);
9581
9655
  await new Promise((resolve) => setTimeout(resolve, graceMs));
9582
9656
  }
9583
- /** Requests received and not yet handed to the model. */
9657
+ /**
9658
+ * Requests received and ready to hand to the model. None while out of the
9659
+ * room: they stay queued until it is back, since telling their senders
9660
+ * they were received needs the room.
9661
+ */
9584
9662
  get pendingRequests() {
9585
- return this.inbox.length;
9663
+ return this.open ? this.inbox.length : 0;
9586
9664
  }
9587
9665
  /**
9588
9666
  * Hands every queued request to the caller (the model) and tells each
9589
- * sender it was received. They can then be answered with `reply`.
9667
+ * sender it was received. They can then be answered with `reply`. Hands
9668
+ * nothing while out of the room (see pendingRequests).
9590
9669
  */
9591
9670
  takeRequests() {
9671
+ if (!this.open) return [];
9592
9672
  const taken = this.inbox;
9593
9673
  this.inbox = [];
9594
9674
  for (const request of taken) {
@@ -9611,25 +9691,38 @@ var LiveLink = class LiveLink {
9611
9691
  }
9612
9692
  /**
9613
9693
  * Resolves with the queued requests as soon as there is one, or with none
9614
- * after `timeoutMs` or when the room disconnects.
9694
+ * after `timeoutMs`, or once the session is lost or left. A drop the link
9695
+ * recovers from does not end the wait: it keeps the same deadline.
9615
9696
  */
9616
9697
  async waitForRequests(timeoutMs) {
9617
- if (this.inbox.length === 0 && this.open) {
9618
- this.waiting++;
9619
- this.updateActivity();
9620
- await new Promise((resolve) => {
9621
- const wake = () => {
9622
- clearTimeout(timer);
9623
- this.waiters.delete(wake);
9624
- this.waiting--;
9625
- resolve();
9626
- };
9627
- const timer = setTimeout(wake, timeoutMs);
9628
- this.waiters.add(wake);
9629
- });
9698
+ const deadline = Date.now() + timeoutMs;
9699
+ while (this.recoverable && this.pendingRequests === 0) {
9700
+ const remaining = deadline - Date.now();
9701
+ if (remaining <= 0) break;
9702
+ await this.waitForWake(remaining);
9703
+ if (this.open) break;
9630
9704
  }
9631
9705
  return this.takeRequests();
9632
9706
  }
9707
+ /** In the room, or on its way back. */
9708
+ get recoverable() {
9709
+ return this._state === "connected" || this._state === "reconnecting";
9710
+ }
9711
+ /** Waits for a request, a change of connection, or `timeoutMs`. */
9712
+ waitForWake(timeoutMs) {
9713
+ this.waiting++;
9714
+ this.updateActivity();
9715
+ return new Promise((resolve) => {
9716
+ const wake = () => {
9717
+ clearTimeout(timer);
9718
+ this.waiters.delete(wake);
9719
+ this.waiting--;
9720
+ resolve();
9721
+ };
9722
+ const timer = setTimeout(wake, timeoutMs);
9723
+ this.waiters.add(wake);
9724
+ });
9725
+ }
9633
9726
  /**
9634
9727
  * Sends an answer to the person behind a delivered request, pointing at
9635
9728
  * `elements` when given, else at the elements the agent changed for it.
@@ -9637,7 +9730,7 @@ var LiveLink = class LiveLink {
9637
9730
  * could not be told apart from another request's (`ambiguous`).
9638
9731
  */
9639
9732
  reply(id, text, elements) {
9640
- if (!this.open) throw new LiveError("Not connected to the live room.");
9733
+ this.assertConnected();
9641
9734
  if (!this.answerable.has(id)) throw new LiveError(`Unknown request id "${id}".`);
9642
9735
  const touched = this.answerable.get(id) ?? null;
9643
9736
  const trimmed = text.trim();
@@ -9684,17 +9777,50 @@ var LiveLink = class LiveLink {
9684
9777
  send(message) {
9685
9778
  if (this.socket?.readyState === WebSocket.OPEN) this.socket.send(JSON.stringify(message));
9686
9779
  }
9687
- connect(origin) {
9688
- const wsOrigin = origin.replace(/^http/, "ws");
9689
- const socket = new WebSocket(`${wsOrigin}/session/ws?room=${encodeURIComponent(this.room)}&clientId=${randomClientId()}`);
9690
- this.socket = socket;
9691
- const history = this.diagram.history;
9780
+ /**
9781
+ * Opens one socket to the room and resolves with what `onInit` returns,
9782
+ * run as soon as the room's `init` arrives (in the same event, so no
9783
+ * remote command can slip in before it). Rejects with an AttemptFailed
9784
+ * when the attempt ends before that. Every listener belongs to this
9785
+ * attempt only: once another socket is opened or the link is left, this
9786
+ * socket's events are ignored.
9787
+ */
9788
+ openSocket(onInit, timeoutMs = JOIN_TIMEOUT_MS) {
9789
+ const attempt = ++this.attemptId;
9790
+ const current = () => attempt === this.attemptId;
9791
+ const origin = this.origin;
9792
+ const url = `${origin.replace(/^http/, "ws")}/session/ws?room=${encodeURIComponent(this.room)}&clientId=${this.clientId}`;
9692
9793
  return new Promise((resolve, reject) => {
9693
- const timer = setTimeout(() => {
9694
- socket.close();
9695
- reject(new LiveError("Timed out joining the live room."));
9696
- }, JOIN_TIMEOUT_MS);
9794
+ let socket;
9795
+ try {
9796
+ socket = new WebSocket(url);
9797
+ } catch (error) {
9798
+ reject(new AttemptFailed("Could not connect to the live room.", {
9799
+ code: null,
9800
+ reason: error instanceof Error ? error.message : String(error)
9801
+ }, false));
9802
+ return;
9803
+ }
9804
+ this.socket = socket;
9805
+ /** In the room: `init` arrived. */
9806
+ let admitted = false;
9807
+ /** The promise is settled, one way or the other. */
9808
+ let settled = false;
9809
+ const fail = (error) => {
9810
+ if (settled) return;
9811
+ settled = true;
9812
+ clearTimeout(timer);
9813
+ reject(error);
9814
+ try {
9815
+ socket.close();
9816
+ } catch {}
9817
+ };
9818
+ const timer = setTimeout(() => fail(new AttemptFailed("Timed out joining the live room.", {
9819
+ code: null,
9820
+ reason: "join timed out"
9821
+ }, false)), timeoutMs);
9697
9822
  socket.addEventListener("open", () => {
9823
+ if (!current()) return;
9698
9824
  const license = process.env.MARKASSO_LICENSE?.trim();
9699
9825
  if (license && isConfiguredInstance(origin)) this.send({
9700
9826
  type: "auth",
@@ -9707,6 +9833,7 @@ var LiveLink = class LiveLink {
9707
9833
  });
9708
9834
  });
9709
9835
  socket.addEventListener("message", (event) => {
9836
+ if (!current()) return;
9710
9837
  let msg;
9711
9838
  try {
9712
9839
  msg = JSON.parse(String(event.data));
@@ -9714,33 +9841,15 @@ var LiveLink = class LiveLink {
9714
9841
  return;
9715
9842
  }
9716
9843
  if (msg.type === "init") {
9844
+ if (settled) return;
9845
+ admitted = true;
9846
+ settled = true;
9717
9847
  clearTimeout(timer);
9718
- this.selfId = msg.self;
9719
- this.peers = msg.peers;
9720
- const local = [...this.diagram.elements];
9721
- let seeded = false;
9722
- let discarded = 0;
9723
- if (msg.commands.length > 0) {
9724
- discarded = local.length;
9725
- history.resetForLiveReplay(msg.commands.filter(isValidSessionCommand));
9726
- } else if (local.length > 0) {
9727
- for (const command of createCommands(local, { validOnly: true })) this.publish(command);
9728
- seeded = true;
9729
- }
9730
- history.setOnCommand((command) => {
9731
- if (this.open && isSessionCommand(command)) this.publish(command);
9732
- });
9733
- this.untrack();
9734
- this.stopTracking = this.diagram.onLocalChange((changed, removed) => this.noteEdited(changed, removed));
9735
- this.open = true;
9736
- this.sendActivity(this.currentActivity());
9737
- resolve({
9738
- seeded,
9739
- discarded
9740
- });
9848
+ resolve(onInit(msg));
9741
9849
  } else if (msg.type === "apply") {
9850
+ if (!admitted) return;
9742
9851
  if (isSessionCommand(msg.command) && isValidSessionCommand(msg.command)) try {
9743
- history.applyRemote(msg.command);
9852
+ this.diagram.history.applyRemote(msg.command);
9744
9853
  } catch (error) {
9745
9854
  console.error("Skipped a live command that failed to apply", error);
9746
9855
  }
@@ -9748,31 +9857,136 @@ var LiveLink = class LiveLink {
9748
9857
  else if (msg.type === "request") this.receiveRequest(msg);
9749
9858
  else if (msg.type === "rejected" && typeof msg.reason === "string") {
9750
9859
  if (!this.rejections.includes(msg.reason)) this.rejections.push(msg.reason);
9751
- } else if (msg.type === "error" && !this.open) {
9752
- clearTimeout(timer);
9753
- reject(new LiveError(msg.error === "licence required" ? licenceMessage(origin) : `The live room refused to join: ${msg.error}.`));
9860
+ } else if (msg.type === "error" && !admitted) {
9861
+ const final = msg.error === "licence required" || msg.error === "room full";
9862
+ fail(new AttemptFailed(msg.error === "licence required" ? licenceMessage(origin) : `The live room refused to join: ${msg.error}.`, {
9863
+ code: null,
9864
+ reason: msg.error
9865
+ }, final));
9754
9866
  }
9755
9867
  });
9756
9868
  socket.addEventListener("close", (event) => {
9757
- clearTimeout(timer);
9758
- if (!this.open) reject(new LiveError(event.code === CLOSE_LICENCE_REQUIRED ? licenceMessage(origin) : "The live room closed the connection."));
9759
- this.open = false;
9760
- this.outbox.clear();
9761
- history.setOnCommand(void 0);
9762
- this.untrack();
9763
- this.clearIdleTimer();
9764
- this.wakeWaiters();
9869
+ if (!current()) return;
9870
+ const close = {
9871
+ code: typeof event.code === "number" ? event.code : null,
9872
+ reason: typeof event.reason === "string" ? event.reason : ""
9873
+ };
9874
+ if (!admitted) {
9875
+ fail(new AttemptFailed(close.code === CLOSE_LICENCE_REQUIRED ? licenceMessage(origin) : "The live room closed the connection.", close, isFinalClose(close)));
9876
+ return;
9877
+ }
9878
+ this.dropped(close);
9765
9879
  });
9766
9880
  socket.addEventListener("error", () => {
9767
- if (!this.open) {
9768
- clearTimeout(timer);
9769
- reject(new LiveError("Could not connect to the live room."));
9770
- }
9881
+ if (!current() || admitted) return;
9882
+ fail(new AttemptFailed("Could not connect to the live room.", {
9883
+ code: null,
9884
+ reason: "socket error"
9885
+ }, false));
9771
9886
  });
9772
9887
  });
9773
9888
  }
9889
+ /**
9890
+ * Takes the room's state on `init`. On the first join the room's log
9891
+ * replaces the local diagram, or the local diagram seeds an empty room;
9892
+ * on a reconnect the room is authoritative even when empty, and nothing
9893
+ * is published, so stale content never comes back.
9894
+ */
9895
+ enterRoom(msg, first) {
9896
+ const history = this.diagram.history;
9897
+ this.selfId = msg.self;
9898
+ this.peers = msg.peers;
9899
+ const local = [...this.diagram.elements];
9900
+ let seeded = false;
9901
+ let discarded = 0;
9902
+ if (msg.commands.length > 0 || !first) {
9903
+ if (first) discarded = local.length;
9904
+ history.resetForLiveReplay(msg.commands.filter(isValidSessionCommand));
9905
+ } else if (local.length > 0) {
9906
+ for (const command of createCommands(local, { validOnly: true })) this.publish(command);
9907
+ seeded = true;
9908
+ }
9909
+ if (first) {
9910
+ history.setOnCommand((command) => {
9911
+ if (this.open && isSessionCommand(command)) this.publish(command);
9912
+ });
9913
+ this.untrack();
9914
+ this.stopTracking = this.diagram.onLocalChange((changed, removed) => {
9915
+ if (this.open) this.noteEdited(changed, removed);
9916
+ });
9917
+ }
9918
+ this._state = "connected";
9919
+ this.reconnectAttempt = 0;
9920
+ this.clearIdleTimer();
9921
+ this.sendActivity(this.currentActivity());
9922
+ if (this.inbox.length > 0) this.wakeWaiters();
9923
+ return {
9924
+ seeded,
9925
+ discarded
9926
+ };
9927
+ }
9928
+ /** The socket of a joined session closed: retry unless it is final. */
9929
+ dropped(close) {
9930
+ this._lastClose = close;
9931
+ this.dropClose = close;
9932
+ this.outbox.clear();
9933
+ this.clearIdleTimer();
9934
+ if (isFinalClose(close)) {
9935
+ this.lose();
9936
+ return;
9937
+ }
9938
+ this._state = "reconnecting";
9939
+ this.reconnectAttempt = 0;
9940
+ this.reconnectDeadline = Date.now() + RECONNECT_WINDOW_MS;
9941
+ this.scheduleReconnect();
9942
+ }
9943
+ scheduleReconnect() {
9944
+ const delay = Math.min(RECONNECT_BASE_MS * 2 ** this.reconnectAttempt, RECONNECT_MAX_MS);
9945
+ this.reconnectAttempt++;
9946
+ if (Date.now() + delay >= this.reconnectDeadline) {
9947
+ this.lose();
9948
+ return;
9949
+ }
9950
+ this.reconnectTimer = setTimeout(() => {
9951
+ this.reconnectTimer = null;
9952
+ this.reconnect();
9953
+ }, delay);
9954
+ }
9955
+ async reconnect() {
9956
+ if (this._state !== "reconnecting") return;
9957
+ const remaining = this.reconnectDeadline - Date.now();
9958
+ try {
9959
+ await this.openSocket((msg) => {
9960
+ this.notices.push(`The live session dropped${describeClose(this.dropClose)} and reconnected. The board was reloaded from the room, so your most recent edits may be missing: call diagram_read before editing further.`);
9961
+ return this.enterRoom(msg, false);
9962
+ }, Math.min(JOIN_TIMEOUT_MS, remaining));
9963
+ } catch (error) {
9964
+ if (this._state !== "reconnecting") return;
9965
+ if (error instanceof AttemptFailed) {
9966
+ this._lastClose = error.close;
9967
+ if (error.final) {
9968
+ this.lose();
9969
+ return;
9970
+ }
9971
+ } else console.error("Unexpected error while reconnecting", error);
9972
+ this.scheduleReconnect();
9973
+ }
9974
+ }
9975
+ /** Gives up on the room: waiting calls return, nothing is sent anymore. */
9976
+ lose() {
9977
+ this._state = "lost";
9978
+ this.cancelReconnect();
9979
+ this.untrack();
9980
+ this.clearIdleTimer();
9981
+ this.wakeWaiters();
9982
+ }
9983
+ cancelReconnect() {
9984
+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
9985
+ this.reconnectTimer = null;
9986
+ }
9774
9987
  /** Moves the agent's cursor so people see where it is working. */
9775
9988
  pointAt(x, y) {
9989
+ if (!this.open) return;
9776
9990
  this.send({
9777
9991
  type: "cursor",
9778
9992
  x,
@@ -9782,12 +9996,13 @@ var LiveLink = class LiveLink {
9782
9996
  });
9783
9997
  }
9784
9998
  leave() {
9785
- this.outbox.drain();
9786
- this.open = false;
9999
+ if (this.open) this.outbox.drain();
10000
+ this._state = "left";
10001
+ this.attemptId++;
10002
+ this.cancelReconnect();
9787
10003
  this.wakeWaiters();
9788
10004
  this.untrack();
9789
10005
  this.clearIdleTimer();
9790
- this.diagram.history.setOnCommand(void 0);
9791
10006
  this.socket?.close();
9792
10007
  this.socket = null;
9793
10008
  }
@@ -10110,6 +10325,14 @@ var edgeRefSchema = {
10110
10325
  };
10111
10326
  var diagram = new Diagram();
10112
10327
  var live = null;
10328
+ /**
10329
+ * Bumped whenever the session changes (new or opened diagram, join, leave),
10330
+ * so a live_join that another change overtook while it was connecting
10331
+ * leaves its room instead of taking over.
10332
+ */
10333
+ var sessionEpoch = 0;
10334
+ /** live_join calls run one at a time (see joinLive). */
10335
+ var joining = Promise.resolve();
10113
10336
  function text(message) {
10114
10337
  return { content: [{
10115
10338
  type: "text",
@@ -10189,13 +10412,48 @@ function guarded(run) {
10189
10412
  if (live && live.editCount > (live === before ? editsBefore : 0)) await live.settle(QUEUE_WAIT_MS, REFUSAL_WAIT_MS);
10190
10413
  const refused = [before, live !== before ? live : null].map((link) => link?.takeRejections() ?? "").filter(Boolean);
10191
10414
  if (refused.length > 0 && first) first.text += `\n${refused.join("\n")}`;
10415
+ if (live && first) {
10416
+ const edited = live.editCount > (live === before ? editsBefore : 0);
10417
+ const status = liveStatus(live, edited);
10418
+ if (status) first.text += `\n${status}`;
10419
+ }
10192
10420
  return result;
10193
10421
  });
10194
10422
  }
10195
- function liveSuffix() {
10196
- if (!live) return "";
10197
- if (!live.connected) return "\nWarning: the live session disconnected; call live_join again.";
10198
- return `\nLive: changes are visible to everyone in ${live.url}`;
10423
+ /**
10424
+ * The live session's status for the end of an answer, written after the
10425
+ * call's edits are settled: one-shot notes (a reconnect), a warning while
10426
+ * the room is out of reach, or where the edits of this call can be seen.
10427
+ */
10428
+ function liveStatus(link, edited) {
10429
+ const lines = link.takeNotices();
10430
+ if (link.state === "reconnecting") lines.push("Warning: the live session dropped and is reconnecting: edits made now do not reach the room.");
10431
+ else if (link.state === "lost") lines.push(`Warning: the live session was lost${describeClose(link.lastClose)}; call live_join again.`);
10432
+ else if (edited && link.connected) lines.push(`Live: changes are visible to everyone in ${link.url}`);
10433
+ return lines.join("\n");
10434
+ }
10435
+ /**
10436
+ * Leaves the current room and joins the one at `link`. Joins run one at a
10437
+ * time, since two at once would both replay their room into the same
10438
+ * diagram; one overtaken by another session change leaves right away.
10439
+ */
10440
+ function joinLive(link, name) {
10441
+ const run = async () => {
10442
+ live?.leave();
10443
+ live = null;
10444
+ const epoch = ++sessionEpoch;
10445
+ const target = diagram;
10446
+ const result = await LiveLink.join(target, link, name);
10447
+ if (epoch !== sessionEpoch || target !== diagram) {
10448
+ result.link.leave();
10449
+ throw new LiveError("The session changed while joining (another diagram or live call): the join was cancelled.");
10450
+ }
10451
+ live = result.link;
10452
+ return result;
10453
+ };
10454
+ const next = joining.then(run, run);
10455
+ joining = next.catch(() => void 0);
10456
+ return next;
10199
10457
  }
10200
10458
  /** Points the agent's cursor at the given nodes on a live board. */
10201
10459
  function pointAtKeys(keys) {
@@ -10219,6 +10477,7 @@ server.registerTool("diagram_new", {
10219
10477
  }, guarded(() => {
10220
10478
  live?.leave();
10221
10479
  live = null;
10480
+ sessionEpoch++;
10222
10481
  diagram = new Diagram();
10223
10482
  return "New empty diagram ready.";
10224
10483
  }));
@@ -10230,6 +10489,7 @@ server.registerTool("diagram_open", {
10230
10489
  const elements = /^https?:\/\//.test(source) ? await loadShareLink(source) : await loadMarkassoFile(source);
10231
10490
  live?.leave();
10232
10491
  live = null;
10492
+ sessionEpoch++;
10233
10493
  diagram = new Diagram(elements);
10234
10494
  return `Opened ${elements.length} elements.\n${describeDiagram(diagram)}`;
10235
10495
  }));
@@ -10249,7 +10509,7 @@ server.registerTool("diagram_add_nodes", {
10249
10509
  }, guarded(async ({ nodes }) => {
10250
10510
  const keys = await diagram.addNodes(nodes);
10251
10511
  pointAtKeys(keys);
10252
- return `Added ${keys.length} nodes: ${keys.join(", ")}.${liveSuffix()}`;
10512
+ return `Added ${keys.length} nodes: ${keys.join(", ")}.`;
10253
10513
  }));
10254
10514
  server.registerTool("diagram_connect", {
10255
10515
  title: "Connect nodes",
@@ -10258,7 +10518,7 @@ server.registerTool("diagram_connect", {
10258
10518
  }, guarded(({ edges }) => {
10259
10519
  const count = diagram.connect(edges);
10260
10520
  pointAtKeys(edges.map((e) => e.to));
10261
- return `Added ${count} connections.${liveSuffix()}`;
10521
+ return `Added ${count} connections.`;
10262
10522
  }));
10263
10523
  server.registerTool("diagram_update", {
10264
10524
  title: "Update node",
@@ -10277,7 +10537,7 @@ server.registerTool("diagram_update", {
10277
10537
  const { key, ...patch } = args;
10278
10538
  diagram.update(key, patch);
10279
10539
  pointAtKeys([key]);
10280
- return `Updated ${key}.${liveSuffix()}`;
10540
+ return `Updated ${key}.`;
10281
10541
  }));
10282
10542
  server.registerTool("diagram_remove", {
10283
10543
  title: "Remove nodes",
@@ -10285,7 +10545,7 @@ server.registerTool("diagram_remove", {
10285
10545
  inputSchema: { keys: z.array(z.string()).min(1).max(200).describe("Keys of the nodes to remove") },
10286
10546
  annotations: { destructiveHint: true }
10287
10547
  }, guarded(({ keys }) => {
10288
- return `Removed ${diagram.remove(keys)} nodes.${liveSuffix()}`;
10548
+ return `Removed ${diagram.remove(keys)} nodes.`;
10289
10549
  }));
10290
10550
  server.registerTool("diagram_disconnect", {
10291
10551
  title: "Remove connections",
@@ -10293,7 +10553,7 @@ server.registerTool("diagram_disconnect", {
10293
10553
  inputSchema: { edges: z.array(z.object(edgeRefSchema)).min(1).max(200).describe("Connections to remove") },
10294
10554
  annotations: { destructiveHint: true }
10295
10555
  }, guarded(({ edges }) => {
10296
- return `Removed ${diagram.disconnect(edges)} connections.${liveSuffix()}`;
10556
+ return `Removed ${diagram.disconnect(edges)} connections.`;
10297
10557
  }));
10298
10558
  server.registerTool("diagram_update_edge", {
10299
10559
  title: "Update connection",
@@ -10320,7 +10580,7 @@ server.registerTool("diagram_update_edge", {
10320
10580
  ...rest,
10321
10581
  ...newLabel !== void 0 && { label: newLabel }
10322
10582
  });
10323
- return `Updated the connection.${liveSuffix()}`;
10583
+ return `Updated the connection.`;
10324
10584
  }));
10325
10585
  server.registerTool("diagram_layout", {
10326
10586
  title: "Auto layout",
@@ -10332,7 +10592,7 @@ server.registerTool("diagram_layout", {
10332
10592
  }, guarded(({ direction, keys }) => {
10333
10593
  const count = diagram.layout(direction ?? "TB", keys);
10334
10594
  if (count === 0) return "Nothing to lay out.";
10335
- return `Arranged ${count} nodes (${direction ?? "TB"}).${warningsSuffix(diagram)}${liveSuffix()}`;
10595
+ return `Arranged ${count} nodes (${direction ?? "TB"}).${warningsSuffix(diagram)}`;
10336
10596
  }));
10337
10597
  server.registerTool("icons_search", {
10338
10598
  title: "Search icons",
@@ -10438,12 +10698,10 @@ server.registerTool("live_join", {
10438
10698
  },
10439
10699
  annotations: { openWorldHint: true }
10440
10700
  }, guarded(async ({ link, name }) => {
10441
- live?.leave();
10442
- const result = await LiveLink.join(diagram, link, name ?? "AI agent");
10443
- live = result.link;
10701
+ const result = await joinLive(link, name ?? "AI agent");
10444
10702
  const notes = [result.seeded ? "The room was empty: your diagram was published to it." : "", result.discarded > 0 ? `The room already had content: it replaced your ${result.discarded} local elements.` : ""].filter(Boolean);
10445
10703
  return [
10446
- `Joined ${live.url}.`,
10704
+ `Joined ${result.link.url}.`,
10447
10705
  ...notes,
10448
10706
  describeDiagram(diagram)
10449
10707
  ].join("\n");
@@ -10456,6 +10714,7 @@ server.registerTool("live_leave", {
10456
10714
  if (!live) return "Not in a live session.";
10457
10715
  live.leave();
10458
10716
  live = null;
10717
+ sessionEpoch++;
10459
10718
  return "Left the live session.";
10460
10719
  }));
10461
10720
  server.registerTool("live_wait_request", {
@@ -10467,7 +10726,8 @@ server.registerTool("live_wait_request", {
10467
10726
  const link = live;
10468
10727
  const requests = await link.waitForRequests((timeoutSeconds ?? 50) * 1e3);
10469
10728
  if (requests.length > 0) return formatRequests(requests).trimStart();
10470
- if (!link.connected) return "The live session disconnected; call live_join again.";
10729
+ if (link.state === "left") return "Stopped waiting: the live session was left.";
10730
+ if (link.state === "lost") return "Stopped waiting: the live session ended.";
10471
10731
  return "No requests yet. Call live_wait_request again to keep listening, or live_leave to stop.";
10472
10732
  }));
10473
10733
  server.registerTool("live_reply", {
@@ -10480,6 +10740,7 @@ server.registerTool("live_reply", {
10480
10740
  }
10481
10741
  }, guarded(({ requestId, text, nodes }) => {
10482
10742
  if (!live) return "Not in a live session.";
10743
+ live.assertConnected();
10483
10744
  const { pointed, ambiguous } = live.reply(requestId, text, nodes ? diagram.idsOfKeys(nodes) : void 0);
10484
10745
  if (ambiguous) return "Reply sent without pointing at elements: you changed the board while several requests were open, so the changes cannot be told apart. Pass nodes to point at what this request changed.";
10485
10746
  return pointed > 0 ? `Reply sent, pointing at ${pointed} element${pointed === 1 ? "" : "s"}.` : "Reply sent.";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@markasso/mcp",
3
- "version": "0.10.0",
3
+ "version": "0.10.1",
4
4
  "mcpName": "io.github.AlbertoBarrago/markasso",
5
5
  "description": "MCP server that lets AI agents create, read and edit Markasso diagrams, offline or live on a shared board",
6
6
  "type": "module",