@markasso/mcp 0.7.2 → 0.7.4

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 +204 -122
  2. package/package.json +2 -2
@@ -4326,7 +4326,7 @@ function escapeXml(str) {
4326
4326
  }
4327
4327
  //#endregion
4328
4328
  //#region package.json
4329
- var version = "0.7.2";
4329
+ var version = "0.7.4";
4330
4330
  //#endregion
4331
4331
  //#region ../src/core/layout.ts
4332
4332
  /** Orders vertices without recursion, preserving input order when unconstrained. */
@@ -4481,7 +4481,6 @@ function createAppState() {
4481
4481
  gridSize: 20,
4482
4482
  gridType: "dot",
4483
4483
  strokeStyle: "solid",
4484
- justCreatedText: false,
4485
4484
  toolLocked: false,
4486
4485
  shapeKind: "terminator",
4487
4486
  lineRouting: "straight",
@@ -4516,13 +4515,9 @@ var EPHEMERAL_COMMANDS = /* @__PURE__ */ new Set([
4516
4515
  "CLEAR_SELECTION",
4517
4516
  "SET_TOOL",
4518
4517
  "SET_STROKE_COLOR",
4519
- "SET_FILL_COLOR",
4520
- "SET_STROKE_WIDTH",
4521
4518
  "TOGGLE_GRID",
4522
4519
  "SET_GRID_TYPE",
4523
- "SET_TOOL_LOCK",
4524
- "CLEAR_JUST_CREATED_TEXT",
4525
- "SET_JUST_CREATED_TEXT"
4520
+ "SET_TOOL_LOCK"
4526
4521
  ]);
4527
4522
  function isEphemeralCommand(type) {
4528
4523
  return EPHEMERAL_COMMANDS.has(type);
@@ -4831,20 +4826,6 @@ function reducer(scene, command, isRemote = false) {
4831
4826
  strokeColor: command.color
4832
4827
  }
4833
4828
  };
4834
- case "SET_FILL_COLOR": return {
4835
- ...scene,
4836
- appState: {
4837
- ...scene.appState,
4838
- fillColor: command.color
4839
- }
4840
- };
4841
- case "SET_STROKE_WIDTH": return {
4842
- ...scene,
4843
- appState: {
4844
- ...scene.appState,
4845
- strokeWidth: command.width
4846
- }
4847
- };
4848
4829
  case "SET_FONT_FAMILY": return {
4849
4830
  ...scene,
4850
4831
  appState: isRemote ? scene.appState : {
@@ -4901,13 +4882,6 @@ function reducer(scene, command, isRemote = false) {
4901
4882
  rotation: normalizeRotation(command.rotation)
4902
4883
  } : el)
4903
4884
  };
4904
- case "SET_STROKE_STYLE": return {
4905
- ...scene,
4906
- appState: {
4907
- ...scene.appState,
4908
- strokeStyle: command.style
4909
- }
4910
- };
4911
4885
  case "REORDER_ELEMENTS": {
4912
4886
  const idSet = new Set(command.ids);
4913
4887
  const moving = scene.elements.filter((el) => idSet.has(el.id));
@@ -4923,20 +4897,6 @@ function reducer(scene, command, isRemote = false) {
4923
4897
  elements: reordered
4924
4898
  };
4925
4899
  }
4926
- case "TOGGLE_ELEMENT_VISIBILITY": return {
4927
- ...scene,
4928
- elements: scene.elements.map((el) => el.id === command.id ? {
4929
- ...el,
4930
- visible: el.visible === false
4931
- } : el)
4932
- };
4933
- case "RENAME_LAYER": return {
4934
- ...scene,
4935
- elements: scene.elements.map((el) => el.id === command.id ? {
4936
- ...el,
4937
- layerName: command.name
4938
- } : el)
4939
- };
4940
4900
  case "LOAD_SCENE": return {
4941
4901
  ...scene,
4942
4902
  elements: command.elements,
@@ -4981,20 +4941,6 @@ function reducer(scene, command, isRemote = false) {
4981
4941
  } : el)
4982
4942
  };
4983
4943
  }
