@pixerate/editor 0.52.0 → 0.54.0

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 (142) hide show
  1. package/dist/agent/index.cjs +37 -29
  2. package/dist/agent/index.cjs.map +1 -1
  3. package/dist/agent/index.d.cts +4 -3
  4. package/dist/agent/index.d.ts +4 -3
  5. package/dist/agent/index.js +16 -8
  6. package/dist/agent/index.js.map +1 -1
  7. package/dist/animation/index.cjs +15 -1
  8. package/dist/animation/index.cjs.map +1 -1
  9. package/dist/animation/index.d.cts +3 -226
  10. package/dist/animation/index.d.ts +3 -226
  11. package/dist/animation/index.js +14 -0
  12. package/dist/bridge/cli.cjs +36 -0
  13. package/dist/bridge/cli.cjs.map +1 -0
  14. package/dist/bridge/cli.d.cts +1 -0
  15. package/dist/bridge/cli.d.ts +1 -0
  16. package/dist/bridge/cli.js +36 -0
  17. package/dist/bridge/cli.js.map +1 -0
  18. package/dist/bridge/index.cjs +16 -0
  19. package/dist/bridge/index.cjs.map +1 -0
  20. package/dist/bridge/index.d.cts +65 -0
  21. package/dist/bridge/index.d.ts +65 -0
  22. package/dist/bridge/index.js +16 -0
  23. package/dist/bridge/index.js.map +1 -0
  24. package/dist/bridge-client-C5OziCRK.d.cts +148 -0
  25. package/dist/bridge-client-C5dRjrz5.d.ts +148 -0
  26. package/dist/canvas/index.cjs +1308 -528
  27. package/dist/canvas/index.cjs.map +1 -1
  28. package/dist/canvas/index.d.cts +309 -5
  29. package/dist/canvas/index.d.ts +309 -5
  30. package/dist/canvas/index.js +1295 -515
  31. package/dist/canvas/index.js.map +1 -1
  32. package/dist/chart/index.cjs +193 -192
  33. package/dist/chart/index.cjs.map +1 -1
  34. package/dist/chart/index.d.cts +77 -59
  35. package/dist/chart/index.d.ts +77 -59
  36. package/dist/chart/index.js +87 -86
  37. package/dist/chart/index.js.map +1 -1
  38. package/dist/{chunk-UAW5FEMD.js → chunk-3S72F46R.js} +66 -8
  39. package/dist/chunk-3S72F46R.js.map +1 -0
  40. package/dist/{chunk-5TWIN7ZJ.js → chunk-47WWV3LI.js} +34 -4
  41. package/dist/chunk-47WWV3LI.js.map +1 -0
  42. package/dist/{chunk-OV7UAKIY.js → chunk-633QC34G.js} +172 -1
  43. package/dist/chunk-633QC34G.js.map +1 -0
  44. package/dist/chunk-AWKPSOSX.js +401 -0
  45. package/dist/chunk-AWKPSOSX.js.map +1 -0
  46. package/dist/chunk-B6DSIEXA.js +96 -0
  47. package/dist/chunk-B6DSIEXA.js.map +1 -0
  48. package/dist/{chunk-5N6AQCVB.js → chunk-BQQZ6MOI.js} +3 -3
  49. package/dist/{chunk-M5Z77GFH.cjs → chunk-C3JHII3M.cjs} +53 -53
  50. package/dist/{chunk-M5Z77GFH.cjs.map → chunk-C3JHII3M.cjs.map} +1 -1
  51. package/dist/{chunk-JOX6MJW4.cjs → chunk-CKRNELPO.cjs} +176 -5
  52. package/dist/chunk-CKRNELPO.cjs.map +1 -0
  53. package/dist/{chunk-TGBCBQFV.cjs → chunk-DK6QBGCS.cjs} +45 -15
  54. package/dist/chunk-DK6QBGCS.cjs.map +1 -0
  55. package/dist/chunk-EGFUVXKK.cjs +96 -0
  56. package/dist/chunk-EGFUVXKK.cjs.map +1 -0
  57. package/dist/{chunk-AMWXSYCI.js → chunk-GPWNYQ7R.js} +2 -370
  58. package/dist/chunk-GPWNYQ7R.js.map +1 -0
  59. package/dist/chunk-H5K77C7Y.cjs +3848 -0
  60. package/dist/chunk-H5K77C7Y.cjs.map +1 -0
  61. package/dist/chunk-K73CKYUM.cjs +458 -0
  62. package/dist/chunk-K73CKYUM.cjs.map +1 -0
  63. package/dist/{chunk-GTZXF4BI.cjs → chunk-NK3WL5TJ.cjs} +298 -133
  64. package/dist/chunk-NK3WL5TJ.cjs.map +1 -0
  65. package/dist/{chunk-3ZBAXET6.cjs → chunk-NN3JGUSX.cjs} +80 -22
  66. package/dist/chunk-NN3JGUSX.cjs.map +1 -0
  67. package/dist/chunk-NV22EMOZ.cjs +401 -0
  68. package/dist/chunk-NV22EMOZ.cjs.map +1 -0
  69. package/dist/{chunk-YMKPMXZ4.js → chunk-OIKYP7XC.js} +4 -4
  70. package/dist/{chunk-FEMIVHN3.cjs → chunk-P43HUQRX.cjs} +16 -16
  71. package/dist/{chunk-FEMIVHN3.cjs.map → chunk-P43HUQRX.cjs.map} +1 -1
  72. package/dist/chunk-PTMIGXZ2.js +467 -0
  73. package/dist/chunk-PTMIGXZ2.js.map +1 -0
  74. package/dist/chunk-QIWFEEWG.cjs +467 -0
  75. package/dist/chunk-QIWFEEWG.cjs.map +1 -0
  76. package/dist/{chunk-QFTVLEVN.js → chunk-RIXTW3C4.js} +3 -3
  77. package/dist/{chunk-WBOAXDKD.js → chunk-VODBAO32.js} +222 -57
  78. package/dist/chunk-VODBAO32.js.map +1 -0
  79. package/dist/chunk-WWJNC7SX.js +3848 -0
  80. package/dist/chunk-WWJNC7SX.js.map +1 -0
  81. package/dist/{chunk-2DEBI6KU.cjs → chunk-YZZMX6V7.cjs} +10 -10
  82. package/dist/{chunk-2DEBI6KU.cjs.map → chunk-YZZMX6V7.cjs.map} +1 -1
  83. package/dist/commands/index.d.cts +1 -1
  84. package/dist/commands/index.d.ts +1 -1
  85. package/dist/{controller-DS3drIvy.d.cts → controller-CX0QfSv0.d.cts} +53 -2
  86. package/dist/{controller-BdKzaxs2.d.ts → controller-DscWQbjO.d.ts} +53 -2
  87. package/dist/diagram/index.cjs +1146 -0
  88. package/dist/diagram/index.cjs.map +1 -0
  89. package/dist/diagram/index.d.cts +787 -0
  90. package/dist/diagram/index.d.ts +787 -0
  91. package/dist/diagram/index.js +1146 -0
  92. package/dist/diagram/index.js.map +1 -0
  93. package/dist/{easing-DTmX99QG.d.cts → easing-CNGk-W6d.d.cts} +1 -1
  94. package/dist/{easing-DTmX99QG.d.ts → easing-CNGk-W6d.d.ts} +1 -1
  95. package/dist/export/index.cjs +4 -4
  96. package/dist/export/index.js +3 -3
  97. package/dist/extensions/index.cjs +6 -6
  98. package/dist/extensions/index.d.cts +2 -2
  99. package/dist/extensions/index.d.ts +2 -2
  100. package/dist/extensions/index.js +5 -5
  101. package/dist/generation/index.d.cts +2 -2
  102. package/dist/generation/index.d.ts +2 -2
  103. package/dist/image-editor/index.d.cts +1 -1
  104. package/dist/image-editor/index.d.ts +1 -1
  105. package/dist/{index-Dt9lzydb.d.ts → index-CALDD35B.d.ts} +1 -1
  106. package/dist/{index-DOy9HzfC.d.cts → index-DIWB6xMf.d.cts} +1 -1
  107. package/dist/index.cjs +13 -13
  108. package/dist/index.d.cts +3 -3
  109. package/dist/index.d.ts +3 -3
  110. package/dist/index.js +6 -6
  111. package/dist/parameters/index.d.cts +1 -1
  112. package/dist/parameters/index.d.ts +1 -1
  113. package/dist/player-DSMjdgQ9.d.cts +225 -0
  114. package/dist/player-DdfVrKWq.d.ts +225 -0
  115. package/dist/presence-Cb6WhcrQ.d.cts +77 -0
  116. package/dist/presence-Cb6WhcrQ.d.ts +77 -0
  117. package/dist/{registry-CSlH4iUn.d.ts → registry-7AZFuand.d.ts} +1 -1
  118. package/dist/{registry-B4l-lYts.d.cts → registry-DIpIaCkH.d.cts} +1 -1
  119. package/dist/tools/index.cjs +10 -2
  120. package/dist/tools/index.cjs.map +1 -1
  121. package/dist/tools/index.d.cts +3 -74
  122. package/dist/tools/index.d.ts +3 -74
  123. package/dist/tools/index.js +12 -4
  124. package/dist/types-BULrFyuQ.d.cts +316 -0
  125. package/dist/types-BULrFyuQ.d.ts +316 -0
  126. package/dist/vector/index.d.cts +1 -1
  127. package/dist/vector/index.d.ts +1 -1
  128. package/package.json +14 -1
  129. package/dist/chunk-3ZBAXET6.cjs.map +0 -1
  130. package/dist/chunk-5TWIN7ZJ.js.map +0 -1
  131. package/dist/chunk-AMWXSYCI.js.map +0 -1
  132. package/dist/chunk-GTZXF4BI.cjs.map +0 -1
  133. package/dist/chunk-JOX6MJW4.cjs.map +0 -1
  134. package/dist/chunk-OV7UAKIY.js.map +0 -1
  135. package/dist/chunk-TGBCBQFV.cjs.map +0 -1
  136. package/dist/chunk-UAW5FEMD.js.map +0 -1
  137. package/dist/chunk-WBOAXDKD.js.map +0 -1
  138. package/dist/chunk-XFYUFVAX.cjs +0 -826
  139. package/dist/chunk-XFYUFVAX.cjs.map +0 -1
  140. /package/dist/{chunk-5N6AQCVB.js.map → chunk-BQQZ6MOI.js.map} +0 -0
  141. /package/dist/{chunk-YMKPMXZ4.js.map → chunk-OIKYP7XC.js.map} +0 -0
  142. /package/dist/{chunk-QFTVLEVN.js.map → chunk-RIXTW3C4.js.map} +0 -0
