@makaio/extension-filesystem 1.0.0-dev-1786014320559 → 1.0.0-dev-1789404058608
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/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./src-
|
|
1
|
+
import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./src-Ba4NZ-VM.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};
|
package/dist/server.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./src-
|
|
1
|
+
import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./src-Ba4NZ-VM.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};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
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
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(`
|
|
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);try{if(!(await p.stat()).isFile())throw Error(`Path is not a regular file: ${s}`);let r=p.createReadStream({encoding:`utf-8`,autoClose:!1}),c=v.createInterface({input:r,crlfDelay:1/0});try{for await(let r of c)if(a++,t.test(r)){if(i.length>=n){o=!0;break}i.push({file:e,line:a,text:r})}}finally{c.close(),r.destroy()}}finally{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
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};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@makaio/extension-filesystem",
|
|
3
3
|
"description": "Filesystem tool extension for AI agents with path validation.",
|
|
4
|
-
"version": "1.0.0-dev-
|
|
4
|
+
"version": "1.0.0-dev-1789404058608",
|
|
5
5
|
"types": "dist/index.d.ts",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"repository": {
|