@mastra/dane 0.0.2-alpha.2 → 0.0.2-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/commands/issue-labeler.d.ts +1 -0
  2. package/dist/commands/issue-labeler.js +18 -0
  3. package/dist/commands/message.d.ts +1 -0
  4. package/dist/commands/message.js +12 -0
  5. package/dist/index.d.ts +2 -0
  6. package/{src/index.ts → dist/index.js} +0 -5
  7. package/dist/mastra/agents/index.d.ts +167 -0
  8. package/{src/mastra/agents/index.ts → dist/mastra/agents/index.js} +25 -28
  9. package/dist/mastra/index.d.ts +195 -0
  10. package/dist/mastra/index.js +29 -0
  11. package/dist/mastra/integrations/index.d.ts +4 -0
  12. package/{src/mastra/integrations/index.ts → dist/mastra/integrations/index.js} +3 -5
  13. package/dist/mastra/tools/browser.d.ts +39 -0
  14. package/dist/mastra/tools/browser.js +116 -0
  15. package/dist/mastra/tools/calendar.d.ts +20 -0
  16. package/dist/mastra/tools/calendar.js +134 -0
  17. package/dist/mastra/tools/crawl.d.ts +32 -0
  18. package/dist/mastra/tools/crawl.js +24 -0
  19. package/dist/mastra/tools/execa.d.ts +26 -0
  20. package/dist/mastra/tools/execa.js +39 -0
  21. package/dist/mastra/tools/fs.d.ts +32 -0
  22. package/dist/mastra/tools/fs.js +36 -0
  23. package/dist/mastra/tools/pdf.d.ts +20 -0
  24. package/dist/mastra/tools/pdf.js +41 -0
  25. package/dist/mastra/workflows/chat.d.ts +12 -0
  26. package/dist/mastra/workflows/chat.js +93 -0
  27. package/dist/mastra/workflows/index.js +2 -0
  28. package/dist/mastra/workflows/issue-labeler.d.ts +15 -0
  29. package/dist/mastra/workflows/issue-labeler.js +85 -0
  30. package/package.json +7 -4
  31. package/CHANGELOG.md +0 -37
  32. package/docker-compose.yaml +0 -22
  33. package/src/commands/issue-labeler.ts +0 -26
  34. package/src/commands/message.ts +0 -16
  35. package/src/mastra/index.ts +0 -32
  36. package/src/mastra/tools/browser.ts +0 -132
  37. package/src/mastra/tools/calendar.ts +0 -154
  38. package/src/mastra/tools/crawl.ts +0 -26
  39. package/src/mastra/tools/execa.ts +0 -41
  40. package/src/mastra/tools/fs.ts +0 -36
  41. package/src/mastra/tools/pdf.ts +0 -46
  42. package/src/mastra/workflows/chat.ts +0 -111
  43. package/src/mastra/workflows/issue-labeler.ts +0 -104
  44. package/test/data/05-versions-space.pdf +0 -0
  45. package/test/data/05-versions-space.pdf.txt +0 -42
  46. package/test-files/roman.md +0 -79
  47. package/test-files/sample-1.pdf +0 -0
  48. package/test-files/taxes/2022.txt +0 -45
  49. package/test-files/taxes/2023.txt +0 -44
  50. package/tsconfig.json +0 -11
  51. /package/{src/mastra/workflows/index.ts → dist/mastra/workflows/index.d.ts} +0 -0
