toolpack-sdk 1.4.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,121 +1,303 @@
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(`
1
+ var Xb=Object.defineProperty;var h=(r,e)=>()=>(r&&(e=r(r=0)),e);var le=(r,e)=>{for(var t in e)Xb(r,t,{get:e[t],enumerable:!0})};import Yb from"path";import{fileURLToPath as Zb}from"url";var ew,tw,d,l=h(()=>{"use strict";ew=()=>Zb(import.meta.url),tw=()=>Yb.dirname(ew()),d=tw()});function cC(r){return!r||typeof r!="object"?!1:["CONTEXT_WINDOW_EXCEEDED","INSUFFICIENT_CONTEXT","SUMMARIZATION_ERROR","CONTEXT_WINDOW_CONFIG_ERROR","CONVERSATION_NOT_FOUND"].includes(r.code)}function pC(r,e){return r instanceof Er?{shouldRetry:r.isRetryable(),shouldFallback:!0,action:r.isRetryable()?"prune":"fail",message:r.getSuggestedRecovery()}:r instanceof _r?{shouldRetry:!1,shouldFallback:!0,action:r.strategy==="fail"?"prune":"none",message:`Context window exceeded. Strategy: ${r.strategy}`}:r instanceof $r?{shouldRetry:!1,shouldFallback:!0,action:"fail",message:"Insufficient context after recovery attempts"}:{shouldRetry:!1,shouldFallback:!1,action:"none",message:"Unknown context window error"}}var A,we,Pe,j,W,Qe,Yi,Zi,_r,$r,Er,ea,ta,ce=h(()=>{"use strict";l();A=class extends Error{constructor(t,o,n,s){super(t);this.code=o;this.statusCode=n;this.cause=s;this.name="SDKError"}code;statusCode;cause},we=class extends A{constructor(e,t){super(e,"AUTHENTICATION_ERROR",401,t),this.name="AuthenticationError"}},Pe=class extends A{constructor(t,o,n){super(t,"RATE_LIMIT_ERROR",429,n);this.retryAfter=o;this.name="RateLimitError"}retryAfter},j=class extends A{constructor(e,t){super(e,"INVALID_REQUEST_ERROR",400,t),this.name="InvalidRequestError"}},W=class extends A{constructor(e,t="PROVIDER_ERROR",o=500,n){super(e,t,o,n),this.name="ProviderError"}},Qe=class extends A{constructor(e,t){super(e,"CONNECTION_ERROR",503,t),this.name="ConnectionError"}},Yi=class extends A{constructor(t,o,n){super(t,"PAGE_ERROR",502,n);this.pageUrl=o;this.name="PageError"}pageUrl},Zi=class extends A{constructor(t,o,n){super(t,"TIMEOUT_ERROR",504,n);this.phase=o;this.name="TimeoutError"}phase},_r=class extends A{constructor(t,o,n,s,i,a){super(t,"CONTEXT_WINDOW_EXCEEDED",400,a);this.conversationId=o;this.currentTokens=n;this.contextWindowLimit=s;this.strategy=i;this.name="ContextWindowExceededError"}conversationId;currentTokens;contextWindowLimit;strategy;getOverageTokens(){return Math.max(0,this.currentTokens-this.contextWindowLimit)}getUsagePercentage(){return Math.round(this.currentTokens/this.contextWindowLimit*100)}getDetailedReport(){return`
2
+ Context Window Exceeded
3
+ =======================
4
+ Conversation ID: ${this.conversationId}
5
+ Current Tokens: ${this.currentTokens}
6
+ Context Window Limit: ${this.contextWindowLimit}
7
+ Overage: ${this.getOverageTokens()} tokens
8
+ Usage: ${this.getUsagePercentage()}%
9
+ Strategy: ${this.strategy}
10
+
11
+ Message: ${this.message}
12
+ `.trim()}},$r=class extends A{constructor(t,o,n,s,i,a){super(t,"INSUFFICIENT_CONTEXT",400,a);this.conversationId=o;this.requiredTokens=n;this.availableTokens=s;this.minimumRequiredTokens=i;this.name="InsufficientContextError"}conversationId;requiredTokens;availableTokens;minimumRequiredTokens;getDeficit(){return Math.max(0,this.requiredTokens-this.availableTokens)}isRecoverable(){return this.availableTokens>=this.minimumRequiredTokens*.5}getDetailedReport(){return`
13
+ Insufficient Context
14
+ ====================
15
+ Conversation ID: ${this.conversationId}
16
+ Required Tokens: ${this.requiredTokens}
17
+ Available Tokens: ${this.availableTokens}
18
+ Deficit: ${this.getDeficit()} tokens
19
+ Minimum Required: ${this.minimumRequiredTokens}
20
+ Recoverable: ${this.isRecoverable()?"Yes":"No"}
21
+
22
+ Message: ${this.message}
23
+ `.trim()}},Er=class extends A{constructor(t,o,n,s,i,a){super(t,"SUMMARIZATION_ERROR",500,a);this.conversationId=o;this.messageCount=n;this.failureReason=s;this.summaryAttempt=i;this.name="SummarizationError"}conversationId;messageCount;failureReason;summaryAttempt;isRetryable(){return this.failureReason==="provider_error"||this.failureReason==="insufficient_tokens"}getSuggestedRecovery(){switch(this.failureReason){case"provider_error":return"Retry the summarization request or switch to a different summarizer model";case"invalid_response":return"Review the summarizer prompt or use a different model";case"insufficient_tokens":return"Reduce the number of messages to summarize or increase the summary token budget";case"invalid_quality":return"Adjust summarization parameters or use a more capable model";default:return"Manual intervention required"}}getDetailedReport(){let t=`
24
+ Summarization Error
25
+ ===================
26
+ Conversation ID: ${this.conversationId}
27
+ Messages Attempted: ${this.messageCount}
28
+ Failure Reason: ${this.failureReason}
29
+ Retryable: ${this.isRetryable()?"Yes":"No"}
30
+ Recovery Action: ${this.getSuggestedRecovery()}
31
+
32
+ Message: ${this.message}`;return this.summaryAttempt?t+`
33
+
34
+ Partial Summary:
35
+ ${this.summaryAttempt.substring(0,500)}${this.summaryAttempt.length>500?"...":""}`:t.trim()}},ea=class extends A{constructor(t,o,n,s,i){super(t,"CONTEXT_WINDOW_CONFIG_ERROR",400,i);this.configField=o;this.providedValue=n;this.constraint=s;this.name="ContextWindowConfigError"}configField;providedValue;constraint;getDetailedReport(){return`
36
+ Context Window Configuration Error
37
+ ===================================
38
+ Field: ${this.configField}
39
+ Provided Value: ${JSON.stringify(this.providedValue)}
40
+ Constraint: ${this.constraint}
41
+
42
+ Message: ${this.message}
43
+ `.trim()}},ta=class extends A{constructor(t,o,n){super(t,"CONVERSATION_NOT_FOUND",404,n);this.conversationId=o;this.name="ConversationNotFoundError"}conversationId}});var dw,re,Lt=h(()=>{"use strict";l();dw={enabled:!1,alwaysLoadedTools:[],alwaysLoadedCategories:[],searchResultLimit:5,cacheDiscoveredTools:!0},re={enabled:!0,autoExecute:!0,maxToolRounds:5,toolChoicePolicy:"auto",resultMaxChars:2e4,enabledTools:[],enabledToolCategories:[],toolSearch:dw}});import{appendFileSync as da,mkdirSync as uw}from"fs";import{dirname as fw,isAbsolute as gw,join as hw,resolve as yw}from"path";function ma(r){if(!r)return;let e=r.toLowerCase();if(e in Lr)return e;console.warn(`[Toolpack Warning] Invalid log level "${r}". Falling back to "info".`)}function ua(r){if(r?.enabled!==void 0&&(ft=r.enabled),r?.filePath&&(Te=r.filePath),r?.level&&(jt=ma(r.level)||"info"),process.env.TOOLPACK_SDK_LOG_ENABLED!==void 0&&(ft=process.env.TOOLPACK_SDK_LOG_ENABLED==="true"),process.env.TOOLPACK_SDK_LOG_FILE&&(Te=process.env.TOOLPACK_SDK_LOG_FILE,ft=!0),process.env.TOOLPACK_SDK_LOG_LEVEL&&(jt=ma(process.env.TOOLPACK_SDK_LOG_LEVEL)||jt),process.env.TOOLPACK_SDK_LOG_CONSOLE!==void 0&&(jr=process.env.TOOLPACK_SDK_LOG_CONSOLE==="true"),r?.console!==void 0&&process.env.TOOLPACK_SDK_LOG_CONSOLE===void 0&&(jr=r.console),ft)try{Te=gw(Te)?Te:yw(process.cwd(),Te),uw(fw(Te),{recursive:!0}),da(Te,`[${new Date().toISOString()}] [INFO] [Logger] initialized level=${jt} file=${Te}
44
+ `)}catch(e){console.warn(`[Toolpack Warning] Failed to initialize log file "${Te}": ${e.message}`),ft=!1}}function Ye(r){return ft?Lr[r]<=Lr[jt]:!1}function Ft(r,e){if(!Ye(r))return;let o=`[${new Date().toISOString()}] [${r.toUpperCase()}] ${fa(e)}`;da(Te,o+`
45
+ `),jr&&(r==="error"?console.error:r==="warn"?console.warn:console.log)(o)}function pe(r){Ft("error",r)}function I(r){Ft("warn",r)}function P(r){Ft("info",r)}function y(r){Ft("debug",r)}function Ae(r){Ft("trace",r)}function fa(r){return r.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]").replace(/\bghs_[A-Za-z0-9]{10,}\b/g,"ghs_[REDACTED]").replace(/\bghp_[A-Za-z0-9]{10,}\b/g,"ghp_[REDACTED]").replace(/\bghu_[A-Za-z0-9]{10,}\b/g,"ghu_[REDACTED]").replace(/\bghr_[A-Za-z0-9]{10,}\b/g,"ghr_[REDACTED]")}function O(r,e=200){try{let t=typeof r=="string"?r:JSON.stringify(r),o=fa(t);return o.length<=e?o:`${o.slice(0,e)}\u2026`}catch{return"[Unserializable]"}}function Y(r,e,t){Ye("debug")&&(y(`[${e}][${r}] Messages (${t.length}):`),t.forEach((o,n)=>{y(`[${e}][${r}] #${n} role=${o?.role} content=${O(o?.content,300)}`)}))}var Lr,ft,jt,Te,jr,k=h(()=>{"use strict";l();Lr={error:0,warn:1,info:2,debug:3,trace:4},ft=!1,jt="info",Te=hw(process.cwd(),"toolpack-sdk.log"),jr=!1});var qt={};le(qt,{fetchUrlAsBase64:()=>Pa,getMimeType:()=>xa,isDataUri:()=>va,normalizeImagePart:()=>xw,parseDataUri:()=>Ca,readFileAsBase64:()=>ka,toDataUri:()=>Tw});import*as wa from"fs/promises";import*as Ta from"path";function xa(r){let e=Ta.extname(r).toLowerCase();return ww[e]||"application/octet-stream"}function va(r){return r.startsWith("data:")}function Ca(r){let e=r.match(/^data:(.*?);base64,(.+)$/);return e?{mimeType:e[1],data:e[2]}:null}function Tw(r,e){return`data:${e};base64,${r}`}async function ka(r){try{return{data:(await wa.readFile(r)).toString("base64"),mimeType:xa(r)}}catch(e){throw new j(`Failed to read image file: ${r}`,e)}}async function Pa(r){try{let e=await fetch(r);if(!e.ok)throw new Error(`HTTP ${e.status} ${e.statusText}`);let t=await e.arrayBuffer(),o=Buffer.from(t),n=e.headers.get("content-type")||"application/octet-stream";return n=n.split(";")[0].trim(),{data:o.toString("base64"),mimeType:n}}catch(e){throw new W(`Failed to download image from URL: ${r}`,"FETCH_ERROR",500,e)}}async function xw(r){if(r.type==="image_data")return{data:r.image_data.data,mimeType:r.image_data.mimeType};if(r.type==="image_file")return await ka(r.image_file.path);if(r.type==="image_url"){let e=r.image_url.url;if(va(e)){let t=Ca(e);if(!t)throw new j(`Malformed data URI provided in image_url: ${e.substring(0,50)}...`);return t}return await Pa(e)}throw new j(`Unknown ImagePart type: ${r.type}`)}var ww,gt=h(()=>{"use strict";l();ce();ww={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".heic":"image/heic",".heif":"image/heif"}});var Ma,Oa,Na,Aa,Ia,La=h(()=>{"use strict";l();Ma="fs.read_file",Oa="Read File",Na="Read the contents of a file at the given path. Returns the file content as a string.",Aa="filesystem",Ia={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 yt from"fs";async function Ew(r){let e=r.path,t=r.encoding||"utf-8";if(y(`[fs.read-file] execute path="${e}" encoding=${t}`),!e)throw new Error("path is required");if(!yt.existsSync(e))throw new Error(`File not found: ${e}`);if(yt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);return yt.readFileSync(e,t)}var Bt,Br=h(()=>{"use strict";l();La();k();Bt={name:Ma,displayName:Oa,description:Na,parameters:Ia,category:Aa,execute:Ew}});var ja,Fa,qa,Wa,Ua,Ga=h(()=>{"use strict";l();ja="fs.write_file",Fa="Write File",qa="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.",Wa="filesystem",Ua={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 bt from"fs";import*as Ba from"path";async function Dw(r){let e=r.path,t=r.content,o=r.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 n=Ba.dirname(e);return bt.existsSync(n)||bt.mkdirSync(n,{recursive:!0}),bt.writeFileSync(e,t,o),`File written successfully: ${e} (${Buffer.byteLength(t,o)} bytes)`}var zt,zr=h(()=>{"use strict";l();Ga();k();zt={name:ja,displayName:Fa,description:qa,parameters:Ua,category:Wa,execute:Dw,confirmation:{level:"high",reason:"This will overwrite the entire file contents.",showArgs:["path"]}}});var za,Ha,Ka,Ja,Va,Qa=h(()=>{"use strict";l();za="fs.append_file",Ha="Append File",Ka="Append content to the end of a file. Creates the file if it does not exist.",Ja="filesystem",Va={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 wt from"fs";import*as Xa from"path";async function Mw(r){let e=r.path,t=r.content,o=r.encoding||"utf-8";if(!e)throw new Error("path is required");if(t==null)throw new Error("content is required");let n=Xa.dirname(e);return wt.existsSync(n)||wt.mkdirSync(n,{recursive:!0}),wt.appendFileSync(e,t,o),`Content appended to: ${e} (${Buffer.byteLength(t,o)} bytes appended)`}var Ht,Hr=h(()=>{"use strict";l();Qa();Ht={name:za,displayName:Ha,description:Ka,parameters:Va,category:Ja,execute:Mw,confirmation:{level:"medium",reason:"This will modify the file by appending content.",showArgs:["path"]}}});var Ya,Za,el,tl,ol,nl=h(()=>{"use strict";l();Ya="fs.delete_file",Za="Delete File",el="Remove/delete a file from the filesystem. Does not delete directories.",tl="filesystem",ol={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to delete"}},required:["path"]}});import*as Tt from"fs";async function Ow(r){let e=r.path;if(y(`[fs.delete-file] execute path="${e}"`),!e)throw new Error("path is required");if(!Tt.existsSync(e))throw new Error(`File not found: ${e}`);if(Tt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}. Use a different tool to remove directories.`);return Tt.unlinkSync(e),`File deleted successfully: ${e}`}var Kt,Kr=h(()=>{"use strict";l();nl();k();Kt={name:Ya,displayName:Za,description:el,parameters:ol,category:tl,execute:Ow,confirmation:{level:"high",reason:"This will permanently delete the file. This action cannot be undone.",showArgs:["path"]}}});var rl,sl,il,al,ll,cl=h(()=>{"use strict";l();rl="fs.exists",sl="Exists",il="Check if a file or directory exists at the given path. Returns true or false.",al="filesystem",ll={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to check"}},required:["path"]}});import*as pl from"fs";async function Nw(r){let e=r.path;if(!e)throw new Error("path is required");let t=pl.existsSync(e);return JSON.stringify({exists:t,path:e})}var Jt,Jr=h(()=>{"use strict";l();cl();Jt={name:rl,displayName:sl,description:il,parameters:ll,category:al,execute:Nw}});var ml,dl,ul,fl,gl,hl=h(()=>{"use strict";l();ml="fs.stat",dl="Stat",ul="Get file or directory information including size, type, and modification date.",fl="filesystem",gl={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to get info for"}},required:["path"]}});import*as _n from"fs";async function Aw(r){let e=r.path;if(!e)throw new Error("path is required");if(!_n.existsSync(e))throw new Error(`Path not found: ${e}`);let t=_n.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 Vt,Vr=h(()=>{"use strict";l();hl();Vt={name:ml,displayName:dl,description:ul,parameters:gl,category:fl,execute:Aw}});var yl,bl,wl,Tl,xl,vl=h(()=>{"use strict";l();yl="fs.list_dir",bl="List Directory",wl="List files and directories at the given path. Optionally recurse into subdirectories.",Tl="filesystem",xl={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 tt from"fs";import*as Cl from"path";function kl(r,e,t,o=""){let n=tt.readdirSync(r,{withFileTypes:!0});for(let s of n){let i=Cl.join(r,s.name),a=o?`${o}/${s.name}`:s.name;if(s.isDirectory())t.push({name:a,type:"directory",size:0}),e&&kl(i,!0,t,a);else if(s.isFile()){let c=tt.statSync(i);t.push({name:a,type:"file",size:c.size})}}}async function Iw(r){let e=r.path,t=r.recursive===!0;if(!e)throw new Error("path is required");if(!tt.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!tt.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let n=[];return kl(e,t,n),JSON.stringify(n,null,2)}var Qt,Qr=h(()=>{"use strict";l();vl();Qt={name:yl,displayName:bl,description:wl,parameters:xl,category:Tl,execute:Iw}});var Pl,Sl,Rl,_l,$l,El=h(()=>{"use strict";l();Pl="fs.create_dir",Sl="Create Directory",Rl="Create a directory at the given path. Creates parent directories recursively if they do not exist.",_l="filesystem",$l={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 xt from"fs";async function Lw(r){let e=r.path,t=r.recursive!==!1;if(!e)throw new Error("path is required");if(xt.existsSync(e)){if(xt.statSync(e).isDirectory())return`Directory already exists: ${e}`;throw new Error(`Path exists but is not a directory: ${e}`)}return xt.mkdirSync(e,{recursive:t}),`Directory created: ${e}`}var Xt,Xr=h(()=>{"use strict";l();El();Xt={name:Pl,displayName:Sl,description:Rl,parameters:$l,category:_l,execute:Lw}});var Dl,Ml,Ol,Nl,Al,Il=h(()=>{"use strict";l();Dl="fs.move",Ml="Move",Ol="Move or rename a file or directory from one path to another.",Nl="filesystem",Al={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 ot from"fs";import*as Ll from"path";async function jw(r){let e=r.path,t=r.new_path;if(!e)throw new Error("path is required");if(!t)throw new Error("new_path is required");if(!ot.existsSync(e))throw new Error(`Source not found: ${e}`);let o=Ll.dirname(t);return ot.existsSync(o)||ot.mkdirSync(o,{recursive:!0}),ot.renameSync(e,t),`Moved: ${e} \u2192 ${t}`}var Yt,Yr=h(()=>{"use strict";l();Il();Yt={name:Dl,displayName:Ml,description:Ol,parameters:Al,category:Nl,execute:jw,confirmation:{level:"high",reason:"This will move/rename the file or directory, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var jl,Fl,ql,Wl,Ul,Gl=h(()=>{"use strict";l();jl="fs.copy",Fl="Copy",ql="Copy a file or directory from one path to another. Recursively copies directories.",Wl="filesystem",Ul={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 se from"fs";import*as Zt from"path";function Bl(r,e){if(se.statSync(r).isDirectory()){se.existsSync(e)||se.mkdirSync(e,{recursive:!0});let o=se.readdirSync(r);for(let n of o)Bl(Zt.join(r,n),Zt.join(e,n))}else se.copyFileSync(r,e)}async function Fw(r){let e=r.path,t=r.new_path;if(!e)throw new Error("path is required");if(!t)throw new Error("new_path is required");if(!se.existsSync(e))throw new Error(`Source not found: ${e}`);let o=Zt.dirname(t);return se.existsSync(o)||se.mkdirSync(o,{recursive:!0}),Bl(e,t),`Copied ${se.statSync(e).isDirectory()?"directory":"file"}: ${e} \u2192 ${t}`}var eo,Zr=h(()=>{"use strict";l();Gl();eo={name:jl,displayName:Fl,description:ql,parameters:Ul,category:Wl,execute:Fw,confirmation:{level:"medium",reason:"This will copy files or directories, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var zl,Hl,Kl,Jl,Vl,Ql=h(()=>{"use strict";l();zl="fs.read_file_range",Hl="Read File Range",Kl="Read a specific range of lines from a file. Useful for reading portions of large files without loading the entire content.",Jl="filesystem",Vl={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 vt from"fs";async function qw(r){let e=r.path,t=r.start_line,o=r.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(!vt.existsSync(e))throw new Error(`File not found: ${e}`);if(vt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let i=vt.readFileSync(e,"utf-8").split(`
46
+ `),a=i.length,c=Math.min(t,a),p=Math.min(o,a),f=i.slice(c-1,p).map((g,w)=>`${c+w}: ${g}`).join(`
4
47
  `);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"}):
48
+ ${f}`}var to,es=h(()=>{"use strict";l();Ql();to={name:zl,displayName:Hl,description:Kl,parameters:Vl,category:Jl,execute:qw}});var Xl,Yl,Zl,ec,tc,oc=h(()=>{"use strict";l();Xl="fs.search",Yl="Search",Zl="Search for text in files within a directory. Returns matching lines with file paths and line numbers.",ec="filesystem",tc={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 Le from"fs";import*as nc from"path";function Ww(r,e,t,o){try{let s=Le.readFileSync(r,"utf-8").split(`
49
+ `);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:r,line:i+1,content:a.trim()})}}catch{}}function rc(r,e,t,o,n){let s=Le.readdirSync(r,{withFileTypes:!0});for(let i of s){if(o.length>=n)break;let a=nc.join(r,i.name);i.isDirectory()&&t?rc(a,e,!0,o,n):i.isFile()&&Ww(a,e,o,n)}}async function Uw(r){let e=r.path,t=r.query,o=r.recursive!==!1,n=r.max_results||50,s=!!r.regex,i=!!r.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 g=i?"":"i";a=new RegExp(f,g)}if(!Le.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Le.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let p=[];if(rc(e,a,o,p,n),p.length===0)return`No matches found for "${t}" in ${e}`;let m=p.length>=n?`
50
+ (results capped at ${n})`:"";return JSON.stringify(p,null,2)+m}var oo,ts=h(()=>{"use strict";l();oc();k();oo={name:Xl,displayName:Yl,description:Zl,parameters:tc,category:ec,execute:Uw}});var sc,ic,ac,lc,cc,pc=h(()=>{"use strict";l();sc="fs.replace_in_file",ic="Replace In File",ac="Find and replace text in a file. Returns the number of replacements made.",lc="filesystem",cc={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 je from"fs";async function Gw(r){let e=r.path,t=r.search,o=r.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(!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 s=je.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 je.writeFileSync(e,c,"utf-8"),`Replaced ${i} occurrence(s) in ${e}`}var no,os=h(()=>{"use strict";l();pc();no={name:sc,displayName:ic,description:ac,parameters:cc,category:lc,execute:Gw,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 mc,dc,uc,fc,gc,hc=h(()=>{"use strict";l();mc="fs.tree",dc="Tree",uc="Get a tree representation of a directory structure. Useful for understanding project layout at a glance.",fc="filesystem",gc={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 Ct from"fs";import*as $n from"path";function yc(r,e,t,o,n){if(t>o)return;let i=Ct.readdirSync(r,{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()?(n.push(`${e}${m}${c.name}/`),yc($n.join(r,c.name),e+f,t+1,o,n)):n.push(`${e}${m}${c.name}`)}}async function Bw(r){let e=r.path,t=r.depth||3;if(!e)throw new Error("path is required");if(!Ct.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Ct.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let s=[`${$n.basename(e)}/`];return yc(e,"",1,t,s),s.join(`
51
+ `)}var ro,ns=h(()=>{"use strict";l();hc();ro={name:mc,displayName:dc,description:uc,parameters:gc,category:fc,execute:Bw}});var bc,wc,Tc,xc,vc,Cc=h(()=>{"use strict";l();bc="fs.glob",wc="Glob Pattern Match",Tc='Find files matching glob patterns (e.g., "**/*.ts", "src/**/*.test.js")',xc="filesystem",vc={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 zw from"fast-glob";async function Hw(r){let e=r.pattern,t=r.cwd,o=r.ignore,n=r.onlyFiles!==!1,s=r.onlyDirectories===!0,i=r.absolute===!0;if(!e)throw new Error("pattern is required");let a=e.replace(/\\/g,"/");try{let c=await zw(a,{cwd:t||process.cwd(),ignore:o||["node_modules/**",".git/**"],onlyFiles:n,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 so,rs=h(()=>{"use strict";l();Cc();so={name:bc,displayName:wc,description:Tc,parameters:vc,category:xc,execute:Hw}});var kc,Pc,Sc,Rc,_c,$c=h(()=>{"use strict";l();kc="fs.delete_dir",Pc="Delete Directory",Sc="Delete a directory and all its contents recursively",Rc="filesystem",_c={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 Kw}from"fs/promises";import{existsSync as Jw,statSync as Vw}from"fs";async function Qw(r){let e=r.path,t=r.force!==!1;if(!e)throw new Error("path is required");if(!Jw(e))throw new Error(`Directory does not exist: ${e}`);if(!Vw(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);try{return await Kw(e,{recursive:!0,force:t}),`Directory deleted successfully: ${e}`}catch(n){throw new Error(`Failed to delete directory "${e}": ${n.message}`)}}var io,ss=h(()=>{"use strict";l();$c();io={name:kc,displayName:Pc,description:Sc,parameters:_c,category:Rc,execute:Qw,confirmation:{level:"high",reason:"This will recursively delete the directory and all its contents. This action cannot be undone.",showArgs:["path"]}}});var Ec,Dc,Mc,Oc,Nc,Ac=h(()=>{"use strict";l();Ec="fs.batch_read",Dc="Batch Read Files",Mc="Read multiple files efficiently in one operation. Returns content for each file or error if read fails.",Oc="filesystem",Nc={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 Xw}from"fs/promises";async function Yw(r){let e=r.paths,t=r.encoding||"utf-8",o=r.continueOnError!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("paths array is required and must not be empty");let n=[],s=0,i=0;for(let a of e)try{let c=await Xw(a,t);n.push({path:a,content:c,success:!0}),s++}catch(c){let p=c.message;if(n.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:n},null,2)}var ao,is=h(()=>{"use strict";l();Ac();ao={name:Ec,displayName:Dc,description:Mc,parameters:Nc,category:Oc,execute:Yw}});var Ic,Lc,jc,Fc,qc,Wc=h(()=>{"use strict";l();Ic="fs.batch_write",Lc="Batch Write Files",jc="Write multiple files atomically in one operation. If atomic mode is enabled, all writes succeed or all are rolled back on failure.",Fc="filesystem",qc={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 Uc,mkdir as Zw,readFile as eT,unlink as tT}from"fs/promises";import{dirname as oT,resolve as nT}from"path";import{existsSync as Gc}from"fs";async function rT(r){let e=r.files,t=r.encoding||"utf-8",o=r.atomic!==!1,n=r.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=nT(a.path);if(o){let p=Gc(c),m={path:c,existed:p};p&&(m.originalContent=await eT(c,t)),s.push(m)}if(n){let p=oT(c);await Zw(p,{recursive:!0})}await Uc(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 Uc(c.path,c.originalContent,t):!c.existed&&Gc(c.path)&&await tT(c.path)}catch{}throw new Error(`Batch write failed and rolled back: ${a.message}`)}throw new Error(`Batch write failed: ${a.message}`)}}var lo,as=h(()=>{"use strict";l();Wc();lo={name:Ic,displayName:Lc,description:jc,parameters:qc,category:Fc,execute:rT,confirmation:{level:"high",reason:"This will overwrite multiple files at once.",showArgs:["files"]}}});var zc={};le(zc,{fsAppendFileTool:()=>Ht,fsBatchReadTool:()=>ao,fsBatchWriteTool:()=>lo,fsCopyTool:()=>eo,fsCreateDirTool:()=>Xt,fsDeleteDirTool:()=>io,fsDeleteFileTool:()=>Kt,fsExistsTool:()=>Jt,fsGlobTool:()=>so,fsListDirTool:()=>Qt,fsMoveTool:()=>Yt,fsReadFileRangeTool:()=>to,fsReadFileTool:()=>Bt,fsReplaceInFileTool:()=>no,fsSearchTool:()=>oo,fsStatTool:()=>Vt,fsToolsProject:()=>Bc,fsTreeTool:()=>ro,fsWriteFileTool:()=>zt});var Bc,ls=h(()=>{"use strict";l();Br();zr();Hr();Kr();Jr();Vr();Qr();Xr();Yr();Zr();es();ts();os();ns();rs();ss();is();as();Br();zr();Hr();Kr();Jr();Vr();Qr();Xr();Yr();Zr();es();ts();os();ns();rs();ss();is();as();Bc={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:[Bt,zt,Ht,Kt,Jt,Vt,Qt,Xt,Yt,eo,to,oo,no,ro,so,io,ao,lo],dependencies:{"fast-glob":"^3.3.2"}}});var Hc,Kc,Jc,Vc,Qc,Xc=h(()=>{"use strict";l();Hc="exec.run",Kc="Run",Jc="Execute a command directly (without shell) and return its output. Use exec.run_shell for pipes, redirects, or shell features.",Vc="execution",Qc={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 sT}from"child_process";async function iT(r){let e=r.command,t=r.cwd,o=r.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 sT(e,{cwd:t,timeout:o,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"]})||"(command completed with no output)"}catch(n){let s=n.stdout||"",i=n.stderr||"";return`Command failed (exit code ${n.status??"unknown"}):
9
52
  STDOUT:
10
53
  ${s}
11
54
  STDERR:
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"}):
55
+ ${i}`}}var co,cs=h(()=>{"use strict";l();Xc();k();co={name:Hc,displayName:Kc,description:Jc,parameters:Qc,category:Vc,execute:iT,confirmation:{level:"high",reason:"This will execute a shell command on the host system.",showArgs:["command"]}}});var Yc,Zc,ep,tp,op,np=h(()=>{"use strict";l();Yc="exec.run_shell",Zc="Run Shell",ep="Execute a command through the system shell. Supports pipes, redirects, environment variable expansion, and other shell features.",tp="execution",op={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 aT}from"child_process";function lT(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function cT(r){let e=r.command,t=r.cwd,o=r.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 aT(e,{cwd:t,timeout:o,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],shell:lT()})||"(command completed with no output)"}catch(n){let s=n.stdout||"",i=n.stderr||"";return`Command failed (exit code ${n.status??"unknown"}):
13
56
  STDOUT:
14
57
  ${s}
15
58
  STDERR:
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)}
59
+ ${i}`}}var po,ps=h(()=>{"use strict";l();np();k();po={name:Yc,displayName:Zc,description:ep,parameters:op,category:tp,execute:cT,confirmation:{level:"high",reason:"This will execute a shell command with explicit shell context.",showArgs:["command"]}}});function rp(r,e,t){let o=`proc_${pT++}`,n={id:o,command:r,cwd:e,process:t,startedAt:new Date().toISOString(),stdout:"",stderr:""};return t.stdout?.on("data",s=>{n.stdout+=s.toString(),n.stdout.length>1e6&&(n.stdout=n.stdout.slice(-5e5))}),t.stderr?.on("data",s=>{n.stderr+=s.toString(),n.stderr.length>1e6&&(n.stderr=n.stderr.slice(-5e5))}),t.on("exit",()=>{}),En.set(o,n),o}function Dn(r){return En.get(r)}function sp(r){let e=En.get(r);if(!e)return!1;let t=e.process.exitCode===null;return t&&e.process.kill("SIGTERM"),t}function ip(){return Array.from(En.values()).map(r=>({id:r.id,command:r.command,cwd:r.cwd,startedAt:r.startedAt,alive:r.process.exitCode===null,pid:r.process.pid}))}var En,pT,mo=h(()=>{"use strict";l();En=new Map,pT=1});var ap,lp,cp,pp,mp,dp=h(()=>{"use strict";l();ap="exec.run_background",lp="Run Background",cp="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.",pp="execution",mp={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 mT}from"child_process";async function dT(r){let e=r.command,t=r.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=mT(e,[],{cwd:t,shell:!0,stdio:["ignore","pipe","pipe"],detached:!1}),n=rp(e,t,o);return JSON.stringify({id:n,pid:o.pid,command:e,message:`Background process started. Use exec.read_output("${n}") to read output, exec.kill("${n}") to stop.`})}var uo,ms=h(()=>{"use strict";l();mo();dp();k();uo={name:ap,displayName:lp,description:cp,parameters:mp,category:pp,execute:dT,confirmation:{level:"high",reason:"This will spawn a background process that runs unsupervised.",showArgs:["command"]}}});var up,fp,gp,hp,yp,bp=h(()=>{"use strict";l();up="exec.read_output",fp="Read Output",gp="Read stdout and stderr from a background process started with exec.run_background.",hp="execution",yp={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function uT(r){let e=r.process_id;if(!e)throw new Error("process_id is required");let t=Dn(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 fo,ds=h(()=>{"use strict";l();mo();bp();fo={name:up,displayName:fp,description:gp,parameters:yp,category:hp,execute:uT}});var wp,Tp,xp,vp,Cp,kp=h(()=>{"use strict";l();wp="exec.kill",Tp="Kill",xp="Kill a background process started with exec.run_background.",vp="execution",Cp={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function fT(r){let e=r.process_id;if(!e)throw new Error("process_id is required");let t=Dn(e);if(!t)throw new Error(`Process not found: ${e}`);return sp(e)?`Process ${e} (${t.command}) killed successfully.`:`Process ${e} (${t.command}) was already terminated (exit code: ${t.process.exitCode}).`}var go,us=h(()=>{"use strict";l();mo();kp();go={name:wp,displayName:Tp,description:xp,parameters:Cp,category:vp,execute:fT,confirmation:{level:"medium",reason:"This will terminate a running process.",showArgs:["process_id"]}}});var Pp,Sp,Rp,_p,$p,Ep=h(()=>{"use strict";l();Pp="exec.list_processes",Sp="List Processes",Rp="List all managed background processes started with exec.run_background, including their status.",_p="execution",$p={type:"object",properties:{}}});async function gT(r){let e=ip();return e.length===0?"No managed background processes.":JSON.stringify(e,null,2)}var ho,fs=h(()=>{"use strict";l();mo();Ep();ho={name:Pp,displayName:Sp,description:Rp,parameters:$p,category:_p,execute:gT}});var Mp={};le(Mp,{execKillTool:()=>go,execListProcessesTool:()=>ho,execReadOutputTool:()=>fo,execRunBackgroundTool:()=>uo,execRunShellTool:()=>po,execRunTool:()=>co,execToolsProject:()=>Dp});var Dp,gs=h(()=>{"use strict";l();cs();ps();ms();ds();us();fs();cs();ps();ms();ds();us();fs();Dp={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:[co,po,uo,fo,go,ho],dependencies:{}}});var Op,Np,Ap,Ip,Lp,jp=h(()=>{"use strict";l();Op="system.info",Np="Info",Ap="Get system information including OS, CPU, memory, and architecture.",Ip="system",Lp={type:"object",properties:{}}});import*as F from"os";async function hT(r){return y("[system.info] execute"),JSON.stringify({platform:F.platform(),arch:F.arch(),release:F.release(),hostname:F.hostname(),uptime:F.uptime(),cpus:{model:F.cpus()[0]?.model||"unknown",count:F.cpus().length},memory:{total:F.totalmem(),free:F.freemem(),used:F.totalmem()-F.freemem()},homedir:F.homedir(),tmpdir:F.tmpdir(),nodeVersion:process.version},null,2)}var yo,hs=h(()=>{"use strict";l();jp();k();yo={name:Op,displayName:Np,description:Ap,parameters:Lp,category:Ip,execute:hT}});var Fp,qp,Wp,Up,Gp,Bp=h(()=>{"use strict";l();Fp="system.env",qp="Environment",Wp="Get environment variable(s). If key is provided, returns that specific variable. Otherwise returns all environment variables.",Up="system",Gp={type:"object",properties:{key:{type:"string",description:"Specific environment variable name to get (optional, returns all if omitted)"}}}});async function yT(r){let e=r.key;if(y(`[system.env] execute key=${e??"all"}`),e){let n=process.env[e];return n===void 0?`Environment variable "${e}" is not set.`:JSON.stringify({[e]:n})}let t={},o=Object.keys(process.env).sort();for(let n of o)process.env[n]!==void 0&&(t[n]=process.env[n]);return JSON.stringify(t,null,2)}var bo,ys=h(()=>{"use strict";l();Bp();k();bo={name:Fp,displayName:qp,description:Wp,parameters:Gp,category:Up,execute:yT}});var zp,Hp,Kp,Jp,Vp,Qp=h(()=>{"use strict";l();zp="system.set_env",Hp="Set Environment",Kp="Set an environment variable for the current session. Does not persist across restarts.",Jp="system",Vp={type:"object",properties:{key:{type:"string",description:"Environment variable name"},value:{type:"string",description:"Value to set"}},required:["key","value"]}});async function bT(r){let e=r.key,t=r.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 wo,bs=h(()=>{"use strict";l();Qp();wo={name:zp,displayName:Hp,description:Kp,parameters:Vp,category:Jp,execute:bT,confirmation:{level:"medium",reason:"This will modify the process environment, affecting all subsequent operations.",showArgs:["key","value"]}}});var Xp,Yp,Zp,em,tm,om=h(()=>{"use strict";l();Xp="system.cwd",Yp="Current Directory",Zp="Get the current working directory of the process.",em="system",tm={type:"object",properties:{}}});async function wT(r){return y("[system.cwd] execute"),JSON.stringify({cwd:process.cwd()})}var To,ws=h(()=>{"use strict";l();om();k();To={name:Xp,displayName:Yp,description:Zp,parameters:tm,category:em,execute:wT}});var nm,rm,sm,im,am,lm=h(()=>{"use strict";l();nm="system.disk_usage",rm="Disk Usage",sm="Get disk usage information for a given path or the root filesystem.",im="system",am={type:"object",properties:{path:{type:"string",description:"Path to check disk usage for (default: /)",default:"/"}}}});import*as pm from"fs";import*as mm from"os";import*as Mn from"path";import{execSync as cm}from"child_process";function Ts(r){let e=["B","KB","MB","GB","TB","PB"],t=r,o=0;for(;t>=1024&&o<e.length-1;)t/=1024,o++;return`${t.toFixed(1)}${e[o]}`}async function TT(r){let t=r.path||(process.platform==="win32"?mm.tmpdir():"/");t=Mn.resolve(t);let o=process.platform==="win32";try{let n=pm.statfsSync(t),s=BigInt(n.blocks)*BigInt(n.bsize),i=BigInt(n.bavail)*BigInt(n.bsize),a=BigInt(n.bfree)*BigInt(n.bsize),c=s-a,p=s>0?Number(c*BigInt(100)/s):0;return JSON.stringify({path:t,filesystem:"statfs",size:Ts(Number(s)),used:Ts(Number(c)),available:Ts(Number(i)),usePercent:`${p}%`,mountedOn:t},null,2)}catch(n){try{if(o){let c=Mn.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=cm(p,{encoding:"utf-8",timeout:5e3,shell:"powershell.exe"}),f=JSON.parse(m.trim()),g=f.Total||0,w=f.Free||0,b=f.Used||0,T=g>0?Math.round(b/g*100):0;return JSON.stringify({path:t,filesystem:f.Name||"NTFS",size:`${(g/1024**3).toFixed(1)}G`,used:`${(b/1024**3).toFixed(1)}G`,available:`${(w/1024**3).toFixed(1)}G`,usePercent:`${T}%`,mountedOn:f.Drive||`${c}`},null,2)}let s=cm(`df -h "${t}"`,{encoding:"utf-8",timeout:5e3}),i=s.trim().split(`
60
+ `);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}: ${n?.message||n}; fallback error: ${s.message}`)}}}var xo,xs=h(()=>{"use strict";l();lm();xo={name:nm,displayName:rm,description:sm,parameters:am,category:im,execute:TT}});var um={};le(um,{systemCwdTool:()=>To,systemDiskUsageTool:()=>xo,systemEnvTool:()=>bo,systemInfoTool:()=>yo,systemSetEnvTool:()=>wo,systemToolsProject:()=>dm});var dm,vs=h(()=>{"use strict";l();hs();ys();bs();ws();xs();hs();ys();bs();ws();xs();dm={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:[yo,bo,wo,To,xo],dependencies:{}}});var fm,gm,hm,ym,bm,wm=h(()=>{"use strict";l();fm="http.get",gm="GET",hm="Make an HTTP GET request to a URL and return the response body.",ym="network",bm={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 xT(r){let e=r.url,t=r.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||{}}),n=await o.text(),s=`HTTP ${o.status} ${o.statusText}`;return o.ok?n.length>Tm?`${s}
61
+ ${n.substring(0,Tm)}
19
62
 
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)}
63
+ ... (truncated, total ${n.length} characters)`:`${s}
64
+ ${n}`:`${s}
65
+ ${n}`}var Tm,vo,Cs=h(()=>{"use strict";l();wm();k();Tm=1e5;vo={name:fm,displayName:gm,description:hm,parameters:bm,category:ym,execute:xT}});var xm,vm,Cm,km,Pm,Sm=h(()=>{"use strict";l();xm="http.post",vm="POST",Cm="Make an HTTP POST request to a URL with an optional body and return the response.",km="network",Pm={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 vT(r){let e=r.url,t=r.body,o=r.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 n=await fetch(e,{method:"POST",headers:o,body:t||void 0}),s=await n.text(),i=`HTTP ${n.status} ${n.statusText}`;return s.length>Rm?`${i}
66
+ ${s.substring(0,Rm)}
24
67
 
25
68
  ... (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)}
69
+ ${s}`}var Rm,Co,ks=h(()=>{"use strict";l();Sm();k();Rm=1e5;Co={name:xm,displayName:vm,description:Cm,parameters:Pm,category:km,execute:vT,confirmation:{level:"high",reason:"This will send an HTTP POST request with arbitrary payload.",showArgs:["url","body"]}}});var _m,$m,Em,Dm,Mm,Om=h(()=>{"use strict";l();_m="http.put",$m="PUT",Em="Make an HTTP PUT request to a URL with an optional body and return the response.",Dm="network",Mm={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 CT(r){let e=r.url,t=r.body,o=r.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 n=await fetch(e,{method:"PUT",headers:o,body:t||void 0}),s=await n.text(),i=`HTTP ${n.status} ${n.statusText}`;return s.length>Nm?`${i}
70
+ ${s.substring(0,Nm)}
28
71
 
29
72
  ... (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)}
73
+ ${s}`}var Nm,ko,Ps=h(()=>{"use strict";l();Om();k();Nm=1e5;ko={name:_m,displayName:$m,description:Em,parameters:Mm,category:Dm,execute:CT,confirmation:{level:"high",reason:"This will send an HTTP PUT request to overwrite remote resources.",showArgs:["url","body"]}}});var Am,Im,Lm,jm,Fm,qm=h(()=>{"use strict";l();Am="http.delete",Im="DELETE",Lm="Make an HTTP DELETE request to a URL and return the response.",jm="network",Fm={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 kT(r){let e=r.url,t=r.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||{}}),n=await o.text(),s=`HTTP ${o.status} ${o.statusText}`;return n.length>Wm?`${s}
74
+ ${n.substring(0,Wm)}
32
75
 
33
76
  ... (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(`
77
+ ${n}`}var Wm,Po,Ss=h(()=>{"use strict";l();qm();k();Wm=1e5;Po={name:Am,displayName:Im,description:Lm,parameters:Fm,category:jm,execute:kT,confirmation:{level:"high",reason:"This will send an HTTP DELETE request to destroy remote resources.",showArgs:["url"]}}});var Um,Gm,Bm,zm,Hm,Km=h(()=>{"use strict";l();Um="http.download",Gm="Download",Bm="Download a file from a URL and save it to a local path.",zm="network",Hm={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 kt from"fs";import*as Jm from"path";async function PT(r){let e=r.url,t=r.path,o=r.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 n=await fetch(e,{method:"GET",headers:o||{}});if(!n.ok)throw new Error(`Download failed: HTTP ${n.status} ${n.statusText}`);let s=Buffer.from(await n.arrayBuffer()),i=Jm.dirname(t);return kt.existsSync(i)||kt.mkdirSync(i,{recursive:!0}),kt.writeFileSync(t,s),`Downloaded ${e} \u2192 ${t} (${s.length} bytes)`}var So,Rs=h(()=>{"use strict";l();Km();k();So={name:Um,displayName:Gm,description:Bm,parameters:Hm,category:zm,execute:PT}});var Qm={};le(Qm,{httpDeleteTool:()=>Po,httpDownloadTool:()=>So,httpGetTool:()=>vo,httpPostTool:()=>Co,httpPutTool:()=>ko,httpToolsProject:()=>Vm});var Vm,_s=h(()=>{"use strict";l();Cs();ks();Ps();Ss();Rs();Cs();ks();Ps();Ss();Rs();Vm={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:[vo,Co,ko,Po,So],dependencies:{}}});var Xm,Ym,Zm,ed,td,od=h(()=>{"use strict";l();Xm="github.graphql.execute",Ym="GitHub GraphQL",Zm=["Execute a GitHub GraphQL query or mutation with standard headers.","NOTE: GitHub App installation tokens (ghs_*) cannot call certain write mutations.","The following mutations require a PAT and will return FORBIDDEN with an App token:","resolveReviewThread, unresolveReviewThread.","If using an App token, avoid these mutations and use fallback strategies (replies, new comments)."].join(" "),ed="github",td={type:"object",properties:{query:{type:"string",description:"GraphQL query string"},variables:{type:"object",description:"Optional GraphQL variables"},repo:{type:"string",description:"owner/name \u2014 used for token resolution when no explicit token is provided"},token:{type:"string",description:"GitHub token (App installation or PAT). Optional \u2014 omit to auto-resolve from server credentials."}},required:["query"]}});function z(r,e){let t={Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",...e||{}};return r&&(t.Authorization=`Bearer ${r}`),t}var Re=h(()=>{"use strict";l()});import*as sd from"crypto";async function G(r,e){if(e)return e;let t=process.env.GITHUB_PAT;if(t)return t;let o=process.env.GITHUB_APP_ID,n=process.env.GITHUB_APP_PRIVATE_KEY?.replace(/\\n/g,`
78
+ `);if(!o||!n)throw new Error("No GitHub token available. Set GITHUB_PAT, or GITHUB_APP_ID + GITHUB_APP_PRIVATE_KEY.");let s=await ST(o,n,r);return RT(o,n,s)}async function ST(r,e,t){if(!t)throw new Error("Cannot resolve GitHub App installation token without a repo name. Pass args.repo or set GITHUB_PAT.");let o=rd.get(t);if(o!==void 0)return o;let n=id(r,e),s=await fetch(`https://api.github.com/repos/${t}/installation`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}});if(!s.ok){let a=await s.text();throw new Error(`Failed to look up installation for ${t} (${s.status}): ${a}`)}let i=await s.json();return rd.set(t,i.id),i.id}async function RT(r,e,t){let o=nd.get(t);if(o&&o.expiresAt>Date.now()+6e4)return o.token;let n=id(r,e),s=await fetch(`https://api.github.com/app/installations/${t}/access_tokens`,{method:"POST",headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}});if(!s.ok){let a=await s.text();throw new Error(`Failed to mint installation token (${s.status}): ${a}`)}let i=await s.json();return nd.set(t,{token:i.token,expiresAt:new Date(i.expires_at).getTime()}),i.token}function id(r,e){let t=Math.floor(Date.now()/1e3),o={alg:"RS256",typ:"JWT"},n={iat:t-30,exp:t+540,iss:r},s=c=>Buffer.from(JSON.stringify(c)).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_"),i=`${s(o)}.${s(n)}`,a=sd.createSign("RSA-SHA256");return a.update(i),a.end(),`${i}.`+a.sign(e).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")}var nd,rd,xe=h(()=>{"use strict";l();nd=new Map,rd=new Map});async function _T(r){let e=r.query,t=r.variables??{},o=await G(r.repo,r.token);y(`[github.graphql.execute] query_len=${e?.length??0}`);let n=await fetch("https://api.github.com/graphql",{method:"POST",headers:z(o,{"Content-Type":"application/json"}),body:JSON.stringify({query:e,variables:t})}),s=await n.text();try{let i=JSON.parse(s);i&&Array.isArray(i.errors)&&i.errors.length>0&&y(`[github.graphql.execute] errors=${i.errors.length}`)}catch{}return`HTTP ${n.status} ${n.statusText}
79
+ ${s}`}var Ro,$s=h(()=>{"use strict";l();od();k();Re();xe();Ro={name:Xm,displayName:Ym,description:Zm,parameters:td,category:ed,execute:_T}});var ad,ld,cd,pd,md,dd=h(()=>{"use strict";l();ad="github.contents.getText",ld="Get Repo File (Text)",cd="Fetch file content (decoded text) via the GitHub Contents API.",pd="github",md={type:"object",properties:{repo:{type:"string",description:"owner/name (e.g. octo/repo)"},path:{type:"string",description:"File path within the repo"},ref:{type:"string",description:"Branch, tag, or commit sha"},token:{type:"string",description:"GitHub token (App installation or PAT)"},maxBytes:{type:"integer",description:"Optional max bytes of decoded text to return; if exceeded, result is truncated with a footer."}},required:["repo","path"]}});import{Buffer as On}from"buffer";async function $T(r){let e=r.repo,t=r.path,o=r.ref,n=await G(e,r.token),s=r.maxBytes?Number(r.maxBytes):void 0,i=t.split("/").map(m=>encodeURIComponent(m)).join("/"),a=`https://api.github.com/repos/${e}/contents/${i}${o?`?ref=${encodeURIComponent(o)}`:""}`;y(`[github.contents.getText] repo=${e} path=${t} ref=${o??""}`);let c=await fetch(a,{method:"GET",headers:z(n)}),p=await c.text();if(!c.ok)return`HTTP ${c.status} ${c.statusText}
80
+ ${p}`;try{let f=JSON.parse(p)?.content;if(typeof f=="string"){let g=On.from(f.replace(/\n/g,""),"base64").toString("utf8");if(s&&On.byteLength(g,"utf8")>s){let w=On.from(g,"utf8").subarray(0,s).toString("utf8"),b=`
81
+ \u2026 [truncated, ${s} of ${On.byteLength(g,"utf8")} bytes]`;return`HTTP ${c.status} ${c.statusText}
82
+ ${w}${b}`}return`HTTP ${c.status} ${c.statusText}
83
+ ${g}`}}catch{}return`HTTP ${c.status} ${c.statusText}
84
+ ${p}`}var _o,Es=h(()=>{"use strict";l();dd();k();Re();xe();_o={name:ad,displayName:ld,description:cd,parameters:md,category:pd,execute:$T}});var ud,fd,gd,hd,yd,bd=h(()=>{"use strict";l();ud="github.pr.reviewThreads.list",fd="List PR Review Threads",gd="List PR review threads via GraphQL (optionally unresolved only).",hd="github",yd={type:"object",properties:{repo:{type:"string",description:"owner/name"},number:{type:"integer",description:"PR number"},token:{type:"string",description:"GitHub token (App installation or PAT)"},unresolvedOnly:{type:"boolean",description:"If true, filter unresolved threads only"},first:{type:"integer",description:"Threads page size (max 100). Default 100."},after:{type:"string",description:"Cursor for pagination (GraphQL pageInfo.endCursor)."},commentsFirst:{type:"integer",description:"Comments per thread (max 100). Default 20."},includeMeta:{type:"boolean",description:"If true, return { headRefOid, threads, pageInfo } instead of array."}},required:["repo","number"]}});async function ET(r){let[e,t]=String(r.repo).split("/"),o=Number(r.number),n=await G(r.repo,r.token),s=!!r.unresolvedOnly,i=r.first?Number(r.first):100,a=r.after?String(r.after):void 0,c=r.commentsFirst?Number(r.commentsFirst):20,p=!!r.includeMeta;y(`[github.pr.reviewThreads.list] repo=${e}/${t} pr=${o} unresolvedOnly=${s} first=${i} after=${a??""} commentsFirst=${c} includeMeta=${p}`);let f=await fetch("https://api.github.com/graphql",{method:"POST",headers:z(n,{"Content-Type":"application/json"}),body:JSON.stringify({query:`query($owner:String!,$name:String!,$number:Int!,$first:Int!,$after:String,$commentsFirst:Int!){
85
+ repository(owner:$owner,name:$name){
86
+ pullRequest(number:$number){
87
+ headRefOid
88
+ reviewThreads(first:$first, after:$after){
89
+ pageInfo{ hasNextPage endCursor }
90
+ nodes{ id isResolved isOutdated comments(first:$commentsFirst){ nodes{ databaseId body author{login} path } } }
91
+ }
92
+ }
93
+ }
94
+ }`,variables:{owner:e,name:t,number:o,first:i,after:a,commentsFirst:c}})}),g=await f.text();if(!f.ok)return`HTTP ${f.status} ${f.statusText}
95
+ ${g}`;try{let w=JSON.parse(g);w&&Array.isArray(w.errors)&&w.errors.length>0&&y(`[github.pr.reviewThreads.list] errors=${w.errors.length}`);let b=w?.data?.repository?.pullRequest,T=b?.reviewThreads?.pageInfo??{hasNextPage:!1,endCursor:null},v=b?.reviewThreads?.nodes??[];if(s&&(v=v.filter(C=>C?.isResolved===!1)),p){let C={headRefOid:b?.headRefOid,threads:v,pageInfo:T};return`HTTP 200 OK
96
+ ${JSON.stringify(C)}`}return`HTTP 200 OK
97
+ ${JSON.stringify(v)}`}catch{return`HTTP ${f.status} ${f.statusText}
98
+ ${g}`}}var $o,Ds=h(()=>{"use strict";l();bd();Re();k();xe();$o={name:ud,displayName:fd,description:gd,parameters:yd,category:hd,execute:ET}});var wd,Td,xd,vd,Cd,kd=h(()=>{"use strict";l();wd="github.pr.reviewThreads.resolve",Td="Resolve Review Thread",xd=["Resolve a PR review thread via GraphQL resolveReviewThread mutation.","IMPORTANT: GitHub App installation tokens (ghs_*) cannot call this mutation \u2014 GitHub returns FORBIDDEN.","This tool only works with a Personal Access Token (PAT) that has repo scope.","If you are using a GitHub App installation token, do NOT call this tool.","Instead, post a reply on the thread acknowledging the fix and ask the author to resolve it manually."].join(" "),vd="github",Cd={type:"object",properties:{threadId:{type:"string",description:"GraphQL node ID of the review thread"},repo:{type:"string",description:"owner/name \u2014 used for token resolution when no explicit token is provided"},token:{type:"string",description:"GitHub token \u2014 MUST be a PAT with repo scope. App installation tokens (ghs_*) will receive FORBIDDEN."}},required:["threadId"]}});async function DT(r){let e=String(r.threadId),t=await G(r.repo,r.token);y(`[github.pr.reviewThreads.resolve] threadId=${e}`);let n=await fetch("https://api.github.com/graphql",{method:"POST",headers:z(t,{"Content-Type":"application/json"}),body:JSON.stringify({query:"mutation($id:ID!){ resolveReviewThread(input:{threadId:$id}) { thread { id isResolved } } }",variables:{id:e}})}),s=await n.text();if(n.ok)try{if(JSON.parse(s).errors?.find(c=>c.type==="FORBIDDEN"))return["TOOL_UNSUPPORTED_FOR_TOKEN_TYPE: resolveReviewThread is not available for GitHub App installation tokens (ghs_*).","GitHub requires a user identity (PAT with repo scope) for this operation.","Fallback action: post a reply on the thread acknowledging the fix and ask the author to resolve it manually."].join(" ")}catch{}return`HTTP ${n.status} ${n.statusText}
99
+ ${s}`}var Eo,Ms=h(()=>{"use strict";l();kd();Re();k();xe();Eo={name:wd,displayName:Td,description:xd,parameters:Cd,category:vd,execute:DT}});var Pd,Sd,Rd,_d,$d,Ed=h(()=>{"use strict";l();Pd="github.pr.reviewComments.reply",Sd="Reply to Review Comment",Rd="Reply within an existing PR review thread to maintain continuity.",_d="github",$d={type:"object",properties:{repo:{type:"string",description:"owner/name"},number:{type:"integer",description:"PR number"},inReplyTo:{type:"integer",description:"databaseId of the review comment to reply to"},body:{type:"string",description:"Reply body"},token:{type:"string",description:"GitHub token (App installation or PAT)"}},required:["repo","number","inReplyTo","body"]}});async function MT(r){let e=String(r.repo),t=Number(r.number),o=Number(r.inReplyTo),n=String(r.body),s=await G(e,r.token),i=`https://api.github.com/repos/${e}/pulls/${t}/comments/${o}/replies`;y(`[github.pr.reviewComments.reply] repo=${e} inReplyTo=${o}`);let a=await fetch(i,{method:"POST",headers:z(s,{"Content-Type":"application/json"}),body:JSON.stringify({body:n})}),c=await a.text();return`HTTP ${a.status} ${a.statusText}
100
+ ${c}`}var Do,Os=h(()=>{"use strict";l();Ed();k();Re();xe();Do={name:Pd,displayName:Sd,description:Rd,parameters:$d,category:_d,execute:MT}});var Dd,Md,Od,Nd,Ad,Id=h(()=>{"use strict";l();Dd="github.pr.diff.get",Md="Get PR Diff",Od="Fetch the unified diff for a pull request (text/patch).",Nd="github",Ad={type:"object",properties:{repo:{type:"string",description:"owner/name"},number:{type:"integer",description:"PR number"},token:{type:"string",description:"GitHub token (App installation or PAT)"},maxBytes:{type:"integer",description:"Optional max bytes of diff to return; if exceeded, result is truncated with a footer."}},required:["repo","number"]}});import{Buffer as Ns}from"buffer";async function OT(r){let e=String(r.repo),t=Number(r.number),o=await G(e,r.token),n=r.maxBytes?Number(r.maxBytes):void 0,s=`https://api.github.com/repos/${e}/pulls/${t}`;y(`[github.pr.diff.get] repo=${e} pr=${t}`);let i=await fetch(s,{method:"GET",headers:z(o,{Accept:"application/vnd.github.v3.diff"})}),a=await i.text();if(n&&Ns.byteLength(a,"utf8")>n){let c=Ns.from(a,"utf8").subarray(0,n).toString("utf8"),p=`
101
+ \u2026 [truncated, ${n} of ${Ns.byteLength(a,"utf8")} bytes]`;return`HTTP ${i.status} ${i.statusText}
102
+ ${c}${p}`}return`HTTP ${i.status} ${i.statusText}
103
+ ${a}`}var Mo,As=h(()=>{"use strict";l();Id();Re();k();xe();Mo={name:Dd,displayName:Md,description:Od,parameters:Ad,category:Nd,execute:OT}});var Ld,jd,Fd,qd,Wd,Ud=h(()=>{"use strict";l();Ld="github.pr.files.list",jd="List PR Files",Fd="List files changed in a PR with positions metadata.",qd="github",Wd={type:"object",properties:{repo:{type:"string",description:"owner/name"},number:{type:"integer",description:"PR number"},token:{type:"string",description:"GitHub token (App installation or PAT)"},perPage:{type:"integer",description:"Results per page (max 100)"},page:{type:"integer",description:"Page number"}},required:["repo","number"]}});async function NT(r){let e=String(r.repo),t=Number(r.number),o=await G(e,r.token),n=r.perPage?Number(r.perPage):void 0,s=r.page?Number(r.page):void 0,i=new URLSearchParams;n&&i.set("per_page",String(n)),s&&i.set("page",String(s));let a=`https://api.github.com/repos/${e}/pulls/${t}/files${i.toString()?`?${i.toString()}`:""}`;y(`[github.pr.files.list] repo=${e} pr=${t} perPage=${n??""} page=${s??""}`);let c=await fetch(a,{method:"GET",headers:z(o)}),p=await c.text();return`HTTP ${c.status} ${c.statusText}
104
+ ${p}`}var Oo,Is=h(()=>{"use strict";l();Ud();Re();k();xe();Oo={name:Ld,displayName:jd,description:Fd,parameters:Wd,category:qd,execute:NT}});var Gd,Bd,zd,Hd,Kd,Jd=h(()=>{"use strict";l();Gd="github.pr.reviews.submit",Bd="Submit PR Review",zd="Submit a PR review (APPROVE, REQUEST_CHANGES, or COMMENT), optionally with inline comments.",Hd="github",Kd={type:"object",properties:{repo:{type:"string",description:"owner/name"},number:{type:"integer",description:"PR number"},event:{type:"string",description:"Review event",enum:["APPROVE","REQUEST_CHANGES","COMMENT"]},body:{type:"string",description:"Top-level review body"},comments:{type:"array",description:"Optional inline comments array",items:{type:"object",properties:{path:{type:"string",description:"File path"},position:{type:"integer",description:"Position in the diff"},body:{type:"string",description:"Comment body"}},required:["path","position","body"]}},token:{type:"string",description:"GitHub token (App installation or PAT)"}},required:["repo","number","event"]}});async function AT(r){let e=String(r.repo),t=Number(r.number),o=String(r.event),n=r.body?String(r.body):void 0,s=Array.isArray(r.comments)?r.comments:void 0,i=await G(e,r.token),a=`https://api.github.com/repos/${e}/pulls/${t}/reviews`;y(`[github.pr.reviews.submit] repo=${e} pr=${t} event=${o} comments=${s?.length??0}`);let c={event:o};n&&(c.body=n),s&&s.length>0&&(c.comments=s);let p=await fetch(a,{method:"POST",headers:z(i,{"Content-Type":"application/json"}),body:JSON.stringify(c)}),m=await p.text();return`HTTP ${p.status} ${p.statusText}
105
+ ${m}`}var No,Ls=h(()=>{"use strict";l();Jd();Re();k();xe();No={name:Gd,displayName:Bd,description:zd,parameters:Kd,category:Hd,execute:AT}});var Vd,Qd,Xd,Yd,Zd,eu=h(()=>{"use strict";l();Vd="github.issues.comments.create",Qd="Create Issue/PR Comment",Xd="Create a comment on an issue or pull request (conversation tab).",Yd="github",Zd={type:"object",properties:{repo:{type:"string",description:"owner/name"},number:{type:"integer",description:"Issue or PR number"},body:{type:"string",description:"Comment body"},token:{type:"string",description:"GitHub token (App installation or PAT)"}},required:["repo","number","body"]}});async function IT(r){let e=String(r.repo),t=Number(r.number),o=String(r.body),n=await G(e,r.token),s=`https://api.github.com/repos/${e}/issues/${t}/comments`;y(`[github.issues.comments.create] repo=${e} number=${t}`);let i=await fetch(s,{method:"POST",headers:z(n,{"Content-Type":"application/json"}),body:JSON.stringify({body:o})}),a=await i.text();return`HTTP ${i.status} ${i.statusText}
106
+ ${a}`}var Ao,js=h(()=>{"use strict";l();eu();Re();k();xe();Ao={name:Vd,displayName:Qd,description:Xd,parameters:Zd,category:Yd,execute:IT}});var ou={};le(ou,{githubContentsGetTextTool:()=>_o,githubGraphqlExecuteTool:()=>Ro,githubIssuesCommentsCreateTool:()=>Ao,githubPrDiffGetTool:()=>Mo,githubPrFilesListTool:()=>Oo,githubPrReviewCommentsReplyTool:()=>Do,githubPrReviewThreadsListTool:()=>$o,githubPrReviewThreadsResolveTool:()=>Eo,githubPrReviewsSubmitTool:()=>No,githubToolsProject:()=>tu});var tu,Fs=h(()=>{"use strict";l();$s();Es();Ds();Ms();Os();As();Is();Ls();js();$s();Es();Ds();Ms();Os();As();Is();Ls();js();tu={manifest:{key:"github",name:"github-tools",displayName:"GitHub",version:"1.0.0",description:"GitHub GraphQL/REST tools for PR threads, comments, and contents.",author:"Toolpack",tools:["github.graphql.execute","github.contents.getText","github.pr.reviewThreads.list","github.pr.reviewThreads.resolve","github.pr.reviewComments.reply","github.pr.diff.get","github.pr.files.list","github.pr.reviews.submit","github.issues.comments.create"],category:"network"},tools:[Ro,_o,$o,Eo,Do,Mo,Oo,No,Ao],dependencies:{}}});var nu,ru,su,iu,au,lu=h(()=>{"use strict";l();nu="web.fetch",ru="Fetch",su="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).",iu="network",au={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 qs from"cheerio";function cu(r,e){let t=qs.load(r);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",n=t('meta[name="author"]').attr("content")||t('meta[property="article:author"]').attr("content")||t(".author").first().text().trim()||void 0,s=t('meta[property="article:published_time"]').attr("content")||t("time").first().attr("datetime")||t(".date, .published").first().text().trim()||void 0,i=["article","main",'[role="main"]',".content",".article-content",".post-content","#content"],a="";for(let w of i){let b=t(w).first();if(b.length>0&&(a=b.text().trim(),a.length>200))break}(!a||a.length<200)&&(a=t("body").text().trim()),a=a.replace(/\s+/g," ").trim();let c=[];t("p").each((w,b)=>{let T=t(b).text().trim();T.length>50&&c.length<3&&c.push(T)});let p=c.join(`
35
107
 
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}
108
+ `)||a.substring(0,500),m=[];t("h2, h3").each((w,b)=>{let T=t(b).text().trim();T&&T.length>5&&T.length<200&&m.length<10&&m.push(T)});let f=a.split(/\s+/).length,g=a.split(/\s+/);return g.length>2e3&&(a=g.slice(0,2e3).join(" ")+"..."),{title:o,url:e,author:n,publishDate:s,excerpt:p.substring(0,1e3),mainContent:a.substring(0,1e4),keyPoints:m,wordCount:f}}function pu(r,e){let t=qs.load(r);t("script, style, nav, header, footer").remove();let o=t("title").text().trim()||t("h1").first().text().trim()||"Untitled",n=t('meta[name="description"]').attr("content")||t('meta[property="og:description"]').attr("content")||"";return n||t("p").each((s,i)=>{let a=t(i).text().trim();a.length>50&&!n&&(n=a)}),n||(n=t("body").text().trim().replace(/\s+/g," ")),{title:o,url:e,snippet:n.substring(0,500)}}function mu(r){let e=[];return e.push(`# ${r.title}`),e.push(`URL: ${r.url}`),r.author&&e.push(`Author: ${r.author}`),r.publishDate&&e.push(`Published: ${r.publishDate}`),e.push(`Word Count: ${r.wordCount}`),e.push(""),r.keyPoints.length>0&&(e.push("## Key Points"),r.keyPoints.forEach(t=>{e.push(`- ${t}`)}),e.push("")),e.push("## Excerpt"),e.push(r.excerpt),e.push(""),e.push("## Main Content"),e.push(r.mainContent),e.join(`
109
+ `)}function du(r){return`# ${r.title}
110
+ URL: ${r.url}
39
111
 
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)+`
112
+ ${r.snippet}`}var uu=h(()=>{"use strict";l()});async function LT(r){let e=r.url,t=r.extractionMode||"full",o=r.headers,n=r.timeout||3e4;if(y(`[web.fetch] execute url="${e}" mode=${t} timeout=${n}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(),n),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 ${n}ms`):p}finally{clearTimeout(i)}if(!a.ok)return`HTTP ${a.status} ${a.statusText}
113
+ ${await a.text()}`;let c=await a.text();if(t==="structured"){let p=cu(c,e);return mu(p)}else if(t==="minimal"){let p=pu(c,e);return du(p)}else return c.length>15e3?c.substring(0,15e3)+`
42
114
 
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(`
115
+ [TRUNCATED: showing 15K of ${c.length} total characters]`:c}var Io,Ws=h(()=>{"use strict";l();lu();uu();k();Io={name:nu,displayName:ru,description:su,parameters:au,category:iu,execute:LT}});var fu,gu,hu,yu,bu,wu=h(()=>{"use strict";l();fu="web.search",gu="Search",hu="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.",yu="network",bu={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 Fe from"fs";import*as Nn from"path";function An(r){let e=xu(r);if(!Fe.existsSync(e))return{};try{let t=Fe.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return{}}}function Lo(r){let e=An(r),t=FT(e.tools||e);return y(JSON.stringify(t??{})),t}function jT(r,e){let t=xu(e),o={};try{Fe.existsSync(t)&&(o=JSON.parse(Fe.readFileSync(t,"utf-8")))}catch{o={}}o.tools=r,Fe.writeFileSync(t,JSON.stringify(o,null,4),"utf-8")}function FT(r){let e=r.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:r.enabled??re.enabled,autoExecute:r.autoExecute??re.autoExecute,maxToolRounds:r.maxToolRounds??re.maxToolRounds,toolChoicePolicy:r.toolChoicePolicy??re.toolChoicePolicy,resultMaxChars:r.resultMaxChars??re.resultMaxChars,enabledTools:r.enabledTools??re.enabledTools,enabledToolCategories:r.enabledToolCategories??re.enabledToolCategories,toolSearch:r.toolSearch??re.toolSearch,additionalConfigurations:e}}function xu(r){return r?r.endsWith(".json")?Nn.resolve(r):Nn.resolve(r,Tu):Nn.resolve(process.cwd(),Tu)}var Tu,Us=h(()=>{"use strict";l();Lt();k();Tu="toolpack.config.json"});import*as Cu from"cheerio";function UT(r,e){y("[web.search] Parsing DuckDuckGo Lite response");let t=Cu.load(r),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 GT(r){if(r)switch(r){case"day":return 1;case"week":return 7;case"month":return 31;case"year":return 365;default:return}}function vu(r){if(!r)return"";switch(r){case"day":return"pd";case"week":return"pw";case"month":return"pm";case"year":return"py";default:return""}}async function BT(r){let e=r.query,t=r.max_results||5,o=r.include_answer||!1,n=r.freshness;y(`[web.search] execute query="${e}" max_results=${t} includeAnswer=${o} freshness=${n??"none"}`);let s=`Request timed out after ${r.timeout||3e4}ms`,i=()=>{let f=new AbortController,g=setTimeout(()=>f.abort(),r.timeout||3e4);return{signal:f.signal,clear:()=>clearTimeout(g)}};if(!e)throw new Error("query is required");let a=Lo();if(y(`[web.search] config=${JSON.stringify(a)}`),a.additionalConfigurations?.webSearch?.tavilyApiKey){y("[web.search] using Tavily API");try{let{signal:f,clear:g}=i(),w=GT(n),b={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:a.additionalConfigurations.webSearch.tavilyApiKey,query:e,max_results:t,include_answer:o,...w&&{days:w}}),signal:f};y(`[web.search] Tavily request=${JSON.stringify(b)}`);let T=await fetch("https://api.tavily.com/search",b).finally(g);if(T.ok){let v=await T.json();if(v.results&&v.results.length>0){let C=v.results.map(x=>({title:x.title,link:x.url,snippet:x.content}));return o&&v.answer?JSON.stringify({answer:v.answer,results:C},null,2):JSON.stringify(C,null,2)}}else pe(`[web.search] Tavily search failed with status ${T.status}`)}catch(f){pe(`[web.search] Tavily search failed, falling back: ${f}`)}}if(a.additionalConfigurations?.webSearch?.braveApiKey)try{let{signal:f,clear:g}=i();if(o){let w=vu(n),b=w?`&freshness=${w}`:"",T=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(e)}&count=${Math.min(t,20)}&summary=1${b}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":a.additionalConfigurations.webSearch.braveApiKey},signal:f}).finally(g);if(T.ok){let v=await T.json(),C=v.summarizer?.key;if(C&&v.web?.results){let{signal:x,clear:R}=i(),D=await fetch(`https://api.search.brave.com/res/v1/summarizer/search?key=${C}`,{headers:{Accept:"application/json","X-Subscription-Token":a.additionalConfigurations.webSearch.braveApiKey},signal:x}).finally(R);if(D.ok){let M=await D.json(),S=v.web.results.slice(0,t).map(_=>({title:_.title,link:_.url,snippet:_.description})),$=M.summary?.map(_=>_.data).join(`
116
+ `)||M.title;return JSON.stringify({answer:$,results:S},null,2)}}if(v.web?.results){let x=v.web.results.slice(0,t).map(R=>({title:R.title,link:R.url,snippet:R.description}));return JSON.stringify(x,null,2)}}}else{let w=vu(n),b=w?`&freshness=${w}`:"",T=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(e)}&count=${Math.min(t,20)}${b}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":a.additionalConfigurations.webSearch.braveApiKey},signal:f}).finally(g);if(T.ok){let v=await T.json();if(v.web?.results&&v.web.results.length>0){let C=v.web.results.slice(0,t).map(x=>({title:x.title,link:x.url,snippet:x.description}));return JSON.stringify(C,null,2)}}}}catch(f){I(`[web.search] Brave search failed, falling back: ${f}`)}let{signal:c,clear:p}=i(),m;try{m=await fetch(qT,{method:"POST",headers:{"User-Agent":WT,"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(),g=UT(f,t);if(g.length>0)return JSON.stringify(g,null,2)}return JSON.stringify({error:"search_unavailable",message:`Search failed to find results for "${e}" across all providers.`,suggestion:"Please configure a search provider API key (tavilyApiKey or braveApiKey) in toolpack.config.json under tools.additionalConfigurations.webSearch."})}var qT,WT,jo,Gs=h(()=>{"use strict";l();wu();Us();k();qT="https://lite.duckduckgo.com/lite/",WT="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";jo={name:fu,displayName:gu,description:hu,parameters:bu,category:yu,execute:BT}});var ku,Pu,Su,Ru,_u,$u=h(()=>{"use strict";l();ku="web.scrape",Pu="Scrape",Su="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.",Ru="network",_u={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 Mu from"cheerio";async function KT(r){let e=r.url,t=r.selector,o=r.section,n=r.format||"text",s=r.max_length||6e3,i=r.timeout||3e4;if(y(`[web.scrape] execute url="${e}" format=${n} 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":zT},signal:a.signal})}catch(b){throw b.name==="AbortError"?new Error(`Request timed out after ${i}ms`):b}finally{clearTimeout(c)}if(!p.ok)throw new Error(`Failed to fetch ${e}: HTTP ${p.status} ${p.statusText}`);let m=await p.text(),f=Mu.load(m);for(let b of HT)f(b).remove();if(n==="tables"){let b=[];return f("table").each((T,v)=>{let C=[],x=[];f(v).find("th").each((R,D)=>{x.push(f(D).text().trim())}),f(v).find("tr").each((R,D)=>{let M=x.length>0?{}:[],S=f(D).find("td");S.length>0&&(S.each(($,_)=>{let L=f(_).text().trim();x.length>0&&x[$]?M[x[$]]=L:M.push(L)}),C.push(M))}),C.length>0&&b.push({id:`Table ${T+1}`,headers:x.length>0?x:void 0,rows:C})}),b.length===0?`No tables found on ${e}`:JSON.stringify(b,null,2)}let g="";if(o){let b=o.toLowerCase(),T=null,v=0;if(f("h1, h2, h3, h4, h5, h6").each((C,x)=>{if(f(x).text().toLowerCase().includes(b))return T=x,v=parseInt(x.tagName.charAt(1)),!1}),T){let C=f(T),x=[],R=C.next();for(;R.length>0;){let D=R.prop("tagName")?.toLowerCase();if(D&&/^h[1-6]$/.test(D)&&parseInt(D.charAt(1))<=v)break;let M=R.text().trim();M&&x.push(M),R=R.next()}x.length>0?(g=x.join(`
45
117
 
46
- `).replace(/\s+/g," ").trim(),h=`[Section: "${o}"]
118
+ `).replace(/\s+/g," ").trim(),g=`[Section: "${o}"]
47
119
 
48
- ${h}`):h=`[Note: Found heading "${o}" but no content below it. Falling back to full page.]
120
+ ${g}`):g=`[Note: Found heading "${o}" but no content below it. Falling back to full page.]
49
121
 
50
- `}else h=`[Note: Section "${o}" not found. Falling back to full page.]
122
+ `}else g=`[Note: Section "${o}" not found. Falling back to full page.]
51
123
 
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.]
124
+ `}if(!g||g.includes("Falling back to full page"))if(g&&g.includes("Falling back to full page")&&(g=""),t){let b=f(t);if(b.length>0)g=b.text().replace(/\s+/g," ").trim();else{for(let T of Eu){let v=f(T);if(v.length>0){let C=v.text().replace(/\s+/g," ").trim();if(C.length>Du){g=C;break}}}if(g)g=`[Note: Selector "${t}" not found. Showing auto-detected main content instead.]
53
125
 
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).]
126
+ ${g}`;else return`No element found matching selector "${t}" and could not auto-detect main content from ${e}`}}else for(let b of Eu){let T=f(b);if(T.length>0){let v=T.text().replace(/\s+/g," ").trim();if(v.length>Du){g=v;break}}}if(g||(g=f("body").text().replace(/\s+/g," ").trim(),g&&(g=`[Note: Could not detect main content area. Showing full page text (may include navigation).]
55
127
 
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.]
128
+ ${g}`)),!g)return`Could not extract any content from ${e}`;if(g.length>s){let b=g.substring(0,s);return`[Warning: Content exceeds ${s} chars (actual: ${g.length} chars). Showing first ${s} chars only.]
57
129
 
58
130
  RECOMMENDATION: Use web.map to see page structure, then use web.scrape with section parameter to extract specific sections.
59
131
 
60
132
  Page content from ${e}:
61
133
 
62
- ${w}
134
+ ${b}
63
135
 
64
- ... [Content truncated. ${h.length-s} chars remaining. Use section parameter to extract specific sections.]`}return`Page content from ${e}:
136
+ ... [Content truncated. ${g.length-s} chars remaining. Use section parameter to extract specific sections.]`}return`Page content from ${e}:
65
137
 
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}:
138
+ ${g}`}var zT,HT,Eu,Du,Fo,Bs=h(()=>{"use strict";l();$u();k();zT="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",HT=["script","style","nav","footer","header","iframe",".ads",".sidebar","noscript"],Eu=["article","main",".content","#content",'[role="main"]',"body"],Du=200;Fo={name:ku,displayName:Pu,description:Su,parameters:_u,category:Ru,execute:KT}});var Ou,Nu,Au,Iu,Lu,ju=h(()=>{"use strict";l();Ou="web.extract_links",Nu="Extract Links",Au="Extract all links from a webpage. Returns an array of objects with text and URL. Optionally filter by pattern.",Iu="network",Lu={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 Fu from"cheerio";async function VT(r){let e=r.url,t=r.filter,o=r.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 n=new AbortController,s=setTimeout(()=>n.abort(),o),i;try{i=await fetch(e,{method:"GET",headers:{"User-Agent":JT},signal:n.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=Fu.load(a),p=new URL(e),m=[];return c("a[href]").each((f,g)=>{let w=c(g),b=w.attr("href");if(!b)return;let T;try{T=new URL(b,e).toString()}catch{return}if(T.startsWith("javascript:")||T.startsWith("mailto:")||T.startsWith("tel:"))return;let v=w.text().trim()||"[no text]";if(t){if(t==="same-domain")try{if(new URL(T).hostname!==p.hostname)return}catch{return}else if(!T.includes(t))return}m.push({text:v,url:T})}),m.length===0?`No links found on ${e}${t?` matching filter "${t}"`:""}`:JSON.stringify(m,null,2)}var JT,qo,zs=h(()=>{"use strict";l();ju();JT="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";qo={name:Ou,displayName:Nu,description:Au,parameters:Lu,category:Iu,execute:VT}});var qu,Wu,Uu,Gu,Bu,zu=h(()=>{"use strict";l();qu="web.map",Wu="Map",Uu="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.",Gu="network",Bu={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 Hu from"cheerio";async function XT(r){let e=r.url,t=r.timeout||3e4;if(!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=new AbortController,n=setTimeout(()=>o.abort(),t),s;try{s=await fetch(e,{method:"GET",headers:{"User-Agent":QT},signal:o.signal})}catch(m){throw m.name==="AbortError"?new Error(`Request timed out after ${t}ms`):m}finally{clearTimeout(n)}if(!s.ok)throw new Error(`Failed to fetch ${e}: HTTP ${s.status} ${s.statusText}`);let i=await s.text(),a=Hu.load(i),c=[];if(a("h1, h2, h3, h4, h5, h6").each((m,f)=>{let g=f.tagName.toLowerCase(),w=parseInt(g.charAt(1)),b=a(f).text().trim();b&&c.push({level:w,text:b})}),c.length===0)return`No headings found on ${e}. The page may not have a clear structure.`;let p=`Page outline for ${e}:
67
139
 
68
140
  `;for(let m of c){let f=" ".repeat(m.level-1);p+=`${f}${"#".repeat(m.level)} ${m.text}
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(`
141
+ `}return p}var QT,Wo,Hs=h(()=>{"use strict";l();zu();QT="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Wo={name:qu,displayName:Wu,description:Uu,parameters:Bu,category:Gu,execute:XT}});var Ku,Ju,Vu,Qu,Xu,Yu=h(()=>{"use strict";l();Ku="web.metadata",Ju="Extract Metadata",Vu="Extract Open Graph, Twitter Cards, JSON-LD, and meta tags from a URL.",Qu="network",Xu={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 Zu from"cheerio";async function ZT(r){let e=r.url,t=r.timeout||3e4;if(!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=new AbortController,n=setTimeout(()=>o.abort(),t),s;try{s=await fetch(e,{method:"GET",headers:{"User-Agent":YT},signal:o.signal})}catch(p){throw p.name==="AbortError"?new Error(`Request timed out after ${t}ms`):p}finally{clearTimeout(n)}if(!s.ok)throw new Error(`Failed to fetch ${e}: HTTP ${s.status} ${s.statusText}`);let i=await s.text(),a=Zu.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:",""),g=a(m).attr("content");f&&g&&(c.openGraph[f]=g)}),a('meta[name^="twitter:"]').each((p,m)=>{let f=a(m).attr("name")?.replace("twitter:",""),g=a(m).attr("content");f&&g&&(c.twitter[f]=g)}),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 YT,Uo,Ks=h(()=>{"use strict";l();Yu();YT="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Uo={name:Ku,displayName:Ju,description:Vu,parameters:Xu,category:Qu,execute:ZT}});var ef,tf,of,nf,rf,sf=h(()=>{"use strict";l();ef="web.sitemap",tf="Extract Sitemap",of="Parse sitemap.xml or robots.txt to discover all pages on a site. Returns an array of URLs with lastmod/priority if available.",nf="network",rf={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 af from"cheerio";async function Js(r,e){let t=new AbortController,o=setTimeout(()=>t.abort(),e);try{return await fetch(r,{method:"GET",headers:{"User-Agent":ex},signal:t.signal})}catch(n){throw n.name==="AbortError"?new Error(`Request timed out after ${e}ms`):n}finally{clearTimeout(o)}}async function tx(r){let e=r.url,t=r.max_urls||100,o=r.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 n=e,s=!1;!e.endsWith(".xml")&&!e.endsWith(".txt")&&(n=new URL(e.endsWith("/")?"sitemap.xml":"/sitemap.xml",e).toString(),s=!0);let i;try{i=await Js(n,o),!i.ok&&s&&(n=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await Js(n,o))}catch(p){if(s)n=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await Js(n,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(n.endsWith(".xml")||a.trim().startsWith("<")){let p=af.load(a,{xmlMode:!0}),m=p("sitemap > loc");if(m.length>0)return m.each((g,w)=>{c.length>=t||c.push({loc:p(w).text()})}),JSON.stringify({type:"sitemapindex",urls:c},null,2);p("urlset > url").each((g,w)=>{if(c.length>=t)return;let b=p(w);c.push({loc:b.children("loc").text(),lastmod:b.children("lastmod").text()||void 0,priority:b.children("priority").text()||void 0})})}else{let p=a.split(`
142
+ `);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 g=f.substring(6).trim();c.push({loc:new URL(g,n).toString()})}}}return JSON.stringify(c,null,2)}var ex,Go,Vs=h(()=>{"use strict";l();sf();ex="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Go={name:ef,displayName:tf,description:of,parameters:rf,category:nf,execute:tx}});var lf,cf,pf,mf,df,uf=h(()=>{"use strict";l();lf="web.feed",cf="Extract Feed",pf="Parse RSS/Atom feeds and return structured entries. Requires rss-parser library to be installed.",mf="network",df={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 ff(){try{let r=await import("rss-parser");return new(r.default||r)}catch{throw new Error("rss-parser is not installed. Please install it using `npm install rss-parser` to use this feature.")}}var gf=h(()=>{"use strict";l()});async function ox(r){let e=r.url,t=r.max_entries||10,o=r.timeout||3e4;if(!e)throw new Error("url is required");let n=await ff();n.options={...n.options,timeout:o};try{let s=await n.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 Bo,Qs=h(()=>{"use strict";l();uf();gf();Bo={name:lf,displayName:cf,description:pf,parameters:df,category:mf,execute:ox}});var hf,yf,bf,wf,Tf,xf=h(()=>{"use strict";l();hf="web.screenshot",yf="Screenshot",bf="Render a page with headless browser and return screenshot Base64 PNG or rendered HTML.",wf="network",Tf={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 vf(){try{let r=await import("puppeteer");return r.default||r}catch{throw new Error("Puppeteer is not installed. Please install it using `npm install puppeteer` to use this feature.")}}var Cf=h(()=>{"use strict";l()});async function rx(r){let e=r.url,t=r.format||"html",o=r.viewport,n=r.timeout||3e4;if(!e)throw new Error("url is required");let i=await(await vf()).launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]});try{let a=await i.newPage();if(await a.setUserAgent(nx),await a.setViewport({width:o?.width||1280,height:o?.height||800}),await a.goto(e,{waitUntil:"networkidle2",timeout:n}),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 nx,zo,Xs=h(()=>{"use strict";l();xf();Cf();nx="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";zo={name:hf,displayName:yf,description:bf,parameters:Tf,category:wf,execute:rx}});var Pf={};le(Pf,{webExtractLinksTool:()=>qo,webFeedTool:()=>Bo,webFetchTool:()=>Io,webMapTool:()=>Wo,webMetadataTool:()=>Uo,webScrapeTool:()=>Fo,webScreenshotTool:()=>zo,webSearchTool:()=>jo,webSitemapTool:()=>Go,webToolsProject:()=>kf});var kf,Ys=h(()=>{"use strict";l();Ws();Gs();Bs();zs();Hs();Ks();Vs();Qs();Xs();Ws();Gs();Bs();zs();Hs();Ks();Vs();Qs();Xs();kf={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:[Io,jo,Fo,qo,Wo,Uo,Go,Bo,zo],dependencies:{cheerio:"^1.0.0-rc.12"}}});var Sf,Rf,_f,$f,Ef,Df=h(()=>{"use strict";l();Sf="coding.find_symbol",Rf="Find Symbol",_f="Find function, class, or variable definitions in JavaScript/TypeScript files using AST parsing",$f="coding",Ef={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 sx}from"path";function In(r){let e=sx(r).toLowerCase();return ix[e]||"unknown"}var ix,Zs=h(()=>{"use strict";l();ix={".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 nt from"web-tree-sitter";import*as De from"fs";import*as qe from"path";import*as Of from"os";var Mf,ei,ax,Ln,Nf=h(()=>{"use strict";l();Mf=nt.default||nt.Parser||nt,ei=qe.join(Of.homedir(),".toolpack-sdk","grammars"),ax=qe.resolve(d,"../../grammars"),Ln=class{grammars=new Map;isInitialized=!1;async init(){this.isInitialized||(await Mf.init({locateFile(e,t){return qe.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(nt.Language||Mf.Language).load(o);return this.grammars.set(e,s),s}async resolveGrammarPath(e){let t=`tree-sitter-${e}.wasm`,o=qe.resolve(d,"../../../../../../node_modules/tree-sitter-wasms/out",t);if(De.existsSync(o))return o;let n=qe.join(ax,t);if(De.existsSync(n))return n;let s=qe.join(ei,t);return De.existsSync(s)||await this.downloadGrammar(e,s),s}async downloadGrammar(e,t){De.existsSync(ei)||De.mkdirSync(ei,{recursive:!0});let o=`https://unpkg.com/tree-sitter-wasms@latest/out/tree-sitter-${e}.wasm`,n=await fetch(o);if(!n.ok)throw new Error(`Failed to download grammar for ${e}: ${n.statusText}`);let s=await n.arrayBuffer(),i=Buffer.from(s);De.writeFileSync(t,i)}}});import*as Ho from"web-tree-sitter";import*as Af from"fs";import*as If from"crypto";var lx,jn,Lf=h(()=>{"use strict";l();Zs();Nf();lx=Ho.default||Ho.Parser||Ho,jn=class{treeCache=new Map;maxCacheSize=50;parser=null;grammarManager;constructor(){this.grammarManager=new Ln}hash(e){return If.createHash("md5").update(e).digest("hex")}async getTree(e,t){let o=t!==void 0?t:Af.readFileSync(e,"utf-8"),n=this.hash(o),s=this.treeCache.get(e),i=In(e);if(i==="unknown")throw new Error(`Unsupported file type for ${e}`);let a=await this.grammarManager.ensureGrammar(i);if(s&&s.contentHash===n)return s.lastAccessed=Date.now(),{tree:s.tree,language:s.language,grammar:a};this.parser||(await this.grammarManager.init(),this.parser=new lx),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:n,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,n]of this.treeCache.entries())n.lastAccessed<t&&(t=n.lastAccessed,e=o);if(e){let o=this.treeCache.get(e);o&&o.tree.delete(),this.treeCache.delete(e)}}}});import{parse as cx}from"@babel/parser";import*as ti from"@babel/traverse";var _e,Fn,jf=h(()=>{"use strict";l();_e=ti.default||ti,Fn=class{parseCode(e){return cx(e,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]})}async findSymbols(e,t,o){let n=[];try{let s=this.parseCode(e.content),i=e.filePath;_e(s,{FunctionDeclaration(a){a.node.id?.name===t&&(!o||o==="function")&&n.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")&&n.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")&&n.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")&&n.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")&&n.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"type",name:t})}})}catch{}return n}async getSymbols(e,t){let o=[];try{let n=this.parseCode(e.content);_e(n,{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(n){throw new Error(`Failed to parse file "${e.filePath}": ${n.message}`)}return o}async getImports(e){let t=[];try{let o=this.parseCode(e.content);_e(o,{ImportDeclaration(n){let s=n.node.source.value,i=[],a="side-effect";for(let c of n.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:n.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 n=[];try{let s=e.content,i=s.split(`
143
+ `),a=this.parseCode(s);_e(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,g=i[m-1]||"";n.push({file:e.filePath,line:m,column:f,context:g.trim(),isDeclaration:p})}}}})}catch{}return n}async getSymbolAtPosition(e,t,o){try{let n=this.parseCode(e.content),s=null;return _e(n,{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),n=e.filePath,s=null;return _e(o,{FunctionDeclaration(i){i.node.id?.name===t&&(s={file:n,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:n,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:n,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:n,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:n,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);_e(o,{ExportNamedDeclaration(n){if(n.node.declaration)if(n.node.declaration.type==="VariableDeclaration")for(let s of n.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 n.node.declaration.type==="FunctionDeclaration"&&n.node.declaration.id?t.push({name:n.node.declaration.id.name,kind:"function",line:n.node.declaration.loc?.start.line||0,column:n.node.declaration.loc?.start.column||0}):n.node.declaration.type==="ClassDeclaration"&&n.node.declaration.id&&t.push({name:n.node.declaration.id.name,kind:"class",line:n.node.declaration.loc?.start.line||0,column:n.node.declaration.loc?.start.column||0});else if(n.node.specifiers)for(let s of n.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(n){let s="default",i="default";n.node.declaration.type==="ClassDeclaration"&&n.node.declaration.id?(s=n.node.declaration.id.name,i="class"):n.node.declaration.type==="FunctionDeclaration"&&n.node.declaration.id?(s=n.node.declaration.id.name,i="function"):n.node.declaration.type==="Identifier"&&(s=n.node.declaration.name,i="variable"),t.push({name:s,kind:i,line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})}})}catch{}return t}async getOutline(e){let t=[];try{return(await this.getSymbols(e)).map(n=>({name:n.name,kind:n.kind,line:n.line,column:n.column,children:[]}))}catch{}return t}async extractFunction(e,t,o,n,s,i){let a=e.content.split(`
144
+ `),c=Math.max(0,t-1),p=Math.min(a.length,n),m=a.slice(c,p).join(`
73
145
  `),f=`
74
146
  function ${i}() {
75
147
  ${m}
76
148
  }
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=`
149
+ `,g=`${i}();`;return{newFunction:f,replacementCall:g}}async getCallHierarchy(e,t,o){try{let n=this.parseCode(e.content),s=e.filePath,i=null,a="",c=0,p=0;if(_e(n,{Function(b){let T=b.node.loc;T&&T.start.line<=t&&T.end&&T.end.line>=t&&(i=b,c=T.start.line,p=T.start.column,b.node.type==="FunctionDeclaration"&&b.node.id?a=b.node.id.name:b.parent.type==="VariableDeclarator"&&b.parent.id.type==="Identifier"?a=b.parent.id.name:b.parent.type==="ClassMethod"||b.parent.type==="ObjectMethod"?b.parent.key.type==="Identifier"&&(a=b.parent.key.name):a="<anonymous>")}}),!i||a==="<anonymous>")return null;let m=[],f=[];_e(n,{CallExpression(b){let T=b.node.loc;if(!T||T.start.line<c||T.end&&T.end.line>c+1e3)return;let v=!1,C=b;for(;C;){if(C.isFunction()&&C.node.type==="FunctionDeclaration"&&C.node.id?.name===a){v=!0;break}C=C.parentPath}if(!v)return;let x=b.node.callee,R="<unknown>";x.type==="Identifier"?R=x.name:x.type==="MemberExpression"&&x.property.type==="Identifier"&&(R=x.property.name),R!=="<unknown>"&&f.push({file:s,name:R,line:b.node.loc?.start.line||0,column:b.node.loc?.start.column||0})}}),_e(n,{CallExpression(b){let T=b.node.callee,v=!1;if((T.type==="Identifier"&&T.name===a||T.type==="MemberExpression"&&T.property.type==="Identifier"&&T.property.name===a)&&(v=!0),v){let C="<global>",x=b;for(;x;){if(x.isFunction()){x.node.type==="FunctionDeclaration"&&x.node.id?C=x.node.id.name:x.parent.type==="VariableDeclarator"&&x.parent.id.type==="Identifier"?C=x.parent.id.name:(x.parent.type==="ClassMethod"||x.parent.type==="ObjectMethod")&&x.parent.key.type==="Identifier"&&(C=x.parent.key.name);break}x=x.parentPath}m.push({file:s,name:C,line:b.node.loc?.start.line||0,column:b.node.loc?.start.column||0})}}});let g=[...new Map(m.map(b=>[`${b.name}:${b.line}`,b])).values()],w=[...new Map(f.map(b=>[`${b.name}:${b.line}`,b])).values()];return{file:s,name:a,line:c,column:p,callers:g,callees:w}}catch{return null}}}});function ve(r,e){oi[r]=e}var oi,rt=h(()=>{"use strict";l();oi={}});var px,Ff=h(()=>{"use strict";l();rt();px={symbols:`
150
+ (function_definition
151
+ name: (identifier) @name.function) @definition.function
152
+
153
+ (class_definition
154
+ name: (identifier) @name.class) @definition.class
155
+
156
+ (assignment
157
+ left: (identifier) @name.variable) @definition.variable
158
+ `,imports:`
159
+ (import_statement
160
+ name: (dotted_name) @name) @import
161
+
162
+ (import_from_statement
163
+ module_name: (dotted_name)? @source
164
+ name: (dotted_name) @name) @import
165
+ `,references:`
166
+ (identifier) @reference
167
+ `};ve("python",px)});var mx,qf=h(()=>{"use strict";l();rt();mx={symbols:`
168
+ (function_declaration
169
+ name: (identifier) @name.function) @definition.function
170
+
171
+ (method_declaration
172
+ name: (field_identifier) @name.method) @definition.method
173
+
174
+ (type_spec
175
+ name: (type_identifier) @name.type) @definition.type
176
+
177
+ (var_declaration
178
+ (var_spec
179
+ name: (identifier) @name.variable)) @definition.variable
180
+ `,imports:`
181
+ (import_declaration
182
+ (import_spec
183
+ name: (package_identifier)? @name
184
+ path: (interpreted_string_literal) @source)) @import
185
+
186
+ (import_declaration
187
+ (import_spec_list
188
+ (import_spec
189
+ name: (package_identifier)? @name
190
+ path: (interpreted_string_literal) @source))) @import
191
+ `,references:`
192
+ (identifier) @reference
193
+ (field_identifier) @reference
194
+ (type_identifier) @reference
195
+ `};ve("go",mx)});var dx,Wf=h(()=>{"use strict";l();rt();dx={symbols:`
196
+ (function_item
197
+ name: (identifier) @name.function) @definition.function
198
+
199
+ (struct_item
200
+ name: (type_identifier) @name.class) @definition.class
201
+
202
+ (enum_item
203
+ name: (type_identifier) @name.class) @definition.class
204
+
205
+ (trait_item
206
+ name: (type_identifier) @name.interface) @definition.interface
207
+
208
+ (let_declaration
209
+ pattern: (identifier) @name.variable) @definition.variable
210
+ `,imports:`
211
+ (use_declaration
212
+ argument: (_) @source) @import
213
+ `,references:`
214
+ (identifier) @reference
215
+ (type_identifier) @reference
216
+ (field_identifier) @reference
217
+ `};ve("rust",dx)});var ux,Uf=h(()=>{"use strict";l();rt();ux={symbols:`
218
+ (method_declaration
219
+ name: (identifier) @name.method) @definition.method
220
+
221
+ (class_declaration
222
+ name: (identifier) @name.class) @definition.class
223
+
224
+ (interface_declaration
225
+ name: (identifier) @name.interface) @definition.interface
226
+
227
+ (enum_declaration
228
+ name: (identifier) @name.class) @definition.class
229
+
230
+ (variable_declarator
231
+ name: (identifier) @name.variable) @definition.variable
232
+ `,imports:`
233
+ (import_declaration
234
+ (_) @source) @import
235
+ `,references:`
236
+ (identifier) @reference
237
+ (type_identifier) @reference
238
+ `};ve("java",ux)});var Gf,Bf=h(()=>{"use strict";l();rt();Gf={symbols:`
239
+ (function_definition
240
+ declarator: (function_declarator
241
+ declarator: (identifier) @name.function)) @definition.function
242
+
243
+ (class_specifier
244
+ name: (type_identifier) @name.class) @definition.class
245
+
246
+ (struct_specifier
247
+ name: (type_identifier) @name.class) @definition.class
248
+
249
+ (declaration
250
+ declarator: (init_declarator
251
+ declarator: (identifier) @name.variable)) @definition.variable
252
+ `,imports:`
253
+ (preproc_include
254
+ path: (_) @source) @import
255
+ `,references:`
256
+ (identifier) @reference
257
+ (type_identifier) @reference
258
+ (field_identifier) @reference
259
+ `};ve("cpp",Gf);ve("c",Gf)});var qn,zf=h(()=>{"use strict";l();rt();Ff();qf();Wf();Uf();Bf();qn=class{constructor(e){this.context=e}context;async executeQuery(e,t){let{tree:o,language:n,grammar:s}=await this.context.getTree(e.filePath,e.content),i=oi[n];if(!i||!i[t])throw new Error(`Query ${t} not found for language ${n}`);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"),n=[];for(let s of o)if(s.name.startsWith("name.")){let i=s.name.split(".")[1];(!t||t===i)&&n.push({name:s.node.text,kind:i,line:s.node.startPosition.row+1,column:s.node.startPosition.column})}return n}async getImports(e){let{captures:t}=await this.executeQuery(e,"imports"),o=t.filter(s=>s.name==="import").map(s=>s.node),n=[];for(let s of o)n.push({source:s.text,imports:[s.text],line:s.startPosition.row+1,type:"side-effect"});return n}async findReferences(e,t,o){let{captures:n}=await this.executeQuery(e,"references"),s=e.content.split(`
260
+ `),i=[];for(let a of n)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:n}=await this.context.getTree(e.filePath,e.content),s=n.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 n(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)n(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 n(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,n,s,i){let a=e.content.split(`
261
+ `),c=Math.max(0,t-1),p=Math.min(a.length,n),m=a.slice(c,p).join(`
262
+ `),f="",g="",w=e.filePath.split(".").pop()?.toLowerCase();return w==="py"||w==="pyi"?(f=`
81
263
  def ${i}():
82
264
  ${m.split(`
83
- `).map(w=>" "+w).join(`
265
+ `).map(b=>" "+b).join(`
84
266
  `)}
85
- `,h=`${i}()`):b==="go"?(f=`
267
+ `,g=`${i}()`):w==="go"?(f=`
86
268
  func ${i}() {
87
269
  ${m}
88
270
  }
89
- `,h=`${i}()`):b==="rs"?(f=`
271
+ `,g=`${i}()`):w==="rs"?(f=`
90
272
  fn ${i}() {
91
273
  ${m}
92
274
  }
93
- `,h=`${i}();`):b==="sh"||b==="bash"?(f=`
275
+ `,g=`${i}();`):w==="sh"||w==="bash"?(f=`
94
276
  ${i}() {
95
277
  ${m}
96
278
  }
97
- `,h=`${i}`):(f=`
279
+ `,g=`${i}`):(f=`
98
280
  void ${i}() {
99
281
  ${m}
100
282
  }
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}
283
+ `,g=`${i}();`),{newFunction:f,replacementCall:g}}async getCallHierarchy(e,t,o){let n=await this.getSymbolAtPosition(e,t,o);if(!n)return null;let i=(await this.findReferences(e,n,!1)).map(a=>({file:a.file,name:a.context.trim()||"<anonymous>",line:a.line,column:a.column}));return{file:e.filePath,name:n,line:t,column:o,callers:i,callees:[]}}}});var Wn,Hf=h(()=>{"use strict";l();Zs();jf();zf();Wn=class{constructor(e){this.context=e;this.babelParser=new Fn,this.treeSitterParser=new qn(this.context)}context;babelParser;treeSitterParser;getParser(e){switch(In(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 fx,statSync as gx,readdirSync as hx}from"fs";import{join as yx,extname as bx}from"path";var Un,Kf=h(()=>{"use strict";l();de();Un=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=hx(e,{withFileTypes:!0});for(let n of o){let s=yx(e,n.name);n.name==="node_modules"||n.name===".git"||n.name==="dist"||n.name==="build"||(n.isDirectory()?t.push(...await this.getAllSupportedFiles(s)):n.isFile()&&this.supportedExtensions.includes(bx(n.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=gx(e).mtimeMs;if(this.fileMtimes.get(e)===o)return;let n=fx(e,"utf-8"),s=q.getParser(e);this.removeFileFromIndex(e);let i=await s.getSymbols({filePath:e,content:n});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 wx,q,Pt,de=h(()=>{"use strict";l();Lf();Hf();Kf();wx=new jn,q=new Wn(wx),Pt=new Un});import{readFileSync as Tx,statSync as xx,readdirSync as vx}from"fs";import{join as Cx,extname as kx}from"path";async function Jf(r,e,t){try{let o=Tx(r,"utf-8");return await q.getParser(r).findSymbols({filePath:r,content:o},e,t)}catch{return[]}}async function Vf(r,e,t){let o=[];try{let n=vx(r,{withFileTypes:!0});for(let s of n){let i=Cx(r,s.name);if(!(s.name==="node_modules"||s.name===".git"||s.name==="dist")){if(s.isDirectory()){let a=await Vf(i,e,t);o.push(...a)}else if(s.isFile()&&Px.includes(kx(s.name))){let a=await Jf(i,e,t);o.push(...a)}}}}catch{}return o}async function Sx(r){let e=r.symbol,t=r.path,o=r.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 n=xx(t),s;if(n.isDirectory())s=await Vf(t,e,o);else if(n.isFile())s=await Jf(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 Px,Ko,ni=h(()=>{"use strict";l();Df();de();k();Px=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];Ko={name:Sf,displayName:Rf,description:_f,parameters:Ef,category:$f,execute:Sx}});var Qf,Xf,Yf,Zf,eg,tg=h(()=>{"use strict";l();Qf="coding.get_symbols",Xf="Get Symbols",Yf="List all symbols (functions, classes, variables, etc.) in a JavaScript/TypeScript file",Zf="coding",eg={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 Rx}from"fs";async function _x(r){let e=r.file,t=r.kind;if(y(`[coding.get-symbols] execute file="${e}" kind=${t??"all"}`),!e)throw new Error("file is required");try{let o=Rx(e,"utf-8"),s=await q.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 Jo,ri=h(()=>{"use strict";l();tg();de();k();Jo={name:Qf,displayName:Xf,description:Yf,parameters:eg,category:Zf,execute:_x}});var og,ng,rg,sg,ig,ag=h(()=>{"use strict";l();og="coding.get_imports",ng="Get Imports",rg="List all import statements in a JavaScript/TypeScript file",sg="coding",ig={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"}},required:["file"]}});import{readFileSync as $x}from"fs";async function Ex(r){let e=r.file;if(y(`[coding.get-imports] execute file="${e}"`),!e)throw new Error("file is required");try{let t=$x(e,"utf-8"),n=await q.getParser(e).getImports({filePath:e,content:t});return JSON.stringify({file:e,count:n.length,imports:n},null,2)}catch(t){throw new Error(`Failed to map explicit imports in file "${e}": ${t.message}`)}}var Vo,si=h(()=>{"use strict";l();ag();de();k();Vo={name:og,displayName:ng,description:rg,parameters:ig,category:sg,execute:Ex}});var lg,cg,pg,mg,dg,ug=h(()=>{"use strict";l();lg="coding.find_references",cg="Find References",pg="Find all references to a symbol across JavaScript/TypeScript files",mg="coding",dg={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 Dx,statSync as Mx}from"fs";async function fg(r,e,t){try{let o=Dx(r,"utf-8");return await q.getParser(r).findReferences({filePath:r,content:o},e,t)}catch{return[]}}async function Ox(r,e,t){let o=[];await Pt.buildIndex(r);let n=await Pt.getDefinitionFiles(e,r);for(let s of n)if(s.startsWith(r)){let i=await fg(s,e,t);o.push(...i)}return o}async function Nx(r){let e=r.symbol,t=r.path,o=r.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 n=Mx(t),s;if(n.isDirectory())s=await Ox(t,e,o);else if(n.isFile())s=await fg(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 Qo,ii=h(()=>{"use strict";l();ug();de();k();Qo={name:lg,displayName:cg,description:pg,parameters:dg,category:mg,execute:Nx}});var gg,hg,yg,bg,wg,Tg=h(()=>{"use strict";l();gg="coding.go_to_definition",hg="Go To Definition",yg="Jump to the definition of a symbol at a specific location in a file",bg="coding",wg={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 xg,statSync as Ax}from"fs";import{dirname as Ix}from"path";async function Lx(r,e,t){try{let o=xg(r,"utf-8");return await q.getParser(r).getSymbolAtPosition({filePath:r,content:o},e,t)}catch{return null}}async function vg(r,e){try{let t=xg(r,"utf-8");return await q.getParser(r).getDefinition({filePath:r,content:t},e)}catch{return null}}async function jx(r,e){await Pt.buildIndex(r);let t=await Pt.getDefinitionFiles(e,r);for(let o of t)if(o.startsWith(r)){let n=await vg(o,e);if(n)return n}return null}async function Fx(r){let e=r.file,t=r.line,o=r.column,n=r.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 Lx(e,t,o);if(!s)return JSON.stringify({found:!1,message:`No symbol found at ${e}:${t}:${o}`},null,2);let i=await vg(e,s);if(!i){let a=n||Ix(e);Ax(a).isDirectory()&&(i=await jx(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 Xo,ai=h(()=>{"use strict";l();Tg();de();Xo={name:gg,displayName:hg,description:yg,parameters:wg,category:bg,execute:Fx}});var Cg,kg,Pg,Sg,Rg,_g=h(()=>{"use strict";l();Cg="coding.multi_file_edit",kg="Multi-File Edit",Pg="Edit multiple files atomically with rollback on failure",Sg="coding",Rg={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 qx,writeFileSync as $g,existsSync as Wx}from"fs";async function Ux(r){let e=r.edits,t=r.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(!Wx(s.file))throw new Error(`File does not exist: ${s.file}`)}let o=[],n=[];try{for(let s of e){let i=qx(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(Gx(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)}$g(s.file,a,"utf-8"),n.push(s.file)}return JSON.stringify({success:!0,filesModified:n.length,files:n},null,2)}catch(s){if(t&&o.length>0){for(let i of o)try{$g(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 Gx(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Yo,li=h(()=>{"use strict";l();_g();Yo={name:Cg,displayName:kg,description:Pg,parameters:Rg,category:Sg,execute:Ux,confirmation:{level:"high",reason:"This will modify multiple source code files atomically.",showArgs:["edits"]}}});var Eg,Dg,Mg,Og,Ng,Ag=h(()=>{"use strict";l();Eg="coding.refactor_rename",Dg="Refactor Rename",Mg="Rename a symbol across the entire codebase intelligently",Og="coding",Ng={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 Bx,writeFileSync as zx,readdirSync as Hx}from"fs";import{join as Kx,extname as Jx}from"path";import{parse as Vx}from"@babel/parser";import*as ci from"@babel/traverse";function Yx(r,e,t,o){let n=[];try{let s=Bx(r,"utf-8"),i=s.split(`
284
+ `),a=Vx(s,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]}),c=[];if(Qx(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}),n.push({file:r,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 g=p[f],w=g.substring(0,m.column),b=g.substring(m.column+m.length);p[f]=w+t+b}}zx(r,p.join(`
285
+ `),"utf-8")}}catch{}return{file:r,occurrences:n.length,changes:n}}function Ig(r,e,t,o){let n=[];try{let s=Hx(r,{withFileTypes:!0});for(let i of s){let a=Kx(r,i.name);if(!(i.name==="node_modules"||i.name===".git"||i.name==="dist")){if(i.isDirectory())n.push(...Ig(a,e,t,o));else if(i.isFile()&&Xx.includes(Jx(i.name))){let c=Yx(a,e,t,o);c.occurrences>0&&n.push(c)}}}}catch{}return n}async function Zx(r){let e=r.symbol,t=r.newName,o=r.path,n=r.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=Ig(o,e,t,n),i=s.reduce((c,p)=>c+p.occurrences,0),a=s.length;return JSON.stringify({success:!0,dryRun:n,oldName:e,newName:t,filesAffected:a,totalOccurrences:i,changes:s},null,2)}var Qx,Xx,Zo,pi=h(()=>{"use strict";l();Ag();Qx=ci.default||ci,Xx=[".js",".jsx",".ts",".tsx",".mjs",".cjs"];Zo={name:Eg,displayName:Dg,description:Mg,parameters:Ng,category:Og,execute:Zx,confirmation:{level:"high",reason:"This will rename a symbol across multiple files, rewriting source code without backup.",showArgs:["symbol","newName"]}}});var Lg,jg,Fg,qg,Wg,Ug=h(()=>{"use strict";l();Lg="coding.get_outline",jg="Get File Outline",Fg="Gets a hierarchical outline of symbols (classes, functions, methods) in a specified file.",qg="coding",Wg={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to outline"}},required:["file"]}});import{readFileSync as ev,statSync as tv}from"fs";async function ov(r){let e=r.file;if(y(`[coding.get-outline] execute file="${e}"`),!e)throw new Error("file is required");try{if(!tv(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=ev(e,"utf-8"),o=q.getParser(e);if(!o.getOutline)return JSON.stringify({file:e,error:"Outline extraction is not specifically implemented for this language yet."});let n=await o.getOutline({filePath:e,content:t});return JSON.stringify({file:e,outline:n},null,2)}catch(t){throw new Error(`Failed to safely extract outline from file "${e}": ${t.message}`)}}var en,mi=h(()=>{"use strict";l();Ug();de();k();en={name:Lg,displayName:jg,description:Fg,parameters:Wg,category:qg,execute:ov}});var Gg,Bg,zg,Hg,Kg,Jg=h(()=>{"use strict";l();Gg="coding.get_diagnostics",Bg="Get File Diagnostics",zg="Gets syntax errors and warnings for a file utilizing AST parsing.",Hg="coding",Kg={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to check for diagnostics"}},required:["file"]}});import{readFileSync as nv,statSync as rv}from"fs";async function sv(r){let e=r.file;if(!e)throw new Error("file is required");try{if(!rv(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=nv(e,"utf-8"),o=q.getParser(e);if(!o.getDiagnostics)return JSON.stringify({file:e,error:"Diagnostics extraction is not specifically implemented for this language yet."});let n=await o.getDiagnostics({filePath:e,content:t});return JSON.stringify({file:e,diagnostics:n},null,2)}catch(t){throw new Error(`Failed to get diagnostics from file "${e}": ${t.message}`)}}var tn,di=h(()=>{"use strict";l();Jg();de();tn={name:Gg,displayName:Bg,description:zg,parameters:Kg,category:Hg,execute:sv}});var Vg,Qg,Xg,Yg,Zg,eh=h(()=>{"use strict";l();Vg="coding.get_exports",Qg="Get File Exports",Xg="Lists all symbols exported by a file.",Yg="coding",Zg={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"}},required:["file"]}});import{readFileSync as iv,statSync as av}from"fs";async function lv(r){let e=r.file;if(y(`[coding.get-exports] execute file="${e}"`),!e)throw new Error("file is required");try{if(!av(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=iv(e,"utf-8"),o=q.getParser(e);if(!o.getExports)return JSON.stringify({file:e,error:"Exports extraction is not specifically implemented for this language yet."});let n=await o.getExports({filePath:e,content:t});return JSON.stringify({file:e,exports:n},null,2)}catch(t){throw new Error(`Failed to extract exports from file "${e}": ${t.message}`)}}var on,ui=h(()=>{"use strict";l();eh();de();k();on={name:Vg,displayName:Qg,description:Xg,parameters:Zg,category:Yg,execute:lv}});var th,oh,nh,rh,sh,ih=h(()=>{"use strict";l();th="coding.extract_function",oh="Extract Function",nh="Extracts a selected code region into a new function, automatically detecting required parameters and return values.",rh="coding",sh={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 cv,statSync as pv}from"fs";async function mv(r){let e=r.file,t=r.startLine,o=r.startColumn,n=r.endLine,s=r.endColumn,i=r.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(n===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(!pv(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let a=cv(e,"utf-8"),c=q.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,n,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 nn,fi=h(()=>{"use strict";l();ih();de();nn={name:th,displayName:oh,description:nh,parameters:sh,category:rh,execute:mv}});var ah,lh,ch,ph,mh,dh=h(()=>{"use strict";l();ah="coding.get_call_hierarchy",lh="Get Call Hierarchy",ch="Shows callers and callees of a specific function or method.",ph="coding",mh={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 dv,statSync as uv}from"fs";async function fv(r){let e=r.file,t=r.line,o=r.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(!uv(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let n=dv(e,"utf-8"),s=q.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:n},t,o);return JSON.stringify({file:e,hierarchy:i},null,2)}catch(n){throw new Error(`Failed to get call hierarchy from file "${e}": ${n.message}`)}}var rn,gi=h(()=>{"use strict";l();dh();de();rn={name:ah,displayName:lh,description:ch,parameters:mh,category:ph,execute:fv}});var fh={};le(fh,{codingExtractFunctionTool:()=>nn,codingFindReferencesTool:()=>Qo,codingFindSymbolTool:()=>Ko,codingGetCallHierarchyTool:()=>rn,codingGetDiagnosticsTool:()=>tn,codingGetExportsTool:()=>on,codingGetImportsTool:()=>Vo,codingGetOutlineTool:()=>en,codingGetSymbolsTool:()=>Jo,codingGoToDefinitionTool:()=>Xo,codingMultiFileEditTool:()=>Yo,codingRefactorRenameTool:()=>Zo,codingToolsProject:()=>uh});var uh,hi=h(()=>{"use strict";l();ni();ri();si();ii();ai();li();pi();mi();di();ui();fi();gi();ni();ri();si();ii();ai();li();pi();mi();di();ui();fi();gi();uh={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:[Ko,Jo,Vo,Qo,Xo,en,tn,on,nn,rn,Yo,Zo],dependencies:{"@babel/parser":"^7.24.0","@babel/traverse":"^7.24.0","@babel/types":"^7.24.0"}}});var gh,hh=h(()=>{"use strict";l();gh={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 gv}from"simple-git";function U(r){let e={baseDir:r||process.cwd(),binary:"git",maxConcurrentProcesses:6};return gv(e)}var Ce=h(()=>{"use strict";l()});var Gn,yh=h(()=>{"use strict";l();hh();Ce();Gn={name:"git.status",displayName:"Git Status",description:"Get the working tree status, including modified, staged, and untracked files.",category:"version-control",parameters:gh,execute:async r=>{let e=r.path;try{let o=await U().status(e?[e]:[]);if(o.isClean())return"Working tree clean";let n=[];return n.push(`Branch: ${o.current}`),o.tracking&&n.push(`Tracking: ${o.tracking}`),o.ahead>0&&n.push(`Ahead: ${o.ahead}`),o.behind>0&&n.push(`Behind: ${o.behind}`),n.push("---"),o.conflicted.length>0&&n.push(`Conflicted: ${o.conflicted.join(", ")}`),o.created.length>0&&n.push(`Created: ${o.created.join(", ")}`),o.deleted.length>0&&n.push(`Deleted: ${o.deleted.join(", ")}`),o.modified.length>0&&n.push(`Modified: ${o.modified.join(", ")}`),o.renamed.length>0&&n.push(`Renamed: ${o.renamed.map(s=>`${s.from} -> ${s.to}`).join(", ")}`),o.staged.length>0&&n.push(`Staged: ${o.staged.join(", ")}`),o.not_added.length>0&&n.push(`Untracked: ${o.not_added.join(", ")}`),n.join(`
286
+ `)}catch(t){return`Error getting git status: ${t instanceof Error?t.message:String(t)}`}}}});var bh,wh=h(()=>{"use strict";l();bh={type:"object",properties:{path:{type:"string",description:"Optional path to get the diff for. If omitted, gets the diff for the entire repository."},base:{type:"string",description:"Optional base commit/ref for comparing two revisions. When used with head, runs git diff base...head."},head:{type:"string",description:"Optional head commit/ref for comparing two revisions. When used with base, runs git diff base...head."},staged:{type:"boolean",description:"If true, gets the diff of staged changes instead of unstaged changes.",default:!1},cloneDir:{type:"string",description:"Optional local repository directory, typically the cloneDir returned by git.clone. When provided, this tool runs in that repository instead of the current working directory."}}}});var Bn,Th=h(()=>{"use strict";l();wh();Ce();Bn={name:"git.diff",displayName:"Git Diff",description:"Show changes between commits, commit and working tree, etc.",category:"version-control",parameters:bh,execute:async r=>{let e=r.path,t=r.base,o=r.head,n=r.staged,s=r.cloneDir;try{let i=U(s),a=[];if(t||o){if(!t||!o)return"Error getting git diff: both base and head are required when comparing revisions.";a.push(`${t}...${o}`)}n&&a.push("--cached"),e&&a.push("--",e);let c=await i.diff(a);return c||"No changes found."}catch(i){return`Error getting git diff: ${i instanceof Error?i.message:String(i)}`}}}});var xh,vh=h(()=>{"use strict";l();xh={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."},cloneDir:{type:"string",description:"Optional local repository directory, typically the cloneDir returned by git.clone. When provided, this tool runs in that repository instead of the current working directory."}}}});var zn,Ch=h(()=>{"use strict";l();vh();Ce();zn={name:"git.log",displayName:"Git Log",description:"Show commit logs.",category:"version-control",parameters:xh,execute:async r=>{let e=r.maxCount||10,t=r.path,o=r.cloneDir;try{let n=U(o),s={maxCount:e};t&&(s.file=t);let i=await n.log(s);return i.all.length===0?"No commits found.":i.all.map(a=>`Commit: ${a.hash}
287
+ Author: ${a.author_name} <${a.author_email}>
288
+ Date: ${a.date}
289
+ Message: ${a.message}
108
290
  `).join(`---
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.
291
+ `)}catch(n){return`Error getting git log: ${n instanceof Error?n.message:String(n)}`}}}});var kh,Ph=h(()=>{"use strict";l();kh={type:"object",properties:{path:{type:"string",description:"Path to the file or directory to stage. To stage all changes, use '.'."}},required:["path"]}});var Hn,Sh=h(()=>{"use strict";l();Ph();Ce();Hn={name:"git.add",displayName:"Git Add",description:"Add file contents to the index (stage changes).",category:"version-control",parameters:kh,execute:async r=>{let e=r.path;try{return await U().add(e),`Successfully staged changes for: ${e}`}catch(t){return`Error staging changes: ${t instanceof Error?t.message:String(t)}`}}}});var Rh,_h=h(()=>{"use strict";l();Rh={type:"object",properties:{message:{type:"string",description:"The commit message."}},required:["message"]}});var Kn,$h=h(()=>{"use strict";l();_h();Ce();Kn={name:"git.commit",displayName:"Git Commit",description:"Record changes to the repository.",category:"version-control",parameters:Rh,execute:async r=>{let e=r.message;try{let o=await U().commit(e);return o.commit?`Successfully committed changes.
110
292
  Commit: ${o.commit}
111
293
  Branch: ${o.branch}
112
- Summary: ${o.summary.changes} changes, ${o.summary.insertions} insertions, ${o.summary.deletions} deletions.`:"Nothing to commit."}catch(t){return`Error committing changes: ${t instanceof Error?t.message:String(t)}`}},confirmation:{level:"medium",reason:"This will create a permanent commit in the repository history.",showArgs:["message"]}}});var 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}
294
+ 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 Eh,Dh=h(()=>{"use strict";l();Eh={type:"object",properties:{path:{type:"string",description:"Path to the file to blame."},sha:{type:"string",description:"Optional commit SHA or ref to blame at. If omitted, blames the current checkout."},cloneDir:{type:"string",description:"Optional local repository directory, typically the cloneDir returned by git.clone. When provided, this tool runs in that repository instead of the current working directory."}},required:["path"]}});var Jn,Mh=h(()=>{"use strict";l();Dh();Ce();Jn={name:"git.blame",displayName:"Git Blame",description:"Show what revision and author last modified each line of a file.",category:"version-control",parameters:Eh,execute:async r=>{let e=r.path,t=r.sha,o=r.cloneDir;try{let n=U(o),s=["blame"];return t&&s.push(t),s.push("--",e),await n.raw(s)}catch(n){return`Error running git blame: ${n instanceof Error?n.message:String(n)}`}}}});var Oh,Nh=h(()=>{"use strict";l();Oh={type:"object",properties:{remote:{type:"boolean",description:"List remote branches as well.",default:!1}}}});var Vn,Ah=h(()=>{"use strict";l();Nh();Ce();Vn={name:"git.branch_list",displayName:"Git Branch List",description:"List all branches.",category:"version-control",parameters:Oh,execute:async r=>{let e=r.remote;try{let t=U(),o=e?["-a"]:[],n=await t.branch(o);return`Current Branch: ${n.current}
113
295
 
114
296
  Branches:
115
- ${r.all.join(`
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:
297
+ ${n.all.join(`
298
+ `)}`}catch(t){return`Error listing branches: ${t instanceof Error?t.message:String(t)}`}}}});var Ih,Lh=h(()=>{"use strict";l();Ih={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 Qn,jh=h(()=>{"use strict";l();Lh();Ce();Qn={name:"git.branch_create",displayName:"Git Branch Create",description:"Create a new branch.",category:"version-control",parameters:Ih,execute:async r=>{let e=r.name,t=r.checkout,o=r.startPoint;try{let n=U();return t?(o?await n.checkoutBranch(e,o):await n.checkoutLocalBranch(e),`Successfully created and switched to branch: ${e}`):(o?await n.branch([e,o]):await n.branch([e]),`Successfully created branch: ${e}`)}catch(n){return`Error creating branch: ${n instanceof Error?n.message:String(n)}`}}}});var Fh,qh=h(()=>{"use strict";l();Fh={type:"object",properties:{branch:{type:"string",description:"Name of the branch or commit to checkout."}},required:["branch"]}});var Xn,Wh=h(()=>{"use strict";l();qh();Ce();Xn={name:"git.checkout",displayName:"Git Checkout",description:"Switch branches or restore working tree files.",category:"version-control",parameters:Fh,execute:async r=>{let e=r.branch;try{return await U().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 Uh,Gh=h(()=>{"use strict";l();Uh={type:"object",properties:{repo:{type:"string",description:'The repository to clone in "owner/repo" format (e.g., "microsoft/typescript").'},sha:{type:"string",description:"The commit SHA to checkout (always use SHAs, never branch names \u2014 handles force-pushes correctly)."},filter:{type:"string",description:'Git partial clone filter. "blob:none" (default) skips file blobs for a fast clone \u2014 blobs are fetched on demand when you read files or run git blame. Use "none" when you need immediate access to all file contents without extra fetches (e.g. heavy blame across many files).',default:"blob:none"},depth:{type:"number",description:"Commit history depth. Default 50 is enough for most PR reviews. Use 0 for full history when you need complete git log or blame across a long-lived file.",default:50},cloneRoot:{type:"string",description:"Override the local directory where clones are stored. Leave unset in almost all cases \u2014 the default is managed automatically."}},required:["repo","sha"]}});import*as ie from"fs/promises";import*as Zn from"path";async function bv(r){for(;Yn.has(r);)await Yn.get(r);let e,t=new Promise(o=>{e=o});return Yn.set(r,t),()=>{Yn.delete(r),e()}}async function Bh(r){let e=0,t=await ie.readdir(r,{withFileTypes:!0});for(let o of t){let n=Zn.join(r,o.name);if(o.isDirectory())e+=await Bh(n);else if(o.isFile()){let s=await ie.stat(n);e+=s.size}}return e}async function wv(r,e){let t=e-r;for(;We>t&&Ue.size>0;){let o=null,n=null;for(let[s,i]of Ue)(!o||i.lastAccessedAt<o.lastAccessedAt)&&(o=i,n=s);if(!n||!o)break;try{await ie.rm(o.cloneDir,{recursive:!0,force:!0}),We=Math.max(0,We-o.sizeBytes),Ue.delete(n)}catch{break}}}async function Tv(r,e,t,o,n){let i=`https://x-access-token:${await G(r)}@github.com/${r}.git`,a=r.replace("/","_"),c=Zn.resolve(n,a),p=U(n),m=Ue.get(r);if(m)try{if(await ie.access(c),m.sha===e)return m.lastAccessedAt=Date.now(),c;await ie.rm(c,{recursive:!0,force:!0}),We=Math.max(0,We-m.sizeBytes),Ue.delete(r)}catch{We=Math.max(0,We-m.sizeBytes),Ue.delete(r)}else try{await ie.access(c),await ie.rm(c,{recursive:!0,force:!0})}catch{}let f=["--no-checkout"];o>0&&f.push("--depth",o.toString()),t&&t!=="none"&&f.push("--filter",t);try{await p.clone(i,a,f);let g=U(c);try{let b=["origin",e];o>0&&b.push("--depth",o.toString()),await g.fetch(b)}catch{}await g.checkout(["--force",e]);let w=await Bh(c);return We+=w,Ue.set(r,{cloneDir:c,repo:r,sha:e,sizeBytes:w,lastAccessedAt:Date.now()}),c}catch(g){try{await ie.rm(c,{recursive:!0,force:!0})}catch{}throw g}}function xv(r){return(r instanceof Error?r.message:String(r)).replace(/x-access-token:[^@]+@/g,"x-access-token:***@")}var hv,yv,Ue,Yn,We,er,zh=h(()=>{"use strict";l();Gh();Ce();xe();hv=".toolpack/clones",yv=5e9,Ue=new Map,Yn=new Map,We=0;er={name:"git.clone",displayName:"Git Clone",description:"Clone a GitHub repository at a specific commit SHA for local inspection. Call this before using git.diff, git.blame, git.log, fs.*, or coding.* tools \u2014 those tools accept the returned cloneDir to operate locally instead of through the GitHub API. Repeated calls with the same repo+sha are instant (cached). Disk is managed automatically with LRU eviction.",category:"version-control",parameters:Uh,execute:async r=>{let e=r.repo,t=r.sha,o=r.filter??"blob:none",n=r.depth??50,s=r.cloneRoot??process.env.SENTINEL_CLONE_ROOT??hv,i=parseInt(process.env.SENTINEL_CLONE_MAX_BYTES??"0",10)||yv;if(!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(e))return'Error: repo must be in "owner/repo" format with alphanumeric, hyphens, underscores, or dots only (e.g., "microsoft/typescript")';if(!/^[a-f0-9]{7,40}$/i.test(t))return"Error: sha must be a valid commit SHA (7-40 hex characters)";await ie.mkdir(s,{recursive:!0});let c=await bv(e);try{let p=Ue.get(e);if(p&&p.sha===t)return p.lastAccessedAt=Date.now(),JSON.stringify({cloneDir:p.cloneDir,next:"Pass cloneDir to compatible git, filesystem, or coding tools to inspect this checkout."});await wv(1e8,i);let m=await Tv(e,t,o,n,s);return JSON.stringify({cloneDir:m,next:"Pass cloneDir to compatible git, filesystem, or coding tools to inspect this checkout."})}catch(p){return`Error cloning repository: ${xv(p)}`}finally{c()}}}});var Kh={};le(Kh,{gitAddTool:()=>Hn,gitBlameTool:()=>Jn,gitBranchCreateTool:()=>Qn,gitBranchListTool:()=>Vn,gitCheckoutTool:()=>Xn,gitCloneTool:()=>er,gitCommitTool:()=>Kn,gitDiffTool:()=>Bn,gitLogTool:()=>zn,gitStatusTool:()=>Gn,gitToolsProject:()=>Hh});var Hh,yi=h(()=>{"use strict";l();yh();Th();Ch();Sh();$h();Mh();Ah();jh();Wh();zh();Hh={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","git.clone"],category:"version-control"},tools:[Gn,Bn,zn,Hn,Kn,Jn,Vn,Qn,Xn,er],dependencies:{"simple-git":"^3.27.0"}}});var Jh,Vh=h(()=>{"use strict";l();Jh={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 Qh from"diff";var tr,Xh=h(()=>{"use strict";l();Vh();k();tr={name:"diff.create",displayName:"Create Diff",description:"Generate a unified diff from two text contents.",category:"diff",parameters:Jh,execute:async r=>{let e=r.oldContent,t=r.newContent,o=r.fileName||"file",n=r.contextLines??4;y(`[diff.create] execute fileName="${o}" contextLines=${n}`);try{return Qh.createPatch(o,e,t,"","",{context:n})}catch(s){return`Error creating diff: ${s instanceof Error?s.message:String(s)}`}}}});var Yh,Zh=h(()=>{"use strict";l();Yh={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 ty from"diff";import{promises as ey}from"fs";var or,oy=h(()=>{"use strict";l();Zh();k();or={name:"diff.apply",displayName:"Apply Diff",description:"Apply a unified diff patch to a file.",category:"diff",parameters:Yh,execute:async r=>{let e=r.path,t=r.patch;y(`[diff.apply] execute path="${e}"`);try{let o=await ey.readFile(e,"utf8"),n=ty.applyPatch(o,t);return n===!1?"Failed to apply patch. The patch may be malformed or conflicting with the current file content.":(await ey.writeFile(e,n,"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 ny,ry=h(()=>{"use strict";l();ny={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 sy from"diff";import{promises as vv}from"fs";var nr,iy=h(()=>{"use strict";l();ry();nr={name:"diff.preview",displayName:"Preview Diff",description:"Preview the result of applying a patch to a file without modifying it.",category:"diff",parameters:ny,execute:async r=>{let e=r.path,t=r.patch;try{let o=await vv.readFile(e,"utf8"),n=sy.applyPatch(o,t);return n===!1?"Patch preview failed. The patch would not apply cleanly.":`Preview of ${e} after patch:
117
299
 
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(`
300
+ ${n}`}catch(o){return`Error previewing patch: ${o instanceof Error?o.message:String(o)}`}}}});var ly={};le(ly,{diffApplyTool:()=>or,diffCreateTool:()=>tr,diffPreviewTool:()=>nr,diffToolsProject:()=>ay});var ay,bi=h(()=>{"use strict";l();Xh();oy();iy();ay={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:[tr,or,nr],dependencies:{diff:"^7.0.0"}}});var cy,py=h(()=>{"use strict";l();cy={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 Ge,rr=h(()=>{"use strict";l();Ge=class{connectionString;constructor(e){this.connectionString=e}}});import my from"better-sqlite3";import*as wi from"fs";var sn,dy=h(()=>{"use strict";l();rr();sn=class extends Ge{getDb(){if(!wi.existsSync(this.connectionString))throw new Error(`Database file not found: ${this.connectionString}`);return new my(this.connectionString,{readonly:!1})}async query(e,t=[]){let o=this.getDb();try{let n=o.prepare(e);return n.reader?n.all(t):(n.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(!wi.existsSync(e))throw new Error(`Database file not found: ${e}`);let n=new my(e,{readonly:!1});try{let s=n.prepare(t);return s.reader?s.all(o):s.run(o)}finally{n.close()}}}});import Cv from"pg";var sr,uy=h(()=>{"use strict";l();rr();sr=class extends Ge{async getClient(){let e=new Cv.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 n=this.convertSql(e);return(await o.query(n,t)).rows}finally{await o.end()}}async execute(e,t=[]){let o=await this.getClient();try{let n=this.convertSql(e),s=await o.query(n,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
301
  SELECT column_name, data_type, is_nullable, column_default
120
302
  FROM information_schema.columns
121
303
  WHERE table_name = $1
@@ -123,42 +305,115 @@ ${r}`}catch(o){return`Error previewing patch: ${o instanceof Error?o.message:Str
123
305
  SELECT table_name as name, table_type
124
306
  FROM information_schema.tables
125
307
  WHERE table_schema = 'public'
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.
308
+ `)}}});import kv from"mysql2/promise";var ir,fy=h(()=>{"use strict";l();rr();ir=class extends Ge{async getConnection(){return await kv.createConnection(this.connectionString)}async query(e,t=[]){let o=await this.getConnection();try{let[n]=await o.execute(e,t);return n}finally{await o.end()}}async execute(e,t=[]){let o=await this.getConnection();try{let[n]=await o.execute(e,t);return{changes:n.affectedRows,lastInsertRowid:n.insertId,raw:n}}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(n=>n[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 Q,Be=h(()=>{"use strict";l();dy();uy();fy();Q=class{static getAdapter(e){return e.startsWith("postgres://")||e.startsWith("postgresql://")?new sr(e):e.startsWith("mysql://")?new ir(e):e.startsWith("sqlite://")?new sn(e.replace("sqlite://","")):new sn(e)}}});var ar,gy=h(()=>{"use strict";l();py();Be();k();ar={name:"db.query",displayName:"Database Query",description:"Execute raw SQL queries against an SQLite, PostgreSQL, or MySQL database.",category:"database",parameters:cy,execute:async r=>{let e=r.db,t=r.sql,o=r.params||[];y(`[db.query] execute db="${e}" sql="${t.substring(0,80)}..." params=${o.length}`);try{let s=await Q.getAdapter(e).query(t,o);return JSON.stringify(s,null,2)}catch(n){return`Database query error: ${n instanceof Error?n.message:String(n)}`}}}});var hy,yy=h(()=>{"use strict";l();hy={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 lr,by=h(()=>{"use strict";l();yy();Be();lr={name:"db.schema",displayName:"Database Schema",description:"Get the structural schema of a database or a specific table.",category:"database",parameters:hy,execute:async r=>{let e=r.db,t=r.table;try{let n=await Q.getAdapter(e).getSchema(t);return JSON.stringify(n,null,2)}catch(o){return`Database schema error: ${o instanceof Error?o.message:String(o)}`}}}});var wy,Ty=h(()=>{"use strict";l();wy={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"}},required:["db"]}});var cr,xy=h(()=>{"use strict";l();Ty();Be();cr={name:"db.tables",displayName:"Database Tables",description:"List all user tables in the database.",category:"database",parameters:wy,execute:async r=>{let e=r.db;try{let o=await Q.getAdapter(e).getTables();return JSON.stringify(o,null,2)}catch(t){return`Database tables error: ${t instanceof Error?t.message:String(t)}`}}}});var vy,Cy=h(()=>{"use strict";l();vy={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 pr,ky=h(()=>{"use strict";l();Cy();Be();pr={name:"db.insert",displayName:"Database Insert",description:"Insert a new row into an SQLite table safely.",category:"database",parameters:vy,execute:async r=>{let e=r.db,t=r.table,o=r.data;if(Object.keys(o).length===0)return"Error: No data provided to insert.";try{let n=Object.keys(o).join(", "),s=Object.keys(o).map(()=>"?").join(", "),i=Object.values(o),a=`INSERT INTO ${t} (${n}) VALUES (${s})`,p=await Q.getAdapter(e).execute(a,i);return JSON.stringify(p,null,2)}catch(n){return`Database insert error: ${n instanceof Error?n.message:String(n)}`}},confirmation:{level:"medium",reason:"This will insert rows into the database, creating permanent records.",showArgs:["table","data"]}}});var Py,Sy=h(()=>{"use strict";l();Py={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 mr,Ry=h(()=>{"use strict";l();Sy();Be();mr={name:"db.update",displayName:"Database Update",description:"Update existing rows in a database table.",category:"database",parameters:Py,execute:async r=>{let e=r.db,t=r.table,o=r.data,n=r.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 ${n}`,p=await Q.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 _y,$y=h(()=>{"use strict";l();_y={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 dr,Ey=h(()=>{"use strict";l();$y();Be();dr={name:"db.delete",displayName:"Database Delete",description:"Delete rows from a database table.",category:"database",parameters:_y,execute:async r=>{let e=r.db,t=r.table,o=r.where;try{let n=`DELETE FROM ${t} WHERE ${o}`,i=await Q.getAdapter(e).execute(n);return JSON.stringify(i,null,2)}catch(n){return`Database delete error: ${n instanceof Error?n.message:String(n)}`}},confirmation:{level:"high",reason:"This will permanently delete rows from the database.",showArgs:["table","where"]}}});var Dy,My=h(()=>{"use strict";l();Dy={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 ur,Oy=h(()=>{"use strict";l();My();Be();ur={name:"db.count",displayName:"Database Count",description:"Count rows in a database table.",category:"database",parameters:Dy,execute:async r=>{let e=r.db,t=r.table,o=r.where;try{let n=o?`WHERE ${o}`:"",s=`SELECT COUNT(*) as count FROM ${t} ${n}`,a=await Q.getAdapter(e).query(s);return Array.isArray(a)&&a.length>0?`Rows: ${a[0].count}`:"Count: 0"}catch(n){return`Database count error: ${n instanceof Error?n.message:String(n)}`}}}});var Ay={};le(Ay,{dbCountTool:()=>ur,dbDeleteTool:()=>dr,dbInsertTool:()=>pr,dbQueryTool:()=>ar,dbSchemaTool:()=>lr,dbTablesTool:()=>cr,dbToolsProject:()=>Ny,dbUpdateTool:()=>mr});var Ny,Ti=h(()=>{"use strict";l();gy();by();xy();ky();Ry();Ey();Oy();Ny={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:[ar,lr,cr,pr,mr,dr,ur],dependencies:{"better-sqlite3":"^11.3.0"}}});var Iy,Ly=h(()=>{"use strict";l();Iy={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 Pv}from"netlify";var ze,fr=h(()=>{"use strict";l();ze=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 Pv(e)}}});var gr,jy=h(()=>{"use strict";l();Ly();fr();k();gr={name:"cloud.deploy",displayName:"Cloud Deploy",description:"Deploy a static directory to Netlify.",category:"cloud",parameters:Iy,execute:async r=>{let e=r.siteId,t=r.dir,o=r.message;y(`[cloud.deploy] execute siteId="${e}" dir="${t}" message="${o??"none"}"`);try{let s=await ze.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(n){return`Cloud deployment error: ${n instanceof Error?n.message:String(n)}`}},confirmation:{level:"high",reason:"This will deploy to production (live site).",showArgs:["siteId","dir"]}}});var Fy,qy=h(()=>{"use strict";l();Fy={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 hr,Wy=h(()=>{"use strict";l();qy();fr();hr={name:"cloud.status",displayName:"Cloud Status",description:"Check the status of a specific Netlify deployment.",category:"cloud",parameters:Fy,execute:async r=>{let e=r.siteId,t=r.deployId;try{let n=await ze.getClient().getSiteDeploy({site_id:e,deploy_id:t});return JSON.stringify({id:n.id,state:n.state,error_message:n.error_message,created_at:n.created_at,updated_at:n.updated_at,url:n.url},null,2)}catch(o){return`Cloud status error: ${o instanceof Error?o.message:String(o)}`}}}});var Uy,Gy=h(()=>{"use strict";l();Uy={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 yr,By=h(()=>{"use strict";l();Gy();fr();k();yr={name:"cloud.list",displayName:"Cloud Deployments List",description:"List recent deployments for a Netlify site.",category:"cloud",parameters:Uy,execute:async r=>{let e=r.siteId,t=r.limit||5;y(`[cloud.list] execute siteId="${e}" limit=${t}`);try{let n=await ze.getClient().listSiteDeploys({site_id:e,page:1,per_page:t});if(!Array.isArray(n))return"Unexpected response format from Netlify API";let s=n.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 Hy={};le(Hy,{cloudDeployTool:()=>gr,cloudListTool:()=>yr,cloudStatusTool:()=>hr,cloudToolsProject:()=>zy});var zy,xi=h(()=>{"use strict";l();jy();Wy();By();zy={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:[gr,hr,yr],dependencies:{netlify:"^13.1.20"}}});var Ky,Jy,Vy,Qy,Xy,Yy=h(()=>{"use strict";l();Ky="slack.chat.postMessage",Jy="Post Slack Message",Vy="Post a message to a Slack channel or thread. Supports plain mrkdwn text and optional Block Kit blocks for rich formatting. Use thread_ts to reply inside an existing thread.",Qy="slack",Xy={type:"object",properties:{channel:{type:"string",description:"Channel ID or channel name (e.g. #general) to post to."},text:{type:"string",description:"Message text in Slack mrkdwn format. Always required \u2014 used as fallback when blocks are provided."},thread_ts:{type:"string",description:"Timestamp of the parent message to reply in a thread. Omit to post at top level."},blocks:{type:"string",description:"Optional Block Kit layout as a JSON string. When provided, text is used only as the notification fallback."},token:{type:"string",description:"Slack bot token. Defaults to TOOLPACK_SLACK_BOT_TOKEN env var."}},required:["channel","text"]}});function ue(r){if(r)return r;let e=process.env.TOOLPACK_SLACK_BOT_TOKEN;if(e)return e;throw new Error("No Slack token available. Set TOOLPACK_SLACK_BOT_TOKEN or pass token in tool args.")}var st=h(()=>{"use strict";l()});function Sv(r){return{Authorization:`Bearer ${r}`,"Content-Type":"application/json; charset=utf-8"}}async function fe(r,e,t){let o=await fetch(`https://slack.com/api/${r}`,{method:"POST",headers:Sv(e),body:JSON.stringify(t)});if(!o.ok)throw new Error(`Slack HTTP error ${o.status} ${o.statusText}`);let n=await o.json();if(!n.ok)throw new Error(`Slack API error: ${n.error??"unknown"}`);return n}var it=h(()=>{"use strict";l()});async function Rv(r){let e=String(r.channel),t=String(r.text),o=r.thread_ts?String(r.thread_ts):void 0,n=r.blocks?String(r.blocks):void 0,s=ue(r.token),i={channel:e,text:t};if(o&&(i.thread_ts=o),n)try{i.blocks=JSON.parse(n)}catch{return"Error: blocks is not valid JSON."}let a=await fe("chat.postMessage",s,i),c=a.ts??"";return`Message posted. channel=${a.channel??e} ts=${c}`}var an,vi=h(()=>{"use strict";l();Yy();st();it();an={name:Ky,displayName:Jy,description:Vy,parameters:Xy,category:Qy,execute:Rv}});var Zy,eb,tb,ob,nb,rb=h(()=>{"use strict";l();Zy="slack.chat.postEphemeral",eb="Post Ephemeral Slack Message",tb="Post a temporary message visible only to a specific user in a Slack channel. Useful for private confirmations, status updates, or error messages that should not be seen by others.",ob="slack",nb={type:"object",properties:{channel:{type:"string",description:"Channel ID where the ephemeral message will appear."},user:{type:"string",description:"Slack user ID of the person who will see the message."},text:{type:"string",description:"Message text in Slack mrkdwn format."},thread_ts:{type:"string",description:"Timestamp of the parent message to show the ephemeral reply inside a thread."},token:{type:"string",description:"Slack bot token. Defaults to TOOLPACK_SLACK_BOT_TOKEN env var."}},required:["channel","user","text"]}});async function _v(r){let e=String(r.channel),t=String(r.user),o=String(r.text),n=r.thread_ts?String(r.thread_ts):void 0,s=ue(r.token),i={channel:e,user:t,text:o};return n&&(i.thread_ts=n),await fe("chat.postEphemeral",s,i),`Ephemeral message sent to user=${t} in channel=${e}.`}var ln,Ci=h(()=>{"use strict";l();rb();st();it();ln={name:Zy,displayName:eb,description:tb,parameters:nb,category:ob,execute:_v}});var sb,ib,ab,lb,cb,pb=h(()=>{"use strict";l();sb="slack.reactions.add",ib="Add Slack Reaction",ab="Add an emoji reaction to a Slack message. Useful for acknowledging receipt (\u{1F440} eyes), signalling completion (\u2705 white_check_mark), or flagging issues (\u26A0\uFE0F warning). Requires the reactions:write OAuth scope on the Slack app.",lb="slack",cb={type:"object",properties:{channel:{type:"string",description:"Channel ID containing the message to react to."},timestamp:{type:"string",description:"Timestamp of the message to react to."},name:{type:"string",description:'Emoji name without colons (e.g. "eyes", "white_check_mark", "warning", "x").'},token:{type:"string",description:"Slack bot token. Defaults to TOOLPACK_SLACK_BOT_TOKEN env var."}},required:["channel","timestamp","name"]}});async function $v(r){let e=String(r.channel),t=String(r.timestamp),o=String(r.name),n=ue(r.token);try{await fe("reactions.add",n,{channel:e,timestamp:t,name:o})}catch(s){if(s instanceof Error&&s.message.includes("already_reacted"))return`Reaction :${o}: already present on message ts=${t}.`;throw s}return`Reaction :${o}: added to message ts=${t} in channel=${e}.`}var cn,ki=h(()=>{"use strict";l();pb();st();it();cn={name:sb,displayName:ib,description:ab,parameters:cb,category:lb,execute:$v}});var mb,db,ub,fb,gb,hb=h(()=>{"use strict";l();mb="slack.conversations.history",db="Get Slack Channel History",ub="Fetch recent messages from a Slack channel. Useful for reading conversation context, checking what was discussed, or finding a specific message timestamp to react to or thread-reply into.",fb="slack",gb={type:"object",properties:{channel:{type:"string",description:"Channel ID to fetch history from."},limit:{type:"integer",description:"Maximum number of messages to return. Defaults to 10, max 100."},oldest:{type:"string",description:"Only return messages after this Unix timestamp (inclusive)."},latest:{type:"string",description:"Only return messages before this Unix timestamp (exclusive)."},token:{type:"string",description:"Slack bot token. Defaults to TOOLPACK_SLACK_BOT_TOKEN env var."}},required:["channel"]}});async function Ev(r){let e=String(r.channel),t=typeof r.limit=="number"?Math.min(r.limit,100):10,o=ue(r.token),n={channel:e,limit:t};r.oldest&&(n.oldest=String(r.oldest)),r.latest&&(n.latest=String(r.latest));let i=(await fe("conversations.history",o,n)).messages??[];return i.length===0?"No messages found.":[...i].reverse().map(c=>{let p=c.user?`user:${c.user}`:c.bot_id?`bot:${c.bot_id}`:"unknown",m=c.reply_count?` [thread: ${c.reply_count} replies]`:"",f=(c.text??"").replace(/\n/g," ").slice(0,200);return`[${c.ts}] ${p}${m}: ${f}`}).join(`
309
+ `)}var pn,Pi=h(()=>{"use strict";l();hb();st();it();pn={name:mb,displayName:db,description:ub,parameters:gb,category:fb,execute:Ev}});var yb,bb,wb,Tb,xb,vb=h(()=>{"use strict";l();yb="slack.conversations.replies",bb="Get Slack Thread Replies",wb="Fetch all replies in a Slack thread. Use this to read the full conversation history of a thread, including who replied and when. Requires the channel ID and the timestamp (ts) of the parent message that started the thread.",Tb="slack",xb={type:"object",properties:{channel:{type:"string",description:"Channel ID that contains the thread."},ts:{type:"string",description:"Timestamp of the parent message that started the thread."},limit:{type:"integer",description:"Maximum number of replies to return. Defaults to 20, max 100."},oldest:{type:"string",description:"Only return replies after this Unix timestamp (inclusive)."},latest:{type:"string",description:"Only return replies before this Unix timestamp (exclusive)."},token:{type:"string",description:"Slack bot token. Defaults to TOOLPACK_SLACK_BOT_TOKEN env var."}},required:["channel","ts"]}});async function Dv(r){let e=String(r.channel),t=String(r.ts),o=typeof r.limit=="number"?Math.min(r.limit,100):20,n=ue(r.token),s={channel:e,ts:t,limit:o};r.oldest&&(s.oldest=String(r.oldest)),r.latest&&(s.latest=String(r.latest));let a=(await fe("conversations.replies",n,s)).messages??[];return a.length===0?"No replies found.":a.map((p,m)=>{let f=p.user?`user:${p.user}`:p.bot_id?`bot:${p.bot_id}`:"unknown",g=m===0?" [parent]":"",w=(p.text??"").replace(/\n/g," ").slice(0,200);return`[${p.ts}] ${f}${g}: ${w}`}).join(`
310
+ `)}var mn,Si=h(()=>{"use strict";l();vb();st();it();mn={name:yb,displayName:bb,description:wb,parameters:xb,category:Tb,execute:Dv}});var Cb,kb,Pb,Sb,Rb,_b=h(()=>{"use strict";l();Cb="slack.auth.test",kb="Slack Auth Test",Pb="Verify the bot token and retrieve the identity of the calling app. Returns the bot_id, user_id, team, and workspace URL. Use this when the bot_id is not configured and is needed for self-suppression or other identity checks.",Sb="slack",Rb={type:"object",properties:{token:{type:"string",description:"Slack bot token. Defaults to TOOLPACK_SLACK_BOT_TOKEN env var."}},required:[]}});async function Mv(r){let e=ue(r.token),t=await fe("auth.test",e,{});return JSON.stringify({bot_id:t.bot_id,user_id:t.user_id,user:t.user,team:t.team,team_id:t.team_id,url:t.url},null,2)}var dn,Ri=h(()=>{"use strict";l();_b();st();it();dn={name:Cb,displayName:kb,description:Pb,parameters:Rb,category:Sb,execute:Mv}});var Eb={};le(Eb,{slackAuthTestTool:()=>dn,slackChatPostEphemeralTool:()=>ln,slackChatPostMessageTool:()=>an,slackConversationsHistoryTool:()=>pn,slackConversationsRepliesTool:()=>mn,slackReactionsAddTool:()=>cn,slackToolsProject:()=>$b});var $b,_i=h(()=>{"use strict";l();vi();Ci();ki();Pi();Si();Ri();vi();Ci();ki();Pi();Si();Ri();$b={manifest:{key:"slack",name:"slack-tools",displayName:"Slack",version:"1.0.0",description:"Slack Web API tools \u2014 post messages, reply in threads, react to messages, read channel history, read thread replies, and verify bot identity.",author:"Toolpack",tools:["slack.chat.postMessage","slack.chat.postEphemeral","slack.reactions.add","slack.conversations.history","slack.conversations.replies","slack.auth.test"],category:"network"},tools:[an,ln,cn,pn,mn,dn]}});l();ce();l();ce();import{EventEmitter as bw}from"events";l();ce();var Dt=class extends A{constructor(t,o,n,s,i,a){super(t,"CONTEXT_WINDOW_EXCEEDED",400,a);this.conversationId=o;this.currentTokens=n;this.contextWindowLimit=s;this.strategy=i;this.name="ContextWindowExceededError"}conversationId;currentTokens;contextWindowLimit;strategy;getOverageTokens(){return Math.max(0,this.currentTokens-this.contextWindowLimit)}getUsagePercentage(){return Math.round(this.currentTokens/this.contextWindowLimit*100)}getDetailedReport(){return`
311
+ Context Window Exceeded
312
+ =======================
313
+ Conversation ID: ${this.conversationId}
314
+ Current Tokens: ${this.currentTokens}
315
+ Context Window Limit: ${this.contextWindowLimit}
316
+ Overage: ${this.getOverageTokens()} tokens
317
+ Usage: ${this.getUsagePercentage()}%
318
+ Strategy: ${this.strategy}
319
+
320
+ Message: ${this.message}
321
+ `.trim()}};var Mt=class extends A{constructor(t,o,n,s,i,a){super(t,"SUMMARIZATION_ERROR",500,a);this.conversationId=o;this.messageCount=n;this.failureReason=s;this.summaryAttempt=i;this.name="SummarizationError"}conversationId;messageCount;failureReason;summaryAttempt;isRetryable(){return this.failureReason==="provider_error"||this.failureReason==="insufficient_tokens"}getSuggestedRecovery(){switch(this.failureReason){case"provider_error":return"Retry the summarization request or switch to a different summarizer model";case"invalid_response":return"Review the summarizer prompt or use a different model";case"insufficient_tokens":return"Reduce the number of messages to summarize or increase the summary token budget";case"invalid_quality":return"Adjust summarization parameters or use a more capable model";default:return"Manual intervention required"}}getDetailedReport(){let t=`
322
+ Summarization Error
323
+ ===================
324
+ Conversation ID: ${this.conversationId}
325
+ Messages Attempted: ${this.messageCount}
326
+ Failure Reason: ${this.failureReason}
327
+ Retryable: ${this.isRetryable()?"Yes":"No"}
328
+ Recovery Action: ${this.getSuggestedRecovery()}
329
+
330
+ Message: ${this.message}`;return this.summaryAttempt?t+`
331
+
332
+ Partial Summary:
333
+ ${this.summaryAttempt.substring(0,500)}${this.summaryAttempt.length>500?"...":""}`:t.trim()}};l();var Dr=null;async function ow(){if(!Dr)try{Dr=await import("js-tiktoken")}catch{}return Dr}var oa={"gpt-4.1":3,"gpt-4.1-mini":3,"gpt-5.1":3,"gpt-5.2":3,"gpt-5.4":3,"gpt-5.4-pro":3,__default__:4},nw=2;async function rw(r,e){try{let t=await ow();if(!t)return Ne(r);let o=t.encoding_for_model(e),n=0,s=oa[e]??oa.__default__;for(let i of r){if(n+=s,typeof i.content=="string")n+=o.encode(i.content).length;else if(Array.isArray(i.content))for(let a of i.content)a.type==="text"?n+=o.encode(a.text).length:(a.type==="image_data"||a.type==="image_url"||a.type==="image_file")&&(n+=256);if(i.tool_calls?.length)for(let a of i.tool_calls)n+=o.encode(a.function.name).length,n+=o.encode(a.function.arguments).length;i.name&&(n+=o.encode(i.name).length)}return n+=nw,n}catch{return Ne(r)}}async function sw(r,e){try{let t=Ne(r);return Math.ceil(t*1.1)}catch{return Ne(r)}}async function iw(r,e){try{let t=Ne(r);return Math.ceil(t*1.05)}catch{return Ne(r)}}async function aw(r,e){let t=Ne(r);return Math.ceil(t*1.05)}function Ne(r){let e=0;for(let t of r){if(e+=50,typeof t.content=="string")e+=t.content.length;else if(Array.isArray(t.content))for(let o of t.content)o.type==="text"?e+=o.text.length:(o.type==="image_data"||o.type==="image_url"||o.type==="image_file")&&(e+=1e3);if(t.tool_calls?.length)for(let o of t.tool_calls)e+=o.function.name.length,e+=o.function.arguments.length;t.name&&(e+=t.name.length)}return Math.ceil(e/4)}async function na(r,e,t){let o=t.toLowerCase();return o==="openai"||o==="openai-gpt"?rw(r,e):o==="anthropic"||o==="claude"?sw(r,e):o==="gemini"||o==="google"?iw(r,e):o==="ollama"?aw(r,e):Ne(r)}function hC(r,e,t){let o=e-t;return r>o}function yC(r,e){return Math.round(r/e*100)}function ra(r,e=1.15){return Math.ceil(r*e)}l();function sa(r,e,t=!0){let o=r.length,n=[],s=0,i=[];r.forEach((p,m)=>{t&&p.role==="system"||p.role!=="tool"&&i.push({index:m,message:p})});for(let{message:p}of i){if(s>=e)break;let m=Mr(p);if(s+=m,n.push(p),p.role==="assistant"&&p.tool_calls?.length){let f=new Set(p.tool_calls.map(g=>g.id));for(let g of r)g.role==="tool"&&g.tool_call_id&&f.has(g.tool_call_id)&&(s+=Mr(g),n.push(g))}}let a=new Set(n),c=r.filter(p=>!a.has(p));return{removed:n.length,tokensReclaimed:s,newTotal:c.length,pruneInfo:{beforeCount:o,afterCount:c.length,removedMessages:n}}}function TC(r,e){if(typeof r.content=="string"){let t=e*4;if(r.content.length<=t)return r;let o=r.content.substring(0,t),n=Math.ceil((r.content.length-t)/4);return{...r,content:`${o}
334
+
335
+ [...truncated ${n} tokens]`}}else if(Array.isArray(r.content)){let t=r.content.filter(a=>a.type==="text"),o=t.reduce((a,c)=>a+(c.text?.length||0),0),n=e*4;if(o<=n)return r;let s=0,i=[];for(let a of t)if(a.type==="text"){let c=n-s;if(c<=0)break;let p=a.text;if(p.length<=c)i.push(a),s+=p.length;else{let m=p.substring(0,c),f=Math.ceil((p.length-c)/4);i.push({type:"text",text:`${m}
336
+
337
+ [...truncated ${f} tokens]`});break}}return{...r,content:i.length>0?i:r.content}}return r}function Mr(r){let e=4;if(typeof r.content=="string")e+=Math.ceil(r.content.length/4);else if(Array.isArray(r.content))for(let t of r.content)t.type==="text"?e+=Math.ceil((t.text?.length||0)/4):(t.type==="image_data"||t.type==="image_url"||t.type==="image_file")&&(e+=256);if(r.tool_calls?.length)for(let t of r.tool_calls)e+=Math.ceil(t.function.name.length/4),e+=Math.ceil(t.function.arguments.length/4);return r.name&&(e+=Math.ceil(r.name.length/4)),e}function xC(r){let e={system:[],user:[],assistant:[],tool:[]};return r.forEach(t=>{e[t.role]??=[],e[t.role].push(t)}),e}function vC(r){let e=0,t={},o=0;for(let n of r){let s=Mr(n);e+=s,o=Math.max(o,s),t[n.role]??=0,t[n.role]++}return{totalMessages:r.length,totalTokens:e,byRole:t,largestMessageTokens:o}}l();ce();function Or(r){return r.content==null?"":typeof r.content=="string"?r.content:r.content.map(e=>e.type==="text"?e.text:e.type==="image_url"?`[image: ${e.image_url.url}]`:e.type==="image_file"?`[image-file: ${e.image_file.path}]`:e.type==="image_data"?`[image-data: ${e.image_data.mimeType}]`:"").filter(Boolean).join(" ")}function lw(r,e){if(e)return e;let t=r.filter(c=>c.role==="user"),o=r.filter(c=>c.role==="assistant"),n=r.filter(c=>c.role==="tool"),s=r.length,i=t.length,a=o.length;return`Please provide a concise summary of the following conversation history. The conversation contains ${s} messages (${i} user messages, ${a} assistant responses${n.length>0?`, and ${n.length} tool responses`:""}).
338
+
339
+ Focus on:
340
+ 1. Key topics discussed
341
+ 2. Important decisions or conclusions
342
+ 3. User's intent and goals
343
+ 4. Relevant context for continuing the conversation
344
+
345
+ The summary should be comprehensive yet concise, preserving all critical information needed to continue the conversation naturally.
346
+
347
+ ---
348
+ CONVERSATION:
349
+ ${r.map((c,p)=>{let m=Or(c);return`[Message ${p+1}] ${c.role.toUpperCase()}: ${m.substring(0,200)}${m.length>200?"...":""}`}).join(`
350
+ `)}
351
+ ---
352
+
353
+ SUMMARY:`}function Nr(r,e){return{role:"system",content:`[Context Summary]
354
+ This conversation has been summarized to manage context window. The following is a summary of the first ${e} messages:
355
+
356
+ ${r}
357
+
358
+ [End Summary]
359
+
360
+ Use this summary to understand the conversation context. When responding, acknowledge that you're aware of the previous conversation and continue naturally.`}}function SC(r){let e=new Set,t=[],o=[],n="";for(let s of r)if(s.role==="user"){let i=Or(s);n=i,i.includes("?")&&o.push(i.split(`
361
+ `)[0]);let a=i.match(/\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*\b/g);a&&a.forEach(c=>e.add(c))}else if(s.role==="assistant"){let i=Or(s);if(i.includes("decided")||i.includes("concluded")||i.includes("determined")){let a=i.split(/[.!?]+/);for(let c of a)(c.includes("decided")||c.includes("concluded")||c.includes("determined"))&&t.push(c.trim())}}return{topics:Array.from(e).slice(0,10),decisions:t.slice(0,5),userGoals:o.slice(0,5),context:n.substring(0,200)}}function cw(r){return Math.ceil(r.length/4)}function ia(r){let e=[];return(!r.summary||r.summary.length<10)&&e.push("Summary is too short"),r.summary.length>5e3&&e.push("Summary is excessively long"),r.messageCount<2&&e.push("Must summarize at least 2 messages"),r.summaryTokens>=r.originalTokens*.8&&e.push("Summary is not significantly shorter than original messages"),r.tokensSaved<0&&e.push("Token calculation error: saved tokens is negative"),{valid:e.length===0,issues:e}}function aa(r,e){let t=lw(r,e.summaryPrompt);return[{role:"system",content:`You are a conversation summarizer. Your task is to create a clear, concise summary of the provided conversation that preserves all critical information.
362
+
363
+ Maximum summary length: ${e.maxSummaryTokens||500} tokens.
364
+ Format: Write only the summary without any additional commentary.`},{role:"user",content:t}]}function la(r,e,t){let o=cw(r),n=Math.max(0,t-o);return{summary:r.trim(),messageCount:e.length,originalTokens:t,summaryTokens:o,tokensSaved:n,timestamp:new Date}}function RC(r,e,t){let o=[...r];return o.push(Nr(e.summary,e.messageCount)),o.push(...t),o}function _C(r,e,t){let o=Math.round(r.tokensSaved/r.originalTokens*100);return`
365
+ Summarization Report
366
+ ====================
367
+ Timestamp: ${r.timestamp.toISOString()}
368
+ Status: \u2713 Summarization completed
369
+
370
+ Input Analysis:
371
+ - Messages summarized: ${r.messageCount}
372
+ - Original token count: ${r.originalTokens}
373
+ - Summary token count: ${r.summaryTokens}
374
+ - Tokens saved: ${r.tokensSaved} (${o}% reduction)
375
+
376
+ Message Count:
377
+ - Before: ${e} messages
378
+ - After: ${t} messages
379
+ - Reduction: ${e-t} messages
380
+
381
+ Summary Preview:
382
+ ${r.summary.substring(0,300)}${r.summary.length>300?"...":""}
383
+ `.trim()}function $C(r){if(r.length===0)throw new A("Cannot merge empty summarization results","CONTEXT_WINDOW_ERROR");return{summary:r.map(t=>`[Round ${r.indexOf(t)+1}] ${t.summary}`).join(`
384
+
385
+ `),messageCount:r.reduce((t,o)=>t+o.messageCount,0),originalTokens:r.reduce((t,o)=>t+o.originalTokens,0),summaryTokens:r.reduce((t,o)=>t+o.summaryTokens,0),tokensSaved:r.reduce((t,o)=>t+o.tokensSaved,0),timestamp:new Date}}l();var Ar=class{states=new Map;config;maxTokens=1e5;constructor(e){this.config=e}getOrCreateState(e){return this.states.has(e)||this.states.set(e,{conversationId:e,estimatedTokens:0,lastUpdated:Date.now(),pruneCount:0,lastPrunedAt:void 0,warningsSent:0,summarizationCount:0}),this.states.get(e)}updateTokenCount(e,t){let o=this.getOrCreateState(e);return o.estimatedTokens=t,o.lastUpdated=Date.now(),o}recordPruneOperation(e,t){let o=this.getOrCreateState(e);return o.pruneCount++,o.lastPrunedAt=Date.now(),o.estimatedTokens=Math.max(0,o.estimatedTokens-t),o.lastUpdated=Date.now(),o}recordWarning(e){let t=this.getOrCreateState(e);return t.warningsSent++,t.lastUpdated=Date.now(),t}recordSummarization(e,t){let o=this.getOrCreateState(e);return o.summarizationCount++,o.estimatedTokens=Math.max(0,o.estimatedTokens-t),o.lastUpdated=Date.now(),o}getState(e){return this.states.get(e)}getAllStates(){return Array.from(this.states.values())}deleteState(e){return this.states.delete(e)}clearAllStates(){this.states.clear()}getStatistics(e){let t=this.states.get(e);if(!t)return null;let o=this.config.pruneThreshold||1e5,n=Math.round(t.estimatedTokens/o*100);return{conversationId:e,currentTokens:t.estimatedTokens,pruneCount:t.pruneCount,summarizationCount:t.summarizationCount,warningsSent:t.warningsSent,lastActivity:new Date(t.lastUpdated),contextWindowPercentage:n}}getExceedingThreshold(e){let t=e||this.maxTokens*(this.config.pruneThreshold||85)/100;return Array.from(this.states.values()).filter(o=>o.estimatedTokens>t)}getAtRiskConversations(e=80){let t=this.maxTokens,o=t*e/100;return Array.from(this.states.values()).filter(n=>n.estimatedTokens>o&&n.estimatedTokens<=t)}generateReport(){let e=this.getAllStates();if(e.length===0)return"No conversations tracked yet.";let t=this.config.pruneThreshold||1e5,o=["Context Window State Report","==========================",`Report Generated: ${new Date().toISOString()}`,`Context Window Limit: ${t} tokens`,`Total Conversations: ${e.length}`,""],n=e.reduce((f,g)=>f+g.estimatedTokens,0),s=e.reduce((f,g)=>f+g.pruneCount,0),i=e.reduce((f,g)=>f+g.summarizationCount,0),a=Math.round(n/e.length);o.push("Summary:"),o.push(`- Total tokens across all conversations: ${n}`),o.push(`- Average tokens per conversation: ${a}`),o.push(`- Total prune operations: ${s}`),o.push(`- Total summarizations: ${i}`),o.push("");let c=this.getAtRiskConversations();c.length>0&&(o.push(`At-Risk Conversations (80%+ threshold): ${c.length}`),c.forEach(f=>{let g=Math.round(f.estimatedTokens/t*100);o.push(`- ${f.conversationId}: ${f.estimatedTokens}/${t} tokens (${g}%)`)}),o.push(""));let p=this.getExceedingThreshold();return p.length>0&&(o.push(`Exceeded Conversations: ${p.length}`),p.forEach(f=>{let g=f.estimatedTokens-t;o.push(`- ${f.conversationId}: ${f.estimatedTokens}/${t} tokens (+${g} over)`)}),o.push("")),o.push("Most Active Conversations (by operations):"),[...e].sort((f,g)=>{let w=f.pruneCount+f.summarizationCount;return g.pruneCount+g.summarizationCount-w}).slice(0,5).forEach(f=>{let g=f.pruneCount+f.summarizationCount;o.push(`- ${f.conversationId}: ${f.pruneCount} prunes, ${f.summarizationCount} summarizations (${g} operations)`)}),o.join(`
386
+ `)}export(){let e={};for(let[t,o]of this.states.entries())e[t]={...o,lastUpdated:o.lastUpdated,lastPrunedAt:o.lastPrunedAt};return e}import(e){for(let[t,o]of Object.entries(e))this.states.set(t,{...o,lastUpdated:typeof o.lastUpdated=="number"?o.lastUpdated:new Date(o.lastUpdated).getTime(),lastPrunedAt:o.lastPrunedAt&&typeof o.lastPrunedAt!="number"?new Date(o.lastPrunedAt).getTime():o.lastPrunedAt})}pruneInactiveConversations(e=60){let t=Date.now()-e*60*1e3,o=[];for(let[n,s]of this.states.entries())s.lastUpdated<t&&o.push(n);return o.forEach(n=>this.states.delete(n)),o}getMemoryUsage(){let e=this.states.size,t=e*500;return{conversationCount:e,approximateByteSize:t}}validateIntegrity(){let e=[];for(let[t,o]of this.states.entries())(!t||typeof t!="string")&&e.push(`Invalid conversation ID: ${t}`),o.estimatedTokens<0&&e.push(`Negative token count for ${t}: ${o.estimatedTokens}`),o.pruneCount<0&&e.push(`Negative prune count for ${t}: ${o.pruneCount}`),o.summarizationCount<0&&e.push(`Negative summarization count for ${t}: ${o.summarizationCount}`),o.warningsSent<0&&e.push(`Negative warning count for ${t}: ${o.warningsSent}`),(typeof o.lastUpdated!="number"||o.lastUpdated<=0)&&e.push(`Invalid lastUpdated timestamp for ${t}`),o.lastPrunedAt!==void 0&&(typeof o.lastPrunedAt!="number"||o.lastPrunedAt<=0)&&e.push(`Invalid lastPrunedAt timestamp for ${t}`);return{isValid:e.length===0,issues:e}}};function ca(r){return new Ar(r)}l();l();l();var pt={name:3,displayName:2.5,description:2,category:1.5,parameterNames:1,parameterDescriptions:.5},Ot=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 n=new Set(o.tokens);for(let s of n)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,n=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(n&&c.tool.category!==n)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<pt.name;i++)t.push(e.name);for(let i=0;i<pt.displayName;i++)t.push(e.displayName);for(let i=0;i<pt.description;i++)t.push(e.description);for(let i=0;i<pt.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<pt.parameterNames;c++)t.push(i);if(a.description)for(let c=0;c<pt.parameterDescriptions;c++)t.push(a.description)}let o=t.join(" ").toLowerCase(),n=this.tokenize(o),s=this.computeTermFrequencies(n);return{toolName:e.name,tool:e,text:o,tokens:n,length:n.length,termFrequencies:s}}tokenize(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1).filter(t=>!pw.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 n of e){let s=t.termFrequencies.get(n)||0;if(s===0)continue;let i=this.idf.get(n)||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}}},pw=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 mt=class r{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 r;for(let o of e)if(o.role==="tool"){let n=o;if(typeof n.content=="string")try{let s=JSON.parse(n.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 Nt="tool.search",dt={name:Nt,displayName:"Search Tools",category:"meta",description:`Search for available tools by keyword or natural language query.
127
387
  Use this to discover tools before using them.
128
388
  Examples: "file operations", "web scraping", "run command", "http request"
129
389
 
130
390
  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 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}
391
+ 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 At(){return{name:dt.name,displayName:dt.displayName,description:dt.description,parameters:dt.parameters,category:dt.category}}function bn(r){return r===Nt}l();var mw={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 Ir(r){let e=r.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=r.getByCategory(o).length,i=mw[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(`
392
+ `)}var It=class{discoveryCache=new mt;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 n=[],s=new Set;n.push(At()),s.add(Nt);let i=o.toolSearch?.alwaysLoadedTools??[];for(let c of i){let p=t.get(c);p&&!s.has(c)&&(n.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)||(n.push(this.toSchema(p)),s.add(p.name));if(o.toolSearch?.cacheDiscoveredTools!==!1){let c=mt.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&&(n.push(this.toSchema(f)),s.add(m))}}return n}resolveLegacy(e,t){let o;if(t.enabledTools.length===0&&t.enabledToolCategories.length===0)o=e.getEnabled();else{let n=e.getByNames(t.enabledTools),s=e.getByCategories(t.enabledToolCategories),i=new Set;o=[];for(let a of[...n,...s])i.has(a.name)||(i.add(a.name),o.push(a))}return o.map(n=>this.toSchema(n))}toSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category}}};Lt();l();function pa(r){if(r.disabled)return"";let e=r.includeWorkingDirectory!==!1,t=r.includeToolCategories!==!1,o=e?`
393
+ Working directory: ${r.workingDirectory}`:"",n=t&&r.toolCategories.length>0?`
394
+ Available tool categories: ${r.toolCategories.join(", ")}`:"";return`You are an AI assistant with access to tools that let you interact with the user's system.${o}${n}
135
395
 
136
396
  When the user asks you to do something, be proactive:
137
397
  - Use your tools to find information rather than asking the user for details you can discover yourself
138
398
  - 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 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
-
142
- User's new message: "${a}"
143
-
144
- Does this message:
145
- 1. Ask about the same topic/context as recent tools? OR
146
- 2. Request new information that requires external tools (web search, file access, commands)?
399
+ - Only ask the user for clarification when you genuinely cannot determine their intent or lack the required tools`}l();var ut=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,n=this.actionPatterns.filter(a=>a.test(t)).length,s=o/this.analyticalPatterns.length,i=n/this.actionPatterns.length;if(o>n&&o>0){let a=Math.min(s,1);return n>0&&(a=Math.min(a,.5)),{type:"analytical",confidence:a,reasoning:`Matched ${o} analytical patterns${n>0?`, ${n} action patterns (capped confidence)`:""}`}}else return n>o&&n>0?{type:"action",confidence:Math.min(i,1),reasoning:`Matched ${n} action patterns`}:o===n&&o>0?{type:"analytical",confidence:.5,reasoning:`Mixed query (${o} analytical, ${n} 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 wn=class{analyzeDependencies(e){let t=[];for(let o=0;o<e.length;o++){let n=e[o],s=[],i=JSON.stringify(n.arguments).toLowerCase();for(let a=0;a<o;a++){let c=e[a];this.hasDependency(n,c,i)&&s.push(c.id)}t.push({toolCallId:n.id,dependsOn:s})}return t}hasDependency(e,t,o){if(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()))return!0;let s=["github.pr.files.list","github.pr.diff.get","github.contents.getText"];if(["github.pr.reviews.submit","github.pr.reviewComments.reply"].includes(e.name)&&s.includes(t.name)||e.name==="github.contents.getText"&&t.name==="github.pr.files.list"||e.name==="github.pr.reviewThreads.resolve"&&t.name==="github.pr.reviewThreads.list")return!0;let a=["slack.conversations.history","slack.conversations.replies"];return!!(["slack.chat.postMessage","slack.chat.postEphemeral"].includes(e.name)&&a.includes(t.name)||e.name==="slack.reactions.add"&&a.includes(t.name))}async executeWithDependencies(e,t,o=5){if(e.length===0)return new Map;let n=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;(n.find(g=>g.toolCallId===p.id)?.dependsOn.every(g=>i.has(g))??!0)&&a.push(p)}if(a.length===0){let p=e.filter(m=>!i.has(m.id));throw new Error(`Circular dependency detected in tool calls: ${p.map(m=>m.name).join(", ")}`)}let c=await this.executeBatchWithLimit(a,t,o);for(let{id:p,result:m}of c)s.set(p,m),i.add(p)}return s}async executeBatchWithLimit(e,t,o){let n=[];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);n.push(...c)}return n}shouldUseParallelExecution(e){return e.length>=2}};l();function Xe(r){for(let e=r.length-1;e>=0;e--){let t=r[e];if(t?.role!=="user")continue;let o=t?.content;return typeof o=="string"?o:Array.isArray(o)?o.map(n=>n?.type==="text"?n.text:"").filter(Boolean).join(`
400
+ `):""}return""}k();var ga=0;function ha(){return ga+=1,`${Date.now()}-${ga}`}function Tn(r,e){Ye("debug")&&(y(`[AIClient][${r}] Messages (${e.length}):`),e.forEach((t,o)=>{let n=O(t.content,300);y(`[AIClient][${r}] #${o} role=${t.role} content=${n}`)}))}function ya(r){let e=Xe(r).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 ba(r){let e=Xe(r).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(n=>n.test(e))&&!o.some(n=>n.test(e))}var xn=class extends bw{providers;defaultProvider;toolRegistry;toolsConfig;toolRouter;bm25Engine;queryClassifier;toolOrchestrator;activeMode=null;overrideSystemPrompt;disableBaseContext;toolResultMaxChars;hitlConfig;onToolConfirm;currentRound=0;conversationId;contextWindowConfig;contextWindowStateManager;providerModelCache=new Map;constructor(e){super(),this.providers=new Map(Object.entries(e.providers)),this.defaultProvider=e.defaultProvider,this.toolRegistry=e.toolRegistry,this.toolsConfig=e.toolsConfig||re,this.toolRouter=new It,this.bm25Engine=new Ot,this.queryClassifier=new ut,this.toolOrchestrator=new wn,this.overrideSystemPrompt=e.systemPrompt,this.disableBaseContext=e.disableBaseContext||!1;let t=this.toolsConfig.resultMaxChars??re.resultMaxChars??2e4;this.toolResultMaxChars=Number.isFinite(t)&&t>0?t:2e4,this.hitlConfig=e.hitlConfig,this.onToolConfirm=e.onToolConfirm,this.conversationId=e.conversationId,this.contextWindowConfig=e.contextWindowConfig,this.providerModelCache=new Map,this.contextWindowConfig&&this.contextWindowConfig.enabled!==!1&&(this.contextWindowStateManager=ca(this.contextWindowConfig)),this.toolRegistry&&this.bm25Engine.index(this.toolRegistry.getAll())}getConversationId(){return this.conversationId||"global"}async getModelInfo(e,t){let o=e.name||e.constructor.name,n=this.providerModelCache.get(o);if(!n){try{n=await e.getModels()}catch{n=[]}this.providerModelCache.set(o,n)}return n.find(s=>s.id===t||s.displayName===t)}async countRequestTokens(e,t,o){let n=await t.countTokens(e.messages,o);return typeof n=="number"&&Number.isFinite(n)?n:na(e.messages,o,t.getDisplayName().toLowerCase())}async pruneConversation(e,t,o){let n=this.contextWindowConfig?.retainSystemMessages??!0,s=e;for(let i=0;i<3;i+=1){let a=await this.countRequestTokens(s,t,s.model);if(a<=o)return s;let c=a-o,p=sa(s.messages,c,n),m=new Set(p.pruneInfo.removedMessages),f=s.messages.filter(b=>!m.has(b)),g={...s,messages:f};if(this.contextWindowStateManager&&this.contextWindowStateManager.recordPruneOperation(this.getConversationId(),p.tokensReclaimed),await this.countRequestTokens(g,t,g.model)<=o||f.length===s.messages.length)return g;s=g}return e}async pruneToMaxMessageHistory(e){let t=this.contextWindowConfig?.maxMessageHistoryLength;if(!t||e.messages.length<=t)return e;let o=this.contextWindowConfig?.retainSystemMessages??!0,n=[];e.messages.forEach((c,p)=>{o&&c.role==="system"||c.role!=="tool"&&n.push(p)});let s=Math.max(0,e.messages.length-t);if(s===0)return e;let i=new Set(n.slice(0,s)),a=e.messages.filter((c,p)=>!i.has(p));return{...e,messages:a}}async summarizeConversation(e,t){let o=e.messages,n=o.filter(v=>v.role==="system"),s=o.filter(v=>v.role!=="system");if(s.length<4)return e;let i=s.slice(-4),a=s.slice(0,-4);if(a.length<2)return e;let c=this.contextWindowConfig?.summarizerModel||e.model,p=aa(a,{model:c,maxSummaryTokens:500}),m=await t.generate({model:c,messages:p,max_tokens:500,temperature:0,response_format:"text"});if(!m.content)throw new Mt("Summarization provider returned no summary",this.getConversationId(),a.length,"invalid_response");let f=await this.countRequestTokens({...e,messages:a},t,c),g=la(m.content,a,f),w=ia(g);if(!w.valid)throw new Mt(`Summarization result is invalid: ${w.issues.join("; ")}`,this.getConversationId(),a.length,"invalid_quality",m.content);let b=Nr(g.summary,a.length),T=[...n,b,...i];return this.contextWindowStateManager&&this.contextWindowStateManager.recordSummarization(this.getConversationId(),g.tokensSaved),{...e,messages:T}}async enforceContextWindow(e,t){if(!this.contextWindowConfig||this.contextWindowConfig.enabled===!1)return e;let o=await this.pruneToMaxMessageHistory(e),n=await this.getModelInfo(t,o.model),s=n?.contextWindow??1e5,i=o.max_tokens??n?.maxOutputTokens??1024,a=this.contextWindowConfig.outputTokenBuffer??1.15,c=ra(i,a),p=Math.max(0,s-c),m=Math.floor(s*((this.contextWindowConfig.pruneThreshold??85)/100)),f=Math.min(p,m),g=await this.countRequestTokens(o,t,o.model);if(this.contextWindowStateManager&&(this.contextWindowStateManager.updateTokenCount(this.getConversationId(),g),g>f&&this.contextWindowStateManager.recordWarning(this.getConversationId())),g<=f)return o;let w=this.contextWindowConfig.strategy??"prune";if(w==="fail"&&g>p)throw new Dt("Context window exceeded by request messages",this.getConversationId(),g,p,w);if(w==="summarize")try{let T=await this.summarizeConversation(o,t);if(await this.countRequestTokens(T,t,T.model)<=p)return T;o=await this.pruneConversation(T,t,p)}catch{o=await this.pruneConversation(o,t,p)}else o=await this.pruneConversation(o,t,p);let b=await this.countRequestTokens(o,t,o.model);if(b>p&&w==="fail")throw new Dt("Context window exceeded after attempted cleanup",this.getConversationId(),b,p,w);return o}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 n=t.bypass??{};return!!(n.tools?.includes(e.name)||n.categories?.includes(e.category)||e.confirmation&&n.levels?.includes(e.confirmation.level))}registerProvider(e,t){this.providers.set(e,t)}getProvider(e){let t=e||this.defaultProvider;if(!t)throw new A("No provider specified and no default provider configured","NO_PROVIDER_CONFIGURED",400);let o=this.providers.get(t);if(!o)throw new A(`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 A(`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,P(`[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()),P(`[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 n=ha(),s=this.injectBaseAgentContext(e);s=this.injectOverrideSystemPrompt(s),s=this.injectModeSystemPrompt(s);let i=t||this.defaultProvider,a=await this.enrichRequestWithTools(s),c=a.request,p=a.requestToolMap;c=await this.enforceContextWindow(c,o);let m=process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||this.toolsConfig.toolChoicePolicy||"auto",f=(c.tools?.length||0)>0,g=c.tool_choice!=null,w=ya(c.messages),b=ba(c.messages);!g&&f&&(m==="required"||m==="required_for_actions"&&w)&&(c.tool_choice="required");let v=o?.constructor?.name||"UnknownProvider",C={...this.stripRequestTools(c),__toolpack_request_id:n};P(`[AIClient][${n}] generate() start provider=${i} class=${v} model=${c.model} messages=${c.messages.length} tools=${c.tools?.length||0} tool_choice=${c.tool_choice??"unset"} policy=${m} needsTools=${w} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),Tn(n,c.messages);let x=await o.generate(C);if(y(`[AIClient][${n}] generate() initial response finish_reason=${x.finish_reason??"unknown"} tool_calls=${x.tool_calls?.length||0} content_preview=${O(x.content||"",200)}`),this.toolsConfig.autoExecute&&(this.toolRegistry||p.size>0)){let R=Xe(c.messages),D=this.queryClassifier.classify(R),M=this.toolsConfig.maxToolRounds,S=c.maxToolRounds!==void 0?c.maxToolRounds:this.queryClassifier.getToolRoundsAdjustment(D,M);c.maxToolRounds!==void 0?y(`[AIClient][${n}] maxToolRounds overridden per-request: ${S} (classifier bypassed)`):S!==M?P(`[AIClient][${n}] Query classified as ${D.type} (confidence: ${D.confidence.toFixed(2)}), adjusted maxToolRounds: ${M} \u2192 ${S}`):y(`[AIClient][${n}] Query classified as ${D.type} (confidence: ${D.confidence.toFixed(2)}), keeping maxToolRounds: ${S}`);let $=0,_=[...c.messages];for(x.tool_calls&&x.tool_calls.length>0&&P(`[AIClient] Received ${x.tool_calls.length} tool call(s): ${x.tool_calls.map(L=>L.name).join(", ")}`);x.tool_calls&&x.tool_calls.length>0&&$<S;){$++,this.currentRound=$,P(`[AIClient][${n}] generate() tool round ${$}/${S} tool_calls=${x.tool_calls.length}`),_.push({role:"assistant",content:x.content||"",tool_calls:x.tool_calls.map(K=>({id:K.id,type:"function",function:{name:K.name,arguments:JSON.stringify(K.arguments)}}))});let L=this.toolOrchestrator.shouldUseParallelExecution(x.tool_calls),$e=3,Oe=x.tool_calls,ge=x.tool_calls.filter(K=>K.name==="web.fetch");if(ge.length>$e){P(`[AIClient][${n}] Limiting web.fetch calls from ${ge.length} \u2192 ${$e} to prevent context overflow`);let K=ge.slice(0,$e);Oe=[...x.tool_calls.filter(ye=>ye.name!=="web.fetch"),...K];let V=ge.slice($e);for(let ye of V)_.push({role:"tool",tool_call_id:ye.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let ae=5e4,X=0;if(L){P(`[AIClient][${n}] Using parallel execution for ${Oe.length} tools`);let K=await this.toolOrchestrator.executeWithDependencies(Oe,J=>this.executeTool(J,p),5);for(let J of Oe){let V=K.get(J.id),ye=typeof V=="string"?V:JSON.stringify(V),be=ae-X,oe;X+ye.length>ae?(I(`[AIClient][${n}] Tool output budget exceeded (${ae} chars)`),oe=this.budgetTruncate(ye,be)):typeof V=="string"&&V.length>this.toolResultMaxChars?oe=`${V.slice(0,this.toolResultMaxChars)}
401
+ [TRUNCATED tool result: ${V.length} chars]`:oe=ye;let Je=typeof oe=="string"?oe:JSON.stringify(oe);X+=Je.length,_.push({role:"tool",tool_call_id:J.id,content:oe})}y(`[AIClient][${n}] Round tool output size: ${X} chars (budget: ${ae})`)}else{P(`[AIClient][${n}] Using sequential execution for ${Oe.length} tools`);for(let K of Oe){let J=await this.executeTool(K,p),V=typeof J=="string"?J:JSON.stringify(J),ye=ae-X,be;X+V.length>ae?(I(`[AIClient][${n}] Tool output budget exceeded (${ae} chars)`),be=this.budgetTruncate(V,ye)):typeof J=="string"&&J.length>this.toolResultMaxChars?be=`${J.slice(0,this.toolResultMaxChars)}
402
+ [TRUNCATED tool result: ${J.length} chars]`:be=V;let oe=typeof be=="string"?be:JSON.stringify(be);X+=oe.length,_.push({role:"tool",tool_call_id:K.id,content:be})}y(`[AIClient][${n}] Round tool output size: ${X} chars (budget: ${ae})`)}let ct={...c,messages:_,__toolpack_request_id:n},he=this.stripRequestTools((await this.enrichRequestWithTools(ct)).request);he=await this.enforceContextWindow(he,o),he.tool_choice==="required"&&(he.tool_choice=b?"none":"auto",P(`[AIClient][${n}] generate() followup tool_choice override required->${he.tool_choice}`)),Ye("debug")&&(y(`[AIClient][${n}] generate() followup request messages=${_.length}`),Tn(n,_)),x=await o.generate(he),y(`[AIClient][${n}] generate() followup response finish_reason=${x.finish_reason??"unknown"} tool_calls=${x.tool_calls?.length||0} content_preview=${O(x.content||"",200)}`)}}return x}catch(n){throw this.wrapError(n)}}async*stream(e,t){let o=this.getProvider(t);try{let n=ha(),s=t||this.defaultProvider,i=this.injectBaseAgentContext(e);i=this.injectOverrideSystemPrompt(i),i=this.injectModeSystemPrompt(i);let a=await this.enrichRequestWithTools(i),c=a.request,p=a.requestToolMap;c=await this.enforceContextWindow(c,o);let m=process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||this.toolsConfig.toolChoicePolicy||"auto",f=(c.tools?.length||0)>0,g=c.tool_choice!=null,w=ya(c.messages),b=ba(c.messages);!g&&f&&(m==="required"||m==="required_for_actions"&&w)&&(c.tool_choice="required");let v=o?.constructor?.name||"UnknownProvider",C={...this.stripRequestTools(c),__toolpack_request_id:n};if(P(`[AIClient][${n}] stream() start provider=${s} class=${v} model=${c.model} messages=${c.messages.length} tools=${c.tools?.length||0} tool_choice=${c.tool_choice??"unset"} policy=${m} needsTools=${w} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),Tn(n,c.messages),!this.toolsConfig.autoExecute||!this.toolRegistry&&p.size===0){yield*o.stream(C);return}let x=[...c.messages],R=0,D=Xe(c.messages),M=this.queryClassifier.classify(D),S=this.toolsConfig.maxToolRounds,$=c.maxToolRounds!==void 0?c.maxToolRounds:this.queryClassifier.getToolRoundsAdjustment(M,S);for(c.maxToolRounds!==void 0?y(`[AIClient][${n}] stream() maxToolRounds overridden per-request: ${$} (classifier bypassed)`):$!==S&&P(`[AIClient][${n}] stream() Query classified as ${M.type} (confidence: ${M.confidence.toFixed(2)}), adjusted maxToolRounds: ${S} \u2192 ${$}`);R<=$;){if(e.signal?.aborted){P(`[AIClient][${n}] stream() aborted by signal`);return}let _="",L=[];R++,this.currentRound=R,P(`[AIClient][${n}] stream() round_start ${R}/${$}`);let $e=null,Oe={...c,messages:x},ge=this.stripRequestTools((await this.enrichRequestWithTools(Oe)).request);ge=await this.enforceContextWindow(ge,o),R>1&&ge.tool_choice==="required"&&(ge.tool_choice=b?"none":"auto",P(`[AIClient][${n}] stream() round_${R} tool_choice override required->${ge.tool_choice}`));for await(let E of o.stream(ge)){if(e.signal?.aborted){P(`[AIClient][${n}] stream() aborted by signal during chunk processing`);return}E.tool_calls&&E.tool_calls.length>0&&(L.push(...E.tool_calls),y(`[AIClient][${n}] stream() tool_calls_chunk count=${E.tool_calls.length} names=${E.tool_calls.map(ne=>ne.name).join(", ")}`),yield E),E.delta&&(_+=E.delta,yield E),E.finish_reason&&($e=E.finish_reason),E.finish_reason==="stop"&&(yield E)}if(y(`[AIClient][${n}] stream() round_end finish_reason=${$e??"unknown"} accumulated_len=${_.length} tool_calls_total=${L.length} content_preview=${O(_,200)}`),L.length===0)break;P(`[AIClient][${n}] stream() received ${L.length} tool call(s): ${L.map(E=>E.name).join(", ")}`),P(`[AIClient][${n}] stream() tool round ${R}/${$}`),x.push({role:"assistant",content:_||"",tool_calls:L.map(E=>({id:E.id,type:"function",function:{name:E.name,arguments:JSON.stringify(E.arguments)}}))});let ae=3,X=L,ct=L.filter(E=>E.name==="web.fetch");if(ct.length>ae){P(`[AIClient][${n}] Limiting web.fetch calls from ${ct.length} \u2192 ${ae} to prevent context overflow`);let E=ct.slice(0,ae);X=[...L.filter(Et=>Et.name!=="web.fetch"),...E];let Ee=ct.slice(ae);for(let Et of Ee)x.push({role:"tool",tool_call_id:Et.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let he=5e4,K=0,J=[],V=!1,ye=setInterval(()=>{V||J.push({delta:""})},500),be=Date.now(),oe,Je;try{if(X.length>=2)P(`[AIClient][${n}] stream() using parallel execution for ${X.length} tools`),Je=new Map,oe=await this.toolOrchestrator.executeWithDependencies(X,async E=>{let ne=Date.now(),Ee=await this.executeTool(E,p);return Je.set(E.id,Date.now()-ne),Ee},5);else{P(`[AIClient][${n}] stream() executing single tool sequentially`),Je=new Map,oe=new Map;for(let E of X){let ne=Date.now(),Ee=await this.executeTool(E,p);Je.set(E.id,Date.now()-ne),oe.set(E.id,Ee)}}}finally{V=!0,clearInterval(ye)}for(;J.length>0;)yield J.shift();await new Promise(E=>setTimeout(E,0)),y(`[AIClient][${n}] stream() tool batch completed in ${Date.now()-be}ms`);for(let E of X){let ne=oe.get(E.id),Ee=typeof ne=="string"?ne:JSON.stringify(ne),Et=he-K,Qb=Je.get(E.id)??0,Ve;K+Ee.length>he?(I(`[AIClient][${n}] Tool output budget exceeded (${he} chars)`),Ve=this.budgetTruncate(Ee,Et)):typeof ne=="string"&&ne.length>this.toolResultMaxChars?Ve=`${ne.slice(0,this.toolResultMaxChars)}
403
+ [TRUNCATED tool result: ${ne.length} chars]`:Ve=Ee;let Xi=typeof Ve=="string"?Ve:JSON.stringify(Ve);K+=Xi.length,x.push({role:"tool",tool_call_id:E.id,content:Ve}),yield{delta:"",tool_calls:[{...E,result:Xi,duration:Qb}]}}y(`[AIClient][${n}] Round tool output size: ${K} chars (budget: ${he})`),Ye("debug")&&(y(`[AIClient][${n}] stream() after_tools messages=${x.length}`),Tn(n,x))}}catch(n){throw this.wrapError(n)}}async embed(e,t){let o=this.getProvider(t);try{return await o.embed(e)}catch(n){throw this.wrapError(n)}}async enrichRequestWithTools(e){if(this.activeMode?.blockAllTools)return P(`[AIClient] Mode "${this.activeMode.displayName}" blocks all tools`),{request:e,requestToolMap:new Map};let t=this.buildRequestToolMap(e.requestTools),o=Array.from(t.values()).map(m=>this.requestToolToSchema(m)),n=t.size>0;if(!this.toolsConfig.enabled&&!n)return y("[AIClient] Tools disabled and no request-scoped tools"),{request:e,requestToolMap:t};let s=this.toolsConfig;if(this.activeMode?.toolSearch&&this.toolsConfig.toolSearch&&(s={...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=${s.toolSearch?.enabled}, alwaysLoadedTools=${s.toolSearch?.alwaysLoadedTools?.length||0}`)),e.tools&&e.tools.length>0){if(!s.toolSearch?.enabled||!this.toolRegistry){y(`[AIClient] Request already has ${e.tools.length} tools`);let b=this.mergeToolCallRequests(e.tools,this.schemasToToolCallRequests(o)),T=b===e.tools?e:{...e,tools:b};return{request:this.injectRequestToolGuidance(T,b),requestToolMap:t}}let m=await this.toolRouter.resolve(e.messages,this.toolRegistry,s);if(y(`[AIClient] Resolved ${m.length} tools to send: ${m.map(b=>b.name).join(", ")||"none"}`),this.activeMode&&m.length>0){let b=m.length;m=this.filterSchemasByMode(m,this.activeMode);let T=b-m.length;T>0&&P(`[AIClient] Mode "${this.activeMode.displayName}" filtered out ${T} tools`)}let f=new Set(e.tools.map(b=>b.function.name)),g=m.filter(b=>!f.has(b.name)).map(b=>({type:"function",function:{name:b.name,description:b.description,parameters:b.parameters}}));if(g.length===0){y(`[AIClient] Request already has ${e.tools.length} tools (no new discoveries)`);let b=this.mergeToolCallRequests(e.tools,this.schemasToToolCallRequests(o)),T=b===e.tools?e:{...e,tools:b};return{request:this.injectRequestToolGuidance(T,b),requestToolMap:t}}let w={...e,tools:this.mergeToolCallRequests([...e.tools,...g],this.schemasToToolCallRequests(o))};return s.toolSearch?.enabled&&this.toolRegistry&&(w=this.injectToolSearchPrompt(w)),{request:this.injectRequestToolGuidance(w,w.tools),requestToolMap:t}}if(!this.toolRegistry){y("[AIClient] Tool registry not configured, skipping tool resolution");let m=this.schemasToToolCallRequests(o),f=m.length>0?{...e,tools:m}:e;return{request:this.injectRequestToolGuidance(f,m),requestToolMap:t}}let i=this.toolRegistry,a=await this.toolRouter.resolve(e.messages,i,s);if(y(`[AIClient] Resolved ${a.length} tools to send: ${a.map(m=>m.name).join(", ")||"none"}`),this.activeMode&&a.length>0){let m=a.length;a=this.filterSchemasByMode(a,this.activeMode);let f=m-a.length;f>0&&P(`[AIClient] Mode "${this.activeMode.displayName}" filtered out ${f} tools`)}let c=this.schemasToToolCallRequests(this.mergeSchemas(a,o));if(c.length===0)return{request:e,requestToolMap:t};let p={...e,tools:c};return this.toolsConfig.toolSearch?.enabled&&i&&(p=this.injectToolSearchPrompt(p)),{request:this.injectRequestToolGuidance(p,c),requestToolMap:t}}buildRequestToolMap(e){let t=new Map;for(let o of e||[])t.set(o.name,o);return t}requestToolToSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category,cacheable:e.cacheable}}mergeSchemas(e,t){let o=new Map;for(let n of e)o.set(n.name,n);for(let n of t)o.set(n.name,n);return Array.from(o.values())}schemasToToolCallRequests(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}))}mergeToolCallRequests(e,t){if(t.length===0)return e;let o=new Map;for(let n of e)o.set(n.function.name,n);for(let n of t)o.set(n.function.name,n);return Array.from(o.values())}injectRequestToolGuidance(e,t){let o=new Set((t||e.tools||[]).map(c=>c.function.name));if(o.size===0)return e;let n="<!-- TOOLPACK_REQUEST_TOOL_GUIDANCE -->",s=[];if(o.has("knowledge_search")||o.has("knowledge_add")){let c=["Knowledge Base:"];o.has("knowledge_search")&&c.push("- Use `knowledge_search` when you need factual or domain-specific information that may already be stored."),o.has("knowledge_add")&&c.push("- Use `knowledge_add` when you encounter a durable fact, user preference, or decision that future conversations should know. Do not add confidential information, routine task outputs, or context that is specific to this conversation only."),s.push(c.join(`
404
+ `))}if(o.has("conversation_search")&&s.push("Conversation History:\n- Only recent messages may be present in context.\n- Use `conversation_search` to find relevant details from earlier in this conversation when needed."),s.length===0)return e;let i=`${n}
405
+ ${s.join(`
147
406
 
148
- If the message is general knowledge (math, definitions, explanations) or completely unrelated to recent tool context, answer NO.
149
- If it asks about the same context OR needs new external information, answer YES.
407
+ `)}`,a=e.messages.findIndex(c=>c.role==="system");if(a>=0){let c=e.messages.map((p,m)=>{if(m!==a)return p;let f=typeof p.content=="string"?p.content:"";return f.includes(n)?p:{...p,content:`${f}
150
408
 
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}
409
+ ${i}`.trim()}});return{...e,messages:c}}return{...e,messages:[{role:"system",content:i},...e.messages]}}stripRequestTools(e){let{requestTools:t,...o}=e;return o}filterSchemasByMode(e,t){return e.filter(o=>{if(t.blockedTools.includes(o.name)||t.blockedToolCategories.includes(o.category))return!1;if(bn(o.name)){let i=t.toolSearch?.enabled;if(i!==void 0?i:this.toolsConfig.toolSearch?.enabled??!1)return!0}let n=t.allowedTools.length>0,s=t.allowedToolCategories.length>0;if(n||s){let i=n&&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(n=>n.role==="system")){let n=e.messages.map(s=>{if(s.role==="system"){let i=typeof s.content=="string"?s.content:"";return{...s,content:`${i}
155
410
 
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}
411
+ ${t}`}}return s});return{...e,messages:n}}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(n=>n.role==="system")){let n=e.messages.map(s=>{if(s.role==="system"){let i=typeof s.content=="string"?s.content:"";return{...s,content:`${i}
157
412
 
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}
413
+ ${t}`}}return s});return{...e,messages:n}}else return{...e,messages:[{role:"system",content:t},...e.messages]}}injectBaseAgentContext(e){let t=!0,o=!0,n,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,n=this.activeMode.baseContext.custom);let i=n||pa({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
414
 
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=`
415
+ ${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??[],n="";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(`
416
+ `);i&&(n=`
162
417
 
163
418
  You have these tools always available:
164
419
  ${i}
@@ -166,9 +421,9 @@ ${i}
166
421
  Use these tools directly when appropriate for the task.`)}let s=`
167
422
  IMPORTANT: Tool Discovery Instructions
168
423
 
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}
424
+ 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.${n}
170
425
 
171
- ${Er(this.toolRegistry)}
426
+ ${Ir(this.toolRegistry)}
172
427
 
173
428
  When you need a tool:
174
429
  1. Check if it's in your current tool list
@@ -178,33 +433,67 @@ When you need a tool:
178
433
  NEVER guess or hallucinate tool names. ALWAYS use tool.search to discover tools you don't have.
179
434
  `.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
435
 
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
436
+ ${s}`}}return a});return{...e,messages:i}}else return{...e,messages:[{role:"system",content:s},...e.messages]}}async executeTool(e,t){let o=Date.now();this.emit("tool:started",{toolName:e.name,toolCallId:e.id,status:"started",args:e.arguments}),P(`[AIClient] Executing tool: ${e.name} with args: ${O(e.arguments,500)}`);let n=t.get(e.name),s=n?void 0:this.toolRegistry?.get(e.name);if(!n&&!this.toolRegistry){let a="No tool registry configured";return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:a,duration:Date.now()-o}),JSON.stringify({error:a})}if(bn(e.name)){let a=this.executeToolSearch(e.arguments),c=Date.now()-o;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof a=="string"?a.substring(0,200):JSON.stringify(a).substring(0,200),duration:c}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:a,duration:c,status:"success",timestamp:Date.now()}),a}let i=n||s;if(!i){I(`[AIClient] Tool '${e.name}' not found in registry`);let a=this.findSimilarToolName(e.name),c=a?`Tool '${e.name}' not found. Did you mean '${a}'? 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:c,duration:Date.now()-o}),JSON.stringify({error:c})}try{let a=e.arguments;if(s?.confirmation&&this.onToolConfirm&&!this.isBypassed(s)){this.emit("tool:confirmation_requested",{tool:s,args:a,level:s.confirmation.level,reason:s.confirmation.reason});let g=await this.onToolConfirm(s,a,{roundNumber:this.currentRound,conversationId:this.conversationId});if(this.emit("tool:confirmation_resolved",{tool:s,args:a,level:s.confirmation.level,reason:s.confirmation.reason,decision:g}),g.action==="deny"){let w=`[Execution denied by user${g.reason?": "+g.reason:""}]`,b=Date.now()-o;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:w,duration:b}),this.emit("tool:log",{id:e.id,name:e.name,arguments:a,result:w,duration:b,status:"success",timestamp:Date.now()}),w}g.action==="modify"&&(a=g.args)}let c={workspaceRoot:process.cwd(),config:this.toolsConfig?.additionalConfigurations??{},log:g=>P(`[Tool] ${g}`)},p=n?await n.execute(a):await i.execute(a,c),m=Date.now()-o;this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof p=="string"?p.substring(0,200):JSON.stringify(p).substring(0,200),duration:m}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:p,duration:m,status:"success",timestamp:Date.now()});let f=typeof p=="string"?p.length:JSON.stringify(p).length;return P(`[AIClient] Tool ${e.name} executed successfully in ${m}ms result_len=${f}`),Ye("debug")&&y(`[AIClient] Tool ${e.name} result_preview=${O(p,400)}`),typeof p=="string"?p:JSON.stringify(p)}catch(a){let c=Date.now()-o,p=a.message||"Tool execution failed";return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:p,duration:c}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:JSON.stringify({error:p}),duration:c,status:"error",timestamp:Date.now()}),pe(`[AIClient] Tool ${e.name} failed: ${O(p,300)}`),JSON.stringify({error:p})}}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 n=e.replace(/\./g,"_");if(t.some(c=>c.name===n))return n;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 n=0;n<=t.length;n++)o[n]=[n];for(let n=0;n<=e.length;n++)o[0][n]=n;for(let n=1;n<=t.length;n++)for(let s=1;s<=e.length;s++)t.charAt(n-1)===e.charAt(s-1)?o[n][s]=o[n-1][s-1]:o[n][s]=Math.min(o[n-1][s-1]+1,o[n][s-1]+1,o[n-1][s]+1);return o[t.length][e.length]}executeToolSearch(e){let{query:t,category:o}=e,n=this.toolsConfig.toolSearch?.searchResultLimit??5,s=typeof o=="string"&&o.length>0?o:void 0;if(this.activeMode&&!(this.filterSchemasByMode([At()],this.activeMode).length>0))return I("[AIClient] tool.search blocked by active mode"),JSON.stringify({query:t,found:0,tools:[],hint:"tool.search is not allowed in the current mode."});P(`[AIClient] Executing tool.search: query="${t}" category=${s||"all"} limit=${n}`);let i=this.activeMode?Math.max(n*4,n):n,a=this.bm25Engine.search(t,{limit:i,category:s});if(this.activeMode&&a.length>0){let p=this.filterSchemasByMode(a.map(w=>w.tool),this.activeMode),m=new Set(p.map(w=>w.name)),f=a.length;a=a.filter(w=>m.has(w.toolName));let g=f-a.length;g>0&&y(`[AIClient] tool.search filtered out ${g} disallowed results for mode "${this.activeMode.displayName}"`)}a.length>n&&(a=a.slice(0,n));let c=a.map(p=>p.toolName);return this.toolRouter.getDiscoveryCache().recordDiscovery(t,c),y(`[AIClient] tool.search found ${a.length} tools: ${c.join(", ")||"none"}`),JSON.stringify({query:t,found:a.length,tools:a.map(p=>({name:p.tool.name,displayName:p.tool.displayName,description:p.tool.description,category:p.tool.category,parameters:p.tool.parameters,relevanceScore:Math.round(p.score*100)/100})),hint:a.length>0?`Found ${a.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 A?e:new W(e.message||"Unknown provider error","UNKNOWN_PROVIDER_ERROR",500,e)}budgetTruncate(e,t){let o=`
437
+ [Output truncated \u2014 round budget reached. Call the tool again with a narrower query to retrieve more.]`,s=t-o.length;return s>=100?e.slice(0,s)+o:"[Tool output omitted \u2014 round budget exhausted. Call the tool again with a narrower query.]"}};l();l();import Sa from"@anthropic-ai/sdk";l();ce();var Z=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()}`)}async countTokens(e,t){return null}};ce();k();var vn=class extends Z{client;constructor(e,t){super(),this.client=new Sa({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(n=>this.sanitizeToolName(n.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),n=o.system,s=o.userMessages,i={model:e.model,messages:s,system:n,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: ${O(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"}`),Y(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=${O(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),n={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?(n.tools=e.tools.map(m=>({name:this.sanitizeToolName(m.function.name),description:m.function.description,input_schema:m.function.parameters})),e.tool_choice==="required"?n.tool_choice={type:"any"}:e.tool_choice==="none"?delete n.tools:n.tool_choice={type:"auto"},y(`[Anthropic][${t}] Sending ${n.tools?.length||0} tools with tool_choice: ${n.tool_choice?.type||"unset"}`),n.tools&&n.tools.length>0&&y(`[Anthropic][${t}] First tool: ${O(n.tools[0],800)}`)):y(`[Anthropic][${t}] NO TOOLS in request`),y(`[Anthropic][${t}] Stream request: model=${n.model}, messages=${n.messages.length}, tools=${n.tools?.length||0}, tool_choice=${n.tool_choice?.type??"unset"}`),Y(t,"Anthropic",n.messages);let s=await this.client.messages.create(n,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"&&(Ae(`[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,n=[],{normalizeImagePart:s}=await Promise.resolve().then(()=>(gt(),qt));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(`
438
+ `);a&&(o=a)}}else if(i.role==="tool"&&i.tool_call_id)n.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(`
439
+ `);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});n.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)),n.push({role:i.role==="user"?"user":"assistant",content:a})}return{system:o,userMessages:n}}mapFinishReason(e){return e==="end_turn"?"stop":e==="max_tokens"?"length":e==="stop_sequence"?"stop":e}handleError(e){if(e instanceof Sa.APIError){let t=e.message;return e.status===401?new we(t,e):e.status===429?new Pe(t,void 0,e):e.status&&e.status>=400&&e.status<500?new j(t,e):new W(t,"ANTHROPIC_ERROR",e.status||500,e)}return new W("Unknown Anthropic error","UNKNOWN",500,e)}};l();import{VertexAI as vw}from"@google-cloud/vertexai";ce();k();var Cn=class extends Z{vertexAI;location;constructor(e={}){super(),this.name="vertexai";let t=e.projectId??process.env.TOOLPACK_VERTEXAI_PROJECT??process.env.VERTEX_AI_PROJECT??process.env.GOOGLE_CLOUD_PROJECT;if(!t)throw new we("Vertex AI requires a GCP project ID. Pass projectId in config or set TOOLPACK_VERTEXAI_PROJECT / VERTEX_AI_PROJECT / GOOGLE_CLOUD_PROJECT.");this.location=e.location??process.env.TOOLPACK_VERTEXAI_LOCATION??process.env.VERTEX_AI_LOCATION??"us-central1",this.vertexAI=new vw({project:t,location:this.location,googleAuthOptions:e.googleAuthOptions})}getDisplayName(){return"Google Vertex AI"}async getModels(){return[{id:"gemini-2.5-pro-preview-05-06",displayName:"Gemini 2.5 Pro Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-2.5-flash-preview-04-17",displayName:"Gemini 2.5 Flash Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-2.0-flash-001",displayName:"Gemini 2.0 Flash",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:1048576,maxOutputTokens:8192},{id:"gemini-1.5-pro-002",displayName:"Gemini 1.5 Pro",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:2097152,maxOutputTokens:8192},{id:"gemini-1.5-flash-002",displayName:"Gemini 1.5 Flash",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:1048576,maxOutputTokens:8192}]}async generate(e){try{let t=e.__toolpack_request_id||`vtx-${Date.now()}`;y(`[VertexAI][${t}] generate() model=${e.model} messages=${e.messages.length} tools=${e.tools?.length??0}`),Y(t,"VertexAI",e.messages);let o=this.buildModel(e),{history:n,lastUserMessage:s}=this.formatHistory(e.messages),c=(await o.startChat({history:n}).sendMessage(s)).response,{content:p,toolCalls:m}=this.parseResponse(c,e.tools);return y(`[VertexAI][${t}] Response finish_reason=${m.length>0?"tool_calls":"stop"} tool_calls=${m.length} content_preview=${O(p,200)}`),{content:p||null,usage:{prompt_tokens:c.usageMetadata?.promptTokenCount??0,completion_tokens:c.usageMetadata?.candidatesTokenCount??0,total_tokens:c.usageMetadata?.totalTokenCount??0},finish_reason:m.length>0?"tool_calls":"stop",tool_calls:m.length>0?m:void 0,raw:c}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`vtx-str-${Date.now()}`;y(`[VertexAI][${t}] stream() model=${e.model} messages=${e.messages.length} tools=${e.tools?.length??0}`),Y(t,"VertexAI",e.messages);let o=this.buildModel(e),{history:n,lastUserMessage:s}=this.formatHistory(e.messages),a=await o.startChat({history:n}).sendMessageStream(s);for await(let c of a.stream)for(let p of c.candidates??[])for(let m of p.content?.parts??[])if(m.functionCall){let f=m.functionCall;y(`[VertexAI][${t}] stream tool_call name=${f.name}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:`vtx_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,name:this.restoreToolName(f.name,e.tools),arguments:f.args??{}}]}}else m.text&&(yield{delta:m.text})}catch(t){throw this.handleError(t)}}async embed(e){throw new j("Vertex AI embeddings are not supported by this adapter. Use the Gemini adapter (gemini provider) with text-embedding-004 instead.")}buildModel(e){let t={model:e.model,systemInstruction:this.extractSystemInstruction(e.messages),generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:e.response_format==="json_object"?"application/json":"text/plain"}};return e.tools&&e.tools.length>0&&(t.tools=[{functionDeclarations:e.tools.map(o=>({name:this.sanitizeToolName(o.function.name),description:o.function.description,parameters:this.sanitizeSchema(o.function.parameters)}))}]),this.vertexAI.getGenerativeModel(t)}formatHistory(e){let t=e.filter(i=>i.role!=="system");if(t.length===0)return{history:[],lastUserMessage:""};let o=t.slice(0,-1),n=t[t.length-1];return{history:o.map(i=>{if(i.role==="tool"&&i.tool_call_id)return{role:"function",parts:[{functionResponse:{name:this.sanitizeToolName(i.name??i.tool_call_id),response:{name:this.sanitizeToolName(i.name??i.tool_call_id),content:typeof i.content=="string"?i.content:JSON.stringify(i.content)}}}]};if(i.role==="assistant"&&i.tool_calls&&i.tool_calls.length>0){let a=[];typeof i.content=="string"&&i.content&&a.push({text:i.content});for(let c of i.tool_calls)a.push({functionCall:{name:this.sanitizeToolName(c.function.name),args:typeof c.function.arguments=="string"?JSON.parse(c.function.arguments||"{}"):c.function.arguments}});return{role:"model",parts:a}}return{role:i.role==="user"?"user":"model",parts:this.contentToParts(i.content)}}),lastUserMessage:this.contentToParts(n.content)}}contentToParts(e){return typeof e=="string"?[{text:e}]:e?e.map(t=>t.type==="text"?{text:t.text}:t.type==="image_data"?{inlineData:{mimeType:t.mimeType??"image/jpeg",data:t.data}}:null).filter(t=>t!==null):[]}parseResponse(e,t){let o=[],n="";for(let s of e.candidates??[])for(let i of s.content?.parts??[])if(i.text&&(n+=i.text),i.functionCall){let a=i.functionCall;o.push({id:`vtx_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,name:this.restoreToolName(a.name,t),arguments:a.args??{}})}return{content:n,toolCalls:o}}extractSystemInstruction(e){let t=e.filter(o=>o.role==="system");if(t.length!==0)return t.map(o=>typeof o.content=="string"?o.content:"").join(`
440
+ `)}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(n=>this.sanitizeToolName(n.function.name)===e)?.function.name??e.replace(/_/g,".")}sanitizeSchema(e){if(!e||typeof e!="object")return e;let t={};for(let[o,n]of Object.entries(e))["additionalProperties","exclusiveMinimum","exclusiveMaximum","$schema","$id","definitions","$defs"].includes(o)||(t[o]=typeof n=="object"&&n!==null?Array.isArray(n)?n.map(s=>this.sanitizeSchema(s)):this.sanitizeSchema(n):n);return t}handleError(e){let t=e?.message??String(e);return e?.status===429||t.includes("RESOURCE_EXHAUSTED")?new Pe(t,void 0,e):e?.status===401||e?.status===403||t.includes("UNAUTHENTICATED")||t.includes("PERMISSION_DENIED")?new we(t,e):e?.status>=400&&e?.status<500?new j(t,e):new W(t||"Vertex AI Error","VERTEXAI_ERROR",e?.status??500,e)}};l();import{GoogleGenerativeAI as Cw}from"@google/generative-ai";ce();k();var kn=class extends Z{genAI;constructor(e){super(),this.genAI=new Cw(e)}supportsFileUpload(){return!0}sanitizeSchema(e){if(!e||typeof e!="object")return e;let t={};for(let[o,n]of Object.entries(e))o==="additionalProperties"||o==="exclusiveMinimum"||o==="exclusiveMaximum"||o==="$schema"||o==="$id"||o==="definitions"||o==="$defs"||(typeof n=="object"&&n!==null?Array.isArray(n)?t[o]=n.map(s=>this.sanitizeSchema(s)):t[o]=this.sanitizeSchema(n):t[o]=n);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 n=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
441
  Content-Type: application/json\r
185
442
  \r
186
443
  ${m}\r
187
444
  `),Buffer.from(`--${p}\r
188
445
  Content-Type: ${i}\r
189
446
  \r
190
- `),r,Buffer.from(`\r
447
+ `),n,Buffer.from(`\r
191
448
  --${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 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(`
449
+ `)]),g=await fetch(c,{method:"POST",headers:{"Content-Type":`multipart/related; boundary=${p}`},body:f});if(!g.ok){let b=await g.text();throw new Error(`Gemini file upload failed: ${g.status} ${b}`)}let w=await g.json();return{id:w.file?.name||w.name,url:w.file?.uri||w.uri}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{let t=this.genAI.apiKey,o=`https://generativelanguage.googleapis.com/v1beta/${e}?key=${t}`,n=await fetch(o,{method:"DELETE"});if(!n.ok){let s=await n.text();throw new Error(`Gemini file deletion failed: ${n.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(n=>this.sanitizeToolName(n.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,o={model:e.model,systemInstruction:this.extractSystemInstruction(e.messages)};e.tools&&e.tools.length>0?(o.tools=[{functionDeclarations:e.tools.map(g=>({name:this.sanitizeToolName(g.function.name),description:g.function.description,parameters:this.sanitizeSchema(g.function.parameters)}))}],y(`[Gemini][${t}] Sending ${e.tools.length} tools`),e.tools.length>0&&y(`[Gemini][${t}] First tool: ${O(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}`),Y(t,"Gemini",e.messages);let n=this.genAI.getGenerativeModel(o),{history:s,lastUserMessage:i}=await this.formatHistory(e.messages,e.mediaOptions),p=await(await n.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 g of p.candidates||[])for(let w of g.content?.parts||[])if(w.text&&(f+=w.text),w.functionCall){let b=w.functionCall;m.push({id:`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(b.name,e.tools),arguments:b.args||{}})}return y(`[Gemini][${t}] Response finish_reason=${m.length>0?"tool_calls":"stop"} tool_calls=${m.length} content_preview=${O(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: ${O(e.tools[0],800)}`),Y(o,"Gemini",e.messages);let n=this.genAI.getGenerativeModel(t),{history:s,lastUserMessage:i}=await this.formatHistory(e.messages,e.mediaOptions),c=await n.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 n=>(await t.embedContent(n)).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(n=>n.text).join(`
193
450
  `)).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],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}]
451
+ `)}async formatHistory(e,t={}){let o=e.filter(m=>m.role!=="system");if(o.length===0)return{history:[],lastUserMessage:""};let n=o[o.length-1],s=o.slice(0,o.length-1),{normalizeImagePart:i}=await Promise.resolve().then(()=>(gt(),qt)),a=async m=>typeof m=="string"?[{text:m}]:m===null?[]:(await Promise.all(m.map(async g=>{if(g.type==="text")return{text:g.text};if(g.type==="image_data"||g.type==="image_file"||g.type==="image_url")try{let{data:w,mimeType:b}=await i(g);return{inlineData:{mimeType:b,data:w}}}catch{return g.type==="image_url"?{text:`[Image: ${g.image_url.url}]`}:{text:"[Unresolvable Image]"}}return null}))).filter(Boolean),c=await Promise.all(s.map(async m=>{if(m.role==="tool"&&m.tool_call_id)return{role:"function",parts:[{functionResponse:{name:this.sanitizeToolName(m.name||m.tool_call_id),response:{name:this.sanitizeToolName(m.name||m.tool_call_id),content:typeof m.content=="string"?m.content:JSON.stringify(m.content)}}}]};if(m.role==="assistant"&&m.tool_calls&&m.tool_calls.length>0){let f=[];if(typeof m.content=="string"&&m.content)f.push({text:m.content});else if(Array.isArray(m.content)){let g=m.content.filter(w=>typeof w=="object"&&w.type==="text").map(w=>w.text).join(`
452
+ `);g&&f.push({text:g})}for(let g of m.tool_calls)f.push({functionCall:{name:this.sanitizeToolName(g.function.name),args:typeof g.function.arguments=="string"?JSON.parse(g.function.arguments||"{}"):g.function.arguments}});return{role:"model",parts:f}}return{role:m.role==="user"?"user":"model",parts:await a(m.content)}})),p=typeof n.content=="string"?n.content:await a(n.content);return{history:c,lastUserMessage:p}}handleError(e){return e.status===429?new Pe(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 W(e.message||"Gemini Error","GEMINI_ERROR",e.status||500,e)}};l();ce();import*as Ie from"fs";import*as Fr from"path";var Ra="toolpack.config.json",Pn=new Map;async function _a(r){for(;Pn.has(r);)await Pn.get(r);let e,t=new Promise(o=>{e=o});return Pn.set(r,t),()=>{Pn.delete(r),e()}}function Ze(r){if(r&&Ie.existsSync(r))return r;let e=Fr.join(process.cwd(),Ra);return Ie.existsSync(e)?e:null}function Ut(r){if(!r)return null;try{let e=Ie.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}var Wt=null;function qr(r){if(Wt)return Wt;let e=r||Ze();return Wt=Ut(e)||{},Wt}function Wr(){Wt=null}function kw(r){return(qr(r).ollama?.models||[]).map(o=>({type:`ollama-${o.model.replace(/[:.]/g,"-")}`,model:o.model,label:o.label||o.model}))}function Sn(r){return qr(r).ollama?.baseUrl||"http://localhost:11434"}async function Pw(r){let{type:e,value:t,configPath:o}=r,n=o||Ze();n||(n=Fr.join(process.cwd(),Ra));let s=await _a(n);try{let i=Ut(n)||{};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{Ie.writeFileSync(n,JSON.stringify(i,null,4),"utf-8")}catch(a){throw new A(`Failed to write bypass rule to config file: ${a instanceof Error?a.message:String(a)}`,"CONFIG_WRITE_ERROR")}Wr()}finally{s()}}async function Sw(r){let{type:e,value:t,configPath:o}=r,n=o||Ze();if(!n)return;let s=await _a(n);try{let i=Ut(n);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{Ie.writeFileSync(n,JSON.stringify(i,null,4),"utf-8")}catch(a){throw new A(`Failed to remove bypass rule from config file: ${a instanceof Error?a.message:String(a)}`,"CONFIG_WRITE_ERROR")}Wr()}finally{s()}}l();l();ce();k();l();import $a from"http";function Se(r,e,t,o,n=12e4){return new Promise((s,i)=>{let a=new URL(e,r),c={hostname:a.hostname,port:a.port,path:a.pathname,method:t,headers:{"Content-Type":"application/json"},timeout:n},p=$a.request(c,m=>{let f=[];m.on("data",g=>f.push(g)),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 Ur(r,e,t,o=12e4,n){let s,i=!1;return n&&n.addEventListener("abort",()=>{i=!0,s&&s.destroy()},{once:!0}),{stream:async function*(){let c=new URL(e,r),p={hostname:c.hostname,port:c.port,path:c.pathname,method:"POST",headers:{"Content-Type":"application/json"},timeout:o},m=await new Promise((g,w)=>{s=$a.request(p,g),s.on("error",w),s.on("timeout",()=>{s.destroy(),w(new Error("Stream request timed out"))}),s.write(JSON.stringify(t)),s.end()});if(m.statusCode&&m.statusCode>=400){let g="";for await(let w of m)g+=w.toString();throw new Error(`Ollama HTTP ${m.statusCode}: ${g}`)}let f="";for await(let g of m){if(i)break;let w=g.toString();if(f+=w,f.includes('"error"'))try{let T=JSON.parse(f.trim());if(T.error)throw new Error(`Ollama: ${T.error}`)}catch(T){if(T.message.startsWith("Ollama:"))throw T}let b=f.split(`
453
+ `);f=b.pop()||"";for(let T of b)T.trim()&&(yield T)}f.trim()&&!i&&(yield f.trim())}(),abort:()=>{i=!0,s&&s.destroy()}}}var et=class extends Z{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(n=>n.name.split(":")[0].toLowerCase()===t||n.name.toLowerCase()===this.config.model.toLowerCase()))throw new j(`Model "${this.config.model}" is not pulled in Ollama. Run: ollama pull ${this.config.model}
454
+ Available models: ${e.map(n=>n.name).join(", ")||"(none)"}`);return e}async listModels(){try{let e=await Se(this.baseUrl,"/api/tags","GET",void 0,5e3);if(e.status!==200)throw new W(`Ollama returned status ${e.status}`,"OLLAMA_ERROR",e.status);return JSON.parse(e.body).models||[]}catch(e){throw e instanceof W?e:new Qe(`Cannot connect to Ollama at ${this.baseUrl}. Is Ollama running? (ollama serve)`,e)}}async isAvailable(){try{return await Se(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(),n=o.split(":")[0];return t.some(s=>s.name.split(":")[0].toLowerCase()===n||s.name.toLowerCase()===o)}catch{return!1}}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(n=>this.sanitizeToolName(n.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))),n=e.model||this.config.model,s={model:n,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: ${O(e.tools[0],800)}`),y(`[Ollama][${t}] NO TOOLS in request`)),y(`[Ollama][${t}] generate() request: model=${n}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),Y(t,"Ollama",e.messages);try{let i=await Se(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=${O(p.content,200)}`),p}catch(i){throw i instanceof W?i:new Qe(`Failed to generate with Ollama model "${n}": ${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))),n=e.model||this.config.model,s={model:n,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: ${O(e.tools[0],800)}`),y(`[Ollama][${t}] NO TOOLS in request`)),y(`[Ollama][${t}] Stream request: model=${n}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),Y(t,"Ollama",e.messages);let{stream:i}=Ur(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){Ae(`[Ollama][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"};return}}catch{}}catch(a){throw new Qe(`Stream failed for Ollama model "${n}": ${a.message}`,a)}}async embed(e){let t=e.__toolpack_request_id||`emb-${Date.now()}`,o=typeof e.input=="string"?[e.input]:e.input,n=e.model||this.config.model;y(`[Ollama][${t}] Embedding request: model=${n}, inputs=${o.length}`);try{let s=await Se(this.baseUrl,"/api/embed","POST",{model:n,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 W?s:new Qe(`Embedding failed for Ollama model "${n}": ${s.message}`,s)}}async disconnect(){}async toOllamaMessage(e,t={}){let o="",n=[],{normalizeImagePart:s}=await Promise.resolve().then(()=>(gt(),qt));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+`
455
+ `;else if(a.type==="image_url"||a.type==="image_data"||a.type==="image_file")try{let{data:c}=await s(a);n.push(c)}catch{a.type==="image_url"?o+=`[Image: ${a.image_url.url}]
199
456
  `:o+=`[Unresolvable Image]
200
- `}o=o.trim()}let i={role:e.role,content:o};return r.length>0&&(i.images=r),e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0?i.tool_calls=e.tool_calls.map(a=>({function:{name:this.sanitizeToolName(a.function.name),arguments:typeof a.function.arguments=="string"?JSON.parse(a.function.arguments||"{}"):a.function.arguments}})):e.role==="tool"&&(i.content=o||JSON.stringify(e.content),e.name&&(i.tool_name=this.sanitizeToolName(e.name))),i}handleHttpError(e,t){let o=`Ollama error (HTTP ${e})`;try{let r=JSON.parse(t);r.error&&(o=`Ollama: ${r.error}`)}catch{}return e===404?new 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()}`:""}
457
+ `}o=o.trim()}let i={role:e.role,content:o};return n.length>0&&(i.images=n),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 n=JSON.parse(t);n.error&&(o=`Ollama: ${n.error}`)}catch{}return e===404?new j(`Model not found: ${o}`):new W(o,"OLLAMA_ERROR",e)}};l();var Gt=class extends Z{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 Se(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:n,...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 et({model:e,baseUrl:this.baseUrl,timeout:this.timeout}),this.adapterCache.set(e,t)),t}async buildModelInfo(e){let t=!1,o=!1,n=!1;try{let a=await Se(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)),n=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))),n||(n=["nomic-embed","mxbai-embed","all-minilm","bge-","snowflake-arctic-embed"].some(c=>s.includes(c)));let i={toolCalling:t,vision:o,embeddings:n};return this.capabilityCache.set(e.name,i),{id:e.name,displayName:e.name,capabilities:{chat:!0,streaming:!0,toolCalling:t,embeddings:n,vision:o}}}async probeToolSupport(e){try{let t=await Se(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 Gr=[{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 Rw(){return Gr[0].model}function _w(r){let e=r.toLowerCase();return Gr.some(t=>t.model.toLowerCase()===e||t.model.split(":")[0].toLowerCase()===e.split(":")[0].toLowerCase())}function $w(){return[...Gr]}l();import Ea from"openai";ce();k();var ht=class extends Z{client;constructor(e,t){super(),this.client=new Ea({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()}`,n={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&&(n.tools=e.tools.map(f=>{let g=this.sanitizeToolName(f.function.name);return s.set(g,f.function.name),{type:"function",function:{name:g,description:f.function.description,parameters:f.function.parameters}}}),n.tool_choice=e.tool_choice||"auto",y(`[OpenAI][${t}] Sending ${n.tools.length} tools with tool_choice: ${n.tool_choice}`),y(`[OpenAI][${t}] First tool: ${O(n.tools[0],800)}`)),y(`[OpenAI][${t}] Request params: ${O({model:n.model,messages_count:n.messages.length,has_tools:!!n.tools,tools_count:n.tools?.length,tool_choice:n.tool_choice},800)}`),Y(t,"OpenAI",n.messages);let i=await this.client.chat.completions.create(n,e.signal?{signal:e.signal}:void 0);Ae(`[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: ${O(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()}`,n={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?(n.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}}}),n.tool_choice=e.tool_choice||"auto",y(`[OpenAI][${t}] Sending ${n.tools.length} tools with tool_choice: ${n.tool_choice}`),y(`[OpenAI][${t}] First tool: ${O(n.tools[0],800)}`)):y(`[OpenAI][${t}] NO TOOLS in request`),y(`[OpenAI][${t}] Stream request: model=${n.model}, messages=${n.messages.length}, tools=${n.tools?.length||0}, tool_choice=${n.tool_choice??"unset"}`),Y(t,"OpenAI",n.messages);let i=await this.client.chat.completions.create(n,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&&Ae(`[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 g=a.get(f);m.id&&(g.id=m.id),m.function?.name&&(g.name=m.function.name),m.function?.arguments&&(g.args+=m.function.arguments),Ae(`[OpenAI][${t}] tool_call_delta idx=${f} id=${m.id||g.id||""} name=${m.function?.name||g.name||""} args_delta=${O(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(n=>n.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(()=>(gt(),qt)),n=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:n.filter(Boolean)}}handleError(e){if(e instanceof Ea.APIError){let t=e.message;return e.status===401?new we(t,e):e.status===429?new Pe(t,void 0,e):e.status&&e.status>=400&&e.status<500?new j(t,e):new W(t,e.code||"OPENAI_ERROR",e.status||500,e)}return new W("Unknown error","UNKNOWN",500,e)}};l();var Da="https://openrouter.ai/api/v1",Rn=class extends ht{name="openrouter";_apiKey;constructor(e,t={}){super(e,Da),this._apiKey=e}getDisplayName(){return"OpenRouter"}supportsFileUpload(){return!1}async generate(e){return super.generate(this.normalizeRequest(e))}async*stream(e){yield*super.stream(this.normalizeRequest(e))}normalizeRequest(e){return e.tool_choice==="none"?{...e,tools:void 0,tool_choice:void 0}:e}async getModels(){try{let e=await fetch(`${Da}/models`,{headers:{Authorization:`Bearer ${this._apiKey}`}});return e.ok?(await e.json()).data.map(o=>this.mapModel(o)):[]}catch{return[]}}mapModel(e){let o=(e.architecture?.modality??"text->text").includes("image");return{id:e.id,displayName:e.name??e.id,capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:o},contextWindow:e.context_length??void 0,maxOutputTokens:e.top_provider?.max_completion_tokens??void 0,inputModalities:o?["text","image"]:["text"],outputModalities:["text"],reasoningTier:null,costTier:this.deriveCostTier(e.pricing)}}deriveCostTier(e){if(!e?.prompt)return"unknown";let t=parseFloat(e.prompt)*1e6;return t<1?"low":t<5?"medium":t<20?"high":"premium"}};gt();l();Lt();l();Lt();var un=class{tools=new Map;projects=new Map;config=re;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,n=[];for(let s of[...e,...t])o.has(s.name)||(o.add(s.name),n.push(s));return n}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 n of Object.keys(t))try{await import(n)}catch{o.push(n)}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(()=>(ls(),zc)),{execToolsProject:t}=await Promise.resolve().then(()=>(gs(),Mp)),{systemToolsProject:o}=await Promise.resolve().then(()=>(vs(),um)),{httpToolsProject:n}=await Promise.resolve().then(()=>(_s(),Qm)),{githubToolsProject:s}=await Promise.resolve().then(()=>(Fs(),ou)),{webToolsProject:i}=await Promise.resolve().then(()=>(Ys(),Pf)),{codingToolsProject:a}=await Promise.resolve().then(()=>(hi(),fh)),{gitToolsProject:c}=await Promise.resolve().then(()=>(yi(),Kh)),{diffToolsProject:p}=await Promise.resolve().then(()=>(bi(),ly)),{dbToolsProject:m}=await Promise.resolve().then(()=>(Ti(),Ay)),{cloudToolsProject:f}=await Promise.resolve().then(()=>(xi(),Hy)),{slackToolsProject:g}=await Promise.resolve().then(()=>(_i(),Eb));await this.loadProjects([e,t,o,n,s,i,a,c,p,m,f,g])}};Us();l();k();function Ov(r){if(!r.key||!/^[a-z0-9-]+$/.test(r.key))throw new Error(`Invalid tool project key: "${r.key}". Must be non-empty, lowercase, and contain no spaces (use hyphens).`);if(!r.name.trim())throw new Error("Tool project name cannot be empty.");if(!r.tools||r.tools.length===0)throw new Error("Tool project must contain at least one tool.");for(let t of r.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!==r.category&&I(`[Toolpack] Tool "${t.name}" has category "${t.category}" which does not match project category "${r.category}".`)}let e=r.tools.map(t=>t.name);return{manifest:{key:r.key,name:r.name,displayName:r.displayName,version:r.version,description:r.description,author:r.author,repository:r.repository,category:r.category,tools:e},dependencies:r.dependencies,tools:r.tools}}ls();gs();vs();_s();Fs();Ys();hi();yi();bi();Ti();xi();l();l();k();import{execFileSync as Nv}from"child_process";function N(r,e){if(r.includes("\0")||r.includes(`
458
+ `)||r.includes("\r"))throw new Error(`Invalid ${e}: contains disallowed characters.`);return r}function Av(r){let e=typeof r.stdout=="string"?r.stdout:"",t=typeof r.stderr=="string"?r.stderr:"",o=r.status??"unknown",n=t.split(/\r?\n/).filter(i=>i.trim().length>0),s=n.find(i=>i.toLowerCase().startsWith("error:"))||n[0]||r.message||"";return`kubectl failed (exit code ${o})${s?`: ${s.trim()}`:""}
202
459
  STDOUT:
203
460
  ${e}
204
461
  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=`
462
+ ${t}`}function me(r,e,t=3e4){r.forEach((o,n)=>N(o,`kubectl argument #${n}`)),y(`[k8s-tools] execute: kubectl ${r.join(" ")}`);try{return Nv("kubectl",r,{input:e,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],timeout:t})||"(kubectl completed with no output)"}catch(o){return Av(o)}}function Iv(r){if(!r)return 3e5;let e=r.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 ke="kubernetes";function Db(r){if(!r)return;if(typeof r=="string")return r;let e=Object.entries(r).filter(([,t])=>t!==void 0&&t!=="");if(e.length)return e.map(([t,o])=>`${N(t,"label key")}=${N(o,"label value")}`).join(",")}var $i={name:"k8s.list_pods",displayName:"Kubernetes List Pods",description:"List pods in the current or a specific Kubernetes namespace.",category:ke,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 r=>{let e=["get","pods"],t=r.output;t?e.push("-o",t):e.push("-o","wide"),r.allNamespaces&&e.push("--all-namespaces"),r.namespace&&!r.allNamespaces&&e.push("-n",N(r.namespace,"namespace"));let o=Db(r.labelSelector)??r.labels;return o&&e.push("-l",N(o,"labels")),me(e)}},Ei={name:"k8s.describe",displayName:"Kubernetes Describe Resource",description:"Describe a Kubernetes resource or resource instance.",category:ke,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 r=>{let t=["describe",N(r.resource,"resource")];return r.name&&t.push(N(r.name,"name")),r.namespace&&t.push("-n",N(r.namespace,"namespace")),me(t)}},Di={name:"k8s.get_logs",displayName:"Kubernetes Get Pod Logs",description:"Fetch logs from a Kubernetes pod, optionally from a specific container.",category:ke,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 r=>{let e=["logs",N(r.podName,"podName")];return r.container&&e.push("-c",N(r.container,"container")),r.namespace&&e.push("-n",N(r.namespace,"namespace")),typeof r.tailLines=="number"&&e.push("--tail",`${r.tailLines}`),r.since&&e.push("--since",N(r.since,"since")),me(e)}},Mi={name:"k8s.apply_manifest",displayName:"Kubernetes Apply Manifest",description:"Apply a Kubernetes manifest from a file path or inline YAML content.",category:ke,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 r=>{let e=r.path,t=r.manifest,o=["apply"];if(r.dryRun&&o.push("--dry-run=client"),o.push("-f"),e)return o.push(N(e,"path")),r.namespace&&o.push("-n",N(r.namespace,"namespace")),me(o);if(!t)throw new Error("Either path or manifest is required to apply a Kubernetes manifest.");return r.namespace&&o.push("-n",N(r.namespace,"namespace")),o.push("-"),me(o,t)}},Oi={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:ke,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 r=>{let e=r.path,t=r.resource,o=r.name;if(e){let s=["delete"];return r.dryRun&&s.push("--dry-run=client"),s.push("-f",N(e,"path")),r.namespace&&s.push("-n",N(r.namespace,"namespace")),me(s)}if(!t||!o)throw new Error("resource and name are required unless a manifest path is provided.");let n=["delete",N(t,"resource"),N(o,"name")];return r.namespace&&n.push("-n",N(r.namespace,"namespace")),r.force&&n.push("--force","--grace-period=0"),r.dryRun&&n.push("--dry-run=client"),me(n)}},Ni={name:"k8s.list_services",displayName:"Kubernetes List Services",description:"List services in the current or a specific Kubernetes namespace.",category:ke,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 r=>{let e=["get","services"],t=r.output;return e.push("-o",t||"wide"),r.allNamespaces&&e.push("--all-namespaces"),r.namespace&&!r.allNamespaces&&e.push("-n",N(r.namespace,"namespace")),me(e)}},Ai={name:"k8s.list_deployments",displayName:"Kubernetes List Deployments",description:"List deployments in the current or a specific Kubernetes namespace.",category:ke,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 r=>{let e=["get","deployments"],t=r.output;e.push("-o",t||"wide"),r.allNamespaces&&e.push("--all-namespaces"),r.namespace&&!r.allNamespaces&&e.push("-n",N(r.namespace,"namespace"));let o=Db(r.labelSelector)??r.labels;return o&&e.push("-l",N(o,"labels")),me(e)}},Ii={name:"k8s.get_config_map",displayName:"Kubernetes Get ConfigMap",description:"Retrieve a ConfigMap from a Kubernetes namespace.",category:ke,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 r=>{let e=["get","configmap",N(r.name,"name"),"-o",r.output||"yaml"];return r.namespace&&e.push("-n",N(r.namespace,"namespace")),me(e)}},Li={name:"k8s.switch_context",displayName:"Kubernetes Switch Context",description:"Switch the active kubectl context to a different Kubernetes cluster or namespace configuration.",category:ke,parameters:{type:"object",properties:{context:{type:"string",description:"The kubeconfig context to switch to."}},required:["context"]},execute:async r=>me(["config","use-context",N(r.context,"context")])},ji={name:"k8s.get_namespaces",displayName:"Kubernetes Get Namespaces",description:"List namespaces in the current Kubernetes context.",category:ke,parameters:{type:"object",properties:{output:{type:"string",description:"Output format for the namespace list.",enum:["wide","name","json","yaml"],default:"wide"}},required:[]},execute:async r=>me(["get","namespaces","-o",r.output||"wide"])},Fi={name:"k8s.wait_for_deployment",displayName:"Kubernetes Wait For Deployment",description:"Wait for a Kubernetes deployment to complete its rollout.",category:ke,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 r=>{let e=r.timeout,t=["rollout","status",`deployment/${N(r.name,"name")}`,"--timeout",e||"300s"];return r.namespace&&t.push("-n",N(r.namespace,"namespace")),me(t,void 0,Iv(e))}};var Lv={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:[$i,Ei,Di,Mi,Oi,Ni,Ai,Ii,Li,ji,Fi]};_i();l();l();k();import{spawn as jv}from"child_process";import{EventEmitter as Fv}from"events";var br=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},fn=class extends Fv{constructor(t){super();this.config=t;this.defaultTimeoutMs=t.requestTimeoutMs??3e4,this.autoReconnect=t.autoReconnect??!1,this.maxReconnectAttempts=t.maxReconnectAttempts??3,this.reconnectDelayMs=t.reconnectDelayMs??1e3}config;process=null;messageQueue=new Map;nextId=1;buffer="";_connected=!1;_shuttingDown=!1;_reconnectAttempts=0;defaultTimeoutMs;autoReconnect;maxReconnectAttempts;reconnectDelayMs;get connected(){return this._connected&&this.process!==null}async initializeServer(){await this.request("initialize",{client:"toolpack-sdk"})}async connect(){if(this._shuttingDown)throw new Me("Client is shutting down");if(this.buffer="",this.process=jv(this.config.command,this.config.args||[],{env:{...process.env,...this.config.env},stdio:["pipe","pipe","pipe"]}),!this.process.stdout||!this.process.stdin)throw new Me("Failed to spawn MCP server: stdout/stdin unavailable");this.process.stdout.on("data",t=>{this.handleData(t)}),this.process.stderr&&this.process.stderr.on("data",t=>{I(`[MCP server stderr] ${t.toString().trim()}`)}),this.process.on("error",t=>{this._connected=!1,this.emit("error",t)}),this.process.on("exit",t=>{let o=this._connected;this._connected=!1,this.process=null,this.rejectAllPending(new Me(`MCP server exited with code ${t}`,t)),this.emit("close",t),o&&!this._shuttingDown&&this.autoReconnect&&this.attemptReconnect()}),this._reconnectAttempts=0,await this.initializeServer(),this._connected=!0}async attemptReconnect(){if(this._reconnectAttempts>=this.maxReconnectAttempts){this.emit("reconnect_failed",this._reconnectAttempts);return}this._reconnectAttempts++;let t=this._reconnectAttempts;if(this.emit("reconnecting",{attempt:t,max:this.maxReconnectAttempts}),await new Promise(o=>setTimeout(o,this.reconnectDelayMs*t)),!this._shuttingDown)try{await this.connect(),this.emit("reconnected",{attempt:t})}catch(o){this.emit("reconnect_error",{attempt:t,error:o})}}handleData(t){this.buffer+=t.toString();let o;for(;(o=this.buffer.indexOf(`
463
+ `))!==-1;){let n=this.buffer.slice(0,o).trim();if(this.buffer=this.buffer.slice(o+1),n)try{let s=JSON.parse(n);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={},n){return this.request("tools/call",{name:t,arguments:o},n)}async readResource(t,o){return this.request("resources/read",{uri:t},o)}async request(t,o,n){if(!this.process||!this.process.stdin)throw new Me("Client not connected");let s=this.nextId++,i=n??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 br(t,i)))},i)),this.messageQueue.set(s,{resolve:c,reject:p,timer:m});try{this.process.stdin.write(JSON.stringify(a)+`
464
+ `)}catch(f){m&&clearTimeout(m),this.messageQueue.delete(s),p(f)}})}async disconnect(t=3e3){if(this._shuttingDown=!0,this.rejectAllPending(new Me("Client disconnecting")),!this.process){this._shuttingDown=!1;return}let o=this.process;return new Promise(n=>{let s=!1,i=()=>{s||(s=!0,this.process=null,this._connected=!1,this._shuttingDown=!1,n())};o.once("exit",i),o.kill("SIGTERM"),setTimeout(()=>{if(!s){try{o.kill("SIGKILL")}catch{}i()}},t)})}kill(){this._shuttingDown=!0,this.rejectAllPending(new Me("Client killed")),this.process&&(this.process.kill("SIGKILL"),this.process=null),this._connected=!1,this._shuttingDown=!1}rejectAllPending(t){for(let[o,n]of this.messageQueue)n.timer&&clearTimeout(n.timer),n.reject(t);this.messageQueue.clear()}};k();var wr=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:n,...s}=e;P(`[MCP] Connecting to server: ${o||t}`);try{let i=new fn({...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 pe(`[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){I(`[MCP] Server ${e} not found`);return}P(`[MCP] Disconnecting from ${e}`);for(let[o,n]of this.toolOwners)n===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,n){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{P(`[MCP] Executing ${e.name} on ${t}`);let a=await n.callTool(e.name,i);return JSON.stringify(a)}catch(a){throw pe(`[MCP] Tool execution failed: ${a}`),a}}}}setupClientEvents(e,t){e.on("error",o=>{pe(`[MCP] ${t} error: ${o}`)}),e.on("close",o=>{I(`[MCP] ${t} closed with code ${o}`)}),e.on("reconnecting",({attempt:o,max:n})=>{P(`[MCP] ${t} reconnecting (${o}/${n})`)}),e.on("reconnected",({attempt:o})=>{P(`[MCP] ${t} reconnected after ${o} attempts`),this.refreshServerTools(t).catch(n=>{pe(`[MCP] ${t} tool refresh failed after reconnect: ${n}`)})}),e.on("reconnect_failed",o=>{pe(`[MCP] ${t} failed to reconnect after ${o} attempts`)}),e.on("notification",o=>{P(`[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||[];P(`[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 qi(r){let e=new wr(r);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(n=>n.name)},tools:t,mcpManager:e}}async function Wi(r){"mcpManager"in r&&await r.mcpManager.disconnectAll()}l();import*as H from"fs/promises";import*as ee from"path";function Gi(r){let e={},t=r.match(/^---\n([\s\S]*?)\n---/);if(!t||!t[1])return e;for(let o of t[1].split(`
465
+ `)){let n=o.indexOf(":");if(n===-1)continue;let s=o.substring(0,n).trim(),i=o.substring(n+1).trim();e[s]=i}return e}function Bi(r){let e=r.match(/\[(.*)\]/);return!e||!e[1]?[]:e[1].split(",").map(t=>t.trim().replace(/"/g,"")).filter(Boolean)}function Ui(r){let e=[],t=r.match(/## Triggers\n\n([\s\S]*?)(?=\n## |$)/);if(!t||!t[1])return e;for(let o of t[1].split(`
466
+ `).filter(n=>n.startsWith("- "))){let n=o.match(/^- "(.*)"/);n&&n[1]&&e.push(n[1])}return e}function at(r,e){let t=r.match(new RegExp(`## ${e}\\n\\n([\\s\\S]*?)(?=\\n## |$)`));return t&&t[1]?t[1].trim():""}async function Mb(r,e){async function t(o){let n;try{n=await H.readdir(o)}catch{return null}for(let s of n){let i=ee.join(o,s),a;try{a=await H.stat(i)}catch{continue}if(a.isDirectory()){let c=await t(i);if(c)return c}else if(a.isFile()&&s===`${e}.skill.md`)return i}return null}return t(r)}async function qv(r){let e=[];async function t(o){let n;try{n=await H.readdir(o)}catch{return}for(let s of n){let i=ee.join(o,s),a;try{a=await H.stat(i)}catch{continue}a.isDirectory()?await t(i):a.isFile()&&s.endsWith(".skill.md")&&e.push(i)}}return await t(r),e}function Wv(r){let{name:e,title:t,description:o,triggers:n,instructions:s,examples:i,tags:a}=r,c=new Date().toISOString(),p=a&&a.length>0?a.map(f=>`"${f}"`).join(", "):"",m=["---",`name: ${e}`,`title: ${t}`,"version: 1.0.0",`updated: ${c}`,`tags: [${p}]`,"---","","## Description","",o,"","## Triggers","",n.map(f=>`- "${f}"`).join(`
467
+ `),"","## Instructions","",s,""];return i&&m.push("## Examples","",i,""),m.join(`
468
+ `)}function Uv(r){return{name:"skill.create",displayName:"Create Skill",description:"Create a new .skill.md file in the skill library.",category:"skills",parameters:{type:"object",properties:{name:{type:"string",description:'Skill name in kebab-case (e.g. "code-review"). Used as the filename.'},title:{type:"string",description:"Human-readable title for the skill (max 100 chars)."},description:{type:"string",description:"Short description for BM25 search indexing (max 300 chars)."},triggers:{type:"array",items:{type:"string"},description:"List of trigger phrases that activate this skill (min 1, max 10)."},instructions:{type:"string",description:"Behavioral instructions injected into context when the skill activates (max 2000 chars)."},examples:{type:"string",description:"Optional examples section (max 3000 chars, never auto-injected)."},tags:{type:"array",items:{type:"string"},description:"Optional tags for filtering and search (max 10)."},subfolder:{type:"string",description:'Optional subfolder within the skills directory (e.g. "coding").'}},required:["name","title","description","triggers","instructions"]},async execute(e){let t=e.name,o=e.title,n=e.description,s=e.triggers??[],i=e.instructions,a=e.examples,c=e.tags??[],p=e.subfolder;if(!/^[a-z][a-z0-9-]*$/.test(t))return JSON.stringify({error:"invalid_name",message:"Skill name must be kebab-case (lowercase letters, numbers, hyphens, starting with a letter)"},null,2);let m=p?ee.join(r,p):r;await H.mkdir(m,{recursive:!0});let f=ee.join(m,`${t}.skill.md`);try{return await H.access(f),JSON.stringify({error:"skill_exists",message:`Skill "${t}" already exists at ${f}. Use skill.update to modify it.`},null,2)}catch{}let g=Wv({name:t,title:o,description:n,triggers:s,instructions:i,examples:a,tags:c});return await H.writeFile(f,g,"utf-8"),JSON.stringify({success:!0,skill:t,path:f,message:`Skill "${o}" created successfully`},null,2)}}}function Gv(r){return{name:"skill.read",displayName:"Read Skill",description:"Read a skill file by name. Optionally read only a specific section.",category:"skills",parameters:{type:"object",properties:{name:{type:"string",description:"Skill name (without the .skill.md extension)."},section:{type:"string",enum:["all","metadata","description","triggers","instructions","examples"],description:"Which section to return (default: all).",default:"all"}},required:["name"]},async execute(e){let t=e.name,o=e.section||"all",n=await Mb(r,t);if(!n)return JSON.stringify({error:"skill_not_found",message:`Skill "${t}" not found. Use skill.list to see available skills.`},null,2);let s=(await H.readFile(n,"utf-8")).replace(/\r\n/g,`
469
+ `),i=Gi(s),a={name:i.name||t,title:i.title||t,version:i.version,tags:i.tags?Bi(i.tags):[],updated:i.updated,path:n};return JSON.stringify(o==="metadata"?{skill:t,metadata:a}:o==="description"?{skill:t,description:at(s,"Description")}:o==="triggers"?{skill:t,triggers:Ui(s)}:o==="instructions"?{skill:t,instructions:at(s,"Instructions")}:o==="examples"?{skill:t,examples:at(s,"Examples")}:{skill:t,path:n,metadata:a,description:at(s,"Description"),triggers:Ui(s),instructions:at(s,"Instructions"),examples:at(s,"Examples")||void 0},null,2)}}}function Bv(r){return{name:"skill.update",displayName:"Update Skill",description:"Update fields of an existing skill. Only provided fields are changed.",category:"skills",parameters:{type:"object",properties:{name:{type:"string",description:"Skill name to update."},title:{type:"string",description:"New title (optional)."},description:{type:"string",description:"New description replacing the existing one (optional)."},triggers:{type:"array",items:{type:"string"},description:"New triggers list replacing the existing one (optional)."},instructions:{type:"string",description:"New instructions replacing the existing ones (optional)."},addExamples:{type:"string",description:"Additional examples text to append to the Examples section (optional)."},addTags:{type:"array",items:{type:"string"},description:"Tags to add to the existing tags (optional)."}},required:["name"]},async execute(e){let t=e.name,o=e.title,n=e.description,s=e.triggers,i=e.instructions,a=e.addExamples,c=e.addTags,p=await Mb(r,t);if(!p)return JSON.stringify({error:"skill_not_found",message:`Skill "${t}" not found. Use skill.create to create it first.`},null,2);let m=(await H.readFile(p,"utf-8")).replace(/\r\n/g,`
470
+ `),f=Gi(m),g=f.tags?Bi(f.tags):[],w=f.title||t,b=f.version||"1.0.0",T=o??w,v=c?[...new Set([...g,...c])]:g,C=new Date().toISOString();if(n!==void 0&&(m=m.replace(/## Description\n\n[\s\S]*?(?=\n## )/,`## Description
471
+
472
+ ${n}
473
+
474
+ `)),s!==void 0){let R=s.map(D=>`- "${D}"`).join(`
475
+ `);m=m.replace(/## Triggers\n\n[\s\S]*?(?=\n## )/,`## Triggers
476
+
477
+ ${R}
478
+
479
+ `)}if(i!==void 0&&(m=m.replace(/## Instructions\n\n[\s\S]*?(?=\n## |$)/,`## Instructions
480
+
481
+ ${i}
482
+
483
+ `)),a){let R=m.match(/## Examples\n\n([\s\S]*?)(?=\n## |$)/);if(R){let D=R[1]??"",M=D.trim()?`
484
+
485
+ `:"";m=m.replace(/## Examples\n\n[\s\S]*?(?=\n## |$)/,`## Examples
486
+
487
+ ${D}${M}${a}
488
+
489
+ `)}else m=m.trimEnd()+`
490
+
491
+ ## Examples
492
+
493
+ ${a}
494
+ `}m=m.replace(/^---\n[\s\S]*?\n---/,["---",`name: ${t}`,`title: ${T}`,`version: ${b}`,`updated: ${C}`,`tags: [${v.map(R=>`"${R}"`).join(", ")}]`,"---"].join(`
495
+ `)),await H.writeFile(p,m,"utf-8");let x=[];return o&&x.push("title"),n!==void 0&&x.push("description"),s!==void 0&&x.push("triggers"),i!==void 0&&x.push("instructions"),a&&x.push("examples (appended)"),c&&x.push(`tags (+${c.length})`),JSON.stringify({success:!0,skill:t,path:p,updated:x,message:`Skill "${t}" updated successfully`},null,2)}}}function zv(r){return{name:"skill.list",displayName:"List Skills",description:"List all skills in the skill library, optionally filtered by tag.",category:"skills",parameters:{type:"object",properties:{tag:{type:"string",description:"Filter skills by tag (optional)."},verbose:{type:"boolean",description:"Include description and triggers in the output (default: false).",default:!1}},required:[]},async execute(e){let t=e.tag,o=e.verbose??!1;try{await H.access(r)}catch{return JSON.stringify({skills:[],count:0,message:"No skills directory found. Use skill.create to create your first skill."},null,2)}let n=await qv(r);if(n.length===0)return JSON.stringify({skills:[],count:0,message:"No skills found. Use skill.create to create your first skill."},null,2);let s=[];for(let i of n){let a=(await H.readFile(i,"utf-8")).replace(/\r\n/g,`
496
+ `),c=Gi(a),p=c.name||ee.basename(i,".skill.md"),m=c.title||p,f=c.tags?Bi(c.tags):[];if(t&&!f.includes(t))continue;let g=ee.dirname(ee.relative(r,i)),w=g==="."?void 0:g.split(ee.sep)[0];o?s.push({name:p,title:m,tags:f,category:w,description:at(a,"Description")||void 0,triggers:Ui(a)}):s.push({name:p,title:m,tags:f,category:w})}return JSON.stringify({skills:s,count:s.length,filtered:t?`by tag: ${t}`:null},null,2)}}}function Hv(r){let e=ee.resolve(r?.dir??".toolpack/skills"),t=[Uv(e),Gv(e),Bv(e),zv(e)];return{manifest:{key:"skill",name:"skill-tools",displayName:"Skill Management",version:"1.0.0",description:"Tools for creating, reading, updating, and listing agent skill files.",tools:["skill.create","skill.read","skill.update","skill.list"],category:"skills"},tools:t}}l();l();l();l();var zi=`
208
497
  You are a planning assistant. Given a user request, create a detailed step-by-step plan.
209
498
 
210
499
  Rules:
@@ -230,26 +519,7 @@ Rules:
230
519
  }
231
520
  ]
232
521
  }
233
- `,Ts=`
234
- You are executing step {stepNumber} of a plan.
235
-
236
- Plan summary: {planSummary}
237
-
238
- Current step: {stepDescription}
239
-
240
- Previous steps completed:
241
- {previousStepsResults}
242
-
243
- Execute this step now. Use the available tools as needed to accomplish this specific step.
244
- Make reasonable assumptions if any details are ambiguous - do NOT ask the user for clarification or additional input.
245
- Produce concrete results based on the information available.
246
- If you cannot complete this step, explain why.
247
-
248
- IMPORTANT: Your response should be written as if you are directly answering the user.
249
- Do NOT mention steps, plans, workflow details, or internal process in your response.
250
- Do NOT say things like "Step 1 is complete" or "proceeding to the next step".
251
- Just provide the actual answer or result naturally.
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=`
522
+ `,hU={name:"Direct",planning:{enabled:!1},progress:{enabled:!0}},Ob={name:"Agent",planning:{enabled:!0,planningPrompt:zi},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},Kv=`
253
523
  Create a step-by-step plan for this coding task.
254
524
 
255
525
  Rules:
@@ -272,72 +542,32 @@ JSON Schema:
272
542
  }
273
543
  ]
274
544
  }
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=`
290
- Based on the result of the previous step, do we need to add any new steps to our plan before continuing?
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
-
298
- If additional steps are truly required, respond with a JSON object containing the new steps.
299
- If not necessary or if the plan is sufficient, respond with {"steps": []}.
300
-
301
- JSON Schema:
302
- {
303
- "steps": [
304
- { "description": "What to do", "expectedTools": [] }
305
- ]
306
- }
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=`
545
+ `,Nb={name:"Coding",planning:{enabled:!0,planningPrompt:Kv},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},Ab={name:"Chat",planning:{enabled:!1},progress:{enabled:!1}};var Ib={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:Ob,toolSearch:{alwaysLoadedTools:["fs.read_file","fs.write_file","fs.list_dir","web.search","web.fetch","skill.search","skill.read"]}},Lb={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:Ab,toolSearch:{alwaysLoadedTools:["web.search","web.fetch","fs.read_file","fs.list_dir"]}},jb={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:Nb,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"]}},Tr=[Ib,jb,Lb],St="chat";var gn=class{modes=new Map;orderedNames=[];constructor(){for(let e of Tr)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 n of t)if(e[n]!==void 0&&!Array.isArray(e[n]))throw new Error(`ModeConfig.${n} 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(St);if(!e)throw new Error(`Default mode "${St}" not found in registry`);return e}getNext(e){let t=this.orderedNames.indexOf(e),o=t===-1?0:(t+1)%this.orderedNames.length,n=this.orderedNames[o],s=this.modes.get(n);if(!s)throw new Error(`Mode "${n}" not found in registry`);return s}get size(){return this.modes.size}remove(e){if(Tr.some(n=>n.name===e))return!1;let o=this.modes.delete(e);return o&&(this.orderedNames=this.orderedNames.filter(n=>n!==e)),o}};l();function Jv(r){return{name:r.name,displayName:r.displayName,description:r.description||r.displayName,systemPrompt:r.systemPrompt,allowedToolCategories:r.allowedToolCategories||[],blockedToolCategories:r.blockedToolCategories||[],allowedTools:r.allowedTools||[],blockedTools:r.blockedTools||[],blockAllTools:r.blockAllTools||!1,baseContext:r.baseContext,workflow:r.workflow}}l();var Hi={planning:{enabled:!1},progress:{enabled:!0}};l();k();var Vv=zi,hn=class{client;config;constructor(e,t){this.client=e,this.config=t}async createPlan(e,t){let o=this.config?.planningPrompt||Vv,n=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="${n}..."`);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 P(`[Planner] createPlan() succeeded plan.id=${m.id} steps=${m.steps.length}`),m}catch(p){return I(`[Planner] createPlan() failed, using fallback: ${p.message}`),this.createFallbackPlan(e)}}parsePlan(e,t,o){try{let n=JSON.parse(e);if(!n.summary||!Array.isArray(n.steps))throw new Error("Invalid plan structure: missing summary or steps array");let s=this.config?.maxSteps??20,i=n.steps.slice(0,s);n.steps.length>s&&I(`[Planner] parsePlan() truncated ${n.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:n.summary,steps:a,status:"draft",createdAt:new Date,planningResponse:o}}catch(n){return I(`[Planner] parsePlan() failed: ${n.message} \u2014 using fallback`),this.createFallbackPlan(t)}}createFallbackPlan(e){I("[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();import{EventEmitter as Qv}from"events";k();var xr=class extends Qv{client;config;planner;queryClassifier;pendingApprovals=new Map;constructor(e,t,o){super(),this.client=e,this.config=t,this.queryClassifier=o||new ut,this.planner=new hn(e,t.planning)}getConfig(){return this.config}setConfig(e){this.config=e,this.planner=new hn(this.client,e.planning)}shouldRouteSimpleQuery(e){if(!this.config.complexityRouting?.enabled)return!1;let t=this.config.complexityRouting.strategy??"single-step";if(t==="disabled")return!1;let o=Xe(e.messages);if(!o)return!1;let n=this.queryClassifier.classify(o),s=this.config.complexityRouting.confidenceThreshold??.6,i=!1;switch(n.type){case"action":i=!1;break;case"conversational":i=!0;break;case"analytical":i=n.confidence>=s;break}return y(`[Workflow] shouldRouteSimpleQuery() type=${n.type} confidence=${n.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;if(y(`[Workflow] execute() planningEnabled=${o} provider=${t??"default"}`),!o)return y("[Workflow] execute() mode=direct"),this.executeDirect(e,t);y("[Workflow] execute() mode=plan-direct \u2014 creating plan");let n=await this.createPlan(e,t);if(this.emit("workflow:plan_created",n),this.config.planning?.requireApproval){P(`[Workflow] Plan "${n.id}" requires approval \u2014 waiting`),this.emitProgress(n,"awaiting_approval","Waiting for plan approval");let s=await this.waitForApproval(n.id);if(this.emit("workflow:plan_decision",n,s),!s)return P(`[Workflow] Plan "${n.id}" rejected by user`),n.status="cancelled",this.emitProgress(n,"failed","Plan rejected by user"),{success:!1,plan:n,error:"Plan rejected by user",metrics:{totalDuration:0,stepsCompleted:0,stepsFailed:0,retriesUsed:0}};P(`[Workflow] Plan "${n.id}" approved`)}return n.status="approved",this.executePlanDirect(n,e,t)}async executeDirect(e,t){let o=Date.now(),n=this.createDummyPlan(e);y(`[Workflow] executeDirect() provider=${t??"default"}`);try{this.emitProgress(n,"executing","Direct execution");let s=await this.client.generate(e,t);n.status="completed",n.completedAt=new Date,n.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:n,output:s.content||void 0,response:s,metrics:{totalDuration:Date.now()-o,stepsCompleted:1,stepsFailed:0,retriesUsed:0}};return this.emit("workflow:completed",n,a),this.emitProgress(n,"completed","Done"),a}catch(s){n.status="failed",n.completedAt=new Date,n.steps[0].status="failed",I(`[Workflow] executeDirect() failed: ${s.message}`);let i={success:!1,plan:n,error:s.message,metrics:{totalDuration:Date.now()-o,stepsCompleted:0,stepsFailed:1,retriesUsed:0}};return this.emit("workflow:failed",n,s),this.emitProgress(n,"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 n=await this.planner.createPlan(e,t);return P(`[Workflow] createPlan() completed plan.id=${n.id} steps=${n.steps.length}`),n}async executePlanDirect(e,t,o){let n=Date.now();e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e),this.emitProgress(e,"executing","Executing plan",10),y(`[Workflow] executePlanDirect() plan.id=${e.id} steps=${e.steps.length} provider=${o??"default"}`);let s=`
310
546
  You have created the following plan to fulfill the request:
311
547
  Summary: ${e.summary}
312
548
 
313
549
  Steps:
314
- ${e.steps.map(a=>`${a.number}. ${a.description}`).join(`
550
+ ${e.steps.map(c=>`${c.number}. ${c.description}`).join(`
315
551
  `)}
316
552
 
317
553
  Execute this plan now.
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.
319
- Summary: ${e.summary}
320
- Steps:
321
- `+e.steps.map(t=>`[${t.status.toUpperCase()}] ${t.description}`).join(`
322
- `)}extractFinalOutput(e){let t=e.steps[e.steps.length-1];if(t&&/synthesize|summarize|consolidate|combine/i.test(t.description)&&e.steps.length>1)for(let r=e.steps.length-1;r>=0;r--){let s=e.steps[r];if(s.status==="completed"&&s.result?.output)return s.result.output}else{let r=[];for(let s of e.steps)s.status==="completed"&&s.result?.output&&r.push(s.result.output);if(r.length>0)return r.join(`
554
+ `.trim(),i=this.injectPlanContext(t.messages,s),a={...t,messages:i};try{let c=await this.client.generate(a,o);e.steps.forEach(m=>{m.status="completed",m.result={success:!0,output:c.content||"",response:c}}),e.status="completed",e.completedAt=new Date,e.metrics=this.computeMetrics(e,n,0),y(`[Workflow] executePlanDirect() completed plan.id=${e.id} duration=${Date.now()-n}ms`);let p={success:!0,plan:e,output:c.content||void 0,response:c,metrics:e.metrics};return this.emit("workflow:completed",e,p),this.emitProgress(e,"completed","Done"),p}catch(c){e.status="failed",e.completedAt=new Date,I(`[Workflow] executePlanDirect() failed plan.id=${e.id}: ${c.message}`);let p={success:!1,plan:e,error:c.message,metrics:this.computeMetrics(e,n,0)};return this.emit("workflow:failed",e,c),this.emitProgress(e,"failed","Execution failed"),p}}emitProgress(e,t,o,n){if(!this.config.progress?.enabled)return;let s=e.steps.length,i=e.steps.filter(p=>p.status==="completed"||p.status==="skipped").length,a=n??(s>0?Math.round(i/s*100):0),c={planId:e.id,currentStep:Math.min(i+1,s),totalSteps:s,percentage:a,currentStepDescription:o??e.steps[i]?.description??"Done",status:t??"executing"};this.emit("workflow:progress",c)}computeMetrics(e,t,o){return{totalDuration:Date.now()-t,stepsCompleted:e.steps.filter(n=>n.status==="completed").length,stepsFailed:e.steps.filter(n=>n.status==="failed").length,retriesUsed:o}}createDummyPlan(e){let t=e.messages.filter(o=>o.role==="user").map(o=>typeof o.content=="string"?o.content:"[Object]").join(`
555
+ `);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}}injectPlanContext(e,t){if(e[0]?.role==="system"){let n=e[0],s=typeof n.content=="string"?n.content:n.content.map(i=>i.text??"").join("");return[{...n,content:`${t}
556
+
557
+ ---
323
558
 
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:`
559
+ ${s}`},...e.slice(1)]}return[{role:"system",content:t},...e]}async*stream(e,t){if(this.shouldRouteSimpleQuery(e)){y("[Workflow] stream() complexity-routed \u2192 direct"),yield*this.streamDirect(e,t);return}let o=this.config.planning?.enabled;if(y(`[Workflow] stream() planningEnabled=${o} provider=${t??"default"}`),!o){y("[Workflow] stream() mode=direct"),yield*this.streamDirect(e,t);return}yield{delta:"",workflowStep:{number:0,description:"Creating plan..."}};let n=await this.planner.createPlan(e,t);if(this.emit("workflow:plan_created",n),this.config.planning?.requireApproval){this.emitProgress(n,"awaiting_approval","Waiting for plan approval"),yield{delta:`
325
560
 
326
561
  **Plan Created:**
327
- ${s.summary}
562
+ ${n.summary}
328
563
 
329
564
  Steps:
330
- ${s.steps.map(a=>`${a.number}. ${a.description}`).join(`
565
+ ${n.steps.map(i=>`${i.number}. ${i.description}`).join(`
331
566
  `)}
332
567
 
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:`
334
-
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:`
568
+ *Waiting for approval...*`,workflowStep:{number:0,description:"Awaiting approval"}};let s=await this.waitForApproval(n.id);if(this.emit("workflow:plan_decision",n,s),!s){n.status="cancelled",yield{delta:`
336
569
 
337
- **Step failed:** ${f?.message}
338
- *Workflow aborted.*`,finish_reason:"stop"};return}else w==="skip"&&(c.status="skipped",yield{delta:`
339
- *Step skipped due to failure.*
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=`
570
+ *Plan rejected by user.*`,finish_reason:"stop"};return}}n.status="approved",yield*this.streamPlanDirect(n,e,t)}async*streamDirect(e,t){yield*this.client.stream(e,t)}async*streamPlanDirect(e,t,o){e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e);let n=`
341
571
  You have created the following plan to fulfill the request:
342
572
  Summary: ${e.summary}
343
573
 
@@ -346,4 +576,45 @@ ${e.steps.map(a=>`${a.number}. ${a.description}`).join(`
346
576
  `)}
347
577
 
348
578
  Execute this plan now.
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};
579
+ `.trim(),s={...t,messages:this.injectPlanContext(t.messages,n)},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)}),this.emitProgress(e,"completed","Done")}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 Fb}from"events";k();var qb=class r extends Fb{client;activeProviderName;modeRegistry;workflowExecutor;knowledgeLayers=[];customProviderNames=new Set;mcpToolProject=null;_interceptors=[];constructor(e,t,o){super(),this.client=e,this.activeProviderName=t,this.modeRegistry=o;let n=this.client.getProvider(t);n&&this.forwardEvents(n),this.workflowExecutor=new xr(this.client,Hi,this.client.getQueryClassifier()),this.forwardWorkflowEvents()}buildKnowledgeRequestTools(){return this.knowledgeLayers.length===0?[]:this.knowledgeLayers.length===1?[this.knowledgeLayers[0].toTool(),{name:"knowledge_add",displayName:"Add to Knowledge",description:"Add important new information to the knowledge base for future reference.",category:"knowledge",parameters:{type:"object",properties:{content:{type:"string",description:"The content to add to the knowledge base."},metadata:{type:"object",description:"Optional metadata such as source, category, or tags."}},required:["content"]},execute:async s=>({success:!0,id:await this.knowledgeLayers[0].add(s.content,s.metadata),message:"Content added to knowledge base successfully."})}]:[{name:"knowledge_search",displayName:"Knowledge Search",description:`Search across ${this.knowledgeLayers.length} knowledge layers for relevant information.`,category:"search",cacheable:!1,parameters:{type:"object",properties:{query:{type:"string",description:"Search query to find relevant information"},limit:{type:"number",description:"Maximum number of results to return (default: 10)"},threshold:{type:"number",description:"Minimum similarity threshold 0-1 (default: 0.7)"},filter:{type:"object",description:"Optional metadata filters"}},required:["query"]},execute:async o=>{let s=(await Promise.all(this.knowledgeLayers.map(async(a,c)=>(await a.toTool().execute({query:o.query,limit:o.limit,threshold:o.threshold,filter:o.filter})).map(f=>({...f,_layer:c}))))).flat();s.sort((a,c)=>(c.score??0)-(a.score??0));let i=o.limit??10;return s.slice(0,i)}},{name:"knowledge_add",displayName:"Add to Knowledge",description:"Add important new information to the primary knowledge base for future reference.",category:"knowledge",parameters:{type:"object",properties:{content:{type:"string",description:"The content to add to the knowledge base."},metadata:{type:"object",description:"Optional metadata such as source, category, or tags."}},required:["content"]},execute:async o=>({success:!0,id:await this.knowledgeLayers[0].add(o.content,o.metadata),message:"Content added to knowledge base successfully."})}]}prepareRequest(e){let t=[...this.buildKnowledgeRequestTools(),...e.requestTools||[]];if(t.length===0)return e;let o=new Map;for(let n of t)o.set(n.name,n);return{...e,requestTools:Array.from(o.values())}}static async init(e){let t=An(e.configPath);ua(t.logging);let o=new un,n=Lo(e.configPath);o.setConfig(n),e.tools&&await o.loadBuiltIn(),e.customTools&&await o.loadProjects(e.customTools);let s=null,i=e.mcp||t.mcp;if(i)try{P("[MCP] Initializing MCP tool integration");let S=await qi(i);s=S,await o.loadProjects([S]),P(`[MCP] Loaded ${S.tools.length} tools from MCP servers`)}catch(S){pe(`[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,g=e.defaultProvider||e.provider;if(e.providers)for(let[S,$]of Object.entries(e.providers)){let _=S===g,L=await r.createProvider(S,$,e.configPath,!_);L&&(m[S]=L)}else if(e.provider){let S={apiKey:e.apiKey,model:e.model,projectId:e.projectId,location:e.location,googleAuthOptions:e.googleAuthOptions},$=await r.createProvider(e.provider,S,e.configPath,!1);$&&(m[e.provider]=$)}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(([$,_])=>(_.name=_.name||$,_));for(let $ of S){if(typeof $.generate!="function"||typeof $.stream!="function"||typeof $.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 _=$.name;if(!_)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[_])throw new Error(`Custom provider name "${_}" conflicts with a built-in provider designation. Choose a different name.`);f.add(_),m[_]=$}}if(!g&&e.customProviders&&(g=(Array.isArray(e.customProviders)?e.customProviders[0]:Object.values(e.customProviders)[0])?.name),!g)throw new Error("No default provider specified.");let w=new gn;if(e.customModes)for(let S of e.customModes)w.register(S);let b={...p,...e.modeOverrides||{}};for(let[S,$]of Object.entries(b)){let _=w.get(S);if(_){$.systemPrompt!==void 0&&(_.systemPrompt=$.systemPrompt),$.toolSearch&&(_.toolSearch={..._.toolSearch||{},...$.toolSearch});for(let[L,$e]of Object.entries($))L!=="systemPrompt"&&L!=="toolSearch"&&(_[L]=$e)}}let T=t.hitl||{};e.confirmationMode!==void 0&&(T.confirmationMode=e.confirmationMode),T.enabled===void 0&&e.onToolConfirm&&(T.enabled=!0),T.confirmationMode===void 0&&e.onToolConfirm&&(T.confirmationMode="all");let v=new xn({providers:m,defaultProvider:g,toolRegistry:o,toolsConfig:o.getConfig(),systemPrompt:a,disableBaseContext:c,hitlConfig:Object.keys(T).length>0?T:void 0,onToolConfirm:e.onToolConfirm,conversationId:e.conversationId,contextWindowConfig:e.contextWindow}),C=new r(v,g,w),x=e.knowledge,R=x==null?[]:Array.isArray(x)?x:[x];C.knowledgeLayers=R.filter(S=>!!S&&typeof S.toTool=="function"),C.customProviderNames=f,C.mcpToolProject=s,C._interceptors=e.interceptors??[];for(let S of C._interceptors)S.init&&await S.init();let D=e.defaultMode||St,M=w.get(D);return M&&(v.setMode(M),M.workflow&&C.workflowExecutor.setConfig(M.workflow)),C}static async createProvider(e,t,o,n=!1){if(e==="vertexai")return new Cn({projectId:t.projectId,location:t.location,googleAuthOptions:t.googleAuthOptions});if(["openai","anthropic","gemini","openrouter"].includes(e)){let s=`TOOLPACK_${e.toUpperCase()}_KEY`,i=t.apiKey||process.env[s]||process.env[`${e.toUpperCase()}_API_KEY`];if(!i){if(n)return null;throw new Error(`No API key found for '${e}'. Set ${s} or pass apiKey in config.`)}switch(e){case"openai":return new ht(i,t.baseUrl);case"anthropic":return new vn(i,t.baseUrl);case"gemini":return new kn(i);case"openrouter":return new Rn(i,{siteUrl:t.siteUrl,siteName:t.siteName})}}if(e==="ollama")return new Gt({baseUrl:t.baseUrl||Sn(o)});if(e.startsWith("ollama-")){let s=t.model||e.replace(/^ollama-/,""),i=t.baseUrl||Sn(o);return new et({model:s,baseUrl:i})}throw new Error(`Unknown provider type: ${e}`)}async generate(e,t){let o;if(typeof e=="string"?o={messages:[{role:"user",content:e}],model:""}:o=e,o=this.prepareRequest(o),this.getMode()?.workflow?.planning?.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 g=f.result.response.usage;i+=g.prompt_tokens,a+=g.completion_tokens||0,c+=g.total_tokens,p.steps.push({stepNumber:f.number,description:f.description,usage:g})}let m={prompt_tokens:i,completion_tokens:a,total_tokens:c};return s.response?{...s.response,content:s.output||s.response.content||null,usage:m,usage_details:p}:{content:s.output||null,usage:m,usage_details:p}}return this._interceptors.length>0?this._buildInterceptorChain(this._interceptors,i=>this.client.generate(i??o,t))(o):this.client.generate(o,t)}_buildInterceptorChain(e,t){return e.reduceRight((o,n)=>s=>n(s,i=>o(i??s)),t)}async*stream(e,t){let o=this.prepareRequest(e),n=this.getMode(),s=t||this.activeProviderName;if(n?.workflow?.planning?.enabled){yield*this.workflowExecutor.stream(o,s);return}yield*this.client.stream(o,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||Ze();if(t)try{let o=Ut(t);o?.hitl&&this.client.updateHitlConfig(o.hitl)}catch(o){I(`[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 Wi(this.mcpToolProject)}async listProviders(){let e=this.client.getProviders(),t=[];for(let[o,n]of e.entries()){let s=this.customProviderNames.has(o),i=[];try{i=await n.getModels()}catch(a){I(`[Toolpack] Failed to fetch models for provider '${o}': ${a}`)}t.push({name:o,displayName:n.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 n of o.models)t.push({...n,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(Hi),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 Fb&&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: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();l();l();var vr=class{capacity;map;constructor(e){this.capacity=e,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}set(e,t){if(this.map.has(e))this.map.delete(e);else if(this.map.size>=this.capacity){let o=this.map.keys().next().value;o!==void 0&&this.map.delete(o)}this.map.set(e,t)}has(e){return this.map.has(e)}get size(){return this.map.size}};var Ki=class{lru;maxMessagesPerConversation;constructor(e={}){this.lru=new vr(e.maxConversations??500),this.maxMessagesPerConversation=e.maxMessagesPerConversation??500}async append(e){let t=this.lru.get(e.conversationId);t||(t=[],this.lru.set(e.conversationId,t)),!t.some(o=>o.id===e.id)&&(t.push(e),t.sort((o,n)=>o.timestamp.localeCompare(n.timestamp)),t.length>this.maxMessagesPerConversation&&t.splice(0,t.length-this.maxMessagesPerConversation))}async get(e,t={}){let n=(this.lru.get(e)??[]).slice();if(t.scope!==void 0&&(n=n.filter(s=>s.scope===t.scope)),t.sinceTimestamp!==void 0&&(n=n.filter(s=>s.timestamp>=t.sinceTimestamp)),t.participantIds!==void 0&&t.participantIds.length>0){let s=new Set(t.participantIds);n=n.filter(i=>s.has(i.participant.id))}return t.limit!==void 0&&n.length>t.limit&&(n=n.slice(n.length-t.limit)),n}async search(e,t,o={}){let n=this.lru.get(e)??[],s=t.toLowerCase(),i=o.limit??10,a=o.tokenCap??2e3,c=n.filter(f=>f.content.toLowerCase().includes(s)).slice().reverse(),p=[],m=0;for(let f of c){if(p.length>=i)break;let g=Math.ceil(f.content.length/4);if(p.length>0&&m+g>a)break;p.push(f),m+=g}return p}async deleteMessages(e,t){let o=this.lru.get(e);if(!o||t.length===0)return;let n=new Set(t),s=o.filter(i=>!n.has(i.id));this.lru.set(e,s)}clearConversation(e){this.lru.set(e,[])}get conversationCount(){return this.lru.size}};l();import Xv from"better-sqlite3";import*as Rt from"fs";import*as yn from"path";function Yv(){let r=yn.join(process.cwd(),".toolpack","db","conversation");return Rt.existsSync(r)||Rt.mkdirSync(r,{recursive:!0}),yn.join(r,"conversation.sqlite")}var Ji=class{db;maxMessagesPerConversation;useFTS;constructor(e={}){let t=e.dbPath??Yv(),o=yn.dirname(t);if(Rt.existsSync(o)||Rt.mkdirSync(o,{recursive:!0}),this.db=new Xv(t),e.enableWAL!==!1){try{this.db.pragma("journal_mode = WAL")}catch{}try{this.db.pragma("synchronous = NORMAL")}catch{}}this.useFTS=e.useFTS===!0,this.maxMessagesPerConversation=e.maxMessagesPerConversation??500,this.initSchema()}initSchema(){this.db.exec(`
580
+ CREATE TABLE IF NOT EXISTS messages (
581
+ id TEXT NOT NULL,
582
+ conversation_id TEXT NOT NULL,
583
+ participant_kind TEXT,
584
+ participant_id TEXT,
585
+ participant_display_name TEXT,
586
+ content TEXT NOT NULL,
587
+ timestamp TEXT NOT NULL,
588
+ scope TEXT NOT NULL,
589
+ metadata TEXT,
590
+ PRIMARY KEY (conversation_id, id)
591
+ )`),this.db.exec("CREATE INDEX IF NOT EXISTS idx_messages_conv_ts ON messages (conversation_id, timestamp)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_messages_conv_scope_ts ON messages (conversation_id, scope, timestamp)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_messages_conv_participant_ts ON messages (conversation_id, participant_id, timestamp)"),this.useFTS&&(this.db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(doc_key UNINDEXED, content, tokenize = 'unicode61')"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_messages_fts_key ON messages_fts (doc_key)"))}async append(e){let t=this.db.prepare(`INSERT OR IGNORE INTO messages (
592
+ id, conversation_id, participant_kind, participant_id, participant_display_name,
593
+ content, timestamp, scope, metadata
594
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`),o=e.metadata?JSON.stringify(e.metadata):null,n=t.run(e.id,e.conversationId,e.participant.kind,e.participant.id,e.participant.displayName??null,e.content,e.timestamp,e.scope,o);if(this.useFTS&&n.changes>0){let s=`${e.conversationId}:${e.id}`;this.db.prepare("INSERT INTO messages_fts (doc_key, content) VALUES (?, ?)").run(s,e.content)}if(this.maxMessagesPerConversation>0){let a=this.db.prepare("SELECT COUNT(1) as c FROM messages WHERE conversation_id = ?").get(e.conversationId)?.c??0;if(a>this.maxMessagesPerConversation){let c=a-this.maxMessagesPerConversation,m=this.db.prepare("SELECT id FROM messages WHERE conversation_id = ? ORDER BY timestamp ASC LIMIT ?").all(e.conversationId,c).map(f=>f.id);if(m.length>0){let f=m.map(()=>"?").join(",");if(this.db.prepare(`DELETE FROM messages WHERE conversation_id = ? AND id IN (${f})`).run(e.conversationId,...m),this.useFTS){let w=m.map(v=>`${e.conversationId}:${v}`),b=w.map(()=>"?").join(",");this.db.prepare(`DELETE FROM messages_fts WHERE doc_key IN (${b})`).run(...w)}}}}}async get(e,t={}){let o=["conversation_id = ?"],n=[e];if(t.scope!==void 0&&(o.push("scope = ?"),n.push(t.scope)),t.sinceTimestamp!==void 0&&(o.push("timestamp >= ?"),n.push(t.sinceTimestamp)),t.participantIds&&t.participantIds.length>0){let p=t.participantIds.map(()=>"?").join(",");o.push(`participant_id IN (${p})`),n.push(...t.participantIds)}let i=`SELECT id, conversation_id, participant_kind, participant_id, participant_display_name, content, timestamp, scope, metadata FROM messages ${o.length?`WHERE ${o.join(" AND ")}`:""} ORDER BY timestamp ASC`,c=this.db.prepare(i).all(n).map(p=>this.rowToMessage(p));return t.limit!==void 0&&c.length>t.limit&&(c=c.slice(c.length-t.limit)),c}async search(e,t,o={}){let n=o.limit??10,s=o.tokenCap??2e3,i=[];this.useFTS?i=this.db.prepare(`
595
+ SELECT m.id, m.conversation_id, m.participant_kind, m.participant_id, m.participant_display_name,
596
+ m.content, m.timestamp, m.scope, m.metadata
597
+ FROM messages m
598
+ JOIN messages_fts f ON f.doc_key = (m.conversation_id || ':' || m.id)
599
+ WHERE m.conversation_id = ? AND f.content MATCH ?
600
+ ORDER BY m.timestamp DESC`).all(e,t):i=this.db.prepare(`
601
+ SELECT id, conversation_id, participant_kind, participant_id, participant_display_name,
602
+ content, timestamp, scope, metadata
603
+ FROM messages
604
+ WHERE conversation_id = ? AND content LIKE ? COLLATE NOCASE
605
+ ORDER BY timestamp DESC`).all(e,`%${t}%`);let a=i.map(m=>this.rowToMessage(m)),c=[],p=0;for(let m of a){if(c.length>=n)break;let f=Math.ceil(m.content.length/4);if(c.length>0&&p+f>s)break;c.push(m),p+=f}return c}async deleteMessages(e,t){if(!t||t.length===0)return;let o=t.map(()=>"?").join(",");if(this.db.prepare(`DELETE FROM messages WHERE conversation_id = ? AND id IN (${o})`).run(e,...t),this.useFTS){let s=t.map(c=>`${e}:${c}`),i=s.map(()=>"?").join(",");this.db.prepare(`DELETE FROM messages_fts WHERE doc_key IN (${i})`).run(...s)}}clearConversation(e){this.useFTS&&this.db.prepare("DELETE FROM messages_fts WHERE doc_key LIKE ?").run(`${e}:%`),this.db.prepare("DELETE FROM messages WHERE conversation_id = ?").run(e)}rowToMessage(e){return{id:e.id,conversationId:e.conversation_id,participant:{kind:e.participant_kind,id:e.participant_id,displayName:e.participant_display_name??void 0},content:e.content,timestamp:e.timestamp,scope:e.scope,metadata:e.metadata?JSON.parse(e.metadata):void 0}}close(){try{this.db.close()}catch{}}};l();import*as Wb from"os";import*as lt from"path";import*as _t from"fs";var Ub=".toolpack",Gb="config",Bb="toolpack.config.json";function Zv(){return Wb.homedir()}function eC(){return lt.join(Zv(),Ub)}function zb(){return lt.join(eC(),Gb)}function Cr(){return lt.join(zb(),Bb)}function tC(r=process.cwd()){return lt.join(r,Ub)}function Hb(r=process.cwd()){return lt.join(tC(r),Gb)}function kr(r=process.cwd()){return lt.join(Hb(r),Bb)}function Kb(){let r=zb();_t.existsSync(r)||_t.mkdirSync(r,{recursive:!0})}function k1(r=process.cwd()){let e=Hb(r);_t.existsSync(e)||_t.mkdirSync(e,{recursive:!0})}l();import*as te from"fs";import*as Pr from"path";function Qi(r,e){if(!e)return r;if(!r)return e;let t={...r};for(let o of Object.keys(e))e[o]instanceof Array?t[o]=e[o]:e[o]instanceof Object&&o in r?t[o]=Qi(r[o],e[o]):t[o]=e[o];return t}function Vi(r){if(!te.existsSync(r))return null;try{let e=te.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}function $1(r=process.cwd()){let e=Pr.join(r,"toolpack.config.json"),t=Cr(),o=kr(r),n=Vi(e)||{},s=Vi(t)||{},i=Vi(o)||{},a=Qi(n,s);return a=Qi(a,i),a}function E1(r=process.cwd()){let e=Pr.join(r,"toolpack.config.json"),t=Cr(),o=kr(r),n=!te.existsSync(t),s=null,i="default";return te.existsSync(o)?(s=o,i="local"):te.existsSync(t)?(s=t,i="global"):te.existsSync(e)&&(s=e,i="base"),{isFirstRun:n,activeConfigPath:s,configSource:i}}function D1(r=process.cwd()){let e=Cr();if(!te.existsSync(e)){Kb();let t=null,o=kr(r);if(te.existsSync(o))t=o;else{let s=Pr.join(r,"toolpack.config.json");if(te.existsSync(s))t=s;else{let i=Ze();i&&te.existsSync(i)&&(t=i)}}let n={};if(t)try{let s=te.readFileSync(t,"utf-8");n=JSON.parse(s)}catch{}te.writeFileSync(e,JSON.stringify(n,null,4),"utf-8")}}l();l();l();import*as Ke from"fs/promises";import*as $t from"path";l();var oC=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","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","then"]),Sr=class{documents=new Map;termFrequencies=new Map;documentLengths=new Map;avgDocLength=0;k1;b;constructor(e=1.5,t=.75){this.k1=e,this.b=t}tokenize(e){if(!e)return[];let t=e.toLowerCase();return t=t.replace(/([a-z])([A-Z])/g,"$1 $2"),t=t.replace(/[^a-z0-9]/g," "),t.split(/\s+/).filter(o=>o.length>1).filter(o=>!oC.has(o))}addDocument(e,t){this.documents.set(e,t);let o=this.tokenize(t);this.documentLengths.set(e,o.length);let n={};for(let s of o)n[s]=(n[s]??0)+1;for(let[s,i]of Object.entries(n))this.termFrequencies.has(s)||this.termFrequencies.set(s,new Map),this.termFrequencies.get(s).set(e,i);this.updateAvgDocLength()}clear(){this.documents.clear(),this.termFrequencies.clear(),this.documentLengths.clear(),this.avgDocLength=0}get size(){return this.documents.size}updateAvgDocLength(){if(this.documentLengths.size===0){this.avgDocLength=0;return}let e=0;this.documentLengths.forEach(t=>{e+=t}),this.avgDocLength=e/this.documentLengths.size}idf(e){let t=this.documents.size,o=this.termFrequencies.get(e)?.size??0;return o===0?0:Math.log((t-o+.5)/(o+.5)+1)}search(e,t=10){let o=this.tokenize(e);if(o.length===0)return[];let n={};this.documents.forEach((i,a)=>{let c=0,p=this.documentLengths.get(a)??0;for(let m of o){let f=this.termFrequencies.get(m);if(!f)continue;let g=f.get(a)??0;if(g===0)continue;let w=this.idf(m),b=g*(this.k1+1),T=g+this.k1*(1-this.b+this.b*(p/this.avgDocLength));c+=w*(b/T)}c>0&&(n[a]=c)});let s=Object.entries(n).map(([i,a])=>({id:i,score:a}));return s.sort((i,a)=>a.score-i.score),s.slice(0,t)}};l();import*as He from"path";function Jb(r,e,t){let o=r.match(/^---\n([\s\S]*?)\n---/),n="",s="",i,a=[];if(o&&o[1]){let R=o[1].split(`
606
+ `);for(let D of R){let M=D.indexOf(":");if(M===-1)continue;let S=D.substring(0,M).trim(),$=D.substring(M+1).trim();if(S==="name"&&(n=$),S==="title"&&(s=$),S==="version"&&(i=$),S==="tags"){let _=$.match(/\[(.*)\]/);_&&_[1]&&(a=_[1].split(",").map(L=>L.trim().replace(/"/g,"")).filter(Boolean))}}}n||(n=He.basename(e,".skill.md"));let c=r.match(/## Description\n\n([\s\S]*?)(?=\n## |$)/),p=c&&c[1]?c[1].trim():"",m=r.match(/## Triggers\n\n([\s\S]*?)(?=\n## |$)/),f=[];if(m&&m[1]){let R=m[1].split(`
607
+ `).filter(D=>D.startsWith("- "));for(let D of R){let M=D.match(/^- "(.*)"/);M&&M[1]&&f.push(M[1])}}let g=r.match(/## Instructions\n\n([\s\S]*?)(?=\n## |$)/),w=g&&g[1]?g[1].trim():"",b=r.match(/## Examples\n\n([\s\S]*?)(?=\n## |$)/),T=b&&b[1]?b[1].trim():void 0,v=He.relative(t,e),C=He.dirname(v),x=C==="."?void 0:C.split(He.sep)[0];return{name:n,title:s,version:i,tags:a,category:x,filePath:e,description:p,triggers:f,instructions:w,examples:T||void 0,lastModified:0}}l();l();var B={name:50,title:100,tags:{count:10,each:30},description:300,triggers:{count:10,min:1,each:100},instructions:2e3,examples:3e3};var nC=/^[a-z][a-z0-9-]*$/;function Vb(r,e){let t=[],o=[];r.name?(nC.test(r.name)||t.push(`name "${r.name}" must match kebab-case pattern /^[a-z][a-z0-9-]*$/`),r.name.length>B.name&&o.push(`name exceeds ${B.name} character limit (${r.name.length} chars)`)):t.push("name is required in frontmatter"),r.title?r.title.length>B.title&&o.push(`title exceeds ${B.title} character limit (${r.title.length} chars)`):t.push("title is required in frontmatter"),r.tags.length>B.tags.count&&o.push(`too many tags (${r.tags.length}); maximum is ${B.tags.count}`);for(let n of r.tags)n.length>B.tags.each&&o.push(`tag "${n}" exceeds ${B.tags.each} character limit`);if(r.description?r.description.length>B.description&&o.push(`description exceeds ${B.description} character limit (${r.description.length} chars)`):t.push("## Description section is required and must not be empty"),!r.triggers||r.triggers.length===0)t.push("## Triggers section must contain at least one trigger");else{r.triggers.length>B.triggers.count&&o.push(`too many triggers (${r.triggers.length}); maximum is ${B.triggers.count}`);for(let n of r.triggers)n.length>B.triggers.each&&o.push(`trigger "${n.substring(0,50)}..." exceeds ${B.triggers.each} character limit`)}return r.instructions?r.instructions.length>B.instructions&&o.push(`instructions exceed ${B.instructions} character limit (${r.instructions.length} chars)`):t.push("## Instructions section is required and must not be empty"),r.examples&&r.examples.length>B.examples&&o.push(`examples exceed ${B.examples} character limit (${r.examples.length} chars)`),{file:e,errors:t,warnings:o}}var Rr=class{dir;onValidationError;loaded=!1;skills=new Map;fileMtimes=new Map;index=new Sr;_buildPromise=null;constructor(e){this.dir=$t.resolve(e.dir),this.onValidationError=e.onValidationError}async findSkillFiles(e){let t=[],o;try{o=await Ke.readdir(e)}catch{return t}for(let n of o){let s=$t.join(e,n),i;try{i=await Ke.stat(s)}catch{continue}if(i.isDirectory()){let a=await this.findSkillFiles(s);t.push(...a)}else i.isFile()&&n.endsWith(".skill.md")&&t.push(s)}return t}buildIndexContent(e){let t=[];t.push(e.name,e.name,e.name),t.push(e.title,e.title,e.title);for(let o of e.tags)t.push(o,o);for(let o of e.triggers)t.push(o,o);return t.push(e.description),t.join(" ")}async needsRebuild(e){if(!this.loaded||e.length!==this.fileMtimes.size)return!0;for(let t of e)try{let o=await Ke.stat(t),n=this.fileMtimes.get(t);if(n===void 0||o.mtimeMs!==n)return!0}catch{return!0}return!1}async buildIndex(e){this.loaded=!1,this.skills.clear(),this.fileMtimes.clear(),this.index.clear();let t=[],o=[],n=new Map;for(let s of e){let i,a;try{let[g,w]=await Promise.all([Ke.readFile(s,"utf-8"),Ke.stat(s)]);i=g.replace(/\r\n/g,`
608
+ `),a=w.mtimeMs}catch{continue}this.fileMtimes.set(s,a);let c=Jb(i,s,this.dir);c.lastModified=a;let p=$t.relative(this.dir,s),m=Vb(c,p);if(m.warnings.length>0)for(let g of m.warnings)console.warn(`[skills] ${p}: ${g}`);if(m.errors.length>0){t.push({file:p,errors:m.errors}),this.onValidationError==="warn"&&console.warn(`[skills] Skipping invalid skill "${p}": ${m.errors.join("; ")}`);continue}let f=n.get(c.name);if(f){let g=`duplicate skill name "${c.name}" \u2014 already defined in "${f}"`;t.push({file:p,errors:[g]}),this.onValidationError==="warn"&&console.warn(`[skills] Skipping "${p}": ${g}`);continue}n.set(c.name,p),o.push(c)}if(t.length>0&&this.onValidationError==="fail"){let s=t.map(i=>` ${i.file}:
609
+ ${i.errors.join(`
610
+ `)}`).join(`
611
+ `);throw new Error(`Skills validation failed \u2014 fix the following files before starting:
612
+ ${s}`)}for(let s of o)this.skills.set(s.name,s),this.index.addDocument(s.name,this.buildIndexContent(s));this.loaded=!0}async ensureLoaded(){if(this._buildPromise)return this._buildPromise;let e=await this.findSkillFiles(this.dir);if(this._buildPromise)return this._buildPromise;if(await this.needsRebuild(e))return this._buildPromise?this._buildPromise:(this._buildPromise=this.buildIndex(e).finally(()=>{this._buildPromise=null}),this._buildPromise)}async search(e,t,o){await this.ensureLoaded();let n=this.index.search(e,t),s=[];for(let i of n){if(i.score<o)continue;let a=this.skills.get(i.id);a&&s.push({skill:a,score:i.score})}return s}async get(e){return await this.ensureLoaded(),this.skills.get(e)}async list(e){await this.ensureLoaded();let t=Array.from(this.skills.values());return e?.tag?t.filter(o=>o.tags.includes(e.tag)):t}};function rC(r){let e=r?.dir??".toolpack/skills",t=r?.maxSkills??3,o=r?.minScore??.3,n=r?.onValidationError??"fail",s=new Rr({dir:e,onValidationError:n});return Object.assign(async(i,a)=>{let c=i.messages??[],p=-1;for(let g=c.length-1;g>=0;g--)if(c[g].role==="user"){p=g;break}let m=p>=0?c[p]:null,f=m&&typeof m.content=="string"?m.content.trim():"";if(f){let g=await s.search(f,t,o);if(g.length>0){let b=`<skill-instructions>
613
+ ${g.map(v=>`--- Skill: ${v.skill.title} ---
614
+ ${v.skill.instructions.trim()}
615
+ ---`).join(`
616
+
617
+ `)}
618
+ </skill-instructions>`,T=c.map((v,C)=>C===p&&typeof v.content=="string"?{...v,content:`${b}
619
+
620
+ ${v.content}`}:v);return a({...i,messages:T})}}return a(i)},{init:()=>s.ensureLoaded()})}export{Ib as AGENT_MODE,zi as AGENT_PLANNING_PROMPT,Ob as AGENT_WORKFLOW,xn as AIClient,vn as AnthropicAdapter,we as AuthenticationError,Ot as BM25SearchEngine,Tr as BUILT_IN_MODES,Lb as CHAT_MODE,Ab as CHAT_WORKFLOW,jb as CODING_MODE,Kv as CODING_PLANNING_PROMPT,Nb as CODING_WORKFLOW,Gb as CONFIG_DIR_NAME,Bb as CONFIG_FILE_NAME,Qe as ConnectionError,ea as ContextWindowConfigError,_r as ContextWindowExceededError,Ar as ContextWindowStateManager,ta as ConversationNotFoundError,St as DEFAULT_MODE_NAME,re as DEFAULT_TOOLS_CONFIG,dw as DEFAULT_TOOL_SEARCH_CONFIG,hU as DEFAULT_WORKFLOW,Hi as DEFAULT_WORKFLOW_CONFIG,kn as GeminiAdapter,Ki as InMemoryConversationStore,$r as InsufficientContextError,j as InvalidRequestError,fn as McpClient,Me as McpConnectionError,br as McpTimeoutError,wr as McpToolManager,gn as ModeRegistry,et as OllamaAdapter,Gt as OllamaProvider,ht as OpenAIAdapter,Rn as OpenRouterAdapter,Yi as PageError,hn as Planner,Z as ProviderAdapter,W as ProviderError,Pe as RateLimitError,A as SDKError,Ji as SQLiteConversationStore,Er as SummarizationError,Ub as TOOLPACK_DIR_NAME,Nt as TOOL_SEARCH_NAME,Zi as TimeoutError,mt as ToolDiscoveryCache,un as ToolRegistry,It as ToolRouter,qb as Toolpack,Cn as VertexAIAdapter,xr as WorkflowExecutor,Pw as addBypassRule,RC as buildSummarizedHistory,gr as cloudDeployTool,yr as cloudListTool,hr as cloudStatusTool,zy as cloudToolsProject,nn as codingExtractFunctionTool,Qo as codingFindReferencesTool,Ko as codingFindSymbolTool,rn as codingGetCallHierarchyTool,tn as codingGetDiagnosticsTool,on as codingGetExportsTool,Vo as codingGetImportsTool,en as codingGetOutlineTool,Jo as codingGetSymbolsTool,Xo as codingGoToDefinitionTool,Yo as codingMultiFileEditTool,Zo as codingRefactorRenameTool,uh as codingToolsProject,na as countTokens,ca as createContextWindowStateManager,qi as createMcpToolProject,Jv as createMode,rC as createSkillInterceptor,Hv as createSkillTools,_C as createSummarizationReport,Nr as createSummarySystemMessage,Ov as createToolProject,ur as dbCountTool,dr as dbDeleteTool,pr as dbInsertTool,ar as dbQueryTool,lr as dbSchemaTool,cr as dbTablesTool,Ny as dbToolsProject,mr as dbUpdateTool,or as diffApplyTool,tr as diffCreateTool,nr as diffPreviewTool,ay as diffToolsProject,Wi as disconnectMcpToolProject,Kb as ensureGlobalConfigDir,k1 as ensureLocalConfigDir,cw as estimateSummaryTokens,Ne as estimateTokenCount,go as execKillTool,ho as execListProcessesTool,fo as execReadOutputTool,uo as execRunBackgroundTool,po as execRunShellTool,co as execRunTool,Dp as execToolsProject,SC as extractConversationKeypoints,Pa as fetchUrlAsBase64,Ht as fsAppendFileTool,ao as fsBatchReadTool,lo as fsBatchWriteTool,eo as fsCopyTool,Xt as fsCreateDirTool,io as fsDeleteDirTool,Kt as fsDeleteFileTool,Jt as fsExistsTool,so as fsGlobTool,Qt as fsListDirTool,Yt as fsMoveTool,to as fsReadFileRangeTool,Bt as fsReadFileTool,no as fsReplaceInFileTool,oo as fsSearchTool,Vt as fsStatTool,Bc as fsToolsProject,ro as fsTreeTool,zt as fsWriteFileTool,lw as generateSummarizationPrompt,Ir as generateToolCategoriesPrompt,yC as getContextWindowPercentage,Rw as getDefaultSlmModel,zb as getGlobalConfigDir,Cr as getGlobalConfigPath,eC as getGlobalToolpackDir,Hb as getLocalConfigDir,kr as getLocalConfigPath,tC as getLocalToolpackDir,vC as getMessageStats,xa as getMimeType,Sn as getOllamaBaseUrl,kw as getOllamaProviderEntries,$w as getRegisteredSlmModels,E1 as getRuntimeConfigStatus,ra as getSafeOutputReserve,At as getToolSearchSchema,qr as getToolpackConfig,Zv as getUserHomeDir,Hn as gitAddTool,Jn as gitBlameTool,Qn as gitBranchCreateTool,Vn as gitBranchListTool,Xn as gitCheckoutTool,er as gitCloneTool,Kn as gitCommitTool,Bn as gitDiffTool,zn as gitLogTool,Gn as gitStatusTool,Hh as gitToolsProject,_o as githubContentsGetTextTool,Ro as githubGraphqlExecuteTool,Ao as githubIssuesCommentsCreateTool,Mo as githubPrDiffGetTool,Oo as githubPrFilesListTool,Do as githubPrReviewCommentsReplyTool,$o as githubPrReviewThreadsListTool,Eo as githubPrReviewThreadsResolveTool,No as githubPrReviewsSubmitTool,tu as githubToolsProject,xC as groupMessagesByRole,pC as handleContextWindowError,Po as httpDeleteTool,So as httpDownloadTool,vo as httpGetTool,Co as httpPostTool,ko as httpPutTool,Vm as httpToolsProject,D1 as initializeGlobalConfigIfFirstRun,cC as isContextWindowError,va as isDataUri,_w as isRegisteredSlm,bn as isToolSearchTool,Mi as k8sApplyManifestTool,Oi as k8sDeleteResourceTool,Ei as k8sDescribeTool,Ii as k8sGetConfigMapTool,Di as k8sGetLogsTool,ji as k8sGetNamespacesTool,Ai as k8sListDeploymentsTool,$i as k8sListPodsTool,Ni as k8sListServicesTool,Li as k8sSwitchContextTool,Lv as k8sToolsProject,Fi as k8sWaitForDeploymentTool,An as loadFullConfig,$1 as loadRuntimeConfig,Lo as loadToolsConfig,$C as mergeSummarizationResults,xw as normalizeImagePart,Se as ollamaRequest,Ur as ollamaStream,Ca as parseDataUri,la as parseSummarizationResponse,aa as prepareSummarizationRequest,sa as pruneMessages,ka as readFileAsBase64,Wr as reloadToolpackConfig,Sw as removeBypassRule,jT as saveToolsConfig,dn as slackAuthTestTool,ln as slackChatPostEphemeralTool,an as slackChatPostMessageTool,pn as slackConversationsHistoryTool,mn as slackConversationsRepliesTool,cn as slackReactionsAddTool,$b as slackToolsProject,To as systemCwdTool,xo as systemDiskUsageTool,bo as systemEnvTool,yo as systemInfoTool,wo as systemSetEnvTool,dm as systemToolsProject,Tw as toDataUri,dt as toolSearchDefinition,TC as truncateMessage,ia as validateSummarizationResult,qo as webExtractLinksTool,Bo as webFeedTool,Io as webFetchTool,Wo as webMapTool,Uo as webMetadataTool,Fo as webScrapeTool,zo as webScreenshotTool,jo as webSearchTool,Go as webSitemapTool,kf as webToolsProject,hC as wouldExceedContextWindow};