File size: 2,966 Bytes
c09f67c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import type { AppContext } from "@api/ai/agents/config/shared";
import { db } from "@midday/db/client";
import { getDocuments } from "@midday/db/queries";
import { getAppUrl } from "@midday/utils/envs";
import { formatDate } from "@midday/utils/format";
import { tool } from "ai";
import { z } from "zod";

const getDocumentsSchema = z.object({
  cursor: z.string().nullable().optional().describe("Pagination cursor"),
  pageSize: z.number().min(1).max(100).default(10).describe("Page size"),
  q: z.string().nullable().optional().describe("Search query"),
  tags: z.array(z.string()).nullable().optional().describe("Tag IDs"),
  start: z.string().nullable().optional().describe("Start date (ISO 8601)"),
  end: z.string().nullable().optional().describe("End date (ISO 8601)"),
});

export const getDocumentsTool = tool({
  description:
    "Retrieve and filter documents with pagination, sorting, and search.",
  inputSchema: getDocumentsSchema,
  execute: async function* (
    { cursor, pageSize = 10, q, tags, start, end },
    executionOptions,
  ) {
    const appContext = executionOptions.experimental_context as AppContext;
    const teamId = appContext.teamId as string;

    if (!teamId) {
      yield {
        text: "Unable to retrieve documents: Team ID not found in context.",
      };
      return;
    }

    try {
      const params = {
        teamId,
        cursor: cursor ?? null,
        pageSize,
        q: q ?? null,
        tags: tags ?? null,
        start: start ?? null,
        end: end ?? null,
      };

      const result = await getDocuments(db, params);

      if (result.data.length === 0) {
        yield { text: "No documents found matching your criteria." };
        return;
      }

      const formattedDocuments = result.data.map((document) => {
        const tagNames =
          document.documentTagAssignments
            ?.map((dta) => dta.documentTag?.name)
            .filter((name): name is string => Boolean(name))
            .join(", ") || "None";

        return {
          id: document.id,
          name: document.name?.split("/").pop() || "Untitled",
          title:
            document.title || document.name?.split("/").pop() || "Untitled",
          date: document.date ? formatDate(document.date) : "N/A",
          tags: tagNames,
          status: document.processingStatus || "unknown",
        };
      });

      const response = `| Name | Title | Date | Tags | Status |\n|------|-------|------|------|--------|\n${formattedDocuments.map((doc) => `| ${doc.name} | ${doc.title} | ${doc.date} | ${doc.tags} | ${doc.status} |`).join("\n")}\n\n**${result.data.length} documents**`;

      yield {
        text: response,
        link: {
          text: "View all documents",
          url: `${getAppUrl()}/vault`,
        },
      };
    } catch (error) {
      yield {
        text: `Failed to retrieve documents: ${error instanceof Error ? error.message : "Unknown error"}`,
      };
    }
  },
});