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.

chore(agents): teach AI editors all @-mention chips, including dates and agent sessions (#6366)

Wolf Mermelstein3dea96a7df0e
diff --git a/apps/docs/AI/mcp/tools/edit-document.mdx b/apps/docs/AI/mcp/tools/edit-document.mdx
index dd7a25e84f..a7882e2681 100644
--- a/apps/docs/AI/mcp/tools/edit-document.mdx
+++ b/apps/docs/AI/mcp/tools/edit-document.mdx
@@ -1,15 +1,15 @@
---
title: EditDocument
-description: "Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Uploaded files -- PDFs, DOCX, spreadsheets, 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(s), include each person's userId and email. 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. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Uploaded files -- PDFs, DOCX, spreadsheets, 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 automations; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips. To insert document-card(s), include each document's documentId and documentName."
---
# EditDocument
-Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Uploaded files -- PDFs, DOCX, spreadsheets, 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(s), include each person's userId and email. 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. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Uploaded files -- PDFs, DOCX, spreadsheets, 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 automations; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips. To insert document-card(s), include each document's documentId and documentName.
## Parameters
| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `document_id` | string | Yes | The ID of the markdown document to edit. If you are not certain the document is markdown, call ReadMetadata first and check that `fileType` is `md` -- passing an uploaded file here fails. |
-| `instructions` | string | Yes | Natural language instructions. For mention(s), include userId and email per person. For document-card(s), include documentId and documentName per document. You may need to look these up. |
+| `instructions` | string | Yes | Natural language instructions. For @-mention chips, include each item's ids and details: userId/email for people; documentId/documentName/blockName for documents and similar items; session id for agent sessions; ISO datetime and displayFormat for time chips. For document-card(s), include documentId and documentName per document. You may need to look these up. |
diff --git a/apps/web/src/lib/core/component/AI/util/stream/mentionPlugin.test.ts b/apps/web/src/lib/core/component/AI/util/stream/mentionPlugin.test.ts
index ae790cbeac..00604c1010 100644
--- a/apps/web/src/lib/core/component/AI/util/stream/mentionPlugin.test.ts
+++ b/apps/web/src/lib/core/component/AI/util/stream/mentionPlugin.test.ts
@@ -15,6 +15,7 @@ const OTHER_MACRO_XML_TAGS = [
'<m-contact-mention>{"contactId":"c1","name":"Ness Chu"}</m-contact-mention>',
'<m-pr-mention>{"id":"foreign-1","label":"macro/macro#123"}</m-pr-mention>',
'<m-group-mention>{"groupAlias":"here"}</m-group-mention>',
+ '<m-agent-session-mention>{"id":"sess-1","label":"Fix login"}</m-agent-session-mention>',
'<m-theme-mention>{"name":"onboarding","data":{}}</m-theme-mention>',
'<m-tag>{"optionId":"tag-1","propertyDefinitionId":"prop-1","scope":"team","name":"Launch"}</m-tag>',
'<m-await>{"awaitId":"a1","text":"Waiting","inline":true}</m-await>',
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 1e9765909e..6f2a5cce3e 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
@@ -2456,7 +2456,7 @@ export interface DisplayResultsResponse {
message: string;
}
/**
- * Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Uploaded files -- PDFs, DOCX, spreadsheets, 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(s), include each person's userId and email. 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. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Uploaded files -- PDFs, DOCX, spreadsheets, 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 automations; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips. To insert document-card(s), include each document's documentId and documentName.
*/
export interface EditDocument {
/**
@@ -2464,7 +2464,7 @@ export interface EditDocument {
*/
document_id: string;
/**
- * Natural language instructions. For mention(s), include userId and email per person. For document-card(s), include documentId and documentName per document. You may need to look these up.
+ * Natural language instructions. For @-mention chips, include each item's ids and details: userId/email for people; documentId/documentName/blockName for documents and similar items; session id for agent sessions; ISO datetime and displayFormat for time chips. For document-card(s), include documentId and documentName per document. You may need to look these up.
*/
instructions: string;
}
diff --git a/crates/documents/src/inbound/toolset/edit_document.rs b/crates/documents/src/inbound/toolset/edit_document.rs
index 97c63f334f..af421c9f38 100644
--- a/crates/documents/src/inbound/toolset/edit_document.rs
+++ b/crates/documents/src/inbound/toolset/edit_document.rs
@@ -24,7 +24,7 @@ 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. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Uploaded files -- PDFs, DOCX, spreadsheets, 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(s), include each person's userId and email. 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. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Uploaded files -- PDFs, DOCX, spreadsheets, 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 automations; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips. To insert document-card(s), include each document's documentId and documentName."
)]
pub struct EditDocument {
#[schemars(
@@ -32,7 +32,7 @@ pub struct EditDocument {
)]
pub document_id: String,
#[schemars(
- description = "Natural language instructions. For mention(s), include userId and email per person. For document-card(s), include documentId and documentName per document. You may need to look these up."
+ description = "Natural language instructions. For @-mention chips, include each item's ids and details: userId/email for people; documentId/documentName/blockName for documents and similar items; session id for agent sessions; ISO datetime and displayFormat for time chips. For document-card(s), include documentId and documentName per document. You may need to look these up."
)]
pub instructions: String,
}
diff --git a/crates/mention_utils/src/parse.rs b/crates/mention_utils/src/parse.rs
index 1ca8eb2bf0..186cd52d80 100644
--- a/crates/mention_utils/src/parse.rs
+++ b/crates/mention_utils/src/parse.rs
@@ -127,6 +127,34 @@ impl<'de> XmlTaggedParsed<'de> for ParsedGroupMention<'de> {
const TAG_NAME: &'static str = "m-group-mention";
}
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+#[non_exhaustive]
+pub struct ParsedAgentSessionMention<'a> {
+ #[serde(borrow)]
+ pub id: Cow<'a, str>,
+ #[serde(borrow, default)]
+ pub label: Option<Cow<'a, str>>,
+}
+
+impl<'de> XmlTaggedParsed<'de> for ParsedAgentSessionMention<'de> {
+ const TAG_NAME: &'static str = "m-agent-session-mention";
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+#[non_exhaustive]
+pub struct ParsedPullRequestMention<'a> {
+ #[serde(borrow)]
+ pub id: Cow<'a, str>,
+ #[serde(borrow, default)]
+ pub label: Option<Cow<'a, str>>,
+}
+
+impl<'de> XmlTaggedParsed<'de> for ParsedPullRequestMention<'de> {
+ const TAG_NAME: &'static str = "m-pr-mention";
+}
+
#[derive(Debug)]
pub enum XmlTag<'de> {
Link(ParsedLink<'de>),
@@ -135,6 +163,8 @@ pub enum XmlTag<'de> {
Contact(ParsedContactMention<'de>),
Date(ParsedDateMention<'de>),
Group(ParsedGroupMention<'de>),
+ AgentSession(ParsedAgentSessionMention<'de>),
+ PullRequest(ParsedPullRequestMention<'de>),
}
fn parse_xml_tag(s: &str) -> IResult<&str, XmlTag<'_>> {
@@ -145,6 +175,8 @@ fn parse_xml_tag(s: &str) -> IResult<&str, XmlTag<'_>> {
ParsedContactMention::parse.map(XmlTag::Contact),
ParsedDateMention::parse.map(XmlTag::Date),
ParsedGroupMention::parse.map(XmlTag::Group),
+ ParsedAgentSessionMention::parse.map(XmlTag::AgentSession),
+ ParsedPullRequestMention::parse.map(XmlTag::PullRequest),
))
.parse(s)
}
@@ -157,6 +189,8 @@ fn is_recognized_tag_name(name: &str) -> bool {
ParsedContactMention::TAG_NAME,
ParsedDateMention::TAG_NAME,
ParsedGroupMention::TAG_NAME,
+ ParsedAgentSessionMention::TAG_NAME,
+ ParsedPullRequestMention::TAG_NAME,
]
.iter()
.any(|recognized| recognized.eq_ignore_ascii_case(name))
@@ -233,6 +267,14 @@ pub trait XmlFormatter: Sized {
) -> std::fmt::Result;
fn format_date(date: &ParsedDateMention<'_>, f: &mut Formatter<'_>) -> std::fmt::Result;
fn format_group(group: &ParsedGroupMention<'_>, f: &mut Formatter<'_>) -> std::fmt::Result;
+ fn format_agent_session(
+ session: &ParsedAgentSessionMention<'_>,
+ f: &mut Formatter<'_>,
+ ) -> std::fmt::Result;
+ fn format_pull_request(
+ pr: &ParsedPullRequestMention<'_>,
+ f: &mut Formatter<'_>,
+ ) -> std::fmt::Result;
fn format_xml_text(text: ParsedXmlText<'_>) -> ReformattedXmlText<Self> {
use std::fmt::Display;
@@ -288,6 +330,20 @@ pub trait XmlFormatter: Sized {
Adapter(|f: &mut Formatter<'_>| Self::format_group(&g, f))
)
}
+ TextSegment::Xml(XmlTag::AgentSession(s)) => {
+ write!(
+ acc,
+ "{}",
+ Adapter(|f: &mut Formatter<'_>| Self::format_agent_session(&s, f))
+ )
+ }
+ TextSegment::Xml(XmlTag::PullRequest(p)) => {
+ write!(
+ acc,
+ "{}",
+ Adapter(|f: &mut Formatter<'_>| Self::format_pull_request(&p, f))
+ )
+ }
TextSegment::Plain(s) => {
write!(
acc,
@@ -339,6 +395,35 @@ impl XmlFormatter for PlainTextFormatter {
fn format_group(group: &ParsedGroupMention<'_>, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "@{}", group.group_alias)
}
+
+ fn format_agent_session(
+ session: &ParsedAgentSessionMention<'_>,
+ f: &mut Formatter<'_>,
+ ) -> std::fmt::Result {
+ write!(
+ f,
+ "{}",
+ session
+ .label
+ .as_deref()
+ .filter(|label| !label.is_empty())
+ .unwrap_or("Agent session")
+ )
+ }
+
+ fn format_pull_request(
+ pr: &ParsedPullRequestMention<'_>,
+ f: &mut Formatter<'_>,
+ ) -> std::fmt::Result {
+ write!(
+ f,
+ "{}",
+ pr.label
+ .as_deref()
+ .filter(|label| !label.is_empty())
+ .unwrap_or("Pull request")
+ )
+ }
}
/// xml formatter which completely removes the inner text of all xml tags
@@ -375,4 +460,18 @@ impl XmlFormatter for NullXmlFormatter {
fn format_group(_group: &ParsedGroupMention<'_>, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "")
}
+
+ fn format_agent_session(
+ _session: &ParsedAgentSessionMention<'_>,
+ f: &mut Formatter<'_>,
+ ) -> std::fmt::Result {
+ write!(f, "")
+ }
+
+ fn format_pull_request(
+ _pr: &ParsedPullRequestMention<'_>,
+ f: &mut Formatter<'_>,
+ ) -> std::fmt::Result {
+ write!(f, "")
+ }
}
diff --git a/crates/mention_utils/src/tests.rs b/crates/mention_utils/src/tests.rs
index 7d52b4cc37..953ef2926d 100644
--- a/crates/mention_utils/src/tests.rs
+++ b/crates/mention_utils/src/tests.rs
@@ -1,9 +1,9 @@
use cool_asserts::assert_matches;
use crate::parse::{
- NullXmlFormatter, ParsedContactMention, ParsedDateMention, ParsedDocumentMention,
- ParsedGroupMention, ParsedLink, ParsedUserMention, ParsedXmlText, PlainTextFormatter,
- TextSegment, XmlFormatter, XmlTag,
+ NullXmlFormatter, ParsedAgentSessionMention, ParsedContactMention, ParsedDateMention,
+ ParsedDocumentMention, ParsedGroupMention, ParsedLink, ParsedPullRequestMention,
+ ParsedUserMention, ParsedXmlText, PlainTextFormatter, TextSegment, XmlFormatter, XmlTag,
};
// =============================================================================
@@ -702,6 +702,60 @@ fn parse_group_mention_with_user_mention() {
});
}
+// =============================================================================
+// Agent session and pull request mention tests
+// =============================================================================
+
+#[test]
+fn parse_agent_session_mention() {
+ let input = r#"see <m-agent-session-mention>{"id":"sess-1","label":"Fix login"}</m-agent-session-mention>"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Plain("see "),
+ TextSegment::Xml(XmlTag::AgentSession(ParsedAgentSessionMention { id, label })),
+ ] => {
+ assert_eq!(id.as_ref(), "sess-1");
+ assert_eq!(label.as_deref(), Some("Fix login"));
+ });
+}
+
+#[test]
+fn parse_agent_session_mention_without_label() {
+ let input = r#"<m-agent-session-mention>{"id":"sess-1"}</m-agent-session-mention>"#;
+ let parsed = ParsedXmlText::parse(input).unwrap();
+ let rendered = PlainTextFormatter::format_xml_text(parsed).0;
+ assert_eq!(rendered, "Agent session");
+}
+
+#[test]
+fn parse_agent_session_mention_missing_id() {
+ let input = r#"<m-agent-session-mention>{"label":"Fix login"}</m-agent-session-mention>"#;
+ assert!(ParsedXmlText::parse(input).is_err());
+}
+
+#[test]
+fn parse_pull_request_mention() {
+ let input = r#"<m-pr-mention>{"id":"foreign-1","label":"macro/macro#123"}</m-pr-mention>"#;
+ let parsed = ParsedXmlText::parse(input).unwrap();
+ let rendered = PlainTextFormatter::format_xml_text(parsed).0;
+ assert_eq!(rendered, "macro/macro#123");
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Xml(XmlTag::PullRequest(ParsedPullRequestMention { id, label })),
+ ] => {
+ assert_eq!(id.as_ref(), "foreign-1");
+ assert_eq!(label.as_deref(), Some("macro/macro#123"));
+ });
+}
+
+#[test]
+fn parse_pull_request_mention_without_label() {
+ let input = r#"<m-pr-mention>{"id":"foreign-1"}</m-pr-mention>"#;
+ let parsed = ParsedXmlText::parse(input).unwrap();
+ let rendered = PlainTextFormatter::format_xml_text(parsed).0;
+ assert_eq!(rendered, "Pull request");
+}
+
// =============================================================================
// Unknown / unrecognized tag tests
// =============================================================================
diff --git a/crates/prompt/src/agent_session.rs b/crates/prompt/src/agent_session.rs
index 619d080453..e970c4a775 100644
--- a/crates/prompt/src/agent_session.rs
+++ b/crates/prompt/src/agent_session.rs
@@ -8,7 +8,7 @@ static INSTRUCTIONS: &str = r##"You are Macro's agent, working inside an agent s
- Each prompt is a message from a user in the thread. Answer it directly; use your tools to look things up or act in the workspace when that is what the request needs.
- Be concise and directly useful. Respond in Markdown.
-- When you reference a Macro document, channel, chat, project, task, email thread, or calendar event, emit an XML mention tag (see the mentioning rules). Those tags render as clickable chips in the session and in the channel thread. Do not use plain Markdown links or bare names for Macro items.
+- When you reference a Macro document, channel, chat, project, task, email thread, calendar event, person, date/time, agent session, or other mentionable chip, emit the matching XML mention tag (see the mentioning rules). Those tags render as clickable chips in the session and in the channel thread. Do not use plain Markdown links or bare names for Macro items.
- You have no shell and no filesystem. Everything you can do, you do through the tools you are given.
- Work autonomously: nobody can approve intermediate questions mid-turn, so make reasonable assumptions, state them briefly, and proceed.
"##;
diff --git a/crates/prompt/src/document_content_links.rs b/crates/prompt/src/document_content_links.rs
index b8376299a1..765c5b1ee7 100644
--- a/crates/prompt/src/document_content_links.rs
+++ b/crates/prompt/src/document_content_links.rs
@@ -27,13 +27,16 @@ For Markdown document content, link to other Macro documents, channels, chats, p
`<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"md","blockParams":{}}</m-document-mention>`
-This holds true even when `CreateDocument` is called through the MCP server, where you are otherwise told to link items in your own chat replies as plain Markdown URLs — that rule is about your conversational responses to the MCP client, not about content you write into a Macro document. Do NOT use plain Markdown links or bare URLs to reference other Macro items inside document content; only `<m-document-mention>` tags render as working links there.
+The same Markdown parser also renders the other in-app chip tags: `<m-date-mention>` for a day or time, `<m-agent-session-mention>` for an agent session (add `"expanded":true` for the card that follows the latest turn), `<m-user-mention>` / `<m-contact-mention>` / `<m-group-mention>` for people and groups, and `<m-pr-mention>` for a pull request. Use those tags in document content the same way you would in a chat reply.
-The same applies to `EditDocument`: when its `instructions` ask for a mention or document-card, include the referenced item's id and name so the editing worker can construct the correct in-app markup itself.
+This holds true even when `CreateDocument` is called through the MCP server, where you are otherwise told to link items in your own chat replies as plain Markdown URLs — that rule is about your conversational responses to the MCP client, not about content you write into a Macro document. Do NOT use plain Markdown links or bare URLs to reference other Macro items inside document content; only `<m-document-mention>` tags (and the other chip tags above) render as working links there.
+
+The same applies to `EditDocument`: when its `instructions` ask for a mention chip (person, date/time, document, agent session, and so on) or a document-card, include the referenced item's ids and details so the editing worker can construct the correct in-app markup itself. Date chips need an ISO datetime and displayFormat; they do not need a looked-up id.
"##;
static INTENT: &str = "Content written into Markdown documents via CreateDocument or EditDocument \
-links other Macro items with `<m-document-mention>` XML tags — never plain Markdown URLs — \
+links other Macro items with `<m-document-mention>` XML tags and the other in-app chip tags \
+(dates, agent sessions, people) — never plain Markdown URLs — \
regardless of whether the tool call arrived in-app or over MCP, while non-Markdown documents carry \
no Markdown syntax or mention tags at all.";
diff --git a/crates/prompt/src/lib.rs b/crates/prompt/src/lib.rs
index b422e9e4d2..70c6795aac 100644
--- a/crates/prompt/src/lib.rs
+++ b/crates/prompt/src/lib.rs
@@ -218,6 +218,18 @@ mod tests {
let preamble = agent_session::PROMPT.to_string();
assert!(preamble.contains("XML mention tag"));
assert!(preamble.contains("clickable chips"));
+ assert!(preamble.contains("agent session"));
+ assert!(preamble.contains("date/time"));
+ }
+
+ #[test]
+ fn mentions_prompt_covers_date_and_agent_session_chips() {
+ let instructions = mentions::PROMPT.instructions.as_ref();
+ assert!(instructions.contains("<m-date-mention>"));
+ assert!(instructions.contains("<m-agent-session-mention>"));
+ assert!(instructions.contains("<m-user-mention>"));
+ assert!(instructions.contains("\"expanded\":true"));
+ assert!(instructions.contains("\"blockName\":\"skill\""));
}
#[test]
diff --git a/crates/prompt/src/mentions.rs b/crates/prompt/src/mentions.rs
index 0376f3c87b..7a46e49b60 100644
--- a/crates/prompt/src/mentions.rs
+++ b/crates/prompt/src/mentions.rs
@@ -16,12 +16,15 @@
use crate::types::StaticPrompt;
-static TITLE: &str = "Mentioning documents, channels, channel messages, chats, projects, email threads, and calendar events";
+static TITLE: &str = "Mentioning documents, people, dates, agent sessions, and other chips";
static INSTRUCTIONS: &str = r##"These rules apply everywhere you author Markdown in Macro: your own conversational replies (AI chat and agent session transcripts), `SendChannelMessage` content, `SendEmail` bodies, and `CreateDocument`/`EditDocument` content for Markdown (`.md`) documents. They do NOT apply to non-Markdown documents created via `CreateDocument` (e.g. PDF, CSV, PNG, XLSX, DOCX) — those are raw file bytes, never parsed as Markdown, and must never contain mention tags or Markdown syntax.
-When referencing a document, channel, chat, project, email thread, or calendar event, use XML mention tags with a JSON payload.
-The AI does not need to know the name — an empty string is fine and the frontend will resolve it.
+When referencing a Macro item, person, date/time, agent session, or other mentionable chip, use XML mention tags with a JSON payload. Those tags render as clickable chips. Do not use plain Markdown links or bare names for these. Empty name/label strings are fine — the frontend resolves them.
+
+### Documents, channels, chats, and similar items
+
+Use `<m-document-mention>` with the right `blockName` (and `blockParams` when needed):
- Document mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"md","blockParams":{}}</m-document-mention>`
- Channel mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"channel","blockParams":{}}</m-document-mention>`
@@ -32,27 +35,49 @@ The AI does not need to know the name — an empty string is fine and the fronte
- Email thread mention: `<m-document-mention>{"documentId":"{thread_id}","documentName":"","blockName":"email","blockParams":{}}</m-document-mention>`
- Calendar event mention: `<m-document-mention>{"documentId":"{event_id}","documentName":"","blockName":"calendar","blockParams":{}}</m-document-mention>`
- Calendar event occurrence mention: `<m-document-mention>{"documentId":"{event_id}","documentName":"","blockName":"calendar","blockParams":{"occurrenceKey":"{recurrence_id}"}}</m-document-mention>`
-
-If a tool result tells you an app is not connected for the person you are working for and hands you a `<m-connect-app>{"appSlug":"...","name":"..."}</m-connect-app>` tag, include that tag verbatim in your reply: it renders as a button that connects the app. Never invent one; only repeat the tag a tool result gave you. End that reply by asking them to let you know once they have connected the app so you can try again.
+- Skill mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"skill","blockParams":{}}</m-document-mention>`
+- Call mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"call","blockParams":{}}</m-document-mention>`
+- Automation mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"automation","blockParams":{}}</m-document-mention>`
+- Snippet mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"snippet","blockParams":{}}</m-document-mention>`
+- CRM company mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"company","blockParams":{}}</m-document-mention>`
The `blockName` for an email thread is always exactly `email` — never `thread` or `email_thread`, which the frontend cannot resolve.
The `blockName` for a calendar event is always exactly `calendar` — never `calendar_event`, which the frontend cannot resolve. `documentId` is the `eventId` a calendar tool returned. To point at one instance of a recurring event, pass that occurrence's `recurrenceId` from ListCalendarEvents as the `occurrenceKey` block param; otherwise omit it and the mention previews the nearest instance. A calendar event mention resolves only for users who have that event on their own calendar.
-Only the entity types listed above can be mentioned. A calendar itself is NOT a mentionable entity: never put a `calendarId` (e.g. from ListCalendars) in a mention tag — the frontend cannot resolve it and renders a broken chip. Refer to a calendar by name in plain text and mention only individual events on it. The same goes for any other id with no mention format listed here: plain text, never an improvised tag.
When a tool returns both a channel id and a channel message id, link the specific message using the channel message mention format. Do not link only the channel unless you are referring to the whole channel.
+### People, groups, dates, agent sessions, and pull requests
+
+These use their own tags — never wrap them in `<m-document-mention>`:
+
+- Person: `<m-user-mention>{"userId":"{id}","email":"{email}"}</m-user-mention>`
+- Contact: `<m-contact-mention>{"contactId":"{id}","name":"{name}","emailOrDomain":"{email_or_domain}","isCompany":false}</m-contact-mention>`
+- Group: `<m-group-mention>{"groupAlias":"{alias}"}</m-group-mention>`
+- Date/time: `<m-date-mention>{"date":"{iso_datetime}","displayFormat":"{label}"}</m-date-mention>`
+- Agent session: `<m-agent-session-mention>{"id":"{session_id}","label":""}</m-agent-session-mention>`
+- Pull request: `<m-pr-mention>{"id":"{id}","label":""}</m-pr-mention>`
+
+Date/time chips do not need a looked-up id. `date` is an ISO 8601 datetime; `displayFormat` is the chip label the user sees (e.g. "Mon, Dec 1, 2025", "Today", "Tomorrow", "3:00 PM"). Prefer a date chip over typing a date as plain text when you are naming a specific day or time.
+
+Agent session chips reference an existing session by id from a tool result. An empty `label` is fine. Set `"expanded":true` to insert the card (Magic Chip) that follows the session's latest turn instead of the compact underlined title. Do not invent session ids.
+
+If a tool result tells you an app is not connected for the person you are working for and hands you a `<m-connect-app>{"appSlug":"...","name":"..."}</m-connect-app>` tag, include that tag verbatim in your reply: it renders as a button that connects the app. Never invent one; only repeat the tag a tool result gave you. End that reply by asking them to let you know once they have connected the app so you can try again.
+
+Only the tag formats listed here can be mentioned. Never invent a tag name or put an id in the wrong tag. A calendar itself is NOT a mentionable entity: never put a `calendarId` (e.g. from ListCalendars) in a mention tag — the frontend cannot resolve it and renders a broken chip. Refer to a calendar by name in plain text and mention only individual events on it. The same goes for any other id with no mention format listed here: plain text, never an improvised tag.
+
+`EditDocument` does not take mention tags in `instructions`. Include each referenced item's ids and details (userId/email, documentId/blockName, session id, ISO date and displayFormat, and so on) so the editing worker can insert the chip itself.
+
### Example Response
If no inline or node ids are present:
"See the document for details<m-document-mention>{"documentId":"6a2b138d-dfbe-439a-a78b-282471a1e165","documentName":"","blockName":"md","blockParams":{}}</m-document-mention>."
"##;
-static INTENT: &str = "Entities and channel messages are referenced with correctly formatted \
-<m-document-mention> XML tags using the right blockName and blockParams for each entity type, \
-including exactly \"email\" for email threads, exactly \"calendar\" for calendar events, and \
-channel_message_id for specific channel messages, \
+static INTENT: &str = "Entities, people, dates, agent sessions, and other chips are referenced \
+with the matching XML mention tag (m-document-mention with the right blockName/blockParams, \
+m-user-mention, m-date-mention, m-agent-session-mention, and the other listed chip tags) \
across every Markdown surface (AI chat replies, agent session replies, channel messages, \
email bodies, and Markdown documents) — never inside non-Markdown documents, and never for \
-ids outside the listed entity types (a calendar id from ListCalendars is not mentionable; \
+ids outside the listed types (a calendar id from ListCalendars is not mentionable; \
only individual events are).";
/// The entity-mention prompt.
diff --git a/crates/prompt/tests/compose.rs b/crates/prompt/tests/compose.rs
index 093711201b..45447ba710 100644
--- a/crates/prompt/tests/compose.rs
+++ b/crates/prompt/tests/compose.rs
@@ -6,7 +6,7 @@ const BASE_TITLES: [&str; 6] = [
"# Tone and Style",
"# Math Rendering Rules",
"# Citation Rules",
- "# Mentioning documents, channels, channel messages, chats, projects, email threads, and calendar events",
+ "# Mentioning documents, people, dates, agent sessions, and other chips",
"# Do Not Rules",
"# Terms",
];
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 25e49344da..39fc7ffe7c 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -162,9 +162,14 @@ An agent session is `/app/agent/<uuid>`. The composer placeholder is
**`Message the agent, @mention anything`**. Creating one (`c` then `a`, or
`Create` → `Agent`) leaves that composer focused — on mobile that is the same
Create-menu `triggerFocusInput` as chat, so the keyboard opens. Type `@` to insert the same mention chips
-used in chat and channels; they serialize as `<m-document-mention>` tags in the prompt
-the agent sees. Agent replies that emit those tags render as clickable chips in the
-transcript (and in the originating channel thread).
+used in chat and channels; they serialize as mention-chip tags in the prompt
+the agent sees (`<m-document-mention>` for docs/channels/chats/tasks/emails/calendar
+events/skills, `<m-date-mention>` for a day or time, `<m-agent-session-mention>`
+for an agent session, `<m-user-mention>` for a person, and the other chip tags).
+Agent replies that emit those tags render as clickable chips in the
+transcript (and in the originating channel thread). An agent-session chip with
+`"expanded":true` renders as the Magic Chip card that follows the session's
+latest turn.
`@mention` a person in a prompt and, if you can edit the session, they are granted edit
access and get an `agent_session_mentioned` notification that opens the session; a viewer's
mention only notifies people who could already open it.
diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.md
index c6dc431120..c7993dd043 100644
--- a/docs/AGENT_GUIDE/documents.md
+++ b/docs/AGENT_GUIDE/documents.md
@@ -64,7 +64,9 @@ fetch cascade.
press Enter (or click `Send`).
3. While running, the button row shows an author chip (e.g. `Wolf (AI)`) and a `Stop` button
(a11y text `Stop AI edit`). Edits stream directly into the document — there is no
- accept/reject step.
+ accept/reject step. The editor can insert the same `@` mention chips a person can:
+ dates/times, people, documents, channels, agent sessions (including the expanded
+ Magic Chip card), and the other chip types.
4. Completion signal: the `Stop` button disappears. Poll for that with `evaluate_script`;
do not rely on `wait_for` text.
diff --git a/packages/lexical-core/tests/xml-serialize.test.ts b/packages/lexical-core/tests/xml-serialize.test.ts
index a005e992e0..5baa0128dc 100644
--- a/packages/lexical-core/tests/xml-serialize.test.ts
+++ b/packages/lexical-core/tests/xml-serialize.test.ts
@@ -12,6 +12,7 @@ import {
import { describe, expect, it } from 'vitest';
import { NodeReplacements, SupportedNodeTypes } from '../node-list';
import { $createCustomCodeNode } from '../nodes/CustomCodeNode';
+import { $createDocumentMentionNode } from '../nodes/DocumentMentionNode';
import { $createEquationNode } from '../nodes/EquationNode';
import { $createHtmlRenderNode } from '../nodes/HtmlRenderNode';
import { $createImageNode } from '../nodes/ImageNode';
@@ -301,6 +302,30 @@ describe('xml serialization', () => {
`);
});
+ it('document mention keeps blockName and blockParams', () => {
+ expect(
+ serialize(() => {
+ const p = $createParagraphNode();
+ p.append(
+ $createDocumentMentionNode({
+ documentId: 'ch-1',
+ documentName: 'bugs',
+ blockName: 'channel',
+ blockParams: { channel_message_id: 'msg-1' },
+ })
+ );
+ $getRoot().append(p);
+ })
+ ).toMatchInlineSnapshot(`
+ "
+ <doc>
+ <p>
+ <document-mention documentId="ch-1" name="bugs" blockName="channel" blockParams="{&quot;channel_message_id&quot;:&quot;msg-1&quot;}"/>
+ </p>
+ </doc>"
+ `);
+ });
+
it('tab serializes minimally', () => {
expect(
serialize(() => {
diff --git a/packages/lexical-core/transformers/xml/codecs.ts b/packages/lexical-core/transformers/xml/codecs.ts
index a8b9c981db..a4b8391d3b 100644
--- a/packages/lexical-core/transformers/xml/codecs.ts
+++ b/packages/lexical-core/transformers/xml/codecs.ts
@@ -329,6 +329,11 @@ 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),
+ }),
})
)
)
@@ -355,7 +360,11 @@ export function serializeNode(node: SerNode): FxpNode {
el(
'agent-session-mention',
[],
- nodeAttrs(n, { sessionId: n.id, ...(n.label && { label: n.label }) })
+ nodeAttrs(n, {
+ sessionId: n.id,
+ ...(n.label && { label: n.label }),
+ ...(n.expanded && { expanded: 'true' }),
+ })
)
)
.with({ type: 'pr-mention' }, (n) =>
diff --git a/packages/lexical-core/transformers/xml/nodes.ts b/packages/lexical-core/transformers/xml/nodes.ts
index 1cd60e6678..13c47c0057 100644
--- a/packages/lexical-core/transformers/xml/nodes.ts
+++ b/packages/lexical-core/transformers/xml/nodes.ts
@@ -173,6 +173,8 @@ export type DocumentMentionNode = Id & {
version: number;
documentId: string;
documentName: string;
+ blockName?: string;
+ blockParams?: Record<string, string>;
};
export type ContactMentionNode = Id & {
@@ -195,6 +197,7 @@ export type AgentSessionMentionNode = Id & {
version: number;
id: string;
label?: string;
+ expanded?: boolean;
};
export type PullRequestMentionNode = Id & {
diff --git a/services/ai-editing-worker/scripts/generate-sandbox.ts b/services/ai-editing-worker/scripts/generate-sandbox.ts
index 67d83d1548..9666bc6ab9 100644
--- a/services/ai-editing-worker/scripts/generate-sandbox.ts
+++ b/services/ai-editing-worker/scripts/generate-sandbox.ts
@@ -2,7 +2,7 @@
* Transpiles DocumentEditor + EditError to plain JS and writes editor-sandbox-code.ts.
* Run via `bun scripts/generate-sandbox.ts` (wired into prebuild).
*/
-import { join, dirname } from 'node:path';
+import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
@@ -11,12 +11,24 @@ const t = new Bun.Transpiler({ loader: 'ts' });
async function transpile(relPath: string): Promise<string> {
const src = await Bun.file(join(root, relPath)).text();
// Strip import/export — QuickJS evaluates a plain script, not an ES module.
- return t.transformSync(src)
+ return t
+ .transformSync(src)
.replace(/^import\s.*$/gm, '')
.replace(/^export\s+(?:default\s+)?/gm, '')
.trim();
}
+/** Biome formats this generated file with single-quoted string literals. */
+function asSingleQuotedTsString(value: string): string {
+ return `'${value
+ .replace(/\\/g, '\\\\')
+ .replace(/'/g, "\\'")
+ .replace(/\r/g, '\\r')
+ .replace(/\n/g, '\\n')
+ .replace(/\u2028/g, '\\u2028')
+ .replace(/\u2029/g, '\\u2029')}'`;
+}
+
const code = [
await transpile('src/ai-editing/editor/errors.ts'),
await transpile('src/ai-editing/editor/document-editor.ts'),
@@ -24,7 +36,9 @@ const code = [
const out = `// Auto-generated by scripts/generate-sandbox.ts — do not edit.
// Source of truth: src/ai-editing/editor/document-editor.ts
-export const SANDBOX_CODE = ${JSON.stringify(code)};
+// biome-ignore-all lint/suspicious/noTemplateCurlyInString: generated JS contains template literals
+export const SANDBOX_CODE =
+ ${asSingleQuotedTsString(code)};
`;
await Bun.write(join(root, 'src/editor-sandbox-code.ts'), out);
diff --git a/services/ai-editing-worker/src/ai-editing/doc/doc.test.ts b/services/ai-editing-worker/src/ai-editing/doc/doc.test.ts
index 9ba8620627..506170c818 100644
--- a/services/ai-editing-worker/src/ai-editing/doc/doc.test.ts
+++ b/services/ai-editing-worker/src/ai-editing/doc/doc.test.ts
@@ -410,6 +410,72 @@ describe('Doc.insertInline — offset placement', () => {
const out = serializeWithXml(session);
expect(out.indexOf('hello')).toBeLessThan(out.indexOf('2026-01-01'));
});
+
+ it('inserts user, date, agent-session, and document mention chips', () => {
+ const { session, ids } = setup('Go');
+ const doc = new Doc(session);
+ doc.apply({
+ kind: 'insertInline',
+ ref: 'u',
+ node: ids[0]!,
+ at: 3,
+ spec: {
+ inline: 'mention',
+ mention: { kind: 'user', userId: 'u1', email: '[email protected]' },
+ },
+ });
+ doc.apply({
+ kind: 'insertInline',
+ ref: 'd',
+ node: ids[0]!,
+ at: 3,
+ spec: {
+ inline: 'date',
+ date: '2026-07-08T00:00:00.000Z',
+ displayFormat: 'Today',
+ },
+ });
+ doc.apply({
+ kind: 'insertInline',
+ ref: 's',
+ node: ids[0]!,
+ at: 3,
+ spec: {
+ inline: 'mention',
+ mention: {
+ kind: 'agent_session',
+ id: 'sess-1',
+ label: 'Fix login',
+ expanded: true,
+ },
+ },
+ });
+ doc.apply({
+ kind: 'insertInline',
+ ref: 'doc',
+ node: ids[0]!,
+ at: 3,
+ spec: {
+ inline: 'mention',
+ mention: {
+ kind: 'document',
+ documentId: 'doc-1',
+ documentName: 'Spec',
+ blockName: 'md',
+ blockParams: { foo: 'bar' },
+ },
+ },
+ });
+ const xml = serializeWithXml(session);
+ expect(xml).toContain('<user-mention');
+ expect(xml).toContain('userId="u1"');
+ expect(xml).toContain('<date-mention');
+ expect(xml).toContain('displayFormat="Today"');
+ expect(xml).toContain('<agent-session-mention');
+ expect(xml).toContain('sessionId="sess-1"');
+ expect(xml).toContain('<document-mention');
+ expect(xml).toContain('documentId="doc-1"');
+ });
});
describe('Doc — chained block-type swaps stay addressable by the original id', () => {
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 045505f899..c8047aca3a 100644
--- a/services/ai-editing-worker/src/ai-editing/doc/doc.ts
+++ b/services/ai-editing-worker/src/ai-editing/doc/doc.ts
@@ -31,6 +31,7 @@ import {
TableCellHeaderStates,
type TableNode,
} from '@lexical/table';
+import { $createAgentSessionMentionNode } from '@macro-inc/lexical-core/nodes/AgentSessionMentionNode';
import { $createContactMentionNode } from '@macro-inc/lexical-core/nodes/ContactMentionNode';
import {
$createDateMentionNode,
@@ -46,6 +47,8 @@ import {
$createImageNode,
ImageNode,
} from '@macro-inc/lexical-core/nodes/ImageNode';
+import { $createPullRequestMentionNode } from '@macro-inc/lexical-core/nodes/PullRequestMentionNode';
+import { $createTagMentionNode } from '@macro-inc/lexical-core/nodes/TagMentionNode';
import { $createUserMentionNode } from '@macro-inc/lexical-core/nodes/UserMentionNode';
import {
$createVideoNode,
@@ -72,7 +75,6 @@ import * as blocks from '../ai-toolkit/blocks';
import * as inline from '../ai-toolkit/inline';
import * as lists from '../ai-toolkit/lists';
import * as locate from '../ai-toolkit/locate';
-import { assertSubstringMatched } from './substring-miss';
import * as modify from '../ai-toolkit/modify';
import type { LexicalSession } from '../ai-toolkit/session';
import * as tables from '../ai-toolkit/tables';
@@ -88,6 +90,7 @@ import type {
} from '../editor';
import { EditError } from '../editor';
import type { DocReader, DocWriter, Match } from './interfaces';
+import { assertSubstringMatched } from './substring-miss';
const FORMAT_BIT: Record<
Format,
@@ -994,25 +997,51 @@ export function buildNode(spec: NodeSpec): LexicalNode {
displayFormat: session.displayFormat ?? session.date,
})
)
- .with({ inline: 'mention' }, (session) => {
- const m = session.mention;
- if (m.kind === 'user')
- return $createUserMentionNode({ userId: m.userId, email: m.email });
- if (m.kind === 'contact')
- return $createContactMentionNode({
- contactId: m.contactId,
- name: m.name,
- emailOrDomain: m.emailOrDomain,
- isCompany: m.isCompany,
- });
- if (m.kind === 'group')
- return $createGroupMentionNode({ groupAlias: m.groupAlias });
- return $createDocumentMentionNode({
- documentId: m.documentId,
- documentName: m.documentName,
- blockName: m.blockName,
- });
- })
+ .with({ inline: 'mention' }, (session) =>
+ match(session.mention)
+ .with({ kind: 'user' }, (m) =>
+ $createUserMentionNode({ userId: m.userId, email: m.email })
+ )
+ .with({ kind: 'contact' }, (m) =>
+ $createContactMentionNode({
+ contactId: m.contactId,
+ name: m.name,
+ emailOrDomain: m.emailOrDomain,
+ isCompany: m.isCompany,
+ })
+ )
+ .with({ kind: 'group' }, (m) =>
+ $createGroupMentionNode({ groupAlias: m.groupAlias })
+ )
+ .with({ kind: 'document' }, (m) =>
+ $createDocumentMentionNode({
+ documentId: m.documentId,
+ documentName: m.documentName,
+ blockName: m.blockName,
+ blockParams: m.blockParams,
+ })
+ )
+ .with({ kind: 'agent_session' }, (m) =>
+ $createAgentSessionMentionNode({
+ id: m.id,
+ label: m.label,
+ expanded: m.expanded,
+ })
+ )
+ .with({ kind: 'pr' }, (m) =>
+ $createPullRequestMentionNode({ id: m.id, label: m.label })
+ )
+ .with({ kind: 'tag' }, (m) =>
+ $createTagMentionNode({
+ optionId: m.optionId,
+ propertyDefinitionId: m.propertyDefinitionId,
+ scope: m.scope,
+ name: m.name,
+ color: m.color,
+ })
+ )
+ .exhaustive()
+ )
.exhaustive();
}
diff --git a/services/ai-editing-worker/src/ai-editing/editor/document-editor.test.ts b/services/ai-editing-worker/src/ai-editing/editor/document-editor.test.ts
index 179b44e89c..68a07f9697 100644
--- a/services/ai-editing-worker/src/ai-editing/editor/document-editor.test.ts
+++ b/services/ai-editing-worker/src/ai-editing/editor/document-editor.test.ts
@@ -427,6 +427,51 @@ describe('DocumentEditor — mention methods push insertInline ops', () => {
kind: 'insertInline',
spec: { inline: 'mention', mention: { kind: 'document' } },
});
+ const es = ed();
+ es.mentionAgentSession('b1', 0, {
+ id: 'sess-1',
+ label: 'Fix login',
+ expanded: true,
+ });
+ expect(es.drain()[0]).toMatchObject({
+ kind: 'insertInline',
+ spec: {
+ inline: 'mention',
+ mention: {
+ kind: 'agent_session',
+ id: 'sess-1',
+ label: 'Fix login',
+ expanded: true,
+ },
+ },
+ });
+ const epr = ed();
+ epr.mentionPullRequest('b1', 0, { id: 'pr-1', label: 'macro#1' });
+ expect(epr.drain()[0]).toMatchObject({
+ kind: 'insertInline',
+ spec: { inline: 'mention', mention: { kind: 'pr', id: 'pr-1' } },
+ });
+ const et = ed();
+ et.mentionTag('b1', 0, {
+ optionId: 'o',
+ propertyDefinitionId: 'p',
+ scope: 'team',
+ name: 'Launch',
+ });
+ expect(et.drain()[0]).toMatchObject({
+ kind: 'insertInline',
+ spec: { inline: 'mention', mention: { kind: 'tag', name: 'Launch' } },
+ });
+ const edate = ed();
+ edate.mentionDate('b1', 0, '2026-07-08T00:00:00.000Z', 'Today');
+ expect(edate.drain()[0]).toMatchObject({
+ kind: 'insertInline',
+ spec: {
+ inline: 'date',
+ date: '2026-07-08T00:00:00.000Z',
+ displayFormat: 'Today',
+ },
+ });
});
});
@@ -647,6 +692,10 @@ describe('DocumentEditor — mention methods require a valid block id', () => {
expect(() => ed().mentionGroup('nope', 0, { groupAlias: 'g' })).toThrow(
/nope/
);
+ expect(() => ed().mentionAgentSession('nope', 0, { id: 's' })).toThrow(
+ /nope/
+ );
+ expect(() => ed().mentionDate('nope', 0, '2026-01-01')).toThrow(/nope/);
});
});
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 f9a8e139fd..8174b53106 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
@@ -66,7 +66,7 @@ export class DocumentEditor {
if (typeof id !== 'string') {
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 ' +
+ "Insert helpers return the new node's id directly, so use that value " +
'as-is rather than a property of it.'
);
}
@@ -602,6 +602,16 @@ export class DocumentEditor {
displayFormat,
});
}
+
+ /** @-mention a date/time. Same as `insertDate`. */
+ public mentionDate(
+ blockId: NodeId,
+ at: number,
+ isoDate: string,
+ displayFormat?: string
+ ): Ref {
+ return this.insertDate(blockId, at, isoDate, displayFormat);
+ }
private insertInline(id: NodeId, at: number, spec: NodeSpec): Ref {
this.requireId(id);
if (at < 0) throw new EditError(`inline offset must be >= 0, got ${at}`);
@@ -646,11 +656,49 @@ export class DocumentEditor {
public mentionDocument(
blockId: NodeId,
at: number,
- entity: { documentId: string; documentName: string; blockName: string }
+ entity: {
+ documentId: string;
+ documentName: string;
+ blockName: string;
+ blockParams?: Record<string, string>;
+ }
): Ref {
return this.insertMention(blockId, at, { kind: 'document', ...entity });
}
+ public mentionAgentSession(
+ blockId: NodeId,
+ at: number,
+ entity: { id: string; label?: string; expanded?: boolean }
+ ): Ref {
+ return this.insertMention(blockId, at, {
+ kind: 'agent_session',
+ ...entity,
+ });
+ }
+
+ public mentionPullRequest(
+ blockId: NodeId,
+ at: number,
+ entity: { id: string; label?: string }
+ ): Ref {
+ return this.insertMention(blockId, at, { kind: 'pr', ...entity });
+ }
+
+ public mentionTag(
+ blockId: NodeId,
+ at: number,
+ entity: {
+ optionId: string;
+ propertyDefinitionId: string;
+ scope: 'user' | 'team';
+ name: string;
+ color?: string;
+ }
+ ): Ref {
+ return this.insertMention(blockId, at, { kind: 'tag', ...entity });
+ }
+
public setImageAlt(id: NodeId, alt: string): this {
this.requireId(id);
return this.push({ kind: 'setImageAlt', node: id, alt });
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 383d727951..079d2abd00 100644
--- a/services/ai-editing-worker/src/ai-editing/editor/ops.ts
+++ b/services/ai-editing-worker/src/ai-editing/editor/ops.ts
@@ -76,7 +76,8 @@ export type NodeSpec =
export type ListKind = 'bullet' | 'number' | 'check';
-/** Entity-mention specs. Ids are supplied with the edit request, not looked up. */
+/** Entity-mention specs. Ids are supplied with the edit request, not looked up.
+ * Date/time chips are `insertDate` / `{ inline: 'date' }`, not this union. */
export type MentionSpec =
| { kind: 'user'; userId: string; email: string }
| {
@@ -92,6 +93,17 @@ export type MentionSpec =
documentId: string;
documentName: string;
blockName: string;
+ blockParams?: Record<string, string>;
+ }
+ | { kind: 'agent_session'; id: string; label?: string; expanded?: boolean }
+ | { kind: 'pr'; id: string; label?: string }
+ | {
+ kind: 'tag';
+ optionId: string;
+ propertyDefinitionId: string;
+ scope: 'user' | 'team';
+ name: string;
+ color?: string;
};
/** Block-type targets for `setBlockType`. */
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 ddeae3ee70..f617e6a54c 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
@@ -36,7 +36,7 @@ The writer has the complete API reference. Use this compact list to help yoursel
## Native Objects
- Block objects: `insertDivider`, `insertImage`, `insertVideo`, `insertEquation`; or via `insertBlockAfter`/`appendBlock` with specs `document-card` (documentId, documentName, blockName, blockParams?) and `html-render` (html)
-- Inline objects: `insertInlineEquation`, `insertLineBreak`, `insertDate`, `insertMention`, `mentionUser`, `mentionContact`, `mentionGroup`, `mentionDocument`
+- Inline objects: `insertInlineEquation`, `insertLineBreak`, `insertDate`/`mentionDate` (time chip), `insertMention`, `mentionUser`, `mentionContact`, `mentionGroup`, `mentionDocument`, `mentionAgentSession`, `mentionPullRequest`, `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`
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 499a4421ae..5fd44cf0ca 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
@@ -300,7 +300,7 @@ After:
- `insertVideo(afterId, { srcType, url, controls?, width?, height? })`
- `insertEquation(afterId, tex)` · `insertInlineEquation(blockId, at, tex)`
- `insertLineBreak(blockId, at)` — inserts a **soft line break** (Shift+Enter) within a block. Use only when multiple lines must live in a single semantic block (poetry, addresses, signature blocks). For ordinary multi-line content, insert separate paragraph nodes instead.
-- `insertDate(blockId, at, isoDate, displayFormat?)`
+- `insertDate(blockId, at, isoDate, displayFormat?)` / `mentionDate(...)` — inserts a date/time **mention chip** (the same chip `@` inserts). Prefer this over typing a date as plain text.
- `insertTextAfterInline(inlineRef, text)` — inserts a plain text node immediately after an inline object. Use this (not `appendText`) when you need text to follow an inline equation, date, line break, or other inline node.
The `at` in `insertInlineEquation`/`insertLineBreak`/`insertDate` is a **character offset into the block's plain text** — inline objects don't count toward it. Compute it (`text.length`, `text.indexOf('word')`) rather than guessing. When you do use `insertLineBreak` for soft-break content, set the first line then add each break at the running text length and `insertTextAfterInline` the next line:
@@ -342,7 +342,7 @@ After:
<video id="b4" version="1" srcType="url" _id="" url="https://x/movie.mp4" width="0" height="0" scale="1" constrainedWidth="null" constrainedHeight="null" controls="true"/>
<image id="b5" version="1" srcType="url" _id="" url="https://x/cat.png" width="0" height="0" scale="1" constrainedWidth="null" constrainedHeight="null" alt="cat"/>
<hr id="b6"/>
- <p id="b2"><equation id="b7" version="1" equation="x^2" inline="true"/><t id="t2">Bel</t><br id="b8"/><date id="b9" date="2026-06-23" displayFormat="MMM d, yyyy"/><t id="t3">ow</t></p>
+ <p id="b2"><equation id="b7" version="1" equation="x^2" inline="true"/><t id="t2">Bel</t><br id="b8"/><date-mention id="b9" date="2026-06-23" displayFormat="MMM d, yyyy"/><t id="t3">ow</t></p>
</doc>
```
@@ -366,7 +366,7 @@ Before:
<doc>
<image id="img1" version="1" srcType="url" _id="" url="https://x/cat.png" alt="cat"/>
<video id="vid1" version="1" srcType="url" _id="" url="https://x/old.mp4" controls="true"/>
- <p id="b1"><date id="date1" date="2026-06-23" displayFormat="MMM d"/></p>
+ <p id="b1"><date-mention id="date1" date="2026-06-23" displayFormat="MMM d"/></p>
</doc>
```
@@ -376,23 +376,33 @@ After:
<doc>
<image id="img1" version="1" srcType="url" _id="" url="https://x/dog.png" alt="dog"/>
<video id="vid1" version="1" srcType="url" _id="" url="https://x/new.mp4" controls="false"/>
- <p id="b1"><date id="date1" date="2026-07-01" displayFormat="yyyy-MM-dd"/></p>
+ <p id="b1"><date-mention id="date1" date="2026-07-01" displayFormat="yyyy-MM-dd"/></p>
</doc>
```
## Mentions
-Use the ids and details supplied in the task -- do not invent them.
+These insert the same @-mention chips the user inserts from the `@` menu. Use the ids and details supplied in the task -- do not invent entity ids. Date/time chips do not need a looked-up id.
+Existing chips in the document XML look like `<user-mention>`, `<date-mention>`, `<document-mention>`, `<agent-session-mention>`, `<contact-mention>`, `<group-mention>`, `<pr-mention>`, `<tag-mention>`. Leave them intact unless the task asks to change them.
+
+- `insertDate(blockId, at, isoDate, displayFormat?)` · `mentionDate(...)` — time chip. `isoDate` is ISO 8601; `displayFormat` is the label on the chip (e.g. `'Mon, Dec 1, 2025'`, `'Today'`, `'3:00 PM'`).
- `insertMention(blockId, at, mention)`
- `mentionUser(blockId, at, { userId, email })`
- `mentionContact(blockId, at, { contactId, name, emailOrDomain, isCompany })`
- `mentionGroup(blockId, at, { groupAlias })`
-- `mentionDocument(blockId, at, { documentId, documentName, blockName })`
+- `mentionDocument(blockId, at, { documentId, documentName, blockName, blockParams? })` — documents, channels, chats, projects, tasks, emails, calendar events, skills, calls, automations (`blockName` is `md`/`channel`/`chat`/`project`/`task`/`email`/`calendar`/`skill`/`call`/`automation`/…). `blockParams` is for channel messages (`channel_message_id`) and calendar occurrences (`occurrenceKey`).
+- `mentionAgentSession(blockId, at, { id, label?, expanded? })` — existing agent session. `expanded: true` inserts the card that follows the session's latest turn.
+- `mentionPullRequest(blockId, at, { id, label? })`
+- `mentionTag(blockId, at, { optionId, propertyDefinitionId, scope, name, color? })`
```ts
+// `at` is a plain-text offset; chips do not increase it. 6 appends after "Email ".
editor.mentionUser('b1', 6, { userId: 'u1', email: '[email protected]' });
-editor.mentionContact('b1', 7, { contactId: 'c1', name: 'Acme', emailOrDomain: 'acme.com', isCompany: true });
+editor.mentionContact('b1', 6, { contactId: 'c1', name: 'Acme', emailOrDomain: 'acme.com', isCompany: true });
+editor.mentionDate('b1', 6, '2026-07-08T00:00:00.000Z', 'Today');
+editor.mentionAgentSession('b1', 6, { id: 'sess-1', label: 'Fix login' });
+editor.mentionDocument('b1', 6, { documentId: 'd1', documentName: 'Spec', blockName: 'md' });
```
Before:
@@ -407,7 +417,7 @@ After:
```xml
<doc>
- <p id="b1"><t id="t1">Email </t><mention id="m1" kind="user" userId="u1" email="[email protected]"/><mention id="m2" kind="contact" contactId="c1" name="Acme" emailOrDomain="acme.com" isCompany="true"/></p>
+ <p id="b1"><t id="t1">Email </t><document-mention id="m5" documentId="d1" name="Spec" blockName="md"/><agent-session-mention id="m4" sessionId="sess-1" label="Fix login"/><date-mention id="m3" date="2026-07-08T00:00:00.000Z" displayFormat="Today"/><contact-mention id="m2" contactId="c1" name="Acme" email="acme.com" isCompany="true"/><user-mention id="m1" userId="u1" email="[email protected]"/></p>
</doc>
```
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 a236c6607a..c0895329a9 100644
--- a/services/ai-editing-worker/src/ai-editing/prompts/SUPERVISOR.md
+++ b/services/ai-editing-worker/src/ai-editing/prompts/SUPERVISOR.md
@@ -21,7 +21,7 @@ You should provide high level English instructions to writers about the changes
- Mention existing XML ids for the target region. The writers only get to see context surrounding mentioned nodes.
- Use native editor objects when appropriate, like dividers, tables, etc. Do not simulate native objects with plain text, like `======` for a divider.
-- To mention a person, use the `userId`/`email` (or `contactId`/`name`/`emailOrDomain`) from the request. 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.
+- To mention a person, date/time, document, channel, agent session, or other chip, use the ids and details from the request (userId/email, documentId/documentName/blockName, session id, ISO date plus displayFormat). 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.
- 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.
@@ -40,5 +40,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 a mention or document-card if the required ids were not provided in the request. Do not invent or guess ids.
+- 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.
- Do not use it just because an edit is complex -- attempt those directly.
diff --git a/services/ai-editing-worker/src/editor-sandbox-code.ts b/services/ai-editing-worker/src/editor-sandbox-code.ts
index c9a6977d52..d8ff918e24 100644
--- a/services/ai-editing-worker/src/editor-sandbox-code.ts
+++ b/services/ai-editing-worker/src/editor-sandbox-code.ts
@@ -1,3 +1,5 @@
// Auto-generated by scripts/generate-sandbox.ts — do not edit.
// Source of truth: src/ai-editing/editor/document-editor.ts
-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 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 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}";
+// 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 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}';