@pixerate/editor 0.26.0 → 0.27.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.
- package/README.md +8 -2
- package/dist/agent/index.cjs +59 -9
- package/dist/agent/index.cjs.map +1 -1
- package/dist/agent/index.d.cts +6 -4
- package/dist/agent/index.d.ts +6 -4
- package/dist/agent/index.js +52 -2
- package/dist/agent/index.js.map +1 -1
- package/dist/{builtins-Chj6zv_O.d.ts → builtins-haN82vjT.d.ts} +33 -3
- package/dist/{builtins-CdPcLwwF.d.cts → builtins-nMXh9sT3.d.cts} +33 -3
- package/dist/canvas/index.cjs +372 -8
- package/dist/canvas/index.cjs.map +1 -1
- package/dist/canvas/index.d.cts +72 -4
- package/dist/canvas/index.d.ts +72 -4
- package/dist/canvas/index.js +368 -4
- package/dist/canvas/index.js.map +1 -1
- package/dist/{chunk-UBCFIABU.js → chunk-5H2OPMXZ.js} +183 -6
- package/dist/chunk-5H2OPMXZ.js.map +1 -0
- package/dist/{chunk-NFVBT3UZ.cjs → chunk-66IMF6OD.cjs} +108 -25
- package/dist/chunk-66IMF6OD.cjs.map +1 -0
- package/dist/{chunk-Q2OHWD2A.js → chunk-6IO7WUSU.js} +19 -5
- package/dist/chunk-6IO7WUSU.js.map +1 -0
- package/dist/{chunk-YOMYSFJU.cjs → chunk-AGR7EVRW.cjs} +49 -35
- package/dist/chunk-AGR7EVRW.cjs.map +1 -0
- package/dist/{chunk-RRREAOVM.cjs → chunk-HNDSPZ5T.cjs} +4 -4
- package/dist/{chunk-RRREAOVM.cjs.map → chunk-HNDSPZ5T.cjs.map} +1 -1
- package/dist/chunk-HXDMZQTD.cjs +497 -0
- package/dist/chunk-HXDMZQTD.cjs.map +1 -0
- package/dist/chunk-IB3ZHQAX.js +497 -0
- package/dist/chunk-IB3ZHQAX.js.map +1 -0
- package/dist/{chunk-X7HXL2SB.js → chunk-JT7AXQTE.js} +336 -10
- package/dist/chunk-JT7AXQTE.js.map +1 -0
- package/dist/{chunk-HDYMLS3X.cjs → chunk-MC2LQN5S.cjs} +196 -19
- package/dist/chunk-MC2LQN5S.cjs.map +1 -0
- package/dist/{chunk-JOIREKL7.js → chunk-UKI64KUD.js} +85 -2
- package/dist/chunk-UKI64KUD.js.map +1 -0
- package/dist/{chunk-MHEPLBFB.js → chunk-WON34HKM.js} +2 -2
- package/dist/{chunk-NQF32I6Z.cjs → chunk-YK5TATOF.cjs} +461 -135
- package/dist/chunk-YK5TATOF.cjs.map +1 -0
- package/dist/commands/index.cjs +30 -410
- package/dist/commands/index.cjs.map +1 -1
- package/dist/commands/index.d.cts +1 -1
- package/dist/commands/index.d.ts +1 -1
- package/dist/commands/index.js +17 -397
- package/dist/commands/index.js.map +1 -1
- package/dist/{controller-CxXGOEmy.d.cts → controller-w6eRTjF8.d.cts} +67 -2
- package/dist/{controller-CxXGOEmy.d.ts → controller-w6eRTjF8.d.ts} +67 -2
- package/dist/extensions/index.cjs +23 -5
- package/dist/extensions/index.cjs.map +1 -1
- package/dist/extensions/index.d.cts +1 -1
- package/dist/extensions/index.d.ts +1 -1
- package/dist/extensions/index.js +23 -5
- package/dist/{index-jcJwmBYt.d.cts → index-C6gaQRH0.d.cts} +53 -4
- package/dist/{index-B273Zllk.d.ts → index-DXAv_R08.d.ts} +53 -4
- package/dist/index.cjs +66 -26
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +8 -6
- package/dist/index.d.ts +8 -6
- package/dist/index.js +46 -6
- package/dist/index.js.map +1 -1
- package/dist/serializers/index.cjs +5 -3
- package/dist/serializers/index.cjs.map +1 -1
- package/dist/serializers/index.d.cts +13 -3
- package/dist/serializers/index.d.ts +13 -3
- package/dist/serializers/index.js +4 -2
- package/dist/spreadsheet/index.cjs +22 -2
- package/dist/spreadsheet/index.cjs.map +1 -1
- package/dist/spreadsheet/index.d.cts +76 -3
- package/dist/spreadsheet/index.d.ts +76 -3
- package/dist/spreadsheet/index.js +21 -1
- package/package.json +1 -1
- package/dist/chunk-HDYMLS3X.cjs.map +0 -1
- package/dist/chunk-JOIREKL7.js.map +0 -1
- package/dist/chunk-NFVBT3UZ.cjs.map +0 -1
- package/dist/chunk-NQF32I6Z.cjs.map +0 -1
- package/dist/chunk-Q2OHWD2A.js.map +0 -1
- package/dist/chunk-UBCFIABU.js.map +0 -1
- package/dist/chunk-X7HXL2SB.js.map +0 -1
- package/dist/chunk-YOMYSFJU.cjs.map +0 -1
- /package/dist/{chunk-MHEPLBFB.js.map → chunk-WON34HKM.js.map} +0 -0
package/README.md
CHANGED
|
@@ -153,6 +153,7 @@ registry.register(createTableCommands(editor)); // table.insertTable, table.addR
|
|
|
153
153
|
```
|
|
154
154
|
|
|
155
155
|
- **Actions** (`TABLE_ACTIONS`): `insertTable` (no nesting), `addRowBefore` / `addRowAfter` / `deleteRow`, `addColumnBefore` / `addColumnAfter` / `deleteColumn`, `deleteTable`, `mergeCells` / `splitCell`, `toggleHeaderRow` / `toggleHeaderColumn` / `toggleHeaderCell`, `goToNextCell` / `goToPreviousCell` (Tab / Shift+Tab), `setCellAlignment` (`{ align }`) and `setCellBackground` (`{ color }`, sanitized). `createTableStore(editor)` is the external store the React and Svelte toolbars use; `DEFAULT_TABLE_TOOLBAR` lists their buttons. `createRichTextToolProvider` adds an `edit_table` agent tool when the schema has tables.
|
|
156
|
+
- **No nested tables**: pasting a table (HTML, markdown or the rich clipboard) on its own while the cursor is in a cell fills the cells from that cell, growing the table when needed (a cell selection is filled and clipped as before); pasted content that contains a table among other blocks, and imported files with tables (`importFilesIntoEditor`, `FileImport`), are inserted after the outermost table, and the cell keeps its content. A guard moves any table another edit puts into a cell (`insertContent`, `insertTable`) after the table; tracked changes still record the insertion. Documents that already contain nested tables load and stay unchanged (initial content, `setContent`, undo, collaboration); set `ALLOW_NESTED_TABLES_META` on a transaction to opt out of the guard.
|
|
156
157
|
- **Export**: `getEditorText` writes each row as a line of tab-separated cells. Markdown (`markdown: true`) writes a GFM pipe table (column alignment from the header cells, `|` escaped) when the first row is all header cells, nothing spans and every cell holds one paragraph; otherwise the table is written as HTML, which parses back. GFM tables in markdown input become tables.
|
|
157
158
|
- **Track changes**: edits inside cells are tracked like any text. Inserting or deleting rows, columns (their cells) or a whole table is tracked as a whole-block change (`blockChange` with `operation`): rejecting an insertion or accepting a deletion removes the rows/cells/table; deleting rows you inserted yourself removes them. Header toggles are tracked as block changes (reject restores the cell type). Cell attributes (alignment, background, widths) are not tracked, and merging or splitting cells is refused while tracking. `compareDocuments` compares tables row by row and cell by cell.
|
|
158
159
|
- Style the tables in your CSS (`.tableWrapper`, `table`, `th`, `td`, `.selectedCell`, `.column-resize-handle`; the table has the `pixerate-table` class).
|
|
@@ -345,9 +346,11 @@ sheet.defineName("Revenue", "=Sales!$F$2:$F$11");
|
|
|
345
346
|
sheet.defineName("WithTax", "=LAMBDA(x, x*1.2)");
|
|
346
347
|
sheet.setCellValue(sheet.document.rows[0].id, sheet.document.columns[0].id, "=WithTax(SUM(Revenue))");
|
|
347
348
|
sheet.renameSheet("Sales", "Sales 2026"); // formulas become ='Sales 2026'!…
|
|
348
|
-
sheet.getWorkbook(); // { sheets, activeSheetId, names }
|
|
349
|
+
sheet.getWorkbook(); // { sheets, activeSheetId, names }: save every sheet
|
|
349
350
|
```
|
|
350
351
|
|
|
352
|
+
**Saving.** Either save `getWorkbook()` (every sheet, with all names in `names`) and load it with `{ workbook }` / `loadWorkbook`, or keep saving the document passed to `onDocumentChange` and load it with `{ document }` / `loadDocument`: each sheet document's `names` holds the workbook-scoped names plus that sheet's own sheet-scoped names (any `sheetId` there means "this sheet"), so a single-sheet app round-trips names (LAMBDA names included) without changes. When a workbook is loaded, `workbook.names` wins over names repeated in `sheets[*].names`, and names found only in sheet documents are added (first sheet wins). `getWorkbook()` keeps names in `names` only. Documents and workbooks saved before names existed load as before.
|
|
353
|
+
|
|
351
354
|
Formulas reference other sheets (`Sheet2!A1`, `'My Sheet'!A1:B2`, `Data!A1#`) and 3-D ranges (`SUM(Sheet1:Sheet3!A1)`). Deleting a sheet turns references to it into `#REF!`; inserting or deleting rows and columns rewrites references from every sheet. Names can be workbook- or sheet-scoped (`{ sheet }`), are validated like Excel (`validateDefinedName`), and `renameName` rewrites the formulas using them. `LAMBDA` values can be called inline (`=LAMBDA(x, x+1)(2)`), stored with `LET` or a name (recursion is capped at 1000 calls with `#NUM!`), or passed to `MAP`, `REDUCE`, `SCAN`, `BYROW`, `BYCOL` and `MAKEARRAY`. Undo restores the sheet a step changed (switching to it) or, for sheet and name operations, the whole workbook.
|
|
352
355
|
|
|
353
356
|
## Spreadsheet conditional formatting and data validation
|
|
@@ -401,8 +404,11 @@ Each module is also available as a subpath import:
|
|
|
401
404
|
| `@pixerate/editor/commands` | `CommandRegistry`, `ShortcutMap`, palette ranking, `createCommandToolProvider` and built-in history / arrange / spreadsheet commands (no third-party imports) |
|
|
402
405
|
| `@pixerate/editor/persistence` | Autosave and crash recovery (`createAutosaveController`, `createRecoveryPolicy`, `createRevisionTracker`), storage adapters (memory, localStorage, IndexedDB, OPFS) and document migration (`migrateDocument`, `loadSections`, `LoadReport`) (no third-party imports) |
|
|
403
406
|
| `@pixerate/editor/generation` | Model capability descriptors, `planGenerationRequest`, `capabilitiesToJsonSchema`, `createGenerationToolProvider`, provenance, `createBatchResolver` and job-progress estimates (no third-party imports) |
|
|
407
|
+
| `@pixerate/editor/compare` | `diffSequences` (Myers + patience), `compareDocuments` and `compareHtml`: two versions of a document as tracked changes (also re-exported from the root entry) |
|
|
408
|
+
| `@pixerate/editor/export` | Word export: `exportDocx`, `exportDocxBlob`, `createDocxParts`, `DocxExportController`, plus the zip writer and XML escapers it uses (no third-party imports; also re-exported from the root entry) |
|
|
409
|
+
| `@pixerate/editor/tokens` | Design tokens: collections, modes, aliases, `TokenStore`, `resolveToken`, W3C Design Tokens JSON and CSS custom-property export (no third-party imports) |
|
|
404
410
|
|
|
405
|
-
The root entry (`@pixerate/editor`) re-exports everything except canvas, agent, commands, persistence, generation and image editor, including TipTap. Import from the narrowest subpath you need: `grammar`, `history`, `spreadsheet`, `commands`, `persistence` and `image-editor` have no third-party imports, so a spreadsheet-only app bundles no TipTap, markdown or dagre code. The package is marked `sideEffects: false`, so unused root exports are also tree-shaken.
|
|
411
|
+
The root entry (`@pixerate/editor`) re-exports everything except canvas, agent, commands, persistence, generation, tokens and image editor, including TipTap. Import from the narrowest subpath you need: `grammar`, `history`, `spreadsheet`, `commands`, `persistence` and `image-editor` have no third-party imports, so a spreadsheet-only app bundles no TipTap, markdown or dagre code. The package is marked `sideEffects: false`, so unused root exports are also tree-shaken.
|
|
406
412
|
|
|
407
413
|
## Autosave, crash recovery and document migration
|
|
408
414
|
|
package/dist/agent/index.cjs
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
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
2
|
|
|
3
|
+
var _chunkHXDMZQTDcjs = require('../chunk-HXDMZQTD.cjs');
|
|
4
|
+
|
|
5
|
+
|
|
3
6
|
var _chunkCPOKFNBGcjs = require('../chunk-CPOKFNBG.cjs');
|
|
4
7
|
|
|
5
8
|
|
|
@@ -7,12 +10,12 @@ var _chunkCPOKFNBGcjs = require('../chunk-CPOKFNBG.cjs');
|
|
|
7
10
|
|
|
8
11
|
|
|
9
12
|
|
|
10
|
-
var
|
|
13
|
+
var _chunkMC2LQN5Scjs = require('../chunk-MC2LQN5S.cjs');
|
|
11
14
|
|
|
12
15
|
|
|
13
16
|
|
|
14
17
|
|
|
15
|
-
var
|
|
18
|
+
var _chunk66IMF6ODcjs = require('../chunk-66IMF6OD.cjs');
|
|
16
19
|
require('../chunk-BVP3TSLH.cjs');
|
|
17
20
|
require('../chunk-IFHKKVXH.cjs');
|
|
18
21
|
|
|
@@ -25,6 +28,7 @@ var _chunkEWCOFSCQcjs = require('../chunk-EWCOFSCQ.cjs');
|
|
|
25
28
|
|
|
26
29
|
|
|
27
30
|
var _chunkWADCJ7A7cjs = require('../chunk-WADCJ7A7.cjs');
|
|
31
|
+
require('../chunk-26BVFKHU.cjs');
|
|
28
32
|
|
|
29
33
|
// src/agent/planner.ts
|
|
30
34
|
function normalizeSide(side) {
|
|
@@ -710,7 +714,7 @@ var _state = require('@tiptap/pm/state');
|
|
|
710
714
|
var toEditor = (target) => "commands" in target ? target : target.editor;
|
|
711
715
|
function replaceWithText(editor, from, to, text) {
|
|
712
716
|
const { state, view } = editor;
|
|
713
|
-
const tr = /[\r\n]/.test(text) ? state.tr.replace(from, to,
|
|
717
|
+
const tr = /[\r\n]/.test(text) ? state.tr.replace(from, to, _chunk66IMF6ODcjs.plainTextToSlice.call(void 0, text, state.schema)) : text ? state.tr.insertText(text, from, to) : state.tr.delete(from, to);
|
|
714
718
|
view.dispatch(tr.scrollIntoView());
|
|
715
719
|
}
|
|
716
720
|
function selectionInfo(editor) {
|
|
@@ -743,7 +747,7 @@ function createRichTextToolProvider(target, options) {
|
|
|
743
747
|
},
|
|
744
748
|
handler: ({ format = "text" }) => {
|
|
745
749
|
const ed = editor();
|
|
746
|
-
const content = format === "html" ? ed.getHTML() : format === "markdown" ?
|
|
750
|
+
const content = format === "html" ? ed.getHTML() : format === "markdown" ? _chunk66IMF6ODcjs.getEditorMarkdown.call(void 0, ed) : _chunk66IMF6ODcjs.getEditorText.call(void 0, ed);
|
|
747
751
|
return { format, content, selection: selectionInfo(ed), size: ed.state.doc.content.size };
|
|
748
752
|
}
|
|
749
753
|
};
|
|
@@ -809,7 +813,7 @@ function createRichTextToolProvider(target, options) {
|
|
|
809
813
|
inputSchema: {
|
|
810
814
|
type: "object",
|
|
811
815
|
properties: {
|
|
812
|
-
operation: { type: "string", enum:
|
|
816
|
+
operation: { type: "string", enum: _chunkMC2LQN5Scjs.TABLE_ACTIONS.map((a) => a.action), description: "Table operation." },
|
|
813
817
|
at: { type: "integer", minimum: 0, description: "Document position to place the cursor first (e.g. inside a cell)." },
|
|
814
818
|
rows: { type: "integer", minimum: 1, maximum: 100, description: "insertTable: rows (default 3)." },
|
|
815
819
|
cols: { type: "integer", minimum: 1, maximum: 50, description: "insertTable: columns (default 3)." },
|
|
@@ -839,10 +843,10 @@ function createRichTextToolProvider(target, options) {
|
|
|
839
843
|
ed.view.dispatch(ed.state.tr.setSelection(_state.TextSelection.near(ed.state.doc.resolve(at))));
|
|
840
844
|
}
|
|
841
845
|
const action = operation;
|
|
842
|
-
const state =
|
|
846
|
+
const state = _chunkMC2LQN5Scjs.getTableActionState.call(void 0, ed, action, params);
|
|
843
847
|
if (state !== true) throw new Error(state);
|
|
844
|
-
|
|
845
|
-
const table =
|
|
848
|
+
_chunkMC2LQN5Scjs.runTableAction.call(void 0, ed, action, params);
|
|
849
|
+
const table = _chunkMC2LQN5Scjs.getTableState.call(void 0, ed);
|
|
846
850
|
return {
|
|
847
851
|
operation,
|
|
848
852
|
table: table.inTable ? { rows: table.rows, columns: table.columns, row: table.row, column: table.column } : null,
|
|
@@ -857,7 +861,7 @@ function createRichTextToolProvider(target, options) {
|
|
|
857
861
|
const ed = editor();
|
|
858
862
|
if (!ed || ed.isDestroyed) return [];
|
|
859
863
|
if (!ed.isEditable) return [getText];
|
|
860
|
-
return
|
|
864
|
+
return _chunkMC2LQN5Scjs.isTableEnabled.call(void 0, ed) ? [getText, insertText, replaceSelection, editTable] : [getText, insertText, replaceSelection];
|
|
861
865
|
},
|
|
862
866
|
subscribe: (notify) => {
|
|
863
867
|
const ed = editor();
|
|
@@ -1110,6 +1114,52 @@ function createCanvasComponentToolProvider(controller, options = { id: "canvas-c
|
|
|
1110
1114
|
({ id }) => check(controller.restoreMainComponent(id))
|
|
1111
1115
|
)
|
|
1112
1116
|
];
|
|
1117
|
+
if (_chunkHXDMZQTDcjs.hasVariantCommands.call(void 0, controller)) {
|
|
1118
|
+
const SET = { type: "string", description: "Component set, or one of its variants (default: the selection\u2019s set)." };
|
|
1119
|
+
const VARIANT = { type: "string", description: "Variant id (default: the first selected variant)." };
|
|
1120
|
+
const VALUES = { type: "object", additionalProperties: { type: "string" }, description: 'Variant property \u2192 value, e.g. { "Size": "Medium" }.' };
|
|
1121
|
+
tools.push(
|
|
1122
|
+
tool(
|
|
1123
|
+
"add_variant",
|
|
1124
|
+
'Adds a variant to a component set by duplicating one (default: the set\u2019s default variant) with new property values. Unnamed properties keep the source\u2019s values; new property names are added to every variant ("Default"). A combination another variant has is refused. Without values the next "VariantN" is used.',
|
|
1125
|
+
{ setId: SET, from: { type: "string", description: "Variant to duplicate." }, variant: VALUES, x: { type: "number" }, y: { type: "number" } },
|
|
1126
|
+
({ setId, from, variant, x, y }) => check(
|
|
1127
|
+
controller.addVariant(setId, {
|
|
1128
|
+
...from !== void 0 ? { from } : {},
|
|
1129
|
+
...variant ? { variant } : {},
|
|
1130
|
+
...x !== void 0 || y !== void 0 ? { position: { x: _nullishCoalesce(x, () => ( 0)), y: _nullishCoalesce(y, () => ( 0)) } } : {}
|
|
1131
|
+
})
|
|
1132
|
+
)
|
|
1133
|
+
),
|
|
1134
|
+
tool(
|
|
1135
|
+
"remove_variant",
|
|
1136
|
+
"Removes a variant from its component set (not the last one). Its instances switch to the closest remaining variant, keeping overrides.",
|
|
1137
|
+
{ id: VARIANT },
|
|
1138
|
+
({ id }) => check(controller.removeVariant(id))
|
|
1139
|
+
),
|
|
1140
|
+
tool(
|
|
1141
|
+
"set_variant_properties",
|
|
1142
|
+
"Sets a variant\u2019s property values (merged with its current ones); new property names are added to every variant. A combination another variant has is refused.",
|
|
1143
|
+
{ values: VALUES, id: VARIANT },
|
|
1144
|
+
({ values, id }) => check(controller.setVariantProperties(values, id)),
|
|
1145
|
+
{ required: ["values"] }
|
|
1146
|
+
),
|
|
1147
|
+
tool(
|
|
1148
|
+
"rename_variant_property",
|
|
1149
|
+
"Renames a variant property across a component set (instances keep their variant).",
|
|
1150
|
+
{ name: { type: "string" }, newName: { type: "string" }, setId: SET },
|
|
1151
|
+
({ name, newName, setId }) => check(controller.renameVariantProperty(name, newName, setId)),
|
|
1152
|
+
{ required: ["name", "newName"] }
|
|
1153
|
+
),
|
|
1154
|
+
tool(
|
|
1155
|
+
"rename_variant_value",
|
|
1156
|
+
"Renames a value of a variant property across a component set (instances keep their variant).",
|
|
1157
|
+
{ property: { type: "string" }, value: { type: "string" }, newValue: { type: "string" }, setId: SET },
|
|
1158
|
+
({ property, value, newValue, setId }) => check(controller.renameVariantValue(property, value, newValue, setId)),
|
|
1159
|
+
{ required: ["property", "value", "newValue"] }
|
|
1160
|
+
)
|
|
1161
|
+
);
|
|
1162
|
+
}
|
|
1113
1163
|
return { id: options.id, namespace: options.namespace, tools };
|
|
1114
1164
|
}
|
|
1115
1165
|
|
package/dist/agent/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/editor/editor/packages/core/dist/agent/index.cjs","../../src/agent/planner.ts","../../src/agent/tools.ts","../../src/agent/registry.ts","../../src/agent/providers.ts","../../src/agent/componentTools.ts"],"names":[],"mappings":"AAAA;AACE;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACF,yDAA8B;AAC9B,iCAA8B;AAC9B,iCAA8B;AAC9B;AACE;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACF,yDAA8B;AAC9B;AACA;ACpBO,SAAS,aAAA,CAAc,IAAA,EAAuC;AACpE,EAAA,OAAA,CAAQ,IAAA,EAAM;AAAA,IACb,KAAK,KAAA;AAA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AkB,MAAA;AAAmG,MAAA;AACvF,MAAA;AACnC,IAAA;AAC6F,IAAA;AAChE,IAAA;AACgB,MAAA;AACkB,MAAA;AAC5C,MAAA;AAClB,IAAA;AACD,IAAA;AAAK,MAAA;AAA0B,MAAA;AAA6F,MAAA;AAClF,MAAA;AAC1C,IAAA;AACD,EAAA;AAC6D,EAAA;AAC9D;ALs+BiG;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/editor/editor/packages/core/dist/agent/index.cjs","sourcesContent":[null,"import { ensureLayout, getLayoutedNodes, placeBeside } from '../canvas/layout.js';\nimport type { CanvasEdge, CanvasNode, Rect, Side } from '../canvas/types.js';\nimport type { AgentCommand, AgentStep, EditorSnapshot } from './types.js';\n\n/**\n * Normalizes a placement side from either the planner vocabulary (`right | below | left | above`)\n * or the MCP tool schema vocabulary (`top | right | bottom | left`). Unknown values fall back to `right`.\n */\nexport function normalizeSide(side: string | undefined | null): Side {\n\tswitch (side) {\n\t\tcase 'top':\n\t\tcase 'above':\n\t\t\treturn 'above';\n\t\tcase 'bottom':\n\t\tcase 'below':\n\t\t\treturn 'below';\n\t\tcase 'left':\n\t\t\treturn 'left';\n\t\tcase 'right':\n\t\tdefault:\n\t\t\treturn 'right';\n\t}\n}\n\n/**\n * Plans a sequence of atomic execution steps from a high-level agent command.\n */\nexport function planAgentCommand<\n\tTNode extends CanvasNode = CanvasNode,\n\tTEdge extends CanvasEdge = CanvasEdge\n>(\n\tcommand: AgentCommand<TNode, TEdge>,\n\tsnapshot: EditorSnapshot<TNode, TEdge>,\n\toptions: {\n\t\tdefaultNodeSize?: { width: number; height: number };\n\t\tidGenerator?: () => string;\n\t} = {}\n): AgentStep<TNode, TEdge>[] {\n\tconst defaultNodeSize = options.defaultNodeSize ?? { width: 200, height: 60 };\n\tconst idGen = options.idGenerator ?? (() => `node-${Math.random().toString(36).substring(2, 9)}`);\n\tconst edgeIdGen = () => `edge-${Math.random().toString(36).substring(2, 9)}`;\n\n\tconst nodes = snapshot.canvas?.nodes ?? [];\n\tconst edges = snapshot.canvas?.edges ?? [];\n\n\tswitch (command.type) {\n\t\tcase 'canvas:add_node': {\n\t\t\tlet pos = command.node.position;\n\t\t\t// Only anchor to (and connect from) a node that actually exists.\n\t\t\tconst anchorId =\n\t\t\t\tcommand.nearNodeId && nodes.some((n) => n.id === command.nearNodeId)\n\t\t\t\t\t? command.nearNodeId\n\t\t\t\t\t: undefined;\n\n\t\t\tif (!pos) {\n\t\t\t\tconst rects: Record<string, Rect> = {};\n\t\t\t\tfor (const n of nodes) {\n\t\t\t\t\trects[n.id] = {\n\t\t\t\t\t\tx: n.position.x,\n\t\t\t\t\t\ty: n.position.y,\n\t\t\t\t\t\twidth: n.measured?.width ?? (n as any).width ?? defaultNodeSize.width,\n\t\t\t\t\t\theight: n.measured?.height ?? (n as any).height ?? defaultNodeSize.height\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (anchorId) {\n\t\t\t\t\t// Use collision-aware directional placement\n\t\t\t\t\tpos = placeBeside(rects, defaultNodeSize, normalizeSide(command.side), anchorId);\n\t\t\t\t} else if (nodes.length > 0) {\n\t\t\t\t\t// Default beside the last node\n\t\t\t\t\tconst lastNode = nodes[nodes.length - 1];\n\t\t\t\t\tpos = placeBeside(rects, defaultNodeSize, 'right', lastNode.id);\n\t\t\t\t} else {\n\t\t\t\t\tpos = { x: 100, y: 100 };\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst fullNode: TNode = {\n\t\t\t\t...command.node,\n\t\t\t\tid: command.node.id || idGen(),\n\t\t\t\tposition: pos\n\t\t\t} as TNode;\n\n\t\t\tconst steps: AgentStep<TNode, TEdge>[] = [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:canvas_add_node',\n\t\t\t\t\tnode: fullNode\n\t\t\t\t}\n\t\t\t];\n\n\t\t\t// If attached to nearNode, optionally automatically connect\n\t\t\tif (anchorId) {\n\t\t\t\tsteps.push({\n\t\t\t\t\ttype: 'step:canvas_add_edge',\n\t\t\t\t\tedge: {\n\t\t\t\t\t\tid: edgeIdGen(),\n\t\t\t\t\t\tsource: anchorId,\n\t\t\t\t\t\ttarget: fullNode.id\n\t\t\t\t\t} as TEdge\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn steps;\n\t\t}\n\n\t\tcase 'canvas:remove_nodes': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:canvas_remove_nodes',\n\t\t\t\t\tnodeIds: command.nodeIds\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'canvas:connect': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:canvas_add_edge',\n\t\t\t\t\tedge: {\n\t\t\t\t\t\tid: edgeIdGen(),\n\t\t\t\t\t\tsource: command.source,\n\t\t\t\t\t\ttarget: command.target,\n\t\t\t\t\t\tlabel: command.label\n\t\t\t\t\t} as TEdge\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'canvas:update_node': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:canvas_update_node',\n\t\t\t\t\tid: command.id,\n\t\t\t\t\tdata: command.data\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'canvas:layout': {\n\t\t\tconst dir = command.direction ?? 'LR';\n\t\t\tlet layouted: TNode[];\n\n\t\t\t// Matches the MCP tool schema: `incremental` defaults to true.\n\t\t\tif (command.incremental ?? true) {\n\t\t\t\tconst stored: Record<string, { x: number; y: number }> = {};\n\t\t\t\tfor (const n of nodes) {\n\t\t\t\t\tif (n.position && (n.position.x !== 0 || n.position.y !== 0)) {\n\t\t\t\t\t\tstored[n.id] = { ...n.position };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlayouted = ensureLayout(nodes, edges, {\n\t\t\t\t\tdirection: dir,\n\t\t\t\t\tstoredPositions: stored\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tlayouted = getLayoutedNodes(nodes, edges, undefined, { direction: dir });\n\t\t\t}\n\n\t\t\tconst positions: Record<string, { x: number; y: number }> = {};\n\t\t\tfor (const node of layouted) {\n\t\t\t\tpositions[node.id] = { ...node.position };\n\t\t\t}\n\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:canvas_move_nodes',\n\t\t\t\t\tpositions\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'canvas:select': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:canvas_select',\n\t\t\t\t\tnodeIds: command.nodeIds\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'canvas:highlight': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:canvas_highlight',\n\t\t\t\t\tnodeIds: command.nodeIds,\n\t\t\t\t\tcolor: command.color ?? '#3b82f6',\n\t\t\t\t\tdurationMs: command.durationMs ?? 2000\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'prompt:insert_text': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:prompt_insert',\n\t\t\t\t\ttext: command.text,\n\t\t\t\t\tat: command.at\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'prompt:replace_range': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:prompt_replace',\n\t\t\t\t\tfrom: command.from,\n\t\t\t\t\tto: command.to,\n\t\t\t\t\ttext: command.text\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'prompt:set_variable': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:prompt_set_variable',\n\t\t\t\t\tname: command.name,\n\t\t\t\t\tvalue: command.value\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'prompt:select': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:prompt_select',\n\t\t\t\t\tfrom: command.from,\n\t\t\t\t\tto: command.to\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'choreography:say': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:say',\n\t\t\t\t\ttext: command.text,\n\t\t\t\t\tatNodeId: command.atNodeId,\n\t\t\t\t\tposition: command.position\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'choreography:wait': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:wait',\n\t\t\t\t\tms: command.ms\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'tool:call': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:tool_call',\n\t\t\t\t\tname: command.name,\n\t\t\t\t\targuments: command.arguments ?? {}\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tdefault: {\n\t\t\treturn [];\n\t\t}\n\t}\n}\n\n/**\n * Converts an MCP tool call into a planner command. `edit_canvas` and\n * `edit_prompt` (see `tools.ts`) map to canvas/prompt commands using the MCP\n * schema's vocabulary; every other tool, including dynamic `ToolRegistry`\n * tools, becomes a `tool:call` command. Returns `null` when a static tool's\n * arguments are missing what the operation needs.\n */\nexport function toolCallToAgentCommand<\n\tTNode extends CanvasNode = CanvasNode,\n\tTEdge extends CanvasEdge = CanvasEdge\n>(name: string, args: Record<string, any> = {}): AgentCommand<TNode, TEdge> | null {\n\tconst ids = (value: unknown): string[] | null =>\n\t\tArray.isArray(value) && value.every((v) => typeof v === 'string') ? value : null;\n\tconst num = (value: unknown) => typeof value === 'number' && Number.isFinite(value);\n\n\tif (name === 'edit_canvas') {\n\t\tswitch (args.operation) {\n\t\t\tcase 'add_node':\n\t\t\t\treturn args.node && typeof args.node === 'object'\n\t\t\t\t\t? { type: 'canvas:add_node', node: args.node, nearNodeId: args.nearNodeId, side: args.side }\n\t\t\t\t\t: null;\n\t\t\tcase 'remove_nodes':\n\t\t\t\treturn ids(args.nodeIds) ? { type: 'canvas:remove_nodes', nodeIds: args.nodeIds } : null;\n\t\t\tcase 'connect':\n\t\t\t\treturn typeof args.source === 'string' && typeof args.target === 'string'\n\t\t\t\t\t? { type: 'canvas:connect', source: args.source, target: args.target, label: args.label }\n\t\t\t\t\t: null;\n\t\t\tcase 'update_node': {\n\t\t\t\tconst id = args.node?.id ?? args.id;\n\t\t\t\treturn typeof id === 'string'\n\t\t\t\t\t? { type: 'canvas:update_node', id, data: args.node?.data ?? args.data ?? {} }\n\t\t\t\t\t: null;\n\t\t\t}\n\t\t\tcase 'layout':\n\t\t\t\treturn { type: 'canvas:layout', direction: args.direction, incremental: args.incremental };\n\t\t\tcase 'select':\n\t\t\t\treturn ids(args.nodeIds) ? { type: 'canvas:select', nodeIds: args.nodeIds } : null;\n\t\t\tcase 'highlight':\n\t\t\t\treturn ids(args.nodeIds) ? { type: 'canvas:highlight', nodeIds: args.nodeIds } : null;\n\t\t\tdefault:\n\t\t\t\treturn null;\n\t\t}\n\t}\n\n\tif (name === 'edit_prompt') {\n\t\tswitch (args.operation) {\n\t\t\tcase 'insert_text':\n\t\t\t\treturn typeof args.text === 'string'\n\t\t\t\t\t? { type: 'prompt:insert_text', text: args.text, at: num(args.at) ? args.at : undefined }\n\t\t\t\t\t: null;\n\t\t\tcase 'replace_range':\n\t\t\t\treturn typeof args.text === 'string' && num(args.from) && num(args.to)\n\t\t\t\t\t? { type: 'prompt:replace_range', from: args.from, to: args.to, text: args.text }\n\t\t\t\t\t: null;\n\t\t\tcase 'set_variable':\n\t\t\t\treturn typeof args.name === 'string'\n\t\t\t\t\t? { type: 'prompt:set_variable', name: args.name, value: args.value }\n\t\t\t\t\t: null;\n\t\t\tcase 'select':\n\t\t\t\treturn num(args.from) && num(args.to) ? { type: 'prompt:select', from: args.from, to: args.to } : null;\n\t\t\tdefault:\n\t\t\t\treturn null;\n\t\t}\n\t}\n\n\treturn { type: 'tool:call', name, arguments: args };\n}\n\n/**\n * Plans the steps for an MCP tool call: static editor tools are planned like\n * the equivalent commands, any other tool becomes a `step:tool_call` to be\n * executed with `ToolRegistry.callTool`. Returns `[]` for invalid arguments.\n */\nexport function planToolCall<\n\tTNode extends CanvasNode = CanvasNode,\n\tTEdge extends CanvasEdge = CanvasEdge\n>(\n\tname: string,\n\targs: Record<string, any>,\n\tsnapshot: EditorSnapshot<TNode, TEdge>,\n\toptions?: Parameters<typeof planAgentCommand>[2]\n): AgentStep<TNode, TEdge>[] {\n\tconst command = toolCallToAgentCommand<TNode, TEdge>(name, args);\n\treturn command ? planAgentCommand(command, snapshot, options) : [];\n}\n","/**\n * Standard MCP Tool Definitions for @pixerate/editor.\n * Compatible with the Model Context Protocol (MCP) tool specification schema.\n */\n\nexport const MCP_TOOL_GET_EDITOR_STATE = {\n\tname: 'get_editor_state',\n\ttitle: 'Get editor state',\n\tannotations: {\n\t\ttitle: 'Get editor state',\n\t\treadOnlyHint: true,\n\t\tdestructiveHint: false,\n\t\tidempotentHint: true,\n\t\topenWorldHint: false\n\t},\n\tdescription:\n\t\t'Retrieves the current state of the document, variables, selection, and canvas graph (nodes and edges).',\n\tinputSchema: {\n\t\ttype: 'object',\n\t\tproperties: {\n\t\t\tincludeDocument: {\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdescription: 'Whether to include the prompt document text and variables (default: true).'\n\t\t\t},\n\t\t\tincludeCanvas: {\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdescription: 'Whether to include the canvas nodes and edges (default: true).'\n\t\t\t}\n\t\t}\n\t}\n} as const;\n\nexport const MCP_TOOL_EDIT_CANVAS = {\n\tname: 'edit_canvas',\n\ttitle: 'Edit the canvas',\n\tannotations: {\n\t\ttitle: 'Edit the canvas',\n\t\treadOnlyHint: false,\n\t\tdestructiveHint: true,\n\t\tidempotentHint: false,\n\t\topenWorldHint: false\n\t},\n\tdescription:\n\t\t'Applies high-level structural operations to the visual canvas (adding nodes, connecting edges, organizing layout, or moving elements).',\n\tinputSchema: {\n\t\ttype: 'object',\n\t\tproperties: {\n\t\t\toperation: {\n\t\t\t\ttype: 'string',\n\t\t\t\tenum: [\n\t\t\t\t\t'add_node',\n\t\t\t\t\t'remove_nodes',\n\t\t\t\t\t'connect',\n\t\t\t\t\t'update_node',\n\t\t\t\t\t'layout',\n\t\t\t\t\t'select',\n\t\t\t\t\t'highlight'\n\t\t\t\t],\n\t\t\t\tdescription: 'The canvas operation to execute.'\n\t\t\t},\n\t\t\tnode: {\n\t\t\t\ttype: 'object',\n\t\t\t\tdescription: 'Node definition when operation is add_node. Can omit position to auto-place.'\n\t\t\t},\n\t\t\tnearNodeId: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdescription: 'Anchor node ID to position beside using collision-aware placement.'\n\t\t\t},\n\t\t\tside: {\n\t\t\t\ttype: 'string',\n\t\t\t\tenum: ['top', 'right', 'bottom', 'left'],\n\t\t\t\tdescription: 'Side of the anchor node to place the new node beside.'\n\t\t\t},\n\t\t\tnodeIds: {\n\t\t\t\ttype: 'array',\n\t\t\t\titems: { type: 'string' },\n\t\t\t\tdescription: 'Array of node IDs for remove_nodes, select, or highlight.'\n\t\t\t},\n\t\t\tsource: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdescription: 'Source node ID for connect operation.'\n\t\t\t},\n\t\t\ttarget: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdescription: 'Target node ID for connect operation.'\n\t\t\t},\n\t\t\tlabel: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdescription: 'Optional edge label for connect operation.'\n\t\t\t},\n\t\t\tdirection: {\n\t\t\t\ttype: 'string',\n\t\t\t\tenum: ['LR', 'TB', 'RL', 'BT'],\n\t\t\t\tdescription: 'Layout direction (default LR).'\n\t\t\t},\n\t\t\tincremental: {\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdescription: 'Preserve existing node coordinates and blend layout (default true).'\n\t\t\t}\n\t\t},\n\t\trequired: ['operation']\n\t}\n} as const;\n\nexport const MCP_TOOL_EDIT_PROMPT = {\n\tname: 'edit_prompt',\n\ttitle: 'Edit the prompt',\n\tannotations: {\n\t\ttitle: 'Edit the prompt',\n\t\treadOnlyHint: false,\n\t\tdestructiveHint: true,\n\t\tidempotentHint: false,\n\t\topenWorldHint: false\n\t},\n\tdescription:\n\t\t'Applies edits to the prompt template document, including inserting text, replacing ranges, and setting variables.',\n\tinputSchema: {\n\t\ttype: 'object',\n\t\tproperties: {\n\t\t\toperation: {\n\t\t\t\ttype: 'string',\n\t\t\t\tenum: ['insert_text', 'replace_range', 'set_variable', 'select'],\n\t\t\t\tdescription: 'The prompt operation to execute.'\n\t\t\t},\n\t\t\ttext: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdescription: 'Text to insert or replace.'\n\t\t\t},\n\t\t\tat: {\n\t\t\t\ttype: 'number',\n\t\t\t\tdescription: 'Position to insert text at.'\n\t\t\t},\n\t\t\tfrom: {\n\t\t\t\ttype: 'number',\n\t\t\t\tdescription: 'Start offset for replace_range or select.'\n\t\t\t},\n\t\t\tto: {\n\t\t\t\ttype: 'number',\n\t\t\t\tdescription: 'End offset for replace_range or select.'\n\t\t\t},\n\t\t\tname: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdescription: 'Variable name for set_variable.'\n\t\t\t},\n\t\t\tvalue: {\n\t\t\t\tdescription: 'Variable value for set_variable.'\n\t\t\t}\n\t\t},\n\t\trequired: ['operation']\n\t}\n} as const;\n\nexport const MCP_TOOL_VIEW_EDITOR = {\n\tname: 'view_editor',\n\ttitle: 'View the editor',\n\tannotations: {\n\t\ttitle: 'View the editor',\n\t\treadOnlyHint: true,\n\t\tdestructiveHint: false,\n\t\tidempotentHint: true,\n\t\topenWorldHint: false\n\t},\n\tdescription:\n\t\t'Captures a visual image snapshot (JPEG or PNG) of the editor canvas or viewport for multimodal evaluation. Active agent cursor indicators are automatically excluded from the snapshot.',\n\tinputSchema: {\n\t\ttype: 'object',\n\t\tproperties: {\n\t\t\tscope: {\n\t\t\t\ttype: 'string',\n\t\t\t\tenum: ['viewport', 'canvas'],\n\t\t\t\tdescription: 'Whether to capture only the visible viewport or the full canvas bounding box (default: viewport).'\n\t\t\t},\n\t\t\tformat: {\n\t\t\t\ttype: 'string',\n\t\t\t\tenum: ['jpeg', 'png'],\n\t\t\t\tdescription: 'Image format of the base64 snapshot (default: jpeg).'\n\t\t\t},\n\t\t\tmaxEdge: {\n\t\t\t\ttype: 'integer',\n\t\t\t\tdescription: 'Maximum width or height dimension in pixels (default: 1024).'\n\t\t\t}\n\t\t}\n\t}\n} as const;\n\n/**\n * CSS selectors for ephemeral UI overlays (such as agent cursors, presence tags, and transient bubbles)\n * that should be excluded during canvas image export and visual snapshot generation.\n */\nexport const EXPORT_EXCLUDED_SELECTORS = [\n\t'.pixerate-presence',\n\t'.agent-presence',\n\t'.ursula-presence'\n] as const;\n\nexport const EDITOR_MCP_TOOLS = [\n\tMCP_TOOL_GET_EDITOR_STATE,\n\tMCP_TOOL_EDIT_CANVAS,\n\tMCP_TOOL_EDIT_PROMPT,\n\tMCP_TOOL_VIEW_EDITOR\n] as const;\n\n","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 { Editor } from '@tiptap/core';\nimport { plainTextToSlice, getEditorText } from '../serializers/plain-text.js';\nimport { getEditorMarkdown } from '../serializers/markdown.js';\nimport { TextSelection } from '@tiptap/pm/state';\nimport {\n\tTABLE_ACTIONS,\n\tgetTableActionState,\n\tgetTableState,\n\tisTableEnabled,\n\trunTableAction,\n\ttype TableAction\n} from '../extensions/table/actions.js';\nimport type { SpreadsheetController } from '../spreadsheet/controller.js';\nimport { colNameToIndex, indexToColName, isFormulaError } from '../spreadsheet/formula/evaluator.js';\nimport { planToolCall } from './planner.js';\nimport type { AgentTool, AgentToolProvider } from './registry.js';\nimport {\n\tMCP_TOOL_EDIT_CANVAS,\n\tMCP_TOOL_EDIT_PROMPT,\n\tMCP_TOOL_GET_EDITOR_STATE,\n\tMCP_TOOL_VIEW_EDITOR\n} from './tools.js';\nimport type { AgentStep, EditorSnapshot } from './types.js';\nimport type { CanvasEdge, CanvasNode } from '../canvas/types.js';\n\nexport interface ToolProviderOptions {\n\t/** Provider id (unique per registry). */\n\tid: string;\n\t/** Always prefix tool names with `<namespace>__`. */\n\tnamespace?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Rich-text editor provider\n// ---------------------------------------------------------------------------\n\n/** A TipTap editor, or anything exposing one as `.editor` (e.g. `EditorController`). */\nexport type RichTextToolTarget = Editor | { editor: Editor };\n\nconst toEditor = (target: RichTextToolTarget): Editor =>\n\t'commands' in target ? (target as Editor) : (target as { editor: Editor }).editor;\n\n/** Replaces `from..to` with literal text (HTML is not parsed; newlines split paragraphs). */\nfunction replaceWithText(editor: Editor, from: number, to: number, text: string) {\n\tconst { state, view } = editor;\n\tconst tr = /[\\r\\n]/.test(text)\n\t\t? state.tr.replace(from, to, plainTextToSlice(text, state.schema))\n\t\t: text\n\t\t\t? state.tr.insertText(text, from, to)\n\t\t\t: state.tr.delete(from, to);\n\tview.dispatch(tr.scrollIntoView());\n}\n\nfunction selectionInfo(editor: Editor) {\n\tconst { from, to } = editor.state.selection;\n\treturn { from, to, text: editor.state.doc.textBetween(from, to, '\\n') };\n}\n\n/**\n * Tools for a mounted rich-text editor: `get_text` (always), plus\n * `insert_text` and `replace_selection` while the editor is editable, and\n * `edit_table` when the schema has tables (`createRichTextPreset`'s `table`).\n * Positions are ProseMirror document positions (as in `selection.from`).\n * The provider re-announces its tool list when editability changes and\n * exposes no tools once the editor is destroyed.\n */\nexport function createRichTextToolProvider(\n\ttarget: RichTextToolTarget,\n\toptions: ToolProviderOptions\n): AgentToolProvider {\n\tconst editor = () => toEditor(target);\n\n\tconst getText: AgentTool = {\n\t\tname: 'get_text',\n\t\ttitle: 'Get document text',\n\t\tdescription:\n\t\t\t'Returns the document content (plain text by default, or HTML / markdown) and the current selection.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\tformat: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tenum: ['text', 'html', 'markdown'],\n\t\t\t\t\tdescription: 'Content format (default: text).'\n\t\t\t\t}\n\t\t\t},\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: {\n\t\t\ttitle: 'Get document text',\n\t\t\treadOnlyHint: true,\n\t\t\tdestructiveHint: false,\n\t\t\tidempotentHint: true,\n\t\t\topenWorldHint: false\n\t\t},\n\t\thandler: ({ format = 'text' }) => {\n\t\t\tconst ed = editor();\n\t\t\tconst content =\n\t\t\t\tformat === 'html' ? ed.getHTML() : format === 'markdown' ? getEditorMarkdown(ed) : getEditorText(ed);\n\t\t\treturn { format, content, selection: selectionInfo(ed), size: ed.state.doc.content.size };\n\t\t}\n\t};\n\n\tconst insertText: AgentTool = {\n\t\tname: 'insert_text',\n\t\ttitle: 'Insert text',\n\t\tdescription:\n\t\t\t'Inserts literal text (newlines start new paragraphs) at a document position, or at the cursor when `at` is omitted.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\ttext: { type: 'string', description: 'Text to insert.' },\n\t\t\t\tat: { type: 'integer', minimum: 0, description: 'Document position (default: the selection).' }\n\t\t\t},\n\t\t\trequired: ['text'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: {\n\t\t\ttitle: 'Insert text',\n\t\t\treadOnlyHint: false,\n\t\t\tdestructiveHint: false,\n\t\t\tidempotentHint: false,\n\t\t\topenWorldHint: false\n\t\t},\n\t\thandler: ({ text, at }) => {\n\t\t\tconst ed = editor();\n\t\t\tconst size = ed.state.doc.content.size;\n\t\t\tif (at !== undefined && at > size) {\n\t\t\t\tthrow new Error(`Position ${at} is outside the document (size ${size}).`);\n\t\t\t}\n\t\t\tconst { from, to } = ed.state.selection;\n\t\t\treplaceWithText(ed, at ?? from, at ?? to, text);\n\t\t\treturn { inserted: text.length, selection: selectionInfo(ed) };\n\t\t}\n\t};\n\n\tconst replaceSelection: AgentTool = {\n\t\tname: 'replace_selection',\n\t\ttitle: 'Replace selection',\n\t\tdescription: 'Replaces the selected content with literal text (an empty string deletes the selection).',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: { text: { type: 'string', description: 'Replacement text.' } },\n\t\t\trequired: ['text'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: {\n\t\t\ttitle: 'Replace selection',\n\t\t\treadOnlyHint: false,\n\t\t\tdestructiveHint: true,\n\t\t\tidempotentHint: false,\n\t\t\topenWorldHint: false\n\t\t},\n\t\thandler: ({ text }) => {\n\t\t\tconst ed = editor();\n\t\t\tconst { from, to } = ed.state.selection;\n\t\t\treplaceWithText(ed, from, to, text);\n\t\t\treturn { replaced: { from, to }, selection: selectionInfo(ed) };\n\t\t}\n\t};\n\n\tconst editTable: AgentTool = {\n\t\tname: 'edit_table',\n\t\ttitle: 'Edit tables',\n\t\tdescription:\n\t\t\t'Inserts a table or edits the table at the cursor (or at `at`): add/delete rows and columns, delete the table, ' +\n\t\t\t'merge/split cells, toggle header row/column/cell, move between cells, set cell alignment or background. ' +\n\t\t\t'Returns the table size and the cursor cell afterwards.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\toperation: { type: 'string', enum: TABLE_ACTIONS.map((a) => a.action), description: 'Table operation.' },\n\t\t\t\tat: { type: 'integer', minimum: 0, description: 'Document position to place the cursor first (e.g. inside a cell).' },\n\t\t\t\trows: { type: 'integer', minimum: 1, maximum: 100, description: 'insertTable: rows (default 3).' },\n\t\t\t\tcols: { type: 'integer', minimum: 1, maximum: 50, description: 'insertTable: columns (default 3).' },\n\t\t\t\twithHeaderRow: { type: 'boolean', description: 'insertTable: first row is a header row (default true).' },\n\t\t\t\talign: {\n\t\t\t\t\ttype: ['string', 'null'],\n\t\t\t\t\tenum: ['left', 'center', 'right', 'justify', null],\n\t\t\t\t\tdescription: 'setCellAlignment: alignment, or null to clear.'\n\t\t\t\t},\n\t\t\t\tcolor: { type: ['string', 'null'], description: 'setCellBackground: CSS color, or null to clear.' }\n\t\t\t},\n\t\t\trequired: ['operation'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: {\n\t\t\ttitle: 'Edit tables',\n\t\t\treadOnlyHint: false,\n\t\t\tdestructiveHint: true,\n\t\t\tidempotentHint: false,\n\t\t\topenWorldHint: false\n\t\t},\n\t\thandler: ({ operation, at, ...params }) => {\n\t\t\tconst ed = editor();\n\t\t\tif (at !== undefined) {\n\t\t\t\tconst size = ed.state.doc.content.size;\n\t\t\t\tif (at > size) throw new Error(`Position ${at} is outside the document (size ${size}).`);\n\t\t\t\ted.view.dispatch(ed.state.tr.setSelection(TextSelection.near(ed.state.doc.resolve(at))));\n\t\t\t}\n\t\t\tconst action = operation as TableAction;\n\t\t\tconst state = getTableActionState(ed, action, params);\n\t\t\tif (state !== true) throw new Error(state);\n\t\t\trunTableAction(ed, action, params);\n\t\t\tconst table = getTableState(ed);\n\t\t\treturn {\n\t\t\t\toperation,\n\t\t\t\ttable: table.inTable\n\t\t\t\t\t? { rows: table.rows, columns: table.columns, row: table.row, column: table.column }\n\t\t\t\t\t: null,\n\t\t\t\tselection: selectionInfo(ed)\n\t\t\t};\n\t\t}\n\t};\n\n\treturn {\n\t\tid: options.id,\n\t\tnamespace: options.namespace,\n\t\ttools: () => {\n\t\t\tconst ed = editor();\n\t\t\tif (!ed || ed.isDestroyed) return [];\n\t\t\tif (!ed.isEditable) return [getText];\n\t\t\treturn isTableEnabled(ed)\n\t\t\t\t? [getText, insertText, replaceSelection, editTable]\n\t\t\t\t: [getText, insertText, replaceSelection];\n\t\t},\n\t\tsubscribe: (notify) => {\n\t\t\tconst ed = editor();\n\t\t\t// `setEditable` emits `update`; the registry ignores signals that don't change the list.\n\t\t\ted.on('update', notify);\n\t\t\ted.on('destroy', notify);\n\t\t\treturn () => {\n\t\t\t\ted.off('update', notify);\n\t\t\t\ted.off('destroy', notify);\n\t\t\t};\n\t\t}\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Spreadsheet provider\n// ---------------------------------------------------------------------------\n\nconst CELL_REF_REGEX = /^\\$?([A-Za-z]{1,3})\\$?(\\d{1,7})$/;\n\nfunction parseCell(ref: string): { col: number; row: number } {\n\tconst match = CELL_REF_REGEX.exec(ref.trim());\n\tif (!match) throw new Error(`Invalid cell reference \"${ref}\". Use A1 notation, e.g. \"B3\".`);\n\treturn { col: colNameToIndex(match[1].toUpperCase()), row: parseInt(match[2], 10) - 1 };\n}\n\n/**\n * Tools for a spreadsheet controller: `get_range` (A1 notation, values and raw\n * input) and `set_cell` (raw input; values starting with `=` are formulas).\n */\nexport function createSpreadsheetToolProvider(\n\tcontroller: SpreadsheetController,\n\toptions: ToolProviderOptions\n): AgentToolProvider {\n\tconst lookup = (row: number, col: number) => {\n\t\tconst rowDef = controller.document.rows[row];\n\t\tconst colDef = controller.document.columns[col];\n\t\treturn rowDef && colDef ? { rowDef, colDef } : null;\n\t};\n\n\tconst getRange: AgentTool = {\n\t\tname: 'get_range',\n\t\ttitle: 'Read cells',\n\t\tdescription:\n\t\t\t'Reads a cell range in A1 notation (e.g. \"A1:C5\" or \"B2\") and returns computed values, raw input and errors.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\trange: { type: 'string', description: 'A1-notation cell or range.' }\n\t\t\t},\n\t\t\trequired: ['range'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: {\n\t\t\ttitle: 'Read cells',\n\t\t\treadOnlyHint: true,\n\t\t\tdestructiveHint: false,\n\t\t\tidempotentHint: true,\n\t\t\topenWorldHint: false\n\t\t},\n\t\thandler: ({ range }) => {\n\t\t\tconst [startRef, endRef = startRef] = String(range).split(':');\n\t\t\tconst start = parseCell(startRef);\n\t\t\tconst end = parseCell(endRef);\n\t\t\tconst rowCount = controller.document.rows.length;\n\t\t\tconst colCount = controller.document.columns.length;\n\t\t\tconst r0 = Math.min(start.row, end.row);\n\t\t\tconst r1 = Math.min(Math.max(start.row, end.row), rowCount - 1);\n\t\t\tconst c0 = Math.min(start.col, end.col);\n\t\t\tconst c1 = Math.min(Math.max(start.col, end.col), colCount - 1);\n\t\t\tconst values: unknown[][] = [];\n\t\t\tconst raw: string[][] = [];\n\t\t\tconst errors: Array<{ cell: string; error: string }> = [];\n\t\t\tfor (let r = r0; r <= r1; r++) {\n\t\t\t\tconst valueRow: unknown[] = [];\n\t\t\t\tconst rawRow: string[] = [];\n\t\t\t\tfor (let c = c0; c <= c1; c++) {\n\t\t\t\t\tconst found = lookup(r, c)!;\n\t\t\t\t\tconst cell = controller.getCell(found.rowDef.id, found.colDef.id);\n\t\t\t\t\tvalueRow.push(cell.error ?? cell.value);\n\t\t\t\t\trawRow.push(cell.raw);\n\t\t\t\t\tconst error = cell.error ?? (isFormulaError(cell.value) ? cell.value : undefined);\n\t\t\t\t\tif (error) errors.push({ cell: `${indexToColName(c)}${r + 1}`, error });\n\t\t\t\t}\n\t\t\t\tvalues.push(valueRow);\n\t\t\t\traw.push(rawRow);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\trange: values.length && values[0].length ? `${indexToColName(c0)}${r0 + 1}:${indexToColName(c1)}${r1 + 1}` : null,\n\t\t\t\tvalues,\n\t\t\t\traw,\n\t\t\t\terrors,\n\t\t\t\tsheet: { rows: rowCount, columns: colCount }\n\t\t\t};\n\t\t}\n\t};\n\n\tconst setCell: AgentTool = {\n\t\tname: 'set_cell',\n\t\ttitle: 'Set a cell',\n\t\tdescription: 'Sets the raw input of one cell (A1 notation). Values starting with \"=\" are formulas.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\tcell: { type: 'string', description: 'A1-notation cell, e.g. \"B3\".' },\n\t\t\t\tvalue: { type: ['string', 'number', 'boolean'], description: 'Raw cell input.' }\n\t\t\t},\n\t\t\trequired: ['cell', 'value'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: {\n\t\t\ttitle: 'Set a cell',\n\t\t\treadOnlyHint: false,\n\t\t\tdestructiveHint: true,\n\t\t\tidempotentHint: true,\n\t\t\topenWorldHint: false\n\t\t},\n\t\thandler: ({ cell, value }) => {\n\t\t\tconst { row, col } = parseCell(cell);\n\t\t\tconst found = lookup(row, col);\n\t\t\tif (!found) throw new Error(`Cell ${cell} is outside the sheet.`);\n\t\t\tconst { rowDef, colDef } = found;\n\t\t\tif (colDef.readOnly || controller.getCell(rowDef.id, colDef.id).readOnly || colDef.type === 'formula') {\n\t\t\t\tthrow new Error(`Cell ${cell} is read-only.`);\n\t\t\t}\n\t\t\tcontroller.setCellValue(rowDef.id, colDef.id, String(value));\n\t\t\tconst updated = controller.getCell(rowDef.id, colDef.id);\n\t\t\treturn { cell: cell.toUpperCase(), raw: updated.raw, value: updated.error ?? updated.value };\n\t\t}\n\t};\n\n\treturn { id: options.id, namespace: options.namespace, tools: [getRange, setCell] };\n}\n\n// ---------------------------------------------------------------------------\n// Static editor tools (tools.ts) as a provider\n// ---------------------------------------------------------------------------\n\nexport interface EditorMcpToolProviderOptions<\n\tTNode extends CanvasNode = CanvasNode,\n\tTEdge extends CanvasEdge = CanvasEdge\n> extends ToolProviderOptions {\n\t/** Current editor / canvas state. */\n\tgetSnapshot: () => EditorSnapshot<TNode, TEdge>;\n\t/** Applies planned steps (e.g. via your canvas runes / editor controller). */\n\tapplySteps: (steps: AgentStep<TNode, TEdge>[]) => void | Promise<void>;\n\t/** Optional `view_editor` implementation; the tool is only exposed when provided. */\n\tcaptureView?: (args: { scope?: 'viewport' | 'canvas'; format?: 'jpeg' | 'png'; maxEdge?: number }) =>\n\t\t| Promise<{ data: string; mimeType: string }>\n\t\t| { data: string; mimeType: string };\n\t/** Options forwarded to the planner. */\n\tplannerOptions?: Parameters<typeof planToolCall>[3];\n}\n\n/**\n * Exposes the static MCP tools from `tools.ts` (`get_editor_state`,\n * `edit_canvas`, `edit_prompt`, `view_editor`) through a `ToolRegistry`,\n * planning edits with `planToolCall` and handing the steps to `applySteps`.\n */\nexport function createEditorMcpToolProvider<\n\tTNode extends CanvasNode = CanvasNode,\n\tTEdge extends CanvasEdge = CanvasEdge\n>(options: EditorMcpToolProviderOptions<TNode, TEdge>): AgentToolProvider {\n\tconst edit = (name: string) => async (args: Record<string, any>) => {\n\t\tconst steps = planToolCall<TNode, TEdge>(name, args, options.getSnapshot(), options.plannerOptions);\n\t\tif (steps.length === 0) {\n\t\t\tthrow new Error(`Operation \"${args.operation}\" is missing required arguments.`);\n\t\t}\n\t\tawait options.applySteps(steps);\n\t\treturn { applied: steps.length, steps: steps.map((s) => s.type) };\n\t};\n\n\tconst tools: AgentTool[] = [\n\t\t{\n\t\t\t...MCP_TOOL_GET_EDITOR_STATE,\n\t\t\thandler: ({ includeDocument = true, includeCanvas = true }) => {\n\t\t\t\tconst snapshot = options.getSnapshot();\n\t\t\t\treturn {\n\t\t\t\t\t...(includeDocument && snapshot.document ? { document: snapshot.document } : {}),\n\t\t\t\t\t...(includeCanvas && snapshot.canvas ? { canvas: snapshot.canvas } : {})\n\t\t\t\t};\n\t\t\t}\n\t\t},\n\t\t{ ...MCP_TOOL_EDIT_CANVAS, handler: edit(MCP_TOOL_EDIT_CANVAS.name) },\n\t\t{ ...MCP_TOOL_EDIT_PROMPT, handler: edit(MCP_TOOL_EDIT_PROMPT.name) }\n\t] as AgentTool[];\n\n\tif (options.captureView) {\n\t\tconst capture = options.captureView;\n\t\ttools.push({\n\t\t\t...MCP_TOOL_VIEW_EDITOR,\n\t\t\thandler: async (args) => {\n\t\t\t\tconst image = await capture(args);\n\t\t\t\treturn { content: [{ type: 'image', data: image.data, mimeType: image.mimeType }] };\n\t\t\t}\n\t\t} as AgentTool);\n\t}\n\n\treturn { id: options.id, namespace: options.namespace, tools };\n}\n","import type { ComponentCommandTarget } from '../commands/builtins.js';\nimport type { AgentTool, AgentToolProvider } from './registry.js';\nimport type { ToolProviderOptions } from './providers.js';\n\nconst IDS = { type: 'array', items: { type: 'string' }, description: 'Node ids (default: the selection).' } as const;\nconst ID = { type: 'string', description: 'An instance, or a layer inside one (default: the first selected node).' } as const;\n\nconst READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false } as const;\nconst WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false } as const;\n\ntype Outcome = { ok: true; ids: string[] } | { ok: false; reason: string };\nconst check = (result: Outcome) => {\n\tif (!result.ok) throw new Error(result.reason);\n\treturn { ids: result.ids };\n};\n\n/**\n * Agent tools for canvas components and instances, backed by a components controller\n * (`createCanvasComponentsController`): `list_components`, `inspect_instance`,\n * `create_component`, `combine_as_variants`, `create_instance`, `set_instance_properties`\n * (variants and component properties), `swap_instance`, `reset_overrides`, `push_overrides`,\n * `detach_instance`, `go_to_main_component` and `restore_main_component`. Refused actions come\n * back as tool errors carrying the reason.\n */\nexport function createCanvasComponentToolProvider(\n\tcontroller: ComponentCommandTarget,\n\toptions: ToolProviderOptions = { id: 'canvas-components' }\n): AgentToolProvider {\n\tconst tool = (\n\t\tname: string,\n\t\tdescription: string,\n\t\tproperties: Record<string, unknown>,\n\t\thandler: AgentTool['handler'],\n\t\textra: { required?: string[]; readOnly?: boolean } = {}\n\t): AgentTool => ({\n\t\tname,\n\t\tdescription,\n\t\tinputSchema: { type: 'object', properties: properties as never, ...(extra.required ? { required: extra.required } : {}), additionalProperties: false },\n\t\tannotations: extra.readOnly ? READ : WRITE,\n\t\thandler\n\t});\n\tconst tools: AgentTool[] = [\n\t\ttool('list_components', 'Lists components (id, name, variant values, instance count) and component sets with their variant options.', {}, () => controller.list(), {\n\t\t\treadOnly: true\n\t\t}),\n\t\ttool(\n\t\t\t'inspect_instance',\n\t\t\t'Describes an instance: its main component, variant, component property values (with types) and the overrides of its layers.',\n\t\t\t{ id: ID },\n\t\t\t({ id }) => {\n\t\t\t\tconst info = controller.inspect(id);\n\t\t\t\tif (!info) throw new Error('Not an instance (or a layer inside one).');\n\t\t\t\treturn info;\n\t\t\t},\n\t\t\t{ readOnly: true }\n\t\t),\n\t\ttool('create_component', 'Turns the given frame into a main component, or wraps the given layers in a new one.', { ids: IDS }, ({ ids }) =>\n\t\t\tcheck(controller.createComponent(ids))\n\t\t),\n\t\ttool('combine_as_variants', 'Wraps sibling components in a component set (variants named \"Property=Value, …\").', { ids: IDS }, ({ ids }) =>\n\t\t\tcheck(controller.combineAsVariants(ids))\n\t\t),\n\t\ttool(\n\t\t\t'create_instance',\n\t\t\t'Places an instance of a component or component set, optionally inside a frame, at a position, with property values.',\n\t\t\t{\n\t\t\t\tcomponentId: { type: 'string' },\n\t\t\t\tparentId: { type: 'string' },\n\t\t\t\tx: { type: 'number' },\n\t\t\t\ty: { type: 'number' },\n\t\t\t\tproperties: { type: 'object', additionalProperties: true, description: 'Variant and component property values.' }\n\t\t\t},\n\t\t\t({ componentId, parentId, x, y, properties }) =>\n\t\t\t\tcheck(\n\t\t\t\t\tcontroller.createInstance(componentId, {\n\t\t\t\t\t\t...(parentId !== undefined ? { parentId } : {}),\n\t\t\t\t\t\t...(x !== undefined || y !== undefined ? { position: { x: x ?? 0, y: y ?? 0 } } : {}),\n\t\t\t\t\t\t...(properties ? { properties } : {})\n\t\t\t\t\t})\n\t\t\t\t),\n\t\t\t{ required: ['componentId'] }\n\t\t),\n\t\ttool(\n\t\t\t'set_instance_properties',\n\t\t\t'Sets property values of instances: variant properties switch the variant (keeping compatible overrides), booleans toggle layers, text sets text, instance swap takes a component id.',\n\t\t\t{ properties: { type: 'object', additionalProperties: true }, ids: IDS },\n\t\t\t({ properties, ids }) => check(controller.setInstanceProperties(properties, ids)),\n\t\t\t{ required: ['properties'] }\n\t\t),\n\t\ttool(\n\t\t\t'swap_instance',\n\t\t\t'Makes instances show another component (or a set’s default variant), keeping overrides of layers with matching names.',\n\t\t\t{ componentId: { type: 'string' }, ids: IDS },\n\t\t\t({ componentId, ids }) => check(controller.swapInstance(componentId, ids)),\n\t\t\t{ required: ['componentId'] }\n\t\t),\n\t\ttool(\n\t\t\t'reset_overrides',\n\t\t\t'Resets overrides: of a whole instance (default), of one layer, or one override group such as \"data.label\" or \"shape.fill\".',\n\t\t\t{ id: ID, group: { type: 'string' } },\n\t\t\t({ id, group }) => check(controller.resetOverrides(id, group))\n\t\t),\n\t\ttool('push_overrides', 'Copies an instance’s overrides to its main component (and so to every other instance).', { id: ID }, ({ id }) =>\n\t\t\tcheck(controller.pushOverrides(id))\n\t\t),\n\t\ttool('detach_instance', 'Turns instances into plain frames that keep their current look.', { ids: IDS }, ({ ids }) => check(controller.detachInstance(ids))),\n\t\ttool('go_to_main_component', 'Selects the main component of an instance and returns its id.', { id: ID }, ({ id }) => {\n\t\t\tconst main = controller.goToMainComponent(id);\n\t\t\tif (!main) throw new Error('The main component was not found.');\n\t\t\treturn { id: main };\n\t\t}),\n\t\ttool('restore_main_component', 'Turns an instance whose main component was deleted back into the main component.', { id: ID }, ({ id }) =>\n\t\t\tcheck(controller.restoreMainComponent(id))\n\t\t)\n\t];\n\treturn { id: options.id, namespace: options.namespace, tools };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/editor/editor/packages/core/dist/agent/index.cjs","../../src/agent/planner.ts","../../src/agent/tools.ts","../../src/agent/registry.ts","../../src/agent/providers.ts","../../src/agent/componentTools.ts"],"names":[],"mappings":"AAAA;AACE;AACF,yDAA8B;AAC9B;AACE;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACF,yDAA8B;AAC9B,iCAA8B;AAC9B,iCAA8B;AAC9B;AACE;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACF,yDAA8B;AAC9B,iCAA8B;AAC9B;AACA;ACxBO,SAAS,aAAA,CAAc,IAAA,EAAuC;AACpE,EAAA,OAAA,CAAQ,IAAA,EAAM;AAAA,IACb,KAAK,KAAA;AAAA,IACL,KAAK,OAAA;AACJ,MAAA,OAAO,OAAA;AAAA,IACR,KAAK,QAAA;AAAA,IACL,KAAK,OAAA;AACJ,MAAA,OAAO,OAAA;AAAA,IACR,KAAK,MAAA;AACJ,MAAA,OAAO,MAAA;AAAA,IACR,KAAK,OAAA;AAAA,IACL,OAAA;AACC,MAAA,OAAO,OAAA;AAAA,EACT;AACD;AAKO,SAAS,gBAAA,CAIf,OAAA,EACA,QAAA,EACA,QAAA,EAGI,CAAC,CAAA,EACuB;AAC5B,EAAA,MAAM,gBAAA,mBAAkB,OAAA,CAAQ,eAAA,UAAmB,EAAE,KAAA,EAAO,GAAA,EAAK,MAAA,EAAQ,GAAG,GAAA;AAC5E,EAAA,MAAM,MAAA,mBAAQ,OAAA,CAAQ,WAAA,UAAA,CAAgB,CAAA,EAAA,GAAM,CAAA,KAAA,EAAQ,IAAA,CAAK,MAAA,CAAO,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,SAAA,CAAU,CAAA,EAAG,CAAC,CAAC,CAAA,CAAA;AACpB,EAAA;AAEjC,EAAA;AACA,EAAA;AAEnB,EAAA;AACG,IAAA;AACA,MAAA;AAInB,MAAA;AAGM,MAAA;AAC4B,QAAA;AACd,QAAA;AAC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G;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/editor/editor/packages/core/dist/agent/index.cjs","sourcesContent":[null,"import { ensureLayout, getLayoutedNodes, placeBeside } from '../canvas/layout.js';\nimport type { CanvasEdge, CanvasNode, Rect, Side } from '../canvas/types.js';\nimport type { AgentCommand, AgentStep, EditorSnapshot } from './types.js';\n\n/**\n * Normalizes a placement side from either the planner vocabulary (`right | below | left | above`)\n * or the MCP tool schema vocabulary (`top | right | bottom | left`). Unknown values fall back to `right`.\n */\nexport function normalizeSide(side: string | undefined | null): Side {\n\tswitch (side) {\n\t\tcase 'top':\n\t\tcase 'above':\n\t\t\treturn 'above';\n\t\tcase 'bottom':\n\t\tcase 'below':\n\t\t\treturn 'below';\n\t\tcase 'left':\n\t\t\treturn 'left';\n\t\tcase 'right':\n\t\tdefault:\n\t\t\treturn 'right';\n\t}\n}\n\n/**\n * Plans a sequence of atomic execution steps from a high-level agent command.\n */\nexport function planAgentCommand<\n\tTNode extends CanvasNode = CanvasNode,\n\tTEdge extends CanvasEdge = CanvasEdge\n>(\n\tcommand: AgentCommand<TNode, TEdge>,\n\tsnapshot: EditorSnapshot<TNode, TEdge>,\n\toptions: {\n\t\tdefaultNodeSize?: { width: number; height: number };\n\t\tidGenerator?: () => string;\n\t} = {}\n): AgentStep<TNode, TEdge>[] {\n\tconst defaultNodeSize = options.defaultNodeSize ?? { width: 200, height: 60 };\n\tconst idGen = options.idGenerator ?? (() => `node-${Math.random().toString(36).substring(2, 9)}`);\n\tconst edgeIdGen = () => `edge-${Math.random().toString(36).substring(2, 9)}`;\n\n\tconst nodes = snapshot.canvas?.nodes ?? [];\n\tconst edges = snapshot.canvas?.edges ?? [];\n\n\tswitch (command.type) {\n\t\tcase 'canvas:add_node': {\n\t\t\tlet pos = command.node.position;\n\t\t\t// Only anchor to (and connect from) a node that actually exists.\n\t\t\tconst anchorId =\n\t\t\t\tcommand.nearNodeId && nodes.some((n) => n.id === command.nearNodeId)\n\t\t\t\t\t? command.nearNodeId\n\t\t\t\t\t: undefined;\n\n\t\t\tif (!pos) {\n\t\t\t\tconst rects: Record<string, Rect> = {};\n\t\t\t\tfor (const n of nodes) {\n\t\t\t\t\trects[n.id] = {\n\t\t\t\t\t\tx: n.position.x,\n\t\t\t\t\t\ty: n.position.y,\n\t\t\t\t\t\twidth: n.measured?.width ?? (n as any).width ?? defaultNodeSize.width,\n\t\t\t\t\t\theight: n.measured?.height ?? (n as any).height ?? defaultNodeSize.height\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (anchorId) {\n\t\t\t\t\t// Use collision-aware directional placement\n\t\t\t\t\tpos = placeBeside(rects, defaultNodeSize, normalizeSide(command.side), anchorId);\n\t\t\t\t} else if (nodes.length > 0) {\n\t\t\t\t\t// Default beside the last node\n\t\t\t\t\tconst lastNode = nodes[nodes.length - 1];\n\t\t\t\t\tpos = placeBeside(rects, defaultNodeSize, 'right', lastNode.id);\n\t\t\t\t} else {\n\t\t\t\t\tpos = { x: 100, y: 100 };\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst fullNode: TNode = {\n\t\t\t\t...command.node,\n\t\t\t\tid: command.node.id || idGen(),\n\t\t\t\tposition: pos\n\t\t\t} as TNode;\n\n\t\t\tconst steps: AgentStep<TNode, TEdge>[] = [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:canvas_add_node',\n\t\t\t\t\tnode: fullNode\n\t\t\t\t}\n\t\t\t];\n\n\t\t\t// If attached to nearNode, optionally automatically connect\n\t\t\tif (anchorId) {\n\t\t\t\tsteps.push({\n\t\t\t\t\ttype: 'step:canvas_add_edge',\n\t\t\t\t\tedge: {\n\t\t\t\t\t\tid: edgeIdGen(),\n\t\t\t\t\t\tsource: anchorId,\n\t\t\t\t\t\ttarget: fullNode.id\n\t\t\t\t\t} as TEdge\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn steps;\n\t\t}\n\n\t\tcase 'canvas:remove_nodes': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:canvas_remove_nodes',\n\t\t\t\t\tnodeIds: command.nodeIds\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'canvas:connect': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:canvas_add_edge',\n\t\t\t\t\tedge: {\n\t\t\t\t\t\tid: edgeIdGen(),\n\t\t\t\t\t\tsource: command.source,\n\t\t\t\t\t\ttarget: command.target,\n\t\t\t\t\t\tlabel: command.label\n\t\t\t\t\t} as TEdge\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'canvas:update_node': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:canvas_update_node',\n\t\t\t\t\tid: command.id,\n\t\t\t\t\tdata: command.data\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'canvas:layout': {\n\t\t\tconst dir = command.direction ?? 'LR';\n\t\t\tlet layouted: TNode[];\n\n\t\t\t// Matches the MCP tool schema: `incremental` defaults to true.\n\t\t\tif (command.incremental ?? true) {\n\t\t\t\tconst stored: Record<string, { x: number; y: number }> = {};\n\t\t\t\tfor (const n of nodes) {\n\t\t\t\t\tif (n.position && (n.position.x !== 0 || n.position.y !== 0)) {\n\t\t\t\t\t\tstored[n.id] = { ...n.position };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlayouted = ensureLayout(nodes, edges, {\n\t\t\t\t\tdirection: dir,\n\t\t\t\t\tstoredPositions: stored\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tlayouted = getLayoutedNodes(nodes, edges, undefined, { direction: dir });\n\t\t\t}\n\n\t\t\tconst positions: Record<string, { x: number; y: number }> = {};\n\t\t\tfor (const node of layouted) {\n\t\t\t\tpositions[node.id] = { ...node.position };\n\t\t\t}\n\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:canvas_move_nodes',\n\t\t\t\t\tpositions\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'canvas:select': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:canvas_select',\n\t\t\t\t\tnodeIds: command.nodeIds\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'canvas:highlight': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:canvas_highlight',\n\t\t\t\t\tnodeIds: command.nodeIds,\n\t\t\t\t\tcolor: command.color ?? '#3b82f6',\n\t\t\t\t\tdurationMs: command.durationMs ?? 2000\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'prompt:insert_text': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:prompt_insert',\n\t\t\t\t\ttext: command.text,\n\t\t\t\t\tat: command.at\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'prompt:replace_range': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:prompt_replace',\n\t\t\t\t\tfrom: command.from,\n\t\t\t\t\tto: command.to,\n\t\t\t\t\ttext: command.text\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'prompt:set_variable': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:prompt_set_variable',\n\t\t\t\t\tname: command.name,\n\t\t\t\t\tvalue: command.value\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'prompt:select': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:prompt_select',\n\t\t\t\t\tfrom: command.from,\n\t\t\t\t\tto: command.to\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'choreography:say': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:say',\n\t\t\t\t\ttext: command.text,\n\t\t\t\t\tatNodeId: command.atNodeId,\n\t\t\t\t\tposition: command.position\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'choreography:wait': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:wait',\n\t\t\t\t\tms: command.ms\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tcase 'tool:call': {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'step:tool_call',\n\t\t\t\t\tname: command.name,\n\t\t\t\t\targuments: command.arguments ?? {}\n\t\t\t\t}\n\t\t\t];\n\t\t}\n\n\t\tdefault: {\n\t\t\treturn [];\n\t\t}\n\t}\n}\n\n/**\n * Converts an MCP tool call into a planner command. `edit_canvas` and\n * `edit_prompt` (see `tools.ts`) map to canvas/prompt commands using the MCP\n * schema's vocabulary; every other tool, including dynamic `ToolRegistry`\n * tools, becomes a `tool:call` command. Returns `null` when a static tool's\n * arguments are missing what the operation needs.\n */\nexport function toolCallToAgentCommand<\n\tTNode extends CanvasNode = CanvasNode,\n\tTEdge extends CanvasEdge = CanvasEdge\n>(name: string, args: Record<string, any> = {}): AgentCommand<TNode, TEdge> | null {\n\tconst ids = (value: unknown): string[] | null =>\n\t\tArray.isArray(value) && value.every((v) => typeof v === 'string') ? value : null;\n\tconst num = (value: unknown) => typeof value === 'number' && Number.isFinite(value);\n\n\tif (name === 'edit_canvas') {\n\t\tswitch (args.operation) {\n\t\t\tcase 'add_node':\n\t\t\t\treturn args.node && typeof args.node === 'object'\n\t\t\t\t\t? { type: 'canvas:add_node', node: args.node, nearNodeId: args.nearNodeId, side: args.side }\n\t\t\t\t\t: null;\n\t\t\tcase 'remove_nodes':\n\t\t\t\treturn ids(args.nodeIds) ? { type: 'canvas:remove_nodes', nodeIds: args.nodeIds } : null;\n\t\t\tcase 'connect':\n\t\t\t\treturn typeof args.source === 'string' && typeof args.target === 'string'\n\t\t\t\t\t? { type: 'canvas:connect', source: args.source, target: args.target, label: args.label }\n\t\t\t\t\t: null;\n\t\t\tcase 'update_node': {\n\t\t\t\tconst id = args.node?.id ?? args.id;\n\t\t\t\treturn typeof id === 'string'\n\t\t\t\t\t? { type: 'canvas:update_node', id, data: args.node?.data ?? args.data ?? {} }\n\t\t\t\t\t: null;\n\t\t\t}\n\t\t\tcase 'layout':\n\t\t\t\treturn { type: 'canvas:layout', direction: args.direction, incremental: args.incremental };\n\t\t\tcase 'select':\n\t\t\t\treturn ids(args.nodeIds) ? { type: 'canvas:select', nodeIds: args.nodeIds } : null;\n\t\t\tcase 'highlight':\n\t\t\t\treturn ids(args.nodeIds) ? { type: 'canvas:highlight', nodeIds: args.nodeIds } : null;\n\t\t\tdefault:\n\t\t\t\treturn null;\n\t\t}\n\t}\n\n\tif (name === 'edit_prompt') {\n\t\tswitch (args.operation) {\n\t\t\tcase 'insert_text':\n\t\t\t\treturn typeof args.text === 'string'\n\t\t\t\t\t? { type: 'prompt:insert_text', text: args.text, at: num(args.at) ? args.at : undefined }\n\t\t\t\t\t: null;\n\t\t\tcase 'replace_range':\n\t\t\t\treturn typeof args.text === 'string' && num(args.from) && num(args.to)\n\t\t\t\t\t? { type: 'prompt:replace_range', from: args.from, to: args.to, text: args.text }\n\t\t\t\t\t: null;\n\t\t\tcase 'set_variable':\n\t\t\t\treturn typeof args.name === 'string'\n\t\t\t\t\t? { type: 'prompt:set_variable', name: args.name, value: args.value }\n\t\t\t\t\t: null;\n\t\t\tcase 'select':\n\t\t\t\treturn num(args.from) && num(args.to) ? { type: 'prompt:select', from: args.from, to: args.to } : null;\n\t\t\tdefault:\n\t\t\t\treturn null;\n\t\t}\n\t}\n\n\treturn { type: 'tool:call', name, arguments: args };\n}\n\n/**\n * Plans the steps for an MCP tool call: static editor tools are planned like\n * the equivalent commands, any other tool becomes a `step:tool_call` to be\n * executed with `ToolRegistry.callTool`. Returns `[]` for invalid arguments.\n */\nexport function planToolCall<\n\tTNode extends CanvasNode = CanvasNode,\n\tTEdge extends CanvasEdge = CanvasEdge\n>(\n\tname: string,\n\targs: Record<string, any>,\n\tsnapshot: EditorSnapshot<TNode, TEdge>,\n\toptions?: Parameters<typeof planAgentCommand>[2]\n): AgentStep<TNode, TEdge>[] {\n\tconst command = toolCallToAgentCommand<TNode, TEdge>(name, args);\n\treturn command ? planAgentCommand(command, snapshot, options) : [];\n}\n","/**\n * Standard MCP Tool Definitions for @pixerate/editor.\n * Compatible with the Model Context Protocol (MCP) tool specification schema.\n */\n\nexport const MCP_TOOL_GET_EDITOR_STATE = {\n\tname: 'get_editor_state',\n\ttitle: 'Get editor state',\n\tannotations: {\n\t\ttitle: 'Get editor state',\n\t\treadOnlyHint: true,\n\t\tdestructiveHint: false,\n\t\tidempotentHint: true,\n\t\topenWorldHint: false\n\t},\n\tdescription:\n\t\t'Retrieves the current state of the document, variables, selection, and canvas graph (nodes and edges).',\n\tinputSchema: {\n\t\ttype: 'object',\n\t\tproperties: {\n\t\t\tincludeDocument: {\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdescription: 'Whether to include the prompt document text and variables (default: true).'\n\t\t\t},\n\t\t\tincludeCanvas: {\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdescription: 'Whether to include the canvas nodes and edges (default: true).'\n\t\t\t}\n\t\t}\n\t}\n} as const;\n\nexport const MCP_TOOL_EDIT_CANVAS = {\n\tname: 'edit_canvas',\n\ttitle: 'Edit the canvas',\n\tannotations: {\n\t\ttitle: 'Edit the canvas',\n\t\treadOnlyHint: false,\n\t\tdestructiveHint: true,\n\t\tidempotentHint: false,\n\t\topenWorldHint: false\n\t},\n\tdescription:\n\t\t'Applies high-level structural operations to the visual canvas (adding nodes, connecting edges, organizing layout, or moving elements).',\n\tinputSchema: {\n\t\ttype: 'object',\n\t\tproperties: {\n\t\t\toperation: {\n\t\t\t\ttype: 'string',\n\t\t\t\tenum: [\n\t\t\t\t\t'add_node',\n\t\t\t\t\t'remove_nodes',\n\t\t\t\t\t'connect',\n\t\t\t\t\t'update_node',\n\t\t\t\t\t'layout',\n\t\t\t\t\t'select',\n\t\t\t\t\t'highlight'\n\t\t\t\t],\n\t\t\t\tdescription: 'The canvas operation to execute.'\n\t\t\t},\n\t\t\tnode: {\n\t\t\t\ttype: 'object',\n\t\t\t\tdescription: 'Node definition when operation is add_node. Can omit position to auto-place.'\n\t\t\t},\n\t\t\tnearNodeId: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdescription: 'Anchor node ID to position beside using collision-aware placement.'\n\t\t\t},\n\t\t\tside: {\n\t\t\t\ttype: 'string',\n\t\t\t\tenum: ['top', 'right', 'bottom', 'left'],\n\t\t\t\tdescription: 'Side of the anchor node to place the new node beside.'\n\t\t\t},\n\t\t\tnodeIds: {\n\t\t\t\ttype: 'array',\n\t\t\t\titems: { type: 'string' },\n\t\t\t\tdescription: 'Array of node IDs for remove_nodes, select, or highlight.'\n\t\t\t},\n\t\t\tsource: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdescription: 'Source node ID for connect operation.'\n\t\t\t},\n\t\t\ttarget: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdescription: 'Target node ID for connect operation.'\n\t\t\t},\n\t\t\tlabel: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdescription: 'Optional edge label for connect operation.'\n\t\t\t},\n\t\t\tdirection: {\n\t\t\t\ttype: 'string',\n\t\t\t\tenum: ['LR', 'TB', 'RL', 'BT'],\n\t\t\t\tdescription: 'Layout direction (default LR).'\n\t\t\t},\n\t\t\tincremental: {\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdescription: 'Preserve existing node coordinates and blend layout (default true).'\n\t\t\t}\n\t\t},\n\t\trequired: ['operation']\n\t}\n} as const;\n\nexport const MCP_TOOL_EDIT_PROMPT = {\n\tname: 'edit_prompt',\n\ttitle: 'Edit the prompt',\n\tannotations: {\n\t\ttitle: 'Edit the prompt',\n\t\treadOnlyHint: false,\n\t\tdestructiveHint: true,\n\t\tidempotentHint: false,\n\t\topenWorldHint: false\n\t},\n\tdescription:\n\t\t'Applies edits to the prompt template document, including inserting text, replacing ranges, and setting variables.',\n\tinputSchema: {\n\t\ttype: 'object',\n\t\tproperties: {\n\t\t\toperation: {\n\t\t\t\ttype: 'string',\n\t\t\t\tenum: ['insert_text', 'replace_range', 'set_variable', 'select'],\n\t\t\t\tdescription: 'The prompt operation to execute.'\n\t\t\t},\n\t\t\ttext: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdescription: 'Text to insert or replace.'\n\t\t\t},\n\t\t\tat: {\n\t\t\t\ttype: 'number',\n\t\t\t\tdescription: 'Position to insert text at.'\n\t\t\t},\n\t\t\tfrom: {\n\t\t\t\ttype: 'number',\n\t\t\t\tdescription: 'Start offset for replace_range or select.'\n\t\t\t},\n\t\t\tto: {\n\t\t\t\ttype: 'number',\n\t\t\t\tdescription: 'End offset for replace_range or select.'\n\t\t\t},\n\t\t\tname: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdescription: 'Variable name for set_variable.'\n\t\t\t},\n\t\t\tvalue: {\n\t\t\t\tdescription: 'Variable value for set_variable.'\n\t\t\t}\n\t\t},\n\t\trequired: ['operation']\n\t}\n} as const;\n\nexport const MCP_TOOL_VIEW_EDITOR = {\n\tname: 'view_editor',\n\ttitle: 'View the editor',\n\tannotations: {\n\t\ttitle: 'View the editor',\n\t\treadOnlyHint: true,\n\t\tdestructiveHint: false,\n\t\tidempotentHint: true,\n\t\topenWorldHint: false\n\t},\n\tdescription:\n\t\t'Captures a visual image snapshot (JPEG or PNG) of the editor canvas or viewport for multimodal evaluation. Active agent cursor indicators are automatically excluded from the snapshot.',\n\tinputSchema: {\n\t\ttype: 'object',\n\t\tproperties: {\n\t\t\tscope: {\n\t\t\t\ttype: 'string',\n\t\t\t\tenum: ['viewport', 'canvas'],\n\t\t\t\tdescription: 'Whether to capture only the visible viewport or the full canvas bounding box (default: viewport).'\n\t\t\t},\n\t\t\tformat: {\n\t\t\t\ttype: 'string',\n\t\t\t\tenum: ['jpeg', 'png'],\n\t\t\t\tdescription: 'Image format of the base64 snapshot (default: jpeg).'\n\t\t\t},\n\t\t\tmaxEdge: {\n\t\t\t\ttype: 'integer',\n\t\t\t\tdescription: 'Maximum width or height dimension in pixels (default: 1024).'\n\t\t\t}\n\t\t}\n\t}\n} as const;\n\n/**\n * CSS selectors for ephemeral UI overlays (such as agent cursors, presence tags, and transient bubbles)\n * that should be excluded during canvas image export and visual snapshot generation.\n */\nexport const EXPORT_EXCLUDED_SELECTORS = [\n\t'.pixerate-presence',\n\t'.agent-presence',\n\t'.ursula-presence'\n] as const;\n\nexport const EDITOR_MCP_TOOLS = [\n\tMCP_TOOL_GET_EDITOR_STATE,\n\tMCP_TOOL_EDIT_CANVAS,\n\tMCP_TOOL_EDIT_PROMPT,\n\tMCP_TOOL_VIEW_EDITOR\n] as const;\n\n","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 { Editor } from '@tiptap/core';\nimport { plainTextToSlice, getEditorText } from '../serializers/plain-text.js';\nimport { getEditorMarkdown } from '../serializers/markdown.js';\nimport { TextSelection } from '@tiptap/pm/state';\nimport {\n\tTABLE_ACTIONS,\n\tgetTableActionState,\n\tgetTableState,\n\tisTableEnabled,\n\trunTableAction,\n\ttype TableAction\n} from '../extensions/table/actions.js';\nimport type { SpreadsheetController } from '../spreadsheet/controller.js';\nimport { colNameToIndex, indexToColName, isFormulaError } from '../spreadsheet/formula/evaluator.js';\nimport { planToolCall } from './planner.js';\nimport type { AgentTool, AgentToolProvider } from './registry.js';\nimport {\n\tMCP_TOOL_EDIT_CANVAS,\n\tMCP_TOOL_EDIT_PROMPT,\n\tMCP_TOOL_GET_EDITOR_STATE,\n\tMCP_TOOL_VIEW_EDITOR\n} from './tools.js';\nimport type { AgentStep, EditorSnapshot } from './types.js';\nimport type { CanvasEdge, CanvasNode } from '../canvas/types.js';\n\nexport interface ToolProviderOptions {\n\t/** Provider id (unique per registry). */\n\tid: string;\n\t/** Always prefix tool names with `<namespace>__`. */\n\tnamespace?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Rich-text editor provider\n// ---------------------------------------------------------------------------\n\n/** A TipTap editor, or anything exposing one as `.editor` (e.g. `EditorController`). */\nexport type RichTextToolTarget = Editor | { editor: Editor };\n\nconst toEditor = (target: RichTextToolTarget): Editor =>\n\t'commands' in target ? (target as Editor) : (target as { editor: Editor }).editor;\n\n/** Replaces `from..to` with literal text (HTML is not parsed; newlines split paragraphs). */\nfunction replaceWithText(editor: Editor, from: number, to: number, text: string) {\n\tconst { state, view } = editor;\n\tconst tr = /[\\r\\n]/.test(text)\n\t\t? state.tr.replace(from, to, plainTextToSlice(text, state.schema))\n\t\t: text\n\t\t\t? state.tr.insertText(text, from, to)\n\t\t\t: state.tr.delete(from, to);\n\tview.dispatch(tr.scrollIntoView());\n}\n\nfunction selectionInfo(editor: Editor) {\n\tconst { from, to } = editor.state.selection;\n\treturn { from, to, text: editor.state.doc.textBetween(from, to, '\\n') };\n}\n\n/**\n * Tools for a mounted rich-text editor: `get_text` (always), plus\n * `insert_text` and `replace_selection` while the editor is editable, and\n * `edit_table` when the schema has tables (`createRichTextPreset`'s `table`).\n * Positions are ProseMirror document positions (as in `selection.from`).\n * The provider re-announces its tool list when editability changes and\n * exposes no tools once the editor is destroyed.\n */\nexport function createRichTextToolProvider(\n\ttarget: RichTextToolTarget,\n\toptions: ToolProviderOptions\n): AgentToolProvider {\n\tconst editor = () => toEditor(target);\n\n\tconst getText: AgentTool = {\n\t\tname: 'get_text',\n\t\ttitle: 'Get document text',\n\t\tdescription:\n\t\t\t'Returns the document content (plain text by default, or HTML / markdown) and the current selection.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\tformat: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tenum: ['text', 'html', 'markdown'],\n\t\t\t\t\tdescription: 'Content format (default: text).'\n\t\t\t\t}\n\t\t\t},\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: {\n\t\t\ttitle: 'Get document text',\n\t\t\treadOnlyHint: true,\n\t\t\tdestructiveHint: false,\n\t\t\tidempotentHint: true,\n\t\t\topenWorldHint: false\n\t\t},\n\t\thandler: ({ format = 'text' }) => {\n\t\t\tconst ed = editor();\n\t\t\tconst content =\n\t\t\t\tformat === 'html' ? ed.getHTML() : format === 'markdown' ? getEditorMarkdown(ed) : getEditorText(ed);\n\t\t\treturn { format, content, selection: selectionInfo(ed), size: ed.state.doc.content.size };\n\t\t}\n\t};\n\n\tconst insertText: AgentTool = {\n\t\tname: 'insert_text',\n\t\ttitle: 'Insert text',\n\t\tdescription:\n\t\t\t'Inserts literal text (newlines start new paragraphs) at a document position, or at the cursor when `at` is omitted.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\ttext: { type: 'string', description: 'Text to insert.' },\n\t\t\t\tat: { type: 'integer', minimum: 0, description: 'Document position (default: the selection).' }\n\t\t\t},\n\t\t\trequired: ['text'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: {\n\t\t\ttitle: 'Insert text',\n\t\t\treadOnlyHint: false,\n\t\t\tdestructiveHint: false,\n\t\t\tidempotentHint: false,\n\t\t\topenWorldHint: false\n\t\t},\n\t\thandler: ({ text, at }) => {\n\t\t\tconst ed = editor();\n\t\t\tconst size = ed.state.doc.content.size;\n\t\t\tif (at !== undefined && at > size) {\n\t\t\t\tthrow new Error(`Position ${at} is outside the document (size ${size}).`);\n\t\t\t}\n\t\t\tconst { from, to } = ed.state.selection;\n\t\t\treplaceWithText(ed, at ?? from, at ?? to, text);\n\t\t\treturn { inserted: text.length, selection: selectionInfo(ed) };\n\t\t}\n\t};\n\n\tconst replaceSelection: AgentTool = {\n\t\tname: 'replace_selection',\n\t\ttitle: 'Replace selection',\n\t\tdescription: 'Replaces the selected content with literal text (an empty string deletes the selection).',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: { text: { type: 'string', description: 'Replacement text.' } },\n\t\t\trequired: ['text'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: {\n\t\t\ttitle: 'Replace selection',\n\t\t\treadOnlyHint: false,\n\t\t\tdestructiveHint: true,\n\t\t\tidempotentHint: false,\n\t\t\topenWorldHint: false\n\t\t},\n\t\thandler: ({ text }) => {\n\t\t\tconst ed = editor();\n\t\t\tconst { from, to } = ed.state.selection;\n\t\t\treplaceWithText(ed, from, to, text);\n\t\t\treturn { replaced: { from, to }, selection: selectionInfo(ed) };\n\t\t}\n\t};\n\n\tconst editTable: AgentTool = {\n\t\tname: 'edit_table',\n\t\ttitle: 'Edit tables',\n\t\tdescription:\n\t\t\t'Inserts a table or edits the table at the cursor (or at `at`): add/delete rows and columns, delete the table, ' +\n\t\t\t'merge/split cells, toggle header row/column/cell, move between cells, set cell alignment or background. ' +\n\t\t\t'Returns the table size and the cursor cell afterwards.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\toperation: { type: 'string', enum: TABLE_ACTIONS.map((a) => a.action), description: 'Table operation.' },\n\t\t\t\tat: { type: 'integer', minimum: 0, description: 'Document position to place the cursor first (e.g. inside a cell).' },\n\t\t\t\trows: { type: 'integer', minimum: 1, maximum: 100, description: 'insertTable: rows (default 3).' },\n\t\t\t\tcols: { type: 'integer', minimum: 1, maximum: 50, description: 'insertTable: columns (default 3).' },\n\t\t\t\twithHeaderRow: { type: 'boolean', description: 'insertTable: first row is a header row (default true).' },\n\t\t\t\talign: {\n\t\t\t\t\ttype: ['string', 'null'],\n\t\t\t\t\tenum: ['left', 'center', 'right', 'justify', null],\n\t\t\t\t\tdescription: 'setCellAlignment: alignment, or null to clear.'\n\t\t\t\t},\n\t\t\t\tcolor: { type: ['string', 'null'], description: 'setCellBackground: CSS color, or null to clear.' }\n\t\t\t},\n\t\t\trequired: ['operation'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: {\n\t\t\ttitle: 'Edit tables',\n\t\t\treadOnlyHint: false,\n\t\t\tdestructiveHint: true,\n\t\t\tidempotentHint: false,\n\t\t\topenWorldHint: false\n\t\t},\n\t\thandler: ({ operation, at, ...params }) => {\n\t\t\tconst ed = editor();\n\t\t\tif (at !== undefined) {\n\t\t\t\tconst size = ed.state.doc.content.size;\n\t\t\t\tif (at > size) throw new Error(`Position ${at} is outside the document (size ${size}).`);\n\t\t\t\ted.view.dispatch(ed.state.tr.setSelection(TextSelection.near(ed.state.doc.resolve(at))));\n\t\t\t}\n\t\t\tconst action = operation as TableAction;\n\t\t\tconst state = getTableActionState(ed, action, params);\n\t\t\tif (state !== true) throw new Error(state);\n\t\t\trunTableAction(ed, action, params);\n\t\t\tconst table = getTableState(ed);\n\t\t\treturn {\n\t\t\t\toperation,\n\t\t\t\ttable: table.inTable\n\t\t\t\t\t? { rows: table.rows, columns: table.columns, row: table.row, column: table.column }\n\t\t\t\t\t: null,\n\t\t\t\tselection: selectionInfo(ed)\n\t\t\t};\n\t\t}\n\t};\n\n\treturn {\n\t\tid: options.id,\n\t\tnamespace: options.namespace,\n\t\ttools: () => {\n\t\t\tconst ed = editor();\n\t\t\tif (!ed || ed.isDestroyed) return [];\n\t\t\tif (!ed.isEditable) return [getText];\n\t\t\treturn isTableEnabled(ed)\n\t\t\t\t? [getText, insertText, replaceSelection, editTable]\n\t\t\t\t: [getText, insertText, replaceSelection];\n\t\t},\n\t\tsubscribe: (notify) => {\n\t\t\tconst ed = editor();\n\t\t\t// `setEditable` emits `update`; the registry ignores signals that don't change the list.\n\t\t\ted.on('update', notify);\n\t\t\ted.on('destroy', notify);\n\t\t\treturn () => {\n\t\t\t\ted.off('update', notify);\n\t\t\t\ted.off('destroy', notify);\n\t\t\t};\n\t\t}\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Spreadsheet provider\n// ---------------------------------------------------------------------------\n\nconst CELL_REF_REGEX = /^\\$?([A-Za-z]{1,3})\\$?(\\d{1,7})$/;\n\nfunction parseCell(ref: string): { col: number; row: number } {\n\tconst match = CELL_REF_REGEX.exec(ref.trim());\n\tif (!match) throw new Error(`Invalid cell reference \"${ref}\". Use A1 notation, e.g. \"B3\".`);\n\treturn { col: colNameToIndex(match[1].toUpperCase()), row: parseInt(match[2], 10) - 1 };\n}\n\n/**\n * Tools for a spreadsheet controller: `get_range` (A1 notation, values and raw\n * input) and `set_cell` (raw input; values starting with `=` are formulas).\n */\nexport function createSpreadsheetToolProvider(\n\tcontroller: SpreadsheetController,\n\toptions: ToolProviderOptions\n): AgentToolProvider {\n\tconst lookup = (row: number, col: number) => {\n\t\tconst rowDef = controller.document.rows[row];\n\t\tconst colDef = controller.document.columns[col];\n\t\treturn rowDef && colDef ? { rowDef, colDef } : null;\n\t};\n\n\tconst getRange: AgentTool = {\n\t\tname: 'get_range',\n\t\ttitle: 'Read cells',\n\t\tdescription:\n\t\t\t'Reads a cell range in A1 notation (e.g. \"A1:C5\" or \"B2\") and returns computed values, raw input and errors.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\trange: { type: 'string', description: 'A1-notation cell or range.' }\n\t\t\t},\n\t\t\trequired: ['range'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: {\n\t\t\ttitle: 'Read cells',\n\t\t\treadOnlyHint: true,\n\t\t\tdestructiveHint: false,\n\t\t\tidempotentHint: true,\n\t\t\topenWorldHint: false\n\t\t},\n\t\thandler: ({ range }) => {\n\t\t\tconst [startRef, endRef = startRef] = String(range).split(':');\n\t\t\tconst start = parseCell(startRef);\n\t\t\tconst end = parseCell(endRef);\n\t\t\tconst rowCount = controller.document.rows.length;\n\t\t\tconst colCount = controller.document.columns.length;\n\t\t\tconst r0 = Math.min(start.row, end.row);\n\t\t\tconst r1 = Math.min(Math.max(start.row, end.row), rowCount - 1);\n\t\t\tconst c0 = Math.min(start.col, end.col);\n\t\t\tconst c1 = Math.min(Math.max(start.col, end.col), colCount - 1);\n\t\t\tconst values: unknown[][] = [];\n\t\t\tconst raw: string[][] = [];\n\t\t\tconst errors: Array<{ cell: string; error: string }> = [];\n\t\t\tfor (let r = r0; r <= r1; r++) {\n\t\t\t\tconst valueRow: unknown[] = [];\n\t\t\t\tconst rawRow: string[] = [];\n\t\t\t\tfor (let c = c0; c <= c1; c++) {\n\t\t\t\t\tconst found = lookup(r, c)!;\n\t\t\t\t\tconst cell = controller.getCell(found.rowDef.id, found.colDef.id);\n\t\t\t\t\tvalueRow.push(cell.error ?? cell.value);\n\t\t\t\t\trawRow.push(cell.raw);\n\t\t\t\t\tconst error = cell.error ?? (isFormulaError(cell.value) ? cell.value : undefined);\n\t\t\t\t\tif (error) errors.push({ cell: `${indexToColName(c)}${r + 1}`, error });\n\t\t\t\t}\n\t\t\t\tvalues.push(valueRow);\n\t\t\t\traw.push(rawRow);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\trange: values.length && values[0].length ? `${indexToColName(c0)}${r0 + 1}:${indexToColName(c1)}${r1 + 1}` : null,\n\t\t\t\tvalues,\n\t\t\t\traw,\n\t\t\t\terrors,\n\t\t\t\tsheet: { rows: rowCount, columns: colCount }\n\t\t\t};\n\t\t}\n\t};\n\n\tconst setCell: AgentTool = {\n\t\tname: 'set_cell',\n\t\ttitle: 'Set a cell',\n\t\tdescription: 'Sets the raw input of one cell (A1 notation). Values starting with \"=\" are formulas.',\n\t\tinputSchema: {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\tcell: { type: 'string', description: 'A1-notation cell, e.g. \"B3\".' },\n\t\t\t\tvalue: { type: ['string', 'number', 'boolean'], description: 'Raw cell input.' }\n\t\t\t},\n\t\t\trequired: ['cell', 'value'],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tannotations: {\n\t\t\ttitle: 'Set a cell',\n\t\t\treadOnlyHint: false,\n\t\t\tdestructiveHint: true,\n\t\t\tidempotentHint: true,\n\t\t\topenWorldHint: false\n\t\t},\n\t\thandler: ({ cell, value }) => {\n\t\t\tconst { row, col } = parseCell(cell);\n\t\t\tconst found = lookup(row, col);\n\t\t\tif (!found) throw new Error(`Cell ${cell} is outside the sheet.`);\n\t\t\tconst { rowDef, colDef } = found;\n\t\t\tif (colDef.readOnly || controller.getCell(rowDef.id, colDef.id).readOnly || colDef.type === 'formula') {\n\t\t\t\tthrow new Error(`Cell ${cell} is read-only.`);\n\t\t\t}\n\t\t\tcontroller.setCellValue(rowDef.id, colDef.id, String(value));\n\t\t\tconst updated = controller.getCell(rowDef.id, colDef.id);\n\t\t\treturn { cell: cell.toUpperCase(), raw: updated.raw, value: updated.error ?? updated.value };\n\t\t}\n\t};\n\n\treturn { id: options.id, namespace: options.namespace, tools: [getRange, setCell] };\n}\n\n// ---------------------------------------------------------------------------\n// Static editor tools (tools.ts) as a provider\n// ---------------------------------------------------------------------------\n\nexport interface EditorMcpToolProviderOptions<\n\tTNode extends CanvasNode = CanvasNode,\n\tTEdge extends CanvasEdge = CanvasEdge\n> extends ToolProviderOptions {\n\t/** Current editor / canvas state. */\n\tgetSnapshot: () => EditorSnapshot<TNode, TEdge>;\n\t/** Applies planned steps (e.g. via your canvas runes / editor controller). */\n\tapplySteps: (steps: AgentStep<TNode, TEdge>[]) => void | Promise<void>;\n\t/** Optional `view_editor` implementation; the tool is only exposed when provided. */\n\tcaptureView?: (args: { scope?: 'viewport' | 'canvas'; format?: 'jpeg' | 'png'; maxEdge?: number }) =>\n\t\t| Promise<{ data: string; mimeType: string }>\n\t\t| { data: string; mimeType: string };\n\t/** Options forwarded to the planner. */\n\tplannerOptions?: Parameters<typeof planToolCall>[3];\n}\n\n/**\n * Exposes the static MCP tools from `tools.ts` (`get_editor_state`,\n * `edit_canvas`, `edit_prompt`, `view_editor`) through a `ToolRegistry`,\n * planning edits with `planToolCall` and handing the steps to `applySteps`.\n */\nexport function createEditorMcpToolProvider<\n\tTNode extends CanvasNode = CanvasNode,\n\tTEdge extends CanvasEdge = CanvasEdge\n>(options: EditorMcpToolProviderOptions<TNode, TEdge>): AgentToolProvider {\n\tconst edit = (name: string) => async (args: Record<string, any>) => {\n\t\tconst steps = planToolCall<TNode, TEdge>(name, args, options.getSnapshot(), options.plannerOptions);\n\t\tif (steps.length === 0) {\n\t\t\tthrow new Error(`Operation \"${args.operation}\" is missing required arguments.`);\n\t\t}\n\t\tawait options.applySteps(steps);\n\t\treturn { applied: steps.length, steps: steps.map((s) => s.type) };\n\t};\n\n\tconst tools: AgentTool[] = [\n\t\t{\n\t\t\t...MCP_TOOL_GET_EDITOR_STATE,\n\t\t\thandler: ({ includeDocument = true, includeCanvas = true }) => {\n\t\t\t\tconst snapshot = options.getSnapshot();\n\t\t\t\treturn {\n\t\t\t\t\t...(includeDocument && snapshot.document ? { document: snapshot.document } : {}),\n\t\t\t\t\t...(includeCanvas && snapshot.canvas ? { canvas: snapshot.canvas } : {})\n\t\t\t\t};\n\t\t\t}\n\t\t},\n\t\t{ ...MCP_TOOL_EDIT_CANVAS, handler: edit(MCP_TOOL_EDIT_CANVAS.name) },\n\t\t{ ...MCP_TOOL_EDIT_PROMPT, handler: edit(MCP_TOOL_EDIT_PROMPT.name) }\n\t] as AgentTool[];\n\n\tif (options.captureView) {\n\t\tconst capture = options.captureView;\n\t\ttools.push({\n\t\t\t...MCP_TOOL_VIEW_EDITOR,\n\t\t\thandler: async (args) => {\n\t\t\t\tconst image = await capture(args);\n\t\t\t\treturn { content: [{ type: 'image', data: image.data, mimeType: image.mimeType }] };\n\t\t\t}\n\t\t} as AgentTool);\n\t}\n\n\treturn { id: options.id, namespace: options.namespace, tools };\n}\n","import { hasVariantCommands, type ComponentCommandTarget } from '../commands/builtins.js';\nimport type { AgentTool, AgentToolProvider } from './registry.js';\nimport type { ToolProviderOptions } from './providers.js';\n\nconst IDS = { type: 'array', items: { type: 'string' }, description: 'Node ids (default: the selection).' } as const;\nconst ID = { type: 'string', description: 'An instance, or a layer inside one (default: the first selected node).' } as const;\n\nconst READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false } as const;\nconst WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false } as const;\n\ntype Outcome = { ok: true; ids: string[] } | { ok: false; reason: string };\nconst check = (result: Outcome) => {\n\tif (!result.ok) throw new Error(result.reason);\n\treturn { ids: result.ids };\n};\n\n/**\n * Agent tools for canvas components and instances, backed by a components controller\n * (`createCanvasComponentsController`): `list_components`, `inspect_instance`,\n * `create_component`, `combine_as_variants`, `create_instance`, `set_instance_properties`\n * (variants and component properties), `swap_instance`, `reset_overrides`, `push_overrides`,\n * `detach_instance`, `go_to_main_component`, `restore_main_component` and (when the controller\n * has them) the variant editors `add_variant`, `remove_variant`, `set_variant_properties`,\n * `rename_variant_property` and `rename_variant_value`. Refused actions come back as tool errors\n * carrying the reason.\n */\nexport function createCanvasComponentToolProvider(\n\tcontroller: ComponentCommandTarget,\n\toptions: ToolProviderOptions = { id: 'canvas-components' }\n): AgentToolProvider {\n\tconst tool = (\n\t\tname: string,\n\t\tdescription: string,\n\t\tproperties: Record<string, unknown>,\n\t\thandler: AgentTool['handler'],\n\t\textra: { required?: string[]; readOnly?: boolean } = {}\n\t): AgentTool => ({\n\t\tname,\n\t\tdescription,\n\t\tinputSchema: { type: 'object', properties: properties as never, ...(extra.required ? { required: extra.required } : {}), additionalProperties: false },\n\t\tannotations: extra.readOnly ? READ : WRITE,\n\t\thandler\n\t});\n\tconst tools: AgentTool[] = [\n\t\ttool('list_components', 'Lists components (id, name, variant values, instance count) and component sets with their variant options.', {}, () => controller.list(), {\n\t\t\treadOnly: true\n\t\t}),\n\t\ttool(\n\t\t\t'inspect_instance',\n\t\t\t'Describes an instance: its main component, variant, component property values (with types) and the overrides of its layers.',\n\t\t\t{ id: ID },\n\t\t\t({ id }) => {\n\t\t\t\tconst info = controller.inspect(id);\n\t\t\t\tif (!info) throw new Error('Not an instance (or a layer inside one).');\n\t\t\t\treturn info;\n\t\t\t},\n\t\t\t{ readOnly: true }\n\t\t),\n\t\ttool('create_component', 'Turns the given frame into a main component, or wraps the given layers in a new one.', { ids: IDS }, ({ ids }) =>\n\t\t\tcheck(controller.createComponent(ids))\n\t\t),\n\t\ttool('combine_as_variants', 'Wraps sibling components in a component set (variants named \"Property=Value, …\").', { ids: IDS }, ({ ids }) =>\n\t\t\tcheck(controller.combineAsVariants(ids))\n\t\t),\n\t\ttool(\n\t\t\t'create_instance',\n\t\t\t'Places an instance of a component or component set, optionally inside a frame, at a position, with property values.',\n\t\t\t{\n\t\t\t\tcomponentId: { type: 'string' },\n\t\t\t\tparentId: { type: 'string' },\n\t\t\t\tx: { type: 'number' },\n\t\t\t\ty: { type: 'number' },\n\t\t\t\tproperties: { type: 'object', additionalProperties: true, description: 'Variant and component property values.' }\n\t\t\t},\n\t\t\t({ componentId, parentId, x, y, properties }) =>\n\t\t\t\tcheck(\n\t\t\t\t\tcontroller.createInstance(componentId, {\n\t\t\t\t\t\t...(parentId !== undefined ? { parentId } : {}),\n\t\t\t\t\t\t...(x !== undefined || y !== undefined ? { position: { x: x ?? 0, y: y ?? 0 } } : {}),\n\t\t\t\t\t\t...(properties ? { properties } : {})\n\t\t\t\t\t})\n\t\t\t\t),\n\t\t\t{ required: ['componentId'] }\n\t\t),\n\t\ttool(\n\t\t\t'set_instance_properties',\n\t\t\t'Sets property values of instances: variant properties switch the variant (keeping compatible overrides), booleans toggle layers, text sets text, instance swap takes a component id.',\n\t\t\t{ properties: { type: 'object', additionalProperties: true }, ids: IDS },\n\t\t\t({ properties, ids }) => check(controller.setInstanceProperties(properties, ids)),\n\t\t\t{ required: ['properties'] }\n\t\t),\n\t\ttool(\n\t\t\t'swap_instance',\n\t\t\t'Makes instances show another component (or a set’s default variant), keeping overrides of layers with matching names.',\n\t\t\t{ componentId: { type: 'string' }, ids: IDS },\n\t\t\t({ componentId, ids }) => check(controller.swapInstance(componentId, ids)),\n\t\t\t{ required: ['componentId'] }\n\t\t),\n\t\ttool(\n\t\t\t'reset_overrides',\n\t\t\t'Resets overrides: of a whole instance (default), of one layer, or one override group such as \"data.label\" or \"shape.fill\".',\n\t\t\t{ id: ID, group: { type: 'string' } },\n\t\t\t({ id, group }) => check(controller.resetOverrides(id, group))\n\t\t),\n\t\ttool('push_overrides', 'Copies an instance’s overrides to its main component (and so to every other instance).', { id: ID }, ({ id }) =>\n\t\t\tcheck(controller.pushOverrides(id))\n\t\t),\n\t\ttool('detach_instance', 'Turns instances into plain frames that keep their current look.', { ids: IDS }, ({ ids }) => check(controller.detachInstance(ids))),\n\t\ttool('go_to_main_component', 'Selects the main component of an instance and returns its id.', { id: ID }, ({ id }) => {\n\t\t\tconst main = controller.goToMainComponent(id);\n\t\t\tif (!main) throw new Error('The main component was not found.');\n\t\t\treturn { id: main };\n\t\t}),\n\t\ttool('restore_main_component', 'Turns an instance whose main component was deleted back into the main component.', { id: ID }, ({ id }) =>\n\t\t\tcheck(controller.restoreMainComponent(id))\n\t\t)\n\t];\n\tif (hasVariantCommands(controller)) {\n\t\tconst SET = { type: 'string', description: 'Component set, or one of its variants (default: the selection’s set).' };\n\t\tconst VARIANT = { type: 'string', description: 'Variant id (default: the first selected variant).' };\n\t\tconst VALUES = { type: 'object', additionalProperties: { type: 'string' }, description: 'Variant property → value, e.g. { \"Size\": \"Medium\" }.' };\n\t\ttools.push(\n\t\t\ttool(\n\t\t\t\t'add_variant',\n\t\t\t\t'Adds a variant to a component set by duplicating one (default: the set’s default variant) with new property values. Unnamed properties keep the source’s values; new property names are added to every variant (\"Default\"). A combination another variant has is refused. Without values the next \"VariantN\" is used.',\n\t\t\t\t{ setId: SET, from: { type: 'string', description: 'Variant to duplicate.' }, variant: VALUES, x: { type: 'number' }, y: { type: 'number' } },\n\t\t\t\t({ setId, from, variant, x, y }) =>\n\t\t\t\t\tcheck(\n\t\t\t\t\t\tcontroller.addVariant(setId, {\n\t\t\t\t\t\t\t...(from !== undefined ? { from } : {}),\n\t\t\t\t\t\t\t...(variant ? { variant } : {}),\n\t\t\t\t\t\t\t...(x !== undefined || y !== undefined ? { position: { x: x ?? 0, y: y ?? 0 } } : {})\n\t\t\t\t\t\t})\n\t\t\t\t\t)\n\t\t\t),\n\t\t\ttool(\n\t\t\t\t'remove_variant',\n\t\t\t\t'Removes a variant from its component set (not the last one). Its instances switch to the closest remaining variant, keeping overrides.',\n\t\t\t\t{ id: VARIANT },\n\t\t\t\t({ id }) => check(controller.removeVariant(id))\n\t\t\t),\n\t\t\ttool(\n\t\t\t\t'set_variant_properties',\n\t\t\t\t'Sets a variant’s property values (merged with its current ones); new property names are added to every variant. A combination another variant has is refused.',\n\t\t\t\t{ values: VALUES, id: VARIANT },\n\t\t\t\t({ values, id }) => check(controller.setVariantProperties(values, id)),\n\t\t\t\t{ required: ['values'] }\n\t\t\t),\n\t\t\ttool(\n\t\t\t\t'rename_variant_property',\n\t\t\t\t'Renames a variant property across a component set (instances keep their variant).',\n\t\t\t\t{ name: { type: 'string' }, newName: { type: 'string' }, setId: SET },\n\t\t\t\t({ name, newName, setId }) => check(controller.renameVariantProperty(name, newName, setId)),\n\t\t\t\t{ required: ['name', 'newName'] }\n\t\t\t),\n\t\t\ttool(\n\t\t\t\t'rename_variant_value',\n\t\t\t\t'Renames a value of a variant property across a component set (instances keep their variant).',\n\t\t\t\t{ property: { type: 'string' }, value: { type: 'string' }, newValue: { type: 'string' }, setId: SET },\n\t\t\t\t({ property, value, newValue, setId }) => check(controller.renameVariantValue(property, value, newValue, setId)),\n\t\t\t\t{ required: ['property', 'value', 'newValue'] }\n\t\t\t)\n\t\t);\n\t}\n\treturn { id: options.id, namespace: options.namespace, tools };\n}\n"]}
|
package/dist/agent/index.d.cts
CHANGED
|
@@ -3,8 +3,8 @@ export { J as JsonSchema, a as JsonSchemaType, S as SchemaValidationError, v as
|
|
|
3
3
|
import { A as AgentToolProvider } from '../registry-DnzpgY27.cjs';
|
|
4
4
|
export { a as AgentTool, b as AgentToolHandler, M as McpListToolsResult, c as McpToolContent, d as McpToolDefinition, e as McpToolResult, T as TOOL_NAMESPACE_SEPARATOR, f as ToolCallContext, g as ToolCallError, h as ToolErrorCode, i as ToolRegistry, j as ToolRegistryError, k as ToolRegistryOptions, l as createToolRegistry, t as toToolResult } from '../registry-DnzpgY27.cjs';
|
|
5
5
|
import { Editor } from '@tiptap/core';
|
|
6
|
-
import { S as SpreadsheetController } from '../controller-
|
|
7
|
-
import { b as ComponentCommandTarget } from '../builtins-
|
|
6
|
+
import { S as SpreadsheetController } from '../controller-w6eRTjF8.cjs';
|
|
7
|
+
import { b as ComponentCommandTarget } from '../builtins-nMXh9sT3.cjs';
|
|
8
8
|
import '../types-GT5a5YAX.cjs';
|
|
9
9
|
import '../registry-D0GADKc7.cjs';
|
|
10
10
|
|
|
@@ -591,8 +591,10 @@ declare function createEditorMcpToolProvider<TNode extends CanvasNode = CanvasNo
|
|
|
591
591
|
* (`createCanvasComponentsController`): `list_components`, `inspect_instance`,
|
|
592
592
|
* `create_component`, `combine_as_variants`, `create_instance`, `set_instance_properties`
|
|
593
593
|
* (variants and component properties), `swap_instance`, `reset_overrides`, `push_overrides`,
|
|
594
|
-
* `detach_instance`, `go_to_main_component` and
|
|
595
|
-
*
|
|
594
|
+
* `detach_instance`, `go_to_main_component`, `restore_main_component` and (when the controller
|
|
595
|
+
* has them) the variant editors `add_variant`, `remove_variant`, `set_variant_properties`,
|
|
596
|
+
* `rename_variant_property` and `rename_variant_value`. Refused actions come back as tool errors
|
|
597
|
+
* carrying the reason.
|
|
596
598
|
*/
|
|
597
599
|
declare function createCanvasComponentToolProvider(controller: ComponentCommandTarget, options?: ToolProviderOptions): AgentToolProvider;
|
|
598
600
|
|
package/dist/agent/index.d.ts
CHANGED
|
@@ -3,8 +3,8 @@ export { J as JsonSchema, a as JsonSchemaType, S as SchemaValidationError, v as
|
|
|
3
3
|
import { A as AgentToolProvider } from '../registry-BDe-vlv3.js';
|
|
4
4
|
export { a as AgentTool, b as AgentToolHandler, M as McpListToolsResult, c as McpToolContent, d as McpToolDefinition, e as McpToolResult, T as TOOL_NAMESPACE_SEPARATOR, f as ToolCallContext, g as ToolCallError, h as ToolErrorCode, i as ToolRegistry, j as ToolRegistryError, k as ToolRegistryOptions, l as createToolRegistry, t as toToolResult } from '../registry-BDe-vlv3.js';
|
|
5
5
|
import { Editor } from '@tiptap/core';
|
|
6
|
-
import { S as SpreadsheetController } from '../controller-
|
|
7
|
-
import { b as ComponentCommandTarget } from '../builtins-
|
|
6
|
+
import { S as SpreadsheetController } from '../controller-w6eRTjF8.js';
|
|
7
|
+
import { b as ComponentCommandTarget } from '../builtins-haN82vjT.js';
|
|
8
8
|
import '../types-GT5a5YAX.js';
|
|
9
9
|
import '../registry-DhVUZioj.js';
|
|
10
10
|
|
|
@@ -591,8 +591,10 @@ declare function createEditorMcpToolProvider<TNode extends CanvasNode = CanvasNo
|
|
|
591
591
|
* (`createCanvasComponentsController`): `list_components`, `inspect_instance`,
|
|
592
592
|
* `create_component`, `combine_as_variants`, `create_instance`, `set_instance_properties`
|
|
593
593
|
* (variants and component properties), `swap_instance`, `reset_overrides`, `push_overrides`,
|
|
594
|
-
* `detach_instance`, `go_to_main_component` and
|
|
595
|
-
*
|
|
594
|
+
* `detach_instance`, `go_to_main_component`, `restore_main_component` and (when the controller
|
|
595
|
+
* has them) the variant editors `add_variant`, `remove_variant`, `set_variant_properties`,
|
|
596
|
+
* `rename_variant_property` and `rename_variant_value`. Refused actions come back as tool errors
|
|
597
|
+
* carrying the reason.
|
|
596
598
|
*/
|
|
597
599
|
declare function createCanvasComponentToolProvider(controller: ComponentCommandTarget, options?: ToolProviderOptions): AgentToolProvider;
|
|
598
600
|
|