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/dist/index.js CHANGED
@@ -1,57 +1,57 @@
1
- var Gf=Object.defineProperty;var g=(s,e)=>()=>(s&&(e=s(s=0)),e);var re=(s,e)=>{for(var t in e)Gf(s,t,{get:e[t],enumerable:!0})};import Bf from"path";import{fileURLToPath as Jf}from"url";var Hf,zf,d,l=g(()=>{"use strict";Hf=()=>Jf(import.meta.url),zf=()=>Bf.dirname(Hf()),d=zf()});var H,ge,he,M,F,ke,ss,is,ce=g(()=>{"use strict";l();H=class extends Error{constructor(t,o,r,n){super(t);this.code=o;this.statusCode=r;this.cause=n;this.name="SDKError"}code;statusCode;cause},ge=class extends H{constructor(e,t){super(e,"AUTHENTICATION_ERROR",401,t),this.name="AuthenticationError"}},he=class extends H{constructor(t,o,r){super(t,"RATE_LIMIT_ERROR",429,r);this.retryAfter=o;this.name="RateLimitError"}retryAfter},M=class extends H{constructor(e,t){super(e,"INVALID_REQUEST_ERROR",400,t),this.name="InvalidRequestError"}},F=class extends H{constructor(e,t="PROVIDER_ERROR",o=500,r){super(e,t,o,r),this.name="ProviderError"}},ke=class extends H{constructor(e,t){super(e,"CONNECTION_ERROR",503,t),this.name="ConnectionError"}},ss=class extends H{constructor(t,o,r){super(t,"PAGE_ERROR",502,r);this.pageUrl=o;this.name="PageError"}pageUrl},is=class extends H{constructor(t,o,r){super(t,"TIMEOUT_ERROR",504,r);this.phase=o;this.name="TimeoutError"}phase}});var Yf,z,tt=g(()=>{"use strict";l();Yf={enabled:!1,alwaysLoadedTools:[],alwaysLoadedCategories:[],searchResultLimit:5,cacheDiscoveredTools:!0},z={enabled:!0,autoExecute:!0,maxToolRounds:5,toolChoicePolicy:"auto",resultMaxChars:2e4,enabledTools:[],enabledToolCategories:[],toolSearch:Yf}});import{appendFileSync as Vf}from"fs";import{join as Xf}from"path";function ls(s){if(!s)return;let e=s.toLowerCase();if(e in $r)return e;console.warn(`[Toolpack Warning] Invalid log level "${s}". Falling back to "info".`)}function cs(s){s?.enabled!==void 0&&(oo=s.enabled),s?.filePath&&(_r=s.filePath),s?.level&&(ro=ls(s.level)||"info"),process.env.TOOLPACK_SDK_LOG_ENABLED!==void 0&&(oo=process.env.TOOLPACK_SDK_LOG_ENABLED==="true"),process.env.TOOLPACK_SDK_LOG_FILE&&(_r=process.env.TOOLPACK_SDK_LOG_FILE,oo=!0),process.env.TOOLPACK_SDK_LOG_LEVEL&&(ro=ls(process.env.TOOLPACK_SDK_LOG_LEVEL)||ro)}function Re(s){return oo?$r[s]<=$r[ro]:!1}function ot(s,e){if(!Re(s))return;let o=`[${new Date().toISOString()}] [${s.toUpperCase()}] ${e}
2
- `;Vf(_r,o)}function Q(s){ot("error",s)}function D(s){ot("warn",s)}function v(s){ot("info",s)}function y(s){ot("debug",s)}function ye(s){ot("trace",s)}function Zf(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=Zf(t);return o.length<=e?o:`${o.slice(0,e)}\u2026`}catch{return"[Unserializable]"}}function V(s,e,t){Re("debug")&&(y(`[${e}][${s}] Messages (${t.length}):`),t.forEach((o,r)=>{y(`[${e}][${s}] #${r} role=${o?.role} content=${E(o?.content,300)}`)}))}var $r,oo,ro,_r,_=g(()=>{"use strict";l();$r={error:0,warn:1,info:2,debug:3,trace:4},oo=!1,ro="info",_r=Xf(process.cwd(),"toolpack-sdk.log")});var rt={};re(rt,{fetchUrlAsBase64:()=>Ps,getMimeType:()=>ws,isDataUri:()=>bs,normalizeImagePart:()=>ng,parseDataUri:()=>xs,readFileAsBase64:()=>Ts,toDataUri:()=>rg});import*as hs from"fs/promises";import*as ys from"path";function ws(s){let e=ys.extname(s).toLowerCase();return og[e]||"application/octet-stream"}function bs(s){return s.startsWith("data:")}function xs(s){let e=s.match(/^data:(.*?);base64,(.+)$/);return e?{mimeType:e[1],data:e[2]}:null}function rg(s,e){return`data:${e};base64,${s}`}async function Ts(s){try{return{data:(await hs.readFile(s)).toString("base64"),mimeType:ws(s)}}catch(e){throw new M(`Failed to read image file: ${s}`,e)}}async function Ps(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 F(`Failed to download image from URL: ${s}`,"FETCH_ERROR",500,e)}}async function ng(s){if(s.type==="image_data")return{data:s.image_data.data,mimeType:s.image_data.mimeType};if(s.type==="image_file")return await Ts(s.image_file.path);if(s.type==="image_url"){let e=s.image_url.url;if(bs(e)){let t=xs(e);if(!t)throw new M(`Malformed data URI provided in image_url: ${e.substring(0,50)}...`);return t}return await Ps(e)}throw new M(`Unknown ImagePart type: ${s.type}`)}var og,Le=g(()=>{"use strict";l();ce();og={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".heic":"image/heic",".heif":"image/heif"}});var _s,ks,Rs,Ds,Es,Ns=g(()=>{"use strict";l();_s="fs.read_file",ks="Read File",Rs="Read the contents of a file at the given path. Returns the file content as a string.",Ds="filesystem",Es={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"]}});import*as qe from"fs";async function ug(s){let e=s.path,t=s.encoding||"utf-8";if(y(`[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 at,Ar=g(()=>{"use strict";l();Ns();_();at={name:_s,displayName:ks,description:Rs,parameters:Es,category:Ds,execute:ug}});var As,Ms,Os,Is,js,Fs=g(()=>{"use strict";l();As="fs.write_file",Ms="Write File",Os="Write content to a file. Creates parent directories if they do not exist. Overwrites existing files.",Is="filesystem",js={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"]}});import*as Ue from"fs";import*as Ls from"path";async function fg(s){let e=s.path,t=s.content,o=s.encoding||"utf-8";if(y(`[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=Ls.dirname(e);return Ue.existsSync(r)||Ue.mkdirSync(r,{recursive:!0}),Ue.writeFileSync(e,t,o),`File written successfully: ${e} (${Buffer.byteLength(t,o)} bytes)`}var lt,Mr=g(()=>{"use strict";l();Fs();_();lt={name:As,displayName:Ms,description:Os,parameters:js,category:Is,execute:fg}});var qs,Us,Ws,Gs,Bs,Js=g(()=>{"use strict";l();qs="fs.append_file",Us="Append File",Ws="Append content to the end of a file. Creates the file if it does not exist.",Gs="filesystem",Bs={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"]}});import*as We from"fs";import*as Hs from"path";async function gg(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=Hs.dirname(e);return We.existsSync(r)||We.mkdirSync(r,{recursive:!0}),We.appendFileSync(e,t,o),`Content appended to: ${e} (${Buffer.byteLength(t,o)} bytes appended)`}var ct,Or=g(()=>{"use strict";l();Js();ct={name:qs,displayName:Us,description:Ws,parameters:Bs,category:Gs,execute:gg}});var zs,Ks,Qs,Ys,Vs,Xs=g(()=>{"use strict";l();zs="fs.delete_file",Ks="Delete File",Qs="Delete a file at the given path. Does not delete directories.",Ys="filesystem",Vs={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to delete"}},required:["path"]}});import*as Ge from"fs";async function hg(s){let e=s.path;if(y(`[fs.delete-file] execute path="${e}"`),!e)throw new Error("path is required");if(!Ge.existsSync(e))throw new Error(`File not found: ${e}`);if(Ge.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}. Use a different tool to remove directories.`);return Ge.unlinkSync(e),`File deleted successfully: ${e}`}var pt,Ir=g(()=>{"use strict";l();Xs();_();pt={name:zs,displayName:Ks,description:Qs,parameters:Vs,category:Ys,execute:hg}});var Zs,ei,ti,oi,ri,ni=g(()=>{"use strict";l();Zs="fs.exists",ei="Exists",ti="Check if a file or directory exists at the given path. Returns true or false.",oi="filesystem",ri={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to check"}},required:["path"]}});import*as si from"fs";async function yg(s){let e=s.path;if(!e)throw new Error("path is required");let t=si.existsSync(e);return JSON.stringify({exists:t,path:e})}var mt,jr=g(()=>{"use strict";l();ni();mt={name:Zs,displayName:ei,description:ti,parameters:ri,category:oi,execute:yg}});var ii,ai,li,ci,pi,mi=g(()=>{"use strict";l();ii="fs.stat",ai="Stat",li="Get file or directory information including size, type, and modification date.",ci="filesystem",pi={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to get info for"}},required:["path"]}});import*as mo from"fs";async function wg(s){let e=s.path;if(!e)throw new Error("path is required");if(!mo.existsSync(e))throw new Error(`Path not found: ${e}`);let t=mo.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 dt,Fr=g(()=>{"use strict";l();mi();dt={name:ii,displayName:ai,description:li,parameters:pi,category:ci,execute:wg}});var di,ui,fi,gi,hi,yi=g(()=>{"use strict";l();di="fs.list_dir",ui="List Directory",fi="List files and directories at the given path. Optionally recurse into subdirectories.",gi="filesystem",hi={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"]}});import*as Ee from"fs";import*as wi from"path";function bi(s,e,t,o=""){let r=Ee.readdirSync(s,{withFileTypes:!0});for(let n of r){let a=wi.join(s,n.name),i=o?`${o}/${n.name}`:n.name;if(n.isDirectory())t.push({name:i,type:"directory",size:0}),e&&bi(a,!0,t,i);else if(n.isFile()){let c=Ee.statSync(a);t.push({name:i,type:"file",size:c.size})}}}async function bg(s){let e=s.path,t=s.recursive===!0;if(!e)throw new Error("path is required");if(!Ee.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Ee.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let r=[];return bi(e,t,r),JSON.stringify(r,null,2)}var ut,Lr=g(()=>{"use strict";l();yi();ut={name:di,displayName:ui,description:fi,parameters:hi,category:gi,execute:bg}});var xi,Ti,Pi,Ci,vi,Si=g(()=>{"use strict";l();xi="fs.create_dir",Ti="Create Directory",Pi="Create a directory at the given path. Creates parent directories recursively if they do not exist.",Ci="filesystem",vi={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"]}});import*as Be from"fs";async function xg(s){let e=s.path,t=s.recursive!==!1;if(!e)throw new Error("path is required");if(Be.existsSync(e)){if(Be.statSync(e).isDirectory())return`Directory already exists: ${e}`;throw new Error(`Path exists but is not a directory: ${e}`)}return Be.mkdirSync(e,{recursive:t}),`Directory created: ${e}`}var ft,qr=g(()=>{"use strict";l();Si();ft={name:xi,displayName:Ti,description:Pi,parameters:vi,category:Ci,execute:xg}});var $i,_i,ki,Ri,Di,Ei=g(()=>{"use strict";l();$i="fs.move",_i="Move",ki="Move or rename a file or directory from one path to another.",Ri="filesystem",Di={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});import*as Ne from"fs";import*as Ni from"path";async function Tg(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(!Ne.existsSync(e))throw new Error(`Source not found: ${e}`);let o=Ni.dirname(t);return Ne.existsSync(o)||Ne.mkdirSync(o,{recursive:!0}),Ne.renameSync(e,t),`Moved: ${e} \u2192 ${t}`}var gt,Ur=g(()=>{"use strict";l();Ei();gt={name:$i,displayName:_i,description:ki,parameters:Di,category:Ri,execute:Tg}});var Ai,Mi,Oi,Ii,ji,Fi=g(()=>{"use strict";l();Ai="fs.copy",Mi="Copy",Oi="Copy a file or directory from one path to another. Recursively copies directories.",Ii="filesystem",ji={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});import*as K from"fs";import*as ht from"path";function Li(s,e){if(K.statSync(s).isDirectory()){K.existsSync(e)||K.mkdirSync(e,{recursive:!0});let o=K.readdirSync(s);for(let r of o)Li(ht.join(s,r),ht.join(e,r))}else K.copyFileSync(s,e)}async function Pg(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(!K.existsSync(e))throw new Error(`Source not found: ${e}`);let o=ht.dirname(t);return K.existsSync(o)||K.mkdirSync(o,{recursive:!0}),Li(e,t),`Copied ${K.statSync(e).isDirectory()?"directory":"file"}: ${e} \u2192 ${t}`}var yt,Wr=g(()=>{"use strict";l();Fi();yt={name:Ai,displayName:Mi,description:Oi,parameters:ji,category:Ii,execute:Pg}});var qi,Ui,Wi,Gi,Bi,Ji=g(()=>{"use strict";l();qi="fs.read_file_range",Ui="Read File Range",Wi="Read a specific range of lines from a file. Useful for reading portions of large files without loading the entire content.",Gi="filesystem",Bi={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"]}});import*as Je from"fs";async function Cg(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(!Je.existsSync(e))throw new Error(`File not found: ${e}`);if(Je.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let a=Je.readFileSync(e,"utf-8").split(`
3
- `),i=a.length,c=Math.min(t,i),p=Math.min(o,i),f=a.slice(c-1,p).map((h,x)=>`${c+x}: ${h}`).join(`
1
+ var Kf=Object.defineProperty;var g=(s,e)=>()=>(s&&(e=s(s=0)),e);var re=(s,e)=>{for(var t in e)Kf(s,t,{get:e[t],enumerable:!0})};import Qf from"path";import{fileURLToPath as Yf}from"url";var Vf,Xf,d,l=g(()=>{"use strict";Vf=()=>Yf(import.meta.url),Xf=()=>Qf.dirname(Vf()),d=Xf()});var H,ge,he,M,F,ke,as,ls,ce=g(()=>{"use strict";l();H=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},ge=class extends H{constructor(e,t){super(e,"AUTHENTICATION_ERROR",401,t),this.name="AuthenticationError"}},he=class extends H{constructor(t,r,o){super(t,"RATE_LIMIT_ERROR",429,o);this.retryAfter=r;this.name="RateLimitError"}retryAfter},M=class extends H{constructor(e,t){super(e,"INVALID_REQUEST_ERROR",400,t),this.name="InvalidRequestError"}},F=class extends H{constructor(e,t="PROVIDER_ERROR",r=500,o){super(e,t,r,o),this.name="ProviderError"}},ke=class extends H{constructor(e,t){super(e,"CONNECTION_ERROR",503,t),this.name="ConnectionError"}},as=class extends H{constructor(t,r,o){super(t,"PAGE_ERROR",502,o);this.pageUrl=r;this.name="PageError"}pageUrl},ls=class extends H{constructor(t,r,o){super(t,"TIMEOUT_ERROR",504,o);this.phase=r;this.name="TimeoutError"}phase}});var tg,z,rt=g(()=>{"use strict";l();tg={enabled:!1,alwaysLoadedTools:[],alwaysLoadedCategories:[],searchResultLimit:5,cacheDiscoveredTools:!0},z={enabled:!0,autoExecute:!0,maxToolRounds:5,toolChoicePolicy:"auto",resultMaxChars:2e4,enabledTools:[],enabledToolCategories:[],toolSearch:tg}});import{appendFileSync as og}from"fs";import{join as rg}from"path";function ps(s){if(!s)return;let e=s.toLowerCase();if(e in $r)return e;console.warn(`[Toolpack Warning] Invalid log level "${s}". Falling back to "info".`)}function ms(s){s?.enabled!==void 0&&(ro=s.enabled),s?.filePath&&(_r=s.filePath),s?.level&&(no=ps(s.level)||"info"),process.env.TOOLPACK_SDK_LOG_ENABLED!==void 0&&(ro=process.env.TOOLPACK_SDK_LOG_ENABLED==="true"),process.env.TOOLPACK_SDK_LOG_FILE&&(_r=process.env.TOOLPACK_SDK_LOG_FILE,ro=!0),process.env.TOOLPACK_SDK_LOG_LEVEL&&(no=ps(process.env.TOOLPACK_SDK_LOG_LEVEL)||no)}function Ee(s){return ro?$r[s]<=$r[no]:!1}function nt(s,e){if(!Ee(s))return;let r=`[${new Date().toISOString()}] [${s.toUpperCase()}] ${e}
2
+ `;og(_r,r)}function Q(s){nt("error",s)}function E(s){nt("warn",s)}function v(s){nt("info",s)}function y(s){nt("debug",s)}function ye(s){nt("trace",s)}function ng(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=ng(t);return r.length<=e?r:`${r.slice(0,e)}\u2026`}catch{return"[Unserializable]"}}function V(s,e,t){Ee("debug")&&(y(`[${e}][${s}] Messages (${t.length}):`),t.forEach((r,o)=>{y(`[${e}][${s}] #${o} role=${r?.role} content=${D(r?.content,300)}`)}))}var $r,ro,no,_r,k=g(()=>{"use strict";l();$r={error:0,warn:1,info:2,debug:3,trace:4},ro=!1,no="info",_r=rg(process.cwd(),"toolpack-sdk.log")});var st={};re(st,{fetchUrlAsBase64:()=>vs,getMimeType:()=>xs,isDataUri:()=>Ts,normalizeImagePart:()=>cg,parseDataUri:()=>Ps,readFileAsBase64:()=>Cs,toDataUri:()=>lg});import*as ws from"fs/promises";import*as bs from"path";function xs(s){let e=bs.extname(s).toLowerCase();return ag[e]||"application/octet-stream"}function Ts(s){return s.startsWith("data:")}function Ps(s){let e=s.match(/^data:(.*?);base64,(.+)$/);return e?{mimeType:e[1],data:e[2]}:null}function lg(s,e){return`data:${e};base64,${s}`}async function Cs(s){try{return{data:(await ws.readFile(s)).toString("base64"),mimeType:xs(s)}}catch(e){throw new M(`Failed to read image file: ${s}`,e)}}async function vs(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 F(`Failed to download image from URL: ${s}`,"FETCH_ERROR",500,e)}}async function cg(s){if(s.type==="image_data")return{data:s.image_data.data,mimeType:s.image_data.mimeType};if(s.type==="image_file")return await Cs(s.image_file.path);if(s.type==="image_url"){let e=s.image_url.url;if(Ts(e)){let t=Ps(e);if(!t)throw new M(`Malformed data URI provided in image_url: ${e.substring(0,50)}...`);return t}return await vs(e)}throw new M(`Unknown ImagePart type: ${s.type}`)}var ag,Ue=g(()=>{"use strict";l();ce();ag={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".heic":"image/heic",".heif":"image/heif"}});var Rs,Es,Ds,Ns,As,Ms=g(()=>{"use strict";l();Rs="fs.read_file",Es="Read File",Ds="Read the contents of a file at the given path. Returns the file content as a string.",Ns="filesystem",As={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"]}});import*as We from"fs";async function wg(s){let e=s.path,t=s.encoding||"utf-8";if(y(`[fs.read-file] execute path="${e}" encoding=${t}`),!e)throw new Error("path is required");if(!We.existsSync(e))throw new Error(`File not found: ${e}`);if(We.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);return We.readFileSync(e,t)}var ct,Ar=g(()=>{"use strict";l();Ms();k();ct={name:Rs,displayName:Es,description:Ds,parameters:As,category:Ns,execute:wg}});var Os,Is,js,Fs,Ls,qs=g(()=>{"use strict";l();Os="fs.write_file",Is="Write File",js="Write content to a file. Creates parent directories if they do not exist. Overwrites existing files.",Fs="filesystem",Ls={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"]}});import*as Ge from"fs";import*as Us from"path";async function bg(s){let e=s.path,t=s.content,r=s.encoding||"utf-8";if(y(`[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=Us.dirname(e);return Ge.existsSync(o)||Ge.mkdirSync(o,{recursive:!0}),Ge.writeFileSync(e,t,r),`File written successfully: ${e} (${Buffer.byteLength(t,r)} bytes)`}var pt,Mr=g(()=>{"use strict";l();qs();k();pt={name:Os,displayName:Is,description:js,parameters:Ls,category:Fs,execute:bg}});var Ws,Gs,Bs,Js,Hs,zs=g(()=>{"use strict";l();Ws="fs.append_file",Gs="Append File",Bs="Append content to the end of a file. Creates the file if it does not exist.",Js="filesystem",Hs={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"]}});import*as Be from"fs";import*as Ks from"path";async function xg(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=Ks.dirname(e);return Be.existsSync(o)||Be.mkdirSync(o,{recursive:!0}),Be.appendFileSync(e,t,r),`Content appended to: ${e} (${Buffer.byteLength(t,r)} bytes appended)`}var mt,Or=g(()=>{"use strict";l();zs();mt={name:Ws,displayName:Gs,description:Bs,parameters:Hs,category:Js,execute:xg}});var Qs,Ys,Vs,Xs,Zs,ei=g(()=>{"use strict";l();Qs="fs.delete_file",Ys="Delete File",Vs="Delete a file at the given path. Does not delete directories.",Xs="filesystem",Zs={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to delete"}},required:["path"]}});import*as Je from"fs";async function Tg(s){let e=s.path;if(y(`[fs.delete-file] execute path="${e}"`),!e)throw new Error("path is required");if(!Je.existsSync(e))throw new Error(`File not found: ${e}`);if(Je.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}. Use a different tool to remove directories.`);return Je.unlinkSync(e),`File deleted successfully: ${e}`}var dt,Ir=g(()=>{"use strict";l();ei();k();dt={name:Qs,displayName:Ys,description:Vs,parameters:Zs,category:Xs,execute:Tg}});var ti,oi,ri,ni,si,ii=g(()=>{"use strict";l();ti="fs.exists",oi="Exists",ri="Check if a file or directory exists at the given path. Returns true or false.",ni="filesystem",si={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to check"}},required:["path"]}});import*as ai from"fs";async function Pg(s){let e=s.path;if(!e)throw new Error("path is required");let t=ai.existsSync(e);return JSON.stringify({exists:t,path:e})}var ut,jr=g(()=>{"use strict";l();ii();ut={name:ti,displayName:oi,description:ri,parameters:si,category:ni,execute:Pg}});var li,ci,pi,mi,di,ui=g(()=>{"use strict";l();li="fs.stat",ci="Stat",pi="Get file or directory information including size, type, and modification date.",mi="filesystem",di={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to get info for"}},required:["path"]}});import*as mo from"fs";async function Cg(s){let e=s.path;if(!e)throw new Error("path is required");if(!mo.existsSync(e))throw new Error(`Path not found: ${e}`);let t=mo.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 ft,Fr=g(()=>{"use strict";l();ui();ft={name:li,displayName:ci,description:pi,parameters:di,category:mi,execute:Cg}});var fi,gi,hi,yi,wi,bi=g(()=>{"use strict";l();fi="fs.list_dir",gi="List Directory",hi="List files and directories at the given path. Optionally recurse into subdirectories.",yi="filesystem",wi={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"]}});import*as Ne from"fs";import*as xi from"path";function Ti(s,e,t,r=""){let o=Ne.readdirSync(s,{withFileTypes:!0});for(let n of o){let a=xi.join(s,n.name),i=r?`${r}/${n.name}`:n.name;if(n.isDirectory())t.push({name:i,type:"directory",size:0}),e&&Ti(a,!0,t,i);else if(n.isFile()){let c=Ne.statSync(a);t.push({name:i,type:"file",size:c.size})}}}async function vg(s){let e=s.path,t=s.recursive===!0;if(!e)throw new Error("path is required");if(!Ne.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Ne.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let o=[];return Ti(e,t,o),JSON.stringify(o,null,2)}var gt,Lr=g(()=>{"use strict";l();bi();gt={name:fi,displayName:gi,description:hi,parameters:wi,category:yi,execute:vg}});var Pi,Ci,vi,Si,$i,_i=g(()=>{"use strict";l();Pi="fs.create_dir",Ci="Create Directory",vi="Create a directory at the given path. Creates parent directories recursively if they do not exist.",Si="filesystem",$i={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"]}});import*as He from"fs";async function Sg(s){let e=s.path,t=s.recursive!==!1;if(!e)throw new Error("path is required");if(He.existsSync(e)){if(He.statSync(e).isDirectory())return`Directory already exists: ${e}`;throw new Error(`Path exists but is not a directory: ${e}`)}return He.mkdirSync(e,{recursive:t}),`Directory created: ${e}`}var ht,qr=g(()=>{"use strict";l();_i();ht={name:Pi,displayName:Ci,description:vi,parameters:$i,category:Si,execute:Sg}});var ki,Ri,Ei,Di,Ni,Ai=g(()=>{"use strict";l();ki="fs.move",Ri="Move",Ei="Move or rename a file or directory from one path to another.",Di="filesystem",Ni={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});import*as Ae from"fs";import*as Mi from"path";async function $g(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(!Ae.existsSync(e))throw new Error(`Source not found: ${e}`);let r=Mi.dirname(t);return Ae.existsSync(r)||Ae.mkdirSync(r,{recursive:!0}),Ae.renameSync(e,t),`Moved: ${e} \u2192 ${t}`}var yt,Ur=g(()=>{"use strict";l();Ai();yt={name:ki,displayName:Ri,description:Ei,parameters:Ni,category:Di,execute:$g}});var Oi,Ii,ji,Fi,Li,qi=g(()=>{"use strict";l();Oi="fs.copy",Ii="Copy",ji="Copy a file or directory from one path to another. Recursively copies directories.",Fi="filesystem",Li={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});import*as K from"fs";import*as wt from"path";function Ui(s,e){if(K.statSync(s).isDirectory()){K.existsSync(e)||K.mkdirSync(e,{recursive:!0});let r=K.readdirSync(s);for(let o of r)Ui(wt.join(s,o),wt.join(e,o))}else K.copyFileSync(s,e)}async function _g(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(!K.existsSync(e))throw new Error(`Source not found: ${e}`);let r=wt.dirname(t);return K.existsSync(r)||K.mkdirSync(r,{recursive:!0}),Ui(e,t),`Copied ${K.statSync(e).isDirectory()?"directory":"file"}: ${e} \u2192 ${t}`}var bt,Wr=g(()=>{"use strict";l();qi();bt={name:Oi,displayName:Ii,description:ji,parameters:Li,category:Fi,execute:_g}});var Wi,Gi,Bi,Ji,Hi,zi=g(()=>{"use strict";l();Wi="fs.read_file_range",Gi="Read File Range",Bi="Read a specific range of lines from a file. Useful for reading portions of large files without loading the entire content.",Ji="filesystem",Hi={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"]}});import*as ze from"fs";async function kg(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(!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}`);let a=ze.readFileSync(e,"utf-8").split(`
3
+ `),i=a.length,c=Math.min(t,i),p=Math.min(r,i),f=a.slice(c-1,p).map((h,b)=>`${c+b}: ${h}`).join(`
4
4
  `);return`Lines ${c}-${p} of ${i} total:
5
- ${f}`}var wt,Gr=g(()=>{"use strict";l();Ji();wt={name:qi,displayName:Ui,description:Wi,parameters:Bi,category:Gi,execute:Cg}});var Hi,zi,Ki,Qi,Yi,Vi=g(()=>{"use strict";l();Hi="fs.search",zi="Search",Ki="Search for text in files within a directory. Returns matching lines with file paths and line numbers.",Qi="filesystem",Yi={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"]}});import*as we from"fs";import*as Xi from"path";function vg(s,e,t,o){try{let n=we.readFileSync(s,"utf-8").split(`
6
- `);for(let a=0;a<n.length&&t.length<o;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 Zi(s,e,t,o,r){let n=we.readdirSync(s,{withFileTypes:!0});for(let a of n){if(o.length>=r)break;let i=Xi.join(s,a.name);a.isDirectory()&&t?Zi(i,e,!0,o,r):a.isFile()&&vg(i,e,o,r)}}async function Sg(s){let e=s.path,t=s.query,o=s.recursive!==!1,r=s.max_results||50,n=!!s.regex,a=!!s.case_sensitive;if(y(`[fs.search] execute path="${e}" query="${t}" recursive=${o} 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 f=t;n||(f=f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));let h=a?"":"i";i=new RegExp(f,h)}if(!we.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!we.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let p=[];if(Zi(e,i,o,p,r),p.length===0)return`No matches found for "${t}" in ${e}`;let m=p.length>=r?`
7
- (results capped at ${r})`:"";return JSON.stringify(p,null,2)+m}var bt,Br=g(()=>{"use strict";l();Vi();_();bt={name:Hi,displayName:zi,description:Ki,parameters:Yi,category:Qi,execute:Sg}});var ea,ta,oa,ra,na,sa=g(()=>{"use strict";l();ea="fs.replace_in_file",ta="Replace In File",oa="Find and replace text in a file. Returns the number of replacements made.",ra="filesystem",na={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"]}});import*as be from"fs";async function $g(s){let e=s.path,t=s.search,o=s.replace;if(!e)throw new Error("path is required");if(!t)throw new Error("search is required");if(o==null)throw new Error("replace is required");if(!be.existsSync(e))throw new Error(`File not found: ${e}`);if(be.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let n=be.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(o);return be.writeFileSync(e,c,"utf-8"),`Replaced ${a} occurrence(s) in ${e}`}var xt,Jr=g(()=>{"use strict";l();sa();xt={name:ea,displayName:ta,description:oa,parameters:na,category:ra,execute:$g}});var ia,aa,la,ca,pa,ma=g(()=>{"use strict";l();ia="fs.tree",aa="Tree",la="Get a tree representation of a directory structure. Useful for understanding project layout at a glance.",ca="filesystem",pa={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"]}});import*as He from"fs";import*as uo from"path";function da(s,e,t,o,r){if(t>o)return;let a=He.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 ",f=p?" ":"\u2502 ";c.isDirectory()?(r.push(`${e}${m}${c.name}/`),da(uo.join(s,c.name),e+f,t+1,o,r)):r.push(`${e}${m}${c.name}`)}}async function _g(s){let e=s.path,t=s.depth||3;if(!e)throw new Error("path is required");if(!He.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!He.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let n=[`${uo.basename(e)}/`];return da(e,"",1,t,n),n.join(`
8
- `)}var Tt,Hr=g(()=>{"use strict";l();ma();Tt={name:ia,displayName:aa,description:la,parameters:pa,category:ca,execute:_g}});var ua,fa,ga,ha,ya,wa=g(()=>{"use strict";l();ua="fs.glob",fa="Glob Pattern Match",ga='Find files matching glob patterns (e.g., "**/*.ts", "src/**/*.test.js")',ha="filesystem",ya={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"]}});import kg from"fast-glob";async function Rg(s){let e=s.pattern,t=s.cwd,o=s.ignore,r=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 kg(i,{cwd:t||process.cwd(),ignore:o||["node_modules/**",".git/**"],onlyFiles:r,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 fo,zr=g(()=>{"use strict";l();wa();fo={name:ua,displayName:fa,description:ga,parameters:ya,category:ha,execute:Rg}});var ba,xa,Ta,Pa,Ca,va=g(()=>{"use strict";l();ba="fs.delete_dir",xa="Delete Directory",Ta="Delete a directory and all its contents recursively",Pa="filesystem",Ca={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"]}});import{rm as Dg}from"fs/promises";import{existsSync as Eg,statSync as Ng}from"fs";async function Ag(s){let e=s.path,t=s.force!==!1;if(!e)throw new Error("path is required");if(!Eg(e))throw new Error(`Directory does not exist: ${e}`);if(!Ng(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);try{return await Dg(e,{recursive:!0,force:t}),`Directory deleted successfully: ${e}`}catch(r){throw new Error(`Failed to delete directory "${e}": ${r.message}`)}}var go,Kr=g(()=>{"use strict";l();va();go={name:ba,displayName:xa,description:Ta,parameters:Ca,category:Pa,execute:Ag}});var Sa,$a,_a,ka,Ra,Da=g(()=>{"use strict";l();Sa="fs.batch_read",$a="Batch Read Files",_a="Read multiple files efficiently in one operation. Returns content for each file or error if read fails.",ka="filesystem",Ra={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"]}});import{readFile as Mg}from"fs/promises";async function Og(s){let e=s.paths,t=s.encoding||"utf-8",o=s.continueOnError!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("paths array is required and must not be empty");let r=[],n=0,a=0;for(let i of e)try{let c=await Mg(i,t);r.push({path:i,content:c,success:!0}),n++}catch(c){let p=c.message;if(r.push({path:i,error:p,success:!1}),a++,!o)throw new Error(`Failed to read file "${i}": ${p}`)}return JSON.stringify({total:e.length,success:n,failed:a,results:r},null,2)}var ho,Qr=g(()=>{"use strict";l();Da();ho={name:Sa,displayName:$a,description:_a,parameters:Ra,category:ka,execute:Og}});var Ea,Na,Aa,Ma,Oa,Ia=g(()=>{"use strict";l();Ea="fs.batch_write",Na="Batch Write Files",Aa="Write multiple files atomically in one operation. If atomic mode is enabled, all writes succeed or all are rolled back on failure.",Ma="filesystem",Oa={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"]}});import{writeFile as ja,mkdir as Ig,readFile as jg,unlink as Fg}from"fs/promises";import{dirname as Lg,resolve as qg}from"path";import{existsSync as Fa}from"fs";async function Ug(s){let e=s.files,t=s.encoding||"utf-8",o=s.atomic!==!1,r=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=qg(i.path);if(o){let p=Fa(c),m={path:c,existed:p};p&&(m.originalContent=await jg(c,t)),n.push(m)}if(r){let p=Lg(c);await Ig(p,{recursive:!0})}await ja(c,i.content,t),a.push(c)}return JSON.stringify({success:!0,written:a.length,files:a},null,2)}catch(i){if(o&&n.length>0){for(let c of n)try{c.existed&&c.originalContent!==void 0?await ja(c.path,c.originalContent,t):!c.existed&&Fa(c.path)&&await Fg(c.path)}catch{}throw new Error(`Batch write failed and rolled back: ${i.message}`)}throw new Error(`Batch write failed: ${i.message}`)}}var yo,Yr=g(()=>{"use strict";l();Ia();yo={name:Ea,displayName:Na,description:Aa,parameters:Oa,category:Ma,execute:Ug}});var qa={};re(qa,{fsAppendFileTool:()=>ct,fsBatchReadTool:()=>ho,fsBatchWriteTool:()=>yo,fsCopyTool:()=>yt,fsCreateDirTool:()=>ft,fsDeleteDirTool:()=>go,fsDeleteFileTool:()=>pt,fsExistsTool:()=>mt,fsGlobTool:()=>fo,fsListDirTool:()=>ut,fsMoveTool:()=>gt,fsReadFileRangeTool:()=>wt,fsReadFileTool:()=>at,fsReplaceInFileTool:()=>xt,fsSearchTool:()=>bt,fsStatTool:()=>dt,fsToolsProject:()=>La,fsTreeTool:()=>Tt,fsWriteFileTool:()=>lt});var La,Vr=g(()=>{"use strict";l();Ar();Mr();Or();Ir();jr();Fr();Lr();qr();Ur();Wr();Gr();Br();Jr();Hr();zr();Kr();Qr();Yr();Ar();Mr();Or();Ir();jr();Fr();Lr();qr();Ur();Wr();Gr();Br();Jr();Hr();zr();Kr();Qr();Yr();La={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:[at,lt,ct,pt,mt,dt,ut,ft,gt,yt,wt,bt,xt,Tt,fo,go,ho,yo],dependencies:{"fast-glob":"^3.3.2"}}});var Ua,Wa,Ga,Ba,Ja,Ha=g(()=>{"use strict";l();Ua="exec.run",Wa="Run",Ga="Execute a command directly (without shell) and return its output. Use exec.run_shell for pipes, redirects, or shell features.",Ba="execution",Ja={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"]}});import{execSync as Wg}from"child_process";async function Gg(s){let e=s.command,t=s.cwd,o=s.timeout||3e4;if(!e)throw new Error("command is required");y(`[exec.run] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${o}ms`);try{return Wg(e,{cwd:t,timeout:o,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"]})||"(command completed with no output)"}catch(r){let n=r.stdout||"",a=r.stderr||"";return`Command failed (exit code ${r.status??"unknown"}):
5
+ ${f}`}var xt,Gr=g(()=>{"use strict";l();zi();xt={name:Wi,displayName:Gi,description:Bi,parameters:Hi,category:Ji,execute:kg}});var Ki,Qi,Yi,Vi,Xi,Zi=g(()=>{"use strict";l();Ki="fs.search",Qi="Search",Yi="Search for text in files within a directory. Returns matching lines with file paths and line numbers.",Vi="filesystem",Xi={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"]}});import*as we from"fs";import*as ea from"path";function Rg(s,e,t,r){try{let n=we.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 ta(s,e,t,r,o){let n=we.readdirSync(s,{withFileTypes:!0});for(let a of n){if(r.length>=o)break;let i=ea.join(s,a.name);a.isDirectory()&&t?ta(i,e,!0,r,o):a.isFile()&&Rg(i,e,r,o)}}async function Eg(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(y(`[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 f=t;n||(f=f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));let h=a?"":"i";i=new RegExp(f,h)}if(!we.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!we.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let p=[];if(ta(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 Tt,Br=g(()=>{"use strict";l();Zi();k();Tt={name:Ki,displayName:Qi,description:Yi,parameters:Xi,category:Vi,execute:Eg}});var oa,ra,na,sa,ia,aa=g(()=>{"use strict";l();oa="fs.replace_in_file",ra="Replace In File",na="Find and replace text in a file. Returns the number of replacements made.",sa="filesystem",ia={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"]}});import*as be from"fs";async function Dg(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(!be.existsSync(e))throw new Error(`File not found: ${e}`);if(be.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let n=be.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 be.writeFileSync(e,c,"utf-8"),`Replaced ${a} occurrence(s) in ${e}`}var Pt,Jr=g(()=>{"use strict";l();aa();Pt={name:oa,displayName:ra,description:na,parameters:ia,category:sa,execute:Dg}});var la,ca,pa,ma,da,ua=g(()=>{"use strict";l();la="fs.tree",ca="Tree",pa="Get a tree representation of a directory structure. Useful for understanding project layout at a glance.",ma="filesystem",da={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"]}});import*as Ke from"fs";import*as uo from"path";function fa(s,e,t,r,o){if(t>r)return;let a=Ke.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 ",f=p?" ":"\u2502 ";c.isDirectory()?(o.push(`${e}${m}${c.name}/`),fa(uo.join(s,c.name),e+f,t+1,r,o)):o.push(`${e}${m}${c.name}`)}}async function Ng(s){let e=s.path,t=s.depth||3;if(!e)throw new Error("path is required");if(!Ke.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Ke.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let n=[`${uo.basename(e)}/`];return fa(e,"",1,t,n),n.join(`
8
+ `)}var Ct,Hr=g(()=>{"use strict";l();ua();Ct={name:la,displayName:ca,description:pa,parameters:da,category:ma,execute:Ng}});var ga,ha,ya,wa,ba,xa=g(()=>{"use strict";l();ga="fs.glob",ha="Glob Pattern Match",ya='Find files matching glob patterns (e.g., "**/*.ts", "src/**/*.test.js")',wa="filesystem",ba={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"]}});import Ag from"fast-glob";async function Mg(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 Ag(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 fo,zr=g(()=>{"use strict";l();xa();fo={name:ga,displayName:ha,description:ya,parameters:ba,category:wa,execute:Mg}});var Ta,Pa,Ca,va,Sa,$a=g(()=>{"use strict";l();Ta="fs.delete_dir",Pa="Delete Directory",Ca="Delete a directory and all its contents recursively",va="filesystem",Sa={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"]}});import{rm as Og}from"fs/promises";import{existsSync as Ig,statSync as jg}from"fs";async function Fg(s){let e=s.path,t=s.force!==!1;if(!e)throw new Error("path is required");if(!Ig(e))throw new Error(`Directory does not exist: ${e}`);if(!jg(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);try{return await Og(e,{recursive:!0,force:t}),`Directory deleted successfully: ${e}`}catch(o){throw new Error(`Failed to delete directory "${e}": ${o.message}`)}}var go,Kr=g(()=>{"use strict";l();$a();go={name:Ta,displayName:Pa,description:Ca,parameters:Sa,category:va,execute:Fg}});var _a,ka,Ra,Ea,Da,Na=g(()=>{"use strict";l();_a="fs.batch_read",ka="Batch Read Files",Ra="Read multiple files efficiently in one operation. Returns content for each file or error if read fails.",Ea="filesystem",Da={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"]}});import{readFile as Lg}from"fs/promises";async function qg(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 Lg(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 ho,Qr=g(()=>{"use strict";l();Na();ho={name:_a,displayName:ka,description:Ra,parameters:Da,category:Ea,execute:qg}});var Aa,Ma,Oa,Ia,ja,Fa=g(()=>{"use strict";l();Aa="fs.batch_write",Ma="Batch Write Files",Oa="Write multiple files atomically in one operation. If atomic mode is enabled, all writes succeed or all are rolled back on failure.",Ia="filesystem",ja={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"]}});import{writeFile as La,mkdir as Ug,readFile as Wg,unlink as Gg}from"fs/promises";import{dirname as Bg,resolve as Jg}from"path";import{existsSync as qa}from"fs";async function Hg(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=Jg(i.path);if(r){let p=qa(c),m={path:c,existed:p};p&&(m.originalContent=await Wg(c,t)),n.push(m)}if(o){let p=Bg(c);await Ug(p,{recursive:!0})}await La(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 La(c.path,c.originalContent,t):!c.existed&&qa(c.path)&&await Gg(c.path)}catch{}throw new Error(`Batch write failed and rolled back: ${i.message}`)}throw new Error(`Batch write failed: ${i.message}`)}}var yo,Yr=g(()=>{"use strict";l();Fa();yo={name:Aa,displayName:Ma,description:Oa,parameters:ja,category:Ia,execute:Hg}});var Wa={};re(Wa,{fsAppendFileTool:()=>mt,fsBatchReadTool:()=>ho,fsBatchWriteTool:()=>yo,fsCopyTool:()=>bt,fsCreateDirTool:()=>ht,fsDeleteDirTool:()=>go,fsDeleteFileTool:()=>dt,fsExistsTool:()=>ut,fsGlobTool:()=>fo,fsListDirTool:()=>gt,fsMoveTool:()=>yt,fsReadFileRangeTool:()=>xt,fsReadFileTool:()=>ct,fsReplaceInFileTool:()=>Pt,fsSearchTool:()=>Tt,fsStatTool:()=>ft,fsToolsProject:()=>Ua,fsTreeTool:()=>Ct,fsWriteFileTool:()=>pt});var Ua,Vr=g(()=>{"use strict";l();Ar();Mr();Or();Ir();jr();Fr();Lr();qr();Ur();Wr();Gr();Br();Jr();Hr();zr();Kr();Qr();Yr();Ar();Mr();Or();Ir();jr();Fr();Lr();qr();Ur();Wr();Gr();Br();Jr();Hr();zr();Kr();Qr();Yr();Ua={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:[ct,pt,mt,dt,ut,ft,gt,ht,yt,bt,xt,Tt,Pt,Ct,fo,go,ho,yo],dependencies:{"fast-glob":"^3.3.2"}}});var Ga,Ba,Ja,Ha,za,Ka=g(()=>{"use strict";l();Ga="exec.run",Ba="Run",Ja="Execute a command directly (without shell) and return its output. Use exec.run_shell for pipes, redirects, or shell features.",Ha="execution",za={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"]}});import{execSync as zg}from"child_process";async function Kg(s){let e=s.command,t=s.cwd,r=s.timeout||3e4;if(!e)throw new Error("command is required");y(`[exec.run] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${r}ms`);try{return zg(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 Pt,Xr=g(()=>{"use strict";l();Ha();_();Pt={name:Ua,displayName:Wa,description:Ga,parameters:Ja,category:Ba,execute:Gg}});var za,Ka,Qa,Ya,Va,Xa=g(()=>{"use strict";l();za="exec.run_shell",Ka="Run Shell",Qa="Execute a command through the system shell. Supports pipes, redirects, environment variable expansion, and other shell features.",Ya="execution",Va={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"]}});import{execSync as Bg}from"child_process";function Jg(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function Hg(s){let e=s.command,t=s.cwd,o=s.timeout||3e4;if(!e)throw new Error("command is required");y(`[exec.run-shell] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${o}ms`);try{return Bg(e,{cwd:t,timeout:o,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],shell:Jg()})||"(command completed with no output)"}catch(r){let n=r.stdout||"",a=r.stderr||"";return`Command failed (exit code ${r.status??"unknown"}):
12
+ ${a}`}}var vt,Xr=g(()=>{"use strict";l();Ka();k();vt={name:Ga,displayName:Ba,description:Ja,parameters:za,category:Ha,execute:Kg}});var Qa,Ya,Va,Xa,Za,el=g(()=>{"use strict";l();Qa="exec.run_shell",Ya="Run Shell",Va="Execute a command through the system shell. Supports pipes, redirects, environment variable expansion, and other shell features.",Xa="execution",Za={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"]}});import{execSync as Qg}from"child_process";function Yg(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function Vg(s){let e=s.command,t=s.cwd,r=s.timeout||3e4;if(!e)throw new Error("command is required");y(`[exec.run-shell] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${r}ms`);try{return Qg(e,{cwd:t,timeout:r,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],shell:Yg()})||"(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 Ct,Zr=g(()=>{"use strict";l();Xa();_();Ct={name:za,displayName:Ka,description:Qa,parameters:Va,category:Ya,execute:Hg}});function Za(s,e,t){let o=`proc_${zg++}`,r={id:o,command:s,cwd:e,process:t,startedAt:new Date().toISOString(),stdout:"",stderr:""};return t.stdout?.on("data",n=>{r.stdout+=n.toString(),r.stdout.length>1e6&&(r.stdout=r.stdout.slice(-5e5))}),t.stderr?.on("data",n=>{r.stderr+=n.toString(),r.stderr.length>1e6&&(r.stderr=r.stderr.slice(-5e5))}),t.on("exit",()=>{}),wo.set(o,r),o}function bo(s){return wo.get(s)}function el(s){let e=wo.get(s);if(!e)return!1;let t=e.process.exitCode===null;return t&&e.process.kill("SIGTERM"),t}function tl(){return Array.from(wo.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 wo,zg,vt=g(()=>{"use strict";l();wo=new Map,zg=1});var ol,rl,nl,sl,il,al=g(()=>{"use strict";l();ol="exec.run_background",rl="Run Background",nl="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.",sl="execution",il={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"]}});import{spawn as Kg}from"child_process";async function Qg(s){let e=s.command,t=s.cwd;if(!e)throw new Error("command is required");if(y(`[exec.run-background] execute command="${e.substring(0,100)}" cwd=${t??"default"}`),!e)throw new Error("command is required");let o=Kg(e,[],{cwd:t,shell:!0,stdio:["ignore","pipe","pipe"],detached:!1}),r=Za(e,t,o);return JSON.stringify({id:r,pid:o.pid,command:e,message:`Background process started. Use exec.read_output("${r}") to read output, exec.kill("${r}") to stop.`})}var St,en=g(()=>{"use strict";l();vt();al();_();St={name:ol,displayName:rl,description:nl,parameters:il,category:sl,execute:Qg}});var ll,cl,pl,ml,dl,ul=g(()=>{"use strict";l();ll="exec.read_output",cl="Read Output",pl="Read stdout and stderr from a background process started with exec.run_background.",ml="execution",dl={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function Yg(s){let e=s.process_id;if(!e)throw new Error("process_id is required");let t=bo(e);if(!t)throw new Error(`Process not found: ${e}`);let o=t.process.exitCode===null;return JSON.stringify({id:t.id,alive:o,exitCode:t.process.exitCode,stdout:t.stdout,stderr:t.stderr})}var $t,tn=g(()=>{"use strict";l();vt();ul();$t={name:ll,displayName:cl,description:pl,parameters:dl,category:ml,execute:Yg}});var fl,gl,hl,yl,wl,bl=g(()=>{"use strict";l();fl="exec.kill",gl="Kill",hl="Kill a background process started with exec.run_background.",yl="execution",wl={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function Vg(s){let e=s.process_id;if(!e)throw new Error("process_id is required");let t=bo(e);if(!t)throw new Error(`Process not found: ${e}`);return el(e)?`Process ${e} (${t.command}) killed successfully.`:`Process ${e} (${t.command}) was already terminated (exit code: ${t.process.exitCode}).`}var _t,on=g(()=>{"use strict";l();vt();bl();_t={name:fl,displayName:gl,description:hl,parameters:wl,category:yl,execute:Vg}});var xl,Tl,Pl,Cl,vl,Sl=g(()=>{"use strict";l();xl="exec.list_processes",Tl="List Processes",Pl="List all managed background processes started with exec.run_background, including their status.",Cl="execution",vl={type:"object",properties:{}}});async function Xg(s){let e=tl();return e.length===0?"No managed background processes.":JSON.stringify(e,null,2)}var kt,rn=g(()=>{"use strict";l();vt();Sl();kt={name:xl,displayName:Tl,description:Pl,parameters:vl,category:Cl,execute:Xg}});var _l={};re(_l,{execKillTool:()=>_t,execListProcessesTool:()=>kt,execReadOutputTool:()=>$t,execRunBackgroundTool:()=>St,execRunShellTool:()=>Ct,execRunTool:()=>Pt,execToolsProject:()=>$l});var $l,nn=g(()=>{"use strict";l();Xr();Zr();en();tn();on();rn();Xr();Zr();en();tn();on();rn();$l={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:[Pt,Ct,St,$t,_t,kt],dependencies:{}}});var kl,Rl,Dl,El,Nl,Al=g(()=>{"use strict";l();kl="system.info",Rl="Info",Dl="Get system information including OS, CPU, memory, and architecture.",El="system",Nl={type:"object",properties:{}}});import*as N from"os";async function Zg(s){return y("[system.info] execute"),JSON.stringify({platform:N.platform(),arch:N.arch(),release:N.release(),hostname:N.hostname(),uptime:N.uptime(),cpus:{model:N.cpus()[0]?.model||"unknown",count:N.cpus().length},memory:{total:N.totalmem(),free:N.freemem(),used:N.totalmem()-N.freemem()},homedir:N.homedir(),tmpdir:N.tmpdir(),nodeVersion:process.version},null,2)}var Rt,sn=g(()=>{"use strict";l();Al();_();Rt={name:kl,displayName:Rl,description:Dl,parameters:Nl,category:El,execute:Zg}});var Ml,Ol,Il,jl,Fl,Ll=g(()=>{"use strict";l();Ml="system.env",Ol="Environment",Il="Get environment variable(s). If key is provided, returns that specific variable. Otherwise returns all environment variables.",jl="system",Fl={type:"object",properties:{key:{type:"string",description:"Specific environment variable name to get (optional, returns all if omitted)"}}}});async function eh(s){let e=s.key;if(y(`[system.env] execute key=${e??"all"}`),e){let r=process.env[e];return r===void 0?`Environment variable "${e}" is not set.`:JSON.stringify({[e]:r})}let t={},o=Object.keys(process.env).sort();for(let r of o)process.env[r]!==void 0&&(t[r]=process.env[r]);return JSON.stringify(t,null,2)}var Dt,an=g(()=>{"use strict";l();Ll();_();Dt={name:Ml,displayName:Ol,description:Il,parameters:Fl,category:jl,execute:eh}});var ql,Ul,Wl,Gl,Bl,Jl=g(()=>{"use strict";l();ql="system.set_env",Ul="Set Environment",Wl="Set an environment variable for the current session. Does not persist across restarts.",Gl="system",Bl={type:"object",properties:{key:{type:"string",description:"Environment variable name"},value:{type:"string",description:"Value to set"}},required:["key","value"]}});async function th(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 o=process.env[e];return process.env[e]=t,o!==void 0?`Environment variable "${e}" updated (was: "${o}", now: "${t}")`:`Environment variable "${e}" set to "${t}"`}var Et,ln=g(()=>{"use strict";l();Jl();Et={name:ql,displayName:Ul,description:Wl,parameters:Bl,category:Gl,execute:th}});var Hl,zl,Kl,Ql,Yl,Vl=g(()=>{"use strict";l();Hl="system.cwd",zl="Current Directory",Kl="Get the current working directory of the process.",Ql="system",Yl={type:"object",properties:{}}});async function oh(s){return y("[system.cwd] execute"),JSON.stringify({cwd:process.cwd()})}var Nt,cn=g(()=>{"use strict";l();Vl();_();Nt={name:Hl,displayName:zl,description:Kl,parameters:Yl,category:Ql,execute:oh}});var Xl,Zl,ec,tc,oc,rc=g(()=>{"use strict";l();Xl="system.disk_usage",Zl="Disk Usage",ec="Get disk usage information for a given path or the root filesystem.",tc="system",oc={type:"object",properties:{path:{type:"string",description:"Path to check disk usage for (default: /)",default:"/"}}}});import*as sc from"fs";import*as ic from"os";import*as xo from"path";import{execSync as nc}from"child_process";function pn(s){let e=["B","KB","MB","GB","TB","PB"],t=s,o=0;for(;t>=1024&&o<e.length-1;)t/=1024,o++;return`${t.toFixed(1)}${e[o]}`}async function rh(s){let t=s.path||(process.platform==="win32"?ic.tmpdir():"/");t=xo.resolve(t);let o=process.platform==="win32";try{let r=sc.statfsSync(t),n=BigInt(r.blocks)*BigInt(r.bsize),a=BigInt(r.bavail)*BigInt(r.bsize),i=BigInt(r.bfree)*BigInt(r.bsize),c=n-i,p=n>0?Number(c*BigInt(100)/n):0;return JSON.stringify({path:t,filesystem:"statfs",size:pn(Number(n)),used:pn(Number(c)),available:pn(Number(a)),usePercent:`${p}%`,mountedOn:t},null,2)}catch(r){try{if(o){let c=xo.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=nc(p,{encoding:"utf-8",timeout:5e3,shell:"powershell.exe"}),f=JSON.parse(m.trim()),h=f.Total||0,x=f.Free||0,w=f.Used||0,b=h>0?Math.round(w/h*100):0;return JSON.stringify({path:t,filesystem:f.Name||"NTFS",size:`${(h/1024**3).toFixed(1)}G`,used:`${(w/1024**3).toFixed(1)}G`,available:`${(x/1024**3).toFixed(1)}G`,usePercent:`${b}%`,mountedOn:f.Drive||`${c}`},null,2)}let n=nc(`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}: ${r?.message||r}; fallback error: ${n.message}`)}}}var At,mn=g(()=>{"use strict";l();rc();At={name:Xl,displayName:Zl,description:ec,parameters:oc,category:tc,execute:rh}});var lc={};re(lc,{systemCwdTool:()=>Nt,systemDiskUsageTool:()=>At,systemEnvTool:()=>Dt,systemInfoTool:()=>Rt,systemSetEnvTool:()=>Et,systemToolsProject:()=>ac});var ac,dn=g(()=>{"use strict";l();sn();an();ln();cn();mn();sn();an();ln();cn();mn();ac={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:[Rt,Dt,Et,Nt,At],dependencies:{}}});var cc,pc,mc,dc,uc,fc=g(()=>{"use strict";l();cc="http.get",pc="GET",mc="Make an HTTP GET request to a URL and return the response body.",dc="network",uc={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 nh(s){let e=s.url,t=s.headers;if(y(`[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 o=await fetch(e,{method:"GET",headers:t||{}}),r=await o.text(),n=`HTTP ${o.status} ${o.statusText}`;return o.ok?r.length>gc?`${n}
18
- ${r.substring(0,gc)}
16
+ ${a}`}}var St,Zr=g(()=>{"use strict";l();el();k();St={name:Qa,displayName:Ya,description:Va,parameters:Za,category:Xa,execute:Vg}});function tl(s,e,t){let r=`proc_${Xg++}`,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",()=>{}),wo.set(r,o),r}function bo(s){return wo.get(s)}function ol(s){let e=wo.get(s);if(!e)return!1;let t=e.process.exitCode===null;return t&&e.process.kill("SIGTERM"),t}function rl(){return Array.from(wo.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 wo,Xg,$t=g(()=>{"use strict";l();wo=new Map,Xg=1});var nl,sl,il,al,ll,cl=g(()=>{"use strict";l();nl="exec.run_background",sl="Run Background",il="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.",al="execution",ll={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"]}});import{spawn as Zg}from"child_process";async function eh(s){let e=s.command,t=s.cwd;if(!e)throw new Error("command is required");if(y(`[exec.run-background] execute command="${e.substring(0,100)}" cwd=${t??"default"}`),!e)throw new Error("command is required");let r=Zg(e,[],{cwd:t,shell:!0,stdio:["ignore","pipe","pipe"],detached:!1}),o=tl(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 _t,en=g(()=>{"use strict";l();$t();cl();k();_t={name:nl,displayName:sl,description:il,parameters:ll,category:al,execute:eh}});var pl,ml,dl,ul,fl,gl=g(()=>{"use strict";l();pl="exec.read_output",ml="Read Output",dl="Read stdout and stderr from a background process started with exec.run_background.",ul="execution",fl={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function th(s){let e=s.process_id;if(!e)throw new Error("process_id is required");let t=bo(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 kt,tn=g(()=>{"use strict";l();$t();gl();kt={name:pl,displayName:ml,description:dl,parameters:fl,category:ul,execute:th}});var hl,yl,wl,bl,xl,Tl=g(()=>{"use strict";l();hl="exec.kill",yl="Kill",wl="Kill a background process started with exec.run_background.",bl="execution",xl={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function oh(s){let e=s.process_id;if(!e)throw new Error("process_id is required");let t=bo(e);if(!t)throw new Error(`Process not found: ${e}`);return ol(e)?`Process ${e} (${t.command}) killed successfully.`:`Process ${e} (${t.command}) was already terminated (exit code: ${t.process.exitCode}).`}var Rt,on=g(()=>{"use strict";l();$t();Tl();Rt={name:hl,displayName:yl,description:wl,parameters:xl,category:bl,execute:oh}});var Pl,Cl,vl,Sl,$l,_l=g(()=>{"use strict";l();Pl="exec.list_processes",Cl="List Processes",vl="List all managed background processes started with exec.run_background, including their status.",Sl="execution",$l={type:"object",properties:{}}});async function rh(s){let e=rl();return e.length===0?"No managed background processes.":JSON.stringify(e,null,2)}var Et,rn=g(()=>{"use strict";l();$t();_l();Et={name:Pl,displayName:Cl,description:vl,parameters:$l,category:Sl,execute:rh}});var Rl={};re(Rl,{execKillTool:()=>Rt,execListProcessesTool:()=>Et,execReadOutputTool:()=>kt,execRunBackgroundTool:()=>_t,execRunShellTool:()=>St,execRunTool:()=>vt,execToolsProject:()=>kl});var kl,nn=g(()=>{"use strict";l();Xr();Zr();en();tn();on();rn();Xr();Zr();en();tn();on();rn();kl={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:[vt,St,_t,kt,Rt,Et],dependencies:{}}});var El,Dl,Nl,Al,Ml,Ol=g(()=>{"use strict";l();El="system.info",Dl="Info",Nl="Get system information including OS, CPU, memory, and architecture.",Al="system",Ml={type:"object",properties:{}}});import*as N from"os";async function nh(s){return y("[system.info] execute"),JSON.stringify({platform:N.platform(),arch:N.arch(),release:N.release(),hostname:N.hostname(),uptime:N.uptime(),cpus:{model:N.cpus()[0]?.model||"unknown",count:N.cpus().length},memory:{total:N.totalmem(),free:N.freemem(),used:N.totalmem()-N.freemem()},homedir:N.homedir(),tmpdir:N.tmpdir(),nodeVersion:process.version},null,2)}var Dt,sn=g(()=>{"use strict";l();Ol();k();Dt={name:El,displayName:Dl,description:Nl,parameters:Ml,category:Al,execute:nh}});var Il,jl,Fl,Ll,ql,Ul=g(()=>{"use strict";l();Il="system.env",jl="Environment",Fl="Get environment variable(s). If key is provided, returns that specific variable. Otherwise returns all environment variables.",Ll="system",ql={type:"object",properties:{key:{type:"string",description:"Specific environment variable name to get (optional, returns all if omitted)"}}}});async function sh(s){let e=s.key;if(y(`[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 Nt,an=g(()=>{"use strict";l();Ul();k();Nt={name:Il,displayName:jl,description:Fl,parameters:ql,category:Ll,execute:sh}});var Wl,Gl,Bl,Jl,Hl,zl=g(()=>{"use strict";l();Wl="system.set_env",Gl="Set Environment",Bl="Set an environment variable for the current session. Does not persist across restarts.",Jl="system",Hl={type:"object",properties:{key:{type:"string",description:"Environment variable name"},value:{type:"string",description:"Value to set"}},required:["key","value"]}});async function ih(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 At,ln=g(()=>{"use strict";l();zl();At={name:Wl,displayName:Gl,description:Bl,parameters:Hl,category:Jl,execute:ih}});var Kl,Ql,Yl,Vl,Xl,Zl=g(()=>{"use strict";l();Kl="system.cwd",Ql="Current Directory",Yl="Get the current working directory of the process.",Vl="system",Xl={type:"object",properties:{}}});async function ah(s){return y("[system.cwd] execute"),JSON.stringify({cwd:process.cwd()})}var Mt,cn=g(()=>{"use strict";l();Zl();k();Mt={name:Kl,displayName:Ql,description:Yl,parameters:Xl,category:Vl,execute:ah}});var ec,tc,oc,rc,nc,sc=g(()=>{"use strict";l();ec="system.disk_usage",tc="Disk Usage",oc="Get disk usage information for a given path or the root filesystem.",rc="system",nc={type:"object",properties:{path:{type:"string",description:"Path to check disk usage for (default: /)",default:"/"}}}});import*as ac from"fs";import*as lc from"os";import*as xo from"path";import{execSync as ic}from"child_process";function pn(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 lh(s){let t=s.path||(process.platform==="win32"?lc.tmpdir():"/");t=xo.resolve(t);let r=process.platform==="win32";try{let o=ac.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:pn(Number(n)),used:pn(Number(c)),available:pn(Number(a)),usePercent:`${p}%`,mountedOn:t},null,2)}catch(o){try{if(r){let c=xo.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=ic(p,{encoding:"utf-8",timeout:5e3,shell:"powershell.exe"}),f=JSON.parse(m.trim()),h=f.Total||0,b=f.Free||0,w=f.Used||0,x=h>0?Math.round(w/h*100):0;return JSON.stringify({path:t,filesystem:f.Name||"NTFS",size:`${(h/1024**3).toFixed(1)}G`,used:`${(w/1024**3).toFixed(1)}G`,available:`${(b/1024**3).toFixed(1)}G`,usePercent:`${x}%`,mountedOn:f.Drive||`${c}`},null,2)}let n=ic(`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 Ot,mn=g(()=>{"use strict";l();sc();Ot={name:ec,displayName:tc,description:oc,parameters:nc,category:rc,execute:lh}});var pc={};re(pc,{systemCwdTool:()=>Mt,systemDiskUsageTool:()=>Ot,systemEnvTool:()=>Nt,systemInfoTool:()=>Dt,systemSetEnvTool:()=>At,systemToolsProject:()=>cc});var cc,dn=g(()=>{"use strict";l();sn();an();ln();cn();mn();sn();an();ln();cn();mn();cc={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:[Dt,Nt,At,Mt,Ot],dependencies:{}}});var mc,dc,uc,fc,gc,hc=g(()=>{"use strict";l();mc="http.get",dc="GET",uc="Make an HTTP GET request to a URL and return the response body.",fc="network",gc={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 ch(s){let e=s.url,t=s.headers;if(y(`[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>yc?`${n}
18
+ ${o.substring(0,yc)}
19
19
 
20
- ... (truncated, total ${r.length} characters)`:`${n}
21
- ${r}`:`${n}
22
- ${r}`}var gc,Mt,un=g(()=>{"use strict";l();fc();_();gc=1e5;Mt={name:cc,displayName:pc,description:mc,parameters:uc,category:dc,execute:nh}});var hc,yc,wc,bc,xc,Tc=g(()=>{"use strict";l();hc="http.post",yc="POST",wc="Make an HTTP POST request to a URL with an optional body and return the response.",bc="network",xc={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 sh(s){let e=s.url,t=s.body,o=s.headers||{};if(y(`[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&&!o["Content-Type"]&&!o["content-type"])try{JSON.parse(t),o["Content-Type"]="application/json"}catch{o["Content-Type"]="text/plain"}let r=await fetch(e,{method:"POST",headers:o,body:t||void 0}),n=await r.text(),a=`HTTP ${r.status} ${r.statusText}`;return n.length>Pc?`${a}
23
- ${n.substring(0,Pc)}
20
+ ... (truncated, total ${o.length} characters)`:`${n}
21
+ ${o}`:`${n}
22
+ ${o}`}var yc,It,un=g(()=>{"use strict";l();hc();k();yc=1e5;It={name:mc,displayName:dc,description:uc,parameters:gc,category:fc,execute:ch}});var wc,bc,xc,Tc,Pc,Cc=g(()=>{"use strict";l();wc="http.post",bc="POST",xc="Make an HTTP POST request to a URL with an optional body and return the response.",Tc="network",Pc={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 ph(s){let e=s.url,t=s.body,r=s.headers||{};if(y(`[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>vc?`${a}
23
+ ${n.substring(0,vc)}
24
24
 
25
25
  ... (truncated, total ${n.length} characters)`:`${a}
26
- ${n}`}var Pc,Ot,fn=g(()=>{"use strict";l();Tc();_();Pc=1e5;Ot={name:hc,displayName:yc,description:wc,parameters:xc,category:bc,execute:sh}});var Cc,vc,Sc,$c,_c,kc=g(()=>{"use strict";l();Cc="http.put",vc="PUT",Sc="Make an HTTP PUT request to a URL with an optional body and return the response.",$c="network",_c={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 ih(s){let e=s.url,t=s.body,o=s.headers||{};if(y(`[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&&!o["Content-Type"]&&!o["content-type"])try{JSON.parse(t),o["Content-Type"]="application/json"}catch{o["Content-Type"]="text/plain"}let r=await fetch(e,{method:"PUT",headers:o,body:t||void 0}),n=await r.text(),a=`HTTP ${r.status} ${r.statusText}`;return n.length>Rc?`${a}
27
- ${n.substring(0,Rc)}
26
+ ${n}`}var vc,jt,fn=g(()=>{"use strict";l();Cc();k();vc=1e5;jt={name:wc,displayName:bc,description:xc,parameters:Pc,category:Tc,execute:ph}});var Sc,$c,_c,kc,Rc,Ec=g(()=>{"use strict";l();Sc="http.put",$c="PUT",_c="Make an HTTP PUT request to a URL with an optional body and return the response.",kc="network",Rc={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 mh(s){let e=s.url,t=s.body,r=s.headers||{};if(y(`[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>Dc?`${a}
27
+ ${n.substring(0,Dc)}
28
28
 
29
29
  ... (truncated)`:`${a}
30
- ${n}`}var Rc,It,gn=g(()=>{"use strict";l();kc();_();Rc=1e5;It={name:Cc,displayName:vc,description:Sc,parameters:_c,category:$c,execute:ih}});var Dc,Ec,Nc,Ac,Mc,Oc=g(()=>{"use strict";l();Dc="http.delete",Ec="DELETE",Nc="Make an HTTP DELETE request to a URL and return the response.",Ac="network",Mc={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 ah(s){let e=s.url,t=s.headers;if(y(`[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 o=await fetch(e,{method:"DELETE",headers:t||{}}),r=await o.text(),n=`HTTP ${o.status} ${o.statusText}`;return r.length>Ic?`${n}
31
- ${r.substring(0,Ic)}
30
+ ${n}`}var Dc,Ft,gn=g(()=>{"use strict";l();Ec();k();Dc=1e5;Ft={name:Sc,displayName:$c,description:_c,parameters:Rc,category:kc,execute:mh}});var Nc,Ac,Mc,Oc,Ic,jc=g(()=>{"use strict";l();Nc="http.delete",Ac="DELETE",Mc="Make an HTTP DELETE request to a URL and return the response.",Oc="network",Ic={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 dh(s){let e=s.url,t=s.headers;if(y(`[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>Fc?`${n}
31
+ ${o.substring(0,Fc)}
32
32
 
33
33
  ... (truncated)`:`${n}
34
- ${r}`}var Ic,jt,hn=g(()=>{"use strict";l();Oc();_();Ic=1e5;jt={name:Dc,displayName:Ec,description:Nc,parameters:Mc,category:Ac,execute:ah}});var jc,Fc,Lc,qc,Uc,Wc=g(()=>{"use strict";l();jc="http.download",Fc="Download",Lc="Download a file from a URL and save it to a local path.",qc="network",Uc={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"]}});import*as ze from"fs";import*as Gc from"path";async function lh(s){let e=s.url,t=s.path,o=s.headers;if(y(`[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 r=await fetch(e,{method:"GET",headers:o||{}});if(!r.ok)throw new Error(`Download failed: HTTP ${r.status} ${r.statusText}`);let n=Buffer.from(await r.arrayBuffer()),a=Gc.dirname(t);return ze.existsSync(a)||ze.mkdirSync(a,{recursive:!0}),ze.writeFileSync(t,n),`Downloaded ${e} \u2192 ${t} (${n.length} bytes)`}var Ft,yn=g(()=>{"use strict";l();Wc();_();Ft={name:jc,displayName:Fc,description:Lc,parameters:Uc,category:qc,execute:lh}});var Jc={};re(Jc,{httpDeleteTool:()=>jt,httpDownloadTool:()=>Ft,httpGetTool:()=>Mt,httpPostTool:()=>Ot,httpPutTool:()=>It,httpToolsProject:()=>Bc});var Bc,wn=g(()=>{"use strict";l();un();fn();gn();hn();yn();un();fn();gn();hn();yn();Bc={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:[Mt,Ot,It,jt,Ft],dependencies:{}}});var Hc,zc,Kc,Qc,Yc,Vc=g(()=>{"use strict";l();Hc="web.fetch",zc="Fetch",Kc="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).",Qc="network",Yc={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"]}});import*as bn from"cheerio";function Xc(s,e){let t=bn.load(s);t("script, style, nav, header, footer, aside, .advertisement, .ad, .sidebar").remove();let o=t("title").text().trim()||t("h1").first().text().trim()||t('meta[property="og:title"]').attr("content")||"Untitled",r=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 x of a){let w=t(x).first();if(w.length>0&&(i=w.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((x,w)=>{let b=t(w).text().trim();b.length>50&&c.length<3&&c.push(b)});let p=c.join(`
34
+ ${o}`}var Fc,Lt,hn=g(()=>{"use strict";l();jc();k();Fc=1e5;Lt={name:Nc,displayName:Ac,description:Mc,parameters:Ic,category:Oc,execute:dh}});var Lc,qc,Uc,Wc,Gc,Bc=g(()=>{"use strict";l();Lc="http.download",qc="Download",Uc="Download a file from a URL and save it to a local path.",Wc="network",Gc={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"]}});import*as Qe from"fs";import*as Jc from"path";async function uh(s){let e=s.url,t=s.path,r=s.headers;if(y(`[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=Jc.dirname(t);return Qe.existsSync(a)||Qe.mkdirSync(a,{recursive:!0}),Qe.writeFileSync(t,n),`Downloaded ${e} \u2192 ${t} (${n.length} bytes)`}var qt,yn=g(()=>{"use strict";l();Bc();k();qt={name:Lc,displayName:qc,description:Uc,parameters:Gc,category:Wc,execute:uh}});var zc={};re(zc,{httpDeleteTool:()=>Lt,httpDownloadTool:()=>qt,httpGetTool:()=>It,httpPostTool:()=>jt,httpPutTool:()=>Ft,httpToolsProject:()=>Hc});var Hc,wn=g(()=>{"use strict";l();un();fn();gn();hn();yn();un();fn();gn();hn();yn();Hc={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:[It,jt,Ft,Lt,qt],dependencies:{}}});var Kc,Qc,Yc,Vc,Xc,Zc=g(()=>{"use strict";l();Kc="web.fetch",Qc="Fetch",Yc="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).",Vc="network",Xc={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"]}});import*as bn from"cheerio";function ep(s,e){let t=bn.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 b of a){let w=t(b).first();if(w.length>0&&(i=w.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((b,w)=>{let x=t(w).text().trim();x.length>50&&c.length<3&&c.push(x)});let p=c.join(`
35
35
 
36
- `)||i.substring(0,500),m=[];t("h2, h3").each((x,w)=>{let b=t(w).text().trim();b&&b.length>5&&b.length<200&&m.length<10&&m.push(b)});let f=i.split(/\s+/).length,h=i.split(/\s+/);return h.length>2e3&&(i=h.slice(0,2e3).join(" ")+"..."),{title:o,url:e,author:r,publishDate:n,excerpt:p.substring(0,1e3),mainContent:i.substring(0,1e4),keyPoints:m,wordCount:f}}function Zc(s,e){let t=bn.load(s);t("script, style, nav, header, footer").remove();let o=t("title").text().trim()||t("h1").first().text().trim()||"Untitled",r=t('meta[name="description"]').attr("content")||t('meta[property="og:description"]').attr("content")||"";return r||t("p").each((n,a)=>{let i=t(a).text().trim();i.length>50&&!r&&(r=i)}),r||(r=t("body").text().trim().replace(/\s+/g," ")),{title:o,url:e,snippet:r.substring(0,500)}}function ep(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 tp(s){return`# ${s.title}
36
+ `)||i.substring(0,500),m=[];t("h2, h3").each((b,w)=>{let x=t(w).text().trim();x&&x.length>5&&x.length<200&&m.length<10&&m.push(x)});let f=i.split(/\s+/).length,h=i.split(/\s+/);return h.length>2e3&&(i=h.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:f}}function tp(s,e){let t=bn.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 op(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 rp(s){return`# ${s.title}
38
38
  URL: ${s.url}
39
39
 
40
- ${s.snippet}`}var op=g(()=>{"use strict";l()});async function ch(s){let e=s.url,t=s.extractionMode||"full",o=s.headers,r=s.timeout||3e4;if(y(`[web.fetch] execute url="${e}" mode=${t} timeout=${r}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(),r),i;try{i=await fetch(e,{method:"GET",headers:o||{},signal:n.signal})}catch(p){throw p.name==="AbortError"?new Error(`Request timed out after ${r}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=Xc(c,e);return ep(p)}else if(t==="minimal"){let p=Zc(c,e);return tp(p)}else return c.length>15e3?c.substring(0,15e3)+`
40
+ ${s.snippet}`}var np=g(()=>{"use strict";l()});async function fh(s){let e=s.url,t=s.extractionMode||"full",r=s.headers,o=s.timeout||3e4;if(y(`[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=ep(c,e);return op(p)}else if(t==="minimal"){let p=tp(c,e);return rp(p)}else return c.length>15e3?c.substring(0,15e3)+`
42
42
 
43
- [TRUNCATED: showing 15K of ${c.length} total characters]`:c}var Lt,xn=g(()=>{"use strict";l();Vc();op();_();Lt={name:Hc,displayName:zc,description:Kc,parameters:Yc,category:Qc,execute:ch}});var rp,np,sp,ip,ap,lp=g(()=>{"use strict";l();rp="web.search",np="Search",sp="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.",ip="network",ap={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"]}});import*as xe from"fs";import*as To from"path";function Po(s){let e=pp(s);if(!xe.existsSync(e))return{};try{let t=xe.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return{}}}function qt(s){let e=Po(s),t=mh(e.tools||e);return y(JSON.stringify(t??{})),t}function ph(s,e){let t=pp(e),o={};try{xe.existsSync(t)&&(o=JSON.parse(xe.readFileSync(t,"utf-8")))}catch{o={}}o.tools=s,xe.writeFileSync(t,JSON.stringify(o,null,4),"utf-8")}function mh(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??z.enabled,autoExecute:s.autoExecute??z.autoExecute,maxToolRounds:s.maxToolRounds??z.maxToolRounds,toolChoicePolicy:s.toolChoicePolicy??z.toolChoicePolicy,resultMaxChars:s.resultMaxChars??z.resultMaxChars,intelligentToolDetection:s.intelligentToolDetection,enabledTools:s.enabledTools??z.enabledTools,enabledToolCategories:s.enabledToolCategories??z.enabledToolCategories,toolSearch:s.toolSearch??z.toolSearch,additionalConfigurations:e}}function pp(s){return s?s.endsWith(".json")?To.resolve(s):To.resolve(s,cp):To.resolve(process.cwd(),cp)}var cp,Tn=g(()=>{"use strict";l();tt();_();cp="toolpack.config.json"});import*as dp from"cheerio";function fh(s,e){y("[web.search] Parsing DuckDuckGo Lite response");let t=dp.load(s),o=[];return t("a.result-link").each((n,a)=>{if(o.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&&o.push({title:c,link:p,snippet:m.slice(0,200)})}),o}function gh(s){if(s)switch(s){case"day":return 1;case"week":return 7;case"month":return 31;case"year":return 365;default:return}}function mp(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 hh(s){let e=s.query,t=s.max_results||5,o=s.include_answer||!1,r=s.freshness;y(`[web.search] execute query="${e}" max_results=${t} includeAnswer=${o} freshness=${r??"none"}`);let n=`Request timed out after ${s.timeout||3e4}ms`,a=()=>{let f=new AbortController,h=setTimeout(()=>f.abort(),s.timeout||3e4);return{signal:f.signal,clear:()=>clearTimeout(h)}};if(!e)throw new Error("query is required");let i=qt();if(y(`[web.search] config=${JSON.stringify(i)}`),i.additionalConfigurations?.webSearch?.tavilyApiKey){y("[web.search] using Tavily API");try{let{signal:f,clear:h}=a(),x=gh(r),w={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:i.additionalConfigurations.webSearch.tavilyApiKey,query:e,max_results:t,include_answer:o,...x&&{days:x}}),signal:f};y(`[web.search] Tavily request=${JSON.stringify(w)}`);let b=await fetch("https://api.tavily.com/search",w).finally(h);if(b.ok){let P=await b.json();if(P.results&&P.results.length>0){let S=P.results.map(C=>({title:C.title,link:C.url,snippet:C.content}));return o&&P.answer?JSON.stringify({answer:P.answer,results:S},null,2):JSON.stringify(S,null,2)}}else Q(`[web.search] Tavily search failed with status ${b.status}`)}catch(f){Q(`[web.search] Tavily search failed, falling back: ${f}`)}}if(i.additionalConfigurations?.webSearch?.braveApiKey)try{let{signal:f,clear:h}=a();if(o){let x=mp(r),w=x?`&freshness=${x}`:"",b=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(e)}&count=${Math.min(t,20)}&summary=1${w}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":i.additionalConfigurations.webSearch.braveApiKey},signal:f}).finally(h);if(b.ok){let P=await b.json(),S=P.summarizer?.key;if(S&&P.web?.results){let{signal:C,clear:T}=a(),k=await fetch(`https://api.search.brave.com/res/v1/summarizer/search?key=${S}`,{headers:{Accept:"application/json","X-Subscription-Token":i.additionalConfigurations.webSearch.braveApiKey},signal:C}).finally(T);if(k.ok){let R=await k.json(),I=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:I},null,2)}}if(P.web?.results){let C=P.web.results.slice(0,t).map(T=>({title:T.title,link:T.url,snippet:T.description}));return JSON.stringify(C,null,2)}}}else{let x=mp(r),w=x?`&freshness=${x}`:"",b=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(e)}&count=${Math.min(t,20)}${w}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":i.additionalConfigurations.webSearch.braveApiKey},signal:f}).finally(h);if(b.ok){let P=await b.json();if(P.web?.results&&P.web.results.length>0){let S=P.web.results.slice(0,t).map(C=>({title:C.title,link:C.url,snippet:C.description}));return JSON.stringify(S,null,2)}}}}catch(f){D(`[web.search] Brave search failed, falling back: ${f}`)}let{signal:c,clear:p}=a(),m;try{m=await fetch(dh,{method:"POST",headers:{"User-Agent":uh,"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(f){throw f.name==="AbortError"?new Error(n):f}finally{p()}if(m.ok){let f=await m.text(),h=fh(f,t);if(h.length>0)return JSON.stringify(h,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 dh,uh,Ut,Pn=g(()=>{"use strict";l();lp();Tn();_();dh="https://lite.duckduckgo.com/lite/",uh="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";Ut={name:rp,displayName:np,description:sp,parameters:ap,category:ip,execute:hh}});var up,fp,gp,hp,yp,wp=g(()=>{"use strict";l();up="web.scrape",fp="Scrape",gp="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.",hp="network",yp={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"]}});import*as Tp from"cheerio";async function bh(s){let e=s.url,t=s.selector,o=s.section,r=s.format||"text",n=s.max_length||6e3,a=s.timeout||3e4;if(y(`[web.scrape] execute url="${e}" format=${r} selector=${t??"none"} section=${o??"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":yh},signal:i.signal})}catch(w){throw w.name==="AbortError"?new Error(`Request timed out after ${a}ms`):w}finally{clearTimeout(c)}if(!p.ok)throw new Error(`Failed to fetch ${e}: HTTP ${p.status} ${p.statusText}`);let m=await p.text(),f=Tp.load(m);for(let w of wh)f(w).remove();if(r==="tables"){let w=[];return f("table").each((b,P)=>{let S=[],C=[];f(P).find("th").each((T,k)=>{C.push(f(k).text().trim())}),f(P).find("tr").each((T,k)=>{let R=C.length>0?{}:[],I=f(k).find("td");I.length>0&&(I.each((U,L)=>{let j=f(L).text().trim();C.length>0&&C[U]?R[C[U]]=j:R.push(j)}),S.push(R))}),S.length>0&&w.push({id:`Table ${b+1}`,headers:C.length>0?C:void 0,rows:S})}),w.length===0?`No tables found on ${e}`:JSON.stringify(w,null,2)}let h="";if(o){let w=o.toLowerCase(),b=null,P=0;if(f("h1, h2, h3, h4, h5, h6").each((S,C)=>{if(f(C).text().toLowerCase().includes(w))return b=C,P=parseInt(C.tagName.charAt(1)),!1}),b){let S=f(b),C=[],T=S.next();for(;T.length>0;){let k=T.prop("tagName")?.toLowerCase();if(k&&/^h[1-6]$/.test(k)&&parseInt(k.charAt(1))<=P)break;let R=T.text().trim();R&&C.push(R),T=T.next()}C.length>0?(h=C.join(`
43
+ [TRUNCATED: showing 15K of ${c.length} total characters]`:c}var Ut,xn=g(()=>{"use strict";l();Zc();np();k();Ut={name:Kc,displayName:Qc,description:Yc,parameters:Xc,category:Vc,execute:fh}});var sp,ip,ap,lp,cp,pp=g(()=>{"use strict";l();sp="web.search",ip="Search",ap="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.",lp="network",cp={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"]}});import*as xe from"fs";import*as To from"path";function Po(s){let e=dp(s);if(!xe.existsSync(e))return{};try{let t=xe.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return{}}}function Wt(s){let e=Po(s),t=hh(e.tools||e);return y(JSON.stringify(t??{})),t}function gh(s,e){let t=dp(e),r={};try{xe.existsSync(t)&&(r=JSON.parse(xe.readFileSync(t,"utf-8")))}catch{r={}}r.tools=s,xe.writeFileSync(t,JSON.stringify(r,null,4),"utf-8")}function hh(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??z.enabled,autoExecute:s.autoExecute??z.autoExecute,maxToolRounds:s.maxToolRounds??z.maxToolRounds,toolChoicePolicy:s.toolChoicePolicy??z.toolChoicePolicy,resultMaxChars:s.resultMaxChars??z.resultMaxChars,intelligentToolDetection:s.intelligentToolDetection,enabledTools:s.enabledTools??z.enabledTools,enabledToolCategories:s.enabledToolCategories??z.enabledToolCategories,toolSearch:s.toolSearch??z.toolSearch,additionalConfigurations:e}}function dp(s){return s?s.endsWith(".json")?To.resolve(s):To.resolve(s,mp):To.resolve(process.cwd(),mp)}var mp,Tn=g(()=>{"use strict";l();rt();k();mp="toolpack.config.json"});import*as fp from"cheerio";function bh(s,e){y("[web.search] Parsing DuckDuckGo Lite response");let t=fp.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 xh(s){if(s)switch(s){case"day":return 1;case"week":return 7;case"month":return 31;case"year":return 365;default:return}}function up(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 Th(s){let e=s.query,t=s.max_results||5,r=s.include_answer||!1,o=s.freshness;y(`[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 f=new AbortController,h=setTimeout(()=>f.abort(),s.timeout||3e4);return{signal:f.signal,clear:()=>clearTimeout(h)}};if(!e)throw new Error("query is required");let i=Wt();if(y(`[web.search] config=${JSON.stringify(i)}`),i.additionalConfigurations?.webSearch?.tavilyApiKey){y("[web.search] using Tavily API");try{let{signal:f,clear:h}=a(),b=xh(o),w={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:i.additionalConfigurations.webSearch.tavilyApiKey,query:e,max_results:t,include_answer:r,...b&&{days:b}}),signal:f};y(`[web.search] Tavily request=${JSON.stringify(w)}`);let x=await fetch("https://api.tavily.com/search",w).finally(h);if(x.ok){let P=await x.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 Q(`[web.search] Tavily search failed with status ${x.status}`)}catch(f){Q(`[web.search] Tavily search failed, falling back: ${f}`)}}if(i.additionalConfigurations?.webSearch?.braveApiKey)try{let{signal:f,clear:h}=a();if(r){let b=up(o),w=b?`&freshness=${b}`:"",x=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(e)}&count=${Math.min(t,20)}&summary=1${w}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":i.additionalConfigurations.webSearch.braveApiKey},signal:f}).finally(h);if(x.ok){let P=await x.json(),$=P.summarizer?.key;if($&&P.web?.results){let{signal:C,clear:T}=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(T);if(S.ok){let R=await S.json(),I=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:I},null,2)}}if(P.web?.results){let C=P.web.results.slice(0,t).map(T=>({title:T.title,link:T.url,snippet:T.description}));return JSON.stringify(C,null,2)}}}else{let b=up(o),w=b?`&freshness=${b}`:"",x=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(e)}&count=${Math.min(t,20)}${w}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":i.additionalConfigurations.webSearch.braveApiKey},signal:f}).finally(h);if(x.ok){let P=await x.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(f){E(`[web.search] Brave search failed, falling back: ${f}`)}let{signal:c,clear:p}=a(),m;try{m=await fetch(yh,{method:"POST",headers:{"User-Agent":wh,"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(f){throw f.name==="AbortError"?new Error(n):f}finally{p()}if(m.ok){let f=await m.text(),h=bh(f,t);if(h.length>0)return JSON.stringify(h,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 yh,wh,Gt,Pn=g(()=>{"use strict";l();pp();Tn();k();yh="https://lite.duckduckgo.com/lite/",wh="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";Gt={name:sp,displayName:ip,description:ap,parameters:cp,category:lp,execute:Th}});var gp,hp,yp,wp,bp,xp=g(()=>{"use strict";l();gp="web.scrape",hp="Scrape",yp="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.",wp="network",bp={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"]}});import*as Cp from"cheerio";async function vh(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(y(`[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":Ph},signal:i.signal})}catch(w){throw w.name==="AbortError"?new Error(`Request timed out after ${a}ms`):w}finally{clearTimeout(c)}if(!p.ok)throw new Error(`Failed to fetch ${e}: HTTP ${p.status} ${p.statusText}`);let m=await p.text(),f=Cp.load(m);for(let w of Ch)f(w).remove();if(o==="tables"){let w=[];return f("table").each((x,P)=>{let $=[],C=[];f(P).find("th").each((T,S)=>{C.push(f(S).text().trim())}),f(P).find("tr").each((T,S)=>{let R=C.length>0?{}:[],I=f(S).find("td");I.length>0&&(I.each((U,L)=>{let j=f(L).text().trim();C.length>0&&C[U]?R[C[U]]=j:R.push(j)}),$.push(R))}),$.length>0&&w.push({id:`Table ${x+1}`,headers:C.length>0?C:void 0,rows:$})}),w.length===0?`No tables found on ${e}`:JSON.stringify(w,null,2)}let h="";if(r){let w=r.toLowerCase(),x=null,P=0;if(f("h1, h2, h3, h4, h5, h6").each(($,C)=>{if(f(C).text().toLowerCase().includes(w))return x=C,P=parseInt(C.tagName.charAt(1)),!1}),x){let $=f(x),C=[],T=$.next();for(;T.length>0;){let S=T.prop("tagName")?.toLowerCase();if(S&&/^h[1-6]$/.test(S)&&parseInt(S.charAt(1))<=P)break;let R=T.text().trim();R&&C.push(R),T=T.next()}C.length>0?(h=C.join(`
45
45
 
46
- `).replace(/\s+/g," ").trim(),h=`[Section: "${o}"]
46
+ `).replace(/\s+/g," ").trim(),h=`[Section: "${r}"]
47
47
 
48
- ${h}`):h=`[Note: Found heading "${o}" but no content below it. Falling back to full page.]
48
+ ${h}`):h=`[Note: Found heading "${r}" but no content below it. Falling back to full page.]
49
49
 
50
- `}else h=`[Note: Section "${o}" not found. Falling back to full page.]
50
+ `}else h=`[Note: Section "${r}" not found. Falling back to full page.]
51
51
 
52
- `}if(!h||h.includes("Falling back to full page"))if(h&&h.includes("Falling back to full page")&&(h=""),t){let w=f(t);if(w.length>0)h=w.text().replace(/\s+/g," ").trim();else{for(let b of bp){let P=f(b);if(P.length>0){let S=P.text().replace(/\s+/g," ").trim();if(S.length>xp){h=S;break}}}if(h)h=`[Note: Selector "${t}" not found. Showing auto-detected main content instead.]
52
+ `}if(!h||h.includes("Falling back to full page"))if(h&&h.includes("Falling back to full page")&&(h=""),t){let w=f(t);if(w.length>0)h=w.text().replace(/\s+/g," ").trim();else{for(let x of Tp){let P=f(x);if(P.length>0){let $=P.text().replace(/\s+/g," ").trim();if($.length>Pp){h=$;break}}}if(h)h=`[Note: Selector "${t}" not found. Showing auto-detected main content instead.]
53
53
 
54
- ${h}`;else return`No element found matching selector "${t}" and could not auto-detect main content from ${e}`}}else for(let w of bp){let b=f(w);if(b.length>0){let P=b.text().replace(/\s+/g," ").trim();if(P.length>xp){h=P;break}}}if(h||(h=f("body").text().replace(/\s+/g," ").trim(),h&&(h=`[Note: Could not detect main content area. Showing full page text (may include navigation).]
54
+ ${h}`;else return`No element found matching selector "${t}" and could not auto-detect main content from ${e}`}}else for(let w of Tp){let x=f(w);if(x.length>0){let P=x.text().replace(/\s+/g," ").trim();if(P.length>Pp){h=P;break}}}if(h||(h=f("body").text().replace(/\s+/g," ").trim(),h&&(h=`[Note: Could not detect main content area. Showing full page text (may include navigation).]
55
55
 
56
56
  ${h}`)),!h)return`Could not extract any content from ${e}`;if(h.length>n){let w=h.substring(0,n);return`[Warning: Content exceeds ${n} chars (actual: ${h.length} chars). Showing first ${n} chars only.]
57
57
 
@@ -63,34 +63,34 @@ ${w}
63
63
 
64
64
  ... [Content truncated. ${h.length-n} chars remaining. Use section parameter to extract specific sections.]`}return`Page content from ${e}:
65
65
 
66
- ${h}`}var yh,wh,bp,xp,Wt,Cn=g(()=>{"use strict";l();wp();_();yh="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",wh=["script","style","nav","footer","header","iframe",".ads",".sidebar","noscript"],bp=["article","main",".content","#content",'[role="main"]',"body"],xp=200;Wt={name:up,displayName:fp,description:gp,parameters:yp,category:hp,execute:bh}});var Pp,Cp,vp,Sp,$p,_p=g(()=>{"use strict";l();Pp="web.extract_links",Cp="Extract Links",vp="Extract all links from a webpage. Returns an array of objects with text and URL. Optionally filter by pattern.",Sp="network",$p={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"]}});import*as kp from"cheerio";async function Th(s){let e=s.url,t=s.filter,o=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,n=setTimeout(()=>r.abort(),o),a;try{a=await fetch(e,{method:"GET",headers:{"User-Agent":xh},signal:r.signal})}catch(f){throw f.name==="AbortError"?new Error(`Request timed out after ${o}ms`):f}finally{clearTimeout(n)}if(!a.ok)throw new Error(`Failed to fetch ${e}: HTTP ${a.status} ${a.statusText}`);let i=await a.text(),c=kp.load(i),p=new URL(e),m=[];return c("a[href]").each((f,h)=>{let x=c(h),w=x.attr("href");if(!w)return;let b;try{b=new URL(w,e).toString()}catch{return}if(b.startsWith("javascript:")||b.startsWith("mailto:")||b.startsWith("tel:"))return;let P=x.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 xh,Gt,vn=g(()=>{"use strict";l();_p();xh="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Gt={name:Pp,displayName:Cp,description:vp,parameters:$p,category:Sp,execute:Th}});var Rp,Dp,Ep,Np,Ap,Mp=g(()=>{"use strict";l();Rp="web.map",Dp="Map",Ep="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.",Np="network",Ap={type:"object",properties:{url:{type:"string",description:"The URL to map"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as Op from"cheerio";async function Ch(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 o=new AbortController,r=setTimeout(()=>o.abort(),t),n;try{n=await fetch(e,{method:"GET",headers:{"User-Agent":Ph},signal:o.signal})}catch(m){throw m.name==="AbortError"?new Error(`Request timed out after ${t}ms`):m}finally{clearTimeout(r)}if(!n.ok)throw new Error(`Failed to fetch ${e}: HTTP ${n.status} ${n.statusText}`);let a=await n.text(),i=Op.load(a),c=[];if(i("h1, h2, h3, h4, h5, h6").each((m,f)=>{let h=f.tagName.toLowerCase(),x=parseInt(h.charAt(1)),w=i(f).text().trim();w&&c.push({level:x,text:w})}),c.length===0)return`No headings found on ${e}. The page may not have a clear structure.`;let p=`Page outline for ${e}:
66
+ ${h}`}var Ph,Ch,Tp,Pp,Bt,Cn=g(()=>{"use strict";l();xp();k();Ph="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",Ch=["script","style","nav","footer","header","iframe",".ads",".sidebar","noscript"],Tp=["article","main",".content","#content",'[role="main"]',"body"],Pp=200;Bt={name:gp,displayName:hp,description:yp,parameters:bp,category:wp,execute:vh}});var vp,Sp,$p,_p,kp,Rp=g(()=>{"use strict";l();vp="web.extract_links",Sp="Extract Links",$p="Extract all links from a webpage. Returns an array of objects with text and URL. Optionally filter by pattern.",_p="network",kp={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"]}});import*as Ep from"cheerio";async function $h(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":Sh},signal:o.signal})}catch(f){throw f.name==="AbortError"?new Error(`Request timed out after ${r}ms`):f}finally{clearTimeout(n)}if(!a.ok)throw new Error(`Failed to fetch ${e}: HTTP ${a.status} ${a.statusText}`);let i=await a.text(),c=Ep.load(i),p=new URL(e),m=[];return c("a[href]").each((f,h)=>{let b=c(h),w=b.attr("href");if(!w)return;let x;try{x=new URL(w,e).toString()}catch{return}if(x.startsWith("javascript:")||x.startsWith("mailto:")||x.startsWith("tel:"))return;let P=b.text().trim()||"[no text]";if(t){if(t==="same-domain")try{if(new URL(x).hostname!==p.hostname)return}catch{return}else if(!x.includes(t))return}m.push({text:P,url:x})}),m.length===0?`No links found on ${e}${t?` matching filter "${t}"`:""}`:JSON.stringify(m,null,2)}var Sh,Jt,vn=g(()=>{"use strict";l();Rp();Sh="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:vp,displayName:Sp,description:$p,parameters:kp,category:_p,execute:$h}});var Dp,Np,Ap,Mp,Op,Ip=g(()=>{"use strict";l();Dp="web.map",Np="Map",Ap="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.",Mp="network",Op={type:"object",properties:{url:{type:"string",description:"The URL to map"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as jp from"cheerio";async function kh(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":_h},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=jp.load(a),c=[];if(i("h1, h2, h3, h4, h5, h6").each((m,f)=>{let h=f.tagName.toLowerCase(),b=parseInt(h.charAt(1)),w=i(f).text().trim();w&&c.push({level:b,text:w})}),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 f=" ".repeat(m.level-1);p+=`${f}${"#".repeat(m.level)} ${m.text}
69
- `}return p}var Ph,Co,Sn=g(()=>{"use strict";l();Mp();Ph="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Co={name:Rp,displayName:Dp,description:Ep,parameters:Ap,category:Np,execute:Ch}});var Ip,jp,Fp,Lp,qp,Up=g(()=>{"use strict";l();Ip="web.metadata",jp="Extract Metadata",Fp="Extract Open Graph, Twitter Cards, JSON-LD, and meta tags from a URL.",Lp="network",qp={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"]}});import*as Wp from"cheerio";async function Sh(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 o=new AbortController,r=setTimeout(()=>o.abort(),t),n;try{n=await fetch(e,{method:"GET",headers:{"User-Agent":vh},signal:o.signal})}catch(p){throw p.name==="AbortError"?new Error(`Request timed out after ${t}ms`):p}finally{clearTimeout(r)}if(!n.ok)throw new Error(`Failed to fetch ${e}: HTTP ${n.status} ${n.statusText}`);let a=await n.text(),i=Wp.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 f=i(m).attr("property")?.replace("og:",""),h=i(m).attr("content");f&&h&&(c.openGraph[f]=h)}),i('meta[name^="twitter:"]').each((p,m)=>{let f=i(m).attr("name")?.replace("twitter:",""),h=i(m).attr("content");f&&h&&(c.twitter[f]=h)}),i('script[type="application/ld+json"]').each((p,m)=>{let f=i(m).html();if(f)try{c.jsonLd.push(JSON.parse(f))}catch{}}),JSON.stringify(c,null,2)}var vh,vo,$n=g(()=>{"use strict";l();Up();vh="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";vo={name:Ip,displayName:jp,description:Fp,parameters:qp,category:Lp,execute:Sh}});var Gp,Bp,Jp,Hp,zp,Kp=g(()=>{"use strict";l();Gp="web.sitemap",Bp="Extract Sitemap",Jp="Parse sitemap.xml or robots.txt to discover all pages on a site. Returns an array of URLs with lastmod/priority if available.",Hp="network",zp={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"]}});import*as Qp from"cheerio";async function _n(s,e){let t=new AbortController,o=setTimeout(()=>t.abort(),e);try{return await fetch(s,{method:"GET",headers:{"User-Agent":$h},signal:t.signal})}catch(r){throw r.name==="AbortError"?new Error(`Request timed out after ${e}ms`):r}finally{clearTimeout(o)}}async function _h(s){let e=s.url,t=s.max_urls||100,o=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=e,n=!1;!e.endsWith(".xml")&&!e.endsWith(".txt")&&(r=new URL(e.endsWith("/")?"sitemap.xml":"/sitemap.xml",e).toString(),n=!0);let a;try{a=await _n(r,o),!a.ok&&n&&(r=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),a=await _n(r,o))}catch(p){if(n)r=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),a=await _n(r,o);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(r.endsWith(".xml")||i.trim().startsWith("<")){let p=Qp.load(i,{xmlMode:!0}),m=p("sitemap > loc");if(m.length>0)return m.each((h,x)=>{c.length>=t||c.push({loc:p(x).text()})}),JSON.stringify({type:"sitemapindex",urls:c},null,2);p("urlset > url").each((h,x)=>{if(c.length>=t)return;let w=p(x);c.push({loc:w.children("loc").text(),lastmod:w.children("lastmod").text()||void 0,priority:w.children("priority").text()||void 0})})}else{let p=i.split(`
70
- `);for(let m of p){if(c.length>=t)break;let f=m.trim();if(f.toLowerCase().startsWith("sitemap:"))c.push({loc:f.substring(8).trim()});else if(f.toLowerCase().startsWith("allow:")){let h=f.substring(6).trim();c.push({loc:new URL(h,r).toString()})}}}return JSON.stringify(c,null,2)}var $h,So,kn=g(()=>{"use strict";l();Kp();$h="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";So={name:Gp,displayName:Bp,description:Jp,parameters:zp,category:Hp,execute:_h}});var Yp,Vp,Xp,Zp,em,tm=g(()=>{"use strict";l();Yp="web.feed",Vp="Extract Feed",Xp="Parse RSS/Atom feeds and return structured entries. Requires rss-parser library to be installed.",Zp="network",em={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 om(){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 rm=g(()=>{"use strict";l()});async function kh(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 om();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 $o,Rn=g(()=>{"use strict";l();tm();rm();$o={name:Yp,displayName:Vp,description:Xp,parameters:em,category:Zp,execute:kh}});var nm,sm,im,am,lm,cm=g(()=>{"use strict";l();nm="web.screenshot",sm="Screenshot",im="Render a page with headless browser and return screenshot Base64 PNG or rendered HTML.",am="network",lm={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 pm(){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 mm=g(()=>{"use strict";l()});async function Dh(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 pm()).launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]});try{let i=await a.newPage();if(await i.setUserAgent(Rh),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 Rh,_o,Dn=g(()=>{"use strict";l();cm();mm();Rh="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";_o={name:nm,displayName:sm,description:im,parameters:lm,category:am,execute:Dh}});var um={};re(um,{webExtractLinksTool:()=>Gt,webFeedTool:()=>$o,webFetchTool:()=>Lt,webMapTool:()=>Co,webMetadataTool:()=>vo,webScrapeTool:()=>Wt,webScreenshotTool:()=>_o,webSearchTool:()=>Ut,webSitemapTool:()=>So,webToolsProject:()=>dm});var dm,En=g(()=>{"use strict";l();xn();Pn();Cn();vn();Sn();$n();kn();Rn();Dn();xn();Pn();Cn();vn();Sn();$n();kn();Rn();Dn();dm={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:[Lt,Ut,Wt,Gt,Co,vo,So,$o,_o],dependencies:{cheerio:"^1.0.0-rc.12"}}});var fm,gm,hm,ym,wm,bm=g(()=>{"use strict";l();fm="coding.find_symbol",gm="Find Symbol",hm="Find function, class, or variable definitions in JavaScript/TypeScript files using AST parsing",ym="coding",wm={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"]}});import{extname as Eh}from"path";function ko(s){let e=Eh(s).toLowerCase();return Nh[e]||"unknown"}var Nh,Nn=g(()=>{"use strict";l();Nh={".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"}});import*as Ae from"web-tree-sitter";import*as pe from"fs";import*as Te from"path";import*as Tm from"os";var xm,An,Ah,Ro,Pm=g(()=>{"use strict";l();xm=Ae.default||Ae.Parser||Ae,An=Te.join(Tm.homedir(),".toolpack-sdk","grammars"),Ah=Te.resolve(d,"../../grammars"),Ro=class{grammars=new Map;isInitialized=!1;async init(){this.isInitialized||(await xm.init({locateFile(e,t){return Te.join(d,"../../../../../../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(Ae.Language||xm.Language).load(o);return this.grammars.set(e,n),n}async resolveGrammarPath(e){let t=`tree-sitter-${e}.wasm`,o=Te.resolve(d,"../../../../../../node_modules/tree-sitter-wasms/out",t);if(pe.existsSync(o))return o;let r=Te.join(Ah,t);if(pe.existsSync(r))return r;let n=Te.join(An,t);return pe.existsSync(n)||await this.downloadGrammar(e,n),n}async downloadGrammar(e,t){pe.existsSync(An)||pe.mkdirSync(An,{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);pe.writeFileSync(t,a)}}});import*as Bt from"web-tree-sitter";import*as Cm from"fs";import*as vm from"crypto";var Mh,Do,Sm=g(()=>{"use strict";l();Nn();Pm();Mh=Bt.default||Bt.Parser||Bt,Do=class{treeCache=new Map;maxCacheSize=50;parser=null;grammarManager;constructor(){this.grammarManager=new Ro}hash(e){return vm.createHash("md5").update(e).digest("hex")}async getTree(e,t){let o=t!==void 0?t:Cm.readFileSync(e,"utf-8"),r=this.hash(o),n=this.treeCache.get(e),a=ko(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 Mh),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)}}}});import{parse as Oh}from"@babel/parser";import*as Mn from"@babel/traverse";var se,Eo,$m=g(()=>{"use strict";l();se=Mn.default||Mn,Eo=class{parseCode(e){return Oh(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||o){let m=c.node.loc?.start.line||0,f=c.node.loc?.start.column||0,h=a[m-1]||"";r.push({file:e.filePath,line:m,column:f,context:h.trim(),isDeclaration:p})}}}})}catch{}return r}async getSymbolAtPosition(e,t,o){try{let r=this.parseCode(e.content),n=null;return se(r,{Identifier(a){let i=a.node.loc;i&&i.start.line===t&&i.start.column===o&&(n=a.node.name,a.stop())}}),n}catch{return null}}async getDefinition(e,t){try{let o=this.parseCode(e.content),r=e.filePath,n=null;return se(o,{FunctionDeclaration(a){a.node.id?.name===t&&(n={file:r,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:r,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:r,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:r,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:r,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 o=this.parseCode(e.content);se(o,{ExportNamedDeclaration(r){if(r.node.declaration)if(r.node.declaration.type==="VariableDeclaration")for(let n of r.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 r.node.declaration.type==="FunctionDeclaration"&&r.node.declaration.id?t.push({name:r.node.declaration.id.name,kind:"function",line:r.node.declaration.loc?.start.line||0,column:r.node.declaration.loc?.start.column||0}):r.node.declaration.type==="ClassDeclaration"&&r.node.declaration.id&&t.push({name:r.node.declaration.id.name,kind:"class",line:r.node.declaration.loc?.start.line||0,column:r.node.declaration.loc?.start.column||0});else if(r.node.specifiers)for(let n of r.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(r){let n="default",a="default";r.node.declaration.type==="ClassDeclaration"&&r.node.declaration.id?(n=r.node.declaration.id.name,a="class"):r.node.declaration.type==="FunctionDeclaration"&&r.node.declaration.id?(n=r.node.declaration.id.name,a="function"):r.node.declaration.type==="Identifier"&&(n=r.node.declaration.name,a="variable"),t.push({name:n,kind:a,line:r.node.loc?.start.line||0,column:r.node.loc?.start.column||0})}})}catch{}return t}async getOutline(e){let t=[];try{return(await this.getSymbols(e)).map(r=>({name:r.name,kind:r.kind,line:r.line,column:r.column,children:[]}))}catch{}return t}async extractFunction(e,t,o,r,n,a){let i=e.content.split(`
72
- `),c=Math.max(0,t-1),p=Math.min(i.length,r),m=i.slice(c,p).join(`
69
+ `}return p}var _h,Co,Sn=g(()=>{"use strict";l();Ip();_h="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Co={name:Dp,displayName:Np,description:Ap,parameters:Op,category:Mp,execute:kh}});var Fp,Lp,qp,Up,Wp,Gp=g(()=>{"use strict";l();Fp="web.metadata",Lp="Extract Metadata",qp="Extract Open Graph, Twitter Cards, JSON-LD, and meta tags from a URL.",Up="network",Wp={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"]}});import*as Bp from"cheerio";async function Eh(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":Rh},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=Bp.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 f=i(m).attr("property")?.replace("og:",""),h=i(m).attr("content");f&&h&&(c.openGraph[f]=h)}),i('meta[name^="twitter:"]').each((p,m)=>{let f=i(m).attr("name")?.replace("twitter:",""),h=i(m).attr("content");f&&h&&(c.twitter[f]=h)}),i('script[type="application/ld+json"]').each((p,m)=>{let f=i(m).html();if(f)try{c.jsonLd.push(JSON.parse(f))}catch{}}),JSON.stringify(c,null,2)}var Rh,vo,$n=g(()=>{"use strict";l();Gp();Rh="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";vo={name:Fp,displayName:Lp,description:qp,parameters:Wp,category:Up,execute:Eh}});var Jp,Hp,zp,Kp,Qp,Yp=g(()=>{"use strict";l();Jp="web.sitemap",Hp="Extract Sitemap",zp="Parse sitemap.xml or robots.txt to discover all pages on a site. Returns an array of URLs with lastmod/priority if available.",Kp="network",Qp={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"]}});import*as Vp from"cheerio";async function _n(s,e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);try{return await fetch(s,{method:"GET",headers:{"User-Agent":Dh},signal:t.signal})}catch(o){throw o.name==="AbortError"?new Error(`Request timed out after ${e}ms`):o}finally{clearTimeout(r)}}async function Nh(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 _n(o,r),!a.ok&&n&&(o=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),a=await _n(o,r))}catch(p){if(n)o=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),a=await _n(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=Vp.load(i,{xmlMode:!0}),m=p("sitemap > loc");if(m.length>0)return m.each((h,b)=>{c.length>=t||c.push({loc:p(b).text()})}),JSON.stringify({type:"sitemapindex",urls:c},null,2);p("urlset > url").each((h,b)=>{if(c.length>=t)return;let w=p(b);c.push({loc:w.children("loc").text(),lastmod:w.children("lastmod").text()||void 0,priority:w.children("priority").text()||void 0})})}else{let p=i.split(`
70
+ `);for(let m of p){if(c.length>=t)break;let f=m.trim();if(f.toLowerCase().startsWith("sitemap:"))c.push({loc:f.substring(8).trim()});else if(f.toLowerCase().startsWith("allow:")){let h=f.substring(6).trim();c.push({loc:new URL(h,o).toString()})}}}return JSON.stringify(c,null,2)}var Dh,So,kn=g(()=>{"use strict";l();Yp();Dh="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";So={name:Jp,displayName:Hp,description:zp,parameters:Qp,category:Kp,execute:Nh}});var Xp,Zp,em,tm,om,rm=g(()=>{"use strict";l();Xp="web.feed",Zp="Extract Feed",em="Parse RSS/Atom feeds and return structured entries. Requires rss-parser library to be installed.",tm="network",om={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 nm(){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 sm=g(()=>{"use strict";l()});async function Ah(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 nm();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 $o,Rn=g(()=>{"use strict";l();rm();sm();$o={name:Xp,displayName:Zp,description:em,parameters:om,category:tm,execute:Ah}});var im,am,lm,cm,pm,mm=g(()=>{"use strict";l();im="web.screenshot",am="Screenshot",lm="Render a page with headless browser and return screenshot Base64 PNG or rendered HTML.",cm="network",pm={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 dm(){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 um=g(()=>{"use strict";l()});async function Oh(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 dm()).launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]});try{let i=await a.newPage();if(await i.setUserAgent(Mh),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 Mh,_o,En=g(()=>{"use strict";l();mm();um();Mh="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";_o={name:im,displayName:am,description:lm,parameters:pm,category:cm,execute:Oh}});var gm={};re(gm,{webExtractLinksTool:()=>Jt,webFeedTool:()=>$o,webFetchTool:()=>Ut,webMapTool:()=>Co,webMetadataTool:()=>vo,webScrapeTool:()=>Bt,webScreenshotTool:()=>_o,webSearchTool:()=>Gt,webSitemapTool:()=>So,webToolsProject:()=>fm});var fm,Dn=g(()=>{"use strict";l();xn();Pn();Cn();vn();Sn();$n();kn();Rn();En();xn();Pn();Cn();vn();Sn();$n();kn();Rn();En();fm={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:[Ut,Gt,Bt,Jt,Co,vo,So,$o,_o],dependencies:{cheerio:"^1.0.0-rc.12"}}});var hm,ym,wm,bm,xm,Tm=g(()=>{"use strict";l();hm="coding.find_symbol",ym="Find Symbol",wm="Find function, class, or variable definitions in JavaScript/TypeScript files using AST parsing",bm="coding",xm={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"]}});import{extname as Ih}from"path";function ko(s){let e=Ih(s).toLowerCase();return jh[e]||"unknown"}var jh,Nn=g(()=>{"use strict";l();jh={".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"}});import*as Me from"web-tree-sitter";import*as pe from"fs";import*as Te from"path";import*as Cm from"os";var Pm,An,Fh,Ro,vm=g(()=>{"use strict";l();Pm=Me.default||Me.Parser||Me,An=Te.join(Cm.homedir(),".toolpack-sdk","grammars"),Fh=Te.resolve(d,"../../grammars"),Ro=class{grammars=new Map;isInitialized=!1;async init(){this.isInitialized||(await Pm.init({locateFile(e,t){return Te.join(d,"../../../../../../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(Me.Language||Pm.Language).load(r);return this.grammars.set(e,n),n}async resolveGrammarPath(e){let t=`tree-sitter-${e}.wasm`,r=Te.resolve(d,"../../../../../../node_modules/tree-sitter-wasms/out",t);if(pe.existsSync(r))return r;let o=Te.join(Fh,t);if(pe.existsSync(o))return o;let n=Te.join(An,t);return pe.existsSync(n)||await this.downloadGrammar(e,n),n}async downloadGrammar(e,t){pe.existsSync(An)||pe.mkdirSync(An,{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);pe.writeFileSync(t,a)}}});import*as Ht from"web-tree-sitter";import*as Sm from"fs";import*as $m from"crypto";var Lh,Eo,_m=g(()=>{"use strict";l();Nn();vm();Lh=Ht.default||Ht.Parser||Ht,Eo=class{treeCache=new Map;maxCacheSize=50;parser=null;grammarManager;constructor(){this.grammarManager=new Ro}hash(e){return $m.createHash("md5").update(e).digest("hex")}async getTree(e,t){let r=t!==void 0?t:Sm.readFileSync(e,"utf-8"),o=this.hash(r),n=this.treeCache.get(e),a=ko(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 Lh),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)}}}});import{parse as qh}from"@babel/parser";import*as Mn from"@babel/traverse";var se,Do,km=g(()=>{"use strict";l();se=Mn.default||Mn,Do=class{parseCode(e){return qh(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,f=c.node.loc?.start.column||0,h=a[m-1]||"";o.push({file:e.filePath,line:m,column:f,context:h.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
  `),f=`
74
74
  function ${a}() {
75
75
  ${m}
76
76
  }
77
- `,h=`${a}();`;return{newFunction:f,replacementCall:h}}async getCallHierarchy(e,t,o){try{let r=this.parseCode(e.content),n=e.filePath,a=null,i="",c=0,p=0;if(se(r,{Function(w){let b=w.node.loc;b&&b.start.line<=t&&b.end&&b.end.line>=t&&(a=w,c=b.start.line,p=b.start.column,w.node.type==="FunctionDeclaration"&&w.node.id?i=w.node.id.name:w.parent.type==="VariableDeclarator"&&w.parent.id.type==="Identifier"?i=w.parent.id.name:w.parent.type==="ClassMethod"||w.parent.type==="ObjectMethod"?w.parent.key.type==="Identifier"&&(i=w.parent.key.name):i="<anonymous>")}}),!a||i==="<anonymous>")return null;let m=[],f=[];se(r,{CallExpression(w){let b=w.node.loc;if(!b||b.start.line<c||b.end&&b.end.line>c+1e3)return;let P=!1,S=w;for(;S;){if(S.isFunction()&&S.node.type==="FunctionDeclaration"&&S.node.id?.name===i){P=!0;break}S=S.parentPath}if(!P)return;let C=w.node.callee,T="<unknown>";C.type==="Identifier"?T=C.name:C.type==="MemberExpression"&&C.property.type==="Identifier"&&(T=C.property.name),T!=="<unknown>"&&f.push({file:n,name:T,line:w.node.loc?.start.line||0,column:w.node.loc?.start.column||0})}}),se(r,{CallExpression(w){let b=w.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 S="<global>",C=w;for(;C;){if(C.isFunction()){C.node.type==="FunctionDeclaration"&&C.node.id?S=C.node.id.name:C.parent.type==="VariableDeclarator"&&C.parent.id.type==="Identifier"?S=C.parent.id.name:(C.parent.type==="ClassMethod"||C.parent.type==="ObjectMethod")&&C.parent.key.type==="Identifier"&&(S=C.parent.key.name);break}C=C.parentPath}m.push({file:n,name:S,line:w.node.loc?.start.line||0,column:w.node.loc?.start.column||0})}}});let h=[...new Map(m.map(w=>[`${w.name}:${w.line}`,w])).values()],x=[...new Map(f.map(w=>[`${w.name}:${w.line}`,w])).values()];return{file:n,name:i,line:c,column:p,callers:h,callees:x}}catch{return null}}}});var _m,km=g(()=>{"use strict";l();_m={}});var No,Rm=g(()=>{"use strict";l();km();No=class{constructor(e){this.context=e}context;async executeQuery(e,t){let{tree:o,language:r,grammar:n}=await this.context.getTree(e.filePath,e.content),a=_m[r];if(!a||!a[t])throw new Error(`Query ${t} not found for language ${r}`);let i=a[t],c=n.query(i);return{tree:o,captures:c.captures(o.rootNode)}}async findSymbols(e,t,o){return(await this.getSymbols(e,o)).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:o}=await this.executeQuery(e,"symbols"),r=[];for(let n of o)if(n.name.startsWith("name.")){let a=n.name.split(".")[1];(!t||t===a)&&r.push({name:n.node.text,kind:a,line:n.node.startPosition.row+1,column:n.node.startPosition.column})}return r}async getImports(e){let{captures:t}=await this.executeQuery(e,"imports"),o=t.filter(n=>n.name==="import").map(n=>n.node),r=[];for(let n of o)r.push({source:n.text,imports:[n.text],line:n.startPosition.row+1,type:"side-effect"});return r}async findReferences(e,t,o){let{captures:r}=await this.executeQuery(e,"references"),n=e.content.split(`
78
- `),a=[];for(let i of r)if(i.node.text===t){let c=i.node.parent?.type.includes("definition")||i.node.parent?.type.includes("declaration");if(!c||o){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,o){let{tree:r}=await this.context.getTree(e.filePath,e.content),n=r.rootNode.descendantForPosition({row:t-1,column:o});return n&&n.type==="identifier"?n.text:null}async getDefinition(e,t){let o=await this.findSymbols(e,t);return o.length>0?o[0]:null}async getDiagnostics(e){let{tree:t}=await this.context.getTree(e.filePath,e.content),o=[];function r(n){if(n.hasError()){n.type==="ERROR"&&o.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)r(a)}else n.isMissing&&n.isMissing()&&o.push({message:`Missing ${n.type} at line ${n.startPosition.row+1}`,line:n.startPosition.row+1,column:n.startPosition.column,severity:"error"})}return r(t.rootNode),o}async getExports(e){return[]}async getOutline(e){return(await this.getSymbols(e)).map(o=>({name:o.name,kind:o.kind,line:o.line,column:o.column,children:[]}))}async extractFunction(e,t,o,r,n,a){let i=e.content.split(`
79
- `),c=Math.max(0,t-1),p=Math.min(i.length,r),m=i.slice(c,p).join(`
80
- `),f="",h="",x=e.filePath.split(".").pop()?.toLowerCase();return x==="py"||x==="pyi"?(f=`
77
+ `,h=`${a}();`;return{newFunction:f,replacementCall:h}}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(w){let x=w.node.loc;x&&x.start.line<=t&&x.end&&x.end.line>=t&&(a=w,c=x.start.line,p=x.start.column,w.node.type==="FunctionDeclaration"&&w.node.id?i=w.node.id.name:w.parent.type==="VariableDeclarator"&&w.parent.id.type==="Identifier"?i=w.parent.id.name:w.parent.type==="ClassMethod"||w.parent.type==="ObjectMethod"?w.parent.key.type==="Identifier"&&(i=w.parent.key.name):i="<anonymous>")}}),!a||i==="<anonymous>")return null;let m=[],f=[];se(o,{CallExpression(w){let x=w.node.loc;if(!x||x.start.line<c||x.end&&x.end.line>c+1e3)return;let P=!1,$=w;for(;$;){if($.isFunction()&&$.node.type==="FunctionDeclaration"&&$.node.id?.name===i){P=!0;break}$=$.parentPath}if(!P)return;let C=w.node.callee,T="<unknown>";C.type==="Identifier"?T=C.name:C.type==="MemberExpression"&&C.property.type==="Identifier"&&(T=C.property.name),T!=="<unknown>"&&f.push({file:n,name:T,line:w.node.loc?.start.line||0,column:w.node.loc?.start.column||0})}}),se(o,{CallExpression(w){let x=w.node.callee,P=!1;if((x.type==="Identifier"&&x.name===i||x.type==="MemberExpression"&&x.property.type==="Identifier"&&x.property.name===i)&&(P=!0),P){let $="<global>",C=w;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:w.node.loc?.start.line||0,column:w.node.loc?.start.column||0})}}});let h=[...new Map(m.map(w=>[`${w.name}:${w.line}`,w])).values()],b=[...new Map(f.map(w=>[`${w.name}:${w.line}`,w])).values()];return{file:n,name:i,line:c,column:p,callers:h,callees:b}}catch{return null}}}});var Rm,Em=g(()=>{"use strict";l();Rm={}});var No,Dm=g(()=>{"use strict";l();Em();No=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=Rm[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
+ `),f="",h="",b=e.filePath.split(".").pop()?.toLowerCase();return b==="py"||b==="pyi"?(f=`
81
81
  def ${a}():
82
82
  ${m.split(`
83
83
  `).map(w=>" "+w).join(`
84
84
  `)}
85
- `,h=`${a}()`):x==="go"?(f=`
85
+ `,h=`${a}()`):b==="go"?(f=`
86
86
  func ${a}() {
87
87
  ${m}
88
88
  }
89
- `,h=`${a}()`):x==="rs"?(f=`
89
+ `,h=`${a}()`):b==="rs"?(f=`
90
90
  fn ${a}() {
91
91
  ${m}
92
92
  }
93
- `,h=`${a}();`):x==="sh"||x==="bash"?(f=`
93
+ `,h=`${a}();`):b==="sh"||b==="bash"?(f=`
94
94
  ${a}() {
95
95
  ${m}
96
96
  }
@@ -98,24 +98,24 @@ ${m}
98
98
  void ${a}() {
99
99
  ${m}
100
100
  }
101
- `,h=`${a}();`),{newFunction:f,replacementCall:h}}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 Ao,Dm=g(()=>{"use strict";l();Nn();$m();Rm();Ao=class{constructor(e){this.context=e;this.babelParser=new Eo,this.treeSitterParser=new No(this.context)}context;babelParser;treeSitterParser;getParser(e){switch(ko(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}`)}}}});import{readFileSync as Ih,statSync as jh,readdirSync as Fh}from"fs";import{join as Lh,extname as qh}from"path";var Mo,Em=g(()=>{"use strict";l();X();Mo=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=Fh(e,{withFileTypes:!0});for(let r of o){let n=Lh(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(qh(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=jh(e).mtimeMs;if(this.fileMtimes.get(e)===o)return;let r=Ih(e,"utf-8"),n=A.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 Uh,A,Ke,X=g(()=>{"use strict";l();Sm();Dm();Em();Uh=new Do,A=new Ao(Uh),Ke=new Mo});import{readFileSync as Wh,statSync as Gh,readdirSync as Bh}from"fs";import{join as Jh,extname as Hh}from"path";async function Nm(s,e,t){try{let o=Wh(s,"utf-8");return await A.getParser(s).findSymbols({filePath:s,content:o},e,t)}catch{return[]}}async function Am(s,e,t){let o=[];try{let r=Bh(s,{withFileTypes:!0});for(let n of r){let a=Jh(s,n.name);if(!(n.name==="node_modules"||n.name===".git"||n.name==="dist")){if(n.isDirectory()){let i=await Am(a,e,t);o.push(...i)}else if(n.isFile()&&zh.includes(Hh(n.name))){let i=await Nm(a,e,t);o.push(...i)}}}}catch{}return o}async function Kh(s){let e=s.symbol,t=s.path,o=s.kind;if(y(`[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=Gh(t),n;if(r.isDirectory())n=await Am(t,e,o);else if(r.isFile())n=await Nm(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 zh,Jt,On=g(()=>{"use strict";l();bm();X();_();zh=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];Jt={name:fm,displayName:gm,description:hm,parameters:wm,category:ym,execute:Kh}});var Mm,Om,Im,jm,Fm,Lm=g(()=>{"use strict";l();Mm="coding.get_symbols",Om="Get Symbols",Im="List all symbols (functions, classes, variables, etc.) in a JavaScript/TypeScript file",jm="coding",Fm={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"]}});import{readFileSync as Qh}from"fs";async function Yh(s){let e=s.file,t=s.kind;if(y(`[coding.get-symbols] execute file="${e}" kind=${t??"all"}`),!e)throw new Error("file is required");try{let o=Qh(e,"utf-8"),n=await A.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 Ht,In=g(()=>{"use strict";l();Lm();X();_();Ht={name:Mm,displayName:Om,description:Im,parameters:Fm,category:jm,execute:Yh}});var qm,Um,Wm,Gm,Bm,Jm=g(()=>{"use strict";l();qm="coding.get_imports",Um="Get Imports",Wm="List all import statements in a JavaScript/TypeScript file",Gm="coding",Bm={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"}},required:["file"]}});import{readFileSync as Vh}from"fs";async function Xh(s){let e=s.file;if(y(`[coding.get-imports] execute file="${e}"`),!e)throw new Error("file is required");try{let t=Vh(e,"utf-8"),r=await A.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 zt,jn=g(()=>{"use strict";l();Jm();X();_();zt={name:qm,displayName:Um,description:Wm,parameters:Bm,category:Gm,execute:Xh}});var Hm,zm,Km,Qm,Ym,Vm=g(()=>{"use strict";l();Hm="coding.find_references",zm="Find References",Km="Find all references to a symbol across JavaScript/TypeScript files",Qm="coding",Ym={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"]}});import{readFileSync as Zh,statSync as ey}from"fs";async function Xm(s,e,t){try{let o=Zh(s,"utf-8");return await A.getParser(s).findReferences({filePath:s,content:o},e,t)}catch{return[]}}async function ty(s,e,t){let o=[];await Ke.buildIndex(s);let r=await Ke.getDefinitionFiles(e,s);for(let n of r)if(n.startsWith(s)){let a=await Xm(n,e,t);o.push(...a)}return o}async function oy(s){let e=s.symbol,t=s.path,o=s.includeDeclaration===!0;if(y(`[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=ey(t),n;if(r.isDirectory())n=await ty(t,e,o);else if(r.isFile())n=await Xm(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 Oo,Fn=g(()=>{"use strict";l();Vm();X();_();Oo={name:Hm,displayName:zm,description:Km,parameters:Ym,category:Qm,execute:oy}});var Zm,ed,td,od,rd,nd=g(()=>{"use strict";l();Zm="coding.go_to_definition",ed="Go To Definition",td="Jump to the definition of a symbol at a specific location in a file",od="coding",rd={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"]}});import{readFileSync as sd,statSync as ry}from"fs";import{dirname as ny}from"path";async function sy(s,e,t){try{let o=sd(s,"utf-8");return await A.getParser(s).getSymbolAtPosition({filePath:s,content:o},e,t)}catch{return null}}async function id(s,e){try{let t=sd(s,"utf-8");return await A.getParser(s).getDefinition({filePath:s,content:t},e)}catch{return null}}async function iy(s,e){await Ke.buildIndex(s);let t=await Ke.getDefinitionFiles(e,s);for(let o of t)if(o.startsWith(s)){let r=await id(o,e);if(r)return r}return null}async function ay(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 sy(e,t,o);if(!n)return JSON.stringify({found:!1,message:`No symbol found at ${e}:${t}:${o}`},null,2);let a=await id(e,n);if(!a){let i=r||ny(e);ry(i).isDirectory()&&(a=await iy(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 Io,Ln=g(()=>{"use strict";l();nd();X();Io={name:Zm,displayName:ed,description:td,parameters:rd,category:od,execute:ay}});var ad,ld,cd,pd,md,dd=g(()=>{"use strict";l();ad="coding.multi_file_edit",ld="Multi-File Edit",cd="Edit multiple files atomically with rollback on failure",pd="coding",md={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"]}});import{readFileSync as ly,writeFileSync as ud,existsSync as cy}from"fs";async function py(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(!cy(n.file))throw new Error(`File does not exist: ${n.file}`)}let o=[],r=[];try{for(let n of e){let a=ly(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(my(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)}ud(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{ud(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 my(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var jo,qn=g(()=>{"use strict";l();dd();jo={name:ad,displayName:ld,description:cd,parameters:md,category:pd,execute:py}});var fd,gd,hd,yd,wd,bd=g(()=>{"use strict";l();fd="coding.refactor_rename",gd="Refactor Rename",hd="Rename a symbol across the entire codebase intelligently",yd="coding",wd={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"]}});import{readFileSync as dy,writeFileSync as uy,readdirSync as fy}from"fs";import{join as gy,extname as hy}from"path";import{parse as yy}from"@babel/parser";import*as Un from"@babel/traverse";function xy(s,e,t,o){let r=[];try{let n=dy(s,"utf-8"),a=n.split(`
102
- `),i=yy(n,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]}),c=[];if(wy(i,{Identifier(p){if(p.node.name===e){let m=p.node.loc?.start.line||0,f=p.node.loc?.start.column||0;c.push({line:m,column:f,length:e.length}),r.push({file:s,line:m,column:f,oldName:e,newName:t})}}}),!o&&c.length>0){c.sort((m,f)=>m.line!==f.line?f.line-m.line:f.column-m.column);let p=[...a];for(let m of c){let f=m.line-1;if(f>=0&&f<p.length){let h=p[f],x=h.substring(0,m.column),w=h.substring(m.column+m.length);p[f]=x+t+w}}uy(s,p.join(`
103
- `),"utf-8")}}catch{}return{file:s,occurrences:r.length,changes:r}}function xd(s,e,t,o){let r=[];try{let n=fy(s,{withFileTypes:!0});for(let a of n){let i=gy(s,a.name);if(!(a.name==="node_modules"||a.name===".git"||a.name==="dist")){if(a.isDirectory())r.push(...xd(i,e,t,o));else if(a.isFile()&&by.includes(hy(a.name))){let c=xy(i,e,t,o);c.occurrences>0&&r.push(c)}}}}catch{}return r}async function Ty(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=xd(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 wy,by,Fo,Wn=g(()=>{"use strict";l();bd();wy=Un.default||Un,by=[".js",".jsx",".ts",".tsx",".mjs",".cjs"];Fo={name:fd,displayName:gd,description:hd,parameters:wd,category:yd,execute:Ty}});var Td,Pd,Cd,vd,Sd,$d=g(()=>{"use strict";l();Td="coding.get_outline",Pd="Get File Outline",Cd="Gets a hierarchical outline of symbols (classes, functions, methods) in a specified file.",vd="coding",Sd={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to outline"}},required:["file"]}});import{readFileSync as Py,statSync as Cy}from"fs";async function vy(s){let e=s.file;if(y(`[coding.get-outline] execute file="${e}"`),!e)throw new Error("file is required");try{if(!Cy(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=Py(e,"utf-8"),o=A.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 Lo,Gn=g(()=>{"use strict";l();$d();X();_();Lo={name:Td,displayName:Pd,description:Cd,parameters:Sd,category:vd,execute:vy}});var _d,kd,Rd,Dd,Ed,Nd=g(()=>{"use strict";l();_d="coding.get_diagnostics",kd="Get File Diagnostics",Rd="Gets syntax errors and warnings for a file utilizing AST parsing.",Dd="coding",Ed={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to check for diagnostics"}},required:["file"]}});import{readFileSync as Sy,statSync as $y}from"fs";async function _y(s){let e=s.file;if(!e)throw new Error("file is required");try{if(!$y(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=Sy(e,"utf-8"),o=A.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 qo,Bn=g(()=>{"use strict";l();Nd();X();qo={name:_d,displayName:kd,description:Rd,parameters:Ed,category:Dd,execute:_y}});var Ad,Md,Od,Id,jd,Fd=g(()=>{"use strict";l();Ad="coding.get_exports",Md="Get File Exports",Od="Lists all symbols exported by a file.",Id="coding",jd={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"}},required:["file"]}});import{readFileSync as ky,statSync as Ry}from"fs";async function Dy(s){let e=s.file;if(y(`[coding.get-exports] execute file="${e}"`),!e)throw new Error("file is required");try{if(!Ry(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=ky(e,"utf-8"),o=A.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 Uo,Jn=g(()=>{"use strict";l();Fd();X();_();Uo={name:Ad,displayName:Md,description:Od,parameters:jd,category:Id,execute:Dy}});var Ld,qd,Ud,Wd,Gd,Bd=g(()=>{"use strict";l();Ld="coding.extract_function",qd="Extract Function",Ud="Extracts a selected code region into a new function, automatically detecting required parameters and return values.",Wd="coding",Gd={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"]}});import{readFileSync as Ey,statSync as Ny}from"fs";async function Ay(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(!Ny(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let i=Ey(e,"utf-8"),c=A.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 Wo,Hn=g(()=>{"use strict";l();Bd();X();Wo={name:Ld,displayName:qd,description:Ud,parameters:Gd,category:Wd,execute:Ay}});var Jd,Hd,zd,Kd,Qd,Yd=g(()=>{"use strict";l();Jd="coding.get_call_hierarchy",Hd="Get Call Hierarchy",zd="Shows callers and callees of a specific function or method.",Kd="coding",Qd={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"]}});import{readFileSync as My,statSync as Oy}from"fs";async function Iy(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(!Oy(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let r=My(e,"utf-8"),n=A.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 Go,zn=g(()=>{"use strict";l();Yd();X();Go={name:Jd,displayName:Hd,description:zd,parameters:Qd,category:Kd,execute:Iy}});var Xd={};re(Xd,{codingExtractFunctionTool:()=>Wo,codingFindReferencesTool:()=>Oo,codingFindSymbolTool:()=>Jt,codingGetCallHierarchyTool:()=>Go,codingGetDiagnosticsTool:()=>qo,codingGetExportsTool:()=>Uo,codingGetImportsTool:()=>zt,codingGetOutlineTool:()=>Lo,codingGetSymbolsTool:()=>Ht,codingGoToDefinitionTool:()=>Io,codingMultiFileEditTool:()=>jo,codingRefactorRenameTool:()=>Fo,codingToolsProject:()=>Vd});var Vd,Kn=g(()=>{"use strict";l();On();In();jn();Fn();Ln();qn();Wn();Gn();Bn();Jn();Hn();zn();On();In();jn();Fn();Ln();qn();Wn();Gn();Bn();Jn();Hn();zn();Vd={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:[Jt,Ht,zt,Oo,Io,Lo,qo,Uo,Wo,Go,jo,Fo],dependencies:{"@babel/parser":"^7.24.0","@babel/traverse":"^7.24.0","@babel/types":"^7.24.0"}}});var Zd,eu=g(()=>{"use strict";l();Zd={type:"object",properties:{path:{type:"string",description:"Optional path or directory to check the status for. If omitted, checks the entire repository."}}}});import{simpleGit as jy}from"simple-git";function q(s){let e={baseDir:s||process.cwd(),binary:"git",maxConcurrentProcesses:6};return jy(e)}var ie=g(()=>{"use strict";l()});var Bo,tu=g(()=>{"use strict";l();eu();ie();Bo={name:"git.status",displayName:"Git Status",description:"Get the working tree status, including modified, staged, and untracked files.",category:"version-control",parameters:Zd,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 ou,ru=g(()=>{"use strict";l();ou={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 Jo,nu=g(()=>{"use strict";l();ru();ie();Jo={name:"git.diff",displayName:"Git Diff",description:"Show changes between commits, commit and working tree, etc.",category:"version-control",parameters:ou,execute:async s=>{let e=s.path,t=s.staged;try{let o=q(),r=[];t&&r.push("--cached"),e&&r.push("--",e);let n=await o.diff(r);return n||"No changes found."}catch(o){return`Error getting git diff: ${o instanceof Error?o.message:String(o)}`}}}});var su,iu=g(()=>{"use strict";l();su={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,au=g(()=>{"use strict";l();iu();ie();Ho={name:"git.log",displayName:"Git Log",description:"Show commit logs.",category:"version-control",parameters:su,execute:async s=>{let e=s.maxCount||10,t=s.path;try{let o=q(),r={maxCount:e};t&&(r.file=t);let n=await o.log(r);return n.all.length===0?"No commits found.":n.all.map(a=>`Commit: ${a.hash}
101
+ `,h=`${a}();`),{newFunction:f,replacementCall:h}}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 Ao,Nm=g(()=>{"use strict";l();Nn();km();Dm();Ao=class{constructor(e){this.context=e;this.babelParser=new Do,this.treeSitterParser=new No(this.context)}context;babelParser;treeSitterParser;getParser(e){switch(ko(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}`)}}}});import{readFileSync as Uh,statSync as Wh,readdirSync as Gh}from"fs";import{join as Bh,extname as Jh}from"path";var Mo,Am=g(()=>{"use strict";l();X();Mo=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=Gh(e,{withFileTypes:!0});for(let o of r){let n=Bh(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(Jh(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=Wh(e).mtimeMs;if(this.fileMtimes.get(e)===r)return;let o=Uh(e,"utf-8"),n=A.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 Hh,A,Ye,X=g(()=>{"use strict";l();_m();Nm();Am();Hh=new Eo,A=new Ao(Hh),Ye=new Mo});import{readFileSync as zh,statSync as Kh,readdirSync as Qh}from"fs";import{join as Yh,extname as Vh}from"path";async function Mm(s,e,t){try{let r=zh(s,"utf-8");return await A.getParser(s).findSymbols({filePath:s,content:r},e,t)}catch{return[]}}async function Om(s,e,t){let r=[];try{let o=Qh(s,{withFileTypes:!0});for(let n of o){let a=Yh(s,n.name);if(!(n.name==="node_modules"||n.name===".git"||n.name==="dist")){if(n.isDirectory()){let i=await Om(a,e,t);r.push(...i)}else if(n.isFile()&&Xh.includes(Vh(n.name))){let i=await Mm(a,e,t);r.push(...i)}}}}catch{}return r}async function Zh(s){let e=s.symbol,t=s.path,r=s.kind;if(y(`[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=Kh(t),n;if(o.isDirectory())n=await Om(t,e,r);else if(o.isFile())n=await Mm(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 Xh,zt,On=g(()=>{"use strict";l();Tm();X();k();Xh=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];zt={name:hm,displayName:ym,description:wm,parameters:xm,category:bm,execute:Zh}});var Im,jm,Fm,Lm,qm,Um=g(()=>{"use strict";l();Im="coding.get_symbols",jm="Get Symbols",Fm="List all symbols (functions, classes, variables, etc.) in a JavaScript/TypeScript file",Lm="coding",qm={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"]}});import{readFileSync as ey}from"fs";async function ty(s){let e=s.file,t=s.kind;if(y(`[coding.get-symbols] execute file="${e}" kind=${t??"all"}`),!e)throw new Error("file is required");try{let r=ey(e,"utf-8"),n=await A.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 Kt,In=g(()=>{"use strict";l();Um();X();k();Kt={name:Im,displayName:jm,description:Fm,parameters:qm,category:Lm,execute:ty}});var Wm,Gm,Bm,Jm,Hm,zm=g(()=>{"use strict";l();Wm="coding.get_imports",Gm="Get Imports",Bm="List all import statements in a JavaScript/TypeScript file",Jm="coding",Hm={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"}},required:["file"]}});import{readFileSync as oy}from"fs";async function ry(s){let e=s.file;if(y(`[coding.get-imports] execute file="${e}"`),!e)throw new Error("file is required");try{let t=oy(e,"utf-8"),o=await A.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 Qt,jn=g(()=>{"use strict";l();zm();X();k();Qt={name:Wm,displayName:Gm,description:Bm,parameters:Hm,category:Jm,execute:ry}});var Km,Qm,Ym,Vm,Xm,Zm=g(()=>{"use strict";l();Km="coding.find_references",Qm="Find References",Ym="Find all references to a symbol across JavaScript/TypeScript files",Vm="coding",Xm={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"]}});import{readFileSync as ny,statSync as sy}from"fs";async function ed(s,e,t){try{let r=ny(s,"utf-8");return await A.getParser(s).findReferences({filePath:s,content:r},e,t)}catch{return[]}}async function iy(s,e,t){let r=[];await Ye.buildIndex(s);let o=await Ye.getDefinitionFiles(e,s);for(let n of o)if(n.startsWith(s)){let a=await ed(n,e,t);r.push(...a)}return r}async function ay(s){let e=s.symbol,t=s.path,r=s.includeDeclaration===!0;if(y(`[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=sy(t),n;if(o.isDirectory())n=await iy(t,e,r);else if(o.isFile())n=await ed(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 Oo,Fn=g(()=>{"use strict";l();Zm();X();k();Oo={name:Km,displayName:Qm,description:Ym,parameters:Xm,category:Vm,execute:ay}});var td,od,rd,nd,sd,id=g(()=>{"use strict";l();td="coding.go_to_definition",od="Go To Definition",rd="Jump to the definition of a symbol at a specific location in a file",nd="coding",sd={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"]}});import{readFileSync as ad,statSync as ly}from"fs";import{dirname as cy}from"path";async function py(s,e,t){try{let r=ad(s,"utf-8");return await A.getParser(s).getSymbolAtPosition({filePath:s,content:r},e,t)}catch{return null}}async function ld(s,e){try{let t=ad(s,"utf-8");return await A.getParser(s).getDefinition({filePath:s,content:t},e)}catch{return null}}async function my(s,e){await Ye.buildIndex(s);let t=await Ye.getDefinitionFiles(e,s);for(let r of t)if(r.startsWith(s)){let o=await ld(r,e);if(o)return o}return null}async function dy(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 py(e,t,r);if(!n)return JSON.stringify({found:!1,message:`No symbol found at ${e}:${t}:${r}`},null,2);let a=await ld(e,n);if(!a){let i=o||cy(e);ly(i).isDirectory()&&(a=await my(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 Io,Ln=g(()=>{"use strict";l();id();X();Io={name:td,displayName:od,description:rd,parameters:sd,category:nd,execute:dy}});var cd,pd,md,dd,ud,fd=g(()=>{"use strict";l();cd="coding.multi_file_edit",pd="Multi-File Edit",md="Edit multiple files atomically with rollback on failure",dd="coding",ud={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"]}});import{readFileSync as uy,writeFileSync as gd,existsSync as fy}from"fs";async function gy(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(!fy(n.file))throw new Error(`File does not exist: ${n.file}`)}let r=[],o=[];try{for(let n of e){let a=uy(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(hy(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)}gd(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{gd(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 hy(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var jo,qn=g(()=>{"use strict";l();fd();jo={name:cd,displayName:pd,description:md,parameters:ud,category:dd,execute:gy}});var hd,yd,wd,bd,xd,Td=g(()=>{"use strict";l();hd="coding.refactor_rename",yd="Refactor Rename",wd="Rename a symbol across the entire codebase intelligently",bd="coding",xd={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"]}});import{readFileSync as yy,writeFileSync as wy,readdirSync as by}from"fs";import{join as xy,extname as Ty}from"path";import{parse as Py}from"@babel/parser";import*as Un from"@babel/traverse";function Sy(s,e,t,r){let o=[];try{let n=yy(s,"utf-8"),a=n.split(`
102
+ `),i=Py(n,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]}),c=[];if(Cy(i,{Identifier(p){if(p.node.name===e){let m=p.node.loc?.start.line||0,f=p.node.loc?.start.column||0;c.push({line:m,column:f,length:e.length}),o.push({file:s,line:m,column:f,oldName:e,newName:t})}}}),!r&&c.length>0){c.sort((m,f)=>m.line!==f.line?f.line-m.line:f.column-m.column);let p=[...a];for(let m of c){let f=m.line-1;if(f>=0&&f<p.length){let h=p[f],b=h.substring(0,m.column),w=h.substring(m.column+m.length);p[f]=b+t+w}}wy(s,p.join(`
103
+ `),"utf-8")}}catch{}return{file:s,occurrences:o.length,changes:o}}function Pd(s,e,t,r){let o=[];try{let n=by(s,{withFileTypes:!0});for(let a of n){let i=xy(s,a.name);if(!(a.name==="node_modules"||a.name===".git"||a.name==="dist")){if(a.isDirectory())o.push(...Pd(i,e,t,r));else if(a.isFile()&&vy.includes(Ty(a.name))){let c=Sy(i,e,t,r);c.occurrences>0&&o.push(c)}}}}catch{}return o}async function $y(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=Pd(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 Cy,vy,Fo,Wn=g(()=>{"use strict";l();Td();Cy=Un.default||Un,vy=[".js",".jsx",".ts",".tsx",".mjs",".cjs"];Fo={name:hd,displayName:yd,description:wd,parameters:xd,category:bd,execute:$y}});var Cd,vd,Sd,$d,_d,kd=g(()=>{"use strict";l();Cd="coding.get_outline",vd="Get File Outline",Sd="Gets a hierarchical outline of symbols (classes, functions, methods) in a specified file.",$d="coding",_d={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to outline"}},required:["file"]}});import{readFileSync as _y,statSync as ky}from"fs";async function Ry(s){let e=s.file;if(y(`[coding.get-outline] execute file="${e}"`),!e)throw new Error("file is required");try{if(!ky(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=_y(e,"utf-8"),r=A.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 Lo,Gn=g(()=>{"use strict";l();kd();X();k();Lo={name:Cd,displayName:vd,description:Sd,parameters:_d,category:$d,execute:Ry}});var Rd,Ed,Dd,Nd,Ad,Md=g(()=>{"use strict";l();Rd="coding.get_diagnostics",Ed="Get File Diagnostics",Dd="Gets syntax errors and warnings for a file utilizing AST parsing.",Nd="coding",Ad={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to check for diagnostics"}},required:["file"]}});import{readFileSync as Ey,statSync as Dy}from"fs";async function Ny(s){let e=s.file;if(!e)throw new Error("file is required");try{if(!Dy(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=Ey(e,"utf-8"),r=A.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 qo,Bn=g(()=>{"use strict";l();Md();X();qo={name:Rd,displayName:Ed,description:Dd,parameters:Ad,category:Nd,execute:Ny}});var Od,Id,jd,Fd,Ld,qd=g(()=>{"use strict";l();Od="coding.get_exports",Id="Get File Exports",jd="Lists all symbols exported by a file.",Fd="coding",Ld={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"}},required:["file"]}});import{readFileSync as Ay,statSync as My}from"fs";async function Oy(s){let e=s.file;if(y(`[coding.get-exports] execute file="${e}"`),!e)throw new Error("file is required");try{if(!My(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=Ay(e,"utf-8"),r=A.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 Uo,Jn=g(()=>{"use strict";l();qd();X();k();Uo={name:Od,displayName:Id,description:jd,parameters:Ld,category:Fd,execute:Oy}});var Ud,Wd,Gd,Bd,Jd,Hd=g(()=>{"use strict";l();Ud="coding.extract_function",Wd="Extract Function",Gd="Extracts a selected code region into a new function, automatically detecting required parameters and return values.",Bd="coding",Jd={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"]}});import{readFileSync as Iy,statSync as jy}from"fs";async function Fy(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(!jy(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let i=Iy(e,"utf-8"),c=A.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 Wo,Hn=g(()=>{"use strict";l();Hd();X();Wo={name:Ud,displayName:Wd,description:Gd,parameters:Jd,category:Bd,execute:Fy}});var zd,Kd,Qd,Yd,Vd,Xd=g(()=>{"use strict";l();zd="coding.get_call_hierarchy",Kd="Get Call Hierarchy",Qd="Shows callers and callees of a specific function or method.",Yd="coding",Vd={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"]}});import{readFileSync as Ly,statSync as qy}from"fs";async function Uy(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(!qy(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let o=Ly(e,"utf-8"),n=A.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 Go,zn=g(()=>{"use strict";l();Xd();X();Go={name:zd,displayName:Kd,description:Qd,parameters:Vd,category:Yd,execute:Uy}});var eu={};re(eu,{codingExtractFunctionTool:()=>Wo,codingFindReferencesTool:()=>Oo,codingFindSymbolTool:()=>zt,codingGetCallHierarchyTool:()=>Go,codingGetDiagnosticsTool:()=>qo,codingGetExportsTool:()=>Uo,codingGetImportsTool:()=>Qt,codingGetOutlineTool:()=>Lo,codingGetSymbolsTool:()=>Kt,codingGoToDefinitionTool:()=>Io,codingMultiFileEditTool:()=>jo,codingRefactorRenameTool:()=>Fo,codingToolsProject:()=>Zd});var Zd,Kn=g(()=>{"use strict";l();On();In();jn();Fn();Ln();qn();Wn();Gn();Bn();Jn();Hn();zn();On();In();jn();Fn();Ln();qn();Wn();Gn();Bn();Jn();Hn();zn();Zd={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:[zt,Kt,Qt,Oo,Io,Lo,qo,Uo,Wo,Go,jo,Fo],dependencies:{"@babel/parser":"^7.24.0","@babel/traverse":"^7.24.0","@babel/types":"^7.24.0"}}});var tu,ou=g(()=>{"use strict";l();tu={type:"object",properties:{path:{type:"string",description:"Optional path or directory to check the status for. If omitted, checks the entire repository."}}}});import{simpleGit as Wy}from"simple-git";function q(s){let e={baseDir:s||process.cwd(),binary:"git",maxConcurrentProcesses:6};return Wy(e)}var ie=g(()=>{"use strict";l()});var Bo,ru=g(()=>{"use strict";l();ou();ie();Bo={name:"git.status",displayName:"Git Status",description:"Get the working tree status, including modified, staged, and untracked files.",category:"version-control",parameters:tu,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 nu,su=g(()=>{"use strict";l();nu={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 Jo,iu=g(()=>{"use strict";l();su();ie();Jo={name:"git.diff",displayName:"Git Diff",description:"Show changes between commits, commit and working tree, etc.",category:"version-control",parameters:nu,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 au,lu=g(()=>{"use strict";l();au={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,cu=g(()=>{"use strict";l();lu();ie();Ho={name:"git.log",displayName:"Git Log",description:"Show commit logs.",category:"version-control",parameters:au,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(o){return`Error getting git log: ${o instanceof Error?o.message:String(o)}`}}}});var lu,cu=g(()=>{"use strict";l();lu={type:"object",properties:{path:{type:"string",description:"Path to the file or directory to stage. To stage all changes, use '.'."}},required:["path"]}});var zo,pu=g(()=>{"use strict";l();cu();ie();zo={name:"git.add",displayName:"Git Add",description:"Add file contents to the index (stage changes).",category:"version-control",parameters:lu,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 mu,du=g(()=>{"use strict";l();mu={type:"object",properties:{message:{type:"string",description:"The commit message."}},required:["message"]}});var Ko,uu=g(()=>{"use strict";l();du();ie();Ko={name:"git.commit",displayName:"Git Commit",description:"Record changes to the repository.",category:"version-control",parameters:mu,execute:async s=>{let e=s.message;try{let o=await q().commit(e);return o.commit?`Successfully committed changes.
110
- Commit: ${o.commit}
111
- Branch: ${o.branch}
112
- Summary: ${o.summary.changes} changes, ${o.summary.insertions} insertions, ${o.summary.deletions} deletions.`:"Nothing to commit."}catch(t){return`Error committing changes: ${t instanceof Error?t.message:String(t)}`}}}});var fu,gu=g(()=>{"use strict";l();fu={type:"object",properties:{path:{type:"string",description:"Path to the file to blame."}},required:["path"]}});var Qo,hu=g(()=>{"use strict";l();gu();ie();Qo={name:"git.blame",displayName:"Git Blame",description:"Show what revision and author last modified each line of a file.",category:"version-control",parameters:fu,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 yu,wu=g(()=>{"use strict";l();yu={type:"object",properties:{remote:{type:"boolean",description:"List remote branches as well.",default:!1}}}});var Yo,bu=g(()=>{"use strict";l();wu();ie();Yo={name:"git.branch_list",displayName:"Git Branch List",description:"List all branches.",category:"version-control",parameters:yu,execute:async s=>{let e=s.remote;try{let t=q(),o=e?["-a"]:[],r=await t.branch(o);return`Current Branch: ${r.current}
109
+ `)}catch(r){return`Error getting git log: ${r instanceof Error?r.message:String(r)}`}}}});var pu,mu=g(()=>{"use strict";l();pu={type:"object",properties:{path:{type:"string",description:"Path to the file or directory to stage. To stage all changes, use '.'."}},required:["path"]}});var zo,du=g(()=>{"use strict";l();mu();ie();zo={name:"git.add",displayName:"Git Add",description:"Add file contents to the index (stage changes).",category:"version-control",parameters:pu,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 uu,fu=g(()=>{"use strict";l();uu={type:"object",properties:{message:{type:"string",description:"The commit message."}},required:["message"]}});var Ko,gu=g(()=>{"use strict";l();fu();ie();Ko={name:"git.commit",displayName:"Git Commit",description:"Record changes to the repository.",category:"version-control",parameters:uu,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 hu,yu=g(()=>{"use strict";l();hu={type:"object",properties:{path:{type:"string",description:"Path to the file to blame."}},required:["path"]}});var Qo,wu=g(()=>{"use strict";l();yu();ie();Qo={name:"git.blame",displayName:"Git Blame",description:"Show what revision and author last modified each line of a file.",category:"version-control",parameters:hu,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 bu,xu=g(()=>{"use strict";l();bu={type:"object",properties:{remote:{type:"boolean",description:"List remote branches as well.",default:!1}}}});var Yo,Tu=g(()=>{"use strict";l();xu();ie();Yo={name:"git.branch_list",displayName:"Git Branch List",description:"List all branches.",category:"version-control",parameters:bu,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
- ${r.all.join(`
116
- `)}`}catch(t){return`Error listing branches: ${t instanceof Error?t.message:String(t)}`}}}});var xu,Tu=g(()=>{"use strict";l();xu={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 Vo,Pu=g(()=>{"use strict";l();Tu();ie();Vo={name:"git.branch_create",displayName:"Git Branch Create",description:"Create a new branch.",category:"version-control",parameters:xu,execute:async s=>{let e=s.name,t=s.checkout,o=s.startPoint;try{let r=q();return t?(o?await r.checkoutBranch(e,o):await r.checkoutLocalBranch(e),`Successfully created and switched to branch: ${e}`):(o?await r.branch([e,o]):await r.branch([e]),`Successfully created branch: ${e}`)}catch(r){return`Error creating branch: ${r instanceof Error?r.message:String(r)}`}}}});var Cu,vu=g(()=>{"use strict";l();Cu={type:"object",properties:{branch:{type:"string",description:"Name of the branch or commit to checkout."}},required:["branch"]}});var Xo,Su=g(()=>{"use strict";l();vu();ie();Xo={name:"git.checkout",displayName:"Git Checkout",description:"Switch branches or restore working tree files.",category:"version-control",parameters:Cu,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 _u={};re(_u,{gitAddTool:()=>zo,gitBlameTool:()=>Qo,gitBranchCreateTool:()=>Vo,gitBranchListTool:()=>Yo,gitCheckoutTool:()=>Xo,gitCommitTool:()=>Ko,gitDiffTool:()=>Jo,gitLogTool:()=>Ho,gitStatusTool:()=>Bo,gitToolsProject:()=>$u});var $u,Qn=g(()=>{"use strict";l();tu();nu();au();pu();uu();hu();bu();Pu();Su();$u={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:[Bo,Jo,Ho,zo,Ko,Qo,Yo,Vo,Xo],dependencies:{"simple-git":"^3.27.0"}}});var ku,Ru=g(()=>{"use strict";l();ku={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"]}});import*as Du from"diff";var Zo,Eu=g(()=>{"use strict";l();Ru();_();Zo={name:"diff.create",displayName:"Create Diff",description:"Generate a unified diff from two text contents.",category:"diff",parameters:ku,execute:async s=>{let e=s.oldContent,t=s.newContent,o=s.fileName||"file",r=s.contextLines??4;y(`[diff.create] execute fileName="${o}" contextLines=${r}`);try{return Du.createPatch(o,e,t,"","",{context:r})}catch(n){return`Error creating diff: ${n instanceof Error?n.message:String(n)}`}}}});var Nu,Au=g(()=>{"use strict";l();Nu={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"]}});import*as Ou from"diff";import{promises as Mu}from"fs";var er,Iu=g(()=>{"use strict";l();Au();_();er={name:"diff.apply",displayName:"Apply Diff",description:"Apply a unified diff patch to a file.",category:"diff",parameters:Nu,execute:async s=>{let e=s.path,t=s.patch;y(`[diff.apply] execute path="${e}"`);try{let o=await Mu.readFile(e,"utf8"),r=Ou.applyPatch(o,t);return r===!1?"Failed to apply patch. The patch may be malformed or conflicting with the current file content.":(await Mu.writeFile(e,r,"utf8"),`Successfully applied patch to ${e}`)}catch(o){return`Error applying patch: ${o instanceof Error?o.message:String(o)}`}}}});var ju,Fu=g(()=>{"use strict";l();ju={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"]}});import*as Lu from"diff";import{promises as Fy}from"fs";var tr,qu=g(()=>{"use strict";l();Fu();tr={name:"diff.preview",displayName:"Preview Diff",description:"Preview the result of applying a patch to a file without modifying it.",category:"diff",parameters:ju,execute:async s=>{let e=s.path,t=s.patch;try{let o=await Fy.readFile(e,"utf8"),r=Lu.applyPatch(o,t);return r===!1?"Patch preview failed. The patch would not apply cleanly.":`Preview of ${e} after patch:
115
+ ${o.all.join(`
116
+ `)}`}catch(t){return`Error listing branches: ${t instanceof Error?t.message:String(t)}`}}}});var Pu,Cu=g(()=>{"use strict";l();Pu={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 Vo,vu=g(()=>{"use strict";l();Cu();ie();Vo={name:"git.branch_create",displayName:"Git Branch Create",description:"Create a new branch.",category:"version-control",parameters:Pu,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 Su,$u=g(()=>{"use strict";l();Su={type:"object",properties:{branch:{type:"string",description:"Name of the branch or commit to checkout."}},required:["branch"]}});var Xo,_u=g(()=>{"use strict";l();$u();ie();Xo={name:"git.checkout",displayName:"Git Checkout",description:"Switch branches or restore working tree files.",category:"version-control",parameters:Su,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 Ru={};re(Ru,{gitAddTool:()=>zo,gitBlameTool:()=>Qo,gitBranchCreateTool:()=>Vo,gitBranchListTool:()=>Yo,gitCheckoutTool:()=>Xo,gitCommitTool:()=>Ko,gitDiffTool:()=>Jo,gitLogTool:()=>Ho,gitStatusTool:()=>Bo,gitToolsProject:()=>ku});var ku,Qn=g(()=>{"use strict";l();ru();iu();cu();du();gu();wu();Tu();vu();_u();ku={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:[Bo,Jo,Ho,zo,Ko,Qo,Yo,Vo,Xo],dependencies:{"simple-git":"^3.27.0"}}});var Eu,Du=g(()=>{"use strict";l();Eu={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"]}});import*as Nu from"diff";var Zo,Au=g(()=>{"use strict";l();Du();k();Zo={name:"diff.create",displayName:"Create Diff",description:"Generate a unified diff from two text contents.",category:"diff",parameters:Eu,execute:async s=>{let e=s.oldContent,t=s.newContent,r=s.fileName||"file",o=s.contextLines??4;y(`[diff.create] execute fileName="${r}" contextLines=${o}`);try{return Nu.createPatch(r,e,t,"","",{context:o})}catch(n){return`Error creating diff: ${n instanceof Error?n.message:String(n)}`}}}});var Mu,Ou=g(()=>{"use strict";l();Mu={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"]}});import*as ju from"diff";import{promises as Iu}from"fs";var er,Fu=g(()=>{"use strict";l();Ou();k();er={name:"diff.apply",displayName:"Apply Diff",description:"Apply a unified diff patch to a file.",category:"diff",parameters:Mu,execute:async s=>{let e=s.path,t=s.patch;y(`[diff.apply] execute path="${e}"`);try{let r=await Iu.readFile(e,"utf8"),o=ju.applyPatch(r,t);return o===!1?"Failed to apply patch. The patch may be malformed or conflicting with the current file content.":(await Iu.writeFile(e,o,"utf8"),`Successfully applied patch to ${e}`)}catch(r){return`Error applying patch: ${r instanceof Error?r.message:String(r)}`}}}});var Lu,qu=g(()=>{"use strict";l();Lu={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"]}});import*as Uu from"diff";import{promises as Gy}from"fs";var tr,Wu=g(()=>{"use strict";l();qu();tr={name:"diff.preview",displayName:"Preview Diff",description:"Preview the result of applying a patch to a file without modifying it.",category:"diff",parameters:Lu,execute:async s=>{let e=s.path,t=s.patch;try{let r=await Gy.readFile(e,"utf8"),o=Uu.applyPatch(r,t);return o===!1?"Patch preview failed. The patch would not apply cleanly.":`Preview of ${e} after patch:
117
117
 
118
- ${r}`}catch(o){return`Error previewing patch: ${o instanceof Error?o.message:String(o)}`}}}});var Wu={};re(Wu,{diffApplyTool:()=>er,diffCreateTool:()=>Zo,diffPreviewTool:()=>tr,diffToolsProject:()=>Uu});var Uu,Yn=g(()=>{"use strict";l();Eu();Iu();qu();Uu={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:[Zo,er,tr],dependencies:{diff:"^7.0.0"}}});var Gu,Bu=g(()=>{"use strict";l();Gu={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 Pe,or=g(()=>{"use strict";l();Pe=class{connectionString;constructor(e){this.connectionString=e}}});import Ju from"better-sqlite3";import*as Vn from"fs";var Kt,Hu=g(()=>{"use strict";l();or();Kt=class extends Pe{getDb(){if(!Vn.existsSync(this.connectionString))throw new Error(`Database file not found: ${this.connectionString}`);return new Ju(this.connectionString,{readonly:!1})}async query(e,t=[]){let o=this.getDb();try{let r=o.prepare(e);return r.reader?r.all(t):(r.run(t),[])}finally{o.close()}}async execute(e,t=[]){let o=this.getDb();try{let n=o.prepare(e).run(t);return{changes:n.changes,lastInsertRowid:n.lastInsertRowid,raw:n}}finally{o.close()}}async getTables(){return(await this.query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")).map(o=>o.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,o=[]){if(!Vn.existsSync(e))throw new Error(`Database file not found: ${e}`);let r=new Ju(e,{readonly:!1});try{let n=r.prepare(t);return n.reader?n.all(o):n.run(o)}finally{r.close()}}}});import Ly from"pg";var rr,zu=g(()=>{"use strict";l();or();rr=class extends Pe{async getClient(){let e=new Ly.Client({connectionString:this.connectionString});return await e.connect(),e}convertSql(e){let t=1;return e.replace(/\?/g,()=>`$${t++}`)}async query(e,t=[]){let o=await this.getClient();try{let r=this.convertSql(e);return(await o.query(r,t)).rows}finally{await o.end()}}async execute(e,t=[]){let o=await this.getClient();try{let r=this.convertSql(e),n=await o.query(r,t);return{changes:n.rowCount??0,raw:n}}finally{await o.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(o=>o.name)}async getSchema(e){return e?await this.query(`
118
+ ${o}`}catch(r){return`Error previewing patch: ${r instanceof Error?r.message:String(r)}`}}}});var Bu={};re(Bu,{diffApplyTool:()=>er,diffCreateTool:()=>Zo,diffPreviewTool:()=>tr,diffToolsProject:()=>Gu});var Gu,Yn=g(()=>{"use strict";l();Au();Fu();Wu();Gu={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:[Zo,er,tr],dependencies:{diff:"^7.0.0"}}});var Ju,Hu=g(()=>{"use strict";l();Ju={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 Pe,or=g(()=>{"use strict";l();Pe=class{connectionString;constructor(e){this.connectionString=e}}});import zu from"better-sqlite3";import*as Vn from"fs";var Yt,Ku=g(()=>{"use strict";l();or();Yt=class extends Pe{getDb(){if(!Vn.existsSync(this.connectionString))throw new Error(`Database file not found: ${this.connectionString}`);return new zu(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(!Vn.existsSync(e))throw new Error(`Database file not found: ${e}`);let o=new zu(e,{readonly:!1});try{let n=o.prepare(t);return n.reader?n.all(r):n.run(r)}finally{o.close()}}}});import By from"pg";var rr,Qu=g(()=>{"use strict";l();or();rr=class extends Pe{async getClient(){let e=new By.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
- `)}}});import qy from"mysql2/promise";var nr,Ku=g(()=>{"use strict";l();or();nr=class extends Pe{async getConnection(){return await qy.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,Ce=g(()=>{"use strict";l();Hu();zu();Ku();G=class{static getAdapter(e){return e.startsWith("postgres://")||e.startsWith("postgresql://")?new rr(e):e.startsWith("mysql://")?new nr(e):e.startsWith("sqlite://")?new Kt(e.replace("sqlite://","")):new Kt(e)}}});var sr,Qu=g(()=>{"use strict";l();Bu();Ce();_();sr={name:"db.query",displayName:"Database Query",description:"Execute raw SQL queries against an SQLite, PostgreSQL, or MySQL database.",category:"database",parameters:Gu,execute:async s=>{let e=s.db,t=s.sql,o=s.params||[];y(`[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 Yu,Vu=g(()=>{"use strict";l();Yu={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 ir,Xu=g(()=>{"use strict";l();Vu();Ce();ir={name:"db.schema",displayName:"Database Schema",description:"Get the structural schema of a database or a specific table.",category:"database",parameters:Yu,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 Zu,ef=g(()=>{"use strict";l();Zu={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"}},required:["db"]}});var ar,tf=g(()=>{"use strict";l();ef();Ce();ar={name:"db.tables",displayName:"Database Tables",description:"List all user tables in the database.",category:"database",parameters:Zu,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 of,rf=g(()=>{"use strict";l();of={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 lr,nf=g(()=>{"use strict";l();rf();Ce();lr={name:"db.insert",displayName:"Database Insert",description:"Insert a new row into an SQLite table safely.",category:"database",parameters:of,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 sf,af=g(()=>{"use strict";l();sf={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 cr,lf=g(()=>{"use strict";l();af();Ce();cr={name:"db.update",displayName:"Database Update",description:"Update existing rows in a database table.",category:"database",parameters:sf,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 cf,pf=g(()=>{"use strict";l();cf={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 pr,mf=g(()=>{"use strict";l();pf();Ce();pr={name:"db.delete",displayName:"Database Delete",description:"Delete rows from a database table.",category:"database",parameters:cf,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 df,uf=g(()=>{"use strict";l();df={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 mr,ff=g(()=>{"use strict";l();uf();Ce();mr={name:"db.count",displayName:"Database Count",description:"Count rows in a database table.",category:"database",parameters:df,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 hf={};re(hf,{dbCountTool:()=>mr,dbDeleteTool:()=>pr,dbInsertTool:()=>lr,dbQueryTool:()=>sr,dbSchemaTool:()=>ir,dbTablesTool:()=>ar,dbToolsProject:()=>gf,dbUpdateTool:()=>cr});var gf,Xn=g(()=>{"use strict";l();Qu();Xu();tf();nf();lf();mf();ff();gf={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:[sr,ir,ar,lr,cr,pr,mr],dependencies:{"better-sqlite3":"^11.3.0"}}});var yf,wf=g(()=>{"use strict";l();yf={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"]}});import{NetlifyAPI as Uy}from"netlify";var ve,dr=g(()=>{"use strict";l();ve=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 Uy(e)}}});var ur,bf=g(()=>{"use strict";l();wf();dr();_();ur={name:"cloud.deploy",displayName:"Cloud Deploy",description:"Deploy a static directory to Netlify.",category:"cloud",parameters:yf,execute:async s=>{let e=s.siteId,t=s.dir,o=s.message;y(`[cloud.deploy] execute siteId="${e}" dir="${t}" message="${o??"none"}"`);try{let n=await ve.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 xf,Tf=g(()=>{"use strict";l();xf={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 fr,Pf=g(()=>{"use strict";l();Tf();dr();fr={name:"cloud.status",displayName:"Cloud Status",description:"Check the status of a specific Netlify deployment.",category:"cloud",parameters:xf,execute:async s=>{let e=s.siteId,t=s.deployId;try{let r=await ve.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 Cf,vf=g(()=>{"use strict";l();Cf={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 gr,Sf=g(()=>{"use strict";l();vf();dr();_();gr={name:"cloud.list",displayName:"Cloud Deployments List",description:"List recent deployments for a Netlify site.",category:"cloud",parameters:Cf,execute:async s=>{let e=s.siteId,t=s.limit||5;y(`[cloud.list] execute siteId="${e}" limit=${t}`);try{let r=await ve.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 _f={};re(_f,{cloudDeployTool:()=>ur,cloudListTool:()=>gr,cloudStatusTool:()=>fr,cloudToolsProject:()=>$f});var $f,Zn=g(()=>{"use strict";l();bf();Pf();Sf();$f={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:[ur,fr,gr],dependencies:{netlify:"^13.1.20"}}});l();ce();l();ce();import{EventEmitter as eg}from"events";l();l();l();var Ie={name:3,displayName:2.5,description:2,category:1.5,parameterNames:1,parameterDescriptions:.5},Xe=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<Ie.name;a++)t.push(e.name);for(let a=0;a<Ie.displayName;a++)t.push(e.displayName);for(let a=0;a<Ie.description;a++)t.push(e.description);for(let a=0;a<Ie.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<Ie.parameterNames;c++)t.push(a);if(i.description)for(let c=0;c<Ie.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=>!Kf.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}}},Kf=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 je=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 Ze="tool.search",Fe={name:Ze,displayName:"Search Tools",category:"meta",description:`Search for available tools by keyword or natural language query.
126
+ `)}}});import Jy from"mysql2/promise";var nr,Yu=g(()=>{"use strict";l();or();nr=class extends Pe{async getConnection(){return await Jy.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,Ce=g(()=>{"use strict";l();Ku();Qu();Yu();G=class{static getAdapter(e){return e.startsWith("postgres://")||e.startsWith("postgresql://")?new rr(e):e.startsWith("mysql://")?new nr(e):e.startsWith("sqlite://")?new Yt(e.replace("sqlite://","")):new Yt(e)}}});var sr,Vu=g(()=>{"use strict";l();Hu();Ce();k();sr={name:"db.query",displayName:"Database Query",description:"Execute raw SQL queries against an SQLite, PostgreSQL, or MySQL database.",category:"database",parameters:Ju,execute:async s=>{let e=s.db,t=s.sql,r=s.params||[];y(`[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 Xu,Zu=g(()=>{"use strict";l();Xu={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 ir,ef=g(()=>{"use strict";l();Zu();Ce();ir={name:"db.schema",displayName:"Database Schema",description:"Get the structural schema of a database or a specific table.",category:"database",parameters:Xu,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 tf,of=g(()=>{"use strict";l();tf={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"}},required:["db"]}});var ar,rf=g(()=>{"use strict";l();of();Ce();ar={name:"db.tables",displayName:"Database Tables",description:"List all user tables in the database.",category:"database",parameters:tf,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 nf,sf=g(()=>{"use strict";l();nf={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 lr,af=g(()=>{"use strict";l();sf();Ce();lr={name:"db.insert",displayName:"Database Insert",description:"Insert a new row into an SQLite table safely.",category:"database",parameters:nf,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 lf,cf=g(()=>{"use strict";l();lf={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 cr,pf=g(()=>{"use strict";l();cf();Ce();cr={name:"db.update",displayName:"Database Update",description:"Update existing rows in a database table.",category:"database",parameters:lf,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 mf,df=g(()=>{"use strict";l();mf={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 pr,uf=g(()=>{"use strict";l();df();Ce();pr={name:"db.delete",displayName:"Database Delete",description:"Delete rows from a database table.",category:"database",parameters:mf,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 ff,gf=g(()=>{"use strict";l();ff={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 mr,hf=g(()=>{"use strict";l();gf();Ce();mr={name:"db.count",displayName:"Database Count",description:"Count rows in a database table.",category:"database",parameters:ff,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 wf={};re(wf,{dbCountTool:()=>mr,dbDeleteTool:()=>pr,dbInsertTool:()=>lr,dbQueryTool:()=>sr,dbSchemaTool:()=>ir,dbTablesTool:()=>ar,dbToolsProject:()=>yf,dbUpdateTool:()=>cr});var yf,Xn=g(()=>{"use strict";l();Vu();ef();rf();af();pf();uf();hf();yf={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:[sr,ir,ar,lr,cr,pr,mr],dependencies:{"better-sqlite3":"^11.3.0"}}});var bf,xf=g(()=>{"use strict";l();bf={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"]}});import{NetlifyAPI as Hy}from"netlify";var ve,dr=g(()=>{"use strict";l();ve=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 Hy(e)}}});var ur,Tf=g(()=>{"use strict";l();xf();dr();k();ur={name:"cloud.deploy",displayName:"Cloud Deploy",description:"Deploy a static directory to Netlify.",category:"cloud",parameters:bf,execute:async s=>{let e=s.siteId,t=s.dir,r=s.message;y(`[cloud.deploy] execute siteId="${e}" dir="${t}" message="${r??"none"}"`);try{let n=await ve.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 Pf,Cf=g(()=>{"use strict";l();Pf={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 fr,vf=g(()=>{"use strict";l();Cf();dr();fr={name:"cloud.status",displayName:"Cloud Status",description:"Check the status of a specific Netlify deployment.",category:"cloud",parameters:Pf,execute:async s=>{let e=s.siteId,t=s.deployId;try{let o=await ve.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 Sf,$f=g(()=>{"use strict";l();Sf={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 gr,_f=g(()=>{"use strict";l();$f();dr();k();gr={name:"cloud.list",displayName:"Cloud Deployments List",description:"List recent deployments for a Netlify site.",category:"cloud",parameters:Sf,execute:async s=>{let e=s.siteId,t=s.limit||5;y(`[cloud.list] execute siteId="${e}" limit=${t}`);try{let o=await ve.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 Rf={};re(Rf,{cloudDeployTool:()=>ur,cloudListTool:()=>gr,cloudStatusTool:()=>fr,cloudToolsProject:()=>kf});var kf,Zn=g(()=>{"use strict";l();Tf();vf();_f();kf={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:[ur,fr,gr],dependencies:{netlify:"^13.1.20"}}});l();ce();l();ce();import{EventEmitter as sg}from"events";l();l();l();var je={name:3,displayName:2.5,description:2,category:1.5,parameterNames:1,parameterDescriptions:.5},et=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<je.name;a++)t.push(e.name);for(let a=0;a<je.displayName;a++)t.push(e.displayName);for(let a=0;a<je.description;a++)t.push(e.description);for(let a=0;a<je.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<je.parameterNames;c++)t.push(a);if(i.description)for(let c=0;c<je.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=>!Zf.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}}},Zf=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 Fe=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 tt="tool.search",Le={name:tt,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 Cr(){return{name:Fe.name,displayName:Fe.displayName,description:Fe.description,parameters:Fe.parameters,category:Fe.category}}function vr(s){return s===Ze}l();var Qf={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 Sr(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 o of e){let n=s.getByCategory(o).length,a=Qf[o]||o;t.push(`- **${o}** (${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 et=class{discoveryCache=new je;async resolve(e,t,o){return o.enabled?o.toolSearch?.enabled?this.resolveWithToolSearch(e,t,o):this.resolveLegacy(t,o):[]}getDiscoveryCache(){return this.discoveryCache}clearDiscoveryCache(){this.discoveryCache.clear()}resolveWithToolSearch(e,t,o){let r=[],n=new Set;r.push(Cr()),n.add(Ze);let a=o.toolSearch?.alwaysLoadedTools??[];for(let c of a){let p=t.get(c);p&&!n.has(c)&&(r.push(this.toSchema(p)),n.add(c))}let i=o.toolSearch?.alwaysLoadedCategories??[];for(let c of i)for(let p of t.getByCategory(c))n.has(p.name)||(r.push(this.toSchema(p)),n.add(p.name));if(o.toolSearch?.cacheDiscoveredTools!==!1){let c=je.fromMessages(e);this.discoveryCache.merge(c);let p=this.discoveryCache.getDiscoveredTools();for(let m of p){let f=t.get(m);f&&!n.has(m)&&f.cacheable!==!1&&(r.push(this.toSchema(f)),n.add(m))}}return r}resolveLegacy(e,t){let o;if(t.enabledTools.length===0&&t.enabledToolCategories.length===0)o=e.getEnabled();else{let r=e.getByNames(t.enabledTools),n=e.getByCategories(t.enabledToolCategories),a=new Set;o=[];for(let i of[...r,...n])a.has(i.name)||(a.add(i.name),o.push(i))}return o.map(r=>this.toSchema(r))}toSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category}}};tt();l();function as(s){if(s.disabled)return"";let e=s.includeWorkingDirectory!==!1,t=s.includeToolCategories!==!1,o=e?`
133
- Working directory: ${s.workingDirectory}`:"",r=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.${o}${r}
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 Cr(){return{name:Le.name,displayName:Le.displayName,description:Le.description,parameters:Le.parameters,category:Le.category}}function vr(s){return s===tt}l();var eg={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 Sr(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=eg[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 ot=class{discoveryCache=new Fe;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(Cr()),n.add(tt);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=Fe.fromMessages(e);this.discoveryCache.merge(c);let p=this.discoveryCache.getDiscoveredTools();for(let m of p){let f=t.get(m);f&&!n.has(m)&&f.cacheable!==!1&&(o.push(this.toSchema(f)),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}}};rt();l();function cs(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 eo=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(),o=this.analyticalPatterns.filter(i=>i.test(t)).length,r=this.actionPatterns.filter(i=>i.test(t)).length,n=o/this.analyticalPatterns.length,a=r/this.actionPatterns.length;return o>r&&o>0?{type:"analytical",confidence:Math.min(n,1),reasoning:`Matched ${o} analytical patterns`}:r>o&&r>0?{type:"action",confidence:Math.min(a,1),reasoning:`Matched ${r} action patterns`}:o===r&&o>0?{type:"analytical",confidence:.5,reasoning:`Mixed query (${o} analytical, ${r} 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 to=class{analyzeDependencies(e){let t=[];for(let o=0;o<e.length;o++){let r=e[o],n=[],a=JSON.stringify(r.arguments).toLowerCase();for(let i=0;i<o;i++){let c=e[i];this.hasDependency(r,c,a)&&n.push(c.id)}t.push({toolCallId:r.id,dependsOn:n})}return t}hasDependency(e,t,o){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&&o.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&&o.includes(t.arguments.url.toLowerCase()))}async executeWithDependencies(e,t,o=5){if(e.length===0)return new Map;let r=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;(r.find(h=>h.toolCallId===p.id)?.dependsOn.every(h=>a.has(h))??!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,o);for(let{id:p,result:m}of c)n.set(p,m),a.add(p)}return n}async executeBatchWithLimit(e,t,o){let r=[];if(e.length<=o){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+=o){let i=e.slice(n,n+o).map(async p=>{let m=await t(p);return{id:p.id,result:m}}),c=await Promise.all(i);r.push(...c)}return r}shouldUseParallelExecution(e){return e.length<2?!1:this.analyzeDependencies(e).filter(r=>r.dependsOn.length===0).length>=2}};_();var ps=0;function kr(){return ps+=1,`${Date.now()}-${ps}`}function no(s,e){Re("debug")&&(y(`[AIClient][${s}] Messages (${e.length}):`),e.forEach((t,o)=>{let r=E(t.content,300);y(`[AIClient][${s}] #${o} role=${t.role} content=${r}`)}))}function so(s){for(let e=s.length-1;e>=0;e--){let t=s[e];if(t?.role!=="user")continue;let o=t?.content;return typeof o=="string"?o:Array.isArray(o)?o.map(r=>r?.type==="text"?r.text:"").filter(Boolean).join(`
140
- `):""}return""}function ms(s){let e=so(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(o=>o.test(e)):!1}function ds(s,e){let t=-1;for(let r=s.length-1;r>=0;r--){let n=s[r];if(n.role==="tool"||n.role==="assistant"&&n.tool_calls&&n.tool_calls.length>0){t=r;break}}if(t===-1)return!1;let o=s.length-1-t;return o>0&&o<=e}function us(s){return{openai:"gpt-4.1-mini",anthropic:"claude-3-haiku-20240307",gemini:"gemini-2.0-flash-exp",ollama:"llama3.2"}[s]||"default"}function tg(s){let e=[],t=0;for(let o=s.length-1;o>=0&&t<2;o--){let r=s[o];if(r.role==="assistant"&&r.tool_calls&&r.tool_calls.length>0){t++;for(let n of r.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 fs(s,e,t,o){let r=kr();y(`[AIClient][${r}] inferNeedsToolsWithAI() provider=${e} model=${o}`);let n=tg(t),i=t.filter(p=>p.role==="user").slice(-1)[0]?.content||"",c=`Recent tool usage: ${n}
139
+ - Only ask the user for clarification when you genuinely cannot determine their intent or lack the required tools`}l();var qe=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 oo=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(h=>h.toolCallId===p.id)?.dependsOn.every(h=>a.has(h))??!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 Re(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 ds=0;function kr(){return ds+=1,`${Date.now()}-${ds}`}function so(s,e){Ee("debug")&&(y(`[AIClient][${s}] Messages (${e.length}):`),e.forEach((t,r)=>{let o=D(t.content,300);y(`[AIClient][${s}] #${r} role=${t.role} content=${o}`)}))}function us(s){let e=Re(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 fs(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 gs(s){return{openai:"gpt-4.1-mini",anthropic:"claude-3-haiku-20240307",gemini:"gemini-2.0-flash-exp",ollama:"llama3.2"}[s]||"default"}function ig(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 hs(s,e,t,r){let o=kr();y(`[AIClient][${o}] inferNeedsToolsWithAI() provider=${e} model=${r}`);let n=ig(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:o,messages:[{role:"user",content:c}],max_tokens:10,temperature:0})).content||"").trim().toUpperCase(),f=m.startsWith("YES");return y(`[AIClient][${r}] inferNeedsToolsWithAI() context="${n}" message="${i.substring(0,50)}" result=${f} (raw: ${m})`),f}catch(p){return D(`[AIClient][${r}] inferNeedsToolsWithAI() error=${p} - falling back to false`),!1}}function gs(s){let e=so(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/],o=[/\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(r=>r.test(e))&&!o.some(r=>r.test(e))}var io=class extends eg{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||z,this.toolRouter=new et,this.bm25Engine=new Xe,this.queryClassifier=new eo,this.toolOrchestrator=new to,this.overrideSystemPrompt=e.systemPrompt,this.disableBaseContext=e.disableBaseContext||!1;let t=this.toolsConfig.resultMaxChars??z.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 H("No provider specified and no default provider configured","NO_PROVIDER_CONFIGURED",400);let o=this.providers.get(t);if(!o)throw new H(`Provider '${t}' not found`,"PROVIDER_NOT_FOUND",404);return o}setDefaultProvider(e){if(!this.providers.has(e))throw new H(`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}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 o=this.getProvider(t);try{let r=kr(),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,f=ms(i.messages),h=this.toolsConfig.intelligentToolDetection,x=!1;if(!f&&h?.enabled&&p&&ds(i.messages,h.maxFollowUpMessages)){v(`[AIClient][${r}] Message is after tool call, using AI to infer tool needs`);let R=us(a||"openai");f=await fs(o,a||"openai",i.messages,R),x=!0}let w=gs(i.messages);!m&&p&&(c==="required"||c==="required_for_actions"&&f)?i.tool_choice="required":!m&&p&&x&&!f&&(i.tool_choice="none",v(`[AIClient][${r}] AI inference determined no tools needed, setting tool_choice=none`));let S=o?.constructor?.name||"UnknownProvider",C={...i,__toolpack_request_id:r};v(`[AIClient][${r}] generate() start provider=${a} class=${S} model=${i.model} messages=${i.messages.length} tools=${i.tools?.length||0} tool_choice=${i.tool_choice??"unset"} policy=${c} needsTools=${f} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),no(r,i.messages);let T=await o.generate(C);if(y(`[AIClient][${r}] generate() initial response finish_reason=${T.finish_reason??"unknown"} tool_calls=${T.tool_calls?.length||0} content_preview=${E(T.content||"",200)}`),this.toolsConfig.enabled&&this.toolsConfig.autoExecute&&this.toolRegistry){let k=so(i.messages),R=this.queryClassifier.classify(k),I=this.toolsConfig.maxToolRounds,U=this.queryClassifier.getToolRoundsAdjustment(R,I);U!==I?v(`[AIClient][${r}] Query classified as ${R.type} (confidence: ${R.confidence.toFixed(2)}), adjusted maxToolRounds: ${I} \u2192 ${U}`):y(`[AIClient][${r}] Query classified as ${R.type} (confidence: ${R.confidence.toFixed(2)}), keeping maxToolRounds: ${U}`);let L=0,j=[...i.messages];for(T.tool_calls&&T.tool_calls.length>0&&v(`[AIClient] Received ${T.tool_calls.length} tool call(s): ${T.tool_calls.map(B=>B.name).join(", ")}`);T.tool_calls&&T.tool_calls.length>0&&L<U;){L++,v(`[AIClient][${r}] generate() tool round ${L}/${U} tool_calls=${T.tool_calls.length}`),j.push({role:"assistant",content:T.content||"",tool_calls:T.tool_calls.map(W=>({id:W.id,type:"function",function:{name:W.name,arguments:JSON.stringify(W.arguments)}}))});let B=this.toolOrchestrator.shouldUseParallelExecution(T.tool_calls),Se=3,de=T.tool_calls,ae=T.tool_calls.filter(W=>W.name==="web.fetch");if(ae.length>Se){v(`[AIClient][${r}] Limiting web.fetch calls from ${ae.length} \u2192 ${Se} to prevent context overflow`);let W=ae.slice(0,Se);de=[...T.tool_calls.filter($=>$.name!=="web.fetch"),...W];let O=ae.slice(Se);for(let $ of O)j.push({role:"tool",tool_call_id:$.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let Z=5e4,le=0;if(B){v(`[AIClient][${r}] Using parallel execution for ${de.length} tools`);let W=await this.toolOrchestrator.executeWithDependencies(de,O=>this.executeTool(O),5),ee=!1;for(let O of de){if(ee){j.push({role:"tool",tool_call_id:O.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let $=W.get(O.id),te=typeof $=="string"?$:JSON.stringify($);if(le+te.length>Z){D(`[AIClient][${r}] Tool output budget exceeded (${Z} chars), adding placeholder for remaining tools`),j.push({role:"tool",tool_call_id:O.id,content:"[Skipped: tool output budget exceeded for this round]"}),ee=!0;continue}let oe=typeof $=="string"&&$.length>this.toolResultMaxChars?`${$.slice(0,this.toolResultMaxChars)}
152
- [TRUNCATED tool result: ${$.length} chars]`:$,$e=typeof oe=="string"?oe:JSON.stringify(oe);le+=$e.length,j.push({role:"tool",tool_call_id:O.id,content:oe})}y(`[AIClient][${r}] Round tool output size: ${le} chars (budget: ${Z})`)}else{v(`[AIClient][${r}] Using sequential execution for ${de.length} tools`);let W=!1;for(let ee of de){if(W){j.push({role:"tool",tool_call_id:ee.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let O=await this.executeTool(ee),$=typeof O=="string"?O:JSON.stringify(O);if(le+$.length>Z){D(`[AIClient][${r}] Tool output budget exceeded (${Z} chars), adding placeholder for remaining tools`),j.push({role:"tool",tool_call_id:ee.id,content:"[Skipped: tool output budget exceeded for this round]"}),W=!0;continue}let te=typeof O=="string"&&O.length>this.toolResultMaxChars?`${O.slice(0,this.toolResultMaxChars)}
153
- [TRUNCATED tool result: ${O.length} chars]`:O,oe=typeof te=="string"?te:JSON.stringify(te);le+=oe.length,j.push({role:"tool",tool_call_id:ee.id,content:te})}y(`[AIClient][${r}] Round tool output size: ${le} chars (budget: ${Z})`)}let Oe={...i,messages:j,__toolpack_request_id:r},ue=await this.enrichRequestWithTools(Oe);ue.tool_choice==="required"&&(ue.tool_choice=w?"none":"auto",v(`[AIClient][${r}] generate() followup tool_choice override required->${ue.tool_choice}`)),Re("debug")&&(y(`[AIClient][${r}] generate() followup request messages=${j.length}`),no(r,j)),T=await o.generate(ue),y(`[AIClient][${r}] generate() followup response finish_reason=${T.finish_reason??"unknown"} tool_calls=${T.tool_calls?.length||0} content_preview=${E(T.content||"",200)}`)}}return T}catch(r){throw this.wrapError(r)}}async*stream(e,t){let o=this.getProvider(t);try{let r=kr(),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,f=ms(i.messages),h=this.toolsConfig.intelligentToolDetection,x=!1;if(!f&&h?.enabled&&p&&ds(i.messages,h.maxFollowUpMessages)){v(`[AIClient][${r}] Message is after tool call, using AI to infer tool needs`);let B=us(n||"openai");f=await fs(o,n||"openai",i.messages,B),x=!0}let w=gs(i.messages);!m&&p&&(c==="required"||c==="required_for_actions"&&f)?i.tool_choice="required":!m&&p&&x&&!f&&(i.tool_choice="none",v(`[AIClient][${r}] AI inference determined no tools needed, setting tool_choice=none`));let S=o?.constructor?.name||"UnknownProvider",C={...i,__toolpack_request_id:r};if(v(`[AIClient][${r}] stream() start provider=${n} class=${S} model=${i.model} messages=${i.messages.length} tools=${i.tools?.length||0} tool_choice=${i.tool_choice??"unset"} policy=${c} needsTools=${f} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),no(r,i.messages),!this.toolsConfig.enabled||!this.toolsConfig.autoExecute||!this.toolRegistry){yield*o.stream(C);return}let T=[...i.messages],k=0,R=so(i.messages),I=this.queryClassifier.classify(R),U=this.toolsConfig.maxToolRounds,L=this.queryClassifier.getToolRoundsAdjustment(I,U);for(L!==U&&v(`[AIClient][${r}] stream() Query classified as ${I.type} (confidence: ${I.confidence.toFixed(2)}), adjusted maxToolRounds: ${U} \u2192 ${L}`);k<=L;){if(e.signal?.aborted){v(`[AIClient][${r}] stream() aborted by signal`);return}let j="",B=[];v(`[AIClient][${r}] stream() round_start ${k+1}/${L}`);let Se=null,de={...C,messages:T},ae=await this.enrichRequestWithTools(de);k>0&&ae.tool_choice==="required"&&(ae.tool_choice=w?"none":"auto",v(`[AIClient][${r}] stream() round_${k+1} tool_choice override required->${ae.tool_choice}`));for await(let $ of o.stream(ae)){if(e.signal?.aborted){v(`[AIClient][${r}] stream() aborted by signal during chunk processing`);return}$.tool_calls&&$.tool_calls.length>0&&(B.push(...$.tool_calls),y(`[AIClient][${r}] stream() tool_calls_chunk count=${$.tool_calls.length} names=${$.tool_calls.map(te=>te.name).join(", ")}`),yield $),$.delta&&(j+=$.delta,yield $),$.finish_reason&&(Se=$.finish_reason),$.finish_reason==="stop"&&(yield $)}if(y(`[AIClient][${r}] stream() round_end finish_reason=${Se??"unknown"} accumulated_len=${j.length} tool_calls_total=${B.length} content_preview=${E(j,200)}`),B.length===0)break;if(v(`[AIClient][${r}] stream() received ${B.length} tool call(s): ${B.map($=>$.name).join(", ")}`),k++,k>L){v(`[AIClient][${r}] stream() max tool rounds (${L}) reached`);break}v(`[AIClient][${r}] stream() tool round ${k}/${L}`),T.push({role:"assistant",content:j||"",tool_calls:B.map($=>({id:$.id,type:"function",function:{name:$.name,arguments:JSON.stringify($.arguments)}}))});let Z=3,le=B,Oe=B.filter($=>$.name==="web.fetch");if(Oe.length>Z){v(`[AIClient][${r}] Limiting web.fetch calls from ${Oe.length} \u2192 ${Z} to prevent context overflow`);let $=Oe.slice(0,Z);le=[...B.filter($e=>$e.name!=="web.fetch"),...$];let oe=Oe.slice(Z);for(let $e of oe)T.push({role:"tool",tool_call_id:$e.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let ue=5e4,W=0,ee=!1,O=[];for(let $ of le){if(ee){T.push({role:"tool",tool_call_id:$.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let te=Date.now(),oe=!1,$e=setInterval(()=>{oe||O.push({delta:""})},500),fe=await this.executeTool($);oe=!0,clearInterval($e);let Lf=Date.now()-te;for(;O.length>0;)yield O.shift();await new Promise(Wf=>setTimeout(Wf,0));let qf=typeof fe=="string"?fe:JSON.stringify(fe);if(W+qf.length>ue){D(`[AIClient][${r}] Tool output budget exceeded (${ue} chars), adding placeholder for remaining tools`),T.push({role:"tool",tool_call_id:$.id,content:"[Skipped: tool output budget exceeded for this round]"}),ee=!0;continue}let _e=typeof fe=="string"&&fe.length>this.toolResultMaxChars?`${fe.slice(0,this.toolResultMaxChars)}
154
- [TRUNCATED tool result: ${fe.length} chars]`:fe,Uf=typeof _e=="string"?_e:JSON.stringify(_e);W+=Uf.length,T.push({role:"tool",tool_call_id:$.id,content:_e}),yield{delta:"",tool_calls:[{...$,result:typeof _e=="string"?_e:JSON.stringify(_e),duration:Lf}]}}y(`[AIClient][${r}] Round tool output size: ${W} chars (budget: ${ue})`),Re("debug")&&(y(`[AIClient][${r}] stream() after_tools messages=${T.length}`),no(r,T))}}catch(r){throw this.wrapError(r)}}async embed(e,t){let o=this.getProvider(t);try{return await o.embed(e)}catch(r){throw this.wrapError(r)}}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 y("[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}:{}}},y(`[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 y(`[AIClient] Request already has ${e.tools.length} tools`),e;let i=await this.toolRouter.resolve(e.messages,this.toolRegistry,t);if(y(`[AIClient] Resolved ${i.length} tools to send: ${i.map(f=>f.name).join(", ")||"none"}`),this.activeMode&&i.length>0){let f=i.length;i=this.filterSchemasByMode(i,this.activeMode);let h=f-i.length;h>0&&v(`[AIClient] Mode "${this.activeMode.displayName}" filtered out ${h} tools`)}let c=new Set(e.tools.map(f=>f.function.name)),p=i.filter(f=>!c.has(f.name)).map(f=>({type:"function",function:{name:f.name,description:f.description,parameters:f.parameters}}));if(p.length===0)return y(`[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 y("[AIClient] Tool registry not configured, skipping tool resolution"),e;let o=this.toolRegistry,r=await this.toolRouter.resolve(e.messages,o,t);if(y(`[AIClient] Resolved ${r.length} tools to send: ${r.map(i=>i.name).join(", ")||"none"}`),this.activeMode&&r.length>0){let i=r.length;r=this.filterSchemasByMode(r,this.activeMode);let c=i-r.length;c>0&&v(`[AIClient] Mode "${this.activeMode.displayName}" filtered out ${c} tools`)}if(r.length===0)return e;let n=r.map(i=>({type:"function",function:{name:i.name,description:i.description,parameters:i.parameters}})),a={...e,tools:n};return this.toolsConfig.toolSearch?.enabled&&o&&(a=this.injectToolSearchPrompt(a)),a}filterSchemasByMode(e,t){return e.filter(o=>{if(t.blockedTools.includes(o.name)||t.blockedToolCategories.includes(o.category))return!1;let r=t.allowedTools.length>0,n=t.allowedToolCategories.length>0;if(r||n){let a=r&&t.allowedTools.includes(o.name),i=n&&t.allowedToolCategories.includes(o.category);return a||i}return!0})}injectModeSystemPrompt(e){if(!this.activeMode||!this.activeMode.systemPrompt)return y(`[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(y(`[AIClient] injectModeSystemPrompt: Injecting mode prompt for ${this.activeMode.name}, length=${t.length}`),e.messages.some(r=>r.role==="system")){let r=e.messages.map(n=>{if(n.role==="system"){let a=typeof n.content=="string"?n.content:"";return{...n,content:`${a}
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(),f=m.startsWith("YES");return y(`[AIClient][${o}] inferNeedsToolsWithAI() context="${n}" message="${i.substring(0,50)}" result=${f} (raw: ${m})`),f}catch(p){return E(`[AIClient][${o}] inferNeedsToolsWithAI() error=${p} - falling back to false`),!1}}function ys(s){let e=Re(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 io=class extends sg{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||z,this.toolRouter=new ot,this.bm25Engine=new et,this.queryClassifier=new qe,this.toolOrchestrator=new oo,this.overrideSystemPrompt=e.systemPrompt,this.disableBaseContext=e.disableBaseContext||!1;let t=this.toolsConfig.resultMaxChars??z.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 H("No provider specified and no default provider configured","NO_PROVIDER_CONFIGURED",400);let r=this.providers.get(t);if(!r)throw new H(`Provider '${t}' not found`,"PROVIDER_NOT_FOUND",404);return r}setDefaultProvider(e){if(!this.providers.has(e))throw new H(`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=kr(),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,f=us(i.messages),h=this.toolsConfig.intelligentToolDetection,b=!1;if(!f&&h?.enabled&&p&&fs(i.messages,h.maxFollowUpMessages)){v(`[AIClient][${o}] Message is after tool call, using AI to infer tool needs`);let R=gs(a||"openai");f=await hs(r,a||"openai",i.messages,R),b=!0}let w=ys(i.messages);!m&&p&&(c==="required"||c==="required_for_actions"&&f)?i.tool_choice="required":!m&&p&&b&&!f&&(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=${f} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),so(o,i.messages);let T=await r.generate(C);if(y(`[AIClient][${o}] generate() initial response finish_reason=${T.finish_reason??"unknown"} tool_calls=${T.tool_calls?.length||0} content_preview=${D(T.content||"",200)}`),this.toolsConfig.enabled&&this.toolsConfig.autoExecute&&this.toolRegistry){let S=Re(i.messages),R=this.queryClassifier.classify(S),I=this.toolsConfig.maxToolRounds,U=this.queryClassifier.getToolRoundsAdjustment(R,I);U!==I?v(`[AIClient][${o}] Query classified as ${R.type} (confidence: ${R.confidence.toFixed(2)}), adjusted maxToolRounds: ${I} \u2192 ${U}`):y(`[AIClient][${o}] Query classified as ${R.type} (confidence: ${R.confidence.toFixed(2)}), keeping maxToolRounds: ${U}`);let L=0,j=[...i.messages];for(T.tool_calls&&T.tool_calls.length>0&&v(`[AIClient] Received ${T.tool_calls.length} tool call(s): ${T.tool_calls.map(B=>B.name).join(", ")}`);T.tool_calls&&T.tool_calls.length>0&&L<U;){L++,v(`[AIClient][${o}] generate() tool round ${L}/${U} tool_calls=${T.tool_calls.length}`),j.push({role:"assistant",content:T.content||"",tool_calls:T.tool_calls.map(W=>({id:W.id,type:"function",function:{name:W.name,arguments:JSON.stringify(W.arguments)}}))});let B=this.toolOrchestrator.shouldUseParallelExecution(T.tool_calls),Se=3,de=T.tool_calls,ae=T.tool_calls.filter(W=>W.name==="web.fetch");if(ae.length>Se){v(`[AIClient][${o}] Limiting web.fetch calls from ${ae.length} \u2192 ${Se} to prevent context overflow`);let W=ae.slice(0,Se);de=[...T.tool_calls.filter(_=>_.name!=="web.fetch"),...W];let O=ae.slice(Se);for(let _ of O)j.push({role:"tool",tool_call_id:_.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let Z=5e4,le=0;if(B){v(`[AIClient][${o}] Using parallel execution for ${de.length} tools`);let W=await this.toolOrchestrator.executeWithDependencies(de,O=>this.executeTool(O),5),ee=!1;for(let O of de){if(ee){j.push({role:"tool",tool_call_id:O.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let _=W.get(O.id),te=typeof _=="string"?_:JSON.stringify(_);if(le+te.length>Z){E(`[AIClient][${o}] Tool output budget exceeded (${Z} chars), adding placeholder for remaining tools`),j.push({role:"tool",tool_call_id:O.id,content:"[Skipped: tool output budget exceeded for this round]"}),ee=!0;continue}let oe=typeof _=="string"&&_.length>this.toolResultMaxChars?`${_.slice(0,this.toolResultMaxChars)}
152
+ [TRUNCATED tool result: ${_.length} chars]`:_,$e=typeof oe=="string"?oe:JSON.stringify(oe);le+=$e.length,j.push({role:"tool",tool_call_id:O.id,content:oe})}y(`[AIClient][${o}] Round tool output size: ${le} chars (budget: ${Z})`)}else{v(`[AIClient][${o}] Using sequential execution for ${de.length} tools`);let W=!1;for(let ee of de){if(W){j.push({role:"tool",tool_call_id:ee.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let O=await this.executeTool(ee),_=typeof O=="string"?O:JSON.stringify(O);if(le+_.length>Z){E(`[AIClient][${o}] Tool output budget exceeded (${Z} chars), adding placeholder for remaining tools`),j.push({role:"tool",tool_call_id:ee.id,content:"[Skipped: tool output budget exceeded for this round]"}),W=!0;continue}let te=typeof O=="string"&&O.length>this.toolResultMaxChars?`${O.slice(0,this.toolResultMaxChars)}
153
+ [TRUNCATED tool result: ${O.length} chars]`:O,oe=typeof te=="string"?te:JSON.stringify(te);le+=oe.length,j.push({role:"tool",tool_call_id:ee.id,content:te})}y(`[AIClient][${o}] Round tool output size: ${le} chars (budget: ${Z})`)}let Ie={...i,messages:j,__toolpack_request_id:o},ue=await this.enrichRequestWithTools(Ie);ue.tool_choice==="required"&&(ue.tool_choice=w?"none":"auto",v(`[AIClient][${o}] generate() followup tool_choice override required->${ue.tool_choice}`)),Ee("debug")&&(y(`[AIClient][${o}] generate() followup request messages=${j.length}`),so(o,j)),T=await r.generate(ue),y(`[AIClient][${o}] generate() followup response finish_reason=${T.finish_reason??"unknown"} tool_calls=${T.tool_calls?.length||0} content_preview=${D(T.content||"",200)}`)}}return T}catch(o){throw this.wrapError(o)}}async*stream(e,t){let r=this.getProvider(t);try{let o=kr(),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,f=us(i.messages),h=this.toolsConfig.intelligentToolDetection,b=!1;if(!f&&h?.enabled&&p&&fs(i.messages,h.maxFollowUpMessages)){v(`[AIClient][${o}] Message is after tool call, using AI to infer tool needs`);let B=gs(n||"openai");f=await hs(r,n||"openai",i.messages,B),b=!0}let w=ys(i.messages);!m&&p&&(c==="required"||c==="required_for_actions"&&f)?i.tool_choice="required":!m&&p&&b&&!f&&(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=${f} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),so(o,i.messages),!this.toolsConfig.enabled||!this.toolsConfig.autoExecute||!this.toolRegistry){yield*r.stream(C);return}let T=[...i.messages],S=0,R=Re(i.messages),I=this.queryClassifier.classify(R),U=this.toolsConfig.maxToolRounds,L=this.queryClassifier.getToolRoundsAdjustment(I,U);for(L!==U&&v(`[AIClient][${o}] stream() Query classified as ${I.type} (confidence: ${I.confidence.toFixed(2)}), adjusted maxToolRounds: ${U} \u2192 ${L}`);S<=L;){if(e.signal?.aborted){v(`[AIClient][${o}] stream() aborted by signal`);return}let j="",B=[];v(`[AIClient][${o}] stream() round_start ${S+1}/${L}`);let Se=null,de={...C,messages:T},ae=await this.enrichRequestWithTools(de);S>0&&ae.tool_choice==="required"&&(ae.tool_choice=w?"none":"auto",v(`[AIClient][${o}] stream() round_${S+1} tool_choice override required->${ae.tool_choice}`));for await(let _ of r.stream(ae)){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),y(`[AIClient][${o}] stream() tool_calls_chunk count=${_.tool_calls.length} names=${_.tool_calls.map(te=>te.name).join(", ")}`),yield _),_.delta&&(j+=_.delta,yield _),_.finish_reason&&(Se=_.finish_reason),_.finish_reason==="stop"&&(yield _)}if(y(`[AIClient][${o}] stream() round_end finish_reason=${Se??"unknown"} accumulated_len=${j.length} tool_calls_total=${B.length} content_preview=${D(j,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}`),T.push({role:"assistant",content:j||"",tool_calls:B.map(_=>({id:_.id,type:"function",function:{name:_.name,arguments:JSON.stringify(_.arguments)}}))});let Z=3,le=B,Ie=B.filter(_=>_.name==="web.fetch");if(Ie.length>Z){v(`[AIClient][${o}] Limiting web.fetch calls from ${Ie.length} \u2192 ${Z} to prevent context overflow`);let _=Ie.slice(0,Z);le=[...B.filter($e=>$e.name!=="web.fetch"),..._];let oe=Ie.slice(Z);for(let $e of oe)T.push({role:"tool",tool_call_id:$e.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let ue=5e4,W=0,ee=!1,O=[];for(let _ of le){if(ee){T.push({role:"tool",tool_call_id:_.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let te=Date.now(),oe=!1,$e=setInterval(()=>{oe||O.push({delta:""})},500),fe=await this.executeTool(_);oe=!0,clearInterval($e);let Bf=Date.now()-te;for(;O.length>0;)yield O.shift();await new Promise(zf=>setTimeout(zf,0));let Jf=typeof fe=="string"?fe:JSON.stringify(fe);if(W+Jf.length>ue){E(`[AIClient][${o}] Tool output budget exceeded (${ue} chars), adding placeholder for remaining tools`),T.push({role:"tool",tool_call_id:_.id,content:"[Skipped: tool output budget exceeded for this round]"}),ee=!0;continue}let _e=typeof fe=="string"&&fe.length>this.toolResultMaxChars?`${fe.slice(0,this.toolResultMaxChars)}
154
+ [TRUNCATED tool result: ${fe.length} chars]`:fe,Hf=typeof _e=="string"?_e:JSON.stringify(_e);W+=Hf.length,T.push({role:"tool",tool_call_id:_.id,content:_e}),yield{delta:"",tool_calls:[{..._,result:typeof _e=="string"?_e:JSON.stringify(_e),duration:Bf}]}}y(`[AIClient][${o}] Round tool output size: ${W} chars (budget: ${ue})`),Ee("debug")&&(y(`[AIClient][${o}] stream() after_tools messages=${T.length}`),so(o,T))}}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 y("[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}:{}}},y(`[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 y(`[AIClient] Request already has ${e.tools.length} tools`),e;let i=await this.toolRouter.resolve(e.messages,this.toolRegistry,t);if(y(`[AIClient] Resolved ${i.length} tools to send: ${i.map(f=>f.name).join(", ")||"none"}`),this.activeMode&&i.length>0){let f=i.length;i=this.filterSchemasByMode(i,this.activeMode);let h=f-i.length;h>0&&v(`[AIClient] Mode "${this.activeMode.displayName}" filtered out ${h} tools`)}let c=new Set(e.tools.map(f=>f.function.name)),p=i.filter(f=>!c.has(f.name)).map(f=>({type:"function",function:{name:f.name,description:f.description,parameters:f.parameters}}));if(p.length===0)return y(`[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 y("[AIClient] Tool registry not configured, skipping tool resolution"),e;let r=this.toolRegistry,o=await this.toolRouter.resolve(e.messages,r,t);if(y(`[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 y(`[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(y(`[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:r}}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(r=>r.role==="system")){let r=e.messages.map(n=>{if(n.role==="system"){let a=typeof n.content=="string"?n.content:"";return{...n,content:`${a}
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:r}}else return{...e,messages:[{role:"system",content:t},...e.messages]}}injectBaseAgentContext(e){let t=!0,o=!0,r,n=this.disableBaseContext;if(this.activeMode?.baseContext===!1)return e;this.activeMode?.baseContext&&(t=this.activeMode.baseContext.includeWorkingDirectory!==!1,o=this.activeMode.baseContext.includeToolCategories!==!1,r=this.activeMode.baseContext.custom);let a=r||as({workingDirectory:process.cwd(),toolCategories:this.toolRegistry?this.toolRegistry.getCategories():[],disabled:n,includeWorkingDirectory:t,includeToolCategories:o});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}
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||cs({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"),o=this.toolsConfig.toolSearch?.alwaysLoadedTools??[],r="";if(o.length>0){let a=o.map(i=>{let c=this.toolRegistry?.get(i);return c?` - **${c.name}**: ${c.description}`:null}).filter(Boolean).join(`
161
- `);a&&(r=`
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,7 +166,7 @@ ${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.${r}
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
  ${Sr(this.toolRegistry)}
172
172
 
@@ -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: ${E(e.arguments,500)}`),!this.toolRegistry){let r="No tool registry configured";return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:r,duration:Date.now()-t}),JSON.stringify({error:r})}if(vr(e.name)){let r=this.executeToolSearch(e.arguments),n=Date.now()-t;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof r=="string"?r.substring(0,200):JSON.stringify(r).substring(0,200),duration:n}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:r,duration:n,status:"success",timestamp:Date.now()}),r}let o=this.toolRegistry.get(e.name);if(!o){D(`[AIClient] Tool '${e.name}' not found in registry`);let r=this.findSimilarToolName(e.name),n=r?`Tool '${e.name}' not found. Did you mean '${r}'? 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 r={workspaceRoot:process.cwd(),config:this.toolsConfig?.additionalConfigurations??{},log:i=>v(`[Tool] ${i}`)},n=await o.execute(e.arguments,r),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}`),Re("debug")&&y(`[AIClient] Tool ${e.name} result_preview=${E(n,400)}`),n}catch(r){let n=Date.now()-t,a=r.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()}),Q(`[AIClient] Tool ${e.name} failed: ${E(a,300)}`),JSON.stringify({error:a})}}findSimilarToolName(e){if(!this.toolRegistry)return null;let t=this.toolRegistry.getAll(),o=e.replace(/_/g,".");if(t.some(c=>c.name===o))return o;let r=e.replace(/\./g,"_");if(t.some(c=>c.name===r))return r;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 o=[];for(let r=0;r<=t.length;r++)o[r]=[r];for(let r=0;r<=e.length;r++)o[0][r]=r;for(let r=1;r<=t.length;r++)for(let n=1;n<=e.length;n++)t.charAt(r-1)===e.charAt(n-1)?o[r][n]=o[r-1][n-1]:o[r][n]=Math.min(o[r-1][n-1]+1,o[r][n-1]+1,o[r-1][n]+1);return o[t.length][e.length]}executeToolSearch(e){let{query:t,category:o}=e,r=this.toolsConfig.toolSearch?.searchResultLimit??5;v(`[AIClient] Executing tool.search: query="${t}" category=${o||"all"} limit=${r}`);let n=this.bm25Engine.search(t,{limit:r,category:o}),a=n.map(i=>i.toolName);return this.toolRouter.getDiscoveryCache().recordDiscovery(t,a),y(`[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 H?e:new F(e.message||"Unknown provider error","UNKNOWN_PROVIDER_ERROR",500,e)}};l();l();import Cs from"@anthropic-ai/sdk";l();ce();var Y=class{name;async getModels(){return[]}getDisplayName(){return this.name||this.constructor.name.replace(/Adapter$/,"")}supportsFileUpload(){return!1}async uploadFile(e){throw new M(`File upload API is not supported by ${this.getDisplayName()}`)}async deleteFile(e){throw new M(`File deletion API is not supported by ${this.getDisplayName()}`)}};ce();_();var ao=class extends Y{client;constructor(e,t){super(),this.client=new Cs({apiKey:e,baseURL:t})}supportsFileUpload(){return!0}async uploadFile(e){try{let t=await import("fs");if(!e.filePath)throw new M("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(r=>this.sanitizeToolName(r.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,o=await this.toAnthropicMessages(e.messages,e.mediaOptions),r=o.system,n=o.userMessages,a={model:e.model,messages:n,system:r,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"},y(`[Anthropic][${t}] Sending ${a.tools?.length||0} tools with tool_choice: ${a.tool_choice?.type||"unset"}`),a.tools&&a.tools.length>0&&y(`[Anthropic][${t}] First tool: ${E(a.tools[0],800)}`)):y(`[Anthropic][${t}] NO TOOLS in request`),y(`[Anthropic][${t}] generate() request: model=${a.model}, messages=${a.messages.length}, tools=${a.tools?.length||0}, tool_choice=${a.tool_choice?.type??"unset"}`),V(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 y(`[Anthropic][${t}] Response finish_reason=${i.stop_reason} tool_calls=${p.length} content_preview=${E(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()}`,o=await this.toAnthropicMessages(e.messages,e.mediaOptions),r={model:e.model,messages:o.userMessages,system:o.system,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p,stream:!0};e.tools&&e.tools.length>0?(r.tools=e.tools.map(m=>({name:this.sanitizeToolName(m.function.name),description:m.function.description,input_schema:m.function.parameters})),e.tool_choice==="required"?r.tool_choice={type:"any"}:e.tool_choice==="none"?delete r.tools:r.tool_choice={type:"auto"},y(`[Anthropic][${t}] Sending ${r.tools?.length||0} tools with tool_choice: ${r.tool_choice?.type||"unset"}`),r.tools&&r.tools.length>0&&y(`[Anthropic][${t}] First tool: ${E(r.tools[0],800)}`)):y(`[Anthropic][${t}] NO TOOLS in request`),y(`[Anthropic][${t}] Stream request: model=${r.model}, messages=${r.messages.length}, tools=${r.tools?.length||0}, tool_choice=${r.tool_choice?.type??"unset"}`),V(t,"Anthropic",r.messages);let n=await this.client.messages.create(r,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&&(y(`[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"&&(ye(`[Anthropic][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"})}catch(t){throw this.handleError(t)}}async embed(e){throw new M("Embeddings are not strictly supported by the Anthropic API currently.")}async toAnthropicMessages(e,t={}){let o,r=[],{normalizeImagePart:n}=await Promise.resolve().then(()=>(Le(),rt));for(let a of e)if(a.role==="system"){if(typeof a.content=="string")o=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&&(o=i)}}else if(a.role==="tool"&&a.tool_call_id)r.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});r.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)),r.push({role:a.role==="user"?"user":"assistant",content:i})}return{system:o,userMessages:r}}mapFinishReason(e){return e==="end_turn"?"stop":e==="max_tokens"?"length":e==="stop_sequence"?"stop":e}handleError(e){if(e instanceof Cs.APIError){let t=e.message;return e.status===401?new ge(t,e):e.status===429?new he(t,void 0,e):e.status&&e.status>=400&&e.status<500?new M(t,e):new F(t,"ANTHROPIC_ERROR",e.status||500,e)}return new F("Unknown Anthropic error","UNKNOWN",500,e)}};l();import{GoogleGenerativeAI as sg}from"@google/generative-ai";ce();_();var lo=class extends Y{genAI;constructor(e){super(),this.genAI=new sg(e)}supportsFileUpload(){return!0}sanitizeSchema(e){if(!e||typeof e!="object")return e;let t={};for(let[o,r]of Object.entries(e))o==="additionalProperties"||o==="exclusiveMinimum"||o==="exclusiveMaximum"||o==="$schema"||o==="$id"||o==="definitions"||o==="$defs"||(typeof r=="object"&&r!==null?Array.isArray(r)?t[o]=r.map(n=>this.sanitizeSchema(n)):t[o]=this.sanitizeSchema(r):t[o]=r);return t}async uploadFile(e){try{let t=await import("fs"),o=await import("path");if(!e.filePath)throw new M("Gemini uploadFile requires a filePath.");let r=await t.promises.readFile(e.filePath),n=o.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}}),f=Buffer.concat([Buffer.from(`--${p}\r
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(vr(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}`),Ee("debug")&&y(`[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()}),Q(`[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),y(`[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 H?e:new F(e.message||"Unknown provider error","UNKNOWN_PROVIDER_ERROR",500,e)}};l();l();import Ss from"@anthropic-ai/sdk";l();ce();var Y=class{name;async getModels(){return[]}getDisplayName(){return this.name||this.constructor.name.replace(/Adapter$/,"")}supportsFileUpload(){return!1}async uploadFile(e){throw new M(`File upload API is not supported by ${this.getDisplayName()}`)}async deleteFile(e){throw new M(`File deletion API is not supported by ${this.getDisplayName()}`)}};ce();k();var ao=class extends Y{client;constructor(e,t){super(),this.client=new Ss({apiKey:e,baseURL:t})}supportsFileUpload(){return!0}async uploadFile(e){try{let t=await import("fs");if(!e.filePath)throw new M("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"},y(`[Anthropic][${t}] Sending ${a.tools?.length||0} tools with tool_choice: ${a.tool_choice?.type||"unset"}`),a.tools&&a.tools.length>0&&y(`[Anthropic][${t}] First tool: ${D(a.tools[0],800)}`)):y(`[Anthropic][${t}] NO TOOLS in request`),y(`[Anthropic][${t}] generate() request: model=${a.model}, messages=${a.messages.length}, tools=${a.tools?.length||0}, tool_choice=${a.tool_choice?.type??"unset"}`),V(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 y(`[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"},y(`[Anthropic][${t}] Sending ${o.tools?.length||0} tools with tool_choice: ${o.tool_choice?.type||"unset"}`),o.tools&&o.tools.length>0&&y(`[Anthropic][${t}] First tool: ${D(o.tools[0],800)}`)):y(`[Anthropic][${t}] NO TOOLS in request`),y(`[Anthropic][${t}] Stream request: model=${o.model}, messages=${o.messages.length}, tools=${o.tools?.length||0}, tool_choice=${o.tool_choice?.type??"unset"}`),V(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&&(y(`[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"&&(ye(`[Anthropic][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"})}catch(t){throw this.handleError(t)}}async embed(e){throw new M("Embeddings are not strictly supported by the Anthropic API currently.")}async toAnthropicMessages(e,t={}){let r,o=[],{normalizeImagePart:n}=await Promise.resolve().then(()=>(Ue(),st));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 Ss.APIError){let t=e.message;return e.status===401?new ge(t,e):e.status===429?new he(t,void 0,e):e.status&&e.status>=400&&e.status<500?new M(t,e):new F(t,"ANTHROPIC_ERROR",e.status||500,e)}return new F("Unknown Anthropic error","UNKNOWN",500,e)}};l();import{GoogleGenerativeAI as pg}from"@google/generative-ai";ce();k();var lo=class extends Y{genAI;constructor(e){super(),this.genAI=new pg(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 M("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}}),f=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
- `),r,Buffer.from(`\r
190
+ `),o,Buffer.from(`\r
191
191
  --${p}--\r
192
- `)]),h=await fetch(c,{method:"POST",headers:{"Content-Type":`multipart/related; boundary=${p}`},body:f});if(!h.ok){let w=await h.text();throw new Error(`Gemini file upload failed: ${h.status} ${w}`)}let x=await h.json();return{id:x.file?.name||x.name,url:x.file?.uri||x.uri}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{let t=this.genAI.apiKey,o=`https://generativelanguage.googleapis.com/v1beta/${e}?key=${t}`,r=await fetch(o,{method:"DELETE"});if(!r.ok){let n=await r.text();throw new Error(`Gemini file deletion failed: ${r.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(r=>this.sanitizeToolName(r.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,o={model:e.model,systemInstruction:this.extractSystemInstruction(e.messages)};e.tools&&e.tools.length>0?(o.tools=[{functionDeclarations:e.tools.map(h=>({name:this.sanitizeToolName(h.function.name),description:h.function.description,parameters:this.sanitizeSchema(h.function.parameters)}))}],y(`[Gemini][${t}] Sending ${e.tools.length} tools`),e.tools.length>0&&y(`[Gemini][${t}] First tool: ${E(e.tools[0],800)}`)):y(`[Gemini][${t}] NO TOOLS in request`),y(`[Gemini][${t}] generate() request: model=${e.model}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),V(t,"Gemini",e.messages);let r=this.genAI.getGenerativeModel(o),{history:n,lastUserMessage:a}=await this.formatHistory(e.messages,e.mediaOptions),p=await(await r.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=[],f="";for(let h of p.candidates||[])for(let x of h.content?.parts||[])if(x.text&&(f+=x.text),x.functionCall){let w=x.functionCall;m.push({id:`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(w.name,e.tools),arguments:w.args||{}})}return y(`[Gemini][${t}] Response finish_reason=${m.length>0?"tool_calls":"stop"} tool_calls=${m.length} content_preview=${E(f,200)}`),{content:f||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 o=e.__toolpack_request_id||`str-${Date.now()}`;y(`[Gemini][${o}] Stream request: model=${e.model}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),e.tools&&e.tools.length>0&&y(`[Gemini][${o}] First tool: ${E(e.tools[0],800)}`),V(o,"Gemini",e.messages);let r=this.genAI.getGenerativeModel(t),{history:n,lastUserMessage:a}=await this.formatHistory(e.messages,e.mediaOptions),c=await r.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?(y(`[Gemini][${o}] 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(f=>f.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 r=>(await t.embedContent(r)).embedding.values))}:{embeddings:[(await t.embedContent(e.input)).embedding.values]}}catch(t){throw this.handleError(t)}}extractSystemInstruction(e){let t=e.filter(o=>o.role==="system");if(t.length!==0)return t.map(o=>typeof o.content=="string"?o.content:o.content===null?"":o.content.map(r=>r.text).join(`
192
+ `)]),h=await fetch(c,{method:"POST",headers:{"Content-Type":`multipart/related; boundary=${p}`},body:f});if(!h.ok){let w=await h.text();throw new Error(`Gemini file upload failed: ${h.status} ${w}`)}let b=await h.json();return{id:b.file?.name||b.name,url:b.file?.uri||b.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(h=>({name:this.sanitizeToolName(h.function.name),description:h.function.description,parameters:this.sanitizeSchema(h.function.parameters)}))}],y(`[Gemini][${t}] Sending ${e.tools.length} tools`),e.tools.length>0&&y(`[Gemini][${t}] First tool: ${D(e.tools[0],800)}`)):y(`[Gemini][${t}] NO TOOLS in request`),y(`[Gemini][${t}] generate() request: model=${e.model}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),V(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=[],f="";for(let h of p.candidates||[])for(let b of h.content?.parts||[])if(b.text&&(f+=b.text),b.functionCall){let w=b.functionCall;m.push({id:`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(w.name,e.tools),arguments:w.args||{}})}return y(`[Gemini][${t}] Response finish_reason=${m.length>0?"tool_calls":"stop"} tool_calls=${m.length} content_preview=${D(f,200)}`),{content:f||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()}`;y(`[Gemini][${r}] Stream request: model=${e.model}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),e.tools&&e.tools.length>0&&y(`[Gemini][${r}] First tool: ${D(e.tools[0],800)}`),V(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?(y(`[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(f=>f.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 o=e.filter(m=>m.role!=="system");if(o.length===0)return{history:[],lastUserMessage:""};let r=o[o.length-1],n=o.slice(0,o.length-1),{normalizeImagePart:a}=await Promise.resolve().then(()=>(Le(),rt)),i=async m=>typeof m=="string"?[{text:m}]:m===null?[]:(await Promise.all(m.map(async h=>{if(h.type==="text")return{text:h.text};if(h.type==="image_data"||h.type==="image_file"||h.type==="image_url")try{let{data:x,mimeType:w}=await a(h);return{inlineData:{mimeType:w,data:x}}}catch{return h.type==="image_url"?{text:`[Image: ${h.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 f=[];if(typeof m.content=="string"&&m.content)f.push({text:m.content});else if(Array.isArray(m.content)){let h=m.content.filter(x=>typeof x=="object"&&x.type==="text").map(x=>x.text).join(`
195
- `);h&&f.push({text:h})}for(let h of m.tool_calls)f.push({functionCall:{name:this.sanitizeToolName(h.function.name),args:typeof h.function.arguments=="string"?JSON.parse(h.function.arguments||"{}"):h.function.arguments}});return{role:"model",parts:f}}return{role:m.role==="user"?"user":"model",parts:await i(m.content)}})),p=typeof r.content=="string"?r.content:await i(r.content);return{history:c,lastUserMessage:p}}handleError(e){return e.status===429?new he(e.message,void 0,e):e.status>=400&&e.status<500?new M(e.message,e):e.message&&e.message.includes("API key")?new ge(e.message,e):new F(e.message||"Gemini Error","GEMINI_ERROR",e.status||500,e)}};l();import*as st from"fs";import*as vs from"path";var ig="toolpack.config.json";function Rr(s){if(s&&st.existsSync(s))return s;let e=vs.join(process.cwd(),ig);return st.existsSync(e)?e:null}function ag(s){if(!s)return null;try{let e=st.readFileSync(s,"utf-8");return JSON.parse(e)}catch{return null}}var nt=null;function Dr(s){if(nt)return nt;let e=s||Rr();return nt=ag(e)||{},nt}function lg(){nt=null}function cg(s){return(Dr(s).ollama?.models||[]).map(o=>({type:`ollama-${o.model.replace(/[:.]/g,"-")}`,model:o.model,label:o.label||o.model}))}function co(s){return Dr(s).ollama?.baseUrl||"http://localhost:11434"}l();l();ce();_();l();import Ss from"http";function ne(s,e,t,o,r=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:r},p=Ss.request(c,m=>{let f=[];m.on("data",h=>f.push(h)),m.on("end",()=>{n({status:m.statusCode||0,body:Buffer.concat(f).toString("utf-8")})})});p.on("error",m=>a(m)),p.on("timeout",()=>{p.destroy(),a(new Error("Request timed out"))}),o&&p.write(JSON.stringify(o)),p.end()})}function Er(s,e,t,o=12e4,r){let n,a=!1;return r&&r.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:o},m=await new Promise((h,x)=>{n=Ss.request(p,h),n.on("error",x),n.on("timeout",()=>{n.destroy(),x(new Error("Stream request timed out"))}),n.write(JSON.stringify(t)),n.end()});if(m.statusCode&&m.statusCode>=400){let h="";for await(let x of m)h+=x.toString();throw new Error(`Ollama HTTP ${m.statusCode}: ${h}`)}let f="";for await(let h of m){if(a)break;let x=h.toString();if(f+=x,f.includes('"error"'))try{let b=JSON.parse(f.trim());if(b.error)throw new Error(`Ollama: ${b.error}`)}catch(b){if(b.message.startsWith("Ollama:"))throw b}let w=f.split(`
196
- `);f=w.pop()||"";for(let b of w)b.trim()&&(yield b)}f.trim()&&!a&&(yield f.trim())}(),abort:()=>{a=!0,n&&n.destroy()}}}var De=class extends Y{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(r=>r.name.split(":")[0].toLowerCase()===t||r.name.toLowerCase()===this.config.model.toLowerCase()))throw new M(`Model "${this.config.model}" is not pulled in Ollama. Run: ollama pull ${this.config.model}
197
- Available models: ${e.map(r=>r.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 F(`Ollama returned status ${e.status}`,"OLLAMA_ERROR",e.status);return JSON.parse(e.body).models||[]}catch(e){throw e instanceof F?e:new ke(`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(),o=(e||this.config.model).toLowerCase(),r=o.split(":")[0];return t.some(n=>n.name.split(":")[0].toLowerCase()===r||n.name.toLowerCase()===o)}catch{return!1}}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(r=>this.sanitizeToolName(r.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){let t=e.__toolpack_request_id||`gen-${Date.now()}`,o=await Promise.all(e.messages.map(a=>this.toOllamaMessage(a,e.mediaOptions))),r=e.model||this.config.model,n={model:r,messages:o,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}})),y(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&y(`[Ollama][${t}] First tool: ${E(e.tools[0],800)}`),y(`[Ollama][${t}] NO TOOLS in request`)),y(`[Ollama][${t}] generate() request: model=${r}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),V(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 y(`[Ollama][${t}] Response finish_reason=${p.finish_reason} tool_calls=${c.length} content_preview=${E(p.content,200)}`),p}catch(a){throw a instanceof F?a:new ke(`Failed to generate with Ollama model "${r}": ${a.message}`,a)}}async*stream(e){let t=e.__toolpack_request_id||`str-${Date.now()}`,o=await Promise.all(e.messages.map(i=>this.toOllamaMessage(i,e.mediaOptions))),r=e.model||this.config.model,n={model:r,messages:o,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}})),y(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&y(`[Ollama][${t}] First tool: ${E(e.tools[0],800)}`),y(`[Ollama][${t}] NO TOOLS in request`)),y(`[Ollama][${t}] Stream request: model=${r}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),V(t,"Ollama",e.messages);let{stream:a}=Er(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||{}}));y(`[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){ye(`[Ollama][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"};return}}catch{}}catch(i){throw new ke(`Stream failed for Ollama model "${r}": ${i.message}`,i)}}async embed(e){let t=e.__toolpack_request_id||`emb-${Date.now()}`,o=typeof e.input=="string"?[e.input]:e.input,r=e.model||this.config.model;y(`[Ollama][${t}] Embedding request: model=${r}, inputs=${o.length}`);try{let n=await ne(this.baseUrl,"/api/embed","POST",{model:r,input:o},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 F?n:new ke(`Embedding failed for Ollama model "${r}": ${n.message}`,n)}}async disconnect(){}async toOllamaMessage(e,t={}){let o="",r=[],{normalizeImagePart:n}=await Promise.resolve().then(()=>(Le(),rt));if(typeof e.content=="string")o=e.content;else if(e.content!==null){for(let i of e.content)if(i.type==="text")o+=i.text+`
198
- `;else if(i.type==="image_url"||i.type==="image_data"||i.type==="image_file")try{let{data:c}=await n(i);r.push(c)}catch{i.type==="image_url"?o+=`[Image: ${i.image_url.url}]
199
- `:o+=`[Unresolvable Image]
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 M(`Model not found: ${o}`):new F(o,"OLLAMA_ERROR",e)}};l();var it=class extends Y{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 De({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 Nr=[{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 pg(){return Nr[0].model}function mg(s){let e=s.toLowerCase();return Nr.some(t=>t.model.toLowerCase()===e||t.model.split(":")[0].toLowerCase()===e.split(":")[0].toLowerCase())}function dg(){return[...Nr]}l();import $s from"openai";ce();_();var po=class extends Y{client;constructor(e,t){super(),this.client=new $s({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 M("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(f=>this.toOpenAIMessage(f,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(f=>{let h=this.sanitizeToolName(f.function.name);return n.set(h,f.function.name),{type:"function",function:{name:h,description:f.function.description,parameters:f.function.parameters}}}),r.tool_choice=e.tool_choice||"auto",y(`[OpenAI][${t}] Sending ${r.tools.length} tools with tool_choice: ${r.tool_choice}`),y(`[OpenAI][${t}] First tool: ${E(r.tools[0],800)}`)),y(`[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)}`),V(t,"OpenAI",r.messages);let a=await this.client.chat.completions.create(r,e.signal?{signal:e.signal}:void 0);ye(`[OpenAI][${t}] Raw completion: ${JSON.stringify(a)}`);let i=a.choices[0].message;y(`[OpenAI][${t}] Response: finish_reason=${a.choices[0].finish_reason}`),y(`[OpenAI][${t}] Response has tool_calls: ${!!i.tool_calls}, count: ${i.tool_calls?.length||0}`),y(`[OpenAI][${t}] Response content: ${JSON.stringify(i.content)}`),i.content&&y(`[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(f=>({id:f.id,name:n.get(f.function.name)||f.function.name,arguments:JSON.parse(f.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",y(`[OpenAI][${t}] Sending ${r.tools.length} tools with tool_choice: ${r.tool_choice}`),y(`[OpenAI][${t}] First tool: ${E(r.tools[0],800)}`)):y(`[OpenAI][${t}] NO TOOLS in request`),y(`[OpenAI][${t}] Stream request: model=${r.model}, messages=${r.messages.length}, tools=${r.tools?.length||0}, tool_choice=${r.tool_choice??"unset"}`),V(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&&ye(`[OpenAI][${t}] Stream chunk finish_reason=${p.finish_reason}`),p.delta.tool_calls)for(let m of p.delta.tool_calls){let f=m.index;i.has(f)||i.set(f,{id:m.id||"",name:m.function?.name||"",args:""});let h=i.get(f);m.id&&(h.id=m.id),m.function?.name&&(h.name=m.function.name),m.function?.arguments&&(h.args+=m.function.arguments),ye(`[OpenAI][${t}] tool_call_delta idx=${f} id=${m.id||h.id||""} name=${m.function?.name||h.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(f=>({id:f.id,name:n.get(f.name)||f.name,arguments:JSON.parse(f.args||"{}")}));y(`[OpenAI][${t}] Stream finish_reason=tool_calls accumulated_calls=${m.length} names=${m.map(f=>f.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(()=>(Le(),rt)),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 $s.APIError){let t=e.message;return e.status===401?new ge(t,e):e.status===429?new he(t,void 0,e):e.status&&e.status>=400&&e.status<500?new M(t,e):new F(t,e.code||"OPENAI_ERROR",e.status||500,e)}return new F("Unknown error","UNKNOWN",500,e)}};Le();l();tt();l();tt();var Qt=class{tools=new Map;projects=new Map;config=z;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(()=>(Vr(),qa)),{execToolsProject:t}=await Promise.resolve().then(()=>(nn(),_l)),{systemToolsProject:o}=await Promise.resolve().then(()=>(dn(),lc)),{httpToolsProject:r}=await Promise.resolve().then(()=>(wn(),Jc)),{webToolsProject:n}=await Promise.resolve().then(()=>(En(),um)),{codingToolsProject:a}=await Promise.resolve().then(()=>(Kn(),Xd)),{gitToolsProject:i}=await Promise.resolve().then(()=>(Qn(),_u)),{diffToolsProject:c}=await Promise.resolve().then(()=>(Yn(),Wu)),{dbToolsProject:p}=await Promise.resolve().then(()=>(Xn(),hf)),{cloudToolsProject:m}=await Promise.resolve().then(()=>(Zn(),_f));await this.loadProjects([e,t,o,r,n,a,i,c,p,m])}};Tn();l();_();function Wy(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}}Vr();nn();dn();wn();En();Kn();Qn();Yn();Xn();Zn();l();l();_();import{spawn as Gy}from"child_process";import{EventEmitter as By}from"events";var hr=class extends Error{constructor(e,t){super(`MCP request timed out after ${t}ms: ${e}`),this.name="McpTimeoutError"}},me=class extends Error{constructor(t,o){super(t);this.exitCode=o;this.name="McpConnectionError"}exitCode},Yt=class extends By{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 me("Client is shutting down");return new Promise((t,o)=>{try{if(this.buffer="",this.process=Gy(this.config.command,this.config.args||[],{env:{...process.env,...this.config.env},stdio:["pipe","pipe","pipe"]}),!this.process.stdout||!this.process.stdin)throw new me("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 me(`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 r=this.buffer.slice(0,o).trim();if(this.buffer=this.buffer.slice(o+1),r)try{let n=JSON.parse(r);this.handleMessage(n)}catch{}}}handleMessage(t){if(t.id&&(t.result!==void 0||t.error)){let o=this.messageQueue.get(t.id);o&&(o.timer&&clearTimeout(o.timer),t.error?o.reject(new Error(t.error.message)):o.resolve(t.result),this.messageQueue.delete(t.id))}else t.method&&(this.emit("notification",t),this.emit(t.method,t.params))}async callTool(t,o={},r){return this.request("tools/call",{name:t,arguments:o},r)}async readResource(t,o){return this.request("resources/read",{uri:t},o)}async request(t,o,r){if(!this.process||!this.process.stdin)throw new me("Client not connected");let n=this.nextId++,a=r??this.defaultTimeoutMs,i={jsonrpc:"2.0",id:n,method:t,params:o};return new Promise((c,p)=>{let m;a>0&&(m=setTimeout(()=>{let f=this.messageQueue.get(n);f&&(this.messageQueue.delete(n),f.reject(new hr(t,a)))},a)),this.messageQueue.set(n,{resolve:c,reject:p,timer:m});try{this.process.stdin.write(JSON.stringify(i)+`
202
- `)}catch(f){m&&clearTimeout(m),this.messageQueue.delete(n),p(f)}})}async disconnect(t=3e3){if(this._shuttingDown=!0,this.rejectAllPending(new me("Client disconnecting")),!this.process){this._shuttingDown=!1;return}let o=this.process;return new Promise(r=>{let n=!1,a=()=>{n||(n=!0,this.process=null,this._connected=!1,this._shuttingDown=!1,r())};o.once("exit",a),o.kill("SIGTERM"),setTimeout(()=>{if(!n){try{o.kill("SIGKILL")}catch{}a()}},t)})}kill(){this._shuttingDown=!0,this.rejectAllPending(new me("Client killed")),this.process&&(this.process.kill("SIGKILL"),this.process=null),this._connected=!1,this._shuttingDown=!1}rejectAllPending(t){for(let[o,r]of this.messageQueue)r.timer&&clearTimeout(r.timer),r.reject(t);this.messageQueue.clear()}};_();var yr=class{constructor(e){this.config=e}config;clients=new Map;serverConfigs=new Map;toolDefinitions=new Map;async connectServer(e){let{name:t,displayName:o,toolPrefix:r,...n}=e;v(`[MCP] Connecting to server: ${o||t}`);try{let a=new Yt({...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=r||`mcp.${t}.`;for(let m of c){let f=this.convertMcpTool(m,t,p,a);this.toolDefinitions.set(f.name,f)}this.clients.set(t,a),this.serverConfigs.set(t,e)}catch(a){throw Q(`[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){D(`[MCP] Server ${e} not found`);return}v(`[MCP] Disconnecting from ${e}`);for(let[o,r]of this.toolDefinitions)r.name.includes(e)&&this.toolDefinitions.delete(o);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,o,r){let n={type:"object",properties:e.inputSchema.properties||{},required:e.inputSchema.required||[]};return{name:`${o}${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 r.callTool(e.name,a);return JSON.stringify(i)}catch(i){throw Q(`[MCP] Tool execution failed: ${i}`),i}}}}setupClientEvents(e,t){e.on("error",o=>{Q(`[MCP] ${t} error: ${o}`)}),e.on("close",o=>{D(`[MCP] ${t} closed with code ${o}`)}),e.on("reconnecting",({attempt:o,max:r})=>{v(`[MCP] ${t} reconnecting (${o}/${r})`)}),e.on("reconnected",({attempt:o})=>{v(`[MCP] ${t} reconnected after ${o} attempts`)}),e.on("reconnect_failed",o=>{Q(`[MCP] ${t} failed to reconnect after ${o} attempts`)}),e.on("notification",o=>{v(`[MCP] ${t} notification: ${JSON.stringify(o)}`)})}};async function es(s){let e=new yr(s);await e.connectAll();let t=e.getToolDefinitions(),o={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(r=>r.name)},tools:t};return o._mcpManager=e,o}async function ts(s){let e=s._mcpManager;e&&await e.disconnectAll()}l();l();l();var kf={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:{planning:{enabled:!0},steps:{enabled:!0,retryOnFailure:!0,allowDynamicSteps:!0},progress:{enabled:!0}},toolSearch:{alwaysLoadedTools:["fs.read_file","fs.write_file","fs.list_dir","web.search","web.fetch","skill.search","skill.read"]}},Rf={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:{planning:{enabled:!1},steps:{enabled:!1}},toolSearch:{alwaysLoadedTools:["web.search","web.fetch"]}},wr=[kf,Rf],Qe="chat";var Vt=class{modes=new Map;orderedNames=[];constructor(){for(let e of wr)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 r of t)if(e[r]!==void 0&&!Array.isArray(e[r]))throw new Error(`ModeConfig.${r} must be an array`);let o=this.modes.has(e.name);this.modes.set(e.name,e),o||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 o=this.modes.get(t);o&&e.push(o)}return e}getNames(){return[...this.orderedNames]}getDefault(){let e=this.modes.get(Qe);if(!e)throw new Error(`Default mode "${Qe}" not found in registry`);return e}getNext(e){let t=this.orderedNames.indexOf(e),o=t===-1?0:(t+1)%this.orderedNames.length,r=this.orderedNames[o],n=this.modes.get(r);if(!n)throw new Error(`Mode "${r}" not found in registry`);return n}get size(){return this.modes.size}remove(e){if(wr.some(r=>r.name===e))return!1;let o=this.modes.delete(e);return o&&(this.orderedNames=this.orderedNames.filter(r=>r!==e)),o}};l();function Jy(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 os={planning:{enabled:!1},steps:{enabled:!1},progress:{enabled:!0}};l();_();var Hy=`
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(()=>(Ue(),st)),i=async m=>typeof m=="string"?[{text:m}]:m===null?[]:(await Promise.all(m.map(async h=>{if(h.type==="text")return{text:h.text};if(h.type==="image_data"||h.type==="image_file"||h.type==="image_url")try{let{data:b,mimeType:w}=await a(h);return{inlineData:{mimeType:w,data:b}}}catch{return h.type==="image_url"?{text:`[Image: ${h.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 f=[];if(typeof m.content=="string"&&m.content)f.push({text:m.content});else if(Array.isArray(m.content)){let h=m.content.filter(b=>typeof b=="object"&&b.type==="text").map(b=>b.text).join(`
195
+ `);h&&f.push({text:h})}for(let h of m.tool_calls)f.push({functionCall:{name:this.sanitizeToolName(h.function.name),args:typeof h.function.arguments=="string"?JSON.parse(h.function.arguments||"{}"):h.function.arguments}});return{role:"model",parts:f}}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 he(e.message,void 0,e):e.status>=400&&e.status<500?new M(e.message,e):e.message&&e.message.includes("API key")?new ge(e.message,e):new F(e.message||"Gemini Error","GEMINI_ERROR",e.status||500,e)}};l();import*as at from"fs";import*as $s from"path";var mg="toolpack.config.json";function Rr(s){if(s&&at.existsSync(s))return s;let e=$s.join(process.cwd(),mg);return at.existsSync(e)?e:null}function dg(s){if(!s)return null;try{let e=at.readFileSync(s,"utf-8");return JSON.parse(e)}catch{return null}}var it=null;function Er(s){if(it)return it;let e=s||Rr();return it=dg(e)||{},it}function ug(){it=null}function fg(s){return(Er(s).ollama?.models||[]).map(r=>({type:`ollama-${r.model.replace(/[:.]/g,"-")}`,model:r.model,label:r.label||r.model}))}function co(s){return Er(s).ollama?.baseUrl||"http://localhost:11434"}l();l();ce();k();l();import _s from"http";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=_s.request(c,m=>{let f=[];m.on("data",h=>f.push(h)),m.on("end",()=>{n({status:m.statusCode||0,body:Buffer.concat(f).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 Dr(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((h,b)=>{n=_s.request(p,h),n.on("error",b),n.on("timeout",()=>{n.destroy(),b(new Error("Stream request timed out"))}),n.write(JSON.stringify(t)),n.end()});if(m.statusCode&&m.statusCode>=400){let h="";for await(let b of m)h+=b.toString();throw new Error(`Ollama HTTP ${m.statusCode}: ${h}`)}let f="";for await(let h of m){if(a)break;let b=h.toString();if(f+=b,f.includes('"error"'))try{let x=JSON.parse(f.trim());if(x.error)throw new Error(`Ollama: ${x.error}`)}catch(x){if(x.message.startsWith("Ollama:"))throw x}let w=f.split(`
196
+ `);f=w.pop()||"";for(let x of w)x.trim()&&(yield x)}f.trim()&&!a&&(yield f.trim())}(),abort:()=>{a=!0,n&&n.destroy()}}}var De=class extends Y{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 M(`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 F(`Ollama returned status ${e.status}`,"OLLAMA_ERROR",e.status);return JSON.parse(e.body).models||[]}catch(e){throw e instanceof F?e:new ke(`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}})),y(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&y(`[Ollama][${t}] First tool: ${D(e.tools[0],800)}`),y(`[Ollama][${t}] NO TOOLS in request`)),y(`[Ollama][${t}] generate() request: model=${o}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),V(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 y(`[Ollama][${t}] Response finish_reason=${p.finish_reason} tool_calls=${c.length} content_preview=${D(p.content,200)}`),p}catch(a){throw a instanceof F?a:new ke(`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}})),y(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&y(`[Ollama][${t}] First tool: ${D(e.tools[0],800)}`),y(`[Ollama][${t}] NO TOOLS in request`)),y(`[Ollama][${t}] Stream request: model=${o}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),V(t,"Ollama",e.messages);let{stream:a}=Dr(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||{}}));y(`[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){ye(`[Ollama][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"};return}}catch{}}catch(i){throw new ke(`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;y(`[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 F?n:new ke(`Embedding failed for Ollama model "${o}": ${n.message}`,n)}}async disconnect(){}async toOllamaMessage(e,t={}){let r="",o=[],{normalizeImagePart:n}=await Promise.resolve().then(()=>(Ue(),st));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 M(`Model not found: ${r}`):new F(r,"OLLAMA_ERROR",e)}};l();var lt=class extends Y{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 De({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 Nr=[{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 gg(){return Nr[0].model}function hg(s){let e=s.toLowerCase();return Nr.some(t=>t.model.toLowerCase()===e||t.model.split(":")[0].toLowerCase()===e.split(":")[0].toLowerCase())}function yg(){return[...Nr]}l();import ks from"openai";ce();k();var po=class extends Y{client;constructor(e,t){super(),this.client=new ks({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 M("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(f=>this.toOpenAIMessage(f,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(f=>{let h=this.sanitizeToolName(f.function.name);return n.set(h,f.function.name),{type:"function",function:{name:h,description:f.function.description,parameters:f.function.parameters}}}),o.tool_choice=e.tool_choice||"auto",y(`[OpenAI][${t}] Sending ${o.tools.length} tools with tool_choice: ${o.tool_choice}`),y(`[OpenAI][${t}] First tool: ${D(o.tools[0],800)}`)),y(`[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)}`),V(t,"OpenAI",o.messages);let a=await this.client.chat.completions.create(o,e.signal?{signal:e.signal}:void 0);ye(`[OpenAI][${t}] Raw completion: ${JSON.stringify(a)}`);let i=a.choices[0].message;y(`[OpenAI][${t}] Response: finish_reason=${a.choices[0].finish_reason}`),y(`[OpenAI][${t}] Response has tool_calls: ${!!i.tool_calls}, count: ${i.tool_calls?.length||0}`),y(`[OpenAI][${t}] Response content: ${JSON.stringify(i.content)}`),i.content&&y(`[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(f=>({id:f.id,name:n.get(f.function.name)||f.function.name,arguments:JSON.parse(f.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",y(`[OpenAI][${t}] Sending ${o.tools.length} tools with tool_choice: ${o.tool_choice}`),y(`[OpenAI][${t}] First tool: ${D(o.tools[0],800)}`)):y(`[OpenAI][${t}] NO TOOLS in request`),y(`[OpenAI][${t}] Stream request: model=${o.model}, messages=${o.messages.length}, tools=${o.tools?.length||0}, tool_choice=${o.tool_choice??"unset"}`),V(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&&ye(`[OpenAI][${t}] Stream chunk finish_reason=${p.finish_reason}`),p.delta.tool_calls)for(let m of p.delta.tool_calls){let f=m.index;i.has(f)||i.set(f,{id:m.id||"",name:m.function?.name||"",args:""});let h=i.get(f);m.id&&(h.id=m.id),m.function?.name&&(h.name=m.function.name),m.function?.arguments&&(h.args+=m.function.arguments),ye(`[OpenAI][${t}] tool_call_delta idx=${f} id=${m.id||h.id||""} name=${m.function?.name||h.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(f=>({id:f.id,name:n.get(f.name)||f.name,arguments:JSON.parse(f.args||"{}")}));y(`[OpenAI][${t}] Stream finish_reason=tool_calls accumulated_calls=${m.length} names=${m.map(f=>f.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(()=>(Ue(),st)),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 ks.APIError){let t=e.message;return e.status===401?new ge(t,e):e.status===429?new he(t,void 0,e):e.status&&e.status>=400&&e.status<500?new M(t,e):new F(t,e.code||"OPENAI_ERROR",e.status||500,e)}return new F("Unknown error","UNKNOWN",500,e)}};Ue();l();rt();l();rt();var Vt=class{tools=new Map;projects=new Map;config=z;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(()=>(Vr(),Wa)),{execToolsProject:t}=await Promise.resolve().then(()=>(nn(),Rl)),{systemToolsProject:r}=await Promise.resolve().then(()=>(dn(),pc)),{httpToolsProject:o}=await Promise.resolve().then(()=>(wn(),zc)),{webToolsProject:n}=await Promise.resolve().then(()=>(Dn(),gm)),{codingToolsProject:a}=await Promise.resolve().then(()=>(Kn(),eu)),{gitToolsProject:i}=await Promise.resolve().then(()=>(Qn(),Ru)),{diffToolsProject:c}=await Promise.resolve().then(()=>(Yn(),Bu)),{dbToolsProject:p}=await Promise.resolve().then(()=>(Xn(),wf)),{cloudToolsProject:m}=await Promise.resolve().then(()=>(Zn(),Rf));await this.loadProjects([e,t,r,o,n,a,i,c,p,m])}};Tn();l();k();function zy(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}}Vr();nn();dn();wn();Dn();Kn();Qn();Yn();Xn();Zn();l();l();k();import{spawn as Ky}from"child_process";import{EventEmitter as Qy}from"events";var hr=class extends Error{constructor(e,t){super(`MCP request timed out after ${t}ms: ${e}`),this.name="McpTimeoutError"}},me=class extends Error{constructor(t,r){super(t);this.exitCode=r;this.name="McpConnectionError"}exitCode},Xt=class extends Qy{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 me("Client is shutting down");return new Promise((t,r)=>{try{if(this.buffer="",this.process=Ky(this.config.command,this.config.args||[],{env:{...process.env,...this.config.env},stdio:["pipe","pipe","pipe"]}),!this.process.stdout||!this.process.stdin)throw new me("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 me(`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 me("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 f=this.messageQueue.get(n);f&&(this.messageQueue.delete(n),f.reject(new hr(t,a)))},a)),this.messageQueue.set(n,{resolve:c,reject:p,timer:m});try{this.process.stdin.write(JSON.stringify(i)+`
202
+ `)}catch(f){m&&clearTimeout(m),this.messageQueue.delete(n),p(f)}})}async disconnect(t=3e3){if(this._shuttingDown=!0,this.rejectAllPending(new me("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 me("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 yr=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 Xt({...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 f=this.convertMcpTool(m,t,p,a);this.toolDefinitions.set(f.name,f)}this.clients.set(t,a),this.serverConfigs.set(t,e)}catch(a){throw Q(`[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 Q(`[MCP] Tool execution failed: ${i}`),i}}}}setupClientEvents(e,t){e.on("error",r=>{Q(`[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=>{Q(`[MCP] ${t} failed to reconnect after ${r} attempts`)}),e.on("notification",r=>{v(`[MCP] ${t} notification: ${JSON.stringify(r)}`)})}};async function es(s){let e=new yr(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 ts(s){let e=s._mcpManager;e&&await e.disconnectAll()}l();l();l();l();var os=`
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. The final step must synthesize the workflow's results into a concise deliverable, avoiding redundant word-for-word repetition of earlier step outputs
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
- `,Xt=class{client;config;constructor(e,t){this.client=e,this.config=t}async createPlan(e,t){let o=this.config?.planningPrompt||Hy,r=e.messages.filter(p=>p.role==="user").map(p=>typeof p.content=="string"?p.content:"[obj]").join(" ").substring(0,100);y(`[Planner] createPlan() provider=${t??"default"} maxSteps=${this.config?.maxSteps??20} request="${r}..."`);let n=e.messages.filter(p=>p.role==="system"),a=e.messages.filter(p=>p.role!=="system"),i=[{role:"system",content:o},...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 D(`[Planner] createPlan() failed, using fallback: ${p.message}`),this.createFallbackPlan(e)}}async createImplicitPlan(e,t){return this.createPlan(e,t)}parsePlan(e,t,o){try{let r=JSON.parse(e);if(!r.summary||!Array.isArray(r.steps))throw new Error("Invalid plan structure: missing summary or steps array");let n=this.config?.maxSteps??20,a=r.steps.slice(0,n);r.steps.length>n&&D(`[Planner] parsePlan() truncated ${r.steps.length} steps to maxSteps=${n}`),y(`[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:r.summary,steps:i,status:"draft",createdAt:new Date,planningResponse:o}}catch(r){return D(`[Planner] parsePlan() failed: ${r.message} \u2014 using fallback`),this.createFallbackPlan(t)}}createFallbackPlan(e){D("[Planner] createFallbackPlan() \u2014 creating single-step fallback due to plan generation failure");let t=e.messages.filter(o=>o.role==="user").map(o=>typeof o.content=="string"?o.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 Ye=class{static getProgress(e){let t=e.steps.length,o=e.steps.findIndex(c=>c.status!=="completed"&&c.status!=="skipped");o===-1&&(o=t);let r=t>0?Math.round(o/t*100):0,n=e.steps[o],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(o+1,t),totalSteps:t,percentage:r,currentStepDescription:a,status:i}}static summarizeCompletedSteps(e,t){let o=[];for(let r of e.steps){if(r.id===t)break;if(r.status==="completed"&&r.result){let n=r.result.toolsUsed?.length?` (Tools: ${r.result.toolsUsed.join(", ")})`:"",a=r.result.output||"No output";a.length>500&&(a=a.substring(0,500)+"... [truncated]"),o.push(`Step ${r.number}: ${r.description}${n}
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 zy=`
228
+ `,rs=`
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
- `,Ky=`
247
+ `,JN={name:"Direct",planning:{enabled:!1},steps:{enabled:!1},progress:{enabled:!0}},Ef={name:"Agent",planning:{enabled:!0,planningPrompt:os},steps:{enabled:!0,retryOnFailure:!0,allowDynamicSteps:!1,stepPrompt:rs},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},Yy=`
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
+ `,Vy=`
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
+ `,Df={name:"Coding",planning:{enabled:!0,planningPrompt:Yy},steps:{enabled:!0,retryOnFailure:!0,allowDynamicSteps:!1,stepPrompt:Vy},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},Nf={name:"Chat",planning:{enabled:!1},steps:{enabled:!1},progress:{enabled:!1}};var Af={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:Ef,toolSearch:{alwaysLoadedTools:["fs.read_file","fs.write_file","fs.list_dir","web.search","web.fetch","skill.search","skill.read"]}},Mf={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:Nf,toolSearch:{alwaysLoadedTools:["web.search","web.fetch","fs.read_file","fs.list_dir"]}},Xy={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:Df,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"]}},wr=[Af,Xy,Mf],Ve="chat";var Zt=class{modes=new Map;orderedNames=[];constructor(){for(let e of wr)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(Ve);if(!e)throw new Error(`Default mode "${Ve}" 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(wr.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 Zy(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 ns={planning:{enabled:!1},steps:{enabled:!1},progress:{enabled:!0}};l();k();var ew=os,eo=class{client;config;constructor(e,t){this.client=e,this.config=t}async createPlan(e,t){let r=this.config?.planningPrompt||ew,o=e.messages.filter(p=>p.role==="user").map(p=>typeof p.content=="string"?p.content:"[obj]").join(" ").substring(0,100);y(`[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}`),y(`[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 Xe=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 tw=rs,ow=`
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
- `,Zt=class{client;config;constructor(e,t){this.client=e,this.config=t}async executeStep(e,t,o,r){let n=Date.now();y(`[StepExecutor] executeStep() step=${e.number} "${e.description}" expectedTools=${e.expectedTools?.join(",")||"none"}`);let a=this.buildStepRequest(e,t,o);try{let i=await this.client.generate(a,r),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 D(`[StepExecutor] Step ${e.number} failed in ${c}ms: ${i.message}`),{success:!1,error:i.message||"Unknown execution error",duration:c}}}async*streamStep(e,t,o,r){y(`[StepExecutor] streamStep() step=${e.number} "${e.description}"`);let n=this.buildStepRequest(e,t,o);yield*this.client.stream(n,r)}buildStepRequest(e,t,o){let r=Ye.summarizeCompletedSteps(t,e.id),n=zy.replace("{stepNumber}",e.number.toString()).replace("{planSummary}",t.summary).replace("{stepDescription}",e.description).replace("{previousStepsResults}",r),a=o.messages.filter(m=>m.role==="system"),i=o.messages.filter(m=>m.role!=="system"),c=[...a,...i],p=[];for(let m of t.steps){if(m.id===e.id)break;if(m.status==="completed"&&m.result?.output){let f=m.result.output;f.length>2e3&&(f=f.substring(0,2e3)+`
266
- ... [truncated]`),p.push({role:"assistant",content:`[Step ${m.number}: ${m.description}]
267
- ${f}`}),p.push({role:"user",content:`Step ${m.number} is complete. Now proceed with the next step.`})}}return{...o,messages:[{role:"system",content:n},...c,...p],tool_choice:"auto"}}async checkForDynamicSteps(e,t,o,r){if(!this.config?.allowDynamicSteps)return[];let n=t.steps.length,a=this.config.maxTotalSteps??50;if(n>=a)return y(`[StepExecutor] checkForDynamicSteps() skipped \u2014 already at maxTotalSteps=${a}`),[];y(`[StepExecutor] checkForDynamicSteps() after step=${e.number} currentTotal=${n} max=${a}`);let i=Ky,c=o.messages.filter(h=>h.role==="system"),p=o.messages.filter(h=>h.role!=="system"),m=[...c,...p],f={...o,tool_choice:"none",response_format:"json_object",messages:[...m,{role:"assistant",content:e.result?.output||""},{role:"user",content:i}]};try{let h=await this.client.generate(f,r),x=JSON.parse(h.content||'{"steps": []}');if(Array.isArray(x.steps)&&x.steps.length>0){let w=a-n,b=x.steps.slice(0,w),P=new Set(t.steps.map(C=>this.normalizeStepDescription(C.description))),S=b.filter(C=>{let T=this.normalizeStepDescription(C.description||"");return P.has(T)?!1:(P.add(T),!0)});return S.length===0?(y("[StepExecutor] checkForDynamicSteps() all proposed steps were duplicates \u2014 skipping"),[]):(v(`[StepExecutor] checkForDynamicSteps() adding ${S.length} dynamic step(s) after step ${e.number}`),S.map((C,T)=>({id:`step-${Date.now()}-dyn-${T}`,number:0,description:C.description||"Dynamic step",expectedTools:C.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();import{EventEmitter as Qy}from"events";_();var br=class extends Qy{client;config;planner;stepExecutor;pendingApprovals=new Map;constructor(e,t){super(),this.client=e,this.config=t,this.planner=new Xt(e,t.planning),this.stepExecutor=new Zt(e,t.steps)}getConfig(){return this.config}setConfig(e){this.config=e,this.planner=new Xt(this.client,e.planning),this.stepExecutor=new Zt(this.client,e.steps)}async execute(e,t){let o=this.config.planning?.enabled,r=this.config.steps?.enabled;if(y(`[Workflow] execute() planningEnabled=${o} stepsEnabled=${r} provider=${t??"default"}`),!o&&!r)return y("[Workflow] execute() mode=direct"),this.executeDirect(e,t);let n=null;if(o){if(y("[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 r?(n||(y("[Workflow] execute() mode=steps-only \u2014 creating implicit plan"),n=await this.planner.createImplicitPlan(e,t),this.emit("workflow:plan_created",n),n.status="approved"),this.executeStepByStep(n,e,t)):n?(y("[Workflow] execute() mode=plan-direct (planning only, no steps)"),this.executePlanDirect(n,e,t)):this.executeDirect(e,t)}async executeDirect(e,t){let o=Date.now(),r=this.createDummyPlan(e);y(`[Workflow] executeDirect() provider=${t??"default"}`);try{this.emitProgress(r,"executing","Direct execution");let n=await this.client.generate(e,t);r.status="completed",r.completedAt=new Date,r.steps[0].status="completed";let a=Date.now()-o;y(`[Workflow] executeDirect() completed in ${a}ms content_len=${n.content?.length??0}`);let i={success:!0,plan:r,output:n.content||void 0,metrics:{totalDuration:Date.now()-o,stepsCompleted:1,stepsFailed:0,retriesUsed:0}};return this.emit("workflow:completed",r,i),this.emitProgress(r,"completed","Done"),i}catch(n){r.status="failed",r.completedAt=new Date,r.steps[0].status="failed",D(`[Workflow] executeDirect() failed: ${n.message}`);let a={success:!1,plan:r,error:n.message,metrics:{totalDuration:Date.now()-o,stepsCompleted:0,stepsFailed:1,retriesUsed:0}};return this.emit("workflow:failed",r,n),this.emitProgress(r,"failed","Execution failed"),a}}async createPlan(e,t){y(`[Workflow] createPlan() provider=${t??"default"}`);let o=this.createDummyPlan(e);o.status="draft",this.emitProgress(o,"planning","Creating plan...");let r=await this.planner.createPlan(e,t);return v(`[Workflow] createPlan() completed plan.id=${r.id} steps=${r.steps.length}`),r}async executeStepByStep(e,t,o){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 r=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 w=p.dependsOn.filter(b=>{let P=e.steps.find(S=>S.id===String(b)||S.number===Number(b));return P?P.status!=="completed":!1});if(w.length>0){y(`[Workflow] Step ${p.number} skipped \u2014 unmet deps: ${w.join(", ")}`),p.status="skipped",p.result={success:!1,error:`Unmet dependencies: ${w.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,f=this.config.steps?.maxRetries??3,h=null,x=!1;for(;m<=f;)try{let w=await this.stepExecutor.executeStep(p,e,t,o);if(w.success){p.status="completed",p.result=w,this.emit("workflow:step_complete",p,e),y(`[Workflow] Step ${p.number} completed in ${w.duration??0}ms toolsUsed=${(w.toolsUsed??[]).join(",")||"none"}`),x=!0;break}else throw new Error(w.error||"Step returned unsuccessful result")}catch(w){if(h=w,m++,m<=f&&this.config.steps?.retryOnFailure)n++,D(`[Workflow] Step ${p.number} failed (attempt ${m}/${f}), retrying: ${h.message}`),this.emit("workflow:step_retry",p,m,e),this.emitProgress(e,"executing",`[Retry ${m}] ${p.description}`);else{D(`[Workflow] Step ${p.number} failed permanently: ${h.message}`),p.status="failed",p.result={success:!1,error:h.message},this.emit("workflow:step_failed",p,h,e);break}}if(!x){let w=this.config.onFailure?.strategy||"abort";if(y(`[Workflow] Step ${p.number} failed \u2014 applying strategy="${w}"`),w==="abort"){e.status="failed",e.completedAt=new Date;let b={success:!1,plan:e,error:`Step ${p.number} failed: ${h?.message}`,metrics:this.computeMetrics(e,r,n)};return this.emit("workflow:failed",e,h),this.emitProgress(e,"failed","Workflow aborted due to step failure"),b}else if(w==="ask_user"){if(this.emitProgress(e,"awaiting_approval",`Step failed: ${h?.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,r,n)};return this.emit("workflow:failed",e,new Error(P.error)),P}p.status="skipped"}else p.status="skipped"}if(x&&this.config.steps?.allowDynamicSteps){let w=await this.stepExecutor.checkForDynamicSteps(p,e,t,o);if(w.length>0){let b=p.number+1;for(let P of w)P.number=b++;for(let P=c+1;P<e.steps.length;P++)e.steps[P].number=b++;e.steps.splice(c+1,0,...w),w.forEach(P=>this.emit("workflow:step_added",P,e))}}}let a=this.computeMetrics(e,r,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,o){let r=Date.now();e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e),this.emitProgress(e,"executing","Executing plan"),y(`[Workflow] executePlanDirect() plan.id=${e.id} steps=${e.steps.length} provider=${o??"default"}`);let n=`
302
+ `,to=class{client;config;constructor(e,t){this.client=e,this.config=t}async executeStep(e,t,r,o){let n=Date.now();y(`[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){y(`[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=Xe.summarizeCompletedSteps(t,e.id),a=(this.config?.stepPrompt||tw).replace("{stepNumber}",e.number.toString()).replace("{planSummary}",t.summary).replace("{stepDescription}",e.description).replace("{previousStepsResults}",o),i=r.messages.filter(f=>f.role==="system"),c=r.messages.filter(f=>f.role!=="system"),p=[...i,...c],m=[];for(let f of t.steps){if(f.id===e.id)break;if(f.status==="completed"&&f.result?.output){let h=f.result.output;h.length>2e3&&(h=h.substring(0,2e3)+`
303
+ ... [truncated]`),m.push({role:"assistant",content:h}),m.push({role:"user",content:`Step ${f.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 y(`[StepExecutor] checkForDynamicSteps() skipped \u2014 already at maxTotalSteps=${a}`),[];y(`[StepExecutor] checkForDynamicSteps() after step=${e.number} currentTotal=${n} max=${a}`);let i=t.steps.filter(b=>b.status==="pending"&&b.number>e.number).map(b=>`${b.number}. ${b.description}`).join(`
304
+ `)||"None",c=ow.replace("{{REMAINING_STEPS}}",i),p=r.messages.filter(b=>b.role==="system"),m=r.messages.filter(b=>b.role!=="system"),f=[...p,...m],h={...r,tool_choice:"none",response_format:"json_object",messages:[...f,{role:"assistant",content:e.result?.output||""},{role:"user",content:c}]};try{let b=await this.client.generate(h,o),w=JSON.parse(b.content||'{"steps": []}');if(Array.isArray(w.steps)&&w.steps.length>0){let x=a-n,P=w.steps.slice(0,x),$=new Set(t.steps.map(T=>this.normalizeStepDescription(T.description))),C=P.filter(T=>{let S=this.normalizeStepDescription(T.description||"");return $.has(S)?!1:($.add(S),!0)});return C.length===0?(y("[StepExecutor] checkForDynamicSteps() all proposed steps were duplicates \u2014 skipping"),[]):(v(`[StepExecutor] checkForDynamicSteps() adding ${C.length} dynamic step(s) after step ${e.number}`),C.map((T,S)=>({id:`step-${Date.now()}-dyn-${S}`,number:0,description:T.description||"Dynamic step",expectedTools:T.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();import{EventEmitter as rw}from"events";k();var br=class extends rw{client;config;planner;stepExecutor;queryClassifier;pendingApprovals=new Map;constructor(e,t,r){super(),this.client=e,this.config=t,this.queryClassifier=r||new qe,this.planner=new eo(e,t.planning),this.stepExecutor=new to(e,t.steps)}getConfig(){return this.config}setConfig(e){this.config=e,this.planner=new eo(this.client,e.planning),this.stepExecutor=new to(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=Re(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 y(`[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(y(`[Workflow] execute() planningEnabled=${r} stepsEnabled=${o} provider=${t??"default"}`),!r&&!o)return y("[Workflow] execute() mode=direct"),this.executeDirect(e,t);let n=null;if(r){if(y("[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||(y("[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?(y("[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);y(`[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;y(`[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){y(`[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 w=p.dependsOn.filter(x=>{let P=e.steps.find($=>$.id===String(x)||$.number===Number(x));return P?P.status!=="completed":!1});if(w.length>0){y(`[Workflow] Step ${p.number} skipped \u2014 unmet deps: ${w.join(", ")}`),p.status="skipped",p.result={success:!1,error:`Unmet dependencies: ${w.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,f=this.config.steps?.maxRetries??3,h=null,b=!1;for(;m<=f;)try{let w=await this.stepExecutor.executeStep(p,e,t,r);if(w.success){p.status="completed",p.result=w,this.emit("workflow:step_complete",p,e),y(`[Workflow] Step ${p.number} completed in ${w.duration??0}ms toolsUsed=${(w.toolsUsed??[]).join(",")||"none"}`),b=!0;break}else throw new Error(w.error||"Step returned unsuccessful result")}catch(w){if(h=w,m++,m<=f&&this.config.steps?.retryOnFailure)n++,E(`[Workflow] Step ${p.number} failed (attempt ${m}/${f}), retrying: ${h.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: ${h.message}`),p.status="failed",p.result={success:!1,error:h.message},this.emit("workflow:step_failed",p,h,e);break}}if(!b){let w=this.config.onFailure?.strategy||"abort";if(y(`[Workflow] Step ${p.number} failed \u2014 applying strategy="${w}"`),w==="abort"){e.status="failed",e.completedAt=new Date;let x={success:!1,plan:e,error:`Step ${p.number} failed: ${h?.message}`,metrics:this.computeMetrics(e,o,n)};return this.emit("workflow:failed",e,h),this.emitProgress(e,"failed","Workflow aborted due to step failure"),x}else if(w==="ask_user"){if(this.emitProgress(e,"awaiting_approval",`Step failed: ${h?.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(b&&this.config.steps?.allowDynamicSteps){let w=await this.stepExecutor.checkForDynamicSteps(p,e,t,r);if(w.length>0){let x=p.number+1;for(let P of w)P.number=x++;for(let P=c+1;P<e.steps.length;P++)e.steps[P].number=x++;e.steps.splice(c+1,0,...w),w.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"),y(`[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,o);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,r,0),y(`[Workflow] executePlanDirect() completed plan.id=${e.id} duration=${Date.now()-r}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,D(`[Workflow] executePlanDirect() failed plan.id=${e.id}: ${i.message}`);let c={success:!1,plan:e,error:i.message,metrics:this.computeMetrics(e,r,0)};return this.emit("workflow:failed",e,i),this.emitProgress(e,"failed","Execution failed"),c}}emitProgress(e,t,o){if(!this.config.progress?.enabled)return;let r=Ye.getProgress(e);t&&(r.status=t),o&&(r.currentStepDescription=o),this.emit("workflow:progress",r)}computeMetrics(e,t,o){return{totalDuration:Date.now()-t,stepsCompleted:e.steps.filter(r=>r.status==="completed").length,stepsFailed:e.steps.filter(r=>r.status==="failed").length,retriesUsed:o}}summarizePlanResult(e){return`Workflow completed.
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),y(`[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=Xe.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){for(let t=e.steps.length-1;t>=0;t--){let o=e.steps[t];if(o.status==="completed"&&o.result?.output)return o.result.output}return e.steps.length===0||e.steps.every(t=>t.status==="pending")?e.summary:this.summarizePlanResult(e)}extractFinalResponse(e){for(let t=e.steps.length-1;t>=0;t--){let o=e.steps[t];if(o.status==="completed"&&o.result?.response)return o.result.response}}createDummyPlan(e){let t=e.messages.filter(o=>o.role==="user").map(o=>typeof o.content=="string"?o.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 o=this.config.planning?.enabled,r=this.config.steps?.enabled;if(y(`[Workflow] stream() planningEnabled=${o} stepsEnabled=${r} provider=${t??"default"}`),!o&&!r){y("[Workflow] stream() mode=direct"),yield*this.streamDirect(e,t);return}let n=null;if(o){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:`
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(y(`[Workflow] stream() planningEnabled=${r} stepsEnabled=${o} provider=${t??"default"}`),!r&&!o){y("[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(r){n||(n=await this.planner.createImplicitPlan(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,o){e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e);let r=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 w=c.dependsOn.filter(b=>{let P=e.steps.find(S=>S.id===String(b)||S.number===Number(b));return P?P.status!=="completed":!1});if(w.length>0){c.status="skipped",c.result={success:!1,error:`Unmet dependencies: ${w.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,f=null,h=!1,x="";for(;p<=m;)try{for await(let w of this.stepExecutor.streamStep(c,e,t,o)){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}w.delta&&(x+=w.delta),yield{...w,workflowStep:{number:c.number,description:c.description}}}c.status="completed",c.result={success:!0,output:x,duration:Date.now()-r},this.emit("workflow:step_complete",c,e),this.emitProgress(e,"executing"),h=!0;break}catch(w){if(f=w,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:f.message},this.emit("workflow:step_failed",c,f,e);break}}if(!h){let w=this.config.onFailure?.strategy||"abort";if(w==="abort"){e.status="failed",e.completedAt=new Date,this.emit("workflow:failed",e,f),yield{delta:`
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 w=c.dependsOn.filter(x=>{let P=e.steps.find($=>$.id===String(x)||$.number===Number(x));return P?P.status!=="completed":!1});if(w.length>0){c.status="skipped",c.result={success:!1,error:`Unmet dependencies: ${w.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,f=null,h=!1,b="";for(;p<=m;)try{for await(let w 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}w.delta&&(b+=w.delta),yield{...w,workflowStep:{number:c.number,description:c.description}}}c.status="completed",c.result={success:!0,output:b,duration:Date.now()-o},this.emit("workflow:step_complete",c,e),this.emitProgress(e,"executing"),h=!0;break}catch(w){if(f=w,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:f.message},this.emit("workflow:step_failed",c,f,e);break}}if(!h){let w=this.config.onFailure?.strategy||"abort";if(w==="abort"){e.status="failed",e.completedAt=new Date,this.emit("workflow:failed",e,f),yield{delta:`
292
331
 
293
332
  **Step failed:** ${f?.message}
294
333
  *Workflow aborted.*`,finish_reason:"stop"};return}else w==="skip"&&(c.status="skipped",yield{delta:`
295
334
  *Step skipped due to failure.*
296
- `,workflowStep:{number:c.number,description:c.description}})}if(h&&this.config.steps?.allowDynamicSteps){let w=await this.stepExecutor.checkForDynamicSteps(c,e,t,o);if(w.length>0){let b=c.number+1;for(let P of w)P.number=b++;for(let P=i+1;P<e.steps.length;P++)e.steps[P].number=b++;e.steps.splice(i+1,0,...w),w.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,r,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,o){e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e);let r=`
335
+ `,workflowStep:{number:c.number,description:c.description}})}if(h&&this.config.steps?.allowDynamicSteps){let w=await this.stepExecutor.checkForDynamicSteps(c,e,t,r);if(w.length>0){let x=c.number+1;for(let P of w)P.number=x++;for(let P=i+1;P<e.steps.length;P++)e.steps[P].number=x++;e.steps.splice(i+1,0,...w),w.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();import{EventEmitter as Df}from"events";_();var Ef=class s extends Df{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 br(this.client,os),this.forwardWorkflowEvents()}static async init(e){let t=Po(e.configPath);cs(t.logging);let o=new Qt,r=qt(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 T=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:[T]};await o.loadProjects([k]),v("[Knowledge] Registered knowledge_search tool")}catch(T){Q(`[Knowledge] Failed to register knowledge tool: ${T}`)}let n=null,a=e.mcp||t.mcp;if(a)try{v("[MCP] Initializing MCP tool integration");let T=await es(a);n=T,await o.loadProjects([T]),v(`[MCP] Loaded ${T.tools.length} tools from MCP servers`)}catch(T){Q(`[MCP] Failed to initialize MCP tools: ${T}`)}let i=t.systemPrompt,c=e.disableBaseContext||t.disableBaseContext||t.baseContext===!1||!1,p=t.modeOverrides||{},m={},f=new Set,h=e.defaultProvider||e.provider;if(e.providers)for(let[T,k]of Object.entries(e.providers)){let R=T===h,I=await s.createProvider(T,k,e.configPath,!R);I&&(m[T]=I)}else if(e.provider){let T={apiKey:e.apiKey,model:e.model},k=await s.createProvider(e.provider,T,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 T=Array.isArray(e.customProviders)?e.customProviders:Object.entries(e.customProviders).map(([k,R])=>(R.name=R.name||k,R));for(let k of T){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.`);f.add(R),m[R]=k}}if(!h&&e.customProviders&&(h=(Array.isArray(e.customProviders)?e.customProviders[0]:Object.values(e.customProviders)[0])?.name),!h)throw new Error("No default provider specified.");let x=new Vt;if(e.customModes)for(let T of e.customModes)x.register(T);let w={...p,...e.modeOverrides||{}};for(let[T,k]of Object.entries(w)){let R=x.get(T);if(R){k.systemPrompt!==void 0&&(R.systemPrompt=k.systemPrompt),k.toolSearch&&(R.toolSearch={...R.toolSearch||{},...k.toolSearch});for(let[I,U]of Object.entries(k))I!=="systemPrompt"&&I!=="toolSearch"&&(R[I]=U)}}let b=new io({providers:m,defaultProvider:h,toolRegistry:o,toolsConfig:o.getConfig(),systemPrompt:i,disableBaseContext:c}),P=new s(b,h,x);P.customProviderNames=f,P.mcpToolProject=n;let S=e.defaultMode||Qe,C=x.get(S);return C&&(b.setMode(C),C.workflow&&P.workflowExecutor.setConfig(C.workflow)),P}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 po(a,t.baseUrl);case"anthropic":return new ao(a,t.baseUrl);case"gemini":return new lo(a)}}if(e==="ollama")return new it({baseUrl:t.baseUrl||co(o)});if(e.startsWith("ollama-")){let n=t.model||e.replace(/^ollama-/,""),a=t.baseUrl||co(o);return new De({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 f of n.plan.steps)if(f.status==="completed"&&f.result?.response?.usage){let h=f.result.response.usage;a+=h.prompt_tokens,i+=h.completion_tokens||0,c+=h.total_tokens,p.steps.push({stepNumber:f.number,description:f.description,usage:h})}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 ts(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(os),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 Df&&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();import*as Nf from"os";import*as Me from"path";import*as Ve from"fs";var Af=".toolpack",Mf="config",Of="toolpack.config.json";function Yy(){return Nf.homedir()}function Vy(){return Me.join(Yy(),Af)}function If(){return Me.join(Vy(),Mf)}function xr(){return Me.join(If(),Of)}function Xy(s=process.cwd()){return Me.join(s,Af)}function jf(s=process.cwd()){return Me.join(Xy(s),Mf)}function Tr(s=process.cwd()){return Me.join(jf(s),Of)}function Ff(){let s=If();Ve.existsSync(s)||Ve.mkdirSync(s,{recursive:!0})}function RA(s=process.cwd()){let e=jf(s);Ve.existsSync(e)||Ve.mkdirSync(e,{recursive:!0})}l();import*as J from"fs";import*as Pr from"path";function ns(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]=ns(s[o],e[o]):t[o]=e[o];return t}function rs(s){if(!J.existsSync(s))return null;try{let e=J.readFileSync(s,"utf-8");return JSON.parse(e)}catch{return null}}function MA(s=process.cwd()){let e=Pr.join(s,"toolpack.config.json"),t=xr(),o=Tr(s),r=rs(e)||{},n=rs(t)||{},a=rs(o)||{},i=ns(r,n);return i=ns(i,a),i}function OA(s=process.cwd()){let e=Pr.join(s,"toolpack.config.json"),t=xr(),o=Tr(s),r=!J.existsSync(t),n=null,a="default";return J.existsSync(o)?(n=o,a="local"):J.existsSync(t)?(n=t,a="global"):J.existsSync(e)&&(n=e,a="base"),{isFirstRun:r,activeConfigPath:n,configSource:a}}function IA(s=process.cwd()){let e=xr();if(!J.existsSync(e)){Ff();let t=null,o=Tr(s);if(J.existsSync(o))t=o;else{let n=Pr.join(s,"toolpack.config.json");if(J.existsSync(n))t=n;else{let a=Rr();a&&J.existsSync(a)&&(t=a)}}let r={};if(t)try{let n=J.readFileSync(t,"utf-8");r=JSON.parse(n)}catch{}J.writeFileSync(e,JSON.stringify(r,null,4),"utf-8")}}l();export{kf as AGENT_MODE,io as AIClient,ao as AnthropicAdapter,ge as AuthenticationError,Xe as BM25SearchEngine,wr as BUILT_IN_MODES,Rf as CHAT_MODE,Mf as CONFIG_DIR_NAME,Of as CONFIG_FILE_NAME,ke as ConnectionError,Qe as DEFAULT_MODE_NAME,z as DEFAULT_TOOLS_CONFIG,Yf as DEFAULT_TOOL_SEARCH_CONFIG,os as DEFAULT_WORKFLOW_CONFIG,lo as GeminiAdapter,M as InvalidRequestError,Yt as McpClient,me as McpConnectionError,hr as McpTimeoutError,yr as McpToolManager,Vt as ModeRegistry,De as OllamaAdapter,it as OllamaProvider,po as OpenAIAdapter,ss as PageError,Xt as Planner,Y as ProviderAdapter,F as ProviderError,he as RateLimitError,H as SDKError,Zt as StepExecutor,Af as TOOLPACK_DIR_NAME,Ze as TOOL_SEARCH_NAME,is as TimeoutError,je as ToolDiscoveryCache,Qt as ToolRegistry,et as ToolRouter,Ef as Toolpack,br as WorkflowExecutor,ur as cloudDeployTool,gr as cloudListTool,fr as cloudStatusTool,$f as cloudToolsProject,Jt as codingFindSymbolTool,zt as codingGetImportsTool,Ht as codingGetSymbolsTool,Vd as codingToolsProject,es as createMcpToolProject,Jy as createMode,Wy as createToolProject,mr as dbCountTool,pr as dbDeleteTool,lr as dbInsertTool,sr as dbQueryTool,ir as dbSchemaTool,ar as dbTablesTool,gf as dbToolsProject,cr as dbUpdateTool,er as diffApplyTool,Zo as diffCreateTool,tr as diffPreviewTool,Uu as diffToolsProject,ts as disconnectMcpToolProject,Ff as ensureGlobalConfigDir,RA as ensureLocalConfigDir,_t as execKillTool,kt as execListProcessesTool,$t as execReadOutputTool,St as execRunBackgroundTool,Ct as execRunShellTool,Pt as execRunTool,$l as execToolsProject,Ps as fetchUrlAsBase64,ct as fsAppendFileTool,yt as fsCopyTool,ft as fsCreateDirTool,pt as fsDeleteFileTool,mt as fsExistsTool,ut as fsListDirTool,gt as fsMoveTool,wt as fsReadFileRangeTool,at as fsReadFileTool,xt as fsReplaceInFileTool,bt as fsSearchTool,dt as fsStatTool,La as fsToolsProject,Tt as fsTreeTool,lt as fsWriteFileTool,Sr as generateToolCategoriesPrompt,pg as getDefaultSlmModel,If as getGlobalConfigDir,xr as getGlobalConfigPath,Vy as getGlobalToolpackDir,jf as getLocalConfigDir,Tr as getLocalConfigPath,Xy as getLocalToolpackDir,ws as getMimeType,co as getOllamaBaseUrl,cg as getOllamaProviderEntries,dg as getRegisteredSlmModels,OA as getRuntimeConfigStatus,Cr as getToolSearchSchema,Dr as getToolpackConfig,Yy as getUserHomeDir,zo as gitAddTool,Qo as gitBlameTool,Vo as gitBranchCreateTool,Yo as gitBranchListTool,Xo as gitCheckoutTool,Ko as gitCommitTool,Jo as gitDiffTool,Ho as gitLogTool,Bo as gitStatusTool,$u as gitToolsProject,jt as httpDeleteTool,Ft as httpDownloadTool,Mt as httpGetTool,Ot as httpPostTool,It as httpPutTool,Bc as httpToolsProject,IA as initializeGlobalConfigIfFirstRun,bs as isDataUri,mg as isRegisteredSlm,vr as isToolSearchTool,Po as loadFullConfig,MA as loadRuntimeConfig,qt as loadToolsConfig,ng as normalizeImagePart,ne as ollamaRequest,Er as ollamaStream,xs as parseDataUri,Ts as readFileAsBase64,lg as reloadToolpackConfig,ph as saveToolsConfig,Nt as systemCwdTool,At as systemDiskUsageTool,Dt as systemEnvTool,Rt as systemInfoTool,Et as systemSetEnvTool,ac as systemToolsProject,rg as toDataUri,Fe as toolSearchDefinition,Gt as webExtractLinksTool,Lt as webFetchTool,Wt as webScrapeTool,Ut as webSearchTool,dm as 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();import{EventEmitter as Of}from"events";k();var If=class s extends Of{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 br(this.client,ns,this.client.getQueryClassifier()),this.forwardWorkflowEvents()}static async init(e){let t=Po(e.configPath);ms(t.logging);let r=new Vt,o=Wt(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 T=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:[T]};await r.loadProjects([S]),v("[Knowledge] Registered knowledge_search tool")}catch(T){Q(`[Knowledge] Failed to register knowledge tool: ${T}`)}let n=null,a=e.mcp||t.mcp;if(a)try{v("[MCP] Initializing MCP tool integration");let T=await es(a);n=T,await r.loadProjects([T]),v(`[MCP] Loaded ${T.tools.length} tools from MCP servers`)}catch(T){Q(`[MCP] Failed to initialize MCP tools: ${T}`)}let i=t.systemPrompt,c=e.disableBaseContext||t.disableBaseContext||t.baseContext===!1||!1,p=t.modeOverrides||{},m={},f=new Set,h=e.defaultProvider||e.provider;if(e.providers)for(let[T,S]of Object.entries(e.providers)){let R=T===h,I=await s.createProvider(T,S,e.configPath,!R);I&&(m[T]=I)}else if(e.provider){let T={apiKey:e.apiKey,model:e.model},S=await s.createProvider(e.provider,T,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 T=Array.isArray(e.customProviders)?e.customProviders:Object.entries(e.customProviders).map(([S,R])=>(R.name=R.name||S,R));for(let S of T){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.`);f.add(R),m[R]=S}}if(!h&&e.customProviders&&(h=(Array.isArray(e.customProviders)?e.customProviders[0]:Object.values(e.customProviders)[0])?.name),!h)throw new Error("No default provider specified.");let b=new Zt;if(e.customModes)for(let T of e.customModes)b.register(T);let w={...p,...e.modeOverrides||{}};for(let[T,S]of Object.entries(w)){let R=b.get(T);if(R){S.systemPrompt!==void 0&&(R.systemPrompt=S.systemPrompt),S.toolSearch&&(R.toolSearch={...R.toolSearch||{},...S.toolSearch});for(let[I,U]of Object.entries(S))I!=="systemPrompt"&&I!=="toolSearch"&&(R[I]=U)}}let x=new io({providers:m,defaultProvider:h,toolRegistry:r,toolsConfig:r.getConfig(),systemPrompt:i,disableBaseContext:c}),P=new s(x,h,b);P.customProviderNames=f,P.mcpToolProject=n;let $=e.defaultMode||Ve,C=b.get($);return C&&(x.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 po(a,t.baseUrl);case"anthropic":return new ao(a,t.baseUrl);case"gemini":return new lo(a)}}if(e==="ollama")return new lt({baseUrl:t.baseUrl||co(r)});if(e.startsWith("ollama-")){let n=t.model||e.replace(/^ollama-/,""),a=t.baseUrl||co(r);return new De({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 f of n.plan.steps)if(f.status==="completed"&&f.result?.response?.usage){let h=f.result.response.usage;a+=h.prompt_tokens,i+=h.completion_tokens||0,c+=h.total_tokens,p.steps.push({stepNumber:f.number,description:f.description,usage:h})}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 ts(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(ns),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 Of&&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();import*as jf from"os";import*as Oe from"path";import*as Ze from"fs";var Ff=".toolpack",Lf="config",qf="toolpack.config.json";function nw(){return jf.homedir()}function sw(){return Oe.join(nw(),Ff)}function Uf(){return Oe.join(sw(),Lf)}function xr(){return Oe.join(Uf(),qf)}function iw(s=process.cwd()){return Oe.join(s,Ff)}function Wf(s=process.cwd()){return Oe.join(iw(s),Lf)}function Tr(s=process.cwd()){return Oe.join(Wf(s),qf)}function Gf(){let s=Uf();Ze.existsSync(s)||Ze.mkdirSync(s,{recursive:!0})}function KA(s=process.cwd()){let e=Wf(s);Ze.existsSync(e)||Ze.mkdirSync(e,{recursive:!0})}l();import*as J from"fs";import*as Pr from"path";function is(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]=is(s[r],e[r]):t[r]=e[r];return t}function ss(s){if(!J.existsSync(s))return null;try{let e=J.readFileSync(s,"utf-8");return JSON.parse(e)}catch{return null}}function ZA(s=process.cwd()){let e=Pr.join(s,"toolpack.config.json"),t=xr(),r=Tr(s),o=ss(e)||{},n=ss(t)||{},a=ss(r)||{},i=is(o,n);return i=is(i,a),i}function eM(s=process.cwd()){let e=Pr.join(s,"toolpack.config.json"),t=xr(),r=Tr(s),o=!J.existsSync(t),n=null,a="default";return J.existsSync(r)?(n=r,a="local"):J.existsSync(t)?(n=t,a="global"):J.existsSync(e)&&(n=e,a="base"),{isFirstRun:o,activeConfigPath:n,configSource:a}}function tM(s=process.cwd()){let e=xr();if(!J.existsSync(e)){Gf();let t=null,r=Tr(s);if(J.existsSync(r))t=r;else{let n=Pr.join(s,"toolpack.config.json");if(J.existsSync(n))t=n;else{let a=Rr();a&&J.existsSync(a)&&(t=a)}}let o={};if(t)try{let n=J.readFileSync(t,"utf-8");o=JSON.parse(n)}catch{}J.writeFileSync(e,JSON.stringify(o,null,4),"utf-8")}}l();export{Af as AGENT_MODE,os as AGENT_PLANNING_PROMPT,rs as AGENT_STEP_PROMPT,Ef as AGENT_WORKFLOW,io as AIClient,ao as AnthropicAdapter,ge as AuthenticationError,et as BM25SearchEngine,wr as BUILT_IN_MODES,Mf as CHAT_MODE,Nf as CHAT_WORKFLOW,Yy as CODING_PLANNING_PROMPT,Vy as CODING_STEP_PROMPT,Df as CODING_WORKFLOW,Lf as CONFIG_DIR_NAME,qf as CONFIG_FILE_NAME,ke as ConnectionError,Ve as DEFAULT_MODE_NAME,z as DEFAULT_TOOLS_CONFIG,tg as DEFAULT_TOOL_SEARCH_CONFIG,JN as DEFAULT_WORKFLOW,ns as DEFAULT_WORKFLOW_CONFIG,lo as GeminiAdapter,M as InvalidRequestError,Xt as McpClient,me as McpConnectionError,hr as McpTimeoutError,yr as McpToolManager,Zt as ModeRegistry,De as OllamaAdapter,lt as OllamaProvider,po as OpenAIAdapter,as as PageError,eo as Planner,Y as ProviderAdapter,F as ProviderError,he as RateLimitError,H as SDKError,to as StepExecutor,Ff as TOOLPACK_DIR_NAME,tt as TOOL_SEARCH_NAME,ls as TimeoutError,Fe as ToolDiscoveryCache,Vt as ToolRegistry,ot as ToolRouter,If as Toolpack,br as WorkflowExecutor,ur as cloudDeployTool,gr as cloudListTool,fr as cloudStatusTool,kf as cloudToolsProject,zt as codingFindSymbolTool,Qt as codingGetImportsTool,Kt as codingGetSymbolsTool,Zd as codingToolsProject,es as createMcpToolProject,Zy as createMode,zy as createToolProject,mr as dbCountTool,pr as dbDeleteTool,lr as dbInsertTool,sr as dbQueryTool,ir as dbSchemaTool,ar as dbTablesTool,yf as dbToolsProject,cr as dbUpdateTool,er as diffApplyTool,Zo as diffCreateTool,tr as diffPreviewTool,Gu as diffToolsProject,ts as disconnectMcpToolProject,Gf as ensureGlobalConfigDir,KA as ensureLocalConfigDir,Rt as execKillTool,Et as execListProcessesTool,kt as execReadOutputTool,_t as execRunBackgroundTool,St as execRunShellTool,vt as execRunTool,kl as execToolsProject,vs as fetchUrlAsBase64,mt as fsAppendFileTool,bt as fsCopyTool,ht as fsCreateDirTool,dt as fsDeleteFileTool,ut as fsExistsTool,gt as fsListDirTool,yt as fsMoveTool,xt as fsReadFileRangeTool,ct as fsReadFileTool,Pt as fsReplaceInFileTool,Tt as fsSearchTool,ft as fsStatTool,Ua as fsToolsProject,Ct as fsTreeTool,pt as fsWriteFileTool,Sr as generateToolCategoriesPrompt,gg as getDefaultSlmModel,Uf as getGlobalConfigDir,xr as getGlobalConfigPath,sw as getGlobalToolpackDir,Wf as getLocalConfigDir,Tr as getLocalConfigPath,iw as getLocalToolpackDir,xs as getMimeType,co as getOllamaBaseUrl,fg as getOllamaProviderEntries,yg as getRegisteredSlmModels,eM as getRuntimeConfigStatus,Cr as getToolSearchSchema,Er as getToolpackConfig,nw as getUserHomeDir,zo as gitAddTool,Qo as gitBlameTool,Vo as gitBranchCreateTool,Yo as gitBranchListTool,Xo as gitCheckoutTool,Ko as gitCommitTool,Jo as gitDiffTool,Ho as gitLogTool,Bo as gitStatusTool,ku as gitToolsProject,Lt as httpDeleteTool,qt as httpDownloadTool,It as httpGetTool,jt as httpPostTool,Ft as httpPutTool,Hc as httpToolsProject,tM as initializeGlobalConfigIfFirstRun,Ts as isDataUri,hg as isRegisteredSlm,vr as isToolSearchTool,Po as loadFullConfig,ZA as loadRuntimeConfig,Wt as loadToolsConfig,cg as normalizeImagePart,ne as ollamaRequest,Dr as ollamaStream,Ps as parseDataUri,Cs as readFileAsBase64,ug as reloadToolpackConfig,gh as saveToolsConfig,Mt as systemCwdTool,Ot as systemDiskUsageTool,Nt as systemEnvTool,Dt as systemInfoTool,At as systemSetEnvTool,cc as systemToolsProject,lg as toDataUri,Le as toolSearchDefinition,Jt as webExtractLinksTool,Ut as webFetchTool,Bt as webScrapeTool,Gt as webSearchTool,fm as webToolsProject};