@@ -0,0 +1,85 @@
1
+ import { Step, Workflow } from '@mastra/core';
2
+ import { z } from 'zod';
3
+ import { github } from '../integrations/index.js';
4
+ export const githubIssueLabeler = new Workflow({
5
+ name: 'github-issue-labeler',
6
+ triggerSchema: z.object({
7
+ repo: z.string(),
8
+ owner: z.string(),
9
+ issue_number: z.number(),
10
+ }),
11
+ });
12
+ const getIssue = new Step({
13
+ id: 'getIssue',
14
+ outputSchema: z.object({
15
+ title: z.string(),
16
+ body: z.string(),
17
+ labelNames: z.array(z.string()),
18
+ }),
19
+ execute: async ({ context }) => {
20
+ const client = await github.getApiClient();
21
+ const issue = await client.issuesGet({
22
+ path: {
23
+ // TODO: Type triggerData in machineContext to the triggerSchema
24
+ owner: context?.machineContext?.triggerData?.owner,
25
+ repo: context?.machineContext?.triggerData?.repo,
26
+ issue_number: context?.machineContext?.triggerData?.issue_number,
27
+ },
28
+ });
29
+ const labels = await client.issuesListLabelsForRepo({
30
+ path: {
31
+ owner: context?.machineContext?.triggerData?.owner,
32
+ repo: context?.machineContext?.triggerData?.repo,
33
+ },
34
+ });
35
+ const labelNames = labels?.data?.map(label => label.name);
36
+ return { title: issue?.data?.title, body: issue?.data?.body, labelNames: labelNames };
37
+ },
38
+ });
39
+ const labelIssue = new Step({
40
+ id: 'labelIssue',
41
+ outputSchema: z.object({
42
+ labels: z.array(z.string()),
43
+ }),
44
+ execute: async ({ context, mastra }) => {
45
+ const parentStep = context?.machineContext?.stepResults?.getIssue;
46
+ if (!parentStep || parentStep.status !== 'success') {
47
+ return { labels: [] };
48
+ }
49
+ const daneIssueLabeler = mastra?.agents?.daneIssueLabeler;
50
+ const res = await daneIssueLabeler?.generate(`
51
+ Hey Dane, given:
52
+ * this issue title: ${parentStep?.payload?.title}
53
+ * this issue body: ${parentStep?.payload?.body}
54
+ * these labels: ${parentStep?.payload?.labelNames}
55
+
56
+ What label or labels would you assign?
57
+ `, {
58
+ schema: z.object({
59
+ labels: z.array(z.string()),
60
+ }),
61
+ });
62
+ return { labels: res?.object?.labels };
63
+ },
64
+ });
65
+ const applyLabels = new Step({
66
+ id: 'applyLabels',
67
+ execute: async ({ context }) => {
68
+ const parentStep = context?.machineContext?.stepResults?.labelIssue;
69
+ if (!parentStep || parentStep.status !== 'success') {
70
+ return;
71
+ }
72
+ const client = await github.getApiClient();
73
+ await client.issuesAddLabels({
74
+ path: {
75
+ owner: context?.machineContext?.triggerData?.owner,
76
+ repo: context?.machineContext?.triggerData?.repo,
77
+ issue_number: context?.machineContext?.triggerData?.issue_number,
78
+ },
79
+ body: {
80
+ labels: parentStep.payload.labels,
81
+ },
82
+ });
83
+ },
84
+ });
85
+ githubIssueLabeler.step(getIssue).then(labelIssue).then(applyLabels).commit();
package/package.json CHANGED
@@ -1,8 +1,11 @@
1
1
  {
2
2
  "name": "@mastra/dane",
3
- "version": "0.0.2-alpha.2",
3
+ "version": "0.0.2-alpha.4",
4
4
  "main": "dist/index.js",
5
5
  "type": "module",
6
+ "files": [
7
+ "dist"
8
+ ],
6
9
  "bin": {
7
10
  "dane": "./dist/index.js"
8
11
  },
@@ -31,11 +34,11 @@
31
34
  "sqlite3": "^5.1.7",
32
35
  "typescript": "^5.5.4",
33
36
  "zod": "^3.24.0",
34
- "@mastra/engine": "0.0.5-alpha.32",
35
37
  "@mastra/core": "0.1.27-alpha.38",
36
- "@mastra/github": "1.0.3-alpha.21",
38
+ "@mastra/firecrawl": "1.0.4-alpha.23",
39
+ "@mastra/engine": "0.0.5-alpha.32",
40
+ "@mastra/github": "1.0.3-alpha.22",
37
41
  "@mastra/memory": "0.0.2-alpha.17",
38
- "@mastra/firecrawl": "1.0.4-alpha.22",
39
42
  "@mastra/rag": "0.0.2-alpha.22"
40
43
  },
