π€― 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
β¨ feat(page-agent): execute tools server-side via HeadlessEditor (#15023)
Arvin Xu20cea3a6bf29
diff --git a/package.json b/package.jsonindex 16af8fcbba5..4bb06edb2db 100644--- a/package.json+++ b/package.json@@ -283,7 +283,7 @@"@lobehub/analytics": "^1.6.2","@lobehub/charts": "^5.0.0","@lobehub/desktop-ipc-typings": "workspace:*",- "@lobehub/editor": "^4.15.0",+ "@lobehub/editor": "^4.16.1","@lobehub/icons": "^5.0.0","@lobehub/market-sdk": "0.33.3","@lobehub/tts": "^5.1.2",diff --git a/packages/builtin-tool-page-agent/package.json b/packages/builtin-tool-page-agent/package.jsonindex 0f7330ef608..280fa1afb08 100644--- a/packages/builtin-tool-page-agent/package.json+++ b/packages/builtin-tool-page-agent/package.json@@ -5,7 +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","dependencies": {diff --git a/packages/builtin-tool-page-agent/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-page-agent/src/ExecutionRuntime/index.test.tsnew file mode 100644index 00000000000..32f4c5fb796--- /dev/null+++ b/packages/builtin-tool-page-agent/src/ExecutionRuntime/index.test.ts@@ -0,0 +1,111 @@+// @vitest-environment node+import { describe, expect, it, vi } from 'vitest';++import type { PageAgentInvocationContext, PageAgentRuntimeService } from './index';+import { PageAgentExecutionRuntime } from './index';++const DOC_ID = 'doc_test_1';+const ctxWithDoc: PageAgentInvocationContext = { documentId: DOC_ID, userId: 'u1' };+const ctxNoDoc: PageAgentInvocationContext = { userId: 'u1' };++const buildService = (+ overrides: Partial<PageAgentRuntimeService> = {},+): PageAgentRuntimeService => {+ const ok = async (apiName: string) => ({+ content: `ok:${apiName}`,+ state: { ran: apiName },+ });+ return {+ editTitle: vi.fn(() => ok('editTitle')),+ getPageContent: vi.fn(() => ok('getPageContent')),+ initPage: vi.fn(() => ok('initPage')),+ modifyNodes: vi.fn(() => ok('modifyNodes')),+ replaceText: vi.fn(() => ok('replaceText')),+ ...overrides,+ };+};++describe('PageAgentExecutionRuntime', () => {+ describe('documentId guard', () => {+ it('rejects every API call when documentId is missing', async () => {+ const service = buildService();+ const runtime = new PageAgentExecutionRuntime(service);++ const results = await Promise.all([+ runtime.initPage({ markdown: '# Hi' }, ctxNoDoc),+ runtime.editTitle({ title: 'x' }, ctxNoDoc),+ runtime.getPageContent({}, ctxNoDoc),+ runtime.modifyNodes({ operations: [{ action: 'remove', id: 'a' }] }, ctxNoDoc),+ runtime.replaceText({ newText: 'a', searchText: 'b' }, ctxNoDoc),+ ]);++ for (const result of results) {+ expect(result.success).toBe(false);+ expect((result.error as { type?: string }).type).toBe('PageAgentMissingDocumentId');+ }++ // Service callbacks never invoked.+ expect(service.initPage).not.toHaveBeenCalled();+ expect(service.editTitle).not.toHaveBeenCalled();+ expect(service.getPageContent).not.toHaveBeenCalled();+ expect(service.modifyNodes).not.toHaveBeenCalled();+ expect(service.replaceText).not.toHaveBeenCalled();+ });+ });++ describe('forwarding', () => {+ it('forwards each API call to the service with args + context', async () => {+ const service = buildService();+ const runtime = new PageAgentExecutionRuntime(service);++ await runtime.modifyNodes({ operations: [{ action: 'remove', id: 'a' }] }, ctxWithDoc);++ expect(service.modifyNodes).toHaveBeenCalledWith(+ { operations: [{ action: 'remove', id: 'a' }] },+ ctxWithDoc,+ );+ });++ it('envelopes the service output with success + documentId', async () => {+ const service = buildService({+ modifyNodes: async () => ({+ content: 'changed',+ state: { successCount: 3 },+ }),+ });+ const runtime = new PageAgentExecutionRuntime(service);++ const result = await runtime.modifyNodes(+ { operations: [{ action: 'remove', id: 'a' }] },+ ctxWithDoc,+ );++ expect(result.success).toBe(true);+ expect(result.content).toBe('changed');+ expect(result.state).toMatchObject({+ documentId: DOC_ID,+ successCount: 3,+ });+ });+ });++ describe('error envelope', () => {+ it('wraps thrown service errors as PageAgentRuntimeError', async () => {+ const service = buildService({+ modifyNodes: async () => {+ throw new Error('boom');+ },+ });+ const runtime = new PageAgentExecutionRuntime(service);++ const result = await runtime.modifyNodes(+ { operations: [{ action: 'remove', id: 'a' }] },+ ctxWithDoc,+ );++ expect(result.success).toBe(false);+ expect(result.content).toBe('boom');+ expect((result.error as { type?: string }).type).toBe('PageAgentRuntimeError');+ });+ });+});diff --git a/packages/builtin-tool-page-agent/src/ExecutionRuntime/index.ts b/packages/builtin-tool-page-agent/src/ExecutionRuntime/index.tsnew file mode 100644index 00000000000..6b2555d6f61--- /dev/null+++ b/packages/builtin-tool-page-agent/src/ExecutionRuntime/index.ts@@ -0,0 +1,138 @@+import type {+ EditTitleArgs,+ GetPageContentArgs,+ InitDocumentArgs,+ ModifyNodesArgs,+ ReplaceTextArgs,+} from '@lobechat/editor-runtime';+import type { BuiltinServerRuntimeOutput } from '@lobechat/types';++/**+ * Context passed to every page-agent server invocation.+ *+ * Mirrors the subset of `BuiltinToolContext` the page-agent tools rely on.+ * Kept minimal so this package does not depend on `@lobechat/types`'+ * full context shape (which carries renderer-only fields).+ */+export interface PageAgentInvocationContext {+ documentId?: string | null;+ operationId?: string;+ stepIndex?: number;+ toolCallId?: string;+ userId?: string;+}++/**+ * Shape every page-agent API callback must return. The runtime shell wraps+ * this into a `BuiltinServerRuntimeOutput` (filling `success: true`, adding+ * `documentId` to the state envelope, attaching error metadata on throw).+ */+export interface PageAgentApiOutput {+ content: string;+ state?: Record<string, unknown>;+}++/**+ * Service contract that host code (server runtime registration) implements.+ *+ * Implementations are expected to:+ * 1. Load the document row identified by `ctx.documentId`.+ * 2. Run the requested mutation against a `HeadlessEditor` + `EditorRuntime`+ * pair (page-agent tools always operate on a single document).+ * 3. Persist the new editorData/content/title back through `DocumentService`.+ * 4. Return both a human-readable `content` string and a `state` object+ * with at least `documentEditorData` / `documentContent` /+ * `documentTitle` so the renderer's `onAfterCall` hook can apply the+ * patch to the live Lexical editor without an extra DB roundtrip.+ *+ * Keeping the contract here (and the implementation at the registration site)+ * avoids dragging `@lobehub/editor` / `@lobechat/editor-runtime` into this+ * package's static import graph.+ */+export interface PageAgentRuntimeService {+ editTitle: (args: EditTitleArgs, ctx: PageAgentInvocationContext) => Promise<PageAgentApiOutput>;+ getPageContent: (+ args: GetPageContentArgs,+ ctx: PageAgentInvocationContext,+ ) => Promise<PageAgentApiOutput>;+ initPage: (+ args: InitDocumentArgs,+ ctx: PageAgentInvocationContext,+ ) => Promise<PageAgentApiOutput>;+ modifyNodes: (+ args: ModifyNodesArgs,+ ctx: PageAgentInvocationContext,+ ) => Promise<PageAgentApiOutput>;+ replaceText: (+ args: ReplaceTextArgs,+ ctx: PageAgentInvocationContext,+ ) => Promise<PageAgentApiOutput>;+}++const MISSING_DOCUMENT_ID =+ 'PageAgent server runtime received a tool call without documentId in context. ' ++ 'The conversation must be scoped to an open page editor.';++const failure = (message: string, type: string, body?: unknown): BuiltinServerRuntimeOutput => ({+ content: message,+ error: { body, message, type } as unknown,+ success: false,+});++/**+ * Server-side page-agent execution runtime.+ *+ * The runtime is a thin shell:+ * - validates `documentId` is present+ * - forwards to the host-supplied {@link PageAgentRuntimeService}+ * - normalizes success / failure into {@link BuiltinServerRuntimeOutput}+ *+ * All editor wiring (HeadlessEditor hydration, EditorRuntime invocation,+ * exports, persistence, silent-failure detection) lives in the consumer of+ * this class β see `src/server/services/toolExecution/serverRuntimes/pageAgent.ts`.+ */+export class PageAgentExecutionRuntime {+ private service: PageAgentRuntimeService;++ constructor(service: PageAgentRuntimeService) {+ this.service = service;+ }++ initPage = (args: InitDocumentArgs, ctx: PageAgentInvocationContext) =>+ this.dispatch('initPage', ctx, () => this.service.initPage(args, ctx));++ editTitle = (args: EditTitleArgs, ctx: PageAgentInvocationContext) =>+ this.dispatch('editTitle', ctx, () => this.service.editTitle(args, ctx));++ getPageContent = (args: GetPageContentArgs, ctx: PageAgentInvocationContext) =>+ this.dispatch('getPageContent', ctx, () => this.service.getPageContent(args, ctx));++ modifyNodes = (args: ModifyNodesArgs, ctx: PageAgentInvocationContext) =>+ this.dispatch('modifyNodes', ctx, () => this.service.modifyNodes(args, ctx));++ replaceText = (args: ReplaceTextArgs, ctx: PageAgentInvocationContext) =>+ this.dispatch('replaceText', ctx, () => this.service.replaceText(args, ctx));++ private async dispatch(+ apiName: string,+ ctx: PageAgentInvocationContext,+ invoke: () => Promise<PageAgentApiOutput>,+ ): Promise<BuiltinServerRuntimeOutput> {+ if (!ctx.documentId) {+ return failure(MISSING_DOCUMENT_ID, 'PageAgentMissingDocumentId');+ }++ try {+ const output = await invoke();+ return {+ content: output.content,+ state: { documentId: ctx.documentId, ...output.state },+ success: true,+ };+ } catch (error) {+ const err = error as Error;+ console.error(`[PageAgentExecutionRuntime] ${apiName} error`, err);+ return failure(err.message, 'PageAgentRuntimeError', err);+ }+ }+}diff --git a/packages/builtin-tool-page-agent/src/executor/index.test.ts b/packages/builtin-tool-page-agent/src/client/executor/index.test.tssimilarity index 99%rename from packages/builtin-tool-page-agent/src/executor/index.test.tsrename to packages/builtin-tool-page-agent/src/client/executor/index.test.tsindex d076d71b8a5..8c8ee41f5a6 100644--- a/packages/builtin-tool-page-agent/src/executor/index.test.ts+++ b/packages/builtin-tool-page-agent/src/client/executor/index.test.ts@@ -2,7 +2,7 @@ import type { EditorRuntime } from '@lobechat/editor-runtime';import type { BuiltinToolContext } from '@lobechat/types';import { beforeEach, describe, expect, it, vi } from 'vitest';-import { PageAgentIdentifier } from '../types';+import { PageAgentIdentifier } from '../../types';import { PageAgentExecutor } from './index';describe('PageAgentExecutor', () => {diff --git a/packages/builtin-tool-page-agent/src/executor/index.ts b/packages/builtin-tool-page-agent/src/client/executor/index.tssimilarity index 80%rename from packages/builtin-tool-page-agent/src/executor/index.tsrename to packages/builtin-tool-page-agent/src/client/executor/index.tsindex 8acb2d9d832..b2d6f4f1bd5 100644--- a/packages/builtin-tool-page-agent/src/executor/index.ts+++ b/packages/builtin-tool-page-agent/src/client/executor/index.ts@@ -6,7 +6,7 @@ import type {ModifyNodesArgs,ReplaceTextArgs,} from '@lobechat/editor-runtime';-import type { BuiltinToolResult } from '@lobechat/types';+import type { BuiltinToolResult, ToolAfterCallContext } from '@lobechat/types';import { BaseExecutor } from '@lobechat/types';import debug from 'debug';@@ -16,8 +16,8 @@ import type {InitDocumentState,ModifyNodesState,ReplaceTextState,-} from '../types';-import { PageAgentIdentifier } from '../types';+} from '../../types';+import { PageAgentIdentifier } from '../../types';const log = debug('lobe-page-agent:executor');@@ -125,6 +125,65 @@ class PageAgentExecutor extends BaseExecutor<typeof PageAgentApiName> {};}+ /**+ * Apply server-side execution result to the renderer.+ *+ * The page-agent tool now runs on the server (manifest `executors: ['server']`),+ * but the renderer still owns the live Lexical instance and the in-memory+ * document store. When the agent stream delivers `tool_end`, the gateway+ * event handler routes here so we can:+ * 1. Push the new `editorData`/`title` into the mounted editor via+ * `EditorRuntime.applyServerSnapshot` (which skips the auto-save loop).+ * 2. Mark `useDocumentStore` clean and update `lastSaved*` so the renderer+ * does not re-save what the server just wrote.+ *+ * If the editor for this `documentId` is not currently mounted (e.g. user+ * navigated away), we skip β next open will hydrate from the row directly.+ */+ onAfterCall = async ({ result }: ToolAfterCallContext): Promise<void> => {+ if (!result.success) return;++ const state = result.state as+ | {+ documentContent?: unknown;+ documentEditorData?: unknown;+ documentId?: unknown;+ documentTitle?: unknown;+ }+ | undefined+ | null;+ if (!state || typeof state !== 'object') return;++ const documentId = typeof state.documentId === 'string' ? state.documentId : undefined;+ if (!documentId) return;++ const content = typeof state.documentContent === 'string' ? state.documentContent : undefined;+ const title = typeof state.documentTitle === 'string' ? state.documentTitle : undefined;+ const editorData =+ state.documentEditorData && typeof state.documentEditorData === 'object'+ ? (state.documentEditorData as Record<string, unknown>)+ : undefined;++ // Only push into the live editor when this runtime is bound to the same+ // document the server just wrote. Otherwise the snapshot would overwrite+ // a different page's editor β store-level sync still runs below.+ if (this.runtime.isReady() && this.runtime.getCurrentDocId() === documentId) {+ this.runtime.applyServerSnapshot({ content, editorData, title });+ }++ // Always reconcile the document store: even if the editor isn't mounted,+ // the row was written and any cached projection should match.+ // Dynamic import keeps the renderer-only store graph (zustand + tRPC+ // client) out of this package's static import tree so server-side+ // unit tests of `executor/server.ts` don't have to load it.+ try {+ const { getDocumentStoreState } = await import('@/store/document');+ getDocumentStoreState().applyServerSnapshot(documentId, { content, editorData, title });+ } catch (error) {+ log('[PageAgentExecutor] applyServerSnapshot store sync failed', error);+ }+ };+// ==================== Initialize ====================/**diff --git a/packages/builtin-tool-page-agent/src/client/index.ts b/packages/builtin-tool-page-agent/src/client/index.tsindex 027c6d2c2c5..6b27dcd3cb7 100644--- a/packages/builtin-tool-page-agent/src/client/index.ts+++ b/packages/builtin-tool-page-agent/src/client/index.ts@@ -1,3 +1,4 @@+export { PageAgentExecutor } from './executor';export { PageAgentInspectors } from './Inspector';export { PageAgentPlaceholders } from './Placeholder';export { PageAgentRenders } from './Render';diff --git a/packages/builtin-tool-page-agent/src/index.ts b/packages/builtin-tool-page-agent/src/index.tsindex 1d79b3aef53..283298084c7 100644--- a/packages/builtin-tool-page-agent/src/index.ts+++ b/packages/builtin-tool-page-agent/src/index.ts@@ -1,4 +1,3 @@-// Re-export runtime types from @lobechat/editor-runtimeexport { PageAgentManifest } from './manifest';export { systemPrompt } from './systemRole';export {diff --git a/packages/builtin-tool-page-agent/src/manifest.ts b/packages/builtin-tool-page-agent/src/manifest.tsindex 0f19b77b6b3..6b903ea1162 100644--- a/packages/builtin-tool-page-agent/src/manifest.ts+++ b/packages/builtin-tool-page-agent/src/manifest.ts@@ -4,7 +4,6 @@ import { systemPrompt } from './systemRole';import { DocumentApiName, PageAgentIdentifier } from './types';export const PageAgentManifest: BuiltinToolManifest = {- executors: ['client'],api: [// ============ Initialize ============{diff --git a/packages/builtin-tool-page-agent/vitest.config.mts b/packages/builtin-tool-page-agent/vitest.config.mtsindex 059dba28d06..6a7d8caedd0 100644--- a/packages/builtin-tool-page-agent/vitest.config.mts+++ b/packages/builtin-tool-page-agent/vitest.config.mts@@ -1,6 +1,17 @@+import { dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { defineConfig } from 'vitest/config';+const packageDir = dirname(fileURLToPath(import.meta.url));+const repoRoot = resolve(packageDir, '../..');+export default defineConfig({+ resolve: {+ alias: {+ '@': resolve(repoRoot, 'src'),+ },+ },test: {coverage: {provider: 'v8',diff --git a/packages/editor-runtime/src/EditorRuntime.ts b/packages/editor-runtime/src/EditorRuntime.tsindex 7049265d73e..e3386bcdded 100644--- a/packages/editor-runtime/src/EditorRuntime.ts+++ b/packages/editor-runtime/src/EditorRuntime.ts@@ -1,6 +1,6 @@import type { PageContentContext } from '@lobechat/prompts';import type { IEditor } from '@lobehub/editor';-import { LITEXML_APPLY_COMMAND, LITEXML_MODIFY_COMMAND } from '@lobehub/editor';+import { LITEXML_APPLY_COMMAND, LITEXML_MODIFY_COMMAND } from '@lobehub/editor/litexml-commands';import debug from 'debug';import type {@@ -40,6 +40,16 @@ export interface EditorMutationContext {apiName: EditorMutationApiName;}+/**+ * Payload for a single LiteXML modify-batch operation β the runtime shape of+ * the `LITEXML_MODIFY_COMMAND` payload.+ */+export type LiteXMLBatchOperation =+ | { action: 'insert'; afterId: string; litexml: string }+ | { action: 'insert'; beforeId: string; litexml: string }+ | { action: 'modify'; litexml: string | string[] }+ | { action: 'remove'; id: string };+export interface EditorRuntimeDebugSnapshot {currentDocId?: string;dataSourceTypes: string[];@@ -177,6 +187,55 @@ export class EditorRuntime {}}+ /**+ * Apply a snapshot produced by the server-side PageAgent execution runtime+ * onto the currently mounted editor. Skips persistence side-effects: the+ * server already wrote the row, so calling `afterMutateHandler` here would+ * loop the save path back through `commitEditorMutation`.+ *+ * `editorData` is the Lexical `SerializedEditorState` (or `null`/`undefined`+ * when the server only changed metadata such as the title).+ */+ applyServerSnapshot(snapshot: {+ content?: string;+ editorData?: Record<string, unknown> | null;+ title?: string;+ }): boolean {+ let applied = false;++ if (this.editor && snapshot.editorData) {+ try {+ this.editor.setDocument('json', JSON.stringify(snapshot.editorData), { keepId: true });+ applied = true;+ } catch (error) {+ log('[EditorRuntime] applyServerSnapshot:editorData failed', error);+ }+ } else if (this.editor && typeof snapshot.content === 'string') {+ try {+ this.editor.setDocument('markdown', snapshot.content, { keepId: true });+ applied = true;+ } catch (error) {+ log('[EditorRuntime] applyServerSnapshot:markdown failed', error);+ }+ }++ if (typeof snapshot.title === 'string' && this.titleSetter) {+ try {+ this.titleSetter(snapshot.title);+ applied = true;+ } catch (error) {+ log('[EditorRuntime] applyServerSnapshot:title failed', error);+ }+ }++ log('[EditorRuntime] applyServerSnapshot', {+ applied,+ hasEditorData: !!snapshot.editorData,+ hasTitle: typeof snapshot.title === 'string',+ });+ return applied;+ }+/*** Get the current editor instance*/@@ -480,9 +539,7 @@ export class EditorRuntime {throw new Error('modifyNodes failed: LiteXML data source is not ready.');}- // Dispatch all operations at once. The LiteXML command handler returns false- // even after handling the command, so the return value is not a failure signal.- log('Dispatching LITEXML_MODIFY_COMMAND with payload:', commandPayload);+ log('Dispatching LiteXML modify batch with payload:', commandPayload);editor.dispatchCommand(LITEXML_MODIFY_COMMAND, commandPayload);const successCount = results.filter((r) => r.success).length;@@ -773,11 +830,8 @@ export class EditorRuntime {throw new Error('replaceText failed: LiteXML data source is not ready.');}- const dispatchSuccess = editor.dispatchCommand(LITEXML_APPLY_COMMAND, {- litexml: litexmlUpdates,- });-- log('Command dispatched, success:', dispatchSuccess);+ editor.dispatchCommand(LITEXML_APPLY_COMMAND, { litexml: litexmlUpdates });+ log('LiteXML replace dispatched');}const result = { modifiedNodeIds, replacementCount: totalReplacementCount };diff --git a/packages/editor-runtime/src/index.ts b/packages/editor-runtime/src/index.tsindex aade677ea6a..804aa18c8df 100644--- a/packages/editor-runtime/src/index.ts+++ b/packages/editor-runtime/src/index.ts@@ -1,2 +1,2 @@-export { EditorRuntime } from './EditorRuntime';+export { EditorRuntime, type LiteXMLBatchOperation } from './EditorRuntime';export * from './types';diff --git a/src/server/services/toolExecution/serverRuntimes/index.ts b/src/server/services/toolExecution/serverRuntimes/index.tsindex d21375d9262..cebb934cb0e 100644--- a/src/server/services/toolExecution/serverRuntimes/index.ts+++ b/src/server/services/toolExecution/serverRuntimes/index.ts@@ -25,6 +25,7 @@ import { localSystemRuntime } from './localSystem';import { memoryRuntime } from './memory';import { messageRuntime } from './message';import { notebookRuntime } from './notebook';+import { pageAgentRuntime } from './pageAgent';import { remoteDeviceRuntime } from './remoteDevice';import { selfFeedbackIntentRuntime } from './selfFeedbackIntent';import { skillManagementRuntime } from './skillManagement';@@ -81,6 +82,7 @@ registerRuntimes([agentSignalReviewRuntime,agentSignalReflectionRuntime,agentSignalFeedbackIntentRuntime,+ pageAgentRuntime,]);// ==================== Registry API ====================diff --git a/src/server/services/toolExecution/serverRuntimes/pageAgent.ts b/src/server/services/toolExecution/serverRuntimes/pageAgent.tsnew file mode 100644index 00000000000..ff31447c5b6--- /dev/null+++ b/src/server/services/toolExecution/serverRuntimes/pageAgent.ts@@ -0,0 +1,399 @@+import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';+import {+ PageAgentExecutionRuntime,+ type PageAgentInvocationContext,+ type PageAgentRuntimeService,+} from '@lobechat/builtin-tool-page-agent/executionRuntime';+import { EditorRuntime } from '@lobechat/editor-runtime';+import { createHeadlessEditor, type HeadlessEditor } from '@lobehub/editor/headless';+import type { SerializedEditorState, SerializedLexicalNode } from 'lexical';++import { DocumentModel } from '@/database/models/document';+import { type LobeChatDatabase } from '@/database/type';+import { isValidEditorData } from '@/libs/editor/isValidEditorData';+import { DocumentService } from '@/server/services/document';++import type { ServerRuntimeRegistration } from './types';++type SerializedEditor = SerializedEditorState<SerializedLexicalNode>;++type EditorRuntimeEditorParam = Parameters<EditorRuntime['setEditor']>[0];++interface DocumentSnapshot {+ content: string;+ editorData: Record<string, unknown> | null;+ title: string;+}++interface InvocationEnv {+ getTitle: () => string;+ headless: HeadlessEditor;+ runtime: EditorRuntime;+ setTitle: (title: string) => void;+ snapshot: DocumentSnapshot;+}++/**+ * Cheap, dependency-free fingerprint used only to detect whether a mutation+ * actually changed the document body. Collisions are tolerated β at worst we+ * miss a silent-failure warning; we never lose persistence.+ */+const hashEditorData = (data: unknown): string => {+ const json = JSON.stringify(data ?? null);+ let hash = 5381;+ for (let i = 0; i < json.length; i++) {+ hash = (hash * 33) ^ json.charCodeAt(i);+ }+ return `${json.length}:${(hash >>> 0).toString(16)}`;+};++interface InvariantFlags {+ editorChanged: boolean;+ handlerReportedChange: boolean;+ titleChanged: boolean;+}++interface InvariantViolation {+ apiName: string;+ detail: string;+ kind: 'silent-no-op' | 'unexpected-mutation';+}++const detectHandlerReportedChange = (apiName: string, state: Record<string, unknown>): boolean => {+ switch (apiName) {+ case 'modifyNodes': {+ const successCount = state.successCount;+ return typeof successCount === 'number' && successCount > 0;+ }+ case 'replaceText': {+ const count = state.replacementCount;+ return typeof count === 'number' && count > 0;+ }+ case 'initPage': {+ const nodeCount = state.nodeCount;+ return typeof nodeCount === 'number' && nodeCount > 0;+ }+ default: {+ return false;+ }+ }+};++const detectInvariantViolation = (+ apiName: string,+ flags: InvariantFlags,+): InvariantViolation | undefined => {+ // editTitle is exempt: title lives outside editorData, so editorChanged is+ // expected to be false.+ if (apiName === 'editTitle') return undefined;++ if (flags.handlerReportedChange && !flags.editorChanged && !flags.titleChanged) {+ return {+ apiName,+ detail: 'Handler reported successful mutation but exported editorData hash did not change.',+ kind: 'silent-no-op',+ };+ }++ if (!flags.handlerReportedChange && flags.editorChanged) {+ return {+ apiName,+ detail: 'Editor state changed even though handler did not report any successful change.',+ kind: 'unexpected-mutation',+ };+ }++ return undefined;+};++interface PageAgentServiceContext {+ documentModel: DocumentModel;+ documentService: DocumentService;+}++const loadSnapshot = async (+ documentModel: DocumentModel,+ documentId: string,+): Promise<DocumentSnapshot> => {+ const doc = await documentModel.findById(documentId);+ if (!doc) {+ throw new Error(`Page document not found: ${documentId}`);+ }+ return {+ content: doc.content ?? '',+ editorData: (doc.editorData ?? null) as Record<string, unknown> | null,+ title: doc.title ?? 'Untitled',+ };+};++const buildEnv = (snapshot: DocumentSnapshot, documentId: string): InvocationEnv => {+ const headless = createHeadlessEditor();+ let title = snapshot.title;++ if (isValidEditorData(snapshot.editorData)) {+ headless.hydrateEditorData(snapshot.editorData as unknown as SerializedEditor, {+ keepId: true,+ });+ } else if (snapshot.content.trim().length > 0) {+ headless.hydrateMarkdown(snapshot.content, { keepId: true });+ }+ // Otherwise leave the headless editor in its default empty state.++ const runtime = new EditorRuntime();+ // `headless.kernel` is structurally `IEditor`; pnpm may resolve `@lobehub/editor`+ // to a different copy here than `@lobechat/editor-runtime` does, making the two+ // `IEditor` types nominally distinct. They are runtime-identical β bridge via+ // unknown to keep the contract explicit.+ runtime.setEditor(headless.kernel as unknown as EditorRuntimeEditorParam);+ runtime.setCurrentDocId(documentId);+ // `EditorRuntime` dispatches `LITEXML_*_COMMAND` (imported from the DOM-free+ // `@lobehub/editor/litexml-commands` subpath) straight onto the kernel. The+ // headless bundle's `LitexmlPlugin` registers its listeners against the same+ // single command identities, so the dispatch lands without any adapter.+ runtime.setTitleHandlers(+ (next) => {+ title = next;+ },+ () => title,+ );++ return {+ getTitle: () => title,+ headless,+ runtime,+ setTitle: (next) => {+ title = next;+ },+ snapshot,+ };+};++interface WithEditorOptions {+ exportEditorData?: boolean;+ /** Whether to enforce silent-failure invariant checks on this invocation. */+ invariantCheck?: boolean;+ /** Whether to persist any captured patch back to the document row. */+ persist?: boolean;+}++interface HandlerOutput {+ content: string;+ state: Record<string, unknown>;+}++const withEditor = async (+ { documentModel, documentService }: PageAgentServiceContext,+ apiName: string,+ ctx: PageAgentInvocationContext,+ handler: (env: InvocationEnv) => Promise<HandlerOutput>,+ options: WithEditorOptions = {},+): Promise<HandlerOutput> => {+ const documentId = ctx.documentId;+ // The runtime shell already rejected missing documentId; this guard is for+ // type-narrowing only.+ if (!documentId) {+ throw new Error('documentId is required');+ }++ const snapshot = await loadSnapshot(documentModel, documentId);+ const env = buildEnv(snapshot, documentId);+ const exportEditorData = options.exportEditorData !== false;+ const persist = options.persist !== false;+ const invariantCheck = options.invariantCheck !== false;++ try {+ const beforeHash = exportEditorData+ ? hashEditorData(env.headless.export().editorData)+ : undefined;++ const handlerResult = await handler(env);++ const exported = exportEditorData ? env.headless.export() : undefined;+ const afterHash = exported ? hashEditorData(exported.editorData) : undefined;+ const titleChanged = env.getTitle() !== snapshot.title;+ const editorChanged = exportEditorData && beforeHash !== undefined && beforeHash !== afterHash;++ const invariantViolation = invariantCheck+ ? detectInvariantViolation(apiName, {+ editorChanged,+ handlerReportedChange: detectHandlerReportedChange(apiName, handlerResult.state),+ titleChanged,+ })+ : undefined;++ if (invariantViolation) {+ console.warn(+ `[PageAgentServerRuntime] invariant violation in ${apiName}:`,+ invariantViolation,+ { documentId, operationId: ctx.operationId, toolCallId: ctx.toolCallId },+ );+ }++ const patch: {+ content?: string;+ editorData?: Record<string, unknown>;+ title?: string;+ } = {};+ if (exported) {+ patch.content = exported.markdown;+ patch.editorData = exported.editorData as unknown as Record<string, unknown>;+ }+ if (titleChanged) {+ patch.title = env.getTitle();+ }++ if (persist && Object.keys(patch).length > 0) {+ await documentService.updateDocument(documentId, {+ content: patch.content,+ editorData: patch.editorData,+ saveSource: 'llm_call',+ title: patch.title,+ });+ }++ return {+ content: handlerResult.content,+ state: {+ ...handlerResult.state,+ documentContent: patch.content,+ documentEditorData: patch.editorData,+ documentTitle: env.getTitle(),+ ...(invariantViolation ? { invariantViolation } : {}),+ },+ };+ } finally {+ env.headless.destroy();+ }+};++const buildService = (db: LobeChatDatabase, userId: string): PageAgentRuntimeService => {+ const documentModel = new DocumentModel(db, userId);+ const documentService = new DocumentService(db, userId);+ const serviceCtx: PageAgentServiceContext = { documentModel, documentService };++ return {+ editTitle: (args, ctx) =>+ withEditor(+ serviceCtx,+ 'editTitle',+ ctx,+ async ({ runtime }) => {+ const result = await runtime.editTitle(args);+ return {+ content: `Title changed from "${result.previousTitle}" to "${result.newTitle}".`,+ state: { newTitle: result.newTitle, previousTitle: result.previousTitle },+ };+ },+ { exportEditorData: false },+ ),++ getPageContent: (args, ctx) =>+ withEditor(+ serviceCtx,+ 'getPageContent',+ ctx,+ async ({ runtime, getTitle }) => {+ const result = await runtime.getPageContent(args);+ return {+ content: result.markdown || result.xml || '',+ state: {+ markdown: result.markdown,+ metadata: {+ fileType: 'document',+ title: getTitle(),+ totalCharCount: result.charCount,+ totalLineCount: result.lineCount,+ },+ xml: result.xml,+ },+ };+ },+ { persist: false },+ ),++ initPage: (args, ctx) =>+ withEditor(serviceCtx, 'initPage', ctx, async ({ runtime }) => {+ const result = await runtime.initPage(args);+ return {+ content: result.extractedTitle+ ? `Document initialized with ${result.nodeCount} nodes. Title "${result.extractedTitle}" extracted and set.`+ : `Document initialized with ${result.nodeCount} nodes.`,+ state: {+ extractedTitle: result.extractedTitle,+ nodeCount: result.nodeCount,+ rootId: 'root',+ },+ };+ }),++ modifyNodes: (args, ctx) =>+ withEditor(serviceCtx, 'modifyNodes', ctx, async ({ runtime }) => {+ const result = await runtime.modifyNodes(args);+ const operations = Array.isArray(args.operations)+ ? args.operations+ : args.operations+ ? [args.operations]+ : [];+ const actionSummary = operations.reduce<Record<string, number>>((acc, op) => {+ if (!op) return acc;+ acc[op.action] = (acc[op.action] || 0) + 1;+ return acc;+ }, {});+ const summary = Object.entries(actionSummary)+ .map(([action, count]) => `${count} ${action}${count > 1 ? 's' : ''}`)+ .join(', ');+ return {+ content: `Successfully executed ${summary} (${result.successCount}/${result.totalCount} operations succeeded).`,+ state: {+ results: result.results,+ successCount: result.successCount,+ totalCount: result.totalCount,+ },+ };+ }),++ replaceText: (args, ctx) =>+ withEditor(serviceCtx, 'replaceText', ctx, async ({ runtime }) => {+ const result = await runtime.replaceText(args);+ const scope = args.nodeIds?.length+ ? `within ${args.nodeIds.length} specified node(s)`+ : 'across the document';+ const content =+ result.replacementCount > 0+ ? `Successfully replaced ${result.replacementCount} occurrence(s) of "${args.searchText}" with "${args.newText}" ${scope}. Modified ${result.modifiedNodeIds.length} node(s).`+ : `No occurrences of "${args.searchText}" found ${scope}.`;+ return {+ content,+ state: {+ modifiedNodeIds: result.modifiedNodeIds,+ replacementCount: result.replacementCount,+ },+ };+ }),+ };+};++/**+ * Registers the page-agent builtin server runtime.+ *+ * Each tool invocation:+ * 1. loads the `documents` row,+ * 2. hydrates a `@lobehub/editor` HeadlessEditor from `editorData`/`content`,+ * 3. runs the requested page-agent API via the shared `EditorRuntime`,+ * 4. exports the new Lexical state and writes it back via+ * `DocumentService.updateDocument` (saveSource: 'llm_call' β also appends+ * a `documentHistories` snapshot).+ *+ * The renderer's `PageAgentExecutor.onAfterCall` consumes the returned+ * `result.state.document*` fields to apply the new editorData to the live+ * Lexical editor and reconcile the document store.+ */+export const pageAgentRuntime: ServerRuntimeRegistration = {+ factory: (context) => {+ if (!context.userId || !context.serverDB) {+ throw new Error('userId and serverDB are required for Page Agent execution');+ }+ return new PageAgentExecutionRuntime(buildService(context.serverDB, context.userId));+ },+ identifier: PageAgentIdentifier,+};diff --git a/src/store/document/slices/editor/action.ts b/src/store/document/slices/editor/action.tsindex aed3ef92631..359e27655e4 100644--- a/src/store/document/slices/editor/action.ts+++ b/src/store/document/slices/editor/action.ts@@ -182,6 +182,49 @@ export class EditorActionImpl {internal_dispatchDocument({ id: documentId, type: 'updateDocument', value: { isDirty: true } });};+ /**+ * Apply a snapshot returned by the server-side page-agent tool executor.+ * The server has already written `documents.content` / `documents.editorData`,+ * so this only updates in-memory store state to match: clears the dirty flag,+ * advances `lastSaved*` and refreshes `lastUpdatedTime`. Editor-level Lexical+ * application is handled by `EditorRuntime.applyServerSnapshot` upstream.+ */+ applyServerSnapshot = (+ documentId: string,+ snapshot: {+ content?: string;+ editorData?: Record<string, unknown>;+ title?: string;+ },+ ): void => {+ const { documents, internal_dispatchDocument } = this.#get();+ const doc = documents[documentId];+ if (!doc) return;++ const value: Record<string, unknown> = {+ isDirty: false,+ lastUpdatedTime: new Date(),+ saveStatus: 'saved',+ };++ if (typeof snapshot.content === 'string') {+ value.content = snapshot.content;+ value.lastSavedContent = snapshot.content;+ }+ if (snapshot.editorData && isValidEditorData(snapshot.editorData)) {+ value.editorData = structuredClone(snapshot.editorData);+ value.lastSavedEditorData = structuredClone(snapshot.editorData);+ }+ if (typeof snapshot.title === 'string') {+ value.title = snapshot.title;+ }++ internal_dispatchDocument(+ { id: documentId, type: 'updateDocument', value: value as Partial<typeof doc> },+ n('applyServerSnapshot'),+ );+ };+onEditorInit = async (editor: IEditor): Promise<void> => {const { activeDocumentId, documents } = this.#get();if (!editor || !activeDocumentId) return;diff --git a/src/store/tool/slices/builtin/executors/lobe-page-agent.ts b/src/store/tool/slices/builtin/executors/lobe-page-agent.tsindex 23a51f92245..090ebdd3b2f 100644--- a/src/store/tool/slices/builtin/executors/lobe-page-agent.ts+++ b/src/store/tool/slices/builtin/executors/lobe-page-agent.ts@@ -4,7 +4,7 @@* Creates and exports the PageAgentExecutor instance for registration.* Also exports the runtime for editor instance injection.*/-import { PageAgentExecutor } from '@lobechat/builtin-tool-page-agent/executor';+import { PageAgentExecutor } from '@lobechat/builtin-tool-page-agent/client';import { EditorRuntime } from '@lobechat/editor-runtime';// Create singleton instance of the runtime