toolpack-sdk 1.2.0 → 1.3.0
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/README.md +130 -9
- package/dist/index.cjs +141 -105
- package/dist/index.d.cts +106 -12
- package/dist/index.d.ts +106 -12
- package/dist/index.js +140 -104
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,57 +1,57 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`;(0,ai.appendFileSync)(Xr,o)}function Y(s){Vt("error",s)}function D(s){Vt("warn",s)}function v(s){Vt("info",s)}function h(s){Vt("debug",s)}function be(s){Vt("trace",s)}function Vg(s){return s.replace(/\bsk-[A-Za-z0-9_-]{10,}\b/g,"[REDACTED]").replace(/\bsk-proj-[A-Za-z0-9_-]{10,}\b/g,"[REDACTED]").replace(/\bAIza[0-9A-Za-z_-]{10,}\b/g,"[REDACTED]").replace(/\bBearer\s+[A-Za-z0-9._-]{10,}\b/g,"Bearer [REDACTED]")}function E(s,e=200){try{let t=typeof s=="string"?s:JSON.stringify(s),o=Vg(t);return o.length<=e?o:`${o.slice(0,e)}\u2026`}catch{return"[Unserializable]"}}function X(s,e,t){Ae("debug")&&(h(`[${e}][${s}] Messages (${t.length}):`),t.forEach((o,r)=>{h(`[${e}][${s}] #${r} role=${o?.role} content=${E(o?.content,300)}`)}))}var ai,li,Vr,zo,Ko,Xr,_=f(()=>{"use strict";l();ai=require("fs"),li=require("path"),Vr={error:0,warn:1,info:2,debug:3,trace:4},zo=!1,Ko="info",Xr=(0,li.join)(process.cwd(),"toolpack-sdk.log")});var Zt={};V(Zt,{fetchUrlAsBase64:()=>nn,getMimeType:()=>en,isDataUri:()=>tn,normalizeImagePart:()=>xi,parseDataUri:()=>on,readFileAsBase64:()=>rn,toDataUri:()=>bi});function en(s){let e=wi.extname(s).toLowerCase();return Zg[e]||"application/octet-stream"}function tn(s){return s.startsWith("data:")}function on(s){let e=s.match(/^data:(.*?);base64,(.+)$/);return e?{mimeType:e[1],data:e[2]}:null}function bi(s,e){return`data:${e};base64,${s}`}async function rn(s){try{return{data:(await yi.readFile(s)).toString("base64"),mimeType:en(s)}}catch(e){throw new N(`Failed to read image file: ${s}`,e)}}async function nn(s){try{let e=await fetch(s);if(!e.ok)throw new Error(`HTTP ${e.status} ${e.statusText}`);let t=await e.arrayBuffer(),o=Buffer.from(t),r=e.headers.get("content-type")||"application/octet-stream";return r=r.split(";")[0].trim(),{data:o.toString("base64"),mimeType:r}}catch(e){throw new I(`Failed to download image from URL: ${s}`,"FETCH_ERROR",500,e)}}async function xi(s){if(s.type==="image_data")return{data:s.image_data.data,mimeType:s.image_data.mimeType};if(s.type==="image_file")return await rn(s.image_file.path);if(s.type==="image_url"){let e=s.image_url.url;if(tn(e)){let t=on(e);if(!t)throw new N(`Malformed data URI provided in image_url: ${e.substring(0,50)}...`);return t}return await nn(e)}throw new N(`Unknown ImagePart type: ${s.type}`)}var yi,wi,Zg,Je=f(()=>{"use strict";l();yi=P(require("fs/promises"),1),wi=P(require("path"),1);de();Zg={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".heic":"image/heic",".heif":"image/heif"}});var ki,Ri,Di,Ei,Ni,Ai=f(()=>{"use strict";l();ki="fs.read_file",Ri="Read File",Di="Read the contents of a file at the given path. Returns the file content as a string.",Ei="filesystem",Ni={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path"]}});async function oh(s){let e=s.path,t=s.encoding||"utf-8";if(h(`[fs.read-file] execute path="${e}" encoding=${t}`),!e)throw new Error("path is required");if(!ze.existsSync(e))throw new Error(`File not found: ${e}`);if(ze.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);return ze.readFileSync(e,t)}var ze,Ke,mn=f(()=>{"use strict";l();ze=P(require("fs"),1);Ai();_();Ke={name:ki,displayName:Ri,description:Di,parameters:Ni,category:Ei,execute:oh}});var Mi,Oi,Ii,ji,Fi,Li=f(()=>{"use strict";l();Mi="fs.write_file",Oi="Write File",Ii="Write content to a file. Creates parent directories if they do not exist. Overwrites existing files.",ji="filesystem",Fi={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to write"},content:{type:"string",description:"Content to write to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});async function rh(s){let e=s.path,t=s.content,o=s.encoding||"utf-8";if(h(`[fs.write-file] execute path="${e}" encoding=${o} content_len=${t?.length??0}`),!e)throw new Error("path is required");if(t==null)throw new Error("content is required");let r=qi.dirname(e);return Qe.existsSync(r)||Qe.mkdirSync(r,{recursive:!0}),Qe.writeFileSync(e,t,o),`File written successfully: ${e} (${Buffer.byteLength(t,o)} bytes)`}var Qe,qi,Ye,dn=f(()=>{"use strict";l();Qe=P(require("fs"),1),qi=P(require("path"),1);Li();_();Ye={name:Mi,displayName:Oi,description:Ii,parameters:Fi,category:ji,execute:rh}});var Ui,Wi,Gi,Bi,Ji,Hi=f(()=>{"use strict";l();Ui="fs.append_file",Wi="Append File",Gi="Append content to the end of a file. Creates the file if it does not exist.",Bi="filesystem",Ji={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to append to"},content:{type:"string",description:"Content to append to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});async function nh(s){let e=s.path,t=s.content,o=s.encoding||"utf-8";if(!e)throw new Error("path is required");if(t==null)throw new Error("content is required");let r=zi.dirname(e);return Ve.existsSync(r)||Ve.mkdirSync(r,{recursive:!0}),Ve.appendFileSync(e,t,o),`Content appended to: ${e} (${Buffer.byteLength(t,o)} bytes appended)`}var Ve,zi,Xe,un=f(()=>{"use strict";l();Ve=P(require("fs"),1),zi=P(require("path"),1);Hi();Xe={name:Ui,displayName:Wi,description:Gi,parameters:Ji,category:Bi,execute:nh}});var Ki,Qi,Yi,Vi,Xi,Zi=f(()=>{"use strict";l();Ki="fs.delete_file",Qi="Delete File",Yi="Delete a file at the given path. Does not delete directories.",Vi="filesystem",Xi={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to delete"}},required:["path"]}});async function sh(s){let e=s.path;if(h(`[fs.delete-file] execute path="${e}"`),!e)throw new Error("path is required");if(!Ze.existsSync(e))throw new Error(`File not found: ${e}`);if(Ze.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}. Use a different tool to remove directories.`);return Ze.unlinkSync(e),`File deleted successfully: ${e}`}var Ze,et,fn=f(()=>{"use strict";l();Ze=P(require("fs"),1);Zi();_();et={name:Ki,displayName:Qi,description:Yi,parameters:Xi,category:Vi,execute:sh}});var ea,ta,oa,ra,na,sa=f(()=>{"use strict";l();ea="fs.exists",ta="Exists",oa="Check if a file or directory exists at the given path. Returns true or false.",ra="filesystem",na={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to check"}},required:["path"]}});async function ih(s){let e=s.path;if(!e)throw new Error("path is required");let t=ia.existsSync(e);return JSON.stringify({exists:t,path:e})}var ia,tt,gn=f(()=>{"use strict";l();ia=P(require("fs"),1);sa();tt={name:ea,displayName:ta,description:oa,parameters:na,category:ra,execute:ih}});var aa,la,ca,pa,ma,da=f(()=>{"use strict";l();aa="fs.stat",la="Stat",ca="Get file or directory information including size, type, and modification date.",pa="filesystem",ma={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to get info for"}},required:["path"]}});async function ah(s){let e=s.path;if(!e)throw new Error("path is required");if(!Zo.existsSync(e))throw new Error(`Path not found: ${e}`);let t=Zo.statSync(e);return JSON.stringify({path:e,type:t.isDirectory()?"directory":t.isFile()?"file":"other",size:t.size,created:t.birthtime.toISOString(),modified:t.mtime.toISOString(),accessed:t.atime.toISOString(),permissions:t.mode.toString(8)})}var Zo,ot,hn=f(()=>{"use strict";l();Zo=P(require("fs"),1);da();ot={name:aa,displayName:la,description:ca,parameters:ma,category:pa,execute:ah}});var ua,fa,ga,ha,ya,wa=f(()=>{"use strict";l();ua="fs.list_dir",fa="List Directory",ga="List files and directories at the given path. Optionally recurse into subdirectories.",ha="filesystem",ya={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to list"},recursive:{type:"boolean",description:"Whether to list recursively (default: false)",default:!1}},required:["path"]}});function xa(s,e,t,o=""){let r=Me.readdirSync(s,{withFileTypes:!0});for(let n of r){let a=ba.join(s,n.name),i=o?`${o}/${n.name}`:n.name;if(n.isDirectory())t.push({name:i,type:"directory",size:0}),e&&xa(a,!0,t,i);else if(n.isFile()){let c=Me.statSync(a);t.push({name:i,type:"file",size:c.size})}}}async function lh(s){let e=s.path,t=s.recursive===!0;if(!e)throw new Error("path is required");if(!Me.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Me.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let r=[];return xa(e,t,r),JSON.stringify(r,null,2)}var Me,ba,rt,yn=f(()=>{"use strict";l();Me=P(require("fs"),1),ba=P(require("path"),1);wa();rt={name:ua,displayName:fa,description:ga,parameters:ya,category:ha,execute:lh}});var Ta,Pa,Ca,va,Sa,$a=f(()=>{"use strict";l();Ta="fs.create_dir",Pa="Create Directory",Ca="Create a directory at the given path. Creates parent directories recursively if they do not exist.",va="filesystem",Sa={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to create"},recursive:{type:"boolean",description:"Create parent directories if they do not exist (default: true)",default:!0}},required:["path"]}});async function ch(s){let e=s.path,t=s.recursive!==!1;if(!e)throw new Error("path is required");if(nt.existsSync(e)){if(nt.statSync(e).isDirectory())return`Directory already exists: ${e}`;throw new Error(`Path exists but is not a directory: ${e}`)}return nt.mkdirSync(e,{recursive:t}),`Directory created: ${e}`}var nt,st,wn=f(()=>{"use strict";l();nt=P(require("fs"),1);$a();st={name:Ta,displayName:Pa,description:Ca,parameters:Sa,category:va,execute:ch}});var _a,ka,Ra,Da,Ea,Na=f(()=>{"use strict";l();_a="fs.move",ka="Move",Ra="Move or rename a file or directory from one path to another.",Da="filesystem",Ea={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});async function ph(s){let e=s.path,t=s.new_path;if(!e)throw new Error("path is required");if(!t)throw new Error("new_path is required");if(!Oe.existsSync(e))throw new Error(`Source not found: ${e}`);let o=Aa.dirname(t);return Oe.existsSync(o)||Oe.mkdirSync(o,{recursive:!0}),Oe.renameSync(e,t),`Moved: ${e} \u2192 ${t}`}var Oe,Aa,it,bn=f(()=>{"use strict";l();Oe=P(require("fs"),1),Aa=P(require("path"),1);Na();it={name:_a,displayName:ka,description:Ra,parameters:Ea,category:Da,execute:ph}});var Ma,Oa,Ia,ja,Fa,La=f(()=>{"use strict";l();Ma="fs.copy",Oa="Copy",Ia="Copy a file or directory from one path to another. Recursively copies directories.",ja="filesystem",Fa={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});function qa(s,e){if(Q.statSync(s).isDirectory()){Q.existsSync(e)||Q.mkdirSync(e,{recursive:!0});let o=Q.readdirSync(s);for(let r of o)qa(io.join(s,r),io.join(e,r))}else Q.copyFileSync(s,e)}async function mh(s){let e=s.path,t=s.new_path;if(!e)throw new Error("path is required");if(!t)throw new Error("new_path is required");if(!Q.existsSync(e))throw new Error(`Source not found: ${e}`);let o=io.dirname(t);return Q.existsSync(o)||Q.mkdirSync(o,{recursive:!0}),qa(e,t),`Copied ${Q.statSync(e).isDirectory()?"directory":"file"}: ${e} \u2192 ${t}`}var Q,io,at,xn=f(()=>{"use strict";l();Q=P(require("fs"),1),io=P(require("path"),1);La();at={name:Ma,displayName:Oa,description:Ia,parameters:Fa,category:ja,execute:mh}});var Ua,Wa,Ga,Ba,Ja,Ha=f(()=>{"use strict";l();Ua="fs.read_file_range",Wa="Read File Range",Ga="Read a specific range of lines from a file. Useful for reading portions of large files without loading the entire content.",Ba="filesystem",Ja={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},start_line:{type:"integer",description:"Start line number (1-indexed)"},end_line:{type:"integer",description:"End line number (1-indexed, inclusive)"}},required:["path","start_line","end_line"]}});async function dh(s){let e=s.path,t=s.start_line,o=s.end_line;if(!e)throw new Error("path is required");if(t==null)throw new Error("start_line is required");if(o==null)throw new Error("end_line is required");if(t<1)throw new Error("start_line must be >= 1");if(o<t)throw new Error("end_line must be >= start_line");if(!lt.existsSync(e))throw new Error(`File not found: ${e}`);if(lt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let a=lt.readFileSync(e,"utf-8").split(`
|
|
3
|
-
`),i=a.length,c=Math.min(t,i),p=Math.min(
|
|
1
|
+
"use strict";var Yg=Object.create;var Go=Object.defineProperty;var Vg=Object.getOwnPropertyDescriptor;var Xg=Object.getOwnPropertyNames;var Zg=Object.getPrototypeOf,eh=Object.prototype.hasOwnProperty;var f=(s,e)=>()=>(s&&(e=s(s=0)),e);var V=(s,e)=>{for(var t in e)Go(s,t,{get:e[t],enumerable:!0})},li=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Xg(e))!eh.call(s,o)&&o!==t&&Go(s,o,{get:()=>e[o],enumerable:!(r=Vg(e,o))||r.enumerable});return s};var T=(s,e,t)=>(t=s!=null?Yg(Zg(s)):{},li(e||!s||!s.__esModule?Go(t,"default",{value:s,enumerable:!0}):t,s)),th=s=>li(Go({},"__esModule",{value:!0}),s);var l=f(()=>{"use strict"});var J,pe,me,N,I,we,Vr,Xr,de=f(()=>{"use strict";l();J=class extends Error{constructor(t,r,o,n){super(t);this.code=r;this.statusCode=o;this.cause=n;this.name="SDKError"}code;statusCode;cause},pe=class extends J{constructor(e,t){super(e,"AUTHENTICATION_ERROR",401,t),this.name="AuthenticationError"}},me=class extends J{constructor(t,r,o){super(t,"RATE_LIMIT_ERROR",429,o);this.retryAfter=r;this.name="RateLimitError"}retryAfter},N=class extends J{constructor(e,t){super(e,"INVALID_REQUEST_ERROR",400,t),this.name="InvalidRequestError"}},I=class extends J{constructor(e,t="PROVIDER_ERROR",r=500,o){super(e,t,r,o),this.name="ProviderError"}},we=class extends J{constructor(e,t){super(e,"CONNECTION_ERROR",503,t),this.name="ConnectionError"}},Vr=class extends J{constructor(t,r,o){super(t,"PAGE_ERROR",502,o);this.pageUrl=r;this.name="PageError"}pageUrl},Xr=class extends J{constructor(t,r,o){super(t,"TIMEOUT_ERROR",504,o);this.phase=r;this.name="TimeoutError"}phase}});var ci,H,Xt=f(()=>{"use strict";l();ci={enabled:!1,alwaysLoadedTools:[],alwaysLoadedCategories:[],searchResultLimit:5,cacheDiscoveredTools:!0},H={enabled:!0,autoExecute:!0,maxToolRounds:5,toolChoicePolicy:"auto",resultMaxChars:2e4,enabledTools:[],enabledToolCategories:[],toolSearch:ci}});function mi(s){if(!s)return;let e=s.toLowerCase();if(e in Zr)return e;console.warn(`[Toolpack Warning] Invalid log level "${s}". Falling back to "info".`)}function fi(s){s?.enabled!==void 0&&(Ko=s.enabled),s?.filePath&&(en=s.filePath),s?.level&&(Qo=mi(s.level)||"info"),process.env.TOOLPACK_SDK_LOG_ENABLED!==void 0&&(Ko=process.env.TOOLPACK_SDK_LOG_ENABLED==="true"),process.env.TOOLPACK_SDK_LOG_FILE&&(en=process.env.TOOLPACK_SDK_LOG_FILE,Ko=!0),process.env.TOOLPACK_SDK_LOG_LEVEL&&(Qo=mi(process.env.TOOLPACK_SDK_LOG_LEVEL)||Qo)}function Me(s){return Ko?Zr[s]<=Zr[Qo]:!1}function Zt(s,e){if(!Me(s))return;let r=`[${new Date().toISOString()}] [${s.toUpperCase()}] ${e}
|
|
2
|
+
`;(0,di.appendFileSync)(en,r)}function Y(s){Zt("error",s)}function E(s){Zt("warn",s)}function v(s){Zt("info",s)}function h(s){Zt("debug",s)}function be(s){Zt("trace",s)}function nh(s){return s.replace(/\bsk-[A-Za-z0-9_-]{10,}\b/g,"[REDACTED]").replace(/\bsk-proj-[A-Za-z0-9_-]{10,}\b/g,"[REDACTED]").replace(/\bAIza[0-9A-Za-z_-]{10,}\b/g,"[REDACTED]").replace(/\bBearer\s+[A-Za-z0-9._-]{10,}\b/g,"Bearer [REDACTED]")}function D(s,e=200){try{let t=typeof s=="string"?s:JSON.stringify(s),r=nh(t);return r.length<=e?r:`${r.slice(0,e)}\u2026`}catch{return"[Unserializable]"}}function X(s,e,t){Me("debug")&&(h(`[${e}][${s}] Messages (${t.length}):`),t.forEach((r,o)=>{h(`[${e}][${s}] #${o} role=${r?.role} content=${D(r?.content,300)}`)}))}var di,ui,Zr,Ko,Qo,en,k=f(()=>{"use strict";l();di=require("fs"),ui=require("path"),Zr={error:0,warn:1,info:2,debug:3,trace:4},Ko=!1,Qo="info",en=(0,ui.join)(process.cwd(),"toolpack-sdk.log")});var to={};V(to,{fetchUrlAsBase64:()=>an,getMimeType:()=>on,isDataUri:()=>rn,normalizeImagePart:()=>Si,parseDataUri:()=>nn,readFileAsBase64:()=>sn,toDataUri:()=>vi});function on(s){let e=Ci.extname(s).toLowerCase();return ih[e]||"application/octet-stream"}function rn(s){return s.startsWith("data:")}function nn(s){let e=s.match(/^data:(.*?);base64,(.+)$/);return e?{mimeType:e[1],data:e[2]}:null}function vi(s,e){return`data:${e};base64,${s}`}async function sn(s){try{return{data:(await Pi.readFile(s)).toString("base64"),mimeType:on(s)}}catch(e){throw new N(`Failed to read image file: ${s}`,e)}}async function an(s){try{let e=await fetch(s);if(!e.ok)throw new Error(`HTTP ${e.status} ${e.statusText}`);let t=await e.arrayBuffer(),r=Buffer.from(t),o=e.headers.get("content-type")||"application/octet-stream";return o=o.split(";")[0].trim(),{data:r.toString("base64"),mimeType:o}}catch(e){throw new I(`Failed to download image from URL: ${s}`,"FETCH_ERROR",500,e)}}async function Si(s){if(s.type==="image_data")return{data:s.image_data.data,mimeType:s.image_data.mimeType};if(s.type==="image_file")return await sn(s.image_file.path);if(s.type==="image_url"){let e=s.image_url.url;if(rn(e)){let t=nn(e);if(!t)throw new N(`Malformed data URI provided in image_url: ${e.substring(0,50)}...`);return t}return await an(e)}throw new N(`Unknown ImagePart type: ${s.type}`)}var Pi,Ci,ih,ze=f(()=>{"use strict";l();Pi=T(require("fs/promises"),1),Ci=T(require("path"),1);de();ih={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".heic":"image/heic",".heif":"image/heif"}});var Ai,Mi,Oi,Ii,ji,Fi=f(()=>{"use strict";l();Ai="fs.read_file",Mi="Read File",Oi="Read the contents of a file at the given path. Returns the file content as a string.",Ii="filesystem",ji={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path"]}});async function ch(s){let e=s.path,t=s.encoding||"utf-8";if(h(`[fs.read-file] execute path="${e}" encoding=${t}`),!e)throw new Error("path is required");if(!Qe.existsSync(e))throw new Error(`File not found: ${e}`);if(Qe.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);return Qe.readFileSync(e,t)}var Qe,Ye,un=f(()=>{"use strict";l();Qe=T(require("fs"),1);Fi();k();Ye={name:Ai,displayName:Mi,description:Oi,parameters:ji,category:Ii,execute:ch}});var Li,qi,Ui,Wi,Gi,Bi=f(()=>{"use strict";l();Li="fs.write_file",qi="Write File",Ui="Write content to a file. Creates parent directories if they do not exist. Overwrites existing files.",Wi="filesystem",Gi={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to write"},content:{type:"string",description:"Content to write to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});async function ph(s){let e=s.path,t=s.content,r=s.encoding||"utf-8";if(h(`[fs.write-file] execute path="${e}" encoding=${r} content_len=${t?.length??0}`),!e)throw new Error("path is required");if(t==null)throw new Error("content is required");let o=Ji.dirname(e);return Ve.existsSync(o)||Ve.mkdirSync(o,{recursive:!0}),Ve.writeFileSync(e,t,r),`File written successfully: ${e} (${Buffer.byteLength(t,r)} bytes)`}var Ve,Ji,Xe,fn=f(()=>{"use strict";l();Ve=T(require("fs"),1),Ji=T(require("path"),1);Bi();k();Xe={name:Li,displayName:qi,description:Ui,parameters:Gi,category:Wi,execute:ph}});var Hi,zi,Ki,Qi,Yi,Vi=f(()=>{"use strict";l();Hi="fs.append_file",zi="Append File",Ki="Append content to the end of a file. Creates the file if it does not exist.",Qi="filesystem",Yi={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to append to"},content:{type:"string",description:"Content to append to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});async function mh(s){let e=s.path,t=s.content,r=s.encoding||"utf-8";if(!e)throw new Error("path is required");if(t==null)throw new Error("content is required");let o=Xi.dirname(e);return Ze.existsSync(o)||Ze.mkdirSync(o,{recursive:!0}),Ze.appendFileSync(e,t,r),`Content appended to: ${e} (${Buffer.byteLength(t,r)} bytes appended)`}var Ze,Xi,et,gn=f(()=>{"use strict";l();Ze=T(require("fs"),1),Xi=T(require("path"),1);Vi();et={name:Hi,displayName:zi,description:Ki,parameters:Yi,category:Qi,execute:mh}});var Zi,ea,ta,oa,ra,na=f(()=>{"use strict";l();Zi="fs.delete_file",ea="Delete File",ta="Delete a file at the given path. Does not delete directories.",oa="filesystem",ra={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to delete"}},required:["path"]}});async function dh(s){let e=s.path;if(h(`[fs.delete-file] execute path="${e}"`),!e)throw new Error("path is required");if(!tt.existsSync(e))throw new Error(`File not found: ${e}`);if(tt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}. Use a different tool to remove directories.`);return tt.unlinkSync(e),`File deleted successfully: ${e}`}var tt,ot,hn=f(()=>{"use strict";l();tt=T(require("fs"),1);na();k();ot={name:Zi,displayName:ea,description:ta,parameters:ra,category:oa,execute:dh}});var sa,ia,aa,la,ca,pa=f(()=>{"use strict";l();sa="fs.exists",ia="Exists",aa="Check if a file or directory exists at the given path. Returns true or false.",la="filesystem",ca={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to check"}},required:["path"]}});async function uh(s){let e=s.path;if(!e)throw new Error("path is required");let t=ma.existsSync(e);return JSON.stringify({exists:t,path:e})}var ma,rt,yn=f(()=>{"use strict";l();ma=T(require("fs"),1);pa();rt={name:sa,displayName:ia,description:aa,parameters:ca,category:la,execute:uh}});var da,ua,fa,ga,ha,ya=f(()=>{"use strict";l();da="fs.stat",ua="Stat",fa="Get file or directory information including size, type, and modification date.",ga="filesystem",ha={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to get info for"}},required:["path"]}});async function fh(s){let e=s.path;if(!e)throw new Error("path is required");if(!Zo.existsSync(e))throw new Error(`Path not found: ${e}`);let t=Zo.statSync(e);return JSON.stringify({path:e,type:t.isDirectory()?"directory":t.isFile()?"file":"other",size:t.size,created:t.birthtime.toISOString(),modified:t.mtime.toISOString(),accessed:t.atime.toISOString(),permissions:t.mode.toString(8)})}var Zo,nt,wn=f(()=>{"use strict";l();Zo=T(require("fs"),1);ya();nt={name:da,displayName:ua,description:fa,parameters:ha,category:ga,execute:fh}});var wa,ba,xa,Ta,Pa,Ca=f(()=>{"use strict";l();wa="fs.list_dir",ba="List Directory",xa="List files and directories at the given path. Optionally recurse into subdirectories.",Ta="filesystem",Pa={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to list"},recursive:{type:"boolean",description:"Whether to list recursively (default: false)",default:!1}},required:["path"]}});function Sa(s,e,t,r=""){let o=Oe.readdirSync(s,{withFileTypes:!0});for(let n of o){let a=va.join(s,n.name),i=r?`${r}/${n.name}`:n.name;if(n.isDirectory())t.push({name:i,type:"directory",size:0}),e&&Sa(a,!0,t,i);else if(n.isFile()){let c=Oe.statSync(a);t.push({name:i,type:"file",size:c.size})}}}async function gh(s){let e=s.path,t=s.recursive===!0;if(!e)throw new Error("path is required");if(!Oe.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Oe.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let o=[];return Sa(e,t,o),JSON.stringify(o,null,2)}var Oe,va,st,bn=f(()=>{"use strict";l();Oe=T(require("fs"),1),va=T(require("path"),1);Ca();st={name:wa,displayName:ba,description:xa,parameters:Pa,category:Ta,execute:gh}});var $a,_a,ka,Ra,Ea,Da=f(()=>{"use strict";l();$a="fs.create_dir",_a="Create Directory",ka="Create a directory at the given path. Creates parent directories recursively if they do not exist.",Ra="filesystem",Ea={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to create"},recursive:{type:"boolean",description:"Create parent directories if they do not exist (default: true)",default:!0}},required:["path"]}});async function hh(s){let e=s.path,t=s.recursive!==!1;if(!e)throw new Error("path is required");if(it.existsSync(e)){if(it.statSync(e).isDirectory())return`Directory already exists: ${e}`;throw new Error(`Path exists but is not a directory: ${e}`)}return it.mkdirSync(e,{recursive:t}),`Directory created: ${e}`}var it,at,xn=f(()=>{"use strict";l();it=T(require("fs"),1);Da();at={name:$a,displayName:_a,description:ka,parameters:Ea,category:Ra,execute:hh}});var Na,Aa,Ma,Oa,Ia,ja=f(()=>{"use strict";l();Na="fs.move",Aa="Move",Ma="Move or rename a file or directory from one path to another.",Oa="filesystem",Ia={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});async function yh(s){let e=s.path,t=s.new_path;if(!e)throw new Error("path is required");if(!t)throw new Error("new_path is required");if(!Ie.existsSync(e))throw new Error(`Source not found: ${e}`);let r=Fa.dirname(t);return Ie.existsSync(r)||Ie.mkdirSync(r,{recursive:!0}),Ie.renameSync(e,t),`Moved: ${e} \u2192 ${t}`}var Ie,Fa,lt,Tn=f(()=>{"use strict";l();Ie=T(require("fs"),1),Fa=T(require("path"),1);ja();lt={name:Na,displayName:Aa,description:Ma,parameters:Ia,category:Oa,execute:yh}});var La,qa,Ua,Wa,Ga,Ba=f(()=>{"use strict";l();La="fs.copy",qa="Copy",Ua="Copy a file or directory from one path to another. Recursively copies directories.",Wa="filesystem",Ga={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});function Ja(s,e){if(Q.statSync(s).isDirectory()){Q.existsSync(e)||Q.mkdirSync(e,{recursive:!0});let r=Q.readdirSync(s);for(let o of r)Ja(lo.join(s,o),lo.join(e,o))}else Q.copyFileSync(s,e)}async function wh(s){let e=s.path,t=s.new_path;if(!e)throw new Error("path is required");if(!t)throw new Error("new_path is required");if(!Q.existsSync(e))throw new Error(`Source not found: ${e}`);let r=lo.dirname(t);return Q.existsSync(r)||Q.mkdirSync(r,{recursive:!0}),Ja(e,t),`Copied ${Q.statSync(e).isDirectory()?"directory":"file"}: ${e} \u2192 ${t}`}var Q,lo,ct,Pn=f(()=>{"use strict";l();Q=T(require("fs"),1),lo=T(require("path"),1);Ba();ct={name:La,displayName:qa,description:Ua,parameters:Ga,category:Wa,execute:wh}});var Ha,za,Ka,Qa,Ya,Va=f(()=>{"use strict";l();Ha="fs.read_file_range",za="Read File Range",Ka="Read a specific range of lines from a file. Useful for reading portions of large files without loading the entire content.",Qa="filesystem",Ya={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},start_line:{type:"integer",description:"Start line number (1-indexed)"},end_line:{type:"integer",description:"End line number (1-indexed, inclusive)"}},required:["path","start_line","end_line"]}});async function bh(s){let e=s.path,t=s.start_line,r=s.end_line;if(!e)throw new Error("path is required");if(t==null)throw new Error("start_line is required");if(r==null)throw new Error("end_line is required");if(t<1)throw new Error("start_line must be >= 1");if(r<t)throw new Error("end_line must be >= start_line");if(!pt.existsSync(e))throw new Error(`File not found: ${e}`);if(pt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let a=pt.readFileSync(e,"utf-8").split(`
|
|
3
|
+
`),i=a.length,c=Math.min(t,i),p=Math.min(r,i),u=a.slice(c-1,p).map((g,w)=>`${c+w}: ${g}`).join(`
|
|
4
4
|
`);return`Lines ${c}-${p} of ${i} total:
|
|
5
|
-
${u}`}var
|
|
6
|
-
`);for(let a=0;a<n.length&&t.length<
|
|
7
|
-
(results capped at ${
|
|
8
|
-
`)}var
|
|
5
|
+
${u}`}var pt,mt,Cn=f(()=>{"use strict";l();pt=T(require("fs"),1);Va();mt={name:Ha,displayName:za,description:Ka,parameters:Ya,category:Qa,execute:bh}});var Xa,Za,el,tl,ol,rl=f(()=>{"use strict";l();Xa="fs.search",Za="Search",el="Search for text in files within a directory. Returns matching lines with file paths and line numbers.",tl="filesystem",ol={type:"object",properties:{path:{type:"string",description:"Directory path to search in"},query:{type:"string",description:"Text or pattern to search for"},recursive:{type:"boolean",description:"Search recursively in subdirectories (default: true)",default:!0},max_results:{type:"integer",description:"Maximum number of matching lines to return (default: 50)",default:50},regex:{type:"boolean",description:"Treat query as a regular expression (default: false)",default:!1},case_sensitive:{type:"boolean",description:"Perform case-sensitive search. If false, search is case-insensitive (default: false)",default:!1}},required:["path","query"]}});function xh(s,e,t,r){try{let n=Te.readFileSync(s,"utf-8").split(`
|
|
6
|
+
`);for(let a=0;a<n.length&&t.length<r;a++){let i=n[a];(typeof e=="string"?i.includes(e):e.test(i))&&t.push({file:s,line:a+1,content:i.trim()})}}catch{}}function sl(s,e,t,r,o){let n=Te.readdirSync(s,{withFileTypes:!0});for(let a of n){if(r.length>=o)break;let i=nl.join(s,a.name);a.isDirectory()&&t?sl(i,e,!0,r,o):a.isFile()&&xh(i,e,r,o)}}async function Th(s){let e=s.path,t=s.query,r=s.recursive!==!1,o=s.max_results||50,n=!!s.regex,a=!!s.case_sensitive;if(h(`[fs.search] execute path="${e}" query="${t}" recursive=${r} regex=${n} caseSensitive=${a}`),!e)throw new Error("path is required");if(!t)throw new Error("query is required");let i=t;if(n||!a){let u=t;n||(u=u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));let g=a?"":"i";i=new RegExp(u,g)}if(!Te.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Te.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let p=[];if(sl(e,i,r,p,o),p.length===0)return`No matches found for "${t}" in ${e}`;let m=p.length>=o?`
|
|
7
|
+
(results capped at ${o})`:"";return JSON.stringify(p,null,2)+m}var Te,nl,dt,vn=f(()=>{"use strict";l();Te=T(require("fs"),1),nl=T(require("path"),1);rl();k();dt={name:Xa,displayName:Za,description:el,parameters:ol,category:tl,execute:Th}});var il,al,ll,cl,pl,ml=f(()=>{"use strict";l();il="fs.replace_in_file",al="Replace In File",ll="Find and replace text in a file. Returns the number of replacements made.",cl="filesystem",pl={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path"},search:{type:"string",description:"Text to search for"},replace:{type:"string",description:"Text to replace with"}},required:["path","search","replace"]}});async function Ph(s){let e=s.path,t=s.search,r=s.replace;if(!e)throw new Error("path is required");if(!t)throw new Error("search is required");if(r==null)throw new Error("replace is required");if(!Pe.existsSync(e))throw new Error(`File not found: ${e}`);if(Pe.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let n=Pe.readFileSync(e,"utf-8"),a=0,i=0;for(;(i=n.indexOf(t,i))!==-1;)a++,i+=t.length;if(a===0)return`No occurrences of "${t}" found in ${e}`;let c=n.split(t).join(r);return Pe.writeFileSync(e,c,"utf-8"),`Replaced ${a} occurrence(s) in ${e}`}var Pe,ut,Sn=f(()=>{"use strict";l();Pe=T(require("fs"),1);ml();ut={name:il,displayName:al,description:ll,parameters:pl,category:cl,execute:Ph}});var dl,ul,fl,gl,hl,yl=f(()=>{"use strict";l();dl="fs.tree",ul="Tree",fl="Get a tree representation of a directory structure. Useful for understanding project layout at a glance.",gl="filesystem",hl={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path"},depth:{type:"integer",description:"Maximum depth to traverse (default: 3)",default:3}},required:["path"]}});function wl(s,e,t,r,o){if(t>r)return;let a=ft.readdirSync(s,{withFileTypes:!0}).sort((i,c)=>i.isDirectory()&&!c.isDirectory()?-1:!i.isDirectory()&&c.isDirectory()?1:i.name.localeCompare(c.name));for(let i=0;i<a.length;i++){let c=a[i],p=i===a.length-1,m=p?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",u=p?" ":"\u2502 ";c.isDirectory()?(o.push(`${e}${m}${c.name}/`),wl(er.join(s,c.name),e+u,t+1,r,o)):o.push(`${e}${m}${c.name}`)}}async function Ch(s){let e=s.path,t=s.depth||3;if(!e)throw new Error("path is required");if(!ft.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!ft.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let n=[`${er.basename(e)}/`];return wl(e,"",1,t,n),n.join(`
|
|
8
|
+
`)}var ft,er,gt,$n=f(()=>{"use strict";l();ft=T(require("fs"),1),er=T(require("path"),1);yl();gt={name:dl,displayName:ul,description:fl,parameters:hl,category:gl,execute:Ch}});var bl,xl,Tl,Pl,Cl,vl=f(()=>{"use strict";l();bl="fs.glob",xl="Glob Pattern Match",Tl='Find files matching glob patterns (e.g., "**/*.ts", "src/**/*.test.js")',Pl="filesystem",Cl={type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files (e.g., "**/*.ts", "src/**/*.json")'},cwd:{type:"string",description:"Root directory to search from (defaults to current working directory)"},ignore:{type:"array",items:{type:"string"},description:'Patterns to ignore (e.g., ["node_modules/**", "dist/**"])'},onlyFiles:{type:"boolean",description:"Return only files, not directories (default: true)"},onlyDirectories:{type:"boolean",description:"Return only directories, not files (default: false)"},absolute:{type:"boolean",description:"Return absolute paths instead of relative (default: false)"}},required:["pattern"]}});async function vh(s){let e=s.pattern,t=s.cwd,r=s.ignore,o=s.onlyFiles!==!1,n=s.onlyDirectories===!0,a=s.absolute===!0;if(!e)throw new Error("pattern is required");let i=e.replace(/\\/g,"/");try{let c=await(0,Sl.default)(i,{cwd:t||process.cwd(),ignore:r||["node_modules/**",".git/**"],onlyFiles:o,onlyDirectories:n,absolute:a,dot:!0});return JSON.stringify({pattern:e,files:c,count:c.length},null,2)}catch(c){throw new Error(`Failed to glob pattern "${e}": ${c.message}`)}}var Sl,tr,_n=f(()=>{"use strict";l();Sl=T(require("fast-glob"),1);vl();tr={name:bl,displayName:xl,description:Tl,parameters:Cl,category:Pl,execute:vh}});var $l,_l,kl,Rl,El,Dl=f(()=>{"use strict";l();$l="fs.delete_dir",_l="Delete Directory",kl="Delete a directory and all its contents recursively",Rl="filesystem",El={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to the directory to delete"},force:{type:"boolean",description:"Force deletion even if directory is not empty (default: true)"}},required:["path"]}});async function Sh(s){let e=s.path,t=s.force!==!1;if(!e)throw new Error("path is required");if(!(0,or.existsSync)(e))throw new Error(`Directory does not exist: ${e}`);if(!(0,or.statSync)(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);try{return await(0,Nl.rm)(e,{recursive:!0,force:t}),`Directory deleted successfully: ${e}`}catch(o){throw new Error(`Failed to delete directory "${e}": ${o.message}`)}}var Nl,or,rr,kn=f(()=>{"use strict";l();Nl=require("fs/promises"),or=require("fs");Dl();rr={name:$l,displayName:_l,description:kl,parameters:El,category:Rl,execute:Sh}});var Al,Ml,Ol,Il,jl,Fl=f(()=>{"use strict";l();Al="fs.batch_read",Ml="Batch Read Files",Ol="Read multiple files efficiently in one operation. Returns content for each file or error if read fails.",Il="filesystem",jl={type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Array of file paths to read"},encoding:{type:"string",description:"File encoding (default: utf-8)"},continueOnError:{type:"boolean",description:"Continue reading other files if one fails (default: true)"}},required:["paths"]}});async function $h(s){let e=s.paths,t=s.encoding||"utf-8",r=s.continueOnError!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("paths array is required and must not be empty");let o=[],n=0,a=0;for(let i of e)try{let c=await(0,Ll.readFile)(i,t);o.push({path:i,content:c,success:!0}),n++}catch(c){let p=c.message;if(o.push({path:i,error:p,success:!1}),a++,!r)throw new Error(`Failed to read file "${i}": ${p}`)}return JSON.stringify({total:e.length,success:n,failed:a,results:o},null,2)}var Ll,nr,Rn=f(()=>{"use strict";l();Ll=require("fs/promises");Fl();nr={name:Al,displayName:Ml,description:Ol,parameters:jl,category:Il,execute:$h}});var ql,Ul,Wl,Gl,Bl,Jl=f(()=>{"use strict";l();ql="fs.batch_write",Ul="Batch Write Files",Wl="Write multiple files atomically in one operation. If atomic mode is enabled, all writes succeed or all are rolled back on failure.",Gl="filesystem",Bl={type:"object",properties:{files:{type:"array",items:{type:"object",properties:{path:{type:"string"},content:{type:"string"}}},description:"Array of files to write, each with path and content"},encoding:{type:"string",description:"File encoding (default: utf-8)"},atomic:{type:"boolean",description:"Atomic mode: rollback all writes if any fails (default: true)"},createDirs:{type:"boolean",description:"Create parent directories if they don't exist (default: true)"}},required:["files"]}});async function _h(s){let e=s.files,t=s.encoding||"utf-8",r=s.atomic!==!1,o=s.createDirs!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("files array is required and must not be empty");for(let i of e)if(!i.path||i.content===void 0)throw new Error("Each file must have path and content properties");let n=[],a=[];try{for(let i of e){let c=(0,sr.resolve)(i.path);if(r){let p=(0,En.existsSync)(c),m={path:c,existed:p};p&&(m.originalContent=await(0,ue.readFile)(c,t)),n.push(m)}if(o){let p=(0,sr.dirname)(c);await(0,ue.mkdir)(p,{recursive:!0})}await(0,ue.writeFile)(c,i.content,t),a.push(c)}return JSON.stringify({success:!0,written:a.length,files:a},null,2)}catch(i){if(r&&n.length>0){for(let c of n)try{c.existed&&c.originalContent!==void 0?await(0,ue.writeFile)(c.path,c.originalContent,t):!c.existed&&(0,En.existsSync)(c.path)&&await(0,ue.unlink)(c.path)}catch{}throw new Error(`Batch write failed and rolled back: ${i.message}`)}throw new Error(`Batch write failed: ${i.message}`)}}var ue,sr,En,ir,Dn=f(()=>{"use strict";l();ue=require("fs/promises"),sr=require("path"),En=require("fs");Jl();ir={name:ql,displayName:Ul,description:Wl,parameters:Bl,category:Gl,execute:_h}});var Hl={};V(Hl,{fsAppendFileTool:()=>et,fsBatchReadTool:()=>nr,fsBatchWriteTool:()=>ir,fsCopyTool:()=>ct,fsCreateDirTool:()=>at,fsDeleteDirTool:()=>rr,fsDeleteFileTool:()=>ot,fsExistsTool:()=>rt,fsGlobTool:()=>tr,fsListDirTool:()=>st,fsMoveTool:()=>lt,fsReadFileRangeTool:()=>mt,fsReadFileTool:()=>Ye,fsReplaceInFileTool:()=>ut,fsSearchTool:()=>dt,fsStatTool:()=>nt,fsToolsProject:()=>Nn,fsTreeTool:()=>gt,fsWriteFileTool:()=>Xe});var Nn,An=f(()=>{"use strict";l();un();fn();gn();hn();yn();wn();bn();xn();Tn();Pn();Cn();vn();Sn();$n();_n();kn();Rn();Dn();un();fn();gn();hn();yn();wn();bn();xn();Tn();Pn();Cn();vn();Sn();$n();_n();kn();Rn();Dn();Nn={manifest:{key:"fs",name:"fs-tools",displayName:"File System",version:"1.0.0",description:"File system tools for reading, writing, searching, and managing files and directories.",author:"Sajeer",tools:["fs.read_file","fs.write_file","fs.append_file","fs.delete_file","fs.exists","fs.stat","fs.list_dir","fs.create_dir","fs.move","fs.copy","fs.read_file_range","fs.search","fs.replace_in_file","fs.tree","fs.glob","fs.delete_dir","fs.batch_read","fs.batch_write"],category:"filesystem"},tools:[Ye,Xe,et,ot,rt,nt,st,at,lt,ct,mt,dt,ut,gt,tr,rr,nr,ir],dependencies:{"fast-glob":"^3.3.2"}}});var zl,Kl,Ql,Yl,Vl,Xl=f(()=>{"use strict";l();zl="exec.run",Kl="Run",Ql="Execute a command directly (without shell) and return its output. Use exec.run_shell for pipes, redirects, or shell features.",Yl="execution",Vl={type:"object",properties:{command:{type:"string",description:"The command to execute"},cwd:{type:"string",description:"Working directory for the command (optional)"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["command"]}});async function kh(s){let e=s.command,t=s.cwd,r=s.timeout||3e4;if(!e)throw new Error("command is required");h(`[exec.run] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${r}ms`);try{return(0,Zl.execSync)(e,{cwd:t,timeout:r,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"]})||"(command completed with no output)"}catch(o){let n=o.stdout||"",a=o.stderr||"";return`Command failed (exit code ${o.status??"unknown"}):
|
|
9
9
|
STDOUT:
|
|
10
10
|
${n}
|
|
11
11
|
STDERR:
|
|
12
|
-
${a}`}}var
|
|
12
|
+
${a}`}}var Zl,ht,Mn=f(()=>{"use strict";l();Zl=require("child_process");Xl();k();ht={name:zl,displayName:Kl,description:Ql,parameters:Vl,category:Yl,execute:kh}});var ec,tc,oc,rc,nc,sc=f(()=>{"use strict";l();ec="exec.run_shell",tc="Run Shell",oc="Execute a command through the system shell. Supports pipes, redirects, environment variable expansion, and other shell features.",rc="execution",nc={type:"object",properties:{command:{type:"string",description:"The shell command to execute (supports pipes, redirects, etc.)"},cwd:{type:"string",description:"Working directory for the command (optional)"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["command"]}});function Rh(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function Eh(s){let e=s.command,t=s.cwd,r=s.timeout||3e4;if(!e)throw new Error("command is required");h(`[exec.run-shell] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${r}ms`);try{return(0,ic.execSync)(e,{cwd:t,timeout:r,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],shell:Rh()})||"(command completed with no output)"}catch(o){let n=o.stdout||"",a=o.stderr||"";return`Command failed (exit code ${o.status??"unknown"}):
|
|
13
13
|
STDOUT:
|
|
14
14
|
${n}
|
|
15
15
|
STDERR:
|
|
16
|
-
${a}`}}var
|
|
17
|
-
`);if(a.length<2)return n;let i=a[1].split(/\s+/);return JSON.stringify({path:t,filesystem:i[0]||"unknown",size:i[1]||"unknown",used:i[2]||"unknown",available:i[3]||"unknown",usePercent:i[4]||"unknown",mountedOn:i[5]||"unknown"},null,2)}catch(n){throw new Error(`Failed to get disk usage for ${t}: ${
|
|
18
|
-
${
|
|
16
|
+
${a}`}}var ic,yt,On=f(()=>{"use strict";l();ic=require("child_process");sc();k();yt={name:ec,displayName:tc,description:oc,parameters:nc,category:rc,execute:Eh}});function ac(s,e,t){let r=`proc_${Dh++}`,o={id:r,command:s,cwd:e,process:t,startedAt:new Date().toISOString(),stdout:"",stderr:""};return t.stdout?.on("data",n=>{o.stdout+=n.toString(),o.stdout.length>1e6&&(o.stdout=o.stdout.slice(-5e5))}),t.stderr?.on("data",n=>{o.stderr+=n.toString(),o.stderr.length>1e6&&(o.stderr=o.stderr.slice(-5e5))}),t.on("exit",()=>{}),ar.set(r,o),r}function lr(s){return ar.get(s)}function lc(s){let e=ar.get(s);if(!e)return!1;let t=e.process.exitCode===null;return t&&e.process.kill("SIGTERM"),t}function cc(){return Array.from(ar.values()).map(s=>({id:s.id,command:s.command,cwd:s.cwd,startedAt:s.startedAt,alive:s.process.exitCode===null,pid:s.process.pid}))}var ar,Dh,co=f(()=>{"use strict";l();ar=new Map,Dh=1});var pc,mc,dc,uc,fc,gc=f(()=>{"use strict";l();pc="exec.run_background",mc="Run Background",dc="Start a command as a background process. Returns a process ID that can be used with exec.read_output, exec.kill, and exec.list_processes.",uc="execution",fc={type:"object",properties:{command:{type:"string",description:"The command to run in the background"},cwd:{type:"string",description:"Working directory for the command (optional)"}},required:["command"]}});async function Nh(s){let e=s.command,t=s.cwd;if(!e)throw new Error("command is required");if(h(`[exec.run-background] execute command="${e.substring(0,100)}" cwd=${t??"default"}`),!e)throw new Error("command is required");let r=(0,hc.spawn)(e,[],{cwd:t,shell:!0,stdio:["ignore","pipe","pipe"],detached:!1}),o=ac(e,t,r);return JSON.stringify({id:o,pid:r.pid,command:e,message:`Background process started. Use exec.read_output("${o}") to read output, exec.kill("${o}") to stop.`})}var hc,wt,In=f(()=>{"use strict";l();hc=require("child_process");co();gc();k();wt={name:pc,displayName:mc,description:dc,parameters:fc,category:uc,execute:Nh}});var yc,wc,bc,xc,Tc,Pc=f(()=>{"use strict";l();yc="exec.read_output",wc="Read Output",bc="Read stdout and stderr from a background process started with exec.run_background.",xc="execution",Tc={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function Ah(s){let e=s.process_id;if(!e)throw new Error("process_id is required");let t=lr(e);if(!t)throw new Error(`Process not found: ${e}`);let r=t.process.exitCode===null;return JSON.stringify({id:t.id,alive:r,exitCode:t.process.exitCode,stdout:t.stdout,stderr:t.stderr})}var bt,jn=f(()=>{"use strict";l();co();Pc();bt={name:yc,displayName:wc,description:bc,parameters:Tc,category:xc,execute:Ah}});var Cc,vc,Sc,$c,_c,kc=f(()=>{"use strict";l();Cc="exec.kill",vc="Kill",Sc="Kill a background process started with exec.run_background.",$c="execution",_c={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function Mh(s){let e=s.process_id;if(!e)throw new Error("process_id is required");let t=lr(e);if(!t)throw new Error(`Process not found: ${e}`);return lc(e)?`Process ${e} (${t.command}) killed successfully.`:`Process ${e} (${t.command}) was already terminated (exit code: ${t.process.exitCode}).`}var xt,Fn=f(()=>{"use strict";l();co();kc();xt={name:Cc,displayName:vc,description:Sc,parameters:_c,category:$c,execute:Mh}});var Rc,Ec,Dc,Nc,Ac,Mc=f(()=>{"use strict";l();Rc="exec.list_processes",Ec="List Processes",Dc="List all managed background processes started with exec.run_background, including their status.",Nc="execution",Ac={type:"object",properties:{}}});async function Oh(s){let e=cc();return e.length===0?"No managed background processes.":JSON.stringify(e,null,2)}var Tt,Ln=f(()=>{"use strict";l();co();Mc();Tt={name:Rc,displayName:Ec,description:Dc,parameters:Ac,category:Nc,execute:Oh}});var Oc={};V(Oc,{execKillTool:()=>xt,execListProcessesTool:()=>Tt,execReadOutputTool:()=>bt,execRunBackgroundTool:()=>wt,execRunShellTool:()=>yt,execRunTool:()=>ht,execToolsProject:()=>qn});var qn,Un=f(()=>{"use strict";l();Mn();On();In();jn();Fn();Ln();Mn();On();In();jn();Fn();Ln();qn={manifest:{key:"exec",name:"exec-tools",displayName:"Execution",version:"1.0.0",description:"Code execution tools for running commands, managing background processes, and automation.",author:"Sajeer",tools:["exec.run","exec.run_shell","exec.run_background","exec.read_output","exec.kill","exec.list_processes"],category:"execution"},tools:[ht,yt,wt,bt,xt,Tt],dependencies:{}}});var Ic,jc,Fc,Lc,qc,Uc=f(()=>{"use strict";l();Ic="system.info",jc="Info",Fc="Get system information including OS, CPU, memory, and architecture.",Lc="system",qc={type:"object",properties:{}}});async function Ih(s){return h("[system.info] execute"),JSON.stringify({platform:A.platform(),arch:A.arch(),release:A.release(),hostname:A.hostname(),uptime:A.uptime(),cpus:{model:A.cpus()[0]?.model||"unknown",count:A.cpus().length},memory:{total:A.totalmem(),free:A.freemem(),used:A.totalmem()-A.freemem()},homedir:A.homedir(),tmpdir:A.tmpdir(),nodeVersion:process.version},null,2)}var A,Pt,Wn=f(()=>{"use strict";l();A=T(require("os"),1);Uc();k();Pt={name:Ic,displayName:jc,description:Fc,parameters:qc,category:Lc,execute:Ih}});var Wc,Gc,Bc,Jc,Hc,zc=f(()=>{"use strict";l();Wc="system.env",Gc="Environment",Bc="Get environment variable(s). If key is provided, returns that specific variable. Otherwise returns all environment variables.",Jc="system",Hc={type:"object",properties:{key:{type:"string",description:"Specific environment variable name to get (optional, returns all if omitted)"}}}});async function jh(s){let e=s.key;if(h(`[system.env] execute key=${e??"all"}`),e){let o=process.env[e];return o===void 0?`Environment variable "${e}" is not set.`:JSON.stringify({[e]:o})}let t={},r=Object.keys(process.env).sort();for(let o of r)process.env[o]!==void 0&&(t[o]=process.env[o]);return JSON.stringify(t,null,2)}var Ct,Gn=f(()=>{"use strict";l();zc();k();Ct={name:Wc,displayName:Gc,description:Bc,parameters:Hc,category:Jc,execute:jh}});var Kc,Qc,Yc,Vc,Xc,Zc=f(()=>{"use strict";l();Kc="system.set_env",Qc="Set Environment",Yc="Set an environment variable for the current session. Does not persist across restarts.",Vc="system",Xc={type:"object",properties:{key:{type:"string",description:"Environment variable name"},value:{type:"string",description:"Value to set"}},required:["key","value"]}});async function Fh(s){let e=s.key,t=s.value;if(!e)throw new Error("key is required");if(t==null)throw new Error("value is required");let r=process.env[e];return process.env[e]=t,r!==void 0?`Environment variable "${e}" updated (was: "${r}", now: "${t}")`:`Environment variable "${e}" set to "${t}"`}var vt,Bn=f(()=>{"use strict";l();Zc();vt={name:Kc,displayName:Qc,description:Yc,parameters:Xc,category:Vc,execute:Fh}});var ep,tp,op,rp,np,sp=f(()=>{"use strict";l();ep="system.cwd",tp="Current Directory",op="Get the current working directory of the process.",rp="system",np={type:"object",properties:{}}});async function Lh(s){return h("[system.cwd] execute"),JSON.stringify({cwd:process.cwd()})}var St,Jn=f(()=>{"use strict";l();sp();k();St={name:ep,displayName:tp,description:op,parameters:np,category:rp,execute:Lh}});var ip,ap,lp,cp,pp,mp=f(()=>{"use strict";l();ip="system.disk_usage",ap="Disk Usage",lp="Get disk usage information for a given path or the root filesystem.",cp="system",pp={type:"object",properties:{path:{type:"string",description:"Path to check disk usage for (default: /)",default:"/"}}}});function Hn(s){let e=["B","KB","MB","GB","TB","PB"],t=s,r=0;for(;t>=1024&&r<e.length-1;)t/=1024,r++;return`${t.toFixed(1)}${e[r]}`}async function qh(s){let t=s.path||(process.platform==="win32"?up.tmpdir():"/");t=cr.resolve(t);let r=process.platform==="win32";try{let o=dp.statfsSync(t),n=BigInt(o.blocks)*BigInt(o.bsize),a=BigInt(o.bavail)*BigInt(o.bsize),i=BigInt(o.bfree)*BigInt(o.bsize),c=n-i,p=n>0?Number(c*BigInt(100)/n):0;return JSON.stringify({path:t,filesystem:"statfs",size:Hn(Number(n)),used:Hn(Number(c)),available:Hn(Number(a)),usePercent:`${p}%`,mountedOn:t},null,2)}catch(o){try{if(r){let c=cr.parse(t).root.replace(/\\$/,"")||"C:",p=`Get-PSDrive -Name ${c.replace(":","")} | Select-Object @{n='Drive';e={$_.Name+':'}},@{n='Used';e={$_.Used}},@{n='Free';e={$_.Free}},@{n='Total';e={$_.Used+$_.Free}} | ConvertTo-Json`,m=(0,zn.execSync)(p,{encoding:"utf-8",timeout:5e3,shell:"powershell.exe"}),u=JSON.parse(m.trim()),g=u.Total||0,w=u.Free||0,y=u.Used||0,b=g>0?Math.round(y/g*100):0;return JSON.stringify({path:t,filesystem:u.Name||"NTFS",size:`${(g/1024**3).toFixed(1)}G`,used:`${(y/1024**3).toFixed(1)}G`,available:`${(w/1024**3).toFixed(1)}G`,usePercent:`${b}%`,mountedOn:u.Drive||`${c}`},null,2)}let n=(0,zn.execSync)(`df -h "${t}"`,{encoding:"utf-8",timeout:5e3}),a=n.trim().split(`
|
|
17
|
+
`);if(a.length<2)return n;let i=a[1].split(/\s+/);return JSON.stringify({path:t,filesystem:i[0]||"unknown",size:i[1]||"unknown",used:i[2]||"unknown",available:i[3]||"unknown",usePercent:i[4]||"unknown",mountedOn:i[5]||"unknown"},null,2)}catch(n){throw new Error(`Failed to get disk usage for ${t}: ${o?.message||o}; fallback error: ${n.message}`)}}}var dp,up,cr,zn,$t,Kn=f(()=>{"use strict";l();dp=T(require("fs"),1),up=T(require("os"),1),cr=T(require("path"),1),zn=require("child_process");mp();$t={name:ip,displayName:ap,description:lp,parameters:pp,category:cp,execute:qh}});var fp={};V(fp,{systemCwdTool:()=>St,systemDiskUsageTool:()=>$t,systemEnvTool:()=>Ct,systemInfoTool:()=>Pt,systemSetEnvTool:()=>vt,systemToolsProject:()=>Qn});var Qn,Yn=f(()=>{"use strict";l();Wn();Gn();Bn();Jn();Kn();Wn();Gn();Bn();Jn();Kn();Qn={manifest:{key:"system",name:"system-tools",displayName:"System",version:"1.0.0",description:"System tools for querying OS info, environment variables, working directory, and disk usage.",author:"Sajeer",tools:["system.info","system.env","system.set_env","system.cwd","system.disk_usage"],category:"system"},tools:[Pt,Ct,vt,St,$t],dependencies:{}}});var gp,hp,yp,wp,bp,xp=f(()=>{"use strict";l();gp="http.get",hp="GET",yp="Make an HTTP GET request to a URL and return the response body.",wp="network",bp={type:"object",properties:{url:{type:"string",description:"The URL to request"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url"]}});async function Uh(s){let e=s.url,t=s.headers;if(h(`[http.get] execute url="${e}"`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let r=await fetch(e,{method:"GET",headers:t||{}}),o=await r.text(),n=`HTTP ${r.status} ${r.statusText}`;return r.ok?o.length>Tp?`${n}
|
|
18
|
+
${o.substring(0,Tp)}
|
|
19
19
|
|
|
20
|
-
... (truncated, total ${
|
|
21
|
-
${
|
|
22
|
-
${
|
|
23
|
-
${n.substring(0,
|
|
20
|
+
... (truncated, total ${o.length} characters)`:`${n}
|
|
21
|
+
${o}`:`${n}
|
|
22
|
+
${o}`}var Tp,_t,Vn=f(()=>{"use strict";l();xp();k();Tp=1e5;_t={name:gp,displayName:hp,description:yp,parameters:bp,category:wp,execute:Uh}});var Pp,Cp,vp,Sp,$p,_p=f(()=>{"use strict";l();Pp="http.post",Cp="POST",vp="Make an HTTP POST request to a URL with an optional body and return the response.",Sp="network",$p={type:"object",properties:{url:{type:"string",description:"The URL to request"},body:{type:"string",description:"Request body (JSON string or plain text)"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url"]}});async function Wh(s){let e=s.url,t=s.body,r=s.headers||{};if(h(`[http.post] execute url="${e}" body_len=${t?.length??0}`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");if(t&&!r["Content-Type"]&&!r["content-type"])try{JSON.parse(t),r["Content-Type"]="application/json"}catch{r["Content-Type"]="text/plain"}let o=await fetch(e,{method:"POST",headers:r,body:t||void 0}),n=await o.text(),a=`HTTP ${o.status} ${o.statusText}`;return n.length>kp?`${a}
|
|
23
|
+
${n.substring(0,kp)}
|
|
24
24
|
|
|
25
25
|
... (truncated, total ${n.length} characters)`:`${a}
|
|
26
|
-
${n}`}var
|
|
27
|
-
${n.substring(0,
|
|
26
|
+
${n}`}var kp,kt,Xn=f(()=>{"use strict";l();_p();k();kp=1e5;kt={name:Pp,displayName:Cp,description:vp,parameters:$p,category:Sp,execute:Wh}});var Rp,Ep,Dp,Np,Ap,Mp=f(()=>{"use strict";l();Rp="http.put",Ep="PUT",Dp="Make an HTTP PUT request to a URL with an optional body and return the response.",Np="network",Ap={type:"object",properties:{url:{type:"string",description:"The URL to request"},body:{type:"string",description:"Request body (JSON string or plain text)"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url"]}});async function Gh(s){let e=s.url,t=s.body,r=s.headers||{};if(h(`[http.put] execute url="${e}" body_len=${t?.length??0}`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");if(t&&!r["Content-Type"]&&!r["content-type"])try{JSON.parse(t),r["Content-Type"]="application/json"}catch{r["Content-Type"]="text/plain"}let o=await fetch(e,{method:"PUT",headers:r,body:t||void 0}),n=await o.text(),a=`HTTP ${o.status} ${o.statusText}`;return n.length>Op?`${a}
|
|
27
|
+
${n.substring(0,Op)}
|
|
28
28
|
|
|
29
29
|
... (truncated)`:`${a}
|
|
30
|
-
${n}`}var
|
|
31
|
-
${
|
|
30
|
+
${n}`}var Op,Rt,Zn=f(()=>{"use strict";l();Mp();k();Op=1e5;Rt={name:Rp,displayName:Ep,description:Dp,parameters:Ap,category:Np,execute:Gh}});var Ip,jp,Fp,Lp,qp,Up=f(()=>{"use strict";l();Ip="http.delete",jp="DELETE",Fp="Make an HTTP DELETE request to a URL and return the response.",Lp="network",qp={type:"object",properties:{url:{type:"string",description:"The URL to request"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url"]}});async function Bh(s){let e=s.url,t=s.headers;if(h(`[http.delete] execute url="${e}"`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let r=await fetch(e,{method:"DELETE",headers:t||{}}),o=await r.text(),n=`HTTP ${r.status} ${r.statusText}`;return o.length>Wp?`${n}
|
|
31
|
+
${o.substring(0,Wp)}
|
|
32
32
|
|
|
33
33
|
... (truncated)`:`${n}
|
|
34
|
-
${
|
|
34
|
+
${o}`}var Wp,Et,es=f(()=>{"use strict";l();Up();k();Wp=1e5;Et={name:Ip,displayName:jp,description:Fp,parameters:qp,category:Lp,execute:Bh}});var Gp,Bp,Jp,Hp,zp,Kp=f(()=>{"use strict";l();Gp="http.download",Bp="Download",Jp="Download a file from a URL and save it to a local path.",Hp="network",zp={type:"object",properties:{url:{type:"string",description:"The URL to download from"},path:{type:"string",description:"Local file path to save the downloaded file"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url","path"]}});async function Jh(s){let e=s.url,t=s.path,r=s.headers;if(h(`[http.download] execute url="${e}" path="${t}"`),!e)throw new Error("url is required");if(!t)throw new Error("path is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=await fetch(e,{method:"GET",headers:r||{}});if(!o.ok)throw new Error(`Download failed: HTTP ${o.status} ${o.statusText}`);let n=Buffer.from(await o.arrayBuffer()),a=Qp.dirname(t);return Dt.existsSync(a)||Dt.mkdirSync(a,{recursive:!0}),Dt.writeFileSync(t,n),`Downloaded ${e} \u2192 ${t} (${n.length} bytes)`}var Dt,Qp,Nt,ts=f(()=>{"use strict";l();Dt=T(require("fs"),1),Qp=T(require("path"),1);Kp();k();Nt={name:Gp,displayName:Bp,description:Jp,parameters:zp,category:Hp,execute:Jh}});var Yp={};V(Yp,{httpDeleteTool:()=>Et,httpDownloadTool:()=>Nt,httpGetTool:()=>_t,httpPostTool:()=>kt,httpPutTool:()=>Rt,httpToolsProject:()=>os});var os,rs=f(()=>{"use strict";l();Vn();Xn();Zn();es();ts();Vn();Xn();Zn();es();ts();os={manifest:{key:"http",name:"http-tools",displayName:"HTTP",version:"1.0.0",description:"HTTP tools for making GET, POST, PUT, DELETE requests and downloading files.",author:"Sajeer",tools:["http.get","http.post","http.put","http.delete","http.download"],category:"network"},tools:[_t,kt,Rt,Et,Nt],dependencies:{}}});var Vp,Xp,Zp,em,tm,om=f(()=>{"use strict";l();Vp="web.fetch",Xp="Fetch",Zp="Fetch content from a URL. Supports multiple extraction modes: full (raw HTML up to 15K chars), structured (title, excerpt, key points), or minimal (title + snippet).",em="network",tm={type:"object",properties:{url:{type:"string",description:"The URL to fetch"},extractionMode:{type:"string",description:'Content extraction mode: "full" (raw HTML, 15K limit), "structured" (title, excerpt, key points, main content), or "minimal" (title + 500 char snippet). Default: "full"',enum:["full","structured","minimal"],default:"full"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});function rm(s,e){let t=ns.load(s);t("script, style, nav, header, footer, aside, .advertisement, .ad, .sidebar").remove();let r=t("title").text().trim()||t("h1").first().text().trim()||t('meta[property="og:title"]').attr("content")||"Untitled",o=t('meta[name="author"]').attr("content")||t('meta[property="article:author"]').attr("content")||t(".author").first().text().trim()||void 0,n=t('meta[property="article:published_time"]').attr("content")||t("time").first().attr("datetime")||t(".date, .published").first().text().trim()||void 0,a=["article","main",'[role="main"]',".content",".article-content",".post-content","#content"],i="";for(let w of a){let y=t(w).first();if(y.length>0&&(i=y.text().trim(),i.length>200))break}(!i||i.length<200)&&(i=t("body").text().trim()),i=i.replace(/\s+/g," ").trim();let c=[];t("p").each((w,y)=>{let b=t(y).text().trim();b.length>50&&c.length<3&&c.push(b)});let p=c.join(`
|
|
35
35
|
|
|
36
|
-
`)||i.substring(0,500),m=[];t("h2, h3").each((
|
|
37
|
-
`)}function
|
|
36
|
+
`)||i.substring(0,500),m=[];t("h2, h3").each((w,y)=>{let b=t(y).text().trim();b&&b.length>5&&b.length<200&&m.length<10&&m.push(b)});let u=i.split(/\s+/).length,g=i.split(/\s+/);return g.length>2e3&&(i=g.slice(0,2e3).join(" ")+"..."),{title:r,url:e,author:o,publishDate:n,excerpt:p.substring(0,1e3),mainContent:i.substring(0,1e4),keyPoints:m,wordCount:u}}function nm(s,e){let t=ns.load(s);t("script, style, nav, header, footer").remove();let r=t("title").text().trim()||t("h1").first().text().trim()||"Untitled",o=t('meta[name="description"]').attr("content")||t('meta[property="og:description"]').attr("content")||"";return o||t("p").each((n,a)=>{let i=t(a).text().trim();i.length>50&&!o&&(o=i)}),o||(o=t("body").text().trim().replace(/\s+/g," ")),{title:r,url:e,snippet:o.substring(0,500)}}function sm(s){let e=[];return e.push(`# ${s.title}`),e.push(`URL: ${s.url}`),s.author&&e.push(`Author: ${s.author}`),s.publishDate&&e.push(`Published: ${s.publishDate}`),e.push(`Word Count: ${s.wordCount}`),e.push(""),s.keyPoints.length>0&&(e.push("## Key Points"),s.keyPoints.forEach(t=>{e.push(`- ${t}`)}),e.push("")),e.push("## Excerpt"),e.push(s.excerpt),e.push(""),e.push("## Main Content"),e.push(s.mainContent),e.join(`
|
|
37
|
+
`)}function im(s){return`# ${s.title}
|
|
38
38
|
URL: ${s.url}
|
|
39
39
|
|
|
40
|
-
${s.snippet}`}var
|
|
41
|
-
${await i.text()}`;let c=await i.text();if(t==="structured"){let p=
|
|
40
|
+
${s.snippet}`}var ns,am=f(()=>{"use strict";l();ns=T(require("cheerio"),1)});async function Hh(s){let e=s.url,t=s.extractionMode||"full",r=s.headers,o=s.timeout||3e4;if(h(`[web.fetch] execute url="${e}" mode=${t} timeout=${o}ms`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let n=new AbortController,a=setTimeout(()=>n.abort(),o),i;try{i=await fetch(e,{method:"GET",headers:r||{},signal:n.signal})}catch(p){throw p.name==="AbortError"?new Error(`Request timed out after ${o}ms`):p}finally{clearTimeout(a)}if(!i.ok)return`HTTP ${i.status} ${i.statusText}
|
|
41
|
+
${await i.text()}`;let c=await i.text();if(t==="structured"){let p=rm(c,e);return sm(p)}else if(t==="minimal"){let p=nm(c,e);return im(p)}else return c.length>15e3?c.substring(0,15e3)+`
|
|
42
42
|
|
|
43
|
-
[TRUNCATED: showing 15K of ${c.length} total characters]`:c}var
|
|
44
|
-
`)||R.title;return JSON.stringify({answer:U,results:j},null,2)}}if(
|
|
43
|
+
[TRUNCATED: showing 15K of ${c.length} total characters]`:c}var At,ss=f(()=>{"use strict";l();om();am();k();At={name:Vp,displayName:Xp,description:Zp,parameters:tm,category:em,execute:Hh}});var lm,cm,pm,mm,dm,um=f(()=>{"use strict";l();lm="web.search",cm="Search",pm="Search the web using multiple providers (Tavily, Brave, DuckDuckGo Lite) with automatic fallback. Supports real-time results via freshness parameter and AI-generated answers. Configure API keys via environment variables (TOOLPACK_TAVILY_API_KEY, TOOLPACK_BRAVE_API_KEY) or toolpack.config.json for best results.",mm="network",dm={type:"object",properties:{query:{type:"string",description:"The search query"},max_results:{type:"integer",description:"Maximum number of results to return (default: 5)",default:5},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4},include_answer:{type:"boolean",description:"Include AI-generated answer summary (works with Tavily and Brave APIs). Default: false",default:!1},freshness:{type:"string",description:'Time range for fresh/recent results: "day" (last 24h), "week" (last 7 days), "month" (last 31 days), "year" (last 365 days). Ensures latest real-time data. Supported by Tavily and Brave APIs; DuckDuckGo returns general results.',enum:["day","week","month","year"]}},required:["query"]}});function po(s){let e=hm(s);if(!Ce.existsSync(e))return{};try{let t=Ce.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return{}}}function Mt(s){let e=po(s),t=zh(e.tools||e);return h(JSON.stringify(t??{})),t}function gm(s,e){let t=hm(e),r={};try{Ce.existsSync(t)&&(r=JSON.parse(Ce.readFileSync(t,"utf-8")))}catch{r={}}r.tools=s,Ce.writeFileSync(t,JSON.stringify(r,null,4),"utf-8")}function zh(s){let e=s.additionalConfigurations||{};return e.webSearch||(e.webSearch={}),!e.webSearch.tavilyApiKey&&process.env.TOOLPACK_TAVILY_API_KEY&&(e.webSearch.tavilyApiKey=process.env.TOOLPACK_TAVILY_API_KEY),!e.webSearch.braveApiKey&&process.env.TOOLPACK_BRAVE_API_KEY&&(e.webSearch.braveApiKey=process.env.TOOLPACK_BRAVE_API_KEY),{enabled:s.enabled??H.enabled,autoExecute:s.autoExecute??H.autoExecute,maxToolRounds:s.maxToolRounds??H.maxToolRounds,toolChoicePolicy:s.toolChoicePolicy??H.toolChoicePolicy,resultMaxChars:s.resultMaxChars??H.resultMaxChars,intelligentToolDetection:s.intelligentToolDetection,enabledTools:s.enabledTools??H.enabledTools,enabledToolCategories:s.enabledToolCategories??H.enabledToolCategories,toolSearch:s.toolSearch??H.toolSearch,additionalConfigurations:e}}function hm(s){return s?s.endsWith(".json")?pr.resolve(s):pr.resolve(s,fm):pr.resolve(process.cwd(),fm)}var Ce,pr,fm,is=f(()=>{"use strict";l();Ce=T(require("fs"),1),pr=T(require("path"),1);Xt();k();fm="toolpack.config.json"});function Yh(s,e){h("[web.search] Parsing DuckDuckGo Lite response");let t=wm.load(s),r=[];return t("a.result-link").each((n,a)=>{if(r.length>=e)return;let i=t(a),c=i.text().trim(),p=i.attr("href"),m=i.siblings(".result-snippet").text().trim();m||(m=i.parent().text().replace(c,"").trim()),c&&p&&r.push({title:c,link:p,snippet:m.slice(0,200)})}),r}function Vh(s){if(s)switch(s){case"day":return 1;case"week":return 7;case"month":return 31;case"year":return 365;default:return}}function ym(s){if(!s)return"";switch(s){case"day":return"pd";case"week":return"pw";case"month":return"pm";case"year":return"py";default:return""}}async function Xh(s){let e=s.query,t=s.max_results||5,r=s.include_answer||!1,o=s.freshness;h(`[web.search] execute query="${e}" max_results=${t} includeAnswer=${r} freshness=${o??"none"}`);let n=`Request timed out after ${s.timeout||3e4}ms`,a=()=>{let u=new AbortController,g=setTimeout(()=>u.abort(),s.timeout||3e4);return{signal:u.signal,clear:()=>clearTimeout(g)}};if(!e)throw new Error("query is required");let i=Mt();if(h(`[web.search] config=${JSON.stringify(i)}`),i.additionalConfigurations?.webSearch?.tavilyApiKey){h("[web.search] using Tavily API");try{let{signal:u,clear:g}=a(),w=Vh(o),y={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:i.additionalConfigurations.webSearch.tavilyApiKey,query:e,max_results:t,include_answer:r,...w&&{days:w}}),signal:u};h(`[web.search] Tavily request=${JSON.stringify(y)}`);let b=await fetch("https://api.tavily.com/search",y).finally(g);if(b.ok){let P=await b.json();if(P.results&&P.results.length>0){let $=P.results.map(C=>({title:C.title,link:C.url,snippet:C.content}));return r&&P.answer?JSON.stringify({answer:P.answer,results:$},null,2):JSON.stringify($,null,2)}}else Y(`[web.search] Tavily search failed with status ${b.status}`)}catch(u){Y(`[web.search] Tavily search failed, falling back: ${u}`)}}if(i.additionalConfigurations?.webSearch?.braveApiKey)try{let{signal:u,clear:g}=a();if(r){let w=ym(o),y=w?`&freshness=${w}`:"",b=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(e)}&count=${Math.min(t,20)}&summary=1${y}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":i.additionalConfigurations.webSearch.braveApiKey},signal:u}).finally(g);if(b.ok){let P=await b.json(),$=P.summarizer?.key;if($&&P.web?.results){let{signal:C,clear:x}=a(),S=await fetch(`https://api.search.brave.com/res/v1/summarizer/search?key=${$}`,{headers:{Accept:"application/json","X-Subscription-Token":i.additionalConfigurations.webSearch.braveApiKey},signal:C}).finally(x);if(S.ok){let R=await S.json(),j=P.web.results.slice(0,t).map(L=>({title:L.title,link:L.url,snippet:L.description})),U=R.summary?.map(L=>L.data).join(`
|
|
44
|
+
`)||R.title;return JSON.stringify({answer:U,results:j},null,2)}}if(P.web?.results){let C=P.web.results.slice(0,t).map(x=>({title:x.title,link:x.url,snippet:x.description}));return JSON.stringify(C,null,2)}}}else{let w=ym(o),y=w?`&freshness=${w}`:"",b=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(e)}&count=${Math.min(t,20)}${y}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":i.additionalConfigurations.webSearch.braveApiKey},signal:u}).finally(g);if(b.ok){let P=await b.json();if(P.web?.results&&P.web.results.length>0){let $=P.web.results.slice(0,t).map(C=>({title:C.title,link:C.url,snippet:C.description}));return JSON.stringify($,null,2)}}}}catch(u){E(`[web.search] Brave search failed, falling back: ${u}`)}let{signal:c,clear:p}=a(),m;try{m=await fetch(Kh,{method:"POST",headers:{"User-Agent":Qh,"Content-Type":"application/x-www-form-urlencoded",Origin:"https://lite.duckduckgo.com",Referer:"https://lite.duckduckgo.com/"},body:new URLSearchParams({q:e}).toString(),signal:c})}catch(u){throw u.name==="AbortError"?new Error(n):u}finally{p()}if(m.ok){let u=await m.text(),g=Yh(u,t);if(g.length>0)return JSON.stringify(g,null,2)}return JSON.stringify({error:"search_unavailable",message:`Search failed to find results for "${e}" across all providers.`,suggestion:"Please configure a search provider API key (tavilyApiKey or braveApiKey) in toolpack.config.json under tools.additionalConfigurations.webSearch."})}var wm,Kh,Qh,Ot,as=f(()=>{"use strict";l();wm=T(require("cheerio"),1);um();is();k();Kh="https://lite.duckduckgo.com/lite/",Qh="Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1";Ot={name:lm,displayName:cm,description:pm,parameters:dm,category:mm,execute:Xh}});var bm,xm,Tm,Pm,Cm,vm=f(()=>{"use strict";l();bm="web.scrape",xm="Scrape",Tm="Extract clean text content from a webpage. RECOMMENDED WORKFLOW: Use web.map first to see page structure, then use section parameter to extract specific sections. Strips scripts, styles, navigation, and other junk. By default, auto-detects and extracts the main article/content area.",Pm="network",Cm={type:"object",properties:{url:{type:"string",description:"The URL to scrape"},section:{type:"string",description:'Optional section name to extract (e.g., "talks", "about", "experience"). Finds the heading containing this text and extracts content until the next same-level heading. Use web.map first to discover available sections.'},format:{type:"string",description:'Output format: "text" (clean readable text) or "tables" (extract table data as JSON array). Default: "text"',enum:["text","tables"],default:"text"},selector:{type:"string",description:"Optional CSS selector to target a specific element. Only use if you know the exact selector exists."},max_length:{type:"integer",description:"Maximum characters to return (default: 6000). Keep small (3000-6000) to avoid context limits.",default:6e3},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function ty(s){let e=s.url,t=s.selector,r=s.section,o=s.format||"text",n=s.max_length||6e3,a=s.timeout||3e4;if(h(`[web.scrape] execute url="${e}" format=${o} selector=${t??"none"} section=${r??"none"} timeout=${a}ms`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let i=new AbortController,c=setTimeout(()=>i.abort(),a),p;try{p=await fetch(e,{method:"GET",headers:{"User-Agent":Zh},signal:i.signal})}catch(y){throw y.name==="AbortError"?new Error(`Request timed out after ${a}ms`):y}finally{clearTimeout(c)}if(!p.ok)throw new Error(`Failed to fetch ${e}: HTTP ${p.status} ${p.statusText}`);let m=await p.text(),u=_m.load(m);for(let y of ey)u(y).remove();if(o==="tables"){let y=[];return u("table").each((b,P)=>{let $=[],C=[];u(P).find("th").each((x,S)=>{C.push(u(S).text().trim())}),u(P).find("tr").each((x,S)=>{let R=C.length>0?{}:[],j=u(S).find("td");j.length>0&&(j.each((U,L)=>{let F=u(L).text().trim();C.length>0&&C[U]?R[C[U]]=F:R.push(F)}),$.push(R))}),$.length>0&&y.push({id:`Table ${b+1}`,headers:C.length>0?C:void 0,rows:$})}),y.length===0?`No tables found on ${e}`:JSON.stringify(y,null,2)}let g="";if(r){let y=r.toLowerCase(),b=null,P=0;if(u("h1, h2, h3, h4, h5, h6").each(($,C)=>{if(u(C).text().toLowerCase().includes(y))return b=C,P=parseInt(C.tagName.charAt(1)),!1}),b){let $=u(b),C=[],x=$.next();for(;x.length>0;){let S=x.prop("tagName")?.toLowerCase();if(S&&/^h[1-6]$/.test(S)&&parseInt(S.charAt(1))<=P)break;let R=x.text().trim();R&&C.push(R),x=x.next()}C.length>0?(g=C.join(`
|
|
45
45
|
|
|
46
|
-
`).replace(/\s+/g," ").trim(),g=`[Section: "${
|
|
46
|
+
`).replace(/\s+/g," ").trim(),g=`[Section: "${r}"]
|
|
47
47
|
|
|
48
|
-
${g}`):g=`[Note: Found heading "${
|
|
48
|
+
${g}`):g=`[Note: Found heading "${r}" but no content below it. Falling back to full page.]
|
|
49
49
|
|
|
50
|
-
`}else g=`[Note: Section "${
|
|
50
|
+
`}else g=`[Note: Section "${r}" not found. Falling back to full page.]
|
|
51
51
|
|
|
52
|
-
`}if(!g||g.includes("Falling back to full page"))if(g&&g.includes("Falling back to full page")&&(g=""),t){let y=u(t);if(y.length>0)g=y.text().replace(/\s+/g," ").trim();else{for(let
|
|
52
|
+
`}if(!g||g.includes("Falling back to full page"))if(g&&g.includes("Falling back to full page")&&(g=""),t){let y=u(t);if(y.length>0)g=y.text().replace(/\s+/g," ").trim();else{for(let b of Sm){let P=u(b);if(P.length>0){let $=P.text().replace(/\s+/g," ").trim();if($.length>$m){g=$;break}}}if(g)g=`[Note: Selector "${t}" not found. Showing auto-detected main content instead.]
|
|
53
53
|
|
|
54
|
-
${g}`;else return`No element found matching selector "${t}" and could not auto-detect main content from ${e}`}}else for(let y of
|
|
54
|
+
${g}`;else return`No element found matching selector "${t}" and could not auto-detect main content from ${e}`}}else for(let y of Sm){let b=u(y);if(b.length>0){let P=b.text().replace(/\s+/g," ").trim();if(P.length>$m){g=P;break}}}if(g||(g=u("body").text().replace(/\s+/g," ").trim(),g&&(g=`[Note: Could not detect main content area. Showing full page text (may include navigation).]
|
|
55
55
|
|
|
56
56
|
${g}`)),!g)return`Could not extract any content from ${e}`;if(g.length>n){let y=g.substring(0,n);return`[Warning: Content exceeds ${n} chars (actual: ${g.length} chars). Showing first ${n} chars only.]
|
|
57
57
|
|
|
@@ -63,34 +63,34 @@ ${y}
|
|
|
63
63
|
|
|
64
64
|
... [Content truncated. ${g.length-n} chars remaining. Use section parameter to extract specific sections.]`}return`Page content from ${e}:
|
|
65
65
|
|
|
66
|
-
${g}`}var
|
|
66
|
+
${g}`}var _m,Zh,ey,Sm,$m,It,ls=f(()=>{"use strict";l();_m=T(require("cheerio"),1);vm();k();Zh="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",ey=["script","style","nav","footer","header","iframe",".ads",".sidebar","noscript"],Sm=["article","main",".content","#content",'[role="main"]',"body"],$m=200;It={name:bm,displayName:xm,description:Tm,parameters:Cm,category:Pm,execute:ty}});var km,Rm,Em,Dm,Nm,Am=f(()=>{"use strict";l();km="web.extract_links",Rm="Extract Links",Em="Extract all links from a webpage. Returns an array of objects with text and URL. Optionally filter by pattern.",Dm="network",Nm={type:"object",properties:{url:{type:"string",description:"The URL to extract links from"},filter:{type:"string",description:'Optional filter: "same-domain" to only include links from the same domain, or a substring to match against URLs'},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function ry(s){let e=s.url,t=s.filter,r=s.timeout||3e4;if(!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=new AbortController,n=setTimeout(()=>o.abort(),r),a;try{a=await fetch(e,{method:"GET",headers:{"User-Agent":oy},signal:o.signal})}catch(u){throw u.name==="AbortError"?new Error(`Request timed out after ${r}ms`):u}finally{clearTimeout(n)}if(!a.ok)throw new Error(`Failed to fetch ${e}: HTTP ${a.status} ${a.statusText}`);let i=await a.text(),c=Mm.load(i),p=new URL(e),m=[];return c("a[href]").each((u,g)=>{let w=c(g),y=w.attr("href");if(!y)return;let b;try{b=new URL(y,e).toString()}catch{return}if(b.startsWith("javascript:")||b.startsWith("mailto:")||b.startsWith("tel:"))return;let P=w.text().trim()||"[no text]";if(t){if(t==="same-domain")try{if(new URL(b).hostname!==p.hostname)return}catch{return}else if(!b.includes(t))return}m.push({text:P,url:b})}),m.length===0?`No links found on ${e}${t?` matching filter "${t}"`:""}`:JSON.stringify(m,null,2)}var Mm,oy,jt,cs=f(()=>{"use strict";l();Mm=T(require("cheerio"),1);Am();oy="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";jt={name:km,displayName:Rm,description:Em,parameters:Nm,category:Dm,execute:ry}});var Om,Im,jm,Fm,Lm,qm=f(()=>{"use strict";l();Om="web.map",Im="Map",jm="Extract the structure/outline of a webpage by returning all headings (h1-h6). Use this FIRST when you need to understand what sections exist on a page before scraping specific content. Returns a lightweight outline showing the page hierarchy.",Fm="network",Lm={type:"object",properties:{url:{type:"string",description:"The URL to map"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function sy(s){let e=s.url,t=s.timeout||3e4;if(!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let r=new AbortController,o=setTimeout(()=>r.abort(),t),n;try{n=await fetch(e,{method:"GET",headers:{"User-Agent":ny},signal:r.signal})}catch(m){throw m.name==="AbortError"?new Error(`Request timed out after ${t}ms`):m}finally{clearTimeout(o)}if(!n.ok)throw new Error(`Failed to fetch ${e}: HTTP ${n.status} ${n.statusText}`);let a=await n.text(),i=Um.load(a),c=[];if(i("h1, h2, h3, h4, h5, h6").each((m,u)=>{let g=u.tagName.toLowerCase(),w=parseInt(g.charAt(1)),y=i(u).text().trim();y&&c.push({level:w,text:y})}),c.length===0)return`No headings found on ${e}. The page may not have a clear structure.`;let p=`Page outline for ${e}:
|
|
67
67
|
|
|
68
68
|
`;for(let m of c){let u=" ".repeat(m.level-1);p+=`${u}${"#".repeat(m.level)} ${m.text}
|
|
69
|
-
`}return p}var
|
|
70
|
-
`);for(let m of p){if(c.length>=t)break;let u=m.trim();if(u.toLowerCase().startsWith("sitemap:"))c.push({loc:u.substring(8).trim()});else if(u.toLowerCase().startsWith("allow:")){let g=u.substring(6).trim();c.push({loc:new URL(g,r).toString()})}}}return JSON.stringify(c,null,2)}var Ym,ty,ur,ms=f(()=>{"use strict";l();Ym=P(require("cheerio"),1);Qm();ty="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";ur={name:Bm,displayName:Jm,description:Hm,parameters:Km,category:zm,execute:oy}});var Vm,Xm,Zm,ed,td,od=f(()=>{"use strict";l();Vm="web.feed",Xm="Extract Feed",Zm="Parse RSS/Atom feeds and return structured entries. Requires rss-parser library to be installed.",ed="network",td={type:"object",properties:{url:{type:"string",description:"The URL of the RSS/Atom feed"},max_entries:{type:"integer",description:"Maximum number of entries to return (default: 10)",default:10},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function rd(){try{let s=await import("rss-parser");return new(s.default||s)}catch{throw new Error("rss-parser is not installed. Please install it using `npm install rss-parser` to use this feature.")}}var nd=f(()=>{"use strict";l()});async function ry(s){let e=s.url,t=s.max_entries||10,o=s.timeout||3e4;if(!e)throw new Error("url is required");let r=await rd();r.options={...r.options,timeout:o};try{let n=await r.parseURL(e),a=n.items.slice(0,t).map(i=>({title:i.title,link:i.link,published:i.pubDate||i.isoDate,summary:i.contentSnippet||i.content}));return JSON.stringify({feedTitle:n.title,feedDescription:n.description,entries:a},null,2)}catch(n){throw new Error(`Failed to parse feed from ${e}: ${n.message}`)}}var fr,ds=f(()=>{"use strict";l();od();nd();fr={name:Vm,displayName:Xm,description:Zm,parameters:td,category:ed,execute:ry}});var sd,id,ad,ld,cd,pd=f(()=>{"use strict";l();sd="web.screenshot",id="Screenshot",ad="Render a page with headless browser and return screenshot Base64 PNG or rendered HTML.",ld="network",cd={type:"object",properties:{url:{type:"string",description:"The URL to capture"},format:{type:"string",description:'Output format: "html" or "png" (default: "html")',enum:["html","png"],default:"html"},viewport:{type:"object",description:"Optional viewport { width, height } (default: { width: 1280, height: 800 })",properties:{width:{type:"integer"},height:{type:"integer"}}},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function md(){try{let s=await import("puppeteer");return s.default||s}catch{throw new Error("Puppeteer is not installed. Please install it using `npm install puppeteer` to use this feature.")}}var dd=f(()=>{"use strict";l()});async function sy(s){let e=s.url,t=s.format||"html",o=s.viewport,r=s.timeout||3e4;if(!e)throw new Error("url is required");let a=await(await md()).launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]});try{let i=await a.newPage();if(await i.setUserAgent(ny),await i.setViewport({width:o?.width||1280,height:o?.height||800}),await i.goto(e,{waitUntil:"networkidle2",timeout:r}),t==="png"){let c=await i.screenshot({type:"png",fullPage:!0}),p;return Buffer.isBuffer(c)?p=c.toString("base64"):p=Buffer.from(c).toString("base64"),`data:image/png;base64,${p}`}else return await i.content()}finally{await a.close()}}var ny,gr,us=f(()=>{"use strict";l();pd();dd();ny="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";gr={name:sd,displayName:id,description:ad,parameters:cd,category:ld,execute:sy}});var ud={};V(ud,{webExtractLinksTool:()=>Ot,webFeedTool:()=>fr,webFetchTool:()=>Et,webMapTool:()=>mr,webMetadataTool:()=>dr,webScrapeTool:()=>Mt,webScreenshotTool:()=>gr,webSearchTool:()=>At,webSitemapTool:()=>ur,webToolsProject:()=>fs});var fs,gs=f(()=>{"use strict";l();rs();ss();is();as();ls();cs();ms();ds();us();rs();ss();is();as();ls();cs();ms();ds();us();fs={manifest:{key:"web",name:"web-tools",displayName:"Web",version:"1.0.0",description:"Web intelligence tools for fetching, searching, scraping, and extracting content from the web.",author:"Sajeer",tools:["web.fetch","web.search","web.scrape","web.extract_links","web.map","web.metadata","web.sitemap","web.feed","web.screenshot"],category:"network"},tools:[Et,At,Mt,Ot,mr,dr,ur,fr,gr],dependencies:{cheerio:"^1.0.0-rc.12"}}});var fd,gd,hd,yd,wd,bd=f(()=>{"use strict";l();fd="coding.find_symbol",gd="Find Symbol",hd="Find function, class, or variable definitions in JavaScript/TypeScript files using AST parsing",yd="coding",wd={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find (function, class, variable, etc.)"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["symbol","path"]}});function hr(s){let e=(0,xd.extname)(s).toLowerCase();return iy[e]||"unknown"}var xd,iy,hs=f(()=>{"use strict";l();xd=require("path"),iy={".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"jsx",".ts":"typescript",".tsx":"tsx",".py":"python",".go":"go",".rs":"rust",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".hpp":"cpp",".cc":"cpp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".hs":"haskell",".ex":"elixir",".exs":"elixir",".html":"html",".htm":"html",".css":"css",".json":"json",".yaml":"yaml",".yml":"yaml",".md":"markdown",".sh":"bash",".bash":"bash"}});var Ie,fe,ve,Pd,Td,ys,ay,yr,Cd=f(()=>{"use strict";l();Ie=P(require("web-tree-sitter"),1),fe=P(require("fs"),1),ve=P(require("path"),1),Pd=P(require("os"),1),Td=Ie.default||Ie.Parser||Ie,ys=ve.join(Pd.homedir(),".toolpack-sdk","grammars"),ay=ve.resolve(__dirname,"../../grammars"),yr=class{grammars=new Map;isInitialized=!1;async init(){this.isInitialized||(await Td.init({locateFile(e,t){return ve.join(__dirname,"../../../../../../node_modules/web-tree-sitter",e)}}),this.isInitialized=!0)}async ensureGrammar(e){await this.init();let t=this.grammars.get(e);if(t)return t;let o=await this.resolveGrammarPath(e),n=await(Ie.Language||Td.Language).load(o);return this.grammars.set(e,n),n}async resolveGrammarPath(e){let t=`tree-sitter-${e}.wasm`,o=ve.resolve(__dirname,"../../../../../../node_modules/tree-sitter-wasms/out",t);if(fe.existsSync(o))return o;let r=ve.join(ay,t);if(fe.existsSync(r))return r;let n=ve.join(ys,t);return fe.existsSync(n)||await this.downloadGrammar(e,n),n}async downloadGrammar(e,t){fe.existsSync(ys)||fe.mkdirSync(ys,{recursive:!0});let o=`https://unpkg.com/tree-sitter-wasms@latest/out/tree-sitter-${e}.wasm`,r=await fetch(o);if(!r.ok)throw new Error(`Failed to download grammar for ${e}: ${r.statusText}`);let n=await r.arrayBuffer(),a=Buffer.from(n);fe.writeFileSync(t,a)}}});var co,vd,Sd,ly,wr,$d=f(()=>{"use strict";l();co=P(require("web-tree-sitter"),1),vd=P(require("fs"),1),Sd=P(require("crypto"),1);hs();Cd();ly=co.default||co.Parser||co,wr=class{treeCache=new Map;maxCacheSize=50;parser=null;grammarManager;constructor(){this.grammarManager=new yr}hash(e){return Sd.createHash("md5").update(e).digest("hex")}async getTree(e,t){let o=t!==void 0?t:vd.readFileSync(e,"utf-8"),r=this.hash(o),n=this.treeCache.get(e),a=hr(e);if(a==="unknown")throw new Error(`Unsupported file type for ${e}`);let i=await this.grammarManager.ensureGrammar(a);if(n&&n.contentHash===r)return n.lastAccessed=Date.now(),{tree:n.tree,language:n.language,grammar:i};this.parser||(await this.grammarManager.init(),this.parser=new ly),this.parser.setLanguage(i);let c;return n?(n.tree&&n.tree.delete(),c=this.parser.parse(o)):c=this.parser.parse(o),this.treeCache.set(e,{tree:c,language:a,contentHash:r,lastAccessed:Date.now()}),this.evictIfNeeded(),{tree:c,language:a,grammar:i}}evictIfNeeded(){if(this.treeCache.size<=this.maxCacheSize)return;let e="",t=1/0;for(let[o,r]of this.treeCache.entries())r.lastAccessed<t&&(t=r.lastAccessed,e=o);if(e){let o=this.treeCache.get(e);o&&o.tree.delete(),this.treeCache.delete(e)}}}});var _d,ws,se,br,kd=f(()=>{"use strict";l();_d=require("@babel/parser"),ws=P(require("@babel/traverse"),1),se=ws.default||ws,br=class{parseCode(e){return(0,_d.parse)(e,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]})}async findSymbols(e,t,o){let r=[];try{let n=this.parseCode(e.content),a=e.filePath;se(n,{FunctionDeclaration(i){i.node.id?.name===t&&(!o||o==="function")&&r.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"function",name:t})},ClassDeclaration(i){i.node.id?.name===t&&(!o||o==="class")&&r.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"class",name:t})},VariableDeclarator(i){if(i.node.id.type==="Identifier"&&i.node.id.name===t){let c=i.parent,p=c.type==="VariableDeclaration"?c.kind:"variable";(!o||o===p||o==="variable")&&r.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:p,name:t})}},TSInterfaceDeclaration(i){i.node.id.name===t&&(!o||o==="interface")&&r.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"interface",name:t})},TSTypeAliasDeclaration(i){i.node.id.name===t&&(!o||o==="type")&&r.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"type",name:t})}})}catch{}return r}async getSymbols(e,t){let o=[];try{let r=this.parseCode(e.content);se(r,{FunctionDeclaration(n){n.node.id?.name&&(!t||t==="function")&&o.push({name:n.node.id.name,kind:"function",line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})},ClassDeclaration(n){n.node.id?.name&&(!t||t==="class")&&o.push({name:n.node.id.name,kind:"class",line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})},VariableDeclarator(n){if(n.node.id.type==="Identifier"){let a=n.parent,i=a.type==="VariableDeclaration"?a.kind:"variable";(!t||t===i||t==="variable")&&o.push({name:n.node.id.name,kind:i,line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})}},TSInterfaceDeclaration(n){(!t||t==="interface")&&o.push({name:n.node.id.name,kind:"interface",line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})},TSTypeAliasDeclaration(n){(!t||t==="type")&&o.push({name:n.node.id.name,kind:"type",line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})}})}catch(r){throw new Error(`Failed to parse file "${e.filePath}": ${r.message}`)}return o}async getImports(e){let t=[];try{let o=this.parseCode(e.content);se(o,{ImportDeclaration(r){let n=r.node.source.value,a=[],i="side-effect";for(let c of r.node.specifiers)if(c.type==="ImportDefaultSpecifier")a.push(c.local.name),i="default";else if(c.type==="ImportNamespaceSpecifier")a.push(`* as ${c.local.name}`),i="namespace";else if(c.type==="ImportSpecifier"){let p=c.imported.type==="Identifier"?c.imported.name:c.imported.value,m=c.local.name;a.push(p===m?p:`${p} as ${m}`),i="named"}t.push({source:n,imports:a,line:r.node.loc?.start.line||0,type:i})}})}catch(o){throw new Error(`Failed to parse file "${e.filePath}": ${o.message}`)}return t}async findReferences(e,t,o){let r=[];try{let n=e.content,a=n.split(`
|
|
71
|
-
`),i=this.parseCode(n);se(i,{Identifier(c){if(c.node.name===t){let p=c.isFunctionDeclaration()||c.isClassDeclaration()||c.parent.type==="VariableDeclarator"&&c.parent.id===c.node||c.parent.type==="TSInterfaceDeclaration"&&c.parent.id===c.node||c.parent.type==="TSTypeAliasDeclaration"&&c.parent.id===c.node;if(!p||
|
|
72
|
-
`),c=Math.max(0,t-1),p=Math.min(i.length,
|
|
69
|
+
`}return p}var Um,ny,mr,ps=f(()=>{"use strict";l();Um=T(require("cheerio"),1);qm();ny="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";mr={name:Om,displayName:Im,description:jm,parameters:Lm,category:Fm,execute:sy}});var Wm,Gm,Bm,Jm,Hm,zm=f(()=>{"use strict";l();Wm="web.metadata",Gm="Extract Metadata",Bm="Extract Open Graph, Twitter Cards, JSON-LD, and meta tags from a URL.",Jm="network",Hm={type:"object",properties:{url:{type:"string",description:"The URL to extract metadata from"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function ay(s){let e=s.url,t=s.timeout||3e4;if(!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let r=new AbortController,o=setTimeout(()=>r.abort(),t),n;try{n=await fetch(e,{method:"GET",headers:{"User-Agent":iy},signal:r.signal})}catch(p){throw p.name==="AbortError"?new Error(`Request timed out after ${t}ms`):p}finally{clearTimeout(o)}if(!n.ok)throw new Error(`Failed to fetch ${e}: HTTP ${n.status} ${n.statusText}`);let a=await n.text(),i=Km.load(a),c={title:i("title").text()||"",description:i('meta[name="description"]').attr("content")||i('meta[property="og:description"]').attr("content")||"",author:i('meta[name="author"]').attr("content")||"",openGraph:{},twitter:{},jsonLd:[]};return i('meta[property^="og:"]').each((p,m)=>{let u=i(m).attr("property")?.replace("og:",""),g=i(m).attr("content");u&&g&&(c.openGraph[u]=g)}),i('meta[name^="twitter:"]').each((p,m)=>{let u=i(m).attr("name")?.replace("twitter:",""),g=i(m).attr("content");u&&g&&(c.twitter[u]=g)}),i('script[type="application/ld+json"]').each((p,m)=>{let u=i(m).html();if(u)try{c.jsonLd.push(JSON.parse(u))}catch{}}),JSON.stringify(c,null,2)}var Km,iy,dr,ms=f(()=>{"use strict";l();Km=T(require("cheerio"),1);zm();iy="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";dr={name:Wm,displayName:Gm,description:Bm,parameters:Hm,category:Jm,execute:ay}});var Qm,Ym,Vm,Xm,Zm,ed=f(()=>{"use strict";l();Qm="web.sitemap",Ym="Extract Sitemap",Vm="Parse sitemap.xml or robots.txt to discover all pages on a site. Returns an array of URLs with lastmod/priority if available.",Xm="network",Zm={type:"object",properties:{url:{type:"string",description:"The base URL or direct sitemap.xml / robots.txt URL"},max_urls:{type:"integer",description:"Maximum number of URLs to return (default: 100)",default:100},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function ds(s,e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);try{return await fetch(s,{method:"GET",headers:{"User-Agent":ly},signal:t.signal})}catch(o){throw o.name==="AbortError"?new Error(`Request timed out after ${e}ms`):o}finally{clearTimeout(r)}}async function cy(s){let e=s.url,t=s.max_urls||100,r=s.timeout||3e4;if(!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=e,n=!1;!e.endsWith(".xml")&&!e.endsWith(".txt")&&(o=new URL(e.endsWith("/")?"sitemap.xml":"/sitemap.xml",e).toString(),n=!0);let a;try{a=await ds(o,r),!a.ok&&n&&(o=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),a=await ds(o,r))}catch(p){if(n)o=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),a=await ds(o,r);else throw p}if(!a||!a.ok)throw new Error(`Failed to fetch sitemap or robots.txt from ${e}`);let i=await a.text(),c=[];if(o.endsWith(".xml")||i.trim().startsWith("<")){let p=td.load(i,{xmlMode:!0}),m=p("sitemap > loc");if(m.length>0)return m.each((g,w)=>{c.length>=t||c.push({loc:p(w).text()})}),JSON.stringify({type:"sitemapindex",urls:c},null,2);p("urlset > url").each((g,w)=>{if(c.length>=t)return;let y=p(w);c.push({loc:y.children("loc").text(),lastmod:y.children("lastmod").text()||void 0,priority:y.children("priority").text()||void 0})})}else{let p=i.split(`
|
|
70
|
+
`);for(let m of p){if(c.length>=t)break;let u=m.trim();if(u.toLowerCase().startsWith("sitemap:"))c.push({loc:u.substring(8).trim()});else if(u.toLowerCase().startsWith("allow:")){let g=u.substring(6).trim();c.push({loc:new URL(g,o).toString()})}}}return JSON.stringify(c,null,2)}var td,ly,ur,us=f(()=>{"use strict";l();td=T(require("cheerio"),1);ed();ly="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";ur={name:Qm,displayName:Ym,description:Vm,parameters:Zm,category:Xm,execute:cy}});var od,rd,nd,sd,id,ad=f(()=>{"use strict";l();od="web.feed",rd="Extract Feed",nd="Parse RSS/Atom feeds and return structured entries. Requires rss-parser library to be installed.",sd="network",id={type:"object",properties:{url:{type:"string",description:"The URL of the RSS/Atom feed"},max_entries:{type:"integer",description:"Maximum number of entries to return (default: 10)",default:10},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function ld(){try{let s=await import("rss-parser");return new(s.default||s)}catch{throw new Error("rss-parser is not installed. Please install it using `npm install rss-parser` to use this feature.")}}var cd=f(()=>{"use strict";l()});async function py(s){let e=s.url,t=s.max_entries||10,r=s.timeout||3e4;if(!e)throw new Error("url is required");let o=await ld();o.options={...o.options,timeout:r};try{let n=await o.parseURL(e),a=n.items.slice(0,t).map(i=>({title:i.title,link:i.link,published:i.pubDate||i.isoDate,summary:i.contentSnippet||i.content}));return JSON.stringify({feedTitle:n.title,feedDescription:n.description,entries:a},null,2)}catch(n){throw new Error(`Failed to parse feed from ${e}: ${n.message}`)}}var fr,fs=f(()=>{"use strict";l();ad();cd();fr={name:od,displayName:rd,description:nd,parameters:id,category:sd,execute:py}});var pd,md,dd,ud,fd,gd=f(()=>{"use strict";l();pd="web.screenshot",md="Screenshot",dd="Render a page with headless browser and return screenshot Base64 PNG or rendered HTML.",ud="network",fd={type:"object",properties:{url:{type:"string",description:"The URL to capture"},format:{type:"string",description:'Output format: "html" or "png" (default: "html")',enum:["html","png"],default:"html"},viewport:{type:"object",description:"Optional viewport { width, height } (default: { width: 1280, height: 800 })",properties:{width:{type:"integer"},height:{type:"integer"}}},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function hd(){try{let s=await import("puppeteer");return s.default||s}catch{throw new Error("Puppeteer is not installed. Please install it using `npm install puppeteer` to use this feature.")}}var yd=f(()=>{"use strict";l()});async function dy(s){let e=s.url,t=s.format||"html",r=s.viewport,o=s.timeout||3e4;if(!e)throw new Error("url is required");let a=await(await hd()).launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]});try{let i=await a.newPage();if(await i.setUserAgent(my),await i.setViewport({width:r?.width||1280,height:r?.height||800}),await i.goto(e,{waitUntil:"networkidle2",timeout:o}),t==="png"){let c=await i.screenshot({type:"png",fullPage:!0}),p;return Buffer.isBuffer(c)?p=c.toString("base64"):p=Buffer.from(c).toString("base64"),`data:image/png;base64,${p}`}else return await i.content()}finally{await a.close()}}var my,gr,gs=f(()=>{"use strict";l();gd();yd();my="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";gr={name:pd,displayName:md,description:dd,parameters:fd,category:ud,execute:dy}});var wd={};V(wd,{webExtractLinksTool:()=>jt,webFeedTool:()=>fr,webFetchTool:()=>At,webMapTool:()=>mr,webMetadataTool:()=>dr,webScrapeTool:()=>It,webScreenshotTool:()=>gr,webSearchTool:()=>Ot,webSitemapTool:()=>ur,webToolsProject:()=>hs});var hs,ys=f(()=>{"use strict";l();ss();as();ls();cs();ps();ms();us();fs();gs();ss();as();ls();cs();ps();ms();us();fs();gs();hs={manifest:{key:"web",name:"web-tools",displayName:"Web",version:"1.0.0",description:"Web intelligence tools for fetching, searching, scraping, and extracting content from the web.",author:"Sajeer",tools:["web.fetch","web.search","web.scrape","web.extract_links","web.map","web.metadata","web.sitemap","web.feed","web.screenshot"],category:"network"},tools:[At,Ot,It,jt,mr,dr,ur,fr,gr],dependencies:{cheerio:"^1.0.0-rc.12"}}});var bd,xd,Td,Pd,Cd,vd=f(()=>{"use strict";l();bd="coding.find_symbol",xd="Find Symbol",Td="Find function, class, or variable definitions in JavaScript/TypeScript files using AST parsing",Pd="coding",Cd={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find (function, class, variable, etc.)"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["symbol","path"]}});function hr(s){let e=(0,Sd.extname)(s).toLowerCase();return uy[e]||"unknown"}var Sd,uy,ws=f(()=>{"use strict";l();Sd=require("path"),uy={".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"jsx",".ts":"typescript",".tsx":"tsx",".py":"python",".go":"go",".rs":"rust",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".hpp":"cpp",".cc":"cpp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".hs":"haskell",".ex":"elixir",".exs":"elixir",".html":"html",".htm":"html",".css":"css",".json":"json",".yaml":"yaml",".yml":"yaml",".md":"markdown",".sh":"bash",".bash":"bash"}});var je,fe,ve,_d,$d,bs,fy,yr,kd=f(()=>{"use strict";l();je=T(require("web-tree-sitter"),1),fe=T(require("fs"),1),ve=T(require("path"),1),_d=T(require("os"),1),$d=je.default||je.Parser||je,bs=ve.join(_d.homedir(),".toolpack-sdk","grammars"),fy=ve.resolve(__dirname,"../../grammars"),yr=class{grammars=new Map;isInitialized=!1;async init(){this.isInitialized||(await $d.init({locateFile(e,t){return ve.join(__dirname,"../../../../../../node_modules/web-tree-sitter",e)}}),this.isInitialized=!0)}async ensureGrammar(e){await this.init();let t=this.grammars.get(e);if(t)return t;let r=await this.resolveGrammarPath(e),n=await(je.Language||$d.Language).load(r);return this.grammars.set(e,n),n}async resolveGrammarPath(e){let t=`tree-sitter-${e}.wasm`,r=ve.resolve(__dirname,"../../../../../../node_modules/tree-sitter-wasms/out",t);if(fe.existsSync(r))return r;let o=ve.join(fy,t);if(fe.existsSync(o))return o;let n=ve.join(bs,t);return fe.existsSync(n)||await this.downloadGrammar(e,n),n}async downloadGrammar(e,t){fe.existsSync(bs)||fe.mkdirSync(bs,{recursive:!0});let r=`https://unpkg.com/tree-sitter-wasms@latest/out/tree-sitter-${e}.wasm`,o=await fetch(r);if(!o.ok)throw new Error(`Failed to download grammar for ${e}: ${o.statusText}`);let n=await o.arrayBuffer(),a=Buffer.from(n);fe.writeFileSync(t,a)}}});var mo,Rd,Ed,gy,wr,Dd=f(()=>{"use strict";l();mo=T(require("web-tree-sitter"),1),Rd=T(require("fs"),1),Ed=T(require("crypto"),1);ws();kd();gy=mo.default||mo.Parser||mo,wr=class{treeCache=new Map;maxCacheSize=50;parser=null;grammarManager;constructor(){this.grammarManager=new yr}hash(e){return Ed.createHash("md5").update(e).digest("hex")}async getTree(e,t){let r=t!==void 0?t:Rd.readFileSync(e,"utf-8"),o=this.hash(r),n=this.treeCache.get(e),a=hr(e);if(a==="unknown")throw new Error(`Unsupported file type for ${e}`);let i=await this.grammarManager.ensureGrammar(a);if(n&&n.contentHash===o)return n.lastAccessed=Date.now(),{tree:n.tree,language:n.language,grammar:i};this.parser||(await this.grammarManager.init(),this.parser=new gy),this.parser.setLanguage(i);let c;return n?(n.tree&&n.tree.delete(),c=this.parser.parse(r)):c=this.parser.parse(r),this.treeCache.set(e,{tree:c,language:a,contentHash:o,lastAccessed:Date.now()}),this.evictIfNeeded(),{tree:c,language:a,grammar:i}}evictIfNeeded(){if(this.treeCache.size<=this.maxCacheSize)return;let e="",t=1/0;for(let[r,o]of this.treeCache.entries())o.lastAccessed<t&&(t=o.lastAccessed,e=r);if(e){let r=this.treeCache.get(e);r&&r.tree.delete(),this.treeCache.delete(e)}}}});var Nd,xs,se,br,Ad=f(()=>{"use strict";l();Nd=require("@babel/parser"),xs=T(require("@babel/traverse"),1),se=xs.default||xs,br=class{parseCode(e){return(0,Nd.parse)(e,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]})}async findSymbols(e,t,r){let o=[];try{let n=this.parseCode(e.content),a=e.filePath;se(n,{FunctionDeclaration(i){i.node.id?.name===t&&(!r||r==="function")&&o.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"function",name:t})},ClassDeclaration(i){i.node.id?.name===t&&(!r||r==="class")&&o.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"class",name:t})},VariableDeclarator(i){if(i.node.id.type==="Identifier"&&i.node.id.name===t){let c=i.parent,p=c.type==="VariableDeclaration"?c.kind:"variable";(!r||r===p||r==="variable")&&o.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:p,name:t})}},TSInterfaceDeclaration(i){i.node.id.name===t&&(!r||r==="interface")&&o.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"interface",name:t})},TSTypeAliasDeclaration(i){i.node.id.name===t&&(!r||r==="type")&&o.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"type",name:t})}})}catch{}return o}async getSymbols(e,t){let r=[];try{let o=this.parseCode(e.content);se(o,{FunctionDeclaration(n){n.node.id?.name&&(!t||t==="function")&&r.push({name:n.node.id.name,kind:"function",line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})},ClassDeclaration(n){n.node.id?.name&&(!t||t==="class")&&r.push({name:n.node.id.name,kind:"class",line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})},VariableDeclarator(n){if(n.node.id.type==="Identifier"){let a=n.parent,i=a.type==="VariableDeclaration"?a.kind:"variable";(!t||t===i||t==="variable")&&r.push({name:n.node.id.name,kind:i,line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})}},TSInterfaceDeclaration(n){(!t||t==="interface")&&r.push({name:n.node.id.name,kind:"interface",line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})},TSTypeAliasDeclaration(n){(!t||t==="type")&&r.push({name:n.node.id.name,kind:"type",line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})}})}catch(o){throw new Error(`Failed to parse file "${e.filePath}": ${o.message}`)}return r}async getImports(e){let t=[];try{let r=this.parseCode(e.content);se(r,{ImportDeclaration(o){let n=o.node.source.value,a=[],i="side-effect";for(let c of o.node.specifiers)if(c.type==="ImportDefaultSpecifier")a.push(c.local.name),i="default";else if(c.type==="ImportNamespaceSpecifier")a.push(`* as ${c.local.name}`),i="namespace";else if(c.type==="ImportSpecifier"){let p=c.imported.type==="Identifier"?c.imported.name:c.imported.value,m=c.local.name;a.push(p===m?p:`${p} as ${m}`),i="named"}t.push({source:n,imports:a,line:o.node.loc?.start.line||0,type:i})}})}catch(r){throw new Error(`Failed to parse file "${e.filePath}": ${r.message}`)}return t}async findReferences(e,t,r){let o=[];try{let n=e.content,a=n.split(`
|
|
71
|
+
`),i=this.parseCode(n);se(i,{Identifier(c){if(c.node.name===t){let p=c.isFunctionDeclaration()||c.isClassDeclaration()||c.parent.type==="VariableDeclarator"&&c.parent.id===c.node||c.parent.type==="TSInterfaceDeclaration"&&c.parent.id===c.node||c.parent.type==="TSTypeAliasDeclaration"&&c.parent.id===c.node;if(!p||r){let m=c.node.loc?.start.line||0,u=c.node.loc?.start.column||0,g=a[m-1]||"";o.push({file:e.filePath,line:m,column:u,context:g.trim(),isDeclaration:p})}}}})}catch{}return o}async getSymbolAtPosition(e,t,r){try{let o=this.parseCode(e.content),n=null;return se(o,{Identifier(a){let i=a.node.loc;i&&i.start.line===t&&i.start.column===r&&(n=a.node.name,a.stop())}}),n}catch{return null}}async getDefinition(e,t){try{let r=this.parseCode(e.content),o=e.filePath,n=null;return se(r,{FunctionDeclaration(a){a.node.id?.name===t&&(n={file:o,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"function",name:t},a.stop())},ClassDeclaration(a){a.node.id?.name===t&&(n={file:o,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"class",name:t},a.stop())},VariableDeclarator(a){if(a.node.id.type==="Identifier"&&a.node.id.name===t){let i=a.parent,c=i.type==="VariableDeclaration"?i.kind:"variable";n={file:o,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:c,name:t},a.stop()}},TSInterfaceDeclaration(a){a.node.id.name===t&&(n={file:o,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"interface",name:t},a.stop())},TSTypeAliasDeclaration(a){a.node.id.name===t&&(n={file:o,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"type",name:t},a.stop())}}),n}catch{return null}}async getDiagnostics(e){try{return this.parseCode(e.content),[]}catch(t){return[{message:t.message,line:t.loc?.line||0,column:t.loc?.column||0,severity:"error"}]}}async getExports(e){let t=[];try{let r=this.parseCode(e.content);se(r,{ExportNamedDeclaration(o){if(o.node.declaration)if(o.node.declaration.type==="VariableDeclaration")for(let n of o.node.declaration.declarations)n.id.type==="Identifier"&&t.push({name:n.id.name,kind:"variable",line:n.loc?.start.line||0,column:n.loc?.start.column||0});else o.node.declaration.type==="FunctionDeclaration"&&o.node.declaration.id?t.push({name:o.node.declaration.id.name,kind:"function",line:o.node.declaration.loc?.start.line||0,column:o.node.declaration.loc?.start.column||0}):o.node.declaration.type==="ClassDeclaration"&&o.node.declaration.id&&t.push({name:o.node.declaration.id.name,kind:"class",line:o.node.declaration.loc?.start.line||0,column:o.node.declaration.loc?.start.column||0});else if(o.node.specifiers)for(let n of o.node.specifiers)n.exported.type==="Identifier"&&t.push({name:n.exported.name,kind:"export",line:n.loc?.start.line||0,column:n.loc?.start.column||0})},ExportDefaultDeclaration(o){let n="default",a="default";o.node.declaration.type==="ClassDeclaration"&&o.node.declaration.id?(n=o.node.declaration.id.name,a="class"):o.node.declaration.type==="FunctionDeclaration"&&o.node.declaration.id?(n=o.node.declaration.id.name,a="function"):o.node.declaration.type==="Identifier"&&(n=o.node.declaration.name,a="variable"),t.push({name:n,kind:a,line:o.node.loc?.start.line||0,column:o.node.loc?.start.column||0})}})}catch{}return t}async getOutline(e){let t=[];try{return(await this.getSymbols(e)).map(o=>({name:o.name,kind:o.kind,line:o.line,column:o.column,children:[]}))}catch{}return t}async extractFunction(e,t,r,o,n,a){let i=e.content.split(`
|
|
72
|
+
`),c=Math.max(0,t-1),p=Math.min(i.length,o),m=i.slice(c,p).join(`
|
|
73
73
|
`),u=`
|
|
74
74
|
function ${a}() {
|
|
75
75
|
${m}
|
|
76
76
|
}
|
|
77
|
-
`,g=`${a}();`;return{newFunction:u,replacementCall:g}}async getCallHierarchy(e,t,
|
|
78
|
-
`),a=[];for(let i of
|
|
79
|
-
`),c=Math.max(0,t-1),p=Math.min(i.length,
|
|
80
|
-
`),u="",g="",
|
|
77
|
+
`,g=`${a}();`;return{newFunction:u,replacementCall:g}}async getCallHierarchy(e,t,r){try{let o=this.parseCode(e.content),n=e.filePath,a=null,i="",c=0,p=0;if(se(o,{Function(y){let b=y.node.loc;b&&b.start.line<=t&&b.end&&b.end.line>=t&&(a=y,c=b.start.line,p=b.start.column,y.node.type==="FunctionDeclaration"&&y.node.id?i=y.node.id.name:y.parent.type==="VariableDeclarator"&&y.parent.id.type==="Identifier"?i=y.parent.id.name:y.parent.type==="ClassMethod"||y.parent.type==="ObjectMethod"?y.parent.key.type==="Identifier"&&(i=y.parent.key.name):i="<anonymous>")}}),!a||i==="<anonymous>")return null;let m=[],u=[];se(o,{CallExpression(y){let b=y.node.loc;if(!b||b.start.line<c||b.end&&b.end.line>c+1e3)return;let P=!1,$=y;for(;$;){if($.isFunction()&&$.node.type==="FunctionDeclaration"&&$.node.id?.name===i){P=!0;break}$=$.parentPath}if(!P)return;let C=y.node.callee,x="<unknown>";C.type==="Identifier"?x=C.name:C.type==="MemberExpression"&&C.property.type==="Identifier"&&(x=C.property.name),x!=="<unknown>"&&u.push({file:n,name:x,line:y.node.loc?.start.line||0,column:y.node.loc?.start.column||0})}}),se(o,{CallExpression(y){let b=y.node.callee,P=!1;if((b.type==="Identifier"&&b.name===i||b.type==="MemberExpression"&&b.property.type==="Identifier"&&b.property.name===i)&&(P=!0),P){let $="<global>",C=y;for(;C;){if(C.isFunction()){C.node.type==="FunctionDeclaration"&&C.node.id?$=C.node.id.name:C.parent.type==="VariableDeclarator"&&C.parent.id.type==="Identifier"?$=C.parent.id.name:(C.parent.type==="ClassMethod"||C.parent.type==="ObjectMethod")&&C.parent.key.type==="Identifier"&&($=C.parent.key.name);break}C=C.parentPath}m.push({file:n,name:$,line:y.node.loc?.start.line||0,column:y.node.loc?.start.column||0})}}});let g=[...new Map(m.map(y=>[`${y.name}:${y.line}`,y])).values()],w=[...new Map(u.map(y=>[`${y.name}:${y.line}`,y])).values()];return{file:n,name:i,line:c,column:p,callers:g,callees:w}}catch{return null}}}});var Md,Od=f(()=>{"use strict";l();Md={}});var xr,Id=f(()=>{"use strict";l();Od();xr=class{constructor(e){this.context=e}context;async executeQuery(e,t){let{tree:r,language:o,grammar:n}=await this.context.getTree(e.filePath,e.content),a=Md[o];if(!a||!a[t])throw new Error(`Query ${t} not found for language ${o}`);let i=a[t],c=n.query(i);return{tree:r,captures:c.captures(r.rootNode)}}async findSymbols(e,t,r){return(await this.getSymbols(e,r)).filter(n=>n.name===t).map(n=>({file:e.filePath,line:n.line,column:n.column,kind:n.kind,name:n.name}))}async getSymbols(e,t){let{captures:r}=await this.executeQuery(e,"symbols"),o=[];for(let n of r)if(n.name.startsWith("name.")){let a=n.name.split(".")[1];(!t||t===a)&&o.push({name:n.node.text,kind:a,line:n.node.startPosition.row+1,column:n.node.startPosition.column})}return o}async getImports(e){let{captures:t}=await this.executeQuery(e,"imports"),r=t.filter(n=>n.name==="import").map(n=>n.node),o=[];for(let n of r)o.push({source:n.text,imports:[n.text],line:n.startPosition.row+1,type:"side-effect"});return o}async findReferences(e,t,r){let{captures:o}=await this.executeQuery(e,"references"),n=e.content.split(`
|
|
78
|
+
`),a=[];for(let i of o)if(i.node.text===t){let c=i.node.parent?.type.includes("definition")||i.node.parent?.type.includes("declaration");if(!c||r){let p=i.node.startPosition.row+1;a.push({file:e.filePath,line:p,column:i.node.startPosition.column,context:n[p-1].trim(),isDeclaration:!!c})}}return a}async getSymbolAtPosition(e,t,r){let{tree:o}=await this.context.getTree(e.filePath,e.content),n=o.rootNode.descendantForPosition({row:t-1,column:r});return n&&n.type==="identifier"?n.text:null}async getDefinition(e,t){let r=await this.findSymbols(e,t);return r.length>0?r[0]:null}async getDiagnostics(e){let{tree:t}=await this.context.getTree(e.filePath,e.content),r=[];function o(n){if(n.hasError()){n.type==="ERROR"&&r.push({message:`Syntax error at line ${n.startPosition.row+1}`,line:n.startPosition.row+1,column:n.startPosition.column,severity:"error"});for(let a of n.children)o(a)}else n.isMissing&&n.isMissing()&&r.push({message:`Missing ${n.type} at line ${n.startPosition.row+1}`,line:n.startPosition.row+1,column:n.startPosition.column,severity:"error"})}return o(t.rootNode),r}async getExports(e){return[]}async getOutline(e){return(await this.getSymbols(e)).map(r=>({name:r.name,kind:r.kind,line:r.line,column:r.column,children:[]}))}async extractFunction(e,t,r,o,n,a){let i=e.content.split(`
|
|
79
|
+
`),c=Math.max(0,t-1),p=Math.min(i.length,o),m=i.slice(c,p).join(`
|
|
80
|
+
`),u="",g="",w=e.filePath.split(".").pop()?.toLowerCase();return w==="py"||w==="pyi"?(u=`
|
|
81
81
|
def ${a}():
|
|
82
82
|
${m.split(`
|
|
83
83
|
`).map(y=>" "+y).join(`
|
|
84
84
|
`)}
|
|
85
|
-
`,g=`${a}()`):
|
|
85
|
+
`,g=`${a}()`):w==="go"?(u=`
|
|
86
86
|
func ${a}() {
|
|
87
87
|
${m}
|
|
88
88
|
}
|
|
89
|
-
`,g=`${a}()`):
|
|
89
|
+
`,g=`${a}()`):w==="rs"?(u=`
|
|
90
90
|
fn ${a}() {
|
|
91
91
|
${m}
|
|
92
92
|
}
|
|
93
|
-
`,g=`${a}();`):
|
|
93
|
+
`,g=`${a}();`):w==="sh"||w==="bash"?(u=`
|
|
94
94
|
${a}() {
|
|
95
95
|
${m}
|
|
96
96
|
}
|
|
@@ -98,24 +98,24 @@ ${m}
|
|
|
98
98
|
void ${a}() {
|
|
99
99
|
${m}
|
|
100
100
|
}
|
|
101
|
-
`,g=`${a}();`),{newFunction:u,replacementCall:g}}async getCallHierarchy(e,t,o){let r=await this.getSymbolAtPosition(e,t,o);if(!r)return null;let a=(await this.findReferences(e,r,!1)).map(i=>({file:i.file,name:i.context.trim()||"<anonymous>",line:i.line,column:i.column}));return{file:e.filePath,name:r,line:t,column:o,callers:a,callees:[]}}}});var Tr,Nd=f(()=>{"use strict";l();hs();kd();Ed();Tr=class{constructor(e){this.context=e;this.babelParser=new br,this.treeSitterParser=new xr(this.context)}context;babelParser;treeSitterParser;getParser(e){switch(hr(e)){case"javascript":case"typescript":case"tsx":case"jsx":return this.babelParser;case"python":case"go":case"rust":case"java":case"c":case"cpp":return this.treeSitterParser;default:throw new Error(`Unsupported or unknown language for file: ${e}`)}}}});var It,Cr,Pr,Ad=f(()=>{"use strict";l();It=require("fs"),Cr=require("path");Z();Pr=class{isBuilt=!1;isBuilding=!1;data={symbolLocations:new Map};fileMtimes=new Map;supportedExtensions=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];async getAllSupportedFiles(e){let t=[];try{let o=(0,It.readdirSync)(e,{withFileTypes:!0});for(let r of o){let n=(0,Cr.join)(e,r.name);r.name==="node_modules"||r.name===".git"||r.name==="dist"||r.name==="build"||(r.isDirectory()?t.push(...await this.getAllSupportedFiles(n)):r.isFile()&&this.supportedExtensions.includes((0,Cr.extname)(r.name).toLowerCase())&&t.push(n))}}catch{}return t}async buildIndex(e){if(!(this.isBuilt||this.isBuilding)){this.isBuilding=!0;try{let t=await this.getAllSupportedFiles(e);for(let o of t)await this.updateFile(o);this.isBuilt=!0}finally{this.isBuilding=!1}}}async updateFile(e){try{let o=(0,It.statSync)(e).mtimeMs;if(this.fileMtimes.get(e)===o)return;let r=(0,It.readFileSync)(e,"utf-8"),n=M.getParser(e);this.removeFileFromIndex(e);let a=await n.getSymbols({filePath:e,content:r});for(let i of a){let c=this.data.symbolLocations.get(i.name);c?c.add(e):this.data.symbolLocations.set(i.name,new Set([e]))}this.fileMtimes.set(e,o)}catch{this.removeFileFromIndex(e)}}removeFileFromIndex(e){for(let[t,o]of this.data.symbolLocations.entries())o.delete(e),o.size===0&&this.data.symbolLocations.delete(t);this.fileMtimes.delete(e)}async getDefinitionFiles(e,t){await this.buildIndex(t);let o=this.data.symbolLocations.get(e);return o?Array.from(o):[]}}});var cy,M,jt,Z=f(()=>{"use strict";l();$d();Nd();Ad();cy=new wr,M=new Tr(cy),jt=new Pr});async function Md(s,e,t){try{let o=(0,Ft.readFileSync)(s,"utf-8");return await M.getParser(s).findSymbols({filePath:s,content:o},e,t)}catch{return[]}}async function Od(s,e,t){let o=[];try{let r=(0,Ft.readdirSync)(s,{withFileTypes:!0});for(let n of r){let a=(0,vr.join)(s,n.name);if(!(n.name==="node_modules"||n.name===".git"||n.name==="dist")){if(n.isDirectory()){let i=await Od(a,e,t);o.push(...i)}else if(n.isFile()&&py.includes((0,vr.extname)(n.name))){let i=await Md(a,e,t);o.push(...i)}}}}catch{}return o}async function my(s){let e=s.symbol,t=s.path,o=s.kind;if(h(`[coding.find-symbol] execute symbol="${e}" path="${t}" kind=${o??"all"}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let r=(0,Ft.statSync)(t),n;if(r.isDirectory())n=await Od(t,e,o);else if(r.isFile())n=await Md(t,e,o);else throw new Error(`Path is neither a file nor directory: ${t}`);return JSON.stringify({symbol:e,found:n.length,locations:n},null,2)}var Ft,vr,py,Lt,bs=f(()=>{"use strict";l();Ft=require("fs"),vr=require("path");bd();Z();_();py=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];Lt={name:fd,displayName:gd,description:hd,parameters:wd,category:yd,execute:my}});var Id,jd,Fd,Ld,qd,Ud=f(()=>{"use strict";l();Id="coding.get_symbols",jd="Get Symbols",Fd="List all symbols (functions, classes, variables, etc.) in a JavaScript/TypeScript file",Ld="coding",qd={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["file"]}});async function dy(s){let e=s.file,t=s.kind;if(h(`[coding.get-symbols] execute file="${e}" kind=${t??"all"}`),!e)throw new Error("file is required");try{let o=(0,Wd.readFileSync)(e,"utf-8"),n=await M.getParser(e).getSymbols({filePath:e,content:o},t);return JSON.stringify({file:e,count:n.length,symbols:n},null,2)}catch(o){throw new Error(`Failed to parse file "${e}": ${o.message}`)}}var Wd,qt,xs=f(()=>{"use strict";l();Wd=require("fs");Ud();Z();_();qt={name:Id,displayName:jd,description:Fd,parameters:qd,category:Ld,execute:dy}});var Gd,Bd,Jd,Hd,zd,Kd=f(()=>{"use strict";l();Gd="coding.get_imports",Bd="Get Imports",Jd="List all import statements in a JavaScript/TypeScript file",Hd="coding",zd={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"}},required:["file"]}});async function uy(s){let e=s.file;if(h(`[coding.get-imports] execute file="${e}"`),!e)throw new Error("file is required");try{let t=(0,Qd.readFileSync)(e,"utf-8"),r=await M.getParser(e).getImports({filePath:e,content:t});return JSON.stringify({file:e,count:r.length,imports:r},null,2)}catch(t){throw new Error(`Failed to map explicit imports in file "${e}": ${t.message}`)}}var Qd,Ut,Ts=f(()=>{"use strict";l();Qd=require("fs");Kd();Z();_();Ut={name:Gd,displayName:Bd,description:Jd,parameters:zd,category:Hd,execute:uy}});var Yd,Vd,Xd,Zd,eu,tu=f(()=>{"use strict";l();Yd="coding.find_references",Vd="Find References",Xd="Find all references to a symbol across JavaScript/TypeScript files",Zd="coding",eu={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find references for"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},includeDeclaration:{type:"boolean",description:"Include the symbol declaration in results (default: false)"}},required:["symbol","path"]}});async function ou(s,e,t){try{let o=(0,Sr.readFileSync)(s,"utf-8");return await M.getParser(s).findReferences({filePath:s,content:o},e,t)}catch{return[]}}async function fy(s,e,t){let o=[];await jt.buildIndex(s);let r=await jt.getDefinitionFiles(e,s);for(let n of r)if(n.startsWith(s)){let a=await ou(n,e,t);o.push(...a)}return o}async function gy(s){let e=s.symbol,t=s.path,o=s.includeDeclaration===!0;if(h(`[coding.find-references] execute symbol="${e}" path="${t}" includeDecl=${o}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let r=(0,Sr.statSync)(t),n;if(r.isDirectory())n=await fy(t,e,o);else if(r.isFile())n=await ou(t,e,o);else throw new Error(`Path is neither a file nor directory: ${t}`);return JSON.stringify({symbol:e,found:n.length,references:n},null,2)}var Sr,$r,Ps=f(()=>{"use strict";l();Sr=require("fs");tu();Z();_();$r={name:Yd,displayName:Vd,description:Xd,parameters:eu,category:Zd,execute:gy}});var ru,nu,su,iu,au,lu=f(()=>{"use strict";l();ru="coding.go_to_definition",nu="Go To Definition",su="Jump to the definition of a symbol at a specific location in a file",iu="coding",au={type:"object",properties:{file:{type:"string",description:"Path to the file containing the symbol reference"},line:{type:"integer",description:"Line number where the symbol is referenced (1-indexed)"},column:{type:"integer",description:"Column number where the symbol is referenced (0-indexed)"},searchPath:{type:"string",description:"Optional: directory to search for the definition (defaults to file directory)"}},required:["file","line","column"]}});async function hy(s,e,t){try{let o=(0,po.readFileSync)(s,"utf-8");return await M.getParser(s).getSymbolAtPosition({filePath:s,content:o},e,t)}catch{return null}}async function pu(s,e){try{let t=(0,po.readFileSync)(s,"utf-8");return await M.getParser(s).getDefinition({filePath:s,content:t},e)}catch{return null}}async function yy(s,e){await jt.buildIndex(s);let t=await jt.getDefinitionFiles(e,s);for(let o of t)if(o.startsWith(s)){let r=await pu(o,e);if(r)return r}return null}async function wy(s){let e=s.file,t=s.line,o=s.column,r=s.searchPath;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("line is required");if(o===void 0)throw new Error("column is required");let n=await hy(e,t,o);if(!n)return JSON.stringify({found:!1,message:`No symbol found at ${e}:${t}:${o}`},null,2);let a=await pu(e,n);if(!a){let i=r||(0,cu.dirname)(e);(0,po.statSync)(i).isDirectory()&&(a=await yy(i,n))}return JSON.stringify(a?{found:!0,symbol:n,definition:a}:{found:!1,symbol:n,message:`Definition not found for symbol "${n}"`},null,2)}var po,cu,_r,Cs=f(()=>{"use strict";l();po=require("fs"),cu=require("path");lu();Z();_r={name:ru,displayName:nu,description:su,parameters:au,category:iu,execute:wy}});var mu,du,uu,fu,gu,hu=f(()=>{"use strict";l();mu="coding.multi_file_edit",du="Multi-File Edit",uu="Edit multiple files atomically with rollback on failure",fu="coding",gu={type:"object",properties:{edits:{type:"array",items:{type:"object",properties:{file:{type:"string"},changes:{type:"array",items:{type:"object",properties:{oldText:{type:"string"},newText:{type:"string"}}}}}},description:"Array of file edits, each with file path and array of text replacements"},atomic:{type:"boolean",description:"Atomic mode: rollback all edits if any fails (default: true)"}},required:["edits"]}});async function by(s){let e=s.edits,t=s.atomic!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("edits array is required and must not be empty");for(let n of e){if(!n.file)throw new Error("Each edit must have a file property");if(!n.changes||!Array.isArray(n.changes))throw new Error("Each edit must have a changes array");if(!(0,je.existsSync)(n.file))throw new Error(`File does not exist: ${n.file}`)}let o=[],r=[];try{for(let n of e){let a=(0,je.readFileSync)(n.file,"utf-8");t&&o.push({file:n.file,content:a});let i=a;for(let c of n.changes){if(!c.oldText)throw new Error("Each change must have oldText property");if(c.newText===void 0)throw new Error("Each change must have newText property");let p=(i.match(new RegExp(xy(c.oldText),"g"))||[]).length;if(p===0)throw new Error(`Text not found in ${n.file}: "${c.oldText.substring(0,50)}..."`);if(p>1)throw new Error(`Ambiguous replacement in ${n.file}: "${c.oldText.substring(0,50)}..." appears ${p} times`);i=i.replace(c.oldText,c.newText)}(0,je.writeFileSync)(n.file,i,"utf-8"),r.push(n.file)}return JSON.stringify({success:!0,filesModified:r.length,files:r},null,2)}catch(n){if(t&&o.length>0){for(let a of o)try{(0,je.writeFileSync)(a.file,a.content,"utf-8")}catch{}throw new Error(`Multi-file edit failed and rolled back: ${n.message}`)}throw new Error(`Multi-file edit failed: ${n.message}`)}}function xy(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var je,kr,vs=f(()=>{"use strict";l();je=require("fs");hu();kr={name:mu,displayName:du,description:uu,parameters:gu,category:fu,execute:by}});var yu,wu,bu,xu,Tu,Pu=f(()=>{"use strict";l();yu="coding.refactor_rename",wu="Refactor Rename",bu="Rename a symbol across the entire codebase intelligently",xu="coding",Tu={type:"object",properties:{symbol:{type:"string",description:"Current name of the symbol to rename"},newName:{type:"string",description:"New name for the symbol"},path:{type:"string",description:"Directory path to search and rename in"},dryRun:{type:"boolean",description:"Preview changes without applying them (default: false)"}},required:["symbol","newName","path"]}});function Cy(s,e,t,o){let r=[];try{let n=(0,Wt.readFileSync)(s,"utf-8"),a=n.split(`
|
|
102
|
-
`),i=(0,
|
|
103
|
-
`),"utf-8")}}catch{}return{file:s,occurrences:r.length,changes:r}}function vu(s,e,t,o){let r=[];try{let n=(0,Wt.readdirSync)(s,{withFileTypes:!0});for(let a of n){let i=(0,Rr.join)(s,a.name);if(!(a.name==="node_modules"||a.name===".git"||a.name==="dist")){if(a.isDirectory())r.push(...vu(i,e,t,o));else if(a.isFile()&&Py.includes((0,Rr.extname)(a.name))){let c=Cy(i,e,t,o);c.occurrences>0&&r.push(c)}}}}catch{}return r}async function vy(s){let e=s.symbol,t=s.newName,o=s.path,r=s.dryRun===!0;if(!e)throw new Error("symbol is required");if(!t)throw new Error("newName is required");if(!o)throw new Error("path is required");if(e===t)throw new Error("New name must be different from old name");let n=vu(o,e,t,r),a=n.reduce((c,p)=>c+p.occurrences,0),i=n.length;return JSON.stringify({success:!0,dryRun:r,oldName:e,newName:t,filesAffected:i,totalOccurrences:a,changes:n},null,2)}var Wt,Rr,Cu,Ss,Ty,Py,Dr,$s=f(()=>{"use strict";l();Wt=require("fs"),Rr=require("path"),Cu=require("@babel/parser"),Ss=P(require("@babel/traverse"),1);Pu();Ty=Ss.default||Ss,Py=[".js",".jsx",".ts",".tsx",".mjs",".cjs"];Dr={name:yu,displayName:wu,description:bu,parameters:Tu,category:xu,execute:vy}});var Su,$u,_u,ku,Ru,Du=f(()=>{"use strict";l();Su="coding.get_outline",$u="Get File Outline",_u="Gets a hierarchical outline of symbols (classes, functions, methods) in a specified file.",ku="coding",Ru={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to outline"}},required:["file"]}});async function Sy(s){let e=s.file;if(h(`[coding.get-outline] execute file="${e}"`),!e)throw new Error("file is required");try{if(!(0,Er.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,Er.readFileSync)(e,"utf-8"),o=M.getParser(e);if(!o.getOutline)return JSON.stringify({file:e,error:"Outline extraction is not specifically implemented for this language yet."});let r=await o.getOutline({filePath:e,content:t});return JSON.stringify({file:e,outline:r},null,2)}catch(t){throw new Error(`Failed to safely extract outline from file "${e}": ${t.message}`)}}var Er,Nr,_s=f(()=>{"use strict";l();Er=require("fs");Du();Z();_();Nr={name:Su,displayName:$u,description:_u,parameters:Ru,category:ku,execute:Sy}});var Eu,Nu,Au,Mu,Ou,Iu=f(()=>{"use strict";l();Eu="coding.get_diagnostics",Nu="Get File Diagnostics",Au="Gets syntax errors and warnings for a file utilizing AST parsing.",Mu="coding",Ou={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to check for diagnostics"}},required:["file"]}});async function $y(s){let e=s.file;if(!e)throw new Error("file is required");try{if(!(0,Ar.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,Ar.readFileSync)(e,"utf-8"),o=M.getParser(e);if(!o.getDiagnostics)return JSON.stringify({file:e,error:"Diagnostics extraction is not specifically implemented for this language yet."});let r=await o.getDiagnostics({filePath:e,content:t});return JSON.stringify({file:e,diagnostics:r},null,2)}catch(t){throw new Error(`Failed to get diagnostics from file "${e}": ${t.message}`)}}var Ar,Mr,ks=f(()=>{"use strict";l();Ar=require("fs");Iu();Z();Mr={name:Eu,displayName:Nu,description:Au,parameters:Ou,category:Mu,execute:$y}});var ju,Fu,Lu,qu,Uu,Wu=f(()=>{"use strict";l();ju="coding.get_exports",Fu="Get File Exports",Lu="Lists all symbols exported by a file.",qu="coding",Uu={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"}},required:["file"]}});async function _y(s){let e=s.file;if(h(`[coding.get-exports] execute file="${e}"`),!e)throw new Error("file is required");try{if(!(0,Or.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,Or.readFileSync)(e,"utf-8"),o=M.getParser(e);if(!o.getExports)return JSON.stringify({file:e,error:"Exports extraction is not specifically implemented for this language yet."});let r=await o.getExports({filePath:e,content:t});return JSON.stringify({file:e,exports:r},null,2)}catch(t){throw new Error(`Failed to extract exports from file "${e}": ${t.message}`)}}var Or,Ir,Rs=f(()=>{"use strict";l();Or=require("fs");Wu();Z();_();Ir={name:ju,displayName:Fu,description:Lu,parameters:Uu,category:qu,execute:_y}});var Gu,Bu,Ju,Hu,zu,Ku=f(()=>{"use strict";l();Gu="coding.extract_function",Bu="Extract Function",Ju="Extracts a selected code region into a new function, automatically detecting required parameters and return values.",Hu="coding",zu={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"},startLine:{type:"number",description:"1-indexed start line of the code to extract"},startColumn:{type:"number",description:"0-indexed start column of the code to extract"},endLine:{type:"number",description:"1-indexed end line of the code to extract"},endColumn:{type:"number",description:"0-indexed end column of the code to extract"},newFunctionName:{type:"string",description:"The name for the newly extracted function"}},required:["file","startLine","startColumn","endLine","endColumn","newFunctionName"]}});async function ky(s){let e=s.file,t=s.startLine,o=s.startColumn,r=s.endLine,n=s.endColumn,a=s.newFunctionName;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("startLine is required");if(o===void 0)throw new Error("startColumn is required");if(r===void 0)throw new Error("endLine is required");if(n===void 0)throw new Error("endColumn is required");if(!a)throw new Error("newFunctionName is required");try{if(!(0,jr.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let i=(0,jr.readFileSync)(e,"utf-8"),c=M.getParser(e);if(!c.extractFunction)return JSON.stringify({file:e,error:"Function extraction is not specifically implemented for this language yet."});let p=await c.extractFunction({filePath:e,content:i},t,o,r,n,a);return JSON.stringify({file:e,result:p},null,2)}catch(i){throw new Error(`Failed to extract function from file "${e}": ${i.message}`)}}var jr,Fr,Ds=f(()=>{"use strict";l();jr=require("fs");Ku();Z();Fr={name:Gu,displayName:Bu,description:Ju,parameters:zu,category:Hu,execute:ky}});var Qu,Yu,Vu,Xu,Zu,ef=f(()=>{"use strict";l();Qu="coding.get_call_hierarchy",Yu="Get Call Hierarchy",Vu="Shows callers and callees of a specific function or method.",Xu="coding",Zu={type:"object",properties:{file:{type:"string",description:"The absolute path to the file containing the function"},line:{type:"number",description:"1-indexed line number where the function is defined or called"},column:{type:"number",description:"0-indexed column number where the function is defined or called"}},required:["file","line","column"]}});async function Ry(s){let e=s.file,t=s.line,o=s.column;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("line is required");if(o===void 0)throw new Error("column is required");try{if(!(0,Lr.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let r=(0,Lr.readFileSync)(e,"utf-8"),n=M.getParser(e);if(!n.getCallHierarchy)return JSON.stringify({file:e,error:"Call hierarchy is not specifically implemented for this language yet."});let a=await n.getCallHierarchy({filePath:e,content:r},t,o);return JSON.stringify({file:e,hierarchy:a},null,2)}catch(r){throw new Error(`Failed to get call hierarchy from file "${e}": ${r.message}`)}}var Lr,qr,Es=f(()=>{"use strict";l();Lr=require("fs");ef();Z();qr={name:Qu,displayName:Yu,description:Vu,parameters:Zu,category:Xu,execute:Ry}});var tf={};V(tf,{codingExtractFunctionTool:()=>Fr,codingFindReferencesTool:()=>$r,codingFindSymbolTool:()=>Lt,codingGetCallHierarchyTool:()=>qr,codingGetDiagnosticsTool:()=>Mr,codingGetExportsTool:()=>Ir,codingGetImportsTool:()=>Ut,codingGetOutlineTool:()=>Nr,codingGetSymbolsTool:()=>qt,codingGoToDefinitionTool:()=>_r,codingMultiFileEditTool:()=>kr,codingRefactorRenameTool:()=>Dr,codingToolsProject:()=>Ns});var Ns,As=f(()=>{"use strict";l();bs();xs();Ts();Ps();Cs();vs();$s();_s();ks();Rs();Ds();Es();bs();xs();Ts();Ps();Cs();vs();$s();_s();ks();Rs();Ds();Es();Ns={manifest:{key:"coding",name:"coding-tools",displayName:"Code Intelligence",version:"1.0.0",description:"AST-aware code intelligence tools for finding symbols, references, and analyzing code structure.",author:"Sajeer",tools:["coding.find_symbol","coding.get_symbols","coding.get_imports","coding.find_references","coding.go_to_definition","coding.get_outline","coding.get_diagnostics","coding.get_exports","coding.extract_function","coding.get_call_hierarchy","coding.multi_file_edit","coding.refactor_rename"],category:"coding"},tools:[Lt,qt,Ut,$r,_r,Nr,Mr,Ir,Fr,qr,kr,Dr],dependencies:{"@babel/parser":"^7.24.0","@babel/traverse":"^7.24.0","@babel/types":"^7.24.0"}}});var of,rf=f(()=>{"use strict";l();of={type:"object",properties:{path:{type:"string",description:"Optional path or directory to check the status for. If omitted, checks the entire repository."}}}});function q(s){let e={baseDir:s||process.cwd(),binary:"git",maxConcurrentProcesses:6};return(0,nf.simpleGit)(e)}var nf,ie=f(()=>{"use strict";l();nf=require("simple-git")});var mo,sf=f(()=>{"use strict";l();rf();ie();mo={name:"git.status",displayName:"Git Status",description:"Get the working tree status, including modified, staged, and untracked files.",category:"version-control",parameters:of,execute:async s=>{let e=s.path;try{let o=await q().status(e?[e]:[]);if(o.isClean())return"Working tree clean";let r=[];return r.push(`Branch: ${o.current}`),o.tracking&&r.push(`Tracking: ${o.tracking}`),o.ahead>0&&r.push(`Ahead: ${o.ahead}`),o.behind>0&&r.push(`Behind: ${o.behind}`),r.push("---"),o.conflicted.length>0&&r.push(`Conflicted: ${o.conflicted.join(", ")}`),o.created.length>0&&r.push(`Created: ${o.created.join(", ")}`),o.deleted.length>0&&r.push(`Deleted: ${o.deleted.join(", ")}`),o.modified.length>0&&r.push(`Modified: ${o.modified.join(", ")}`),o.renamed.length>0&&r.push(`Renamed: ${o.renamed.map(n=>`${n.from} -> ${n.to}`).join(", ")}`),o.staged.length>0&&r.push(`Staged: ${o.staged.join(", ")}`),o.not_added.length>0&&r.push(`Untracked: ${o.not_added.join(", ")}`),r.join(`
|
|
104
|
-
`)}catch(t){return`Error getting git status: ${t instanceof Error?t.message:String(t)}`}}}});var
|
|
101
|
+
`,g=`${a}();`),{newFunction:u,replacementCall:g}}async getCallHierarchy(e,t,r){let o=await this.getSymbolAtPosition(e,t,r);if(!o)return null;let a=(await this.findReferences(e,o,!1)).map(i=>({file:i.file,name:i.context.trim()||"<anonymous>",line:i.line,column:i.column}));return{file:e.filePath,name:o,line:t,column:r,callers:a,callees:[]}}}});var Tr,jd=f(()=>{"use strict";l();ws();Ad();Id();Tr=class{constructor(e){this.context=e;this.babelParser=new br,this.treeSitterParser=new xr(this.context)}context;babelParser;treeSitterParser;getParser(e){switch(hr(e)){case"javascript":case"typescript":case"tsx":case"jsx":return this.babelParser;case"python":case"go":case"rust":case"java":case"c":case"cpp":return this.treeSitterParser;default:throw new Error(`Unsupported or unknown language for file: ${e}`)}}}});var Ft,Cr,Pr,Fd=f(()=>{"use strict";l();Ft=require("fs"),Cr=require("path");Z();Pr=class{isBuilt=!1;isBuilding=!1;data={symbolLocations:new Map};fileMtimes=new Map;supportedExtensions=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];async getAllSupportedFiles(e){let t=[];try{let r=(0,Ft.readdirSync)(e,{withFileTypes:!0});for(let o of r){let n=(0,Cr.join)(e,o.name);o.name==="node_modules"||o.name===".git"||o.name==="dist"||o.name==="build"||(o.isDirectory()?t.push(...await this.getAllSupportedFiles(n)):o.isFile()&&this.supportedExtensions.includes((0,Cr.extname)(o.name).toLowerCase())&&t.push(n))}}catch{}return t}async buildIndex(e){if(!(this.isBuilt||this.isBuilding)){this.isBuilding=!0;try{let t=await this.getAllSupportedFiles(e);for(let r of t)await this.updateFile(r);this.isBuilt=!0}finally{this.isBuilding=!1}}}async updateFile(e){try{let r=(0,Ft.statSync)(e).mtimeMs;if(this.fileMtimes.get(e)===r)return;let o=(0,Ft.readFileSync)(e,"utf-8"),n=M.getParser(e);this.removeFileFromIndex(e);let a=await n.getSymbols({filePath:e,content:o});for(let i of a){let c=this.data.symbolLocations.get(i.name);c?c.add(e):this.data.symbolLocations.set(i.name,new Set([e]))}this.fileMtimes.set(e,r)}catch{this.removeFileFromIndex(e)}}removeFileFromIndex(e){for(let[t,r]of this.data.symbolLocations.entries())r.delete(e),r.size===0&&this.data.symbolLocations.delete(t);this.fileMtimes.delete(e)}async getDefinitionFiles(e,t){await this.buildIndex(t);let r=this.data.symbolLocations.get(e);return r?Array.from(r):[]}}});var hy,M,Lt,Z=f(()=>{"use strict";l();Dd();jd();Fd();hy=new wr,M=new Tr(hy),Lt=new Pr});async function Ld(s,e,t){try{let r=(0,qt.readFileSync)(s,"utf-8");return await M.getParser(s).findSymbols({filePath:s,content:r},e,t)}catch{return[]}}async function qd(s,e,t){let r=[];try{let o=(0,qt.readdirSync)(s,{withFileTypes:!0});for(let n of o){let a=(0,vr.join)(s,n.name);if(!(n.name==="node_modules"||n.name===".git"||n.name==="dist")){if(n.isDirectory()){let i=await qd(a,e,t);r.push(...i)}else if(n.isFile()&&yy.includes((0,vr.extname)(n.name))){let i=await Ld(a,e,t);r.push(...i)}}}}catch{}return r}async function wy(s){let e=s.symbol,t=s.path,r=s.kind;if(h(`[coding.find-symbol] execute symbol="${e}" path="${t}" kind=${r??"all"}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let o=(0,qt.statSync)(t),n;if(o.isDirectory())n=await qd(t,e,r);else if(o.isFile())n=await Ld(t,e,r);else throw new Error(`Path is neither a file nor directory: ${t}`);return JSON.stringify({symbol:e,found:n.length,locations:n},null,2)}var qt,vr,yy,Ut,Ts=f(()=>{"use strict";l();qt=require("fs"),vr=require("path");vd();Z();k();yy=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];Ut={name:bd,displayName:xd,description:Td,parameters:Cd,category:Pd,execute:wy}});var Ud,Wd,Gd,Bd,Jd,Hd=f(()=>{"use strict";l();Ud="coding.get_symbols",Wd="Get Symbols",Gd="List all symbols (functions, classes, variables, etc.) in a JavaScript/TypeScript file",Bd="coding",Jd={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["file"]}});async function by(s){let e=s.file,t=s.kind;if(h(`[coding.get-symbols] execute file="${e}" kind=${t??"all"}`),!e)throw new Error("file is required");try{let r=(0,zd.readFileSync)(e,"utf-8"),n=await M.getParser(e).getSymbols({filePath:e,content:r},t);return JSON.stringify({file:e,count:n.length,symbols:n},null,2)}catch(r){throw new Error(`Failed to parse file "${e}": ${r.message}`)}}var zd,Wt,Ps=f(()=>{"use strict";l();zd=require("fs");Hd();Z();k();Wt={name:Ud,displayName:Wd,description:Gd,parameters:Jd,category:Bd,execute:by}});var Kd,Qd,Yd,Vd,Xd,Zd=f(()=>{"use strict";l();Kd="coding.get_imports",Qd="Get Imports",Yd="List all import statements in a JavaScript/TypeScript file",Vd="coding",Xd={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"}},required:["file"]}});async function xy(s){let e=s.file;if(h(`[coding.get-imports] execute file="${e}"`),!e)throw new Error("file is required");try{let t=(0,eu.readFileSync)(e,"utf-8"),o=await M.getParser(e).getImports({filePath:e,content:t});return JSON.stringify({file:e,count:o.length,imports:o},null,2)}catch(t){throw new Error(`Failed to map explicit imports in file "${e}": ${t.message}`)}}var eu,Gt,Cs=f(()=>{"use strict";l();eu=require("fs");Zd();Z();k();Gt={name:Kd,displayName:Qd,description:Yd,parameters:Xd,category:Vd,execute:xy}});var tu,ou,ru,nu,su,iu=f(()=>{"use strict";l();tu="coding.find_references",ou="Find References",ru="Find all references to a symbol across JavaScript/TypeScript files",nu="coding",su={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find references for"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},includeDeclaration:{type:"boolean",description:"Include the symbol declaration in results (default: false)"}},required:["symbol","path"]}});async function au(s,e,t){try{let r=(0,Sr.readFileSync)(s,"utf-8");return await M.getParser(s).findReferences({filePath:s,content:r},e,t)}catch{return[]}}async function Ty(s,e,t){let r=[];await Lt.buildIndex(s);let o=await Lt.getDefinitionFiles(e,s);for(let n of o)if(n.startsWith(s)){let a=await au(n,e,t);r.push(...a)}return r}async function Py(s){let e=s.symbol,t=s.path,r=s.includeDeclaration===!0;if(h(`[coding.find-references] execute symbol="${e}" path="${t}" includeDecl=${r}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let o=(0,Sr.statSync)(t),n;if(o.isDirectory())n=await Ty(t,e,r);else if(o.isFile())n=await au(t,e,r);else throw new Error(`Path is neither a file nor directory: ${t}`);return JSON.stringify({symbol:e,found:n.length,references:n},null,2)}var Sr,$r,vs=f(()=>{"use strict";l();Sr=require("fs");iu();Z();k();$r={name:tu,displayName:ou,description:ru,parameters:su,category:nu,execute:Py}});var lu,cu,pu,mu,du,uu=f(()=>{"use strict";l();lu="coding.go_to_definition",cu="Go To Definition",pu="Jump to the definition of a symbol at a specific location in a file",mu="coding",du={type:"object",properties:{file:{type:"string",description:"Path to the file containing the symbol reference"},line:{type:"integer",description:"Line number where the symbol is referenced (1-indexed)"},column:{type:"integer",description:"Column number where the symbol is referenced (0-indexed)"},searchPath:{type:"string",description:"Optional: directory to search for the definition (defaults to file directory)"}},required:["file","line","column"]}});async function Cy(s,e,t){try{let r=(0,uo.readFileSync)(s,"utf-8");return await M.getParser(s).getSymbolAtPosition({filePath:s,content:r},e,t)}catch{return null}}async function gu(s,e){try{let t=(0,uo.readFileSync)(s,"utf-8");return await M.getParser(s).getDefinition({filePath:s,content:t},e)}catch{return null}}async function vy(s,e){await Lt.buildIndex(s);let t=await Lt.getDefinitionFiles(e,s);for(let r of t)if(r.startsWith(s)){let o=await gu(r,e);if(o)return o}return null}async function Sy(s){let e=s.file,t=s.line,r=s.column,o=s.searchPath;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("line is required");if(r===void 0)throw new Error("column is required");let n=await Cy(e,t,r);if(!n)return JSON.stringify({found:!1,message:`No symbol found at ${e}:${t}:${r}`},null,2);let a=await gu(e,n);if(!a){let i=o||(0,fu.dirname)(e);(0,uo.statSync)(i).isDirectory()&&(a=await vy(i,n))}return JSON.stringify(a?{found:!0,symbol:n,definition:a}:{found:!1,symbol:n,message:`Definition not found for symbol "${n}"`},null,2)}var uo,fu,_r,Ss=f(()=>{"use strict";l();uo=require("fs"),fu=require("path");uu();Z();_r={name:lu,displayName:cu,description:pu,parameters:du,category:mu,execute:Sy}});var hu,yu,wu,bu,xu,Tu=f(()=>{"use strict";l();hu="coding.multi_file_edit",yu="Multi-File Edit",wu="Edit multiple files atomically with rollback on failure",bu="coding",xu={type:"object",properties:{edits:{type:"array",items:{type:"object",properties:{file:{type:"string"},changes:{type:"array",items:{type:"object",properties:{oldText:{type:"string"},newText:{type:"string"}}}}}},description:"Array of file edits, each with file path and array of text replacements"},atomic:{type:"boolean",description:"Atomic mode: rollback all edits if any fails (default: true)"}},required:["edits"]}});async function $y(s){let e=s.edits,t=s.atomic!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("edits array is required and must not be empty");for(let n of e){if(!n.file)throw new Error("Each edit must have a file property");if(!n.changes||!Array.isArray(n.changes))throw new Error("Each edit must have a changes array");if(!(0,Fe.existsSync)(n.file))throw new Error(`File does not exist: ${n.file}`)}let r=[],o=[];try{for(let n of e){let a=(0,Fe.readFileSync)(n.file,"utf-8");t&&r.push({file:n.file,content:a});let i=a;for(let c of n.changes){if(!c.oldText)throw new Error("Each change must have oldText property");if(c.newText===void 0)throw new Error("Each change must have newText property");let p=(i.match(new RegExp(_y(c.oldText),"g"))||[]).length;if(p===0)throw new Error(`Text not found in ${n.file}: "${c.oldText.substring(0,50)}..."`);if(p>1)throw new Error(`Ambiguous replacement in ${n.file}: "${c.oldText.substring(0,50)}..." appears ${p} times`);i=i.replace(c.oldText,c.newText)}(0,Fe.writeFileSync)(n.file,i,"utf-8"),o.push(n.file)}return JSON.stringify({success:!0,filesModified:o.length,files:o},null,2)}catch(n){if(t&&r.length>0){for(let a of r)try{(0,Fe.writeFileSync)(a.file,a.content,"utf-8")}catch{}throw new Error(`Multi-file edit failed and rolled back: ${n.message}`)}throw new Error(`Multi-file edit failed: ${n.message}`)}}function _y(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Fe,kr,$s=f(()=>{"use strict";l();Fe=require("fs");Tu();kr={name:hu,displayName:yu,description:wu,parameters:xu,category:bu,execute:$y}});var Pu,Cu,vu,Su,$u,_u=f(()=>{"use strict";l();Pu="coding.refactor_rename",Cu="Refactor Rename",vu="Rename a symbol across the entire codebase intelligently",Su="coding",$u={type:"object",properties:{symbol:{type:"string",description:"Current name of the symbol to rename"},newName:{type:"string",description:"New name for the symbol"},path:{type:"string",description:"Directory path to search and rename in"},dryRun:{type:"boolean",description:"Preview changes without applying them (default: false)"}},required:["symbol","newName","path"]}});function Ey(s,e,t,r){let o=[];try{let n=(0,Bt.readFileSync)(s,"utf-8"),a=n.split(`
|
|
102
|
+
`),i=(0,ku.parse)(n,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]}),c=[];if(ky(i,{Identifier(p){if(p.node.name===e){let m=p.node.loc?.start.line||0,u=p.node.loc?.start.column||0;c.push({line:m,column:u,length:e.length}),o.push({file:s,line:m,column:u,oldName:e,newName:t})}}}),!r&&c.length>0){c.sort((m,u)=>m.line!==u.line?u.line-m.line:u.column-m.column);let p=[...a];for(let m of c){let u=m.line-1;if(u>=0&&u<p.length){let g=p[u],w=g.substring(0,m.column),y=g.substring(m.column+m.length);p[u]=w+t+y}}(0,Bt.writeFileSync)(s,p.join(`
|
|
103
|
+
`),"utf-8")}}catch{}return{file:s,occurrences:o.length,changes:o}}function Ru(s,e,t,r){let o=[];try{let n=(0,Bt.readdirSync)(s,{withFileTypes:!0});for(let a of n){let i=(0,Rr.join)(s,a.name);if(!(a.name==="node_modules"||a.name===".git"||a.name==="dist")){if(a.isDirectory())o.push(...Ru(i,e,t,r));else if(a.isFile()&&Ry.includes((0,Rr.extname)(a.name))){let c=Ey(i,e,t,r);c.occurrences>0&&o.push(c)}}}}catch{}return o}async function Dy(s){let e=s.symbol,t=s.newName,r=s.path,o=s.dryRun===!0;if(!e)throw new Error("symbol is required");if(!t)throw new Error("newName is required");if(!r)throw new Error("path is required");if(e===t)throw new Error("New name must be different from old name");let n=Ru(r,e,t,o),a=n.reduce((c,p)=>c+p.occurrences,0),i=n.length;return JSON.stringify({success:!0,dryRun:o,oldName:e,newName:t,filesAffected:i,totalOccurrences:a,changes:n},null,2)}var Bt,Rr,ku,_s,ky,Ry,Er,ks=f(()=>{"use strict";l();Bt=require("fs"),Rr=require("path"),ku=require("@babel/parser"),_s=T(require("@babel/traverse"),1);_u();ky=_s.default||_s,Ry=[".js",".jsx",".ts",".tsx",".mjs",".cjs"];Er={name:Pu,displayName:Cu,description:vu,parameters:$u,category:Su,execute:Dy}});var Eu,Du,Nu,Au,Mu,Ou=f(()=>{"use strict";l();Eu="coding.get_outline",Du="Get File Outline",Nu="Gets a hierarchical outline of symbols (classes, functions, methods) in a specified file.",Au="coding",Mu={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to outline"}},required:["file"]}});async function Ny(s){let e=s.file;if(h(`[coding.get-outline] execute file="${e}"`),!e)throw new Error("file is required");try{if(!(0,Dr.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,Dr.readFileSync)(e,"utf-8"),r=M.getParser(e);if(!r.getOutline)return JSON.stringify({file:e,error:"Outline extraction is not specifically implemented for this language yet."});let o=await r.getOutline({filePath:e,content:t});return JSON.stringify({file:e,outline:o},null,2)}catch(t){throw new Error(`Failed to safely extract outline from file "${e}": ${t.message}`)}}var Dr,Nr,Rs=f(()=>{"use strict";l();Dr=require("fs");Ou();Z();k();Nr={name:Eu,displayName:Du,description:Nu,parameters:Mu,category:Au,execute:Ny}});var Iu,ju,Fu,Lu,qu,Uu=f(()=>{"use strict";l();Iu="coding.get_diagnostics",ju="Get File Diagnostics",Fu="Gets syntax errors and warnings for a file utilizing AST parsing.",Lu="coding",qu={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to check for diagnostics"}},required:["file"]}});async function Ay(s){let e=s.file;if(!e)throw new Error("file is required");try{if(!(0,Ar.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,Ar.readFileSync)(e,"utf-8"),r=M.getParser(e);if(!r.getDiagnostics)return JSON.stringify({file:e,error:"Diagnostics extraction is not specifically implemented for this language yet."});let o=await r.getDiagnostics({filePath:e,content:t});return JSON.stringify({file:e,diagnostics:o},null,2)}catch(t){throw new Error(`Failed to get diagnostics from file "${e}": ${t.message}`)}}var Ar,Mr,Es=f(()=>{"use strict";l();Ar=require("fs");Uu();Z();Mr={name:Iu,displayName:ju,description:Fu,parameters:qu,category:Lu,execute:Ay}});var Wu,Gu,Bu,Ju,Hu,zu=f(()=>{"use strict";l();Wu="coding.get_exports",Gu="Get File Exports",Bu="Lists all symbols exported by a file.",Ju="coding",Hu={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"}},required:["file"]}});async function My(s){let e=s.file;if(h(`[coding.get-exports] execute file="${e}"`),!e)throw new Error("file is required");try{if(!(0,Or.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,Or.readFileSync)(e,"utf-8"),r=M.getParser(e);if(!r.getExports)return JSON.stringify({file:e,error:"Exports extraction is not specifically implemented for this language yet."});let o=await r.getExports({filePath:e,content:t});return JSON.stringify({file:e,exports:o},null,2)}catch(t){throw new Error(`Failed to extract exports from file "${e}": ${t.message}`)}}var Or,Ir,Ds=f(()=>{"use strict";l();Or=require("fs");zu();Z();k();Ir={name:Wu,displayName:Gu,description:Bu,parameters:Hu,category:Ju,execute:My}});var Ku,Qu,Yu,Vu,Xu,Zu=f(()=>{"use strict";l();Ku="coding.extract_function",Qu="Extract Function",Yu="Extracts a selected code region into a new function, automatically detecting required parameters and return values.",Vu="coding",Xu={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"},startLine:{type:"number",description:"1-indexed start line of the code to extract"},startColumn:{type:"number",description:"0-indexed start column of the code to extract"},endLine:{type:"number",description:"1-indexed end line of the code to extract"},endColumn:{type:"number",description:"0-indexed end column of the code to extract"},newFunctionName:{type:"string",description:"The name for the newly extracted function"}},required:["file","startLine","startColumn","endLine","endColumn","newFunctionName"]}});async function Oy(s){let e=s.file,t=s.startLine,r=s.startColumn,o=s.endLine,n=s.endColumn,a=s.newFunctionName;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("startLine is required");if(r===void 0)throw new Error("startColumn is required");if(o===void 0)throw new Error("endLine is required");if(n===void 0)throw new Error("endColumn is required");if(!a)throw new Error("newFunctionName is required");try{if(!(0,jr.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let i=(0,jr.readFileSync)(e,"utf-8"),c=M.getParser(e);if(!c.extractFunction)return JSON.stringify({file:e,error:"Function extraction is not specifically implemented for this language yet."});let p=await c.extractFunction({filePath:e,content:i},t,r,o,n,a);return JSON.stringify({file:e,result:p},null,2)}catch(i){throw new Error(`Failed to extract function from file "${e}": ${i.message}`)}}var jr,Fr,Ns=f(()=>{"use strict";l();jr=require("fs");Zu();Z();Fr={name:Ku,displayName:Qu,description:Yu,parameters:Xu,category:Vu,execute:Oy}});var ef,tf,of,rf,nf,sf=f(()=>{"use strict";l();ef="coding.get_call_hierarchy",tf="Get Call Hierarchy",of="Shows callers and callees of a specific function or method.",rf="coding",nf={type:"object",properties:{file:{type:"string",description:"The absolute path to the file containing the function"},line:{type:"number",description:"1-indexed line number where the function is defined or called"},column:{type:"number",description:"0-indexed column number where the function is defined or called"}},required:["file","line","column"]}});async function Iy(s){let e=s.file,t=s.line,r=s.column;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("line is required");if(r===void 0)throw new Error("column is required");try{if(!(0,Lr.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let o=(0,Lr.readFileSync)(e,"utf-8"),n=M.getParser(e);if(!n.getCallHierarchy)return JSON.stringify({file:e,error:"Call hierarchy is not specifically implemented for this language yet."});let a=await n.getCallHierarchy({filePath:e,content:o},t,r);return JSON.stringify({file:e,hierarchy:a},null,2)}catch(o){throw new Error(`Failed to get call hierarchy from file "${e}": ${o.message}`)}}var Lr,qr,As=f(()=>{"use strict";l();Lr=require("fs");sf();Z();qr={name:ef,displayName:tf,description:of,parameters:nf,category:rf,execute:Iy}});var af={};V(af,{codingExtractFunctionTool:()=>Fr,codingFindReferencesTool:()=>$r,codingFindSymbolTool:()=>Ut,codingGetCallHierarchyTool:()=>qr,codingGetDiagnosticsTool:()=>Mr,codingGetExportsTool:()=>Ir,codingGetImportsTool:()=>Gt,codingGetOutlineTool:()=>Nr,codingGetSymbolsTool:()=>Wt,codingGoToDefinitionTool:()=>_r,codingMultiFileEditTool:()=>kr,codingRefactorRenameTool:()=>Er,codingToolsProject:()=>Ms});var Ms,Os=f(()=>{"use strict";l();Ts();Ps();Cs();vs();Ss();$s();ks();Rs();Es();Ds();Ns();As();Ts();Ps();Cs();vs();Ss();$s();ks();Rs();Es();Ds();Ns();As();Ms={manifest:{key:"coding",name:"coding-tools",displayName:"Code Intelligence",version:"1.0.0",description:"AST-aware code intelligence tools for finding symbols, references, and analyzing code structure.",author:"Sajeer",tools:["coding.find_symbol","coding.get_symbols","coding.get_imports","coding.find_references","coding.go_to_definition","coding.get_outline","coding.get_diagnostics","coding.get_exports","coding.extract_function","coding.get_call_hierarchy","coding.multi_file_edit","coding.refactor_rename"],category:"coding"},tools:[Ut,Wt,Gt,$r,_r,Nr,Mr,Ir,Fr,qr,kr,Er],dependencies:{"@babel/parser":"^7.24.0","@babel/traverse":"^7.24.0","@babel/types":"^7.24.0"}}});var lf,cf=f(()=>{"use strict";l();lf={type:"object",properties:{path:{type:"string",description:"Optional path or directory to check the status for. If omitted, checks the entire repository."}}}});function q(s){let e={baseDir:s||process.cwd(),binary:"git",maxConcurrentProcesses:6};return(0,pf.simpleGit)(e)}var pf,ie=f(()=>{"use strict";l();pf=require("simple-git")});var fo,mf=f(()=>{"use strict";l();cf();ie();fo={name:"git.status",displayName:"Git Status",description:"Get the working tree status, including modified, staged, and untracked files.",category:"version-control",parameters:lf,execute:async s=>{let e=s.path;try{let r=await q().status(e?[e]:[]);if(r.isClean())return"Working tree clean";let o=[];return o.push(`Branch: ${r.current}`),r.tracking&&o.push(`Tracking: ${r.tracking}`),r.ahead>0&&o.push(`Ahead: ${r.ahead}`),r.behind>0&&o.push(`Behind: ${r.behind}`),o.push("---"),r.conflicted.length>0&&o.push(`Conflicted: ${r.conflicted.join(", ")}`),r.created.length>0&&o.push(`Created: ${r.created.join(", ")}`),r.deleted.length>0&&o.push(`Deleted: ${r.deleted.join(", ")}`),r.modified.length>0&&o.push(`Modified: ${r.modified.join(", ")}`),r.renamed.length>0&&o.push(`Renamed: ${r.renamed.map(n=>`${n.from} -> ${n.to}`).join(", ")}`),r.staged.length>0&&o.push(`Staged: ${r.staged.join(", ")}`),r.not_added.length>0&&o.push(`Untracked: ${r.not_added.join(", ")}`),o.join(`
|
|
104
|
+
`)}catch(t){return`Error getting git status: ${t instanceof Error?t.message:String(t)}`}}}});var df,uf=f(()=>{"use strict";l();df={type:"object",properties:{path:{type:"string",description:"Optional path to get the diff for. If omitted, gets the diff for the entire repository."},staged:{type:"boolean",description:"If true, gets the diff of staged changes instead of unstaged changes.",default:!1}}}});var go,ff=f(()=>{"use strict";l();uf();ie();go={name:"git.diff",displayName:"Git Diff",description:"Show changes between commits, commit and working tree, etc.",category:"version-control",parameters:df,execute:async s=>{let e=s.path,t=s.staged;try{let r=q(),o=[];t&&o.push("--cached"),e&&o.push("--",e);let n=await r.diff(o);return n||"No changes found."}catch(r){return`Error getting git diff: ${r instanceof Error?r.message:String(r)}`}}}});var gf,hf=f(()=>{"use strict";l();gf={type:"object",properties:{maxCount:{type:"number",description:"Maximum number of commits to return. Defaults to 10 to prevent large outputs.",default:10},path:{type:"string",description:"Optional path to get the log for specific file or directory."}}}});var ho,yf=f(()=>{"use strict";l();hf();ie();ho={name:"git.log",displayName:"Git Log",description:"Show commit logs.",category:"version-control",parameters:gf,execute:async s=>{let e=s.maxCount||10,t=s.path;try{let r=q(),o={maxCount:e};t&&(o.file=t);let n=await r.log(o);return n.all.length===0?"No commits found.":n.all.map(a=>`Commit: ${a.hash}
|
|
105
105
|
Author: ${a.author_name} <${a.author_email}>
|
|
106
106
|
Date: ${a.date}
|
|
107
107
|
Message: ${a.message}
|
|
108
108
|
`).join(`---
|
|
109
|
-
`)}catch(
|
|
110
|
-
Commit: ${
|
|
111
|
-
Branch: ${
|
|
112
|
-
Summary: ${
|
|
109
|
+
`)}catch(r){return`Error getting git log: ${r instanceof Error?r.message:String(r)}`}}}});var wf,bf=f(()=>{"use strict";l();wf={type:"object",properties:{path:{type:"string",description:"Path to the file or directory to stage. To stage all changes, use '.'."}},required:["path"]}});var yo,xf=f(()=>{"use strict";l();bf();ie();yo={name:"git.add",displayName:"Git Add",description:"Add file contents to the index (stage changes).",category:"version-control",parameters:wf,execute:async s=>{let e=s.path;try{return await q().add(e),`Successfully staged changes for: ${e}`}catch(t){return`Error staging changes: ${t instanceof Error?t.message:String(t)}`}}}});var Tf,Pf=f(()=>{"use strict";l();Tf={type:"object",properties:{message:{type:"string",description:"The commit message."}},required:["message"]}});var wo,Cf=f(()=>{"use strict";l();Pf();ie();wo={name:"git.commit",displayName:"Git Commit",description:"Record changes to the repository.",category:"version-control",parameters:Tf,execute:async s=>{let e=s.message;try{let r=await q().commit(e);return r.commit?`Successfully committed changes.
|
|
110
|
+
Commit: ${r.commit}
|
|
111
|
+
Branch: ${r.branch}
|
|
112
|
+
Summary: ${r.summary.changes} changes, ${r.summary.insertions} insertions, ${r.summary.deletions} deletions.`:"Nothing to commit."}catch(t){return`Error committing changes: ${t instanceof Error?t.message:String(t)}`}}}});var vf,Sf=f(()=>{"use strict";l();vf={type:"object",properties:{path:{type:"string",description:"Path to the file to blame."}},required:["path"]}});var bo,$f=f(()=>{"use strict";l();Sf();ie();bo={name:"git.blame",displayName:"Git Blame",description:"Show what revision and author last modified each line of a file.",category:"version-control",parameters:vf,execute:async s=>{let e=s.path;try{return await q().raw(["blame",e])}catch(t){return`Error running git blame: ${t instanceof Error?t.message:String(t)}`}}}});var _f,kf=f(()=>{"use strict";l();_f={type:"object",properties:{remote:{type:"boolean",description:"List remote branches as well.",default:!1}}}});var xo,Rf=f(()=>{"use strict";l();kf();ie();xo={name:"git.branch_list",displayName:"Git Branch List",description:"List all branches.",category:"version-control",parameters:_f,execute:async s=>{let e=s.remote;try{let t=q(),r=e?["-a"]:[],o=await t.branch(r);return`Current Branch: ${o.current}
|
|
113
113
|
|
|
114
114
|
Branches:
|
|
115
|
-
${
|
|
116
|
-
`)}`}catch(t){return`Error listing branches: ${t instanceof Error?t.message:String(t)}`}}}});var
|
|
115
|
+
${o.all.join(`
|
|
116
|
+
`)}`}catch(t){return`Error listing branches: ${t instanceof Error?t.message:String(t)}`}}}});var Ef,Df=f(()=>{"use strict";l();Ef={type:"object",properties:{name:{type:"string",description:"Name of the new branch."},checkout:{type:"boolean",description:"Whether to checkout the new branch after creating it.",default:!1},startPoint:{type:"string",description:"Optional start point (commit hash or branch name) for the new branch."}},required:["name"]}});var To,Nf=f(()=>{"use strict";l();Df();ie();To={name:"git.branch_create",displayName:"Git Branch Create",description:"Create a new branch.",category:"version-control",parameters:Ef,execute:async s=>{let e=s.name,t=s.checkout,r=s.startPoint;try{let o=q();return t?(r?await o.checkoutBranch(e,r):await o.checkoutLocalBranch(e),`Successfully created and switched to branch: ${e}`):(r?await o.branch([e,r]):await o.branch([e]),`Successfully created branch: ${e}`)}catch(o){return`Error creating branch: ${o instanceof Error?o.message:String(o)}`}}}});var Af,Mf=f(()=>{"use strict";l();Af={type:"object",properties:{branch:{type:"string",description:"Name of the branch or commit to checkout."}},required:["branch"]}});var Po,Of=f(()=>{"use strict";l();Mf();ie();Po={name:"git.checkout",displayName:"Git Checkout",description:"Switch branches or restore working tree files.",category:"version-control",parameters:Af,execute:async s=>{let e=s.branch;try{return await q().checkout(e),`Successfully checked out: ${e}`}catch(t){return`Error checking out branch: ${t instanceof Error?t.message:String(t)}`}}}});var If={};V(If,{gitAddTool:()=>yo,gitBlameTool:()=>bo,gitBranchCreateTool:()=>To,gitBranchListTool:()=>xo,gitCheckoutTool:()=>Po,gitCommitTool:()=>wo,gitDiffTool:()=>go,gitLogTool:()=>ho,gitStatusTool:()=>fo,gitToolsProject:()=>Is});var Is,js=f(()=>{"use strict";l();mf();ff();yf();xf();Cf();$f();Rf();Nf();Of();Is={manifest:{key:"git",name:"git-tools",displayName:"Git Version Control",version:"1.0.0",description:"Git operations for reading repository state, checking diffs, creating commits, and managing branches.",author:"Sajeer",tools:["git.status","git.diff","git.log","git.add","git.commit","git.blame","git.branch_list","git.branch_create","git.checkout"],category:"version-control"},tools:[fo,go,ho,yo,wo,bo,xo,To,Po],dependencies:{"simple-git":"^3.27.0"}}});var jf,Ff=f(()=>{"use strict";l();jf={type:"object",properties:{oldContent:{type:"string",description:"The original text content."},newContent:{type:"string",description:"The new text content."},fileName:{type:"string",description:"Optional filename to include in the patch header."},contextLines:{type:"number",description:"Number of context lines to include around differences. Default is 4.",default:4}},required:["oldContent","newContent"]}});var Lf,Co,qf=f(()=>{"use strict";l();Ff();Lf=T(require("diff"),1);k();Co={name:"diff.create",displayName:"Create Diff",description:"Generate a unified diff from two text contents.",category:"diff",parameters:jf,execute:async s=>{let e=s.oldContent,t=s.newContent,r=s.fileName||"file",o=s.contextLines??4;h(`[diff.create] execute fileName="${r}" contextLines=${o}`);try{return Lf.createPatch(r,e,t,"","",{context:o})}catch(n){return`Error creating diff: ${n instanceof Error?n.message:String(n)}`}}}});var Uf,Wf=f(()=>{"use strict";l();Uf={type:"object",properties:{path:{type:"string",description:"Path to the file to patch."},patch:{type:"string",description:"Unified diff string to apply."}},required:["path","patch"]}});var Gf,Fs,vo,Bf=f(()=>{"use strict";l();Wf();Gf=T(require("diff"),1),Fs=require("fs");k();vo={name:"diff.apply",displayName:"Apply Diff",description:"Apply a unified diff patch to a file.",category:"diff",parameters:Uf,execute:async s=>{let e=s.path,t=s.patch;h(`[diff.apply] execute path="${e}"`);try{let r=await Fs.promises.readFile(e,"utf8"),o=Gf.applyPatch(r,t);return o===!1?"Failed to apply patch. The patch may be malformed or conflicting with the current file content.":(await Fs.promises.writeFile(e,o,"utf8"),`Successfully applied patch to ${e}`)}catch(r){return`Error applying patch: ${r instanceof Error?r.message:String(r)}`}}}});var Jf,Hf=f(()=>{"use strict";l();Jf={type:"object",properties:{path:{type:"string",description:"Path to the file to apply the patch against for preview."},patch:{type:"string",description:"Unified diff string to preview."}},required:["path","patch"]}});var zf,Kf,So,Qf=f(()=>{"use strict";l();Hf();zf=T(require("diff"),1),Kf=require("fs"),So={name:"diff.preview",displayName:"Preview Diff",description:"Preview the result of applying a patch to a file without modifying it.",category:"diff",parameters:Jf,execute:async s=>{let e=s.path,t=s.patch;try{let r=await Kf.promises.readFile(e,"utf8"),o=zf.applyPatch(r,t);return o===!1?"Patch preview failed. The patch would not apply cleanly.":`Preview of ${e} after patch:
|
|
117
117
|
|
|
118
|
-
${
|
|
118
|
+
${o}`}catch(r){return`Error previewing patch: ${r instanceof Error?r.message:String(r)}`}}}});var Yf={};V(Yf,{diffApplyTool:()=>vo,diffCreateTool:()=>Co,diffPreviewTool:()=>So,diffToolsProject:()=>Ls});var Ls,qs=f(()=>{"use strict";l();qf();Bf();Qf();Ls={manifest:{key:"diff",name:"diff-tools",displayName:"Diff and Patch",version:"1.0.0",description:"Tools to create and apply unified diff changes to files safely.",author:"Sajeer",tools:["diff.create","diff.apply","diff.preview"],category:"diff"},tools:[Co,vo,So],dependencies:{diff:"^7.0.0"}}});var Vf,Xf=f(()=>{"use strict";l();Vf={type:"object",properties:{db:{type:"string",description:"Database connection URI (e.g. postgres://user:pass@host/db, mysql://...) or local SQLite file path (.sqlite, .db)"},sql:{type:"string",description:"The SQL query to execute"},params:{type:"array",description:"Optional array of parameters for parameterized queries (to prevent SQL injection)",items:{},default:[]}},required:["db","sql"]}});var Se,Ur=f(()=>{"use strict";l();Se=class{connectionString;constructor(e){this.connectionString=e}}});var Us,Ws,$o,Zf=f(()=>{"use strict";l();Us=T(require("better-sqlite3"),1),Ws=T(require("fs"),1);Ur();$o=class extends Se{getDb(){if(!Ws.existsSync(this.connectionString))throw new Error(`Database file not found: ${this.connectionString}`);return new Us.default(this.connectionString,{readonly:!1})}async query(e,t=[]){let r=this.getDb();try{let o=r.prepare(e);return o.reader?o.all(t):(o.run(t),[])}finally{r.close()}}async execute(e,t=[]){let r=this.getDb();try{let n=r.prepare(e).run(t);return{changes:n.changes,lastInsertRowid:n.lastInsertRowid,raw:n}}finally{r.close()}}async getTables(){return(await this.query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")).map(r=>r.name)}async getSchema(e){return e?await this.query(`PRAGMA table_info("${e}")`):await this.query("SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")}static executeSession(e,t,r=[]){if(!Ws.existsSync(e))throw new Error(`Database file not found: ${e}`);let o=new Us.default(e,{readonly:!1});try{let n=o.prepare(t);return n.reader?n.all(r):n.run(r)}finally{o.close()}}}});var eg,Wr,tg=f(()=>{"use strict";l();eg=T(require("pg"),1);Ur();Wr=class extends Se{async getClient(){let e=new eg.default.Client({connectionString:this.connectionString});return await e.connect(),e}convertSql(e){let t=1;return e.replace(/\?/g,()=>`$${t++}`)}async query(e,t=[]){let r=await this.getClient();try{let o=this.convertSql(e);return(await r.query(o,t)).rows}finally{await r.end()}}async execute(e,t=[]){let r=await this.getClient();try{let o=this.convertSql(e),n=await r.query(o,t);return{changes:n.rowCount??0,raw:n}}finally{await r.end()}}async getTables(){return(await this.query("SELECT tablename as name FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema'")).map(r=>r.name)}async getSchema(e){return e?await this.query(`
|
|
119
119
|
SELECT column_name, data_type, is_nullable, column_default
|
|
120
120
|
FROM information_schema.columns
|
|
121
121
|
WHERE table_name = $1
|
|
@@ -123,21 +123,21 @@ ${r}`}catch(o){return`Error previewing patch: ${o instanceof Error?o.message:Str
|
|
|
123
123
|
SELECT table_name as name, table_type
|
|
124
124
|
FROM information_schema.tables
|
|
125
125
|
WHERE table_schema = 'public'
|
|
126
|
-
`)}}});var Vf,Gr,Xf=f(()=>{"use strict";l();Vf=P(require("mysql2/promise"),1);Ur();Gr=class extends Se{async getConnection(){return await Vf.default.createConnection(this.connectionString)}async query(e,t=[]){let o=await this.getConnection();try{let[r]=await o.execute(e,t);return r}finally{await o.end()}}async execute(e,t=[]){let o=await this.getConnection();try{let[r]=await o.execute(e,t);return{changes:r.affectedRows,lastInsertRowid:r.insertId,raw:r}}finally{await o.end()}}async getTables(){let t=await this.query("SHOW TABLES");if(!t||t.length===0)return[];let o=Object.keys(t[0]);return t.map(r=>r[o[0]])}async getSchema(e){if(e){let t=await this.getConnection();try{let[o]=await t.query("DESCRIBE ??",[e]);return o}finally{await t.end()}}else return await this.query("SHOW TABLES")}}});var G,$e=f(()=>{"use strict";l();Kf();Yf();Xf();G=class{static getAdapter(e){return e.startsWith("postgres://")||e.startsWith("postgresql://")?new Wr(e):e.startsWith("mysql://")?new Gr(e):e.startsWith("sqlite://")?new vo(e.replace("sqlite://","")):new vo(e)}}});var So,Zf=f(()=>{"use strict";l();zf();$e();_();So={name:"db.query",displayName:"Database Query",description:"Execute raw SQL queries against an SQLite, PostgreSQL, or MySQL database.",category:"database",parameters:Hf,execute:async s=>{let e=s.db,t=s.sql,o=s.params||[];h(`[db.query] execute db="${e}" sql="${t.substring(0,80)}..." params=${o.length}`);try{let n=await G.getAdapter(e).query(t,o);return JSON.stringify(n,null,2)}catch(r){return`Database query error: ${r instanceof Error?r.message:String(r)}`}}}});var eg,tg=f(()=>{"use strict";l();eg={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Optional specific table name to inspect. If omitted, returns structural summary of all tables."}},required:["db"]}});var $o,og=f(()=>{"use strict";l();tg();$e();$o={name:"db.schema",displayName:"Database Schema",description:"Get the structural schema of a database or a specific table.",category:"database",parameters:eg,execute:async s=>{let e=s.db,t=s.table;try{let r=await G.getAdapter(e).getSchema(t);return JSON.stringify(r,null,2)}catch(o){return`Database schema error: ${o instanceof Error?o.message:String(o)}`}}}});var rg,ng=f(()=>{"use strict";l();rg={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"}},required:["db"]}});var _o,sg=f(()=>{"use strict";l();ng();$e();_o={name:"db.tables",displayName:"Database Tables",description:"List all user tables in the database.",category:"database",parameters:rg,execute:async s=>{let e=s.db;try{let o=await G.getAdapter(e).getTables();return JSON.stringify(o,null,2)}catch(t){return`Database tables error: ${t instanceof Error?t.message:String(t)}`}}}});var ig,ag=f(()=>{"use strict";l();ig={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to insert into"},data:{type:"object",description:"Key-value pairs of column names and values to insert"}},required:["db","table","data"]}});var ko,lg=f(()=>{"use strict";l();ag();$e();ko={name:"db.insert",displayName:"Database Insert",description:"Insert a new row into an SQLite table safely.",category:"database",parameters:ig,execute:async s=>{let e=s.db,t=s.table,o=s.data;if(Object.keys(o).length===0)return"Error: No data provided to insert.";try{let r=Object.keys(o).join(", "),n=Object.keys(o).map(()=>"?").join(", "),a=Object.values(o),i=`INSERT INTO ${t} (${r}) VALUES (${n})`,p=await G.getAdapter(e).execute(i,a);return JSON.stringify(p,null,2)}catch(r){return`Database insert error: ${r instanceof Error?r.message:String(r)}`}}}});var cg,pg=f(()=>{"use strict";l();cg={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to update"},data:{type:"object",description:"Key-value pairs of column names and new values"},where:{type:"string",description:'WHERE clause condition (e.g. "id = 5"). DO NOT INCLUDE the word WHERE.'}},required:["db","table","data","where"]}});var Ro,mg=f(()=>{"use strict";l();pg();$e();Ro={name:"db.update",displayName:"Database Update",description:"Update existing rows in a database table.",category:"database",parameters:cg,execute:async s=>{let e=s.db,t=s.table,o=s.data,r=s.where;if(Object.keys(o).length===0)return"Error: No data provided to update.";try{let n=Object.keys(o).map(m=>`${m} = ?`).join(", "),a=Object.values(o),i=`UPDATE ${t} SET ${n} WHERE ${r}`,p=await G.getAdapter(e).execute(i,a);return JSON.stringify(p,null,2)}catch(n){return`Database update error: ${n instanceof Error?n.message:String(n)}`}}}});var dg,ug=f(()=>{"use strict";l();dg={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to delete from"},where:{type:"string",description:'WHERE clause condition (e.g. "id = 5"). DO NOT INCLUDE the word WHERE.'}},required:["db","table","where"]}});var Do,fg=f(()=>{"use strict";l();ug();$e();Do={name:"db.delete",displayName:"Database Delete",description:"Delete rows from a database table.",category:"database",parameters:dg,execute:async s=>{let e=s.db,t=s.table,o=s.where;try{let r=`DELETE FROM ${t} WHERE ${o}`,a=await G.getAdapter(e).execute(r);return JSON.stringify(a,null,2)}catch(r){return`Database delete error: ${r instanceof Error?r.message:String(r)}`}}}});var gg,hg=f(()=>{"use strict";l();gg={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to count rows from"},where:{type:"string",description:"Optional WHERE clause condition"}},required:["db","table"]}});var Eo,yg=f(()=>{"use strict";l();hg();$e();Eo={name:"db.count",displayName:"Database Count",description:"Count rows in a database table.",category:"database",parameters:gg,execute:async s=>{let e=s.db,t=s.table,o=s.where;try{let r=o?`WHERE ${o}`:"",n=`SELECT COUNT(*) as count FROM ${t} ${r}`,i=await G.getAdapter(e).query(n);return Array.isArray(i)&&i.length>0?`Rows: ${i[0].count}`:"Count: 0"}catch(r){return`Database count error: ${r instanceof Error?r.message:String(r)}`}}}});var wg={};V(wg,{dbCountTool:()=>Eo,dbDeleteTool:()=>Do,dbInsertTool:()=>ko,dbQueryTool:()=>So,dbSchemaTool:()=>$o,dbTablesTool:()=>_o,dbToolsProject:()=>Us,dbUpdateTool:()=>Ro});var Us,Ws=f(()=>{"use strict";l();Zf();og();sg();lg();mg();fg();yg();Us={manifest:{key:"db",name:"db-tools",displayName:"Database Tools",version:"1.0.0",description:"Stateless database operations enabling the AI to interact with local databases.",author:"Sajeer",tools:["db.query","db.schema","db.tables","db.insert","db.update","db.delete","db.count"],category:"database"},tools:[So,$o,_o,ko,Ro,Do,Eo],dependencies:{"better-sqlite3":"^11.3.0"}}});var bg,xg=f(()=>{"use strict";l();bg={type:"object",properties:{siteId:{type:"string",description:'The Netlify Site ID to deploy to (e.g. "api_id" from Netlify UI)'},dir:{type:"string",description:'The local directory path to deploy (e.g. "./dist" or "./public")'},message:{type:"string",description:"Optional deployment message/commit note"}},required:["siteId","dir"]}});var Tg,_e,Br=f(()=>{"use strict";l();Tg=require("netlify"),_e=class{static getClient(){let e=process.env.NETLIFY_AUTH_TOKEN;if(!e)throw new Error("NETLIFY_AUTH_TOKEN environment variable is required to use Netlify cloud tools.");return new Tg.NetlifyAPI(e)}}});var No,Pg=f(()=>{"use strict";l();xg();Br();_();No={name:"cloud.deploy",displayName:"Cloud Deploy",description:"Deploy a static directory to Netlify.",category:"cloud",parameters:bg,execute:async s=>{let e=s.siteId,t=s.dir,o=s.message;h(`[cloud.deploy] execute siteId="${e}" dir="${t}" message="${o??"none"}"`);try{let n=await _e.getClient().deploy(e,t,{message:o||"Deployed via Toolpack SDK",draft:!1});return JSON.stringify({id:n.deployId,url:n.deploy.url,admin_url:n.deploy.admin_url,state:n.deploy.state},null,2)}catch(r){return`Cloud deployment error: ${r instanceof Error?r.message:String(r)}`}}}});var Cg,vg=f(()=>{"use strict";l();Cg={type:"object",properties:{siteId:{type:"string",description:"The Netlify Site ID"},deployId:{type:"string",description:"The specific Deployment ID to check"}},required:["siteId","deployId"]}});var Ao,Sg=f(()=>{"use strict";l();vg();Br();Ao={name:"cloud.status",displayName:"Cloud Status",description:"Check the status of a specific Netlify deployment.",category:"cloud",parameters:Cg,execute:async s=>{let e=s.siteId,t=s.deployId;try{let r=await _e.getClient().getSiteDeploy({site_id:e,deploy_id:t});return JSON.stringify({id:r.id,state:r.state,error_message:r.error_message,created_at:r.created_at,updated_at:r.updated_at,url:r.url},null,2)}catch(o){return`Cloud status error: ${o instanceof Error?o.message:String(o)}`}}}});var $g,_g=f(()=>{"use strict";l();$g={type:"object",properties:{siteId:{type:"string",description:"The Netlify Site ID"},limit:{type:"number",description:"Number of recent deployments to return. Defaults to 5.",default:5}},required:["siteId"]}});var Mo,kg=f(()=>{"use strict";l();_g();Br();_();Mo={name:"cloud.list",displayName:"Cloud Deployments List",description:"List recent deployments for a Netlify site.",category:"cloud",parameters:$g,execute:async s=>{let e=s.siteId,t=s.limit||5;h(`[cloud.list] execute siteId="${e}" limit=${t}`);try{let r=await _e.getClient().listSiteDeploys({site_id:e,page:1,per_page:t});if(!Array.isArray(r))return"Unexpected response format from Netlify API";let n=r.map(a=>({id:a.id,state:a.state,created_at:a.created_at,url:a.url,branch:a.branch,title:a.title}));return JSON.stringify(n,null,2)}catch(o){return`Cloud list error: ${o instanceof Error?o.message:String(o)}`}}}});var Rg={};V(Rg,{cloudDeployTool:()=>No,cloudListTool:()=>Mo,cloudStatusTool:()=>Ao,cloudToolsProject:()=>Gs});var Gs,Bs=f(()=>{"use strict";l();Pg();Sg();kg();Gs={manifest:{key:"cloud",name:"cloud-tools",displayName:"Cloud Deployment",version:"1.0.0",description:"Cloud deployment operations allowing the AI to publish directories directly to the internet.",author:"Sajeer",tools:["cloud.deploy","cloud.status","cloud.list"],category:"cloud"},tools:[No,Ao,Mo],dependencies:{netlify:"^13.1.20"}}});var jy={};V(jy,{AGENT_MODE:()=>Js,AIClient:()=>Xt,AnthropicAdapter:()=>eo,AuthenticationError:()=>pe,BM25SearchEngine:()=>We,BUILT_IN_MODES:()=>jo,CHAT_MODE:()=>Hs,CONFIG_DIR_NAME:()=>Ys,CONFIG_FILE_NAME:()=>Vs,ConnectionError:()=>we,DEFAULT_MODE_NAME:()=>Fe,DEFAULT_TOOLS_CONFIG:()=>H,DEFAULT_TOOL_SEARCH_CONFIG:()=>ni,DEFAULT_WORKFLOW_CONFIG:()=>zr,GeminiAdapter:()=>to,InvalidRequestError:()=>N,McpClient:()=>Bt,McpConnectionError:()=>ae,McpTimeoutError:()=>Oo,McpToolManager:()=>Io,ModeRegistry:()=>Jt,OllamaAdapter:()=>xe,OllamaProvider:()=>He,OpenAIAdapter:()=>so,PageError:()=>Qr,Planner:()=>Ht,ProviderAdapter:()=>K,ProviderError:()=>I,RateLimitError:()=>me,SDKError:()=>J,StepExecutor:()=>Kt,TOOLPACK_DIR_NAME:()=>Qs,TOOL_SEARCH_NAME:()=>Ge,TimeoutError:()=>Yr,ToolDiscoveryCache:()=>Ee,ToolRegistry:()=>Gt,ToolRouter:()=>Be,Toolpack:()=>Ks,WorkflowExecutor:()=>Fo,cloudDeployTool:()=>No,cloudListTool:()=>Mo,cloudStatusTool:()=>Ao,cloudToolsProject:()=>Gs,codingFindSymbolTool:()=>Lt,codingGetImportsTool:()=>Ut,codingGetSymbolsTool:()=>qt,codingToolsProject:()=>Ns,createMcpToolProject:()=>Jr,createMode:()=>Ag,createToolProject:()=>Dg,dbCountTool:()=>Eo,dbDeleteTool:()=>Do,dbInsertTool:()=>ko,dbQueryTool:()=>So,dbSchemaTool:()=>$o,dbTablesTool:()=>_o,dbToolsProject:()=>Us,dbUpdateTool:()=>Ro,diffApplyTool:()=>Po,diffCreateTool:()=>To,diffPreviewTool:()=>Co,diffToolsProject:()=>js,disconnectMcpToolProject:()=>Hr,ensureGlobalConfigDir:()=>ei,ensureLocalConfigDir:()=>Ay,execKillTool:()=>wt,execListProcessesTool:()=>bt,execReadOutputTool:()=>yt,execRunBackgroundTool:()=>ht,execRunShellTool:()=>gt,execRunTool:()=>ft,execToolsProject:()=>Fn,fetchUrlAsBase64:()=>nn,fsAppendFileTool:()=>Xe,fsCopyTool:()=>at,fsCreateDirTool:()=>st,fsDeleteFileTool:()=>et,fsExistsTool:()=>tt,fsListDirTool:()=>rt,fsMoveTool:()=>it,fsReadFileRangeTool:()=>ct,fsReadFileTool:()=>Ke,fsReplaceInFileTool:()=>mt,fsSearchTool:()=>pt,fsStatTool:()=>ot,fsToolsProject:()=>Dn,fsTreeTool:()=>ut,fsWriteFileTool:()=>Ye,generateToolCategoriesPrompt:()=>Bo,getDefaultSlmModel:()=>Si,getGlobalConfigDir:()=>Xs,getGlobalConfigPath:()=>Lo,getGlobalToolpackDir:()=>jg,getLocalConfigDir:()=>Zs,getLocalConfigPath:()=>qo,getLocalToolpackDir:()=>Fg,getMimeType:()=>en,getOllamaBaseUrl:()=>no,getOllamaProviderEntries:()=>vi,getRegisteredSlmModels:()=>_i,getRuntimeConfigStatus:()=>Oy,getToolSearchSchema:()=>Wo,getToolpackConfig:()=>Vo,getUserHomeDir:()=>Ig,gitAddTool:()=>go,gitBlameTool:()=>yo,gitBranchCreateTool:()=>bo,gitBranchListTool:()=>wo,gitCheckoutTool:()=>xo,gitCommitTool:()=>ho,gitDiffTool:()=>uo,gitLogTool:()=>fo,gitStatusTool:()=>mo,gitToolsProject:()=>Ms,httpDeleteTool:()=>kt,httpDownloadTool:()=>Dt,httpGetTool:()=>St,httpPostTool:()=>$t,httpPutTool:()=>_t,httpToolsProject:()=>es,initializeGlobalConfigIfFirstRun:()=>Iy,isDataUri:()=>tn,isRegisteredSlm:()=>$i,isToolSearchTool:()=>Go,loadFullConfig:()=>lo,loadRuntimeConfig:()=>My,loadToolsConfig:()=>Nt,normalizeImagePart:()=>xi,ollamaRequest:()=>ne,ollamaStream:()=>Xo,parseDataUri:()=>on,readFileAsBase64:()=>rn,reloadToolpackConfig:()=>Ci,saveToolsConfig:()=>pm,systemCwdTool:()=>Ct,systemDiskUsageTool:()=>vt,systemEnvTool:()=>Tt,systemInfoTool:()=>xt,systemSetEnvTool:()=>Pt,systemToolsProject:()=>zn,toDataUri:()=>bi,toolSearchDefinition:()=>Ne,webExtractLinksTool:()=>Ot,webFetchTool:()=>Et,webScrapeTool:()=>Mt,webSearchTool:()=>At,webToolsProject:()=>fs});module.exports=Kg(jy);l();de();l();var hi=require("events");de();l();l();l();var Ue={name:3,displayName:2.5,description:2,category:1.5,parameterNames:1,parameterDescriptions:.5},We=class{documents=[];avgDocLength=0;idf=new Map;totalDocs=0;docFrequencies=new Map;k1=1.2;b=.75;index(e){this.documents=[],this.docFrequencies.clear(),this.idf.clear();for(let t of e){let o=this.createDocument(t);this.documents.push(o);let r=new Set(o.tokens);for(let n of r)this.docFrequencies.set(n,(this.docFrequencies.get(n)||0)+1)}this.totalDocs=this.documents.length,this.computeIDF(),this.avgDocLength=this.computeAvgDocLength()}search(e,t){let o=t?.limit??5,r=t?.category,n=t?.minScore??0,a=this.tokenize(e.toLowerCase());if(a.length===0)return[];let i=[];for(let c of this.documents){if(r&&c.tool.category!==r)continue;let p=this.computeBM25Score(a,c);p>n&&i.push({toolName:c.toolName,score:p,tool:c.tool})}return i.sort((c,p)=>p.score-c.score).slice(0,o).map(({toolName:c,score:p,tool:m})=>({toolName:c,score:p,tool:this.toSchema(m)}))}getIndexedCount(){return this.documents.length}isIndexed(e){return this.documents.some(t=>t.toolName===e)}createDocument(e){let t=[];for(let a=0;a<Ue.name;a++)t.push(e.name);for(let a=0;a<Ue.displayName;a++)t.push(e.displayName);for(let a=0;a<Ue.description;a++)t.push(e.description);for(let a=0;a<Ue.category;a++)t.push(e.category);if(e.parameters?.properties)for(let[a,i]of Object.entries(e.parameters.properties)){for(let c=0;c<Ue.parameterNames;c++)t.push(a);if(i.description)for(let c=0;c<Ue.parameterDescriptions;c++)t.push(i.description)}let o=t.join(" ").toLowerCase(),r=this.tokenize(o),n=this.computeTermFrequencies(r);return{toolName:e.name,tool:e,text:o,tokens:r,length:r.length,termFrequencies:n}}tokenize(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1).filter(t=>!Qg.has(t))}computeTermFrequencies(e){let t=new Map;for(let o of e)t.set(o,(t.get(o)||0)+1);return t}computeIDF(){this.idf.clear();for(let[e,t]of this.docFrequencies){let o=Math.log((this.totalDocs-t+.5)/(t+.5)+1);this.idf.set(e,o)}}computeAvgDocLength(){return this.documents.length===0?0:this.documents.reduce((t,o)=>t+o.length,0)/this.documents.length}computeBM25Score(e,t){let o=0;for(let r of e){let n=t.termFrequencies.get(r)||0;if(n===0)continue;let a=this.idf.get(r)||0,i=t.length,c=n*(this.k1+1),p=n+this.k1*(1-this.b+this.b*(i/this.avgDocLength));o+=a*(c/p)}return o}toSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category}}},Qg=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","it","its","this","that","these","those","i","you","he","she","we","they","what","which","who","whom","when","where","why","how","all","each","every","both","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","just","also","now","here","there"]);l();var Ee=class s{discoveredTools=new Set;searchHistory=[];recordDiscovery(e,t){for(let o of t)this.discoveredTools.add(o);this.searchHistory.push({query:e,tools:t,timestamp:Date.now()})}getDiscoveredTools(){return Array.from(this.discoveredTools)}isDiscovered(e){return this.discoveredTools.has(e)}getDiscoveredCount(){return this.discoveredTools.size}getSearchHistory(){return[...this.searchHistory]}static fromMessages(e){let t=new s;for(let o of e)if(o.role==="tool"){let r=o;if(typeof r.content=="string")try{let n=JSON.parse(r.content);if(n.query&&n.tools&&Array.isArray(n.tools)){let a=n.tools.map(i=>typeof i=="string"?i:i.name).filter(Boolean);a.length>0&&t.recordDiscovery(n.query,a)}}catch{}}return t}clear(){this.discoveredTools.clear(),this.searchHistory=[]}merge(e){for(let t of e.getDiscoveredTools())this.discoveredTools.add(t);this.searchHistory.push(...e.getSearchHistory())}};l();var Ge="tool.search",Ne={name:Ge,displayName:"Search Tools",category:"meta",description:`Search for available tools by keyword or natural language query.
|
|
126
|
+
`)}}});var og,Gr,rg=f(()=>{"use strict";l();og=T(require("mysql2/promise"),1);Ur();Gr=class extends Se{async getConnection(){return await og.default.createConnection(this.connectionString)}async query(e,t=[]){let r=await this.getConnection();try{let[o]=await r.execute(e,t);return o}finally{await r.end()}}async execute(e,t=[]){let r=await this.getConnection();try{let[o]=await r.execute(e,t);return{changes:o.affectedRows,lastInsertRowid:o.insertId,raw:o}}finally{await r.end()}}async getTables(){let t=await this.query("SHOW TABLES");if(!t||t.length===0)return[];let r=Object.keys(t[0]);return t.map(o=>o[r[0]])}async getSchema(e){if(e){let t=await this.getConnection();try{let[r]=await t.query("DESCRIBE ??",[e]);return r}finally{await t.end()}}else return await this.query("SHOW TABLES")}}});var G,$e=f(()=>{"use strict";l();Zf();tg();rg();G=class{static getAdapter(e){return e.startsWith("postgres://")||e.startsWith("postgresql://")?new Wr(e):e.startsWith("mysql://")?new Gr(e):e.startsWith("sqlite://")?new $o(e.replace("sqlite://","")):new $o(e)}}});var _o,ng=f(()=>{"use strict";l();Xf();$e();k();_o={name:"db.query",displayName:"Database Query",description:"Execute raw SQL queries against an SQLite, PostgreSQL, or MySQL database.",category:"database",parameters:Vf,execute:async s=>{let e=s.db,t=s.sql,r=s.params||[];h(`[db.query] execute db="${e}" sql="${t.substring(0,80)}..." params=${r.length}`);try{let n=await G.getAdapter(e).query(t,r);return JSON.stringify(n,null,2)}catch(o){return`Database query error: ${o instanceof Error?o.message:String(o)}`}}}});var sg,ig=f(()=>{"use strict";l();sg={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Optional specific table name to inspect. If omitted, returns structural summary of all tables."}},required:["db"]}});var ko,ag=f(()=>{"use strict";l();ig();$e();ko={name:"db.schema",displayName:"Database Schema",description:"Get the structural schema of a database or a specific table.",category:"database",parameters:sg,execute:async s=>{let e=s.db,t=s.table;try{let o=await G.getAdapter(e).getSchema(t);return JSON.stringify(o,null,2)}catch(r){return`Database schema error: ${r instanceof Error?r.message:String(r)}`}}}});var lg,cg=f(()=>{"use strict";l();lg={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"}},required:["db"]}});var Ro,pg=f(()=>{"use strict";l();cg();$e();Ro={name:"db.tables",displayName:"Database Tables",description:"List all user tables in the database.",category:"database",parameters:lg,execute:async s=>{let e=s.db;try{let r=await G.getAdapter(e).getTables();return JSON.stringify(r,null,2)}catch(t){return`Database tables error: ${t instanceof Error?t.message:String(t)}`}}}});var mg,dg=f(()=>{"use strict";l();mg={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to insert into"},data:{type:"object",description:"Key-value pairs of column names and values to insert"}},required:["db","table","data"]}});var Eo,ug=f(()=>{"use strict";l();dg();$e();Eo={name:"db.insert",displayName:"Database Insert",description:"Insert a new row into an SQLite table safely.",category:"database",parameters:mg,execute:async s=>{let e=s.db,t=s.table,r=s.data;if(Object.keys(r).length===0)return"Error: No data provided to insert.";try{let o=Object.keys(r).join(", "),n=Object.keys(r).map(()=>"?").join(", "),a=Object.values(r),i=`INSERT INTO ${t} (${o}) VALUES (${n})`,p=await G.getAdapter(e).execute(i,a);return JSON.stringify(p,null,2)}catch(o){return`Database insert error: ${o instanceof Error?o.message:String(o)}`}}}});var fg,gg=f(()=>{"use strict";l();fg={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to update"},data:{type:"object",description:"Key-value pairs of column names and new values"},where:{type:"string",description:'WHERE clause condition (e.g. "id = 5"). DO NOT INCLUDE the word WHERE.'}},required:["db","table","data","where"]}});var Do,hg=f(()=>{"use strict";l();gg();$e();Do={name:"db.update",displayName:"Database Update",description:"Update existing rows in a database table.",category:"database",parameters:fg,execute:async s=>{let e=s.db,t=s.table,r=s.data,o=s.where;if(Object.keys(r).length===0)return"Error: No data provided to update.";try{let n=Object.keys(r).map(m=>`${m} = ?`).join(", "),a=Object.values(r),i=`UPDATE ${t} SET ${n} WHERE ${o}`,p=await G.getAdapter(e).execute(i,a);return JSON.stringify(p,null,2)}catch(n){return`Database update error: ${n instanceof Error?n.message:String(n)}`}}}});var yg,wg=f(()=>{"use strict";l();yg={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to delete from"},where:{type:"string",description:'WHERE clause condition (e.g. "id = 5"). DO NOT INCLUDE the word WHERE.'}},required:["db","table","where"]}});var No,bg=f(()=>{"use strict";l();wg();$e();No={name:"db.delete",displayName:"Database Delete",description:"Delete rows from a database table.",category:"database",parameters:yg,execute:async s=>{let e=s.db,t=s.table,r=s.where;try{let o=`DELETE FROM ${t} WHERE ${r}`,a=await G.getAdapter(e).execute(o);return JSON.stringify(a,null,2)}catch(o){return`Database delete error: ${o instanceof Error?o.message:String(o)}`}}}});var xg,Tg=f(()=>{"use strict";l();xg={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to count rows from"},where:{type:"string",description:"Optional WHERE clause condition"}},required:["db","table"]}});var Ao,Pg=f(()=>{"use strict";l();Tg();$e();Ao={name:"db.count",displayName:"Database Count",description:"Count rows in a database table.",category:"database",parameters:xg,execute:async s=>{let e=s.db,t=s.table,r=s.where;try{let o=r?`WHERE ${r}`:"",n=`SELECT COUNT(*) as count FROM ${t} ${o}`,i=await G.getAdapter(e).query(n);return Array.isArray(i)&&i.length>0?`Rows: ${i[0].count}`:"Count: 0"}catch(o){return`Database count error: ${o instanceof Error?o.message:String(o)}`}}}});var Cg={};V(Cg,{dbCountTool:()=>Ao,dbDeleteTool:()=>No,dbInsertTool:()=>Eo,dbQueryTool:()=>_o,dbSchemaTool:()=>ko,dbTablesTool:()=>Ro,dbToolsProject:()=>Gs,dbUpdateTool:()=>Do});var Gs,Bs=f(()=>{"use strict";l();ng();ag();pg();ug();hg();bg();Pg();Gs={manifest:{key:"db",name:"db-tools",displayName:"Database Tools",version:"1.0.0",description:"Stateless database operations enabling the AI to interact with local databases.",author:"Sajeer",tools:["db.query","db.schema","db.tables","db.insert","db.update","db.delete","db.count"],category:"database"},tools:[_o,ko,Ro,Eo,Do,No,Ao],dependencies:{"better-sqlite3":"^11.3.0"}}});var vg,Sg=f(()=>{"use strict";l();vg={type:"object",properties:{siteId:{type:"string",description:'The Netlify Site ID to deploy to (e.g. "api_id" from Netlify UI)'},dir:{type:"string",description:'The local directory path to deploy (e.g. "./dist" or "./public")'},message:{type:"string",description:"Optional deployment message/commit note"}},required:["siteId","dir"]}});var $g,_e,Br=f(()=>{"use strict";l();$g=require("netlify"),_e=class{static getClient(){let e=process.env.NETLIFY_AUTH_TOKEN;if(!e)throw new Error("NETLIFY_AUTH_TOKEN environment variable is required to use Netlify cloud tools.");return new $g.NetlifyAPI(e)}}});var Mo,_g=f(()=>{"use strict";l();Sg();Br();k();Mo={name:"cloud.deploy",displayName:"Cloud Deploy",description:"Deploy a static directory to Netlify.",category:"cloud",parameters:vg,execute:async s=>{let e=s.siteId,t=s.dir,r=s.message;h(`[cloud.deploy] execute siteId="${e}" dir="${t}" message="${r??"none"}"`);try{let n=await _e.getClient().deploy(e,t,{message:r||"Deployed via Toolpack SDK",draft:!1});return JSON.stringify({id:n.deployId,url:n.deploy.url,admin_url:n.deploy.admin_url,state:n.deploy.state},null,2)}catch(o){return`Cloud deployment error: ${o instanceof Error?o.message:String(o)}`}}}});var kg,Rg=f(()=>{"use strict";l();kg={type:"object",properties:{siteId:{type:"string",description:"The Netlify Site ID"},deployId:{type:"string",description:"The specific Deployment ID to check"}},required:["siteId","deployId"]}});var Oo,Eg=f(()=>{"use strict";l();Rg();Br();Oo={name:"cloud.status",displayName:"Cloud Status",description:"Check the status of a specific Netlify deployment.",category:"cloud",parameters:kg,execute:async s=>{let e=s.siteId,t=s.deployId;try{let o=await _e.getClient().getSiteDeploy({site_id:e,deploy_id:t});return JSON.stringify({id:o.id,state:o.state,error_message:o.error_message,created_at:o.created_at,updated_at:o.updated_at,url:o.url},null,2)}catch(r){return`Cloud status error: ${r instanceof Error?r.message:String(r)}`}}}});var Dg,Ng=f(()=>{"use strict";l();Dg={type:"object",properties:{siteId:{type:"string",description:"The Netlify Site ID"},limit:{type:"number",description:"Number of recent deployments to return. Defaults to 5.",default:5}},required:["siteId"]}});var Io,Ag=f(()=>{"use strict";l();Ng();Br();k();Io={name:"cloud.list",displayName:"Cloud Deployments List",description:"List recent deployments for a Netlify site.",category:"cloud",parameters:Dg,execute:async s=>{let e=s.siteId,t=s.limit||5;h(`[cloud.list] execute siteId="${e}" limit=${t}`);try{let o=await _e.getClient().listSiteDeploys({site_id:e,page:1,per_page:t});if(!Array.isArray(o))return"Unexpected response format from Netlify API";let n=o.map(a=>({id:a.id,state:a.state,created_at:a.created_at,url:a.url,branch:a.branch,title:a.title}));return JSON.stringify(n,null,2)}catch(r){return`Cloud list error: ${r instanceof Error?r.message:String(r)}`}}}});var Mg={};V(Mg,{cloudDeployTool:()=>Mo,cloudListTool:()=>Io,cloudStatusTool:()=>Oo,cloudToolsProject:()=>Js});var Js,Hs=f(()=>{"use strict";l();_g();Eg();Ag();Js={manifest:{key:"cloud",name:"cloud-tools",displayName:"Cloud Deployment",version:"1.0.0",description:"Cloud deployment operations allowing the AI to publish directories directly to the internet.",author:"Sajeer",tools:["cloud.deploy","cloud.status","cloud.list"],category:"cloud"},tools:[Mo,Oo,Io],dependencies:{netlify:"^13.1.20"}}});var Hy={};V(Hy,{AGENT_MODE:()=>Ys,AGENT_PLANNING_PROMPT:()=>zr,AGENT_STEP_PROMPT:()=>Kr,AGENT_WORKFLOW:()=>zs,AIClient:()=>eo,AnthropicAdapter:()=>oo,AuthenticationError:()=>pe,BM25SearchEngine:()=>Ge,BUILT_IN_MODES:()=>Lo,CHAT_MODE:()=>Vs,CHAT_WORKFLOW:()=>Qs,CODING_PLANNING_PROMPT:()=>Fg,CODING_STEP_PROMPT:()=>Lg,CODING_WORKFLOW:()=>Ks,CONFIG_DIR_NAME:()=>ti,CONFIG_FILE_NAME:()=>oi,ConnectionError:()=>we,DEFAULT_MODE_NAME:()=>Le,DEFAULT_TOOLS_CONFIG:()=>H,DEFAULT_TOOL_SEARCH_CONFIG:()=>ci,DEFAULT_WORKFLOW:()=>jy,DEFAULT_WORKFLOW_CONFIG:()=>Qr,GeminiAdapter:()=>ro,InvalidRequestError:()=>N,McpClient:()=>Ht,McpConnectionError:()=>ae,McpTimeoutError:()=>jo,McpToolManager:()=>Fo,ModeRegistry:()=>zt,OllamaAdapter:()=>xe,OllamaProvider:()=>Ke,OpenAIAdapter:()=>ao,PageError:()=>Vr,Planner:()=>Kt,ProviderAdapter:()=>K,ProviderError:()=>I,RateLimitError:()=>me,SDKError:()=>J,StepExecutor:()=>Yt,TOOLPACK_DIR_NAME:()=>ei,TOOL_SEARCH_NAME:()=>Be,TimeoutError:()=>Xr,ToolDiscoveryCache:()=>De,ToolRegistry:()=>Jt,ToolRouter:()=>Je,Toolpack:()=>Zs,WorkflowExecutor:()=>qo,cloudDeployTool:()=>Mo,cloudListTool:()=>Io,cloudStatusTool:()=>Oo,cloudToolsProject:()=>Js,codingFindSymbolTool:()=>Ut,codingGetImportsTool:()=>Gt,codingGetSymbolsTool:()=>Wt,codingToolsProject:()=>Ms,createMcpToolProject:()=>Jr,createMode:()=>qg,createToolProject:()=>Og,dbCountTool:()=>Ao,dbDeleteTool:()=>No,dbInsertTool:()=>Eo,dbQueryTool:()=>_o,dbSchemaTool:()=>ko,dbTablesTool:()=>Ro,dbToolsProject:()=>Gs,dbUpdateTool:()=>Do,diffApplyTool:()=>vo,diffCreateTool:()=>Co,diffPreviewTool:()=>So,diffToolsProject:()=>Ls,disconnectMcpToolProject:()=>Hr,ensureGlobalConfigDir:()=>si,ensureLocalConfigDir:()=>Wy,execKillTool:()=>xt,execListProcessesTool:()=>Tt,execReadOutputTool:()=>bt,execRunBackgroundTool:()=>wt,execRunShellTool:()=>yt,execRunTool:()=>ht,execToolsProject:()=>qn,fetchUrlAsBase64:()=>an,fsAppendFileTool:()=>et,fsCopyTool:()=>ct,fsCreateDirTool:()=>at,fsDeleteFileTool:()=>ot,fsExistsTool:()=>rt,fsListDirTool:()=>st,fsMoveTool:()=>lt,fsReadFileRangeTool:()=>mt,fsReadFileTool:()=>Ye,fsReplaceInFileTool:()=>ut,fsSearchTool:()=>dt,fsStatTool:()=>nt,fsToolsProject:()=>Nn,fsTreeTool:()=>gt,fsWriteFileTool:()=>Xe,generateToolCategoriesPrompt:()=>Ho,getDefaultSlmModel:()=>Ei,getGlobalConfigDir:()=>ri,getGlobalConfigPath:()=>Uo,getGlobalToolpackDir:()=>Bg,getLocalConfigDir:()=>ni,getLocalConfigPath:()=>Wo,getLocalToolpackDir:()=>Jg,getMimeType:()=>on,getOllamaBaseUrl:()=>io,getOllamaProviderEntries:()=>Ri,getRegisteredSlmModels:()=>Ni,getRuntimeConfigStatus:()=>By,getToolSearchSchema:()=>Bo,getToolpackConfig:()=>Vo,getUserHomeDir:()=>Gg,gitAddTool:()=>yo,gitBlameTool:()=>bo,gitBranchCreateTool:()=>To,gitBranchListTool:()=>xo,gitCheckoutTool:()=>Po,gitCommitTool:()=>wo,gitDiffTool:()=>go,gitLogTool:()=>ho,gitStatusTool:()=>fo,gitToolsProject:()=>Is,httpDeleteTool:()=>Et,httpDownloadTool:()=>Nt,httpGetTool:()=>_t,httpPostTool:()=>kt,httpPutTool:()=>Rt,httpToolsProject:()=>os,initializeGlobalConfigIfFirstRun:()=>Jy,isDataUri:()=>rn,isRegisteredSlm:()=>Di,isToolSearchTool:()=>Jo,loadFullConfig:()=>po,loadRuntimeConfig:()=>Gy,loadToolsConfig:()=>Mt,normalizeImagePart:()=>Si,ollamaRequest:()=>ne,ollamaStream:()=>Xo,parseDataUri:()=>nn,readFileAsBase64:()=>sn,reloadToolpackConfig:()=>ki,saveToolsConfig:()=>gm,systemCwdTool:()=>St,systemDiskUsageTool:()=>$t,systemEnvTool:()=>Ct,systemInfoTool:()=>Pt,systemSetEnvTool:()=>vt,systemToolsProject:()=>Qn,toDataUri:()=>vi,toolSearchDefinition:()=>Ne,webExtractLinksTool:()=>jt,webFetchTool:()=>At,webScrapeTool:()=>It,webSearchTool:()=>Ot,webToolsProject:()=>hs});module.exports=th(Hy);l();de();l();var Ti=require("events");de();l();l();l();var We={name:3,displayName:2.5,description:2,category:1.5,parameterNames:1,parameterDescriptions:.5},Ge=class{documents=[];avgDocLength=0;idf=new Map;totalDocs=0;docFrequencies=new Map;k1=1.2;b=.75;index(e){this.documents=[],this.docFrequencies.clear(),this.idf.clear();for(let t of e){let r=this.createDocument(t);this.documents.push(r);let o=new Set(r.tokens);for(let n of o)this.docFrequencies.set(n,(this.docFrequencies.get(n)||0)+1)}this.totalDocs=this.documents.length,this.computeIDF(),this.avgDocLength=this.computeAvgDocLength()}search(e,t){let r=t?.limit??5,o=t?.category,n=t?.minScore??0,a=this.tokenize(e.toLowerCase());if(a.length===0)return[];let i=[];for(let c of this.documents){if(o&&c.tool.category!==o)continue;let p=this.computeBM25Score(a,c);p>n&&i.push({toolName:c.toolName,score:p,tool:c.tool})}return i.sort((c,p)=>p.score-c.score).slice(0,r).map(({toolName:c,score:p,tool:m})=>({toolName:c,score:p,tool:this.toSchema(m)}))}getIndexedCount(){return this.documents.length}isIndexed(e){return this.documents.some(t=>t.toolName===e)}createDocument(e){let t=[];for(let a=0;a<We.name;a++)t.push(e.name);for(let a=0;a<We.displayName;a++)t.push(e.displayName);for(let a=0;a<We.description;a++)t.push(e.description);for(let a=0;a<We.category;a++)t.push(e.category);if(e.parameters?.properties)for(let[a,i]of Object.entries(e.parameters.properties)){for(let c=0;c<We.parameterNames;c++)t.push(a);if(i.description)for(let c=0;c<We.parameterDescriptions;c++)t.push(i.description)}let r=t.join(" ").toLowerCase(),o=this.tokenize(r),n=this.computeTermFrequencies(o);return{toolName:e.name,tool:e,text:r,tokens:o,length:o.length,termFrequencies:n}}tokenize(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1).filter(t=>!oh.has(t))}computeTermFrequencies(e){let t=new Map;for(let r of e)t.set(r,(t.get(r)||0)+1);return t}computeIDF(){this.idf.clear();for(let[e,t]of this.docFrequencies){let r=Math.log((this.totalDocs-t+.5)/(t+.5)+1);this.idf.set(e,r)}}computeAvgDocLength(){return this.documents.length===0?0:this.documents.reduce((t,r)=>t+r.length,0)/this.documents.length}computeBM25Score(e,t){let r=0;for(let o of e){let n=t.termFrequencies.get(o)||0;if(n===0)continue;let a=this.idf.get(o)||0,i=t.length,c=n*(this.k1+1),p=n+this.k1*(1-this.b+this.b*(i/this.avgDocLength));r+=a*(c/p)}return r}toSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category}}},oh=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","it","its","this","that","these","those","i","you","he","she","we","they","what","which","who","whom","when","where","why","how","all","each","every","both","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","just","also","now","here","there"]);l();var De=class s{discoveredTools=new Set;searchHistory=[];recordDiscovery(e,t){for(let r of t)this.discoveredTools.add(r);this.searchHistory.push({query:e,tools:t,timestamp:Date.now()})}getDiscoveredTools(){return Array.from(this.discoveredTools)}isDiscovered(e){return this.discoveredTools.has(e)}getDiscoveredCount(){return this.discoveredTools.size}getSearchHistory(){return[...this.searchHistory]}static fromMessages(e){let t=new s;for(let r of e)if(r.role==="tool"){let o=r;if(typeof o.content=="string")try{let n=JSON.parse(o.content);if(n.query&&n.tools&&Array.isArray(n.tools)){let a=n.tools.map(i=>typeof i=="string"?i:i.name).filter(Boolean);a.length>0&&t.recordDiscovery(n.query,a)}}catch{}}return t}clear(){this.discoveredTools.clear(),this.searchHistory=[]}merge(e){for(let t of e.getDiscoveredTools())this.discoveredTools.add(t);this.searchHistory.push(...e.getSearchHistory())}};l();var Be="tool.search",Ne={name:Be,displayName:"Search Tools",category:"meta",description:`Search for available tools by keyword or natural language query.
|
|
127
127
|
Use this to discover tools before using them.
|
|
128
128
|
Examples: "file operations", "web scraping", "run command", "http request"
|
|
129
129
|
|
|
130
130
|
Returns a list of matching tools with their names, descriptions, and parameters.
|
|
131
|
-
After discovering tools, you can call them directly by name.`,parameters:{type:"object",properties:{query:{type:"string",description:'Natural language search query (e.g., "read files", "web scraping", "execute shell commands")'},category:{type:"string",description:"Optional: filter by category",enum:["filesystem","network","execution","system","meta"]}},required:["query"]},execute:async()=>{throw new Error("tool.search execution must be handled by AIClient")}};function
|
|
132
|
-
`)}var
|
|
133
|
-
Working directory: ${s.workingDirectory}`:"",
|
|
134
|
-
Available tool categories: ${s.toolCategories.join(", ")}`:"";return`You are an AI assistant with access to tools that let you interact with the user's system.${
|
|
131
|
+
After discovering tools, you can call them directly by name.`,parameters:{type:"object",properties:{query:{type:"string",description:'Natural language search query (e.g., "read files", "web scraping", "execute shell commands")'},category:{type:"string",description:"Optional: filter by category",enum:["filesystem","network","execution","system","meta"]}},required:["query"]},execute:async()=>{throw new Error("tool.search execution must be handled by AIClient")}};function Bo(){return{name:Ne.name,displayName:Ne.displayName,description:Ne.description,parameters:Ne.parameters,category:Ne.category}}function Jo(s){return s===Be}l();var rh={filesystem:"File operations (read, write, delete, list, search files)",network:"HTTP requests and web scraping (GET, POST, fetch pages, extract data)",execution:"Run shell commands and manage processes",system:"System information, environment variables, disk usage",meta:"Tool discovery and management"};function Ho(s){let e=s.getCategories();if(e.length===0)return"No tools are currently available.";let t=["You have access to tools in the following categories:",""];for(let r of e){let n=s.getByCategory(r).length,a=rh[r]||r;t.push(`- **${r}** (${n} tools): ${a}`)}return t.push(""),t.push("Use `tool.search` to discover specific tools when needed."),t.push('Example: tool.search({ query: "read file" }) to find file reading tools.'),t.join(`
|
|
132
|
+
`)}var Je=class{discoveryCache=new De;async resolve(e,t,r){return r.enabled?r.toolSearch?.enabled?this.resolveWithToolSearch(e,t,r):this.resolveLegacy(t,r):[]}getDiscoveryCache(){return this.discoveryCache}clearDiscoveryCache(){this.discoveryCache.clear()}resolveWithToolSearch(e,t,r){let o=[],n=new Set;o.push(Bo()),n.add(Be);let a=r.toolSearch?.alwaysLoadedTools??[];for(let c of a){let p=t.get(c);p&&!n.has(c)&&(o.push(this.toSchema(p)),n.add(c))}let i=r.toolSearch?.alwaysLoadedCategories??[];for(let c of i)for(let p of t.getByCategory(c))n.has(p.name)||(o.push(this.toSchema(p)),n.add(p.name));if(r.toolSearch?.cacheDiscoveredTools!==!1){let c=De.fromMessages(e);this.discoveryCache.merge(c);let p=this.discoveryCache.getDiscoveredTools();for(let m of p){let u=t.get(m);u&&!n.has(m)&&u.cacheable!==!1&&(o.push(this.toSchema(u)),n.add(m))}}return o}resolveLegacy(e,t){let r;if(t.enabledTools.length===0&&t.enabledToolCategories.length===0)r=e.getEnabled();else{let o=e.getByNames(t.enabledTools),n=e.getByCategories(t.enabledToolCategories),a=new Set;r=[];for(let i of[...o,...n])a.has(i.name)||(a.add(i.name),r.push(i))}return r.map(o=>this.toSchema(o))}toSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category}}};Xt();l();function pi(s){if(s.disabled)return"";let e=s.includeWorkingDirectory!==!1,t=s.includeToolCategories!==!1,r=e?`
|
|
133
|
+
Working directory: ${s.workingDirectory}`:"",o=t&&s.toolCategories.length>0?`
|
|
134
|
+
Available tool categories: ${s.toolCategories.join(", ")}`:"";return`You are an AI assistant with access to tools that let you interact with the user's system.${r}${o}
|
|
135
135
|
|
|
136
136
|
When the user asks you to do something, be proactive:
|
|
137
137
|
- Use your tools to find information rather than asking the user for details you can discover yourself
|
|
138
138
|
- Read files, list directories, and explore the codebase when asked to analyze or understand a project
|
|
139
|
-
- Only ask the user for clarification when you genuinely cannot determine their intent or lack the required tools`}l();var
|
|
140
|
-
`):""}return""}function
|
|
139
|
+
- Only ask the user for clarification when you genuinely cannot determine their intent or lack the required tools`}l();var He=class{analyticalPatterns=[/\b(analyze|find|search|check|list|show)\b/i,/\b(biggest|largest|smallest|most|least|all|every|count)\b/i,/\b(explain|understand|review|audit|inspect|examine)\b/i,/\b(compare|difference|similar|match|pattern)\b/i,/\b(what|where|how many|which|who|when|why|how)\b/i,/\?$/];actionPatterns=[/\b(create|write|update|modify|edit|patch|delete|remove|rename|move|copy)\b/i,/\b(run|execute|start|stop|restart|deploy|install|build)\b/i,/\b(fix|refactor|implement|add|change|replace|insert)\b/i,/\b(make|do|set|configure|setup|initialize)\b/i];classify(e){if(!e||e.trim().length===0)return{type:"conversational",confidence:0};let t=e.toLowerCase(),r=this.analyticalPatterns.filter(i=>i.test(t)).length,o=this.actionPatterns.filter(i=>i.test(t)).length,n=r/this.analyticalPatterns.length,a=o/this.actionPatterns.length;if(r>o&&r>0){let i=Math.min(n,1);return o>0&&(i=Math.min(i,.5)),{type:"analytical",confidence:i,reasoning:`Matched ${r} analytical patterns${o>0?`, ${o} action patterns (capped confidence)`:""}`}}else return o>r&&o>0?{type:"action",confidence:Math.min(a,1),reasoning:`Matched ${o} action patterns`}:r===o&&r>0?{type:"analytical",confidence:.5,reasoning:`Mixed query (${r} analytical, ${o} action patterns)`}:{type:"conversational",confidence:.3,reasoning:"No strong analytical or action patterns detected"}}getToolRoundsAdjustment(e,t){return e.type==="analytical"&&e.confidence>.6?Math.min(t+3,10):(e.type==="action"&&e.confidence>.6,t)}};l();var zo=class{analyzeDependencies(e){let t=[];for(let r=0;r<e.length;r++){let o=e[r],n=[],a=JSON.stringify(o.arguments).toLowerCase();for(let i=0;i<r;i++){let c=e[i];this.hasDependency(o,c,a)&&n.push(c.id)}t.push({toolCallId:o.id,dependsOn:n})}return t}hasDependency(e,t,r){return!!(e.arguments.path&&t.arguments.path&&e.arguments.path===t.arguments.path||e.arguments.file_path&&t.arguments.file_path&&e.arguments.file_path===t.arguments.file_path||e.arguments.filePath&&t.arguments.filePath&&e.arguments.filePath===t.arguments.filePath||["fs.write_file","fs.delete_file","fs.move","fs.copy","fs.replace_in_file","fs.append_file"].includes(e.name)&&t.arguments.path&&r.includes(t.arguments.path.toLowerCase())||e.name==="exec.read_output"&&t.name==="exec.run_background"||e.name==="http.download"&&t.name==="http.get"&&t.arguments.url&&r.includes(t.arguments.url.toLowerCase()))}async executeWithDependencies(e,t,r=5){if(e.length===0)return new Map;let o=this.analyzeDependencies(e),n=new Map,a=new Set;for(;a.size<e.length;){let i=[];for(let p of e){if(a.has(p.id))continue;(o.find(g=>g.toolCallId===p.id)?.dependsOn.every(g=>a.has(g))??!0)&&i.push(p)}if(i.length===0){let p=e.filter(m=>!a.has(m.id));throw new Error(`Circular dependency detected in tool calls: ${p.map(m=>m.name).join(", ")}`)}let c=await this.executeBatchWithLimit(i,t,r);for(let{id:p,result:m}of c)n.set(p,m),a.add(p)}return n}async executeBatchWithLimit(e,t,r){let o=[];if(e.length<=r){let n=e.map(async a=>{let i=await t(a);return{id:a.id,result:i}});return await Promise.all(n)}for(let n=0;n<e.length;n+=r){let i=e.slice(n,n+r).map(async p=>{let m=await t(p);return{id:p.id,result:m}}),c=await Promise.all(i);o.push(...c)}return o}shouldUseParallelExecution(e){return e.length<2?!1:this.analyzeDependencies(e).filter(o=>o.dependsOn.length===0).length>=2}};l();function Ae(s){for(let e=s.length-1;e>=0;e--){let t=s[e];if(t?.role!=="user")continue;let r=t?.content;return typeof r=="string"?r:Array.isArray(r)?r.map(o=>o?.type==="text"?o.text:"").filter(Boolean).join(`
|
|
140
|
+
`):""}return""}k();var gi=0;function tn(){return gi+=1,`${Date.now()}-${gi}`}function Yo(s,e){Me("debug")&&(h(`[AIClient][${s}] Messages (${e.length}):`),e.forEach((t,r)=>{let o=D(t.content,300);h(`[AIClient][${s}] #${r} role=${t.role} content=${o}`)}))}function hi(s){let e=Ae(s).toLowerCase();return e?[/\b(list|show|print|display)\b.*\b(files|folders|directory|dir)\b/,/\b(current|this)\b.*\b(directory|folder|repo|repository)\b/,/\b(read|open|view)\b.*\b(file|log|config|json|yaml|env)\b/,/\b(write|create|update|modify|edit|patch|delete|remove|rename|move|copy)\b.*\b(file|folder|directory)\b/,/\b(run|execute)\b.*\b(command|shell|script|tests?)\b/,/\b(http|get|post|put|delete|download|fetch|curl)\b/,/\b(web|search|scrape|crawl|map)\b/,/https?:\/\//].some(r=>r.test(e)):!1}function yi(s,e){let t=-1;for(let o=s.length-1;o>=0;o--){let n=s[o];if(n.role==="tool"||n.role==="assistant"&&n.tool_calls&&n.tool_calls.length>0){t=o;break}}if(t===-1)return!1;let r=s.length-1-t;return r>0&&r<=e}function wi(s){return{openai:"gpt-4.1-mini",anthropic:"claude-3-haiku-20240307",gemini:"gemini-2.0-flash-exp",ollama:"llama3.2"}[s]||"default"}function sh(s){let e=[],t=0;for(let r=s.length-1;r>=0&&t<2;r--){let o=s[r];if(o.role==="assistant"&&o.tool_calls&&o.tool_calls.length>0){t++;for(let n of o.tool_calls){let a=n.function?.name||"unknown",i=n.function?.arguments,c=`Tool: ${a}`;if(i)try{let p=typeof i=="string"?JSON.parse(i):i;p.url&&(c+=` (URL: ${p.url})`),p.file_path&&(c+=` (File: ${p.file_path})`),p.section&&(c+=` (Section: ${p.section})`),p.query&&(c+=` (Query: ${p.query})`),p.command&&(c+=` (Command: ${p.command.substring(0,50)})`)}catch{}e.push(c)}}}return e.length>0?e.join(", "):"None"}async function bi(s,e,t,r){let o=tn();h(`[AIClient][${o}] inferNeedsToolsWithAI() provider=${e} model=${r}`);let n=sh(t),i=t.filter(p=>p.role==="user").slice(-1)[0]?.content||"",c=`Recent tool usage: ${n}
|
|
141
141
|
|
|
142
142
|
User's new message: "${i}"
|
|
143
143
|
|
|
@@ -148,17 +148,17 @@ Does this message:
|
|
|
148
148
|
If the message is general knowledge (math, definitions, explanations) or completely unrelated to recent tool context, answer NO.
|
|
149
149
|
If it asks about the same context OR needs new external information, answer YES.
|
|
150
150
|
|
|
151
|
-
Answer only: YES or NO`;try{let m=((await s.generate({model:
|
|
152
|
-
[TRUNCATED tool result: ${
|
|
153
|
-
[TRUNCATED tool result: ${O.length} chars]`:O,re=typeof oe=="string"?oe:JSON.stringify(oe);ce+=re.length,F.push({role:"tool",tool_call_id:te.id,content:oe})}h(`[AIClient][${
|
|
154
|
-
[TRUNCATED tool result: ${ye.length} chars]`:ye,
|
|
151
|
+
Answer only: YES or NO`;try{let m=((await s.generate({model:r,messages:[{role:"user",content:c}],max_tokens:10,temperature:0})).content||"").trim().toUpperCase(),u=m.startsWith("YES");return h(`[AIClient][${o}] inferNeedsToolsWithAI() context="${n}" message="${i.substring(0,50)}" result=${u} (raw: ${m})`),u}catch(p){return E(`[AIClient][${o}] inferNeedsToolsWithAI() error=${p} - falling back to false`),!1}}function xi(s){let e=Ae(s).toLowerCase();if(!e)return!1;let t=[/\b(list|show|print|display)\b.*\b(files|folders|directory|dir)\b/,/\b(current|this)\b.*\b(directory|folder|repo|repository)\b/,/\b(read|open|view)\b.*\b(file|log|config|json|yaml|env)\b/],r=[/\b(write|create|update|modify|edit|patch|delete|remove|rename|move|copy)\b/,/\b(run|execute)\b.*\b(command|shell|script|tests?)\b/,/\b(http|get|post|put|delete|download|fetch|curl)\b/,/\b(web|search|scrape|crawl)\b/];return t.some(o=>o.test(e))&&!r.some(o=>o.test(e))}var eo=class extends Ti.EventEmitter{providers;defaultProvider;toolRegistry;toolsConfig;toolRouter;bm25Engine;queryClassifier;toolOrchestrator;activeMode=null;overrideSystemPrompt;disableBaseContext;toolResultMaxChars;constructor(e){super(),this.providers=new Map(Object.entries(e.providers)),this.defaultProvider=e.defaultProvider,this.toolRegistry=e.toolRegistry,this.toolsConfig=e.toolsConfig||H,this.toolRouter=new Je,this.bm25Engine=new Ge,this.queryClassifier=new He,this.toolOrchestrator=new zo,this.overrideSystemPrompt=e.systemPrompt,this.disableBaseContext=e.disableBaseContext||!1;let t=this.toolsConfig.resultMaxChars??H.resultMaxChars??2e4;this.toolResultMaxChars=Number.isFinite(t)&&t>0?t:2e4,this.toolRegistry&&this.bm25Engine.index(this.toolRegistry.getAll())}registerProvider(e,t){this.providers.set(e,t)}getProvider(e){let t=e||this.defaultProvider;if(!t)throw new J("No provider specified and no default provider configured","NO_PROVIDER_CONFIGURED",400);let r=this.providers.get(t);if(!r)throw new J(`Provider '${t}' not found`,"PROVIDER_NOT_FOUND",404);return r}setDefaultProvider(e){if(!this.providers.has(e))throw new J(`Provider '${e}' not found`,"PROVIDER_NOT_FOUND",404);this.defaultProvider=e}getToolRegistry(){return this.toolRegistry}getProviders(){return new Map(this.providers)}setToolRegistry(e){this.toolRegistry=e}setToolsConfig(e){this.toolsConfig=e}setSystemPrompt(e){this.overrideSystemPrompt=e}setMode(e){this.activeMode=e,v(`[AIClient] Mode set to: ${e?e.displayName:"none (cleared)"}`)}getMode(){return this.activeMode}getQueryClassifier(){return this.queryClassifier}reindexTools(){this.toolRegistry&&(this.bm25Engine.index(this.toolRegistry.getAll()),v(`[AIClient] Re-indexed ${this.bm25Engine.getIndexedCount()} tools for BM25 search`))}clearToolDiscoveryCache(){this.toolRouter.clearDiscoveryCache()}async generate(e,t){let r=this.getProvider(t);try{let o=tn(),n=this.injectBaseAgentContext(e);n=this.injectOverrideSystemPrompt(n),n=this.injectModeSystemPrompt(n);let a=t||this.defaultProvider,i=await this.enrichRequestWithTools(n),c=process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||this.toolsConfig.toolChoicePolicy||"auto",p=(i.tools?.length||0)>0,m=i.tool_choice!=null,u=hi(i.messages),g=this.toolsConfig.intelligentToolDetection,w=!1;if(!u&&g?.enabled&&p&&yi(i.messages,g.maxFollowUpMessages)){v(`[AIClient][${o}] Message is after tool call, using AI to infer tool needs`);let R=wi(a||"openai");u=await bi(r,a||"openai",i.messages,R),w=!0}let y=xi(i.messages);!m&&p&&(c==="required"||c==="required_for_actions"&&u)?i.tool_choice="required":!m&&p&&w&&!u&&(i.tool_choice="none",v(`[AIClient][${o}] AI inference determined no tools needed, setting tool_choice=none`));let $=r?.constructor?.name||"UnknownProvider",C={...i,__toolpack_request_id:o};v(`[AIClient][${o}] generate() start provider=${a} class=${$} model=${i.model} messages=${i.messages.length} tools=${i.tools?.length||0} tool_choice=${i.tool_choice??"unset"} policy=${c} needsTools=${u} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),Yo(o,i.messages);let x=await r.generate(C);if(h(`[AIClient][${o}] generate() initial response finish_reason=${x.finish_reason??"unknown"} tool_calls=${x.tool_calls?.length||0} content_preview=${D(x.content||"",200)}`),this.toolsConfig.enabled&&this.toolsConfig.autoExecute&&this.toolRegistry){let S=Ae(i.messages),R=this.queryClassifier.classify(S),j=this.toolsConfig.maxToolRounds,U=this.queryClassifier.getToolRoundsAdjustment(R,j);U!==j?v(`[AIClient][${o}] Query classified as ${R.type} (confidence: ${R.confidence.toFixed(2)}), adjusted maxToolRounds: ${j} \u2192 ${U}`):h(`[AIClient][${o}] Query classified as ${R.type} (confidence: ${R.confidence.toFixed(2)}), keeping maxToolRounds: ${U}`);let L=0,F=[...i.messages];for(x.tool_calls&&x.tool_calls.length>0&&v(`[AIClient] Received ${x.tool_calls.length} tool call(s): ${x.tool_calls.map(B=>B.name).join(", ")}`);x.tool_calls&&x.tool_calls.length>0&&L<U;){L++,v(`[AIClient][${o}] generate() tool round ${L}/${U} tool_calls=${x.tool_calls.length}`),F.push({role:"assistant",content:x.content||"",tool_calls:x.tool_calls.map(W=>({id:W.id,type:"function",function:{name:W.name,arguments:JSON.stringify(W.arguments)}}))});let B=this.toolOrchestrator.shouldUseParallelExecution(x.tool_calls),ke=3,ge=x.tool_calls,le=x.tool_calls.filter(W=>W.name==="web.fetch");if(le.length>ke){v(`[AIClient][${o}] Limiting web.fetch calls from ${le.length} \u2192 ${ke} to prevent context overflow`);let W=le.slice(0,ke);ge=[...x.tool_calls.filter(_=>_.name!=="web.fetch"),...W];let O=le.slice(ke);for(let _ of O)F.push({role:"tool",tool_call_id:_.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let ee=5e4,ce=0;if(B){v(`[AIClient][${o}] Using parallel execution for ${ge.length} tools`);let W=await this.toolOrchestrator.executeWithDependencies(ge,O=>this.executeTool(O),5),te=!1;for(let O of ge){if(te){F.push({role:"tool",tool_call_id:O.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let _=W.get(O.id),oe=typeof _=="string"?_:JSON.stringify(_);if(ce+oe.length>ee){E(`[AIClient][${o}] Tool output budget exceeded (${ee} chars), adding placeholder for remaining tools`),F.push({role:"tool",tool_call_id:O.id,content:"[Skipped: tool output budget exceeded for this round]"}),te=!0;continue}let re=typeof _=="string"&&_.length>this.toolResultMaxChars?`${_.slice(0,this.toolResultMaxChars)}
|
|
152
|
+
[TRUNCATED tool result: ${_.length} chars]`:_,Re=typeof re=="string"?re:JSON.stringify(re);ce+=Re.length,F.push({role:"tool",tool_call_id:O.id,content:re})}h(`[AIClient][${o}] Round tool output size: ${ce} chars (budget: ${ee})`)}else{v(`[AIClient][${o}] Using sequential execution for ${ge.length} tools`);let W=!1;for(let te of ge){if(W){F.push({role:"tool",tool_call_id:te.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let O=await this.executeTool(te),_=typeof O=="string"?O:JSON.stringify(O);if(ce+_.length>ee){E(`[AIClient][${o}] Tool output budget exceeded (${ee} chars), adding placeholder for remaining tools`),F.push({role:"tool",tool_call_id:te.id,content:"[Skipped: tool output budget exceeded for this round]"}),W=!0;continue}let oe=typeof O=="string"&&O.length>this.toolResultMaxChars?`${O.slice(0,this.toolResultMaxChars)}
|
|
153
|
+
[TRUNCATED tool result: ${O.length} chars]`:O,re=typeof oe=="string"?oe:JSON.stringify(oe);ce+=re.length,F.push({role:"tool",tool_call_id:te.id,content:oe})}h(`[AIClient][${o}] Round tool output size: ${ce} chars (budget: ${ee})`)}let Ue={...i,messages:F,__toolpack_request_id:o},he=await this.enrichRequestWithTools(Ue);he.tool_choice==="required"&&(he.tool_choice=y?"none":"auto",v(`[AIClient][${o}] generate() followup tool_choice override required->${he.tool_choice}`)),Me("debug")&&(h(`[AIClient][${o}] generate() followup request messages=${F.length}`),Yo(o,F)),x=await r.generate(he),h(`[AIClient][${o}] generate() followup response finish_reason=${x.finish_reason??"unknown"} tool_calls=${x.tool_calls?.length||0} content_preview=${D(x.content||"",200)}`)}}return x}catch(o){throw this.wrapError(o)}}async*stream(e,t){let r=this.getProvider(t);try{let o=tn(),n=t||this.defaultProvider,a=this.injectBaseAgentContext(e);a=this.injectOverrideSystemPrompt(a),a=this.injectModeSystemPrompt(a);let i=await this.enrichRequestWithTools(a),c=process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||this.toolsConfig.toolChoicePolicy||"auto",p=(i.tools?.length||0)>0,m=i.tool_choice!=null,u=hi(i.messages),g=this.toolsConfig.intelligentToolDetection,w=!1;if(!u&&g?.enabled&&p&&yi(i.messages,g.maxFollowUpMessages)){v(`[AIClient][${o}] Message is after tool call, using AI to infer tool needs`);let B=wi(n||"openai");u=await bi(r,n||"openai",i.messages,B),w=!0}let y=xi(i.messages);!m&&p&&(c==="required"||c==="required_for_actions"&&u)?i.tool_choice="required":!m&&p&&w&&!u&&(i.tool_choice="none",v(`[AIClient][${o}] AI inference determined no tools needed, setting tool_choice=none`));let $=r?.constructor?.name||"UnknownProvider",C={...i,__toolpack_request_id:o};if(v(`[AIClient][${o}] stream() start provider=${n} class=${$} model=${i.model} messages=${i.messages.length} tools=${i.tools?.length||0} tool_choice=${i.tool_choice??"unset"} policy=${c} needsTools=${u} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),Yo(o,i.messages),!this.toolsConfig.enabled||!this.toolsConfig.autoExecute||!this.toolRegistry){yield*r.stream(C);return}let x=[...i.messages],S=0,R=Ae(i.messages),j=this.queryClassifier.classify(R),U=this.toolsConfig.maxToolRounds,L=this.queryClassifier.getToolRoundsAdjustment(j,U);for(L!==U&&v(`[AIClient][${o}] stream() Query classified as ${j.type} (confidence: ${j.confidence.toFixed(2)}), adjusted maxToolRounds: ${U} \u2192 ${L}`);S<=L;){if(e.signal?.aborted){v(`[AIClient][${o}] stream() aborted by signal`);return}let F="",B=[];v(`[AIClient][${o}] stream() round_start ${S+1}/${L}`);let ke=null,ge={...C,messages:x},le=await this.enrichRequestWithTools(ge);S>0&&le.tool_choice==="required"&&(le.tool_choice=y?"none":"auto",v(`[AIClient][${o}] stream() round_${S+1} tool_choice override required->${le.tool_choice}`));for await(let _ of r.stream(le)){if(e.signal?.aborted){v(`[AIClient][${o}] stream() aborted by signal during chunk processing`);return}_.tool_calls&&_.tool_calls.length>0&&(B.push(..._.tool_calls),h(`[AIClient][${o}] stream() tool_calls_chunk count=${_.tool_calls.length} names=${_.tool_calls.map(oe=>oe.name).join(", ")}`),yield _),_.delta&&(F+=_.delta,yield _),_.finish_reason&&(ke=_.finish_reason),_.finish_reason==="stop"&&(yield _)}if(h(`[AIClient][${o}] stream() round_end finish_reason=${ke??"unknown"} accumulated_len=${F.length} tool_calls_total=${B.length} content_preview=${D(F,200)}`),B.length===0)break;if(v(`[AIClient][${o}] stream() received ${B.length} tool call(s): ${B.map(_=>_.name).join(", ")}`),S++,S>L){v(`[AIClient][${o}] stream() max tool rounds (${L}) reached`);break}v(`[AIClient][${o}] stream() tool round ${S}/${L}`),x.push({role:"assistant",content:F||"",tool_calls:B.map(_=>({id:_.id,type:"function",function:{name:_.name,arguments:JSON.stringify(_.arguments)}}))});let ee=3,ce=B,Ue=B.filter(_=>_.name==="web.fetch");if(Ue.length>ee){v(`[AIClient][${o}] Limiting web.fetch calls from ${Ue.length} \u2192 ${ee} to prevent context overflow`);let _=Ue.slice(0,ee);ce=[...B.filter(Re=>Re.name!=="web.fetch"),..._];let re=Ue.slice(ee);for(let Re of re)x.push({role:"tool",tool_call_id:Re.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let he=5e4,W=0,te=!1,O=[];for(let _ of ce){if(te){x.push({role:"tool",tool_call_id:_.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let oe=Date.now(),re=!1,Re=setInterval(()=>{re||O.push({delta:""})},500),ye=await this.executeTool(_);re=!0,clearInterval(Re);let Hg=Date.now()-oe;for(;O.length>0;)yield O.shift();await new Promise(Qg=>setTimeout(Qg,0));let zg=typeof ye=="string"?ye:JSON.stringify(ye);if(W+zg.length>he){E(`[AIClient][${o}] Tool output budget exceeded (${he} chars), adding placeholder for remaining tools`),x.push({role:"tool",tool_call_id:_.id,content:"[Skipped: tool output budget exceeded for this round]"}),te=!0;continue}let Ee=typeof ye=="string"&&ye.length>this.toolResultMaxChars?`${ye.slice(0,this.toolResultMaxChars)}
|
|
154
|
+
[TRUNCATED tool result: ${ye.length} chars]`:ye,Kg=typeof Ee=="string"?Ee:JSON.stringify(Ee);W+=Kg.length,x.push({role:"tool",tool_call_id:_.id,content:Ee}),yield{delta:"",tool_calls:[{..._,result:typeof Ee=="string"?Ee:JSON.stringify(Ee),duration:Hg}]}}h(`[AIClient][${o}] Round tool output size: ${W} chars (budget: ${he})`),Me("debug")&&(h(`[AIClient][${o}] stream() after_tools messages=${x.length}`),Yo(o,x))}}catch(o){throw this.wrapError(o)}}async embed(e,t){let r=this.getProvider(t);try{return await r.embed(e)}catch(o){throw this.wrapError(o)}}async enrichRequestWithTools(e){if(this.activeMode?.blockAllTools)return v(`[AIClient] Mode "${this.activeMode.displayName}" blocks all tools`),e;if(!this.toolsConfig.enabled||!this.toolRegistry&&(e.tools?.length||0)===0)return h("[AIClient] Tools disabled or no registry"),e;let t=this.toolsConfig;if(this.activeMode?.toolSearch&&this.toolsConfig.toolSearch&&(t={...this.toolsConfig,toolSearch:{...this.toolsConfig.toolSearch,...this.activeMode.toolSearch.enabled!==void 0?{enabled:this.activeMode.toolSearch.enabled}:{},...this.activeMode.toolSearch.alwaysLoadedTools?{alwaysLoadedTools:this.activeMode.toolSearch.alwaysLoadedTools}:{},...this.activeMode.toolSearch.alwaysLoadedCategories?{alwaysLoadedCategories:this.activeMode.toolSearch.alwaysLoadedCategories}:{}}},h(`[AIClient] Merged mode toolSearch config: enabled=${t.toolSearch?.enabled}, alwaysLoadedTools=${t.toolSearch?.alwaysLoadedTools?.length||0}`)),e.tools&&e.tools.length>0){if(!t.toolSearch?.enabled||!this.toolRegistry)return h(`[AIClient] Request already has ${e.tools.length} tools`),e;let i=await this.toolRouter.resolve(e.messages,this.toolRegistry,t);if(h(`[AIClient] Resolved ${i.length} tools to send: ${i.map(u=>u.name).join(", ")||"none"}`),this.activeMode&&i.length>0){let u=i.length;i=this.filterSchemasByMode(i,this.activeMode);let g=u-i.length;g>0&&v(`[AIClient] Mode "${this.activeMode.displayName}" filtered out ${g} tools`)}let c=new Set(e.tools.map(u=>u.function.name)),p=i.filter(u=>!c.has(u.name)).map(u=>({type:"function",function:{name:u.name,description:u.description,parameters:u.parameters}}));if(p.length===0)return h(`[AIClient] Request already has ${e.tools.length} tools (no new discoveries)`),e;let m={...e,tools:[...e.tools,...p]};return t.toolSearch?.enabled&&this.toolRegistry&&(m=this.injectToolSearchPrompt(m)),m}if(!this.toolRegistry)return h("[AIClient] Tool registry not configured, skipping tool resolution"),e;let r=this.toolRegistry,o=await this.toolRouter.resolve(e.messages,r,t);if(h(`[AIClient] Resolved ${o.length} tools to send: ${o.map(i=>i.name).join(", ")||"none"}`),this.activeMode&&o.length>0){let i=o.length;o=this.filterSchemasByMode(o,this.activeMode);let c=i-o.length;c>0&&v(`[AIClient] Mode "${this.activeMode.displayName}" filtered out ${c} tools`)}if(o.length===0)return e;let n=o.map(i=>({type:"function",function:{name:i.name,description:i.description,parameters:i.parameters}})),a={...e,tools:n};return this.toolsConfig.toolSearch?.enabled&&r&&(a=this.injectToolSearchPrompt(a)),a}filterSchemasByMode(e,t){return e.filter(r=>{if(t.blockedTools.includes(r.name)||t.blockedToolCategories.includes(r.category))return!1;let o=t.allowedTools.length>0,n=t.allowedToolCategories.length>0;if(o||n){let a=o&&t.allowedTools.includes(r.name),i=n&&t.allowedToolCategories.includes(r.category);return a||i}return!0})}injectModeSystemPrompt(e){if(!this.activeMode||!this.activeMode.systemPrompt)return h(`[AIClient] injectModeSystemPrompt: No active mode or empty systemPrompt. activeMode=${this.activeMode?.name}, systemPrompt=${this.activeMode?.systemPrompt?.substring(0,50)}`),e;let t=this.activeMode.systemPrompt;if(h(`[AIClient] injectModeSystemPrompt: Injecting mode prompt for ${this.activeMode.name}, length=${t.length}`),e.messages.some(o=>o.role==="system")){let o=e.messages.map(n=>{if(n.role==="system"){let a=typeof n.content=="string"?n.content:"";return{...n,content:`${a}
|
|
155
155
|
|
|
156
|
-
${t}`}}return n});return{...e,messages:
|
|
156
|
+
${t}`}}return n});return{...e,messages:o}}else return{...e,messages:[{role:"system",content:t},...e.messages]}}injectOverrideSystemPrompt(e){if(!this.overrideSystemPrompt)return e;let t=this.overrideSystemPrompt;if(e.messages.some(o=>o.role==="system")){let o=e.messages.map(n=>{if(n.role==="system"){let a=typeof n.content=="string"?n.content:"";return{...n,content:`${a}
|
|
157
157
|
|
|
158
|
-
${t}`}}return n});return{...e,messages:
|
|
158
|
+
${t}`}}return n});return{...e,messages:o}}else return{...e,messages:[{role:"system",content:t},...e.messages]}}injectBaseAgentContext(e){let t=!0,r=!0,o,n=this.disableBaseContext;if(this.activeMode?.baseContext===!1)return e;this.activeMode?.baseContext&&(t=this.activeMode.baseContext.includeWorkingDirectory!==!1,r=this.activeMode.baseContext.includeToolCategories!==!1,o=this.activeMode.baseContext.custom);let a=o||pi({workingDirectory:process.cwd(),toolCategories:this.toolRegistry?this.toolRegistry.getCategories():[],disabled:n,includeWorkingDirectory:t,includeToolCategories:r});if(!a)return e;if(e.messages.some(c=>c.role==="system")){let c=e.messages.map(p=>{if(p.role==="system"){let m=typeof p.content=="string"?p.content:"";return{...p,content:`${a}
|
|
159
159
|
|
|
160
|
-
${m}`}}return p});return{...e,messages:c}}else return{...e,messages:[{role:"system",content:a},...e.messages]}}injectToolSearchPrompt(e){if(!this.toolRegistry)return e;let t=e.messages.some(a=>a.role==="system"),
|
|
161
|
-
`);a&&(
|
|
160
|
+
${m}`}}return p});return{...e,messages:c}}else return{...e,messages:[{role:"system",content:a},...e.messages]}}injectToolSearchPrompt(e){if(!this.toolRegistry)return e;let t=e.messages.some(a=>a.role==="system"),r=this.toolsConfig.toolSearch?.alwaysLoadedTools??[],o="";if(r.length>0){let a=r.map(i=>{let c=this.toolRegistry?.get(i);return c?` - **${c.name}**: ${c.description}`:null}).filter(Boolean).join(`
|
|
161
|
+
`);a&&(o=`
|
|
162
162
|
|
|
163
163
|
You have these tools always available:
|
|
164
164
|
${a}
|
|
@@ -166,9 +166,9 @@ ${a}
|
|
|
166
166
|
Use these tools directly when appropriate for the task.`)}let n=`
|
|
167
167
|
IMPORTANT: Tool Discovery Instructions
|
|
168
168
|
|
|
169
|
-
You have access to a limited set of tools. If you need a tool that is not in your current list, you MUST use the 'tool.search' tool to discover it.${
|
|
169
|
+
You have access to a limited set of tools. If you need a tool that is not in your current list, you MUST use the 'tool.search' tool to discover it.${o}
|
|
170
170
|
|
|
171
|
-
${
|
|
171
|
+
${Ho(this.toolRegistry)}
|
|
172
172
|
|
|
173
173
|
When you need a tool:
|
|
174
174
|
1. Check if it's in your current tool list
|
|
@@ -178,28 +178,28 @@ When you need a tool:
|
|
|
178
178
|
NEVER guess or hallucinate tool names. ALWAYS use tool.search to discover tools you don't have.
|
|
179
179
|
`.trim();if(t){let a=e.messages.map(i=>{if(i.role==="system"){let c=typeof i.content=="string"?i.content:"";return{...i,content:`${c}
|
|
180
180
|
|
|
181
|
-
${n}`}}return i});return{...e,messages:a}}else return{...e,messages:[{role:"system",content:n},...e.messages]}}async executeTool(e){let t=Date.now();if(this.emit("tool:started",{toolName:e.name,toolCallId:e.id,status:"started",args:e.arguments}),v(`[AIClient] Executing tool: ${e.name} with args: ${
|
|
182
|
-
`);i&&(
|
|
183
|
-
`);c&&i.push({type:"text",text:c})}for(let c of a.tool_calls)i.push({type:"tool_use",id:c.id,name:this.sanitizeToolName(c.function.name),input:typeof c.function.arguments=="string"?JSON.parse(c.function.arguments||"{}"):c.function.arguments});
|
|
181
|
+
${n}`}}return i});return{...e,messages:a}}else return{...e,messages:[{role:"system",content:n},...e.messages]}}async executeTool(e){let t=Date.now();if(this.emit("tool:started",{toolName:e.name,toolCallId:e.id,status:"started",args:e.arguments}),v(`[AIClient] Executing tool: ${e.name} with args: ${D(e.arguments,500)}`),!this.toolRegistry){let o="No tool registry configured";return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:o,duration:Date.now()-t}),JSON.stringify({error:o})}if(Jo(e.name)){let o=this.executeToolSearch(e.arguments),n=Date.now()-t;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof o=="string"?o.substring(0,200):JSON.stringify(o).substring(0,200),duration:n}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:o,duration:n,status:"success",timestamp:Date.now()}),o}let r=this.toolRegistry.get(e.name);if(!r){E(`[AIClient] Tool '${e.name}' not found in registry`);let o=this.findSimilarToolName(e.name),n=o?`Tool '${e.name}' not found. Did you mean '${o}'? Use tool.search to discover available tools.`:`Tool '${e.name}' not found. Use tool.search to discover available tools.`;return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:n,duration:Date.now()-t}),JSON.stringify({error:n})}try{let o={workspaceRoot:process.cwd(),config:this.toolsConfig?.additionalConfigurations??{},log:i=>v(`[Tool] ${i}`)},n=await r.execute(e.arguments,o),a=Date.now()-t;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof n=="string"?n.substring(0,200):JSON.stringify(n).substring(0,200),duration:a}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:n,duration:a,status:"success",timestamp:Date.now()}),v(`[AIClient] Tool ${e.name} executed successfully in ${a}ms result_len=${n?.length??0}`),Me("debug")&&h(`[AIClient] Tool ${e.name} result_preview=${D(n,400)}`),n}catch(o){let n=Date.now()-t,a=o.message||"Tool execution failed";return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:a,duration:n}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:JSON.stringify({error:a}),duration:n,status:"error",timestamp:Date.now()}),Y(`[AIClient] Tool ${e.name} failed: ${D(a,300)}`),JSON.stringify({error:a})}}findSimilarToolName(e){if(!this.toolRegistry)return null;let t=this.toolRegistry.getAll(),r=e.replace(/_/g,".");if(t.some(c=>c.name===r))return r;let o=e.replace(/\./g,"_");if(t.some(c=>c.name===o))return o;let n=e.replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase().replace(/_/g,".");if(t.some(c=>c.name===n))return n;let a=null,i=1/0;for(let c of t){let p=this.levenshteinDistance(e.toLowerCase(),c.name.toLowerCase());p<=2&&p<i&&(i=p,a=c.name)}return a}levenshteinDistance(e,t){let r=[];for(let o=0;o<=t.length;o++)r[o]=[o];for(let o=0;o<=e.length;o++)r[0][o]=o;for(let o=1;o<=t.length;o++)for(let n=1;n<=e.length;n++)t.charAt(o-1)===e.charAt(n-1)?r[o][n]=r[o-1][n-1]:r[o][n]=Math.min(r[o-1][n-1]+1,r[o][n-1]+1,r[o-1][n]+1);return r[t.length][e.length]}executeToolSearch(e){let{query:t,category:r}=e,o=this.toolsConfig.toolSearch?.searchResultLimit??5;v(`[AIClient] Executing tool.search: query="${t}" category=${r||"all"} limit=${o}`);let n=this.bm25Engine.search(t,{limit:o,category:r}),a=n.map(i=>i.toolName);return this.toolRouter.getDiscoveryCache().recordDiscovery(t,a),h(`[AIClient] tool.search found ${n.length} tools: ${a.join(", ")||"none"}`),JSON.stringify({query:t,found:n.length,tools:n.map(i=>({name:i.tool.name,displayName:i.tool.displayName,description:i.tool.description,category:i.tool.category,parameters:i.tool.parameters,relevanceScore:Math.round(i.score*100)/100})),hint:n.length>0?`Found ${n.length} tools. You can now call any of these tools directly.`:`No tools found for "${t}". Try a different search term.`})}wrapError(e){return e instanceof J?e:new I(e.message||"Unknown provider error","UNKNOWN_PROVIDER_ERROR",500,e)}};l();l();var ln=T(require("@anthropic-ai/sdk"),1);l();de();var K=class{name;async getModels(){return[]}getDisplayName(){return this.name||this.constructor.name.replace(/Adapter$/,"")}supportsFileUpload(){return!1}async uploadFile(e){throw new N(`File upload API is not supported by ${this.getDisplayName()}`)}async deleteFile(e){throw new N(`File deletion API is not supported by ${this.getDisplayName()}`)}};de();k();var oo=class extends K{client;constructor(e,t){super(),this.client=new ln.default({apiKey:e,baseURL:t})}supportsFileUpload(){return!0}async uploadFile(e){try{let t=await import("fs");if(!e.filePath)throw new N("Anthropic uploadFile requires a filePath.");return{id:(await this.client.files.create({file:t.createReadStream(e.filePath),purpose:e.purpose||"vision"})).id}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{await this.client.files.delete(e)}catch(t){throw this.handleError(t)}}getDisplayName(){return"Anthropic"}async getModels(){return[{id:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:64e3},{id:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-sonnet-4-6",displayName:"Claude Sonnet 4.6",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-opus-4-5",displayName:"Claude Opus 4.5",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-opus-4-6",displayName:"Claude Opus 4.6",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384}]}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(o=>this.sanitizeToolName(o.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,r=await this.toAnthropicMessages(e.messages,e.mediaOptions),o=r.system,n=r.userMessages,a={model:e.model,messages:n,system:o,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p,stream:!1};e.tools&&e.tools.length>0?(a.tools=e.tools.map(m=>({name:this.sanitizeToolName(m.function.name),description:m.function.description,input_schema:m.function.parameters})),e.tool_choice==="required"?a.tool_choice={type:"any"}:e.tool_choice==="none"?delete a.tools:a.tool_choice={type:"auto"},h(`[Anthropic][${t}] Sending ${a.tools?.length||0} tools with tool_choice: ${a.tool_choice?.type||"unset"}`),a.tools&&a.tools.length>0&&h(`[Anthropic][${t}] First tool: ${D(a.tools[0],800)}`)):h(`[Anthropic][${t}] NO TOOLS in request`),h(`[Anthropic][${t}] generate() request: model=${a.model}, messages=${a.messages.length}, tools=${a.tools?.length||0}, tool_choice=${a.tool_choice?.type??"unset"}`),X(t,"Anthropic",a.messages);let i=await this.client.messages.create(a,e.signal?{signal:e.signal}:void 0),c=[],p=[];for(let m of i.content)m.type==="text"?c.push(m.text):m.type==="tool_use"&&p.push({id:m.id,name:this.restoreToolName(m.name,e.tools),arguments:m.input});return h(`[Anthropic][${t}] Response finish_reason=${i.stop_reason} tool_calls=${p.length} content_preview=${D(c.join(""),200)}`),{content:c.length>0?c.join(""):null,usage:{prompt_tokens:i.usage.input_tokens,completion_tokens:i.usage.output_tokens,total_tokens:i.usage.input_tokens+i.usage.output_tokens},finish_reason:this.mapFinishReason(i.stop_reason),tool_calls:p.length>0?p:void 0,raw:i}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`str-${Date.now()}`,r=await this.toAnthropicMessages(e.messages,e.mediaOptions),o={model:e.model,messages:r.userMessages,system:r.system,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p,stream:!0};e.tools&&e.tools.length>0?(o.tools=e.tools.map(m=>({name:this.sanitizeToolName(m.function.name),description:m.function.description,input_schema:m.function.parameters})),e.tool_choice==="required"?o.tool_choice={type:"any"}:e.tool_choice==="none"?delete o.tools:o.tool_choice={type:"auto"},h(`[Anthropic][${t}] Sending ${o.tools?.length||0} tools with tool_choice: ${o.tool_choice?.type||"unset"}`),o.tools&&o.tools.length>0&&h(`[Anthropic][${t}] First tool: ${D(o.tools[0],800)}`)):h(`[Anthropic][${t}] NO TOOLS in request`),h(`[Anthropic][${t}] Stream request: model=${o.model}, messages=${o.messages.length}, tools=${o.tools?.length||0}, tool_choice=${o.tool_choice?.type??"unset"}`),X(t,"Anthropic",o.messages);let n=await this.client.messages.create(o,e.signal?{signal:e.signal}:void 0),a="",i="",c="",p=!1;for await(let m of n)m.type==="content_block_start"&&m.content_block?.type==="tool_use"&&(p=!0,a=m.content_block.id,i=m.content_block.name,c=""),m.type==="content_block_delta"&&(m.delta.type==="text_delta"?yield{delta:m.delta.text}:m.delta.type==="input_json_delta"&&p&&(c+=m.delta.partial_json)),m.type==="content_block_stop"&&p&&(h(`[Anthropic][${t}] Stream finish_reason=tool_calls accumulated_call=${i}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:a,name:this.restoreToolName(i,e.tools),arguments:JSON.parse(c||"{}")}]},p=!1),m.type==="message_stop"&&(be(`[Anthropic][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"})}catch(t){throw this.handleError(t)}}async embed(e){throw new N("Embeddings are not strictly supported by the Anthropic API currently.")}async toAnthropicMessages(e,t={}){let r,o=[],{normalizeImagePart:n}=await Promise.resolve().then(()=>(ze(),to));for(let a of e)if(a.role==="system"){if(typeof a.content=="string")r=a.content;else if(a.content!==null){let i=a.content.filter(c=>typeof c=="object"&&c.type==="text").map(c=>c.text).join(`
|
|
182
|
+
`);i&&(r=i)}}else if(a.role==="tool"&&a.tool_call_id)o.push({role:"user",content:[{type:"tool_result",tool_use_id:a.tool_call_id,content:typeof a.content=="string"?a.content:JSON.stringify(a.content)}]});else if(a.role==="assistant"&&a.tool_calls&&a.tool_calls.length>0){let i=[];if(typeof a.content=="string"&&a.content)i.push({type:"text",text:a.content});else if(Array.isArray(a.content)){let c=a.content.filter(p=>typeof p=="object"&&p.type==="text").map(p=>p.text).join(`
|
|
183
|
+
`);c&&i.push({type:"text",text:c})}for(let c of a.tool_calls)i.push({type:"tool_use",id:c.id,name:this.sanitizeToolName(c.function.name),input:typeof c.function.arguments=="string"?JSON.parse(c.function.arguments||"{}"):c.function.arguments});o.push({role:"assistant",content:i})}else{let i=[];typeof a.content=="string"?i=a.content:a.content!==null&&(i=(await Promise.all(a.content.map(async c=>{if(c.type==="text")return{type:"text",text:c.text};if(c.type==="image_url"){let p=c.image_url.url;if(p.startsWith("data:")){let m=p.match(/^data:(image\/\w+);base64,(.+)$/);if(m)return{type:"image",source:{type:"base64",media_type:m[1],data:m[2]}}}return{type:"image",source:{type:"url",url:p}}}if(c.type==="image_data"||c.type==="image_file"){let{data:p,mimeType:m}=await n(c);return{type:"image",source:{type:"base64",media_type:m,data:p}}}return null}))).filter(Boolean)),o.push({role:a.role==="user"?"user":"assistant",content:i})}return{system:r,userMessages:o}}mapFinishReason(e){return e==="end_turn"?"stop":e==="max_tokens"?"length":e==="stop_sequence"?"stop":e}handleError(e){if(e instanceof ln.default.APIError){let t=e.message;return e.status===401?new pe(t,e):e.status===429?new me(t,void 0,e):e.status&&e.status>=400&&e.status<500?new N(t,e):new I(t,"ANTHROPIC_ERROR",e.status||500,e)}return new I("Unknown Anthropic error","UNKNOWN",500,e)}};l();var $i=require("@google/generative-ai");de();k();var ro=class extends K{genAI;constructor(e){super(),this.genAI=new $i.GoogleGenerativeAI(e)}supportsFileUpload(){return!0}sanitizeSchema(e){if(!e||typeof e!="object")return e;let t={};for(let[r,o]of Object.entries(e))r==="additionalProperties"||r==="exclusiveMinimum"||r==="exclusiveMaximum"||r==="$schema"||r==="$id"||r==="definitions"||r==="$defs"||(typeof o=="object"&&o!==null?Array.isArray(o)?t[r]=o.map(n=>this.sanitizeSchema(n)):t[r]=this.sanitizeSchema(o):t[r]=o);return t}async uploadFile(e){try{let t=await import("fs"),r=await import("path");if(!e.filePath)throw new N("Gemini uploadFile requires a filePath.");let o=await t.promises.readFile(e.filePath),n=r.basename(e.filePath),a=e.mimeType||"application/octet-stream",c=`https://generativelanguage.googleapis.com/upload/v1beta/files?key=${this.genAI.apiKey}`,p="----WebKitFormBoundary"+Math.random().toString(36).substring(2),m=JSON.stringify({file:{displayName:n}}),u=Buffer.concat([Buffer.from(`--${p}\r
|
|
184
184
|
Content-Type: application/json\r
|
|
185
185
|
\r
|
|
186
186
|
${m}\r
|
|
187
187
|
`),Buffer.from(`--${p}\r
|
|
188
188
|
Content-Type: ${a}\r
|
|
189
189
|
\r
|
|
190
|
-
`),
|
|
190
|
+
`),o,Buffer.from(`\r
|
|
191
191
|
--${p}--\r
|
|
192
|
-
`)]),g=await fetch(c,{method:"POST",headers:{"Content-Type":`multipart/related; boundary=${p}`},body:u});if(!g.ok){let y=await g.text();throw new Error(`Gemini file upload failed: ${g.status} ${y}`)}let
|
|
192
|
+
`)]),g=await fetch(c,{method:"POST",headers:{"Content-Type":`multipart/related; boundary=${p}`},body:u});if(!g.ok){let y=await g.text();throw new Error(`Gemini file upload failed: ${g.status} ${y}`)}let w=await g.json();return{id:w.file?.name||w.name,url:w.file?.uri||w.uri}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{let t=this.genAI.apiKey,r=`https://generativelanguage.googleapis.com/v1beta/${e}?key=${t}`,o=await fetch(r,{method:"DELETE"});if(!o.ok){let n=await o.text();throw new Error(`Gemini file deletion failed: ${o.status} ${n}`)}}catch(t){throw this.handleError(t)}}getDisplayName(){return"Google Gemini"}async getModels(){return[{id:"gemini-3.1-flash-lite-preview",displayName:"Gemini 3.1 Flash-Lite Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-3-flash-preview",displayName:"Gemini 3 Flash Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-3.1-pro-preview",displayName:"Gemini 3.1 Pro Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1048576,maxOutputTokens:65536}]}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(o=>this.sanitizeToolName(o.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,r={model:e.model,systemInstruction:this.extractSystemInstruction(e.messages)};e.tools&&e.tools.length>0?(r.tools=[{functionDeclarations:e.tools.map(g=>({name:this.sanitizeToolName(g.function.name),description:g.function.description,parameters:this.sanitizeSchema(g.function.parameters)}))}],h(`[Gemini][${t}] Sending ${e.tools.length} tools`),e.tools.length>0&&h(`[Gemini][${t}] First tool: ${D(e.tools[0],800)}`)):h(`[Gemini][${t}] NO TOOLS in request`),h(`[Gemini][${t}] generate() request: model=${e.model}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),X(t,"Gemini",e.messages);let o=this.genAI.getGenerativeModel(r),{history:n,lastUserMessage:a}=await this.formatHistory(e.messages,e.mediaOptions),p=await(await o.startChat({history:n,generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:e.response_format==="json_object"?"application/json":"text/plain"}}).sendMessage(a)).response,m=[],u="";for(let g of p.candidates||[])for(let w of g.content?.parts||[])if(w.text&&(u+=w.text),w.functionCall){let y=w.functionCall;m.push({id:`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(y.name,e.tools),arguments:y.args||{}})}return h(`[Gemini][${t}] Response finish_reason=${m.length>0?"tool_calls":"stop"} tool_calls=${m.length} content_preview=${D(u,200)}`),{content:u||null,usage:{prompt_tokens:p.usageMetadata?.promptTokenCount||0,completion_tokens:p.usageMetadata?.candidatesTokenCount||0,total_tokens:p.usageMetadata?.totalTokenCount||0},finish_reason:m.length>0?"tool_calls":"stop",tool_calls:m.length>0?m:void 0,raw:p}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t={model:e.model,systemInstruction:this.extractSystemInstruction(e.messages)};e.tools&&e.tools.length>0&&(t.tools=[{functionDeclarations:e.tools.map(p=>({name:this.sanitizeToolName(p.function.name),description:p.function.description,parameters:this.sanitizeSchema(p.function.parameters)}))}]);let r=e.__toolpack_request_id||`str-${Date.now()}`;h(`[Gemini][${r}] Stream request: model=${e.model}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),e.tools&&e.tools.length>0&&h(`[Gemini][${r}] First tool: ${D(e.tools[0],800)}`),X(r,"Gemini",e.messages);let o=this.genAI.getGenerativeModel(t),{history:n,lastUserMessage:a}=await this.formatHistory(e.messages,e.mediaOptions),c=await o.startChat({history:n,generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:e.response_format==="json_object"?"application/json":"text/plain"}}).sendMessageStream(a);for await(let p of c.stream){for(let m of p.candidates?.[0]?.content?.parts||[])m.functionCall?(h(`[Gemini][${r}] Stream finish_reason=tool_calls name=${m.functionCall.name}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(m.functionCall.name,e.tools),arguments:m.functionCall.args||{}}]}):m.text&&(yield{delta:m.text});try{let m=p.text();m&&!p.candidates?.[0]?.content?.parts?.some(u=>u.text)&&(yield{delta:m})}catch{}}}catch(t){throw this.handleError(t)}}async embed(e){try{let t=this.genAI.getGenerativeModel({model:e.model});return Array.isArray(e.input)?{embeddings:await Promise.all(e.input.map(async o=>(await t.embedContent(o)).embedding.values))}:{embeddings:[(await t.embedContent(e.input)).embedding.values]}}catch(t){throw this.handleError(t)}}extractSystemInstruction(e){let t=e.filter(r=>r.role==="system");if(t.length!==0)return t.map(r=>typeof r.content=="string"?r.content:r.content===null?"":r.content.map(o=>o.text).join(`
|
|
193
193
|
`)).join(`
|
|
194
|
-
`)}async formatHistory(e,t={}){let
|
|
195
|
-
`);g&&u.push({text:g})}for(let g of m.tool_calls)u.push({functionCall:{name:this.sanitizeToolName(g.function.name),args:typeof g.function.arguments=="string"?JSON.parse(g.function.arguments||"{}"):g.function.arguments}});return{role:"model",parts:u}}return{role:m.role==="user"?"user":"model",parts:await i(m.content)}})),p=typeof
|
|
196
|
-
`);u=y.pop()||"";for(let
|
|
197
|
-
Available models: ${e.map(
|
|
198
|
-
`;else if(i.type==="image_url"||i.type==="image_data"||i.type==="image_file")try{let{data:c}=await n(i);
|
|
199
|
-
`:
|
|
200
|
-
`}o=o.trim()}let a={role:e.role,content:o};return r.length>0&&(a.images=r),e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0?a.tool_calls=e.tool_calls.map(i=>({function:{name:this.sanitizeToolName(i.function.name),arguments:typeof i.function.arguments=="string"?JSON.parse(i.function.arguments||"{}"):i.function.arguments}})):e.role==="tool"&&(a.content=o||JSON.stringify(e.content),e.name&&(a.tool_name=this.sanitizeToolName(e.name))),a}handleHttpError(e,t){let o=`Ollama error (HTTP ${e})`;try{let r=JSON.parse(t);r.error&&(o=`Ollama: ${r.error}`)}catch{}return e===404?new N(`Model not found: ${o}`):new I(o,"OLLAMA_ERROR",e)}};l();var He=class extends K{baseUrl;timeout;adapterCache=new Map;capabilityCache=new Map;constructor(e){super(),this.baseUrl=e?.baseUrl||"http://localhost:11434",this.timeout=12e4}getDisplayName(){return"Ollama"}async getModels(){let e;try{let t=await ne(this.baseUrl,"/api/tags","GET",void 0,5e3);if(t.status!==200)return[];e=JSON.parse(t.body).models||[]}catch{return[]}return Promise.all(e.map(t=>this.buildModelInfo(t)))}async generate(e){return this.getAdapterForModel(e.model).generate(this.stripToolsIfNeeded(e))}async*stream(e){yield*this.getAdapterForModel(e.model).stream(this.stripToolsIfNeeded(e))}async embed(e){return this.getAdapterForModel(e.model).embed(e)}async disconnect(){this.adapterCache.clear(),this.capabilityCache.clear()}stripToolsIfNeeded(e){let t=this.capabilityCache.get(e.model);if(t&&!t.toolCalling&&e.tools&&e.tools.length>0){let{tools:o,tool_choice:r,...n}=e,a=n,i={role:"system",content:"You do not have access to any tools or functions. Do not attempt to call tools, output tool invocations, or reference tool usage. Answer the user directly using only your own knowledge."};return a.messages=[...a.messages,i],a}return e}getAdapterForModel(e){let t=this.adapterCache.get(e);return t||(t=new xe({model:e,baseUrl:this.baseUrl,timeout:this.timeout}),this.adapterCache.set(e,t)),t}async buildModelInfo(e){let t=!1,o=!1,r=!1;try{let i=await ne(this.baseUrl,"/api/show","POST",{model:e.name},3e3);if(i.status===200){let p=(JSON.parse(i.body).details?.families||[]).map(m=>m.toLowerCase());o=p.some(m=>["clip","mllama"].includes(m)),r=p.some(m=>m.includes("bert")||m.includes("nomic"))}}catch{}t=await this.probeToolSupport(e.name);let n=e.name.toLowerCase();o||(o=["llava","vision","bakllava","moondream"].some(c=>n.includes(c))),r||(r=["nomic-embed","mxbai-embed","all-minilm","bge-","snowflake-arctic-embed"].some(c=>n.includes(c)));let a={toolCalling:t,vision:o,embeddings:r};return this.capabilityCache.set(e.name,a),{id:e.name,displayName:e.name,capabilities:{chat:!0,streaming:!0,toolCalling:t,embeddings:r,vision:o}}}async probeToolSupport(e){try{let t=await ne(this.baseUrl,"/api/chat","POST",{model:e,messages:[{role:"user",content:"hi"}],tools:[{type:"function",function:{name:"__probe",description:"probe",parameters:{type:"object",properties:{}}}}],stream:!1},1e4);return t.status>=400?!1:!JSON.parse(t.body).error}catch{return!1}}};l();var cn=[{model:"qwen2.5-coder:3b",label:"Qwen 2.5 Coder 3B",params:"3B",size:"~2GB",selectorCapability:5,description:"Best code understanding at small size. Excellent HTML/CSS comprehension."},{model:"phi3:mini",label:"Phi-3 Mini",params:"3.8B",size:"~2.3GB",selectorCapability:4,description:"Strong reasoning for its size. Good at structured output."},{model:"codegemma:2b",label:"CodeGemma 2B",params:"2B",size:"~1.4GB",selectorCapability:4,description:"Compact code model from Google. Fast inference."},{model:"deepseek-coder:1.3b",label:"DeepSeek Coder 1.3B",params:"1.3B",size:"~0.8GB",selectorCapability:3,description:"Smallest viable option. Very fast but less accurate."},{model:"qwen2.5-coder:7b",label:"Qwen 2.5 Coder 7B",params:"7B",size:"~4.5GB",selectorCapability:5,description:"Higher accuracy than 3B variant. Requires more RAM/VRAM."},{model:"codellama:7b",label:"Code Llama 7B",params:"7B",size:"~3.8GB",selectorCapability:4,description:"Meta code model. Solid HTML/CSS understanding."}];function Si(){return cn[0].model}function $i(s){let e=s.toLowerCase();return cn.some(t=>t.model.toLowerCase()===e||t.model.split(":")[0].toLowerCase()===e.split(":")[0].toLowerCase())}function _i(){return[...cn]}l();var pn=P(require("openai"),1);de();_();var so=class extends K{client;constructor(e,t){super(),this.client=new pn.default({apiKey:e,baseURL:t,timeout:6e4,maxRetries:2})}supportsFileUpload(){return!0}async uploadFile(e){try{let t=await import("fs");if(!e.filePath)throw new N("OpenAI uploadFile requires a filePath.");return{id:(await this.client.files.create({file:t.createReadStream(e.filePath),purpose:e.purpose||"vision"})).id}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{await this.client.files.delete(e)}catch(t){throw this.handleError(t)}}getDisplayName(){return"OpenAI"}async getModels(){return[{id:"gpt-4.1-mini",displayName:"GPT-4.1 Mini",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1047576,maxOutputTokens:32768,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:null,costTier:"low"},{id:"gpt-4.1",displayName:"GPT-4.1",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1047576,maxOutputTokens:32768,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:null,costTier:"medium"},{id:"gpt-5.1",displayName:"GPT-5.1",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:4e5,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"medium"},{id:"gpt-5.2",displayName:"GPT-5.2",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:4e5,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"high"},{id:"gpt-5.4",displayName:"GPT-5.4",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:105e4,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"high"},{id:"gpt-5.4-pro",displayName:"GPT-5.4 Pro",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:105e4,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"extended",costTier:"premium"}]}sanitizeToolName(e){return e.replace(/\./g,"_")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,r={messages:await Promise.all(e.messages.map(u=>this.toOpenAIMessage(u,e.mediaOptions))),model:e.model,temperature:e.temperature,max_tokens:e.max_tokens,top_p:e.top_p,response_format:e.response_format==="json_object"?{type:"json_object"}:void 0,stream:!1},n=new Map;e.tools&&e.tools.length>0&&(r.tools=e.tools.map(u=>{let g=this.sanitizeToolName(u.function.name);return n.set(g,u.function.name),{type:"function",function:{name:g,description:u.function.description,parameters:u.function.parameters}}}),r.tool_choice=e.tool_choice||"auto",h(`[OpenAI][${t}] Sending ${r.tools.length} tools with tool_choice: ${r.tool_choice}`),h(`[OpenAI][${t}] First tool: ${E(r.tools[0],800)}`)),h(`[OpenAI][${t}] Request params: ${E({model:r.model,messages_count:r.messages.length,has_tools:!!r.tools,tools_count:r.tools?.length,tool_choice:r.tool_choice},800)}`),X(t,"OpenAI",r.messages);let a=await this.client.chat.completions.create(r,e.signal?{signal:e.signal}:void 0);be(`[OpenAI][${t}] Raw completion: ${JSON.stringify(a)}`);let i=a.choices[0].message;h(`[OpenAI][${t}] Response: finish_reason=${a.choices[0].finish_reason}`),h(`[OpenAI][${t}] Response has tool_calls: ${!!i.tool_calls}, count: ${i.tool_calls?.length||0}`),h(`[OpenAI][${t}] Response content: ${JSON.stringify(i.content)}`),i.content&&h(`[OpenAI][${t}] Response content preview: ${E(i.content,200)}`);let c=a.choices[0],p,m=c.message.tool_calls;return m&&m.length>0&&(p=m.map(u=>({id:u.id,name:n.get(u.function.name)||u.function.name,arguments:JSON.parse(u.function.arguments)}))),{content:c.message.content,usage:a.usage?{prompt_tokens:a.usage.prompt_tokens,completion_tokens:a.usage.completion_tokens,total_tokens:a.usage.total_tokens}:void 0,finish_reason:c.finish_reason,tool_calls:p,raw:a}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`str-${Date.now()}`,r={messages:await Promise.all(e.messages.map(c=>this.toOpenAIMessage(c,e.mediaOptions))),model:e.model,temperature:e.temperature,max_tokens:e.max_tokens,top_p:e.top_p,response_format:e.response_format==="json_object"?{type:"json_object"}:void 0,stream:!0},n=new Map;e.tools&&e.tools.length>0?(r.tools=e.tools.map(c=>{let p=this.sanitizeToolName(c.function.name);return n.set(p,c.function.name),{type:"function",function:{name:p,description:c.function.description,parameters:c.function.parameters}}}),r.tool_choice=e.tool_choice||"auto",h(`[OpenAI][${t}] Sending ${r.tools.length} tools with tool_choice: ${r.tool_choice}`),h(`[OpenAI][${t}] First tool: ${E(r.tools[0],800)}`)):h(`[OpenAI][${t}] NO TOOLS in request`),h(`[OpenAI][${t}] Stream request: model=${r.model}, messages=${r.messages.length}, tools=${r.tools?.length||0}, tool_choice=${r.tool_choice??"unset"}`),X(t,"OpenAI",r.messages);let a=await this.client.chat.completions.create(r,e.signal?{signal:e.signal}:void 0),i=new Map;for await(let c of a){let p=c.choices[0];if(p.finish_reason&&be(`[OpenAI][${t}] Stream chunk finish_reason=${p.finish_reason}`),p.delta.tool_calls)for(let m of p.delta.tool_calls){let u=m.index;i.has(u)||i.set(u,{id:m.id||"",name:m.function?.name||"",args:""});let g=i.get(u);m.id&&(g.id=m.id),m.function?.name&&(g.name=m.function.name),m.function?.arguments&&(g.args+=m.function.arguments),be(`[OpenAI][${t}] tool_call_delta idx=${u} id=${m.id||g.id||""} name=${m.function?.name||g.name||""} args_delta=${E(m.function?.arguments||"",200)}`)}if(p.delta.content&&(yield{delta:p.delta.content,finish_reason:p.finish_reason,usage:c.usage}),!p.delta.content&&p.finish_reason&&p.finish_reason!=="tool_calls"&&(yield{delta:"",finish_reason:p.finish_reason,usage:c.usage}),p.finish_reason==="tool_calls"&&i.size>0){let m=Array.from(i.values()).map(u=>({id:u.id,name:n.get(u.name)||u.name,arguments:JSON.parse(u.args||"{}")}));h(`[OpenAI][${t}] Stream finish_reason=tool_calls accumulated_calls=${m.length} names=${m.map(u=>u.name).join(", ")}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:m}}}}catch(t){throw this.handleError(t)}}async embed(e){try{let t=typeof e.input=="string"?[e.input]:e.input,o=await this.client.embeddings.create({model:e.model,input:t});return{embeddings:o.data.map(r=>r.embedding),usage:o.usage}}catch(t){throw this.handleError(t)}}async toOpenAIMessage(e,t={}){if(e.role==="tool"&&e.tool_call_id)return{role:"tool",tool_call_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content??"")};if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0)return{role:"assistant",content:typeof e.content=="string"?e.content:"",tool_calls:e.tool_calls.map(n=>({id:n.id,type:"function",function:{name:this.sanitizeToolName(n.function.name),arguments:n.function.arguments}}))};if(typeof e.content=="string")return{role:e.role,content:e.content};if(e.content===null||e.content===void 0)return{role:e.role,content:""};let{normalizeImagePart:o}=await Promise.resolve().then(()=>(Je(),Zt)),r=await Promise.all(e.content.map(async n=>{if(n.type==="text")return{type:"text",text:n.text};if(n.type==="image_url")return{type:"image_url",image_url:{url:n.image_url.url}};if(n.type==="image_data"||n.type==="image_file"){let{data:a,mimeType:i}=await o(n);return{type:"image_url",image_url:{url:`data:${i};base64,${a}`}}}return null}));return{role:e.role,content:r.filter(Boolean)}}handleError(e){if(e instanceof pn.default.APIError){let t=e.message;return e.status===401?new pe(t,e):e.status===429?new me(t,void 0,e):e.status&&e.status>=400&&e.status<500?new N(t,e):new I(t,e.code||"OPENAI_ERROR",e.status||500,e)}return new I("Unknown error","UNKNOWN",500,e)}};Je();l();Yt();l();Yt();var Gt=class{tools=new Map;projects=new Map;config=H;register(e){this.tools.set(e.name,e)}registerCustom(e){this.tools.set(e.name,e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getNames(){return Array.from(this.tools.keys())}getByCategory(e){return Array.from(this.tools.values()).filter(t=>t.category===e)}getEnabled(){if(this.config.enabledTools.length===0&&this.config.enabledToolCategories.length===0)return Array.from(this.tools.values());let e=this.getByNames(this.config.enabledTools),t=this.getByCategories(this.config.enabledToolCategories),o=new Set,r=[];for(let n of[...e,...t])o.has(n.name)||(o.add(n.name),r.push(n));return r}getSchemas(e){return(e?e.map(o=>this.tools.get(o)).filter(Boolean):this.getEnabled()).map(o=>({name:o.name,displayName:o.displayName,description:o.description,parameters:o.parameters,category:o.category}))}getByNames(e){return e.map(t=>this.tools.get(t)).filter(Boolean)}getByCategories(e){let t=new Set(e);return Array.from(this.tools.values()).filter(o=>t.has(o.category))}getCategories(){let e=new Set;for(let t of this.tools.values())e.add(t.category);return Array.from(e)}getAll(){return Array.from(this.tools.values())}setConfig(e){this.config=e}getConfig(){return this.config}get size(){return this.tools.size}async validateDependencies(e){let t=e.dependencies;if(!t||Object.keys(t).length===0)return[];let o=[];for(let r of Object.keys(t))try{await import(r)}catch{o.push(r)}return o}async loadProject(e){let t=await this.validateDependencies(e);if(t.length>0)throw new Error(`Tool project "${e.manifest.name}" has missing dependencies: ${t.join(", ")}. Install them with: npm install ${t.join(" ")}`);this.projects.set(e.manifest.name,e);for(let o of e.tools)this.register(o)}async loadProjects(e){for(let t of e)await this.loadProject(t)}getProject(e){return this.projects.get(e)}getProjects(){return Array.from(this.projects.values())}getProjectNames(){return Array.from(this.projects.keys())}async loadBuiltIn(){let{fsToolsProject:e}=await Promise.resolve().then(()=>(En(),Ul)),{execToolsProject:t}=await Promise.resolve().then(()=>(Ln(),Dc)),{systemToolsProject:o}=await Promise.resolve().then(()=>(Kn(),cp)),{httpToolsProject:r}=await Promise.resolve().then(()=>(ts(),Jp)),{webToolsProject:n}=await Promise.resolve().then(()=>(gs(),ud)),{codingToolsProject:a}=await Promise.resolve().then(()=>(As(),tf)),{gitToolsProject:i}=await Promise.resolve().then(()=>(Os(),Ef)),{diffToolsProject:c}=await Promise.resolve().then(()=>(Fs(),Jf)),{dbToolsProject:p}=await Promise.resolve().then(()=>(Ws(),wg)),{cloudToolsProject:m}=await Promise.resolve().then(()=>(Bs(),Rg));await this.loadProjects([e,t,o,r,n,a,i,c,p,m])}};ns();l();_();function Dg(s){if(!s.key||!/^[a-z0-9-]+$/.test(s.key))throw new Error(`Invalid tool project key: "${s.key}". Must be non-empty, lowercase, and contain no spaces (use hyphens).`);if(!s.name.trim())throw new Error("Tool project name cannot be empty.");if(!s.tools||s.tools.length===0)throw new Error("Tool project must contain at least one tool.");for(let t of s.tools){if(!t.name)throw new Error("Tool is missing a name.");if(!t.description)throw new Error(`Tool "${t.name}" is missing a description.`);if(!t.parameters)throw new Error(`Tool "${t.name}" is missing parameters.`);if(typeof t.execute!="function")throw new Error(`Tool "${t.name}" is missing an execute function.`);t.category!==s.category&&D(`[Toolpack] Tool "${t.name}" has category "${t.category}" which does not match project category "${s.category}".`)}let e=s.tools.map(t=>t.name);return{manifest:{key:s.key,name:s.name,displayName:s.displayName,version:s.version,description:s.description,author:s.author,repository:s.repository,category:s.category,tools:e},dependencies:s.dependencies,tools:s.tools}}En();Ln();Kn();ts();gs();As();Os();Fs();Ws();Bs();l();l();var Eg=require("child_process"),Ng=require("events");_();var Oo=class extends Error{constructor(e,t){super(`MCP request timed out after ${t}ms: ${e}`),this.name="McpTimeoutError"}},ae=class extends Error{constructor(t,o){super(t);this.exitCode=o;this.name="McpConnectionError"}exitCode},Bt=class extends Ng.EventEmitter{constructor(t){super();this.config=t;this.defaultTimeoutMs=t.requestTimeoutMs??3e4,this.autoReconnect=t.autoReconnect??!1,this.maxReconnectAttempts=t.maxReconnectAttempts??3,this.reconnectDelayMs=t.reconnectDelayMs??1e3}config;process=null;messageQueue=new Map;nextId=1;buffer="";_connected=!1;_shuttingDown=!1;_reconnectAttempts=0;defaultTimeoutMs;autoReconnect;maxReconnectAttempts;reconnectDelayMs;get connected(){return this._connected&&this.process!==null}async connect(){if(this._shuttingDown)throw new ae("Client is shutting down");return new Promise((t,o)=>{try{if(this.buffer="",this.process=(0,Eg.spawn)(this.config.command,this.config.args||[],{env:{...process.env,...this.config.env},stdio:["pipe","pipe","pipe"]}),!this.process.stdout||!this.process.stdin)throw new ae("Failed to spawn MCP server: stdout/stdin unavailable");this.process.stdout.on("data",r=>{this.handleData(r)}),this.process.stderr&&this.process.stderr.on("data",r=>{D(`[MCP server stderr] ${r.toString().trim()}`)}),this.process.on("error",r=>{this._connected=!1,this.emit("error",r)}),this.process.on("exit",r=>{let n=this._connected;this._connected=!1,this.process=null,this.rejectAllPending(new ae(`MCP server exited with code ${r}`,r)),this.emit("close",r),n&&!this._shuttingDown&&this.autoReconnect&&this.attemptReconnect()}),this._connected=!0,this._reconnectAttempts=0,setTimeout(t,500)}catch(r){o(r)}})}async attemptReconnect(){if(this._reconnectAttempts>=this.maxReconnectAttempts){this.emit("reconnect_failed",this._reconnectAttempts);return}this._reconnectAttempts++;let t=this._reconnectAttempts;if(this.emit("reconnecting",{attempt:t,max:this.maxReconnectAttempts}),await new Promise(o=>setTimeout(o,this.reconnectDelayMs*t)),!this._shuttingDown)try{await this.connect(),this.emit("reconnected",{attempt:t})}catch(o){this.emit("reconnect_error",{attempt:t,error:o})}}handleData(t){this.buffer+=t.toString();let o;for(;(o=this.buffer.indexOf(`
|
|
201
|
-
`))!==-1;){let
|
|
202
|
-
`)}catch(u){m&&clearTimeout(m),this.messageQueue.delete(n),p(u)}})}async disconnect(t=3e3){if(this._shuttingDown=!0,this.rejectAllPending(new ae("Client disconnecting")),!this.process){this._shuttingDown=!1;return}let
|
|
194
|
+
`)}async formatHistory(e,t={}){let r=e.filter(m=>m.role!=="system");if(r.length===0)return{history:[],lastUserMessage:""};let o=r[r.length-1],n=r.slice(0,r.length-1),{normalizeImagePart:a}=await Promise.resolve().then(()=>(ze(),to)),i=async m=>typeof m=="string"?[{text:m}]:m===null?[]:(await Promise.all(m.map(async g=>{if(g.type==="text")return{text:g.text};if(g.type==="image_data"||g.type==="image_file"||g.type==="image_url")try{let{data:w,mimeType:y}=await a(g);return{inlineData:{mimeType:y,data:w}}}catch{return g.type==="image_url"?{text:`[Image: ${g.image_url.url}]`}:{text:"[Unresolvable Image]"}}return null}))).filter(Boolean),c=await Promise.all(n.map(async m=>{if(m.role==="tool"&&m.tool_call_id)return{role:"function",parts:[{functionResponse:{name:this.sanitizeToolName(m.name||m.tool_call_id),response:{name:this.sanitizeToolName(m.name||m.tool_call_id),content:typeof m.content=="string"?m.content:JSON.stringify(m.content)}}}]};if(m.role==="assistant"&&m.tool_calls&&m.tool_calls.length>0){let u=[];if(typeof m.content=="string"&&m.content)u.push({text:m.content});else if(Array.isArray(m.content)){let g=m.content.filter(w=>typeof w=="object"&&w.type==="text").map(w=>w.text).join(`
|
|
195
|
+
`);g&&u.push({text:g})}for(let g of m.tool_calls)u.push({functionCall:{name:this.sanitizeToolName(g.function.name),args:typeof g.function.arguments=="string"?JSON.parse(g.function.arguments||"{}"):g.function.arguments}});return{role:"model",parts:u}}return{role:m.role==="user"?"user":"model",parts:await i(m.content)}})),p=typeof o.content=="string"?o.content:await i(o.content);return{history:c,lastUserMessage:p}}handleError(e){return e.status===429?new me(e.message,void 0,e):e.status>=400&&e.status<500?new N(e.message,e):e.message&&e.message.includes("API key")?new pe(e.message,e):new I(e.message||"Gemini Error","GEMINI_ERROR",e.status||500,e)}};l();var so=T(require("fs"),1),_i=T(require("path"),1),ah="toolpack.config.json";function cn(s){if(s&&so.existsSync(s))return s;let e=_i.join(process.cwd(),ah);return so.existsSync(e)?e:null}function lh(s){if(!s)return null;try{let e=so.readFileSync(s,"utf-8");return JSON.parse(e)}catch{return null}}var no=null;function Vo(s){if(no)return no;let e=s||cn();return no=lh(e)||{},no}function ki(){no=null}function Ri(s){return(Vo(s).ollama?.models||[]).map(r=>({type:`ollama-${r.model.replace(/[:.]/g,"-")}`,model:r.model,label:r.label||r.model}))}function io(s){return Vo(s).ollama?.baseUrl||"http://localhost:11434"}l();l();de();k();l();var pn=T(require("http"),1);function ne(s,e,t,r,o=12e4){return new Promise((n,a)=>{let i=new URL(e,s),c={hostname:i.hostname,port:i.port,path:i.pathname,method:t,headers:{"Content-Type":"application/json"},timeout:o},p=pn.default.request(c,m=>{let u=[];m.on("data",g=>u.push(g)),m.on("end",()=>{n({status:m.statusCode||0,body:Buffer.concat(u).toString("utf-8")})})});p.on("error",m=>a(m)),p.on("timeout",()=>{p.destroy(),a(new Error("Request timed out"))}),r&&p.write(JSON.stringify(r)),p.end()})}function Xo(s,e,t,r=12e4,o){let n,a=!1;return o&&o.addEventListener("abort",()=>{a=!0,n&&n.destroy()},{once:!0}),{stream:async function*(){let c=new URL(e,s),p={hostname:c.hostname,port:c.port,path:c.pathname,method:"POST",headers:{"Content-Type":"application/json"},timeout:r},m=await new Promise((g,w)=>{n=pn.default.request(p,g),n.on("error",w),n.on("timeout",()=>{n.destroy(),w(new Error("Stream request timed out"))}),n.write(JSON.stringify(t)),n.end()});if(m.statusCode&&m.statusCode>=400){let g="";for await(let w of m)g+=w.toString();throw new Error(`Ollama HTTP ${m.statusCode}: ${g}`)}let u="";for await(let g of m){if(a)break;let w=g.toString();if(u+=w,u.includes('"error"'))try{let b=JSON.parse(u.trim());if(b.error)throw new Error(`Ollama: ${b.error}`)}catch(b){if(b.message.startsWith("Ollama:"))throw b}let y=u.split(`
|
|
196
|
+
`);u=y.pop()||"";for(let b of y)b.trim()&&(yield b)}u.trim()&&!a&&(yield u.trim())}(),abort:()=>{a=!0,n&&n.destroy()}}}var xe=class extends K{config;baseUrl;timeout;modelName;constructor(e){super(),this.config=e,this.baseUrl=e.baseUrl||"http://localhost:11434",this.timeout=e.timeout||12e4,this.modelName=e.model}getDisplayName(){return"Ollama"}async getModels(){try{return(await this.listModels()).map(t=>({id:t.name,displayName:t.name,capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!0,vision:!0}}))}catch{return[]}}async connect(){let e=await this.listModels(),t=this.config.model.split(":")[0].toLowerCase();if(!e.some(o=>o.name.split(":")[0].toLowerCase()===t||o.name.toLowerCase()===this.config.model.toLowerCase()))throw new N(`Model "${this.config.model}" is not pulled in Ollama. Run: ollama pull ${this.config.model}
|
|
197
|
+
Available models: ${e.map(o=>o.name).join(", ")||"(none)"}`);return e}async listModels(){try{let e=await ne(this.baseUrl,"/api/tags","GET",void 0,5e3);if(e.status!==200)throw new I(`Ollama returned status ${e.status}`,"OLLAMA_ERROR",e.status);return JSON.parse(e.body).models||[]}catch(e){throw e instanceof I?e:new we(`Cannot connect to Ollama at ${this.baseUrl}. Is Ollama running? (ollama serve)`,e)}}async isAvailable(){try{return await ne(this.baseUrl,"/api/tags","GET",void 0,3e3),!0}catch{return!1}}async isModelAvailable(e){try{let t=await this.listModels(),r=(e||this.config.model).toLowerCase(),o=r.split(":")[0];return t.some(n=>n.name.split(":")[0].toLowerCase()===o||n.name.toLowerCase()===r)}catch{return!1}}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(o=>this.sanitizeToolName(o.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){let t=e.__toolpack_request_id||`gen-${Date.now()}`,r=await Promise.all(e.messages.map(a=>this.toOllamaMessage(a,e.mediaOptions))),o=e.model||this.config.model,n={model:o,messages:r,stream:!1,options:{temperature:e.temperature??this.config.temperature??.7,num_ctx:this.config.numCtx}};e.tools&&e.tools.length>0&&e.tool_choice!=="none"&&(n.tools=e.tools.map(a=>({type:"function",function:{name:this.sanitizeToolName(a.function.name),description:a.function.description,parameters:a.function.parameters}})),h(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&h(`[Ollama][${t}] First tool: ${D(e.tools[0],800)}`),h(`[Ollama][${t}] NO TOOLS in request`)),h(`[Ollama][${t}] generate() request: model=${o}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),X(t,"Ollama",e.messages);try{let a=await ne(this.baseUrl,"/api/chat","POST",n,this.timeout);if(a.status!==200)throw this.handleHttpError(a.status,a.body);let i=JSON.parse(a.body),c=[];if(i.message?.tool_calls)for(let m of i.message.tool_calls)c.push({id:`ollama_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(m.function.name,e.tools),arguments:m.function.arguments||{}});let p={content:i.message?.content||null,usage:i.prompt_eval_count!=null?{prompt_tokens:i.prompt_eval_count||0,completion_tokens:i.eval_count||0,total_tokens:(i.prompt_eval_count||0)+(i.eval_count||0)}:void 0,finish_reason:c.length>0?"tool_calls":i.done?"stop":void 0,tool_calls:c.length>0?c:void 0,raw:i};return h(`[Ollama][${t}] Response finish_reason=${p.finish_reason} tool_calls=${c.length} content_preview=${D(p.content,200)}`),p}catch(a){throw a instanceof I?a:new we(`Failed to generate with Ollama model "${o}": ${a.message}`,a)}}async*stream(e){let t=e.__toolpack_request_id||`str-${Date.now()}`,r=await Promise.all(e.messages.map(i=>this.toOllamaMessage(i,e.mediaOptions))),o=e.model||this.config.model,n={model:o,messages:r,stream:!0,options:{temperature:e.temperature??this.config.temperature??.7,num_ctx:this.config.numCtx}};e.tools&&e.tools.length>0&&e.tool_choice!=="none"&&(n.tools=e.tools.map(i=>({type:"function",function:{name:this.sanitizeToolName(i.function.name),description:i.function.description,parameters:i.function.parameters}})),h(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&h(`[Ollama][${t}] First tool: ${D(e.tools[0],800)}`),h(`[Ollama][${t}] NO TOOLS in request`)),h(`[Ollama][${t}] Stream request: model=${o}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),X(t,"Ollama",e.messages);let{stream:a}=Xo(this.baseUrl,"/api/chat",n,this.timeout,e.signal);try{for await(let i of a)try{let c=JSON.parse(i);if(c.message?.content){let p=c.message.tool_calls&&c.message.tool_calls.length>0;yield{delta:c.message.content,finish_reason:c.done&&!p?"stop":void 0,usage:c.done&&c.prompt_eval_count!=null?{prompt_tokens:c.prompt_eval_count||0,completion_tokens:c.eval_count||0,total_tokens:(c.prompt_eval_count||0)+(c.eval_count||0)}:void 0}}if(c.message?.tool_calls&&c.message.tool_calls.length>0){let p=c.message.tool_calls.map(m=>({id:`ollama_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(m.function.name,e.tools),arguments:m.function.arguments||{}}));h(`[Ollama][${t}] Stream finish_reason=tool_calls name=${p[0]?.name}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:p}}if(c.done&&!c.message?.content&&!c.message?.tool_calls){be(`[Ollama][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"};return}}catch{}}catch(i){throw new we(`Stream failed for Ollama model "${o}": ${i.message}`,i)}}async embed(e){let t=e.__toolpack_request_id||`emb-${Date.now()}`,r=typeof e.input=="string"?[e.input]:e.input,o=e.model||this.config.model;h(`[Ollama][${t}] Embedding request: model=${o}, inputs=${r.length}`);try{let n=await ne(this.baseUrl,"/api/embed","POST",{model:o,input:r},this.timeout);if(n.status!==200)throw this.handleHttpError(n.status,n.body);return{embeddings:JSON.parse(n.body).embeddings||[]}}catch(n){throw n instanceof I?n:new we(`Embedding failed for Ollama model "${o}": ${n.message}`,n)}}async disconnect(){}async toOllamaMessage(e,t={}){let r="",o=[],{normalizeImagePart:n}=await Promise.resolve().then(()=>(ze(),to));if(typeof e.content=="string")r=e.content;else if(e.content!==null){for(let i of e.content)if(i.type==="text")r+=i.text+`
|
|
198
|
+
`;else if(i.type==="image_url"||i.type==="image_data"||i.type==="image_file")try{let{data:c}=await n(i);o.push(c)}catch{i.type==="image_url"?r+=`[Image: ${i.image_url.url}]
|
|
199
|
+
`:r+=`[Unresolvable Image]
|
|
200
|
+
`}r=r.trim()}let a={role:e.role,content:r};return o.length>0&&(a.images=o),e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0?a.tool_calls=e.tool_calls.map(i=>({function:{name:this.sanitizeToolName(i.function.name),arguments:typeof i.function.arguments=="string"?JSON.parse(i.function.arguments||"{}"):i.function.arguments}})):e.role==="tool"&&(a.content=r||JSON.stringify(e.content),e.name&&(a.tool_name=this.sanitizeToolName(e.name))),a}handleHttpError(e,t){let r=`Ollama error (HTTP ${e})`;try{let o=JSON.parse(t);o.error&&(r=`Ollama: ${o.error}`)}catch{}return e===404?new N(`Model not found: ${r}`):new I(r,"OLLAMA_ERROR",e)}};l();var Ke=class extends K{baseUrl;timeout;adapterCache=new Map;capabilityCache=new Map;constructor(e){super(),this.baseUrl=e?.baseUrl||"http://localhost:11434",this.timeout=12e4}getDisplayName(){return"Ollama"}async getModels(){let e;try{let t=await ne(this.baseUrl,"/api/tags","GET",void 0,5e3);if(t.status!==200)return[];e=JSON.parse(t.body).models||[]}catch{return[]}return Promise.all(e.map(t=>this.buildModelInfo(t)))}async generate(e){return this.getAdapterForModel(e.model).generate(this.stripToolsIfNeeded(e))}async*stream(e){yield*this.getAdapterForModel(e.model).stream(this.stripToolsIfNeeded(e))}async embed(e){return this.getAdapterForModel(e.model).embed(e)}async disconnect(){this.adapterCache.clear(),this.capabilityCache.clear()}stripToolsIfNeeded(e){let t=this.capabilityCache.get(e.model);if(t&&!t.toolCalling&&e.tools&&e.tools.length>0){let{tools:r,tool_choice:o,...n}=e,a=n,i={role:"system",content:"You do not have access to any tools or functions. Do not attempt to call tools, output tool invocations, or reference tool usage. Answer the user directly using only your own knowledge."};return a.messages=[...a.messages,i],a}return e}getAdapterForModel(e){let t=this.adapterCache.get(e);return t||(t=new xe({model:e,baseUrl:this.baseUrl,timeout:this.timeout}),this.adapterCache.set(e,t)),t}async buildModelInfo(e){let t=!1,r=!1,o=!1;try{let i=await ne(this.baseUrl,"/api/show","POST",{model:e.name},3e3);if(i.status===200){let p=(JSON.parse(i.body).details?.families||[]).map(m=>m.toLowerCase());r=p.some(m=>["clip","mllama"].includes(m)),o=p.some(m=>m.includes("bert")||m.includes("nomic"))}}catch{}t=await this.probeToolSupport(e.name);let n=e.name.toLowerCase();r||(r=["llava","vision","bakllava","moondream"].some(c=>n.includes(c))),o||(o=["nomic-embed","mxbai-embed","all-minilm","bge-","snowflake-arctic-embed"].some(c=>n.includes(c)));let a={toolCalling:t,vision:r,embeddings:o};return this.capabilityCache.set(e.name,a),{id:e.name,displayName:e.name,capabilities:{chat:!0,streaming:!0,toolCalling:t,embeddings:o,vision:r}}}async probeToolSupport(e){try{let t=await ne(this.baseUrl,"/api/chat","POST",{model:e,messages:[{role:"user",content:"hi"}],tools:[{type:"function",function:{name:"__probe",description:"probe",parameters:{type:"object",properties:{}}}}],stream:!1},1e4);return t.status>=400?!1:!JSON.parse(t.body).error}catch{return!1}}};l();var mn=[{model:"qwen2.5-coder:3b",label:"Qwen 2.5 Coder 3B",params:"3B",size:"~2GB",selectorCapability:5,description:"Best code understanding at small size. Excellent HTML/CSS comprehension."},{model:"phi3:mini",label:"Phi-3 Mini",params:"3.8B",size:"~2.3GB",selectorCapability:4,description:"Strong reasoning for its size. Good at structured output."},{model:"codegemma:2b",label:"CodeGemma 2B",params:"2B",size:"~1.4GB",selectorCapability:4,description:"Compact code model from Google. Fast inference."},{model:"deepseek-coder:1.3b",label:"DeepSeek Coder 1.3B",params:"1.3B",size:"~0.8GB",selectorCapability:3,description:"Smallest viable option. Very fast but less accurate."},{model:"qwen2.5-coder:7b",label:"Qwen 2.5 Coder 7B",params:"7B",size:"~4.5GB",selectorCapability:5,description:"Higher accuracy than 3B variant. Requires more RAM/VRAM."},{model:"codellama:7b",label:"Code Llama 7B",params:"7B",size:"~3.8GB",selectorCapability:4,description:"Meta code model. Solid HTML/CSS understanding."}];function Ei(){return mn[0].model}function Di(s){let e=s.toLowerCase();return mn.some(t=>t.model.toLowerCase()===e||t.model.split(":")[0].toLowerCase()===e.split(":")[0].toLowerCase())}function Ni(){return[...mn]}l();var dn=T(require("openai"),1);de();k();var ao=class extends K{client;constructor(e,t){super(),this.client=new dn.default({apiKey:e,baseURL:t,timeout:6e4,maxRetries:2})}supportsFileUpload(){return!0}async uploadFile(e){try{let t=await import("fs");if(!e.filePath)throw new N("OpenAI uploadFile requires a filePath.");return{id:(await this.client.files.create({file:t.createReadStream(e.filePath),purpose:e.purpose||"vision"})).id}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{await this.client.files.delete(e)}catch(t){throw this.handleError(t)}}getDisplayName(){return"OpenAI"}async getModels(){return[{id:"gpt-4.1-mini",displayName:"GPT-4.1 Mini",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1047576,maxOutputTokens:32768,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:null,costTier:"low"},{id:"gpt-4.1",displayName:"GPT-4.1",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1047576,maxOutputTokens:32768,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:null,costTier:"medium"},{id:"gpt-5.1",displayName:"GPT-5.1",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:4e5,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"medium"},{id:"gpt-5.2",displayName:"GPT-5.2",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:4e5,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"high"},{id:"gpt-5.4",displayName:"GPT-5.4",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:105e4,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"high"},{id:"gpt-5.4-pro",displayName:"GPT-5.4 Pro",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:105e4,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"extended",costTier:"premium"}]}sanitizeToolName(e){return e.replace(/\./g,"_")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,o={messages:await Promise.all(e.messages.map(u=>this.toOpenAIMessage(u,e.mediaOptions))),model:e.model,temperature:e.temperature,max_tokens:e.max_tokens,top_p:e.top_p,response_format:e.response_format==="json_object"?{type:"json_object"}:void 0,stream:!1},n=new Map;e.tools&&e.tools.length>0&&(o.tools=e.tools.map(u=>{let g=this.sanitizeToolName(u.function.name);return n.set(g,u.function.name),{type:"function",function:{name:g,description:u.function.description,parameters:u.function.parameters}}}),o.tool_choice=e.tool_choice||"auto",h(`[OpenAI][${t}] Sending ${o.tools.length} tools with tool_choice: ${o.tool_choice}`),h(`[OpenAI][${t}] First tool: ${D(o.tools[0],800)}`)),h(`[OpenAI][${t}] Request params: ${D({model:o.model,messages_count:o.messages.length,has_tools:!!o.tools,tools_count:o.tools?.length,tool_choice:o.tool_choice},800)}`),X(t,"OpenAI",o.messages);let a=await this.client.chat.completions.create(o,e.signal?{signal:e.signal}:void 0);be(`[OpenAI][${t}] Raw completion: ${JSON.stringify(a)}`);let i=a.choices[0].message;h(`[OpenAI][${t}] Response: finish_reason=${a.choices[0].finish_reason}`),h(`[OpenAI][${t}] Response has tool_calls: ${!!i.tool_calls}, count: ${i.tool_calls?.length||0}`),h(`[OpenAI][${t}] Response content: ${JSON.stringify(i.content)}`),i.content&&h(`[OpenAI][${t}] Response content preview: ${D(i.content,200)}`);let c=a.choices[0],p,m=c.message.tool_calls;return m&&m.length>0&&(p=m.map(u=>({id:u.id,name:n.get(u.function.name)||u.function.name,arguments:JSON.parse(u.function.arguments)}))),{content:c.message.content,usage:a.usage?{prompt_tokens:a.usage.prompt_tokens,completion_tokens:a.usage.completion_tokens,total_tokens:a.usage.total_tokens}:void 0,finish_reason:c.finish_reason,tool_calls:p,raw:a}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`str-${Date.now()}`,o={messages:await Promise.all(e.messages.map(c=>this.toOpenAIMessage(c,e.mediaOptions))),model:e.model,temperature:e.temperature,max_tokens:e.max_tokens,top_p:e.top_p,response_format:e.response_format==="json_object"?{type:"json_object"}:void 0,stream:!0},n=new Map;e.tools&&e.tools.length>0?(o.tools=e.tools.map(c=>{let p=this.sanitizeToolName(c.function.name);return n.set(p,c.function.name),{type:"function",function:{name:p,description:c.function.description,parameters:c.function.parameters}}}),o.tool_choice=e.tool_choice||"auto",h(`[OpenAI][${t}] Sending ${o.tools.length} tools with tool_choice: ${o.tool_choice}`),h(`[OpenAI][${t}] First tool: ${D(o.tools[0],800)}`)):h(`[OpenAI][${t}] NO TOOLS in request`),h(`[OpenAI][${t}] Stream request: model=${o.model}, messages=${o.messages.length}, tools=${o.tools?.length||0}, tool_choice=${o.tool_choice??"unset"}`),X(t,"OpenAI",o.messages);let a=await this.client.chat.completions.create(o,e.signal?{signal:e.signal}:void 0),i=new Map;for await(let c of a){let p=c.choices[0];if(p.finish_reason&&be(`[OpenAI][${t}] Stream chunk finish_reason=${p.finish_reason}`),p.delta.tool_calls)for(let m of p.delta.tool_calls){let u=m.index;i.has(u)||i.set(u,{id:m.id||"",name:m.function?.name||"",args:""});let g=i.get(u);m.id&&(g.id=m.id),m.function?.name&&(g.name=m.function.name),m.function?.arguments&&(g.args+=m.function.arguments),be(`[OpenAI][${t}] tool_call_delta idx=${u} id=${m.id||g.id||""} name=${m.function?.name||g.name||""} args_delta=${D(m.function?.arguments||"",200)}`)}if(p.delta.content&&(yield{delta:p.delta.content,finish_reason:p.finish_reason,usage:c.usage}),!p.delta.content&&p.finish_reason&&p.finish_reason!=="tool_calls"&&(yield{delta:"",finish_reason:p.finish_reason,usage:c.usage}),p.finish_reason==="tool_calls"&&i.size>0){let m=Array.from(i.values()).map(u=>({id:u.id,name:n.get(u.name)||u.name,arguments:JSON.parse(u.args||"{}")}));h(`[OpenAI][${t}] Stream finish_reason=tool_calls accumulated_calls=${m.length} names=${m.map(u=>u.name).join(", ")}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:m}}}}catch(t){throw this.handleError(t)}}async embed(e){try{let t=typeof e.input=="string"?[e.input]:e.input,r=await this.client.embeddings.create({model:e.model,input:t});return{embeddings:r.data.map(o=>o.embedding),usage:r.usage}}catch(t){throw this.handleError(t)}}async toOpenAIMessage(e,t={}){if(e.role==="tool"&&e.tool_call_id)return{role:"tool",tool_call_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content??"")};if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0)return{role:"assistant",content:typeof e.content=="string"?e.content:"",tool_calls:e.tool_calls.map(n=>({id:n.id,type:"function",function:{name:this.sanitizeToolName(n.function.name),arguments:n.function.arguments}}))};if(typeof e.content=="string")return{role:e.role,content:e.content};if(e.content===null||e.content===void 0)return{role:e.role,content:""};let{normalizeImagePart:r}=await Promise.resolve().then(()=>(ze(),to)),o=await Promise.all(e.content.map(async n=>{if(n.type==="text")return{type:"text",text:n.text};if(n.type==="image_url")return{type:"image_url",image_url:{url:n.image_url.url}};if(n.type==="image_data"||n.type==="image_file"){let{data:a,mimeType:i}=await r(n);return{type:"image_url",image_url:{url:`data:${i};base64,${a}`}}}return null}));return{role:e.role,content:o.filter(Boolean)}}handleError(e){if(e instanceof dn.default.APIError){let t=e.message;return e.status===401?new pe(t,e):e.status===429?new me(t,void 0,e):e.status&&e.status>=400&&e.status<500?new N(t,e):new I(t,e.code||"OPENAI_ERROR",e.status||500,e)}return new I("Unknown error","UNKNOWN",500,e)}};ze();l();Xt();l();Xt();var Jt=class{tools=new Map;projects=new Map;config=H;register(e){this.tools.set(e.name,e)}registerCustom(e){this.tools.set(e.name,e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getNames(){return Array.from(this.tools.keys())}getByCategory(e){return Array.from(this.tools.values()).filter(t=>t.category===e)}getEnabled(){if(this.config.enabledTools.length===0&&this.config.enabledToolCategories.length===0)return Array.from(this.tools.values());let e=this.getByNames(this.config.enabledTools),t=this.getByCategories(this.config.enabledToolCategories),r=new Set,o=[];for(let n of[...e,...t])r.has(n.name)||(r.add(n.name),o.push(n));return o}getSchemas(e){return(e?e.map(r=>this.tools.get(r)).filter(Boolean):this.getEnabled()).map(r=>({name:r.name,displayName:r.displayName,description:r.description,parameters:r.parameters,category:r.category}))}getByNames(e){return e.map(t=>this.tools.get(t)).filter(Boolean)}getByCategories(e){let t=new Set(e);return Array.from(this.tools.values()).filter(r=>t.has(r.category))}getCategories(){let e=new Set;for(let t of this.tools.values())e.add(t.category);return Array.from(e)}getAll(){return Array.from(this.tools.values())}setConfig(e){this.config=e}getConfig(){return this.config}get size(){return this.tools.size}async validateDependencies(e){let t=e.dependencies;if(!t||Object.keys(t).length===0)return[];let r=[];for(let o of Object.keys(t))try{await import(o)}catch{r.push(o)}return r}async loadProject(e){let t=await this.validateDependencies(e);if(t.length>0)throw new Error(`Tool project "${e.manifest.name}" has missing dependencies: ${t.join(", ")}. Install them with: npm install ${t.join(" ")}`);this.projects.set(e.manifest.name,e);for(let r of e.tools)this.register(r)}async loadProjects(e){for(let t of e)await this.loadProject(t)}getProject(e){return this.projects.get(e)}getProjects(){return Array.from(this.projects.values())}getProjectNames(){return Array.from(this.projects.keys())}async loadBuiltIn(){let{fsToolsProject:e}=await Promise.resolve().then(()=>(An(),Hl)),{execToolsProject:t}=await Promise.resolve().then(()=>(Un(),Oc)),{systemToolsProject:r}=await Promise.resolve().then(()=>(Yn(),fp)),{httpToolsProject:o}=await Promise.resolve().then(()=>(rs(),Yp)),{webToolsProject:n}=await Promise.resolve().then(()=>(ys(),wd)),{codingToolsProject:a}=await Promise.resolve().then(()=>(Os(),af)),{gitToolsProject:i}=await Promise.resolve().then(()=>(js(),If)),{diffToolsProject:c}=await Promise.resolve().then(()=>(qs(),Yf)),{dbToolsProject:p}=await Promise.resolve().then(()=>(Bs(),Cg)),{cloudToolsProject:m}=await Promise.resolve().then(()=>(Hs(),Mg));await this.loadProjects([e,t,r,o,n,a,i,c,p,m])}};is();l();k();function Og(s){if(!s.key||!/^[a-z0-9-]+$/.test(s.key))throw new Error(`Invalid tool project key: "${s.key}". Must be non-empty, lowercase, and contain no spaces (use hyphens).`);if(!s.name.trim())throw new Error("Tool project name cannot be empty.");if(!s.tools||s.tools.length===0)throw new Error("Tool project must contain at least one tool.");for(let t of s.tools){if(!t.name)throw new Error("Tool is missing a name.");if(!t.description)throw new Error(`Tool "${t.name}" is missing a description.`);if(!t.parameters)throw new Error(`Tool "${t.name}" is missing parameters.`);if(typeof t.execute!="function")throw new Error(`Tool "${t.name}" is missing an execute function.`);t.category!==s.category&&E(`[Toolpack] Tool "${t.name}" has category "${t.category}" which does not match project category "${s.category}".`)}let e=s.tools.map(t=>t.name);return{manifest:{key:s.key,name:s.name,displayName:s.displayName,version:s.version,description:s.description,author:s.author,repository:s.repository,category:s.category,tools:e},dependencies:s.dependencies,tools:s.tools}}An();Un();Yn();rs();ys();Os();js();qs();Bs();Hs();l();l();var Ig=require("child_process"),jg=require("events");k();var jo=class extends Error{constructor(e,t){super(`MCP request timed out after ${t}ms: ${e}`),this.name="McpTimeoutError"}},ae=class extends Error{constructor(t,r){super(t);this.exitCode=r;this.name="McpConnectionError"}exitCode},Ht=class extends jg.EventEmitter{constructor(t){super();this.config=t;this.defaultTimeoutMs=t.requestTimeoutMs??3e4,this.autoReconnect=t.autoReconnect??!1,this.maxReconnectAttempts=t.maxReconnectAttempts??3,this.reconnectDelayMs=t.reconnectDelayMs??1e3}config;process=null;messageQueue=new Map;nextId=1;buffer="";_connected=!1;_shuttingDown=!1;_reconnectAttempts=0;defaultTimeoutMs;autoReconnect;maxReconnectAttempts;reconnectDelayMs;get connected(){return this._connected&&this.process!==null}async connect(){if(this._shuttingDown)throw new ae("Client is shutting down");return new Promise((t,r)=>{try{if(this.buffer="",this.process=(0,Ig.spawn)(this.config.command,this.config.args||[],{env:{...process.env,...this.config.env},stdio:["pipe","pipe","pipe"]}),!this.process.stdout||!this.process.stdin)throw new ae("Failed to spawn MCP server: stdout/stdin unavailable");this.process.stdout.on("data",o=>{this.handleData(o)}),this.process.stderr&&this.process.stderr.on("data",o=>{E(`[MCP server stderr] ${o.toString().trim()}`)}),this.process.on("error",o=>{this._connected=!1,this.emit("error",o)}),this.process.on("exit",o=>{let n=this._connected;this._connected=!1,this.process=null,this.rejectAllPending(new ae(`MCP server exited with code ${o}`,o)),this.emit("close",o),n&&!this._shuttingDown&&this.autoReconnect&&this.attemptReconnect()}),this._connected=!0,this._reconnectAttempts=0,setTimeout(t,500)}catch(o){r(o)}})}async attemptReconnect(){if(this._reconnectAttempts>=this.maxReconnectAttempts){this.emit("reconnect_failed",this._reconnectAttempts);return}this._reconnectAttempts++;let t=this._reconnectAttempts;if(this.emit("reconnecting",{attempt:t,max:this.maxReconnectAttempts}),await new Promise(r=>setTimeout(r,this.reconnectDelayMs*t)),!this._shuttingDown)try{await this.connect(),this.emit("reconnected",{attempt:t})}catch(r){this.emit("reconnect_error",{attempt:t,error:r})}}handleData(t){this.buffer+=t.toString();let r;for(;(r=this.buffer.indexOf(`
|
|
201
|
+
`))!==-1;){let o=this.buffer.slice(0,r).trim();if(this.buffer=this.buffer.slice(r+1),o)try{let n=JSON.parse(o);this.handleMessage(n)}catch{}}}handleMessage(t){if(t.id&&(t.result!==void 0||t.error)){let r=this.messageQueue.get(t.id);r&&(r.timer&&clearTimeout(r.timer),t.error?r.reject(new Error(t.error.message)):r.resolve(t.result),this.messageQueue.delete(t.id))}else t.method&&(this.emit("notification",t),this.emit(t.method,t.params))}async callTool(t,r={},o){return this.request("tools/call",{name:t,arguments:r},o)}async readResource(t,r){return this.request("resources/read",{uri:t},r)}async request(t,r,o){if(!this.process||!this.process.stdin)throw new ae("Client not connected");let n=this.nextId++,a=o??this.defaultTimeoutMs,i={jsonrpc:"2.0",id:n,method:t,params:r};return new Promise((c,p)=>{let m;a>0&&(m=setTimeout(()=>{let u=this.messageQueue.get(n);u&&(this.messageQueue.delete(n),u.reject(new jo(t,a)))},a)),this.messageQueue.set(n,{resolve:c,reject:p,timer:m});try{this.process.stdin.write(JSON.stringify(i)+`
|
|
202
|
+
`)}catch(u){m&&clearTimeout(m),this.messageQueue.delete(n),p(u)}})}async disconnect(t=3e3){if(this._shuttingDown=!0,this.rejectAllPending(new ae("Client disconnecting")),!this.process){this._shuttingDown=!1;return}let r=this.process;return new Promise(o=>{let n=!1,a=()=>{n||(n=!0,this.process=null,this._connected=!1,this._shuttingDown=!1,o())};r.once("exit",a),r.kill("SIGTERM"),setTimeout(()=>{if(!n){try{r.kill("SIGKILL")}catch{}a()}},t)})}kill(){this._shuttingDown=!0,this.rejectAllPending(new ae("Client killed")),this.process&&(this.process.kill("SIGKILL"),this.process=null),this._connected=!1,this._shuttingDown=!1}rejectAllPending(t){for(let[r,o]of this.messageQueue)o.timer&&clearTimeout(o.timer),o.reject(t);this.messageQueue.clear()}};k();var Fo=class{constructor(e){this.config=e}config;clients=new Map;serverConfigs=new Map;toolDefinitions=new Map;async connectServer(e){let{name:t,displayName:r,toolPrefix:o,...n}=e;v(`[MCP] Connecting to server: ${r||t}`);try{let a=new Ht({...n,requestTimeoutMs:n.requestTimeoutMs??this.config.defaultTimeoutMs,autoReconnect:n.autoReconnect??this.config.autoReconnect??!0});this.setupClientEvents(a,t),await a.connect();let c=(await a.request("tools/list"))?.tools||[];v(`[MCP] Discovered ${c.length} tools from ${t}`);let p=o||`mcp.${t}.`;for(let m of c){let u=this.convertMcpTool(m,t,p,a);this.toolDefinitions.set(u.name,u)}this.clients.set(t,a),this.serverConfigs.set(t,e)}catch(a){throw Y(`[MCP] Failed to connect to ${t}: ${a}`),a}}async connectAll(){let e=this.config.servers.filter(t=>t.autoConnect!==!1).map(t=>this.connectServer(t));await Promise.allSettled(e)}async disconnectServer(e){let t=this.clients.get(e);if(!t){E(`[MCP] Server ${e} not found`);return}v(`[MCP] Disconnecting from ${e}`);for(let[r,o]of this.toolDefinitions)o.name.includes(e)&&this.toolDefinitions.delete(r);await t.disconnect(),this.clients.delete(e),this.serverConfigs.delete(e)}async disconnectAll(){let e=Array.from(this.clients.keys()).map(t=>this.disconnectServer(t));await Promise.allSettled(e)}getToolDefinitions(){return Array.from(this.toolDefinitions.values())}getConnectedServers(){return Array.from(this.clients.keys())}isServerConnected(e){return this.clients.get(e)?.connected??!1}convertMcpTool(e,t,r,o){let n={type:"object",properties:e.inputSchema.properties||{},required:e.inputSchema.required||[]};return{name:`${r}${e.name}`,displayName:e.name,description:e.description||`MCP tool from ${t}`,category:"mcp",parameters:n,execute:async a=>{try{v(`[MCP] Executing ${e.name} on ${t}`);let i=await o.callTool(e.name,a);return JSON.stringify(i)}catch(i){throw Y(`[MCP] Tool execution failed: ${i}`),i}}}}setupClientEvents(e,t){e.on("error",r=>{Y(`[MCP] ${t} error: ${r}`)}),e.on("close",r=>{E(`[MCP] ${t} closed with code ${r}`)}),e.on("reconnecting",({attempt:r,max:o})=>{v(`[MCP] ${t} reconnecting (${r}/${o})`)}),e.on("reconnected",({attempt:r})=>{v(`[MCP] ${t} reconnected after ${r} attempts`)}),e.on("reconnect_failed",r=>{Y(`[MCP] ${t} failed to reconnect after ${r} attempts`)}),e.on("notification",r=>{v(`[MCP] ${t} notification: ${JSON.stringify(r)}`)})}};async function Jr(s){let e=new Fo(s);await e.connectAll();let t=e.getToolDefinitions(),r={manifest:{key:"mcp-tools",name:"mcp-tools",displayName:"MCP Tools",version:"1.0.0",description:`Tools from ${e.getConnectedServers().length} MCP server(s)`,category:"mcp",author:"Toolpack SDK",tools:t.map(o=>o.name)},tools:t};return r._mcpManager=e,r}async function Hr(s){let e=s._mcpManager;e&&await e.disconnectAll()}l();l();l();l();var zr=`
|
|
203
203
|
You are a planning assistant. Given a user request, create a detailed step-by-step plan.
|
|
204
204
|
|
|
205
205
|
Rules:
|
|
@@ -212,7 +212,7 @@ Rules:
|
|
|
212
212
|
7. Steps should produce concrete outputs, not ask questions or wait for user input
|
|
213
213
|
8. ALWAYS include at least one step, even for simple questions. For simple factual questions, create a single step like "Provide the answer to [question]"
|
|
214
214
|
9. When a step uses information gathered by a previous step, set "dependsOn" to that step's number and phrase the description as "Using the [data] from step N, [do something]" instead of gathering it again
|
|
215
|
-
10.
|
|
215
|
+
10. For plans with MORE than 2 steps, the final step must synthesize the workflow's results into a concise deliverable, avoiding redundant word-for-word repetition of earlier step outputs. For plans with 1-2 steps, no synthesis step is needed.
|
|
216
216
|
11. The exact result MUST be valid JSON matching this schema:
|
|
217
217
|
{
|
|
218
218
|
"summary": "Brief description of the overall goal",
|
|
@@ -225,12 +225,7 @@ Rules:
|
|
|
225
225
|
}
|
|
226
226
|
]
|
|
227
227
|
}
|
|
228
|
-
`,
|
|
229
|
-
Result: ${a}`)}else r.status==="failed"?o.push(`Step ${r.number}: ${r.description}
|
|
230
|
-
Failed: ${r.result?.error||"Unknown error"}`):r.status==="skipped"&&o.push(`Step ${r.number}: ${r.description}
|
|
231
|
-
Skipped.`)}return o.length===0?"No previous steps.":o.join(`
|
|
232
|
-
|
|
233
|
-
`)}};_();var Ey=`
|
|
228
|
+
`,Kr=`
|
|
234
229
|
You are executing step {stepNumber} of a plan.
|
|
235
230
|
|
|
236
231
|
Plan summary: {planSummary}
|
|
@@ -244,15 +239,57 @@ Execute this step now. Use the available tools as needed to accomplish this spec
|
|
|
244
239
|
Make reasonable assumptions if any details are ambiguous - do NOT ask the user for clarification or additional input.
|
|
245
240
|
Produce concrete results based on the information available.
|
|
246
241
|
If you cannot complete this step, explain why.
|
|
247
|
-
If you need to add additional steps to the plan, indicate that clearly in your response.
|
|
248
242
|
|
|
249
243
|
IMPORTANT: Your response should be written as if you are directly answering the user.
|
|
250
244
|
Do NOT mention steps, plans, workflow details, or internal process in your response.
|
|
251
245
|
Do NOT say things like "Step 1 is complete" or "proceeding to the next step".
|
|
252
246
|
Just provide the actual answer or result naturally.
|
|
253
|
-
`,
|
|
247
|
+
`,jy={name:"Direct",planning:{enabled:!1},steps:{enabled:!1},progress:{enabled:!0}},zs={name:"Agent",planning:{enabled:!0,planningPrompt:zr},steps:{enabled:!0,retryOnFailure:!0,allowDynamicSteps:!1,stepPrompt:Kr},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},Fg=`
|
|
248
|
+
Create a step-by-step plan for this coding task.
|
|
249
|
+
|
|
250
|
+
Rules:
|
|
251
|
+
1. Break into actionable steps using tools (read/write files, search code)
|
|
252
|
+
2. Each step executes independently without user input
|
|
253
|
+
3. Order by dependencies
|
|
254
|
+
4. Individual steps: be concise and technical. No conversational filler.
|
|
255
|
+
5. For >2 steps, final step summarizes changes with conversational explanation
|
|
256
|
+
6. Output valid JSON: {"summary": "...", "steps": [{...}]}
|
|
257
|
+
|
|
258
|
+
JSON Schema:
|
|
259
|
+
{
|
|
260
|
+
"summary": "Brief description of the overall goal",
|
|
261
|
+
"steps": [
|
|
262
|
+
{
|
|
263
|
+
"number": 1,
|
|
264
|
+
"description": "What this step does",
|
|
265
|
+
"expectedTools": ["tool.name"],
|
|
266
|
+
"dependsOn": []
|
|
267
|
+
}
|
|
268
|
+
]
|
|
269
|
+
}
|
|
270
|
+
`,Lg=`
|
|
271
|
+
Execute step {stepNumber}: {stepDescription}
|
|
272
|
+
|
|
273
|
+
Plan: {planSummary}
|
|
274
|
+
|
|
275
|
+
Previous: {previousStepsResults}
|
|
276
|
+
|
|
277
|
+
Use tools. Be concise. Show code changes clearly.
|
|
278
|
+
No meta-commentary about steps or workflow.
|
|
279
|
+
`,Ks={name:"Coding",planning:{enabled:!0,planningPrompt:Fg},steps:{enabled:!0,retryOnFailure:!0,allowDynamicSteps:!1,stepPrompt:Lg},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},Qs={name:"Chat",planning:{enabled:!1},steps:{enabled:!1},progress:{enabled:!1}};var Ys={name:"agent",displayName:"Agent",description:"Full autonomous access \u2014 read, write, execute, browse",systemPrompt:["You are an autonomous AI agent with full access to all available tools.","You must use the tools provided to accomplish tasks end-to-end proactively.","If you require a capability that is not listed in your current tools, ALWAYS use `tool.search` to find it before improvising or giving up.","Before considering a tool to call, make sure that is the right tool for the job as per the users prompt.","Verify your actions and check for success or failure states.","Explain your actions briefly as you go."].join(" "),allowedToolCategories:[],blockedToolCategories:[],allowedTools:[],blockedTools:[],blockAllTools:!1,baseContext:{includeWorkingDirectory:!0,includeToolCategories:!0},workflow:zs,toolSearch:{alwaysLoadedTools:["fs.read_file","fs.write_file","fs.list_dir","web.search","web.fetch","skill.search","skill.read"]}},Vs={name:"chat",displayName:"Chat",description:"Conversational assistant with web access",systemPrompt:["You are a conversational AI assistant with web access.","You can search the web, fetch online content, and make HTTP requests.","You do NOT have access to the local filesystem, command execution, or code modification.","Answer questions using your knowledge and web tools when helpful.","If the user asks for local file operations or code changes,","explain that you are in Chat mode and suggest they switch to Agent mode."].join(" "),allowedToolCategories:["network"],blockedToolCategories:["filesystem","execution","system","coding","git","database"],allowedTools:[],blockedTools:[],blockAllTools:!1,baseContext:{includeWorkingDirectory:!1,includeToolCategories:!0},workflow:Qs,toolSearch:{alwaysLoadedTools:["web.search","web.fetch","fs.read_file","fs.list_dir"]}},Fy={name:"coding",displayName:"Coding",description:"Concise coding mode \u2014 minimal text, focused on file operations and code changes",systemPrompt:["Coding assistant. Use tools to modify code.","Be concise. No conversational filler.","Show code changes clearly."].join(" "),allowedToolCategories:[],blockedToolCategories:[],allowedTools:[],blockedTools:[],blockAllTools:!1,baseContext:{includeWorkingDirectory:!0,includeToolCategories:!0},workflow:Ks,toolSearch:{alwaysLoadedTools:["coding.read_code","coding.search_code","fs.read_file","fs.write_file","fs.list_dir","skill.search","skill.read","web.search","web.fetch"]}},Lo=[Ys,Fy,Vs],Le="chat";var zt=class{modes=new Map;orderedNames=[];constructor(){for(let e of Lo)this.register(e)}register(e){if(!e.name||typeof e.name!="string")throw new Error("ModeConfig.name is required and must be a non-empty string");if(!e.displayName||typeof e.displayName!="string")throw new Error("ModeConfig.displayName is required and must be a non-empty string");if(typeof e.systemPrompt!="string")throw new Error("ModeConfig.systemPrompt must be a string (can be empty for passthrough)");if(e.blockAllTools!==void 0&&typeof e.blockAllTools!="boolean")throw new Error("ModeConfig.blockAllTools must be a boolean");let t=["allowedToolCategories","blockedToolCategories","allowedTools","blockedTools"];for(let o of t)if(e[o]!==void 0&&!Array.isArray(e[o]))throw new Error(`ModeConfig.${o} must be an array`);let r=this.modes.has(e.name);this.modes.set(e.name,e),r||this.orderedNames.push(e.name)}get(e){return this.modes.get(e)}has(e){return this.modes.has(e)}getAll(){let e=[];for(let t of this.orderedNames){let r=this.modes.get(t);r&&e.push(r)}return e}getNames(){return[...this.orderedNames]}getDefault(){let e=this.modes.get(Le);if(!e)throw new Error(`Default mode "${Le}" not found in registry`);return e}getNext(e){let t=this.orderedNames.indexOf(e),r=t===-1?0:(t+1)%this.orderedNames.length,o=this.orderedNames[r],n=this.modes.get(o);if(!n)throw new Error(`Mode "${o}" not found in registry`);return n}get size(){return this.modes.size}remove(e){if(Lo.some(o=>o.name===e))return!1;let r=this.modes.delete(e);return r&&(this.orderedNames=this.orderedNames.filter(o=>o!==e)),r}};l();function qg(s){return{name:s.name,displayName:s.displayName,description:s.description||s.displayName,systemPrompt:s.systemPrompt,allowedToolCategories:s.allowedToolCategories||[],blockedToolCategories:s.blockedToolCategories||[],allowedTools:s.allowedTools||[],blockedTools:s.blockedTools||[],blockAllTools:s.blockAllTools||!1,baseContext:s.baseContext,workflow:s.workflow}}l();var Qr={planning:{enabled:!1},steps:{enabled:!1},progress:{enabled:!0}};l();k();var Ly=zr,Kt=class{client;config;constructor(e,t){this.client=e,this.config=t}async createPlan(e,t){let r=this.config?.planningPrompt||Ly,o=e.messages.filter(p=>p.role==="user").map(p=>typeof p.content=="string"?p.content:"[obj]").join(" ").substring(0,100);h(`[Planner] createPlan() provider=${t??"default"} maxSteps=${this.config?.maxSteps??20} request="${o}..."`);let n=e.messages.filter(p=>p.role==="system"),a=e.messages.filter(p=>p.role!=="system"),i=[{role:"system",content:r},...n,...a],c={...e,tools:void 0,tool_choice:"none",response_format:"json_object",messages:i};try{let p=await this.client.generate(c,t),m=this.parsePlan(p.content||"",e,p);return v(`[Planner] createPlan() succeeded plan.id=${m.id} steps=${m.steps.length}`),m}catch(p){return E(`[Planner] createPlan() failed, using fallback: ${p.message}`),this.createFallbackPlan(e)}}parsePlan(e,t,r){try{let o=JSON.parse(e);if(!o.summary||!Array.isArray(o.steps))throw new Error("Invalid plan structure: missing summary or steps array");let n=this.config?.maxSteps??20,a=o.steps.slice(0,n);o.steps.length>n&&E(`[Planner] parsePlan() truncated ${o.steps.length} steps to maxSteps=${n}`),h(`[Planner] parsePlan() parsed ${a.length} steps successfully`);let i=a.map((p,m)=>({id:`step-${Date.now()}-${m}`,number:p.number||m+1,description:p.description||"Unknown step",expectedTools:p.expectedTools||[],dependsOn:p.dependsOn||[],status:"pending"})),c=t.messages.filter(p=>p.role==="user").map(p=>typeof p.content=="string"?p.content:"[Complex Object]").join("\\n");return{id:`plan-${Date.now()}`,request:c,summary:o.summary,steps:i,status:"draft",createdAt:new Date,planningResponse:r}}catch(o){return E(`[Planner] parsePlan() failed: ${o.message} \u2014 using fallback`),this.createFallbackPlan(t)}}createFallbackPlan(e){E("[Planner] createFallbackPlan() \u2014 creating single-step fallback due to plan generation failure");let t=e.messages.filter(r=>r.role==="user").map(r=>typeof r.content=="string"?r.content:"[Complex Object]").join("\\n");return{id:`plan-${Date.now()}-fallback`,request:t,summary:"Fallback single-step plan due to generation failure",steps:[{id:"step-1",number:1,description:"Execute the user request",status:"pending",expectedTools:[],dependsOn:[]}],status:"draft",createdAt:new Date}}};l();l();var Qt=class{static getProgress(e){let t=e.steps.length,r=e.steps.findIndex(c=>c.status!=="completed"&&c.status!=="skipped");r===-1&&(r=t);let o=t>0?Math.round(r/t*100):0,n=e.steps[r],a=n?n.description:"Done",i="executing";return e.status==="draft"&&(i="planning"),e.status==="approved"&&(i="executing"),e.status==="completed"&&(i="completed"),(e.status==="failed"||e.status==="cancelled")&&(i="failed"),{planId:e.id,currentStep:Math.min(r+1,t),totalSteps:t,percentage:o,currentStepDescription:a,status:i}}static summarizeCompletedSteps(e,t){let r=[];for(let o of e.steps){if(o.id===t)break;if(o.status==="completed"&&o.result){let n=o.result.toolsUsed?.length?` (Tools: ${o.result.toolsUsed.join(", ")})`:"",a=o.result.output||"No output";a.length>500&&(a=a.substring(0,500)+"... [truncated]"),r.push(`Step ${o.number}: ${o.description}${n}
|
|
280
|
+
Result: ${a}`)}else o.status==="failed"?r.push(`Step ${o.number}: ${o.description}
|
|
281
|
+
Failed: ${o.result?.error||"Unknown error"}`):o.status==="skipped"&&r.push(`Step ${o.number}: ${o.description}
|
|
282
|
+
Skipped.`)}return r.length===0?"No previous steps.":r.join(`
|
|
283
|
+
|
|
284
|
+
`)}};k();var qy=Kr,Uy=`
|
|
254
285
|
Based on the result of the previous step, do we need to add any new steps to our plan before continuing?
|
|
255
286
|
Only add steps if they are absolutely necessary to complete the user's request.
|
|
287
|
+
|
|
288
|
+
Already planned next steps:
|
|
289
|
+
{{REMAINING_STEPS}}
|
|
290
|
+
|
|
291
|
+
Only suggest steps if they are NOT covered by the above.
|
|
292
|
+
|
|
256
293
|
If additional steps are truly required, respond with a JSON object containing the new steps.
|
|
257
294
|
If not necessary or if the plan is sufficient, respond with {"steps": []}.
|
|
258
295
|
|
|
@@ -262,9 +299,9 @@ JSON Schema:
|
|
|
262
299
|
{ "description": "What to do", "expectedTools": [] }
|
|
263
300
|
]
|
|
264
301
|
}
|
|
265
|
-
`,
|
|
266
|
-
... [truncated]`),
|
|
267
|
-
|
|
302
|
+
`,Yt=class{client;config;constructor(e,t){this.client=e,this.config=t}async executeStep(e,t,r,o){let n=Date.now();h(`[StepExecutor] executeStep() step=${e.number} "${e.description}" expectedTools=${e.expectedTools?.join(",")||"none"}`);let a=this.buildStepRequest(e,t,r);try{let i=await this.client.generate(a,o),c=new Set;i.tool_calls&&i.tool_calls.forEach(m=>c.add(m.name));let p=Date.now()-n;return v(`[StepExecutor] Step ${e.number} completed in ${p}ms toolsUsed=[${Array.from(c).join(", ")||"none"}] output_len=${i.content?.length??0}`),{success:!0,output:i.content||"Step completed successfully.",toolsUsed:Array.from(c),duration:p,response:i}}catch(i){let c=Date.now()-n;return E(`[StepExecutor] Step ${e.number} failed in ${c}ms: ${i.message}`),{success:!1,error:i.message||"Unknown execution error",duration:c}}}async*streamStep(e,t,r,o){h(`[StepExecutor] streamStep() step=${e.number} "${e.description}"`);let n=this.buildStepRequest(e,t,r);yield*this.client.stream(n,o)}buildStepRequest(e,t,r){let o=Qt.summarizeCompletedSteps(t,e.id),a=(this.config?.stepPrompt||qy).replace("{stepNumber}",e.number.toString()).replace("{planSummary}",t.summary).replace("{stepDescription}",e.description).replace("{previousStepsResults}",o),i=r.messages.filter(u=>u.role==="system"),c=r.messages.filter(u=>u.role!=="system"),p=[...i,...c],m=[];for(let u of t.steps){if(u.id===e.id)break;if(u.status==="completed"&&u.result?.output){let g=u.result.output;g.length>2e3&&(g=g.substring(0,2e3)+`
|
|
303
|
+
... [truncated]`),m.push({role:"assistant",content:g}),m.push({role:"user",content:`Step ${u.number} is complete. Now proceed with the next step.`})}}return{...r,messages:[{role:"system",content:a},...p,...m],tool_choice:"auto"}}async checkForDynamicSteps(e,t,r,o){if(!this.config?.allowDynamicSteps)return[];let n=t.steps.length,a=this.config.maxTotalSteps??50;if(n>=a)return h(`[StepExecutor] checkForDynamicSteps() skipped \u2014 already at maxTotalSteps=${a}`),[];h(`[StepExecutor] checkForDynamicSteps() after step=${e.number} currentTotal=${n} max=${a}`);let i=t.steps.filter(w=>w.status==="pending"&&w.number>e.number).map(w=>`${w.number}. ${w.description}`).join(`
|
|
304
|
+
`)||"None",c=Uy.replace("{{REMAINING_STEPS}}",i),p=r.messages.filter(w=>w.role==="system"),m=r.messages.filter(w=>w.role!=="system"),u=[...p,...m],g={...r,tool_choice:"none",response_format:"json_object",messages:[...u,{role:"assistant",content:e.result?.output||""},{role:"user",content:c}]};try{let w=await this.client.generate(g,o),y=JSON.parse(w.content||'{"steps": []}');if(Array.isArray(y.steps)&&y.steps.length>0){let b=a-n,P=y.steps.slice(0,b),$=new Set(t.steps.map(x=>this.normalizeStepDescription(x.description))),C=P.filter(x=>{let S=this.normalizeStepDescription(x.description||"");return $.has(S)?!1:($.add(S),!0)});return C.length===0?(h("[StepExecutor] checkForDynamicSteps() all proposed steps were duplicates \u2014 skipping"),[]):(v(`[StepExecutor] checkForDynamicSteps() adding ${C.length} dynamic step(s) after step ${e.number}`),C.map((x,S)=>({id:`step-${Date.now()}-dyn-${S}`,number:0,description:x.description||"Dynamic step",expectedTools:x.expectedTools||[],dependsOn:[e.id],status:"pending"})))}}catch{}return[]}normalizeStepDescription(e){return e.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim().split(" ").filter(t=>t.length>2).sort().join(" ")}};l();var Ug=require("events");k();var qo=class extends Ug.EventEmitter{client;config;planner;stepExecutor;queryClassifier;pendingApprovals=new Map;constructor(e,t,r){super(),this.client=e,this.config=t,this.queryClassifier=r||new He,this.planner=new Kt(e,t.planning),this.stepExecutor=new Yt(e,t.steps)}getConfig(){return this.config}setConfig(e){this.config=e,this.planner=new Kt(this.client,e.planning),this.stepExecutor=new Yt(this.client,e.steps)}shouldRouteSimpleQuery(e){if(!this.config.complexityRouting?.enabled)return!1;let t=this.config.complexityRouting.strategy??"single-step";if(t==="disabled")return!1;let r=Ae(e.messages);if(!r)return!1;let o=this.queryClassifier.classify(r),n=this.config.complexityRouting.confidenceThreshold??.6,a=!1;switch(o.type){case"action":a=!1;break;case"conversational":a=!0;break;case"analytical":a=o.confidence>=n;break}return h(`[Workflow] shouldRouteSimpleQuery() type=${o.type} confidence=${o.confidence.toFixed(2)} threshold=${n} shouldRoute=${a} strategy=${t}`),a}async execute(e,t){if(this.shouldRouteSimpleQuery(e))return this.executeDirect(e,t);let r=this.config.planning?.enabled,o=this.config.steps?.enabled;if(h(`[Workflow] execute() planningEnabled=${r} stepsEnabled=${o} provider=${t??"default"}`),!r&&!o)return h("[Workflow] execute() mode=direct"),this.executeDirect(e,t);let n=null;if(r){if(h("[Workflow] execute() mode=planning \u2014 creating plan"),n=await this.createPlan(e,t),this.emit("workflow:plan_created",n),this.config.planning?.requireApproval){v(`[Workflow] Plan "${n.id}" requires approval \u2014 waiting`),this.emitProgress(n,"awaiting_approval","Waiting for plan approval");let a=await this.waitForApproval(n.id);if(this.emit("workflow:plan_decision",n,a),!a)return v(`[Workflow] Plan "${n.id}" rejected by user`),n.status="cancelled",this.emitProgress(n,"failed","Plan rejected by user"),{success:!1,plan:n,error:"Plan rejected by user",metrics:{totalDuration:0,stepsCompleted:0,stepsFailed:0,retriesUsed:0}};v(`[Workflow] Plan "${n.id}" approved`)}n.status="approved"}return o?(n||(h("[Workflow] execute() mode=steps-only \u2014 creating implicit plan"),n=await this.planner.createPlan(e,t),this.emit("workflow:plan_created",n),n.status="approved"),this.executeStepByStep(n,e,t)):n?(h("[Workflow] execute() mode=plan-direct (planning only, no steps)"),this.executePlanDirect(n,e,t)):this.executeDirect(e,t)}async executeDirect(e,t){let r=Date.now(),o=this.createDummyPlan(e);h(`[Workflow] executeDirect() provider=${t??"default"}`);try{this.emitProgress(o,"executing","Direct execution");let n=await this.client.generate(e,t);o.status="completed",o.completedAt=new Date,o.steps[0].status="completed";let a=Date.now()-r;h(`[Workflow] executeDirect() completed in ${a}ms content_len=${n.content?.length??0}`);let i={success:!0,plan:o,output:n.content||void 0,metrics:{totalDuration:Date.now()-r,stepsCompleted:1,stepsFailed:0,retriesUsed:0}};return this.emit("workflow:completed",o,i),this.emitProgress(o,"completed","Done"),i}catch(n){o.status="failed",o.completedAt=new Date,o.steps[0].status="failed",E(`[Workflow] executeDirect() failed: ${n.message}`);let a={success:!1,plan:o,error:n.message,metrics:{totalDuration:Date.now()-r,stepsCompleted:0,stepsFailed:1,retriesUsed:0}};return this.emit("workflow:failed",o,n),this.emitProgress(o,"failed","Execution failed"),a}}async createPlan(e,t){h(`[Workflow] createPlan() provider=${t??"default"}`);let r=this.createDummyPlan(e);r.status="draft",this.emitProgress(r,"planning","Creating plan...");let o=await this.planner.createPlan(e,t);return v(`[Workflow] createPlan() completed plan.id=${o.id} steps=${o.steps.length}`),o}async executeStepByStep(e,t,r){e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e),v(`[Workflow] executeStepByStep() plan.id=${e.id} steps=${e.steps.length} maxRetries=${this.config.steps?.maxRetries??3}`);let o=Date.now(),n=0;for(let c=0;c<e.steps.length;c++){let p=e.steps[c];if(p.status!=="pending"&&p.status!=="failed")continue;if(p.dependsOn?.length){let y=p.dependsOn.filter(b=>{let P=e.steps.find($=>$.id===String(b)||$.number===Number(b));return P?P.status!=="completed":!1});if(y.length>0){h(`[Workflow] Step ${p.number} skipped \u2014 unmet deps: ${y.join(", ")}`),p.status="skipped",p.result={success:!1,error:`Unmet dependencies: ${y.join(", ")}`};continue}}p.status="in_progress",this.emit("workflow:step_start",p,e),this.emitProgress(e,"executing",p.description),v(`[Workflow] Step ${p.number}/${e.steps.length} starting: "${p.description}"`);let m=0,u=this.config.steps?.maxRetries??3,g=null,w=!1;for(;m<=u;)try{let y=await this.stepExecutor.executeStep(p,e,t,r);if(y.success){p.status="completed",p.result=y,this.emit("workflow:step_complete",p,e),h(`[Workflow] Step ${p.number} completed in ${y.duration??0}ms toolsUsed=${(y.toolsUsed??[]).join(",")||"none"}`),w=!0;break}else throw new Error(y.error||"Step returned unsuccessful result")}catch(y){if(g=y,m++,m<=u&&this.config.steps?.retryOnFailure)n++,E(`[Workflow] Step ${p.number} failed (attempt ${m}/${u}), retrying: ${g.message}`),this.emit("workflow:step_retry",p,m,e),this.emitProgress(e,"executing",`[Retry ${m}] ${p.description}`);else{E(`[Workflow] Step ${p.number} failed permanently: ${g.message}`),p.status="failed",p.result={success:!1,error:g.message},this.emit("workflow:step_failed",p,g,e);break}}if(!w){let y=this.config.onFailure?.strategy||"abort";if(h(`[Workflow] Step ${p.number} failed \u2014 applying strategy="${y}"`),y==="abort"){e.status="failed",e.completedAt=new Date;let b={success:!1,plan:e,error:`Step ${p.number} failed: ${g?.message}`,metrics:this.computeMetrics(e,o,n)};return this.emit("workflow:failed",e,g),this.emitProgress(e,"failed","Workflow aborted due to step failure"),b}else if(y==="ask_user"){if(this.emitProgress(e,"awaiting_approval",`Step failed: ${g?.message}. Continue?`),!await this.waitForApproval(e.id)){e.status="failed",e.completedAt=new Date;let P={success:!1,plan:e,error:`Workflow aborted by user after step ${p.number} failure`,metrics:this.computeMetrics(e,o,n)};return this.emit("workflow:failed",e,new Error(P.error)),P}p.status="skipped"}else p.status="skipped"}if(w&&this.config.steps?.allowDynamicSteps){let y=await this.stepExecutor.checkForDynamicSteps(p,e,t,r);if(y.length>0){let b=p.number+1;for(let P of y)P.number=b++;for(let P=c+1;P<e.steps.length;P++)e.steps[P].number=b++;e.steps.splice(c+1,0,...y),y.forEach(P=>this.emit("workflow:step_added",P,e))}}}let a=this.computeMetrics(e,o,n);e.status="completed",e.completedAt=new Date,e.metrics=a,v(`[Workflow] executeStepByStep() completed plan.id=${e.id} duration=${a.totalDuration}ms stepsCompleted=${a.stepsCompleted} stepsFailed=${a.stepsFailed} retriesUsed=${n}`);let i={success:!0,plan:e,output:this.extractFinalOutput(e),response:this.extractFinalResponse(e),metrics:e.metrics};return this.emit("workflow:completed",e,i),this.emitProgress(e,"completed","Done"),i}async executePlanDirect(e,t,r){let o=Date.now();e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e),this.emitProgress(e,"executing","Executing plan"),h(`[Workflow] executePlanDirect() plan.id=${e.id} steps=${e.steps.length} provider=${r??"default"}`);let n=`
|
|
268
305
|
You have created the following plan to fulfill the request:
|
|
269
306
|
Summary: ${e.summary}
|
|
270
307
|
|
|
@@ -273,11 +310,13 @@ ${e.steps.map(i=>`${i.number}. ${i.description}`).join(`
|
|
|
273
310
|
`)}
|
|
274
311
|
|
|
275
312
|
Execute this plan now.
|
|
276
|
-
`.trim(),a={...t,messages:[{role:"system",content:n},...t.messages]};try{let i=await this.client.generate(a,
|
|
313
|
+
`.trim(),a={...t,messages:[{role:"system",content:n},...t.messages]};try{let i=await this.client.generate(a,r);e.steps.forEach(p=>{p.status="completed",p.result={success:!0,output:i.content||""}}),e.status="completed",e.completedAt=new Date,e.metrics=this.computeMetrics(e,o,0),h(`[Workflow] executePlanDirect() completed plan.id=${e.id} duration=${Date.now()-o}ms`);let c={success:!0,plan:e,output:i.content||void 0,metrics:e.metrics};return this.emit("workflow:completed",e,c),this.emitProgress(e,"completed","Done"),c}catch(i){e.status="failed",e.completedAt=new Date,E(`[Workflow] executePlanDirect() failed plan.id=${e.id}: ${i.message}`);let c={success:!1,plan:e,error:i.message,metrics:this.computeMetrics(e,o,0)};return this.emit("workflow:failed",e,i),this.emitProgress(e,"failed","Execution failed"),c}}emitProgress(e,t,r){if(!this.config.progress?.enabled)return;let o=Qt.getProgress(e);t&&(o.status=t),r&&(o.currentStepDescription=r),this.emit("workflow:progress",o)}computeMetrics(e,t,r){return{totalDuration:Date.now()-t,stepsCompleted:e.steps.filter(o=>o.status==="completed").length,stepsFailed:e.steps.filter(o=>o.status==="failed").length,retriesUsed:r}}summarizePlanResult(e){return`Workflow completed.
|
|
277
314
|
Summary: ${e.summary}
|
|
278
315
|
Steps:
|
|
279
316
|
`+e.steps.map(t=>`[${t.status.toUpperCase()}] ${t.description}`).join(`
|
|
280
|
-
`)}extractFinalOutput(e){
|
|
317
|
+
`)}extractFinalOutput(e){let t=e.steps[e.steps.length-1];if(t&&/synthesize|summarize|consolidate|combine/i.test(t.description)&&e.steps.length>1)for(let o=e.steps.length-1;o>=0;o--){let n=e.steps[o];if(n.status==="completed"&&n.result?.output)return n.result.output}else{let o=[];for(let n of e.steps)n.status==="completed"&&n.result?.output&&o.push(n.result.output);if(o.length>0)return o.join(`
|
|
318
|
+
|
|
319
|
+
`)}return e.steps.length===0||e.steps.every(o=>o.status==="pending")?e.summary:this.summarizePlanResult(e)}extractFinalResponse(e){for(let t=e.steps.length-1;t>=0;t--){let r=e.steps[t];if(r.status==="completed"&&r.result?.response)return r.result.response}}createDummyPlan(e){let t=e.messages.filter(r=>r.role==="user").map(r=>typeof r.content=="string"?r.content:"[Object]").join("\\n");return{id:`plan-direct-${Date.now()}`,request:t,summary:"Direct execution",steps:[{id:"step-1",number:1,description:"Execute request",status:"pending",dependsOn:[],expectedTools:[]}],status:"in_progress",createdAt:new Date}}async*stream(e,t){let r=this.config.planning?.enabled,o=this.config.steps?.enabled;if(h(`[Workflow] stream() planningEnabled=${r} stepsEnabled=${o} provider=${t??"default"}`),!r&&!o){h("[Workflow] stream() mode=direct"),yield*this.streamDirect(e,t);return}let n=null;if(r){if(yield{delta:"",workflowStep:{number:0,description:"Creating plan..."}},n=await this.planner.createPlan(e,t),this.emit("workflow:plan_created",n),this.config.planning?.requireApproval){this.emitProgress(n,"awaiting_approval","Waiting for plan approval"),yield{delta:`
|
|
281
320
|
|
|
282
321
|
**Plan Created:**
|
|
283
322
|
${n.summary}
|
|
@@ -288,12 +327,12 @@ ${n.steps.map(i=>`${i.number}. ${i.description}`).join(`
|
|
|
288
327
|
|
|
289
328
|
*Waiting for approval...*`,workflowStep:{number:0,description:"Awaiting approval"}};let a=await this.waitForApproval(n.id);if(this.emit("workflow:plan_decision",n,a),!a){n.status="cancelled",yield{delta:`
|
|
290
329
|
|
|
291
|
-
*Plan rejected by user.*`,finish_reason:"stop"};return}}n.status="approved"}if(
|
|
330
|
+
*Plan rejected by user.*`,finish_reason:"stop"};return}}n.status="approved"}if(o){n||(n=await this.planner.createPlan(e,t),this.emit("workflow:plan_created",n),n.status="approved"),yield*this.streamStepByStep(n,e,t);return}if(n){yield*this.streamPlanDirect(n,e,t);return}yield*this.streamDirect(e,t)}async*streamDirect(e,t){yield*this.client.stream(e,t)}async*streamStepByStep(e,t,r){e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e);let o=Date.now(),n=0;for(let i=0;i<e.steps.length;i++){if(t.signal?.aborted){e.status="cancelled",e.completedAt=new Date,this.emit("workflow:failed",e,new Error("Interrupted by user"));return}let c=e.steps[i];if(c.status!=="pending"&&c.status!=="failed")continue;if(c.dependsOn?.length){let y=c.dependsOn.filter(b=>{let P=e.steps.find($=>$.id===String(b)||$.number===Number(b));return P?P.status!=="completed":!1});if(y.length>0){c.status="skipped",c.result={success:!1,error:`Unmet dependencies: ${y.join(", ")}`};continue}}c.status="in_progress",this.emit("workflow:step_start",c,e),this.emitProgress(e,"executing",c.description);let p=0,m=this.config.steps?.maxRetries??3,u=null,g=!1,w="";for(;p<=m;)try{for await(let y of this.stepExecutor.streamStep(c,e,t,r)){if(t.signal?.aborted){c.status="skipped",e.status="cancelled",e.completedAt=new Date,this.emit("workflow:failed",e,new Error("Interrupted by user"));return}y.delta&&(w+=y.delta),yield{...y,workflowStep:{number:c.number,description:c.description}}}c.status="completed",c.result={success:!0,output:w,duration:Date.now()-o},this.emit("workflow:step_complete",c,e),this.emitProgress(e,"executing"),g=!0;break}catch(y){if(u=y,p++,p<=m&&this.config.steps?.retryOnFailure)n++,this.emit("workflow:step_retry",c,p,e),this.emitProgress(e,"executing",`[Retry ${p}/${m}] ${c.description}`);else{c.status="failed",c.result={success:!1,error:u.message},this.emit("workflow:step_failed",c,u,e);break}}if(!g){let y=this.config.onFailure?.strategy||"abort";if(y==="abort"){e.status="failed",e.completedAt=new Date,this.emit("workflow:failed",e,u),yield{delta:`
|
|
292
331
|
|
|
293
332
|
**Step failed:** ${u?.message}
|
|
294
333
|
*Workflow aborted.*`,finish_reason:"stop"};return}else y==="skip"&&(c.status="skipped",yield{delta:`
|
|
295
334
|
*Step skipped due to failure.*
|
|
296
|
-
`,workflowStep:{number:c.number,description:c.description}})}if(g&&this.config.steps?.allowDynamicSteps){let y=await this.stepExecutor.checkForDynamicSteps(c,e,t,
|
|
335
|
+
`,workflowStep:{number:c.number,description:c.description}})}if(g&&this.config.steps?.allowDynamicSteps){let y=await this.stepExecutor.checkForDynamicSteps(c,e,t,r);if(y.length>0){let b=c.number+1;for(let P of y)P.number=b++;for(let P=i+1;P<e.steps.length;P++)e.steps[P].number=b++;e.steps.splice(i+1,0,...y),y.forEach(P=>this.emit("workflow:step_added",P,e)),this.emitProgress(e,"executing")}}}e.status="completed",e.completedAt=new Date,e.metrics=this.computeMetrics(e,o,n);let a={success:!0,plan:e,output:this.extractFinalOutput(e),response:this.extractFinalResponse(e),metrics:e.metrics};this.emit("workflow:completed",e,a),this.emitProgress(e,"completed","Done"),yield{delta:"",finish_reason:"stop"}}async*streamPlanDirect(e,t,r){e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e);let o=`
|
|
297
336
|
You have created the following plan to fulfill the request:
|
|
298
337
|
Summary: ${e.summary}
|
|
299
338
|
|
|
@@ -302,7 +341,4 @@ ${e.steps.map(i=>`${i.number}. ${i.description}`).join(`
|
|
|
302
341
|
`)}
|
|
303
342
|
|
|
304
343
|
Execute this plan now.
|
|
305
|
-
`.trim(),n={...t,messages:[{role:"system",content:r},...t.messages]};yield{delta:`**Plan:**
|
|
306
|
-
${e.summary}
|
|
307
|
-
|
|
308
|
-
`};let a="";for await(let i of this.client.stream(n,o))i.delta&&(a+=i.delta),yield i;e.steps.forEach(i=>{i.status="completed",i.result={success:!0,output:a}}),e.status="completed",e.completedAt=new Date,this.emit("workflow:completed",e,{success:!0,plan:e,output:a,metrics:this.computeMetrics(e,e.startedAt.getTime(),0)})}waitForApproval(e){return new Promise(t=>{this.pendingApprovals.set(e,t)})}approvePlan(e){let t=this.pendingApprovals.get(e);t&&(t(!0),this.pendingApprovals.delete(e))}rejectPlan(e){let t=this.pendingApprovals.get(e);t&&(t(!1),this.pendingApprovals.delete(e))}};l();var zs=require("events");_();var Ks=class s extends zs.EventEmitter{client;activeProviderName;modeRegistry;workflowExecutor;customProviderNames=new Set;mcpToolProject=null;constructor(e,t,o){super(),this.client=e,this.activeProviderName=t,this.modeRegistry=o;let r=this.client.getProvider(t);r&&this.forwardEvents(r),this.workflowExecutor=new Fo(this.client,zr),this.forwardWorkflowEvents()}static async init(e){let t=lo(e.configPath);ci(t.logging);let o=new Gt,r=Nt(e.configPath);if(o.setConfig(r),e.tools&&await o.loadBuiltIn(),e.customTools&&await o.loadProjects(e.customTools),e.knowledge&&typeof e.knowledge.toTool=="function")try{let x=e.knowledge.toTool(),k={manifest:{key:"knowledge",name:"knowledge",displayName:"Knowledge Base",version:"1.0.0",description:"RAG-powered knowledge base search",tools:["knowledge_search"],category:"search"},tools:[x]};await o.loadProjects([k]),v("[Knowledge] Registered knowledge_search tool")}catch(x){Y(`[Knowledge] Failed to register knowledge tool: ${x}`)}let n=null,a=e.mcp||t.mcp;if(a)try{v("[MCP] Initializing MCP tool integration");let x=await Jr(a);n=x,await o.loadProjects([x]),v(`[MCP] Loaded ${x.tools.length} tools from MCP servers`)}catch(x){Y(`[MCP] Failed to initialize MCP tools: ${x}`)}let i=t.systemPrompt,c=e.disableBaseContext||t.disableBaseContext||t.baseContext===!1||!1,p=t.modeOverrides||{},m={},u=new Set,g=e.defaultProvider||e.provider;if(e.providers)for(let[x,k]of Object.entries(e.providers)){let R=x===g,j=await s.createProvider(x,k,e.configPath,!R);j&&(m[x]=j)}else if(e.provider){let x={apiKey:e.apiKey,model:e.model},k=await s.createProvider(e.provider,x,e.configPath,!1);k&&(m[e.provider]=k)}else if(!e.customProviders)throw new Error('No provider specified. Pass { provider: "name" }, { providers: { ... } }, or { customProviders: { ... } } to init().');if(e.customProviders){let x=Array.isArray(e.customProviders)?e.customProviders:Object.entries(e.customProviders).map(([k,R])=>(R.name=R.name||k,R));for(let k of x){if(typeof k.generate!="function"||typeof k.stream!="function"||typeof k.embed!="function")throw new Error("Custom provider must implement the ProviderAdapter interface (generate, stream, embed methods). Import { ProviderAdapter } from 'toolpack' and implement or extend it.");let R=k.name;if(!R)throw new Error("Custom provider must have a 'name' property set. Set adapter.name in the constructor or use the record syntax: { 'provider-name': adapter }");if(m[R])throw new Error(`Custom provider name "${R}" conflicts with a built-in provider designation. Choose a different name.`);u.add(R),m[R]=k}}if(!g&&e.customProviders&&(g=(Array.isArray(e.customProviders)?e.customProviders[0]:Object.values(e.customProviders)[0])?.name),!g)throw new Error("No default provider specified.");let b=new Jt;if(e.customModes)for(let x of e.customModes)b.register(x);let y={...p,...e.modeOverrides||{}};for(let[x,k]of Object.entries(y)){let R=b.get(x);if(R){k.systemPrompt!==void 0&&(R.systemPrompt=k.systemPrompt),k.toolSearch&&(R.toolSearch={...R.toolSearch||{},...k.toolSearch});for(let[j,U]of Object.entries(k))j!=="systemPrompt"&&j!=="toolSearch"&&(R[j]=U)}}let w=new Xt({providers:m,defaultProvider:g,toolRegistry:o,toolsConfig:o.getConfig(),systemPrompt:i,disableBaseContext:c}),T=new s(w,g,b);T.customProviderNames=u,T.mcpToolProject=n;let S=e.defaultMode||Fe,C=b.get(S);return C&&(w.setMode(C),C.workflow&&T.workflowExecutor.setConfig(C.workflow)),T}static async createProvider(e,t,o,r=!1){if(["openai","anthropic","gemini"].includes(e)){let n=`TOOLPACK_${e.toUpperCase()}_KEY`,a=t.apiKey||process.env[n]||process.env[`${e.toUpperCase()}_API_KEY`];if(!a){if(r)return null;throw new Error(`No API key found for '${e}'. Set ${n} or pass apiKey in config.`)}switch(e){case"openai":return new so(a,t.baseUrl);case"anthropic":return new eo(a,t.baseUrl);case"gemini":return new to(a)}}if(e==="ollama")return new He({baseUrl:t.baseUrl||no(o)});if(e.startsWith("ollama-")){let n=t.model||e.replace(/^ollama-/,""),a=t.baseUrl||no(o);return new xe({model:n,baseUrl:a})}throw new Error(`Unknown provider type: ${e}`)}async generate(e,t){let o;typeof e=="string"?o={messages:[{role:"user",content:e}],model:""}:o=e;let r=this.getMode();if(r?.workflow?.planning?.enabled||r?.workflow?.steps?.enabled){let n=await this.workflowExecutor.execute(o,t||this.activeProviderName),a=0,i=0,c=0,p={steps:[]};n.plan.planningResponse?.usage&&(a+=n.plan.planningResponse.usage.prompt_tokens,i+=n.plan.planningResponse.usage.completion_tokens||0,c+=n.plan.planningResponse.usage.total_tokens,p.planning=n.plan.planningResponse.usage);for(let u of n.plan.steps)if(u.status==="completed"&&u.result?.response?.usage){let g=u.result.response.usage;a+=g.prompt_tokens,i+=g.completion_tokens||0,c+=g.total_tokens,p.steps.push({stepNumber:u.number,description:u.description,usage:g})}let m={prompt_tokens:a,completion_tokens:i,total_tokens:c};return n.response?{...n.response,content:n.output||n.response.content||null,usage:m,usage_details:p}:{content:n.output||null,usage:m,usage_details:p}}return this.client.generate(o,t)}async*stream(e,t){let o=this.getMode(),r=t||this.activeProviderName;if(o?.workflow?.planning?.enabled||o?.workflow?.steps?.enabled){yield*this.workflowExecutor.stream(e,r);return}yield*this.client.stream(e,t)}async embed(e,t){return this.client.embed(e,t)}setProvider(e){let t=this.client.getProvider(e);this.activeProviderName=e,this.client.setDefaultProvider(e),this.forwardEvents(t)}getProvider(){return this.client.getProvider(this.activeProviderName)}getClient(){return this.client}getWorkflowExecutor(){return this.workflowExecutor}async disconnect(){let e=this.getProvider();e&&"disconnect"in e&&await e.disconnect(),this.mcpToolProject&&await Hr(this.mcpToolProject)}async listProviders(){let e=this.client.getProviders(),t=[];for(let[o,r]of e.entries()){let n=this.customProviderNames.has(o),a=[];try{a=await r.getModels()}catch(i){D(`[Toolpack] Failed to fetch models for provider '${o}': ${i}`)}t.push({name:o,displayName:r.getDisplayName(),type:n?"custom":"built-in",models:a})}return t}async loadToolProject(e){let t=this.client.getToolRegistry();if(t)await t.loadProject(e);else throw new Error("No tool registry configured. Initialize Toolpack with tools enabled.")}async listModels(){let e=await this.listProviders(),t=[];for(let o of e)for(let r of o.models)t.push({...r,provider:o.name});return t}setMode(e){let t=this.modeRegistry.get(e);if(!t)throw new Error(`Mode "${e}" not found. Available modes: ${this.modeRegistry.getNames().join(", ")}`);return this.client.setMode(t),t.workflow?this.workflowExecutor.setConfig(t.workflow):this.workflowExecutor.setConfig(zr),t}getMode(){return this.client.getMode()}getActiveModeName(){let e=this.client.getMode();return e?e.displayName:"Default"}getModes(){return this.modeRegistry.getAll()}cycleMode(){let e=this.client.getMode(),t=e?e.name:"default",o=this.modeRegistry.getNext(t);return this.client.setMode(o),o}registerMode(e){this.modeRegistry.register(e)}forwardEvents(e){e instanceof zs.EventEmitter&&e.on("status",t=>this.emit("status",t))}forwardWorkflowEvents(){let e=this.workflowExecutor;e.on("workflow:plan_created",t=>this.emit("workflow:plan_created",t)),e.on("workflow:plan_decision",(t,o)=>this.emit("workflow:plan_decision",t,o)),e.on("workflow:started",t=>this.emit("workflow:started",t)),e.on("workflow:step_start",(t,o)=>this.emit("workflow:step_start",t,o)),e.on("workflow:step_complete",(t,o)=>this.emit("workflow:step_complete",t,o)),e.on("workflow:step_failed",(t,o,r)=>this.emit("workflow:step_failed",t,o,r)),e.on("workflow:step_retry",(t,o,r)=>this.emit("workflow:step_retry",t,o,r)),e.on("workflow:step_added",(t,o)=>this.emit("workflow:step_added",t,o)),e.on("workflow:progress",t=>this.emit("workflow:progress",t)),e.on("workflow:completed",(t,o)=>this.emit("workflow:completed",t,o)),e.on("workflow:failed",(t,o)=>this.emit("workflow:failed",t,o))}};l();var Og=P(require("os"),1),Le=P(require("path"),1),Qt=P(require("fs"),1),Qs=".toolpack",Ys="config",Vs="toolpack.config.json";function Ig(){return Og.homedir()}function jg(){return Le.join(Ig(),Qs)}function Xs(){return Le.join(jg(),Ys)}function Lo(){return Le.join(Xs(),Vs)}function Fg(s=process.cwd()){return Le.join(s,Qs)}function Zs(s=process.cwd()){return Le.join(Fg(s),Ys)}function qo(s=process.cwd()){return Le.join(Zs(s),Vs)}function ei(){let s=Xs();Qt.existsSync(s)||Qt.mkdirSync(s,{recursive:!0})}function Ay(s=process.cwd()){let e=Zs(s);Qt.existsSync(e)||Qt.mkdirSync(e,{recursive:!0})}l();var z=P(require("fs"),1),Kr=P(require("path"),1);function oi(s,e){if(!e)return s;if(!s)return e;let t={...s};for(let o of Object.keys(e))e[o]instanceof Array?t[o]=e[o]:e[o]instanceof Object&&o in s?t[o]=oi(s[o],e[o]):t[o]=e[o];return t}function ti(s){if(!z.existsSync(s))return null;try{let e=z.readFileSync(s,"utf-8");return JSON.parse(e)}catch{return null}}function My(s=process.cwd()){let e=Kr.join(s,"toolpack.config.json"),t=Lo(),o=qo(s),r=ti(e)||{},n=ti(t)||{},a=ti(o)||{},i=oi(r,n);return i=oi(i,a),i}function Oy(s=process.cwd()){let e=Kr.join(s,"toolpack.config.json"),t=Lo(),o=qo(s),r=!z.existsSync(t),n=null,a="default";return z.existsSync(o)?(n=o,a="local"):z.existsSync(t)?(n=t,a="global"):z.existsSync(e)&&(n=e,a="base"),{isFirstRun:r,activeConfigPath:n,configSource:a}}function Iy(s=process.cwd()){let e=Lo();if(!z.existsSync(e)){ei();let t=null,o=qo(s);if(z.existsSync(o))t=o;else{let n=Kr.join(s,"toolpack.config.json");if(z.existsSync(n))t=n;else{let a=an();a&&z.existsSync(a)&&(t=a)}}let r={};if(t)try{let n=z.readFileSync(t,"utf-8");r=JSON.parse(n)}catch{}z.writeFileSync(e,JSON.stringify(r,null,4),"utf-8")}}l();0&&(module.exports={AGENT_MODE,AIClient,AnthropicAdapter,AuthenticationError,BM25SearchEngine,BUILT_IN_MODES,CHAT_MODE,CONFIG_DIR_NAME,CONFIG_FILE_NAME,ConnectionError,DEFAULT_MODE_NAME,DEFAULT_TOOLS_CONFIG,DEFAULT_TOOL_SEARCH_CONFIG,DEFAULT_WORKFLOW_CONFIG,GeminiAdapter,InvalidRequestError,McpClient,McpConnectionError,McpTimeoutError,McpToolManager,ModeRegistry,OllamaAdapter,OllamaProvider,OpenAIAdapter,PageError,Planner,ProviderAdapter,ProviderError,RateLimitError,SDKError,StepExecutor,TOOLPACK_DIR_NAME,TOOL_SEARCH_NAME,TimeoutError,ToolDiscoveryCache,ToolRegistry,ToolRouter,Toolpack,WorkflowExecutor,cloudDeployTool,cloudListTool,cloudStatusTool,cloudToolsProject,codingFindSymbolTool,codingGetImportsTool,codingGetSymbolsTool,codingToolsProject,createMcpToolProject,createMode,createToolProject,dbCountTool,dbDeleteTool,dbInsertTool,dbQueryTool,dbSchemaTool,dbTablesTool,dbToolsProject,dbUpdateTool,diffApplyTool,diffCreateTool,diffPreviewTool,diffToolsProject,disconnectMcpToolProject,ensureGlobalConfigDir,ensureLocalConfigDir,execKillTool,execListProcessesTool,execReadOutputTool,execRunBackgroundTool,execRunShellTool,execRunTool,execToolsProject,fetchUrlAsBase64,fsAppendFileTool,fsCopyTool,fsCreateDirTool,fsDeleteFileTool,fsExistsTool,fsListDirTool,fsMoveTool,fsReadFileRangeTool,fsReadFileTool,fsReplaceInFileTool,fsSearchTool,fsStatTool,fsToolsProject,fsTreeTool,fsWriteFileTool,generateToolCategoriesPrompt,getDefaultSlmModel,getGlobalConfigDir,getGlobalConfigPath,getGlobalToolpackDir,getLocalConfigDir,getLocalConfigPath,getLocalToolpackDir,getMimeType,getOllamaBaseUrl,getOllamaProviderEntries,getRegisteredSlmModels,getRuntimeConfigStatus,getToolSearchSchema,getToolpackConfig,getUserHomeDir,gitAddTool,gitBlameTool,gitBranchCreateTool,gitBranchListTool,gitCheckoutTool,gitCommitTool,gitDiffTool,gitLogTool,gitStatusTool,gitToolsProject,httpDeleteTool,httpDownloadTool,httpGetTool,httpPostTool,httpPutTool,httpToolsProject,initializeGlobalConfigIfFirstRun,isDataUri,isRegisteredSlm,isToolSearchTool,loadFullConfig,loadRuntimeConfig,loadToolsConfig,normalizeImagePart,ollamaRequest,ollamaStream,parseDataUri,readFileAsBase64,reloadToolpackConfig,saveToolsConfig,systemCwdTool,systemDiskUsageTool,systemEnvTool,systemInfoTool,systemSetEnvTool,systemToolsProject,toDataUri,toolSearchDefinition,webExtractLinksTool,webFetchTool,webScrapeTool,webSearchTool,webToolsProject});
|
|
344
|
+
`.trim(),n={...t,messages:[{role:"system",content:o},...t.messages]},a="";for await(let i of this.client.stream(n,r))i.delta&&(a+=i.delta),yield i;e.steps.forEach(i=>{i.status="completed",i.result={success:!0,output:a}}),e.status="completed",e.completedAt=new Date,this.emit("workflow:completed",e,{success:!0,plan:e,output:a,metrics:this.computeMetrics(e,e.startedAt.getTime(),0)})}waitForApproval(e){return new Promise(t=>{this.pendingApprovals.set(e,t)})}approvePlan(e){let t=this.pendingApprovals.get(e);t&&(t(!0),this.pendingApprovals.delete(e))}rejectPlan(e){let t=this.pendingApprovals.get(e);t&&(t(!1),this.pendingApprovals.delete(e))}};l();var Xs=require("events");k();var Zs=class s extends Xs.EventEmitter{client;activeProviderName;modeRegistry;workflowExecutor;customProviderNames=new Set;mcpToolProject=null;constructor(e,t,r){super(),this.client=e,this.activeProviderName=t,this.modeRegistry=r;let o=this.client.getProvider(t);o&&this.forwardEvents(o),this.workflowExecutor=new qo(this.client,Qr,this.client.getQueryClassifier()),this.forwardWorkflowEvents()}static async init(e){let t=po(e.configPath);fi(t.logging);let r=new Jt,o=Mt(e.configPath);if(r.setConfig(o),e.tools&&await r.loadBuiltIn(),e.customTools&&await r.loadProjects(e.customTools),e.knowledge&&typeof e.knowledge.toTool=="function")try{let x=e.knowledge.toTool(),S={manifest:{key:"knowledge",name:"knowledge",displayName:"Knowledge Base",version:"1.0.0",description:"RAG-powered knowledge base search",tools:["knowledge_search"],category:"search"},tools:[x]};await r.loadProjects([S]),v("[Knowledge] Registered knowledge_search tool")}catch(x){Y(`[Knowledge] Failed to register knowledge tool: ${x}`)}let n=null,a=e.mcp||t.mcp;if(a)try{v("[MCP] Initializing MCP tool integration");let x=await Jr(a);n=x,await r.loadProjects([x]),v(`[MCP] Loaded ${x.tools.length} tools from MCP servers`)}catch(x){Y(`[MCP] Failed to initialize MCP tools: ${x}`)}let i=t.systemPrompt,c=e.disableBaseContext||t.disableBaseContext||t.baseContext===!1||!1,p=t.modeOverrides||{},m={},u=new Set,g=e.defaultProvider||e.provider;if(e.providers)for(let[x,S]of Object.entries(e.providers)){let R=x===g,j=await s.createProvider(x,S,e.configPath,!R);j&&(m[x]=j)}else if(e.provider){let x={apiKey:e.apiKey,model:e.model},S=await s.createProvider(e.provider,x,e.configPath,!1);S&&(m[e.provider]=S)}else if(!e.customProviders)throw new Error('No provider specified. Pass { provider: "name" }, { providers: { ... } }, or { customProviders: { ... } } to init().');if(e.customProviders){let x=Array.isArray(e.customProviders)?e.customProviders:Object.entries(e.customProviders).map(([S,R])=>(R.name=R.name||S,R));for(let S of x){if(typeof S.generate!="function"||typeof S.stream!="function"||typeof S.embed!="function")throw new Error("Custom provider must implement the ProviderAdapter interface (generate, stream, embed methods). Import { ProviderAdapter } from 'toolpack' and implement or extend it.");let R=S.name;if(!R)throw new Error("Custom provider must have a 'name' property set. Set adapter.name in the constructor or use the record syntax: { 'provider-name': adapter }");if(m[R])throw new Error(`Custom provider name "${R}" conflicts with a built-in provider designation. Choose a different name.`);u.add(R),m[R]=S}}if(!g&&e.customProviders&&(g=(Array.isArray(e.customProviders)?e.customProviders[0]:Object.values(e.customProviders)[0])?.name),!g)throw new Error("No default provider specified.");let w=new zt;if(e.customModes)for(let x of e.customModes)w.register(x);let y={...p,...e.modeOverrides||{}};for(let[x,S]of Object.entries(y)){let R=w.get(x);if(R){S.systemPrompt!==void 0&&(R.systemPrompt=S.systemPrompt),S.toolSearch&&(R.toolSearch={...R.toolSearch||{},...S.toolSearch});for(let[j,U]of Object.entries(S))j!=="systemPrompt"&&j!=="toolSearch"&&(R[j]=U)}}let b=new eo({providers:m,defaultProvider:g,toolRegistry:r,toolsConfig:r.getConfig(),systemPrompt:i,disableBaseContext:c}),P=new s(b,g,w);P.customProviderNames=u,P.mcpToolProject=n;let $=e.defaultMode||Le,C=w.get($);return C&&(b.setMode(C),C.workflow&&P.workflowExecutor.setConfig(C.workflow)),P}static async createProvider(e,t,r,o=!1){if(["openai","anthropic","gemini"].includes(e)){let n=`TOOLPACK_${e.toUpperCase()}_KEY`,a=t.apiKey||process.env[n]||process.env[`${e.toUpperCase()}_API_KEY`];if(!a){if(o)return null;throw new Error(`No API key found for '${e}'. Set ${n} or pass apiKey in config.`)}switch(e){case"openai":return new ao(a,t.baseUrl);case"anthropic":return new oo(a,t.baseUrl);case"gemini":return new ro(a)}}if(e==="ollama")return new Ke({baseUrl:t.baseUrl||io(r)});if(e.startsWith("ollama-")){let n=t.model||e.replace(/^ollama-/,""),a=t.baseUrl||io(r);return new xe({model:n,baseUrl:a})}throw new Error(`Unknown provider type: ${e}`)}async generate(e,t){let r;typeof e=="string"?r={messages:[{role:"user",content:e}],model:""}:r=e;let o=this.getMode();if(o?.workflow?.planning?.enabled||o?.workflow?.steps?.enabled){let n=await this.workflowExecutor.execute(r,t||this.activeProviderName),a=0,i=0,c=0,p={steps:[]};n.plan.planningResponse?.usage&&(a+=n.plan.planningResponse.usage.prompt_tokens,i+=n.plan.planningResponse.usage.completion_tokens||0,c+=n.plan.planningResponse.usage.total_tokens,p.planning=n.plan.planningResponse.usage);for(let u of n.plan.steps)if(u.status==="completed"&&u.result?.response?.usage){let g=u.result.response.usage;a+=g.prompt_tokens,i+=g.completion_tokens||0,c+=g.total_tokens,p.steps.push({stepNumber:u.number,description:u.description,usage:g})}let m={prompt_tokens:a,completion_tokens:i,total_tokens:c};return n.response?{...n.response,content:n.output||n.response.content||null,usage:m,usage_details:p}:{content:n.output||null,usage:m,usage_details:p}}return this.client.generate(r,t)}async*stream(e,t){let r=this.getMode(),o=t||this.activeProviderName;if(r?.workflow?.planning?.enabled||r?.workflow?.steps?.enabled){yield*this.workflowExecutor.stream(e,o);return}yield*this.client.stream(e,t)}async embed(e,t){return this.client.embed(e,t)}setProvider(e){let t=this.client.getProvider(e);this.activeProviderName=e,this.client.setDefaultProvider(e),this.forwardEvents(t)}getProvider(){return this.client.getProvider(this.activeProviderName)}getClient(){return this.client}getWorkflowExecutor(){return this.workflowExecutor}async disconnect(){let e=this.getProvider();e&&"disconnect"in e&&await e.disconnect(),this.mcpToolProject&&await Hr(this.mcpToolProject)}async listProviders(){let e=this.client.getProviders(),t=[];for(let[r,o]of e.entries()){let n=this.customProviderNames.has(r),a=[];try{a=await o.getModels()}catch(i){E(`[Toolpack] Failed to fetch models for provider '${r}': ${i}`)}t.push({name:r,displayName:o.getDisplayName(),type:n?"custom":"built-in",models:a})}return t}async loadToolProject(e){let t=this.client.getToolRegistry();if(t)await t.loadProject(e);else throw new Error("No tool registry configured. Initialize Toolpack with tools enabled.")}async listModels(){let e=await this.listProviders(),t=[];for(let r of e)for(let o of r.models)t.push({...o,provider:r.name});return t}setMode(e){let t=this.modeRegistry.get(e);if(!t)throw new Error(`Mode "${e}" not found. Available modes: ${this.modeRegistry.getNames().join(", ")}`);return this.client.setMode(t),t.workflow?this.workflowExecutor.setConfig(t.workflow):this.workflowExecutor.setConfig(Qr),t}getMode(){return this.client.getMode()}getActiveModeName(){let e=this.client.getMode();return e?e.displayName:"Default"}getModes(){return this.modeRegistry.getAll()}cycleMode(){let e=this.client.getMode(),t=e?e.name:"default",r=this.modeRegistry.getNext(t);return this.client.setMode(r),r}registerMode(e){this.modeRegistry.register(e)}forwardEvents(e){e instanceof Xs.EventEmitter&&e.on("status",t=>this.emit("status",t))}forwardWorkflowEvents(){let e=this.workflowExecutor;e.on("workflow:plan_created",t=>this.emit("workflow:plan_created",t)),e.on("workflow:plan_decision",(t,r)=>this.emit("workflow:plan_decision",t,r)),e.on("workflow:started",t=>this.emit("workflow:started",t)),e.on("workflow:step_start",(t,r)=>this.emit("workflow:step_start",t,r)),e.on("workflow:step_complete",(t,r)=>this.emit("workflow:step_complete",t,r)),e.on("workflow:step_failed",(t,r,o)=>this.emit("workflow:step_failed",t,r,o)),e.on("workflow:step_retry",(t,r,o)=>this.emit("workflow:step_retry",t,r,o)),e.on("workflow:step_added",(t,r)=>this.emit("workflow:step_added",t,r)),e.on("workflow:progress",t=>this.emit("workflow:progress",t)),e.on("workflow:completed",(t,r)=>this.emit("workflow:completed",t,r)),e.on("workflow:failed",(t,r)=>this.emit("workflow:failed",t,r))}};l();var Wg=T(require("os"),1),qe=T(require("path"),1),Vt=T(require("fs"),1),ei=".toolpack",ti="config",oi="toolpack.config.json";function Gg(){return Wg.homedir()}function Bg(){return qe.join(Gg(),ei)}function ri(){return qe.join(Bg(),ti)}function Uo(){return qe.join(ri(),oi)}function Jg(s=process.cwd()){return qe.join(s,ei)}function ni(s=process.cwd()){return qe.join(Jg(s),ti)}function Wo(s=process.cwd()){return qe.join(ni(s),oi)}function si(){let s=ri();Vt.existsSync(s)||Vt.mkdirSync(s,{recursive:!0})}function Wy(s=process.cwd()){let e=ni(s);Vt.existsSync(e)||Vt.mkdirSync(e,{recursive:!0})}l();var z=T(require("fs"),1),Yr=T(require("path"),1);function ai(s,e){if(!e)return s;if(!s)return e;let t={...s};for(let r of Object.keys(e))e[r]instanceof Array?t[r]=e[r]:e[r]instanceof Object&&r in s?t[r]=ai(s[r],e[r]):t[r]=e[r];return t}function ii(s){if(!z.existsSync(s))return null;try{let e=z.readFileSync(s,"utf-8");return JSON.parse(e)}catch{return null}}function Gy(s=process.cwd()){let e=Yr.join(s,"toolpack.config.json"),t=Uo(),r=Wo(s),o=ii(e)||{},n=ii(t)||{},a=ii(r)||{},i=ai(o,n);return i=ai(i,a),i}function By(s=process.cwd()){let e=Yr.join(s,"toolpack.config.json"),t=Uo(),r=Wo(s),o=!z.existsSync(t),n=null,a="default";return z.existsSync(r)?(n=r,a="local"):z.existsSync(t)?(n=t,a="global"):z.existsSync(e)&&(n=e,a="base"),{isFirstRun:o,activeConfigPath:n,configSource:a}}function Jy(s=process.cwd()){let e=Uo();if(!z.existsSync(e)){si();let t=null,r=Wo(s);if(z.existsSync(r))t=r;else{let n=Yr.join(s,"toolpack.config.json");if(z.existsSync(n))t=n;else{let a=cn();a&&z.existsSync(a)&&(t=a)}}let o={};if(t)try{let n=z.readFileSync(t,"utf-8");o=JSON.parse(n)}catch{}z.writeFileSync(e,JSON.stringify(o,null,4),"utf-8")}}l();0&&(module.exports={AGENT_MODE,AGENT_PLANNING_PROMPT,AGENT_STEP_PROMPT,AGENT_WORKFLOW,AIClient,AnthropicAdapter,AuthenticationError,BM25SearchEngine,BUILT_IN_MODES,CHAT_MODE,CHAT_WORKFLOW,CODING_PLANNING_PROMPT,CODING_STEP_PROMPT,CODING_WORKFLOW,CONFIG_DIR_NAME,CONFIG_FILE_NAME,ConnectionError,DEFAULT_MODE_NAME,DEFAULT_TOOLS_CONFIG,DEFAULT_TOOL_SEARCH_CONFIG,DEFAULT_WORKFLOW,DEFAULT_WORKFLOW_CONFIG,GeminiAdapter,InvalidRequestError,McpClient,McpConnectionError,McpTimeoutError,McpToolManager,ModeRegistry,OllamaAdapter,OllamaProvider,OpenAIAdapter,PageError,Planner,ProviderAdapter,ProviderError,RateLimitError,SDKError,StepExecutor,TOOLPACK_DIR_NAME,TOOL_SEARCH_NAME,TimeoutError,ToolDiscoveryCache,ToolRegistry,ToolRouter,Toolpack,WorkflowExecutor,cloudDeployTool,cloudListTool,cloudStatusTool,cloudToolsProject,codingFindSymbolTool,codingGetImportsTool,codingGetSymbolsTool,codingToolsProject,createMcpToolProject,createMode,createToolProject,dbCountTool,dbDeleteTool,dbInsertTool,dbQueryTool,dbSchemaTool,dbTablesTool,dbToolsProject,dbUpdateTool,diffApplyTool,diffCreateTool,diffPreviewTool,diffToolsProject,disconnectMcpToolProject,ensureGlobalConfigDir,ensureLocalConfigDir,execKillTool,execListProcessesTool,execReadOutputTool,execRunBackgroundTool,execRunShellTool,execRunTool,execToolsProject,fetchUrlAsBase64,fsAppendFileTool,fsCopyTool,fsCreateDirTool,fsDeleteFileTool,fsExistsTool,fsListDirTool,fsMoveTool,fsReadFileRangeTool,fsReadFileTool,fsReplaceInFileTool,fsSearchTool,fsStatTool,fsToolsProject,fsTreeTool,fsWriteFileTool,generateToolCategoriesPrompt,getDefaultSlmModel,getGlobalConfigDir,getGlobalConfigPath,getGlobalToolpackDir,getLocalConfigDir,getLocalConfigPath,getLocalToolpackDir,getMimeType,getOllamaBaseUrl,getOllamaProviderEntries,getRegisteredSlmModels,getRuntimeConfigStatus,getToolSearchSchema,getToolpackConfig,getUserHomeDir,gitAddTool,gitBlameTool,gitBranchCreateTool,gitBranchListTool,gitCheckoutTool,gitCommitTool,gitDiffTool,gitLogTool,gitStatusTool,gitToolsProject,httpDeleteTool,httpDownloadTool,httpGetTool,httpPostTool,httpPutTool,httpToolsProject,initializeGlobalConfigIfFirstRun,isDataUri,isRegisteredSlm,isToolSearchTool,loadFullConfig,loadRuntimeConfig,loadToolsConfig,normalizeImagePart,ollamaRequest,ollamaStream,parseDataUri,readFileAsBase64,reloadToolpackConfig,saveToolsConfig,systemCwdTool,systemDiskUsageTool,systemEnvTool,systemInfoTool,systemSetEnvTool,systemToolsProject,toDataUri,toolSearchDefinition,webExtractLinksTool,webFetchTool,webScrapeTool,webSearchTool,webToolsProject});
|