π€― 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
π fix(agent-documents): present documents as clickable links, centralize result strings (#15989)
Arvin Xu7f45a8d73002
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.tsindex 6c906f355af..90d6c67cf14 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts@@ -220,7 +220,9 @@ describe('agentDocumentsRuntime auto-pin to task', () => {{ agentId: 'agent-1' },);- expect(result.content).toBe('Created document "Daily Brief" (agent-doc-assoc-id).');+ expect(result.content).toBe(+ 'Created document "Daily Brief" (internal id: agent-doc-assoc-id).',+ );});});@@ -283,7 +285,9 @@ describe('AgentDocumentsExecutionRuntime.createDocument', () => {expect(result.content).toContain('https://app.example.com/agent/agent-1/docs/docs_document-row-id',);- expect(result.content).toContain('Use id agent-doc-assoc-id for further edits');+ expect(result.content).toContain('clickable markdown link');+ expect(result.content).toContain('Internal id agent-doc-assoc-id');+ expect(result.content).toContain('never show it to the user');});it('refuses to run without agentId', async () => {diff --git a/packages/builtin-tool-agent-documents/package.json b/packages/builtin-tool-agent-documents/package.jsonindex d5dce379c0f..fee9206f0b0 100644--- a/packages/builtin-tool-agent-documents/package.json+++ b/packages/builtin-tool-agent-documents/package.json@@ -9,6 +9,9 @@"./executionRuntime": "./src/ExecutionRuntime/index.ts"},"main": "./src/index.ts",+ "dependencies": {+ "@lobechat/prompts": "workspace:*"+ },"devDependencies": {"@lobechat/types": "workspace:*"},diff --git a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.tsindex 1c9226374f8..78f59395f89 100644--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts@@ -1,3 +1,12 @@+import {+ formatCopyDocumentResult,+ formatCreateDocumentResult,+ formatModifyDocumentResult,+ formatRemoveDocumentResult,+ formatRenameDocumentResult,+ formatReplaceDocumentResult,+ formatUpdateLoadRuleResult,+} from '@lobechat/prompts';import type { BuiltinServerRuntimeOutput } from '@lobechat/types';import type {@@ -155,6 +164,17 @@ export class AgentDocumentsExecutionRuntime {return context.agentId;}+ /**+ * Resolve a shareable document url so every document-referencing result can+ * hand the user a clickable link instead of a raw internal id. Returns+ * undefined when no url builder is configured or the `documents` row id is+ * unknown β callers fall back to the id-only result wording in that case.+ */+ private buildDocumentUrl(agentId: string, documentId?: string): MaybePromise<string | undefined> {+ if (!documentId) return undefined;+ return this.options.getDocumentUrl?.({ agentId, documentId });+ }+private getCurrentDocumentId(context?: AgentDocumentOperationContext) {if (context?.scope !== 'page') return;return context.currentDocumentId ?? undefined;@@ -252,12 +272,20 @@ export class AgentDocumentsExecutionRuntime {scope === 'currentTopic'? await this.service.listTopicDocuments({ agentId, scope, sourceType, topicId: topicId! }): await this.service.listDocuments({ agentId, scope, sourceType });- const list = docs.map((d) => ({- ...(d.documentId ? { documentId: d.documentId } : {}),- filename: d.filename ?? d.title ?? '',- id: d.id,- title: d.title,- }));+ const list = await Promise.all(+ docs.map(async (d) => {+ const url = await this.buildDocumentUrl(agentId, d.documentId);+ return {+ ...(d.documentId ? { documentId: d.documentId } : {}),+ filename: d.filename ?? d.title ?? '',+ id: d.id,+ title: d.title,+ // The clickable link lets the agent reference any listed document to+ // the user; omitted when no url builder is configured.+ ...(url ? { url } : {}),+ };+ }),+ );return {content: JSON.stringify(list),@@ -303,14 +331,10 @@ export class AgentDocumentsExecutionRuntime {// The document route is keyed by the `documents` id; the URL lets the agent// hand the user a clickable link. `created.id` (the agentDocuments row id)// is kept separately because subsequent edit/read/remove calls key off it.- const url = created.documentId- ? await this.options.getDocumentUrl?.({ agentId, documentId: created.documentId })- : undefined;+ const url = await this.buildDocumentUrl(agentId, created.documentId);return {- content: url- ? `Created document "${title}" (${url}). Use id ${created.id} for further edits.`- : `Created document "${title}" (${created.id}).`,+ content: formatCreateDocumentResult({ id: created.id, title, url }),state: { agentDocumentId: created.id, documentId: created.documentId },success: true,};@@ -362,8 +386,14 @@ export class AgentDocumentsExecutionRuntime {const doc = await this.service.replaceDocumentContent({ ...args, agentId });if (!doc) return { content: `Failed to update document ${args.id}.`, success: false };+ const url = await this.buildDocumentUrl(agentId, doc.documentId ?? existing.documentId);+return {- content: `Updated document ${args.id}.`,+ content: formatReplaceDocumentResult({+ id: args.id,+ title: doc.title ?? existing.title,+ url,+ }),state: { id: args.id, updated: true },success: true,};@@ -401,8 +431,15 @@ export class AgentDocumentsExecutionRuntime {success: true,}));+ const url = await this.buildDocumentUrl(agentId, updated.documentId ?? existing.documentId);+return {- content: `Modified document ${args.id}. Applied ${results.length} operation(s).`,+ content: formatModifyDocumentResult({+ id: args.id,+ operationCount: results.length,+ title: updated.title ?? existing.title,+ url,+ }),state: {id: args.id,results,@@ -429,7 +466,7 @@ export class AgentDocumentsExecutionRuntime {if (!deleted) return { content: `Document not found: ${args.id}`, success: false };return {- content: `Removed document ${args.id}.`,+ content: formatRemoveDocumentResult({ id: args.id }),state: { deleted: true, id: args.id },success: true,};@@ -457,8 +494,10 @@ export class AgentDocumentsExecutionRuntime {const doc = await this.service.renameDocument({ ...args, agentId });if (!doc) return { content: `Failed to rename document ${args.id}.`, success: false };+ const url = await this.buildDocumentUrl(agentId, doc.documentId ?? existing.documentId);+return {- content: `Renamed document ${args.id} to "${args.newTitle}".`,+ content: formatRenameDocumentResult({ id: args.id, title: args.newTitle, url }),state: { id: args.id, newTitle: args.newTitle, renamed: true },success: true,};@@ -479,8 +518,15 @@ export class AgentDocumentsExecutionRuntime {const copied = await this.service.copyDocument({ ...args, agentId });if (!copied) return { content: `Document not found: ${args.id}`, success: false };+ const url = await this.buildDocumentUrl(agentId, copied.documentId);+return {- content: `Copied document ${args.id} to ${copied.id}.`,+ content: formatCopyDocumentResult({+ fromId: args.id,+ id: copied.id,+ title: copied.title,+ url,+ }),state: { copiedFromId: args.id, newDocumentId: copied.id },success: true,};@@ -501,8 +547,10 @@ export class AgentDocumentsExecutionRuntime {const updated = await this.service.updateLoadRule({ ...args, agentId });if (!updated) return { content: `Document not found: ${args.id}`, success: false };+ const url = await this.buildDocumentUrl(agentId, updated.documentId);+return {- content: `Updated load rule for document ${args.id}.`,+ content: formatUpdateLoadRuleResult({ id: args.id, title: updated.title, url }),state: { applied: true, rule: args.rule },success: true,};diff --git a/packages/builtin-tool-agent-documents/src/systemRole.ts b/packages/builtin-tool-agent-documents/src/systemRole.tsindex 5f5a8299626..d87fd72558b 100644--- a/packages/builtin-tool-agent-documents/src/systemRole.ts+++ b/packages/builtin-tool-agent-documents/src/systemRole.ts@@ -46,7 +46,8 @@ export const systemPrompt = `You have access to an Agent Documents tool for crea<response_format>When using this tool:1. Confirm the action taken.-2. Include key identifiers (document ID/title) in the response.-3. Clearly explain if something is not found or if an operation failed.+2. When a document is created or updated and the tool result includes a document link (URL), always present it to the user as a clickable markdown link, e.g. [document title](url). This is the primary way the user opens the document.+3. Never expose the internal document ID to the user. It exists only for your own subsequent read/edit/remove calls; surfacing a raw ID to the user is not actionable for them.+4. Clearly explain if something is not found or if an operation failed.</response_format>`;diff --git a/packages/prompts/src/prompts/agentDocuments/formatResults.test.ts b/packages/prompts/src/prompts/agentDocuments/formatResults.test.tsnew file mode 100644index 00000000000..18f45deadd9--- /dev/null+++ b/packages/prompts/src/prompts/agentDocuments/formatResults.test.ts@@ -0,0 +1,73 @@+import { describe, expect, it } from 'vitest';++import {+ formatCopyDocumentResult,+ formatCreateDocumentResult,+ formatModifyDocumentResult,+ formatRemoveDocumentResult,+ formatRenameDocumentResult,+ formatReplaceDocumentResult,+ formatUpdateLoadRuleResult,+} from './formatResults';++const URL = 'https://app.example.com/agent/agent-1/docs/docs_row';++describe('agentDocuments formatResults', () => {+ describe('with a url present', () => {+ it('formats create with a clickable link and the internal id hidden', () => {+ expect(formatCreateDocumentResult({ id: 'assoc-id', title: 'Daily Brief', url: URL })).toBe(+ `Created document "Daily Brief". Share this link with the user as a clickable markdown link: ${URL}. (Internal id assoc-id β for your own further edit/read/remove calls only; never show it to the user.)`,+ );+ });++ it('formats replace', () => {+ expect(formatReplaceDocumentResult({ id: 'a', title: 'T', url: URL })).toBe(+ `Updated document "T". Share this link with the user as a clickable markdown link: ${URL}. (Internal id a β for your own further edit/read/remove calls only; never show it to the user.)`,+ );+ });++ it('formats rename with the new title', () => {+ expect(formatRenameDocumentResult({ id: 'a', title: 'New Title', url: URL })).toBe(+ `Renamed document to "New Title". Share this link with the user as a clickable markdown link: ${URL}. (Internal id a β for your own further edit/read/remove calls only; never show it to the user.)`,+ );+ });++ it('formats update-load-rule', () => {+ expect(formatUpdateLoadRuleResult({ id: 'a', title: 'T', url: URL })).toBe(+ `Updated load rule for document "T". Share this link with the user as a clickable markdown link: ${URL}. (Internal id a β for your own further edit/read/remove calls only; never show it to the user.)`,+ );+ });++ it('formats modify with the operation count', () => {+ expect(formatModifyDocumentResult({ id: 'a', operationCount: 3, title: 'T', url: URL })).toBe(+ `Modified document "T", applied 3 operation(s). Share this link with the user as a clickable markdown link: ${URL}. (Internal id a β for your own further edit/read/remove calls only; never show it to the user.)`,+ );+ });++ it('formats copy naming both source and new document', () => {+ expect(+ formatCopyDocumentResult({ fromId: 'src-id', id: 'new-id', title: 'Copy', url: URL }),+ ).toBe(+ `Copied document src-id to a new document "Copy". Share this link with the user as a clickable markdown link: ${URL}. (Internal id new-id β for your own further edit/read/remove calls only; never show it to the user.)`,+ );+ });+ });++ describe('without a url', () => {+ it('falls back to exposing the id as the only handle', () => {+ expect(formatCreateDocumentResult({ id: 'assoc-id', title: 'Daily Brief' })).toBe(+ 'Created document "Daily Brief" (internal id: assoc-id).',+ );+ });++ it('uses a generic label when no title is provided', () => {+ expect(formatReplaceDocumentResult({ id: 'assoc-id' })).toBe(+ 'Updated document the document (internal id: assoc-id).',+ );+ });+ });++ it('reports removal with only the id (no live url to share)', () => {+ expect(formatRemoveDocumentResult({ id: 'assoc-id' })).toBe('Removed document assoc-id.');+ });+});diff --git a/packages/prompts/src/prompts/agentDocuments/formatResults.ts b/packages/prompts/src/prompts/agentDocuments/formatResults.tsnew file mode 100644index 00000000000..dfea0ad7d4c--- /dev/null+++ b/packages/prompts/src/prompts/agentDocuments/formatResults.ts@@ -0,0 +1,94 @@+export interface AgentDocumentWriteResultParams {+ /**+ * The `agentDocuments` association row id. It is the handle the agent uses for+ * subsequent read/edit/remove calls β it is NOT actionable for the end user,+ * so it must never be surfaced to them when a shareable url exists.+ */+ id: string;+ /** Document title, used as the human-facing label. */+ title?: string;+ /**+ * Shareable url that opens the document. When present, the agent is told to+ * relay it as a clickable markdown link; otherwise the id is the only handle.+ */+ url?: string;+}++const titleLabel = (title?: string): string => (title ? `"${title}"` : 'the document');++/**+ * Render a write-class tool result with a consistent link/id policy.+ *+ * `lead` is the action clause without trailing punctuation, e.g.+ * `Created document "Daily Brief"`. When a url is present the agent must hand+ * the user a clickable link and keep the internal id to itself; when it is+ * absent (no url builder configured) the id is the only handle, so it is shown.+ */+const formatWriteResult = (lead: string, { id, url }: { id: string; url?: string }): string =>+ url+ ? `${lead}. Share this link with the user as a clickable markdown link: ${url}. ` ++ `(Internal id ${id} β for your own further edit/read/remove calls only; never show it to the user.)`+ : `${lead} (internal id: ${id}).`;++export const formatCreateDocumentResult = ({+ id,+ title,+ url,+}: AgentDocumentWriteResultParams): string =>+ formatWriteResult(`Created document ${titleLabel(title)}`, { id, url });++export const formatReplaceDocumentResult = ({+ id,+ title,+ url,+}: AgentDocumentWriteResultParams): string =>+ formatWriteResult(`Updated document ${titleLabel(title)}`, { id, url });++export interface FormatModifyDocumentResultParams extends AgentDocumentWriteResultParams {+ operationCount: number;+}++export const formatModifyDocumentResult = ({+ id,+ title,+ url,+ operationCount,+}: FormatModifyDocumentResultParams): string =>+ formatWriteResult(+ `Modified document ${titleLabel(title)}, applied ${operationCount} operation(s)`,+ { id, url },+ );++export const formatRenameDocumentResult = ({+ id,+ title,+ url,+}: AgentDocumentWriteResultParams): string =>+ formatWriteResult(`Renamed document to ${titleLabel(title)}`, { id, url });++export interface FormatCopyDocumentResultParams extends AgentDocumentWriteResultParams {+ /** The source document's id that was copied from. */+ fromId: string;+}++export const formatCopyDocumentResult = ({+ id,+ title,+ url,+ fromId,+}: FormatCopyDocumentResultParams): string =>+ formatWriteResult(`Copied document ${fromId} to a new document ${titleLabel(title)}`, {+ id,+ url,+ });++export const formatUpdateLoadRuleResult = ({+ id,+ title,+ url,+}: AgentDocumentWriteResultParams): string =>+ formatWriteResult(`Updated load rule for document ${titleLabel(title)}`, { id, url });++/** A removed document has no live url to share, so only the id is reported. */+export const formatRemoveDocumentResult = ({ id }: { id: string }): string =>+ `Removed document ${id}.`;diff --git a/packages/prompts/src/prompts/agentDocuments/index.ts b/packages/prompts/src/prompts/agentDocuments/index.tsnew file mode 100644index 00000000000..cdf0465a7c5--- /dev/null+++ b/packages/prompts/src/prompts/agentDocuments/index.ts@@ -0,0 +1 @@+export * from './formatResults';diff --git a/packages/prompts/src/prompts/index.ts b/packages/prompts/src/prompts/index.tsindex f7bc8b5ecf5..c011e78e7a4 100644--- a/packages/prompts/src/prompts/index.ts+++ b/packages/prompts/src/prompts/index.ts@@ -1,4 +1,5 @@export * from './agentBuilder';+export * from './agentDocuments';export * from './agentGroup';export * from './agentSignal';export * from './agentSkillManager';