@@ -0,0 +1,467 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;
2
+
3
+ var _chunkRIWPYSKUcjs = require('./chunk-RIWPYSKU.cjs');
4
+
5
+ // src/tools/registry.ts
6
+ var ToolRegistryError = class extends Error {
7
+
8
+ constructor(code, message) {
9
+ super(message);
10
+ this.name = "ToolRegistryError";
11
+ this.code = code;
12
+ }
13
+ };
14
+ var TOOL_NAMESPACE_SEPARATOR = "__";
15
+ var TOOL_NAME_REGEX = /^[A-Za-z0-9_.-]{1,128}$/;
16
+ var sanitizeNamespace = (id) => id.replace(/[^A-Za-z0-9_-]/g, "_");
17
+ function readTools(provider) {
18
+ return typeof provider.tools === "function" ? provider.tools() : provider.tools;
19
+ }
20
+ function toDefinition(name, tool) {
21
+ const { handler: _handler, name: _name, ...rest } = tool;
22
+ return { name, ...rest };
23
+ }
24
+ function errorResult(error) {
25
+ const details = _optionalChain([error, 'access', _ => _.details, 'optionalAccess', _2 => _2.length]) ? "\n" + error.details.map((d) => `- ${d.path}: ${d.message}`).join("\n") : "";
26
+ return {
27
+ isError: true,
28
+ content: [{ type: "text", text: `${error.message}${details}` }],
29
+ structuredContent: { error }
30
+ };
31
+ }
32
+ function toToolResult(value) {
33
+ if (value && typeof value === "object" && Array.isArray(value.content)) {
34
+ return value;
35
+ }
36
+ if (value === void 0) return { content: [] };
37
+ if (typeof value === "string") return { content: [{ type: "text", text: value }] };
38
+ const text = JSON.stringify(value);
39
+ const isPlainObject = typeof value === "object" && value !== null && !Array.isArray(value);
40
+ return {
41
+ content: [{ type: "text", text: _nullishCoalesce(text, () => ( String(value))) }],
42
+ ...isPlainObject ? { structuredContent: value } : {}
43
+ };
44
+ }
45
+ var ToolRegistry = (_class = class {
46
+ /** MCP server capabilities this registry supports. */
47
+ __init() {this.capabilities = { tools: { listChanged: true } }}
48
+ __init2() {this.entries = []}
49
+ __init3() {this.listeners = /* @__PURE__ */ new Set()}
50
+
51
+ __init4() {this.timer = null}
52
+
53
+ constructor(options = {}) {;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this);_class.prototype.__init4.call(this);
54
+ this.options = {
55
+ onCollision: _nullishCoalesce(options.onCollision, () => ( "namespace")),
56
+ listChangedDelayMs: _nullishCoalesce(options.listChangedDelayMs, () => ( 0)),
57
+ validateArguments: _nullishCoalesce(options.validateArguments, () => ( true))
58
+ };
59
+ this.lastSignature = this.signature();
60
+ }
61
+ /**
62
+ * Registers a provider and returns a function that unregisters it.
63
+ * Throws a {@link ToolRegistryError} for a duplicate provider id, an invalid
64
+ * tool name, or (with `onCollision: 'error'`) a tool name collision.
65
+ */
66
+ register(provider) {
67
+ if (this.entries.some((e) => e.provider.id === provider.id)) {
68
+ throw new ToolRegistryError("duplicate_provider", `Tool provider "${provider.id}" is already registered.`);
69
+ }
70
+ for (const tool of readTools(provider)) {
71
+ if (!TOOL_NAME_REGEX.test(tool.name)) {
72
+ throw new ToolRegistryError("invalid_tool", `Invalid tool name "${tool.name}" from provider "${provider.id}".`);
73
+ }
74
+ }
75
+ const entry = { provider };
76
+ this.entries.push(entry);
77
+ try {
78
+ const names = this.resolve(this.options.onCollision === "error").map((t) => t.name);
79
+ const duplicate = names.find((name, i) => names.indexOf(name) !== i);
80
+ if (duplicate) {
81
+ throw new ToolRegistryError("name_collision", `Tool name "${duplicate}" is exposed more than once.`);
82
+ }
83
+ } catch (error) {
84
+ this.entries.pop();
85
+ throw error;
86
+ }
87
+ if (provider.subscribe) {
88
+ entry.unsubscribe = provider.subscribe(() => this.notifyListChanged());
89
+ }
90
+ this.notifyListChanged();
91
+ let registered = true;
92
+ return () => {
93
+ if (!registered) return;
94
+ registered = false;
95
+ this.unregister(provider);
96
+ };
97
+ }
98
+ /** Removes a provider by id or instance. Returns whether it was registered. */
99
+ unregister(providerOrId) {
100
+ const index = this.entries.findIndex(
101
+ (e) => typeof providerOrId === "string" ? e.provider.id === providerOrId : e.provider === providerOrId
102
+ );
103
+ if (index === -1) return false;
104
+ const [entry] = this.entries.splice(index, 1);
105
+ _optionalChain([entry, 'access', _3 => _3.unsubscribe, 'optionalCall', _4 => _4()]);
106
+ this.notifyListChanged();
107
+ return true;
108
+ }
109
+ /** Registered provider ids in registration order. */
110
+ providerIds() {
111
+ return this.entries.map((e) => e.provider.id);
112
+ }
113
+ /**
114
+ * Resolves exposed names. Tools are ordered by provider registration, then
115
+ * by their order within the provider.
116
+ */
117
+ resolve(throwOnCollision = false) {
118
+ const all = [];
119
+ const counts = /* @__PURE__ */ new Map();
120
+ for (const { provider } of this.entries) {
121
+ for (const tool of readTools(provider)) {
122
+ all.push({ name: tool.name, tool, provider });
123
+ if (!provider.namespace) counts.set(tool.name, (_nullishCoalesce(counts.get(tool.name), () => ( 0))) + 1);
124
+ }
125
+ }
126
+ for (const item of all) {
127
+ const prefix = _nullishCoalesce(item.provider.namespace, () => ( ((_nullishCoalesce(counts.get(item.name), () => ( 0))) > 1 ? item.provider.id : void 0)));
128
+ if (prefix !== void 0) {
129
+ if (throwOnCollision && !item.provider.namespace) {
130
+ throw new ToolRegistryError(
131
+ "name_collision",
132
+ `Tool "${item.name}" from provider "${item.provider.id}" collides with another provider's tool.`
133
+ );
134
+ }
135
+ item.name = `${sanitizeNamespace(prefix)}${TOOL_NAMESPACE_SEPARATOR}${item.name}`;
136
+ }
137
+ }
138
+ return all;
139
+ }
140
+ /** MCP `tools/list` result for the current providers. */
141
+ listTools() {
142
+ return { tools: this.resolve().map(({ name, tool }) => toDefinition(name, tool)) };
143
+ }
144
+ /** Whether a tool with this exposed name exists. */
145
+ hasTool(name) {
146
+ return this.resolve().some((t) => t.name === name);
147
+ }
148
+ /** Looks up a tool definition by exposed name. */
149
+ getTool(name) {
150
+ const found = this.resolve().find((t) => t.name === name);
151
+ return found ? toDefinition(found.name, found.tool) : void 0;
152
+ }
153
+ /**
154
+ * Calls a tool by exposed name and returns an MCP `tools/call` result.
155
+ * Never rejects: unknown tools, invalid arguments and handler errors come
156
+ * back as `isError: true` results with a {@link ToolCallError} in
157
+ * `structuredContent.error` (MCP transports may map `unknown_tool` to a
158
+ * JSON-RPC `-32602` error instead).
159
+ */
160
+ async callTool(name, args = {}, options = {}) {
161
+ const found = this.resolve().find((t) => t.name === name);
162
+ if (!found) {
163
+ return errorResult({ code: "unknown_tool", message: `Unknown tool "${name}".`, tool: name });
164
+ }
165
+ const input = _nullishCoalesce(args, () => ( {}));
166
+ if (this.options.validateArguments) {
167
+ const details = _chunkRIWPYSKUcjs.validateJsonSchema.call(void 0, input, found.tool.inputSchema);
168
+ if (details.length > 0) {
169
+ return errorResult({
170
+ code: "invalid_arguments",
171
+ message: `Invalid arguments for tool "${name}".`,
172
+ tool: name,
173
+ details
174
+ });
175
+ }
176
+ }
177
+ try {
178
+ const value = await found.tool.handler(input, {
179
+ name,
180
+ providerId: found.provider.id,
181
+ signal: options.signal
182
+ });
183
+ return toToolResult(value);
184
+ } catch (error) {
185
+ return errorResult({
186
+ code: "tool_failed",
187
+ message: error instanceof Error ? error.message : String(error),
188
+ tool: name
189
+ });
190
+ }
191
+ }
192
+ /**
193
+ * Subscribes to tool-list changes. Notifications are coalesced: many
194
+ * registrations or provider signals within the delay window produce one
195
+ * call, and none if the exposed list ends up unchanged (e.g. a provider
196
+ * unmounted and remounted). Returns an unsubscribe function.
197
+ */
198
+ onListChanged(listener) {
199
+ this.listeners.add(listener);
200
+ return () => {
201
+ this.listeners.delete(listener);
202
+ };
203
+ }
204
+ /** Schedules a coalesced `listChanged` check; providers may call it directly. */
205
+ notifyListChanged() {
206
+ if (this.timer !== null) return;
207
+ this.timer = setTimeout(() => this.flush(), this.options.listChangedDelayMs);
208
+ }
209
+ /** Runs a pending `listChanged` check immediately. */
210
+ flush() {
211
+ if (this.timer !== null) {
212
+ clearTimeout(this.timer);
213
+ this.timer = null;
214
+ }
215
+ const signature = this.signature();
216
+ if (signature === this.lastSignature) return;
217
+ this.lastSignature = signature;
218
+ const { tools } = this.listTools();
219
+ for (const listener of Array.from(this.listeners)) listener(tools);
220
+ }
221
+ signature() {
222
+ try {
223
+ return JSON.stringify(this.listTools().tools);
224
+ } catch (e2) {
225
+ return String(Math.random());
226
+ }
227
+ }
228
+ /** Unregisters every provider and listener and cancels pending notifications. */
229
+ dispose() {
230
+ if (this.timer !== null) clearTimeout(this.timer);
231
+ this.timer = null;
232
+ for (const entry of this.entries.splice(0)) _optionalChain([entry, 'access', _5 => _5.unsubscribe, 'optionalCall', _6 => _6()]);
233
+ this.listeners.clear();
234
+ }
235
+ }, _class);
236
+ function createToolRegistry(options) {
237
+ return new ToolRegistry(options);
238
+ }
239
+
240
+ // src/tools/mcp-server.ts
241
+ var MCP_PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];
242
+ var JSON_RPC_ERRORS = {
243
+ parseError: -32700,
244
+ invalidRequest: -32600,
245
+ methodNotFound: -32601,
246
+ invalidParams: -32602,
247
+ internalError: -32603
248
+ };
249
+ var errorResponse = (id, code, message, data) => ({
250
+ jsonrpc: "2.0",
251
+ id,
252
+ error: { code, message, ...data !== void 0 ? { data } : {} }
253
+ });
254
+ function createMcpServer(registry, options) {
255
+ let initialized = false;
256
+ let unsubscribe = null;
257
+ const running = /* @__PURE__ */ new Map();
258
+ const startNotifications = () => {
259
+ if (unsubscribe || !options.send) return;
260
+ const send = options.send;
261
+ unsubscribe = registry.onListChanged(() => send({ jsonrpc: "2.0", method: "notifications/tools/list_changed" }));
262
+ };
263
+ async function dispatch(request) {
264
+ const id = _nullishCoalesce(request.id, () => ( null));
265
+ const isNotification = request.id === void 0 || request.id === null;
266
+ const params = _nullishCoalesce(request.params, () => ( {}));
267
+ switch (request.method) {
268
+ case "initialize": {
269
+ const requested = String(_nullishCoalesce(params.protocolVersion, () => ( "")));
270
+ const protocolVersion = MCP_PROTOCOL_VERSIONS.includes(requested) ? requested : MCP_PROTOCOL_VERSIONS[0];
271
+ return {
272
+ jsonrpc: "2.0",
273
+ id,
274
+ result: {
275
+ protocolVersion,
276
+ capabilities: registry.capabilities,
277
+ serverInfo: { name: options.name, version: options.version, ...options.title ? { title: options.title } : {} },
278
+ ...options.instructions ? { instructions: options.instructions } : {}
279
+ }
280
+ };
281
+ }
282
+ case "notifications/initialized":
283
+ initialized = true;
284
+ startNotifications();
285
+ return null;
286
+ case "notifications/cancelled": {
287
+ const requestId = params.requestId;
288
+ if (requestId !== void 0) _optionalChain([running, 'access', _7 => _7.get, 'call', _8 => _8(requestId), 'optionalAccess', _9 => _9.abort, 'call', _10 => _10(params.reason)]);
289
+ return null;
290
+ }
291
+ case "ping":
292
+ return { jsonrpc: "2.0", id, result: {} };
293
+ case "tools/list":
294
+ return { jsonrpc: "2.0", id, result: registry.listTools() };
295
+ case "tools/call": {
296
+ const name = params.name;
297
+ if (typeof name !== "string") {
298
+ return errorResponse(id, JSON_RPC_ERRORS.invalidParams, 'tools/call needs a string "name".');
299
+ }
300
+ if (!registry.hasTool(name)) {
301
+ return errorResponse(id, JSON_RPC_ERRORS.invalidParams, `Unknown tool: ${name}`);
302
+ }
303
+ const args = params.arguments;
304
+ if (args !== void 0 && (typeof args !== "object" || args === null || Array.isArray(args))) {
305
+ return errorResponse(id, JSON_RPC_ERRORS.invalidParams, '"arguments" must be an object.');
306
+ }
307
+ const controller = new AbortController();
308
+ if (!isNotification) running.set(id, controller);
309
+ try {
310
+ const result = await registry.callTool(name, _nullishCoalesce(args, () => ( {})), { signal: controller.signal });
311
+ if (controller.signal.aborted) return null;
312
+ return { jsonrpc: "2.0", id, result };
313
+ } finally {
314
+ if (!isNotification) running.delete(id);
315
+ }
316
+ }
317
+ default:
318
+ if (isNotification) return null;
319
+ return errorResponse(id, JSON_RPC_ERRORS.methodNotFound, `Method not found: ${request.method}`);
320
+ }
321
+ }
322
+ return {
323
+ get initialized() {
324
+ return initialized;
325
+ },
326
+ async handle(message) {
327
+ let request;
328
+ if (typeof message === "string") {
329
+ try {
330
+ request = JSON.parse(message);
331
+ } catch (e3) {
332
+ return errorResponse(null, JSON_RPC_ERRORS.parseError, "Parse error.");
333
+ }
334
+ } else {
335
+ request = message;
336
+ }
337
+ if (!request || typeof request !== "object" || Array.isArray(request) || request.jsonrpc !== "2.0" || typeof request.method !== "string") {
338
+ const id = request && typeof request === "object" && !Array.isArray(request) ? _nullishCoalesce(request.id, () => ( null)) : null;
339
+ return errorResponse(id, JSON_RPC_ERRORS.invalidRequest, "Invalid JSON-RPC 2.0 request.");
340
+ }
341
+ try {
342
+ return await dispatch(request);
343
+ } catch (error) {
344
+ if (request.id === void 0 || request.id === null) return null;
345
+ return errorResponse(
346
+ request.id,
347
+ JSON_RPC_ERRORS.internalError,
348
+ error instanceof Error ? error.message : String(error)
349
+ );
350
+ }
351
+ },
352
+ close() {
353
+ _optionalChain([unsubscribe, 'optionalCall', _11 => _11()]);
354
+ unsubscribe = null;
355
+ for (const controller of running.values()) controller.abort("Server closed.");
356
+ running.clear();
357
+ }
358
+ };
359
+ }
360
+
361
+ // src/tools/bridge-client.ts
362
+ var TOOL_BRIDGE_PROTOCOL = 1;
363
+ var TOOL_BRIDGE_DEFAULT_PORT = 4477;
364
+ function connectToolBridge(registry, options) {
365
+ const Ctor = _nullishCoalesce(options.WebSocket, () => ( globalThis.WebSocket));
366
+ if (!Ctor) throw new Error("No WebSocket implementation: pass options.WebSocket.");
367
+ const base = _nullishCoalesce(options.url, () => ( `ws://127.0.0.1:${TOOL_BRIDGE_DEFAULT_PORT}`));
368
+ const url = options.token ? `${base}${base.includes("?") ? "&" : "?"}token=${encodeURIComponent(options.token)}` : base;
369
+ let status = "connecting";
370
+ let editorId = null;
371
+ let socket = null;
372
+ let closed = false;
373
+ let delay = 500;
374
+ let retry = null;
375
+ const running = /* @__PURE__ */ new Map();
376
+ const setStatus = (next, detail) => {
377
+ if (next === status && !detail) return;
378
+ status = next;
379
+ _optionalChain([options, 'access', _12 => _12.onStatus, 'optionalCall', _13 => _13(next, detail)]);
380
+ };
381
+ const send = (message) => {
382
+ if (socket && socket.readyState === 1) socket.send(JSON.stringify(message));
383
+ };
384
+ const unsubscribe = registry.onListChanged((tools) => send({ t: "tools", tools }));
385
+ const open = () => {
386
+ if (closed) return;
387
+ setStatus("connecting");
388
+ const ws = new Ctor(url);
389
+ socket = ws;
390
+ ws.addEventListener("open", () => {
391
+ delay = 500;
392
+ send({ t: "hello", v: TOOL_BRIDGE_PROTOCOL, name: options.name, ...options.kind ? { kind: options.kind } : {}, tools: registry.listTools().tools });
393
+ });
394
+ ws.addEventListener("message", (event) => {
395
+ let message;
396
+ try {
397
+ message = JSON.parse(String(event.data));
398
+ } catch (e4) {
399
+ return;
400
+ }
401
+ if (message.t === "welcome") {
402
+ editorId = message.id;
403
+ setStatus("connected");
404
+ } else if (message.t === "call") {
405
+ const controller = new AbortController();
406
+ running.set(message.id, controller);
407
+ void registry.callTool(message.name, _nullishCoalesce(message.arguments, () => ( {})), { signal: controller.signal }).then((result) => {
408
+ running.delete(message.id);
409
+ if (!controller.signal.aborted) send({ t: "result", id: message.id, result });
410
+ });
411
+ } else if (message.t === "cancel") {
412
+ _optionalChain([running, 'access', _14 => _14.get, 'call', _15 => _15(message.id), 'optionalAccess', _16 => _16.abort, 'call', _17 => _17(_nullishCoalesce(message.reason, () => ( "Cancelled by the agent.")))]);
413
+ running.delete(message.id);
414
+ }
415
+ });
416
+ ws.addEventListener("close", (event) => {
417
+ if (socket !== ws) return;
418
+ socket = null;
419
+ editorId = null;
420
+ for (const controller of running.values()) controller.abort("The bridge disconnected.");
421
+ running.clear();
422
+ if (closed) return setStatus("closed");
423
+ setStatus("disconnected", event.reason || void 0);
424
+ if (options.reconnect === false) return;
425
+ retry = setTimeout(open, delay);
426
+ delay = Math.min(1e4, delay * 2);
427
+ });
428
+ ws.addEventListener("error", () => {
429
+ });
430
+ };
431
+ open();
432
+ return {
433
+ get status() {
434
+ return status;
435
+ },
436
+ get editorId() {
437
+ return editorId;
438
+ },
439
+ close() {
440
+ if (closed) return;
441
+ closed = true;
442
+ if (retry) clearTimeout(retry);
443
+ unsubscribe();
444
+ for (const controller of running.values()) controller.abort("The editor disconnected.");
445
+ running.clear();
446
+ const ws = socket;
447
+ socket = null;
448
+ _optionalChain([ws, 'optionalAccess', _18 => _18.close, 'call', _19 => _19(1e3, "Editor closed.")]);
449
+ setStatus("closed");
450
+ }
451
+ };
452
+ }
453
+
454
+
455
+
456
+
457
+
458
+
459
+
460
+
461
+
462
+
463
+
464
+
465
+
466
+ exports.ToolRegistryError = ToolRegistryError; exports.TOOL_NAMESPACE_SEPARATOR = TOOL_NAMESPACE_SEPARATOR; exports.toToolResult = toToolResult; exports.ToolRegistry = ToolRegistry; exports.createToolRegistry = createToolRegistry; exports.MCP_PROTOCOL_VERSIONS = MCP_PROTOCOL_VERSIONS; exports.JSON_RPC_ERRORS = JSON_RPC_ERRORS; exports.createMcpServer = createMcpServer; exports.TOOL_BRIDGE_PROTOCOL = TOOL_BRIDGE_PROTOCOL; exports.TOOL_BRIDGE_DEFAULT_PORT = TOOL_BRIDGE_DEFAULT_PORT; exports.connectToolBridge = connectToolBridge;
467
+ //# sourceMappingURL=chunk-QIWFEEWG.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/editor/editor/packages/core/dist/chunk-QIWFEEWG.cjs","../src/tools/registry.ts","../src/tools/mcp-server.ts","../src/tools/bridge-client.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACA;AC8EO,IAAM,kBAAA,EAAN,MAAA,QAAgC,MAAM;AAAA,EACnC;AAAA,EAET,WAAA,CAAY,IAAA,EAAiC,OAAA,EAAiB;AAC7D,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,KAAA,EAAO,mBAAA;AACZ,IAAA,IAAA,CAAK,KAAA,EAAO,IAAA;AAAA,EACb;AACD,CAAA;AAgBO,IAAM,yBAAA,EAA2B,IAAA;AAExC,IAAM,gBAAA,EAAkB,yBAAA;AACxB,IAAM,kBAAA,EAAoB,CAAC,EAAA,EAAA,GAAe,EAAA,CAAG,OAAA,CAAQ,iBAAA,EAAmB,GAAG,CAAA;AAa3E,SAAS,SAAA,CAAU,QAAA,EAAmD;AACrE,EAAA,OAAO,OAAO,QAAA,CAAS,MAAA,IAAU,WAAA,EAAa,QAAA,CAAS,KAAA,CAAM,EAAA,EAAI,QAAA,CAAS,KAAA;AAC3E;AAEA,SAAS,YAAA,CAAa,IAAA,EAAc,IAAA,EAAoC;AACvE,EAAA,MAAM,EAAE,OAAA,EAAS,QAAA,EAAU,IAAA,EAAM,KAAA,EAAO,GAAG,KAAK,EAAA,EAAI,IAAA;AACpD,EAAA,OAAO,EAAE,IAAA,EAAM,GAAG,KAAK,CAAA;AACxB;AAEA,SAAS,WAAA,CAAY,KAAA,EAAqC;AACzD,EAAA,MAAM,QAAA,kBAAU,KAAA,mBAAM,OAAA,6BAAS,SAAA,E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D;AHwSoG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/editor/editor/packages/core/dist/chunk-QIWFEEWG.cjs","sourcesContent":[null,"import { validateJsonSchema, type JsonSchema, type SchemaValidationError } from './schema.js';\n\n/**\n * MCP-shaped tool definition, as returned by `tools/list`.\n */\nexport interface McpToolDefinition {\n\tname: string;\n\ttitle?: string;\n\tdescription?: string;\n\tinputSchema: JsonSchema & { type: 'object' };\n\toutputSchema?: JsonSchema;\n\tannotations?: {\n\t\ttitle?: string;\n\t\treadOnlyHint?: boolean;\n\t\tdestructiveHint?: boolean;\n\t\tidempotentHint?: boolean;\n\t\topenWorldHint?: boolean;\n\t\t[key: string]: unknown;\n\t};\n}\n\nexport type McpToolContent =\n\t| { type: 'text'; text: string }\n\t| { type: 'image'; data: string; mimeType: string }\n\t| { type: string; [key: string]: unknown };\n\n/** MCP `tools/call` result. */\nexport interface McpToolResult {\n\tcontent: McpToolContent[];\n\tstructuredContent?: Record<string, unknown>;\n\tisError?: boolean;\n}\n\n/** MCP `tools/list` result. */\nexport interface McpListToolsResult {\n\ttools: McpToolDefinition[];\n}\n\nexport interface ToolCallContext {\n\t/** Name the tool was called by (possibly namespaced). */\n\tname: string;\n\t/** Id of the provider that owns the tool. */\n\tproviderId: string;\n\tsignal?: AbortSignal;\n}\n\n/**\n * Handler return values are normalized into an {@link McpToolResult}: a full\n * result (`{ content: [...] }`) is passed through, a string becomes a text\n * block, `undefined` becomes an empty result, and anything else is returned\n * as `structuredContent` (plain objects) plus a JSON text block.\n */\nexport type AgentToolHandler = (args: Record<string, any>, context: ToolCallContext) => unknown | Promise<unknown>;\n\nexport interface AgentTool extends McpToolDefinition {\n\thandler: AgentToolHandler;\n}\n\n/**\n * A source of tools, typically one per mounted editor, spreadsheet or canvas.\n */\nexport interface AgentToolProvider {\n\t/** Unique id within a registry, e.g. `doc-1`. Used as the namespace on collisions. */\n\tid: string;\n\t/** Always prefix this provider's tools with `<namespace>__`. */\n\tnamespace?: string;\n\t/** Tools, or a function returning the current tools (re-read on every `listTools`). */\n\ttools: readonly AgentTool[] | (() => readonly AgentTool[]);\n\t/** Lets the provider signal that its tool list changed; returns an unsubscribe function. */\n\tsubscribe?: (notify: () => void) => () => void;\n}\n\nexport type ToolErrorCode = 'unknown_tool' | 'invalid_arguments' | 'tool_failed';\n\n/** Structured error carried in `structuredContent.error` of a failed call. */\nexport interface ToolCallError {\n\tcode: ToolErrorCode;\n\tmessage: string;\n\ttool: string;\n\tdetails?: SchemaValidationError[];\n}\n\nexport class ToolRegistryError extends Error {\n\treadonly code: 'duplicate_provider' | 'name_collision' | 'invalid_tool';\n\n\tconstructor(code: ToolRegistryError['code'], message: string) {\n\t\tsuper(message);\n\t\tthis.name = 'ToolRegistryError';\n\t\tthis.code = code;\n\t}\n}\n\nexport interface ToolRegistryOptions {\n\t/**\n\t * What to do when two providers contribute the same tool name:\n\t * `namespace` (default) exposes every colliding tool as `<providerId>__<name>`;\n\t * `error` makes `register` throw.\n\t */\n\tonCollision?: 'namespace' | 'error';\n\t/** Coalescing window for `listChanged` notifications in ms (default 0: same tick). */\n\tlistChangedDelayMs?: number;\n\t/** Validate arguments against `inputSchema` before calling handlers (default `true`). */\n\tvalidateArguments?: boolean;\n}\n\n/** Separator between namespace and tool name; valid in MCP and LLM tool-name charsets. */\nexport const TOOL_NAMESPACE_SEPARATOR = '__';\n\nconst TOOL_NAME_REGEX = /^[A-Za-z0-9_.-]{1,128}$/;\nconst sanitizeNamespace = (id: string) => id.replace(/[^A-Za-z0-9_-]/g, '_');\n\ninterface ResolvedTool {\n\tname: string;\n\ttool: AgentTool;\n\tprovider: AgentToolProvider;\n}\n\ninterface ProviderEntry {\n\tprovider: AgentToolProvider;\n\tunsubscribe?: () => void;\n}\n\nfunction readTools(provider: AgentToolProvider): readonly AgentTool[] {\n\treturn typeof provider.tools === 'function' ? provider.tools() : provider.tools;\n}\n\nfunction toDefinition(name: string, tool: AgentTool): McpToolDefinition {\n\tconst { handler: _handler, name: _name, ...rest } = tool;\n\treturn { name, ...rest };\n}\n\nfunction errorResult(error: ToolCallError): McpToolResult {\n\tconst details = error.details?.length\n\t\t? '\\n' + error.details.map((d) => `- ${d.path}: ${d.message}`).join('\\n')\n\t\t: '';\n\treturn {\n\t\tisError: true,\n\t\tcontent: [{ type: 'text', text: `${error.message}${details}` }],\n\t\tstructuredContent: { error: error as unknown as Record<string, unknown> }\n\t};\n}\n\n/** Normalizes a handler's return value into an MCP `tools/call` result. */\nexport function toToolResult(value: unknown): McpToolResult {\n\tif (\n\t\tvalue &&\n\t\ttypeof value === 'object' &&\n\t\tArray.isArray((value as McpToolResult).content)\n\t) {\n\t\treturn value as McpToolResult;\n\t}\n\tif (value === undefined) return { content: [] };\n\tif (typeof value === 'string') return { content: [{ type: 'text', text: value }] };\n\tconst text = JSON.stringify(value);\n\tconst isPlainObject = typeof value === 'object' && value !== null && !Array.isArray(value);\n\treturn {\n\t\tcontent: [{ type: 'text', text: text ?? String(value) }],\n\t\t...(isPlainObject ? { structuredContent: value as Record<string, unknown> } : {})\n\t};\n}\n\n/**\n * Transport-agnostic registry of agent tools contributed by live providers.\n *\n * `listTools()` and `callTool()` return MCP `tools/list` / `tools/call`\n * result shapes, and `onListChanged` fires (coalesced) whenever the exposed\n * tool list changes, mirroring MCP's `notifications/tools/list_changed`, so an\n * MCP server can be a thin wrapper around it.\n */\nexport class ToolRegistry {\n\t/** MCP server capabilities this registry supports. */\n\treadonly capabilities = { tools: { listChanged: true } } as const;\n\n\tprivate readonly entries: ProviderEntry[] = [];\n\tprivate readonly listeners = new Set<(tools: McpToolDefinition[]) => void>();\n\tprivate readonly options: Required<ToolRegistryOptions>;\n\tprivate timer: ReturnType<typeof setTimeout> | null = null;\n\tprivate lastSignature: string;\n\n\tconstructor(options: ToolRegistryOptions = {}) {\n\t\tthis.options = {\n\t\t\tonCollision: options.onCollision ?? 'namespace',\n\t\t\tlistChangedDelayMs: options.listChangedDelayMs ?? 0,\n\t\t\tvalidateArguments: options.validateArguments ?? true\n\t\t};\n\t\tthis.lastSignature = this.signature();\n\t}\n\n\t/**\n\t * Registers a provider and returns a function that unregisters it.\n\t * Throws a {@link ToolRegistryError} for a duplicate provider id, an invalid\n\t * tool name, or (with `onCollision: 'error'`) a tool name collision.\n\t */\n\tregister(provider: AgentToolProvider): () => void {\n\t\tif (this.entries.some((e) => e.provider.id === provider.id)) {\n\t\t\tthrow new ToolRegistryError('duplicate_provider', `Tool provider \"${provider.id}\" is already registered.`);\n\t\t}\n\t\tfor (const tool of readTools(provider)) {\n\t\t\tif (!TOOL_NAME_REGEX.test(tool.name)) {\n\t\t\t\tthrow new ToolRegistryError('invalid_tool', `Invalid tool name \"${tool.name}\" from provider \"${provider.id}\".`);\n\t\t\t}\n\t\t}\n\t\tconst entry: ProviderEntry = { provider };\n\t\tthis.entries.push(entry);\n\t\ttry {\n\t\t\tconst names = this.resolve(this.options.onCollision === 'error').map((t) => t.name);\n\t\t\tconst duplicate = names.find((name, i) => names.indexOf(name) !== i);\n\t\t\tif (duplicate) {\n\t\t\t\t// Only possible with explicit namespaces (or duplicate names within one provider).\n\t\t\t\tthrow new ToolRegistryError('name_collision', `Tool name \"${duplicate}\" is exposed more than once.`);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.entries.pop();\n\t\t\tthrow error;\n\t\t}\n\t\tif (provider.subscribe) {\n\t\t\tentry.unsubscribe = provider.subscribe(() => this.notifyListChanged());\n\t\t}\n\t\tthis.notifyListChanged();\n\t\tlet registered = true;\n\t\treturn () => {\n\t\t\tif (!registered) return;\n\t\t\tregistered = false;\n\t\t\tthis.unregister(provider);\n\t\t};\n\t}\n\n\t/** Removes a provider by id or instance. Returns whether it was registered. */\n\tunregister(providerOrId: string | AgentToolProvider): boolean {\n\t\tconst index = this.entries.findIndex((e) =>\n\t\t\ttypeof providerOrId === 'string' ? e.provider.id === providerOrId : e.provider === providerOrId\n\t\t);\n\t\tif (index === -1) return false;\n\t\tconst [entry] = this.entries.splice(index, 1);\n\t\tentry.unsubscribe?.();\n\t\tthis.notifyListChanged();\n\t\treturn true;\n\t}\n\n\t/** Registered provider ids in registration order. */\n\tproviderIds(): string[] {\n\t\treturn this.entries.map((e) => e.provider.id);\n\t}\n\n\t/**\n\t * Resolves exposed names. Tools are ordered by provider registration, then\n\t * by their order within the provider.\n\t */\n\tprivate resolve(throwOnCollision = false): ResolvedTool[] {\n\t\tconst all: ResolvedTool[] = [];\n\t\tconst counts = new Map<string, number>();\n\t\tfor (const { provider } of this.entries) {\n\t\t\tfor (const tool of readTools(provider)) {\n\t\t\t\tall.push({ name: tool.name, tool, provider });\n\t\t\t\tif (!provider.namespace) counts.set(tool.name, (counts.get(tool.name) ?? 0) + 1);\n\t\t\t}\n\t\t}\n\t\tfor (const item of all) {\n\t\t\tconst prefix = item.provider.namespace ?? ((counts.get(item.name) ?? 0) > 1 ? item.provider.id : undefined);\n\t\t\tif (prefix !== undefined) {\n\t\t\t\tif (throwOnCollision && !item.provider.namespace) {\n\t\t\t\t\tthrow new ToolRegistryError(\n\t\t\t\t\t\t'name_collision',\n\t\t\t\t\t\t`Tool \"${item.name}\" from provider \"${item.provider.id}\" collides with another provider's tool.`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\titem.name = `${sanitizeNamespace(prefix)}${TOOL_NAMESPACE_SEPARATOR}${item.name}`;\n\t\t\t}\n\t\t}\n\t\treturn all;\n\t}\n\n\t/** MCP `tools/list` result for the current providers. */\n\tlistTools(): McpListToolsResult {\n\t\treturn { tools: this.resolve().map(({ name, tool }) => toDefinition(name, tool)) };\n\t}\n\n\t/** Whether a tool with this exposed name exists. */\n\thasTool(name: string): boolean {\n\t\treturn this.resolve().some((t) => t.name === name);\n\t}\n\n\t/** Looks up a tool definition by exposed name. */\n\tgetTool(name: string): McpToolDefinition | undefined {\n\t\tconst found = this.resolve().find((t) => t.name === name);\n\t\treturn found ? toDefinition(found.name, found.tool) : undefined;\n\t}\n\n\t/**\n\t * Calls a tool by exposed name and returns an MCP `tools/call` result.\n\t * Never rejects: unknown tools, invalid arguments and handler errors come\n\t * back as `isError: true` results with a {@link ToolCallError} in\n\t * `structuredContent.error` (MCP transports may map `unknown_tool` to a\n\t * JSON-RPC `-32602` error instead).\n\t */\n\tasync callTool(name: string, args: Record<string, unknown> = {}, options: { signal?: AbortSignal } = {}): Promise<McpToolResult> {\n\t\tconst found = this.resolve().find((t) => t.name === name);\n\t\tif (!found) {\n\t\t\treturn errorResult({ code: 'unknown_tool', message: `Unknown tool \"${name}\".`, tool: name });\n\t\t}\n\t\tconst input = args ?? {};\n\t\tif (this.options.validateArguments) {\n\t\t\tconst details = validateJsonSchema(input, found.tool.inputSchema);\n\t\t\tif (details.length > 0) {\n\t\t\t\treturn errorResult({\n\t\t\t\t\tcode: 'invalid_arguments',\n\t\t\t\t\tmessage: `Invalid arguments for tool \"${name}\".`,\n\t\t\t\t\ttool: name,\n\t\t\t\t\tdetails\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tconst value = await found.tool.handler(input as Record<string, any>, {\n\t\t\t\tname,\n\t\t\t\tproviderId: found.provider.id,\n\t\t\t\tsignal: options.signal\n\t\t\t});\n\t\t\treturn toToolResult(value);\n\t\t} catch (error) {\n\t\t\treturn errorResult({\n\t\t\t\tcode: 'tool_failed',\n\t\t\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\t\t\ttool: name\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Subscribes to tool-list changes. Notifications are coalesced: many\n\t * registrations or provider signals within the delay window produce one\n\t * call, and none if the exposed list ends up unchanged (e.g. a provider\n\t * unmounted and remounted). Returns an unsubscribe function.\n\t */\n\tonListChanged(listener: (tools: McpToolDefinition[]) => void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\t/** Schedules a coalesced `listChanged` check; providers may call it directly. */\n\tnotifyListChanged(): void {\n\t\tif (this.timer !== null) return;\n\t\tthis.timer = setTimeout(() => this.flush(), this.options.listChangedDelayMs);\n\t}\n\n\t/** Runs a pending `listChanged` check immediately. */\n\tflush(): void {\n\t\tif (this.timer !== null) {\n\t\t\tclearTimeout(this.timer);\n\t\t\tthis.timer = null;\n\t\t}\n\t\tconst signature = this.signature();\n\t\tif (signature === this.lastSignature) return;\n\t\tthis.lastSignature = signature;\n\t\tconst { tools } = this.listTools();\n\t\tfor (const listener of Array.from(this.listeners)) listener(tools);\n\t}\n\n\tprivate signature(): string {\n\t\ttry {\n\t\t\treturn JSON.stringify(this.listTools().tools);\n\t\t} catch {\n\t\t\treturn String(Math.random());\n\t\t}\n\t}\n\n\t/** Unregisters every provider and listener and cancels pending notifications. */\n\tdispose(): void {\n\t\tif (this.timer !== null) clearTimeout(this.timer);\n\t\tthis.timer = null;\n\t\tfor (const entry of this.entries.splice(0)) entry.unsubscribe?.();\n\t\tthis.listeners.clear();\n\t}\n}\n\nexport function createToolRegistry(options?: ToolRegistryOptions): ToolRegistry {\n\treturn new ToolRegistry(options);\n}\n","import type { ToolRegistry } from './registry.js';\n\n/** MCP protocol revisions this server speaks, newest first. */\nexport const MCP_PROTOCOL_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05'] as const;\n\nexport type JsonRpcId = string | number;\n\nexport interface JsonRpcRequest {\n\tjsonrpc: '2.0';\n\tid?: JsonRpcId | null;\n\tmethod: string;\n\tparams?: Record<string, any>;\n}\n\nexport interface JsonRpcResponse {\n\tjsonrpc: '2.0';\n\tid: JsonRpcId | null;\n\tresult?: unknown;\n\terror?: { code: number; message: string; data?: unknown };\n}\n\nexport interface JsonRpcNotification {\n\tjsonrpc: '2.0';\n\tmethod: string;\n\tparams?: Record<string, unknown>;\n}\n\n/** Standard JSON-RPC error codes used by the server. */\nexport const JSON_RPC_ERRORS = {\n\tparseError: -32700,\n\tinvalidRequest: -32600,\n\tmethodNotFound: -32601,\n\tinvalidParams: -32602,\n\tinternalError: -32603\n} as const;\n\nexport interface McpServerOptions {\n\t/** `serverInfo` sent in the `initialize` result. */\n\tname: string;\n\tversion: string;\n\ttitle?: string;\n\t/** Usage hints for the client's model, sent in the `initialize` result. */\n\tinstructions?: string;\n\t/**\n\t * Sends server → client messages (`notifications/tools/list_changed`).\n\t * Without it the server still answers requests but announces nothing.\n\t */\n\tsend?: (message: JsonRpcNotification) => void;\n}\n\nexport interface McpServer {\n\t/**\n\t * Handles one client message (a JSON string or a parsed object) and\n\t * resolves to the response to send back, or `null` for notifications.\n\t * Never rejects.\n\t */\n\thandle(message: string | JsonRpcRequest): Promise<JsonRpcResponse | null>;\n\t/** Whether the client has completed the `initialize` handshake. */\n\treadonly initialized: boolean;\n\t/** Stops list-changed notifications and aborts running tool calls. */\n\tclose(): void;\n}\n\nconst errorResponse = (id: JsonRpcId | null, code: number, message: string, data?: unknown): JsonRpcResponse => ({\n\tjsonrpc: '2.0',\n\tid,\n\terror: { code, message, ...(data !== undefined ? { data } : {}) }\n});\n\n/**\n * A transport-agnostic MCP server for a {@link ToolRegistry}: wire `handle`\n * to any transport (stdio lines, a WebSocket, `postMessage`, an HTTP POST\n * handler) and pass `send` for server → client notifications.\n *\n * Supports `initialize` (with protocol version negotiation), `ping`,\n * `tools/list`, `tools/call` and `notifications/cancelled` (aborts the\n * call's `signal`), and announces `notifications/tools/list_changed` after\n * the client sends `notifications/initialized`. An unknown tool is a\n * JSON-RPC `-32602` error, as the MCP spec asks; invalid arguments and\n * handler failures are `isError` tool results the model can read and fix.\n */\nexport function createMcpServer(registry: ToolRegistry, options: McpServerOptions): McpServer {\n\tlet initialized = false;\n\tlet unsubscribe: (() => void) | null = null;\n\tconst running = new Map<JsonRpcId, AbortController>();\n\n\tconst startNotifications = () => {\n\t\tif (unsubscribe || !options.send) return;\n\t\tconst send = options.send;\n\t\tunsubscribe = registry.onListChanged(() => send({ jsonrpc: '2.0', method: 'notifications/tools/list_changed' }));\n\t};\n\n\tasync function dispatch(request: JsonRpcRequest): Promise<JsonRpcResponse | null> {\n\t\tconst id = request.id ?? null;\n\t\tconst isNotification = request.id === undefined || request.id === null;\n\t\tconst params = request.params ?? {};\n\n\t\tswitch (request.method) {\n\t\t\tcase 'initialize': {\n\t\t\t\tconst requested = String(params.protocolVersion ?? '');\n\t\t\t\tconst protocolVersion = (MCP_PROTOCOL_VERSIONS as readonly string[]).includes(requested)\n\t\t\t\t\t? requested\n\t\t\t\t\t: MCP_PROTOCOL_VERSIONS[0];\n\t\t\t\treturn {\n\t\t\t\t\tjsonrpc: '2.0',\n\t\t\t\t\tid,\n\t\t\t\t\tresult: {\n\t\t\t\t\t\tprotocolVersion,\n\t\t\t\t\t\tcapabilities: registry.capabilities,\n\t\t\t\t\t\tserverInfo: { name: options.name, version: options.version, ...(options.title ? { title: options.title } : {}) },\n\t\t\t\t\t\t...(options.instructions ? { instructions: options.instructions } : {})\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\t\t\tcase 'notifications/initialized':\n\t\t\t\tinitialized = true;\n\t\t\t\tstartNotifications();\n\t\t\t\treturn null;\n\t\t\tcase 'notifications/cancelled': {\n\t\t\t\tconst requestId = params.requestId as JsonRpcId | undefined;\n\t\t\t\tif (requestId !== undefined) running.get(requestId)?.abort(params.reason);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tcase 'ping':\n\t\t\t\treturn { jsonrpc: '2.0', id, result: {} };\n\t\t\tcase 'tools/list':\n\t\t\t\treturn { jsonrpc: '2.0', id, result: registry.listTools() };\n\t\t\tcase 'tools/call': {\n\t\t\t\tconst name = params.name;\n\t\t\t\tif (typeof name !== 'string') {\n\t\t\t\t\treturn errorResponse(id, JSON_RPC_ERRORS.invalidParams, 'tools/call needs a string \"name\".');\n\t\t\t\t}\n\t\t\t\tif (!registry.hasTool(name)) {\n\t\t\t\t\treturn errorResponse(id, JSON_RPC_ERRORS.invalidParams, `Unknown tool: ${name}`);\n\t\t\t\t}\n\t\t\t\tconst args = params.arguments;\n\t\t\t\tif (args !== undefined && (typeof args !== 'object' || args === null || Array.isArray(args))) {\n\t\t\t\t\treturn errorResponse(id, JSON_RPC_ERRORS.invalidParams, '\"arguments\" must be an object.');\n\t\t\t\t}\n\t\t\t\tconst controller = new AbortController();\n\t\t\t\tif (!isNotification) running.set(id as JsonRpcId, controller);\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await registry.callTool(name, args ?? {}, { signal: controller.signal });\n\t\t\t\t\t// A cancelled request gets no response (MCP cancellation semantics).\n\t\t\t\t\tif (controller.signal.aborted) return null;\n\t\t\t\t\treturn { jsonrpc: '2.0', id, result };\n\t\t\t\t} finally {\n\t\t\t\t\tif (!isNotification) running.delete(id as JsonRpcId);\n\t\t\t\t}\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tif (isNotification) return null;\n\t\t\t\treturn errorResponse(id, JSON_RPC_ERRORS.methodNotFound, `Method not found: ${request.method}`);\n\t\t}\n\t}\n\n\treturn {\n\t\tget initialized() {\n\t\t\treturn initialized;\n\t\t},\n\t\tasync handle(message) {\n\t\t\tlet request: JsonRpcRequest;\n\t\t\tif (typeof message === 'string') {\n\t\t\t\ttry {\n\t\t\t\t\trequest = JSON.parse(message);\n\t\t\t\t} catch {\n\t\t\t\t\treturn errorResponse(null, JSON_RPC_ERRORS.parseError, 'Parse error.');\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trequest = message;\n\t\t\t}\n\t\t\tif (\n\t\t\t\t!request ||\n\t\t\t\ttypeof request !== 'object' ||\n\t\t\t\tArray.isArray(request) ||\n\t\t\t\trequest.jsonrpc !== '2.0' ||\n\t\t\t\ttypeof request.method !== 'string'\n\t\t\t) {\n\t\t\t\tconst id = request && typeof request === 'object' && !Array.isArray(request) ? (request as JsonRpcRequest).id ?? null : null;\n\t\t\t\treturn errorResponse(id, JSON_RPC_ERRORS.invalidRequest, 'Invalid JSON-RPC 2.0 request.');\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn await dispatch(request);\n\t\t\t} catch (error) {\n\t\t\t\tif (request.id === undefined || request.id === null) return null;\n\t\t\t\treturn errorResponse(\n\t\t\t\t\trequest.id,\n\t\t\t\t\tJSON_RPC_ERRORS.internalError,\n\t\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t\tclose() {\n\t\t\tunsubscribe?.();\n\t\t\tunsubscribe = null;\n\t\t\tfor (const controller of running.values()) controller.abort('Server closed.');\n\t\t\trunning.clear();\n\t\t}\n\t};\n}\n","// The editor side of the tool bridge (Ursula's `connectRemote` / src/remote/protocol.ts): a page\n// connects its ToolRegistry to a local MCP bridge process over a WebSocket, and the bridge's MCP\n// client can then list and call the page's tools. No imports beyond the registry types, so it\n// runs in browsers, workers and Node alike.\nimport type { McpToolDefinition, McpToolResult, ToolRegistry } from './registry.js';\n\n/** Protocol version spoken between `connectToolBridge` and `createToolBridge`. */\nexport const TOOL_BRIDGE_PROTOCOL = 1;\n\n/** Default port the bridge listens on (127.0.0.1 only). */\nexport const TOOL_BRIDGE_DEFAULT_PORT = 4477;\n\n/** Editor → bridge messages. */\nexport type ToolBridgeEditorMessage =\n\t| { t: 'hello'; v: number; name: string; kind?: string; tools: McpToolDefinition[] }\n\t| { t: 'tools'; tools: McpToolDefinition[] }\n\t| { t: 'result'; id: string; result: McpToolResult };\n\n/** Bridge → editor messages. */\nexport type ToolBridgeServerMessage =\n\t| { t: 'welcome'; v: number; id: string }\n\t| { t: 'call'; id: string; name: string; arguments: Record<string, unknown> }\n\t| { t: 'cancel'; id: string; reason?: string };\n\nexport type ToolBridgeStatus = 'connecting' | 'connected' | 'disconnected' | 'closed';\n\n/** The parts of a WebSocket the client uses (the browser's, Node's global one, or `ws`). */\nexport interface ToolBridgeSocket {\n\treadonly readyState: number;\n\tsend(data: string): void;\n\tclose(code?: number, reason?: string): void;\n\taddEventListener(type: 'open' | 'close' | 'error' | 'message', listener: (event: any) => void): void;\n}\n\nexport interface ConnectToolBridgeOptions {\n\t/** Bridge URL (default `ws://127.0.0.1:4477`). */\n\turl?: string;\n\t/** The bridge's token, if it was started with one (sent as `?token=`). */\n\ttoken?: string;\n\t/** How this editor is listed to the agent (`list_editors`), e.g. \"Diagram — Order flow\". */\n\tname: string;\n\t/** What kind of editor this is (\"diagram\", \"chart\", \"document\"…), shown in `list_editors`. */\n\tkind?: string;\n\t/** Reconnect after the bridge goes away (default true), backing off up to 10 s. */\n\treconnect?: boolean;\n\t/** WebSocket constructor (default: the global one). */\n\tWebSocket?: new (url: string) => ToolBridgeSocket;\n\t/** Called when the connection state changes. */\n\tonStatus?: (status: ToolBridgeStatus, detail?: string) => void;\n}\n\nexport interface ToolBridgeConnection {\n\treadonly status: ToolBridgeStatus;\n\t/** The id the bridge gave this editor (`list_editors`), once connected. */\n\treadonly editorId: string | null;\n\t/** Disconnects and stops reconnecting; running calls are aborted. */\n\tclose(): void;\n}\n\n/**\n * Connects a `ToolRegistry` to a local MCP bridge (`createToolBridge` /\n * `pixerate-mcp-bridge`), so an MCP client (Claude Desktop, Claude Code, an IDE) can call\n * the page's tools: the registry's tool list is sent on connect and whenever it changes,\n * calls run through `registry.callTool` with an `AbortSignal` the bridge cancels, and the\n * connection comes back after the bridge restarts.\n */\nexport function connectToolBridge(registry: ToolRegistry, options: ConnectToolBridgeOptions): ToolBridgeConnection {\n\tconst Ctor = options.WebSocket ?? (globalThis as { WebSocket?: new (url: string) => ToolBridgeSocket }).WebSocket;\n\tif (!Ctor) throw new Error('No WebSocket implementation: pass options.WebSocket.');\n\tconst base = options.url ?? `ws://127.0.0.1:${TOOL_BRIDGE_DEFAULT_PORT}`;\n\tconst url = options.token ? `${base}${base.includes('?') ? '&' : '?'}token=${encodeURIComponent(options.token)}` : base;\n\tlet status: ToolBridgeStatus = 'connecting';\n\tlet editorId: string | null = null;\n\tlet socket: ToolBridgeSocket | null = null;\n\tlet closed = false;\n\tlet delay = 500;\n\tlet retry: ReturnType<typeof setTimeout> | null = null;\n\tconst running = new Map<string, AbortController>();\n\tconst setStatus = (next: ToolBridgeStatus, detail?: string) => {\n\t\tif (next === status && !detail) return;\n\t\tstatus = next;\n\t\toptions.onStatus?.(next, detail);\n\t};\n\tconst send = (message: ToolBridgeEditorMessage) => {\n\t\tif (socket && socket.readyState === 1) socket.send(JSON.stringify(message));\n\t};\n\tconst unsubscribe = registry.onListChanged((tools) => send({ t: 'tools', tools }));\n\n\tconst open = () => {\n\t\tif (closed) return;\n\t\tsetStatus('connecting');\n\t\tconst ws = new Ctor(url);\n\t\tsocket = ws;\n\t\tws.addEventListener('open', () => {\n\t\t\tdelay = 500;\n\t\t\tsend({ t: 'hello', v: TOOL_BRIDGE_PROTOCOL, name: options.name, ...(options.kind ? { kind: options.kind } : {}), tools: registry.listTools().tools });\n\t\t});\n\t\tws.addEventListener('message', (event: { data: unknown }) => {\n\t\t\tlet message: ToolBridgeServerMessage;\n\t\t\ttry {\n\t\t\t\tmessage = JSON.parse(String(event.data));\n\t\t\t} catch {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (message.t === 'welcome') {\n\t\t\t\teditorId = message.id;\n\t\t\t\tsetStatus('connected');\n\t\t\t} else if (message.t === 'call') {\n\t\t\t\tconst controller = new AbortController();\n\t\t\t\trunning.set(message.id, controller);\n\t\t\t\tvoid registry.callTool(message.name, message.arguments ?? {}, { signal: controller.signal }).then((result) => {\n\t\t\t\t\trunning.delete(message.id);\n\t\t\t\t\tif (!controller.signal.aborted) send({ t: 'result', id: message.id, result });\n\t\t\t\t});\n\t\t\t} else if (message.t === 'cancel') {\n\t\t\t\trunning.get(message.id)?.abort(message.reason ?? 'Cancelled by the agent.');\n\t\t\t\trunning.delete(message.id);\n\t\t\t}\n\t\t});\n\t\tws.addEventListener('close', (event: { code?: number; reason?: string }) => {\n\t\t\tif (socket !== ws) return;\n\t\t\tsocket = null;\n\t\t\teditorId = null;\n\t\t\tfor (const controller of running.values()) controller.abort('The bridge disconnected.');\n\t\t\trunning.clear();\n\t\t\tif (closed) return setStatus('closed');\n\t\t\tsetStatus('disconnected', event.reason || undefined);\n\t\t\tif (options.reconnect === false) return;\n\t\t\tretry = setTimeout(open, delay);\n\t\t\tdelay = Math.min(10_000, delay * 2);\n\t\t});\n\t\t// Errors are followed by `close`, which handles reconnecting.\n\t\tws.addEventListener('error', () => {});\n\t};\n\topen();\n\n\treturn {\n\t\tget status() {\n\t\t\treturn status;\n\t\t},\n\t\tget editorId() {\n\t\t\treturn editorId;\n\t\t},\n\t\tclose() {\n\t\t\tif (closed) return;\n\t\t\tclosed = true;\n\t\t\tif (retry) clearTimeout(retry);\n\t\t\tunsubscribe();\n\t\t\tfor (const controller of running.values()) controller.abort('The editor disconnected.');\n\t\t\trunning.clear();\n\t\t\tconst ws = socket;\n\t\t\tsocket = null;\n\t\t\tws?.close(1000, 'Editor closed.');\n\t\t\tsetStatus('closed');\n\t\t}\n\t};\n}\n"]}
@@ -6,11 +6,11 @@ import {
6
6
  describeChart,
7
7
  layoutChart,
8
8
  layoutSparkline
9
- } from "./chunk-WBOAXDKD.js";
9
+ } from "./chunk-VODBAO32.js";
10
10
  import {
11
11
  DEFAULT_CHART_THEME,
12
12
  normalizeChartSpec
13
- } from "./chunk-OV7UAKIY.js";
13
+ } from "./chunk-633QC34G.js";
14
14
  import {
15
15
  isTrackChangesEnabled
16
16
  } from "./chunk-SWE3NPOU.js";
@@ -2057,4 +2057,4 @@ export {
2057
2057
  getTableState,
2058
2058
  createTableStore
2059
2059
  };
2060
- //# sourceMappingURL=chunk-QFTVLEVN.js.map
2060
+ //# sourceMappingURL=chunk-RIXTW3C4.js.map