@markasso/mcp 0.9.1 → 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 +532 -88
  2. package/package.json +1 -1
@@ -1993,6 +1993,20 @@ function getBundledIcon(ref) {
1993
1993
  //#region ../src/io/agent_requests_protocol.ts
1994
1994
  /** Longest reply text an agent can send back. */
1995
1995
  var MAX_AGENT_REPLY_CHARS = 4e3;
1996
+ /**
1997
+ * The valid element ids of an untrusted `elements` field: strings of 1 to
1998
+ * MAX_ELEMENT_ID_CHARS characters, without duplicates, at most
1999
+ * MAX_REPLY_ELEMENTS. Anything else yields an empty list.
2000
+ */
2001
+ function sanitizeReplyElements(value) {
2002
+ if (!Array.isArray(value)) return [];
2003
+ const ids = /* @__PURE__ */ new Set();
2004
+ for (const id of value.slice(0, 200)) {
2005
+ if (ids.size >= 50) break;
2006
+ if (typeof id === "string" && id.length > 0 && id.length <= 128) ids.add(id);
2007
+ }
2008
+ return [...ids];
2009
+ }
1996
2010
  //#endregion
1997
2011
  //#region ../src/core/geometry.ts
1998
2012
  /**
@@ -5733,7 +5747,7 @@ function escapeXml(str) {
5733
5747
  }
5734
5748
  //#endregion
5735
5749
  //#region package.json
5736
- var version = "0.9.1";
5750
+ var version = "0.10.1";
5737
5751
  //#endregion
5738
5752
  //#region ../src/core/layout.ts
5739
5753
  /** Space kept on both sides of a label between ranks. */
@@ -8258,6 +8272,17 @@ function elementLabel(el) {
8258
8272
  if (el.type === "text") return el.content;
8259
8273
  return "label" in el && el.label ? el.label : "";
8260
8274
  }
8275
+ /**
8276
+ * Whether two versions of an element hold the same values, one level deep:
8277
+ * enough to tell a no-op patch (a label set to what it was) from an edit.
8278
+ * Nested values (points, styles) compare by reference, so a rewritten array
8279
+ * counts as a change even when equal: at worst one element too many.
8280
+ */
8281
+ function sameFields(a, b) {
8282
+ const aKeys = Object.keys(a);
8283
+ if (aKeys.length !== Object.keys(b).length) return false;
8284
+ return aKeys.every((key) => a[key] === b[key]);
8285
+ }
8261
8286
  var Diagram = class {
8262
8287
  history;
8263
8288
  /** Keys given by the agent; other elements get derived keys on read. */
@@ -8337,13 +8362,48 @@ var Diagram = class {
8337
8362
  }
8338
8363
  }
8339
8364
  /** `findId`, or the error the model can act on. */
8365
+ /**
8366
+ * Element ids of the nodes `keys` names (as diagram_read shows them).
8367
+ * Throws on an unknown key, like every tool that takes keys.
8368
+ */
8369
+ idsOfKeys(keys) {
8370
+ return keys.map((key) => this.idOf(key));
8371
+ }
8340
8372
  idOf(key) {
8341
8373
  const id = this.findId(key);
8342
8374
  if (id !== void 0) return id;
8343
8375
  throw new DiagramError(`Unknown node "${key}". Call diagram_read to see the keys.`);
8344
8376
  }
8377
+ /** See onLocalChange. */
8378
+ changeListeners = /* @__PURE__ */ new Set();
8379
+ /**
8380
+ * Notified after each edit this diagram makes itself (never a remote one
8381
+ * from a live room) with the ids of the elements it created or really
8382
+ * changed (an edit that leaves every field as it was does not count), and
8383
+ * of those it deleted.
8384
+ */
8385
+ onLocalChange(cb) {
8386
+ this.changeListeners.add(cb);
8387
+ return () => {
8388
+ this.changeListeners.delete(cb);
8389
+ };
8390
+ }
8345
8391
  dispatch(command) {
8392
+ if (this.changeListeners.size === 0) {
8393
+ this.history.dispatch(command);
8394
+ return;
8395
+ }
8396
+ const before = new Map(this.elements.map((el) => [el.id, el]));
8346
8397
  this.history.dispatch(command);
8398
+ const changed = /* @__PURE__ */ new Set();
8399
+ for (const el of this.elements) {
8400
+ const old = before.get(el.id);
8401
+ before.delete(el.id);
8402
+ if (old !== el && !(old && sameFields(old, el))) changed.add(el.id);
8403
+ }
8404
+ const removed = new Set(before.keys());
8405
+ if (changed.size === 0 && removed.size === 0) return;
8406
+ for (const listener of this.changeListeners) listener(changed, removed);
8347
8407
  }
8348
8408
  /** Bottom-left of the current content, where new nodes start a row. */
8349
8409
  nextRowOrigin() {
@@ -9312,15 +9372,53 @@ async function writeFileAtomic(path, data) {
9312
9372
  var MAX_INBOX = 20;
9313
9373
  /** Delivered request ids the agent may still answer with `reply`. */
9314
9374
  var MAX_ANSWERABLE = 100;
9375
+ /**
9376
+ * How long the agent must stay idle before the room hears it: a model that
9377
+ * calls live_wait_request again right after a timeout never shows as idle.
9378
+ */
9379
+ var IDLE_GRACE_MS = 5e3;
9380
+ /** Elements remembered per request; well above what a reply carries. */
9381
+ var MAX_TRACKED_ELEMENTS = 500;
9315
9382
  var ROOM_ID = /^[a-zA-Z0-9_-]{3,64}$/;
9316
9383
  var AGENT_COLOR = "#c77dff";
9317
9384
  var JOIN_TIMEOUT_MS = 1e4;
9318
9385
  /** Close code the room uses for an agent without a valid licence. */
9319
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;
9320
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.";
9321
9399
  var LiveError = class extends Error {
9322
9400
  name = "LiveError";
9323
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
+ };
9324
9422
  /**
9325
9423
  * Whether a live link points at the Markasso instance this server is set up
9326
9424
  * for (`MARKASSO_URL`, default markasso.it). The licence key is a paid
@@ -9372,30 +9470,157 @@ var REJECTION_TEXT = {
9372
9470
  };
9373
9471
  var LiveLink = class LiveLink {
9374
9472
  diagram;
9473
+ origin;
9375
9474
  name;
9376
9475
  room;
9377
9476
  url;
9378
9477
  socket = null;
9379
9478
  peers = [];
9380
9479
  selfId = "";
9381
- 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 = [];
9382
9501
  inbox = [];
9383
- answerable = /* @__PURE__ */ new Set();
9502
+ /**
9503
+ * Delivered request ids the agent may answer, each with the elements the
9504
+ * agent changed for it (sent with the reply), or null once that cannot be
9505
+ * told: edits made while several requests waited for an answer could be
9506
+ * for any of them, so none of them claims those edits.
9507
+ */
9508
+ answerable = /* @__PURE__ */ new Map();
9509
+ /** Delivered requests still waiting for their first reply. */
9510
+ unanswered = /* @__PURE__ */ new Set();
9511
+ /** live_wait_request calls currently waiting. */
9512
+ waiting = 0;
9513
+ /** The activity the room last heard from this agent. */
9514
+ activitySent = null;
9515
+ idleTimer = null;
9516
+ stopTracking = null;
9384
9517
  /** Pending `waitForRequests` calls, woken by a request or a disconnect. */
9385
9518
  waiters = /* @__PURE__ */ new Set();
9386
9519
  /** Set while replaying a remote undo/redo, which History re-emits. */
9387
9520
  constructor(diagram, room, origin, name) {
9388
9521
  this.diagram = diagram;
9522
+ this.origin = origin;
9389
9523
  this.name = name;
9390
9524
  this.room = room;
9391
9525
  this.url = `${origin}/?live=${encodeURIComponent(room)}`;
9392
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
+ }
9548
+ /**
9549
+ * Attributes the agent's own edits to the request it is working on, when
9550
+ * only one waits for an answer (see `answerable`). Deleted elements leave
9551
+ * every request, so they never fill the bound.
9552
+ */
9553
+ noteEdited(changed, removed) {
9554
+ for (const requestId of this.answerable.keys()) {
9555
+ const touched = this.answerable.get(requestId);
9556
+ for (const id of removed) touched?.delete(id);
9557
+ }
9558
+ if (changed.size === 0) return;
9559
+ if (this.unanswered.size > 1) {
9560
+ for (const requestId of this.unanswered) this.answerable.set(requestId, null);
9561
+ return;
9562
+ }
9563
+ for (const requestId of this.unanswered) {
9564
+ const touched = this.answerable.get(requestId);
9565
+ if (!touched) continue;
9566
+ for (const id of changed) {
9567
+ if (touched.size >= MAX_TRACKED_ELEMENTS) break;
9568
+ touched.add(id);
9569
+ }
9570
+ }
9571
+ }
9572
+ /**
9573
+ * What the agent is doing for the people in the room: waiting for
9574
+ * requests, busy with delivered ones still unanswered, or neither.
9575
+ */
9576
+ currentActivity() {
9577
+ if (this.waiting > 0) return "listening";
9578
+ if (this.unanswered.size > 0) return "working";
9579
+ return "idle";
9580
+ }
9581
+ /**
9582
+ * Tells the room when the activity changes. Going idle waits
9583
+ * IDLE_GRACE_MS, and is dropped if the agent is busy again by then.
9584
+ */
9585
+ updateActivity() {
9586
+ if (!this.open) return;
9587
+ const next = this.currentActivity();
9588
+ if (next === "idle" && this.activitySent !== "idle") {
9589
+ if (this.idleTimer) return;
9590
+ this.idleTimer = setTimeout(() => {
9591
+ this.idleTimer = null;
9592
+ if (this.currentActivity() === "idle") this.sendActivity("idle");
9593
+ }, IDLE_GRACE_MS);
9594
+ this.idleTimer.unref?.();
9595
+ return;
9596
+ }
9597
+ this.clearIdleTimer();
9598
+ if (next !== this.activitySent) this.sendActivity(next);
9599
+ }
9600
+ sendActivity(activity) {
9601
+ this.activitySent = activity;
9602
+ this.send({
9603
+ type: "presence",
9604
+ name: this.name,
9605
+ color: AGENT_COLOR,
9606
+ activity
9607
+ });
9608
+ }
9609
+ clearIdleTimer() {
9610
+ if (this.idleTimer) clearTimeout(this.idleTimer);
9611
+ this.idleTimer = null;
9612
+ }
9613
+ /** Stops attributing edits (the session is over). */
9614
+ untrack() {
9615
+ this.stopTracking?.();
9616
+ this.stopTracking = null;
9617
+ }
9393
9618
  static async join(diagram, link, name) {
9394
9619
  const { room, origin } = parseLiveLink(link);
9395
9620
  const live = new LiveLink(diagram, room, origin, name);
9396
9621
  return {
9397
9622
  link: live,
9398
- ...await live.connect(origin)
9623
+ ...await live.openSocket((msg) => live.enterRoom(msg, true))
9399
9624
  };
9400
9625
  }
9401
9626
  get connected() {
@@ -9429,60 +9654,102 @@ var LiveLink = class LiveLink {
9429
9654
  await this.outbox.idle(timeoutMs);
9430
9655
  await new Promise((resolve) => setTimeout(resolve, graceMs));
9431
9656
  }
9432
- /** 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
+ */
9433
9662
  get pendingRequests() {
9434
- return this.inbox.length;
9663
+ return this.open ? this.inbox.length : 0;
9435
9664
  }
9436
9665
  /**
9437
9666
  * Hands every queued request to the caller (the model) and tells each
9438
- * 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).
9439
9669
  */
9440
9670
  takeRequests() {
9671
+ if (!this.open) return [];
9441
9672
  const taken = this.inbox;
9442
9673
  this.inbox = [];
9443
9674
  for (const request of taken) {
9444
- this.answerable.add(request.id);
9445
- this.send({
9446
- type: "agent_status",
9447
- id: request.id,
9448
- status: "received"
9449
- });
9675
+ this.answerable.set(request.id, /* @__PURE__ */ new Set());
9676
+ this.unanswered.add(request.id);
9450
9677
  }
9451
9678
  while (this.answerable.size > MAX_ANSWERABLE) {
9452
- const oldest = this.answerable.values().next().value;
9679
+ const oldest = this.answerable.keys().next().value;
9453
9680
  if (oldest === void 0) break;
9454
9681
  this.answerable.delete(oldest);
9682
+ this.unanswered.delete(oldest);
9455
9683
  }
9684
+ this.updateActivity();
9685
+ for (const request of taken) this.send({
9686
+ type: "agent_status",
9687
+ id: request.id,
9688
+ status: "received"
9689
+ });
9456
9690
  return taken;
9457
9691
  }
9458
9692
  /**
9459
9693
  * Resolves with the queued requests as soon as there is one, or with none
9460
- * 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.
9461
9696
  */
9462
9697
  async waitForRequests(timeoutMs) {
9463
- if (this.inbox.length === 0 && this.open) await new Promise((resolve) => {
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;
9704
+ }
9705
+ return this.takeRequests();
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) => {
9464
9716
  const wake = () => {
9465
9717
  clearTimeout(timer);
9466
9718
  this.waiters.delete(wake);
9719
+ this.waiting--;
9467
9720
  resolve();
9468
9721
  };
9469
9722
  const timer = setTimeout(wake, timeoutMs);
9470
9723
  this.waiters.add(wake);
9471
9724
  });
9472
- return this.takeRequests();
9473
9725
  }
9474
- /** Sends an answer to the person behind a delivered request. */
9475
- reply(id, text) {
9476
- if (!this.open) throw new LiveError("Not connected to the live room.");
9726
+ /**
9727
+ * Sends an answer to the person behind a delivered request, pointing at
9728
+ * `elements` when given, else at the elements the agent changed for it.
9729
+ * Returns how many elements the reply points at, and whether the changes
9730
+ * could not be told apart from another request's (`ambiguous`).
9731
+ */
9732
+ reply(id, text, elements) {
9733
+ this.assertConnected();
9477
9734
  if (!this.answerable.has(id)) throw new LiveError(`Unknown request id "${id}".`);
9735
+ const touched = this.answerable.get(id) ?? null;
9478
9736
  const trimmed = text.trim();
9479
9737
  if (!trimmed || trimmed.length > 4e3) throw new LiveError(`A reply needs 1 to ${MAX_AGENT_REPLY_CHARS} characters.`);
9738
+ const present = new Set(this.diagram.elements.map((el) => el.id));
9739
+ const ids = sanitizeReplyElements([...elements ?? touched ?? []].filter((elementId) => present.has(elementId)));
9740
+ this.unanswered.delete(id);
9741
+ this.updateActivity();
9480
9742
  this.send({
9481
9743
  type: "agent_status",
9482
9744
  id,
9483
9745
  status: "replied",
9484
- text: trimmed
9746
+ text: trimmed,
9747
+ ...ids.length > 0 ? { elements: ids } : {}
9485
9748
  });
9749
+ return {
9750
+ pointed: ids.length,
9751
+ ambiguous: !elements && touched === null
9752
+ };
9486
9753
  }
9487
9754
  wakeWaiters() {
9488
9755
  for (const wake of [...this.waiters]) wake();
@@ -9510,17 +9777,50 @@ var LiveLink = class LiveLink {
9510
9777
  send(message) {
9511
9778
  if (this.socket?.readyState === WebSocket.OPEN) this.socket.send(JSON.stringify(message));
9512
9779
  }
9513
- connect(origin) {
9514
- const wsOrigin = origin.replace(/^http/, "ws");
9515
- const socket = new WebSocket(`${wsOrigin}/session/ws?room=${encodeURIComponent(this.room)}&clientId=${randomClientId()}`);
9516
- this.socket = socket;
9517
- 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}`;
9518
9793
  return new Promise((resolve, reject) => {
9519
- const timer = setTimeout(() => {
9520
- socket.close();
9521
- reject(new LiveError("Timed out joining the live room."));
9522
- }, 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);
9523
9822
  socket.addEventListener("open", () => {
9823
+ if (!current()) return;
9524
9824
  const license = process.env.MARKASSO_LICENSE?.trim();
9525
9825
  if (license && isConfiguredInstance(origin)) this.send({
9526
9826
  type: "auth",
@@ -9533,6 +9833,7 @@ var LiveLink = class LiveLink {
9533
9833
  });
9534
9834
  });
9535
9835
  socket.addEventListener("message", (event) => {
9836
+ if (!current()) return;
9536
9837
  let msg;
9537
9838
  try {
9538
9839
  msg = JSON.parse(String(event.data));
@@ -9540,30 +9841,15 @@ var LiveLink = class LiveLink {
9540
9841
  return;
9541
9842
  }
9542
9843
  if (msg.type === "init") {
9844
+ if (settled) return;
9845
+ admitted = true;
9846
+ settled = true;
9543
9847
  clearTimeout(timer);
9544
- this.selfId = msg.self;
9545
- this.peers = msg.peers;
9546
- const local = [...this.diagram.elements];
9547
- let seeded = false;
9548
- let discarded = 0;
9549
- if (msg.commands.length > 0) {
9550
- discarded = local.length;
9551
- history.resetForLiveReplay(msg.commands.filter(isValidSessionCommand));
9552
- } else if (local.length > 0) {
9553
- for (const command of createCommands(local, { validOnly: true })) this.publish(command);
9554
- seeded = true;
9555
- }
9556
- history.setOnCommand((command) => {
9557
- if (this.open && isSessionCommand(command)) this.publish(command);
9558
- });
9559
- this.open = true;
9560
- resolve({
9561
- seeded,
9562
- discarded
9563
- });
9848
+ resolve(onInit(msg));
9564
9849
  } else if (msg.type === "apply") {
9850
+ if (!admitted) return;
9565
9851
  if (isSessionCommand(msg.command) && isValidSessionCommand(msg.command)) try {
9566
- history.applyRemote(msg.command);
9852
+ this.diagram.history.applyRemote(msg.command);
9567
9853
  } catch (error) {
9568
9854
  console.error("Skipped a live command that failed to apply", error);
9569
9855
  }
@@ -9571,29 +9857,136 @@ var LiveLink = class LiveLink {
9571
9857
  else if (msg.type === "request") this.receiveRequest(msg);
9572
9858
  else if (msg.type === "rejected" && typeof msg.reason === "string") {
9573
9859
  if (!this.rejections.includes(msg.reason)) this.rejections.push(msg.reason);
9574
- } else if (msg.type === "error" && !this.open) {
9575
- clearTimeout(timer);
9576
- 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));
9577
9866
  }
9578
9867
  });
9579
9868
  socket.addEventListener("close", (event) => {
9580
- clearTimeout(timer);
9581
- if (!this.open) reject(new LiveError(event.code === CLOSE_LICENCE_REQUIRED ? licenceMessage(origin) : "The live room closed the connection."));
9582
- this.open = false;
9583
- this.outbox.clear();
9584
- history.setOnCommand(void 0);
9585
- 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);
9586
9879
  });
9587
9880
  socket.addEventListener("error", () => {
9588
- if (!this.open) {
9589
- clearTimeout(timer);
9590
- reject(new LiveError("Could not connect to the live room."));
9591
- }
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));
9592
9886
  });
9593
9887
  });
9594
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
+ }
9595
9987
  /** Moves the agent's cursor so people see where it is working. */
9596
9988
  pointAt(x, y) {
9989
+ if (!this.open) return;
9597
9990
  this.send({
9598
9991
  type: "cursor",
9599
9992
  x,
@@ -9603,10 +9996,13 @@ var LiveLink = class LiveLink {
9603
9996
  });
9604
9997
  }
9605
9998
  leave() {
9606
- this.outbox.drain();
9607
- this.open = false;
9999
+ if (this.open) this.outbox.drain();
10000
+ this._state = "left";
10001
+ this.attemptId++;
10002
+ this.cancelReconnect();
9608
10003
  this.wakeWaiters();
9609
- this.diagram.history.setOnCommand(void 0);
10004
+ this.untrack();
10005
+ this.clearIdleTimer();
9610
10006
  this.socket?.close();
9611
10007
  this.socket = null;
9612
10008
  }
@@ -9929,6 +10325,14 @@ var edgeRefSchema = {
9929
10325
  };
9930
10326
  var diagram = new Diagram();
9931
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();
9932
10336
  function text(message) {
9933
10337
  return { content: [{
9934
10338
  type: "text",
@@ -10008,13 +10412,48 @@ function guarded(run) {
10008
10412
  if (live && live.editCount > (live === before ? editsBefore : 0)) await live.settle(QUEUE_WAIT_MS, REFUSAL_WAIT_MS);
10009
10413
  const refused = [before, live !== before ? live : null].map((link) => link?.takeRejections() ?? "").filter(Boolean);
10010
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
+ }
10011
10420
  return result;
10012
10421
  });
10013
10422
  }
10014
- function liveSuffix() {
10015
- if (!live) return "";
10016
- if (!live.connected) return "\nWarning: the live session disconnected; call live_join again.";
10017
- 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;
10018
10457
  }
10019
10458
  /** Points the agent's cursor at the given nodes on a live board. */
10020
10459
  function pointAtKeys(keys) {
@@ -10038,6 +10477,7 @@ server.registerTool("diagram_new", {
10038
10477
  }, guarded(() => {
10039
10478
  live?.leave();
10040
10479
  live = null;
10480
+ sessionEpoch++;
10041
10481
  diagram = new Diagram();
10042
10482
  return "New empty diagram ready.";
10043
10483
  }));
@@ -10049,6 +10489,7 @@ server.registerTool("diagram_open", {
10049
10489
  const elements = /^https?:\/\//.test(source) ? await loadShareLink(source) : await loadMarkassoFile(source);
10050
10490
  live?.leave();
10051
10491
  live = null;
10492
+ sessionEpoch++;
10052
10493
  diagram = new Diagram(elements);
10053
10494
  return `Opened ${elements.length} elements.\n${describeDiagram(diagram)}`;
10054
10495
  }));
@@ -10068,7 +10509,7 @@ server.registerTool("diagram_add_nodes", {
10068
10509
  }, guarded(async ({ nodes }) => {
10069
10510
  const keys = await diagram.addNodes(nodes);
10070
10511
  pointAtKeys(keys);
10071
- return `Added ${keys.length} nodes: ${keys.join(", ")}.${liveSuffix()}`;
10512
+ return `Added ${keys.length} nodes: ${keys.join(", ")}.`;
10072
10513
  }));
10073
10514
  server.registerTool("diagram_connect", {
10074
10515
  title: "Connect nodes",
@@ -10077,7 +10518,7 @@ server.registerTool("diagram_connect", {
10077
10518
  }, guarded(({ edges }) => {
10078
10519
  const count = diagram.connect(edges);
10079
10520
  pointAtKeys(edges.map((e) => e.to));
10080
- return `Added ${count} connections.${liveSuffix()}`;
10521
+ return `Added ${count} connections.`;
10081
10522
  }));
10082
10523
  server.registerTool("diagram_update", {
10083
10524
  title: "Update node",
@@ -10096,7 +10537,7 @@ server.registerTool("diagram_update", {
10096
10537
  const { key, ...patch } = args;
10097
10538
  diagram.update(key, patch);
10098
10539
  pointAtKeys([key]);
10099
- return `Updated ${key}.${liveSuffix()}`;
10540
+ return `Updated ${key}.`;
10100
10541
  }));
10101
10542
  server.registerTool("diagram_remove", {
10102
10543
  title: "Remove nodes",
@@ -10104,7 +10545,7 @@ server.registerTool("diagram_remove", {
10104
10545
  inputSchema: { keys: z.array(z.string()).min(1).max(200).describe("Keys of the nodes to remove") },
10105
10546
  annotations: { destructiveHint: true }
10106
10547
  }, guarded(({ keys }) => {
10107
- return `Removed ${diagram.remove(keys)} nodes.${liveSuffix()}`;
10548
+ return `Removed ${diagram.remove(keys)} nodes.`;
10108
10549
  }));
10109
10550
  server.registerTool("diagram_disconnect", {
10110
10551
  title: "Remove connections",
@@ -10112,7 +10553,7 @@ server.registerTool("diagram_disconnect", {
10112
10553
  inputSchema: { edges: z.array(z.object(edgeRefSchema)).min(1).max(200).describe("Connections to remove") },
10113
10554
  annotations: { destructiveHint: true }
10114
10555
  }, guarded(({ edges }) => {
10115
- return `Removed ${diagram.disconnect(edges)} connections.${liveSuffix()}`;
10556
+ return `Removed ${diagram.disconnect(edges)} connections.`;
10116
10557
  }));
10117
10558
  server.registerTool("diagram_update_edge", {
10118
10559
  title: "Update connection",
@@ -10139,7 +10580,7 @@ server.registerTool("diagram_update_edge", {
10139
10580
  ...rest,
10140
10581
  ...newLabel !== void 0 && { label: newLabel }
10141
10582
  });
10142
- return `Updated the connection.${liveSuffix()}`;
10583
+ return `Updated the connection.`;
10143
10584
  }));
10144
10585
  server.registerTool("diagram_layout", {
10145
10586
  title: "Auto layout",
@@ -10151,7 +10592,7 @@ server.registerTool("diagram_layout", {
10151
10592
  }, guarded(({ direction, keys }) => {
10152
10593
  const count = diagram.layout(direction ?? "TB", keys);
10153
10594
  if (count === 0) return "Nothing to lay out.";
10154
- return `Arranged ${count} nodes (${direction ?? "TB"}).${warningsSuffix(diagram)}${liveSuffix()}`;
10595
+ return `Arranged ${count} nodes (${direction ?? "TB"}).${warningsSuffix(diagram)}`;
10155
10596
  }));
10156
10597
  server.registerTool("icons_search", {
10157
10598
  title: "Search icons",
@@ -10257,12 +10698,10 @@ server.registerTool("live_join", {
10257
10698
  },
10258
10699
  annotations: { openWorldHint: true }
10259
10700
  }, guarded(async ({ link, name }) => {
10260
- live?.leave();
10261
- const result = await LiveLink.join(diagram, link, name ?? "AI agent");
10262
- live = result.link;
10701
+ const result = await joinLive(link, name ?? "AI agent");
10263
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);
10264
10703
  return [
10265
- `Joined ${live.url}.`,
10704
+ `Joined ${result.link.url}.`,
10266
10705
  ...notes,
10267
10706
  describeDiagram(diagram)
10268
10707
  ].join("\n");
@@ -10275,6 +10714,7 @@ server.registerTool("live_leave", {
10275
10714
  if (!live) return "Not in a live session.";
10276
10715
  live.leave();
10277
10716
  live = null;
10717
+ sessionEpoch++;
10278
10718
  return "Left the live session.";
10279
10719
  }));
10280
10720
  server.registerTool("live_wait_request", {
@@ -10286,20 +10726,24 @@ server.registerTool("live_wait_request", {
10286
10726
  const link = live;
10287
10727
  const requests = await link.waitForRequests((timeoutSeconds ?? 50) * 1e3);
10288
10728
  if (requests.length > 0) return formatRequests(requests).trimStart();
10289
- 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.";
10290
10731
  return "No requests yet. Call live_wait_request again to keep listening, or live_leave to stop.";
10291
10732
  }));
10292
10733
  server.registerTool("live_reply", {
10293
10734
  title: "Reply to a live request",
10294
- description: "Answer a request from a person in the live room. The answer appears under your name in their participant list. Keep it short; the board itself shows what you changed.",
10735
+ description: "Answer a request from a person in the live room. The answer appears in their chat with you, with a button that selects and zooms to the elements you changed for that request. When you handle several requests at once, pass nodes: changes made while more than one request is open are not attributed to any of them. Keep it short; the board itself shows what you changed.",
10295
10736
  inputSchema: {
10296
10737
  requestId: z.string().min(1).max(64).describe("Id of the request"),
10297
- text: z.string().min(1).max(MAX_AGENT_REPLY_CHARS).describe("Short answer shown to the person")
10738
+ text: z.string().min(1).max(MAX_AGENT_REPLY_CHARS).describe("Short answer shown to the person"),
10739
+ nodes: z.array(z.string().min(1)).max(50).optional().describe("Keys of the nodes the answer is about (see diagram_read). Defaults to the elements you changed for this request.")
10298
10740
  }
10299
- }, guarded(({ requestId, text }) => {
10741
+ }, guarded(({ requestId, text, nodes }) => {
10300
10742
  if (!live) return "Not in a live session.";
10301
- live.reply(requestId, text);
10302
- return "Reply sent.";
10743
+ live.assertConnected();
10744
+ const { pointed, ambiguous } = live.reply(requestId, text, nodes ? diagram.idsOfKeys(nodes) : void 0);
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.";
10746
+ return pointed > 0 ? `Reply sent, pointing at ${pointed} element${pointed === 1 ? "" : "s"}.` : "Reply sent.";
10303
10747
  }));
10304
10748
  await server.connect(new StdioServerTransport());
10305
10749
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@markasso/mcp",
3
- "version": "0.9.1",
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",