🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
:recycle: refactor: refactor builtin-tool implement
arvinxx9ede8e7ffd95
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex 68f83fdd36e..c8631a72795 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -74,6 +74,10 @@"builtins.lobe-page-agent.apiName.editTitle": "Edit page title","builtins.lobe-page-agent.apiName.indentListItem": "Indent list item","builtins.lobe-page-agent.apiName.initPage": "Initialize page",+ "builtins.lobe-page-agent.apiName.initPage.chars": " chars",+ "builtins.lobe-page-agent.apiName.initPage.creating": "Creating document",+ "builtins.lobe-page-agent.apiName.initPage.lines": " lines",+ "builtins.lobe-page-agent.apiName.initPage.result": "Document created","builtins.lobe-page-agent.apiName.insertTableColumn": "Insert table column","builtins.lobe-page-agent.apiName.insertTableRow": "Insert table row","builtins.lobe-page-agent.apiName.listSnapshots": "List snapshots",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex 654e7170f64..1c93941cb32 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -92,6 +92,7 @@"builtins.lobe-page-agent.apiName.indentListItem": "缩进列表项","builtins.lobe-page-agent.apiName.initPage": "开始书写内容","builtins.lobe-page-agent.apiName.initPage.chars": "字",+ "builtins.lobe-page-agent.apiName.initPage.creating": "文档创作中","builtins.lobe-page-agent.apiName.initPage.lines": "行","builtins.lobe-page-agent.apiName.initPage.result": "已创作文档","builtins.lobe-page-agent.apiName.insertTableColumn": "插入表格列",diff --git a/packages/builtin-tool-memory/package.json b/packages/builtin-tool-memory/package.jsonindex 316de8529e8..94bc76f6f60 100644--- a/packages/builtin-tool-memory/package.json+++ b/packages/builtin-tool-memory/package.json@@ -3,7 +3,8 @@"version": "1.0.0","private": true,"exports": {- ".": "./src/index.ts"+ ".": "./src/index.ts",+ "./executor": "./src/executor/index.ts"},"main": "./src/index.ts","dependencies": {diff --git a/packages/builtin-tool-memory/src/executor/index.ts b/packages/builtin-tool-memory/src/executor/index.tsnew file mode 100644index 00000000000..ddc3a324512--- /dev/null+++ b/packages/builtin-tool-memory/src/executor/index.ts@@ -0,0 +1,307 @@+import type {+ AddIdentityActionSchema,+ ContextMemoryItemSchema,+ ExperienceMemoryItemSchema,+ PreferenceMemoryItemSchema,+ RemoveIdentityActionSchema,+ UpdateIdentityActionSchema,+} from '@lobechat/memory-user-memory/schemas';+import { BaseExecutor, type BuiltinToolResult, SearchMemoryParams } from '@lobechat/types';+import type { z } from 'zod';++import { userMemoryService } from '@/services/userMemory';++import { MemoryIdentifier } from '../manifest';+import { MemoryApiName } from '../types';++/**+ * Format search results into human-readable summary+ */+const formatSearchResultsSummary = (result: {+ contexts: unknown[];+ experiences: unknown[];+ preferences: unknown[];+}): string => {+ const total = result.contexts.length + result.experiences.length + result.preferences.length;++ if (total === 0) {+ return '🔍 No memories found matching the query.';+ }++ const parts: string[] = [`🔍 Found ${total} memories:`];++ if (result.contexts.length > 0) {+ parts.push(`- ${result.contexts.length} context memories`);+ }+ if (result.experiences.length > 0) {+ parts.push(`- ${result.experiences.length} experience memories`);+ }+ if (result.preferences.length > 0) {+ parts.push(`- ${result.preferences.length} preference memories`);+ }++ return parts.join('\n');+};++/**+ * Memory Tool Executor+ *+ * Handles all memory-related operations including search, add, update, and remove.+ */+class MemoryExecutor extends BaseExecutor<typeof MemoryApiName> {+ readonly identifier = MemoryIdentifier;+ protected readonly apiEnum = MemoryApiName;++ // ==================== Search API ====================++ /**+ * Search user memories based on query+ */+ searchUserMemory = async (params: SearchMemoryParams): Promise<BuiltinToolResult> => {+ try {+ const result = await userMemoryService.searchMemory(params);++ return {+ content: formatSearchResultsSummary(result),+ state: result,+ success: true,+ };+ } catch (error) {+ const err = error as Error;+ return {+ error: {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ success: false,+ };+ }+ };++ // ==================== Add APIs ====================++ /**+ * Add a context memory+ */+ addContextMemory = async (+ params: z.infer<typeof ContextMemoryItemSchema>,+ ): Promise<BuiltinToolResult> => {+ try {+ const result = await userMemoryService.addContextMemory(params);++ if (!result.success) {+ return {+ error: {+ message: result.message,+ type: 'PluginServerError',+ },+ success: false,+ };+ }++ return {+ content: `🧠 Context memory saved: "${params.title}"`,+ state: { contextId: result.contextId, memoryId: result.memoryId },+ success: true,+ };+ } catch (error) {+ const err = error as Error;+ return {+ error: {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ success: false,+ };+ }+ };++ /**+ * Add an experience memory+ */+ addExperienceMemory = async (+ params: z.infer<typeof ExperienceMemoryItemSchema>,+ ): Promise<BuiltinToolResult> => {+ try {+ const result = await userMemoryService.addExperienceMemory(params);++ if (!result.success) {+ return {+ error: {+ message: result.message,+ type: 'PluginServerError',+ },+ success: false,+ };+ }++ return {+ content: `🧠 Experience memory saved: "${params.title}"`,+ state: { experienceId: result.experienceId, memoryId: result.memoryId },+ success: true,+ };+ } catch (error) {+ const err = error as Error;+ return {+ error: {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ success: false,+ };+ }+ };++ /**+ * Add an identity memory+ */+ addIdentityMemory = async (+ params: z.infer<typeof AddIdentityActionSchema>,+ ): Promise<BuiltinToolResult> => {+ try {+ const result = await userMemoryService.addIdentityMemory(params);++ if (!result.success) {+ return {+ error: {+ message: result.message,+ type: 'PluginServerError',+ },+ success: false,+ };+ }++ return {+ content: `🧠 Identity memory saved: "${params.title}"`,+ state: { identityId: result.identityId, memoryId: result.memoryId },+ success: true,+ };+ } catch (error) {+ const err = error as Error;+ return {+ error: {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ success: false,+ };+ }+ };++ /**+ * Add a preference memory+ */+ addPreferenceMemory = async (+ params: z.infer<typeof PreferenceMemoryItemSchema>,+ ): Promise<BuiltinToolResult> => {+ try {+ const result = await userMemoryService.addPreferenceMemory(params);++ if (!result.success) {+ return {+ error: {+ message: result.message,+ type: 'PluginServerError',+ },+ success: false,+ };+ }++ return {+ content: `🧠 Preference memory saved: "${params.title}"`,+ state: { memoryId: result.memoryId, preferenceId: result.preferenceId },+ success: true,+ };+ } catch (error) {+ const err = error as Error;+ return {+ error: {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ success: false,+ };+ }+ };++ // ==================== Update/Remove APIs ====================++ /**+ * Update an identity memory+ */+ updateIdentityMemory = async (+ params: z.infer<typeof UpdateIdentityActionSchema>,+ ): Promise<BuiltinToolResult> => {+ try {+ const result = await userMemoryService.updateIdentityMemory(params);++ if (!result.success) {+ return {+ error: {+ message: result.message,+ type: 'PluginServerError',+ },+ success: false,+ };+ }++ return {+ content: `✏️ Identity memory updated: ${params.id}`,+ state: { identityId: params.id },+ success: true,+ };+ } catch (error) {+ const err = error as Error;+ return {+ error: {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ success: false,+ };+ }+ };++ /**+ * Remove an identity memory+ */+ removeIdentityMemory = async (+ params: z.infer<typeof RemoveIdentityActionSchema>,+ ): Promise<BuiltinToolResult> => {+ try {+ const result = await userMemoryService.removeIdentityMemory(params);++ if (!result.success) {+ return {+ error: { message: result.message, type: 'PluginServerError' },+ success: false,+ };+ }++ return {+ content: `🗑️ Identity memory removed: ${params.id}\nReason: ${params.reason}`,+ state: { identityId: params.id, reason: params.reason },+ success: true,+ };+ } catch (error) {+ const err = error as Error;+ return {+ error: {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ success: false,+ };+ }+ };+}++// Export the executor instance for registration+export const memoryExecutor = new MemoryExecutor();diff --git a/packages/builtin-tool-memory/src/index.ts b/packages/builtin-tool-memory/src/index.tsindex 01bebb53dd7..8bb61d6f34c 100644--- a/packages/builtin-tool-memory/src/index.ts+++ b/packages/builtin-tool-memory/src/index.ts@@ -1,3 +1,3 @@-export { MemoryManifest, UserMemoryManifest } from './manifest';+export { MemoryIdentifier, MemoryManifest } from './manifest';export { systemPrompt } from './systemRole';-export { MemoryApiName, type MemoryApiNameType,UserMemoryApiName } from './types';+export { MemoryApiName, type MemoryApiNameType } from './types';diff --git a/packages/builtin-tool-memory/src/manifest.ts b/packages/builtin-tool-memory/src/manifest.tsindex dc1dc725cec..a3bcbc013be 100644--- a/packages/builtin-tool-memory/src/manifest.ts+++ b/packages/builtin-tool-memory/src/manifest.ts@@ -12,6 +12,8 @@ import type { BuiltinToolManifest } from '@lobechat/types';import { systemPrompt } from './systemRole';import { MemoryApiName } from './types';+export const MemoryIdentifier = 'lobe-user-memory';+export const MemoryManifest: BuiltinToolManifest = {api: [{diff --git a/packages/builtin-tool-notebook/package.json b/packages/builtin-tool-notebook/package.jsonindex a4a9a8f2efe..b5258fc7762 100644--- a/packages/builtin-tool-notebook/package.json+++ b/packages/builtin-tool-notebook/package.json@@ -5,6 +5,7 @@"exports": {".": "./src/index.ts","./client": "./src/client/index.ts",+ "./executor": "./src/executor/index.ts","./executionRuntime": "./src/ExecutionRuntime/index.ts"},"main": "./src/index.ts",diff --git a/src/store/tool/slices/builtin/executors/lobe-notebook.ts b/packages/builtin-tool-notebook/src/executor/index.tssimilarity index 94%rename from src/store/tool/slices/builtin/executors/lobe-notebook.tsrename to packages/builtin-tool-notebook/src/executor/index.tsindex 31d740ca1e7..385522a1676 100644--- a/src/store/tool/slices/builtin/executors/lobe-notebook.ts+++ b/packages/builtin-tool-notebook/src/executor/index.ts@@ -6,6 +6,10 @@** Note: listDocuments is not exposed as a tool - it's automatically injected by the system.*/+import { BaseExecutor, type BuiltinToolContext, type BuiltinToolResult } from '@lobechat/types';++import { notebookService } from '@/services/notebook';+import {type CreateDocumentArgs,type DeleteDocumentArgs,@@ -13,10 +17,7 @@ import {NotebookApiName,NotebookIdentifier,type UpdateDocumentArgs,-} from '@lobechat/builtin-tool-notebook';-import { BaseExecutor, type BuiltinToolContext, type BuiltinToolResult } from '@lobechat/types';--import { notebookService } from '@/services/notebook';+} from '../types';class NotebookExecutor extends BaseExecutor<typeof NotebookApiName> {readonly identifier = NotebookIdentifier;@@ -50,7 +51,7 @@ class NotebookExecutor extends BaseExecutor<typeof NotebookApiName> {});return {- content: `Document "${document.title}" created successfully`,+ content: `📝 Document "${document.title}" created successfully`,state: { document },success: true,};@@ -82,7 +83,7 @@ class NotebookExecutor extends BaseExecutor<typeof NotebookApiName> {const document = await notebookService.updateDocument(params);return {- content: `Document updated successfully`,+ content: `✏️ Document updated successfully`,state: { document },success: true,};@@ -153,7 +154,7 @@ class NotebookExecutor extends BaseExecutor<typeof NotebookApiName> {await notebookService.deleteDocument(params.id);return {- content: `Document deleted successfully`,+ content: `🗑️ Document deleted successfully`,success: true,};} catch (e) {diff --git a/packages/builtin-tool-page-agent/package.json b/packages/builtin-tool-page-agent/package.jsonindex b33e62996cc..c0994300677 100644--- a/packages/builtin-tool-page-agent/package.json+++ b/packages/builtin-tool-page-agent/package.json@@ -5,11 +5,14 @@"exports": {".": "./src/index.ts","./client": "./src/client/index.ts",+ "./executor": "./src/executor/index.ts","./executionRuntime": "./src/ExecutionRuntime/index.ts"},"main": "./src/index.ts","devDependencies": {- "@lobechat/types": "workspace:*"+ "@lobechat/types": "workspace:*",+ "@lobehub/editor": "^3",+ "lexical": "^0.39.0"},"peerDependencies": {"@lobehub/editor": "^3",diff --git a/packages/builtin-tool-page-agent/src/ExecutionRuntime/__snapshots__/index.test.ts.snap b/packages/builtin-tool-page-agent/src/ExecutionRuntime/__snapshots__/index.test.ts.snapnew file mode 100644index 00000000000..05e48f1a373--- /dev/null+++ b/packages/builtin-tool-page-agent/src/ExecutionRuntime/__snapshots__/index.test.ts.snap@@ -0,0 +1,145 @@+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html++exports[`PageAgentExecutionRuntime > modifyNodes > error handling > should normalize single operation to array 1`] = `+"# Title++Single op++First paragraph.++Second paragraph.++"+`;++exports[`PageAgentExecutionRuntime > modifyNodes > insert > should insert multiple nodes after same node 1`] = `+"# Title++Insert 3++Insert 2++Insert 1++First paragraph.++Second paragraph.++"+`;++exports[`PageAgentExecutionRuntime > modifyNodes > insert > should insert single node after existing node 1`] = `+"# Title++New inserted paragraph++First paragraph.++Second paragraph.++"+`;++exports[`PageAgentExecutionRuntime > modifyNodes > mixed operations > should handle insert, modify, and remove in single call 1`] = `+"# Title++# Updated title++New content++First paragraph.++Second paragraph.++"+`;++exports[`PageAgentExecutionRuntime > modifyNodes > modify > should modify existing node content 1`] = `+"# Title++First paragraph.++Modified content here++Second paragraph.++"+`;++exports[`PageAgentExecutionRuntime > modifyNodes > modify > should modify multiple nodes at once 1`] = `+"# Title++First paragraph.++Modified first++Second paragraph.++Modified second++"+`;++exports[`PageAgentExecutionRuntime > modifyNodes > remove > should remove existing node 1`] = `+"<?xml version="1.0" encoding="UTF-8"?>+<root>+ <h1 id="ll63">+ <span id="lqqe">Title</span>+ </h1>+ <p id="m7fb">+ <span id="mczm">Second paragraph.</span>+ </p>+</root>"+`;++exports[`PageAgentExecutionRuntime > modifyNodes > remove > should remove multiple nodes 1`] = `+"# Title++First paragraph.++Second paragraph.++"+`;++exports[`PageAgentExecutionRuntime > replaceText > should replace all occurrences by default 1`] = `+"Hi world. This is a test. Hi again. Testing the world.++"+`;++exports[`PageAgentExecutionRuntime > replaceText > should support regex first occurrence only 1`] = `+"X world. This is a test. Hello again. Testing the world.++"+`;++exports[`PageAgentExecutionRuntime > replaceText > should support regex patterns with optional groups 1`] = `+"Hello world. This is a demo. Hello again. Testing the world.++"+`;++exports[`PageAgentExecutionRuntime > replaceText > should support regex with alternation 1`] = `+"X X. This is a test. X again. Testing the X.++"+`;++exports[`PageAgentExecutionRuntime > replaceText > should support regex with character classes 1`] = `+"Guest and Guest are online.++"+`;++exports[`PageAgentExecutionRuntime > replaceText > should support regex with quantifiers 1`] = `+"Hi world! Hi again!++"+`;++exports[`PageAgentExecutionRuntime > replaceText > should support regex with word boundaries 1`] = `+"Hello universe. This is a test. Hello again. Testing the universe.++"+`;diff --git a/packages/builtin-tool-page-agent/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-page-agent/src/ExecutionRuntime/index.test.tsindex 9dafdc14bfb..a08d5da304e 100644--- a/packages/builtin-tool-page-agent/src/ExecutionRuntime/index.test.ts+++ b/packages/builtin-tool-page-agent/src/ExecutionRuntime/index.test.ts@@ -1,675 +1,569 @@import {- IEditor,- LITEXML_APPLY_COMMAND,- LITEXML_INSERT_COMMAND,- LITEXML_REMOVE_COMMAND,+ CommonPlugin,+ type IEditor,+ Kernel,+ LitexmlPlugin,+ MarkdownPlugin,+ moment,} from '@lobehub/editor';+import { resetRandomKey } from 'lexical';import { beforeEach, describe, expect, it, vi } from 'vitest';import { PageAgentExecutionRuntime } from './index';-/**- * Helper to generate LiteXML from document state- * Converts JSON document structure to LiteXML format- */-const generateLiteXML = (documentState: any): string => {- const nodeToXML = (node: any, index: number, parentPath: string = ''): string => {- const nodeId = parentPath ? `${parentPath}_${index}` : `node_${index}`;+describe('PageAgentExecutionRuntime', () => {+ let runtime: PageAgentExecutionRuntime;+ let editor: IEditor;+ let mockTitleSetter: ReturnType<typeof vi.fn>;+ let mockTitleGetter: ReturnType<typeof vi.fn>;- if (node.type === 'text') {- return `<span id="${nodeId}">${node.text || ''}</span>`;- }+ beforeEach(() => {+ resetRandomKey();+ editor = new Kernel();+ editor.registerPlugins([CommonPlugin, MarkdownPlugin, LitexmlPlugin]);+ editor.initNodeEditor();- let tagName = node.type;- if (node.type === 'heading') tagName = node.tag || 'h1';- if (node.type === 'paragraph') tagName = 'p';- if (node.type === 'tablerow') tagName = 'tr';- if (node.type === 'tablecell') tagName = 'td';+ runtime = new PageAgentExecutionRuntime();+ runtime.setEditor(editor);- const children = node.children- ? node.children.map((child: any, i: number) => nodeToXML(child, i, nodeId)).join('')- : '';+ mockTitleSetter = vi.fn();+ mockTitleGetter = vi.fn().mockReturnValue('Test Title');+ runtime.setTitleHandlers(mockTitleSetter, mockTitleGetter);+ });- return `<${tagName} id="${nodeId}">${children}</${tagName}>`;- };+ describe('initPage', () => {+ it('should initialize document from markdown and verify editor state', async () => {+ const inputMarkdown = 'Hello world\n\nThis is a paragraph.';+ const result = await runtime.initPage({ markdown: inputMarkdown });+ await moment();- if (!documentState?.root?.children) return '';+ // Verify result+ expect(result.nodeCount).toBeGreaterThanOrEqual(0);+ expect(result.extractedTitle).toBeUndefined();- return documentState.root.children- .map((child: any, i: number) => nodeToXML(child, i, ''))- .join('');-};+ // Verify editor state - full text match (editor adds trailing space)+ const editorMarkdown = editor.getDocument('markdown') as unknown as string;+ expect(editorMarkdown).toBe('Hello world\n\nThis is a paragraph. \n\n');-describe('PageAgentExecutionRuntime - Node CRUD Operations', () => {- let runtime: PageAgentExecutionRuntime;- let mockEditor: IEditor;- let documentState: any;- let dispatchCommandMock: ReturnType<typeof vi.fn>;+ // Verify XML structure+ const editorXml = editor.getDocument('litexml') as unknown as string;+ expect(editorXml).toMatch(/<root>.*<p id="[^"]+".*>.*Hello world.*<\/p>.*<\/root>/s);+ });- beforeEach(() => {- runtime = new PageAgentExecutionRuntime();+ it('should extract title from markdown heading and set content without title', async () => {+ const result = await runtime.initPage({+ markdown: '# My Document Title\n\nThis is the content.',+ });+ await moment();- // Mock document state- documentState = {- root: {- children: [- {- children: [- {- text: 'Title',- type: 'text',- },- ],- tag: 'h1',- type: 'heading',- },- {- children: [- {- text: 'This is a paragraph',- type: 'text',- },- ],- type: 'paragraph',- },- ],- type: 'root',- },- };-- // Create dispatchCommand mock that simulates editor behavior- dispatchCommandMock = vi.fn((command: any, payload: any) => {- if (command === LITEXML_INSERT_COMMAND) {- // Simulate inserting a node - parse litexml and add to document- const litexml = payload.litexml;- const match = /<(\w+)[^>]*>(?:<span>)?([^<]*)(?:<\/span>)?<\/\1>/.exec(litexml);- if (match) {- const [, tagName, content] = match;- const newNode: any = {- children: content ? [{ text: content, type: 'text' }] : [],- type: tagName === 'p' ? 'paragraph' : tagName.startsWith('h') ? 'heading' : tagName,- };- if (tagName.startsWith('h')) {- newNode.tag = tagName;- }-- // Handle position based on afterId or beforeId- const afterId = payload.afterId;- const beforeId = payload.beforeId;-- if (afterId === 'root') {- // Append to root- documentState.root.children.push(newNode);- } else if (afterId) {- // Insert after the reference node- const nodeMatch = /^node_(\d+)(?:_(\d+))?$/.exec(afterId);- if (nodeMatch) {- const parentIndex = parseInt(nodeMatch[1], 10);- const childIndex =- nodeMatch[2] !== undefined ? parseInt(nodeMatch[2], 10) : undefined;-- if (childIndex !== undefined) {- // Append to parent node's children (after last child = append)- documentState.root.children[parentIndex].children.push({- text: content,- type: 'text',- });- } else {- // Insert after this node at root level- documentState.root.children.splice(parentIndex + 1, 0, newNode);- }- }- } else if (beforeId) {- // Insert before the reference node- const nodeMatch = /^node_(\d+)(?:_(\d+))?$/.exec(beforeId);- if (nodeMatch) {- const parentIndex = parseInt(nodeMatch[1], 10);- const childIndex =- nodeMatch[2] !== undefined ? parseInt(nodeMatch[2], 10) : undefined;-- if (childIndex !== undefined) {- // Prepend to parent node's children (before first child = prepend)- documentState.root.children[parentIndex].children.unshift({- text: content,- type: 'text',- });- } else {- // Insert before this node at root level- documentState.root.children.splice(parentIndex, 0, newNode);- }- }- }- }- return true;- }+ // Verify title extraction+ expect(result.extractedTitle).toBe('My Document Title');+ expect(mockTitleSetter).toHaveBeenCalledWith('My Document Title');- if (command === LITEXML_APPLY_COMMAND) {- // Simulate updating nodes- const litexmlList = Array.isArray(payload.litexml) ? payload.litexml : [payload.litexml];- for (const litexml of litexmlList) {- const idMatch = /id="([^"]+)"/.exec(litexml);- if (idMatch) {- const nodeId = idMatch[1];- // Extract content - try nested span first, then direct content between tags- let content = '';- const spanMatch = /<span[^>]*>([^<]*)<\/span>/.exec(litexml);- if (spanMatch) {- content = spanMatch[1];- } else {- // Direct content: <p id="...">content</p>- const directMatch = />([^<]+)<\/\w+>$/.exec(litexml);- if (directMatch) {- content = directMatch[1];- }- }-- // Find and update the node- const nodeMatch = /^node_(\d+)(?:_(\d+))?$/.exec(nodeId);- if (nodeMatch) {- const parentIndex = parseInt(nodeMatch[1], 10);- const childIndex =- nodeMatch[2] !== undefined ? parseInt(nodeMatch[2], 10) : undefined;-- if (childIndex !== undefined) {- // Update child text node- if (documentState.root.children[parentIndex]?.children[childIndex]) {- documentState.root.children[parentIndex].children[childIndex].text = content;- }- } else {- // Update parent node- const node = documentState.root.children[parentIndex];- if (node) {- if (content) {- node.children = [{ text: content, type: 'text' }];- }- // Handle attributes- const classMatch = /className="([^"]*)"/.exec(litexml);- if (classMatch && classMatch[1] !== 'null') {- node.className = classMatch[1];- } else if (litexml.includes('className=')) {- delete node.className;- }- const dataTestMatch = /data-test="([^"]*)"/.exec(litexml);- if (dataTestMatch && dataTestMatch[1] !== 'null') {- node['data-test'] = dataTestMatch[1];- }- }- }- }- }- }- return true;- }+ // Verify editor state - only content without title (editor adds trailing space)+ const editorMarkdown = editor.getDocument('markdown') as unknown as string;+ expect(editorMarkdown).toBe('This is the content. \n\n');+ });- if (command === LITEXML_REMOVE_COMMAND) {- const nodeId = payload.id;- const nodeMatch = /^node_(\d+)(?:_(\d+))?$/.exec(nodeId);- if (nodeMatch) {- const parentIndex = parseInt(nodeMatch[1], 10);- const childIndex = nodeMatch[2] !== undefined ? parseInt(nodeMatch[2], 10) : undefined;-- if (childIndex !== undefined) {- // Delete child node- if (documentState.root.children[parentIndex]?.children) {- documentState.root.children[parentIndex].children.splice(childIndex, 1);- }- } else {- // Delete parent node- documentState.root.children.splice(parentIndex, 1);- }- }- return true;- }+ it('should handle markdown with multiple headings', async () => {+ const result = await runtime.initPage({+ markdown: '# Main Title\n\n## Section 1\n\nContent here.\n\n## Section 2\n\nMore content.',+ });+ await moment();- return false;+ // Verify title extraction (only first h1)+ expect(result.extractedTitle).toBe('Main Title');++ // Verify editor state - content after title extraction (editor adds trailing space)+ const editorMarkdown = editor.getDocument('markdown') as unknown as string;+ expect(editorMarkdown).toBe(+ '## Section 1\n\nContent here. \n\n## Section 2\n\nMore content. \n\n',+ );});- // Mock editor- mockEditor = {- dispatchCommand: dispatchCommandMock,- getDocument: vi.fn((format: string) => {- if (format === 'json') {- return documentState;- }- if (format === 'litexml') {- return generateLiteXML(documentState);- }- return null;- }),- setDocument: vi.fn((format: string, content: string) => {- if (format === 'json') {- documentState = JSON.parse(content);- }- }),- } as unknown as IEditor;+ it('should throw error when editor is not initialized', async () => {+ runtime.setEditor(null);- runtime.setEditor(mockEditor);+ await expect(runtime.initPage({ markdown: 'Test' })).rejects.toThrow(+ 'Editor not initialized',+ );+ });});- describe('createNode', () => {- it('should create a paragraph node and append to root', async () => {- const result = await runtime.createNode({- content: 'New paragraph content',- type: 'p',- });+ describe('editTitle', () => {+ it('should update title and return previous and new title', async () => {+ const result = await runtime.editTitle({ title: 'New Title' });- expect(result.success).toBe(true);- expect(result.content).toContain('Successfully created p node');- expect(documentState.root.children).toHaveLength(3);- expect(documentState.root.children[2].type).toBe('paragraph');- expect(documentState.root.children[2].children[0].text).toBe('New paragraph content');+ expect(result.previousTitle).toBe('Test Title');+ expect(result.newTitle).toBe('New Title');+ expect(mockTitleSetter).toHaveBeenCalledWith('New Title');});- it('should create a heading node with tag', async () => {- const result = await runtime.createNode({- content: 'New heading',- type: 'h2',- });+ it('should throw error when title handlers are not set', async () => {+ runtime.setTitleHandlers(null, null);- expect(result.success).toBe(true);- const newHeading = documentState.root.children[2];- expect(newHeading.type).toBe('heading');- expect(newHeading.tag).toBe('h2');- expect(newHeading.children[0].text).toBe('New heading');+ await expect(runtime.editTitle({ title: 'New Title' })).rejects.toThrow(+ 'Title handlers not initialized',+ );});+ });- it('should insert node after reference node', async () => {- const result = await runtime.createNode({- content: 'Inserted paragraph',- position: 'after',- referenceNodeId: 'node_0',- type: 'p',+ describe('getPageContent', () => {+ beforeEach(async () => {+ await runtime.initPage({+ markdown: '# Test Document\n\nThis is **bold** and *italic* text.',});+ await moment();+ });- expect(result.success).toBe(true);- // Verify dispatchCommand was called with correct payload- expect(dispatchCommandMock).toHaveBeenCalledWith(- LITEXML_INSERT_COMMAND,- expect.objectContaining({- afterId: 'node_0',- litexml: expect.stringContaining('Inserted paragraph'),- }),- );+ it('should return markdown content', async () => {+ const result = await runtime.getPageContent({ format: 'markdown' });++ expect(result.markdown).toBeDefined();+ expect(result.markdown).toContain('bold');+ expect(result.xml).toBeUndefined();});- it('should insert node before reference node', async () => {- const result = await runtime.createNode({- content: 'Inserted before',- position: 'before',- referenceNodeId: 'node_1',- type: 'p',- });+ it('should return xml content', async () => {+ const result = await runtime.getPageContent({ format: 'xml' });- expect(result.success).toBe(true);- // Verify dispatchCommand was called with correct payload- expect(dispatchCommandMock).toHaveBeenCalledWith(- LITEXML_INSERT_COMMAND,- expect.objectContaining({- beforeId: 'node_1',- litexml: expect.stringContaining('Inserted before'),- }),- );+ expect(result.xml).toBeDefined();+ expect(result.xml).toContain('id=');+ expect(result.markdown).toBeUndefined();});- it('should append node as child of reference node', async () => {- const result = await runtime.createNode({- content: 'Child text',- position: 'append',- referenceNodeId: 'node_0',- type: 'span',- });+ it('should return both formats by default', async () => {+ const result = await runtime.getPageContent({ format: 'both' });- expect(result.success).toBe(true);- // Verify dispatchCommand was called - append uses afterId- expect(dispatchCommandMock).toHaveBeenCalledWith(- LITEXML_INSERT_COMMAND,- expect.objectContaining({- afterId: 'node_0',- litexml: expect.stringContaining('Child text'),- }),- );+ expect(result.markdown).toBeDefined();+ expect(result.xml).toBeDefined();});- it('should prepend node as child of reference node', async () => {- const result = await runtime.createNode({- content: 'First child',- position: 'prepend',- referenceNodeId: 'node_0',- type: 'span',- });+ it('should include metadata', async () => {+ const result = await runtime.getPageContent({ format: 'both' });- expect(result.success).toBe(true);- // Note: Current implementation treats 'prepend' same as 'append' (uses afterId)- // Only 'before' position uses beforeId- expect(dispatchCommandMock).toHaveBeenCalledWith(- LITEXML_INSERT_COMMAND,- expect.objectContaining({- afterId: 'node_0',- litexml: expect.stringContaining('First child'),- }),- );+ expect(result.title).toBe('Test Title');+ expect(result.charCount).toBeGreaterThan(0);+ expect(result.lineCount).toBeGreaterThan(0);});});- describe('updateNode', () => {- it('should update node content', async () => {- const result = await runtime.updateNode({- content: 'Updated paragraph text',- nodeId: 'node_1',+ describe('modifyNodes', () => {+ beforeEach(async () => {+ editor.setDocument('markdown', '# Title\n\nFirst paragraph.\n\nSecond paragraph.\n\n');+ await moment();+ });++ describe('insert', () => {+ it('should insert single node after existing node', async () => {+ const xmlBefore = editor.getDocument('litexml') as unknown as string;+ const idMatch = /id="([^"]+)"/.exec(xmlBefore);+ const existingId = idMatch ? idMatch[1] : 'root';++ const result = await runtime.modifyNodes({+ operations: [+ {+ action: 'insert',+ afterId: existingId,+ litexml: '<p>New inserted paragraph</p>',+ },+ ],+ });+ await moment();++ expect(result.successCount).toBe(1);+ expect(result.totalCount).toBe(1);+ expect(result.results[0].action).toBe('insert');+ expect(result.results[0].success).toBe(true);++ const markdown = editor.getDocument('markdown') as unknown as string;+ expect(markdown).toMatchSnapshot();});- expect(result.success).toBe(true);- expect(result.content).toContain('Successfully updated node node_1');- expect(documentState.root.children[1].children[0].text).toBe('Updated paragraph text');+ it('should insert multiple nodes after same node', async () => {+ const xmlBefore = editor.getDocument('litexml') as unknown as string;+ const idMatch = /id="([^"]+)"/.exec(xmlBefore);+ const existingId = idMatch ? idMatch[1] : 'root';++ const result = await runtime.modifyNodes({+ operations: [+ { action: 'insert', afterId: existingId, litexml: '<p>Insert 1</p>' },+ { action: 'insert', afterId: existingId, litexml: '<p>Insert 2</p>' },+ { action: 'insert', afterId: existingId, litexml: '<p>Insert 3</p>' },+ ],+ });+ await moment();++ expect(result.successCount).toBe(3);+ expect(result.totalCount).toBe(3);++ const markdown = editor.getDocument('markdown') as unknown as string;+ expect(markdown).toMatchSnapshot();+ });});- it('should update text node content', async () => {- const result = await runtime.updateNode({- content: 'Updated title',- nodeId: 'node_0_0',+ describe('modify', () => {+ it('should modify existing node content', async () => {+ const xmlBefore = editor.getDocument('litexml') as unknown as string;+ const paragraphMatch = /<p id="([^"]+)"/.exec(xmlBefore);+ const paragraphId = paragraphMatch![1];++ const result = await runtime.modifyNodes({+ operations: [+ {+ action: 'modify',+ litexml: `<p id="${paragraphId}">Modified content here</p>`,+ },+ ],+ });+ await moment();++ expect(result.successCount).toBe(1);+ expect(result.results[0].action).toBe('modify');++ const markdown = editor.getDocument('markdown') as unknown as string;+ expect(markdown).toMatchSnapshot();});- expect(result.success).toBe(true);- expect(documentState.root.children[0].children[0].text).toBe('Updated title');+ it('should modify multiple nodes at once', async () => {+ const xmlBefore = editor.getDocument('litexml') as unknown as string;+ const paragraphMatches = [...xmlBefore.matchAll(/<p id="([^"]+)"/g)];++ if (paragraphMatches.length >= 2) {+ const result = await runtime.modifyNodes({+ operations: [+ {+ action: 'modify',+ litexml: [+ `<p id="${paragraphMatches[0][1]}">Modified first</p>`,+ `<p id="${paragraphMatches[1][1]}">Modified second</p>`,+ ],+ },+ ],+ });+ await moment();++ expect(result.successCount).toBe(1);++ const markdown = editor.getDocument('markdown') as unknown as string;+ expect(markdown).toMatchSnapshot();+ }+ });});- it('should update node attributes', async () => {- const result = await runtime.updateNode({- attributes: {- 'className': 'custom-class',- 'data-test': 'test-value',- },- nodeId: 'node_1',+ describe('remove', () => {+ it('should remove existing node', async () => {+ const xmlBefore = editor.getDocument('litexml') as unknown as string;+ const paragraphMatch = /<p id="([^"]+)"/.exec(xmlBefore);+ const paragraphId = paragraphMatch![1];++ const result = await runtime.modifyNodes({+ operations: [+ {+ action: 'remove',+ id: paragraphId,+ },+ ],+ });+ await moment();++ expect(result.successCount).toBe(1);+ expect(result.results[0].action).toBe('remove');++ const markdownAfter = editor.getDocument('litexml') as unknown as string;+ expect(markdownAfter).toMatchSnapshot();});- expect(result.success).toBe(true);- const paragraph = documentState.root.children[1];- expect(paragraph.className).toBe('custom-class');- expect(paragraph['data-test']).toBe('test-value');- });+ it('should remove multiple nodes', async () => {+ const xmlBefore = editor.getDocument('litexml') as unknown as string;+ const paragraphMatches = [...xmlBefore.matchAll(/<p id="([^"]+)"/g)];- it('should remove attributes when set to null', async () => {- // First add an attribute- documentState.root.children[1].className = 'to-remove';+ if (paragraphMatches.length >= 2) {+ const result = await runtime.modifyNodes({+ operations: [+ { action: 'remove', id: paragraphMatches[0][1] },+ { action: 'remove', id: paragraphMatches[1][1] },+ ],+ });+ await moment();- const result = await runtime.updateNode({- attributes: {- className: null,- },- nodeId: 'node_1',+ expect(result.successCount).toBe(2);++ const xml = editor.getDocument('markdown') as unknown as string;+ expect(xml).toMatchSnapshot();+ }});+ });- expect(result.success).toBe(true);- // Verify the command was dispatched with the correct payload- // Note: The actual attribute removal depends on editor behavior- expect(dispatchCommandMock).toHaveBeenCalledWith(- LITEXML_APPLY_COMMAND,- expect.objectContaining({- litexml: expect.arrayContaining([expect.stringContaining('id="node_1"')]),- }),- );+ describe('mixed operations', () => {+ it('should handle insert, modify, and remove in single call', async () => {+ const xmlBefore = editor.getDocument('litexml') as unknown as string;+ const idMatch = /id="([^"]+)"/.exec(xmlBefore);+ const existingId = idMatch ? idMatch[1] : 'root';++ const result = await runtime.modifyNodes({+ operations: [+ { action: 'insert', afterId: existingId, litexml: '<p>New content</p>' },+ { action: 'modify', litexml: `<h1 id="${existingId}">Updated title</h1>` },+ ],+ });+ await moment();++ expect(result.totalCount).toBe(2);++ const markdown = editor.getDocument('markdown') as unknown as string;+ expect(markdown).toMatchSnapshot();+ });});- it('should fail when node not found', async () => {- const result = await runtime.updateNode({- content: 'Updated text',- nodeId: 'node_99',+ describe('error handling', () => {+ it('should throw error when no operations provided', async () => {+ await expect(+ runtime.modifyNodes({+ // @ts-expect-error - Testing invalid input+ operations: undefined,+ }),+ ).rejects.toThrow('No operations provided');});- expect(result.success).toBe(false);- expect(result.content).toContain('not found');+ it('should normalize single operation to array', async () => {+ const xmlBefore = editor.getDocument('litexml') as unknown as string;+ const idMatch = /id="([^"]+)"/.exec(xmlBefore);+ const existingId = idMatch ? idMatch[1] : 'root';++ const result = await runtime.modifyNodes({+ // @ts-expect-error - Testing LLM edge case+ operations: { action: 'insert', afterId: existingId, litexml: '<p>Single op</p>' },+ });+ await moment();++ expect(result.successCount).toBe(1);++ const markdown = editor.getDocument('markdown') as unknown as string;+ expect(markdown).toMatchSnapshot();+ });});});- describe('deleteNode', () => {- it('should delete a node', async () => {- const result = await runtime.deleteNode({- nodeId: 'node_1',+ describe('replaceText', () => {+ beforeEach(async () => {+ editor.setDocument(+ 'markdown',+ 'Hello world. This is a test. Hello again. Testing the world.\n\n',+ );+ await moment();+ });++ it('should replace all occurrences by default', async () => {+ const result = await runtime.replaceText({+ searchText: 'Hello',+ newText: 'Hi',});+ await moment();++ expect(result.replacementCount).toBe(2);+ expect(result.modifiedNodeIds.length).toBeGreaterThan(0);- expect(result.success).toBe(true);- // The implementation uses the XML tag name (p) in the message- expect(result.content).toContain('Successfully deleted p node');- expect(documentState.root.children).toHaveLength(1);- expect(documentState.root.children[0].type).toBe('heading');+ const markdown = editor.getDocument('markdown') as unknown as string;+ expect(markdown).toMatchSnapshot();});- it('should delete a child node', async () => {- const result = await runtime.deleteNode({- nodeId: 'node_0_0',+ it('should replace first occurrence only when replaceAll is false', async () => {+ const result = await runtime.replaceText({+ searchText: 'Hello',+ newText: 'Hi',+ replaceAll: false,});+ await moment();- expect(result.success).toBe(true);- expect(documentState.root.children[0].children).toHaveLength(0);+ expect(result.replacementCount).toBe(1);});- it('should fail when trying to delete root node', async () => {- const result = await runtime.deleteNode({- nodeId: 'node_',+ it('should support regex patterns with optional groups', async () => {+ const result = await runtime.replaceText({+ searchText: 'test(ing)?',+ newText: 'demo',+ useRegex: true,});+ await moment();- expect(result.success).toBe(false);- // The implementation returns 'not found' since 'node_' is not a valid node in the XML- expect(result.content).toContain('not found');+ expect(result.replacementCount).toBeGreaterThan(0);++ const markdown = editor.getDocument('markdown') as unknown as string;+ expect(markdown).toMatchSnapshot();});- it('should fail when node not found', async () => {- const result = await runtime.deleteNode({- nodeId: 'node_99',+ it('should support regex with word boundaries', async () => {+ const result = await runtime.replaceText({+ searchText: '\\bworld\\b',+ newText: 'universe',+ useRegex: true,});+ await moment();++ expect(result.replacementCount).toBe(2);- expect(result.success).toBe(false);- expect(result.content).toContain('not found');+ const markdown = editor.getDocument('markdown') as unknown as string;+ expect(markdown).toMatchSnapshot();});- });- describe('integration tests', () => {- it('should support creating, updating, and deleting nodes in sequence', async () => {- // Create a new paragraph- const createResult = await runtime.createNode({- content: 'New content',- type: 'p',- });- expect(createResult.success).toBe(true);+ it('should support regex with character classes', async () => {+ editor.setDocument('markdown', 'User123 and User456 are online.\n\n');+ await moment();- // Update the new paragraph- const updateResult = await runtime.updateNode({- content: 'Updated content',- nodeId: 'node_2',+ const result = await runtime.replaceText({+ searchText: 'User\\d+',+ newText: 'Guest',+ useRegex: true,});- expect(updateResult.success).toBe(true);- expect(documentState.root.children[2].children[0].text).toBe('Updated content');+ await moment();- // Delete the paragraph- const deleteResult = await runtime.deleteNode({- nodeId: 'node_2',- });- expect(deleteResult.success).toBe(true);- expect(documentState.root.children).toHaveLength(2);- });- });+ expect(result.replacementCount).toBe(2);- describe('Table Operations', () => {- beforeEach(() => {- // Set up a document with a table - nodes need 'key' property for findNodeByKey- documentState = {- root: {- children: [- {- children: [- {- children: [- {- children: [{ text: 'Header 1', type: 'text' }],- key: 'node_0_0_0',- type: 'tablecell',- },- {- children: [{ text: 'Header 2', type: 'text' }],- key: 'node_0_0_1',- type: 'tablecell',- },- {- children: [{ text: 'Header 3', type: 'text' }],- key: 'node_0_0_2',- type: 'tablecell',- },- ],- key: 'node_0_0',- type: 'tablerow',- },- {- children: [- {- children: [{ text: 'Cell 1', type: 'text' }],- key: 'node_0_1_0',- type: 'tablecell',- },- {- children: [{ text: 'Cell 2', type: 'text' }],- key: 'node_0_1_1',- type: 'tablecell',- },- {- children: [{ text: 'Cell 3', type: 'text' }],- key: 'node_0_1_2',- type: 'tablecell',- },- ],- key: 'node_0_1',- type: 'tablerow',- },- ],- key: 'node_0',- type: 'table',- },- ],- type: 'root',- },- };+ const markdown = editor.getDocument('markdown') as unknown as string;+ expect(markdown).toMatchSnapshot();});- describe('insertTableRow', () => {- it('should insert a row at the end of table', async () => {- const result = await runtime.insertTableRow({- cells: ['New 1', 'New 2', 'New 3'],- tableId: 'node_0',- });+ it('should support regex with quantifiers', async () => {+ editor.setDocument('markdown', 'Hellooo world! Helloooooo again!\n\n');+ await moment();- expect(result.success).toBe(true);- expect(documentState.root.children[0].children).toHaveLength(3);- const newRow = documentState.root.children[0].children[2];- expect(newRow.type).toBe('tablerow');- expect(newRow.children[0].children[0].text).toBe('New 1');+ const result = await runtime.replaceText({+ searchText: 'Hello+',+ newText: 'Hi',+ useRegex: true,});+ await moment();- it('should insert a row before a reference row', async () => {- const result = await runtime.insertTableRow({- cells: ['Inserted 1', 'Inserted 2', 'Inserted 3'],- position: 'before',- referenceRowId: 'node_0_1',- tableId: 'node_0',- });+ expect(result.replacementCount).toBe(2);++ const markdown = editor.getDocument('markdown') as unknown as string;+ expect(markdown).toMatchSnapshot();+ });- expect(result.success).toBe(true);- expect(documentState.root.children[0].children).toHaveLength(3);- const insertedRow = documentState.root.children[0].children[1];- expect(insertedRow.children[0].children[0].text).toBe('Inserted 1');+ it('should support regex with alternation', async () => {+ const result = await runtime.replaceText({+ searchText: 'Hello|world',+ newText: 'X',+ useRegex: true,});+ await moment();- it('should insert a row with empty cells if no content provided', async () => {- const result = await runtime.insertTableRow({- tableId: 'node_0',- });+ expect(result.replacementCount).toBe(4);- expect(result.success).toBe(true);- const newRow = documentState.root.children[0].children[2];- expect(newRow.children).toHaveLength(3);- expect(newRow.children[0].children).toHaveLength(0);- });+ const markdown = editor.getDocument('markdown') as unknown as string;+ expect(markdown).toMatchSnapshot();});- describe('insertTableColumn', () => {- it('should insert a column at specified index', async () => {- const result = await runtime.insertTableColumn({- cells: ['Header 4', 'Cell 4'],- columnIndex: 1,- tableId: 'node_0',- });-- expect(result.success).toBe(true);- expect(documentState.root.children[0].children[0].children).toHaveLength(4);- expect(documentState.root.children[0].children[0].children[1].children[0].text).toBe(- 'Header 4',- );- expect(documentState.root.children[0].children[1].children[1].children[0].text).toBe(- 'Cell 4',- );+ it('should support regex first occurrence only', async () => {+ const result = await runtime.replaceText({+ searchText: 'Hello|world',+ newText: 'X',+ useRegex: true,+ replaceAll: false,});+ await moment();- it('should insert a column at the end with index -1', async () => {- const result = await runtime.insertTableColumn({- cells: ['Header 4', 'Cell 4'],- columnIndex: -1,- tableId: 'node_0',- });+ expect(result.replacementCount).toBe(1);++ const markdown = editor.getDocument('markdown') as unknown as string;+ expect(markdown).toMatchSnapshot();+ });- expect(result.success).toBe(true);- expect(documentState.root.children[0].children[0].children).toHaveLength(4);- const lastCell = documentState.root.children[0].children[0].children[3];- expect(lastCell.children[0].text).toBe('Header 4');+ it('should return zero replacements when no match found', async () => {+ const result = await runtime.replaceText({+ searchText: 'nonexistent',+ newText: 'replacement',});++ expect(result.replacementCount).toBe(0);+ expect(result.modifiedNodeIds).toEqual([]);});- describe('deleteTableRow', () => {- it('should delete a row by ID', async () => {- const result = await runtime.deleteTableRow({- rowId: 'node_0_1',- });+ it('should throw error for invalid regex pattern', async () => {+ await expect(+ runtime.replaceText({+ searchText: '[invalid',+ newText: 'replacement',+ useRegex: true,+ }),+ ).rejects.toThrow('Invalid regex pattern');+ });- expect(result.success).toBe(true);- expect(documentState.root.children[0].children).toHaveLength(1);- expect(documentState.root.children[0].children[0].children[0].children[0].text).toBe(- 'Header 1',- );- });+ it('should replace within specific nodes when nodeIds provided', async () => {+ const xml = editor.getDocument('litexml') as unknown as string;+ const nodeIdMatch = /<p id="([^"]+)"/.exec(xml);- it('should fail when row ID is invalid', async () => {- const result = await runtime.deleteTableRow({- rowId: 'node_0_99',+ if (nodeIdMatch) {+ const result = await runtime.replaceText({+ searchText: 'world',+ newText: 'universe',+ nodeIds: [nodeIdMatch[1]],});+ await moment();- expect(result.success).toBe(false);- expect(result.content).toContain('not found');- });+ // Should only replace in specified node+ expect(result.modifiedNodeIds.length).toBeLessThanOrEqual(1);+ }});+ });- describe('deleteTableColumn', () => {- it('should delete a column at specified index', async () => {- const result = await runtime.deleteTableColumn({- columnIndex: 1,- tableId: 'node_0',- });+ describe('document ID management', () => {+ it('should set and get current document ID', () => {+ runtime.setCurrentDocId('doc-123');+ expect(runtime.getCurrentDocId()).toBe('doc-123');+ });- expect(result.success).toBe(true);- expect(documentState.root.children[0].children[0].children).toHaveLength(2);- expect(documentState.root.children[0].children[0].children[0].children[0].text).toBe(- 'Header 1',- );- expect(documentState.root.children[0].children[0].children[1].children[0].text).toBe(- 'Header 3',- );- });+ it('should return undefined when no document ID is set', () => {+ const newRuntime = new PageAgentExecutionRuntime();+ expect(newRuntime.getCurrentDocId()).toBeUndefined();+ });- it('should fail when table not found', async () => {- const result = await runtime.deleteTableColumn({- columnIndex: 0,- tableId: 'node_99',- });+ it('should include document ID in getPageContent result', async () => {+ runtime.setCurrentDocId('my-doc-id');+ await runtime.initPage({ markdown: 'Test content' });+ await moment();- expect(result.success).toBe(false);- expect(result.content).toContain('not found');- });+ const result = await runtime.getPageContent({ format: 'markdown' });+ expect(result.documentId).toBe('my-doc-id');+ });+ });++ describe('getPageContentContext', () => {+ beforeEach(async () => {+ await runtime.initPage({ markdown: 'Test content for context' });+ await moment();+ });++ it('should return context with markdown only', () => {+ const context = runtime.getPageContentContext('markdown');++ expect(context.markdown).toBeDefined();+ expect(context.xml).toBeUndefined();+ expect(context.metadata.title).toBe('Test Title');+ });++ it('should return context with xml only', () => {+ const context = runtime.getPageContentContext('xml');++ expect(context.xml).toBeDefined();+ expect(context.markdown).toBeUndefined();+ });++ it('should return context with both formats', () => {+ const context = runtime.getPageContentContext('both');++ expect(context.markdown).toBeDefined();+ expect(context.xml).toBeDefined();+ expect(context.metadata.charCount).toBeGreaterThan(0);+ expect(context.metadata.lineCount).toBeGreaterThan(0);+ });++ it('should default to both formats', () => {+ const context = runtime.getPageContentContext();++ expect(context.markdown).toBeDefined();+ expect(context.xml).toBeDefined();});});});diff --git a/packages/builtin-tool-page-agent/src/ExecutionRuntime/index.ts b/packages/builtin-tool-page-agent/src/ExecutionRuntime/index.tsindex 2281c666311..1a8a2db9f55 100644--- a/packages/builtin-tool-page-agent/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-page-agent/src/ExecutionRuntime/index.ts@@ -1,84 +1,19 @@-/* eslint-disable @typescript-eslint/no-unused-vars */-import { PageContentContext, formatPageContentContext } from '@lobechat/prompts';-import { BuiltinServerRuntimeOutput } from '@lobechat/types';-import {- IEditor,- LITEXML_APPLY_COMMAND,- LITEXML_INSERT_COMMAND,- LITEXML_MODIFY_COMMAND,- LITEXML_REMOVE_COMMAND,-} from '@lobehub/editor';+import { type PageContentContext } from '@lobechat/prompts';+import { type IEditor, LITEXML_APPLY_COMMAND, LITEXML_MODIFY_COMMAND } from '@lobehub/editor';import debug from 'debug';import type {- BatchUpdateArgs,- CompareSnapshotsArgs,- CompareSnapshotsState,- ConvertToListArgs,- ConvertToListState,- CreateNodeArgs,- CreateNodeState,- CropImageArgs,- CropImageState,- DeleteNodeArgs,- DeleteNodeState,- DeleteSnapshotArgs,- DeleteSnapshotState,- DeleteTableColumnArgs,- DeleteTableColumnState,- DeleteTableRowArgs,- DeleteTableRowState,- DuplicateNodeArgs,- DuplicateNodeState,EditTitleArgs,- EditTitleState,+ EditTitleRuntimeResult,GetPageContentArgs,- GetPageContentState,- IndentListItemArgs,- IndentListItemState,+ GetPageContentRuntimeResult,InitDocumentArgs,- InitDocumentState,- InsertTableColumnArgs,- InsertTableColumnState,- InsertTableRowArgs,- InsertTableRowState,- ListSnapshotsArgs,- ListSnapshotsState,- MergeNodesArgs,- MergeNodesState,+ InitPageRuntimeResult,ModifyNodesArgs,- ModifyNodesState,+ ModifyNodesRuntimeResult,ModifyOperationResult,- MoveNodeArgs,- MoveNodeState,- NodeCreate,- NodeCreateResult,- NodeUpdate,- NodeUpdateResult,- OutdentListItemArgs,- OutdentListItemState,ReplaceTextArgs,- ReplaceTextState,- ResizeImageArgs,- ResizeImageState,- RestoreSnapshotArgs,- RestoreSnapshotState,- RotateImageArgs,- RotateImageState,- SaveSnapshotArgs,- SaveSnapshotState,- SetImageAltArgs,- SetImageAltState,- SplitNodeArgs,- SplitNodeState,- ToggleListTypeArgs,- ToggleListTypeState,- UnwrapNodeArgs,- UnwrapNodeState,- UpdateNodeArgs,- UpdateNodeState,- WrapNodesArgs,- WrapNodesState,+ ReplaceTextRuntimeResult,} from '../types';const log = debug('page:page-agent');@@ -148,119 +83,71 @@ export class PageAgentExecutionRuntime {// ==================== Initialize ====================/**- * Replace the content from Markdown+ * Initialize document from Markdown content+ * @returns Raw result with nodeCount and extractedTitle*/- async initPage(args: InitDocumentArgs): Promise<BuiltinServerRuntimeOutput> {- try {- const editor = this.getEditor();-- let markdown = args.markdown;- let extractedTitle: string | undefined;-- // Check if markdown starts with a # title heading- const titleMatch = /^#\s+(.+?)(?:\r?\n|$)/.exec(markdown);- if (titleMatch) {- extractedTitle = titleMatch[1].trim();- // Remove the title line from markdown- markdown = markdown.slice(titleMatch[0].length).trimStart();-- // Set the title separately if title handlers are available- if (this.titleSetter) {- this.titleSetter(extractedTitle);- }- }+ async initPage(args: InitDocumentArgs): Promise<InitPageRuntimeResult> {+ const editor = this.getEditor();- // Set markdown content directly - the editor will convert it internally- editor.setDocument('markdown', markdown);-- // Get the resulting document to count nodes- const jsonState = editor.getDocument('json') as any;- const nodeCount = jsonState?.children?.length || 0;-- const titleInfo = extractedTitle- ? ` Title "${extractedTitle}" was extracted and set separately.`- : '';-- return {- content: `Successfully initialized document with ${nodeCount} top-level nodes from ${args.markdown.length} characters of markdown content.${titleInfo}`,- state: {- nodeCount,- rootId: 'root',- } as InitDocumentState,- success: true,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to initialize document: ${err.message}`,- error,- success: false,- };+ let markdown = args.markdown;+ let extractedTitle: string | undefined;++ // Check if markdown starts with a # title heading+ const titleMatch = /^#\s+(.+?)(?:\r?\n|$)/.exec(markdown);+ if (titleMatch) {+ extractedTitle = titleMatch[1].trim();+ // Remove the title line from markdown+ markdown = markdown.slice(titleMatch[0].length).trimStart();++ // Set the title separately if title handlers are available+ if (this.titleSetter) {+ this.titleSetter(extractedTitle);+ }}++ // Set markdown content directly - the editor will convert it internally+ editor.setDocument('markdown', markdown);++ // Get the resulting document to count nodes+ const jsonState = editor.getDocument('json') as any;+ const nodeCount = jsonState?.children?.length || 0;++ return { extractedTitle, nodeCount };}// ==================== Metadata ====================/*** Edit the page title+ * @returns Raw result with newTitle and previousTitle*/- async editTitle(args: EditTitleArgs): Promise<BuiltinServerRuntimeOutput> {- try {- const { setter, getter } = this.getTitleHandlers();- const previousTitle = getter();-- // Update the title- setter(args.title);-- return {- content: `Successfully updated document title from "${previousTitle}" to "${args.title}".`,- state: {- newTitle: args.title,- previousTitle,- } as EditTitleState,- success: true,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to update document title: ${err.message}`,- error,- success: false,- };- }+ async editTitle(args: EditTitleArgs): Promise<EditTitleRuntimeResult> {+ const { setter, getter } = this.getTitleHandlers();+ const previousTitle = getter();++ // Update the title+ setter(args.title);++ return { newTitle: args.title, previousTitle };}// ==================== Query & Read ====================/*** Get the current page content and metadata+ * @returns Raw result with document content and metadata*/- async getPageContent(args: GetPageContentArgs): Promise<BuiltinServerRuntimeOutput> {- try {- const context = this.getPageContentContext(args.format);-- return {- content: formatPageContentContext(context),- state: {- documentId: this.currentDocId || 'current',- markdown: context.markdown,- metadata: {- title: context.metadata.title,- totalCharCount: context.metadata.charCount,- totalLineCount: context.metadata.lineCount,- },- xml: context.xml,- } as GetPageContentState,- success: true,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to get page content: ${err.message}`,- error,- success: false,- };- }+ async getPageContent(args: GetPageContentArgs): Promise<GetPageContentRuntimeResult> {+ const context = this.getPageContentContext(args.format);++ return {+ charCount: context.metadata.charCount,+ documentId: this.currentDocId || 'current',+ lineCount: context.metadata.lineCount,+ markdown: context.markdown,+ title: context.metadata.title,+ xml: context.xml,+ };}/**@@ -294,792 +181,95 @@ export class PageAgentExecutionRuntime {return context;}- // ==================== Helper Methods ====================-- /**- * Find a node in the Lexical JSON structure by its Lexical key- * @param root - The root node to search from- * @param key - The Lexical key (e.g., "9p5r")- * @returns The found node or null- */- private findNodeByKey(node: any, key: string): any {- if (!node) return null;-- // Check if this node has the key we're looking for- if (node.key === key) {- return node;- }-- // Recursively search children- if (node.children && Array.isArray(node.children)) {- for (const child of node.children) {- const found = this.findNodeByKey(child, key);- if (found) return found;- }- }-- return null;- }-- /**- * Find a node in XML string by its id attribute- * @param xml - The XML string to search- * @param nodeId - The id attribute value to find- * @returns Object with tag name and content, or null if not found- */- private findNodeInXML(xml: string, nodeId: string): { content: string; tagName: string } | null {- if (!xml || !nodeId) return null;-- // Match the element with the given id- // Pattern: <tagName id="nodeId" ...>content</tagName> or self-closing <tagName id="nodeId" ... />- const escapedId = nodeId.replaceAll(/[$()*+.?[\\\]^{|}]/g, '\\$&');-- // First try to match a full element with opening and closing tags- const fullElementRegex = new RegExp(- `<(\\w+)\\s+[^>]*id="${escapedId}"[^>]*>([\\s\\S]*?)<\\/\\1>`,- 'i',- );- const fullMatch = fullElementRegex.exec(xml);-- if (fullMatch) {- return {- content: fullMatch[2],- tagName: fullMatch[1],- };- }-- // Try self-closing tag- const selfClosingRegex = new RegExp(`<(\\w+)\\s+[^>]*id="${escapedId}"[^>]*/\\s*>`, 'i');- const selfClosingMatch = selfClosingRegex.exec(xml);-- if (selfClosingMatch) {- return {- content: '',- tagName: selfClosingMatch[1],- };- }-- return null;- }-- /**- * Find parent node and index of a child node by its key- * Returns { parent, index } or null if not found- */- private findParentAndIndex(- node: any,- targetKey: string,- parent: any = null,- index: number = -1,- ): { index: number; parent: any } | null {- if (!node) return null;-- // Check if this node has the key we're looking for- if (node.key === targetKey) {- return { index, parent };- }-- // Recursively search children- if (node.children && Array.isArray(node.children)) {- for (let i = 0; i < node.children.length; i++) {- const found = this.findParentAndIndex(node.children[i], targetKey, node, i);- if (found) return found;- }- }-- return null;- }-- /**- * Parse simple XML to Lexical nodes (for table structures)- */- private parseSimpleXmlToLexical(xml: string): any[] {- const result: any[] = [];-- // Simple regex-based XML parsing for table structures- // Match tags like <tr>, <td>, <th>, etc.- const tagRegex = /<(\w+)[^>]*>([\S\s]*?)<\/\1>|<(\w+)[^>]*\/>/g;- let match;-- while ((match = tagRegex.exec(xml)) !== null) {- const tagName = match[1] || match[3];- const innerContent = match[2] || '';-- // Skip thead and tbody wrappers - Lexical tables don't use these- if (tagName === 'thead' || tagName === 'tbody') {- // Just parse their children directly- const children = this.parseSimpleXmlToLexical(innerContent);- result.push(...children);- continue;- }-- const node: any = {- type: this.mapNodeTypeToLexical(tagName),- };-- // Recursively parse inner content if it contains more tags- if (innerContent && /<\w+/.test(innerContent)) {- node.children = this.parseSimpleXmlToLexical(innerContent);- } else if (innerContent.trim()) {- // Plain text content- node.children = [{ text: innerContent.trim(), type: 'text' }];- } else {- // Empty node- node.children = [];- }-- result.push(node);- }-- return result;- }-- /**- * Create a Lexical node structure from parameters- */- private createLexicalNode(args: NodeCreate): any {- const lexicalType = this.mapNodeTypeToLexical(args.type);-- // Handle text nodes specially- if (lexicalType === 'text' || args.type === 'span') {- return {- text: args.content || '',- type: 'text',- ...args.attributes,- };- }-- const node: any = {- type: lexicalType,- };-- // Add type-specific properties- if (/^h[1-6]$/.test(args.type)) {- node.tag = args.type;- }-- // Add content- if (args.content) {- node.children = [- {- text: args.content,- type: 'text',- },- ];- }-- // Parse and add children if provided- if (args.children) {- // For tables and complex structures, parse XML- if (lexicalType === 'table' || /<(tr|td|th|thead|tbody)/.test(args.children)) {- const parsedChildren = this.parseSimpleXmlToLexical(args.children);- if (parsedChildren.length > 0) {- node.children = parsedChildren;- }- } else {- // For simple cases, store as text- node.children = [- {- text: args.children,- type: 'text',- },- ];- }- }-- // Add attributes (stored in Lexical-specific fields)- if (args.attributes) {- Object.assign(node, args.attributes);- }-- return node;- }-- /**- * Map XML node types to Lexical node types- */- private mapNodeTypeToLexical(type: string): string {- const mapping: Record<string, string> = {- a: 'link',- blockquote: 'quote',- code: 'code',- h1: 'heading',- h2: 'heading',- h3: 'heading',- h4: 'heading',- h5: 'heading',- h6: 'heading',- img: 'image',- li: 'listitem',- ol: 'list',- p: 'paragraph',- pre: 'code',- span: 'text',- table: 'table',- tbody: 'tablebody',- td: 'tablecell',- th: 'tablecell',- thead: 'tablehead',- tr: 'tablerow',- ul: 'list',- };-- return mapping[type] || type;- }-- // ==================== Basic CRUD ====================-- /**- * Build LiteXML and command payload for a single node creation- */- private buildNodeCreatePayload(nodeCreate: NodeCreate): {- commandPayload: { afterId: string; litexml: string } | { beforeId: string; litexml: string };- litexml: string;- } {- const nodeType = nodeCreate.type;- let content = '';-- if (nodeCreate.content) {- // For text content, wrap in span- content = `<span>${nodeCreate.content}</span>`;- } else if (nodeCreate.children) {- content = nodeCreate.children;- }-- // Build attributes string- let attributesStr = '';- if (nodeCreate.attributes) {- for (const [key, value] of Object.entries(nodeCreate.attributes)) {- if (value !== null && value !== undefined) {- attributesStr += ` ${key}="${value}"`;- }- }- }-- const litexml = `<${nodeType}${attributesStr}>${content}</${nodeType}>`;-- // Use LITEXML_INSERT_COMMAND to insert the node- // The command expects either { beforeId, litexml } or { afterId, litexml }- const position = nodeCreate.position || 'after';- const referenceId = nodeCreate.referenceNodeId || 'root';-- const commandPayload =- position === 'before'- ? { beforeId: referenceId, litexml }- : { afterId: referenceId, litexml };-- return { commandPayload, litexml };- }-- /**- * Create one or multiple nodes in the document.- * Supports two modes:- * 1. Single node: args contains type, content, etc. directly- * 2. Multiple nodes: args contains nodes array with NodeCreate objects- */- async createNode(args: CreateNodeArgs): Promise<BuiltinServerRuntimeOutput> {- try {- const editor = this.getEditor();-- // Normalize input to always work with an array of nodes- const isMultiNodeCreate =- 'nodes' in args && Array.isArray((args as { nodes: NodeCreate[] }).nodes);- const nodeCreates: NodeCreate[] = isMultiNodeCreate- ? (args as { nodes: NodeCreate[] }).nodes- : [args as NodeCreate];-- log(- 'Creating nodes:',- nodeCreates.map((n) => n.type),- );-- const results: NodeCreateResult[] = [];- const createdNodeIds: string[] = [];- const errors: string[] = [];-- // Process each node creation- for (const nodeCreate of nodeCreates) {- try {- const { commandPayload, litexml } = this.buildNodeCreatePayload(nodeCreate);-- log('Generated LiteXML for', nodeCreate.type, ':', litexml);-- const success = editor.dispatchCommand(LITEXML_INSERT_COMMAND, commandPayload);-- log('Command dispatched, success:', success);-- // Node ID will be assigned by the editor, we track it as 'pending'- const createdNodeId = 'pending';- createdNodeIds.push(createdNodeId);-- results.push({- content: nodeCreate.content ?? nodeCreate.children,- createdNodeId,- success: true,- type: nodeCreate.type,- });- } catch (error) {- const err = error as Error;- log('Error creating node:', nodeCreate.type, err.message);- errors.push(`${nodeCreate.type}: ${err.message}`);-- results.push({- createdNodeId: '',- success: false,- type: nodeCreate.type,- });- }- }-- // Build response message- const successCount = results.filter((r) => r.success).length;- const nodesSummary =- nodeCreates.length === 1- ? `${nodeCreates[0].type} node`- : `${successCount} nodes (${nodeCreates.map((n) => n.type).join(', ')})`;-- let content = `Successfully created ${nodesSummary}.`;- if (errors.length > 0) {- content += ` Errors: ${errors.join('; ')}`;- }-- // Return state with detailed results and backward compatibility- const state: CreateNodeState = {- createdNodeId: createdNodeIds.length === 1 ? createdNodeIds[0] : undefined,- createdNodeIds,- results,- };-- return {- content,- state,- success: successCount > 0,- };- } catch (error) {- const err = error as Error;- console.error('[createNode] Error:', err.message, err.stack);- return {- content: `Failed to create node: ${err.message}`,- error,- success: false,- };- }- }+ // ==================== Unified Node Operations ====================/**- * Build LiteXML for a single node update+ * Unified node operations API using LITEXML_MODIFY_COMMAND.+ * Supports insert, modify, and remove operations in a single call.+ * @returns Raw result with results, successCount and totalCount*/- private buildNodeUpdateLiteXML(- nodeUpdate: NodeUpdate,- pageXML: string,- ): { litexml: string; updates: string[] } | { error: string } {- const xmlNode = this.findNodeInXML(pageXML, nodeUpdate.nodeId);-- if (!xmlNode) {- return { error: `Node ${nodeUpdate.nodeId} not found` };- }-- const nodeType = xmlNode.tagName;- const updates: string[] = [];-- // Start building the XML tag- let attributes = `id="${nodeUpdate.nodeId}"`;+ async modifyNodes(args: ModifyNodesArgs): Promise<ModifyNodesRuntimeResult> {+ const editor = this.getEditor();+ let { operations } = args;- // Add or update attributes- if (nodeUpdate.attributes) {- for (const [key, value] of Object.entries(nodeUpdate.attributes)) {- if (value !== null) {- attributes += ` ${key}="${value}"`;- updates.push(`set attribute ${key}`);- }- }+ // Normalize operations to always be an array+ // Handle case where LLM sends a single operation object instead of array+ if (!operations) {+ throw new Error('No operations provided');}- // Build content- let content = '';- if (nodeUpdate.content !== undefined) {- content = nodeUpdate.content;- updates.push('content');- } else if (nodeUpdate.children !== undefined) {- content = nodeUpdate.children;- updates.push('children');- } else {- // Keep existing content from XML- content = xmlNode.content;+ if (!Array.isArray(operations)) {+ log('Converting single operation to array');+ operations = [operations as any];}- const litexml = `<${nodeType} ${attributes}>${content}</${nodeType}>`;+ log('Processing operations:', operations.length);- return { litexml, updates };- }+ // Build the command payload for LITEXML_MODIFY_COMMAND+ const commandPayload: Array<+ | { action: 'insert'; afterId: string; litexml: string }+ | { action: 'insert'; beforeId: string; litexml: string }+ | { action: 'modify'; litexml: string | string[] }+ | { action: 'remove'; id: string }+ > = [];- /**- * Update one or multiple nodes in the document.- * Supports two modes:- * 1. Single node: args contains `nodeId` with optional `content`, `children`, `attributes`- * 2. Multiple nodes: args contains `nodes` array with NodeUpdate objects- */- async updateNode(args: UpdateNodeArgs): Promise<BuiltinServerRuntimeOutput> {- try {- const editor = this.getEditor();+ const results: ModifyOperationResult[] = [];- // Normalize input to always work with an array of nodes- const isMultiNodeUpdate =- 'nodes' in args && Array.isArray((args as { nodes: NodeUpdate[] }).nodes);- const nodeUpdates: NodeUpdate[] = isMultiNodeUpdate- ? (args as { nodes: NodeUpdate[] }).nodes- : [args as NodeUpdate];-- log(- 'Attempting to update nodes:',- nodeUpdates.map((n) => n.nodeId),- );-- const pageXML = editor.getDocument('litexml') as unknown as string;- log('pageXML:', pageXML);-- const litexmlList: string[] = [];- const updatedNodeIds: string[] = [];- const allUpdates: string[] = [];- const errors: string[] = [];- const results: NodeUpdateResult[] = [];-- // Build LiteXML for each node update- for (const nodeUpdate of nodeUpdates) {- const result = this.buildNodeUpdateLiteXML(nodeUpdate, pageXML);-- if ('error' in result) {- console.error('[updateNode] Node not found:', nodeUpdate.nodeId);- errors.push(result.error);- // Track failed updates in results- results.push({- nodeId: nodeUpdate.nodeId,- success: false,- });- continue;- }-- log('Generated LiteXML for', nodeUpdate.nodeId, ':', result.litexml);- litexmlList.push(result.litexml);- updatedNodeIds.push(nodeUpdate.nodeId);- allUpdates.push(...result.updates);-- // Track successful updates with their new values- results.push({- attributes: nodeUpdate.attributes,- content: nodeUpdate.content ?? nodeUpdate.children,- nodeId: nodeUpdate.nodeId,- success: true,- });- }-- // If no valid nodes to update, return error- if (litexmlList.length === 0) {- throw new Error(errors.join('; '));- }-- // Dispatch all updates at once- const success = editor.dispatchCommand(LITEXML_APPLY_COMMAND, {- litexml: litexmlList,- });-- log('Command dispatched, success:', success);-- const updateSummary = allUpdates.length > 0 ? ` (${allUpdates.join(', ')})` : '';- const nodesSummary =- updatedNodeIds.length === 1- ? `node ${updatedNodeIds[0]}`- : `${updatedNodeIds.length} nodes (${updatedNodeIds.join(', ')})`;-- let content = `Successfully updated ${nodesSummary}${updateSummary}.`;- if (errors.length > 0) {- content += ` Warnings: ${errors.join('; ')}`;- }-- // Return state with detailed results and backward compatibility- const state: UpdateNodeState = {- results,- updatedNodeId: updatedNodeIds.length === 1 ? updatedNodeIds[0] : undefined,- updatedNodeIds,- };-- return {- content,- state,- success: true,- };- } catch (error) {- const err = error as Error;- console.error('[updateNode] Error:', err.message, err.stack);- return {- content: `Failed to update node: ${err.message}`,- error,- success: false,- };- }- }-- /**- * Convert Lexical node type back to XML tag name- */- private mapLexicalTypeToXML(lexicalType: string): string {- const mapping: Record<string, string> = {- code: 'code',- heading: 'h1', // Will need the tag property for h1-h6- image: 'img',- link: 'a',- list: 'ul', // Will need to check list type- listitem: 'li',- paragraph: 'p',- quote: 'blockquote',- table: 'table',- tablebody: 'tbody',- tablecell: 'td',- tablehead: 'thead',- tablerow: 'tr',- text: 'span',- };-- return mapping[lexicalType] || lexicalType;- }-- /**- * Convert node children to string representation- */- private stringifyNodeChildren(children: any[]): string {- if (!children || children.length === 0) return '';-- return children- .map((child) => {- if (child.type === 'text') {- return child.text || '';- }- // For other nodes, recursively stringify- const tag = this.mapLexicalTypeToXML(child.type);- const content = child.children ? this.stringifyNodeChildren(child.children) : '';- return `<${tag}>${content}</${tag}>`;- })- .join('');- }-- async deleteNode(args: DeleteNodeArgs): Promise<BuiltinServerRuntimeOutput> {- try {- const editor = this.getEditor();-- log('Deleting node:', args.nodeId);-- // First verify the node exists in the XML- const pageXML = editor.getDocument('litexml') as unknown as string;- const xmlNode = this.findNodeInXML(pageXML, args.nodeId);-- if (!xmlNode) {- console.error('[deleteNode] Node not found in XML:', args.nodeId);- throw new Error(`Node ${args.nodeId} not found`);- }-- log('Found node to delete:', xmlNode.tagName);-- // Use LITEXML_REMOVE_COMMAND to remove the node- const success = editor.dispatchCommand(LITEXML_REMOVE_COMMAND, {- id: args.nodeId,- });-- log('Command dispatched, success:', success);-- return {- content: `Successfully deleted ${xmlNode.tagName} node ${args.nodeId}.`,- state: { deletedNodeId: args.nodeId } as DeleteNodeState,- success: true,- };- } catch (error) {- const err = error as Error;- console.error('[deleteNode] Error:', err.message, err.stack);- return {- content: `Failed to delete node: ${err.message}`,- error,- success: false,- };- }- }-- // ==================== Unified Node Operations ====================-- /**- * Unified node operations API using LITEXML_MODIFY_COMMAND.- * Supports insert, modify, and remove operations in a single call.- */- async modifyNodes(args: ModifyNodesArgs): Promise<BuiltinServerRuntimeOutput> {- try {- const editor = this.getEditor();- let { operations } = args;-- // Normalize operations to always be an array- // Handle case where LLM sends a single operation object instead of array- if (!operations) {- throw new Error('No operations provided');- }-- if (!Array.isArray(operations)) {- log('Converting single operation to array');- operations = [operations as any];- }-- log('Processing operations:', operations.length);-- // Build the command payload for LITEXML_MODIFY_COMMAND- const commandPayload: Array<- | { action: 'insert'; afterId: string; litexml: string }- | { action: 'insert'; beforeId: string; litexml: string }- | { action: 'modify'; litexml: string | string[] }- | { action: 'remove'; id: string }- > = [];-- const results: ModifyOperationResult[] = [];-- for (const op of operations) {- try {- switch (op.action) {- case 'insert': {- if ('beforeId' in op) {- commandPayload.push({- action: 'insert',- beforeId: op.beforeId,- litexml: op.litexml,- });- } else if ('afterId' in op) {- commandPayload.push({- action: 'insert',- afterId: op.afterId,- litexml: op.litexml,- });- }- results.push({ action: 'insert', success: true });- break;- }-- case 'modify': {+ for (const op of operations) {+ try {+ switch (op.action) {+ case 'insert': {+ if ('beforeId' in op) {commandPayload.push({- action: 'modify',+ action: 'insert',+ beforeId: op.beforeId,litexml: op.litexml,});- results.push({ action: 'modify', success: true });- break;- }-- case 'remove': {+ } else if ('afterId' in op) {commandPayload.push({- action: 'remove',- id: op.id,+ action: 'insert',+ afterId: op.afterId,+ litexml: op.litexml,});- results.push({ action: 'remove', success: true });- break;}+ results.push({ action: 'insert', success: true });+ break;}- } catch (error) {- const err = error as Error;- console.error('[modifyNodes] Error processing operation:', op.action, err.message);- results.push({ action: op.action, error: err.message, success: false });- }- }-- // Dispatch all operations at once- log('Dispatching LITEXML_MODIFY_COMMAND with payload:', commandPayload);- const success = editor.dispatchCommand(LITEXML_MODIFY_COMMAND, commandPayload);- log('Command dispatched, success:', success);-- const successCount = results.filter((r) => r.success).length;- const totalCount = results.length;- // Build summary message- const actionSummary = operations.reduce(- (acc, op) => {- acc[op.action] = (acc[op.action] || 0) + 1;- return acc;- },- {} as Record<string, number>,- );-- const summaryParts = Object.entries(actionSummary).map(- ([action, count]) => `${count} ${action}${count > 1 ? 's' : ''}`,- );- const content = `Successfully executed ${summaryParts.join(', ')} (${successCount}/${totalCount} operations succeeded).`;-- const state: ModifyNodesState = {- results,- successCount,- totalCount,- };+ case 'modify': {+ commandPayload.push({+ action: 'modify',+ litexml: op.litexml,+ });+ results.push({ action: 'modify', success: true });+ break;+ }- return {- content,- state,- success: successCount > 0,- };- } catch (error) {- const err = error as Error;- console.error('[modifyNodes] Error:', err.message, err.stack);- return {- content: `Failed to modify nodes: ${err.message}`,- error,- success: false,- };+ case 'remove': {+ commandPayload.push({+ action: 'remove',+ id: op.id,+ });+ results.push({ action: 'remove', success: true });+ break;+ }+ }+ } catch (error) {+ const err = error as Error;+ console.error('[modifyNodes] Error processing operation:', op.action, err.message);+ results.push({ action: op.action, error: err.message, success: false });+ }}- }- async moveNode(args: MoveNodeArgs): Promise<BuiltinServerRuntimeOutput> {- try {- // TODO: Implement node move- return {- content: `Node move not yet implemented`,- state: { movedNodeId: args.nodeId, newPosition: '' } as MoveNodeState,- success: false,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to move node: ${err.message}`,- error,- success: false,- };- }- }+ // Dispatch all operations at once+ log('Dispatching LITEXML_MODIFY_COMMAND with payload:', commandPayload);+ const success = editor.dispatchCommand(LITEXML_MODIFY_COMMAND, commandPayload);+ log('Command dispatched, success:', success);- async duplicateNode(args: DuplicateNodeArgs): Promise<BuiltinServerRuntimeOutput> {- try {- // TODO: Implement node duplication- return {- content: `Node duplication not yet implemented`,- state: { newNodeId: '', originalNodeId: args.nodeId } as DuplicateNodeState,- success: false,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to duplicate node: ${err.message}`,- error,- success: false,- };- }- }+ const successCount = results.filter((r) => r.success).length;+ const totalCount = results.length;- // ==================== Batch Operations ====================-- async batchUpdate(args: BatchUpdateArgs): Promise<BuiltinServerRuntimeOutput> {- try {- // TODO: Implement batch update- return {- content: `Batch update not yet implemented`,- state: { updatedNodeIds: args.nodeIds } as any,- success: false,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to batch update: ${err.message}`,- error,- success: false,- };- }+ return { results, successCount, totalCount };}// ==================== Text Operations ====================@@ -1251,721 +441,116 @@ export class PageAgentExecutionRuntime {/*** Find and replace text across the document or within specific nodes+ * @returns Raw result with modifiedNodeIds and replacementCount*/- async replaceText(args: ReplaceTextArgs): Promise<BuiltinServerRuntimeOutput> {- try {- const editor = this.getEditor();- const { searchText, newText, useRegex = false, replaceAll = true, nodeIds } = args;-- log('Starting replacement:', {- newText,- nodeIds,- replaceAll,- searchText,- useRegex,- });-- // Get the current document as LiteXML- const pageXML = editor.getDocument('litexml') as unknown as string;-- if (!pageXML) {- throw new Error('Document is empty or not initialized');- }-- // Create search pattern- let searchPattern: RegExp | string;- if (useRegex) {- try {- searchPattern = new RegExp(searchText, replaceAll ? 'g' : '');- } catch {- throw new Error(`Invalid regex pattern: ${searchText}`);- }- } else {- searchPattern = searchText;- }-- // Extract nodes from LiteXML- const nodes = this.extractNodesFromLiteXML(pageXML);- log('Found nodes:', nodes.length);-- // Filter nodes if nodeIds is specified and non-empty- // Treat empty array as "search all nodes"- const hasNodeFilter = nodeIds && nodeIds.length > 0;- const targetNodes = hasNodeFilter ? nodes.filter((node) => nodeIds.includes(node.id)) : nodes;-- if (hasNodeFilter && targetNodes.length === 0) {- log(- '[replaceText] Node IDs requested:',- nodeIds,- 'Available IDs:',- nodes.map((n) => n.id),- );- throw new Error(`None of the specified nodes were found: ${nodeIds.join(', ')}`);- }-- // Track replacements- let totalReplacementCount = 0;- const modifiedNodeIds: string[] = [];- const litexmlUpdates: string[] = [];-- // Process each target node- for (const node of targetNodes) {- // Check if the node content contains the search text- const hasMatch =- typeof searchPattern === 'string'- ? node.content.includes(searchPattern)- : searchPattern.test(node.content);-- if (!hasMatch) continue;-- // Reset regex lastIndex if using regex- if (searchPattern instanceof RegExp) {- searchPattern.lastIndex = 0;- }-- // Replace text in the node content- const { count, newContent } = this.replaceTextInContent(- node.content,- searchPattern,- newText,- replaceAll,- );-- if (count > 0) {- totalReplacementCount += count;- modifiedNodeIds.push(node.id);-- // Build the updated LiteXML for this node- // Extract attributes from the original fullMatch- const attrMatch = /<\w+\s+([^>]*)>/.exec(node.fullMatch);- const attributes = attrMatch ? attrMatch[1] : `id="${node.id}"`;-- const updatedLitexml = `<${node.tagName} ${attributes}>${newContent}</${node.tagName}>`;- litexmlUpdates.push(updatedLitexml);-- log('Updated node:', node.id, 'count:', count);-- // If not replacing all, stop after first replacement- if (!replaceAll) {- break;- }- }- }-- // Apply updates if any replacements were made- if (litexmlUpdates.length > 0) {- log('Applying updates:', litexmlUpdates.length);- const success = editor.dispatchCommand(LITEXML_APPLY_COMMAND, {- litexml: litexmlUpdates,- });- log('Command dispatched, success:', success);- }-- // Build response message- const scopeDescription = nodeIds- ? `within ${nodeIds.length} specified node(s)`- : 'across the document';-- const content =- totalReplacementCount > 0- ? `Successfully replaced ${totalReplacementCount} occurrence(s) of "${searchText}" with "${newText}" ${scopeDescription}. Modified ${modifiedNodeIds.length} node(s).`- : `No occurrences of "${searchText}" found ${scopeDescription}.`;-- const state: ReplaceTextState = {- modifiedNodeIds,- replacementCount: totalReplacementCount,- };-- return {- content,- state,- success: true,- };- } catch (error) {- const err = error as Error;- console.error('[replaceText] Error:', err.message, err.stack);- return {- content: `Failed to replace text: ${err.message}`,- error,- success: false,- };- }- }+ async replaceText(args: ReplaceTextArgs): Promise<ReplaceTextRuntimeResult> {+ const editor = this.getEditor();+ const { searchText, newText, useRegex = false, replaceAll = true, nodeIds } = args;- // ==================== Structure Operations ====================-- async mergeNodes(_args: MergeNodesArgs): Promise<BuiltinServerRuntimeOutput> {- try {- // TODO: Implement node merging- return {- content: `Node merging not yet implemented`,- state: { mergedNodeId: '', removedNodeIds: [] } as MergeNodesState,- success: false,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to merge nodes: ${err.message}`,- error,- success: false,- };- }- }+ log('Starting replacement:', {+ newText,+ nodeIds,+ replaceAll,+ searchText,+ useRegex,+ });- async splitNode(args: SplitNodeArgs): Promise<BuiltinServerRuntimeOutput> {- try {- // TODO: Implement node splitting- return {- content: `Node splitting not yet implemented`,- state: { newNodeIds: ['', ''], originalNodeId: args.nodeId } as SplitNodeState,- success: false,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to split node: ${err.message}`,- error,- success: false,- };- }- }+ // Get the current document as LiteXML+ const pageXML = editor.getDocument('litexml') as unknown as string;- async unwrapNode(args: UnwrapNodeArgs): Promise<BuiltinServerRuntimeOutput> {- try {- // TODO: Implement node unwrapping- return {- content: `Node unwrapping not yet implemented`,- state: { childNodeIds: [], removedNodeId: args.nodeId } as UnwrapNodeState,- success: false,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to unwrap node: ${err.message}`,- error,- success: false,- };+ if (!pageXML) {+ throw new Error('Document is empty or not initialized');}- }- async wrapNodes(args: WrapNodesArgs): Promise<BuiltinServerRuntimeOutput> {- try {- // TODO: Implement node wrapping- return {- content: `Node wrapping not yet implemented`,- state: { wrappedNodeIds: args.nodeIds, wrapperNodeId: '' } as WrapNodesState,- success: false,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to wrap nodes: ${err.message}`,- error,- success: false,- };+ // Create search pattern+ let searchPattern: RegExp | string;+ if (useRegex) {+ try {+ searchPattern = new RegExp(searchText, replaceAll ? 'g' : '');+ } catch {+ throw new Error(`Invalid regex pattern: ${searchText}`);+ }+ } else {+ searchPattern = searchText;}- }- // ==================== Table Operations ====================+ // Extract nodes from LiteXML+ const nodes = this.extractNodesFromLiteXML(pageXML);+ log('Found nodes:', nodes.length);- /**- * Helper: Create an empty table cell- */- private createTableCell(content?: string): any {- return {- children: content- ? [- {- text: content,- type: 'text',- },- ]- : [],- type: 'tablecell',- };- }+ // Filter nodes if nodeIds is specified and non-empty+ // Treat empty array as "search all nodes"+ const hasNodeFilter = nodeIds && nodeIds.length > 0;+ const targetNodes = hasNodeFilter ? nodes.filter((node) => nodeIds.includes(node.id)) : nodes;- /**- * Helper: Find table node by Lexical key- */- private findTableNode(docJson: any, tableId: string): any {- const table = this.findNodeByKey(docJson.root, tableId);-- if (!table || table.type !== 'table') {- throw new Error(`Table ${tableId} not found`);+ if (hasNodeFilter && targetNodes.length === 0) {+ log(+ '[replaceText] Node IDs requested:',+ nodeIds,+ 'Available IDs:',+ nodes.map((n) => n.id),+ );+ throw new Error(`None of the specified nodes were found: ${nodeIds.join(', ')}`);}- return table;- }-- async insertTableRow(args: InsertTableRowArgs): Promise<BuiltinServerRuntimeOutput> {- try {- const editor = this.getEditor();- const docJson = editor.getDocument('json') as any;-- if (!docJson || !docJson.root) {- throw new Error('Document not initialized');- }-- const table = this.findTableNode(docJson, args.tableId);-- // Determine column count from first row- const columnCount = table.children?.[0]?.children?.length || args.cells?.length || 3;-- // Create new row with cells- const newRow: any = {- children: [],- type: 'tablerow',- };-- // Create cells for the new row- for (let i = 0; i < columnCount; i++) {- const cellContent = args.cells?.[i] || '';- newRow.children.push(this.createTableCell(cellContent));- }-- // Insert the row at the specified position- if (!table.children) {- table.children = [];- }-- let insertIndex = table.children.length;-- if (args.referenceRowId) {- // Find the reference row within the table- const refIndex = table.children.findIndex((row: any) => row.key === args.referenceRowId);- if (refIndex !== -1) {- insertIndex = args.position === 'before' ? refIndex : refIndex + 1;- }- }+ // Track replacements+ let totalReplacementCount = 0;+ const modifiedNodeIds: string[] = [];+ const litexmlUpdates: string[] = [];- // Generate a unique key for the new row- newRow.key = `${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;-- table.children.splice(insertIndex, 0, newRow);-- // Update the document- editor.setDocument('json', JSON.stringify(docJson));-- return {- content: `Successfully inserted row with ${columnCount} cells into table ${args.tableId}.`,- state: { newRowId: newRow.key } as InsertTableRowState,- success: true,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to insert table row: ${err.message}`,- error,- success: false,- };- }- }+ // Process each target node+ for (const node of targetNodes) {+ // Check if the node content contains the search text+ const hasMatch =+ typeof searchPattern === 'string'+ ? node.content.includes(searchPattern)+ : searchPattern.test(node.content);- async insertTableColumn(args: InsertTableColumnArgs): Promise<BuiltinServerRuntimeOutput> {- try {- const editor = this.getEditor();- const docJson = editor.getDocument('json') as any;+ if (!hasMatch) continue;- if (!docJson || !docJson.root) {- throw new Error('Document not initialized');+ // Reset regex lastIndex if using regex+ if (searchPattern instanceof RegExp) {+ searchPattern.lastIndex = 0;}- const table = this.findTableNode(docJson, args.tableId);+ // Replace text in the node content+ const { count, newContent } = this.replaceTextInContent(+ node.content,+ searchPattern,+ newText,+ replaceAll,+ );- if (!table.children || table.children.length === 0) {- throw new Error('Table has no rows');- }+ if (count > 0) {+ totalReplacementCount += count;+ modifiedNodeIds.push(node.id);- const newCellIds: string[] = [];- const columnIndex =- args.columnIndex === -1 ? table.children[0].children.length : args.columnIndex;+ // Build the updated LiteXML for this node+ // Extract attributes from the original fullMatch+ const attrMatch = /<\w+\s+([^>]*)>/.exec(node.fullMatch);+ const attributes = attrMatch ? attrMatch[1] : `id="${node.id}"`;- // Add a cell to each row- table.children.forEach((row: any, rowIndex: number) => {- if (row.type !== 'tablerow') return;+ const updatedLitexml = `<${node.tagName} ${attributes}>${newContent}</${node.tagName}>`;+ litexmlUpdates.push(updatedLitexml);- if (!row.children) {- row.children = [];- }+ log('Updated node:', node.id, 'count:', count);- // Determine cell content- let cellContent = '';- if (rowIndex === 0 && args.headerContent) {- cellContent = args.headerContent;- } else if (args.cells && args.cells[rowIndex]) {- cellContent = args.cells[rowIndex];+ // If not replacing all, stop after first replacement+ if (!replaceAll) {+ break;}-- const newCell = this.createTableCell(cellContent);- // Generate a unique key for the new cell- newCell.key = `${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;- row.children.splice(columnIndex, 0, newCell);-- // Track the new cell key- newCellIds.push(newCell.key);- });-- // Update the document- editor.setDocument('json', JSON.stringify(docJson));-- return {- content: `Successfully inserted column at index ${columnIndex} in table ${args.tableId}.`,- state: { columnIndex, newCellIds } as InsertTableColumnState,- success: true,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to insert table column: ${err.message}`,- error,- success: false,- };- }- }-- async deleteTableRow(args: DeleteTableRowArgs): Promise<BuiltinServerRuntimeOutput> {- try {- const editor = this.getEditor();- const docJson = editor.getDocument('json') as any;-- if (!docJson || !docJson.root) {- throw new Error('Document not initialized');- }-- // Find the row by Lexical key and its parent- const result = this.findParentAndIndex(docJson.root, args.rowId);-- if (!result || !result.parent) {- throw new Error(`Row ${args.rowId} not found`);- }-- const { parent: table, index: rowIndex } = result;-- // Verify parent is a table- if (table.type !== 'table') {- throw new Error('Parent of row is not a table');}-- if (!table.children || !table.children[rowIndex]) {- throw new Error(`Row ${args.rowId} not found in table children`);- }-- // Remove the row- table.children.splice(rowIndex, 1);-- // Update the document- editor.setDocument('json', JSON.stringify(docJson));-- return {- content: `Successfully deleted row ${args.rowId} from table.`,- state: { deletedRowId: args.rowId } as DeleteTableRowState,- success: true,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to delete table row: ${err.message}`,- error,- success: false,- };}- }-- async deleteTableColumn(args: DeleteTableColumnArgs): Promise<BuiltinServerRuntimeOutput> {- try {- const editor = this.getEditor();- const docJson = editor.getDocument('json') as any;-- if (!docJson || !docJson.root) {- throw new Error('Document not initialized');- }-- const table = this.findTableNode(docJson, args.tableId);-- if (!table.children || table.children.length === 0) {- throw new Error('Table has no rows');- }-- const deletedCellIds: string[] = [];- // Remove the cell at columnIndex from each row- table.children.forEach((row: any) => {- if (row.type !== 'tablerow') return;-- if (!row.children || !row.children[args.columnIndex]) {- return;- }-- // Track the deleted cell key- const deletedCell = row.children[args.columnIndex];- if (deletedCell.key) {- deletedCellIds.push(deletedCell.key);- }-- // Remove the cell- row.children.splice(args.columnIndex, 1);+ // Apply updates if any replacements were made+ if (litexmlUpdates.length > 0) {+ log('Applying updates:', litexmlUpdates.length);+ const success = editor.dispatchCommand(LITEXML_APPLY_COMMAND, {+ litexml: litexmlUpdates,});-- // Update the document- editor.setDocument('json', JSON.stringify(docJson));-- return {- content: `Successfully deleted column at index ${args.columnIndex} from table ${args.tableId}.`,- state: { columnIndex: args.columnIndex, deletedCellIds } as DeleteTableColumnState,- success: true,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to delete table column: ${err.message}`,- error,- success: false,- };- }- }-- // ==================== Image Operations ====================-- async cropImage(args: CropImageArgs): Promise<BuiltinServerRuntimeOutput> {- try {- // TODO: Implement image cropping- return {- content: `Image cropping not yet implemented`,- state: { nodeId: args.nodeId } as CropImageState,- success: false,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to crop image: ${err.message}`,- error,- success: false,- };- }- }-- async resizeImage(args: ResizeImageArgs): Promise<BuiltinServerRuntimeOutput> {- try {- // TODO: Implement image resizing- return {- content: `Image resizing not yet implemented`,- state: { newHeight: 0, newWidth: 0, nodeId: args.nodeId } as ResizeImageState,- success: false,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to resize image: ${err.message}`,- error,- success: false,- };- }- }-- async rotateImage(args: RotateImageArgs): Promise<BuiltinServerRuntimeOutput> {- try {- // TODO: Implement image rotation- return {- content: `Image rotation not yet implemented`,- state: { newAngle: args.angle, nodeId: args.nodeId } as RotateImageState,- success: false,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to rotate image: ${err.message}`,- error,- success: false,- };- }- }-- async setImageAlt(args: SetImageAltArgs): Promise<BuiltinServerRuntimeOutput> {- try {- // TODO: Implement image alt text setting- return {- content: `Image alt text setting not yet implemented`,- state: { nodeId: args.nodeId } as SetImageAltState,- success: false,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to set image alt text: ${err.message}`,- error,- success: false,- };- }- }-- // ==================== List Operations ====================-- async convertToList(args: ConvertToListArgs): Promise<BuiltinServerRuntimeOutput> {- try {- // TODO: Implement list conversion- return {- content: `List conversion not yet implemented`,- state: { listId: '', nodeIds: args.nodeIds } as ConvertToListState,- success: false,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to convert to list: ${err.message}`,- error,- success: false,- };- }- }-- async indentListItem(args: IndentListItemArgs): Promise<BuiltinServerRuntimeOutput> {- try {- // TODO: Implement list item indentation- return {- content: `List item indentation not yet implemented`,- state: { newParentId: '', nodeId: args.nodeId } as IndentListItemState,- success: false,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to indent list item: ${err.message}`,- error,- success: false,- };- }- }-- async outdentListItem(args: OutdentListItemArgs): Promise<BuiltinServerRuntimeOutput> {- try {- // TODO: Implement list item outdentation- return {- content: `List item outdentation not yet implemented`,- state: { newParentId: '', nodeId: args.nodeId } as OutdentListItemState,- success: false,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to outdent list item: ${err.message}`,- error,- success: false,- };- }- }-- async toggleListType(args: ToggleListTypeArgs): Promise<BuiltinServerRuntimeOutput> {- try {- // TODO: Implement list type toggling- return {- content: `List type toggling not yet implemented`,- state: { listId: args.listId, newType: args.targetType } as ToggleListTypeState,- success: false,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to toggle list type: ${err.message}`,- error,- success: false,- };- }- }-- // ==================== Snapshot Operations ====================-- async compareSnapshots(_args: CompareSnapshotsArgs): Promise<BuiltinServerRuntimeOutput> {- try {- // TODO: Implement snapshot comparison- return {- content: `Snapshot comparison not yet implemented`,- state: {- additions: [],- deletions: [],- modifications: [],- } as CompareSnapshotsState,- success: false,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to compare snapshots: ${err.message}`,- error,- success: false,- };- }- }-- async deleteSnapshot(args: DeleteSnapshotArgs): Promise<BuiltinServerRuntimeOutput> {- try {- // TODO: Implement snapshot deletion- return {- content: `Snapshot deletion not yet implemented`,- state: { deletedSnapshotId: args.snapshotId } as DeleteSnapshotState,- success: false,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to delete snapshot: ${err.message}`,- error,- success: false,- };- }- }-- async listSnapshots(_args: ListSnapshotsArgs): Promise<BuiltinServerRuntimeOutput> {- try {- // TODO: Implement snapshot listing- return {- content: `Snapshot listing not yet implemented`,- state: { snapshots: [], total: 0 } as ListSnapshotsState,- success: false,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to list snapshots: ${err.message}`,- error,- success: false,- };- }- }-- async restoreSnapshot(args: RestoreSnapshotArgs): Promise<BuiltinServerRuntimeOutput> {- try {- // TODO: Implement snapshot restoration- return {- content: `Snapshot restoration not yet implemented`,- state: { restoredSnapshotId: args.snapshotId } as RestoreSnapshotState,- success: false,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to restore snapshot: ${err.message}`,- error,- success: false,- };+ log('Command dispatched, success:', success);}- }- async saveSnapshot(_args: SaveSnapshotArgs): Promise<BuiltinServerRuntimeOutput> {- try {- // TODO: Implement snapshot saving- return {- content: `Snapshot saving not yet implemented`,- state: { snapshotId: '' } as SaveSnapshotState,- success: false,- };- } catch (error) {- const err = error as Error;- return {- content: `Failed to save snapshot: ${err.message}`,- error,- success: false,- };- }+ return { modifiedNodeIds, replacementCount: totalReplacementCount };}}diff --git a/packages/builtin-tool-page-agent/src/client/Inspector/GetPageContent/index.tsx b/packages/builtin-tool-page-agent/src/client/Inspector/GetPageContent/index.tsxindex 4d1e93ca74f..32e0b8e9a87 100644--- a/packages/builtin-tool-page-agent/src/client/Inspector/GetPageContent/index.tsx+++ b/packages/builtin-tool-page-agent/src/client/Inspector/GetPageContent/index.tsx@@ -8,13 +8,14 @@ import { useTranslation } from 'react-i18next';import { shinyTextStyles } from '@/styles';const styles = createStaticStyles(({ css, cssVar }) => ({+ done: css`+ color: ${cssVar.colorTextDescription};+ `,root: css`overflow: hidden;display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 1;-- color: ${cssVar.colorTextDescription};`,}));@@ -22,7 +23,7 @@ export const GetPageContentInspector = memo<BuiltinInspectorProps>(({ isArgumentconst { t } = useTranslation('plugin');return (- <div className={cx(styles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}>+ <div className={cx(styles.root, isArgumentsStreaming ? shinyTextStyles.shinyText : styles.done)}><span>{t('builtins.lobe-page-agent.apiName.getPageContent')}</span></div>);diff --git a/packages/builtin-tool-page-agent/src/client/Inspector/InitPage/index.tsx b/packages/builtin-tool-page-agent/src/client/Inspector/InitPage/index.tsxindex c98f0310702..d45c545937d 100644--- a/packages/builtin-tool-page-agent/src/client/Inspector/InitPage/index.tsx+++ b/packages/builtin-tool-page-agent/src/client/Inspector/InitPage/index.tsx@@ -47,16 +47,41 @@ export const InitPageInspector = memo<BuiltinInspectorProps<InitDocumentArgs, Inconst hasContent = displayLines > 0 || chars > 0;// During streaming without content, show init- if (isArgumentsStreaming && !hasContent) {+ if (isArgumentsStreaming) {+ if (!hasContent)+ return (+ <div className={cx(styles.root, shinyTextStyles.shinyText)}>+ <span>{t('builtins.lobe-page-agent.apiName.initPage')}</span>+ </div>+ );++ // During streaming with content, show "creating" title with shiny effectreturn (- <div className={cx(styles.root, shinyTextStyles.shinyText)}>- <span>{t('builtins.lobe-page-agent.apiName.initPage')}</span>+ <div className={styles.root}>+ <span className={shinyTextStyles.shinyText}>+ {t('builtins.lobe-page-agent.apiName.initPage.creating')}+ </span>+ {displayLines > 0 && (+ <span className={styles.lines}>+ {' '}+ <Icon icon={Plus} size={12} />+ <AnimatedNumber value={displayLines} />+ {t('builtins.lobe-page-agent.apiName.initPage.lines')}+ </span>+ )}+ {chars > 0 && (+ <span className={styles.chars}>+ {' '}+ <AnimatedNumber value={chars} />+ {t('builtins.lobe-page-agent.apiName.initPage.chars')}+ </span>+ )}</div>);}return (- <div className={cx(styles.root, isArgumentsStreaming && shinyTextStyles.shinyText)}>+ <div className={styles.root}><span className={styles.title}>{t('builtins.lobe-page-agent.apiName.initPage.result')}</span>diff --git a/packages/builtin-tool-page-agent/src/executor/index.test.ts b/packages/builtin-tool-page-agent/src/executor/index.test.tsnew file mode 100644index 00000000000..55e4ae2b340--- /dev/null+++ b/packages/builtin-tool-page-agent/src/executor/index.test.ts@@ -0,0 +1,322 @@+import type { BuiltinToolContext } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { PageAgentExecutionRuntime } from '../ExecutionRuntime';+import { PageAgentIdentifier } from '../types';+import { PageAgentExecutor } from './index';++describe('PageAgentExecutor', () => {+ let executor: PageAgentExecutor;+ let mockRuntime: PageAgentExecutionRuntime;+ const mockContext = {} as BuiltinToolContext;++ beforeEach(() => {+ // Create mock runtime with all methods+ mockRuntime = {+ editTitle: vi.fn(),+ getPageContent: vi.fn(),+ initPage: vi.fn(),+ modifyNodes: vi.fn(),+ replaceText: vi.fn(),+ } as unknown as PageAgentExecutionRuntime;++ executor = new PageAgentExecutor(mockRuntime);+ });++ describe('constructor and basic properties', () => {+ it('should have correct identifier', () => {+ expect(executor.identifier).toBe(PageAgentIdentifier);+ });++ it('should have all API methods registered', () => {+ expect(executor.hasApi('initPage')).toBe(true);+ expect(executor.hasApi('editTitle')).toBe(true);+ expect(executor.hasApi('getPageContent')).toBe(true);+ expect(executor.hasApi('modifyNodes')).toBe(true);+ expect(executor.hasApi('replaceText')).toBe(true);+ });++ it('should return false for non-existent API', () => {+ expect(executor.hasApi('nonExistentApi')).toBe(false);+ });+ });++ describe('initPage', () => {+ it('should format result with extracted title', async () => {+ vi.mocked(mockRuntime.initPage).mockResolvedValue({+ extractedTitle: 'My Document',+ nodeCount: 5,+ });++ const result = await executor.initPage({ markdown: '# My Document\n\nContent' });++ expect(result.success).toBe(true);+ expect(result.content).toBe(+ 'Document initialized with 5 nodes. Title "My Document" extracted and set.',+ );+ expect(result.state).toEqual({+ nodeCount: 5,+ rootId: 'root',+ });+ });++ it('should format result without extracted title', async () => {+ vi.mocked(mockRuntime.initPage).mockResolvedValue({+ extractedTitle: undefined,+ nodeCount: 3,+ });++ const result = await executor.initPage({ markdown: 'Just content' });++ expect(result.success).toBe(true);+ expect(result.content).toBe('Document initialized with 3 nodes.');+ });++ it('should handle errors', async () => {+ vi.mocked(mockRuntime.initPage).mockRejectedValue(new Error('Editor not initialized'));++ const result = await executor.initPage({ markdown: 'content' });++ expect(result.success).toBe(false);+ expect(result.error?.message).toBe('Editor not initialized');+ expect(result.error?.type).toBe('PluginServerError');+ });+ });++ describe('editTitle', () => {+ it('should format title change result', async () => {+ vi.mocked(mockRuntime.editTitle).mockResolvedValue({+ newTitle: 'New Title',+ previousTitle: 'Old Title',+ });++ const result = await executor.editTitle({ title: 'New Title' });++ expect(result.success).toBe(true);+ expect(result.content).toBe('Title changed from "Old Title" to "New Title".');+ expect(result.state).toEqual({+ newTitle: 'New Title',+ previousTitle: 'Old Title',+ });+ });++ it('should handle errors', async () => {+ vi.mocked(mockRuntime.editTitle).mockRejectedValue(new Error('Title handlers not set'));++ const result = await executor.editTitle({ title: 'New Title' });++ expect(result.success).toBe(false);+ expect(result.error?.message).toBe('Title handlers not set');+ });+ });++ describe('getPageContent', () => {+ it('should format result with markdown content', async () => {+ vi.mocked(mockRuntime.getPageContent).mockResolvedValue({+ charCount: 100,+ documentId: 'doc-123',+ lineCount: 10,+ markdown: '# Title\n\nContent here',+ title: 'My Document',+ xml: undefined,+ });++ const result = await executor.getPageContent({ format: 'markdown' });++ expect(result.success).toBe(true);+ expect(result.content).toBe('# Title\n\nContent here');+ expect(result.state).toEqual({+ documentId: 'doc-123',+ markdown: '# Title\n\nContent here',+ metadata: {+ fileType: 'document',+ title: 'My Document',+ totalCharCount: 100,+ totalLineCount: 10,+ },+ xml: undefined,+ });+ });++ it('should format result with XML content', async () => {+ vi.mocked(mockRuntime.getPageContent).mockResolvedValue({+ charCount: 50,+ documentId: 'doc-123',+ lineCount: 5,+ markdown: undefined,+ title: 'My Document',+ xml: '<p id="1">Content</p>',+ });++ const result = await executor.getPageContent({ format: 'xml' });++ expect(result.success).toBe(true);+ expect(result.content).toBe('<p id="1">Content</p>');+ });++ it('should handle errors', async () => {+ vi.mocked(mockRuntime.getPageContent).mockRejectedValue(new Error('Editor not initialized'));++ const result = await executor.getPageContent({ format: 'both' });++ expect(result.success).toBe(false);+ expect(result.error?.message).toBe('Editor not initialized');+ });+ });++ describe('modifyNodes', () => {+ it('should format successful operations result', async () => {+ vi.mocked(mockRuntime.modifyNodes).mockResolvedValue({+ results: [+ { action: 'insert', success: true },+ { action: 'modify', success: true },+ { action: 'remove', success: true },+ ],+ successCount: 3,+ totalCount: 3,+ });++ const result = await executor.modifyNodes({+ operations: [+ { action: 'insert', afterId: 'node1', litexml: '<p>New</p>' },+ { action: 'modify', litexml: '<p id="node2">Updated</p>' },+ { action: 'remove', id: 'node3' },+ ],+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('1 insert');+ expect(result.content).toContain('1 modify');+ expect(result.content).toContain('1 remove');+ expect(result.content).toContain('3/3 operations succeeded');+ });++ it('should format partial success result', async () => {+ vi.mocked(mockRuntime.modifyNodes).mockResolvedValue({+ results: [+ { action: 'insert', success: true },+ { action: 'modify', error: 'Node not found', success: false },+ ],+ successCount: 1,+ totalCount: 2,+ });++ const result = await executor.modifyNodes({+ operations: [+ { action: 'insert', afterId: 'node1', litexml: '<p>New</p>' },+ { action: 'modify', litexml: '<p id="invalid">Updated</p>' },+ ],+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('1/2 operations succeeded');+ });++ it('should return success false when all operations fail', async () => {+ vi.mocked(mockRuntime.modifyNodes).mockResolvedValue({+ results: [{ action: 'modify', error: 'Node not found', success: false }],+ successCount: 0,+ totalCount: 1,+ });++ const result = await executor.modifyNodes({+ operations: [{ action: 'modify', litexml: '<p id="invalid">Updated</p>' }],+ });++ expect(result.success).toBe(false);+ });++ it('should handle errors', async () => {+ vi.mocked(mockRuntime.modifyNodes).mockRejectedValue(new Error('No operations provided'));++ const result = await executor.modifyNodes({ operations: [] });++ expect(result.success).toBe(false);+ expect(result.error?.message).toBe('No operations provided');+ });+ });++ describe('replaceText', () => {+ it('should format successful replacement result', async () => {+ vi.mocked(mockRuntime.replaceText).mockResolvedValue({+ modifiedNodeIds: ['node1', 'node2'],+ replacementCount: 5,+ });++ const result = await executor.replaceText({ newText: 'new', searchText: 'old' });++ expect(result.success).toBe(true);+ expect(result.content).toContain('Successfully replaced 5 occurrence(s)');+ expect(result.content).toContain('"old"');+ expect(result.content).toContain('"new"');+ expect(result.content).toContain('Modified 2 node(s)');+ expect(result.state).toEqual({+ modifiedNodeIds: ['node1', 'node2'],+ replacementCount: 5,+ });+ });++ it('should format result with nodeIds filter', async () => {+ vi.mocked(mockRuntime.replaceText).mockResolvedValue({+ modifiedNodeIds: ['node1'],+ replacementCount: 2,+ });++ const result = await executor.replaceText({+ newText: 'new',+ nodeIds: ['node1', 'node2'],+ searchText: 'old',+ });++ expect(result.content).toContain('within 2 specified node(s)');+ });++ it('should format no matches result', async () => {+ vi.mocked(mockRuntime.replaceText).mockResolvedValue({+ modifiedNodeIds: [],+ replacementCount: 0,+ });++ const result = await executor.replaceText({ newText: 'new', searchText: 'notfound' });++ expect(result.success).toBe(true);+ expect(result.content).toContain('No occurrences of "notfound" found');+ });++ it('should handle errors', async () => {+ vi.mocked(mockRuntime.replaceText).mockRejectedValue(+ new Error('Invalid regex pattern: [invalid'),+ );++ const result = await executor.replaceText({+ newText: 'new',+ searchText: '[invalid',+ useRegex: true,+ });++ expect(result.success).toBe(false);+ expect(result.error?.message).toContain('Invalid regex');+ });+ });++ describe('invoke method', () => {+ it('should invoke the correct method based on apiName', async () => {+ vi.mocked(mockRuntime.editTitle).mockResolvedValue({+ newTitle: 'New',+ previousTitle: 'Old',+ });++ const result = await executor.invoke('editTitle', { title: 'New' }, mockContext);++ expect(result.success).toBe(true);+ expect(mockRuntime.editTitle).toHaveBeenCalledWith({ title: 'New' });+ });++ it('should return error for unknown API', async () => {+ const result = await executor.invoke('unknownApi', {}, mockContext);++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('ApiNotFound');+ });+ });+});diff --git a/packages/builtin-tool-page-agent/src/executor/index.ts b/packages/builtin-tool-page-agent/src/executor/index.tsnew file mode 100644index 00000000000..f6963d709ea--- /dev/null+++ b/packages/builtin-tool-page-agent/src/executor/index.ts@@ -0,0 +1,247 @@+import { BaseExecutor, type BuiltinToolResult } from '@lobechat/types';++import { PageAgentExecutionRuntime } from '../ExecutionRuntime';+import type {+ EditTitleArgs,+ EditTitleState,+ GetPageContentArgs,+ GetPageContentState,+ InitDocumentArgs,+ InitDocumentState,+ ModifyNodesArgs,+ ModifyNodesState,+ ReplaceTextArgs,+ ReplaceTextState,+} from '../types';+import { PageAgentIdentifier } from '../types';++/**+ * API enum for Page Agent executor+ * Only includes APIs that are exposed in the manifest+ */+const PageAgentApiName = {+ // Document Metadata+ editTitle: 'editTitle',++ // Query & Read+ getPageContent: 'getPageContent',++ // Initialize+ initPage: 'initPage',++ // Unified Node Operations+ modifyNodes: 'modifyNodes',++ // Text Operations+ replaceText: 'replaceText',+} as const;++/**+ * Page Agent Executor+ *+ * Wraps the PageAgentExecutionRuntime to provide a unified executor interface+ * that follows the BaseExecutor pattern used by other builtin tools.+ *+ * Note: Page Agent is a client-side tool that directly manipulates the Lexical editor.+ * The runtime must be configured with an editor instance before use.+ */+class PageAgentExecutor extends BaseExecutor<typeof PageAgentApiName> {+ readonly identifier = PageAgentIdentifier;+ protected readonly apiEnum = PageAgentApiName;++ /**+ * The execution runtime instance+ * This is a singleton that should be configured with an editor instance externally+ */+ private runtime: PageAgentExecutionRuntime;++ constructor(runtime: PageAgentExecutionRuntime) {+ super();+ this.runtime = runtime;+ }++ // ==================== Initialize ====================++ /**+ * Initialize a new document from Markdown content+ */+ initPage = async (params: InitDocumentArgs): Promise<BuiltinToolResult> => {+ try {+ const result = await this.runtime.initPage(params);++ const content = result.extractedTitle+ ? `Document initialized with ${result.nodeCount} nodes. Title "${result.extractedTitle}" extracted and set.`+ : `Document initialized with ${result.nodeCount} nodes.`;++ const state: InitDocumentState = {+ nodeCount: result.nodeCount,+ rootId: 'root',+ };++ return { content, state, success: true };+ } catch (error) {+ const err = error as Error;+ return {+ error: {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ success: false,+ };+ }+ };++ // ==================== Document Metadata ====================++ /**+ * Edit the page title+ */+ editTitle = async (params: EditTitleArgs): Promise<BuiltinToolResult> => {+ try {+ const result = await this.runtime.editTitle(params);++ const content = `Title changed from "${result.previousTitle}" to "${result.newTitle}".`;++ const state: EditTitleState = {+ newTitle: result.newTitle,+ previousTitle: result.previousTitle,+ };++ return { content, state, success: true };+ } catch (error) {+ const err = error as Error;+ return {+ error: {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ success: false,+ };+ }+ };++ // ==================== Query & Read ====================++ /**+ * Get page content in XML, markdown, or both formats+ */+ getPageContent = async (params: GetPageContentArgs): Promise<BuiltinToolResult> => {+ try {+ const result = await this.runtime.getPageContent(params);++ const state: GetPageContentState = {+ documentId: result.documentId,+ markdown: result.markdown,+ metadata: {+ fileType: 'document',+ title: result.title,+ totalCharCount: result.charCount,+ totalLineCount: result.lineCount,+ },+ xml: result.xml,+ };++ // For getPageContent, the content IS the document content+ // We return the formatted content based on the requested format+ const content = result.markdown || result.xml || '';++ return { content, state, success: true };+ } catch (error) {+ const err = error as Error;+ return {+ error: {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ success: false,+ };+ }+ };++ // ==================== Unified Node Operations ====================++ /**+ * Perform unified node operations (insert, modify, remove)+ */+ modifyNodes = async (params: ModifyNodesArgs): Promise<BuiltinToolResult> => {+ try {+ const result = await this.runtime.modifyNodes(params);++ // Build summary message+ const actionSummary = params.operations.reduce(+ (acc, op) => {+ acc[op.action] = (acc[op.action] || 0) + 1;+ return acc;+ },+ {} as Record<string, number>,+ );++ const summaryParts = Object.entries(actionSummary).map(+ ([action, count]) => `${count} ${action}${count > 1 ? 's' : ''}`,+ );+ const content = `Successfully executed ${summaryParts.join(', ')} (${result.successCount}/${result.totalCount} operations succeeded).`;++ const state: ModifyNodesState = {+ results: result.results,+ successCount: result.successCount,+ totalCount: result.totalCount,+ };++ return { content, state, success: result.successCount > 0 };+ } catch (error) {+ const err = error as Error;+ return {+ error: {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ success: false,+ };+ }+ };++ // ==================== Text Operations ====================++ /**+ * Find and replace text across the document+ */+ replaceText = async (params: ReplaceTextArgs): Promise<BuiltinToolResult> => {+ try {+ const result = await this.runtime.replaceText(params);++ // Build response message+ const scopeDescription = params.nodeIds+ ? `within ${params.nodeIds.length} specified node(s)`+ : 'across the document';++ const content =+ result.replacementCount > 0+ ? `Successfully replaced ${result.replacementCount} occurrence(s) of "${params.searchText}" with "${params.newText}" ${scopeDescription}. Modified ${result.modifiedNodeIds.length} node(s).`+ : `No occurrences of "${params.searchText}" found ${scopeDescription}.`;++ const state: ReplaceTextState = {+ modifiedNodeIds: result.modifiedNodeIds,+ replacementCount: result.replacementCount,+ };++ return { content, state, success: true };+ } catch (error) {+ const err = error as Error;+ return {+ error: {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ success: false,+ };+ }+ };+}++// Export the executor class and a factory function+export { PageAgentExecutor };diff --git a/packages/builtin-tool-page-agent/src/index.ts b/packages/builtin-tool-page-agent/src/index.tsindex d72e2dbfd86..842409a4a8b 100644--- a/packages/builtin-tool-page-agent/src/index.ts+++ b/packages/builtin-tool-page-agent/src/index.ts@@ -1,47 +1,13 @@export { PageAgentManifest } from './manifest';export { systemPrompt } from './systemRole';export {- type BatchUpdateArgs,- type CompareSnapshotsArgs,- type CompareSnapshotsState,- type ConvertToListArgs,- type ConvertToListState,- type CreateNodeArgs,- type CreateNodeState,- type CropImageArgs,- type CropImageState,- type DeleteNodeArgs,- type DeleteNodeState,- type DeleteSnapshotArgs,- type DeleteSnapshotState,- type DeleteTableColumnArgs,- type DeleteTableColumnState,- type DeleteTableRowArgs,- type DeleteTableRowState,DocumentApiName,- type DocumentNode,- type DuplicateNodeArgs,- type DuplicateNodeState,type EditTitleArgs,type EditTitleState,- type FindNodesArgs,- type FindNodesState,- type GetNodeArgs,- type GetNodeState,type GetPageContentArgs,type GetPageContentState,- type IndentListItemArgs,- type IndentListItemState,type InitDocumentArgs,type InitDocumentState,- type InsertTableColumnArgs,- type InsertTableColumnState,- type InsertTableRowArgs,- type InsertTableRowState,- type ListSnapshotsArgs,- type ListSnapshotsState,- type MergeNodesArgs,- type MergeNodesState,type ModifyInsertOperation,type ModifyNodesArgs,type ModifyNodesState,@@ -49,38 +15,7 @@ export {type ModifyOperationResult,type ModifyRemoveOperation,type ModifyUpdateOperation,- type MoveNodeArgs,- type MoveNodeState,- type NodeCreate,- type NodeCreateResult,- type NodePosition,- type NodeType,- type NodeUpdate,- type NodeUpdateResult,- type OutdentListItemArgs,- type OutdentListItemState,PageAgentIdentifier,type ReplaceTextArgs,type ReplaceTextState,- type ResizeImageArgs,- type ResizeImageState,- type RestoreSnapshotArgs,- type RestoreSnapshotState,- type RotateImageArgs,- type RotateImageState,- type SaveSnapshotArgs,- type SaveSnapshotState,- type SetImageAltArgs,- type SetImageAltState,- type SnapshotInfo,- type SplitNodeArgs,- type SplitNodeState,- type ToggleListTypeArgs,- type ToggleListTypeState,- type UnwrapNodeArgs,- type UnwrapNodeState,- type UpdateNodeArgs,- type UpdateNodeState,- type WrapNodesArgs,- type WrapNodesState,} from './types';diff --git a/packages/builtin-tool-page-agent/src/systemRole.ts b/packages/builtin-tool-page-agent/src/systemRole.tsindex d0d8d5eb10e..f9f0f863315 100644--- a/packages/builtin-tool-page-agent/src/systemRole.ts+++ b/packages/builtin-tool-page-agent/src/systemRole.ts@@ -52,6 +52,9 @@ IMPORTANT: When creating or updating nodes, use plain text content directly. Do**Query & Read:**4. **getPageContent** - Get the latest page content in XML or markdown format. Use this when you need to refresh the current document state after modifications or when the context may be outdated.++**Text Operations:**+5. **replaceText** - Find and replace text across the document or within specific nodes. Supports plain text and regex patterns.</core_capabilities><workflow>@@ -62,6 +65,7 @@ IMPORTANT: When creating or updating nodes, use plain text content directly. Do**Step 2: Execute the Changes**- For new pages or complete rewrites: Use initPage with well-structured Markdown, then use editTitle to update the title- For targeted edits: Use modifyNodes with appropriate operations (insert, modify, remove)+- For find-and-replace: Use replaceText for batch text replacements across the document (supports regex)- For document metadata: Use editTitle to update the title- Note: The current page content (XML with node IDs) is provided in the system context, so you can directly reference node IDs for modifications@@ -210,6 +214,41 @@ getPageContent({ format: "xml" })getPageContent({ format: "markdown" })\`\`\`+## Text Operations++**replaceText**+Find and replace text across the document or within specific nodes.++Parameters:+- searchText: Required. The text to find. Can be plain text or a regex pattern.+- newText: Required. The replacement text.+- useRegex: Optional. Set to true to treat searchText as a regular expression. Default: false.+- replaceAll: Optional. Whether to replace all occurrences or just the first one. Default: true.+- nodeIds: Optional. Array of node IDs to limit the replacement scope. If not provided, searches entire document.++\`\`\`+// Simple text replacement+replaceText({ searchText: "old text", newText: "new text" })++// Replace first occurrence only+replaceText({ searchText: "Hello", newText: "Hi", replaceAll: false })++// Regex: replace all numbers+replaceText({ searchText: "\\\\d+", newText: "X", useRegex: true })++// Regex: word boundaries+replaceText({ searchText: "\\\\bword\\\\b", newText: "term", useRegex: true })++// Regex: optional groups+replaceText({ searchText: "color(u)?r", newText: "shade", useRegex: true })++// Regex: alternation+replaceText({ searchText: "cat|dog", newText: "pet", useRegex: true })++// Replace within specific nodes only+replaceText({ searchText: "draft", newText: "final", nodeIds: ["node-1", "node-2"] })+\`\`\`+</tool_usage_guidelines><error_handling>@@ -302,7 +341,7 @@ Here are some examples of correct usage of page tools:</example><example_docstring>- This example shows creating a table structure.+ This example shows creating a table structure using modifyNodes insert action.</example_docstring><example>@@ -311,7 +350,7 @@ Here are some examples of correct usage of page tools:<assistant_response>I'll create a comparison table for your product tiers.- [Calls createNode with type "table" and children containing thead with column headers (Feature, Basic, Pro, Enterprise) and tbody with feature rows]+ [Calls modifyNodes with operations: [{ action: "insert", afterId: "root", litexml: "<table><thead><tr><th>Feature</th><th>Basic</th><th>Pro</th><th>Enterprise</th></tr></thead><tbody><tr><td>Storage</td><td>10GB</td><td>100GB</td><td>Unlimited</td></tr></tbody></table>" }]]I've added a comparison table with your three product tiers. The table includes headers and rows for different features across Basic, Pro, and Enterprise tiers.</assistant_response>@@ -319,40 +358,83 @@ Here are some examples of correct usage of page tools:<example_docstring>This example demonstrates batch updating multiple nodes at once.+ Note: The assistant describes changes using content references, NOT internal IDs.</example_docstring><example>- <user_query>Fix the typos in paragraphs 4, 6, and 8</user_query>+ <user_query>Fix the typos in the introduction, methodology, and conclusion paragraphs</user_query><assistant_response>I'll fix the typos in all three paragraphs at once.[Calls modifyNodes with operations: [{ action: "modify", litexml: ['<p id="4">Corrected text...</p>', '<p id="6">Corrected text...</p>', '<p id="8">Corrected text...</p>'] }]]- Done! I've corrected the typos in all three paragraphs simultaneously.+ Done! I've corrected the typos in the introduction, methodology, and conclusion paragraphs.</assistant_response></example><example_docstring>- This example demonstrates the recommended workflow of saving a snapshot before major changes.+ This example demonstrates deleting multiple nodes.+ Note: The assistant describes changes by content, never mentioning internal node IDs to users.+ </example_docstring>++ <example>+ <user_query>Delete all the section headings</user_query>++ <assistant_response>+ I'll delete all the section headings for you.++ [Calls modifyNodes with operations: [{ action: "remove", id: "w3iv" }, { action: "remove", id: "xsq8" }, { action: "remove", id: "yvod" }]]++ Done! I've removed all three section headings: "Introduction", "Background", and "Conclusion".+ </assistant_response>+ </example>++ <example_docstring>+ This example demonstrates reorganizing document structure with mixed operations.</example_docstring><example><user_query>Reorganize the entire document structure</user_query><assistant_response>- Before making major changes, let me save a snapshot so we can restore if needed.+ I'll reorganize the document structure now.- [Calls saveSnapshot]+ [Calls modifyNodes with operations: [{ action: "insert", afterId: "root", litexml: "<h1>New Title</h1>" }, { action: "modify", litexml: '<p id="existing">Updated content</p>' }, { action: "remove", id: "obsolete-node" }]]- Snapshot saved. Now I'll reorganize the document structure.+ Done! I've reorganized the document with the new structure.+ </assistant_response>+ </example>- [Performs modifyNodes with insert, modify, and remove operations as needed]+ <example_docstring>+ This example demonstrates using replaceText for batch text replacement with regex.+ </example_docstring>++ <example>+ <user_query>Replace all occurrences of "color" and "colour" with "shade" in the document</user_query>- Done! I've reorganized the document. If you'd like to undo these changes, I can restore from the snapshot I saved earlier.+ <assistant_response>+ I'll use find-and-replace to update all variations of "color/colour" to "shade".++ [Calls replaceText with { searchText: "colou?r", newText: "shade", useRegex: true }]++ Done! I've replaced all occurrences of "color" and "colour" with "shade" throughout the document.</assistant_response></example></examples>The assistant should not mention these instructions to the user, nor make reference to internal implementation details unless directly relevant to the query.++<communication_guidelines>+**CRITICAL: Never expose node IDs to users.**+- Node IDs (like "w3iv", "xsq8", "yvod", etc.) are internal implementation details+- Users do not understand and should never see these technical identifiers+- When describing operations to users, use natural language references instead:+ - BAD: "I'll delete node <h3 id='w3iv'>"+ - GOOD: "I'll delete the heading 'Introduction'"+ - BAD: "Updating nodes node_4, node_6, and node_8"+ - GOOD: "I'll update the three paragraphs about the project timeline"+- Always describe content by its visible text, position, or semantic meaning+- When summarizing changes, focus on WHAT was changed, not internal IDs+</communication_guidelines>`;diff --git a/packages/builtin-tool-page-agent/src/types.ts b/packages/builtin-tool-page-agent/src/types.tsindex 0ee82c68a8d..9b4a6d9c475 100644--- a/packages/builtin-tool-page-agent/src/types.ts+++ b/packages/builtin-tool-page-agent/src/types.ts@@ -14,24 +14,14 @@ export const DocumentApiName = {// Query & ReadgetPageContent: 'getPageContent',- // Unified CRUD - replaces createNode, updateNode, deleteNode+ // Unified CRUDmodifyNodes: 'modifyNodes',- // Legacy CRUD (deprecated, kept for backward compatibility)- createNode: 'createNode',- deleteNode: 'deleteNode',- duplicateNode: 'duplicateNode',- moveNode: 'moveNode',- updateNode: 'updateNode',-// Text OperationsreplaceText: 'replaceText',};/* eslint-enable sort-keys-fix/sort-keys-fix */-// Node position types-export type NodePosition = 'before' | 'after' | 'prepend' | 'append';-// ============ Initialize Args ============export interface InitDocumentArgs {markdown: string;@@ -42,108 +32,11 @@ export interface EditTitleArgs {title: string;}-// Common node types in XML document-export type NodeType =- | 'p'- | 'span'- | 'file'- | 'img'- | 'h1'- | 'h2'- | 'h3'- | 'h4'- | 'h5'- | 'h6'- | 'ul'- | 'ol'- | 'li'- | 'table'- | 'thead'- | 'tbody'- | 'tr'- | 'td'- | 'th'- | 'blockquote'- | 'code'- | 'pre'- | 'a'- | 'br'- | 'hr'- | 'div'- | string;-// ============ Query & Search Args ============export interface GetPageContentArgs {format?: 'xml' | 'markdown' | 'both';}-export interface GetNodeArgs {- nodeId: string;-}--export interface FindNodesArgs {- attributes?: Record<string, string>;- containsText?: string;- type?: NodeType;-}--// ============ Basic CRUD Args ============--/** Single node creation specification */-export interface NodeCreate {- attributes?: Record<string, string>;- children?: string;- content?: string;- position?: NodePosition;- referenceNodeId?: string;- type: NodeType;-}--/**- * Args for creating nodes. Supports two modes:- * 1. Single node: Use type, content, etc. directly- * 2. Multiple nodes: Use nodes array containing multiple NodeCreate objects- */-export type CreateNodeArgs =- | NodeCreate- | {- nodes: NodeCreate[];- };--/** Single node update specification */-export interface NodeUpdate {- attributes?: Record<string, string | null>;- children?: string;- content?: string;- nodeId: string;-}--/**- * Args for updating nodes. Supports two modes:- * 1. Single node: Use `nodeId` with optional `content`, `children`, `attributes`- * 2. Multiple nodes: Use `nodes` array containing multiple NodeUpdate objects- */-export type UpdateNodeArgs =- | NodeUpdate- | {- nodes: NodeUpdate[];- };--export interface DeleteNodeArgs {- nodeId: string;-}--export interface MoveNodeArgs {- nodeId: string;- position: NodePosition;- targetNodeId: string;-}--export interface DuplicateNodeArgs {- nodeId: string;- position?: 'before' | 'after';-}-// ============ Unified Modify Nodes Args ============/** Insert operation: insert a node before or after a reference node */@@ -188,64 +81,7 @@ export interface ReplaceTextArgs {useRegex?: boolean;}-// ============ Batch Operations Args ============-export interface BatchUpdateArgs {- attributes?: Record<string, string | null>;- nodeIds: string[];-}--// ============ Structure Operations Args ============-export interface WrapNodesArgs {- nodeIds: string[];- wrapperAttributes?: Record<string, string>;- wrapperType: NodeType;-}--export interface UnwrapNodeArgs {- nodeId: string;-}--export interface MergeNodesArgs {- nodeIds: string[];-}--export interface SplitNodeArgs {- nodeId: string;- splitAt: number;-}--// ============ Table Operations Args ============-export interface InsertTableRowArgs {- cells?: string[];- position?: 'before' | 'after';- referenceRowId?: string;- tableId: string;-}--export interface InsertTableColumnArgs {- cells?: string[];- columnIndex: number;- headerContent?: string;- tableId: string;-}--export interface DeleteTableRowArgs {- rowId: string;-}--export interface DeleteTableColumnArgs {- columnIndex: number;- tableId: string;-}-// ============ State Types for Renders ============-export interface DocumentNode {- attributes?: Record<string, string>;- children?: DocumentNode[];- content?: string;- id: string;- type: string;-}export interface GetPageContentState {documentId: string;@@ -259,67 +95,6 @@ export interface GetPageContentState {xml?: string;}-export interface GetNodeState {- node: DocumentNode;-}--export interface FindNodesState {- matches: Array<{- id: string;- preview?: string;- type: string;- }>;- total: number;-}--/** Details of a single node creation result */-export interface NodeCreateResult {- content?: string;- createdNodeId: string;- success: boolean;- type: string;-}--export interface CreateNodeState {- /** @deprecated Use results instead. Kept for backward compatibility */- createdNodeId?: string;- /** @deprecated Use results instead. Kept for backward compatibility */- createdNodeIds?: string[];- /** Individual creation results with details */- results: NodeCreateResult[];-}--/** Details of a single node update result */-export interface NodeUpdateResult {- attributes?: Record<string, string | null>;- content?: string;- nodeId: string;- success: boolean;-}--export interface UpdateNodeState {- /** Individual update results with details */- results: NodeUpdateResult[];- /** @deprecated Use results instead. Kept for backward compatibility */- updatedNodeId?: string;- /** @deprecated Use results instead. Kept for backward compatibility */- updatedNodeIds?: string[];-}--export interface DeleteNodeState {- deletedNodeId: string;-}--export interface MoveNodeState {- movedNodeId: string;- newPosition: string;-}--export interface DuplicateNodeState {- newNodeId: string;- originalNodeId: string;-}-/** Result of a single modify operation */export interface ModifyOperationResult {action: 'insert' | 'remove' | 'modify';@@ -340,156 +115,6 @@ export interface ReplaceTextState {replacementCount: number;}-export interface BatchUpdateState {- updatedNodeIds: string[];-}--export interface WrapNodesState {- wrappedNodeIds: string[];- wrapperNodeId: string;-}--export interface UnwrapNodeState {- childNodeIds: string[];- removedNodeId: string;-}--export interface MergeNodesState {- mergedNodeId: string;- removedNodeIds: string[];-}--export interface SplitNodeState {- newNodeIds: [string, string];- originalNodeId: string;-}--export interface InsertTableRowState {- newRowId: string;-}--export interface InsertTableColumnState {- columnIndex: number;- newCellIds: string[];-}--export interface DeleteTableRowState {- deletedRowId: string;-}--export interface DeleteTableColumnState {- columnIndex: number;- deletedCellIds: string[];-}--// ============ Image Operations Args ============-export interface ResizeImageArgs {- height?: number;- keepAspectRatio?: boolean;- nodeId: string;- width?: number;-}--export interface CropImageArgs {- height: number;- nodeId: string;- width: number;- x: number;- y: number;-}--export interface RotateImageArgs {- angle: 90 | 180 | 270 | -90 | -180 | -270;- nodeId: string;-}--export interface SetImageAltArgs {- alt: string;- nodeId: string;-}--// ============ List Operations Args ============-export interface IndentListItemArgs {- nodeId: string;-}--export interface OutdentListItemArgs {- nodeId: string;-}--export interface ToggleListTypeArgs {- listId: string;- targetType: 'ul' | 'ol';-}--export interface ConvertToListArgs {- listType: 'ul' | 'ol';- nodeIds: string[];-}--// ============ Snapshot Operations Args ============-export interface SaveSnapshotArgs {- description?: string;-}--export interface RestoreSnapshotArgs {- snapshotId: string;-}--export interface ListSnapshotsArgs {- limit?: number;-}--export interface DeleteSnapshotArgs {- snapshotId: string;-}--export interface CompareSnapshotsArgs {- snapshotId1: string;- snapshotId2: string;-}--// ============ Image Operations State ============-export interface ResizeImageState {- newHeight: number;- newWidth: number;- nodeId: string;-}--export interface CropImageState {- nodeId: string;-}--export interface RotateImageState {- newAngle: number;- nodeId: string;-}--export interface SetImageAltState {- nodeId: string;-}--// ============ List Operations State ============-export interface IndentListItemState {- newParentId: string;- nodeId: string;-}--export interface OutdentListItemState {- newParentId: string;- nodeId: string;-}--export interface ToggleListTypeState {- listId: string;- newType: 'ul' | 'ol';-}--export interface ConvertToListState {- listId: string;- nodeIds: string[];-}-// ============ Initialize State ============export interface InitDocumentState {nodeCount: number;@@ -502,33 +127,36 @@ export interface EditTitleState {previousTitle: string;}-// ============ Snapshot Operations State ============-export interface SnapshotInfo {- createdAt: string;- description?: string;- id: string;- nodeCount: number;-}+// ============ Runtime Result Types ============+// These are the raw result types returned by Runtime methods+// Executor is responsible for converting these to BuiltinToolResult format-export interface SaveSnapshotState {- snapshotId: string;+export interface InitPageRuntimeResult {+ extractedTitle?: string;+ nodeCount: number;}-export interface RestoreSnapshotState {- restoredSnapshotId: string;+export interface EditTitleRuntimeResult {+ newTitle: string;+ previousTitle: string;}-export interface ListSnapshotsState {- snapshots: SnapshotInfo[];- total: number;+export interface GetPageContentRuntimeResult {+ charCount?: number;+ documentId: string;+ lineCount?: number;+ markdown?: string;+ title: string;+ xml?: string;}-export interface DeleteSnapshotState {- deletedSnapshotId: string;+export interface ModifyNodesRuntimeResult {+ results: ModifyOperationResult[];+ successCount: number;+ totalCount: number;}-export interface CompareSnapshotsState {- additions: string[];- deletions: string[];- modifications: string[];+export interface ReplaceTextRuntimeResult {+ modifiedNodeIds: string[];+ replacementCount: number;}diff --git a/packages/builtin-tool-page-agent/vitest.config.mts b/packages/builtin-tool-page-agent/vitest.config.mtsnew file mode 100644index 00000000000..059dba28d06--- /dev/null+++ b/packages/builtin-tool-page-agent/vitest.config.mts@@ -0,0 +1,17 @@+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ coverage: {+ provider: 'v8',+ reporter: ['text', 'json', 'lcov', 'text-summary'],+ },+ environment: 'node',+ server: {+ deps: {+ // Inline @emoji-mart packages to avoid ESM JSON import issues+ inline: [/@emoji-mart/, /@lobehub\/ui/],+ },+ },+ },+});diff --git a/src/app/[variants]/(auth)/_layout/index.tsx b/src/app/[variants]/(auth)/_layout/index.tsxindex c9d41fa044b..65530f09d94 100644--- a/src/app/[variants]/(auth)/_layout/index.tsx+++ b/src/app/[variants]/(auth)/_layout/index.tsx@@ -40,7 +40,7 @@ const AuthContainer: FC<PropsWithChildren> = ({ children }) => {</Center><Center padding={24}><Text align={'center'} type={'secondary'}>- © 2025 LobeHub, Inc. All rights reserved.+ © 2025 LobeHub. All rights reserved.</Text></Center></Flexbox>diff --git a/src/app/[variants]/onboarding/_layout/index.tsx b/src/app/[variants]/onboarding/_layout/index.tsxindex 9d395b0f9ea..a85639ea16f 100644--- a/src/app/[variants]/onboarding/_layout/index.tsx+++ b/src/app/[variants]/onboarding/_layout/index.tsx@@ -39,7 +39,7 @@ const OnBoardingContainer: FC<PropsWithChildren> = ({ children }) => {</Center><Center padding={24}><Text align={'center'} type={'secondary'}>- © 2025 LobeHub, Inc. All rights reserved.+ © 2025 LobeHub. All rights reserved.</Text></Center></Flexbox>diff --git a/src/features/PageEditor/StoreUpdater.tsx b/src/features/PageEditor/StoreUpdater.tsxindex b4f6f40e835..176d1f651c0 100644--- a/src/features/PageEditor/StoreUpdater.tsx+++ b/src/features/PageEditor/StoreUpdater.tsx@@ -5,9 +5,9 @@ import debug from 'debug';import React, { memo, useEffect, useRef } from 'react';import { createStoreUpdater } from 'zustand-utils';-import { pageAgentRuntime } from '@/store/chat/slices/builtinTool/actions/pageAgent';import { useFileStore } from '@/store/file';import { documentSelectors } from '@/store/file/slices/document/selectors';+import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';import { type PublicState, usePageEditorStore, useStoreApi } from './store';@@ -192,6 +192,8 @@ const StoreUpdater = memo<StoreUpdaterProps>(// Connect editor to page agent runtimeuseEffect(() => {if (editor) {+ // for easier debug , mount editor instance to window+ window.__editor = editor;pageAgentRuntime.setEditor(editor);}return () => {diff --git a/src/features/PageEditor/store/action.ts b/src/features/PageEditor/store/action.tsindex 2acd95b8e6a..bac7a2d0c42 100644--- a/src/features/PageEditor/store/action.ts+++ b/src/features/PageEditor/store/action.ts@@ -4,8 +4,8 @@ import { debounce } from 'es-toolkit/compat';import { type StateCreator } from 'zustand';import { documentService } from '@/services/document';-import { pageAgentRuntime } from '@/store/chat/slices/builtinTool/actions/pageAgent';import { useFileStore } from '@/store/file';+import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';import { DocumentSourceType, type LobeDocument } from '@/types/document';import { type State, initialState } from './initialState';diff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.tsindex 9b32dc2ac39..1e887fd827d 100644--- a/src/locales/default/plugin.ts+++ b/src/locales/default/plugin.ts@@ -92,6 +92,7 @@ export default {'builtins.lobe-page-agent.apiName.indentListItem': 'Indent list item','builtins.lobe-page-agent.apiName.initPage': 'Start writing content','builtins.lobe-page-agent.apiName.initPage.chars': ' chars',+ 'builtins.lobe-page-agent.apiName.initPage.creating': 'Creating document','builtins.lobe-page-agent.apiName.initPage.lines': ' lines','builtins.lobe-page-agent.apiName.initPage.result': 'Document created','builtins.lobe-page-agent.apiName.insertTableColumn': 'Insert table column',diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.tsindex 7c26060d6cc..866822143ed 100644--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts@@ -36,13 +36,13 @@ import { messageService } from '@/services/message';import { createAgentExecutors } from '@/store/chat/agents/createAgentExecutors';import { type ChatStore } from '@/store/chat/store';import { getFileStoreState } from '@/store/file/store';+import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';import { toolInterventionSelectors } from '@/store/user/selectors';import { getUserStoreState } from '@/store/user/store';import { topicSelectors } from '../../../selectors';import { cleanSpeakerTag } from '../../../utils/cleanSpeakerTag';import { messageMapKey } from '../../../utils/messageMapKey';-import { pageAgentRuntime } from '../../builtinTool/actions/pageAgent';import { selectTodosFromMessages } from '../../message/selectors/dbMessage';const log = debug('lobe-store:streaming-executor');@@ -940,7 +940,10 @@ export const streamingExecutor: StateCreator<// Create a new array to avoid modifying the original messageslet messages = [...originalMessages];- console.log('[internal_execAgentRuntime] Context scope:', { scope: context.scope, agentId: effectiveAgentId });+ console.log('[internal_execAgentRuntime] Context scope:', {+ scope: context.scope,+ agentId: effectiveAgentId,+ });// Use effectiveAgentId to get agent config (subAgentId in group orchestration, agentId otherwise)// resolveAgentConfig handles:diff --git a/src/store/chat/slices/builtinTool/actions/index.ts b/src/store/chat/slices/builtinTool/actions/index.tsindex cc85da1ad05..879b76cedb9 100644--- a/src/store/chat/slices/builtinTool/actions/index.ts+++ b/src/store/chat/slices/builtinTool/actions/index.ts@@ -7,9 +7,7 @@ import { type GroupAgentBuilderAction, groupAgentBuilderSlice } from './groupAgeimport { type ChatCodeInterpreterAction, codeInterpreterSlice } from './interpreter';import { type KnowledgeBaseAction, knowledgeBaseSlice } from './knowledgeBase';import { type LocalFileAction, localSystemSlice } from './localSystem';-import { type PageAgentAction, pageAgentSlice } from './pageAgent';import { type SearchAction, searchSlice } from './search';-import { type UserMemoryAction, userMemorySlice } from './userMemory';export interface ChatBuiltinToolActionextends@@ -17,10 +15,8 @@ export interface ChatBuiltinToolActionLocalFileAction,ChatCodeInterpreterAction,KnowledgeBaseAction,- UserMemoryAction,AgentBuilderAction,- GroupAgentBuilderAction,- PageAgentAction {}+ GroupAgentBuilderAction {}export const chatToolSlice: StateCreator<ChatStore,@@ -32,8 +28,6 @@ export const chatToolSlice: StateCreator<...localSystemSlice(...params),...codeInterpreterSlice(...params),...knowledgeBaseSlice(...params),- ...userMemorySlice(...params),...agentBuilderSlice(...params),...groupAgentBuilderSlice(...params),- ...pageAgentSlice(...params),});diff --git a/src/store/chat/slices/builtinTool/actions/pageAgent.ts b/src/store/chat/slices/builtinTool/actions/pageAgent.tsdeleted file mode 100644index 391e0d346c0..00000000000--- a/src/store/chat/slices/builtinTool/actions/pageAgent.ts+++ /dev/null@@ -1,721 +0,0 @@-import { PageAgentExecutionRuntime } from '@lobechat/builtin-tool-page-agent/executionRuntime';-import debug from 'debug';-import { type StateCreator } from 'zustand/vanilla';--import { type ChatStore } from '@/store/chat/store';--const log = debug('page:page-agent');--export interface PageAgentAction {- // ============ Batch Operations ============- batchUpdate: (id: string, params: any) => Promise<boolean>;-- // ============ Snapshot Operations ============- compareSnapshots: (id: string, params: any) => Promise<boolean>;-- // ============ List Operations ============- convertToList: (id: string, params: any) => Promise<boolean>;- // ============ Basic CRUD (Legacy) ============- createNode: (id: string, params: any) => Promise<boolean>;- // ============ Image Operations ============- cropImage: (id: string, params: any) => Promise<boolean>;- deleteNode: (id: string, params: any) => Promise<boolean>;- deleteSnapshot: (id: string, params: any) => Promise<boolean>;- // ============ Table Operations ============- deleteTableColumn: (id: string, params: any) => Promise<boolean>;-- deleteTableRow: (id: string, params: any) => Promise<boolean>;-- duplicateNode: (id: string, params: any) => Promise<boolean>;-- // ============ Document Metadata ============- editTitle: (id: string, params: any) => Promise<boolean>;- // ============ Query & Read ============- getPageContent: (id: string, params: any) => Promise<boolean>;- indentListItem: (id: string, params: any) => Promise<boolean>;- // ============ Initialize ============- initPage: (id: string, params: any) => Promise<boolean>;-- insertTableColumn: (id: string, params: any) => Promise<boolean>;- insertTableRow: (id: string, params: any) => Promise<boolean>;- listSnapshots: (id: string, params: any) => Promise<boolean>;- // ============ Structure Operations ============- mergeNodes: (id: string, params: any) => Promise<boolean>;-- // ============ Unified Node Operations ============- modifyNodes: (id: string, params: any) => Promise<boolean>;-- moveNode: (id: string, params: any) => Promise<boolean>;- outdentListItem: (id: string, params: any) => Promise<boolean>;- // ============ Text Operations ============- replaceText: (id: string, params: any) => Promise<boolean>;- resizeImage: (id: string, params: any) => Promise<boolean>;-- restoreSnapshot: (id: string, params: any) => Promise<boolean>;- rotateImage: (id: string, params: any) => Promise<boolean>;- saveSnapshot: (id: string, params: any) => Promise<boolean>;- setImageAlt: (id: string, params: any) => Promise<boolean>;-- splitNode: (id: string, params: any) => Promise<boolean>;- toggleListType: (id: string, params: any) => Promise<boolean>;- unwrapNode: (id: string, params: any) => Promise<boolean>;- updateNode: (id: string, params: any) => Promise<boolean>;- wrapNodes: (id: string, params: any) => Promise<boolean>;-}--// Create singleton instance of the runtime-const runtime = new PageAgentExecutionRuntime();--// Export runtime for external use (e.g., setting editor instance)-export { runtime as pageAgentRuntime };--export const pageAgentSlice: StateCreator<- ChatStore,- [['zustand/devtools', never]],- [],- PageAgentAction-> = (set, get) => ({- // ============ Batch Operations ============- batchUpdate: async (id, params) => {- log('batchUpdate', id, params);- return true;- },-- // ============ Snapshot Operations ============- compareSnapshots: async (id, params) => {- log('compareSnapshots', id, params);- return true;- },-- // ============ List Operations ============- convertToList: async (id, params) => {- log('convertToList', id, params);- return true;- },-- // ============ Basic CRUD ============- createNode: async (id, params) => {- const parentOperationId = get().messageOperationMap[id];-- const { operationId } = get().startOperation({- context: { messageId: id },- metadata: { apiName: 'createNode', params, startTime: Date.now() },- parentOperationId,- type: 'builtinToolPageAgent',- });-- const context = { operationId };-- try {- const result = await runtime.createNode(params);- const { content, success, error, state } = result;-- get().completeOperation(operationId);- await get().optimisticUpdateMessageContent(id, content, undefined, context);-- if (success) {- await get().optimisticUpdatePluginState(id, state, context);- } else {- await get().optimisticUpdatePluginError(- id,- {- body: error,- message: error?.message || content,- type: 'PluginServerError',- },- context,- );- }-- return true;- } catch (error) {- const err = error as Error;-- if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {- get().failOperation(operationId, {- message: 'User cancelled the request',- type: 'UserAborted',- });- return true;- }-- get().failOperation(operationId, {- message: err.message,- type: 'PluginServerError',- });-- await get().optimisticUpdateMessagePluginError(- id,- {- body: error,- message: err.message,- type: 'PluginServerError',- },- context,- );-- return true;- }- },-- // ============ Image Operations ============- cropImage: async (id, params) => {- log('cropImage', id, params);- return true;- },-- deleteNode: async (id, params) => {- const parentOperationId = get().messageOperationMap[id];-- const { operationId } = get().startOperation({- context: { messageId: id },- metadata: { apiName: 'deleteNode', params, startTime: Date.now() },- parentOperationId,- type: 'builtinToolPageAgent',- });-- const context = { operationId };-- try {- const result = await runtime.deleteNode(params);- const { content, success, error, state } = result;-- get().completeOperation(operationId);- await get().optimisticUpdateMessageContent(id, content, undefined, context);-- if (success) {- await get().optimisticUpdatePluginState(id, state, context);- } else {- await get().optimisticUpdatePluginError(- id,- {- body: error,- message: error?.message || content,- type: 'PluginServerError',- },- context,- );- }-- return true;- } catch (error) {- const err = error as Error;-- if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {- get().failOperation(operationId, {- message: 'User cancelled the request',- type: 'UserAborted',- });- return true;- }-- get().failOperation(operationId, {- message: err.message,- type: 'PluginServerError',- });-- await get().optimisticUpdateMessagePluginError(- id,- {- body: error,- message: err.message,- type: 'PluginServerError',- },- context,- );-- return true;- }- },-- deleteSnapshot: async (id, params) => {- log('deleteSnapshot', id, params);- return true;- },-- // ============ Table Operations ============- deleteTableColumn: async (id, params) => {- log('deleteTableColumn', id, params);- return true;- },-- deleteTableRow: async (id, params) => {- log('deleteTableRow', id, params);- return true;- },-- duplicateNode: async (id, params) => {- log('duplicateNode', id, params);- return true;- },-- // ============ Document Metadata ============- editTitle: async (id, params) => {- const parentOperationId = get().messageOperationMap[id];-- const { operationId } = get().startOperation({- context: { messageId: id },- metadata: { apiName: 'editTitle', params, startTime: Date.now() },- parentOperationId,- type: 'builtinToolPageAgent',- });-- const context = { operationId };-- try {- const result = await runtime.editTitle(params);- const { content, success, error, state } = result;-- get().completeOperation(operationId);- await get().optimisticUpdateMessageContent(id, content, undefined, context);-- if (success) {- await get().optimisticUpdatePluginState(id, state, context);- } else {- await get().optimisticUpdatePluginError(- id,- {- body: error,- message: error?.message || content,- type: 'PluginServerError',- },- context,- );- }-- return true;- } catch (error) {- const err = error as Error;-- if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {- get().failOperation(operationId, {- message: 'User cancelled the request',- type: 'UserAborted',- });- return true;- }-- get().failOperation(operationId, {- message: err.message,- type: 'PluginServerError',- });-- await get().optimisticUpdateMessagePluginError(- id,- {- body: error,- message: err.message,- type: 'PluginServerError',- },- context,- );-- return true;- }- },-- // ============ Query & Read ============- getPageContent: async (id, params) => {- const parentOperationId = get().messageOperationMap[id];-- const { operationId } = get().startOperation({- context: { messageId: id },- metadata: { apiName: 'getPageContent', params, startTime: Date.now() },- parentOperationId,- type: 'builtinToolPageAgent',- });-- const context = { operationId };-- try {- const result = await runtime.getPageContent(params);- const { content, success, error, state } = result;-- get().completeOperation(operationId);- await get().optimisticUpdateMessageContent(id, content, undefined, context);-- if (success) {- await get().optimisticUpdatePluginState(id, state, context);- } else {- await get().optimisticUpdatePluginError(- id,- {- body: error,- message: error?.message || content,- type: 'PluginServerError',- },- context,- );- }-- return true;- } catch (error) {- const err = error as Error;-- if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {- get().failOperation(operationId, {- message: 'User cancelled the request',- type: 'UserAborted',- });- return true;- }-- get().failOperation(operationId, {- message: err.message,- type: 'PluginServerError',- });-- await get().optimisticUpdateMessagePluginError(- id,- {- body: error,- message: err.message,- type: 'PluginServerError',- },- context,- );-- return true;- }- },-- indentListItem: async (id, params) => {- log('indentListItem', id, params);- return true;- },-- // ============ Initialize ============- initPage: async (id, params) => {- const parentOperationId = get().messageOperationMap[id];-- const { operationId } = get().startOperation({- context: { messageId: id },- metadata: { apiName: 'initPage', params, startTime: Date.now() },- parentOperationId,- type: 'builtinToolPageAgent',- });-- const context = { operationId };-- try {- const result = await runtime.initPage(params);- const { content, success, error, state } = result;-- get().completeOperation(operationId);- await get().optimisticUpdateMessageContent(id, content, undefined, context);-- if (success) {- await get().optimisticUpdatePluginState(id, state, context);- } else {- await get().optimisticUpdatePluginError(- id,- {- body: error,- message: error?.message || content,- type: 'PluginServerError',- },- context,- );- }-- return true;- } catch (error) {- const err = error as Error;-- if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {- get().failOperation(operationId, {- message: 'User cancelled the request',- type: 'UserAborted',- });- return true;- }-- get().failOperation(operationId, {- message: err.message,- type: 'PluginServerError',- });-- await get().optimisticUpdateMessagePluginError(- id,- {- body: error,- message: err.message,- type: 'PluginServerError',- },- context,- );-- return true;- }- },-- insertTableColumn: async (id, params) => {- log('insertTableColumn', id, params);- return true;- },-- insertTableRow: async (id, params) => {- log('insertTableRow', id, params);- return true;- },-- listSnapshots: async (id, params) => {- log('listSnapshots', id, params);- return true;- },-- // ============ Structure Operations ============- mergeNodes: async (id, params) => {- log('mergeNodes', id, params);- return true;- },-- // ============ Unified Node Operations ============- modifyNodes: async (id, params) => {- const parentOperationId = get().messageOperationMap[id];-- const { operationId } = get().startOperation({- context: { messageId: id },- metadata: { apiName: 'modifyNodes', params, startTime: Date.now() },- parentOperationId,- type: 'builtinToolPageAgent',- });-- const context = { operationId };-- try {- const result = await runtime.modifyNodes(params);- const { content, success, error, state } = result;-- get().completeOperation(operationId);- await get().optimisticUpdateMessageContent(id, content, undefined, context);-- if (success) {- await get().optimisticUpdatePluginState(id, state, context);- } else {- await get().optimisticUpdatePluginError(- id,- {- body: error,- message: error?.message || content,- type: 'PluginServerError',- },- context,- );- }-- return true;- } catch (error) {- const err = error as Error;-- if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {- get().failOperation(operationId, {- message: 'User cancelled the request',- type: 'UserAborted',- });- return true;- }-- get().failOperation(operationId, {- message: err.message,- type: 'PluginServerError',- });-- await get().optimisticUpdateMessagePluginError(- id,- {- body: error,- message: err.message,- type: 'PluginServerError',- },- context,- );-- return true;- }- },-- moveNode: async (id, params) => {- log('moveNode', id, params);- return true;- },-- outdentListItem: async (id, params) => {- log('outdentListItem', id, params);- return true;- },-- // ============ Text Operations ============- replaceText: async (id, params) => {- const parentOperationId = get().messageOperationMap[id];-- const { operationId } = get().startOperation({- context: { messageId: id },- metadata: { apiName: 'replaceText', params, startTime: Date.now() },- parentOperationId,- type: 'builtinToolPageAgent',- });-- const context = { operationId };-- try {- const result = await runtime.replaceText(params);- const { content, success, error, state } = result;-- get().completeOperation(operationId);- await get().optimisticUpdateMessageContent(id, content, undefined, context);-- if (success) {- await get().optimisticUpdatePluginState(id, state, context);- } else {- await get().optimisticUpdatePluginError(- id,- {- body: error,- message: error?.message || content,- type: 'PluginServerError',- },- context,- );- }-- return true;- } catch (error) {- const err = error as Error;-- if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {- get().failOperation(operationId, {- message: 'User cancelled the request',- type: 'UserAborted',- });- return true;- }-- get().failOperation(operationId, {- message: err.message,- type: 'PluginServerError',- });-- await get().optimisticUpdateMessagePluginError(- id,- {- body: error,- message: err.message,- type: 'PluginServerError',- },- context,- );-- return true;- }- },-- resizeImage: async (id, params) => {- log('resizeImage', id, params);- return true;- },-- restoreSnapshot: async (id, params) => {- log('restoreSnapshot', id, params);- return true;- },-- rotateImage: async (id, params) => {- log('rotateImage', id, params);- return true;- },-- saveSnapshot: async (id, params) => {- log('saveSnapshot', id, params);- return true;- },-- setImageAlt: async (id, params) => {- log('setImageAlt', id, params);- return true;- },-- splitNode: async (id, params) => {- log('splitNode', id, params);- return true;- },-- toggleListType: async (id, params) => {- log('toggleListType', id, params);- return true;- },-- unwrapNode: async (id, params) => {- log('unwrapNode', id, params);- return true;- },-- updateNode: async (id, params) => {- const parentOperationId = get().messageOperationMap[id];-- const { operationId } = get().startOperation({- context: { messageId: id },- metadata: { apiName: 'updateNode', params, startTime: Date.now() },- parentOperationId,- type: 'builtinToolPageAgent',- });-- const context = { operationId };-- try {- const result = await runtime.updateNode(params);- const { content, success, error, state } = result;-- get().completeOperation(operationId);- await get().optimisticUpdateMessageContent(id, content, undefined, context);-- if (success) {- await get().optimisticUpdatePluginState(id, state, context);- } else {- await get().optimisticUpdatePluginError(- id,- {- body: error,- message: error?.message || content,- type: 'PluginServerError',- },- context,- );- }-- return true;- } catch (error) {- const err = error as Error;-- if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {- get().failOperation(operationId, {- message: 'User cancelled the request',- type: 'UserAborted',- });- return true;- }-- get().failOperation(operationId, {- message: err.message,- type: 'PluginServerError',- });-- await get().optimisticUpdateMessagePluginError(- id,- {- body: error,- message: err.message,- type: 'PluginServerError',- },- context,- );-- return true;- }- },-- wrapNodes: async (id, params) => {- log('wrapNodes', id, params);- return true;- },-});diff --git a/src/store/chat/slices/builtinTool/actions/userMemory.ts b/src/store/chat/slices/builtinTool/actions/userMemory.tsdeleted file mode 100644index 1e33b20ff8e..00000000000--- a/src/store/chat/slices/builtinTool/actions/userMemory.ts+++ /dev/null@@ -1,151 +0,0 @@-import type {- AddIdentityActionSchema,- ContextMemoryItemSchema,- ExperienceMemoryItemSchema,- PreferenceMemoryItemSchema,- RemoveIdentityActionSchema,- UpdateIdentityActionSchema,-} from '@lobechat/memory-user-memory/schemas';-import { type z } from 'zod';-import { type StateCreator } from 'zustand/vanilla';--import { userMemoryService } from '@/services/userMemory';-import { type ChatStore } from '@/store/chat/store';-import { type SearchMemoryParams } from '@/types/userMemory';--export interface UserMemoryAction {- addContextMemory: (- id: string,- params: z.infer<typeof ContextMemoryItemSchema>,- ) => Promise<boolean>;- addExperienceMemory: (- id: string,- params: z.infer<typeof ExperienceMemoryItemSchema>,- ) => Promise<boolean>;- addIdentityMemory: (- id: string,- params: z.infer<typeof AddIdentityActionSchema>,- ) => Promise<boolean>;- addPreferenceMemory: (- id: string,- params: z.infer<typeof PreferenceMemoryItemSchema>,- ) => Promise<boolean>;- removeIdentityMemory: (- id: string,- params: z.infer<typeof RemoveIdentityActionSchema>,- ) => Promise<boolean>;- searchUserMemory: (id: string, params: SearchMemoryParams) => Promise<boolean>;- updateIdentityMemory: (- id: string,- params: z.infer<typeof UpdateIdentityActionSchema>,- ) => Promise<boolean>;-}--const runMemoryTool = async (- id: string,- executor: () => Promise<unknown>,- get: () => ChatStore,- errorPayload?: (error: Error) => unknown,-): Promise<boolean> => {- const {- completeOperation,- failOperation,- messageOperationMap,- optimisticUpdateMessageContent,- optimisticUpdateMessagePluginError,- startOperation,- } = get();-- const parentOperationId = messageOperationMap[id];- const { operationId } = startOperation({- context: { messageId: id },- metadata: { startTime: Date.now() },- parentOperationId,- type: 'builtinToolMemory',- });- const context = { operationId };-- try {- const result = await executor();- completeOperation(operationId);- await optimisticUpdateMessageContent(id, JSON.stringify(result), undefined, context);-- if (typeof (result as any)?.success === 'boolean') return (result as any).success;-- return true;- } catch (error) {- const err = error as Error;-- console.error('Failed to run memory tool:', err);-- failOperation(operationId, {- message: err.message,- type: 'PluginServerError',- });-- await optimisticUpdateMessagePluginError(- id,- {- body: error,- message: err.message,- type: 'PluginServerError',- },- context,- );-- const fallback = errorPayload?.(err) ?? {- message: `Failed to run memory tool: ${err.message}`,- success: false,- };-- await optimisticUpdateMessageContent(id, JSON.stringify(fallback), undefined, context);-- return false;- }-};--export const userMemorySlice: StateCreator<- ChatStore,- [['zustand/devtools', never]],- [],- UserMemoryAction-> = (_set, get) => ({- addContextMemory: async (id, params) => {- return runMemoryTool(id, () => userMemoryService.addContextMemory(params), get);- },-- addExperienceMemory: async (id, params) => {- return runMemoryTool(id, () => userMemoryService.addExperienceMemory(params), get);- },-- addIdentityMemory: async (id, params) => {- return runMemoryTool(id, () => userMemoryService.addIdentityMemory(params), get);- },-- addPreferenceMemory: async (id, params) => {- return runMemoryTool(id, () => userMemoryService.addPreferenceMemory(params), get);- },-- removeIdentityMemory: async (id, params) => {- return runMemoryTool(id, () => userMemoryService.removeIdentityMemory(params), get);- },-- searchUserMemory: async (id, params) => {- return runMemoryTool(- id,- () => userMemoryService.searchMemory(params),- get,- (error) => ({- contexts: [],- error: `Failed to retrieve memories: ${error.message}`,- experiences: [],- preferences: [],- success: false,- }),- );- },-- updateIdentityMemory: async (id, params) => {- return runMemoryTool(id, () => userMemoryService.updateIdentityMemory(params), get);- },-});diff --git a/src/store/tool/slices/builtin/executors/index.ts b/src/store/tool/slices/builtin/executors/index.tsindex af0d43ed288..70b93310aa1 100644--- a/src/store/tool/slices/builtin/executors/index.ts+++ b/src/store/tool/slices/builtin/executors/index.ts@@ -6,27 +6,20 @@*/import { groupManagementExecutor } from '@lobechat/builtin-tool-group-management/executor';import { gtdExecutor } from '@lobechat/builtin-tool-gtd/executor';+import { memoryExecutor } from '@lobechat/builtin-tool-memory/executor';+import { notebookExecutor } from '@lobechat/builtin-tool-notebook/executor';import type { IBuiltinToolExecutor } from '../types';-// ==================== Import and register all executors ====================--import { notebookExecutor } from './lobe-notebook';+import { pageAgentExecutor } from './lobe-page-agent';import { webBrowsing } from './lobe-web-browsing';+// ==================== Import and register all executors ====================+/*** Registry structure: Map<identifier, executor instance>*/const executorRegistry = new Map<string, IBuiltinToolExecutor>();-/**- * Register a builtin tool executor class instance- *- * @param executor - The executor instance to register- */-export const registerExecutor = (executor: IBuiltinToolExecutor): void => {- executorRegistry.set(executor.identifier, executor);-};-/*** Get a builtin tool executor by identifier*@@ -109,8 +102,23 @@ export const invokeExecutor = async (return executor.invoke(apiName, params, ctx);};+/**+ * Register builtin tool executor instances+ *+ * @param executors - Array of executor instances to register+ */+const registerExecutors = (executors: IBuiltinToolExecutor[]): void => {+ for (const executor of executors) {+ executorRegistry.set(executor.identifier, executor);+ }+};+// Register all executor instances-registerExecutor(groupManagementExecutor);-registerExecutor(gtdExecutor);-registerExecutor(notebookExecutor);-registerExecutor(webBrowsing);+registerExecutors([+ groupManagementExecutor,+ gtdExecutor,+ memoryExecutor,+ notebookExecutor,+ pageAgentExecutor,+ webBrowsing,+]);diff --git a/src/store/tool/slices/builtin/executors/lobe-page-agent.ts b/src/store/tool/slices/builtin/executors/lobe-page-agent.tsnew file mode 100644index 00000000000..c796c870314--- /dev/null+++ b/src/store/tool/slices/builtin/executors/lobe-page-agent.ts@@ -0,0 +1,14 @@+/**+ * Lobe Page Agent Executor+ *+ * Creates and exports the PageAgentExecutor instance for registration.+ * Also exports the runtime for editor instance injection.+ */+import { PageAgentExecutionRuntime } from '@lobechat/builtin-tool-page-agent/executionRuntime';+import { PageAgentExecutor } from '@lobechat/builtin-tool-page-agent/executor';++// Create singleton instance of the runtime+export const pageAgentRuntime = new PageAgentExecutionRuntime();++// Create executor instance with the runtime+export const pageAgentExecutor = new PageAgentExecutor(pageAgentRuntime);