toolpack-sdk 1.2.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/README.md +214 -9
- package/dist/index.cjs +166 -125
- package/dist/index.d.cts +444 -192
- package/dist/index.d.ts +444 -192
- package/dist/index.js +166 -125
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,47 +1,47 @@
|
|
|
1
|
-
var
|
|
2
|
-
`;Vf(_r,o)}function Q(s){ot("error",s)}function D(s){ot("warn",s)}function v(s){ot("info",s)}function y(s){ot("debug",s)}function ye(s){ot("trace",s)}function Zf(s){return s.replace(/\bsk-[A-Za-z0-9_-]{10,}\b/g,"[REDACTED]").replace(/\bsk-proj-[A-Za-z0-9_-]{10,}\b/g,"[REDACTED]").replace(/\bAIza[0-9A-Za-z_-]{10,}\b/g,"[REDACTED]").replace(/\bBearer\s+[A-Za-z0-9._-]{10,}\b/g,"Bearer [REDACTED]")}function E(s,e=200){try{let t=typeof s=="string"?s:JSON.stringify(s),o=Zf(t);return o.length<=e?o:`${o.slice(0,e)}\u2026`}catch{return"[Unserializable]"}}function V(s,e,t){Re("debug")&&(y(`[${e}][${s}] Messages (${t.length}):`),t.forEach((o,r)=>{y(`[${e}][${s}] #${r} role=${o?.role} content=${E(o?.content,300)}`)}))}var $r,oo,ro,_r,_=g(()=>{"use strict";l();$r={error:0,warn:1,info:2,debug:3,trace:4},oo=!1,ro="info",_r=Xf(process.cwd(),"toolpack-sdk.log")});var rt={};re(rt,{fetchUrlAsBase64:()=>Ps,getMimeType:()=>ws,isDataUri:()=>bs,normalizeImagePart:()=>ng,parseDataUri:()=>xs,readFileAsBase64:()=>Ts,toDataUri:()=>rg});import*as hs from"fs/promises";import*as ys from"path";function ws(s){let e=ys.extname(s).toLowerCase();return og[e]||"application/octet-stream"}function bs(s){return s.startsWith("data:")}function xs(s){let e=s.match(/^data:(.*?);base64,(.+)$/);return e?{mimeType:e[1],data:e[2]}:null}function rg(s,e){return`data:${e};base64,${s}`}async function Ts(s){try{return{data:(await hs.readFile(s)).toString("base64"),mimeType:ws(s)}}catch(e){throw new M(`Failed to read image file: ${s}`,e)}}async function Ps(s){try{let e=await fetch(s);if(!e.ok)throw new Error(`HTTP ${e.status} ${e.statusText}`);let t=await e.arrayBuffer(),o=Buffer.from(t),r=e.headers.get("content-type")||"application/octet-stream";return r=r.split(";")[0].trim(),{data:o.toString("base64"),mimeType:r}}catch(e){throw new F(`Failed to download image from URL: ${s}`,"FETCH_ERROR",500,e)}}async function ng(s){if(s.type==="image_data")return{data:s.image_data.data,mimeType:s.image_data.mimeType};if(s.type==="image_file")return await Ts(s.image_file.path);if(s.type==="image_url"){let e=s.image_url.url;if(bs(e)){let t=xs(e);if(!t)throw new M(`Malformed data URI provided in image_url: ${e.substring(0,50)}...`);return t}return await Ps(e)}throw new M(`Unknown ImagePart type: ${s.type}`)}var og,Le=g(()=>{"use strict";l();ce();og={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".heic":"image/heic",".heif":"image/heif"}});var _s,ks,Rs,Ds,Es,Ns=g(()=>{"use strict";l();_s="fs.read_file",ks="Read File",Rs="Read the contents of a file at the given path. Returns the file content as a string.",Ds="filesystem",Es={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path"]}});import*as qe from"fs";async function ug(s){let e=s.path,t=s.encoding||"utf-8";if(y(`[fs.read-file] execute path="${e}" encoding=${t}`),!e)throw new Error("path is required");if(!qe.existsSync(e))throw new Error(`File not found: ${e}`);if(qe.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);return qe.readFileSync(e,t)}var at,Ar=g(()=>{"use strict";l();Ns();_();at={name:_s,displayName:ks,description:Rs,parameters:Es,category:Ds,execute:ug}});var As,Ms,Os,Is,js,Fs=g(()=>{"use strict";l();As="fs.write_file",Ms="Write File",Os="Write content to a file. Creates parent directories if they do not exist. Overwrites existing files.",Is="filesystem",js={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to write"},content:{type:"string",description:"Content to write to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});import*as Ue from"fs";import*as Ls from"path";async function fg(s){let e=s.path,t=s.content,o=s.encoding||"utf-8";if(y(`[fs.write-file] execute path="${e}" encoding=${o} content_len=${t?.length??0}`),!e)throw new Error("path is required");if(t==null)throw new Error("content is required");let r=Ls.dirname(e);return Ue.existsSync(r)||Ue.mkdirSync(r,{recursive:!0}),Ue.writeFileSync(e,t,o),`File written successfully: ${e} (${Buffer.byteLength(t,o)} bytes)`}var lt,Mr=g(()=>{"use strict";l();Fs();_();lt={name:As,displayName:Ms,description:Os,parameters:js,category:Is,execute:fg}});var qs,Us,Ws,Gs,Bs,Js=g(()=>{"use strict";l();qs="fs.append_file",Us="Append File",Ws="Append content to the end of a file. Creates the file if it does not exist.",Gs="filesystem",Bs={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to append to"},content:{type:"string",description:"Content to append to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});import*as We from"fs";import*as Hs from"path";async function gg(s){let e=s.path,t=s.content,o=s.encoding||"utf-8";if(!e)throw new Error("path is required");if(t==null)throw new Error("content is required");let r=Hs.dirname(e);return We.existsSync(r)||We.mkdirSync(r,{recursive:!0}),We.appendFileSync(e,t,o),`Content appended to: ${e} (${Buffer.byteLength(t,o)} bytes appended)`}var ct,Or=g(()=>{"use strict";l();Js();ct={name:qs,displayName:Us,description:Ws,parameters:Bs,category:Gs,execute:gg}});var zs,Ks,Qs,Ys,Vs,Xs=g(()=>{"use strict";l();zs="fs.delete_file",Ks="Delete File",Qs="Delete a file at the given path. Does not delete directories.",Ys="filesystem",Vs={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to delete"}},required:["path"]}});import*as Ge from"fs";async function hg(s){let e=s.path;if(y(`[fs.delete-file] execute path="${e}"`),!e)throw new Error("path is required");if(!Ge.existsSync(e))throw new Error(`File not found: ${e}`);if(Ge.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}. Use a different tool to remove directories.`);return Ge.unlinkSync(e),`File deleted successfully: ${e}`}var pt,Ir=g(()=>{"use strict";l();Xs();_();pt={name:zs,displayName:Ks,description:Qs,parameters:Vs,category:Ys,execute:hg}});var Zs,ei,ti,oi,ri,ni=g(()=>{"use strict";l();Zs="fs.exists",ei="Exists",ti="Check if a file or directory exists at the given path. Returns true or false.",oi="filesystem",ri={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to check"}},required:["path"]}});import*as si from"fs";async function yg(s){let e=s.path;if(!e)throw new Error("path is required");let t=si.existsSync(e);return JSON.stringify({exists:t,path:e})}var mt,jr=g(()=>{"use strict";l();ni();mt={name:Zs,displayName:ei,description:ti,parameters:ri,category:oi,execute:yg}});var ii,ai,li,ci,pi,mi=g(()=>{"use strict";l();ii="fs.stat",ai="Stat",li="Get file or directory information including size, type, and modification date.",ci="filesystem",pi={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to get info for"}},required:["path"]}});import*as mo from"fs";async function wg(s){let e=s.path;if(!e)throw new Error("path is required");if(!mo.existsSync(e))throw new Error(`Path not found: ${e}`);let t=mo.statSync(e);return JSON.stringify({path:e,type:t.isDirectory()?"directory":t.isFile()?"file":"other",size:t.size,created:t.birthtime.toISOString(),modified:t.mtime.toISOString(),accessed:t.atime.toISOString(),permissions:t.mode.toString(8)})}var dt,Fr=g(()=>{"use strict";l();mi();dt={name:ii,displayName:ai,description:li,parameters:pi,category:ci,execute:wg}});var di,ui,fi,gi,hi,yi=g(()=>{"use strict";l();di="fs.list_dir",ui="List Directory",fi="List files and directories at the given path. Optionally recurse into subdirectories.",gi="filesystem",hi={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to list"},recursive:{type:"boolean",description:"Whether to list recursively (default: false)",default:!1}},required:["path"]}});import*as Ee from"fs";import*as wi from"path";function bi(s,e,t,o=""){let r=Ee.readdirSync(s,{withFileTypes:!0});for(let n of r){let a=wi.join(s,n.name),i=o?`${o}/${n.name}`:n.name;if(n.isDirectory())t.push({name:i,type:"directory",size:0}),e&&bi(a,!0,t,i);else if(n.isFile()){let c=Ee.statSync(a);t.push({name:i,type:"file",size:c.size})}}}async function bg(s){let e=s.path,t=s.recursive===!0;if(!e)throw new Error("path is required");if(!Ee.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Ee.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let r=[];return bi(e,t,r),JSON.stringify(r,null,2)}var ut,Lr=g(()=>{"use strict";l();yi();ut={name:di,displayName:ui,description:fi,parameters:hi,category:gi,execute:bg}});var xi,Ti,Pi,Ci,vi,Si=g(()=>{"use strict";l();xi="fs.create_dir",Ti="Create Directory",Pi="Create a directory at the given path. Creates parent directories recursively if they do not exist.",Ci="filesystem",vi={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to create"},recursive:{type:"boolean",description:"Create parent directories if they do not exist (default: true)",default:!0}},required:["path"]}});import*as Be from"fs";async function xg(s){let e=s.path,t=s.recursive!==!1;if(!e)throw new Error("path is required");if(Be.existsSync(e)){if(Be.statSync(e).isDirectory())return`Directory already exists: ${e}`;throw new Error(`Path exists but is not a directory: ${e}`)}return Be.mkdirSync(e,{recursive:t}),`Directory created: ${e}`}var ft,qr=g(()=>{"use strict";l();Si();ft={name:xi,displayName:Ti,description:Pi,parameters:vi,category:Ci,execute:xg}});var $i,_i,ki,Ri,Di,Ei=g(()=>{"use strict";l();$i="fs.move",_i="Move",ki="Move or rename a file or directory from one path to another.",Ri="filesystem",Di={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});import*as Ne from"fs";import*as Ni from"path";async function Tg(s){let e=s.path,t=s.new_path;if(!e)throw new Error("path is required");if(!t)throw new Error("new_path is required");if(!Ne.existsSync(e))throw new Error(`Source not found: ${e}`);let o=Ni.dirname(t);return Ne.existsSync(o)||Ne.mkdirSync(o,{recursive:!0}),Ne.renameSync(e,t),`Moved: ${e} \u2192 ${t}`}var gt,Ur=g(()=>{"use strict";l();Ei();gt={name:$i,displayName:_i,description:ki,parameters:Di,category:Ri,execute:Tg}});var Ai,Mi,Oi,Ii,ji,Fi=g(()=>{"use strict";l();Ai="fs.copy",Mi="Copy",Oi="Copy a file or directory from one path to another. Recursively copies directories.",Ii="filesystem",ji={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});import*as K from"fs";import*as ht from"path";function Li(s,e){if(K.statSync(s).isDirectory()){K.existsSync(e)||K.mkdirSync(e,{recursive:!0});let o=K.readdirSync(s);for(let r of o)Li(ht.join(s,r),ht.join(e,r))}else K.copyFileSync(s,e)}async function Pg(s){let e=s.path,t=s.new_path;if(!e)throw new Error("path is required");if(!t)throw new Error("new_path is required");if(!K.existsSync(e))throw new Error(`Source not found: ${e}`);let o=ht.dirname(t);return K.existsSync(o)||K.mkdirSync(o,{recursive:!0}),Li(e,t),`Copied ${K.statSync(e).isDirectory()?"directory":"file"}: ${e} \u2192 ${t}`}var yt,Wr=g(()=>{"use strict";l();Fi();yt={name:Ai,displayName:Mi,description:Oi,parameters:ji,category:Ii,execute:Pg}});var qi,Ui,Wi,Gi,Bi,Ji=g(()=>{"use strict";l();qi="fs.read_file_range",Ui="Read File Range",Wi="Read a specific range of lines from a file. Useful for reading portions of large files without loading the entire content.",Gi="filesystem",Bi={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},start_line:{type:"integer",description:"Start line number (1-indexed)"},end_line:{type:"integer",description:"End line number (1-indexed, inclusive)"}},required:["path","start_line","end_line"]}});import*as Je from"fs";async function Cg(s){let e=s.path,t=s.start_line,o=s.end_line;if(!e)throw new Error("path is required");if(t==null)throw new Error("start_line is required");if(o==null)throw new Error("end_line is required");if(t<1)throw new Error("start_line must be >= 1");if(o<t)throw new Error("end_line must be >= start_line");if(!Je.existsSync(e))throw new Error(`File not found: ${e}`);if(Je.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let a=Je.readFileSync(e,"utf-8").split(`
|
|
3
|
-
`),i
|
|
4
|
-
`);return`Lines ${c}-${p} of ${
|
|
5
|
-
${f}`}var
|
|
6
|
-
`);for(let
|
|
7
|
-
(results capped at ${r})`:"";return JSON.stringify(p,null,2)+m}var
|
|
8
|
-
`)}var
|
|
1
|
+
var fg=Object.defineProperty;var g=(n,e)=>()=>(n&&(e=n(n=0)),e);var se=(n,e)=>{for(var t in e)fg(n,t,{get:e[t],enumerable:!0})};import gg from"path";import{fileURLToPath as hg}from"url";var yg,wg,d,l=g(()=>{"use strict";yg=()=>hg(import.meta.url),wg=()=>gg.dirname(yg()),d=wg()});var G,we,be,j,U,Ne,Ss,ks,ae=g(()=>{"use strict";l();G=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},we=class extends G{constructor(e,t){super(e,"AUTHENTICATION_ERROR",401,t),this.name="AuthenticationError"}},be=class extends G{constructor(t,o,r){super(t,"RATE_LIMIT_ERROR",429,r);this.retryAfter=o;this.name="RateLimitError"}retryAfter},j=class extends G{constructor(e,t){super(e,"INVALID_REQUEST_ERROR",400,t),this.name="InvalidRequestError"}},U=class extends G{constructor(e,t="PROVIDER_ERROR",o=500,r){super(e,t,o,r),this.name="ProviderError"}},Ne=class extends G{constructor(e,t){super(e,"CONNECTION_ERROR",503,t),this.name="ConnectionError"}},Ss=class extends G{constructor(t,o,r){super(t,"PAGE_ERROR",502,r);this.pageUrl=o;this.name="PageError"}pageUrl},ks=class extends G{constructor(t,o,r){super(t,"TIMEOUT_ERROR",504,r);this.phase=o;this.name="TimeoutError"}phase}});var Tg,z,lt=g(()=>{"use strict";l();Tg={enabled:!1,alwaysLoadedTools:[],alwaysLoadedCategories:[],searchResultLimit:5,cacheDiscoveredTools:!0},z={enabled:!0,autoExecute:!0,maxToolRounds:5,toolChoicePolicy:"auto",resultMaxChars:2e4,enabledTools:[],enabledToolCategories:[],toolSearch:Tg}});import{appendFileSync as Pg}from"fs";import{join as Cg}from"path";function _s(n){if(!n)return;let e=n.toLowerCase();if(e in Nr)return e;console.warn(`[Toolpack Warning] Invalid log level "${n}". Falling back to "info".`)}function Rs(n){n?.enabled!==void 0&&(lo=n.enabled),n?.filePath&&(Ar=n.filePath),n?.level&&(co=_s(n.level)||"info"),process.env.TOOLPACK_SDK_LOG_ENABLED!==void 0&&(lo=process.env.TOOLPACK_SDK_LOG_ENABLED==="true"),process.env.TOOLPACK_SDK_LOG_FILE&&(Ar=process.env.TOOLPACK_SDK_LOG_FILE,lo=!0),process.env.TOOLPACK_SDK_LOG_LEVEL&&(co=_s(process.env.TOOLPACK_SDK_LOG_LEVEL)||co)}function Me(n){return lo?Nr[n]<=Nr[co]:!1}function ct(n,e){if(!Me(n))return;let o=`[${new Date().toISOString()}] [${n.toUpperCase()}] ${e}
|
|
2
|
+
`;Pg(Ar,o)}function Q(n){ct("error",n)}function E(n){ct("warn",n)}function v(n){ct("info",n)}function y(n){ct("debug",n)}function xe(n){ct("trace",n)}function vg(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=vg(t);return o.length<=e?o:`${o.slice(0,e)}\u2026`}catch{return"[Unserializable]"}}function Z(n,e,t){Me("debug")&&(y(`[${e}][${n}] Messages (${t.length}):`),t.forEach((o,r)=>{y(`[${e}][${n}] #${r} role=${o?.role} content=${A(o?.content,300)}`)}))}var Nr,lo,co,Ar,_=g(()=>{"use strict";l();Nr={error:0,warn:1,info:2,debug:3,trace:4},lo=!1,co="info",Ar=Cg(process.cwd(),"toolpack-sdk.log")});var pt={};se(pt,{fetchUrlAsBase64:()=>Ws,getMimeType:()=>Ls,isDataUri:()=>Fs,normalizeImagePart:()=>Rg,parseDataUri:()=>qs,readFileAsBase64:()=>Us,toDataUri:()=>_g});import*as Is from"fs/promises";import*as js from"path";function Ls(n){let e=js.extname(n).toLowerCase();return $g[e]||"application/octet-stream"}function Fs(n){return n.startsWith("data:")}function qs(n){let e=n.match(/^data:(.*?);base64,(.+)$/);return e?{mimeType:e[1],data:e[2]}:null}function _g(n,e){return`data:${e};base64,${n}`}async function Us(n){try{return{data:(await Is.readFile(n)).toString("base64"),mimeType:Ls(n)}}catch(e){throw new j(`Failed to read image file: ${n}`,e)}}async function Ws(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 U(`Failed to download image from URL: ${n}`,"FETCH_ERROR",500,e)}}async function Rg(n){if(n.type==="image_data")return{data:n.image_data.data,mimeType:n.image_data.mimeType};if(n.type==="image_file")return await Us(n.image_file.path);if(n.type==="image_url"){let e=n.image_url.url;if(Fs(e)){let t=qs(e);if(!t)throw new j(`Malformed data URI provided in image_url: ${e.substring(0,50)}...`);return t}return await Ws(e)}throw new j(`Unknown ImagePart type: ${n.type}`)}var $g,Je=g(()=>{"use strict";l();ae();$g={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".heic":"image/heic",".heif":"image/heif"}});var zs,Qs,Ys,Vs,Xs,Zs=g(()=>{"use strict";l();zs="fs.read_file",Qs="Read File",Ys="Read the contents of a file at the given path. Returns the file content as a string.",Vs="filesystem",Xs={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path"]}});import*as He from"fs";async function jg(n){let e=n.path,t=n.encoding||"utf-8";if(y(`[fs.read-file] execute path="${e}" encoding=${t}`),!e)throw new Error("path is required");if(!He.existsSync(e))throw new Error(`File not found: ${e}`);if(He.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);return He.readFileSync(e,t)}var ft,qr=g(()=>{"use strict";l();Zs();_();ft={name:zs,displayName:Qs,description:Ys,parameters:Xs,category:Vs,execute:jg}});var ei,ti,oi,ri,ni,si=g(()=>{"use strict";l();ei="fs.write_file",ti="Write File",oi="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.",ri="filesystem",ni={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to write"},content:{type:"string",description:"Content to write to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});import*as ze from"fs";import*as ii from"path";async function Lg(n){let e=n.path,t=n.content,o=n.encoding||"utf-8";if(y(`[fs.write-file] execute path="${e}" encoding=${o} content_len=${t?.length??0}`),!e)throw new Error("path is required");if(t==null)throw new Error("content is required");let r=ii.dirname(e);return ze.existsSync(r)||ze.mkdirSync(r,{recursive:!0}),ze.writeFileSync(e,t,o),`File written successfully: ${e} (${Buffer.byteLength(t,o)} bytes)`}var gt,Ur=g(()=>{"use strict";l();si();_();gt={name:ei,displayName:ti,description:oi,parameters:ni,category:ri,execute:Lg,confirmation:{level:"high",reason:"This will overwrite the entire file contents.",showArgs:["path"]}}});var ai,li,ci,pi,mi,di=g(()=>{"use strict";l();ai="fs.append_file",li="Append File",ci="Append content to the end of a file. Creates the file if it does not exist.",pi="filesystem",mi={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to append to"},content:{type:"string",description:"Content to append to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});import*as Qe from"fs";import*as ui from"path";async function Fg(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=ui.dirname(e);return Qe.existsSync(r)||Qe.mkdirSync(r,{recursive:!0}),Qe.appendFileSync(e,t,o),`Content appended to: ${e} (${Buffer.byteLength(t,o)} bytes appended)`}var ht,Wr=g(()=>{"use strict";l();di();ht={name:ai,displayName:li,description:ci,parameters:mi,category:pi,execute:Fg,confirmation:{level:"medium",reason:"This will modify the file by appending content.",showArgs:["path"]}}});var fi,gi,hi,yi,wi,bi=g(()=>{"use strict";l();fi="fs.delete_file",gi="Delete File",hi="Remove/delete a file from the filesystem. Does not delete directories.",yi="filesystem",wi={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to delete"}},required:["path"]}});import*as Ye from"fs";async function qg(n){let e=n.path;if(y(`[fs.delete-file] execute path="${e}"`),!e)throw new Error("path is required");if(!Ye.existsSync(e))throw new Error(`File not found: ${e}`);if(Ye.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}. Use a different tool to remove directories.`);return Ye.unlinkSync(e),`File deleted successfully: ${e}`}var yt,Gr=g(()=>{"use strict";l();bi();_();yt={name:fi,displayName:gi,description:hi,parameters:wi,category:yi,execute:qg,confirmation:{level:"high",reason:"This will permanently delete the file. This action cannot be undone.",showArgs:["path"]}}});var xi,Ti,Pi,Ci,vi,Si=g(()=>{"use strict";l();xi="fs.exists",Ti="Exists",Pi="Check if a file or directory exists at the given path. Returns true or false.",Ci="filesystem",vi={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to check"}},required:["path"]}});import*as ki from"fs";async function Ug(n){let e=n.path;if(!e)throw new Error("path is required");let t=ki.existsSync(e);return JSON.stringify({exists:t,path:e})}var wt,Br=g(()=>{"use strict";l();Si();wt={name:xi,displayName:Ti,description:Pi,parameters:vi,category:Ci,execute:Ug}});var $i,_i,Ri,Di,Ei,Ni=g(()=>{"use strict";l();$i="fs.stat",_i="Stat",Ri="Get file or directory information including size, type, and modification date.",Di="filesystem",Ei={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to get info for"}},required:["path"]}});import*as wo from"fs";async function Wg(n){let e=n.path;if(!e)throw new Error("path is required");if(!wo.existsSync(e))throw new Error(`Path not found: ${e}`);let t=wo.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 bt,Kr=g(()=>{"use strict";l();Ni();bt={name:$i,displayName:_i,description:Ri,parameters:Ei,category:Di,execute:Wg}});var Ai,Mi,Oi,Ii,ji,Li=g(()=>{"use strict";l();Ai="fs.list_dir",Mi="List Directory",Oi="List files and directories at the given path. Optionally recurse into subdirectories.",Ii="filesystem",ji={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to list"},recursive:{type:"boolean",description:"Whether to list recursively (default: false)",default:!1}},required:["path"]}});import*as je from"fs";import*as Fi from"path";function qi(n,e,t,o=""){let r=je.readdirSync(n,{withFileTypes:!0});for(let s of r){let i=Fi.join(n,s.name),a=o?`${o}/${s.name}`:s.name;if(s.isDirectory())t.push({name:a,type:"directory",size:0}),e&&qi(i,!0,t,a);else if(s.isFile()){let c=je.statSync(i);t.push({name:a,type:"file",size:c.size})}}}async function Gg(n){let e=n.path,t=n.recursive===!0;if(!e)throw new Error("path is required");if(!je.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!je.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let r=[];return qi(e,t,r),JSON.stringify(r,null,2)}var xt,Jr=g(()=>{"use strict";l();Li();xt={name:Ai,displayName:Mi,description:Oi,parameters:ji,category:Ii,execute:Gg}});var Ui,Wi,Gi,Bi,Ki,Ji=g(()=>{"use strict";l();Ui="fs.create_dir",Wi="Create Directory",Gi="Create a directory at the given path. Creates parent directories recursively if they do not exist.",Bi="filesystem",Ki={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to create"},recursive:{type:"boolean",description:"Create parent directories if they do not exist (default: true)",default:!0}},required:["path"]}});import*as Ve from"fs";async function Bg(n){let e=n.path,t=n.recursive!==!1;if(!e)throw new Error("path is required");if(Ve.existsSync(e)){if(Ve.statSync(e).isDirectory())return`Directory already exists: ${e}`;throw new Error(`Path exists but is not a directory: ${e}`)}return Ve.mkdirSync(e,{recursive:t}),`Directory created: ${e}`}var Tt,Hr=g(()=>{"use strict";l();Ji();Tt={name:Ui,displayName:Wi,description:Gi,parameters:Ki,category:Bi,execute:Bg}});var Hi,zi,Qi,Yi,Vi,Xi=g(()=>{"use strict";l();Hi="fs.move",zi="Move",Qi="Move or rename a file or directory from one path to another.",Yi="filesystem",Vi={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});import*as Le from"fs";import*as Zi from"path";async function Kg(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(!Le.existsSync(e))throw new Error(`Source not found: ${e}`);let o=Zi.dirname(t);return Le.existsSync(o)||Le.mkdirSync(o,{recursive:!0}),Le.renameSync(e,t),`Moved: ${e} \u2192 ${t}`}var Pt,zr=g(()=>{"use strict";l();Xi();Pt={name:Hi,displayName:zi,description:Qi,parameters:Vi,category:Yi,execute:Kg,confirmation:{level:"high",reason:"This will move/rename the file or directory, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var ea,ta,oa,ra,na,sa=g(()=>{"use strict";l();ea="fs.copy",ta="Copy",oa="Copy a file or directory from one path to another. Recursively copies directories.",ra="filesystem",na={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});import*as Y from"fs";import*as Ct from"path";function ia(n,e){if(Y.statSync(n).isDirectory()){Y.existsSync(e)||Y.mkdirSync(e,{recursive:!0});let o=Y.readdirSync(n);for(let r of o)ia(Ct.join(n,r),Ct.join(e,r))}else Y.copyFileSync(n,e)}async function Jg(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(!Y.existsSync(e))throw new Error(`Source not found: ${e}`);let o=Ct.dirname(t);return Y.existsSync(o)||Y.mkdirSync(o,{recursive:!0}),ia(e,t),`Copied ${Y.statSync(e).isDirectory()?"directory":"file"}: ${e} \u2192 ${t}`}var vt,Qr=g(()=>{"use strict";l();sa();vt={name:ea,displayName:ta,description:oa,parameters:na,category:ra,execute:Jg,confirmation:{level:"medium",reason:"This will copy files or directories, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var aa,la,ca,pa,ma,da=g(()=>{"use strict";l();aa="fs.read_file_range",la="Read File Range",ca="Read a specific range of lines from a file. Useful for reading portions of large files without loading the entire content.",pa="filesystem",ma={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},start_line:{type:"integer",description:"Start line number (1-indexed)"},end_line:{type:"integer",description:"End line number (1-indexed, inclusive)"}},required:["path","start_line","end_line"]}});import*as Xe from"fs";async function Hg(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(!Xe.existsSync(e))throw new Error(`File not found: ${e}`);if(Xe.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let i=Xe.readFileSync(e,"utf-8").split(`
|
|
3
|
+
`),a=i.length,c=Math.min(t,a),p=Math.min(o,a),f=i.slice(c-1,p).map((h,b)=>`${c+b}: ${h}`).join(`
|
|
4
|
+
`);return`Lines ${c}-${p} of ${a} total:
|
|
5
|
+
${f}`}var St,Yr=g(()=>{"use strict";l();da();St={name:aa,displayName:la,description:ca,parameters:ma,category:pa,execute:Hg}});var ua,fa,ga,ha,ya,wa=g(()=>{"use strict";l();ua="fs.search",fa="Search",ga="Search for text in files within a directory. Returns matching lines with file paths and line numbers.",ha="filesystem",ya={type:"object",properties:{path:{type:"string",description:"Directory path to search in"},query:{type:"string",description:"Text or pattern to search for"},recursive:{type:"boolean",description:"Search recursively in subdirectories (default: true)",default:!0},max_results:{type:"integer",description:"Maximum number of matching lines to return (default: 50)",default:50},regex:{type:"boolean",description:"Treat query as a regular expression (default: false)",default:!1},case_sensitive:{type:"boolean",description:"Perform case-sensitive search. If false, search is case-insensitive (default: false)",default:!1}},required:["path","query"]}});import*as Pe from"fs";import*as ba from"path";function zg(n,e,t,o){try{let s=Pe.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 xa(n,e,t,o,r){let s=Pe.readdirSync(n,{withFileTypes:!0});for(let i of s){if(o.length>=r)break;let a=ba.join(n,i.name);i.isDirectory()&&t?xa(a,e,!0,o,r):i.isFile()&&zg(a,e,o,r)}}async function Qg(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(y(`[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 f=t;s||(f=f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));let h=i?"":"i";a=new RegExp(f,h)}if(!Pe.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Pe.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let p=[];if(xa(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 kt,Vr=g(()=>{"use strict";l();wa();_();kt={name:ua,displayName:fa,description:ga,parameters:ya,category:ha,execute:Qg}});var Ta,Pa,Ca,va,Sa,ka=g(()=>{"use strict";l();Ta="fs.replace_in_file",Pa="Replace In File",Ca="Find and replace text in a file. Returns the number of replacements made.",va="filesystem",Sa={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path"},search:{type:"string",description:"Text to search for"},replace:{type:"string",description:"Text to replace with"}},required:["path","search","replace"]}});import*as Ce from"fs";async function Yg(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(!Ce.existsSync(e))throw new Error(`File not found: ${e}`);if(Ce.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let s=Ce.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 Ce.writeFileSync(e,c,"utf-8"),`Replaced ${i} occurrence(s) in ${e}`}var $t,Xr=g(()=>{"use strict";l();ka();$t={name:Ta,displayName:Pa,description:Ca,parameters:Sa,category:va,execute:Yg,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 $a,_a,Ra,Da,Ea,Na=g(()=>{"use strict";l();$a="fs.tree",_a="Tree",Ra="Get a tree representation of a directory structure. Useful for understanding project layout at a glance.",Da="filesystem",Ea={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path"},depth:{type:"integer",description:"Maximum depth to traverse (default: 3)",default:3}},required:["path"]}});import*as Ze from"fs";import*as bo from"path";function Aa(n,e,t,o,r){if(t>o)return;let i=Ze.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 ",f=p?" ":"\u2502 ";c.isDirectory()?(r.push(`${e}${m}${c.name}/`),Aa(bo.join(n,c.name),e+f,t+1,o,r)):r.push(`${e}${m}${c.name}`)}}async function Vg(n){let e=n.path,t=n.depth||3;if(!e)throw new Error("path is required");if(!Ze.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Ze.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let s=[`${bo.basename(e)}/`];return Aa(e,"",1,t,s),s.join(`
|
|
8
|
+
`)}var _t,Zr=g(()=>{"use strict";l();Na();_t={name:$a,displayName:_a,description:Ra,parameters:Ea,category:Da,execute:Vg}});var Ma,Oa,Ia,ja,La,Fa=g(()=>{"use strict";l();Ma="fs.glob",Oa="Glob Pattern Match",Ia='Find files matching glob patterns (e.g., "**/*.ts", "src/**/*.test.js")',ja="filesystem",La={type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files (e.g., "**/*.ts", "src/**/*.json")'},cwd:{type:"string",description:"Root directory to search from (defaults to current working directory)"},ignore:{type:"array",items:{type:"string"},description:'Patterns to ignore (e.g., ["node_modules/**", "dist/**"])'},onlyFiles:{type:"boolean",description:"Return only files, not directories (default: true)"},onlyDirectories:{type:"boolean",description:"Return only directories, not files (default: false)"},absolute:{type:"boolean",description:"Return absolute paths instead of relative (default: false)"}},required:["pattern"]}});import Xg from"fast-glob";async function Zg(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 Xg(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 xo,en=g(()=>{"use strict";l();Fa();xo={name:Ma,displayName:Oa,description:Ia,parameters:La,category:ja,execute:Zg}});var qa,Ua,Wa,Ga,Ba,Ka=g(()=>{"use strict";l();qa="fs.delete_dir",Ua="Delete Directory",Wa="Delete a directory and all its contents recursively",Ga="filesystem",Ba={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to the directory to delete"},force:{type:"boolean",description:"Force deletion even if directory is not empty (default: true)"}},required:["path"]}});import{rm as eh}from"fs/promises";import{existsSync as th,statSync as oh}from"fs";async function rh(n){let e=n.path,t=n.force!==!1;if(!e)throw new Error("path is required");if(!th(e))throw new Error(`Directory does not exist: ${e}`);if(!oh(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);try{return await eh(e,{recursive:!0,force:t}),`Directory deleted successfully: ${e}`}catch(r){throw new Error(`Failed to delete directory "${e}": ${r.message}`)}}var To,tn=g(()=>{"use strict";l();Ka();To={name:qa,displayName:Ua,description:Wa,parameters:Ba,category:Ga,execute:rh,confirmation:{level:"high",reason:"This will recursively delete the directory and all its contents. This action cannot be undone.",showArgs:["path"]}}});var Ja,Ha,za,Qa,Ya,Va=g(()=>{"use strict";l();Ja="fs.batch_read",Ha="Batch Read Files",za="Read multiple files efficiently in one operation. Returns content for each file or error if read fails.",Qa="filesystem",Ya={type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Array of file paths to read"},encoding:{type:"string",description:"File encoding (default: utf-8)"},continueOnError:{type:"boolean",description:"Continue reading other files if one fails (default: true)"}},required:["paths"]}});import{readFile as nh}from"fs/promises";async function sh(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 nh(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 Po,on=g(()=>{"use strict";l();Va();Po={name:Ja,displayName:Ha,description:za,parameters:Ya,category:Qa,execute:sh}});var Xa,Za,el,tl,ol,rl=g(()=>{"use strict";l();Xa="fs.batch_write",Za="Batch Write Files",el="Write multiple files atomically in one operation. If atomic mode is enabled, all writes succeed or all are rolled back on failure.",tl="filesystem",ol={type:"object",properties:{files:{type:"array",items:{type:"object",properties:{path:{type:"string"},content:{type:"string"}}},description:"Array of files to write, each with path and content"},encoding:{type:"string",description:"File encoding (default: utf-8)"},atomic:{type:"boolean",description:"Atomic mode: rollback all writes if any fails (default: true)"},createDirs:{type:"boolean",description:"Create parent directories if they don't exist (default: true)"}},required:["files"]}});import{writeFile as nl,mkdir as ih,readFile as ah,unlink as lh}from"fs/promises";import{dirname as ch,resolve as ph}from"path";import{existsSync as sl}from"fs";async function mh(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=ph(a.path);if(o){let p=sl(c),m={path:c,existed:p};p&&(m.originalContent=await ah(c,t)),s.push(m)}if(r){let p=ch(c);await ih(p,{recursive:!0})}await nl(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 nl(c.path,c.originalContent,t):!c.existed&&sl(c.path)&&await lh(c.path)}catch{}throw new Error(`Batch write failed and rolled back: ${a.message}`)}throw new Error(`Batch write failed: ${a.message}`)}}var Co,rn=g(()=>{"use strict";l();rl();Co={name:Xa,displayName:Za,description:el,parameters:ol,category:tl,execute:mh,confirmation:{level:"high",reason:"This will overwrite multiple files at once.",showArgs:["files"]}}});var al={};se(al,{fsAppendFileTool:()=>ht,fsBatchReadTool:()=>Po,fsBatchWriteTool:()=>Co,fsCopyTool:()=>vt,fsCreateDirTool:()=>Tt,fsDeleteDirTool:()=>To,fsDeleteFileTool:()=>yt,fsExistsTool:()=>wt,fsGlobTool:()=>xo,fsListDirTool:()=>xt,fsMoveTool:()=>Pt,fsReadFileRangeTool:()=>St,fsReadFileTool:()=>ft,fsReplaceInFileTool:()=>$t,fsSearchTool:()=>kt,fsStatTool:()=>bt,fsToolsProject:()=>il,fsTreeTool:()=>_t,fsWriteFileTool:()=>gt});var il,nn=g(()=>{"use strict";l();qr();Ur();Wr();Gr();Br();Kr();Jr();Hr();zr();Qr();Yr();Vr();Xr();Zr();en();tn();on();rn();qr();Ur();Wr();Gr();Br();Kr();Jr();Hr();zr();Qr();Yr();Vr();Xr();Zr();en();tn();on();rn();il={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:[ft,gt,ht,yt,wt,bt,xt,Tt,Pt,vt,St,kt,$t,_t,xo,To,Po,Co],dependencies:{"fast-glob":"^3.3.2"}}});var ll,cl,pl,ml,dl,ul=g(()=>{"use strict";l();ll="exec.run",cl="Run",pl="Execute a command directly (without shell) and return its output. Use exec.run_shell for pipes, redirects, or shell features.",ml="execution",dl={type:"object",properties:{command:{type:"string",description:"The command to execute"},cwd:{type:"string",description:"Working directory for the command (optional)"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["command"]}});import{execSync as dh}from"child_process";async function uh(n){let e=n.command,t=n.cwd,o=n.timeout||3e4;if(!e)throw new Error("command is required");y(`[exec.run] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${o}ms`);try{return dh(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
|
-
${
|
|
10
|
+
${s}
|
|
11
11
|
STDERR:
|
|
12
|
-
${
|
|
12
|
+
${i}`}}var Rt,sn=g(()=>{"use strict";l();ul();_();Rt={name:ll,displayName:cl,description:pl,parameters:dl,category:ml,execute:uh,confirmation:{level:"high",reason:"This will execute a shell command on the host system.",showArgs:["command"]}}});var fl,gl,hl,yl,wl,bl=g(()=>{"use strict";l();fl="exec.run_shell",gl="Run Shell",hl="Execute a command through the system shell. Supports pipes, redirects, environment variable expansion, and other shell features.",yl="execution",wl={type:"object",properties:{command:{type:"string",description:"The shell command to execute (supports pipes, redirects, etc.)"},cwd:{type:"string",description:"Working directory for the command (optional)"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["command"]}});import{execSync as fh}from"child_process";function gh(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function hh(n){let e=n.command,t=n.cwd,o=n.timeout||3e4;if(!e)throw new Error("command is required");y(`[exec.run-shell] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${o}ms`);try{return fh(e,{cwd:t,timeout:o,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],shell:gh()})||"(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
|
-
${
|
|
14
|
+
${s}
|
|
15
15
|
STDERR:
|
|
16
|
-
${
|
|
17
|
-
`);if(
|
|
18
|
-
${r.substring(0,
|
|
16
|
+
${i}`}}var Dt,an=g(()=>{"use strict";l();bl();_();Dt={name:fl,displayName:gl,description:hl,parameters:wl,category:yl,execute:hh,confirmation:{level:"high",reason:"This will execute a shell command with explicit shell context.",showArgs:["command"]}}});function xl(n,e,t){let o=`proc_${yh++}`,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",()=>{}),vo.set(o,r),o}function So(n){return vo.get(n)}function Tl(n){let e=vo.get(n);if(!e)return!1;let t=e.process.exitCode===null;return t&&e.process.kill("SIGTERM"),t}function Pl(){return Array.from(vo.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 vo,yh,Et=g(()=>{"use strict";l();vo=new Map,yh=1});var Cl,vl,Sl,kl,$l,_l=g(()=>{"use strict";l();Cl="exec.run_background",vl="Run Background",Sl="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.",kl="execution",$l={type:"object",properties:{command:{type:"string",description:"The command to run in the background"},cwd:{type:"string",description:"Working directory for the command (optional)"}},required:["command"]}});import{spawn as wh}from"child_process";async function bh(n){let e=n.command,t=n.cwd;if(!e)throw new Error("command is required");if(y(`[exec.run-background] execute command="${e.substring(0,100)}" cwd=${t??"default"}`),!e)throw new Error("command is required");let o=wh(e,[],{cwd:t,shell:!0,stdio:["ignore","pipe","pipe"],detached:!1}),r=xl(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 Nt,ln=g(()=>{"use strict";l();Et();_l();_();Nt={name:Cl,displayName:vl,description:Sl,parameters:$l,category:kl,execute:bh,confirmation:{level:"high",reason:"This will spawn a background process that runs unsupervised.",showArgs:["command"]}}});var Rl,Dl,El,Nl,Al,Ml=g(()=>{"use strict";l();Rl="exec.read_output",Dl="Read Output",El="Read stdout and stderr from a background process started with exec.run_background.",Nl="execution",Al={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function xh(n){let e=n.process_id;if(!e)throw new Error("process_id is required");let t=So(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 At,cn=g(()=>{"use strict";l();Et();Ml();At={name:Rl,displayName:Dl,description:El,parameters:Al,category:Nl,execute:xh}});var Ol,Il,jl,Ll,Fl,ql=g(()=>{"use strict";l();Ol="exec.kill",Il="Kill",jl="Kill a background process started with exec.run_background.",Ll="execution",Fl={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function Th(n){let e=n.process_id;if(!e)throw new Error("process_id is required");let t=So(e);if(!t)throw new Error(`Process not found: ${e}`);return Tl(e)?`Process ${e} (${t.command}) killed successfully.`:`Process ${e} (${t.command}) was already terminated (exit code: ${t.process.exitCode}).`}var Mt,pn=g(()=>{"use strict";l();Et();ql();Mt={name:Ol,displayName:Il,description:jl,parameters:Fl,category:Ll,execute:Th,confirmation:{level:"medium",reason:"This will terminate a running process.",showArgs:["process_id"]}}});var Ul,Wl,Gl,Bl,Kl,Jl=g(()=>{"use strict";l();Ul="exec.list_processes",Wl="List Processes",Gl="List all managed background processes started with exec.run_background, including their status.",Bl="execution",Kl={type:"object",properties:{}}});async function Ph(n){let e=Pl();return e.length===0?"No managed background processes.":JSON.stringify(e,null,2)}var Ot,mn=g(()=>{"use strict";l();Et();Jl();Ot={name:Ul,displayName:Wl,description:Gl,parameters:Kl,category:Bl,execute:Ph}});var zl={};se(zl,{execKillTool:()=>Mt,execListProcessesTool:()=>Ot,execReadOutputTool:()=>At,execRunBackgroundTool:()=>Nt,execRunShellTool:()=>Dt,execRunTool:()=>Rt,execToolsProject:()=>Hl});var Hl,dn=g(()=>{"use strict";l();sn();an();ln();cn();pn();mn();sn();an();ln();cn();pn();mn();Hl={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:[Rt,Dt,Nt,At,Mt,Ot],dependencies:{}}});var Ql,Yl,Vl,Xl,Zl,ec=g(()=>{"use strict";l();Ql="system.info",Yl="Info",Vl="Get system information including OS, CPU, memory, and architecture.",Xl="system",Zl={type:"object",properties:{}}});import*as M from"os";async function Ch(n){return y("[system.info] execute"),JSON.stringify({platform:M.platform(),arch:M.arch(),release:M.release(),hostname:M.hostname(),uptime:M.uptime(),cpus:{model:M.cpus()[0]?.model||"unknown",count:M.cpus().length},memory:{total:M.totalmem(),free:M.freemem(),used:M.totalmem()-M.freemem()},homedir:M.homedir(),tmpdir:M.tmpdir(),nodeVersion:process.version},null,2)}var It,un=g(()=>{"use strict";l();ec();_();It={name:Ql,displayName:Yl,description:Vl,parameters:Zl,category:Xl,execute:Ch}});var tc,oc,rc,nc,sc,ic=g(()=>{"use strict";l();tc="system.env",oc="Environment",rc="Get environment variable(s). If key is provided, returns that specific variable. Otherwise returns all environment variables.",nc="system",sc={type:"object",properties:{key:{type:"string",description:"Specific environment variable name to get (optional, returns all if omitted)"}}}});async function vh(n){let e=n.key;if(y(`[system.env] execute key=${e??"all"}`),e){let r=process.env[e];return r===void 0?`Environment variable "${e}" is not set.`:JSON.stringify({[e]:r})}let t={},o=Object.keys(process.env).sort();for(let r of o)process.env[r]!==void 0&&(t[r]=process.env[r]);return JSON.stringify(t,null,2)}var jt,fn=g(()=>{"use strict";l();ic();_();jt={name:tc,displayName:oc,description:rc,parameters:sc,category:nc,execute:vh}});var ac,lc,cc,pc,mc,dc=g(()=>{"use strict";l();ac="system.set_env",lc="Set Environment",cc="Set an environment variable for the current session. Does not persist across restarts.",pc="system",mc={type:"object",properties:{key:{type:"string",description:"Environment variable name"},value:{type:"string",description:"Value to set"}},required:["key","value"]}});async function Sh(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 Lt,gn=g(()=>{"use strict";l();dc();Lt={name:ac,displayName:lc,description:cc,parameters:mc,category:pc,execute:Sh,confirmation:{level:"medium",reason:"This will modify the process environment, affecting all subsequent operations.",showArgs:["key","value"]}}});var uc,fc,gc,hc,yc,wc=g(()=>{"use strict";l();uc="system.cwd",fc="Current Directory",gc="Get the current working directory of the process.",hc="system",yc={type:"object",properties:{}}});async function kh(n){return y("[system.cwd] execute"),JSON.stringify({cwd:process.cwd()})}var Ft,hn=g(()=>{"use strict";l();wc();_();Ft={name:uc,displayName:fc,description:gc,parameters:yc,category:hc,execute:kh}});var bc,xc,Tc,Pc,Cc,vc=g(()=>{"use strict";l();bc="system.disk_usage",xc="Disk Usage",Tc="Get disk usage information for a given path or the root filesystem.",Pc="system",Cc={type:"object",properties:{path:{type:"string",description:"Path to check disk usage for (default: /)",default:"/"}}}});import*as kc from"fs";import*as $c from"os";import*as ko from"path";import{execSync as Sc}from"child_process";function yn(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 $h(n){let t=n.path||(process.platform==="win32"?$c.tmpdir():"/");t=ko.resolve(t);let o=process.platform==="win32";try{let r=kc.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:yn(Number(s)),used:yn(Number(c)),available:yn(Number(i)),usePercent:`${p}%`,mountedOn:t},null,2)}catch(r){try{if(o){let c=ko.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=Sc(p,{encoding:"utf-8",timeout:5e3,shell:"powershell.exe"}),f=JSON.parse(m.trim()),h=f.Total||0,b=f.Free||0,w=f.Used||0,x=h>0?Math.round(w/h*100):0;return JSON.stringify({path:t,filesystem:f.Name||"NTFS",size:`${(h/1024**3).toFixed(1)}G`,used:`${(w/1024**3).toFixed(1)}G`,available:`${(b/1024**3).toFixed(1)}G`,usePercent:`${x}%`,mountedOn:f.Drive||`${c}`},null,2)}let s=Sc(`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 qt,wn=g(()=>{"use strict";l();vc();qt={name:bc,displayName:xc,description:Tc,parameters:Cc,category:Pc,execute:$h}});var Rc={};se(Rc,{systemCwdTool:()=>Ft,systemDiskUsageTool:()=>qt,systemEnvTool:()=>jt,systemInfoTool:()=>It,systemSetEnvTool:()=>Lt,systemToolsProject:()=>_c});var _c,bn=g(()=>{"use strict";l();un();fn();gn();hn();wn();un();fn();gn();hn();wn();_c={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:[It,jt,Lt,Ft,qt],dependencies:{}}});var Dc,Ec,Nc,Ac,Mc,Oc=g(()=>{"use strict";l();Dc="http.get",Ec="GET",Nc="Make an HTTP GET request to a URL and return the response body.",Ac="network",Mc={type:"object",properties:{url:{type:"string",description:"The URL to request"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url"]}});async function _h(n){let e=n.url,t=n.headers;if(y(`[http.get] execute url="${e}"`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=await fetch(e,{method:"GET",headers:t||{}}),r=await o.text(),s=`HTTP ${o.status} ${o.statusText}`;return o.ok?r.length>Ic?`${s}
|
|
18
|
+
${r.substring(0,Ic)}
|
|
19
19
|
|
|
20
|
-
... (truncated, total ${r.length} characters)`:`${
|
|
21
|
-
${r}`:`${
|
|
22
|
-
${r}`}var
|
|
23
|
-
${
|
|
20
|
+
... (truncated, total ${r.length} characters)`:`${s}
|
|
21
|
+
${r}`:`${s}
|
|
22
|
+
${r}`}var Ic,Ut,xn=g(()=>{"use strict";l();Oc();_();Ic=1e5;Ut={name:Dc,displayName:Ec,description:Nc,parameters:Mc,category:Ac,execute:_h}});var jc,Lc,Fc,qc,Uc,Wc=g(()=>{"use strict";l();jc="http.post",Lc="POST",Fc="Make an HTTP POST request to a URL with an optional body and return the response.",qc="network",Uc={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 Rh(n){let e=n.url,t=n.body,o=n.headers||{};if(y(`[http.post] execute url="${e}" body_len=${t?.length??0}`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");if(t&&!o["Content-Type"]&&!o["content-type"])try{JSON.parse(t),o["Content-Type"]="application/json"}catch{o["Content-Type"]="text/plain"}let r=await fetch(e,{method:"POST",headers:o,body:t||void 0}),s=await r.text(),i=`HTTP ${r.status} ${r.statusText}`;return s.length>Gc?`${i}
|
|
23
|
+
${s.substring(0,Gc)}
|
|
24
24
|
|
|
25
|
-
... (truncated, total ${
|
|
26
|
-
${
|
|
27
|
-
${
|
|
25
|
+
... (truncated, total ${s.length} characters)`:`${i}
|
|
26
|
+
${s}`}var Gc,Wt,Tn=g(()=>{"use strict";l();Wc();_();Gc=1e5;Wt={name:jc,displayName:Lc,description:Fc,parameters:Uc,category:qc,execute:Rh,confirmation:{level:"high",reason:"This will send an HTTP POST request with arbitrary payload.",showArgs:["url","body"]}}});var Bc,Kc,Jc,Hc,zc,Qc=g(()=>{"use strict";l();Bc="http.put",Kc="PUT",Jc="Make an HTTP PUT request to a URL with an optional body and return the response.",Hc="network",zc={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 Dh(n){let e=n.url,t=n.body,o=n.headers||{};if(y(`[http.put] execute url="${e}" body_len=${t?.length??0}`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");if(t&&!o["Content-Type"]&&!o["content-type"])try{JSON.parse(t),o["Content-Type"]="application/json"}catch{o["Content-Type"]="text/plain"}let r=await fetch(e,{method:"PUT",headers:o,body:t||void 0}),s=await r.text(),i=`HTTP ${r.status} ${r.statusText}`;return s.length>Yc?`${i}
|
|
27
|
+
${s.substring(0,Yc)}
|
|
28
28
|
|
|
29
|
-
... (truncated)`:`${
|
|
30
|
-
${
|
|
31
|
-
${r.substring(0,
|
|
29
|
+
... (truncated)`:`${i}
|
|
30
|
+
${s}`}var Yc,Gt,Pn=g(()=>{"use strict";l();Qc();_();Yc=1e5;Gt={name:Bc,displayName:Kc,description:Jc,parameters:zc,category:Hc,execute:Dh,confirmation:{level:"high",reason:"This will send an HTTP PUT request to overwrite remote resources.",showArgs:["url","body"]}}});var Vc,Xc,Zc,ep,tp,op=g(()=>{"use strict";l();Vc="http.delete",Xc="DELETE",Zc="Make an HTTP DELETE request to a URL and return the response.",ep="network",tp={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 Eh(n){let e=n.url,t=n.headers;if(y(`[http.delete] execute url="${e}"`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=await fetch(e,{method:"DELETE",headers:t||{}}),r=await o.text(),s=`HTTP ${o.status} ${o.statusText}`;return r.length>rp?`${s}
|
|
31
|
+
${r.substring(0,rp)}
|
|
32
32
|
|
|
33
|
-
... (truncated)`:`${
|
|
34
|
-
${r}`}var
|
|
33
|
+
... (truncated)`:`${s}
|
|
34
|
+
${r}`}var rp,Bt,Cn=g(()=>{"use strict";l();op();_();rp=1e5;Bt={name:Vc,displayName:Xc,description:Zc,parameters:tp,category:ep,execute:Eh,confirmation:{level:"high",reason:"This will send an HTTP DELETE request to destroy remote resources.",showArgs:["url"]}}});var np,sp,ip,ap,lp,cp=g(()=>{"use strict";l();np="http.download",sp="Download",ip="Download a file from a URL and save it to a local path.",ap="network",lp={type:"object",properties:{url:{type:"string",description:"The URL to download from"},path:{type:"string",description:"Local file path to save the downloaded file"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url","path"]}});import*as et from"fs";import*as pp from"path";async function Nh(n){let e=n.url,t=n.path,o=n.headers;if(y(`[http.download] execute url="${e}" path="${t}"`),!e)throw new Error("url is required");if(!t)throw new Error("path is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let r=await fetch(e,{method:"GET",headers:o||{}});if(!r.ok)throw new Error(`Download failed: HTTP ${r.status} ${r.statusText}`);let s=Buffer.from(await r.arrayBuffer()),i=pp.dirname(t);return et.existsSync(i)||et.mkdirSync(i,{recursive:!0}),et.writeFileSync(t,s),`Downloaded ${e} \u2192 ${t} (${s.length} bytes)`}var Kt,vn=g(()=>{"use strict";l();cp();_();Kt={name:np,displayName:sp,description:ip,parameters:lp,category:ap,execute:Nh}});var dp={};se(dp,{httpDeleteTool:()=>Bt,httpDownloadTool:()=>Kt,httpGetTool:()=>Ut,httpPostTool:()=>Wt,httpPutTool:()=>Gt,httpToolsProject:()=>mp});var mp,Sn=g(()=>{"use strict";l();xn();Tn();Pn();Cn();vn();xn();Tn();Pn();Cn();vn();mp={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:[Ut,Wt,Gt,Bt,Kt],dependencies:{}}});var up,fp,gp,hp,yp,wp=g(()=>{"use strict";l();up="web.fetch",fp="Fetch",gp="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).",hp="network",yp={type:"object",properties:{url:{type:"string",description:"The URL to fetch"},extractionMode:{type:"string",description:'Content extraction mode: "full" (raw HTML, 15K limit), "structured" (title, excerpt, key points, main content), or "minimal" (title + 500 char snippet). Default: "full"',enum:["full","structured","minimal"],default:"full"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as kn from"cheerio";function bp(n,e){let t=kn.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 b of i){let w=t(b).first();if(w.length>0&&(a=w.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((b,w)=>{let x=t(w).text().trim();x.length>50&&c.length<3&&c.push(x)});let p=c.join(`
|
|
35
35
|
|
|
36
|
-
`)||
|
|
37
|
-
`)}function
|
|
38
|
-
URL: ${
|
|
36
|
+
`)||a.substring(0,500),m=[];t("h2, h3").each((b,w)=>{let x=t(w).text().trim();x&&x.length>5&&x.length<200&&m.length<10&&m.push(x)});let f=a.split(/\s+/).length,h=a.split(/\s+/);return h.length>2e3&&(a=h.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:f}}function xp(n,e){let t=kn.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 Tp(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 Pp(n){return`# ${n.title}
|
|
38
|
+
URL: ${n.url}
|
|
39
39
|
|
|
40
|
-
${
|
|
41
|
-
${await
|
|
40
|
+
${n.snippet}`}var Cp=g(()=>{"use strict";l()});async function Ah(n){let e=n.url,t=n.extractionMode||"full",o=n.headers,r=n.timeout||3e4;if(y(`[web.fetch] execute url="${e}" mode=${t} timeout=${r}ms`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let 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=bp(c,e);return Tp(p)}else if(t==="minimal"){let p=xp(c,e);return Pp(p)}else return c.length>15e3?c.substring(0,15e3)+`
|
|
42
42
|
|
|
43
|
-
[TRUNCATED: showing 15K of ${c.length} total characters]`:c}var
|
|
44
|
-
`)||R.title;return JSON.stringify({answer:
|
|
43
|
+
[TRUNCATED: showing 15K of ${c.length} total characters]`:c}var Jt,$n=g(()=>{"use strict";l();wp();Cp();_();Jt={name:up,displayName:fp,description:gp,parameters:yp,category:hp,execute:Ah}});var vp,Sp,kp,$p,_p,Rp=g(()=>{"use strict";l();vp="web.search",Sp="Search",kp="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.",$p="network",_p={type:"object",properties:{query:{type:"string",description:"The search query"},max_results:{type:"integer",description:"Maximum number of results to return (default: 5)",default:5},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4},include_answer:{type:"boolean",description:"Include AI-generated answer summary (works with Tavily and Brave APIs). Default: false",default:!1},freshness:{type:"string",description:'Time range for fresh/recent results: "day" (last 24h), "week" (last 7 days), "month" (last 31 days), "year" (last 365 days). Ensures latest real-time data. Supported by Tavily and Brave APIs; DuckDuckGo returns general results.',enum:["day","week","month","year"]}},required:["query"]}});import*as ve from"fs";import*as $o from"path";function _o(n){let e=Ep(n);if(!ve.existsSync(e))return{};try{let t=ve.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return{}}}function Ht(n){let e=_o(n),t=Oh(e.tools||e);return y(JSON.stringify(t??{})),t}function Mh(n,e){let t=Ep(e),o={};try{ve.existsSync(t)&&(o=JSON.parse(ve.readFileSync(t,"utf-8")))}catch{o={}}o.tools=n,ve.writeFileSync(t,JSON.stringify(o,null,4),"utf-8")}function Oh(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??z.enabled,autoExecute:n.autoExecute??z.autoExecute,maxToolRounds:n.maxToolRounds??z.maxToolRounds,toolChoicePolicy:n.toolChoicePolicy??z.toolChoicePolicy,resultMaxChars:n.resultMaxChars??z.resultMaxChars,intelligentToolDetection:n.intelligentToolDetection,enabledTools:n.enabledTools??z.enabledTools,enabledToolCategories:n.enabledToolCategories??z.enabledToolCategories,toolSearch:n.toolSearch??z.toolSearch,additionalConfigurations:e}}function Ep(n){return n?n.endsWith(".json")?$o.resolve(n):$o.resolve(n,Dp):$o.resolve(process.cwd(),Dp)}var Dp,_n=g(()=>{"use strict";l();lt();_();Dp="toolpack.config.json"});import*as Ap from"cheerio";function Lh(n,e){y("[web.search] Parsing DuckDuckGo Lite response");let t=Ap.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 Fh(n){if(n)switch(n){case"day":return 1;case"week":return 7;case"month":return 31;case"year":return 365;default:return}}function Np(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 qh(n){let e=n.query,t=n.max_results||5,o=n.include_answer||!1,r=n.freshness;y(`[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 f=new AbortController,h=setTimeout(()=>f.abort(),n.timeout||3e4);return{signal:f.signal,clear:()=>clearTimeout(h)}};if(!e)throw new Error("query is required");let a=Ht();if(y(`[web.search] config=${JSON.stringify(a)}`),a.additionalConfigurations?.webSearch?.tavilyApiKey){y("[web.search] using Tavily API");try{let{signal:f,clear:h}=i(),b=Fh(r),w={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:a.additionalConfigurations.webSearch.tavilyApiKey,query:e,max_results:t,include_answer:o,...b&&{days:b}}),signal:f};y(`[web.search] Tavily request=${JSON.stringify(w)}`);let x=await fetch("https://api.tavily.com/search",w).finally(h);if(x.ok){let T=await x.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 ${x.status}`)}catch(f){Q(`[web.search] Tavily search failed, falling back: ${f}`)}}if(a.additionalConfigurations?.webSearch?.braveApiKey)try{let{signal:f,clear:h}=i();if(o){let b=Np(r),w=b?`&freshness=${b}`:"",x=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(e)}&count=${Math.min(t,20)}&summary=1${w}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":a.additionalConfigurations.webSearch.braveApiKey},signal:f}).finally(h);if(x.ok){let T=await x.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(I=>({title:I.title,link:I.url,snippet:I.description})),L=R.summary?.map(I=>I.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 b=Np(r),w=b?`&freshness=${b}`:"",x=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(e)}&count=${Math.min(t,20)}${w}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":a.additionalConfigurations.webSearch.braveApiKey},signal:f}).finally(h);if(x.ok){let T=await x.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(f){E(`[web.search] Brave search failed, falling back: ${f}`)}let{signal:c,clear:p}=i(),m;try{m=await fetch(Ih,{method:"POST",headers:{"User-Agent":jh,"Content-Type":"application/x-www-form-urlencoded",Origin:"https://lite.duckduckgo.com",Referer:"https://lite.duckduckgo.com/"},body:new URLSearchParams({q:e}).toString(),signal:c})}catch(f){throw f.name==="AbortError"?new Error(s):f}finally{p()}if(m.ok){let f=await m.text(),h=Lh(f,t);if(h.length>0)return JSON.stringify(h,null,2)}return JSON.stringify({error:"search_unavailable",message:`Search failed to find results for "${e}" across all providers.`,suggestion:"Please configure a search provider API key (tavilyApiKey or braveApiKey) in toolpack.config.json under tools.additionalConfigurations.webSearch."})}var Ih,jh,zt,Rn=g(()=>{"use strict";l();Rp();_n();_();Ih="https://lite.duckduckgo.com/lite/",jh="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";zt={name:vp,displayName:Sp,description:kp,parameters:_p,category:$p,execute:qh}});var Mp,Op,Ip,jp,Lp,Fp=g(()=>{"use strict";l();Mp="web.scrape",Op="Scrape",Ip="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.",jp="network",Lp={type:"object",properties:{url:{type:"string",description:"The URL to scrape"},section:{type:"string",description:'Optional section name to extract (e.g., "talks", "about", "experience"). Finds the heading containing this text and extracts content until the next same-level heading. Use web.map first to discover available sections.'},format:{type:"string",description:'Output format: "text" (clean readable text) or "tables" (extract table data as JSON array). Default: "text"',enum:["text","tables"],default:"text"},selector:{type:"string",description:"Optional CSS selector to target a specific element. Only use if you know the exact selector exists."},max_length:{type:"integer",description:"Maximum characters to return (default: 6000). Keep small (3000-6000) to avoid context limits.",default:6e3},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as Wp from"cheerio";async function Gh(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(y(`[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":Uh},signal:a.signal})}catch(w){throw w.name==="AbortError"?new Error(`Request timed out after ${i}ms`):w}finally{clearTimeout(c)}if(!p.ok)throw new Error(`Failed to fetch ${e}: HTTP ${p.status} ${p.statusText}`);let m=await p.text(),f=Wp.load(m);for(let w of Wh)f(w).remove();if(r==="tables"){let w=[];return f("table").each((x,T)=>{let k=[],C=[];f(T).find("th").each((P,S)=>{C.push(f(S).text().trim())}),f(T).find("tr").each((P,S)=>{let R=C.length>0?{}:[],D=f(S).find("td");D.length>0&&(D.each((L,I)=>{let q=f(I).text().trim();C.length>0&&C[L]?R[C[L]]=q:R.push(q)}),k.push(R))}),k.length>0&&w.push({id:`Table ${x+1}`,headers:C.length>0?C:void 0,rows:k})}),w.length===0?`No tables found on ${e}`:JSON.stringify(w,null,2)}let h="";if(o){let w=o.toLowerCase(),x=null,T=0;if(f("h1, h2, h3, h4, h5, h6").each((k,C)=>{if(f(C).text().toLowerCase().includes(w))return x=C,T=parseInt(C.tagName.charAt(1)),!1}),x){let k=f(x),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?(h=C.join(`
|
|
45
45
|
|
|
46
46
|
`).replace(/\s+/g," ").trim(),h=`[Section: "${o}"]
|
|
47
47
|
|
|
@@ -49,11 +49,11 @@ ${h}`):h=`[Note: Found heading "${o}" but no content below it. Falling back to f
|
|
|
49
49
|
|
|
50
50
|
`}else h=`[Note: Section "${o}" not found. Falling back to full page.]
|
|
51
51
|
|
|
52
|
-
`}if(!h||h.includes("Falling back to full page"))if(h&&h.includes("Falling back to full page")&&(h=""),t){let w=f(t);if(w.length>0)h=w.text().replace(/\s+/g," ").trim();else{for(let
|
|
52
|
+
`}if(!h||h.includes("Falling back to full page"))if(h&&h.includes("Falling back to full page")&&(h=""),t){let w=f(t);if(w.length>0)h=w.text().replace(/\s+/g," ").trim();else{for(let x of qp){let T=f(x);if(T.length>0){let k=T.text().replace(/\s+/g," ").trim();if(k.length>Up){h=k;break}}}if(h)h=`[Note: Selector "${t}" not found. Showing auto-detected main content instead.]
|
|
53
53
|
|
|
54
|
-
${h}`;else return`No element found matching selector "${t}" and could not auto-detect main content from ${e}`}}else for(let w of
|
|
54
|
+
${h}`;else return`No element found matching selector "${t}" and could not auto-detect main content from ${e}`}}else for(let w of qp){let x=f(w);if(x.length>0){let T=x.text().replace(/\s+/g," ").trim();if(T.length>Up){h=T;break}}}if(h||(h=f("body").text().replace(/\s+/g," ").trim(),h&&(h=`[Note: Could not detect main content area. Showing full page text (may include navigation).]
|
|
55
55
|
|
|
56
|
-
${h}`)),!h)return`Could not extract any content from ${e}`;if(h.length>
|
|
56
|
+
${h}`)),!h)return`Could not extract any content from ${e}`;if(h.length>s){let w=h.substring(0,s);return`[Warning: Content exceeds ${s} chars (actual: ${h.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
|
${w}
|
|
63
63
|
|
|
64
|
-
... [Content truncated. ${h.length-
|
|
64
|
+
... [Content truncated. ${h.length-s} chars remaining. Use section parameter to extract specific sections.]`}return`Page content from ${e}:
|
|
65
65
|
|
|
66
|
-
${h}`}var
|
|
66
|
+
${h}`}var Uh,Wh,qp,Up,Qt,Dn=g(()=>{"use strict";l();Fp();_();Uh="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",Wh=["script","style","nav","footer","header","iframe",".ads",".sidebar","noscript"],qp=["article","main",".content","#content",'[role="main"]',"body"],Up=200;Qt={name:Mp,displayName:Op,description:Ip,parameters:Lp,category:jp,execute:Gh}});var Gp,Bp,Kp,Jp,Hp,zp=g(()=>{"use strict";l();Gp="web.extract_links",Bp="Extract Links",Kp="Extract all links from a webpage. Returns an array of objects with text and URL. Optionally filter by pattern.",Jp="network",Hp={type:"object",properties:{url:{type:"string",description:"The URL to extract links from"},filter:{type:"string",description:'Optional filter: "same-domain" to only include links from the same domain, or a substring to match against URLs'},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as Qp from"cheerio";async function Kh(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":Bh},signal:r.signal})}catch(f){throw f.name==="AbortError"?new Error(`Request timed out after ${o}ms`):f}finally{clearTimeout(s)}if(!i.ok)throw new Error(`Failed to fetch ${e}: HTTP ${i.status} ${i.statusText}`);let a=await i.text(),c=Qp.load(a),p=new URL(e),m=[];return c("a[href]").each((f,h)=>{let b=c(h),w=b.attr("href");if(!w)return;let x;try{x=new URL(w,e).toString()}catch{return}if(x.startsWith("javascript:")||x.startsWith("mailto:")||x.startsWith("tel:"))return;let T=b.text().trim()||"[no text]";if(t){if(t==="same-domain")try{if(new URL(x).hostname!==p.hostname)return}catch{return}else if(!x.includes(t))return}m.push({text:T,url:x})}),m.length===0?`No links found on ${e}${t?` matching filter "${t}"`:""}`:JSON.stringify(m,null,2)}var Bh,Yt,En=g(()=>{"use strict";l();zp();Bh="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Yt={name:Gp,displayName:Bp,description:Kp,parameters:Hp,category:Jp,execute:Kh}});var Yp,Vp,Xp,Zp,em,tm=g(()=>{"use strict";l();Yp="web.map",Vp="Map",Xp="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.",Zp="network",em={type:"object",properties:{url:{type:"string",description:"The URL to map"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as om from"cheerio";async function Hh(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":Jh},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=om.load(i),c=[];if(a("h1, h2, h3, h4, h5, h6").each((m,f)=>{let h=f.tagName.toLowerCase(),b=parseInt(h.charAt(1)),w=a(f).text().trim();w&&c.push({level:b,text:w})}),c.length===0)return`No headings found on ${e}. The page may not have a clear structure.`;let p=`Page outline for ${e}:
|
|
67
67
|
|
|
68
68
|
`;for(let m of c){let f=" ".repeat(m.level-1);p+=`${f}${"#".repeat(m.level)} ${m.text}
|
|
69
|
-
`}return p}var
|
|
70
|
-
`);for(let m of p){if(c.length>=t)break;let f=m.trim();if(f.toLowerCase().startsWith("sitemap:"))c.push({loc:f.substring(8).trim()});else if(f.toLowerCase().startsWith("allow:")){let h=f.substring(6).trim();c.push({loc:new URL(h,r).toString()})}}}return JSON.stringify(c,null,2)}var $h,So,kn=g(()=>{"use strict";l();Kp();$h="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";So={name:Gp,displayName:Bp,description:Jp,parameters:zp,category:Hp,execute:_h}});var Yp,Vp,Xp,Zp,em,tm=g(()=>{"use strict";l();Yp="web.feed",Vp="Extract Feed",Xp="Parse RSS/Atom feeds and return structured entries. Requires rss-parser library to be installed.",Zp="network",em={type:"object",properties:{url:{type:"string",description:"The URL of the RSS/Atom feed"},max_entries:{type:"integer",description:"Maximum number of entries to return (default: 10)",default:10},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function om(){try{let s=await import("rss-parser");return new(s.default||s)}catch{throw new Error("rss-parser is not installed. Please install it using `npm install rss-parser` to use this feature.")}}var rm=g(()=>{"use strict";l()});async function kh(s){let e=s.url,t=s.max_entries||10,o=s.timeout||3e4;if(!e)throw new Error("url is required");let r=await om();r.options={...r.options,timeout:o};try{let n=await r.parseURL(e),a=n.items.slice(0,t).map(i=>({title:i.title,link:i.link,published:i.pubDate||i.isoDate,summary:i.contentSnippet||i.content}));return JSON.stringify({feedTitle:n.title,feedDescription:n.description,entries:a},null,2)}catch(n){throw new Error(`Failed to parse feed from ${e}: ${n.message}`)}}var $o,Rn=g(()=>{"use strict";l();tm();rm();$o={name:Yp,displayName:Vp,description:Xp,parameters:em,category:Zp,execute:kh}});var nm,sm,im,am,lm,cm=g(()=>{"use strict";l();nm="web.screenshot",sm="Screenshot",im="Render a page with headless browser and return screenshot Base64 PNG or rendered HTML.",am="network",lm={type:"object",properties:{url:{type:"string",description:"The URL to capture"},format:{type:"string",description:'Output format: "html" or "png" (default: "html")',enum:["html","png"],default:"html"},viewport:{type:"object",description:"Optional viewport { width, height } (default: { width: 1280, height: 800 })",properties:{width:{type:"integer"},height:{type:"integer"}}},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function pm(){try{let s=await import("puppeteer");return s.default||s}catch{throw new Error("Puppeteer is not installed. Please install it using `npm install puppeteer` to use this feature.")}}var mm=g(()=>{"use strict";l()});async function Dh(s){let e=s.url,t=s.format||"html",o=s.viewport,r=s.timeout||3e4;if(!e)throw new Error("url is required");let a=await(await pm()).launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]});try{let i=await a.newPage();if(await i.setUserAgent(Rh),await i.setViewport({width:o?.width||1280,height:o?.height||800}),await i.goto(e,{waitUntil:"networkidle2",timeout:r}),t==="png"){let c=await i.screenshot({type:"png",fullPage:!0}),p;return Buffer.isBuffer(c)?p=c.toString("base64"):p=Buffer.from(c).toString("base64"),`data:image/png;base64,${p}`}else return await i.content()}finally{await a.close()}}var Rh,_o,Dn=g(()=>{"use strict";l();cm();mm();Rh="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";_o={name:nm,displayName:sm,description:im,parameters:lm,category:am,execute:Dh}});var um={};re(um,{webExtractLinksTool:()=>Gt,webFeedTool:()=>$o,webFetchTool:()=>Lt,webMapTool:()=>Co,webMetadataTool:()=>vo,webScrapeTool:()=>Wt,webScreenshotTool:()=>_o,webSearchTool:()=>Ut,webSitemapTool:()=>So,webToolsProject:()=>dm});var dm,En=g(()=>{"use strict";l();xn();Pn();Cn();vn();Sn();$n();kn();Rn();Dn();xn();Pn();Cn();vn();Sn();$n();kn();Rn();Dn();dm={manifest:{key:"web",name:"web-tools",displayName:"Web",version:"1.0.0",description:"Web intelligence tools for fetching, searching, scraping, and extracting content from the web.",author:"Sajeer",tools:["web.fetch","web.search","web.scrape","web.extract_links","web.map","web.metadata","web.sitemap","web.feed","web.screenshot"],category:"network"},tools:[Lt,Ut,Wt,Gt,Co,vo,So,$o,_o],dependencies:{cheerio:"^1.0.0-rc.12"}}});var fm,gm,hm,ym,wm,bm=g(()=>{"use strict";l();fm="coding.find_symbol",gm="Find Symbol",hm="Find function, class, or variable definitions in JavaScript/TypeScript files using AST parsing",ym="coding",wm={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find (function, class, variable, etc.)"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["symbol","path"]}});import{extname as Eh}from"path";function ko(s){let e=Eh(s).toLowerCase();return Nh[e]||"unknown"}var Nh,Nn=g(()=>{"use strict";l();Nh={".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"jsx",".ts":"typescript",".tsx":"tsx",".py":"python",".go":"go",".rs":"rust",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".hpp":"cpp",".cc":"cpp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".hs":"haskell",".ex":"elixir",".exs":"elixir",".html":"html",".htm":"html",".css":"css",".json":"json",".yaml":"yaml",".yml":"yaml",".md":"markdown",".sh":"bash",".bash":"bash"}});import*as Ae from"web-tree-sitter";import*as pe from"fs";import*as Te from"path";import*as Tm from"os";var xm,An,Ah,Ro,Pm=g(()=>{"use strict";l();xm=Ae.default||Ae.Parser||Ae,An=Te.join(Tm.homedir(),".toolpack-sdk","grammars"),Ah=Te.resolve(d,"../../grammars"),Ro=class{grammars=new Map;isInitialized=!1;async init(){this.isInitialized||(await xm.init({locateFile(e,t){return Te.join(d,"../../../../../../node_modules/web-tree-sitter",e)}}),this.isInitialized=!0)}async ensureGrammar(e){await this.init();let t=this.grammars.get(e);if(t)return t;let o=await this.resolveGrammarPath(e),n=await(Ae.Language||xm.Language).load(o);return this.grammars.set(e,n),n}async resolveGrammarPath(e){let t=`tree-sitter-${e}.wasm`,o=Te.resolve(d,"../../../../../../node_modules/tree-sitter-wasms/out",t);if(pe.existsSync(o))return o;let r=Te.join(Ah,t);if(pe.existsSync(r))return r;let n=Te.join(An,t);return pe.existsSync(n)||await this.downloadGrammar(e,n),n}async downloadGrammar(e,t){pe.existsSync(An)||pe.mkdirSync(An,{recursive:!0});let o=`https://unpkg.com/tree-sitter-wasms@latest/out/tree-sitter-${e}.wasm`,r=await fetch(o);if(!r.ok)throw new Error(`Failed to download grammar for ${e}: ${r.statusText}`);let n=await r.arrayBuffer(),a=Buffer.from(n);pe.writeFileSync(t,a)}}});import*as Bt from"web-tree-sitter";import*as Cm from"fs";import*as vm from"crypto";var Mh,Do,Sm=g(()=>{"use strict";l();Nn();Pm();Mh=Bt.default||Bt.Parser||Bt,Do=class{treeCache=new Map;maxCacheSize=50;parser=null;grammarManager;constructor(){this.grammarManager=new Ro}hash(e){return vm.createHash("md5").update(e).digest("hex")}async getTree(e,t){let o=t!==void 0?t:Cm.readFileSync(e,"utf-8"),r=this.hash(o),n=this.treeCache.get(e),a=ko(e);if(a==="unknown")throw new Error(`Unsupported file type for ${e}`);let i=await this.grammarManager.ensureGrammar(a);if(n&&n.contentHash===r)return n.lastAccessed=Date.now(),{tree:n.tree,language:n.language,grammar:i};this.parser||(await this.grammarManager.init(),this.parser=new Mh),this.parser.setLanguage(i);let c;return n?(n.tree&&n.tree.delete(),c=this.parser.parse(o)):c=this.parser.parse(o),this.treeCache.set(e,{tree:c,language:a,contentHash:r,lastAccessed:Date.now()}),this.evictIfNeeded(),{tree:c,language:a,grammar:i}}evictIfNeeded(){if(this.treeCache.size<=this.maxCacheSize)return;let e="",t=1/0;for(let[o,r]of this.treeCache.entries())r.lastAccessed<t&&(t=r.lastAccessed,e=o);if(e){let o=this.treeCache.get(e);o&&o.tree.delete(),this.treeCache.delete(e)}}}});import{parse as Oh}from"@babel/parser";import*as Mn from"@babel/traverse";var se,Eo,$m=g(()=>{"use strict";l();se=Mn.default||Mn,Eo=class{parseCode(e){return Oh(e,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]})}async findSymbols(e,t,o){let r=[];try{let n=this.parseCode(e.content),a=e.filePath;se(n,{FunctionDeclaration(i){i.node.id?.name===t&&(!o||o==="function")&&r.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"function",name:t})},ClassDeclaration(i){i.node.id?.name===t&&(!o||o==="class")&&r.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"class",name:t})},VariableDeclarator(i){if(i.node.id.type==="Identifier"&&i.node.id.name===t){let c=i.parent,p=c.type==="VariableDeclaration"?c.kind:"variable";(!o||o===p||o==="variable")&&r.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:p,name:t})}},TSInterfaceDeclaration(i){i.node.id.name===t&&(!o||o==="interface")&&r.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"interface",name:t})},TSTypeAliasDeclaration(i){i.node.id.name===t&&(!o||o==="type")&&r.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"type",name:t})}})}catch{}return r}async getSymbols(e,t){let o=[];try{let r=this.parseCode(e.content);se(r,{FunctionDeclaration(n){n.node.id?.name&&(!t||t==="function")&&o.push({name:n.node.id.name,kind:"function",line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})},ClassDeclaration(n){n.node.id?.name&&(!t||t==="class")&&o.push({name:n.node.id.name,kind:"class",line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})},VariableDeclarator(n){if(n.node.id.type==="Identifier"){let a=n.parent,i=a.type==="VariableDeclaration"?a.kind:"variable";(!t||t===i||t==="variable")&&o.push({name:n.node.id.name,kind:i,line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})}},TSInterfaceDeclaration(n){(!t||t==="interface")&&o.push({name:n.node.id.name,kind:"interface",line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})},TSTypeAliasDeclaration(n){(!t||t==="type")&&o.push({name:n.node.id.name,kind:"type",line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})}})}catch(r){throw new Error(`Failed to parse file "${e.filePath}": ${r.message}`)}return o}async getImports(e){let t=[];try{let o=this.parseCode(e.content);se(o,{ImportDeclaration(r){let n=r.node.source.value,a=[],i="side-effect";for(let c of r.node.specifiers)if(c.type==="ImportDefaultSpecifier")a.push(c.local.name),i="default";else if(c.type==="ImportNamespaceSpecifier")a.push(`* as ${c.local.name}`),i="namespace";else if(c.type==="ImportSpecifier"){let p=c.imported.type==="Identifier"?c.imported.name:c.imported.value,m=c.local.name;a.push(p===m?p:`${p} as ${m}`),i="named"}t.push({source:n,imports:a,line:r.node.loc?.start.line||0,type:i})}})}catch(o){throw new Error(`Failed to parse file "${e.filePath}": ${o.message}`)}return t}async findReferences(e,t,o){let r=[];try{let n=e.content,a=n.split(`
|
|
71
|
-
`),
|
|
72
|
-
`),c=Math.max(0,t-1),p=Math.min(
|
|
69
|
+
`}return p}var Jh,Ro,Nn=g(()=>{"use strict";l();tm();Jh="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Ro={name:Yp,displayName:Vp,description:Xp,parameters:em,category:Zp,execute:Hh}});var rm,nm,sm,im,am,lm=g(()=>{"use strict";l();rm="web.metadata",nm="Extract Metadata",sm="Extract Open Graph, Twitter Cards, JSON-LD, and meta tags from a URL.",im="network",am={type:"object",properties:{url:{type:"string",description:"The URL to extract metadata from"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as cm from"cheerio";async function Qh(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":zh},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=cm.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 f=a(m).attr("property")?.replace("og:",""),h=a(m).attr("content");f&&h&&(c.openGraph[f]=h)}),a('meta[name^="twitter:"]').each((p,m)=>{let f=a(m).attr("name")?.replace("twitter:",""),h=a(m).attr("content");f&&h&&(c.twitter[f]=h)}),a('script[type="application/ld+json"]').each((p,m)=>{let f=a(m).html();if(f)try{c.jsonLd.push(JSON.parse(f))}catch{}}),JSON.stringify(c,null,2)}var zh,Do,An=g(()=>{"use strict";l();lm();zh="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Do={name:rm,displayName:nm,description:sm,parameters:am,category:im,execute:Qh}});var pm,mm,dm,um,fm,gm=g(()=>{"use strict";l();pm="web.sitemap",mm="Extract Sitemap",dm="Parse sitemap.xml or robots.txt to discover all pages on a site. Returns an array of URLs with lastmod/priority if available.",um="network",fm={type:"object",properties:{url:{type:"string",description:"The base URL or direct sitemap.xml / robots.txt URL"},max_urls:{type:"integer",description:"Maximum number of URLs to return (default: 100)",default:100},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as hm from"cheerio";async function Mn(n,e){let t=new AbortController,o=setTimeout(()=>t.abort(),e);try{return await fetch(n,{method:"GET",headers:{"User-Agent":Yh},signal:t.signal})}catch(r){throw r.name==="AbortError"?new Error(`Request timed out after ${e}ms`):r}finally{clearTimeout(o)}}async function Vh(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 Mn(r,o),!i.ok&&s&&(r=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await Mn(r,o))}catch(p){if(s)r=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await Mn(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=hm.load(a,{xmlMode:!0}),m=p("sitemap > loc");if(m.length>0)return m.each((h,b)=>{c.length>=t||c.push({loc:p(b).text()})}),JSON.stringify({type:"sitemapindex",urls:c},null,2);p("urlset > url").each((h,b)=>{if(c.length>=t)return;let w=p(b);c.push({loc:w.children("loc").text(),lastmod:w.children("lastmod").text()||void 0,priority:w.children("priority").text()||void 0})})}else{let p=a.split(`
|
|
70
|
+
`);for(let m of p){if(c.length>=t)break;let f=m.trim();if(f.toLowerCase().startsWith("sitemap:"))c.push({loc:f.substring(8).trim()});else if(f.toLowerCase().startsWith("allow:")){let h=f.substring(6).trim();c.push({loc:new URL(h,r).toString()})}}}return JSON.stringify(c,null,2)}var Yh,Eo,On=g(()=>{"use strict";l();gm();Yh="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Eo={name:pm,displayName:mm,description:dm,parameters:fm,category:um,execute:Vh}});var ym,wm,bm,xm,Tm,Pm=g(()=>{"use strict";l();ym="web.feed",wm="Extract Feed",bm="Parse RSS/Atom feeds and return structured entries. Requires rss-parser library to be installed.",xm="network",Tm={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 Cm(){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 vm=g(()=>{"use strict";l()});async function Xh(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 Cm();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 No,In=g(()=>{"use strict";l();Pm();vm();No={name:ym,displayName:wm,description:bm,parameters:Tm,category:xm,execute:Xh}});var Sm,km,$m,_m,Rm,Dm=g(()=>{"use strict";l();Sm="web.screenshot",km="Screenshot",$m="Render a page with headless browser and return screenshot Base64 PNG or rendered HTML.",_m="network",Rm={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 Em(){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 Nm=g(()=>{"use strict";l()});async function ey(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 Em()).launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]});try{let a=await i.newPage();if(await a.setUserAgent(Zh),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 Zh,Ao,jn=g(()=>{"use strict";l();Dm();Nm();Zh="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Ao={name:Sm,displayName:km,description:$m,parameters:Rm,category:_m,execute:ey}});var Mm={};se(Mm,{webExtractLinksTool:()=>Yt,webFeedTool:()=>No,webFetchTool:()=>Jt,webMapTool:()=>Ro,webMetadataTool:()=>Do,webScrapeTool:()=>Qt,webScreenshotTool:()=>Ao,webSearchTool:()=>zt,webSitemapTool:()=>Eo,webToolsProject:()=>Am});var Am,Ln=g(()=>{"use strict";l();$n();Rn();Dn();En();Nn();An();On();In();jn();$n();Rn();Dn();En();Nn();An();On();In();jn();Am={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:[Jt,zt,Qt,Yt,Ro,Do,Eo,No,Ao],dependencies:{cheerio:"^1.0.0-rc.12"}}});var Om,Im,jm,Lm,Fm,qm=g(()=>{"use strict";l();Om="coding.find_symbol",Im="Find Symbol",jm="Find function, class, or variable definitions in JavaScript/TypeScript files using AST parsing",Lm="coding",Fm={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find (function, class, variable, etc.)"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["symbol","path"]}});import{extname as ty}from"path";function Mo(n){let e=ty(n).toLowerCase();return oy[e]||"unknown"}var oy,Fn=g(()=>{"use strict";l();oy={".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"jsx",".ts":"typescript",".tsx":"tsx",".py":"python",".go":"go",".rs":"rust",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".hpp":"cpp",".cc":"cpp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".hs":"haskell",".ex":"elixir",".exs":"elixir",".html":"html",".htm":"html",".css":"css",".json":"json",".yaml":"yaml",".yml":"yaml",".md":"markdown",".sh":"bash",".bash":"bash"}});import*as Fe from"web-tree-sitter";import*as ue from"fs";import*as Se from"path";import*as Wm from"os";var Um,qn,ry,Oo,Gm=g(()=>{"use strict";l();Um=Fe.default||Fe.Parser||Fe,qn=Se.join(Wm.homedir(),".toolpack-sdk","grammars"),ry=Se.resolve(d,"../../grammars"),Oo=class{grammars=new Map;isInitialized=!1;async init(){this.isInitialized||(await Um.init({locateFile(e,t){return Se.join(d,"../../../../../../node_modules/web-tree-sitter",e)}}),this.isInitialized=!0)}async ensureGrammar(e){await this.init();let t=this.grammars.get(e);if(t)return t;let o=await this.resolveGrammarPath(e),s=await(Fe.Language||Um.Language).load(o);return this.grammars.set(e,s),s}async resolveGrammarPath(e){let t=`tree-sitter-${e}.wasm`,o=Se.resolve(d,"../../../../../../node_modules/tree-sitter-wasms/out",t);if(ue.existsSync(o))return o;let r=Se.join(ry,t);if(ue.existsSync(r))return r;let s=Se.join(qn,t);return ue.existsSync(s)||await this.downloadGrammar(e,s),s}async downloadGrammar(e,t){ue.existsSync(qn)||ue.mkdirSync(qn,{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);ue.writeFileSync(t,i)}}});import*as Vt from"web-tree-sitter";import*as Bm from"fs";import*as Km from"crypto";var ny,Io,Jm=g(()=>{"use strict";l();Fn();Gm();ny=Vt.default||Vt.Parser||Vt,Io=class{treeCache=new Map;maxCacheSize=50;parser=null;grammarManager;constructor(){this.grammarManager=new Oo}hash(e){return Km.createHash("md5").update(e).digest("hex")}async getTree(e,t){let o=t!==void 0?t:Bm.readFileSync(e,"utf-8"),r=this.hash(o),s=this.treeCache.get(e),i=Mo(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 ny),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)}}}});import{parse as sy}from"@babel/parser";import*as Un from"@babel/traverse";var ce,jo,Hm=g(()=>{"use strict";l();ce=Un.default||Un,jo=class{parseCode(e){return sy(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,f=c.node.loc?.start.column||0,h=i[m-1]||"";r.push({file:e.filePath,line:m,column:f,context:h.trim(),isDeclaration:p})}}}})}catch{}return r}async getSymbolAtPosition(e,t,o){try{let r=this.parseCode(e.content),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
|
`),f=`
|
|
74
|
-
function ${
|
|
74
|
+
function ${i}() {
|
|
75
75
|
${m}
|
|
76
76
|
}
|
|
77
|
-
`,h=`${
|
|
78
|
-
`),
|
|
79
|
-
`),c=Math.max(0,t-1),p=Math.min(
|
|
80
|
-
`),f="",h="",
|
|
81
|
-
def ${
|
|
77
|
+
`,h=`${i}();`;return{newFunction:f,replacementCall:h}}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(w){let x=w.node.loc;x&&x.start.line<=t&&x.end&&x.end.line>=t&&(i=w,c=x.start.line,p=x.start.column,w.node.type==="FunctionDeclaration"&&w.node.id?a=w.node.id.name:w.parent.type==="VariableDeclarator"&&w.parent.id.type==="Identifier"?a=w.parent.id.name:w.parent.type==="ClassMethod"||w.parent.type==="ObjectMethod"?w.parent.key.type==="Identifier"&&(a=w.parent.key.name):a="<anonymous>")}}),!i||a==="<anonymous>")return null;let m=[],f=[];ce(r,{CallExpression(w){let x=w.node.loc;if(!x||x.start.line<c||x.end&&x.end.line>c+1e3)return;let T=!1,k=w;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=w.node.callee,P="<unknown>";C.type==="Identifier"?P=C.name:C.type==="MemberExpression"&&C.property.type==="Identifier"&&(P=C.property.name),P!=="<unknown>"&&f.push({file:s,name:P,line:w.node.loc?.start.line||0,column:w.node.loc?.start.column||0})}}),ce(r,{CallExpression(w){let x=w.node.callee,T=!1;if((x.type==="Identifier"&&x.name===a||x.type==="MemberExpression"&&x.property.type==="Identifier"&&x.property.name===a)&&(T=!0),T){let k="<global>",C=w;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:w.node.loc?.start.line||0,column:w.node.loc?.start.column||0})}}});let h=[...new Map(m.map(w=>[`${w.name}:${w.line}`,w])).values()],b=[...new Map(f.map(w=>[`${w.name}:${w.line}`,w])).values()];return{file:s,name:a,line:c,column:p,callers:h,callees:b}}catch{return null}}}});var zm,Qm=g(()=>{"use strict";l();zm={}});var Lo,Ym=g(()=>{"use strict";l();Qm();Lo=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=zm[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
|
+
`),f="",h="",b=e.filePath.split(".").pop()?.toLowerCase();return b==="py"||b==="pyi"?(f=`
|
|
81
|
+
def ${i}():
|
|
82
82
|
${m.split(`
|
|
83
83
|
`).map(w=>" "+w).join(`
|
|
84
84
|
`)}
|
|
85
|
-
`,h=`${
|
|
86
|
-
func ${
|
|
85
|
+
`,h=`${i}()`):b==="go"?(f=`
|
|
86
|
+
func ${i}() {
|
|
87
87
|
${m}
|
|
88
88
|
}
|
|
89
|
-
`,h=`${
|
|
90
|
-
fn ${
|
|
89
|
+
`,h=`${i}()`):b==="rs"?(f=`
|
|
90
|
+
fn ${i}() {
|
|
91
91
|
${m}
|
|
92
92
|
}
|
|
93
|
-
`,h=`${
|
|
94
|
-
${
|
|
93
|
+
`,h=`${i}();`):b==="sh"||b==="bash"?(f=`
|
|
94
|
+
${i}() {
|
|
95
95
|
${m}
|
|
96
96
|
}
|
|
97
|
-
`,h=`${
|
|
98
|
-
void ${
|
|
97
|
+
`,h=`${i}`):(f=`
|
|
98
|
+
void ${i}() {
|
|
99
99
|
${m}
|
|
100
100
|
}
|
|
101
|
-
`,h=`${a}();`),{newFunction:f,replacementCall:h}}async getCallHierarchy(e,t,o){let r=await this.getSymbolAtPosition(e,t,o);if(!r)return null;let a=(await this.findReferences(e,r,!1)).map(i=>({file:i.file,name:i.context.trim()||"<anonymous>",line:i.line,column:i.column}));return{file:e.filePath,name:r,line:t,column:o,callers:a,callees:[]}}}});var Ao,Dm=g(()=>{"use strict";l();Nn();$m();Rm();Ao=class{constructor(e){this.context=e;this.babelParser=new Eo,this.treeSitterParser=new No(this.context)}context;babelParser;treeSitterParser;getParser(e){switch(ko(e)){case"javascript":case"typescript":case"tsx":case"jsx":return this.babelParser;case"python":case"go":case"rust":case"java":case"c":case"cpp":return this.treeSitterParser;default:throw new Error(`Unsupported or unknown language for file: ${e}`)}}}});import{readFileSync as Ih,statSync as jh,readdirSync as Fh}from"fs";import{join as Lh,extname as qh}from"path";var Mo,Em=g(()=>{"use strict";l();X();Mo=class{isBuilt=!1;isBuilding=!1;data={symbolLocations:new Map};fileMtimes=new Map;supportedExtensions=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];async getAllSupportedFiles(e){let t=[];try{let o=Fh(e,{withFileTypes:!0});for(let r of o){let n=Lh(e,r.name);r.name==="node_modules"||r.name===".git"||r.name==="dist"||r.name==="build"||(r.isDirectory()?t.push(...await this.getAllSupportedFiles(n)):r.isFile()&&this.supportedExtensions.includes(qh(r.name).toLowerCase())&&t.push(n))}}catch{}return t}async buildIndex(e){if(!(this.isBuilt||this.isBuilding)){this.isBuilding=!0;try{let t=await this.getAllSupportedFiles(e);for(let o of t)await this.updateFile(o);this.isBuilt=!0}finally{this.isBuilding=!1}}}async updateFile(e){try{let o=jh(e).mtimeMs;if(this.fileMtimes.get(e)===o)return;let r=Ih(e,"utf-8"),n=A.getParser(e);this.removeFileFromIndex(e);let a=await n.getSymbols({filePath:e,content:r});for(let i of a){let c=this.data.symbolLocations.get(i.name);c?c.add(e):this.data.symbolLocations.set(i.name,new Set([e]))}this.fileMtimes.set(e,o)}catch{this.removeFileFromIndex(e)}}removeFileFromIndex(e){for(let[t,o]of this.data.symbolLocations.entries())o.delete(e),o.size===0&&this.data.symbolLocations.delete(t);this.fileMtimes.delete(e)}async getDefinitionFiles(e,t){await this.buildIndex(t);let o=this.data.symbolLocations.get(e);return o?Array.from(o):[]}}});var Uh,A,Ke,X=g(()=>{"use strict";l();Sm();Dm();Em();Uh=new Do,A=new Ao(Uh),Ke=new Mo});import{readFileSync as Wh,statSync as Gh,readdirSync as Bh}from"fs";import{join as Jh,extname as Hh}from"path";async function Nm(s,e,t){try{let o=Wh(s,"utf-8");return await A.getParser(s).findSymbols({filePath:s,content:o},e,t)}catch{return[]}}async function Am(s,e,t){let o=[];try{let r=Bh(s,{withFileTypes:!0});for(let n of r){let a=Jh(s,n.name);if(!(n.name==="node_modules"||n.name===".git"||n.name==="dist")){if(n.isDirectory()){let i=await Am(a,e,t);o.push(...i)}else if(n.isFile()&&zh.includes(Hh(n.name))){let i=await Nm(a,e,t);o.push(...i)}}}}catch{}return o}async function Kh(s){let e=s.symbol,t=s.path,o=s.kind;if(y(`[coding.find-symbol] execute symbol="${e}" path="${t}" kind=${o??"all"}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let r=Gh(t),n;if(r.isDirectory())n=await Am(t,e,o);else if(r.isFile())n=await Nm(t,e,o);else throw new Error(`Path is neither a file nor directory: ${t}`);return JSON.stringify({symbol:e,found:n.length,locations:n},null,2)}var zh,Jt,On=g(()=>{"use strict";l();bm();X();_();zh=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];Jt={name:fm,displayName:gm,description:hm,parameters:wm,category:ym,execute:Kh}});var Mm,Om,Im,jm,Fm,Lm=g(()=>{"use strict";l();Mm="coding.get_symbols",Om="Get Symbols",Im="List all symbols (functions, classes, variables, etc.) in a JavaScript/TypeScript file",jm="coding",Fm={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["file"]}});import{readFileSync as Qh}from"fs";async function Yh(s){let e=s.file,t=s.kind;if(y(`[coding.get-symbols] execute file="${e}" kind=${t??"all"}`),!e)throw new Error("file is required");try{let o=Qh(e,"utf-8"),n=await A.getParser(e).getSymbols({filePath:e,content:o},t);return JSON.stringify({file:e,count:n.length,symbols:n},null,2)}catch(o){throw new Error(`Failed to parse file "${e}": ${o.message}`)}}var Ht,In=g(()=>{"use strict";l();Lm();X();_();Ht={name:Mm,displayName:Om,description:Im,parameters:Fm,category:jm,execute:Yh}});var qm,Um,Wm,Gm,Bm,Jm=g(()=>{"use strict";l();qm="coding.get_imports",Um="Get Imports",Wm="List all import statements in a JavaScript/TypeScript file",Gm="coding",Bm={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"}},required:["file"]}});import{readFileSync as Vh}from"fs";async function Xh(s){let e=s.file;if(y(`[coding.get-imports] execute file="${e}"`),!e)throw new Error("file is required");try{let t=Vh(e,"utf-8"),r=await A.getParser(e).getImports({filePath:e,content:t});return JSON.stringify({file:e,count:r.length,imports:r},null,2)}catch(t){throw new Error(`Failed to map explicit imports in file "${e}": ${t.message}`)}}var zt,jn=g(()=>{"use strict";l();Jm();X();_();zt={name:qm,displayName:Um,description:Wm,parameters:Bm,category:Gm,execute:Xh}});var Hm,zm,Km,Qm,Ym,Vm=g(()=>{"use strict";l();Hm="coding.find_references",zm="Find References",Km="Find all references to a symbol across JavaScript/TypeScript files",Qm="coding",Ym={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find references for"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},includeDeclaration:{type:"boolean",description:"Include the symbol declaration in results (default: false)"}},required:["symbol","path"]}});import{readFileSync as Zh,statSync as ey}from"fs";async function Xm(s,e,t){try{let o=Zh(s,"utf-8");return await A.getParser(s).findReferences({filePath:s,content:o},e,t)}catch{return[]}}async function ty(s,e,t){let o=[];await Ke.buildIndex(s);let r=await Ke.getDefinitionFiles(e,s);for(let n of r)if(n.startsWith(s)){let a=await Xm(n,e,t);o.push(...a)}return o}async function oy(s){let e=s.symbol,t=s.path,o=s.includeDeclaration===!0;if(y(`[coding.find-references] execute symbol="${e}" path="${t}" includeDecl=${o}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let r=ey(t),n;if(r.isDirectory())n=await ty(t,e,o);else if(r.isFile())n=await Xm(t,e,o);else throw new Error(`Path is neither a file nor directory: ${t}`);return JSON.stringify({symbol:e,found:n.length,references:n},null,2)}var Oo,Fn=g(()=>{"use strict";l();Vm();X();_();Oo={name:Hm,displayName:zm,description:Km,parameters:Ym,category:Qm,execute:oy}});var Zm,ed,td,od,rd,nd=g(()=>{"use strict";l();Zm="coding.go_to_definition",ed="Go To Definition",td="Jump to the definition of a symbol at a specific location in a file",od="coding",rd={type:"object",properties:{file:{type:"string",description:"Path to the file containing the symbol reference"},line:{type:"integer",description:"Line number where the symbol is referenced (1-indexed)"},column:{type:"integer",description:"Column number where the symbol is referenced (0-indexed)"},searchPath:{type:"string",description:"Optional: directory to search for the definition (defaults to file directory)"}},required:["file","line","column"]}});import{readFileSync as sd,statSync as ry}from"fs";import{dirname as ny}from"path";async function sy(s,e,t){try{let o=sd(s,"utf-8");return await A.getParser(s).getSymbolAtPosition({filePath:s,content:o},e,t)}catch{return null}}async function id(s,e){try{let t=sd(s,"utf-8");return await A.getParser(s).getDefinition({filePath:s,content:t},e)}catch{return null}}async function iy(s,e){await Ke.buildIndex(s);let t=await Ke.getDefinitionFiles(e,s);for(let o of t)if(o.startsWith(s)){let r=await id(o,e);if(r)return r}return null}async function ay(s){let e=s.file,t=s.line,o=s.column,r=s.searchPath;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("line is required");if(o===void 0)throw new Error("column is required");let n=await sy(e,t,o);if(!n)return JSON.stringify({found:!1,message:`No symbol found at ${e}:${t}:${o}`},null,2);let a=await id(e,n);if(!a){let i=r||ny(e);ry(i).isDirectory()&&(a=await iy(i,n))}return JSON.stringify(a?{found:!0,symbol:n,definition:a}:{found:!1,symbol:n,message:`Definition not found for symbol "${n}"`},null,2)}var Io,Ln=g(()=>{"use strict";l();nd();X();Io={name:Zm,displayName:ed,description:td,parameters:rd,category:od,execute:ay}});var ad,ld,cd,pd,md,dd=g(()=>{"use strict";l();ad="coding.multi_file_edit",ld="Multi-File Edit",cd="Edit multiple files atomically with rollback on failure",pd="coding",md={type:"object",properties:{edits:{type:"array",items:{type:"object",properties:{file:{type:"string"},changes:{type:"array",items:{type:"object",properties:{oldText:{type:"string"},newText:{type:"string"}}}}}},description:"Array of file edits, each with file path and array of text replacements"},atomic:{type:"boolean",description:"Atomic mode: rollback all edits if any fails (default: true)"}},required:["edits"]}});import{readFileSync as ly,writeFileSync as ud,existsSync as cy}from"fs";async function py(s){let e=s.edits,t=s.atomic!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("edits array is required and must not be empty");for(let n of e){if(!n.file)throw new Error("Each edit must have a file property");if(!n.changes||!Array.isArray(n.changes))throw new Error("Each edit must have a changes array");if(!cy(n.file))throw new Error(`File does not exist: ${n.file}`)}let o=[],r=[];try{for(let n of e){let a=ly(n.file,"utf-8");t&&o.push({file:n.file,content:a});let i=a;for(let c of n.changes){if(!c.oldText)throw new Error("Each change must have oldText property");if(c.newText===void 0)throw new Error("Each change must have newText property");let p=(i.match(new RegExp(my(c.oldText),"g"))||[]).length;if(p===0)throw new Error(`Text not found in ${n.file}: "${c.oldText.substring(0,50)}..."`);if(p>1)throw new Error(`Ambiguous replacement in ${n.file}: "${c.oldText.substring(0,50)}..." appears ${p} times`);i=i.replace(c.oldText,c.newText)}ud(n.file,i,"utf-8"),r.push(n.file)}return JSON.stringify({success:!0,filesModified:r.length,files:r},null,2)}catch(n){if(t&&o.length>0){for(let a of o)try{ud(a.file,a.content,"utf-8")}catch{}throw new Error(`Multi-file edit failed and rolled back: ${n.message}`)}throw new Error(`Multi-file edit failed: ${n.message}`)}}function my(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var jo,qn=g(()=>{"use strict";l();dd();jo={name:ad,displayName:ld,description:cd,parameters:md,category:pd,execute:py}});var fd,gd,hd,yd,wd,bd=g(()=>{"use strict";l();fd="coding.refactor_rename",gd="Refactor Rename",hd="Rename a symbol across the entire codebase intelligently",yd="coding",wd={type:"object",properties:{symbol:{type:"string",description:"Current name of the symbol to rename"},newName:{type:"string",description:"New name for the symbol"},path:{type:"string",description:"Directory path to search and rename in"},dryRun:{type:"boolean",description:"Preview changes without applying them (default: false)"}},required:["symbol","newName","path"]}});import{readFileSync as dy,writeFileSync as uy,readdirSync as fy}from"fs";import{join as gy,extname as hy}from"path";import{parse as yy}from"@babel/parser";import*as Un from"@babel/traverse";function xy(s,e,t,o){let r=[];try{let n=dy(s,"utf-8"),a=n.split(`
|
|
102
|
-
`),
|
|
103
|
-
`),"utf-8")}}catch{}return{file:s,occurrences:r.length,changes:r}}function xd(s,e,t,o){let r=[];try{let n=fy(s,{withFileTypes:!0});for(let a of n){let i=gy(s,a.name);if(!(a.name==="node_modules"||a.name===".git"||a.name==="dist")){if(a.isDirectory())r.push(...xd(i,e,t,o));else if(a.isFile()&&by.includes(hy(a.name))){let c=xy(i,e,t,o);c.occurrences>0&&r.push(c)}}}}catch{}return r}async function Ty(s){let e=s.symbol,t=s.newName,o=s.path,r=s.dryRun===!0;if(!e)throw new Error("symbol is required");if(!t)throw new Error("newName is required");if(!o)throw new Error("path is required");if(e===t)throw new Error("New name must be different from old name");let n=xd(o,e,t,r),a=n.reduce((c,p)=>c+p.occurrences,0),i=n.length;return JSON.stringify({success:!0,dryRun:r,oldName:e,newName:t,filesAffected:i,totalOccurrences:a,changes:n},null,2)}var wy,by,Fo,Wn=g(()=>{"use strict";l();bd();wy=Un.default||Un,by=[".js",".jsx",".ts",".tsx",".mjs",".cjs"];Fo={name:fd,displayName:gd,description:hd,parameters:wd,category:yd,execute:Ty}});var Td,Pd,Cd,vd,Sd,$d=g(()=>{"use strict";l();Td="coding.get_outline",Pd="Get File Outline",Cd="Gets a hierarchical outline of symbols (classes, functions, methods) in a specified file.",vd="coding",Sd={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to outline"}},required:["file"]}});import{readFileSync as Py,statSync as Cy}from"fs";async function vy(s){let e=s.file;if(y(`[coding.get-outline] execute file="${e}"`),!e)throw new Error("file is required");try{if(!Cy(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=Py(e,"utf-8"),o=A.getParser(e);if(!o.getOutline)return JSON.stringify({file:e,error:"Outline extraction is not specifically implemented for this language yet."});let r=await o.getOutline({filePath:e,content:t});return JSON.stringify({file:e,outline:r},null,2)}catch(t){throw new Error(`Failed to safely extract outline from file "${e}": ${t.message}`)}}var Lo,Gn=g(()=>{"use strict";l();$d();X();_();Lo={name:Td,displayName:Pd,description:Cd,parameters:Sd,category:vd,execute:vy}});var _d,kd,Rd,Dd,Ed,Nd=g(()=>{"use strict";l();_d="coding.get_diagnostics",kd="Get File Diagnostics",Rd="Gets syntax errors and warnings for a file utilizing AST parsing.",Dd="coding",Ed={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to check for diagnostics"}},required:["file"]}});import{readFileSync as Sy,statSync as $y}from"fs";async function _y(s){let e=s.file;if(!e)throw new Error("file is required");try{if(!$y(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=Sy(e,"utf-8"),o=A.getParser(e);if(!o.getDiagnostics)return JSON.stringify({file:e,error:"Diagnostics extraction is not specifically implemented for this language yet."});let r=await o.getDiagnostics({filePath:e,content:t});return JSON.stringify({file:e,diagnostics:r},null,2)}catch(t){throw new Error(`Failed to get diagnostics from file "${e}": ${t.message}`)}}var qo,Bn=g(()=>{"use strict";l();Nd();X();qo={name:_d,displayName:kd,description:Rd,parameters:Ed,category:Dd,execute:_y}});var Ad,Md,Od,Id,jd,Fd=g(()=>{"use strict";l();Ad="coding.get_exports",Md="Get File Exports",Od="Lists all symbols exported by a file.",Id="coding",jd={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"}},required:["file"]}});import{readFileSync as ky,statSync as Ry}from"fs";async function Dy(s){let e=s.file;if(y(`[coding.get-exports] execute file="${e}"`),!e)throw new Error("file is required");try{if(!Ry(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=ky(e,"utf-8"),o=A.getParser(e);if(!o.getExports)return JSON.stringify({file:e,error:"Exports extraction is not specifically implemented for this language yet."});let r=await o.getExports({filePath:e,content:t});return JSON.stringify({file:e,exports:r},null,2)}catch(t){throw new Error(`Failed to extract exports from file "${e}": ${t.message}`)}}var Uo,Jn=g(()=>{"use strict";l();Fd();X();_();Uo={name:Ad,displayName:Md,description:Od,parameters:jd,category:Id,execute:Dy}});var Ld,qd,Ud,Wd,Gd,Bd=g(()=>{"use strict";l();Ld="coding.extract_function",qd="Extract Function",Ud="Extracts a selected code region into a new function, automatically detecting required parameters and return values.",Wd="coding",Gd={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"},startLine:{type:"number",description:"1-indexed start line of the code to extract"},startColumn:{type:"number",description:"0-indexed start column of the code to extract"},endLine:{type:"number",description:"1-indexed end line of the code to extract"},endColumn:{type:"number",description:"0-indexed end column of the code to extract"},newFunctionName:{type:"string",description:"The name for the newly extracted function"}},required:["file","startLine","startColumn","endLine","endColumn","newFunctionName"]}});import{readFileSync as Ey,statSync as Ny}from"fs";async function Ay(s){let e=s.file,t=s.startLine,o=s.startColumn,r=s.endLine,n=s.endColumn,a=s.newFunctionName;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("startLine is required");if(o===void 0)throw new Error("startColumn is required");if(r===void 0)throw new Error("endLine is required");if(n===void 0)throw new Error("endColumn is required");if(!a)throw new Error("newFunctionName is required");try{if(!Ny(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let i=Ey(e,"utf-8"),c=A.getParser(e);if(!c.extractFunction)return JSON.stringify({file:e,error:"Function extraction is not specifically implemented for this language yet."});let p=await c.extractFunction({filePath:e,content:i},t,o,r,n,a);return JSON.stringify({file:e,result:p},null,2)}catch(i){throw new Error(`Failed to extract function from file "${e}": ${i.message}`)}}var Wo,Hn=g(()=>{"use strict";l();Bd();X();Wo={name:Ld,displayName:qd,description:Ud,parameters:Gd,category:Wd,execute:Ay}});var Jd,Hd,zd,Kd,Qd,Yd=g(()=>{"use strict";l();Jd="coding.get_call_hierarchy",Hd="Get Call Hierarchy",zd="Shows callers and callees of a specific function or method.",Kd="coding",Qd={type:"object",properties:{file:{type:"string",description:"The absolute path to the file containing the function"},line:{type:"number",description:"1-indexed line number where the function is defined or called"},column:{type:"number",description:"0-indexed column number where the function is defined or called"}},required:["file","line","column"]}});import{readFileSync as My,statSync as Oy}from"fs";async function Iy(s){let e=s.file,t=s.line,o=s.column;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("line is required");if(o===void 0)throw new Error("column is required");try{if(!Oy(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let r=My(e,"utf-8"),n=A.getParser(e);if(!n.getCallHierarchy)return JSON.stringify({file:e,error:"Call hierarchy is not specifically implemented for this language yet."});let a=await n.getCallHierarchy({filePath:e,content:r},t,o);return JSON.stringify({file:e,hierarchy:a},null,2)}catch(r){throw new Error(`Failed to get call hierarchy from file "${e}": ${r.message}`)}}var Go,zn=g(()=>{"use strict";l();Yd();X();Go={name:Jd,displayName:Hd,description:zd,parameters:Qd,category:Kd,execute:Iy}});var Xd={};re(Xd,{codingExtractFunctionTool:()=>Wo,codingFindReferencesTool:()=>Oo,codingFindSymbolTool:()=>Jt,codingGetCallHierarchyTool:()=>Go,codingGetDiagnosticsTool:()=>qo,codingGetExportsTool:()=>Uo,codingGetImportsTool:()=>zt,codingGetOutlineTool:()=>Lo,codingGetSymbolsTool:()=>Ht,codingGoToDefinitionTool:()=>Io,codingMultiFileEditTool:()=>jo,codingRefactorRenameTool:()=>Fo,codingToolsProject:()=>Vd});var Vd,Kn=g(()=>{"use strict";l();On();In();jn();Fn();Ln();qn();Wn();Gn();Bn();Jn();Hn();zn();On();In();jn();Fn();Ln();qn();Wn();Gn();Bn();Jn();Hn();zn();Vd={manifest:{key:"coding",name:"coding-tools",displayName:"Code Intelligence",version:"1.0.0",description:"AST-aware code intelligence tools for finding symbols, references, and analyzing code structure.",author:"Sajeer",tools:["coding.find_symbol","coding.get_symbols","coding.get_imports","coding.find_references","coding.go_to_definition","coding.get_outline","coding.get_diagnostics","coding.get_exports","coding.extract_function","coding.get_call_hierarchy","coding.multi_file_edit","coding.refactor_rename"],category:"coding"},tools:[Jt,Ht,zt,Oo,Io,Lo,qo,Uo,Wo,Go,jo,Fo],dependencies:{"@babel/parser":"^7.24.0","@babel/traverse":"^7.24.0","@babel/types":"^7.24.0"}}});var Zd,eu=g(()=>{"use strict";l();Zd={type:"object",properties:{path:{type:"string",description:"Optional path or directory to check the status for. If omitted, checks the entire repository."}}}});import{simpleGit as jy}from"simple-git";function q(s){let e={baseDir:s||process.cwd(),binary:"git",maxConcurrentProcesses:6};return jy(e)}var ie=g(()=>{"use strict";l()});var Bo,tu=g(()=>{"use strict";l();eu();ie();Bo={name:"git.status",displayName:"Git Status",description:"Get the working tree status, including modified, staged, and untracked files.",category:"version-control",parameters:Zd,execute:async s=>{let e=s.path;try{let o=await q().status(e?[e]:[]);if(o.isClean())return"Working tree clean";let r=[];return r.push(`Branch: ${o.current}`),o.tracking&&r.push(`Tracking: ${o.tracking}`),o.ahead>0&&r.push(`Ahead: ${o.ahead}`),o.behind>0&&r.push(`Behind: ${o.behind}`),r.push("---"),o.conflicted.length>0&&r.push(`Conflicted: ${o.conflicted.join(", ")}`),o.created.length>0&&r.push(`Created: ${o.created.join(", ")}`),o.deleted.length>0&&r.push(`Deleted: ${o.deleted.join(", ")}`),o.modified.length>0&&r.push(`Modified: ${o.modified.join(", ")}`),o.renamed.length>0&&r.push(`Renamed: ${o.renamed.map(n=>`${n.from} -> ${n.to}`).join(", ")}`),o.staged.length>0&&r.push(`Staged: ${o.staged.join(", ")}`),o.not_added.length>0&&r.push(`Untracked: ${o.not_added.join(", ")}`),r.join(`
|
|
104
|
-
`)}catch(t){return`Error getting git status: ${t instanceof Error?t.message:String(t)}`}}}});var
|
|
105
|
-
Author: ${
|
|
106
|
-
Date: ${
|
|
107
|
-
Message: ${
|
|
101
|
+
`,h=`${i}();`),{newFunction:f,replacementCall:h}}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 Fo,Vm=g(()=>{"use strict";l();Fn();Hm();Ym();Fo=class{constructor(e){this.context=e;this.babelParser=new jo,this.treeSitterParser=new Lo(this.context)}context;babelParser;treeSitterParser;getParser(e){switch(Mo(e)){case"javascript":case"typescript":case"tsx":case"jsx":return this.babelParser;case"python":case"go":case"rust":case"java":case"c":case"cpp":return this.treeSitterParser;default:throw new Error(`Unsupported or unknown language for file: ${e}`)}}}});import{readFileSync as iy,statSync as ay,readdirSync as ly}from"fs";import{join as cy,extname as py}from"path";var qo,Xm=g(()=>{"use strict";l();ee();qo=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=ly(e,{withFileTypes:!0});for(let r of o){let s=cy(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(py(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=ay(e).mtimeMs;if(this.fileMtimes.get(e)===o)return;let r=iy(e,"utf-8"),s=O.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 my,O,tt,ee=g(()=>{"use strict";l();Jm();Vm();Xm();my=new Io,O=new Fo(my),tt=new qo});import{readFileSync as dy,statSync as uy,readdirSync as fy}from"fs";import{join as gy,extname as hy}from"path";async function Zm(n,e,t){try{let o=dy(n,"utf-8");return await O.getParser(n).findSymbols({filePath:n,content:o},e,t)}catch{return[]}}async function ed(n,e,t){let o=[];try{let r=fy(n,{withFileTypes:!0});for(let s of r){let i=gy(n,s.name);if(!(s.name==="node_modules"||s.name===".git"||s.name==="dist")){if(s.isDirectory()){let a=await ed(i,e,t);o.push(...a)}else if(s.isFile()&&yy.includes(hy(s.name))){let a=await Zm(i,e,t);o.push(...a)}}}}catch{}return o}async function wy(n){let e=n.symbol,t=n.path,o=n.kind;if(y(`[coding.find-symbol] execute symbol="${e}" path="${t}" kind=${o??"all"}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let r=uy(t),s;if(r.isDirectory())s=await ed(t,e,o);else if(r.isFile())s=await Zm(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 yy,Xt,Wn=g(()=>{"use strict";l();qm();ee();_();yy=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];Xt={name:Om,displayName:Im,description:jm,parameters:Fm,category:Lm,execute:wy}});var td,od,rd,nd,sd,id=g(()=>{"use strict";l();td="coding.get_symbols",od="Get Symbols",rd="List all symbols (functions, classes, variables, etc.) in a JavaScript/TypeScript file",nd="coding",sd={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["file"]}});import{readFileSync as by}from"fs";async function xy(n){let e=n.file,t=n.kind;if(y(`[coding.get-symbols] execute file="${e}" kind=${t??"all"}`),!e)throw new Error("file is required");try{let o=by(e,"utf-8"),s=await O.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 Zt,Gn=g(()=>{"use strict";l();id();ee();_();Zt={name:td,displayName:od,description:rd,parameters:sd,category:nd,execute:xy}});var ad,ld,cd,pd,md,dd=g(()=>{"use strict";l();ad="coding.get_imports",ld="Get Imports",cd="List all import statements in a JavaScript/TypeScript file",pd="coding",md={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"}},required:["file"]}});import{readFileSync as Ty}from"fs";async function Py(n){let e=n.file;if(y(`[coding.get-imports] execute file="${e}"`),!e)throw new Error("file is required");try{let t=Ty(e,"utf-8"),r=await O.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 eo,Bn=g(()=>{"use strict";l();dd();ee();_();eo={name:ad,displayName:ld,description:cd,parameters:md,category:pd,execute:Py}});var ud,fd,gd,hd,yd,wd=g(()=>{"use strict";l();ud="coding.find_references",fd="Find References",gd="Find all references to a symbol across JavaScript/TypeScript files",hd="coding",yd={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find references for"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},includeDeclaration:{type:"boolean",description:"Include the symbol declaration in results (default: false)"}},required:["symbol","path"]}});import{readFileSync as Cy,statSync as vy}from"fs";async function bd(n,e,t){try{let o=Cy(n,"utf-8");return await O.getParser(n).findReferences({filePath:n,content:o},e,t)}catch{return[]}}async function Sy(n,e,t){let o=[];await tt.buildIndex(n);let r=await tt.getDefinitionFiles(e,n);for(let s of r)if(s.startsWith(n)){let i=await bd(s,e,t);o.push(...i)}return o}async function ky(n){let e=n.symbol,t=n.path,o=n.includeDeclaration===!0;if(y(`[coding.find-references] execute symbol="${e}" path="${t}" includeDecl=${o}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let r=vy(t),s;if(r.isDirectory())s=await Sy(t,e,o);else if(r.isFile())s=await bd(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 Uo,Kn=g(()=>{"use strict";l();wd();ee();_();Uo={name:ud,displayName:fd,description:gd,parameters:yd,category:hd,execute:ky}});var xd,Td,Pd,Cd,vd,Sd=g(()=>{"use strict";l();xd="coding.go_to_definition",Td="Go To Definition",Pd="Jump to the definition of a symbol at a specific location in a file",Cd="coding",vd={type:"object",properties:{file:{type:"string",description:"Path to the file containing the symbol reference"},line:{type:"integer",description:"Line number where the symbol is referenced (1-indexed)"},column:{type:"integer",description:"Column number where the symbol is referenced (0-indexed)"},searchPath:{type:"string",description:"Optional: directory to search for the definition (defaults to file directory)"}},required:["file","line","column"]}});import{readFileSync as kd,statSync as $y}from"fs";import{dirname as _y}from"path";async function Ry(n,e,t){try{let o=kd(n,"utf-8");return await O.getParser(n).getSymbolAtPosition({filePath:n,content:o},e,t)}catch{return null}}async function $d(n,e){try{let t=kd(n,"utf-8");return await O.getParser(n).getDefinition({filePath:n,content:t},e)}catch{return null}}async function Dy(n,e){await tt.buildIndex(n);let t=await tt.getDefinitionFiles(e,n);for(let o of t)if(o.startsWith(n)){let r=await $d(o,e);if(r)return r}return null}async function Ey(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 Ry(e,t,o);if(!s)return JSON.stringify({found:!1,message:`No symbol found at ${e}:${t}:${o}`},null,2);let i=await $d(e,s);if(!i){let a=r||_y(e);$y(a).isDirectory()&&(i=await Dy(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,Jn=g(()=>{"use strict";l();Sd();ee();Wo={name:xd,displayName:Td,description:Pd,parameters:vd,category:Cd,execute:Ey}});var _d,Rd,Dd,Ed,Nd,Ad=g(()=>{"use strict";l();_d="coding.multi_file_edit",Rd="Multi-File Edit",Dd="Edit multiple files atomically with rollback on failure",Ed="coding",Nd={type:"object",properties:{edits:{type:"array",items:{type:"object",properties:{file:{type:"string"},changes:{type:"array",items:{type:"object",properties:{oldText:{type:"string"},newText:{type:"string"}}}}}},description:"Array of file edits, each with file path and array of text replacements"},atomic:{type:"boolean",description:"Atomic mode: rollback all edits if any fails (default: true)"}},required:["edits"]}});import{readFileSync as Ny,writeFileSync as Md,existsSync as Ay}from"fs";async function My(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(!Ay(s.file))throw new Error(`File does not exist: ${s.file}`)}let o=[],r=[];try{for(let s of e){let i=Ny(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(Oy(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)}Md(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{Md(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 Oy(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Go,Hn=g(()=>{"use strict";l();Ad();Go={name:_d,displayName:Rd,description:Dd,parameters:Nd,category:Ed,execute:My,confirmation:{level:"high",reason:"This will modify multiple source code files atomically.",showArgs:["edits"]}}});var Od,Id,jd,Ld,Fd,qd=g(()=>{"use strict";l();Od="coding.refactor_rename",Id="Refactor Rename",jd="Rename a symbol across the entire codebase intelligently",Ld="coding",Fd={type:"object",properties:{symbol:{type:"string",description:"Current name of the symbol to rename"},newName:{type:"string",description:"New name for the symbol"},path:{type:"string",description:"Directory path to search and rename in"},dryRun:{type:"boolean",description:"Preview changes without applying them (default: false)"}},required:["symbol","newName","path"]}});import{readFileSync as Iy,writeFileSync as jy,readdirSync as Ly}from"fs";import{join as Fy,extname as qy}from"path";import{parse as Uy}from"@babel/parser";import*as zn from"@babel/traverse";function By(n,e,t,o){let r=[];try{let s=Iy(n,"utf-8"),i=s.split(`
|
|
102
|
+
`),a=Uy(s,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]}),c=[];if(Wy(a,{Identifier(p){if(p.node.name===e){let m=p.node.loc?.start.line||0,f=p.node.loc?.start.column||0;c.push({line:m,column:f,length:e.length}),r.push({file:n,line:m,column:f,oldName:e,newName:t})}}}),!o&&c.length>0){c.sort((m,f)=>m.line!==f.line?f.line-m.line:f.column-m.column);let p=[...i];for(let m of c){let f=m.line-1;if(f>=0&&f<p.length){let h=p[f],b=h.substring(0,m.column),w=h.substring(m.column+m.length);p[f]=b+t+w}}jy(n,p.join(`
|
|
103
|
+
`),"utf-8")}}catch{}return{file:n,occurrences:r.length,changes:r}}function Ud(n,e,t,o){let r=[];try{let s=Ly(n,{withFileTypes:!0});for(let i of s){let a=Fy(n,i.name);if(!(i.name==="node_modules"||i.name===".git"||i.name==="dist")){if(i.isDirectory())r.push(...Ud(a,e,t,o));else if(i.isFile()&&Gy.includes(qy(i.name))){let c=By(a,e,t,o);c.occurrences>0&&r.push(c)}}}}catch{}return r}async function Ky(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=Ud(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 Wy,Gy,Bo,Qn=g(()=>{"use strict";l();qd();Wy=zn.default||zn,Gy=[".js",".jsx",".ts",".tsx",".mjs",".cjs"];Bo={name:Od,displayName:Id,description:jd,parameters:Fd,category:Ld,execute:Ky,confirmation:{level:"high",reason:"This will rename a symbol across multiple files, rewriting source code without backup.",showArgs:["symbol","newName"]}}});var Wd,Gd,Bd,Kd,Jd,Hd=g(()=>{"use strict";l();Wd="coding.get_outline",Gd="Get File Outline",Bd="Gets a hierarchical outline of symbols (classes, functions, methods) in a specified file.",Kd="coding",Jd={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to outline"}},required:["file"]}});import{readFileSync as Jy,statSync as Hy}from"fs";async function zy(n){let e=n.file;if(y(`[coding.get-outline] execute file="${e}"`),!e)throw new Error("file is required");try{if(!Hy(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=Jy(e,"utf-8"),o=O.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 Ko,Yn=g(()=>{"use strict";l();Hd();ee();_();Ko={name:Wd,displayName:Gd,description:Bd,parameters:Jd,category:Kd,execute:zy}});var zd,Qd,Yd,Vd,Xd,Zd=g(()=>{"use strict";l();zd="coding.get_diagnostics",Qd="Get File Diagnostics",Yd="Gets syntax errors and warnings for a file utilizing AST parsing.",Vd="coding",Xd={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to check for diagnostics"}},required:["file"]}});import{readFileSync as Qy,statSync as Yy}from"fs";async function Vy(n){let e=n.file;if(!e)throw new Error("file is required");try{if(!Yy(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=Qy(e,"utf-8"),o=O.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 Jo,Vn=g(()=>{"use strict";l();Zd();ee();Jo={name:zd,displayName:Qd,description:Yd,parameters:Xd,category:Vd,execute:Vy}});var eu,tu,ou,ru,nu,su=g(()=>{"use strict";l();eu="coding.get_exports",tu="Get File Exports",ou="Lists all symbols exported by a file.",ru="coding",nu={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"}},required:["file"]}});import{readFileSync as Xy,statSync as Zy}from"fs";async function ew(n){let e=n.file;if(y(`[coding.get-exports] execute file="${e}"`),!e)throw new Error("file is required");try{if(!Zy(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=Xy(e,"utf-8"),o=O.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 Ho,Xn=g(()=>{"use strict";l();su();ee();_();Ho={name:eu,displayName:tu,description:ou,parameters:nu,category:ru,execute:ew}});var iu,au,lu,cu,pu,mu=g(()=>{"use strict";l();iu="coding.extract_function",au="Extract Function",lu="Extracts a selected code region into a new function, automatically detecting required parameters and return values.",cu="coding",pu={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"},startLine:{type:"number",description:"1-indexed start line of the code to extract"},startColumn:{type:"number",description:"0-indexed start column of the code to extract"},endLine:{type:"number",description:"1-indexed end line of the code to extract"},endColumn:{type:"number",description:"0-indexed end column of the code to extract"},newFunctionName:{type:"string",description:"The name for the newly extracted function"}},required:["file","startLine","startColumn","endLine","endColumn","newFunctionName"]}});import{readFileSync as tw,statSync as ow}from"fs";async function rw(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(!ow(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let a=tw(e,"utf-8"),c=O.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 zo,Zn=g(()=>{"use strict";l();mu();ee();zo={name:iu,displayName:au,description:lu,parameters:pu,category:cu,execute:rw}});var du,uu,fu,gu,hu,yu=g(()=>{"use strict";l();du="coding.get_call_hierarchy",uu="Get Call Hierarchy",fu="Shows callers and callees of a specific function or method.",gu="coding",hu={type:"object",properties:{file:{type:"string",description:"The absolute path to the file containing the function"},line:{type:"number",description:"1-indexed line number where the function is defined or called"},column:{type:"number",description:"0-indexed column number where the function is defined or called"}},required:["file","line","column"]}});import{readFileSync as nw,statSync as sw}from"fs";async function iw(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(!sw(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let r=nw(e,"utf-8"),s=O.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 Qo,es=g(()=>{"use strict";l();yu();ee();Qo={name:du,displayName:uu,description:fu,parameters:hu,category:gu,execute:iw}});var bu={};se(bu,{codingExtractFunctionTool:()=>zo,codingFindReferencesTool:()=>Uo,codingFindSymbolTool:()=>Xt,codingGetCallHierarchyTool:()=>Qo,codingGetDiagnosticsTool:()=>Jo,codingGetExportsTool:()=>Ho,codingGetImportsTool:()=>eo,codingGetOutlineTool:()=>Ko,codingGetSymbolsTool:()=>Zt,codingGoToDefinitionTool:()=>Wo,codingMultiFileEditTool:()=>Go,codingRefactorRenameTool:()=>Bo,codingToolsProject:()=>wu});var wu,ts=g(()=>{"use strict";l();Wn();Gn();Bn();Kn();Jn();Hn();Qn();Yn();Vn();Xn();Zn();es();Wn();Gn();Bn();Kn();Jn();Hn();Qn();Yn();Vn();Xn();Zn();es();wu={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:[Xt,Zt,eo,Uo,Wo,Ko,Jo,Ho,zo,Qo,Go,Bo],dependencies:{"@babel/parser":"^7.24.0","@babel/traverse":"^7.24.0","@babel/types":"^7.24.0"}}});var xu,Tu=g(()=>{"use strict";l();xu={type:"object",properties:{path:{type:"string",description:"Optional path or directory to check the status for. If omitted, checks the entire repository."}}}});import{simpleGit as aw}from"simple-git";function W(n){let e={baseDir:n||process.cwd(),binary:"git",maxConcurrentProcesses:6};return aw(e)}var pe=g(()=>{"use strict";l()});var Yo,Pu=g(()=>{"use strict";l();Tu();pe();Yo={name:"git.status",displayName:"Git Status",description:"Get the working tree status, including modified, staged, and untracked files.",category:"version-control",parameters:xu,execute:async n=>{let e=n.path;try{let o=await W().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 Cu,vu=g(()=>{"use strict";l();Cu={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 Vo,Su=g(()=>{"use strict";l();vu();pe();Vo={name:"git.diff",displayName:"Git Diff",description:"Show changes between commits, commit and working tree, etc.",category:"version-control",parameters:Cu,execute:async n=>{let e=n.path,t=n.staged;try{let o=W(),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 ku,$u=g(()=>{"use strict";l();ku={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 Xo,_u=g(()=>{"use strict";l();$u();pe();Xo={name:"git.log",displayName:"Git Log",description:"Show commit logs.",category:"version-control",parameters:ku,execute:async n=>{let e=n.maxCount||10,t=n.path;try{let o=W(),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(o){return`Error getting git log: ${o instanceof Error?o.message:String(o)}`}}}});var
|
|
109
|
+
`)}catch(o){return`Error getting git log: ${o instanceof Error?o.message:String(o)}`}}}});var Ru,Du=g(()=>{"use strict";l();Ru={type:"object",properties:{path:{type:"string",description:"Path to the file or directory to stage. To stage all changes, use '.'."}},required:["path"]}});var Zo,Eu=g(()=>{"use strict";l();Du();pe();Zo={name:"git.add",displayName:"Git Add",description:"Add file contents to the index (stage changes).",category:"version-control",parameters:Ru,execute:async n=>{let e=n.path;try{return await W().add(e),`Successfully staged changes for: ${e}`}catch(t){return`Error staging changes: ${t instanceof Error?t.message:String(t)}`}}}});var Nu,Au=g(()=>{"use strict";l();Nu={type:"object",properties:{message:{type:"string",description:"The commit message."}},required:["message"]}});var er,Mu=g(()=>{"use strict";l();Au();pe();er={name:"git.commit",displayName:"Git Commit",description:"Record changes to the repository.",category:"version-control",parameters:Nu,execute:async n=>{let e=n.message;try{let o=await W().commit(e);return o.commit?`Successfully committed changes.
|
|
110
110
|
Commit: ${o.commit}
|
|
111
111
|
Branch: ${o.branch}
|
|
112
|
-
Summary: ${o.summary.changes} changes, ${o.summary.insertions} insertions, ${o.summary.deletions} deletions.`:"Nothing to commit."}catch(t){return`Error committing changes: ${t instanceof Error?t.message:String(t)}`}}}});var
|
|
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 Ou,Iu=g(()=>{"use strict";l();Ou={type:"object",properties:{path:{type:"string",description:"Path to the file to blame."}},required:["path"]}});var tr,ju=g(()=>{"use strict";l();Iu();pe();tr={name:"git.blame",displayName:"Git Blame",description:"Show what revision and author last modified each line of a file.",category:"version-control",parameters:Ou,execute:async n=>{let e=n.path;try{return await W().raw(["blame",e])}catch(t){return`Error running git blame: ${t instanceof Error?t.message:String(t)}`}}}});var Lu,Fu=g(()=>{"use strict";l();Lu={type:"object",properties:{remote:{type:"boolean",description:"List remote branches as well.",default:!1}}}});var or,qu=g(()=>{"use strict";l();Fu();pe();or={name:"git.branch_list",displayName:"Git Branch List",description:"List all branches.",category:"version-control",parameters:Lu,execute:async n=>{let e=n.remote;try{let t=W(),o=e?["-a"]:[],r=await t.branch(o);return`Current Branch: ${r.current}
|
|
113
113
|
|
|
114
114
|
Branches:
|
|
115
115
|
${r.all.join(`
|
|
116
|
-
`)}`}catch(t){return`Error listing branches: ${t instanceof Error?t.message:String(t)}`}}}});var
|
|
116
|
+
`)}`}catch(t){return`Error listing branches: ${t instanceof Error?t.message:String(t)}`}}}});var Uu,Wu=g(()=>{"use strict";l();Uu={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 rr,Gu=g(()=>{"use strict";l();Wu();pe();rr={name:"git.branch_create",displayName:"Git Branch Create",description:"Create a new branch.",category:"version-control",parameters:Uu,execute:async n=>{let e=n.name,t=n.checkout,o=n.startPoint;try{let r=W();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 Bu,Ku=g(()=>{"use strict";l();Bu={type:"object",properties:{branch:{type:"string",description:"Name of the branch or commit to checkout."}},required:["branch"]}});var nr,Ju=g(()=>{"use strict";l();Ku();pe();nr={name:"git.checkout",displayName:"Git Checkout",description:"Switch branches or restore working tree files.",category:"version-control",parameters:Bu,execute:async n=>{let e=n.branch;try{return await W().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 zu={};se(zu,{gitAddTool:()=>Zo,gitBlameTool:()=>tr,gitBranchCreateTool:()=>rr,gitBranchListTool:()=>or,gitCheckoutTool:()=>nr,gitCommitTool:()=>er,gitDiffTool:()=>Vo,gitLogTool:()=>Xo,gitStatusTool:()=>Yo,gitToolsProject:()=>Hu});var Hu,os=g(()=>{"use strict";l();Pu();Su();_u();Eu();Mu();ju();qu();Gu();Ju();Hu={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:[Yo,Vo,Xo,Zo,er,tr,or,rr,nr],dependencies:{"simple-git":"^3.27.0"}}});var Qu,Yu=g(()=>{"use strict";l();Qu={type:"object",properties:{oldContent:{type:"string",description:"The original text content."},newContent:{type:"string",description:"The new text content."},fileName:{type:"string",description:"Optional filename to include in the patch header."},contextLines:{type:"number",description:"Number of context lines to include around differences. Default is 4.",default:4}},required:["oldContent","newContent"]}});import*as Vu from"diff";var sr,Xu=g(()=>{"use strict";l();Yu();_();sr={name:"diff.create",displayName:"Create Diff",description:"Generate a unified diff from two text contents.",category:"diff",parameters:Qu,execute:async n=>{let e=n.oldContent,t=n.newContent,o=n.fileName||"file",r=n.contextLines??4;y(`[diff.create] execute fileName="${o}" contextLines=${r}`);try{return Vu.createPatch(o,e,t,"","",{context:r})}catch(s){return`Error creating diff: ${s instanceof Error?s.message:String(s)}`}}}});var Zu,ef=g(()=>{"use strict";l();Zu={type:"object",properties:{path:{type:"string",description:"Path to the file to patch."},patch:{type:"string",description:"Unified diff string to apply."}},required:["path","patch"]}});import*as of from"diff";import{promises as tf}from"fs";var ir,rf=g(()=>{"use strict";l();ef();_();ir={name:"diff.apply",displayName:"Apply Diff",description:"Apply a unified diff patch to a file.",category:"diff",parameters:Zu,execute:async n=>{let e=n.path,t=n.patch;y(`[diff.apply] execute path="${e}"`);try{let o=await tf.readFile(e,"utf8"),r=of.applyPatch(o,t);return r===!1?"Failed to apply patch. The patch may be malformed or conflicting with the current file content.":(await tf.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 nf,sf=g(()=>{"use strict";l();nf={type:"object",properties:{path:{type:"string",description:"Path to the file to apply the patch against for preview."},patch:{type:"string",description:"Unified diff string to preview."}},required:["path","patch"]}});import*as af from"diff";import{promises as lw}from"fs";var ar,lf=g(()=>{"use strict";l();sf();ar={name:"diff.preview",displayName:"Preview Diff",description:"Preview the result of applying a patch to a file without modifying it.",category:"diff",parameters:nf,execute:async n=>{let e=n.path,t=n.patch;try{let o=await lw.readFile(e,"utf8"),r=af.applyPatch(o,t);return r===!1?"Patch preview failed. The patch would not apply cleanly.":`Preview of ${e} after patch:
|
|
117
117
|
|
|
118
|
-
${r}`}catch(o){return`Error previewing patch: ${o instanceof Error?o.message:String(o)}`}}}});var
|
|
118
|
+
${r}`}catch(o){return`Error previewing patch: ${o instanceof Error?o.message:String(o)}`}}}});var pf={};se(pf,{diffApplyTool:()=>ir,diffCreateTool:()=>sr,diffPreviewTool:()=>ar,diffToolsProject:()=>cf});var cf,rs=g(()=>{"use strict";l();Xu();rf();lf();cf={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:[sr,ir,ar],dependencies:{diff:"^7.0.0"}}});var mf,df=g(()=>{"use strict";l();mf={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 ke,lr=g(()=>{"use strict";l();ke=class{connectionString;constructor(e){this.connectionString=e}}});import uf from"better-sqlite3";import*as ns from"fs";var to,ff=g(()=>{"use strict";l();lr();to=class extends ke{getDb(){if(!ns.existsSync(this.connectionString))throw new Error(`Database file not found: ${this.connectionString}`);return new uf(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(!ns.existsSync(e))throw new Error(`Database file not found: ${e}`);let r=new uf(e,{readonly:!1});try{let s=r.prepare(t);return s.reader?s.all(o):s.run(o)}finally{r.close()}}}});import cw from"pg";var cr,gf=g(()=>{"use strict";l();lr();cr=class extends ke{async getClient(){let e=new cw.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 @@ ${r}`}catch(o){return`Error previewing patch: ${o instanceof Error?o.message:Str
|
|
|
123
123
|
SELECT table_name as name, table_type
|
|
124
124
|
FROM information_schema.tables
|
|
125
125
|
WHERE table_schema = 'public'
|
|
126
|
-
`)}}});import qy from"mysql2/promise";var nr,Ku=g(()=>{"use strict";l();or();nr=class extends Pe{async getConnection(){return await qy.createConnection(this.connectionString)}async query(e,t=[]){let o=await this.getConnection();try{let[r]=await o.execute(e,t);return r}finally{await o.end()}}async execute(e,t=[]){let o=await this.getConnection();try{let[r]=await o.execute(e,t);return{changes:r.affectedRows,lastInsertRowid:r.insertId,raw:r}}finally{await o.end()}}async getTables(){let t=await this.query("SHOW TABLES");if(!t||t.length===0)return[];let o=Object.keys(t[0]);return t.map(r=>r[o[0]])}async getSchema(e){if(e){let t=await this.getConnection();try{let[o]=await t.query("DESCRIBE ??",[e]);return o}finally{await t.end()}}else return await this.query("SHOW TABLES")}}});var G,Ce=g(()=>{"use strict";l();Hu();zu();Ku();G=class{static getAdapter(e){return e.startsWith("postgres://")||e.startsWith("postgresql://")?new rr(e):e.startsWith("mysql://")?new nr(e):e.startsWith("sqlite://")?new Kt(e.replace("sqlite://","")):new Kt(e)}}});var sr,Qu=g(()=>{"use strict";l();Bu();Ce();_();sr={name:"db.query",displayName:"Database Query",description:"Execute raw SQL queries against an SQLite, PostgreSQL, or MySQL database.",category:"database",parameters:Gu,execute:async s=>{let e=s.db,t=s.sql,o=s.params||[];y(`[db.query] execute db="${e}" sql="${t.substring(0,80)}..." params=${o.length}`);try{let n=await G.getAdapter(e).query(t,o);return JSON.stringify(n,null,2)}catch(r){return`Database query error: ${r instanceof Error?r.message:String(r)}`}}}});var Yu,Vu=g(()=>{"use strict";l();Yu={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Optional specific table name to inspect. If omitted, returns structural summary of all tables."}},required:["db"]}});var ir,Xu=g(()=>{"use strict";l();Vu();Ce();ir={name:"db.schema",displayName:"Database Schema",description:"Get the structural schema of a database or a specific table.",category:"database",parameters:Yu,execute:async s=>{let e=s.db,t=s.table;try{let r=await G.getAdapter(e).getSchema(t);return JSON.stringify(r,null,2)}catch(o){return`Database schema error: ${o instanceof Error?o.message:String(o)}`}}}});var Zu,ef=g(()=>{"use strict";l();Zu={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"}},required:["db"]}});var ar,tf=g(()=>{"use strict";l();ef();Ce();ar={name:"db.tables",displayName:"Database Tables",description:"List all user tables in the database.",category:"database",parameters:Zu,execute:async s=>{let e=s.db;try{let o=await G.getAdapter(e).getTables();return JSON.stringify(o,null,2)}catch(t){return`Database tables error: ${t instanceof Error?t.message:String(t)}`}}}});var of,rf=g(()=>{"use strict";l();of={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to insert into"},data:{type:"object",description:"Key-value pairs of column names and values to insert"}},required:["db","table","data"]}});var lr,nf=g(()=>{"use strict";l();rf();Ce();lr={name:"db.insert",displayName:"Database Insert",description:"Insert a new row into an SQLite table safely.",category:"database",parameters:of,execute:async s=>{let e=s.db,t=s.table,o=s.data;if(Object.keys(o).length===0)return"Error: No data provided to insert.";try{let r=Object.keys(o).join(", "),n=Object.keys(o).map(()=>"?").join(", "),a=Object.values(o),i=`INSERT INTO ${t} (${r}) VALUES (${n})`,p=await G.getAdapter(e).execute(i,a);return JSON.stringify(p,null,2)}catch(r){return`Database insert error: ${r instanceof Error?r.message:String(r)}`}}}});var sf,af=g(()=>{"use strict";l();sf={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to update"},data:{type:"object",description:"Key-value pairs of column names and new values"},where:{type:"string",description:'WHERE clause condition (e.g. "id = 5"). DO NOT INCLUDE the word WHERE.'}},required:["db","table","data","where"]}});var cr,lf=g(()=>{"use strict";l();af();Ce();cr={name:"db.update",displayName:"Database Update",description:"Update existing rows in a database table.",category:"database",parameters:sf,execute:async s=>{let e=s.db,t=s.table,o=s.data,r=s.where;if(Object.keys(o).length===0)return"Error: No data provided to update.";try{let n=Object.keys(o).map(m=>`${m} = ?`).join(", "),a=Object.values(o),i=`UPDATE ${t} SET ${n} WHERE ${r}`,p=await G.getAdapter(e).execute(i,a);return JSON.stringify(p,null,2)}catch(n){return`Database update error: ${n instanceof Error?n.message:String(n)}`}}}});var cf,pf=g(()=>{"use strict";l();cf={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to delete from"},where:{type:"string",description:'WHERE clause condition (e.g. "id = 5"). DO NOT INCLUDE the word WHERE.'}},required:["db","table","where"]}});var pr,mf=g(()=>{"use strict";l();pf();Ce();pr={name:"db.delete",displayName:"Database Delete",description:"Delete rows from a database table.",category:"database",parameters:cf,execute:async s=>{let e=s.db,t=s.table,o=s.where;try{let r=`DELETE FROM ${t} WHERE ${o}`,a=await G.getAdapter(e).execute(r);return JSON.stringify(a,null,2)}catch(r){return`Database delete error: ${r instanceof Error?r.message:String(r)}`}}}});var df,uf=g(()=>{"use strict";l();df={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to count rows from"},where:{type:"string",description:"Optional WHERE clause condition"}},required:["db","table"]}});var mr,ff=g(()=>{"use strict";l();uf();Ce();mr={name:"db.count",displayName:"Database Count",description:"Count rows in a database table.",category:"database",parameters:df,execute:async s=>{let e=s.db,t=s.table,o=s.where;try{let r=o?`WHERE ${o}`:"",n=`SELECT COUNT(*) as count FROM ${t} ${r}`,i=await G.getAdapter(e).query(n);return Array.isArray(i)&&i.length>0?`Rows: ${i[0].count}`:"Count: 0"}catch(r){return`Database count error: ${r instanceof Error?r.message:String(r)}`}}}});var hf={};re(hf,{dbCountTool:()=>mr,dbDeleteTool:()=>pr,dbInsertTool:()=>lr,dbQueryTool:()=>sr,dbSchemaTool:()=>ir,dbTablesTool:()=>ar,dbToolsProject:()=>gf,dbUpdateTool:()=>cr});var gf,Xn=g(()=>{"use strict";l();Qu();Xu();tf();nf();lf();mf();ff();gf={manifest:{key:"db",name:"db-tools",displayName:"Database Tools",version:"1.0.0",description:"Stateless database operations enabling the AI to interact with local databases.",author:"Sajeer",tools:["db.query","db.schema","db.tables","db.insert","db.update","db.delete","db.count"],category:"database"},tools:[sr,ir,ar,lr,cr,pr,mr],dependencies:{"better-sqlite3":"^11.3.0"}}});var yf,wf=g(()=>{"use strict";l();yf={type:"object",properties:{siteId:{type:"string",description:'The Netlify Site ID to deploy to (e.g. "api_id" from Netlify UI)'},dir:{type:"string",description:'The local directory path to deploy (e.g. "./dist" or "./public")'},message:{type:"string",description:"Optional deployment message/commit note"}},required:["siteId","dir"]}});import{NetlifyAPI as Uy}from"netlify";var ve,dr=g(()=>{"use strict";l();ve=class{static getClient(){let e=process.env.NETLIFY_AUTH_TOKEN;if(!e)throw new Error("NETLIFY_AUTH_TOKEN environment variable is required to use Netlify cloud tools.");return new Uy(e)}}});var ur,bf=g(()=>{"use strict";l();wf();dr();_();ur={name:"cloud.deploy",displayName:"Cloud Deploy",description:"Deploy a static directory to Netlify.",category:"cloud",parameters:yf,execute:async s=>{let e=s.siteId,t=s.dir,o=s.message;y(`[cloud.deploy] execute siteId="${e}" dir="${t}" message="${o??"none"}"`);try{let n=await ve.getClient().deploy(e,t,{message:o||"Deployed via Toolpack SDK",draft:!1});return JSON.stringify({id:n.deployId,url:n.deploy.url,admin_url:n.deploy.admin_url,state:n.deploy.state},null,2)}catch(r){return`Cloud deployment error: ${r instanceof Error?r.message:String(r)}`}}}});var xf,Tf=g(()=>{"use strict";l();xf={type:"object",properties:{siteId:{type:"string",description:"The Netlify Site ID"},deployId:{type:"string",description:"The specific Deployment ID to check"}},required:["siteId","deployId"]}});var fr,Pf=g(()=>{"use strict";l();Tf();dr();fr={name:"cloud.status",displayName:"Cloud Status",description:"Check the status of a specific Netlify deployment.",category:"cloud",parameters:xf,execute:async s=>{let e=s.siteId,t=s.deployId;try{let r=await ve.getClient().getSiteDeploy({site_id:e,deploy_id:t});return JSON.stringify({id:r.id,state:r.state,error_message:r.error_message,created_at:r.created_at,updated_at:r.updated_at,url:r.url},null,2)}catch(o){return`Cloud status error: ${o instanceof Error?o.message:String(o)}`}}}});var Cf,vf=g(()=>{"use strict";l();Cf={type:"object",properties:{siteId:{type:"string",description:"The Netlify Site ID"},limit:{type:"number",description:"Number of recent deployments to return. Defaults to 5.",default:5}},required:["siteId"]}});var gr,Sf=g(()=>{"use strict";l();vf();dr();_();gr={name:"cloud.list",displayName:"Cloud Deployments List",description:"List recent deployments for a Netlify site.",category:"cloud",parameters:Cf,execute:async s=>{let e=s.siteId,t=s.limit||5;y(`[cloud.list] execute siteId="${e}" limit=${t}`);try{let r=await ve.getClient().listSiteDeploys({site_id:e,page:1,per_page:t});if(!Array.isArray(r))return"Unexpected response format from Netlify API";let n=r.map(a=>({id:a.id,state:a.state,created_at:a.created_at,url:a.url,branch:a.branch,title:a.title}));return JSON.stringify(n,null,2)}catch(o){return`Cloud list error: ${o instanceof Error?o.message:String(o)}`}}}});var _f={};re(_f,{cloudDeployTool:()=>ur,cloudListTool:()=>gr,cloudStatusTool:()=>fr,cloudToolsProject:()=>$f});var $f,Zn=g(()=>{"use strict";l();bf();Pf();Sf();$f={manifest:{key:"cloud",name:"cloud-tools",displayName:"Cloud Deployment",version:"1.0.0",description:"Cloud deployment operations allowing the AI to publish directories directly to the internet.",author:"Sajeer",tools:["cloud.deploy","cloud.status","cloud.list"],category:"cloud"},tools:[ur,fr,gr],dependencies:{netlify:"^13.1.20"}}});l();ce();l();ce();import{EventEmitter as eg}from"events";l();l();l();var Ie={name:3,displayName:2.5,description:2,category:1.5,parameterNames:1,parameterDescriptions:.5},Xe=class{documents=[];avgDocLength=0;idf=new Map;totalDocs=0;docFrequencies=new Map;k1=1.2;b=.75;index(e){this.documents=[],this.docFrequencies.clear(),this.idf.clear();for(let t of e){let o=this.createDocument(t);this.documents.push(o);let r=new Set(o.tokens);for(let n of r)this.docFrequencies.set(n,(this.docFrequencies.get(n)||0)+1)}this.totalDocs=this.documents.length,this.computeIDF(),this.avgDocLength=this.computeAvgDocLength()}search(e,t){let o=t?.limit??5,r=t?.category,n=t?.minScore??0,a=this.tokenize(e.toLowerCase());if(a.length===0)return[];let i=[];for(let c of this.documents){if(r&&c.tool.category!==r)continue;let p=this.computeBM25Score(a,c);p>n&&i.push({toolName:c.toolName,score:p,tool:c.tool})}return i.sort((c,p)=>p.score-c.score).slice(0,o).map(({toolName:c,score:p,tool:m})=>({toolName:c,score:p,tool:this.toSchema(m)}))}getIndexedCount(){return this.documents.length}isIndexed(e){return this.documents.some(t=>t.toolName===e)}createDocument(e){let t=[];for(let a=0;a<Ie.name;a++)t.push(e.name);for(let a=0;a<Ie.displayName;a++)t.push(e.displayName);for(let a=0;a<Ie.description;a++)t.push(e.description);for(let a=0;a<Ie.category;a++)t.push(e.category);if(e.parameters?.properties)for(let[a,i]of Object.entries(e.parameters.properties)){for(let c=0;c<Ie.parameterNames;c++)t.push(a);if(i.description)for(let c=0;c<Ie.parameterDescriptions;c++)t.push(i.description)}let o=t.join(" ").toLowerCase(),r=this.tokenize(o),n=this.computeTermFrequencies(r);return{toolName:e.name,tool:e,text:o,tokens:r,length:r.length,termFrequencies:n}}tokenize(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1).filter(t=>!Kf.has(t))}computeTermFrequencies(e){let t=new Map;for(let o of e)t.set(o,(t.get(o)||0)+1);return t}computeIDF(){this.idf.clear();for(let[e,t]of this.docFrequencies){let o=Math.log((this.totalDocs-t+.5)/(t+.5)+1);this.idf.set(e,o)}}computeAvgDocLength(){return this.documents.length===0?0:this.documents.reduce((t,o)=>t+o.length,0)/this.documents.length}computeBM25Score(e,t){let o=0;for(let r of e){let n=t.termFrequencies.get(r)||0;if(n===0)continue;let a=this.idf.get(r)||0,i=t.length,c=n*(this.k1+1),p=n+this.k1*(1-this.b+this.b*(i/this.avgDocLength));o+=a*(c/p)}return o}toSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category}}},Kf=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","it","its","this","that","these","those","i","you","he","she","we","they","what","which","who","whom","when","where","why","how","all","each","every","both","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","just","also","now","here","there"]);l();var je=class s{discoveredTools=new Set;searchHistory=[];recordDiscovery(e,t){for(let o of t)this.discoveredTools.add(o);this.searchHistory.push({query:e,tools:t,timestamp:Date.now()})}getDiscoveredTools(){return Array.from(this.discoveredTools)}isDiscovered(e){return this.discoveredTools.has(e)}getDiscoveredCount(){return this.discoveredTools.size}getSearchHistory(){return[...this.searchHistory]}static fromMessages(e){let t=new s;for(let o of e)if(o.role==="tool"){let r=o;if(typeof r.content=="string")try{let n=JSON.parse(r.content);if(n.query&&n.tools&&Array.isArray(n.tools)){let a=n.tools.map(i=>typeof i=="string"?i:i.name).filter(Boolean);a.length>0&&t.recordDiscovery(n.query,a)}}catch{}}return t}clear(){this.discoveredTools.clear(),this.searchHistory=[]}merge(e){for(let t of e.getDiscoveredTools())this.discoveredTools.add(t);this.searchHistory.push(...e.getSearchHistory())}};l();var Ze="tool.search",Fe={name:Ze,displayName:"Search Tools",category:"meta",description:`Search for available tools by keyword or natural language query.
|
|
126
|
+
`)}}});import pw from"mysql2/promise";var pr,hf=g(()=>{"use strict";l();lr();pr=class extends ke{async getConnection(){return await pw.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,$e=g(()=>{"use strict";l();ff();gf();hf();K=class{static getAdapter(e){return e.startsWith("postgres://")||e.startsWith("postgresql://")?new cr(e):e.startsWith("mysql://")?new pr(e):e.startsWith("sqlite://")?new to(e.replace("sqlite://","")):new to(e)}}});var mr,yf=g(()=>{"use strict";l();df();$e();_();mr={name:"db.query",displayName:"Database Query",description:"Execute raw SQL queries against an SQLite, PostgreSQL, or MySQL database.",category:"database",parameters:mf,execute:async n=>{let e=n.db,t=n.sql,o=n.params||[];y(`[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 wf,bf=g(()=>{"use strict";l();wf={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 dr,xf=g(()=>{"use strict";l();bf();$e();dr={name:"db.schema",displayName:"Database Schema",description:"Get the structural schema of a database or a specific table.",category:"database",parameters:wf,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 Tf,Pf=g(()=>{"use strict";l();Tf={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"}},required:["db"]}});var ur,Cf=g(()=>{"use strict";l();Pf();$e();ur={name:"db.tables",displayName:"Database Tables",description:"List all user tables in the database.",category:"database",parameters:Tf,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 vf,Sf=g(()=>{"use strict";l();vf={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 fr,kf=g(()=>{"use strict";l();Sf();$e();fr={name:"db.insert",displayName:"Database Insert",description:"Insert a new row into an SQLite table safely.",category:"database",parameters:vf,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 $f,_f=g(()=>{"use strict";l();$f={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 gr,Rf=g(()=>{"use strict";l();_f();$e();gr={name:"db.update",displayName:"Database Update",description:"Update existing rows in a database table.",category:"database",parameters:$f,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 Df,Ef=g(()=>{"use strict";l();Df={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to delete from"},where:{type:"string",description:'WHERE clause condition (e.g. "id = 5"). DO NOT INCLUDE the word WHERE.'}},required:["db","table","where"]}});var hr,Nf=g(()=>{"use strict";l();Ef();$e();hr={name:"db.delete",displayName:"Database Delete",description:"Delete rows from a database table.",category:"database",parameters:Df,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 Af,Mf=g(()=>{"use strict";l();Af={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 yr,Of=g(()=>{"use strict";l();Mf();$e();yr={name:"db.count",displayName:"Database Count",description:"Count rows in a database table.",category:"database",parameters:Af,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 jf={};se(jf,{dbCountTool:()=>yr,dbDeleteTool:()=>hr,dbInsertTool:()=>fr,dbQueryTool:()=>mr,dbSchemaTool:()=>dr,dbTablesTool:()=>ur,dbToolsProject:()=>If,dbUpdateTool:()=>gr});var If,ss=g(()=>{"use strict";l();yf();xf();Cf();kf();Rf();Nf();Of();If={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:[mr,dr,ur,fr,gr,hr,yr],dependencies:{"better-sqlite3":"^11.3.0"}}});var Lf,Ff=g(()=>{"use strict";l();Lf={type:"object",properties:{siteId:{type:"string",description:'The Netlify Site ID to deploy to (e.g. "api_id" from Netlify UI)'},dir:{type:"string",description:'The local directory path to deploy (e.g. "./dist" or "./public")'},message:{type:"string",description:"Optional deployment message/commit note"}},required:["siteId","dir"]}});import{NetlifyAPI as mw}from"netlify";var _e,wr=g(()=>{"use strict";l();_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 mw(e)}}});var br,qf=g(()=>{"use strict";l();Ff();wr();_();br={name:"cloud.deploy",displayName:"Cloud Deploy",description:"Deploy a static directory to Netlify.",category:"cloud",parameters:Lf,execute:async n=>{let e=n.siteId,t=n.dir,o=n.message;y(`[cloud.deploy] execute siteId="${e}" dir="${t}" message="${o??"none"}"`);try{let s=await _e.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 Uf,Wf=g(()=>{"use strict";l();Uf={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 xr,Gf=g(()=>{"use strict";l();Wf();wr();xr={name:"cloud.status",displayName:"Cloud Status",description:"Check the status of a specific Netlify deployment.",category:"cloud",parameters:Uf,execute:async n=>{let e=n.siteId,t=n.deployId;try{let r=await _e.getClient().getSiteDeploy({site_id:e,deploy_id:t});return JSON.stringify({id:r.id,state:r.state,error_message:r.error_message,created_at:r.created_at,updated_at:r.updated_at,url:r.url},null,2)}catch(o){return`Cloud status error: ${o instanceof Error?o.message:String(o)}`}}}});var Bf,Kf=g(()=>{"use strict";l();Bf={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 Tr,Jf=g(()=>{"use strict";l();Kf();wr();_();Tr={name:"cloud.list",displayName:"Cloud Deployments List",description:"List recent deployments for a Netlify site.",category:"cloud",parameters:Bf,execute:async n=>{let e=n.siteId,t=n.limit||5;y(`[cloud.list] execute siteId="${e}" limit=${t}`);try{let r=await _e.getClient().listSiteDeploys({site_id:e,page:1,per_page:t});if(!Array.isArray(r))return"Unexpected response format from Netlify API";let 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 zf={};se(zf,{cloudDeployTool:()=>br,cloudListTool:()=>Tr,cloudStatusTool:()=>xr,cloudToolsProject:()=>Hf});var Hf,is=g(()=>{"use strict";l();qf();Gf();Jf();Hf={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:[br,xr,Tr],dependencies:{netlify:"^13.1.20"}}});l();ae();l();ae();import{EventEmitter as Sg}from"events";l();l();l();var We={name:3,displayName:2.5,description:2,category:1.5,parameterNames:1,parameterDescriptions:.5},st=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<We.name;i++)t.push(e.name);for(let i=0;i<We.displayName;i++)t.push(e.displayName);for(let i=0;i<We.description;i++)t.push(e.description);for(let i=0;i<We.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<We.parameterNames;c++)t.push(i);if(a.description)for(let c=0;c<We.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=>!bg.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}}},bg=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 Ge=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 it="tool.search",Be={name:it,displayName:"Search Tools",category:"meta",description:`Search for available tools by keyword or natural language query.
|
|
127
127
|
Use this to discover tools before using them.
|
|
128
128
|
Examples: "file operations", "web scraping", "run command", "http request"
|
|
129
129
|
|
|
130
130
|
Returns a list of matching tools with their names, descriptions, and parameters.
|
|
131
|
-
After discovering tools, you can call them directly by name.`,parameters:{type:"object",properties:{query:{type:"string",description:'Natural language search query (e.g., "read files", "web scraping", "execute shell commands")'},category:{type:"string",description:"Optional: filter by category",enum:["filesystem","network","execution","system","meta"]}},required:["query"]},execute:async()=>{throw new Error("tool.search execution must be handled by AIClient")}};function
|
|
132
|
-
`)}var
|
|
133
|
-
Working directory: ${
|
|
134
|
-
Available tool categories: ${
|
|
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 Rr(){return{name:Be.name,displayName:Be.displayName,description:Be.description,parameters:Be.parameters,category:Be.category}}function Dr(n){return n===it}l();var xg={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 Er(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=xg[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 at=class{discoveryCache=new Ge;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(Rr()),s.add(it);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=Ge.fromMessages(e);this.discoveryCache.merge(c);let p=this.discoveryCache.getDiscoveredTools();for(let m of p){let f=t.get(m);f&&!s.has(m)&&f.cacheable!==!1&&(r.push(this.toSchema(f)),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}}};lt();l();function $s(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
|
|
140
|
-
`):""}return""}function
|
|
139
|
+
- Only ask the user for clarification when you genuinely cannot determine their intent or lack the required tools`}l();var Ke=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 ao=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(h=>h.toolCallId===p.id)?.dependsOn.every(h=>i.has(h))??!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 Ae(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 Ds=0;function Mr(){return Ds+=1,`${Date.now()}-${Ds}`}function po(n,e){Me("debug")&&(y(`[AIClient][${n}] Messages (${e.length}):`),e.forEach((t,o)=>{let r=A(t.content,300);y(`[AIClient][${n}] #${o} role=${t.role} content=${r}`)}))}function Es(n){let e=Ae(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 Ns(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 As(n){return{openai:"gpt-4.1-mini",anthropic:"claude-3-haiku-20240307",gemini:"gemini-2.0-flash-exp",ollama:"llama3.2"}[n]||"default"}function kg(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 Ms(n,e,t,o){let r=Mr();y(`[AIClient][${r}] inferNeedsToolsWithAI() provider=${e} model=${o}`);let s=kg(t),a=t.filter(p=>p.role==="user").slice(-1)[0]?.content||"",c=`Recent tool usage: ${s}
|
|
141
141
|
|
|
142
|
-
User's new message: "${
|
|
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
|
|
152
|
-
[TRUNCATED tool result: ${$.length} chars]
|
|
153
|
-
[TRUNCATED tool result: ${
|
|
154
|
-
[TRUNCATED tool result: ${
|
|
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(),f=m.startsWith("YES");return y(`[AIClient][${r}] inferNeedsToolsWithAI() context="${s}" message="${a.substring(0,50)}" result=${f} (raw: ${m})`),f}catch(p){return E(`[AIClient][${r}] inferNeedsToolsWithAI() error=${p} - falling back to false`),!1}}function Os(n){let e=Ae(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 mo=class extends Sg{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||z,this.toolRouter=new at,this.bm25Engine=new st,this.queryClassifier=new Ke,this.toolOrchestrator=new ao,this.overrideSystemPrompt=e.systemPrompt,this.disableBaseContext=e.disableBaseContext||!1;let t=this.toolsConfig.resultMaxChars??z.resultMaxChars??2e4;this.toolResultMaxChars=Number.isFinite(t)&&t>0?t:2e4,this.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 G("No provider specified and no default provider configured","NO_PROVIDER_CONFIGURED",400);let o=this.providers.get(t);if(!o)throw new G(`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 G(`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=Mr(),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,f=Es(a.messages),h=this.toolsConfig.intelligentToolDetection,b=!1;if(!f&&h?.enabled&&p&&Ns(a.messages,h.maxFollowUpMessages)){v(`[AIClient][${r}] Message is after tool call, using AI to infer tool needs`);let R=As(i||"openai");f=await Ms(o,i||"openai",a.messages,R),b=!0}let w=Os(a.messages);!m&&p&&(c==="required"||c==="required_for_actions"&&f)?a.tool_choice="required":!m&&p&&b&&!f&&(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=${f} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),po(r,a.messages);let P=await o.generate(C);if(y(`[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=Ae(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}`):y(`[AIClient][${r}] Query classified as ${R.type} (confidence: ${R.confidence.toFixed(2)}), keeping maxToolRounds: ${L}`);let I=0,q=[...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&&I<L;){I++,this.currentRound=I,v(`[AIClient][${r}] generate() tool round ${I}/${L} tool_calls=${P.tool_calls.length}`),q.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),Re=3,ge=P.tool_calls,me=P.tool_calls.filter(B=>B.name==="web.fetch");if(me.length>Re){v(`[AIClient][${r}] Limiting web.fetch calls from ${me.length} \u2192 ${Re} to prevent context overflow`);let B=me.slice(0,Re);ge=[...P.tool_calls.filter($=>$.name!=="web.fetch"),...B];let F=me.slice(Re);for(let $ of F)q.push({role:"tool",tool_call_id:$.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let te=5e4,de=0;if(J){v(`[AIClient][${r}] Using parallel execution for ${ge.length} tools`);let B=await this.toolOrchestrator.executeWithDependencies(ge,F=>this.executeTool(F),5),oe=!1;for(let F of ge){if(oe){q.push({role:"tool",tool_call_id:F.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let $=B.get(F.id),re=typeof $=="string"?$:JSON.stringify($);if(de+re.length>te){E(`[AIClient][${r}] Tool output budget exceeded (${te} chars), adding placeholder for remaining tools`),q.push({role:"tool",tool_call_id:F.id,content:"[Skipped: tool output budget exceeded for this round]"}),oe=!0;continue}let ne=typeof $=="string"&&$.length>this.toolResultMaxChars?`${$.slice(0,this.toolResultMaxChars)}
|
|
152
|
+
[TRUNCATED tool result: ${$.length} chars]`:$,De=typeof ne=="string"?ne:JSON.stringify(ne);de+=De.length,q.push({role:"tool",tool_call_id:F.id,content:ne})}y(`[AIClient][${r}] Round tool output size: ${de} chars (budget: ${te})`)}else{v(`[AIClient][${r}] Using sequential execution for ${ge.length} tools`);let B=!1;for(let oe of ge){if(B){q.push({role:"tool",tool_call_id:oe.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let F=await this.executeTool(oe),$=typeof F=="string"?F:JSON.stringify(F);if(de+$.length>te){E(`[AIClient][${r}] Tool output budget exceeded (${te} chars), adding placeholder for remaining tools`),q.push({role:"tool",tool_call_id:oe.id,content:"[Skipped: tool output budget exceeded for this round]"}),B=!0;continue}let re=typeof F=="string"&&F.length>this.toolResultMaxChars?`${F.slice(0,this.toolResultMaxChars)}
|
|
153
|
+
[TRUNCATED tool result: ${F.length} chars]`:F,ne=typeof re=="string"?re:JSON.stringify(re);de+=ne.length,q.push({role:"tool",tool_call_id:oe.id,content:re})}y(`[AIClient][${r}] Round tool output size: ${de} chars (budget: ${te})`)}let Ue={...a,messages:q,__toolpack_request_id:r},he=await this.enrichRequestWithTools(Ue);he.tool_choice==="required"&&(he.tool_choice=w?"none":"auto",v(`[AIClient][${r}] generate() followup tool_choice override required->${he.tool_choice}`)),Me("debug")&&(y(`[AIClient][${r}] generate() followup request messages=${q.length}`),po(r,q)),P=await o.generate(he),y(`[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=Mr(),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,f=Es(a.messages),h=this.toolsConfig.intelligentToolDetection,b=!1;if(!f&&h?.enabled&&p&&Ns(a.messages,h.maxFollowUpMessages)){v(`[AIClient][${r}] Message is after tool call, using AI to infer tool needs`);let J=As(s||"openai");f=await Ms(o,s||"openai",a.messages,J),b=!0}let w=Os(a.messages);!m&&p&&(c==="required"||c==="required_for_actions"&&f)?a.tool_choice="required":!m&&p&&b&&!f&&(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=${f} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),po(r,a.messages),!this.toolsConfig.enabled||!this.toolsConfig.autoExecute||!this.toolRegistry){yield*o.stream(C);return}let P=[...a.messages],S=0,R=Ae(a.messages),D=this.queryClassifier.classify(R),L=this.toolsConfig.maxToolRounds,I=this.queryClassifier.getToolRoundsAdjustment(D,L);for(I!==L&&v(`[AIClient][${r}] stream() Query classified as ${D.type} (confidence: ${D.confidence.toFixed(2)}), adjusted maxToolRounds: ${L} \u2192 ${I}`);S<=I;){if(e.signal?.aborted){v(`[AIClient][${r}] stream() aborted by signal`);return}let q="",J=[];S++,this.currentRound=S,v(`[AIClient][${r}] stream() round_start ${S}/${I}`);let Re=null,ge={...C,messages:P},me=await this.enrichRequestWithTools(ge);S>0&&me.tool_choice==="required"&&(me.tool_choice=w?"none":"auto",v(`[AIClient][${r}] stream() round_${S+1} tool_choice override required->${me.tool_choice}`));for await(let $ of o.stream(me)){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),y(`[AIClient][${r}] stream() tool_calls_chunk count=${$.tool_calls.length} names=${$.tool_calls.map(re=>re.name).join(", ")}`),yield $),$.delta&&(q+=$.delta,yield $),$.finish_reason&&(Re=$.finish_reason),$.finish_reason==="stop"&&(yield $)}if(y(`[AIClient][${r}] stream() round_end finish_reason=${Re??"unknown"} accumulated_len=${q.length} tool_calls_total=${J.length} content_preview=${A(q,200)}`),J.length===0)break;if(v(`[AIClient][${r}] stream() received ${J.length} tool call(s): ${J.map($=>$.name).join(", ")}`),S++,S>I){v(`[AIClient][${r}] stream() max tool rounds (${I}) reached`);break}v(`[AIClient][${r}] stream() tool round ${S}/${I}`),P.push({role:"assistant",content:q||"",tool_calls:J.map($=>({id:$.id,type:"function",function:{name:$.name,arguments:JSON.stringify($.arguments)}}))});let te=3,de=J,Ue=J.filter($=>$.name==="web.fetch");if(Ue.length>te){v(`[AIClient][${r}] Limiting web.fetch calls from ${Ue.length} \u2192 ${te} to prevent context overflow`);let $=Ue.slice(0,te);de=[...J.filter(De=>De.name!=="web.fetch"),...$];let ne=Ue.slice(te);for(let De of ne)P.push({role:"tool",tool_call_id:De.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let he=5e4,B=0,oe=!1,F=[];for(let $ of de){if(oe){P.push({role:"tool",tool_call_id:$.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let re=Date.now(),ne=!1,De=setInterval(()=>{ne||F.push({delta:""})},500),ye=await this.executeTool($);ne=!0,clearInterval(De);let pg=Date.now()-re;for(;F.length>0;)yield F.shift();await new Promise(ug=>setTimeout(ug,0));let mg=typeof ye=="string"?ye:JSON.stringify(ye);if(B+mg.length>he){E(`[AIClient][${r}] Tool output budget exceeded (${he} chars), adding placeholder for remaining tools`),P.push({role:"tool",tool_call_id:$.id,content:"[Skipped: tool output budget exceeded for this round]"}),oe=!0;continue}let Ee=typeof ye=="string"&&ye.length>this.toolResultMaxChars?`${ye.slice(0,this.toolResultMaxChars)}
|
|
154
|
+
[TRUNCATED tool result: ${ye.length} chars]`:ye,dg=typeof Ee=="string"?Ee:JSON.stringify(Ee);B+=dg.length,P.push({role:"tool",tool_call_id:$.id,content:Ee}),yield{delta:"",tool_calls:[{...$,result:typeof Ee=="string"?Ee:JSON.stringify(Ee),duration:pg}]}}y(`[AIClient][${r}] Round tool output size: ${B} chars (budget: ${he})`),Me("debug")&&(y(`[AIClient][${r}] stream() after_tools messages=${P.length}`),po(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 y("[AIClient] Tools disabled or no registry"),e;let t=this.toolsConfig;if(this.activeMode?.toolSearch&&this.toolsConfig.toolSearch&&(t={...this.toolsConfig,toolSearch:{...this.toolsConfig.toolSearch,...this.activeMode.toolSearch.enabled!==void 0?{enabled:this.activeMode.toolSearch.enabled}:{},...this.activeMode.toolSearch.alwaysLoadedTools?{alwaysLoadedTools:this.activeMode.toolSearch.alwaysLoadedTools}:{},...this.activeMode.toolSearch.alwaysLoadedCategories?{alwaysLoadedCategories:this.activeMode.toolSearch.alwaysLoadedCategories}:{}}},y(`[AIClient] Merged mode toolSearch config: enabled=${t.toolSearch?.enabled}, alwaysLoadedTools=${t.toolSearch?.alwaysLoadedTools?.length||0}`)),e.tools&&e.tools.length>0){if(!t.toolSearch?.enabled||!this.toolRegistry)return y(`[AIClient] Request already has ${e.tools.length} tools`),e;let a=await this.toolRouter.resolve(e.messages,this.toolRegistry,t);if(y(`[AIClient] Resolved ${a.length} tools to send: ${a.map(f=>f.name).join(", ")||"none"}`),this.activeMode&&a.length>0){let f=a.length;a=this.filterSchemasByMode(a,this.activeMode);let h=f-a.length;h>0&&v(`[AIClient] Mode "${this.activeMode.displayName}" filtered out ${h} tools`)}let c=new Set(e.tools.map(f=>f.function.name)),p=a.filter(f=>!c.has(f.name)).map(f=>({type:"function",function:{name:f.name,description:f.description,parameters:f.parameters}}));if(p.length===0)return y(`[AIClient] Request already has ${e.tools.length} tools (no new discoveries)`),e;let m={...e,tools:[...e.tools,...p]};return t.toolSearch?.enabled&&this.toolRegistry&&(m=this.injectToolSearchPrompt(m)),m}if(!this.toolRegistry)return y("[AIClient] Tool registry not configured, skipping tool resolution"),e;let o=this.toolRegistry,r=await this.toolRouter.resolve(e.messages,o,t);if(y(`[AIClient] Resolved ${r.length} tools to send: ${r.map(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 y(`[AIClient] injectModeSystemPrompt: No active mode or empty systemPrompt. activeMode=${this.activeMode?.name}, systemPrompt=${this.activeMode?.systemPrompt?.substring(0,50)}`),e;let t=this.activeMode.systemPrompt;if(y(`[AIClient] injectModeSystemPrompt: Injecting mode prompt for ${this.activeMode.name}, length=${t.length}`),e.messages.some(r=>r.role==="system")){let r=e.messages.map(s=>{if(s.role==="system"){let i=typeof s.content=="string"?s.content:"";return{...s,content:`${i}
|
|
155
155
|
|
|
156
|
-
${t}`}}return
|
|
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
|
|
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||$s({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:
|
|
161
|
-
`);
|
|
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
|
-
${
|
|
164
|
+
${i}
|
|
165
165
|
|
|
166
|
-
Use these tools directly when appropriate for the task.`)}let
|
|
166
|
+
Use these tools directly when appropriate for the task.`)}let s=`
|
|
167
167
|
IMPORTANT: Tool Discovery Instructions
|
|
168
168
|
|
|
169
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
|
-
${
|
|
171
|
+
${Er(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
|
|
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: ${E(e.arguments,500)}`),!this.toolRegistry){let r="No tool registry configured";return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:r,duration:Date.now()-t}),JSON.stringify({error:r})}if(vr(e.name)){let r=this.executeToolSearch(e.arguments),n=Date.now()-t;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof r=="string"?r.substring(0,200):JSON.stringify(r).substring(0,200),duration:n}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:r,duration:n,status:"success",timestamp:Date.now()}),r}let o=this.toolRegistry.get(e.name);if(!o){D(`[AIClient] Tool '${e.name}' not found in registry`);let r=this.findSimilarToolName(e.name),n=r?`Tool '${e.name}' not found. Did you mean '${r}'? Use tool.search to discover available tools.`:`Tool '${e.name}' not found. Use tool.search to discover available tools.`;return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:n,duration:Date.now()-t}),JSON.stringify({error:n})}try{let r={workspaceRoot:process.cwd(),config:this.toolsConfig?.additionalConfigurations??{},log:i=>v(`[Tool] ${i}`)},n=await o.execute(e.arguments,r),a=Date.now()-t;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof n=="string"?n.substring(0,200):JSON.stringify(n).substring(0,200),duration:a}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:n,duration:a,status:"success",timestamp:Date.now()}),v(`[AIClient] Tool ${e.name} executed successfully in ${a}ms result_len=${n?.length??0}`),Re("debug")&&y(`[AIClient] Tool ${e.name} result_preview=${E(n,400)}`),n}catch(r){let n=Date.now()-t,a=r.message||"Tool execution failed";return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:a,duration:n}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:JSON.stringify({error:a}),duration:n,status:"error",timestamp:Date.now()}),Q(`[AIClient] Tool ${e.name} failed: ${E(a,300)}`),JSON.stringify({error:a})}}findSimilarToolName(e){if(!this.toolRegistry)return null;let t=this.toolRegistry.getAll(),o=e.replace(/_/g,".");if(t.some(c=>c.name===o))return o;let r=e.replace(/\./g,"_");if(t.some(c=>c.name===r))return r;let n=e.replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase().replace(/_/g,".");if(t.some(c=>c.name===n))return n;let a=null,i=1/0;for(let c of t){let p=this.levenshteinDistance(e.toLowerCase(),c.name.toLowerCase());p<=2&&p<i&&(i=p,a=c.name)}return a}levenshteinDistance(e,t){let o=[];for(let r=0;r<=t.length;r++)o[r]=[r];for(let r=0;r<=e.length;r++)o[0][r]=r;for(let r=1;r<=t.length;r++)for(let n=1;n<=e.length;n++)t.charAt(r-1)===e.charAt(n-1)?o[r][n]=o[r-1][n-1]:o[r][n]=Math.min(o[r-1][n-1]+1,o[r][n-1]+1,o[r-1][n]+1);return o[t.length][e.length]}executeToolSearch(e){let{query:t,category:o}=e,r=this.toolsConfig.toolSearch?.searchResultLimit??5;v(`[AIClient] Executing tool.search: query="${t}" category=${o||"all"} limit=${r}`);let n=this.bm25Engine.search(t,{limit:r,category:o}),a=n.map(i=>i.toolName);return this.toolRouter.getDiscoveryCache().recordDiscovery(t,a),y(`[AIClient] tool.search found ${n.length} tools: ${a.join(", ")||"none"}`),JSON.stringify({query:t,found:n.length,tools:n.map(i=>({name:i.tool.name,displayName:i.tool.displayName,description:i.tool.description,category:i.tool.category,parameters:i.tool.parameters,relevanceScore:Math.round(i.score*100)/100})),hint:n.length>0?`Found ${n.length} tools. You can now call any of these tools directly.`:`No tools found for "${t}". Try a different search term.`})}wrapError(e){return e instanceof H?e:new F(e.message||"Unknown provider error","UNKNOWN_PROVIDER_ERROR",500,e)}};l();l();import Cs from"@anthropic-ai/sdk";l();ce();var Y=class{name;async getModels(){return[]}getDisplayName(){return this.name||this.constructor.name.replace(/Adapter$/,"")}supportsFileUpload(){return!1}async uploadFile(e){throw new M(`File upload API is not supported by ${this.getDisplayName()}`)}async deleteFile(e){throw new M(`File deletion API is not supported by ${this.getDisplayName()}`)}};ce();_();var ao=class extends Y{client;constructor(e,t){super(),this.client=new Cs({apiKey:e,baseURL:t})}supportsFileUpload(){return!0}async uploadFile(e){try{let t=await import("fs");if(!e.filePath)throw new M("Anthropic uploadFile requires a filePath.");return{id:(await this.client.files.create({file:t.createReadStream(e.filePath),purpose:e.purpose||"vision"})).id}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{await this.client.files.delete(e)}catch(t){throw this.handleError(t)}}getDisplayName(){return"Anthropic"}async getModels(){return[{id:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:64e3},{id:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-sonnet-4-6",displayName:"Claude Sonnet 4.6",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-opus-4-5",displayName:"Claude Opus 4.5",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-opus-4-6",displayName:"Claude Opus 4.6",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384}]}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(r=>this.sanitizeToolName(r.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,o=await this.toAnthropicMessages(e.messages,e.mediaOptions),r=o.system,n=o.userMessages,a={model:e.model,messages:n,system:r,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p,stream:!1};e.tools&&e.tools.length>0?(a.tools=e.tools.map(m=>({name:this.sanitizeToolName(m.function.name),description:m.function.description,input_schema:m.function.parameters})),e.tool_choice==="required"?a.tool_choice={type:"any"}:e.tool_choice==="none"?delete a.tools:a.tool_choice={type:"auto"},y(`[Anthropic][${t}] Sending ${a.tools?.length||0} tools with tool_choice: ${a.tool_choice?.type||"unset"}`),a.tools&&a.tools.length>0&&y(`[Anthropic][${t}] First tool: ${E(a.tools[0],800)}`)):y(`[Anthropic][${t}] NO TOOLS in request`),y(`[Anthropic][${t}] generate() request: model=${a.model}, messages=${a.messages.length}, tools=${a.tools?.length||0}, tool_choice=${a.tool_choice?.type??"unset"}`),V(t,"Anthropic",a.messages);let i=await this.client.messages.create(a,e.signal?{signal:e.signal}:void 0),c=[],p=[];for(let m of i.content)m.type==="text"?c.push(m.text):m.type==="tool_use"&&p.push({id:m.id,name:this.restoreToolName(m.name,e.tools),arguments:m.input});return y(`[Anthropic][${t}] Response finish_reason=${i.stop_reason} tool_calls=${p.length} content_preview=${E(c.join(""),200)}`),{content:c.length>0?c.join(""):null,usage:{prompt_tokens:i.usage.input_tokens,completion_tokens:i.usage.output_tokens,total_tokens:i.usage.input_tokens+i.usage.output_tokens},finish_reason:this.mapFinishReason(i.stop_reason),tool_calls:p.length>0?p:void 0,raw:i}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`str-${Date.now()}`,o=await this.toAnthropicMessages(e.messages,e.mediaOptions),r={model:e.model,messages:o.userMessages,system:o.system,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p,stream:!0};e.tools&&e.tools.length>0?(r.tools=e.tools.map(m=>({name:this.sanitizeToolName(m.function.name),description:m.function.description,input_schema:m.function.parameters})),e.tool_choice==="required"?r.tool_choice={type:"any"}:e.tool_choice==="none"?delete r.tools:r.tool_choice={type:"auto"},y(`[Anthropic][${t}] Sending ${r.tools?.length||0} tools with tool_choice: ${r.tool_choice?.type||"unset"}`),r.tools&&r.tools.length>0&&y(`[Anthropic][${t}] First tool: ${E(r.tools[0],800)}`)):y(`[Anthropic][${t}] NO TOOLS in request`),y(`[Anthropic][${t}] Stream request: model=${r.model}, messages=${r.messages.length}, tools=${r.tools?.length||0}, tool_choice=${r.tool_choice?.type??"unset"}`),V(t,"Anthropic",r.messages);let n=await this.client.messages.create(r,e.signal?{signal:e.signal}:void 0),a="",i="",c="",p=!1;for await(let m of n)m.type==="content_block_start"&&m.content_block?.type==="tool_use"&&(p=!0,a=m.content_block.id,i=m.content_block.name,c=""),m.type==="content_block_delta"&&(m.delta.type==="text_delta"?yield{delta:m.delta.text}:m.delta.type==="input_json_delta"&&p&&(c+=m.delta.partial_json)),m.type==="content_block_stop"&&p&&(y(`[Anthropic][${t}] Stream finish_reason=tool_calls accumulated_call=${i}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:a,name:this.restoreToolName(i,e.tools),arguments:JSON.parse(c||"{}")}]},p=!1),m.type==="message_stop"&&(ye(`[Anthropic][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"})}catch(t){throw this.handleError(t)}}async embed(e){throw new M("Embeddings are not strictly supported by the Anthropic API currently.")}async toAnthropicMessages(e,t={}){let o,r=[],{normalizeImagePart:n}=await Promise.resolve().then(()=>(Le(),rt));for(let a of e)if(a.role==="system"){if(typeof a.content=="string")o=a.content;else if(a.content!==null){let i=a.content.filter(c=>typeof c=="object"&&c.type==="text").map(c=>c.text).join(`
|
|
182
|
-
`);
|
|
183
|
-
`);c&&
|
|
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(Dr(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}`),Me("debug")&&y(`[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),y(`[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 G?e:new U(e.message||"Unknown provider error","UNKNOWN_PROVIDER_ERROR",500,e)}};l();l();import Gs from"@anthropic-ai/sdk";l();ae();var V=class{name;async getModels(){return[]}getDisplayName(){return this.name||this.constructor.name.replace(/Adapter$/,"")}supportsFileUpload(){return!1}async uploadFile(e){throw new j(`File upload API is not supported by ${this.getDisplayName()}`)}async deleteFile(e){throw new j(`File deletion API is not supported by ${this.getDisplayName()}`)}};ae();_();var uo=class extends V{client;constructor(e,t){super(),this.client=new Gs({apiKey:e,baseURL:t})}supportsFileUpload(){return!0}async uploadFile(e){try{let t=await import("fs");if(!e.filePath)throw new j("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"},y(`[Anthropic][${t}] Sending ${i.tools?.length||0} tools with tool_choice: ${i.tool_choice?.type||"unset"}`),i.tools&&i.tools.length>0&&y(`[Anthropic][${t}] First tool: ${A(i.tools[0],800)}`)):y(`[Anthropic][${t}] NO TOOLS in request`),y(`[Anthropic][${t}] generate() request: model=${i.model}, messages=${i.messages.length}, tools=${i.tools?.length||0}, tool_choice=${i.tool_choice?.type??"unset"}`),Z(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 y(`[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"},y(`[Anthropic][${t}] Sending ${r.tools?.length||0} tools with tool_choice: ${r.tool_choice?.type||"unset"}`),r.tools&&r.tools.length>0&&y(`[Anthropic][${t}] First tool: ${A(r.tools[0],800)}`)):y(`[Anthropic][${t}] NO TOOLS in request`),y(`[Anthropic][${t}] Stream request: model=${r.model}, messages=${r.messages.length}, tools=${r.tools?.length||0}, tool_choice=${r.tool_choice?.type??"unset"}`),Z(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&&(y(`[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"&&(xe(`[Anthropic][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"})}catch(t){throw this.handleError(t)}}async embed(e){throw new j("Embeddings are not strictly supported by the Anthropic API currently.")}async toAnthropicMessages(e,t={}){let o,r=[],{normalizeImagePart:s}=await Promise.resolve().then(()=>(Je(),pt));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 Gs.APIError){let t=e.message;return e.status===401?new we(t,e):e.status===429?new be(t,void 0,e):e.status&&e.status>=400&&e.status<500?new j(t,e):new U(t,"ANTHROPIC_ERROR",e.status||500,e)}return new U("Unknown Anthropic error","UNKNOWN",500,e)}};l();import{GoogleGenerativeAI as Dg}from"@google/generative-ai";ae();_();var fo=class extends V{genAI;constructor(e){super(),this.genAI=new Dg(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 j("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}}),f=Buffer.concat([Buffer.from(`--${p}\r
|
|
184
184
|
Content-Type: application/json\r
|
|
185
185
|
\r
|
|
186
186
|
${m}\r
|
|
187
187
|
`),Buffer.from(`--${p}\r
|
|
188
|
-
Content-Type: ${
|
|
188
|
+
Content-Type: ${i}\r
|
|
189
189
|
\r
|
|
190
190
|
`),r,Buffer.from(`\r
|
|
191
191
|
--${p}--\r
|
|
192
|
-
`)]),h=await fetch(c,{method:"POST",headers:{"Content-Type":`multipart/related; boundary=${p}`},body:f});if(!h.ok){let w=await h.text();throw new Error(`Gemini file upload failed: ${h.status} ${w}`)}let
|
|
192
|
+
`)]),h=await fetch(c,{method:"POST",headers:{"Content-Type":`multipart/related; boundary=${p}`},body:f});if(!h.ok){let w=await h.text();throw new Error(`Gemini file upload failed: ${h.status} ${w}`)}let b=await h.json();return{id:b.file?.name||b.name,url:b.file?.uri||b.uri}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{let t=this.genAI.apiKey,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(h=>({name:this.sanitizeToolName(h.function.name),description:h.function.description,parameters:this.sanitizeSchema(h.function.parameters)}))}],y(`[Gemini][${t}] Sending ${e.tools.length} tools`),e.tools.length>0&&y(`[Gemini][${t}] First tool: ${A(e.tools[0],800)}`)):y(`[Gemini][${t}] NO TOOLS in request`),y(`[Gemini][${t}] generate() request: model=${e.model}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),Z(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=[],f="";for(let h of p.candidates||[])for(let b of h.content?.parts||[])if(b.text&&(f+=b.text),b.functionCall){let w=b.functionCall;m.push({id:`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(w.name,e.tools),arguments:w.args||{}})}return y(`[Gemini][${t}] Response finish_reason=${m.length>0?"tool_calls":"stop"} tool_calls=${m.length} content_preview=${A(f,200)}`),{content:f||null,usage:{prompt_tokens:p.usageMetadata?.promptTokenCount||0,completion_tokens:p.usageMetadata?.candidatesTokenCount||0,total_tokens:p.usageMetadata?.totalTokenCount||0},finish_reason:m.length>0?"tool_calls":"stop",tool_calls:m.length>0?m:void 0,raw:p}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t={model:e.model,systemInstruction:this.extractSystemInstruction(e.messages)};e.tools&&e.tools.length>0&&(t.tools=[{functionDeclarations:e.tools.map(p=>({name:this.sanitizeToolName(p.function.name),description:p.function.description,parameters:this.sanitizeSchema(p.function.parameters)}))}]);let o=e.__toolpack_request_id||`str-${Date.now()}`;y(`[Gemini][${o}] Stream request: model=${e.model}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),e.tools&&e.tools.length>0&&y(`[Gemini][${o}] First tool: ${A(e.tools[0],800)}`),Z(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?(y(`[Gemini][${o}] Stream finish_reason=tool_calls name=${m.functionCall.name}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(m.functionCall.name,e.tools),arguments:m.functionCall.args||{}}]}):m.text&&(yield{delta:m.text});try{let m=p.text();m&&!p.candidates?.[0]?.content?.parts?.some(f=>f.text)&&(yield{delta:m})}catch{}}}catch(t){throw this.handleError(t)}}async embed(e){try{let t=this.genAI.getGenerativeModel({model:e.model});return Array.isArray(e.input)?{embeddings:await Promise.all(e.input.map(async r=>(await t.embedContent(r)).embedding.values))}:{embeddings:[(await t.embedContent(e.input)).embedding.values]}}catch(t){throw this.handleError(t)}}extractSystemInstruction(e){let t=e.filter(o=>o.role==="system");if(t.length!==0)return t.map(o=>typeof o.content=="string"?o.content:o.content===null?"":o.content.map(r=>r.text).join(`
|
|
193
193
|
`)).join(`
|
|
194
|
-
`)}async formatHistory(e,t={}){let o=e.filter(m=>m.role!=="system");if(o.length===0)return{history:[],lastUserMessage:""};let r=o[o.length-1],
|
|
195
|
-
`);h&&f.push({text:h})}for(let h of m.tool_calls)f.push({functionCall:{name:this.sanitizeToolName(h.function.name),args:typeof h.function.arguments=="string"?JSON.parse(h.function.arguments||"{}"):h.function.arguments}});return{role:"model",parts:f}}return{role:m.role==="user"?"user":"model",parts:await
|
|
196
|
-
`);f=w.pop()||"";for(let
|
|
197
|
-
Available models: ${e.map(r=>r.name).join(", ")||"(none)"}`);return e}async listModels(){try{let e=await
|
|
198
|
-
`;else if(
|
|
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(()=>(Je(),pt)),a=async m=>typeof m=="string"?[{text:m}]:m===null?[]:(await Promise.all(m.map(async h=>{if(h.type==="text")return{text:h.text};if(h.type==="image_data"||h.type==="image_file"||h.type==="image_url")try{let{data:b,mimeType:w}=await i(h);return{inlineData:{mimeType:w,data:b}}}catch{return h.type==="image_url"?{text:`[Image: ${h.image_url.url}]`}:{text:"[Unresolvable Image]"}}return null}))).filter(Boolean),c=await Promise.all(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 f=[];if(typeof m.content=="string"&&m.content)f.push({text:m.content});else if(Array.isArray(m.content)){let h=m.content.filter(b=>typeof b=="object"&&b.type==="text").map(b=>b.text).join(`
|
|
195
|
+
`);h&&f.push({text:h})}for(let h of m.tool_calls)f.push({functionCall:{name:this.sanitizeToolName(h.function.name),args:typeof h.function.arguments=="string"?JSON.parse(h.function.arguments||"{}"):h.function.arguments}});return{role:"model",parts:f}}return{role:m.role==="user"?"user":"model",parts:await 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 be(e.message,void 0,e):e.status>=400&&e.status<500?new j(e.message,e):e.message&&e.message.includes("API key")?new we(e.message,e):new U(e.message||"Gemini Error","GEMINI_ERROR",e.status||500,e)}};l();ae();import*as Te from"fs";import*as Or from"path";var Bs="toolpack.config.json",go=new Map;async function Ks(n){for(;go.has(n);)await go.get(n);let e,t=new Promise(o=>{e=o});return go.set(n,t),()=>{go.delete(n),e()}}function Oe(n){if(n&&Te.existsSync(n))return n;let e=Or.join(process.cwd(),Bs);return Te.existsSync(e)?e:null}function dt(n){if(!n)return null;try{let e=Te.readFileSync(n,"utf-8");return JSON.parse(e)}catch{return null}}var mt=null;function Ir(n){if(mt)return mt;let e=n||Oe();return mt=dt(e)||{},mt}function jr(){mt=null}function Eg(n){return(Ir(n).ollama?.models||[]).map(o=>({type:`ollama-${o.model.replace(/[:.]/g,"-")}`,model:o.model,label:o.label||o.model}))}function ho(n){return Ir(n).ollama?.baseUrl||"http://localhost:11434"}async function Ng(n){let{type:e,value:t,configPath:o}=n,r=o||Oe();r||(r=Or.join(process.cwd(),Bs));let s=await Ks(r);try{let i=dt(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{Te.writeFileSync(r,JSON.stringify(i,null,4),"utf-8")}catch(a){throw new G(`Failed to write bypass rule to config file: ${a instanceof Error?a.message:String(a)}`,"CONFIG_WRITE_ERROR")}jr()}finally{s()}}async function Ag(n){let{type:e,value:t,configPath:o}=n,r=o||Oe();if(!r)return;let s=await Ks(r);try{let i=dt(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{Te.writeFileSync(r,JSON.stringify(i,null,4),"utf-8")}catch(a){throw new G(`Failed to remove bypass rule from config file: ${a instanceof Error?a.message:String(a)}`,"CONFIG_WRITE_ERROR")}jr()}finally{s()}}l();l();ae();_();l();import Js from"http";function le(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=Js.request(c,m=>{let f=[];m.on("data",h=>f.push(h)),m.on("end",()=>{s({status:m.statusCode||0,body:Buffer.concat(f).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 Lr(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((h,b)=>{s=Js.request(p,h),s.on("error",b),s.on("timeout",()=>{s.destroy(),b(new Error("Stream request timed out"))}),s.write(JSON.stringify(t)),s.end()});if(m.statusCode&&m.statusCode>=400){let h="";for await(let b of m)h+=b.toString();throw new Error(`Ollama HTTP ${m.statusCode}: ${h}`)}let f="";for await(let h of m){if(i)break;let b=h.toString();if(f+=b,f.includes('"error"'))try{let x=JSON.parse(f.trim());if(x.error)throw new Error(`Ollama: ${x.error}`)}catch(x){if(x.message.startsWith("Ollama:"))throw x}let w=f.split(`
|
|
196
|
+
`);f=w.pop()||"";for(let x of w)x.trim()&&(yield x)}f.trim()&&!i&&(yield f.trim())}(),abort:()=>{i=!0,s&&s.destroy()}}}var Ie=class extends V{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 j(`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 le(this.baseUrl,"/api/tags","GET",void 0,5e3);if(e.status!==200)throw new U(`Ollama returned status ${e.status}`,"OLLAMA_ERROR",e.status);return JSON.parse(e.body).models||[]}catch(e){throw e instanceof U?e:new Ne(`Cannot connect to Ollama at ${this.baseUrl}. Is Ollama running? (ollama serve)`,e)}}async isAvailable(){try{return await le(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}})),y(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&y(`[Ollama][${t}] First tool: ${A(e.tools[0],800)}`),y(`[Ollama][${t}] NO TOOLS in request`)),y(`[Ollama][${t}] generate() request: model=${r}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),Z(t,"Ollama",e.messages);try{let i=await le(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 y(`[Ollama][${t}] Response finish_reason=${p.finish_reason} tool_calls=${c.length} content_preview=${A(p.content,200)}`),p}catch(i){throw i instanceof U?i:new Ne(`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}})),y(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&y(`[Ollama][${t}] First tool: ${A(e.tools[0],800)}`),y(`[Ollama][${t}] NO TOOLS in request`)),y(`[Ollama][${t}] Stream request: model=${r}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),Z(t,"Ollama",e.messages);let{stream:i}=Lr(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||{}}));y(`[Ollama][${t}] Stream finish_reason=tool_calls name=${p[0]?.name}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:p}}if(c.done&&!c.message?.content&&!c.message?.tool_calls){xe(`[Ollama][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"};return}}catch{}}catch(a){throw new Ne(`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;y(`[Ollama][${t}] Embedding request: model=${r}, inputs=${o.length}`);try{let s=await le(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 U?s:new Ne(`Embedding failed for Ollama model "${r}": ${s.message}`,s)}}async disconnect(){}async toOllamaMessage(e,t={}){let o="",r=[],{normalizeImagePart:s}=await Promise.resolve().then(()=>(Je(),pt));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
199
|
`:o+=`[Unresolvable Image]
|
|
200
|
-
`}o=o.trim()}let a={role:e.role,content:o};return r.length>0&&(a.images=r),e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0?a.tool_calls=e.tool_calls.map(i=>({function:{name:this.sanitizeToolName(i.function.name),arguments:typeof i.function.arguments=="string"?JSON.parse(i.function.arguments||"{}"):i.function.arguments}})):e.role==="tool"&&(a.content=o||JSON.stringify(e.content),e.name&&(a.tool_name=this.sanitizeToolName(e.name))),a}handleHttpError(e,t){let o=`Ollama error (HTTP ${e})`;try{let r=JSON.parse(t);r.error&&(o=`Ollama: ${r.error}`)}catch{}return e===404?new M(`Model not found: ${o}`):new F(o,"OLLAMA_ERROR",e)}};l();var it=class extends Y{baseUrl;timeout;adapterCache=new Map;capabilityCache=new Map;constructor(e){super(),this.baseUrl=e?.baseUrl||"http://localhost:11434",this.timeout=12e4}getDisplayName(){return"Ollama"}async getModels(){let e;try{let t=await ne(this.baseUrl,"/api/tags","GET",void 0,5e3);if(t.status!==200)return[];e=JSON.parse(t.body).models||[]}catch{return[]}return Promise.all(e.map(t=>this.buildModelInfo(t)))}async generate(e){return this.getAdapterForModel(e.model).generate(this.stripToolsIfNeeded(e))}async*stream(e){yield*this.getAdapterForModel(e.model).stream(this.stripToolsIfNeeded(e))}async embed(e){return this.getAdapterForModel(e.model).embed(e)}async disconnect(){this.adapterCache.clear(),this.capabilityCache.clear()}stripToolsIfNeeded(e){let t=this.capabilityCache.get(e.model);if(t&&!t.toolCalling&&e.tools&&e.tools.length>0){let{tools:o,tool_choice:r,...n}=e,a=n,i={role:"system",content:"You do not have access to any tools or functions. Do not attempt to call tools, output tool invocations, or reference tool usage. Answer the user directly using only your own knowledge."};return a.messages=[...a.messages,i],a}return e}getAdapterForModel(e){let t=this.adapterCache.get(e);return t||(t=new De({model:e,baseUrl:this.baseUrl,timeout:this.timeout}),this.adapterCache.set(e,t)),t}async buildModelInfo(e){let t=!1,o=!1,r=!1;try{let i=await ne(this.baseUrl,"/api/show","POST",{model:e.name},3e3);if(i.status===200){let p=(JSON.parse(i.body).details?.families||[]).map(m=>m.toLowerCase());o=p.some(m=>["clip","mllama"].includes(m)),r=p.some(m=>m.includes("bert")||m.includes("nomic"))}}catch{}t=await this.probeToolSupport(e.name);let n=e.name.toLowerCase();o||(o=["llava","vision","bakllava","moondream"].some(c=>n.includes(c))),r||(r=["nomic-embed","mxbai-embed","all-minilm","bge-","snowflake-arctic-embed"].some(c=>n.includes(c)));let a={toolCalling:t,vision:o,embeddings:r};return this.capabilityCache.set(e.name,a),{id:e.name,displayName:e.name,capabilities:{chat:!0,streaming:!0,toolCalling:t,embeddings:r,vision:o}}}async probeToolSupport(e){try{let t=await ne(this.baseUrl,"/api/chat","POST",{model:e,messages:[{role:"user",content:"hi"}],tools:[{type:"function",function:{name:"__probe",description:"probe",parameters:{type:"object",properties:{}}}}],stream:!1},1e4);return t.status>=400?!1:!JSON.parse(t.body).error}catch{return!1}}};l();var Nr=[{model:"qwen2.5-coder:3b",label:"Qwen 2.5 Coder 3B",params:"3B",size:"~2GB",selectorCapability:5,description:"Best code understanding at small size. Excellent HTML/CSS comprehension."},{model:"phi3:mini",label:"Phi-3 Mini",params:"3.8B",size:"~2.3GB",selectorCapability:4,description:"Strong reasoning for its size. Good at structured output."},{model:"codegemma:2b",label:"CodeGemma 2B",params:"2B",size:"~1.4GB",selectorCapability:4,description:"Compact code model from Google. Fast inference."},{model:"deepseek-coder:1.3b",label:"DeepSeek Coder 1.3B",params:"1.3B",size:"~0.8GB",selectorCapability:3,description:"Smallest viable option. Very fast but less accurate."},{model:"qwen2.5-coder:7b",label:"Qwen 2.5 Coder 7B",params:"7B",size:"~4.5GB",selectorCapability:5,description:"Higher accuracy than 3B variant. Requires more RAM/VRAM."},{model:"codellama:7b",label:"Code Llama 7B",params:"7B",size:"~3.8GB",selectorCapability:4,description:"Meta code model. Solid HTML/CSS understanding."}];function pg(){return Nr[0].model}function mg(s){let e=s.toLowerCase();return Nr.some(t=>t.model.toLowerCase()===e||t.model.split(":")[0].toLowerCase()===e.split(":")[0].toLowerCase())}function dg(){return[...Nr]}l();import $s from"openai";ce();_();var po=class extends Y{client;constructor(e,t){super(),this.client=new $s({apiKey:e,baseURL:t,timeout:6e4,maxRetries:2})}supportsFileUpload(){return!0}async uploadFile(e){try{let t=await import("fs");if(!e.filePath)throw new M("OpenAI uploadFile requires a filePath.");return{id:(await this.client.files.create({file:t.createReadStream(e.filePath),purpose:e.purpose||"vision"})).id}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{await this.client.files.delete(e)}catch(t){throw this.handleError(t)}}getDisplayName(){return"OpenAI"}async getModels(){return[{id:"gpt-4.1-mini",displayName:"GPT-4.1 Mini",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1047576,maxOutputTokens:32768,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:null,costTier:"low"},{id:"gpt-4.1",displayName:"GPT-4.1",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1047576,maxOutputTokens:32768,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:null,costTier:"medium"},{id:"gpt-5.1",displayName:"GPT-5.1",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:4e5,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"medium"},{id:"gpt-5.2",displayName:"GPT-5.2",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:4e5,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"high"},{id:"gpt-5.4",displayName:"GPT-5.4",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:105e4,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"high"},{id:"gpt-5.4-pro",displayName:"GPT-5.4 Pro",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:105e4,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"extended",costTier:"premium"}]}sanitizeToolName(e){return e.replace(/\./g,"_")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,r={messages:await Promise.all(e.messages.map(f=>this.toOpenAIMessage(f,e.mediaOptions))),model:e.model,temperature:e.temperature,max_tokens:e.max_tokens,top_p:e.top_p,response_format:e.response_format==="json_object"?{type:"json_object"}:void 0,stream:!1},n=new Map;e.tools&&e.tools.length>0&&(r.tools=e.tools.map(f=>{let h=this.sanitizeToolName(f.function.name);return n.set(h,f.function.name),{type:"function",function:{name:h,description:f.function.description,parameters:f.function.parameters}}}),r.tool_choice=e.tool_choice||"auto",y(`[OpenAI][${t}] Sending ${r.tools.length} tools with tool_choice: ${r.tool_choice}`),y(`[OpenAI][${t}] First tool: ${E(r.tools[0],800)}`)),y(`[OpenAI][${t}] Request params: ${E({model:r.model,messages_count:r.messages.length,has_tools:!!r.tools,tools_count:r.tools?.length,tool_choice:r.tool_choice},800)}`),V(t,"OpenAI",r.messages);let a=await this.client.chat.completions.create(r,e.signal?{signal:e.signal}:void 0);ye(`[OpenAI][${t}] Raw completion: ${JSON.stringify(a)}`);let i=a.choices[0].message;y(`[OpenAI][${t}] Response: finish_reason=${a.choices[0].finish_reason}`),y(`[OpenAI][${t}] Response has tool_calls: ${!!i.tool_calls}, count: ${i.tool_calls?.length||0}`),y(`[OpenAI][${t}] Response content: ${JSON.stringify(i.content)}`),i.content&&y(`[OpenAI][${t}] Response content preview: ${E(i.content,200)}`);let c=a.choices[0],p,m=c.message.tool_calls;return m&&m.length>0&&(p=m.map(f=>({id:f.id,name:n.get(f.function.name)||f.function.name,arguments:JSON.parse(f.function.arguments)}))),{content:c.message.content,usage:a.usage?{prompt_tokens:a.usage.prompt_tokens,completion_tokens:a.usage.completion_tokens,total_tokens:a.usage.total_tokens}:void 0,finish_reason:c.finish_reason,tool_calls:p,raw:a}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`str-${Date.now()}`,r={messages:await Promise.all(e.messages.map(c=>this.toOpenAIMessage(c,e.mediaOptions))),model:e.model,temperature:e.temperature,max_tokens:e.max_tokens,top_p:e.top_p,response_format:e.response_format==="json_object"?{type:"json_object"}:void 0,stream:!0},n=new Map;e.tools&&e.tools.length>0?(r.tools=e.tools.map(c=>{let p=this.sanitizeToolName(c.function.name);return n.set(p,c.function.name),{type:"function",function:{name:p,description:c.function.description,parameters:c.function.parameters}}}),r.tool_choice=e.tool_choice||"auto",y(`[OpenAI][${t}] Sending ${r.tools.length} tools with tool_choice: ${r.tool_choice}`),y(`[OpenAI][${t}] First tool: ${E(r.tools[0],800)}`)):y(`[OpenAI][${t}] NO TOOLS in request`),y(`[OpenAI][${t}] Stream request: model=${r.model}, messages=${r.messages.length}, tools=${r.tools?.length||0}, tool_choice=${r.tool_choice??"unset"}`),V(t,"OpenAI",r.messages);let a=await this.client.chat.completions.create(r,e.signal?{signal:e.signal}:void 0),i=new Map;for await(let c of a){let p=c.choices[0];if(p.finish_reason&&ye(`[OpenAI][${t}] Stream chunk finish_reason=${p.finish_reason}`),p.delta.tool_calls)for(let m of p.delta.tool_calls){let f=m.index;i.has(f)||i.set(f,{id:m.id||"",name:m.function?.name||"",args:""});let h=i.get(f);m.id&&(h.id=m.id),m.function?.name&&(h.name=m.function.name),m.function?.arguments&&(h.args+=m.function.arguments),ye(`[OpenAI][${t}] tool_call_delta idx=${f} id=${m.id||h.id||""} name=${m.function?.name||h.name||""} args_delta=${E(m.function?.arguments||"",200)}`)}if(p.delta.content&&(yield{delta:p.delta.content,finish_reason:p.finish_reason,usage:c.usage}),!p.delta.content&&p.finish_reason&&p.finish_reason!=="tool_calls"&&(yield{delta:"",finish_reason:p.finish_reason,usage:c.usage}),p.finish_reason==="tool_calls"&&i.size>0){let m=Array.from(i.values()).map(f=>({id:f.id,name:n.get(f.name)||f.name,arguments:JSON.parse(f.args||"{}")}));y(`[OpenAI][${t}] Stream finish_reason=tool_calls accumulated_calls=${m.length} names=${m.map(f=>f.name).join(", ")}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:m}}}}catch(t){throw this.handleError(t)}}async embed(e){try{let t=typeof e.input=="string"?[e.input]:e.input,o=await this.client.embeddings.create({model:e.model,input:t});return{embeddings:o.data.map(r=>r.embedding),usage:o.usage}}catch(t){throw this.handleError(t)}}async toOpenAIMessage(e,t={}){if(e.role==="tool"&&e.tool_call_id)return{role:"tool",tool_call_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content??"")};if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0)return{role:"assistant",content:typeof e.content=="string"?e.content:"",tool_calls:e.tool_calls.map(n=>({id:n.id,type:"function",function:{name:this.sanitizeToolName(n.function.name),arguments:n.function.arguments}}))};if(typeof e.content=="string")return{role:e.role,content:e.content};if(e.content===null||e.content===void 0)return{role:e.role,content:""};let{normalizeImagePart:o}=await Promise.resolve().then(()=>(Le(),rt)),r=await Promise.all(e.content.map(async n=>{if(n.type==="text")return{type:"text",text:n.text};if(n.type==="image_url")return{type:"image_url",image_url:{url:n.image_url.url}};if(n.type==="image_data"||n.type==="image_file"){let{data:a,mimeType:i}=await o(n);return{type:"image_url",image_url:{url:`data:${i};base64,${a}`}}}return null}));return{role:e.role,content:r.filter(Boolean)}}handleError(e){if(e instanceof $s.APIError){let t=e.message;return e.status===401?new ge(t,e):e.status===429?new he(t,void 0,e):e.status&&e.status>=400&&e.status<500?new M(t,e):new F(t,e.code||"OPENAI_ERROR",e.status||500,e)}return new F("Unknown error","UNKNOWN",500,e)}};Le();l();tt();l();tt();var Qt=class{tools=new Map;projects=new Map;config=z;register(e){this.tools.set(e.name,e)}registerCustom(e){this.tools.set(e.name,e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getNames(){return Array.from(this.tools.keys())}getByCategory(e){return Array.from(this.tools.values()).filter(t=>t.category===e)}getEnabled(){if(this.config.enabledTools.length===0&&this.config.enabledToolCategories.length===0)return Array.from(this.tools.values());let e=this.getByNames(this.config.enabledTools),t=this.getByCategories(this.config.enabledToolCategories),o=new Set,r=[];for(let n of[...e,...t])o.has(n.name)||(o.add(n.name),r.push(n));return r}getSchemas(e){return(e?e.map(o=>this.tools.get(o)).filter(Boolean):this.getEnabled()).map(o=>({name:o.name,displayName:o.displayName,description:o.description,parameters:o.parameters,category:o.category}))}getByNames(e){return e.map(t=>this.tools.get(t)).filter(Boolean)}getByCategories(e){let t=new Set(e);return Array.from(this.tools.values()).filter(o=>t.has(o.category))}getCategories(){let e=new Set;for(let t of this.tools.values())e.add(t.category);return Array.from(e)}getAll(){return Array.from(this.tools.values())}setConfig(e){this.config=e}getConfig(){return this.config}get size(){return this.tools.size}async validateDependencies(e){let t=e.dependencies;if(!t||Object.keys(t).length===0)return[];let o=[];for(let r of Object.keys(t))try{await import(r)}catch{o.push(r)}return o}async loadProject(e){let t=await this.validateDependencies(e);if(t.length>0)throw new Error(`Tool project "${e.manifest.name}" has missing dependencies: ${t.join(", ")}. Install them with: npm install ${t.join(" ")}`);this.projects.set(e.manifest.name,e);for(let o of e.tools)this.register(o)}async loadProjects(e){for(let t of e)await this.loadProject(t)}getProject(e){return this.projects.get(e)}getProjects(){return Array.from(this.projects.values())}getProjectNames(){return Array.from(this.projects.keys())}async loadBuiltIn(){let{fsToolsProject:e}=await Promise.resolve().then(()=>(Vr(),qa)),{execToolsProject:t}=await Promise.resolve().then(()=>(nn(),_l)),{systemToolsProject:o}=await Promise.resolve().then(()=>(dn(),lc)),{httpToolsProject:r}=await Promise.resolve().then(()=>(wn(),Jc)),{webToolsProject:n}=await Promise.resolve().then(()=>(En(),um)),{codingToolsProject:a}=await Promise.resolve().then(()=>(Kn(),Xd)),{gitToolsProject:i}=await Promise.resolve().then(()=>(Qn(),_u)),{diffToolsProject:c}=await Promise.resolve().then(()=>(Yn(),Wu)),{dbToolsProject:p}=await Promise.resolve().then(()=>(Xn(),hf)),{cloudToolsProject:m}=await Promise.resolve().then(()=>(Zn(),_f));await this.loadProjects([e,t,o,r,n,a,i,c,p,m])}};Tn();l();_();function Wy(s){if(!s.key||!/^[a-z0-9-]+$/.test(s.key))throw new Error(`Invalid tool project key: "${s.key}". Must be non-empty, lowercase, and contain no spaces (use hyphens).`);if(!s.name.trim())throw new Error("Tool project name cannot be empty.");if(!s.tools||s.tools.length===0)throw new Error("Tool project must contain at least one tool.");for(let t of s.tools){if(!t.name)throw new Error("Tool is missing a name.");if(!t.description)throw new Error(`Tool "${t.name}" is missing a description.`);if(!t.parameters)throw new Error(`Tool "${t.name}" is missing parameters.`);if(typeof t.execute!="function")throw new Error(`Tool "${t.name}" is missing an execute function.`);t.category!==s.category&&D(`[Toolpack] Tool "${t.name}" has category "${t.category}" which does not match project category "${s.category}".`)}let e=s.tools.map(t=>t.name);return{manifest:{key:s.key,name:s.name,displayName:s.displayName,version:s.version,description:s.description,author:s.author,repository:s.repository,category:s.category,tools:e},dependencies:s.dependencies,tools:s.tools}}Vr();nn();dn();wn();En();Kn();Qn();Yn();Xn();Zn();l();l();_();import{spawn as Gy}from"child_process";import{EventEmitter as By}from"events";var hr=class extends Error{constructor(e,t){super(`MCP request timed out after ${t}ms: ${e}`),this.name="McpTimeoutError"}},me=class extends Error{constructor(t,o){super(t);this.exitCode=o;this.name="McpConnectionError"}exitCode},Yt=class extends By{constructor(t){super();this.config=t;this.defaultTimeoutMs=t.requestTimeoutMs??3e4,this.autoReconnect=t.autoReconnect??!1,this.maxReconnectAttempts=t.maxReconnectAttempts??3,this.reconnectDelayMs=t.reconnectDelayMs??1e3}config;process=null;messageQueue=new Map;nextId=1;buffer="";_connected=!1;_shuttingDown=!1;_reconnectAttempts=0;defaultTimeoutMs;autoReconnect;maxReconnectAttempts;reconnectDelayMs;get connected(){return this._connected&&this.process!==null}async connect(){if(this._shuttingDown)throw new me("Client is shutting down");return new Promise((t,o)=>{try{if(this.buffer="",this.process=Gy(this.config.command,this.config.args||[],{env:{...process.env,...this.config.env},stdio:["pipe","pipe","pipe"]}),!this.process.stdout||!this.process.stdin)throw new me("Failed to spawn MCP server: stdout/stdin unavailable");this.process.stdout.on("data",r=>{this.handleData(r)}),this.process.stderr&&this.process.stderr.on("data",r=>{D(`[MCP server stderr] ${r.toString().trim()}`)}),this.process.on("error",r=>{this._connected=!1,this.emit("error",r)}),this.process.on("exit",r=>{let n=this._connected;this._connected=!1,this.process=null,this.rejectAllPending(new me(`MCP server exited with code ${r}`,r)),this.emit("close",r),n&&!this._shuttingDown&&this.autoReconnect&&this.attemptReconnect()}),this._connected=!0,this._reconnectAttempts=0,setTimeout(t,500)}catch(r){o(r)}})}async attemptReconnect(){if(this._reconnectAttempts>=this.maxReconnectAttempts){this.emit("reconnect_failed",this._reconnectAttempts);return}this._reconnectAttempts++;let t=this._reconnectAttempts;if(this.emit("reconnecting",{attempt:t,max:this.maxReconnectAttempts}),await new Promise(o=>setTimeout(o,this.reconnectDelayMs*t)),!this._shuttingDown)try{await this.connect(),this.emit("reconnected",{attempt:t})}catch(o){this.emit("reconnect_error",{attempt:t,error:o})}}handleData(t){this.buffer+=t.toString();let o;for(;(o=this.buffer.indexOf(`
|
|
201
|
-
`)
|
|
202
|
-
|
|
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 j(`Model not found: ${o}`):new U(o,"OLLAMA_ERROR",e)}};l();var ut=class extends V{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 le(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 Ie({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 le(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 le(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 Fr=[{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 Mg(){return Fr[0].model}function Og(n){let e=n.toLowerCase();return Fr.some(t=>t.model.toLowerCase()===e||t.model.split(":")[0].toLowerCase()===e.split(":")[0].toLowerCase())}function Ig(){return[...Fr]}l();import Hs from"openai";ae();_();var yo=class extends V{client;constructor(e,t){super(),this.client=new Hs({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 j("OpenAI uploadFile requires a filePath.");return{id:(await this.client.files.create({file:t.createReadStream(e.filePath),purpose:e.purpose||"vision"})).id}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{await this.client.files.delete(e)}catch(t){throw this.handleError(t)}}getDisplayName(){return"OpenAI"}async getModels(){return[{id:"gpt-4.1-mini",displayName:"GPT-4.1 Mini",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1047576,maxOutputTokens:32768,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:null,costTier:"low"},{id:"gpt-4.1",displayName:"GPT-4.1",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1047576,maxOutputTokens:32768,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:null,costTier:"medium"},{id:"gpt-5.1",displayName:"GPT-5.1",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:4e5,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"medium"},{id:"gpt-5.2",displayName:"GPT-5.2",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:4e5,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"high"},{id:"gpt-5.4",displayName:"GPT-5.4",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:105e4,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"high"},{id:"gpt-5.4-pro",displayName:"GPT-5.4 Pro",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:105e4,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"extended",costTier:"premium"}]}sanitizeToolName(e){return e.replace(/\./g,"_")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,r={messages:await Promise.all(e.messages.map(f=>this.toOpenAIMessage(f,e.mediaOptions))),model:e.model,temperature:e.temperature,max_tokens:e.max_tokens,top_p:e.top_p,response_format:e.response_format==="json_object"?{type:"json_object"}:void 0,stream:!1},s=new Map;e.tools&&e.tools.length>0&&(r.tools=e.tools.map(f=>{let h=this.sanitizeToolName(f.function.name);return s.set(h,f.function.name),{type:"function",function:{name:h,description:f.function.description,parameters:f.function.parameters}}}),r.tool_choice=e.tool_choice||"auto",y(`[OpenAI][${t}] Sending ${r.tools.length} tools with tool_choice: ${r.tool_choice}`),y(`[OpenAI][${t}] First tool: ${A(r.tools[0],800)}`)),y(`[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)}`),Z(t,"OpenAI",r.messages);let i=await this.client.chat.completions.create(r,e.signal?{signal:e.signal}:void 0);xe(`[OpenAI][${t}] Raw completion: ${JSON.stringify(i)}`);let a=i.choices[0].message;y(`[OpenAI][${t}] Response: finish_reason=${i.choices[0].finish_reason}`),y(`[OpenAI][${t}] Response has tool_calls: ${!!a.tool_calls}, count: ${a.tool_calls?.length||0}`),y(`[OpenAI][${t}] Response content: ${JSON.stringify(a.content)}`),a.content&&y(`[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(f=>({id:f.id,name:s.get(f.function.name)||f.function.name,arguments:JSON.parse(f.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",y(`[OpenAI][${t}] Sending ${r.tools.length} tools with tool_choice: ${r.tool_choice}`),y(`[OpenAI][${t}] First tool: ${A(r.tools[0],800)}`)):y(`[OpenAI][${t}] NO TOOLS in request`),y(`[OpenAI][${t}] Stream request: model=${r.model}, messages=${r.messages.length}, tools=${r.tools?.length||0}, tool_choice=${r.tool_choice??"unset"}`),Z(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&&xe(`[OpenAI][${t}] Stream chunk finish_reason=${p.finish_reason}`),p.delta.tool_calls)for(let m of p.delta.tool_calls){let f=m.index;a.has(f)||a.set(f,{id:m.id||"",name:m.function?.name||"",args:""});let h=a.get(f);m.id&&(h.id=m.id),m.function?.name&&(h.name=m.function.name),m.function?.arguments&&(h.args+=m.function.arguments),xe(`[OpenAI][${t}] tool_call_delta idx=${f} id=${m.id||h.id||""} name=${m.function?.name||h.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(f=>({id:f.id,name:s.get(f.name)||f.name,arguments:JSON.parse(f.args||"{}")}));y(`[OpenAI][${t}] Stream finish_reason=tool_calls accumulated_calls=${m.length} names=${m.map(f=>f.name).join(", ")}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:m}}}}catch(t){throw this.handleError(t)}}async embed(e){try{let t=typeof e.input=="string"?[e.input]:e.input,o=await this.client.embeddings.create({model:e.model,input:t});return{embeddings:o.data.map(r=>r.embedding),usage:o.usage}}catch(t){throw this.handleError(t)}}async toOpenAIMessage(e,t={}){if(e.role==="tool"&&e.tool_call_id)return{role:"tool",tool_call_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content??"")};if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0)return{role:"assistant",content:typeof e.content=="string"?e.content:"",tool_calls:e.tool_calls.map(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(()=>(Je(),pt)),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 Hs.APIError){let t=e.message;return e.status===401?new we(t,e):e.status===429?new be(t,void 0,e):e.status&&e.status>=400&&e.status<500?new j(t,e):new U(t,e.code||"OPENAI_ERROR",e.status||500,e)}return new U("Unknown error","UNKNOWN",500,e)}};Je();l();lt();l();lt();var oo=class{tools=new Map;projects=new Map;config=z;register(e){this.tools.set(e.name,e)}registerCustom(e){this.tools.set(e.name,e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getNames(){return Array.from(this.tools.keys())}getByCategory(e){return Array.from(this.tools.values()).filter(t=>t.category===e)}getEnabled(){if(this.config.enabledTools.length===0&&this.config.enabledToolCategories.length===0)return Array.from(this.tools.values());let e=this.getByNames(this.config.enabledTools),t=this.getByCategories(this.config.enabledToolCategories),o=new Set,r=[];for(let 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(()=>(nn(),al)),{execToolsProject:t}=await Promise.resolve().then(()=>(dn(),zl)),{systemToolsProject:o}=await Promise.resolve().then(()=>(bn(),Rc)),{httpToolsProject:r}=await Promise.resolve().then(()=>(Sn(),dp)),{webToolsProject:s}=await Promise.resolve().then(()=>(Ln(),Mm)),{codingToolsProject:i}=await Promise.resolve().then(()=>(ts(),bu)),{gitToolsProject:a}=await Promise.resolve().then(()=>(os(),zu)),{diffToolsProject:c}=await Promise.resolve().then(()=>(rs(),pf)),{dbToolsProject:p}=await Promise.resolve().then(()=>(ss(),jf)),{cloudToolsProject:m}=await Promise.resolve().then(()=>(is(),zf));await this.loadProjects([e,t,o,r,s,i,a,c,p,m])}};_n();l();_();function dw(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}}nn();dn();bn();Sn();Ln();ts();os();rs();ss();is();l();l();_();import{execFileSync as uw}from"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 fw(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}`)),y(`[k8s-tools] execute: kubectl ${n.join(" ")}`);try{return uw("kubectl",n,{input:e,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],timeout:t})||"(kubectl completed with no output)"}catch(o){return fw(o)}}function gw(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 ie="kubernetes";function Qf(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 as={name:"k8s.list_pods",displayName:"Kubernetes List Pods",description:"List pods in the current or a specific Kubernetes namespace.",category:ie,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=Qf(n.labelSelector)??n.labels;return o&&e.push("-l",N(o,"labels")),X(e)}},ls={name:"k8s.describe",displayName:"Kubernetes Describe Resource",description:"Describe a Kubernetes resource or resource instance.",category:ie,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)}},cs={name:"k8s.get_logs",displayName:"Kubernetes Get Pod Logs",description:"Fetch logs from a Kubernetes pod, optionally from a specific container.",category:ie,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)}},ps={name:"k8s.apply_manifest",displayName:"Kubernetes Apply Manifest",description:"Apply a Kubernetes manifest from a file path or inline YAML content.",category:ie,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)}},ms={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:ie,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)}},ds={name:"k8s.list_services",displayName:"Kubernetes List Services",description:"List services in the current or a specific Kubernetes namespace.",category:ie,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)}},us={name:"k8s.list_deployments",displayName:"Kubernetes List Deployments",description:"List deployments in the current or a specific Kubernetes namespace.",category:ie,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=Qf(n.labelSelector)??n.labels;return o&&e.push("-l",N(o,"labels")),X(e)}},fs={name:"k8s.get_config_map",displayName:"Kubernetes Get ConfigMap",description:"Retrieve a ConfigMap from a Kubernetes namespace.",category:ie,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)}},gs={name:"k8s.switch_context",displayName:"Kubernetes Switch Context",description:"Switch the active kubectl context to a different Kubernetes cluster or namespace configuration.",category:ie,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")])},hs={name:"k8s.get_namespaces",displayName:"Kubernetes Get Namespaces",description:"List namespaces in the current Kubernetes context.",category:ie,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"])},ys={name:"k8s.wait_for_deployment",displayName:"Kubernetes Wait For Deployment",description:"Wait for a Kubernetes deployment to complete its rollout.",category:ie,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,gw(e))}};var hw={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:[as,ls,cs,ps,ms,ds,us,fs,gs,hs,ys]};l();l();_();import{spawn as yw}from"child_process";import{EventEmitter as ww}from"events";var Pr=class extends Error{constructor(e,t){super(`MCP request timed out after ${t}ms: ${e}`),this.name="McpTimeoutError"}},fe=class extends Error{constructor(t,o){super(t);this.exitCode=o;this.name="McpConnectionError"}exitCode},ro=class extends ww{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 fe("Client is shutting down");if(this.buffer="",this.process=yw(this.config.command,this.config.args||[],{env:{...process.env,...this.config.env},stdio:["pipe","pipe","pipe"]}),!this.process.stdout||!this.process.stdin)throw new fe("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 fe(`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 fe("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 f=this.messageQueue.get(s);f&&(this.messageQueue.delete(s),f.reject(new Pr(t,i)))},i)),this.messageQueue.set(s,{resolve:c,reject:p,timer:m});try{this.process.stdin.write(JSON.stringify(a)+`
|
|
207
|
+
`)}catch(f){m&&clearTimeout(m),this.messageQueue.delete(s),p(f)}})}async disconnect(t=3e3){if(this._shuttingDown=!0,this.rejectAllPending(new fe("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 fe("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 Cr=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 ro({...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 ws(n){let e=new Cr(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 bs(n){"mcpManager"in n&&await n.mcpManager.disconnectAll()}l();l();l();l();var xs=`
|
|
203
208
|
You are a planning assistant. Given a user request, create a detailed step-by-step plan.
|
|
204
209
|
|
|
205
210
|
Rules:
|
|
@@ -212,7 +217,7 @@ Rules:
|
|
|
212
217
|
7. Steps should produce concrete outputs, not ask questions or wait for user input
|
|
213
218
|
8. ALWAYS include at least one step, even for simple questions. For simple factual questions, create a single step like "Provide the answer to [question]"
|
|
214
219
|
9. When a step uses information gathered by a previous step, set "dependsOn" to that step's number and phrase the description as "Using the [data] from step N, [do something]" instead of gathering it again
|
|
215
|
-
10.
|
|
220
|
+
10. For plans with MORE than 2 steps, the final step must synthesize the workflow's results into a concise deliverable, avoiding redundant word-for-word repetition of earlier step outputs. For plans with 1-2 steps, no synthesis step is needed.
|
|
216
221
|
11. The exact result MUST be valid JSON matching this schema:
|
|
217
222
|
{
|
|
218
223
|
"summary": "Brief description of the overall goal",
|
|
@@ -225,12 +230,7 @@ Rules:
|
|
|
225
230
|
}
|
|
226
231
|
]
|
|
227
232
|
}
|
|
228
|
-
`,
|
|
229
|
-
Result: ${a}`)}else r.status==="failed"?o.push(`Step ${r.number}: ${r.description}
|
|
230
|
-
Failed: ${r.result?.error||"Unknown error"}`):r.status==="skipped"&&o.push(`Step ${r.number}: ${r.description}
|
|
231
|
-
Skipped.`)}return o.length===0?"No previous steps.":o.join(`
|
|
232
|
-
|
|
233
|
-
`)}};_();var zy=`
|
|
233
|
+
`,Ts=`
|
|
234
234
|
You are executing step {stepNumber} of a plan.
|
|
235
235
|
|
|
236
236
|
Plan summary: {planSummary}
|
|
@@ -244,15 +244,57 @@ Execute this step now. Use the available tools as needed to accomplish this spec
|
|
|
244
244
|
Make reasonable assumptions if any details are ambiguous - do NOT ask the user for clarification or additional input.
|
|
245
245
|
Produce concrete results based on the information available.
|
|
246
246
|
If you cannot complete this step, explain why.
|
|
247
|
-
If you need to add additional steps to the plan, indicate that clearly in your response.
|
|
248
247
|
|
|
249
248
|
IMPORTANT: Your response should be written as if you are directly answering the user.
|
|
250
249
|
Do NOT mention steps, plans, workflow details, or internal process in your response.
|
|
251
250
|
Do NOT say things like "Step 1 is complete" or "proceeding to the next step".
|
|
252
251
|
Just provide the actual answer or result naturally.
|
|
253
|
-
`,
|
|
252
|
+
`,CA={name:"Direct",planning:{enabled:!1},steps:{enabled:!1},progress:{enabled:!0}},Yf={name:"Agent",planning:{enabled:!0,planningPrompt:xs},steps:{enabled:!0,retryOnFailure:!0,allowDynamicSteps:!1,stepPrompt:Ts},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},bw=`
|
|
253
|
+
Create a step-by-step plan for this coding task.
|
|
254
|
+
|
|
255
|
+
Rules:
|
|
256
|
+
1. Break into actionable steps using tools (read/write files, search code)
|
|
257
|
+
2. Each step executes independently without user input
|
|
258
|
+
3. Order by dependencies
|
|
259
|
+
4. Individual steps: be concise and technical. No conversational filler.
|
|
260
|
+
5. For >2 steps, final step summarizes changes with conversational explanation
|
|
261
|
+
6. Output valid JSON: {"summary": "...", "steps": [{...}]}
|
|
262
|
+
|
|
263
|
+
JSON Schema:
|
|
264
|
+
{
|
|
265
|
+
"summary": "Brief description of the overall goal",
|
|
266
|
+
"steps": [
|
|
267
|
+
{
|
|
268
|
+
"number": 1,
|
|
269
|
+
"description": "What this step does",
|
|
270
|
+
"expectedTools": ["tool.name"],
|
|
271
|
+
"dependsOn": []
|
|
272
|
+
}
|
|
273
|
+
]
|
|
274
|
+
}
|
|
275
|
+
`,xw=`
|
|
276
|
+
Execute step {stepNumber}: {stepDescription}
|
|
277
|
+
|
|
278
|
+
Plan: {planSummary}
|
|
279
|
+
|
|
280
|
+
Previous: {previousStepsResults}
|
|
281
|
+
|
|
282
|
+
Use tools. Be concise. Show code changes clearly.
|
|
283
|
+
No meta-commentary about steps or workflow.
|
|
284
|
+
`,Vf={name:"Coding",planning:{enabled:!0,planningPrompt:bw},steps:{enabled:!0,retryOnFailure:!0,allowDynamicSteps:!1,stepPrompt:xw},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},Xf={name:"Chat",planning:{enabled:!1},steps:{enabled:!1},progress:{enabled:!1}};var Zf={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:Yf,toolSearch:{alwaysLoadedTools:["fs.read_file","fs.write_file","fs.list_dir","web.search","web.fetch","skill.search","skill.read"]}},eg={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:Xf,toolSearch:{alwaysLoadedTools:["web.search","web.fetch","fs.read_file","fs.list_dir"]}},Tw={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:Vf,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"]}},vr=[Zf,Tw,eg],ot="chat";var no=class{modes=new Map;orderedNames=[];constructor(){for(let e of vr)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(ot);if(!e)throw new Error(`Default mode "${ot}" 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(vr.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 Pw(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 Ps={planning:{enabled:!1},steps:{enabled:!1},progress:{enabled:!0}};l();_();var Cw=xs,so=class{client;config;constructor(e,t){this.client=e,this.config=t}async createPlan(e,t){let o=this.config?.planningPrompt||Cw,r=e.messages.filter(p=>p.role==="user").map(p=>typeof p.content=="string"?p.content:"[obj]").join(" ").substring(0,100);y(`[Planner] createPlan() provider=${t??"default"} maxSteps=${this.config?.maxSteps??20} request="${r}..."`);let 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}`),y(`[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 rt=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(`
|
|
288
|
+
|
|
289
|
+
`)}};_();var vw=Ts,Sw=`
|
|
254
290
|
Based on the result of the previous step, do we need to add any new steps to our plan before continuing?
|
|
255
291
|
Only add steps if they are absolutely necessary to complete the user's request.
|
|
292
|
+
|
|
293
|
+
Already planned next steps:
|
|
294
|
+
{{REMAINING_STEPS}}
|
|
295
|
+
|
|
296
|
+
Only suggest steps if they are NOT covered by the above.
|
|
297
|
+
|
|
256
298
|
If additional steps are truly required, respond with a JSON object containing the new steps.
|
|
257
299
|
If not necessary or if the plan is sufficient, respond with {"steps": []}.
|
|
258
300
|
|
|
@@ -262,47 +304,46 @@ JSON Schema:
|
|
|
262
304
|
{ "description": "What to do", "expectedTools": [] }
|
|
263
305
|
]
|
|
264
306
|
}
|
|
265
|
-
`,
|
|
266
|
-
... [truncated]`),
|
|
267
|
-
|
|
307
|
+
`,io=class{client;config;constructor(e,t){this.client=e,this.config=t}async executeStep(e,t,o,r){let s=Date.now();y(`[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){y(`[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=rt.summarizeCompletedSteps(t,e.id),i=(this.config?.stepPrompt||vw).replace("{stepNumber}",e.number.toString()).replace("{planSummary}",t.summary).replace("{stepDescription}",e.description).replace("{previousStepsResults}",r),a=o.messages.filter(f=>f.role==="system"),c=o.messages.filter(f=>f.role!=="system"),p=[...a,...c],m=[];for(let f of t.steps){if(f.id===e.id)break;if(f.status==="completed"&&f.result?.output){let h=f.result.output;h.length>2e3&&(h=h.substring(0,2e3)+`
|
|
308
|
+
... [truncated]`),m.push({role:"assistant",content:h}),m.push({role:"user",content:`Step ${f.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 y(`[StepExecutor] checkForDynamicSteps() skipped \u2014 already at maxTotalSteps=${i}`),[];y(`[StepExecutor] checkForDynamicSteps() after step=${e.number} currentTotal=${s} max=${i}`);let a=t.steps.filter(b=>b.status==="pending"&&b.number>e.number).map(b=>`${b.number}. ${b.description}`).join(`
|
|
309
|
+
`)||"None",c=Sw.replace("{{REMAINING_STEPS}}",a),p=o.messages.filter(b=>b.role==="system"),m=o.messages.filter(b=>b.role!=="system"),f=[...p,...m],h={...o,tool_choice:"none",response_format:"json_object",messages:[...f,{role:"assistant",content:e.result?.output||""},{role:"user",content:c}]};try{let b=await this.client.generate(h,r),w=JSON.parse(b.content||'{"steps": []}');if(Array.isArray(w.steps)&&w.steps.length>0){let x=i-s,T=w.steps.slice(0,x),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?(y("[StepExecutor] checkForDynamicSteps() all proposed steps were duplicates \u2014 skipping"),[]):(v(`[StepExecutor] checkForDynamicSteps() adding ${C.length} dynamic step(s) after step ${e.number}`),C.map((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();import{EventEmitter as kw}from"events";_();var Sr=class extends kw{client;config;planner;stepExecutor;queryClassifier;pendingApprovals=new Map;constructor(e,t,o){super(),this.client=e,this.config=t,this.queryClassifier=o||new Ke,this.planner=new so(e,t.planning),this.stepExecutor=new io(e,t.steps)}getConfig(){return this.config}setConfig(e){this.config=e,this.planner=new so(this.client,e.planning),this.stepExecutor=new io(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=Ae(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 y(`[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(y(`[Workflow] execute() planningEnabled=${o} stepsEnabled=${r} provider=${t??"default"}`),!o&&!r)return y("[Workflow] execute() mode=direct"),this.executeDirect(e,t);let s=null;if(o){if(y("[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||(y("[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?(y("[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);y(`[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;y(`[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){y(`[Workflow] createPlan() provider=${t??"default"}`);let o=this.createDummyPlan(e);o.status="draft",this.emitProgress(o,"planning","Creating plan...");let r=await this.planner.createPlan(e,t);return v(`[Workflow] createPlan() completed plan.id=${r.id} steps=${r.steps.length}`),r}async executeStepByStep(e,t,o){e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e),v(`[Workflow] executeStepByStep() plan.id=${e.id} steps=${e.steps.length} maxRetries=${this.config.steps?.maxRetries??3}`);let r=Date.now(),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 w=p.dependsOn.filter(x=>{let T=e.steps.find(k=>k.id===String(x)||k.number===Number(x));return T?T.status!=="completed":!1});if(w.length>0){y(`[Workflow] Step ${p.number} skipped \u2014 unmet deps: ${w.join(", ")}`),p.status="skipped",p.result={success:!1,error:`Unmet dependencies: ${w.join(", ")}`};continue}}p.status="in_progress",this.emit("workflow:step_start",p,e),this.emitProgress(e,"executing",p.description),v(`[Workflow] Step ${p.number}/${e.steps.length} starting: "${p.description}"`);let m=0,f=this.config.steps?.maxRetries??3,h=null,b=!1;for(;m<=f;)try{let w=await this.stepExecutor.executeStep(p,e,t,o);if(w.success){p.status="completed",p.result=w,this.emit("workflow:step_complete",p,e),y(`[Workflow] Step ${p.number} completed in ${w.duration??0}ms toolsUsed=${(w.toolsUsed??[]).join(",")||"none"}`),b=!0;break}else throw new Error(w.error||"Step returned unsuccessful result")}catch(w){if(h=w,m++,m<=f&&this.config.steps?.retryOnFailure)s++,E(`[Workflow] Step ${p.number} failed (attempt ${m}/${f}), retrying: ${h.message}`),this.emit("workflow:step_retry",p,m,e),this.emitProgress(e,"executing",`[Retry ${m}] ${p.description}`);else{E(`[Workflow] Step ${p.number} failed permanently: ${h.message}`),p.status="failed",p.result={success:!1,error:h.message},this.emit("workflow:step_failed",p,h,e);break}}if(!b){let w=this.config.onFailure?.strategy||"abort";if(y(`[Workflow] Step ${p.number} failed \u2014 applying strategy="${w}"`),w==="abort"){e.status="failed",e.completedAt=new Date;let x={success:!1,plan:e,error:`Step ${p.number} failed: ${h?.message}`,metrics:this.computeMetrics(e,r,s)};return this.emit("workflow:failed",e,h),this.emitProgress(e,"failed","Workflow aborted due to step failure"),x}else if(w==="ask_user"){if(this.emitProgress(e,"awaiting_approval",`Step failed: ${h?.message}. Continue?`),!await this.waitForApproval(e.id)){e.status="failed",e.completedAt=new Date;let 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(b&&this.config.steps?.allowDynamicSteps){let w=await this.stepExecutor.checkForDynamicSteps(p,e,t,o);if(w.length>0){let x=p.number+1;for(let T of w)T.number=x++;for(let T=c+1;T<e.steps.length;T++)e.steps[T].number=x++;e.steps.splice(c+1,0,...w),w.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"),y(`[Workflow] executePlanDirect() plan.id=${e.id} steps=${e.steps.length} provider=${o??"default"}`);let s=`
|
|
268
310
|
You have created the following plan to fulfill the request:
|
|
269
311
|
Summary: ${e.summary}
|
|
270
312
|
|
|
271
313
|
Steps:
|
|
272
|
-
${e.steps.map(
|
|
314
|
+
${e.steps.map(a=>`${a.number}. ${a.description}`).join(`
|
|
273
315
|
`)}
|
|
274
316
|
|
|
275
317
|
Execute this plan now.
|
|
276
|
-
`.trim(),
|
|
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),y(`[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=rt.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.
|
|
277
319
|
Summary: ${e.summary}
|
|
278
320
|
Steps:
|
|
279
321
|
`+e.steps.map(t=>`[${t.status.toUpperCase()}] ${t.description}`).join(`
|
|
280
|
-
`)}extractFinalOutput(e){
|
|
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(`
|
|
323
|
+
|
|
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(y(`[Workflow] stream() planningEnabled=${o} stepsEnabled=${r} provider=${t??"default"}`),!o&&!r){y("[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:`
|
|
281
325
|
|
|
282
326
|
**Plan Created:**
|
|
283
|
-
${
|
|
327
|
+
${s.summary}
|
|
284
328
|
|
|
285
329
|
Steps:
|
|
286
|
-
${
|
|
330
|
+
${s.steps.map(a=>`${a.number}. ${a.description}`).join(`
|
|
287
331
|
`)}
|
|
288
332
|
|
|
289
|
-
*Waiting for approval...*`,workflowStep:{number:0,description:"Awaiting approval"}};let
|
|
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:`
|
|
290
334
|
|
|
291
|
-
*Plan rejected by user.*`,finish_reason:"stop"};return}}
|
|
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 w=c.dependsOn.filter(x=>{let T=e.steps.find(k=>k.id===String(x)||k.number===Number(x));return T?T.status!=="completed":!1});if(w.length>0){c.status="skipped",c.result={success:!1,error:`Unmet dependencies: ${w.join(", ")}`};continue}}c.status="in_progress",this.emit("workflow:step_start",c,e),this.emitProgress(e,"executing",c.description);let p=0,m=this.config.steps?.maxRetries??3,f=null,h=!1,b="";for(;p<=m;)try{for await(let w of this.stepExecutor.streamStep(c,e,t,o)){if(t.signal?.aborted){c.status="skipped",e.status="cancelled",e.completedAt=new Date,this.emit("workflow:failed",e,new Error("Interrupted by user"));return}w.delta&&(b+=w.delta),yield{...w,workflowStep:{number:c.number,description:c.description}}}c.status="completed",c.result={success:!0,output:b,duration:Date.now()-r},this.emit("workflow:step_complete",c,e),this.emitProgress(e,"executing"),h=!0;break}catch(w){if(f=w,p++,p<=m&&this.config.steps?.retryOnFailure)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:f.message},this.emit("workflow:step_failed",c,f,e);break}}if(!h){let w=this.config.onFailure?.strategy||"abort";if(w==="abort"){e.status="failed",e.completedAt=new Date,this.emit("workflow:failed",e,f),yield{delta:`
|
|
292
336
|
|
|
293
337
|
**Step failed:** ${f?.message}
|
|
294
338
|
*Workflow aborted.*`,finish_reason:"stop"};return}else w==="skip"&&(c.status="skipped",yield{delta:`
|
|
295
339
|
*Step skipped due to failure.*
|
|
296
|
-
`,workflowStep:{number:c.number,description:c.description}})}if(h&&this.config.steps?.allowDynamicSteps){let w=await this.stepExecutor.checkForDynamicSteps(c,e,t,o);if(w.length>0){let
|
|
340
|
+
`,workflowStep:{number:c.number,description:c.description}})}if(h&&this.config.steps?.allowDynamicSteps){let w=await this.stepExecutor.checkForDynamicSteps(c,e,t,o);if(w.length>0){let x=c.number+1;for(let T of w)T.number=x++;for(let T=a+1;T<e.steps.length;T++)e.steps[T].number=x++;e.steps.splice(a+1,0,...w),w.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=`
|
|
297
341
|
You have created the following plan to fulfill the request:
|
|
298
342
|
Summary: ${e.summary}
|
|
299
343
|
|
|
300
344
|
Steps:
|
|
301
|
-
${e.steps.map(
|
|
345
|
+
${e.steps.map(a=>`${a.number}. ${a.description}`).join(`
|
|
302
346
|
`)}
|
|
303
347
|
|
|
304
348
|
Execute this plan now.
|
|
305
|
-
`.trim(),n={...t,messages:[{role:"system",content:r},...t.messages]};yield{delta:`**Plan:**
|
|
306
|
-
${e.summary}
|
|
307
|
-
|
|
308
|
-
`};let a="";for await(let i of this.client.stream(n,o))i.delta&&(a+=i.delta),yield i;e.steps.forEach(i=>{i.status="completed",i.result={success:!0,output:a}}),e.status="completed",e.completedAt=new Date,this.emit("workflow:completed",e,{success:!0,plan:e,output:a,metrics:this.computeMetrics(e,e.startedAt.getTime(),0)})}waitForApproval(e){return new Promise(t=>{this.pendingApprovals.set(e,t)})}approvePlan(e){let t=this.pendingApprovals.get(e);t&&(t(!0),this.pendingApprovals.delete(e))}rejectPlan(e){let t=this.pendingApprovals.get(e);t&&(t(!1),this.pendingApprovals.delete(e))}};l();import{EventEmitter as Df}from"events";_();var Ef=class s extends Df{client;activeProviderName;modeRegistry;workflowExecutor;customProviderNames=new Set;mcpToolProject=null;constructor(e,t,o){super(),this.client=e,this.activeProviderName=t,this.modeRegistry=o;let r=this.client.getProvider(t);r&&this.forwardEvents(r),this.workflowExecutor=new br(this.client,os),this.forwardWorkflowEvents()}static async init(e){let t=Po(e.configPath);cs(t.logging);let o=new Qt,r=qt(e.configPath);if(o.setConfig(r),e.tools&&await o.loadBuiltIn(),e.customTools&&await o.loadProjects(e.customTools),e.knowledge&&typeof e.knowledge.toTool=="function")try{let T=e.knowledge.toTool(),k={manifest:{key:"knowledge",name:"knowledge",displayName:"Knowledge Base",version:"1.0.0",description:"RAG-powered knowledge base search",tools:["knowledge_search"],category:"search"},tools:[T]};await o.loadProjects([k]),v("[Knowledge] Registered knowledge_search tool")}catch(T){Q(`[Knowledge] Failed to register knowledge tool: ${T}`)}let n=null,a=e.mcp||t.mcp;if(a)try{v("[MCP] Initializing MCP tool integration");let T=await es(a);n=T,await o.loadProjects([T]),v(`[MCP] Loaded ${T.tools.length} tools from MCP servers`)}catch(T){Q(`[MCP] Failed to initialize MCP tools: ${T}`)}let i=t.systemPrompt,c=e.disableBaseContext||t.disableBaseContext||t.baseContext===!1||!1,p=t.modeOverrides||{},m={},f=new Set,h=e.defaultProvider||e.provider;if(e.providers)for(let[T,k]of Object.entries(e.providers)){let R=T===h,I=await s.createProvider(T,k,e.configPath,!R);I&&(m[T]=I)}else if(e.provider){let T={apiKey:e.apiKey,model:e.model},k=await s.createProvider(e.provider,T,e.configPath,!1);k&&(m[e.provider]=k)}else if(!e.customProviders)throw new Error('No provider specified. Pass { provider: "name" }, { providers: { ... } }, or { customProviders: { ... } } to init().');if(e.customProviders){let T=Array.isArray(e.customProviders)?e.customProviders:Object.entries(e.customProviders).map(([k,R])=>(R.name=R.name||k,R));for(let k of T){if(typeof k.generate!="function"||typeof k.stream!="function"||typeof k.embed!="function")throw new Error("Custom provider must implement the ProviderAdapter interface (generate, stream, embed methods). Import { ProviderAdapter } from 'toolpack' and implement or extend it.");let R=k.name;if(!R)throw new Error("Custom provider must have a 'name' property set. Set adapter.name in the constructor or use the record syntax: { 'provider-name': adapter }");if(m[R])throw new Error(`Custom provider name "${R}" conflicts with a built-in provider designation. Choose a different name.`);f.add(R),m[R]=k}}if(!h&&e.customProviders&&(h=(Array.isArray(e.customProviders)?e.customProviders[0]:Object.values(e.customProviders)[0])?.name),!h)throw new Error("No default provider specified.");let x=new Vt;if(e.customModes)for(let T of e.customModes)x.register(T);let w={...p,...e.modeOverrides||{}};for(let[T,k]of Object.entries(w)){let R=x.get(T);if(R){k.systemPrompt!==void 0&&(R.systemPrompt=k.systemPrompt),k.toolSearch&&(R.toolSearch={...R.toolSearch||{},...k.toolSearch});for(let[I,U]of Object.entries(k))I!=="systemPrompt"&&I!=="toolSearch"&&(R[I]=U)}}let b=new io({providers:m,defaultProvider:h,toolRegistry:o,toolsConfig:o.getConfig(),systemPrompt:i,disableBaseContext:c}),P=new s(b,h,x);P.customProviderNames=f,P.mcpToolProject=n;let S=e.defaultMode||Qe,C=x.get(S);return C&&(b.setMode(C),C.workflow&&P.workflowExecutor.setConfig(C.workflow)),P}static async createProvider(e,t,o,r=!1){if(["openai","anthropic","gemini"].includes(e)){let n=`TOOLPACK_${e.toUpperCase()}_KEY`,a=t.apiKey||process.env[n]||process.env[`${e.toUpperCase()}_API_KEY`];if(!a){if(r)return null;throw new Error(`No API key found for '${e}'. Set ${n} or pass apiKey in config.`)}switch(e){case"openai":return new po(a,t.baseUrl);case"anthropic":return new ao(a,t.baseUrl);case"gemini":return new lo(a)}}if(e==="ollama")return new it({baseUrl:t.baseUrl||co(o)});if(e.startsWith("ollama-")){let n=t.model||e.replace(/^ollama-/,""),a=t.baseUrl||co(o);return new De({model:n,baseUrl:a})}throw new Error(`Unknown provider type: ${e}`)}async generate(e,t){let o;typeof e=="string"?o={messages:[{role:"user",content:e}],model:""}:o=e;let r=this.getMode();if(r?.workflow?.planning?.enabled||r?.workflow?.steps?.enabled){let n=await this.workflowExecutor.execute(o,t||this.activeProviderName),a=0,i=0,c=0,p={steps:[]};n.plan.planningResponse?.usage&&(a+=n.plan.planningResponse.usage.prompt_tokens,i+=n.plan.planningResponse.usage.completion_tokens||0,c+=n.plan.planningResponse.usage.total_tokens,p.planning=n.plan.planningResponse.usage);for(let f of n.plan.steps)if(f.status==="completed"&&f.result?.response?.usage){let h=f.result.response.usage;a+=h.prompt_tokens,i+=h.completion_tokens||0,c+=h.total_tokens,p.steps.push({stepNumber:f.number,description:f.description,usage:h})}let m={prompt_tokens:a,completion_tokens:i,total_tokens:c};return n.response?{...n.response,content:n.output||n.response.content||null,usage:m,usage_details:p}:{content:n.output||null,usage:m,usage_details:p}}return this.client.generate(o,t)}async*stream(e,t){let o=this.getMode(),r=t||this.activeProviderName;if(o?.workflow?.planning?.enabled||o?.workflow?.steps?.enabled){yield*this.workflowExecutor.stream(e,r);return}yield*this.client.stream(e,t)}async embed(e,t){return this.client.embed(e,t)}setProvider(e){let t=this.client.getProvider(e);this.activeProviderName=e,this.client.setDefaultProvider(e),this.forwardEvents(t)}getProvider(){return this.client.getProvider(this.activeProviderName)}getClient(){return this.client}getWorkflowExecutor(){return this.workflowExecutor}async disconnect(){let e=this.getProvider();e&&"disconnect"in e&&await e.disconnect(),this.mcpToolProject&&await ts(this.mcpToolProject)}async listProviders(){let e=this.client.getProviders(),t=[];for(let[o,r]of e.entries()){let n=this.customProviderNames.has(o),a=[];try{a=await r.getModels()}catch(i){D(`[Toolpack] Failed to fetch models for provider '${o}': ${i}`)}t.push({name:o,displayName:r.getDisplayName(),type:n?"custom":"built-in",models:a})}return t}async loadToolProject(e){let t=this.client.getToolRegistry();if(t)await t.loadProject(e);else throw new Error("No tool registry configured. Initialize Toolpack with tools enabled.")}async listModels(){let e=await this.listProviders(),t=[];for(let o of e)for(let r of o.models)t.push({...r,provider:o.name});return t}setMode(e){let t=this.modeRegistry.get(e);if(!t)throw new Error(`Mode "${e}" not found. Available modes: ${this.modeRegistry.getNames().join(", ")}`);return this.client.setMode(t),t.workflow?this.workflowExecutor.setConfig(t.workflow):this.workflowExecutor.setConfig(os),t}getMode(){return this.client.getMode()}getActiveModeName(){let e=this.client.getMode();return e?e.displayName:"Default"}getModes(){return this.modeRegistry.getAll()}cycleMode(){let e=this.client.getMode(),t=e?e.name:"default",o=this.modeRegistry.getNext(t);return this.client.setMode(o),o}registerMode(e){this.modeRegistry.register(e)}forwardEvents(e){e instanceof Df&&e.on("status",t=>this.emit("status",t))}forwardWorkflowEvents(){let e=this.workflowExecutor;e.on("workflow:plan_created",t=>this.emit("workflow:plan_created",t)),e.on("workflow:plan_decision",(t,o)=>this.emit("workflow:plan_decision",t,o)),e.on("workflow:started",t=>this.emit("workflow:started",t)),e.on("workflow:step_start",(t,o)=>this.emit("workflow:step_start",t,o)),e.on("workflow:step_complete",(t,o)=>this.emit("workflow:step_complete",t,o)),e.on("workflow:step_failed",(t,o,r)=>this.emit("workflow:step_failed",t,o,r)),e.on("workflow:step_retry",(t,o,r)=>this.emit("workflow:step_retry",t,o,r)),e.on("workflow:step_added",(t,o)=>this.emit("workflow:step_added",t,o)),e.on("workflow:progress",t=>this.emit("workflow:progress",t)),e.on("workflow:completed",(t,o)=>this.emit("workflow:completed",t,o)),e.on("workflow:failed",(t,o)=>this.emit("workflow:failed",t,o))}};l();import*as Nf from"os";import*as Me from"path";import*as Ve from"fs";var Af=".toolpack",Mf="config",Of="toolpack.config.json";function Yy(){return Nf.homedir()}function Vy(){return Me.join(Yy(),Af)}function If(){return Me.join(Vy(),Mf)}function xr(){return Me.join(If(),Of)}function Xy(s=process.cwd()){return Me.join(s,Af)}function jf(s=process.cwd()){return Me.join(Xy(s),Mf)}function Tr(s=process.cwd()){return Me.join(jf(s),Of)}function Ff(){let s=If();Ve.existsSync(s)||Ve.mkdirSync(s,{recursive:!0})}function RA(s=process.cwd()){let e=jf(s);Ve.existsSync(e)||Ve.mkdirSync(e,{recursive:!0})}l();import*as J from"fs";import*as Pr from"path";function ns(s,e){if(!e)return s;if(!s)return e;let t={...s};for(let o of Object.keys(e))e[o]instanceof Array?t[o]=e[o]:e[o]instanceof Object&&o in s?t[o]=ns(s[o],e[o]):t[o]=e[o];return t}function rs(s){if(!J.existsSync(s))return null;try{let e=J.readFileSync(s,"utf-8");return JSON.parse(e)}catch{return null}}function MA(s=process.cwd()){let e=Pr.join(s,"toolpack.config.json"),t=xr(),o=Tr(s),r=rs(e)||{},n=rs(t)||{},a=rs(o)||{},i=ns(r,n);return i=ns(i,a),i}function OA(s=process.cwd()){let e=Pr.join(s,"toolpack.config.json"),t=xr(),o=Tr(s),r=!J.existsSync(t),n=null,a="default";return J.existsSync(o)?(n=o,a="local"):J.existsSync(t)?(n=t,a="global"):J.existsSync(e)&&(n=e,a="base"),{isFirstRun:r,activeConfigPath:n,configSource:a}}function IA(s=process.cwd()){let e=xr();if(!J.existsSync(e)){Ff();let t=null,o=Tr(s);if(J.existsSync(o))t=o;else{let n=Pr.join(s,"toolpack.config.json");if(J.existsSync(n))t=n;else{let a=Rr();a&&J.existsSync(a)&&(t=a)}}let r={};if(t)try{let n=J.readFileSync(t,"utf-8");r=JSON.parse(n)}catch{}J.writeFileSync(e,JSON.stringify(r,null,4),"utf-8")}}l();export{kf as AGENT_MODE,io as AIClient,ao as AnthropicAdapter,ge as AuthenticationError,Xe as BM25SearchEngine,wr as BUILT_IN_MODES,Rf as CHAT_MODE,Mf as CONFIG_DIR_NAME,Of as CONFIG_FILE_NAME,ke as ConnectionError,Qe as DEFAULT_MODE_NAME,z as DEFAULT_TOOLS_CONFIG,Yf as DEFAULT_TOOL_SEARCH_CONFIG,os as DEFAULT_WORKFLOW_CONFIG,lo as GeminiAdapter,M as InvalidRequestError,Yt as McpClient,me as McpConnectionError,hr as McpTimeoutError,yr as McpToolManager,Vt as ModeRegistry,De as OllamaAdapter,it as OllamaProvider,po as OpenAIAdapter,ss as PageError,Xt as Planner,Y as ProviderAdapter,F as ProviderError,he as RateLimitError,H as SDKError,Zt as StepExecutor,Af as TOOLPACK_DIR_NAME,Ze as TOOL_SEARCH_NAME,is as TimeoutError,je as ToolDiscoveryCache,Qt as ToolRegistry,et as ToolRouter,Ef as Toolpack,br as WorkflowExecutor,ur as cloudDeployTool,gr as cloudListTool,fr as cloudStatusTool,$f as cloudToolsProject,Jt as codingFindSymbolTool,zt as codingGetImportsTool,Ht as codingGetSymbolsTool,Vd as codingToolsProject,es as createMcpToolProject,Jy as createMode,Wy as createToolProject,mr as dbCountTool,pr as dbDeleteTool,lr as dbInsertTool,sr as dbQueryTool,ir as dbSchemaTool,ar as dbTablesTool,gf as dbToolsProject,cr as dbUpdateTool,er as diffApplyTool,Zo as diffCreateTool,tr as diffPreviewTool,Uu as diffToolsProject,ts as disconnectMcpToolProject,Ff as ensureGlobalConfigDir,RA as ensureLocalConfigDir,_t as execKillTool,kt as execListProcessesTool,$t as execReadOutputTool,St as execRunBackgroundTool,Ct as execRunShellTool,Pt as execRunTool,$l as execToolsProject,Ps as fetchUrlAsBase64,ct as fsAppendFileTool,yt as fsCopyTool,ft as fsCreateDirTool,pt as fsDeleteFileTool,mt as fsExistsTool,ut as fsListDirTool,gt as fsMoveTool,wt as fsReadFileRangeTool,at as fsReadFileTool,xt as fsReplaceInFileTool,bt as fsSearchTool,dt as fsStatTool,La as fsToolsProject,Tt as fsTreeTool,lt as fsWriteFileTool,Sr as generateToolCategoriesPrompt,pg as getDefaultSlmModel,If as getGlobalConfigDir,xr as getGlobalConfigPath,Vy as getGlobalToolpackDir,jf as getLocalConfigDir,Tr as getLocalConfigPath,Xy as getLocalToolpackDir,ws as getMimeType,co as getOllamaBaseUrl,cg as getOllamaProviderEntries,dg as getRegisteredSlmModels,OA as getRuntimeConfigStatus,Cr as getToolSearchSchema,Dr as getToolpackConfig,Yy as getUserHomeDir,zo as gitAddTool,Qo as gitBlameTool,Vo as gitBranchCreateTool,Yo as gitBranchListTool,Xo as gitCheckoutTool,Ko as gitCommitTool,Jo as gitDiffTool,Ho as gitLogTool,Bo as gitStatusTool,$u as gitToolsProject,jt as httpDeleteTool,Ft as httpDownloadTool,Mt as httpGetTool,Ot as httpPostTool,It as httpPutTool,Bc as httpToolsProject,IA as initializeGlobalConfigIfFirstRun,bs as isDataUri,mg as isRegisteredSlm,vr as isToolSearchTool,Po as loadFullConfig,MA as loadRuntimeConfig,qt as loadToolsConfig,ng as normalizeImagePart,ne as ollamaRequest,Er as ollamaStream,xs as parseDataUri,Ts as readFileAsBase64,lg as reloadToolpackConfig,ph as saveToolsConfig,Nt as systemCwdTool,At as systemDiskUsageTool,Dt as systemEnvTool,Rt as systemInfoTool,Et as systemSetEnvTool,ac as systemToolsProject,rg as toDataUri,Fe as toolSearchDefinition,Gt as webExtractLinksTool,Lt as webFetchTool,Wt as webScrapeTool,Ut as webSearchTool,dm as webToolsProject};
|
|
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();import{EventEmitter as tg}from"events";_();var og=class n extends tg{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 Sr(this.client,Ps,this.client.getQueryClassifier()),this.forwardWorkflowEvents()}static async init(e){let t=_o(e.configPath);Rs(t.logging);let o=new oo,r=Ht(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 ws(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={},f=new Set,h=e.defaultProvider||e.provider;if(e.providers)for(let[S,R]of Object.entries(e.providers)){let D=S===h,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.`);f.add(D),m[D]=R}}if(!h&&e.customProviders&&(h=(Array.isArray(e.customProviders)?e.customProviders[0]:Object.values(e.customProviders)[0])?.name),!h)throw new Error("No default provider specified.");let b=new no;if(e.customModes)for(let S of e.customModes)b.register(S);let w={...p,...e.modeOverrides||{}};for(let[S,R]of Object.entries(w)){let D=b.get(S);if(D){R.systemPrompt!==void 0&&(D.systemPrompt=R.systemPrompt),R.toolSearch&&(D.toolSearch={...D.toolSearch||{},...R.toolSearch});for(let[L,I]of Object.entries(R))L!=="systemPrompt"&&L!=="toolSearch"&&(D[L]=I)}}let x=t.hitl||{};e.confirmationMode!==void 0&&(x.confirmationMode=e.confirmationMode),x.enabled===void 0&&e.onToolConfirm&&(x.enabled=!0),x.confirmationMode===void 0&&e.onToolConfirm&&(x.confirmationMode="all");let T=new mo({providers:m,defaultProvider:h,toolRegistry:o,toolsConfig:o.getConfig(),systemPrompt:a,disableBaseContext:c,hitlConfig:Object.keys(x).length>0?x:void 0,onToolConfirm:e.onToolConfirm,conversationId:e.conversationId}),k=new n(T,h,b);k.customProviderNames=f,k.mcpToolProject=s;let C=e.defaultMode||ot,P=b.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 yo(i,t.baseUrl);case"anthropic":return new uo(i,t.baseUrl);case"gemini":return new fo(i)}}if(e==="ollama")return new ut({baseUrl:t.baseUrl||ho(o)});if(e.startsWith("ollama-")){let s=t.model||e.replace(/^ollama-/,""),i=t.baseUrl||ho(o);return new Ie({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 f of s.plan.steps)if(f.status==="completed"&&f.result?.response?.usage){let h=f.result.response.usage;i+=h.prompt_tokens,a+=h.completion_tokens||0,c+=h.total_tokens,p.steps.push({stepNumber:f.number,description:f.description,usage:h})}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||Oe();if(t)try{let o=dt(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 bs(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(Ps),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 tg&&e.on("status",t=>this.emit("status",t))}forwardWorkflowEvents(){let e=this.workflowExecutor;e.on("workflow:plan_created",t=>this.emit("workflow:plan_created",t)),e.on("workflow:plan_decision",(t,o)=>this.emit("workflow:plan_decision",t,o)),e.on("workflow:started",t=>this.emit("workflow:started",t)),e.on("workflow:step_start",(t,o)=>this.emit("workflow:step_start",t,o)),e.on("workflow:step_complete",(t,o)=>this.emit("workflow:step_complete",t,o)),e.on("workflow:step_failed",(t,o,r)=>this.emit("workflow:step_failed",t,o,r)),e.on("workflow:step_retry",(t,o,r)=>this.emit("workflow:step_retry",t,o,r)),e.on("workflow:step_added",(t,o)=>this.emit("workflow:step_added",t,o)),e.on("workflow:progress",t=>this.emit("workflow:progress",t)),e.on("workflow:completed",(t,o)=>this.emit("workflow:completed",t,o)),e.on("workflow:failed",(t,o)=>this.emit("workflow:failed",t,o))}};l();import*as rg from"os";import*as qe from"path";import*as nt from"fs";var ng=".toolpack",sg="config",ig="toolpack.config.json";function $w(){return rg.homedir()}function _w(){return qe.join($w(),ng)}function ag(){return qe.join(_w(),sg)}function kr(){return qe.join(ag(),ig)}function Rw(n=process.cwd()){return qe.join(n,ng)}function lg(n=process.cwd()){return qe.join(Rw(n),sg)}function $r(n=process.cwd()){return qe.join(lg(n),ig)}function cg(){let n=ag();nt.existsSync(n)||nt.mkdirSync(n,{recursive:!0})}function kM(n=process.cwd()){let e=lg(n);nt.existsSync(e)||nt.mkdirSync(e,{recursive:!0})}l();import*as H from"fs";import*as _r from"path";function vs(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]=vs(n[o],e[o]):t[o]=e[o];return t}function Cs(n){if(!H.existsSync(n))return null;try{let e=H.readFileSync(n,"utf-8");return JSON.parse(e)}catch{return null}}function EM(n=process.cwd()){let e=_r.join(n,"toolpack.config.json"),t=kr(),o=$r(n),r=Cs(e)||{},s=Cs(t)||{},i=Cs(o)||{},a=vs(r,s);return a=vs(a,i),a}function NM(n=process.cwd()){let e=_r.join(n,"toolpack.config.json"),t=kr(),o=$r(n),r=!H.existsSync(t),s=null,i="default";return H.existsSync(o)?(s=o,i="local"):H.existsSync(t)?(s=t,i="global"):H.existsSync(e)&&(s=e,i="base"),{isFirstRun:r,activeConfigPath:s,configSource:i}}function AM(n=process.cwd()){let e=kr();if(!H.existsSync(e)){cg();let t=null,o=$r(n);if(H.existsSync(o))t=o;else{let s=_r.join(n,"toolpack.config.json");if(H.existsSync(s))t=s;else{let i=Oe();i&&H.existsSync(i)&&(t=i)}}let r={};if(t)try{let s=H.readFileSync(t,"utf-8");r=JSON.parse(s)}catch{}H.writeFileSync(e,JSON.stringify(r,null,4),"utf-8")}}l();export{Zf as AGENT_MODE,xs as AGENT_PLANNING_PROMPT,Ts as AGENT_STEP_PROMPT,Yf as AGENT_WORKFLOW,mo as AIClient,uo as AnthropicAdapter,we as AuthenticationError,st as BM25SearchEngine,vr as BUILT_IN_MODES,eg as CHAT_MODE,Xf as CHAT_WORKFLOW,bw as CODING_PLANNING_PROMPT,xw as CODING_STEP_PROMPT,Vf as CODING_WORKFLOW,sg as CONFIG_DIR_NAME,ig as CONFIG_FILE_NAME,Ne as ConnectionError,ot as DEFAULT_MODE_NAME,z as DEFAULT_TOOLS_CONFIG,Tg as DEFAULT_TOOL_SEARCH_CONFIG,CA as DEFAULT_WORKFLOW,Ps as DEFAULT_WORKFLOW_CONFIG,fo as GeminiAdapter,j as InvalidRequestError,ro as McpClient,fe as McpConnectionError,Pr as McpTimeoutError,Cr as McpToolManager,no as ModeRegistry,Ie as OllamaAdapter,ut as OllamaProvider,yo as OpenAIAdapter,Ss as PageError,so as Planner,V as ProviderAdapter,U as ProviderError,be as RateLimitError,G as SDKError,io as StepExecutor,ng as TOOLPACK_DIR_NAME,it as TOOL_SEARCH_NAME,ks as TimeoutError,Ge as ToolDiscoveryCache,oo as ToolRegistry,at as ToolRouter,og as Toolpack,Sr as WorkflowExecutor,Ng as addBypassRule,br as cloudDeployTool,Tr as cloudListTool,xr as cloudStatusTool,Hf as cloudToolsProject,Xt as codingFindSymbolTool,eo as codingGetImportsTool,Zt as codingGetSymbolsTool,wu as codingToolsProject,ws as createMcpToolProject,Pw as createMode,dw as createToolProject,yr as dbCountTool,hr as dbDeleteTool,fr as dbInsertTool,mr as dbQueryTool,dr as dbSchemaTool,ur as dbTablesTool,If as dbToolsProject,gr as dbUpdateTool,ir as diffApplyTool,sr as diffCreateTool,ar as diffPreviewTool,cf as diffToolsProject,bs as disconnectMcpToolProject,cg as ensureGlobalConfigDir,kM as ensureLocalConfigDir,Mt as execKillTool,Ot as execListProcessesTool,At as execReadOutputTool,Nt as execRunBackgroundTool,Dt as execRunShellTool,Rt as execRunTool,Hl as execToolsProject,Ws as fetchUrlAsBase64,ht as fsAppendFileTool,vt as fsCopyTool,Tt as fsCreateDirTool,yt as fsDeleteFileTool,wt as fsExistsTool,xt as fsListDirTool,Pt as fsMoveTool,St as fsReadFileRangeTool,ft as fsReadFileTool,$t as fsReplaceInFileTool,kt as fsSearchTool,bt as fsStatTool,il as fsToolsProject,_t as fsTreeTool,gt as fsWriteFileTool,Er as generateToolCategoriesPrompt,Mg as getDefaultSlmModel,ag as getGlobalConfigDir,kr as getGlobalConfigPath,_w as getGlobalToolpackDir,lg as getLocalConfigDir,$r as getLocalConfigPath,Rw as getLocalToolpackDir,Ls as getMimeType,ho as getOllamaBaseUrl,Eg as getOllamaProviderEntries,Ig as getRegisteredSlmModels,NM as getRuntimeConfigStatus,Rr as getToolSearchSchema,Ir as getToolpackConfig,$w as getUserHomeDir,Zo as gitAddTool,tr as gitBlameTool,rr as gitBranchCreateTool,or as gitBranchListTool,nr as gitCheckoutTool,er as gitCommitTool,Vo as gitDiffTool,Xo as gitLogTool,Yo as gitStatusTool,Hu as gitToolsProject,Bt as httpDeleteTool,Kt as httpDownloadTool,Ut as httpGetTool,Wt as httpPostTool,Gt as httpPutTool,mp as httpToolsProject,AM as initializeGlobalConfigIfFirstRun,Fs as isDataUri,Og as isRegisteredSlm,Dr as isToolSearchTool,ps as k8sApplyManifestTool,ms as k8sDeleteResourceTool,ls as k8sDescribeTool,fs as k8sGetConfigMapTool,cs as k8sGetLogsTool,hs as k8sGetNamespacesTool,us as k8sListDeploymentsTool,as as k8sListPodsTool,ds as k8sListServicesTool,gs as k8sSwitchContextTool,hw as k8sToolsProject,ys as k8sWaitForDeploymentTool,_o as loadFullConfig,EM as loadRuntimeConfig,Ht as loadToolsConfig,Rg as normalizeImagePart,le as ollamaRequest,Lr as ollamaStream,qs as parseDataUri,Us as readFileAsBase64,jr as reloadToolpackConfig,Ag as removeBypassRule,Mh as saveToolsConfig,Ft as systemCwdTool,qt as systemDiskUsageTool,jt as systemEnvTool,It as systemInfoTool,Lt as systemSetEnvTool,_c as systemToolsProject,_g as toDataUri,Be as toolSearchDefinition,Yt as webExtractLinksTool,Jt as webFetchTool,Qt as webScrapeTool,zt as webSearchTool,Am as webToolsProject};
|