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.

♻️ refactor(server): split the 1,392-line agentDocument router into sub-domain modules (#21093)

Arvin Xu3a44bda325a8
diff --git a/apps/server/src/routers/lambda/agentDocument.ts b/apps/server/src/routers/lambda/agentDocument.ts
deleted file mode 100644
index 9d981303384..00000000000
--- a/apps/server/src/routers/lambda/agentDocument.ts
+++ /dev/null
@@ -1,1392 +0,0 @@
-import {
- DOCUMENT_TEMPLATES,
- DocumentLoadFormat,
- DocumentLoadRule,
-} from '@lobechat/agent-templates';
-import { MOVE_DOCUMENTS_MAX_IDS } from '@lobechat/builtin-tool-agent-documents';
-import { AGENT_DOCUMENT_CATEGORY } from '@lobechat/const';
-import { TRPCError } from '@trpc/server';
-import matter from 'gray-matter';
-import { z } from 'zod';
-
-import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
-import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
-import { TopicTrigger } from '@/const/topic';
-import { AgentDocumentModel, deriveAgentDocumentFields } from '@/database/models/agentDocuments';
-import { TopicModel } from '@/database/models/topic';
-import { TopicDocumentModel } from '@/database/models/topicDocument';
-import { router } from '@/libs/trpc/lambda';
-import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-import { AgentDocumentsService } from '@/server/services/agentDocuments';
-import { createDocumentWorkRegistrar } from '@/server/services/agentDocuments/documentWork';
-import { emitAgentDocumentToolOutcomeSafely } from '@/server/services/agentDocuments/toolOutcome';
-import { AgentDocumentVfsService } from '@/server/services/agentDocumentVfs';
-import { AgentDocumentVfsError } from '@/server/services/agentDocumentVfs/errors';
-import { getUnifiedSkillNamespaceRootPath } from '@/server/services/agentDocumentVfs/mounts/skills/path';
-import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';
-import { SkillManagementDocumentService } from '@/server/services/skillManagement';
-import { SystemAgentService } from '@/server/services/systemAgent';
-
-const MAX_METADATA_BYTES = 16 * 1024;
-const MAX_RULE_REGEXP_LENGTH = 512;
-
-const agentDocumentVfsErrorToTRPCCode = (
- code: AgentDocumentVfsError['code'],
-): 'BAD_REQUEST' | 'CONFLICT' | 'FORBIDDEN' | 'METHOD_NOT_SUPPORTED' | 'NOT_FOUND' => {
- switch (code) {
- case 'CONFLICT': {
- return 'CONFLICT';
- }
- case 'FORBIDDEN': {
- return 'FORBIDDEN';
- }
- case 'METHOD_NOT_SUPPORTED': {
- return 'METHOD_NOT_SUPPORTED';
- }
- case 'NOT_FOUND': {
- return 'NOT_FOUND';
- }
- default: {
- return 'BAD_REQUEST';
- }
- }
-};
-
-const handleAgentDocumentVfsError = (error: unknown): never => {
- if (error instanceof TRPCError) {
- throw error;
- }
-
- if (error instanceof AgentDocumentVfsError) {
- throw new TRPCError({
- cause: error,
- code: agentDocumentVfsErrorToTRPCCode(error.code),
- message: error.message,
- });
- }
-
- throw error;
-};
-
-const metadataSchema = z
- .record(z.string(), z.unknown())
- .refine((value) => JSON.stringify(value).length <= MAX_METADATA_BYTES, {
- message: `metadata must be ${MAX_METADATA_BYTES} bytes or smaller`,
- });
-
-const toolLoadRuleSchema = z.object({
- keywordMatchMode: z.enum(['any', 'all']).optional(),
- keywords: z.array(z.string()).optional(),
- maxTokens: z.number().int().min(0).optional(),
- policyLoadFormat: z.nativeEnum(DocumentLoadFormat).optional(),
- priority: z.number().int().min(0).optional(),
- regexp: z.string().max(MAX_RULE_REGEXP_LENGTH).optional(),
- rule: z.nativeEnum(DocumentLoadRule).optional(),
- timeRange: z.object({ from: z.string().optional(), to: z.string().optional() }).optional(),
-});
-
-const readFormatSchema = z.enum(['xml', 'markdown', 'both']).optional();
-const readLocSchema = z
- .tuple([z.number().int().min(0), z.number().int().min(0)])
- .refine(([startLine, endLine]) => endLine >= startLine, {
- message: 'loc end line must be greater than or equal to start line',
- })
- .optional();
-const writeCreateModeSchema = z.enum(['always-new', 'if-missing', 'must-exist']).optional();
-const recursiveSchema = z.boolean().optional();
-const mountedSkillNamespaceSchema = z.literal('agent');
-const agentDocumentToolContextSchema = z.object({
- messageId: z.string(),
- operationId: z.string().optional(),
- rootOperationId: z.string().optional(),
- taskId: z.string().nullish(),
- threadId: z.string().nullish(),
- toolCallId: z.string(),
- toolMessageId: z.string().optional(),
- topicId: z.string().optional(),
-});
-const agentDocumentToolTriggerSchema = z
- .object({
- // REVIEW: @nekomeowww is not fully certain this attribution boundary is clear enough.
- // TODO: Remove this explicit parameter threading if gateway-mode migration makes tool execution fully server-attributed.
- toolContext: agentDocumentToolContextSchema.optional(),
- trigger: z.literal('tool').optional(),
- })
- .superRefine((value, ctx) => {
- if (value.trigger === 'tool' && !value.toolContext) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- message: 'toolContext is required when trigger is tool',
- path: ['toolContext'],
- });
- }
- });
-
-const createMountedSkillSchema = z.object({
- agentId: z.string(),
- content: z.string(),
- skillName: z.string().min(1),
- targetNamespace: mountedSkillNamespaceSchema,
-});
-
-const deleteMountedSkillSchema = z.object({
- agentId: z.string(),
- path: z.string(),
-});
-
-const updateMountedSkillSchema = z.object({
- agentId: z.string(),
- content: z.string(),
- path: z.string(),
-});
-
-const liteXMLOperationSchema = z.union([
- z.object({
- action: z.literal('insert'),
- beforeId: z.string(),
- litexml: z.string(),
- }),
- z.object({
- action: z.literal('insert'),
- afterId: z.string(),
- litexml: z.string(),
- }),
- z.object({
- action: z.literal('modify'),
- litexml: z.union([z.string(), z.array(z.string())]),
- }),
- z.object({
- action: z.literal('remove'),
- id: z.string(),
- }),
-]);
-
-const agentDocumentProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
- const { ctx } = opts;
- const wsId = ctx.workspaceId ?? undefined;
-
- return opts.next({
- ctx: {
- agentDocumentModel: new AgentDocumentModel(ctx.serverDB, ctx.userId, wsId),
- agentDocumentService: new AgentDocumentsService(ctx.serverDB, ctx.userId, wsId),
- agentDocumentVfsService: new AgentDocumentVfsService(ctx.serverDB, ctx.userId, wsId),
- skillManagementService: new SkillManagementDocumentService(ctx.serverDB, ctx.userId, wsId),
- systemAgentService: new SystemAgentService(ctx.serverDB, ctx.userId, wsId),
- documentWorkRegistrar: createDocumentWorkRegistrar({
- db: ctx.serverDB,
- logPrefix: '[agentDocumentRouter]',
- userId: ctx.userId,
- workspaceId: wsId,
- }),
- topicModel: new TopicModel(ctx.serverDB, ctx.userId, wsId),
- topicDocumentModel: new TopicDocumentModel(ctx.serverDB, ctx.userId, wsId),
- },
- });
-});
-
-// Write variant gates viewers out of every agent-document mutation
-// (upsert/delete/rename/copy/skill-edit, plus the VFS path-based writes).
-// Read endpoints keep using `agentDocumentProcedure`.
-const agentDocumentProcedureWrite = agentDocumentProcedure.use(
- withScopedPermission('document:update'),
-);
-
-const emitCreateDocumentToolOutcome = async (input: {
- agentDocumentId?: string;
- agentId: string;
- apiName: string;
- errorReason?: string;
- hintIsSkill?: boolean;
- status: 'failed' | 'succeeded';
- toolContext?: z.infer<typeof agentDocumentToolContextSchema>;
- topicId?: string;
- userId: string;
-}) => {
- const { toolContext } = input;
-
- if (!toolContext) return;
-
- await emitAgentDocumentToolOutcomeSafely({
- agentDocumentId: input.agentDocumentId,
- agentId: input.agentId,
- apiName: input.apiName,
- errorReason: input.errorReason,
- hintIsSkill: input.hintIsSkill,
- messageId: toolContext.messageId,
- operationId: toolContext.operationId,
- relation: 'created',
- status: input.status,
- summary:
- input.status === 'succeeded'
- ? 'Agent documents created a document.'
- : 'Agent documents failed to create a document.',
- taskId: toolContext.taskId,
- toolAction: 'create',
- toolCallId: toolContext.toolCallId,
- topicId: input.topicId ?? toolContext.topicId,
- userId: input.userId,
- });
-};
-
-/**
- * Strips a leading YAML frontmatter block from Markdown so it can be re-fed as
- * `bodyMarkdown` to the skill-management service (which renders its own
- * frontmatter and rejects bodies that already contain one).
- */
-const stripLeadingFrontmatter = (content: string): string => {
- try {
- const parsed = matter(content);
- return parsed.matter ? parsed.content.trimStart() : content;
- } catch {
- return content;
- }
-};
-
-const convertSkillErrorToTRPC = (error: unknown): never => {
- if (error instanceof TRPCError) throw error;
-
- if (error instanceof Error) {
- if (/already exists/i.test(error.message)) {
- throw new TRPCError({ cause: error, code: 'CONFLICT', message: error.message });
- }
- if (/invalid skill name|required|frontmatter/i.test(error.message)) {
- throw new TRPCError({ cause: error, code: 'BAD_REQUEST', message: error.message });
- }
- }
-
- throw error;
-};
-
-/**
- * Resolve the markdown body of a document that is eligible to become a skill.
- *
- * Shared by `convertDocumentToSkill` and `generateSkillMeta`. Rejects missing
- * documents, and — same as the convert path — folders, web sources, and
- * managed skill bundle/index rows. `createSkill` reparents the source row under
- * a new bundle, so converting an existing skill index would strip its original
- * bundle of its SKILL.md and corrupt it. The UI hides the action for these, but
- * a stale/scripted client could still call through, so enforce it server-side.
- */
-const resolveConvertibleDocumentBody = async (
- service: AgentDocumentsService,
- agentId: string,
- sourceAgentDocumentId: string,
-): Promise<string> => {
- const source = await service.getDocumentById(sourceAgentDocumentId, agentId);
-
- if (!source) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Source document not found' });
- }
-
- const { category, isFolder } = deriveAgentDocumentFields(source);
- if (category !== AGENT_DOCUMENT_CATEGORY || isFolder) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: 'Only a plain agent document can be converted into a skill',
- });
- }
-
- const bodyMarkdown = stripLeadingFrontmatter(source.content ?? '').trim();
-
- if (!bodyMarkdown) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: 'Cannot convert an empty document into a skill',
- });
- }
-
- return bodyMarkdown;
-};
-
-export const agentDocumentRouter = router({
- /**
- * Get all available template sets
- */
- getTemplates: agentDocumentProcedure.query(async () => {
- return Object.entries(DOCUMENT_TEMPLATES).map(([id, template]) => ({
- description: template.description,
- filenames: template.templates.map((item) => item.filename),
- id,
- name: template.name,
- }));
- }),
-
- /**
- * Get all documents for an agent
- */
- getDocuments: agentDocumentProcedure
- .input(z.object({ agentId: z.string() }))
- .query(async ({ ctx, input }) => {
- return ctx.agentDocumentService.getAgentDocuments(input.agentId);
- }),
-
- /**
- * Get documents for chat context injection.
- */
- getContextDocuments: agentDocumentProcedure
- .input(z.object({ agentId: z.string() }))
- .query(async ({ ctx, input }) => {
- return ctx.agentDocumentService.getAgentContextDocuments(input.agentId);
- }),
-
- /**
- * Get a specific document by filename
- */
- getDocument: agentDocumentProcedure
- .input(
- z.object({
- agentId: z.string(),
- filename: z.string(),
- }),
- )
- .query(async ({ ctx, input }) => {
- return ctx.agentDocumentService.getDocument(input.agentId, input.filename);
- }),
-
- /**
- * Return the chat topic that anchors the doc-scoped conversation for this
- * `(documentId, agentId)` pair, creating it idempotently on the first call.
- *
- * Topics are marked with `trigger='document'` so they stay out of the main
- * sidebar history (`MAIN_SIDEBAR_EXCLUDE_TRIGGERS` already excludes them).
- * The mapping is persisted through `topic_documents`, so subsequent calls
- * resolve the same topic id.
- */
- getOrCreateChatTopic: agentDocumentProcedure
- .input(
- z.object({
- agentId: z.string(),
- documentId: z.string(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- const existing = await ctx.topicModel.findByAgentAndDocumentTrigger({
- agentId: input.agentId,
- documentId: input.documentId,
- trigger: TopicTrigger.Document,
- });
- if (existing) return { topicId: existing.id };
-
- const document = await ctx.agentDocumentService.findRowByDocumentId(
- input.agentId,
- input.documentId,
- );
- if (!document) {
- throw new TRPCError({
- code: 'NOT_FOUND',
- message: `Document not found for agentId=${input.agentId}`,
- });
- }
-
- const title = document.title || document.filename || 'Document chat';
- const topic = await ctx.topicModel.create({
- agentId: input.agentId,
- title,
- trigger: TopicTrigger.Document,
- });
-
- await ctx.topicDocumentModel.associate({
- documentId: input.documentId,
- topicId: topic.id,
- });
-
- return { topicId: topic.id };
- }),
-
- /**
- * Create or update a document
- */
- upsertDocument: agentDocumentProcedureWrite
- .input(
- z.object({
- agentId: z.string(),
- content: z.string(),
- createdAt: z.date().optional(),
- filename: z.string(),
- metadata: metadataSchema.optional(),
- updatedAt: z.date().optional(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- return ctx.agentDocumentService.upsertDocument({
- agentId: input.agentId,
- content: input.content,
- createdAt: input.createdAt,
- filename: input.filename,
- metadata: input.metadata,
- updatedAt: input.updatedAt,
- });
- }),
-
- /**
- * Delete a specific document
- */
- deleteDocument: agentDocumentProcedureWrite
- .input(
- z.object({
- agentId: z.string(),
- filename: z.string(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- const doc = await ctx.agentDocumentService.getDocument(input.agentId, input.filename);
- if (!doc) return;
-
- return ctx.agentDocumentService.deleteDocument(doc.id);
- }),
-
- /**
- * Delete all documents for an agent
- */
- deleteAllDocuments: agentDocumentProcedureWrite
- .input(z.object({ agentId: z.string() }))
- .mutation(async ({ ctx, input }) => {
- return ctx.agentDocumentService.deleteAllDocuments(input.agentId);
- }),
-
- /**
- * Initialize documents from a template set
- */
- initializeFromTemplate: agentDocumentProcedureWrite
- .input(
- z.object({
- agentId: z.string(),
- templateSet: z.enum(Object.keys(DOCUMENT_TEMPLATES) as [string, ...string[]]),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- return ctx.agentDocumentService.initializeFromTemplate(
- input.agentId,
- input.templateSet as keyof typeof DOCUMENT_TEMPLATES,
- );
- }),
-
- /**
- * Get agent context for conversations
- */
- getContext: agentDocumentProcedure
- .input(z.object({ agentId: z.string() }))
- .query(async ({ ctx, input }) => {
- return ctx.agentDocumentService.getAgentContext(input.agentId);
- }),
-
- /**
- * Get documents as a map
- */
- getDocumentsMap: agentDocumentProcedure
- .input(z.object({ agentId: z.string() }))
- .query(async ({ ctx, input }) => {
- const map = await ctx.agentDocumentService.getDocumentsMap(input.agentId);
- // Convert Map to object for JSON serialization
- return Object.fromEntries(map);
- }),
-
- /**
- * Clone documents from one agent to another
- */
- cloneDocuments: agentDocumentProcedureWrite
- .input(
- z.object({
- sourceAgentId: z.string(),
- targetAgentId: z.string(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- return ctx.agentDocumentService.cloneDocuments(input.sourceAgentId, input.targetAgentId);
- }),
-
- /**
- * Check if agent has documents
- */
- hasDocuments: agentDocumentProcedure
- .input(z.object({ agentId: z.string() }))
- .query(async ({ ctx, input }) => {
- return ctx.agentDocumentService.hasDocuments(input.agentId);
- }),
-
- /**
- * Tool-oriented: list documents for an agent
- */
- listDocuments: agentDocumentProcedure
- .input(
- z.object({
- agentId: z.string(),
- // Drop `sourceType: 'web'` docs (saved web-clips / articles). These grow
- // unbounded and dominate the payload, but only the working-sidebar "web"
- // tab renders them. Hot-path consumers (slash menu, skills) pass this so
- // the list stays small. Ignored for `currentTopic` scope.
- excludeWeb: z.boolean().optional().default(false),
- // Reveal the auto-created `.tool-results` archive. Off by default so
- // user-facing lists stay clean; the agent document-listing tool opts in.
- includeArchivedToolResults: z.boolean().optional().default(false),
- // Restrict the listing to the direct children of this folder so the model
- // can expand a folder collapsed in the progressive index.
- parentId: z.string().optional(),
- scope: z.enum(['agent', 'currentTopic']).optional().default('agent'),
- sourceType: z.enum(['all', 'file', 'web']).optional().default('all'),
- topicId: z.string().optional(),
- // Stamp `childCount` on entries with something nested under them (the
- // agent tool needs it to spot a workflow document holding its runs).
- withChildCount: z.boolean().optional().default(false),
- }),
- )
- .query(async ({ ctx, input }) => {
- const { excludeWeb, includeArchivedToolResults, parentId } = input;
- const withChildCounts = async <T extends { documentId: string }>(docs: T[]) => {
- if (!input.withChildCount) return docs;
- const counts = await ctx.agentDocumentService.countChildren(input.agentId);
- return docs.map((doc) => ({ ...doc, childCount: counts.get(doc.documentId) ?? 0 }));
- };
- try {
- if (input.scope === 'currentTopic') {
- if (!input.topicId) {
- throw new Error('topicId is required to list current topic documents');
- }
-
- const docs = await ctx.agentDocumentService.listDocumentsForTopic(
- input.agentId,
- input.topicId,
- input.sourceType,
- { includeArchivedToolResults },
- );
- if (!parentId) return await withChildCounts(docs);
-
- // Topic listing joins through topic associations rather than the agent
- // folder tree, so the parent filter is applied in-memory here.
- const parent = await ctx.agentDocumentService.resolveParent(input.agentId, parentId);
- return await withChildCounts(docs.filter((d) => d.parentId === parent.documentId));
- }
-
- return await withChildCounts(
- await ctx.agentDocumentService.listDocuments(input.agentId, input.sourceType, {
- excludeWeb,
- includeArchivedToolResults,
- parentId,
- }),
- );
- } catch (error) {
- return handleAgentDocumentVfsError(error);
- }
- }),
-
- /**
- * Tool-oriented: list documents by VFS path
- */
- listDocumentsByPath: agentDocumentProcedure
- .input(
- z.object({
- agentId: z.string(),
- cursor: z.string().optional(),
- limit: z.number().int().positive().max(500).optional(),
- path: z.string(),
- topicId: z.string().optional(),
- }),
- )
- .query(async ({ ctx, input }) => {
- try {
- return await ctx.agentDocumentVfsService.list(
- input.path,
- {
- agentId: input.agentId,
- topicId: input.topicId,
- },
- {
- cursor: input.cursor,
- limit: input.limit,
- },
- );
- } catch (error) {
- handleAgentDocumentVfsError(error);
- }
- }),
-
- /**
- * Tool-oriented: stat document by VFS path
- */
- statDocumentByPath: agentDocumentProcedure
- .input(
- z.object({
- agentId: z.string(),
- path: z.string(),
- topicId: z.string().optional(),
- }),
- )
- .query(async ({ ctx, input }) => {
- try {
- return await ctx.agentDocumentVfsService.stat(input.path, {
- agentId: input.agentId,
- topicId: input.topicId,
- });
- } catch (error) {
- handleAgentDocumentVfsError(error);
- }
- }),
-
- /**
- * Tool-oriented: read document by VFS path
- */
- readDocumentByPath: agentDocumentProcedure
- .input(
- z.object({
- agentId: z.string(),
- loc: readLocSchema,
- path: z.string(),
- topicId: z.string().optional(),
- }),
- )
- .query(async ({ ctx, input }) => {
- try {
- return await ctx.agentDocumentVfsService.read(
- input.path,
- {
- agentId: input.agentId,
- topicId: input.topicId,
- },
- {
- loc: input.loc,
- },
- );
- } catch (error) {
- handleAgentDocumentVfsError(error);
- }
- }),
-
- /**
- * Tool-oriented: write document by VFS path
- */
- writeDocumentByPath: agentDocumentProcedureWrite
- .input(
- z.object({
- agentId: z.string(),
- content: z.string(),
- createMode: writeCreateModeSchema,
- path: z.string(),
- topicId: z.string().optional(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- try {
- return await ctx.agentDocumentVfsService.write(
- input.path,
- input.content,
- {
- agentId: input.agentId,
- topicId: input.topicId,
- },
- { createMode: input.createMode },
- );
- } catch (error) {
- handleAgentDocumentVfsError(error);
- }
- }),
-
- createSkillByPath: agentDocumentProcedureWrite
- .input(createMountedSkillSchema)
- .mutation(async ({ ctx, input }) => {
- try {
- const path = `${getUnifiedSkillNamespaceRootPath(input.targetNamespace)}/${input.skillName}`;
-
- return await ctx.agentDocumentVfsService.write(
- path,
- input.content,
- {
- agentId: input.agentId,
- },
- { createMode: 'always-new' },
- );
- } catch (error) {
- handleAgentDocumentVfsError(error);
- }
- }),
-
- /**
- * Converts an existing agent document into a managed skill (direct migration).
- *
- * The source document row is reused as the skill's `SKILL.md` index (its
- * `documents.id` / `agent_documents.id` are preserved), and a new
- * `skills/bundle` parent is created to hold it. After this call the original
- * document no longer appears at its previous location in the tree.
- */
- convertDocumentToSkill: agentDocumentProcedureWrite
- .input(
- z.object({
- agentId: z.string(),
- description: z.string().trim().min(1),
- name: z.string().trim().min(1),
- sourceAgentDocumentId: z.string(),
- title: z.string().trim().min(1),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- const bodyMarkdown = await resolveConvertibleDocumentBody(
- ctx.agentDocumentService,
- input.agentId,
- input.sourceAgentDocumentId,
- );
-
- try {
- return await ctx.skillManagementService.createSkill({
- agentId: input.agentId,
- bodyMarkdown,
- description: input.description,
- name: input.name,
- sourceAgentDocumentId: input.sourceAgentDocumentId,
- title: input.title,
- });
- } catch (error) {
- return convertSkillErrorToTRPC(error);
- }
- }),
-
- /**
- * Generates skill metadata (name / title / description) from a document's
- * content, used to prefill the convert-to-skill form. Does not mutate the
- * document; returns `null` when generation fails so the caller can fall back
- * to its own defaults.
- */
- generateSkillMeta: agentDocumentProcedureWrite
- .input(
- z.object({
- agentId: z.string(),
- sourceAgentDocumentId: z.string(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- const bodyMarkdown = await resolveConvertibleDocumentBody(
- ctx.agentDocumentService,
- input.agentId,
- input.sourceAgentDocumentId,
- );
-
- return ctx.systemAgentService.generateSkillMeta({
- agentId: input.agentId,
- content: bodyMarkdown,
- });
- }),
-
- updateSkillByPath: agentDocumentProcedureWrite
- .input(updateMountedSkillSchema)
- .mutation(async ({ ctx, input }) => {
- try {
- return await ctx.agentDocumentVfsService.write(
- input.path,
- input.content,
- {
- agentId: input.agentId,
- },
- { createMode: 'must-exist' },
- );
- } catch (error) {
- handleAgentDocumentVfsError(error);
- }
- }),
-
- deleteSkillByPath: agentDocumentProcedureWrite
- .input(deleteMountedSkillSchema)
- .mutation(async ({ ctx, input }) => {
- try {
- await ctx.agentDocumentVfsService.delete(input.path, {
- agentId: input.agentId,
- });
- } catch (error) {
- handleAgentDocumentVfsError(error);
- }
- }),
-
- /**
- * Tool-oriented: create a VFS directory
- */
- mkdirDocumentByPath: agentDocumentProcedureWrite
- .input(
- z.object({
- agentId: z.string(),
- path: z.string(),
- recursive: recursiveSchema,
- topicId: z.string().optional(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- try {
- return await ctx.agentDocumentVfsService.mkdir(
- input.path,
- {
- agentId: input.agentId,
- topicId: input.topicId,
- },
- { recursive: input.recursive },
- );
- } catch (error) {
- handleAgentDocumentVfsError(error);
- }
- }),
-
- /**
- * Tool-oriented: rename or move a VFS path
- */
- renameDocumentByPath: agentDocumentProcedureWrite
- .input(
- z.object({
- agentId: z.string(),
- force: z.boolean().optional(),
- fromPath: z.string(),
- toPath: z.string(),
- topicId: z.string().optional(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- try {
- return await ctx.agentDocumentVfsService.rename(
- input.fromPath,
- input.toPath,
- {
- agentId: input.agentId,
- topicId: input.topicId,
- },
- { overwrite: input.force },
- );
- } catch (error) {
- handleAgentDocumentVfsError(error);
- }
- }),
-
- /**
- * Tool-oriented: copy a VFS path
- */
- copyDocumentByPath: agentDocumentProcedureWrite
- .input(
- z.object({
- agentId: z.string(),
- force: z.boolean().optional(),
- fromPath: z.string(),
- toPath: z.string(),
- topicId: z.string().optional(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- try {
- return await ctx.agentDocumentVfsService.copy(
- input.fromPath,
- input.toPath,
- {
- agentId: input.agentId,
- topicId: input.topicId,
- },
- { overwrite: input.force },
- );
- } catch (error) {
- handleAgentDocumentVfsError(error);
- }
- }),
-
- /**
- * Tool-oriented: soft-delete a VFS path
- */
- deleteDocumentByPath: agentDocumentProcedureWrite
- .input(
- z.object({
- agentId: z.string(),
- force: z.boolean().optional(),
- path: z.string(),
- recursive: recursiveSchema,
- topicId: z.string().optional(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- try {
- await ctx.agentDocumentVfsService.delete(
- input.path,
- {
- agentId: input.agentId,
- topicId: input.topicId,
- },
- { recursive: input.recursive },
- );
- } catch (error) {
- handleAgentDocumentVfsError(error);
- }
- }),
-
- /**
- * Tool-oriented: list agent-scoped trash entries
- */
- listTrashDocumentsByPath: agentDocumentProcedure
- .input(
- z.object({
- agentId: z.string(),
- path: z.string().optional(),
- topicId: z.string().optional(),
- }),
- )
- .query(async ({ ctx, input }) => {
- try {
- return await ctx.agentDocumentVfsService.listTrash(
- {
- agentId: input.agentId,
- topicId: input.topicId,
- },
- input.path,
- );
- } catch (error) {
- handleAgentDocumentVfsError(error);
- }
- }),
-
- /**
- * Tool-oriented: restore a trash entry
- */
- restoreDocumentFromTrashByPath: agentDocumentProcedureWrite
- .input(
- z.object({
- agentId: z.string(),
- path: z.string(),
- topicId: z.string().optional(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- try {
- return await ctx.agentDocumentVfsService.restoreFromTrashByPath(input.path, {
- agentId: input.agentId,
- topicId: input.topicId,
- });
- } catch (error) {
- handleAgentDocumentVfsError(error);
- }
- }),
-
- /**
- * Tool-oriented: permanently remove a trash entry
- */
- deleteDocumentPermanentlyByPath: agentDocumentProcedureWrite
- .input(
- z.object({
- agentId: z.string(),
- force: z.boolean().optional(),
- path: z.string(),
- recursive: recursiveSchema,
- topicId: z.string().optional(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- try {
- await ctx.agentDocumentVfsService.deletePermanentlyByPath(input.path, {
- agentId: input.agentId,
- topicId: input.topicId,
- });
- } catch (error) {
- handleAgentDocumentVfsError(error);
- }
- }),
-
- /**
- * Tool-oriented: associate an existing document with an agent
- */
- associateDocument: agentDocumentProcedureWrite
- .input(
- z.object({
- agentId: z.string(),
- documentId: z.string(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- return ctx.agentDocumentService.associateDocument(input.agentId, input.documentId);
- }),
-
- importFile: agentDocumentProcedureWrite
- .input(
- z.object({
- agentId: z.string(),
- fileId: z.string(),
- parentId: z.string().nullish(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- return ctx.agentDocumentService.importFile(input.agentId, input.fileId, input.parentId);
- }),
-
- /**
- * Tool-oriented: create document
- */
- createDocument: agentDocumentProcedureWrite
- .input(
- z
- .object({
- agentId: z.string(),
- content: z.string(),
- hintIsSkill: z.boolean().optional(),
- parentId: z.string().optional(),
- title: z.string(),
- })
- .and(agentDocumentToolTriggerSchema),
- )
- .mutation(async ({ ctx, input }) => {
- try {
- const doc = await ctx.agentDocumentService.createDocument(
- input.agentId,
- input.title,
- input.content,
- {
- hintIsSkill: input.hintIsSkill,
- parentId: input.parentId,
- },
- );
-
- if (input.trigger === 'tool') {
- await emitCreateDocumentToolOutcome({
- agentDocumentId: doc?.id,
- agentId: input.agentId,
- apiName: 'createDocument',
- hintIsSkill: input.hintIsSkill,
- status: 'succeeded',
- toolContext: input.toolContext,
- userId: ctx.userId,
- });
- }
-
- return doc;
- } catch (error) {
- if (input.trigger === 'tool') {
- await emitCreateDocumentToolOutcome({
- agentId: input.agentId,
- apiName: 'createDocument',
- errorReason: error instanceof Error ? error.message : String(error),
- hintIsSkill: input.hintIsSkill,
- status: 'failed',
- toolContext: input.toolContext,
- userId: ctx.userId,
- });
- }
-
- throw error;
- }
- }),
-
- /**
- * Create an agent document and associate it with a topic in one call.
- * Used by the topic → page flow to create an agent document.
- */
- createForTopic: agentDocumentProcedureWrite
- .input(
- z
- .object({
- agentId: z.string(),
- content: z.string(),
- hintIsSkill: z.boolean().optional(),
- parentId: z.string().optional(),
- title: z.string(),
- topicId: z.string(),
- })
- .and(agentDocumentToolTriggerSchema),
- )
- .mutation(async ({ ctx, input }) => {
- try {
- // Use the creator-facing finder: a visitor topic's title must not be
- // copied into a creator-owned document.
- const topic = input.title.trim()
- ? undefined
- : await ctx.topicModel.findOwnTopicById(input.topicId);
- const title = input.title.trim() || topic?.title || '';
- const doc = await ctx.agentDocumentService.createForTopic(
- input.agentId,
- title,
- input.content,
- input.topicId,
- { hintIsSkill: input.hintIsSkill, parentId: input.parentId },
- );
-
- if (input.trigger === 'tool') {
- await emitCreateDocumentToolOutcome({
- agentDocumentId: doc?.id,
- agentId: input.agentId,
- apiName: 'createForTopic',
- hintIsSkill: input.hintIsSkill,
- status: 'succeeded',
- toolContext: input.toolContext,
- topicId: input.topicId,
- userId: ctx.userId,
- });
- }
-
- return doc;
- } catch (error) {
- if (input.trigger === 'tool') {
- await emitCreateDocumentToolOutcome({
- agentId: input.agentId,
- apiName: 'createForTopic',
- errorReason: error instanceof Error ? error.message : String(error),
- hintIsSkill: input.hintIsSkill,
- status: 'failed',
- toolContext: input.toolContext,
- topicId: input.topicId,
- userId: ctx.userId,
- });
- }
-
- throw error;
- }
- }),
-
- /** Read-only document payload for the standalone Agent Document page. */
- getReaderDocument: agentDocumentProcedure
- .input(
- z.object({
- agentId: z.string(),
- documentId: z.string(),
- }),
- )
- .query(async ({ ctx, input }) => {
- const grantedPermissions = (ctx as { workspacePermissionCodes?: string[] })
- .workspacePermissionCodes;
-
- if (ctx.workspaceId) {
- await assertCanPerformResourceAction({
- action: 'view',
- db: ctx.serverDB,
- grantedPermissions,
- resourceId: input.agentId,
- resourceType: 'agent',
- userId: ctx.userId,
- workspaceId: ctx.workspaceId,
- });
- }
-
- const document = await ctx.agentDocumentService.getReaderDocument(
- input.agentId,
- input.documentId,
- );
-
- if (!document) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent document not found' });
- }
-
- if (ctx.workspaceId) {
- await assertCanPerformResourceAction({
- action: 'view',
- db: ctx.serverDB,
- grantedPermissions,
- resourceId: input.documentId,
- resourceType: 'document',
- userId: ctx.userId,
- workspaceId: ctx.workspaceId,
- });
- }
-
- return {
- content: document.content,
- documentId: document.documentId,
- filename: document.filename,
- fileType: document.fileType,
- sourceType: document.sourceType,
- title: document.title,
- updatedAt: document.updatedAt,
- };
- }),
-
- /**
- * Tool-oriented: read document by id
- */
- readDocument: agentDocumentProcedure
- .input(
- z.object({
- agentId: z.string(),
- format: readFormatSchema,
- id: z.string(),
- }),
- )
- .query(async ({ ctx, input }) => {
- return input.format
- ? ctx.agentDocumentService.getDocumentSnapshotById(input.id, input.agentId)
- : ctx.agentDocumentService.getDocumentById(input.id, input.agentId);
- }),
-
- /**
- * Tool-oriented: modify document nodes by id through LiteXML.
- */
- modifyNodes: agentDocumentProcedureWrite
- .input(
- z
- .object({
- agentId: z.string(),
- id: z.string(),
- operations: z.array(liteXMLOperationSchema).min(1),
- })
- .and(agentDocumentToolTriggerSchema),
- )
- .mutation(async ({ ctx, input }) => {
- const doc = await ctx.agentDocumentService.modifyDocumentNodesById(
- input.id,
- input.operations,
- input.agentId,
- );
-
- return doc;
- }),
-
- /**
- * Tool-oriented: replace document content by id
- */
- replaceDocumentContent: agentDocumentProcedureWrite
- .input(
- z
- .object({
- agentId: z.string(),
- content: z.string(),
- id: z.string(),
- })
- .and(agentDocumentToolTriggerSchema),
- )
- .mutation(async ({ ctx, input }) => {
- const doc = await ctx.agentDocumentService.replaceDocumentContentById(
- input.id,
- input.content,
- input.agentId,
- );
-
- return doc;
- }),
-
- /**
- * Tool-oriented: remove document by id
- */
- removeDocument: agentDocumentProcedureWrite
- .input(
- z
- .object({
- agentId: z.string(),
- id: z.string(),
- // Also delete documents nested under it; without it a parent with
- // children is refused instead of stranding them.
- withChildren: z.boolean().optional(),
- })
- .and(agentDocumentToolTriggerSchema),
- )
- .mutation(async ({ ctx, input }) => {
- const doc = await ctx.agentDocumentService.getDocumentById(input.id, input.agentId);
- const deleted = await ctx.agentDocumentService
- .removeDocumentById(input.id, input.agentId, { withChildren: input.withChildren })
- .catch(handleAgentDocumentVfsError);
- if (deleted && input.trigger === 'tool') {
- await ctx.documentWorkRegistrar.deleteDocumentWork({
- agentDocumentId: input.id,
- agentId: input.agentId,
- documentId: doc?.documentId,
- });
- }
-
- return { deleted, id: input.id };
- }),
-
- /**
- * Tool-oriented: copy document by id
- */
- copyDocument: agentDocumentProcedureWrite
- .input(
- z
- .object({
- agentId: z.string(),
- id: z.string(),
- newTitle: z.string().optional(),
- })
- .and(agentDocumentToolTriggerSchema),
- )
- .mutation(async ({ ctx, input }) => {
- try {
- const doc = await ctx.agentDocumentService.copyDocumentById(
- input.id,
- input.newTitle,
- input.agentId,
- );
-
- return doc;
- } catch (error) {
- handleAgentDocumentVfsError(error);
- }
- }),
-
- /**
- * Tool-oriented: rename document by id
- */
- renameDocument: agentDocumentProcedureWrite
- .input(
- z
- .object({
- agentId: z.string(),
- id: z.string(),
- newTitle: z.string(),
- })
- .and(agentDocumentToolTriggerSchema),
- )
- .mutation(async ({ ctx, input }) => {
- try {
- const doc = await ctx.agentDocumentService.renameDocumentById(
- input.id,
- input.newTitle,
- input.agentId,
- );
-
- return doc;
- } catch (error) {
- handleAgentDocumentVfsError(error);
- }
- }),
-
- /**
- * Tool-oriented: create a folder by name, under the root or a parent (folder or document) id
- */
- createFolder: agentDocumentProcedureWrite
- .input(
- z.object({
- agentId: z.string(),
- parentId: z.string().nullish(),
- title: z.string(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- try {
- return await ctx.agentDocumentService.createFolder(
- input.agentId,
- input.title,
- input.parentId,
- );
- } catch (error) {
- handleAgentDocumentVfsError(error);
- }
- }),
-
- /**
- * Tool-oriented: move documents/folders by id under a parent (folder or document), or to the root with `null`
- */
- moveDocuments: agentDocumentProcedureWrite
- .input(
- z.object({
- agentId: z.string(),
- ids: z.array(z.string()).min(1).max(MOVE_DOCUMENTS_MAX_IDS),
- parentId: z.string().nullable(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- try {
- return await ctx.agentDocumentService.moveDocuments(
- input.agentId,
- input.ids,
- input.parentId,
- );
- } catch (error) {
- handleAgentDocumentVfsError(error);
- }
- }),
-
- /**
- * Tool-oriented: update document load rule by id
- */
- updateLoadRule: agentDocumentProcedureWrite
- .input(
- z.object({
- agentId: z.string(),
- id: z.string(),
- rule: toolLoadRuleSchema,
- }),
- )
- .mutation(async ({ ctx, input }) => {
- return ctx.agentDocumentService.updateLoadRuleById(input.id, input.rule, input.agentId);
- }),
-});
diff --git a/apps/server/src/routers/lambda/agentDocument/documents.ts b/apps/server/src/routers/lambda/agentDocument/documents.ts
new file mode 100644
index 00000000000..f4e600c7511
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentDocument/documents.ts
@@ -0,0 +1,211 @@
+import { DOCUMENT_TEMPLATES } from '@lobechat/agent-templates';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { TopicTrigger } from '@/const/topic';
+import { router } from '@/libs/trpc/lambda';
+
+import { agentDocumentProcedure, agentDocumentProcedureWrite } from './procedures';
+
+const MAX_METADATA_BYTES = 16 * 1024;
+
+const metadataSchema = z
+ .record(z.string(), z.unknown())
+ .refine((value) => JSON.stringify(value).length <= MAX_METADATA_BYTES, {
+ message: `metadata must be ${MAX_METADATA_BYTES} bytes or smaller`,
+ });
+
+export const documentsRouter = router({
+ /**
+ * Get all available template sets
+ */
+ getTemplates: agentDocumentProcedure.query(async () => {
+ return Object.entries(DOCUMENT_TEMPLATES).map(([id, template]) => ({
+ description: template.description,
+ filenames: template.templates.map((item) => item.filename),
+ id,
+ name: template.name,
+ }));
+ }),
+ /**
+ * Get all documents for an agent
+ */
+ getDocuments: agentDocumentProcedure
+ .input(z.object({ agentId: z.string() }))
+ .query(async ({ ctx, input }) => {
+ return ctx.agentDocumentService.getAgentDocuments(input.agentId);
+ }),
+ /**
+ * Get documents for chat context injection.
+ */
+ getContextDocuments: agentDocumentProcedure
+ .input(z.object({ agentId: z.string() }))
+ .query(async ({ ctx, input }) => {
+ return ctx.agentDocumentService.getAgentContextDocuments(input.agentId);
+ }),
+ /**
+ * Get a specific document by filename
+ */
+ getDocument: agentDocumentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ filename: z.string(),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ return ctx.agentDocumentService.getDocument(input.agentId, input.filename);
+ }),
+ /**
+ * Return the chat topic that anchors the doc-scoped conversation for this
+ * `(documentId, agentId)` pair, creating it idempotently on the first call.
+ *
+ * Topics are marked with `trigger='document'` so they stay out of the main
+ * sidebar history (`MAIN_SIDEBAR_EXCLUDE_TRIGGERS` already excludes them).
+ * The mapping is persisted through `topic_documents`, so subsequent calls
+ * resolve the same topic id.
+ */
+ getOrCreateChatTopic: agentDocumentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ documentId: z.string(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const existing = await ctx.topicModel.findByAgentAndDocumentTrigger({
+ agentId: input.agentId,
+ documentId: input.documentId,
+ trigger: TopicTrigger.Document,
+ });
+ if (existing) return { topicId: existing.id };
+
+ const document = await ctx.agentDocumentService.findRowByDocumentId(
+ input.agentId,
+ input.documentId,
+ );
+ if (!document) {
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: `Document not found for agentId=${input.agentId}`,
+ });
+ }
+
+ const title = document.title || document.filename || 'Document chat';
+ const topic = await ctx.topicModel.create({
+ agentId: input.agentId,
+ title,
+ trigger: TopicTrigger.Document,
+ });
+
+ await ctx.topicDocumentModel.associate({
+ documentId: input.documentId,
+ topicId: topic.id,
+ });
+
+ return { topicId: topic.id };
+ }),
+ /**
+ * Create or update a document
+ */
+ upsertDocument: agentDocumentProcedureWrite
+ .input(
+ z.object({
+ agentId: z.string(),
+ content: z.string(),
+ createdAt: z.date().optional(),
+ filename: z.string(),
+ metadata: metadataSchema.optional(),
+ updatedAt: z.date().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ return ctx.agentDocumentService.upsertDocument({
+ agentId: input.agentId,
+ content: input.content,
+ createdAt: input.createdAt,
+ filename: input.filename,
+ metadata: input.metadata,
+ updatedAt: input.updatedAt,
+ });
+ }),
+ /**
+ * Delete a specific document
+ */
+ deleteDocument: agentDocumentProcedureWrite
+ .input(
+ z.object({
+ agentId: z.string(),
+ filename: z.string(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const doc = await ctx.agentDocumentService.getDocument(input.agentId, input.filename);
+ if (!doc) return;
+
+ return ctx.agentDocumentService.deleteDocument(doc.id);
+ }),
+ /**
+ * Delete all documents for an agent
+ */
+ deleteAllDocuments: agentDocumentProcedureWrite
+ .input(z.object({ agentId: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ return ctx.agentDocumentService.deleteAllDocuments(input.agentId);
+ }),
+ /**
+ * Initialize documents from a template set
+ */
+ initializeFromTemplate: agentDocumentProcedureWrite
+ .input(
+ z.object({
+ agentId: z.string(),
+ templateSet: z.enum(Object.keys(DOCUMENT_TEMPLATES) as [string, ...string[]]),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ return ctx.agentDocumentService.initializeFromTemplate(
+ input.agentId,
+ input.templateSet as keyof typeof DOCUMENT_TEMPLATES,
+ );
+ }),
+ /**
+ * Get agent context for conversations
+ */
+ getContext: agentDocumentProcedure
+ .input(z.object({ agentId: z.string() }))
+ .query(async ({ ctx, input }) => {
+ return ctx.agentDocumentService.getAgentContext(input.agentId);
+ }),
+ /**
+ * Get documents as a map
+ */
+ getDocumentsMap: agentDocumentProcedure
+ .input(z.object({ agentId: z.string() }))
+ .query(async ({ ctx, input }) => {
+ const map = await ctx.agentDocumentService.getDocumentsMap(input.agentId);
+ // Convert Map to object for JSON serialization
+ return Object.fromEntries(map);
+ }),
+ /**
+ * Clone documents from one agent to another
+ */
+ cloneDocuments: agentDocumentProcedureWrite
+ .input(
+ z.object({
+ sourceAgentId: z.string(),
+ targetAgentId: z.string(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ return ctx.agentDocumentService.cloneDocuments(input.sourceAgentId, input.targetAgentId);
+ }),
+ /**
+ * Check if agent has documents
+ */
+ hasDocuments: agentDocumentProcedure
+ .input(z.object({ agentId: z.string() }))
+ .query(async ({ ctx, input }) => {
+ return ctx.agentDocumentService.hasDocuments(input.agentId);
+ }),
+});
diff --git a/apps/server/src/routers/lambda/agentDocument/index.procedures.test.ts b/apps/server/src/routers/lambda/agentDocument/index.procedures.test.ts
new file mode 100644
index 00000000000..4c33e770707
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentDocument/index.procedures.test.ts
@@ -0,0 +1,73 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import { agentDocumentRouter } from './index';
+
+/**
+ * Pins the router's public surface: every procedure path, its kind, and its
+ * middleware chain length (which encodes the procedure builder and its input
+ * parsers). Splitting the router across files must keep all three.
+ */
+describe('agentDocumentRouter procedures', () => {
+ const procedures = (agentDocumentRouter as any)._def.procedures as Record<string, any>;
+
+ it('exposes exactly the expected procedure paths', () => {
+ expect(Object.keys(procedures).sort()).toEqual(expected().map(([name]) => name));
+ });
+
+ it.each(expected())('%s is a %s with %i middlewares', (name, type, middlewares) => {
+ expect(procedures[name]._def.type).toBe(type);
+ expect(procedures[name]._def.middlewares).toHaveLength(middlewares);
+ });
+});
+
+function expected(): Array<
+ [name: string, type: 'mutation' | 'query' | 'subscription', middlewares: number]
+> {
+ return [
+ ['associateDocument', 'mutation', 13],
+ ['cloneDocuments', 'mutation', 13],
+ ['convertDocumentToSkill', 'mutation', 13],
+ ['copyDocument', 'mutation', 13],
+ ['copyDocumentByPath', 'mutation', 13],
+ ['createDocument', 'mutation', 13],
+ ['createFolder', 'mutation', 13],
+ ['createForTopic', 'mutation', 13],
+ ['createSkillByPath', 'mutation', 13],
+ ['deleteAllDocuments', 'mutation', 13],
+ ['deleteDocument', 'mutation', 13],
+ ['deleteDocumentByPath', 'mutation', 13],
+ ['deleteDocumentPermanentlyByPath', 'mutation', 13],
+ ['deleteSkillByPath', 'mutation', 13],
+ ['generateSkillMeta', 'mutation', 13],
+ ['getContext', 'query', 12],
+ ['getContextDocuments', 'query', 12],
+ ['getDocument', 'query', 12],
+ ['getDocuments', 'query', 12],
+ ['getDocumentsMap', 'query', 12],
+ ['getOrCreateChatTopic', 'mutation', 12],
+ ['getReaderDocument', 'query', 12],
+ ['getTemplates', 'query', 11],
+ ['hasDocuments', 'query', 12],
+ ['importFile', 'mutation', 13],
+ ['initializeFromTemplate', 'mutation', 13],
+ ['listDocuments', 'query', 12],
+ ['listDocumentsByPath', 'query', 12],
+ ['listTrashDocumentsByPath', 'query', 12],
+ ['mkdirDocumentByPath', 'mutation', 13],
+ ['modifyNodes', 'mutation', 13],
+ ['moveDocuments', 'mutation', 13],
+ ['readDocument', 'query', 12],
+ ['readDocumentByPath', 'query', 12],
+ ['removeDocument', 'mutation', 13],
+ ['renameDocument', 'mutation', 13],
+ ['renameDocumentByPath', 'mutation', 13],
+ ['replaceDocumentContent', 'mutation', 13],
+ ['restoreDocumentFromTrashByPath', 'mutation', 13],
+ ['statDocumentByPath', 'query', 12],
+ ['updateLoadRule', 'mutation', 13],
+ ['updateSkillByPath', 'mutation', 13],
+ ['upsertDocument', 'mutation', 13],
+ ['writeDocumentByPath', 'mutation', 13],
+ ];
+}
diff --git a/apps/server/src/routers/lambda/agentDocument/index.ts b/apps/server/src/routers/lambda/agentDocument/index.ts
new file mode 100644
index 00000000000..1cde3ac096c
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentDocument/index.ts
@@ -0,0 +1,13 @@
+import { mergeRouters } from '@/libs/trpc/lambda';
+
+import { documentsRouter } from './documents';
+import { skillsRouter } from './skills';
+import { toolDocumentsRouter } from './toolDocuments';
+import { vfsRouter } from './vfs';
+
+export const agentDocumentRouter = mergeRouters(
+ documentsRouter,
+ vfsRouter,
+ skillsRouter,
+ toolDocumentsRouter,
+);
diff --git a/apps/server/src/routers/lambda/agentDocument/procedures.ts b/apps/server/src/routers/lambda/agentDocument/procedures.ts
new file mode 100644
index 00000000000..f75593bfabf
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentDocument/procedures.ts
@@ -0,0 +1,82 @@
+import { TRPCError } from '@trpc/server';
+
+import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { AgentDocumentModel } from '@/database/models/agentDocuments';
+import { TopicModel } from '@/database/models/topic';
+import { TopicDocumentModel } from '@/database/models/topicDocument';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { AgentDocumentsService } from '@/server/services/agentDocuments';
+import { createDocumentWorkRegistrar } from '@/server/services/agentDocuments/documentWork';
+import { AgentDocumentVfsService } from '@/server/services/agentDocumentVfs';
+import { AgentDocumentVfsError } from '@/server/services/agentDocumentVfs/errors';
+import { SkillManagementDocumentService } from '@/server/services/skillManagement';
+import { SystemAgentService } from '@/server/services/systemAgent';
+
+const agentDocumentVfsErrorToTRPCCode = (
+ code: AgentDocumentVfsError['code'],
+): 'BAD_REQUEST' | 'CONFLICT' | 'FORBIDDEN' | 'METHOD_NOT_SUPPORTED' | 'NOT_FOUND' => {
+ switch (code) {
+ case 'CONFLICT': {
+ return 'CONFLICT';
+ }
+ case 'FORBIDDEN': {
+ return 'FORBIDDEN';
+ }
+ case 'METHOD_NOT_SUPPORTED': {
+ return 'METHOD_NOT_SUPPORTED';
+ }
+ case 'NOT_FOUND': {
+ return 'NOT_FOUND';
+ }
+ default: {
+ return 'BAD_REQUEST';
+ }
+ }
+};
+
+export const handleAgentDocumentVfsError = (error: unknown): never => {
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+
+ if (error instanceof AgentDocumentVfsError) {
+ throw new TRPCError({
+ cause: error,
+ code: agentDocumentVfsErrorToTRPCCode(error.code),
+ message: error.message,
+ });
+ }
+
+ throw error;
+};
+
+export const agentDocumentProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+ const wsId = ctx.workspaceId ?? undefined;
+
+ return opts.next({
+ ctx: {
+ agentDocumentModel: new AgentDocumentModel(ctx.serverDB, ctx.userId, wsId),
+ agentDocumentService: new AgentDocumentsService(ctx.serverDB, ctx.userId, wsId),
+ agentDocumentVfsService: new AgentDocumentVfsService(ctx.serverDB, ctx.userId, wsId),
+ skillManagementService: new SkillManagementDocumentService(ctx.serverDB, ctx.userId, wsId),
+ systemAgentService: new SystemAgentService(ctx.serverDB, ctx.userId, wsId),
+ documentWorkRegistrar: createDocumentWorkRegistrar({
+ db: ctx.serverDB,
+ logPrefix: '[agentDocumentRouter]',
+ userId: ctx.userId,
+ workspaceId: wsId,
+ }),
+ topicModel: new TopicModel(ctx.serverDB, ctx.userId, wsId),
+ topicDocumentModel: new TopicDocumentModel(ctx.serverDB, ctx.userId, wsId),
+ },
+ });
+});
+
+// Write variant gates viewers out of every agent-document mutation
+// (upsert/delete/rename/copy/skill-edit, plus the VFS path-based writes).
+// Read endpoints keep using `agentDocumentProcedure`.
+export const agentDocumentProcedureWrite = agentDocumentProcedure.use(
+ withScopedPermission('document:update'),
+);
diff --git a/apps/server/src/routers/lambda/agentDocument/skills.ts b/apps/server/src/routers/lambda/agentDocument/skills.ts
new file mode 100644
index 00000000000..9f19c6ae0c4
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentDocument/skills.ts
@@ -0,0 +1,212 @@
+import { AGENT_DOCUMENT_CATEGORY } from '@lobechat/const';
+import { TRPCError } from '@trpc/server';
+import matter from 'gray-matter';
+import { z } from 'zod';
+
+import { deriveAgentDocumentFields } from '@/database/models/agentDocuments';
+import { router } from '@/libs/trpc/lambda';
+import type { AgentDocumentsService } from '@/server/services/agentDocuments';
+import { getUnifiedSkillNamespaceRootPath } from '@/server/services/agentDocumentVfs/mounts/skills/path';
+
+import { agentDocumentProcedureWrite, handleAgentDocumentVfsError } from './procedures';
+
+const mountedSkillNamespaceSchema = z.literal('agent');
+
+const createMountedSkillSchema = z.object({
+ agentId: z.string(),
+ content: z.string(),
+ skillName: z.string().min(1),
+ targetNamespace: mountedSkillNamespaceSchema,
+});
+
+const deleteMountedSkillSchema = z.object({
+ agentId: z.string(),
+ path: z.string(),
+});
+
+const updateMountedSkillSchema = z.object({
+ agentId: z.string(),
+ content: z.string(),
+ path: z.string(),
+});
+
+/**
+ * Strips a leading YAML frontmatter block from Markdown so it can be re-fed as
+ * `bodyMarkdown` to the skill-management service (which renders its own
+ * frontmatter and rejects bodies that already contain one).
+ */
+const stripLeadingFrontmatter = (content: string): string => {
+ try {
+ const parsed = matter(content);
+ return parsed.matter ? parsed.content.trimStart() : content;
+ } catch {
+ return content;
+ }
+};
+
+const convertSkillErrorToTRPC = (error: unknown): never => {
+ if (error instanceof TRPCError) throw error;
+
+ if (error instanceof Error) {
+ if (/already exists/i.test(error.message)) {
+ throw new TRPCError({ cause: error, code: 'CONFLICT', message: error.message });
+ }
+ if (/invalid skill name|required|frontmatter/i.test(error.message)) {
+ throw new TRPCError({ cause: error, code: 'BAD_REQUEST', message: error.message });
+ }
+ }
+
+ throw error;
+};
+
+/**
+ * Resolve the markdown body of a document that is eligible to become a skill.
+ *
+ * Shared by `convertDocumentToSkill` and `generateSkillMeta`. Rejects missing
+ * documents, and — same as the convert path — folders, web sources, and
+ * managed skill bundle/index rows. `createSkill` reparents the source row under
+ * a new bundle, so converting an existing skill index would strip its original
+ * bundle of its SKILL.md and corrupt it. The UI hides the action for these, but
+ * a stale/scripted client could still call through, so enforce it server-side.
+ */
+const resolveConvertibleDocumentBody = async (
+ service: AgentDocumentsService,
+ agentId: string,
+ sourceAgentDocumentId: string,
+): Promise<string> => {
+ const source = await service.getDocumentById(sourceAgentDocumentId, agentId);
+
+ if (!source) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Source document not found' });
+ }
+
+ const { category, isFolder } = deriveAgentDocumentFields(source);
+ if (category !== AGENT_DOCUMENT_CATEGORY || isFolder) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Only a plain agent document can be converted into a skill',
+ });
+ }
+
+ const bodyMarkdown = stripLeadingFrontmatter(source.content ?? '').trim();
+
+ if (!bodyMarkdown) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Cannot convert an empty document into a skill',
+ });
+ }
+
+ return bodyMarkdown;
+};
+
+export const skillsRouter = router({
+ createSkillByPath: agentDocumentProcedureWrite
+ .input(createMountedSkillSchema)
+ .mutation(async ({ ctx, input }) => {
+ try {
+ const path = `${getUnifiedSkillNamespaceRootPath(input.targetNamespace)}/${input.skillName}`;
+
+ return await ctx.agentDocumentVfsService.write(
+ path,
+ input.content,
+ {
+ agentId: input.agentId,
+ },
+ { createMode: 'always-new' },
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+ /**
+ * Converts an existing agent document into a managed skill (direct migration).
+ *
+ * The source document row is reused as the skill's `SKILL.md` index (its
+ * `documents.id` / `agent_documents.id` are preserved), and a new
+ * `skills/bundle` parent is created to hold it. After this call the original
+ * document no longer appears at its previous location in the tree.
+ */
+ convertDocumentToSkill: agentDocumentProcedureWrite
+ .input(
+ z.object({
+ agentId: z.string(),
+ description: z.string().trim().min(1),
+ name: z.string().trim().min(1),
+ sourceAgentDocumentId: z.string(),
+ title: z.string().trim().min(1),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const bodyMarkdown = await resolveConvertibleDocumentBody(
+ ctx.agentDocumentService,
+ input.agentId,
+ input.sourceAgentDocumentId,
+ );
+
+ try {
+ return await ctx.skillManagementService.createSkill({
+ agentId: input.agentId,
+ bodyMarkdown,
+ description: input.description,
+ name: input.name,
+ sourceAgentDocumentId: input.sourceAgentDocumentId,
+ title: input.title,
+ });
+ } catch (error) {
+ return convertSkillErrorToTRPC(error);
+ }
+ }),
+ /**
+ * Generates skill metadata (name / title / description) from a document's
+ * content, used to prefill the convert-to-skill form. Does not mutate the
+ * document; returns `null` when generation fails so the caller can fall back
+ * to its own defaults.
+ */
+ generateSkillMeta: agentDocumentProcedureWrite
+ .input(
+ z.object({
+ agentId: z.string(),
+ sourceAgentDocumentId: z.string(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const bodyMarkdown = await resolveConvertibleDocumentBody(
+ ctx.agentDocumentService,
+ input.agentId,
+ input.sourceAgentDocumentId,
+ );
+
+ return ctx.systemAgentService.generateSkillMeta({
+ agentId: input.agentId,
+ content: bodyMarkdown,
+ });
+ }),
+ updateSkillByPath: agentDocumentProcedureWrite
+ .input(updateMountedSkillSchema)
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await ctx.agentDocumentVfsService.write(
+ input.path,
+ input.content,
+ {
+ agentId: input.agentId,
+ },
+ { createMode: 'must-exist' },
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+ deleteSkillByPath: agentDocumentProcedureWrite
+ .input(deleteMountedSkillSchema)
+ .mutation(async ({ ctx, input }) => {
+ try {
+ await ctx.agentDocumentVfsService.delete(input.path, {
+ agentId: input.agentId,
+ });
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+});
diff --git a/apps/server/src/routers/lambda/agentDocument/toolDocuments.ts b/apps/server/src/routers/lambda/agentDocument/toolDocuments.ts
new file mode 100644
index 00000000000..83678eeb227
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentDocument/toolDocuments.ts
@@ -0,0 +1,517 @@
+import { DocumentLoadFormat, DocumentLoadRule } from '@lobechat/agent-templates';
+import { MOVE_DOCUMENTS_MAX_IDS } from '@lobechat/builtin-tool-agent-documents';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { router } from '@/libs/trpc/lambda';
+import { emitAgentDocumentToolOutcomeSafely } from '@/server/services/agentDocuments/toolOutcome';
+import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';
+
+import {
+ agentDocumentProcedure,
+ agentDocumentProcedureWrite,
+ handleAgentDocumentVfsError,
+} from './procedures';
+
+const MAX_RULE_REGEXP_LENGTH = 512;
+
+const toolLoadRuleSchema = z.object({
+ keywordMatchMode: z.enum(['any', 'all']).optional(),
+ keywords: z.array(z.string()).optional(),
+ maxTokens: z.number().int().min(0).optional(),
+ policyLoadFormat: z.nativeEnum(DocumentLoadFormat).optional(),
+ priority: z.number().int().min(0).optional(),
+ regexp: z.string().max(MAX_RULE_REGEXP_LENGTH).optional(),
+ rule: z.nativeEnum(DocumentLoadRule).optional(),
+ timeRange: z.object({ from: z.string().optional(), to: z.string().optional() }).optional(),
+});
+
+const readFormatSchema = z.enum(['xml', 'markdown', 'both']).optional();
+
+const agentDocumentToolContextSchema = z.object({
+ messageId: z.string(),
+ operationId: z.string().optional(),
+ rootOperationId: z.string().optional(),
+ taskId: z.string().nullish(),
+ threadId: z.string().nullish(),
+ toolCallId: z.string(),
+ toolMessageId: z.string().optional(),
+ topicId: z.string().optional(),
+});
+
+const agentDocumentToolTriggerSchema = z
+ .object({
+ // REVIEW: @nekomeowww is not fully certain this attribution boundary is clear enough.
+ // TODO: Remove this explicit parameter threading if gateway-mode migration makes tool execution fully server-attributed.
+ toolContext: agentDocumentToolContextSchema.optional(),
+ trigger: z.literal('tool').optional(),
+ })
+ .superRefine((value, ctx) => {
+ if (value.trigger === 'tool' && !value.toolContext) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: 'toolContext is required when trigger is tool',
+ path: ['toolContext'],
+ });
+ }
+ });
+
+const liteXMLOperationSchema = z.union([
+ z.object({
+ action: z.literal('insert'),
+ beforeId: z.string(),
+ litexml: z.string(),
+ }),
+ z.object({
+ action: z.literal('insert'),
+ afterId: z.string(),
+ litexml: z.string(),
+ }),
+ z.object({
+ action: z.literal('modify'),
+ litexml: z.union([z.string(), z.array(z.string())]),
+ }),
+ z.object({
+ action: z.literal('remove'),
+ id: z.string(),
+ }),
+]);
+
+const emitCreateDocumentToolOutcome = async (input: {
+ agentDocumentId?: string;
+ agentId: string;
+ apiName: string;
+ errorReason?: string;
+ hintIsSkill?: boolean;
+ status: 'failed' | 'succeeded';
+ toolContext?: z.infer<typeof agentDocumentToolContextSchema>;
+ topicId?: string;
+ userId: string;
+}) => {
+ const { toolContext } = input;
+
+ if (!toolContext) return;
+
+ await emitAgentDocumentToolOutcomeSafely({
+ agentDocumentId: input.agentDocumentId,
+ agentId: input.agentId,
+ apiName: input.apiName,
+ errorReason: input.errorReason,
+ hintIsSkill: input.hintIsSkill,
+ messageId: toolContext.messageId,
+ operationId: toolContext.operationId,
+ relation: 'created',
+ status: input.status,
+ summary:
+ input.status === 'succeeded'
+ ? 'Agent documents created a document.'
+ : 'Agent documents failed to create a document.',
+ taskId: toolContext.taskId,
+ toolAction: 'create',
+ toolCallId: toolContext.toolCallId,
+ topicId: input.topicId ?? toolContext.topicId,
+ userId: input.userId,
+ });
+};
+
+export const toolDocumentsRouter = router({
+ /**
+ * Tool-oriented: associate an existing document with an agent
+ */
+ associateDocument: agentDocumentProcedureWrite
+ .input(
+ z.object({
+ agentId: z.string(),
+ documentId: z.string(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ return ctx.agentDocumentService.associateDocument(input.agentId, input.documentId);
+ }),
+ importFile: agentDocumentProcedureWrite
+ .input(
+ z.object({
+ agentId: z.string(),
+ fileId: z.string(),
+ parentId: z.string().nullish(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ return ctx.agentDocumentService.importFile(input.agentId, input.fileId, input.parentId);
+ }),
+ /**
+ * Tool-oriented: create document
+ */
+ createDocument: agentDocumentProcedureWrite
+ .input(
+ z
+ .object({
+ agentId: z.string(),
+ content: z.string(),
+ hintIsSkill: z.boolean().optional(),
+ parentId: z.string().optional(),
+ title: z.string(),
+ })
+ .and(agentDocumentToolTriggerSchema),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ const doc = await ctx.agentDocumentService.createDocument(
+ input.agentId,
+ input.title,
+ input.content,
+ {
+ hintIsSkill: input.hintIsSkill,
+ parentId: input.parentId,
+ },
+ );
+
+ if (input.trigger === 'tool') {
+ await emitCreateDocumentToolOutcome({
+ agentDocumentId: doc?.id,
+ agentId: input.agentId,
+ apiName: 'createDocument',
+ hintIsSkill: input.hintIsSkill,
+ status: 'succeeded',
+ toolContext: input.toolContext,
+ userId: ctx.userId,
+ });
+ }
+
+ return doc;
+ } catch (error) {
+ if (input.trigger === 'tool') {
+ await emitCreateDocumentToolOutcome({
+ agentId: input.agentId,
+ apiName: 'createDocument',
+ errorReason: error instanceof Error ? error.message : String(error),
+ hintIsSkill: input.hintIsSkill,
+ status: 'failed',
+ toolContext: input.toolContext,
+ userId: ctx.userId,
+ });
+ }
+
+ throw error;
+ }
+ }),
+ /**
+ * Create an agent document and associate it with a topic in one call.
+ * Used by the topic → page flow to create an agent document.
+ */
+ createForTopic: agentDocumentProcedureWrite
+ .input(
+ z
+ .object({
+ agentId: z.string(),
+ content: z.string(),
+ hintIsSkill: z.boolean().optional(),
+ parentId: z.string().optional(),
+ title: z.string(),
+ topicId: z.string(),
+ })
+ .and(agentDocumentToolTriggerSchema),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ // Use the creator-facing finder: a visitor topic's title must not be
+ // copied into a creator-owned document.
+ const topic = input.title.trim()
+ ? undefined
+ : await ctx.topicModel.findOwnTopicById(input.topicId);
+ const title = input.title.trim() || topic?.title || '';
+ const doc = await ctx.agentDocumentService.createForTopic(
+ input.agentId,
+ title,
+ input.content,
+ input.topicId,
+ { hintIsSkill: input.hintIsSkill, parentId: input.parentId },
+ );
+
+ if (input.trigger === 'tool') {
+ await emitCreateDocumentToolOutcome({
+ agentDocumentId: doc?.id,
+ agentId: input.agentId,
+ apiName: 'createForTopic',
+ hintIsSkill: input.hintIsSkill,
+ status: 'succeeded',
+ toolContext: input.toolContext,
+ topicId: input.topicId,
+ userId: ctx.userId,
+ });
+ }
+
+ return doc;
+ } catch (error) {
+ if (input.trigger === 'tool') {
+ await emitCreateDocumentToolOutcome({
+ agentId: input.agentId,
+ apiName: 'createForTopic',
+ errorReason: error instanceof Error ? error.message : String(error),
+ hintIsSkill: input.hintIsSkill,
+ status: 'failed',
+ toolContext: input.toolContext,
+ topicId: input.topicId,
+ userId: ctx.userId,
+ });
+ }
+
+ throw error;
+ }
+ }),
+ /** Read-only document payload for the standalone Agent Document page. */
+ getReaderDocument: agentDocumentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ documentId: z.string(),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ const grantedPermissions = (ctx as { workspacePermissionCodes?: string[] })
+ .workspacePermissionCodes;
+
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'view',
+ db: ctx.serverDB,
+ grantedPermissions,
+ resourceId: input.agentId,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
+
+ const document = await ctx.agentDocumentService.getReaderDocument(
+ input.agentId,
+ input.documentId,
+ );
+
+ if (!document) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent document not found' });
+ }
+
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'view',
+ db: ctx.serverDB,
+ grantedPermissions,
+ resourceId: input.documentId,
+ resourceType: 'document',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
+
+ return {
+ content: document.content,
+ documentId: document.documentId,
+ filename: document.filename,
+ fileType: document.fileType,
+ sourceType: document.sourceType,
+ title: document.title,
+ updatedAt: document.updatedAt,
+ };
+ }),
+ /**
+ * Tool-oriented: read document by id
+ */
+ readDocument: agentDocumentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ format: readFormatSchema,
+ id: z.string(),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ return input.format
+ ? ctx.agentDocumentService.getDocumentSnapshotById(input.id, input.agentId)
+ : ctx.agentDocumentService.getDocumentById(input.id, input.agentId);
+ }),
+ /**
+ * Tool-oriented: modify document nodes by id through LiteXML.
+ */
+ modifyNodes: agentDocumentProcedureWrite
+ .input(
+ z
+ .object({
+ agentId: z.string(),
+ id: z.string(),
+ operations: z.array(liteXMLOperationSchema).min(1),
+ })
+ .and(agentDocumentToolTriggerSchema),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const doc = await ctx.agentDocumentService.modifyDocumentNodesById(
+ input.id,
+ input.operations,
+ input.agentId,
+ );
+
+ return doc;
+ }),
+ /**
+ * Tool-oriented: replace document content by id
+ */
+ replaceDocumentContent: agentDocumentProcedureWrite
+ .input(
+ z
+ .object({
+ agentId: z.string(),
+ content: z.string(),
+ id: z.string(),
+ })
+ .and(agentDocumentToolTriggerSchema),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const doc = await ctx.agentDocumentService.replaceDocumentContentById(
+ input.id,
+ input.content,
+ input.agentId,
+ );
+
+ return doc;
+ }),
+ /**
+ * Tool-oriented: remove document by id
+ */
+ removeDocument: agentDocumentProcedureWrite
+ .input(
+ z
+ .object({
+ agentId: z.string(),
+ id: z.string(),
+ // Also delete documents nested under it; without it a parent with
+ // children is refused instead of stranding them.
+ withChildren: z.boolean().optional(),
+ })
+ .and(agentDocumentToolTriggerSchema),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const doc = await ctx.agentDocumentService.getDocumentById(input.id, input.agentId);
+ const deleted = await ctx.agentDocumentService
+ .removeDocumentById(input.id, input.agentId, { withChildren: input.withChildren })
+ .catch(handleAgentDocumentVfsError);
+ if (deleted && input.trigger === 'tool') {
+ await ctx.documentWorkRegistrar.deleteDocumentWork({
+ agentDocumentId: input.id,
+ agentId: input.agentId,
+ documentId: doc?.documentId,
+ });
+ }
+
+ return { deleted, id: input.id };
+ }),
+ /**
+ * Tool-oriented: copy document by id
+ */
+ copyDocument: agentDocumentProcedureWrite
+ .input(
+ z
+ .object({
+ agentId: z.string(),
+ id: z.string(),
+ newTitle: z.string().optional(),
+ })
+ .and(agentDocumentToolTriggerSchema),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ const doc = await ctx.agentDocumentService.copyDocumentById(
+ input.id,
+ input.newTitle,
+ input.agentId,
+ );
+
+ return doc;
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+ /**
+ * Tool-oriented: rename document by id
+ */
+ renameDocument: agentDocumentProcedureWrite
+ .input(
+ z
+ .object({
+ agentId: z.string(),
+ id: z.string(),
+ newTitle: z.string(),
+ })
+ .and(agentDocumentToolTriggerSchema),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ const doc = await ctx.agentDocumentService.renameDocumentById(
+ input.id,
+ input.newTitle,
+ input.agentId,
+ );
+
+ return doc;
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+ /**
+ * Tool-oriented: create a folder by name, under the root or a parent (folder or document) id
+ */
+ createFolder: agentDocumentProcedureWrite
+ .input(
+ z.object({
+ agentId: z.string(),
+ parentId: z.string().nullish(),
+ title: z.string(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await ctx.agentDocumentService.createFolder(
+ input.agentId,
+ input.title,
+ input.parentId,
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+ /**
+ * Tool-oriented: move documents/folders by id under a parent (folder or document), or to the root with `null`
+ */
+ moveDocuments: agentDocumentProcedureWrite
+ .input(
+ z.object({
+ agentId: z.string(),
+ ids: z.array(z.string()).min(1).max(MOVE_DOCUMENTS_MAX_IDS),
+ parentId: z.string().nullable(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await ctx.agentDocumentService.moveDocuments(
+ input.agentId,
+ input.ids,
+ input.parentId,
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+ /**
+ * Tool-oriented: update document load rule by id
+ */
+ updateLoadRule: agentDocumentProcedureWrite
+ .input(
+ z.object({
+ agentId: z.string(),
+ id: z.string(),
+ rule: toolLoadRuleSchema,
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ return ctx.agentDocumentService.updateLoadRuleById(input.id, input.rule, input.agentId);
+ }),
+});
diff --git a/apps/server/src/routers/lambda/agentDocument/vfs.ts b/apps/server/src/routers/lambda/agentDocument/vfs.ts
new file mode 100644
index 00000000000..52743c877db
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentDocument/vfs.ts
@@ -0,0 +1,371 @@
+import { z } from 'zod';
+
+import { router } from '@/libs/trpc/lambda';
+
+import {
+ agentDocumentProcedure,
+ agentDocumentProcedureWrite,
+ handleAgentDocumentVfsError,
+} from './procedures';
+
+const readLocSchema = z
+ .tuple([z.number().int().min(0), z.number().int().min(0)])
+ .refine(([startLine, endLine]) => endLine >= startLine, {
+ message: 'loc end line must be greater than or equal to start line',
+ })
+ .optional();
+
+const writeCreateModeSchema = z.enum(['always-new', 'if-missing', 'must-exist']).optional();
+
+const recursiveSchema = z.boolean().optional();
+
+export const vfsRouter = router({
+ /**
+ * Tool-oriented: list documents for an agent
+ */
+ listDocuments: agentDocumentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ // Drop `sourceType: 'web'` docs (saved web-clips / articles). These grow
+ // unbounded and dominate the payload, but only the working-sidebar "web"
+ // tab renders them. Hot-path consumers (slash menu, skills) pass this so
+ // the list stays small. Ignored for `currentTopic` scope.
+ excludeWeb: z.boolean().optional().default(false),
+ // Reveal the auto-created `.tool-results` archive. Off by default so
+ // user-facing lists stay clean; the agent document-listing tool opts in.
+ includeArchivedToolResults: z.boolean().optional().default(false),
+ // Restrict the listing to the direct children of this folder so the model
+ // can expand a folder collapsed in the progressive index.
+ parentId: z.string().optional(),
+ scope: z.enum(['agent', 'currentTopic']).optional().default('agent'),
+ sourceType: z.enum(['all', 'file', 'web']).optional().default('all'),
+ topicId: z.string().optional(),
+ // Stamp `childCount` on entries with something nested under them (the
+ // agent tool needs it to spot a workflow document holding its runs).
+ withChildCount: z.boolean().optional().default(false),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ const { excludeWeb, includeArchivedToolResults, parentId } = input;
+ const withChildCounts = async <T extends { documentId: string }>(docs: T[]) => {
+ if (!input.withChildCount) return docs;
+ const counts = await ctx.agentDocumentService.countChildren(input.agentId);
+ return docs.map((doc) => ({ ...doc, childCount: counts.get(doc.documentId) ?? 0 }));
+ };
+ try {
+ if (input.scope === 'currentTopic') {
+ if (!input.topicId) {
+ throw new Error('topicId is required to list current topic documents');
+ }
+
+ const docs = await ctx.agentDocumentService.listDocumentsForTopic(
+ input.agentId,
+ input.topicId,
+ input.sourceType,
+ { includeArchivedToolResults },
+ );
+ if (!parentId) return await withChildCounts(docs);
+
+ // Topic listing joins through topic associations rather than the agent
+ // folder tree, so the parent filter is applied in-memory here.
+ const parent = await ctx.agentDocumentService.resolveParent(input.agentId, parentId);
+ return await withChildCounts(docs.filter((d) => d.parentId === parent.documentId));
+ }
+
+ return await withChildCounts(
+ await ctx.agentDocumentService.listDocuments(input.agentId, input.sourceType, {
+ excludeWeb,
+ includeArchivedToolResults,
+ parentId,
+ }),
+ );
+ } catch (error) {
+ return handleAgentDocumentVfsError(error);
+ }
+ }),
+ /**
+ * Tool-oriented: list documents by VFS path
+ */
+ listDocumentsByPath: agentDocumentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ cursor: z.string().optional(),
+ limit: z.number().int().positive().max(500).optional(),
+ path: z.string(),
+ topicId: z.string().optional(),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ try {
+ return await ctx.agentDocumentVfsService.list(
+ input.path,
+ {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ },
+ {
+ cursor: input.cursor,
+ limit: input.limit,
+ },
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+ /**
+ * Tool-oriented: stat document by VFS path
+ */
+ statDocumentByPath: agentDocumentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ path: z.string(),
+ topicId: z.string().optional(),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ try {
+ return await ctx.agentDocumentVfsService.stat(input.path, {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ });
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+ /**
+ * Tool-oriented: read document by VFS path
+ */
+ readDocumentByPath: agentDocumentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ loc: readLocSchema,
+ path: z.string(),
+ topicId: z.string().optional(),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ try {
+ return await ctx.agentDocumentVfsService.read(
+ input.path,
+ {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ },
+ {
+ loc: input.loc,
+ },
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+ /**
+ * Tool-oriented: write document by VFS path
+ */
+ writeDocumentByPath: agentDocumentProcedureWrite
+ .input(
+ z.object({
+ agentId: z.string(),
+ content: z.string(),
+ createMode: writeCreateModeSchema,
+ path: z.string(),
+ topicId: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await ctx.agentDocumentVfsService.write(
+ input.path,
+ input.content,
+ {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ },
+ { createMode: input.createMode },
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+ /**
+ * Tool-oriented: create a VFS directory
+ */
+ mkdirDocumentByPath: agentDocumentProcedureWrite
+ .input(
+ z.object({
+ agentId: z.string(),
+ path: z.string(),
+ recursive: recursiveSchema,
+ topicId: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await ctx.agentDocumentVfsService.mkdir(
+ input.path,
+ {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ },
+ { recursive: input.recursive },
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+ /**
+ * Tool-oriented: rename or move a VFS path
+ */
+ renameDocumentByPath: agentDocumentProcedureWrite
+ .input(
+ z.object({
+ agentId: z.string(),
+ force: z.boolean().optional(),
+ fromPath: z.string(),
+ toPath: z.string(),
+ topicId: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await ctx.agentDocumentVfsService.rename(
+ input.fromPath,
+ input.toPath,
+ {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ },
+ { overwrite: input.force },
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+ /**
+ * Tool-oriented: copy a VFS path
+ */
+ copyDocumentByPath: agentDocumentProcedureWrite
+ .input(
+ z.object({
+ agentId: z.string(),
+ force: z.boolean().optional(),
+ fromPath: z.string(),
+ toPath: z.string(),
+ topicId: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await ctx.agentDocumentVfsService.copy(
+ input.fromPath,
+ input.toPath,
+ {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ },
+ { overwrite: input.force },
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+ /**
+ * Tool-oriented: soft-delete a VFS path
+ */
+ deleteDocumentByPath: agentDocumentProcedureWrite
+ .input(
+ z.object({
+ agentId: z.string(),
+ force: z.boolean().optional(),
+ path: z.string(),
+ recursive: recursiveSchema,
+ topicId: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ await ctx.agentDocumentVfsService.delete(
+ input.path,
+ {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ },
+ { recursive: input.recursive },
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+ /**
+ * Tool-oriented: list agent-scoped trash entries
+ */
+ listTrashDocumentsByPath: agentDocumentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ path: z.string().optional(),
+ topicId: z.string().optional(),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ try {
+ return await ctx.agentDocumentVfsService.listTrash(
+ {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ },
+ input.path,
+ );
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+ /**
+ * Tool-oriented: restore a trash entry
+ */
+ restoreDocumentFromTrashByPath: agentDocumentProcedureWrite
+ .input(
+ z.object({
+ agentId: z.string(),
+ path: z.string(),
+ topicId: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await ctx.agentDocumentVfsService.restoreFromTrashByPath(input.path, {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ });
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+ /**
+ * Tool-oriented: permanently remove a trash entry
+ */
+ deleteDocumentPermanentlyByPath: agentDocumentProcedureWrite
+ .input(
+ z.object({
+ agentId: z.string(),
+ force: z.boolean().optional(),
+ path: z.string(),
+ recursive: recursiveSchema,
+ topicId: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ await ctx.agentDocumentVfsService.deletePermanentlyByPath(input.path, {
+ agentId: input.agentId,
+ topicId: input.topicId,
+ });
+ } catch (error) {
+ handleAgentDocumentVfsError(error);
+ }
+ }),
+});