toolpack-sdk 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var lT=Object.create;var mr=Object.defineProperty;var cT=Object.getOwnPropertyDescriptor;var pT=Object.getOwnPropertyNames;var mT=Object.getPrototypeOf,dT=Object.prototype.hasOwnProperty;var g=(r,e)=>()=>(r&&(e=r(r=0)),e);var le=(r,e)=>{for(var t in e)mr(r,t,{get:e[t],enumerable:!0})},fl=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of pT(e))!dT.call(r,n)&&n!==t&&mr(r,n,{get:()=>e[n],enumerable:!(o=cT(e,n))||o.enumerable});return r};var T=(r,e,t)=>(t=r!=null?lT(mT(r)):{},fl(e||!r||!r.__esModule?mr(t,"default",{value:r,enumerable:!0}):t,r)),uT=r=>fl(mr({},"__esModule",{value:!0}),r);var c=g(()=>{"use strict"});function fT(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 gT(r,e){return r instanceof fr?{shouldRetry:r.isRetryable(),shouldFallback:!0,action:r.isRetryable()?"prune":"fail",message:r.getSuggestedRecovery()}:r instanceof dr?{shouldRetry:!1,shouldFallback:!0,action:r.strategy==="fail"?"prune":"none",message:`Context window exceeded. Strategy: ${r.strategy}`}:r instanceof ur?{shouldRetry:!1,shouldFallback:!0,action:"fail",message:"Insufficient context after recovery attempts"}:{shouldRetry:!1,shouldFallback:!1,action:"none",message:"Unknown context window error"}}var N,he,ce,I,j,Ie,vs,Cs,dr,ur,fr,Ps,ks,pe=g(()=>{"use strict";c();N=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},he=class extends N{constructor(e,t){super(e,"AUTHENTICATION_ERROR",401,t),this.name="AuthenticationError"}},ce=class extends N{constructor(t,o,n){super(t,"RATE_LIMIT_ERROR",429,n);this.retryAfter=o;this.name="RateLimitError"}retryAfter},I=class extends N{constructor(e,t){super(e,"INVALID_REQUEST_ERROR",400,t),this.name="InvalidRequestError"}},j=class extends N{constructor(e,t="PROVIDER_ERROR",o=500,n){super(e,t,o,n),this.name="ProviderError"}},Ie=class extends N{constructor(e,t){super(e,"CONNECTION_ERROR",503,t),this.name="ConnectionError"}},vs=class extends N{constructor(t,o,n){super(t,"PAGE_ERROR",502,n);this.pageUrl=o;this.name="PageError"}pageUrl},Cs=class extends N{constructor(t,o,n){super(t,"TIMEOUT_ERROR",504,n);this.phase=o;this.name="TimeoutError"}phase},dr=class extends N{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`
1
+ "use strict";var ox=Object.create;var _r=Object.defineProperty;var nx=Object.getOwnPropertyDescriptor;var rx=Object.getOwnPropertyNames;var sx=Object.getPrototypeOf,ix=Object.prototype.hasOwnProperty;var g=(r,e)=>()=>(r&&(e=r(r=0)),e);var X=(r,e)=>{for(var t in e)_r(r,t,{get:e[t],enumerable:!0})},El=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of rx(e))!ix.call(r,n)&&n!==t&&_r(r,n,{get:()=>e[n],enumerable:!(o=nx(e,n))||o.enumerable});return r};var T=(r,e,t)=>(t=r!=null?ox(sx(r)):{},El(e||!r||!r.__esModule?_r(t,"default",{value:r,enumerable:!0}):t,r)),ax=r=>El(_r({},"__esModule",{value:!0}),r);var c=g(()=>{"use strict"});function lx(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 cx(r,e){return r instanceof Er?{shouldRetry:r.isRetryable(),shouldFallback:!0,action:r.isRetryable()?"prune":"fail",message:r.getSuggestedRecovery()}:r instanceof Rr?{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,he,ce,I,j,Le,Rs,$s,Rr,$r,Er,Es,Ds,pe=g(()=>{"use strict";c();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},he=class extends A{constructor(e,t){super(e,"AUTHENTICATION_ERROR",401,t),this.name="AuthenticationError"}},ce=class extends A{constructor(t,o,n){super(t,"RATE_LIMIT_ERROR",429,n);this.retryAfter=o;this.name="RateLimitError"}retryAfter},I=class extends A{constructor(e,t){super(e,"INVALID_REQUEST_ERROR",400,t),this.name="InvalidRequestError"}},j=class extends A{constructor(e,t="PROVIDER_ERROR",o=500,n){super(e,t,o,n),this.name="ProviderError"}},Le=class extends A{constructor(e,t){super(e,"CONNECTION_ERROR",503,t),this.name="ConnectionError"}},Rs=class extends A{constructor(t,o,n){super(t,"PAGE_ERROR",502,n);this.pageUrl=o;this.name="PageError"}pageUrl},$s=class extends A{constructor(t,o,n){super(t,"TIMEOUT_ERROR",504,n);this.phase=o;this.name="TimeoutError"}phase},Rr=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
2
  Context Window Exceeded
3
3
  =======================
4
4
  Conversation ID: ${this.conversationId}
@@ -9,7 +9,7 @@ Usage: ${this.getUsagePercentage()}%
9
9
  Strategy: ${this.strategy}
10
10
 
11
11
  Message: ${this.message}
12
- `.trim()}},ur=class extends N{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`
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
13
  Insufficient Context
14
14
  ====================
15
15
  Conversation ID: ${this.conversationId}
@@ -20,7 +20,7 @@ Minimum Required: ${this.minimumRequiredTokens}
20
20
  Recoverable: ${this.isRecoverable()?"Yes":"No"}
21
21
 
22
22
  Message: ${this.message}
23
- `.trim()}},fr=class extends N{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=`
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
24
  Summarization Error
25
25
  ===================
26
26
  Conversation ID: ${this.conversationId}
@@ -32,7 +32,7 @@ Recovery Action: ${this.getSuggestedRecovery()}
32
32
  Message: ${this.message}`;return this.summaryAttempt?t+`
33
33
 
34
34
  Partial Summary:
35
- ${this.summaryAttempt.substring(0,500)}${this.summaryAttempt.length>500?"...":""}`:t.trim()}},Ps=class extends N{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`
35
+ ${this.summaryAttempt.substring(0,500)}${this.summaryAttempt.length>500?"...":""}`:t.trim()}},Es=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
36
  Context Window Configuration Error
37
37
  ===================================
38
38
  Field: ${this.configField}
@@ -40,48 +40,58 @@ Provided Value: ${JSON.stringify(this.providedValue)}
40
40
  Constraint: ${this.constraint}
41
41
 
42
42
  Message: ${this.message}
43
- `.trim()}},ks=class extends N{constructor(t,o,n){super(t,"CONVERSATION_NOT_FOUND",404,n);this.conversationId=o;this.name="ConversationNotFoundError"}conversationId}});var wl,te,gn=g(()=>{"use strict";c();wl={enabled:!1,alwaysLoadedTools:[],alwaysLoadedCategories:[],searchResultLimit:5,cacheDiscoveredTools:!0},te={enabled:!0,autoExecute:!0,maxToolRounds:5,toolChoicePolicy:"auto",resultMaxChars:2e4,enabledTools:[],enabledToolCategories:[],toolSearch:wl}});function xl(r){if(!r)return;let e=r.toLowerCase();if(e in Is)return e;console.warn(`[Toolpack Warning] Invalid log level "${r}". Falling back to "info".`)}function vl(r){if(r?.enabled!==void 0&&(Pt=r.enabled),r?.filePath&&(ve=r.filePath),r?.level&&(hn=xl(r.level)||"info"),process.env.TOOLPACK_SDK_LOG_ENABLED!==void 0&&(Pt=process.env.TOOLPACK_SDK_LOG_ENABLED==="true"),process.env.TOOLPACK_SDK_LOG_FILE&&(ve=process.env.TOOLPACK_SDK_LOG_FILE,Pt=!0),process.env.TOOLPACK_SDK_LOG_LEVEL&&(hn=xl(process.env.TOOLPACK_SDK_LOG_LEVEL)||hn),process.env.TOOLPACK_SDK_LOG_CONSOLE!==void 0&&(Ls=process.env.TOOLPACK_SDK_LOG_CONSOLE==="true"),r?.console!==void 0&&process.env.TOOLPACK_SDK_LOG_CONSOLE===void 0&&(Ls=r.console),Pt)try{ve=(0,Le.isAbsolute)(ve)?ve:(0,Le.resolve)(process.cwd(),ve),(0,yn.mkdirSync)((0,Le.dirname)(ve),{recursive:!0}),(0,yn.appendFileSync)(ve,`[${new Date().toISOString()}] [INFO] [Logger] initialized level=${hn} file=${ve}
44
- `)}catch(e){console.warn(`[Toolpack Warning] Failed to initialize log file "${ve}": ${e.message}`),Pt=!1}}function ot(r){return Pt?Is[r]<=Is[hn]:!1}function bn(r,e){if(!ot(r))return;let o=`[${new Date().toISOString()}] [${r.toUpperCase()}] ${Cl(e)}`;(0,yn.appendFileSync)(ve,o+`
45
- `),Ls&&(r==="error"?console.error:r==="warn"?console.warn:console.log)(o)}function me(r){bn("error",r)}function L(r){bn("warn",r)}function S(r){bn("info",r)}function h(r){bn("debug",r)}function je(r){bn("trace",r)}function Cl(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=Cl(t);return o.length<=e?o:`${o.slice(0,e)}\u2026`}catch{return"[Unserializable]"}}function oe(r,e,t){ot("debug")&&(h(`[${e}][${r}] Messages (${t.length}):`),t.forEach((o,n)=>{h(`[${e}][${r}] #${n} role=${o?.role} content=${O(o?.content,300)}`)}))}var yn,Le,Is,Pt,hn,ve,Ls,k=g(()=>{"use strict";c();yn=require("fs"),Le=require("path"),Is={error:0,warn:1,info:2,debug:3,trace:4},Pt=!1,hn="info",ve=(0,Le.join)(process.cwd(),"toolpack-sdk.log"),Ls=!1});var Tn={};le(Tn,{fetchUrlAsBase64:()=>Us,getMimeType:()=>js,isDataUri:()=>Fs,normalizeImagePart:()=>Ml,parseDataUri:()=>qs,readFileAsBase64:()=>Ws,toDataUri:()=>Dl});function js(r){let e=El.extname(r).toLowerCase();return OT[e]||"application/octet-stream"}function Fs(r){return r.startsWith("data:")}function qs(r){let e=r.match(/^data:(.*?);base64,(.+)$/);return e?{mimeType:e[1],data:e[2]}:null}function Dl(r,e){return`data:${e};base64,${r}`}async function Ws(r){try{return{data:(await $l.readFile(r)).toString("base64"),mimeType:js(r)}}catch(e){throw new I(`Failed to read image file: ${r}`,e)}}async function Us(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 j(`Failed to download image from URL: ${r}`,"FETCH_ERROR",500,e)}}async function Ml(r){if(r.type==="image_data")return{data:r.image_data.data,mimeType:r.image_data.mimeType};if(r.type==="image_file")return await Ws(r.image_file.path);if(r.type==="image_url"){let e=r.image_url.url;if(Fs(e)){let t=qs(e);if(!t)throw new I(`Malformed data URI provided in image_url: ${e.substring(0,50)}...`);return t}return await Us(e)}throw new I(`Unknown ImagePart type: ${r.type}`)}var $l,El,OT,kt=g(()=>{"use strict";c();$l=T(require("fs/promises"),1),El=T(require("path"),1);pe();OT={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".heic":"image/heic",".heif":"image/heif"}});var Bl,zl,Hl,Kl,Jl,Vl=g(()=>{"use strict";c();Bl="fs.read_file",zl="Read File",Hl="Read the contents of a file at the given path. Returns the file content as a string.",Kl="filesystem",Jl={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path"]}});async function NT(r){let e=r.path,t=r.encoding||"utf-8";if(h(`[fs.read-file] execute path="${e}" encoding=${t}`),!e)throw new Error("path is required");if(!Rt.existsSync(e))throw new Error(`File not found: ${e}`);if(Rt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);return Rt.readFileSync(e,t)}var Rt,_t,Js=g(()=>{"use strict";c();Rt=T(require("fs"),1);Vl();k();_t={name:Bl,displayName:zl,description:Hl,parameters:Jl,category:Kl,execute:NT}});var Ql,Xl,Yl,Zl,ec,tc=g(()=>{"use strict";c();Ql="fs.write_file",Xl="Write File",Yl="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.",Zl="filesystem",ec={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to write"},content:{type:"string",description:"Content to write to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});async function AT(r){let e=r.path,t=r.content,o=r.encoding||"utf-8";if(h(`[fs.write-file] execute path="${e}" encoding=${o} content_len=${t?.length??0}`),!e)throw new Error("path is required");if(t==null)throw new Error("content is required");let n=oc.dirname(e);return $t.existsSync(n)||$t.mkdirSync(n,{recursive:!0}),$t.writeFileSync(e,t,o),`File written successfully: ${e} (${Buffer.byteLength(t,o)} bytes)`}var $t,oc,Et,Vs=g(()=>{"use strict";c();$t=T(require("fs"),1),oc=T(require("path"),1);tc();k();Et={name:Ql,displayName:Xl,description:Yl,parameters:ec,category:Zl,execute:AT,confirmation:{level:"high",reason:"This will overwrite the entire file contents.",showArgs:["path"]}}});var nc,rc,sc,ic,ac,lc=g(()=>{"use strict";c();nc="fs.append_file",rc="Append File",sc="Append content to the end of a file. Creates the file if it does not exist.",ic="filesystem",ac={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to append to"},content:{type:"string",description:"Content to append to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});async function IT(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=cc.dirname(e);return Dt.existsSync(n)||Dt.mkdirSync(n,{recursive:!0}),Dt.appendFileSync(e,t,o),`Content appended to: ${e} (${Buffer.byteLength(t,o)} bytes appended)`}var Dt,cc,Mt,Qs=g(()=>{"use strict";c();Dt=T(require("fs"),1),cc=T(require("path"),1);lc();Mt={name:nc,displayName:rc,description:sc,parameters:ac,category:ic,execute:IT,confirmation:{level:"medium",reason:"This will modify the file by appending content.",showArgs:["path"]}}});var pc,mc,dc,uc,fc,gc=g(()=>{"use strict";c();pc="fs.delete_file",mc="Delete File",dc="Remove/delete a file from the filesystem. Does not delete directories.",uc="filesystem",fc={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to delete"}},required:["path"]}});async function LT(r){let e=r.path;if(h(`[fs.delete-file] execute path="${e}"`),!e)throw new Error("path is required");if(!Ot.existsSync(e))throw new Error(`File not found: ${e}`);if(Ot.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}. Use a different tool to remove directories.`);return Ot.unlinkSync(e),`File deleted successfully: ${e}`}var Ot,Nt,Xs=g(()=>{"use strict";c();Ot=T(require("fs"),1);gc();k();Nt={name:pc,displayName:mc,description:dc,parameters:fc,category:uc,execute:LT,confirmation:{level:"high",reason:"This will permanently delete the file. This action cannot be undone.",showArgs:["path"]}}});var hc,yc,bc,wc,Tc,xc=g(()=>{"use strict";c();hc="fs.exists",yc="Exists",bc="Check if a file or directory exists at the given path. Returns true or false.",wc="filesystem",Tc={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to check"}},required:["path"]}});async function jT(r){let e=r.path;if(!e)throw new Error("path is required");let t=vc.existsSync(e);return JSON.stringify({exists:t,path:e})}var vc,At,Ys=g(()=>{"use strict";c();vc=T(require("fs"),1);xc();At={name:hc,displayName:yc,description:bc,parameters:Tc,category:wc,execute:jT}});var Cc,Pc,kc,Sc,Rc,_c=g(()=>{"use strict";c();Cc="fs.stat",Pc="Stat",kc="Get file or directory information including size, type, and modification date.",Sc="filesystem",Rc={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to get info for"}},required:["path"]}});async function FT(r){let e=r.path;if(!e)throw new Error("path is required");if(!Pr.existsSync(e))throw new Error(`Path not found: ${e}`);let t=Pr.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 Pr,It,Zs=g(()=>{"use strict";c();Pr=T(require("fs"),1);_c();It={name:Cc,displayName:Pc,description:kc,parameters:Rc,category:Sc,execute:FT}});var $c,Ec,Dc,Mc,Oc,Nc=g(()=>{"use strict";c();$c="fs.list_dir",Ec="List Directory",Dc="List files and directories at the given path. Optionally recurse into subdirectories.",Mc="filesystem",Oc={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to list"},recursive:{type:"boolean",description:"Whether to list recursively (default: false)",default:!1}},required:["path"]}});function Ic(r,e,t,o=""){let n=st.readdirSync(r,{withFileTypes:!0});for(let s of n){let i=Ac.join(r,s.name),a=o?`${o}/${s.name}`:s.name;if(s.isDirectory())t.push({name:a,type:"directory",size:0}),e&&Ic(i,!0,t,a);else if(s.isFile()){let l=st.statSync(i);t.push({name:a,type:"file",size:l.size})}}}async function qT(r){let e=r.path,t=r.recursive===!0;if(!e)throw new Error("path is required");if(!st.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!st.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let n=[];return Ic(e,t,n),JSON.stringify(n,null,2)}var st,Ac,Lt,ei=g(()=>{"use strict";c();st=T(require("fs"),1),Ac=T(require("path"),1);Nc();Lt={name:$c,displayName:Ec,description:Dc,parameters:Oc,category:Mc,execute:qT}});var Lc,jc,Fc,qc,Wc,Uc=g(()=>{"use strict";c();Lc="fs.create_dir",jc="Create Directory",Fc="Create a directory at the given path. Creates parent directories recursively if they do not exist.",qc="filesystem",Wc={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to create"},recursive:{type:"boolean",description:"Create parent directories if they do not exist (default: true)",default:!0}},required:["path"]}});async function WT(r){let e=r.path,t=r.recursive!==!1;if(!e)throw new Error("path is required");if(jt.existsSync(e)){if(jt.statSync(e).isDirectory())return`Directory already exists: ${e}`;throw new Error(`Path exists but is not a directory: ${e}`)}return jt.mkdirSync(e,{recursive:t}),`Directory created: ${e}`}var jt,Ft,ti=g(()=>{"use strict";c();jt=T(require("fs"),1);Uc();Ft={name:Lc,displayName:jc,description:Fc,parameters:Wc,category:qc,execute:WT}});var Gc,Bc,zc,Hc,Kc,Jc=g(()=>{"use strict";c();Gc="fs.move",Bc="Move",zc="Move or rename a file or directory from one path to another.",Hc="filesystem",Kc={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});async function UT(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(!it.existsSync(e))throw new Error(`Source not found: ${e}`);let o=Vc.dirname(t);return it.existsSync(o)||it.mkdirSync(o,{recursive:!0}),it.renameSync(e,t),`Moved: ${e} \u2192 ${t}`}var it,Vc,qt,oi=g(()=>{"use strict";c();it=T(require("fs"),1),Vc=T(require("path"),1);Jc();qt={name:Gc,displayName:Bc,description:zc,parameters:Kc,category:Hc,execute:UT,confirmation:{level:"high",reason:"This will move/rename the file or directory, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var Qc,Xc,Yc,Zc,ep,tp=g(()=>{"use strict";c();Qc="fs.copy",Xc="Copy",Yc="Copy a file or directory from one path to another. Recursively copies directories.",Zc="filesystem",ep={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});function op(r,e){if(de.statSync(r).isDirectory()){de.existsSync(e)||de.mkdirSync(e,{recursive:!0});let o=de.readdirSync(r);for(let n of o)op(_n.join(r,n),_n.join(e,n))}else de.copyFileSync(r,e)}async function GT(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(!de.existsSync(e))throw new Error(`Source not found: ${e}`);let o=_n.dirname(t);return de.existsSync(o)||de.mkdirSync(o,{recursive:!0}),op(e,t),`Copied ${de.statSync(e).isDirectory()?"directory":"file"}: ${e} \u2192 ${t}`}var de,_n,Wt,ni=g(()=>{"use strict";c();de=T(require("fs"),1),_n=T(require("path"),1);tp();Wt={name:Qc,displayName:Xc,description:Yc,parameters:ep,category:Zc,execute:GT,confirmation:{level:"medium",reason:"This will copy files or directories, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var np,rp,sp,ip,ap,lp=g(()=>{"use strict";c();np="fs.read_file_range",rp="Read File Range",sp="Read a specific range of lines from a file. Useful for reading portions of large files without loading the entire content.",ip="filesystem",ap={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},start_line:{type:"integer",description:"Start line number (1-indexed)"},end_line:{type:"integer",description:"End line number (1-indexed, inclusive)"}},required:["path","start_line","end_line"]}});async function BT(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(!Ut.existsSync(e))throw new Error(`File not found: ${e}`);if(Ut.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let i=Ut.readFileSync(e,"utf-8").split(`
46
- `),a=i.length,l=Math.min(t,a),p=Math.min(o,a),u=i.slice(l-1,p).map((f,b)=>`${l+b}: ${f}`).join(`
43
+ `.trim()}},Ds=class extends A{constructor(t,o,n){super(t,"CONVERSATION_NOT_FOUND",404,n);this.conversationId=o;this.name="ConversationNotFoundError"}conversationId}});var vt,Ct,kx,Nl=g(()=>{"use strict";c();vt={name:3,displayName:2.5,description:2,category:1.5,parameterNames:1,parameterDescriptions:.5},Ct=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 l of this.documents){if(n&&l.tool.category!==n)continue;let p=this.computeBM25Score(i,l);p>s&&a.push({toolName:l.toolName,score:p,tool:l.tool})}return a.sort((l,p)=>p.score-l.score).slice(0,o).map(({toolName:l,score:p,tool:m})=>({toolName:l,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<vt.name;i++)t.push(e.name);for(let i=0;i<vt.displayName;i++)t.push(e.displayName);for(let i=0;i<vt.description;i++)t.push(e.description);for(let i=0;i<vt.category;i++)t.push(e.category);if(e.parameters?.properties)for(let[i,a]of Object.entries(e.parameters.properties)){for(let l=0;l<vt.parameterNames;l++)t.push(i);if(a.description)for(let l=0;l<vt.parameterDescriptions;l++)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=>!kx.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,l=s*(this.k1+1),p=s+this.k1*(1-this.b+this.b*(a/this.avgDocLength));o+=i*(l/p)}return o}toSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category}}},kx=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"])});var ot,Il=g(()=>{"use strict";c();ot=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())}}});function Fe(){return{name:nt.name,displayName:nt.displayName,description:nt.description,parameters:nt.parameters,category:nt.category}}function rt(r){return r===je}var je,nt,Ll=g(()=>{"use strict";c();je="tool.search",nt={name:je,displayName:"Search Tools",category:"meta",description:`Search for available tools by keyword or natural language query.
44
+ Use this to discover tools before using them.
45
+ Examples: "file operations", "web scraping", "run command", "http request"
46
+
47
+ Returns a list of matching tools with their names, descriptions, and parameters.
48
+ 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 Or(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=Px[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(`
49
+ `)}var Px,jl=g(()=>{"use strict";c();Px={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"}});var Tn=g(()=>{"use strict";c();Nl();Il();Ll();jl()});var Fl,oe,xn=g(()=>{"use strict";c();Fl={enabled:!1,alwaysLoadedTools:[],alwaysLoadedCategories:[],searchResultLimit:5,cacheDiscoveredTools:!0},oe={enabled:!0,autoExecute:!0,maxToolRounds:5,toolChoicePolicy:"auto",resultMaxChars:2e4,enabledTools:[],enabledToolCategories:[],toolSearch:Fl}});function Wl(r){if(!r)return;let e=r.toLowerCase();if(e in Us)return e;console.warn(`[Toolpack Warning] Invalid log level "${r}". Falling back to "info".`)}function Ul(r){if(r?.enabled!==void 0&&(Pt=r.enabled),r?.filePath&&(ve=r.filePath),r?.level&&(vn=Wl(r.level)||"info"),process.env.TOOLPACK_SDK_LOG_ENABLED!==void 0&&(Pt=process.env.TOOLPACK_SDK_LOG_ENABLED==="true"),process.env.TOOLPACK_SDK_LOG_FILE&&(ve=process.env.TOOLPACK_SDK_LOG_FILE,Pt=!0),process.env.TOOLPACK_SDK_LOG_LEVEL&&(vn=Wl(process.env.TOOLPACK_SDK_LOG_LEVEL)||vn),process.env.TOOLPACK_SDK_LOG_CONSOLE!==void 0&&(Gs=process.env.TOOLPACK_SDK_LOG_CONSOLE==="true"),r?.console!==void 0&&process.env.TOOLPACK_SDK_LOG_CONSOLE===void 0&&(Gs=r.console),Pt)try{ve=(0,qe.isAbsolute)(ve)?ve:(0,qe.resolve)(process.cwd(),ve),(0,Cn.mkdirSync)((0,qe.dirname)(ve),{recursive:!0}),(0,Cn.appendFileSync)(ve,`[${new Date().toISOString()}] [INFO] [Logger] initialized level=${vn} file=${ve}
50
+ `)}catch(e){console.warn(`[Toolpack Warning] Failed to initialize log file "${ve}": ${e.message}`),Pt=!1}}function it(r){return Pt?Us[r]<=Us[vn]:!1}function Sn(r,e){if(!it(r))return;let o=`[${new Date().toISOString()}] [${r.toUpperCase()}] ${Gl(e)}`;(0,Cn.appendFileSync)(ve,o+`
51
+ `),Gs&&(r==="error"?console.error:r==="warn"?console.warn:console.log)(o)}function me(r){Sn("error",r)}function L(r){Sn("warn",r)}function P(r){Sn("info",r)}function h(r){Sn("debug",r)}function We(r){Sn("trace",r)}function Gl(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=Gl(t);return o.length<=e?o:`${o.slice(0,e)}\u2026`}catch{return"[Unserializable]"}}function ne(r,e,t){it("debug")&&(h(`[${e}][${r}] Messages (${t.length}):`),t.forEach((o,n)=>{h(`[${e}][${r}] #${n} role=${o?.role} content=${O(o?.content,300)}`)}))}var Cn,qe,Us,Pt,vn,ve,Gs,k=g(()=>{"use strict";c();Cn=require("fs"),qe=require("path"),Us={error:0,warn:1,info:2,debug:3,trace:4},Pt=!1,vn="info",ve=(0,qe.join)(process.cwd(),"toolpack-sdk.log"),Gs=!1});var Pn={};X(Pn,{fetchUrlAsBase64:()=>Js,getMimeType:()=>Bs,isDataUri:()=>zs,normalizeImagePart:()=>Yl,parseDataUri:()=>Hs,readFileAsBase64:()=>Ks,toDataUri:()=>Xl});function Bs(r){let e=Ql.extname(r).toLowerCase();return _x[e]||"application/octet-stream"}function zs(r){return r.startsWith("data:")}function Hs(r){let e=r.match(/^data:(.*?);base64,(.+)$/);return e?{mimeType:e[1],data:e[2]}:null}function Xl(r,e){return`data:${e};base64,${r}`}async function Ks(r){try{return{data:(await Vl.readFile(r)).toString("base64"),mimeType:Bs(r)}}catch(e){throw new I(`Failed to read image file: ${r}`,e)}}async function Js(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 j(`Failed to download image from URL: ${r}`,"FETCH_ERROR",500,e)}}async function Yl(r){if(r.type==="image_data")return{data:r.image_data.data,mimeType:r.image_data.mimeType};if(r.type==="image_file")return await Ks(r.image_file.path);if(r.type==="image_url"){let e=r.image_url.url;if(zs(e)){let t=Hs(e);if(!t)throw new I(`Malformed data URI provided in image_url: ${e.substring(0,50)}...`);return t}return await Js(e)}throw new I(`Unknown ImagePart type: ${r.type}`)}var Vl,Ql,_x,_t=g(()=>{"use strict";c();Vl=T(require("fs/promises"),1),Ql=T(require("path"),1);pe();_x={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".heic":"image/heic",".heif":"image/heif"}});var dc,uc,fc,gc,hc,yc=g(()=>{"use strict";c();dc="fs.read_file",uc="Read File",fc="Read the contents of a file at the given path. Returns the file content as a string.",gc="filesystem",hc={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path"]}});async function Rx(r){let e=r.path,t=r.encoding||"utf-8";if(h(`[fs.read-file] execute path="${e}" encoding=${t}`),!e)throw new Error("path is required");if(!$t.existsSync(e))throw new Error(`File not found: ${e}`);if($t.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);return $t.readFileSync(e,t)}var $t,Et,ni=g(()=>{"use strict";c();$t=T(require("fs"),1);yc();k();Et={name:dc,displayName:uc,description:fc,parameters:hc,category:gc,execute:Rx}});var bc,wc,Tc,xc,vc,Cc=g(()=>{"use strict";c();bc="fs.write_file",wc="Write File",Tc="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.",xc="filesystem",vc={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to write"},content:{type:"string",description:"Content to write to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});async function $x(r){let e=r.path,t=r.content,o=r.encoding||"utf-8";if(h(`[fs.write-file] execute path="${e}" encoding=${o} content_len=${t?.length??0}`),!e)throw new Error("path is required");if(t==null)throw new Error("content is required");let n=Sc.dirname(e);return Dt.existsSync(n)||Dt.mkdirSync(n,{recursive:!0}),Dt.writeFileSync(e,t,o),`File written successfully: ${e} (${Buffer.byteLength(t,o)} bytes)`}var Dt,Sc,Mt,ri=g(()=>{"use strict";c();Dt=T(require("fs"),1),Sc=T(require("path"),1);Cc();k();Mt={name:bc,displayName:wc,description:Tc,parameters:vc,category:xc,execute:$x,confirmation:{level:"high",reason:"This will overwrite the entire file contents.",showArgs:["path"]}}});var kc,Pc,_c,Rc,$c,Ec=g(()=>{"use strict";c();kc="fs.append_file",Pc="Append File",_c="Append content to the end of a file. Creates the file if it does not exist.",Rc="filesystem",$c={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to append to"},content:{type:"string",description:"Content to append to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});async function Ex(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=Dc.dirname(e);return Ot.existsSync(n)||Ot.mkdirSync(n,{recursive:!0}),Ot.appendFileSync(e,t,o),`Content appended to: ${e} (${Buffer.byteLength(t,o)} bytes appended)`}var Ot,Dc,At,si=g(()=>{"use strict";c();Ot=T(require("fs"),1),Dc=T(require("path"),1);Ec();At={name:kc,displayName:Pc,description:_c,parameters:$c,category:Rc,execute:Ex,confirmation:{level:"medium",reason:"This will modify the file by appending content.",showArgs:["path"]}}});var Mc,Oc,Ac,Nc,Ic,Lc=g(()=>{"use strict";c();Mc="fs.delete_file",Oc="Delete File",Ac="Remove/delete a file from the filesystem. Does not delete directories.",Nc="filesystem",Ic={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to delete"}},required:["path"]}});async function Dx(r){let e=r.path;if(h(`[fs.delete-file] execute path="${e}"`),!e)throw new Error("path is required");if(!Nt.existsSync(e))throw new Error(`File not found: ${e}`);if(Nt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}. Use a different tool to remove directories.`);return Nt.unlinkSync(e),`File deleted successfully: ${e}`}var Nt,It,ii=g(()=>{"use strict";c();Nt=T(require("fs"),1);Lc();k();It={name:Mc,displayName:Oc,description:Ac,parameters:Ic,category:Nc,execute:Dx,confirmation:{level:"high",reason:"This will permanently delete the file. This action cannot be undone.",showArgs:["path"]}}});var jc,Fc,qc,Wc,Uc,Gc=g(()=>{"use strict";c();jc="fs.exists",Fc="Exists",qc="Check if a file or directory exists at the given path. Returns true or false.",Wc="filesystem",Uc={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to check"}},required:["path"]}});async function Mx(r){let e=r.path;if(!e)throw new Error("path is required");let t=Bc.existsSync(e);return JSON.stringify({exists:t,path:e})}var Bc,Lt,ai=g(()=>{"use strict";c();Bc=T(require("fs"),1);Gc();Lt={name:jc,displayName:Fc,description:qc,parameters:Uc,category:Wc,execute:Mx}});var zc,Hc,Kc,Jc,Vc,Qc=g(()=>{"use strict";c();zc="fs.stat",Hc="Stat",Kc="Get file or directory information including size, type, and modification date.",Jc="filesystem",Vc={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to get info for"}},required:["path"]}});async function Ox(r){let e=r.path;if(!e)throw new Error("path is required");if(!qr.existsSync(e))throw new Error(`Path not found: ${e}`);let t=qr.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 qr,jt,li=g(()=>{"use strict";c();qr=T(require("fs"),1);Qc();jt={name:zc,displayName:Hc,description:Kc,parameters:Vc,category:Jc,execute:Ox}});var Xc,Yc,Zc,ep,tp,op=g(()=>{"use strict";c();Xc="fs.list_dir",Yc="List Directory",Zc="List files and directories at the given path. Optionally recurse into subdirectories.",ep="filesystem",tp={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to list"},recursive:{type:"boolean",description:"Whether to list recursively (default: false)",default:!1}},required:["path"]}});function rp(r,e,t,o=""){let n=ct.readdirSync(r,{withFileTypes:!0});for(let s of n){let i=np.join(r,s.name),a=o?`${o}/${s.name}`:s.name;if(s.isDirectory())t.push({name:a,type:"directory",size:0}),e&&rp(i,!0,t,a);else if(s.isFile()){let l=ct.statSync(i);t.push({name:a,type:"file",size:l.size})}}}async function Ax(r){let e=r.path,t=r.recursive===!0;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 n=[];return rp(e,t,n),JSON.stringify(n,null,2)}var ct,np,Ft,ci=g(()=>{"use strict";c();ct=T(require("fs"),1),np=T(require("path"),1);op();Ft={name:Xc,displayName:Yc,description:Zc,parameters:tp,category:ep,execute:Ax}});var sp,ip,ap,lp,cp,pp=g(()=>{"use strict";c();sp="fs.create_dir",ip="Create Directory",ap="Create a directory at the given path. Creates parent directories recursively if they do not exist.",lp="filesystem",cp={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to create"},recursive:{type:"boolean",description:"Create parent directories if they do not exist (default: true)",default:!0}},required:["path"]}});async function Nx(r){let e=r.path,t=r.recursive!==!1;if(!e)throw new Error("path is required");if(qt.existsSync(e)){if(qt.statSync(e).isDirectory())return`Directory already exists: ${e}`;throw new Error(`Path exists but is not a directory: ${e}`)}return qt.mkdirSync(e,{recursive:t}),`Directory created: ${e}`}var qt,Wt,pi=g(()=>{"use strict";c();qt=T(require("fs"),1);pp();Wt={name:sp,displayName:ip,description:ap,parameters:cp,category:lp,execute:Nx}});var mp,dp,up,fp,gp,hp=g(()=>{"use strict";c();mp="fs.move",dp="Move",up="Move or rename a file or directory from one path to another.",fp="filesystem",gp={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});async function Ix(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(!pt.existsSync(e))throw new Error(`Source not found: ${e}`);let o=yp.dirname(t);return pt.existsSync(o)||pt.mkdirSync(o,{recursive:!0}),pt.renameSync(e,t),`Moved: ${e} \u2192 ${t}`}var pt,yp,Ut,mi=g(()=>{"use strict";c();pt=T(require("fs"),1),yp=T(require("path"),1);hp();Ut={name:mp,displayName:dp,description:up,parameters:gp,category:fp,execute:Ix,confirmation:{level:"high",reason:"This will move/rename the file or directory, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var bp,wp,Tp,xp,vp,Cp=g(()=>{"use strict";c();bp="fs.copy",wp="Copy",Tp="Copy a file or directory from one path to another. Recursively copies directories.",xp="filesystem",vp={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});function Sp(r,e){if(de.statSync(r).isDirectory()){de.existsSync(e)||de.mkdirSync(e,{recursive:!0});let o=de.readdirSync(r);for(let n of o)Sp(An.join(r,n),An.join(e,n))}else de.copyFileSync(r,e)}async function Lx(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(!de.existsSync(e))throw new Error(`Source not found: ${e}`);let o=An.dirname(t);return de.existsSync(o)||de.mkdirSync(o,{recursive:!0}),Sp(e,t),`Copied ${de.statSync(e).isDirectory()?"directory":"file"}: ${e} \u2192 ${t}`}var de,An,Gt,di=g(()=>{"use strict";c();de=T(require("fs"),1),An=T(require("path"),1);Cp();Gt={name:bp,displayName:wp,description:Tp,parameters:vp,category:xp,execute:Lx,confirmation:{level:"medium",reason:"This will copy files or directories, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var kp,Pp,_p,Rp,$p,Ep=g(()=>{"use strict";c();kp="fs.read_file_range",Pp="Read File Range",_p="Read a specific range of lines from a file. Useful for reading portions of large files without loading the entire content.",Rp="filesystem",$p={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},start_line:{type:"integer",description:"Start line number (1-indexed)"},end_line:{type:"integer",description:"End line number (1-indexed, inclusive)"}},required:["path","start_line","end_line"]}});async function jx(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(!Bt.existsSync(e))throw new Error(`File not found: ${e}`);if(Bt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let i=Bt.readFileSync(e,"utf-8").split(`
52
+ `),a=i.length,l=Math.min(t,a),p=Math.min(o,a),d=i.slice(l-1,p).map((f,b)=>`${l+b}: ${f}`).join(`
47
53
  `);return`Lines ${l}-${p} of ${a} total:
48
- ${u}`}var Ut,Gt,ri=g(()=>{"use strict";c();Ut=T(require("fs"),1);lp();Gt={name:np,displayName:rp,description:sp,parameters:ap,category:ip,execute:BT}});var cp,pp,mp,dp,up,fp=g(()=>{"use strict";c();cp="fs.search",pp="Search",mp="Search for text in files within a directory. Returns matching lines with file paths and line numbers.",dp="filesystem",up={type:"object",properties:{path:{type:"string",description:"Directory path to search in"},query:{type:"string",description:"Text or pattern to search for"},recursive:{type:"boolean",description:"Search recursively in subdirectories (default: true)",default:!0},max_results:{type:"integer",description:"Maximum number of matching lines to return (default: 50)",default:50},regex:{type:"boolean",description:"Treat query as a regular expression (default: false)",default:!1},case_sensitive:{type:"boolean",description:"Perform case-sensitive search. If false, search is case-insensitive (default: false)",default:!1}},required:["path","query"]}});function zT(r,e,t,o){try{let s=We.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 hp(r,e,t,o,n){let s=We.readdirSync(r,{withFileTypes:!0});for(let i of s){if(o.length>=n)break;let a=gp.join(r,i.name);i.isDirectory()&&t?hp(a,e,!0,o,n):i.isFile()&&zT(a,e,o,n)}}async function HT(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(h(`[fs.search] execute path="${e}" query="${t}" recursive=${o} regex=${s} caseSensitive=${i}`),!e)throw new Error("path is required");if(!t)throw new Error("query is required");let a=t;if(s||!i){let u=t;s||(u=u.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));let f=i?"":"i";a=new RegExp(u,f)}if(!We.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!We.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let p=[];if(hp(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 We,gp,Bt,si=g(()=>{"use strict";c();We=T(require("fs"),1),gp=T(require("path"),1);fp();k();Bt={name:cp,displayName:pp,description:mp,parameters:up,category:dp,execute:HT}});var yp,bp,wp,Tp,xp,vp=g(()=>{"use strict";c();yp="fs.replace_in_file",bp="Replace In File",wp="Find and replace text in a file. Returns the number of replacements made.",Tp="filesystem",xp={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path"},search:{type:"string",description:"Text to search for"},replace:{type:"string",description:"Text to replace with"}},required:["path","search","replace"]}});async function KT(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(!Ue.existsSync(e))throw new Error(`File not found: ${e}`);if(Ue.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let s=Ue.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 l=s.split(t).join(o);return Ue.writeFileSync(e,l,"utf-8"),`Replaced ${i} occurrence(s) in ${e}`}var Ue,zt,ii=g(()=>{"use strict";c();Ue=T(require("fs"),1);vp();zt={name:yp,displayName:bp,description:wp,parameters:xp,category:Tp,execute:KT,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 Cp,Pp,kp,Sp,Rp,_p=g(()=>{"use strict";c();Cp="fs.tree",Pp="Tree",kp="Get a tree representation of a directory structure. Useful for understanding project layout at a glance.",Sp="filesystem",Rp={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path"},depth:{type:"integer",description:"Maximum depth to traverse (default: 3)",default:3}},required:["path"]}});function $p(r,e,t,o,n){if(t>o)return;let i=Ht.readdirSync(r,{withFileTypes:!0}).sort((a,l)=>a.isDirectory()&&!l.isDirectory()?-1:!a.isDirectory()&&l.isDirectory()?1:a.name.localeCompare(l.name));for(let a=0;a<i.length;a++){let l=i[a],p=a===i.length-1,m=p?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",u=p?" ":"\u2502 ";l.isDirectory()?(n.push(`${e}${m}${l.name}/`),$p(kr.join(r,l.name),e+u,t+1,o,n)):n.push(`${e}${m}${l.name}`)}}async function JT(r){let e=r.path,t=r.depth||3;if(!e)throw new Error("path is required");if(!Ht.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Ht.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let s=[`${kr.basename(e)}/`];return $p(e,"",1,t,s),s.join(`
51
- `)}var Ht,kr,Kt,ai=g(()=>{"use strict";c();Ht=T(require("fs"),1),kr=T(require("path"),1);_p();Kt={name:Cp,displayName:Pp,description:kp,parameters:Rp,category:Sp,execute:JT}});var Ep,Dp,Mp,Op,Np,Ap=g(()=>{"use strict";c();Ep="fs.glob",Dp="Glob Pattern Match",Mp='Find files matching glob patterns (e.g., "**/*.ts", "src/**/*.test.js")',Op="filesystem",Np={type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files (e.g., "**/*.ts", "src/**/*.json")'},cwd:{type:"string",description:"Root directory to search from (defaults to current working directory)"},ignore:{type:"array",items:{type:"string"},description:'Patterns to ignore (e.g., ["node_modules/**", "dist/**"])'},onlyFiles:{type:"boolean",description:"Return only files, not directories (default: true)"},onlyDirectories:{type:"boolean",description:"Return only directories, not files (default: false)"},absolute:{type:"boolean",description:"Return absolute paths instead of relative (default: false)"}},required:["pattern"]}});async function VT(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 l=await(0,Ip.default)(a,{cwd:t||process.cwd(),ignore:o||["node_modules/**",".git/**"],onlyFiles:n,onlyDirectories:s,absolute:i,dot:!0});return JSON.stringify({pattern:e,files:l,count:l.length},null,2)}catch(l){throw new Error(`Failed to glob pattern "${e}": ${l.message}`)}}var Ip,Jt,li=g(()=>{"use strict";c();Ip=T(require("fast-glob"),1);Ap();Jt={name:Ep,displayName:Dp,description:Mp,parameters:Np,category:Op,execute:VT}});var Lp,jp,Fp,qp,Wp,Up=g(()=>{"use strict";c();Lp="fs.delete_dir",jp="Delete Directory",Fp="Delete a directory and all its contents recursively",qp="filesystem",Wp={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to the directory to delete"},force:{type:"boolean",description:"Force deletion even if directory is not empty (default: true)"}},required:["path"]}});async function QT(r){let e=r.path,t=r.force!==!1;if(!e)throw new Error("path is required");if(!(0,Sr.existsSync)(e))throw new Error(`Directory does not exist: ${e}`);if(!(0,Sr.statSync)(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);try{return await(0,Gp.rm)(e,{recursive:!0,force:t}),`Directory deleted successfully: ${e}`}catch(n){throw new Error(`Failed to delete directory "${e}": ${n.message}`)}}var Gp,Sr,Vt,ci=g(()=>{"use strict";c();Gp=require("fs/promises"),Sr=require("fs");Up();Vt={name:Lp,displayName:jp,description:Fp,parameters:Wp,category:qp,execute:QT,confirmation:{level:"high",reason:"This will recursively delete the directory and all its contents. This action cannot be undone.",showArgs:["path"]}}});var Bp,zp,Hp,Kp,Jp,Vp=g(()=>{"use strict";c();Bp="fs.batch_read",zp="Batch Read Files",Hp="Read multiple files efficiently in one operation. Returns content for each file or error if read fails.",Kp="filesystem",Jp={type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Array of file paths to read"},encoding:{type:"string",description:"File encoding (default: utf-8)"},continueOnError:{type:"boolean",description:"Continue reading other files if one fails (default: true)"}},required:["paths"]}});async function XT(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 l=await(0,Qp.readFile)(a,t);n.push({path:a,content:l,success:!0}),s++}catch(l){let p=l.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 Qp,Qt,pi=g(()=>{"use strict";c();Qp=require("fs/promises");Vp();Qt={name:Bp,displayName:zp,description:Hp,parameters:Jp,category:Kp,execute:XT}});var Xp,Yp,Zp,em,tm,om=g(()=>{"use strict";c();Xp="fs.batch_write",Yp="Batch Write Files",Zp="Write multiple files atomically in one operation. If atomic mode is enabled, all writes succeed or all are rolled back on failure.",em="filesystem",tm={type:"object",properties:{files:{type:"array",items:{type:"object",properties:{path:{type:"string"},content:{type:"string"}}},description:"Array of files to write, each with path and content"},encoding:{type:"string",description:"File encoding (default: utf-8)"},atomic:{type:"boolean",description:"Atomic mode: rollback all writes if any fails (default: true)"},createDirs:{type:"boolean",description:"Create parent directories if they don't exist (default: true)"}},required:["files"]}});async function YT(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 l=(0,Rr.resolve)(a.path);if(o){let p=(0,mi.existsSync)(l),m={path:l,existed:p};p&&(m.originalContent=await(0,Ne.readFile)(l,t)),s.push(m)}if(n){let p=(0,Rr.dirname)(l);await(0,Ne.mkdir)(p,{recursive:!0})}await(0,Ne.writeFile)(l,a.content,t),i.push(l)}return JSON.stringify({success:!0,written:i.length,files:i},null,2)}catch(a){if(o&&s.length>0){for(let l of s)try{l.existed&&l.originalContent!==void 0?await(0,Ne.writeFile)(l.path,l.originalContent,t):!l.existed&&(0,mi.existsSync)(l.path)&&await(0,Ne.unlink)(l.path)}catch{}throw new Error(`Batch write failed and rolled back: ${a.message}`)}throw new Error(`Batch write failed: ${a.message}`)}}var Ne,Rr,mi,Xt,di=g(()=>{"use strict";c();Ne=require("fs/promises"),Rr=require("path"),mi=require("fs");om();Xt={name:Xp,displayName:Yp,description:Zp,parameters:tm,category:em,execute:YT,confirmation:{level:"high",reason:"This will overwrite multiple files at once.",showArgs:["files"]}}});var nm={};le(nm,{fsAppendFileTool:()=>Mt,fsBatchReadTool:()=>Qt,fsBatchWriteTool:()=>Xt,fsCopyTool:()=>Wt,fsCreateDirTool:()=>Ft,fsDeleteDirTool:()=>Vt,fsDeleteFileTool:()=>Nt,fsExistsTool:()=>At,fsGlobTool:()=>Jt,fsListDirTool:()=>Lt,fsMoveTool:()=>qt,fsReadFileRangeTool:()=>Gt,fsReadFileTool:()=>_t,fsReplaceInFileTool:()=>zt,fsSearchTool:()=>Bt,fsStatTool:()=>It,fsToolsProject:()=>ui,fsTreeTool:()=>Kt,fsWriteFileTool:()=>Et});var ui,fi=g(()=>{"use strict";c();Js();Vs();Qs();Xs();Ys();Zs();ei();ti();oi();ni();ri();si();ii();ai();li();ci();pi();di();Js();Vs();Qs();Xs();Ys();Zs();ei();ti();oi();ni();ri();si();ii();ai();li();ci();pi();di();ui={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:[_t,Et,Mt,Nt,At,It,Lt,Ft,qt,Wt,Gt,Bt,zt,Kt,Jt,Vt,Qt,Xt],dependencies:{"fast-glob":"^3.3.2"}}});var rm,sm,im,am,lm,cm=g(()=>{"use strict";c();rm="exec.run",sm="Run",im="Execute a command directly (without shell) and return its output. Use exec.run_shell for pipes, redirects, or shell features.",am="execution",lm={type:"object",properties:{command:{type:"string",description:"The command to execute"},cwd:{type:"string",description:"Working directory for the command (optional)"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["command"]}});async function ZT(r){let e=r.command,t=r.cwd,o=r.timeout||3e4;if(!e)throw new Error("command is required");h(`[exec.run] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${o}ms`);try{return(0,pm.execSync)(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"}):
54
+ ${d}`}var Bt,zt,ui=g(()=>{"use strict";c();Bt=T(require("fs"),1);Ep();zt={name:kp,displayName:Pp,description:_p,parameters:$p,category:Rp,execute:jx}});var Dp,Mp,Op,Ap,Np,Ip=g(()=>{"use strict";c();Dp="fs.search",Mp="Search",Op="Search for text in files within a directory. Returns matching lines with file paths and line numbers.",Ap="filesystem",Np={type:"object",properties:{path:{type:"string",description:"Directory path to search in"},query:{type:"string",description:"Text or pattern to search for"},recursive:{type:"boolean",description:"Search recursively in subdirectories (default: true)",default:!0},max_results:{type:"integer",description:"Maximum number of matching lines to return (default: 50)",default:50},regex:{type:"boolean",description:"Treat query as a regular expression (default: false)",default:!1},case_sensitive:{type:"boolean",description:"Perform case-sensitive search. If false, search is case-insensitive (default: false)",default:!1}},required:["path","query"]}});function Fx(r,e,t,o){try{let s=Be.readFileSync(r,"utf-8").split(`
55
+ `);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 jp(r,e,t,o,n){let s=Be.readdirSync(r,{withFileTypes:!0});for(let i of s){if(o.length>=n)break;let a=Lp.join(r,i.name);i.isDirectory()&&t?jp(a,e,!0,o,n):i.isFile()&&Fx(a,e,o,n)}}async function qx(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(h(`[fs.search] execute path="${e}" query="${t}" recursive=${o} regex=${s} caseSensitive=${i}`),!e)throw new Error("path is required");if(!t)throw new Error("query is required");let a=t;if(s||!i){let d=t;s||(d=d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));let f=i?"":"i";a=new RegExp(d,f)}if(!Be.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Be.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let p=[];if(jp(e,a,o,p,n),p.length===0)return`No matches found for "${t}" in ${e}`;let m=p.length>=n?`
56
+ (results capped at ${n})`:"";return JSON.stringify(p,null,2)+m}var Be,Lp,Ht,fi=g(()=>{"use strict";c();Be=T(require("fs"),1),Lp=T(require("path"),1);Ip();k();Ht={name:Dp,displayName:Mp,description:Op,parameters:Np,category:Ap,execute:qx}});var Fp,qp,Wp,Up,Gp,Bp=g(()=>{"use strict";c();Fp="fs.replace_in_file",qp="Replace In File",Wp="Find and replace text in a file. Returns the number of replacements made.",Up="filesystem",Gp={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path"},search:{type:"string",description:"Text to search for"},replace:{type:"string",description:"Text to replace with"}},required:["path","search","replace"]}});async function Wx(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(!ze.existsSync(e))throw new Error(`File not found: ${e}`);if(ze.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let s=ze.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 l=s.split(t).join(o);return ze.writeFileSync(e,l,"utf-8"),`Replaced ${i} occurrence(s) in ${e}`}var ze,Kt,gi=g(()=>{"use strict";c();ze=T(require("fs"),1);Bp();Kt={name:Fp,displayName:qp,description:Wp,parameters:Gp,category:Up,execute:Wx,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 zp,Hp,Kp,Jp,Vp,Qp=g(()=>{"use strict";c();zp="fs.tree",Hp="Tree",Kp="Get a tree representation of a directory structure. Useful for understanding project layout at a glance.",Jp="filesystem",Vp={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path"},depth:{type:"integer",description:"Maximum depth to traverse (default: 3)",default:3}},required:["path"]}});function Xp(r,e,t,o,n){if(t>o)return;let i=Jt.readdirSync(r,{withFileTypes:!0}).sort((a,l)=>a.isDirectory()&&!l.isDirectory()?-1:!a.isDirectory()&&l.isDirectory()?1:a.name.localeCompare(l.name));for(let a=0;a<i.length;a++){let l=i[a],p=a===i.length-1,m=p?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",d=p?" ":"\u2502 ";l.isDirectory()?(n.push(`${e}${m}${l.name}/`),Xp(Wr.join(r,l.name),e+d,t+1,o,n)):n.push(`${e}${m}${l.name}`)}}async function Ux(r){let e=r.path,t=r.depth||3;if(!e)throw new Error("path is required");if(!Jt.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Jt.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let s=[`${Wr.basename(e)}/`];return Xp(e,"",1,t,s),s.join(`
57
+ `)}var Jt,Wr,Vt,hi=g(()=>{"use strict";c();Jt=T(require("fs"),1),Wr=T(require("path"),1);Qp();Vt={name:zp,displayName:Hp,description:Kp,parameters:Vp,category:Jp,execute:Ux}});var Yp,Zp,em,tm,om,nm=g(()=>{"use strict";c();Yp="fs.glob",Zp="Glob Pattern Match",em='Find files matching glob patterns (e.g., "**/*.ts", "src/**/*.test.js")',tm="filesystem",om={type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files (e.g., "**/*.ts", "src/**/*.json")'},cwd:{type:"string",description:"Root directory to search from (defaults to current working directory)"},ignore:{type:"array",items:{type:"string"},description:'Patterns to ignore (e.g., ["node_modules/**", "dist/**"])'},onlyFiles:{type:"boolean",description:"Return only files, not directories (default: true)"},onlyDirectories:{type:"boolean",description:"Return only directories, not files (default: false)"},absolute:{type:"boolean",description:"Return absolute paths instead of relative (default: false)"}},required:["pattern"]}});async function Gx(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 l=await(0,rm.default)(a,{cwd:t||process.cwd(),ignore:o||["node_modules/**",".git/**"],onlyFiles:n,onlyDirectories:s,absolute:i,dot:!0});return JSON.stringify({pattern:e,files:l,count:l.length},null,2)}catch(l){throw new Error(`Failed to glob pattern "${e}": ${l.message}`)}}var rm,Qt,yi=g(()=>{"use strict";c();rm=T(require("fast-glob"),1);nm();Qt={name:Yp,displayName:Zp,description:em,parameters:om,category:tm,execute:Gx}});var sm,im,am,lm,cm,pm=g(()=>{"use strict";c();sm="fs.delete_dir",im="Delete Directory",am="Delete a directory and all its contents recursively",lm="filesystem",cm={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to the directory to delete"},force:{type:"boolean",description:"Force deletion even if directory is not empty (default: true)"}},required:["path"]}});async function Bx(r){let e=r.path,t=r.force!==!1;if(!e)throw new Error("path is required");if(!(0,Ur.existsSync)(e))throw new Error(`Directory does not exist: ${e}`);if(!(0,Ur.statSync)(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);try{return await(0,mm.rm)(e,{recursive:!0,force:t}),`Directory deleted successfully: ${e}`}catch(n){throw new Error(`Failed to delete directory "${e}": ${n.message}`)}}var mm,Ur,Xt,bi=g(()=>{"use strict";c();mm=require("fs/promises"),Ur=require("fs");pm();Xt={name:sm,displayName:im,description:am,parameters:cm,category:lm,execute:Bx,confirmation:{level:"high",reason:"This will recursively delete the directory and all its contents. This action cannot be undone.",showArgs:["path"]}}});var dm,um,fm,gm,hm,ym=g(()=>{"use strict";c();dm="fs.batch_read",um="Batch Read Files",fm="Read multiple files efficiently in one operation. Returns content for each file or error if read fails.",gm="filesystem",hm={type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Array of file paths to read"},encoding:{type:"string",description:"File encoding (default: utf-8)"},continueOnError:{type:"boolean",description:"Continue reading other files if one fails (default: true)"}},required:["paths"]}});async function zx(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 l=await(0,bm.readFile)(a,t);n.push({path:a,content:l,success:!0}),s++}catch(l){let p=l.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 bm,Yt,wi=g(()=>{"use strict";c();bm=require("fs/promises");ym();Yt={name:dm,displayName:um,description:fm,parameters:hm,category:gm,execute:zx}});var wm,Tm,xm,vm,Cm,Sm=g(()=>{"use strict";c();wm="fs.batch_write",Tm="Batch Write Files",xm="Write multiple files atomically in one operation. If atomic mode is enabled, all writes succeed or all are rolled back on failure.",vm="filesystem",Cm={type:"object",properties:{files:{type:"array",items:{type:"object",properties:{path:{type:"string"},content:{type:"string"}}},description:"Array of files to write, each with path and content"},encoding:{type:"string",description:"File encoding (default: utf-8)"},atomic:{type:"boolean",description:"Atomic mode: rollback all writes if any fails (default: true)"},createDirs:{type:"boolean",description:"Create parent directories if they don't exist (default: true)"}},required:["files"]}});async function Hx(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 l=(0,Gr.resolve)(a.path);if(o){let p=(0,Ti.existsSync)(l),m={path:l,existed:p};p&&(m.originalContent=await(0,Ae.readFile)(l,t)),s.push(m)}if(n){let p=(0,Gr.dirname)(l);await(0,Ae.mkdir)(p,{recursive:!0})}await(0,Ae.writeFile)(l,a.content,t),i.push(l)}return JSON.stringify({success:!0,written:i.length,files:i},null,2)}catch(a){if(o&&s.length>0){for(let l of s)try{l.existed&&l.originalContent!==void 0?await(0,Ae.writeFile)(l.path,l.originalContent,t):!l.existed&&(0,Ti.existsSync)(l.path)&&await(0,Ae.unlink)(l.path)}catch{}throw new Error(`Batch write failed and rolled back: ${a.message}`)}throw new Error(`Batch write failed: ${a.message}`)}}var Ae,Gr,Ti,Zt,xi=g(()=>{"use strict";c();Ae=require("fs/promises"),Gr=require("path"),Ti=require("fs");Sm();Zt={name:wm,displayName:Tm,description:xm,parameters:Cm,category:vm,execute:Hx,confirmation:{level:"high",reason:"This will overwrite multiple files at once.",showArgs:["files"]}}});var km={};X(km,{fsAppendFileTool:()=>At,fsBatchReadTool:()=>Yt,fsBatchWriteTool:()=>Zt,fsCopyTool:()=>Gt,fsCreateDirTool:()=>Wt,fsDeleteDirTool:()=>Xt,fsDeleteFileTool:()=>It,fsExistsTool:()=>Lt,fsGlobTool:()=>Qt,fsListDirTool:()=>Ft,fsMoveTool:()=>Ut,fsReadFileRangeTool:()=>zt,fsReadFileTool:()=>Et,fsReplaceInFileTool:()=>Kt,fsSearchTool:()=>Ht,fsStatTool:()=>jt,fsToolsProject:()=>vi,fsTreeTool:()=>Vt,fsWriteFileTool:()=>Mt});var vi,Ci=g(()=>{"use strict";c();ni();ri();si();ii();ai();li();ci();pi();mi();di();ui();fi();gi();hi();yi();bi();wi();xi();ni();ri();si();ii();ai();li();ci();pi();mi();di();ui();fi();gi();hi();yi();bi();wi();xi();vi={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:[Et,Mt,At,It,Lt,jt,Ft,Wt,Ut,Gt,zt,Ht,Kt,Vt,Qt,Xt,Yt,Zt],dependencies:{"fast-glob":"^3.3.2"}}});var Pm,_m,Rm,$m,Em,Dm=g(()=>{"use strict";c();Pm="exec.run",_m="Run",Rm="Execute a command directly (without shell) and return its output. Use exec.run_shell for pipes, redirects, or shell features.",$m="execution",Em={type:"object",properties:{command:{type:"string",description:"The command to execute"},cwd:{type:"string",description:"Working directory for the command (optional)"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["command"]}});async function Kx(r){let e=r.command,t=r.cwd,o=r.timeout||3e4;if(!e)throw new Error("command is required");h(`[exec.run] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${o}ms`);try{return(0,Mm.execSync)(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"}):
52
58
  STDOUT:
53
59
  ${s}
54
60
  STDERR:
55
- ${i}`}}var pm,Yt,gi=g(()=>{"use strict";c();pm=require("child_process");cm();k();Yt={name:rm,displayName:sm,description:im,parameters:lm,category:am,execute:ZT,confirmation:{level:"high",reason:"This will execute a shell command on the host system.",showArgs:["command"]}}});var mm,dm,um,fm,gm,hm=g(()=>{"use strict";c();mm="exec.run_shell",dm="Run Shell",um="Execute a command through the system shell. Supports pipes, redirects, environment variable expansion, and other shell features.",fm="execution",gm={type:"object",properties:{command:{type:"string",description:"The shell command to execute (supports pipes, redirects, etc.)"},cwd:{type:"string",description:"Working directory for the command (optional)"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["command"]}});function ex(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function tx(r){let e=r.command,t=r.cwd,o=r.timeout||3e4;if(!e)throw new Error("command is required");h(`[exec.run-shell] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${o}ms`);try{return(0,ym.execSync)(e,{cwd:t,timeout:o,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],shell:ex()})||"(command completed with no output)"}catch(n){let s=n.stdout||"",i=n.stderr||"";return`Command failed (exit code ${n.status??"unknown"}):
61
+ ${i}`}}var Mm,eo,Si=g(()=>{"use strict";c();Mm=require("child_process");Dm();k();eo={name:Pm,displayName:_m,description:Rm,parameters:Em,category:$m,execute:Kx,confirmation:{level:"high",reason:"This will execute a shell command on the host system.",showArgs:["command"]}}});var Om,Am,Nm,Im,Lm,jm=g(()=>{"use strict";c();Om="exec.run_shell",Am="Run Shell",Nm="Execute a command through the system shell. Supports pipes, redirects, environment variable expansion, and other shell features.",Im="execution",Lm={type:"object",properties:{command:{type:"string",description:"The shell command to execute (supports pipes, redirects, etc.)"},cwd:{type:"string",description:"Working directory for the command (optional)"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["command"]}});function Jx(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function Vx(r){let e=r.command,t=r.cwd,o=r.timeout||3e4;if(!e)throw new Error("command is required");h(`[exec.run-shell] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${o}ms`);try{return(0,Fm.execSync)(e,{cwd:t,timeout:o,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],shell:Jx()})||"(command completed with no output)"}catch(n){let s=n.stdout||"",i=n.stderr||"";return`Command failed (exit code ${n.status??"unknown"}):
56
62
  STDOUT:
57
63
  ${s}
58
64
  STDERR:
59
- ${i}`}}var ym,Zt,hi=g(()=>{"use strict";c();ym=require("child_process");hm();k();Zt={name:mm,displayName:dm,description:um,parameters:gm,category:fm,execute:tx,confirmation:{level:"high",reason:"This will execute a shell command with explicit shell context.",showArgs:["command"]}}});function bm(r,e,t){let o=`proc_${ox++}`,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",()=>{}),_r.set(o,n),o}function $r(r){return _r.get(r)}function wm(r){let e=_r.get(r);if(!e)return!1;let t=e.process.exitCode===null;return t&&e.process.kill("SIGTERM"),t}function Tm(){return Array.from(_r.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 _r,ox,$n=g(()=>{"use strict";c();_r=new Map,ox=1});var xm,vm,Cm,Pm,km,Sm=g(()=>{"use strict";c();xm="exec.run_background",vm="Run Background",Cm="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.",Pm="execution",km={type:"object",properties:{command:{type:"string",description:"The command to run in the background"},cwd:{type:"string",description:"Working directory for the command (optional)"}},required:["command"]}});async function nx(r){let e=r.command,t=r.cwd;if(!e)throw new Error("command is required");if(h(`[exec.run-background] execute command="${e.substring(0,100)}" cwd=${t??"default"}`),!e)throw new Error("command is required");let o=(0,Rm.spawn)(e,[],{cwd:t,shell:!0,stdio:["ignore","pipe","pipe"],detached:!1}),n=bm(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 Rm,eo,yi=g(()=>{"use strict";c();Rm=require("child_process");$n();Sm();k();eo={name:xm,displayName:vm,description:Cm,parameters:km,category:Pm,execute:nx,confirmation:{level:"high",reason:"This will spawn a background process that runs unsupervised.",showArgs:["command"]}}});var _m,$m,Em,Dm,Mm,Om=g(()=>{"use strict";c();_m="exec.read_output",$m="Read Output",Em="Read stdout and stderr from a background process started with exec.run_background.",Dm="execution",Mm={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function rx(r){let e=r.process_id;if(!e)throw new Error("process_id is required");let t=$r(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 to,bi=g(()=>{"use strict";c();$n();Om();to={name:_m,displayName:$m,description:Em,parameters:Mm,category:Dm,execute:rx}});var Nm,Am,Im,Lm,jm,Fm=g(()=>{"use strict";c();Nm="exec.kill",Am="Kill",Im="Kill a background process started with exec.run_background.",Lm="execution",jm={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function sx(r){let e=r.process_id;if(!e)throw new Error("process_id is required");let t=$r(e);if(!t)throw new Error(`Process not found: ${e}`);return wm(e)?`Process ${e} (${t.command}) killed successfully.`:`Process ${e} (${t.command}) was already terminated (exit code: ${t.process.exitCode}).`}var oo,wi=g(()=>{"use strict";c();$n();Fm();oo={name:Nm,displayName:Am,description:Im,parameters:jm,category:Lm,execute:sx,confirmation:{level:"medium",reason:"This will terminate a running process.",showArgs:["process_id"]}}});var qm,Wm,Um,Gm,Bm,zm=g(()=>{"use strict";c();qm="exec.list_processes",Wm="List Processes",Um="List all managed background processes started with exec.run_background, including their status.",Gm="execution",Bm={type:"object",properties:{}}});async function ix(r){let e=Tm();return e.length===0?"No managed background processes.":JSON.stringify(e,null,2)}var no,Ti=g(()=>{"use strict";c();$n();zm();no={name:qm,displayName:Wm,description:Um,parameters:Bm,category:Gm,execute:ix}});var Hm={};le(Hm,{execKillTool:()=>oo,execListProcessesTool:()=>no,execReadOutputTool:()=>to,execRunBackgroundTool:()=>eo,execRunShellTool:()=>Zt,execRunTool:()=>Yt,execToolsProject:()=>xi});var xi,vi=g(()=>{"use strict";c();gi();hi();yi();bi();wi();Ti();gi();hi();yi();bi();wi();Ti();xi={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:[Yt,Zt,eo,to,oo,no],dependencies:{}}});var Km,Jm,Vm,Qm,Xm,Ym=g(()=>{"use strict";c();Km="system.info",Jm="Info",Vm="Get system information including OS, CPU, memory, and architecture.",Qm="system",Xm={type:"object",properties:{}}});async function ax(r){return h("[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 F,ro,Ci=g(()=>{"use strict";c();F=T(require("os"),1);Ym();k();ro={name:Km,displayName:Jm,description:Vm,parameters:Xm,category:Qm,execute:ax}});var Zm,ed,td,od,nd,rd=g(()=>{"use strict";c();Zm="system.env",ed="Environment",td="Get environment variable(s). If key is provided, returns that specific variable. Otherwise returns all environment variables.",od="system",nd={type:"object",properties:{key:{type:"string",description:"Specific environment variable name to get (optional, returns all if omitted)"}}}});async function lx(r){let e=r.key;if(h(`[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 so,Pi=g(()=>{"use strict";c();rd();k();so={name:Zm,displayName:ed,description:td,parameters:nd,category:od,execute:lx}});var sd,id,ad,ld,cd,pd=g(()=>{"use strict";c();sd="system.set_env",id="Set Environment",ad="Set an environment variable for the current session. Does not persist across restarts.",ld="system",cd={type:"object",properties:{key:{type:"string",description:"Environment variable name"},value:{type:"string",description:"Value to set"}},required:["key","value"]}});async function cx(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 io,ki=g(()=>{"use strict";c();pd();io={name:sd,displayName:id,description:ad,parameters:cd,category:ld,execute:cx,confirmation:{level:"medium",reason:"This will modify the process environment, affecting all subsequent operations.",showArgs:["key","value"]}}});var md,dd,ud,fd,gd,hd=g(()=>{"use strict";c();md="system.cwd",dd="Current Directory",ud="Get the current working directory of the process.",fd="system",gd={type:"object",properties:{}}});async function px(r){return h("[system.cwd] execute"),JSON.stringify({cwd:process.cwd()})}var ao,Si=g(()=>{"use strict";c();hd();k();ao={name:md,displayName:dd,description:ud,parameters:gd,category:fd,execute:px}});var yd,bd,wd,Td,xd,vd=g(()=>{"use strict";c();yd="system.disk_usage",bd="Disk Usage",wd="Get disk usage information for a given path or the root filesystem.",Td="system",xd={type:"object",properties:{path:{type:"string",description:"Path to check disk usage for (default: /)",default:"/"}}}});function Ri(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 mx(r){let t=r.path||(process.platform==="win32"?Pd.tmpdir():"/");t=Er.resolve(t);let o=process.platform==="win32";try{let n=Cd.statfsSync(t),s=BigInt(n.blocks)*BigInt(n.bsize),i=BigInt(n.bavail)*BigInt(n.bsize),a=BigInt(n.bfree)*BigInt(n.bsize),l=s-a,p=s>0?Number(l*BigInt(100)/s):0;return JSON.stringify({path:t,filesystem:"statfs",size:Ri(Number(s)),used:Ri(Number(l)),available:Ri(Number(i)),usePercent:`${p}%`,mountedOn:t},null,2)}catch(n){try{if(o){let l=Er.parse(t).root.replace(/\\$/,"")||"C:",p=`Get-PSDrive -Name ${l.replace(":","")} | Select-Object @{n='Drive';e={$_.Name+':'}},@{n='Used';e={$_.Used}},@{n='Free';e={$_.Free}},@{n='Total';e={$_.Used+$_.Free}} | ConvertTo-Json`,m=(0,_i.execSync)(p,{encoding:"utf-8",timeout:5e3,shell:"powershell.exe"}),u=JSON.parse(m.trim()),f=u.Total||0,b=u.Free||0,y=u.Used||0,w=f>0?Math.round(y/f*100):0;return JSON.stringify({path:t,filesystem:u.Name||"NTFS",size:`${(f/1024**3).toFixed(1)}G`,used:`${(y/1024**3).toFixed(1)}G`,available:`${(b/1024**3).toFixed(1)}G`,usePercent:`${w}%`,mountedOn:u.Drive||`${l}`},null,2)}let s=(0,_i.execSync)(`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 Cd,Pd,Er,_i,lo,$i=g(()=>{"use strict";c();Cd=T(require("fs"),1),Pd=T(require("os"),1),Er=T(require("path"),1),_i=require("child_process");vd();lo={name:yd,displayName:bd,description:wd,parameters:xd,category:Td,execute:mx}});var kd={};le(kd,{systemCwdTool:()=>ao,systemDiskUsageTool:()=>lo,systemEnvTool:()=>so,systemInfoTool:()=>ro,systemSetEnvTool:()=>io,systemToolsProject:()=>Ei});var Ei,Di=g(()=>{"use strict";c();Ci();Pi();ki();Si();$i();Ci();Pi();ki();Si();$i();Ei={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:[ro,so,io,ao,lo],dependencies:{}}});var Sd,Rd,_d,$d,Ed,Dd=g(()=>{"use strict";c();Sd="http.get",Rd="GET",_d="Make an HTTP GET request to a URL and return the response body.",$d="network",Ed={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 dx(r){let e=r.url,t=r.headers;if(h(`[http.get] execute url="${e}"`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=await fetch(e,{method:"GET",headers:t||{}}),n=await o.text(),s=`HTTP ${o.status} ${o.statusText}`;return o.ok?n.length>Md?`${s}
61
- ${n.substring(0,Md)}
65
+ ${i}`}}var Fm,to,ki=g(()=>{"use strict";c();Fm=require("child_process");jm();k();to={name:Om,displayName:Am,description:Nm,parameters:Lm,category:Im,execute:Vx,confirmation:{level:"high",reason:"This will execute a shell command with explicit shell context.",showArgs:["command"]}}});function qm(r,e,t){let o=`proc_${Qx++}`,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",()=>{}),Br.set(o,n),o}function oo(r){return Br.get(r)}function Wm(r){let e=Br.get(r);if(!e)return!1;let t=e.process.exitCode===null;return t&&e.process.kill("SIGTERM"),t}function Um(){return Array.from(Br.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 Br,Qx,no=g(()=>{"use strict";c();Br=new Map,Qx=1});var Gm,Bm,zm,Hm,Km,Jm=g(()=>{"use strict";c();Gm="exec.run_background",Bm="Run Background",zm="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.",Hm="execution",Km={type:"object",properties:{command:{type:"string",description:"The command to run in the background"},cwd:{type:"string",description:"Working directory for the command (optional)"}},required:["command"]}});async function Xx(r){let e=r.command,t=r.cwd;if(!e)throw new Error("command is required");if(h(`[exec.run-background] execute command="${e.substring(0,100)}" cwd=${t??"default"}`),!e)throw new Error("command is required");let o=(0,Vm.spawn)(e,[],{cwd:t,shell:!0,stdio:["ignore","pipe","pipe"],detached:!1}),n=qm(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 Vm,ro,Pi=g(()=>{"use strict";c();Vm=require("child_process");no();Jm();k();ro={name:Gm,displayName:Bm,description:zm,parameters:Km,category:Hm,execute:Xx,confirmation:{level:"medium",reason:"This will spawn a background process that runs unsupervised.",showArgs:["command"]}}});var Qm,Xm,Ym,Zm,ed,td=g(()=>{"use strict";c();Qm="exec.run_blocking",Xm="Run Blocking",Ym="Execute a shell command and wait for it to finish naturally \u2014 no timeout. Use this for commands that take variable or unknown time (e.g. npm install, builds, tests). Returns exit code, stdout, and stderr when the process exits. For processes that never exit (servers, watchers), use exec.run_background instead.",Zm="execution",ed={type:"object",properties:{command:{type:"string",description:"The shell command to execute. Supports pipes, redirects, and shell features."},cwd:{type:"string",description:"Working directory for the command (optional). Defaults to the current working directory."}},required:["command"]}});function Yx(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function Zx(r){let e=r.command,t=r.cwd;if(!e)throw new Error("command is required");return h(`[exec.run-blocking] execute command="${e.substring(0,100)}" cwd=${t??"default"} (no timeout)`),new Promise(o=>{let n="",s="",i=(0,od.spawn)(e,[],{cwd:t,shell:Yx(),stdio:["ignore","pipe","pipe"]});i.stdout?.on("data",a=>{n+=a.toString(),n.length>2e6&&(n=n.slice(-1e6))}),i.stderr?.on("data",a=>{s+=a.toString(),s.length>2e6&&(s=s.slice(-1e6))}),i.on("close",a=>{let l=a??0;h(`[exec.run-blocking] finished exitCode=${l} stdout_len=${n.length} stderr_len=${s.length}`),o(JSON.stringify({exitCode:l,stdout:n||"(no output)",stderr:s||"",success:l===0}))}),i.on("error",a=>{h(`[exec.run-blocking] spawn error: ${a.message}`),o(JSON.stringify({exitCode:1,stdout:"",stderr:a.message,success:!1}))})})}var od,so,_i=g(()=>{"use strict";c();od=require("child_process");td();k();so={name:Qm,displayName:Xm,description:Ym,parameters:ed,category:Zm,execute:Zx,confirmation:{level:"medium",reason:"This will execute a shell command and block until it completes.",showArgs:["command"]}}});var nd,rd,sd,id,ad,ld=g(()=>{"use strict";c();nd="exec.read_output",rd="Read Output",sd="Read stdout and stderr from a background process started with exec.run_background.",id="execution",ad={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function ev(r){let e=r.process_id;if(!e)throw new Error("process_id is required");let t=oo(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 io,Ri=g(()=>{"use strict";c();no();ld();io={name:nd,displayName:rd,description:sd,parameters:ad,category:id,execute:ev}});var cd,pd,md,dd,ud,fd=g(()=>{"use strict";c();cd="exec.tail_output",pd="Tail Process Output",md="Read the last N lines of output from a background process started with exec.run_background. Use this to monitor long-running or non-exiting processes (e.g. dev servers, watchers) to detect ready signals, errors, or progress without reading all accumulated output. Returns alive status, exit code, and the most recent lines of stdout and stderr.",dd="execution",ud={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background."},lines:{type:"integer",description:"Number of lines to return from the end of stdout (default: 20).",default:20}},required:["process_id"]}});async function tv(r){let e=r.process_id,t=typeof r.lines=="number"?Math.max(1,Math.floor(r.lines)):20;if(!e)throw new Error("process_id is required");let o=oo(e);if(!o)return JSON.stringify({error:`Process not found: ${e}`,hint:"Use exec.run_background to start a process first, then pass its id here."});let n=o.process.exitCode===null,s=o.process.exitCode,i=o.stdout.split(`
66
+ `),a=i.slice(-t).join(`
67
+ `).trim(),p=o.stderr.split(`
68
+ `).filter(m=>m.trim()).slice(-3).join(`
69
+ `).trim();return JSON.stringify({id:e,alive:n,exitCode:s,lastLines:a||"(no output yet)",lastStderr:p||"",totalStdoutLines:i.length})}var ao,$i=g(()=>{"use strict";c();no();fd();ao={name:cd,displayName:pd,description:md,parameters:ud,category:dd,execute:tv}});var gd,hd,yd,bd,wd,Td=g(()=>{"use strict";c();gd="exec.kill",hd="Kill",yd="Kill a background process started with exec.run_background.",bd="execution",wd={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function ov(r){let e=r.process_id;if(!e)throw new Error("process_id is required");let t=oo(e);if(!t)throw new Error(`Process not found: ${e}`);return Wm(e)?`Process ${e} (${t.command}) killed successfully.`:`Process ${e} (${t.command}) was already terminated (exit code: ${t.process.exitCode}).`}var lo,Ei=g(()=>{"use strict";c();no();Td();lo={name:gd,displayName:hd,description:yd,parameters:wd,category:bd,execute:ov,confirmation:{level:"medium",reason:"This will terminate a running process.",showArgs:["process_id"]}}});var xd,vd,Cd,Sd,kd,Pd=g(()=>{"use strict";c();xd="exec.list_processes",vd="List Processes",Cd="List all managed background processes started with exec.run_background, including their status.",Sd="execution",kd={type:"object",properties:{}}});async function nv(r){let e=Um();return e.length===0?"No managed background processes.":JSON.stringify(e,null,2)}var co,Di=g(()=>{"use strict";c();no();Pd();co={name:xd,displayName:vd,description:Cd,parameters:kd,category:Sd,execute:nv}});var _d={};X(_d,{execKillTool:()=>lo,execListProcessesTool:()=>co,execReadOutputTool:()=>io,execRunBackgroundTool:()=>ro,execRunBlockingTool:()=>so,execRunShellTool:()=>to,execRunTool:()=>eo,execTailOutputTool:()=>ao,execToolsProject:()=>Mi});var Mi,Oi=g(()=>{"use strict";c();Si();ki();Pi();_i();Ri();$i();Ei();Di();Si();ki();Pi();_i();Ri();$i();Ei();Di();Mi={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.run_blocking","exec.read_output","exec.tail_output","exec.kill","exec.list_processes"],category:"execution"},tools:[eo,to,ro,so,io,ao,lo,co],dependencies:{}}});var Rd,$d,Ed,Dd,Md,Od=g(()=>{"use strict";c();Rd="system.info",$d="Info",Ed="Get system information including OS, CPU, memory, and architecture.",Dd="system",Md={type:"object",properties:{}}});async function rv(r){return h("[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 F,po,Ai=g(()=>{"use strict";c();F=T(require("os"),1);Od();k();po={name:Rd,displayName:$d,description:Ed,parameters:Md,category:Dd,execute:rv}});var Ad,Nd,Id,Ld,jd,Fd=g(()=>{"use strict";c();Ad="system.env",Nd="Environment",Id="Get environment variable(s). If key is provided, returns that specific variable. Otherwise returns all environment variables.",Ld="system",jd={type:"object",properties:{key:{type:"string",description:"Specific environment variable name to get (optional, returns all if omitted)"}}}});async function sv(r){let e=r.key;if(h(`[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 mo,Ni=g(()=>{"use strict";c();Fd();k();mo={name:Ad,displayName:Nd,description:Id,parameters:jd,category:Ld,execute:sv}});var qd,Wd,Ud,Gd,Bd,zd=g(()=>{"use strict";c();qd="system.set_env",Wd="Set Environment",Ud="Set an environment variable for the current session. Does not persist across restarts.",Gd="system",Bd={type:"object",properties:{key:{type:"string",description:"Environment variable name"},value:{type:"string",description:"Value to set"}},required:["key","value"]}});async function iv(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 uo,Ii=g(()=>{"use strict";c();zd();uo={name:qd,displayName:Wd,description:Ud,parameters:Bd,category:Gd,execute:iv,confirmation:{level:"medium",reason:"This will modify the process environment, affecting all subsequent operations.",showArgs:["key","value"]}}});var Hd,Kd,Jd,Vd,Qd,Xd=g(()=>{"use strict";c();Hd="system.cwd",Kd="Current Directory",Jd="Get the current working directory of the process.",Vd="system",Qd={type:"object",properties:{}}});async function av(r){return h("[system.cwd] execute"),JSON.stringify({cwd:process.cwd()})}var fo,Li=g(()=>{"use strict";c();Xd();k();fo={name:Hd,displayName:Kd,description:Jd,parameters:Qd,category:Vd,execute:av}});var Yd,Zd,eu,tu,ou,nu=g(()=>{"use strict";c();Yd="system.disk_usage",Zd="Disk Usage",eu="Get disk usage information for a given path or the root filesystem.",tu="system",ou={type:"object",properties:{path:{type:"string",description:"Path to check disk usage for (default: /)",default:"/"}}}});function ji(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 lv(r){let t=r.path||(process.platform==="win32"?su.tmpdir():"/");t=zr.resolve(t);let o=process.platform==="win32";try{let n=ru.statfsSync(t),s=BigInt(n.blocks)*BigInt(n.bsize),i=BigInt(n.bavail)*BigInt(n.bsize),a=BigInt(n.bfree)*BigInt(n.bsize),l=s-a,p=s>0?Number(l*BigInt(100)/s):0;return JSON.stringify({path:t,filesystem:"statfs",size:ji(Number(s)),used:ji(Number(l)),available:ji(Number(i)),usePercent:`${p}%`,mountedOn:t},null,2)}catch(n){try{if(o){let l=zr.parse(t).root.replace(/\\$/,"")||"C:",p=`Get-PSDrive -Name ${l.replace(":","")} | Select-Object @{n='Drive';e={$_.Name+':'}},@{n='Used';e={$_.Used}},@{n='Free';e={$_.Free}},@{n='Total';e={$_.Used+$_.Free}} | ConvertTo-Json`,m=(0,Fi.execSync)(p,{encoding:"utf-8",timeout:5e3,shell:"powershell.exe"}),d=JSON.parse(m.trim()),f=d.Total||0,b=d.Free||0,y=d.Used||0,w=f>0?Math.round(y/f*100):0;return JSON.stringify({path:t,filesystem:d.Name||"NTFS",size:`${(f/1024**3).toFixed(1)}G`,used:`${(y/1024**3).toFixed(1)}G`,available:`${(b/1024**3).toFixed(1)}G`,usePercent:`${w}%`,mountedOn:d.Drive||`${l}`},null,2)}let s=(0,Fi.execSync)(`df -h "${t}"`,{encoding:"utf-8",timeout:5e3}),i=s.trim().split(`
70
+ `);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 ru,su,zr,Fi,go,qi=g(()=>{"use strict";c();ru=T(require("fs"),1),su=T(require("os"),1),zr=T(require("path"),1),Fi=require("child_process");nu();go={name:Yd,displayName:Zd,description:eu,parameters:ou,category:tu,execute:lv}});var iu={};X(iu,{systemCwdTool:()=>fo,systemDiskUsageTool:()=>go,systemEnvTool:()=>mo,systemInfoTool:()=>po,systemSetEnvTool:()=>uo,systemToolsProject:()=>Wi});var Wi,Ui=g(()=>{"use strict";c();Ai();Ni();Ii();Li();qi();Ai();Ni();Ii();Li();qi();Wi={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:[po,mo,uo,fo,go],dependencies:{}}});var au,lu,cu,pu,mu,du=g(()=>{"use strict";c();au="http.get",lu="GET",cu="Make an HTTP GET request to a URL and return the response body.",pu="network",mu={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 cv(r){let e=r.url,t=r.headers;if(h(`[http.get] execute url="${e}"`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=await fetch(e,{method:"GET",headers:t||{}}),n=await o.text(),s=`HTTP ${o.status} ${o.statusText}`;return o.ok?n.length>uu?`${s}
71
+ ${n.substring(0,uu)}
62
72
 
63
73
  ... (truncated, total ${n.length} characters)`:`${s}
64
74
  ${n}`:`${s}
65
- ${n}`}var Md,co,Mi=g(()=>{"use strict";c();Dd();k();Md=1e5;co={name:Sd,displayName:Rd,description:_d,parameters:Ed,category:$d,execute:dx}});var Od,Nd,Ad,Id,Ld,jd=g(()=>{"use strict";c();Od="http.post",Nd="POST",Ad="Make an HTTP POST request to a URL with an optional body and return the response.",Id="network",Ld={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 ux(r){let e=r.url,t=r.body,o=r.headers||{};if(h(`[http.post] execute url="${e}" body_len=${t?.length??0}`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");if(t&&!o["Content-Type"]&&!o["content-type"])try{JSON.parse(t),o["Content-Type"]="application/json"}catch{o["Content-Type"]="text/plain"}let 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>Fd?`${i}
66
- ${s.substring(0,Fd)}
75
+ ${n}`}var uu,ho,Gi=g(()=>{"use strict";c();du();k();uu=1e5;ho={name:au,displayName:lu,description:cu,parameters:mu,category:pu,execute:cv}});var fu,gu,hu,yu,bu,wu=g(()=>{"use strict";c();fu="http.post",gu="POST",hu="Make an HTTP POST request to a URL with an optional body and return the response.",yu="network",bu={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 pv(r){let e=r.url,t=r.body,o=r.headers||{};if(h(`[http.post] execute url="${e}" body_len=${t?.length??0}`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");if(t&&!o["Content-Type"]&&!o["content-type"])try{JSON.parse(t),o["Content-Type"]="application/json"}catch{o["Content-Type"]="text/plain"}let 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>Tu?`${i}
76
+ ${s.substring(0,Tu)}
67
77
 
68
78
  ... (truncated, total ${s.length} characters)`:`${i}
69
- ${s}`}var Fd,po,Oi=g(()=>{"use strict";c();jd();k();Fd=1e5;po={name:Od,displayName:Nd,description:Ad,parameters:Ld,category:Id,execute:ux,confirmation:{level:"high",reason:"This will send an HTTP POST request with arbitrary payload.",showArgs:["url","body"]}}});var qd,Wd,Ud,Gd,Bd,zd=g(()=>{"use strict";c();qd="http.put",Wd="PUT",Ud="Make an HTTP PUT request to a URL with an optional body and return the response.",Gd="network",Bd={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 fx(r){let e=r.url,t=r.body,o=r.headers||{};if(h(`[http.put] execute url="${e}" body_len=${t?.length??0}`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");if(t&&!o["Content-Type"]&&!o["content-type"])try{JSON.parse(t),o["Content-Type"]="application/json"}catch{o["Content-Type"]="text/plain"}let 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>Hd?`${i}
70
- ${s.substring(0,Hd)}
79
+ ${s}`}var Tu,yo,Bi=g(()=>{"use strict";c();wu();k();Tu=1e5;yo={name:fu,displayName:gu,description:hu,parameters:bu,category:yu,execute:pv,confirmation:{level:"high",reason:"This will send an HTTP POST request with arbitrary payload.",showArgs:["url","body"]}}});var xu,vu,Cu,Su,ku,Pu=g(()=>{"use strict";c();xu="http.put",vu="PUT",Cu="Make an HTTP PUT request to a URL with an optional body and return the response.",Su="network",ku={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 mv(r){let e=r.url,t=r.body,o=r.headers||{};if(h(`[http.put] execute url="${e}" body_len=${t?.length??0}`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");if(t&&!o["Content-Type"]&&!o["content-type"])try{JSON.parse(t),o["Content-Type"]="application/json"}catch{o["Content-Type"]="text/plain"}let 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>_u?`${i}
80
+ ${s.substring(0,_u)}
71
81
 
72
82
  ... (truncated)`:`${i}
73
- ${s}`}var Hd,mo,Ni=g(()=>{"use strict";c();zd();k();Hd=1e5;mo={name:qd,displayName:Wd,description:Ud,parameters:Bd,category:Gd,execute:fx,confirmation:{level:"high",reason:"This will send an HTTP PUT request to overwrite remote resources.",showArgs:["url","body"]}}});var Kd,Jd,Vd,Qd,Xd,Yd=g(()=>{"use strict";c();Kd="http.delete",Jd="DELETE",Vd="Make an HTTP DELETE request to a URL and return the response.",Qd="network",Xd={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 gx(r){let e=r.url,t=r.headers;if(h(`[http.delete] execute url="${e}"`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=await fetch(e,{method:"DELETE",headers:t||{}}),n=await o.text(),s=`HTTP ${o.status} ${o.statusText}`;return n.length>Zd?`${s}
74
- ${n.substring(0,Zd)}
83
+ ${s}`}var _u,bo,zi=g(()=>{"use strict";c();Pu();k();_u=1e5;bo={name:xu,displayName:vu,description:Cu,parameters:ku,category:Su,execute:mv,confirmation:{level:"high",reason:"This will send an HTTP PUT request to overwrite remote resources.",showArgs:["url","body"]}}});var Ru,$u,Eu,Du,Mu,Ou=g(()=>{"use strict";c();Ru="http.delete",$u="DELETE",Eu="Make an HTTP DELETE request to a URL and return the response.",Du="network",Mu={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 dv(r){let e=r.url,t=r.headers;if(h(`[http.delete] execute url="${e}"`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=await fetch(e,{method:"DELETE",headers:t||{}}),n=await o.text(),s=`HTTP ${o.status} ${o.statusText}`;return n.length>Au?`${s}
84
+ ${n.substring(0,Au)}
75
85
 
76
86
  ... (truncated)`:`${s}
77
- ${n}`}var Zd,uo,Ai=g(()=>{"use strict";c();Yd();k();Zd=1e5;uo={name:Kd,displayName:Jd,description:Vd,parameters:Xd,category:Qd,execute:gx,confirmation:{level:"high",reason:"This will send an HTTP DELETE request to destroy remote resources.",showArgs:["url"]}}});var eu,tu,ou,nu,ru,su=g(()=>{"use strict";c();eu="http.download",tu="Download",ou="Download a file from a URL and save it to a local path.",nu="network",ru={type:"object",properties:{url:{type:"string",description:"The URL to download from"},path:{type:"string",description:"Local file path to save the downloaded file"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url","path"]}});async function hx(r){let e=r.url,t=r.path,o=r.headers;if(h(`[http.download] execute url="${e}" path="${t}"`),!e)throw new Error("url is required");if(!t)throw new Error("path is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let 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=iu.dirname(t);return fo.existsSync(i)||fo.mkdirSync(i,{recursive:!0}),fo.writeFileSync(t,s),`Downloaded ${e} \u2192 ${t} (${s.length} bytes)`}var fo,iu,go,Ii=g(()=>{"use strict";c();fo=T(require("fs"),1),iu=T(require("path"),1);su();k();go={name:eu,displayName:tu,description:ou,parameters:ru,category:nu,execute:hx}});var au={};le(au,{httpDeleteTool:()=>uo,httpDownloadTool:()=>go,httpGetTool:()=>co,httpPostTool:()=>po,httpPutTool:()=>mo,httpToolsProject:()=>Li});var Li,ji=g(()=>{"use strict";c();Mi();Oi();Ni();Ai();Ii();Mi();Oi();Ni();Ai();Ii();Li={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:[co,po,mo,uo,go],dependencies:{}}});var lu,cu,pu,mu,du,uu=g(()=>{"use strict";c();lu="github.graphql.execute",cu="GitHub GraphQL",pu=["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(" "),mu="github",du={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 J(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 _e=g(()=>{"use strict";c()});async function B(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 yx(o,n,r);return bx(o,n,s)}async function yx(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=gu.get(t);if(o!==void 0)return o;let n=yu(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 gu.set(t,i.id),i.id}async function bx(r,e,t){let o=fu.get(t);if(o&&o.expiresAt>Date.now()+6e4)return o.token;let n=yu(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 fu.set(t,{token:i.token,expiresAt:new Date(i.expires_at).getTime()}),i.token}function yu(r,e){let t=Math.floor(Date.now()/1e3),o={alg:"RS256",typ:"JWT"},n={iat:t-30,exp:t+540,iss:r},s=l=>Buffer.from(JSON.stringify(l)).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_"),i=`${s(o)}.${s(n)}`,a=hu.createSign("RSA-SHA256");return a.update(i),a.end(),`${i}.`+a.sign(e).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")}var hu,fu,gu,Pe=g(()=>{"use strict";c();hu=T(require("crypto"),1),fu=new Map,gu=new Map});async function wx(r){let e=r.query,t=r.variables??{},o=await B(r.repo,r.token);h(`[github.graphql.execute] query_len=${e?.length??0}`);let n=await fetch("https://api.github.com/graphql",{method:"POST",headers:J(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&&h(`[github.graphql.execute] errors=${i.errors.length}`)}catch{}return`HTTP ${n.status} ${n.statusText}
79
- ${s}`}var ho,Fi=g(()=>{"use strict";c();uu();k();_e();Pe();ho={name:lu,displayName:cu,description:pu,parameters:du,category:mu,execute:wx}});var bu,wu,Tu,xu,vu,Cu=g(()=>{"use strict";c();bu="github.contents.getText",wu="Get Repo File (Text)",Tu="Fetch file content (decoded text) via the GitHub Contents API.",xu="github",vu={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"]}});async function Tx(r){let e=r.repo,t=r.path,o=r.ref,n=await B(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)}`:""}`;h(`[github.contents.getText] repo=${e} path=${t} ref=${o??""}`);let l=await fetch(a,{method:"GET",headers:J(n)}),p=await l.text();if(!l.ok)return`HTTP ${l.status} ${l.statusText}
80
- ${p}`;try{let u=JSON.parse(p)?.content;if(typeof u=="string"){let f=En.Buffer.from(u.replace(/\n/g,""),"base64").toString("utf8");if(s&&En.Buffer.byteLength(f,"utf8")>s){let b=En.Buffer.from(f,"utf8").subarray(0,s).toString("utf8"),y=`
81
- \u2026 [truncated, ${s} of ${En.Buffer.byteLength(f,"utf8")} bytes]`;return`HTTP ${l.status} ${l.statusText}
87
+ ${n}`}var Au,wo,Hi=g(()=>{"use strict";c();Ou();k();Au=1e5;wo={name:Ru,displayName:$u,description:Eu,parameters:Mu,category:Du,execute:dv,confirmation:{level:"high",reason:"This will send an HTTP DELETE request to destroy remote resources.",showArgs:["url"]}}});var Nu,Iu,Lu,ju,Fu,qu=g(()=>{"use strict";c();Nu="http.download",Iu="Download",Lu="Download a file from a URL and save it to a local path.",ju="network",Fu={type:"object",properties:{url:{type:"string",description:"The URL to download from"},path:{type:"string",description:"Local file path to save the downloaded file"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url","path"]}});async function uv(r){let e=r.url,t=r.path,o=r.headers;if(h(`[http.download] execute url="${e}" path="${t}"`),!e)throw new Error("url is required");if(!t)throw new Error("path is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let 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=Wu.dirname(t);return To.existsSync(i)||To.mkdirSync(i,{recursive:!0}),To.writeFileSync(t,s),`Downloaded ${e} \u2192 ${t} (${s.length} bytes)`}var To,Wu,xo,Ki=g(()=>{"use strict";c();To=T(require("fs"),1),Wu=T(require("path"),1);qu();k();xo={name:Nu,displayName:Iu,description:Lu,parameters:Fu,category:ju,execute:uv}});var Uu={};X(Uu,{httpDeleteTool:()=>wo,httpDownloadTool:()=>xo,httpGetTool:()=>ho,httpPostTool:()=>yo,httpPutTool:()=>bo,httpToolsProject:()=>Ji});var Ji,Vi=g(()=>{"use strict";c();Gi();Bi();zi();Hi();Ki();Gi();Bi();zi();Hi();Ki();Ji={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:[ho,yo,bo,wo,xo],dependencies:{}}});var Gu,Bu,zu,Hu,Ku,Ju=g(()=>{"use strict";c();Gu="github.graphql.execute",Bu="GitHub GraphQL",zu=["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(" "),Hu="github",Ku={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 J(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=g(()=>{"use strict";c()});async function B(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,`
88
+ `);if(!o||!n)throw new Error("No GitHub token available. Set GITHUB_PAT, or GITHUB_APP_ID + GITHUB_APP_PRIVATE_KEY.");let s=await fv(o,n,r);return gv(o,n,s)}async function fv(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=Qu.get(t);if(o!==void 0)return o;let n=Yu(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 Qu.set(t,i.id),i.id}async function gv(r,e,t){let o=Vu.get(t);if(o&&o.expiresAt>Date.now()+6e4)return o.token;let n=Yu(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 Vu.set(t,{token:i.token,expiresAt:new Date(i.expires_at).getTime()}),i.token}function Yu(r,e){let t=Math.floor(Date.now()/1e3),o={alg:"RS256",typ:"JWT"},n={iat:t-30,exp:t+540,iss:r},s=l=>Buffer.from(JSON.stringify(l)).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_"),i=`${s(o)}.${s(n)}`,a=Xu.createSign("RSA-SHA256");return a.update(i),a.end(),`${i}.`+a.sign(e).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")}var Xu,Vu,Qu,Se=g(()=>{"use strict";c();Xu=T(require("crypto"),1),Vu=new Map,Qu=new Map});async function hv(r){let e=r.query,t=r.variables??{},o=await B(r.repo,r.token);h(`[github.graphql.execute] query_len=${e?.length??0}`);let n=await fetch("https://api.github.com/graphql",{method:"POST",headers:J(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&&h(`[github.graphql.execute] errors=${i.errors.length}`)}catch{}return`HTTP ${n.status} ${n.statusText}
89
+ ${s}`}var vo,Qi=g(()=>{"use strict";c();Ju();k();Re();Se();vo={name:Gu,displayName:Bu,description:zu,parameters:Ku,category:Hu,execute:hv}});var Zu,ef,tf,of,nf,rf=g(()=>{"use strict";c();Zu="github.contents.getText",ef="Get Repo File (Text)",tf="Fetch file content (decoded text) via the GitHub Contents API.",of="github",nf={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"]}});async function yv(r){let e=r.repo,t=r.path,o=r.ref,n=await B(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)}`:""}`;h(`[github.contents.getText] repo=${e} path=${t} ref=${o??""}`);let l=await fetch(a,{method:"GET",headers:J(n)}),p=await l.text();if(!l.ok)return`HTTP ${l.status} ${l.statusText}
90
+ ${p}`;try{let d=JSON.parse(p)?.content;if(typeof d=="string"){let f=Nn.Buffer.from(d.replace(/\n/g,""),"base64").toString("utf8");if(s&&Nn.Buffer.byteLength(f,"utf8")>s){let b=Nn.Buffer.from(f,"utf8").subarray(0,s).toString("utf8"),y=`
91
+ \u2026 [truncated, ${s} of ${Nn.Buffer.byteLength(f,"utf8")} bytes]`;return`HTTP ${l.status} ${l.statusText}
82
92
  ${b}${y}`}return`HTTP ${l.status} ${l.statusText}
83
93
  ${f}`}}catch{}return`HTTP ${l.status} ${l.statusText}
84
- ${p}`}var En,yo,qi=g(()=>{"use strict";c();Cu();k();_e();Pe();En=require("buffer");yo={name:bu,displayName:wu,description:Tu,parameters:vu,category:xu,execute:Tx}});var Pu,ku,Su,Ru,_u,$u=g(()=>{"use strict";c();Pu="github.pr.reviewThreads.list",ku="List PR Review Threads",Su="List PR review threads via GraphQL (optionally unresolved only).",Ru="github",_u={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 xx(r){let[e,t]=String(r.repo).split("/"),o=Number(r.number),n=await B(r.repo,r.token),s=!!r.unresolvedOnly,i=r.first?Number(r.first):100,a=r.after?String(r.after):void 0,l=r.commentsFirst?Number(r.commentsFirst):20,p=!!r.includeMeta;h(`[github.pr.reviewThreads.list] repo=${e}/${t} pr=${o} unresolvedOnly=${s} first=${i} after=${a??""} commentsFirst=${l} includeMeta=${p}`);let u=await fetch("https://api.github.com/graphql",{method:"POST",headers:J(n,{"Content-Type":"application/json"}),body:JSON.stringify({query:`query($owner:String!,$name:String!,$number:Int!,$first:Int!,$after:String,$commentsFirst:Int!){
94
+ ${p}`}var Nn,Co,Xi=g(()=>{"use strict";c();rf();k();Re();Se();Nn=require("buffer");Co={name:Zu,displayName:ef,description:tf,parameters:nf,category:of,execute:yv}});var sf,af,lf,cf,pf,mf=g(()=>{"use strict";c();sf="github.pr.reviewThreads.list",af="List PR Review Threads",lf="List PR review threads via GraphQL (optionally unresolved only).",cf="github",pf={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 bv(r){let[e,t]=String(r.repo).split("/"),o=Number(r.number),n=await B(r.repo,r.token),s=!!r.unresolvedOnly,i=r.first?Number(r.first):100,a=r.after?String(r.after):void 0,l=r.commentsFirst?Number(r.commentsFirst):20,p=!!r.includeMeta;h(`[github.pr.reviewThreads.list] repo=${e}/${t} pr=${o} unresolvedOnly=${s} first=${i} after=${a??""} commentsFirst=${l} includeMeta=${p}`);let d=await fetch("https://api.github.com/graphql",{method:"POST",headers:J(n,{"Content-Type":"application/json"}),body:JSON.stringify({query:`query($owner:String!,$name:String!,$number:Int!,$first:Int!,$after:String,$commentsFirst:Int!){
85
95
  repository(owner:$owner,name:$name){
86
96
  pullRequest(number:$number){
87
97
  headRefOid
@@ -91,29 +101,29 @@ ${p}`}var En,yo,qi=g(()=>{"use strict";c();Cu();k();_e();Pe();En=require("buffer
91
101
  }
92
102
  }
93
103
  }
94
- }`,variables:{owner:e,name:t,number:o,first:i,after:a,commentsFirst:l}})}),f=await u.text();if(!u.ok)return`HTTP ${u.status} ${u.statusText}
104
+ }`,variables:{owner:e,name:t,number:o,first:i,after:a,commentsFirst:l}})}),f=await d.text();if(!d.ok)return`HTTP ${d.status} ${d.statusText}
95
105
  ${f}`;try{let b=JSON.parse(f);b&&Array.isArray(b.errors)&&b.errors.length>0&&h(`[github.pr.reviewThreads.list] errors=${b.errors.length}`);let y=b?.data?.repository?.pullRequest,w=y?.reviewThreads?.pageInfo??{hasNextPage:!1,endCursor:null},x=y?.reviewThreads?.nodes??[];if(s&&(x=x.filter(C=>C?.isResolved===!1)),p){let C={headRefOid:y?.headRefOid,threads:x,pageInfo:w};return`HTTP 200 OK
96
106
  ${JSON.stringify(C)}`}return`HTTP 200 OK
97
- ${JSON.stringify(x)}`}catch{return`HTTP ${u.status} ${u.statusText}
98
- ${f}`}}var bo,Wi=g(()=>{"use strict";c();$u();_e();k();Pe();bo={name:Pu,displayName:ku,description:Su,parameters:_u,category:Ru,execute:xx}});var Eu,Du,Mu,Ou,Nu,Au=g(()=>{"use strict";c();Eu="github.pr.reviewThreads.resolve",Du="Resolve Review Thread",Mu=["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(" "),Ou="github",Nu={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 vx(r){let e=String(r.threadId),t=await B(r.repo,r.token);h(`[github.pr.reviewThreads.resolve] threadId=${e}`);let n=await fetch("https://api.github.com/graphql",{method:"POST",headers:J(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(l=>l.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 wo,Ui=g(()=>{"use strict";c();Au();_e();k();Pe();wo={name:Eu,displayName:Du,description:Mu,parameters:Nu,category:Ou,execute:vx}});var Iu,Lu,ju,Fu,qu,Wu=g(()=>{"use strict";c();Iu="github.pr.reviewComments.reply",Lu="Reply to Review Comment",ju="Reply within an existing PR review thread to maintain continuity.",Fu="github",qu={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 Cx(r){let e=String(r.repo),t=Number(r.number),o=Number(r.inReplyTo),n=String(r.body),s=await B(e,r.token),i=`https://api.github.com/repos/${e}/pulls/${t}/comments/${o}/replies`;h(`[github.pr.reviewComments.reply] repo=${e} inReplyTo=${o}`);let a=await fetch(i,{method:"POST",headers:J(s,{"Content-Type":"application/json"}),body:JSON.stringify({body:n})}),l=await a.text();return`HTTP ${a.status} ${a.statusText}
100
- ${l}`}var To,Gi=g(()=>{"use strict";c();Wu();k();_e();Pe();To={name:Iu,displayName:Lu,description:ju,parameters:qu,category:Fu,execute:Cx}});var Uu,Gu,Bu,zu,Hu,Ku=g(()=>{"use strict";c();Uu="github.pr.diff.get",Gu="Get PR Diff",Bu="Fetch the unified diff for a pull request (text/patch).",zu="github",Hu={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"]}});async function Px(r){let e=String(r.repo),t=Number(r.number),o=await B(e,r.token),n=r.maxBytes?Number(r.maxBytes):void 0,s=`https://api.github.com/repos/${e}/pulls/${t}`;h(`[github.pr.diff.get] repo=${e} pr=${t}`);let i=await fetch(s,{method:"GET",headers:J(o,{Accept:"application/vnd.github.v3.diff"})}),a=await i.text();if(n&&Dr.Buffer.byteLength(a,"utf8")>n){let l=Dr.Buffer.from(a,"utf8").subarray(0,n).toString("utf8"),p=`
101
- \u2026 [truncated, ${n} of ${Dr.Buffer.byteLength(a,"utf8")} bytes]`;return`HTTP ${i.status} ${i.statusText}
107
+ ${JSON.stringify(x)}`}catch{return`HTTP ${d.status} ${d.statusText}
108
+ ${f}`}}var So,Yi=g(()=>{"use strict";c();mf();Re();k();Se();So={name:sf,displayName:af,description:lf,parameters:pf,category:cf,execute:bv}});var df,uf,ff,gf,hf,yf=g(()=>{"use strict";c();df="github.pr.reviewThreads.resolve",uf="Resolve Review Thread",ff=["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(" "),gf="github",hf={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 wv(r){let e=String(r.threadId),t=await B(r.repo,r.token);h(`[github.pr.reviewThreads.resolve] threadId=${e}`);let n=await fetch("https://api.github.com/graphql",{method:"POST",headers:J(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(l=>l.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}
109
+ ${s}`}var ko,Zi=g(()=>{"use strict";c();yf();Re();k();Se();ko={name:df,displayName:uf,description:ff,parameters:hf,category:gf,execute:wv}});var bf,wf,Tf,xf,vf,Cf=g(()=>{"use strict";c();bf="github.pr.reviewComments.reply",wf="Reply to Review Comment",Tf="Reply within an existing PR review thread to maintain continuity.",xf="github",vf={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 Tv(r){let e=String(r.repo),t=Number(r.number),o=Number(r.inReplyTo),n=String(r.body),s=await B(e,r.token),i=`https://api.github.com/repos/${e}/pulls/${t}/comments/${o}/replies`;h(`[github.pr.reviewComments.reply] repo=${e} inReplyTo=${o}`);let a=await fetch(i,{method:"POST",headers:J(s,{"Content-Type":"application/json"}),body:JSON.stringify({body:n})}),l=await a.text();return`HTTP ${a.status} ${a.statusText}
110
+ ${l}`}var Po,ea=g(()=>{"use strict";c();Cf();k();Re();Se();Po={name:bf,displayName:wf,description:Tf,parameters:vf,category:xf,execute:Tv}});var Sf,kf,Pf,_f,Rf,$f=g(()=>{"use strict";c();Sf="github.pr.diff.get",kf="Get PR Diff",Pf="Fetch the unified diff for a pull request (text/patch).",_f="github",Rf={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"]}});async function xv(r){let e=String(r.repo),t=Number(r.number),o=await B(e,r.token),n=r.maxBytes?Number(r.maxBytes):void 0,s=`https://api.github.com/repos/${e}/pulls/${t}`;h(`[github.pr.diff.get] repo=${e} pr=${t}`);let i=await fetch(s,{method:"GET",headers:J(o,{Accept:"application/vnd.github.v3.diff"})}),a=await i.text();if(n&&Hr.Buffer.byteLength(a,"utf8")>n){let l=Hr.Buffer.from(a,"utf8").subarray(0,n).toString("utf8"),p=`
111
+ \u2026 [truncated, ${n} of ${Hr.Buffer.byteLength(a,"utf8")} bytes]`;return`HTTP ${i.status} ${i.statusText}
102
112
  ${l}${p}`}return`HTTP ${i.status} ${i.statusText}
103
- ${a}`}var Dr,xo,Bi=g(()=>{"use strict";c();Ku();_e();k();Pe();Dr=require("buffer");xo={name:Uu,displayName:Gu,description:Bu,parameters:Hu,category:zu,execute:Px}});var Ju,Vu,Qu,Xu,Yu,Zu=g(()=>{"use strict";c();Ju="github.pr.files.list",Vu="List PR Files",Qu="List files changed in a PR with positions metadata.",Xu="github",Yu={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 kx(r){let e=String(r.repo),t=Number(r.number),o=await B(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()}`:""}`;h(`[github.pr.files.list] repo=${e} pr=${t} perPage=${n??""} page=${s??""}`);let l=await fetch(a,{method:"GET",headers:J(o)}),p=await l.text();return`HTTP ${l.status} ${l.statusText}
104
- ${p}`}var vo,zi=g(()=>{"use strict";c();Zu();_e();k();Pe();vo={name:Ju,displayName:Vu,description:Qu,parameters:Yu,category:Xu,execute:kx}});var ef,tf,of,nf,rf,sf=g(()=>{"use strict";c();ef="github.pr.reviews.submit",tf="Submit PR Review",of="Submit a PR review (APPROVE, REQUEST_CHANGES, or COMMENT), optionally with inline comments.",nf="github",rf={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 Sx(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 B(e,r.token),a=`https://api.github.com/repos/${e}/pulls/${t}/reviews`;h(`[github.pr.reviews.submit] repo=${e} pr=${t} event=${o} comments=${s?.length??0}`);let l={event:o};n&&(l.body=n),s&&s.length>0&&(l.comments=s);let p=await fetch(a,{method:"POST",headers:J(i,{"Content-Type":"application/json"}),body:JSON.stringify(l)}),m=await p.text();return`HTTP ${p.status} ${p.statusText}
105
- ${m}`}var Co,Hi=g(()=>{"use strict";c();sf();_e();k();Pe();Co={name:ef,displayName:tf,description:of,parameters:rf,category:nf,execute:Sx}});var af,lf,cf,pf,mf,df=g(()=>{"use strict";c();af="github.issues.comments.create",lf="Create Issue/PR Comment",cf="Create a comment on an issue or pull request (conversation tab).",pf="github",mf={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 Rx(r){let e=String(r.repo),t=Number(r.number),o=String(r.body),n=await B(e,r.token),s=`https://api.github.com/repos/${e}/issues/${t}/comments`;h(`[github.issues.comments.create] repo=${e} number=${t}`);let i=await fetch(s,{method:"POST",headers:J(n,{"Content-Type":"application/json"}),body:JSON.stringify({body:o})}),a=await i.text();return`HTTP ${i.status} ${i.statusText}
106
- ${a}`}var Po,Ki=g(()=>{"use strict";c();df();_e();k();Pe();Po={name:af,displayName:lf,description:cf,parameters:mf,category:pf,execute:Rx}});var uf={};le(uf,{githubContentsGetTextTool:()=>yo,githubGraphqlExecuteTool:()=>ho,githubIssuesCommentsCreateTool:()=>Po,githubPrDiffGetTool:()=>xo,githubPrFilesListTool:()=>vo,githubPrReviewCommentsReplyTool:()=>To,githubPrReviewThreadsListTool:()=>bo,githubPrReviewThreadsResolveTool:()=>wo,githubPrReviewsSubmitTool:()=>Co,githubToolsProject:()=>Ji});var Ji,Vi=g(()=>{"use strict";c();Fi();qi();Wi();Ui();Gi();Bi();zi();Hi();Ki();Fi();qi();Wi();Ui();Gi();Bi();zi();Hi();Ki();Ji={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:[ho,yo,bo,wo,To,xo,vo,Co,Po],dependencies:{}}});var ff,gf,hf,yf,bf,wf=g(()=>{"use strict";c();ff="web.fetch",gf="Fetch",hf="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).",yf="network",bf={type:"object",properties:{url:{type:"string",description:"The URL to fetch"},extractionMode:{type:"string",description:'Content extraction mode: "full" (raw HTML, 15K limit), "structured" (title, excerpt, key points, main content), or "minimal" (title + 500 char snippet). Default: "full"',enum:["full","structured","minimal"],default:"full"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});function Tf(r,e){let t=Qi.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 b of i){let y=t(b).first();if(y.length>0&&(a=y.text().trim(),a.length>200))break}(!a||a.length<200)&&(a=t("body").text().trim()),a=a.replace(/\s+/g," ").trim();let l=[];t("p").each((b,y)=>{let w=t(y).text().trim();w.length>50&&l.length<3&&l.push(w)});let p=l.join(`
113
+ ${a}`}var Hr,_o,ta=g(()=>{"use strict";c();$f();Re();k();Se();Hr=require("buffer");_o={name:Sf,displayName:kf,description:Pf,parameters:Rf,category:_f,execute:xv}});var Ef,Df,Mf,Of,Af,Nf=g(()=>{"use strict";c();Ef="github.pr.files.list",Df="List PR Files",Mf="List files changed in a PR with positions metadata.",Of="github",Af={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 vv(r){let e=String(r.repo),t=Number(r.number),o=await B(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()}`:""}`;h(`[github.pr.files.list] repo=${e} pr=${t} perPage=${n??""} page=${s??""}`);let l=await fetch(a,{method:"GET",headers:J(o)}),p=await l.text();return`HTTP ${l.status} ${l.statusText}
114
+ ${p}`}var Ro,oa=g(()=>{"use strict";c();Nf();Re();k();Se();Ro={name:Ef,displayName:Df,description:Mf,parameters:Af,category:Of,execute:vv}});var If,Lf,jf,Ff,qf,Wf=g(()=>{"use strict";c();If="github.pr.reviews.submit",Lf="Submit PR Review",jf="Submit a PR review (APPROVE, REQUEST_CHANGES, or COMMENT), optionally with inline comments.",Ff="github",qf={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 Cv(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 B(e,r.token),a=`https://api.github.com/repos/${e}/pulls/${t}/reviews`;h(`[github.pr.reviews.submit] repo=${e} pr=${t} event=${o} comments=${s?.length??0}`);let l={event:o};n&&(l.body=n),s&&s.length>0&&(l.comments=s);let p=await fetch(a,{method:"POST",headers:J(i,{"Content-Type":"application/json"}),body:JSON.stringify(l)}),m=await p.text();return`HTTP ${p.status} ${p.statusText}
115
+ ${m}`}var $o,na=g(()=>{"use strict";c();Wf();Re();k();Se();$o={name:If,displayName:Lf,description:jf,parameters:qf,category:Ff,execute:Cv}});var Uf,Gf,Bf,zf,Hf,Kf=g(()=>{"use strict";c();Uf="github.issues.comments.create",Gf="Create Issue/PR Comment",Bf="Create a comment on an issue or pull request (conversation tab).",zf="github",Hf={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 Sv(r){let e=String(r.repo),t=Number(r.number),o=String(r.body),n=await B(e,r.token),s=`https://api.github.com/repos/${e}/issues/${t}/comments`;h(`[github.issues.comments.create] repo=${e} number=${t}`);let i=await fetch(s,{method:"POST",headers:J(n,{"Content-Type":"application/json"}),body:JSON.stringify({body:o})}),a=await i.text();return`HTTP ${i.status} ${i.statusText}
116
+ ${a}`}var Eo,ra=g(()=>{"use strict";c();Kf();Re();k();Se();Eo={name:Uf,displayName:Gf,description:Bf,parameters:Hf,category:zf,execute:Sv}});var Jf={};X(Jf,{githubContentsGetTextTool:()=>Co,githubGraphqlExecuteTool:()=>vo,githubIssuesCommentsCreateTool:()=>Eo,githubPrDiffGetTool:()=>_o,githubPrFilesListTool:()=>Ro,githubPrReviewCommentsReplyTool:()=>Po,githubPrReviewThreadsListTool:()=>So,githubPrReviewThreadsResolveTool:()=>ko,githubPrReviewsSubmitTool:()=>$o,githubToolsProject:()=>sa});var sa,ia=g(()=>{"use strict";c();Qi();Xi();Yi();Zi();ea();ta();oa();na();ra();Qi();Xi();Yi();Zi();ea();ta();oa();na();ra();sa={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:[vo,Co,So,ko,Po,_o,Ro,$o,Eo],dependencies:{}}});var Vf,Qf,Xf,Yf,Zf,eg=g(()=>{"use strict";c();Vf="web.fetch",Qf="Fetch",Xf="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).",Yf="network",Zf={type:"object",properties:{url:{type:"string",description:"The URL to fetch"},extractionMode:{type:"string",description:'Content extraction mode: "full" (raw HTML, 15K limit), "structured" (title, excerpt, key points, main content), or "minimal" (title + 500 char snippet). Default: "full"',enum:["full","structured","minimal"],default:"full"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});function tg(r,e){let t=aa.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 b of i){let y=t(b).first();if(y.length>0&&(a=y.text().trim(),a.length>200))break}(!a||a.length<200)&&(a=t("body").text().trim()),a=a.replace(/\s+/g," ").trim();let l=[];t("p").each((b,y)=>{let w=t(y).text().trim();w.length>50&&l.length<3&&l.push(w)});let p=l.join(`
107
117
 
108
- `)||a.substring(0,500),m=[];t("h2, h3").each((b,y)=>{let w=t(y).text().trim();w&&w.length>5&&w.length<200&&m.length<10&&m.push(w)});let u=a.split(/\s+/).length,f=a.split(/\s+/);return f.length>2e3&&(a=f.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:u}}function xf(r,e){let t=Qi.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 vf(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 Cf(r){return`# ${r.title}
118
+ `)||a.substring(0,500),m=[];t("h2, h3").each((b,y)=>{let w=t(y).text().trim();w&&w.length>5&&w.length<200&&m.length<10&&m.push(w)});let d=a.split(/\s+/).length,f=a.split(/\s+/);return f.length>2e3&&(a=f.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:d}}function og(r,e){let t=aa.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 ng(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(`
119
+ `)}function rg(r){return`# ${r.title}
110
120
  URL: ${r.url}
111
121
 
112
- ${r.snippet}`}var Qi,Pf=g(()=>{"use strict";c();Qi=T(require("cheerio"),1)});async function _x(r){let e=r.url,t=r.extractionMode||"full",o=r.headers,n=r.timeout||3e4;if(h(`[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 l=await a.text();if(t==="structured"){let p=Tf(l,e);return vf(p)}else if(t==="minimal"){let p=xf(l,e);return Cf(p)}else return l.length>15e3?l.substring(0,15e3)+`
122
+ ${r.snippet}`}var aa,sg=g(()=>{"use strict";c();aa=T(require("cheerio"),1)});async function kv(r){let e=r.url,t=r.extractionMode||"full",o=r.headers,n=r.timeout||3e4;if(h(`[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}
123
+ ${await a.text()}`;let l=await a.text();if(t==="structured"){let p=tg(l,e);return ng(p)}else if(t==="minimal"){let p=og(l,e);return rg(p)}else return l.length>15e3?l.substring(0,15e3)+`
114
124
 
115
- [TRUNCATED: showing 15K of ${l.length} total characters]`:l}var ko,Xi=g(()=>{"use strict";c();wf();Pf();k();ko={name:ff,displayName:gf,description:hf,parameters:bf,category:yf,execute:_x}});var kf,Sf,Rf,_f,$f,Ef=g(()=>{"use strict";c();kf="web.search",Sf="Search",Rf="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.",_f="network",$f={type:"object",properties:{query:{type:"string",description:"The search query"},max_results:{type:"integer",description:"Maximum number of results to return (default: 5)",default:5},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4},include_answer:{type:"boolean",description:"Include AI-generated answer summary (works with Tavily and Brave APIs). Default: false",default:!1},freshness:{type:"string",description:'Time range for fresh/recent results: "day" (last 24h), "week" (last 7 days), "month" (last 31 days), "year" (last 365 days). Ensures latest real-time data. Supported by Tavily and Brave APIs; DuckDuckGo returns general results.',enum:["day","week","month","year"]}},required:["query"]}});function Dn(r){let e=Of(r);if(!Ge.existsSync(e))return{};try{let t=Ge.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return{}}}function So(r){let e=Dn(r),t=$x(e.tools||e);return h(JSON.stringify(t??{})),t}function Mf(r,e){let t=Of(e),o={};try{Ge.existsSync(t)&&(o=JSON.parse(Ge.readFileSync(t,"utf-8")))}catch{o={}}o.tools=r,Ge.writeFileSync(t,JSON.stringify(o,null,4),"utf-8")}function $x(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??te.enabled,autoExecute:r.autoExecute??te.autoExecute,maxToolRounds:r.maxToolRounds??te.maxToolRounds,toolChoicePolicy:r.toolChoicePolicy??te.toolChoicePolicy,resultMaxChars:r.resultMaxChars??te.resultMaxChars,enabledTools:r.enabledTools??te.enabledTools,enabledToolCategories:r.enabledToolCategories??te.enabledToolCategories,toolSearch:r.toolSearch??te.toolSearch,additionalConfigurations:e}}function Of(r){return r?r.endsWith(".json")?Mr.resolve(r):Mr.resolve(r,Df):Mr.resolve(process.cwd(),Df)}var Ge,Mr,Df,Yi=g(()=>{"use strict";c();Ge=T(require("fs"),1),Mr=T(require("path"),1);gn();k();Df="toolpack.config.json"});function Mx(r,e){h("[web.search] Parsing DuckDuckGo Lite response");let t=Af.load(r),o=[];return t("a.result-link").each((s,i)=>{if(o.length>=e)return;let a=t(i),l=a.text().trim(),p=a.attr("href"),m=a.siblings(".result-snippet").text().trim();m||(m=a.parent().text().replace(l,"").trim()),l&&p&&o.push({title:l,link:p,snippet:m.slice(0,200)})}),o}function Ox(r){if(r)switch(r){case"day":return 1;case"week":return 7;case"month":return 31;case"year":return 365;default:return}}function Nf(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 Nx(r){let e=r.query,t=r.max_results||5,o=r.include_answer||!1,n=r.freshness;h(`[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 u=new AbortController,f=setTimeout(()=>u.abort(),r.timeout||3e4);return{signal:u.signal,clear:()=>clearTimeout(f)}};if(!e)throw new Error("query is required");let a=So();if(h(`[web.search] config=${JSON.stringify(a)}`),a.additionalConfigurations?.webSearch?.tavilyApiKey){h("[web.search] using Tavily API");try{let{signal:u,clear:f}=i(),b=Ox(n),y={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:a.additionalConfigurations.webSearch.tavilyApiKey,query:e,max_results:t,include_answer:o,...b&&{days:b}}),signal:u};h(`[web.search] Tavily request=${JSON.stringify(y)}`);let w=await fetch("https://api.tavily.com/search",y).finally(f);if(w.ok){let x=await w.json();if(x.results&&x.results.length>0){let C=x.results.map(v=>({title:v.title,link:v.url,snippet:v.content}));return o&&x.answer?JSON.stringify({answer:x.answer,results:C},null,2):JSON.stringify(C,null,2)}}else me(`[web.search] Tavily search failed with status ${w.status}`)}catch(u){me(`[web.search] Tavily search failed, falling back: ${u}`)}}if(a.additionalConfigurations?.webSearch?.braveApiKey)try{let{signal:u,clear:f}=i();if(o){let b=Nf(n),y=b?`&freshness=${b}`:"",w=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(e)}&count=${Math.min(t,20)}&summary=1${y}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":a.additionalConfigurations.webSearch.braveApiKey},signal:u}).finally(f);if(w.ok){let x=await w.json(),C=x.summarizer?.key;if(C&&x.web?.results){let{signal:v,clear:$}=i(),P=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:v}).finally($);if(P.ok){let M=await P.json(),R=x.web.results.slice(0,t).map(_=>({title:_.title,link:_.url,snippet:_.description})),D=M.summary?.map(_=>_.data).join(`
116
- `)||M.title;return JSON.stringify({answer:D,results:R},null,2)}}if(x.web?.results){let v=x.web.results.slice(0,t).map($=>({title:$.title,link:$.url,snippet:$.description}));return JSON.stringify(v,null,2)}}}else{let b=Nf(n),y=b?`&freshness=${b}`:"",w=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(e)}&count=${Math.min(t,20)}${y}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":a.additionalConfigurations.webSearch.braveApiKey},signal:u}).finally(f);if(w.ok){let x=await w.json();if(x.web?.results&&x.web.results.length>0){let C=x.web.results.slice(0,t).map(v=>({title:v.title,link:v.url,snippet:v.description}));return JSON.stringify(C,null,2)}}}}catch(u){L(`[web.search] Brave search failed, falling back: ${u}`)}let{signal:l,clear:p}=i(),m;try{m=await fetch(Ex,{method:"POST",headers:{"User-Agent":Dx,"Content-Type":"application/x-www-form-urlencoded",Origin:"https://lite.duckduckgo.com",Referer:"https://lite.duckduckgo.com/"},body:new URLSearchParams({q:e}).toString(),signal:l})}catch(u){throw u.name==="AbortError"?new Error(s):u}finally{p()}if(m.ok){let u=await m.text(),f=Mx(u,t);if(f.length>0)return JSON.stringify(f,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 Af,Ex,Dx,Ro,Zi=g(()=>{"use strict";c();Af=T(require("cheerio"),1);Ef();Yi();k();Ex="https://lite.duckduckgo.com/lite/",Dx="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";Ro={name:kf,displayName:Sf,description:Rf,parameters:$f,category:_f,execute:Nx}});var If,Lf,jf,Ff,qf,Wf=g(()=>{"use strict";c();If="web.scrape",Lf="Scrape",jf="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.",Ff="network",qf={type:"object",properties:{url:{type:"string",description:"The URL to scrape"},section:{type:"string",description:'Optional section name to extract (e.g., "talks", "about", "experience"). Finds the heading containing this text and extracts content until the next same-level heading. Use web.map first to discover available sections.'},format:{type:"string",description:'Output format: "text" (clean readable text) or "tables" (extract table data as JSON array). Default: "text"',enum:["text","tables"],default:"text"},selector:{type:"string",description:"Optional CSS selector to target a specific element. Only use if you know the exact selector exists."},max_length:{type:"integer",description:"Maximum characters to return (default: 6000). Keep small (3000-6000) to avoid context limits.",default:6e3},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function Lx(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(h(`[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,l=setTimeout(()=>a.abort(),i),p;try{p=await fetch(e,{method:"GET",headers:{"User-Agent":Ax},signal:a.signal})}catch(y){throw y.name==="AbortError"?new Error(`Request timed out after ${i}ms`):y}finally{clearTimeout(l)}if(!p.ok)throw new Error(`Failed to fetch ${e}: HTTP ${p.status} ${p.statusText}`);let m=await p.text(),u=Bf.load(m);for(let y of Ix)u(y).remove();if(n==="tables"){let y=[];return u("table").each((w,x)=>{let C=[],v=[];u(x).find("th").each(($,P)=>{v.push(u(P).text().trim())}),u(x).find("tr").each(($,P)=>{let M=v.length>0?{}:[],R=u(P).find("td");R.length>0&&(R.each((D,_)=>{let W=u(_).text().trim();v.length>0&&v[D]?M[v[D]]=W:M.push(W)}),C.push(M))}),C.length>0&&y.push({id:`Table ${w+1}`,headers:v.length>0?v:void 0,rows:C})}),y.length===0?`No tables found on ${e}`:JSON.stringify(y,null,2)}let f="";if(o){let y=o.toLowerCase(),w=null,x=0;if(u("h1, h2, h3, h4, h5, h6").each((C,v)=>{if(u(v).text().toLowerCase().includes(y))return w=v,x=parseInt(v.tagName.charAt(1)),!1}),w){let C=u(w),v=[],$=C.next();for(;$.length>0;){let P=$.prop("tagName")?.toLowerCase();if(P&&/^h[1-6]$/.test(P)&&parseInt(P.charAt(1))<=x)break;let M=$.text().trim();M&&v.push(M),$=$.next()}v.length>0?(f=v.join(`
125
+ [TRUNCATED: showing 15K of ${l.length} total characters]`:l}var Do,la=g(()=>{"use strict";c();eg();sg();k();Do={name:Vf,displayName:Qf,description:Xf,parameters:Zf,category:Yf,execute:kv}});var ig,ag,lg,cg,pg,mg=g(()=>{"use strict";c();ig="web.search",ag="Search",lg="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.",cg="network",pg={type:"object",properties:{query:{type:"string",description:"The search query"},max_results:{type:"integer",description:"Maximum number of results to return (default: 5)",default:5},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4},include_answer:{type:"boolean",description:"Include AI-generated answer summary (works with Tavily and Brave APIs). Default: false",default:!1},freshness:{type:"string",description:'Time range for fresh/recent results: "day" (last 24h), "week" (last 7 days), "month" (last 31 days), "year" (last 365 days). Ensures latest real-time data. Supported by Tavily and Brave APIs; DuckDuckGo returns general results.',enum:["day","week","month","year"]}},required:["query"]}});function In(r){let e=fg(r);if(!He.existsSync(e))return{};try{let t=He.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return{}}}function Mo(r){let e=In(r),t=Pv(e.tools||e);return h(JSON.stringify(t??{})),t}function ug(r,e){let t=fg(e),o={};try{He.existsSync(t)&&(o=JSON.parse(He.readFileSync(t,"utf-8")))}catch{o={}}o.tools=r,He.writeFileSync(t,JSON.stringify(o,null,4),"utf-8")}function Pv(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??oe.enabled,autoExecute:r.autoExecute??oe.autoExecute,maxToolRounds:r.maxToolRounds??oe.maxToolRounds,toolChoicePolicy:r.toolChoicePolicy??oe.toolChoicePolicy,resultMaxChars:r.resultMaxChars??oe.resultMaxChars,enabledTools:r.enabledTools??oe.enabledTools,enabledToolCategories:r.enabledToolCategories??oe.enabledToolCategories,toolSearch:r.toolSearch??oe.toolSearch,additionalConfigurations:e}}function fg(r){return r?r.endsWith(".json")?Kr.resolve(r):Kr.resolve(r,dg):Kr.resolve(process.cwd(),dg)}var He,Kr,dg,ca=g(()=>{"use strict";c();He=T(require("fs"),1),Kr=T(require("path"),1);xn();k();dg="toolpack.config.json"});function $v(r,e){h("[web.search] Parsing DuckDuckGo Lite response");let t=hg.load(r),o=[];return t("a.result-link").each((s,i)=>{if(o.length>=e)return;let a=t(i),l=a.text().trim(),p=a.attr("href"),m=a.siblings(".result-snippet").text().trim();m||(m=a.parent().text().replace(l,"").trim()),l&&p&&o.push({title:l,link:p,snippet:m.slice(0,200)})}),o}function Ev(r){if(r)switch(r){case"day":return 1;case"week":return 7;case"month":return 31;case"year":return 365;default:return}}function gg(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 Dv(r){let e=r.query,t=r.max_results||5,o=r.include_answer||!1,n=r.freshness;h(`[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 d=new AbortController,f=setTimeout(()=>d.abort(),r.timeout||3e4);return{signal:d.signal,clear:()=>clearTimeout(f)}};if(!e)throw new Error("query is required");let a=Mo();if(h(`[web.search] config=${JSON.stringify(a)}`),a.additionalConfigurations?.webSearch?.tavilyApiKey){h("[web.search] using Tavily API");try{let{signal:d,clear:f}=i(),b=Ev(n),y={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:a.additionalConfigurations.webSearch.tavilyApiKey,query:e,max_results:t,include_answer:o,...b&&{days:b}}),signal:d};h(`[web.search] Tavily request=${JSON.stringify(y)}`);let w=await fetch("https://api.tavily.com/search",y).finally(f);if(w.ok){let x=await w.json();if(x.results&&x.results.length>0){let C=x.results.map(v=>({title:v.title,link:v.url,snippet:v.content}));return o&&x.answer?JSON.stringify({answer:x.answer,results:C},null,2):JSON.stringify(C,null,2)}}else me(`[web.search] Tavily search failed with status ${w.status}`)}catch(d){me(`[web.search] Tavily search failed, falling back: ${d}`)}}if(a.additionalConfigurations?.webSearch?.braveApiKey)try{let{signal:d,clear:f}=i();if(o){let b=gg(n),y=b?`&freshness=${b}`:"",w=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(e)}&count=${Math.min(t,20)}&summary=1${y}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":a.additionalConfigurations.webSearch.braveApiKey},signal:d}).finally(f);if(w.ok){let x=await w.json(),C=x.summarizer?.key;if(C&&x.web?.results){let{signal:v,clear:$}=i(),S=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:v}).finally($);if(S.ok){let M=await S.json(),_=x.web.results.slice(0,t).map(R=>({title:R.title,link:R.url,snippet:R.description})),D=M.summary?.map(R=>R.data).join(`
126
+ `)||M.title;return JSON.stringify({answer:D,results:_},null,2)}}if(x.web?.results){let v=x.web.results.slice(0,t).map($=>({title:$.title,link:$.url,snippet:$.description}));return JSON.stringify(v,null,2)}}}else{let b=gg(n),y=b?`&freshness=${b}`:"",w=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(e)}&count=${Math.min(t,20)}${y}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":a.additionalConfigurations.webSearch.braveApiKey},signal:d}).finally(f);if(w.ok){let x=await w.json();if(x.web?.results&&x.web.results.length>0){let C=x.web.results.slice(0,t).map(v=>({title:v.title,link:v.url,snippet:v.description}));return JSON.stringify(C,null,2)}}}}catch(d){L(`[web.search] Brave search failed, falling back: ${d}`)}let{signal:l,clear:p}=i(),m;try{m=await fetch(_v,{method:"POST",headers:{"User-Agent":Rv,"Content-Type":"application/x-www-form-urlencoded",Origin:"https://lite.duckduckgo.com",Referer:"https://lite.duckduckgo.com/"},body:new URLSearchParams({q:e}).toString(),signal:l})}catch(d){throw d.name==="AbortError"?new Error(s):d}finally{p()}if(m.ok){let d=await m.text(),f=$v(d,t);if(f.length>0)return JSON.stringify(f,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 hg,_v,Rv,Oo,pa=g(()=>{"use strict";c();hg=T(require("cheerio"),1);mg();ca();k();_v="https://lite.duckduckgo.com/lite/",Rv="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";Oo={name:ig,displayName:ag,description:lg,parameters:pg,category:cg,execute:Dv}});var yg,bg,wg,Tg,xg,vg=g(()=>{"use strict";c();yg="web.scrape",bg="Scrape",wg="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.",Tg="network",xg={type:"object",properties:{url:{type:"string",description:"The URL to scrape"},section:{type:"string",description:'Optional section name to extract (e.g., "talks", "about", "experience"). Finds the heading containing this text and extracts content until the next same-level heading. Use web.map first to discover available sections.'},format:{type:"string",description:'Output format: "text" (clean readable text) or "tables" (extract table data as JSON array). Default: "text"',enum:["text","tables"],default:"text"},selector:{type:"string",description:"Optional CSS selector to target a specific element. Only use if you know the exact selector exists."},max_length:{type:"integer",description:"Maximum characters to return (default: 6000). Keep small (3000-6000) to avoid context limits.",default:6e3},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function Av(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(h(`[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,l=setTimeout(()=>a.abort(),i),p;try{p=await fetch(e,{method:"GET",headers:{"User-Agent":Mv},signal:a.signal})}catch(y){throw y.name==="AbortError"?new Error(`Request timed out after ${i}ms`):y}finally{clearTimeout(l)}if(!p.ok)throw new Error(`Failed to fetch ${e}: HTTP ${p.status} ${p.statusText}`);let m=await p.text(),d=kg.load(m);for(let y of Ov)d(y).remove();if(n==="tables"){let y=[];return d("table").each((w,x)=>{let C=[],v=[];d(x).find("th").each(($,S)=>{v.push(d(S).text().trim())}),d(x).find("tr").each(($,S)=>{let M=v.length>0?{}:[],_=d(S).find("td");_.length>0&&(_.each((D,R)=>{let W=d(R).text().trim();v.length>0&&v[D]?M[v[D]]=W:M.push(W)}),C.push(M))}),C.length>0&&y.push({id:`Table ${w+1}`,headers:v.length>0?v:void 0,rows:C})}),y.length===0?`No tables found on ${e}`:JSON.stringify(y,null,2)}let f="";if(o){let y=o.toLowerCase(),w=null,x=0;if(d("h1, h2, h3, h4, h5, h6").each((C,v)=>{if(d(v).text().toLowerCase().includes(y))return w=v,x=parseInt(v.tagName.charAt(1)),!1}),w){let C=d(w),v=[],$=C.next();for(;$.length>0;){let S=$.prop("tagName")?.toLowerCase();if(S&&/^h[1-6]$/.test(S)&&parseInt(S.charAt(1))<=x)break;let M=$.text().trim();M&&v.push(M),$=$.next()}v.length>0?(f=v.join(`
117
127
 
118
128
  `).replace(/\s+/g," ").trim(),f=`[Section: "${o}"]
119
129
 
@@ -121,9 +131,9 @@ ${f}`):f=`[Note: Found heading "${o}" but no content below it. Falling back to f
121
131
 
122
132
  `}else f=`[Note: Section "${o}" not found. Falling back to full page.]
123
133
 
124
- `}if(!f||f.includes("Falling back to full page"))if(f&&f.includes("Falling back to full page")&&(f=""),t){let y=u(t);if(y.length>0)f=y.text().replace(/\s+/g," ").trim();else{for(let w of Uf){let x=u(w);if(x.length>0){let C=x.text().replace(/\s+/g," ").trim();if(C.length>Gf){f=C;break}}}if(f)f=`[Note: Selector "${t}" not found. Showing auto-detected main content instead.]
134
+ `}if(!f||f.includes("Falling back to full page"))if(f&&f.includes("Falling back to full page")&&(f=""),t){let y=d(t);if(y.length>0)f=y.text().replace(/\s+/g," ").trim();else{for(let w of Cg){let x=d(w);if(x.length>0){let C=x.text().replace(/\s+/g," ").trim();if(C.length>Sg){f=C;break}}}if(f)f=`[Note: Selector "${t}" not found. Showing auto-detected main content instead.]
125
135
 
126
- ${f}`;else return`No element found matching selector "${t}" and could not auto-detect main content from ${e}`}}else for(let y of Uf){let w=u(y);if(w.length>0){let x=w.text().replace(/\s+/g," ").trim();if(x.length>Gf){f=x;break}}}if(f||(f=u("body").text().replace(/\s+/g," ").trim(),f&&(f=`[Note: Could not detect main content area. Showing full page text (may include navigation).]
136
+ ${f}`;else return`No element found matching selector "${t}" and could not auto-detect main content from ${e}`}}else for(let y of Cg){let w=d(y);if(w.length>0){let x=w.text().replace(/\s+/g," ").trim();if(x.length>Sg){f=x;break}}}if(f||(f=d("body").text().replace(/\s+/g," ").trim(),f&&(f=`[Note: Could not detect main content area. Showing full page text (may include navigation).]
127
137
 
128
138
  ${f}`)),!f)return`Could not extract any content from ${e}`;if(f.length>s){let y=f.substring(0,s);return`[Warning: Content exceeds ${s} chars (actual: ${f.length} chars). Showing first ${s} chars only.]
129
139
 
@@ -135,18 +145,18 @@ ${y}
135
145
 
136
146
  ... [Content truncated. ${f.length-s} chars remaining. Use section parameter to extract specific sections.]`}return`Page content from ${e}:
137
147
 
138
- ${f}`}var Bf,Ax,Ix,Uf,Gf,_o,ea=g(()=>{"use strict";c();Bf=T(require("cheerio"),1);Wf();k();Ax="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",Ix=["script","style","nav","footer","header","iframe",".ads",".sidebar","noscript"],Uf=["article","main",".content","#content",'[role="main"]',"body"],Gf=200;_o={name:If,displayName:Lf,description:jf,parameters:qf,category:Ff,execute:Lx}});var zf,Hf,Kf,Jf,Vf,Qf=g(()=>{"use strict";c();zf="web.extract_links",Hf="Extract Links",Kf="Extract all links from a webpage. Returns an array of objects with text and URL. Optionally filter by pattern.",Jf="network",Vf={type:"object",properties:{url:{type:"string",description:"The URL to extract links from"},filter:{type:"string",description:'Optional filter: "same-domain" to only include links from the same domain, or a substring to match against URLs'},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function Fx(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":jx},signal:n.signal})}catch(u){throw u.name==="AbortError"?new Error(`Request timed out after ${o}ms`):u}finally{clearTimeout(s)}if(!i.ok)throw new Error(`Failed to fetch ${e}: HTTP ${i.status} ${i.statusText}`);let a=await i.text(),l=Xf.load(a),p=new URL(e),m=[];return l("a[href]").each((u,f)=>{let b=l(f),y=b.attr("href");if(!y)return;let w;try{w=new URL(y,e).toString()}catch{return}if(w.startsWith("javascript:")||w.startsWith("mailto:")||w.startsWith("tel:"))return;let x=b.text().trim()||"[no text]";if(t){if(t==="same-domain")try{if(new URL(w).hostname!==p.hostname)return}catch{return}else if(!w.includes(t))return}m.push({text:x,url:w})}),m.length===0?`No links found on ${e}${t?` matching filter "${t}"`:""}`:JSON.stringify(m,null,2)}var Xf,jx,$o,ta=g(()=>{"use strict";c();Xf=T(require("cheerio"),1);Qf();jx="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";$o={name:zf,displayName:Hf,description:Kf,parameters:Vf,category:Jf,execute:Fx}});var Yf,Zf,eg,tg,og,ng=g(()=>{"use strict";c();Yf="web.map",Zf="Map",eg="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.",tg="network",og={type:"object",properties:{url:{type:"string",description:"The URL to map"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function Wx(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":qx},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=rg.load(i),l=[];if(a("h1, h2, h3, h4, h5, h6").each((m,u)=>{let f=u.tagName.toLowerCase(),b=parseInt(f.charAt(1)),y=a(u).text().trim();y&&l.push({level:b,text:y})}),l.length===0)return`No headings found on ${e}. The page may not have a clear structure.`;let p=`Page outline for ${e}:
148
+ ${f}`}var kg,Mv,Ov,Cg,Sg,Ao,ma=g(()=>{"use strict";c();kg=T(require("cheerio"),1);vg();k();Mv="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",Ov=["script","style","nav","footer","header","iframe",".ads",".sidebar","noscript"],Cg=["article","main",".content","#content",'[role="main"]',"body"],Sg=200;Ao={name:yg,displayName:bg,description:wg,parameters:xg,category:Tg,execute:Av}});var Pg,_g,Rg,$g,Eg,Dg=g(()=>{"use strict";c();Pg="web.extract_links",_g="Extract Links",Rg="Extract all links from a webpage. Returns an array of objects with text and URL. Optionally filter by pattern.",$g="network",Eg={type:"object",properties:{url:{type:"string",description:"The URL to extract links from"},filter:{type:"string",description:'Optional filter: "same-domain" to only include links from the same domain, or a substring to match against URLs'},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function Iv(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":Nv},signal:n.signal})}catch(d){throw d.name==="AbortError"?new Error(`Request timed out after ${o}ms`):d}finally{clearTimeout(s)}if(!i.ok)throw new Error(`Failed to fetch ${e}: HTTP ${i.status} ${i.statusText}`);let a=await i.text(),l=Mg.load(a),p=new URL(e),m=[];return l("a[href]").each((d,f)=>{let b=l(f),y=b.attr("href");if(!y)return;let w;try{w=new URL(y,e).toString()}catch{return}if(w.startsWith("javascript:")||w.startsWith("mailto:")||w.startsWith("tel:"))return;let x=b.text().trim()||"[no text]";if(t){if(t==="same-domain")try{if(new URL(w).hostname!==p.hostname)return}catch{return}else if(!w.includes(t))return}m.push({text:x,url:w})}),m.length===0?`No links found on ${e}${t?` matching filter "${t}"`:""}`:JSON.stringify(m,null,2)}var Mg,Nv,No,da=g(()=>{"use strict";c();Mg=T(require("cheerio"),1);Dg();Nv="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";No={name:Pg,displayName:_g,description:Rg,parameters:Eg,category:$g,execute:Iv}});var Og,Ag,Ng,Ig,Lg,jg=g(()=>{"use strict";c();Og="web.map",Ag="Map",Ng="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.",Ig="network",Lg={type:"object",properties:{url:{type:"string",description:"The URL to map"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function jv(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":Lv},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=Fg.load(i),l=[];if(a("h1, h2, h3, h4, h5, h6").each((m,d)=>{let f=d.tagName.toLowerCase(),b=parseInt(f.charAt(1)),y=a(d).text().trim();y&&l.push({level:b,text:y})}),l.length===0)return`No headings found on ${e}. The page may not have a clear structure.`;let p=`Page outline for ${e}:
139
149
 
140
- `;for(let m of l){let u=" ".repeat(m.level-1);p+=`${u}${"#".repeat(m.level)} ${m.text}
141
- `}return p}var rg,qx,Eo,oa=g(()=>{"use strict";c();rg=T(require("cheerio"),1);ng();qx="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:Yf,displayName:Zf,description:eg,parameters:og,category:tg,execute:Wx}});var sg,ig,ag,lg,cg,pg=g(()=>{"use strict";c();sg="web.metadata",ig="Extract Metadata",ag="Extract Open Graph, Twitter Cards, JSON-LD, and meta tags from a URL.",lg="network",cg={type:"object",properties:{url:{type:"string",description:"The URL to extract metadata from"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function Gx(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":Ux},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=mg.load(i),l={title:a("title").text()||"",description:a('meta[name="description"]').attr("content")||a('meta[property="og:description"]').attr("content")||"",author:a('meta[name="author"]').attr("content")||"",openGraph:{},twitter:{},jsonLd:[]};return a('meta[property^="og:"]').each((p,m)=>{let u=a(m).attr("property")?.replace("og:",""),f=a(m).attr("content");u&&f&&(l.openGraph[u]=f)}),a('meta[name^="twitter:"]').each((p,m)=>{let u=a(m).attr("name")?.replace("twitter:",""),f=a(m).attr("content");u&&f&&(l.twitter[u]=f)}),a('script[type="application/ld+json"]').each((p,m)=>{let u=a(m).html();if(u)try{l.jsonLd.push(JSON.parse(u))}catch{}}),JSON.stringify(l,null,2)}var mg,Ux,Do,na=g(()=>{"use strict";c();mg=T(require("cheerio"),1);pg();Ux="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:sg,displayName:ig,description:ag,parameters:cg,category:lg,execute:Gx}});var dg,ug,fg,gg,hg,yg=g(()=>{"use strict";c();dg="web.sitemap",ug="Extract Sitemap",fg="Parse sitemap.xml or robots.txt to discover all pages on a site. Returns an array of URLs with lastmod/priority if available.",gg="network",hg={type:"object",properties:{url:{type:"string",description:"The base URL or direct sitemap.xml / robots.txt URL"},max_urls:{type:"integer",description:"Maximum number of URLs to return (default: 100)",default:100},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function ra(r,e){let t=new AbortController,o=setTimeout(()=>t.abort(),e);try{return await fetch(r,{method:"GET",headers:{"User-Agent":Bx},signal:t.signal})}catch(n){throw n.name==="AbortError"?new Error(`Request timed out after ${e}ms`):n}finally{clearTimeout(o)}}async function zx(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 ra(n,o),!i.ok&&s&&(n=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await ra(n,o))}catch(p){if(s)n=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await ra(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(),l=[];if(n.endsWith(".xml")||a.trim().startsWith("<")){let p=bg.load(a,{xmlMode:!0}),m=p("sitemap > loc");if(m.length>0)return m.each((f,b)=>{l.length>=t||l.push({loc:p(b).text()})}),JSON.stringify({type:"sitemapindex",urls:l},null,2);p("urlset > url").each((f,b)=>{if(l.length>=t)return;let y=p(b);l.push({loc:y.children("loc").text(),lastmod:y.children("lastmod").text()||void 0,priority:y.children("priority").text()||void 0})})}else{let p=a.split(`
142
- `);for(let m of p){if(l.length>=t)break;let u=m.trim();if(u.toLowerCase().startsWith("sitemap:"))l.push({loc:u.substring(8).trim()});else if(u.toLowerCase().startsWith("allow:")){let f=u.substring(6).trim();l.push({loc:new URL(f,n).toString()})}}}return JSON.stringify(l,null,2)}var bg,Bx,Mo,sa=g(()=>{"use strict";c();bg=T(require("cheerio"),1);yg();Bx="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Mo={name:dg,displayName:ug,description:fg,parameters:hg,category:gg,execute:zx}});var wg,Tg,xg,vg,Cg,Pg=g(()=>{"use strict";c();wg="web.feed",Tg="Extract Feed",xg="Parse RSS/Atom feeds and return structured entries. Requires rss-parser library to be installed.",vg="network",Cg={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 kg(){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 Sg=g(()=>{"use strict";c()});async function Hx(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 kg();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 Oo,ia=g(()=>{"use strict";c();Pg();Sg();Oo={name:wg,displayName:Tg,description:xg,parameters:Cg,category:vg,execute:Hx}});var Rg,_g,$g,Eg,Dg,Mg=g(()=>{"use strict";c();Rg="web.screenshot",_g="Screenshot",$g="Render a page with headless browser and return screenshot Base64 PNG or rendered HTML.",Eg="network",Dg={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 Og(){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 Ng=g(()=>{"use strict";c()});async function Jx(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 Og()).launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]});try{let a=await i.newPage();if(await a.setUserAgent(Kx),await a.setViewport({width:o?.width||1280,height:o?.height||800}),await a.goto(e,{waitUntil:"networkidle2",timeout:n}),t==="png"){let l=await a.screenshot({type:"png",fullPage:!0}),p;return Buffer.isBuffer(l)?p=l.toString("base64"):p=Buffer.from(l).toString("base64"),`data:image/png;base64,${p}`}else return await a.content()}finally{await i.close()}}var Kx,No,aa=g(()=>{"use strict";c();Mg();Ng();Kx="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";No={name:Rg,displayName:_g,description:$g,parameters:Dg,category:Eg,execute:Jx}});var Ag={};le(Ag,{webExtractLinksTool:()=>$o,webFeedTool:()=>Oo,webFetchTool:()=>ko,webMapTool:()=>Eo,webMetadataTool:()=>Do,webScrapeTool:()=>_o,webScreenshotTool:()=>No,webSearchTool:()=>Ro,webSitemapTool:()=>Mo,webToolsProject:()=>la});var la,ca=g(()=>{"use strict";c();Xi();Zi();ea();ta();oa();na();sa();ia();aa();Xi();Zi();ea();ta();oa();na();sa();ia();aa();la={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:[ko,Ro,_o,$o,Eo,Do,Mo,Oo,No],dependencies:{cheerio:"^1.0.0-rc.12"}}});var Ig,Lg,jg,Fg,qg,Wg=g(()=>{"use strict";c();Ig="coding.find_symbol",Lg="Find Symbol",jg="Find function, class, or variable definitions in JavaScript/TypeScript files using AST parsing",Fg="coding",qg={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find (function, class, variable, etc.)"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["symbol","path"]}});function Or(r){let e=(0,Ug.extname)(r).toLowerCase();return Vx[e]||"unknown"}var Ug,Vx,pa=g(()=>{"use strict";c();Ug=require("path"),Vx={".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"jsx",".ts":"typescript",".tsx":"tsx",".py":"python",".go":"go",".rs":"rust",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".hpp":"cpp",".cc":"cpp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".hs":"haskell",".ex":"elixir",".exs":"elixir",".html":"html",".htm":"html",".css":"css",".json":"json",".yaml":"yaml",".yml":"yaml",".md":"markdown",".sh":"bash",".bash":"bash"}});var at,Ae,Be,Bg,Gg,ma,Qx,Nr,zg=g(()=>{"use strict";c();at=T(require("web-tree-sitter"),1),Ae=T(require("fs"),1),Be=T(require("path"),1),Bg=T(require("os"),1),Gg=at.default||at.Parser||at,ma=Be.join(Bg.homedir(),".toolpack-sdk","grammars"),Qx=Be.resolve(__dirname,"../../grammars"),Nr=class{grammars=new Map;isInitialized=!1;async init(){this.isInitialized||(await Gg.init({locateFile(e,t){return Be.join(__dirname,"../../../../../../node_modules/web-tree-sitter",e)}}),this.isInitialized=!0)}async ensureGrammar(e){await this.init();let t=this.grammars.get(e);if(t)return t;let o=await this.resolveGrammarPath(e),s=await(at.Language||Gg.Language).load(o);return this.grammars.set(e,s),s}async resolveGrammarPath(e){let t=`tree-sitter-${e}.wasm`,o=Be.resolve(__dirname,"../../../../../../node_modules/tree-sitter-wasms/out",t);if(Ae.existsSync(o))return o;let n=Be.join(Qx,t);if(Ae.existsSync(n))return n;let s=Be.join(ma,t);return Ae.existsSync(s)||await this.downloadGrammar(e,s),s}async downloadGrammar(e,t){Ae.existsSync(ma)||Ae.mkdirSync(ma,{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);Ae.writeFileSync(t,i)}}});var Mn,Hg,Kg,Xx,Ar,Jg=g(()=>{"use strict";c();Mn=T(require("web-tree-sitter"),1),Hg=T(require("fs"),1),Kg=T(require("crypto"),1);pa();zg();Xx=Mn.default||Mn.Parser||Mn,Ar=class{treeCache=new Map;maxCacheSize=50;parser=null;grammarManager;constructor(){this.grammarManager=new Nr}hash(e){return Kg.createHash("md5").update(e).digest("hex")}async getTree(e,t){let o=t!==void 0?t:Hg.readFileSync(e,"utf-8"),n=this.hash(o),s=this.treeCache.get(e),i=Or(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 Xx),this.parser.setLanguage(a);let l;return s?(s.tree&&s.tree.delete(),l=this.parser.parse(o)):l=this.parser.parse(o),this.treeCache.set(e,{tree:l,language:i,contentHash:n,lastAccessed:Date.now()}),this.evictIfNeeded(),{tree:l,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)}}}});var Vg,da,$e,Ir,Qg=g(()=>{"use strict";c();Vg=require("@babel/parser"),da=T(require("@babel/traverse"),1),$e=da.default||da,Ir=class{parseCode(e){return(0,Vg.parse)(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 l=a.parent,p=l.type==="VariableDeclaration"?l.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 l of n.node.specifiers)if(l.type==="ImportDefaultSpecifier")i.push(l.local.name),a="default";else if(l.type==="ImportNamespaceSpecifier")i.push(`* as ${l.local.name}`),a="namespace";else if(l.type==="ImportSpecifier"){let p=l.imported.type==="Identifier"?l.imported.name:l.imported.value,m=l.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(l){if(l.node.name===t){let p=l.isFunctionDeclaration()||l.isClassDeclaration()||l.parent.type==="VariableDeclarator"&&l.parent.id===l.node||l.parent.type==="TSInterfaceDeclaration"&&l.parent.id===l.node||l.parent.type==="TSTypeAliasDeclaration"&&l.parent.id===l.node;if(!p||o){let m=l.node.loc?.start.line||0,u=l.node.loc?.start.column||0,f=i[m-1]||"";n.push({file:e.filePath,line:m,column:u,context:f.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,l=a.type==="VariableDeclaration"?a.kind:"variable";s={file:n,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:l,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(`
150
+ `;for(let m of l){let d=" ".repeat(m.level-1);p+=`${d}${"#".repeat(m.level)} ${m.text}
151
+ `}return p}var Fg,Lv,Io,ua=g(()=>{"use strict";c();Fg=T(require("cheerio"),1);jg();Lv="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Io={name:Og,displayName:Ag,description:Ng,parameters:Lg,category:Ig,execute:jv}});var qg,Wg,Ug,Gg,Bg,zg=g(()=>{"use strict";c();qg="web.metadata",Wg="Extract Metadata",Ug="Extract Open Graph, Twitter Cards, JSON-LD, and meta tags from a URL.",Gg="network",Bg={type:"object",properties:{url:{type:"string",description:"The URL to extract metadata from"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function qv(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":Fv},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=Hg.load(i),l={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 d=a(m).attr("property")?.replace("og:",""),f=a(m).attr("content");d&&f&&(l.openGraph[d]=f)}),a('meta[name^="twitter:"]').each((p,m)=>{let d=a(m).attr("name")?.replace("twitter:",""),f=a(m).attr("content");d&&f&&(l.twitter[d]=f)}),a('script[type="application/ld+json"]').each((p,m)=>{let d=a(m).html();if(d)try{l.jsonLd.push(JSON.parse(d))}catch{}}),JSON.stringify(l,null,2)}var Hg,Fv,Lo,fa=g(()=>{"use strict";c();Hg=T(require("cheerio"),1);zg();Fv="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Lo={name:qg,displayName:Wg,description:Ug,parameters:Bg,category:Gg,execute:qv}});var Kg,Jg,Vg,Qg,Xg,Yg=g(()=>{"use strict";c();Kg="web.sitemap",Jg="Extract Sitemap",Vg="Parse sitemap.xml or robots.txt to discover all pages on a site. Returns an array of URLs with lastmod/priority if available.",Qg="network",Xg={type:"object",properties:{url:{type:"string",description:"The base URL or direct sitemap.xml / robots.txt URL"},max_urls:{type:"integer",description:"Maximum number of URLs to return (default: 100)",default:100},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function ga(r,e){let t=new AbortController,o=setTimeout(()=>t.abort(),e);try{return await fetch(r,{method:"GET",headers:{"User-Agent":Wv},signal:t.signal})}catch(n){throw n.name==="AbortError"?new Error(`Request timed out after ${e}ms`):n}finally{clearTimeout(o)}}async function Uv(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 ga(n,o),!i.ok&&s&&(n=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await ga(n,o))}catch(p){if(s)n=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await ga(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(),l=[];if(n.endsWith(".xml")||a.trim().startsWith("<")){let p=Zg.load(a,{xmlMode:!0}),m=p("sitemap > loc");if(m.length>0)return m.each((f,b)=>{l.length>=t||l.push({loc:p(b).text()})}),JSON.stringify({type:"sitemapindex",urls:l},null,2);p("urlset > url").each((f,b)=>{if(l.length>=t)return;let y=p(b);l.push({loc:y.children("loc").text(),lastmod:y.children("lastmod").text()||void 0,priority:y.children("priority").text()||void 0})})}else{let p=a.split(`
152
+ `);for(let m of p){if(l.length>=t)break;let d=m.trim();if(d.toLowerCase().startsWith("sitemap:"))l.push({loc:d.substring(8).trim()});else if(d.toLowerCase().startsWith("allow:")){let f=d.substring(6).trim();l.push({loc:new URL(f,n).toString()})}}}return JSON.stringify(l,null,2)}var Zg,Wv,jo,ha=g(()=>{"use strict";c();Zg=T(require("cheerio"),1);Yg();Wv="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";jo={name:Kg,displayName:Jg,description:Vg,parameters:Xg,category:Qg,execute:Uv}});var eh,th,oh,nh,rh,sh=g(()=>{"use strict";c();eh="web.feed",th="Extract Feed",oh="Parse RSS/Atom feeds and return structured entries. Requires rss-parser library to be installed.",nh="network",rh={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 ih(){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 ah=g(()=>{"use strict";c()});async function Gv(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 ih();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 Fo,ya=g(()=>{"use strict";c();sh();ah();Fo={name:eh,displayName:th,description:oh,parameters:rh,category:nh,execute:Gv}});var lh,ch,ph,mh,dh,uh=g(()=>{"use strict";c();lh="web.screenshot",ch="Screenshot",ph="Render a page with headless browser and return screenshot Base64 PNG or rendered HTML.",mh="network",dh={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 fh(){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 gh=g(()=>{"use strict";c()});async function zv(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 fh()).launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]});try{let a=await i.newPage();if(await a.setUserAgent(Bv),await a.setViewport({width:o?.width||1280,height:o?.height||800}),await a.goto(e,{waitUntil:"networkidle2",timeout:n}),t==="png"){let l=await a.screenshot({type:"png",fullPage:!0}),p;return Buffer.isBuffer(l)?p=l.toString("base64"):p=Buffer.from(l).toString("base64"),`data:image/png;base64,${p}`}else return await a.content()}finally{await i.close()}}var Bv,qo,ba=g(()=>{"use strict";c();uh();gh();Bv="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:lh,displayName:ch,description:ph,parameters:dh,category:mh,execute:zv}});var hh={};X(hh,{webExtractLinksTool:()=>No,webFeedTool:()=>Fo,webFetchTool:()=>Do,webMapTool:()=>Io,webMetadataTool:()=>Lo,webScrapeTool:()=>Ao,webScreenshotTool:()=>qo,webSearchTool:()=>Oo,webSitemapTool:()=>jo,webToolsProject:()=>wa});var wa,Ta=g(()=>{"use strict";c();la();pa();ma();da();ua();fa();ha();ya();ba();la();pa();ma();da();ua();fa();ha();ya();ba();wa={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:[Do,Oo,Ao,No,Io,Lo,jo,Fo,qo],dependencies:{cheerio:"^1.0.0-rc.12"}}});var yh,bh,wh,Th,xh,vh=g(()=>{"use strict";c();yh="coding.find_symbol",bh="Find Symbol",wh="Find function, class, or variable definitions in JavaScript/TypeScript files using AST parsing",Th="coding",xh={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find (function, class, variable, etc.)"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["symbol","path"]}});function Jr(r){let e=(0,Ch.extname)(r).toLowerCase();return Hv[e]||"unknown"}var Ch,Hv,xa=g(()=>{"use strict";c();Ch=require("path"),Hv={".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"jsx",".ts":"typescript",".tsx":"tsx",".py":"python",".go":"go",".rs":"rust",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".hpp":"cpp",".cc":"cpp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".hs":"haskell",".ex":"elixir",".exs":"elixir",".html":"html",".htm":"html",".css":"css",".json":"json",".yaml":"yaml",".yml":"yaml",".md":"markdown",".sh":"bash",".bash":"bash"}});var mt,Ne,Ke,kh,Sh,va,Kv,Vr,Ph=g(()=>{"use strict";c();mt=T(require("web-tree-sitter"),1),Ne=T(require("fs"),1),Ke=T(require("path"),1),kh=T(require("os"),1),Sh=mt.default||mt.Parser||mt,va=Ke.join(kh.homedir(),".toolpack-sdk","grammars"),Kv=Ke.resolve(__dirname,"../../grammars"),Vr=class{grammars=new Map;isInitialized=!1;async init(){this.isInitialized||(await Sh.init({locateFile(e,t){return Ke.join(__dirname,"../../../../../../node_modules/web-tree-sitter",e)}}),this.isInitialized=!0)}async ensureGrammar(e){await this.init();let t=this.grammars.get(e);if(t)return t;let o=await this.resolveGrammarPath(e),s=await(mt.Language||Sh.Language).load(o);return this.grammars.set(e,s),s}async resolveGrammarPath(e){let t=`tree-sitter-${e}.wasm`,o=Ke.resolve(__dirname,"../../../../../../node_modules/tree-sitter-wasms/out",t);if(Ne.existsSync(o))return o;let n=Ke.join(Kv,t);if(Ne.existsSync(n))return n;let s=Ke.join(va,t);return Ne.existsSync(s)||await this.downloadGrammar(e,s),s}async downloadGrammar(e,t){Ne.existsSync(va)||Ne.mkdirSync(va,{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);Ne.writeFileSync(t,i)}}});var Ln,_h,Rh,Jv,Qr,$h=g(()=>{"use strict";c();Ln=T(require("web-tree-sitter"),1),_h=T(require("fs"),1),Rh=T(require("crypto"),1);xa();Ph();Jv=Ln.default||Ln.Parser||Ln,Qr=class{treeCache=new Map;maxCacheSize=50;parser=null;grammarManager;constructor(){this.grammarManager=new Vr}hash(e){return Rh.createHash("md5").update(e).digest("hex")}async getTree(e,t){let o=t!==void 0?t:_h.readFileSync(e,"utf-8"),n=this.hash(o),s=this.treeCache.get(e),i=Jr(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 Jv),this.parser.setLanguage(a);let l;return s?(s.tree&&s.tree.delete(),l=this.parser.parse(o)):l=this.parser.parse(o),this.treeCache.set(e,{tree:l,language:i,contentHash:n,lastAccessed:Date.now()}),this.evictIfNeeded(),{tree:l,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)}}}});var Eh,Ca,$e,Xr,Dh=g(()=>{"use strict";c();Eh=require("@babel/parser"),Ca=T(require("@babel/traverse"),1),$e=Ca.default||Ca,Xr=class{parseCode(e){return(0,Eh.parse)(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 l=a.parent,p=l.type==="VariableDeclaration"?l.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 l of n.node.specifiers)if(l.type==="ImportDefaultSpecifier")i.push(l.local.name),a="default";else if(l.type==="ImportNamespaceSpecifier")i.push(`* as ${l.local.name}`),a="namespace";else if(l.type==="ImportSpecifier"){let p=l.imported.type==="Identifier"?l.imported.name:l.imported.value,m=l.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(`
153
+ `),a=this.parseCode(s);$e(a,{Identifier(l){if(l.node.name===t){let p=l.isFunctionDeclaration()||l.isClassDeclaration()||l.parent.type==="VariableDeclarator"&&l.parent.id===l.node||l.parent.type==="TSInterfaceDeclaration"&&l.parent.id===l.node||l.parent.type==="TSTypeAliasDeclaration"&&l.parent.id===l.node;if(!p||o){let m=l.node.loc?.start.line||0,d=l.node.loc?.start.column||0,f=i[m-1]||"";n.push({file:e.filePath,line:m,column:d,context:f.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,l=a.type==="VariableDeclaration"?a.kind:"variable";s={file:n,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:l,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
154
  `),l=Math.max(0,t-1),p=Math.min(a.length,n),m=a.slice(l,p).join(`
145
- `),u=`
155
+ `),d=`
146
156
  function ${i}() {
147
157
  ${m}
148
158
  }
149
- `,f=`${i}();`;return{newFunction:u,replacementCall:f}}async getCallHierarchy(e,t,o){try{let n=this.parseCode(e.content),s=e.filePath,i=null,a="",l=0,p=0;if($e(n,{Function(y){let w=y.node.loc;w&&w.start.line<=t&&w.end&&w.end.line>=t&&(i=y,l=w.start.line,p=w.start.column,y.node.type==="FunctionDeclaration"&&y.node.id?a=y.node.id.name:y.parent.type==="VariableDeclarator"&&y.parent.id.type==="Identifier"?a=y.parent.id.name:y.parent.type==="ClassMethod"||y.parent.type==="ObjectMethod"?y.parent.key.type==="Identifier"&&(a=y.parent.key.name):a="<anonymous>")}}),!i||a==="<anonymous>")return null;let m=[],u=[];$e(n,{CallExpression(y){let w=y.node.loc;if(!w||w.start.line<l||w.end&&w.end.line>l+1e3)return;let x=!1,C=y;for(;C;){if(C.isFunction()&&C.node.type==="FunctionDeclaration"&&C.node.id?.name===a){x=!0;break}C=C.parentPath}if(!x)return;let v=y.node.callee,$="<unknown>";v.type==="Identifier"?$=v.name:v.type==="MemberExpression"&&v.property.type==="Identifier"&&($=v.property.name),$!=="<unknown>"&&u.push({file:s,name:$,line:y.node.loc?.start.line||0,column:y.node.loc?.start.column||0})}}),$e(n,{CallExpression(y){let w=y.node.callee,x=!1;if((w.type==="Identifier"&&w.name===a||w.type==="MemberExpression"&&w.property.type==="Identifier"&&w.property.name===a)&&(x=!0),x){let C="<global>",v=y;for(;v;){if(v.isFunction()){v.node.type==="FunctionDeclaration"&&v.node.id?C=v.node.id.name:v.parent.type==="VariableDeclarator"&&v.parent.id.type==="Identifier"?C=v.parent.id.name:(v.parent.type==="ClassMethod"||v.parent.type==="ObjectMethod")&&v.parent.key.type==="Identifier"&&(C=v.parent.key.name);break}v=v.parentPath}m.push({file:s,name:C,line:y.node.loc?.start.line||0,column:y.node.loc?.start.column||0})}}});let f=[...new Map(m.map(y=>[`${y.name}:${y.line}`,y])).values()],b=[...new Map(u.map(y=>[`${y.name}:${y.line}`,y])).values()];return{file:s,name:a,line:l,column:p,callers:f,callees:b}}catch{return null}}}});function ke(r,e){ua[r]=e}var ua,lt=g(()=>{"use strict";c();ua={}});var Yx,Xg=g(()=>{"use strict";c();lt();Yx={symbols:`
159
+ `,f=`${i}();`;return{newFunction:d,replacementCall:f}}async getCallHierarchy(e,t,o){try{let n=this.parseCode(e.content),s=e.filePath,i=null,a="",l=0,p=0;if($e(n,{Function(y){let w=y.node.loc;w&&w.start.line<=t&&w.end&&w.end.line>=t&&(i=y,l=w.start.line,p=w.start.column,y.node.type==="FunctionDeclaration"&&y.node.id?a=y.node.id.name:y.parent.type==="VariableDeclarator"&&y.parent.id.type==="Identifier"?a=y.parent.id.name:y.parent.type==="ClassMethod"||y.parent.type==="ObjectMethod"?y.parent.key.type==="Identifier"&&(a=y.parent.key.name):a="<anonymous>")}}),!i||a==="<anonymous>")return null;let m=[],d=[];$e(n,{CallExpression(y){let w=y.node.loc;if(!w||w.start.line<l||w.end&&w.end.line>l+1e3)return;let x=!1,C=y;for(;C;){if(C.isFunction()&&C.node.type==="FunctionDeclaration"&&C.node.id?.name===a){x=!0;break}C=C.parentPath}if(!x)return;let v=y.node.callee,$="<unknown>";v.type==="Identifier"?$=v.name:v.type==="MemberExpression"&&v.property.type==="Identifier"&&($=v.property.name),$!=="<unknown>"&&d.push({file:s,name:$,line:y.node.loc?.start.line||0,column:y.node.loc?.start.column||0})}}),$e(n,{CallExpression(y){let w=y.node.callee,x=!1;if((w.type==="Identifier"&&w.name===a||w.type==="MemberExpression"&&w.property.type==="Identifier"&&w.property.name===a)&&(x=!0),x){let C="<global>",v=y;for(;v;){if(v.isFunction()){v.node.type==="FunctionDeclaration"&&v.node.id?C=v.node.id.name:v.parent.type==="VariableDeclarator"&&v.parent.id.type==="Identifier"?C=v.parent.id.name:(v.parent.type==="ClassMethod"||v.parent.type==="ObjectMethod")&&v.parent.key.type==="Identifier"&&(C=v.parent.key.name);break}v=v.parentPath}m.push({file:s,name:C,line:y.node.loc?.start.line||0,column:y.node.loc?.start.column||0})}}});let f=[...new Map(m.map(y=>[`${y.name}:${y.line}`,y])).values()],b=[...new Map(d.map(y=>[`${y.name}:${y.line}`,y])).values()];return{file:s,name:a,line:l,column:p,callers:f,callees:b}}catch{return null}}}});function ke(r,e){Sa[r]=e}var Sa,dt=g(()=>{"use strict";c();Sa={}});var Vv,Mh=g(()=>{"use strict";c();dt();Vv={symbols:`
150
160
  (function_definition
151
161
  name: (identifier) @name.function) @definition.function
152
162
 
@@ -164,7 +174,7 @@ ${m}
164
174
  name: (dotted_name) @name) @import
165
175
  `,references:`
166
176
  (identifier) @reference
167
- `};ke("python",Yx)});var Zx,Yg=g(()=>{"use strict";c();lt();Zx={symbols:`
177
+ `};ke("python",Vv)});var Qv,Oh=g(()=>{"use strict";c();dt();Qv={symbols:`
168
178
  (function_declaration
169
179
  name: (identifier) @name.function) @definition.function
170
180
 
@@ -192,7 +202,7 @@ ${m}
192
202
  (identifier) @reference
193
203
  (field_identifier) @reference
194
204
  (type_identifier) @reference
195
- `};ke("go",Zx)});var ev,Zg=g(()=>{"use strict";c();lt();ev={symbols:`
205
+ `};ke("go",Qv)});var Xv,Ah=g(()=>{"use strict";c();dt();Xv={symbols:`
196
206
  (function_item
197
207
  name: (identifier) @name.function) @definition.function
198
208
 
@@ -214,7 +224,7 @@ ${m}
214
224
  (identifier) @reference
215
225
  (type_identifier) @reference
216
226
  (field_identifier) @reference
217
- `};ke("rust",ev)});var tv,eh=g(()=>{"use strict";c();lt();tv={symbols:`
227
+ `};ke("rust",Xv)});var Yv,Nh=g(()=>{"use strict";c();dt();Yv={symbols:`
218
228
  (method_declaration
219
229
  name: (identifier) @name.method) @definition.method
220
230
 
@@ -235,7 +245,7 @@ ${m}
235
245
  `,references:`
236
246
  (identifier) @reference
237
247
  (type_identifier) @reference
238
- `};ke("java",tv)});var th,oh=g(()=>{"use strict";c();lt();th={symbols:`
248
+ `};ke("java",Yv)});var Ih,Lh=g(()=>{"use strict";c();dt();Ih={symbols:`
239
249
  (function_definition
240
250
  declarator: (function_declarator
241
251
  declarator: (identifier) @name.function)) @definition.function
@@ -256,48 +266,48 @@ ${m}
256
266
  (identifier) @reference
257
267
  (type_identifier) @reference
258
268
  (field_identifier) @reference
259
- `};ke("cpp",th);ke("c",th)});var Lr,nh=g(()=>{"use strict";c();lt();Xg();Yg();Zg();eh();oh();Lr=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=ua[n];if(!i||!i[t])throw new Error(`Query ${t} not found for language ${n}`);let a=i[t],l=s.query(a);return{tree:o,captures:l.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(`
269
+ `};ke("cpp",Ih);ke("c",Ih)});var Yr,jh=g(()=>{"use strict";c();dt();Mh();Oh();Ah();Nh();Lh();Yr=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=Sa[n];if(!i||!i[t])throw new Error(`Query ${t} not found for language ${n}`);let a=i[t],l=s.query(a);return{tree:o,captures:l.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
270
  `),i=[];for(let a of n)if(a.node.text===t){let l=a.node.parent?.type.includes("definition")||a.node.parent?.type.includes("declaration");if(!l||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:!!l})}}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
271
  `),l=Math.max(0,t-1),p=Math.min(a.length,n),m=a.slice(l,p).join(`
262
- `),u="",f="",b=e.filePath.split(".").pop()?.toLowerCase();return b==="py"||b==="pyi"?(u=`
272
+ `),d="",f="",b=e.filePath.split(".").pop()?.toLowerCase();return b==="py"||b==="pyi"?(d=`
263
273
  def ${i}():
264
274
  ${m.split(`
265
275
  `).map(y=>" "+y).join(`
266
276
  `)}
267
- `,f=`${i}()`):b==="go"?(u=`
277
+ `,f=`${i}()`):b==="go"?(d=`
268
278
  func ${i}() {
269
279
  ${m}
270
280
  }
271
- `,f=`${i}()`):b==="rs"?(u=`
281
+ `,f=`${i}()`):b==="rs"?(d=`
272
282
  fn ${i}() {
273
283
  ${m}
274
284
  }
275
- `,f=`${i}();`):b==="sh"||b==="bash"?(u=`
285
+ `,f=`${i}();`):b==="sh"||b==="bash"?(d=`
276
286
  ${i}() {
277
287
  ${m}
278
288
  }
279
- `,f=`${i}`):(u=`
289
+ `,f=`${i}`):(d=`
280
290
  void ${i}() {
281
291
  ${m}
282
292
  }
283
- `,f=`${i}();`),{newFunction:u,replacementCall:f}}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 jr,rh=g(()=>{"use strict";c();pa();Qg();nh();jr=class{constructor(e){this.context=e;this.babelParser=new Ir,this.treeSitterParser=new Lr(this.context)}context;babelParser;treeSitterParser;getParser(e){switch(Or(e)){case"javascript":case"typescript":case"tsx":case"jsx":return this.babelParser;case"python":case"go":case"rust":case"java":case"c":case"cpp":return this.treeSitterParser;default:throw new Error(`Unsupported or unknown language for file: ${e}`)}}}});var Ao,qr,Fr,sh=g(()=>{"use strict";c();Ao=require("fs"),qr=require("path");ye();Fr=class{isBuilt=!1;isBuilding=!1;data={symbolLocations:new Map};fileMtimes=new Map;supportedExtensions=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];async getAllSupportedFiles(e){let t=[];try{let o=(0,Ao.readdirSync)(e,{withFileTypes:!0});for(let n of o){let s=(0,qr.join)(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((0,qr.extname)(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=(0,Ao.statSync)(e).mtimeMs;if(this.fileMtimes.get(e)===o)return;let n=(0,Ao.readFileSync)(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 l=this.data.symbolLocations.get(a.name);l?l.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 ov,q,Io,ye=g(()=>{"use strict";c();Jg();rh();sh();ov=new Ar,q=new jr(ov),Io=new Fr});async function ih(r,e,t){try{let o=(0,Lo.readFileSync)(r,"utf-8");return await q.getParser(r).findSymbols({filePath:r,content:o},e,t)}catch{return[]}}async function ah(r,e,t){let o=[];try{let n=(0,Lo.readdirSync)(r,{withFileTypes:!0});for(let s of n){let i=(0,Wr.join)(r,s.name);if(!(s.name==="node_modules"||s.name===".git"||s.name==="dist")){if(s.isDirectory()){let a=await ah(i,e,t);o.push(...a)}else if(s.isFile()&&nv.includes((0,Wr.extname)(s.name))){let a=await ih(i,e,t);o.push(...a)}}}}catch{}return o}async function rv(r){let e=r.symbol,t=r.path,o=r.kind;if(h(`[coding.find-symbol] execute symbol="${e}" path="${t}" kind=${o??"all"}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let n=(0,Lo.statSync)(t),s;if(n.isDirectory())s=await ah(t,e,o);else if(n.isFile())s=await ih(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 Lo,Wr,nv,jo,fa=g(()=>{"use strict";c();Lo=require("fs"),Wr=require("path");Wg();ye();k();nv=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];jo={name:Ig,displayName:Lg,description:jg,parameters:qg,category:Fg,execute:rv}});var lh,ch,ph,mh,dh,uh=g(()=>{"use strict";c();lh="coding.get_symbols",ch="Get Symbols",ph="List all symbols (functions, classes, variables, etc.) in a JavaScript/TypeScript file",mh="coding",dh={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["file"]}});async function sv(r){let e=r.file,t=r.kind;if(h(`[coding.get-symbols] execute file="${e}" kind=${t??"all"}`),!e)throw new Error("file is required");try{let o=(0,fh.readFileSync)(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 fh,Fo,ga=g(()=>{"use strict";c();fh=require("fs");uh();ye();k();Fo={name:lh,displayName:ch,description:ph,parameters:dh,category:mh,execute:sv}});var gh,hh,yh,bh,wh,Th=g(()=>{"use strict";c();gh="coding.get_imports",hh="Get Imports",yh="List all import statements in a JavaScript/TypeScript file",bh="coding",wh={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"}},required:["file"]}});async function iv(r){let e=r.file;if(h(`[coding.get-imports] execute file="${e}"`),!e)throw new Error("file is required");try{let t=(0,xh.readFileSync)(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 xh,qo,ha=g(()=>{"use strict";c();xh=require("fs");Th();ye();k();qo={name:gh,displayName:hh,description:yh,parameters:wh,category:bh,execute:iv}});var vh,Ch,Ph,kh,Sh,Rh=g(()=>{"use strict";c();vh="coding.find_references",Ch="Find References",Ph="Find all references to a symbol across JavaScript/TypeScript files",kh="coding",Sh={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find references for"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},includeDeclaration:{type:"boolean",description:"Include the symbol declaration in results (default: false)"}},required:["symbol","path"]}});async function _h(r,e,t){try{let o=(0,Ur.readFileSync)(r,"utf-8");return await q.getParser(r).findReferences({filePath:r,content:o},e,t)}catch{return[]}}async function av(r,e,t){let o=[];await Io.buildIndex(r);let n=await Io.getDefinitionFiles(e,r);for(let s of n)if(s.startsWith(r)){let i=await _h(s,e,t);o.push(...i)}return o}async function lv(r){let e=r.symbol,t=r.path,o=r.includeDeclaration===!0;if(h(`[coding.find-references] execute symbol="${e}" path="${t}" includeDecl=${o}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let n=(0,Ur.statSync)(t),s;if(n.isDirectory())s=await av(t,e,o);else if(n.isFile())s=await _h(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 Ur,Wo,ya=g(()=>{"use strict";c();Ur=require("fs");Rh();ye();k();Wo={name:vh,displayName:Ch,description:Ph,parameters:Sh,category:kh,execute:lv}});var $h,Eh,Dh,Mh,Oh,Nh=g(()=>{"use strict";c();$h="coding.go_to_definition",Eh="Go To Definition",Dh="Jump to the definition of a symbol at a specific location in a file",Mh="coding",Oh={type:"object",properties:{file:{type:"string",description:"Path to the file containing the symbol reference"},line:{type:"integer",description:"Line number where the symbol is referenced (1-indexed)"},column:{type:"integer",description:"Column number where the symbol is referenced (0-indexed)"},searchPath:{type:"string",description:"Optional: directory to search for the definition (defaults to file directory)"}},required:["file","line","column"]}});async function cv(r,e,t){try{let o=(0,On.readFileSync)(r,"utf-8");return await q.getParser(r).getSymbolAtPosition({filePath:r,content:o},e,t)}catch{return null}}async function Ih(r,e){try{let t=(0,On.readFileSync)(r,"utf-8");return await q.getParser(r).getDefinition({filePath:r,content:t},e)}catch{return null}}async function pv(r,e){await Io.buildIndex(r);let t=await Io.getDefinitionFiles(e,r);for(let o of t)if(o.startsWith(r)){let n=await Ih(o,e);if(n)return n}return null}async function mv(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 cv(e,t,o);if(!s)return JSON.stringify({found:!1,message:`No symbol found at ${e}:${t}:${o}`},null,2);let i=await Ih(e,s);if(!i){let a=n||(0,Ah.dirname)(e);(0,On.statSync)(a).isDirectory()&&(i=await pv(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 On,Ah,Uo,ba=g(()=>{"use strict";c();On=require("fs"),Ah=require("path");Nh();ye();Uo={name:$h,displayName:Eh,description:Dh,parameters:Oh,category:Mh,execute:mv}});var Lh,jh,Fh,qh,Wh,Uh=g(()=>{"use strict";c();Lh="coding.multi_file_edit",jh="Multi-File Edit",Fh="Edit multiple files atomically with rollback on failure",qh="coding",Wh={type:"object",properties:{edits:{type:"array",items:{type:"object",properties:{file:{type:"string"},changes:{type:"array",items:{type:"object",properties:{oldText:{type:"string"},newText:{type:"string"}}}}}},description:"Array of file edits, each with file path and array of text replacements"},atomic:{type:"boolean",description:"Atomic mode: rollback all edits if any fails (default: true)"}},required:["edits"]}});async function dv(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(!(0,ct.existsSync)(s.file))throw new Error(`File does not exist: ${s.file}`)}let o=[],n=[];try{for(let s of e){let i=(0,ct.readFileSync)(s.file,"utf-8");t&&o.push({file:s.file,content:i});let a=i;for(let l of s.changes){if(!l.oldText)throw new Error("Each change must have oldText property");if(l.newText===void 0)throw new Error("Each change must have newText property");let p=(a.match(new RegExp(uv(l.oldText),"g"))||[]).length;if(p===0)throw new Error(`Text not found in ${s.file}: "${l.oldText.substring(0,50)}..."`);if(p>1)throw new Error(`Ambiguous replacement in ${s.file}: "${l.oldText.substring(0,50)}..." appears ${p} times`);a=a.replace(l.oldText,l.newText)}(0,ct.writeFileSync)(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{(0,ct.writeFileSync)(i.file,i.content,"utf-8")}catch{}throw new Error(`Multi-file edit failed and rolled back: ${s.message}`)}throw new Error(`Multi-file edit failed: ${s.message}`)}}function uv(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ct,Go,wa=g(()=>{"use strict";c();ct=require("fs");Uh();Go={name:Lh,displayName:jh,description:Fh,parameters:Wh,category:qh,execute:dv,confirmation:{level:"high",reason:"This will modify multiple source code files atomically.",showArgs:["edits"]}}});var Gh,Bh,zh,Hh,Kh,Jh=g(()=>{"use strict";c();Gh="coding.refactor_rename",Bh="Refactor Rename",zh="Rename a symbol across the entire codebase intelligently",Hh="coding",Kh={type:"object",properties:{symbol:{type:"string",description:"Current name of the symbol to rename"},newName:{type:"string",description:"New name for the symbol"},path:{type:"string",description:"Directory path to search and rename in"},dryRun:{type:"boolean",description:"Preview changes without applying them (default: false)"}},required:["symbol","newName","path"]}});function hv(r,e,t,o){let n=[];try{let s=(0,Bo.readFileSync)(r,"utf-8"),i=s.split(`
284
- `),a=(0,Vh.parse)(s,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]}),l=[];if(fv(a,{Identifier(p){if(p.node.name===e){let m=p.node.loc?.start.line||0,u=p.node.loc?.start.column||0;l.push({line:m,column:u,length:e.length}),n.push({file:r,line:m,column:u,oldName:e,newName:t})}}}),!o&&l.length>0){l.sort((m,u)=>m.line!==u.line?u.line-m.line:u.column-m.column);let p=[...i];for(let m of l){let u=m.line-1;if(u>=0&&u<p.length){let f=p[u],b=f.substring(0,m.column),y=f.substring(m.column+m.length);p[u]=b+t+y}}(0,Bo.writeFileSync)(r,p.join(`
285
- `),"utf-8")}}catch{}return{file:r,occurrences:n.length,changes:n}}function Qh(r,e,t,o){let n=[];try{let s=(0,Bo.readdirSync)(r,{withFileTypes:!0});for(let i of s){let a=(0,Gr.join)(r,i.name);if(!(i.name==="node_modules"||i.name===".git"||i.name==="dist")){if(i.isDirectory())n.push(...Qh(a,e,t,o));else if(i.isFile()&&gv.includes((0,Gr.extname)(i.name))){let l=hv(a,e,t,o);l.occurrences>0&&n.push(l)}}}}catch{}return n}async function yv(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=Qh(o,e,t,n),i=s.reduce((l,p)=>l+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 Bo,Gr,Vh,Ta,fv,gv,zo,xa=g(()=>{"use strict";c();Bo=require("fs"),Gr=require("path"),Vh=require("@babel/parser"),Ta=T(require("@babel/traverse"),1);Jh();fv=Ta.default||Ta,gv=[".js",".jsx",".ts",".tsx",".mjs",".cjs"];zo={name:Gh,displayName:Bh,description:zh,parameters:Kh,category:Hh,execute:yv,confirmation:{level:"high",reason:"This will rename a symbol across multiple files, rewriting source code without backup.",showArgs:["symbol","newName"]}}});var Xh,Yh,Zh,ey,ty,oy=g(()=>{"use strict";c();Xh="coding.get_outline",Yh="Get File Outline",Zh="Gets a hierarchical outline of symbols (classes, functions, methods) in a specified file.",ey="coding",ty={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to outline"}},required:["file"]}});async function bv(r){let e=r.file;if(h(`[coding.get-outline] execute file="${e}"`),!e)throw new Error("file is required");try{if(!(0,Br.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,Br.readFileSync)(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 Br,Ho,va=g(()=>{"use strict";c();Br=require("fs");oy();ye();k();Ho={name:Xh,displayName:Yh,description:Zh,parameters:ty,category:ey,execute:bv}});var ny,ry,sy,iy,ay,ly=g(()=>{"use strict";c();ny="coding.get_diagnostics",ry="Get File Diagnostics",sy="Gets syntax errors and warnings for a file utilizing AST parsing.",iy="coding",ay={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to check for diagnostics"}},required:["file"]}});async function wv(r){let e=r.file;if(!e)throw new Error("file is required");try{if(!(0,zr.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,zr.readFileSync)(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 zr,Ko,Ca=g(()=>{"use strict";c();zr=require("fs");ly();ye();Ko={name:ny,displayName:ry,description:sy,parameters:ay,category:iy,execute:wv}});var cy,py,my,dy,uy,fy=g(()=>{"use strict";c();cy="coding.get_exports",py="Get File Exports",my="Lists all symbols exported by a file.",dy="coding",uy={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"}},required:["file"]}});async function Tv(r){let e=r.file;if(h(`[coding.get-exports] execute file="${e}"`),!e)throw new Error("file is required");try{if(!(0,Hr.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,Hr.readFileSync)(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 Hr,Jo,Pa=g(()=>{"use strict";c();Hr=require("fs");fy();ye();k();Jo={name:cy,displayName:py,description:my,parameters:uy,category:dy,execute:Tv}});var gy,hy,yy,by,wy,Ty=g(()=>{"use strict";c();gy="coding.extract_function",hy="Extract Function",yy="Extracts a selected code region into a new function, automatically detecting required parameters and return values.",by="coding",wy={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"},startLine:{type:"number",description:"1-indexed start line of the code to extract"},startColumn:{type:"number",description:"0-indexed start column of the code to extract"},endLine:{type:"number",description:"1-indexed end line of the code to extract"},endColumn:{type:"number",description:"0-indexed end column of the code to extract"},newFunctionName:{type:"string",description:"The name for the newly extracted function"}},required:["file","startLine","startColumn","endLine","endColumn","newFunctionName"]}});async function xv(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(!(0,Kr.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let a=(0,Kr.readFileSync)(e,"utf-8"),l=q.getParser(e);if(!l.extractFunction)return JSON.stringify({file:e,error:"Function extraction is not specifically implemented for this language yet."});let p=await l.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 Kr,Vo,ka=g(()=>{"use strict";c();Kr=require("fs");Ty();ye();Vo={name:gy,displayName:hy,description:yy,parameters:wy,category:by,execute:xv}});var xy,vy,Cy,Py,ky,Sy=g(()=>{"use strict";c();xy="coding.get_call_hierarchy",vy="Get Call Hierarchy",Cy="Shows callers and callees of a specific function or method.",Py="coding",ky={type:"object",properties:{file:{type:"string",description:"The absolute path to the file containing the function"},line:{type:"number",description:"1-indexed line number where the function is defined or called"},column:{type:"number",description:"0-indexed column number where the function is defined or called"}},required:["file","line","column"]}});async function vv(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(!(0,Jr.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let n=(0,Jr.readFileSync)(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 Jr,Qo,Sa=g(()=>{"use strict";c();Jr=require("fs");Sy();ye();Qo={name:xy,displayName:vy,description:Cy,parameters:ky,category:Py,execute:vv}});var Ry={};le(Ry,{codingExtractFunctionTool:()=>Vo,codingFindReferencesTool:()=>Wo,codingFindSymbolTool:()=>jo,codingGetCallHierarchyTool:()=>Qo,codingGetDiagnosticsTool:()=>Ko,codingGetExportsTool:()=>Jo,codingGetImportsTool:()=>qo,codingGetOutlineTool:()=>Ho,codingGetSymbolsTool:()=>Fo,codingGoToDefinitionTool:()=>Uo,codingMultiFileEditTool:()=>Go,codingRefactorRenameTool:()=>zo,codingToolsProject:()=>Ra});var Ra,_a=g(()=>{"use strict";c();fa();ga();ha();ya();ba();wa();xa();va();Ca();Pa();ka();Sa();fa();ga();ha();ya();ba();wa();xa();va();Ca();Pa();ka();Sa();Ra={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:[jo,Fo,qo,Wo,Uo,Ho,Ko,Jo,Vo,Qo,Go,zo],dependencies:{"@babel/parser":"^7.24.0","@babel/traverse":"^7.24.0","@babel/types":"^7.24.0"}}});var _y,$y=g(()=>{"use strict";c();_y={type:"object",properties:{path:{type:"string",description:"Optional path or directory to check the status for. If omitted, checks the entire repository."}}}});function G(r){let e={baseDir:r||process.cwd(),binary:"git",maxConcurrentProcesses:6};return(0,Ey.simpleGit)(e)}var Ey,Se=g(()=>{"use strict";c();Ey=require("simple-git")});var Nn,Dy=g(()=>{"use strict";c();$y();Se();Nn={name:"git.status",displayName:"Git Status",description:"Get the working tree status, including modified, staged, and untracked files.",category:"version-control",parameters:_y,execute:async r=>{let e=r.path;try{let o=await G().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 My,Oy=g(()=>{"use strict";c();My={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 An,Ny=g(()=>{"use strict";c();Oy();Se();An={name:"git.diff",displayName:"Git Diff",description:"Show changes between commits, commit and working tree, etc.",category:"version-control",parameters:My,execute:async r=>{let e=r.path,t=r.base,o=r.head,n=r.staged,s=r.cloneDir;try{let i=G(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 l=await i.diff(a);return l||"No changes found."}catch(i){return`Error getting git diff: ${i instanceof Error?i.message:String(i)}`}}}});var Ay,Iy=g(()=>{"use strict";c();Ay={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 In,Ly=g(()=>{"use strict";c();Iy();Se();In={name:"git.log",displayName:"Git Log",description:"Show commit logs.",category:"version-control",parameters:Ay,execute:async r=>{let e=r.maxCount||10,t=r.path,o=r.cloneDir;try{let n=G(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}
293
+ `,f=`${i}();`),{newFunction:d,replacementCall:f}}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 Zr,Fh=g(()=>{"use strict";c();xa();Dh();jh();Zr=class{constructor(e){this.context=e;this.babelParser=new Xr,this.treeSitterParser=new Yr(this.context)}context;babelParser;treeSitterParser;getParser(e){switch(Jr(e)){case"javascript":case"typescript":case"tsx":case"jsx":return this.babelParser;case"python":case"go":case"rust":case"java":case"c":case"cpp":return this.treeSitterParser;default:throw new Error(`Unsupported or unknown language for file: ${e}`)}}}});var Wo,ts,es,qh=g(()=>{"use strict";c();Wo=require("fs"),ts=require("path");ye();es=class{isBuilt=!1;isBuilding=!1;data={symbolLocations:new Map};fileMtimes=new Map;supportedExtensions=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];async getAllSupportedFiles(e){let t=[];try{let o=(0,Wo.readdirSync)(e,{withFileTypes:!0});for(let n of o){let s=(0,ts.join)(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((0,ts.extname)(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=(0,Wo.statSync)(e).mtimeMs;if(this.fileMtimes.get(e)===o)return;let n=(0,Wo.readFileSync)(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 l=this.data.symbolLocations.get(a.name);l?l.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 Zv,q,Uo,ye=g(()=>{"use strict";c();$h();Fh();qh();Zv=new Qr,q=new Zr(Zv),Uo=new es});async function Wh(r,e,t){try{let o=(0,Go.readFileSync)(r,"utf-8");return await q.getParser(r).findSymbols({filePath:r,content:o},e,t)}catch{return[]}}async function Uh(r,e,t){let o=[];try{let n=(0,Go.readdirSync)(r,{withFileTypes:!0});for(let s of n){let i=(0,os.join)(r,s.name);if(!(s.name==="node_modules"||s.name===".git"||s.name==="dist")){if(s.isDirectory()){let a=await Uh(i,e,t);o.push(...a)}else if(s.isFile()&&eC.includes((0,os.extname)(s.name))){let a=await Wh(i,e,t);o.push(...a)}}}}catch{}return o}async function tC(r){let e=r.symbol,t=r.path,o=r.kind;if(h(`[coding.find-symbol] execute symbol="${e}" path="${t}" kind=${o??"all"}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let n=(0,Go.statSync)(t),s;if(n.isDirectory())s=await Uh(t,e,o);else if(n.isFile())s=await Wh(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 Go,os,eC,Bo,ka=g(()=>{"use strict";c();Go=require("fs"),os=require("path");vh();ye();k();eC=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];Bo={name:yh,displayName:bh,description:wh,parameters:xh,category:Th,execute:tC}});var Gh,Bh,zh,Hh,Kh,Jh=g(()=>{"use strict";c();Gh="coding.get_symbols",Bh="Get Symbols",zh="List all symbols (functions, classes, variables, etc.) in a JavaScript/TypeScript file",Hh="coding",Kh={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["file"]}});async function oC(r){let e=r.file,t=r.kind;if(h(`[coding.get-symbols] execute file="${e}" kind=${t??"all"}`),!e)throw new Error("file is required");try{let o=(0,Vh.readFileSync)(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 Vh,zo,Pa=g(()=>{"use strict";c();Vh=require("fs");Jh();ye();k();zo={name:Gh,displayName:Bh,description:zh,parameters:Kh,category:Hh,execute:oC}});var Qh,Xh,Yh,Zh,ey,ty=g(()=>{"use strict";c();Qh="coding.get_imports",Xh="Get Imports",Yh="List all import statements in a JavaScript/TypeScript file",Zh="coding",ey={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"}},required:["file"]}});async function nC(r){let e=r.file;if(h(`[coding.get-imports] execute file="${e}"`),!e)throw new Error("file is required");try{let t=(0,oy.readFileSync)(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 oy,Ho,_a=g(()=>{"use strict";c();oy=require("fs");ty();ye();k();Ho={name:Qh,displayName:Xh,description:Yh,parameters:ey,category:Zh,execute:nC}});var ny,ry,sy,iy,ay,ly=g(()=>{"use strict";c();ny="coding.find_references",ry="Find References",sy="Find all references to a symbol across JavaScript/TypeScript files",iy="coding",ay={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find references for"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},includeDeclaration:{type:"boolean",description:"Include the symbol declaration in results (default: false)"}},required:["symbol","path"]}});async function cy(r,e,t){try{let o=(0,ns.readFileSync)(r,"utf-8");return await q.getParser(r).findReferences({filePath:r,content:o},e,t)}catch{return[]}}async function rC(r,e,t){let o=[];await Uo.buildIndex(r);let n=await Uo.getDefinitionFiles(e,r);for(let s of n)if(s.startsWith(r)){let i=await cy(s,e,t);o.push(...i)}return o}async function sC(r){let e=r.symbol,t=r.path,o=r.includeDeclaration===!0;if(h(`[coding.find-references] execute symbol="${e}" path="${t}" includeDecl=${o}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let n=(0,ns.statSync)(t),s;if(n.isDirectory())s=await rC(t,e,o);else if(n.isFile())s=await cy(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 ns,Ko,Ra=g(()=>{"use strict";c();ns=require("fs");ly();ye();k();Ko={name:ny,displayName:ry,description:sy,parameters:ay,category:iy,execute:sC}});var py,my,dy,uy,fy,gy=g(()=>{"use strict";c();py="coding.go_to_definition",my="Go To Definition",dy="Jump to the definition of a symbol at a specific location in a file",uy="coding",fy={type:"object",properties:{file:{type:"string",description:"Path to the file containing the symbol reference"},line:{type:"integer",description:"Line number where the symbol is referenced (1-indexed)"},column:{type:"integer",description:"Column number where the symbol is referenced (0-indexed)"},searchPath:{type:"string",description:"Optional: directory to search for the definition (defaults to file directory)"}},required:["file","line","column"]}});async function iC(r,e,t){try{let o=(0,jn.readFileSync)(r,"utf-8");return await q.getParser(r).getSymbolAtPosition({filePath:r,content:o},e,t)}catch{return null}}async function yy(r,e){try{let t=(0,jn.readFileSync)(r,"utf-8");return await q.getParser(r).getDefinition({filePath:r,content:t},e)}catch{return null}}async function aC(r,e){await Uo.buildIndex(r);let t=await Uo.getDefinitionFiles(e,r);for(let o of t)if(o.startsWith(r)){let n=await yy(o,e);if(n)return n}return null}async function lC(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 iC(e,t,o);if(!s)return JSON.stringify({found:!1,message:`No symbol found at ${e}:${t}:${o}`},null,2);let i=await yy(e,s);if(!i){let a=n||(0,hy.dirname)(e);(0,jn.statSync)(a).isDirectory()&&(i=await aC(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 jn,hy,Jo,$a=g(()=>{"use strict";c();jn=require("fs"),hy=require("path");gy();ye();Jo={name:py,displayName:my,description:dy,parameters:fy,category:uy,execute:lC}});var by,wy,Ty,xy,vy,Cy=g(()=>{"use strict";c();by="coding.multi_file_edit",wy="Multi-File Edit",Ty="Edit multiple files atomically with rollback on failure",xy="coding",vy={type:"object",properties:{edits:{type:"array",items:{type:"object",properties:{file:{type:"string"},changes:{type:"array",items:{type:"object",properties:{oldText:{type:"string"},newText:{type:"string"}}}}}},description:"Array of file edits, each with file path and array of text replacements"},atomic:{type:"boolean",description:"Atomic mode: rollback all edits if any fails (default: true)"}},required:["edits"]}});async function cC(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(!(0,ut.existsSync)(s.file))throw new Error(`File does not exist: ${s.file}`)}let o=[],n=[];try{for(let s of e){let i=(0,ut.readFileSync)(s.file,"utf-8");t&&o.push({file:s.file,content:i});let a=i;for(let l of s.changes){if(!l.oldText)throw new Error("Each change must have oldText property");if(l.newText===void 0)throw new Error("Each change must have newText property");let p=(a.match(new RegExp(pC(l.oldText),"g"))||[]).length;if(p===0)throw new Error(`Text not found in ${s.file}: "${l.oldText.substring(0,50)}..."`);if(p>1)throw new Error(`Ambiguous replacement in ${s.file}: "${l.oldText.substring(0,50)}..." appears ${p} times`);a=a.replace(l.oldText,l.newText)}(0,ut.writeFileSync)(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{(0,ut.writeFileSync)(i.file,i.content,"utf-8")}catch{}throw new Error(`Multi-file edit failed and rolled back: ${s.message}`)}throw new Error(`Multi-file edit failed: ${s.message}`)}}function pC(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ut,Vo,Ea=g(()=>{"use strict";c();ut=require("fs");Cy();Vo={name:by,displayName:wy,description:Ty,parameters:vy,category:xy,execute:cC,confirmation:{level:"high",reason:"This will modify multiple source code files atomically.",showArgs:["edits"]}}});var Sy,ky,Py,_y,Ry,$y=g(()=>{"use strict";c();Sy="coding.refactor_rename",ky="Refactor Rename",Py="Rename a symbol across the entire codebase intelligently",_y="coding",Ry={type:"object",properties:{symbol:{type:"string",description:"Current name of the symbol to rename"},newName:{type:"string",description:"New name for the symbol"},path:{type:"string",description:"Directory path to search and rename in"},dryRun:{type:"boolean",description:"Preview changes without applying them (default: false)"}},required:["symbol","newName","path"]}});function uC(r,e,t,o){let n=[];try{let s=(0,Qo.readFileSync)(r,"utf-8"),i=s.split(`
294
+ `),a=(0,Ey.parse)(s,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]}),l=[];if(mC(a,{Identifier(p){if(p.node.name===e){let m=p.node.loc?.start.line||0,d=p.node.loc?.start.column||0;l.push({line:m,column:d,length:e.length}),n.push({file:r,line:m,column:d,oldName:e,newName:t})}}}),!o&&l.length>0){l.sort((m,d)=>m.line!==d.line?d.line-m.line:d.column-m.column);let p=[...i];for(let m of l){let d=m.line-1;if(d>=0&&d<p.length){let f=p[d],b=f.substring(0,m.column),y=f.substring(m.column+m.length);p[d]=b+t+y}}(0,Qo.writeFileSync)(r,p.join(`
295
+ `),"utf-8")}}catch{}return{file:r,occurrences:n.length,changes:n}}function Dy(r,e,t,o){let n=[];try{let s=(0,Qo.readdirSync)(r,{withFileTypes:!0});for(let i of s){let a=(0,rs.join)(r,i.name);if(!(i.name==="node_modules"||i.name===".git"||i.name==="dist")){if(i.isDirectory())n.push(...Dy(a,e,t,o));else if(i.isFile()&&dC.includes((0,rs.extname)(i.name))){let l=uC(a,e,t,o);l.occurrences>0&&n.push(l)}}}}catch{}return n}async function fC(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=Dy(o,e,t,n),i=s.reduce((l,p)=>l+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 Qo,rs,Ey,Da,mC,dC,Xo,Ma=g(()=>{"use strict";c();Qo=require("fs"),rs=require("path"),Ey=require("@babel/parser"),Da=T(require("@babel/traverse"),1);$y();mC=Da.default||Da,dC=[".js",".jsx",".ts",".tsx",".mjs",".cjs"];Xo={name:Sy,displayName:ky,description:Py,parameters:Ry,category:_y,execute:fC,confirmation:{level:"high",reason:"This will rename a symbol across multiple files, rewriting source code without backup.",showArgs:["symbol","newName"]}}});var My,Oy,Ay,Ny,Iy,Ly=g(()=>{"use strict";c();My="coding.get_outline",Oy="Get File Outline",Ay="Gets a hierarchical outline of symbols (classes, functions, methods) in a specified file.",Ny="coding",Iy={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to outline"}},required:["file"]}});async function gC(r){let e=r.file;if(h(`[coding.get-outline] execute file="${e}"`),!e)throw new Error("file is required");try{if(!(0,ss.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,ss.readFileSync)(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 ss,Yo,Oa=g(()=>{"use strict";c();ss=require("fs");Ly();ye();k();Yo={name:My,displayName:Oy,description:Ay,parameters:Iy,category:Ny,execute:gC}});var jy,Fy,qy,Wy,Uy,Gy=g(()=>{"use strict";c();jy="coding.get_diagnostics",Fy="Get File Diagnostics",qy="Gets syntax errors and warnings for a file utilizing AST parsing.",Wy="coding",Uy={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to check for diagnostics"}},required:["file"]}});async function hC(r){let e=r.file;if(!e)throw new Error("file is required");try{if(!(0,is.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,is.readFileSync)(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 is,Zo,Aa=g(()=>{"use strict";c();is=require("fs");Gy();ye();Zo={name:jy,displayName:Fy,description:qy,parameters:Uy,category:Wy,execute:hC}});var By,zy,Hy,Ky,Jy,Vy=g(()=>{"use strict";c();By="coding.get_exports",zy="Get File Exports",Hy="Lists all symbols exported by a file.",Ky="coding",Jy={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"}},required:["file"]}});async function yC(r){let e=r.file;if(h(`[coding.get-exports] execute file="${e}"`),!e)throw new Error("file is required");try{if(!(0,as.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,as.readFileSync)(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 as,en,Na=g(()=>{"use strict";c();as=require("fs");Vy();ye();k();en={name:By,displayName:zy,description:Hy,parameters:Jy,category:Ky,execute:yC}});var Qy,Xy,Yy,Zy,eb,tb=g(()=>{"use strict";c();Qy="coding.extract_function",Xy="Extract Function",Yy="Extracts a selected code region into a new function, automatically detecting required parameters and return values.",Zy="coding",eb={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"},startLine:{type:"number",description:"1-indexed start line of the code to extract"},startColumn:{type:"number",description:"0-indexed start column of the code to extract"},endLine:{type:"number",description:"1-indexed end line of the code to extract"},endColumn:{type:"number",description:"0-indexed end column of the code to extract"},newFunctionName:{type:"string",description:"The name for the newly extracted function"}},required:["file","startLine","startColumn","endLine","endColumn","newFunctionName"]}});async function bC(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(!(0,ls.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let a=(0,ls.readFileSync)(e,"utf-8"),l=q.getParser(e);if(!l.extractFunction)return JSON.stringify({file:e,error:"Function extraction is not specifically implemented for this language yet."});let p=await l.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 ls,tn,Ia=g(()=>{"use strict";c();ls=require("fs");tb();ye();tn={name:Qy,displayName:Xy,description:Yy,parameters:eb,category:Zy,execute:bC}});var ob,nb,rb,sb,ib,ab=g(()=>{"use strict";c();ob="coding.get_call_hierarchy",nb="Get Call Hierarchy",rb="Shows callers and callees of a specific function or method.",sb="coding",ib={type:"object",properties:{file:{type:"string",description:"The absolute path to the file containing the function"},line:{type:"number",description:"1-indexed line number where the function is defined or called"},column:{type:"number",description:"0-indexed column number where the function is defined or called"}},required:["file","line","column"]}});async function wC(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(!(0,cs.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let n=(0,cs.readFileSync)(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 cs,on,La=g(()=>{"use strict";c();cs=require("fs");ab();ye();on={name:ob,displayName:nb,description:rb,parameters:ib,category:sb,execute:wC}});var lb={};X(lb,{codingExtractFunctionTool:()=>tn,codingFindReferencesTool:()=>Ko,codingFindSymbolTool:()=>Bo,codingGetCallHierarchyTool:()=>on,codingGetDiagnosticsTool:()=>Zo,codingGetExportsTool:()=>en,codingGetImportsTool:()=>Ho,codingGetOutlineTool:()=>Yo,codingGetSymbolsTool:()=>zo,codingGoToDefinitionTool:()=>Jo,codingMultiFileEditTool:()=>Vo,codingRefactorRenameTool:()=>Xo,codingToolsProject:()=>ja});var ja,Fa=g(()=>{"use strict";c();ka();Pa();_a();Ra();$a();Ea();Ma();Oa();Aa();Na();Ia();La();ka();Pa();_a();Ra();$a();Ea();Ma();Oa();Aa();Na();Ia();La();ja={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:[Bo,zo,Ho,Ko,Jo,Yo,Zo,en,tn,on,Vo,Xo],dependencies:{"@babel/parser":"^7.24.0","@babel/traverse":"^7.24.0","@babel/types":"^7.24.0"}}});var cb,pb=g(()=>{"use strict";c();cb={type:"object",properties:{path:{type:"string",description:"Optional path or directory to check the status for. If omitted, checks the entire repository."}}}});function G(r){let e={baseDir:r||process.cwd(),binary:"git",maxConcurrentProcesses:6};return(0,mb.simpleGit)(e)}var mb,Pe=g(()=>{"use strict";c();mb=require("simple-git")});var Fn,db=g(()=>{"use strict";c();pb();Pe();Fn={name:"git.status",displayName:"Git Status",description:"Get the working tree status, including modified, staged, and untracked files.",category:"version-control",parameters:cb,execute:async r=>{let e=r.path;try{let o=await G().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(`
296
+ `)}catch(t){return`Error getting git status: ${t instanceof Error?t.message:String(t)}`}}}});var ub,fb=g(()=>{"use strict";c();ub={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 qn,gb=g(()=>{"use strict";c();fb();Pe();qn={name:"git.diff",displayName:"Git Diff",description:"Show changes between commits, commit and working tree, etc.",category:"version-control",parameters:ub,execute:async r=>{let e=r.path,t=r.base,o=r.head,n=r.staged,s=r.cloneDir;try{let i=G(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 l=await i.diff(a);return l||"No changes found."}catch(i){return`Error getting git diff: ${i instanceof Error?i.message:String(i)}`}}}});var hb,yb=g(()=>{"use strict";c();hb={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 Wn,bb=g(()=>{"use strict";c();yb();Pe();Wn={name:"git.log",displayName:"Git Log",description:"Show commit logs.",category:"version-control",parameters:hb,execute:async r=>{let e=r.maxCount||10,t=r.path,o=r.cloneDir;try{let n=G(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
297
  Author: ${a.author_name} <${a.author_email}>
288
298
  Date: ${a.date}
289
299
  Message: ${a.message}
290
300
  `).join(`---
291
- `)}catch(n){return`Error getting git log: ${n instanceof Error?n.message:String(n)}`}}}});var jy,Fy=g(()=>{"use strict";c();jy={type:"object",properties:{path:{type:"string",description:"Path to the file or directory to stage. To stage all changes, use '.'."}},required:["path"]}});var Ln,qy=g(()=>{"use strict";c();Fy();Se();Ln={name:"git.add",displayName:"Git Add",description:"Add file contents to the index (stage changes).",category:"version-control",parameters:jy,execute:async r=>{let e=r.path;try{return await G().add(e),`Successfully staged changes for: ${e}`}catch(t){return`Error staging changes: ${t instanceof Error?t.message:String(t)}`}}}});var Wy,Uy=g(()=>{"use strict";c();Wy={type:"object",properties:{message:{type:"string",description:"The commit message."}},required:["message"]}});var jn,Gy=g(()=>{"use strict";c();Uy();Se();jn={name:"git.commit",displayName:"Git Commit",description:"Record changes to the repository.",category:"version-control",parameters:Wy,execute:async r=>{let e=r.message;try{let o=await G().commit(e);return o.commit?`Successfully committed changes.
301
+ `)}catch(n){return`Error getting git log: ${n instanceof Error?n.message:String(n)}`}}}});var wb,Tb=g(()=>{"use strict";c();wb={type:"object",properties:{path:{type:"string",description:"Path to the file or directory to stage. To stage all changes, use '.'."}},required:["path"]}});var Un,xb=g(()=>{"use strict";c();Tb();Pe();Un={name:"git.add",displayName:"Git Add",description:"Add file contents to the index (stage changes).",category:"version-control",parameters:wb,execute:async r=>{let e=r.path;try{return await G().add(e),`Successfully staged changes for: ${e}`}catch(t){return`Error staging changes: ${t instanceof Error?t.message:String(t)}`}}}});var vb,Cb=g(()=>{"use strict";c();vb={type:"object",properties:{message:{type:"string",description:"The commit message."}},required:["message"]}});var Gn,Sb=g(()=>{"use strict";c();Cb();Pe();Gn={name:"git.commit",displayName:"Git Commit",description:"Record changes to the repository.",category:"version-control",parameters:vb,execute:async r=>{let e=r.message;try{let o=await G().commit(e);return o.commit?`Successfully committed changes.
292
302
  Commit: ${o.commit}
293
303
  Branch: ${o.branch}
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 By,zy=g(()=>{"use strict";c();By={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 Fn,Hy=g(()=>{"use strict";c();zy();Se();Fn={name:"git.blame",displayName:"Git Blame",description:"Show what revision and author last modified each line of a file.",category:"version-control",parameters:By,execute:async r=>{let e=r.path,t=r.sha,o=r.cloneDir;try{let n=G(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 Ky,Jy=g(()=>{"use strict";c();Ky={type:"object",properties:{remote:{type:"boolean",description:"List remote branches as well.",default:!1}}}});var qn,Vy=g(()=>{"use strict";c();Jy();Se();qn={name:"git.branch_list",displayName:"Git Branch List",description:"List all branches.",category:"version-control",parameters:Ky,execute:async r=>{let e=r.remote;try{let t=G(),o=e?["-a"]:[],n=await t.branch(o);return`Current Branch: ${n.current}
304
+ 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 kb,Pb=g(()=>{"use strict";c();kb={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 Bn,_b=g(()=>{"use strict";c();Pb();Pe();Bn={name:"git.blame",displayName:"Git Blame",description:"Show what revision and author last modified each line of a file.",category:"version-control",parameters:kb,execute:async r=>{let e=r.path,t=r.sha,o=r.cloneDir;try{let n=G(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 Rb,$b=g(()=>{"use strict";c();Rb={type:"object",properties:{remote:{type:"boolean",description:"List remote branches as well.",default:!1}}}});var zn,Eb=g(()=>{"use strict";c();$b();Pe();zn={name:"git.branch_list",displayName:"Git Branch List",description:"List all branches.",category:"version-control",parameters:Rb,execute:async r=>{let e=r.remote;try{let t=G(),o=e?["-a"]:[],n=await t.branch(o);return`Current Branch: ${n.current}
295
305
 
296
306
  Branches:
297
307
  ${n.all.join(`
298
- `)}`}catch(t){return`Error listing branches: ${t instanceof Error?t.message:String(t)}`}}}});var Qy,Xy=g(()=>{"use strict";c();Qy={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 Wn,Yy=g(()=>{"use strict";c();Xy();Se();Wn={name:"git.branch_create",displayName:"Git Branch Create",description:"Create a new branch.",category:"version-control",parameters:Qy,execute:async r=>{let e=r.name,t=r.checkout,o=r.startPoint;try{let n=G();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 Zy,eb=g(()=>{"use strict";c();Zy={type:"object",properties:{branch:{type:"string",description:"Name of the branch or commit to checkout."}},required:["branch"]}});var Un,tb=g(()=>{"use strict";c();eb();Se();Un={name:"git.checkout",displayName:"Git Checkout",description:"Switch branches or restore working tree files.",category:"version-control",parameters:Zy,execute:async r=>{let e=r.branch;try{return await G().checkout(e),`Successfully checked out: ${e}`}catch(t){return`Error checking out branch: ${t instanceof Error?t.message:String(t)}`}},confirmation:{level:"medium",reason:"This will switch branches, potentially losing uncommitted changes.",showArgs:["branch"]}}});var ob,nb=g(()=>{"use strict";c();ob={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"]}});async function kv(r){for(;Vr.has(r);)await Vr.get(r);let e,t=new Promise(o=>{e=o});return Vr.set(r,t),()=>{Vr.delete(r),e()}}async function rb(r){let e=0,t=await ue.readdir(r,{withFileTypes:!0});for(let o of t){let n=Qr.join(r,o.name);if(o.isDirectory())e+=await rb(n);else if(o.isFile()){let s=await ue.stat(n);e+=s.size}}return e}async function Sv(r,e){let t=e-r;for(;ze>t&&He.size>0;){let o=null,n=null;for(let[s,i]of He)(!o||i.lastAccessedAt<o.lastAccessedAt)&&(o=i,n=s);if(!n||!o)break;try{await ue.rm(o.cloneDir,{recursive:!0,force:!0}),ze=Math.max(0,ze-o.sizeBytes),He.delete(n)}catch{break}}}async function Rv(r,e,t,o,n){let i=`https://x-access-token:${await B(r)}@github.com/${r}.git`,a=r.replace("/","_"),l=Qr.resolve(n,a),p=G(n),m=He.get(r);if(m)try{if(await ue.access(l),m.sha===e)return m.lastAccessedAt=Date.now(),l;await ue.rm(l,{recursive:!0,force:!0}),ze=Math.max(0,ze-m.sizeBytes),He.delete(r)}catch{ze=Math.max(0,ze-m.sizeBytes),He.delete(r)}else try{await ue.access(l),await ue.rm(l,{recursive:!0,force:!0})}catch{}let u=["--no-checkout"];o>0&&u.push("--depth",o.toString()),t&&t!=="none"&&u.push("--filter",t);try{await p.clone(i,a,u);let f=G(l);try{let y=["origin",e];o>0&&y.push("--depth",o.toString()),await f.fetch(y)}catch{}await f.checkout(["--force",e]);let b=await rb(l);return ze+=b,He.set(r,{cloneDir:l,repo:r,sha:e,sizeBytes:b,lastAccessedAt:Date.now()}),l}catch(f){try{await ue.rm(l,{recursive:!0,force:!0})}catch{}throw f}}function _v(r){return(r instanceof Error?r.message:String(r)).replace(/x-access-token:[^@]+@/g,"x-access-token:***@")}var ue,Qr,Cv,Pv,He,Vr,ze,Gn,sb=g(()=>{"use strict";c();nb();Se();Pe();ue=T(require("fs/promises"),1),Qr=T(require("path"),1),Cv=".toolpack/clones",Pv=5e9,He=new Map,Vr=new Map,ze=0;Gn={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:ob,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??Cv,i=parseInt(process.env.SENTINEL_CLONE_MAX_BYTES??"0",10)||Pv;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 ue.mkdir(s,{recursive:!0});let l=await kv(e);try{let p=He.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 Sv(1e8,i);let m=await Rv(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: ${_v(p)}`}finally{l()}}}});var ib={};le(ib,{gitAddTool:()=>Ln,gitBlameTool:()=>Fn,gitBranchCreateTool:()=>Wn,gitBranchListTool:()=>qn,gitCheckoutTool:()=>Un,gitCloneTool:()=>Gn,gitCommitTool:()=>jn,gitDiffTool:()=>An,gitLogTool:()=>In,gitStatusTool:()=>Nn,gitToolsProject:()=>$a});var $a,Ea=g(()=>{"use strict";c();Dy();Ny();Ly();qy();Gy();Hy();Vy();Yy();tb();sb();$a={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:[Nn,An,In,Ln,jn,Fn,qn,Wn,Un,Gn],dependencies:{"simple-git":"^3.27.0"}}});var ab,lb=g(()=>{"use strict";c();ab={type:"object",properties:{oldContent:{type:"string",description:"The original text content."},newContent:{type:"string",description:"The new text content."},fileName:{type:"string",description:"Optional filename to include in the patch header."},contextLines:{type:"number",description:"Number of context lines to include around differences. Default is 4.",default:4}},required:["oldContent","newContent"]}});var cb,Bn,pb=g(()=>{"use strict";c();lb();cb=T(require("diff"),1);k();Bn={name:"diff.create",displayName:"Create Diff",description:"Generate a unified diff from two text contents.",category:"diff",parameters:ab,execute:async r=>{let e=r.oldContent,t=r.newContent,o=r.fileName||"file",n=r.contextLines??4;h(`[diff.create] execute fileName="${o}" contextLines=${n}`);try{return cb.createPatch(o,e,t,"","",{context:n})}catch(s){return`Error creating diff: ${s instanceof Error?s.message:String(s)}`}}}});var mb,db=g(()=>{"use strict";c();mb={type:"object",properties:{path:{type:"string",description:"Path to the file to patch."},patch:{type:"string",description:"Unified diff string to apply."}},required:["path","patch"]}});var ub,Da,zn,fb=g(()=>{"use strict";c();db();ub=T(require("diff"),1),Da=require("fs");k();zn={name:"diff.apply",displayName:"Apply Diff",description:"Apply a unified diff patch to a file.",category:"diff",parameters:mb,execute:async r=>{let e=r.path,t=r.patch;h(`[diff.apply] execute path="${e}"`);try{let o=await Da.promises.readFile(e,"utf8"),n=ub.applyPatch(o,t);return n===!1?"Failed to apply patch. The patch may be malformed or conflicting with the current file content.":(await Da.promises.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 gb,hb=g(()=>{"use strict";c();gb={type:"object",properties:{path:{type:"string",description:"Path to the file to apply the patch against for preview."},patch:{type:"string",description:"Unified diff string to preview."}},required:["path","patch"]}});var yb,bb,Hn,wb=g(()=>{"use strict";c();hb();yb=T(require("diff"),1),bb=require("fs"),Hn={name:"diff.preview",displayName:"Preview Diff",description:"Preview the result of applying a patch to a file without modifying it.",category:"diff",parameters:gb,execute:async r=>{let e=r.path,t=r.patch;try{let o=await bb.promises.readFile(e,"utf8"),n=yb.applyPatch(o,t);return n===!1?"Patch preview failed. The patch would not apply cleanly.":`Preview of ${e} after patch:
308
+ `)}`}catch(t){return`Error listing branches: ${t instanceof Error?t.message:String(t)}`}}}});var Db,Mb=g(()=>{"use strict";c();Db={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 Hn,Ob=g(()=>{"use strict";c();Mb();Pe();Hn={name:"git.branch_create",displayName:"Git Branch Create",description:"Create a new branch.",category:"version-control",parameters:Db,execute:async r=>{let e=r.name,t=r.checkout,o=r.startPoint;try{let n=G();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 Ab,Nb=g(()=>{"use strict";c();Ab={type:"object",properties:{branch:{type:"string",description:"Name of the branch or commit to checkout."}},required:["branch"]}});var Kn,Ib=g(()=>{"use strict";c();Nb();Pe();Kn={name:"git.checkout",displayName:"Git Checkout",description:"Switch branches or restore working tree files.",category:"version-control",parameters:Ab,execute:async r=>{let e=r.branch;try{return await G().checkout(e),`Successfully checked out: ${e}`}catch(t){return`Error checking out branch: ${t instanceof Error?t.message:String(t)}`}},confirmation:{level:"medium",reason:"This will switch branches, potentially losing uncommitted changes.",showArgs:["branch"]}}});var Lb,jb=g(()=>{"use strict";c();Lb={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"]}});async function vC(r){for(;ps.has(r);)await ps.get(r);let e,t=new Promise(o=>{e=o});return ps.set(r,t),()=>{ps.delete(r),e()}}async function Fb(r){let e=0,t=await ue.readdir(r,{withFileTypes:!0});for(let o of t){let n=ms.join(r,o.name);if(o.isDirectory())e+=await Fb(n);else if(o.isFile()){let s=await ue.stat(n);e+=s.size}}return e}async function CC(r,e){let t=e-r;for(;Je>t&&Ve.size>0;){let o=null,n=null;for(let[s,i]of Ve)(!o||i.lastAccessedAt<o.lastAccessedAt)&&(o=i,n=s);if(!n||!o)break;try{await ue.rm(o.cloneDir,{recursive:!0,force:!0}),Je=Math.max(0,Je-o.sizeBytes),Ve.delete(n)}catch{break}}}async function SC(r,e,t,o,n){let i=`https://x-access-token:${await B(r)}@github.com/${r}.git`,a=r.replace("/","_"),l=ms.resolve(n,a),p=G(n),m=Ve.get(r);if(m)try{if(await ue.access(l),m.sha===e)return m.lastAccessedAt=Date.now(),l;await ue.rm(l,{recursive:!0,force:!0}),Je=Math.max(0,Je-m.sizeBytes),Ve.delete(r)}catch{Je=Math.max(0,Je-m.sizeBytes),Ve.delete(r)}else try{await ue.access(l),await ue.rm(l,{recursive:!0,force:!0})}catch{}let d=["--no-checkout"];o>0&&d.push("--depth",o.toString()),t&&t!=="none"&&d.push("--filter",t);try{await p.clone(i,a,d);let f=G(l);try{let y=["origin",e];o>0&&y.push("--depth",o.toString()),await f.fetch(y)}catch{}await f.checkout(["--force",e]);let b=await Fb(l);return Je+=b,Ve.set(r,{cloneDir:l,repo:r,sha:e,sizeBytes:b,lastAccessedAt:Date.now()}),l}catch(f){try{await ue.rm(l,{recursive:!0,force:!0})}catch{}throw f}}function kC(r){return(r instanceof Error?r.message:String(r)).replace(/x-access-token:[^@]+@/g,"x-access-token:***@")}var ue,ms,TC,xC,Ve,ps,Je,Jn,qb=g(()=>{"use strict";c();jb();Pe();Se();ue=T(require("fs/promises"),1),ms=T(require("path"),1),TC=".toolpack/clones",xC=5e9,Ve=new Map,ps=new Map,Je=0;Jn={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:Lb,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??TC,i=parseInt(process.env.SENTINEL_CLONE_MAX_BYTES??"0",10)||xC;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 ue.mkdir(s,{recursive:!0});let l=await vC(e);try{let p=Ve.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 CC(1e8,i);let m=await SC(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: ${kC(p)}`}finally{l()}}}});var Wb={};X(Wb,{gitAddTool:()=>Un,gitBlameTool:()=>Bn,gitBranchCreateTool:()=>Hn,gitBranchListTool:()=>zn,gitCheckoutTool:()=>Kn,gitCloneTool:()=>Jn,gitCommitTool:()=>Gn,gitDiffTool:()=>qn,gitLogTool:()=>Wn,gitStatusTool:()=>Fn,gitToolsProject:()=>qa});var qa,Wa=g(()=>{"use strict";c();db();gb();bb();xb();Sb();_b();Eb();Ob();Ib();qb();qa={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:[Fn,qn,Wn,Un,Gn,Bn,zn,Hn,Kn,Jn],dependencies:{"simple-git":"^3.27.0"}}});var Ub,Gb=g(()=>{"use strict";c();Ub={type:"object",properties:{oldContent:{type:"string",description:"The original text content."},newContent:{type:"string",description:"The new text content."},fileName:{type:"string",description:"Optional filename to include in the patch header."},contextLines:{type:"number",description:"Number of context lines to include around differences. Default is 4.",default:4}},required:["oldContent","newContent"]}});var Bb,Vn,zb=g(()=>{"use strict";c();Gb();Bb=T(require("diff"),1);k();Vn={name:"diff.create",displayName:"Create Diff",description:"Generate a unified diff from two text contents.",category:"diff",parameters:Ub,execute:async r=>{let e=r.oldContent,t=r.newContent,o=r.fileName||"file",n=r.contextLines??4;h(`[diff.create] execute fileName="${o}" contextLines=${n}`);try{return Bb.createPatch(o,e,t,"","",{context:n})}catch(s){return`Error creating diff: ${s instanceof Error?s.message:String(s)}`}}}});var Hb,Kb=g(()=>{"use strict";c();Hb={type:"object",properties:{path:{type:"string",description:"Path to the file to patch."},patch:{type:"string",description:"Unified diff string to apply."}},required:["path","patch"]}});var Jb,Ua,Qn,Vb=g(()=>{"use strict";c();Kb();Jb=T(require("diff"),1),Ua=require("fs");k();Qn={name:"diff.apply",displayName:"Apply Diff",description:"Apply a unified diff patch to a file.",category:"diff",parameters:Hb,execute:async r=>{let e=r.path,t=r.patch;h(`[diff.apply] execute path="${e}"`);try{let o=await Ua.promises.readFile(e,"utf8"),n=Jb.applyPatch(o,t);return n===!1?"Failed to apply patch. The patch may be malformed or conflicting with the current file content.":(await Ua.promises.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 Qb,Xb=g(()=>{"use strict";c();Qb={type:"object",properties:{path:{type:"string",description:"Path to the file to apply the patch against for preview."},patch:{type:"string",description:"Unified diff string to preview."}},required:["path","patch"]}});var Yb,Zb,Xn,ew=g(()=>{"use strict";c();Xb();Yb=T(require("diff"),1),Zb=require("fs"),Xn={name:"diff.preview",displayName:"Preview Diff",description:"Preview the result of applying a patch to a file without modifying it.",category:"diff",parameters:Qb,execute:async r=>{let e=r.path,t=r.patch;try{let o=await Zb.promises.readFile(e,"utf8"),n=Yb.applyPatch(o,t);return n===!1?"Patch preview failed. The patch would not apply cleanly.":`Preview of ${e} after patch:
299
309
 
300
- ${n}`}catch(o){return`Error previewing patch: ${o instanceof Error?o.message:String(o)}`}}}});var Tb={};le(Tb,{diffApplyTool:()=>zn,diffCreateTool:()=>Bn,diffPreviewTool:()=>Hn,diffToolsProject:()=>Ma});var Ma,Oa=g(()=>{"use strict";c();pb();fb();wb();Ma={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:[Bn,zn,Hn],dependencies:{diff:"^7.0.0"}}});var xb,vb=g(()=>{"use strict";c();xb={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,Xr=g(()=>{"use strict";c();Ke=class{connectionString;constructor(e){this.connectionString=e}}});var Na,Aa,Kn,Cb=g(()=>{"use strict";c();Na=T(require("better-sqlite3"),1),Aa=T(require("fs"),1);Xr();Kn=class extends Ke{getDb(){if(!Aa.existsSync(this.connectionString))throw new Error(`Database file not found: ${this.connectionString}`);return new Na.default(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(!Aa.existsSync(e))throw new Error(`Database file not found: ${e}`);let n=new Na.default(e,{readonly:!1});try{let s=n.prepare(t);return s.reader?s.all(o):s.run(o)}finally{n.close()}}}});var Pb,Yr,kb=g(()=>{"use strict";c();Pb=T(require("pg"),1);Xr();Yr=class extends Ke{async getClient(){let e=new Pb.default.Client({connectionString:this.connectionString});return await e.connect(),e}convertSql(e){let t=1;return e.replace(/\?/g,()=>`$${t++}`)}async query(e,t=[]){let o=await this.getClient();try{let 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(`
310
+ ${n}`}catch(o){return`Error previewing patch: ${o instanceof Error?o.message:String(o)}`}}}});var tw={};X(tw,{diffApplyTool:()=>Qn,diffCreateTool:()=>Vn,diffPreviewTool:()=>Xn,diffToolsProject:()=>Ga});var Ga,Ba=g(()=>{"use strict";c();zb();Vb();ew();Ga={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:[Vn,Qn,Xn],dependencies:{diff:"^7.0.0"}}});var ow,nw=g(()=>{"use strict";c();ow={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 Qe,ds=g(()=>{"use strict";c();Qe=class{connectionString;constructor(e){this.connectionString=e}}});var za,Ha,Yn,rw=g(()=>{"use strict";c();za=T(require("better-sqlite3"),1),Ha=T(require("fs"),1);ds();Yn=class extends Qe{getDb(){if(!Ha.existsSync(this.connectionString))throw new Error(`Database file not found: ${this.connectionString}`);return new za.default(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(!Ha.existsSync(e))throw new Error(`Database file not found: ${e}`);let n=new za.default(e,{readonly:!1});try{let s=n.prepare(t);return s.reader?s.all(o):s.run(o)}finally{n.close()}}}});var sw,us,iw=g(()=>{"use strict";c();sw=T(require("pg"),1);ds();us=class extends Qe{async getClient(){let e=new sw.default.Client({connectionString:this.connectionString});return await e.connect(),e}convertSql(e){let t=1;return e.replace(/\?/g,()=>`$${t++}`)}async query(e,t=[]){let o=await this.getClient();try{let 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(`
301
311
  SELECT column_name, data_type, is_nullable, column_default
302
312
  FROM information_schema.columns
303
313
  WHERE table_name = $1
@@ -305,9 +315,14 @@ ${n}`}catch(o){return`Error previewing patch: ${o instanceof Error?o.message:Str
305
315
  SELECT table_name as name, table_type
306
316
  FROM information_schema.tables
307
317
  WHERE table_schema = 'public'
308
- `)}}});var Sb,Zr,Rb=g(()=>{"use strict";c();Sb=T(require("mysql2/promise"),1);Xr();Zr=class extends Ke{async getConnection(){return await Sb.default.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 Y,Je=g(()=>{"use strict";c();Cb();kb();Rb();Y=class{static getAdapter(e){return e.startsWith("postgres://")||e.startsWith("postgresql://")?new Yr(e):e.startsWith("mysql://")?new Zr(e):e.startsWith("sqlite://")?new Kn(e.replace("sqlite://","")):new Kn(e)}}});var Jn,_b=g(()=>{"use strict";c();vb();Je();k();Jn={name:"db.query",displayName:"Database Query",description:"Execute raw SQL queries against an SQLite, PostgreSQL, or MySQL database.",category:"database",parameters:xb,execute:async r=>{let e=r.db,t=r.sql,o=r.params||[];h(`[db.query] execute db="${e}" sql="${t.substring(0,80)}..." params=${o.length}`);try{let s=await Y.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 $b,Eb=g(()=>{"use strict";c();$b={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 Vn,Db=g(()=>{"use strict";c();Eb();Je();Vn={name:"db.schema",displayName:"Database Schema",description:"Get the structural schema of a database or a specific table.",category:"database",parameters:$b,execute:async r=>{let e=r.db,t=r.table;try{let n=await Y.getAdapter(e).getSchema(t);return JSON.stringify(n,null,2)}catch(o){return`Database schema error: ${o instanceof Error?o.message:String(o)}`}}}});var Mb,Ob=g(()=>{"use strict";c();Mb={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"}},required:["db"]}});var Qn,Nb=g(()=>{"use strict";c();Ob();Je();Qn={name:"db.tables",displayName:"Database Tables",description:"List all user tables in the database.",category:"database",parameters:Mb,execute:async r=>{let e=r.db;try{let o=await Y.getAdapter(e).getTables();return JSON.stringify(o,null,2)}catch(t){return`Database tables error: ${t instanceof Error?t.message:String(t)}`}}}});var Ab,Ib=g(()=>{"use strict";c();Ab={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 Xn,Lb=g(()=>{"use strict";c();Ib();Je();Xn={name:"db.insert",displayName:"Database Insert",description:"Insert a new row into an SQLite table safely.",category:"database",parameters:Ab,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 Y.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 jb,Fb=g(()=>{"use strict";c();jb={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 Yn,qb=g(()=>{"use strict";c();Fb();Je();Yn={name:"db.update",displayName:"Database Update",description:"Update existing rows in a database table.",category:"database",parameters:jb,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 Y.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 Wb,Ub=g(()=>{"use strict";c();Wb={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 Zn,Gb=g(()=>{"use strict";c();Ub();Je();Zn={name:"db.delete",displayName:"Database Delete",description:"Delete rows from a database table.",category:"database",parameters:Wb,execute:async r=>{let e=r.db,t=r.table,o=r.where;try{let n=`DELETE FROM ${t} WHERE ${o}`,i=await Y.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 Bb,zb=g(()=>{"use strict";c();Bb={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 er,Hb=g(()=>{"use strict";c();zb();Je();er={name:"db.count",displayName:"Database Count",description:"Count rows in a database table.",category:"database",parameters:Bb,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 Y.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 Kb={};le(Kb,{dbCountTool:()=>er,dbDeleteTool:()=>Zn,dbInsertTool:()=>Xn,dbQueryTool:()=>Jn,dbSchemaTool:()=>Vn,dbTablesTool:()=>Qn,dbToolsProject:()=>Ia,dbUpdateTool:()=>Yn});var Ia,La=g(()=>{"use strict";c();_b();Db();Nb();Lb();qb();Gb();Hb();Ia={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:[Jn,Vn,Qn,Xn,Yn,Zn,er],dependencies:{"better-sqlite3":"^11.3.0"}}});var Jb,Vb=g(()=>{"use strict";c();Jb={type:"object",properties:{siteId:{type:"string",description:'The Netlify Site ID to deploy to (e.g. "api_id" from Netlify UI)'},dir:{type:"string",description:'The local directory path to deploy (e.g. "./dist" or "./public")'},message:{type:"string",description:"Optional deployment message/commit note"}},required:["siteId","dir"]}});var Qb,Ve,es=g(()=>{"use strict";c();Qb=require("netlify"),Ve=class{static getClient(){let e=process.env.NETLIFY_AUTH_TOKEN;if(!e)throw new Error("NETLIFY_AUTH_TOKEN environment variable is required to use Netlify cloud tools.");return new Qb.NetlifyAPI(e)}}});var tr,Xb=g(()=>{"use strict";c();Vb();es();k();tr={name:"cloud.deploy",displayName:"Cloud Deploy",description:"Deploy a static directory to Netlify.",category:"cloud",parameters:Jb,execute:async r=>{let e=r.siteId,t=r.dir,o=r.message;h(`[cloud.deploy] execute siteId="${e}" dir="${t}" message="${o??"none"}"`);try{let s=await Ve.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 Yb,Zb=g(()=>{"use strict";c();Yb={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 or,ew=g(()=>{"use strict";c();Zb();es();or={name:"cloud.status",displayName:"Cloud Status",description:"Check the status of a specific Netlify deployment.",category:"cloud",parameters:Yb,execute:async r=>{let e=r.siteId,t=r.deployId;try{let n=await Ve.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 tw,ow=g(()=>{"use strict";c();tw={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 nr,nw=g(()=>{"use strict";c();ow();es();k();nr={name:"cloud.list",displayName:"Cloud Deployments List",description:"List recent deployments for a Netlify site.",category:"cloud",parameters:tw,execute:async r=>{let e=r.siteId,t=r.limit||5;h(`[cloud.list] execute siteId="${e}" limit=${t}`);try{let n=await Ve.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 rw={};le(rw,{cloudDeployTool:()=>tr,cloudListTool:()=>nr,cloudStatusTool:()=>or,cloudToolsProject:()=>ja});var ja,Fa=g(()=>{"use strict";c();Xb();ew();nw();ja={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:[tr,or,nr],dependencies:{netlify:"^13.1.20"}}});var sw,iw,aw,lw,cw,pw=g(()=>{"use strict";c();sw="slack.chat.postMessage",iw="Post Slack Message",aw="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.",lw="slack",cw={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 be(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 pt=g(()=>{"use strict";c()});function $v(r){return{Authorization:`Bearer ${r}`,"Content-Type":"application/json; charset=utf-8"}}async function we(r,e,t){let o=await fetch(`https://slack.com/api/${r}`,{method:"POST",headers:$v(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 mt=g(()=>{"use strict";c()});async function Ev(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=be(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 we("chat.postMessage",s,i),l=a.ts??"";return`Message posted. channel=${a.channel??e} ts=${l}`}var Xo,qa=g(()=>{"use strict";c();pw();pt();mt();Xo={name:sw,displayName:iw,description:aw,parameters:cw,category:lw,execute:Ev}});var mw,dw,uw,fw,gw,hw=g(()=>{"use strict";c();mw="slack.chat.postEphemeral",dw="Post Ephemeral Slack Message",uw="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.",fw="slack",gw={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 Dv(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=be(r.token),i={channel:e,user:t,text:o};return n&&(i.thread_ts=n),await we("chat.postEphemeral",s,i),`Ephemeral message sent to user=${t} in channel=${e}.`}var Yo,Wa=g(()=>{"use strict";c();hw();pt();mt();Yo={name:mw,displayName:dw,description:uw,parameters:gw,category:fw,execute:Dv}});var yw,bw,ww,Tw,xw,vw=g(()=>{"use strict";c();yw="slack.reactions.add",bw="Add Slack Reaction",ww="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.",Tw="slack",xw={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 Mv(r){let e=String(r.channel),t=String(r.timestamp),o=String(r.name),n=be(r.token);try{await we("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 Zo,Ua=g(()=>{"use strict";c();vw();pt();mt();Zo={name:yw,displayName:bw,description:ww,parameters:xw,category:Tw,execute:Mv}});var Cw,Pw,kw,Sw,Rw,_w=g(()=>{"use strict";c();Cw="slack.conversations.history",Pw="Get Slack Channel History",kw="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.",Sw="slack",Rw={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 Ov(r){let e=String(r.channel),t=typeof r.limit=="number"?Math.min(r.limit,100):10,o=be(r.token),n={channel:e,limit:t};r.oldest&&(n.oldest=String(r.oldest)),r.latest&&(n.latest=String(r.latest));let i=(await we("conversations.history",o,n)).messages??[];return i.length===0?"No messages found.":[...i].reverse().map(l=>{let p=l.user?`user:${l.user}`:l.bot_id?`bot:${l.bot_id}`:"unknown",m=l.reply_count?` [thread: ${l.reply_count} replies]`:"",u=(l.text??"").replace(/\n/g," ").slice(0,200);return`[${l.ts}] ${p}${m}: ${u}`}).join(`
309
- `)}var en,Ga=g(()=>{"use strict";c();_w();pt();mt();en={name:Cw,displayName:Pw,description:kw,parameters:Rw,category:Sw,execute:Ov}});var $w,Ew,Dw,Mw,Ow,Nw=g(()=>{"use strict";c();$w="slack.conversations.replies",Ew="Get Slack Thread Replies",Dw="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.",Mw="slack",Ow={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 Nv(r){let e=String(r.channel),t=String(r.ts),o=typeof r.limit=="number"?Math.min(r.limit,100):20,n=be(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 we("conversations.replies",n,s)).messages??[];return a.length===0?"No replies found.":a.map((p,m)=>{let u=p.user?`user:${p.user}`:p.bot_id?`bot:${p.bot_id}`:"unknown",f=m===0?" [parent]":"",b=(p.text??"").replace(/\n/g," ").slice(0,200);return`[${p.ts}] ${u}${f}: ${b}`}).join(`
310
- `)}var tn,Ba=g(()=>{"use strict";c();Nw();pt();mt();tn={name:$w,displayName:Ew,description:Dw,parameters:Ow,category:Mw,execute:Nv}});var Aw,Iw,Lw,jw,Fw,qw=g(()=>{"use strict";c();Aw="slack.auth.test",Iw="Slack Auth Test",Lw="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.",jw="slack",Fw={type:"object",properties:{token:{type:"string",description:"Slack bot token. Defaults to TOOLPACK_SLACK_BOT_TOKEN env var."}},required:[]}});async function Av(r){let e=be(r.token),t=await we("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 on,za=g(()=>{"use strict";c();qw();pt();mt();on={name:Aw,displayName:Iw,description:Lw,parameters:Fw,category:jw,execute:Av}});var Ww={};le(Ww,{slackAuthTestTool:()=>on,slackChatPostEphemeralTool:()=>Yo,slackChatPostMessageTool:()=>Xo,slackConversationsHistoryTool:()=>en,slackConversationsRepliesTool:()=>tn,slackReactionsAddTool:()=>Zo,slackToolsProject:()=>Ha});var Ha,Ka=g(()=>{"use strict";c();qa();Wa();Ua();Ga();Ba();za();qa();Wa();Ua();Ga();Ba();za();Ha={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:[Xo,Yo,Zo,en,tn,on]}});var Zv={};le(Zv,{AGENT_MODE:()=>el,AGENT_PLANNING_PROMPT:()=>fs,AGENT_WORKFLOW:()=>Xa,AIClient:()=>wn,AnthropicAdapter:()=>xn,AuthenticationError:()=>he,BM25SearchEngine:()=>wt,BUILT_IN_MODES:()=>ir,CHAT_MODE:()=>tl,CHAT_WORKFLOW:()=>Za,CODING_MODE:()=>ol,CODING_PLANNING_PROMPT:()=>Qw,CODING_WORKFLOW:()=>Ya,CONFIG_DIR_NAME:()=>il,CONFIG_FILE_NAME:()=>al,ConnectionError:()=>Ie,ContextWindowConfigError:()=>Ps,ContextWindowExceededError:()=>dr,ContextWindowStateManager:()=>hr,ConversationNotFoundError:()=>ks,DEFAULT_MODE_NAME:()=>ut,DEFAULT_TOOLS_CONFIG:()=>te,DEFAULT_TOOL_SEARCH_CONFIG:()=>wl,DEFAULT_WORKFLOW:()=>Bv,DEFAULT_WORKFLOW_CONFIG:()=>gs,GeminiAdapter:()=>Cn,InMemoryConversationStore:()=>ys,InsufficientContextError:()=>ur,InvalidRequestError:()=>I,McpClient:()=>rn,McpConnectionError:()=>Ee,McpTimeoutError:()=>rr,McpToolManager:()=>sr,ModeRegistry:()=>sn,OllamaAdapter:()=>qe,OllamaProvider:()=>St,OpenAIAdapter:()=>rt,OpenRouterAdapter:()=>Rn,PageError:()=>vs,Planner:()=>an,ProviderAdapter:()=>X,ProviderError:()=>j,RateLimitError:()=>ce,SDKError:()=>N,SQLiteConversationStore:()=>bs,SummarizationError:()=>fr,TOOLPACK_DIR_NAME:()=>sl,TOOL_SEARCH_NAME:()=>Tt,TimeoutError:()=>Cs,ToolDiscoveryCache:()=>Ze,ToolRegistry:()=>nn,ToolRouter:()=>vt,Toolpack:()=>rl,VertexAIAdapter:()=>vn,WorkflowExecutor:()=>ar,addBypassRule:()=>jl,buildSummarizedHistory:()=>_T,cloudDeployTool:()=>tr,cloudListTool:()=>nr,cloudStatusTool:()=>or,cloudToolsProject:()=>ja,codingExtractFunctionTool:()=>Vo,codingFindReferencesTool:()=>Wo,codingFindSymbolTool:()=>jo,codingGetCallHierarchyTool:()=>Qo,codingGetDiagnosticsTool:()=>Ko,codingGetExportsTool:()=>Jo,codingGetImportsTool:()=>qo,codingGetOutlineTool:()=>Ho,codingGetSymbolsTool:()=>Fo,codingGoToDefinitionTool:()=>Uo,codingMultiFileEditTool:()=>Go,codingRefactorRenameTool:()=>zo,codingToolsProject:()=>Ra,countTokens:()=>Rs,createContextWindowStateManager:()=>As,createMcpToolProject:()=>ds,createMode:()=>Xw,createSkillInterceptor:()=>iT,createSkillTools:()=>Vw,createSummarizationReport:()=>$T,createSummarySystemMessage:()=>gr,createToolProject:()=>Uw,dbCountTool:()=>er,dbDeleteTool:()=>Zn,dbInsertTool:()=>Xn,dbQueryTool:()=>Jn,dbSchemaTool:()=>Vn,dbTablesTool:()=>Qn,dbToolsProject:()=>Ia,dbUpdateTool:()=>Yn,diffApplyTool:()=>zn,diffCreateTool:()=>Bn,diffPreviewTool:()=>Hn,diffToolsProject:()=>Ma,disconnectMcpToolProject:()=>us,ensureGlobalConfigDir:()=>pl,ensureLocalConfigDir:()=>Kv,estimateSummaryTokens:()=>bl,estimateTokenCount:()=>Oe,execKillTool:()=>oo,execListProcessesTool:()=>no,execReadOutputTool:()=>to,execRunBackgroundTool:()=>eo,execRunShellTool:()=>Zt,execRunTool:()=>Yt,execToolsProject:()=>xi,extractConversationKeypoints:()=>RT,fetchUrlAsBase64:()=>Us,fsAppendFileTool:()=>Mt,fsBatchReadTool:()=>Qt,fsBatchWriteTool:()=>Xt,fsCopyTool:()=>Wt,fsCreateDirTool:()=>Ft,fsDeleteDirTool:()=>Vt,fsDeleteFileTool:()=>Nt,fsExistsTool:()=>At,fsGlobTool:()=>Jt,fsListDirTool:()=>Lt,fsMoveTool:()=>qt,fsReadFileRangeTool:()=>Gt,fsReadFileTool:()=>_t,fsReplaceInFileTool:()=>zt,fsSearchTool:()=>Bt,fsStatTool:()=>It,fsToolsProject:()=>ui,fsTreeTool:()=>Kt,fsWriteFileTool:()=>Et,generateSummarizationPrompt:()=>yl,generateToolCategoriesPrompt:()=>yr,getContextWindowPercentage:()=>CT,getDefaultSlmModel:()=>ql,getGlobalConfigDir:()=>ll,getGlobalConfigPath:()=>cr,getGlobalToolpackDir:()=>oT,getLocalConfigDir:()=>cl,getLocalConfigPath:()=>pr,getLocalToolpackDir:()=>nT,getMessageStats:()=>ST,getMimeType:()=>js,getOllamaBaseUrl:()=>Sn,getOllamaProviderEntries:()=>Ll,getRegisteredSlmModels:()=>Ul,getRuntimeConfigStatus:()=>Vv,getSafeOutputReserve:()=>_s,getToolSearchSchema:()=>xt,getToolpackConfig:()=>xr,getUserHomeDir:()=>tT,gitAddTool:()=>Ln,gitBlameTool:()=>Fn,gitBranchCreateTool:()=>Wn,gitBranchListTool:()=>qn,gitCheckoutTool:()=>Un,gitCloneTool:()=>Gn,gitCommitTool:()=>jn,gitDiffTool:()=>An,gitLogTool:()=>In,gitStatusTool:()=>Nn,gitToolsProject:()=>$a,githubContentsGetTextTool:()=>yo,githubGraphqlExecuteTool:()=>ho,githubIssuesCommentsCreateTool:()=>Po,githubPrDiffGetTool:()=>xo,githubPrFilesListTool:()=>vo,githubPrReviewCommentsReplyTool:()=>To,githubPrReviewThreadsListTool:()=>bo,githubPrReviewThreadsResolveTool:()=>wo,githubPrReviewsSubmitTool:()=>Co,githubToolsProject:()=>Ji,groupMessagesByRole:()=>kT,handleContextWindowError:()=>gT,httpDeleteTool:()=>uo,httpDownloadTool:()=>go,httpGetTool:()=>co,httpPostTool:()=>po,httpPutTool:()=>mo,httpToolsProject:()=>Li,initializeGlobalConfigIfFirstRun:()=>Qv,isContextWindowError:()=>fT,isDataUri:()=>Fs,isRegisteredSlm:()=>Wl,isToolSearchTool:()=>fn,k8sApplyManifestTool:()=>rs,k8sDeleteResourceTool:()=>ss,k8sDescribeTool:()=>os,k8sGetConfigMapTool:()=>ls,k8sGetLogsTool:()=>ns,k8sGetNamespacesTool:()=>ps,k8sListDeploymentsTool:()=>as,k8sListPodsTool:()=>ts,k8sListServicesTool:()=>is,k8sSwitchContextTool:()=>cs,k8sToolsProject:()=>zw,k8sWaitForDeploymentTool:()=>ms,loadFullConfig:()=>Dn,loadRuntimeConfig:()=>Jv,loadToolsConfig:()=>So,mergeSummarizationResults:()=>ET,normalizeImagePart:()=>Ml,ollamaRequest:()=>Ce,ollamaStream:()=>Cr,parseDataUri:()=>qs,parseSummarizationResponse:()=>Ns,prepareSummarizationRequest:()=>Os,pruneMessages:()=>Es,readFileAsBase64:()=>Ws,reloadToolpackConfig:()=>vr,removeBypassRule:()=>Fl,saveToolsConfig:()=>Mf,slackAuthTestTool:()=>on,slackChatPostEphemeralTool:()=>Yo,slackChatPostMessageTool:()=>Xo,slackConversationsHistoryTool:()=>en,slackConversationsRepliesTool:()=>tn,slackReactionsAddTool:()=>Zo,slackToolsProject:()=>Ha,systemCwdTool:()=>ao,systemDiskUsageTool:()=>lo,systemEnvTool:()=>so,systemInfoTool:()=>ro,systemSetEnvTool:()=>io,systemToolsProject:()=>Ei,toDataUri:()=>Dl,toolSearchDefinition:()=>et,truncateMessage:()=>PT,validateSummarizationResult:()=>Ms,webExtractLinksTool:()=>$o,webFeedTool:()=>Oo,webFetchTool:()=>ko,webMapTool:()=>Eo,webMetadataTool:()=>Do,webScrapeTool:()=>_o,webScreenshotTool:()=>No,webSearchTool:()=>Ro,webSitemapTool:()=>Mo,webToolsProject:()=>la,wouldExceedContextWindow:()=>vT});module.exports=uT(Zv);c();pe();c();var _l=require("events");pe();c();pe();async function gl(r,e={}){let{maxRetries:t=3,backoffMs:o=[1e4,3e4,6e4],isRetryable:n=i=>i instanceof ce,onRetry:s}=e;for(let i=0;i<=t;i++)try{return await r()}catch(a){if(n(a)&&i<t){let l=a?.retryAfter!=null?a.retryAfter*1e3:o[i]??o[o.length-1]??6e4;s?.(i+1,l,a),await new Promise(p=>setTimeout(p,l));continue}throw a}throw new ce("Rate limit retries exhausted")}c();pe();var dn=class extends N{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`
318
+ `)}}});var aw,fs,lw=g(()=>{"use strict";c();aw=T(require("mysql2/promise"),1);ds();fs=class extends Qe{async getConnection(){return await aw.default.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 Z,Xe=g(()=>{"use strict";c();rw();iw();lw();Z=class{static getAdapter(e){return e.startsWith("postgres://")||e.startsWith("postgresql://")?new us(e):e.startsWith("mysql://")?new fs(e):e.startsWith("sqlite://")?new Yn(e.replace("sqlite://","")):new Yn(e)}}});var Zn,cw=g(()=>{"use strict";c();nw();Xe();k();Zn={name:"db.query",displayName:"Database Query",description:"Execute raw SQL queries against an SQLite, PostgreSQL, or MySQL database.",category:"database",parameters:ow,execute:async r=>{let e=r.db,t=r.sql,o=r.params||[];h(`[db.query] execute db="${e}" sql="${t.substring(0,80)}..." params=${o.length}`);try{let s=await Z.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 pw,mw=g(()=>{"use strict";c();pw={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 er,dw=g(()=>{"use strict";c();mw();Xe();er={name:"db.schema",displayName:"Database Schema",description:"Get the structural schema of a database or a specific table.",category:"database",parameters:pw,execute:async r=>{let e=r.db,t=r.table;try{let n=await Z.getAdapter(e).getSchema(t);return JSON.stringify(n,null,2)}catch(o){return`Database schema error: ${o instanceof Error?o.message:String(o)}`}}}});var uw,fw=g(()=>{"use strict";c();uw={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"}},required:["db"]}});var tr,gw=g(()=>{"use strict";c();fw();Xe();tr={name:"db.tables",displayName:"Database Tables",description:"List all user tables in the database.",category:"database",parameters:uw,execute:async r=>{let e=r.db;try{let o=await Z.getAdapter(e).getTables();return JSON.stringify(o,null,2)}catch(t){return`Database tables error: ${t instanceof Error?t.message:String(t)}`}}}});var hw,yw=g(()=>{"use strict";c();hw={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 or,bw=g(()=>{"use strict";c();yw();Xe();or={name:"db.insert",displayName:"Database Insert",description:"Insert a new row into an SQLite table safely.",category:"database",parameters:hw,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 Z.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 ww,Tw=g(()=>{"use strict";c();ww={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 nr,xw=g(()=>{"use strict";c();Tw();Xe();nr={name:"db.update",displayName:"Database Update",description:"Update existing rows in a database table.",category:"database",parameters:ww,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 Z.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 vw,Cw=g(()=>{"use strict";c();vw={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 rr,Sw=g(()=>{"use strict";c();Cw();Xe();rr={name:"db.delete",displayName:"Database Delete",description:"Delete rows from a database table.",category:"database",parameters:vw,execute:async r=>{let e=r.db,t=r.table,o=r.where;try{let n=`DELETE FROM ${t} WHERE ${o}`,i=await Z.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 kw,Pw=g(()=>{"use strict";c();kw={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 sr,_w=g(()=>{"use strict";c();Pw();Xe();sr={name:"db.count",displayName:"Database Count",description:"Count rows in a database table.",category:"database",parameters:kw,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 Z.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 Rw={};X(Rw,{dbCountTool:()=>sr,dbDeleteTool:()=>rr,dbInsertTool:()=>or,dbQueryTool:()=>Zn,dbSchemaTool:()=>er,dbTablesTool:()=>tr,dbToolsProject:()=>Ka,dbUpdateTool:()=>nr});var Ka,Ja=g(()=>{"use strict";c();cw();dw();gw();bw();xw();Sw();_w();Ka={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:[Zn,er,tr,or,nr,rr,sr],dependencies:{"better-sqlite3":"^11.3.0"}}});var $w,Ew=g(()=>{"use strict";c();$w={type:"object",properties:{siteId:{type:"string",description:'The Netlify Site ID to deploy to (e.g. "api_id" from Netlify UI)'},dir:{type:"string",description:'The local directory path to deploy (e.g. "./dist" or "./public")'},message:{type:"string",description:"Optional deployment message/commit note"}},required:["siteId","dir"]}});var Dw,Ye,gs=g(()=>{"use strict";c();Dw=require("netlify"),Ye=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 Dw.NetlifyAPI(e)}}});var ir,Mw=g(()=>{"use strict";c();Ew();gs();k();ir={name:"cloud.deploy",displayName:"Cloud Deploy",description:"Deploy a static directory to Netlify.",category:"cloud",parameters:$w,execute:async r=>{let e=r.siteId,t=r.dir,o=r.message;h(`[cloud.deploy] execute siteId="${e}" dir="${t}" message="${o??"none"}"`);try{let s=await Ye.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 Ow,Aw=g(()=>{"use strict";c();Ow={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 ar,Nw=g(()=>{"use strict";c();Aw();gs();ar={name:"cloud.status",displayName:"Cloud Status",description:"Check the status of a specific Netlify deployment.",category:"cloud",parameters:Ow,execute:async r=>{let e=r.siteId,t=r.deployId;try{let n=await Ye.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 Iw,Lw=g(()=>{"use strict";c();Iw={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 lr,jw=g(()=>{"use strict";c();Lw();gs();k();lr={name:"cloud.list",displayName:"Cloud Deployments List",description:"List recent deployments for a Netlify site.",category:"cloud",parameters:Iw,execute:async r=>{let e=r.siteId,t=r.limit||5;h(`[cloud.list] execute siteId="${e}" limit=${t}`);try{let n=await Ye.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 Fw={};X(Fw,{cloudDeployTool:()=>ir,cloudListTool:()=>lr,cloudStatusTool:()=>ar,cloudToolsProject:()=>Va});var Va,Qa=g(()=>{"use strict";c();Mw();Nw();jw();Va={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:[ir,ar,lr],dependencies:{netlify:"^13.1.20"}}});var qw,Ww,Uw,Gw,Bw,zw=g(()=>{"use strict";c();qw="slack.chat.postMessage",Ww="Post Slack Message",Uw="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.",Gw="slack",Bw={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 be(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 ft=g(()=>{"use strict";c()});function PC(r){return{Authorization:`Bearer ${r}`,"Content-Type":"application/json; charset=utf-8"}}async function we(r,e,t){let o=await fetch(`https://slack.com/api/${r}`,{method:"POST",headers:PC(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 gt=g(()=>{"use strict";c()});async function _C(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=be(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 we("chat.postMessage",s,i),l=a.ts??"";return`Message posted. channel=${a.channel??e} ts=${l}`}var nn,Xa=g(()=>{"use strict";c();zw();ft();gt();nn={name:qw,displayName:Ww,description:Uw,parameters:Bw,category:Gw,execute:_C}});var Hw,Kw,Jw,Vw,Qw,Xw=g(()=>{"use strict";c();Hw="slack.chat.postEphemeral",Kw="Post Ephemeral Slack Message",Jw="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.",Vw="slack",Qw={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 RC(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=be(r.token),i={channel:e,user:t,text:o};return n&&(i.thread_ts=n),await we("chat.postEphemeral",s,i),`Ephemeral message sent to user=${t} in channel=${e}.`}var rn,Ya=g(()=>{"use strict";c();Xw();ft();gt();rn={name:Hw,displayName:Kw,description:Jw,parameters:Qw,category:Vw,execute:RC}});var Yw,Zw,eT,tT,oT,nT=g(()=>{"use strict";c();Yw="slack.reactions.add",Zw="Add Slack Reaction",eT="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.",tT="slack",oT={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 $C(r){let e=String(r.channel),t=String(r.timestamp),o=String(r.name),n=be(r.token);try{await we("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 sn,Za=g(()=>{"use strict";c();nT();ft();gt();sn={name:Yw,displayName:Zw,description:eT,parameters:oT,category:tT,execute:$C}});var rT,sT,iT,aT,lT,cT=g(()=>{"use strict";c();rT="slack.conversations.history",sT="Get Slack Channel History",iT="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.",aT="slack",lT={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 EC(r){let e=String(r.channel),t=typeof r.limit=="number"?Math.min(r.limit,100):10,o=be(r.token),n={channel:e,limit:t};r.oldest&&(n.oldest=String(r.oldest)),r.latest&&(n.latest=String(r.latest));let i=(await we("conversations.history",o,n)).messages??[];return i.length===0?"No messages found.":[...i].reverse().map(l=>{let p=l.user?`user:${l.user}`:l.bot_id?`bot:${l.bot_id}`:"unknown",m=l.reply_count?` [thread: ${l.reply_count} replies]`:"",d=(l.text??"").replace(/\n/g," ").slice(0,200);return`[${l.ts}] ${p}${m}: ${d}`}).join(`
319
+ `)}var an,el=g(()=>{"use strict";c();cT();ft();gt();an={name:rT,displayName:sT,description:iT,parameters:lT,category:aT,execute:EC}});var pT,mT,dT,uT,fT,gT=g(()=>{"use strict";c();pT="slack.conversations.replies",mT="Get Slack Thread Replies",dT="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.",uT="slack",fT={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 DC(r){let e=String(r.channel),t=String(r.ts),o=typeof r.limit=="number"?Math.min(r.limit,100):20,n=be(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 we("conversations.replies",n,s)).messages??[];return a.length===0?"No replies found.":a.map((p,m)=>{let d=p.user?`user:${p.user}`:p.bot_id?`bot:${p.bot_id}`:"unknown",f=m===0?" [parent]":"",b=(p.text??"").replace(/\n/g," ").slice(0,200);return`[${p.ts}] ${d}${f}: ${b}`}).join(`
320
+ `)}var ln,tl=g(()=>{"use strict";c();gT();ft();gt();ln={name:pT,displayName:mT,description:dT,parameters:fT,category:uT,execute:DC}});var hT,yT,bT,wT,TT,xT=g(()=>{"use strict";c();hT="slack.auth.test",yT="Slack Auth Test",bT="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.",wT="slack",TT={type:"object",properties:{token:{type:"string",description:"Slack bot token. Defaults to TOOLPACK_SLACK_BOT_TOKEN env var."}},required:[]}});async function MC(r){let e=be(r.token),t=await we("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 cn,ol=g(()=>{"use strict";c();xT();ft();gt();cn={name:hT,displayName:yT,description:bT,parameters:TT,category:wT,execute:MC}});var vT={};X(vT,{slackAuthTestTool:()=>cn,slackChatPostEphemeralTool:()=>rn,slackChatPostMessageTool:()=>nn,slackConversationsHistoryTool:()=>an,slackConversationsRepliesTool:()=>ln,slackReactionsAddTool:()=>sn,slackToolsProject:()=>nl});var nl,rl=g(()=>{"use strict";c();Xa();Ya();Za();el();tl();ol();Xa();Ya();Za();el();tl();ol();nl={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:[nn,rn,sn,an,ln,cn]}});function N(r,e){if(r.includes("\0")||r.includes(`
321
+ `)||r.includes("\r"))throw new Error(`Invalid ${e}: contains disallowed characters.`);return r}function OC(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()}`:""}
322
+ STDOUT:
323
+ ${e}
324
+ STDERR:
325
+ ${t}`}function ge(r,e,t=3e4){r.forEach((o,n)=>N(o,`kubectl argument #${n}`)),h(`[k8s-tools] execute: kubectl ${r.join(" ")}`);try{return(0,CT.execFileSync)("kubectl",r,{input:e,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],timeout:t})||"(kubectl completed with no output)"}catch(o){return OC(o)}}function AC(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}}function ST(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 CT,_e,cr,pr,mr,dr,ur,fr,gr,hr,yr,br,wr,kT=g(()=>{"use strict";c();CT=require("child_process");k();_e="kubernetes";cr={name:"k8s.list_pods",displayName:"Kubernetes List Pods",description:"List pods in the current or a specific Kubernetes namespace.",category:_e,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=ST(r.labelSelector)??r.labels;return o&&e.push("-l",N(o,"labels")),ge(e)}},pr={name:"k8s.describe",displayName:"Kubernetes Describe Resource",description:"Describe a Kubernetes resource or resource instance.",category:_e,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")),ge(t)}},mr={name:"k8s.get_logs",displayName:"Kubernetes Get Pod Logs",description:"Fetch logs from a Kubernetes pod, optionally from a specific container.",category:_e,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")),ge(e)}},dr={name:"k8s.apply_manifest",displayName:"Kubernetes Apply Manifest",description:"Apply a Kubernetes manifest from a file path or inline YAML content.",category:_e,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")),ge(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("-"),ge(o,t)}},ur={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:_e,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")),ge(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"),ge(n)}},fr={name:"k8s.list_services",displayName:"Kubernetes List Services",description:"List services in the current or a specific Kubernetes namespace.",category:_e,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")),ge(e)}},gr={name:"k8s.list_deployments",displayName:"Kubernetes List Deployments",description:"List deployments in the current or a specific Kubernetes namespace.",category:_e,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=ST(r.labelSelector)??r.labels;return o&&e.push("-l",N(o,"labels")),ge(e)}},hr={name:"k8s.get_config_map",displayName:"Kubernetes Get ConfigMap",description:"Retrieve a ConfigMap from a Kubernetes namespace.",category:_e,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")),ge(e)}},yr={name:"k8s.switch_context",displayName:"Kubernetes Switch Context",description:"Switch the active kubectl context to a different Kubernetes cluster or namespace configuration.",category:_e,parameters:{type:"object",properties:{context:{type:"string",description:"The kubeconfig context to switch to."}},required:["context"]},execute:async r=>ge(["config","use-context",N(r.context,"context")])},br={name:"k8s.get_namespaces",displayName:"Kubernetes Get Namespaces",description:"List namespaces in the current Kubernetes context.",category:_e,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=>ge(["get","namespaces","-o",r.output||"wide"])},wr={name:"k8s.wait_for_deployment",displayName:"Kubernetes Wait For Deployment",description:"Wait for a Kubernetes deployment to complete its rollout.",category:_e,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")),ge(t,void 0,AC(e))}}});var PT={};X(PT,{k8sApplyManifestTool:()=>dr,k8sDeleteResourceTool:()=>ur,k8sDescribeTool:()=>pr,k8sGetConfigMapTool:()=>hr,k8sGetLogsTool:()=>mr,k8sGetNamespacesTool:()=>br,k8sListDeploymentsTool:()=>gr,k8sListPodsTool:()=>cr,k8sListServicesTool:()=>fr,k8sSwitchContextTool:()=>yr,k8sToolsProject:()=>sl,k8sWaitForDeploymentTool:()=>wr});var sl,il=g(()=>{"use strict";c();kT();sl={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:[cr,pr,mr,dr,ur,fr,gr,hr,yr,br,wr]}});function NT(r){switch(r.mode){case"static":return new hl(r.tokens);case"jwt":return new yl(r);case"custom":return{verifyAccessToken:r.verifyAccessToken}}}async function IT(r,e,t,o){let n=r.headers.authorization,s=typeof n=="string"&&n.startsWith("Bearer ")?n.slice(7):null;if(!s)return e.writeHead(401,{"WWW-Authenticate":"Bearer"}).end(),!1;let i;try{i=await o.verifyAccessToken(s)}catch{return e.writeHead(401,{"WWW-Authenticate":"Bearer"}).end(),!1}let a="requiredScopes"in t?t.requiredScopes:void 0;if(a?.length){let l=new Set(i.scopes),p=a.filter(m=>!l.has(m));if(p.length>0)return e.writeHead(403).end(`Missing required scopes: ${p.join(", ")}`),!1}return r.auth=i,!0}var Ts,hl,yl,LT=g(()=>{"use strict";c();Ts=require("jose");hl=class{tokenSet;constructor(e){if(e.length===0)throw new Error('McpAuthConfig static mode: tokens array must not be empty. Generate a token with: crypto.randomBytes(32).toString("hex")');this.tokenSet=new Set(e)}async verifyAccessToken(e){if(!this.tokenSet.has(e))throw new Error("Invalid bearer token.");return{token:e,clientId:"static-client",scopes:[]}}},yl=class{JWKS;audience;issuer;constructor(e){this.JWKS=(0,Ts.createRemoteJWKSet)(new URL(e.jwksUrl)),this.audience=e.audience,this.issuer=e.issuer}async verifyAccessToken(e){let{payload:t}=await(0,Ts.jwtVerify)(e,this.JWKS,{audience:this.audience,issuer:this.issuer}),o=t.scope??t.scp,n=Array.isArray(o)?o.filter(i=>typeof i=="string"):typeof o=="string"?o.split(" ").filter(Boolean):[],s=typeof t.client_id=="string"?t.client_id:typeof t.sub=="string"?t.sub:"unknown";return{token:e,clientId:s,scopes:n,expiresAt:t.exp}}}});var zT={};X(zT,{startMcpServer:()=>GC});async function GC(r,e,t){let o=new UT.Server({name:e.serverName??"Toolpack SDK",version:e.serverVersion??"2.0.0"},{capabilities:{tools:{}}});if(o.setRequestHandler(xs.ListToolsRequestSchema,async()=>{if(e.searchMode){let i=HC(r,e),a=Fe(),l=i.map(p=>{let m=FT(p);return{name:p.name,description:p.description??"",inputSchema:p.parameters??{type:"object",properties:{}},...m!==void 0&&{annotations:m}}});return{tools:[{name:a.name,description:a.description??"",inputSchema:a.parameters,annotations:{readOnlyHint:!0}},...l,...jT(e)]}}return{tools:[...bl(r,e.expose).map(i=>{let a=FT(i);return{name:i.name,description:i.description??"",inputSchema:i.parameters??{type:"object",properties:{}},...a!==void 0&&{annotations:a}}}),...jT(e)]}}),o.setRequestHandler(xs.CallToolRequestSchema,async n=>{let{name:s,arguments:i}=n.params;if(e.searchMode&&rt(s)){if(!t)return Ie("tool.search is not available: searchFn was not provided to startMcpServer.",!0);try{let l=t(i??{});return Ie(l)}catch(l){let p=l instanceof Error?l.message:String(l);return Ie(`tool.search error: ${p}`,!0)}}if(s.startsWith("agent.")){let l=s.slice(6),p=(e.agents??[]).find(m=>m.name===l);if(!p)return Ie(`Agent not found: ${l}`,!0);try{let m=await p.invoke(i??{});return Ie(m)}catch(m){let d=m instanceof Error?m.message:String(m);return Ie(`Agent error (${l}): ${d}`,!0)}}let a=BC(r,s,e.expose);if(!a)return Ie(`Tool not found: ${s}`,!0);try{let l={workspaceRoot:process.cwd(),config:r.getConfig().additionalConfigurations??{},log:m=>P(`[MCP Tool] ${m}`)},p=await a.execute(i??{},l);return Ie(p)}catch(l){let p=l instanceof Error?l.message:String(l);return Ie(`Error executing ${s}: ${p}`,!0)}}),e.transport==="stdio"){let n=new GT.StdioServerTransport;return await o.connect(n),{get toolCount(){return bl(r,e.expose).length},port:0,stop:async()=>{await o.close()}}}if(e.transport==="http"){let n=e.port??3e3;e.auth||P("[MCP Server] Warning: HTTP transport started without authentication. Safe for localhost only. Set `auth` in startMcpServer() before exposing this server to a network.");let s=new BT.StreamableHTTPServerTransport({sessionIdGenerator:()=>(0,WT.randomUUID)()}),i=e.auth?NT(e.auth):null,a=(0,qT.createServer)(async(p,m)=>{if(e.auth?.mode==="jwt"&&e.serverUrl&&p.url==="/.well-known/oauth-protected-resource"){let d={resource:e.serverUrl};e.auth.issuer&&(d.authorization_servers=[e.auth.issuer]),m.writeHead(200,{"Content-Type":"application/json"}).end(JSON.stringify(d));return}i&&!await IT(p,m,e.auth,i).catch(f=>(P(`[MCP Server] Auth error: ${f instanceof Error?f.message:String(f)}`),m.headersSent||m.writeHead(500).end("Internal Server Error"),!1))||s.handleRequest(p,m).catch(d=>{P(`[MCP Server] HTTP request handler error: ${d instanceof Error?d.message:String(d)}`),m.headersSent||m.writeHead(500).end("Internal Server Error")})});await o.connect(s);try{await new Promise((p,m)=>{let d=f=>{m(f.code==="EADDRINUSE"?new Error(`MCP HTTP server failed to start: port ${n} is already in use.`):f)};a.once("error",d),a.listen(n,()=>{a.off("error",d),p()})})}catch(p){throw await o.close().catch(()=>{}),p}let l=a.address().port;return{get toolCount(){return bl(r,e.expose).length},port:l,stop:async()=>{try{await o.close()}finally{await new Promise((p,m)=>{a.close(d=>d?m(d):p())})}}}}throw new Error(`Unknown MCP transport: "${e.transport}". Use 'stdio' or 'http'.`)}function bl(r,e){return e?e.categories?.length?r.getByCategories(e.categories):e.tools?.length?r.getByNames(e.tools):r.getEnabled():r.getEnabled()}function BC(r,e,t){let o=r.get(e);if(o)return t?.categories?.length?new Set(t.categories).has(o.category)?o:void 0:t?.tools?.length?t.tools.includes(e)?o:void 0:zC(r,o,e)?o:void 0}function zC(r,e,t){let{enabledTools:o,enabledToolCategories:n}=r.getConfig();return o.length===0&&n.length===0?!0:o.includes(t)||n.includes(e.category)}function jT(r){return(r.agents??[]).map(e=>({name:`agent.${e.name}`,description:e.description,inputSchema:e.inputSchema??{type:"object",properties:{}}}))}function HC(r,e){let t=r.getConfig().toolSearch;if(!t)return[];let o=r.getByNames(t.alwaysLoadedTools),n=r.getByCategories(t.alwaysLoadedCategories),s=new Set([je]),i=[...o,...n].filter(a=>s.has(a.name)?!1:(s.add(a.name),!0));if(e.expose?.categories?.length){let a=new Set(e.expose.categories);return i.filter(l=>a.has(l.category))}if(e.expose?.tools?.length){let a=new Set(e.expose.tools);return i.filter(l=>a.has(l.name))}return i}function FT(r){if(r.annotations)return r.annotations;if(r.confirmation)return{destructiveHint:!0}}function Ie(r,e=!1){return{content:[{type:"text",text:typeof r=="string"?r:JSON.stringify(r,null,2)}],isError:e}}var qT,WT,UT,GT,BT,xs,HT=g(()=>{"use strict";c();qT=require("http"),WT=require("crypto"),UT=require("@modelcontextprotocol/sdk/server/index.js"),GT=require("@modelcontextprotocol/sdk/server/stdio.js"),BT=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),xs=require("@modelcontextprotocol/sdk/types.js");k();LT();Tn()});var eS={};X(eS,{AGENT_MODE:()=>ul,AGENT_PLANNING_PROMPT:()=>bs,AGENT_WORKFLOW:()=>pl,AIClient:()=>kn,AnthropicAdapter:()=>_n,AuthenticationError:()=>he,BM25SearchEngine:()=>Ct,BUILT_IN_MODES:()=>vr,CHAT_MODE:()=>fl,CHAT_WORKFLOW:()=>dl,CODING_MODE:()=>gl,CODING_PLANNING_PROMPT:()=>MT,CODING_WORKFLOW:()=>ml,CONFIG_DIR_NAME:()=>vl,CONFIG_FILE_NAME:()=>Cl,ConnectionError:()=>Le,ContextWindowConfigError:()=>Es,ContextWindowExceededError:()=>Rr,ContextWindowStateManager:()=>Mr,ConversationNotFoundError:()=>Ds,DEFAULT_MODE_NAME:()=>yt,DEFAULT_TOOLS_CONFIG:()=>oe,DEFAULT_TOOL_SEARCH_CONFIG:()=>Fl,DEFAULT_WORKFLOW:()=>WC,DEFAULT_WORKFLOW_CONFIG:()=>ws,GeminiAdapter:()=>$n,InMemoryConversationStore:()=>Cs,InsufficientContextError:()=>$r,InvalidRequestError:()=>I,McpClient:()=>mn,McpConnectionError:()=>Ee,McpTimeoutError:()=>Tr,McpToolManager:()=>xr,ModeRegistry:()=>dn,OllamaAdapter:()=>Ge,OllamaProvider:()=>Rt,OpenAIAdapter:()=>lt,OpenRouterAdapter:()=>On,PageError:()=>Rs,Planner:()=>un,ProviderAdapter:()=>Y,ProviderError:()=>j,RateLimitError:()=>ce,SDKError:()=>A,SQLiteConversationStore:()=>Ss,SummarizationError:()=>Er,TOOLPACK_DIR_NAME:()=>xl,TOOL_SEARCH_NAME:()=>je,TimeoutError:()=>$s,ToolDiscoveryCache:()=>ot,ToolRegistry:()=>pn,ToolRouter:()=>St,Toolpack:()=>Tl,VertexAIAdapter:()=>Rn,WorkflowExecutor:()=>Cr,addBypassRule:()=>ic,buildSummarizedHistory:()=>vx,cloudDeployTool:()=>ir,cloudListTool:()=>lr,cloudStatusTool:()=>ar,cloudToolsProject:()=>Va,codingExtractFunctionTool:()=>tn,codingFindReferencesTool:()=>Ko,codingFindSymbolTool:()=>Bo,codingGetCallHierarchyTool:()=>on,codingGetDiagnosticsTool:()=>Zo,codingGetExportsTool:()=>en,codingGetImportsTool:()=>Ho,codingGetOutlineTool:()=>Yo,codingGetSymbolsTool:()=>zo,codingGoToDefinitionTool:()=>Jo,codingMultiFileEditTool:()=>Vo,codingRefactorRenameTool:()=>Xo,codingToolsProject:()=>ja,countTokens:()=>Os,createContextWindowStateManager:()=>Ws,createMcpToolProject:()=>hs,createMode:()=>OT,createSkillInterceptor:()=>ex,createSkillTools:()=>DT,createSummarizationReport:()=>Cx,createSummarySystemMessage:()=>Dr,createToolProject:()=>_T,dbCountTool:()=>sr,dbDeleteTool:()=>rr,dbInsertTool:()=>or,dbQueryTool:()=>Zn,dbSchemaTool:()=>er,dbTablesTool:()=>tr,dbToolsProject:()=>Ka,dbUpdateTool:()=>nr,diffApplyTool:()=>Qn,diffCreateTool:()=>Vn,diffPreviewTool:()=>Xn,diffToolsProject:()=>Ga,disconnectMcpToolProject:()=>ys,ensureGlobalConfigDir:()=>Pl,ensureLocalConfigDir:()=>JC,estimateSummaryTokens:()=>Al,estimateTokenCount:()=>Oe,execKillTool:()=>lo,execListProcessesTool:()=>co,execReadOutputTool:()=>io,execRunBackgroundTool:()=>ro,execRunBlockingTool:()=>so,execRunShellTool:()=>to,execRunTool:()=>eo,execTailOutputTool:()=>ao,execToolsProject:()=>Mi,extractConversationKeypoints:()=>xx,fetchUrlAsBase64:()=>Js,fsAppendFileTool:()=>At,fsBatchReadTool:()=>Yt,fsBatchWriteTool:()=>Zt,fsCopyTool:()=>Gt,fsCreateDirTool:()=>Wt,fsDeleteDirTool:()=>Xt,fsDeleteFileTool:()=>It,fsExistsTool:()=>Lt,fsGlobTool:()=>Qt,fsListDirTool:()=>Ft,fsMoveTool:()=>Ut,fsReadFileRangeTool:()=>zt,fsReadFileTool:()=>Et,fsReplaceInFileTool:()=>Kt,fsSearchTool:()=>Ht,fsStatTool:()=>jt,fsToolsProject:()=>vi,fsTreeTool:()=>Vt,fsWriteFileTool:()=>Mt,generateSummarizationPrompt:()=>Ol,generateToolCategoriesPrompt:()=>Or,getContextWindowPercentage:()=>yx,getDefaultSlmModel:()=>lc,getGlobalConfigDir:()=>Sl,getGlobalConfigPath:()=>kr,getGlobalToolpackDir:()=>QT,getLocalConfigDir:()=>kl,getLocalConfigPath:()=>Pr,getLocalToolpackDir:()=>XT,getMessageStats:()=>Tx,getMimeType:()=>Bs,getOllamaBaseUrl:()=>Mn,getOllamaProviderEntries:()=>sc,getRegisteredSlmModels:()=>pc,getRuntimeConfigStatus:()=>QC,getSafeOutputReserve:()=>As,getToolSearchSchema:()=>Fe,getToolpackConfig:()=>Lr,getUserHomeDir:()=>VT,gitAddTool:()=>Un,gitBlameTool:()=>Bn,gitBranchCreateTool:()=>Hn,gitBranchListTool:()=>zn,gitCheckoutTool:()=>Kn,gitCloneTool:()=>Jn,gitCommitTool:()=>Gn,gitDiffTool:()=>qn,gitLogTool:()=>Wn,gitStatusTool:()=>Fn,gitToolsProject:()=>qa,githubContentsGetTextTool:()=>Co,githubGraphqlExecuteTool:()=>vo,githubIssuesCommentsCreateTool:()=>Eo,githubPrDiffGetTool:()=>_o,githubPrFilesListTool:()=>Ro,githubPrReviewCommentsReplyTool:()=>Po,githubPrReviewThreadsListTool:()=>So,githubPrReviewThreadsResolveTool:()=>ko,githubPrReviewsSubmitTool:()=>$o,githubToolsProject:()=>sa,groupMessagesByRole:()=>wx,handleContextWindowError:()=>cx,httpDeleteTool:()=>wo,httpDownloadTool:()=>xo,httpGetTool:()=>ho,httpPostTool:()=>yo,httpPutTool:()=>bo,httpToolsProject:()=>Ji,initializeGlobalConfigIfFirstRun:()=>XC,isContextWindowError:()=>lx,isDataUri:()=>zs,isRegisteredSlm:()=>cc,isToolSearchTool:()=>rt,k8sApplyManifestTool:()=>dr,k8sDeleteResourceTool:()=>ur,k8sDescribeTool:()=>pr,k8sGetConfigMapTool:()=>hr,k8sGetLogsTool:()=>mr,k8sGetNamespacesTool:()=>br,k8sListDeploymentsTool:()=>gr,k8sListPodsTool:()=>cr,k8sListServicesTool:()=>fr,k8sSwitchContextTool:()=>yr,k8sToolsProject:()=>sl,k8sWaitForDeploymentTool:()=>wr,loadFullConfig:()=>In,loadRuntimeConfig:()=>VC,loadToolsConfig:()=>Mo,mergeSummarizationResults:()=>Sx,normalizeImagePart:()=>Yl,ollamaRequest:()=>Ce,ollamaStream:()=>Fr,parseDataUri:()=>Hs,parseSummarizationResponse:()=>qs,prepareSummarizationRequest:()=>Fs,pruneMessages:()=>Is,readFileAsBase64:()=>Ks,reloadToolpackConfig:()=>jr,removeBypassRule:()=>ac,saveToolsConfig:()=>ug,slackAuthTestTool:()=>cn,slackChatPostEphemeralTool:()=>rn,slackChatPostMessageTool:()=>nn,slackConversationsHistoryTool:()=>an,slackConversationsRepliesTool:()=>ln,slackReactionsAddTool:()=>sn,slackToolsProject:()=>nl,systemCwdTool:()=>fo,systemDiskUsageTool:()=>go,systemEnvTool:()=>mo,systemInfoTool:()=>po,systemSetEnvTool:()=>uo,systemToolsProject:()=>Wi,toDataUri:()=>Xl,toolSearchDefinition:()=>nt,truncateMessage:()=>bx,validateSummarizationResult:()=>js,webExtractLinksTool:()=>No,webFeedTool:()=>Fo,webFetchTool:()=>Do,webMapTool:()=>Io,webMetadataTool:()=>Lo,webScrapeTool:()=>Ao,webScreenshotTool:()=>qo,webSearchTool:()=>Oo,webSitemapTool:()=>jo,webToolsProject:()=>wa,wouldExceedContextWindow:()=>hx});module.exports=ax(eS);c();pe();c();var Jl=require("events");pe();c();pe();async function Dl(r,e={}){let{maxRetries:t=3,backoffMs:o=[1e4,3e4,6e4],isRetryable:n=i=>i instanceof ce,onRetry:s}=e;for(let i=0;i<=t;i++)try{return await r()}catch(a){if(n(a)&&i<t){let l=a?.retryAfter!=null?a.retryAfter*1e3:o[i]??o[o.length-1]??6e4;s?.(i+1,l,a),await new Promise(p=>setTimeout(p,l));continue}throw a}throw new ce("Rate limit retries exhausted")}c();pe();var bn=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
326
  Context Window Exceeded
312
327
  =======================
313
328
  Conversation ID: ${this.conversationId}
@@ -318,7 +333,7 @@ Usage: ${this.getUsagePercentage()}%
318
333
  Strategy: ${this.strategy}
319
334
 
320
335
  Message: ${this.message}
321
- `.trim()}};var un=class extends N{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=`
336
+ `.trim()}};var wn=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
337
  Summarization Error
323
338
  ===================
324
339
  Conversation ID: ${this.conversationId}
@@ -330,11 +345,11 @@ Recovery Action: ${this.getSuggestedRecovery()}
330
345
  Message: ${this.message}`;return this.summaryAttempt?t+`
331
346
 
332
347
  Partial Summary:
333
- ${this.summaryAttempt.substring(0,500)}${this.summaryAttempt.length>500?"...":""}`:t.trim()}};c();var Ss=null;async function hT(){if(!Ss)try{Ss=await import("js-tiktoken")}catch{}return Ss}var hl={"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},yT=2;async function bT(r,e){try{let t=await hT();if(!t)return Oe(r);let o=t.encoding_for_model(e),n=0,s=hl[e]??hl.__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+=yT,n}catch{return Oe(r)}}async function wT(r,e){try{let t=Oe(r);return Math.ceil(t*1.1)}catch{return Oe(r)}}async function TT(r,e){try{let t=Oe(r);return Math.ceil(t*1.05)}catch{return Oe(r)}}async function xT(r,e){let t=Oe(r);return Math.ceil(t*1.05)}function Oe(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 Rs(r,e,t){let o=t.toLowerCase();return o==="openai"||o==="openai-gpt"?bT(r,e):o==="anthropic"||o==="claude"?wT(r,e):o==="gemini"||o==="google"?TT(r,e):o==="ollama"?xT(r,e):Oe(r)}function vT(r,e,t){let o=e-t;return r>o}function CT(r,e){return Math.round(r/e*100)}function _s(r,e=1.15){return Math.ceil(r*e)}c();function Es(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=$s(p);if(s+=m,n.push(p),p.role==="assistant"&&p.tool_calls?.length){let u=new Set(p.tool_calls.map(f=>f.id));for(let f of r)f.role==="tool"&&f.tool_call_id&&u.has(f.tool_call_id)&&(s+=$s(f),n.push(f))}}let a=new Set(n),l=r.filter(p=>!a.has(p));return{removed:n.length,tokensReclaimed:s,newTotal:l.length,pruneInfo:{beforeCount:o,afterCount:l.length,removedMessages:n}}}function PT(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}
348
+ ${this.summaryAttempt.substring(0,500)}${this.summaryAttempt.length>500?"...":""}`:t.trim()}};c();var Ms=null;async function px(){if(!Ms)try{Ms=await import("js-tiktoken")}catch{}return Ms}var Ml={"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},mx=2;async function dx(r,e){try{let t=await px();if(!t)return Oe(r);let o=t.encoding_for_model(e),n=0,s=Ml[e]??Ml.__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+=mx,n}catch{return Oe(r)}}async function ux(r,e){try{let t=Oe(r);return Math.ceil(t*1.1)}catch{return Oe(r)}}async function fx(r,e){try{let t=Oe(r);return Math.ceil(t*1.05)}catch{return Oe(r)}}async function gx(r,e){let t=Oe(r);return Math.ceil(t*1.05)}function Oe(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 Os(r,e,t){let o=t.toLowerCase();return o==="openai"||o==="openai-gpt"?dx(r,e):o==="anthropic"||o==="claude"?ux(r,e):o==="gemini"||o==="google"?fx(r,e):o==="ollama"?gx(r,e):Oe(r)}function hx(r,e,t){let o=e-t;return r>o}function yx(r,e){return Math.round(r/e*100)}function As(r,e=1.15){return Math.ceil(r*e)}c();function Is(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=Ns(p);if(s+=m,n.push(p),p.role==="assistant"&&p.tool_calls?.length){let d=new Set(p.tool_calls.map(f=>f.id));for(let f of r)f.role==="tool"&&f.tool_call_id&&d.has(f.tool_call_id)&&(s+=Ns(f),n.push(f))}}let a=new Set(n),l=r.filter(p=>!a.has(p));return{removed:n.length,tokensReclaimed:s,newTotal:l.length,pruneInfo:{beforeCount:o,afterCount:l.length,removedMessages:n}}}function bx(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
349
 
335
- [...truncated ${n} tokens]`}}else if(Array.isArray(r.content)){let t=r.content.filter(a=>a.type==="text"),o=t.reduce((a,l)=>a+(l.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 l=n-s;if(l<=0)break;let p=a.text;if(p.length<=l)i.push(a),s+=p.length;else{let m=p.substring(0,l),u=Math.ceil((p.length-l)/4);i.push({type:"text",text:`${m}
350
+ [...truncated ${n} tokens]`}}else if(Array.isArray(r.content)){let t=r.content.filter(a=>a.type==="text"),o=t.reduce((a,l)=>a+(l.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 l=n-s;if(l<=0)break;let p=a.text;if(p.length<=l)i.push(a),s+=p.length;else{let m=p.substring(0,l),d=Math.ceil((p.length-l)/4);i.push({type:"text",text:`${m}
336
351
 
337
- [...truncated ${u} tokens]`});break}}return{...r,content:i.length>0?i:r.content}}return r}function $s(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 kT(r){let e={system:[],user:[],assistant:[],tool:[]};return r.forEach(t=>{e[t.role]??=[],e[t.role].push(t)}),e}function ST(r){let e=0,t={},o=0;for(let n of r){let s=$s(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}}c();pe();function Ds(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 yl(r,e){if(e)return e;let t=r.filter(l=>l.role==="user"),o=r.filter(l=>l.role==="assistant"),n=r.filter(l=>l.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`:""}).
352
+ [...truncated ${d} tokens]`});break}}return{...r,content:i.length>0?i:r.content}}return r}function Ns(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 wx(r){let e={system:[],user:[],assistant:[],tool:[]};return r.forEach(t=>{e[t.role]??=[],e[t.role].push(t)}),e}function Tx(r){let e=0,t={},o=0;for(let n of r){let s=Ns(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}}c();pe();function Ls(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 Ol(r,e){if(e)return e;let t=r.filter(l=>l.role==="user"),o=r.filter(l=>l.role==="assistant"),n=r.filter(l=>l.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
353
 
339
354
  Focus on:
340
355
  1. Key topics discussed
@@ -346,22 +361,22 @@ The summary should be comprehensive yet concise, preserving all critical informa
346
361
 
347
362
  ---
348
363
  CONVERSATION:
349
- ${r.map((l,p)=>{let m=Ds(l);return`[Message ${p+1}] ${l.role.toUpperCase()}: ${m.substring(0,200)}${m.length>200?"...":""}`}).join(`
364
+ ${r.map((l,p)=>{let m=Ls(l);return`[Message ${p+1}] ${l.role.toUpperCase()}: ${m.substring(0,200)}${m.length>200?"...":""}`}).join(`
350
365
  `)}
351
366
  ---
352
367
 
353
- SUMMARY:`}function gr(r,e){return{role:"system",content:`[Context Summary]
368
+ SUMMARY:`}function Dr(r,e){return{role:"system",content:`[Context Summary]
354
369
  This conversation has been summarized to manage context window. The following is a summary of the first ${e} messages:
355
370
 
356
371
  ${r}
357
372
 
358
373
  [End Summary]
359
374
 
360
- Use this summary to understand the conversation context. When responding, acknowledge that you're aware of the previous conversation and continue naturally.`}}function RT(r){let e=new Set,t=[],o=[],n="";for(let s of r)if(s.role==="user"){let i=Ds(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(l=>e.add(l))}else if(s.role==="assistant"){let i=Ds(s);if(i.includes("decided")||i.includes("concluded")||i.includes("determined")){let a=i.split(/[.!?]+/);for(let l of a)(l.includes("decided")||l.includes("concluded")||l.includes("determined"))&&t.push(l.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 bl(r){return Math.ceil(r.length/4)}function Ms(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 Os(r,e){let t=yl(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.
375
+ Use this summary to understand the conversation context. When responding, acknowledge that you're aware of the previous conversation and continue naturally.`}}function xx(r){let e=new Set,t=[],o=[],n="";for(let s of r)if(s.role==="user"){let i=Ls(s);n=i,i.includes("?")&&o.push(i.split(`
376
+ `)[0]);let a=i.match(/\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*\b/g);a&&a.forEach(l=>e.add(l))}else if(s.role==="assistant"){let i=Ls(s);if(i.includes("decided")||i.includes("concluded")||i.includes("determined")){let a=i.split(/[.!?]+/);for(let l of a)(l.includes("decided")||l.includes("concluded")||l.includes("determined"))&&t.push(l.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 Al(r){return Math.ceil(r.length/4)}function js(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 Fs(r,e){let t=Ol(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
377
 
363
378
  Maximum summary length: ${e.maxSummaryTokens||500} tokens.
364
- Format: Write only the summary without any additional commentary.`},{role:"user",content:t}]}function Ns(r,e,t){let o=bl(r),n=Math.max(0,t-o);return{summary:r.trim(),messageCount:e.length,originalTokens:t,summaryTokens:o,tokensSaved:n,timestamp:new Date}}function _T(r,e,t){let o=[...r];return o.push(gr(e.summary,e.messageCount)),o.push(...t),o}function $T(r,e,t){let o=Math.round(r.tokensSaved/r.originalTokens*100);return`
379
+ Format: Write only the summary without any additional commentary.`},{role:"user",content:t}]}function qs(r,e,t){let o=Al(r),n=Math.max(0,t-o);return{summary:r.trim(),messageCount:e.length,originalTokens:t,summaryTokens:o,tokensSaved:n,timestamp:new Date}}function vx(r,e,t){let o=[...r];return o.push(Dr(e.summary,e.messageCount)),o.push(...t),o}function Cx(r,e,t){let o=Math.round(r.tokensSaved/r.originalTokens*100);return`
365
380
  Summarization Report
366
381
  ====================
367
382
  Timestamp: ${r.timestamp.toISOString()}
@@ -380,37 +395,31 @@ Message Count:
380
395
 
381
396
  Summary Preview:
382
397
  ${r.summary.substring(0,300)}${r.summary.length>300?"...":""}
383
- `.trim()}function ET(r){if(r.length===0)throw new N("Cannot merge empty summarization results","CONTEXT_WINDOW_ERROR");return{summary:r.map(t=>`[Round ${r.indexOf(t)+1}] ${t.summary}`).join(`
398
+ `.trim()}function Sx(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
399
 
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}}c();var hr=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((u,f)=>u+f.estimatedTokens,0),s=e.reduce((u,f)=>u+f.pruneCount,0),i=e.reduce((u,f)=>u+f.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 l=this.getAtRiskConversations();l.length>0&&(o.push(`At-Risk Conversations (80%+ threshold): ${l.length}`),l.forEach(u=>{let f=Math.round(u.estimatedTokens/t*100);o.push(`- ${u.conversationId}: ${u.estimatedTokens}/${t} tokens (${f}%)`)}),o.push(""));let p=this.getExceedingThreshold();return p.length>0&&(o.push(`Exceeded Conversations: ${p.length}`),p.forEach(u=>{let f=u.estimatedTokens-t;o.push(`- ${u.conversationId}: ${u.estimatedTokens}/${t} tokens (+${f} over)`)}),o.push("")),o.push("Most Active Conversations (by operations):"),[...e].sort((u,f)=>{let b=u.pruneCount+u.summarizationCount;return f.pruneCount+f.summarizationCount-b}).slice(0,5).forEach(u=>{let f=u.pruneCount+u.summarizationCount;o.push(`- ${u.conversationId}: ${u.pruneCount} prunes, ${u.summarizationCount} summarizations (${f} 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 As(r){return new hr(r)}c();c();c();var bt={name:3,displayName:2.5,description:2,category:1.5,parameterNames:1,parameterDescriptions:.5},wt=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 l of this.documents){if(n&&l.tool.category!==n)continue;let p=this.computeBM25Score(i,l);p>s&&a.push({toolName:l.toolName,score:p,tool:l.tool})}return a.sort((l,p)=>p.score-l.score).slice(0,o).map(({toolName:l,score:p,tool:m})=>({toolName:l,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<bt.name;i++)t.push(e.name);for(let i=0;i<bt.displayName;i++)t.push(e.displayName);for(let i=0;i<bt.description;i++)t.push(e.description);for(let i=0;i<bt.category;i++)t.push(e.category);if(e.parameters?.properties)for(let[i,a]of Object.entries(e.parameters.properties)){for(let l=0;l<bt.parameterNames;l++)t.push(i);if(a.description)for(let l=0;l<bt.parameterDescriptions;l++)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=>!DT.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,l=s*(this.k1+1),p=s+this.k1*(1-this.b+this.b*(a/this.avgDocLength));o+=i*(l/p)}return o}toSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category}}},DT=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"]);c();var Ze=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())}};c();var Tt="tool.search",et={name:Tt,displayName:"Search Tools",category:"meta",description:`Search for available tools by keyword or natural language query.
387
- Use this to discover tools before using them.
388
- Examples: "file operations", "web scraping", "run command", "http request"
389
-
390
- Returns a list of matching tools with their names, descriptions, and parameters.
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 xt(){return{name:et.name,displayName:et.displayName,description:et.description,parameters:et.parameters,category:et.category}}function fn(r){return r===Tt}c();var MT={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 yr(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=MT[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 vt=class{discoveryCache=new Ze;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(xt()),s.add(Tt);let i=o.toolSearch?.alwaysLoadedTools??[];for(let l of i){let p=t.get(l);p&&!s.has(l)&&(n.push(this.toSchema(p)),s.add(l))}let a=o.toolSearch?.alwaysLoadedCategories??[];for(let l of a)for(let p of t.getByCategory(l))s.has(p.name)||(n.push(this.toSchema(p)),s.add(p.name));if(o.toolSearch?.cacheDiscoveredTools!==!1){let l=Ze.fromMessages(e);this.discoveryCache.merge(l);let p=this.discoveryCache.getDiscoveredTools();for(let m of p){let u=t.get(m);u&&!s.has(m)&&u.cacheable!==!1&&(n.push(this.toSchema(u)),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}}};gn();c();function Tl(r){if(r.disabled)return"";let e=r.includeWorkingDirectory!==!1,t=r.includeToolCategories!==!1,o=e?`
400
+ `),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}}c();var Mr=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((d,f)=>d+f.estimatedTokens,0),s=e.reduce((d,f)=>d+f.pruneCount,0),i=e.reduce((d,f)=>d+f.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 l=this.getAtRiskConversations();l.length>0&&(o.push(`At-Risk Conversations (80%+ threshold): ${l.length}`),l.forEach(d=>{let f=Math.round(d.estimatedTokens/t*100);o.push(`- ${d.conversationId}: ${d.estimatedTokens}/${t} tokens (${f}%)`)}),o.push(""));let p=this.getExceedingThreshold();return p.length>0&&(o.push(`Exceeded Conversations: ${p.length}`),p.forEach(d=>{let f=d.estimatedTokens-t;o.push(`- ${d.conversationId}: ${d.estimatedTokens}/${t} tokens (+${f} over)`)}),o.push("")),o.push("Most Active Conversations (by operations):"),[...e].sort((d,f)=>{let b=d.pruneCount+d.summarizationCount;return f.pruneCount+f.summarizationCount-b}).slice(0,5).forEach(d=>{let f=d.pruneCount+d.summarizationCount;o.push(`- ${d.conversationId}: ${d.pruneCount} prunes, ${d.summarizationCount} summarizations (${f} operations)`)}),o.join(`
401
+ `)}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 Ws(r){return new Mr(r)}c();Tn();var St=class{discoveryCache=new ot;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(Fe()),s.add(je);let i=o.toolSearch?.alwaysLoadedTools??[];for(let l of i){let p=t.get(l);p&&!s.has(l)&&(n.push(this.toSchema(p)),s.add(l))}let a=o.toolSearch?.alwaysLoadedCategories??[];for(let l of a)for(let p of t.getByCategory(l))s.has(p.name)||(n.push(this.toSchema(p)),s.add(p.name));if(o.toolSearch?.cacheDiscoveredTools!==!1){let l=ot.fromMessages(e);this.discoveryCache.merge(l);let p=this.discoveryCache.getDiscoveredTools();for(let m of p){let d=t.get(m);d&&!s.has(m)&&d.cacheable!==!1&&(n.push(this.toSchema(d)),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}}};xn();Tn();c();function ql(r){if(r.disabled)return"";let e=r.includeWorkingDirectory!==!1,t=r.includeToolCategories!==!1,o=e?`
393
402
  Working directory: ${r.workingDirectory}`:"",n=t&&r.toolCategories.length>0?`
394
403
  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}
395
404
 
396
405
  When the user asks you to do something, be proactive:
397
406
  - Use your tools to find information rather than asking the user for details you can discover yourself
398
407
  - Read files, list directories, and explore the codebase when asked to analyze or understand a project
399
- - Only ask the user for clarification when you genuinely cannot determine their intent or lack the required tools`}c();var Ct=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)}};c();var br=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 l=e[a];this.hasDependency(n,l,i)&&s.push(l.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(f=>f.toolCallId===p.id)?.dependsOn.every(f=>i.has(f))??!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 l=await this.executeBatchWithLimit(a,t,o);for(let{id:p,result:m}of l)s.set(p,m),i.add(p)}return s}async executeBatchWithLimit(e,t,o){let n=async i=>(await Promise.allSettled(i.map(async l=>({id:l.id,result:await t(l)})))).map((l,p)=>l.status==="fulfilled"?l.value:{id:i[p].id,result:JSON.stringify({error:l.reason?.message??"Tool execution failed"})});if(e.length<=o)return n(e);let s=[];for(let i=0;i<e.length;i+=o)s.push(...await n(e.slice(i,i+o)));return s}shouldUseParallelExecution(e){return e.length>=2}};c();function tt(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 Pl=0;function kl(){return Pl+=1,`${Date.now()}-${Pl}`}function wr(r,e){ot("debug")&&(h(`[AIClient][${r}] Messages (${e.length}):`),e.forEach((t,o)=>{let n=O(t.content,300);h(`[AIClient][${r}] #${o} role=${t.role} content=${n}`)}))}function Sl(r){let e=tt(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 Rl(r){let e=tt(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 wn=class extends _l.EventEmitter{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||te,this.toolRouter=new vt,this.bm25Engine=new wt,this.queryClassifier=new Ct,this.toolOrchestrator=new br,this.overrideSystemPrompt=e.systemPrompt,this.disableBaseContext=e.disableBaseContext||!1;let t=this.toolsConfig.resultMaxChars??te.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=As(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:Rs(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 l=a-o,p=Es(s.messages,l,n),m=new Set(p.pruneInfo.removedMessages),u=s.messages.filter(y=>!m.has(y)),f={...s,messages:u};if(this.contextWindowStateManager&&this.contextWindowStateManager.recordPruneOperation(this.getConversationId(),p.tokensReclaimed),await this.countRequestTokens(f,t,f.model)<=o||u.length===s.messages.length)return f;s=f}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((l,p)=>{o&&l.role==="system"||l.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((l,p)=>!i.has(p));return{...e,messages:a}}async summarizeConversation(e,t){let o=e.messages,n=o.filter(x=>x.role==="system"),s=o.filter(x=>x.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 l=this.contextWindowConfig?.summarizerModel||e.model,p=Os(a,{model:l,maxSummaryTokens:500}),m=await t.generate({model:l,messages:p,max_tokens:500,temperature:0,response_format:"text"});if(!m.content)throw new un("Summarization provider returned no summary",this.getConversationId(),a.length,"invalid_response");let u=await this.countRequestTokens({...e,messages:a},t,l),f=Ns(m.content,a,u),b=Ms(f);if(!b.valid)throw new un(`Summarization result is invalid: ${b.issues.join("; ")}`,this.getConversationId(),a.length,"invalid_quality",m.content);let y=gr(f.summary,a.length),w=[...n,y,...i];return this.contextWindowStateManager&&this.contextWindowStateManager.recordSummarization(this.getConversationId(),f.tokensSaved),{...e,messages:w}}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,l=_s(i,a),p=Math.max(0,s-l),m=Math.floor(s*((this.contextWindowConfig.pruneThreshold??85)/100)),u=Math.min(p,m),f=await this.countRequestTokens(o,t,o.model);if(this.contextWindowStateManager&&(this.contextWindowStateManager.updateTokenCount(this.getConversationId(),f),f>u&&this.contextWindowStateManager.recordWarning(this.getConversationId())),f<=u)return o;let b=this.contextWindowConfig.strategy??"prune";if(b==="fail"&&f>p)throw new dn("Context window exceeded by request messages",this.getConversationId(),f,p,b);if(b==="summarize")try{let w=await this.summarizeConversation(o,t);if(await this.countRequestTokens(w,t,w.model)<=p)return w;o=await this.pruneConversation(w,t,p)}catch{o=await this.pruneConversation(o,t,p)}else o=await this.pruneConversation(o,t,p);let y=await this.countRequestTokens(o,t,o.model);if(y>p&&b==="fail")throw new dn("Context window exceeded after attempted cleanup",this.getConversationId(),y,p,b);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 N("No provider specified and no default provider configured","NO_PROVIDER_CONFIGURED",400);let o=this.providers.get(t);if(!o)throw new N(`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 N(`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,S(`[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()),S(`[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=kl(),s=this.injectBaseAgentContext(e);s=this.injectOverrideSystemPrompt(s),s=this.injectModeSystemPrompt(s);let i=t||this.defaultProvider,a=await this.enrichRequestWithTools(s),l=a.request,p=a.requestToolMap;l=await this.enforceContextWindow(l,o);let m=process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||this.toolsConfig.toolChoicePolicy||"auto",u=(l.tools?.length||0)>0,f=l.tool_choice!=null,b=Sl(l.messages),y=Rl(l.messages);!f&&u&&(m==="required"||m==="required_for_actions"&&b)&&(l.tool_choice="required");let x=o?.constructor?.name||"UnknownProvider",C=this.activeMode?.response_format,v={...this.stripRequestTools(l),__toolpack_request_id:n,...C?{response_format:C}:{}};S(`[AIClient][${n}] generate() start provider=${i} class=${x} model=${l.model} messages=${l.messages.length} tools=${l.tools?.length||0} tool_choice=${l.tool_choice??"unset"} policy=${m} needsTools=${b} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),wr(n,l.messages);let $=M=>gl(()=>o.generate(M),{onRetry:(R,D)=>S(`[AIClient][${n}] Rate limited \u2014 retrying in ${D/1e3}s (attempt ${R}/3)`)}),P=await $(v);if(h(`[AIClient][${n}] generate() initial response finish_reason=${P.finish_reason??"unknown"} tool_calls=${P.tool_calls?.length||0} content_preview=${O(P.content||"",200)}`),this.toolsConfig.autoExecute&&(this.toolRegistry||p.size>0)){let M=tt(l.messages),R=this.queryClassifier.classify(M),D=this.toolsConfig.maxToolRounds,_=l.maxToolRounds!==void 0?l.maxToolRounds:this.queryClassifier.getToolRoundsAdjustment(R,D);l.maxToolRounds!==void 0?h(`[AIClient][${n}] maxToolRounds overridden per-request: ${_} (classifier bypassed)`):_!==D?S(`[AIClient][${n}] Query classified as ${R.type} (confidence: ${R.confidence.toFixed(2)}), adjusted maxToolRounds: ${D} \u2192 ${_}`):h(`[AIClient][${n}] Query classified as ${R.type} (confidence: ${R.confidence.toFixed(2)}), keeping maxToolRounds: ${_}`);let W=0,z=[...l.messages];for(P.tool_calls&&P.tool_calls.length>0&&S(`[AIClient] Received ${P.tool_calls.length} tool call(s): ${P.tool_calls.map(gt=>gt.name).join(", ")}`);P.tool_calls&&P.tool_calls.length>0&&W<_;){W++,this.currentRound=W,S(`[AIClient][${n}] generate() tool round ${W}/${_} tool_calls=${P.tool_calls.length}`),z.push({role:"assistant",content:P.content||"",tool_calls:P.tool_calls.map(K=>({id:K.id,type:"function",function:{name:K.name,arguments:JSON.stringify(K.arguments)}}))});let gt=this.toolOrchestrator.shouldUseParallelExecution(P.tool_calls),ht=3,se=P.tool_calls,De=P.tool_calls.filter(K=>K.name==="web.fetch");if(De.length>ht){S(`[AIClient][${n}] Limiting web.fetch calls from ${De.length} \u2192 ${ht} to prevent context overflow`);let K=De.slice(0,ht);se=[...P.tool_calls.filter(xe=>xe.name!=="web.fetch"),...K];let Q=De.slice(ht);for(let xe of Q)z.push({role:"tool",tool_call_id:xe.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let Z=5e4,fe=0;if(gt){S(`[AIClient][${n}] Using parallel execution for ${se.length} tools`);let K;try{K=await this.toolOrchestrator.executeWithDependencies(se,U=>this.executeTool(U,p),5)}catch(U){me(`[AIClient][${n}] Parallel tool execution failed: ${U.message}`),K=new Map(se.map(Q=>[Q.id,JSON.stringify({error:U.message??"Tool execution failed"})]))}for(let U of se){let Q=K.get(U.id)??JSON.stringify({error:"Tool execution result missing"}),xe=typeof Q=="string"?Q:JSON.stringify(Q),ie=Z-fe,ee;fe+xe.length>Z?(L(`[AIClient][${n}] Tool output budget exceeded (${Z} chars)`),ee=this.budgetTruncate(xe,ie)):typeof Q=="string"&&Q.length>this.toolResultMaxChars?ee=`${Q.slice(0,this.toolResultMaxChars)}
401
- [TRUNCATED tool result: ${Q.length} chars]`:ee=xe;let E=typeof ee=="string"?ee:JSON.stringify(ee);fe+=E.length,z.push({role:"tool",tool_call_id:U.id,content:ee})}h(`[AIClient][${n}] Round tool output size: ${fe} chars (budget: ${Z})`)}else{S(`[AIClient][${n}] Using sequential execution for ${se.length} tools`);for(let K of se){let U;try{U=await this.executeTool(K,p)}catch(E){U=JSON.stringify({error:E.message??"Tool execution failed"})}let Q=typeof U=="string"?U:JSON.stringify(U),xe=Z-fe,ie;fe+Q.length>Z?(L(`[AIClient][${n}] Tool output budget exceeded (${Z} chars)`),ie=this.budgetTruncate(Q,xe)):typeof U=="string"&&U.length>this.toolResultMaxChars?ie=`${U.slice(0,this.toolResultMaxChars)}
402
- [TRUNCATED tool result: ${U.length} chars]`:ie=Q;let ee=typeof ie=="string"?ie:JSON.stringify(ie);fe+=ee.length,z.push({role:"tool",tool_call_id:K.id,content:ie})}h(`[AIClient][${n}] Round tool output size: ${fe} chars (budget: ${Z})`)}let yt={...l,messages:z,__toolpack_request_id:n,...C?{response_format:C}:{}},Te=this.stripRequestTools((await this.enrichRequestWithTools(yt)).request);Te=await this.enforceContextWindow(Te,o),Te.tool_choice==="required"&&(Te.tool_choice=y?"none":"auto",S(`[AIClient][${n}] generate() followup tool_choice override required->${Te.tool_choice}`)),ot("debug")&&(h(`[AIClient][${n}] generate() followup request messages=${z.length}`),wr(n,z)),P=await $(Te),h(`[AIClient][${n}] generate() followup response finish_reason=${P.finish_reason??"unknown"} tool_calls=${P.tool_calls?.length||0} content_preview=${O(P.content||"",200)}`)}}return P}catch(n){throw this.wrapError(n)}}async*stream(e,t){let o=this.getProvider(t);try{let n=kl(),s=t||this.defaultProvider,i=this.injectBaseAgentContext(e);i=this.injectOverrideSystemPrompt(i),i=this.injectModeSystemPrompt(i);let a=await this.enrichRequestWithTools(i),l=a.request,p=a.requestToolMap;l=await this.enforceContextWindow(l,o);let m=process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||this.toolsConfig.toolChoicePolicy||"auto",u=(l.tools?.length||0)>0,f=l.tool_choice!=null,b=Sl(l.messages),y=Rl(l.messages);!f&&u&&(m==="required"||m==="required_for_actions"&&b)&&(l.tool_choice="required");let x=o?.constructor?.name||"UnknownProvider",C=this.activeMode?.response_format,v={...this.stripRequestTools(l),__toolpack_request_id:n,...C?{response_format:C}:{}};if(S(`[AIClient][${n}] stream() start provider=${s} class=${x} model=${l.model} messages=${l.messages.length} tools=${l.tools?.length||0} tool_choice=${l.tool_choice??"unset"} policy=${m} needsTools=${b} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),wr(n,l.messages),!this.toolsConfig.autoExecute||!this.toolRegistry&&p.size===0){yield*o.stream(v);return}let $=[...l.messages],P=0,M=tt(l.messages),R=this.queryClassifier.classify(M),D=this.toolsConfig.maxToolRounds,_=l.maxToolRounds!==void 0?l.maxToolRounds:this.queryClassifier.getToolRoundsAdjustment(R,D);for(l.maxToolRounds!==void 0?h(`[AIClient][${n}] stream() maxToolRounds overridden per-request: ${_} (classifier bypassed)`):_!==D&&S(`[AIClient][${n}] stream() Query classified as ${R.type} (confidence: ${R.confidence.toFixed(2)}), adjusted maxToolRounds: ${D} \u2192 ${_}`);P<=_;){if(e.signal?.aborted){S(`[AIClient][${n}] stream() aborted by signal`);return}let W="",z=[];P++,this.currentRound=P,S(`[AIClient][${n}] stream() round_start ${P}/${_}`);let gt=null,ht={...l,messages:$,...C?{response_format:C}:{}},se=this.stripRequestTools((await this.enrichRequestWithTools(ht)).request);se=await this.enforceContextWindow(se,o),P>1&&se.tool_choice==="required"&&(se.tool_choice=y?"none":"auto",S(`[AIClient][${n}] stream() round_${P} tool_choice override required->${se.tool_choice}`));for await(let E of o.stream(se)){if(e.signal?.aborted){S(`[AIClient][${n}] stream() aborted by signal during chunk processing`);return}E.tool_calls&&E.tool_calls.length>0&&(z.push(...E.tool_calls),h(`[AIClient][${n}] stream() tool_calls_chunk count=${E.tool_calls.length} names=${E.tool_calls.map(ae=>ae.name).join(", ")}`),yield E),E.delta&&(W+=E.delta,yield E),E.finish_reason&&(gt=E.finish_reason),E.finish_reason==="stop"&&(yield E)}if(h(`[AIClient][${n}] stream() round_end finish_reason=${gt??"unknown"} accumulated_len=${W.length} tool_calls_total=${z.length} content_preview=${O(W,200)}`),z.length===0)break;S(`[AIClient][${n}] stream() received ${z.length} tool call(s): ${z.map(E=>E.name).join(", ")}`),S(`[AIClient][${n}] stream() tool round ${P}/${_}`),$.push({role:"assistant",content:W||"",tool_calls:z.map(E=>({id:E.id,type:"function",function:{name:E.name,arguments:JSON.stringify(E.arguments)}}))});let De=3,Z=z,fe=z.filter(E=>E.name==="web.fetch");if(fe.length>De){S(`[AIClient][${n}] Limiting web.fetch calls from ${fe.length} \u2192 ${De} to prevent context overflow`);let E=fe.slice(0,De);Z=[...z.filter(mn=>mn.name!=="web.fetch"),...E];let Me=fe.slice(De);for(let mn of Me)$.push({role:"tool",tool_call_id:mn.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let yt=5e4,Te=0,K=[],U=!1,Q=setInterval(()=>{U||K.push({delta:""})},500),xe=Date.now(),ie,ee;try{if(Z.length>=2)S(`[AIClient][${n}] stream() using parallel execution for ${Z.length} tools`),ee=new Map,ie=await this.toolOrchestrator.executeWithDependencies(Z,async E=>{let ae=Date.now(),Me=await this.executeTool(E,p);return ee.set(E.id,Date.now()-ae),Me},5);else{S(`[AIClient][${n}] stream() executing single tool sequentially`),ee=new Map,ie=new Map;for(let E of Z){let ae=Date.now(),Me=await this.executeTool(E,p);ee.set(E.id,Date.now()-ae),ie.set(E.id,Me)}}}finally{U=!0,clearInterval(Q)}for(;K.length>0;)yield K.shift();await new Promise(E=>setTimeout(E,0)),h(`[AIClient][${n}] stream() tool batch completed in ${Date.now()-xe}ms`);for(let E of Z){let ae=ie.get(E.id),Me=typeof ae=="string"?ae:JSON.stringify(ae),mn=yt-Te,aT=ee.get(E.id)??0,Ye;Te+Me.length>yt?(L(`[AIClient][${n}] Tool output budget exceeded (${yt} chars)`),Ye=this.budgetTruncate(Me,mn)):typeof ae=="string"&&ae.length>this.toolResultMaxChars?Ye=`${ae.slice(0,this.toolResultMaxChars)}
403
- [TRUNCATED tool result: ${ae.length} chars]`:Ye=Me;let ul=typeof Ye=="string"?Ye:JSON.stringify(Ye);Te+=ul.length,$.push({role:"tool",tool_call_id:E.id,content:Ye}),yield{delta:"",tool_calls:[{...E,result:ul,duration:aT}]}}h(`[AIClient][${n}] Round tool output size: ${Te} chars (budget: ${yt})`),ot("debug")&&(h(`[AIClient][${n}] stream() after_tools messages=${$.length}`),wr(n,$))}}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 S(`[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 h("[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}:{}}},h(`[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){h(`[AIClient] Request already has ${e.tools.length} tools`);let y=this.mergeToolCallRequests(e.tools,this.schemasToToolCallRequests(o)),w=y===e.tools?e:{...e,tools:y};return{request:this.injectRequestToolGuidance(w,y),requestToolMap:t}}let m=await this.toolRouter.resolve(e.messages,this.toolRegistry,s);if(h(`[AIClient] Resolved ${m.length} tools to send: ${m.map(y=>y.name).join(", ")||"none"}`),this.activeMode&&m.length>0){let y=m.length;m=this.filterSchemasByMode(m,this.activeMode);let w=y-m.length;w>0&&S(`[AIClient] Mode "${this.activeMode.displayName}" filtered out ${w} tools`)}let u=new Set(e.tools.map(y=>y.function.name)),f=m.filter(y=>!u.has(y.name)).map(y=>({type:"function",function:{name:y.name,description:y.description,parameters:y.parameters}}));if(f.length===0){h(`[AIClient] Request already has ${e.tools.length} tools (no new discoveries)`);let y=this.mergeToolCallRequests(e.tools,this.schemasToToolCallRequests(o)),w=y===e.tools?e:{...e,tools:y};return{request:this.injectRequestToolGuidance(w,y),requestToolMap:t}}let b={...e,tools:this.mergeToolCallRequests([...e.tools,...f],this.schemasToToolCallRequests(o))};return s.toolSearch?.enabled&&this.toolRegistry&&(b=this.injectToolSearchPrompt(b)),{request:this.injectRequestToolGuidance(b,b.tools),requestToolMap:t}}if(!this.toolRegistry){h("[AIClient] Tool registry not configured, skipping tool resolution");let m=this.schemasToToolCallRequests(o),u=m.length>0?{...e,tools:m}:e;return{request:this.injectRequestToolGuidance(u,m),requestToolMap:t}}let i=this.toolRegistry,a=await this.toolRouter.resolve(e.messages,i,s);if(h(`[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 u=m-a.length;u>0&&S(`[AIClient] Mode "${this.activeMode.displayName}" filtered out ${u} tools`)}let l=this.schemasToToolCallRequests(this.mergeSchemas(a,o));if(l.length===0)return{request:e,requestToolMap:t};let p={...e,tools:l};return this.toolsConfig.toolSearch?.enabled&&i&&(p=this.injectToolSearchPrompt(p)),{request:this.injectRequestToolGuidance(p,l),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(l=>l.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 l=["Knowledge Base:"];o.has("knowledge_search")&&l.push("- Use `knowledge_search` when you need factual or domain-specific information that may already be stored."),o.has("knowledge_add")&&l.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(l.join(`
408
+ - Only ask the user for clarification when you genuinely cannot determine their intent or lack the required tools`}c();var kt=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)}};c();var Ar=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 l=e[a];this.hasDependency(n,l,i)&&s.push(l.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(f=>f.toolCallId===p.id)?.dependsOn.every(f=>i.has(f))??!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 l=await this.executeBatchWithLimit(a,t,o);for(let{id:p,result:m}of l)s.set(p,m),i.add(p)}return s}async executeBatchWithLimit(e,t,o){let n=async i=>(await Promise.allSettled(i.map(async l=>({id:l.id,result:await t(l)})))).map((l,p)=>l.status==="fulfilled"?l.value:{id:i[p].id,result:JSON.stringify({error:l.reason?.message??"Tool execution failed"})});if(e.length<=o)return n(e);let s=[];for(let i=0;i<e.length;i+=o)s.push(...await n(e.slice(i,i+o)));return s}shouldUseParallelExecution(e){return e.length>=2}};c();function st(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(`
409
+ `):""}return""}k();var Bl=0;function zl(){return Bl+=1,`${Date.now()}-${Bl}`}function Nr(r,e){it("debug")&&(h(`[AIClient][${r}] Messages (${e.length}):`),e.forEach((t,o)=>{let n=O(t.content,300);h(`[AIClient][${r}] #${o} role=${t.role} content=${n}`)}))}function Hl(r){let e=st(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 Kl(r){let e=st(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 kn=class extends Jl.EventEmitter{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||oe,this.toolRouter=new St,this.bm25Engine=new Ct,this.queryClassifier=new kt,this.toolOrchestrator=new Ar,this.overrideSystemPrompt=e.systemPrompt,this.disableBaseContext=e.disableBaseContext||!1;let t=this.toolsConfig.resultMaxChars??oe.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=Ws(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:Os(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 l=a-o,p=Is(s.messages,l,n),m=new Set(p.pruneInfo.removedMessages),d=s.messages.filter(y=>!m.has(y)),f={...s,messages:d};if(this.contextWindowStateManager&&this.contextWindowStateManager.recordPruneOperation(this.getConversationId(),p.tokensReclaimed),await this.countRequestTokens(f,t,f.model)<=o||d.length===s.messages.length)return f;s=f}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((l,p)=>{o&&l.role==="system"||l.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((l,p)=>!i.has(p));return{...e,messages:a}}async summarizeConversation(e,t){let o=e.messages,n=o.filter(x=>x.role==="system"),s=o.filter(x=>x.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 l=this.contextWindowConfig?.summarizerModel||e.model,p=Fs(a,{model:l,maxSummaryTokens:500}),m=await t.generate({model:l,messages:p,max_tokens:500,temperature:0,response_format:"text"});if(!m.content)throw new wn("Summarization provider returned no summary",this.getConversationId(),a.length,"invalid_response");let d=await this.countRequestTokens({...e,messages:a},t,l),f=qs(m.content,a,d),b=js(f);if(!b.valid)throw new wn(`Summarization result is invalid: ${b.issues.join("; ")}`,this.getConversationId(),a.length,"invalid_quality",m.content);let y=Dr(f.summary,a.length),w=[...n,y,...i];return this.contextWindowStateManager&&this.contextWindowStateManager.recordSummarization(this.getConversationId(),f.tokensSaved),{...e,messages:w}}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,l=As(i,a),p=Math.max(0,s-l),m=Math.floor(s*((this.contextWindowConfig.pruneThreshold??85)/100)),d=Math.min(p,m),f=await this.countRequestTokens(o,t,o.model);if(this.contextWindowStateManager&&(this.contextWindowStateManager.updateTokenCount(this.getConversationId(),f),f>d&&this.contextWindowStateManager.recordWarning(this.getConversationId())),f<=d)return o;let b=this.contextWindowConfig.strategy??"prune";if(b==="fail"&&f>p)throw new bn("Context window exceeded by request messages",this.getConversationId(),f,p,b);if(b==="summarize")try{let w=await this.summarizeConversation(o,t);if(await this.countRequestTokens(w,t,w.model)<=p)return w;o=await this.pruneConversation(w,t,p)}catch{o=await this.pruneConversation(o,t,p)}else o=await this.pruneConversation(o,t,p);let y=await this.countRequestTokens(o,t,o.model);if(y>p&&b==="fail")throw new bn("Context window exceeded after attempted cleanup",this.getConversationId(),y,p,b);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=zl(),s=this.injectBaseAgentContext(e);s=this.injectOverrideSystemPrompt(s),s=this.injectModeSystemPrompt(s);let i=t||this.defaultProvider,a=await this.enrichRequestWithTools(s),l=a.request,p=a.requestToolMap;l=await this.enforceContextWindow(l,o);let m=process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||this.toolsConfig.toolChoicePolicy||"auto",d=(l.tools?.length||0)>0,f=l.tool_choice!=null,b=Hl(l.messages),y=Kl(l.messages);!f&&d&&(m==="required"||m==="required_for_actions"&&b)&&(l.tool_choice="required");let x=o?.constructor?.name||"UnknownProvider",C=this.activeMode?.response_format,v={...this.stripRequestTools(l),__toolpack_request_id:n,...C?{response_format:C}:{}};P(`[AIClient][${n}] generate() start provider=${i} class=${x} model=${l.model} messages=${l.messages.length} tools=${l.tools?.length||0} tool_choice=${l.tool_choice??"unset"} policy=${m} needsTools=${b} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),Nr(n,l.messages);let $=M=>Dl(()=>o.generate(M),{onRetry:(_,D)=>P(`[AIClient][${n}] Rate limited \u2014 retrying in ${D/1e3}s (attempt ${_}/3)`)}),S=await $(v);if(h(`[AIClient][${n}] generate() initial response finish_reason=${S.finish_reason??"unknown"} tool_calls=${S.tool_calls?.length||0} content_preview=${O(S.content||"",200)}`),this.toolsConfig.autoExecute&&(this.toolRegistry||p.size>0)){let M=st(l.messages),_=this.queryClassifier.classify(M),D=this.toolsConfig.maxToolRounds,R=l.maxToolRounds!==void 0?l.maxToolRounds:this.queryClassifier.getToolRoundsAdjustment(_,D);l.maxToolRounds!==void 0?h(`[AIClient][${n}] maxToolRounds overridden per-request: ${R} (classifier bypassed)`):R!==D?P(`[AIClient][${n}] Query classified as ${_.type} (confidence: ${_.confidence.toFixed(2)}), adjusted maxToolRounds: ${D} \u2192 ${R}`):h(`[AIClient][${n}] Query classified as ${_.type} (confidence: ${_.confidence.toFixed(2)}), keeping maxToolRounds: ${R}`);let W=0,z=[...l.messages];for(S.tool_calls&&S.tool_calls.length>0&&P(`[AIClient] Received ${S.tool_calls.length} tool call(s): ${S.tool_calls.map(wt=>wt.name).join(", ")}`);S.tool_calls&&S.tool_calls.length>0&&W<R;){W++,this.currentRound=W,P(`[AIClient][${n}] generate() tool round ${W}/${R} tool_calls=${S.tool_calls.length}`),z.push({role:"assistant",content:S.content||"",tool_calls:S.tool_calls.map(K=>({id:K.id,type:"function",function:{name:K.name,arguments:JSON.stringify(K.arguments)}}))});let wt=this.toolOrchestrator.shouldUseParallelExecution(S.tool_calls),Tt=3,ie=S.tool_calls,De=S.tool_calls.filter(K=>K.name==="web.fetch");if(De.length>Tt){P(`[AIClient][${n}] Limiting web.fetch calls from ${De.length} \u2192 ${Tt} to prevent context overflow`);let K=De.slice(0,Tt);ie=[...S.tool_calls.filter(xe=>xe.name!=="web.fetch"),...K];let Q=De.slice(Tt);for(let xe of Q)z.push({role:"tool",tool_call_id:xe.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let ee=5e4,fe=0;if(wt){P(`[AIClient][${n}] Using parallel execution for ${ie.length} tools`);let K;try{K=await this.toolOrchestrator.executeWithDependencies(ie,U=>this.executeTool(U,p),5)}catch(U){me(`[AIClient][${n}] Parallel tool execution failed: ${U.message}`),K=new Map(ie.map(Q=>[Q.id,JSON.stringify({error:U.message??"Tool execution failed"})]))}for(let U of ie){let Q=K.get(U.id)??JSON.stringify({error:"Tool execution result missing"}),xe=typeof Q=="string"?Q:JSON.stringify(Q),ae=ee-fe,te;fe+xe.length>ee?(L(`[AIClient][${n}] Tool output budget exceeded (${ee} chars)`),te=this.budgetTruncate(xe,ae)):typeof Q=="string"&&Q.length>this.toolResultMaxChars?te=`${Q.slice(0,this.toolResultMaxChars)}
410
+ [TRUNCATED tool result: ${Q.length} chars]`:te=xe;let E=typeof te=="string"?te:JSON.stringify(te);fe+=E.length,z.push({role:"tool",tool_call_id:U.id,content:te})}h(`[AIClient][${n}] Round tool output size: ${fe} chars (budget: ${ee})`)}else{P(`[AIClient][${n}] Using sequential execution for ${ie.length} tools`);for(let K of ie){let U;try{U=await this.executeTool(K,p)}catch(E){U=JSON.stringify({error:E.message??"Tool execution failed"})}let Q=typeof U=="string"?U:JSON.stringify(U),xe=ee-fe,ae;fe+Q.length>ee?(L(`[AIClient][${n}] Tool output budget exceeded (${ee} chars)`),ae=this.budgetTruncate(Q,xe)):typeof U=="string"&&U.length>this.toolResultMaxChars?ae=`${U.slice(0,this.toolResultMaxChars)}
411
+ [TRUNCATED tool result: ${U.length} chars]`:ae=Q;let te=typeof ae=="string"?ae:JSON.stringify(ae);fe+=te.length,z.push({role:"tool",tool_call_id:K.id,content:ae})}h(`[AIClient][${n}] Round tool output size: ${fe} chars (budget: ${ee})`)}let xt={...l,messages:z,__toolpack_request_id:n,...C?{response_format:C}:{}},Te=this.stripRequestTools((await this.enrichRequestWithTools(xt)).request);Te=await this.enforceContextWindow(Te,o),Te.tool_choice==="required"&&(Te.tool_choice=y?"none":"auto",P(`[AIClient][${n}] generate() followup tool_choice override required->${Te.tool_choice}`)),it("debug")&&(h(`[AIClient][${n}] generate() followup request messages=${z.length}`),Nr(n,z)),S=await $(Te),h(`[AIClient][${n}] generate() followup response finish_reason=${S.finish_reason??"unknown"} tool_calls=${S.tool_calls?.length||0} content_preview=${O(S.content||"",200)}`)}}return S.data===void 0&&S.content&&e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format&&(S.data=e.response_format.parse(JSON.parse(S.content))),S}catch(n){throw this.wrapError(n)}}async*stream(e,t){let o=this.getProvider(t);try{let n=zl(),s=t||this.defaultProvider,i=this.injectBaseAgentContext(e);i=this.injectOverrideSystemPrompt(i),i=this.injectModeSystemPrompt(i);let a=await this.enrichRequestWithTools(i),l=a.request,p=a.requestToolMap;l=await this.enforceContextWindow(l,o);let m=process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||this.toolsConfig.toolChoicePolicy||"auto",d=(l.tools?.length||0)>0,f=l.tool_choice!=null,b=Hl(l.messages),y=Kl(l.messages);!f&&d&&(m==="required"||m==="required_for_actions"&&b)&&(l.tool_choice="required");let x=o?.constructor?.name||"UnknownProvider",C=this.activeMode?.response_format,v={...this.stripRequestTools(l),__toolpack_request_id:n,...C?{response_format:C}:{}};if(P(`[AIClient][${n}] stream() start provider=${s} class=${x} model=${l.model} messages=${l.messages.length} tools=${l.tools?.length||0} tool_choice=${l.tool_choice??"unset"} policy=${m} needsTools=${b} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),Nr(n,l.messages),!this.toolsConfig.autoExecute||!this.toolRegistry&&p.size===0){yield*o.stream(v);return}let $=[...l.messages],S=0,M=st(l.messages),_=this.queryClassifier.classify(M),D=this.toolsConfig.maxToolRounds,R=l.maxToolRounds!==void 0?l.maxToolRounds:this.queryClassifier.getToolRoundsAdjustment(_,D);for(l.maxToolRounds!==void 0?h(`[AIClient][${n}] stream() maxToolRounds overridden per-request: ${R} (classifier bypassed)`):R!==D&&P(`[AIClient][${n}] stream() Query classified as ${_.type} (confidence: ${_.confidence.toFixed(2)}), adjusted maxToolRounds: ${D} \u2192 ${R}`);S<=R;){if(e.signal?.aborted){P(`[AIClient][${n}] stream() aborted by signal`);return}let W="",z=[];S++,this.currentRound=S,P(`[AIClient][${n}] stream() round_start ${S}/${R}`);let wt=null,Tt={...l,messages:$,...C?{response_format:C}:{}},ie=this.stripRequestTools((await this.enrichRequestWithTools(Tt)).request);ie=await this.enforceContextWindow(ie,o),S>1&&ie.tool_choice==="required"&&(ie.tool_choice=y?"none":"auto",P(`[AIClient][${n}] stream() round_${S} tool_choice override required->${ie.tool_choice}`));for await(let E of o.stream(ie)){if(e.signal?.aborted){P(`[AIClient][${n}] stream() aborted by signal during chunk processing`);return}E.tool_calls&&E.tool_calls.length>0&&(z.push(...E.tool_calls),h(`[AIClient][${n}] stream() tool_calls_chunk count=${E.tool_calls.length} names=${E.tool_calls.map(le=>le.name).join(", ")}`),yield E),E.delta&&(W+=E.delta,yield E),E.finish_reason&&(wt=E.finish_reason),E.finish_reason==="stop"&&(yield E)}if(h(`[AIClient][${n}] stream() round_end finish_reason=${wt??"unknown"} accumulated_len=${W.length} tool_calls_total=${z.length} content_preview=${O(W,200)}`),z.length===0)break;P(`[AIClient][${n}] stream() received ${z.length} tool call(s): ${z.map(E=>E.name).join(", ")}`),P(`[AIClient][${n}] stream() tool round ${S}/${R}`),$.push({role:"assistant",content:W||"",tool_calls:z.map(E=>({id:E.id,type:"function",function:{name:E.name,arguments:JSON.stringify(E.arguments)}}))});let De=3,ee=z,fe=z.filter(E=>E.name==="web.fetch");if(fe.length>De){P(`[AIClient][${n}] Limiting web.fetch calls from ${fe.length} \u2192 ${De} to prevent context overflow`);let E=fe.slice(0,De);ee=[...z.filter(yn=>yn.name!=="web.fetch"),...E];let Me=fe.slice(De);for(let yn of Me)$.push({role:"tool",tool_call_id:yn.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let xt=5e4,Te=0,K=[],U=!1,Q=setInterval(()=>{U||K.push({delta:""})},500),xe=Date.now(),ae,te;try{if(ee.length>=2)P(`[AIClient][${n}] stream() using parallel execution for ${ee.length} tools`),te=new Map,ae=await this.toolOrchestrator.executeWithDependencies(ee,async E=>{let le=Date.now(),Me=await this.executeTool(E,p);return te.set(E.id,Date.now()-le),Me},5);else{P(`[AIClient][${n}] stream() executing single tool sequentially`),te=new Map,ae=new Map;for(let E of ee){let le=Date.now(),Me=await this.executeTool(E,p);te.set(E.id,Date.now()-le),ae.set(E.id,Me)}}}finally{U=!0,clearInterval(Q)}for(;K.length>0;)yield K.shift();await new Promise(E=>setTimeout(E,0)),h(`[AIClient][${n}] stream() tool batch completed in ${Date.now()-xe}ms`);for(let E of ee){let le=ae.get(E.id),Me=typeof le=="string"?le:JSON.stringify(le),yn=xt-Te,tx=te.get(E.id)??0,tt;Te+Me.length>xt?(L(`[AIClient][${n}] Tool output budget exceeded (${xt} chars)`),tt=this.budgetTruncate(Me,yn)):typeof le=="string"&&le.length>this.toolResultMaxChars?tt=`${le.slice(0,this.toolResultMaxChars)}
412
+ [TRUNCATED tool result: ${le.length} chars]`:tt=Me;let $l=typeof tt=="string"?tt:JSON.stringify(tt);Te+=$l.length,$.push({role:"tool",tool_call_id:E.id,content:tt}),yield{delta:"",tool_calls:[{...E,result:$l,duration:tx}]}}h(`[AIClient][${n}] Round tool output size: ${Te} chars (budget: ${xt})`),it("debug")&&(h(`[AIClient][${n}] stream() after_tools messages=${$.length}`),Nr(n,$))}}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 h("[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}:{}}},h(`[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){h(`[AIClient] Request already has ${e.tools.length} tools`);let y=this.mergeToolCallRequests(e.tools,this.schemasToToolCallRequests(o)),w=y===e.tools?e:{...e,tools:y};return{request:this.injectRequestToolGuidance(w,y),requestToolMap:t}}let m=await this.toolRouter.resolve(e.messages,this.toolRegistry,s);if(h(`[AIClient] Resolved ${m.length} tools to send: ${m.map(y=>y.name).join(", ")||"none"}`),this.activeMode&&m.length>0){let y=m.length;m=this.filterSchemasByMode(m,this.activeMode);let w=y-m.length;w>0&&P(`[AIClient] Mode "${this.activeMode.displayName}" filtered out ${w} tools`)}let d=new Set(e.tools.map(y=>y.function.name)),f=m.filter(y=>!d.has(y.name)).map(y=>({type:"function",function:{name:y.name,description:y.description,parameters:y.parameters}}));if(f.length===0){h(`[AIClient] Request already has ${e.tools.length} tools (no new discoveries)`);let y=this.mergeToolCallRequests(e.tools,this.schemasToToolCallRequests(o)),w=y===e.tools?e:{...e,tools:y};return{request:this.injectRequestToolGuidance(w,y),requestToolMap:t}}let b={...e,tools:this.mergeToolCallRequests([...e.tools,...f],this.schemasToToolCallRequests(o))};return s.toolSearch?.enabled&&this.toolRegistry&&(b=this.injectToolSearchPrompt(b)),{request:this.injectRequestToolGuidance(b,b.tools),requestToolMap:t}}if(!this.toolRegistry){h("[AIClient] Tool registry not configured, skipping tool resolution");let m=this.schemasToToolCallRequests(o),d=m.length>0?{...e,tools:m}:e;return{request:this.injectRequestToolGuidance(d,m),requestToolMap:t}}let i=this.toolRegistry,a=await this.toolRouter.resolve(e.messages,i,s);if(h(`[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 d=m-a.length;d>0&&P(`[AIClient] Mode "${this.activeMode.displayName}" filtered out ${d} tools`)}let l=this.schemasToToolCallRequests(this.mergeSchemas(a,o));if(l.length===0)return{request:e,requestToolMap:t};let p={...e,tools:l};return this.toolsConfig.toolSearch?.enabled&&i&&(p=this.injectToolSearchPrompt(p)),{request:this.injectRequestToolGuidance(p,l),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(l=>l.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 l=["Knowledge Base:"];o.has("knowledge_search")&&l.push("- Use `knowledge_search` when you need factual or domain-specific information that may already be stored."),o.has("knowledge_add")&&l.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(l.join(`
404
413
  `))}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
414
  ${s.join(`
406
415
 
407
- `)}`,a=e.messages.findIndex(l=>l.role==="system");if(a>=0){let l=e.messages.map((p,m)=>{if(m!==a)return p;let u=typeof p.content=="string"?p.content:"";return u.includes(n)?p:{...p,content:`${u}
416
+ `)}`,a=e.messages.findIndex(l=>l.role==="system");if(a>=0){let l=e.messages.map((p,m)=>{if(m!==a)return p;let d=typeof p.content=="string"?p.content:"";return d.includes(n)?p:{...p,content:`${d}
408
417
 
409
- ${i}`.trim()}});return{...e,messages:l}}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(fn(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 h(`[AIClient] injectModeSystemPrompt: No active mode or empty systemPrompt. activeMode=${this.activeMode?.name}, systemPrompt=${this.activeMode?.systemPrompt?.substring(0,50)}`),e;let t=this.activeMode.systemPrompt;if(h(`[AIClient] injectModeSystemPrompt: Injecting mode prompt for ${this.activeMode.name}, length=${t.length}`),e.messages.some(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}
418
+ ${i}`.trim()}});return{...e,messages:l}}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(rt(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 h(`[AIClient] injectModeSystemPrompt: No active mode or empty systemPrompt. activeMode=${this.activeMode?.name}, systemPrompt=${this.activeMode?.systemPrompt?.substring(0,50)}`),e;let t=this.activeMode.systemPrompt;if(h(`[AIClient] injectModeSystemPrompt: Injecting mode prompt for ${this.activeMode.name}, length=${t.length}`),e.messages.some(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}
410
419
 
411
420
  ${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}
412
421
 
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||Tl({workingDirectory:process.cwd(),toolCategories:this.toolRegistry?this.toolRegistry.getCategories():[],disabled:s,includeWorkingDirectory:t,includeToolCategories:o});if(!i)return e;if(e.messages.some(l=>l.role==="system")){let l=e.messages.map(p=>{if(p.role==="system"){let m=typeof p.content=="string"?p.content:"";return{...p,content:`${i}
422
+ ${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||ql({workingDirectory:process.cwd(),toolCategories:this.toolRegistry?this.toolRegistry.getCategories():[],disabled:s,includeWorkingDirectory:t,includeToolCategories:o});if(!i)return e;if(e.messages.some(l=>l.role==="system")){let l=e.messages.map(p=>{if(p.role==="system"){let m=typeof p.content=="string"?p.content:"";return{...p,content:`${i}
414
423
 
415
424
  ${m}`}}return p});return{...e,messages:l}}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 l=this.toolRegistry?.get(a);return l?` - **${l.name}**: ${l.description}`:null}).filter(Boolean).join(`
416
425
  `);i&&(n=`
@@ -423,7 +432,7 @@ IMPORTANT: Tool Discovery Instructions
423
432
 
424
433
  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}
425
434
 
426
- ${yr(this.toolRegistry)}
435
+ ${Or(this.toolRegistry)}
427
436
 
428
437
  When you need a tool:
429
438
  1. Check if it's in your current tool list
@@ -433,11 +442,11 @@ When you need a tool:
433
442
  NEVER guess or hallucinate tool names. ALWAYS use tool.search to discover tools you don't have.
434
443
  `.trim();if(t){let i=e.messages.map(a=>{if(a.role==="system"){let l=typeof a.content=="string"?a.content:"";return{...a,content:`${l}
435
444
 
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}),S(`[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(fn(e.name)){let a=this.executeToolSearch(e.arguments),l=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:l}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:a,duration:l,status:"success",timestamp:Date.now()}),a}let i=n||s;if(!i){L(`[AIClient] Tool '${e.name}' not found in registry`);let a=this.findSimilarToolName(e.name),l=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:l,duration:Date.now()-o}),JSON.stringify({error:l})}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 f=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:f}),f.action==="deny"){let b=`[Execution denied by user${f.reason?": "+f.reason:""}]`,y=Date.now()-o;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:b,duration:y}),this.emit("tool:log",{id:e.id,name:e.name,arguments:a,result:b,duration:y,status:"success",timestamp:Date.now()}),b}f.action==="modify"&&(a=f.args)}let l={workspaceRoot:process.cwd(),config:this.toolsConfig?.additionalConfigurations??{},log:f=>S(`[Tool] ${f}`)},p=n?await n.execute(a):await i.execute(a,l),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 u=typeof p=="string"?p.length:JSON.stringify(p).length;return S(`[AIClient] Tool ${e.name} executed successfully in ${m}ms result_len=${u}`),ot("debug")&&h(`[AIClient] Tool ${e.name} result_preview=${O(p,400)}`),typeof p=="string"?p:JSON.stringify(p)}catch(a){let l=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:l}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:JSON.stringify({error:p}),duration:l,status:"error",timestamp:Date.now()}),me(`[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(l=>l.name===o))return o;let n=e.replace(/\./g,"_");if(t.some(l=>l.name===n))return n;let s=e.replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase().replace(/_/g,".");if(t.some(l=>l.name===s))return s;let i=null,a=1/0;for(let l of t){let p=this.levenshteinDistance(e.toLowerCase(),l.name.toLowerCase());p<=2&&p<a&&(a=p,i=l.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([xt()],this.activeMode).length>0))return L("[AIClient] tool.search blocked by active mode"),JSON.stringify({query:t,found:0,tools:[],hint:"tool.search is not allowed in the current mode."});S(`[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(b=>b.tool),this.activeMode),m=new Set(p.map(b=>b.name)),u=a.length;a=a.filter(b=>m.has(b.toolName));let f=u-a.length;f>0&&h(`[AIClient] tool.search filtered out ${f} disallowed results for mode "${this.activeMode.displayName}"`)}a.length>n&&(a=a.slice(0,n));let l=a.map(p=>p.toolName);return this.toolRouter.getDiscoveryCache().recordDiscovery(t,l),h(`[AIClient] tool.search found ${a.length} tools: ${l.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 N?e:new j(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.]"}};c();c();var Gs=T(require("@anthropic-ai/sdk"),1);c();pe();var X=class{name;async getModels(){return[]}getDisplayName(){return this.name||this.constructor.name.replace(/Adapter$/,"")}supportsFileUpload(){return!1}async uploadFile(e){throw new I(`File upload API is not supported by ${this.getDisplayName()}`)}async deleteFile(e){throw new I(`File deletion API is not supported by ${this.getDisplayName()}`)}async countTokens(e,t){return null}};pe();k();var xn=class extends X{client;constructor(e,t){super(),this.client=new Gs.default({apiKey:e,baseURL:t})}supportsFileUpload(){return!0}async uploadFile(e){try{let t=await import("fs");if(!e.filePath)throw new I("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"},h(`[Anthropic][${t}] Sending ${i.tools?.length||0} tools with tool_choice: ${i.tool_choice?.type||"unset"}`),i.tools&&i.tools.length>0&&h(`[Anthropic][${t}] First tool: ${O(i.tools[0],800)}`)):h(`[Anthropic][${t}] NO TOOLS in request`),h(`[Anthropic][${t}] generate() request: model=${i.model}, messages=${i.messages.length}, tools=${i.tools?.length||0}, tool_choice=${i.tool_choice?.type??"unset"}`),oe(t,"Anthropic",i.messages);let a=await this.client.messages.create(i,e.signal?{signal:e.signal}:void 0),l=[],p=[];for(let m of a.content)m.type==="text"?l.push(m.text):m.type==="tool_use"&&p.push({id:m.id,name:this.restoreToolName(m.name,e.tools),arguments:m.input});return h(`[Anthropic][${t}] Response finish_reason=${a.stop_reason} tool_calls=${p.length} content_preview=${O(l.join(""),200)}`),{content:l.length>0?l.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"},h(`[Anthropic][${t}] Sending ${n.tools?.length||0} tools with tool_choice: ${n.tool_choice?.type||"unset"}`),n.tools&&n.tools.length>0&&h(`[Anthropic][${t}] First tool: ${O(n.tools[0],800)}`)):h(`[Anthropic][${t}] NO TOOLS in request`),h(`[Anthropic][${t}] Stream request: model=${n.model}, messages=${n.messages.length}, tools=${n.tools?.length||0}, tool_choice=${n.tool_choice?.type??"unset"}`),oe(t,"Anthropic",n.messages);let s=await this.client.messages.create(n,e.signal?{signal:e.signal}:void 0),i="",a="",l="",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,l=""),m.type==="content_block_delta"&&(m.delta.type==="text_delta"?yield{delta:m.delta.text}:m.delta.type==="input_json_delta"&&p&&(l+=m.delta.partial_json)),m.type==="content_block_stop"&&p&&(h(`[Anthropic][${t}] Stream finish_reason=tool_calls accumulated_call=${a}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:i,name:this.restoreToolName(a,e.tools),arguments:JSON.parse(l||"{}")}]},p=!1),m.type==="message_stop"&&(je(`[Anthropic][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"})}catch(t){throw this.handleError(t)}}async embed(e){throw new I("Embeddings are not strictly supported by the Anthropic API currently.")}async toAnthropicMessages(e,t={}){let o,n=[],{normalizeImagePart:s}=await Promise.resolve().then(()=>(kt(),Tn));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(l=>typeof l=="object"&&l.type==="text").map(l=>l.text).join(`
445
+ ${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(rt(e.name)){let a=this.executeToolSearch(e.arguments),l=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:l}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:a,duration:l,status:"success",timestamp:Date.now()}),a}let i=n||s;if(!i){L(`[AIClient] Tool '${e.name}' not found in registry`);let a=this.findSimilarToolName(e.name),l=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:l,duration:Date.now()-o}),JSON.stringify({error:l})}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 f=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:f}),f.action==="deny"){let b=`[Execution denied by user${f.reason?": "+f.reason:""}]`,y=Date.now()-o;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:b,duration:y}),this.emit("tool:log",{id:e.id,name:e.name,arguments:a,result:b,duration:y,status:"success",timestamp:Date.now()}),b}f.action==="modify"&&(a=f.args)}let l={workspaceRoot:process.cwd(),config:this.toolsConfig?.additionalConfigurations??{},log:f=>P(`[Tool] ${f}`)},p=n?await n.execute(a):await i.execute(a,l),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 d=typeof p=="string"?p.length:JSON.stringify(p).length;return P(`[AIClient] Tool ${e.name} executed successfully in ${m}ms result_len=${d}`),it("debug")&&h(`[AIClient] Tool ${e.name} result_preview=${O(p,400)}`),typeof p=="string"?p:JSON.stringify(p)}catch(a){let l=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:l}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:JSON.stringify({error:p}),duration:l,status:"error",timestamp:Date.now()}),me(`[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(l=>l.name===o))return o;let n=e.replace(/\./g,"_");if(t.some(l=>l.name===n))return n;let s=e.replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase().replace(/_/g,".");if(t.some(l=>l.name===s))return s;let i=null,a=1/0;for(let l of t){let p=this.levenshteinDistance(e.toLowerCase(),l.name.toLowerCase());p<=2&&p<a&&(a=p,i=l.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([Fe()],this.activeMode).length>0))return L("[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(b=>b.tool),this.activeMode),m=new Set(p.map(b=>b.name)),d=a.length;a=a.filter(b=>m.has(b.toolName));let f=d-a.length;f>0&&h(`[AIClient] tool.search filtered out ${f} disallowed results for mode "${this.activeMode.displayName}"`)}a.length>n&&(a=a.slice(0,n));let l=a.map(p=>p.toolName);return this.toolRouter.getDiscoveryCache().recordDiscovery(t,l),h(`[AIClient] tool.search found ${a.length} tools: ${l.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 j(e.message||"Unknown provider error","UNKNOWN_PROVIDER_ERROR",500,e)}budgetTruncate(e,t){let o=`
446
+ [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.]"}};c();c();var Vs=T(require("@anthropic-ai/sdk"),1),Zl=require("@anthropic-ai/sdk/helpers/zod");c();pe();var Y=class{name;async getModels(){return[]}getDisplayName(){return this.name||this.constructor.name.replace(/Adapter$/,"")}supportsFileUpload(){return!1}async uploadFile(e){throw new I(`File upload API is not supported by ${this.getDisplayName()}`)}async deleteFile(e){throw new I(`File deletion API is not supported by ${this.getDisplayName()}`)}async countTokens(e,t){return null}};pe();k();var _n=class extends Y{client;constructor(e,t){super(),this.client=new Vs.default({apiKey:e,baseURL:t})}supportsFileUpload(){return!0}async uploadFile(e){try{let t=await import("fs");if(!e.filePath)throw new I("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(b=>({name:this.sanitizeToolName(b.function.name),description:b.function.description,input_schema:b.function.parameters})),e.tool_choice==="required"?i.tool_choice={type:"any"}:e.tool_choice==="none"?delete i.tools:i.tool_choice={type:"auto"},h(`[Anthropic][${t}] Sending ${i.tools?.length||0} tools with tool_choice: ${i.tool_choice?.type||"unset"}`),i.tools&&i.tools.length>0&&h(`[Anthropic][${t}] First tool: ${O(i.tools[0],800)}`)):h(`[Anthropic][${t}] NO TOOLS in request`),h(`[Anthropic][${t}] generate() request: model=${i.model}, messages=${i.messages.length}, tools=${i.tools?.length||0}, tool_choice=${i.tool_choice?.type??"unset"}`),ne(t,"Anthropic",i.messages);let a=e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format;a&&(i.output_config={format:(0,Zl.zodOutputFormat)(e.response_format)});let p=a?await this.client.messages.parse(i,e.signal?{signal:e.signal}:void 0):await this.client.messages.create(i,e.signal?{signal:e.signal}:void 0),m=[],d=[];for(let b of p.content)b.type==="text"?m.push(b.text):b.type==="tool_use"&&d.push({id:b.id,name:this.restoreToolName(b.name,e.tools),arguments:b.input});h(`[Anthropic][${t}] Response finish_reason=${p.stop_reason} tool_calls=${d.length} content_preview=${O(m.join(""),200)}`);let f={content:m.length>0?m.join(""):null,usage:{prompt_tokens:p.usage.input_tokens,completion_tokens:p.usage.output_tokens,total_tokens:p.usage.input_tokens+p.usage.output_tokens},finish_reason:this.mapFinishReason(p.stop_reason),tool_calls:d.length>0?d:void 0,raw:p};return a&&p.parsed_output!==void 0&&(f.data=p.parsed_output),f}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"},h(`[Anthropic][${t}] Sending ${n.tools?.length||0} tools with tool_choice: ${n.tool_choice?.type||"unset"}`),n.tools&&n.tools.length>0&&h(`[Anthropic][${t}] First tool: ${O(n.tools[0],800)}`)):h(`[Anthropic][${t}] NO TOOLS in request`),h(`[Anthropic][${t}] Stream request: model=${n.model}, messages=${n.messages.length}, tools=${n.tools?.length||0}, tool_choice=${n.tool_choice?.type??"unset"}`),ne(t,"Anthropic",n.messages);let s=await this.client.messages.create(n,e.signal?{signal:e.signal}:void 0),i="",a="",l="",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,l=""),m.type==="content_block_delta"&&(m.delta.type==="text_delta"?yield{delta:m.delta.text}:m.delta.type==="input_json_delta"&&p&&(l+=m.delta.partial_json)),m.type==="content_block_stop"&&p&&(h(`[Anthropic][${t}] Stream finish_reason=tool_calls accumulated_call=${a}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:i,name:this.restoreToolName(a,e.tools),arguments:JSON.parse(l||"{}")}]},p=!1),m.type==="message_stop"&&(We(`[Anthropic][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"})}catch(t){throw this.handleError(t)}}async embed(e){throw new I("Embeddings are not strictly supported by the Anthropic API currently.")}async toAnthropicMessages(e,t={}){let o,n=[],{normalizeImagePart:s}=await Promise.resolve().then(()=>(_t(),Pn));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(l=>typeof l=="object"&&l.type==="text").map(l=>l.text).join(`
438
447
  `);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 l=i.content.filter(p=>typeof p=="object"&&p.type==="text").map(p=>p.text).join(`
439
- `);l&&a.push({type:"text",text:l})}for(let l of i.tool_calls)a.push({type:"tool_use",id:l.id,name:this.sanitizeToolName(l.function.name),input:typeof l.function.arguments=="string"?JSON.parse(l.function.arguments||"{}"):l.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 l=>{if(l.type==="text")return{type:"text",text:l.text};if(l.type==="image_url"){let p=l.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(l.type==="image_data"||l.type==="image_file"){let{data:p,mimeType:m}=await s(l);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 Gs.default.APIError){let t=e.message;return e.status===401?new he(t,e):e.status===429?new ce(t,void 0,e):e.status&&e.status>=400&&e.status<500?new I(t,e):new j(t,"ANTHROPIC_ERROR",e.status||500,e)}return new j("Unknown Anthropic error","UNKNOWN",500,e)}};c();var Ol=require("@google/genai");pe();k();var vn=class extends X{ai;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 he("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.ai=new Ol.GoogleGenAI({vertexai:!0,project:t,location:this.location,...e.googleAuthOptions?{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()}`;h(`[VertexAI][${t}] generate() model=${e.model} messages=${e.messages.length} tools=${e.tools?.length??0}`),oe(t,"VertexAI",e.messages);let{model:o,config:n}=this.buildRequestParams(e),{history:s,lastUserMessage:i}=this.formatHistory(e.messages),a=[...s,{role:"user",parts:typeof i=="string"?[{text:i}]:i}],l=await this.ai.models.generateContent({model:o,contents:a,config:n}),{content:p,toolCalls:m}=this.parseResponse(l,e.tools);return h(`[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:l.usageMetadata?.promptTokenCount??0,completion_tokens:l.usageMetadata?.candidatesTokenCount??0,total_tokens:l.usageMetadata?.totalTokenCount??0},finish_reason:m.length>0?"tool_calls":"stop",tool_calls:m.length>0?m:void 0,raw:l}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`vtx-str-${Date.now()}`;h(`[VertexAI][${t}] stream() model=${e.model} messages=${e.messages.length} tools=${e.tools?.length??0}`),oe(t,"VertexAI",e.messages);let{model:o,config:n}=this.buildRequestParams(e),{history:s,lastUserMessage:i}=this.formatHistory(e.messages),a=[...s,{role:"user",parts:typeof i=="string"?[{text:i}]:i}],l=await this.ai.models.generateContentStream({model:o,contents:a,config:n});for await(let p of l)for(let m of p.candidates??[])for(let u of m.content?.parts??[])if(u.functionCall){let f=u.functionCall;h(`[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 u.text&&(yield{delta:u.text})}catch(t){throw this.handleError(t)}}async embed(e){throw new I("Vertex AI embeddings are not supported by this adapter. Use the Gemini adapter (gemini provider) with text-embedding-004 instead.")}buildRequestParams(e){let t={systemInstruction:this.extractSystemInstruction(e.messages),maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:e.response_format==="json_object"&&!e.tools?.length?"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)}))}]),{model:e.model,config: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 l of i.tool_calls)a.push({functionCall:{name:this.sanitizeToolName(l.function.name),args:typeof l.function.arguments=="string"?JSON.parse(l.function.arguments||"{}"):l.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 ce(t,void 0,e):e?.status===401||e?.status===403||t.includes("UNAUTHENTICATED")||t.includes("PERMISSION_DENIED")?new he(t,e):e?.status>=400&&e?.status<500?new I(t,e):new j(t||"Vertex AI Error","VERTEXAI_ERROR",e?.status??500,e)}};c();var Nl=require("@google/generative-ai");pe();k();var Cn=class extends X{genAI;constructor(e){super(),this.genAI=new Nl.GoogleGenerativeAI(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 I("Gemini uploadFile requires a filePath.");let n=await t.promises.readFile(e.filePath),s=o.basename(e.filePath),i=e.mimeType||"application/octet-stream",l=`https://generativelanguage.googleapis.com/upload/v1beta/files?key=${this.genAI.apiKey}`,p="----WebKitFormBoundary"+Math.random().toString(36).substring(2),m=JSON.stringify({file:{displayName:s}}),u=Buffer.concat([Buffer.from(`--${p}\r
448
+ `);l&&a.push({type:"text",text:l})}for(let l of i.tool_calls)a.push({type:"tool_use",id:l.id,name:this.sanitizeToolName(l.function.name),input:typeof l.function.arguments=="string"?JSON.parse(l.function.arguments||"{}"):l.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 l=>{if(l.type==="text")return{type:"text",text:l.text};if(l.type==="image_url"){let p=l.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(l.type==="image_data"||l.type==="image_file"){let{data:p,mimeType:m}=await s(l);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 Vs.default.APIError){let t=e.message;return e.status===401?new he(t,e):e.status===429?new ce(t,void 0,e):e.status&&e.status>=400&&e.status<500?new I(t,e):new j(t,"ANTHROPIC_ERROR",e.status||500,e)}return new j("Unknown Anthropic error","UNKNOWN",500,e)}};c();var ec=require("@google/genai"),tc=require("zod-to-json-schema");pe();k();var Rn=class extends Y{ai;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 he("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.ai=new ec.GoogleGenAI({vertexai:!0,project:t,location:this.location,...e.googleAuthOptions?{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()}`;h(`[VertexAI][${t}] generate() model=${e.model} messages=${e.messages.length} tools=${e.tools?.length??0}`),ne(t,"VertexAI",e.messages);let{model:o,config:n}=this.buildRequestParams(e),{history:s,lastUserMessage:i}=this.formatHistory(e.messages),a=[...s,{role:"user",parts:typeof i=="string"?[{text:i}]:i}],l=await this.ai.models.generateContent({model:o,contents:a,config:n}),{content:p,toolCalls:m}=this.parseResponse(l,e.tools);return h(`[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:l.usageMetadata?.promptTokenCount??0,completion_tokens:l.usageMetadata?.candidatesTokenCount??0,total_tokens:l.usageMetadata?.totalTokenCount??0},finish_reason:m.length>0?"tool_calls":"stop",tool_calls:m.length>0?m:void 0,raw:l}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`vtx-str-${Date.now()}`;h(`[VertexAI][${t}] stream() model=${e.model} messages=${e.messages.length} tools=${e.tools?.length??0}`),ne(t,"VertexAI",e.messages);let{model:o,config:n}=this.buildRequestParams(e),{history:s,lastUserMessage:i}=this.formatHistory(e.messages),a=[...s,{role:"user",parts:typeof i=="string"?[{text:i}]:i}],l=await this.ai.models.generateContentStream({model:o,contents:a,config:n});for await(let p of l)for(let m of p.candidates??[])for(let d of m.content?.parts??[])if(d.functionCall){let f=d.functionCall;h(`[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 d.text&&(yield{delta:d.text})}catch(t){throw this.handleError(t)}}async embed(e){throw new I("Vertex AI embeddings are not supported by this adapter. Use the Gemini adapter (gemini provider) with text-embedding-004 instead.")}buildRequestParams(e){let t=e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format,o={systemInstruction:this.extractSystemInstruction(e.messages),maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:(e.response_format==="json_object"||t)&&!e.tools?.length?"application/json":"text/plain",...t&&!e.tools?.length?{responseSchema:this.sanitizeSchema((0,tc.zodToJsonSchema)(e.response_format))}:{}};return e.tools&&e.tools.length>0&&(o.tools=[{functionDeclarations:e.tools.map(n=>({name:this.sanitizeToolName(n.function.name),description:n.function.description,parameters:this.sanitizeSchema(n.function.parameters)}))}]),{model:e.model,config:o}}formatHistory(e){let t=e.filter(a=>a.role!=="system");if(t.length===0)return{history:[],lastUserMessage:""};let o=t.slice(0,-1),n=t[t.length-1],s=o.map(a=>{if(a.role==="tool"&&a.tool_call_id)return{role:"function",parts:[{functionResponse:{name:this.sanitizeToolName(a.name??a.tool_call_id),response:{name:this.sanitizeToolName(a.name??a.tool_call_id),content:typeof a.content=="string"?a.content:JSON.stringify(a.content)}}}]};if(a.role==="assistant"&&a.tool_calls&&a.tool_calls.length>0){let l=[];typeof a.content=="string"&&a.content&&l.push({text:a.content});for(let p of a.tool_calls)l.push({functionCall:{name:this.sanitizeToolName(p.function.name),args:typeof p.function.arguments=="string"?JSON.parse(p.function.arguments||"{}"):p.function.arguments}});return{role:"model",parts:l}}return{role:a.role==="user"?"user":"model",parts:this.contentToParts(a.content)}}),i=[];for(let a of s){let l=i[i.length-1];a.role==="function"&&l?.role==="function"?l.parts.push(...a.parts):i.push(a)}return{history:i,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(`
449
+ `)}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 ce(t,void 0,e):e?.status===401||e?.status===403||t.includes("UNAUTHENTICATED")||t.includes("PERMISSION_DENIED")?new he(t,e):e?.status>=400&&e?.status<500?new I(t,e):new j(t||"Vertex AI Error","VERTEXAI_ERROR",e?.status??500,e)}};c();var oc=require("@google/generative-ai"),Qs=require("zod-to-json-schema");pe();k();var $n=class extends Y{genAI;constructor(e){super(),this.genAI=new oc.GoogleGenerativeAI(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 I("Gemini uploadFile requires a filePath.");let n=await t.promises.readFile(e.filePath),s=o.basename(e.filePath),i=e.mimeType||"application/octet-stream",l=`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}}),d=Buffer.concat([Buffer.from(`--${p}\r
441
450
  Content-Type: application/json\r
442
451
  \r
443
452
  ${m}\r
@@ -446,32 +455,27 @@ Content-Type: ${i}\r
446
455
  \r
447
456
  `),n,Buffer.from(`\r
448
457
  --${p}--\r
449
- `)]),f=await fetch(l,{method:"POST",headers:{"Content-Type":`multipart/related; boundary=${p}`},body:u});if(!f.ok){let y=await f.text();throw new Error(`Gemini file upload failed: ${f.status} ${y}`)}let b=await f.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}`,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(f=>({name:this.sanitizeToolName(f.function.name),description:f.function.description,parameters:this.sanitizeSchema(f.function.parameters)}))}],h(`[Gemini][${t}] Sending ${e.tools.length} tools`),e.tools.length>0&&h(`[Gemini][${t}] First tool: ${O(e.tools[0],800)}`)):h(`[Gemini][${t}] NO TOOLS in request`),h(`[Gemini][${t}] generate() request: model=${e.model}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),oe(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"&&!e.tools?.length?"application/json":"text/plain"}}).sendMessage(i)).response,m=[],u="";for(let f of p.candidates||[])for(let b of f.content?.parts||[])if(b.text&&(u+=b.text),b.functionCall){let y=b.functionCall;m.push({id:`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(y.name,e.tools),arguments:y.args||{}})}return h(`[Gemini][${t}] Response finish_reason=${m.length>0?"tool_calls":"stop"} tool_calls=${m.length} content_preview=${O(u,200)}`),{content:u||null,usage:{prompt_tokens:p.usageMetadata?.promptTokenCount||0,completion_tokens:p.usageMetadata?.candidatesTokenCount||0,total_tokens:p.usageMetadata?.totalTokenCount||0},finish_reason:m.length>0?"tool_calls":"stop",tool_calls:m.length>0?m:void 0,raw:p}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t={model:e.model,systemInstruction:this.extractSystemInstruction(e.messages)};e.tools&&e.tools.length>0&&(t.tools=[{functionDeclarations:e.tools.map(p=>({name:this.sanitizeToolName(p.function.name),description:p.function.description,parameters:this.sanitizeSchema(p.function.parameters)}))}]);let o=e.__toolpack_request_id||`str-${Date.now()}`;h(`[Gemini][${o}] Stream request: model=${e.model}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),e.tools&&e.tools.length>0&&h(`[Gemini][${o}] First tool: ${O(e.tools[0],800)}`),oe(o,"Gemini",e.messages);let n=this.genAI.getGenerativeModel(t),{history:s,lastUserMessage:i}=await this.formatHistory(e.messages,e.mediaOptions),l=await n.startChat({history:s,generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:e.response_format==="json_object"&&!e.tools?.length?"application/json":"text/plain"}}).sendMessageStream(i);for await(let p of l.stream){for(let m of p.candidates?.[0]?.content?.parts||[])m.functionCall?(h(`[Gemini][${o}] Stream finish_reason=tool_calls name=${m.functionCall.name}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(m.functionCall.name,e.tools),arguments:m.functionCall.args||{}}]}):m.text&&(yield{delta:m.text});try{let m=p.text();m&&!p.candidates?.[0]?.content?.parts?.some(u=>u.text)&&(yield{delta:m})}catch{}}}catch(t){throw this.handleError(t)}}async embed(e){try{let t=this.genAI.getGenerativeModel({model:e.model});return Array.isArray(e.input)?{embeddings:await Promise.all(e.input.map(async 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(`
458
+ `)]),f=await fetch(l,{method:"POST",headers:{"Content-Type":`multipart/related; boundary=${p}`},body:d});if(!f.ok){let y=await f.text();throw new Error(`Gemini file upload failed: ${f.status} ${y}`)}let b=await f.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}`,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(f=>({name:this.sanitizeToolName(f.function.name),description:f.function.description,parameters:this.sanitizeSchema(f.function.parameters)}))}],h(`[Gemini][${t}] Sending ${e.tools.length} tools`),e.tools.length>0&&h(`[Gemini][${t}] First tool: ${O(e.tools[0],800)}`)):h(`[Gemini][${t}] NO TOOLS in request`),h(`[Gemini][${t}] generate() request: model=${e.model}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),ne(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"||e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format)&&!e.tools?.length?"application/json":"text/plain",...e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format&&!e.tools?.length?{responseSchema:this.sanitizeSchema((0,Qs.zodToJsonSchema)(e.response_format))}:{}}}).sendMessage(i)).response,m=[],d="";for(let f of p.candidates||[])for(let b of f.content?.parts||[])if(b.text&&(d+=b.text),b.functionCall){let y=b.functionCall;m.push({id:`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(y.name,e.tools),arguments:y.args||{}})}return h(`[Gemini][${t}] Response finish_reason=${m.length>0?"tool_calls":"stop"} tool_calls=${m.length} content_preview=${O(d,200)}`),{content:d||null,usage:{prompt_tokens:p.usageMetadata?.promptTokenCount||0,completion_tokens:p.usageMetadata?.candidatesTokenCount||0,total_tokens:p.usageMetadata?.totalTokenCount||0},finish_reason:m.length>0?"tool_calls":"stop",tool_calls:m.length>0?m:void 0,raw:p}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t={model:e.model,systemInstruction:this.extractSystemInstruction(e.messages)};e.tools&&e.tools.length>0&&(t.tools=[{functionDeclarations:e.tools.map(p=>({name:this.sanitizeToolName(p.function.name),description:p.function.description,parameters:this.sanitizeSchema(p.function.parameters)}))}]);let o=e.__toolpack_request_id||`str-${Date.now()}`;h(`[Gemini][${o}] Stream request: model=${e.model}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),e.tools&&e.tools.length>0&&h(`[Gemini][${o}] First tool: ${O(e.tools[0],800)}`),ne(o,"Gemini",e.messages);let n=this.genAI.getGenerativeModel(t),{history:s,lastUserMessage:i}=await this.formatHistory(e.messages,e.mediaOptions),l=await n.startChat({history:s,generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:(e.response_format==="json_object"||e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format)&&!e.tools?.length?"application/json":"text/plain",...e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format&&!e.tools?.length?{responseSchema:this.sanitizeSchema((0,Qs.zodToJsonSchema)(e.response_format))}:{}}}).sendMessageStream(i);for await(let p of l.stream){for(let m of p.candidates?.[0]?.content?.parts||[])m.functionCall?(h(`[Gemini][${o}] Stream finish_reason=tool_calls name=${m.functionCall.name}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(m.functionCall.name,e.tools),arguments:m.functionCall.args||{}}]}):m.text&&(yield{delta:m.text});try{let m=p.text();m&&!p.candidates?.[0]?.content?.parts?.some(d=>d.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(`
450
459
  `)).join(`
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(()=>(kt(),Tn)),a=async m=>typeof m=="string"?[{text:m}]:m===null?[]:(await Promise.all(m.map(async f=>{if(f.type==="text")return{text:f.text};if(f.type==="image_data"||f.type==="image_file"||f.type==="image_url")try{let{data:b,mimeType:y}=await i(f);return{inlineData:{mimeType:y,data:b}}}catch{return f.type==="image_url"?{text:`[Image: ${f.image_url.url}]`}:{text:"[Unresolvable Image]"}}return null}))).filter(Boolean),l=await Promise.all(s.map(async m=>{if(m.role==="tool"&&m.tool_call_id)return{role:"function",parts:[{functionResponse:{name:this.sanitizeToolName(m.name||m.tool_call_id),response:{name:this.sanitizeToolName(m.name||m.tool_call_id),content:typeof m.content=="string"?m.content:JSON.stringify(m.content)}}}]};if(m.role==="assistant"&&m.tool_calls&&m.tool_calls.length>0){let u=[];if(typeof m.content=="string"&&m.content)u.push({text:m.content});else if(Array.isArray(m.content)){let f=m.content.filter(b=>typeof b=="object"&&b.type==="text").map(b=>b.text).join(`
452
- `);f&&u.push({text:f})}for(let f of m.tool_calls)u.push({functionCall:{name:this.sanitizeToolName(f.function.name),args:typeof f.function.arguments=="string"?JSON.parse(f.function.arguments||"{}"):f.function.arguments}});return{role:"model",parts:u}}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:l,lastUserMessage:p}}handleError(e){return e.status===429?new ce(e.message,void 0,e):e.status>=400&&e.status<500?new I(e.message,e):e.message&&e.message.includes("API key")?new he(e.message,e):new j(e.message||"Gemini Error","GEMINI_ERROR",e.status||500,e)}};c();var Fe=T(require("fs"),1),Bs=T(require("path"),1);pe();var Al="toolpack.config.json",Tr=new Map;async function Il(r){for(;Tr.has(r);)await Tr.get(r);let e,t=new Promise(o=>{e=o});return Tr.set(r,t),()=>{Tr.delete(r),e()}}function nt(r){if(r&&Fe.existsSync(r))return r;let e=Bs.join(process.cwd(),Al);return Fe.existsSync(e)?e:null}function kn(r){if(!r)return null;try{let e=Fe.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}var Pn=null;function xr(r){if(Pn)return Pn;let e=r||nt();return Pn=kn(e)||{},Pn}function vr(){Pn=null}function Ll(r){return(xr(r).ollama?.models||[]).map(o=>({type:`ollama-${o.model.replace(/[:.]/g,"-")}`,model:o.model,label:o.label||o.model}))}function Sn(r){return xr(r).ollama?.baseUrl||"http://localhost:11434"}async function jl(r){let{type:e,value:t,configPath:o}=r,n=o||nt();n||(n=Bs.join(process.cwd(),Al));let s=await Il(n);try{let i=kn(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{Fe.writeFileSync(n,JSON.stringify(i,null,4),"utf-8")}catch(a){throw new N(`Failed to write bypass rule to config file: ${a instanceof Error?a.message:String(a)}`,"CONFIG_WRITE_ERROR")}vr()}finally{s()}}async function Fl(r){let{type:e,value:t,configPath:o}=r,n=o||nt();if(!n)return;let s=await Il(n);try{let i=kn(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{Fe.writeFileSync(n,JSON.stringify(i,null,4),"utf-8")}catch(a){throw new N(`Failed to remove bypass rule from config file: ${a instanceof Error?a.message:String(a)}`,"CONFIG_WRITE_ERROR")}vr()}finally{s()}}c();c();pe();k();c();var zs=T(require("http"),1);function Ce(r,e,t,o,n=12e4){return new Promise((s,i)=>{let a=new URL(e,r),l={hostname:a.hostname,port:a.port,path:a.pathname,method:t,headers:{"Content-Type":"application/json"},timeout:n},p=zs.default.request(l,m=>{let u=[];m.on("data",f=>u.push(f)),m.on("end",()=>{s({status:m.statusCode||0,body:Buffer.concat(u).toString("utf-8")})})});p.on("error",m=>i(m)),p.on("timeout",()=>{p.destroy(),i(new Error("Request timed out"))}),o&&p.write(JSON.stringify(o)),p.end()})}function Cr(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 l=new URL(e,r),p={hostname:l.hostname,port:l.port,path:l.pathname,method:"POST",headers:{"Content-Type":"application/json"},timeout:o},m=await new Promise((f,b)=>{s=zs.default.request(p,f),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 f="";for await(let b of m)f+=b.toString();throw new Error(`Ollama HTTP ${m.statusCode}: ${f}`)}let u="";for await(let f of m){if(i)break;let b=f.toString();if(u+=b,u.includes('"error"'))try{let w=JSON.parse(u.trim());if(w.error)throw new Error(`Ollama: ${w.error}`)}catch(w){if(w.message.startsWith("Ollama:"))throw w}let y=u.split(`
453
- `);u=y.pop()||"";for(let w of y)w.trim()&&(yield w)}u.trim()&&!i&&(yield u.trim())}(),abort:()=>{i=!0,s&&s.destroy()}}}var qe=class extends X{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 I(`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 Ce(this.baseUrl,"/api/tags","GET",void 0,5e3);if(e.status!==200)throw new j(`Ollama returned status ${e.status}`,"OLLAMA_ERROR",e.status);return JSON.parse(e.body).models||[]}catch(e){throw e instanceof j?e:new Ie(`Cannot connect to Ollama at ${this.baseUrl}. Is Ollama running? (ollama serve)`,e)}}async isAvailable(){try{return await Ce(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}})),h(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&h(`[Ollama][${t}] First tool: ${O(e.tools[0],800)}`),h(`[Ollama][${t}] NO TOOLS in request`)),h(`[Ollama][${t}] generate() request: model=${n}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),oe(t,"Ollama",e.messages);try{let i=await Ce(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),l=[];if(a.message?.tool_calls)for(let m of a.message.tool_calls)l.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:l.length>0?"tool_calls":a.done?"stop":void 0,tool_calls:l.length>0?l:void 0,raw:a};return h(`[Ollama][${t}] Response finish_reason=${p.finish_reason} tool_calls=${l.length} content_preview=${O(p.content,200)}`),p}catch(i){throw i instanceof j?i:new Ie(`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}})),h(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&h(`[Ollama][${t}] First tool: ${O(e.tools[0],800)}`),h(`[Ollama][${t}] NO TOOLS in request`)),h(`[Ollama][${t}] Stream request: model=${n}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),oe(t,"Ollama",e.messages);let{stream:i}=Cr(this.baseUrl,"/api/chat",s,this.timeout,e.signal);try{for await(let a of i)try{let l=JSON.parse(a);if(l.message?.content){let p=l.message.tool_calls&&l.message.tool_calls.length>0;yield{delta:l.message.content,finish_reason:l.done&&!p?"stop":void 0,usage:l.done&&l.prompt_eval_count!=null?{prompt_tokens:l.prompt_eval_count||0,completion_tokens:l.eval_count||0,total_tokens:(l.prompt_eval_count||0)+(l.eval_count||0)}:void 0}}if(l.message?.tool_calls&&l.message.tool_calls.length>0){let p=l.message.tool_calls.map(m=>({id:`ollama_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(m.function.name,e.tools),arguments:m.function.arguments||{}}));h(`[Ollama][${t}] Stream finish_reason=tool_calls name=${p[0]?.name}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:p}}if(l.done&&!l.message?.content&&!l.message?.tool_calls){je(`[Ollama][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"};return}}catch{}}catch(a){throw new Ie(`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;h(`[Ollama][${t}] Embedding request: model=${n}, inputs=${o.length}`);try{let s=await Ce(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 j?s:new Ie(`Embedding failed for Ollama model "${n}": ${s.message}`,s)}}async disconnect(){}async toOllamaMessage(e,t={}){let o="",n=[],{normalizeImagePart:s}=await Promise.resolve().then(()=>(kt(),Tn));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+`
460
+ `)}async formatHistory(e,t={}){let o=e.filter(d=>d.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(()=>(_t(),Pn)),a=async d=>typeof d=="string"?[{text:d}]:d===null?[]:(await Promise.all(d.map(async b=>{if(b.type==="text")return{text:b.text};if(b.type==="image_data"||b.type==="image_file"||b.type==="image_url")try{let{data:y,mimeType:w}=await i(b);return{inlineData:{mimeType:w,data:y}}}catch{return b.type==="image_url"?{text:`[Image: ${b.image_url.url}]`}:{text:"[Unresolvable Image]"}}return null}))).filter(Boolean),l=await Promise.all(s.map(async d=>{if(d.role==="tool"&&d.tool_call_id)return{role:"function",parts:[{functionResponse:{name:this.sanitizeToolName(d.name||d.tool_call_id),response:{name:this.sanitizeToolName(d.name||d.tool_call_id),content:typeof d.content=="string"?d.content:JSON.stringify(d.content)}}}]};if(d.role==="assistant"&&d.tool_calls&&d.tool_calls.length>0){let f=[];if(typeof d.content=="string"&&d.content)f.push({text:d.content});else if(Array.isArray(d.content)){let b=d.content.filter(y=>typeof y=="object"&&y.type==="text").map(y=>y.text).join(`
461
+ `);b&&f.push({text:b})}for(let b of d.tool_calls)f.push({functionCall:{name:this.sanitizeToolName(b.function.name),args:typeof b.function.arguments=="string"?JSON.parse(b.function.arguments||"{}"):b.function.arguments}});return{role:"model",parts:f}}return{role:d.role==="user"?"user":"model",parts:await a(d.content)}})),p=[];for(let d of l){let f=p[p.length-1];d.role==="function"&&f?.role==="function"?f.parts.push(...d.parts):p.push(d)}let m=typeof n.content=="string"?n.content:await a(n.content);return{history:p,lastUserMessage:m}}handleError(e){return e.status===429?new ce(e.message,void 0,e):e.status>=400&&e.status<500?new I(e.message,e):e.message&&e.message.includes("API key")?new he(e.message,e):new j(e.message||"Gemini Error","GEMINI_ERROR",e.status||500,e)}};c();var Ue=T(require("fs"),1),Xs=T(require("path"),1);pe();var nc="toolpack.config.json",Ir=new Map;async function rc(r){for(;Ir.has(r);)await Ir.get(r);let e,t=new Promise(o=>{e=o});return Ir.set(r,t),()=>{Ir.delete(r),e()}}function at(r){if(r&&Ue.existsSync(r))return r;let e=Xs.join(process.cwd(),nc);return Ue.existsSync(e)?e:null}function Dn(r){if(!r)return null;try{let e=Ue.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}var En=null;function Lr(r){if(En)return En;let e=r||at();return En=Dn(e)||{},En}function jr(){En=null}function sc(r){return(Lr(r).ollama?.models||[]).map(o=>({type:`ollama-${o.model.replace(/[:.]/g,"-")}`,model:o.model,label:o.label||o.model}))}function Mn(r){return Lr(r).ollama?.baseUrl||"http://localhost:11434"}async function ic(r){let{type:e,value:t,configPath:o}=r,n=o||at();n||(n=Xs.join(process.cwd(),nc));let s=await rc(n);try{let i=Dn(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{Ue.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")}jr()}finally{s()}}async function ac(r){let{type:e,value:t,configPath:o}=r,n=o||at();if(!n)return;let s=await rc(n);try{let i=Dn(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{Ue.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")}jr()}finally{s()}}c();c();var Zs=require("zod-to-json-schema");pe();k();c();var Ys=T(require("http"),1);function Ce(r,e,t,o,n=12e4){return new Promise((s,i)=>{let a=new URL(e,r),l={hostname:a.hostname,port:a.port,path:a.pathname,method:t,headers:{"Content-Type":"application/json"},timeout:n},p=Ys.default.request(l,m=>{let d=[];m.on("data",f=>d.push(f)),m.on("end",()=>{s({status:m.statusCode||0,body:Buffer.concat(d).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 Fr(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 l=new URL(e,r),p={hostname:l.hostname,port:l.port,path:l.pathname,method:"POST",headers:{"Content-Type":"application/json"},timeout:o},m=await new Promise((f,b)=>{s=Ys.default.request(p,f),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 f="";for await(let b of m)f+=b.toString();throw new Error(`Ollama HTTP ${m.statusCode}: ${f}`)}let d="";for await(let f of m){if(i)break;let b=f.toString();if(d+=b,d.includes('"error"'))try{let w=JSON.parse(d.trim());if(w.error)throw new Error(`Ollama: ${w.error}`)}catch(w){if(w.message.startsWith("Ollama:"))throw w}let y=d.split(`
462
+ `);d=y.pop()||"";for(let w of y)w.trim()&&(yield w)}d.trim()&&!i&&(yield d.trim())}(),abort:()=>{i=!0,s&&s.destroy()}}}var Ge=class extends Y{config;baseUrl;timeout;modelName;constructor(e){super(),this.config=e,this.baseUrl=e.baseUrl||"http://localhost:11434",this.timeout=e.timeout||12e4,this.modelName=e.model}getDisplayName(){return"Ollama"}async getModels(){try{return(await this.listModels()).map(t=>({id:t.name,displayName:t.name,capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!0,vision:!0}}))}catch{return[]}}async connect(){let e=await this.listModels(),t=this.config.model.split(":")[0].toLowerCase();if(!e.some(n=>n.name.split(":")[0].toLowerCase()===t||n.name.toLowerCase()===this.config.model.toLowerCase()))throw new I(`Model "${this.config.model}" is not pulled in Ollama. Run: ollama pull ${this.config.model}
463
+ Available models: ${e.map(n=>n.name).join(", ")||"(none)"}`);return e}async listModels(){try{let e=await Ce(this.baseUrl,"/api/tags","GET",void 0,5e3);if(e.status!==200)throw new j(`Ollama returned status ${e.status}`,"OLLAMA_ERROR",e.status);return JSON.parse(e.body).models||[]}catch(e){throw e instanceof j?e:new Le(`Cannot connect to Ollama at ${this.baseUrl}. Is Ollama running? (ollama serve)`,e)}}async isAvailable(){try{return await Ce(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.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format&&(s.format=(0,Zs.zodToJsonSchema)(e.response_format)),e.tools&&e.tools.length>0&&e.tool_choice!=="none"&&(s.tools=e.tools.map(i=>({type:"function",function:{name:this.sanitizeToolName(i.function.name),description:i.function.description,parameters:i.function.parameters}})),h(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&h(`[Ollama][${t}] First tool: ${O(e.tools[0],800)}`),h(`[Ollama][${t}] NO TOOLS in request`)),h(`[Ollama][${t}] generate() request: model=${n}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),ne(t,"Ollama",e.messages);try{let i=await Ce(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),l=[];if(a.message?.tool_calls)for(let m of a.message.tool_calls)l.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:l.length>0?"tool_calls":a.done?"stop":void 0,tool_calls:l.length>0?l:void 0,raw:a};return h(`[Ollama][${t}] Response finish_reason=${p.finish_reason} tool_calls=${l.length} content_preview=${O(p.content,200)}`),p}catch(i){throw i instanceof j?i:new Le(`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.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format&&(s.format=(0,Zs.zodToJsonSchema)(e.response_format)),e.tools&&e.tools.length>0&&e.tool_choice!=="none"&&(s.tools=e.tools.map(a=>({type:"function",function:{name:this.sanitizeToolName(a.function.name),description:a.function.description,parameters:a.function.parameters}})),h(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&h(`[Ollama][${t}] First tool: ${O(e.tools[0],800)}`),h(`[Ollama][${t}] NO TOOLS in request`)),h(`[Ollama][${t}] Stream request: model=${n}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),ne(t,"Ollama",e.messages);let{stream:i}=Fr(this.baseUrl,"/api/chat",s,this.timeout,e.signal);try{for await(let a of i)try{let l=JSON.parse(a);if(l.message?.content){let p=l.message.tool_calls&&l.message.tool_calls.length>0;yield{delta:l.message.content,finish_reason:l.done&&!p?"stop":void 0,usage:l.done&&l.prompt_eval_count!=null?{prompt_tokens:l.prompt_eval_count||0,completion_tokens:l.eval_count||0,total_tokens:(l.prompt_eval_count||0)+(l.eval_count||0)}:void 0}}if(l.message?.tool_calls&&l.message.tool_calls.length>0){let p=l.message.tool_calls.map(m=>({id:`ollama_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(m.function.name,e.tools),arguments:m.function.arguments||{}}));h(`[Ollama][${t}] Stream finish_reason=tool_calls name=${p[0]?.name}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:p}}if(l.done&&!l.message?.content&&!l.message?.tool_calls){We(`[Ollama][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"};return}}catch{}}catch(a){throw new Le(`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;h(`[Ollama][${t}] Embedding request: model=${n}, inputs=${o.length}`);try{let s=await Ce(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 j?s:new Le(`Embedding failed for Ollama model "${n}": ${s.message}`,s)}}async disconnect(){}async toOllamaMessage(e,t={}){let o="",n=[],{normalizeImagePart:s}=await Promise.resolve().then(()=>(_t(),Pn));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
464
  `;else if(a.type==="image_url"||a.type==="image_data"||a.type==="image_file")try{let{data:l}=await s(a);n.push(l)}catch{a.type==="image_url"?o+=`[Image: ${a.image_url.url}]
456
465
  `:o+=`[Unresolvable Image]
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 I(`Model not found: ${o}`):new j(o,"OLLAMA_ERROR",e)}};c();var St=class extends X{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 Ce(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 qe({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 Ce(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(l=>s.includes(l))),n||(n=["nomic-embed","mxbai-embed","all-minilm","bge-","snowflake-arctic-embed"].some(l=>s.includes(l)));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 Ce(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}}};c();var Hs=[{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 ql(){return Hs[0].model}function Wl(r){let e=r.toLowerCase();return Hs.some(t=>t.model.toLowerCase()===e||t.model.split(":")[0].toLowerCase()===e.split(":")[0].toLowerCase())}function Ul(){return[...Hs]}c();var Ks=T(require("openai"),1);pe();k();var rt=class extends X{client;constructor(e,t){super(),this.client=new Ks.default({apiKey:e,baseURL:t,timeout:6e4,maxRetries:2})}supportsFileUpload(){return!0}async uploadFile(e){try{let t=await import("fs");if(!e.filePath)throw new I("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(u=>this.toOpenAIMessage(u,e.mediaOptions))),model:e.model,temperature:e.temperature,max_tokens:e.max_tokens,top_p:e.top_p,response_format:e.response_format==="json_object"?{type:"json_object"}:void 0,stream:!1},s=new Map;e.tools&&e.tools.length>0&&(n.tools=e.tools.map(u=>{let f=this.sanitizeToolName(u.function.name);return s.set(f,u.function.name),{type:"function",function:{name:f,description:u.function.description,parameters:u.function.parameters}}}),n.tool_choice=e.tool_choice||"auto",h(`[OpenAI][${t}] Sending ${n.tools.length} tools with tool_choice: ${n.tool_choice}`),h(`[OpenAI][${t}] First tool: ${O(n.tools[0],800)}`)),h(`[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)}`),oe(t,"OpenAI",n.messages);let i=await this.client.chat.completions.create(n,e.signal?{signal:e.signal}:void 0);je(`[OpenAI][${t}] Raw completion: ${JSON.stringify(i)}`);let a=i.choices[0].message;h(`[OpenAI][${t}] Response: finish_reason=${i.choices[0].finish_reason}`),h(`[OpenAI][${t}] Response has tool_calls: ${!!a.tool_calls}, count: ${a.tool_calls?.length||0}`),h(`[OpenAI][${t}] Response content: ${JSON.stringify(a.content)}`),a.content&&h(`[OpenAI][${t}] Response content preview: ${O(a.content,200)}`);let l=i.choices[0],p,m=l.message.tool_calls;return m&&m.length>0&&(p=m.map(u=>({id:u.id,name:s.get(u.function.name)||u.function.name,arguments:JSON.parse(u.function.arguments)}))),{content:l.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:l.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(l=>this.toOpenAIMessage(l,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(l=>{let p=this.sanitizeToolName(l.function.name);return s.set(p,l.function.name),{type:"function",function:{name:p,description:l.function.description,parameters:l.function.parameters}}}),n.tool_choice=e.tool_choice||"auto",h(`[OpenAI][${t}] Sending ${n.tools.length} tools with tool_choice: ${n.tool_choice}`),h(`[OpenAI][${t}] First tool: ${O(n.tools[0],800)}`)):h(`[OpenAI][${t}] NO TOOLS in request`),h(`[OpenAI][${t}] Stream request: model=${n.model}, messages=${n.messages.length}, tools=${n.tools?.length||0}, tool_choice=${n.tool_choice??"unset"}`),oe(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 l of i){let p=l.choices[0];if(p.finish_reason&&je(`[OpenAI][${t}] Stream chunk finish_reason=${p.finish_reason}`),p.delta.tool_calls)for(let m of p.delta.tool_calls){let u=m.index;a.has(u)||a.set(u,{id:m.id||"",name:m.function?.name||"",args:""});let f=a.get(u);m.id&&(f.id=m.id),m.function?.name&&(f.name=m.function.name),m.function?.arguments&&(f.args+=m.function.arguments),je(`[OpenAI][${t}] tool_call_delta idx=${u} id=${m.id||f.id||""} name=${m.function?.name||f.name||""} args_delta=${O(m.function?.arguments||"",200)}`)}if(p.delta.content&&(yield{delta:p.delta.content,finish_reason:p.finish_reason,usage:l.usage}),!p.delta.content&&p.finish_reason&&p.finish_reason!=="tool_calls"&&(yield{delta:"",finish_reason:p.finish_reason,usage:l.usage}),p.finish_reason==="tool_calls"&&a.size>0){let m=Array.from(a.values()).map(u=>({id:u.id,name:s.get(u.name)||u.name,arguments:JSON.parse(u.args||"{}")}));h(`[OpenAI][${t}] Stream finish_reason=tool_calls accumulated_calls=${m.length} names=${m.map(u=>u.name).join(", ")}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:m}}}}catch(t){throw this.handleError(t)}}async embed(e){try{let t=typeof e.input=="string"?[e.input]:e.input,o=await this.client.embeddings.create({model:e.model,input:t});return{embeddings:o.data.map(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(()=>(kt(),Tn)),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 Ks.default.APIError){let t=e.message;return e.status===401?new he(t,e):e.status===429?new ce(t,void 0,e):e.status&&e.status>=400&&e.status<500?new I(t,e):new j(t,e.code||"OPENAI_ERROR",e.status||500,e)}return new j("Unknown error","UNKNOWN",500,e)}};c();var Gl="https://openrouter.ai/api/v1",Rn=class extends rt{name="openrouter";_apiKey;constructor(e,t={}){super(e,Gl),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(`${Gl}/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"}};kt();c();gn();c();gn();var nn=class{tools=new Map;projects=new Map;config=te;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(()=>(fi(),nm)),{execToolsProject:t}=await Promise.resolve().then(()=>(vi(),Hm)),{systemToolsProject:o}=await Promise.resolve().then(()=>(Di(),kd)),{httpToolsProject:n}=await Promise.resolve().then(()=>(ji(),au)),{githubToolsProject:s}=await Promise.resolve().then(()=>(Vi(),uf)),{webToolsProject:i}=await Promise.resolve().then(()=>(ca(),Ag)),{codingToolsProject:a}=await Promise.resolve().then(()=>(_a(),Ry)),{gitToolsProject:l}=await Promise.resolve().then(()=>(Ea(),ib)),{diffToolsProject:p}=await Promise.resolve().then(()=>(Oa(),Tb)),{dbToolsProject:m}=await Promise.resolve().then(()=>(La(),Kb)),{cloudToolsProject:u}=await Promise.resolve().then(()=>(Fa(),rw)),{slackToolsProject:f}=await Promise.resolve().then(()=>(Ka(),Ww));await this.loadProjects([e,t,o,n,s,i,a,l,p,m,u,f])}};Yi();c();k();function Uw(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&&L(`[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}}fi();vi();Di();ji();Vi();ca();_a();Ea();Oa();La();Fa();c();c();var Gw=require("child_process");k();function A(r,e){if(r.includes("\0")||r.includes(`
458
- `)||r.includes("\r"))throw new Error(`Invalid ${e}: contains disallowed characters.`);return r}function Iv(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()}`:""}
459
- STDOUT:
460
- ${e}
461
- STDERR:
462
- ${t}`}function ge(r,e,t=3e4){r.forEach((o,n)=>A(o,`kubectl argument #${n}`)),h(`[k8s-tools] execute: kubectl ${r.join(" ")}`);try{return(0,Gw.execFileSync)("kubectl",r,{input:e,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],timeout:t})||"(kubectl completed with no output)"}catch(o){return Iv(o)}}function Lv(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 Re="kubernetes";function Bw(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])=>`${A(t,"label key")}=${A(o,"label value")}`).join(",")}var ts={name:"k8s.list_pods",displayName:"Kubernetes List Pods",description:"List pods in the current or a specific Kubernetes namespace.",category:Re,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",A(r.namespace,"namespace"));let o=Bw(r.labelSelector)??r.labels;return o&&e.push("-l",A(o,"labels")),ge(e)}},os={name:"k8s.describe",displayName:"Kubernetes Describe Resource",description:"Describe a Kubernetes resource or resource instance.",category:Re,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",A(r.resource,"resource")];return r.name&&t.push(A(r.name,"name")),r.namespace&&t.push("-n",A(r.namespace,"namespace")),ge(t)}},ns={name:"k8s.get_logs",displayName:"Kubernetes Get Pod Logs",description:"Fetch logs from a Kubernetes pod, optionally from a specific container.",category:Re,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",A(r.podName,"podName")];return r.container&&e.push("-c",A(r.container,"container")),r.namespace&&e.push("-n",A(r.namespace,"namespace")),typeof r.tailLines=="number"&&e.push("--tail",`${r.tailLines}`),r.since&&e.push("--since",A(r.since,"since")),ge(e)}},rs={name:"k8s.apply_manifest",displayName:"Kubernetes Apply Manifest",description:"Apply a Kubernetes manifest from a file path or inline YAML content.",category:Re,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(A(e,"path")),r.namespace&&o.push("-n",A(r.namespace,"namespace")),ge(o);if(!t)throw new Error("Either path or manifest is required to apply a Kubernetes manifest.");return r.namespace&&o.push("-n",A(r.namespace,"namespace")),o.push("-"),ge(o,t)}},ss={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:Re,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",A(e,"path")),r.namespace&&s.push("-n",A(r.namespace,"namespace")),ge(s)}if(!t||!o)throw new Error("resource and name are required unless a manifest path is provided.");let n=["delete",A(t,"resource"),A(o,"name")];return r.namespace&&n.push("-n",A(r.namespace,"namespace")),r.force&&n.push("--force","--grace-period=0"),r.dryRun&&n.push("--dry-run=client"),ge(n)}},is={name:"k8s.list_services",displayName:"Kubernetes List Services",description:"List services in the current or a specific Kubernetes namespace.",category:Re,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",A(r.namespace,"namespace")),ge(e)}},as={name:"k8s.list_deployments",displayName:"Kubernetes List Deployments",description:"List deployments in the current or a specific Kubernetes namespace.",category:Re,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",A(r.namespace,"namespace"));let o=Bw(r.labelSelector)??r.labels;return o&&e.push("-l",A(o,"labels")),ge(e)}},ls={name:"k8s.get_config_map",displayName:"Kubernetes Get ConfigMap",description:"Retrieve a ConfigMap from a Kubernetes namespace.",category:Re,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",A(r.name,"name"),"-o",r.output||"yaml"];return r.namespace&&e.push("-n",A(r.namespace,"namespace")),ge(e)}},cs={name:"k8s.switch_context",displayName:"Kubernetes Switch Context",description:"Switch the active kubectl context to a different Kubernetes cluster or namespace configuration.",category:Re,parameters:{type:"object",properties:{context:{type:"string",description:"The kubeconfig context to switch to."}},required:["context"]},execute:async r=>ge(["config","use-context",A(r.context,"context")])},ps={name:"k8s.get_namespaces",displayName:"Kubernetes Get Namespaces",description:"List namespaces in the current Kubernetes context.",category:Re,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=>ge(["get","namespaces","-o",r.output||"wide"])},ms={name:"k8s.wait_for_deployment",displayName:"Kubernetes Wait For Deployment",description:"Wait for a Kubernetes deployment to complete its rollout.",category:Re,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/${A(r.name,"name")}`,"--timeout",e||"300s"];return r.namespace&&t.push("-n",A(r.namespace,"namespace")),ge(t,void 0,Lv(e))}};var zw={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:[ts,os,ns,rs,ss,is,as,ls,cs,ps,ms]};Ka();c();c();var Hw=require("child_process"),Kw=require("events");k();var rr=class extends Error{constructor(e,t){super(`MCP request timed out after ${t}ms: ${e}`),this.name="McpTimeoutError"}},Ee=class extends Error{constructor(t,o){super(t);this.exitCode=o;this.name="McpConnectionError"}exitCode},rn=class extends Kw.EventEmitter{constructor(t){super();this.config=t;this.defaultTimeoutMs=t.requestTimeoutMs??3e4,this.autoReconnect=t.autoReconnect??!1,this.maxReconnectAttempts=t.maxReconnectAttempts??3,this.reconnectDelayMs=t.reconnectDelayMs??1e3}config;process=null;messageQueue=new Map;nextId=1;buffer="";_connected=!1;_shuttingDown=!1;_reconnectAttempts=0;defaultTimeoutMs;autoReconnect;maxReconnectAttempts;reconnectDelayMs;get connected(){return this._connected&&this.process!==null}async initializeServer(){await this.request("initialize",{client:"toolpack-sdk"})}async connect(){if(this._shuttingDown)throw new Ee("Client is shutting down");if(this.buffer="",this.process=(0,Hw.spawn)(this.config.command,this.config.args||[],{env:{...process.env,...this.config.env},stdio:["pipe","pipe","pipe"]}),!this.process.stdout||!this.process.stdin)throw new Ee("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=>{L(`[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 Ee(`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 Ee("Client not connected");let s=this.nextId++,i=n??this.defaultTimeoutMs,a={jsonrpc:"2.0",id:s,method:t,params:o};return new Promise((l,p)=>{let m;i>0&&(m=setTimeout(()=>{let u=this.messageQueue.get(s);u&&(this.messageQueue.delete(s),u.reject(new rr(t,i)))},i)),this.messageQueue.set(s,{resolve:l,reject:p,timer:m});try{this.process.stdin.write(JSON.stringify(a)+`
464
- `)}catch(u){m&&clearTimeout(m),this.messageQueue.delete(s),p(u)}})}async disconnect(t=3e3){if(this._shuttingDown=!0,this.rejectAllPending(new Ee("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 Ee("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 sr=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;S(`[MCP] Connecting to server: ${o||t}`);try{let i=new rn({...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 me(`[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){L(`[MCP] Server ${e} not found`);return}S(`[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{S(`[MCP] Executing ${e.name} on ${t}`);let a=await n.callTool(e.name,i);return JSON.stringify(a)}catch(a){throw me(`[MCP] Tool execution failed: ${a}`),a}}}}setupClientEvents(e,t){e.on("error",o=>{me(`[MCP] ${t} error: ${o}`)}),e.on("close",o=>{L(`[MCP] ${t} closed with code ${o}`)}),e.on("reconnecting",({attempt:o,max:n})=>{S(`[MCP] ${t} reconnecting (${o}/${n})`)}),e.on("reconnected",({attempt:o})=>{S(`[MCP] ${t} reconnected after ${o} attempts`),this.refreshServerTools(t).catch(n=>{me(`[MCP] ${t} tool refresh failed after reconnect: ${n}`)})}),e.on("reconnect_failed",o=>{me(`[MCP] ${t} failed to reconnect after ${o} attempts`)}),e.on("notification",o=>{S(`[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||[];S(`[MCP] Discovered ${s.length} tools from ${e}`),this.removeServerToolDefinitions(e);let i=o.toolPrefix||`mcp.${e}.`;for(let a of s){let l=this.convertMcpTool(a,e,i,t);this.toolDefinitions.set(l.name,l),this.toolOwners.set(l.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 ds(r){let e=new sr(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 us(r){"mcpManager"in r&&await r.mcpManager.disconnectAll()}c();var V=T(require("fs/promises"),1),ne=T(require("path"),1);function Va(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 Qa(r){let e=r.match(/\[(.*)\]/);return!e||!e[1]?[]:e[1].split(",").map(t=>t.trim().replace(/"/g,"")).filter(Boolean)}function Ja(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 dt(r,e){let t=r.match(new RegExp(`## ${e}\\n\\n([\\s\\S]*?)(?=\\n## |$)`));return t&&t[1]?t[1].trim():""}async function Jw(r,e){async function t(o){let n;try{n=await V.readdir(o)}catch{return null}for(let s of n){let i=ne.join(o,s),a;try{a=await V.stat(i)}catch{continue}if(a.isDirectory()){let l=await t(i);if(l)return l}else if(a.isFile()&&s===`${e}.skill.md`)return i}return null}return t(r)}async function jv(r){let e=[];async function t(o){let n;try{n=await V.readdir(o)}catch{return}for(let s of n){let i=ne.join(o,s),a;try{a=await V.stat(i)}catch{continue}a.isDirectory()?await t(i):a.isFile()&&s.endsWith(".skill.md")&&e.push(i)}}return await t(r),e}function Fv(r){let{name:e,title:t,description:o,triggers:n,instructions:s,examples:i,tags:a}=r,l=new Date().toISOString(),p=a&&a.length>0?a.map(u=>`"${u}"`).join(", "):"",m=["---",`name: ${e}`,`title: ${t}`,"version: 1.0.0",`updated: ${l}`,`tags: [${p}]`,"---","","## Description","",o,"","## Triggers","",n.map(u=>`- "${u}"`).join(`
466
+ `}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 I(`Model not found: ${o}`):new j(o,"OLLAMA_ERROR",e)}};c();var Rt=class extends Y{baseUrl;timeout;adapterCache=new Map;capabilityCache=new Map;constructor(e){super(),this.baseUrl=e?.baseUrl||"http://localhost:11434",this.timeout=12e4}getDisplayName(){return"Ollama"}async getModels(){let e;try{let t=await Ce(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 Ge({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 Ce(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(l=>s.includes(l))),n||(n=["nomic-embed","mxbai-embed","all-minilm","bge-","snowflake-arctic-embed"].some(l=>s.includes(l)));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 Ce(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}}};c();var ei=[{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 lc(){return ei[0].model}function cc(r){let e=r.toLowerCase();return ei.some(t=>t.model.toLowerCase()===e||t.model.split(":")[0].toLowerCase()===e.split(":")[0].toLowerCase())}function pc(){return[...ei]}c();var ti=T(require("openai"),1),oi=require("openai/helpers/zod");pe();k();var lt=class extends Y{client;constructor(e,t){super(),this.client=new ti.default({apiKey:e,baseURL:t,timeout:6e4,maxRetries:2})}supportsFileUpload(){return!0}async uploadFile(e){try{let t=await import("fs");if(!e.filePath)throw new I("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(d=>this.toOpenAIMessage(d,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"}:e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format?(0,oi.zodResponseFormat)(e.response_format,"structured_output"):void 0,stream:!1},s=new Map;e.tools&&e.tools.length>0&&(n.tools=e.tools.map(d=>{let f=this.sanitizeToolName(d.function.name);return s.set(f,d.function.name),{type:"function",function:{name:f,description:d.function.description,parameters:d.function.parameters}}}),n.tool_choice=e.tool_choice||"auto",h(`[OpenAI][${t}] Sending ${n.tools.length} tools with tool_choice: ${n.tool_choice}`),h(`[OpenAI][${t}] First tool: ${O(n.tools[0],800)}`)),h(`[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)}`),ne(t,"OpenAI",n.messages);let i=await this.client.chat.completions.create(n,e.signal?{signal:e.signal}:void 0);We(`[OpenAI][${t}] Raw completion: ${JSON.stringify(i)}`);let a=i.choices[0].message;h(`[OpenAI][${t}] Response: finish_reason=${i.choices[0].finish_reason}`),h(`[OpenAI][${t}] Response has tool_calls: ${!!a.tool_calls}, count: ${a.tool_calls?.length||0}`),h(`[OpenAI][${t}] Response content: ${JSON.stringify(a.content)}`),a.content&&h(`[OpenAI][${t}] Response content preview: ${O(a.content,200)}`);let l=i.choices[0],p,m=l.message.tool_calls;return m&&m.length>0&&(p=m.map(d=>({id:d.id,name:s.get(d.function.name)||d.function.name,arguments:JSON.parse(d.function.arguments)}))),{content:l.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:l.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(l=>this.toOpenAIMessage(l,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"}:e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format?(0,oi.zodResponseFormat)(e.response_format,"structured_output"):void 0,stream:!0},s=new Map;e.tools&&e.tools.length>0?(n.tools=e.tools.map(l=>{let p=this.sanitizeToolName(l.function.name);return s.set(p,l.function.name),{type:"function",function:{name:p,description:l.function.description,parameters:l.function.parameters}}}),n.tool_choice=e.tool_choice||"auto",h(`[OpenAI][${t}] Sending ${n.tools.length} tools with tool_choice: ${n.tool_choice}`),h(`[OpenAI][${t}] First tool: ${O(n.tools[0],800)}`)):h(`[OpenAI][${t}] NO TOOLS in request`),h(`[OpenAI][${t}] Stream request: model=${n.model}, messages=${n.messages.length}, tools=${n.tools?.length||0}, tool_choice=${n.tool_choice??"unset"}`),ne(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 l of i){let p=l.choices[0];if(p.finish_reason&&We(`[OpenAI][${t}] Stream chunk finish_reason=${p.finish_reason}`),p.delta.tool_calls)for(let m of p.delta.tool_calls){let d=m.index;a.has(d)||a.set(d,{id:m.id||"",name:m.function?.name||"",args:""});let f=a.get(d);m.id&&(f.id=m.id),m.function?.name&&(f.name=m.function.name),m.function?.arguments&&(f.args+=m.function.arguments),We(`[OpenAI][${t}] tool_call_delta idx=${d} id=${m.id||f.id||""} name=${m.function?.name||f.name||""} args_delta=${O(m.function?.arguments||"",200)}`)}if(p.delta.content&&(yield{delta:p.delta.content,finish_reason:p.finish_reason,usage:l.usage}),!p.delta.content&&p.finish_reason&&p.finish_reason!=="tool_calls"&&(yield{delta:"",finish_reason:p.finish_reason,usage:l.usage}),p.finish_reason==="tool_calls"&&a.size>0){let m=Array.from(a.values()).map(d=>({id:d.id,name:s.get(d.name)||d.name,arguments:JSON.parse(d.args||"{}")}));h(`[OpenAI][${t}] Stream finish_reason=tool_calls accumulated_calls=${m.length} names=${m.map(d=>d.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(()=>(_t(),Pn)),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 ti.default.APIError){let t=e.message;return e.status===401?new he(t,e):e.status===429?new ce(t,void 0,e):e.status&&e.status>=400&&e.status<500?new I(t,e):new j(t,e.code||"OPENAI_ERROR",e.status||500,e)}return new j("Unknown error","UNKNOWN",500,e)}};c();var mc="https://openrouter.ai/api/v1",On=class extends lt{name="openrouter";_apiKey;constructor(e,t={}){super(e,mc),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(`${mc}/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"}};_t();c();xn();c();xn();var pn=class{tools=new Map;projects=new Map;config=oe;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,...o.cacheable!==void 0&&{cacheable:o.cacheable},...o.annotations!==void 0&&{annotations:o.annotations}}))}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(()=>(Ci(),km)),{execToolsProject:t}=await Promise.resolve().then(()=>(Oi(),_d)),{systemToolsProject:o}=await Promise.resolve().then(()=>(Ui(),iu)),{httpToolsProject:n}=await Promise.resolve().then(()=>(Vi(),Uu)),{githubToolsProject:s}=await Promise.resolve().then(()=>(ia(),Jf)),{webToolsProject:i}=await Promise.resolve().then(()=>(Ta(),hh)),{codingToolsProject:a}=await Promise.resolve().then(()=>(Fa(),lb)),{gitToolsProject:l}=await Promise.resolve().then(()=>(Wa(),Wb)),{diffToolsProject:p}=await Promise.resolve().then(()=>(Ba(),tw)),{dbToolsProject:m}=await Promise.resolve().then(()=>(Ja(),Rw)),{cloudToolsProject:d}=await Promise.resolve().then(()=>(Qa(),Fw)),{slackToolsProject:f}=await Promise.resolve().then(()=>(rl(),vT)),{k8sToolsProject:b}=await Promise.resolve().then(()=>(il(),PT));await this.loadProjects([e,t,o,n,s,i,a,l,p,m,d,f,b])}};ca();c();k();function _T(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&&L(`[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}}Tn();Ci();Oi();Ui();Vi();ia();Ta();Fa();Wa();Ba();Ja();Qa();il();rl();c();c();var RT=require("child_process"),$T=require("events");k();var Tr=class extends Error{constructor(e,t){super(`MCP request timed out after ${t}ms: ${e}`),this.name="McpTimeoutError"}},Ee=class extends Error{constructor(t,o){super(t);this.exitCode=o;this.name="McpConnectionError"}exitCode},mn=class extends $T.EventEmitter{constructor(t){super();this.config=t;this.defaultTimeoutMs=t.requestTimeoutMs??3e4,this.autoReconnect=t.autoReconnect??!1,this.maxReconnectAttempts=t.maxReconnectAttempts??3,this.reconnectDelayMs=t.reconnectDelayMs??1e3}config;process=null;messageQueue=new Map;nextId=1;buffer="";_connected=!1;_shuttingDown=!1;_reconnectAttempts=0;defaultTimeoutMs;autoReconnect;maxReconnectAttempts;reconnectDelayMs;get connected(){return this._connected&&this.process!==null}async initializeServer(){await this.request("initialize",{client:"toolpack-sdk"})}async connect(){if(this._shuttingDown)throw new Ee("Client is shutting down");if(this.buffer="",this.process=(0,RT.spawn)(this.config.command,this.config.args||[],{env:{...process.env,...this.config.env},stdio:["pipe","pipe","pipe"]}),!this.process.stdout||!this.process.stdin)throw new Ee("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=>{L(`[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 Ee(`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(`
467
+ `))!==-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 Ee("Client not connected");let s=this.nextId++,i=n??this.defaultTimeoutMs,a={jsonrpc:"2.0",id:s,method:t,params:o};return new Promise((l,p)=>{let m;i>0&&(m=setTimeout(()=>{let d=this.messageQueue.get(s);d&&(this.messageQueue.delete(s),d.reject(new Tr(t,i)))},i)),this.messageQueue.set(s,{resolve:l,reject:p,timer:m});try{this.process.stdin.write(JSON.stringify(a)+`
468
+ `)}catch(d){m&&clearTimeout(m),this.messageQueue.delete(s),p(d)}})}async disconnect(t=3e3){if(this._shuttingDown=!0,this.rejectAllPending(new Ee("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 Ee("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 xr=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 mn({...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 me(`[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){L(`[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 me(`[MCP] Tool execution failed: ${a}`),a}}}}setupClientEvents(e,t){e.on("error",o=>{me(`[MCP] ${t} error: ${o}`)}),e.on("close",o=>{L(`[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=>{me(`[MCP] ${t} tool refresh failed after reconnect: ${n}`)})}),e.on("reconnect_failed",o=>{me(`[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 l=this.convertMcpTool(a,e,i,t);this.toolDefinitions.set(l.name,l),this.toolOwners.set(l.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 hs(r){let e=new xr(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 ys(r){"mcpManager"in r&&await r.mcpManager.disconnectAll()}c();var V=T(require("fs/promises"),1),re=T(require("path"),1);function ll(r){let e={},t=r.match(/^---\n([\s\S]*?)\n---/);if(!t||!t[1])return e;for(let o of t[1].split(`
469
+ `)){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 cl(r){let e=r.match(/\[(.*)\]/);return!e||!e[1]?[]:e[1].split(",").map(t=>t.trim().replace(/"/g,"")).filter(Boolean)}function al(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(`
470
+ `).filter(n=>n.startsWith("- "))){let n=o.match(/^- "(.*)"/);n&&n[1]&&e.push(n[1])}return e}function ht(r,e){let t=r.match(new RegExp(`## ${e}\\n\\n([\\s\\S]*?)(?=\\n## |$)`));return t&&t[1]?t[1].trim():""}async function ET(r,e){async function t(o){let n;try{n=await V.readdir(o)}catch{return null}for(let s of n){let i=re.join(o,s),a;try{a=await V.stat(i)}catch{continue}if(a.isDirectory()){let l=await t(i);if(l)return l}else if(a.isFile()&&s===`${e}.skill.md`)return i}return null}return t(r)}async function NC(r){let e=[];async function t(o){let n;try{n=await V.readdir(o)}catch{return}for(let s of n){let i=re.join(o,s),a;try{a=await V.stat(i)}catch{continue}a.isDirectory()?await t(i):a.isFile()&&s.endsWith(".skill.md")&&e.push(i)}}return await t(r),e}function IC(r){let{name:e,title:t,description:o,triggers:n,instructions:s,examples:i,tags:a}=r,l=new Date().toISOString(),p=a&&a.length>0?a.map(d=>`"${d}"`).join(", "):"",m=["---",`name: ${e}`,`title: ${t}`,"version: 1.0.0",`updated: ${l}`,`tags: [${p}]`,"---","","## Description","",o,"","## Triggers","",n.map(d=>`- "${d}"`).join(`
467
471
  `),"","## Instructions","",s,""];return i&&m.push("## Examples","",i,""),m.join(`
468
- `)}function qv(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,l=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?ne.join(r,p):r;await V.mkdir(m,{recursive:!0});let u=ne.join(m,`${t}.skill.md`);try{return await V.access(u),JSON.stringify({error:"skill_exists",message:`Skill "${t}" already exists at ${u}. Use skill.update to modify it.`},null,2)}catch{}let f=Fv({name:t,title:o,description:n,triggers:s,instructions:i,examples:a,tags:l});return await V.writeFile(u,f,"utf-8"),JSON.stringify({success:!0,skill:t,path:u,message:`Skill "${o}" created successfully`},null,2)}}}function Wv(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 Jw(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 V.readFile(n,"utf-8")).replace(/\r\n/g,`
469
- `),i=Va(s),a={name:i.name||t,title:i.title||t,version:i.version,tags:i.tags?Qa(i.tags):[],updated:i.updated,path:n};return JSON.stringify(o==="metadata"?{skill:t,metadata:a}:o==="description"?{skill:t,description:dt(s,"Description")}:o==="triggers"?{skill:t,triggers:Ja(s)}:o==="instructions"?{skill:t,instructions:dt(s,"Instructions")}:o==="examples"?{skill:t,examples:dt(s,"Examples")}:{skill:t,path:n,metadata:a,description:dt(s,"Description"),triggers:Ja(s),instructions:dt(s,"Instructions"),examples:dt(s,"Examples")||void 0},null,2)}}}function Uv(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,l=e.addTags,p=await Jw(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 V.readFile(p,"utf-8")).replace(/\r\n/g,`
470
- `),u=Va(m),f=u.tags?Qa(u.tags):[],b=u.title||t,y=u.version||"1.0.0",w=o??b,x=l?[...new Set([...f,...l])]:f,C=new Date().toISOString();if(n!==void 0&&(m=m.replace(/## Description\n\n[\s\S]*?(?=\n## )/,`## Description
472
+ `)}function LC(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,l=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?re.join(r,p):r;await V.mkdir(m,{recursive:!0});let d=re.join(m,`${t}.skill.md`);try{return await V.access(d),JSON.stringify({error:"skill_exists",message:`Skill "${t}" already exists at ${d}. Use skill.update to modify it.`},null,2)}catch{}let f=IC({name:t,title:o,description:n,triggers:s,instructions:i,examples:a,tags:l});return await V.writeFile(d,f,"utf-8"),JSON.stringify({success:!0,skill:t,path:d,message:`Skill "${o}" created successfully`},null,2)}}}function jC(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 ET(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 V.readFile(n,"utf-8")).replace(/\r\n/g,`
473
+ `),i=ll(s),a={name:i.name||t,title:i.title||t,version:i.version,tags:i.tags?cl(i.tags):[],updated:i.updated,path:n};return JSON.stringify(o==="metadata"?{skill:t,metadata:a}:o==="description"?{skill:t,description:ht(s,"Description")}:o==="triggers"?{skill:t,triggers:al(s)}:o==="instructions"?{skill:t,instructions:ht(s,"Instructions")}:o==="examples"?{skill:t,examples:ht(s,"Examples")}:{skill:t,path:n,metadata:a,description:ht(s,"Description"),triggers:al(s),instructions:ht(s,"Instructions"),examples:ht(s,"Examples")||void 0},null,2)}}}function FC(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,l=e.addTags,p=await ET(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 V.readFile(p,"utf-8")).replace(/\r\n/g,`
474
+ `),d=ll(m),f=d.tags?cl(d.tags):[],b=d.title||t,y=d.version||"1.0.0",w=o??b,x=l?[...new Set([...f,...l])]:f,C=new Date().toISOString();if(n!==void 0&&(m=m.replace(/## Description\n\n[\s\S]*?(?=\n## )/,`## Description
471
475
 
472
476
  ${n}
473
477
 
474
- `)),s!==void 0){let $=s.map(P=>`- "${P}"`).join(`
478
+ `)),s!==void 0){let $=s.map(S=>`- "${S}"`).join(`
475
479
  `);m=m.replace(/## Triggers\n\n[\s\S]*?(?=\n## )/,`## Triggers
476
480
 
477
481
  ${$}
@@ -480,11 +484,11 @@ ${$}
480
484
 
481
485
  ${i}
482
486
 
483
- `)),a){let $=m.match(/## Examples\n\n([\s\S]*?)(?=\n## |$)/);if($){let P=$[1]??"",M=P.trim()?`
487
+ `)),a){let $=m.match(/## Examples\n\n([\s\S]*?)(?=\n## |$)/);if($){let S=$[1]??"",M=S.trim()?`
484
488
 
485
489
  `:"";m=m.replace(/## Examples\n\n[\s\S]*?(?=\n## |$)/,`## Examples
486
490
 
487
- ${P}${M}${a}
491
+ ${S}${M}${a}
488
492
 
489
493
  `)}else m=m.trimEnd()+`
490
494
 
@@ -492,8 +496,8 @@ ${P}${M}${a}
492
496
 
493
497
  ${a}
494
498
  `}m=m.replace(/^---\n[\s\S]*?\n---/,["---",`name: ${t}`,`title: ${w}`,`version: ${y}`,`updated: ${C}`,`tags: [${x.map($=>`"${$}"`).join(", ")}]`,"---"].join(`
495
- `)),await V.writeFile(p,m,"utf-8");let v=[];return o&&v.push("title"),n!==void 0&&v.push("description"),s!==void 0&&v.push("triggers"),i!==void 0&&v.push("instructions"),a&&v.push("examples (appended)"),l&&v.push(`tags (+${l.length})`),JSON.stringify({success:!0,skill:t,path:p,updated:v,message:`Skill "${t}" updated successfully`},null,2)}}}function Gv(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 V.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 jv(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 V.readFile(i,"utf-8")).replace(/\r\n/g,`
496
- `),l=Va(a),p=l.name||ne.basename(i,".skill.md"),m=l.title||p,u=l.tags?Qa(l.tags):[];if(t&&!u.includes(t))continue;let f=ne.dirname(ne.relative(r,i)),b=f==="."?void 0:f.split(ne.sep)[0];o?s.push({name:p,title:m,tags:u,category:b,description:dt(a,"Description")||void 0,triggers:Ja(a)}):s.push({name:p,title:m,tags:u,category:b})}return JSON.stringify({skills:s,count:s.length,filtered:t?`by tag: ${t}`:null},null,2)}}}function Vw(r){let e=ne.resolve(r?.dir??".toolpack/skills"),t=[qv(e),Wv(e),Uv(e),Gv(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}}c();c();c();c();var fs=`
499
+ `)),await V.writeFile(p,m,"utf-8");let v=[];return o&&v.push("title"),n!==void 0&&v.push("description"),s!==void 0&&v.push("triggers"),i!==void 0&&v.push("instructions"),a&&v.push("examples (appended)"),l&&v.push(`tags (+${l.length})`),JSON.stringify({success:!0,skill:t,path:p,updated:v,message:`Skill "${t}" updated successfully`},null,2)}}}function qC(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 V.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 NC(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 V.readFile(i,"utf-8")).replace(/\r\n/g,`
500
+ `),l=ll(a),p=l.name||re.basename(i,".skill.md"),m=l.title||p,d=l.tags?cl(l.tags):[];if(t&&!d.includes(t))continue;let f=re.dirname(re.relative(r,i)),b=f==="."?void 0:f.split(re.sep)[0];o?s.push({name:p,title:m,tags:d,category:b,description:ht(a,"Description")||void 0,triggers:al(a)}):s.push({name:p,title:m,tags:d,category:b})}return JSON.stringify({skills:s,count:s.length,filtered:t?`by tag: ${t}`:null},null,2)}}}function DT(r){let e=re.resolve(r?.dir??".toolpack/skills"),t=[LC(e),jC(e),FC(e),qC(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}}c();c();c();c();var bs=`
497
501
  You are a planning assistant. Given a user request, create a detailed step-by-step plan.
498
502
 
499
503
  Rules:
@@ -519,7 +523,7 @@ Rules:
519
523
  }
520
524
  ]
521
525
  }
522
- `,Bv={name:"Direct",planning:{enabled:!1},progress:{enabled:!0}},Xa={name:"Agent",planning:{enabled:!0,planningPrompt:fs},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},Qw=`
526
+ `,WC={name:"Direct",planning:{enabled:!1},progress:{enabled:!0}},pl={name:"Agent",planning:{enabled:!0,planningPrompt:bs},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},MT=`
523
527
  Create a step-by-step plan for this coding task.
524
528
 
525
529
  Rules:
@@ -542,7 +546,7 @@ JSON Schema:
542
546
  }
543
547
  ]
544
548
  }
545
- `,Ya={name:"Coding",planning:{enabled:!0,planningPrompt:Qw},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},Za={name:"Chat",planning:{enabled:!1},progress:{enabled:!1}};var el={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:Xa,toolSearch:{alwaysLoadedTools:["fs.read_file","fs.write_file","fs.list_dir","web.search","web.fetch","skill.search","skill.read"]}},tl={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:Za,toolSearch:{alwaysLoadedTools:["web.search","web.fetch","fs.read_file","fs.list_dir"]}},ol={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:Ya,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"]}},ir=[el,ol,tl],ut="chat";var sn=class{modes=new Map;orderedNames=[];constructor(){for(let e of ir)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(ut);if(!e)throw new Error(`Default mode "${ut}" 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(ir.some(n=>n.name===e))return!1;let o=this.modes.delete(e);return o&&(this.orderedNames=this.orderedNames.filter(n=>n!==e)),o}};c();function Xw(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,response_format:r.response_format,baseContext:r.baseContext,workflow:r.workflow}}c();var gs={planning:{enabled:!1},progress:{enabled:!0}};c();k();var zv=fs,an=class{client;config;constructor(e,t){this.client=e,this.config=t}async createPlan(e,t){let o=this.config?.planningPrompt||zv,n=e.messages.filter(p=>p.role==="user").map(p=>typeof p.content=="string"?p.content:"[obj]").join(" ").substring(0,100);h(`[Planner] createPlan() provider=${t??"default"} maxSteps=${this.config?.maxSteps??20} request="${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],l={...e,tools:void 0,tool_choice:"none",response_format:"json_object",messages:a};try{let p=await this.client.generate(l,t),m=this.parsePlan(p.content||"",e,p);return S(`[Planner] createPlan() succeeded plan.id=${m.id} steps=${m.steps.length}`),m}catch(p){return L(`[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&&L(`[Planner] parsePlan() truncated ${n.steps.length} steps to maxSteps=${s}`),h(`[Planner] parsePlan() parsed ${i.length} steps successfully`);let a=i.map((p,m)=>({id:`step-${Date.now()}-${m}`,number:p.number||m+1,description:p.description||"Unknown step",expectedTools:p.expectedTools||[],dependsOn:p.dependsOn||[],status:"pending"})),l=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:l,summary:n.summary,steps:a,status:"draft",createdAt:new Date,planningResponse:o}}catch(n){return L(`[Planner] parsePlan() failed: ${n.message} \u2014 using fallback`),this.createFallbackPlan(t)}}createFallbackPlan(e){L("[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}}};c();var Yw=require("events");k();var ar=class extends Yw.EventEmitter{client;config;planner;queryClassifier;pendingApprovals=new Map;constructor(e,t,o){super(),this.client=e,this.config=t,this.queryClassifier=o||new Ct,this.planner=new an(e,t.planning)}getConfig(){return this.config}setConfig(e){this.config=e,this.planner=new an(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=tt(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 h(`[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(h(`[Workflow] execute() planningEnabled=${o} provider=${t??"default"}`),!o)return h("[Workflow] execute() mode=direct"),this.executeDirect(e,t);h("[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){S(`[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 S(`[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}};S(`[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);h(`[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;h(`[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",L(`[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){h(`[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 S(`[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),h(`[Workflow] executePlanDirect() plan.id=${e.id} steps=${e.steps.length} provider=${o??"default"}`);let s=`
549
+ `,ml={name:"Coding",planning:{enabled:!0,planningPrompt:MT},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},dl={name:"Chat",planning:{enabled:!1},progress:{enabled:!1}};var ul={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:pl,toolSearch:{alwaysLoadedTools:["fs.read_file","fs.write_file","fs.list_dir","web.search","web.fetch","skill.search","skill.read"]}},fl={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:dl,toolSearch:{alwaysLoadedTools:["web.search","web.fetch","fs.read_file","fs.list_dir"]}},gl={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:ml,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=[ul,gl,fl],yt="chat";var dn=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 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(yt);if(!e)throw new Error(`Default mode "${yt}" 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(vr.some(n=>n.name===e))return!1;let o=this.modes.delete(e);return o&&(this.orderedNames=this.orderedNames.filter(n=>n!==e)),o}};c();function OT(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,response_format:r.response_format,baseContext:r.baseContext,workflow:r.workflow}}c();var ws={planning:{enabled:!1},progress:{enabled:!0}};c();k();var UC=bs,un=class{client;config;constructor(e,t){this.client=e,this.config=t}async createPlan(e,t){let o=this.config?.planningPrompt||UC,n=e.messages.filter(p=>p.role==="user").map(p=>typeof p.content=="string"?p.content:"[obj]").join(" ").substring(0,100);h(`[Planner] createPlan() provider=${t??"default"} maxSteps=${this.config?.maxSteps??20} request="${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],l={...e,tools:void 0,tool_choice:"none",response_format:"json_object",messages:a};try{let p=await this.client.generate(l,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 L(`[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&&L(`[Planner] parsePlan() truncated ${n.steps.length} steps to maxSteps=${s}`),h(`[Planner] parsePlan() parsed ${i.length} steps successfully`);let a=i.map((p,m)=>({id:`step-${Date.now()}-${m}`,number:p.number||m+1,description:p.description||"Unknown step",expectedTools:p.expectedTools||[],dependsOn:p.dependsOn||[],status:"pending"})),l=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:l,summary:n.summary,steps:a,status:"draft",createdAt:new Date,planningResponse:o}}catch(n){return L(`[Planner] parsePlan() failed: ${n.message} \u2014 using fallback`),this.createFallbackPlan(t)}}createFallbackPlan(e){L("[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}}};c();var AT=require("events");k();var Cr=class extends AT.EventEmitter{client;config;planner;queryClassifier;pendingApprovals=new Map;constructor(e,t,o){super(),this.client=e,this.config=t,this.queryClassifier=o||new kt,this.planner=new un(e,t.planning)}getConfig(){return this.config}setConfig(e){this.config=e,this.planner=new un(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=st(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 h(`[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(h(`[Workflow] execute() planningEnabled=${o} provider=${t??"default"}`),!o)return h("[Workflow] execute() mode=direct"),this.executeDirect(e,t);h("[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);h(`[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;h(`[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",L(`[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){h(`[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),h(`[Workflow] executePlanDirect() plan.id=${e.id} steps=${e.steps.length} provider=${o??"default"}`);let s=`
546
550
  You have created the following plan to fulfill the request:
547
551
  Summary: ${e.summary}
548
552
 
@@ -576,7 +580,8 @@ ${e.steps.map(a=>`${a.number}. ${a.description}`).join(`
576
580
  `)}
577
581
 
578
582
  Execute this plan now.
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))}};c();var nl=require("events");k();var rl=class r extends nl.EventEmitter{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 ar(this.client,gs,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,l)=>(await a.toTool().execute({query:o.query,limit:o.limit,threshold:o.threshold,filter:o.filter})).map(u=>({...u,_layer:l}))))).flat();s.sort((a,l)=>(l.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=Dn(e.configPath);vl(t.logging);let o=new nn,n=So(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{S("[MCP] Initializing MCP tool integration");let R=await ds(i);s=R,await o.loadProjects([R]),S(`[MCP] Loaded ${R.tools.length} tools from MCP servers`)}catch(R){me(`[MCP] Failed to initialize MCP tools: ${R}`)}let a=t.systemPrompt,l=e.disableBaseContext||t.disableBaseContext||t.baseContext===!1||!1,p=t.modeOverrides||{},m={},u=new Set,f=e.defaultProvider||e.provider;if(e.providers)for(let[R,D]of Object.entries(e.providers)){let _=R===f,W=await r.createProvider(R,D,e.configPath,!_);W&&(m[R]=W)}else if(e.provider){let R={apiKey:e.apiKey,model:e.model,projectId:e.projectId,location:e.location,googleAuthOptions:e.googleAuthOptions},D=await r.createProvider(e.provider,R,e.configPath,!1);D&&(m[e.provider]=D)}else if(!e.customProviders)throw new Error('No provider specified. Pass { provider: "name" }, { providers: { ... } }, or { customProviders: { ... } } to init().');if(e.customProviders){let R=Array.isArray(e.customProviders)?e.customProviders:Object.entries(e.customProviders).map(([D,_])=>(_.name=_.name||D,_));for(let D of R){if(typeof D.generate!="function"||typeof D.stream!="function"||typeof D.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.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.`);u.add(_),m[_]=D}}if(!f&&e.customProviders&&(f=(Array.isArray(e.customProviders)?e.customProviders[0]:Object.values(e.customProviders)[0])?.name),!f)throw new Error("No default provider specified.");let b=new sn;if(e.customModes)for(let R of e.customModes)b.register(R);let y={...p,...e.modeOverrides||{}};for(let[R,D]of Object.entries(y)){let _=b.get(R);if(_){D.systemPrompt!==void 0&&(_.systemPrompt=D.systemPrompt),D.toolSearch&&(_.toolSearch={..._.toolSearch||{},...D.toolSearch});for(let[W,z]of Object.entries(D))W!=="systemPrompt"&&W!=="toolSearch"&&(_[W]=z)}}let w=t.hitl||{};e.confirmationMode!==void 0&&(w.confirmationMode=e.confirmationMode),w.enabled===void 0&&e.onToolConfirm&&(w.enabled=!0),w.confirmationMode===void 0&&e.onToolConfirm&&(w.confirmationMode="all");let x=new wn({providers:m,defaultProvider:f,toolRegistry:o,toolsConfig:o.getConfig(),systemPrompt:a,disableBaseContext:l,hitlConfig:Object.keys(w).length>0?w:void 0,onToolConfirm:e.onToolConfirm,conversationId:e.conversationId,contextWindowConfig:e.contextWindow}),C=new r(x,f,b),v=e.knowledge,$=v==null?[]:Array.isArray(v)?v:[v];C.knowledgeLayers=$.filter(R=>!!R&&typeof R.toTool=="function"),C.customProviderNames=u,C.mcpToolProject=s,C._interceptors=e.interceptors??[];for(let R of C._interceptors)R.init&&await R.init();let P=e.defaultMode||ut,M=b.get(P);return M&&(x.setMode(M),M.workflow&&C.workflowExecutor.setConfig(M.workflow)),C}static async createProvider(e,t,o,n=!1){if(e==="vertexai")return new vn({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 rt(i,t.baseUrl);case"anthropic":return new xn(i,t.baseUrl);case"gemini":return new Cn(i);case"openrouter":return new Rn(i,{siteUrl:t.siteUrl,siteName:t.siteName})}}if(e==="ollama")return new St({baseUrl:t.baseUrl||Sn(o)});if(e.startsWith("ollama-")){let s=t.model||e.replace(/^ollama-/,""),i=t.baseUrl||Sn(o);return new qe({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,l=0,p={steps:[]};s.plan.planningResponse?.usage&&(i+=s.plan.planningResponse.usage.prompt_tokens,a+=s.plan.planningResponse.usage.completion_tokens||0,l+=s.plan.planningResponse.usage.total_tokens,p.planning=s.plan.planningResponse.usage);for(let u of s.plan.steps)if(u.status==="completed"&&u.result?.response?.usage){let f=u.result.response.usage;i+=f.prompt_tokens,a+=f.completion_tokens||0,l+=f.total_tokens,p.steps.push({stepNumber:u.number,description:u.description,usage:f})}let m={prompt_tokens:i,completion_tokens:a,total_tokens:l};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||nt();if(t)try{let o=kn(t);o?.hitl&&this.client.updateHitlConfig(o.hitl)}catch(o){L(`[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 us(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){L(`[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(gs),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 nl.EventEmitter&&e.on("status",t=>this.emit("status",t))}forwardWorkflowEvents(){let e=this.workflowExecutor;e.on("workflow:plan_created",t=>this.emit("workflow:plan_created",t)),e.on("workflow:plan_decision",(t,o)=>this.emit("workflow:plan_decision",t,o)),e.on("workflow:started",t=>this.emit("workflow:started",t)),e.on("workflow: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))}};c();c();c();var hs=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 ys=class{lru;maxMessagesPerConversation;constructor(e={}){this.lru=new hs(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,l=n.filter(u=>u.content.toLowerCase().includes(s)).slice().reverse(),p=[],m=0;for(let u of l){if(p.length>=i)break;let f=Math.ceil(u.content.length/4);if(p.length>0&&m+f>a)break;p.push(u),m+=f}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}};c();var Zw=T(require("better-sqlite3"),1),ln=T(require("fs"),1),lr=T(require("path"),1);function Hv(){let r=lr.join(process.cwd(),".toolpack","db","conversation");return ln.existsSync(r)||ln.mkdirSync(r,{recursive:!0}),lr.join(r,"conversation.sqlite")}var bs=class{db;maxMessagesPerConversation;useFTS;constructor(e={}){let t=e.dbPath??Hv(),o=lr.dirname(t);if(ln.existsSync(o)||ln.mkdirSync(o,{recursive:!0}),this.db=new Zw.default(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(`
583
+ `.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))}};c();var wl=require("events");k();var Tl=class r extends wl.EventEmitter{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 Cr(this.client,ws,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,l)=>(await a.toTool().execute({query:o.query,limit:o.limit,threshold:o.threshold,filter:o.filter})).map(d=>({...d,_layer:l}))))).flat();s.sort((a,l)=>(l.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=In(e.configPath);Ul(t.logging);let o=new pn,n=Mo(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 _=await hs(i);s=_,await o.loadProjects([_]),P(`[MCP] Loaded ${_.tools.length} tools from MCP servers`)}catch(_){me(`[MCP] Failed to initialize MCP tools: ${_}`)}let a=t.systemPrompt,l=e.disableBaseContext||t.disableBaseContext||t.baseContext===!1||!1,p=t.modeOverrides||{},m={},d=new Set,f=e.defaultProvider||e.provider;if(e.providers)for(let[_,D]of Object.entries(e.providers)){let R=_===f,W=await r.createProvider(_,D,e.configPath,!R);W&&(m[_]=W)}else if(e.provider){let _={apiKey:e.apiKey,model:e.model,projectId:e.projectId,location:e.location,googleAuthOptions:e.googleAuthOptions},D=await r.createProvider(e.provider,_,e.configPath,!1);D&&(m[e.provider]=D)}else if(!e.customProviders)throw new Error('No provider specified. Pass { provider: "name" }, { providers: { ... } }, or { customProviders: { ... } } to init().');if(e.customProviders){let _=Array.isArray(e.customProviders)?e.customProviders:Object.entries(e.customProviders).map(([D,R])=>(R.name=R.name||D,R));for(let D of _){if(typeof D.generate!="function"||typeof D.stream!="function"||typeof D.embed!="function")throw new Error("Custom provider must implement the ProviderAdapter interface (generate, stream, embed methods). Import { ProviderAdapter } from 'toolpack' and implement or extend it.");let R=D.name;if(!R)throw new Error("Custom provider must have a 'name' property set. Set adapter.name in the constructor or use the record syntax: { 'provider-name': adapter }");if(m[R])throw new Error(`Custom provider name "${R}" conflicts with a built-in provider designation. Choose a different name.`);d.add(R),m[R]=D}}if(!f&&e.customProviders&&(f=(Array.isArray(e.customProviders)?e.customProviders[0]:Object.values(e.customProviders)[0])?.name),!f)throw new Error("No default provider specified.");let b=new dn;if(e.customModes)for(let _ of e.customModes)b.register(_);let y={...p,...e.modeOverrides||{}};for(let[_,D]of Object.entries(y)){let R=b.get(_);if(R){D.systemPrompt!==void 0&&(R.systemPrompt=D.systemPrompt),D.toolSearch&&(R.toolSearch={...R.toolSearch||{},...D.toolSearch});for(let[W,z]of Object.entries(D))W!=="systemPrompt"&&W!=="toolSearch"&&(R[W]=z)}}let w=t.hitl||{};e.confirmationMode!==void 0&&(w.confirmationMode=e.confirmationMode),w.enabled===void 0&&e.onToolConfirm&&(w.enabled=!0),w.confirmationMode===void 0&&e.onToolConfirm&&(w.confirmationMode="all");let x=new kn({providers:m,defaultProvider:f,toolRegistry:o,toolsConfig:o.getConfig(),systemPrompt:a,disableBaseContext:l,hitlConfig:Object.keys(w).length>0?w:void 0,onToolConfirm:e.onToolConfirm,conversationId:e.conversationId,contextWindowConfig:e.contextWindow}),C=new r(x,f,b),v=e.knowledge,$=v==null?[]:Array.isArray(v)?v:[v];C.knowledgeLayers=$.filter(_=>!!_&&typeof _.toTool=="function"),C.customProviderNames=d,C.mcpToolProject=s,C._interceptors=e.interceptors??[];for(let _ of C._interceptors)_.init&&await _.init();let S=e.defaultMode||yt,M=b.get(S);return M&&(x.setMode(M),M.workflow&&C.workflowExecutor.setConfig(M.workflow)),C}static async createProvider(e,t,o,n=!1){if(e==="vertexai")return new Rn({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 lt(i,t.baseUrl);case"anthropic":return new _n(i,t.baseUrl);case"gemini":return new $n(i);case"openrouter":return new On(i,{siteUrl:t.siteUrl,siteName:t.siteName})}}if(e==="ollama")return new Rt({baseUrl:t.baseUrl||Mn(o)});if(e.startsWith("ollama-")){let s=t.model||e.replace(/^ollama-/,""),i=t.baseUrl||Mn(o);return new Ge({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,l=0,p={steps:[]};s.plan.planningResponse?.usage&&(i+=s.plan.planningResponse.usage.prompt_tokens,a+=s.plan.planningResponse.usage.completion_tokens||0,l+=s.plan.planningResponse.usage.total_tokens,p.planning=s.plan.planningResponse.usage);for(let d of s.plan.steps)if(d.status==="completed"&&d.result?.response?.usage){let f=d.result.response.usage;i+=f.prompt_tokens,a+=f.completion_tokens||0,l+=f.total_tokens,p.steps.push({stepNumber:d.number,description:d.description,usage:f})}let m={prompt_tokens:i,completion_tokens:a,total_tokens:l};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||at();if(t)try{let o=Dn(t);o?.hitl&&this.client.updateHitlConfig(o.hitl)}catch(o){L(`[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 ys(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){L(`[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 startMcpServer(e){let t=this.client.getToolRegistry();if(!t)throw new Error("No tool registry configured. Initialize Toolpack with tools enabled: Toolpack.init({ tools: true })");let o;try{o=(await Promise.resolve().then(()=>(HT(),zT))).startMcpServer}catch(s){throw s instanceof Error&&s.code==="MODULE_NOT_FOUND"&&s.message.includes("@modelcontextprotocol")?new Error(`MCP server requires @modelcontextprotocol/sdk. Install it with:
584
+ npm install @modelcontextprotocol/sdk`):s}let n=e.searchMode?s=>this.client.executeToolSearch(s):void 0;return o(t,e,n)}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(ws),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 wl.EventEmitter&&e.on("status",t=>this.emit("status",t))}forwardWorkflowEvents(){let e=this.workflowExecutor;e.on("workflow:plan_created",t=>this.emit("workflow:plan_created",t)),e.on("workflow:plan_decision",(t,o)=>this.emit("workflow:plan_decision",t,o)),e.on("workflow:started",t=>this.emit("workflow:started",t)),e.on("workflow: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))}};c();c();c();var vs=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 Cs=class{lru;maxMessagesPerConversation;constructor(e={}){this.lru=new vs(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,l=n.filter(d=>d.content.toLowerCase().includes(s)).slice().reverse(),p=[],m=0;for(let d of l){if(p.length>=i)break;let f=Math.ceil(d.content.length/4);if(p.length>0&&m+f>a)break;p.push(d),m+=f}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}};c();var KT=T(require("better-sqlite3"),1),fn=T(require("fs"),1),Sr=T(require("path"),1);function KC(){let r=Sr.join(process.cwd(),".toolpack","db","conversation");return fn.existsSync(r)||fn.mkdirSync(r,{recursive:!0}),Sr.join(r,"conversation.sqlite")}var Ss=class{db;maxMessagesPerConversation;useFTS;constructor(e={}){let t=e.dbPath??KC(),o=Sr.dirname(t);if(fn.existsSync(o)||fn.mkdirSync(o,{recursive:!0}),this.db=new KT.default(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
585
  CREATE TABLE IF NOT EXISTS messages (
581
586
  id TEXT NOT NULL,
582
587
  conversation_id TEXT NOT NULL,
@@ -591,7 +596,7 @@ Execute this plan now.
591
596
  )`),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
597
  id, conversation_id, participant_kind, participant_id, participant_display_name,
593
598
  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 l=a-this.maxMessagesPerConversation,m=this.db.prepare("SELECT id FROM messages WHERE conversation_id = ? ORDER BY timestamp ASC LIMIT ?").all(e.conversationId,l).map(u=>u.id);if(m.length>0){let u=m.map(()=>"?").join(",");if(this.db.prepare(`DELETE FROM messages WHERE conversation_id = ? AND id IN (${u})`).run(e.conversationId,...m),this.useFTS){let b=m.map(x=>`${e.conversationId}:${x}`),y=b.map(()=>"?").join(",");this.db.prepare(`DELETE FROM messages_fts WHERE doc_key IN (${y})`).run(...b)}}}}}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`,l=this.db.prepare(i).all(n).map(p=>this.rowToMessage(p));return t.limit!==void 0&&l.length>t.limit&&(l=l.slice(l.length-t.limit)),l}async search(e,t,o={}){let n=o.limit??10,s=o.tokenCap??2e3,i=[];this.useFTS?i=this.db.prepare(`
599
+ ) 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 l=a-this.maxMessagesPerConversation,m=this.db.prepare("SELECT id FROM messages WHERE conversation_id = ? ORDER BY timestamp ASC LIMIT ?").all(e.conversationId,l).map(d=>d.id);if(m.length>0){let d=m.map(()=>"?").join(",");if(this.db.prepare(`DELETE FROM messages WHERE conversation_id = ? AND id IN (${d})`).run(e.conversationId,...m),this.useFTS){let b=m.map(x=>`${e.conversationId}:${x}`),y=b.map(()=>"?").join(",");this.db.prepare(`DELETE FROM messages_fts WHERE doc_key IN (${y})`).run(...b)}}}}}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`,l=this.db.prepare(i).all(n).map(p=>this.rowToMessage(p));return t.limit!==void 0&&l.length>t.limit&&(l=l.slice(l.length-t.limit)),l}async search(e,t,o={}){let n=o.limit??10,s=o.tokenCap??2e3,i=[];this.useFTS?i=this.db.prepare(`
595
600
  SELECT m.id, m.conversation_id, m.participant_kind, m.participant_id, m.participant_display_name,
596
601
  m.content, m.timestamp, m.scope, m.metadata
597
602
  FROM messages m
@@ -602,14 +607,14 @@ Execute this plan now.
602
607
  content, timestamp, scope, metadata
603
608
  FROM messages
604
609
  WHERE conversation_id = ? AND content LIKE ? COLLATE NOCASE
605
- ORDER BY timestamp DESC`).all(e,`%${t}%`);let a=i.map(m=>this.rowToMessage(m)),l=[],p=0;for(let m of a){if(l.length>=n)break;let u=Math.ceil(m.content.length/4);if(l.length>0&&p+u>s)break;l.push(m),p+=u}return l}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(l=>`${e}:${l}`),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{}}};c();var eT=T(require("os"),1),ft=T(require("path"),1),cn=T(require("fs"),1),sl=".toolpack",il="config",al="toolpack.config.json";function tT(){return eT.homedir()}function oT(){return ft.join(tT(),sl)}function ll(){return ft.join(oT(),il)}function cr(){return ft.join(ll(),al)}function nT(r=process.cwd()){return ft.join(r,sl)}function cl(r=process.cwd()){return ft.join(nT(r),il)}function pr(r=process.cwd()){return ft.join(cl(r),al)}function pl(){let r=ll();cn.existsSync(r)||cn.mkdirSync(r,{recursive:!0})}function Kv(r=process.cwd()){let e=cl(r);cn.existsSync(e)||cn.mkdirSync(e,{recursive:!0})}c();var re=T(require("fs"),1),ws=T(require("path"),1);function dl(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]=dl(r[o],e[o]):t[o]=e[o];return t}function ml(r){if(!re.existsSync(r))return null;try{let e=re.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}function Jv(r=process.cwd()){let e=ws.join(r,"toolpack.config.json"),t=cr(),o=pr(r),n=ml(e)||{},s=ml(t)||{},i=ml(o)||{},a=dl(n,s);return a=dl(a,i),a}function Vv(r=process.cwd()){let e=ws.join(r,"toolpack.config.json"),t=cr(),o=pr(r),n=!re.existsSync(t),s=null,i="default";return re.existsSync(o)?(s=o,i="local"):re.existsSync(t)?(s=t,i="global"):re.existsSync(e)&&(s=e,i="base"),{isFirstRun:n,activeConfigPath:s,configSource:i}}function Qv(r=process.cwd()){let e=cr();if(!re.existsSync(e)){pl();let t=null,o=pr(r);if(re.existsSync(o))t=o;else{let s=ws.join(r,"toolpack.config.json");if(re.existsSync(s))t=s;else{let i=nt();i&&re.existsSync(i)&&(t=i)}}let n={};if(t)try{let s=re.readFileSync(t,"utf-8");n=JSON.parse(s)}catch{}re.writeFileSync(e,JSON.stringify(n,null,4),"utf-8")}}c();c();c();var Xe=T(require("fs/promises"),1),pn=T(require("path"),1);c();var Xv=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"]),Ts=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=>!Xv.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 l=0,p=this.documentLengths.get(a)??0;for(let m of o){let u=this.termFrequencies.get(m);if(!u)continue;let f=u.get(a)??0;if(f===0)continue;let b=this.idf(m),y=f*(this.k1+1),w=f+this.k1*(1-this.b+this.b*(p/this.avgDocLength));l+=b*(y/w)}l>0&&(n[a]=l)});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)}};c();var Qe=T(require("path"),1);function rT(r,e,t){let o=r.match(/^---\n([\s\S]*?)\n---/),n="",s="",i,a=[];if(o&&o[1]){let $=o[1].split(`
606
- `);for(let P of $){let M=P.indexOf(":");if(M===-1)continue;let R=P.substring(0,M).trim(),D=P.substring(M+1).trim();if(R==="name"&&(n=D),R==="title"&&(s=D),R==="version"&&(i=D),R==="tags"){let _=D.match(/\[(.*)\]/);_&&_[1]&&(a=_[1].split(",").map(W=>W.trim().replace(/"/g,"")).filter(Boolean))}}}n||(n=Qe.basename(e,".skill.md"));let l=r.match(/## Description\n\n([\s\S]*?)(?=\n## |$)/),p=l&&l[1]?l[1].trim():"",m=r.match(/## Triggers\n\n([\s\S]*?)(?=\n## |$)/),u=[];if(m&&m[1]){let $=m[1].split(`
607
- `).filter(P=>P.startsWith("- "));for(let P of $){let M=P.match(/^- "(.*)"/);M&&M[1]&&u.push(M[1])}}let f=r.match(/## Instructions\n\n([\s\S]*?)(?=\n## |$)/),b=f&&f[1]?f[1].trim():"",y=r.match(/## Examples\n\n([\s\S]*?)(?=\n## |$)/),w=y&&y[1]?y[1].trim():void 0,x=Qe.relative(t,e),C=Qe.dirname(x),v=C==="."?void 0:C.split(Qe.sep)[0];return{name:n,title:s,version:i,tags:a,category:v,filePath:e,description:p,triggers:u,instructions:b,examples:w||void 0,lastModified:0}}c();c();var H={name:50,title:100,tags:{count:10,each:30},description:300,triggers:{count:10,min:1,each:100},instructions:2e3,examples:3e3};var Yv=/^[a-z][a-z0-9-]*$/;function sT(r,e){let t=[],o=[];r.name?(Yv.test(r.name)||t.push(`name "${r.name}" must match kebab-case pattern /^[a-z][a-z0-9-]*$/`),r.name.length>H.name&&o.push(`name exceeds ${H.name} character limit (${r.name.length} chars)`)):t.push("name is required in frontmatter"),r.title?r.title.length>H.title&&o.push(`title exceeds ${H.title} character limit (${r.title.length} chars)`):t.push("title is required in frontmatter"),r.tags.length>H.tags.count&&o.push(`too many tags (${r.tags.length}); maximum is ${H.tags.count}`);for(let n of r.tags)n.length>H.tags.each&&o.push(`tag "${n}" exceeds ${H.tags.each} character limit`);if(r.description?r.description.length>H.description&&o.push(`description exceeds ${H.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>H.triggers.count&&o.push(`too many triggers (${r.triggers.length}); maximum is ${H.triggers.count}`);for(let n of r.triggers)n.length>H.triggers.each&&o.push(`trigger "${n.substring(0,50)}..." exceeds ${H.triggers.each} character limit`)}return r.instructions?r.instructions.length>H.instructions&&o.push(`instructions exceed ${H.instructions} character limit (${r.instructions.length} chars)`):t.push("## Instructions section is required and must not be empty"),r.examples&&r.examples.length>H.examples&&o.push(`examples exceed ${H.examples} character limit (${r.examples.length} chars)`),{file:e,errors:t,warnings:o}}var xs=class{dir;onValidationError;loaded=!1;skills=new Map;fileMtimes=new Map;index=new Ts;_buildPromise=null;constructor(e){this.dir=pn.resolve(e.dir),this.onValidationError=e.onValidationError}async findSkillFiles(e){let t=[],o;try{o=await Xe.readdir(e)}catch{return t}for(let n of o){let s=pn.join(e,n),i;try{i=await Xe.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 Xe.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[f,b]=await Promise.all([Xe.readFile(s,"utf-8"),Xe.stat(s)]);i=f.replace(/\r\n/g,`
608
- `),a=b.mtimeMs}catch{continue}this.fileMtimes.set(s,a);let l=rT(i,s,this.dir);l.lastModified=a;let p=pn.relative(this.dir,s),m=sT(l,p);if(m.warnings.length>0)for(let f of m.warnings)console.warn(`[skills] ${p}: ${f}`);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 u=n.get(l.name);if(u){let f=`duplicate skill name "${l.name}" \u2014 already defined in "${u}"`;t.push({file:p,errors:[f]}),this.onValidationError==="warn"&&console.warn(`[skills] Skipping "${p}": ${f}`);continue}n.set(l.name,p),o.push(l)}if(t.length>0&&this.onValidationError==="fail"){let s=t.map(i=>` ${i.file}:
610
+ ORDER BY timestamp DESC`).all(e,`%${t}%`);let a=i.map(m=>this.rowToMessage(m)),l=[],p=0;for(let m of a){if(l.length>=n)break;let d=Math.ceil(m.content.length/4);if(l.length>0&&p+d>s)break;l.push(m),p+=d}return l}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(l=>`${e}:${l}`),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{}}};c();var JT=T(require("os"),1),bt=T(require("path"),1),gn=T(require("fs"),1),xl=".toolpack",vl="config",Cl="toolpack.config.json";function VT(){return JT.homedir()}function QT(){return bt.join(VT(),xl)}function Sl(){return bt.join(QT(),vl)}function kr(){return bt.join(Sl(),Cl)}function XT(r=process.cwd()){return bt.join(r,xl)}function kl(r=process.cwd()){return bt.join(XT(r),vl)}function Pr(r=process.cwd()){return bt.join(kl(r),Cl)}function Pl(){let r=Sl();gn.existsSync(r)||gn.mkdirSync(r,{recursive:!0})}function JC(r=process.cwd()){let e=kl(r);gn.existsSync(e)||gn.mkdirSync(e,{recursive:!0})}c();var se=T(require("fs"),1),ks=T(require("path"),1);function Rl(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]=Rl(r[o],e[o]):t[o]=e[o];return t}function _l(r){if(!se.existsSync(r))return null;try{let e=se.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}function VC(r=process.cwd()){let e=ks.join(r,"toolpack.config.json"),t=kr(),o=Pr(r),n=_l(e)||{},s=_l(t)||{},i=_l(o)||{},a=Rl(n,s);return a=Rl(a,i),a}function QC(r=process.cwd()){let e=ks.join(r,"toolpack.config.json"),t=kr(),o=Pr(r),n=!se.existsSync(t),s=null,i="default";return se.existsSync(o)?(s=o,i="local"):se.existsSync(t)?(s=t,i="global"):se.existsSync(e)&&(s=e,i="base"),{isFirstRun:n,activeConfigPath:s,configSource:i}}function XC(r=process.cwd()){let e=kr();if(!se.existsSync(e)){Pl();let t=null,o=Pr(r);if(se.existsSync(o))t=o;else{let s=ks.join(r,"toolpack.config.json");if(se.existsSync(s))t=s;else{let i=at();i&&se.existsSync(i)&&(t=i)}}let n={};if(t)try{let s=se.readFileSync(t,"utf-8");n=JSON.parse(s)}catch{}se.writeFileSync(e,JSON.stringify(n,null,4),"utf-8")}}c();c();c();var et=T(require("fs/promises"),1),hn=T(require("path"),1);c();var YC=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"]),Ps=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=>!YC.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 l=0,p=this.documentLengths.get(a)??0;for(let m of o){let d=this.termFrequencies.get(m);if(!d)continue;let f=d.get(a)??0;if(f===0)continue;let b=this.idf(m),y=f*(this.k1+1),w=f+this.k1*(1-this.b+this.b*(p/this.avgDocLength));l+=b*(y/w)}l>0&&(n[a]=l)});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)}};c();var Ze=T(require("path"),1);function YT(r,e,t){let o=r.match(/^---\n([\s\S]*?)\n---/),n="",s="",i,a=[];if(o&&o[1]){let $=o[1].split(`
611
+ `);for(let S of $){let M=S.indexOf(":");if(M===-1)continue;let _=S.substring(0,M).trim(),D=S.substring(M+1).trim();if(_==="name"&&(n=D),_==="title"&&(s=D),_==="version"&&(i=D),_==="tags"){let R=D.match(/\[(.*)\]/);R&&R[1]&&(a=R[1].split(",").map(W=>W.trim().replace(/"/g,"")).filter(Boolean))}}}n||(n=Ze.basename(e,".skill.md"));let l=r.match(/## Description\n\n([\s\S]*?)(?=\n## |$)/),p=l&&l[1]?l[1].trim():"",m=r.match(/## Triggers\n\n([\s\S]*?)(?=\n## |$)/),d=[];if(m&&m[1]){let $=m[1].split(`
612
+ `).filter(S=>S.startsWith("- "));for(let S of $){let M=S.match(/^- "(.*)"/);M&&M[1]&&d.push(M[1])}}let f=r.match(/## Instructions\n\n([\s\S]*?)(?=\n## |$)/),b=f&&f[1]?f[1].trim():"",y=r.match(/## Examples\n\n([\s\S]*?)(?=\n## |$)/),w=y&&y[1]?y[1].trim():void 0,x=Ze.relative(t,e),C=Ze.dirname(x),v=C==="."?void 0:C.split(Ze.sep)[0];return{name:n,title:s,version:i,tags:a,category:v,filePath:e,description:p,triggers:d,instructions:b,examples:w||void 0,lastModified:0}}c();c();var H={name:50,title:100,tags:{count:10,each:30},description:300,triggers:{count:10,min:1,each:100},instructions:2e3,examples:3e3};var ZC=/^[a-z][a-z0-9-]*$/;function ZT(r,e){let t=[],o=[];r.name?(ZC.test(r.name)||t.push(`name "${r.name}" must match kebab-case pattern /^[a-z][a-z0-9-]*$/`),r.name.length>H.name&&o.push(`name exceeds ${H.name} character limit (${r.name.length} chars)`)):t.push("name is required in frontmatter"),r.title?r.title.length>H.title&&o.push(`title exceeds ${H.title} character limit (${r.title.length} chars)`):t.push("title is required in frontmatter"),r.tags.length>H.tags.count&&o.push(`too many tags (${r.tags.length}); maximum is ${H.tags.count}`);for(let n of r.tags)n.length>H.tags.each&&o.push(`tag "${n}" exceeds ${H.tags.each} character limit`);if(r.description?r.description.length>H.description&&o.push(`description exceeds ${H.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>H.triggers.count&&o.push(`too many triggers (${r.triggers.length}); maximum is ${H.triggers.count}`);for(let n of r.triggers)n.length>H.triggers.each&&o.push(`trigger "${n.substring(0,50)}..." exceeds ${H.triggers.each} character limit`)}return r.instructions?r.instructions.length>H.instructions&&o.push(`instructions exceed ${H.instructions} character limit (${r.instructions.length} chars)`):t.push("## Instructions section is required and must not be empty"),r.examples&&r.examples.length>H.examples&&o.push(`examples exceed ${H.examples} character limit (${r.examples.length} chars)`),{file:e,errors:t,warnings:o}}var _s=class{dir;onValidationError;loaded=!1;skills=new Map;fileMtimes=new Map;index=new Ps;_buildPromise=null;constructor(e){this.dir=hn.resolve(e.dir),this.onValidationError=e.onValidationError}async findSkillFiles(e){let t=[],o;try{o=await et.readdir(e)}catch{return t}for(let n of o){let s=hn.join(e,n),i;try{i=await et.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 et.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[f,b]=await Promise.all([et.readFile(s,"utf-8"),et.stat(s)]);i=f.replace(/\r\n/g,`
613
+ `),a=b.mtimeMs}catch{continue}this.fileMtimes.set(s,a);let l=YT(i,s,this.dir);l.lastModified=a;let p=hn.relative(this.dir,s),m=ZT(l,p);if(m.warnings.length>0)for(let f of m.warnings)console.warn(`[skills] ${p}: ${f}`);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 d=n.get(l.name);if(d){let f=`duplicate skill name "${l.name}" \u2014 already defined in "${d}"`;t.push({file:p,errors:[f]}),this.onValidationError==="warn"&&console.warn(`[skills] Skipping "${p}": ${f}`);continue}n.set(l.name,p),o.push(l)}if(t.length>0&&this.onValidationError==="fail"){let s=t.map(i=>` ${i.file}:
609
614
  ${i.errors.join(`
610
615
  `)}`).join(`
611
616
  `);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 iT(r){let e=r?.dir??".toolpack/skills",t=r?.maxSkills??3,o=r?.minScore??.3,n=r?.onValidationError??"fail",s=new xs({dir:e,onValidationError:n});return Object.assign(async(i,a)=>{let l=i.messages??[],p=-1;for(let f=l.length-1;f>=0;f--)if(l[f].role==="user"){p=f;break}let m=p>=0?l[p]:null,u=m&&typeof m.content=="string"?m.content.trim():"";if(u){let f=await s.search(u,t,o);if(f.length>0){let y=`<skill-instructions>
617
+ ${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 ex(r){let e=r?.dir??".toolpack/skills",t=r?.maxSkills??3,o=r?.minScore??.3,n=r?.onValidationError??"fail",s=new _s({dir:e,onValidationError:n});return Object.assign(async(i,a)=>{let l=i.messages??[],p=-1;for(let f=l.length-1;f>=0;f--)if(l[f].role==="user"){p=f;break}let m=p>=0?l[p]:null,d=m&&typeof m.content=="string"?m.content.trim():"";if(d){let f=await s.search(d,t,o);if(f.length>0){let y=`<skill-instructions>
613
618
  ${f.map(x=>`--- Skill: ${x.skill.title} ---
614
619
  ${x.skill.instructions.trim()}
615
620
  ---`).join(`
@@ -617,4 +622,4 @@ ${x.skill.instructions.trim()}
617
622
  `)}
618
623
  </skill-instructions>`,w=l.map((x,C)=>C===p&&typeof x.content=="string"?{...x,content:`${y}
619
624
 
620
- ${x.content}`}:x);return a({...i,messages:w})}}return a(i)},{init:()=>s.ensureLoaded()})}0&&(module.exports={AGENT_MODE,AGENT_PLANNING_PROMPT,AGENT_WORKFLOW,AIClient,AnthropicAdapter,AuthenticationError,BM25SearchEngine,BUILT_IN_MODES,CHAT_MODE,CHAT_WORKFLOW,CODING_MODE,CODING_PLANNING_PROMPT,CODING_WORKFLOW,CONFIG_DIR_NAME,CONFIG_FILE_NAME,ConnectionError,ContextWindowConfigError,ContextWindowExceededError,ContextWindowStateManager,ConversationNotFoundError,DEFAULT_MODE_NAME,DEFAULT_TOOLS_CONFIG,DEFAULT_TOOL_SEARCH_CONFIG,DEFAULT_WORKFLOW,DEFAULT_WORKFLOW_CONFIG,GeminiAdapter,InMemoryConversationStore,InsufficientContextError,InvalidRequestError,McpClient,McpConnectionError,McpTimeoutError,McpToolManager,ModeRegistry,OllamaAdapter,OllamaProvider,OpenAIAdapter,OpenRouterAdapter,PageError,Planner,ProviderAdapter,ProviderError,RateLimitError,SDKError,SQLiteConversationStore,SummarizationError,TOOLPACK_DIR_NAME,TOOL_SEARCH_NAME,TimeoutError,ToolDiscoveryCache,ToolRegistry,ToolRouter,Toolpack,VertexAIAdapter,WorkflowExecutor,addBypassRule,buildSummarizedHistory,cloudDeployTool,cloudListTool,cloudStatusTool,cloudToolsProject,codingExtractFunctionTool,codingFindReferencesTool,codingFindSymbolTool,codingGetCallHierarchyTool,codingGetDiagnosticsTool,codingGetExportsTool,codingGetImportsTool,codingGetOutlineTool,codingGetSymbolsTool,codingGoToDefinitionTool,codingMultiFileEditTool,codingRefactorRenameTool,codingToolsProject,countTokens,createContextWindowStateManager,createMcpToolProject,createMode,createSkillInterceptor,createSkillTools,createSummarizationReport,createSummarySystemMessage,createToolProject,dbCountTool,dbDeleteTool,dbInsertTool,dbQueryTool,dbSchemaTool,dbTablesTool,dbToolsProject,dbUpdateTool,diffApplyTool,diffCreateTool,diffPreviewTool,diffToolsProject,disconnectMcpToolProject,ensureGlobalConfigDir,ensureLocalConfigDir,estimateSummaryTokens,estimateTokenCount,execKillTool,execListProcessesTool,execReadOutputTool,execRunBackgroundTool,execRunShellTool,execRunTool,execToolsProject,extractConversationKeypoints,fetchUrlAsBase64,fsAppendFileTool,fsBatchReadTool,fsBatchWriteTool,fsCopyTool,fsCreateDirTool,fsDeleteDirTool,fsDeleteFileTool,fsExistsTool,fsGlobTool,fsListDirTool,fsMoveTool,fsReadFileRangeTool,fsReadFileTool,fsReplaceInFileTool,fsSearchTool,fsStatTool,fsToolsProject,fsTreeTool,fsWriteFileTool,generateSummarizationPrompt,generateToolCategoriesPrompt,getContextWindowPercentage,getDefaultSlmModel,getGlobalConfigDir,getGlobalConfigPath,getGlobalToolpackDir,getLocalConfigDir,getLocalConfigPath,getLocalToolpackDir,getMessageStats,getMimeType,getOllamaBaseUrl,getOllamaProviderEntries,getRegisteredSlmModels,getRuntimeConfigStatus,getSafeOutputReserve,getToolSearchSchema,getToolpackConfig,getUserHomeDir,gitAddTool,gitBlameTool,gitBranchCreateTool,gitBranchListTool,gitCheckoutTool,gitCloneTool,gitCommitTool,gitDiffTool,gitLogTool,gitStatusTool,gitToolsProject,githubContentsGetTextTool,githubGraphqlExecuteTool,githubIssuesCommentsCreateTool,githubPrDiffGetTool,githubPrFilesListTool,githubPrReviewCommentsReplyTool,githubPrReviewThreadsListTool,githubPrReviewThreadsResolveTool,githubPrReviewsSubmitTool,githubToolsProject,groupMessagesByRole,handleContextWindowError,httpDeleteTool,httpDownloadTool,httpGetTool,httpPostTool,httpPutTool,httpToolsProject,initializeGlobalConfigIfFirstRun,isContextWindowError,isDataUri,isRegisteredSlm,isToolSearchTool,k8sApplyManifestTool,k8sDeleteResourceTool,k8sDescribeTool,k8sGetConfigMapTool,k8sGetLogsTool,k8sGetNamespacesTool,k8sListDeploymentsTool,k8sListPodsTool,k8sListServicesTool,k8sSwitchContextTool,k8sToolsProject,k8sWaitForDeploymentTool,loadFullConfig,loadRuntimeConfig,loadToolsConfig,mergeSummarizationResults,normalizeImagePart,ollamaRequest,ollamaStream,parseDataUri,parseSummarizationResponse,prepareSummarizationRequest,pruneMessages,readFileAsBase64,reloadToolpackConfig,removeBypassRule,saveToolsConfig,slackAuthTestTool,slackChatPostEphemeralTool,slackChatPostMessageTool,slackConversationsHistoryTool,slackConversationsRepliesTool,slackReactionsAddTool,slackToolsProject,systemCwdTool,systemDiskUsageTool,systemEnvTool,systemInfoTool,systemSetEnvTool,systemToolsProject,toDataUri,toolSearchDefinition,truncateMessage,validateSummarizationResult,webExtractLinksTool,webFeedTool,webFetchTool,webMapTool,webMetadataTool,webScrapeTool,webScreenshotTool,webSearchTool,webSitemapTool,webToolsProject,wouldExceedContextWindow});
625
+ ${x.content}`}:x);return a({...i,messages:w})}}return a(i)},{init:()=>s.ensureLoaded()})}0&&(module.exports={AGENT_MODE,AGENT_PLANNING_PROMPT,AGENT_WORKFLOW,AIClient,AnthropicAdapter,AuthenticationError,BM25SearchEngine,BUILT_IN_MODES,CHAT_MODE,CHAT_WORKFLOW,CODING_MODE,CODING_PLANNING_PROMPT,CODING_WORKFLOW,CONFIG_DIR_NAME,CONFIG_FILE_NAME,ConnectionError,ContextWindowConfigError,ContextWindowExceededError,ContextWindowStateManager,ConversationNotFoundError,DEFAULT_MODE_NAME,DEFAULT_TOOLS_CONFIG,DEFAULT_TOOL_SEARCH_CONFIG,DEFAULT_WORKFLOW,DEFAULT_WORKFLOW_CONFIG,GeminiAdapter,InMemoryConversationStore,InsufficientContextError,InvalidRequestError,McpClient,McpConnectionError,McpTimeoutError,McpToolManager,ModeRegistry,OllamaAdapter,OllamaProvider,OpenAIAdapter,OpenRouterAdapter,PageError,Planner,ProviderAdapter,ProviderError,RateLimitError,SDKError,SQLiteConversationStore,SummarizationError,TOOLPACK_DIR_NAME,TOOL_SEARCH_NAME,TimeoutError,ToolDiscoveryCache,ToolRegistry,ToolRouter,Toolpack,VertexAIAdapter,WorkflowExecutor,addBypassRule,buildSummarizedHistory,cloudDeployTool,cloudListTool,cloudStatusTool,cloudToolsProject,codingExtractFunctionTool,codingFindReferencesTool,codingFindSymbolTool,codingGetCallHierarchyTool,codingGetDiagnosticsTool,codingGetExportsTool,codingGetImportsTool,codingGetOutlineTool,codingGetSymbolsTool,codingGoToDefinitionTool,codingMultiFileEditTool,codingRefactorRenameTool,codingToolsProject,countTokens,createContextWindowStateManager,createMcpToolProject,createMode,createSkillInterceptor,createSkillTools,createSummarizationReport,createSummarySystemMessage,createToolProject,dbCountTool,dbDeleteTool,dbInsertTool,dbQueryTool,dbSchemaTool,dbTablesTool,dbToolsProject,dbUpdateTool,diffApplyTool,diffCreateTool,diffPreviewTool,diffToolsProject,disconnectMcpToolProject,ensureGlobalConfigDir,ensureLocalConfigDir,estimateSummaryTokens,estimateTokenCount,execKillTool,execListProcessesTool,execReadOutputTool,execRunBackgroundTool,execRunBlockingTool,execRunShellTool,execRunTool,execTailOutputTool,execToolsProject,extractConversationKeypoints,fetchUrlAsBase64,fsAppendFileTool,fsBatchReadTool,fsBatchWriteTool,fsCopyTool,fsCreateDirTool,fsDeleteDirTool,fsDeleteFileTool,fsExistsTool,fsGlobTool,fsListDirTool,fsMoveTool,fsReadFileRangeTool,fsReadFileTool,fsReplaceInFileTool,fsSearchTool,fsStatTool,fsToolsProject,fsTreeTool,fsWriteFileTool,generateSummarizationPrompt,generateToolCategoriesPrompt,getContextWindowPercentage,getDefaultSlmModel,getGlobalConfigDir,getGlobalConfigPath,getGlobalToolpackDir,getLocalConfigDir,getLocalConfigPath,getLocalToolpackDir,getMessageStats,getMimeType,getOllamaBaseUrl,getOllamaProviderEntries,getRegisteredSlmModels,getRuntimeConfigStatus,getSafeOutputReserve,getToolSearchSchema,getToolpackConfig,getUserHomeDir,gitAddTool,gitBlameTool,gitBranchCreateTool,gitBranchListTool,gitCheckoutTool,gitCloneTool,gitCommitTool,gitDiffTool,gitLogTool,gitStatusTool,gitToolsProject,githubContentsGetTextTool,githubGraphqlExecuteTool,githubIssuesCommentsCreateTool,githubPrDiffGetTool,githubPrFilesListTool,githubPrReviewCommentsReplyTool,githubPrReviewThreadsListTool,githubPrReviewThreadsResolveTool,githubPrReviewsSubmitTool,githubToolsProject,groupMessagesByRole,handleContextWindowError,httpDeleteTool,httpDownloadTool,httpGetTool,httpPostTool,httpPutTool,httpToolsProject,initializeGlobalConfigIfFirstRun,isContextWindowError,isDataUri,isRegisteredSlm,isToolSearchTool,k8sApplyManifestTool,k8sDeleteResourceTool,k8sDescribeTool,k8sGetConfigMapTool,k8sGetLogsTool,k8sGetNamespacesTool,k8sListDeploymentsTool,k8sListPodsTool,k8sListServicesTool,k8sSwitchContextTool,k8sToolsProject,k8sWaitForDeploymentTool,loadFullConfig,loadRuntimeConfig,loadToolsConfig,mergeSummarizationResults,normalizeImagePart,ollamaRequest,ollamaStream,parseDataUri,parseSummarizationResponse,prepareSummarizationRequest,pruneMessages,readFileAsBase64,reloadToolpackConfig,removeBypassRule,saveToolsConfig,slackAuthTestTool,slackChatPostEphemeralTool,slackChatPostMessageTool,slackConversationsHistoryTool,slackConversationsRepliesTool,slackReactionsAddTool,slackToolsProject,systemCwdTool,systemDiskUsageTool,systemEnvTool,systemInfoTool,systemSetEnvTool,systemToolsProject,toDataUri,toolSearchDefinition,truncateMessage,validateSummarizationResult,webExtractLinksTool,webFeedTool,webFetchTool,webMapTool,webMetadataTool,webScrapeTool,webScreenshotTool,webSearchTool,webSitemapTool,webToolsProject,wouldExceedContextWindow});