@makaio/extension-filesystem 1.0.0-dev-1783942498489

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Makaio GmbH
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,194 @@
1
+ # @makaio/extension-filesystem
2
+
3
+ Filesystem toolset for Makaio Framework. Cross-platform file operations with path validation and constraints support.
4
+
5
+ ## Quick Start
6
+
7
+ ```typescript
8
+ import { ToolRegistry } from '@makaio/services-core/tools';
9
+ import { filesystemToolset } from '@makaio/extension-filesystem';
10
+ import { createMakaioContext } from '@makaio/framework/core';
11
+
12
+ const registry = new ToolRegistry();
13
+ await registry.register(filesystemToolset);
14
+
15
+ const contextOverrides = createMakaioContext({ cwd: '/path/to/project' });
16
+
17
+ // Read a file
18
+ const result = await registry.execute('read_file', {
19
+ path: './package.json'
20
+ }, { contextOverrides });
21
+
22
+ if (result.success) {
23
+ console.log(result.data.content);
24
+ }
25
+ ```
26
+
27
+ ## Available Tools
28
+
29
+ ### read_file
30
+
31
+ Reads text content from a file with optional line offset/limit.
32
+
33
+ ```typescript
34
+ // Input
35
+ {
36
+ path: string; // Absolute or relative to cwd
37
+ encoding?: 'utf-8' | 'base64'; // Default: 'utf-8'
38
+ offset?: number; // Line offset (0-indexed)
39
+ limit?: number; // Max lines to read
40
+ }
41
+
42
+ // Output
43
+ {
44
+ content: string;
45
+ path: string; // Resolved absolute path
46
+ size: number; // File size in bytes
47
+ totalLines?: number; // Total lines (if text)
48
+ truncated: boolean; // True if limit applied
49
+ }
50
+
51
+ // Annotations: { readOnly: true }
52
+ ```
53
+
54
+ ### write_file
55
+
56
+ Writes content to a file with optional directory creation.
57
+
58
+ ```typescript
59
+ // Input
60
+ {
61
+ path: string; // Absolute or relative to cwd
62
+ content: string; // Content to write
63
+ createDirectories?: boolean; // Create parent dirs if missing
64
+ append?: boolean; // Append instead of overwrite
65
+ }
66
+
67
+ // Output
68
+ {
69
+ path: string; // Resolved absolute path
70
+ bytesWritten: number;
71
+ created: boolean; // True if file was created (not overwritten)
72
+ }
73
+
74
+ // Annotations: { destructive: true }
75
+ ```
76
+
77
+ ### list_directory
78
+
79
+ Lists directory contents with optional recursion.
80
+
81
+ ```typescript
82
+ // Input
83
+ {
84
+ path: string; // Directory path
85
+ recursive?: boolean; // Recurse into subdirectories
86
+ includeHidden?: boolean; // Include dotfiles
87
+ pattern?: string; // Glob pattern to filter entries (*, ?)
88
+ }
89
+
90
+ // Output
91
+ {
92
+ path: string; // Resolved absolute path
93
+ entries: Array<{
94
+ name: string;
95
+ path: string;
96
+ type: 'file' | 'directory' | 'symlink' | 'other';
97
+ size?: number; // For files only
98
+ }>;
99
+ totalCount: number;
100
+ }
101
+
102
+ // Annotations: { readOnly: true }
103
+ ```
104
+
105
+ When `recursive` is false, `pattern` filters the entries returned from the requested directory. When `recursive` is
106
+ true, directories are still included and traversed even if they do not match `pattern`; the pattern is applied to
107
+ non-directory entries.
108
+
109
+ ### delete_file
110
+
111
+ Deletes a regular file. Directories and symlinks are rejected.
112
+
113
+ ```typescript
114
+ // Input
115
+ {
116
+ path: string; // Absolute or relative to cwd
117
+ }
118
+
119
+ // Output
120
+ {
121
+ path: string; // Resolved absolute path of the deleted file
122
+ }
123
+
124
+ // Annotations: { destructive: true }
125
+ ```
126
+
127
+ ## Path Resolution
128
+
129
+ All paths are resolved relative to `context.cwd`:
130
+
131
+ ```typescript
132
+ import { createMakaioContext } from '@makaio/framework/core';
133
+
134
+ const context = createMakaioContext({ cwd: '/home/user/project' });
135
+
136
+ // './src/index.ts' resolves to '/home/user/project/src/index.ts'
137
+ // '/etc/passwd' stays as '/etc/passwd' (absolute)
138
+ ```
139
+
140
+ ## Constraints
141
+
142
+ Use `context.constraints.allowedDirectories` to restrict access:
143
+
144
+ `undefined` applies no directory restriction, an empty array denies all filesystem paths, and a non-empty array allows
145
+ only those directory trees.
146
+
147
+ ```typescript
148
+ const contextOverrides = createMakaioContext({
149
+ cwd: '/home/user/project',
150
+ constraints: {
151
+ allowedDirectories: ['/home/user/project', '/tmp'],
152
+ },
153
+ });
154
+
155
+ // Paths outside allowed directories return PERMISSION_DENIED error
156
+ ```
157
+
158
+ Path validation assumes the filesystem namespace between each configured root and target remains stable for the
159
+ duration of an operation. A same-user process that can concurrently replace directories or symlinks may race pathname
160
+ validation; use OS-level isolation such as separate users, containers, mount namespaces, or restrictive directory
161
+ permissions when concurrent mutation is hostile. File opens use `O_NOFOLLOW` where available as defense-in-depth for
162
+ the final path component, not as an atomic containment guarantee for the full path.
163
+
164
+ ## Direct Tool Access
165
+
166
+ ```typescript
167
+ import { createMakaioContext } from '@makaio/framework/core';
168
+ import { filesystemToolset } from '@makaio/extension-filesystem';
169
+
170
+ const readFileTool = filesystemToolset.tools.read_file;
171
+ const result = await readFileTool.execute({ path: './file.txt' }, createMakaioContext({ cwd: process.cwd() }));
172
+ ```
173
+
174
+ The package root exports the toolset and file-access helpers. Individual tool definitions are not
175
+ root exports; use `filesystemToolset.tools` when a test or adapter needs direct access without a
176
+ registry.
177
+
178
+ ## Cross-Platform Notes
179
+
180
+ - Path separators handled automatically by `node:path`
181
+ - Hidden files detected by `.` prefix (works on all platforms)
182
+ - Line endings preserved as-is (no normalization)
183
+
184
+ ## File Index
185
+
186
+ | File | Purpose |
187
+ |------|---------|
188
+ | `src/toolset.ts` | Toolset definition with all tools |
189
+ | `src/tools/read-file.ts` | read_file implementation |
190
+ | `src/tools/write-file.ts` | write_file implementation |
191
+ | `src/tools/list-directory.ts` | list_directory implementation |
192
+ | `src/tools/delete-file.ts` | delete_file implementation |
193
+ | `src/utils/path-utils.ts` | Path resolution and validation |
194
+ | `src/utils/platform.ts` | Cross-platform helpers |
@@ -0,0 +1,13 @@
1
+ {
2
+ "name": "filesystem",
3
+ "displayName": "Filesystem Tools",
4
+ "version": "0.1.0",
5
+ "makaio": {
6
+ "framework": ">=0.1.0"
7
+ },
8
+ "surface": "headless",
9
+ "entrypoints": {
10
+ "server": true
11
+ },
12
+ "execution": "embedded"
13
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Default deny patterns applied to all projects.
3
+ * Users can negate these with `!pattern` in `.makaioignore`.
4
+ */
5
+ export declare const DEFAULT_DENIED_PATTERNS: readonly string[];
6
+ //# sourceMappingURL=default-patterns.d.ts.map
@@ -0,0 +1,3 @@
1
+ export { DEFAULT_DENIED_PATTERNS } from './default-patterns.js';
2
+ export { createMakaioIgnoreProvider, type MakaioIgnoreProviderOptions } from './makaioignore-provider.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,24 @@
1
+ import type { FileAccessRuleProvider } from '../types.js';
2
+ /** Options for {@link createMakaioIgnoreProvider}. */
3
+ export interface MakaioIgnoreProviderOptions {
4
+ /**
5
+ * Path to the global ignore file (e.g. `~/.makaio/.makaioignore`).
6
+ * Set to `null` to disable global ignore loading.
7
+ */
8
+ readonly globalIgnorePath: string | null;
9
+ }
10
+ /**
11
+ * Create a `FileAccessRuleProvider` that reads `.makaioignore` files from
12
+ * the working directory up to the filesystem root, loads the global ignore
13
+ * file specified in `options.globalIgnorePath`, and applies a default set of deny patterns.
14
+ *
15
+ * Precedence (last writer wins): defaults → global → hierarchical (root → cwd).
16
+ *
17
+ * The provider caches each file by `mtimeMs` so repeated calls within a
18
+ * session are cheap. Changes on disk are detected automatically on the next
19
+ * call.
20
+ * @param options - Configuration for the provider, including the global ignore path
21
+ * @returns A `FileAccessRuleProvider` function
22
+ */
23
+ export declare function createMakaioIgnoreProvider(options: MakaioIgnoreProviderOptions): FileAccessRuleProvider;
24
+ //# sourceMappingURL=makaioignore-provider.d.ts.map
@@ -0,0 +1,15 @@
1
+ import type { MakaioNodeExtension } from '@makaio/framework/contracts/extension';
2
+ import type { IMakaioBus } from '@makaio/framework/bus';
3
+ /**
4
+ * Filesystem tool extension.
5
+ *
6
+ * Contributes the `filesystem` toolset to the runtime `ToolRegistry` while
7
+ * keeping filesystem helper APIs available for composition roots and tests.
8
+ */
9
+ export declare const filesystemPackage: MakaioNodeExtension<IMakaioBus>;
10
+ export default filesystemPackage;
11
+ export { filesystemToolset, readOnlyFilesystemToolset } from './toolset.js';
12
+ export { type FileAccessRules, type FileAccessRuleProvider, FILE_ACCESS_RULES_KEY } from './types.js';
13
+ export { DEFAULT_DENIED_PATTERNS, createMakaioIgnoreProvider } from './ignore/index.js';
14
+ export { extractToolFilePath } from './tool-path-extractor.js';
15
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./src-B8KsDAy0.mjs";export{t as DEFAULT_DENIED_PATTERNS,a as FILE_ACCESS_RULES_KEY,i as createMakaioIgnoreProvider,o as default,o as filesystemPackage,n as extractToolFilePath,e as filesystemToolset,r as readOnlyFilesystemToolset};
@@ -0,0 +1,3 @@
1
+ export { default, filesystemPackage, filesystemToolset, readOnlyFilesystemToolset, FILE_ACCESS_RULES_KEY, DEFAULT_DENIED_PATTERNS, createMakaioIgnoreProvider, extractToolFilePath, } from './index.js';
2
+ export type { FileAccessRules, FileAccessRuleProvider } from './index.js';
3
+ //# sourceMappingURL=server.d.ts.map
@@ -0,0 +1 @@
1
+ import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./src-B8KsDAy0.mjs";export{t as DEFAULT_DENIED_PATTERNS,a as FILE_ACCESS_RULES_KEY,i as createMakaioIgnoreProvider,o as default,o as filesystemPackage,n as extractToolFilePath,e as filesystemToolset,r as readOnlyFilesystemToolset};
@@ -0,0 +1,4 @@
1
+ import{FILE_ACCESS_RULES_KEY as e,ToolErrorCodes as t,defineTool as n,defineToolset as r,errorToToolResult as i,extractToolFilePath as a,toolError as o,toolSuccess as s,widenTool as c}from"@makaio/framework/tools";import*as l from"node:fs/promises";import{readFile as u,stat as d}from"node:fs/promises";import{constants as f,realpathSync as p}from"node:fs";import{z as m}from"zod";import*as h from"node:path";import g from"node:path";import{glob as _}from"glob";import*as v from"node:readline";import y from"safe-regex2";import b from"ignore";function ee(e){let t=e?.allowedDirectories;return t===void 0||Array.isArray(t)&&t.every(e=>typeof e==`string`)}function te(e){return typeof e==`object`&&!!e&&`isDenied`in e&&typeof e.isDenied==`function`}function ne(t){let n=t.constraints?.[e];if(te(n)){if(!ee(n)){let{allowedDirectories:e,...t}=n;return t}return n}}function x(e){let t=h.resolve(e);for(;;)try{let n=p(t);return h.resolve(n,h.relative(t,e))}catch{let e=h.dirname(t);if(e===t)return;t=e}}function S(e,t){let n=process.platform===`win32`?e.toLowerCase():e,r=process.platform===`win32`?t.toLowerCase():t,i=h.relative(n,r);return i===``||!i.startsWith(`..${h.sep}`)&&i!==`..`&&!h.isAbsolute(i)}function C(e,t){return h.isAbsolute(e)?h.normalize(e):h.resolve(t.cwd,e)}function w(e){let t=ne(e),n=e.constraints?.allowedDirectories,r=t?.allowedDirectories??(Array.isArray(n)?n.filter(e=>typeof e==`string`):void 0),i=r?.map(x).filter(e=>e!==void 0);return e=>{let n;if(r!==void 0){if(r.length===0)return{valid:!1,error:`Path '${e}' is outside allowed directories`};let t=x(e);if(n=t,t===void 0||i?.some(e=>S(e,t))!==!0)return{valid:!1,error:`Path '${e}' is outside allowed directories`}}return t&&(n??=x(e),t.isDenied(e)||n!==void 0&&n!==e&&t.isDenied(n))?{valid:!1,error:`Access denied: '${e}' is restricted by .makaioignore rules`}:{valid:!0}}}function re(e,t){return w(t)(e)}function T(e,t,n=w(t)){let r=C(e,t),i=n(r);return i.valid?{valid:!0,path:r}:i}function E(e,t){return e.startsWith(`.`)}function D(e,n){if(e instanceof Error&&`code`in e){let r=e.code;if(r===`ENOENT`)return o(t.RESOURCE_NOT_FOUND,`File not found: ${n}`);if(r===`EACCES`||r===`EPERM`)return o(t.PERMISSION_DENIED,`Permission denied: ${n}`);if(r===`EISDIR`)return o(t.VALIDATION_FAILED,`Path is a directory, not a file: ${n}`)}return i(e)}function O(e){return h.isAbsolute(e)||h.win32.isAbsolute(e)?{valid:!1,error:`Absolute glob patterns are not allowed`}:/(^|[\\/{}(),])\.\.($|[\\/{}(),])/.test(e)?{valid:!1,error:`Glob patterns cannot traverse parent directories`}:{valid:!0}}const k=m.object({path:m.string().describe(`File path (absolute or relative to cwd)`),encoding:m.enum([`utf-8`,`base64`]).default(`utf-8`).optional().describe(`File encoding to use`),offset:m.number().int().min(0).optional().describe(`Line offset to start reading (0-indexed)`),limit:m.number().int().min(1).optional().describe(`Max lines to read`)}),ie=m.object({content:m.string().describe(`File content`),path:m.string().describe(`Resolved absolute path`),size:m.number().describe(`File size in bytes`),totalLines:m.number().optional().describe(`Total lines if text file`),truncated:m.boolean().describe(`True if limit was applied`)});async function ae(e,t,n){return s({content:(await e.readFile()).toString(`base64`),path:t,size:n,truncated:!1})}async function oe(e,t,n,r,i){let a=(await e.readFile(`utf-8`)).split(`
2
+ `),o=a.length,c,l=!1;return i===void 0?c=r>0?a.slice(r):a:(c=a.slice(r,r+i),l=r+i<o),s({content:c.join(`
3
+ `),path:t,size:n,totalLines:o,truncated:l})}const A=n({name:`read_file`,description:`Reads a file from the filesystem. Supports text (utf-8) and binary (base64) encoding. Can read specific line ranges with offset and limit parameters.`,annotations:{readOnly:!0},inputSchema:k,outputSchema:ie,execute:async(e,n)=>{let r=w(n),i=T(e.path,n,r);if(!i.valid)return o(t.PERMISSION_DENIED,i.error);let a=i.path;try{let i=await l.realpath(a),s=r(i);if(!s.valid)return o(t.PERMISSION_DENIED,s.error);if(!(await l.stat(i)).isFile())return o(t.VALIDATION_FAILED,`Path '${a}' is not a file`);let c=f.O_NOFOLLOW??0,u=f.O_NONBLOCK??0,d=await l.open(i,f.O_RDONLY|c|u);try{let r=await d.stat();if(!r.isFile())return o(t.VALIDATION_FAILED,`Path '${a}' is not a file`);let i=n.constraints?.maxFileSize;return i!==void 0&&r.size>i?o(t.VALIDATION_FAILED,`File size ${r.size} exceeds maximum allowed size ${i}`):(e.encoding??`utf-8`)===`base64`?ae(d,a,r.size):oe(d,a,r.size,e.offset??0,e.limit)}finally{await d.close()}}catch(e){return D(e,a)}}}),se=m.object({path:m.string().describe(`File path (absolute or relative to cwd)`),content:m.string().describe(`Content to write`),createDirectories:m.boolean().default(!1).optional().describe(`Create parent directories if they do not exist`),append:m.boolean().default(!1).optional().describe(`Append to file instead of overwriting`)}),ce=m.object({path:m.string().describe(`Resolved absolute path`),bytesWritten:m.number().describe(`Number of bytes written`),created:m.boolean().describe(`True if file was created (not overwritten)`)});async function j(e){try{return await l.access(e),!0}catch{return!1}}const M=n({name:`write_file`,description:`Writes content to a file. Can create parent directories and append to existing files. Returns information about the write operation.`,annotations:{destructive:!0},inputSchema:se,outputSchema:ce,execute:async(e,n)=>{let r=T(e.path,n);if(!r.valid)return o(t.PERMISSION_DENIED,r.error);let i=r.path,a=h.dirname(i),c=re(a,n);if(!c.valid)return o(t.PERMISSION_DENIED,c.error);try{let r=await j(i);e.createDirectories&&await l.mkdir(a,{recursive:!0});let c=n.constraints?.maxFileSize,u=Buffer.byteLength(e.content,`utf-8`);return c!==void 0&&u>c?o(t.VALIDATION_FAILED,`Content size ${u} exceeds maximum allowed size ${c}`):(e.append?await l.appendFile(i,e.content,`utf-8`):await l.writeFile(i,e.content,`utf-8`),s({path:i,bytesWritten:u,created:!r}))}catch(e){return e instanceof Error&&`code`in e&&e.code===`ENOENT`?o(t.RESOURCE_NOT_FOUND,`Parent directory does not exist: ${a}. Set createDirectories: true to create it.`):D(e,i)}}}),N=m.enum([`file`,`directory`,`symlink`,`other`]),P=m.object({name:m.string().describe(`Entry name`),path:m.string().describe(`Full path`),type:N.describe(`Entry type`),size:m.number().optional().describe(`Size in bytes (files only)`)}),F=m.object({path:m.string().describe(`Directory path`),recursive:m.boolean().default(!1).optional().describe(`List directories recursively`),includeHidden:m.boolean().default(!1).optional().describe(`Include hidden files and directories`),pattern:m.string().optional().describe(`Glob pattern to filter entries`)}),I=m.object({path:m.string().describe(`Resolved absolute path`),entries:m.array(P).describe(`Directory entries`),totalCount:m.number().describe(`Total number of entries`)});function L(e){return e.isFile()?`file`:e.isDirectory()?`directory`:e.isSymbolicLink()?`symlink`:`other`}async function R(e,t){let n=L(e),r={name:e.name,path:t,type:n};if(n===`file`)try{r.size=(await l.stat(t)).size}catch{}return r}function z(e,t){let n=e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`).replace(/\?/g,`.`);return RegExp(`^${n}$`,`i`).test(t)}async function B(e,t,n,r,i){let a=[],o=await l.readdir(e,{withFileTypes:!0});for(let s of o){if(!n&&E(s.name,t))continue;let o=h.join(e,s.name);i(o).valid&&(r&&!z(r,s.name)||a.push(await R(s,o)))}return a}async function V(e,t,n,r,i,a){let o=[];async function s(e){if(a?.aborted||!i(e).valid)return;let c=await l.readdir(e,{withFileTypes:!0});for(let l of c){if(a?.aborted)return;if(!n&&E(l.name,t))continue;let c=h.join(e,l.name);if(!i(c).valid)continue;let u=L(l);if((u===`directory`||!r||z(r,l.name))&&o.push(await R(l,c)),u===`directory`)try{await s(c)}catch{}}}return await s(e),o}const H=n({name:`list_directory`,description:`Lists the contents of a directory. Supports recursive listing, hidden file filtering, and glob pattern matching.`,annotations:{readOnly:!0},inputSchema:F,outputSchema:I,execute:async(e,n)=>{let r=w(n),i=T(e.path,n,r);if(!i.valid)return o(t.PERMISSION_DENIED,i.error);let a=i.path;try{if(!(await l.stat(a)).isDirectory())return o(t.VALIDATION_FAILED,`Path '${a}' is not a directory`);let i=e.includeHidden??!1,c=e.pattern,u;return u=e.recursive?await V(a,n,i,c,r,n.signal):await B(a,n,i,c,r),u.sort((e,t)=>e.type===`directory`&&t.type!==`directory`?-1:e.type!==`directory`&&t.type===`directory`?1:e.name.localeCompare(t.name)),s({path:a,entries:u,totalCount:u.length})}catch(e){return e instanceof Error&&`code`in e&&e.code===`ENOTDIR`?o(t.VALIDATION_FAILED,`Path is not a directory: ${a}`):D(e,a)}}}),U=n({name:`delete_file`,description:`Deletes a file from the filesystem. Only removes regular files (rejects symlinks and directories).`,annotations:{destructive:!0},inputSchema:m.object({path:m.string().describe(`File path (absolute or relative to cwd)`)}),outputSchema:m.object({path:m.string().describe(`Resolved absolute path of the deleted file`)}),execute:async(e,n)=>{let r=T(e.path,n);if(!r.valid)return o(t.PERMISSION_DENIED,r.error);let i=r.path;try{return(await l.lstat(i)).isFile()?(await l.unlink(i),s({path:i})):o(t.VALIDATION_FAILED,`Path is not a regular file: ${i}`)}catch(e){return D(e,i)}}}),W=n({name:`edit_file`,description:`Performs exact string replacement in a file. Finds old_string and replaces it with new_string. Fails if old_string is not found, or if found multiple times without replace_all.`,annotations:{destructive:!0},inputSchema:m.object({path:m.string().describe(`File path (absolute or relative to cwd)`),old_string:m.string().min(1).describe(`Exact text to find and replace`),new_string:m.string().describe(`Replacement text`),replace_all:m.boolean().default(!1).optional().describe(`Replace all occurrences instead of just the first`)}),outputSchema:m.object({path:m.string().describe(`Resolved absolute path`),replacements:m.number().describe(`Number of replacements made`)}),execute:async(e,n)=>{let r=T(e.path,n);if(!r.valid)return o(t.PERMISSION_DENIED,r.error);let i=r.path;try{let r=await l.stat(i),a=n.constraints?.maxFileSize;if(a!==void 0&&r.size>a)return o(t.VALIDATION_FAILED,`File size ${r.size} exceeds maximum allowed size ${a}`);let c=await l.readFile(i,`utf-8`);if(!c.includes(e.old_string))return o(t.VALIDATION_FAILED,`old_string not found in file: ${i}`);let u=c.split(e.old_string).length-1;if(u>1&&!e.replace_all)return o(t.VALIDATION_FAILED,`old_string found ${u} times in ${i}. Set replace_all: true to replace all, or provide a more specific old_string.`);let d=e.replace_all?c.replaceAll(e.old_string,e.new_string):c.replace(e.old_string,e.new_string);return a!==void 0&&Buffer.byteLength(d,`utf-8`)>a?o(t.VALIDATION_FAILED,`Resulting file size would exceed maximum allowed size ${a}`):(await l.writeFile(i,d,`utf-8`),s({path:i,replacements:e.replace_all?u:1}))}catch(e){return D(e,i)}}}),G=n({name:`glob_files`,description:`Find files matching a glob pattern. Returns absolute paths. Supports standard glob syntax: *, **, ?, [abc], {a,b}.`,annotations:{destructive:!1},inputSchema:m.object({pattern:m.string().describe(`Glob pattern (e.g. "**/*.ts", "src/**/*.test.ts")`),cwd:m.string().optional().describe(`Base directory for the glob (defaults to context cwd)`),limit:m.number().int().min(1).default(200).optional().describe(`Maximum results to return`),offset:m.number().int().min(0).default(0).optional().describe(`Skip this many results`)}),outputSchema:m.object({paths:m.array(m.string()).describe(`Matched file paths (absolute)`),totalMatches:m.number().describe(`Total matches before pagination`),truncated:m.boolean().describe(`True if more results exist beyond limit`)}),execute:async(e,n)=>{let r=O(e.pattern);if(!r.valid)return o(t.PERMISSION_DENIED,r.error);let a=w(n),c=T(e.cwd??n.cwd,n,a);if(!c.valid)return o(t.PERMISSION_DENIED,c.error);try{let t=(await _(e.pattern,{cwd:c.path,absolute:!0,nodir:!0,dot:!1})).filter(e=>a(e).valid);t.sort();let n=e.offset??0,r=e.limit??200;return s({paths:t.slice(n,n+r),totalMatches:t.length,truncated:n+r<t.length})}catch(e){return i(e)}}}),le=m.object({pattern:m.string().describe(`Search pattern (regex or literal string)`),path:m.string().optional().describe(`Directory to search in (defaults to cwd)`),glob:m.string().optional().describe(`File glob filter (e.g. "*.ts")`),case_insensitive:m.boolean().default(!1).optional().describe(`Case-insensitive matching`),limit:m.number().int().min(1).default(50).optional().describe(`Maximum matches to return`),offset:m.number().int().min(0).default(0).optional().describe(`Skip this many matches`)}),ue=m.object({file:m.string().describe(`File path`),line:m.number().describe(`Line number (1-indexed)`),text:m.string().describe(`Matched line content`)}),de=m.object({matches:m.array(ue).describe(`Matched lines`),totalMatches:m.number().describe(`Number of matches found (may be approximate if search terminated early)`),truncated:m.boolean().describe(`True if more matches exist beyond limit`)});async function fe(e,t,n,r){let i=[],a=0,o=!1,s=await l.realpath(e),c=r(s);if(!c.valid)throw Error(c.error);if(!(await l.stat(s)).isFile())throw Error(`Path is not a regular file: ${s}`);let u=f.O_NOFOLLOW??0,d=f.O_NONBLOCK??0,p=await l.open(s,f.O_RDONLY|u|d),m=p.createReadStream({encoding:`utf-8`,autoClose:!1}),h=v.createInterface({input:m,crlfDelay:1/0});try{if(!(await p.stat()).isFile())throw Error(`Path is not a regular file: ${s}`);for await(let r of h)if(a++,t.test(r)){if(i.length>=n){o=!0;break}i.push({file:e,line:a,text:r})}}finally{h.close(),m.destroy(),await p.close()}return{matches:i,hasMore:o}}const K=n({name:`grep_files`,description:`Search file contents for a pattern. Returns matching lines with file paths and line numbers. Supports regex patterns and optional file glob filtering.`,annotations:{destructive:!1},inputSchema:le,outputSchema:de,execute:async(e,n)=>{let r=e.path??n.cwd,a=w(n),c=T(r,n,a);if(!c.valid)return o(t.PERMISSION_DENIED,c.error);try{if(!(await l.stat(c.path)).isDirectory())return o(t.VALIDATION_FAILED,`Path is not a directory: ${c.path}`);let n=e.glob??`**/*`,r=O(n);if(!r.valid)return o(t.PERMISSION_DENIED,r.error);let i=(await _(n,{cwd:c.path,absolute:!0,nodir:!0,dot:!1})).filter(e=>a(e).valid),u=e.case_insensitive?`i`:``,d;if(!y(e.pattern))return o(t.VALIDATION_FAILED,`Unsafe regex pattern: ${e.pattern}`);try{d=new RegExp(e.pattern,u)}catch{return o(t.VALIDATION_FAILED,`Invalid regex pattern: ${e.pattern}`)}let f=e.offset??0,p=e.limit??50,m=f+p,h=[],g=!1;for(let e of i.sort()){if(h.length>=m){g=!0;break}try{let t=m-h.length,{matches:n,hasMore:r}=await fe(e,d,t,a);if(h.push(...n),r){g=!0;break}}catch{}}return s({matches:h.slice(f,f+p),totalMatches:h.length,truncated:g})}catch(e){return i(e)}}}),q=r({name:`filesystem`,description:`Cross-platform file system operations for reading, writing, and listing files and directories.`,version:`0.1.0`,tools:[c(A),c(M),c(W),c(H),c(U),c(G),c(K)]}),pe=r({name:`filesystem-read-only`,description:`Cross-platform read-only file system operations for reading, listing, and searching files.`,version:`0.1.0`,tools:[c(A),c(H),c(G),c(K)]}),J=`.env,.env.*,*.pem,*.p12,*.pfx,*.jks,**/.ssh/**,**/.ssh/id_*,**/id_rsa,**/id_dsa,**/.ssh/known_hosts,**/.ssh/config,**/.gnupg/**,**/.aws/credentials,**/.azure/credentials,**/.gcloud/**/*.json,**/.npmrc,.npmrc,**/.pypirc,.pypirc,**/.docker/config.json,**/.netrc,**/pip/pip.conf,**/.venv/**,**/venv/**,**/credentials,**/*-credentials.*`.split(`,`);function Y(e){return e.split(g.sep).join(`/`)}function X(e){return e===`..`||e.startsWith(`..${g.sep}`)||e.startsWith(`../`)||g.isAbsolute(e)}async function Z(e,t){try{let n=(await d(e)).mtimeMs,r=Q(t,e);if(r!==void 0&&r.mtime===n)return r;let i=(await u(e,`utf8`)).split(`
4
+ `).map(e=>e.replace(/\r$/,``)),a={patterns:i,mtime:n,matcher:b().add(i)};return $(t,e,a),a}catch(e){if(!_e(e))throw e;return}}async function me(e,t){let n=[],r=e;for(;;){let e=g.join(r,`.makaioignore`),i=await Z(e,t);i!==void 0&&n.push({dir:r,filePath:e,mtime:i.mtime,patterns:i.patterns,matcher:i.matcher});let a=g.dirname(r);if(a===r)break;r=a}return n.reverse()}async function he(e,t){let n=await Z(e,t);return n===void 0?null:{dir:g.dirname(e),filePath:e,mtime:n.mtime,patterns:n.patterns,matcher:n.matcher}}function ge(e,t,n){let r=b().add([...J]),i=t.map(t=>({matcher:t.matcher,cwdFromLayer:g.relative(t.dir,e)}));return t=>{let a=g.relative(e,t);if(a===``||X(a))return!1;let o=Y(a),s=r.ignores(o);if(n!==null){let e=n.matcher.test(o);e.unignored?s=!1:e.ignored&&(s=!0)}for(let{matcher:e,cwdFromLayer:t}of i){let n=t.length>0?Y(g.join(t,a)):o,r=e.test(n);r.unignored?s=!1:r.ignored&&(s=!0)}return s}}function _e(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}function Q(e,t){let n=e.get(t);if(n!==void 0)return e.delete(t),e.set(t,n),n}function $(e,t,n){for(e.has(t)&&e.delete(t),e.set(t,n);e.size>256;){let t=e.keys().next().value;if(t===void 0)break;e.delete(t)}}function ve(e){let{globalIgnorePath:t}=e,n=new Map,r=new Map;return async(e,i)=>{let[a,o]=await Promise.all([me(e,n),t===null?Promise.resolve(null):he(t,n)]),s=(o===null?``:`${o.filePath}:${o.mtime}|`)+a.map(e=>`${e.filePath}:${e.mtime}`).join(`|`),c=Q(r,e),l;return c!==void 0&&c.fingerprint===s?l=c.isDenied:(l=ge(e,a,o),$(r,e,{fingerprint:s,isDenied:l})),{...i!==void 0&&{allowedDirectories:[...i]},isDenied:l}}}const ye={name:`filesystem`,displayName:`Filesystem Tools`,version:`0.1.0`,surface:`headless`,tools:{createToolsets:()=>[q]}};export{q as a,J as i,a as n,pe as o,ve as r,e as s,ye as t};
@@ -0,0 +1,2 @@
1
+ export { extractToolFilePath } from '@makaio/framework/tools';
2
+ //# sourceMappingURL=tool-path-extractor.d.ts.map
@@ -0,0 +1,25 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * Input schema for the delete_file tool.
4
+ */
5
+ export declare const DeleteFileInputSchema: z.ZodObject<{
6
+ path: z.ZodString;
7
+ }, z.core.$strip>;
8
+ /**
9
+ * Output schema for the delete_file tool.
10
+ */
11
+ export declare const DeleteFileOutputSchema: z.ZodObject<{
12
+ path: z.ZodString;
13
+ }, z.core.$strip>;
14
+ export type DeleteFileInput = z.infer<typeof DeleteFileInputSchema>;
15
+ export type DeleteFileOutput = z.infer<typeof DeleteFileOutputSchema>;
16
+ /**
17
+ * Delete file tool definition.
18
+ * Removes a file from the filesystem. Does not delete directories.
19
+ */
20
+ export declare const deleteFileTool: import("@makaio/framework/tools").ToolDefinition<z.ZodObject<{
21
+ path: z.ZodString;
22
+ }, z.core.$strip>, z.ZodObject<{
23
+ path: z.ZodString;
24
+ }, z.core.$strip>>;
25
+ //# sourceMappingURL=delete-file.d.ts.map
@@ -0,0 +1,53 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * Input contract for targeted file edits.
4
+ */
5
+ export interface EditFileInput {
6
+ /** File path, absolute or relative to the execution cwd. */
7
+ readonly path: string;
8
+ /** Exact text to find and replace. */
9
+ readonly old_string: string;
10
+ /** Text to write in place of old_string. */
11
+ readonly new_string: string;
12
+ /** Replace every occurrence instead of requiring a unique match. */
13
+ readonly replace_all?: boolean;
14
+ }
15
+ /**
16
+ * Output contract for successful file edits.
17
+ */
18
+ export interface EditFileOutput {
19
+ /** Resolved absolute path that was edited. */
20
+ readonly path: string;
21
+ /** Number of replacements written. */
22
+ readonly replacements: number;
23
+ }
24
+ /**
25
+ * Input schema for the edit_file tool.
26
+ */
27
+ export declare const EditFileInputSchema: z.ZodObject<{
28
+ path: z.ZodString;
29
+ old_string: z.ZodString;
30
+ new_string: z.ZodString;
31
+ replace_all: z.ZodOptional<z.ZodDefault<z.ZodBoolean>>;
32
+ }, z.core.$strip>;
33
+ /**
34
+ * Output schema for the edit_file tool.
35
+ */
36
+ export declare const EditFileOutputSchema: z.ZodObject<{
37
+ path: z.ZodString;
38
+ replacements: z.ZodNumber;
39
+ }, z.core.$strip>;
40
+ /**
41
+ * Edit file tool definition.
42
+ * Performs exact string replacement in a file.
43
+ */
44
+ export declare const editFileTool: import("@makaio/framework/tools").ToolDefinition<z.ZodObject<{
45
+ path: z.ZodString;
46
+ old_string: z.ZodString;
47
+ new_string: z.ZodString;
48
+ replace_all: z.ZodOptional<z.ZodDefault<z.ZodBoolean>>;
49
+ }, z.core.$strip>, z.ZodObject<{
50
+ path: z.ZodString;
51
+ replacements: z.ZodNumber;
52
+ }, z.core.$strip>>;
53
+ //# sourceMappingURL=edit-file.d.ts.map
@@ -0,0 +1,35 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * Input schema for the glob_files tool.
4
+ */
5
+ export declare const GlobFilesInputSchema: z.ZodObject<{
6
+ pattern: z.ZodString;
7
+ cwd: z.ZodOptional<z.ZodString>;
8
+ limit: z.ZodOptional<z.ZodDefault<z.ZodNumber>>;
9
+ offset: z.ZodOptional<z.ZodDefault<z.ZodNumber>>;
10
+ }, z.core.$strip>;
11
+ /**
12
+ * Output schema for the glob_files tool.
13
+ */
14
+ export declare const GlobFilesOutputSchema: z.ZodObject<{
15
+ paths: z.ZodArray<z.ZodString>;
16
+ totalMatches: z.ZodNumber;
17
+ truncated: z.ZodBoolean;
18
+ }, z.core.$strip>;
19
+ export type GlobFilesInput = z.infer<typeof GlobFilesInputSchema>;
20
+ export type GlobFilesOutput = z.infer<typeof GlobFilesOutputSchema>;
21
+ /**
22
+ * Glob files tool definition.
23
+ * Returns file paths matching a glob pattern.
24
+ */
25
+ export declare const globFilesTool: import("@makaio/framework/tools").ToolDefinition<z.ZodObject<{
26
+ pattern: z.ZodString;
27
+ cwd: z.ZodOptional<z.ZodString>;
28
+ limit: z.ZodOptional<z.ZodDefault<z.ZodNumber>>;
29
+ offset: z.ZodOptional<z.ZodDefault<z.ZodNumber>>;
30
+ }, z.core.$strip>, z.ZodObject<{
31
+ paths: z.ZodArray<z.ZodString>;
32
+ totalMatches: z.ZodNumber;
33
+ truncated: z.ZodBoolean;
34
+ }, z.core.$strip>>;
35
+ //# sourceMappingURL=glob-files.d.ts.map
@@ -0,0 +1,70 @@
1
+ import { z } from 'zod';
2
+ import type { PathValidator } from '../utils/index.js';
3
+ /**
4
+ * Input schema for the grep_files tool.
5
+ */
6
+ export declare const GrepFilesInputSchema: z.ZodObject<{
7
+ pattern: z.ZodString;
8
+ path: z.ZodOptional<z.ZodString>;
9
+ glob: z.ZodOptional<z.ZodString>;
10
+ case_insensitive: z.ZodOptional<z.ZodDefault<z.ZodBoolean>>;
11
+ limit: z.ZodOptional<z.ZodDefault<z.ZodNumber>>;
12
+ offset: z.ZodOptional<z.ZodDefault<z.ZodNumber>>;
13
+ }, z.core.$strip>;
14
+ /**
15
+ * A single grep match.
16
+ */
17
+ declare const GrepMatchSchema: z.ZodObject<{
18
+ file: z.ZodString;
19
+ line: z.ZodNumber;
20
+ text: z.ZodString;
21
+ }, z.core.$strip>;
22
+ /**
23
+ * Output schema for the grep_files tool.
24
+ */
25
+ export declare const GrepFilesOutputSchema: z.ZodObject<{
26
+ matches: z.ZodArray<z.ZodObject<{
27
+ file: z.ZodString;
28
+ line: z.ZodNumber;
29
+ text: z.ZodString;
30
+ }, z.core.$strip>>;
31
+ totalMatches: z.ZodNumber;
32
+ truncated: z.ZodBoolean;
33
+ }, z.core.$strip>;
34
+ export type GrepFilesInput = z.infer<typeof GrepFilesInputSchema>;
35
+ export type GrepFilesOutput = z.infer<typeof GrepFilesOutputSchema>;
36
+ export type GrepMatch = z.infer<typeof GrepMatchSchema>;
37
+ /**
38
+ * Search a single file for lines matching a regex, with a budget.
39
+ * @param filePath - Absolute path to file.
40
+ * @param regex - Compiled regex pattern.
41
+ * @param budget - Maximum matches to collect (0 = stop immediately).
42
+ * @param validate - Path validator compiled for this tool invocation.
43
+ * @returns Array of matches (at most `budget` entries) and whether more remain.
44
+ */
45
+ export declare function searchFile(filePath: string, regex: RegExp, budget: number, validate: PathValidator): Promise<{
46
+ matches: GrepMatch[];
47
+ hasMore: boolean;
48
+ }>;
49
+ /**
50
+ * Grep files tool definition.
51
+ * Searches file contents for a pattern, returning matching lines.
52
+ */
53
+ export declare const grepFilesTool: import("@makaio/framework/tools").ToolDefinition<z.ZodObject<{
54
+ pattern: z.ZodString;
55
+ path: z.ZodOptional<z.ZodString>;
56
+ glob: z.ZodOptional<z.ZodString>;
57
+ case_insensitive: z.ZodOptional<z.ZodDefault<z.ZodBoolean>>;
58
+ limit: z.ZodOptional<z.ZodDefault<z.ZodNumber>>;
59
+ offset: z.ZodOptional<z.ZodDefault<z.ZodNumber>>;
60
+ }, z.core.$strip>, z.ZodObject<{
61
+ matches: z.ZodArray<z.ZodObject<{
62
+ file: z.ZodString;
63
+ line: z.ZodNumber;
64
+ text: z.ZodString;
65
+ }, z.core.$strip>>;
66
+ totalMatches: z.ZodNumber;
67
+ truncated: z.ZodBoolean;
68
+ }, z.core.$strip>>;
69
+ export {};
70
+ //# sourceMappingURL=grep-files.d.ts.map
@@ -0,0 +1,8 @@
1
+ export { readFileTool, ReadFileInputSchema, ReadFileOutputSchema, type ReadFileInput, type ReadFileOutput, } from './read-file.js';
2
+ export { writeFileTool, WriteFileInputSchema, WriteFileOutputSchema, type WriteFileInput, type WriteFileOutput, } from './write-file.js';
3
+ export { listDirectoryTool, ListDirectoryInputSchema, ListDirectoryOutputSchema, type ListDirectoryInput, type ListDirectoryOutput, type DirectoryEntry, type EntryType, } from './list-directory.js';
4
+ export { deleteFileTool, DeleteFileInputSchema, DeleteFileOutputSchema, type DeleteFileInput, type DeleteFileOutput, } from './delete-file.js';
5
+ export { editFileTool, EditFileInputSchema, EditFileOutputSchema, type EditFileInput, type EditFileOutput, } from './edit-file.js';
6
+ export { globFilesTool, GlobFilesInputSchema, GlobFilesOutputSchema, type GlobFilesInput, type GlobFilesOutput, } from './glob-files.js';
7
+ export { grepFilesTool, GrepFilesInputSchema, GrepFilesOutputSchema, type GrepFilesInput, type GrepFilesOutput, type GrepMatch, } from './grep-files.js';
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,81 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * Entry type enumeration for directory listing.
4
+ */
5
+ declare const EntryTypeSchema: z.ZodEnum<{
6
+ directory: "directory";
7
+ file: "file";
8
+ other: "other";
9
+ symlink: "symlink";
10
+ }>;
11
+ export type EntryType = z.infer<typeof EntryTypeSchema>;
12
+ /**
13
+ * Directory entry schema.
14
+ */
15
+ declare const DirectoryEntrySchema: z.ZodObject<{
16
+ name: z.ZodString;
17
+ path: z.ZodString;
18
+ type: z.ZodEnum<{
19
+ directory: "directory";
20
+ file: "file";
21
+ other: "other";
22
+ symlink: "symlink";
23
+ }>;
24
+ size: z.ZodOptional<z.ZodNumber>;
25
+ }, z.core.$strip>;
26
+ export type DirectoryEntry = z.infer<typeof DirectoryEntrySchema>;
27
+ /**
28
+ * Input schema for the list_directory tool.
29
+ */
30
+ export declare const ListDirectoryInputSchema: z.ZodObject<{
31
+ path: z.ZodString;
32
+ recursive: z.ZodOptional<z.ZodDefault<z.ZodBoolean>>;
33
+ includeHidden: z.ZodOptional<z.ZodDefault<z.ZodBoolean>>;
34
+ pattern: z.ZodOptional<z.ZodString>;
35
+ }, z.core.$strip>;
36
+ /**
37
+ * Output schema for the list_directory tool.
38
+ */
39
+ export declare const ListDirectoryOutputSchema: z.ZodObject<{
40
+ path: z.ZodString;
41
+ entries: z.ZodArray<z.ZodObject<{
42
+ name: z.ZodString;
43
+ path: z.ZodString;
44
+ type: z.ZodEnum<{
45
+ directory: "directory";
46
+ file: "file";
47
+ other: "other";
48
+ symlink: "symlink";
49
+ }>;
50
+ size: z.ZodOptional<z.ZodNumber>;
51
+ }, z.core.$strip>>;
52
+ totalCount: z.ZodNumber;
53
+ }, z.core.$strip>;
54
+ export type ListDirectoryInput = z.infer<typeof ListDirectoryInputSchema>;
55
+ export type ListDirectoryOutput = z.infer<typeof ListDirectoryOutputSchema>;
56
+ /**
57
+ * List directory tool definition.
58
+ * Lists contents of a directory with filtering options.
59
+ */
60
+ export declare const listDirectoryTool: import("@makaio/framework/tools").ToolDefinition<z.ZodObject<{
61
+ path: z.ZodString;
62
+ recursive: z.ZodOptional<z.ZodDefault<z.ZodBoolean>>;
63
+ includeHidden: z.ZodOptional<z.ZodDefault<z.ZodBoolean>>;
64
+ pattern: z.ZodOptional<z.ZodString>;
65
+ }, z.core.$strip>, z.ZodObject<{
66
+ path: z.ZodString;
67
+ entries: z.ZodArray<z.ZodObject<{
68
+ name: z.ZodString;
69
+ path: z.ZodString;
70
+ type: z.ZodEnum<{
71
+ directory: "directory";
72
+ file: "file";
73
+ other: "other";
74
+ symlink: "symlink";
75
+ }>;
76
+ size: z.ZodOptional<z.ZodNumber>;
77
+ }, z.core.$strip>>;
78
+ totalCount: z.ZodNumber;
79
+ }, z.core.$strip>>;
80
+ export {};
81
+ //# sourceMappingURL=list-directory.d.ts.map
@@ -0,0 +1,45 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * Input schema for the read_file tool.
4
+ */
5
+ export declare const ReadFileInputSchema: z.ZodObject<{
6
+ path: z.ZodString;
7
+ encoding: z.ZodOptional<z.ZodDefault<z.ZodEnum<{
8
+ base64: "base64";
9
+ "utf-8": "utf-8";
10
+ }>>>;
11
+ offset: z.ZodOptional<z.ZodNumber>;
12
+ limit: z.ZodOptional<z.ZodNumber>;
13
+ }, z.core.$strip>;
14
+ /**
15
+ * Output schema for the read_file tool.
16
+ */
17
+ export declare const ReadFileOutputSchema: z.ZodObject<{
18
+ content: z.ZodString;
19
+ path: z.ZodString;
20
+ size: z.ZodNumber;
21
+ totalLines: z.ZodOptional<z.ZodNumber>;
22
+ truncated: z.ZodBoolean;
23
+ }, z.core.$strip>;
24
+ export type ReadFileInput = z.infer<typeof ReadFileInputSchema>;
25
+ export type ReadFileOutput = z.infer<typeof ReadFileOutputSchema>;
26
+ /**
27
+ * Read file tool definition.
28
+ * Reads a file from the filesystem with optional line offset and limit.
29
+ */
30
+ export declare const readFileTool: import("@makaio/framework/tools").ToolDefinition<z.ZodObject<{
31
+ path: z.ZodString;
32
+ encoding: z.ZodOptional<z.ZodDefault<z.ZodEnum<{
33
+ base64: "base64";
34
+ "utf-8": "utf-8";
35
+ }>>>;
36
+ offset: z.ZodOptional<z.ZodNumber>;
37
+ limit: z.ZodOptional<z.ZodNumber>;
38
+ }, z.core.$strip>, z.ZodObject<{
39
+ content: z.ZodString;
40
+ path: z.ZodString;
41
+ size: z.ZodNumber;
42
+ totalLines: z.ZodOptional<z.ZodNumber>;
43
+ truncated: z.ZodBoolean;
44
+ }, z.core.$strip>>;
45
+ //# sourceMappingURL=read-file.d.ts.map
@@ -0,0 +1,35 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * Input schema for the write_file tool.
4
+ */
5
+ export declare const WriteFileInputSchema: z.ZodObject<{
6
+ path: z.ZodString;
7
+ content: z.ZodString;
8
+ createDirectories: z.ZodOptional<z.ZodDefault<z.ZodBoolean>>;
9
+ append: z.ZodOptional<z.ZodDefault<z.ZodBoolean>>;
10
+ }, z.core.$strip>;
11
+ /**
12
+ * Output schema for the write_file tool.
13
+ */
14
+ export declare const WriteFileOutputSchema: z.ZodObject<{
15
+ path: z.ZodString;
16
+ bytesWritten: z.ZodNumber;
17
+ created: z.ZodBoolean;
18
+ }, z.core.$strip>;
19
+ export type WriteFileInput = z.infer<typeof WriteFileInputSchema>;
20
+ export type WriteFileOutput = z.infer<typeof WriteFileOutputSchema>;
21
+ /**
22
+ * Write file tool definition.
23
+ * Writes content to a file, optionally creating parent directories.
24
+ */
25
+ export declare const writeFileTool: import("@makaio/framework/tools").ToolDefinition<z.ZodObject<{
26
+ path: z.ZodString;
27
+ content: z.ZodString;
28
+ createDirectories: z.ZodOptional<z.ZodDefault<z.ZodBoolean>>;
29
+ append: z.ZodOptional<z.ZodDefault<z.ZodBoolean>>;
30
+ }, z.core.$strip>, z.ZodObject<{
31
+ path: z.ZodString;
32
+ bytesWritten: z.ZodNumber;
33
+ created: z.ZodBoolean;
34
+ }, z.core.$strip>>;
35
+ //# sourceMappingURL=write-file.d.ts.map
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Filesystem toolset for the Makaio Framework.
3
+ *
4
+ * Provides cross-platform file system operations including reading,
5
+ * writing, and listing files and directories.
6
+ *
7
+ * ## Tools
8
+ * - `read_file` - Read file contents (text or binary)
9
+ * - `write_file` - Write content to files
10
+ * - `edit_file` - Exact string replacement in files
11
+ * - `list_directory` - List directory contents
12
+ * - `delete_file` - Delete a file
13
+ * - `glob_files` - Find files matching a glob pattern
14
+ * - `grep_files` - Search file contents for a pattern
15
+ *
16
+ * ## Path Resolution
17
+ * All paths are resolved relative to `context.cwd` unless absolute.
18
+ * Paths are validated against `context.constraints.allowedDirectories`
19
+ * when defined (`[]` denies all; `undefined` is unrestricted).
20
+ *
21
+ * ## Constraints
22
+ * The toolset respects these optional constraints in `MakaioContext`:
23
+ * - `allowedDirectories?: string[]` - Directory allow-list (`[]` denies all)
24
+ * - `maxFileSize: number` - Maximum file size in bytes
25
+ * @example
26
+ * ```typescript
27
+ * import { ToolRegistry } from '@makaio/framework/tools';
28
+ * import { filesystemToolset } from '@makaio/extension-filesystem';
29
+ *
30
+ * const registry = new ToolRegistry();
31
+ * await registry.register(filesystemToolset);
32
+ *
33
+ * // Execute read_file
34
+ * const result = await registry.execute('read_file', {
35
+ * path: './package.json',
36
+ * });
37
+ * ```
38
+ */
39
+ export declare const filesystemToolset: import("@makaio/framework/tools").Toolset<Record<string, import("@makaio/framework/tools").AnyToolDefinition>>;
40
+ /**
41
+ * Read-only filesystem toolset for agents that must not modify the workspace.
42
+ */
43
+ export declare const readOnlyFilesystemToolset: import("@makaio/framework/tools").Toolset<Record<string, import("@makaio/framework/tools").AnyToolDefinition>>;
44
+ //# sourceMappingURL=toolset.d.ts.map
@@ -0,0 +1,2 @@
1
+ export { FILE_ACCESS_RULES_KEY, type FileAccessRuleProvider, type FileAccessRules } from '@makaio/framework/tools';
2
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,14 @@
1
+ import type { MakaioContext } from '@makaio/framework/core';
2
+ import { type FileAccessRules } from '../types.js';
3
+ /**
4
+ * Safely read compiled file access rules from context constraints.
5
+ *
6
+ * When the `isDenied` predicate is present and callable, rules are accepted.
7
+ * If `allowedDirectories` is malformed it is stripped (treated as unrestricted)
8
+ * so the ignore-rules predicate still applies. Fully malformed payloads
9
+ * (missing `isDenied`) are treated as absent.
10
+ * @param context - Makaio execution context
11
+ * @returns File access rules when present and well-formed
12
+ */
13
+ export declare function getFileAccessRules(context: MakaioContext): FileAccessRules | undefined;
14
+ //# sourceMappingURL=file-access-rules.d.ts.map
@@ -0,0 +1,9 @@
1
+ import { type ToolFailure } from '@makaio/framework/tools';
2
+ /**
3
+ * Map a filesystem error to a structured tool failure.
4
+ * @param err - The caught error.
5
+ * @param resolvedPath - Resolved path for error messages.
6
+ * @returns A ToolFailure with an appropriate error code.
7
+ */
8
+ export declare function handleFsError(err: unknown, resolvedPath: string): ToolFailure;
9
+ //# sourceMappingURL=fs-errors.d.ts.map
@@ -0,0 +1,8 @@
1
+ import type { PathValidationResult } from './path-utils.js';
2
+ /**
3
+ * Validates that a glob pattern is scoped to the configured search root.
4
+ * @param pattern - Glob pattern supplied by the tool caller.
5
+ * @returns Validation result indicating whether the pattern stays relative.
6
+ */
7
+ export declare function validateRelativeGlobPattern(pattern: string): PathValidationResult;
8
+ //# sourceMappingURL=glob-patterns.d.ts.map
@@ -0,0 +1,6 @@
1
+ export { resolvePath, createPathValidator, validatePath, resolveAndValidatePath, getFileName, getParentDir, type PathValidationResult, type PathValidator, } from './path-utils.js';
2
+ export { isHiddenName, getPathSeparator, normalizePlatformPath } from './platform.js';
3
+ export { getFileAccessRules } from './file-access-rules.js';
4
+ export { handleFsError } from './fs-errors.js';
5
+ export { validateRelativeGlobPattern } from './glob-patterns.js';
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,63 @@
1
+ import type { MakaioContext } from '@makaio/framework/core';
2
+ /**
3
+ * Result type for path validation.
4
+ */
5
+ export type PathValidationResult = {
6
+ valid: true;
7
+ } | {
8
+ valid: false;
9
+ error: string;
10
+ };
11
+ /** Reusable validator for paths resolved within one tool invocation. */
12
+ export type PathValidator = (resolvedPath: string) => PathValidationResult;
13
+ /**
14
+ * Resolves a path relative to context.cwd.
15
+ * Handles both absolute and relative paths, normalizing the result.
16
+ * @param inputPath - Path to resolve (absolute or relative)
17
+ * @param context - Makaio execution context
18
+ * @returns Normalized absolute path
19
+ */
20
+ export declare function resolvePath(inputPath: string, context: MakaioContext): string;
21
+ /**
22
+ * Compiles path validation for one tool invocation.
23
+ * Canonical allowed roots are resolved once and reused for every candidate.
24
+ * @param context - Makaio execution context with optional constraints
25
+ * @returns Reusable validation function
26
+ */
27
+ export declare function createPathValidator(context: MakaioContext): PathValidator;
28
+ /**
29
+ * Validates that a resolved path is within allowed constraints.
30
+ * Checks against context.constraints.allowedDirectories when provided.
31
+ * @param resolvedPath - Absolute, normalized path to validate
32
+ * @param context - Makaio execution context with optional constraints
33
+ * @returns Validation result indicating if path is allowed
34
+ */
35
+ export declare function validatePath(resolvedPath: string, context: MakaioContext): PathValidationResult;
36
+ /**
37
+ * Resolves and validates a path in one operation.
38
+ * Convenience function that combines resolvePath and validatePath.
39
+ * @param inputPath - Path to resolve and validate
40
+ * @param context - Makaio execution context
41
+ * @param validate - Optional validator compiled by the caller for this invocation
42
+ * @returns Result with resolved path or validation error
43
+ */
44
+ export declare function resolveAndValidatePath(inputPath: string, context: MakaioContext, validate?: PathValidator): {
45
+ valid: true;
46
+ path: string;
47
+ } | {
48
+ valid: false;
49
+ error: string;
50
+ };
51
+ /**
52
+ * Extracts the file name from a path.
53
+ * @param filePath - Full path to extract name from
54
+ * @returns File or directory name
55
+ */
56
+ export declare function getFileName(filePath: string): string;
57
+ /**
58
+ * Gets the parent directory of a path.
59
+ * @param filePath - Path to get parent of
60
+ * @returns Parent directory path
61
+ */
62
+ export declare function getParentDir(filePath: string): string;
63
+ //# sourceMappingURL=path-utils.d.ts.map
@@ -0,0 +1,28 @@
1
+ import type { MakaioContext } from '@makaio/framework/core';
2
+ /**
3
+ * Checks if a file or directory name indicates a hidden item.
4
+ * Uses cross-platform heuristic: names starting with '.' are hidden.
5
+ *
6
+ * Note: On Windows, true hidden files have a hidden attribute that requires
7
+ * additional system calls to detect. This function uses a simplified approach
8
+ * that works consistently across platforms for Unix-style hidden files.
9
+ * @param name - File or directory name (not full path)
10
+ * @param _context - Makaio context (reserved for future platform-specific logic)
11
+ * @returns True if the item appears to be hidden
12
+ */
13
+ export declare function isHiddenName(name: string, _context: MakaioContext): boolean;
14
+ /**
15
+ * Determines the path separator for the current platform.
16
+ * @param context - Makaio context with platform info
17
+ * @returns Path separator character
18
+ */
19
+ export declare function getPathSeparator(context: MakaioContext): string;
20
+ /**
21
+ * Normalizes a path for display based on platform.
22
+ * Ensures consistent separator usage for the target platform.
23
+ * @param filePath - Path to normalize
24
+ * @param context - Makaio context with platform info
25
+ * @returns Path with platform-appropriate separators
26
+ */
27
+ export declare function normalizePlatformPath(filePath: string, context: MakaioContext): string;
28
+ //# sourceMappingURL=platform.d.ts.map
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@makaio/extension-filesystem",
3
+ "description": "Filesystem tool extension for AI agents with path validation.",
4
+ "version": "1.0.0-dev-1783942498489",
5
+ "types": "dist/index.d.ts",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/makaio-ai/makaio-framework.git",
10
+ "directory": "extensions/filesystem"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "default": "./dist/index.mjs"
16
+ },
17
+ "./server": {
18
+ "types": "./dist/server.d.ts",
19
+ "default": "./dist/server.mjs"
20
+ },
21
+ "./package.json": "./package.json"
22
+ },
23
+ "peerDependencies": {
24
+ "@makaio/framework": ">=1.0.0-0 <2.0.0"
25
+ },
26
+ "dependencies": {
27
+ "glob": "^13.0.0",
28
+ "ignore": "^7.0.0",
29
+ "safe-regex2": "^5.1.1",
30
+ "zod": "4.4.3"
31
+ },
32
+ "scripts": {
33
+ "build": "bun build.ts",
34
+ "test": "vitest run"
35
+ },
36
+ "files": [
37
+ "dist",
38
+ "descriptor.json",
39
+ "LICENSE",
40
+ "README.md"
41
+ ],
42
+ "license": "MIT",
43
+ "private": false,
44
+ "main": "dist/index.mjs",
45
+ "publishConfig": {
46
+ "access": "public"
47
+ }
48
+ }