@perstack/base 0.0.19 → 0.0.21

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.
@@ -1,899 +0,0 @@
1
- import { realpathSync, existsSync, statSync } from 'fs';
2
- import fs, { appendFile, mkdir, unlink, readFile, writeFile, readdir, rename, stat } from 'fs/promises';
3
- import { dedent } from 'ts-dedent';
4
- import { z } from 'zod';
5
- import os from 'os';
6
- import path, { dirname, extname, basename, resolve, join } from 'path';
7
- import mime from 'mime-types';
8
-
9
- // src/tools/append-text-file.ts
10
- var workspacePath = realpathSync(expandHome(process.cwd()));
11
- function expandHome(filepath) {
12
- if (filepath.startsWith("~/") || filepath === "~") {
13
- return path.join(os.homedir(), filepath.slice(1));
14
- }
15
- return filepath;
16
- }
17
- async function validatePath(requestedPath) {
18
- const expandedPath = expandHome(requestedPath);
19
- const absolute = path.isAbsolute(expandedPath) ? path.resolve(expandedPath) : path.resolve(process.cwd(), expandedPath);
20
- if (absolute === `${workspacePath}/perstack`) {
21
- throw new Error("Access denied - perstack directory is not allowed");
22
- }
23
- try {
24
- const realAbsolute = await fs.realpath(absolute);
25
- if (!realAbsolute.startsWith(workspacePath)) {
26
- throw new Error("Access denied - symlink target outside allowed directories");
27
- }
28
- return realAbsolute;
29
- } catch (error) {
30
- const parentDir = path.dirname(absolute);
31
- try {
32
- const realParentPath = await fs.realpath(parentDir);
33
- if (!realParentPath.startsWith(workspacePath)) {
34
- throw new Error("Access denied - parent directory outside allowed directories");
35
- }
36
- return absolute;
37
- } catch {
38
- if (!absolute.startsWith(workspacePath)) {
39
- throw new Error(
40
- `Access denied - path outside allowed directories: ${absolute} not in ${workspacePath}`
41
- );
42
- }
43
- throw new Error(`Parent directory does not exist: ${parentDir}`);
44
- }
45
- }
46
- }
47
-
48
- // src/tools/append-text-file.ts
49
- var inputSchema = z.object({
50
- path: z.string().describe("Target file path to append to."),
51
- text: z.string().min(1).max(2e3).describe("Text to append to the file. Max 2000 characters.")
52
- });
53
- function appendTextFileConfig() {
54
- return {
55
- title: "Append text file",
56
- description: dedent`
57
- Adding content to the end of existing files.
58
-
59
- Use cases:
60
- - Adding entries to log files
61
- - Appending data to CSV or JSON files
62
- - Adding new sections to documentation
63
- - Extending configuration files
64
- - Building files incrementally
65
-
66
- How it works:
67
- - Appends text to the end of an existing file
68
- - Does not modify existing content
69
- - Creates a new line before appending if needed
70
- - Returns the appended file path
71
-
72
- Rules:
73
- - FILE MUST EXIST BEFORE APPENDING
74
- - YOU MUST PROVIDE A VALID UTF-8 STRING FOR THE TEXT
75
- - THERE IS A LIMIT ON THE NUMBER OF TOKENS THAT CAN BE GENERATED, SO DO NOT APPEND ALL THE CONTENT AT ONCE
76
- - IF YOU WANT TO APPEND MORE THAN 2000 CHARACTERS, USE THIS TOOL MULTIPLE TIMES
77
- `,
78
- inputSchema: inputSchema.shape
79
- };
80
- }
81
- async function appendTextFile(input) {
82
- const { path: path2, text } = input;
83
- const validatedPath = await validatePath(path2);
84
- if (!existsSync(validatedPath)) {
85
- throw new Error(`File ${path2} does not exist.`);
86
- }
87
- const stats = statSync(validatedPath);
88
- if (!(stats.mode & 128)) {
89
- throw new Error(`File ${path2} is not writable`);
90
- }
91
- await appendFile(validatedPath, text);
92
- return { path: validatedPath, text };
93
- }
94
- function attemptCompletionConfig() {
95
- return {
96
- title: "Attempt completion",
97
- description: dedent`
98
- Task completion signal that triggers immediate final report generation.
99
- Use cases:
100
- - Signaling task completion to Perstack runtime
101
- - Triggering final report generation
102
- - Ending the current expert's work cycle
103
- How it works:
104
- - Sends completion signal to Perstack runtime
105
- - Runtime immediately proceeds to final report generation
106
- - No confirmation or approval step required
107
- - No parameters needed for this signal
108
- Notes:
109
- - Triggers immediate transition to final report
110
- - Should only be used when task is fully complete
111
- - Cannot be reverted once called
112
- `,
113
- inputSchema: {}
114
- };
115
- }
116
- async function attemptCompletion() {
117
- return {
118
- message: "End the agent loop and provide a final report"
119
- };
120
- }
121
- var inputSchema2 = z.object({
122
- path: z.string()
123
- });
124
- function createDirectoryConfig() {
125
- return {
126
- title: "Create directory",
127
- description: dedent`
128
- Directory creator for establishing folder structures in the workspace.
129
-
130
- Use cases:
131
- - Setting up project directory structure
132
- - Creating output folders for generated content
133
- - Organizing files into logical groups
134
- - Preparing directory hierarchies
135
-
136
- How it works:
137
- - Creates directories recursively
138
- - Handles existing directories gracefully
139
- - Creates parent directories as needed
140
- - Returns creation status
141
-
142
- Parameters:
143
- - path: Directory path to create
144
- `,
145
- inputSchema: inputSchema2.shape
146
- };
147
- }
148
- async function createDirectory(input) {
149
- const { path: path2 } = input;
150
- const validatedPath = await validatePath(path2);
151
- const exists = existsSync(validatedPath);
152
- if (exists) {
153
- throw new Error(`Directory ${path2} already exists`);
154
- }
155
- const parentDir = dirname(validatedPath);
156
- if (existsSync(parentDir)) {
157
- const parentStats = statSync(parentDir);
158
- if (!(parentStats.mode & 128)) {
159
- throw new Error(`Parent directory ${parentDir} is not writable`);
160
- }
161
- }
162
- await mkdir(validatedPath, { recursive: true });
163
- return {
164
- path: validatedPath
165
- };
166
- }
167
- var inputSchema3 = z.object({
168
- path: z.string()
169
- });
170
- function deleteFileConfig() {
171
- return {
172
- title: "Delete file",
173
- description: dedent`
174
- File deleter for removing files from the workspace.
175
-
176
- Use cases:
177
- - Removing temporary files
178
- - Cleaning up generated files
179
- - Deleting outdated configuration files
180
- - Removing unwanted artifacts
181
-
182
- How it works:
183
- - Validates file existence and permissions
184
- - Performs atomic delete operation
185
- - Returns deletion status
186
-
187
- Parameters:
188
- - path: File path to delete
189
- `,
190
- inputSchema: inputSchema3.shape
191
- };
192
- }
193
- async function deleteFile(input) {
194
- const { path: path2 } = input;
195
- const validatedPath = await validatePath(path2);
196
- if (!existsSync(validatedPath)) {
197
- throw new Error(`File ${path2} does not exist.`);
198
- }
199
- const stats = statSync(validatedPath);
200
- if (stats.isDirectory()) {
201
- throw new Error(`Path ${path2} is a directory. Use delete directory tool instead.`);
202
- }
203
- if (!(stats.mode & 128)) {
204
- throw new Error(`File ${path2} is not writable`);
205
- }
206
- await unlink(validatedPath);
207
- return {
208
- path: validatedPath
209
- };
210
- }
211
- var inputSchema4 = z.object({
212
- path: z.string().describe("Target file path to edit."),
213
- newText: z.string().min(1).max(2e3).describe("Text to append to the file. Max 2000 characters."),
214
- oldText: z.string().min(1).max(2e3).describe("Exact text to find and replace. Max 2000 characters.")
215
- });
216
- function editTextFileConfig() {
217
- return {
218
- title: "Edit text file",
219
- description: dedent`
220
- Text file editor for modifying existing files with precise text replacement.
221
-
222
- Use cases:
223
- - Updating configuration values
224
- - Modifying code snippets
225
- - Replacing specific text blocks
226
- - Making targeted edits to files
227
-
228
- How it works:
229
- - Reads existing file content
230
- - Performs exact text replacement of oldText with newText
231
- - Normalizes line endings for consistent behavior
232
- - Returns summary of changes made
233
- - For appending text to files, use the appendTextFile tool instead
234
-
235
- Rules:
236
- - YOU MUST PROVIDE A VALID UTF-8 STRING FOR THE TEXT
237
- - THERE IS A LIMIT ON THE NUMBER OF TOKENS THAT CAN BE GENERATED, SO DO NOT WRITE ALL THE CONTENT AT ONCE (IT WILL CAUSE AN ERROR)
238
- - IF YOU WANT TO EDIT MORE THAN 2000 CHARACTERS, USE THIS TOOL MULTIPLE TIMES
239
- - DO NOT USE THIS TOOL FOR APPENDING TEXT TO FILES - USE appendTextFile TOOL INSTEAD
240
- `,
241
- inputSchema: inputSchema4.shape
242
- };
243
- }
244
- async function editTextFile(input) {
245
- const { path: path2, newText, oldText } = input;
246
- const validatedPath = await validatePath(path2);
247
- if (!existsSync(validatedPath)) {
248
- throw new Error(`File ${path2} does not exist.`);
249
- }
250
- const stats = statSync(validatedPath);
251
- if (!(stats.mode & 128)) {
252
- throw new Error(`File ${path2} is not writable`);
253
- }
254
- await applyFileEdit(validatedPath, newText, oldText);
255
- return {
256
- path: validatedPath,
257
- newText,
258
- oldText
259
- };
260
- }
261
- function normalizeLineEndings(text) {
262
- return text.replace(/\r\n/g, "\n");
263
- }
264
- async function applyFileEdit(filePath, newText, oldText) {
265
- const content = normalizeLineEndings(await readFile(filePath, "utf-8"));
266
- const normalizedOld = normalizeLineEndings(oldText);
267
- const normalizedNew = normalizeLineEndings(newText);
268
- if (!content.includes(normalizedOld)) {
269
- throw new Error(`Could not find exact match for oldText in file ${filePath}`);
270
- }
271
- const modifiedContent = content.replace(normalizedOld, normalizedNew);
272
- await writeFile(filePath, modifiedContent, "utf-8");
273
- }
274
- var inputSchema5 = z.object({
275
- path: z.string()
276
- });
277
- function getFileInfoConfig() {
278
- return {
279
- title: "Get file info",
280
- description: dedent`
281
- File information retriever for detailed metadata about files and directories.
282
-
283
- Use cases:
284
- - Checking file existence and type
285
- - Getting file size and timestamps
286
- - Determining MIME types
287
- - Validating file accessibility
288
-
289
- How it works:
290
- - Retrieves comprehensive file system metadata
291
- - Detects MIME type from file extension
292
- - Provides both absolute and relative paths
293
- - Returns human-readable file sizes
294
-
295
- Parameters:
296
- - path: File or directory path to inspect
297
- `,
298
- inputSchema: inputSchema5.shape
299
- };
300
- }
301
- async function getFileInfo(input) {
302
- const { path: path2 } = input;
303
- const validatedPath = await validatePath(path2);
304
- if (!existsSync(validatedPath)) {
305
- throw new Error(`File or directory ${path2} does not exist`);
306
- }
307
- const stats = statSync(validatedPath);
308
- const isDirectory = stats.isDirectory();
309
- const mimeType = isDirectory ? null : mime.lookup(validatedPath) || "application/octet-stream";
310
- const formatSize = (bytes) => {
311
- if (bytes === 0) return "0 B";
312
- const units = ["B", "KB", "MB", "GB", "TB"];
313
- const i = Math.floor(Math.log(bytes) / Math.log(1024));
314
- return `${(bytes / 1024 ** i).toFixed(2)} ${units[i]}`;
315
- };
316
- return {
317
- exists: true,
318
- path: validatedPath,
319
- absolutePath: resolve(validatedPath),
320
- name: basename(validatedPath),
321
- directory: dirname(validatedPath),
322
- extension: isDirectory ? null : extname(validatedPath),
323
- type: isDirectory ? "directory" : "file",
324
- mimeType,
325
- size: stats.size,
326
- sizeFormatted: formatSize(stats.size),
327
- created: stats.birthtime.toISOString(),
328
- modified: stats.mtime.toISOString(),
329
- accessed: stats.atime.toISOString(),
330
- permissions: {
331
- readable: true,
332
- writable: Boolean(stats.mode & 128),
333
- executable: Boolean(stats.mode & 64)
334
- }
335
- };
336
- }
337
- var inputSchema6 = z.object({
338
- path: z.string()
339
- });
340
- function listDirectoryConfig() {
341
- return {
342
- title: "List directory",
343
- description: dedent`
344
- Directory content lister with detailed file information.
345
-
346
- Use cases:
347
- - Exploring project structure
348
- - Finding files in a directory
349
- - Checking directory contents before operations
350
- - Understanding file organization
351
-
352
- How it works:
353
- - Lists all files and subdirectories in specified directory only
354
- - Provides file type, size, and modification time
355
- - Sorts entries alphabetically
356
- - Handles empty directories
357
-
358
- Parameters:
359
- - path: Directory path to list (optional, defaults to workspace root)
360
- `,
361
- inputSchema: inputSchema6.shape
362
- };
363
- }
364
- async function listDirectory(input) {
365
- const { path: path2 } = input;
366
- const validatedPath = await validatePath(path2);
367
- if (!existsSync(validatedPath)) {
368
- throw new Error(`Directory ${path2} does not exist.`);
369
- }
370
- const stats = statSync(validatedPath);
371
- if (!stats.isDirectory()) {
372
- throw new Error(`Path ${path2} is not a directory.`);
373
- }
374
- const entries = await readdir(validatedPath);
375
- const items = [];
376
- for (const entry of entries.sort()) {
377
- try {
378
- const fullPath = await validatePath(join(validatedPath, entry));
379
- const entryStats = statSync(fullPath);
380
- const item = {
381
- name: entry,
382
- path: entry,
383
- type: entryStats.isDirectory() ? "directory" : "file",
384
- size: entryStats.size,
385
- modified: entryStats.mtime.toISOString()
386
- };
387
- items.push(item);
388
- } catch (e) {
389
- if (e instanceof Error && e.message.includes("perstack directory is not allowed")) {
390
- continue;
391
- }
392
- throw e;
393
- }
394
- }
395
- return {
396
- path: validatedPath,
397
- items
398
- };
399
- }
400
- var inputSchema7 = z.object({
401
- source: z.string(),
402
- destination: z.string()
403
- });
404
- function moveFileConfig() {
405
- return {
406
- title: "Move file",
407
- description: dedent`
408
- File mover for relocating or renaming files within the workspace.
409
-
410
- Use cases:
411
- - Renaming files to follow naming conventions
412
- - Moving files to different directories
413
- - Organizing project structure
414
- - Backing up files before modifications
415
-
416
- How it works:
417
- - Validates source file existence
418
- - Creates destination directory if needed
419
- - Performs atomic move operation
420
- - Preserves file permissions and timestamps
421
-
422
- Parameters:
423
- - source: Current file path
424
- - destination: Target file path
425
- `,
426
- inputSchema: inputSchema7.shape
427
- };
428
- }
429
- async function moveFile(input) {
430
- const { source, destination } = input;
431
- const validatedSource = await validatePath(source);
432
- const validatedDestination = await validatePath(destination);
433
- if (!existsSync(validatedSource)) {
434
- throw new Error(`Source file ${source} does not exist.`);
435
- }
436
- const sourceStats = statSync(validatedSource);
437
- if (!(sourceStats.mode & 128)) {
438
- throw new Error(`Source file ${source} is not writable`);
439
- }
440
- if (existsSync(validatedDestination)) {
441
- throw new Error(`Destination ${destination} already exists.`);
442
- }
443
- const destDir = dirname(validatedDestination);
444
- await mkdir(destDir, { recursive: true });
445
- await rename(validatedSource, validatedDestination);
446
- return {
447
- source: validatedSource,
448
- destination: validatedDestination
449
- };
450
- }
451
- var MAX_IMAGE_SIZE = 15 * 1024 * 1024;
452
- var inputSchema8 = z.object({
453
- path: z.string()
454
- });
455
- function readImageFileConfig() {
456
- return {
457
- title: "Read image file",
458
- description: dedent`
459
- Image file reader that converts images to base64 encoded strings with MIME type validation.
460
-
461
- Use cases:
462
- - Loading images for LLM to process
463
- - Retrieving image data for analysis or display
464
- - Converting workspace image files to base64 format
465
-
466
- How it works:
467
- - Validates file existence and MIME type before reading
468
- - Encodes file content as base64 string
469
- - Returns image data with correct MIME type for proper handling
470
- - Rejects unsupported formats with clear error messages
471
-
472
- Supported formats:
473
- - PNG (image/png)
474
- - JPEG/JPG (image/jpeg)
475
- - GIF (image/gif) - static only, animated not supported
476
- - WebP (image/webp)
477
-
478
- Notes:
479
- - Maximum file size: 15MB (larger files will be rejected)
480
- `,
481
- inputSchema: inputSchema8.shape
482
- };
483
- }
484
- async function readImageFile(input) {
485
- const { path: path2 } = input;
486
- const validatedPath = await validatePath(path2);
487
- const isFile = existsSync(validatedPath);
488
- if (!isFile) {
489
- throw new Error(`File ${path2} does not exist.`);
490
- }
491
- const mimeType = mime.lookup(validatedPath);
492
- if (!mimeType || !["image/png", "image/jpeg", "image/gif", "image/webp"].includes(mimeType)) {
493
- throw new Error(`File ${path2} is not supported.`);
494
- }
495
- const fileStats = await stat(validatedPath);
496
- const fileSizeMB = fileStats.size / (1024 * 1024);
497
- if (fileStats.size > MAX_IMAGE_SIZE) {
498
- throw new Error(
499
- `Image file too large (${fileSizeMB.toFixed(1)}MB). Maximum supported size is ${MAX_IMAGE_SIZE / (1024 * 1024)}MB. Please use a smaller image file.`
500
- );
501
- }
502
- return {
503
- path: validatedPath,
504
- mimeType,
505
- size: fileStats.size
506
- };
507
- }
508
- var MAX_PDF_SIZE = 30 * 1024 * 1024;
509
- var inputSchema9 = z.object({
510
- path: z.string()
511
- });
512
- function readPdfFileConfig() {
513
- return {
514
- title: "Read PDF file",
515
- description: dedent`
516
- PDF file reader that converts documents to base64 encoded resources.
517
-
518
- Use cases:
519
- - Extracting content from PDF documents for analysis
520
- - Loading PDF files for LLM processing
521
- - Retrieving PDF data for conversion or manipulation
522
-
523
- How it works:
524
- - Validates file existence and MIME type (application/pdf)
525
- - Encodes PDF content as base64 blob
526
- - Returns as resource type with proper MIME type and URI
527
- - Rejects non-PDF files with clear error messages
528
-
529
- Notes:
530
- - Returns entire PDF content, no page range support
531
- - Maximum file size: 10MB (larger files will be rejected)
532
- - Text extraction not performed, returns raw PDF data
533
- `,
534
- inputSchema: inputSchema9.shape
535
- };
536
- }
537
- async function readPdfFile(input) {
538
- const { path: path2 } = input;
539
- const validatedPath = await validatePath(path2);
540
- const isFile = existsSync(validatedPath);
541
- if (!isFile) {
542
- throw new Error(`File ${path2} does not exist.`);
543
- }
544
- const mimeType = mime.lookup(validatedPath);
545
- if (mimeType !== "application/pdf") {
546
- throw new Error(`File ${path2} is not a PDF file.`);
547
- }
548
- const fileStats = await stat(validatedPath);
549
- const fileSizeMB = fileStats.size / (1024 * 1024);
550
- if (fileStats.size > MAX_PDF_SIZE) {
551
- throw new Error(
552
- `PDF file too large (${fileSizeMB.toFixed(1)}MB). Maximum supported size is ${MAX_PDF_SIZE / (1024 * 1024)}MB. Please use a smaller PDF file.`
553
- );
554
- }
555
- return {
556
- path: validatedPath,
557
- mimeType,
558
- size: fileStats.size
559
- };
560
- }
561
- var inputSchema10 = z.object({
562
- path: z.string(),
563
- from: z.number().optional().describe("The line number to start reading from."),
564
- to: z.number().optional().describe("The line number to stop reading at.")
565
- });
566
- function readTextFileConfig() {
567
- return {
568
- title: "Read text file",
569
- description: dedent`
570
- Text file reader with line range support for UTF-8 encoded files.
571
-
572
- Use cases:
573
- - Reading source code files for analysis
574
- - Extracting specific sections from large text files
575
- - Loading configuration or documentation files
576
- - Viewing log files or data files
577
-
578
- How it works:
579
- - Reads files as UTF-8 encoded text without format validation
580
- - Supports partial file reading via line number ranges
581
- - Returns content wrapped in JSON with metadata
582
- - WARNING: Binary files will cause errors or corrupted output
583
-
584
- Common file types:
585
- - Source code: .ts, .js, .py, .java, .cpp, etc.
586
- - Documentation: .md, .txt, .rst
587
- - Configuration: .json, .yaml, .toml, .ini
588
- - Data files: .csv, .log, .sql
589
- `,
590
- inputSchema: inputSchema10.shape
591
- };
592
- }
593
- async function readTextFile(input) {
594
- const { path: path2, from, to } = input;
595
- const validatedPath = await validatePath(path2);
596
- const isFile = existsSync(validatedPath);
597
- if (!isFile) {
598
- throw new Error(`File ${path2} does not exist.`);
599
- }
600
- const fileContent = await readFile(validatedPath, "utf-8");
601
- const lines = fileContent.split("\n");
602
- const fromLine = from ?? 0;
603
- const toLine = to ?? lines.length;
604
- const selectedLines = lines.slice(fromLine, toLine);
605
- const content = selectedLines.join("\n");
606
- return {
607
- path: path2,
608
- content,
609
- from: fromLine,
610
- to: toLine
611
- };
612
- }
613
- var inputSchema11 = z.object({
614
- urls: z.array(z.string()).min(1).max(10).describe("Array of URLs to test (max 10 URLs).")
615
- });
616
- function testUrlConfig() {
617
- return {
618
- title: "Test URL",
619
- description: dedent`
620
- URL tester that validates multiple URLs and extracts metadata.
621
-
622
- Use cases:
623
- - Checking if URLs are accessible before web scraping
624
- - Validating URL collections for RAG processes
625
- - Extracting page metadata (title, description) for content analysis
626
- - Batch URL validation for link checking
627
-
628
- How it works:
629
- - Performs HTTP GET requests to each URL
630
- - Returns status code, title, and description for each URL
631
- - Handles errors gracefully with timeout protection
632
- - Processes URLs in parallel for performance
633
-
634
- Rules:
635
- - URLs must be valid HTTP/HTTPS addresses
636
- - Maximum 10 URLs per request to prevent abuse
637
- - 10 second timeout per URL request
638
- - Returns empty title/description if HTML parsing fails
639
- `,
640
- inputSchema: inputSchema11.shape
641
- };
642
- }
643
- async function testUrls(input) {
644
- const { urls } = input;
645
- const results = await Promise.allSettled(
646
- urls.map(async (url) => {
647
- try {
648
- const controller = new AbortController();
649
- const timeoutId = setTimeout(() => controller.abort(), 1e4);
650
- const response = await fetch(url, {
651
- method: "GET",
652
- signal: controller.signal,
653
- headers: {
654
- "User-Agent": "Perstack URL Tester/1.0"
655
- }
656
- });
657
- clearTimeout(timeoutId);
658
- let title = "";
659
- let description = "";
660
- if (response.ok && response.headers.get("content-type")?.includes("text/html")) {
661
- try {
662
- const html = await response.text();
663
- title = extractTitle(html);
664
- description = extractDescription(html);
665
- } catch {
666
- }
667
- }
668
- return {
669
- url,
670
- status: response.status,
671
- title,
672
- description
673
- };
674
- } catch (error) {
675
- return {
676
- url,
677
- status: 0,
678
- title: "",
679
- description: error instanceof Error ? error.message : "Unknown error"
680
- };
681
- }
682
- })
683
- );
684
- return {
685
- results: results.map((result) => {
686
- if (result.status === "fulfilled") {
687
- return result.value;
688
- }
689
- return {
690
- url: "unknown",
691
- status: 0,
692
- title: "",
693
- description: "Promise rejected"
694
- };
695
- })
696
- };
697
- }
698
- function extractTitle(html) {
699
- const titleMatch = html.match(/<title[^>]*>([^<]*)/i);
700
- return titleMatch ? titleMatch[1].trim() : "";
701
- }
702
- function extractDescription(html) {
703
- const metaDescMatch = html.match(
704
- /<meta[^>]*name=["']description["'][^>]*content=["']([^"']*)["']/i
705
- );
706
- if (metaDescMatch) {
707
- return metaDescMatch[1].trim();
708
- }
709
- const ogDescMatch = html.match(
710
- /<meta[^>]*property=["']og:description["'][^>]*content=["']([^"']*)["']/i
711
- );
712
- if (ogDescMatch) {
713
- return ogDescMatch[1].trim();
714
- }
715
- return "";
716
- }
717
- var inputSchema12 = z.object({
718
- thought: z.string().describe("Your current thinking step"),
719
- nextThoughtNeeded: z.boolean().optional().describe("true if you need more thinking, even if at what seemed like the end")
720
- });
721
- function thinkConfig() {
722
- return {
723
- title: "think",
724
- description: dedent`
725
- Sequential thinking tool for step-by-step problem analysis and solution development.
726
-
727
- Use cases:
728
- - Breaking down complex problems into manageable steps
729
- - Developing solutions through iterative reasoning
730
- - Analyzing problems that require multiple perspectives
731
- - Planning tasks with dependencies and considerations
732
-
733
- How it works:
734
- - Records each thinking step sequentially
735
- - Maintains thought history for context
736
- - Continues until solution is reached
737
- - Returns thought count and continuation status
738
-
739
- Parameters:
740
- - thought: Current reasoning step or analysis
741
- - nextThoughtNeeded: Whether additional thinking is required (optional)
742
-
743
- Best practices:
744
- - Use multiple calls for sophisticated reasoning chains
745
- - Progress from high-level overview to detailed analysis (drill-down approach)
746
- - Capture insights and eureka moments as they emerge
747
- - Engage in reflective introspection and constructive self-critique
748
- - Set nextThoughtNeeded to false only when fully satisfied with the solution
749
- `,
750
- inputSchema: inputSchema12.shape
751
- };
752
- }
753
- var Thought = class {
754
- thoughtHistory = [];
755
- branches = {};
756
- processThought(input) {
757
- const { nextThoughtNeeded } = input;
758
- this.thoughtHistory.push(input);
759
- return {
760
- nextThoughtNeeded,
761
- thoughtHistoryLength: this.thoughtHistory.length
762
- };
763
- }
764
- };
765
- var thought = new Thought();
766
- async function think(input) {
767
- return thought.processThought(input);
768
- }
769
- var Todo = class {
770
- currentTodoId = 0;
771
- todos = [];
772
- processTodo(input) {
773
- const { newTodos, completedTodos } = input;
774
- if (newTodos) {
775
- this.todos.push(
776
- ...newTodos.map((title) => ({ id: this.currentTodoId++, title, completed: false }))
777
- );
778
- }
779
- if (completedTodos) {
780
- this.todos = this.todos.map((todo2) => ({
781
- ...todo2,
782
- completed: todo2.completed || completedTodos.includes(todo2.id)
783
- }));
784
- }
785
- return {
786
- todos: this.todos
787
- };
788
- }
789
- clearTodo() {
790
- this.todos = [];
791
- this.currentTodoId = 0;
792
- return {
793
- todos: this.todos
794
- };
795
- }
796
- };
797
- var todoSingleton = new Todo();
798
- var todoInputSchema = z.object({
799
- newTodos: z.array(z.string()).describe("New todos to add").optional(),
800
- completedTodos: z.array(z.number()).describe("Todo ids that are completed").optional()
801
- });
802
- function todoConfig() {
803
- return {
804
- title: "todo",
805
- description: dedent`
806
- Todo list manager that tracks tasks and their completion status.
807
-
808
- Use cases:
809
- - Creating new tasks or action items
810
- - Marking tasks as completed
811
- - Viewing current task list and status
812
-
813
- How it works:
814
- - Each todo gets a unique ID when created
815
- - Returns the full todo list after every operation
816
- - Maintains state across multiple calls
817
-
818
- Parameters:
819
- - newTodos: Array of task descriptions to add
820
- - completedTodos: Array of todo IDs to mark as completed
821
- `,
822
- inputSchema: todoInputSchema.shape
823
- };
824
- }
825
- async function todo(input) {
826
- return todoSingleton.processTodo(input);
827
- }
828
- var clearTodoInputSchema = z.object({});
829
- function clearTodoConfig() {
830
- return {
831
- title: "clearTodo",
832
- description: dedent`
833
- Clears the todo list.
834
-
835
- Use cases:
836
- - Resetting the todo list to an empty state
837
- - Starting fresh with a new task list
838
- - Clearing all tasks for a new day or project
839
-
840
- How it works:
841
- - Resets the todo list to an empty state
842
- - Returns an empty todo list
843
- `,
844
- inputSchema: clearTodoInputSchema.shape
845
- };
846
- }
847
- async function clearTodo(input) {
848
- return todoSingleton.clearTodo();
849
- }
850
- var toolInputSchema = z.object({
851
- path: z.string().describe("Target file path (relative or absolute)."),
852
- text: z.string().min(1).max(1e4).describe("Text to write to the file. Max 10000 characters.")
853
- });
854
- function writeTextFileConfig() {
855
- return {
856
- title: "writeTextFile",
857
- description: dedent`
858
- Text file writer that creates or overwrites files with UTF-8 content.
859
-
860
- Use cases:
861
- - Creating new configuration files
862
- - Writing generated code or documentation
863
- - Saving processed data or results
864
- - Creating log files or reports
865
-
866
- How it works:
867
- - Writes content as UTF-8 encoded text
868
- - Returns success status with file path
869
-
870
- Rules:
871
- - IF THE FILE ALREADY EXISTS, IT WILL BE OVERWRITTEN
872
- - YOU MUST PROVIDE A VALID UTF-8 STRING FOR THE TEXT
873
- - THERE IS A LIMIT ON THE NUMBER OF TOKENS THAT CAN BE GENERATED, SO DO NOT WRITE ALL THE CONTENT AT ONCE (IT WILL CAUSE AN ERROR)
874
- - IF YOU WANT TO WRITE MORE THAN 10,000 CHARACTERS, USE "appendTextFile" TOOL AFTER THIS ONE
875
- `,
876
- inputSchema: toolInputSchema.shape
877
- };
878
- }
879
- async function writeTextFile(input) {
880
- const { path: path2, text } = input;
881
- const validatedPath = await validatePath(path2);
882
- if (existsSync(validatedPath)) {
883
- const stats = statSync(validatedPath);
884
- if (!(stats.mode & 128)) {
885
- throw new Error(`File ${path2} is not writable`);
886
- }
887
- }
888
- const dir = dirname(validatedPath);
889
- await mkdir(dir, { recursive: true });
890
- await writeFile(validatedPath, text, "utf-8");
891
- return {
892
- path: validatedPath,
893
- text
894
- };
895
- }
896
-
897
- export { appendTextFile, appendTextFileConfig, attemptCompletion, attemptCompletionConfig, clearTodo, clearTodoConfig, createDirectory, createDirectoryConfig, deleteFile, deleteFileConfig, editTextFile, editTextFileConfig, getFileInfo, getFileInfoConfig, listDirectory, listDirectoryConfig, moveFile, moveFileConfig, readImageFile, readImageFileConfig, readPdfFile, readPdfFileConfig, readTextFile, readTextFileConfig, testUrlConfig, testUrls, think, thinkConfig, todo, todoConfig, writeTextFile, writeTextFileConfig };
898
- //# sourceMappingURL=chunk-4N6IWATT.js.map
899
- //# sourceMappingURL=chunk-4N6IWATT.js.map