4984
- case "CLEAR_JUST_CREATED_TEXT": return {
4985
- ...scene,
4986
- appState: {
4987
- ...scene.appState,
4988
- justCreatedText: false
4989
- }
4990
- };
4991
- case "SET_JUST_CREATED_TEXT": return {
4992
- ...scene,
4993
- appState: {
4994
- ...scene.appState,
4995
- justCreatedText: true
4996
- }
4997
- };
4998
4944
  case "SET_TOOL_LOCK": return {
4999
4945
  ...scene,
5000
4946
  appState: {
@@ -5394,7 +5340,7 @@ var History = class {
5394
5340
  this.drag = null;
5395
5341
  this.future = drag.future;
5396
5342
  rebaseIndices(drag.change, drag.sceneBefore, this._present);
5397
- this.revert(drag.change, "undo", drag.appStateBefore, drag.selectedIdsBefore);
5343
+ this.revert(drag.change, "undo", this._present.appState, drag.appStateBefore, drag.selectedIdsBefore);
5398
5344
  }
5399
5345
  /** Set/replace the outbound hook used to forward local commands (e.g. to a
5400
5346
  * realtime session), including the patches undo/redo produce. Ephemeral
@@ -5432,8 +5378,7 @@ var History = class {
5432
5378
  ...fresh,
5433
5379
  appState: {
5434
5380
  ...appState,
5435
- lastCreatedId: null,
5436
- justCreatedText: false
5381
+ lastCreatedId: null
5437
5382
  },
5438
5383
  viewport: keepViewport ? viewport : fresh.viewport
5439
5384
  };
@@ -5446,7 +5391,7 @@ var History = class {
5446
5391
  this.notify();
5447
5392
  }
5448
5393
  dispatch(command) {
5449
- if (this.readOnly && (!isEphemeralCommand(command.type) || command.type === "SET_JUST_CREATED_TEXT")) return;
5394
+ if (this.readOnly && !isEphemeralCommand(command.type)) return;
5450
5395
  const resolved = withTargets(this._present, command);
5451
5396
  const next = reducer(this._present, resolved);
5452
5397
  if (next === this._present) return;
@@ -5478,7 +5423,7 @@ var History = class {
5478
5423
  const entry = this.past.pop();
5479
5424
  if (!entry) return;
5480
5425
  this.future.push(entry);
5481
- this.revert(entry.change, "undo", entry.appStateBefore);
5426
+ this.revert(entry.change, "undo", entry.appStateAfter, entry.appStateBefore);
5482
5427
  }
5483
5428
  redo() {
5484
5429
  if (this.readOnly) return;
@@ -5489,7 +5434,7 @@ var History = class {
5489
5434
  const entry = this.future.pop();
5490
5435
  if (!entry) return;
5491
5436
  this.past.push(entry);
5492
- this.revert(entry.change, "redo", entry.appStateAfter);
5437
+ this.revert(entry.change, "redo", entry.appStateBefore, entry.appStateAfter);
5493
5438
  }
5494
5439
  canUndo() {
5495
5440
  return !this.readOnly && this.past.length > 0;
@@ -5506,25 +5451,18 @@ var History = class {
5506
5451
  notify() {
5507
5452
  for (const l of this.listeners) l(this._present);
5508
5453
  }
5509
- /** Move the scene across `change` (see buildRevertPatch), restore the local
5510
- * appState of that side, and broadcast the element patch. */
5511
- revert(change, direction, appState, selectedIds) {
5454
+ /** Move the scene across `change` (see buildRevertPatch), move the local
5455
+ * appState fields the step changed from `from` back to `to`, and broadcast
5456
+ * the element patch. */
5457
+ revert(change, direction, from, to, selectedIds) {
5512
5458
  const patch = buildRevertPatch(change, this._present, direction);
5513
5459
  const patched = patch ? reducer(this._present, patch) : this._present;
5514
- this._present = restoreLocalState(patched, appState, selectedIds);
5460
+ this._present = restoreLocalState(patched, from, to, selectedIds);
5515
5461
  if (patch) this.onCommand?.(patch);
5516
5462
  this.notify();
5517
5463
  }
5518
5464
  };
5519
- /**
5520
- * appState fields undo and redo leave as they are now: the tool and the
5521
- * default style, which the tool switch and the style panel also set without
5522
- * an undo step (SET_TOOL inherits the selection's style and sets the shape
5523
- * kind), and view settings. Restoring them would undo choices the user made
5524
- * after the step. The text defaults (font size and family, alignment, mode)
5525
- * and the line routing are restored.
5526
- */
5527
- var KEPT_ON_UNDO = [
5465
+ var KEPT_ON_UNDO_SET = /* @__PURE__ */ new Set([...[
5528
5466
  "activeTool",
5529
5467
  "strokeColor",
5530
5468
  "fillColor",
@@ -5535,22 +5473,17 @@ var KEPT_ON_UNDO = [
5535
5473
  "shapeKind",
5536
5474
  "gridVisible",
5537
5475
  "gridType",
5538
- "toolLocked",
5539
- "justCreatedText"
5540
- ];
5541
- var KEPT_ON_UNDO_SET = /* @__PURE__ */ new Set([...KEPT_ON_UNDO, "lastCreatedId"]);
5476
+ "toolLocked"
5477
+ ], "lastCreatedId"]);
5542
5478
  /**
5543
- * Whether a change is worth an undo step: it touches elements or their order,
5544
- * or an appState field that undo restores. An element change the diff leaves
5479
+ * Whether a change is worth an undo step: it touches elements or their order.
5480
+ * An element change the diff leaves
5545
5481
  * out (a type-only change: the type is identity there) still counts, so the
5546
5482
  * board is never changed without a step.
5547
5483
  */
5548
5484
  function isUndoableChange(change, prev, next) {
5549
5485
  if (change.elements.size > 0 || change.order) return true;
5550
- if (!sameElements(prev.elements, next.elements)) return true;
5551
- const before = prev.appState;
5552
- const after = next.appState;
5553
- return Object.keys(after).some((key) => !KEPT_ON_UNDO_SET.has(key) && after[key] !== before[key]);
5486
+ return !sameElements(prev.elements, next.elements);
5554
5487
  }
5555
5488
  /** Same elements in the same order, by value (unchanged ones keep identity). */
5556
5489
  function sameElements(a, b) {
@@ -5559,24 +5492,30 @@ function sameElements(a, b) {
5559
5492
  return a.every((el, i) => el === b[i] || deepEqual(el, b[i]));
5560
5493
  }
5561
5494
  /**
5562
- * Restore the per-user appState recorded with an undo step (e.g. the font size
5563
- * default a command changed), keeping the fields in KEPT_ON_UNDO as they are
5564
- * now. The selection stays as-is unless `selectedIds` is given (cancelled
5565
- * drag); either way it is limited to elements that still exist.
5495
+ * Restore the per-user appState fields a step changed (e.g. the font size
5496
+ * default a SET_FONT_SIZE on a selection also set): each field that differs
5497
+ * between `from` and `to` goes back to its `to` value, except those in
5498
+ * KEPT_ON_UNDO, as long as it still holds the `from` value. Fields the step
5499
+ * did not change, or that changed since without a step (a default set with
5500
+ * nothing selected), stay as they are now.
5501
+ * The selection stays as-is unless `selectedIds` is given (cancelled drag);
5502
+ * either way it is limited to elements that still exist.
5566
5503
  */
5567
- function restoreLocalState(scene, appState, selectedIds = scene.selectedIds) {
5504
+ function restoreLocalState(scene, from, to, selectedIds = scene.selectedIds) {
5568
5505
  const elementIds = new Set(scene.elements.map((element) => element.id));
5569
- const current = scene.appState;
5570
- const kept = {};
5571
- for (const key of KEPT_ON_UNDO) kept[key] = current[key];
5572
- const currentLastCreatedId = current.lastCreatedId;
5506
+ const restored = {};
5507
+ for (const key of Object.keys(to)) {
5508
+ const changed = from[key] !== to[key];
5509
+ if (!KEPT_ON_UNDO_SET.has(key) && changed && scene.appState[key] === from[key]) Object.assign(restored, { [key]: to[key] });
5510
+ }
5511
+ const lastCreatedId = scene.appState.lastCreatedId;
5573
5512
  return {
5574
5513
  ...scene,
5575
5514
  selectedIds: new Set([...selectedIds].filter((id) => elementIds.has(id))),
5576
5515
  appState: {
5577
- ...appState,
5578
- ...kept,
5579
- lastCreatedId: currentLastCreatedId && elementIds.has(currentLastCreatedId) ? currentLastCreatedId : null
5516
+ ...scene.appState,
5517
+ ...restored,
5518
+ lastCreatedId: lastCreatedId && elementIds.has(lastCreatedId) ? lastCreatedId : null
5580
5519
  }
5581
5520
  };
5582
5521
  }
@@ -5596,7 +5535,7 @@ var ELEMENT_TYPES = /* @__PURE__ */ new Set([
5596
5535
  "text",
5597
5536
  "image"
5598
5537
  ]);
5599
- var STROKE_STYLES$1 = /* @__PURE__ */ new Set([
5538
+ var STROKE_STYLES = /* @__PURE__ */ new Set([
5600
5539
  "solid",
5601
5540
  "dashed",
5602
5541
  "dotted"
@@ -5663,7 +5602,7 @@ function isPoint$1(value) {
5663
5602
  return Array.isArray(value) && value.length === 2 && isFiniteNumberInRange(value[0], -1e7, 1e7) && isFiniteNumberInRange(value[1], -1e7, 1e7);
5664
5603
  }
5665
5604
  function hasValidBaseFields(el) {
5666
- return isString$1(el.id, 128) && el.id.length > 0 && typeof el.type === "string" && ELEMENT_TYPES.has(el.type) && isFiniteNumberInRange(el.x, -1e7, 1e7) && isFiniteNumberInRange(el.y, -1e7, 1e7) && isCssColor(el.strokeColor) && isCssColor(el.fillColor) && isFiniteNumberInRange(el.strokeWidth, 0, 1e3) && isFiniteNumberInRange(el.opacity, 0, 1) && isFiniteNumberInRange(el.roughness, 0, 10) && isOptionalFiniteNumber(el.rotation, -Math.PI * 2, Math.PI * 2) && isOptionalEnum(el.strokeStyle, STROKE_STYLES$1) && isOptionalEnum(el.lineCap, LINE_CAPS) && isOptionalEnum(el.lineJoin, LINE_JOINS) && isOptionalFiniteNumber(el.shadowBlur, 0, 1e3) && isOptionalCssColor(el.shadowColor) && isOptionalFiniteNumber(el.shadowOffsetX) && isOptionalFiniteNumber(el.shadowOffsetY) && isOptionalBoolean(el.visible) && isOptionalString(el.layerName, 1e3) && isOptionalBoolean(el.locked) && isOptionalString(el.groupId, 128);
5605
+ return isString$1(el.id, 128) && el.id.length > 0 && typeof el.type === "string" && ELEMENT_TYPES.has(el.type) && isFiniteNumberInRange(el.x, -1e7, 1e7) && isFiniteNumberInRange(el.y, -1e7, 1e7) && isCssColor(el.strokeColor) && isCssColor(el.fillColor) && isFiniteNumberInRange(el.strokeWidth, 0, 1e3) && isFiniteNumberInRange(el.opacity, 0, 1) && isFiniteNumberInRange(el.roughness, 0, 10) && isOptionalFiniteNumber(el.rotation, -Math.PI * 2, Math.PI * 2) && isOptionalEnum(el.strokeStyle, STROKE_STYLES) && isOptionalEnum(el.lineCap, LINE_CAPS) && isOptionalEnum(el.lineJoin, LINE_JOINS) && isOptionalFiniteNumber(el.shadowBlur, 0, 1e3) && isOptionalCssColor(el.shadowColor) && isOptionalFiniteNumber(el.shadowOffsetX) && isOptionalFiniteNumber(el.shadowOffsetY) && isOptionalBoolean(el.visible) && isOptionalString(el.layerName, 1e3) && isOptionalBoolean(el.locked) && isOptionalString(el.groupId, 128);
5667
5606
  }
5668
5607
  function hasBoxFields(el) {
5669
5608
  return isFiniteNumberInRange(el.width, -1e7, 1e7) && isFiniteNumberInRange(el.height, -1e7, 1e7);
@@ -6597,11 +6536,6 @@ function isElementList(value) {
6597
6536
  function isListOf(value, check) {
6598
6537
  return Array.isArray(value) && value.length <= 5e3 && value.every((item) => isRecord(item) && check(item));
6599
6538
  }
6600
- var STROKE_STYLES = /* @__PURE__ */ new Set([
6601
- "solid",
6602
- "dashed",
6603
- "dotted"
6604
- ]);
6605
6539
  var TEXT_MODES = /* @__PURE__ */ new Set(["text", "code"]);
6606
6540
  var STYLE_STRINGS = [
6607
6541
  "strokeColor",
@@ -6659,10 +6593,7 @@ var CHECKS = {
6659
6593
  SET_FONT_FAMILY: (c) => isString(c.family) && optionalIdList(c.ids),
6660
6594
  SET_FONT_SIZE: (c) => isNumber(c.size) && optionalIdList(c.ids) && optional((bounds) => isListOf(bounds, (box) => isId(box.id) && isNumber(box.width) && isNumber(box.height)))(c.bounds) && optionalNumber(c.width) && optionalNumber(c.height),
6661
6595
  SET_ROTATION: (c) => isId(c.id) && isNumber(c.rotation),
6662
- SET_STROKE_STYLE: (c) => STROKE_STYLES.has(c.style),
6663
6596
  REORDER_ELEMENTS: (c) => isIdList(c.ids) && isNumber(c.targetIndex),
6664
- TOGGLE_ELEMENT_VISIBILITY: (c) => isId(c.id),
6665
- RENAME_LAYER: (c) => isId(c.id) && isString(c.name),
6666
6597
  LOAD_SCENE: (c) => isElementList(c.elements) && validateViewport(c.viewport) !== null,
6667
6598
  GROUP_ELEMENTS: (c) => isIdList(c.ids) && isId(c.groupId),
6668
6599
  UNGROUP_ELEMENTS: (c) => isId(c.groupId),
@@ -6705,10 +6636,18 @@ var LiveOutbox = class {
6705
6636
  return this.queue.length > 0;
6706
6637
  }
6707
6638
  push(command) {
6708
- const last = this.queue.at(-1);
6709
- const merged = last ? mergeCommands(last, command) : null;
6710
- if (merged) this.queue[this.queue.length - 1] = merged;
6711
- else this.queue.push(command);
6639
+ let merged = false;
6640
+ for (let i = this.queue.length - 1; i >= 0; i--) {
6641
+ const waiting = this.queue[i];
6642
+ const combined = mergeCommands(waiting, command);
6643
+ if (combined) {
6644
+ this.queue[i] = combined;
6645
+ merged = true;
6646
+ break;
6647
+ }
6648
+ if (!independent(waiting, command)) break;
6649
+ }
6650
+ if (!merged) this.queue.push(command);
6712
6651
  if (this.timer === null) this.flush();
6713
6652
  }
6714
6653
  /** Sends what the quota allows now, and schedules the rest. */
@@ -6740,6 +6679,15 @@ var LiveOutbox = class {
6740
6679
  this.flush();
6741
6680
  this.clear();
6742
6681
  }
6682
+ /**
6683
+ * Resolves once everything waiting has been sent, or after `timeoutMs`:
6684
+ * for a leave that can wait, so an editing burst held back by the quota
6685
+ * still reaches the room.
6686
+ */
6687
+ async idle(timeoutMs) {
6688
+ const deadline = Date.now() + timeoutMs;
6689
+ while (this.pending && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, this.intervalMs));
6690
+ }
6743
6691
  /** Drops what is waiting, e.g. when the connection is gone. */
6744
6692
  clear() {
6745
6693
  if (this.timer !== null) clearTimeout(this.timer);
@@ -6780,6 +6728,25 @@ function mergeCommands(last, next) {
6780
6728
  if (last.type === "SET_ROTATION" && next.type === "SET_ROTATION") return last.id === next.id ? next : null;
6781
6729
  return null;
6782
6730
  }
6731
+ /** The elements a gesture command acts on, or null for any other command. */
6732
+ function gestureTargets(command) {
6733
+ switch (command.type) {
6734
+ case "MOVE_ELEMENT":
6735
+ case "RESIZE_ELEMENT":
6736
+ case "SET_ROTATION": return [command.id];
6737
+ case "MOVE_ELEMENTS": return command.ids;
6738
+ default: return null;
6739
+ }
6740
+ }
6741
+ /**
6742
+ * Whether two gesture commands act on separate elements, so their order
6743
+ * does not matter. Anything else may depend on what came before it.
6744
+ */
6745
+ function independent(a, b) {
6746
+ const ta = gestureTargets(a);
6747
+ const tb = gestureTargets(b);
6748
+ return !!ta && !!tb && !ta.some((id) => tb.includes(id));
6749
+ }
6783
6750
  /** Elements per CREATE_ELEMENTS, well under the validation limit (5,000). */
6784
6751
  var PIECE_ELEMENTS = 1e3;
6785
6752
  /** Size of one CREATE_ELEMENTS, under the room's message limit (512 KB). */
@@ -6965,6 +6932,13 @@ function randomClientId() {
6965
6932
  const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(24));
6966
6933
  return Array.from(bytes, (b) => alphabet[b % 62]).join("");
6967
6934
  }
6935
+ /** What each refusal reason of the room means, for the model. */
6936
+ var REJECTION_TEXT = {
6937
+ too_large: "one edit was too large for a single message, usually a large image",
6938
+ rate: "too many edits in a short time",
6939
+ full: "the room reached its size limit",
6940
+ invalid: "an edit could not be applied"
6941
+ };
6968
6942
  var LiveLink = class LiveLink {
6969
6943
  diagram;
6970
6944
  name;
@@ -7000,6 +6974,30 @@ var LiveLink = class LiveLink {
7000
6974
  get otherPeers() {
7001
6975
  return this.peers.filter((p) => p.id !== this.selfId);
7002
6976
  }
6977
+ /** Edits handed to the room so far, sent or waiting (see guarded in server.ts). */
6978
+ editCount = 0;
6979
+ /** Reasons the room gave for refusing edits since the last answer. */
6980
+ rejections = [];
6981
+ /**
6982
+ * Why the room refused some of the agent's edits since the last call, as
6983
+ * a note for the model: the board it sees here then differs from the
6984
+ * room's. Empty when nothing was refused.
6985
+ */
6986
+ takeRejections() {
6987
+ if (this.rejections.length === 0) return "";
6988
+ const reasons = this.rejections.map((reason) => REJECTION_TEXT[reason] ?? reason);
6989
+ this.rejections = [];
6990
+ return `The live room refused some of your edits (${reasons.join("; ")}): the other people do not see them.`;
6991
+ }
6992
+ /**
6993
+ * Resolves once the edits held back by the room's quota are sent (at
6994
+ * most `timeoutMs`), then after `graceMs` more, so a refusal of the last
6995
+ * ones has time to arrive.
6996
+ */
6997
+ async settle(timeoutMs, graceMs) {
6998
+ await this.outbox.idle(timeoutMs);
6999
+ await new Promise((resolve) => setTimeout(resolve, graceMs));
7000
+ }
7003
7001
  /** Requests received and not yet handed to the model. */
7004
7002
  get pendingRequests() {
7005
7003
  return this.inbox.length;
@@ -7073,6 +7071,11 @@ var LiveLink = class LiveLink {
7073
7071
  type: "command",
7074
7072
  command
7075
7073
  }) });
7074
+ /** Queues a scene command for the room, counting it (see editCount). */
7075
+ publish(command) {
7076
+ this.editCount++;
7077
+ this.outbox.push(command);
7078
+ }
7076
7079
  send(message) {
7077
7080
  if (this.socket?.readyState === WebSocket.OPEN) this.socket.send(JSON.stringify(message));
7078
7081
  }
@@ -7116,11 +7119,11 @@ var LiveLink = class LiveLink {
7116
7119
  discarded = local.length;
7117
7120
  history.resetForLiveReplay(msg.commands.filter(isValidSessionCommand));
7118
7121
  } else if (local.length > 0) {
7119
- for (const command of createCommands(local, { validOnly: true })) this.outbox.push(command);
7122
+ for (const command of createCommands(local, { validOnly: true })) this.publish(command);
7120
7123
  seeded = true;
7121
7124
  }
7122
7125
  history.setOnCommand((command) => {
7123
- if (this.open && isSessionCommand(command)) this.outbox.push(command);
7126
+ if (this.open && isSessionCommand(command)) this.publish(command);
7124
7127
  });
7125
7128
  this.open = true;
7126
7129
  resolve({
@@ -7135,7 +7138,9 @@ var LiveLink = class LiveLink {
7135
7138
  }
7136
7139
  } else if (msg.type === "presence") this.peers = msg.peers;
7137
7140
  else if (msg.type === "request") this.receiveRequest(msg);
7138
- else if (msg.type === "error" && !this.open) {
7141
+ else if (msg.type === "rejected" && typeof msg.reason === "string") {
7142
+ if (!this.rejections.includes(msg.reason)) this.rejections.push(msg.reason);
7143
+ } else if (msg.type === "error" && !this.open) {
7139
7144
  clearTimeout(timer);
7140
7145
  reject(new LiveError(msg.error === "licence required" ? licenceMessage(origin) : `The live room refused to join: ${msg.error}.`));
7141
7146
  }
@@ -7174,6 +7179,26 @@ var LiveLink = class LiveLink {
7174
7179
  this.socket?.close();
7175
7180
  this.socket = null;
7176
7181
  }
7182
+ /**
7183
+ * Leaves once every edit held back by the room's quota is sent, then
7184
+ * waits for the socket to close (at most `timeoutMs`), so the last edits
7185
+ * leave the process before it exits. A lost connection clears the queue,
7186
+ * which ends the wait; the 60 s cap (twelve quota windows, about 1,800
7187
+ * unmerged commands) only bounds a pathological burst.
7188
+ */
7189
+ async leaveAndWait(timeoutMs = 1e3) {
7190
+ await this.outbox.idle(6e4);
7191
+ const socket = this.socket;
7192
+ const closed = socket && socket.readyState !== 3 ? new Promise((resolve) => {
7193
+ const timer = setTimeout(resolve, timeoutMs);
7194
+ socket.addEventListener("close", () => {
7195
+ clearTimeout(timer);
7196
+ resolve();
7197
+ });
7198
+ }) : Promise.resolve();
7199
+ this.leave();
7200
+ await closed;
7201
+ }
7177
7202
  };
7178
7203
  //#endregion
7179
7204
  //#region src/warnings.ts
@@ -7536,9 +7561,44 @@ function formatRequests(requests) {
7536
7561
  ...lines
7537
7562
  ].join("\n");
7538
7563
  }
7564
+ /**
7565
+ * How long an answer waits for the room to refuse the edits it sent, after
7566
+ * the ones held back by the quota go out (at most QUEUE_WAIT_MS, a bit over
7567
+ * one quota window).
7568
+ */
7569
+ var REFUSAL_WAIT_MS = 250;
7570
+ var QUEUE_WAIT_MS = 6e3;
7571
+ /** Tool calls still running; shutting down waits for them. */
7572
+ var inFlight = 0;
7573
+ var onIdle = [];
7574
+ /** Counts a tool call while it runs (see shutDown). */
7575
+ function tracked(run) {
7576
+ return async (args) => {
7577
+ inFlight++;
7578
+ try {
7579
+ return await run(args);
7580
+ } finally {
7581
+ inFlight--;
7582
+ if (inFlight === 0) for (const resolve of onIdle.splice(0)) resolve();
7583
+ }
7584
+ };
7585
+ }
7586
+ /** Resolves when no tool call is running, or after `timeoutMs`. */
7587
+ function callsDone(timeoutMs) {
7588
+ if (inFlight === 0) return Promise.resolve();
7589
+ return new Promise((resolve) => {
7590
+ const timer = setTimeout(resolve, timeoutMs);
7591
+ onIdle.push(() => {
7592
+ clearTimeout(timer);
7593
+ resolve();
7594
+ });
7595
+ });
7596
+ }
7539
7597
  /** Runs a tool body and turns thrown errors into MCP tool errors. */
7540
7598
  function guarded(run) {
7541
- return async (args) => {
7599
+ return tracked(async (args) => {
7600
+ const before = live;
7601
+ const editsBefore = before?.editCount ?? 0;
7542
7602
  let result;
7543
7603
  try {
7544
7604
  result = text(await run(args));
@@ -7546,12 +7606,13 @@ function guarded(run) {
7546
7606
  result = failure(error);
7547
7607
  }
7548
7608
  const requests = live?.pendingRequests ? live.takeRequests() : [];
7549
- if (requests.length > 0) {
7550
- const first = result.content[0];
7551
- if (first) first.text += `\n${formatRequests(requests)}`;
7552
- }
7609
+ const first = result.content[0];
7610
+ if (requests.length > 0 && first) first.text += `\n${formatRequests(requests)}`;
7611
+ if (live && live.editCount > (live === before ? editsBefore : 0)) await live.settle(QUEUE_WAIT_MS, REFUSAL_WAIT_MS);
7612
+ const refused = [before, live !== before ? live : null].map((link) => link?.takeRejections() ?? "").filter(Boolean);
7613
+ if (refused.length > 0 && first) first.text += `\n${refused.join("\n")}`;
7553
7614
  return result;
7554
- };
7615
+ });
7555
7616
  }
7556
7617
  function liveSuffix() {
7557
7618
  if (!live) return "";
@@ -7749,13 +7810,13 @@ server.registerTool("diagram_export_png", {
7749
7810
  returnImage: z.boolean().optional().describe("Return the image (default true). false with a path only writes the file and answers in text.")
7750
7811
  },
7751
7812
  annotations: { readOnlyHint: true }
7752
- }, async (args) => {
7813
+ }, tracked(async (args) => {
7753
7814
  try {
7754
7815
  return { content: await exportPng(diagram, args) };
7755
7816
  } catch (error) {
7756
7817
  return failure(error);
7757
7818
  }
7758
- });
7819
+ }));
7759
7820
  server.registerTool("diagram_share", {
7760
7821
  title: "Share link",
7761
7822
  description: "Publish the diagram and return a markasso.it link anyone can open. The answer says when the link expires.",
@@ -7820,5 +7881,26 @@ server.registerTool("live_reply", {
7820
7881
  return "Reply sent.";
7821
7882
  }));
7822
7883
  await server.connect(new StdioServerTransport());
7884
+ /**
7885
+ * The client ends the session by closing stdin; the stdio transport does not
7886
+ * notice, and an open live socket would keep the process running as a ghost
7887
+ * peer in the room. Let running tool calls finish (a file being saved, an
7888
+ * answer being written), leave the room, then exit. Signals end it the same
7889
+ * way.
7890
+ */
7891
+ var shuttingDown = false;
7892
+ async function shutDown() {
7893
+ if (shuttingDown) return;
7894
+ shuttingDown = true;
7895
+ try {
7896
+ await callsDone(1e4);
7897
+ await live?.leaveAndWait();
7898
+ } finally {
7899
+ process.exit(0);
7900
+ }
7901
+ }
7902
+ process.stdin.on("end", () => void shutDown());
7903
+ process.stdin.on("close", () => void shutDown());
7904
+ for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => void shutDown());
7823
7905
  //#endregion
7824
7906
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@markasso/mcp",
3
- "version": "0.7.2",
3
+ "version": "0.7.4",
4
4
  "description": "MCP server that lets AI agents create, read and edit Markasso diagrams, offline or live on a shared board",
5
5
  "type": "module",
6
6
  "repository": {
@@ -34,7 +34,7 @@
34
34
  "typecheck": "tsc -p tsconfig.json"
35
35
  },
36
36
  "dependencies": {
37
- "@modelcontextprotocol/sdk": "^1.32.1",
37
+ "@modelcontextprotocol/sdk": "^1.32.2",
38
38
  "@resvg/resvg-js": "^2.6.2",
39
39
  "zod": "^4.6.7"
40
40
  },