toolpack-sdk 1.3.0 → 1.4.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.cjs CHANGED
@@ -1,59 +1,59 @@
1
- "use strict";var Yg=Object.create;var Go=Object.defineProperty;var Vg=Object.getOwnPropertyDescriptor;var Xg=Object.getOwnPropertyNames;var Zg=Object.getPrototypeOf,eh=Object.prototype.hasOwnProperty;var f=(s,e)=>()=>(s&&(e=s(s=0)),e);var V=(s,e)=>{for(var t in e)Go(s,t,{get:e[t],enumerable:!0})},li=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Xg(e))!eh.call(s,o)&&o!==t&&Go(s,o,{get:()=>e[o],enumerable:!(r=Vg(e,o))||r.enumerable});return s};var T=(s,e,t)=>(t=s!=null?Yg(Zg(s)):{},li(e||!s||!s.__esModule?Go(t,"default",{value:s,enumerable:!0}):t,s)),th=s=>li(Go({},"__esModule",{value:!0}),s);var l=f(()=>{"use strict"});var J,pe,me,N,I,we,Vr,Xr,de=f(()=>{"use strict";l();J=class extends Error{constructor(t,r,o,n){super(t);this.code=r;this.statusCode=o;this.cause=n;this.name="SDKError"}code;statusCode;cause},pe=class extends J{constructor(e,t){super(e,"AUTHENTICATION_ERROR",401,t),this.name="AuthenticationError"}},me=class extends J{constructor(t,r,o){super(t,"RATE_LIMIT_ERROR",429,o);this.retryAfter=r;this.name="RateLimitError"}retryAfter},N=class extends J{constructor(e,t){super(e,"INVALID_REQUEST_ERROR",400,t),this.name="InvalidRequestError"}},I=class extends J{constructor(e,t="PROVIDER_ERROR",r=500,o){super(e,t,r,o),this.name="ProviderError"}},we=class extends J{constructor(e,t){super(e,"CONNECTION_ERROR",503,t),this.name="ConnectionError"}},Vr=class extends J{constructor(t,r,o){super(t,"PAGE_ERROR",502,o);this.pageUrl=r;this.name="PageError"}pageUrl},Xr=class extends J{constructor(t,r,o){super(t,"TIMEOUT_ERROR",504,o);this.phase=r;this.name="TimeoutError"}phase}});var ci,H,Xt=f(()=>{"use strict";l();ci={enabled:!1,alwaysLoadedTools:[],alwaysLoadedCategories:[],searchResultLimit:5,cacheDiscoveredTools:!0},H={enabled:!0,autoExecute:!0,maxToolRounds:5,toolChoicePolicy:"auto",resultMaxChars:2e4,enabledTools:[],enabledToolCategories:[],toolSearch:ci}});function mi(s){if(!s)return;let e=s.toLowerCase();if(e in Zr)return e;console.warn(`[Toolpack Warning] Invalid log level "${s}". Falling back to "info".`)}function fi(s){s?.enabled!==void 0&&(Ko=s.enabled),s?.filePath&&(en=s.filePath),s?.level&&(Qo=mi(s.level)||"info"),process.env.TOOLPACK_SDK_LOG_ENABLED!==void 0&&(Ko=process.env.TOOLPACK_SDK_LOG_ENABLED==="true"),process.env.TOOLPACK_SDK_LOG_FILE&&(en=process.env.TOOLPACK_SDK_LOG_FILE,Ko=!0),process.env.TOOLPACK_SDK_LOG_LEVEL&&(Qo=mi(process.env.TOOLPACK_SDK_LOG_LEVEL)||Qo)}function Me(s){return Ko?Zr[s]<=Zr[Qo]:!1}function Zt(s,e){if(!Me(s))return;let r=`[${new Date().toISOString()}] [${s.toUpperCase()}] ${e}
2
- `;(0,di.appendFileSync)(en,r)}function Y(s){Zt("error",s)}function E(s){Zt("warn",s)}function v(s){Zt("info",s)}function h(s){Zt("debug",s)}function be(s){Zt("trace",s)}function nh(s){return s.replace(/\bsk-[A-Za-z0-9_-]{10,}\b/g,"[REDACTED]").replace(/\bsk-proj-[A-Za-z0-9_-]{10,}\b/g,"[REDACTED]").replace(/\bAIza[0-9A-Za-z_-]{10,}\b/g,"[REDACTED]").replace(/\bBearer\s+[A-Za-z0-9._-]{10,}\b/g,"Bearer [REDACTED]")}function D(s,e=200){try{let t=typeof s=="string"?s:JSON.stringify(s),r=nh(t);return r.length<=e?r:`${r.slice(0,e)}\u2026`}catch{return"[Unserializable]"}}function X(s,e,t){Me("debug")&&(h(`[${e}][${s}] Messages (${t.length}):`),t.forEach((r,o)=>{h(`[${e}][${s}] #${o} role=${r?.role} content=${D(r?.content,300)}`)}))}var di,ui,Zr,Ko,Qo,en,k=f(()=>{"use strict";l();di=require("fs"),ui=require("path"),Zr={error:0,warn:1,info:2,debug:3,trace:4},Ko=!1,Qo="info",en=(0,ui.join)(process.cwd(),"toolpack-sdk.log")});var to={};V(to,{fetchUrlAsBase64:()=>an,getMimeType:()=>on,isDataUri:()=>rn,normalizeImagePart:()=>Si,parseDataUri:()=>nn,readFileAsBase64:()=>sn,toDataUri:()=>vi});function on(s){let e=Ci.extname(s).toLowerCase();return ih[e]||"application/octet-stream"}function rn(s){return s.startsWith("data:")}function nn(s){let e=s.match(/^data:(.*?);base64,(.+)$/);return e?{mimeType:e[1],data:e[2]}:null}function vi(s,e){return`data:${e};base64,${s}`}async function sn(s){try{return{data:(await Pi.readFile(s)).toString("base64"),mimeType:on(s)}}catch(e){throw new N(`Failed to read image file: ${s}`,e)}}async function an(s){try{let e=await fetch(s);if(!e.ok)throw new Error(`HTTP ${e.status} ${e.statusText}`);let t=await e.arrayBuffer(),r=Buffer.from(t),o=e.headers.get("content-type")||"application/octet-stream";return o=o.split(";")[0].trim(),{data:r.toString("base64"),mimeType:o}}catch(e){throw new I(`Failed to download image from URL: ${s}`,"FETCH_ERROR",500,e)}}async function Si(s){if(s.type==="image_data")return{data:s.image_data.data,mimeType:s.image_data.mimeType};if(s.type==="image_file")return await sn(s.image_file.path);if(s.type==="image_url"){let e=s.image_url.url;if(rn(e)){let t=nn(e);if(!t)throw new N(`Malformed data URI provided in image_url: ${e.substring(0,50)}...`);return t}return await an(e)}throw new N(`Unknown ImagePart type: ${s.type}`)}var Pi,Ci,ih,ze=f(()=>{"use strict";l();Pi=T(require("fs/promises"),1),Ci=T(require("path"),1);de();ih={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".heic":"image/heic",".heif":"image/heif"}});var Ai,Mi,Oi,Ii,ji,Fi=f(()=>{"use strict";l();Ai="fs.read_file",Mi="Read File",Oi="Read the contents of a file at the given path. Returns the file content as a string.",Ii="filesystem",ji={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path"]}});async function ch(s){let e=s.path,t=s.encoding||"utf-8";if(h(`[fs.read-file] execute path="${e}" encoding=${t}`),!e)throw new Error("path is required");if(!Qe.existsSync(e))throw new Error(`File not found: ${e}`);if(Qe.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);return Qe.readFileSync(e,t)}var Qe,Ye,un=f(()=>{"use strict";l();Qe=T(require("fs"),1);Fi();k();Ye={name:Ai,displayName:Mi,description:Oi,parameters:ji,category:Ii,execute:ch}});var Li,qi,Ui,Wi,Gi,Bi=f(()=>{"use strict";l();Li="fs.write_file",qi="Write File",Ui="Write content to a file. Creates parent directories if they do not exist. Overwrites existing files.",Wi="filesystem",Gi={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to write"},content:{type:"string",description:"Content to write to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});async function ph(s){let e=s.path,t=s.content,r=s.encoding||"utf-8";if(h(`[fs.write-file] execute path="${e}" encoding=${r} content_len=${t?.length??0}`),!e)throw new Error("path is required");if(t==null)throw new Error("content is required");let o=Ji.dirname(e);return Ve.existsSync(o)||Ve.mkdirSync(o,{recursive:!0}),Ve.writeFileSync(e,t,r),`File written successfully: ${e} (${Buffer.byteLength(t,r)} bytes)`}var Ve,Ji,Xe,fn=f(()=>{"use strict";l();Ve=T(require("fs"),1),Ji=T(require("path"),1);Bi();k();Xe={name:Li,displayName:qi,description:Ui,parameters:Gi,category:Wi,execute:ph}});var Hi,zi,Ki,Qi,Yi,Vi=f(()=>{"use strict";l();Hi="fs.append_file",zi="Append File",Ki="Append content to the end of a file. Creates the file if it does not exist.",Qi="filesystem",Yi={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to append to"},content:{type:"string",description:"Content to append to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});async function mh(s){let e=s.path,t=s.content,r=s.encoding||"utf-8";if(!e)throw new Error("path is required");if(t==null)throw new Error("content is required");let o=Xi.dirname(e);return Ze.existsSync(o)||Ze.mkdirSync(o,{recursive:!0}),Ze.appendFileSync(e,t,r),`Content appended to: ${e} (${Buffer.byteLength(t,r)} bytes appended)`}var Ze,Xi,et,gn=f(()=>{"use strict";l();Ze=T(require("fs"),1),Xi=T(require("path"),1);Vi();et={name:Hi,displayName:zi,description:Ki,parameters:Yi,category:Qi,execute:mh}});var Zi,ea,ta,oa,ra,na=f(()=>{"use strict";l();Zi="fs.delete_file",ea="Delete File",ta="Delete a file at the given path. Does not delete directories.",oa="filesystem",ra={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to delete"}},required:["path"]}});async function dh(s){let e=s.path;if(h(`[fs.delete-file] execute path="${e}"`),!e)throw new Error("path is required");if(!tt.existsSync(e))throw new Error(`File not found: ${e}`);if(tt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}. Use a different tool to remove directories.`);return tt.unlinkSync(e),`File deleted successfully: ${e}`}var tt,ot,hn=f(()=>{"use strict";l();tt=T(require("fs"),1);na();k();ot={name:Zi,displayName:ea,description:ta,parameters:ra,category:oa,execute:dh}});var sa,ia,aa,la,ca,pa=f(()=>{"use strict";l();sa="fs.exists",ia="Exists",aa="Check if a file or directory exists at the given path. Returns true or false.",la="filesystem",ca={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to check"}},required:["path"]}});async function uh(s){let e=s.path;if(!e)throw new Error("path is required");let t=ma.existsSync(e);return JSON.stringify({exists:t,path:e})}var ma,rt,yn=f(()=>{"use strict";l();ma=T(require("fs"),1);pa();rt={name:sa,displayName:ia,description:aa,parameters:ca,category:la,execute:uh}});var da,ua,fa,ga,ha,ya=f(()=>{"use strict";l();da="fs.stat",ua="Stat",fa="Get file or directory information including size, type, and modification date.",ga="filesystem",ha={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to get info for"}},required:["path"]}});async function fh(s){let e=s.path;if(!e)throw new Error("path is required");if(!Zo.existsSync(e))throw new Error(`Path not found: ${e}`);let t=Zo.statSync(e);return JSON.stringify({path:e,type:t.isDirectory()?"directory":t.isFile()?"file":"other",size:t.size,created:t.birthtime.toISOString(),modified:t.mtime.toISOString(),accessed:t.atime.toISOString(),permissions:t.mode.toString(8)})}var Zo,nt,wn=f(()=>{"use strict";l();Zo=T(require("fs"),1);ya();nt={name:da,displayName:ua,description:fa,parameters:ha,category:ga,execute:fh}});var wa,ba,xa,Ta,Pa,Ca=f(()=>{"use strict";l();wa="fs.list_dir",ba="List Directory",xa="List files and directories at the given path. Optionally recurse into subdirectories.",Ta="filesystem",Pa={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to list"},recursive:{type:"boolean",description:"Whether to list recursively (default: false)",default:!1}},required:["path"]}});function Sa(s,e,t,r=""){let o=Oe.readdirSync(s,{withFileTypes:!0});for(let n of o){let a=va.join(s,n.name),i=r?`${r}/${n.name}`:n.name;if(n.isDirectory())t.push({name:i,type:"directory",size:0}),e&&Sa(a,!0,t,i);else if(n.isFile()){let c=Oe.statSync(a);t.push({name:i,type:"file",size:c.size})}}}async function gh(s){let e=s.path,t=s.recursive===!0;if(!e)throw new Error("path is required");if(!Oe.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Oe.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let o=[];return Sa(e,t,o),JSON.stringify(o,null,2)}var Oe,va,st,bn=f(()=>{"use strict";l();Oe=T(require("fs"),1),va=T(require("path"),1);Ca();st={name:wa,displayName:ba,description:xa,parameters:Pa,category:Ta,execute:gh}});var $a,_a,ka,Ra,Ea,Da=f(()=>{"use strict";l();$a="fs.create_dir",_a="Create Directory",ka="Create a directory at the given path. Creates parent directories recursively if they do not exist.",Ra="filesystem",Ea={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to create"},recursive:{type:"boolean",description:"Create parent directories if they do not exist (default: true)",default:!0}},required:["path"]}});async function hh(s){let e=s.path,t=s.recursive!==!1;if(!e)throw new Error("path is required");if(it.existsSync(e)){if(it.statSync(e).isDirectory())return`Directory already exists: ${e}`;throw new Error(`Path exists but is not a directory: ${e}`)}return it.mkdirSync(e,{recursive:t}),`Directory created: ${e}`}var it,at,xn=f(()=>{"use strict";l();it=T(require("fs"),1);Da();at={name:$a,displayName:_a,description:ka,parameters:Ea,category:Ra,execute:hh}});var Na,Aa,Ma,Oa,Ia,ja=f(()=>{"use strict";l();Na="fs.move",Aa="Move",Ma="Move or rename a file or directory from one path to another.",Oa="filesystem",Ia={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});async function yh(s){let e=s.path,t=s.new_path;if(!e)throw new Error("path is required");if(!t)throw new Error("new_path is required");if(!Ie.existsSync(e))throw new Error(`Source not found: ${e}`);let r=Fa.dirname(t);return Ie.existsSync(r)||Ie.mkdirSync(r,{recursive:!0}),Ie.renameSync(e,t),`Moved: ${e} \u2192 ${t}`}var Ie,Fa,lt,Tn=f(()=>{"use strict";l();Ie=T(require("fs"),1),Fa=T(require("path"),1);ja();lt={name:Na,displayName:Aa,description:Ma,parameters:Ia,category:Oa,execute:yh}});var La,qa,Ua,Wa,Ga,Ba=f(()=>{"use strict";l();La="fs.copy",qa="Copy",Ua="Copy a file or directory from one path to another. Recursively copies directories.",Wa="filesystem",Ga={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});function Ja(s,e){if(Q.statSync(s).isDirectory()){Q.existsSync(e)||Q.mkdirSync(e,{recursive:!0});let r=Q.readdirSync(s);for(let o of r)Ja(lo.join(s,o),lo.join(e,o))}else Q.copyFileSync(s,e)}async function wh(s){let e=s.path,t=s.new_path;if(!e)throw new Error("path is required");if(!t)throw new Error("new_path is required");if(!Q.existsSync(e))throw new Error(`Source not found: ${e}`);let r=lo.dirname(t);return Q.existsSync(r)||Q.mkdirSync(r,{recursive:!0}),Ja(e,t),`Copied ${Q.statSync(e).isDirectory()?"directory":"file"}: ${e} \u2192 ${t}`}var Q,lo,ct,Pn=f(()=>{"use strict";l();Q=T(require("fs"),1),lo=T(require("path"),1);Ba();ct={name:La,displayName:qa,description:Ua,parameters:Ga,category:Wa,execute:wh}});var Ha,za,Ka,Qa,Ya,Va=f(()=>{"use strict";l();Ha="fs.read_file_range",za="Read File Range",Ka="Read a specific range of lines from a file. Useful for reading portions of large files without loading the entire content.",Qa="filesystem",Ya={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},start_line:{type:"integer",description:"Start line number (1-indexed)"},end_line:{type:"integer",description:"End line number (1-indexed, inclusive)"}},required:["path","start_line","end_line"]}});async function bh(s){let e=s.path,t=s.start_line,r=s.end_line;if(!e)throw new Error("path is required");if(t==null)throw new Error("start_line is required");if(r==null)throw new Error("end_line is required");if(t<1)throw new Error("start_line must be >= 1");if(r<t)throw new Error("end_line must be >= start_line");if(!pt.existsSync(e))throw new Error(`File not found: ${e}`);if(pt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let a=pt.readFileSync(e,"utf-8").split(`
3
- `),i=a.length,c=Math.min(t,i),p=Math.min(r,i),u=a.slice(c-1,p).map((g,w)=>`${c+w}: ${g}`).join(`
4
- `);return`Lines ${c}-${p} of ${i} total:
5
- ${u}`}var pt,mt,Cn=f(()=>{"use strict";l();pt=T(require("fs"),1);Va();mt={name:Ha,displayName:za,description:Ka,parameters:Ya,category:Qa,execute:bh}});var Xa,Za,el,tl,ol,rl=f(()=>{"use strict";l();Xa="fs.search",Za="Search",el="Search for text in files within a directory. Returns matching lines with file paths and line numbers.",tl="filesystem",ol={type:"object",properties:{path:{type:"string",description:"Directory path to search in"},query:{type:"string",description:"Text or pattern to search for"},recursive:{type:"boolean",description:"Search recursively in subdirectories (default: true)",default:!0},max_results:{type:"integer",description:"Maximum number of matching lines to return (default: 50)",default:50},regex:{type:"boolean",description:"Treat query as a regular expression (default: false)",default:!1},case_sensitive:{type:"boolean",description:"Perform case-sensitive search. If false, search is case-insensitive (default: false)",default:!1}},required:["path","query"]}});function xh(s,e,t,r){try{let n=Te.readFileSync(s,"utf-8").split(`
6
- `);for(let a=0;a<n.length&&t.length<r;a++){let i=n[a];(typeof e=="string"?i.includes(e):e.test(i))&&t.push({file:s,line:a+1,content:i.trim()})}}catch{}}function sl(s,e,t,r,o){let n=Te.readdirSync(s,{withFileTypes:!0});for(let a of n){if(r.length>=o)break;let i=nl.join(s,a.name);a.isDirectory()&&t?sl(i,e,!0,r,o):a.isFile()&&xh(i,e,r,o)}}async function Th(s){let e=s.path,t=s.query,r=s.recursive!==!1,o=s.max_results||50,n=!!s.regex,a=!!s.case_sensitive;if(h(`[fs.search] execute path="${e}" query="${t}" recursive=${r} regex=${n} caseSensitive=${a}`),!e)throw new Error("path is required");if(!t)throw new Error("query is required");let i=t;if(n||!a){let u=t;n||(u=u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));let g=a?"":"i";i=new RegExp(u,g)}if(!Te.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Te.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let p=[];if(sl(e,i,r,p,o),p.length===0)return`No matches found for "${t}" in ${e}`;let m=p.length>=o?`
7
- (results capped at ${o})`:"";return JSON.stringify(p,null,2)+m}var Te,nl,dt,vn=f(()=>{"use strict";l();Te=T(require("fs"),1),nl=T(require("path"),1);rl();k();dt={name:Xa,displayName:Za,description:el,parameters:ol,category:tl,execute:Th}});var il,al,ll,cl,pl,ml=f(()=>{"use strict";l();il="fs.replace_in_file",al="Replace In File",ll="Find and replace text in a file. Returns the number of replacements made.",cl="filesystem",pl={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path"},search:{type:"string",description:"Text to search for"},replace:{type:"string",description:"Text to replace with"}},required:["path","search","replace"]}});async function Ph(s){let e=s.path,t=s.search,r=s.replace;if(!e)throw new Error("path is required");if(!t)throw new Error("search is required");if(r==null)throw new Error("replace is required");if(!Pe.existsSync(e))throw new Error(`File not found: ${e}`);if(Pe.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let n=Pe.readFileSync(e,"utf-8"),a=0,i=0;for(;(i=n.indexOf(t,i))!==-1;)a++,i+=t.length;if(a===0)return`No occurrences of "${t}" found in ${e}`;let c=n.split(t).join(r);return Pe.writeFileSync(e,c,"utf-8"),`Replaced ${a} occurrence(s) in ${e}`}var Pe,ut,Sn=f(()=>{"use strict";l();Pe=T(require("fs"),1);ml();ut={name:il,displayName:al,description:ll,parameters:pl,category:cl,execute:Ph}});var dl,ul,fl,gl,hl,yl=f(()=>{"use strict";l();dl="fs.tree",ul="Tree",fl="Get a tree representation of a directory structure. Useful for understanding project layout at a glance.",gl="filesystem",hl={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path"},depth:{type:"integer",description:"Maximum depth to traverse (default: 3)",default:3}},required:["path"]}});function wl(s,e,t,r,o){if(t>r)return;let a=ft.readdirSync(s,{withFileTypes:!0}).sort((i,c)=>i.isDirectory()&&!c.isDirectory()?-1:!i.isDirectory()&&c.isDirectory()?1:i.name.localeCompare(c.name));for(let i=0;i<a.length;i++){let c=a[i],p=i===a.length-1,m=p?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",u=p?" ":"\u2502 ";c.isDirectory()?(o.push(`${e}${m}${c.name}/`),wl(er.join(s,c.name),e+u,t+1,r,o)):o.push(`${e}${m}${c.name}`)}}async function Ch(s){let e=s.path,t=s.depth||3;if(!e)throw new Error("path is required");if(!ft.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!ft.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let n=[`${er.basename(e)}/`];return wl(e,"",1,t,n),n.join(`
8
- `)}var ft,er,gt,$n=f(()=>{"use strict";l();ft=T(require("fs"),1),er=T(require("path"),1);yl();gt={name:dl,displayName:ul,description:fl,parameters:hl,category:gl,execute:Ch}});var bl,xl,Tl,Pl,Cl,vl=f(()=>{"use strict";l();bl="fs.glob",xl="Glob Pattern Match",Tl='Find files matching glob patterns (e.g., "**/*.ts", "src/**/*.test.js")',Pl="filesystem",Cl={type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files (e.g., "**/*.ts", "src/**/*.json")'},cwd:{type:"string",description:"Root directory to search from (defaults to current working directory)"},ignore:{type:"array",items:{type:"string"},description:'Patterns to ignore (e.g., ["node_modules/**", "dist/**"])'},onlyFiles:{type:"boolean",description:"Return only files, not directories (default: true)"},onlyDirectories:{type:"boolean",description:"Return only directories, not files (default: false)"},absolute:{type:"boolean",description:"Return absolute paths instead of relative (default: false)"}},required:["pattern"]}});async function vh(s){let e=s.pattern,t=s.cwd,r=s.ignore,o=s.onlyFiles!==!1,n=s.onlyDirectories===!0,a=s.absolute===!0;if(!e)throw new Error("pattern is required");let i=e.replace(/\\/g,"/");try{let c=await(0,Sl.default)(i,{cwd:t||process.cwd(),ignore:r||["node_modules/**",".git/**"],onlyFiles:o,onlyDirectories:n,absolute:a,dot:!0});return JSON.stringify({pattern:e,files:c,count:c.length},null,2)}catch(c){throw new Error(`Failed to glob pattern "${e}": ${c.message}`)}}var Sl,tr,_n=f(()=>{"use strict";l();Sl=T(require("fast-glob"),1);vl();tr={name:bl,displayName:xl,description:Tl,parameters:Cl,category:Pl,execute:vh}});var $l,_l,kl,Rl,El,Dl=f(()=>{"use strict";l();$l="fs.delete_dir",_l="Delete Directory",kl="Delete a directory and all its contents recursively",Rl="filesystem",El={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to the directory to delete"},force:{type:"boolean",description:"Force deletion even if directory is not empty (default: true)"}},required:["path"]}});async function Sh(s){let e=s.path,t=s.force!==!1;if(!e)throw new Error("path is required");if(!(0,or.existsSync)(e))throw new Error(`Directory does not exist: ${e}`);if(!(0,or.statSync)(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);try{return await(0,Nl.rm)(e,{recursive:!0,force:t}),`Directory deleted successfully: ${e}`}catch(o){throw new Error(`Failed to delete directory "${e}": ${o.message}`)}}var Nl,or,rr,kn=f(()=>{"use strict";l();Nl=require("fs/promises"),or=require("fs");Dl();rr={name:$l,displayName:_l,description:kl,parameters:El,category:Rl,execute:Sh}});var Al,Ml,Ol,Il,jl,Fl=f(()=>{"use strict";l();Al="fs.batch_read",Ml="Batch Read Files",Ol="Read multiple files efficiently in one operation. Returns content for each file or error if read fails.",Il="filesystem",jl={type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Array of file paths to read"},encoding:{type:"string",description:"File encoding (default: utf-8)"},continueOnError:{type:"boolean",description:"Continue reading other files if one fails (default: true)"}},required:["paths"]}});async function $h(s){let e=s.paths,t=s.encoding||"utf-8",r=s.continueOnError!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("paths array is required and must not be empty");let o=[],n=0,a=0;for(let i of e)try{let c=await(0,Ll.readFile)(i,t);o.push({path:i,content:c,success:!0}),n++}catch(c){let p=c.message;if(o.push({path:i,error:p,success:!1}),a++,!r)throw new Error(`Failed to read file "${i}": ${p}`)}return JSON.stringify({total:e.length,success:n,failed:a,results:o},null,2)}var Ll,nr,Rn=f(()=>{"use strict";l();Ll=require("fs/promises");Fl();nr={name:Al,displayName:Ml,description:Ol,parameters:jl,category:Il,execute:$h}});var ql,Ul,Wl,Gl,Bl,Jl=f(()=>{"use strict";l();ql="fs.batch_write",Ul="Batch Write Files",Wl="Write multiple files atomically in one operation. If atomic mode is enabled, all writes succeed or all are rolled back on failure.",Gl="filesystem",Bl={type:"object",properties:{files:{type:"array",items:{type:"object",properties:{path:{type:"string"},content:{type:"string"}}},description:"Array of files to write, each with path and content"},encoding:{type:"string",description:"File encoding (default: utf-8)"},atomic:{type:"boolean",description:"Atomic mode: rollback all writes if any fails (default: true)"},createDirs:{type:"boolean",description:"Create parent directories if they don't exist (default: true)"}},required:["files"]}});async function _h(s){let e=s.files,t=s.encoding||"utf-8",r=s.atomic!==!1,o=s.createDirs!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("files array is required and must not be empty");for(let i of e)if(!i.path||i.content===void 0)throw new Error("Each file must have path and content properties");let n=[],a=[];try{for(let i of e){let c=(0,sr.resolve)(i.path);if(r){let p=(0,En.existsSync)(c),m={path:c,existed:p};p&&(m.originalContent=await(0,ue.readFile)(c,t)),n.push(m)}if(o){let p=(0,sr.dirname)(c);await(0,ue.mkdir)(p,{recursive:!0})}await(0,ue.writeFile)(c,i.content,t),a.push(c)}return JSON.stringify({success:!0,written:a.length,files:a},null,2)}catch(i){if(r&&n.length>0){for(let c of n)try{c.existed&&c.originalContent!==void 0?await(0,ue.writeFile)(c.path,c.originalContent,t):!c.existed&&(0,En.existsSync)(c.path)&&await(0,ue.unlink)(c.path)}catch{}throw new Error(`Batch write failed and rolled back: ${i.message}`)}throw new Error(`Batch write failed: ${i.message}`)}}var ue,sr,En,ir,Dn=f(()=>{"use strict";l();ue=require("fs/promises"),sr=require("path"),En=require("fs");Jl();ir={name:ql,displayName:Ul,description:Wl,parameters:Bl,category:Gl,execute:_h}});var Hl={};V(Hl,{fsAppendFileTool:()=>et,fsBatchReadTool:()=>nr,fsBatchWriteTool:()=>ir,fsCopyTool:()=>ct,fsCreateDirTool:()=>at,fsDeleteDirTool:()=>rr,fsDeleteFileTool:()=>ot,fsExistsTool:()=>rt,fsGlobTool:()=>tr,fsListDirTool:()=>st,fsMoveTool:()=>lt,fsReadFileRangeTool:()=>mt,fsReadFileTool:()=>Ye,fsReplaceInFileTool:()=>ut,fsSearchTool:()=>dt,fsStatTool:()=>nt,fsToolsProject:()=>Nn,fsTreeTool:()=>gt,fsWriteFileTool:()=>Xe});var Nn,An=f(()=>{"use strict";l();un();fn();gn();hn();yn();wn();bn();xn();Tn();Pn();Cn();vn();Sn();$n();_n();kn();Rn();Dn();un();fn();gn();hn();yn();wn();bn();xn();Tn();Pn();Cn();vn();Sn();$n();_n();kn();Rn();Dn();Nn={manifest:{key:"fs",name:"fs-tools",displayName:"File System",version:"1.0.0",description:"File system tools for reading, writing, searching, and managing files and directories.",author:"Sajeer",tools:["fs.read_file","fs.write_file","fs.append_file","fs.delete_file","fs.exists","fs.stat","fs.list_dir","fs.create_dir","fs.move","fs.copy","fs.read_file_range","fs.search","fs.replace_in_file","fs.tree","fs.glob","fs.delete_dir","fs.batch_read","fs.batch_write"],category:"filesystem"},tools:[Ye,Xe,et,ot,rt,nt,st,at,lt,ct,mt,dt,ut,gt,tr,rr,nr,ir],dependencies:{"fast-glob":"^3.3.2"}}});var zl,Kl,Ql,Yl,Vl,Xl=f(()=>{"use strict";l();zl="exec.run",Kl="Run",Ql="Execute a command directly (without shell) and return its output. Use exec.run_shell for pipes, redirects, or shell features.",Yl="execution",Vl={type:"object",properties:{command:{type:"string",description:"The command to execute"},cwd:{type:"string",description:"Working directory for the command (optional)"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["command"]}});async function kh(s){let e=s.command,t=s.cwd,r=s.timeout||3e4;if(!e)throw new Error("command is required");h(`[exec.run] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${r}ms`);try{return(0,Zl.execSync)(e,{cwd:t,timeout:r,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"]})||"(command completed with no output)"}catch(o){let n=o.stdout||"",a=o.stderr||"";return`Command failed (exit code ${o.status??"unknown"}):
1
+ "use strict";var bh=Object.create;var zo=Object.defineProperty;var xh=Object.getOwnPropertyDescriptor;var Th=Object.getOwnPropertyNames;var Ph=Object.getPrototypeOf,Ch=Object.prototype.hasOwnProperty;var f=(n,e)=>()=>(n&&(e=n(n=0)),e);var Z=(n,e)=>{for(var t in e)zo(n,t,{get:e[t],enumerable:!0})},ki=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Th(e))!Ch.call(n,r)&&r!==t&&zo(n,r,{get:()=>e[r],enumerable:!(o=xh(e,r))||o.enumerable});return n};var x=(n,e,t)=>(t=n!=null?bh(Ph(n)):{},ki(e||!n||!n.__esModule?zo(t,"default",{value:n,enumerable:!0}):t,n)),vh=n=>ki(zo({},"__esModule",{value:!0}),n);var l=f(()=>{"use strict"});var W,fe,ge,M,q,Te,hn,yn,le=f(()=>{"use strict";l();W=class extends Error{constructor(t,o,r,s){super(t);this.code=o;this.statusCode=r;this.cause=s;this.name="SDKError"}code;statusCode;cause},fe=class extends W{constructor(e,t){super(e,"AUTHENTICATION_ERROR",401,t),this.name="AuthenticationError"}},ge=class extends W{constructor(t,o,r){super(t,"RATE_LIMIT_ERROR",429,r);this.retryAfter=o;this.name="RateLimitError"}retryAfter},M=class extends W{constructor(e,t){super(e,"INVALID_REQUEST_ERROR",400,t),this.name="InvalidRequestError"}},q=class extends W{constructor(e,t="PROVIDER_ERROR",o=500,r){super(e,t,o,r),this.name="ProviderError"}},Te=class extends W{constructor(e,t){super(e,"CONNECTION_ERROR",503,t),this.name="ConnectionError"}},hn=class extends W{constructor(t,o,r){super(t,"PAGE_ERROR",502,r);this.pageUrl=o;this.name="PageError"}pageUrl},yn=class extends W{constructor(t,o,r){super(t,"TIMEOUT_ERROR",504,r);this.phase=o;this.name="TimeoutError"}phase}});var $i,H,ro=f(()=>{"use strict";l();$i={enabled:!1,alwaysLoadedTools:[],alwaysLoadedCategories:[],searchResultLimit:5,cacheDiscoveredTools:!0},H={enabled:!0,autoExecute:!0,maxToolRounds:5,toolChoicePolicy:"auto",resultMaxChars:2e4,enabledTools:[],enabledToolCategories:[],toolSearch:$i}});function Ri(n){if(!n)return;let e=n.toLowerCase();if(e in wn)return e;console.warn(`[Toolpack Warning] Invalid log level "${n}". Falling back to "info".`)}function Ni(n){n?.enabled!==void 0&&(Zo=n.enabled),n?.filePath&&(bn=n.filePath),n?.level&&(er=Ri(n.level)||"info"),process.env.TOOLPACK_SDK_LOG_ENABLED!==void 0&&(Zo=process.env.TOOLPACK_SDK_LOG_ENABLED==="true"),process.env.TOOLPACK_SDK_LOG_FILE&&(bn=process.env.TOOLPACK_SDK_LOG_FILE,Zo=!0),process.env.TOOLPACK_SDK_LOG_LEVEL&&(er=Ri(process.env.TOOLPACK_SDK_LOG_LEVEL)||er)}function Le(n){return Zo?wn[n]<=wn[er]:!1}function no(n,e){if(!Le(n))return;let o=`[${new Date().toISOString()}] [${n.toUpperCase()}] ${e}
2
+ `;(0,Di.appendFileSync)(bn,o)}function Q(n){no("error",n)}function E(n){no("warn",n)}function v(n){no("info",n)}function h(n){no("debug",n)}function Pe(n){no("trace",n)}function $h(n){return n.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 A(n,e=200){try{let t=typeof n=="string"?n:JSON.stringify(n),o=$h(t);return o.length<=e?o:`${o.slice(0,e)}\u2026`}catch{return"[Unserializable]"}}function ee(n,e,t){Le("debug")&&(h(`[${e}][${n}] Messages (${t.length}):`),t.forEach((o,r)=>{h(`[${e}][${n}] #${r} role=${o?.role} content=${A(o?.content,300)}`)}))}var Di,Ei,wn,Zo,er,bn,_=f(()=>{"use strict";l();Di=require("fs"),Ei=require("path"),wn={error:0,warn:1,info:2,debug:3,trace:4},Zo=!1,er="info",bn=(0,Ei.join)(process.cwd(),"toolpack-sdk.log")});var io={};Z(io,{fetchUrlAsBase64:()=>Sn,getMimeType:()=>Tn,isDataUri:()=>Pn,normalizeImagePart:()=>Gi,parseDataUri:()=>Cn,readFileAsBase64:()=>vn,toDataUri:()=>Wi});function Tn(n){let e=Ui.extname(n).toLowerCase();return Rh[e]||"application/octet-stream"}function Pn(n){return n.startsWith("data:")}function Cn(n){let e=n.match(/^data:(.*?);base64,(.+)$/);return e?{mimeType:e[1],data:e[2]}:null}function Wi(n,e){return`data:${e};base64,${n}`}async function vn(n){try{return{data:(await qi.readFile(n)).toString("base64"),mimeType:Tn(n)}}catch(e){throw new M(`Failed to read image file: ${n}`,e)}}async function Sn(n){try{let e=await fetch(n);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 q(`Failed to download image from URL: ${n}`,"FETCH_ERROR",500,e)}}async function Gi(n){if(n.type==="image_data")return{data:n.image_data.data,mimeType:n.image_data.mimeType};if(n.type==="image_file")return await vn(n.image_file.path);if(n.type==="image_url"){let e=n.image_url.url;if(Pn(e)){let t=Cn(e);if(!t)throw new M(`Malformed data URI provided in image_url: ${e.substring(0,50)}...`);return t}return await Sn(e)}throw new M(`Unknown ImagePart type: ${n.type}`)}var qi,Ui,Rh,Xe=f(()=>{"use strict";l();qi=x(require("fs/promises"),1),Ui=x(require("path"),1);le();Rh={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".heic":"image/heic",".heif":"image/heif"}});var Zi,ea,ta,oa,ra,na=f(()=>{"use strict";l();Zi="fs.read_file",ea="Read File",ta="Read the contents of a file at the given path. Returns the file content as a string.",oa="filesystem",ra={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path"]}});async function Dh(n){let e=n.path,t=n.encoding||"utf-8";if(h(`[fs.read-file] execute path="${e}" encoding=${t}`),!e)throw new Error("path is required");if(!et.existsSync(e))throw new Error(`File not found: ${e}`);if(et.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);return et.readFileSync(e,t)}var et,tt,En=f(()=>{"use strict";l();et=x(require("fs"),1);na();_();tt={name:Zi,displayName:ea,description:ta,parameters:ra,category:oa,execute:Dh}});var sa,ia,aa,la,ca,pa=f(()=>{"use strict";l();sa="fs.write_file",ia="Write File",aa="Write content to a file. Creates parent directories if they do not exist. Overwrites existing files. IMPORTANT: Do NOT use this to delete/remove files - use fs.delete_file for that.",la="filesystem",ca={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to write"},content:{type:"string",description:"Content to write to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});async function Eh(n){let e=n.path,t=n.content,o=n.encoding||"utf-8";if(h(`[fs.write-file] execute path="${e}" encoding=${o} content_len=${t?.length??0}`),!e)throw new Error("path is required");if(t==null)throw new Error("content is required");let r=ma.dirname(e);return ot.existsSync(r)||ot.mkdirSync(r,{recursive:!0}),ot.writeFileSync(e,t,o),`File written successfully: ${e} (${Buffer.byteLength(t,o)} bytes)`}var ot,ma,rt,Nn=f(()=>{"use strict";l();ot=x(require("fs"),1),ma=x(require("path"),1);pa();_();rt={name:sa,displayName:ia,description:aa,parameters:ca,category:la,execute:Eh,confirmation:{level:"high",reason:"This will overwrite the entire file contents.",showArgs:["path"]}}});var da,ua,fa,ga,ha,ya=f(()=>{"use strict";l();da="fs.append_file",ua="Append File",fa="Append content to the end of a file. Creates the file if it does not exist.",ga="filesystem",ha={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to append to"},content:{type:"string",description:"Content to append to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});async function Nh(n){let e=n.path,t=n.content,o=n.encoding||"utf-8";if(!e)throw new Error("path is required");if(t==null)throw new Error("content is required");let r=wa.dirname(e);return nt.existsSync(r)||nt.mkdirSync(r,{recursive:!0}),nt.appendFileSync(e,t,o),`Content appended to: ${e} (${Buffer.byteLength(t,o)} bytes appended)`}var nt,wa,st,An=f(()=>{"use strict";l();nt=x(require("fs"),1),wa=x(require("path"),1);ya();st={name:da,displayName:ua,description:fa,parameters:ha,category:ga,execute:Nh,confirmation:{level:"medium",reason:"This will modify the file by appending content.",showArgs:["path"]}}});var ba,xa,Ta,Pa,Ca,va=f(()=>{"use strict";l();ba="fs.delete_file",xa="Delete File",Ta="Remove/delete a file from the filesystem. Does not delete directories.",Pa="filesystem",Ca={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to delete"}},required:["path"]}});async function Ah(n){let e=n.path;if(h(`[fs.delete-file] execute path="${e}"`),!e)throw new Error("path is required");if(!it.existsSync(e))throw new Error(`File not found: ${e}`);if(it.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}. Use a different tool to remove directories.`);return it.unlinkSync(e),`File deleted successfully: ${e}`}var it,at,Mn=f(()=>{"use strict";l();it=x(require("fs"),1);va();_();at={name:ba,displayName:xa,description:Ta,parameters:Ca,category:Pa,execute:Ah,confirmation:{level:"high",reason:"This will permanently delete the file. This action cannot be undone.",showArgs:["path"]}}});var Sa,ka,$a,_a,Ra,Da=f(()=>{"use strict";l();Sa="fs.exists",ka="Exists",$a="Check if a file or directory exists at the given path. Returns true or false.",_a="filesystem",Ra={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to check"}},required:["path"]}});async function Mh(n){let e=n.path;if(!e)throw new Error("path is required");let t=Ea.existsSync(e);return JSON.stringify({exists:t,path:e})}var Ea,lt,On=f(()=>{"use strict";l();Ea=x(require("fs"),1);Da();lt={name:Sa,displayName:ka,description:$a,parameters:Ra,category:_a,execute:Mh}});var Na,Aa,Ma,Oa,Ia,ja=f(()=>{"use strict";l();Na="fs.stat",Aa="Stat",Ma="Get file or directory information including size, type, and modification date.",Oa="filesystem",Ia={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to get info for"}},required:["path"]}});async function Oh(n){let e=n.path;if(!e)throw new Error("path is required");if(!ir.existsSync(e))throw new Error(`Path not found: ${e}`);let t=ir.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 ir,ct,In=f(()=>{"use strict";l();ir=x(require("fs"),1);ja();ct={name:Na,displayName:Aa,description:Ma,parameters:Ia,category:Oa,execute:Oh}});var La,Fa,qa,Ua,Wa,Ga=f(()=>{"use strict";l();La="fs.list_dir",Fa="List Directory",qa="List files and directories at the given path. Optionally recurse into subdirectories.",Ua="filesystem",Wa={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to list"},recursive:{type:"boolean",description:"Whether to list recursively (default: false)",default:!1}},required:["path"]}});function Ka(n,e,t,o=""){let r=qe.readdirSync(n,{withFileTypes:!0});for(let s of r){let i=Ba.join(n,s.name),a=o?`${o}/${s.name}`:s.name;if(s.isDirectory())t.push({name:a,type:"directory",size:0}),e&&Ka(i,!0,t,a);else if(s.isFile()){let c=qe.statSync(i);t.push({name:a,type:"file",size:c.size})}}}async function Ih(n){let e=n.path,t=n.recursive===!0;if(!e)throw new Error("path is required");if(!qe.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!qe.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let r=[];return Ka(e,t,r),JSON.stringify(r,null,2)}var qe,Ba,pt,jn=f(()=>{"use strict";l();qe=x(require("fs"),1),Ba=x(require("path"),1);Ga();pt={name:La,displayName:Fa,description:qa,parameters:Wa,category:Ua,execute:Ih}});var Ja,Ha,za,Qa,Ya,Va=f(()=>{"use strict";l();Ja="fs.create_dir",Ha="Create Directory",za="Create a directory at the given path. Creates parent directories recursively if they do not exist.",Qa="filesystem",Ya={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to create"},recursive:{type:"boolean",description:"Create parent directories if they do not exist (default: true)",default:!0}},required:["path"]}});async function jh(n){let e=n.path,t=n.recursive!==!1;if(!e)throw new Error("path is required");if(mt.existsSync(e)){if(mt.statSync(e).isDirectory())return`Directory already exists: ${e}`;throw new Error(`Path exists but is not a directory: ${e}`)}return mt.mkdirSync(e,{recursive:t}),`Directory created: ${e}`}var mt,dt,Ln=f(()=>{"use strict";l();mt=x(require("fs"),1);Va();dt={name:Ja,displayName:Ha,description:za,parameters:Ya,category:Qa,execute:jh}});var Xa,Za,el,tl,ol,rl=f(()=>{"use strict";l();Xa="fs.move",Za="Move",el="Move or rename a file or directory from one path to another.",tl="filesystem",ol={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});async function Lh(n){let e=n.path,t=n.new_path;if(!e)throw new Error("path is required");if(!t)throw new Error("new_path is required");if(!Ue.existsSync(e))throw new Error(`Source not found: ${e}`);let o=nl.dirname(t);return Ue.existsSync(o)||Ue.mkdirSync(o,{recursive:!0}),Ue.renameSync(e,t),`Moved: ${e} \u2192 ${t}`}var Ue,nl,ut,Fn=f(()=>{"use strict";l();Ue=x(require("fs"),1),nl=x(require("path"),1);rl();ut={name:Xa,displayName:Za,description:el,parameters:ol,category:tl,execute:Lh,confirmation:{level:"high",reason:"This will move/rename the file or directory, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var sl,il,al,ll,cl,pl=f(()=>{"use strict";l();sl="fs.copy",il="Copy",al="Copy a file or directory from one path to another. Recursively copies directories.",ll="filesystem",cl={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});function ml(n,e){if(V.statSync(n).isDirectory()){V.existsSync(e)||V.mkdirSync(e,{recursive:!0});let o=V.readdirSync(n);for(let r of o)ml(fo.join(n,r),fo.join(e,r))}else V.copyFileSync(n,e)}async function Fh(n){let e=n.path,t=n.new_path;if(!e)throw new Error("path is required");if(!t)throw new Error("new_path is required");if(!V.existsSync(e))throw new Error(`Source not found: ${e}`);let o=fo.dirname(t);return V.existsSync(o)||V.mkdirSync(o,{recursive:!0}),ml(e,t),`Copied ${V.statSync(e).isDirectory()?"directory":"file"}: ${e} \u2192 ${t}`}var V,fo,ft,qn=f(()=>{"use strict";l();V=x(require("fs"),1),fo=x(require("path"),1);pl();ft={name:sl,displayName:il,description:al,parameters:cl,category:ll,execute:Fh,confirmation:{level:"medium",reason:"This will copy files or directories, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var dl,ul,fl,gl,hl,yl=f(()=>{"use strict";l();dl="fs.read_file_range",ul="Read File Range",fl="Read a specific range of lines from a file. Useful for reading portions of large files without loading the entire content.",gl="filesystem",hl={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},start_line:{type:"integer",description:"Start line number (1-indexed)"},end_line:{type:"integer",description:"End line number (1-indexed, inclusive)"}},required:["path","start_line","end_line"]}});async function qh(n){let e=n.path,t=n.start_line,o=n.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(!gt.existsSync(e))throw new Error(`File not found: ${e}`);if(gt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let i=gt.readFileSync(e,"utf-8").split(`
3
+ `),a=i.length,c=Math.min(t,a),p=Math.min(o,a),u=i.slice(c-1,p).map((g,w)=>`${c+w}: ${g}`).join(`
4
+ `);return`Lines ${c}-${p} of ${a} total:
5
+ ${u}`}var gt,ht,Un=f(()=>{"use strict";l();gt=x(require("fs"),1);yl();ht={name:dl,displayName:ul,description:fl,parameters:hl,category:gl,execute:qh}});var wl,bl,xl,Tl,Pl,Cl=f(()=>{"use strict";l();wl="fs.search",bl="Search",xl="Search for text in files within a directory. Returns matching lines with file paths and line numbers.",Tl="filesystem",Pl={type:"object",properties:{path:{type:"string",description:"Directory path to search in"},query:{type:"string",description:"Text or pattern to search for"},recursive:{type:"boolean",description:"Search recursively in subdirectories (default: true)",default:!0},max_results:{type:"integer",description:"Maximum number of matching lines to return (default: 50)",default:50},regex:{type:"boolean",description:"Treat query as a regular expression (default: false)",default:!1},case_sensitive:{type:"boolean",description:"Perform case-sensitive search. If false, search is case-insensitive (default: false)",default:!1}},required:["path","query"]}});function Uh(n,e,t,o){try{let s=Se.readFileSync(n,"utf-8").split(`
6
+ `);for(let i=0;i<s.length&&t.length<o;i++){let a=s[i];(typeof e=="string"?a.includes(e):e.test(a))&&t.push({file:n,line:i+1,content:a.trim()})}}catch{}}function Sl(n,e,t,o,r){let s=Se.readdirSync(n,{withFileTypes:!0});for(let i of s){if(o.length>=r)break;let a=vl.join(n,i.name);i.isDirectory()&&t?Sl(a,e,!0,o,r):i.isFile()&&Uh(a,e,o,r)}}async function Wh(n){let e=n.path,t=n.query,o=n.recursive!==!1,r=n.max_results||50,s=!!n.regex,i=!!n.case_sensitive;if(h(`[fs.search] execute path="${e}" query="${t}" recursive=${o} regex=${s} caseSensitive=${i}`),!e)throw new Error("path is required");if(!t)throw new Error("query is required");let a=t;if(s||!i){let u=t;s||(u=u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));let g=i?"":"i";a=new RegExp(u,g)}if(!Se.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Se.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let p=[];if(Sl(e,a,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 Se,vl,yt,Wn=f(()=>{"use strict";l();Se=x(require("fs"),1),vl=x(require("path"),1);Cl();_();yt={name:wl,displayName:bl,description:xl,parameters:Pl,category:Tl,execute:Wh}});var kl,$l,_l,Rl,Dl,El=f(()=>{"use strict";l();kl="fs.replace_in_file",$l="Replace In File",_l="Find and replace text in a file. Returns the number of replacements made.",Rl="filesystem",Dl={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path"},search:{type:"string",description:"Text to search for"},replace:{type:"string",description:"Text to replace with"}},required:["path","search","replace"]}});async function Gh(n){let e=n.path,t=n.search,o=n.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(!ke.existsSync(e))throw new Error(`File not found: ${e}`);if(ke.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let s=ke.readFileSync(e,"utf-8"),i=0,a=0;for(;(a=s.indexOf(t,a))!==-1;)i++,a+=t.length;if(i===0)return`No occurrences of "${t}" found in ${e}`;let c=s.split(t).join(o);return ke.writeFileSync(e,c,"utf-8"),`Replaced ${i} occurrence(s) in ${e}`}var ke,wt,Gn=f(()=>{"use strict";l();ke=x(require("fs"),1);El();wt={name:kl,displayName:$l,description:_l,parameters:Dl,category:Rl,execute:Gh,confirmation:{level:"high",reason:"This will perform a global find-and-replace operation that may corrupt the file if the pattern is incorrect.",showArgs:["path","search","replace"]}}});var Nl,Al,Ml,Ol,Il,jl=f(()=>{"use strict";l();Nl="fs.tree",Al="Tree",Ml="Get a tree representation of a directory structure. Useful for understanding project layout at a glance.",Ol="filesystem",Il={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path"},depth:{type:"integer",description:"Maximum depth to traverse (default: 3)",default:3}},required:["path"]}});function Ll(n,e,t,o,r){if(t>o)return;let i=bt.readdirSync(n,{withFileTypes:!0}).sort((a,c)=>a.isDirectory()&&!c.isDirectory()?-1:!a.isDirectory()&&c.isDirectory()?1:a.name.localeCompare(c.name));for(let a=0;a<i.length;a++){let c=i[a],p=a===i.length-1,m=p?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",u=p?" ":"\u2502 ";c.isDirectory()?(r.push(`${e}${m}${c.name}/`),Ll(ar.join(n,c.name),e+u,t+1,o,r)):r.push(`${e}${m}${c.name}`)}}async function Bh(n){let e=n.path,t=n.depth||3;if(!e)throw new Error("path is required");if(!bt.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!bt.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let s=[`${ar.basename(e)}/`];return Ll(e,"",1,t,s),s.join(`
8
+ `)}var bt,ar,xt,Bn=f(()=>{"use strict";l();bt=x(require("fs"),1),ar=x(require("path"),1);jl();xt={name:Nl,displayName:Al,description:Ml,parameters:Il,category:Ol,execute:Bh}});var Fl,ql,Ul,Wl,Gl,Bl=f(()=>{"use strict";l();Fl="fs.glob",ql="Glob Pattern Match",Ul='Find files matching glob patterns (e.g., "**/*.ts", "src/**/*.test.js")',Wl="filesystem",Gl={type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files (e.g., "**/*.ts", "src/**/*.json")'},cwd:{type:"string",description:"Root directory to search from (defaults to current working directory)"},ignore:{type:"array",items:{type:"string"},description:'Patterns to ignore (e.g., ["node_modules/**", "dist/**"])'},onlyFiles:{type:"boolean",description:"Return only files, not directories (default: true)"},onlyDirectories:{type:"boolean",description:"Return only directories, not files (default: false)"},absolute:{type:"boolean",description:"Return absolute paths instead of relative (default: false)"}},required:["pattern"]}});async function Kh(n){let e=n.pattern,t=n.cwd,o=n.ignore,r=n.onlyFiles!==!1,s=n.onlyDirectories===!0,i=n.absolute===!0;if(!e)throw new Error("pattern is required");let a=e.replace(/\\/g,"/");try{let c=await(0,Kl.default)(a,{cwd:t||process.cwd(),ignore:o||["node_modules/**",".git/**"],onlyFiles:r,onlyDirectories:s,absolute:i,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 Kl,lr,Kn=f(()=>{"use strict";l();Kl=x(require("fast-glob"),1);Bl();lr={name:Fl,displayName:ql,description:Ul,parameters:Gl,category:Wl,execute:Kh}});var Jl,Hl,zl,Ql,Yl,Vl=f(()=>{"use strict";l();Jl="fs.delete_dir",Hl="Delete Directory",zl="Delete a directory and all its contents recursively",Ql="filesystem",Yl={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to the directory to delete"},force:{type:"boolean",description:"Force deletion even if directory is not empty (default: true)"}},required:["path"]}});async function Jh(n){let e=n.path,t=n.force!==!1;if(!e)throw new Error("path is required");if(!(0,cr.existsSync)(e))throw new Error(`Directory does not exist: ${e}`);if(!(0,cr.statSync)(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);try{return await(0,Xl.rm)(e,{recursive:!0,force:t}),`Directory deleted successfully: ${e}`}catch(r){throw new Error(`Failed to delete directory "${e}": ${r.message}`)}}var Xl,cr,pr,Jn=f(()=>{"use strict";l();Xl=require("fs/promises"),cr=require("fs");Vl();pr={name:Jl,displayName:Hl,description:zl,parameters:Yl,category:Ql,execute:Jh,confirmation:{level:"high",reason:"This will recursively delete the directory and all its contents. This action cannot be undone.",showArgs:["path"]}}});var Zl,ec,tc,oc,rc,nc=f(()=>{"use strict";l();Zl="fs.batch_read",ec="Batch Read Files",tc="Read multiple files efficiently in one operation. Returns content for each file or error if read fails.",oc="filesystem",rc={type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Array of file paths to read"},encoding:{type:"string",description:"File encoding (default: utf-8)"},continueOnError:{type:"boolean",description:"Continue reading other files if one fails (default: true)"}},required:["paths"]}});async function Hh(n){let e=n.paths,t=n.encoding||"utf-8",o=n.continueOnError!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("paths array is required and must not be empty");let r=[],s=0,i=0;for(let a of e)try{let c=await(0,sc.readFile)(a,t);r.push({path:a,content:c,success:!0}),s++}catch(c){let p=c.message;if(r.push({path:a,error:p,success:!1}),i++,!o)throw new Error(`Failed to read file "${a}": ${p}`)}return JSON.stringify({total:e.length,success:s,failed:i,results:r},null,2)}var sc,mr,Hn=f(()=>{"use strict";l();sc=require("fs/promises");nc();mr={name:Zl,displayName:ec,description:tc,parameters:rc,category:oc,execute:Hh}});var ic,ac,lc,cc,pc,mc=f(()=>{"use strict";l();ic="fs.batch_write",ac="Batch Write Files",lc="Write multiple files atomically in one operation. If atomic mode is enabled, all writes succeed or all are rolled back on failure.",cc="filesystem",pc={type:"object",properties:{files:{type:"array",items:{type:"object",properties:{path:{type:"string"},content:{type:"string"}}},description:"Array of files to write, each with path and content"},encoding:{type:"string",description:"File encoding (default: utf-8)"},atomic:{type:"boolean",description:"Atomic mode: rollback all writes if any fails (default: true)"},createDirs:{type:"boolean",description:"Create parent directories if they don't exist (default: true)"}},required:["files"]}});async function zh(n){let e=n.files,t=n.encoding||"utf-8",o=n.atomic!==!1,r=n.createDirs!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("files array is required and must not be empty");for(let a of e)if(!a.path||a.content===void 0)throw new Error("Each file must have path and content properties");let s=[],i=[];try{for(let a of e){let c=(0,dr.resolve)(a.path);if(o){let p=(0,zn.existsSync)(c),m={path:c,existed:p};p&&(m.originalContent=await(0,he.readFile)(c,t)),s.push(m)}if(r){let p=(0,dr.dirname)(c);await(0,he.mkdir)(p,{recursive:!0})}await(0,he.writeFile)(c,a.content,t),i.push(c)}return JSON.stringify({success:!0,written:i.length,files:i},null,2)}catch(a){if(o&&s.length>0){for(let c of s)try{c.existed&&c.originalContent!==void 0?await(0,he.writeFile)(c.path,c.originalContent,t):!c.existed&&(0,zn.existsSync)(c.path)&&await(0,he.unlink)(c.path)}catch{}throw new Error(`Batch write failed and rolled back: ${a.message}`)}throw new Error(`Batch write failed: ${a.message}`)}}var he,dr,zn,ur,Qn=f(()=>{"use strict";l();he=require("fs/promises"),dr=require("path"),zn=require("fs");mc();ur={name:ic,displayName:ac,description:lc,parameters:pc,category:cc,execute:zh,confirmation:{level:"high",reason:"This will overwrite multiple files at once.",showArgs:["files"]}}});var dc={};Z(dc,{fsAppendFileTool:()=>st,fsBatchReadTool:()=>mr,fsBatchWriteTool:()=>ur,fsCopyTool:()=>ft,fsCreateDirTool:()=>dt,fsDeleteDirTool:()=>pr,fsDeleteFileTool:()=>at,fsExistsTool:()=>lt,fsGlobTool:()=>lr,fsListDirTool:()=>pt,fsMoveTool:()=>ut,fsReadFileRangeTool:()=>ht,fsReadFileTool:()=>tt,fsReplaceInFileTool:()=>wt,fsSearchTool:()=>yt,fsStatTool:()=>ct,fsToolsProject:()=>Yn,fsTreeTool:()=>xt,fsWriteFileTool:()=>rt});var Yn,Vn=f(()=>{"use strict";l();En();Nn();An();Mn();On();In();jn();Ln();Fn();qn();Un();Wn();Gn();Bn();Kn();Jn();Hn();Qn();En();Nn();An();Mn();On();In();jn();Ln();Fn();qn();Un();Wn();Gn();Bn();Kn();Jn();Hn();Qn();Yn={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:[tt,rt,st,at,lt,ct,pt,dt,ut,ft,ht,yt,wt,xt,lr,pr,mr,ur],dependencies:{"fast-glob":"^3.3.2"}}});var uc,fc,gc,hc,yc,wc=f(()=>{"use strict";l();uc="exec.run",fc="Run",gc="Execute a command directly (without shell) and return its output. Use exec.run_shell for pipes, redirects, or shell features.",hc="execution",yc={type:"object",properties:{command:{type:"string",description:"The command to execute"},cwd:{type:"string",description:"Working directory for the command (optional)"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["command"]}});async function Qh(n){let e=n.command,t=n.cwd,o=n.timeout||3e4;if(!e)throw new Error("command is required");h(`[exec.run] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${o}ms`);try{return(0,bc.execSync)(e,{cwd:t,timeout:o,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"]})||"(command completed with no output)"}catch(r){let s=r.stdout||"",i=r.stderr||"";return`Command failed (exit code ${r.status??"unknown"}):
9
9
  STDOUT:
10
- ${n}
10
+ ${s}
11
11
  STDERR:
12
- ${a}`}}var Zl,ht,Mn=f(()=>{"use strict";l();Zl=require("child_process");Xl();k();ht={name:zl,displayName:Kl,description:Ql,parameters:Vl,category:Yl,execute:kh}});var ec,tc,oc,rc,nc,sc=f(()=>{"use strict";l();ec="exec.run_shell",tc="Run Shell",oc="Execute a command through the system shell. Supports pipes, redirects, environment variable expansion, and other shell features.",rc="execution",nc={type:"object",properties:{command:{type:"string",description:"The shell command to execute (supports pipes, redirects, etc.)"},cwd:{type:"string",description:"Working directory for the command (optional)"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["command"]}});function Rh(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function Eh(s){let e=s.command,t=s.cwd,r=s.timeout||3e4;if(!e)throw new Error("command is required");h(`[exec.run-shell] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${r}ms`);try{return(0,ic.execSync)(e,{cwd:t,timeout:r,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],shell:Rh()})||"(command completed with no output)"}catch(o){let n=o.stdout||"",a=o.stderr||"";return`Command failed (exit code ${o.status??"unknown"}):
12
+ ${i}`}}var bc,Tt,Xn=f(()=>{"use strict";l();bc=require("child_process");wc();_();Tt={name:uc,displayName:fc,description:gc,parameters:yc,category:hc,execute:Qh,confirmation:{level:"high",reason:"This will execute a shell command on the host system.",showArgs:["command"]}}});var xc,Tc,Pc,Cc,vc,Sc=f(()=>{"use strict";l();xc="exec.run_shell",Tc="Run Shell",Pc="Execute a command through the system shell. Supports pipes, redirects, environment variable expansion, and other shell features.",Cc="execution",vc={type:"object",properties:{command:{type:"string",description:"The shell command to execute (supports pipes, redirects, etc.)"},cwd:{type:"string",description:"Working directory for the command (optional)"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["command"]}});function Yh(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function Vh(n){let e=n.command,t=n.cwd,o=n.timeout||3e4;if(!e)throw new Error("command is required");h(`[exec.run-shell] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${o}ms`);try{return(0,kc.execSync)(e,{cwd:t,timeout:o,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],shell:Yh()})||"(command completed with no output)"}catch(r){let s=r.stdout||"",i=r.stderr||"";return`Command failed (exit code ${r.status??"unknown"}):
13
13
  STDOUT:
14
- ${n}
14
+ ${s}
15
15
  STDERR:
16
- ${a}`}}var ic,yt,On=f(()=>{"use strict";l();ic=require("child_process");sc();k();yt={name:ec,displayName:tc,description:oc,parameters:nc,category:rc,execute:Eh}});function ac(s,e,t){let r=`proc_${Dh++}`,o={id:r,command:s,cwd:e,process:t,startedAt:new Date().toISOString(),stdout:"",stderr:""};return t.stdout?.on("data",n=>{o.stdout+=n.toString(),o.stdout.length>1e6&&(o.stdout=o.stdout.slice(-5e5))}),t.stderr?.on("data",n=>{o.stderr+=n.toString(),o.stderr.length>1e6&&(o.stderr=o.stderr.slice(-5e5))}),t.on("exit",()=>{}),ar.set(r,o),r}function lr(s){return ar.get(s)}function lc(s){let e=ar.get(s);if(!e)return!1;let t=e.process.exitCode===null;return t&&e.process.kill("SIGTERM"),t}function cc(){return Array.from(ar.values()).map(s=>({id:s.id,command:s.command,cwd:s.cwd,startedAt:s.startedAt,alive:s.process.exitCode===null,pid:s.process.pid}))}var ar,Dh,co=f(()=>{"use strict";l();ar=new Map,Dh=1});var pc,mc,dc,uc,fc,gc=f(()=>{"use strict";l();pc="exec.run_background",mc="Run Background",dc="Start a command as a background process. Returns a process ID that can be used with exec.read_output, exec.kill, and exec.list_processes.",uc="execution",fc={type:"object",properties:{command:{type:"string",description:"The command to run in the background"},cwd:{type:"string",description:"Working directory for the command (optional)"}},required:["command"]}});async function Nh(s){let e=s.command,t=s.cwd;if(!e)throw new Error("command is required");if(h(`[exec.run-background] execute command="${e.substring(0,100)}" cwd=${t??"default"}`),!e)throw new Error("command is required");let r=(0,hc.spawn)(e,[],{cwd:t,shell:!0,stdio:["ignore","pipe","pipe"],detached:!1}),o=ac(e,t,r);return JSON.stringify({id:o,pid:r.pid,command:e,message:`Background process started. Use exec.read_output("${o}") to read output, exec.kill("${o}") to stop.`})}var hc,wt,In=f(()=>{"use strict";l();hc=require("child_process");co();gc();k();wt={name:pc,displayName:mc,description:dc,parameters:fc,category:uc,execute:Nh}});var yc,wc,bc,xc,Tc,Pc=f(()=>{"use strict";l();yc="exec.read_output",wc="Read Output",bc="Read stdout and stderr from a background process started with exec.run_background.",xc="execution",Tc={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function Ah(s){let e=s.process_id;if(!e)throw new Error("process_id is required");let t=lr(e);if(!t)throw new Error(`Process not found: ${e}`);let r=t.process.exitCode===null;return JSON.stringify({id:t.id,alive:r,exitCode:t.process.exitCode,stdout:t.stdout,stderr:t.stderr})}var bt,jn=f(()=>{"use strict";l();co();Pc();bt={name:yc,displayName:wc,description:bc,parameters:Tc,category:xc,execute:Ah}});var Cc,vc,Sc,$c,_c,kc=f(()=>{"use strict";l();Cc="exec.kill",vc="Kill",Sc="Kill a background process started with exec.run_background.",$c="execution",_c={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function Mh(s){let e=s.process_id;if(!e)throw new Error("process_id is required");let t=lr(e);if(!t)throw new Error(`Process not found: ${e}`);return lc(e)?`Process ${e} (${t.command}) killed successfully.`:`Process ${e} (${t.command}) was already terminated (exit code: ${t.process.exitCode}).`}var xt,Fn=f(()=>{"use strict";l();co();kc();xt={name:Cc,displayName:vc,description:Sc,parameters:_c,category:$c,execute:Mh}});var Rc,Ec,Dc,Nc,Ac,Mc=f(()=>{"use strict";l();Rc="exec.list_processes",Ec="List Processes",Dc="List all managed background processes started with exec.run_background, including their status.",Nc="execution",Ac={type:"object",properties:{}}});async function Oh(s){let e=cc();return e.length===0?"No managed background processes.":JSON.stringify(e,null,2)}var Tt,Ln=f(()=>{"use strict";l();co();Mc();Tt={name:Rc,displayName:Ec,description:Dc,parameters:Ac,category:Nc,execute:Oh}});var Oc={};V(Oc,{execKillTool:()=>xt,execListProcessesTool:()=>Tt,execReadOutputTool:()=>bt,execRunBackgroundTool:()=>wt,execRunShellTool:()=>yt,execRunTool:()=>ht,execToolsProject:()=>qn});var qn,Un=f(()=>{"use strict";l();Mn();On();In();jn();Fn();Ln();Mn();On();In();jn();Fn();Ln();qn={manifest:{key:"exec",name:"exec-tools",displayName:"Execution",version:"1.0.0",description:"Code execution tools for running commands, managing background processes, and automation.",author:"Sajeer",tools:["exec.run","exec.run_shell","exec.run_background","exec.read_output","exec.kill","exec.list_processes"],category:"execution"},tools:[ht,yt,wt,bt,xt,Tt],dependencies:{}}});var Ic,jc,Fc,Lc,qc,Uc=f(()=>{"use strict";l();Ic="system.info",jc="Info",Fc="Get system information including OS, CPU, memory, and architecture.",Lc="system",qc={type:"object",properties:{}}});async function Ih(s){return h("[system.info] execute"),JSON.stringify({platform:A.platform(),arch:A.arch(),release:A.release(),hostname:A.hostname(),uptime:A.uptime(),cpus:{model:A.cpus()[0]?.model||"unknown",count:A.cpus().length},memory:{total:A.totalmem(),free:A.freemem(),used:A.totalmem()-A.freemem()},homedir:A.homedir(),tmpdir:A.tmpdir(),nodeVersion:process.version},null,2)}var A,Pt,Wn=f(()=>{"use strict";l();A=T(require("os"),1);Uc();k();Pt={name:Ic,displayName:jc,description:Fc,parameters:qc,category:Lc,execute:Ih}});var Wc,Gc,Bc,Jc,Hc,zc=f(()=>{"use strict";l();Wc="system.env",Gc="Environment",Bc="Get environment variable(s). If key is provided, returns that specific variable. Otherwise returns all environment variables.",Jc="system",Hc={type:"object",properties:{key:{type:"string",description:"Specific environment variable name to get (optional, returns all if omitted)"}}}});async function jh(s){let e=s.key;if(h(`[system.env] execute key=${e??"all"}`),e){let o=process.env[e];return o===void 0?`Environment variable "${e}" is not set.`:JSON.stringify({[e]:o})}let t={},r=Object.keys(process.env).sort();for(let o of r)process.env[o]!==void 0&&(t[o]=process.env[o]);return JSON.stringify(t,null,2)}var Ct,Gn=f(()=>{"use strict";l();zc();k();Ct={name:Wc,displayName:Gc,description:Bc,parameters:Hc,category:Jc,execute:jh}});var Kc,Qc,Yc,Vc,Xc,Zc=f(()=>{"use strict";l();Kc="system.set_env",Qc="Set Environment",Yc="Set an environment variable for the current session. Does not persist across restarts.",Vc="system",Xc={type:"object",properties:{key:{type:"string",description:"Environment variable name"},value:{type:"string",description:"Value to set"}},required:["key","value"]}});async function Fh(s){let e=s.key,t=s.value;if(!e)throw new Error("key is required");if(t==null)throw new Error("value is required");let r=process.env[e];return process.env[e]=t,r!==void 0?`Environment variable "${e}" updated (was: "${r}", now: "${t}")`:`Environment variable "${e}" set to "${t}"`}var vt,Bn=f(()=>{"use strict";l();Zc();vt={name:Kc,displayName:Qc,description:Yc,parameters:Xc,category:Vc,execute:Fh}});var ep,tp,op,rp,np,sp=f(()=>{"use strict";l();ep="system.cwd",tp="Current Directory",op="Get the current working directory of the process.",rp="system",np={type:"object",properties:{}}});async function Lh(s){return h("[system.cwd] execute"),JSON.stringify({cwd:process.cwd()})}var St,Jn=f(()=>{"use strict";l();sp();k();St={name:ep,displayName:tp,description:op,parameters:np,category:rp,execute:Lh}});var ip,ap,lp,cp,pp,mp=f(()=>{"use strict";l();ip="system.disk_usage",ap="Disk Usage",lp="Get disk usage information for a given path or the root filesystem.",cp="system",pp={type:"object",properties:{path:{type:"string",description:"Path to check disk usage for (default: /)",default:"/"}}}});function Hn(s){let e=["B","KB","MB","GB","TB","PB"],t=s,r=0;for(;t>=1024&&r<e.length-1;)t/=1024,r++;return`${t.toFixed(1)}${e[r]}`}async function qh(s){let t=s.path||(process.platform==="win32"?up.tmpdir():"/");t=cr.resolve(t);let r=process.platform==="win32";try{let o=dp.statfsSync(t),n=BigInt(o.blocks)*BigInt(o.bsize),a=BigInt(o.bavail)*BigInt(o.bsize),i=BigInt(o.bfree)*BigInt(o.bsize),c=n-i,p=n>0?Number(c*BigInt(100)/n):0;return JSON.stringify({path:t,filesystem:"statfs",size:Hn(Number(n)),used:Hn(Number(c)),available:Hn(Number(a)),usePercent:`${p}%`,mountedOn:t},null,2)}catch(o){try{if(r){let c=cr.parse(t).root.replace(/\\$/,"")||"C:",p=`Get-PSDrive -Name ${c.replace(":","")} | Select-Object @{n='Drive';e={$_.Name+':'}},@{n='Used';e={$_.Used}},@{n='Free';e={$_.Free}},@{n='Total';e={$_.Used+$_.Free}} | ConvertTo-Json`,m=(0,zn.execSync)(p,{encoding:"utf-8",timeout:5e3,shell:"powershell.exe"}),u=JSON.parse(m.trim()),g=u.Total||0,w=u.Free||0,y=u.Used||0,b=g>0?Math.round(y/g*100):0;return JSON.stringify({path:t,filesystem:u.Name||"NTFS",size:`${(g/1024**3).toFixed(1)}G`,used:`${(y/1024**3).toFixed(1)}G`,available:`${(w/1024**3).toFixed(1)}G`,usePercent:`${b}%`,mountedOn:u.Drive||`${c}`},null,2)}let n=(0,zn.execSync)(`df -h "${t}"`,{encoding:"utf-8",timeout:5e3}),a=n.trim().split(`
17
- `);if(a.length<2)return n;let i=a[1].split(/\s+/);return JSON.stringify({path:t,filesystem:i[0]||"unknown",size:i[1]||"unknown",used:i[2]||"unknown",available:i[3]||"unknown",usePercent:i[4]||"unknown",mountedOn:i[5]||"unknown"},null,2)}catch(n){throw new Error(`Failed to get disk usage for ${t}: ${o?.message||o}; fallback error: ${n.message}`)}}}var dp,up,cr,zn,$t,Kn=f(()=>{"use strict";l();dp=T(require("fs"),1),up=T(require("os"),1),cr=T(require("path"),1),zn=require("child_process");mp();$t={name:ip,displayName:ap,description:lp,parameters:pp,category:cp,execute:qh}});var fp={};V(fp,{systemCwdTool:()=>St,systemDiskUsageTool:()=>$t,systemEnvTool:()=>Ct,systemInfoTool:()=>Pt,systemSetEnvTool:()=>vt,systemToolsProject:()=>Qn});var Qn,Yn=f(()=>{"use strict";l();Wn();Gn();Bn();Jn();Kn();Wn();Gn();Bn();Jn();Kn();Qn={manifest:{key:"system",name:"system-tools",displayName:"System",version:"1.0.0",description:"System tools for querying OS info, environment variables, working directory, and disk usage.",author:"Sajeer",tools:["system.info","system.env","system.set_env","system.cwd","system.disk_usage"],category:"system"},tools:[Pt,Ct,vt,St,$t],dependencies:{}}});var gp,hp,yp,wp,bp,xp=f(()=>{"use strict";l();gp="http.get",hp="GET",yp="Make an HTTP GET request to a URL and return the response body.",wp="network",bp={type:"object",properties:{url:{type:"string",description:"The URL to request"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url"]}});async function Uh(s){let e=s.url,t=s.headers;if(h(`[http.get] execute url="${e}"`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let r=await fetch(e,{method:"GET",headers:t||{}}),o=await r.text(),n=`HTTP ${r.status} ${r.statusText}`;return r.ok?o.length>Tp?`${n}
18
- ${o.substring(0,Tp)}
16
+ ${i}`}}var kc,Pt,Zn=f(()=>{"use strict";l();kc=require("child_process");Sc();_();Pt={name:xc,displayName:Tc,description:Pc,parameters:vc,category:Cc,execute:Vh,confirmation:{level:"high",reason:"This will execute a shell command with explicit shell context.",showArgs:["command"]}}});function $c(n,e,t){let o=`proc_${Xh++}`,r={id:o,command:n,cwd:e,process:t,startedAt:new Date().toISOString(),stdout:"",stderr:""};return t.stdout?.on("data",s=>{r.stdout+=s.toString(),r.stdout.length>1e6&&(r.stdout=r.stdout.slice(-5e5))}),t.stderr?.on("data",s=>{r.stderr+=s.toString(),r.stderr.length>1e6&&(r.stderr=r.stderr.slice(-5e5))}),t.on("exit",()=>{}),fr.set(o,r),o}function gr(n){return fr.get(n)}function _c(n){let e=fr.get(n);if(!e)return!1;let t=e.process.exitCode===null;return t&&e.process.kill("SIGTERM"),t}function Rc(){return Array.from(fr.values()).map(n=>({id:n.id,command:n.command,cwd:n.cwd,startedAt:n.startedAt,alive:n.process.exitCode===null,pid:n.process.pid}))}var fr,Xh,go=f(()=>{"use strict";l();fr=new Map,Xh=1});var Dc,Ec,Nc,Ac,Mc,Oc=f(()=>{"use strict";l();Dc="exec.run_background",Ec="Run Background",Nc="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.",Ac="execution",Mc={type:"object",properties:{command:{type:"string",description:"The command to run in the background"},cwd:{type:"string",description:"Working directory for the command (optional)"}},required:["command"]}});async function Zh(n){let e=n.command,t=n.cwd;if(!e)throw new Error("command is required");if(h(`[exec.run-background] execute command="${e.substring(0,100)}" cwd=${t??"default"}`),!e)throw new Error("command is required");let o=(0,Ic.spawn)(e,[],{cwd:t,shell:!0,stdio:["ignore","pipe","pipe"],detached:!1}),r=$c(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 Ic,Ct,es=f(()=>{"use strict";l();Ic=require("child_process");go();Oc();_();Ct={name:Dc,displayName:Ec,description:Nc,parameters:Mc,category:Ac,execute:Zh,confirmation:{level:"high",reason:"This will spawn a background process that runs unsupervised.",showArgs:["command"]}}});var jc,Lc,Fc,qc,Uc,Wc=f(()=>{"use strict";l();jc="exec.read_output",Lc="Read Output",Fc="Read stdout and stderr from a background process started with exec.run_background.",qc="execution",Uc={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function ey(n){let e=n.process_id;if(!e)throw new Error("process_id is required");let t=gr(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 vt,ts=f(()=>{"use strict";l();go();Wc();vt={name:jc,displayName:Lc,description:Fc,parameters:Uc,category:qc,execute:ey}});var Gc,Bc,Kc,Jc,Hc,zc=f(()=>{"use strict";l();Gc="exec.kill",Bc="Kill",Kc="Kill a background process started with exec.run_background.",Jc="execution",Hc={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function ty(n){let e=n.process_id;if(!e)throw new Error("process_id is required");let t=gr(e);if(!t)throw new Error(`Process not found: ${e}`);return _c(e)?`Process ${e} (${t.command}) killed successfully.`:`Process ${e} (${t.command}) was already terminated (exit code: ${t.process.exitCode}).`}var St,os=f(()=>{"use strict";l();go();zc();St={name:Gc,displayName:Bc,description:Kc,parameters:Hc,category:Jc,execute:ty,confirmation:{level:"medium",reason:"This will terminate a running process.",showArgs:["process_id"]}}});var Qc,Yc,Vc,Xc,Zc,ep=f(()=>{"use strict";l();Qc="exec.list_processes",Yc="List Processes",Vc="List all managed background processes started with exec.run_background, including their status.",Xc="execution",Zc={type:"object",properties:{}}});async function oy(n){let e=Rc();return e.length===0?"No managed background processes.":JSON.stringify(e,null,2)}var kt,rs=f(()=>{"use strict";l();go();ep();kt={name:Qc,displayName:Yc,description:Vc,parameters:Zc,category:Xc,execute:oy}});var tp={};Z(tp,{execKillTool:()=>St,execListProcessesTool:()=>kt,execReadOutputTool:()=>vt,execRunBackgroundTool:()=>Ct,execRunShellTool:()=>Pt,execRunTool:()=>Tt,execToolsProject:()=>ns});var ns,ss=f(()=>{"use strict";l();Xn();Zn();es();ts();os();rs();Xn();Zn();es();ts();os();rs();ns={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:[Tt,Pt,Ct,vt,St,kt],dependencies:{}}});var op,rp,np,sp,ip,ap=f(()=>{"use strict";l();op="system.info",rp="Info",np="Get system information including OS, CPU, memory, and architecture.",sp="system",ip={type:"object",properties:{}}});async function ry(n){return h("[system.info] execute"),JSON.stringify({platform:O.platform(),arch:O.arch(),release:O.release(),hostname:O.hostname(),uptime:O.uptime(),cpus:{model:O.cpus()[0]?.model||"unknown",count:O.cpus().length},memory:{total:O.totalmem(),free:O.freemem(),used:O.totalmem()-O.freemem()},homedir:O.homedir(),tmpdir:O.tmpdir(),nodeVersion:process.version},null,2)}var O,$t,is=f(()=>{"use strict";l();O=x(require("os"),1);ap();_();$t={name:op,displayName:rp,description:np,parameters:ip,category:sp,execute:ry}});var lp,cp,pp,mp,dp,up=f(()=>{"use strict";l();lp="system.env",cp="Environment",pp="Get environment variable(s). If key is provided, returns that specific variable. Otherwise returns all environment variables.",mp="system",dp={type:"object",properties:{key:{type:"string",description:"Specific environment variable name to get (optional, returns all if omitted)"}}}});async function ny(n){let e=n.key;if(h(`[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 _t,as=f(()=>{"use strict";l();up();_();_t={name:lp,displayName:cp,description:pp,parameters:dp,category:mp,execute:ny}});var fp,gp,hp,yp,wp,bp=f(()=>{"use strict";l();fp="system.set_env",gp="Set Environment",hp="Set an environment variable for the current session. Does not persist across restarts.",yp="system",wp={type:"object",properties:{key:{type:"string",description:"Environment variable name"},value:{type:"string",description:"Value to set"}},required:["key","value"]}});async function sy(n){let e=n.key,t=n.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 Rt,ls=f(()=>{"use strict";l();bp();Rt={name:fp,displayName:gp,description:hp,parameters:wp,category:yp,execute:sy,confirmation:{level:"medium",reason:"This will modify the process environment, affecting all subsequent operations.",showArgs:["key","value"]}}});var xp,Tp,Pp,Cp,vp,Sp=f(()=>{"use strict";l();xp="system.cwd",Tp="Current Directory",Pp="Get the current working directory of the process.",Cp="system",vp={type:"object",properties:{}}});async function iy(n){return h("[system.cwd] execute"),JSON.stringify({cwd:process.cwd()})}var Dt,cs=f(()=>{"use strict";l();Sp();_();Dt={name:xp,displayName:Tp,description:Pp,parameters:vp,category:Cp,execute:iy}});var kp,$p,_p,Rp,Dp,Ep=f(()=>{"use strict";l();kp="system.disk_usage",$p="Disk Usage",_p="Get disk usage information for a given path or the root filesystem.",Rp="system",Dp={type:"object",properties:{path:{type:"string",description:"Path to check disk usage for (default: /)",default:"/"}}}});function ps(n){let e=["B","KB","MB","GB","TB","PB"],t=n,o=0;for(;t>=1024&&o<e.length-1;)t/=1024,o++;return`${t.toFixed(1)}${e[o]}`}async function ay(n){let t=n.path||(process.platform==="win32"?Ap.tmpdir():"/");t=hr.resolve(t);let o=process.platform==="win32";try{let r=Np.statfsSync(t),s=BigInt(r.blocks)*BigInt(r.bsize),i=BigInt(r.bavail)*BigInt(r.bsize),a=BigInt(r.bfree)*BigInt(r.bsize),c=s-a,p=s>0?Number(c*BigInt(100)/s):0;return JSON.stringify({path:t,filesystem:"statfs",size:ps(Number(s)),used:ps(Number(c)),available:ps(Number(i)),usePercent:`${p}%`,mountedOn:t},null,2)}catch(r){try{if(o){let c=hr.parse(t).root.replace(/\\$/,"")||"C:",p=`Get-PSDrive -Name ${c.replace(":","")} | Select-Object @{n='Drive';e={$_.Name+':'}},@{n='Used';e={$_.Used}},@{n='Free';e={$_.Free}},@{n='Total';e={$_.Used+$_.Free}} | ConvertTo-Json`,m=(0,ms.execSync)(p,{encoding:"utf-8",timeout:5e3,shell:"powershell.exe"}),u=JSON.parse(m.trim()),g=u.Total||0,w=u.Free||0,y=u.Used||0,b=g>0?Math.round(y/g*100):0;return JSON.stringify({path:t,filesystem:u.Name||"NTFS",size:`${(g/1024**3).toFixed(1)}G`,used:`${(y/1024**3).toFixed(1)}G`,available:`${(w/1024**3).toFixed(1)}G`,usePercent:`${b}%`,mountedOn:u.Drive||`${c}`},null,2)}let s=(0,ms.execSync)(`df -h "${t}"`,{encoding:"utf-8",timeout:5e3}),i=s.trim().split(`
17
+ `);if(i.length<2)return s;let a=i[1].split(/\s+/);return JSON.stringify({path:t,filesystem:a[0]||"unknown",size:a[1]||"unknown",used:a[2]||"unknown",available:a[3]||"unknown",usePercent:a[4]||"unknown",mountedOn:a[5]||"unknown"},null,2)}catch(s){throw new Error(`Failed to get disk usage for ${t}: ${r?.message||r}; fallback error: ${s.message}`)}}}var Np,Ap,hr,ms,Et,ds=f(()=>{"use strict";l();Np=x(require("fs"),1),Ap=x(require("os"),1),hr=x(require("path"),1),ms=require("child_process");Ep();Et={name:kp,displayName:$p,description:_p,parameters:Dp,category:Rp,execute:ay}});var Mp={};Z(Mp,{systemCwdTool:()=>Dt,systemDiskUsageTool:()=>Et,systemEnvTool:()=>_t,systemInfoTool:()=>$t,systemSetEnvTool:()=>Rt,systemToolsProject:()=>us});var us,fs=f(()=>{"use strict";l();is();as();ls();cs();ds();is();as();ls();cs();ds();us={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:[$t,_t,Rt,Dt,Et],dependencies:{}}});var Op,Ip,jp,Lp,Fp,qp=f(()=>{"use strict";l();Op="http.get",Ip="GET",jp="Make an HTTP GET request to a URL and return the response body.",Lp="network",Fp={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 ly(n){let e=n.url,t=n.headers;if(h(`[http.get] execute url="${e}"`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=await fetch(e,{method:"GET",headers:t||{}}),r=await o.text(),s=`HTTP ${o.status} ${o.statusText}`;return o.ok?r.length>Up?`${s}
18
+ ${r.substring(0,Up)}
19
19
 
20
- ... (truncated, total ${o.length} characters)`:`${n}
21
- ${o}`:`${n}
22
- ${o}`}var Tp,_t,Vn=f(()=>{"use strict";l();xp();k();Tp=1e5;_t={name:gp,displayName:hp,description:yp,parameters:bp,category:wp,execute:Uh}});var Pp,Cp,vp,Sp,$p,_p=f(()=>{"use strict";l();Pp="http.post",Cp="POST",vp="Make an HTTP POST request to a URL with an optional body and return the response.",Sp="network",$p={type:"object",properties:{url:{type:"string",description:"The URL to request"},body:{type:"string",description:"Request body (JSON string or plain text)"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url"]}});async function Wh(s){let e=s.url,t=s.body,r=s.headers||{};if(h(`[http.post] execute url="${e}" body_len=${t?.length??0}`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");if(t&&!r["Content-Type"]&&!r["content-type"])try{JSON.parse(t),r["Content-Type"]="application/json"}catch{r["Content-Type"]="text/plain"}let o=await fetch(e,{method:"POST",headers:r,body:t||void 0}),n=await o.text(),a=`HTTP ${o.status} ${o.statusText}`;return n.length>kp?`${a}
23
- ${n.substring(0,kp)}
20
+ ... (truncated, total ${r.length} characters)`:`${s}
21
+ ${r}`:`${s}
22
+ ${r}`}var Up,Nt,gs=f(()=>{"use strict";l();qp();_();Up=1e5;Nt={name:Op,displayName:Ip,description:jp,parameters:Fp,category:Lp,execute:ly}});var Wp,Gp,Bp,Kp,Jp,Hp=f(()=>{"use strict";l();Wp="http.post",Gp="POST",Bp="Make an HTTP POST request to a URL with an optional body and return the response.",Kp="network",Jp={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 cy(n){let e=n.url,t=n.body,o=n.headers||{};if(h(`[http.post] execute url="${e}" body_len=${t?.length??0}`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");if(t&&!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}),s=await r.text(),i=`HTTP ${r.status} ${r.statusText}`;return s.length>zp?`${i}
23
+ ${s.substring(0,zp)}
24
24
 
25
- ... (truncated, total ${n.length} characters)`:`${a}
26
- ${n}`}var kp,kt,Xn=f(()=>{"use strict";l();_p();k();kp=1e5;kt={name:Pp,displayName:Cp,description:vp,parameters:$p,category:Sp,execute:Wh}});var Rp,Ep,Dp,Np,Ap,Mp=f(()=>{"use strict";l();Rp="http.put",Ep="PUT",Dp="Make an HTTP PUT request to a URL with an optional body and return the response.",Np="network",Ap={type:"object",properties:{url:{type:"string",description:"The URL to request"},body:{type:"string",description:"Request body (JSON string or plain text)"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url"]}});async function Gh(s){let e=s.url,t=s.body,r=s.headers||{};if(h(`[http.put] execute url="${e}" body_len=${t?.length??0}`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");if(t&&!r["Content-Type"]&&!r["content-type"])try{JSON.parse(t),r["Content-Type"]="application/json"}catch{r["Content-Type"]="text/plain"}let o=await fetch(e,{method:"PUT",headers:r,body:t||void 0}),n=await o.text(),a=`HTTP ${o.status} ${o.statusText}`;return n.length>Op?`${a}
27
- ${n.substring(0,Op)}
25
+ ... (truncated, total ${s.length} characters)`:`${i}
26
+ ${s}`}var zp,At,hs=f(()=>{"use strict";l();Hp();_();zp=1e5;At={name:Wp,displayName:Gp,description:Bp,parameters:Jp,category:Kp,execute:cy,confirmation:{level:"high",reason:"This will send an HTTP POST request with arbitrary payload.",showArgs:["url","body"]}}});var Qp,Yp,Vp,Xp,Zp,em=f(()=>{"use strict";l();Qp="http.put",Yp="PUT",Vp="Make an HTTP PUT request to a URL with an optional body and return the response.",Xp="network",Zp={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 py(n){let e=n.url,t=n.body,o=n.headers||{};if(h(`[http.put] execute url="${e}" body_len=${t?.length??0}`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");if(t&&!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}),s=await r.text(),i=`HTTP ${r.status} ${r.statusText}`;return s.length>tm?`${i}
27
+ ${s.substring(0,tm)}
28
28
 
29
- ... (truncated)`:`${a}
30
- ${n}`}var Op,Rt,Zn=f(()=>{"use strict";l();Mp();k();Op=1e5;Rt={name:Rp,displayName:Ep,description:Dp,parameters:Ap,category:Np,execute:Gh}});var Ip,jp,Fp,Lp,qp,Up=f(()=>{"use strict";l();Ip="http.delete",jp="DELETE",Fp="Make an HTTP DELETE request to a URL and return the response.",Lp="network",qp={type:"object",properties:{url:{type:"string",description:"The URL to request"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url"]}});async function Bh(s){let e=s.url,t=s.headers;if(h(`[http.delete] execute url="${e}"`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let r=await fetch(e,{method:"DELETE",headers:t||{}}),o=await r.text(),n=`HTTP ${r.status} ${r.statusText}`;return o.length>Wp?`${n}
31
- ${o.substring(0,Wp)}
29
+ ... (truncated)`:`${i}
30
+ ${s}`}var tm,Mt,ys=f(()=>{"use strict";l();em();_();tm=1e5;Mt={name:Qp,displayName:Yp,description:Vp,parameters:Zp,category:Xp,execute:py,confirmation:{level:"high",reason:"This will send an HTTP PUT request to overwrite remote resources.",showArgs:["url","body"]}}});var om,rm,nm,sm,im,am=f(()=>{"use strict";l();om="http.delete",rm="DELETE",nm="Make an HTTP DELETE request to a URL and return the response.",sm="network",im={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 my(n){let e=n.url,t=n.headers;if(h(`[http.delete] execute url="${e}"`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=await fetch(e,{method:"DELETE",headers:t||{}}),r=await o.text(),s=`HTTP ${o.status} ${o.statusText}`;return r.length>lm?`${s}
31
+ ${r.substring(0,lm)}
32
32
 
33
- ... (truncated)`:`${n}
34
- ${o}`}var Wp,Et,es=f(()=>{"use strict";l();Up();k();Wp=1e5;Et={name:Ip,displayName:jp,description:Fp,parameters:qp,category:Lp,execute:Bh}});var Gp,Bp,Jp,Hp,zp,Kp=f(()=>{"use strict";l();Gp="http.download",Bp="Download",Jp="Download a file from a URL and save it to a local path.",Hp="network",zp={type:"object",properties:{url:{type:"string",description:"The URL to download from"},path:{type:"string",description:"Local file path to save the downloaded file"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url","path"]}});async function Jh(s){let e=s.url,t=s.path,r=s.headers;if(h(`[http.download] execute url="${e}" path="${t}"`),!e)throw new Error("url is required");if(!t)throw new Error("path is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=await fetch(e,{method:"GET",headers:r||{}});if(!o.ok)throw new Error(`Download failed: HTTP ${o.status} ${o.statusText}`);let n=Buffer.from(await o.arrayBuffer()),a=Qp.dirname(t);return Dt.existsSync(a)||Dt.mkdirSync(a,{recursive:!0}),Dt.writeFileSync(t,n),`Downloaded ${e} \u2192 ${t} (${n.length} bytes)`}var Dt,Qp,Nt,ts=f(()=>{"use strict";l();Dt=T(require("fs"),1),Qp=T(require("path"),1);Kp();k();Nt={name:Gp,displayName:Bp,description:Jp,parameters:zp,category:Hp,execute:Jh}});var Yp={};V(Yp,{httpDeleteTool:()=>Et,httpDownloadTool:()=>Nt,httpGetTool:()=>_t,httpPostTool:()=>kt,httpPutTool:()=>Rt,httpToolsProject:()=>os});var os,rs=f(()=>{"use strict";l();Vn();Xn();Zn();es();ts();Vn();Xn();Zn();es();ts();os={manifest:{key:"http",name:"http-tools",displayName:"HTTP",version:"1.0.0",description:"HTTP tools for making GET, POST, PUT, DELETE requests and downloading files.",author:"Sajeer",tools:["http.get","http.post","http.put","http.delete","http.download"],category:"network"},tools:[_t,kt,Rt,Et,Nt],dependencies:{}}});var Vp,Xp,Zp,em,tm,om=f(()=>{"use strict";l();Vp="web.fetch",Xp="Fetch",Zp="Fetch content from a URL. Supports multiple extraction modes: full (raw HTML up to 15K chars), structured (title, excerpt, key points), or minimal (title + snippet).",em="network",tm={type:"object",properties:{url:{type:"string",description:"The URL to fetch"},extractionMode:{type:"string",description:'Content extraction mode: "full" (raw HTML, 15K limit), "structured" (title, excerpt, key points, main content), or "minimal" (title + 500 char snippet). Default: "full"',enum:["full","structured","minimal"],default:"full"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});function rm(s,e){let t=ns.load(s);t("script, style, nav, header, footer, aside, .advertisement, .ad, .sidebar").remove();let r=t("title").text().trim()||t("h1").first().text().trim()||t('meta[property="og:title"]').attr("content")||"Untitled",o=t('meta[name="author"]').attr("content")||t('meta[property="article:author"]').attr("content")||t(".author").first().text().trim()||void 0,n=t('meta[property="article:published_time"]').attr("content")||t("time").first().attr("datetime")||t(".date, .published").first().text().trim()||void 0,a=["article","main",'[role="main"]',".content",".article-content",".post-content","#content"],i="";for(let w of a){let y=t(w).first();if(y.length>0&&(i=y.text().trim(),i.length>200))break}(!i||i.length<200)&&(i=t("body").text().trim()),i=i.replace(/\s+/g," ").trim();let c=[];t("p").each((w,y)=>{let b=t(y).text().trim();b.length>50&&c.length<3&&c.push(b)});let p=c.join(`
33
+ ... (truncated)`:`${s}
34
+ ${r}`}var lm,Ot,ws=f(()=>{"use strict";l();am();_();lm=1e5;Ot={name:om,displayName:rm,description:nm,parameters:im,category:sm,execute:my,confirmation:{level:"high",reason:"This will send an HTTP DELETE request to destroy remote resources.",showArgs:["url"]}}});var cm,pm,mm,dm,um,fm=f(()=>{"use strict";l();cm="http.download",pm="Download",mm="Download a file from a URL and save it to a local path.",dm="network",um={type:"object",properties:{url:{type:"string",description:"The URL to download from"},path:{type:"string",description:"Local file path to save the downloaded file"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url","path"]}});async function dy(n){let e=n.url,t=n.path,o=n.headers;if(h(`[http.download] execute url="${e}" path="${t}"`),!e)throw new Error("url is required");if(!t)throw new Error("path is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let r=await fetch(e,{method:"GET",headers:o||{}});if(!r.ok)throw new Error(`Download failed: HTTP ${r.status} ${r.statusText}`);let s=Buffer.from(await r.arrayBuffer()),i=gm.dirname(t);return It.existsSync(i)||It.mkdirSync(i,{recursive:!0}),It.writeFileSync(t,s),`Downloaded ${e} \u2192 ${t} (${s.length} bytes)`}var It,gm,jt,bs=f(()=>{"use strict";l();It=x(require("fs"),1),gm=x(require("path"),1);fm();_();jt={name:cm,displayName:pm,description:mm,parameters:um,category:dm,execute:dy}});var hm={};Z(hm,{httpDeleteTool:()=>Ot,httpDownloadTool:()=>jt,httpGetTool:()=>Nt,httpPostTool:()=>At,httpPutTool:()=>Mt,httpToolsProject:()=>xs});var xs,Ts=f(()=>{"use strict";l();gs();hs();ys();ws();bs();gs();hs();ys();ws();bs();xs={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:[Nt,At,Mt,Ot,jt],dependencies:{}}});var ym,wm,bm,xm,Tm,Pm=f(()=>{"use strict";l();ym="web.fetch",wm="Fetch",bm="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).",xm="network",Tm={type:"object",properties:{url:{type:"string",description:"The URL to fetch"},extractionMode:{type:"string",description:'Content extraction mode: "full" (raw HTML, 15K limit), "structured" (title, excerpt, key points, main content), or "minimal" (title + 500 char snippet). Default: "full"',enum:["full","structured","minimal"],default:"full"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});function Cm(n,e){let t=Ps.load(n);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,s=t('meta[property="article:published_time"]').attr("content")||t("time").first().attr("datetime")||t(".date, .published").first().text().trim()||void 0,i=["article","main",'[role="main"]',".content",".article-content",".post-content","#content"],a="";for(let w of i){let y=t(w).first();if(y.length>0&&(a=y.text().trim(),a.length>200))break}(!a||a.length<200)&&(a=t("body").text().trim()),a=a.replace(/\s+/g," ").trim();let c=[];t("p").each((w,y)=>{let b=t(y).text().trim();b.length>50&&c.length<3&&c.push(b)});let p=c.join(`
35
35
 
36
- `)||i.substring(0,500),m=[];t("h2, h3").each((w,y)=>{let b=t(y).text().trim();b&&b.length>5&&b.length<200&&m.length<10&&m.push(b)});let u=i.split(/\s+/).length,g=i.split(/\s+/);return g.length>2e3&&(i=g.slice(0,2e3).join(" ")+"..."),{title:r,url:e,author:o,publishDate:n,excerpt:p.substring(0,1e3),mainContent:i.substring(0,1e4),keyPoints:m,wordCount:u}}function nm(s,e){let t=ns.load(s);t("script, style, nav, header, footer").remove();let r=t("title").text().trim()||t("h1").first().text().trim()||"Untitled",o=t('meta[name="description"]').attr("content")||t('meta[property="og:description"]').attr("content")||"";return o||t("p").each((n,a)=>{let i=t(a).text().trim();i.length>50&&!o&&(o=i)}),o||(o=t("body").text().trim().replace(/\s+/g," ")),{title:r,url:e,snippet:o.substring(0,500)}}function sm(s){let e=[];return e.push(`# ${s.title}`),e.push(`URL: ${s.url}`),s.author&&e.push(`Author: ${s.author}`),s.publishDate&&e.push(`Published: ${s.publishDate}`),e.push(`Word Count: ${s.wordCount}`),e.push(""),s.keyPoints.length>0&&(e.push("## Key Points"),s.keyPoints.forEach(t=>{e.push(`- ${t}`)}),e.push("")),e.push("## Excerpt"),e.push(s.excerpt),e.push(""),e.push("## Main Content"),e.push(s.mainContent),e.join(`
37
- `)}function im(s){return`# ${s.title}
38
- URL: ${s.url}
36
+ `)||a.substring(0,500),m=[];t("h2, h3").each((w,y)=>{let b=t(y).text().trim();b&&b.length>5&&b.length<200&&m.length<10&&m.push(b)});let u=a.split(/\s+/).length,g=a.split(/\s+/);return g.length>2e3&&(a=g.slice(0,2e3).join(" ")+"..."),{title:o,url:e,author:r,publishDate:s,excerpt:p.substring(0,1e3),mainContent:a.substring(0,1e4),keyPoints:m,wordCount:u}}function vm(n,e){let t=Ps.load(n);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((s,i)=>{let a=t(i).text().trim();a.length>50&&!r&&(r=a)}),r||(r=t("body").text().trim().replace(/\s+/g," ")),{title:o,url:e,snippet:r.substring(0,500)}}function Sm(n){let e=[];return e.push(`# ${n.title}`),e.push(`URL: ${n.url}`),n.author&&e.push(`Author: ${n.author}`),n.publishDate&&e.push(`Published: ${n.publishDate}`),e.push(`Word Count: ${n.wordCount}`),e.push(""),n.keyPoints.length>0&&(e.push("## Key Points"),n.keyPoints.forEach(t=>{e.push(`- ${t}`)}),e.push("")),e.push("## Excerpt"),e.push(n.excerpt),e.push(""),e.push("## Main Content"),e.push(n.mainContent),e.join(`
37
+ `)}function km(n){return`# ${n.title}
38
+ URL: ${n.url}
39
39
 
40
- ${s.snippet}`}var ns,am=f(()=>{"use strict";l();ns=T(require("cheerio"),1)});async function Hh(s){let e=s.url,t=s.extractionMode||"full",r=s.headers,o=s.timeout||3e4;if(h(`[web.fetch] execute url="${e}" mode=${t} timeout=${o}ms`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let n=new AbortController,a=setTimeout(()=>n.abort(),o),i;try{i=await fetch(e,{method:"GET",headers:r||{},signal:n.signal})}catch(p){throw p.name==="AbortError"?new Error(`Request timed out after ${o}ms`):p}finally{clearTimeout(a)}if(!i.ok)return`HTTP ${i.status} ${i.statusText}
41
- ${await i.text()}`;let c=await i.text();if(t==="structured"){let p=rm(c,e);return sm(p)}else if(t==="minimal"){let p=nm(c,e);return im(p)}else return c.length>15e3?c.substring(0,15e3)+`
40
+ ${n.snippet}`}var Ps,$m=f(()=>{"use strict";l();Ps=x(require("cheerio"),1)});async function uy(n){let e=n.url,t=n.extractionMode||"full",o=n.headers,r=n.timeout||3e4;if(h(`[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 s=new AbortController,i=setTimeout(()=>s.abort(),r),a;try{a=await fetch(e,{method:"GET",headers:o||{},signal:s.signal})}catch(p){throw p.name==="AbortError"?new Error(`Request timed out after ${r}ms`):p}finally{clearTimeout(i)}if(!a.ok)return`HTTP ${a.status} ${a.statusText}
41
+ ${await a.text()}`;let c=await a.text();if(t==="structured"){let p=Cm(c,e);return Sm(p)}else if(t==="minimal"){let p=vm(c,e);return km(p)}else return c.length>15e3?c.substring(0,15e3)+`
42
42
 
43
- [TRUNCATED: showing 15K of ${c.length} total characters]`:c}var At,ss=f(()=>{"use strict";l();om();am();k();At={name:Vp,displayName:Xp,description:Zp,parameters:tm,category:em,execute:Hh}});var lm,cm,pm,mm,dm,um=f(()=>{"use strict";l();lm="web.search",cm="Search",pm="Search the web using multiple providers (Tavily, Brave, DuckDuckGo Lite) with automatic fallback. Supports real-time results via freshness parameter and AI-generated answers. Configure API keys via environment variables (TOOLPACK_TAVILY_API_KEY, TOOLPACK_BRAVE_API_KEY) or toolpack.config.json for best results.",mm="network",dm={type:"object",properties:{query:{type:"string",description:"The search query"},max_results:{type:"integer",description:"Maximum number of results to return (default: 5)",default:5},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4},include_answer:{type:"boolean",description:"Include AI-generated answer summary (works with Tavily and Brave APIs). Default: false",default:!1},freshness:{type:"string",description:'Time range for fresh/recent results: "day" (last 24h), "week" (last 7 days), "month" (last 31 days), "year" (last 365 days). Ensures latest real-time data. Supported by Tavily and Brave APIs; DuckDuckGo returns general results.',enum:["day","week","month","year"]}},required:["query"]}});function po(s){let e=hm(s);if(!Ce.existsSync(e))return{};try{let t=Ce.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return{}}}function Mt(s){let e=po(s),t=zh(e.tools||e);return h(JSON.stringify(t??{})),t}function gm(s,e){let t=hm(e),r={};try{Ce.existsSync(t)&&(r=JSON.parse(Ce.readFileSync(t,"utf-8")))}catch{r={}}r.tools=s,Ce.writeFileSync(t,JSON.stringify(r,null,4),"utf-8")}function zh(s){let e=s.additionalConfigurations||{};return e.webSearch||(e.webSearch={}),!e.webSearch.tavilyApiKey&&process.env.TOOLPACK_TAVILY_API_KEY&&(e.webSearch.tavilyApiKey=process.env.TOOLPACK_TAVILY_API_KEY),!e.webSearch.braveApiKey&&process.env.TOOLPACK_BRAVE_API_KEY&&(e.webSearch.braveApiKey=process.env.TOOLPACK_BRAVE_API_KEY),{enabled:s.enabled??H.enabled,autoExecute:s.autoExecute??H.autoExecute,maxToolRounds:s.maxToolRounds??H.maxToolRounds,toolChoicePolicy:s.toolChoicePolicy??H.toolChoicePolicy,resultMaxChars:s.resultMaxChars??H.resultMaxChars,intelligentToolDetection:s.intelligentToolDetection,enabledTools:s.enabledTools??H.enabledTools,enabledToolCategories:s.enabledToolCategories??H.enabledToolCategories,toolSearch:s.toolSearch??H.toolSearch,additionalConfigurations:e}}function hm(s){return s?s.endsWith(".json")?pr.resolve(s):pr.resolve(s,fm):pr.resolve(process.cwd(),fm)}var Ce,pr,fm,is=f(()=>{"use strict";l();Ce=T(require("fs"),1),pr=T(require("path"),1);Xt();k();fm="toolpack.config.json"});function Yh(s,e){h("[web.search] Parsing DuckDuckGo Lite response");let t=wm.load(s),r=[];return t("a.result-link").each((n,a)=>{if(r.length>=e)return;let i=t(a),c=i.text().trim(),p=i.attr("href"),m=i.siblings(".result-snippet").text().trim();m||(m=i.parent().text().replace(c,"").trim()),c&&p&&r.push({title:c,link:p,snippet:m.slice(0,200)})}),r}function Vh(s){if(s)switch(s){case"day":return 1;case"week":return 7;case"month":return 31;case"year":return 365;default:return}}function ym(s){if(!s)return"";switch(s){case"day":return"pd";case"week":return"pw";case"month":return"pm";case"year":return"py";default:return""}}async function Xh(s){let e=s.query,t=s.max_results||5,r=s.include_answer||!1,o=s.freshness;h(`[web.search] execute query="${e}" max_results=${t} includeAnswer=${r} freshness=${o??"none"}`);let n=`Request timed out after ${s.timeout||3e4}ms`,a=()=>{let u=new AbortController,g=setTimeout(()=>u.abort(),s.timeout||3e4);return{signal:u.signal,clear:()=>clearTimeout(g)}};if(!e)throw new Error("query is required");let i=Mt();if(h(`[web.search] config=${JSON.stringify(i)}`),i.additionalConfigurations?.webSearch?.tavilyApiKey){h("[web.search] using Tavily API");try{let{signal:u,clear:g}=a(),w=Vh(o),y={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:i.additionalConfigurations.webSearch.tavilyApiKey,query:e,max_results:t,include_answer:r,...w&&{days:w}}),signal:u};h(`[web.search] Tavily request=${JSON.stringify(y)}`);let b=await fetch("https://api.tavily.com/search",y).finally(g);if(b.ok){let P=await b.json();if(P.results&&P.results.length>0){let $=P.results.map(C=>({title:C.title,link:C.url,snippet:C.content}));return r&&P.answer?JSON.stringify({answer:P.answer,results:$},null,2):JSON.stringify($,null,2)}}else Y(`[web.search] Tavily search failed with status ${b.status}`)}catch(u){Y(`[web.search] Tavily search failed, falling back: ${u}`)}}if(i.additionalConfigurations?.webSearch?.braveApiKey)try{let{signal:u,clear:g}=a();if(r){let w=ym(o),y=w?`&freshness=${w}`:"",b=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(e)}&count=${Math.min(t,20)}&summary=1${y}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":i.additionalConfigurations.webSearch.braveApiKey},signal:u}).finally(g);if(b.ok){let P=await b.json(),$=P.summarizer?.key;if($&&P.web?.results){let{signal:C,clear:x}=a(),S=await fetch(`https://api.search.brave.com/res/v1/summarizer/search?key=${$}`,{headers:{Accept:"application/json","X-Subscription-Token":i.additionalConfigurations.webSearch.braveApiKey},signal:C}).finally(x);if(S.ok){let R=await S.json(),j=P.web.results.slice(0,t).map(L=>({title:L.title,link:L.url,snippet:L.description})),U=R.summary?.map(L=>L.data).join(`
44
- `)||R.title;return JSON.stringify({answer:U,results:j},null,2)}}if(P.web?.results){let C=P.web.results.slice(0,t).map(x=>({title:x.title,link:x.url,snippet:x.description}));return JSON.stringify(C,null,2)}}}else{let w=ym(o),y=w?`&freshness=${w}`:"",b=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(e)}&count=${Math.min(t,20)}${y}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":i.additionalConfigurations.webSearch.braveApiKey},signal:u}).finally(g);if(b.ok){let P=await b.json();if(P.web?.results&&P.web.results.length>0){let $=P.web.results.slice(0,t).map(C=>({title:C.title,link:C.url,snippet:C.description}));return JSON.stringify($,null,2)}}}}catch(u){E(`[web.search] Brave search failed, falling back: ${u}`)}let{signal:c,clear:p}=a(),m;try{m=await fetch(Kh,{method:"POST",headers:{"User-Agent":Qh,"Content-Type":"application/x-www-form-urlencoded",Origin:"https://lite.duckduckgo.com",Referer:"https://lite.duckduckgo.com/"},body:new URLSearchParams({q:e}).toString(),signal:c})}catch(u){throw u.name==="AbortError"?new Error(n):u}finally{p()}if(m.ok){let u=await m.text(),g=Yh(u,t);if(g.length>0)return JSON.stringify(g,null,2)}return JSON.stringify({error:"search_unavailable",message:`Search failed to find results for "${e}" across all providers.`,suggestion:"Please configure a search provider API key (tavilyApiKey or braveApiKey) in toolpack.config.json under tools.additionalConfigurations.webSearch."})}var wm,Kh,Qh,Ot,as=f(()=>{"use strict";l();wm=T(require("cheerio"),1);um();is();k();Kh="https://lite.duckduckgo.com/lite/",Qh="Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1";Ot={name:lm,displayName:cm,description:pm,parameters:dm,category:mm,execute:Xh}});var bm,xm,Tm,Pm,Cm,vm=f(()=>{"use strict";l();bm="web.scrape",xm="Scrape",Tm="Extract clean text content from a webpage. RECOMMENDED WORKFLOW: Use web.map first to see page structure, then use section parameter to extract specific sections. Strips scripts, styles, navigation, and other junk. By default, auto-detects and extracts the main article/content area.",Pm="network",Cm={type:"object",properties:{url:{type:"string",description:"The URL to scrape"},section:{type:"string",description:'Optional section name to extract (e.g., "talks", "about", "experience"). Finds the heading containing this text and extracts content until the next same-level heading. Use web.map first to discover available sections.'},format:{type:"string",description:'Output format: "text" (clean readable text) or "tables" (extract table data as JSON array). Default: "text"',enum:["text","tables"],default:"text"},selector:{type:"string",description:"Optional CSS selector to target a specific element. Only use if you know the exact selector exists."},max_length:{type:"integer",description:"Maximum characters to return (default: 6000). Keep small (3000-6000) to avoid context limits.",default:6e3},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function ty(s){let e=s.url,t=s.selector,r=s.section,o=s.format||"text",n=s.max_length||6e3,a=s.timeout||3e4;if(h(`[web.scrape] execute url="${e}" format=${o} selector=${t??"none"} section=${r??"none"} timeout=${a}ms`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let i=new AbortController,c=setTimeout(()=>i.abort(),a),p;try{p=await fetch(e,{method:"GET",headers:{"User-Agent":Zh},signal:i.signal})}catch(y){throw y.name==="AbortError"?new Error(`Request timed out after ${a}ms`):y}finally{clearTimeout(c)}if(!p.ok)throw new Error(`Failed to fetch ${e}: HTTP ${p.status} ${p.statusText}`);let m=await p.text(),u=_m.load(m);for(let y of ey)u(y).remove();if(o==="tables"){let y=[];return u("table").each((b,P)=>{let $=[],C=[];u(P).find("th").each((x,S)=>{C.push(u(S).text().trim())}),u(P).find("tr").each((x,S)=>{let R=C.length>0?{}:[],j=u(S).find("td");j.length>0&&(j.each((U,L)=>{let F=u(L).text().trim();C.length>0&&C[U]?R[C[U]]=F:R.push(F)}),$.push(R))}),$.length>0&&y.push({id:`Table ${b+1}`,headers:C.length>0?C:void 0,rows:$})}),y.length===0?`No tables found on ${e}`:JSON.stringify(y,null,2)}let g="";if(r){let y=r.toLowerCase(),b=null,P=0;if(u("h1, h2, h3, h4, h5, h6").each(($,C)=>{if(u(C).text().toLowerCase().includes(y))return b=C,P=parseInt(C.tagName.charAt(1)),!1}),b){let $=u(b),C=[],x=$.next();for(;x.length>0;){let S=x.prop("tagName")?.toLowerCase();if(S&&/^h[1-6]$/.test(S)&&parseInt(S.charAt(1))<=P)break;let R=x.text().trim();R&&C.push(R),x=x.next()}C.length>0?(g=C.join(`
43
+ [TRUNCATED: showing 15K of ${c.length} total characters]`:c}var Lt,Cs=f(()=>{"use strict";l();Pm();$m();_();Lt={name:ym,displayName:wm,description:bm,parameters:Tm,category:xm,execute:uy}});var _m,Rm,Dm,Em,Nm,Am=f(()=>{"use strict";l();_m="web.search",Rm="Search",Dm="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.",Em="network",Nm={type:"object",properties:{query:{type:"string",description:"The search query"},max_results:{type:"integer",description:"Maximum number of results to return (default: 5)",default:5},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4},include_answer:{type:"boolean",description:"Include AI-generated answer summary (works with Tavily and Brave APIs). Default: false",default:!1},freshness:{type:"string",description:'Time range for fresh/recent results: "day" (last 24h), "week" (last 7 days), "month" (last 31 days), "year" (last 365 days). Ensures latest real-time data. Supported by Tavily and Brave APIs; DuckDuckGo returns general results.',enum:["day","week","month","year"]}},required:["query"]}});function ho(n){let e=Im(n);if(!$e.existsSync(e))return{};try{let t=$e.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return{}}}function Ft(n){let e=ho(n),t=fy(e.tools||e);return h(JSON.stringify(t??{})),t}function Om(n,e){let t=Im(e),o={};try{$e.existsSync(t)&&(o=JSON.parse($e.readFileSync(t,"utf-8")))}catch{o={}}o.tools=n,$e.writeFileSync(t,JSON.stringify(o,null,4),"utf-8")}function fy(n){let e=n.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:n.enabled??H.enabled,autoExecute:n.autoExecute??H.autoExecute,maxToolRounds:n.maxToolRounds??H.maxToolRounds,toolChoicePolicy:n.toolChoicePolicy??H.toolChoicePolicy,resultMaxChars:n.resultMaxChars??H.resultMaxChars,intelligentToolDetection:n.intelligentToolDetection,enabledTools:n.enabledTools??H.enabledTools,enabledToolCategories:n.enabledToolCategories??H.enabledToolCategories,toolSearch:n.toolSearch??H.toolSearch,additionalConfigurations:e}}function Im(n){return n?n.endsWith(".json")?yr.resolve(n):yr.resolve(n,Mm):yr.resolve(process.cwd(),Mm)}var $e,yr,Mm,vs=f(()=>{"use strict";l();$e=x(require("fs"),1),yr=x(require("path"),1);ro();_();Mm="toolpack.config.json"});function yy(n,e){h("[web.search] Parsing DuckDuckGo Lite response");let t=Lm.load(n),o=[];return t("a.result-link").each((s,i)=>{if(o.length>=e)return;let a=t(i),c=a.text().trim(),p=a.attr("href"),m=a.siblings(".result-snippet").text().trim();m||(m=a.parent().text().replace(c,"").trim()),c&&p&&o.push({title:c,link:p,snippet:m.slice(0,200)})}),o}function wy(n){if(n)switch(n){case"day":return 1;case"week":return 7;case"month":return 31;case"year":return 365;default:return}}function jm(n){if(!n)return"";switch(n){case"day":return"pd";case"week":return"pw";case"month":return"pm";case"year":return"py";default:return""}}async function by(n){let e=n.query,t=n.max_results||5,o=n.include_answer||!1,r=n.freshness;h(`[web.search] execute query="${e}" max_results=${t} includeAnswer=${o} freshness=${r??"none"}`);let s=`Request timed out after ${n.timeout||3e4}ms`,i=()=>{let u=new AbortController,g=setTimeout(()=>u.abort(),n.timeout||3e4);return{signal:u.signal,clear:()=>clearTimeout(g)}};if(!e)throw new Error("query is required");let a=Ft();if(h(`[web.search] config=${JSON.stringify(a)}`),a.additionalConfigurations?.webSearch?.tavilyApiKey){h("[web.search] using Tavily API");try{let{signal:u,clear:g}=i(),w=wy(r),y={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:a.additionalConfigurations.webSearch.tavilyApiKey,query:e,max_results:t,include_answer:o,...w&&{days:w}}),signal:u};h(`[web.search] Tavily request=${JSON.stringify(y)}`);let b=await fetch("https://api.tavily.com/search",y).finally(g);if(b.ok){let T=await b.json();if(T.results&&T.results.length>0){let k=T.results.map(C=>({title:C.title,link:C.url,snippet:C.content}));return o&&T.answer?JSON.stringify({answer:T.answer,results:k},null,2):JSON.stringify(k,null,2)}}else Q(`[web.search] Tavily search failed with status ${b.status}`)}catch(u){Q(`[web.search] Tavily search failed, falling back: ${u}`)}}if(a.additionalConfigurations?.webSearch?.braveApiKey)try{let{signal:u,clear:g}=i();if(o){let w=jm(r),y=w?`&freshness=${w}`:"",b=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(e)}&count=${Math.min(t,20)}&summary=1${y}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":a.additionalConfigurations.webSearch.braveApiKey},signal:u}).finally(g);if(b.ok){let T=await b.json(),k=T.summarizer?.key;if(k&&T.web?.results){let{signal:C,clear:P}=i(),S=await fetch(`https://api.search.brave.com/res/v1/summarizer/search?key=${k}`,{headers:{Accept:"application/json","X-Subscription-Token":a.additionalConfigurations.webSearch.braveApiKey},signal:C}).finally(P);if(S.ok){let R=await S.json(),D=T.web.results.slice(0,t).map(j=>({title:j.title,link:j.url,snippet:j.description})),L=R.summary?.map(j=>j.data).join(`
44
+ `)||R.title;return JSON.stringify({answer:L,results:D},null,2)}}if(T.web?.results){let C=T.web.results.slice(0,t).map(P=>({title:P.title,link:P.url,snippet:P.description}));return JSON.stringify(C,null,2)}}}else{let w=jm(r),y=w?`&freshness=${w}`:"",b=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(e)}&count=${Math.min(t,20)}${y}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":a.additionalConfigurations.webSearch.braveApiKey},signal:u}).finally(g);if(b.ok){let T=await b.json();if(T.web?.results&&T.web.results.length>0){let k=T.web.results.slice(0,t).map(C=>({title:C.title,link:C.url,snippet:C.description}));return JSON.stringify(k,null,2)}}}}catch(u){E(`[web.search] Brave search failed, falling back: ${u}`)}let{signal:c,clear:p}=i(),m;try{m=await fetch(gy,{method:"POST",headers:{"User-Agent":hy,"Content-Type":"application/x-www-form-urlencoded",Origin:"https://lite.duckduckgo.com",Referer:"https://lite.duckduckgo.com/"},body:new URLSearchParams({q:e}).toString(),signal:c})}catch(u){throw u.name==="AbortError"?new Error(s):u}finally{p()}if(m.ok){let u=await m.text(),g=yy(u,t);if(g.length>0)return JSON.stringify(g,null,2)}return JSON.stringify({error:"search_unavailable",message:`Search failed to find results for "${e}" across all providers.`,suggestion:"Please configure a search provider API key (tavilyApiKey or braveApiKey) in toolpack.config.json under tools.additionalConfigurations.webSearch."})}var Lm,gy,hy,qt,Ss=f(()=>{"use strict";l();Lm=x(require("cheerio"),1);Am();vs();_();gy="https://lite.duckduckgo.com/lite/",hy="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";qt={name:_m,displayName:Rm,description:Dm,parameters:Nm,category:Em,execute:by}});var Fm,qm,Um,Wm,Gm,Bm=f(()=>{"use strict";l();Fm="web.scrape",qm="Scrape",Um="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.",Wm="network",Gm={type:"object",properties:{url:{type:"string",description:"The URL to scrape"},section:{type:"string",description:'Optional section name to extract (e.g., "talks", "about", "experience"). Finds the heading containing this text and extracts content until the next same-level heading. Use web.map first to discover available sections.'},format:{type:"string",description:'Output format: "text" (clean readable text) or "tables" (extract table data as JSON array). Default: "text"',enum:["text","tables"],default:"text"},selector:{type:"string",description:"Optional CSS selector to target a specific element. Only use if you know the exact selector exists."},max_length:{type:"integer",description:"Maximum characters to return (default: 6000). Keep small (3000-6000) to avoid context limits.",default:6e3},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function Py(n){let e=n.url,t=n.selector,o=n.section,r=n.format||"text",s=n.max_length||6e3,i=n.timeout||3e4;if(h(`[web.scrape] execute url="${e}" format=${r} selector=${t??"none"} section=${o??"none"} timeout=${i}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 a=new AbortController,c=setTimeout(()=>a.abort(),i),p;try{p=await fetch(e,{method:"GET",headers:{"User-Agent":xy},signal:a.signal})}catch(y){throw y.name==="AbortError"?new Error(`Request timed out after ${i}ms`):y}finally{clearTimeout(c)}if(!p.ok)throw new Error(`Failed to fetch ${e}: HTTP ${p.status} ${p.statusText}`);let m=await p.text(),u=Hm.load(m);for(let y of Ty)u(y).remove();if(r==="tables"){let y=[];return u("table").each((b,T)=>{let k=[],C=[];u(T).find("th").each((P,S)=>{C.push(u(S).text().trim())}),u(T).find("tr").each((P,S)=>{let R=C.length>0?{}:[],D=u(S).find("td");D.length>0&&(D.each((L,j)=>{let U=u(j).text().trim();C.length>0&&C[L]?R[C[L]]=U:R.push(U)}),k.push(R))}),k.length>0&&y.push({id:`Table ${b+1}`,headers:C.length>0?C:void 0,rows:k})}),y.length===0?`No tables found on ${e}`:JSON.stringify(y,null,2)}let g="";if(o){let y=o.toLowerCase(),b=null,T=0;if(u("h1, h2, h3, h4, h5, h6").each((k,C)=>{if(u(C).text().toLowerCase().includes(y))return b=C,T=parseInt(C.tagName.charAt(1)),!1}),b){let k=u(b),C=[],P=k.next();for(;P.length>0;){let S=P.prop("tagName")?.toLowerCase();if(S&&/^h[1-6]$/.test(S)&&parseInt(S.charAt(1))<=T)break;let R=P.text().trim();R&&C.push(R),P=P.next()}C.length>0?(g=C.join(`
45
45
 
46
- `).replace(/\s+/g," ").trim(),g=`[Section: "${r}"]
46
+ `).replace(/\s+/g," ").trim(),g=`[Section: "${o}"]
47
47
 
48
- ${g}`):g=`[Note: Found heading "${r}" but no content below it. Falling back to full page.]
48
+ ${g}`):g=`[Note: Found heading "${o}" but no content below it. Falling back to full page.]
49
49
 
50
- `}else g=`[Note: Section "${r}" not found. Falling back to full page.]
50
+ `}else g=`[Note: Section "${o}" not found. Falling back to full page.]
51
51
 
52
- `}if(!g||g.includes("Falling back to full page"))if(g&&g.includes("Falling back to full page")&&(g=""),t){let y=u(t);if(y.length>0)g=y.text().replace(/\s+/g," ").trim();else{for(let b of Sm){let P=u(b);if(P.length>0){let $=P.text().replace(/\s+/g," ").trim();if($.length>$m){g=$;break}}}if(g)g=`[Note: Selector "${t}" not found. Showing auto-detected main content instead.]
52
+ `}if(!g||g.includes("Falling back to full page"))if(g&&g.includes("Falling back to full page")&&(g=""),t){let y=u(t);if(y.length>0)g=y.text().replace(/\s+/g," ").trim();else{for(let b of Km){let T=u(b);if(T.length>0){let k=T.text().replace(/\s+/g," ").trim();if(k.length>Jm){g=k;break}}}if(g)g=`[Note: Selector "${t}" not found. Showing auto-detected main content instead.]
53
53
 
54
- ${g}`;else return`No element found matching selector "${t}" and could not auto-detect main content from ${e}`}}else for(let y of Sm){let b=u(y);if(b.length>0){let P=b.text().replace(/\s+/g," ").trim();if(P.length>$m){g=P;break}}}if(g||(g=u("body").text().replace(/\s+/g," ").trim(),g&&(g=`[Note: Could not detect main content area. Showing full page text (may include navigation).]
54
+ ${g}`;else return`No element found matching selector "${t}" and could not auto-detect main content from ${e}`}}else for(let y of Km){let b=u(y);if(b.length>0){let T=b.text().replace(/\s+/g," ").trim();if(T.length>Jm){g=T;break}}}if(g||(g=u("body").text().replace(/\s+/g," ").trim(),g&&(g=`[Note: Could not detect main content area. Showing full page text (may include navigation).]
55
55
 
56
- ${g}`)),!g)return`Could not extract any content from ${e}`;if(g.length>n){let y=g.substring(0,n);return`[Warning: Content exceeds ${n} chars (actual: ${g.length} chars). Showing first ${n} chars only.]
56
+ ${g}`)),!g)return`Could not extract any content from ${e}`;if(g.length>s){let y=g.substring(0,s);return`[Warning: Content exceeds ${s} chars (actual: ${g.length} chars). Showing first ${s} chars only.]
57
57
 
58
58
  RECOMMENDATION: Use web.map to see page structure, then use web.scrape with section parameter to extract specific sections.
59
59
 
@@ -61,61 +61,61 @@ Page content from ${e}:
61
61
 
62
62
  ${y}
63
63
 
64
- ... [Content truncated. ${g.length-n} chars remaining. Use section parameter to extract specific sections.]`}return`Page content from ${e}:
64
+ ... [Content truncated. ${g.length-s} chars remaining. Use section parameter to extract specific sections.]`}return`Page content from ${e}:
65
65
 
66
- ${g}`}var _m,Zh,ey,Sm,$m,It,ls=f(()=>{"use strict";l();_m=T(require("cheerio"),1);vm();k();Zh="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",ey=["script","style","nav","footer","header","iframe",".ads",".sidebar","noscript"],Sm=["article","main",".content","#content",'[role="main"]',"body"],$m=200;It={name:bm,displayName:xm,description:Tm,parameters:Cm,category:Pm,execute:ty}});var km,Rm,Em,Dm,Nm,Am=f(()=>{"use strict";l();km="web.extract_links",Rm="Extract Links",Em="Extract all links from a webpage. Returns an array of objects with text and URL. Optionally filter by pattern.",Dm="network",Nm={type:"object",properties:{url:{type:"string",description:"The URL to extract links from"},filter:{type:"string",description:'Optional filter: "same-domain" to only include links from the same domain, or a substring to match against URLs'},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function ry(s){let e=s.url,t=s.filter,r=s.timeout||3e4;if(!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=new AbortController,n=setTimeout(()=>o.abort(),r),a;try{a=await fetch(e,{method:"GET",headers:{"User-Agent":oy},signal:o.signal})}catch(u){throw u.name==="AbortError"?new Error(`Request timed out after ${r}ms`):u}finally{clearTimeout(n)}if(!a.ok)throw new Error(`Failed to fetch ${e}: HTTP ${a.status} ${a.statusText}`);let i=await a.text(),c=Mm.load(i),p=new URL(e),m=[];return c("a[href]").each((u,g)=>{let w=c(g),y=w.attr("href");if(!y)return;let b;try{b=new URL(y,e).toString()}catch{return}if(b.startsWith("javascript:")||b.startsWith("mailto:")||b.startsWith("tel:"))return;let P=w.text().trim()||"[no text]";if(t){if(t==="same-domain")try{if(new URL(b).hostname!==p.hostname)return}catch{return}else if(!b.includes(t))return}m.push({text:P,url:b})}),m.length===0?`No links found on ${e}${t?` matching filter "${t}"`:""}`:JSON.stringify(m,null,2)}var Mm,oy,jt,cs=f(()=>{"use strict";l();Mm=T(require("cheerio"),1);Am();oy="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";jt={name:km,displayName:Rm,description:Em,parameters:Nm,category:Dm,execute:ry}});var Om,Im,jm,Fm,Lm,qm=f(()=>{"use strict";l();Om="web.map",Im="Map",jm="Extract the structure/outline of a webpage by returning all headings (h1-h6). Use this FIRST when you need to understand what sections exist on a page before scraping specific content. Returns a lightweight outline showing the page hierarchy.",Fm="network",Lm={type:"object",properties:{url:{type:"string",description:"The URL to map"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function sy(s){let e=s.url,t=s.timeout||3e4;if(!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let r=new AbortController,o=setTimeout(()=>r.abort(),t),n;try{n=await fetch(e,{method:"GET",headers:{"User-Agent":ny},signal:r.signal})}catch(m){throw m.name==="AbortError"?new Error(`Request timed out after ${t}ms`):m}finally{clearTimeout(o)}if(!n.ok)throw new Error(`Failed to fetch ${e}: HTTP ${n.status} ${n.statusText}`);let a=await n.text(),i=Um.load(a),c=[];if(i("h1, h2, h3, h4, h5, h6").each((m,u)=>{let g=u.tagName.toLowerCase(),w=parseInt(g.charAt(1)),y=i(u).text().trim();y&&c.push({level:w,text:y})}),c.length===0)return`No headings found on ${e}. The page may not have a clear structure.`;let p=`Page outline for ${e}:
66
+ ${g}`}var Hm,xy,Ty,Km,Jm,Ut,ks=f(()=>{"use strict";l();Hm=x(require("cheerio"),1);Bm();_();xy="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",Ty=["script","style","nav","footer","header","iframe",".ads",".sidebar","noscript"],Km=["article","main",".content","#content",'[role="main"]',"body"],Jm=200;Ut={name:Fm,displayName:qm,description:Um,parameters:Gm,category:Wm,execute:Py}});var zm,Qm,Ym,Vm,Xm,Zm=f(()=>{"use strict";l();zm="web.extract_links",Qm="Extract Links",Ym="Extract all links from a webpage. Returns an array of objects with text and URL. Optionally filter by pattern.",Vm="network",Xm={type:"object",properties:{url:{type:"string",description:"The URL to extract links from"},filter:{type:"string",description:'Optional filter: "same-domain" to only include links from the same domain, or a substring to match against URLs'},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function vy(n){let e=n.url,t=n.filter,o=n.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,s=setTimeout(()=>r.abort(),o),i;try{i=await fetch(e,{method:"GET",headers:{"User-Agent":Cy},signal:r.signal})}catch(u){throw u.name==="AbortError"?new Error(`Request timed out after ${o}ms`):u}finally{clearTimeout(s)}if(!i.ok)throw new Error(`Failed to fetch ${e}: HTTP ${i.status} ${i.statusText}`);let a=await i.text(),c=ed.load(a),p=new URL(e),m=[];return c("a[href]").each((u,g)=>{let w=c(g),y=w.attr("href");if(!y)return;let b;try{b=new URL(y,e).toString()}catch{return}if(b.startsWith("javascript:")||b.startsWith("mailto:")||b.startsWith("tel:"))return;let T=w.text().trim()||"[no text]";if(t){if(t==="same-domain")try{if(new URL(b).hostname!==p.hostname)return}catch{return}else if(!b.includes(t))return}m.push({text:T,url:b})}),m.length===0?`No links found on ${e}${t?` matching filter "${t}"`:""}`:JSON.stringify(m,null,2)}var ed,Cy,Wt,$s=f(()=>{"use strict";l();ed=x(require("cheerio"),1);Zm();Cy="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Wt={name:zm,displayName:Qm,description:Ym,parameters:Xm,category:Vm,execute:vy}});var td,od,rd,nd,sd,id=f(()=>{"use strict";l();td="web.map",od="Map",rd="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.",nd="network",sd={type:"object",properties:{url:{type:"string",description:"The URL to map"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function ky(n){let e=n.url,t=n.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),s;try{s=await fetch(e,{method:"GET",headers:{"User-Agent":Sy},signal:o.signal})}catch(m){throw m.name==="AbortError"?new Error(`Request timed out after ${t}ms`):m}finally{clearTimeout(r)}if(!s.ok)throw new Error(`Failed to fetch ${e}: HTTP ${s.status} ${s.statusText}`);let i=await s.text(),a=ad.load(i),c=[];if(a("h1, h2, h3, h4, h5, h6").each((m,u)=>{let g=u.tagName.toLowerCase(),w=parseInt(g.charAt(1)),y=a(u).text().trim();y&&c.push({level:w,text:y})}),c.length===0)return`No headings found on ${e}. The page may not have a clear structure.`;let p=`Page outline for ${e}:
67
67
 
68
68
  `;for(let m of c){let u=" ".repeat(m.level-1);p+=`${u}${"#".repeat(m.level)} ${m.text}
69
- `}return p}var Um,ny,mr,ps=f(()=>{"use strict";l();Um=T(require("cheerio"),1);qm();ny="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";mr={name:Om,displayName:Im,description:jm,parameters:Lm,category:Fm,execute:sy}});var Wm,Gm,Bm,Jm,Hm,zm=f(()=>{"use strict";l();Wm="web.metadata",Gm="Extract Metadata",Bm="Extract Open Graph, Twitter Cards, JSON-LD, and meta tags from a URL.",Jm="network",Hm={type:"object",properties:{url:{type:"string",description:"The URL to extract metadata from"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function ay(s){let e=s.url,t=s.timeout||3e4;if(!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let r=new AbortController,o=setTimeout(()=>r.abort(),t),n;try{n=await fetch(e,{method:"GET",headers:{"User-Agent":iy},signal:r.signal})}catch(p){throw p.name==="AbortError"?new Error(`Request timed out after ${t}ms`):p}finally{clearTimeout(o)}if(!n.ok)throw new Error(`Failed to fetch ${e}: HTTP ${n.status} ${n.statusText}`);let a=await n.text(),i=Km.load(a),c={title:i("title").text()||"",description:i('meta[name="description"]').attr("content")||i('meta[property="og:description"]').attr("content")||"",author:i('meta[name="author"]').attr("content")||"",openGraph:{},twitter:{},jsonLd:[]};return i('meta[property^="og:"]').each((p,m)=>{let u=i(m).attr("property")?.replace("og:",""),g=i(m).attr("content");u&&g&&(c.openGraph[u]=g)}),i('meta[name^="twitter:"]').each((p,m)=>{let u=i(m).attr("name")?.replace("twitter:",""),g=i(m).attr("content");u&&g&&(c.twitter[u]=g)}),i('script[type="application/ld+json"]').each((p,m)=>{let u=i(m).html();if(u)try{c.jsonLd.push(JSON.parse(u))}catch{}}),JSON.stringify(c,null,2)}var Km,iy,dr,ms=f(()=>{"use strict";l();Km=T(require("cheerio"),1);zm();iy="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";dr={name:Wm,displayName:Gm,description:Bm,parameters:Hm,category:Jm,execute:ay}});var Qm,Ym,Vm,Xm,Zm,ed=f(()=>{"use strict";l();Qm="web.sitemap",Ym="Extract Sitemap",Vm="Parse sitemap.xml or robots.txt to discover all pages on a site. Returns an array of URLs with lastmod/priority if available.",Xm="network",Zm={type:"object",properties:{url:{type:"string",description:"The base URL or direct sitemap.xml / robots.txt URL"},max_urls:{type:"integer",description:"Maximum number of URLs to return (default: 100)",default:100},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function ds(s,e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);try{return await fetch(s,{method:"GET",headers:{"User-Agent":ly},signal:t.signal})}catch(o){throw o.name==="AbortError"?new Error(`Request timed out after ${e}ms`):o}finally{clearTimeout(r)}}async function cy(s){let e=s.url,t=s.max_urls||100,r=s.timeout||3e4;if(!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=e,n=!1;!e.endsWith(".xml")&&!e.endsWith(".txt")&&(o=new URL(e.endsWith("/")?"sitemap.xml":"/sitemap.xml",e).toString(),n=!0);let a;try{a=await ds(o,r),!a.ok&&n&&(o=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),a=await ds(o,r))}catch(p){if(n)o=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),a=await ds(o,r);else throw p}if(!a||!a.ok)throw new Error(`Failed to fetch sitemap or robots.txt from ${e}`);let i=await a.text(),c=[];if(o.endsWith(".xml")||i.trim().startsWith("<")){let p=td.load(i,{xmlMode:!0}),m=p("sitemap > loc");if(m.length>0)return m.each((g,w)=>{c.length>=t||c.push({loc:p(w).text()})}),JSON.stringify({type:"sitemapindex",urls:c},null,2);p("urlset > url").each((g,w)=>{if(c.length>=t)return;let y=p(w);c.push({loc:y.children("loc").text(),lastmod:y.children("lastmod").text()||void 0,priority:y.children("priority").text()||void 0})})}else{let p=i.split(`
70
- `);for(let m of p){if(c.length>=t)break;let u=m.trim();if(u.toLowerCase().startsWith("sitemap:"))c.push({loc:u.substring(8).trim()});else if(u.toLowerCase().startsWith("allow:")){let g=u.substring(6).trim();c.push({loc:new URL(g,o).toString()})}}}return JSON.stringify(c,null,2)}var td,ly,ur,us=f(()=>{"use strict";l();td=T(require("cheerio"),1);ed();ly="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";ur={name:Qm,displayName:Ym,description:Vm,parameters:Zm,category:Xm,execute:cy}});var od,rd,nd,sd,id,ad=f(()=>{"use strict";l();od="web.feed",rd="Extract Feed",nd="Parse RSS/Atom feeds and return structured entries. Requires rss-parser library to be installed.",sd="network",id={type:"object",properties:{url:{type:"string",description:"The URL of the RSS/Atom feed"},max_entries:{type:"integer",description:"Maximum number of entries to return (default: 10)",default:10},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function ld(){try{let s=await import("rss-parser");return new(s.default||s)}catch{throw new Error("rss-parser is not installed. Please install it using `npm install rss-parser` to use this feature.")}}var cd=f(()=>{"use strict";l()});async function py(s){let e=s.url,t=s.max_entries||10,r=s.timeout||3e4;if(!e)throw new Error("url is required");let o=await ld();o.options={...o.options,timeout:r};try{let n=await o.parseURL(e),a=n.items.slice(0,t).map(i=>({title:i.title,link:i.link,published:i.pubDate||i.isoDate,summary:i.contentSnippet||i.content}));return JSON.stringify({feedTitle:n.title,feedDescription:n.description,entries:a},null,2)}catch(n){throw new Error(`Failed to parse feed from ${e}: ${n.message}`)}}var fr,fs=f(()=>{"use strict";l();ad();cd();fr={name:od,displayName:rd,description:nd,parameters:id,category:sd,execute:py}});var pd,md,dd,ud,fd,gd=f(()=>{"use strict";l();pd="web.screenshot",md="Screenshot",dd="Render a page with headless browser and return screenshot Base64 PNG or rendered HTML.",ud="network",fd={type:"object",properties:{url:{type:"string",description:"The URL to capture"},format:{type:"string",description:'Output format: "html" or "png" (default: "html")',enum:["html","png"],default:"html"},viewport:{type:"object",description:"Optional viewport { width, height } (default: { width: 1280, height: 800 })",properties:{width:{type:"integer"},height:{type:"integer"}}},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function hd(){try{let s=await import("puppeteer");return s.default||s}catch{throw new Error("Puppeteer is not installed. Please install it using `npm install puppeteer` to use this feature.")}}var yd=f(()=>{"use strict";l()});async function dy(s){let e=s.url,t=s.format||"html",r=s.viewport,o=s.timeout||3e4;if(!e)throw new Error("url is required");let a=await(await hd()).launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]});try{let i=await a.newPage();if(await i.setUserAgent(my),await i.setViewport({width:r?.width||1280,height:r?.height||800}),await i.goto(e,{waitUntil:"networkidle2",timeout:o}),t==="png"){let c=await i.screenshot({type:"png",fullPage:!0}),p;return Buffer.isBuffer(c)?p=c.toString("base64"):p=Buffer.from(c).toString("base64"),`data:image/png;base64,${p}`}else return await i.content()}finally{await a.close()}}var my,gr,gs=f(()=>{"use strict";l();gd();yd();my="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";gr={name:pd,displayName:md,description:dd,parameters:fd,category:ud,execute:dy}});var wd={};V(wd,{webExtractLinksTool:()=>jt,webFeedTool:()=>fr,webFetchTool:()=>At,webMapTool:()=>mr,webMetadataTool:()=>dr,webScrapeTool:()=>It,webScreenshotTool:()=>gr,webSearchTool:()=>Ot,webSitemapTool:()=>ur,webToolsProject:()=>hs});var hs,ys=f(()=>{"use strict";l();ss();as();ls();cs();ps();ms();us();fs();gs();ss();as();ls();cs();ps();ms();us();fs();gs();hs={manifest:{key:"web",name:"web-tools",displayName:"Web",version:"1.0.0",description:"Web intelligence tools for fetching, searching, scraping, and extracting content from the web.",author:"Sajeer",tools:["web.fetch","web.search","web.scrape","web.extract_links","web.map","web.metadata","web.sitemap","web.feed","web.screenshot"],category:"network"},tools:[At,Ot,It,jt,mr,dr,ur,fr,gr],dependencies:{cheerio:"^1.0.0-rc.12"}}});var bd,xd,Td,Pd,Cd,vd=f(()=>{"use strict";l();bd="coding.find_symbol",xd="Find Symbol",Td="Find function, class, or variable definitions in JavaScript/TypeScript files using AST parsing",Pd="coding",Cd={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find (function, class, variable, etc.)"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["symbol","path"]}});function hr(s){let e=(0,Sd.extname)(s).toLowerCase();return uy[e]||"unknown"}var Sd,uy,ws=f(()=>{"use strict";l();Sd=require("path"),uy={".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"jsx",".ts":"typescript",".tsx":"tsx",".py":"python",".go":"go",".rs":"rust",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".hpp":"cpp",".cc":"cpp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".hs":"haskell",".ex":"elixir",".exs":"elixir",".html":"html",".htm":"html",".css":"css",".json":"json",".yaml":"yaml",".yml":"yaml",".md":"markdown",".sh":"bash",".bash":"bash"}});var je,fe,ve,_d,$d,bs,fy,yr,kd=f(()=>{"use strict";l();je=T(require("web-tree-sitter"),1),fe=T(require("fs"),1),ve=T(require("path"),1),_d=T(require("os"),1),$d=je.default||je.Parser||je,bs=ve.join(_d.homedir(),".toolpack-sdk","grammars"),fy=ve.resolve(__dirname,"../../grammars"),yr=class{grammars=new Map;isInitialized=!1;async init(){this.isInitialized||(await $d.init({locateFile(e,t){return ve.join(__dirname,"../../../../../../node_modules/web-tree-sitter",e)}}),this.isInitialized=!0)}async ensureGrammar(e){await this.init();let t=this.grammars.get(e);if(t)return t;let r=await this.resolveGrammarPath(e),n=await(je.Language||$d.Language).load(r);return this.grammars.set(e,n),n}async resolveGrammarPath(e){let t=`tree-sitter-${e}.wasm`,r=ve.resolve(__dirname,"../../../../../../node_modules/tree-sitter-wasms/out",t);if(fe.existsSync(r))return r;let o=ve.join(fy,t);if(fe.existsSync(o))return o;let n=ve.join(bs,t);return fe.existsSync(n)||await this.downloadGrammar(e,n),n}async downloadGrammar(e,t){fe.existsSync(bs)||fe.mkdirSync(bs,{recursive:!0});let r=`https://unpkg.com/tree-sitter-wasms@latest/out/tree-sitter-${e}.wasm`,o=await fetch(r);if(!o.ok)throw new Error(`Failed to download grammar for ${e}: ${o.statusText}`);let n=await o.arrayBuffer(),a=Buffer.from(n);fe.writeFileSync(t,a)}}});var mo,Rd,Ed,gy,wr,Dd=f(()=>{"use strict";l();mo=T(require("web-tree-sitter"),1),Rd=T(require("fs"),1),Ed=T(require("crypto"),1);ws();kd();gy=mo.default||mo.Parser||mo,wr=class{treeCache=new Map;maxCacheSize=50;parser=null;grammarManager;constructor(){this.grammarManager=new yr}hash(e){return Ed.createHash("md5").update(e).digest("hex")}async getTree(e,t){let r=t!==void 0?t:Rd.readFileSync(e,"utf-8"),o=this.hash(r),n=this.treeCache.get(e),a=hr(e);if(a==="unknown")throw new Error(`Unsupported file type for ${e}`);let i=await this.grammarManager.ensureGrammar(a);if(n&&n.contentHash===o)return n.lastAccessed=Date.now(),{tree:n.tree,language:n.language,grammar:i};this.parser||(await this.grammarManager.init(),this.parser=new gy),this.parser.setLanguage(i);let c;return n?(n.tree&&n.tree.delete(),c=this.parser.parse(r)):c=this.parser.parse(r),this.treeCache.set(e,{tree:c,language:a,contentHash:o,lastAccessed:Date.now()}),this.evictIfNeeded(),{tree:c,language:a,grammar:i}}evictIfNeeded(){if(this.treeCache.size<=this.maxCacheSize)return;let e="",t=1/0;for(let[r,o]of this.treeCache.entries())o.lastAccessed<t&&(t=o.lastAccessed,e=r);if(e){let r=this.treeCache.get(e);r&&r.tree.delete(),this.treeCache.delete(e)}}}});var Nd,xs,se,br,Ad=f(()=>{"use strict";l();Nd=require("@babel/parser"),xs=T(require("@babel/traverse"),1),se=xs.default||xs,br=class{parseCode(e){return(0,Nd.parse)(e,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]})}async findSymbols(e,t,r){let o=[];try{let n=this.parseCode(e.content),a=e.filePath;se(n,{FunctionDeclaration(i){i.node.id?.name===t&&(!r||r==="function")&&o.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"function",name:t})},ClassDeclaration(i){i.node.id?.name===t&&(!r||r==="class")&&o.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"class",name:t})},VariableDeclarator(i){if(i.node.id.type==="Identifier"&&i.node.id.name===t){let c=i.parent,p=c.type==="VariableDeclaration"?c.kind:"variable";(!r||r===p||r==="variable")&&o.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:p,name:t})}},TSInterfaceDeclaration(i){i.node.id.name===t&&(!r||r==="interface")&&o.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"interface",name:t})},TSTypeAliasDeclaration(i){i.node.id.name===t&&(!r||r==="type")&&o.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"type",name:t})}})}catch{}return o}async getSymbols(e,t){let r=[];try{let o=this.parseCode(e.content);se(o,{FunctionDeclaration(n){n.node.id?.name&&(!t||t==="function")&&r.push({name:n.node.id.name,kind:"function",line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})},ClassDeclaration(n){n.node.id?.name&&(!t||t==="class")&&r.push({name:n.node.id.name,kind:"class",line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})},VariableDeclarator(n){if(n.node.id.type==="Identifier"){let a=n.parent,i=a.type==="VariableDeclaration"?a.kind:"variable";(!t||t===i||t==="variable")&&r.push({name:n.node.id.name,kind:i,line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})}},TSInterfaceDeclaration(n){(!t||t==="interface")&&r.push({name:n.node.id.name,kind:"interface",line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})},TSTypeAliasDeclaration(n){(!t||t==="type")&&r.push({name:n.node.id.name,kind:"type",line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})}})}catch(o){throw new Error(`Failed to parse file "${e.filePath}": ${o.message}`)}return r}async getImports(e){let t=[];try{let r=this.parseCode(e.content);se(r,{ImportDeclaration(o){let n=o.node.source.value,a=[],i="side-effect";for(let c of o.node.specifiers)if(c.type==="ImportDefaultSpecifier")a.push(c.local.name),i="default";else if(c.type==="ImportNamespaceSpecifier")a.push(`* as ${c.local.name}`),i="namespace";else if(c.type==="ImportSpecifier"){let p=c.imported.type==="Identifier"?c.imported.name:c.imported.value,m=c.local.name;a.push(p===m?p:`${p} as ${m}`),i="named"}t.push({source:n,imports:a,line:o.node.loc?.start.line||0,type:i})}})}catch(r){throw new Error(`Failed to parse file "${e.filePath}": ${r.message}`)}return t}async findReferences(e,t,r){let o=[];try{let n=e.content,a=n.split(`
71
- `),i=this.parseCode(n);se(i,{Identifier(c){if(c.node.name===t){let p=c.isFunctionDeclaration()||c.isClassDeclaration()||c.parent.type==="VariableDeclarator"&&c.parent.id===c.node||c.parent.type==="TSInterfaceDeclaration"&&c.parent.id===c.node||c.parent.type==="TSTypeAliasDeclaration"&&c.parent.id===c.node;if(!p||r){let m=c.node.loc?.start.line||0,u=c.node.loc?.start.column||0,g=a[m-1]||"";o.push({file:e.filePath,line:m,column:u,context:g.trim(),isDeclaration:p})}}}})}catch{}return o}async getSymbolAtPosition(e,t,r){try{let o=this.parseCode(e.content),n=null;return se(o,{Identifier(a){let i=a.node.loc;i&&i.start.line===t&&i.start.column===r&&(n=a.node.name,a.stop())}}),n}catch{return null}}async getDefinition(e,t){try{let r=this.parseCode(e.content),o=e.filePath,n=null;return se(r,{FunctionDeclaration(a){a.node.id?.name===t&&(n={file:o,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"function",name:t},a.stop())},ClassDeclaration(a){a.node.id?.name===t&&(n={file:o,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"class",name:t},a.stop())},VariableDeclarator(a){if(a.node.id.type==="Identifier"&&a.node.id.name===t){let i=a.parent,c=i.type==="VariableDeclaration"?i.kind:"variable";n={file:o,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:c,name:t},a.stop()}},TSInterfaceDeclaration(a){a.node.id.name===t&&(n={file:o,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"interface",name:t},a.stop())},TSTypeAliasDeclaration(a){a.node.id.name===t&&(n={file:o,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"type",name:t},a.stop())}}),n}catch{return null}}async getDiagnostics(e){try{return this.parseCode(e.content),[]}catch(t){return[{message:t.message,line:t.loc?.line||0,column:t.loc?.column||0,severity:"error"}]}}async getExports(e){let t=[];try{let r=this.parseCode(e.content);se(r,{ExportNamedDeclaration(o){if(o.node.declaration)if(o.node.declaration.type==="VariableDeclaration")for(let n of o.node.declaration.declarations)n.id.type==="Identifier"&&t.push({name:n.id.name,kind:"variable",line:n.loc?.start.line||0,column:n.loc?.start.column||0});else o.node.declaration.type==="FunctionDeclaration"&&o.node.declaration.id?t.push({name:o.node.declaration.id.name,kind:"function",line:o.node.declaration.loc?.start.line||0,column:o.node.declaration.loc?.start.column||0}):o.node.declaration.type==="ClassDeclaration"&&o.node.declaration.id&&t.push({name:o.node.declaration.id.name,kind:"class",line:o.node.declaration.loc?.start.line||0,column:o.node.declaration.loc?.start.column||0});else if(o.node.specifiers)for(let n of o.node.specifiers)n.exported.type==="Identifier"&&t.push({name:n.exported.name,kind:"export",line:n.loc?.start.line||0,column:n.loc?.start.column||0})},ExportDefaultDeclaration(o){let n="default",a="default";o.node.declaration.type==="ClassDeclaration"&&o.node.declaration.id?(n=o.node.declaration.id.name,a="class"):o.node.declaration.type==="FunctionDeclaration"&&o.node.declaration.id?(n=o.node.declaration.id.name,a="function"):o.node.declaration.type==="Identifier"&&(n=o.node.declaration.name,a="variable"),t.push({name:n,kind:a,line:o.node.loc?.start.line||0,column:o.node.loc?.start.column||0})}})}catch{}return t}async getOutline(e){let t=[];try{return(await this.getSymbols(e)).map(o=>({name:o.name,kind:o.kind,line:o.line,column:o.column,children:[]}))}catch{}return t}async extractFunction(e,t,r,o,n,a){let i=e.content.split(`
72
- `),c=Math.max(0,t-1),p=Math.min(i.length,o),m=i.slice(c,p).join(`
69
+ `}return p}var ad,Sy,wr,_s=f(()=>{"use strict";l();ad=x(require("cheerio"),1);id();Sy="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";wr={name:td,displayName:od,description:rd,parameters:sd,category:nd,execute:ky}});var ld,cd,pd,md,dd,ud=f(()=>{"use strict";l();ld="web.metadata",cd="Extract Metadata",pd="Extract Open Graph, Twitter Cards, JSON-LD, and meta tags from a URL.",md="network",dd={type:"object",properties:{url:{type:"string",description:"The URL to extract metadata from"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function _y(n){let e=n.url,t=n.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),s;try{s=await fetch(e,{method:"GET",headers:{"User-Agent":$y},signal:o.signal})}catch(p){throw p.name==="AbortError"?new Error(`Request timed out after ${t}ms`):p}finally{clearTimeout(r)}if(!s.ok)throw new Error(`Failed to fetch ${e}: HTTP ${s.status} ${s.statusText}`);let i=await s.text(),a=fd.load(i),c={title:a("title").text()||"",description:a('meta[name="description"]').attr("content")||a('meta[property="og:description"]').attr("content")||"",author:a('meta[name="author"]').attr("content")||"",openGraph:{},twitter:{},jsonLd:[]};return a('meta[property^="og:"]').each((p,m)=>{let u=a(m).attr("property")?.replace("og:",""),g=a(m).attr("content");u&&g&&(c.openGraph[u]=g)}),a('meta[name^="twitter:"]').each((p,m)=>{let u=a(m).attr("name")?.replace("twitter:",""),g=a(m).attr("content");u&&g&&(c.twitter[u]=g)}),a('script[type="application/ld+json"]').each((p,m)=>{let u=a(m).html();if(u)try{c.jsonLd.push(JSON.parse(u))}catch{}}),JSON.stringify(c,null,2)}var fd,$y,br,Rs=f(()=>{"use strict";l();fd=x(require("cheerio"),1);ud();$y="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";br={name:ld,displayName:cd,description:pd,parameters:dd,category:md,execute:_y}});var gd,hd,yd,wd,bd,xd=f(()=>{"use strict";l();gd="web.sitemap",hd="Extract Sitemap",yd="Parse sitemap.xml or robots.txt to discover all pages on a site. Returns an array of URLs with lastmod/priority if available.",wd="network",bd={type:"object",properties:{url:{type:"string",description:"The base URL or direct sitemap.xml / robots.txt URL"},max_urls:{type:"integer",description:"Maximum number of URLs to return (default: 100)",default:100},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function Ds(n,e){let t=new AbortController,o=setTimeout(()=>t.abort(),e);try{return await fetch(n,{method:"GET",headers:{"User-Agent":Ry},signal:t.signal})}catch(r){throw r.name==="AbortError"?new Error(`Request timed out after ${e}ms`):r}finally{clearTimeout(o)}}async function Dy(n){let e=n.url,t=n.max_urls||100,o=n.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,s=!1;!e.endsWith(".xml")&&!e.endsWith(".txt")&&(r=new URL(e.endsWith("/")?"sitemap.xml":"/sitemap.xml",e).toString(),s=!0);let i;try{i=await Ds(r,o),!i.ok&&s&&(r=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await Ds(r,o))}catch(p){if(s)r=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await Ds(r,o);else throw p}if(!i||!i.ok)throw new Error(`Failed to fetch sitemap or robots.txt from ${e}`);let a=await i.text(),c=[];if(r.endsWith(".xml")||a.trim().startsWith("<")){let p=Td.load(a,{xmlMode:!0}),m=p("sitemap > loc");if(m.length>0)return m.each((g,w)=>{c.length>=t||c.push({loc:p(w).text()})}),JSON.stringify({type:"sitemapindex",urls:c},null,2);p("urlset > url").each((g,w)=>{if(c.length>=t)return;let y=p(w);c.push({loc:y.children("loc").text(),lastmod:y.children("lastmod").text()||void 0,priority:y.children("priority").text()||void 0})})}else{let p=a.split(`
70
+ `);for(let m of p){if(c.length>=t)break;let u=m.trim();if(u.toLowerCase().startsWith("sitemap:"))c.push({loc:u.substring(8).trim()});else if(u.toLowerCase().startsWith("allow:")){let g=u.substring(6).trim();c.push({loc:new URL(g,r).toString()})}}}return JSON.stringify(c,null,2)}var Td,Ry,xr,Es=f(()=>{"use strict";l();Td=x(require("cheerio"),1);xd();Ry="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";xr={name:gd,displayName:hd,description:yd,parameters:bd,category:wd,execute:Dy}});var Pd,Cd,vd,Sd,kd,$d=f(()=>{"use strict";l();Pd="web.feed",Cd="Extract Feed",vd="Parse RSS/Atom feeds and return structured entries. Requires rss-parser library to be installed.",Sd="network",kd={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 _d(){try{let n=await import("rss-parser");return new(n.default||n)}catch{throw new Error("rss-parser is not installed. Please install it using `npm install rss-parser` to use this feature.")}}var Rd=f(()=>{"use strict";l()});async function Ey(n){let e=n.url,t=n.max_entries||10,o=n.timeout||3e4;if(!e)throw new Error("url is required");let r=await _d();r.options={...r.options,timeout:o};try{let s=await r.parseURL(e),i=s.items.slice(0,t).map(a=>({title:a.title,link:a.link,published:a.pubDate||a.isoDate,summary:a.contentSnippet||a.content}));return JSON.stringify({feedTitle:s.title,feedDescription:s.description,entries:i},null,2)}catch(s){throw new Error(`Failed to parse feed from ${e}: ${s.message}`)}}var Tr,Ns=f(()=>{"use strict";l();$d();Rd();Tr={name:Pd,displayName:Cd,description:vd,parameters:kd,category:Sd,execute:Ey}});var Dd,Ed,Nd,Ad,Md,Od=f(()=>{"use strict";l();Dd="web.screenshot",Ed="Screenshot",Nd="Render a page with headless browser and return screenshot Base64 PNG or rendered HTML.",Ad="network",Md={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 Id(){try{let n=await import("puppeteer");return n.default||n}catch{throw new Error("Puppeteer is not installed. Please install it using `npm install puppeteer` to use this feature.")}}var jd=f(()=>{"use strict";l()});async function Ay(n){let e=n.url,t=n.format||"html",o=n.viewport,r=n.timeout||3e4;if(!e)throw new Error("url is required");let i=await(await Id()).launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]});try{let a=await i.newPage();if(await a.setUserAgent(Ny),await a.setViewport({width:o?.width||1280,height:o?.height||800}),await a.goto(e,{waitUntil:"networkidle2",timeout:r}),t==="png"){let c=await a.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 a.content()}finally{await i.close()}}var Ny,Pr,As=f(()=>{"use strict";l();Od();jd();Ny="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Pr={name:Dd,displayName:Ed,description:Nd,parameters:Md,category:Ad,execute:Ay}});var Ld={};Z(Ld,{webExtractLinksTool:()=>Wt,webFeedTool:()=>Tr,webFetchTool:()=>Lt,webMapTool:()=>wr,webMetadataTool:()=>br,webScrapeTool:()=>Ut,webScreenshotTool:()=>Pr,webSearchTool:()=>qt,webSitemapTool:()=>xr,webToolsProject:()=>Ms});var Ms,Os=f(()=>{"use strict";l();Cs();Ss();ks();$s();_s();Rs();Es();Ns();As();Cs();Ss();ks();$s();_s();Rs();Es();Ns();As();Ms={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,qt,Ut,Wt,wr,br,xr,Tr,Pr],dependencies:{cheerio:"^1.0.0-rc.12"}}});var Fd,qd,Ud,Wd,Gd,Bd=f(()=>{"use strict";l();Fd="coding.find_symbol",qd="Find Symbol",Ud="Find function, class, or variable definitions in JavaScript/TypeScript files using AST parsing",Wd="coding",Gd={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find (function, class, variable, etc.)"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["symbol","path"]}});function Cr(n){let e=(0,Kd.extname)(n).toLowerCase();return My[e]||"unknown"}var Kd,My,Is=f(()=>{"use strict";l();Kd=require("path"),My={".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"jsx",".ts":"typescript",".tsx":"tsx",".py":"python",".go":"go",".rs":"rust",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".hpp":"cpp",".cc":"cpp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".hs":"haskell",".ex":"elixir",".exs":"elixir",".html":"html",".htm":"html",".css":"css",".json":"json",".yaml":"yaml",".yml":"yaml",".md":"markdown",".sh":"bash",".bash":"bash"}});var We,ye,_e,Hd,Jd,js,Oy,vr,zd=f(()=>{"use strict";l();We=x(require("web-tree-sitter"),1),ye=x(require("fs"),1),_e=x(require("path"),1),Hd=x(require("os"),1),Jd=We.default||We.Parser||We,js=_e.join(Hd.homedir(),".toolpack-sdk","grammars"),Oy=_e.resolve(__dirname,"../../grammars"),vr=class{grammars=new Map;isInitialized=!1;async init(){this.isInitialized||(await Jd.init({locateFile(e,t){return _e.join(__dirname,"../../../../../../node_modules/web-tree-sitter",e)}}),this.isInitialized=!0)}async ensureGrammar(e){await this.init();let t=this.grammars.get(e);if(t)return t;let o=await this.resolveGrammarPath(e),s=await(We.Language||Jd.Language).load(o);return this.grammars.set(e,s),s}async resolveGrammarPath(e){let t=`tree-sitter-${e}.wasm`,o=_e.resolve(__dirname,"../../../../../../node_modules/tree-sitter-wasms/out",t);if(ye.existsSync(o))return o;let r=_e.join(Oy,t);if(ye.existsSync(r))return r;let s=_e.join(js,t);return ye.existsSync(s)||await this.downloadGrammar(e,s),s}async downloadGrammar(e,t){ye.existsSync(js)||ye.mkdirSync(js,{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 s=await r.arrayBuffer(),i=Buffer.from(s);ye.writeFileSync(t,i)}}});var yo,Qd,Yd,Iy,Sr,Vd=f(()=>{"use strict";l();yo=x(require("web-tree-sitter"),1),Qd=x(require("fs"),1),Yd=x(require("crypto"),1);Is();zd();Iy=yo.default||yo.Parser||yo,Sr=class{treeCache=new Map;maxCacheSize=50;parser=null;grammarManager;constructor(){this.grammarManager=new vr}hash(e){return Yd.createHash("md5").update(e).digest("hex")}async getTree(e,t){let o=t!==void 0?t:Qd.readFileSync(e,"utf-8"),r=this.hash(o),s=this.treeCache.get(e),i=Cr(e);if(i==="unknown")throw new Error(`Unsupported file type for ${e}`);let a=await this.grammarManager.ensureGrammar(i);if(s&&s.contentHash===r)return s.lastAccessed=Date.now(),{tree:s.tree,language:s.language,grammar:a};this.parser||(await this.grammarManager.init(),this.parser=new Iy),this.parser.setLanguage(a);let c;return s?(s.tree&&s.tree.delete(),c=this.parser.parse(o)):c=this.parser.parse(o),this.treeCache.set(e,{tree:c,language:i,contentHash:r,lastAccessed:Date.now()}),this.evictIfNeeded(),{tree:c,language:i,grammar:a}}evictIfNeeded(){if(this.treeCache.size<=this.maxCacheSize)return;let e="",t=1/0;for(let[o,r]of this.treeCache.entries())r.lastAccessed<t&&(t=r.lastAccessed,e=o);if(e){let o=this.treeCache.get(e);o&&o.tree.delete(),this.treeCache.delete(e)}}}});var Xd,Ls,ce,kr,Zd=f(()=>{"use strict";l();Xd=require("@babel/parser"),Ls=x(require("@babel/traverse"),1),ce=Ls.default||Ls,kr=class{parseCode(e){return(0,Xd.parse)(e,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]})}async findSymbols(e,t,o){let r=[];try{let s=this.parseCode(e.content),i=e.filePath;ce(s,{FunctionDeclaration(a){a.node.id?.name===t&&(!o||o==="function")&&r.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"function",name:t})},ClassDeclaration(a){a.node.id?.name===t&&(!o||o==="class")&&r.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"class",name:t})},VariableDeclarator(a){if(a.node.id.type==="Identifier"&&a.node.id.name===t){let c=a.parent,p=c.type==="VariableDeclaration"?c.kind:"variable";(!o||o===p||o==="variable")&&r.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:p,name:t})}},TSInterfaceDeclaration(a){a.node.id.name===t&&(!o||o==="interface")&&r.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"interface",name:t})},TSTypeAliasDeclaration(a){a.node.id.name===t&&(!o||o==="type")&&r.push({file:i,line:a.node.loc?.start.line||0,column:a.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);ce(r,{FunctionDeclaration(s){s.node.id?.name&&(!t||t==="function")&&o.push({name:s.node.id.name,kind:"function",line:s.node.loc?.start.line||0,column:s.node.loc?.start.column||0})},ClassDeclaration(s){s.node.id?.name&&(!t||t==="class")&&o.push({name:s.node.id.name,kind:"class",line:s.node.loc?.start.line||0,column:s.node.loc?.start.column||0})},VariableDeclarator(s){if(s.node.id.type==="Identifier"){let i=s.parent,a=i.type==="VariableDeclaration"?i.kind:"variable";(!t||t===a||t==="variable")&&o.push({name:s.node.id.name,kind:a,line:s.node.loc?.start.line||0,column:s.node.loc?.start.column||0})}},TSInterfaceDeclaration(s){(!t||t==="interface")&&o.push({name:s.node.id.name,kind:"interface",line:s.node.loc?.start.line||0,column:s.node.loc?.start.column||0})},TSTypeAliasDeclaration(s){(!t||t==="type")&&o.push({name:s.node.id.name,kind:"type",line:s.node.loc?.start.line||0,column:s.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);ce(o,{ImportDeclaration(r){let s=r.node.source.value,i=[],a="side-effect";for(let c of r.node.specifiers)if(c.type==="ImportDefaultSpecifier")i.push(c.local.name),a="default";else if(c.type==="ImportNamespaceSpecifier")i.push(`* as ${c.local.name}`),a="namespace";else if(c.type==="ImportSpecifier"){let p=c.imported.type==="Identifier"?c.imported.name:c.imported.value,m=c.local.name;i.push(p===m?p:`${p} as ${m}`),a="named"}t.push({source:s,imports:i,line:r.node.loc?.start.line||0,type:a})}})}catch(o){throw new Error(`Failed to parse file "${e.filePath}": ${o.message}`)}return t}async findReferences(e,t,o){let r=[];try{let s=e.content,i=s.split(`
71
+ `),a=this.parseCode(s);ce(a,{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,u=c.node.loc?.start.column||0,g=i[m-1]||"";r.push({file:e.filePath,line:m,column:u,context:g.trim(),isDeclaration:p})}}}})}catch{}return r}async getSymbolAtPosition(e,t,o){try{let r=this.parseCode(e.content),s=null;return ce(r,{Identifier(i){let a=i.node.loc;a&&a.start.line===t&&a.start.column===o&&(s=i.node.name,i.stop())}}),s}catch{return null}}async getDefinition(e,t){try{let o=this.parseCode(e.content),r=e.filePath,s=null;return ce(o,{FunctionDeclaration(i){i.node.id?.name===t&&(s={file:r,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"function",name:t},i.stop())},ClassDeclaration(i){i.node.id?.name===t&&(s={file:r,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"class",name:t},i.stop())},VariableDeclarator(i){if(i.node.id.type==="Identifier"&&i.node.id.name===t){let a=i.parent,c=a.type==="VariableDeclaration"?a.kind:"variable";s={file:r,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:c,name:t},i.stop()}},TSInterfaceDeclaration(i){i.node.id.name===t&&(s={file:r,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"interface",name:t},i.stop())},TSTypeAliasDeclaration(i){i.node.id.name===t&&(s={file:r,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"type",name:t},i.stop())}}),s}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);ce(o,{ExportNamedDeclaration(r){if(r.node.declaration)if(r.node.declaration.type==="VariableDeclaration")for(let s of r.node.declaration.declarations)s.id.type==="Identifier"&&t.push({name:s.id.name,kind:"variable",line:s.loc?.start.line||0,column:s.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 s of r.node.specifiers)s.exported.type==="Identifier"&&t.push({name:s.exported.name,kind:"export",line:s.loc?.start.line||0,column:s.loc?.start.column||0})},ExportDefaultDeclaration(r){let s="default",i="default";r.node.declaration.type==="ClassDeclaration"&&r.node.declaration.id?(s=r.node.declaration.id.name,i="class"):r.node.declaration.type==="FunctionDeclaration"&&r.node.declaration.id?(s=r.node.declaration.id.name,i="function"):r.node.declaration.type==="Identifier"&&(s=r.node.declaration.name,i="variable"),t.push({name:s,kind:i,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,s,i){let a=e.content.split(`
72
+ `),c=Math.max(0,t-1),p=Math.min(a.length,r),m=a.slice(c,p).join(`
73
73
  `),u=`
74
- function ${a}() {
74
+ function ${i}() {
75
75
  ${m}
76
76
  }
77
- `,g=`${a}();`;return{newFunction:u,replacementCall:g}}async getCallHierarchy(e,t,r){try{let o=this.parseCode(e.content),n=e.filePath,a=null,i="",c=0,p=0;if(se(o,{Function(y){let b=y.node.loc;b&&b.start.line<=t&&b.end&&b.end.line>=t&&(a=y,c=b.start.line,p=b.start.column,y.node.type==="FunctionDeclaration"&&y.node.id?i=y.node.id.name:y.parent.type==="VariableDeclarator"&&y.parent.id.type==="Identifier"?i=y.parent.id.name:y.parent.type==="ClassMethod"||y.parent.type==="ObjectMethod"?y.parent.key.type==="Identifier"&&(i=y.parent.key.name):i="<anonymous>")}}),!a||i==="<anonymous>")return null;let m=[],u=[];se(o,{CallExpression(y){let b=y.node.loc;if(!b||b.start.line<c||b.end&&b.end.line>c+1e3)return;let P=!1,$=y;for(;$;){if($.isFunction()&&$.node.type==="FunctionDeclaration"&&$.node.id?.name===i){P=!0;break}$=$.parentPath}if(!P)return;let C=y.node.callee,x="<unknown>";C.type==="Identifier"?x=C.name:C.type==="MemberExpression"&&C.property.type==="Identifier"&&(x=C.property.name),x!=="<unknown>"&&u.push({file:n,name:x,line:y.node.loc?.start.line||0,column:y.node.loc?.start.column||0})}}),se(o,{CallExpression(y){let b=y.node.callee,P=!1;if((b.type==="Identifier"&&b.name===i||b.type==="MemberExpression"&&b.property.type==="Identifier"&&b.property.name===i)&&(P=!0),P){let $="<global>",C=y;for(;C;){if(C.isFunction()){C.node.type==="FunctionDeclaration"&&C.node.id?$=C.node.id.name:C.parent.type==="VariableDeclarator"&&C.parent.id.type==="Identifier"?$=C.parent.id.name:(C.parent.type==="ClassMethod"||C.parent.type==="ObjectMethod")&&C.parent.key.type==="Identifier"&&($=C.parent.key.name);break}C=C.parentPath}m.push({file:n,name:$,line:y.node.loc?.start.line||0,column:y.node.loc?.start.column||0})}}});let g=[...new Map(m.map(y=>[`${y.name}:${y.line}`,y])).values()],w=[...new Map(u.map(y=>[`${y.name}:${y.line}`,y])).values()];return{file:n,name:i,line:c,column:p,callers:g,callees:w}}catch{return null}}}});var Md,Od=f(()=>{"use strict";l();Md={}});var xr,Id=f(()=>{"use strict";l();Od();xr=class{constructor(e){this.context=e}context;async executeQuery(e,t){let{tree:r,language:o,grammar:n}=await this.context.getTree(e.filePath,e.content),a=Md[o];if(!a||!a[t])throw new Error(`Query ${t} not found for language ${o}`);let i=a[t],c=n.query(i);return{tree:r,captures:c.captures(r.rootNode)}}async findSymbols(e,t,r){return(await this.getSymbols(e,r)).filter(n=>n.name===t).map(n=>({file:e.filePath,line:n.line,column:n.column,kind:n.kind,name:n.name}))}async getSymbols(e,t){let{captures:r}=await this.executeQuery(e,"symbols"),o=[];for(let n of r)if(n.name.startsWith("name.")){let a=n.name.split(".")[1];(!t||t===a)&&o.push({name:n.node.text,kind:a,line:n.node.startPosition.row+1,column:n.node.startPosition.column})}return o}async getImports(e){let{captures:t}=await this.executeQuery(e,"imports"),r=t.filter(n=>n.name==="import").map(n=>n.node),o=[];for(let n of r)o.push({source:n.text,imports:[n.text],line:n.startPosition.row+1,type:"side-effect"});return o}async findReferences(e,t,r){let{captures:o}=await this.executeQuery(e,"references"),n=e.content.split(`
78
- `),a=[];for(let i of o)if(i.node.text===t){let c=i.node.parent?.type.includes("definition")||i.node.parent?.type.includes("declaration");if(!c||r){let p=i.node.startPosition.row+1;a.push({file:e.filePath,line:p,column:i.node.startPosition.column,context:n[p-1].trim(),isDeclaration:!!c})}}return a}async getSymbolAtPosition(e,t,r){let{tree:o}=await this.context.getTree(e.filePath,e.content),n=o.rootNode.descendantForPosition({row:t-1,column:r});return n&&n.type==="identifier"?n.text:null}async getDefinition(e,t){let r=await this.findSymbols(e,t);return r.length>0?r[0]:null}async getDiagnostics(e){let{tree:t}=await this.context.getTree(e.filePath,e.content),r=[];function o(n){if(n.hasError()){n.type==="ERROR"&&r.push({message:`Syntax error at line ${n.startPosition.row+1}`,line:n.startPosition.row+1,column:n.startPosition.column,severity:"error"});for(let a of n.children)o(a)}else n.isMissing&&n.isMissing()&&r.push({message:`Missing ${n.type} at line ${n.startPosition.row+1}`,line:n.startPosition.row+1,column:n.startPosition.column,severity:"error"})}return o(t.rootNode),r}async getExports(e){return[]}async getOutline(e){return(await this.getSymbols(e)).map(r=>({name:r.name,kind:r.kind,line:r.line,column:r.column,children:[]}))}async extractFunction(e,t,r,o,n,a){let i=e.content.split(`
79
- `),c=Math.max(0,t-1),p=Math.min(i.length,o),m=i.slice(c,p).join(`
77
+ `,g=`${i}();`;return{newFunction:u,replacementCall:g}}async getCallHierarchy(e,t,o){try{let r=this.parseCode(e.content),s=e.filePath,i=null,a="",c=0,p=0;if(ce(r,{Function(y){let b=y.node.loc;b&&b.start.line<=t&&b.end&&b.end.line>=t&&(i=y,c=b.start.line,p=b.start.column,y.node.type==="FunctionDeclaration"&&y.node.id?a=y.node.id.name:y.parent.type==="VariableDeclarator"&&y.parent.id.type==="Identifier"?a=y.parent.id.name:y.parent.type==="ClassMethod"||y.parent.type==="ObjectMethod"?y.parent.key.type==="Identifier"&&(a=y.parent.key.name):a="<anonymous>")}}),!i||a==="<anonymous>")return null;let m=[],u=[];ce(r,{CallExpression(y){let b=y.node.loc;if(!b||b.start.line<c||b.end&&b.end.line>c+1e3)return;let T=!1,k=y;for(;k;){if(k.isFunction()&&k.node.type==="FunctionDeclaration"&&k.node.id?.name===a){T=!0;break}k=k.parentPath}if(!T)return;let C=y.node.callee,P="<unknown>";C.type==="Identifier"?P=C.name:C.type==="MemberExpression"&&C.property.type==="Identifier"&&(P=C.property.name),P!=="<unknown>"&&u.push({file:s,name:P,line:y.node.loc?.start.line||0,column:y.node.loc?.start.column||0})}}),ce(r,{CallExpression(y){let b=y.node.callee,T=!1;if((b.type==="Identifier"&&b.name===a||b.type==="MemberExpression"&&b.property.type==="Identifier"&&b.property.name===a)&&(T=!0),T){let k="<global>",C=y;for(;C;){if(C.isFunction()){C.node.type==="FunctionDeclaration"&&C.node.id?k=C.node.id.name:C.parent.type==="VariableDeclarator"&&C.parent.id.type==="Identifier"?k=C.parent.id.name:(C.parent.type==="ClassMethod"||C.parent.type==="ObjectMethod")&&C.parent.key.type==="Identifier"&&(k=C.parent.key.name);break}C=C.parentPath}m.push({file:s,name:k,line:y.node.loc?.start.line||0,column:y.node.loc?.start.column||0})}}});let g=[...new Map(m.map(y=>[`${y.name}:${y.line}`,y])).values()],w=[...new Map(u.map(y=>[`${y.name}:${y.line}`,y])).values()];return{file:s,name:a,line:c,column:p,callers:g,callees:w}}catch{return null}}}});var eu,tu=f(()=>{"use strict";l();eu={}});var $r,ou=f(()=>{"use strict";l();tu();$r=class{constructor(e){this.context=e}context;async executeQuery(e,t){let{tree:o,language:r,grammar:s}=await this.context.getTree(e.filePath,e.content),i=eu[r];if(!i||!i[t])throw new Error(`Query ${t} not found for language ${r}`);let a=i[t],c=s.query(a);return{tree:o,captures:c.captures(o.rootNode)}}async findSymbols(e,t,o){return(await this.getSymbols(e,o)).filter(s=>s.name===t).map(s=>({file:e.filePath,line:s.line,column:s.column,kind:s.kind,name:s.name}))}async getSymbols(e,t){let{captures:o}=await this.executeQuery(e,"symbols"),r=[];for(let s of o)if(s.name.startsWith("name.")){let i=s.name.split(".")[1];(!t||t===i)&&r.push({name:s.node.text,kind:i,line:s.node.startPosition.row+1,column:s.node.startPosition.column})}return r}async getImports(e){let{captures:t}=await this.executeQuery(e,"imports"),o=t.filter(s=>s.name==="import").map(s=>s.node),r=[];for(let s of o)r.push({source:s.text,imports:[s.text],line:s.startPosition.row+1,type:"side-effect"});return r}async findReferences(e,t,o){let{captures:r}=await this.executeQuery(e,"references"),s=e.content.split(`
78
+ `),i=[];for(let a of r)if(a.node.text===t){let c=a.node.parent?.type.includes("definition")||a.node.parent?.type.includes("declaration");if(!c||o){let p=a.node.startPosition.row+1;i.push({file:e.filePath,line:p,column:a.node.startPosition.column,context:s[p-1].trim(),isDeclaration:!!c})}}return i}async getSymbolAtPosition(e,t,o){let{tree:r}=await this.context.getTree(e.filePath,e.content),s=r.rootNode.descendantForPosition({row:t-1,column:o});return s&&s.type==="identifier"?s.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(s){if(s.hasError()){s.type==="ERROR"&&o.push({message:`Syntax error at line ${s.startPosition.row+1}`,line:s.startPosition.row+1,column:s.startPosition.column,severity:"error"});for(let i of s.children)r(i)}else s.isMissing&&s.isMissing()&&o.push({message:`Missing ${s.type} at line ${s.startPosition.row+1}`,line:s.startPosition.row+1,column:s.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,s,i){let a=e.content.split(`
79
+ `),c=Math.max(0,t-1),p=Math.min(a.length,r),m=a.slice(c,p).join(`
80
80
  `),u="",g="",w=e.filePath.split(".").pop()?.toLowerCase();return w==="py"||w==="pyi"?(u=`
81
- def ${a}():
81
+ def ${i}():
82
82
  ${m.split(`
83
83
  `).map(y=>" "+y).join(`
84
84
  `)}
85
- `,g=`${a}()`):w==="go"?(u=`
86
- func ${a}() {
85
+ `,g=`${i}()`):w==="go"?(u=`
86
+ func ${i}() {
87
87
  ${m}
88
88
  }
89
- `,g=`${a}()`):w==="rs"?(u=`
90
- fn ${a}() {
89
+ `,g=`${i}()`):w==="rs"?(u=`
90
+ fn ${i}() {
91
91
  ${m}
92
92
  }
93
- `,g=`${a}();`):w==="sh"||w==="bash"?(u=`
94
- ${a}() {
93
+ `,g=`${i}();`):w==="sh"||w==="bash"?(u=`
94
+ ${i}() {
95
95
  ${m}
96
96
  }
97
- `,g=`${a}`):(u=`
98
- void ${a}() {
97
+ `,g=`${i}`):(u=`
98
+ void ${i}() {
99
99
  ${m}
100
100
  }
101
- `,g=`${a}();`),{newFunction:u,replacementCall:g}}async getCallHierarchy(e,t,r){let o=await this.getSymbolAtPosition(e,t,r);if(!o)return null;let a=(await this.findReferences(e,o,!1)).map(i=>({file:i.file,name:i.context.trim()||"<anonymous>",line:i.line,column:i.column}));return{file:e.filePath,name:o,line:t,column:r,callers:a,callees:[]}}}});var Tr,jd=f(()=>{"use strict";l();ws();Ad();Id();Tr=class{constructor(e){this.context=e;this.babelParser=new br,this.treeSitterParser=new xr(this.context)}context;babelParser;treeSitterParser;getParser(e){switch(hr(e)){case"javascript":case"typescript":case"tsx":case"jsx":return this.babelParser;case"python":case"go":case"rust":case"java":case"c":case"cpp":return this.treeSitterParser;default:throw new Error(`Unsupported or unknown language for file: ${e}`)}}}});var Ft,Cr,Pr,Fd=f(()=>{"use strict";l();Ft=require("fs"),Cr=require("path");Z();Pr=class{isBuilt=!1;isBuilding=!1;data={symbolLocations:new Map};fileMtimes=new Map;supportedExtensions=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];async getAllSupportedFiles(e){let t=[];try{let r=(0,Ft.readdirSync)(e,{withFileTypes:!0});for(let o of r){let n=(0,Cr.join)(e,o.name);o.name==="node_modules"||o.name===".git"||o.name==="dist"||o.name==="build"||(o.isDirectory()?t.push(...await this.getAllSupportedFiles(n)):o.isFile()&&this.supportedExtensions.includes((0,Cr.extname)(o.name).toLowerCase())&&t.push(n))}}catch{}return t}async buildIndex(e){if(!(this.isBuilt||this.isBuilding)){this.isBuilding=!0;try{let t=await this.getAllSupportedFiles(e);for(let r of t)await this.updateFile(r);this.isBuilt=!0}finally{this.isBuilding=!1}}}async updateFile(e){try{let r=(0,Ft.statSync)(e).mtimeMs;if(this.fileMtimes.get(e)===r)return;let o=(0,Ft.readFileSync)(e,"utf-8"),n=M.getParser(e);this.removeFileFromIndex(e);let a=await n.getSymbols({filePath:e,content:o});for(let i of a){let c=this.data.symbolLocations.get(i.name);c?c.add(e):this.data.symbolLocations.set(i.name,new Set([e]))}this.fileMtimes.set(e,r)}catch{this.removeFileFromIndex(e)}}removeFileFromIndex(e){for(let[t,r]of this.data.symbolLocations.entries())r.delete(e),r.size===0&&this.data.symbolLocations.delete(t);this.fileMtimes.delete(e)}async getDefinitionFiles(e,t){await this.buildIndex(t);let r=this.data.symbolLocations.get(e);return r?Array.from(r):[]}}});var hy,M,Lt,Z=f(()=>{"use strict";l();Dd();jd();Fd();hy=new wr,M=new Tr(hy),Lt=new Pr});async function Ld(s,e,t){try{let r=(0,qt.readFileSync)(s,"utf-8");return await M.getParser(s).findSymbols({filePath:s,content:r},e,t)}catch{return[]}}async function qd(s,e,t){let r=[];try{let o=(0,qt.readdirSync)(s,{withFileTypes:!0});for(let n of o){let a=(0,vr.join)(s,n.name);if(!(n.name==="node_modules"||n.name===".git"||n.name==="dist")){if(n.isDirectory()){let i=await qd(a,e,t);r.push(...i)}else if(n.isFile()&&yy.includes((0,vr.extname)(n.name))){let i=await Ld(a,e,t);r.push(...i)}}}}catch{}return r}async function wy(s){let e=s.symbol,t=s.path,r=s.kind;if(h(`[coding.find-symbol] execute symbol="${e}" path="${t}" kind=${r??"all"}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let o=(0,qt.statSync)(t),n;if(o.isDirectory())n=await qd(t,e,r);else if(o.isFile())n=await Ld(t,e,r);else throw new Error(`Path is neither a file nor directory: ${t}`);return JSON.stringify({symbol:e,found:n.length,locations:n},null,2)}var qt,vr,yy,Ut,Ts=f(()=>{"use strict";l();qt=require("fs"),vr=require("path");vd();Z();k();yy=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];Ut={name:bd,displayName:xd,description:Td,parameters:Cd,category:Pd,execute:wy}});var Ud,Wd,Gd,Bd,Jd,Hd=f(()=>{"use strict";l();Ud="coding.get_symbols",Wd="Get Symbols",Gd="List all symbols (functions, classes, variables, etc.) in a JavaScript/TypeScript file",Bd="coding",Jd={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["file"]}});async function by(s){let e=s.file,t=s.kind;if(h(`[coding.get-symbols] execute file="${e}" kind=${t??"all"}`),!e)throw new Error("file is required");try{let r=(0,zd.readFileSync)(e,"utf-8"),n=await M.getParser(e).getSymbols({filePath:e,content:r},t);return JSON.stringify({file:e,count:n.length,symbols:n},null,2)}catch(r){throw new Error(`Failed to parse file "${e}": ${r.message}`)}}var zd,Wt,Ps=f(()=>{"use strict";l();zd=require("fs");Hd();Z();k();Wt={name:Ud,displayName:Wd,description:Gd,parameters:Jd,category:Bd,execute:by}});var Kd,Qd,Yd,Vd,Xd,Zd=f(()=>{"use strict";l();Kd="coding.get_imports",Qd="Get Imports",Yd="List all import statements in a JavaScript/TypeScript file",Vd="coding",Xd={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"}},required:["file"]}});async function xy(s){let e=s.file;if(h(`[coding.get-imports] execute file="${e}"`),!e)throw new Error("file is required");try{let t=(0,eu.readFileSync)(e,"utf-8"),o=await M.getParser(e).getImports({filePath:e,content:t});return JSON.stringify({file:e,count:o.length,imports:o},null,2)}catch(t){throw new Error(`Failed to map explicit imports in file "${e}": ${t.message}`)}}var eu,Gt,Cs=f(()=>{"use strict";l();eu=require("fs");Zd();Z();k();Gt={name:Kd,displayName:Qd,description:Yd,parameters:Xd,category:Vd,execute:xy}});var tu,ou,ru,nu,su,iu=f(()=>{"use strict";l();tu="coding.find_references",ou="Find References",ru="Find all references to a symbol across JavaScript/TypeScript files",nu="coding",su={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find references for"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},includeDeclaration:{type:"boolean",description:"Include the symbol declaration in results (default: false)"}},required:["symbol","path"]}});async function au(s,e,t){try{let r=(0,Sr.readFileSync)(s,"utf-8");return await M.getParser(s).findReferences({filePath:s,content:r},e,t)}catch{return[]}}async function Ty(s,e,t){let r=[];await Lt.buildIndex(s);let o=await Lt.getDefinitionFiles(e,s);for(let n of o)if(n.startsWith(s)){let a=await au(n,e,t);r.push(...a)}return r}async function Py(s){let e=s.symbol,t=s.path,r=s.includeDeclaration===!0;if(h(`[coding.find-references] execute symbol="${e}" path="${t}" includeDecl=${r}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let o=(0,Sr.statSync)(t),n;if(o.isDirectory())n=await Ty(t,e,r);else if(o.isFile())n=await au(t,e,r);else throw new Error(`Path is neither a file nor directory: ${t}`);return JSON.stringify({symbol:e,found:n.length,references:n},null,2)}var Sr,$r,vs=f(()=>{"use strict";l();Sr=require("fs");iu();Z();k();$r={name:tu,displayName:ou,description:ru,parameters:su,category:nu,execute:Py}});var lu,cu,pu,mu,du,uu=f(()=>{"use strict";l();lu="coding.go_to_definition",cu="Go To Definition",pu="Jump to the definition of a symbol at a specific location in a file",mu="coding",du={type:"object",properties:{file:{type:"string",description:"Path to the file containing the symbol reference"},line:{type:"integer",description:"Line number where the symbol is referenced (1-indexed)"},column:{type:"integer",description:"Column number where the symbol is referenced (0-indexed)"},searchPath:{type:"string",description:"Optional: directory to search for the definition (defaults to file directory)"}},required:["file","line","column"]}});async function Cy(s,e,t){try{let r=(0,uo.readFileSync)(s,"utf-8");return await M.getParser(s).getSymbolAtPosition({filePath:s,content:r},e,t)}catch{return null}}async function gu(s,e){try{let t=(0,uo.readFileSync)(s,"utf-8");return await M.getParser(s).getDefinition({filePath:s,content:t},e)}catch{return null}}async function vy(s,e){await Lt.buildIndex(s);let t=await Lt.getDefinitionFiles(e,s);for(let r of t)if(r.startsWith(s)){let o=await gu(r,e);if(o)return o}return null}async function Sy(s){let e=s.file,t=s.line,r=s.column,o=s.searchPath;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("line is required");if(r===void 0)throw new Error("column is required");let n=await Cy(e,t,r);if(!n)return JSON.stringify({found:!1,message:`No symbol found at ${e}:${t}:${r}`},null,2);let a=await gu(e,n);if(!a){let i=o||(0,fu.dirname)(e);(0,uo.statSync)(i).isDirectory()&&(a=await vy(i,n))}return JSON.stringify(a?{found:!0,symbol:n,definition:a}:{found:!1,symbol:n,message:`Definition not found for symbol "${n}"`},null,2)}var uo,fu,_r,Ss=f(()=>{"use strict";l();uo=require("fs"),fu=require("path");uu();Z();_r={name:lu,displayName:cu,description:pu,parameters:du,category:mu,execute:Sy}});var hu,yu,wu,bu,xu,Tu=f(()=>{"use strict";l();hu="coding.multi_file_edit",yu="Multi-File Edit",wu="Edit multiple files atomically with rollback on failure",bu="coding",xu={type:"object",properties:{edits:{type:"array",items:{type:"object",properties:{file:{type:"string"},changes:{type:"array",items:{type:"object",properties:{oldText:{type:"string"},newText:{type:"string"}}}}}},description:"Array of file edits, each with file path and array of text replacements"},atomic:{type:"boolean",description:"Atomic mode: rollback all edits if any fails (default: true)"}},required:["edits"]}});async function $y(s){let e=s.edits,t=s.atomic!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("edits array is required and must not be empty");for(let n of e){if(!n.file)throw new Error("Each edit must have a file property");if(!n.changes||!Array.isArray(n.changes))throw new Error("Each edit must have a changes array");if(!(0,Fe.existsSync)(n.file))throw new Error(`File does not exist: ${n.file}`)}let r=[],o=[];try{for(let n of e){let a=(0,Fe.readFileSync)(n.file,"utf-8");t&&r.push({file:n.file,content:a});let i=a;for(let c of n.changes){if(!c.oldText)throw new Error("Each change must have oldText property");if(c.newText===void 0)throw new Error("Each change must have newText property");let p=(i.match(new RegExp(_y(c.oldText),"g"))||[]).length;if(p===0)throw new Error(`Text not found in ${n.file}: "${c.oldText.substring(0,50)}..."`);if(p>1)throw new Error(`Ambiguous replacement in ${n.file}: "${c.oldText.substring(0,50)}..." appears ${p} times`);i=i.replace(c.oldText,c.newText)}(0,Fe.writeFileSync)(n.file,i,"utf-8"),o.push(n.file)}return JSON.stringify({success:!0,filesModified:o.length,files:o},null,2)}catch(n){if(t&&r.length>0){for(let a of r)try{(0,Fe.writeFileSync)(a.file,a.content,"utf-8")}catch{}throw new Error(`Multi-file edit failed and rolled back: ${n.message}`)}throw new Error(`Multi-file edit failed: ${n.message}`)}}function _y(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Fe,kr,$s=f(()=>{"use strict";l();Fe=require("fs");Tu();kr={name:hu,displayName:yu,description:wu,parameters:xu,category:bu,execute:$y}});var Pu,Cu,vu,Su,$u,_u=f(()=>{"use strict";l();Pu="coding.refactor_rename",Cu="Refactor Rename",vu="Rename a symbol across the entire codebase intelligently",Su="coding",$u={type:"object",properties:{symbol:{type:"string",description:"Current name of the symbol to rename"},newName:{type:"string",description:"New name for the symbol"},path:{type:"string",description:"Directory path to search and rename in"},dryRun:{type:"boolean",description:"Preview changes without applying them (default: false)"}},required:["symbol","newName","path"]}});function Ey(s,e,t,r){let o=[];try{let n=(0,Bt.readFileSync)(s,"utf-8"),a=n.split(`
102
- `),i=(0,ku.parse)(n,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]}),c=[];if(ky(i,{Identifier(p){if(p.node.name===e){let m=p.node.loc?.start.line||0,u=p.node.loc?.start.column||0;c.push({line:m,column:u,length:e.length}),o.push({file:s,line:m,column:u,oldName:e,newName:t})}}}),!r&&c.length>0){c.sort((m,u)=>m.line!==u.line?u.line-m.line:u.column-m.column);let p=[...a];for(let m of c){let u=m.line-1;if(u>=0&&u<p.length){let g=p[u],w=g.substring(0,m.column),y=g.substring(m.column+m.length);p[u]=w+t+y}}(0,Bt.writeFileSync)(s,p.join(`
103
- `),"utf-8")}}catch{}return{file:s,occurrences:o.length,changes:o}}function Ru(s,e,t,r){let o=[];try{let n=(0,Bt.readdirSync)(s,{withFileTypes:!0});for(let a of n){let i=(0,Rr.join)(s,a.name);if(!(a.name==="node_modules"||a.name===".git"||a.name==="dist")){if(a.isDirectory())o.push(...Ru(i,e,t,r));else if(a.isFile()&&Ry.includes((0,Rr.extname)(a.name))){let c=Ey(i,e,t,r);c.occurrences>0&&o.push(c)}}}}catch{}return o}async function Dy(s){let e=s.symbol,t=s.newName,r=s.path,o=s.dryRun===!0;if(!e)throw new Error("symbol is required");if(!t)throw new Error("newName is required");if(!r)throw new Error("path is required");if(e===t)throw new Error("New name must be different from old name");let n=Ru(r,e,t,o),a=n.reduce((c,p)=>c+p.occurrences,0),i=n.length;return JSON.stringify({success:!0,dryRun:o,oldName:e,newName:t,filesAffected:i,totalOccurrences:a,changes:n},null,2)}var Bt,Rr,ku,_s,ky,Ry,Er,ks=f(()=>{"use strict";l();Bt=require("fs"),Rr=require("path"),ku=require("@babel/parser"),_s=T(require("@babel/traverse"),1);_u();ky=_s.default||_s,Ry=[".js",".jsx",".ts",".tsx",".mjs",".cjs"];Er={name:Pu,displayName:Cu,description:vu,parameters:$u,category:Su,execute:Dy}});var Eu,Du,Nu,Au,Mu,Ou=f(()=>{"use strict";l();Eu="coding.get_outline",Du="Get File Outline",Nu="Gets a hierarchical outline of symbols (classes, functions, methods) in a specified file.",Au="coding",Mu={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to outline"}},required:["file"]}});async function Ny(s){let e=s.file;if(h(`[coding.get-outline] execute file="${e}"`),!e)throw new Error("file is required");try{if(!(0,Dr.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,Dr.readFileSync)(e,"utf-8"),r=M.getParser(e);if(!r.getOutline)return JSON.stringify({file:e,error:"Outline extraction is not specifically implemented for this language yet."});let o=await r.getOutline({filePath:e,content:t});return JSON.stringify({file:e,outline:o},null,2)}catch(t){throw new Error(`Failed to safely extract outline from file "${e}": ${t.message}`)}}var Dr,Nr,Rs=f(()=>{"use strict";l();Dr=require("fs");Ou();Z();k();Nr={name:Eu,displayName:Du,description:Nu,parameters:Mu,category:Au,execute:Ny}});var Iu,ju,Fu,Lu,qu,Uu=f(()=>{"use strict";l();Iu="coding.get_diagnostics",ju="Get File Diagnostics",Fu="Gets syntax errors and warnings for a file utilizing AST parsing.",Lu="coding",qu={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to check for diagnostics"}},required:["file"]}});async function Ay(s){let e=s.file;if(!e)throw new Error("file is required");try{if(!(0,Ar.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,Ar.readFileSync)(e,"utf-8"),r=M.getParser(e);if(!r.getDiagnostics)return JSON.stringify({file:e,error:"Diagnostics extraction is not specifically implemented for this language yet."});let o=await r.getDiagnostics({filePath:e,content:t});return JSON.stringify({file:e,diagnostics:o},null,2)}catch(t){throw new Error(`Failed to get diagnostics from file "${e}": ${t.message}`)}}var Ar,Mr,Es=f(()=>{"use strict";l();Ar=require("fs");Uu();Z();Mr={name:Iu,displayName:ju,description:Fu,parameters:qu,category:Lu,execute:Ay}});var Wu,Gu,Bu,Ju,Hu,zu=f(()=>{"use strict";l();Wu="coding.get_exports",Gu="Get File Exports",Bu="Lists all symbols exported by a file.",Ju="coding",Hu={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"}},required:["file"]}});async function My(s){let e=s.file;if(h(`[coding.get-exports] execute file="${e}"`),!e)throw new Error("file is required");try{if(!(0,Or.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,Or.readFileSync)(e,"utf-8"),r=M.getParser(e);if(!r.getExports)return JSON.stringify({file:e,error:"Exports extraction is not specifically implemented for this language yet."});let o=await r.getExports({filePath:e,content:t});return JSON.stringify({file:e,exports:o},null,2)}catch(t){throw new Error(`Failed to extract exports from file "${e}": ${t.message}`)}}var Or,Ir,Ds=f(()=>{"use strict";l();Or=require("fs");zu();Z();k();Ir={name:Wu,displayName:Gu,description:Bu,parameters:Hu,category:Ju,execute:My}});var Ku,Qu,Yu,Vu,Xu,Zu=f(()=>{"use strict";l();Ku="coding.extract_function",Qu="Extract Function",Yu="Extracts a selected code region into a new function, automatically detecting required parameters and return values.",Vu="coding",Xu={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"},startLine:{type:"number",description:"1-indexed start line of the code to extract"},startColumn:{type:"number",description:"0-indexed start column of the code to extract"},endLine:{type:"number",description:"1-indexed end line of the code to extract"},endColumn:{type:"number",description:"0-indexed end column of the code to extract"},newFunctionName:{type:"string",description:"The name for the newly extracted function"}},required:["file","startLine","startColumn","endLine","endColumn","newFunctionName"]}});async function Oy(s){let e=s.file,t=s.startLine,r=s.startColumn,o=s.endLine,n=s.endColumn,a=s.newFunctionName;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("startLine is required");if(r===void 0)throw new Error("startColumn is required");if(o===void 0)throw new Error("endLine is required");if(n===void 0)throw new Error("endColumn is required");if(!a)throw new Error("newFunctionName is required");try{if(!(0,jr.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let i=(0,jr.readFileSync)(e,"utf-8"),c=M.getParser(e);if(!c.extractFunction)return JSON.stringify({file:e,error:"Function extraction is not specifically implemented for this language yet."});let p=await c.extractFunction({filePath:e,content:i},t,r,o,n,a);return JSON.stringify({file:e,result:p},null,2)}catch(i){throw new Error(`Failed to extract function from file "${e}": ${i.message}`)}}var jr,Fr,Ns=f(()=>{"use strict";l();jr=require("fs");Zu();Z();Fr={name:Ku,displayName:Qu,description:Yu,parameters:Xu,category:Vu,execute:Oy}});var ef,tf,of,rf,nf,sf=f(()=>{"use strict";l();ef="coding.get_call_hierarchy",tf="Get Call Hierarchy",of="Shows callers and callees of a specific function or method.",rf="coding",nf={type:"object",properties:{file:{type:"string",description:"The absolute path to the file containing the function"},line:{type:"number",description:"1-indexed line number where the function is defined or called"},column:{type:"number",description:"0-indexed column number where the function is defined or called"}},required:["file","line","column"]}});async function Iy(s){let e=s.file,t=s.line,r=s.column;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("line is required");if(r===void 0)throw new Error("column is required");try{if(!(0,Lr.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let o=(0,Lr.readFileSync)(e,"utf-8"),n=M.getParser(e);if(!n.getCallHierarchy)return JSON.stringify({file:e,error:"Call hierarchy is not specifically implemented for this language yet."});let a=await n.getCallHierarchy({filePath:e,content:o},t,r);return JSON.stringify({file:e,hierarchy:a},null,2)}catch(o){throw new Error(`Failed to get call hierarchy from file "${e}": ${o.message}`)}}var Lr,qr,As=f(()=>{"use strict";l();Lr=require("fs");sf();Z();qr={name:ef,displayName:tf,description:of,parameters:nf,category:rf,execute:Iy}});var af={};V(af,{codingExtractFunctionTool:()=>Fr,codingFindReferencesTool:()=>$r,codingFindSymbolTool:()=>Ut,codingGetCallHierarchyTool:()=>qr,codingGetDiagnosticsTool:()=>Mr,codingGetExportsTool:()=>Ir,codingGetImportsTool:()=>Gt,codingGetOutlineTool:()=>Nr,codingGetSymbolsTool:()=>Wt,codingGoToDefinitionTool:()=>_r,codingMultiFileEditTool:()=>kr,codingRefactorRenameTool:()=>Er,codingToolsProject:()=>Ms});var Ms,Os=f(()=>{"use strict";l();Ts();Ps();Cs();vs();Ss();$s();ks();Rs();Es();Ds();Ns();As();Ts();Ps();Cs();vs();Ss();$s();ks();Rs();Es();Ds();Ns();As();Ms={manifest:{key:"coding",name:"coding-tools",displayName:"Code Intelligence",version:"1.0.0",description:"AST-aware code intelligence tools for finding symbols, references, and analyzing code structure.",author:"Sajeer",tools:["coding.find_symbol","coding.get_symbols","coding.get_imports","coding.find_references","coding.go_to_definition","coding.get_outline","coding.get_diagnostics","coding.get_exports","coding.extract_function","coding.get_call_hierarchy","coding.multi_file_edit","coding.refactor_rename"],category:"coding"},tools:[Ut,Wt,Gt,$r,_r,Nr,Mr,Ir,Fr,qr,kr,Er],dependencies:{"@babel/parser":"^7.24.0","@babel/traverse":"^7.24.0","@babel/types":"^7.24.0"}}});var lf,cf=f(()=>{"use strict";l();lf={type:"object",properties:{path:{type:"string",description:"Optional path or directory to check the status for. If omitted, checks the entire repository."}}}});function q(s){let e={baseDir:s||process.cwd(),binary:"git",maxConcurrentProcesses:6};return(0,pf.simpleGit)(e)}var pf,ie=f(()=>{"use strict";l();pf=require("simple-git")});var fo,mf=f(()=>{"use strict";l();cf();ie();fo={name:"git.status",displayName:"Git Status",description:"Get the working tree status, including modified, staged, and untracked files.",category:"version-control",parameters:lf,execute:async s=>{let e=s.path;try{let r=await q().status(e?[e]:[]);if(r.isClean())return"Working tree clean";let o=[];return o.push(`Branch: ${r.current}`),r.tracking&&o.push(`Tracking: ${r.tracking}`),r.ahead>0&&o.push(`Ahead: ${r.ahead}`),r.behind>0&&o.push(`Behind: ${r.behind}`),o.push("---"),r.conflicted.length>0&&o.push(`Conflicted: ${r.conflicted.join(", ")}`),r.created.length>0&&o.push(`Created: ${r.created.join(", ")}`),r.deleted.length>0&&o.push(`Deleted: ${r.deleted.join(", ")}`),r.modified.length>0&&o.push(`Modified: ${r.modified.join(", ")}`),r.renamed.length>0&&o.push(`Renamed: ${r.renamed.map(n=>`${n.from} -> ${n.to}`).join(", ")}`),r.staged.length>0&&o.push(`Staged: ${r.staged.join(", ")}`),r.not_added.length>0&&o.push(`Untracked: ${r.not_added.join(", ")}`),o.join(`
104
- `)}catch(t){return`Error getting git status: ${t instanceof Error?t.message:String(t)}`}}}});var df,uf=f(()=>{"use strict";l();df={type:"object",properties:{path:{type:"string",description:"Optional path to get the diff for. If omitted, gets the diff for the entire repository."},staged:{type:"boolean",description:"If true, gets the diff of staged changes instead of unstaged changes.",default:!1}}}});var go,ff=f(()=>{"use strict";l();uf();ie();go={name:"git.diff",displayName:"Git Diff",description:"Show changes between commits, commit and working tree, etc.",category:"version-control",parameters:df,execute:async s=>{let e=s.path,t=s.staged;try{let r=q(),o=[];t&&o.push("--cached"),e&&o.push("--",e);let n=await r.diff(o);return n||"No changes found."}catch(r){return`Error getting git diff: ${r instanceof Error?r.message:String(r)}`}}}});var gf,hf=f(()=>{"use strict";l();gf={type:"object",properties:{maxCount:{type:"number",description:"Maximum number of commits to return. Defaults to 10 to prevent large outputs.",default:10},path:{type:"string",description:"Optional path to get the log for specific file or directory."}}}});var ho,yf=f(()=>{"use strict";l();hf();ie();ho={name:"git.log",displayName:"Git Log",description:"Show commit logs.",category:"version-control",parameters:gf,execute:async s=>{let e=s.maxCount||10,t=s.path;try{let r=q(),o={maxCount:e};t&&(o.file=t);let n=await r.log(o);return n.all.length===0?"No commits found.":n.all.map(a=>`Commit: ${a.hash}
105
- Author: ${a.author_name} <${a.author_email}>
106
- Date: ${a.date}
107
- Message: ${a.message}
101
+ `,g=`${i}();`),{newFunction:u,replacementCall:g}}async getCallHierarchy(e,t,o){let r=await this.getSymbolAtPosition(e,t,o);if(!r)return null;let i=(await this.findReferences(e,r,!1)).map(a=>({file:a.file,name:a.context.trim()||"<anonymous>",line:a.line,column:a.column}));return{file:e.filePath,name:r,line:t,column:o,callers:i,callees:[]}}}});var _r,ru=f(()=>{"use strict";l();Is();Zd();ou();_r=class{constructor(e){this.context=e;this.babelParser=new kr,this.treeSitterParser=new $r(this.context)}context;babelParser;treeSitterParser;getParser(e){switch(Cr(e)){case"javascript":case"typescript":case"tsx":case"jsx":return this.babelParser;case"python":case"go":case"rust":case"java":case"c":case"cpp":return this.treeSitterParser;default:throw new Error(`Unsupported or unknown language for file: ${e}`)}}}});var Gt,Dr,Rr,nu=f(()=>{"use strict";l();Gt=require("fs"),Dr=require("path");te();Rr=class{isBuilt=!1;isBuilding=!1;data={symbolLocations:new Map};fileMtimes=new Map;supportedExtensions=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];async getAllSupportedFiles(e){let t=[];try{let o=(0,Gt.readdirSync)(e,{withFileTypes:!0});for(let r of o){let s=(0,Dr.join)(e,r.name);r.name==="node_modules"||r.name===".git"||r.name==="dist"||r.name==="build"||(r.isDirectory()?t.push(...await this.getAllSupportedFiles(s)):r.isFile()&&this.supportedExtensions.includes((0,Dr.extname)(r.name).toLowerCase())&&t.push(s))}}catch{}return t}async buildIndex(e){if(!(this.isBuilt||this.isBuilding)){this.isBuilding=!0;try{let t=await this.getAllSupportedFiles(e);for(let o of t)await this.updateFile(o);this.isBuilt=!0}finally{this.isBuilding=!1}}}async updateFile(e){try{let o=(0,Gt.statSync)(e).mtimeMs;if(this.fileMtimes.get(e)===o)return;let r=(0,Gt.readFileSync)(e,"utf-8"),s=I.getParser(e);this.removeFileFromIndex(e);let i=await s.getSymbols({filePath:e,content:r});for(let a of i){let c=this.data.symbolLocations.get(a.name);c?c.add(e):this.data.symbolLocations.set(a.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 jy,I,Bt,te=f(()=>{"use strict";l();Vd();ru();nu();jy=new Sr,I=new _r(jy),Bt=new Rr});async function su(n,e,t){try{let o=(0,Kt.readFileSync)(n,"utf-8");return await I.getParser(n).findSymbols({filePath:n,content:o},e,t)}catch{return[]}}async function iu(n,e,t){let o=[];try{let r=(0,Kt.readdirSync)(n,{withFileTypes:!0});for(let s of r){let i=(0,Er.join)(n,s.name);if(!(s.name==="node_modules"||s.name===".git"||s.name==="dist")){if(s.isDirectory()){let a=await iu(i,e,t);o.push(...a)}else if(s.isFile()&&Ly.includes((0,Er.extname)(s.name))){let a=await su(i,e,t);o.push(...a)}}}}catch{}return o}async function Fy(n){let e=n.symbol,t=n.path,o=n.kind;if(h(`[coding.find-symbol] execute symbol="${e}" path="${t}" kind=${o??"all"}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let r=(0,Kt.statSync)(t),s;if(r.isDirectory())s=await iu(t,e,o);else if(r.isFile())s=await su(t,e,o);else throw new Error(`Path is neither a file nor directory: ${t}`);return JSON.stringify({symbol:e,found:s.length,locations:s},null,2)}var Kt,Er,Ly,Jt,Fs=f(()=>{"use strict";l();Kt=require("fs"),Er=require("path");Bd();te();_();Ly=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];Jt={name:Fd,displayName:qd,description:Ud,parameters:Gd,category:Wd,execute:Fy}});var au,lu,cu,pu,mu,du=f(()=>{"use strict";l();au="coding.get_symbols",lu="Get Symbols",cu="List all symbols (functions, classes, variables, etc.) in a JavaScript/TypeScript file",pu="coding",mu={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["file"]}});async function qy(n){let e=n.file,t=n.kind;if(h(`[coding.get-symbols] execute file="${e}" kind=${t??"all"}`),!e)throw new Error("file is required");try{let o=(0,uu.readFileSync)(e,"utf-8"),s=await I.getParser(e).getSymbols({filePath:e,content:o},t);return JSON.stringify({file:e,count:s.length,symbols:s},null,2)}catch(o){throw new Error(`Failed to parse file "${e}": ${o.message}`)}}var uu,Ht,qs=f(()=>{"use strict";l();uu=require("fs");du();te();_();Ht={name:au,displayName:lu,description:cu,parameters:mu,category:pu,execute:qy}});var fu,gu,hu,yu,wu,bu=f(()=>{"use strict";l();fu="coding.get_imports",gu="Get Imports",hu="List all import statements in a JavaScript/TypeScript file",yu="coding",wu={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"}},required:["file"]}});async function Uy(n){let e=n.file;if(h(`[coding.get-imports] execute file="${e}"`),!e)throw new Error("file is required");try{let t=(0,xu.readFileSync)(e,"utf-8"),r=await I.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 xu,zt,Us=f(()=>{"use strict";l();xu=require("fs");bu();te();_();zt={name:fu,displayName:gu,description:hu,parameters:wu,category:yu,execute:Uy}});var Tu,Pu,Cu,vu,Su,ku=f(()=>{"use strict";l();Tu="coding.find_references",Pu="Find References",Cu="Find all references to a symbol across JavaScript/TypeScript files",vu="coding",Su={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find references for"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},includeDeclaration:{type:"boolean",description:"Include the symbol declaration in results (default: false)"}},required:["symbol","path"]}});async function $u(n,e,t){try{let o=(0,Nr.readFileSync)(n,"utf-8");return await I.getParser(n).findReferences({filePath:n,content:o},e,t)}catch{return[]}}async function Wy(n,e,t){let o=[];await Bt.buildIndex(n);let r=await Bt.getDefinitionFiles(e,n);for(let s of r)if(s.startsWith(n)){let i=await $u(s,e,t);o.push(...i)}return o}async function Gy(n){let e=n.symbol,t=n.path,o=n.includeDeclaration===!0;if(h(`[coding.find-references] execute symbol="${e}" path="${t}" includeDecl=${o}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let r=(0,Nr.statSync)(t),s;if(r.isDirectory())s=await Wy(t,e,o);else if(r.isFile())s=await $u(t,e,o);else throw new Error(`Path is neither a file nor directory: ${t}`);return JSON.stringify({symbol:e,found:s.length,references:s},null,2)}var Nr,Ar,Ws=f(()=>{"use strict";l();Nr=require("fs");ku();te();_();Ar={name:Tu,displayName:Pu,description:Cu,parameters:Su,category:vu,execute:Gy}});var _u,Ru,Du,Eu,Nu,Au=f(()=>{"use strict";l();_u="coding.go_to_definition",Ru="Go To Definition",Du="Jump to the definition of a symbol at a specific location in a file",Eu="coding",Nu={type:"object",properties:{file:{type:"string",description:"Path to the file containing the symbol reference"},line:{type:"integer",description:"Line number where the symbol is referenced (1-indexed)"},column:{type:"integer",description:"Column number where the symbol is referenced (0-indexed)"},searchPath:{type:"string",description:"Optional: directory to search for the definition (defaults to file directory)"}},required:["file","line","column"]}});async function By(n,e,t){try{let o=(0,wo.readFileSync)(n,"utf-8");return await I.getParser(n).getSymbolAtPosition({filePath:n,content:o},e,t)}catch{return null}}async function Ou(n,e){try{let t=(0,wo.readFileSync)(n,"utf-8");return await I.getParser(n).getDefinition({filePath:n,content:t},e)}catch{return null}}async function Ky(n,e){await Bt.buildIndex(n);let t=await Bt.getDefinitionFiles(e,n);for(let o of t)if(o.startsWith(n)){let r=await Ou(o,e);if(r)return r}return null}async function Jy(n){let e=n.file,t=n.line,o=n.column,r=n.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 s=await By(e,t,o);if(!s)return JSON.stringify({found:!1,message:`No symbol found at ${e}:${t}:${o}`},null,2);let i=await Ou(e,s);if(!i){let a=r||(0,Mu.dirname)(e);(0,wo.statSync)(a).isDirectory()&&(i=await Ky(a,s))}return JSON.stringify(i?{found:!0,symbol:s,definition:i}:{found:!1,symbol:s,message:`Definition not found for symbol "${s}"`},null,2)}var wo,Mu,Mr,Gs=f(()=>{"use strict";l();wo=require("fs"),Mu=require("path");Au();te();Mr={name:_u,displayName:Ru,description:Du,parameters:Nu,category:Eu,execute:Jy}});var Iu,ju,Lu,Fu,qu,Uu=f(()=>{"use strict";l();Iu="coding.multi_file_edit",ju="Multi-File Edit",Lu="Edit multiple files atomically with rollback on failure",Fu="coding",qu={type:"object",properties:{edits:{type:"array",items:{type:"object",properties:{file:{type:"string"},changes:{type:"array",items:{type:"object",properties:{oldText:{type:"string"},newText:{type:"string"}}}}}},description:"Array of file edits, each with file path and array of text replacements"},atomic:{type:"boolean",description:"Atomic mode: rollback all edits if any fails (default: true)"}},required:["edits"]}});async function Hy(n){let e=n.edits,t=n.atomic!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("edits array is required and must not be empty");for(let s of e){if(!s.file)throw new Error("Each edit must have a file property");if(!s.changes||!Array.isArray(s.changes))throw new Error("Each edit must have a changes array");if(!(0,Ge.existsSync)(s.file))throw new Error(`File does not exist: ${s.file}`)}let o=[],r=[];try{for(let s of e){let i=(0,Ge.readFileSync)(s.file,"utf-8");t&&o.push({file:s.file,content:i});let a=i;for(let c of s.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=(a.match(new RegExp(zy(c.oldText),"g"))||[]).length;if(p===0)throw new Error(`Text not found in ${s.file}: "${c.oldText.substring(0,50)}..."`);if(p>1)throw new Error(`Ambiguous replacement in ${s.file}: "${c.oldText.substring(0,50)}..." appears ${p} times`);a=a.replace(c.oldText,c.newText)}(0,Ge.writeFileSync)(s.file,a,"utf-8"),r.push(s.file)}return JSON.stringify({success:!0,filesModified:r.length,files:r},null,2)}catch(s){if(t&&o.length>0){for(let i of o)try{(0,Ge.writeFileSync)(i.file,i.content,"utf-8")}catch{}throw new Error(`Multi-file edit failed and rolled back: ${s.message}`)}throw new Error(`Multi-file edit failed: ${s.message}`)}}function zy(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ge,Or,Bs=f(()=>{"use strict";l();Ge=require("fs");Uu();Or={name:Iu,displayName:ju,description:Lu,parameters:qu,category:Fu,execute:Hy,confirmation:{level:"high",reason:"This will modify multiple source code files atomically.",showArgs:["edits"]}}});var Wu,Gu,Bu,Ku,Ju,Hu=f(()=>{"use strict";l();Wu="coding.refactor_rename",Gu="Refactor Rename",Bu="Rename a symbol across the entire codebase intelligently",Ku="coding",Ju={type:"object",properties:{symbol:{type:"string",description:"Current name of the symbol to rename"},newName:{type:"string",description:"New name for the symbol"},path:{type:"string",description:"Directory path to search and rename in"},dryRun:{type:"boolean",description:"Preview changes without applying them (default: false)"}},required:["symbol","newName","path"]}});function Vy(n,e,t,o){let r=[];try{let s=(0,Qt.readFileSync)(n,"utf-8"),i=s.split(`
102
+ `),a=(0,zu.parse)(s,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]}),c=[];if(Qy(a,{Identifier(p){if(p.node.name===e){let m=p.node.loc?.start.line||0,u=p.node.loc?.start.column||0;c.push({line:m,column:u,length:e.length}),r.push({file:n,line:m,column:u,oldName:e,newName:t})}}}),!o&&c.length>0){c.sort((m,u)=>m.line!==u.line?u.line-m.line:u.column-m.column);let p=[...i];for(let m of c){let u=m.line-1;if(u>=0&&u<p.length){let g=p[u],w=g.substring(0,m.column),y=g.substring(m.column+m.length);p[u]=w+t+y}}(0,Qt.writeFileSync)(n,p.join(`
103
+ `),"utf-8")}}catch{}return{file:n,occurrences:r.length,changes:r}}function Qu(n,e,t,o){let r=[];try{let s=(0,Qt.readdirSync)(n,{withFileTypes:!0});for(let i of s){let a=(0,Ir.join)(n,i.name);if(!(i.name==="node_modules"||i.name===".git"||i.name==="dist")){if(i.isDirectory())r.push(...Qu(a,e,t,o));else if(i.isFile()&&Yy.includes((0,Ir.extname)(i.name))){let c=Vy(a,e,t,o);c.occurrences>0&&r.push(c)}}}}catch{}return r}async function Xy(n){let e=n.symbol,t=n.newName,o=n.path,r=n.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 s=Qu(o,e,t,r),i=s.reduce((c,p)=>c+p.occurrences,0),a=s.length;return JSON.stringify({success:!0,dryRun:r,oldName:e,newName:t,filesAffected:a,totalOccurrences:i,changes:s},null,2)}var Qt,Ir,zu,Ks,Qy,Yy,jr,Js=f(()=>{"use strict";l();Qt=require("fs"),Ir=require("path"),zu=require("@babel/parser"),Ks=x(require("@babel/traverse"),1);Hu();Qy=Ks.default||Ks,Yy=[".js",".jsx",".ts",".tsx",".mjs",".cjs"];jr={name:Wu,displayName:Gu,description:Bu,parameters:Ju,category:Ku,execute:Xy,confirmation:{level:"high",reason:"This will rename a symbol across multiple files, rewriting source code without backup.",showArgs:["symbol","newName"]}}});var Yu,Vu,Xu,Zu,ef,tf=f(()=>{"use strict";l();Yu="coding.get_outline",Vu="Get File Outline",Xu="Gets a hierarchical outline of symbols (classes, functions, methods) in a specified file.",Zu="coding",ef={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to outline"}},required:["file"]}});async function Zy(n){let e=n.file;if(h(`[coding.get-outline] execute file="${e}"`),!e)throw new Error("file is required");try{if(!(0,Lr.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,Lr.readFileSync)(e,"utf-8"),o=I.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 Lr,Fr,Hs=f(()=>{"use strict";l();Lr=require("fs");tf();te();_();Fr={name:Yu,displayName:Vu,description:Xu,parameters:ef,category:Zu,execute:Zy}});var of,rf,nf,sf,af,lf=f(()=>{"use strict";l();of="coding.get_diagnostics",rf="Get File Diagnostics",nf="Gets syntax errors and warnings for a file utilizing AST parsing.",sf="coding",af={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to check for diagnostics"}},required:["file"]}});async function ew(n){let e=n.file;if(!e)throw new Error("file is required");try{if(!(0,qr.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,qr.readFileSync)(e,"utf-8"),o=I.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 qr,Ur,zs=f(()=>{"use strict";l();qr=require("fs");lf();te();Ur={name:of,displayName:rf,description:nf,parameters:af,category:sf,execute:ew}});var cf,pf,mf,df,uf,ff=f(()=>{"use strict";l();cf="coding.get_exports",pf="Get File Exports",mf="Lists all symbols exported by a file.",df="coding",uf={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"}},required:["file"]}});async function tw(n){let e=n.file;if(h(`[coding.get-exports] execute file="${e}"`),!e)throw new Error("file is required");try{if(!(0,Wr.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,Wr.readFileSync)(e,"utf-8"),o=I.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 Wr,Gr,Qs=f(()=>{"use strict";l();Wr=require("fs");ff();te();_();Gr={name:cf,displayName:pf,description:mf,parameters:uf,category:df,execute:tw}});var gf,hf,yf,wf,bf,xf=f(()=>{"use strict";l();gf="coding.extract_function",hf="Extract Function",yf="Extracts a selected code region into a new function, automatically detecting required parameters and return values.",wf="coding",bf={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"},startLine:{type:"number",description:"1-indexed start line of the code to extract"},startColumn:{type:"number",description:"0-indexed start column of the code to extract"},endLine:{type:"number",description:"1-indexed end line of the code to extract"},endColumn:{type:"number",description:"0-indexed end column of the code to extract"},newFunctionName:{type:"string",description:"The name for the newly extracted function"}},required:["file","startLine","startColumn","endLine","endColumn","newFunctionName"]}});async function ow(n){let e=n.file,t=n.startLine,o=n.startColumn,r=n.endLine,s=n.endColumn,i=n.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(s===void 0)throw new Error("endColumn is required");if(!i)throw new Error("newFunctionName is required");try{if(!(0,Br.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let a=(0,Br.readFileSync)(e,"utf-8"),c=I.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:a},t,o,r,s,i);return JSON.stringify({file:e,result:p},null,2)}catch(a){throw new Error(`Failed to extract function from file "${e}": ${a.message}`)}}var Br,Kr,Ys=f(()=>{"use strict";l();Br=require("fs");xf();te();Kr={name:gf,displayName:hf,description:yf,parameters:bf,category:wf,execute:ow}});var Tf,Pf,Cf,vf,Sf,kf=f(()=>{"use strict";l();Tf="coding.get_call_hierarchy",Pf="Get Call Hierarchy",Cf="Shows callers and callees of a specific function or method.",vf="coding",Sf={type:"object",properties:{file:{type:"string",description:"The absolute path to the file containing the function"},line:{type:"number",description:"1-indexed line number where the function is defined or called"},column:{type:"number",description:"0-indexed column number where the function is defined or called"}},required:["file","line","column"]}});async function rw(n){let e=n.file,t=n.line,o=n.column;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("line is required");if(o===void 0)throw new Error("column is required");try{if(!(0,Jr.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let r=(0,Jr.readFileSync)(e,"utf-8"),s=I.getParser(e);if(!s.getCallHierarchy)return JSON.stringify({file:e,error:"Call hierarchy is not specifically implemented for this language yet."});let i=await s.getCallHierarchy({filePath:e,content:r},t,o);return JSON.stringify({file:e,hierarchy:i},null,2)}catch(r){throw new Error(`Failed to get call hierarchy from file "${e}": ${r.message}`)}}var Jr,Hr,Vs=f(()=>{"use strict";l();Jr=require("fs");kf();te();Hr={name:Tf,displayName:Pf,description:Cf,parameters:Sf,category:vf,execute:rw}});var $f={};Z($f,{codingExtractFunctionTool:()=>Kr,codingFindReferencesTool:()=>Ar,codingFindSymbolTool:()=>Jt,codingGetCallHierarchyTool:()=>Hr,codingGetDiagnosticsTool:()=>Ur,codingGetExportsTool:()=>Gr,codingGetImportsTool:()=>zt,codingGetOutlineTool:()=>Fr,codingGetSymbolsTool:()=>Ht,codingGoToDefinitionTool:()=>Mr,codingMultiFileEditTool:()=>Or,codingRefactorRenameTool:()=>jr,codingToolsProject:()=>Xs});var Xs,Zs=f(()=>{"use strict";l();Fs();qs();Us();Ws();Gs();Bs();Js();Hs();zs();Qs();Ys();Vs();Fs();qs();Us();Ws();Gs();Bs();Js();Hs();zs();Qs();Ys();Vs();Xs={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,Ar,Mr,Fr,Ur,Gr,Kr,Hr,Or,jr],dependencies:{"@babel/parser":"^7.24.0","@babel/traverse":"^7.24.0","@babel/types":"^7.24.0"}}});var _f,Rf=f(()=>{"use strict";l();_f={type:"object",properties:{path:{type:"string",description:"Optional path or directory to check the status for. If omitted, checks the entire repository."}}}});function G(n){let e={baseDir:n||process.cwd(),binary:"git",maxConcurrentProcesses:6};return(0,Df.simpleGit)(e)}var Df,pe=f(()=>{"use strict";l();Df=require("simple-git")});var bo,Ef=f(()=>{"use strict";l();Rf();pe();bo={name:"git.status",displayName:"Git Status",description:"Get the working tree status, including modified, staged, and untracked files.",category:"version-control",parameters:_f,execute:async n=>{let e=n.path;try{let o=await G().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(s=>`${s.from} -> ${s.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 Nf,Af=f(()=>{"use strict";l();Nf={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 xo,Mf=f(()=>{"use strict";l();Af();pe();xo={name:"git.diff",displayName:"Git Diff",description:"Show changes between commits, commit and working tree, etc.",category:"version-control",parameters:Nf,execute:async n=>{let e=n.path,t=n.staged;try{let o=G(),r=[];t&&r.push("--cached"),e&&r.push("--",e);let s=await o.diff(r);return s||"No changes found."}catch(o){return`Error getting git diff: ${o instanceof Error?o.message:String(o)}`}}}});var Of,If=f(()=>{"use strict";l();Of={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 To,jf=f(()=>{"use strict";l();If();pe();To={name:"git.log",displayName:"Git Log",description:"Show commit logs.",category:"version-control",parameters:Of,execute:async n=>{let e=n.maxCount||10,t=n.path;try{let o=G(),r={maxCount:e};t&&(r.file=t);let s=await o.log(r);return s.all.length===0?"No commits found.":s.all.map(i=>`Commit: ${i.hash}
105
+ Author: ${i.author_name} <${i.author_email}>
106
+ Date: ${i.date}
107
+ Message: ${i.message}
108
108
  `).join(`---
109
- `)}catch(r){return`Error getting git log: ${r instanceof Error?r.message:String(r)}`}}}});var wf,bf=f(()=>{"use strict";l();wf={type:"object",properties:{path:{type:"string",description:"Path to the file or directory to stage. To stage all changes, use '.'."}},required:["path"]}});var yo,xf=f(()=>{"use strict";l();bf();ie();yo={name:"git.add",displayName:"Git Add",description:"Add file contents to the index (stage changes).",category:"version-control",parameters:wf,execute:async s=>{let e=s.path;try{return await q().add(e),`Successfully staged changes for: ${e}`}catch(t){return`Error staging changes: ${t instanceof Error?t.message:String(t)}`}}}});var Tf,Pf=f(()=>{"use strict";l();Tf={type:"object",properties:{message:{type:"string",description:"The commit message."}},required:["message"]}});var wo,Cf=f(()=>{"use strict";l();Pf();ie();wo={name:"git.commit",displayName:"Git Commit",description:"Record changes to the repository.",category:"version-control",parameters:Tf,execute:async s=>{let e=s.message;try{let r=await q().commit(e);return r.commit?`Successfully committed changes.
110
- Commit: ${r.commit}
111
- Branch: ${r.branch}
112
- Summary: ${r.summary.changes} changes, ${r.summary.insertions} insertions, ${r.summary.deletions} deletions.`:"Nothing to commit."}catch(t){return`Error committing changes: ${t instanceof Error?t.message:String(t)}`}}}});var vf,Sf=f(()=>{"use strict";l();vf={type:"object",properties:{path:{type:"string",description:"Path to the file to blame."}},required:["path"]}});var bo,$f=f(()=>{"use strict";l();Sf();ie();bo={name:"git.blame",displayName:"Git Blame",description:"Show what revision and author last modified each line of a file.",category:"version-control",parameters:vf,execute:async s=>{let e=s.path;try{return await q().raw(["blame",e])}catch(t){return`Error running git blame: ${t instanceof Error?t.message:String(t)}`}}}});var _f,kf=f(()=>{"use strict";l();_f={type:"object",properties:{remote:{type:"boolean",description:"List remote branches as well.",default:!1}}}});var xo,Rf=f(()=>{"use strict";l();kf();ie();xo={name:"git.branch_list",displayName:"Git Branch List",description:"List all branches.",category:"version-control",parameters:_f,execute:async s=>{let e=s.remote;try{let t=q(),r=e?["-a"]:[],o=await t.branch(r);return`Current Branch: ${o.current}
109
+ `)}catch(o){return`Error getting git log: ${o instanceof Error?o.message:String(o)}`}}}});var Lf,Ff=f(()=>{"use strict";l();Lf={type:"object",properties:{path:{type:"string",description:"Path to the file or directory to stage. To stage all changes, use '.'."}},required:["path"]}});var Po,qf=f(()=>{"use strict";l();Ff();pe();Po={name:"git.add",displayName:"Git Add",description:"Add file contents to the index (stage changes).",category:"version-control",parameters:Lf,execute:async n=>{let e=n.path;try{return await G().add(e),`Successfully staged changes for: ${e}`}catch(t){return`Error staging changes: ${t instanceof Error?t.message:String(t)}`}}}});var Uf,Wf=f(()=>{"use strict";l();Uf={type:"object",properties:{message:{type:"string",description:"The commit message."}},required:["message"]}});var Co,Gf=f(()=>{"use strict";l();Wf();pe();Co={name:"git.commit",displayName:"Git Commit",description:"Record changes to the repository.",category:"version-control",parameters:Uf,execute:async n=>{let e=n.message;try{let o=await G().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)}`}},confirmation:{level:"medium",reason:"This will create a permanent commit in the repository history.",showArgs:["message"]}}});var Bf,Kf=f(()=>{"use strict";l();Bf={type:"object",properties:{path:{type:"string",description:"Path to the file to blame."}},required:["path"]}});var vo,Jf=f(()=>{"use strict";l();Kf();pe();vo={name:"git.blame",displayName:"Git Blame",description:"Show what revision and author last modified each line of a file.",category:"version-control",parameters:Bf,execute:async n=>{let e=n.path;try{return await G().raw(["blame",e])}catch(t){return`Error running git blame: ${t instanceof Error?t.message:String(t)}`}}}});var Hf,zf=f(()=>{"use strict";l();Hf={type:"object",properties:{remote:{type:"boolean",description:"List remote branches as well.",default:!1}}}});var So,Qf=f(()=>{"use strict";l();zf();pe();So={name:"git.branch_list",displayName:"Git Branch List",description:"List all branches.",category:"version-control",parameters:Hf,execute:async n=>{let e=n.remote;try{let t=G(),o=e?["-a"]:[],r=await t.branch(o);return`Current Branch: ${r.current}
113
113
 
114
114
  Branches:
115
- ${o.all.join(`
116
- `)}`}catch(t){return`Error listing branches: ${t instanceof Error?t.message:String(t)}`}}}});var Ef,Df=f(()=>{"use strict";l();Ef={type:"object",properties:{name:{type:"string",description:"Name of the new branch."},checkout:{type:"boolean",description:"Whether to checkout the new branch after creating it.",default:!1},startPoint:{type:"string",description:"Optional start point (commit hash or branch name) for the new branch."}},required:["name"]}});var To,Nf=f(()=>{"use strict";l();Df();ie();To={name:"git.branch_create",displayName:"Git Branch Create",description:"Create a new branch.",category:"version-control",parameters:Ef,execute:async s=>{let e=s.name,t=s.checkout,r=s.startPoint;try{let o=q();return t?(r?await o.checkoutBranch(e,r):await o.checkoutLocalBranch(e),`Successfully created and switched to branch: ${e}`):(r?await o.branch([e,r]):await o.branch([e]),`Successfully created branch: ${e}`)}catch(o){return`Error creating branch: ${o instanceof Error?o.message:String(o)}`}}}});var Af,Mf=f(()=>{"use strict";l();Af={type:"object",properties:{branch:{type:"string",description:"Name of the branch or commit to checkout."}},required:["branch"]}});var Po,Of=f(()=>{"use strict";l();Mf();ie();Po={name:"git.checkout",displayName:"Git Checkout",description:"Switch branches or restore working tree files.",category:"version-control",parameters:Af,execute:async s=>{let e=s.branch;try{return await q().checkout(e),`Successfully checked out: ${e}`}catch(t){return`Error checking out branch: ${t instanceof Error?t.message:String(t)}`}}}});var If={};V(If,{gitAddTool:()=>yo,gitBlameTool:()=>bo,gitBranchCreateTool:()=>To,gitBranchListTool:()=>xo,gitCheckoutTool:()=>Po,gitCommitTool:()=>wo,gitDiffTool:()=>go,gitLogTool:()=>ho,gitStatusTool:()=>fo,gitToolsProject:()=>Is});var Is,js=f(()=>{"use strict";l();mf();ff();yf();xf();Cf();$f();Rf();Nf();Of();Is={manifest:{key:"git",name:"git-tools",displayName:"Git Version Control",version:"1.0.0",description:"Git operations for reading repository state, checking diffs, creating commits, and managing branches.",author:"Sajeer",tools:["git.status","git.diff","git.log","git.add","git.commit","git.blame","git.branch_list","git.branch_create","git.checkout"],category:"version-control"},tools:[fo,go,ho,yo,wo,bo,xo,To,Po],dependencies:{"simple-git":"^3.27.0"}}});var jf,Ff=f(()=>{"use strict";l();jf={type:"object",properties:{oldContent:{type:"string",description:"The original text content."},newContent:{type:"string",description:"The new text content."},fileName:{type:"string",description:"Optional filename to include in the patch header."},contextLines:{type:"number",description:"Number of context lines to include around differences. Default is 4.",default:4}},required:["oldContent","newContent"]}});var Lf,Co,qf=f(()=>{"use strict";l();Ff();Lf=T(require("diff"),1);k();Co={name:"diff.create",displayName:"Create Diff",description:"Generate a unified diff from two text contents.",category:"diff",parameters:jf,execute:async s=>{let e=s.oldContent,t=s.newContent,r=s.fileName||"file",o=s.contextLines??4;h(`[diff.create] execute fileName="${r}" contextLines=${o}`);try{return Lf.createPatch(r,e,t,"","",{context:o})}catch(n){return`Error creating diff: ${n instanceof Error?n.message:String(n)}`}}}});var Uf,Wf=f(()=>{"use strict";l();Uf={type:"object",properties:{path:{type:"string",description:"Path to the file to patch."},patch:{type:"string",description:"Unified diff string to apply."}},required:["path","patch"]}});var Gf,Fs,vo,Bf=f(()=>{"use strict";l();Wf();Gf=T(require("diff"),1),Fs=require("fs");k();vo={name:"diff.apply",displayName:"Apply Diff",description:"Apply a unified diff patch to a file.",category:"diff",parameters:Uf,execute:async s=>{let e=s.path,t=s.patch;h(`[diff.apply] execute path="${e}"`);try{let r=await Fs.promises.readFile(e,"utf8"),o=Gf.applyPatch(r,t);return o===!1?"Failed to apply patch. The patch may be malformed or conflicting with the current file content.":(await Fs.promises.writeFile(e,o,"utf8"),`Successfully applied patch to ${e}`)}catch(r){return`Error applying patch: ${r instanceof Error?r.message:String(r)}`}}}});var Jf,Hf=f(()=>{"use strict";l();Jf={type:"object",properties:{path:{type:"string",description:"Path to the file to apply the patch against for preview."},patch:{type:"string",description:"Unified diff string to preview."}},required:["path","patch"]}});var zf,Kf,So,Qf=f(()=>{"use strict";l();Hf();zf=T(require("diff"),1),Kf=require("fs"),So={name:"diff.preview",displayName:"Preview Diff",description:"Preview the result of applying a patch to a file without modifying it.",category:"diff",parameters:Jf,execute:async s=>{let e=s.path,t=s.patch;try{let r=await Kf.promises.readFile(e,"utf8"),o=zf.applyPatch(r,t);return o===!1?"Patch preview failed. The patch would not apply cleanly.":`Preview of ${e} after patch:
115
+ ${r.all.join(`
116
+ `)}`}catch(t){return`Error listing branches: ${t instanceof Error?t.message:String(t)}`}}}});var Yf,Vf=f(()=>{"use strict";l();Yf={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 ko,Xf=f(()=>{"use strict";l();Vf();pe();ko={name:"git.branch_create",displayName:"Git Branch Create",description:"Create a new branch.",category:"version-control",parameters:Yf,execute:async n=>{let e=n.name,t=n.checkout,o=n.startPoint;try{let r=G();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 Zf,eg=f(()=>{"use strict";l();Zf={type:"object",properties:{branch:{type:"string",description:"Name of the branch or commit to checkout."}},required:["branch"]}});var $o,tg=f(()=>{"use strict";l();eg();pe();$o={name:"git.checkout",displayName:"Git Checkout",description:"Switch branches or restore working tree files.",category:"version-control",parameters:Zf,execute:async n=>{let e=n.branch;try{return await G().checkout(e),`Successfully checked out: ${e}`}catch(t){return`Error checking out branch: ${t instanceof Error?t.message:String(t)}`}},confirmation:{level:"medium",reason:"This will switch branches, potentially losing uncommitted changes.",showArgs:["branch"]}}});var og={};Z(og,{gitAddTool:()=>Po,gitBlameTool:()=>vo,gitBranchCreateTool:()=>ko,gitBranchListTool:()=>So,gitCheckoutTool:()=>$o,gitCommitTool:()=>Co,gitDiffTool:()=>xo,gitLogTool:()=>To,gitStatusTool:()=>bo,gitToolsProject:()=>ei});var ei,ti=f(()=>{"use strict";l();Ef();Mf();jf();qf();Gf();Jf();Qf();Xf();tg();ei={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,xo,To,Po,Co,vo,So,ko,$o],dependencies:{"simple-git":"^3.27.0"}}});var rg,ng=f(()=>{"use strict";l();rg={type:"object",properties:{oldContent:{type:"string",description:"The original text content."},newContent:{type:"string",description:"The new text content."},fileName:{type:"string",description:"Optional filename to include in the patch header."},contextLines:{type:"number",description:"Number of context lines to include around differences. Default is 4.",default:4}},required:["oldContent","newContent"]}});var sg,_o,ig=f(()=>{"use strict";l();ng();sg=x(require("diff"),1);_();_o={name:"diff.create",displayName:"Create Diff",description:"Generate a unified diff from two text contents.",category:"diff",parameters:rg,execute:async n=>{let e=n.oldContent,t=n.newContent,o=n.fileName||"file",r=n.contextLines??4;h(`[diff.create] execute fileName="${o}" contextLines=${r}`);try{return sg.createPatch(o,e,t,"","",{context:r})}catch(s){return`Error creating diff: ${s instanceof Error?s.message:String(s)}`}}}});var ag,lg=f(()=>{"use strict";l();ag={type:"object",properties:{path:{type:"string",description:"Path to the file to patch."},patch:{type:"string",description:"Unified diff string to apply."}},required:["path","patch"]}});var cg,oi,Ro,pg=f(()=>{"use strict";l();lg();cg=x(require("diff"),1),oi=require("fs");_();Ro={name:"diff.apply",displayName:"Apply Diff",description:"Apply a unified diff patch to a file.",category:"diff",parameters:ag,execute:async n=>{let e=n.path,t=n.patch;h(`[diff.apply] execute path="${e}"`);try{let o=await oi.promises.readFile(e,"utf8"),r=cg.applyPatch(o,t);return r===!1?"Failed to apply patch. The patch may be malformed or conflicting with the current file content.":(await oi.promises.writeFile(e,r,"utf8"),`Successfully applied patch to ${e}`)}catch(o){return`Error applying patch: ${o instanceof Error?o.message:String(o)}`}},confirmation:{level:"high",reason:"This will apply a patch to files, which may corrupt them if the patch doesn't match.",showArgs:["path"]}}});var mg,dg=f(()=>{"use strict";l();mg={type:"object",properties:{path:{type:"string",description:"Path to the file to apply the patch against for preview."},patch:{type:"string",description:"Unified diff string to preview."}},required:["path","patch"]}});var ug,fg,Do,gg=f(()=>{"use strict";l();dg();ug=x(require("diff"),1),fg=require("fs"),Do={name:"diff.preview",displayName:"Preview Diff",description:"Preview the result of applying a patch to a file without modifying it.",category:"diff",parameters:mg,execute:async n=>{let e=n.path,t=n.patch;try{let o=await fg.promises.readFile(e,"utf8"),r=ug.applyPatch(o,t);return r===!1?"Patch preview failed. The patch would not apply cleanly.":`Preview of ${e} after patch:
117
117
 
118
- ${o}`}catch(r){return`Error previewing patch: ${r instanceof Error?r.message:String(r)}`}}}});var Yf={};V(Yf,{diffApplyTool:()=>vo,diffCreateTool:()=>Co,diffPreviewTool:()=>So,diffToolsProject:()=>Ls});var Ls,qs=f(()=>{"use strict";l();qf();Bf();Qf();Ls={manifest:{key:"diff",name:"diff-tools",displayName:"Diff and Patch",version:"1.0.0",description:"Tools to create and apply unified diff changes to files safely.",author:"Sajeer",tools:["diff.create","diff.apply","diff.preview"],category:"diff"},tools:[Co,vo,So],dependencies:{diff:"^7.0.0"}}});var Vf,Xf=f(()=>{"use strict";l();Vf={type:"object",properties:{db:{type:"string",description:"Database connection URI (e.g. postgres://user:pass@host/db, mysql://...) or local SQLite file path (.sqlite, .db)"},sql:{type:"string",description:"The SQL query to execute"},params:{type:"array",description:"Optional array of parameters for parameterized queries (to prevent SQL injection)",items:{},default:[]}},required:["db","sql"]}});var Se,Ur=f(()=>{"use strict";l();Se=class{connectionString;constructor(e){this.connectionString=e}}});var Us,Ws,$o,Zf=f(()=>{"use strict";l();Us=T(require("better-sqlite3"),1),Ws=T(require("fs"),1);Ur();$o=class extends Se{getDb(){if(!Ws.existsSync(this.connectionString))throw new Error(`Database file not found: ${this.connectionString}`);return new Us.default(this.connectionString,{readonly:!1})}async query(e,t=[]){let r=this.getDb();try{let o=r.prepare(e);return o.reader?o.all(t):(o.run(t),[])}finally{r.close()}}async execute(e,t=[]){let r=this.getDb();try{let n=r.prepare(e).run(t);return{changes:n.changes,lastInsertRowid:n.lastInsertRowid,raw:n}}finally{r.close()}}async getTables(){return(await this.query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")).map(r=>r.name)}async getSchema(e){return e?await this.query(`PRAGMA table_info("${e}")`):await this.query("SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")}static executeSession(e,t,r=[]){if(!Ws.existsSync(e))throw new Error(`Database file not found: ${e}`);let o=new Us.default(e,{readonly:!1});try{let n=o.prepare(t);return n.reader?n.all(r):n.run(r)}finally{o.close()}}}});var eg,Wr,tg=f(()=>{"use strict";l();eg=T(require("pg"),1);Ur();Wr=class extends Se{async getClient(){let e=new eg.default.Client({connectionString:this.connectionString});return await e.connect(),e}convertSql(e){let t=1;return e.replace(/\?/g,()=>`$${t++}`)}async query(e,t=[]){let r=await this.getClient();try{let o=this.convertSql(e);return(await r.query(o,t)).rows}finally{await r.end()}}async execute(e,t=[]){let r=await this.getClient();try{let o=this.convertSql(e),n=await r.query(o,t);return{changes:n.rowCount??0,raw:n}}finally{await r.end()}}async getTables(){return(await this.query("SELECT tablename as name FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema'")).map(r=>r.name)}async getSchema(e){return e?await this.query(`
118
+ ${r}`}catch(o){return`Error previewing patch: ${o instanceof Error?o.message:String(o)}`}}}});var hg={};Z(hg,{diffApplyTool:()=>Ro,diffCreateTool:()=>_o,diffPreviewTool:()=>Do,diffToolsProject:()=>ri});var ri,ni=f(()=>{"use strict";l();ig();pg();gg();ri={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:[_o,Ro,Do],dependencies:{diff:"^7.0.0"}}});var yg,wg=f(()=>{"use strict";l();yg={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 Re,zr=f(()=>{"use strict";l();Re=class{connectionString;constructor(e){this.connectionString=e}}});var si,ii,Eo,bg=f(()=>{"use strict";l();si=x(require("better-sqlite3"),1),ii=x(require("fs"),1);zr();Eo=class extends Re{getDb(){if(!ii.existsSync(this.connectionString))throw new Error(`Database file not found: ${this.connectionString}`);return new si.default(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 s=o.prepare(e).run(t);return{changes:s.changes,lastInsertRowid:s.lastInsertRowid,raw:s}}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(!ii.existsSync(e))throw new Error(`Database file not found: ${e}`);let r=new si.default(e,{readonly:!1});try{let s=r.prepare(t);return s.reader?s.all(o):s.run(o)}finally{r.close()}}}});var xg,Qr,Tg=f(()=>{"use strict";l();xg=x(require("pg"),1);zr();Qr=class extends Re{async getClient(){let e=new xg.default.Client({connectionString:this.connectionString});return await e.connect(),e}convertSql(e){let t=1;return e.replace(/\?/g,()=>`$${t++}`)}async query(e,t=[]){let 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),s=await o.query(r,t);return{changes:s.rowCount??0,raw:s}}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(`
119
119
  SELECT column_name, data_type, is_nullable, column_default
120
120
  FROM information_schema.columns
121
121
  WHERE table_name = $1
@@ -123,23 +123,23 @@ ${o}`}catch(r){return`Error previewing patch: ${r instanceof Error?r.message:Str
123
123
  SELECT table_name as name, table_type
124
124
  FROM information_schema.tables
125
125
  WHERE table_schema = 'public'
126
- `)}}});var og,Gr,rg=f(()=>{"use strict";l();og=T(require("mysql2/promise"),1);Ur();Gr=class extends Se{async getConnection(){return await og.default.createConnection(this.connectionString)}async query(e,t=[]){let r=await this.getConnection();try{let[o]=await r.execute(e,t);return o}finally{await r.end()}}async execute(e,t=[]){let r=await this.getConnection();try{let[o]=await r.execute(e,t);return{changes:o.affectedRows,lastInsertRowid:o.insertId,raw:o}}finally{await r.end()}}async getTables(){let t=await this.query("SHOW TABLES");if(!t||t.length===0)return[];let r=Object.keys(t[0]);return t.map(o=>o[r[0]])}async getSchema(e){if(e){let t=await this.getConnection();try{let[r]=await t.query("DESCRIBE ??",[e]);return r}finally{await t.end()}}else return await this.query("SHOW TABLES")}}});var G,$e=f(()=>{"use strict";l();Zf();tg();rg();G=class{static getAdapter(e){return e.startsWith("postgres://")||e.startsWith("postgresql://")?new Wr(e):e.startsWith("mysql://")?new Gr(e):e.startsWith("sqlite://")?new $o(e.replace("sqlite://","")):new $o(e)}}});var _o,ng=f(()=>{"use strict";l();Xf();$e();k();_o={name:"db.query",displayName:"Database Query",description:"Execute raw SQL queries against an SQLite, PostgreSQL, or MySQL database.",category:"database",parameters:Vf,execute:async s=>{let e=s.db,t=s.sql,r=s.params||[];h(`[db.query] execute db="${e}" sql="${t.substring(0,80)}..." params=${r.length}`);try{let n=await G.getAdapter(e).query(t,r);return JSON.stringify(n,null,2)}catch(o){return`Database query error: ${o instanceof Error?o.message:String(o)}`}}}});var sg,ig=f(()=>{"use strict";l();sg={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Optional specific table name to inspect. If omitted, returns structural summary of all tables."}},required:["db"]}});var ko,ag=f(()=>{"use strict";l();ig();$e();ko={name:"db.schema",displayName:"Database Schema",description:"Get the structural schema of a database or a specific table.",category:"database",parameters:sg,execute:async s=>{let e=s.db,t=s.table;try{let o=await G.getAdapter(e).getSchema(t);return JSON.stringify(o,null,2)}catch(r){return`Database schema error: ${r instanceof Error?r.message:String(r)}`}}}});var lg,cg=f(()=>{"use strict";l();lg={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"}},required:["db"]}});var Ro,pg=f(()=>{"use strict";l();cg();$e();Ro={name:"db.tables",displayName:"Database Tables",description:"List all user tables in the database.",category:"database",parameters:lg,execute:async s=>{let e=s.db;try{let r=await G.getAdapter(e).getTables();return JSON.stringify(r,null,2)}catch(t){return`Database tables error: ${t instanceof Error?t.message:String(t)}`}}}});var mg,dg=f(()=>{"use strict";l();mg={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to insert into"},data:{type:"object",description:"Key-value pairs of column names and values to insert"}},required:["db","table","data"]}});var Eo,ug=f(()=>{"use strict";l();dg();$e();Eo={name:"db.insert",displayName:"Database Insert",description:"Insert a new row into an SQLite table safely.",category:"database",parameters:mg,execute:async s=>{let e=s.db,t=s.table,r=s.data;if(Object.keys(r).length===0)return"Error: No data provided to insert.";try{let o=Object.keys(r).join(", "),n=Object.keys(r).map(()=>"?").join(", "),a=Object.values(r),i=`INSERT INTO ${t} (${o}) VALUES (${n})`,p=await G.getAdapter(e).execute(i,a);return JSON.stringify(p,null,2)}catch(o){return`Database insert error: ${o instanceof Error?o.message:String(o)}`}}}});var fg,gg=f(()=>{"use strict";l();fg={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to update"},data:{type:"object",description:"Key-value pairs of column names and new values"},where:{type:"string",description:'WHERE clause condition (e.g. "id = 5"). DO NOT INCLUDE the word WHERE.'}},required:["db","table","data","where"]}});var Do,hg=f(()=>{"use strict";l();gg();$e();Do={name:"db.update",displayName:"Database Update",description:"Update existing rows in a database table.",category:"database",parameters:fg,execute:async s=>{let e=s.db,t=s.table,r=s.data,o=s.where;if(Object.keys(r).length===0)return"Error: No data provided to update.";try{let n=Object.keys(r).map(m=>`${m} = ?`).join(", "),a=Object.values(r),i=`UPDATE ${t} SET ${n} WHERE ${o}`,p=await G.getAdapter(e).execute(i,a);return JSON.stringify(p,null,2)}catch(n){return`Database update error: ${n instanceof Error?n.message:String(n)}`}}}});var yg,wg=f(()=>{"use strict";l();yg={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to delete from"},where:{type:"string",description:'WHERE clause condition (e.g. "id = 5"). DO NOT INCLUDE the word WHERE.'}},required:["db","table","where"]}});var No,bg=f(()=>{"use strict";l();wg();$e();No={name:"db.delete",displayName:"Database Delete",description:"Delete rows from a database table.",category:"database",parameters:yg,execute:async s=>{let e=s.db,t=s.table,r=s.where;try{let o=`DELETE FROM ${t} WHERE ${r}`,a=await G.getAdapter(e).execute(o);return JSON.stringify(a,null,2)}catch(o){return`Database delete error: ${o instanceof Error?o.message:String(o)}`}}}});var xg,Tg=f(()=>{"use strict";l();xg={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to count rows from"},where:{type:"string",description:"Optional WHERE clause condition"}},required:["db","table"]}});var Ao,Pg=f(()=>{"use strict";l();Tg();$e();Ao={name:"db.count",displayName:"Database Count",description:"Count rows in a database table.",category:"database",parameters:xg,execute:async s=>{let e=s.db,t=s.table,r=s.where;try{let o=r?`WHERE ${r}`:"",n=`SELECT COUNT(*) as count FROM ${t} ${o}`,i=await G.getAdapter(e).query(n);return Array.isArray(i)&&i.length>0?`Rows: ${i[0].count}`:"Count: 0"}catch(o){return`Database count error: ${o instanceof Error?o.message:String(o)}`}}}});var Cg={};V(Cg,{dbCountTool:()=>Ao,dbDeleteTool:()=>No,dbInsertTool:()=>Eo,dbQueryTool:()=>_o,dbSchemaTool:()=>ko,dbTablesTool:()=>Ro,dbToolsProject:()=>Gs,dbUpdateTool:()=>Do});var Gs,Bs=f(()=>{"use strict";l();ng();ag();pg();ug();hg();bg();Pg();Gs={manifest:{key:"db",name:"db-tools",displayName:"Database Tools",version:"1.0.0",description:"Stateless database operations enabling the AI to interact with local databases.",author:"Sajeer",tools:["db.query","db.schema","db.tables","db.insert","db.update","db.delete","db.count"],category:"database"},tools:[_o,ko,Ro,Eo,Do,No,Ao],dependencies:{"better-sqlite3":"^11.3.0"}}});var vg,Sg=f(()=>{"use strict";l();vg={type:"object",properties:{siteId:{type:"string",description:'The Netlify Site ID to deploy to (e.g. "api_id" from Netlify UI)'},dir:{type:"string",description:'The local directory path to deploy (e.g. "./dist" or "./public")'},message:{type:"string",description:"Optional deployment message/commit note"}},required:["siteId","dir"]}});var $g,_e,Br=f(()=>{"use strict";l();$g=require("netlify"),_e=class{static getClient(){let e=process.env.NETLIFY_AUTH_TOKEN;if(!e)throw new Error("NETLIFY_AUTH_TOKEN environment variable is required to use Netlify cloud tools.");return new $g.NetlifyAPI(e)}}});var Mo,_g=f(()=>{"use strict";l();Sg();Br();k();Mo={name:"cloud.deploy",displayName:"Cloud Deploy",description:"Deploy a static directory to Netlify.",category:"cloud",parameters:vg,execute:async s=>{let e=s.siteId,t=s.dir,r=s.message;h(`[cloud.deploy] execute siteId="${e}" dir="${t}" message="${r??"none"}"`);try{let n=await _e.getClient().deploy(e,t,{message:r||"Deployed via Toolpack SDK",draft:!1});return JSON.stringify({id:n.deployId,url:n.deploy.url,admin_url:n.deploy.admin_url,state:n.deploy.state},null,2)}catch(o){return`Cloud deployment error: ${o instanceof Error?o.message:String(o)}`}}}});var kg,Rg=f(()=>{"use strict";l();kg={type:"object",properties:{siteId:{type:"string",description:"The Netlify Site ID"},deployId:{type:"string",description:"The specific Deployment ID to check"}},required:["siteId","deployId"]}});var Oo,Eg=f(()=>{"use strict";l();Rg();Br();Oo={name:"cloud.status",displayName:"Cloud Status",description:"Check the status of a specific Netlify deployment.",category:"cloud",parameters:kg,execute:async s=>{let e=s.siteId,t=s.deployId;try{let o=await _e.getClient().getSiteDeploy({site_id:e,deploy_id:t});return JSON.stringify({id:o.id,state:o.state,error_message:o.error_message,created_at:o.created_at,updated_at:o.updated_at,url:o.url},null,2)}catch(r){return`Cloud status error: ${r instanceof Error?r.message:String(r)}`}}}});var Dg,Ng=f(()=>{"use strict";l();Dg={type:"object",properties:{siteId:{type:"string",description:"The Netlify Site ID"},limit:{type:"number",description:"Number of recent deployments to return. Defaults to 5.",default:5}},required:["siteId"]}});var Io,Ag=f(()=>{"use strict";l();Ng();Br();k();Io={name:"cloud.list",displayName:"Cloud Deployments List",description:"List recent deployments for a Netlify site.",category:"cloud",parameters:Dg,execute:async s=>{let e=s.siteId,t=s.limit||5;h(`[cloud.list] execute siteId="${e}" limit=${t}`);try{let o=await _e.getClient().listSiteDeploys({site_id:e,page:1,per_page:t});if(!Array.isArray(o))return"Unexpected response format from Netlify API";let n=o.map(a=>({id:a.id,state:a.state,created_at:a.created_at,url:a.url,branch:a.branch,title:a.title}));return JSON.stringify(n,null,2)}catch(r){return`Cloud list error: ${r instanceof Error?r.message:String(r)}`}}}});var Mg={};V(Mg,{cloudDeployTool:()=>Mo,cloudListTool:()=>Io,cloudStatusTool:()=>Oo,cloudToolsProject:()=>Js});var Js,Hs=f(()=>{"use strict";l();_g();Eg();Ag();Js={manifest:{key:"cloud",name:"cloud-tools",displayName:"Cloud Deployment",version:"1.0.0",description:"Cloud deployment operations allowing the AI to publish directories directly to the internet.",author:"Sajeer",tools:["cloud.deploy","cloud.status","cloud.list"],category:"cloud"},tools:[Mo,Oo,Io],dependencies:{netlify:"^13.1.20"}}});var Hy={};V(Hy,{AGENT_MODE:()=>Ys,AGENT_PLANNING_PROMPT:()=>zr,AGENT_STEP_PROMPT:()=>Kr,AGENT_WORKFLOW:()=>zs,AIClient:()=>eo,AnthropicAdapter:()=>oo,AuthenticationError:()=>pe,BM25SearchEngine:()=>Ge,BUILT_IN_MODES:()=>Lo,CHAT_MODE:()=>Vs,CHAT_WORKFLOW:()=>Qs,CODING_PLANNING_PROMPT:()=>Fg,CODING_STEP_PROMPT:()=>Lg,CODING_WORKFLOW:()=>Ks,CONFIG_DIR_NAME:()=>ti,CONFIG_FILE_NAME:()=>oi,ConnectionError:()=>we,DEFAULT_MODE_NAME:()=>Le,DEFAULT_TOOLS_CONFIG:()=>H,DEFAULT_TOOL_SEARCH_CONFIG:()=>ci,DEFAULT_WORKFLOW:()=>jy,DEFAULT_WORKFLOW_CONFIG:()=>Qr,GeminiAdapter:()=>ro,InvalidRequestError:()=>N,McpClient:()=>Ht,McpConnectionError:()=>ae,McpTimeoutError:()=>jo,McpToolManager:()=>Fo,ModeRegistry:()=>zt,OllamaAdapter:()=>xe,OllamaProvider:()=>Ke,OpenAIAdapter:()=>ao,PageError:()=>Vr,Planner:()=>Kt,ProviderAdapter:()=>K,ProviderError:()=>I,RateLimitError:()=>me,SDKError:()=>J,StepExecutor:()=>Yt,TOOLPACK_DIR_NAME:()=>ei,TOOL_SEARCH_NAME:()=>Be,TimeoutError:()=>Xr,ToolDiscoveryCache:()=>De,ToolRegistry:()=>Jt,ToolRouter:()=>Je,Toolpack:()=>Zs,WorkflowExecutor:()=>qo,cloudDeployTool:()=>Mo,cloudListTool:()=>Io,cloudStatusTool:()=>Oo,cloudToolsProject:()=>Js,codingFindSymbolTool:()=>Ut,codingGetImportsTool:()=>Gt,codingGetSymbolsTool:()=>Wt,codingToolsProject:()=>Ms,createMcpToolProject:()=>Jr,createMode:()=>qg,createToolProject:()=>Og,dbCountTool:()=>Ao,dbDeleteTool:()=>No,dbInsertTool:()=>Eo,dbQueryTool:()=>_o,dbSchemaTool:()=>ko,dbTablesTool:()=>Ro,dbToolsProject:()=>Gs,dbUpdateTool:()=>Do,diffApplyTool:()=>vo,diffCreateTool:()=>Co,diffPreviewTool:()=>So,diffToolsProject:()=>Ls,disconnectMcpToolProject:()=>Hr,ensureGlobalConfigDir:()=>si,ensureLocalConfigDir:()=>Wy,execKillTool:()=>xt,execListProcessesTool:()=>Tt,execReadOutputTool:()=>bt,execRunBackgroundTool:()=>wt,execRunShellTool:()=>yt,execRunTool:()=>ht,execToolsProject:()=>qn,fetchUrlAsBase64:()=>an,fsAppendFileTool:()=>et,fsCopyTool:()=>ct,fsCreateDirTool:()=>at,fsDeleteFileTool:()=>ot,fsExistsTool:()=>rt,fsListDirTool:()=>st,fsMoveTool:()=>lt,fsReadFileRangeTool:()=>mt,fsReadFileTool:()=>Ye,fsReplaceInFileTool:()=>ut,fsSearchTool:()=>dt,fsStatTool:()=>nt,fsToolsProject:()=>Nn,fsTreeTool:()=>gt,fsWriteFileTool:()=>Xe,generateToolCategoriesPrompt:()=>Ho,getDefaultSlmModel:()=>Ei,getGlobalConfigDir:()=>ri,getGlobalConfigPath:()=>Uo,getGlobalToolpackDir:()=>Bg,getLocalConfigDir:()=>ni,getLocalConfigPath:()=>Wo,getLocalToolpackDir:()=>Jg,getMimeType:()=>on,getOllamaBaseUrl:()=>io,getOllamaProviderEntries:()=>Ri,getRegisteredSlmModels:()=>Ni,getRuntimeConfigStatus:()=>By,getToolSearchSchema:()=>Bo,getToolpackConfig:()=>Vo,getUserHomeDir:()=>Gg,gitAddTool:()=>yo,gitBlameTool:()=>bo,gitBranchCreateTool:()=>To,gitBranchListTool:()=>xo,gitCheckoutTool:()=>Po,gitCommitTool:()=>wo,gitDiffTool:()=>go,gitLogTool:()=>ho,gitStatusTool:()=>fo,gitToolsProject:()=>Is,httpDeleteTool:()=>Et,httpDownloadTool:()=>Nt,httpGetTool:()=>_t,httpPostTool:()=>kt,httpPutTool:()=>Rt,httpToolsProject:()=>os,initializeGlobalConfigIfFirstRun:()=>Jy,isDataUri:()=>rn,isRegisteredSlm:()=>Di,isToolSearchTool:()=>Jo,loadFullConfig:()=>po,loadRuntimeConfig:()=>Gy,loadToolsConfig:()=>Mt,normalizeImagePart:()=>Si,ollamaRequest:()=>ne,ollamaStream:()=>Xo,parseDataUri:()=>nn,readFileAsBase64:()=>sn,reloadToolpackConfig:()=>ki,saveToolsConfig:()=>gm,systemCwdTool:()=>St,systemDiskUsageTool:()=>$t,systemEnvTool:()=>Ct,systemInfoTool:()=>Pt,systemSetEnvTool:()=>vt,systemToolsProject:()=>Qn,toDataUri:()=>vi,toolSearchDefinition:()=>Ne,webExtractLinksTool:()=>jt,webFetchTool:()=>At,webScrapeTool:()=>It,webSearchTool:()=>Ot,webToolsProject:()=>hs});module.exports=th(Hy);l();de();l();var Ti=require("events");de();l();l();l();var We={name:3,displayName:2.5,description:2,category:1.5,parameterNames:1,parameterDescriptions:.5},Ge=class{documents=[];avgDocLength=0;idf=new Map;totalDocs=0;docFrequencies=new Map;k1=1.2;b=.75;index(e){this.documents=[],this.docFrequencies.clear(),this.idf.clear();for(let t of e){let r=this.createDocument(t);this.documents.push(r);let o=new Set(r.tokens);for(let n of o)this.docFrequencies.set(n,(this.docFrequencies.get(n)||0)+1)}this.totalDocs=this.documents.length,this.computeIDF(),this.avgDocLength=this.computeAvgDocLength()}search(e,t){let r=t?.limit??5,o=t?.category,n=t?.minScore??0,a=this.tokenize(e.toLowerCase());if(a.length===0)return[];let i=[];for(let c of this.documents){if(o&&c.tool.category!==o)continue;let p=this.computeBM25Score(a,c);p>n&&i.push({toolName:c.toolName,score:p,tool:c.tool})}return i.sort((c,p)=>p.score-c.score).slice(0,r).map(({toolName:c,score:p,tool:m})=>({toolName:c,score:p,tool:this.toSchema(m)}))}getIndexedCount(){return this.documents.length}isIndexed(e){return this.documents.some(t=>t.toolName===e)}createDocument(e){let t=[];for(let a=0;a<We.name;a++)t.push(e.name);for(let a=0;a<We.displayName;a++)t.push(e.displayName);for(let a=0;a<We.description;a++)t.push(e.description);for(let a=0;a<We.category;a++)t.push(e.category);if(e.parameters?.properties)for(let[a,i]of Object.entries(e.parameters.properties)){for(let c=0;c<We.parameterNames;c++)t.push(a);if(i.description)for(let c=0;c<We.parameterDescriptions;c++)t.push(i.description)}let r=t.join(" ").toLowerCase(),o=this.tokenize(r),n=this.computeTermFrequencies(o);return{toolName:e.name,tool:e,text:r,tokens:o,length:o.length,termFrequencies:n}}tokenize(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1).filter(t=>!oh.has(t))}computeTermFrequencies(e){let t=new Map;for(let r of e)t.set(r,(t.get(r)||0)+1);return t}computeIDF(){this.idf.clear();for(let[e,t]of this.docFrequencies){let r=Math.log((this.totalDocs-t+.5)/(t+.5)+1);this.idf.set(e,r)}}computeAvgDocLength(){return this.documents.length===0?0:this.documents.reduce((t,r)=>t+r.length,0)/this.documents.length}computeBM25Score(e,t){let r=0;for(let o of e){let n=t.termFrequencies.get(o)||0;if(n===0)continue;let a=this.idf.get(o)||0,i=t.length,c=n*(this.k1+1),p=n+this.k1*(1-this.b+this.b*(i/this.avgDocLength));r+=a*(c/p)}return r}toSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category}}},oh=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","it","its","this","that","these","those","i","you","he","she","we","they","what","which","who","whom","when","where","why","how","all","each","every","both","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","just","also","now","here","there"]);l();var De=class s{discoveredTools=new Set;searchHistory=[];recordDiscovery(e,t){for(let r of t)this.discoveredTools.add(r);this.searchHistory.push({query:e,tools:t,timestamp:Date.now()})}getDiscoveredTools(){return Array.from(this.discoveredTools)}isDiscovered(e){return this.discoveredTools.has(e)}getDiscoveredCount(){return this.discoveredTools.size}getSearchHistory(){return[...this.searchHistory]}static fromMessages(e){let t=new s;for(let r of e)if(r.role==="tool"){let o=r;if(typeof o.content=="string")try{let n=JSON.parse(o.content);if(n.query&&n.tools&&Array.isArray(n.tools)){let a=n.tools.map(i=>typeof i=="string"?i:i.name).filter(Boolean);a.length>0&&t.recordDiscovery(n.query,a)}}catch{}}return t}clear(){this.discoveredTools.clear(),this.searchHistory=[]}merge(e){for(let t of e.getDiscoveredTools())this.discoveredTools.add(t);this.searchHistory.push(...e.getSearchHistory())}};l();var Be="tool.search",Ne={name:Be,displayName:"Search Tools",category:"meta",description:`Search for available tools by keyword or natural language query.
126
+ `)}}});var Pg,Yr,Cg=f(()=>{"use strict";l();Pg=x(require("mysql2/promise"),1);zr();Yr=class extends Re{async getConnection(){return await Pg.default.createConnection(this.connectionString)}async query(e,t=[]){let o=await this.getConnection();try{let[r]=await o.execute(e,t);return r}finally{await o.end()}}async execute(e,t=[]){let o=await this.getConnection();try{let[r]=await o.execute(e,t);return{changes:r.affectedRows,lastInsertRowid:r.insertId,raw:r}}finally{await o.end()}}async getTables(){let t=await this.query("SHOW TABLES");if(!t||t.length===0)return[];let o=Object.keys(t[0]);return t.map(r=>r[o[0]])}async getSchema(e){if(e){let t=await this.getConnection();try{let[o]=await t.query("DESCRIBE ??",[e]);return o}finally{await t.end()}}else return await this.query("SHOW TABLES")}}});var K,De=f(()=>{"use strict";l();bg();Tg();Cg();K=class{static getAdapter(e){return e.startsWith("postgres://")||e.startsWith("postgresql://")?new Qr(e):e.startsWith("mysql://")?new Yr(e):e.startsWith("sqlite://")?new Eo(e.replace("sqlite://","")):new Eo(e)}}});var No,vg=f(()=>{"use strict";l();wg();De();_();No={name:"db.query",displayName:"Database Query",description:"Execute raw SQL queries against an SQLite, PostgreSQL, or MySQL database.",category:"database",parameters:yg,execute:async n=>{let e=n.db,t=n.sql,o=n.params||[];h(`[db.query] execute db="${e}" sql="${t.substring(0,80)}..." params=${o.length}`);try{let s=await K.getAdapter(e).query(t,o);return JSON.stringify(s,null,2)}catch(r){return`Database query error: ${r instanceof Error?r.message:String(r)}`}}}});var Sg,kg=f(()=>{"use strict";l();Sg={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Optional specific table name to inspect. If omitted, returns structural summary of all tables."}},required:["db"]}});var Ao,$g=f(()=>{"use strict";l();kg();De();Ao={name:"db.schema",displayName:"Database Schema",description:"Get the structural schema of a database or a specific table.",category:"database",parameters:Sg,execute:async n=>{let e=n.db,t=n.table;try{let r=await K.getAdapter(e).getSchema(t);return JSON.stringify(r,null,2)}catch(o){return`Database schema error: ${o instanceof Error?o.message:String(o)}`}}}});var _g,Rg=f(()=>{"use strict";l();_g={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"}},required:["db"]}});var Mo,Dg=f(()=>{"use strict";l();Rg();De();Mo={name:"db.tables",displayName:"Database Tables",description:"List all user tables in the database.",category:"database",parameters:_g,execute:async n=>{let e=n.db;try{let o=await K.getAdapter(e).getTables();return JSON.stringify(o,null,2)}catch(t){return`Database tables error: ${t instanceof Error?t.message:String(t)}`}}}});var Eg,Ng=f(()=>{"use strict";l();Eg={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 Oo,Ag=f(()=>{"use strict";l();Ng();De();Oo={name:"db.insert",displayName:"Database Insert",description:"Insert a new row into an SQLite table safely.",category:"database",parameters:Eg,execute:async n=>{let e=n.db,t=n.table,o=n.data;if(Object.keys(o).length===0)return"Error: No data provided to insert.";try{let r=Object.keys(o).join(", "),s=Object.keys(o).map(()=>"?").join(", "),i=Object.values(o),a=`INSERT INTO ${t} (${r}) VALUES (${s})`,p=await K.getAdapter(e).execute(a,i);return JSON.stringify(p,null,2)}catch(r){return`Database insert error: ${r instanceof Error?r.message:String(r)}`}},confirmation:{level:"medium",reason:"This will insert rows into the database, creating permanent records.",showArgs:["table","data"]}}});var Mg,Og=f(()=>{"use strict";l();Mg={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to 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 Io,Ig=f(()=>{"use strict";l();Og();De();Io={name:"db.update",displayName:"Database Update",description:"Update existing rows in a database table.",category:"database",parameters:Mg,execute:async n=>{let e=n.db,t=n.table,o=n.data,r=n.where;if(Object.keys(o).length===0)return"Error: No data provided to update.";try{let s=Object.keys(o).map(m=>`${m} = ?`).join(", "),i=Object.values(o),a=`UPDATE ${t} SET ${s} WHERE ${r}`,p=await K.getAdapter(e).execute(a,i);return JSON.stringify(p,null,2)}catch(s){return`Database update error: ${s instanceof Error?s.message:String(s)}`}},confirmation:{level:"high",reason:"This will update database rows, potentially affecting multiple records.",showArgs:["table","data","where"]}}});var jg,Lg=f(()=>{"use strict";l();jg={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 jo,Fg=f(()=>{"use strict";l();Lg();De();jo={name:"db.delete",displayName:"Database Delete",description:"Delete rows from a database table.",category:"database",parameters:jg,execute:async n=>{let e=n.db,t=n.table,o=n.where;try{let r=`DELETE FROM ${t} WHERE ${o}`,i=await K.getAdapter(e).execute(r);return JSON.stringify(i,null,2)}catch(r){return`Database delete error: ${r instanceof Error?r.message:String(r)}`}},confirmation:{level:"high",reason:"This will permanently delete rows from the database.",showArgs:["table","where"]}}});var qg,Ug=f(()=>{"use strict";l();qg={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 Lo,Wg=f(()=>{"use strict";l();Ug();De();Lo={name:"db.count",displayName:"Database Count",description:"Count rows in a database table.",category:"database",parameters:qg,execute:async n=>{let e=n.db,t=n.table,o=n.where;try{let r=o?`WHERE ${o}`:"",s=`SELECT COUNT(*) as count FROM ${t} ${r}`,a=await K.getAdapter(e).query(s);return Array.isArray(a)&&a.length>0?`Rows: ${a[0].count}`:"Count: 0"}catch(r){return`Database count error: ${r instanceof Error?r.message:String(r)}`}}}});var Gg={};Z(Gg,{dbCountTool:()=>Lo,dbDeleteTool:()=>jo,dbInsertTool:()=>Oo,dbQueryTool:()=>No,dbSchemaTool:()=>Ao,dbTablesTool:()=>Mo,dbToolsProject:()=>ai,dbUpdateTool:()=>Io});var ai,li=f(()=>{"use strict";l();vg();$g();Dg();Ag();Ig();Fg();Wg();ai={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:[No,Ao,Mo,Oo,Io,jo,Lo],dependencies:{"better-sqlite3":"^11.3.0"}}});var Bg,Kg=f(()=>{"use strict";l();Bg={type:"object",properties:{siteId:{type:"string",description:'The Netlify Site ID to deploy to (e.g. "api_id" from Netlify UI)'},dir:{type:"string",description:'The local directory path to deploy (e.g. "./dist" or "./public")'},message:{type:"string",description:"Optional deployment message/commit note"}},required:["siteId","dir"]}});var Jg,Ee,Vr=f(()=>{"use strict";l();Jg=require("netlify"),Ee=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 Jg.NetlifyAPI(e)}}});var Fo,Hg=f(()=>{"use strict";l();Kg();Vr();_();Fo={name:"cloud.deploy",displayName:"Cloud Deploy",description:"Deploy a static directory to Netlify.",category:"cloud",parameters:Bg,execute:async n=>{let e=n.siteId,t=n.dir,o=n.message;h(`[cloud.deploy] execute siteId="${e}" dir="${t}" message="${o??"none"}"`);try{let s=await Ee.getClient().deploy(e,t,{message:o||"Deployed via Toolpack SDK",draft:!1});return JSON.stringify({id:s.deployId,url:s.deploy.url,admin_url:s.deploy.admin_url,state:s.deploy.state},null,2)}catch(r){return`Cloud deployment error: ${r instanceof Error?r.message:String(r)}`}},confirmation:{level:"high",reason:"This will deploy to production (live site).",showArgs:["siteId","dir"]}}});var zg,Qg=f(()=>{"use strict";l();zg={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 qo,Yg=f(()=>{"use strict";l();Qg();Vr();qo={name:"cloud.status",displayName:"Cloud Status",description:"Check the status of a specific Netlify deployment.",category:"cloud",parameters:zg,execute:async n=>{let e=n.siteId,t=n.deployId;try{let r=await Ee.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 Vg,Xg=f(()=>{"use strict";l();Vg={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 Uo,Zg=f(()=>{"use strict";l();Xg();Vr();_();Uo={name:"cloud.list",displayName:"Cloud Deployments List",description:"List recent deployments for a Netlify site.",category:"cloud",parameters:Vg,execute:async n=>{let e=n.siteId,t=n.limit||5;h(`[cloud.list] execute siteId="${e}" limit=${t}`);try{let r=await Ee.getClient().listSiteDeploys({site_id:e,page:1,per_page:t});if(!Array.isArray(r))return"Unexpected response format from Netlify API";let s=r.map(i=>({id:i.id,state:i.state,created_at:i.created_at,url:i.url,branch:i.branch,title:i.title}));return JSON.stringify(s,null,2)}catch(o){return`Cloud list error: ${o instanceof Error?o.message:String(o)}`}}}});var eh={};Z(eh,{cloudDeployTool:()=>Fo,cloudListTool:()=>Uo,cloudStatusTool:()=>qo,cloudToolsProject:()=>ci});var ci,pi=f(()=>{"use strict";l();Hg();Yg();Zg();ci={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:[Fo,qo,Uo],dependencies:{netlify:"^13.1.20"}}});var gw={};Z(gw,{AGENT_MODE:()=>fi,AGENT_PLANNING_PROMPT:()=>dn,AGENT_STEP_PROMPT:()=>un,AGENT_WORKFLOW:()=>mi,AIClient:()=>so,AnthropicAdapter:()=>ao,AuthenticationError:()=>fe,BM25SearchEngine:()=>ze,BUILT_IN_MODES:()=>Bo,CHAT_MODE:()=>gi,CHAT_WORKFLOW:()=>ui,CODING_PLANNING_PROMPT:()=>ah,CODING_STEP_PROMPT:()=>lh,CODING_WORKFLOW:()=>di,CONFIG_DIR_NAME:()=>bi,CONFIG_FILE_NAME:()=>xi,ConnectionError:()=>Te,DEFAULT_MODE_NAME:()=>Be,DEFAULT_TOOLS_CONFIG:()=>H,DEFAULT_TOOL_SEARCH_CONFIG:()=>$i,DEFAULT_WORKFLOW:()=>iw,DEFAULT_WORKFLOW_CONFIG:()=>fn,GeminiAdapter:()=>lo,InvalidRequestError:()=>M,McpClient:()=>Vt,McpConnectionError:()=>me,McpTimeoutError:()=>Wo,McpToolManager:()=>Go,ModeRegistry:()=>Xt,OllamaAdapter:()=>ve,OllamaProvider:()=>Ze,OpenAIAdapter:()=>uo,PageError:()=>hn,Planner:()=>Zt,ProviderAdapter:()=>Y,ProviderError:()=>q,RateLimitError:()=>ge,SDKError:()=>W,StepExecutor:()=>to,TOOLPACK_DIR_NAME:()=>wi,TOOL_SEARCH_NAME:()=>Qe,TimeoutError:()=>yn,ToolDiscoveryCache:()=>Oe,ToolRegistry:()=>Yt,ToolRouter:()=>Ye,Toolpack:()=>yi,WorkflowExecutor:()=>Ko,addBypassRule:()=>zi,cloudDeployTool:()=>Fo,cloudListTool:()=>Uo,cloudStatusTool:()=>qo,cloudToolsProject:()=>ci,codingFindSymbolTool:()=>Jt,codingGetImportsTool:()=>zt,codingGetSymbolsTool:()=>Ht,codingToolsProject:()=>Xs,createMcpToolProject:()=>pn,createMode:()=>ch,createToolProject:()=>th,dbCountTool:()=>Lo,dbDeleteTool:()=>jo,dbInsertTool:()=>Oo,dbQueryTool:()=>No,dbSchemaTool:()=>Ao,dbTablesTool:()=>Mo,dbToolsProject:()=>ai,dbUpdateTool:()=>Io,diffApplyTool:()=>Ro,diffCreateTool:()=>_o,diffPreviewTool:()=>Do,diffToolsProject:()=>ri,disconnectMcpToolProject:()=>mn,ensureGlobalConfigDir:()=>Ci,ensureLocalConfigDir:()=>mw,execKillTool:()=>St,execListProcessesTool:()=>kt,execReadOutputTool:()=>vt,execRunBackgroundTool:()=>Ct,execRunShellTool:()=>Pt,execRunTool:()=>Tt,execToolsProject:()=>ns,fetchUrlAsBase64:()=>Sn,fsAppendFileTool:()=>st,fsCopyTool:()=>ft,fsCreateDirTool:()=>dt,fsDeleteFileTool:()=>at,fsExistsTool:()=>lt,fsListDirTool:()=>pt,fsMoveTool:()=>ut,fsReadFileRangeTool:()=>ht,fsReadFileTool:()=>tt,fsReplaceInFileTool:()=>wt,fsSearchTool:()=>yt,fsStatTool:()=>ct,fsToolsProject:()=>Yn,fsTreeTool:()=>xt,fsWriteFileTool:()=>rt,generateToolCategoriesPrompt:()=>Vo,getDefaultSlmModel:()=>Yi,getGlobalConfigDir:()=>Ti,getGlobalConfigPath:()=>Jo,getGlobalToolpackDir:()=>uh,getLocalConfigDir:()=>Pi,getLocalConfigPath:()=>Ho,getLocalToolpackDir:()=>fh,getMimeType:()=>Tn,getOllamaBaseUrl:()=>mo,getOllamaProviderEntries:()=>Hi,getRegisteredSlmModels:()=>Xi,getRuntimeConfigStatus:()=>uw,getToolSearchSchema:()=>Qo,getToolpackConfig:()=>rr,getUserHomeDir:()=>dh,gitAddTool:()=>Po,gitBlameTool:()=>vo,gitBranchCreateTool:()=>ko,gitBranchListTool:()=>So,gitCheckoutTool:()=>$o,gitCommitTool:()=>Co,gitDiffTool:()=>xo,gitLogTool:()=>To,gitStatusTool:()=>bo,gitToolsProject:()=>ei,httpDeleteTool:()=>Ot,httpDownloadTool:()=>jt,httpGetTool:()=>Nt,httpPostTool:()=>At,httpPutTool:()=>Mt,httpToolsProject:()=>xs,initializeGlobalConfigIfFirstRun:()=>fw,isDataUri:()=>Pn,isRegisteredSlm:()=>Vi,isToolSearchTool:()=>Yo,k8sApplyManifestTool:()=>tn,k8sDeleteResourceTool:()=>on,k8sDescribeTool:()=>Zr,k8sGetConfigMapTool:()=>sn,k8sGetLogsTool:()=>en,k8sGetNamespacesTool:()=>ln,k8sListDeploymentsTool:()=>nn,k8sListPodsTool:()=>Xr,k8sListServicesTool:()=>rn,k8sSwitchContextTool:()=>an,k8sToolsProject:()=>nh,k8sWaitForDeploymentTool:()=>cn,loadFullConfig:()=>ho,loadRuntimeConfig:()=>dw,loadToolsConfig:()=>Ft,normalizeImagePart:()=>Gi,ollamaRequest:()=>ie,ollamaStream:()=>sr,parseDataUri:()=>Cn,readFileAsBase64:()=>vn,reloadToolpackConfig:()=>nr,removeBypassRule:()=>Qi,saveToolsConfig:()=>Om,systemCwdTool:()=>Dt,systemDiskUsageTool:()=>Et,systemEnvTool:()=>_t,systemInfoTool:()=>$t,systemSetEnvTool:()=>Rt,systemToolsProject:()=>us,toDataUri:()=>Wi,toolSearchDefinition:()=>Ie,webExtractLinksTool:()=>Wt,webFetchTool:()=>Lt,webScrapeTool:()=>Ut,webSearchTool:()=>qt,webToolsProject:()=>Ms});module.exports=vh(gw);l();le();l();var Fi=require("events");le();l();l();l();var He={name:3,displayName:2.5,description:2,category:1.5,parameterNames:1,parameterDescriptions:.5},ze=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 s of r)this.docFrequencies.set(s,(this.docFrequencies.get(s)||0)+1)}this.totalDocs=this.documents.length,this.computeIDF(),this.avgDocLength=this.computeAvgDocLength()}search(e,t){let o=t?.limit??5,r=t?.category,s=t?.minScore??0,i=this.tokenize(e.toLowerCase());if(i.length===0)return[];let a=[];for(let c of this.documents){if(r&&c.tool.category!==r)continue;let p=this.computeBM25Score(i,c);p>s&&a.push({toolName:c.toolName,score:p,tool:c.tool})}return a.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 i=0;i<He.name;i++)t.push(e.name);for(let i=0;i<He.displayName;i++)t.push(e.displayName);for(let i=0;i<He.description;i++)t.push(e.description);for(let i=0;i<He.category;i++)t.push(e.category);if(e.parameters?.properties)for(let[i,a]of Object.entries(e.parameters.properties)){for(let c=0;c<He.parameterNames;c++)t.push(i);if(a.description)for(let c=0;c<He.parameterDescriptions;c++)t.push(a.description)}let o=t.join(" ").toLowerCase(),r=this.tokenize(o),s=this.computeTermFrequencies(r);return{toolName:e.name,tool:e,text:o,tokens:r,length:r.length,termFrequencies:s}}tokenize(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1).filter(t=>!Sh.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 s=t.termFrequencies.get(r)||0;if(s===0)continue;let i=this.idf.get(r)||0,a=t.length,c=s*(this.k1+1),p=s+this.k1*(1-this.b+this.b*(a/this.avgDocLength));o+=i*(c/p)}return o}toSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category}}},Sh=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 Oe=class n{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 n;for(let o of e)if(o.role==="tool"){let r=o;if(typeof r.content=="string")try{let s=JSON.parse(r.content);if(s.query&&s.tools&&Array.isArray(s.tools)){let i=s.tools.map(a=>typeof a=="string"?a:a.name).filter(Boolean);i.length>0&&t.recordDiscovery(s.query,i)}}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 Qe="tool.search",Ie={name:Qe,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 Bo(){return{name:Ne.name,displayName:Ne.displayName,description:Ne.description,parameters:Ne.parameters,category:Ne.category}}function Jo(s){return s===Be}l();var rh={filesystem:"File operations (read, write, delete, list, search files)",network:"HTTP requests and web scraping (GET, POST, fetch pages, extract data)",execution:"Run shell commands and manage processes",system:"System information, environment variables, disk usage",meta:"Tool discovery and management"};function Ho(s){let e=s.getCategories();if(e.length===0)return"No tools are currently available.";let t=["You have access to tools in the following categories:",""];for(let r of e){let n=s.getByCategory(r).length,a=rh[r]||r;t.push(`- **${r}** (${n} tools): ${a}`)}return t.push(""),t.push("Use `tool.search` to discover specific tools when needed."),t.push('Example: tool.search({ query: "read file" }) to find file reading tools.'),t.join(`
132
- `)}var Je=class{discoveryCache=new De;async resolve(e,t,r){return r.enabled?r.toolSearch?.enabled?this.resolveWithToolSearch(e,t,r):this.resolveLegacy(t,r):[]}getDiscoveryCache(){return this.discoveryCache}clearDiscoveryCache(){this.discoveryCache.clear()}resolveWithToolSearch(e,t,r){let o=[],n=new Set;o.push(Bo()),n.add(Be);let a=r.toolSearch?.alwaysLoadedTools??[];for(let c of a){let p=t.get(c);p&&!n.has(c)&&(o.push(this.toSchema(p)),n.add(c))}let i=r.toolSearch?.alwaysLoadedCategories??[];for(let c of i)for(let p of t.getByCategory(c))n.has(p.name)||(o.push(this.toSchema(p)),n.add(p.name));if(r.toolSearch?.cacheDiscoveredTools!==!1){let c=De.fromMessages(e);this.discoveryCache.merge(c);let p=this.discoveryCache.getDiscoveredTools();for(let m of p){let u=t.get(m);u&&!n.has(m)&&u.cacheable!==!1&&(o.push(this.toSchema(u)),n.add(m))}}return o}resolveLegacy(e,t){let r;if(t.enabledTools.length===0&&t.enabledToolCategories.length===0)r=e.getEnabled();else{let o=e.getByNames(t.enabledTools),n=e.getByCategories(t.enabledToolCategories),a=new Set;r=[];for(let i of[...o,...n])a.has(i.name)||(a.add(i.name),r.push(i))}return r.map(o=>this.toSchema(o))}toSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category}}};Xt();l();function pi(s){if(s.disabled)return"";let e=s.includeWorkingDirectory!==!1,t=s.includeToolCategories!==!1,r=e?`
133
- Working directory: ${s.workingDirectory}`:"",o=t&&s.toolCategories.length>0?`
134
- Available tool categories: ${s.toolCategories.join(", ")}`:"";return`You are an AI assistant with access to tools that let you interact with the user's system.${r}${o}
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 Qo(){return{name:Ie.name,displayName:Ie.displayName,description:Ie.description,parameters:Ie.parameters,category:Ie.category}}function Yo(n){return n===Qe}l();var kh={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 Vo(n){let e=n.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 s=n.getByCategory(o).length,i=kh[o]||o;t.push(`- **${o}** (${s} tools): ${i}`)}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 Ye=class{discoveryCache=new Oe;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=[],s=new Set;r.push(Qo()),s.add(Qe);let i=o.toolSearch?.alwaysLoadedTools??[];for(let c of i){let p=t.get(c);p&&!s.has(c)&&(r.push(this.toSchema(p)),s.add(c))}let a=o.toolSearch?.alwaysLoadedCategories??[];for(let c of a)for(let p of t.getByCategory(c))s.has(p.name)||(r.push(this.toSchema(p)),s.add(p.name));if(o.toolSearch?.cacheDiscoveredTools!==!1){let c=Oe.fromMessages(e);this.discoveryCache.merge(c);let p=this.discoveryCache.getDiscoveredTools();for(let m of p){let u=t.get(m);u&&!s.has(m)&&u.cacheable!==!1&&(r.push(this.toSchema(u)),s.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),s=e.getByCategories(t.enabledToolCategories),i=new Set;o=[];for(let a of[...r,...s])i.has(a.name)||(i.add(a.name),o.push(a))}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}}};ro();l();function _i(n){if(n.disabled)return"";let e=n.includeWorkingDirectory!==!1,t=n.includeToolCategories!==!1,o=e?`
133
+ Working directory: ${n.workingDirectory}`:"",r=t&&n.toolCategories.length>0?`
134
+ Available tool categories: ${n.toolCategories.join(", ")}`:"";return`You are an AI assistant with access to tools that let you interact with the user's system.${o}${r}
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 He=class{analyticalPatterns=[/\b(analyze|find|search|check|list|show)\b/i,/\b(biggest|largest|smallest|most|least|all|every|count)\b/i,/\b(explain|understand|review|audit|inspect|examine)\b/i,/\b(compare|difference|similar|match|pattern)\b/i,/\b(what|where|how many|which|who|when|why|how)\b/i,/\?$/];actionPatterns=[/\b(create|write|update|modify|edit|patch|delete|remove|rename|move|copy)\b/i,/\b(run|execute|start|stop|restart|deploy|install|build)\b/i,/\b(fix|refactor|implement|add|change|replace|insert)\b/i,/\b(make|do|set|configure|setup|initialize)\b/i];classify(e){if(!e||e.trim().length===0)return{type:"conversational",confidence:0};let t=e.toLowerCase(),r=this.analyticalPatterns.filter(i=>i.test(t)).length,o=this.actionPatterns.filter(i=>i.test(t)).length,n=r/this.analyticalPatterns.length,a=o/this.actionPatterns.length;if(r>o&&r>0){let i=Math.min(n,1);return o>0&&(i=Math.min(i,.5)),{type:"analytical",confidence:i,reasoning:`Matched ${r} analytical patterns${o>0?`, ${o} action patterns (capped confidence)`:""}`}}else return o>r&&o>0?{type:"action",confidence:Math.min(a,1),reasoning:`Matched ${o} action patterns`}:r===o&&r>0?{type:"analytical",confidence:.5,reasoning:`Mixed query (${r} analytical, ${o} action patterns)`}:{type:"conversational",confidence:.3,reasoning:"No strong analytical or action patterns detected"}}getToolRoundsAdjustment(e,t){return e.type==="analytical"&&e.confidence>.6?Math.min(t+3,10):(e.type==="action"&&e.confidence>.6,t)}};l();var zo=class{analyzeDependencies(e){let t=[];for(let r=0;r<e.length;r++){let o=e[r],n=[],a=JSON.stringify(o.arguments).toLowerCase();for(let i=0;i<r;i++){let c=e[i];this.hasDependency(o,c,a)&&n.push(c.id)}t.push({toolCallId:o.id,dependsOn:n})}return t}hasDependency(e,t,r){return!!(e.arguments.path&&t.arguments.path&&e.arguments.path===t.arguments.path||e.arguments.file_path&&t.arguments.file_path&&e.arguments.file_path===t.arguments.file_path||e.arguments.filePath&&t.arguments.filePath&&e.arguments.filePath===t.arguments.filePath||["fs.write_file","fs.delete_file","fs.move","fs.copy","fs.replace_in_file","fs.append_file"].includes(e.name)&&t.arguments.path&&r.includes(t.arguments.path.toLowerCase())||e.name==="exec.read_output"&&t.name==="exec.run_background"||e.name==="http.download"&&t.name==="http.get"&&t.arguments.url&&r.includes(t.arguments.url.toLowerCase()))}async executeWithDependencies(e,t,r=5){if(e.length===0)return new Map;let o=this.analyzeDependencies(e),n=new Map,a=new Set;for(;a.size<e.length;){let i=[];for(let p of e){if(a.has(p.id))continue;(o.find(g=>g.toolCallId===p.id)?.dependsOn.every(g=>a.has(g))??!0)&&i.push(p)}if(i.length===0){let p=e.filter(m=>!a.has(m.id));throw new Error(`Circular dependency detected in tool calls: ${p.map(m=>m.name).join(", ")}`)}let c=await this.executeBatchWithLimit(i,t,r);for(let{id:p,result:m}of c)n.set(p,m),a.add(p)}return n}async executeBatchWithLimit(e,t,r){let o=[];if(e.length<=r){let n=e.map(async a=>{let i=await t(a);return{id:a.id,result:i}});return await Promise.all(n)}for(let n=0;n<e.length;n+=r){let i=e.slice(n,n+r).map(async p=>{let m=await t(p);return{id:p.id,result:m}}),c=await Promise.all(i);o.push(...c)}return o}shouldUseParallelExecution(e){return e.length<2?!1:this.analyzeDependencies(e).filter(o=>o.dependsOn.length===0).length>=2}};l();function Ae(s){for(let e=s.length-1;e>=0;e--){let t=s[e];if(t?.role!=="user")continue;let r=t?.content;return typeof r=="string"?r:Array.isArray(r)?r.map(o=>o?.type==="text"?o.text:"").filter(Boolean).join(`
140
- `):""}return""}k();var gi=0;function tn(){return gi+=1,`${Date.now()}-${gi}`}function Yo(s,e){Me("debug")&&(h(`[AIClient][${s}] Messages (${e.length}):`),e.forEach((t,r)=>{let o=D(t.content,300);h(`[AIClient][${s}] #${r} role=${t.role} content=${o}`)}))}function hi(s){let e=Ae(s).toLowerCase();return e?[/\b(list|show|print|display)\b.*\b(files|folders|directory|dir)\b/,/\b(current|this)\b.*\b(directory|folder|repo|repository)\b/,/\b(read|open|view)\b.*\b(file|log|config|json|yaml|env)\b/,/\b(write|create|update|modify|edit|patch|delete|remove|rename|move|copy)\b.*\b(file|folder|directory)\b/,/\b(run|execute)\b.*\b(command|shell|script|tests?)\b/,/\b(http|get|post|put|delete|download|fetch|curl)\b/,/\b(web|search|scrape|crawl|map)\b/,/https?:\/\//].some(r=>r.test(e)):!1}function yi(s,e){let t=-1;for(let o=s.length-1;o>=0;o--){let n=s[o];if(n.role==="tool"||n.role==="assistant"&&n.tool_calls&&n.tool_calls.length>0){t=o;break}}if(t===-1)return!1;let r=s.length-1-t;return r>0&&r<=e}function wi(s){return{openai:"gpt-4.1-mini",anthropic:"claude-3-haiku-20240307",gemini:"gemini-2.0-flash-exp",ollama:"llama3.2"}[s]||"default"}function sh(s){let e=[],t=0;for(let r=s.length-1;r>=0&&t<2;r--){let o=s[r];if(o.role==="assistant"&&o.tool_calls&&o.tool_calls.length>0){t++;for(let n of o.tool_calls){let a=n.function?.name||"unknown",i=n.function?.arguments,c=`Tool: ${a}`;if(i)try{let p=typeof i=="string"?JSON.parse(i):i;p.url&&(c+=` (URL: ${p.url})`),p.file_path&&(c+=` (File: ${p.file_path})`),p.section&&(c+=` (Section: ${p.section})`),p.query&&(c+=` (Query: ${p.query})`),p.command&&(c+=` (Command: ${p.command.substring(0,50)})`)}catch{}e.push(c)}}}return e.length>0?e.join(", "):"None"}async function bi(s,e,t,r){let o=tn();h(`[AIClient][${o}] inferNeedsToolsWithAI() provider=${e} model=${r}`);let n=sh(t),i=t.filter(p=>p.role==="user").slice(-1)[0]?.content||"",c=`Recent tool usage: ${n}
139
+ - Only ask the user for clarification when you genuinely cannot determine their intent or lack the required tools`}l();var Ve=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(a=>a.test(t)).length,r=this.actionPatterns.filter(a=>a.test(t)).length,s=o/this.analyticalPatterns.length,i=r/this.actionPatterns.length;if(o>r&&o>0){let a=Math.min(s,1);return r>0&&(a=Math.min(a,.5)),{type:"analytical",confidence:a,reasoning:`Matched ${o} analytical patterns${r>0?`, ${r} action patterns (capped confidence)`:""}`}}else return r>o&&r>0?{type:"action",confidence:Math.min(i,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 Xo=class{analyzeDependencies(e){let t=[];for(let o=0;o<e.length;o++){let r=e[o],s=[],i=JSON.stringify(r.arguments).toLowerCase();for(let a=0;a<o;a++){let c=e[a];this.hasDependency(r,c,i)&&s.push(c.id)}t.push({toolCallId:r.id,dependsOn:s})}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),s=new Map,i=new Set;for(;i.size<e.length;){let a=[];for(let p of e){if(i.has(p.id))continue;(r.find(g=>g.toolCallId===p.id)?.dependsOn.every(g=>i.has(g))??!0)&&a.push(p)}if(a.length===0){let p=e.filter(m=>!i.has(m.id));throw new Error(`Circular dependency detected in tool calls: ${p.map(m=>m.name).join(", ")}`)}let c=await this.executeBatchWithLimit(a,t,o);for(let{id:p,result:m}of c)s.set(p,m),i.add(p)}return s}async executeBatchWithLimit(e,t,o){let r=[];if(e.length<=o){let s=e.map(async i=>{let a=await t(i);return{id:i.id,result:a}});return await Promise.all(s)}for(let s=0;s<e.length;s+=o){let a=e.slice(s,s+o).map(async p=>{let m=await t(p);return{id:p.id,result:m}}),c=await Promise.all(a);r.push(...c)}return r}shouldUseParallelExecution(e){return e.length<2?!1:this.analyzeDependencies(e).filter(r=>r.dependsOn.length===0).length>=2}};l();function je(n){for(let e=n.length-1;e>=0;e--){let t=n[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""}_();var Ai=0;function xn(){return Ai+=1,`${Date.now()}-${Ai}`}function tr(n,e){Le("debug")&&(h(`[AIClient][${n}] Messages (${e.length}):`),e.forEach((t,o)=>{let r=A(t.content,300);h(`[AIClient][${n}] #${o} role=${t.role} content=${r}`)}))}function Mi(n){let e=je(n).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 Oi(n,e){let t=-1;for(let r=n.length-1;r>=0;r--){let s=n[r];if(s.role==="tool"||s.role==="assistant"&&s.tool_calls&&s.tool_calls.length>0){t=r;break}}if(t===-1)return!1;let o=n.length-1-t;return o>0&&o<=e}function Ii(n){return{openai:"gpt-4.1-mini",anthropic:"claude-3-haiku-20240307",gemini:"gemini-2.0-flash-exp",ollama:"llama3.2"}[n]||"default"}function _h(n){let e=[],t=0;for(let o=n.length-1;o>=0&&t<2;o--){let r=n[o];if(r.role==="assistant"&&r.tool_calls&&r.tool_calls.length>0){t++;for(let s of r.tool_calls){let i=s.function?.name||"unknown",a=s.function?.arguments,c=`Tool: ${i}`;if(a)try{let p=typeof a=="string"?JSON.parse(a):a;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 ji(n,e,t,o){let r=xn();h(`[AIClient][${r}] inferNeedsToolsWithAI() provider=${e} model=${o}`);let s=_h(t),a=t.filter(p=>p.role==="user").slice(-1)[0]?.content||"",c=`Recent tool usage: ${s}
141
141
 
142
- User's new message: "${i}"
142
+ User's new message: "${a}"
143
143
 
144
144
  Does this message:
145
145
  1. Ask about the same topic/context as recent tools? OR
@@ -148,27 +148,27 @@ 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:r,messages:[{role:"user",content:c}],max_tokens:10,temperature:0})).content||"").trim().toUpperCase(),u=m.startsWith("YES");return h(`[AIClient][${o}] inferNeedsToolsWithAI() context="${n}" message="${i.substring(0,50)}" result=${u} (raw: ${m})`),u}catch(p){return E(`[AIClient][${o}] inferNeedsToolsWithAI() error=${p} - falling back to false`),!1}}function xi(s){let e=Ae(s).toLowerCase();if(!e)return!1;let t=[/\b(list|show|print|display)\b.*\b(files|folders|directory|dir)\b/,/\b(current|this)\b.*\b(directory|folder|repo|repository)\b/,/\b(read|open|view)\b.*\b(file|log|config|json|yaml|env)\b/],r=[/\b(write|create|update|modify|edit|patch|delete|remove|rename|move|copy)\b/,/\b(run|execute)\b.*\b(command|shell|script|tests?)\b/,/\b(http|get|post|put|delete|download|fetch|curl)\b/,/\b(web|search|scrape|crawl)\b/];return t.some(o=>o.test(e))&&!r.some(o=>o.test(e))}var eo=class extends Ti.EventEmitter{providers;defaultProvider;toolRegistry;toolsConfig;toolRouter;bm25Engine;queryClassifier;toolOrchestrator;activeMode=null;overrideSystemPrompt;disableBaseContext;toolResultMaxChars;constructor(e){super(),this.providers=new Map(Object.entries(e.providers)),this.defaultProvider=e.defaultProvider,this.toolRegistry=e.toolRegistry,this.toolsConfig=e.toolsConfig||H,this.toolRouter=new Je,this.bm25Engine=new Ge,this.queryClassifier=new He,this.toolOrchestrator=new zo,this.overrideSystemPrompt=e.systemPrompt,this.disableBaseContext=e.disableBaseContext||!1;let t=this.toolsConfig.resultMaxChars??H.resultMaxChars??2e4;this.toolResultMaxChars=Number.isFinite(t)&&t>0?t:2e4,this.toolRegistry&&this.bm25Engine.index(this.toolRegistry.getAll())}registerProvider(e,t){this.providers.set(e,t)}getProvider(e){let t=e||this.defaultProvider;if(!t)throw new J("No provider specified and no default provider configured","NO_PROVIDER_CONFIGURED",400);let r=this.providers.get(t);if(!r)throw new J(`Provider '${t}' not found`,"PROVIDER_NOT_FOUND",404);return r}setDefaultProvider(e){if(!this.providers.has(e))throw new J(`Provider '${e}' not found`,"PROVIDER_NOT_FOUND",404);this.defaultProvider=e}getToolRegistry(){return this.toolRegistry}getProviders(){return new Map(this.providers)}setToolRegistry(e){this.toolRegistry=e}setToolsConfig(e){this.toolsConfig=e}setSystemPrompt(e){this.overrideSystemPrompt=e}setMode(e){this.activeMode=e,v(`[AIClient] Mode set to: ${e?e.displayName:"none (cleared)"}`)}getMode(){return this.activeMode}getQueryClassifier(){return this.queryClassifier}reindexTools(){this.toolRegistry&&(this.bm25Engine.index(this.toolRegistry.getAll()),v(`[AIClient] Re-indexed ${this.bm25Engine.getIndexedCount()} tools for BM25 search`))}clearToolDiscoveryCache(){this.toolRouter.clearDiscoveryCache()}async generate(e,t){let r=this.getProvider(t);try{let o=tn(),n=this.injectBaseAgentContext(e);n=this.injectOverrideSystemPrompt(n),n=this.injectModeSystemPrompt(n);let a=t||this.defaultProvider,i=await this.enrichRequestWithTools(n),c=process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||this.toolsConfig.toolChoicePolicy||"auto",p=(i.tools?.length||0)>0,m=i.tool_choice!=null,u=hi(i.messages),g=this.toolsConfig.intelligentToolDetection,w=!1;if(!u&&g?.enabled&&p&&yi(i.messages,g.maxFollowUpMessages)){v(`[AIClient][${o}] Message is after tool call, using AI to infer tool needs`);let R=wi(a||"openai");u=await bi(r,a||"openai",i.messages,R),w=!0}let y=xi(i.messages);!m&&p&&(c==="required"||c==="required_for_actions"&&u)?i.tool_choice="required":!m&&p&&w&&!u&&(i.tool_choice="none",v(`[AIClient][${o}] AI inference determined no tools needed, setting tool_choice=none`));let $=r?.constructor?.name||"UnknownProvider",C={...i,__toolpack_request_id:o};v(`[AIClient][${o}] generate() start provider=${a} class=${$} model=${i.model} messages=${i.messages.length} tools=${i.tools?.length||0} tool_choice=${i.tool_choice??"unset"} policy=${c} needsTools=${u} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),Yo(o,i.messages);let x=await r.generate(C);if(h(`[AIClient][${o}] generate() initial response finish_reason=${x.finish_reason??"unknown"} tool_calls=${x.tool_calls?.length||0} content_preview=${D(x.content||"",200)}`),this.toolsConfig.enabled&&this.toolsConfig.autoExecute&&this.toolRegistry){let S=Ae(i.messages),R=this.queryClassifier.classify(S),j=this.toolsConfig.maxToolRounds,U=this.queryClassifier.getToolRoundsAdjustment(R,j);U!==j?v(`[AIClient][${o}] Query classified as ${R.type} (confidence: ${R.confidence.toFixed(2)}), adjusted maxToolRounds: ${j} \u2192 ${U}`):h(`[AIClient][${o}] Query classified as ${R.type} (confidence: ${R.confidence.toFixed(2)}), keeping maxToolRounds: ${U}`);let L=0,F=[...i.messages];for(x.tool_calls&&x.tool_calls.length>0&&v(`[AIClient] Received ${x.tool_calls.length} tool call(s): ${x.tool_calls.map(B=>B.name).join(", ")}`);x.tool_calls&&x.tool_calls.length>0&&L<U;){L++,v(`[AIClient][${o}] generate() tool round ${L}/${U} tool_calls=${x.tool_calls.length}`),F.push({role:"assistant",content:x.content||"",tool_calls:x.tool_calls.map(W=>({id:W.id,type:"function",function:{name:W.name,arguments:JSON.stringify(W.arguments)}}))});let B=this.toolOrchestrator.shouldUseParallelExecution(x.tool_calls),ke=3,ge=x.tool_calls,le=x.tool_calls.filter(W=>W.name==="web.fetch");if(le.length>ke){v(`[AIClient][${o}] Limiting web.fetch calls from ${le.length} \u2192 ${ke} to prevent context overflow`);let W=le.slice(0,ke);ge=[...x.tool_calls.filter(_=>_.name!=="web.fetch"),...W];let O=le.slice(ke);for(let _ of O)F.push({role:"tool",tool_call_id:_.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let ee=5e4,ce=0;if(B){v(`[AIClient][${o}] Using parallel execution for ${ge.length} tools`);let W=await this.toolOrchestrator.executeWithDependencies(ge,O=>this.executeTool(O),5),te=!1;for(let O of ge){if(te){F.push({role:"tool",tool_call_id:O.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let _=W.get(O.id),oe=typeof _=="string"?_:JSON.stringify(_);if(ce+oe.length>ee){E(`[AIClient][${o}] Tool output budget exceeded (${ee} chars), adding placeholder for remaining tools`),F.push({role:"tool",tool_call_id:O.id,content:"[Skipped: tool output budget exceeded for this round]"}),te=!0;continue}let re=typeof _=="string"&&_.length>this.toolResultMaxChars?`${_.slice(0,this.toolResultMaxChars)}
152
- [TRUNCATED tool result: ${_.length} chars]`:_,Re=typeof re=="string"?re:JSON.stringify(re);ce+=Re.length,F.push({role:"tool",tool_call_id:O.id,content:re})}h(`[AIClient][${o}] Round tool output size: ${ce} chars (budget: ${ee})`)}else{v(`[AIClient][${o}] Using sequential execution for ${ge.length} tools`);let W=!1;for(let te of ge){if(W){F.push({role:"tool",tool_call_id:te.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let O=await this.executeTool(te),_=typeof O=="string"?O:JSON.stringify(O);if(ce+_.length>ee){E(`[AIClient][${o}] Tool output budget exceeded (${ee} chars), adding placeholder for remaining tools`),F.push({role:"tool",tool_call_id:te.id,content:"[Skipped: tool output budget exceeded for this round]"}),W=!0;continue}let oe=typeof O=="string"&&O.length>this.toolResultMaxChars?`${O.slice(0,this.toolResultMaxChars)}
153
- [TRUNCATED tool result: ${O.length} chars]`:O,re=typeof oe=="string"?oe:JSON.stringify(oe);ce+=re.length,F.push({role:"tool",tool_call_id:te.id,content:oe})}h(`[AIClient][${o}] Round tool output size: ${ce} chars (budget: ${ee})`)}let Ue={...i,messages:F,__toolpack_request_id:o},he=await this.enrichRequestWithTools(Ue);he.tool_choice==="required"&&(he.tool_choice=y?"none":"auto",v(`[AIClient][${o}] generate() followup tool_choice override required->${he.tool_choice}`)),Me("debug")&&(h(`[AIClient][${o}] generate() followup request messages=${F.length}`),Yo(o,F)),x=await r.generate(he),h(`[AIClient][${o}] generate() followup response finish_reason=${x.finish_reason??"unknown"} tool_calls=${x.tool_calls?.length||0} content_preview=${D(x.content||"",200)}`)}}return x}catch(o){throw this.wrapError(o)}}async*stream(e,t){let r=this.getProvider(t);try{let o=tn(),n=t||this.defaultProvider,a=this.injectBaseAgentContext(e);a=this.injectOverrideSystemPrompt(a),a=this.injectModeSystemPrompt(a);let i=await this.enrichRequestWithTools(a),c=process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||this.toolsConfig.toolChoicePolicy||"auto",p=(i.tools?.length||0)>0,m=i.tool_choice!=null,u=hi(i.messages),g=this.toolsConfig.intelligentToolDetection,w=!1;if(!u&&g?.enabled&&p&&yi(i.messages,g.maxFollowUpMessages)){v(`[AIClient][${o}] Message is after tool call, using AI to infer tool needs`);let B=wi(n||"openai");u=await bi(r,n||"openai",i.messages,B),w=!0}let y=xi(i.messages);!m&&p&&(c==="required"||c==="required_for_actions"&&u)?i.tool_choice="required":!m&&p&&w&&!u&&(i.tool_choice="none",v(`[AIClient][${o}] AI inference determined no tools needed, setting tool_choice=none`));let $=r?.constructor?.name||"UnknownProvider",C={...i,__toolpack_request_id:o};if(v(`[AIClient][${o}] stream() start provider=${n} class=${$} model=${i.model} messages=${i.messages.length} tools=${i.tools?.length||0} tool_choice=${i.tool_choice??"unset"} policy=${c} needsTools=${u} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),Yo(o,i.messages),!this.toolsConfig.enabled||!this.toolsConfig.autoExecute||!this.toolRegistry){yield*r.stream(C);return}let x=[...i.messages],S=0,R=Ae(i.messages),j=this.queryClassifier.classify(R),U=this.toolsConfig.maxToolRounds,L=this.queryClassifier.getToolRoundsAdjustment(j,U);for(L!==U&&v(`[AIClient][${o}] stream() Query classified as ${j.type} (confidence: ${j.confidence.toFixed(2)}), adjusted maxToolRounds: ${U} \u2192 ${L}`);S<=L;){if(e.signal?.aborted){v(`[AIClient][${o}] stream() aborted by signal`);return}let F="",B=[];v(`[AIClient][${o}] stream() round_start ${S+1}/${L}`);let ke=null,ge={...C,messages:x},le=await this.enrichRequestWithTools(ge);S>0&&le.tool_choice==="required"&&(le.tool_choice=y?"none":"auto",v(`[AIClient][${o}] stream() round_${S+1} tool_choice override required->${le.tool_choice}`));for await(let _ of r.stream(le)){if(e.signal?.aborted){v(`[AIClient][${o}] stream() aborted by signal during chunk processing`);return}_.tool_calls&&_.tool_calls.length>0&&(B.push(..._.tool_calls),h(`[AIClient][${o}] stream() tool_calls_chunk count=${_.tool_calls.length} names=${_.tool_calls.map(oe=>oe.name).join(", ")}`),yield _),_.delta&&(F+=_.delta,yield _),_.finish_reason&&(ke=_.finish_reason),_.finish_reason==="stop"&&(yield _)}if(h(`[AIClient][${o}] stream() round_end finish_reason=${ke??"unknown"} accumulated_len=${F.length} tool_calls_total=${B.length} content_preview=${D(F,200)}`),B.length===0)break;if(v(`[AIClient][${o}] stream() received ${B.length} tool call(s): ${B.map(_=>_.name).join(", ")}`),S++,S>L){v(`[AIClient][${o}] stream() max tool rounds (${L}) reached`);break}v(`[AIClient][${o}] stream() tool round ${S}/${L}`),x.push({role:"assistant",content:F||"",tool_calls:B.map(_=>({id:_.id,type:"function",function:{name:_.name,arguments:JSON.stringify(_.arguments)}}))});let ee=3,ce=B,Ue=B.filter(_=>_.name==="web.fetch");if(Ue.length>ee){v(`[AIClient][${o}] Limiting web.fetch calls from ${Ue.length} \u2192 ${ee} to prevent context overflow`);let _=Ue.slice(0,ee);ce=[...B.filter(Re=>Re.name!=="web.fetch"),..._];let re=Ue.slice(ee);for(let Re of re)x.push({role:"tool",tool_call_id:Re.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let he=5e4,W=0,te=!1,O=[];for(let _ of ce){if(te){x.push({role:"tool",tool_call_id:_.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let oe=Date.now(),re=!1,Re=setInterval(()=>{re||O.push({delta:""})},500),ye=await this.executeTool(_);re=!0,clearInterval(Re);let Hg=Date.now()-oe;for(;O.length>0;)yield O.shift();await new Promise(Qg=>setTimeout(Qg,0));let zg=typeof ye=="string"?ye:JSON.stringify(ye);if(W+zg.length>he){E(`[AIClient][${o}] Tool output budget exceeded (${he} chars), adding placeholder for remaining tools`),x.push({role:"tool",tool_call_id:_.id,content:"[Skipped: tool output budget exceeded for this round]"}),te=!0;continue}let Ee=typeof ye=="string"&&ye.length>this.toolResultMaxChars?`${ye.slice(0,this.toolResultMaxChars)}
154
- [TRUNCATED tool result: ${ye.length} chars]`:ye,Kg=typeof Ee=="string"?Ee:JSON.stringify(Ee);W+=Kg.length,x.push({role:"tool",tool_call_id:_.id,content:Ee}),yield{delta:"",tool_calls:[{..._,result:typeof Ee=="string"?Ee:JSON.stringify(Ee),duration:Hg}]}}h(`[AIClient][${o}] Round tool output size: ${W} chars (budget: ${he})`),Me("debug")&&(h(`[AIClient][${o}] stream() after_tools messages=${x.length}`),Yo(o,x))}}catch(o){throw this.wrapError(o)}}async embed(e,t){let r=this.getProvider(t);try{return await r.embed(e)}catch(o){throw this.wrapError(o)}}async enrichRequestWithTools(e){if(this.activeMode?.blockAllTools)return v(`[AIClient] Mode "${this.activeMode.displayName}" blocks all tools`),e;if(!this.toolsConfig.enabled||!this.toolRegistry&&(e.tools?.length||0)===0)return h("[AIClient] Tools disabled or no registry"),e;let t=this.toolsConfig;if(this.activeMode?.toolSearch&&this.toolsConfig.toolSearch&&(t={...this.toolsConfig,toolSearch:{...this.toolsConfig.toolSearch,...this.activeMode.toolSearch.enabled!==void 0?{enabled:this.activeMode.toolSearch.enabled}:{},...this.activeMode.toolSearch.alwaysLoadedTools?{alwaysLoadedTools:this.activeMode.toolSearch.alwaysLoadedTools}:{},...this.activeMode.toolSearch.alwaysLoadedCategories?{alwaysLoadedCategories:this.activeMode.toolSearch.alwaysLoadedCategories}:{}}},h(`[AIClient] Merged mode toolSearch config: enabled=${t.toolSearch?.enabled}, alwaysLoadedTools=${t.toolSearch?.alwaysLoadedTools?.length||0}`)),e.tools&&e.tools.length>0){if(!t.toolSearch?.enabled||!this.toolRegistry)return h(`[AIClient] Request already has ${e.tools.length} tools`),e;let i=await this.toolRouter.resolve(e.messages,this.toolRegistry,t);if(h(`[AIClient] Resolved ${i.length} tools to send: ${i.map(u=>u.name).join(", ")||"none"}`),this.activeMode&&i.length>0){let u=i.length;i=this.filterSchemasByMode(i,this.activeMode);let g=u-i.length;g>0&&v(`[AIClient] Mode "${this.activeMode.displayName}" filtered out ${g} tools`)}let c=new Set(e.tools.map(u=>u.function.name)),p=i.filter(u=>!c.has(u.name)).map(u=>({type:"function",function:{name:u.name,description:u.description,parameters:u.parameters}}));if(p.length===0)return h(`[AIClient] Request already has ${e.tools.length} tools (no new discoveries)`),e;let m={...e,tools:[...e.tools,...p]};return t.toolSearch?.enabled&&this.toolRegistry&&(m=this.injectToolSearchPrompt(m)),m}if(!this.toolRegistry)return h("[AIClient] Tool registry not configured, skipping tool resolution"),e;let r=this.toolRegistry,o=await this.toolRouter.resolve(e.messages,r,t);if(h(`[AIClient] Resolved ${o.length} tools to send: ${o.map(i=>i.name).join(", ")||"none"}`),this.activeMode&&o.length>0){let i=o.length;o=this.filterSchemasByMode(o,this.activeMode);let c=i-o.length;c>0&&v(`[AIClient] Mode "${this.activeMode.displayName}" filtered out ${c} tools`)}if(o.length===0)return e;let n=o.map(i=>({type:"function",function:{name:i.name,description:i.description,parameters:i.parameters}})),a={...e,tools:n};return this.toolsConfig.toolSearch?.enabled&&r&&(a=this.injectToolSearchPrompt(a)),a}filterSchemasByMode(e,t){return e.filter(r=>{if(t.blockedTools.includes(r.name)||t.blockedToolCategories.includes(r.category))return!1;let o=t.allowedTools.length>0,n=t.allowedToolCategories.length>0;if(o||n){let a=o&&t.allowedTools.includes(r.name),i=n&&t.allowedToolCategories.includes(r.category);return a||i}return!0})}injectModeSystemPrompt(e){if(!this.activeMode||!this.activeMode.systemPrompt)return h(`[AIClient] injectModeSystemPrompt: No active mode or empty systemPrompt. activeMode=${this.activeMode?.name}, systemPrompt=${this.activeMode?.systemPrompt?.substring(0,50)}`),e;let t=this.activeMode.systemPrompt;if(h(`[AIClient] injectModeSystemPrompt: Injecting mode prompt for ${this.activeMode.name}, length=${t.length}`),e.messages.some(o=>o.role==="system")){let o=e.messages.map(n=>{if(n.role==="system"){let a=typeof n.content=="string"?n.content:"";return{...n,content:`${a}
151
+ Answer only: YES or NO`;try{let m=((await n.generate({model:o,messages:[{role:"user",content:c}],max_tokens:10,temperature:0})).content||"").trim().toUpperCase(),u=m.startsWith("YES");return h(`[AIClient][${r}] inferNeedsToolsWithAI() context="${s}" message="${a.substring(0,50)}" result=${u} (raw: ${m})`),u}catch(p){return E(`[AIClient][${r}] inferNeedsToolsWithAI() error=${p} - falling back to false`),!1}}function Li(n){let e=je(n).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 so=class extends Fi.EventEmitter{providers;defaultProvider;toolRegistry;toolsConfig;toolRouter;bm25Engine;queryClassifier;toolOrchestrator;activeMode=null;overrideSystemPrompt;disableBaseContext;toolResultMaxChars;hitlConfig;onToolConfirm;currentRound=0;conversationId;constructor(e){super(),this.providers=new Map(Object.entries(e.providers)),this.defaultProvider=e.defaultProvider,this.toolRegistry=e.toolRegistry,this.toolsConfig=e.toolsConfig||H,this.toolRouter=new Ye,this.bm25Engine=new ze,this.queryClassifier=new Ve,this.toolOrchestrator=new Xo,this.overrideSystemPrompt=e.systemPrompt,this.disableBaseContext=e.disableBaseContext||!1;let t=this.toolsConfig.resultMaxChars??H.resultMaxChars??2e4;this.toolResultMaxChars=Number.isFinite(t)&&t>0?t:2e4,this.hitlConfig=e.hitlConfig,this.onToolConfirm=e.onToolConfirm,this.conversationId=e.conversationId,this.toolRegistry&&this.bm25Engine.index(this.toolRegistry.getAll())}isBypassed(e){let t=this.hitlConfig;if(!t||t.enabled===!1)return!0;let o=t.confirmationMode??"all";if(o==="off"||o==="high-only"&&e.confirmation?.level==="medium")return!0;let r=t.bypass??{};return!!(r.tools?.includes(e.name)||r.categories?.includes(e.category)||e.confirmation&&r.levels?.includes(e.confirmation.level))}registerProvider(e,t){this.providers.set(e,t)}getProvider(e){let t=e||this.defaultProvider;if(!t)throw new W("No provider specified and no default provider configured","NO_PROVIDER_CONFIGURED",400);let o=this.providers.get(t);if(!o)throw new W(`Provider '${t}' not found`,"PROVIDER_NOT_FOUND",404);return o}updateHitlConfig(e){this.hitlConfig=e}getHitlConfig(){return this.hitlConfig}setDefaultProvider(e){if(!this.providers.has(e))throw new W(`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 o=this.getProvider(t);try{let r=xn(),s=this.injectBaseAgentContext(e);s=this.injectOverrideSystemPrompt(s),s=this.injectModeSystemPrompt(s);let i=t||this.defaultProvider,a=await this.enrichRequestWithTools(s),c=process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||this.toolsConfig.toolChoicePolicy||"auto",p=(a.tools?.length||0)>0,m=a.tool_choice!=null,u=Mi(a.messages),g=this.toolsConfig.intelligentToolDetection,w=!1;if(!u&&g?.enabled&&p&&Oi(a.messages,g.maxFollowUpMessages)){v(`[AIClient][${r}] Message is after tool call, using AI to infer tool needs`);let R=Ii(i||"openai");u=await ji(o,i||"openai",a.messages,R),w=!0}let y=Li(a.messages);!m&&p&&(c==="required"||c==="required_for_actions"&&u)?a.tool_choice="required":!m&&p&&w&&!u&&(a.tool_choice="none",v(`[AIClient][${r}] AI inference determined no tools needed, setting tool_choice=none`));let k=o?.constructor?.name||"UnknownProvider",C={...a,__toolpack_request_id:r};v(`[AIClient][${r}] generate() start provider=${i} class=${k} model=${a.model} messages=${a.messages.length} tools=${a.tools?.length||0} tool_choice=${a.tool_choice??"unset"} policy=${c} needsTools=${u} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),tr(r,a.messages);let P=await o.generate(C);if(h(`[AIClient][${r}] generate() initial response finish_reason=${P.finish_reason??"unknown"} tool_calls=${P.tool_calls?.length||0} content_preview=${A(P.content||"",200)}`),this.toolsConfig.enabled&&this.toolsConfig.autoExecute&&this.toolRegistry){let S=je(a.messages),R=this.queryClassifier.classify(S),D=this.toolsConfig.maxToolRounds,L=this.queryClassifier.getToolRoundsAdjustment(R,D);L!==D?v(`[AIClient][${r}] Query classified as ${R.type} (confidence: ${R.confidence.toFixed(2)}), adjusted maxToolRounds: ${D} \u2192 ${L}`):h(`[AIClient][${r}] Query classified as ${R.type} (confidence: ${R.confidence.toFixed(2)}), keeping maxToolRounds: ${L}`);let j=0,U=[...a.messages];for(P.tool_calls&&P.tool_calls.length>0&&v(`[AIClient] Received ${P.tool_calls.length} tool call(s): ${P.tool_calls.map(J=>J.name).join(", ")}`);P.tool_calls&&P.tool_calls.length>0&&j<L;){j++,this.currentRound=j,v(`[AIClient][${r}] generate() tool round ${j}/${L} tool_calls=${P.tool_calls.length}`),U.push({role:"assistant",content:P.content||"",tool_calls:P.tool_calls.map(B=>({id:B.id,type:"function",function:{name:B.name,arguments:JSON.stringify(B.arguments)}}))});let J=this.toolOrchestrator.shouldUseParallelExecution(P.tool_calls),Ne=3,we=P.tool_calls,de=P.tool_calls.filter(B=>B.name==="web.fetch");if(de.length>Ne){v(`[AIClient][${r}] Limiting web.fetch calls from ${de.length} \u2192 ${Ne} to prevent context overflow`);let B=de.slice(0,Ne);we=[...P.tool_calls.filter($=>$.name!=="web.fetch"),...B];let F=de.slice(Ne);for(let $ of F)U.push({role:"tool",tool_call_id:$.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let oe=5e4,ue=0;if(J){v(`[AIClient][${r}] Using parallel execution for ${we.length} tools`);let B=await this.toolOrchestrator.executeWithDependencies(we,F=>this.executeTool(F),5),re=!1;for(let F of we){if(re){U.push({role:"tool",tool_call_id:F.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let $=B.get(F.id),ne=typeof $=="string"?$:JSON.stringify($);if(ue+ne.length>oe){E(`[AIClient][${r}] Tool output budget exceeded (${oe} chars), adding placeholder for remaining tools`),U.push({role:"tool",tool_call_id:F.id,content:"[Skipped: tool output budget exceeded for this round]"}),re=!0;continue}let se=typeof $=="string"&&$.length>this.toolResultMaxChars?`${$.slice(0,this.toolResultMaxChars)}
152
+ [TRUNCATED tool result: ${$.length} chars]`:$,Ae=typeof se=="string"?se:JSON.stringify(se);ue+=Ae.length,U.push({role:"tool",tool_call_id:F.id,content:se})}h(`[AIClient][${r}] Round tool output size: ${ue} chars (budget: ${oe})`)}else{v(`[AIClient][${r}] Using sequential execution for ${we.length} tools`);let B=!1;for(let re of we){if(B){U.push({role:"tool",tool_call_id:re.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let F=await this.executeTool(re),$=typeof F=="string"?F:JSON.stringify(F);if(ue+$.length>oe){E(`[AIClient][${r}] Tool output budget exceeded (${oe} chars), adding placeholder for remaining tools`),U.push({role:"tool",tool_call_id:re.id,content:"[Skipped: tool output budget exceeded for this round]"}),B=!0;continue}let ne=typeof F=="string"&&F.length>this.toolResultMaxChars?`${F.slice(0,this.toolResultMaxChars)}
153
+ [TRUNCATED tool result: ${F.length} chars]`:F,se=typeof ne=="string"?ne:JSON.stringify(ne);ue+=se.length,U.push({role:"tool",tool_call_id:re.id,content:ne})}h(`[AIClient][${r}] Round tool output size: ${ue} chars (budget: ${oe})`)}let Je={...a,messages:U,__toolpack_request_id:r},be=await this.enrichRequestWithTools(Je);be.tool_choice==="required"&&(be.tool_choice=y?"none":"auto",v(`[AIClient][${r}] generate() followup tool_choice override required->${be.tool_choice}`)),Le("debug")&&(h(`[AIClient][${r}] generate() followup request messages=${U.length}`),tr(r,U)),P=await o.generate(be),h(`[AIClient][${r}] generate() followup response finish_reason=${P.finish_reason??"unknown"} tool_calls=${P.tool_calls?.length||0} content_preview=${A(P.content||"",200)}`)}}return P}catch(r){throw this.wrapError(r)}}async*stream(e,t){let o=this.getProvider(t);try{let r=xn(),s=t||this.defaultProvider,i=this.injectBaseAgentContext(e);i=this.injectOverrideSystemPrompt(i),i=this.injectModeSystemPrompt(i);let a=await this.enrichRequestWithTools(i),c=process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||this.toolsConfig.toolChoicePolicy||"auto",p=(a.tools?.length||0)>0,m=a.tool_choice!=null,u=Mi(a.messages),g=this.toolsConfig.intelligentToolDetection,w=!1;if(!u&&g?.enabled&&p&&Oi(a.messages,g.maxFollowUpMessages)){v(`[AIClient][${r}] Message is after tool call, using AI to infer tool needs`);let J=Ii(s||"openai");u=await ji(o,s||"openai",a.messages,J),w=!0}let y=Li(a.messages);!m&&p&&(c==="required"||c==="required_for_actions"&&u)?a.tool_choice="required":!m&&p&&w&&!u&&(a.tool_choice="none",v(`[AIClient][${r}] AI inference determined no tools needed, setting tool_choice=none`));let k=o?.constructor?.name||"UnknownProvider",C={...a,__toolpack_request_id:r};if(v(`[AIClient][${r}] stream() start provider=${s} class=${k} model=${a.model} messages=${a.messages.length} tools=${a.tools?.length||0} tool_choice=${a.tool_choice??"unset"} policy=${c} needsTools=${u} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),tr(r,a.messages),!this.toolsConfig.enabled||!this.toolsConfig.autoExecute||!this.toolRegistry){yield*o.stream(C);return}let P=[...a.messages],S=0,R=je(a.messages),D=this.queryClassifier.classify(R),L=this.toolsConfig.maxToolRounds,j=this.queryClassifier.getToolRoundsAdjustment(D,L);for(j!==L&&v(`[AIClient][${r}] stream() Query classified as ${D.type} (confidence: ${D.confidence.toFixed(2)}), adjusted maxToolRounds: ${L} \u2192 ${j}`);S<=j;){if(e.signal?.aborted){v(`[AIClient][${r}] stream() aborted by signal`);return}let U="",J=[];S++,this.currentRound=S,v(`[AIClient][${r}] stream() round_start ${S}/${j}`);let Ne=null,we={...C,messages:P},de=await this.enrichRequestWithTools(we);S>0&&de.tool_choice==="required"&&(de.tool_choice=y?"none":"auto",v(`[AIClient][${r}] stream() round_${S+1} tool_choice override required->${de.tool_choice}`));for await(let $ of o.stream(de)){if(e.signal?.aborted){v(`[AIClient][${r}] stream() aborted by signal during chunk processing`);return}$.tool_calls&&$.tool_calls.length>0&&(J.push(...$.tool_calls),h(`[AIClient][${r}] stream() tool_calls_chunk count=${$.tool_calls.length} names=${$.tool_calls.map(ne=>ne.name).join(", ")}`),yield $),$.delta&&(U+=$.delta,yield $),$.finish_reason&&(Ne=$.finish_reason),$.finish_reason==="stop"&&(yield $)}if(h(`[AIClient][${r}] stream() round_end finish_reason=${Ne??"unknown"} accumulated_len=${U.length} tool_calls_total=${J.length} content_preview=${A(U,200)}`),J.length===0)break;if(v(`[AIClient][${r}] stream() received ${J.length} tool call(s): ${J.map($=>$.name).join(", ")}`),S++,S>j){v(`[AIClient][${r}] stream() max tool rounds (${j}) reached`);break}v(`[AIClient][${r}] stream() tool round ${S}/${j}`),P.push({role:"assistant",content:U||"",tool_calls:J.map($=>({id:$.id,type:"function",function:{name:$.name,arguments:JSON.stringify($.arguments)}}))});let oe=3,ue=J,Je=J.filter($=>$.name==="web.fetch");if(Je.length>oe){v(`[AIClient][${r}] Limiting web.fetch calls from ${Je.length} \u2192 ${oe} to prevent context overflow`);let $=Je.slice(0,oe);ue=[...J.filter(Ae=>Ae.name!=="web.fetch"),...$];let se=Je.slice(oe);for(let Ae of se)P.push({role:"tool",tool_call_id:Ae.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let be=5e4,B=0,re=!1,F=[];for(let $ of ue){if(re){P.push({role:"tool",tool_call_id:$.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let ne=Date.now(),se=!1,Ae=setInterval(()=>{se||F.push({delta:""})},500),xe=await this.executeTool($);se=!0,clearInterval(Ae);let gh=Date.now()-ne;for(;F.length>0;)yield F.shift();await new Promise(wh=>setTimeout(wh,0));let hh=typeof xe=="string"?xe:JSON.stringify(xe);if(B+hh.length>be){E(`[AIClient][${r}] Tool output budget exceeded (${be} chars), adding placeholder for remaining tools`),P.push({role:"tool",tool_call_id:$.id,content:"[Skipped: tool output budget exceeded for this round]"}),re=!0;continue}let Me=typeof xe=="string"&&xe.length>this.toolResultMaxChars?`${xe.slice(0,this.toolResultMaxChars)}
154
+ [TRUNCATED tool result: ${xe.length} chars]`:xe,yh=typeof Me=="string"?Me:JSON.stringify(Me);B+=yh.length,P.push({role:"tool",tool_call_id:$.id,content:Me}),yield{delta:"",tool_calls:[{...$,result:typeof Me=="string"?Me:JSON.stringify(Me),duration:gh}]}}h(`[AIClient][${r}] Round tool output size: ${B} chars (budget: ${be})`),Le("debug")&&(h(`[AIClient][${r}] stream() after_tools messages=${P.length}`),tr(r,P))}}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 h("[AIClient] Tools disabled or no registry"),e;let t=this.toolsConfig;if(this.activeMode?.toolSearch&&this.toolsConfig.toolSearch&&(t={...this.toolsConfig,toolSearch:{...this.toolsConfig.toolSearch,...this.activeMode.toolSearch.enabled!==void 0?{enabled:this.activeMode.toolSearch.enabled}:{},...this.activeMode.toolSearch.alwaysLoadedTools?{alwaysLoadedTools:this.activeMode.toolSearch.alwaysLoadedTools}:{},...this.activeMode.toolSearch.alwaysLoadedCategories?{alwaysLoadedCategories:this.activeMode.toolSearch.alwaysLoadedCategories}:{}}},h(`[AIClient] Merged mode toolSearch config: enabled=${t.toolSearch?.enabled}, alwaysLoadedTools=${t.toolSearch?.alwaysLoadedTools?.length||0}`)),e.tools&&e.tools.length>0){if(!t.toolSearch?.enabled||!this.toolRegistry)return h(`[AIClient] Request already has ${e.tools.length} tools`),e;let a=await this.toolRouter.resolve(e.messages,this.toolRegistry,t);if(h(`[AIClient] Resolved ${a.length} tools to send: ${a.map(u=>u.name).join(", ")||"none"}`),this.activeMode&&a.length>0){let u=a.length;a=this.filterSchemasByMode(a,this.activeMode);let g=u-a.length;g>0&&v(`[AIClient] Mode "${this.activeMode.displayName}" filtered out ${g} tools`)}let c=new Set(e.tools.map(u=>u.function.name)),p=a.filter(u=>!c.has(u.name)).map(u=>({type:"function",function:{name:u.name,description:u.description,parameters:u.parameters}}));if(p.length===0)return h(`[AIClient] Request already has ${e.tools.length} tools (no new discoveries)`),e;let m={...e,tools:[...e.tools,...p]};return t.toolSearch?.enabled&&this.toolRegistry&&(m=this.injectToolSearchPrompt(m)),m}if(!this.toolRegistry)return h("[AIClient] Tool registry not configured, skipping tool resolution"),e;let o=this.toolRegistry,r=await this.toolRouter.resolve(e.messages,o,t);if(h(`[AIClient] Resolved ${r.length} tools to send: ${r.map(a=>a.name).join(", ")||"none"}`),this.activeMode&&r.length>0){let a=r.length;r=this.filterSchemasByMode(r,this.activeMode);let c=a-r.length;c>0&&v(`[AIClient] Mode "${this.activeMode.displayName}" filtered out ${c} tools`)}if(r.length===0)return e;let s=r.map(a=>({type:"function",function:{name:a.name,description:a.description,parameters:a.parameters}})),i={...e,tools:s};return this.toolsConfig.toolSearch?.enabled&&o&&(i=this.injectToolSearchPrompt(i)),i}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,s=t.allowedToolCategories.length>0;if(r||s){let i=r&&t.allowedTools.includes(o.name),a=s&&t.allowedToolCategories.includes(o.category);return i||a}return!0})}injectModeSystemPrompt(e){if(!this.activeMode||!this.activeMode.systemPrompt)return h(`[AIClient] injectModeSystemPrompt: No active mode or empty systemPrompt. activeMode=${this.activeMode?.name}, systemPrompt=${this.activeMode?.systemPrompt?.substring(0,50)}`),e;let t=this.activeMode.systemPrompt;if(h(`[AIClient] injectModeSystemPrompt: Injecting mode prompt for ${this.activeMode.name}, length=${t.length}`),e.messages.some(r=>r.role==="system")){let r=e.messages.map(s=>{if(s.role==="system"){let i=typeof s.content=="string"?s.content:"";return{...s,content:`${i}
155
155
 
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}
156
+ ${t}`}}return s});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(s=>{if(s.role==="system"){let i=typeof s.content=="string"?s.content:"";return{...s,content:`${i}
157
157
 
158
- ${t}`}}return n});return{...e,messages:o}}else return{...e,messages:[{role:"system",content:t},...e.messages]}}injectBaseAgentContext(e){let t=!0,r=!0,o,n=this.disableBaseContext;if(this.activeMode?.baseContext===!1)return e;this.activeMode?.baseContext&&(t=this.activeMode.baseContext.includeWorkingDirectory!==!1,r=this.activeMode.baseContext.includeToolCategories!==!1,o=this.activeMode.baseContext.custom);let a=o||pi({workingDirectory:process.cwd(),toolCategories:this.toolRegistry?this.toolRegistry.getCategories():[],disabled:n,includeWorkingDirectory:t,includeToolCategories:r});if(!a)return e;if(e.messages.some(c=>c.role==="system")){let c=e.messages.map(p=>{if(p.role==="system"){let m=typeof p.content=="string"?p.content:"";return{...p,content:`${a}
158
+ ${t}`}}return s});return{...e,messages:r}}else return{...e,messages:[{role:"system",content:t},...e.messages]}}injectBaseAgentContext(e){let t=!0,o=!0,r,s=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 i=r||_i({workingDirectory:process.cwd(),toolCategories:this.toolRegistry?this.toolRegistry.getCategories():[],disabled:s,includeWorkingDirectory:t,includeToolCategories:o});if(!i)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:`${i}
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"),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=`
160
+ ${m}`}}return p});return{...e,messages:c}}else return{...e,messages:[{role:"system",content:i},...e.messages]}}injectToolSearchPrompt(e){if(!this.toolRegistry)return e;let t=e.messages.some(i=>i.role==="system"),o=this.toolsConfig.toolSearch?.alwaysLoadedTools??[],r="";if(o.length>0){let i=o.map(a=>{let c=this.toolRegistry?.get(a);return c?` - **${c.name}**: ${c.description}`:null}).filter(Boolean).join(`
161
+ `);i&&(r=`
162
162
 
163
163
  You have these tools always available:
164
- ${a}
164
+ ${i}
165
165
 
166
- Use these tools directly when appropriate for the task.`)}let n=`
166
+ Use these tools directly when appropriate for the task.`)}let s=`
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.${o}
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}
170
170
 
171
- ${Ho(this.toolRegistry)}
171
+ ${Vo(this.toolRegistry)}
172
172
 
173
173
  When you need a tool:
174
174
  1. Check if it's in your current tool list
@@ -176,30 +176,35 @@ When you need a tool:
176
176
  3. After discovering tools, you can call them directly in subsequent turns
177
177
 
178
178
  NEVER guess or hallucinate tool names. ALWAYS use tool.search to discover tools you don't have.
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}
179
+ `.trim();if(t){let i=e.messages.map(a=>{if(a.role==="system"){let c=typeof a.content=="string"?a.content:"";return{...a,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: ${D(e.arguments,500)}`),!this.toolRegistry){let o="No tool registry configured";return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:o,duration:Date.now()-t}),JSON.stringify({error:o})}if(Jo(e.name)){let o=this.executeToolSearch(e.arguments),n=Date.now()-t;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof o=="string"?o.substring(0,200):JSON.stringify(o).substring(0,200),duration:n}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:o,duration:n,status:"success",timestamp:Date.now()}),o}let r=this.toolRegistry.get(e.name);if(!r){E(`[AIClient] Tool '${e.name}' not found in registry`);let o=this.findSimilarToolName(e.name),n=o?`Tool '${e.name}' not found. Did you mean '${o}'? Use tool.search to discover available tools.`:`Tool '${e.name}' not found. Use tool.search to discover available tools.`;return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:n,duration:Date.now()-t}),JSON.stringify({error:n})}try{let o={workspaceRoot:process.cwd(),config:this.toolsConfig?.additionalConfigurations??{},log:i=>v(`[Tool] ${i}`)},n=await r.execute(e.arguments,o),a=Date.now()-t;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof n=="string"?n.substring(0,200):JSON.stringify(n).substring(0,200),duration:a}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:n,duration:a,status:"success",timestamp:Date.now()}),v(`[AIClient] Tool ${e.name} executed successfully in ${a}ms result_len=${n?.length??0}`),Me("debug")&&h(`[AIClient] Tool ${e.name} result_preview=${D(n,400)}`),n}catch(o){let n=Date.now()-t,a=o.message||"Tool execution failed";return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:a,duration:n}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:JSON.stringify({error:a}),duration:n,status:"error",timestamp:Date.now()}),Y(`[AIClient] Tool ${e.name} failed: ${D(a,300)}`),JSON.stringify({error:a})}}findSimilarToolName(e){if(!this.toolRegistry)return null;let t=this.toolRegistry.getAll(),r=e.replace(/_/g,".");if(t.some(c=>c.name===r))return r;let o=e.replace(/\./g,"_");if(t.some(c=>c.name===o))return o;let n=e.replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase().replace(/_/g,".");if(t.some(c=>c.name===n))return n;let a=null,i=1/0;for(let c of t){let p=this.levenshteinDistance(e.toLowerCase(),c.name.toLowerCase());p<=2&&p<i&&(i=p,a=c.name)}return a}levenshteinDistance(e,t){let r=[];for(let o=0;o<=t.length;o++)r[o]=[o];for(let o=0;o<=e.length;o++)r[0][o]=o;for(let o=1;o<=t.length;o++)for(let n=1;n<=e.length;n++)t.charAt(o-1)===e.charAt(n-1)?r[o][n]=r[o-1][n-1]:r[o][n]=Math.min(r[o-1][n-1]+1,r[o][n-1]+1,r[o-1][n]+1);return r[t.length][e.length]}executeToolSearch(e){let{query:t,category:r}=e,o=this.toolsConfig.toolSearch?.searchResultLimit??5;v(`[AIClient] Executing tool.search: query="${t}" category=${r||"all"} limit=${o}`);let n=this.bm25Engine.search(t,{limit:o,category:r}),a=n.map(i=>i.toolName);return this.toolRouter.getDiscoveryCache().recordDiscovery(t,a),h(`[AIClient] tool.search found ${n.length} tools: ${a.join(", ")||"none"}`),JSON.stringify({query:t,found:n.length,tools:n.map(i=>({name:i.tool.name,displayName:i.tool.displayName,description:i.tool.description,category:i.tool.category,parameters:i.tool.parameters,relevanceScore:Math.round(i.score*100)/100})),hint:n.length>0?`Found ${n.length} tools. You can now call any of these tools directly.`:`No tools found for "${t}". Try a different search term.`})}wrapError(e){return e instanceof J?e:new I(e.message||"Unknown provider error","UNKNOWN_PROVIDER_ERROR",500,e)}};l();l();var ln=T(require("@anthropic-ai/sdk"),1);l();de();var K=class{name;async getModels(){return[]}getDisplayName(){return this.name||this.constructor.name.replace(/Adapter$/,"")}supportsFileUpload(){return!1}async uploadFile(e){throw new N(`File upload API is not supported by ${this.getDisplayName()}`)}async deleteFile(e){throw new N(`File deletion API is not supported by ${this.getDisplayName()}`)}};de();k();var oo=class extends K{client;constructor(e,t){super(),this.client=new ln.default({apiKey:e,baseURL:t})}supportsFileUpload(){return!0}async uploadFile(e){try{let t=await import("fs");if(!e.filePath)throw new N("Anthropic uploadFile requires a filePath.");return{id:(await this.client.files.create({file:t.createReadStream(e.filePath),purpose:e.purpose||"vision"})).id}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{await this.client.files.delete(e)}catch(t){throw this.handleError(t)}}getDisplayName(){return"Anthropic"}async getModels(){return[{id:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:64e3},{id:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-sonnet-4-6",displayName:"Claude Sonnet 4.6",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-opus-4-5",displayName:"Claude Opus 4.5",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-opus-4-6",displayName:"Claude Opus 4.6",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384}]}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(o=>this.sanitizeToolName(o.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,r=await this.toAnthropicMessages(e.messages,e.mediaOptions),o=r.system,n=r.userMessages,a={model:e.model,messages:n,system:o,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p,stream:!1};e.tools&&e.tools.length>0?(a.tools=e.tools.map(m=>({name:this.sanitizeToolName(m.function.name),description:m.function.description,input_schema:m.function.parameters})),e.tool_choice==="required"?a.tool_choice={type:"any"}:e.tool_choice==="none"?delete a.tools:a.tool_choice={type:"auto"},h(`[Anthropic][${t}] Sending ${a.tools?.length||0} tools with tool_choice: ${a.tool_choice?.type||"unset"}`),a.tools&&a.tools.length>0&&h(`[Anthropic][${t}] First tool: ${D(a.tools[0],800)}`)):h(`[Anthropic][${t}] NO TOOLS in request`),h(`[Anthropic][${t}] generate() request: model=${a.model}, messages=${a.messages.length}, tools=${a.tools?.length||0}, tool_choice=${a.tool_choice?.type??"unset"}`),X(t,"Anthropic",a.messages);let i=await this.client.messages.create(a,e.signal?{signal:e.signal}:void 0),c=[],p=[];for(let m of i.content)m.type==="text"?c.push(m.text):m.type==="tool_use"&&p.push({id:m.id,name:this.restoreToolName(m.name,e.tools),arguments:m.input});return h(`[Anthropic][${t}] Response finish_reason=${i.stop_reason} tool_calls=${p.length} content_preview=${D(c.join(""),200)}`),{content:c.length>0?c.join(""):null,usage:{prompt_tokens:i.usage.input_tokens,completion_tokens:i.usage.output_tokens,total_tokens:i.usage.input_tokens+i.usage.output_tokens},finish_reason:this.mapFinishReason(i.stop_reason),tool_calls:p.length>0?p:void 0,raw:i}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`str-${Date.now()}`,r=await this.toAnthropicMessages(e.messages,e.mediaOptions),o={model:e.model,messages:r.userMessages,system:r.system,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p,stream:!0};e.tools&&e.tools.length>0?(o.tools=e.tools.map(m=>({name:this.sanitizeToolName(m.function.name),description:m.function.description,input_schema:m.function.parameters})),e.tool_choice==="required"?o.tool_choice={type:"any"}:e.tool_choice==="none"?delete o.tools:o.tool_choice={type:"auto"},h(`[Anthropic][${t}] Sending ${o.tools?.length||0} tools with tool_choice: ${o.tool_choice?.type||"unset"}`),o.tools&&o.tools.length>0&&h(`[Anthropic][${t}] First tool: ${D(o.tools[0],800)}`)):h(`[Anthropic][${t}] NO TOOLS in request`),h(`[Anthropic][${t}] Stream request: model=${o.model}, messages=${o.messages.length}, tools=${o.tools?.length||0}, tool_choice=${o.tool_choice?.type??"unset"}`),X(t,"Anthropic",o.messages);let n=await this.client.messages.create(o,e.signal?{signal:e.signal}:void 0),a="",i="",c="",p=!1;for await(let m of n)m.type==="content_block_start"&&m.content_block?.type==="tool_use"&&(p=!0,a=m.content_block.id,i=m.content_block.name,c=""),m.type==="content_block_delta"&&(m.delta.type==="text_delta"?yield{delta:m.delta.text}:m.delta.type==="input_json_delta"&&p&&(c+=m.delta.partial_json)),m.type==="content_block_stop"&&p&&(h(`[Anthropic][${t}] Stream finish_reason=tool_calls accumulated_call=${i}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:a,name:this.restoreToolName(i,e.tools),arguments:JSON.parse(c||"{}")}]},p=!1),m.type==="message_stop"&&(be(`[Anthropic][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"})}catch(t){throw this.handleError(t)}}async embed(e){throw new N("Embeddings are not strictly supported by the Anthropic API currently.")}async toAnthropicMessages(e,t={}){let r,o=[],{normalizeImagePart:n}=await Promise.resolve().then(()=>(ze(),to));for(let a of e)if(a.role==="system"){if(typeof a.content=="string")r=a.content;else if(a.content!==null){let i=a.content.filter(c=>typeof c=="object"&&c.type==="text").map(c=>c.text).join(`
182
- `);i&&(r=i)}}else if(a.role==="tool"&&a.tool_call_id)o.push({role:"user",content:[{type:"tool_result",tool_use_id:a.tool_call_id,content:typeof a.content=="string"?a.content:JSON.stringify(a.content)}]});else if(a.role==="assistant"&&a.tool_calls&&a.tool_calls.length>0){let i=[];if(typeof a.content=="string"&&a.content)i.push({type:"text",text:a.content});else if(Array.isArray(a.content)){let c=a.content.filter(p=>typeof p=="object"&&p.type==="text").map(p=>p.text).join(`
183
- `);c&&i.push({type:"text",text:c})}for(let c of a.tool_calls)i.push({type:"tool_use",id:c.id,name:this.sanitizeToolName(c.function.name),input:typeof c.function.arguments=="string"?JSON.parse(c.function.arguments||"{}"):c.function.arguments});o.push({role:"assistant",content:i})}else{let i=[];typeof a.content=="string"?i=a.content:a.content!==null&&(i=(await Promise.all(a.content.map(async c=>{if(c.type==="text")return{type:"text",text:c.text};if(c.type==="image_url"){let p=c.image_url.url;if(p.startsWith("data:")){let m=p.match(/^data:(image\/\w+);base64,(.+)$/);if(m)return{type:"image",source:{type:"base64",media_type:m[1],data:m[2]}}}return{type:"image",source:{type:"url",url:p}}}if(c.type==="image_data"||c.type==="image_file"){let{data:p,mimeType:m}=await n(c);return{type:"image",source:{type:"base64",media_type:m,data:p}}}return null}))).filter(Boolean)),o.push({role:a.role==="user"?"user":"assistant",content:i})}return{system:r,userMessages:o}}mapFinishReason(e){return e==="end_turn"?"stop":e==="max_tokens"?"length":e==="stop_sequence"?"stop":e}handleError(e){if(e instanceof ln.default.APIError){let t=e.message;return e.status===401?new pe(t,e):e.status===429?new me(t,void 0,e):e.status&&e.status>=400&&e.status<500?new N(t,e):new I(t,"ANTHROPIC_ERROR",e.status||500,e)}return new I("Unknown Anthropic error","UNKNOWN",500,e)}};l();var $i=require("@google/generative-ai");de();k();var ro=class extends K{genAI;constructor(e){super(),this.genAI=new $i.GoogleGenerativeAI(e)}supportsFileUpload(){return!0}sanitizeSchema(e){if(!e||typeof e!="object")return e;let t={};for(let[r,o]of Object.entries(e))r==="additionalProperties"||r==="exclusiveMinimum"||r==="exclusiveMaximum"||r==="$schema"||r==="$id"||r==="definitions"||r==="$defs"||(typeof o=="object"&&o!==null?Array.isArray(o)?t[r]=o.map(n=>this.sanitizeSchema(n)):t[r]=this.sanitizeSchema(o):t[r]=o);return t}async uploadFile(e){try{let t=await import("fs"),r=await import("path");if(!e.filePath)throw new N("Gemini uploadFile requires a filePath.");let o=await t.promises.readFile(e.filePath),n=r.basename(e.filePath),a=e.mimeType||"application/octet-stream",c=`https://generativelanguage.googleapis.com/upload/v1beta/files?key=${this.genAI.apiKey}`,p="----WebKitFormBoundary"+Math.random().toString(36).substring(2),m=JSON.stringify({file:{displayName:n}}),u=Buffer.concat([Buffer.from(`--${p}\r
181
+ ${s}`}}return a});return{...e,messages:i}}else return{...e,messages:[{role:"system",content:s},...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: ${A(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(Yo(e.name)){let r=this.executeToolSearch(e.arguments),s=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:s}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:r,duration:s,status:"success",timestamp:Date.now()}),r}let o=this.toolRegistry.get(e.name);if(!o){E(`[AIClient] Tool '${e.name}' not found in registry`);let r=this.findSimilarToolName(e.name),s=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:s,duration:Date.now()-t}),JSON.stringify({error:s})}try{let r=e.arguments;if(o.confirmation&&this.onToolConfirm&&!this.isBypassed(o)){this.emit("tool:confirmation_requested",{tool:o,args:r,level:o.confirmation.level,reason:o.confirmation.reason});let c=await this.onToolConfirm(o,r,{roundNumber:this.currentRound,conversationId:this.conversationId});if(this.emit("tool:confirmation_resolved",{tool:o,args:r,level:o.confirmation.level,reason:o.confirmation.reason,decision:c}),c.action==="deny"){let p=`[Execution denied by user${c.reason?": "+c.reason:""}]`,m=Date.now()-t;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:p,duration:m}),this.emit("tool:log",{id:e.id,name:e.name,arguments:r,result:p,duration:m,status:"success",timestamp:Date.now()}),p}c.action==="modify"&&(r=c.args)}let s={workspaceRoot:process.cwd(),config:this.toolsConfig?.additionalConfigurations??{},log:c=>v(`[Tool] ${c}`)},i=await o.execute(r,s),a=Date.now()-t;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof i=="string"?i.substring(0,200):JSON.stringify(i).substring(0,200),duration:a}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:i,duration:a,status:"success",timestamp:Date.now()}),v(`[AIClient] Tool ${e.name} executed successfully in ${a}ms result_len=${i?.length??0}`),Le("debug")&&h(`[AIClient] Tool ${e.name} result_preview=${A(i,400)}`),i}catch(r){let s=Date.now()-t,i=r.message||"Tool execution failed";return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:i,duration:s}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:JSON.stringify({error:i}),duration:s,status:"error",timestamp:Date.now()}),Q(`[AIClient] Tool ${e.name} failed: ${A(i,300)}`),JSON.stringify({error:i})}}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 s=e.replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase().replace(/_/g,".");if(t.some(c=>c.name===s))return s;let i=null,a=1/0;for(let c of t){let p=this.levenshteinDistance(e.toLowerCase(),c.name.toLowerCase());p<=2&&p<a&&(a=p,i=c.name)}return i}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 s=1;s<=e.length;s++)t.charAt(r-1)===e.charAt(s-1)?o[r][s]=o[r-1][s-1]:o[r][s]=Math.min(o[r-1][s-1]+1,o[r][s-1]+1,o[r-1][s]+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 s=this.bm25Engine.search(t,{limit:r,category:o}),i=s.map(a=>a.toolName);return this.toolRouter.getDiscoveryCache().recordDiscovery(t,i),h(`[AIClient] tool.search found ${s.length} tools: ${i.join(", ")||"none"}`),JSON.stringify({query:t,found:s.length,tools:s.map(a=>({name:a.tool.name,displayName:a.tool.displayName,description:a.tool.description,category:a.tool.category,parameters:a.tool.parameters,relevanceScore:Math.round(a.score*100)/100})),hint:s.length>0?`Found ${s.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 W?e:new q(e.message||"Unknown provider error","UNKNOWN_PROVIDER_ERROR",500,e)}};l();l();var kn=x(require("@anthropic-ai/sdk"),1);l();le();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()}`)}};le();_();var ao=class extends Y{client;constructor(e,t){super(),this.client=new kn.default({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,s=o.userMessages,i={model:e.model,messages:s,system:r,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p,stream:!1};e.tools&&e.tools.length>0?(i.tools=e.tools.map(m=>({name:this.sanitizeToolName(m.function.name),description:m.function.description,input_schema:m.function.parameters})),e.tool_choice==="required"?i.tool_choice={type:"any"}:e.tool_choice==="none"?delete i.tools:i.tool_choice={type:"auto"},h(`[Anthropic][${t}] Sending ${i.tools?.length||0} tools with tool_choice: ${i.tool_choice?.type||"unset"}`),i.tools&&i.tools.length>0&&h(`[Anthropic][${t}] First tool: ${A(i.tools[0],800)}`)):h(`[Anthropic][${t}] NO TOOLS in request`),h(`[Anthropic][${t}] generate() request: model=${i.model}, messages=${i.messages.length}, tools=${i.tools?.length||0}, tool_choice=${i.tool_choice?.type??"unset"}`),ee(t,"Anthropic",i.messages);let a=await this.client.messages.create(i,e.signal?{signal:e.signal}:void 0),c=[],p=[];for(let m of a.content)m.type==="text"?c.push(m.text):m.type==="tool_use"&&p.push({id:m.id,name:this.restoreToolName(m.name,e.tools),arguments:m.input});return h(`[Anthropic][${t}] Response finish_reason=${a.stop_reason} tool_calls=${p.length} content_preview=${A(c.join(""),200)}`),{content:c.length>0?c.join(""):null,usage:{prompt_tokens:a.usage.input_tokens,completion_tokens:a.usage.output_tokens,total_tokens:a.usage.input_tokens+a.usage.output_tokens},finish_reason:this.mapFinishReason(a.stop_reason),tool_calls:p.length>0?p:void 0,raw:a}}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"},h(`[Anthropic][${t}] Sending ${r.tools?.length||0} tools with tool_choice: ${r.tool_choice?.type||"unset"}`),r.tools&&r.tools.length>0&&h(`[Anthropic][${t}] First tool: ${A(r.tools[0],800)}`)):h(`[Anthropic][${t}] NO TOOLS in request`),h(`[Anthropic][${t}] Stream request: model=${r.model}, messages=${r.messages.length}, tools=${r.tools?.length||0}, tool_choice=${r.tool_choice?.type??"unset"}`),ee(t,"Anthropic",r.messages);let s=await this.client.messages.create(r,e.signal?{signal:e.signal}:void 0),i="",a="",c="",p=!1;for await(let m of s)m.type==="content_block_start"&&m.content_block?.type==="tool_use"&&(p=!0,i=m.content_block.id,a=m.content_block.name,c=""),m.type==="content_block_delta"&&(m.delta.type==="text_delta"?yield{delta:m.delta.text}:m.delta.type==="input_json_delta"&&p&&(c+=m.delta.partial_json)),m.type==="content_block_stop"&&p&&(h(`[Anthropic][${t}] Stream finish_reason=tool_calls accumulated_call=${a}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:i,name:this.restoreToolName(a,e.tools),arguments:JSON.parse(c||"{}")}]},p=!1),m.type==="message_stop"&&(Pe(`[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:s}=await Promise.resolve().then(()=>(Xe(),io));for(let i of e)if(i.role==="system"){if(typeof i.content=="string")o=i.content;else if(i.content!==null){let a=i.content.filter(c=>typeof c=="object"&&c.type==="text").map(c=>c.text).join(`
182
+ `);a&&(o=a)}}else if(i.role==="tool"&&i.tool_call_id)r.push({role:"user",content:[{type:"tool_result",tool_use_id:i.tool_call_id,content:typeof i.content=="string"?i.content:JSON.stringify(i.content)}]});else if(i.role==="assistant"&&i.tool_calls&&i.tool_calls.length>0){let a=[];if(typeof i.content=="string"&&i.content)a.push({type:"text",text:i.content});else if(Array.isArray(i.content)){let c=i.content.filter(p=>typeof p=="object"&&p.type==="text").map(p=>p.text).join(`
183
+ `);c&&a.push({type:"text",text:c})}for(let c of i.tool_calls)a.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:a})}else{let a=[];typeof i.content=="string"?a=i.content:i.content!==null&&(a=(await Promise.all(i.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 s(c);return{type:"image",source:{type:"base64",media_type:m,data:p}}}return null}))).filter(Boolean)),r.push({role:i.role==="user"?"user":"assistant",content:a})}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 kn.default.APIError){let t=e.message;return e.status===401?new fe(t,e):e.status===429?new ge(t,void 0,e):e.status&&e.status>=400&&e.status<500?new M(t,e):new q(t,"ANTHROPIC_ERROR",e.status||500,e)}return new q("Unknown Anthropic error","UNKNOWN",500,e)}};l();var Bi=require("@google/generative-ai");le();_();var lo=class extends Y{genAI;constructor(e){super(),this.genAI=new Bi.GoogleGenerativeAI(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(s=>this.sanitizeSchema(s)):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),s=o.basename(e.filePath),i=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:s}}),u=Buffer.concat([Buffer.from(`--${p}\r
184
184
  Content-Type: application/json\r
185
185
  \r
186
186
  ${m}\r
187
187
  `),Buffer.from(`--${p}\r
188
- Content-Type: ${a}\r
188
+ Content-Type: ${i}\r
189
189
  \r
190
- `),o,Buffer.from(`\r
190
+ `),r,Buffer.from(`\r
191
191
  --${p}--\r
192
- `)]),g=await fetch(c,{method:"POST",headers:{"Content-Type":`multipart/related; boundary=${p}`},body:u});if(!g.ok){let y=await g.text();throw new Error(`Gemini file upload failed: ${g.status} ${y}`)}let w=await g.json();return{id:w.file?.name||w.name,url:w.file?.uri||w.uri}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{let t=this.genAI.apiKey,r=`https://generativelanguage.googleapis.com/v1beta/${e}?key=${t}`,o=await fetch(r,{method:"DELETE"});if(!o.ok){let n=await o.text();throw new Error(`Gemini file deletion failed: ${o.status} ${n}`)}}catch(t){throw this.handleError(t)}}getDisplayName(){return"Google Gemini"}async getModels(){return[{id:"gemini-3.1-flash-lite-preview",displayName:"Gemini 3.1 Flash-Lite Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-3-flash-preview",displayName:"Gemini 3 Flash Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-3.1-pro-preview",displayName:"Gemini 3.1 Pro Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1048576,maxOutputTokens:65536}]}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(o=>this.sanitizeToolName(o.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,r={model:e.model,systemInstruction:this.extractSystemInstruction(e.messages)};e.tools&&e.tools.length>0?(r.tools=[{functionDeclarations:e.tools.map(g=>({name:this.sanitizeToolName(g.function.name),description:g.function.description,parameters:this.sanitizeSchema(g.function.parameters)}))}],h(`[Gemini][${t}] Sending ${e.tools.length} tools`),e.tools.length>0&&h(`[Gemini][${t}] First tool: ${D(e.tools[0],800)}`)):h(`[Gemini][${t}] NO TOOLS in request`),h(`[Gemini][${t}] generate() request: model=${e.model}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),X(t,"Gemini",e.messages);let o=this.genAI.getGenerativeModel(r),{history:n,lastUserMessage:a}=await this.formatHistory(e.messages,e.mediaOptions),p=await(await o.startChat({history:n,generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:e.response_format==="json_object"?"application/json":"text/plain"}}).sendMessage(a)).response,m=[],u="";for(let g of p.candidates||[])for(let w of g.content?.parts||[])if(w.text&&(u+=w.text),w.functionCall){let y=w.functionCall;m.push({id:`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(y.name,e.tools),arguments:y.args||{}})}return h(`[Gemini][${t}] Response finish_reason=${m.length>0?"tool_calls":"stop"} tool_calls=${m.length} content_preview=${D(u,200)}`),{content:u||null,usage:{prompt_tokens:p.usageMetadata?.promptTokenCount||0,completion_tokens:p.usageMetadata?.candidatesTokenCount||0,total_tokens:p.usageMetadata?.totalTokenCount||0},finish_reason:m.length>0?"tool_calls":"stop",tool_calls:m.length>0?m:void 0,raw:p}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t={model:e.model,systemInstruction:this.extractSystemInstruction(e.messages)};e.tools&&e.tools.length>0&&(t.tools=[{functionDeclarations:e.tools.map(p=>({name:this.sanitizeToolName(p.function.name),description:p.function.description,parameters:this.sanitizeSchema(p.function.parameters)}))}]);let r=e.__toolpack_request_id||`str-${Date.now()}`;h(`[Gemini][${r}] Stream request: model=${e.model}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),e.tools&&e.tools.length>0&&h(`[Gemini][${r}] First tool: ${D(e.tools[0],800)}`),X(r,"Gemini",e.messages);let o=this.genAI.getGenerativeModel(t),{history:n,lastUserMessage:a}=await this.formatHistory(e.messages,e.mediaOptions),c=await o.startChat({history:n,generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:e.response_format==="json_object"?"application/json":"text/plain"}}).sendMessageStream(a);for await(let p of c.stream){for(let m of p.candidates?.[0]?.content?.parts||[])m.functionCall?(h(`[Gemini][${r}] Stream finish_reason=tool_calls name=${m.functionCall.name}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(m.functionCall.name,e.tools),arguments:m.functionCall.args||{}}]}):m.text&&(yield{delta:m.text});try{let m=p.text();m&&!p.candidates?.[0]?.content?.parts?.some(u=>u.text)&&(yield{delta:m})}catch{}}}catch(t){throw this.handleError(t)}}async embed(e){try{let t=this.genAI.getGenerativeModel({model:e.model});return Array.isArray(e.input)?{embeddings:await Promise.all(e.input.map(async o=>(await t.embedContent(o)).embedding.values))}:{embeddings:[(await t.embedContent(e.input)).embedding.values]}}catch(t){throw this.handleError(t)}}extractSystemInstruction(e){let t=e.filter(r=>r.role==="system");if(t.length!==0)return t.map(r=>typeof r.content=="string"?r.content:r.content===null?"":r.content.map(o=>o.text).join(`
192
+ `)]),g=await fetch(c,{method:"POST",headers:{"Content-Type":`multipart/related; boundary=${p}`},body:u});if(!g.ok){let y=await g.text();throw new Error(`Gemini file upload failed: ${g.status} ${y}`)}let w=await g.json();return{id:w.file?.name||w.name,url:w.file?.uri||w.uri}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{let t=this.genAI.apiKey,o=`https://generativelanguage.googleapis.com/v1beta/${e}?key=${t}`,r=await fetch(o,{method:"DELETE"});if(!r.ok){let s=await r.text();throw new Error(`Gemini file deletion failed: ${r.status} ${s}`)}}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(g=>({name:this.sanitizeToolName(g.function.name),description:g.function.description,parameters:this.sanitizeSchema(g.function.parameters)}))}],h(`[Gemini][${t}] Sending ${e.tools.length} tools`),e.tools.length>0&&h(`[Gemini][${t}] First tool: ${A(e.tools[0],800)}`)):h(`[Gemini][${t}] NO TOOLS in request`),h(`[Gemini][${t}] generate() request: model=${e.model}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),ee(t,"Gemini",e.messages);let r=this.genAI.getGenerativeModel(o),{history:s,lastUserMessage:i}=await this.formatHistory(e.messages,e.mediaOptions),p=await(await r.startChat({history:s,generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:e.response_format==="json_object"?"application/json":"text/plain"}}).sendMessage(i)).response,m=[],u="";for(let g of p.candidates||[])for(let w of g.content?.parts||[])if(w.text&&(u+=w.text),w.functionCall){let y=w.functionCall;m.push({id:`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(y.name,e.tools),arguments:y.args||{}})}return h(`[Gemini][${t}] Response finish_reason=${m.length>0?"tool_calls":"stop"} tool_calls=${m.length} content_preview=${A(u,200)}`),{content:u||null,usage:{prompt_tokens:p.usageMetadata?.promptTokenCount||0,completion_tokens:p.usageMetadata?.candidatesTokenCount||0,total_tokens:p.usageMetadata?.totalTokenCount||0},finish_reason:m.length>0?"tool_calls":"stop",tool_calls:m.length>0?m:void 0,raw:p}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t={model:e.model,systemInstruction:this.extractSystemInstruction(e.messages)};e.tools&&e.tools.length>0&&(t.tools=[{functionDeclarations:e.tools.map(p=>({name:this.sanitizeToolName(p.function.name),description:p.function.description,parameters:this.sanitizeSchema(p.function.parameters)}))}]);let o=e.__toolpack_request_id||`str-${Date.now()}`;h(`[Gemini][${o}] Stream request: model=${e.model}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),e.tools&&e.tools.length>0&&h(`[Gemini][${o}] First tool: ${A(e.tools[0],800)}`),ee(o,"Gemini",e.messages);let r=this.genAI.getGenerativeModel(t),{history:s,lastUserMessage:i}=await this.formatHistory(e.messages,e.mediaOptions),c=await r.startChat({history:s,generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:e.response_format==="json_object"?"application/json":"text/plain"}}).sendMessageStream(i);for await(let p of c.stream){for(let m of p.candidates?.[0]?.content?.parts||[])m.functionCall?(h(`[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(u=>u.text)&&(yield{delta:m})}catch{}}}catch(t){throw this.handleError(t)}}async embed(e){try{let t=this.genAI.getGenerativeModel({model:e.model});return Array.isArray(e.input)?{embeddings:await Promise.all(e.input.map(async 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(`
193
193
  `)).join(`
194
- `)}async formatHistory(e,t={}){let r=e.filter(m=>m.role!=="system");if(r.length===0)return{history:[],lastUserMessage:""};let o=r[r.length-1],n=r.slice(0,r.length-1),{normalizeImagePart:a}=await Promise.resolve().then(()=>(ze(),to)),i=async m=>typeof m=="string"?[{text:m}]:m===null?[]:(await Promise.all(m.map(async g=>{if(g.type==="text")return{text:g.text};if(g.type==="image_data"||g.type==="image_file"||g.type==="image_url")try{let{data:w,mimeType:y}=await a(g);return{inlineData:{mimeType:y,data:w}}}catch{return g.type==="image_url"?{text:`[Image: ${g.image_url.url}]`}:{text:"[Unresolvable Image]"}}return null}))).filter(Boolean),c=await Promise.all(n.map(async m=>{if(m.role==="tool"&&m.tool_call_id)return{role:"function",parts:[{functionResponse:{name:this.sanitizeToolName(m.name||m.tool_call_id),response:{name:this.sanitizeToolName(m.name||m.tool_call_id),content:typeof m.content=="string"?m.content:JSON.stringify(m.content)}}}]};if(m.role==="assistant"&&m.tool_calls&&m.tool_calls.length>0){let u=[];if(typeof m.content=="string"&&m.content)u.push({text:m.content});else if(Array.isArray(m.content)){let g=m.content.filter(w=>typeof w=="object"&&w.type==="text").map(w=>w.text).join(`
195
- `);g&&u.push({text:g})}for(let g of m.tool_calls)u.push({functionCall:{name:this.sanitizeToolName(g.function.name),args:typeof g.function.arguments=="string"?JSON.parse(g.function.arguments||"{}"):g.function.arguments}});return{role:"model",parts:u}}return{role:m.role==="user"?"user":"model",parts:await i(m.content)}})),p=typeof o.content=="string"?o.content:await i(o.content);return{history:c,lastUserMessage:p}}handleError(e){return e.status===429?new me(e.message,void 0,e):e.status>=400&&e.status<500?new N(e.message,e):e.message&&e.message.includes("API key")?new pe(e.message,e):new I(e.message||"Gemini Error","GEMINI_ERROR",e.status||500,e)}};l();var so=T(require("fs"),1),_i=T(require("path"),1),ah="toolpack.config.json";function cn(s){if(s&&so.existsSync(s))return s;let e=_i.join(process.cwd(),ah);return so.existsSync(e)?e:null}function lh(s){if(!s)return null;try{let e=so.readFileSync(s,"utf-8");return JSON.parse(e)}catch{return null}}var no=null;function Vo(s){if(no)return no;let e=s||cn();return no=lh(e)||{},no}function ki(){no=null}function Ri(s){return(Vo(s).ollama?.models||[]).map(r=>({type:`ollama-${r.model.replace(/[:.]/g,"-")}`,model:r.model,label:r.label||r.model}))}function io(s){return Vo(s).ollama?.baseUrl||"http://localhost:11434"}l();l();de();k();l();var pn=T(require("http"),1);function ne(s,e,t,r,o=12e4){return new Promise((n,a)=>{let i=new URL(e,s),c={hostname:i.hostname,port:i.port,path:i.pathname,method:t,headers:{"Content-Type":"application/json"},timeout:o},p=pn.default.request(c,m=>{let u=[];m.on("data",g=>u.push(g)),m.on("end",()=>{n({status:m.statusCode||0,body:Buffer.concat(u).toString("utf-8")})})});p.on("error",m=>a(m)),p.on("timeout",()=>{p.destroy(),a(new Error("Request timed out"))}),r&&p.write(JSON.stringify(r)),p.end()})}function Xo(s,e,t,r=12e4,o){let n,a=!1;return o&&o.addEventListener("abort",()=>{a=!0,n&&n.destroy()},{once:!0}),{stream:async function*(){let c=new URL(e,s),p={hostname:c.hostname,port:c.port,path:c.pathname,method:"POST",headers:{"Content-Type":"application/json"},timeout:r},m=await new Promise((g,w)=>{n=pn.default.request(p,g),n.on("error",w),n.on("timeout",()=>{n.destroy(),w(new Error("Stream request timed out"))}),n.write(JSON.stringify(t)),n.end()});if(m.statusCode&&m.statusCode>=400){let g="";for await(let w of m)g+=w.toString();throw new Error(`Ollama HTTP ${m.statusCode}: ${g}`)}let u="";for await(let g of m){if(a)break;let w=g.toString();if(u+=w,u.includes('"error"'))try{let b=JSON.parse(u.trim());if(b.error)throw new Error(`Ollama: ${b.error}`)}catch(b){if(b.message.startsWith("Ollama:"))throw b}let y=u.split(`
196
- `);u=y.pop()||"";for(let b of y)b.trim()&&(yield b)}u.trim()&&!a&&(yield u.trim())}(),abort:()=>{a=!0,n&&n.destroy()}}}var xe=class extends K{config;baseUrl;timeout;modelName;constructor(e){super(),this.config=e,this.baseUrl=e.baseUrl||"http://localhost:11434",this.timeout=e.timeout||12e4,this.modelName=e.model}getDisplayName(){return"Ollama"}async getModels(){try{return(await this.listModels()).map(t=>({id:t.name,displayName:t.name,capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!0,vision:!0}}))}catch{return[]}}async connect(){let e=await this.listModels(),t=this.config.model.split(":")[0].toLowerCase();if(!e.some(o=>o.name.split(":")[0].toLowerCase()===t||o.name.toLowerCase()===this.config.model.toLowerCase()))throw new N(`Model "${this.config.model}" is not pulled in Ollama. Run: ollama pull ${this.config.model}
197
- Available models: ${e.map(o=>o.name).join(", ")||"(none)"}`);return e}async listModels(){try{let e=await ne(this.baseUrl,"/api/tags","GET",void 0,5e3);if(e.status!==200)throw new I(`Ollama returned status ${e.status}`,"OLLAMA_ERROR",e.status);return JSON.parse(e.body).models||[]}catch(e){throw e instanceof I?e:new we(`Cannot connect to Ollama at ${this.baseUrl}. Is Ollama running? (ollama serve)`,e)}}async isAvailable(){try{return await ne(this.baseUrl,"/api/tags","GET",void 0,3e3),!0}catch{return!1}}async isModelAvailable(e){try{let t=await this.listModels(),r=(e||this.config.model).toLowerCase(),o=r.split(":")[0];return t.some(n=>n.name.split(":")[0].toLowerCase()===o||n.name.toLowerCase()===r)}catch{return!1}}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(o=>this.sanitizeToolName(o.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){let t=e.__toolpack_request_id||`gen-${Date.now()}`,r=await Promise.all(e.messages.map(a=>this.toOllamaMessage(a,e.mediaOptions))),o=e.model||this.config.model,n={model:o,messages:r,stream:!1,options:{temperature:e.temperature??this.config.temperature??.7,num_ctx:this.config.numCtx}};e.tools&&e.tools.length>0&&e.tool_choice!=="none"&&(n.tools=e.tools.map(a=>({type:"function",function:{name:this.sanitizeToolName(a.function.name),description:a.function.description,parameters:a.function.parameters}})),h(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&h(`[Ollama][${t}] First tool: ${D(e.tools[0],800)}`),h(`[Ollama][${t}] NO TOOLS in request`)),h(`[Ollama][${t}] generate() request: model=${o}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),X(t,"Ollama",e.messages);try{let a=await ne(this.baseUrl,"/api/chat","POST",n,this.timeout);if(a.status!==200)throw this.handleHttpError(a.status,a.body);let i=JSON.parse(a.body),c=[];if(i.message?.tool_calls)for(let m of i.message.tool_calls)c.push({id:`ollama_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(m.function.name,e.tools),arguments:m.function.arguments||{}});let p={content:i.message?.content||null,usage:i.prompt_eval_count!=null?{prompt_tokens:i.prompt_eval_count||0,completion_tokens:i.eval_count||0,total_tokens:(i.prompt_eval_count||0)+(i.eval_count||0)}:void 0,finish_reason:c.length>0?"tool_calls":i.done?"stop":void 0,tool_calls:c.length>0?c:void 0,raw:i};return h(`[Ollama][${t}] Response finish_reason=${p.finish_reason} tool_calls=${c.length} content_preview=${D(p.content,200)}`),p}catch(a){throw a instanceof I?a:new we(`Failed to generate with Ollama model "${o}": ${a.message}`,a)}}async*stream(e){let t=e.__toolpack_request_id||`str-${Date.now()}`,r=await Promise.all(e.messages.map(i=>this.toOllamaMessage(i,e.mediaOptions))),o=e.model||this.config.model,n={model:o,messages:r,stream:!0,options:{temperature:e.temperature??this.config.temperature??.7,num_ctx:this.config.numCtx}};e.tools&&e.tools.length>0&&e.tool_choice!=="none"&&(n.tools=e.tools.map(i=>({type:"function",function:{name:this.sanitizeToolName(i.function.name),description:i.function.description,parameters:i.function.parameters}})),h(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&h(`[Ollama][${t}] First tool: ${D(e.tools[0],800)}`),h(`[Ollama][${t}] NO TOOLS in request`)),h(`[Ollama][${t}] Stream request: model=${o}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),X(t,"Ollama",e.messages);let{stream:a}=Xo(this.baseUrl,"/api/chat",n,this.timeout,e.signal);try{for await(let i of a)try{let c=JSON.parse(i);if(c.message?.content){let p=c.message.tool_calls&&c.message.tool_calls.length>0;yield{delta:c.message.content,finish_reason:c.done&&!p?"stop":void 0,usage:c.done&&c.prompt_eval_count!=null?{prompt_tokens:c.prompt_eval_count||0,completion_tokens:c.eval_count||0,total_tokens:(c.prompt_eval_count||0)+(c.eval_count||0)}:void 0}}if(c.message?.tool_calls&&c.message.tool_calls.length>0){let p=c.message.tool_calls.map(m=>({id:`ollama_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(m.function.name,e.tools),arguments:m.function.arguments||{}}));h(`[Ollama][${t}] Stream finish_reason=tool_calls name=${p[0]?.name}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:p}}if(c.done&&!c.message?.content&&!c.message?.tool_calls){be(`[Ollama][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"};return}}catch{}}catch(i){throw new we(`Stream failed for Ollama model "${o}": ${i.message}`,i)}}async embed(e){let t=e.__toolpack_request_id||`emb-${Date.now()}`,r=typeof e.input=="string"?[e.input]:e.input,o=e.model||this.config.model;h(`[Ollama][${t}] Embedding request: model=${o}, inputs=${r.length}`);try{let n=await ne(this.baseUrl,"/api/embed","POST",{model:o,input:r},this.timeout);if(n.status!==200)throw this.handleHttpError(n.status,n.body);return{embeddings:JSON.parse(n.body).embeddings||[]}}catch(n){throw n instanceof I?n:new we(`Embedding failed for Ollama model "${o}": ${n.message}`,n)}}async disconnect(){}async toOllamaMessage(e,t={}){let r="",o=[],{normalizeImagePart:n}=await Promise.resolve().then(()=>(ze(),to));if(typeof e.content=="string")r=e.content;else if(e.content!==null){for(let i of e.content)if(i.type==="text")r+=i.text+`
198
- `;else if(i.type==="image_url"||i.type==="image_data"||i.type==="image_file")try{let{data:c}=await n(i);o.push(c)}catch{i.type==="image_url"?r+=`[Image: ${i.image_url.url}]
199
- `:r+=`[Unresolvable Image]
200
- `}r=r.trim()}let a={role:e.role,content:r};return o.length>0&&(a.images=o),e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0?a.tool_calls=e.tool_calls.map(i=>({function:{name:this.sanitizeToolName(i.function.name),arguments:typeof i.function.arguments=="string"?JSON.parse(i.function.arguments||"{}"):i.function.arguments}})):e.role==="tool"&&(a.content=r||JSON.stringify(e.content),e.name&&(a.tool_name=this.sanitizeToolName(e.name))),a}handleHttpError(e,t){let r=`Ollama error (HTTP ${e})`;try{let o=JSON.parse(t);o.error&&(r=`Ollama: ${o.error}`)}catch{}return e===404?new N(`Model not found: ${r}`):new I(r,"OLLAMA_ERROR",e)}};l();var Ke=class extends K{baseUrl;timeout;adapterCache=new Map;capabilityCache=new Map;constructor(e){super(),this.baseUrl=e?.baseUrl||"http://localhost:11434",this.timeout=12e4}getDisplayName(){return"Ollama"}async getModels(){let e;try{let t=await ne(this.baseUrl,"/api/tags","GET",void 0,5e3);if(t.status!==200)return[];e=JSON.parse(t.body).models||[]}catch{return[]}return Promise.all(e.map(t=>this.buildModelInfo(t)))}async generate(e){return this.getAdapterForModel(e.model).generate(this.stripToolsIfNeeded(e))}async*stream(e){yield*this.getAdapterForModel(e.model).stream(this.stripToolsIfNeeded(e))}async embed(e){return this.getAdapterForModel(e.model).embed(e)}async disconnect(){this.adapterCache.clear(),this.capabilityCache.clear()}stripToolsIfNeeded(e){let t=this.capabilityCache.get(e.model);if(t&&!t.toolCalling&&e.tools&&e.tools.length>0){let{tools:r,tool_choice:o,...n}=e,a=n,i={role:"system",content:"You do not have access to any tools or functions. Do not attempt to call tools, output tool invocations, or reference tool usage. Answer the user directly using only your own knowledge."};return a.messages=[...a.messages,i],a}return e}getAdapterForModel(e){let t=this.adapterCache.get(e);return t||(t=new xe({model:e,baseUrl:this.baseUrl,timeout:this.timeout}),this.adapterCache.set(e,t)),t}async buildModelInfo(e){let t=!1,r=!1,o=!1;try{let i=await ne(this.baseUrl,"/api/show","POST",{model:e.name},3e3);if(i.status===200){let p=(JSON.parse(i.body).details?.families||[]).map(m=>m.toLowerCase());r=p.some(m=>["clip","mllama"].includes(m)),o=p.some(m=>m.includes("bert")||m.includes("nomic"))}}catch{}t=await this.probeToolSupport(e.name);let n=e.name.toLowerCase();r||(r=["llava","vision","bakllava","moondream"].some(c=>n.includes(c))),o||(o=["nomic-embed","mxbai-embed","all-minilm","bge-","snowflake-arctic-embed"].some(c=>n.includes(c)));let a={toolCalling:t,vision:r,embeddings:o};return this.capabilityCache.set(e.name,a),{id:e.name,displayName:e.name,capabilities:{chat:!0,streaming:!0,toolCalling:t,embeddings:o,vision:r}}}async probeToolSupport(e){try{let t=await ne(this.baseUrl,"/api/chat","POST",{model:e,messages:[{role:"user",content:"hi"}],tools:[{type:"function",function:{name:"__probe",description:"probe",parameters:{type:"object",properties:{}}}}],stream:!1},1e4);return t.status>=400?!1:!JSON.parse(t.body).error}catch{return!1}}};l();var mn=[{model:"qwen2.5-coder:3b",label:"Qwen 2.5 Coder 3B",params:"3B",size:"~2GB",selectorCapability:5,description:"Best code understanding at small size. Excellent HTML/CSS comprehension."},{model:"phi3:mini",label:"Phi-3 Mini",params:"3.8B",size:"~2.3GB",selectorCapability:4,description:"Strong reasoning for its size. Good at structured output."},{model:"codegemma:2b",label:"CodeGemma 2B",params:"2B",size:"~1.4GB",selectorCapability:4,description:"Compact code model from Google. Fast inference."},{model:"deepseek-coder:1.3b",label:"DeepSeek Coder 1.3B",params:"1.3B",size:"~0.8GB",selectorCapability:3,description:"Smallest viable option. Very fast but less accurate."},{model:"qwen2.5-coder:7b",label:"Qwen 2.5 Coder 7B",params:"7B",size:"~4.5GB",selectorCapability:5,description:"Higher accuracy than 3B variant. Requires more RAM/VRAM."},{model:"codellama:7b",label:"Code Llama 7B",params:"7B",size:"~3.8GB",selectorCapability:4,description:"Meta code model. Solid HTML/CSS understanding."}];function Ei(){return mn[0].model}function Di(s){let e=s.toLowerCase();return mn.some(t=>t.model.toLowerCase()===e||t.model.split(":")[0].toLowerCase()===e.split(":")[0].toLowerCase())}function Ni(){return[...mn]}l();var dn=T(require("openai"),1);de();k();var ao=class extends K{client;constructor(e,t){super(),this.client=new dn.default({apiKey:e,baseURL:t,timeout:6e4,maxRetries:2})}supportsFileUpload(){return!0}async uploadFile(e){try{let t=await import("fs");if(!e.filePath)throw new N("OpenAI uploadFile requires a filePath.");return{id:(await this.client.files.create({file:t.createReadStream(e.filePath),purpose:e.purpose||"vision"})).id}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{await this.client.files.delete(e)}catch(t){throw this.handleError(t)}}getDisplayName(){return"OpenAI"}async getModels(){return[{id:"gpt-4.1-mini",displayName:"GPT-4.1 Mini",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1047576,maxOutputTokens:32768,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:null,costTier:"low"},{id:"gpt-4.1",displayName:"GPT-4.1",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1047576,maxOutputTokens:32768,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:null,costTier:"medium"},{id:"gpt-5.1",displayName:"GPT-5.1",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:4e5,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"medium"},{id:"gpt-5.2",displayName:"GPT-5.2",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:4e5,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"high"},{id:"gpt-5.4",displayName:"GPT-5.4",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:105e4,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"high"},{id:"gpt-5.4-pro",displayName:"GPT-5.4 Pro",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:105e4,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"extended",costTier:"premium"}]}sanitizeToolName(e){return e.replace(/\./g,"_")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,o={messages:await Promise.all(e.messages.map(u=>this.toOpenAIMessage(u,e.mediaOptions))),model:e.model,temperature:e.temperature,max_tokens:e.max_tokens,top_p:e.top_p,response_format:e.response_format==="json_object"?{type:"json_object"}:void 0,stream:!1},n=new Map;e.tools&&e.tools.length>0&&(o.tools=e.tools.map(u=>{let g=this.sanitizeToolName(u.function.name);return n.set(g,u.function.name),{type:"function",function:{name:g,description:u.function.description,parameters:u.function.parameters}}}),o.tool_choice=e.tool_choice||"auto",h(`[OpenAI][${t}] Sending ${o.tools.length} tools with tool_choice: ${o.tool_choice}`),h(`[OpenAI][${t}] First tool: ${D(o.tools[0],800)}`)),h(`[OpenAI][${t}] Request params: ${D({model:o.model,messages_count:o.messages.length,has_tools:!!o.tools,tools_count:o.tools?.length,tool_choice:o.tool_choice},800)}`),X(t,"OpenAI",o.messages);let a=await this.client.chat.completions.create(o,e.signal?{signal:e.signal}:void 0);be(`[OpenAI][${t}] Raw completion: ${JSON.stringify(a)}`);let i=a.choices[0].message;h(`[OpenAI][${t}] Response: finish_reason=${a.choices[0].finish_reason}`),h(`[OpenAI][${t}] Response has tool_calls: ${!!i.tool_calls}, count: ${i.tool_calls?.length||0}`),h(`[OpenAI][${t}] Response content: ${JSON.stringify(i.content)}`),i.content&&h(`[OpenAI][${t}] Response content preview: ${D(i.content,200)}`);let c=a.choices[0],p,m=c.message.tool_calls;return m&&m.length>0&&(p=m.map(u=>({id:u.id,name:n.get(u.function.name)||u.function.name,arguments:JSON.parse(u.function.arguments)}))),{content:c.message.content,usage:a.usage?{prompt_tokens:a.usage.prompt_tokens,completion_tokens:a.usage.completion_tokens,total_tokens:a.usage.total_tokens}:void 0,finish_reason:c.finish_reason,tool_calls:p,raw:a}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`str-${Date.now()}`,o={messages:await Promise.all(e.messages.map(c=>this.toOpenAIMessage(c,e.mediaOptions))),model:e.model,temperature:e.temperature,max_tokens:e.max_tokens,top_p:e.top_p,response_format:e.response_format==="json_object"?{type:"json_object"}:void 0,stream:!0},n=new Map;e.tools&&e.tools.length>0?(o.tools=e.tools.map(c=>{let p=this.sanitizeToolName(c.function.name);return n.set(p,c.function.name),{type:"function",function:{name:p,description:c.function.description,parameters:c.function.parameters}}}),o.tool_choice=e.tool_choice||"auto",h(`[OpenAI][${t}] Sending ${o.tools.length} tools with tool_choice: ${o.tool_choice}`),h(`[OpenAI][${t}] First tool: ${D(o.tools[0],800)}`)):h(`[OpenAI][${t}] NO TOOLS in request`),h(`[OpenAI][${t}] Stream request: model=${o.model}, messages=${o.messages.length}, tools=${o.tools?.length||0}, tool_choice=${o.tool_choice??"unset"}`),X(t,"OpenAI",o.messages);let a=await this.client.chat.completions.create(o,e.signal?{signal:e.signal}:void 0),i=new Map;for await(let c of a){let p=c.choices[0];if(p.finish_reason&&be(`[OpenAI][${t}] Stream chunk finish_reason=${p.finish_reason}`),p.delta.tool_calls)for(let m of p.delta.tool_calls){let u=m.index;i.has(u)||i.set(u,{id:m.id||"",name:m.function?.name||"",args:""});let g=i.get(u);m.id&&(g.id=m.id),m.function?.name&&(g.name=m.function.name),m.function?.arguments&&(g.args+=m.function.arguments),be(`[OpenAI][${t}] tool_call_delta idx=${u} id=${m.id||g.id||""} name=${m.function?.name||g.name||""} args_delta=${D(m.function?.arguments||"",200)}`)}if(p.delta.content&&(yield{delta:p.delta.content,finish_reason:p.finish_reason,usage:c.usage}),!p.delta.content&&p.finish_reason&&p.finish_reason!=="tool_calls"&&(yield{delta:"",finish_reason:p.finish_reason,usage:c.usage}),p.finish_reason==="tool_calls"&&i.size>0){let m=Array.from(i.values()).map(u=>({id:u.id,name:n.get(u.name)||u.name,arguments:JSON.parse(u.args||"{}")}));h(`[OpenAI][${t}] Stream finish_reason=tool_calls accumulated_calls=${m.length} names=${m.map(u=>u.name).join(", ")}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:m}}}}catch(t){throw this.handleError(t)}}async embed(e){try{let t=typeof e.input=="string"?[e.input]:e.input,r=await this.client.embeddings.create({model:e.model,input:t});return{embeddings:r.data.map(o=>o.embedding),usage:r.usage}}catch(t){throw this.handleError(t)}}async toOpenAIMessage(e,t={}){if(e.role==="tool"&&e.tool_call_id)return{role:"tool",tool_call_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content??"")};if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0)return{role:"assistant",content:typeof e.content=="string"?e.content:"",tool_calls:e.tool_calls.map(n=>({id:n.id,type:"function",function:{name:this.sanitizeToolName(n.function.name),arguments:n.function.arguments}}))};if(typeof e.content=="string")return{role:e.role,content:e.content};if(e.content===null||e.content===void 0)return{role:e.role,content:""};let{normalizeImagePart:r}=await Promise.resolve().then(()=>(ze(),to)),o=await Promise.all(e.content.map(async n=>{if(n.type==="text")return{type:"text",text:n.text};if(n.type==="image_url")return{type:"image_url",image_url:{url:n.image_url.url}};if(n.type==="image_data"||n.type==="image_file"){let{data:a,mimeType:i}=await r(n);return{type:"image_url",image_url:{url:`data:${i};base64,${a}`}}}return null}));return{role:e.role,content:o.filter(Boolean)}}handleError(e){if(e instanceof dn.default.APIError){let t=e.message;return e.status===401?new pe(t,e):e.status===429?new me(t,void 0,e):e.status&&e.status>=400&&e.status<500?new N(t,e):new I(t,e.code||"OPENAI_ERROR",e.status||500,e)}return new I("Unknown error","UNKNOWN",500,e)}};ze();l();Xt();l();Xt();var Jt=class{tools=new Map;projects=new Map;config=H;register(e){this.tools.set(e.name,e)}registerCustom(e){this.tools.set(e.name,e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getNames(){return Array.from(this.tools.keys())}getByCategory(e){return Array.from(this.tools.values()).filter(t=>t.category===e)}getEnabled(){if(this.config.enabledTools.length===0&&this.config.enabledToolCategories.length===0)return Array.from(this.tools.values());let e=this.getByNames(this.config.enabledTools),t=this.getByCategories(this.config.enabledToolCategories),r=new Set,o=[];for(let n of[...e,...t])r.has(n.name)||(r.add(n.name),o.push(n));return o}getSchemas(e){return(e?e.map(r=>this.tools.get(r)).filter(Boolean):this.getEnabled()).map(r=>({name:r.name,displayName:r.displayName,description:r.description,parameters:r.parameters,category:r.category}))}getByNames(e){return e.map(t=>this.tools.get(t)).filter(Boolean)}getByCategories(e){let t=new Set(e);return Array.from(this.tools.values()).filter(r=>t.has(r.category))}getCategories(){let e=new Set;for(let t of this.tools.values())e.add(t.category);return Array.from(e)}getAll(){return Array.from(this.tools.values())}setConfig(e){this.config=e}getConfig(){return this.config}get size(){return this.tools.size}async validateDependencies(e){let t=e.dependencies;if(!t||Object.keys(t).length===0)return[];let r=[];for(let o of Object.keys(t))try{await import(o)}catch{r.push(o)}return r}async loadProject(e){let t=await this.validateDependencies(e);if(t.length>0)throw new Error(`Tool project "${e.manifest.name}" has missing dependencies: ${t.join(", ")}. Install them with: npm install ${t.join(" ")}`);this.projects.set(e.manifest.name,e);for(let r of e.tools)this.register(r)}async loadProjects(e){for(let t of e)await this.loadProject(t)}getProject(e){return this.projects.get(e)}getProjects(){return Array.from(this.projects.values())}getProjectNames(){return Array.from(this.projects.keys())}async loadBuiltIn(){let{fsToolsProject:e}=await Promise.resolve().then(()=>(An(),Hl)),{execToolsProject:t}=await Promise.resolve().then(()=>(Un(),Oc)),{systemToolsProject:r}=await Promise.resolve().then(()=>(Yn(),fp)),{httpToolsProject:o}=await Promise.resolve().then(()=>(rs(),Yp)),{webToolsProject:n}=await Promise.resolve().then(()=>(ys(),wd)),{codingToolsProject:a}=await Promise.resolve().then(()=>(Os(),af)),{gitToolsProject:i}=await Promise.resolve().then(()=>(js(),If)),{diffToolsProject:c}=await Promise.resolve().then(()=>(qs(),Yf)),{dbToolsProject:p}=await Promise.resolve().then(()=>(Bs(),Cg)),{cloudToolsProject:m}=await Promise.resolve().then(()=>(Hs(),Mg));await this.loadProjects([e,t,r,o,n,a,i,c,p,m])}};is();l();k();function Og(s){if(!s.key||!/^[a-z0-9-]+$/.test(s.key))throw new Error(`Invalid tool project key: "${s.key}". Must be non-empty, lowercase, and contain no spaces (use hyphens).`);if(!s.name.trim())throw new Error("Tool project name cannot be empty.");if(!s.tools||s.tools.length===0)throw new Error("Tool project must contain at least one tool.");for(let t of s.tools){if(!t.name)throw new Error("Tool is missing a name.");if(!t.description)throw new Error(`Tool "${t.name}" is missing a description.`);if(!t.parameters)throw new Error(`Tool "${t.name}" is missing parameters.`);if(typeof t.execute!="function")throw new Error(`Tool "${t.name}" is missing an execute function.`);t.category!==s.category&&E(`[Toolpack] Tool "${t.name}" has category "${t.category}" which does not match project category "${s.category}".`)}let e=s.tools.map(t=>t.name);return{manifest:{key:s.key,name:s.name,displayName:s.displayName,version:s.version,description:s.description,author:s.author,repository:s.repository,category:s.category,tools:e},dependencies:s.dependencies,tools:s.tools}}An();Un();Yn();rs();ys();Os();js();qs();Bs();Hs();l();l();var Ig=require("child_process"),jg=require("events");k();var jo=class extends Error{constructor(e,t){super(`MCP request timed out after ${t}ms: ${e}`),this.name="McpTimeoutError"}},ae=class extends Error{constructor(t,r){super(t);this.exitCode=r;this.name="McpConnectionError"}exitCode},Ht=class extends jg.EventEmitter{constructor(t){super();this.config=t;this.defaultTimeoutMs=t.requestTimeoutMs??3e4,this.autoReconnect=t.autoReconnect??!1,this.maxReconnectAttempts=t.maxReconnectAttempts??3,this.reconnectDelayMs=t.reconnectDelayMs??1e3}config;process=null;messageQueue=new Map;nextId=1;buffer="";_connected=!1;_shuttingDown=!1;_reconnectAttempts=0;defaultTimeoutMs;autoReconnect;maxReconnectAttempts;reconnectDelayMs;get connected(){return this._connected&&this.process!==null}async connect(){if(this._shuttingDown)throw new ae("Client is shutting down");return new Promise((t,r)=>{try{if(this.buffer="",this.process=(0,Ig.spawn)(this.config.command,this.config.args||[],{env:{...process.env,...this.config.env},stdio:["pipe","pipe","pipe"]}),!this.process.stdout||!this.process.stdin)throw new ae("Failed to spawn MCP server: stdout/stdin unavailable");this.process.stdout.on("data",o=>{this.handleData(o)}),this.process.stderr&&this.process.stderr.on("data",o=>{E(`[MCP server stderr] ${o.toString().trim()}`)}),this.process.on("error",o=>{this._connected=!1,this.emit("error",o)}),this.process.on("exit",o=>{let n=this._connected;this._connected=!1,this.process=null,this.rejectAllPending(new ae(`MCP server exited with code ${o}`,o)),this.emit("close",o),n&&!this._shuttingDown&&this.autoReconnect&&this.attemptReconnect()}),this._connected=!0,this._reconnectAttempts=0,setTimeout(t,500)}catch(o){r(o)}})}async attemptReconnect(){if(this._reconnectAttempts>=this.maxReconnectAttempts){this.emit("reconnect_failed",this._reconnectAttempts);return}this._reconnectAttempts++;let t=this._reconnectAttempts;if(this.emit("reconnecting",{attempt:t,max:this.maxReconnectAttempts}),await new Promise(r=>setTimeout(r,this.reconnectDelayMs*t)),!this._shuttingDown)try{await this.connect(),this.emit("reconnected",{attempt:t})}catch(r){this.emit("reconnect_error",{attempt:t,error:r})}}handleData(t){this.buffer+=t.toString();let r;for(;(r=this.buffer.indexOf(`
201
- `))!==-1;){let o=this.buffer.slice(0,r).trim();if(this.buffer=this.buffer.slice(r+1),o)try{let n=JSON.parse(o);this.handleMessage(n)}catch{}}}handleMessage(t){if(t.id&&(t.result!==void 0||t.error)){let r=this.messageQueue.get(t.id);r&&(r.timer&&clearTimeout(r.timer),t.error?r.reject(new Error(t.error.message)):r.resolve(t.result),this.messageQueue.delete(t.id))}else t.method&&(this.emit("notification",t),this.emit(t.method,t.params))}async callTool(t,r={},o){return this.request("tools/call",{name:t,arguments:r},o)}async readResource(t,r){return this.request("resources/read",{uri:t},r)}async request(t,r,o){if(!this.process||!this.process.stdin)throw new ae("Client not connected");let n=this.nextId++,a=o??this.defaultTimeoutMs,i={jsonrpc:"2.0",id:n,method:t,params:r};return new Promise((c,p)=>{let m;a>0&&(m=setTimeout(()=>{let u=this.messageQueue.get(n);u&&(this.messageQueue.delete(n),u.reject(new jo(t,a)))},a)),this.messageQueue.set(n,{resolve:c,reject:p,timer:m});try{this.process.stdin.write(JSON.stringify(i)+`
202
- `)}catch(u){m&&clearTimeout(m),this.messageQueue.delete(n),p(u)}})}async disconnect(t=3e3){if(this._shuttingDown=!0,this.rejectAllPending(new ae("Client disconnecting")),!this.process){this._shuttingDown=!1;return}let r=this.process;return new Promise(o=>{let n=!1,a=()=>{n||(n=!0,this.process=null,this._connected=!1,this._shuttingDown=!1,o())};r.once("exit",a),r.kill("SIGTERM"),setTimeout(()=>{if(!n){try{r.kill("SIGKILL")}catch{}a()}},t)})}kill(){this._shuttingDown=!0,this.rejectAllPending(new ae("Client killed")),this.process&&(this.process.kill("SIGKILL"),this.process=null),this._connected=!1,this._shuttingDown=!1}rejectAllPending(t){for(let[r,o]of this.messageQueue)o.timer&&clearTimeout(o.timer),o.reject(t);this.messageQueue.clear()}};k();var Fo=class{constructor(e){this.config=e}config;clients=new Map;serverConfigs=new Map;toolDefinitions=new Map;async connectServer(e){let{name:t,displayName:r,toolPrefix:o,...n}=e;v(`[MCP] Connecting to server: ${r||t}`);try{let a=new Ht({...n,requestTimeoutMs:n.requestTimeoutMs??this.config.defaultTimeoutMs,autoReconnect:n.autoReconnect??this.config.autoReconnect??!0});this.setupClientEvents(a,t),await a.connect();let c=(await a.request("tools/list"))?.tools||[];v(`[MCP] Discovered ${c.length} tools from ${t}`);let p=o||`mcp.${t}.`;for(let m of c){let u=this.convertMcpTool(m,t,p,a);this.toolDefinitions.set(u.name,u)}this.clients.set(t,a),this.serverConfigs.set(t,e)}catch(a){throw Y(`[MCP] Failed to connect to ${t}: ${a}`),a}}async connectAll(){let e=this.config.servers.filter(t=>t.autoConnect!==!1).map(t=>this.connectServer(t));await Promise.allSettled(e)}async disconnectServer(e){let t=this.clients.get(e);if(!t){E(`[MCP] Server ${e} not found`);return}v(`[MCP] Disconnecting from ${e}`);for(let[r,o]of this.toolDefinitions)o.name.includes(e)&&this.toolDefinitions.delete(r);await t.disconnect(),this.clients.delete(e),this.serverConfigs.delete(e)}async disconnectAll(){let e=Array.from(this.clients.keys()).map(t=>this.disconnectServer(t));await Promise.allSettled(e)}getToolDefinitions(){return Array.from(this.toolDefinitions.values())}getConnectedServers(){return Array.from(this.clients.keys())}isServerConnected(e){return this.clients.get(e)?.connected??!1}convertMcpTool(e,t,r,o){let n={type:"object",properties:e.inputSchema.properties||{},required:e.inputSchema.required||[]};return{name:`${r}${e.name}`,displayName:e.name,description:e.description||`MCP tool from ${t}`,category:"mcp",parameters:n,execute:async a=>{try{v(`[MCP] Executing ${e.name} on ${t}`);let i=await o.callTool(e.name,a);return JSON.stringify(i)}catch(i){throw Y(`[MCP] Tool execution failed: ${i}`),i}}}}setupClientEvents(e,t){e.on("error",r=>{Y(`[MCP] ${t} error: ${r}`)}),e.on("close",r=>{E(`[MCP] ${t} closed with code ${r}`)}),e.on("reconnecting",({attempt:r,max:o})=>{v(`[MCP] ${t} reconnecting (${r}/${o})`)}),e.on("reconnected",({attempt:r})=>{v(`[MCP] ${t} reconnected after ${r} attempts`)}),e.on("reconnect_failed",r=>{Y(`[MCP] ${t} failed to reconnect after ${r} attempts`)}),e.on("notification",r=>{v(`[MCP] ${t} notification: ${JSON.stringify(r)}`)})}};async function Jr(s){let e=new Fo(s);await e.connectAll();let t=e.getToolDefinitions(),r={manifest:{key:"mcp-tools",name:"mcp-tools",displayName:"MCP Tools",version:"1.0.0",description:`Tools from ${e.getConnectedServers().length} MCP server(s)`,category:"mcp",author:"Toolpack SDK",tools:t.map(o=>o.name)},tools:t};return r._mcpManager=e,r}async function Hr(s){let e=s._mcpManager;e&&await e.disconnectAll()}l();l();l();l();var zr=`
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],s=o.slice(0,o.length-1),{normalizeImagePart:i}=await Promise.resolve().then(()=>(Xe(),io)),a=async m=>typeof m=="string"?[{text:m}]:m===null?[]:(await Promise.all(m.map(async g=>{if(g.type==="text")return{text:g.text};if(g.type==="image_data"||g.type==="image_file"||g.type==="image_url")try{let{data:w,mimeType:y}=await i(g);return{inlineData:{mimeType:y,data:w}}}catch{return g.type==="image_url"?{text:`[Image: ${g.image_url.url}]`}:{text:"[Unresolvable Image]"}}return null}))).filter(Boolean),c=await Promise.all(s.map(async m=>{if(m.role==="tool"&&m.tool_call_id)return{role:"function",parts:[{functionResponse:{name:this.sanitizeToolName(m.name||m.tool_call_id),response:{name:this.sanitizeToolName(m.name||m.tool_call_id),content:typeof m.content=="string"?m.content:JSON.stringify(m.content)}}}]};if(m.role==="assistant"&&m.tool_calls&&m.tool_calls.length>0){let u=[];if(typeof m.content=="string"&&m.content)u.push({text:m.content});else if(Array.isArray(m.content)){let g=m.content.filter(w=>typeof w=="object"&&w.type==="text").map(w=>w.text).join(`
195
+ `);g&&u.push({text:g})}for(let g of m.tool_calls)u.push({functionCall:{name:this.sanitizeToolName(g.function.name),args:typeof g.function.arguments=="string"?JSON.parse(g.function.arguments||"{}"):g.function.arguments}});return{role:"model",parts:u}}return{role:m.role==="user"?"user":"model",parts:await a(m.content)}})),p=typeof r.content=="string"?r.content:await a(r.content);return{history:c,lastUserMessage:p}}handleError(e){return e.status===429?new ge(e.message,void 0,e):e.status>=400&&e.status<500?new M(e.message,e):e.message&&e.message.includes("API key")?new fe(e.message,e):new q(e.message||"Gemini Error","GEMINI_ERROR",e.status||500,e)}};l();var Ce=x(require("fs"),1),$n=x(require("path"),1);le();var Ki="toolpack.config.json",or=new Map;async function Ji(n){for(;or.has(n);)await or.get(n);let e,t=new Promise(o=>{e=o});return or.set(n,t),()=>{or.delete(n),e()}}function Fe(n){if(n&&Ce.existsSync(n))return n;let e=$n.join(process.cwd(),Ki);return Ce.existsSync(e)?e:null}function po(n){if(!n)return null;try{let e=Ce.readFileSync(n,"utf-8");return JSON.parse(e)}catch{return null}}var co=null;function rr(n){if(co)return co;let e=n||Fe();return co=po(e)||{},co}function nr(){co=null}function Hi(n){return(rr(n).ollama?.models||[]).map(o=>({type:`ollama-${o.model.replace(/[:.]/g,"-")}`,model:o.model,label:o.label||o.model}))}function mo(n){return rr(n).ollama?.baseUrl||"http://localhost:11434"}async function zi(n){let{type:e,value:t,configPath:o}=n,r=o||Fe();r||(r=$n.join(process.cwd(),Ki));let s=await Ji(r);try{let i=po(r)||{};switch(i.hitl||(i.hitl={}),i.hitl.bypass||(i.hitl.bypass={}),e){case"tool":i.hitl.bypass.tools||(i.hitl.bypass.tools=[]),i.hitl.bypass.tools.includes(t)||i.hitl.bypass.tools.push(t);break;case"category":i.hitl.bypass.categories||(i.hitl.bypass.categories=[]),i.hitl.bypass.categories.includes(t)||i.hitl.bypass.categories.push(t);break;case"level":{i.hitl.bypass.levels||(i.hitl.bypass.levels=[]);let a=t;i.hitl.bypass.levels.includes(a)||i.hitl.bypass.levels.push(a);break}}try{Ce.writeFileSync(r,JSON.stringify(i,null,4),"utf-8")}catch(a){throw new W(`Failed to write bypass rule to config file: ${a instanceof Error?a.message:String(a)}`,"CONFIG_WRITE_ERROR")}nr()}finally{s()}}async function Qi(n){let{type:e,value:t,configPath:o}=n,r=o||Fe();if(!r)return;let s=await Ji(r);try{let i=po(r);if(!i?.hitl?.bypass)return;switch(e){case"tool":i.hitl.bypass.tools&&(i.hitl.bypass.tools=i.hitl.bypass.tools.filter(a=>a!==t));break;case"category":i.hitl.bypass.categories&&(i.hitl.bypass.categories=i.hitl.bypass.categories.filter(a=>a!==t));break;case"level":i.hitl.bypass.levels&&(i.hitl.bypass.levels=i.hitl.bypass.levels.filter(a=>a!==t));break}try{Ce.writeFileSync(r,JSON.stringify(i,null,4),"utf-8")}catch(a){throw new W(`Failed to remove bypass rule from config file: ${a instanceof Error?a.message:String(a)}`,"CONFIG_WRITE_ERROR")}nr()}finally{s()}}l();l();le();_();l();var _n=x(require("http"),1);function ie(n,e,t,o,r=12e4){return new Promise((s,i)=>{let a=new URL(e,n),c={hostname:a.hostname,port:a.port,path:a.pathname,method:t,headers:{"Content-Type":"application/json"},timeout:r},p=_n.default.request(c,m=>{let u=[];m.on("data",g=>u.push(g)),m.on("end",()=>{s({status:m.statusCode||0,body:Buffer.concat(u).toString("utf-8")})})});p.on("error",m=>i(m)),p.on("timeout",()=>{p.destroy(),i(new Error("Request timed out"))}),o&&p.write(JSON.stringify(o)),p.end()})}function sr(n,e,t,o=12e4,r){let s,i=!1;return r&&r.addEventListener("abort",()=>{i=!0,s&&s.destroy()},{once:!0}),{stream:async function*(){let c=new URL(e,n),p={hostname:c.hostname,port:c.port,path:c.pathname,method:"POST",headers:{"Content-Type":"application/json"},timeout:o},m=await new Promise((g,w)=>{s=_n.default.request(p,g),s.on("error",w),s.on("timeout",()=>{s.destroy(),w(new Error("Stream request timed out"))}),s.write(JSON.stringify(t)),s.end()});if(m.statusCode&&m.statusCode>=400){let g="";for await(let w of m)g+=w.toString();throw new Error(`Ollama HTTP ${m.statusCode}: ${g}`)}let u="";for await(let g of m){if(i)break;let w=g.toString();if(u+=w,u.includes('"error"'))try{let b=JSON.parse(u.trim());if(b.error)throw new Error(`Ollama: ${b.error}`)}catch(b){if(b.message.startsWith("Ollama:"))throw b}let y=u.split(`
196
+ `);u=y.pop()||"";for(let b of y)b.trim()&&(yield b)}u.trim()&&!i&&(yield u.trim())}(),abort:()=>{i=!0,s&&s.destroy()}}}var ve=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 ie(this.baseUrl,"/api/tags","GET",void 0,5e3);if(e.status!==200)throw new q(`Ollama returned status ${e.status}`,"OLLAMA_ERROR",e.status);return JSON.parse(e.body).models||[]}catch(e){throw e instanceof q?e:new Te(`Cannot connect to Ollama at ${this.baseUrl}. Is Ollama running? (ollama serve)`,e)}}async isAvailable(){try{return await ie(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(s=>s.name.split(":")[0].toLowerCase()===r||s.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(i=>this.toOllamaMessage(i,e.mediaOptions))),r=e.model||this.config.model,s={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"&&(s.tools=e.tools.map(i=>({type:"function",function:{name:this.sanitizeToolName(i.function.name),description:i.function.description,parameters:i.function.parameters}})),h(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&h(`[Ollama][${t}] First tool: ${A(e.tools[0],800)}`),h(`[Ollama][${t}] NO TOOLS in request`)),h(`[Ollama][${t}] generate() request: model=${r}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),ee(t,"Ollama",e.messages);try{let i=await ie(this.baseUrl,"/api/chat","POST",s,this.timeout);if(i.status!==200)throw this.handleHttpError(i.status,i.body);let a=JSON.parse(i.body),c=[];if(a.message?.tool_calls)for(let m of a.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:a.message?.content||null,usage:a.prompt_eval_count!=null?{prompt_tokens:a.prompt_eval_count||0,completion_tokens:a.eval_count||0,total_tokens:(a.prompt_eval_count||0)+(a.eval_count||0)}:void 0,finish_reason:c.length>0?"tool_calls":a.done?"stop":void 0,tool_calls:c.length>0?c:void 0,raw:a};return h(`[Ollama][${t}] Response finish_reason=${p.finish_reason} tool_calls=${c.length} content_preview=${A(p.content,200)}`),p}catch(i){throw i instanceof q?i:new Te(`Failed to generate with Ollama model "${r}": ${i.message}`,i)}}async*stream(e){let t=e.__toolpack_request_id||`str-${Date.now()}`,o=await Promise.all(e.messages.map(a=>this.toOllamaMessage(a,e.mediaOptions))),r=e.model||this.config.model,s={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"&&(s.tools=e.tools.map(a=>({type:"function",function:{name:this.sanitizeToolName(a.function.name),description:a.function.description,parameters:a.function.parameters}})),h(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&h(`[Ollama][${t}] First tool: ${A(e.tools[0],800)}`),h(`[Ollama][${t}] NO TOOLS in request`)),h(`[Ollama][${t}] Stream request: model=${r}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),ee(t,"Ollama",e.messages);let{stream:i}=sr(this.baseUrl,"/api/chat",s,this.timeout,e.signal);try{for await(let a of i)try{let c=JSON.parse(a);if(c.message?.content){let p=c.message.tool_calls&&c.message.tool_calls.length>0;yield{delta:c.message.content,finish_reason:c.done&&!p?"stop":void 0,usage:c.done&&c.prompt_eval_count!=null?{prompt_tokens:c.prompt_eval_count||0,completion_tokens:c.eval_count||0,total_tokens:(c.prompt_eval_count||0)+(c.eval_count||0)}:void 0}}if(c.message?.tool_calls&&c.message.tool_calls.length>0){let p=c.message.tool_calls.map(m=>({id:`ollama_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(m.function.name,e.tools),arguments:m.function.arguments||{}}));h(`[Ollama][${t}] Stream finish_reason=tool_calls name=${p[0]?.name}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:p}}if(c.done&&!c.message?.content&&!c.message?.tool_calls){Pe(`[Ollama][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"};return}}catch{}}catch(a){throw new Te(`Stream failed for Ollama model "${r}": ${a.message}`,a)}}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;h(`[Ollama][${t}] Embedding request: model=${r}, inputs=${o.length}`);try{let s=await ie(this.baseUrl,"/api/embed","POST",{model:r,input:o},this.timeout);if(s.status!==200)throw this.handleHttpError(s.status,s.body);return{embeddings:JSON.parse(s.body).embeddings||[]}}catch(s){throw s instanceof q?s:new Te(`Embedding failed for Ollama model "${r}": ${s.message}`,s)}}async disconnect(){}async toOllamaMessage(e,t={}){let o="",r=[],{normalizeImagePart:s}=await Promise.resolve().then(()=>(Xe(),io));if(typeof e.content=="string")o=e.content;else if(e.content!==null){for(let a of e.content)if(a.type==="text")o+=a.text+`
198
+ `;else if(a.type==="image_url"||a.type==="image_data"||a.type==="image_file")try{let{data:c}=await s(a);r.push(c)}catch{a.type==="image_url"?o+=`[Image: ${a.image_url.url}]
199
+ `:o+=`[Unresolvable Image]
200
+ `}o=o.trim()}let i={role:e.role,content:o};return r.length>0&&(i.images=r),e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0?i.tool_calls=e.tool_calls.map(a=>({function:{name:this.sanitizeToolName(a.function.name),arguments:typeof a.function.arguments=="string"?JSON.parse(a.function.arguments||"{}"):a.function.arguments}})):e.role==="tool"&&(i.content=o||JSON.stringify(e.content),e.name&&(i.tool_name=this.sanitizeToolName(e.name))),i}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 q(o,"OLLAMA_ERROR",e)}};l();var Ze=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 ie(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,...s}=e,i=s,a={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 i.messages=[...i.messages,a],i}return e}getAdapterForModel(e){let t=this.adapterCache.get(e);return t||(t=new ve({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 a=await ie(this.baseUrl,"/api/show","POST",{model:e.name},3e3);if(a.status===200){let p=(JSON.parse(a.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 s=e.name.toLowerCase();o||(o=["llava","vision","bakllava","moondream"].some(c=>s.includes(c))),r||(r=["nomic-embed","mxbai-embed","all-minilm","bge-","snowflake-arctic-embed"].some(c=>s.includes(c)));let i={toolCalling:t,vision:o,embeddings:r};return this.capabilityCache.set(e.name,i),{id:e.name,displayName:e.name,capabilities:{chat:!0,streaming:!0,toolCalling:t,embeddings:r,vision:o}}}async probeToolSupport(e){try{let t=await ie(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 Rn=[{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 Yi(){return Rn[0].model}function Vi(n){let e=n.toLowerCase();return Rn.some(t=>t.model.toLowerCase()===e||t.model.split(":")[0].toLowerCase()===e.split(":")[0].toLowerCase())}function Xi(){return[...Rn]}l();var Dn=x(require("openai"),1);le();_();var uo=class extends Y{client;constructor(e,t){super(),this.client=new Dn.default({apiKey:e,baseURL:t,timeout:6e4,maxRetries:2})}supportsFileUpload(){return!0}async uploadFile(e){try{let t=await import("fs");if(!e.filePath)throw new 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(u=>this.toOpenAIMessage(u,e.mediaOptions))),model:e.model,temperature:e.temperature,max_tokens:e.max_tokens,top_p:e.top_p,response_format:e.response_format==="json_object"?{type:"json_object"}:void 0,stream:!1},s=new Map;e.tools&&e.tools.length>0&&(r.tools=e.tools.map(u=>{let g=this.sanitizeToolName(u.function.name);return s.set(g,u.function.name),{type:"function",function:{name:g,description:u.function.description,parameters:u.function.parameters}}}),r.tool_choice=e.tool_choice||"auto",h(`[OpenAI][${t}] Sending ${r.tools.length} tools with tool_choice: ${r.tool_choice}`),h(`[OpenAI][${t}] First tool: ${A(r.tools[0],800)}`)),h(`[OpenAI][${t}] Request params: ${A({model:r.model,messages_count:r.messages.length,has_tools:!!r.tools,tools_count:r.tools?.length,tool_choice:r.tool_choice},800)}`),ee(t,"OpenAI",r.messages);let i=await this.client.chat.completions.create(r,e.signal?{signal:e.signal}:void 0);Pe(`[OpenAI][${t}] Raw completion: ${JSON.stringify(i)}`);let a=i.choices[0].message;h(`[OpenAI][${t}] Response: finish_reason=${i.choices[0].finish_reason}`),h(`[OpenAI][${t}] Response has tool_calls: ${!!a.tool_calls}, count: ${a.tool_calls?.length||0}`),h(`[OpenAI][${t}] Response content: ${JSON.stringify(a.content)}`),a.content&&h(`[OpenAI][${t}] Response content preview: ${A(a.content,200)}`);let c=i.choices[0],p,m=c.message.tool_calls;return m&&m.length>0&&(p=m.map(u=>({id:u.id,name:s.get(u.function.name)||u.function.name,arguments:JSON.parse(u.function.arguments)}))),{content:c.message.content,usage:i.usage?{prompt_tokens:i.usage.prompt_tokens,completion_tokens:i.usage.completion_tokens,total_tokens:i.usage.total_tokens}:void 0,finish_reason:c.finish_reason,tool_calls:p,raw:i}}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},s=new Map;e.tools&&e.tools.length>0?(r.tools=e.tools.map(c=>{let p=this.sanitizeToolName(c.function.name);return s.set(p,c.function.name),{type:"function",function:{name:p,description:c.function.description,parameters:c.function.parameters}}}),r.tool_choice=e.tool_choice||"auto",h(`[OpenAI][${t}] Sending ${r.tools.length} tools with tool_choice: ${r.tool_choice}`),h(`[OpenAI][${t}] First tool: ${A(r.tools[0],800)}`)):h(`[OpenAI][${t}] NO TOOLS in request`),h(`[OpenAI][${t}] Stream request: model=${r.model}, messages=${r.messages.length}, tools=${r.tools?.length||0}, tool_choice=${r.tool_choice??"unset"}`),ee(t,"OpenAI",r.messages);let i=await this.client.chat.completions.create(r,e.signal?{signal:e.signal}:void 0),a=new Map;for await(let c of i){let p=c.choices[0];if(p.finish_reason&&Pe(`[OpenAI][${t}] Stream chunk finish_reason=${p.finish_reason}`),p.delta.tool_calls)for(let m of p.delta.tool_calls){let u=m.index;a.has(u)||a.set(u,{id:m.id||"",name:m.function?.name||"",args:""});let g=a.get(u);m.id&&(g.id=m.id),m.function?.name&&(g.name=m.function.name),m.function?.arguments&&(g.args+=m.function.arguments),Pe(`[OpenAI][${t}] tool_call_delta idx=${u} id=${m.id||g.id||""} name=${m.function?.name||g.name||""} args_delta=${A(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"&&a.size>0){let m=Array.from(a.values()).map(u=>({id:u.id,name:s.get(u.name)||u.name,arguments:JSON.parse(u.args||"{}")}));h(`[OpenAI][${t}] Stream finish_reason=tool_calls accumulated_calls=${m.length} names=${m.map(u=>u.name).join(", ")}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:m}}}}catch(t){throw this.handleError(t)}}async embed(e){try{let t=typeof e.input=="string"?[e.input]:e.input,o=await this.client.embeddings.create({model:e.model,input:t});return{embeddings:o.data.map(r=>r.embedding),usage:o.usage}}catch(t){throw this.handleError(t)}}async toOpenAIMessage(e,t={}){if(e.role==="tool"&&e.tool_call_id)return{role:"tool",tool_call_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content??"")};if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0)return{role:"assistant",content:typeof e.content=="string"?e.content:"",tool_calls:e.tool_calls.map(s=>({id:s.id,type:"function",function:{name:this.sanitizeToolName(s.function.name),arguments:s.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(()=>(Xe(),io)),r=await Promise.all(e.content.map(async s=>{if(s.type==="text")return{type:"text",text:s.text};if(s.type==="image_url")return{type:"image_url",image_url:{url:s.image_url.url}};if(s.type==="image_data"||s.type==="image_file"){let{data:i,mimeType:a}=await o(s);return{type:"image_url",image_url:{url:`data:${a};base64,${i}`}}}return null}));return{role:e.role,content:r.filter(Boolean)}}handleError(e){if(e instanceof Dn.default.APIError){let t=e.message;return e.status===401?new fe(t,e):e.status===429?new ge(t,void 0,e):e.status&&e.status>=400&&e.status<500?new M(t,e):new q(t,e.code||"OPENAI_ERROR",e.status||500,e)}return new q("Unknown error","UNKNOWN",500,e)}};Xe();l();ro();l();ro();var Yt=class{tools=new Map;projects=new Map;config=H;register(e){this.tools.set(e.name,e)}registerCustom(e){this.tools.set(e.name,e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getNames(){return Array.from(this.tools.keys())}getByCategory(e){return Array.from(this.tools.values()).filter(t=>t.category===e)}getEnabled(){if(this.config.enabledTools.length===0&&this.config.enabledToolCategories.length===0)return Array.from(this.tools.values());let e=this.getByNames(this.config.enabledTools),t=this.getByCategories(this.config.enabledToolCategories),o=new Set,r=[];for(let s of[...e,...t])o.has(s.name)||(o.add(s.name),r.push(s));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(()=>(Vn(),dc)),{execToolsProject:t}=await Promise.resolve().then(()=>(ss(),tp)),{systemToolsProject:o}=await Promise.resolve().then(()=>(fs(),Mp)),{httpToolsProject:r}=await Promise.resolve().then(()=>(Ts(),hm)),{webToolsProject:s}=await Promise.resolve().then(()=>(Os(),Ld)),{codingToolsProject:i}=await Promise.resolve().then(()=>(Zs(),$f)),{gitToolsProject:a}=await Promise.resolve().then(()=>(ti(),og)),{diffToolsProject:c}=await Promise.resolve().then(()=>(ni(),hg)),{dbToolsProject:p}=await Promise.resolve().then(()=>(li(),Gg)),{cloudToolsProject:m}=await Promise.resolve().then(()=>(pi(),eh));await this.loadProjects([e,t,o,r,s,i,a,c,p,m])}};vs();l();_();function th(n){if(!n.key||!/^[a-z0-9-]+$/.test(n.key))throw new Error(`Invalid tool project key: "${n.key}". Must be non-empty, lowercase, and contain no spaces (use hyphens).`);if(!n.name.trim())throw new Error("Tool project name cannot be empty.");if(!n.tools||n.tools.length===0)throw new Error("Tool project must contain at least one tool.");for(let t of n.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!==n.category&&E(`[Toolpack] Tool "${t.name}" has category "${t.category}" which does not match project category "${n.category}".`)}let e=n.tools.map(t=>t.name);return{manifest:{key:n.key,name:n.name,displayName:n.displayName,version:n.version,description:n.description,author:n.author,repository:n.repository,category:n.category,tools:e},dependencies:n.dependencies,tools:n.tools}}Vn();ss();fs();Ts();Os();Zs();ti();ni();li();pi();l();l();var oh=require("child_process");_();function N(n,e){if(n.includes("\0")||n.includes(`
201
+ `)||n.includes("\r"))throw new Error(`Invalid ${e}: contains disallowed characters.`);return n}function nw(n){let e=typeof n.stdout=="string"?n.stdout:"",t=typeof n.stderr=="string"?n.stderr:"",o=n.status??"unknown",r=t.split(/\r?\n/).filter(i=>i.trim().length>0),s=r.find(i=>i.toLowerCase().startsWith("error:"))||r[0]||n.message||"";return`kubectl failed (exit code ${o})${s?`: ${s.trim()}`:""}
202
+ STDOUT:
203
+ ${e}
204
+ STDERR:
205
+ ${t}`}function X(n,e,t=3e4){n.forEach((o,r)=>N(o,`kubectl argument #${r}`)),h(`[k8s-tools] execute: kubectl ${n.join(" ")}`);try{return(0,oh.execFileSync)("kubectl",n,{input:e,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],timeout:t})||"(kubectl completed with no output)"}catch(o){return nw(o)}}function sw(n){if(!n)return 3e5;let e=n.trim().toLowerCase(),t=/^([0-9]+)(s|m|h)?$/.exec(e);if(!t)return 3e5;let o=Number(t[1]);switch(t[2]){case"h":return o*60*60*1e3;case"m":return o*60*1e3;default:return o*1e3}}var ae="kubernetes";function rh(n){if(!n)return;if(typeof n=="string")return n;let e=Object.entries(n).filter(([,t])=>t!==void 0&&t!=="");if(e.length)return e.map(([t,o])=>`${N(t,"label key")}=${N(o,"label value")}`).join(",")}var Xr={name:"k8s.list_pods",displayName:"Kubernetes List Pods",description:"List pods in the current or a specific Kubernetes namespace.",category:ae,parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to query. If omitted, uses the current namespace."},labels:{type:"string",description:"Label selector to filter pods."},labelSelector:{type:"object",description:"Map of label key/value pairs to filter pods.",additionalProperties:{type:"string"}},output:{type:"string",description:"Output format for the pod list.",enum:["wide","name","json","yaml"],default:"wide"},allNamespaces:{type:"boolean",description:"If true, list pods across all namespaces.",default:!1}},required:[]},execute:async n=>{let e=["get","pods"],t=n.output;t?e.push("-o",t):e.push("-o","wide"),n.allNamespaces&&e.push("--all-namespaces"),n.namespace&&!n.allNamespaces&&e.push("-n",N(n.namespace,"namespace"));let o=rh(n.labelSelector)??n.labels;return o&&e.push("-l",N(o,"labels")),X(e)}},Zr={name:"k8s.describe",displayName:"Kubernetes Describe Resource",description:"Describe a Kubernetes resource or resource instance.",category:ae,parameters:{type:"object",properties:{resource:{type:"string",description:"Resource type to describe, such as pod, service, deployment."},name:{type:"string",description:"Resource name. Optional for cluster-wide descriptions."},namespace:{type:"string",description:"Namespace containing the resource."}},required:["resource"]},execute:async n=>{let t=["describe",N(n.resource,"resource")];return n.name&&t.push(N(n.name,"name")),n.namespace&&t.push("-n",N(n.namespace,"namespace")),X(t)}},en={name:"k8s.get_logs",displayName:"Kubernetes Get Pod Logs",description:"Fetch logs from a Kubernetes pod, optionally from a specific container.",category:ae,parameters:{type:"object",properties:{podName:{type:"string",description:"The name of the pod to fetch logs from."},namespace:{type:"string",description:"Namespace of the pod."},container:{type:"string",description:"Container name inside the pod."},tailLines:{type:"number",description:"Number of log lines to show from the end.",default:100},since:{type:"string",description:"Return logs newer than a relative duration like 5m or 1h."}},required:["podName"]},execute:async n=>{let e=["logs",N(n.podName,"podName")];return n.container&&e.push("-c",N(n.container,"container")),n.namespace&&e.push("-n",N(n.namespace,"namespace")),typeof n.tailLines=="number"&&e.push("--tail",`${n.tailLines}`),n.since&&e.push("--since",N(n.since,"since")),X(e)}},tn={name:"k8s.apply_manifest",displayName:"Kubernetes Apply Manifest",description:"Apply a Kubernetes manifest from a file path or inline YAML content.",category:ae,parameters:{type:"object",properties:{path:{type:"string",description:"Path to the manifest file to apply."},manifest:{type:"string",description:"Inline YAML manifest to apply if no path is provided."},namespace:{type:"string",description:"Namespace to apply the manifest into, if supported by the manifest."},dryRun:{type:"boolean",description:"If true, perform a client-side dry run without applying changes.",default:!1}},required:[]},confirmation:{level:"high",reason:"This will change cluster state by applying a Kubernetes manifest.",showArgs:["path","namespace"]},execute:async n=>{let e=n.path,t=n.manifest,o=["apply"];if(n.dryRun&&o.push("--dry-run=client"),o.push("-f"),e)return o.push(N(e,"path")),n.namespace&&o.push("-n",N(n.namespace,"namespace")),X(o);if(!t)throw new Error("Either path or manifest is required to apply a Kubernetes manifest.");return n.namespace&&o.push("-n",N(n.namespace,"namespace")),o.push("-"),X(o,t)}},on={name:"k8s.delete_resource",displayName:"Kubernetes Delete Resource",description:"Delete a Kubernetes resource by type and name, or delete resources from a manifest file.",category:ae,parameters:{type:"object",properties:{resource:{type:"string",description:"Resource type to delete, such as pod, service, deployment."},name:{type:"string",description:"Name of the resource to delete."},namespace:{type:"string",description:"Namespace containing the resource."},path:{type:"string",description:"Path to a manifest file that contains the resources to delete."},force:{type:"boolean",description:"Force deletion of the resource.",default:!1},dryRun:{type:"boolean",description:"If true, perform a client-side dry run without deleting resources.",default:!1}},required:[]},confirmation:{level:"high",reason:"This will delete resources from the Kubernetes cluster.",showArgs:["resource","name","path"]},execute:async n=>{let e=n.path,t=n.resource,o=n.name;if(e){let s=["delete"];return n.dryRun&&s.push("--dry-run=client"),s.push("-f",N(e,"path")),n.namespace&&s.push("-n",N(n.namespace,"namespace")),X(s)}if(!t||!o)throw new Error("resource and name are required unless a manifest path is provided.");let r=["delete",N(t,"resource"),N(o,"name")];return n.namespace&&r.push("-n",N(n.namespace,"namespace")),n.force&&r.push("--force","--grace-period=0"),n.dryRun&&r.push("--dry-run=client"),X(r)}},rn={name:"k8s.list_services",displayName:"Kubernetes List Services",description:"List services in the current or a specific Kubernetes namespace.",category:ae,parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to query. If omitted, uses the current namespace."},output:{type:"string",description:"Output format for the service list.",enum:["wide","name","json","yaml"],default:"wide"},allNamespaces:{type:"boolean",description:"List services across all namespaces.",default:!1}},required:[]},execute:async n=>{let e=["get","services"],t=n.output;return e.push("-o",t||"wide"),n.allNamespaces&&e.push("--all-namespaces"),n.namespace&&!n.allNamespaces&&e.push("-n",N(n.namespace,"namespace")),X(e)}},nn={name:"k8s.list_deployments",displayName:"Kubernetes List Deployments",description:"List deployments in the current or a specific Kubernetes namespace.",category:ae,parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to query. If omitted, uses the current namespace."},labels:{type:"string",description:"Label selector to filter deployments."},labelSelector:{type:"object",description:"Map of label key/value pairs to filter deployments.",additionalProperties:{type:"string"}},output:{type:"string",description:"Output format for the deployment list.",enum:["wide","name","json","yaml"],default:"wide"},allNamespaces:{type:"boolean",description:"List deployments across all namespaces.",default:!1}},required:[]},execute:async n=>{let e=["get","deployments"],t=n.output;e.push("-o",t||"wide"),n.allNamespaces&&e.push("--all-namespaces"),n.namespace&&!n.allNamespaces&&e.push("-n",N(n.namespace,"namespace"));let o=rh(n.labelSelector)??n.labels;return o&&e.push("-l",N(o,"labels")),X(e)}},sn={name:"k8s.get_config_map",displayName:"Kubernetes Get ConfigMap",description:"Retrieve a ConfigMap from a Kubernetes namespace.",category:ae,parameters:{type:"object",properties:{name:{type:"string",description:"ConfigMap name."},namespace:{type:"string",description:"Namespace containing the ConfigMap."},output:{type:"string",description:"Output format, such as yaml or json.",enum:["yaml","json"],default:"yaml"}},required:["name"]},execute:async n=>{let e=["get","configmap",N(n.name,"name"),"-o",n.output||"yaml"];return n.namespace&&e.push("-n",N(n.namespace,"namespace")),X(e)}},an={name:"k8s.switch_context",displayName:"Kubernetes Switch Context",description:"Switch the active kubectl context to a different Kubernetes cluster or namespace configuration.",category:ae,parameters:{type:"object",properties:{context:{type:"string",description:"The kubeconfig context to switch to."}},required:["context"]},execute:async n=>X(["config","use-context",N(n.context,"context")])},ln={name:"k8s.get_namespaces",displayName:"Kubernetes Get Namespaces",description:"List namespaces in the current Kubernetes context.",category:ae,parameters:{type:"object",properties:{output:{type:"string",description:"Output format for the namespace list.",enum:["wide","name","json","yaml"],default:"wide"}},required:[]},execute:async n=>X(["get","namespaces","-o",n.output||"wide"])},cn={name:"k8s.wait_for_deployment",displayName:"Kubernetes Wait For Deployment",description:"Wait for a Kubernetes deployment to complete its rollout.",category:ae,parameters:{type:"object",properties:{name:{type:"string",description:"Deployment name to wait for."},namespace:{type:"string",description:"Namespace containing the deployment."},timeout:{type:"string",description:"Timeout duration, e.g. 300s or 5m.",default:"300s"}},required:["name"]},execute:async n=>{let e=n.timeout,t=["rollout","status",`deployment/${N(n.name,"name")}`,"--timeout",e||"300s"];return n.namespace&&t.push("-n",N(n.namespace,"namespace")),X(t,void 0,sw(e))}};var nh={manifest:{key:"k8s",name:"k8s-tools",displayName:"Kubernetes",version:"1.0.0",description:"Kubernetes command and cluster inspection tools for working with kubectl and manifests.",author:"toolpack-sdk",tools:["k8s.list_pods","k8s.describe","k8s.get_logs","k8s.apply_manifest","k8s.delete_resource","k8s.list_services","k8s.list_deployments","k8s.get_config_map","k8s.switch_context","k8s.get_namespaces","k8s.wait_for_deployment"],category:"kubernetes"},tools:[Xr,Zr,en,tn,on,rn,nn,sn,an,ln,cn]};l();l();var sh=require("child_process"),ih=require("events");_();var Wo=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},Vt=class extends ih.EventEmitter{constructor(t){super();this.config=t;this.defaultTimeoutMs=t.requestTimeoutMs??3e4,this.autoReconnect=t.autoReconnect??!1,this.maxReconnectAttempts=t.maxReconnectAttempts??3,this.reconnectDelayMs=t.reconnectDelayMs??1e3}config;process=null;messageQueue=new Map;nextId=1;buffer="";_connected=!1;_shuttingDown=!1;_reconnectAttempts=0;defaultTimeoutMs;autoReconnect;maxReconnectAttempts;reconnectDelayMs;get connected(){return this._connected&&this.process!==null}async initializeServer(){await this.request("initialize",{client:"toolpack-sdk"})}async connect(){if(this._shuttingDown)throw new me("Client is shutting down");if(this.buffer="",this.process=(0,sh.spawn)(this.config.command,this.config.args||[],{env:{...process.env,...this.config.env},stdio:["pipe","pipe","pipe"]}),!this.process.stdout||!this.process.stdin)throw new me("Failed to spawn MCP server: stdout/stdin unavailable");this.process.stdout.on("data",t=>{this.handleData(t)}),this.process.stderr&&this.process.stderr.on("data",t=>{E(`[MCP server stderr] ${t.toString().trim()}`)}),this.process.on("error",t=>{this._connected=!1,this.emit("error",t)}),this.process.on("exit",t=>{let o=this._connected;this._connected=!1,this.process=null,this.rejectAllPending(new me(`MCP server exited with code ${t}`,t)),this.emit("close",t),o&&!this._shuttingDown&&this.autoReconnect&&this.attemptReconnect()}),this._reconnectAttempts=0,await this.initializeServer(),this._connected=!0}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(`
206
+ `))!==-1;){let r=this.buffer.slice(0,o).trim();if(this.buffer=this.buffer.slice(o+1),r)try{let s=JSON.parse(r);this.handleMessage(s)}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 s=this.nextId++,i=r??this.defaultTimeoutMs,a={jsonrpc:"2.0",id:s,method:t,params:o};return new Promise((c,p)=>{let m;i>0&&(m=setTimeout(()=>{let u=this.messageQueue.get(s);u&&(this.messageQueue.delete(s),u.reject(new Wo(t,i)))},i)),this.messageQueue.set(s,{resolve:c,reject:p,timer:m});try{this.process.stdin.write(JSON.stringify(a)+`
207
+ `)}catch(u){m&&clearTimeout(m),this.messageQueue.delete(s),p(u)}})}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 s=!1,i=()=>{s||(s=!0,this.process=null,this._connected=!1,this._shuttingDown=!1,r())};o.once("exit",i),o.kill("SIGTERM"),setTimeout(()=>{if(!s){try{o.kill("SIGKILL")}catch{}i()}},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 Go=class{constructor(e){this.config=e}config;clients=new Map;serverConfigs=new Map;toolDefinitions=new Map;toolOwners=new Map;async connectServer(e){let{name:t,displayName:o,toolPrefix:r,...s}=e;v(`[MCP] Connecting to server: ${o||t}`);try{let i=new Vt({...s,requestTimeoutMs:s.requestTimeoutMs??this.config.defaultTimeoutMs,autoReconnect:s.autoReconnect??this.config.autoReconnect??!0});this.setupClientEvents(i,t),await i.connect(),this.clients.set(t,i),this.serverConfigs.set(t,e),await this.discoverServerTools(t,i,e)}catch(i){throw Q(`[MCP] Failed to connect to ${t}: ${i}`),i}}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[o,r]of this.toolOwners)r===e&&(this.toolDefinitions.delete(o),this.toolOwners.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 s={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:s,execute:async i=>{try{v(`[MCP] Executing ${e.name} on ${t}`);let a=await r.callTool(e.name,i);return JSON.stringify(a)}catch(a){throw Q(`[MCP] Tool execution failed: ${a}`),a}}}}setupClientEvents(e,t){e.on("error",o=>{Q(`[MCP] ${t} error: ${o}`)}),e.on("close",o=>{E(`[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`),this.refreshServerTools(t).catch(r=>{Q(`[MCP] ${t} tool refresh failed after reconnect: ${r}`)})}),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)}`)})}removeServerToolDefinitions(e){for(let[t,o]of this.toolOwners)o===e&&(this.toolDefinitions.delete(t),this.toolOwners.delete(t))}async discoverServerTools(e,t,o){let s=(await t.request("tools/list"))?.tools||[];v(`[MCP] Discovered ${s.length} tools from ${e}`),this.removeServerToolDefinitions(e);let i=o.toolPrefix||`mcp.${e}.`;for(let a of s){let c=this.convertMcpTool(a,e,i,t);this.toolDefinitions.set(c.name,c),this.toolOwners.set(c.name,e)}}async refreshServerTools(e){let t=this.clients.get(e),o=this.serverConfigs.get(e);!t||!o||await this.discoverServerTools(e,t,o)}};async function pn(n){let e=new Go(n);await e.connectAll();let t=e.getToolDefinitions();return{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,mcpManager:e}}async function mn(n){"mcpManager"in n&&await n.mcpManager.disconnectAll()}l();l();l();l();var dn=`
203
208
  You are a planning assistant. Given a user request, create a detailed step-by-step plan.
204
209
 
205
210
  Rules:
@@ -225,7 +230,7 @@ Rules:
225
230
  }
226
231
  ]
227
232
  }
228
- `,Kr=`
233
+ `,un=`
229
234
  You are executing step {stepNumber} of a plan.
230
235
 
231
236
  Plan summary: {planSummary}
@@ -244,7 +249,7 @@ IMPORTANT: Your response should be written as if you are directly answering the
244
249
  Do NOT mention steps, plans, workflow details, or internal process in your response.
245
250
  Do NOT say things like "Step 1 is complete" or "proceeding to the next step".
246
251
  Just provide the actual answer or result naturally.
247
- `,jy={name:"Direct",planning:{enabled:!1},steps:{enabled:!1},progress:{enabled:!0}},zs={name:"Agent",planning:{enabled:!0,planningPrompt:zr},steps:{enabled:!0,retryOnFailure:!0,allowDynamicSteps:!1,stepPrompt:Kr},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},Fg=`
252
+ `,iw={name:"Direct",planning:{enabled:!1},steps:{enabled:!1},progress:{enabled:!0}},mi={name:"Agent",planning:{enabled:!0,planningPrompt:dn},steps:{enabled:!0,retryOnFailure:!0,allowDynamicSteps:!1,stepPrompt:un},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},ah=`
248
253
  Create a step-by-step plan for this coding task.
249
254
 
250
255
  Rules:
@@ -267,7 +272,7 @@ JSON Schema:
267
272
  }
268
273
  ]
269
274
  }
270
- `,Lg=`
275
+ `,lh=`
271
276
  Execute step {stepNumber}: {stepDescription}
272
277
 
273
278
  Plan: {planSummary}
@@ -276,12 +281,12 @@ Previous: {previousStepsResults}
276
281
 
277
282
  Use tools. Be concise. Show code changes clearly.
278
283
  No meta-commentary about steps or workflow.
279
- `,Ks={name:"Coding",planning:{enabled:!0,planningPrompt:Fg},steps:{enabled:!0,retryOnFailure:!0,allowDynamicSteps:!1,stepPrompt:Lg},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},Qs={name:"Chat",planning:{enabled:!1},steps:{enabled:!1},progress:{enabled:!1}};var Ys={name:"agent",displayName:"Agent",description:"Full autonomous access \u2014 read, write, execute, browse",systemPrompt:["You are an autonomous AI agent with full access to all available tools.","You must use the tools provided to accomplish tasks end-to-end proactively.","If you require a capability that is not listed in your current tools, ALWAYS use `tool.search` to find it before improvising or giving up.","Before considering a tool to call, make sure that is the right tool for the job as per the users prompt.","Verify your actions and check for success or failure states.","Explain your actions briefly as you go."].join(" "),allowedToolCategories:[],blockedToolCategories:[],allowedTools:[],blockedTools:[],blockAllTools:!1,baseContext:{includeWorkingDirectory:!0,includeToolCategories:!0},workflow:zs,toolSearch:{alwaysLoadedTools:["fs.read_file","fs.write_file","fs.list_dir","web.search","web.fetch","skill.search","skill.read"]}},Vs={name:"chat",displayName:"Chat",description:"Conversational assistant with web access",systemPrompt:["You are a conversational AI assistant with web access.","You can search the web, fetch online content, and make HTTP requests.","You do NOT have access to the local filesystem, command execution, or code modification.","Answer questions using your knowledge and web tools when helpful.","If the user asks for local file operations or code changes,","explain that you are in Chat mode and suggest they switch to Agent mode."].join(" "),allowedToolCategories:["network"],blockedToolCategories:["filesystem","execution","system","coding","git","database"],allowedTools:[],blockedTools:[],blockAllTools:!1,baseContext:{includeWorkingDirectory:!1,includeToolCategories:!0},workflow:Qs,toolSearch:{alwaysLoadedTools:["web.search","web.fetch","fs.read_file","fs.list_dir"]}},Fy={name:"coding",displayName:"Coding",description:"Concise coding mode \u2014 minimal text, focused on file operations and code changes",systemPrompt:["Coding assistant. Use tools to modify code.","Be concise. No conversational filler.","Show code changes clearly."].join(" "),allowedToolCategories:[],blockedToolCategories:[],allowedTools:[],blockedTools:[],blockAllTools:!1,baseContext:{includeWorkingDirectory:!0,includeToolCategories:!0},workflow:Ks,toolSearch:{alwaysLoadedTools:["coding.read_code","coding.search_code","fs.read_file","fs.write_file","fs.list_dir","skill.search","skill.read","web.search","web.fetch"]}},Lo=[Ys,Fy,Vs],Le="chat";var zt=class{modes=new Map;orderedNames=[];constructor(){for(let e of Lo)this.register(e)}register(e){if(!e.name||typeof e.name!="string")throw new Error("ModeConfig.name is required and must be a non-empty string");if(!e.displayName||typeof e.displayName!="string")throw new Error("ModeConfig.displayName is required and must be a non-empty string");if(typeof e.systemPrompt!="string")throw new Error("ModeConfig.systemPrompt must be a string (can be empty for passthrough)");if(e.blockAllTools!==void 0&&typeof e.blockAllTools!="boolean")throw new Error("ModeConfig.blockAllTools must be a boolean");let t=["allowedToolCategories","blockedToolCategories","allowedTools","blockedTools"];for(let o of t)if(e[o]!==void 0&&!Array.isArray(e[o]))throw new Error(`ModeConfig.${o} must be an array`);let r=this.modes.has(e.name);this.modes.set(e.name,e),r||this.orderedNames.push(e.name)}get(e){return this.modes.get(e)}has(e){return this.modes.has(e)}getAll(){let e=[];for(let t of this.orderedNames){let r=this.modes.get(t);r&&e.push(r)}return e}getNames(){return[...this.orderedNames]}getDefault(){let e=this.modes.get(Le);if(!e)throw new Error(`Default mode "${Le}" not found in registry`);return e}getNext(e){let t=this.orderedNames.indexOf(e),r=t===-1?0:(t+1)%this.orderedNames.length,o=this.orderedNames[r],n=this.modes.get(o);if(!n)throw new Error(`Mode "${o}" not found in registry`);return n}get size(){return this.modes.size}remove(e){if(Lo.some(o=>o.name===e))return!1;let r=this.modes.delete(e);return r&&(this.orderedNames=this.orderedNames.filter(o=>o!==e)),r}};l();function qg(s){return{name:s.name,displayName:s.displayName,description:s.description||s.displayName,systemPrompt:s.systemPrompt,allowedToolCategories:s.allowedToolCategories||[],blockedToolCategories:s.blockedToolCategories||[],allowedTools:s.allowedTools||[],blockedTools:s.blockedTools||[],blockAllTools:s.blockAllTools||!1,baseContext:s.baseContext,workflow:s.workflow}}l();var Qr={planning:{enabled:!1},steps:{enabled:!1},progress:{enabled:!0}};l();k();var Ly=zr,Kt=class{client;config;constructor(e,t){this.client=e,this.config=t}async createPlan(e,t){let r=this.config?.planningPrompt||Ly,o=e.messages.filter(p=>p.role==="user").map(p=>typeof p.content=="string"?p.content:"[obj]").join(" ").substring(0,100);h(`[Planner] createPlan() provider=${t??"default"} maxSteps=${this.config?.maxSteps??20} request="${o}..."`);let n=e.messages.filter(p=>p.role==="system"),a=e.messages.filter(p=>p.role!=="system"),i=[{role:"system",content:r},...n,...a],c={...e,tools:void 0,tool_choice:"none",response_format:"json_object",messages:i};try{let p=await this.client.generate(c,t),m=this.parsePlan(p.content||"",e,p);return v(`[Planner] createPlan() succeeded plan.id=${m.id} steps=${m.steps.length}`),m}catch(p){return E(`[Planner] createPlan() failed, using fallback: ${p.message}`),this.createFallbackPlan(e)}}parsePlan(e,t,r){try{let o=JSON.parse(e);if(!o.summary||!Array.isArray(o.steps))throw new Error("Invalid plan structure: missing summary or steps array");let n=this.config?.maxSteps??20,a=o.steps.slice(0,n);o.steps.length>n&&E(`[Planner] parsePlan() truncated ${o.steps.length} steps to maxSteps=${n}`),h(`[Planner] parsePlan() parsed ${a.length} steps successfully`);let i=a.map((p,m)=>({id:`step-${Date.now()}-${m}`,number:p.number||m+1,description:p.description||"Unknown step",expectedTools:p.expectedTools||[],dependsOn:p.dependsOn||[],status:"pending"})),c=t.messages.filter(p=>p.role==="user").map(p=>typeof p.content=="string"?p.content:"[Complex Object]").join("\\n");return{id:`plan-${Date.now()}`,request:c,summary:o.summary,steps:i,status:"draft",createdAt:new Date,planningResponse:r}}catch(o){return E(`[Planner] parsePlan() failed: ${o.message} \u2014 using fallback`),this.createFallbackPlan(t)}}createFallbackPlan(e){E("[Planner] createFallbackPlan() \u2014 creating single-step fallback due to plan generation failure");let t=e.messages.filter(r=>r.role==="user").map(r=>typeof r.content=="string"?r.content:"[Complex Object]").join("\\n");return{id:`plan-${Date.now()}-fallback`,request:t,summary:"Fallback single-step plan due to generation failure",steps:[{id:"step-1",number:1,description:"Execute the user request",status:"pending",expectedTools:[],dependsOn:[]}],status:"draft",createdAt:new Date}}};l();l();var Qt=class{static getProgress(e){let t=e.steps.length,r=e.steps.findIndex(c=>c.status!=="completed"&&c.status!=="skipped");r===-1&&(r=t);let o=t>0?Math.round(r/t*100):0,n=e.steps[r],a=n?n.description:"Done",i="executing";return e.status==="draft"&&(i="planning"),e.status==="approved"&&(i="executing"),e.status==="completed"&&(i="completed"),(e.status==="failed"||e.status==="cancelled")&&(i="failed"),{planId:e.id,currentStep:Math.min(r+1,t),totalSteps:t,percentage:o,currentStepDescription:a,status:i}}static summarizeCompletedSteps(e,t){let r=[];for(let o of e.steps){if(o.id===t)break;if(o.status==="completed"&&o.result){let n=o.result.toolsUsed?.length?` (Tools: ${o.result.toolsUsed.join(", ")})`:"",a=o.result.output||"No output";a.length>500&&(a=a.substring(0,500)+"... [truncated]"),r.push(`Step ${o.number}: ${o.description}${n}
280
- Result: ${a}`)}else o.status==="failed"?r.push(`Step ${o.number}: ${o.description}
281
- Failed: ${o.result?.error||"Unknown error"}`):o.status==="skipped"&&r.push(`Step ${o.number}: ${o.description}
282
- Skipped.`)}return r.length===0?"No previous steps.":r.join(`
284
+ `,di={name:"Coding",planning:{enabled:!0,planningPrompt:ah},steps:{enabled:!0,retryOnFailure:!0,allowDynamicSteps:!1,stepPrompt:lh},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},ui={name:"Chat",planning:{enabled:!1},steps:{enabled:!1},progress:{enabled:!1}};var fi={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:mi,toolSearch:{alwaysLoadedTools:["fs.read_file","fs.write_file","fs.list_dir","web.search","web.fetch","skill.search","skill.read"]}},gi={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:ui,toolSearch:{alwaysLoadedTools:["web.search","web.fetch","fs.read_file","fs.list_dir"]}},aw={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:di,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"]}},Bo=[fi,aw,gi],Be="chat";var Xt=class{modes=new Map;orderedNames=[];constructor(){for(let e of Bo)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(Be);if(!e)throw new Error(`Default mode "${Be}" 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],s=this.modes.get(r);if(!s)throw new Error(`Mode "${r}" not found in registry`);return s}get size(){return this.modes.size}remove(e){if(Bo.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 ch(n){return{name:n.name,displayName:n.displayName,description:n.description||n.displayName,systemPrompt:n.systemPrompt,allowedToolCategories:n.allowedToolCategories||[],blockedToolCategories:n.blockedToolCategories||[],allowedTools:n.allowedTools||[],blockedTools:n.blockedTools||[],blockAllTools:n.blockAllTools||!1,baseContext:n.baseContext,workflow:n.workflow}}l();var fn={planning:{enabled:!1},steps:{enabled:!1},progress:{enabled:!0}};l();_();var lw=dn,Zt=class{client;config;constructor(e,t){this.client=e,this.config=t}async createPlan(e,t){let o=this.config?.planningPrompt||lw,r=e.messages.filter(p=>p.role==="user").map(p=>typeof p.content=="string"?p.content:"[obj]").join(" ").substring(0,100);h(`[Planner] createPlan() provider=${t??"default"} maxSteps=${this.config?.maxSteps??20} request="${r}..."`);let s=e.messages.filter(p=>p.role==="system"),i=e.messages.filter(p=>p.role!=="system"),a=[{role:"system",content:o},...s,...i],c={...e,tools:void 0,tool_choice:"none",response_format:"json_object",messages:a};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,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 s=this.config?.maxSteps??20,i=r.steps.slice(0,s);r.steps.length>s&&E(`[Planner] parsePlan() truncated ${r.steps.length} steps to maxSteps=${s}`),h(`[Planner] parsePlan() parsed ${i.length} steps successfully`);let a=i.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:a,status:"draft",createdAt:new Date,planningResponse:o}}catch(r){return E(`[Planner] parsePlan() failed: ${r.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(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 eo=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,s=e.steps[o],i=s?s.description:"Done",a="executing";return e.status==="draft"&&(a="planning"),e.status==="approved"&&(a="executing"),e.status==="completed"&&(a="completed"),(e.status==="failed"||e.status==="cancelled")&&(a="failed"),{planId:e.id,currentStep:Math.min(o+1,t),totalSteps:t,percentage:r,currentStepDescription:i,status:a}}static summarizeCompletedSteps(e,t){let o=[];for(let r of e.steps){if(r.id===t)break;if(r.status==="completed"&&r.result){let s=r.result.toolsUsed?.length?` (Tools: ${r.result.toolsUsed.join(", ")})`:"",i=r.result.output||"No output";i.length>500&&(i=i.substring(0,500)+"... [truncated]"),o.push(`Step ${r.number}: ${r.description}${s}
285
+ Result: ${i}`)}else r.status==="failed"?o.push(`Step ${r.number}: ${r.description}
286
+ Failed: ${r.result?.error||"Unknown error"}`):r.status==="skipped"&&o.push(`Step ${r.number}: ${r.description}
287
+ Skipped.`)}return o.length===0?"No previous steps.":o.join(`
283
288
 
284
- `)}};k();var qy=Kr,Uy=`
289
+ `)}};_();var cw=un,pw=`
285
290
  Based on the result of the previous step, do we need to add any new steps to our plan before continuing?
286
291
  Only add steps if they are absolutely necessary to complete the user's request.
287
292
 
@@ -299,46 +304,46 @@ JSON Schema:
299
304
  { "description": "What to do", "expectedTools": [] }
300
305
  ]
301
306
  }
302
- `,Yt=class{client;config;constructor(e,t){this.client=e,this.config=t}async executeStep(e,t,r,o){let n=Date.now();h(`[StepExecutor] executeStep() step=${e.number} "${e.description}" expectedTools=${e.expectedTools?.join(",")||"none"}`);let a=this.buildStepRequest(e,t,r);try{let i=await this.client.generate(a,o),c=new Set;i.tool_calls&&i.tool_calls.forEach(m=>c.add(m.name));let p=Date.now()-n;return v(`[StepExecutor] Step ${e.number} completed in ${p}ms toolsUsed=[${Array.from(c).join(", ")||"none"}] output_len=${i.content?.length??0}`),{success:!0,output:i.content||"Step completed successfully.",toolsUsed:Array.from(c),duration:p,response:i}}catch(i){let c=Date.now()-n;return E(`[StepExecutor] Step ${e.number} failed in ${c}ms: ${i.message}`),{success:!1,error:i.message||"Unknown execution error",duration:c}}}async*streamStep(e,t,r,o){h(`[StepExecutor] streamStep() step=${e.number} "${e.description}"`);let n=this.buildStepRequest(e,t,r);yield*this.client.stream(n,o)}buildStepRequest(e,t,r){let o=Qt.summarizeCompletedSteps(t,e.id),a=(this.config?.stepPrompt||qy).replace("{stepNumber}",e.number.toString()).replace("{planSummary}",t.summary).replace("{stepDescription}",e.description).replace("{previousStepsResults}",o),i=r.messages.filter(u=>u.role==="system"),c=r.messages.filter(u=>u.role!=="system"),p=[...i,...c],m=[];for(let u of t.steps){if(u.id===e.id)break;if(u.status==="completed"&&u.result?.output){let g=u.result.output;g.length>2e3&&(g=g.substring(0,2e3)+`
303
- ... [truncated]`),m.push({role:"assistant",content:g}),m.push({role:"user",content:`Step ${u.number} is complete. Now proceed with the next step.`})}}return{...r,messages:[{role:"system",content:a},...p,...m],tool_choice:"auto"}}async checkForDynamicSteps(e,t,r,o){if(!this.config?.allowDynamicSteps)return[];let n=t.steps.length,a=this.config.maxTotalSteps??50;if(n>=a)return h(`[StepExecutor] checkForDynamicSteps() skipped \u2014 already at maxTotalSteps=${a}`),[];h(`[StepExecutor] checkForDynamicSteps() after step=${e.number} currentTotal=${n} max=${a}`);let i=t.steps.filter(w=>w.status==="pending"&&w.number>e.number).map(w=>`${w.number}. ${w.description}`).join(`
304
- `)||"None",c=Uy.replace("{{REMAINING_STEPS}}",i),p=r.messages.filter(w=>w.role==="system"),m=r.messages.filter(w=>w.role!=="system"),u=[...p,...m],g={...r,tool_choice:"none",response_format:"json_object",messages:[...u,{role:"assistant",content:e.result?.output||""},{role:"user",content:c}]};try{let w=await this.client.generate(g,o),y=JSON.parse(w.content||'{"steps": []}');if(Array.isArray(y.steps)&&y.steps.length>0){let b=a-n,P=y.steps.slice(0,b),$=new Set(t.steps.map(x=>this.normalizeStepDescription(x.description))),C=P.filter(x=>{let S=this.normalizeStepDescription(x.description||"");return $.has(S)?!1:($.add(S),!0)});return C.length===0?(h("[StepExecutor] checkForDynamicSteps() all proposed steps were duplicates \u2014 skipping"),[]):(v(`[StepExecutor] checkForDynamicSteps() adding ${C.length} dynamic step(s) after step ${e.number}`),C.map((x,S)=>({id:`step-${Date.now()}-dyn-${S}`,number:0,description:x.description||"Dynamic step",expectedTools:x.expectedTools||[],dependsOn:[e.id],status:"pending"})))}}catch{}return[]}normalizeStepDescription(e){return e.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim().split(" ").filter(t=>t.length>2).sort().join(" ")}};l();var Ug=require("events");k();var qo=class extends Ug.EventEmitter{client;config;planner;stepExecutor;queryClassifier;pendingApprovals=new Map;constructor(e,t,r){super(),this.client=e,this.config=t,this.queryClassifier=r||new He,this.planner=new Kt(e,t.planning),this.stepExecutor=new Yt(e,t.steps)}getConfig(){return this.config}setConfig(e){this.config=e,this.planner=new Kt(this.client,e.planning),this.stepExecutor=new Yt(this.client,e.steps)}shouldRouteSimpleQuery(e){if(!this.config.complexityRouting?.enabled)return!1;let t=this.config.complexityRouting.strategy??"single-step";if(t==="disabled")return!1;let r=Ae(e.messages);if(!r)return!1;let o=this.queryClassifier.classify(r),n=this.config.complexityRouting.confidenceThreshold??.6,a=!1;switch(o.type){case"action":a=!1;break;case"conversational":a=!0;break;case"analytical":a=o.confidence>=n;break}return h(`[Workflow] shouldRouteSimpleQuery() type=${o.type} confidence=${o.confidence.toFixed(2)} threshold=${n} shouldRoute=${a} strategy=${t}`),a}async execute(e,t){if(this.shouldRouteSimpleQuery(e))return this.executeDirect(e,t);let r=this.config.planning?.enabled,o=this.config.steps?.enabled;if(h(`[Workflow] execute() planningEnabled=${r} stepsEnabled=${o} provider=${t??"default"}`),!r&&!o)return h("[Workflow] execute() mode=direct"),this.executeDirect(e,t);let n=null;if(r){if(h("[Workflow] execute() mode=planning \u2014 creating plan"),n=await this.createPlan(e,t),this.emit("workflow:plan_created",n),this.config.planning?.requireApproval){v(`[Workflow] Plan "${n.id}" requires approval \u2014 waiting`),this.emitProgress(n,"awaiting_approval","Waiting for plan approval");let a=await this.waitForApproval(n.id);if(this.emit("workflow:plan_decision",n,a),!a)return v(`[Workflow] Plan "${n.id}" rejected by user`),n.status="cancelled",this.emitProgress(n,"failed","Plan rejected by user"),{success:!1,plan:n,error:"Plan rejected by user",metrics:{totalDuration:0,stepsCompleted:0,stepsFailed:0,retriesUsed:0}};v(`[Workflow] Plan "${n.id}" approved`)}n.status="approved"}return o?(n||(h("[Workflow] execute() mode=steps-only \u2014 creating implicit plan"),n=await this.planner.createPlan(e,t),this.emit("workflow:plan_created",n),n.status="approved"),this.executeStepByStep(n,e,t)):n?(h("[Workflow] execute() mode=plan-direct (planning only, no steps)"),this.executePlanDirect(n,e,t)):this.executeDirect(e,t)}async executeDirect(e,t){let r=Date.now(),o=this.createDummyPlan(e);h(`[Workflow] executeDirect() provider=${t??"default"}`);try{this.emitProgress(o,"executing","Direct execution");let n=await this.client.generate(e,t);o.status="completed",o.completedAt=new Date,o.steps[0].status="completed";let a=Date.now()-r;h(`[Workflow] executeDirect() completed in ${a}ms content_len=${n.content?.length??0}`);let i={success:!0,plan:o,output:n.content||void 0,metrics:{totalDuration:Date.now()-r,stepsCompleted:1,stepsFailed:0,retriesUsed:0}};return this.emit("workflow:completed",o,i),this.emitProgress(o,"completed","Done"),i}catch(n){o.status="failed",o.completedAt=new Date,o.steps[0].status="failed",E(`[Workflow] executeDirect() failed: ${n.message}`);let a={success:!1,plan:o,error:n.message,metrics:{totalDuration:Date.now()-r,stepsCompleted:0,stepsFailed:1,retriesUsed:0}};return this.emit("workflow:failed",o,n),this.emitProgress(o,"failed","Execution failed"),a}}async createPlan(e,t){h(`[Workflow] createPlan() provider=${t??"default"}`);let r=this.createDummyPlan(e);r.status="draft",this.emitProgress(r,"planning","Creating plan...");let o=await this.planner.createPlan(e,t);return v(`[Workflow] createPlan() completed plan.id=${o.id} steps=${o.steps.length}`),o}async executeStepByStep(e,t,r){e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e),v(`[Workflow] executeStepByStep() plan.id=${e.id} steps=${e.steps.length} maxRetries=${this.config.steps?.maxRetries??3}`);let o=Date.now(),n=0;for(let c=0;c<e.steps.length;c++){let p=e.steps[c];if(p.status!=="pending"&&p.status!=="failed")continue;if(p.dependsOn?.length){let y=p.dependsOn.filter(b=>{let P=e.steps.find($=>$.id===String(b)||$.number===Number(b));return P?P.status!=="completed":!1});if(y.length>0){h(`[Workflow] Step ${p.number} skipped \u2014 unmet deps: ${y.join(", ")}`),p.status="skipped",p.result={success:!1,error:`Unmet dependencies: ${y.join(", ")}`};continue}}p.status="in_progress",this.emit("workflow:step_start",p,e),this.emitProgress(e,"executing",p.description),v(`[Workflow] Step ${p.number}/${e.steps.length} starting: "${p.description}"`);let m=0,u=this.config.steps?.maxRetries??3,g=null,w=!1;for(;m<=u;)try{let y=await this.stepExecutor.executeStep(p,e,t,r);if(y.success){p.status="completed",p.result=y,this.emit("workflow:step_complete",p,e),h(`[Workflow] Step ${p.number} completed in ${y.duration??0}ms toolsUsed=${(y.toolsUsed??[]).join(",")||"none"}`),w=!0;break}else throw new Error(y.error||"Step returned unsuccessful result")}catch(y){if(g=y,m++,m<=u&&this.config.steps?.retryOnFailure)n++,E(`[Workflow] Step ${p.number} failed (attempt ${m}/${u}), retrying: ${g.message}`),this.emit("workflow:step_retry",p,m,e),this.emitProgress(e,"executing",`[Retry ${m}] ${p.description}`);else{E(`[Workflow] Step ${p.number} failed permanently: ${g.message}`),p.status="failed",p.result={success:!1,error:g.message},this.emit("workflow:step_failed",p,g,e);break}}if(!w){let y=this.config.onFailure?.strategy||"abort";if(h(`[Workflow] Step ${p.number} failed \u2014 applying strategy="${y}"`),y==="abort"){e.status="failed",e.completedAt=new Date;let b={success:!1,plan:e,error:`Step ${p.number} failed: ${g?.message}`,metrics:this.computeMetrics(e,o,n)};return this.emit("workflow:failed",e,g),this.emitProgress(e,"failed","Workflow aborted due to step failure"),b}else if(y==="ask_user"){if(this.emitProgress(e,"awaiting_approval",`Step failed: ${g?.message}. Continue?`),!await this.waitForApproval(e.id)){e.status="failed",e.completedAt=new Date;let P={success:!1,plan:e,error:`Workflow aborted by user after step ${p.number} failure`,metrics:this.computeMetrics(e,o,n)};return this.emit("workflow:failed",e,new Error(P.error)),P}p.status="skipped"}else p.status="skipped"}if(w&&this.config.steps?.allowDynamicSteps){let y=await this.stepExecutor.checkForDynamicSteps(p,e,t,r);if(y.length>0){let b=p.number+1;for(let P of y)P.number=b++;for(let P=c+1;P<e.steps.length;P++)e.steps[P].number=b++;e.steps.splice(c+1,0,...y),y.forEach(P=>this.emit("workflow:step_added",P,e))}}}let a=this.computeMetrics(e,o,n);e.status="completed",e.completedAt=new Date,e.metrics=a,v(`[Workflow] executeStepByStep() completed plan.id=${e.id} duration=${a.totalDuration}ms stepsCompleted=${a.stepsCompleted} stepsFailed=${a.stepsFailed} retriesUsed=${n}`);let i={success:!0,plan:e,output:this.extractFinalOutput(e),response:this.extractFinalResponse(e),metrics:e.metrics};return this.emit("workflow:completed",e,i),this.emitProgress(e,"completed","Done"),i}async executePlanDirect(e,t,r){let o=Date.now();e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e),this.emitProgress(e,"executing","Executing plan"),h(`[Workflow] executePlanDirect() plan.id=${e.id} steps=${e.steps.length} provider=${r??"default"}`);let n=`
307
+ `,to=class{client;config;constructor(e,t){this.client=e,this.config=t}async executeStep(e,t,o,r){let s=Date.now();h(`[StepExecutor] executeStep() step=${e.number} "${e.description}" expectedTools=${e.expectedTools?.join(",")||"none"}`);let i=this.buildStepRequest(e,t,o);try{let a=await this.client.generate(i,r),c=new Set;a.tool_calls&&a.tool_calls.forEach(m=>c.add(m.name));let p=Date.now()-s;return v(`[StepExecutor] Step ${e.number} completed in ${p}ms toolsUsed=[${Array.from(c).join(", ")||"none"}] output_len=${a.content?.length??0}`),{success:!0,output:a.content||"Step completed successfully.",toolsUsed:Array.from(c),duration:p,response:a}}catch(a){let c=Date.now()-s;return E(`[StepExecutor] Step ${e.number} failed in ${c}ms: ${a.message}`),{success:!1,error:a.message||"Unknown execution error",duration:c}}}async*streamStep(e,t,o,r){h(`[StepExecutor] streamStep() step=${e.number} "${e.description}"`);let s=this.buildStepRequest(e,t,o);yield*this.client.stream(s,r)}buildStepRequest(e,t,o){let r=eo.summarizeCompletedSteps(t,e.id),i=(this.config?.stepPrompt||cw).replace("{stepNumber}",e.number.toString()).replace("{planSummary}",t.summary).replace("{stepDescription}",e.description).replace("{previousStepsResults}",r),a=o.messages.filter(u=>u.role==="system"),c=o.messages.filter(u=>u.role!=="system"),p=[...a,...c],m=[];for(let u of t.steps){if(u.id===e.id)break;if(u.status==="completed"&&u.result?.output){let g=u.result.output;g.length>2e3&&(g=g.substring(0,2e3)+`
308
+ ... [truncated]`),m.push({role:"assistant",content:g}),m.push({role:"user",content:`Step ${u.number} is complete. Now proceed with the next step.`})}}return{...o,messages:[{role:"system",content:i},...p,...m],tool_choice:"auto"}}async checkForDynamicSteps(e,t,o,r){if(!this.config?.allowDynamicSteps)return[];let s=t.steps.length,i=this.config.maxTotalSteps??50;if(s>=i)return h(`[StepExecutor] checkForDynamicSteps() skipped \u2014 already at maxTotalSteps=${i}`),[];h(`[StepExecutor] checkForDynamicSteps() after step=${e.number} currentTotal=${s} max=${i}`);let a=t.steps.filter(w=>w.status==="pending"&&w.number>e.number).map(w=>`${w.number}. ${w.description}`).join(`
309
+ `)||"None",c=pw.replace("{{REMAINING_STEPS}}",a),p=o.messages.filter(w=>w.role==="system"),m=o.messages.filter(w=>w.role!=="system"),u=[...p,...m],g={...o,tool_choice:"none",response_format:"json_object",messages:[...u,{role:"assistant",content:e.result?.output||""},{role:"user",content:c}]};try{let w=await this.client.generate(g,r),y=JSON.parse(w.content||'{"steps": []}');if(Array.isArray(y.steps)&&y.steps.length>0){let b=i-s,T=y.steps.slice(0,b),k=new Set(t.steps.map(P=>this.normalizeStepDescription(P.description))),C=T.filter(P=>{let S=this.normalizeStepDescription(P.description||"");return k.has(S)?!1:(k.add(S),!0)});return C.length===0?(h("[StepExecutor] checkForDynamicSteps() all proposed steps were duplicates \u2014 skipping"),[]):(v(`[StepExecutor] checkForDynamicSteps() adding ${C.length} dynamic step(s) after step ${e.number}`),C.map((P,S)=>({id:`step-${Date.now()}-dyn-${S}`,number:0,description:P.description||"Dynamic step",expectedTools:P.expectedTools||[],dependsOn:[e.id],status:"pending"})))}}catch{}return[]}normalizeStepDescription(e){return e.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim().split(" ").filter(t=>t.length>2).sort().join(" ")}};l();var ph=require("events");_();var Ko=class extends ph.EventEmitter{client;config;planner;stepExecutor;queryClassifier;pendingApprovals=new Map;constructor(e,t,o){super(),this.client=e,this.config=t,this.queryClassifier=o||new Ve,this.planner=new Zt(e,t.planning),this.stepExecutor=new to(e,t.steps)}getConfig(){return this.config}setConfig(e){this.config=e,this.planner=new Zt(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 o=je(e.messages);if(!o)return!1;let r=this.queryClassifier.classify(o),s=this.config.complexityRouting.confidenceThreshold??.6,i=!1;switch(r.type){case"action":i=!1;break;case"conversational":i=!0;break;case"analytical":i=r.confidence>=s;break}return h(`[Workflow] shouldRouteSimpleQuery() type=${r.type} confidence=${r.confidence.toFixed(2)} threshold=${s} shouldRoute=${i} strategy=${t}`),i}async execute(e,t){if(this.shouldRouteSimpleQuery(e))return this.executeDirect(e,t);let o=this.config.planning?.enabled,r=this.config.steps?.enabled;if(h(`[Workflow] execute() planningEnabled=${o} stepsEnabled=${r} provider=${t??"default"}`),!o&&!r)return h("[Workflow] execute() mode=direct"),this.executeDirect(e,t);let s=null;if(o){if(h("[Workflow] execute() mode=planning \u2014 creating plan"),s=await this.createPlan(e,t),this.emit("workflow:plan_created",s),this.config.planning?.requireApproval){v(`[Workflow] Plan "${s.id}" requires approval \u2014 waiting`),this.emitProgress(s,"awaiting_approval","Waiting for plan approval");let i=await this.waitForApproval(s.id);if(this.emit("workflow:plan_decision",s,i),!i)return v(`[Workflow] Plan "${s.id}" rejected by user`),s.status="cancelled",this.emitProgress(s,"failed","Plan rejected by user"),{success:!1,plan:s,error:"Plan rejected by user",metrics:{totalDuration:0,stepsCompleted:0,stepsFailed:0,retriesUsed:0}};v(`[Workflow] Plan "${s.id}" approved`)}s.status="approved"}return r?(s||(h("[Workflow] execute() mode=steps-only \u2014 creating implicit plan"),s=await this.planner.createPlan(e,t),this.emit("workflow:plan_created",s),s.status="approved"),this.executeStepByStep(s,e,t)):s?(h("[Workflow] execute() mode=plan-direct (planning only, no steps)"),this.executePlanDirect(s,e,t)):this.executeDirect(e,t)}async executeDirect(e,t){let o=Date.now(),r=this.createDummyPlan(e);h(`[Workflow] executeDirect() provider=${t??"default"}`);try{this.emitProgress(r,"executing","Direct execution");let s=await this.client.generate(e,t);r.status="completed",r.completedAt=new Date,r.steps[0].status="completed";let i=Date.now()-o;h(`[Workflow] executeDirect() completed in ${i}ms content_len=${s.content?.length??0}`);let a={success:!0,plan:r,output:s.content||void 0,metrics:{totalDuration:Date.now()-o,stepsCompleted:1,stepsFailed:0,retriesUsed:0}};return this.emit("workflow:completed",r,a),this.emitProgress(r,"completed","Done"),a}catch(s){r.status="failed",r.completedAt=new Date,r.steps[0].status="failed",E(`[Workflow] executeDirect() failed: ${s.message}`);let i={success:!1,plan:r,error:s.message,metrics:{totalDuration:Date.now()-o,stepsCompleted:0,stepsFailed:1,retriesUsed:0}};return this.emit("workflow:failed",r,s),this.emitProgress(r,"failed","Execution failed"),i}}async createPlan(e,t){h(`[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(),s=0;for(let c=0;c<e.steps.length;c++){let p=e.steps[c];if(p.status!=="pending"&&p.status!=="failed")continue;if(p.dependsOn?.length){let y=p.dependsOn.filter(b=>{let T=e.steps.find(k=>k.id===String(b)||k.number===Number(b));return T?T.status!=="completed":!1});if(y.length>0){h(`[Workflow] Step ${p.number} skipped \u2014 unmet deps: ${y.join(", ")}`),p.status="skipped",p.result={success:!1,error:`Unmet dependencies: ${y.join(", ")}`};continue}}p.status="in_progress",this.emit("workflow:step_start",p,e),this.emitProgress(e,"executing",p.description),v(`[Workflow] Step ${p.number}/${e.steps.length} starting: "${p.description}"`);let m=0,u=this.config.steps?.maxRetries??3,g=null,w=!1;for(;m<=u;)try{let y=await this.stepExecutor.executeStep(p,e,t,o);if(y.success){p.status="completed",p.result=y,this.emit("workflow:step_complete",p,e),h(`[Workflow] Step ${p.number} completed in ${y.duration??0}ms toolsUsed=${(y.toolsUsed??[]).join(",")||"none"}`),w=!0;break}else throw new Error(y.error||"Step returned unsuccessful result")}catch(y){if(g=y,m++,m<=u&&this.config.steps?.retryOnFailure)s++,E(`[Workflow] Step ${p.number} failed (attempt ${m}/${u}), retrying: ${g.message}`),this.emit("workflow:step_retry",p,m,e),this.emitProgress(e,"executing",`[Retry ${m}] ${p.description}`);else{E(`[Workflow] Step ${p.number} failed permanently: ${g.message}`),p.status="failed",p.result={success:!1,error:g.message},this.emit("workflow:step_failed",p,g,e);break}}if(!w){let y=this.config.onFailure?.strategy||"abort";if(h(`[Workflow] Step ${p.number} failed \u2014 applying strategy="${y}"`),y==="abort"){e.status="failed",e.completedAt=new Date;let b={success:!1,plan:e,error:`Step ${p.number} failed: ${g?.message}`,metrics:this.computeMetrics(e,r,s)};return this.emit("workflow:failed",e,g),this.emitProgress(e,"failed","Workflow aborted due to step failure"),b}else if(y==="ask_user"){if(this.emitProgress(e,"awaiting_approval",`Step failed: ${g?.message}. Continue?`),!await this.waitForApproval(e.id)){e.status="failed",e.completedAt=new Date;let T={success:!1,plan:e,error:`Workflow aborted by user after step ${p.number} failure`,metrics:this.computeMetrics(e,r,s)};return this.emit("workflow:failed",e,new Error(T.error)),T}p.status="skipped"}else p.status="skipped"}if(w&&this.config.steps?.allowDynamicSteps){let y=await this.stepExecutor.checkForDynamicSteps(p,e,t,o);if(y.length>0){let b=p.number+1;for(let T of y)T.number=b++;for(let T=c+1;T<e.steps.length;T++)e.steps[T].number=b++;e.steps.splice(c+1,0,...y),y.forEach(T=>this.emit("workflow:step_added",T,e))}}}let i=this.computeMetrics(e,r,s);e.status="completed",e.completedAt=new Date,e.metrics=i,v(`[Workflow] executeStepByStep() completed plan.id=${e.id} duration=${i.totalDuration}ms stepsCompleted=${i.stepsCompleted} stepsFailed=${i.stepsFailed} retriesUsed=${s}`);let a={success:!0,plan:e,output:this.extractFinalOutput(e),response:this.extractFinalResponse(e),metrics:e.metrics};return this.emit("workflow:completed",e,a),this.emitProgress(e,"completed","Done"),a}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"),h(`[Workflow] executePlanDirect() plan.id=${e.id} steps=${e.steps.length} provider=${o??"default"}`);let s=`
305
310
  You have created the following plan to fulfill the request:
306
311
  Summary: ${e.summary}
307
312
 
308
313
  Steps:
309
- ${e.steps.map(i=>`${i.number}. ${i.description}`).join(`
314
+ ${e.steps.map(a=>`${a.number}. ${a.description}`).join(`
310
315
  `)}
311
316
 
312
317
  Execute this plan now.
313
- `.trim(),a={...t,messages:[{role:"system",content:n},...t.messages]};try{let i=await this.client.generate(a,r);e.steps.forEach(p=>{p.status="completed",p.result={success:!0,output:i.content||""}}),e.status="completed",e.completedAt=new Date,e.metrics=this.computeMetrics(e,o,0),h(`[Workflow] executePlanDirect() completed plan.id=${e.id} duration=${Date.now()-o}ms`);let c={success:!0,plan:e,output:i.content||void 0,metrics:e.metrics};return this.emit("workflow:completed",e,c),this.emitProgress(e,"completed","Done"),c}catch(i){e.status="failed",e.completedAt=new Date,E(`[Workflow] executePlanDirect() failed plan.id=${e.id}: ${i.message}`);let c={success:!1,plan:e,error:i.message,metrics:this.computeMetrics(e,o,0)};return this.emit("workflow:failed",e,i),this.emitProgress(e,"failed","Execution failed"),c}}emitProgress(e,t,r){if(!this.config.progress?.enabled)return;let o=Qt.getProgress(e);t&&(o.status=t),r&&(o.currentStepDescription=r),this.emit("workflow:progress",o)}computeMetrics(e,t,r){return{totalDuration:Date.now()-t,stepsCompleted:e.steps.filter(o=>o.status==="completed").length,stepsFailed:e.steps.filter(o=>o.status==="failed").length,retriesUsed:r}}summarizePlanResult(e){return`Workflow completed.
318
+ `.trim(),i={...t,messages:[{role:"system",content:s},...t.messages]};try{let a=await this.client.generate(i,o);e.steps.forEach(p=>{p.status="completed",p.result={success:!0,output:a.content||""}}),e.status="completed",e.completedAt=new Date,e.metrics=this.computeMetrics(e,r,0),h(`[Workflow] executePlanDirect() completed plan.id=${e.id} duration=${Date.now()-r}ms`);let c={success:!0,plan:e,output:a.content||void 0,metrics:e.metrics};return this.emit("workflow:completed",e,c),this.emitProgress(e,"completed","Done"),c}catch(a){e.status="failed",e.completedAt=new Date,E(`[Workflow] executePlanDirect() failed plan.id=${e.id}: ${a.message}`);let c={success:!1,plan:e,error:a.message,metrics:this.computeMetrics(e,r,0)};return this.emit("workflow:failed",e,a),this.emitProgress(e,"failed","Execution failed"),c}}emitProgress(e,t,o){if(!this.config.progress?.enabled)return;let r=eo.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.
314
319
  Summary: ${e.summary}
315
320
  Steps:
316
321
  `+e.steps.map(t=>`[${t.status.toUpperCase()}] ${t.description}`).join(`
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(`
322
+ `)}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 r=e.steps.length-1;r>=0;r--){let s=e.steps[r];if(s.status==="completed"&&s.result?.output)return s.result.output}else{let r=[];for(let s of e.steps)s.status==="completed"&&s.result?.output&&r.push(s.result.output);if(r.length>0)return r.join(`
318
323
 
319
- `)}return e.steps.length===0||e.steps.every(o=>o.status==="pending")?e.summary:this.summarizePlanResult(e)}extractFinalResponse(e){for(let t=e.steps.length-1;t>=0;t--){let r=e.steps[t];if(r.status==="completed"&&r.result?.response)return r.result.response}}createDummyPlan(e){let t=e.messages.filter(r=>r.role==="user").map(r=>typeof r.content=="string"?r.content:"[Object]").join("\\n");return{id:`plan-direct-${Date.now()}`,request:t,summary:"Direct execution",steps:[{id:"step-1",number:1,description:"Execute request",status:"pending",dependsOn:[],expectedTools:[]}],status:"in_progress",createdAt:new Date}}async*stream(e,t){let r=this.config.planning?.enabled,o=this.config.steps?.enabled;if(h(`[Workflow] stream() planningEnabled=${r} stepsEnabled=${o} provider=${t??"default"}`),!r&&!o){h("[Workflow] stream() mode=direct"),yield*this.streamDirect(e,t);return}let n=null;if(r){if(yield{delta:"",workflowStep:{number:0,description:"Creating plan..."}},n=await this.planner.createPlan(e,t),this.emit("workflow:plan_created",n),this.config.planning?.requireApproval){this.emitProgress(n,"awaiting_approval","Waiting for plan approval"),yield{delta:`
324
+ `)}return e.steps.length===0||e.steps.every(r=>r.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(h(`[Workflow] stream() planningEnabled=${o} stepsEnabled=${r} provider=${t??"default"}`),!o&&!r){h("[Workflow] stream() mode=direct"),yield*this.streamDirect(e,t);return}let s=null;if(o){if(yield{delta:"",workflowStep:{number:0,description:"Creating plan..."}},s=await this.planner.createPlan(e,t),this.emit("workflow:plan_created",s),this.config.planning?.requireApproval){this.emitProgress(s,"awaiting_approval","Waiting for plan approval"),yield{delta:`
320
325
 
321
326
  **Plan Created:**
322
- ${n.summary}
327
+ ${s.summary}
323
328
 
324
329
  Steps:
325
- ${n.steps.map(i=>`${i.number}. ${i.description}`).join(`
330
+ ${s.steps.map(a=>`${a.number}. ${a.description}`).join(`
326
331
  `)}
327
332
 
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:`
333
+ *Waiting for approval...*`,workflowStep:{number:0,description:"Awaiting approval"}};let i=await this.waitForApproval(s.id);if(this.emit("workflow:plan_decision",s,i),!i){s.status="cancelled",yield{delta:`
329
334
 
330
- *Plan rejected by user.*`,finish_reason:"stop"};return}}n.status="approved"}if(o){n||(n=await this.planner.createPlan(e,t),this.emit("workflow:plan_created",n),n.status="approved"),yield*this.streamStepByStep(n,e,t);return}if(n){yield*this.streamPlanDirect(n,e,t);return}yield*this.streamDirect(e,t)}async*streamDirect(e,t){yield*this.client.stream(e,t)}async*streamStepByStep(e,t,r){e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e);let o=Date.now(),n=0;for(let i=0;i<e.steps.length;i++){if(t.signal?.aborted){e.status="cancelled",e.completedAt=new Date,this.emit("workflow:failed",e,new Error("Interrupted by user"));return}let c=e.steps[i];if(c.status!=="pending"&&c.status!=="failed")continue;if(c.dependsOn?.length){let y=c.dependsOn.filter(b=>{let P=e.steps.find($=>$.id===String(b)||$.number===Number(b));return P?P.status!=="completed":!1});if(y.length>0){c.status="skipped",c.result={success:!1,error:`Unmet dependencies: ${y.join(", ")}`};continue}}c.status="in_progress",this.emit("workflow:step_start",c,e),this.emitProgress(e,"executing",c.description);let p=0,m=this.config.steps?.maxRetries??3,u=null,g=!1,w="";for(;p<=m;)try{for await(let y of this.stepExecutor.streamStep(c,e,t,r)){if(t.signal?.aborted){c.status="skipped",e.status="cancelled",e.completedAt=new Date,this.emit("workflow:failed",e,new Error("Interrupted by user"));return}y.delta&&(w+=y.delta),yield{...y,workflowStep:{number:c.number,description:c.description}}}c.status="completed",c.result={success:!0,output:w,duration:Date.now()-o},this.emit("workflow:step_complete",c,e),this.emitProgress(e,"executing"),g=!0;break}catch(y){if(u=y,p++,p<=m&&this.config.steps?.retryOnFailure)n++,this.emit("workflow:step_retry",c,p,e),this.emitProgress(e,"executing",`[Retry ${p}/${m}] ${c.description}`);else{c.status="failed",c.result={success:!1,error:u.message},this.emit("workflow:step_failed",c,u,e);break}}if(!g){let y=this.config.onFailure?.strategy||"abort";if(y==="abort"){e.status="failed",e.completedAt=new Date,this.emit("workflow:failed",e,u),yield{delta:`
335
+ *Plan rejected by user.*`,finish_reason:"stop"};return}}s.status="approved"}if(r){s||(s=await this.planner.createPlan(e,t),this.emit("workflow:plan_created",s),s.status="approved"),yield*this.streamStepByStep(s,e,t);return}if(s){yield*this.streamPlanDirect(s,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(),s=0;for(let a=0;a<e.steps.length;a++){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[a];if(c.status!=="pending"&&c.status!=="failed")continue;if(c.dependsOn?.length){let y=c.dependsOn.filter(b=>{let T=e.steps.find(k=>k.id===String(b)||k.number===Number(b));return T?T.status!=="completed":!1});if(y.length>0){c.status="skipped",c.result={success:!1,error:`Unmet dependencies: ${y.join(", ")}`};continue}}c.status="in_progress",this.emit("workflow:step_start",c,e),this.emitProgress(e,"executing",c.description);let p=0,m=this.config.steps?.maxRetries??3,u=null,g=!1,w="";for(;p<=m;)try{for await(let y of this.stepExecutor.streamStep(c,e,t,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}y.delta&&(w+=y.delta),yield{...y,workflowStep:{number:c.number,description:c.description}}}c.status="completed",c.result={success:!0,output:w,duration:Date.now()-r},this.emit("workflow:step_complete",c,e),this.emitProgress(e,"executing"),g=!0;break}catch(y){if(u=y,p++,p<=m&&this.config.steps?.retryOnFailure)s++,this.emit("workflow:step_retry",c,p,e),this.emitProgress(e,"executing",`[Retry ${p}/${m}] ${c.description}`);else{c.status="failed",c.result={success:!1,error:u.message},this.emit("workflow:step_failed",c,u,e);break}}if(!g){let y=this.config.onFailure?.strategy||"abort";if(y==="abort"){e.status="failed",e.completedAt=new Date,this.emit("workflow:failed",e,u),yield{delta:`
331
336
 
332
337
  **Step failed:** ${u?.message}
333
338
  *Workflow aborted.*`,finish_reason:"stop"};return}else y==="skip"&&(c.status="skipped",yield{delta:`
334
339
  *Step skipped due to failure.*
335
- `,workflowStep:{number:c.number,description:c.description}})}if(g&&this.config.steps?.allowDynamicSteps){let y=await this.stepExecutor.checkForDynamicSteps(c,e,t,r);if(y.length>0){let b=c.number+1;for(let P of y)P.number=b++;for(let P=i+1;P<e.steps.length;P++)e.steps[P].number=b++;e.steps.splice(i+1,0,...y),y.forEach(P=>this.emit("workflow:step_added",P,e)),this.emitProgress(e,"executing")}}}e.status="completed",e.completedAt=new Date,e.metrics=this.computeMetrics(e,o,n);let a={success:!0,plan:e,output:this.extractFinalOutput(e),response:this.extractFinalResponse(e),metrics:e.metrics};this.emit("workflow:completed",e,a),this.emitProgress(e,"completed","Done"),yield{delta:"",finish_reason:"stop"}}async*streamPlanDirect(e,t,r){e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e);let o=`
340
+ `,workflowStep:{number:c.number,description:c.description}})}if(g&&this.config.steps?.allowDynamicSteps){let y=await this.stepExecutor.checkForDynamicSteps(c,e,t,o);if(y.length>0){let b=c.number+1;for(let T of y)T.number=b++;for(let T=a+1;T<e.steps.length;T++)e.steps[T].number=b++;e.steps.splice(a+1,0,...y),y.forEach(T=>this.emit("workflow:step_added",T,e)),this.emitProgress(e,"executing")}}}e.status="completed",e.completedAt=new Date,e.metrics=this.computeMetrics(e,r,s);let i={success:!0,plan:e,output:this.extractFinalOutput(e),response:this.extractFinalResponse(e),metrics:e.metrics};this.emit("workflow:completed",e,i),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=`
336
341
  You have created the following plan to fulfill the request:
337
342
  Summary: ${e.summary}
338
343
 
339
344
  Steps:
340
- ${e.steps.map(i=>`${i.number}. ${i.description}`).join(`
345
+ ${e.steps.map(a=>`${a.number}. ${a.description}`).join(`
341
346
  `)}
342
347
 
343
348
  Execute this plan now.
344
- `.trim(),n={...t,messages:[{role:"system",content:o},...t.messages]},a="";for await(let i of this.client.stream(n,r))i.delta&&(a+=i.delta),yield i;e.steps.forEach(i=>{i.status="completed",i.result={success:!0,output:a}}),e.status="completed",e.completedAt=new Date,this.emit("workflow:completed",e,{success:!0,plan:e,output:a,metrics:this.computeMetrics(e,e.startedAt.getTime(),0)})}waitForApproval(e){return new Promise(t=>{this.pendingApprovals.set(e,t)})}approvePlan(e){let t=this.pendingApprovals.get(e);t&&(t(!0),this.pendingApprovals.delete(e))}rejectPlan(e){let t=this.pendingApprovals.get(e);t&&(t(!1),this.pendingApprovals.delete(e))}};l();var Xs=require("events");k();var Zs=class s extends Xs.EventEmitter{client;activeProviderName;modeRegistry;workflowExecutor;customProviderNames=new Set;mcpToolProject=null;constructor(e,t,r){super(),this.client=e,this.activeProviderName=t,this.modeRegistry=r;let o=this.client.getProvider(t);o&&this.forwardEvents(o),this.workflowExecutor=new qo(this.client,Qr,this.client.getQueryClassifier()),this.forwardWorkflowEvents()}static async init(e){let t=po(e.configPath);fi(t.logging);let r=new Jt,o=Mt(e.configPath);if(r.setConfig(o),e.tools&&await r.loadBuiltIn(),e.customTools&&await r.loadProjects(e.customTools),e.knowledge&&typeof e.knowledge.toTool=="function")try{let x=e.knowledge.toTool(),S={manifest:{key:"knowledge",name:"knowledge",displayName:"Knowledge Base",version:"1.0.0",description:"RAG-powered knowledge base search",tools:["knowledge_search"],category:"search"},tools:[x]};await r.loadProjects([S]),v("[Knowledge] Registered knowledge_search tool")}catch(x){Y(`[Knowledge] Failed to register knowledge tool: ${x}`)}let n=null,a=e.mcp||t.mcp;if(a)try{v("[MCP] Initializing MCP tool integration");let x=await Jr(a);n=x,await r.loadProjects([x]),v(`[MCP] Loaded ${x.tools.length} tools from MCP servers`)}catch(x){Y(`[MCP] Failed to initialize MCP tools: ${x}`)}let i=t.systemPrompt,c=e.disableBaseContext||t.disableBaseContext||t.baseContext===!1||!1,p=t.modeOverrides||{},m={},u=new Set,g=e.defaultProvider||e.provider;if(e.providers)for(let[x,S]of Object.entries(e.providers)){let R=x===g,j=await s.createProvider(x,S,e.configPath,!R);j&&(m[x]=j)}else if(e.provider){let x={apiKey:e.apiKey,model:e.model},S=await s.createProvider(e.provider,x,e.configPath,!1);S&&(m[e.provider]=S)}else if(!e.customProviders)throw new Error('No provider specified. Pass { provider: "name" }, { providers: { ... } }, or { customProviders: { ... } } to init().');if(e.customProviders){let x=Array.isArray(e.customProviders)?e.customProviders:Object.entries(e.customProviders).map(([S,R])=>(R.name=R.name||S,R));for(let S of x){if(typeof S.generate!="function"||typeof S.stream!="function"||typeof S.embed!="function")throw new Error("Custom provider must implement the ProviderAdapter interface (generate, stream, embed methods). Import { ProviderAdapter } from 'toolpack' and implement or extend it.");let R=S.name;if(!R)throw new Error("Custom provider must have a 'name' property set. Set adapter.name in the constructor or use the record syntax: { 'provider-name': adapter }");if(m[R])throw new Error(`Custom provider name "${R}" conflicts with a built-in provider designation. Choose a different name.`);u.add(R),m[R]=S}}if(!g&&e.customProviders&&(g=(Array.isArray(e.customProviders)?e.customProviders[0]:Object.values(e.customProviders)[0])?.name),!g)throw new Error("No default provider specified.");let w=new zt;if(e.customModes)for(let x of e.customModes)w.register(x);let y={...p,...e.modeOverrides||{}};for(let[x,S]of Object.entries(y)){let R=w.get(x);if(R){S.systemPrompt!==void 0&&(R.systemPrompt=S.systemPrompt),S.toolSearch&&(R.toolSearch={...R.toolSearch||{},...S.toolSearch});for(let[j,U]of Object.entries(S))j!=="systemPrompt"&&j!=="toolSearch"&&(R[j]=U)}}let b=new eo({providers:m,defaultProvider:g,toolRegistry:r,toolsConfig:r.getConfig(),systemPrompt:i,disableBaseContext:c}),P=new s(b,g,w);P.customProviderNames=u,P.mcpToolProject=n;let $=e.defaultMode||Le,C=w.get($);return C&&(b.setMode(C),C.workflow&&P.workflowExecutor.setConfig(C.workflow)),P}static async createProvider(e,t,r,o=!1){if(["openai","anthropic","gemini"].includes(e)){let n=`TOOLPACK_${e.toUpperCase()}_KEY`,a=t.apiKey||process.env[n]||process.env[`${e.toUpperCase()}_API_KEY`];if(!a){if(o)return null;throw new Error(`No API key found for '${e}'. Set ${n} or pass apiKey in config.`)}switch(e){case"openai":return new ao(a,t.baseUrl);case"anthropic":return new oo(a,t.baseUrl);case"gemini":return new ro(a)}}if(e==="ollama")return new Ke({baseUrl:t.baseUrl||io(r)});if(e.startsWith("ollama-")){let n=t.model||e.replace(/^ollama-/,""),a=t.baseUrl||io(r);return new xe({model:n,baseUrl:a})}throw new Error(`Unknown provider type: ${e}`)}async generate(e,t){let r;typeof e=="string"?r={messages:[{role:"user",content:e}],model:""}:r=e;let o=this.getMode();if(o?.workflow?.planning?.enabled||o?.workflow?.steps?.enabled){let n=await this.workflowExecutor.execute(r,t||this.activeProviderName),a=0,i=0,c=0,p={steps:[]};n.plan.planningResponse?.usage&&(a+=n.plan.planningResponse.usage.prompt_tokens,i+=n.plan.planningResponse.usage.completion_tokens||0,c+=n.plan.planningResponse.usage.total_tokens,p.planning=n.plan.planningResponse.usage);for(let u of n.plan.steps)if(u.status==="completed"&&u.result?.response?.usage){let g=u.result.response.usage;a+=g.prompt_tokens,i+=g.completion_tokens||0,c+=g.total_tokens,p.steps.push({stepNumber:u.number,description:u.description,usage:g})}let m={prompt_tokens:a,completion_tokens:i,total_tokens:c};return n.response?{...n.response,content:n.output||n.response.content||null,usage:m,usage_details:p}:{content:n.output||null,usage:m,usage_details:p}}return this.client.generate(r,t)}async*stream(e,t){let r=this.getMode(),o=t||this.activeProviderName;if(r?.workflow?.planning?.enabled||r?.workflow?.steps?.enabled){yield*this.workflowExecutor.stream(e,o);return}yield*this.client.stream(e,t)}async embed(e,t){return this.client.embed(e,t)}setProvider(e){let t=this.client.getProvider(e);this.activeProviderName=e,this.client.setDefaultProvider(e),this.forwardEvents(t)}getProvider(){return this.client.getProvider(this.activeProviderName)}getClient(){return this.client}getWorkflowExecutor(){return this.workflowExecutor}async disconnect(){let e=this.getProvider();e&&"disconnect"in e&&await e.disconnect(),this.mcpToolProject&&await Hr(this.mcpToolProject)}async listProviders(){let e=this.client.getProviders(),t=[];for(let[r,o]of e.entries()){let n=this.customProviderNames.has(r),a=[];try{a=await o.getModels()}catch(i){E(`[Toolpack] Failed to fetch models for provider '${r}': ${i}`)}t.push({name:r,displayName:o.getDisplayName(),type:n?"custom":"built-in",models:a})}return t}async loadToolProject(e){let t=this.client.getToolRegistry();if(t)await t.loadProject(e);else throw new Error("No tool registry configured. Initialize Toolpack with tools enabled.")}async listModels(){let e=await this.listProviders(),t=[];for(let r of e)for(let o of r.models)t.push({...o,provider:r.name});return t}setMode(e){let t=this.modeRegistry.get(e);if(!t)throw new Error(`Mode "${e}" not found. Available modes: ${this.modeRegistry.getNames().join(", ")}`);return this.client.setMode(t),t.workflow?this.workflowExecutor.setConfig(t.workflow):this.workflowExecutor.setConfig(Qr),t}getMode(){return this.client.getMode()}getActiveModeName(){let e=this.client.getMode();return e?e.displayName:"Default"}getModes(){return this.modeRegistry.getAll()}cycleMode(){let e=this.client.getMode(),t=e?e.name:"default",r=this.modeRegistry.getNext(t);return this.client.setMode(r),r}registerMode(e){this.modeRegistry.register(e)}forwardEvents(e){e instanceof Xs.EventEmitter&&e.on("status",t=>this.emit("status",t))}forwardWorkflowEvents(){let e=this.workflowExecutor;e.on("workflow:plan_created",t=>this.emit("workflow:plan_created",t)),e.on("workflow:plan_decision",(t,r)=>this.emit("workflow:plan_decision",t,r)),e.on("workflow:started",t=>this.emit("workflow:started",t)),e.on("workflow:step_start",(t,r)=>this.emit("workflow:step_start",t,r)),e.on("workflow:step_complete",(t,r)=>this.emit("workflow:step_complete",t,r)),e.on("workflow:step_failed",(t,r,o)=>this.emit("workflow:step_failed",t,r,o)),e.on("workflow:step_retry",(t,r,o)=>this.emit("workflow:step_retry",t,r,o)),e.on("workflow:step_added",(t,r)=>this.emit("workflow:step_added",t,r)),e.on("workflow:progress",t=>this.emit("workflow:progress",t)),e.on("workflow:completed",(t,r)=>this.emit("workflow:completed",t,r)),e.on("workflow:failed",(t,r)=>this.emit("workflow:failed",t,r))}};l();var Wg=T(require("os"),1),qe=T(require("path"),1),Vt=T(require("fs"),1),ei=".toolpack",ti="config",oi="toolpack.config.json";function Gg(){return Wg.homedir()}function Bg(){return qe.join(Gg(),ei)}function ri(){return qe.join(Bg(),ti)}function Uo(){return qe.join(ri(),oi)}function Jg(s=process.cwd()){return qe.join(s,ei)}function ni(s=process.cwd()){return qe.join(Jg(s),ti)}function Wo(s=process.cwd()){return qe.join(ni(s),oi)}function si(){let s=ri();Vt.existsSync(s)||Vt.mkdirSync(s,{recursive:!0})}function Wy(s=process.cwd()){let e=ni(s);Vt.existsSync(e)||Vt.mkdirSync(e,{recursive:!0})}l();var z=T(require("fs"),1),Yr=T(require("path"),1);function ai(s,e){if(!e)return s;if(!s)return e;let t={...s};for(let r of Object.keys(e))e[r]instanceof Array?t[r]=e[r]:e[r]instanceof Object&&r in s?t[r]=ai(s[r],e[r]):t[r]=e[r];return t}function ii(s){if(!z.existsSync(s))return null;try{let e=z.readFileSync(s,"utf-8");return JSON.parse(e)}catch{return null}}function Gy(s=process.cwd()){let e=Yr.join(s,"toolpack.config.json"),t=Uo(),r=Wo(s),o=ii(e)||{},n=ii(t)||{},a=ii(r)||{},i=ai(o,n);return i=ai(i,a),i}function By(s=process.cwd()){let e=Yr.join(s,"toolpack.config.json"),t=Uo(),r=Wo(s),o=!z.existsSync(t),n=null,a="default";return z.existsSync(r)?(n=r,a="local"):z.existsSync(t)?(n=t,a="global"):z.existsSync(e)&&(n=e,a="base"),{isFirstRun:o,activeConfigPath:n,configSource:a}}function Jy(s=process.cwd()){let e=Uo();if(!z.existsSync(e)){si();let t=null,r=Wo(s);if(z.existsSync(r))t=r;else{let n=Yr.join(s,"toolpack.config.json");if(z.existsSync(n))t=n;else{let a=cn();a&&z.existsSync(a)&&(t=a)}}let o={};if(t)try{let n=z.readFileSync(t,"utf-8");o=JSON.parse(n)}catch{}z.writeFileSync(e,JSON.stringify(o,null,4),"utf-8")}}l();0&&(module.exports={AGENT_MODE,AGENT_PLANNING_PROMPT,AGENT_STEP_PROMPT,AGENT_WORKFLOW,AIClient,AnthropicAdapter,AuthenticationError,BM25SearchEngine,BUILT_IN_MODES,CHAT_MODE,CHAT_WORKFLOW,CODING_PLANNING_PROMPT,CODING_STEP_PROMPT,CODING_WORKFLOW,CONFIG_DIR_NAME,CONFIG_FILE_NAME,ConnectionError,DEFAULT_MODE_NAME,DEFAULT_TOOLS_CONFIG,DEFAULT_TOOL_SEARCH_CONFIG,DEFAULT_WORKFLOW,DEFAULT_WORKFLOW_CONFIG,GeminiAdapter,InvalidRequestError,McpClient,McpConnectionError,McpTimeoutError,McpToolManager,ModeRegistry,OllamaAdapter,OllamaProvider,OpenAIAdapter,PageError,Planner,ProviderAdapter,ProviderError,RateLimitError,SDKError,StepExecutor,TOOLPACK_DIR_NAME,TOOL_SEARCH_NAME,TimeoutError,ToolDiscoveryCache,ToolRegistry,ToolRouter,Toolpack,WorkflowExecutor,cloudDeployTool,cloudListTool,cloudStatusTool,cloudToolsProject,codingFindSymbolTool,codingGetImportsTool,codingGetSymbolsTool,codingToolsProject,createMcpToolProject,createMode,createToolProject,dbCountTool,dbDeleteTool,dbInsertTool,dbQueryTool,dbSchemaTool,dbTablesTool,dbToolsProject,dbUpdateTool,diffApplyTool,diffCreateTool,diffPreviewTool,diffToolsProject,disconnectMcpToolProject,ensureGlobalConfigDir,ensureLocalConfigDir,execKillTool,execListProcessesTool,execReadOutputTool,execRunBackgroundTool,execRunShellTool,execRunTool,execToolsProject,fetchUrlAsBase64,fsAppendFileTool,fsCopyTool,fsCreateDirTool,fsDeleteFileTool,fsExistsTool,fsListDirTool,fsMoveTool,fsReadFileRangeTool,fsReadFileTool,fsReplaceInFileTool,fsSearchTool,fsStatTool,fsToolsProject,fsTreeTool,fsWriteFileTool,generateToolCategoriesPrompt,getDefaultSlmModel,getGlobalConfigDir,getGlobalConfigPath,getGlobalToolpackDir,getLocalConfigDir,getLocalConfigPath,getLocalToolpackDir,getMimeType,getOllamaBaseUrl,getOllamaProviderEntries,getRegisteredSlmModels,getRuntimeConfigStatus,getToolSearchSchema,getToolpackConfig,getUserHomeDir,gitAddTool,gitBlameTool,gitBranchCreateTool,gitBranchListTool,gitCheckoutTool,gitCommitTool,gitDiffTool,gitLogTool,gitStatusTool,gitToolsProject,httpDeleteTool,httpDownloadTool,httpGetTool,httpPostTool,httpPutTool,httpToolsProject,initializeGlobalConfigIfFirstRun,isDataUri,isRegisteredSlm,isToolSearchTool,loadFullConfig,loadRuntimeConfig,loadToolsConfig,normalizeImagePart,ollamaRequest,ollamaStream,parseDataUri,readFileAsBase64,reloadToolpackConfig,saveToolsConfig,systemCwdTool,systemDiskUsageTool,systemEnvTool,systemInfoTool,systemSetEnvTool,systemToolsProject,toDataUri,toolSearchDefinition,webExtractLinksTool,webFetchTool,webScrapeTool,webSearchTool,webToolsProject});
349
+ `.trim(),s={...t,messages:[{role:"system",content:r},...t.messages]},i="";for await(let a of this.client.stream(s,o))a.delta&&(i+=a.delta),yield a;e.steps.forEach(a=>{a.status="completed",a.result={success:!0,output:i}}),e.status="completed",e.completedAt=new Date,this.emit("workflow:completed",e,{success:!0,plan:e,output:i,metrics:this.computeMetrics(e,e.startedAt.getTime(),0)})}waitForApproval(e){return new Promise(t=>{this.pendingApprovals.set(e,t)})}approvePlan(e){let t=this.pendingApprovals.get(e);t&&(t(!0),this.pendingApprovals.delete(e))}rejectPlan(e){let t=this.pendingApprovals.get(e);t&&(t(!1),this.pendingApprovals.delete(e))}};l();var hi=require("events");_();var yi=class n extends hi.EventEmitter{client;activeProviderName;modeRegistry;workflowExecutor;customProviderNames=new Set;mcpToolProject=null;constructor(e,t,o){super(),this.client=e,this.activeProviderName=t,this.modeRegistry=o;let r=this.client.getProvider(t);r&&this.forwardEvents(r),this.workflowExecutor=new Ko(this.client,fn,this.client.getQueryClassifier()),this.forwardWorkflowEvents()}static async init(e){let t=ho(e.configPath);Ni(t.logging);let o=new Yt,r=Ft(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 S=e.knowledge.toTool(),R={manifest:{key:"knowledge",name:"knowledge",displayName:"Knowledge Base",version:"1.0.0",description:"RAG-powered knowledge base search",tools:["knowledge_search"],category:"search"},tools:[S]};await o.loadProjects([R]),v("[Knowledge] Registered knowledge_search tool")}catch(S){Q(`[Knowledge] Failed to register knowledge tool: ${S}`)}let s=null,i=e.mcp||t.mcp;if(i)try{v("[MCP] Initializing MCP tool integration");let S=await pn(i);s=S,await o.loadProjects([S]),v(`[MCP] Loaded ${S.tools.length} tools from MCP servers`)}catch(S){Q(`[MCP] Failed to initialize MCP tools: ${S}`)}let a=t.systemPrompt,c=e.disableBaseContext||t.disableBaseContext||t.baseContext===!1||!1,p=t.modeOverrides||{},m={},u=new Set,g=e.defaultProvider||e.provider;if(e.providers)for(let[S,R]of Object.entries(e.providers)){let D=S===g,L=await n.createProvider(S,R,e.configPath,!D);L&&(m[S]=L)}else if(e.provider){let S={apiKey:e.apiKey,model:e.model},R=await n.createProvider(e.provider,S,e.configPath,!1);R&&(m[e.provider]=R)}else if(!e.customProviders)throw new Error('No provider specified. Pass { provider: "name" }, { providers: { ... } }, or { customProviders: { ... } } to init().');if(e.customProviders){let S=Array.isArray(e.customProviders)?e.customProviders:Object.entries(e.customProviders).map(([R,D])=>(D.name=D.name||R,D));for(let R of S){if(typeof R.generate!="function"||typeof R.stream!="function"||typeof R.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 D=R.name;if(!D)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[D])throw new Error(`Custom provider name "${D}" conflicts with a built-in provider designation. Choose a different name.`);u.add(D),m[D]=R}}if(!g&&e.customProviders&&(g=(Array.isArray(e.customProviders)?e.customProviders[0]:Object.values(e.customProviders)[0])?.name),!g)throw new Error("No default provider specified.");let w=new Xt;if(e.customModes)for(let S of e.customModes)w.register(S);let y={...p,...e.modeOverrides||{}};for(let[S,R]of Object.entries(y)){let D=w.get(S);if(D){R.systemPrompt!==void 0&&(D.systemPrompt=R.systemPrompt),R.toolSearch&&(D.toolSearch={...D.toolSearch||{},...R.toolSearch});for(let[L,j]of Object.entries(R))L!=="systemPrompt"&&L!=="toolSearch"&&(D[L]=j)}}let b=t.hitl||{};e.confirmationMode!==void 0&&(b.confirmationMode=e.confirmationMode),b.enabled===void 0&&e.onToolConfirm&&(b.enabled=!0),b.confirmationMode===void 0&&e.onToolConfirm&&(b.confirmationMode="all");let T=new so({providers:m,defaultProvider:g,toolRegistry:o,toolsConfig:o.getConfig(),systemPrompt:a,disableBaseContext:c,hitlConfig:Object.keys(b).length>0?b:void 0,onToolConfirm:e.onToolConfirm,conversationId:e.conversationId}),k=new n(T,g,w);k.customProviderNames=u,k.mcpToolProject=s;let C=e.defaultMode||Be,P=w.get(C);return P&&(T.setMode(P),P.workflow&&k.workflowExecutor.setConfig(P.workflow)),k}static async createProvider(e,t,o,r=!1){if(["openai","anthropic","gemini"].includes(e)){let s=`TOOLPACK_${e.toUpperCase()}_KEY`,i=t.apiKey||process.env[s]||process.env[`${e.toUpperCase()}_API_KEY`];if(!i){if(r)return null;throw new Error(`No API key found for '${e}'. Set ${s} or pass apiKey in config.`)}switch(e){case"openai":return new uo(i,t.baseUrl);case"anthropic":return new ao(i,t.baseUrl);case"gemini":return new lo(i)}}if(e==="ollama")return new Ze({baseUrl:t.baseUrl||mo(o)});if(e.startsWith("ollama-")){let s=t.model||e.replace(/^ollama-/,""),i=t.baseUrl||mo(o);return new ve({model:s,baseUrl:i})}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 s=await this.workflowExecutor.execute(o,t||this.activeProviderName),i=0,a=0,c=0,p={steps:[]};s.plan.planningResponse?.usage&&(i+=s.plan.planningResponse.usage.prompt_tokens,a+=s.plan.planningResponse.usage.completion_tokens||0,c+=s.plan.planningResponse.usage.total_tokens,p.planning=s.plan.planningResponse.usage);for(let u of s.plan.steps)if(u.status==="completed"&&u.result?.response?.usage){let g=u.result.response.usage;i+=g.prompt_tokens,a+=g.completion_tokens||0,c+=g.total_tokens,p.steps.push({stepNumber:u.number,description:u.description,usage:g})}let m={prompt_tokens:i,completion_tokens:a,total_tokens:c};return s.response?{...s.response,content:s.output||s.response.content||null,usage:m,usage_details:p}:{content:s.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}reloadConfig(e){let t=e||Fe();if(t)try{let o=po(t);o?.hitl&&this.client.updateHitlConfig(o.hitl)}catch(o){E(`[Toolpack] Failed to reload config from ${t}: ${o instanceof Error?o.message:String(o)}`)}}getWorkflowExecutor(){return this.workflowExecutor}async disconnect(){let e=this.getProvider();e&&"disconnect"in e&&await e.disconnect(),this.mcpToolProject&&await mn(this.mcpToolProject)}async listProviders(){let e=this.client.getProviders(),t=[];for(let[o,r]of e.entries()){let s=this.customProviderNames.has(o),i=[];try{i=await r.getModels()}catch(a){E(`[Toolpack] Failed to fetch models for provider '${o}': ${a}`)}t.push({name:o,displayName:r.getDisplayName(),type:s?"custom":"built-in",models:i})}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(fn),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 hi.EventEmitter&&e.on("status",t=>this.emit("status",t))}forwardWorkflowEvents(){let e=this.workflowExecutor;e.on("workflow:plan_created",t=>this.emit("workflow:plan_created",t)),e.on("workflow:plan_decision",(t,o)=>this.emit("workflow:plan_decision",t,o)),e.on("workflow:started",t=>this.emit("workflow:started",t)),e.on("workflow:step_start",(t,o)=>this.emit("workflow:step_start",t,o)),e.on("workflow:step_complete",(t,o)=>this.emit("workflow:step_complete",t,o)),e.on("workflow:step_failed",(t,o,r)=>this.emit("workflow:step_failed",t,o,r)),e.on("workflow:step_retry",(t,o,r)=>this.emit("workflow:step_retry",t,o,r)),e.on("workflow:step_added",(t,o)=>this.emit("workflow:step_added",t,o)),e.on("workflow:progress",t=>this.emit("workflow:progress",t)),e.on("workflow:completed",(t,o)=>this.emit("workflow:completed",t,o)),e.on("workflow:failed",(t,o)=>this.emit("workflow:failed",t,o))}};l();var mh=x(require("os"),1),Ke=x(require("path"),1),oo=x(require("fs"),1),wi=".toolpack",bi="config",xi="toolpack.config.json";function dh(){return mh.homedir()}function uh(){return Ke.join(dh(),wi)}function Ti(){return Ke.join(uh(),bi)}function Jo(){return Ke.join(Ti(),xi)}function fh(n=process.cwd()){return Ke.join(n,wi)}function Pi(n=process.cwd()){return Ke.join(fh(n),bi)}function Ho(n=process.cwd()){return Ke.join(Pi(n),xi)}function Ci(){let n=Ti();oo.existsSync(n)||oo.mkdirSync(n,{recursive:!0})}function mw(n=process.cwd()){let e=Pi(n);oo.existsSync(e)||oo.mkdirSync(e,{recursive:!0})}l();var z=x(require("fs"),1),gn=x(require("path"),1);function Si(n,e){if(!e)return n;if(!n)return e;let t={...n};for(let o of Object.keys(e))e[o]instanceof Array?t[o]=e[o]:e[o]instanceof Object&&o in n?t[o]=Si(n[o],e[o]):t[o]=e[o];return t}function vi(n){if(!z.existsSync(n))return null;try{let e=z.readFileSync(n,"utf-8");return JSON.parse(e)}catch{return null}}function dw(n=process.cwd()){let e=gn.join(n,"toolpack.config.json"),t=Jo(),o=Ho(n),r=vi(e)||{},s=vi(t)||{},i=vi(o)||{},a=Si(r,s);return a=Si(a,i),a}function uw(n=process.cwd()){let e=gn.join(n,"toolpack.config.json"),t=Jo(),o=Ho(n),r=!z.existsSync(t),s=null,i="default";return z.existsSync(o)?(s=o,i="local"):z.existsSync(t)?(s=t,i="global"):z.existsSync(e)&&(s=e,i="base"),{isFirstRun:r,activeConfigPath:s,configSource:i}}function fw(n=process.cwd()){let e=Jo();if(!z.existsSync(e)){Ci();let t=null,o=Ho(n);if(z.existsSync(o))t=o;else{let s=gn.join(n,"toolpack.config.json");if(z.existsSync(s))t=s;else{let i=Fe();i&&z.existsSync(i)&&(t=i)}}let r={};if(t)try{let s=z.readFileSync(t,"utf-8");r=JSON.parse(s)}catch{}z.writeFileSync(e,JSON.stringify(r,null,4),"utf-8")}}l();0&&(module.exports={AGENT_MODE,AGENT_PLANNING_PROMPT,AGENT_STEP_PROMPT,AGENT_WORKFLOW,AIClient,AnthropicAdapter,AuthenticationError,BM25SearchEngine,BUILT_IN_MODES,CHAT_MODE,CHAT_WORKFLOW,CODING_PLANNING_PROMPT,CODING_STEP_PROMPT,CODING_WORKFLOW,CONFIG_DIR_NAME,CONFIG_FILE_NAME,ConnectionError,DEFAULT_MODE_NAME,DEFAULT_TOOLS_CONFIG,DEFAULT_TOOL_SEARCH_CONFIG,DEFAULT_WORKFLOW,DEFAULT_WORKFLOW_CONFIG,GeminiAdapter,InvalidRequestError,McpClient,McpConnectionError,McpTimeoutError,McpToolManager,ModeRegistry,OllamaAdapter,OllamaProvider,OpenAIAdapter,PageError,Planner,ProviderAdapter,ProviderError,RateLimitError,SDKError,StepExecutor,TOOLPACK_DIR_NAME,TOOL_SEARCH_NAME,TimeoutError,ToolDiscoveryCache,ToolRegistry,ToolRouter,Toolpack,WorkflowExecutor,addBypassRule,cloudDeployTool,cloudListTool,cloudStatusTool,cloudToolsProject,codingFindSymbolTool,codingGetImportsTool,codingGetSymbolsTool,codingToolsProject,createMcpToolProject,createMode,createToolProject,dbCountTool,dbDeleteTool,dbInsertTool,dbQueryTool,dbSchemaTool,dbTablesTool,dbToolsProject,dbUpdateTool,diffApplyTool,diffCreateTool,diffPreviewTool,diffToolsProject,disconnectMcpToolProject,ensureGlobalConfigDir,ensureLocalConfigDir,execKillTool,execListProcessesTool,execReadOutputTool,execRunBackgroundTool,execRunShellTool,execRunTool,execToolsProject,fetchUrlAsBase64,fsAppendFileTool,fsCopyTool,fsCreateDirTool,fsDeleteFileTool,fsExistsTool,fsListDirTool,fsMoveTool,fsReadFileRangeTool,fsReadFileTool,fsReplaceInFileTool,fsSearchTool,fsStatTool,fsToolsProject,fsTreeTool,fsWriteFileTool,generateToolCategoriesPrompt,getDefaultSlmModel,getGlobalConfigDir,getGlobalConfigPath,getGlobalToolpackDir,getLocalConfigDir,getLocalConfigPath,getLocalToolpackDir,getMimeType,getOllamaBaseUrl,getOllamaProviderEntries,getRegisteredSlmModels,getRuntimeConfigStatus,getToolSearchSchema,getToolpackConfig,getUserHomeDir,gitAddTool,gitBlameTool,gitBranchCreateTool,gitBranchListTool,gitCheckoutTool,gitCommitTool,gitDiffTool,gitLogTool,gitStatusTool,gitToolsProject,httpDeleteTool,httpDownloadTool,httpGetTool,httpPostTool,httpPutTool,httpToolsProject,initializeGlobalConfigIfFirstRun,isDataUri,isRegisteredSlm,isToolSearchTool,k8sApplyManifestTool,k8sDeleteResourceTool,k8sDescribeTool,k8sGetConfigMapTool,k8sGetLogsTool,k8sGetNamespacesTool,k8sListDeploymentsTool,k8sListPodsTool,k8sListServicesTool,k8sSwitchContextTool,k8sToolsProject,k8sWaitForDeploymentTool,loadFullConfig,loadRuntimeConfig,loadToolsConfig,normalizeImagePart,ollamaRequest,ollamaStream,parseDataUri,readFileAsBase64,reloadToolpackConfig,removeBypassRule,saveToolsConfig,systemCwdTool,systemDiskUsageTool,systemEnvTool,systemInfoTool,systemSetEnvTool,systemToolsProject,toDataUri,toolSearchDefinition,webExtractLinksTool,webFetchTool,webScrapeTool,webSearchTool,webToolsProject});