Skip to content

🀯 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.

✨ feat(knowledge-base): let agents edit existing documents with updateDocument (#23513)

LiJiana26f180d0883
diff --git a/apps/server/src/services/aiAgent/shareGate/dataToolRules.ts b/apps/server/src/services/aiAgent/shareGate/dataToolRules.ts
index c08735a483d..8783c9bf943 100644
--- a/apps/server/src/services/aiAgent/shareGate/dataToolRules.ts
+++ b/apps/server/src/services/aiAgent/shareGate/dataToolRules.ts
@@ -120,6 +120,7 @@ export const DATA_TOOL_ACCESS_RULES: Record<string, DataToolAccessRule> = {
KnowledgeBaseApiName.createKnowledgeBase,
KnowledgeBaseApiName.deleteKnowledgeBase,
KnowledgeBaseApiName.createDocument,
+ KnowledgeBaseApiName.updateDocument,
KnowledgeBaseApiName.addFiles,
KnowledgeBaseApiName.removeFiles,
],
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/knowledgeBase.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/knowledgeBase.test.ts
index 2ce0823c31d..d7e331d8891 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/knowledgeBase.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/knowledgeBase.test.ts
@@ -6,10 +6,13 @@ import { knowledgeBaseRuntime } from '../knowledgeBase';
const mocks = vi.hoisted(() => ({
createDocument: vi.fn(),
+ findKnowledgeBase: vi.fn(),
getAgentAssignedKnowledge: vi.fn(),
getEnabledKnowledgeBaseIds: vi.fn(),
getEnabledKnowledgeBaseIdsForTask: vi.fn(),
+ getDocumentById: vi.fn(),
semanticSearchForChat: vi.fn(),
+ updateDocumentFromInput: vi.fn(),
}));
vi.mock('@/database/models/agent', () => ({
@@ -28,14 +31,22 @@ vi.mock('@/database/models/project', () => ({
}));
vi.mock('@/database/models/file', () => ({ FileModel: vi.fn() }));
-vi.mock('@/database/models/knowledgeBase', () => ({ KnowledgeBaseModel: vi.fn() }));
+vi.mock('@/database/models/knowledgeBase', () => ({
+ KnowledgeBaseModel: vi.fn().mockImplementation(function () {
+ return { findById: mocks.findKnowledgeBase };
+ }),
+}));
+vi.mock('@/database/models/document', () => ({ DocumentModel: vi.fn() }));
vi.mock('@/database/repositories/knowledge', () => ({ KnowledgeRepo: vi.fn() }));
vi.mock('@/server/services/document', () => ({
DocumentService: vi.fn().mockImplementation(function () {
- return { createDocument: mocks.createDocument };
+ return { createDocument: mocks.createDocument, getDocumentById: mocks.getDocumentById };
}),
}));
vi.mock('@/server/services/file', () => ({ FileService: vi.fn() }));
+vi.mock('@/server/services/document/writeFlow', () => ({
+ updateDocumentFromInput: mocks.updateDocumentFromInput,
+}));
vi.mock('@/server/services/knowledgeBase', () => ({
KnowledgeBaseSearchService: vi.fn().mockImplementation(function () {
@@ -148,3 +159,48 @@ describe('knowledgeBaseRuntime createDocument', () => {
);
});
});
+
+describe('knowledgeBaseRuntime updateDocument', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getDocumentById.mockResolvedValue({
+ fileType: 'custom/document',
+ id: 'docs_1',
+ knowledgeBaseId: 'kb_product',
+ title: 'Launch checklist',
+ });
+ mocks.findKnowledgeBase.mockResolvedValue({ id: 'kb_product', name: 'Product' });
+ mocks.updateDocumentFromInput.mockResolvedValue({ historyAppended: true, id: 'docs_1' });
+ });
+
+ it('writes through the shared document write flow as an agent edit', async () => {
+ const result = await createRuntime({
+ operationId: 'op_step',
+ rootOperationId: 'op_root',
+ }).updateDocument({ content: '- ship it\n- announce\n', documentId: 'docs_1' });
+
+ expect(result.success).toBe(true);
+ expect(result.state).toEqual({ id: 'docs_1' });
+ expect(mocks.updateDocumentFromInput).toHaveBeenCalledWith(
+ expect.objectContaining({ userId: 'user_alice' }),
+ {
+ content: '- ship it\n- announce\n',
+ history: { agentId: 'agt_research', operationId: 'op_root' },
+ id: 'docs_1',
+ parentId: undefined,
+ saveSource: 'llm_call',
+ title: undefined,
+ writeSource: 'agent',
+ },
+ );
+ });
+
+ it('does not write when the document belongs to an inaccessible knowledge base', async () => {
+ mocks.findKnowledgeBase.mockResolvedValue(undefined);
+
+ const result = await createRuntime().updateDocument({ documentId: 'docs_1', title: 'x' });
+
+ expect(result.success).toBe(false);
+ expect(mocks.updateDocumentFromInput).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts b/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts
index 86961607354..369df66cb1e 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts
@@ -2,12 +2,14 @@ import { KnowledgeBaseIdentifier } from '@lobechat/builtin-tool-knowledge-base';
import { KnowledgeBaseExecutionRuntime } from '@lobechat/builtin-tool-knowledge-base/executionRuntime';
import { AgentModel } from '@/database/models/agent';
+import { DocumentModel } from '@/database/models/document';
import { FileModel } from '@/database/models/file';
import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
import { ProjectModel } from '@/database/models/project';
import { KnowledgeRepo } from '@/database/repositories/knowledge';
import { DocumentService } from '@/server/services/document';
import { resolveDocumentWrite } from '@/server/services/document/editorData';
+import { updateDocumentFromInput } from '@/server/services/document/writeFlow';
import { FileService } from '@/server/services/file';
import { KnowledgeBaseSearchService } from '@/server/services/knowledgeBase';
import { getKnowledgeBaseIdsMountedByBrowsers } from '@/server/services/knowledgeBaseAccess';
@@ -26,6 +28,7 @@ export const knowledgeBaseRuntime: ServerRuntimeRegistration = {
const projectModel = new ProjectModel(serverDB, userId, workspaceId);
const knowledgeRepo = new KnowledgeRepo(serverDB, userId, workspaceId);
const documentService = new DocumentService(serverDB, userId, workspaceId, agentVisibility);
+ const documentModel = new DocumentModel(serverDB, userId, workspaceId, agentVisibility);
const fileService = new FileService(serverDB, userId, workspaceId);
const searchService = new KnowledgeBaseSearchService(
serverDB,
@@ -192,6 +195,38 @@ export const knowledgeBaseRuntime: ServerRuntimeRegistration = {
});
return { id: doc.id };
},
+ getDocumentById: async (id) => {
+ const doc = await documentService.getDocumentById(id);
+ if (!doc) return undefined;
+ return {
+ fileType: doc.fileType,
+ id: doc.id,
+ knowledgeBaseId: doc.knowledgeBaseId,
+ parentId: doc.parentId,
+ sourceType: doc.sourceType,
+ title: doc.title,
+ };
+ },
+ updateDocument: async ({ content, id, parentId, title }) => {
+ // Same write as the editor and `lh doc edit`: restricted-library and
+ // parent checks, Markdown β†’ editor data, and an open page's live room.
+ const result = await updateDocumentFromInput(
+ { documentModel, documentService, serverDB, userId, workspaceId },
+ {
+ content,
+ history: {
+ agentId,
+ operationId: context.rootOperationId ?? context.operationId,
+ },
+ id,
+ parentId,
+ saveSource: 'llm_call',
+ title,
+ writeSource: 'agent',
+ },
+ );
+ return { id: result.id };
+ },
},
{
getFileItemById: async (id) => {
diff --git a/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/index.ts b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/index.ts
index 5f43f2a5b2e..c86ca102cda 100644
--- a/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/index.ts
@@ -28,6 +28,8 @@ import type {
RemoveFilesArgs,
SearchKnowledgeBaseArgs,
SearchKnowledgeBaseState,
+ UpdateDocumentArgs,
+ UpdateDocumentState,
ViewKnowledgeBaseArgs,
ViewKnowledgeBaseState,
} from '../types';
@@ -77,6 +79,28 @@ interface DocumentResult {
id: string;
}
+interface DocumentDetailResult {
+ fileType: string;
+ id: string;
+ knowledgeBaseId?: string | null;
+ parentId?: string | null;
+ /** `file` = parsed upload, `web` = crawled page; both are derived text, not editable notes. */
+ sourceType?: string | null;
+ title?: string | null;
+}
+
+/** The only document type this tool edits: notes written as text, not parsed uploads. */
+const EDITABLE_DOCUMENT_FILE_TYPE = 'custom/document';
+
+/**
+ * Parsed uploads are stored as `custom/document` too, so the file type alone
+ * cannot tell them from notes; their source type can.
+ */
+const DERIVED_DOCUMENT_SOURCE_TYPES = new Set(['file', 'web']);
+
+/** Upper bound on the ancestor walk; deeper (or already looping) trees are refused. */
+const MAX_PARENT_DEPTH = 64;
+
interface RagService {
getFileContents: (fileIds: string[], signal?: AbortSignal) => Promise<FileContentResult[]>;
semanticSearchForChat: (
@@ -118,6 +142,15 @@ interface DocumentService {
parentId?: string;
title: string;
}) => Promise<DocumentResult>;
+ /** Resolves only documents the caller can access; `undefined` otherwise. */
+ getDocumentById: (id: string) => Promise<DocumentDetailResult | undefined>;
+ /** Fields left `undefined` must stay unchanged. */
+ updateDocument: (params: {
+ content?: string;
+ id: string;
+ parentId?: string;
+ title?: string;
+ }) => Promise<DocumentResult>;
}
interface FileService {
@@ -508,6 +541,136 @@ export class KnowledgeBaseExecutionRuntime {
}
}
+ async updateDocument(args: UpdateDocumentArgs): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ if (!this.documentService) {
+ return { content: 'Document service is not available.', success: false };
+ }
+ // The knowledge base check below is part of the access guard; never skip it.
+ if (!this.knowledgeBaseService) {
+ return { content: 'Knowledge base service is not available.', success: false };
+ }
+
+ const documentId = args.documentId?.trim();
+ if (!documentId) {
+ return { content: 'Error: documentId is required.', success: false };
+ }
+
+ // Models often fill optional fields with "" β€” that means "leave unchanged",
+ // never "erase the body" or "rename to nothing".
+ const content = args.content || undefined;
+ const title = args.title?.trim() ? args.title.trim() : undefined;
+ const parentId = args.parentId?.trim() || undefined;
+
+ if (content === undefined && title === undefined && parentId === undefined) {
+ return {
+ content: 'Error: Nothing to update. Provide at least one of title, content or parentId.',
+ success: false,
+ };
+ }
+
+ const document = await this.documentService.getDocumentById(documentId);
+ if (!document) {
+ return {
+ content: `Document "${documentId}" not found, or you do not have access to it.`,
+ success: false,
+ };
+ }
+
+ if (!document.knowledgeBaseId) {
+ return {
+ content: `Document "${documentId}" is not in a knowledge base, so it cannot be edited with this tool.`,
+ success: false,
+ };
+ }
+
+ if (
+ document.fileType !== EDITABLE_DOCUMENT_FILE_TYPE ||
+ DERIVED_DOCUMENT_SOURCE_TYPES.has(document.sourceType ?? '')
+ ) {
+ return {
+ content: `Document "${documentId}" is an uploaded file or imported web page, not a note, so it cannot be edited. Only documents created as notes (createDocument) can be edited; create a new document instead if needed.`,
+ success: false,
+ };
+ }
+
+ const knowledgeBase = await this.knowledgeBaseService.getKnowledgeBaseById(
+ document.knowledgeBaseId,
+ );
+ if (!knowledgeBase) {
+ return {
+ content: `Document "${documentId}" belongs to a knowledge base you do not have access to.`,
+ success: false,
+ };
+ }
+
+ if (parentId) {
+ if (parentId === documentId) {
+ return { content: 'Error: A document cannot be moved under itself.', success: false };
+ }
+ const parent = await this.documentService.getDocumentById(parentId);
+ if (!parent || parent.knowledgeBaseId !== document.knowledgeBaseId) {
+ return {
+ content: `Parent "${parentId}" not found in knowledge base \`${document.knowledgeBaseId}\`. The new parent must be a folder or document in the same knowledge base.`,
+ success: false,
+ };
+ }
+
+ // Neither the shared write flow nor the model checks ancestry, so a move
+ // under one of the document's own descendants would persist a loop: both
+ // drop out of the tree and subtree walks never terminate.
+ let ancestorId = parent.parentId ?? undefined;
+ let depth = 0;
+ while (ancestorId) {
+ if (ancestorId === documentId) {
+ return {
+ content: `Error: "${parentId}" is inside document "${documentId}", so the document cannot be moved under it.`,
+ success: false,
+ };
+ }
+ if (++depth > MAX_PARENT_DEPTH) {
+ return {
+ content: `Error: Could not verify where "${parentId}" sits in the knowledge base (nesting is too deep), so the document was not moved.`,
+ success: false,
+ };
+ }
+ const ancestor = await this.documentService.getDocumentById(ancestorId);
+ ancestorId = ancestor?.parentId ?? undefined;
+ }
+ }
+
+ const result = await this.documentService.updateDocument({
+ content,
+ id: documentId,
+ parentId,
+ title,
+ });
+
+ if (!result?.id) {
+ return { content: 'Error: Failed to update document.', success: false };
+ }
+
+ const changes: string[] = [];
+ if (content !== undefined) changes.push(`content replaced (${content.length} characters)`);
+ if (title !== undefined) changes.push(`renamed to "${title}"`);
+ if (parentId !== undefined) changes.push(`moved under \`${parentId}\``);
+
+ const state: UpdateDocumentState = { id: result.id };
+
+ return {
+ content: `Document "${title ?? document.title ?? documentId}" (\`${result.id}\`) updated: ${changes.join('; ')}.`,
+ state,
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `Error updating document: ${(e as Error).message}`,
+ error: e,
+ success: false,
+ };
+ }
+ }
+
async addFiles(args: AddFilesArgs): Promise<BuiltinServerRuntimeOutput> {
try {
if (!this.knowledgeBaseService) {
diff --git a/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/updateDocument.test.ts b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/updateDocument.test.ts
new file mode 100644
index 00000000000..c210b29965c
--- /dev/null
+++ b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/updateDocument.test.ts
@@ -0,0 +1,310 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { KnowledgeBaseExecutionRuntime } from './index';
+
+const kbDoc = {
+ fileType: 'custom/document',
+ id: 'docs_a',
+ knowledgeBaseId: 'kb_1',
+ title: 'Roadmap',
+};
+
+const setup = (
+ documents: Record<
+ string,
+ Partial<typeof kbDoc> & { knowledgeBaseId?: string | null; parentId?: string | null }
+ > = {
+ docs_a: kbDoc,
+ },
+ knowledgeBases: string[] = ['kb_1'],
+) => {
+ const documentService = {
+ createDocument: vi.fn(),
+ getDocumentById: vi.fn(async (id: string) => documents[id] as any),
+ updateDocument: vi.fn(async ({ id }: { id: string }) => ({ id })),
+ };
+ const knowledgeBaseService = {
+ addFilesToKnowledgeBase: vi.fn(),
+ createKnowledgeBase: vi.fn(),
+ getKnowledgeBaseById: vi.fn(async (id: string) =>
+ knowledgeBases.includes(id)
+ ? { avatar: null, id, name: id, updatedAt: new Date() }
+ : undefined,
+ ),
+ getKnowledgeBases: vi.fn(),
+ getKnowledgeItems: vi.fn(),
+ removeFilesFromKnowledgeBase: vi.fn(),
+ removeKnowledgeBase: vi.fn(),
+ };
+ const ragService = { getFileContents: vi.fn(), semanticSearchForChat: vi.fn() };
+ const runtime = new KnowledgeBaseExecutionRuntime(
+ ragService,
+ knowledgeBaseService,
+ documentService,
+ );
+ return { documentService, knowledgeBaseService, runtime };
+};
+
+describe('KnowledgeBaseExecutionRuntime.updateDocument', () => {
+ it('replaces the content in place and keeps the document id', async () => {
+ const { documentService, runtime } = setup();
+
+ const result = await runtime.updateDocument({ content: '# v2\nbody', documentId: 'docs_a' });
+
+ expect(result.success).toBe(true);
+ expect(result.state).toEqual({ id: 'docs_a' });
+ expect(result.content).toContain('content replaced (9 characters)');
+ expect(documentService.updateDocument).toHaveBeenCalledWith({
+ content: '# v2\nbody',
+ id: 'docs_a',
+ parentId: undefined,
+ title: undefined,
+ });
+ });
+
+ it('renames without sending content, so the body is not overwritten', async () => {
+ const { documentService, runtime } = setup();
+
+ const result = await runtime.updateDocument({ documentId: 'docs_a', title: 'Roadmap 2027' });
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('renamed to "Roadmap 2027"');
+ const params = documentService.updateDocument.mock.calls[0][0];
+ expect(params.content).toBeUndefined();
+ expect(params.title).toBe('Roadmap 2027');
+ });
+
+ it('treats empty strings as unchanged fields', async () => {
+ const { documentService, runtime } = setup();
+
+ const result = await runtime.updateDocument({
+ content: '',
+ documentId: 'docs_a',
+ parentId: '',
+ title: 'New',
+ });
+
+ expect(result.success).toBe(true);
+ expect(documentService.updateDocument).toHaveBeenCalledWith({
+ content: undefined,
+ id: 'docs_a',
+ parentId: undefined,
+ title: 'New',
+ });
+ });
+
+ it('fails when no field to change is given', async () => {
+ const { documentService, runtime } = setup();
+
+ const result = await runtime.updateDocument({ content: '', documentId: 'docs_a', title: ' ' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('at least one of title, content or parentId');
+ expect(documentService.updateDocument).not.toHaveBeenCalled();
+ });
+
+ it('fails when documentId is missing', async () => {
+ const { runtime } = setup();
+
+ const result = await runtime.updateDocument({ documentId: ' ', title: 'x' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toBe('Error: documentId is required.');
+ });
+
+ it('fails when the document is not found or not accessible', async () => {
+ const { documentService, runtime } = setup();
+
+ const result = await runtime.updateDocument({ documentId: 'docs_missing', title: 'x' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('not found, or you do not have access to it');
+ expect(documentService.updateDocument).not.toHaveBeenCalled();
+ });
+
+ it('refuses file-backed documents such as parsed PDFs', async () => {
+ const { documentService, runtime } = setup({
+ docs_pdf: { fileType: 'application/pdf', id: 'docs_pdf', knowledgeBaseId: 'kb_1' },
+ });
+
+ const result = await runtime.updateDocument({ content: 'x', documentId: 'docs_pdf' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('is an uploaded file or imported web page, not a note');
+ expect(documentService.updateDocument).not.toHaveBeenCalled();
+ });
+
+ // Regression: parseFile stores parsed uploads as custom/document with
+ // sourceType 'file', so a fileType-only guard let the tool overwrite them.
+ it.each(['file', 'web'])(
+ 'refuses %s-sourced documents even when stored as custom/document',
+ async (sourceType) => {
+ const { documentService, runtime } = setup({
+ docs_parsed: {
+ fileType: 'custom/document',
+ id: 'docs_parsed',
+ knowledgeBaseId: 'kb_1',
+ sourceType,
+ } as any,
+ });
+
+ const result = await runtime.updateDocument({ content: 'x', documentId: 'docs_parsed' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('is an uploaded file or imported web page, not a note');
+ expect(documentService.updateDocument).not.toHaveBeenCalled();
+ },
+ );
+
+ it('refuses documents outside any knowledge base', async () => {
+ const { documentService, runtime } = setup({
+ docs_page: { fileType: 'custom/document', id: 'docs_page', knowledgeBaseId: null },
+ });
+
+ const result = await runtime.updateDocument({ content: 'x', documentId: 'docs_page' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('is not in a knowledge base');
+ expect(documentService.updateDocument).not.toHaveBeenCalled();
+ });
+
+ it('refuses documents whose knowledge base the caller cannot access', async () => {
+ const { documentService, runtime } = setup(
+ { docs_a: { ...kbDoc, knowledgeBaseId: 'kb_private' } },
+ ['kb_1'],
+ );
+
+ const result = await runtime.updateDocument({ content: 'x', documentId: 'docs_a' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('knowledge base you do not have access to');
+ expect(documentService.updateDocument).not.toHaveBeenCalled();
+ });
+
+ it('moves under a parent in the same knowledge base', async () => {
+ const { documentService, runtime } = setup({
+ docs_a: kbDoc,
+ docs_folder: { fileType: 'custom/folder', id: 'docs_folder', knowledgeBaseId: 'kb_1' },
+ });
+
+ const result = await runtime.updateDocument({ documentId: 'docs_a', parentId: 'docs_folder' });
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('moved under `docs_folder`');
+ expect(documentService.updateDocument).toHaveBeenCalledWith({
+ content: undefined,
+ id: 'docs_a',
+ parentId: 'docs_folder',
+ title: undefined,
+ });
+ });
+
+ it('refuses a parent from another knowledge base or the document itself', async () => {
+ const { documentService, runtime } = setup({
+ docs_a: kbDoc,
+ docs_other: { fileType: 'custom/folder', id: 'docs_other', knowledgeBaseId: 'kb_2' },
+ });
+
+ const crossKb = await runtime.updateDocument({ documentId: 'docs_a', parentId: 'docs_other' });
+ const self = await runtime.updateDocument({ documentId: 'docs_a', parentId: 'docs_a' });
+
+ expect(crossKb.success).toBe(false);
+ expect(crossKb.content).toContain('must be a folder or document in the same knowledge base');
+ expect(self.success).toBe(false);
+ expect(documentService.updateDocument).not.toHaveBeenCalled();
+ });
+
+ it('refuses a parent nested inside the document being moved', async () => {
+ // docs_a > docs_section > docs_leaf: moving docs_a under docs_leaf would close a loop.
+ const { documentService, runtime } = setup({
+ docs_a: kbDoc,
+ docs_leaf: {
+ fileType: 'custom/document',
+ id: 'docs_leaf',
+ knowledgeBaseId: 'kb_1',
+ parentId: 'docs_section',
+ },
+ docs_section: {
+ fileType: 'custom/folder',
+ id: 'docs_section',
+ knowledgeBaseId: 'kb_1',
+ parentId: 'docs_a',
+ },
+ });
+
+ const result = await runtime.updateDocument({ documentId: 'docs_a', parentId: 'docs_leaf' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('is inside document "docs_a"');
+ expect(documentService.updateDocument).not.toHaveBeenCalled();
+ });
+
+ it('moves under a nested folder whose ancestors do not include the document', async () => {
+ const { documentService, runtime } = setup({
+ docs_a: kbDoc,
+ docs_child: {
+ fileType: 'custom/folder',
+ id: 'docs_child',
+ knowledgeBaseId: 'kb_1',
+ parentId: 'docs_top',
+ },
+ docs_top: { fileType: 'custom/folder', id: 'docs_top', knowledgeBaseId: 'kb_1' },
+ });
+
+ const result = await runtime.updateDocument({ documentId: 'docs_a', parentId: 'docs_child' });
+
+ expect(result.success).toBe(true);
+ expect(documentService.updateDocument).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'docs_a', parentId: 'docs_child' }),
+ );
+ });
+
+ it('refuses the move when the ancestor chain already loops', async () => {
+ const { documentService, runtime } = setup({
+ docs_a: kbDoc,
+ docs_x: {
+ fileType: 'custom/folder',
+ id: 'docs_x',
+ knowledgeBaseId: 'kb_1',
+ parentId: 'docs_y',
+ },
+ docs_y: {
+ fileType: 'custom/folder',
+ id: 'docs_y',
+ knowledgeBaseId: 'kb_1',
+ parentId: 'docs_x',
+ },
+ });
+
+ const result = await runtime.updateDocument({ documentId: 'docs_a', parentId: 'docs_x' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('nesting is too deep');
+ expect(documentService.updateDocument).not.toHaveBeenCalled();
+ });
+
+ it('reports a missing document service', async () => {
+ const runtime = new KnowledgeBaseExecutionRuntime({
+ getFileContents: vi.fn(),
+ semanticSearchForChat: vi.fn(),
+ });
+
+ const result = await runtime.updateDocument({ documentId: 'docs_a', title: 'x' });
+
+ expect(result).toEqual({ content: 'Document service is not available.', success: false });
+ });
+
+ it('surfaces errors thrown by the write', async () => {
+ const { documentService, runtime } = setup();
+ documentService.updateDocument.mockRejectedValueOnce(
+ new Error('Document is being edited by another user'),
+ );
+
+ const result = await runtime.updateDocument({ content: 'x', documentId: 'docs_a' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toBe(
+ 'Error updating document: Document is being edited by another user',
+ );
+ });
+});
diff --git a/packages/builtin-tool-knowledge-base/src/client/executor/index.ts b/packages/builtin-tool-knowledge-base/src/client/executor/index.ts
index 89a6fd2dd59..a27b51549e2 100644
--- a/packages/builtin-tool-knowledge-base/src/client/executor/index.ts
+++ b/packages/builtin-tool-knowledge-base/src/client/executor/index.ts
@@ -21,6 +21,7 @@ import type {
ReadKnowledgeArgs,
RemoveFilesArgs,
SearchKnowledgeBaseArgs,
+ UpdateDocumentArgs,
ViewKnowledgeBaseArgs,
} from '../../types';
import { KnowledgeBaseApiName, KnowledgeBaseIdentifier } from '../../types';
@@ -103,6 +104,28 @@ class KnowledgeBaseExecutor extends BaseExecutor<typeof KnowledgeBaseApiName> {
const doc = await lambdaClient.document.createDocument.mutate(params);
return { id: doc.id };
},
+ getDocumentById: async (id) => {
+ const doc = await lambdaClient.document.getDocumentById.query({ id });
+ if (!doc) return undefined;
+ return {
+ fileType: doc.fileType,
+ id: doc.id,
+ knowledgeBaseId: doc.knowledgeBaseId,
+ parentId: doc.parentId,
+ sourceType: doc.sourceType,
+ title: doc.title,
+ };
+ },
+ updateDocument: async ({ content, id, parentId, title }) => {
+ const result = await lambdaClient.document.updateDocument.mutate({
+ content,
+ id,
+ parentId,
+ saveSource: 'llm_call',
+ title,
+ });
+ return { id: result?.id ?? id };
+ },
},
{
getFileItemById: async (id) => {
@@ -210,6 +233,10 @@ class KnowledgeBaseExecutor extends BaseExecutor<typeof KnowledgeBaseApiName> {
return this.toResult(await this.runtime.createDocument(params));
};
+ updateDocument = async (params: UpdateDocumentArgs): Promise<BuiltinToolResult> => {
+ return this.toResult(await this.runtime.updateDocument(params));
+ };
+
addFiles = async (params: AddFilesArgs): Promise<BuiltinToolResult> => {
return this.toResult(await this.runtime.addFiles(params));
};
diff --git a/packages/builtin-tool-knowledge-base/src/index.ts b/packages/builtin-tool-knowledge-base/src/index.ts
index 44143ad7a54..8d36bb37e1a 100644
--- a/packages/builtin-tool-knowledge-base/src/index.ts
+++ b/packages/builtin-tool-knowledge-base/src/index.ts
@@ -24,6 +24,8 @@ export {
type RemoveFilesArgs,
type SearchKnowledgeBaseArgs,
type SearchKnowledgeBaseState,
+ type UpdateDocumentArgs,
+ type UpdateDocumentState,
type ViewKnowledgeBaseArgs,
type ViewKnowledgeBaseState,
} from './types';
diff --git a/packages/builtin-tool-knowledge-base/src/manifest.test.ts b/packages/builtin-tool-knowledge-base/src/manifest.test.ts
index 330b5765226..34230b6f659 100644
--- a/packages/builtin-tool-knowledge-base/src/manifest.test.ts
+++ b/packages/builtin-tool-knowledge-base/src/manifest.test.ts
@@ -17,4 +17,20 @@ describe('KnowledgeBaseManifest', () => {
expect(search?.description).toContain('otherwise tell the user');
expect(search?.description).not.toContain('read those directly with readKnowledge');
});
+
+ it('exposes updateDocument with only documentId required and points edits away from createDocument', () => {
+ const update = KnowledgeBaseManifest.api.find(
+ (api) => api.name === KnowledgeBaseApiName.updateDocument,
+ );
+
+ expect(update?.parameters.required).toEqual(['documentId']);
+ expect(Object.keys(update?.parameters.properties ?? {}).sort()).toEqual([
+ 'content',
+ 'documentId',
+ 'parentId',
+ 'title',
+ ]);
+ expect(update?.description).toContain('Provide at least one of title, content or parentId');
+ expect(update?.description).toContain('createDocument only creates new documents');
+ });
});
diff --git a/packages/builtin-tool-knowledge-base/src/manifest.ts b/packages/builtin-tool-knowledge-base/src/manifest.ts
index b04d918d256..031ca4e31c0 100644
--- a/packages/builtin-tool-knowledge-base/src/manifest.ts
+++ b/packages/builtin-tool-knowledge-base/src/manifest.ts
@@ -213,6 +213,35 @@ export const KnowledgeBaseManifest: BuiltinToolManifest = {
type: 'object',
},
},
+ {
+ description:
+ 'Edit an existing text/markdown document in a knowledge base in place: replace its content, rename it, or move it under another folder. The document keeps its ID, so existing references stay valid β€” use this instead of creating a new document to revise one; createDocument only creates new documents. Get the documentId from documents[].documentId in searchKnowledgeBase results or from the item list of viewKnowledgeBase. Provide at least one of title, content or parentId; omitted fields are left unchanged, so to only rename or move a document, do not send content. Only documents created as notes (custom/document) can be edited; uploaded files such as parsed PDFs cannot.',
+ name: KnowledgeBaseApiName.updateDocument,
+ parameters: {
+ properties: {
+ content: {
+ description:
+ 'New full text or markdown content. It replaces the whole current body, so read the document first with readKnowledge and send the complete revised text. Omit to keep the current content.',
+ type: 'string',
+ },
+ documentId: {
+ description: 'The ID of the document to edit (docs_*).',
+ type: 'string',
+ },
+ parentId: {
+ description:
+ 'Optional ID of a folder or document in the same knowledge base to move this document under. Omit to keep its current location.',
+ type: 'string',
+ },
+ title: {
+ description: 'New title of the document. Omit to keep the current title.',
+ type: 'string',
+ },
+ },
+ required: ['documentId'],
+ type: 'object',
+ },
+ },
{
description:
'Add existing files to a knowledge base by their file IDs. The files must already exist in the system.',
diff --git a/packages/builtin-tool-knowledge-base/src/systemRole.test.ts b/packages/builtin-tool-knowledge-base/src/systemRole.test.ts
index 344e910328b..8a5cfa06f08 100644
--- a/packages/builtin-tool-knowledge-base/src/systemRole.test.ts
+++ b/packages/builtin-tool-knowledge-base/src/systemRole.test.ts
@@ -27,4 +27,13 @@ describe('systemPrompt', () => {
'Treat any sandbox/CLI file-listing command as a last-resort fallback only, after both listFiles and searchKnowledgeBase have been tried.',
);
});
+
+ it('should route edits of existing documents to updateDocument instead of recreating them', () => {
+ expect(systemPrompt).toContain(
+ "10. Edit an existing document's content, title or location in place (updateDocument)",
+ );
+ expect(systemPrompt).toContain(
+ 'To change an existing document use updateDocument, do not recreate it.',
+ );
+ });
});
diff --git a/packages/builtin-tool-knowledge-base/src/systemRole.ts b/packages/builtin-tool-knowledge-base/src/systemRole.ts
index 4d29592670c..711e92be6a5 100644
--- a/packages/builtin-tool-knowledge-base/src/systemRole.ts
+++ b/packages/builtin-tool-knowledge-base/src/systemRole.ts
@@ -25,8 +25,9 @@ When a user uploads files (images, PDFs, documents, etc.), they go into the reso
7. Create a new knowledge base (createKnowledgeBase)
8. Delete a knowledge base (deleteKnowledgeBase)
9. Create a document in a knowledge base (createDocument)
-10. Add existing files to a knowledge base (addFiles)
-11. Remove files from a knowledge base (removeFiles)
+10. Edit an existing document's content, title or location in place (updateDocument)
+11. Add existing files to a knowledge base (addFiles)
+12. Remove files from a knowledge base (removeFiles)
</core_capabilities>
<workflow>
@@ -47,7 +48,8 @@ When a user uploads files (images, PDFs, documents, etc.), they go into the reso
1. Use listKnowledgeBases to check existing knowledge bases
2. Use createKnowledgeBase to create a new one if needed
3. Use createDocument to add text/markdown content directly
-4. Use addFiles/removeFiles to manage file associations
+4. Use updateDocument to revise, rename or move an existing document β€” never delete and recreate it, which gives it a new ID and breaks existing references
+5. Use addFiles/removeFiles to manage file associations
</workflow>
<tool_selection_guidelines>
@@ -67,7 +69,8 @@ When a user uploads files (images, PDFs, documents, etc.), they go into the reso
**Knowledge base management:**
- **createKnowledgeBase**: Create a new knowledge base with a name and optional description.
- **deleteKnowledgeBase**: Permanently remove a knowledge base. Use with caution.
-- **createDocument**: Add text/markdown notes directly to a knowledge base without file upload.
+- **createDocument**: Add text/markdown notes directly to a knowledge base without file upload. Only for new documents.
+- **updateDocument**: Edit an existing document in place by documentId (from searchKnowledgeBase documents[].documentId or viewKnowledgeBase). To change an existing document use updateDocument, do not recreate it. Pass only the fields to change: content replaces the whole body (read it first with readKnowledge), and a rename or move must not send content. Uploaded files (parsed PDFs, etc.) cannot be edited.
- **addFiles**: Associate existing files (by ID) with a knowledge base. Use to organize resource library files into knowledge bases.
- **removeFiles**: Dissociate files from a knowledge base (files are not deleted, only unlinked).
</tool_selection_guidelines>
diff --git a/packages/builtin-tool-knowledge-base/src/types.ts b/packages/builtin-tool-knowledge-base/src/types.ts
index 1c4cbd34a52..3d2f396d87d 100644
--- a/packages/builtin-tool-knowledge-base/src/types.ts
+++ b/packages/builtin-tool-knowledge-base/src/types.ts
@@ -13,6 +13,7 @@ export const KnowledgeBaseApiName = {
readKnowledge: 'readKnowledge',
removeFiles: 'removeFiles',
searchKnowledgeBase: 'searchKnowledgeBase',
+ updateDocument: 'updateDocument',
viewKnowledgeBase: 'viewKnowledgeBase',
};
@@ -150,6 +151,24 @@ export interface CreateDocumentState {
id: string;
}
+/**
+ * Edit an existing knowledge base document in place, keeping its ID. At least
+ * one of `title`, `content` or `parentId` must be set; an omitted field is left
+ * unchanged.
+ */
+export interface UpdateDocumentArgs {
+ /** Full replacement body (Markdown). Omit to keep the current body. */
+ content?: string;
+ documentId: string;
+ /** Folder or document in the same knowledge base to move the document under. */
+ parentId?: string;
+ title?: string;
+}
+
+export interface UpdateDocumentState {
+ id: string;
+}
+
export interface AddFilesArgs {
fileIds: string[];
knowledgeBaseId: string;