41
44
  "scripts": {
package/CHANGELOG.md DELETED
@@ -1,37 +0,0 @@
1
- # @mastra/dane
2
-
3
- ## 0.0.2-alpha.2
4
-
5
- ### Patch Changes
6
-
7
- - ad58c35: Adds a shebang to the dane entry file
8
-
9
- ## 0.0.2-alpha.1
10
-
11
- ### Patch Changes
12
-
13
- - Updated dependencies [f031a1f]
14
- - @mastra/core@0.1.27-alpha.38
15
- - @mastra/rag@0.0.2-alpha.22
16
- - @mastra/firecrawl@1.0.4-alpha.22
17
- - @mastra/github@1.0.3-alpha.21
18
- - @mastra/engine@0.0.5-alpha.32
19
- - @mastra/memory@0.0.2-alpha.17
20
-
21
- ## 0.0.2-alpha.0
22
-
23
- ### Patch Changes
24
-
25
- - b5393f1: New example: Dane and many fixes to make it work
26
- - 697fbbe: Setup Dane, a cli assistant using the mastra framework.
27
- - Updated dependencies [45fd5b8]
28
- - Updated dependencies [c872875]
29
- - Updated dependencies [f6da688]
30
- - Updated dependencies [1cc6cc0]
31
- - Updated dependencies [b5393f1]
32
- - @mastra/rag@0.0.2-alpha.21
33
- - @mastra/core@0.1.27-alpha.37
34
- - @mastra/engine@0.0.5-alpha.31
35
- - @mastra/firecrawl@1.0.4-alpha.21
36
- - @mastra/memory@0.0.2-alpha.16
37
- - @mastra/github@1.0.3-alpha.20
@@ -1,22 +0,0 @@
1
- services:
2
- db:
3
- image: pgvector/pgvector:pg16
4
- container_name: 'dane-db'
5
- ports:
6
- - '5433:5432'
7
- environment:
8
- POSTGRES_USER: ${POSTGRES_USER:-postgres}
9
- POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres}
10
- POSTGRES_DB: ${POSTGRES_DB:-mastra}
11
- redis:
12
- image: redis
13
- ports:
14
- - 6379:6379
15
- serverless-redis-http:
16
- ports:
17
- - "8079:80"
18
- image: hiett/serverless-redis-http:latest
19
- environment:
20
- SRH_MODE: env
21
- SRH_TOKEN: example_token
22
- SRH_CONNECTION_STRING: "redis://redis:6379" # Using `redis` hostname since they're in the same Docker network.
@@ -1,26 +0,0 @@
1
- import chalk from 'chalk';
2
-
3
- import { mastra } from '../mastra/index.js';
4
-
5
- export async function issueLabelerCommand() {
6
- console.log(chalk.green("Hi! I'm Dane!"));
7
- console.log(chalk.green('Let me label this for you..\n'));
8
- const result = await mastra.getWorkflow('githubIssueLabeler').execute({
9
- triggerData: {
10
- issue_number: parseInt(process.env.ISSUE_NUMBER!, 10),
11
- owner: process.env.OWNER!,
12
- repo: process.env.REPO!,
13
- },
14
- });
15
-
16
- if (result.results?.labelIssue?.status !== 'success') {
17
- console.error(chalk.red(`Failed to apply labels for issue: ${result.triggerData?.issue_number}`));
18
- return;
19
- }
20
-
21
- console.log(
22
- chalk.green(
23
- `Issue: ${result.triggerData?.issue_number} has been labeled with: ${result.results?.labelIssue?.payload?.labels.join(', ')}`,
24
- ),
25
- );
26
- }
@@ -1,16 +0,0 @@
1
- import chalk from 'chalk';
2
-
3
- import { mastra } from '../mastra/index.js';
4
-
5
- export async function message() {
6
- console.log(chalk.green("Hi! I'm Dane!"));
7
- console.log(chalk.green('What would you like to do today?\n'));
8
- console.log(
9
- await mastra.getWorkflow('message').execute({
10
- triggerData: {
11
- resourceid: 'f8b5c3a1-d6e7-4f9c-b2a3-1d8e4c7f9b5a',
12
- threadId: '2d9e8c7f-6b5a-4d3c-8f1e-9b7d5c3a2e8h',
13
- },
14
- }),
15
- );
16
- }
@@ -1,32 +0,0 @@
1
- import { Mastra } from '@mastra/core';
2
- import { PostgresEngine } from '@mastra/engine';
3
- import { UpstashKVMemory } from '@mastra/memory';
4
-
5
- import { dane, daneIssueLabeler } from './agents/index.js';
6
- import { firecrawl } from './integrations/index.js';
7
- import { messageWorkflow, githubIssueLabeler } from './workflows/index.js';
8
-
9
- const engine = new PostgresEngine({
10
- url: 'postgres://postgres:postgres@localhost:5433/mastra',
11
- });
12
-
13
- export const mastra = new Mastra({
14
- agents: {
15
- dane,
16
- daneIssueLabeler,
17
- },
18
- engine,
19
- memory: new UpstashKVMemory({
20
- url: 'http://localhost:8079',
21
- token: `example_token`,
22
- maxTokens: 39000,
23
- }),
24
- workflows: {
25
- message: messageWorkflow,
26
- githubIssueLabeler: githubIssueLabeler,
27
- },
28
- logger: false,
29
- syncs: {
30
- ...firecrawl.getSyncs(),
31
- },
32
- });
@@ -1,132 +0,0 @@
1
- import { createTool } from '@mastra/core';
2
- import { MDocument } from '@mastra/rag';
3
- import chalk from 'chalk';
4
- import { chromium } from 'playwright-core';
5
- import { z } from 'zod';
6
-
7
- export const browserTool = createTool({
8
- id: 'browserTool',
9
- name: 'Browser Tool',
10
- description: 'Browser Tool, opens a browser and navigates to a url capturing the content',
11
- inputSchema: z.object({
12
- url: z.string(),
13
- }),
14
- outputSchema: z.object({
15
- message: z.string(),
16
- }),
17
- execute: async ({ context: { url } }) => {
18
- try {
19
- const browser = await chromium.launch({
20
- headless: true,
21
- });
22
-
23
- const page = await browser.newPage();
24
-
25
- await page.goto(url);
26
-
27
- const docs = MDocument.fromHTML(await page.content());
28
-
29
- await docs.chunk({
30
- strategy: 'html',
31
- options: {
32
- chunkSize: 300,
33
- sections: [
34
- ['h1', 'Header 1'],
35
- ['h2', 'Header 2'],
36
- ['h3', 'Header 3'],
37
- ['h4', 'Header 4'],
38
- ['h5', 'Header 5'],
39
- ['h6', 'Header 6'],
40
- ['p', 'Paragraph'],
41
- ],
42
- },
43
- });
44
-
45
- await page.close();
46
- await browser.close();
47
-
48
- if (!docs.getText().length) {
49
- return { message: 'No content' };
50
- }
51
-
52
- return { message: docs.getText().join('\n') };
53
- } catch (e) {
54
- if (e instanceof Error) {
55
- console.log(`\n${chalk.red(e.message)}`);
56
- return { message: `Error: ${e.message}` };
57
- }
58
- return { message: 'Error' };
59
- }
60
- },
61
- });
62
-
63
- export const googleSearch = createTool({
64
- id: 'googleSearch',
65
- name: 'Google Search',
66
- description: 'Google Search. Passes the query to Google and returns the search results.',
67
- inputSchema: z.object({
68
- query: z.string(),
69
- }),
70
- outputSchema: z.object({
71
- message: z.string(),
72
- }),
73
- execute: async ({ context: { query } }) => {
74
- let browser;
75
- try {
76
- browser = await chromium.launch({
77
- headless: true,
78
- });
79
- } catch (e) {
80
- if (e instanceof Error) {
81
- console.log(`\n${chalk.red(e.message)}`);
82
- return { message: `Error: ${e.message}` };
83
- }
84
- return { message: 'Error' };
85
- }
86
-
87
- try {
88
- const page = await browser.newPage();
89
- await page.goto(`https://www.google.com/search?q=${encodeURIComponent(query)}`);
90
-
91
- console.log(`\n`);
92
- console.log(chalk.blue('Waiting for search results...'));
93
-
94
- try {
95
- await page.click('button:has-text("Accept all")', { timeout: 5000 });
96
- } catch (e) {
97
- // Cookie dialog didn't appear, continue
98
- }
99
- // Wait for results and click first organic result
100
- await page.waitForSelector('#search');
101
-
102
- const text = await page.evaluate(() => {
103
- const links: string[] = [];
104
- const searchResults = document.querySelectorAll('div.g a');
105
-
106
- searchResults.forEach(link => {
107
- const href = link.getAttribute('href');
108
- if (href && href.startsWith('http')) {
109
- links.push(href);
110
- }
111
- });
112
-
113
- return links;
114
- });
115
-
116
- await page.close();
117
- await browser.close();
118
-
119
- if (!text.length) {
120
- return { message: 'No results' };
121
- }
122
-
123
- return { message: text.join('\n') };
124
- } catch (e) {
125
- if (e instanceof Error) {
126
- console.log(`\n${chalk.red(e.message)}`);
127
- return { message: `Error: ${e.message}` };
128
- }
129
- return { message: `Error` };
130
- }
131
- },
132
- });
@@ -1,154 +0,0 @@
1
- import { createTool } from '@mastra/core';
2
- import chalk from 'chalk';
3
- import { execSync } from 'child_process';
4
- import Table from 'cli-table3';
5
- import { z } from 'zod';
6
-
7
- interface CalendarEvent {
8
- title: string;
9
- startDate: Date;
10
- endDate: Date;
11
- location?: string;
12
- description?: string;
13
- }
14
-
15
- class LocalCalendarReader {
16
- async getEvents(): Promise<CalendarEvent[]> {
17
- const script = `
18
- tell application "Calendar"
19
- set eventList to {}
20
- set startDate to (current date) - 7 * days
21
- set endDate to (current date) + 365 * days
22
-
23
- repeat with calendarAccount in calendars
24
- set eventList to eventList & (every event of calendarAccount whose start date is greater than or equal to startDate and start date is less than or equal to endDate)
25
- end repeat
26
-
27
- set output to ""
28
- repeat with anEvent in eventList
29
- set theTitle to summary of anEvent
30
- set theStart to start date of anEvent as string
31
- set theEnd to end date of anEvent as string
32
- set theLoc to location of anEvent
33
- set theDesc to description of anEvent
34
-
35
- if theLoc is missing value then
36
- set theLoc to ""
37
- end if
38
- if theDesc is missing value then
39
- set theDesc to ""
40
- end if
41
-
42
- set output to output & theTitle & "|" & theStart & "|" & theEnd & "|" & theLoc & "|" & theDesc & "
43
- "
44
- end repeat
45
-
46
- return output
47
- end tell
48
- `;
49
-
50
- try {
51
- const result = execSync(`osascript -e '${script}'`).toString();
52
- return this.parseAppleScriptOutput(result);
53
- } catch (error) {
54
- if (error instanceof Error) {
55
- console.error('Raw AppleScript error:', error.message);
56
- throw new Error(`Failed to read Mac calendar: ${error.message}`);
57
- } else {
58
- console.error('An unknown error occurred:', error);
59
- throw new Error('Failed to read Mac calendar');
60
- }
61
- }
62
- }
63
-
64
- private parseAppleScriptOutput(output: string): CalendarEvent[] {
65
- const events: CalendarEvent[] = [];
66
-
67
- const lines = output.split('\n').filter(line => line.trim());
68
-
69
- for (const line of lines) {
70
- try {
71
- const [title, startDateStr, endDateStr, location, description] = line.split('|');
72
-
73
- const startStandardized = startDateStr
74
- ?.split(',')?.[1] // Remove day name
75
- ?.replace(' at ', ' ') // Remove 'at'
76
- ?.trim(); // 'January 3, 2025 9:00:00 AM'
77
-
78
- const startDate = new Date(startStandardized || '');
79
-
80
- const endStandardized = endDateStr
81
- ?.split(',')?.[1] // Remove day name
82
- ?.replace(' at ', ' ') // Remove 'at'
83
- ?.trim(); // 'January 3, 2025 9:00:00 AM'
84
- const endDate = new Date(endStandardized || '');
85
-
86
- const event: CalendarEvent = {
87
- title: title?.trim()!,
88
- startDate,
89
- endDate,
90
- location: location?.trim() || '',
91
- description: description?.trim() || '',
92
- };
93
-
94
- events.push(event);
95
- } catch (error) {
96
- console.error('Failed to parse event line:', line, error);
97
- }
98
- }
99
-
100
- return events.sort((a, b) => a.startDate.getTime() - b.startDate.getTime());
101
- }
102
- }
103
-
104
- const reader = new LocalCalendarReader();
105
-
106
- export const listEvents = createTool({
107
- id: 'listEvents',
108
- name: 'List Events',
109
- description: 'List calendar events',
110
- inputSchema: z.object({
111
- startDate: z.string(),
112
- }),
113
- outputSchema: z.object({
114
- content: z.string(),
115
- }),
116
- execute: async () => {
117
- try {
118
- const events = await reader.getEvents();
119
- const table = new Table({
120
- head: [
121
- chalk.blue('Start'),
122
- chalk.blue('End'),
123
- chalk.blue('Title'),
124
- chalk.blue('Location'),
125
- chalk.blue('Description'),
126
- ],
127
- colWidths: [12, 15, 30, 20, 40],
128
- });
129
-
130
- events.forEach(event => {
131
- if (event.title) {
132
- table.push([
133
- event.startDate.toISOString(),
134
- event.endDate.toISOString(),
135
- event.title || '',
136
- event.location || '',
137
- (event.description || '').substring(0, 37) + '...',
138
- ]);
139
- }
140
- });
141
-
142
- // console.log(chalk.blue(table.toString()));
143
-
144
- return {
145
- content: JSON.stringify(events, null, 2),
146
- };
147
- } catch (e) {
148
- if (e instanceof Error) {
149
- console.log(`\n${chalk.red(e.message)}`);
150
- }
151
- return { content: 'Error' };
152
- }
153
- },
154
- });
@@ -1,26 +0,0 @@
1
- import { createTool } from '@mastra/core';
2
- import { z } from 'zod';
3
-
4
- export const crawl = createTool({
5
- id: 'crawler',
6
- name: 'Crawler Tool',
7
- description: 'Crawler Tool to crawl a website and return the content',
8
- inputSchema: z.object({
9
- url: z.string(),
10
- limit: z.number().default(3),
11
- pathRegex: z.string().nullable(),
12
- }),
13
- outputSchema: z.object({
14
- message: z.string(),
15
- }),
16
- execute: async ({ context, mastra }) => {
17
- await mastra?.syncs?.['FIRECRAWL:CRAWL_AND_SYNC']?.execute({
18
- context,
19
- mastra,
20
- });
21
-
22
- return {
23
- message: 'The website has been successfully crawled and chunks have been synced to the database. Finish.',
24
- };
25
- },
26
- });
@@ -1,41 +0,0 @@
1
- import { createTool } from '@mastra/core';
2
- import chalk from 'chalk';
3
- import { execa } from 'execa';
4
- import { Transform } from 'stream';
5
- import { z } from 'zod';
6
-
7
- // Create transform stream that applies chalk
8
- const colorTransform = new Transform({
9
- transform(chunk, _encoding, callback) {
10
- // Convert chunk to string and apply chalk
11
- const colored = chalk.blue(chunk.toString());
12
- this.push(colored);
13
- callback();
14
- },
15
- });
16
-
17
- export const execaTool = createTool({
18
- id: 'execaTool',
19
- name: 'Execa System Tool',
20
- description: 'Execa System Tool',
21
- inputSchema: z.object({
22
- command: z.string(),
23
- args: z.array(z.string()),
24
- }),
25
- outputSchema: z.object({
26
- message: z.string(),
27
- }),
28
- execute: async ({ context: { command, args } }) => {
29
- try {
30
- const p = execa(command, args);
31
- console.log(`\n`);
32
- p.stdout.pipe(colorTransform).pipe(process.stdout);
33
- p.stderr.pipe(colorTransform).pipe(process.stderr);
34
- const r = await p;
35
-
36
- return { message: r.stdout };
37
- } catch (e) {
38
- return { message: 'Error' };
39
- }
40
- },
41
- });
@@ -1,36 +0,0 @@
1
- import { createTool } from '@mastra/core';
2
- import { readFileSync, writeFileSync } from 'fs';
3
- import { z } from 'zod';
4
-
5
- export const fsTool = createTool({
6
- id: 'fsTool',
7
- name: 'File System Tool',
8
- description: 'File System Tool',
9
- inputSchema: z.object({
10
- action: z.string(),
11
- file: z.string(),
12
- data: z.string(),
13
- }),
14
- outputSchema: z.object({
15
- message: z.string(),
16
- }),
17
- execute: async ({ context: { action, file, data } }) => {
18
- try {
19
- switch (action) {
20
- case 'write':
21
- writeFileSync(file, data);
22
- break;
23
- case 'read':
24
- return { message: readFileSync(file, 'utf8') };
25
- case 'append':
26
- writeFileSync(file, data, { flag: 'a' });
27
- break;
28
- default:
29
- return { message: 'Invalid action' };
30
- }
31
- return { message: 'Success' };
32
- } catch (e) {
33
- return { message: 'Error' };
34
- }
35
- },
36
- });
@@ -1,46 +0,0 @@
1
- import { createTool } from '@mastra/core';
2
- import chalk from 'chalk';
3
- import { existsSync, readFileSync } from 'fs';
4
- import path from 'path';
5
- import pdf from 'pdf-parse';
6
- import { z } from 'zod';
7
-
8
- export const readPDF = createTool({
9
- id: 'readPDF',
10
- name: 'Read PDF',
11
- description: 'Read PDF file and extract information',
12
- inputSchema: z.object({
13
- pdfPath: z.string(),
14
- }),
15
- outputSchema: z.object({
16
- content: z.string(),
17
- }),
18
- execute: async ({ context: { pdfPath } }) => {
19
- try {
20
- // Check if file exists
21
- if (!existsSync(pdfPath)) {
22
- throw new Error('PDF file not found');
23
- }
24
-
25
- // Check if file is a PDF
26
- if (path.extname(pdfPath).toLowerCase() !== '.pdf') {
27
- throw new Error('File is not a PDF');
28
- }
29
-
30
- // Read the PDF file
31
- const dataBuffer = readFileSync(pdfPath);
32
-
33
- // Parse PDF content
34
- const data = await pdf(dataBuffer);
35
-
36
- console.log(chalk.blue('\n'));
37
- console.log(chalk.blue('PDF Information:'));
38
- console.log(chalk.blue('-----------------'));
39
- console.log(chalk.blue(`Number of pages: ${data.numpages}`));
40
-
41
- return { content: data.text };
42
- } catch (e) {
43
- return { content: 'Error scanning PDF' };
44
- }
45
- },
46
- });