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