Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(ai-editing): edit database answers, charts and embedded databases (#9333)

Wolf Mermelstein645adbfcb223
diff --git a/apps/docs/AI/mcp/tools/edit-document.mdx b/apps/docs/AI/mcp/tools/edit-document.mdx
index 590501e599..9a012122d3 100644
--- a/apps/docs/AI/mcp/tools/edit-document.mdx
+++ b/apps/docs/AI/mcp/tools/edit-document.mdx
@@ -7,7 +7,7 @@ description: >-
# EditDocument
-Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Use EditSpreadsheet for native Macro spreadsheets. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Edit uploaded Word (.docx) files with ReadWordDocument and EditWordDocument instead. Other uploaded files -- PDFs, images, source files such as .py or .ts -- are readable but not editable, and are rejected. If the response contains a `clarification` field, invoke again with the requested info appended to `instructions`. To insert @-mention chips, include each referenced item's ids and details in `instructions`: userId/email for people; documentId/documentName/blockName (and blockParams when needed) for documents, channels, chats, projects, tasks, emails, calendar events, skills, calls, and routines; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips; profileId/slug/url for booking links. To insert document-card(s), include each document's documentId and documentName.
+Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Use EditSpreadsheet for native Macro spreadsheets. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Edit uploaded Word (.docx) files with ReadWordDocument and EditWordDocument instead. Other uploaded files -- PDFs, images, source files such as .py or .ts -- are readable but not editable, and are rejected. If the response contains a `clarification` field, invoke again with the requested info appended to `instructions`. To insert @-mention chips, include each referenced item's ids and details in `instructions`: userId/email for people; documentId/documentName/blockName (and blockParams when needed) for documents, channels, chats, projects, tasks, emails, calendar events, skills, calls, and routines; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips; profileId/slug/url for booking links. To insert document-card(s), include each document's documentId and documentName; to embed a database, its databaseId, name, and tableId/viewId. To insert a live database answer or chart, quote the `<m-db-query>` block from SaveDatabaseQuery verbatim in `instructions`.
## Parameters
diff --git a/apps/docs/AI/mcp/tools/save-database-query.mdx b/apps/docs/AI/mcp/tools/save-database-query.mdx
index b566079bbb..2e32066602 100644
--- a/apps/docs/AI/mcp/tools/save-database-query.mdx
+++ b/apps/docs/AI/mcp/tools/save-database-query.mdx
@@ -7,7 +7,7 @@ description: >-
# SaveDatabaseQuery
-Save a read-only SELECT as a live question and get back the block that shows its answer. Paste the returned `markdown` verbatim, into your reply or into a document with CreateDocument/EditDocument, and it renders as a live number, table, or chart that re-runs for whoever views it, with their permissions, so it stays current as the data changes.
+Save a read-only SELECT as a live question and get back the block that shows its answer. Paste the returned `markdown` verbatim into your reply or a CreateDocument document, or quote it verbatim in EditDocument's `instructions`, and it renders as a live number, table, or chart that re-runs for whoever views it, with their permissions, so it stays current as the data changes.
Use it whenever the user asks a question about their data or asks for a chart. Run the SELECT with QueryDatabase first to check it returns what you expect, then save exactly that SQL. The SQL is QueryDatabase's dialect, described there, limited to one SELECT.
@@ -15,7 +15,7 @@ Use it whenever the user asks a question about their data or asks for a chart. R
- `chart` (bar/line/area/scatter/pie): `x` is the label column and `y` the numeric result columns, named exactly as the result columns are; alias aggregates (`COUNT(*) AS invites`) so they have stable names. `color` names a result column whose values split one `y` series into one series per value (e.g. invites per party colored by status); `stack` stacks bar or area series instead of setting them side by side.
- Pass `databaseId` so the question resolves against that database's tables.
-Saved questions never change, and a block you write or edit yourself does not work. To change one, save a new one and use its new block.
+Saved questions never change, and a block you write or edit yourself does not work. To change one, save a new one and use its new block. EditDocument can restyle a block already in a document (chart type, title, height) and switch an embedded database to another table or view by its `tableId`/`viewId`.
## Parameters
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index a521b234b7..5feb25b24e 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -9154,7 +9154,7 @@ export interface EditCommentResponse {
commentId: string;
}
/**
- * Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Use EditSpreadsheet for native Macro spreadsheets. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Edit uploaded Word (.docx) files with ReadWordDocument and EditWordDocument instead. Other uploaded files -- PDFs, images, source files such as .py or .ts -- are readable but not editable, and are rejected. If the response contains a `clarification` field, invoke again with the requested info appended to `instructions`. To insert @-mention chips, include each referenced item's ids and details in `instructions`: userId/email for people; documentId/documentName/blockName (and blockParams when needed) for documents, channels, chats, projects, tasks, emails, calendar events, skills, calls, and routines; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips; profileId/slug/url for booking links. To insert document-card(s), include each document's documentId and documentName.
+ * Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Use EditSpreadsheet for native Macro spreadsheets. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Edit uploaded Word (.docx) files with ReadWordDocument and EditWordDocument instead. Other uploaded files -- PDFs, images, source files such as .py or .ts -- are readable but not editable, and are rejected. If the response contains a `clarification` field, invoke again with the requested info appended to `instructions`. To insert @-mention chips, include each referenced item's ids and details in `instructions`: userId/email for people; documentId/documentName/blockName (and blockParams when needed) for documents, channels, chats, projects, tasks, emails, calendar events, skills, calls, and routines; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips; profileId/slug/url for booking links. To insert document-card(s), include each document's documentId and documentName; to embed a database, its databaseId, name, and tableId/viewId. To insert a live database answer or chart, quote the `<m-db-query>` block from SaveDatabaseQuery verbatim in `instructions`.
*/
export interface EditDocument {
/**
@@ -15099,7 +15099,7 @@ export interface RoutineRunStarted {
};
}
/**
- * Save a read-only SELECT as a live question and get back the block that shows its answer. Paste the returned `markdown` verbatim, into your reply or into a document with CreateDocument/EditDocument, and it renders as a live number, table, or chart that re-runs for whoever views it, with their permissions, so it stays current as the data changes.
+ * Save a read-only SELECT as a live question and get back the block that shows its answer. Paste the returned `markdown` verbatim into your reply or a CreateDocument document, or quote it verbatim in EditDocument's `instructions`, and it renders as a live number, table, or chart that re-runs for whoever views it, with their permissions, so it stays current as the data changes.
*
* Use it whenever the user asks a question about their data or asks for a chart. Run the SELECT with QueryDatabase first to check it returns what you expect, then save exactly that SQL. The SQL is QueryDatabase's dialect, described there, limited to one SELECT.
*
@@ -15107,7 +15107,7 @@ export interface RoutineRunStarted {
* - `chart` (bar/line/area/scatter/pie): `x` is the label column and `y` the numeric result columns, named exactly as the result columns are; alias aggregates (`COUNT(*) AS invites`) so they have stable names. `color` names a result column whose values split one `y` series into one series per value (e.g. invites per party colored by status); `stack` stacks bar or area series instead of setting them side by side.
* - Pass `databaseId` so the question resolves against that database's tables.
*
- * Saved questions never change, and a block you write or edit yourself does not work. To change one, save a new one and use its new block.
+ * Saved questions never change, and a block you write or edit yourself does not work. To change one, save a new one and use its new block. EditDocument can restyle a block already in a document (chart type, title, height) and switch an embedded database to another table or view by its `tableId`/`viewId`.
*/
export interface SaveDatabaseQuery {
/**
diff --git a/crates/databases_sql/src/toolset/save_database_query.md b/crates/databases_sql/src/toolset/save_database_query.md
index c9374ad222..cd77ab33f8 100644
--- a/crates/databases_sql/src/toolset/save_database_query.md
+++ b/crates/databases_sql/src/toolset/save_database_query.md
@@ -1,4 +1,4 @@
-Save a read-only SELECT as a live question and get back the block that shows its answer. Paste the returned `markdown` verbatim, into your reply or into a document with CreateDocument/EditDocument, and it renders as a live number, table, or chart that re-runs for whoever views it, with their permissions, so it stays current as the data changes.
+Save a read-only SELECT as a live question and get back the block that shows its answer. Paste the returned `markdown` verbatim into your reply or a CreateDocument document, or quote it verbatim in EditDocument's `instructions`, and it renders as a live number, table, or chart that re-runs for whoever views it, with their permissions, so it stays current as the data changes.
Use it whenever the user asks a question about their data or asks for a chart. Run the SELECT with QueryDatabase first to check it returns what you expect, then save exactly that SQL. The SQL is QueryDatabase's dialect, described there, limited to one SELECT.
@@ -6,4 +6,4 @@ Use it whenever the user asks a question about their data or asks for a chart. R
- `chart` (bar/line/area/scatter/pie): `x` is the label column and `y` the numeric result columns, named exactly as the result columns are; alias aggregates (`COUNT(*) AS invites`) so they have stable names. `color` names a result column whose values split one `y` series into one series per value (e.g. invites per party colored by status); `stack` stacks bar or area series instead of setting them side by side.
- Pass `databaseId` so the question resolves against that database's tables.
-Saved questions never change, and a block you write or edit yourself does not work. To change one, save a new one and use its new block.
\ No newline at end of file
+Saved questions never change, and a block you write or edit yourself does not work. To change one, save a new one and use its new block. EditDocument can restyle a block already in a document (chart type, title, height) and switch an embedded database to another table or view by its `tableId`/`viewId`.
\ No newline at end of file
diff --git a/crates/documents/src/inbound/toolset/edit_document.rs b/crates/documents/src/inbound/toolset/edit_document.rs
index 304314ef49..03ce55c6a1 100644
--- a/crates/documents/src/inbound/toolset/edit_document.rs
+++ b/crates/documents/src/inbound/toolset/edit_document.rs
@@ -27,7 +27,7 @@ pub(super) mod test;
#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(
title = "EditDocument",
- description = "Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Use EditSpreadsheet for native Macro spreadsheets. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Edit uploaded Word (.docx) files with ReadWordDocument and EditWordDocument instead. Other uploaded files -- PDFs, images, source files such as .py or .ts -- are readable but not editable, and are rejected. If the response contains a `clarification` field, invoke again with the requested info appended to `instructions`. To insert @-mention chips, include each referenced item's ids and details in `instructions`: userId/email for people; documentId/documentName/blockName (and blockParams when needed) for documents, channels, chats, projects, tasks, emails, calendar events, skills, calls, and routines; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips; profileId/slug/url for booking links. To insert document-card(s), include each document's documentId and documentName."
+ description = "Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Use EditSpreadsheet for native Macro spreadsheets. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Edit uploaded Word (.docx) files with ReadWordDocument and EditWordDocument instead. Other uploaded files -- PDFs, images, source files such as .py or .ts -- are readable but not editable, and are rejected. If the response contains a `clarification` field, invoke again with the requested info appended to `instructions`. To insert @-mention chips, include each referenced item's ids and details in `instructions`: userId/email for people; documentId/documentName/blockName (and blockParams when needed) for documents, channels, chats, projects, tasks, emails, calendar events, skills, calls, and routines; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips; profileId/slug/url for booking links. To insert document-card(s), include each document's documentId and documentName; to embed a database, its databaseId, name, and tableId/viewId. To insert a live database answer or chart, quote the `<m-db-query>` block from SaveDatabaseQuery verbatim in `instructions`."
)]
pub struct EditDocument {
#[schemars(
diff --git a/docs/agent-guide/databases.md b/docs/agent-guide/databases.md
index b6cbccb375..6973384f16 100644
--- a/docs/agent-guide/databases.md
+++ b/docs/agent-guide/databases.md
@@ -721,6 +721,15 @@ Escape cancels. Renaming keeps the question and its saved query unchanged. A sav
query names databases, tables, and columns by their display names, so renaming one
it reads makes the answer fail until the question is updated.
+AI document editing (the selection toolbar's **AI edit**, `EditDocument`) works with
+database blocks.
+It inserts a saved answer or chart from the `<m-db-query>` block that
+`SaveDatabaseQuery` returns, can change an existing answer's chart type, title,
+or height without changing its question, and can switch an embedded database
+to another table or view. To check, have chat save a chart and add it to a
+document, then select nearby text, choose **AI edit**, and ask for a pie chart; the same question
+should redraw as a pie.
+
An existing document keeps its answer label when Databases is off and does not
fetch its database results; see [Feature flag](#feature-flag).
diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.md
index 87cf3c7464..1492d8f3d4 100644
--- a/docs/agent-guide/documents.md
+++ b/docs/agent-guide/documents.md
@@ -2690,9 +2690,11 @@ access to the title and property controls.
## AI edit
-1. Click `Edit with AI` (button directly under the editor body).
-2. A focused prompt box appears (placeholder `Describe the edit…`). Type the instruction,
- press Enter (or click `Send`).
+1. Select text in the document, then click `AI edit` in the selection toolbar (on touch,
+ `Edit with AI` in the selection toolbar opens the same prompt in a drawer).
+2. A focused prompt box appears (placeholder `Describe changes`). Type the instruction,
+ press Enter (or click `Send`). The edit runs in fast mode and its changes apply
+ client-side, so they land in the user's undo stack.
Selected-text AI edit uses the shared Send button: muted and disabled for an
empty or whitespace-only prompt, black with a white arrow in light mode once
an instruction is entered (inverted for dark mode), on desktop and mobile.
diff --git a/packages/lexical-core/tests/xml.test.ts b/packages/lexical-core/tests/xml.test.ts
index 6c61b34283..09f26b66e4 100644
--- a/packages/lexical-core/tests/xml.test.ts
+++ b/packages/lexical-core/tests/xml.test.ts
@@ -170,4 +170,59 @@ describe('xml', () => {
expect(xml).toContain('&amp;');
expect(xml).toContain('&gt;');
});
+
+ it('shows which table and view a database card embeds', () => {
+ const state = root([
+ {
+ type: 'document-card',
+ version: 1,
+ documentId: 'db-1',
+ documentName: 'Projects',
+ blockName: 'database',
+ blockParams: { tableId: 'table-1', viewId: 'view-1' },
+ $: { id: 'card' },
+ },
+ ]);
+ expect(toXml(state)).toContain(
+ '<document-card id="card" documentId="db-1" name="Projects" blockName="database" blockParams="{&quot;tableId&quot;:&quot;table-1&quot;,&quot;viewId&quot;:&quot;view-1&quot;}"/>'
+ );
+ });
+
+ it('serializes a database answer with its chart', () => {
+ const state = root([
+ {
+ type: 'database-query',
+ version: 2,
+ queryId: 'q-1',
+ databaseId: 'db-1',
+ prompt: 'Projects per owner',
+ title: 'By owner',
+ displayMode: 'bar',
+ chart: { x: 'owner', y: ['projects'], stack: true },
+ height: 320,
+ $: { id: 'chart' },
+ },
+ paragraph(
+ [
+ text('Total: ', 0, 't1'),
+ {
+ type: 'database-query',
+ version: 2,
+ queryId: 'q-2',
+ prompt: 'How many projects?',
+ displayMode: 'scalar',
+ $: { id: 'n' },
+ },
+ ],
+ 'p1'
+ ),
+ ]);
+ const xml = toXml(state);
+ expect(xml).toContain(
+ '<database-query id="chart" queryId="q-1" databaseId="db-1" displayMode="bar" title="By owner" prompt="Projects per owner" chart="{&quot;x&quot;:&quot;owner&quot;,&quot;y&quot;:[&quot;projects&quot;],&quot;stack&quot;:true}" height="320"/>'
+ );
+ expect(xml).toContain(
+ '<database-query id="n" queryId="q-2" displayMode="scalar" prompt="How many projects?"/>'
+ );
+ });
});
diff --git a/packages/lexical-core/transformers/xml/codecs.ts b/packages/lexical-core/transformers/xml/codecs.ts
index 4ff8ed4c2a..f53fb8577e 100644
--- a/packages/lexical-core/transformers/xml/codecs.ts
+++ b/packages/lexical-core/transformers/xml/codecs.ts
@@ -85,6 +85,7 @@ const KNOWN_TYPES: Record<KnownNode['type'], 1> = {
video: 1,
'html-render': 1,
'document-card': 1,
+ 'database-query': 1,
'user-mention': 1,
'document-mention': 1,
'contact-mention': 1,
@@ -311,6 +312,27 @@ export function serializeNode(node: SerNode): FxpNode {
nodeAttrs(n, {
...(n.documentId && { documentId: n.documentId }),
...(n.documentName && { name: n.documentName }),
+ ...(n.blockName && { blockName: n.blockName }),
+ ...(n.blockParams &&
+ Object.keys(n.blockParams).length > 0 && {
+ blockParams: JSON.stringify(n.blockParams),
+ }),
+ })
+ )
+ )
+ .with({ type: 'database-query' }, (n) =>
+ el(
+ 'database-query',
+ [],
+ nodeAttrs(n, {
+ queryId: n.queryId,
+ ...(n.databaseId && { databaseId: n.databaseId }),
+ ...(n.tableId && { tableId: n.tableId }),
+ displayMode: n.displayMode,
+ ...(n.title && { title: n.title }),
+ prompt: n.prompt,
+ ...(n.chart && { chart: JSON.stringify(n.chart) }),
+ ...(n.height !== undefined && { height: String(n.height) }),
})
)
)
diff --git a/packages/lexical-core/transformers/xml/nodes.ts b/packages/lexical-core/transformers/xml/nodes.ts
index 734258028d..adc29d4ddd 100644
--- a/packages/lexical-core/transformers/xml/nodes.ts
+++ b/packages/lexical-core/transformers/xml/nodes.ts
@@ -1,3 +1,4 @@
+import type { DatabaseQueryData } from '../../nodes/databaseQueryData';
export type Id = { $?: { id: string } };
type EleBase = Id & {
@@ -159,8 +160,16 @@ export type DocumentCardNode = Id & {
version: number;
documentId: string;
documentName: string;
+ blockName?: string;
+ blockParams?: Record<string, string>;
};
+export type DatabaseQueryNode = Id &
+ DatabaseQueryData & {
+ type: 'database-query';
+ version: number;
+ };
+
export type UserMentionNode = Id & {
type: 'user-mention';
version: number;
@@ -263,6 +272,7 @@ export type KnownNode =
| VideoNode
| HtmlRenderNode
| DocumentCardNode
+ | DatabaseQueryNode
| UserMentionNode
| DocumentMentionNode
| ContactMentionNode
diff --git a/services/ai-editing-worker/AI_EDITING.md b/services/ai-editing-worker/AI_EDITING.md
index cf21f33b82..a1ac36e2ee 100644
--- a/services/ai-editing-worker/AI_EDITING.md
+++ b/services/ai-editing-worker/AI_EDITING.md
@@ -120,6 +120,17 @@ There are only three kinds of steps:
We have an abstraction called the "executor" that ties together the animation queue and the document editor. It is what actually "plays" everything.
+### Database blocks
+
+The XML view shows saved database questions as `<database-query>` (queryId,
+displayMode, chart, title) and embedded databases as `<document-card
+blockName="database" blockParams=…>`. Writers insert a question only from the
+`<m-db-query>` block the caller passes (`SaveDatabaseQuery` output); `Doc`
+parses it with the shared lexical-core validator and refuses anything else,
+since the SQL lives on the server. `setDatabaseQueryView` changes presentation
+(display mode, chart, title, height) and never the question;
+`setDatabaseLocation` switches an embedded database's table or view.
+
### "Doc"s
`Doc{Writer/Reader}` is an abstraction over the real Lexical `Document`. This makes everything much more testable. It has a minimal-ish (okay not super minimal) interface that's easy to mock and run against real lexical.
diff --git a/services/ai-editing-worker/src/ai-editing/ai-toolkit/databases.ts b/services/ai-editing-worker/src/ai-editing/ai-toolkit/databases.ts
new file mode 100644
index 0000000000..434bbde22c
--- /dev/null
+++ b/services/ai-editing-worker/src/ai-editing/ai-toolkit/databases.ts
@@ -0,0 +1,95 @@
+import {
+ $createDatabaseQueryNode,
+ $isDatabaseQueryNode,
+ type DatabaseQueryNode,
+ parseDatabaseQueryJson,
+} from '@macro-inc/lexical-core/nodes/DatabaseQueryNode';
+import { $isDocumentCardNode } from '@macro-inc/lexical-core/nodes/DocumentCardNode';
+import {
+ type DatabaseQueryData,
+ isDatabaseQueryChartMode,
+ parseDatabaseQueryData,
+} from '@macro-inc/lexical-core/nodes/databaseQueryData';
+import type { LexicalNode } from 'lexical';
+import { EditError } from '../editor/errors';
+import type { DatabaseQueryView } from '../editor/ops';
+
+function requireChart(data: DatabaseQueryData, label: string): void {
+ if (isDatabaseQueryChartMode(data.displayMode) && !data.chart)
+ throw new EditError(
+ `${label}: a ${data.displayMode} chart needs chart {x, y} naming result columns`
+ );
+}
+
+/** A saved question's `<m-db-query>` block, as `SaveDatabaseQuery` returns it.
+ * The SQL lives on the server, so anything else is refused, never guessed. */
+function parseQueryBlock(query: string): DatabaseQueryData {
+ const json = /^<m-db-query>([\s\S]*)<\/m-db-query>$/.exec(query.trim())?.[1];
+ const data = json === undefined ? undefined : parseDatabaseQueryJson(json);
+ if (!data?.queryId)
+ throw new EditError(
+ 'not a saved <m-db-query>…</m-db-query> block; paste the block from the request verbatim, never write one'
+ );
+ requireChart(data, '<m-db-query>');
+ return data;
+}
+
+/** A block answer; a scalar one is wrapped in a paragraph by the caller. */
+export function $createQueryBlock(query: string): DatabaseQueryNode {
+ return $createDatabaseQueryNode(parseQueryBlock(query));
+}
+
+export function $createInlineQuery(query: string): DatabaseQueryNode {
+ const data = parseQueryBlock(query);
+ if (data.displayMode !== 'scalar')
+ throw new EditError(
+ `only a scalar answer sits inside text; insert this ${data.displayMode} as a block`
+ );
+ return $createDatabaseQueryNode(data);
+}
+
+const VIEW_FIELDS = new Set(['displayMode', 'title', 'chart', 'height']);
+
+/** Change how an answer is shown; `null` removes a field. The question stays. */
+export function $setQueryView(
+ node: LexicalNode,
+ id: string,
+ view: DatabaseQueryView
+): void {
+ if (!$isDatabaseQueryNode(node))
+ throw new EditError(`{${id}} is not a database answer`);
+ const current = node.exportComponentProps();
+ const next: Record<string, unknown> = { ...current };
+ for (const [field, value] of Object.entries(view)) {
+ if (!VIEW_FIELDS.has(field))
+ throw new EditError(
+ `{${id}}: cannot change ${field}; a view changes only displayMode, title, chart, or height`
+ );
+ if (value === null) delete next[field];
+ else if (value !== undefined) next[field] = value;
+ }
+ const data = parseDatabaseQueryData(next);
+ if (!data)
+ throw new EditError(
+ `{${id}}: invalid view. A chart names 1-5 distinct y result columns other than x, and height is 96-1600.`
+ );
+ if ((current.displayMode === 'scalar') !== (data.displayMode === 'scalar'))
+ throw new EditError(
+ `{${id}}: a scalar answer sits inside text, so it cannot switch to or from a table or chart in place; remove it and insert the question's block instead`
+ );
+ requireChart(data, `{${id}}`);
+ node.setQuery(data);
+}
+
+/** Point an embedded database card at another table and view. */
+export function $setLocation(
+ node: LexicalNode,
+ id: string,
+ tableId: string,
+ viewId?: string
+): void {
+ if (!$isDocumentCardNode(node) || node.getBlockName() !== 'database')
+ throw new EditError(`{${id}} is not an embedded database`);
+ // An empty view id shows the table's default view, as the card's own picker does.
+ node.setBlockParams({ tableId, viewId: viewId ?? '' });
+}
diff --git a/services/ai-editing-worker/src/ai-editing/ai-toolkit/index.ts b/services/ai-editing-worker/src/ai-editing/ai-toolkit/index.ts
index e3f2c444b9..c22e74fa51 100644
--- a/services/ai-editing-worker/src/ai-editing/ai-toolkit/index.ts
+++ b/services/ai-editing-worker/src/ai-editing/ai-toolkit/index.ts
@@ -1,4 +1,5 @@
export * from './blocks';
+export * from './databases';
export * from './inline';
export * from './lists';
export * from './locate';
diff --git a/services/ai-editing-worker/src/ai-editing/doc/databases.test.ts b/services/ai-editing-worker/src/ai-editing/doc/databases.test.ts
new file mode 100644
index 0000000000..c424ef1e06
--- /dev/null
+++ b/services/ai-editing-worker/src/ai-editing/doc/databases.test.ts
@@ -0,0 +1,258 @@
+import {
+ $isDatabaseQueryNode,
+ type DatabaseQueryNode,
+} from '@macro-inc/lexical-core/nodes/DatabaseQueryNode';
+import {
+ $isDocumentCardNode,
+ type DocumentCardNode,
+} from '@macro-inc/lexical-core/nodes/DocumentCardNode';
+import { $getRoot, $isParagraphNode } from 'lexical';
+import { describe, expect, it } from 'vitest';
+import { read, setup } from '../ai-toolkit/_test-helpers';
+import type { DatabaseQueryView } from '../editor';
+import { serializeWithXml } from '../utils';
+import { Doc } from './doc';
+
+const CHART_BLOCK =
+ '<m-db-query>{"queryId":"q-1","databaseId":"db-1","title":"By owner","prompt":"Projects per owner","displayMode":"bar","chart":{"x":"owner","y":["projects"]}}</m-db-query>';
+const SCALAR_BLOCK =
+ '<m-db-query>{"queryId":"q-2","databaseId":"db-1","prompt":"How many projects?","displayMode":"scalar"}</m-db-query>';
+const DATABASE_CARD =
+ '<m-document-card>{"documentId":"db-1","documentName":"Projects","blockName":"database","blockParams":{"tableId":"table-1","viewId":"view-1"}}</m-document-card>';
+
+/** Every database answer in the document, block or inside a paragraph. */
+function queryNodes(session: ReturnType<typeof setup>['session']) {
+ return read(session, () =>
+ $getRoot()
+ .getChildren()
+ .flatMap((child) =>
+ $isParagraphNode(child) ? child.getChildren() : [child]
+ )
+ .filter($isDatabaseQueryNode)
+ .map((node: DatabaseQueryNode) => node.exportComponentProps())
+ );
+}
+
+describe('Doc — database answers and charts', () => {
+ it('inserts a chart block from its <m-db-query> markdown', () => {
+ const { session, ids } = setup('intro');
+ new Doc(session).apply({
+ kind: 'insertNode',
+ ref: 'chart',
+ spec: { block: 'database-query', query: CHART_BLOCK },
+ at: { after: ids[0]! },
+ });
+ expect(
+ read(session, () => {
+ const node = $getRoot().getChildren()[1];
+ return $isDatabaseQueryNode(node) ? node.exportComponentProps() : null;
+ })
+ ).toEqual({
+ queryId: 'q-1',
+ databaseId: 'db-1',
+ title: 'By owner',
+ prompt: 'Projects per owner',
+ displayMode: 'bar',
+ chart: { x: 'owner', y: ['projects'] },
+ });
+ expect(serializeWithXml(session)).toContain(
+ '<database-query id="chart" queryId="q-1"'
+ );
+ });
+
+ it('inserts a scalar answer inside a sentence', () => {
+ const { session, ids } = setup('Total: projects');
+ new Doc(session).apply({
+ kind: 'insertInline',
+ ref: 'n',
+ node: ids[0]!,
+ at: 7,
+ spec: { inline: 'database-query', query: SCALAR_BLOCK },
+ });
+ expect(
+ read(session, () =>
+ $getRoot()
+ .getChildren()
+ .flatMap((child) =>
+ $isParagraphNode(child) ? child.getChildren() : [child]
+ )
+ .map((node) => node.getType())
+ )
+ ).toEqual(['text', 'database-query', 'text']);
+ });
+
+ it('refuses a table or chart inside a sentence', () => {
+ const { session, ids } = setup('Total: projects');
+ expect(() =>
+ new Doc(session).apply({
+ kind: 'insertInline',
+ ref: 'n',
+ node: ids[0]!,
+ at: 7,
+ spec: { inline: 'database-query', query: CHART_BLOCK },
+ })
+ ).toThrow(/only a scalar answer sits inside text/);
+ });
+
+ it('refuses text that is not a saved database question', () => {
+ const { session, ids } = setup('intro');
+ const doc = new Doc(session);
+ for (const query of [
+ 'SELECT count(*) FROM projects',
+ '<m-db-query>{"queryId":"","prompt":"draft","displayMode":"table"}</m-db-query>',
+ '<m-db-query>{"queryId":"q","prompt":"p","displayMode":"bar"}</m-db-query>',
+ ]) {
+ expect(() =>
+ doc.apply({
+ kind: 'insertNode',
+ ref: 'chart',
+ spec: { block: 'database-query', query },
+ at: { after: ids[0]! },
+ })
+ ).toThrow(/<m-db-query>/);
+ }
+ expect(queryNodes(session)).toEqual([]);
+ });
+
+ it('switches a chart to another chart type, keeping the saved question', () => {
+ const { session } = setup(CHART_BLOCK);
+ const nodeId = /<database-query id="([^"]+)"/.exec(
+ serializeWithXml(session)
+ )![1]!;
+ new Doc(session).apply({
+ kind: 'setDatabaseQueryView',
+ node: nodeId,
+ view: { displayMode: 'line', title: 'Owner trend', height: 360 },
+ });
+ expect(queryNodes(session)).toEqual([
+ {
+ queryId: 'q-1',
+ databaseId: 'db-1',
+ title: 'Owner trend',
+ prompt: 'Projects per owner',
+ displayMode: 'line',
+ chart: { x: 'owner', y: ['projects'] },
+ height: 360,
+ },
+ ]);
+ });
+
+ it('clears a title and turns a chart into a table', () => {
+ const { session } = setup(CHART_BLOCK);
+ const nodeId = /<database-query id="([^"]+)"/.exec(
+ serializeWithXml(session)
+ )![1]!;
+ new Doc(session).apply({
+ kind: 'setDatabaseQueryView',
+ node: nodeId,
+ view: { displayMode: 'table', title: null, chart: null },
+ });
+ expect(queryNodes(session)).toEqual([
+ {
+ queryId: 'q-1',
+ databaseId: 'db-1',
+ prompt: 'Projects per owner',
+ displayMode: 'table',
+ },
+ ]);
+ });
+
+ it('refuses a view the renderer cannot draw and leaves the chart unchanged', () => {
+ const { session } = setup(`${SCALAR_BLOCK}\n\n${CHART_BLOCK}`);
+ const [scalarId, chartId] = [
+ ...serializeWithXml(session).matchAll(/<database-query id="([^"]+)"/g),
+ ].map((found) => found[1]!);
+ const doc = new Doc(session);
+ expect(() =>
+ doc.apply({
+ kind: 'setDatabaseQueryView',
+ node: chartId!,
+ view: { chart: null },
+ })
+ ).toThrow(/needs chart/);
+ expect(() =>
+ doc.apply({
+ kind: 'setDatabaseQueryView',
+ node: chartId!,
+ view: { displayMode: 'scalar' },
+ })
+ ).toThrow(/scalar/);
+ expect(() =>
+ doc.apply({
+ kind: 'setDatabaseQueryView',
+ node: chartId!,
+ // Model code is untyped; a question field must never ride along.
+ view: { title: 'Other', queryId: 'q-9' } as DatabaseQueryView,
+ })
+ ).toThrow(/cannot change queryId/);
+ expect(() =>
+ doc.apply({
+ kind: 'setDatabaseQueryView',
+ node: scalarId!,
+ view: { displayMode: 'table' },
+ })
+ ).toThrow(/scalar/);
+ expect(queryNodes(session)).toEqual([
+ {
+ queryId: 'q-2',
+ databaseId: 'db-1',
+ prompt: 'How many projects?',
+ displayMode: 'scalar',
+ },
+ {
+ queryId: 'q-1',
+ databaseId: 'db-1',
+ title: 'By owner',
+ prompt: 'Projects per owner',
+ displayMode: 'bar',
+ chart: { x: 'owner', y: ['projects'] },
+ },
+ ]);
+ });
+});
+
+describe('Doc — embedded databases', () => {
+ it('switches an embedded database to another table and view', () => {
+ const { session } = setup(DATABASE_CARD);
+ const cardId = /<document-card id="([^"]+)"/.exec(
+ serializeWithXml(session)
+ )![1]!;
+ const doc = new Doc(session);
+ doc.apply({
+ kind: 'setDatabaseLocation',
+ node: cardId,
+ tableId: 'table-2',
+ viewId: 'view-9',
+ });
+ const params = () =>
+ read(session, () => {
+ const node = $getRoot().getChildren()[0];
+ return $isDocumentCardNode(node)
+ ? (node as DocumentCardNode).getBlockParams()
+ : null;
+ });
+ expect(params()).toEqual({ tableId: 'table-2', viewId: 'view-9' });
+ doc.apply({
+ kind: 'setDatabaseLocation',
+ node: cardId,
+ tableId: 'table-3',
+ });
+ expect(params()).toEqual({ tableId: 'table-3', viewId: '' });
+ });
+
+ it('refuses to retarget a card that is not a database', () => {
+ const { session } = setup(
+ '<m-document-card>{"documentId":"doc-1","documentName":"Plan","blockName":"md"}</m-document-card>'
+ );
+ const cardId = /<document-card id="([^"]+)"/.exec(
+ serializeWithXml(session)
+ )![1]!;
+ expect(() =>
+ new Doc(session).apply({
+ kind: 'setDatabaseLocation',
+ node: cardId,
+ tableId: 'table-2',
+ })
+ ).toThrow(/not an embedded database/);
+ });
+});
diff --git a/services/ai-editing-worker/src/ai-editing/doc/doc.ts b/services/ai-editing-worker/src/ai-editing/doc/doc.ts
index 5dddbe624d..d61b22d197 100644
--- a/services/ai-editing-worker/src/ai-editing/doc/doc.ts
+++ b/services/ai-editing-worker/src/ai-editing/doc/doc.ts
@@ -73,6 +73,7 @@ import {
} from 'lexical';
import { match } from 'ts-pattern';
import * as blocks from '../ai-toolkit/blocks';
+import * as databases from '../ai-toolkit/databases';
import * as inline from '../ai-toolkit/inline';
import * as lists from '../ai-toolkit/lists';
import * as locate from '../ai-toolkit/locate';
@@ -80,6 +81,7 @@ import * as modify from '../ai-toolkit/modify';
import type { LexicalSession } from '../ai-toolkit/session';
import * as tables from '../ai-toolkit/tables';
import type {
+ DatabaseQueryView,
DocumentOp,
Format,
ListKind,
@@ -208,6 +210,12 @@ export class Doc implements DocReader, DocWriter {
.with({ kind: 'setDate' }, (e) =>
this.setDate(e.node, e.date, e.displayFormat)
)
+ .with({ kind: 'setDatabaseQueryView' }, (e) =>
+ this.setDatabaseQueryView(e.node, e.view)
+ )
+ .with({ kind: 'setDatabaseLocation' }, (e) =>
+ this.setDatabaseLocation(e.node, e.tableId, e.viewId)
+ )
.exhaustive();
}
@@ -792,6 +800,27 @@ export class Doc implements DocReader, DocWriter {
});
}
+ private setDatabaseQueryView(node: NodeRef, view: DatabaseQueryView): void {
+ this.tx(() =>
+ databases.$setQueryView(locate.$byId(this.session, node), node, view)
+ );
+ }
+
+ private setDatabaseLocation(
+ node: NodeRef,
+ tableId: string,
+ viewId?: string
+ ): void {
+ this.tx(() =>
+ databases.$setLocation(
+ locate.$byId(this.session, node),
+ node,
+ tableId,
+ viewId
+ )
+ );
+ }
+
/** Resolve an insert anchor to a sibling node. Climbs past inline nodes (so a
* text id resolves to its block) but stops at the first block-level node —
* including a decorator block like a divider/image/video. `$blockById` can't
@@ -971,6 +1000,9 @@ export function buildNode(spec: NodeSpec): LexicalNode {
.with({ block: 'html-render' }, (s) =>
$createHtmlRenderNode({ html: s.html })
)
+ .with({ block: 'database-query' }, (s) =>
+ databases.$createQueryBlock(s.query)
+ )
.with({ block: 'image' }, (session) =>
$createImageNode({
srcType: session.srcType,
@@ -993,6 +1025,9 @@ export function buildNode(spec: NodeSpec): LexicalNode {
$createEquationNode(session.tex, session.inline ?? false)
)
.with({ inline: 'linebreak' }, () => $createLineBreakNode())
+ .with({ inline: 'database-query' }, (s) =>
+ databases.$createInlineQuery(s.query)
+ )
.with({ inline: 'equation' }, (session) =>
$createEquationNode(session.tex, true)
)
diff --git a/services/ai-editing-worker/src/ai-editing/editor/document-editor.ts b/services/ai-editing-worker/src/ai-editing/editor/document-editor.ts
index 9ec51cb643..8d2c7fe7d5 100644
--- a/services/ai-editing-worker/src/ai-editing/editor/document-editor.ts
+++ b/services/ai-editing-worker/src/ai-editing/editor/document-editor.ts
@@ -3,6 +3,7 @@
// or the AI's editor surface won't reflect your edits.
import { EditError } from './errors';
import type {
+ DatabaseQueryView,
DocumentOp,
Format,
ListKind,
@@ -736,6 +737,70 @@ export class DocumentEditor {
this.requireId(id);
return this.push({ kind: 'setDate', node: id, date, displayFormat });
}
+
+ private requireQueryBlock(query: string): void {
+ if (typeof query !== 'string' || !query.includes('<m-db-query>')) {
+ throw new EditError(
+ "pass the saved question's <m-db-query>…</m-db-query> block from the request, verbatim"
+ );
+ }
+ }
+
+ /** A saved database question (`<m-db-query>` block) as a live number, table, or chart. */
+ public insertDatabaseQueryAfter(id: NodeId, query: string): Ref {
+ this.requireQueryBlock(query);
+ return this.insert({ block: 'database-query', query }, { after: id });
+ }
+
+ public insertDatabaseQueryBefore(id: NodeId, query: string): Ref {
+ this.requireQueryBlock(query);
+ return this.insert({ block: 'database-query', query }, { before: id });
+ }
+
+ public appendDatabaseQuery(query: string): Ref {
+ this.requireQueryBlock(query);
+ return this.insert(
+ { block: 'database-query', query },
+ { appendToRoot: true }
+ );
+ }
+
+ /** A scalar answer inside a sentence, at character offset `at`. */
+ public insertInlineDatabaseQuery(
+ blockId: NodeId,
+ at: number,
+ query: string
+ ): Ref {
+ this.requireQueryBlock(query);
+ return this.insertInline(blockId, at, { inline: 'database-query', query });
+ }
+
+ public setDatabaseQueryView(id: NodeId, view: DatabaseQueryView): this {
+ this.requireId(id);
+ if (!view || typeof view !== 'object' || !Object.keys(view).length) {
+ throw new EditError(
+ 'pass at least one of displayMode, title, chart, or height'
+ );
+ }
+ return this.push({ kind: 'setDatabaseQueryView', node: id, view });
+ }
+
+ /** Show another table (and optionally view) of an embedded database card. */
+ public setDatabaseLocation(
+ id: NodeId,
+ location: { tableId: string; viewId?: string }
+ ): this {
+ this.requireId(id);
+ if (typeof location?.tableId !== 'string' || !location.tableId) {
+ throw new EditError('setDatabaseLocation needs a tableId');
+ }
+ return this.push({
+ kind: 'setDatabaseLocation',
+ node: id,
+ tableId: location.tableId,
+ viewId: location.viewId,
+ });
+ }
}
function editorMethodNames(target: DocumentEditor): string[] {
diff --git a/services/ai-editing-worker/src/ai-editing/editor/ops.ts b/services/ai-editing-worker/src/ai-editing/editor/ops.ts
index 27c9483677..0b004f6ca7 100644
--- a/services/ai-editing-worker/src/ai-editing/editor/ops.ts
+++ b/services/ai-editing-worker/src/ai-editing/editor/ops.ts
@@ -5,6 +5,11 @@
* These are plain data — nothing here imports Lexical.
*/
+import type {
+ DatabaseQueryChart,
+ DatabaseQueryDisplayMode,
+} from '@macro-inc/lexical-core/nodes/databaseQueryData';
+
/** A durable node id (the `{id}` / `<t id>` the model sees). */
export type NodeId = string;
@@ -52,6 +57,8 @@ export type NodeSpec =
blockParams?: Record<string, string>;
}
| { block: 'html-render'; html: string }
+ /** `query` is a saved question's `<m-db-query>…</m-db-query>` markdown. */
+ | { block: 'database-query'; query: string }
| {
block: 'image';
srcType: string;
@@ -72,7 +79,9 @@ export type NodeSpec =
| { inline: 'linebreak' }
| { inline: 'equation'; tex: string }
| { inline: 'date'; date: string; displayFormat?: string }
- | { inline: 'mention'; mention: MentionSpec };
+ | { inline: 'mention'; mention: MentionSpec }
+ /** A scalar `<m-db-query>` answer inside a sentence. */
+ | { inline: 'database-query'; query: string };
export type ListKind = 'bullet' | 'number' | 'check';
@@ -113,6 +122,15 @@ export type MentionSpec =
color?: string;
};
+/** Presentation of a saved database question; `null` removes a field. The
+ * question and its SQL never change here: a new question is a new block. */
+export type DatabaseQueryView = {
+ displayMode?: DatabaseQueryDisplayMode;
+ title?: string | null;
+ chart?: DatabaseQueryChart | null;
+ height?: number | null;
+};
+
/** Block-type targets for `setBlockType`. */
export type BlockType = 'paragraph' | 'heading' | 'quote' | 'code';
@@ -228,6 +246,14 @@ export type DocumentOp =
| { kind: 'setImageUrl'; node: NodeRef; url: string }
| { kind: 'setVideoUrl'; node: NodeRef; url: string }
| { kind: 'setVideoControls'; node: NodeRef; controls: boolean }
- | { kind: 'setDate'; node: NodeRef; date: string; displayFormat?: string };
+ | { kind: 'setDate'; node: NodeRef; date: string; displayFormat?: string }
+ // databases
+ | { kind: 'setDatabaseQueryView'; node: NodeRef; view: DatabaseQueryView }
+ | {
+ kind: 'setDatabaseLocation';
+ node: NodeRef;
+ tableId: string;
+ viewId?: string;
+ };
export type DocumentOpKind = DocumentOp['kind'];
diff --git a/services/ai-editing-worker/src/ai-editing/prompts/API_COMPACT.md b/services/ai-editing-worker/src/ai-editing/prompts/API_COMPACT.md
index a37dab8184..20bd7f6599 100644
--- a/services/ai-editing-worker/src/ai-editing/prompts/API_COMPACT.md
+++ b/services/ai-editing-worker/src/ai-editing/prompts/API_COMPACT.md
@@ -39,5 +39,6 @@ The writer has the complete API reference. Use this compact list to help yoursel
- Inline objects: `insertInlineEquation`, `insertLineBreak`, `insertDate`/`mentionDate` (time chip), `insertMention`, `mentionUser`, `mentionContact`, `mentionGroup`, `mentionDocument`, `mentionAgentSession`, `mentionPullRequest`, `mentionBookingLink`, `mentionTag`
- To place text after an inline object: `insertTextAfterInline(inlineRef, text)`. Do **not** use `appendText` for this — it targets the block's last text node and misplaces the text when an inline object is the last child.
- Updates: `setImageAlt`, `setImageUrl`, `setVideoUrl`, `setVideoControls`, `setDate`
+- Databases: `<database-query>` is a saved question shown as a number, table, or chart; `<document-card blockName="database">` embeds a database table/view. `insertDatabaseQueryAfter(id, query)`, `insertDatabaseQueryBefore`, `appendDatabaseQuery(query)`, `insertInlineDatabaseQuery(blockId, at, query)` take the task's `<m-db-query>…</m-db-query>` block verbatim (never write one); `setDatabaseQueryView(id, { displayMode?, title?, chart?, height? })` restyles an answer; `setDatabaseLocation(cardId, { tableId, viewId? })` switches an embedded database's table/view
Our editing team is very well versed in how to use the library and you should never tell them how to get the job done. But this is to help you understand what they are capable of.
diff --git a/services/ai-editing-worker/src/ai-editing/prompts/API_COMPLETE.md b/services/ai-editing-worker/src/ai-editing/prompts/API_COMPLETE.md
index 25f5bd9376..89338a8bf3 100644
--- a/services/ai-editing-worker/src/ai-editing/prompts/API_COMPLETE.md
+++ b/services/ai-editing-worker/src/ai-editing/prompts/API_COMPLETE.md
@@ -432,6 +432,7 @@ After:
- `{ block: 'table', rows }`
- `{ block: 'divider' }`
- `{ block: 'document-card', documentId, documentName, blockName, blockParams? }` where `blockParams` is `Record<string, string>`. Use the ids supplied in the task -- do not invent them.
+- `{ block: 'database-query', query }` -- see Databases.
- `{ block: 'html-render', html }`
- `{ block: 'image', srcType, url, alt?, width?, height? }`
- `{ block: 'video', srcType, url, controls?, width?, height? }`
@@ -461,3 +462,19 @@ After:
<custom-code id="b6" direction="null" format="" indent="0" version="1" language="ts"><t id="t5">const x = 1</t></custom-code>
</doc>
```
+
+## Databases
+
+The XML shows a saved database question as `<database-query queryId displayMode title? prompt chart? height?/>`: a live number (`displayMode="scalar"`, inside a paragraph), table, or `bar`/`line`/`area`/`scatter`/`pie` chart that re-runs for each viewer. An embedded database is `<document-card blockName="database" blockParams='{"tableId":…,"viewId":…}'/>`.
+
+- `insertDatabaseQueryAfter(id, query)` · `insertDatabaseQueryBefore(id, query)` · `appendDatabaseQuery(query)` -- `query` is the `<m-db-query>…</m-db-query>` block from the task, passed verbatim as a string. Never write or alter one yourself; without a block in the task, report that one is needed.
+- `insertInlineDatabaseQuery(blockId, at, query)` -- a `scalar` block inside a sentence.
+- `setDatabaseQueryView(id, { displayMode?, title?, chart?, height? })` -- change how an existing answer is shown; `null` removes `title`, `chart`, or `height`. The question itself never changes. Chart modes need `chart: { x, y: string[], color?, stack?, title? }` naming result columns: keep the existing chart's columns unless the task names others. A `scalar` cannot become a table or chart in place.
+- `setDatabaseLocation(cardId, { tableId, viewId? })` -- show another table or view of an embedded database. Use ids from the task or the card's `blockParams`; an omitted `viewId` shows the table's default view.
+- Embed a database: `{ block: 'document-card', documentId: databaseId, documentName, blockName: 'database', blockParams: { tableId, viewId } }`.
+
+```ts
+const chart = editor.insertDatabaseQueryAfter('h1', '<m-db-query>{"queryId":"q1","databaseId":"db1","title":"Deals by stage","prompt":"Deals by stage","displayMode":"bar","chart":{"x":"stage","y":["deals"]}}</m-db-query>');
+editor.setDatabaseQueryView(chart, { displayMode: 'pie' });
+editor.setDatabaseLocation('card1', { tableId: 'tbl2' });
+```
diff --git a/services/ai-editing-worker/src/ai-editing/prompts/FAST.md b/services/ai-editing-worker/src/ai-editing/prompts/FAST.md
index b2b5eb7db0..9aaa533e7e 100644
--- a/services/ai-editing-worker/src/ai-editing/prompts/FAST.md
+++ b/services/ai-editing-worker/src/ai-editing/prompts/FAST.md
@@ -4,4 +4,4 @@ You are the sole editor. There is no supervisor and no other writers: the user's
- You see the ENTIRE document, line-numbered. When the request names node ids (e.g. "User is selecting nodes ..."), that is the region the user means; stay within it unless the request clearly asks for more.
- **Do not write any text before your first tool call.** Your first output must be a `runCode` call that carries out the whole request. Check each reply's effect report and fix anything that is not what you meant; call `readDocument` to see the document after your own edits.
-- Call `reportBlocked` only when the request cannot be carried out or needs information only the user can give (e.g. an id for a mention or document card that was not provided). Your message must tell the user what to supply. Never use it because the edit is large.
+- Call `reportBlocked` only when the request cannot be carried out or needs information only the user can give (e.g. an id for a mention or document card, or the `<m-db-query>` block for a database answer or chart, that was not provided). Your message must tell the user what to supply. Never use it because the edit is large.
diff --git a/services/ai-editing-worker/src/ai-editing/prompts/SUPERVISOR.md b/services/ai-editing-worker/src/ai-editing/prompts/SUPERVISOR.md
index f9a6c3b14b..e8251650e4 100644
--- a/services/ai-editing-worker/src/ai-editing/prompts/SUPERVISOR.md
+++ b/services/ai-editing-worker/src/ai-editing/prompts/SUPERVISOR.md
@@ -20,7 +20,7 @@ You should aim to complete the task in few dispatch rounds, and should plan care
You should provide high level English instructions to writers about the changes you want different writers to do. For example, "move paragraph Mz5qcIFm to be right above the q3IMz52m heading." Our writers are non technical and can't understand Markdown or coding terms. Try to avoid telling them *how* to do things. Figuring out how to make changes to documents what they are trained to do.
- Mention existing XML ids for the target region. The writers only get to see context surrounding mentioned nodes.
-- To mention a person, date/time, document, channel, agent session, booking link, or other chip, use the ids and details from the request (userId/email, documentId/documentName/blockName, session id, ISO date plus displayFormat, booking-link profileId/slug/url). Date chips do not need a looked-up id. To add a document-card, use the `documentId`/`documentName`/`blockName` from the request. Do not write literal XML/Markdown unless the user wants those literal characters. Do not type `@Name` as plain text when a mention chip exists.
+- To mention a person, date/time, document, channel, agent session, booking link, or other chip, use the ids and details from the request (userId/email, documentId/documentName/blockName, session id, ISO date plus displayFormat, booking-link profileId/slug/url). Date chips do not need a looked-up id. To add a document-card, use the `documentId`/`documentName`/`blockName` from the request. To add a live database answer or chart, hand the writer the request's `<m-db-query>…</m-db-query>` block verbatim; an embedded database is a document-card with `blockName: 'database'` and `blockParams` `{ tableId, viewId }`. Do not write literal XML/Markdown unless the user wants those literal characters. Do not type `@Name` as plain text when a mention chip exists.
- Do not invent or preserve ids. New ids are assigned automatically and existing ids may change.
- Do not write code yourself; describe the change mechanically.
- Do not try to inject formatting like bullet unicode into your snippets. Let the writer handle the formatting.
@@ -39,5 +39,5 @@ If the document meets the users request you are done. Otherwise dispatch an addi
- You MUST call `reportBlocked` if you need more information -- never write clarification text directly as a response.
- Your message must be a directive to invoke you again with what is missing.
-- Always call it before attempting an entity mention or document-card if the required ids were not provided in the request. Date/time chips do not need ids — invent the ISO timestamp and displayFormat. Do not invent or guess entity ids.
+- Always call it before attempting an entity mention, document-card, or database answer if the required ids or `<m-db-query>` block were not provided in the request. Date/time chips do not need ids — invent the ISO timestamp and displayFormat. Do not invent or guess entity ids.
- Do not use it just because an edit is complex -- attempt those directly.
diff --git a/services/ai-editing-worker/src/ai-editing/queue/animators.ts b/services/ai-editing-worker/src/ai-editing/queue/animators.ts
index 1d1844da73..067703f45d 100644
--- a/services/ai-editing-worker/src/ai-editing/queue/animators.ts
+++ b/services/ai-editing-worker/src/ai-editing/queue/animators.ts
@@ -557,6 +557,15 @@ export function animate(op: DocumentOp, ctx: AnimatorCtx): DocumentOpStep[] {
displayFormat: o.displayFormat,
}),
])
+ // databases — focus the block, apply the presentation or location change
+ .with({ kind: 'setDatabaseQueryView' }, (o) => [
+ ...focus(o.node, ctx),
+ edit(o),
+ ])
+ .with({ kind: 'setDatabaseLocation' }, (o) => [
+ ...focus(o.node, ctx),
+ edit(o),
+ ])
// animation primitives — pass through as-is (animators call these directly,
// but they should never be dispatched through animate() in normal use)
.with({ kind: 'insertText' }, (o) => [edit(o)])
diff --git a/services/ai-editing-worker/src/ai-editing/runtime.test.ts b/services/ai-editing-worker/src/ai-editing/runtime.test.ts
index d19f84834f..de4aebdb8f 100644
--- a/services/ai-editing-worker/src/ai-editing/runtime.test.ts
+++ b/services/ai-editing-worker/src/ai-editing/runtime.test.ts
@@ -173,3 +173,28 @@ describe('runtime — awareness ref resolution', () => {
expect(awareness.seen.every((x) => real.has(x.node))).toBe(true);
});
});
+
+describe('runtime — database blocks', () => {
+ it('inserts a saved chart, restyles it, and retargets an embedded database', async () => {
+ const { session } = build(
+ 'Pipeline\n\n<m-document-card>{"documentId":"db-1","documentName":"Projects","blockName":"database","blockParams":{"tableId":"table-1","viewId":"view-1"}}</m-document-card>'
+ );
+ const [headingId, cardId] = topIds(session);
+ const chart =
+ '<m-db-query>{"queryId":"q-1","databaseId":"db-1","title":"By owner","prompt":"Projects per owner","displayMode":"bar","chart":{"x":"owner","y":["projects"]}}</m-db-query>';
+ const summary = await runCode(
+ session,
+ `const chart = editor.insertDatabaseQueryAfter('${headingId}', ${JSON.stringify(chart)});
+ editor.setDatabaseQueryView(chart, { displayMode: 'line' });
+ editor.setDatabaseLocation('${cardId}', { tableId: 'table-2' });`
+ );
+ expect(summary).toContain('CHANGED');
+ const xml = serializeWithXml(session);
+ expect(xml).toContain(
+ '<database-query id="ref-1" queryId="q-1" databaseId="db-1" displayMode="line" title="By owner" prompt="Projects per owner" chart="{&quot;x&quot;:&quot;owner&quot;,&quot;y&quot;:[&quot;projects&quot;]}"/>'
+ );
+ expect(xml).toContain(
+ 'blockParams="{&quot;tableId&quot;:&quot;table-2&quot;,&quot;viewId&quot;:&quot;&quot;}"'
+ );
+ });
+});
diff --git a/services/ai-editing-worker/src/editor-sandbox-code.ts b/services/ai-editing-worker/src/editor-sandbox-code.ts
index 5ba938e525..0f86ffe395 100644
--- a/services/ai-editing-worker/src/editor-sandbox-code.ts
+++ b/services/ai-editing-worker/src/editor-sandbox-code.ts
@@ -2,4 +2,4 @@
// Source of truth: src/ai-editing/editor/document-editor.ts
// biome-ignore-all lint/suspicious/noTemplateCurlyInString: generated JS contains template literals
export const SANDBOX_CODE =
- 'class EditError extends Error {\n constructor(message) {\n super(message);\n this.name = "EditError";\n }\n}\n\nfunction describeBadId(value) {\n if (value === null)\n return "null";\n if (value === undefined)\n return "undefined";\n if (Array.isArray(value))\n return `an array of ${value.length}`;\n if (typeof value === "object") {\n const keys = Object.keys(value).slice(0, 4);\n return `an object with keys [${keys.join(", ")}]`;\n }\n return `a ${typeof value} (${String(value)})`;\n}\n\nclass DocumentEditor {\n ops = [];\n valid;\n refs;\n refIdx = 0;\n constructor(opts) {\n this.valid = new Set(opts.validIds);\n this.refs = opts.refs;\n }\n push(op) {\n this.ops.push(op);\n return this;\n }\n requireId(id) {\n if (typeof id !== "string") {\n throw new EditError(`expected a node id string but got ${describeBadId(id)}. ` + "Insert helpers return the new node\'s id directly, so use that value " + "as-is rather than a property of it.");\n }\n if (id.length === 0)\n throw new EditError("node id is an empty string");\n if (!this.valid.has(id)) {\n throw new EditError(`unknown id "${id}"`);\n }\n }\n requireMatch(match) {\n if (match.length === 0)\n throw new EditError("match string is empty");\n }\n mintRef() {\n const ref = this.refs[this.refIdx++];\n if (!ref) {\n throw new EditError("too many inserts in one snippet (id pool exhausted)");\n }\n this.valid.add(ref);\n return ref;\n }\n drain() {\n const out = this.ops;\n this.ops = [];\n return out;\n }\n format(id, match, format, on = true, scope = { kind: "all" }) {\n this.requireId(id);\n this.requireMatch(match);\n return this.push({\n kind: "formatText",\n node: id,\n match,\n format,\n on,\n scope\n });\n }\n bold(id, match, scope) {\n return this.format(id, match, "bold", true, scope);\n }\n italic(id, match, scope) {\n return this.format(id, match, "italic", true, scope);\n }\n underline(id, match, scope) {\n return this.format(id, match, "underline", true, scope);\n }\n strike(id, match, scope) {\n return this.format(id, match, "strike", true, scope);\n }\n inlineCode(id, match, scope) {\n return this.format(id, match, "code", true, scope);\n }\n unbold(id, match, scope) {\n return this.format(id, match, "bold", false, scope);\n }\n unitalic(id, match, scope) {\n return this.format(id, match, "italic", false, scope);\n }\n ununderline(id, match, scope) {\n return this.format(id, match, "underline", false, scope);\n }\n unstrike(id, match, scope) {\n return this.format(id, match, "strike", false, scope);\n }\n uninlineCode(id, match, scope) {\n return this.format(id, match, "code", false, scope);\n }\n clearFormat(id, match, scope = { kind: "all" }) {\n this.requireId(id);\n if (match !== undefined)\n this.requireMatch(match);\n return this.push({ kind: "clearFormat", node: id, match, scope });\n }\n clearAllFormat(id) {\n return this.clearFormat(id);\n }\n highlight(id, match, scope = { kind: "all" }) {\n this.requireId(id);\n this.requireMatch(match);\n return this.push({ kind: "markText", node: id, match, on: true, scope });\n }\n unhighlight(id, match, scope = { kind: "all" }) {\n this.requireId(id);\n this.requireMatch(match);\n return this.push({ kind: "markText", node: id, match, on: false, scope });\n }\n link(id, match, url, scope = { kind: "all" }) {\n this.requireId(id);\n this.requireMatch(match);\n return this.push({ kind: "linkText", node: id, match, url, scope });\n }\n unlink(id, match, scope = { kind: "all" }) {\n this.requireId(id);\n this.requireMatch(match);\n return this.push({ kind: "linkText", node: id, match, url: null, scope });\n }\n formatNode(node, format, on = true) {\n this.requireId(node);\n return this.push({ kind: "formatNode", node, format, on });\n }\n boldNode(node) {\n return this.formatNode(node, "bold");\n }\n italicNode(node) {\n return this.formatNode(node, "italic");\n }\n underlineNode(node) {\n return this.formatNode(node, "underline");\n }\n strikeNode(node) {\n return this.formatNode(node, "strike");\n }\n codeNode(node) {\n return this.formatNode(node, "code");\n }\n clearNodeFormat(node) {\n this.requireId(node);\n return this.push({ kind: "clearNodeFormat", node });\n }\n setText(id, text) {\n this.requireId(id);\n return this.push({ kind: "setText", node: id, text });\n }\n setEquation(id, tex) {\n this.requireId(id);\n return this.push({ kind: "setEquation", node: id, tex });\n }\n replace(id, find, to, scope = { kind: "all" }) {\n this.requireId(id);\n if (find.length === 0)\n throw new EditError("find string is empty");\n return this.push({ kind: "replaceText", node: id, find, to, scope });\n }\n appendText(id, text) {\n this.requireId(id);\n return this.push({ kind: "appendText", node: id, text });\n }\n prependText(id, text) {\n this.requireId(id);\n return this.push({ kind: "prependText", node: id, text });\n }\n setBlockType(id, args) {\n this.requireId(id);\n return this.push({ kind: "setBlockType", node: id, ...args });\n }\n requireLanguage(language) {\n if (typeof language !== "string" || language.trim().length === 0)\n throw new EditError("code block language is required");\n }\n convertToParagraph(id) {\n return this.setBlockType(id, { block: "paragraph" });\n }\n convertToHeading(id, level) {\n if (level < 1 || level > 6)\n throw new EditError(`heading level must be 1-6, got ${level}`);\n return this.setBlockType(id, { block: "heading", level });\n }\n convertToQuote(id) {\n return this.setBlockType(id, { block: "quote" });\n }\n convertToCodeBlock(id, language) {\n this.requireLanguage(language);\n return this.setBlockType(id, { block: "code", language });\n }\n setLanguage(id, language) {\n return this.convertToCodeBlock(id, language);\n }\n toList(idOrIds, list) {\n const ids = Array.isArray(idOrIds) ? idOrIds : [idOrIds];\n if (ids.length === 0)\n throw new EditError("list requires at least one block");\n for (const id of ids)\n this.requireId(id);\n return this.push({ kind: "setListType", nodes: ids, list });\n }\n bulletList(idOrIds) {\n return this.toList(idOrIds, "bullet");\n }\n numberedList(idOrIds) {\n return this.toList(idOrIds, "number");\n }\n checklist(idOrIds) {\n return this.toList(idOrIds, "check");\n }\n setListType(id, list) {\n return this.toList(id, list);\n }\n check(id) {\n return this.setChecked(id, true);\n }\n uncheck(id) {\n return this.setChecked(id, false);\n }\n setChecked(id, checked) {\n this.requireId(id);\n return this.push({ kind: "setChecked", node: id, checked });\n }\n indent(id, by = 1) {\n this.requireId(id);\n return this.push({\n kind: "setIndent",\n node: id,\n indent: by >= 0 ? "in" : "out"\n });\n }\n outdent(id, by = 1) {\n return this.indent(id, -Math.abs(by));\n }\n setIndent(id, level) {\n this.requireId(id);\n if (level < 0)\n throw new EditError(`indent level must be >= 0, got ${level}`);\n return this.push({ kind: "setIndent", node: id, indent: level });\n }\n insertListItemAfter(id, text, list = "bullet") {\n this.requireId(id);\n const ref = this.mintRef();\n this.push({ kind: "insertListItemAfter", ref, node: id, text, list });\n return ref;\n }\n insertListItemBefore(id, text, list = "bullet") {\n this.requireId(id);\n const ref = this.mintRef();\n this.push({ kind: "insertListItemBefore", ref, node: id, text, list });\n return ref;\n }\n appendListItem(listId, text) {\n this.requireId(listId);\n const ref = this.mintRef();\n this.push({ kind: "appendListItem", ref, node: listId, text });\n return ref;\n }\n prependListItem(listId, text) {\n this.requireId(listId);\n const ref = this.mintRef();\n this.push({ kind: "prependListItem", ref, node: listId, text });\n return ref;\n }\n removeListItem(id) {\n this.requireId(id);\n return this.push({ kind: "removeListItem", node: id });\n }\n insert(spec, at) {\n this.requireAt(at);\n const ref = this.mintRef();\n this.push({ kind: "insertNode", ref, spec, at });\n return ref;\n }\n requireAt(at) {\n if ("after" in at)\n this.requireId(at.after);\n else if ("before" in at)\n this.requireId(at.before);\n }\n insertParagraphAfter(id, text = "") {\n return this.insert({ block: "paragraph", text }, { after: id });\n }\n insertParagraphBefore(id, text = "") {\n return this.insert({ block: "paragraph", text }, { before: id });\n }\n insertHeadingAfter(id, level, text = "") {\n return this.insert({ block: "heading", level, text }, { after: id });\n }\n insertHeadingBefore(id, level, text = "") {\n return this.insert({ block: "heading", level, text }, { before: id });\n }\n insertQuoteAfter(id, text = "") {\n return this.insert({ block: "quote", text }, { after: id });\n }\n insertCodeBlockAfter(id, language, text = "") {\n this.requireLanguage(language);\n return this.insert({ block: "code", language, text }, { after: id });\n }\n insertBlockAfter(id, spec) {\n return this.insert(spec, { after: id });\n }\n insertBlockBefore(id, spec) {\n return this.insert(spec, { before: id });\n }\n appendParagraph(text = "") {\n return this.insert({ block: "paragraph", text }, { appendToRoot: true });\n }\n prependParagraph(text = "") {\n return this.insert({ block: "paragraph", text }, { prependToRoot: true });\n }\n appendBlock(spec) {\n return this.insert(spec, { appendToRoot: true });\n }\n prependBlock(spec) {\n return this.insert(spec, { prependToRoot: true });\n }\n move(id, at) {\n this.requireId(id);\n this.requireAt(at);\n return this.push({ kind: "moveNode", node: id, at });\n }\n remove(id) {\n this.requireId(id);\n return this.push({ kind: "removeNode", node: id });\n }\n removeMany(ids) {\n for (const id of ids)\n this.remove(id);\n return this;\n }\n merge(ids, separator = " ") {\n if (ids.length < 2)\n throw new EditError("merge requires at least two blocks");\n for (const id of ids)\n this.requireId(id);\n return this.push({ kind: "mergeBlocks", nodes: ids, separator });\n }\n insertTableAfter(id, rows) {\n return this.buildTable(rows, { after: id });\n }\n insertTableBefore(id, rows) {\n return this.buildTable(rows, { before: id });\n }\n appendTable(rows) {\n return this.buildTable(rows, { appendToRoot: true });\n }\n buildTable(rows, at) {\n if (rows.length === 0)\n throw new EditError("table requires at least one row");\n const empty = rows.map((row) => row.map(() => ""));\n const ref = this.insert({ block: "table", rows: empty }, at);\n rows.forEach((row, r) => void row.forEach((cell, c) => {\n if (cell)\n this.setCell(ref, r, c, cell);\n }));\n return ref;\n }\n setCell(table, row, col, text) {\n this.requireId(table);\n this.requireCell(row, col);\n return this.push({ kind: "setCell", table, row, col, text });\n }\n addRow(table, at) {\n this.requireId(table);\n return this.push({ kind: "addRow", table, at });\n }\n addColumn(table, at) {\n this.requireId(table);\n return this.push({ kind: "addColumn", table, at });\n }\n removeRow(table, row) {\n this.requireId(table);\n this.requireCell(row, 0);\n return this.push({ kind: "removeRow", table, row });\n }\n removeColumn(table, col) {\n this.requireId(table);\n this.requireCell(0, col);\n return this.push({ kind: "removeColumn", table, col });\n }\n requireCell(row, col) {\n if (row < 0 || col < 0)\n throw new EditError(`cell indices must be >= 0, got (${row}, ${col})`);\n }\n insertDivider(afterId) {\n return this.insert({ block: "divider" }, { after: afterId });\n }\n insertImage(afterId, img) {\n return this.insert({ block: "image", ...img }, { after: afterId });\n }\n insertVideo(afterId, vid) {\n return this.insert({ block: "video", ...vid }, { after: afterId });\n }\n insertEquation(afterId, tex) {\n return this.insert({ block: "equation", tex }, { after: afterId });\n }\n insertInlineEquation(blockId, at, tex) {\n return this.insertInline(blockId, at, { inline: "equation", tex });\n }\n insertTextAfterInline(inlineRef, text) {\n return this.push({\n kind: "insertTextAfterInline",\n inline: inlineRef,\n text\n });\n }\n insertLineBreak(blockId, at) {\n return this.insertInline(blockId, at, { inline: "linebreak" });\n }\n insertDate(blockId, at, isoDate, displayFormat) {\n return this.insertInline(blockId, at, {\n inline: "date",\n date: isoDate,\n displayFormat\n });\n }\n mentionDate(blockId, at, isoDate, displayFormat) {\n return this.insertDate(blockId, at, isoDate, displayFormat);\n }\n insertInline(id, at, spec) {\n this.requireId(id);\n if (at < 0)\n throw new EditError(`inline offset must be >= 0, got ${at}`);\n const ref = this.mintRef();\n this.push({ kind: "insertInline", ref, node: id, at, spec });\n return ref;\n }\n insertMention(blockId, at, mention) {\n return this.insertInline(blockId, at, { inline: "mention", mention });\n }\n mentionUser(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "user", ...entity });\n }\n mentionContact(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "contact", ...entity });\n }\n mentionGroup(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "group", ...entity });\n }\n mentionDocument(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "document", ...entity });\n }\n mentionAgentSession(blockId, at, entity) {\n return this.insertMention(blockId, at, {\n kind: "agent_session",\n ...entity\n });\n }\n mentionPullRequest(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "pr", ...entity });\n }\n mentionBookingLink(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "booking_link", ...entity });\n }\n mentionTag(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "tag", ...entity });\n }\n setImageAlt(id, alt) {\n this.requireId(id);\n return this.push({ kind: "setImageAlt", node: id, alt });\n }\n setImageUrl(id, url) {\n this.requireId(id);\n return this.push({ kind: "setImageUrl", node: id, url });\n }\n setVideoUrl(id, url) {\n this.requireId(id);\n return this.push({ kind: "setVideoUrl", node: id, url });\n }\n setVideoControls(id, controls) {\n this.requireId(id);\n return this.push({ kind: "setVideoControls", node: id, controls });\n }\n setDate(id, date, displayFormat) {\n this.requireId(id);\n return this.push({ kind: "setDate", node: id, date, displayFormat });\n }\n}\nfunction editorMethodNames(target) {\n const names = new Set;\n for (let proto = target;proto && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {\n for (const key of Object.getOwnPropertyNames(proto)) {\n if (key === "constructor" || key.startsWith("_"))\n continue;\n if (typeof target[key] === "function") {\n names.add(key);\n }\n }\n }\n return [...names];\n}\nfunction suggestMethods(wanted, names) {\n const normalizedWanted = wanted.toLowerCase();\n const scored = names.map((name) => {\n const normalizedName = name.toLowerCase();\n let score = 0;\n if (normalizedName === normalizedWanted)\n score = 1000;\n else if (normalizedName.includes(normalizedWanted) || normalizedWanted.includes(normalizedName)) {\n score = 100 + Math.min(normalizedName.length, normalizedWanted.length);\n } else {\n while (score < normalizedName.length && score < normalizedWanted.length && normalizedName[score] === normalizedWanted[score]) {\n score++;\n }\n }\n return { name, score };\n });\n scored.sort((a, b) => b.score - a.score);\n return scored.filter(({ score }) => score >= 3).slice(0, 3).map(({ name }) => name);\n}\nfunction createDocumentEditor(options) {\n const target = new DocumentEditor(options);\n return new Proxy(target, {\n get(editor, property) {\n const value = editor[property];\n if (value !== undefined || typeof property !== "string") {\n return typeof value === "function" ? value.bind(editor) : value;\n }\n return () => {\n const suggestions = suggestMethods(property, editorMethodNames(editor));\n throw new Error(`editor.${property} does not exist` + (suggestions.length ? `. Did you mean: ${suggestions.join(", ")}?` : ".") + " The editor is write-only — to inspect the document use the readDocument tool, not a call inside the snippet.");\n };\n }\n });\n}';
+ 'class EditError extends Error {\n constructor(message) {\n super(message);\n this.name = "EditError";\n }\n}\n\nfunction describeBadId(value) {\n if (value === null)\n return "null";\n if (value === undefined)\n return "undefined";\n if (Array.isArray(value))\n return `an array of ${value.length}`;\n if (typeof value === "object") {\n const keys = Object.keys(value).slice(0, 4);\n return `an object with keys [${keys.join(", ")}]`;\n }\n return `a ${typeof value} (${String(value)})`;\n}\n\nclass DocumentEditor {\n ops = [];\n valid;\n refs;\n refIdx = 0;\n constructor(opts) {\n this.valid = new Set(opts.validIds);\n this.refs = opts.refs;\n }\n push(op) {\n this.ops.push(op);\n return this;\n }\n requireId(id) {\n if (typeof id !== "string") {\n throw new EditError(`expected a node id string but got ${describeBadId(id)}. ` + "Insert helpers return the new node\'s id directly, so use that value " + "as-is rather than a property of it.");\n }\n if (id.length === 0)\n throw new EditError("node id is an empty string");\n if (!this.valid.has(id)) {\n throw new EditError(`unknown id "${id}"`);\n }\n }\n requireMatch(match) {\n if (match.length === 0)\n throw new EditError("match string is empty");\n }\n mintRef() {\n const ref = this.refs[this.refIdx++];\n if (!ref) {\n throw new EditError("too many inserts in one snippet (id pool exhausted)");\n }\n this.valid.add(ref);\n return ref;\n }\n drain() {\n const out = this.ops;\n this.ops = [];\n return out;\n }\n format(id, match, format, on = true, scope = { kind: "all" }) {\n this.requireId(id);\n this.requireMatch(match);\n return this.push({\n kind: "formatText",\n node: id,\n match,\n format,\n on,\n scope\n });\n }\n bold(id, match, scope) {\n return this.format(id, match, "bold", true, scope);\n }\n italic(id, match, scope) {\n return this.format(id, match, "italic", true, scope);\n }\n underline(id, match, scope) {\n return this.format(id, match, "underline", true, scope);\n }\n strike(id, match, scope) {\n return this.format(id, match, "strike", true, scope);\n }\n inlineCode(id, match, scope) {\n return this.format(id, match, "code", true, scope);\n }\n unbold(id, match, scope) {\n return this.format(id, match, "bold", false, scope);\n }\n unitalic(id, match, scope) {\n return this.format(id, match, "italic", false, scope);\n }\n ununderline(id, match, scope) {\n return this.format(id, match, "underline", false, scope);\n }\n unstrike(id, match, scope) {\n return this.format(id, match, "strike", false, scope);\n }\n uninlineCode(id, match, scope) {\n return this.format(id, match, "code", false, scope);\n }\n clearFormat(id, match, scope = { kind: "all" }) {\n this.requireId(id);\n if (match !== undefined)\n this.requireMatch(match);\n return this.push({ kind: "clearFormat", node: id, match, scope });\n }\n clearAllFormat(id) {\n return this.clearFormat(id);\n }\n highlight(id, match, scope = { kind: "all" }) {\n this.requireId(id);\n this.requireMatch(match);\n return this.push({ kind: "markText", node: id, match, on: true, scope });\n }\n unhighlight(id, match, scope = { kind: "all" }) {\n this.requireId(id);\n this.requireMatch(match);\n return this.push({ kind: "markText", node: id, match, on: false, scope });\n }\n link(id, match, url, scope = { kind: "all" }) {\n this.requireId(id);\n this.requireMatch(match);\n return this.push({ kind: "linkText", node: id, match, url, scope });\n }\n unlink(id, match, scope = { kind: "all" }) {\n this.requireId(id);\n this.requireMatch(match);\n return this.push({ kind: "linkText", node: id, match, url: null, scope });\n }\n formatNode(node, format, on = true) {\n this.requireId(node);\n return this.push({ kind: "formatNode", node, format, on });\n }\n boldNode(node) {\n return this.formatNode(node, "bold");\n }\n italicNode(node) {\n return this.formatNode(node, "italic");\n }\n underlineNode(node) {\n return this.formatNode(node, "underline");\n }\n strikeNode(node) {\n return this.formatNode(node, "strike");\n }\n codeNode(node) {\n return this.formatNode(node, "code");\n }\n clearNodeFormat(node) {\n this.requireId(node);\n return this.push({ kind: "clearNodeFormat", node });\n }\n setText(id, text) {\n this.requireId(id);\n return this.push({ kind: "setText", node: id, text });\n }\n setEquation(id, tex) {\n this.requireId(id);\n return this.push({ kind: "setEquation", node: id, tex });\n }\n replace(id, find, to, scope = { kind: "all" }) {\n this.requireId(id);\n if (find.length === 0)\n throw new EditError("find string is empty");\n return this.push({ kind: "replaceText", node: id, find, to, scope });\n }\n appendText(id, text) {\n this.requireId(id);\n return this.push({ kind: "appendText", node: id, text });\n }\n prependText(id, text) {\n this.requireId(id);\n return this.push({ kind: "prependText", node: id, text });\n }\n setBlockType(id, args) {\n this.requireId(id);\n return this.push({ kind: "setBlockType", node: id, ...args });\n }\n requireLanguage(language) {\n if (typeof language !== "string" || language.trim().length === 0)\n throw new EditError("code block language is required");\n }\n convertToParagraph(id) {\n return this.setBlockType(id, { block: "paragraph" });\n }\n convertToHeading(id, level) {\n if (level < 1 || level > 6)\n throw new EditError(`heading level must be 1-6, got ${level}`);\n return this.setBlockType(id, { block: "heading", level });\n }\n convertToQuote(id) {\n return this.setBlockType(id, { block: "quote" });\n }\n convertToCodeBlock(id, language) {\n this.requireLanguage(language);\n return this.setBlockType(id, { block: "code", language });\n }\n setLanguage(id, language) {\n return this.convertToCodeBlock(id, language);\n }\n toList(idOrIds, list) {\n const ids = Array.isArray(idOrIds) ? idOrIds : [idOrIds];\n if (ids.length === 0)\n throw new EditError("list requires at least one block");\n for (const id of ids)\n this.requireId(id);\n return this.push({ kind: "setListType", nodes: ids, list });\n }\n bulletList(idOrIds) {\n return this.toList(idOrIds, "bullet");\n }\n numberedList(idOrIds) {\n return this.toList(idOrIds, "number");\n }\n checklist(idOrIds) {\n return this.toList(idOrIds, "check");\n }\n setListType(id, list) {\n return this.toList(id, list);\n }\n check(id) {\n return this.setChecked(id, true);\n }\n uncheck(id) {\n return this.setChecked(id, false);\n }\n setChecked(id, checked) {\n this.requireId(id);\n return this.push({ kind: "setChecked", node: id, checked });\n }\n indent(id, by = 1) {\n this.requireId(id);\n return this.push({\n kind: "setIndent",\n node: id,\n indent: by >= 0 ? "in" : "out"\n });\n }\n outdent(id, by = 1) {\n return this.indent(id, -Math.abs(by));\n }\n setIndent(id, level) {\n this.requireId(id);\n if (level < 0)\n throw new EditError(`indent level must be >= 0, got ${level}`);\n return this.push({ kind: "setIndent", node: id, indent: level });\n }\n insertListItemAfter(id, text, list = "bullet") {\n this.requireId(id);\n const ref = this.mintRef();\n this.push({ kind: "insertListItemAfter", ref, node: id, text, list });\n return ref;\n }\n insertListItemBefore(id, text, list = "bullet") {\n this.requireId(id);\n const ref = this.mintRef();\n this.push({ kind: "insertListItemBefore", ref, node: id, text, list });\n return ref;\n }\n appendListItem(listId, text) {\n this.requireId(listId);\n const ref = this.mintRef();\n this.push({ kind: "appendListItem", ref, node: listId, text });\n return ref;\n }\n prependListItem(listId, text) {\n this.requireId(listId);\n const ref = this.mintRef();\n this.push({ kind: "prependListItem", ref, node: listId, text });\n return ref;\n }\n removeListItem(id) {\n this.requireId(id);\n return this.push({ kind: "removeListItem", node: id });\n }\n insert(spec, at) {\n this.requireAt(at);\n const ref = this.mintRef();\n this.push({ kind: "insertNode", ref, spec, at });\n return ref;\n }\n requireAt(at) {\n if ("after" in at)\n this.requireId(at.after);\n else if ("before" in at)\n this.requireId(at.before);\n }\n insertParagraphAfter(id, text = "") {\n return this.insert({ block: "paragraph", text }, { after: id });\n }\n insertParagraphBefore(id, text = "") {\n return this.insert({ block: "paragraph", text }, { before: id });\n }\n insertHeadingAfter(id, level, text = "") {\n return this.insert({ block: "heading", level, text }, { after: id });\n }\n insertHeadingBefore(id, level, text = "") {\n return this.insert({ block: "heading", level, text }, { before: id });\n }\n insertQuoteAfter(id, text = "") {\n return this.insert({ block: "quote", text }, { after: id });\n }\n insertCodeBlockAfter(id, language, text = "") {\n this.requireLanguage(language);\n return this.insert({ block: "code", language, text }, { after: id });\n }\n insertBlockAfter(id, spec) {\n return this.insert(spec, { after: id });\n }\n insertBlockBefore(id, spec) {\n return this.insert(spec, { before: id });\n }\n appendParagraph(text = "") {\n return this.insert({ block: "paragraph", text }, { appendToRoot: true });\n }\n prependParagraph(text = "") {\n return this.insert({ block: "paragraph", text }, { prependToRoot: true });\n }\n appendBlock(spec) {\n return this.insert(spec, { appendToRoot: true });\n }\n prependBlock(spec) {\n return this.insert(spec, { prependToRoot: true });\n }\n move(id, at) {\n this.requireId(id);\n this.requireAt(at);\n return this.push({ kind: "moveNode", node: id, at });\n }\n remove(id) {\n this.requireId(id);\n return this.push({ kind: "removeNode", node: id });\n }\n removeMany(ids) {\n for (const id of ids)\n this.remove(id);\n return this;\n }\n merge(ids, separator = " ") {\n if (ids.length < 2)\n throw new EditError("merge requires at least two blocks");\n for (const id of ids)\n this.requireId(id);\n return this.push({ kind: "mergeBlocks", nodes: ids, separator });\n }\n insertTableAfter(id, rows) {\n return this.buildTable(rows, { after: id });\n }\n insertTableBefore(id, rows) {\n return this.buildTable(rows, { before: id });\n }\n appendTable(rows) {\n return this.buildTable(rows, { appendToRoot: true });\n }\n buildTable(rows, at) {\n if (rows.length === 0)\n throw new EditError("table requires at least one row");\n const empty = rows.map((row) => row.map(() => ""));\n const ref = this.insert({ block: "table", rows: empty }, at);\n rows.forEach((row, r) => void row.forEach((cell, c) => {\n if (cell)\n this.setCell(ref, r, c, cell);\n }));\n return ref;\n }\n setCell(table, row, col, text) {\n this.requireId(table);\n this.requireCell(row, col);\n return this.push({ kind: "setCell", table, row, col, text });\n }\n addRow(table, at) {\n this.requireId(table);\n return this.push({ kind: "addRow", table, at });\n }\n addColumn(table, at) {\n this.requireId(table);\n return this.push({ kind: "addColumn", table, at });\n }\n removeRow(table, row) {\n this.requireId(table);\n this.requireCell(row, 0);\n return this.push({ kind: "removeRow", table, row });\n }\n removeColumn(table, col) {\n this.requireId(table);\n this.requireCell(0, col);\n return this.push({ kind: "removeColumn", table, col });\n }\n requireCell(row, col) {\n if (row < 0 || col < 0)\n throw new EditError(`cell indices must be >= 0, got (${row}, ${col})`);\n }\n insertDivider(afterId) {\n return this.insert({ block: "divider" }, { after: afterId });\n }\n insertImage(afterId, img) {\n return this.insert({ block: "image", ...img }, { after: afterId });\n }\n insertVideo(afterId, vid) {\n return this.insert({ block: "video", ...vid }, { after: afterId });\n }\n insertEquation(afterId, tex) {\n return this.insert({ block: "equation", tex }, { after: afterId });\n }\n insertInlineEquation(blockId, at, tex) {\n return this.insertInline(blockId, at, { inline: "equation", tex });\n }\n insertTextAfterInline(inlineRef, text) {\n return this.push({\n kind: "insertTextAfterInline",\n inline: inlineRef,\n text\n });\n }\n insertLineBreak(blockId, at) {\n return this.insertInline(blockId, at, { inline: "linebreak" });\n }\n insertDate(blockId, at, isoDate, displayFormat) {\n return this.insertInline(blockId, at, {\n inline: "date",\n date: isoDate,\n displayFormat\n });\n }\n mentionDate(blockId, at, isoDate, displayFormat) {\n return this.insertDate(blockId, at, isoDate, displayFormat);\n }\n insertInline(id, at, spec) {\n this.requireId(id);\n if (at < 0)\n throw new EditError(`inline offset must be >= 0, got ${at}`);\n const ref = this.mintRef();\n this.push({ kind: "insertInline", ref, node: id, at, spec });\n return ref;\n }\n insertMention(blockId, at, mention) {\n return this.insertInline(blockId, at, { inline: "mention", mention });\n }\n mentionUser(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "user", ...entity });\n }\n mentionContact(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "contact", ...entity });\n }\n mentionGroup(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "group", ...entity });\n }\n mentionDocument(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "document", ...entity });\n }\n mentionAgentSession(blockId, at, entity) {\n return this.insertMention(blockId, at, {\n kind: "agent_session",\n ...entity\n });\n }\n mentionPullRequest(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "pr", ...entity });\n }\n mentionBookingLink(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "booking_link", ...entity });\n }\n mentionTag(blockId, at, entity) {\n return this.insertMention(blockId, at, { kind: "tag", ...entity });\n }\n setImageAlt(id, alt) {\n this.requireId(id);\n return this.push({ kind: "setImageAlt", node: id, alt });\n }\n setImageUrl(id, url) {\n this.requireId(id);\n return this.push({ kind: "setImageUrl", node: id, url });\n }\n setVideoUrl(id, url) {\n this.requireId(id);\n return this.push({ kind: "setVideoUrl", node: id, url });\n }\n setVideoControls(id, controls) {\n this.requireId(id);\n return this.push({ kind: "setVideoControls", node: id, controls });\n }\n setDate(id, date, displayFormat) {\n this.requireId(id);\n return this.push({ kind: "setDate", node: id, date, displayFormat });\n }\n requireQueryBlock(query) {\n if (typeof query !== "string" || !query.includes("<m-db-query>")) {\n throw new EditError("pass the saved question\'s <m-db-query>…</m-db-query> block from the request, verbatim");\n }\n }\n insertDatabaseQueryAfter(id, query) {\n this.requireQueryBlock(query);\n return this.insert({ block: "database-query", query }, { after: id });\n }\n insertDatabaseQueryBefore(id, query) {\n this.requireQueryBlock(query);\n return this.insert({ block: "database-query", query }, { before: id });\n }\n appendDatabaseQuery(query) {\n this.requireQueryBlock(query);\n return this.insert({ block: "database-query", query }, { appendToRoot: true });\n }\n insertInlineDatabaseQuery(blockId, at, query) {\n this.requireQueryBlock(query);\n return this.insertInline(blockId, at, { inline: "database-query", query });\n }\n setDatabaseQueryView(id, view) {\n this.requireId(id);\n if (!view || typeof view !== "object" || !Object.keys(view).length) {\n throw new EditError("pass at least one of displayMode, title, chart, or height");\n }\n return this.push({ kind: "setDatabaseQueryView", node: id, view });\n }\n setDatabaseLocation(id, location) {\n this.requireId(id);\n if (typeof location?.tableId !== "string" || !location.tableId) {\n throw new EditError("setDatabaseLocation needs a tableId");\n }\n return this.push({\n kind: "setDatabaseLocation",\n node: id,\n tableId: location.tableId,\n viewId: location.viewId\n });\n }\n}\nfunction editorMethodNames(target) {\n const names = new Set;\n for (let proto = target;proto && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {\n for (const key of Object.getOwnPropertyNames(proto)) {\n if (key === "constructor" || key.startsWith("_"))\n continue;\n if (typeof target[key] === "function") {\n names.add(key);\n }\n }\n }\n return [...names];\n}\nfunction suggestMethods(wanted, names) {\n const normalizedWanted = wanted.toLowerCase();\n const scored = names.map((name) => {\n const normalizedName = name.toLowerCase();\n let score = 0;\n if (normalizedName === normalizedWanted)\n score = 1000;\n else if (normalizedName.includes(normalizedWanted) || normalizedWanted.includes(normalizedName)) {\n score = 100 + Math.min(normalizedName.length, normalizedWanted.length);\n } else {\n while (score < normalizedName.length && score < normalizedWanted.length && normalizedName[score] === normalizedWanted[score]) {\n score++;\n }\n }\n return { name, score };\n });\n scored.sort((a, b) => b.score - a.score);\n return scored.filter(({ score }) => score >= 3).slice(0, 3).map(({ name }) => name);\n}\nfunction createDocumentEditor(options) {\n const target = new DocumentEditor(options);\n return new Proxy(target, {\n get(editor, property) {\n const value = editor[property];\n if (value !== undefined || typeof property !== "string") {\n return typeof value === "function" ? value.bind(editor) : value;\n }\n return () => {\n const suggestions = suggestMethods(property, editorMethodNames(editor));\n throw new Error(`editor.${property} does not exist` + (suggestions.length ? `. Did you mean: ${suggestions.join(", ")}?` : ".") + " The editor is write-only — to inspect the document use the readDocument tool, not a call inside the snippet.");\n };\n }\n });\n}';